Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -294,3 +294,8 @@ ARK_API_KEY=your-key go run examples/volc/responses/basic/main.go

- Go 1.20 or later
- A Volcengine or BytePlus ModelArk API key

## Third-party notices

See [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md) for third-party
attribution notices.
39 changes: 39 additions & 0 deletions THIRD_PARTY_NOTICES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Third-Party Notices

This repository contains code that is derived from or structurally adapted
from third-party open-source projects.

## Anthropic self-hosted worker SDK

Portions of the self-hosted worker lifecycle and local agent tool
implementations under
`arkruntime/selfhosted`, `arkruntime/lib/environments`, `arkruntime/toolset`,
and `arkruntime/tools/agenttoolset` are structurally adapted from Anthropic's
self-hosted worker SDK implementation:

https://github.com/anthropics/anthropic-sdk-go

The upstream project is licensed under the MIT License. The MIT copyright and
permission notice is preserved below as required by that license.

```text
Copyright 2023 Anthropic, PBC.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
8 changes: 8 additions & 0 deletions arkruntime/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ func NewClientWithAkSk(ak, sk string, setters ...ConfigOption) *Client {
return newClientWithConfig(config)
}

// HTTPClient returns the configured HTTP client.
func (c *Client) HTTPClient() *http.Client {
if c == nil || c.config.HTTPClient == nil {
return http.DefaultClient
}
return c.config.HTTPClient
}

// NewVolcClient constructs a client targeting the Volcengine cloud
// (ark.cn-beijing.volces.com). Reads ARK_API_KEY for api-key auth and
// VOLC_ACCESSKEY/VOLC_SECRETKEY for AK/SK auth, in that preference order.
Expand Down
33 changes: 33 additions & 0 deletions arkruntime/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright (c) 2026 ByteDance Ltd. and/or its affiliates.
// SPDX-License-Identifier: Apache-2.0

package arkruntime

import "testing"

func TestNewClientConfigBaseURL(t *testing.T) {
tests := []struct {
name string
options []ConfigOption
want string
}{
{
name: "default",
want: "https://ark.cn-beijing.volces.com/api/v3",
},
{
name: "override",
options: []ConfigOption{WithBaseUrl("https://example.com/api/v3/")},
want: "https://example.com/api/v3",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
config := NewClientConfig("test-api-key", "", "", test.options...)
if config.BaseURL != test.want {
t.Fatalf("BaseURL = %q, want %q", config.BaseURL, test.want)
}
})
}
}
212 changes: 212 additions & 0 deletions arkruntime/environment_work.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
// Copyright (c) 2026 ByteDance Ltd. and/or its affiliates.
// SPDX-License-Identifier: Apache-2.0

package arkruntime

import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"

"github.com/volcengine/ark-runtime-go/arkruntime/model"
"github.com/volcengine/ark-runtime-go/arkruntime/model/environment"
"github.com/volcengine/ark-runtime-go/arkruntime/utils"
)

const (
environmentWorkWorkerIDHeader = "Ark-Worker-ID"
)

// PollWork polls one work item from an Environment work queue.
func (c *Client) PollWork(
ctx context.Context,
body *environment.PollWorkRequest,
setters ...requestOption,
) (*environment.WorkItem, error) {
if body == nil {
return nil, errors.New("missing required request body")
}
if body.EnvironmentID == "" {
return nil, errors.New("missing required environment_id")
}
q := url.Values{}
if body.WorkerID != "" {
setters = append(setters, WithCustomHeader(environmentWorkWorkerIDHeader, body.WorkerID))
}
if body.BlockMS > 0 {
q.Set("block_ms", strconv.Itoa(body.BlockMS))
}
if body.ReclaimOlderThanMS > 0 {
q.Set("reclaim_older_than_ms", strconv.Itoa(body.ReclaimOlderThanMS))
}
u := c.fullURL(fmt.Sprintf("%s/%s/work/poll", environmentsPrefix, environment.PathEscape(body.EnvironmentID)))
if encoded := q.Encode(); encoded != "" {
u += "?" + encoded
}

opts := append(setters, withBody(nil))
wrap := &environment.WorkItemResponse{}
if err := c.doControlPlaneRequest(ctx, http.MethodGet, u, wrap, opts...); err != nil {
return nil, err
}
if wrap.ID == "" {
return nil, nil
}
return &wrap.WorkItem, nil
}

// AckWork acknowledges one claimed work item.
func (c *Client) AckWork(
ctx context.Context,
body *environment.AckWorkRequest,
setters ...requestOption,
) error {
if body == nil {
return errors.New("missing required request body")
}
if body.EnvironmentID == "" {
return errors.New("missing required environment_id")
}
if body.WorkID == "" {
return errors.New("missing required work_id")
}
u := c.fullURL(fmt.Sprintf("%s/%s/work/%s/ack",
environmentsPrefix,
environment.PathEscape(body.EnvironmentID),
environment.PathEscape(body.WorkID),
))
if workerID, ok := body.WorkerID.Get(); ok {
setters = append(setters, WithCustomHeader(environmentWorkWorkerIDHeader, workerID))
}
wrap := &environment.WorkItemResponse{}
return c.doControlPlaneRequest(ctx, http.MethodPost, u, wrap, append(setters, withBody(nil))...)
}

// HeartbeatWork refreshes a claimed work lease.
func (c *Client) HeartbeatWork(
ctx context.Context,
body *environment.HeartbeatWorkRequest,
setters ...requestOption,
) (*environment.HeartbeatWorkResponse, error) {
if body == nil {
return nil, errors.New("missing required request body")
}
if body.EnvironmentID == "" {
return nil, errors.New("missing required environment_id")
}
if body.WorkID == "" {
return nil, errors.New("missing required work_id")
}
q := url.Values{}
if desiredTTLSeconds, ok := body.DesiredTTLSeconds.Get(); ok && desiredTTLSeconds > 0 {
q.Set("desired_ttl_seconds", strconv.FormatInt(desiredTTLSeconds, 10))
}
if expectedLastHeartbeat, ok := body.ExpectedLastHeartbeat.Get(); ok && expectedLastHeartbeat != "" {
q.Set("expected_last_heartbeat", expectedLastHeartbeat)
}
u := c.fullURL(fmt.Sprintf("%s/%s/work/%s/heartbeat",
environmentsPrefix,
environment.PathEscape(body.EnvironmentID),
environment.PathEscape(body.WorkID),
))
if encoded := q.Encode(); encoded != "" {
u += "?" + encoded
}
wrap := &environment.HeartbeatWorkResponseWrapper{}
if err := c.doControlPlaneRequest(ctx, http.MethodPost, u, wrap, append(setters, withBody(nil))...); err != nil {
return nil, err
}
return &wrap.HeartbeatWorkResponse, nil
}

// StopWork releases or stops one claimed work item.
func (c *Client) StopWork(
ctx context.Context,
body *environment.StopWorkRequest,
setters ...requestOption,
) error {
if body == nil {
return errors.New("missing required request body")
}
if body.EnvironmentID == "" {
return errors.New("missing required environment_id")
}
if body.WorkID == "" {
return errors.New("missing required work_id")
}
u := c.fullURL(fmt.Sprintf("%s/%s/work/%s/stop",
environmentsPrefix,
environment.PathEscape(body.EnvironmentID),
environment.PathEscape(body.WorkID),
))
wrap := &environment.WorkItemResponse{}
return c.doControlPlaneRequest(ctx, http.MethodPost, u, wrap, append(setters, withBody(stopWorkBody(body)))...)
}

type stopWorkRequestBody struct {
Force *bool `json:"force,omitempty"`
}

func stopWorkBody(body *environment.StopWorkRequest) any {
force, ok := body.Force.Get()
if !ok {
return nil
}
return stopWorkRequestBody{Force: &force}
}

func (c *Client) doControlPlaneRequest(
ctx context.Context,
method string,
u string,
v model.Response,
setters ...requestOption,
) error {
return utils.Retry(
ctx,
utils.RetryPolicy{
MaxAttempts: c.config.RetryTimes,
InitialBackoff: model.ErrorRetryBaseDelay,
MaxBackoff: model.ErrorRetryMaxDelay,
},
func() bool { return true },
func() error {
req, reqErr := c.newRequest(ctx, method, u, "", "", setters...)
if reqErr != nil {
return reqErr
}
return c.sendControlPlaneRequest(req, v)
},
nil,
needRetryError,
)
}

func (c *Client) sendControlPlaneRequest(req *http.Request, v model.Response) error {
requestID := req.Header.Get(model.ClientRequestHeader)
req.Header.Set("Accept", "application/json")
if req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/json")
}

res, err := c.config.HTTPClient.Do(req)
if err != nil {
return model.NewRequestError(http.StatusInternalServerError, err, requestID)
}
defer res.Body.Close() //nolint:errcheck // response body close errors are non-actionable

if v != nil {
v.SetHeader(res.Header)
}
if isFailureStatusCode(res) {
return c.handleErrorResp(res)
}
if err := decodeResponse(res.Body, v); err != nil && !errors.Is(err, io.EOF) {
return model.NewRequestError(res.StatusCode, err, requestID)
}
return nil
}
86 changes: 86 additions & 0 deletions arkruntime/internal/selfhostedlog/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Copyright (c) 2026 ByteDance Ltd. and/or its affiliates.
// SPDX-License-Identifier: Apache-2.0

// Package selfhostedlog 为 self-hosted worker 提供兼容 Go 1.20 的结构化日志适配。
package selfhostedlog

import (
"fmt"
"log"
"strconv"
"strings"
)

// Logger 在标准库 log.Logger 上保留 self-hosted worker 使用的键值日志接口。
type Logger struct {
base *log.Logger
attrs []any
}

// New 创建日志适配器,base 为空时使用 log.Default。
func New(base *log.Logger) *Logger {
if base == nil {
base = log.Default()
}
return &Logger{base: base}
}

// With 返回附带固定字段的新日志适配器。
func (l *Logger) With(args ...any) *Logger {
if l == nil {
l = New(nil)
}
attrs := make([]any, 0, len(l.attrs)+len(args))
attrs = append(attrs, l.attrs...)
attrs = append(attrs, args...)
return &Logger{base: l.base, attrs: attrs}
}

// Debug 记录调试日志。
func (l *Logger) Debug(message string, args ...any) { l.output("DEBUG", message, args...) }

// Info 记录信息日志。
func (l *Logger) Info(message string, args ...any) { l.output("INFO", message, args...) }

// Warn 记录警告日志。
func (l *Logger) Warn(message string, args ...any) { l.output("WARN", message, args...) }

// Error 记录错误日志。
func (l *Logger) Error(message string, args ...any) { l.output("ERROR", message, args...) }

func (l *Logger) output(level, message string, args ...any) {
if l == nil {
l = New(nil)
}
all := make([]any, 0, len(l.attrs)+len(args))
all = append(all, l.attrs...)
all = append(all, args...)
l.base.Printf("level=%s msg=%s%s", level, quoteValue(message), formatAttrs(all))
}

func formatAttrs(attrs []any) string {
if len(attrs) == 0 {
return ""
}
var builder strings.Builder
for index := 0; index < len(attrs); index += 2 {
key := fmt.Sprint(attrs[index])
value := any("<missing>")
if index+1 < len(attrs) {
value = attrs[index+1]
}
builder.WriteByte(' ')
builder.WriteString(key)
builder.WriteByte('=')
builder.WriteString(quoteValue(value))
}
return builder.String()
}

func quoteValue(value any) string {
text := fmt.Sprint(value)
if text == "" || strings.ContainsAny(text, " \t\r\n\"=") {
return strconv.Quote(text)
}
return text
}
Loading
Loading