@anthropic-ai/sdk 0.118.0 → 0.120.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/client.d.mts +8 -2
- package/client.d.mts.map +1 -1
- package/client.d.ts +8 -2
- package/client.d.ts.map +1 -1
- package/client.js +6 -0
- package/client.js.map +1 -1
- package/client.mjs +6 -0
- package/client.mjs.map +1 -1
- package/helpers/beta/environments.d.mts +5 -4
- package/helpers/beta/environments.d.mts.map +1 -1
- package/helpers/beta/environments.d.ts +5 -4
- package/helpers/beta/environments.d.ts.map +1 -1
- package/helpers/beta/environments.js +5 -4
- package/helpers/beta/environments.js.map +1 -1
- package/helpers/beta/environments.mjs +5 -4
- package/helpers/beta/environments.mjs.map +1 -1
- package/internal/file-store.d.mts +136 -0
- package/internal/file-store.d.mts.map +1 -0
- package/internal/file-store.d.ts +136 -0
- package/internal/file-store.d.ts.map +1 -0
- package/internal/file-store.js +531 -0
- package/internal/file-store.js.map +1 -0
- package/internal/file-store.mjs +523 -0
- package/internal/file-store.mjs.map +1 -0
- package/lib/environments/poller.d.mts +6 -0
- package/lib/environments/poller.d.mts.map +1 -1
- package/lib/environments/poller.d.ts +6 -0
- package/lib/environments/poller.d.ts.map +1 -1
- package/lib/environments/poller.js +46 -1
- package/lib/environments/poller.js.map +1 -1
- package/lib/environments/poller.mjs +46 -1
- package/lib/environments/poller.mjs.map +1 -1
- package/lib/environments/worker.d.mts +89 -12
- package/lib/environments/worker.d.mts.map +1 -1
- package/lib/environments/worker.d.ts +89 -12
- package/lib/environments/worker.d.ts.map +1 -1
- package/lib/environments/worker.js +336 -67
- package/lib/environments/worker.js.map +1 -1
- package/lib/environments/worker.mjs +336 -68
- package/lib/environments/worker.mjs.map +1 -1
- package/lib/tools/BetaRunnableTool.d.mts +4 -1
- package/lib/tools/BetaRunnableTool.d.mts.map +1 -1
- package/lib/tools/BetaRunnableTool.d.ts +4 -1
- package/lib/tools/BetaRunnableTool.d.ts.map +1 -1
- package/lib/tools/BetaRunnableTool.js +7 -2
- package/lib/tools/BetaRunnableTool.js.map +1 -1
- package/lib/tools/BetaRunnableTool.mjs +7 -2
- package/lib/tools/BetaRunnableTool.mjs.map +1 -1
- package/lib/tools/BetaToolRunner.d.mts.map +1 -1
- package/lib/tools/BetaToolRunner.d.ts.map +1 -1
- package/lib/tools/BetaToolRunner.js +3 -1
- package/lib/tools/BetaToolRunner.js.map +1 -1
- package/lib/tools/BetaToolRunner.mjs +3 -1
- package/lib/tools/BetaToolRunner.mjs.map +1 -1
- package/package.json +1 -1
- package/resources/beta/agents/agents.d.mts +322 -27
- package/resources/beta/agents/agents.d.mts.map +1 -1
- package/resources/beta/agents/agents.d.ts +322 -27
- package/resources/beta/agents/agents.d.ts.map +1 -1
- package/resources/beta/agents/agents.js.map +1 -1
- package/resources/beta/agents/agents.mjs.map +1 -1
- package/resources/beta/agents/index.d.mts +1 -1
- package/resources/beta/agents/index.d.mts.map +1 -1
- package/resources/beta/agents/index.d.ts +1 -1
- package/resources/beta/agents/index.d.ts.map +1 -1
- package/resources/beta/agents/index.js.map +1 -1
- package/resources/beta/agents/index.mjs.map +1 -1
- package/resources/beta/beta.d.mts +6 -6
- package/resources/beta/beta.d.mts.map +1 -1
- package/resources/beta/beta.d.ts +6 -6
- package/resources/beta/beta.d.ts.map +1 -1
- package/resources/beta/beta.js.map +1 -1
- package/resources/beta/beta.mjs.map +1 -1
- package/resources/beta/environments/work.d.mts +5 -1
- package/resources/beta/environments/work.d.mts.map +1 -1
- package/resources/beta/environments/work.d.ts +5 -1
- package/resources/beta/environments/work.d.ts.map +1 -1
- package/resources/beta/environments/work.js +0 -17
- package/resources/beta/environments/work.js.map +1 -1
- package/resources/beta/environments/work.mjs +0 -17
- package/resources/beta/environments/work.mjs.map +1 -1
- package/resources/beta/files.d.mts +22 -22
- package/resources/beta/files.d.mts.map +1 -1
- package/resources/beta/files.d.ts +22 -22
- package/resources/beta/files.d.ts.map +1 -1
- package/resources/beta/files.js +4 -4
- package/resources/beta/files.js.map +1 -1
- package/resources/beta/files.mjs +4 -4
- package/resources/beta/files.mjs.map +1 -1
- package/resources/beta/index.d.mts +3 -3
- package/resources/beta/index.d.mts.map +1 -1
- package/resources/beta/index.d.ts +3 -3
- package/resources/beta/index.d.ts.map +1 -1
- package/resources/beta/index.js.map +1 -1
- package/resources/beta/index.mjs.map +1 -1
- package/resources/beta/messages/index.d.mts +1 -1
- package/resources/beta/messages/index.d.mts.map +1 -1
- package/resources/beta/messages/index.d.ts +1 -1
- package/resources/beta/messages/index.d.ts.map +1 -1
- package/resources/beta/messages/index.js.map +1 -1
- package/resources/beta/messages/index.mjs.map +1 -1
- package/resources/beta/messages/messages.d.mts +1202 -5
- package/resources/beta/messages/messages.d.mts.map +1 -1
- package/resources/beta/messages/messages.d.ts +1202 -5
- package/resources/beta/messages/messages.d.ts.map +1 -1
- package/resources/beta/messages/messages.js.map +1 -1
- package/resources/beta/messages/messages.mjs.map +1 -1
- package/resources/files.d.mts +105 -0
- package/resources/files.d.mts.map +1 -0
- package/resources/files.d.ts +105 -0
- package/resources/files.d.ts.map +1 -0
- package/resources/files.js +52 -0
- package/resources/files.js.map +1 -0
- package/resources/files.mjs +48 -0
- package/resources/files.mjs.map +1 -0
- package/resources/index.d.mts +3 -1
- package/resources/index.d.mts.map +1 -1
- package/resources/index.d.ts +3 -1
- package/resources/index.d.ts.map +1 -1
- package/resources/index.js +5 -1
- package/resources/index.js.map +1 -1
- package/resources/index.mjs +2 -0
- package/resources/index.mjs.map +1 -1
- package/resources/messages/index.d.mts +1 -1
- package/resources/messages/index.d.mts.map +1 -1
- package/resources/messages/index.d.ts +1 -1
- package/resources/messages/index.d.ts.map +1 -1
- package/resources/messages/index.js.map +1 -1
- package/resources/messages/index.mjs.map +1 -1
- package/resources/messages/messages.d.mts +1267 -7
- package/resources/messages/messages.d.mts.map +1 -1
- package/resources/messages/messages.d.ts +1267 -7
- package/resources/messages/messages.d.ts.map +1 -1
- package/resources/messages/messages.js.map +1 -1
- package/resources/messages/messages.mjs.map +1 -1
- package/resources/skills/index.d.mts +3 -0
- package/resources/skills/index.d.mts.map +1 -0
- package/resources/skills/index.d.ts +3 -0
- package/resources/skills/index.d.ts.map +1 -0
- package/resources/skills/index.js +9 -0
- package/resources/skills/index.js.map +1 -0
- package/resources/skills/index.mjs +4 -0
- package/resources/skills/index.mjs.map +1 -0
- package/resources/skills/skills.d.mts +129 -0
- package/resources/skills/skills.d.mts.map +1 -0
- package/resources/skills/skills.d.ts +129 -0
- package/resources/skills/skills.d.ts.map +1 -0
- package/resources/skills/skills.js +44 -0
- package/resources/skills/skills.js.map +1 -0
- package/resources/skills/skills.mjs +39 -0
- package/resources/skills/skills.mjs.map +1 -0
- package/resources/skills/versions.d.mts +104 -0
- package/resources/skills/versions.d.mts.map +1 -0
- package/resources/skills/versions.d.ts +104 -0
- package/resources/skills/versions.d.ts.map +1 -0
- package/resources/skills/versions.js +41 -0
- package/resources/skills/versions.js.map +1 -0
- package/resources/skills/versions.mjs +37 -0
- package/resources/skills/versions.mjs.map +1 -0
- package/resources/skills.d.mts +2 -0
- package/resources/skills.d.mts.map +1 -0
- package/resources/skills.d.ts +2 -0
- package/resources/skills.d.ts.map +1 -0
- package/resources/skills.js +6 -0
- package/resources/skills.js.map +1 -0
- package/resources/skills.mjs +3 -0
- package/resources/skills.mjs.map +1 -0
- package/src/client.ts +172 -0
- package/src/helpers/beta/environments.ts +5 -4
- package/src/internal/file-store.ts +550 -0
- package/src/lib/environments/poller.ts +47 -1
- package/src/lib/environments/worker.ts +419 -79
- package/src/lib/tools/BetaRunnableTool.ts +9 -2
- package/src/lib/tools/BetaToolRunner.ts +6 -1
- package/src/resources/beta/agents/agents.ts +435 -30
- package/src/resources/beta/agents/index.ts +17 -0
- package/src/resources/beta/beta.ts +160 -6
- package/src/resources/beta/environments/work.ts +7 -0
- package/src/resources/beta/files.ts +27 -27
- package/src/resources/beta/index.ts +80 -3
- package/src/resources/beta/messages/index.ts +60 -0
- package/src/resources/beta/messages/messages.ts +1865 -415
- package/src/resources/files.ts +163 -0
- package/src/resources/index.ts +83 -0
- package/src/resources/messages/index.ts +66 -0
- package/src/resources/messages/messages.ts +1648 -115
- package/src/resources/skills/index.ts +21 -0
- package/src/resources/skills/skills.ts +194 -0
- package/src/resources/skills/versions.ts +160 -0
- package/src/resources/skills.ts +3 -0
- package/src/tools/agent-toolset/fs-util.ts +40 -24
- package/src/tools/agent-toolset/memories.ts +1017 -0
- package/src/tools/agent-toolset/node.browser.ts +68 -0
- package/src/tools/agent-toolset/node.ts +139 -53
- package/src/tools/agent-toolset/skills.ts +29 -9
- package/src/tools/agent-toolset/sync-interval.ts +30 -0
- package/src/version.ts +1 -1
- package/tools/agent-toolset/fs-util.d.mts +23 -10
- package/tools/agent-toolset/fs-util.d.mts.map +1 -1
- package/tools/agent-toolset/fs-util.d.ts +23 -10
- package/tools/agent-toolset/fs-util.d.ts.map +1 -1
- package/tools/agent-toolset/fs-util.js +40 -25
- package/tools/agent-toolset/fs-util.js.map +1 -1
- package/tools/agent-toolset/fs-util.mjs +38 -25
- package/tools/agent-toolset/fs-util.mjs.map +1 -1
- package/tools/agent-toolset/memories.d.mts +173 -0
- package/tools/agent-toolset/memories.d.mts.map +1 -0
- package/tools/agent-toolset/memories.d.ts +173 -0
- package/tools/agent-toolset/memories.d.ts.map +1 -0
- package/tools/agent-toolset/memories.js +902 -0
- package/tools/agent-toolset/memories.js.map +1 -0
- package/tools/agent-toolset/memories.mjs +895 -0
- package/tools/agent-toolset/memories.mjs.map +1 -0
- package/tools/agent-toolset/node.browser.d.mts +31 -0
- package/tools/agent-toolset/node.browser.d.mts.map +1 -1
- package/tools/agent-toolset/node.browser.d.ts +31 -0
- package/tools/agent-toolset/node.browser.d.ts.map +1 -1
- package/tools/agent-toolset/node.browser.js +59 -1
- package/tools/agent-toolset/node.browser.js.map +1 -1
- package/tools/agent-toolset/node.browser.mjs +54 -0
- package/tools/agent-toolset/node.browser.mjs.map +1 -1
- package/tools/agent-toolset/node.d.mts +54 -22
- package/tools/agent-toolset/node.d.mts.map +1 -1
- package/tools/agent-toolset/node.d.ts +54 -22
- package/tools/agent-toolset/node.d.ts.map +1 -1
- package/tools/agent-toolset/node.js +83 -44
- package/tools/agent-toolset/node.js.map +1 -1
- package/tools/agent-toolset/node.mjs +77 -44
- package/tools/agent-toolset/node.mjs.map +1 -1
- package/tools/agent-toolset/skills.d.mts +16 -7
- package/tools/agent-toolset/skills.d.mts.map +1 -1
- package/tools/agent-toolset/skills.d.ts +16 -7
- package/tools/agent-toolset/skills.d.ts.map +1 -1
- package/tools/agent-toolset/skills.js +27 -9
- package/tools/agent-toolset/skills.js.map +1 -1
- package/tools/agent-toolset/skills.mjs +27 -9
- package/tools/agent-toolset/skills.mjs.map +1 -1
- package/tools/agent-toolset/sync-interval.d.mts +19 -0
- package/tools/agent-toolset/sync-interval.d.mts.map +1 -0
- package/tools/agent-toolset/sync-interval.d.ts +19 -0
- package/tools/agent-toolset/sync-interval.d.ts.map +1 -0
- package/tools/agent-toolset/sync-interval.js +29 -0
- package/tools/agent-toolset/sync-interval.js.map +1 -0
- package/tools/agent-toolset/sync-interval.mjs +25 -0
- package/tools/agent-toolset/sync-interval.mjs.map +1 -0
- package/version.d.mts +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.mjs +1 -1
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
import { AnthropicError } from '../../core/error';
|
|
1
|
+
import { AnthropicError, APIError } from '../../core/error';
|
|
2
2
|
import type { Anthropic } from '../../client';
|
|
3
|
-
import type { BetaSelfHostedWork } from '../../resources/beta/environments/work';
|
|
3
|
+
import type { BetaSelfHostedWork, BetaWorkSecret } from '../../resources/beta/environments/work';
|
|
4
4
|
import { loggerFor, type Logger } from '../../internal/utils/log';
|
|
5
|
+
import { fromBase64 } from '../../internal/utils/base64';
|
|
6
|
+
import { decodeUTF8 } from '../../internal/utils/bytes';
|
|
5
7
|
import { readEnv } from '../../internal/utils/env';
|
|
6
8
|
import { sleep } from '../../internal/utils/sleep';
|
|
7
9
|
import { isFatal4xx, isStatus } from '../../internal/utils/backoff';
|
|
8
10
|
import { linkAbort } from '../../internal/utils/abort';
|
|
11
|
+
import { isObj } from '../../internal/utils/values';
|
|
9
12
|
import { buildHeaders } from '../../internal/headers';
|
|
10
13
|
import type { BetaRunnableTool } from '../tools/BetaRunnableTool';
|
|
11
14
|
import type { BetaToolRunnerRequestOptions } from '../tools/BetaToolRunner';
|
|
@@ -18,7 +21,9 @@ import { copyClientForHelper } from '../helper-client';
|
|
|
18
21
|
// per-item handler. That keeps this file free of Node-only deps in the static
|
|
19
22
|
// import graph, which is what lets `client.beta.environments.work.worker()`
|
|
20
23
|
// exist as a resource method without pulling Node built-ins into the SDK core.
|
|
21
|
-
import type { AgentToolContext } from '../../tools/agent-toolset/node';
|
|
24
|
+
import type { AgentToolContext, MemoryDeleteMode, SessionMemoryStores } from '../../tools/agent-toolset/node';
|
|
25
|
+
import { checkMemorySyncInterval } from '../../tools/agent-toolset/sync-interval';
|
|
26
|
+
import type { BetaManagedAgentsSession } from '../../resources/beta/sessions/sessions';
|
|
22
27
|
|
|
23
28
|
const HEARTBEAT_DEFAULT_MS = 30_000;
|
|
24
29
|
const HEARTBEAT_TTL_DEFAULT_MS = 90_000;
|
|
@@ -42,10 +47,11 @@ export interface EnvironmentWorkerOptions {
|
|
|
42
47
|
*/
|
|
43
48
|
environmentId?: string;
|
|
44
49
|
/**
|
|
45
|
-
* The environment key — the
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
* to `ANTHROPIC_ENVIRONMENT_KEY` in
|
|
50
|
+
* The environment key — the worker's standing credential: polling always
|
|
51
|
+
* uses it, and per-session calls fall back to it when a claimed item's
|
|
52
|
+
* `secret` doesn't yield a sessions token. Required by
|
|
53
|
+
* {@link EnvironmentWorker.run}; falls back to `ANTHROPIC_ENVIRONMENT_KEY` in
|
|
54
|
+
* {@link EnvironmentWorker.handleItem}.
|
|
49
55
|
*/
|
|
50
56
|
environmentKey?: string;
|
|
51
57
|
/**
|
|
@@ -60,12 +66,41 @@ export interface EnvironmentWorkerOptions {
|
|
|
60
66
|
tools?: EnvironmentWorkerTools;
|
|
61
67
|
/** Base directory for the per-session {@link AgentToolContext}. Defaults to `process.cwd()`. */
|
|
62
68
|
workdir?: string;
|
|
63
|
-
/**
|
|
69
|
+
/**
|
|
70
|
+
* @deprecated No longer accepted: the file tools are always confined to
|
|
71
|
+
* `workdir` plus `allowedRoots`, which is neither behavior this flag used to
|
|
72
|
+
* select, so passing either value throws. Remove it; list extra directories
|
|
73
|
+
* in {@link AgentToolContext.allowedRoots}. The property is removed in a
|
|
74
|
+
* future release.
|
|
75
|
+
*/
|
|
64
76
|
unrestrictedPaths?: boolean;
|
|
65
77
|
/** Forwarded to the per-session {@link AgentToolContext} (`maxFileBytes`). */
|
|
66
78
|
maxFileBytes?: number | null;
|
|
67
79
|
/** Forwarded to {@link SessionToolRunner} (`maxIdleMs`). */
|
|
68
80
|
maxIdleMs?: number;
|
|
81
|
+
/**
|
|
82
|
+
* How often (milliseconds) to sync the session's attached memory stores back
|
|
83
|
+
* while it runs — checked after each dispatched tool call, plus one final
|
|
84
|
+
* sync when the session ends cleanly. Defaults to
|
|
85
|
+
* `DEFAULT_MEMORY_SYNC_INTERVAL_MS` (15s); the constructor throws for
|
|
86
|
+
* values below `MIN_MEMORY_SYNC_INTERVAL_MS` (5s). Every teardown also runs
|
|
87
|
+
* a push-only flush of changed files; that flush and the final sync are
|
|
88
|
+
* each bounded by `MEMORY_FLUSH_TIMEOUT_MS`, and a warning is logged when
|
|
89
|
+
* either bound cuts work off. `null` disables memory download and sync
|
|
90
|
+
* entirely. Memory stores are only touched for work items whose `secret`
|
|
91
|
+
* carries a `sessions_token`; while sync is enabled, an item without one
|
|
92
|
+
* fails when its session has memory stores attached, because those stores
|
|
93
|
+
* cannot be mounted without the token. With `null` the same item runs,
|
|
94
|
+
* without memory, and nothing is logged — turning sync off is the
|
|
95
|
+
* operator's explicit choice.
|
|
96
|
+
*/
|
|
97
|
+
memorySyncIntervalMs?: number | null;
|
|
98
|
+
/**
|
|
99
|
+
* Whether local file deletions may delete on the server — see
|
|
100
|
+
* {@link MemoryDeleteMode}. Uploads and pulls are unaffected.
|
|
101
|
+
* Defaults to `"enabled"`.
|
|
102
|
+
*/
|
|
103
|
+
memorySyncDeletions?: MemoryDeleteMode;
|
|
69
104
|
/** Forwarded to the {@link WorkPoller}. */
|
|
70
105
|
workerId?: string;
|
|
71
106
|
/** External abort signal; aborting it ends the run. */
|
|
@@ -100,12 +135,62 @@ export interface HandleItemOptions {
|
|
|
100
135
|
* `ANTHROPIC_ENVIRONMENT_KEY`.
|
|
101
136
|
*/
|
|
102
137
|
environmentKey?: string;
|
|
138
|
+
/**
|
|
139
|
+
* The work item's per-item `secret` payload from the poll response. Falls
|
|
140
|
+
* back to `ANTHROPIC_WORK_SECRET`. Unlike the others it is optional — when
|
|
141
|
+
* present, the sessions token extracted from it is preferred as the Bearer
|
|
142
|
+
* credential for this item's heartbeat / force-stop / skill-download /
|
|
143
|
+
* session calls; when absent (or undecodable) those calls use the
|
|
144
|
+
* environment key.
|
|
145
|
+
*/
|
|
146
|
+
workSecret?: string;
|
|
103
147
|
/** External abort signal; aborting it ends the run. Defaults to the constructor's signal. */
|
|
104
148
|
signal?: AbortSignal;
|
|
105
149
|
}
|
|
106
150
|
|
|
107
|
-
/**
|
|
108
|
-
|
|
151
|
+
/**
|
|
152
|
+
* The fields of {@link BetaSelfHostedWork} the per-item flow reads. `secret` is
|
|
153
|
+
* declared here rather than picked because the generated model does not carry
|
|
154
|
+
* it — only the poll response populates it.
|
|
155
|
+
*/
|
|
156
|
+
type ClaimedWork = Pick<BetaSelfHostedWork, 'id' | 'environment_id' | 'data'> & {
|
|
157
|
+
secret?: string | null;
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
/** True when the session has at least one memory store attached. */
|
|
161
|
+
function hasMemoryStore(session: BetaManagedAgentsSession): boolean {
|
|
162
|
+
return session.resources.some((r) => r.type === 'memory_store');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Extract the per-item sessions token from a work item's `secret` payload.
|
|
167
|
+
*
|
|
168
|
+
* The `secret` the poll response populates is not itself a credential: it is a
|
|
169
|
+
* URL-safe base64 JSON payload matching {@link BetaWorkSecret} — the
|
|
170
|
+
* `sessions_token` (the bearer for this item's work lifecycle and
|
|
171
|
+
* session-level calls) plus fields this worker does not consume. Returns the
|
|
172
|
+
* sessions token, or `null` (meaning: fall back to the environment key) when
|
|
173
|
+
* the payload is missing, doesn't decode, or carries no token. Never log the
|
|
174
|
+
* payload or anything extracted from it.
|
|
175
|
+
*/
|
|
176
|
+
export function sessionsTokenFromSecret(secret: string | null | undefined): string | null {
|
|
177
|
+
if (!secret) return null;
|
|
178
|
+
let parsed: unknown;
|
|
179
|
+
try {
|
|
180
|
+
// The payload may arrive URL-safe and without base64 padding; normalize
|
|
181
|
+
// both before decoding.
|
|
182
|
+
const normalized = secret.replace(/-/g, '+').replace(/_/g, '/');
|
|
183
|
+
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
|
|
184
|
+
parsed = JSON.parse(decodeUTF8(fromBase64(padded)));
|
|
185
|
+
} catch {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
189
|
+
// The payload is untrusted input, so the token is still checked at runtime
|
|
190
|
+
// rather than trusted to match the schema.
|
|
191
|
+
const token = (parsed as Partial<BetaWorkSecret>).sessions_token;
|
|
192
|
+
return typeof token === 'string' && token !== '' ? token : null;
|
|
193
|
+
}
|
|
109
194
|
|
|
110
195
|
/**
|
|
111
196
|
* The self-hosted environment runner, composed from the control-plane
|
|
@@ -115,9 +200,17 @@ type ClaimedWork = Pick<BetaSelfHostedWork, 'id' | 'environment_id' | 'data'>;
|
|
|
115
200
|
* {@link AgentToolContext}, downloads the session agent's skills
|
|
116
201
|
* (`setupSkills`), then runs a {@link SessionToolRunner} for the session
|
|
117
202
|
* while heartbeating the work-item lease on the same event loop; on exit it
|
|
118
|
-
* force-stops the work item
|
|
119
|
-
*
|
|
120
|
-
*
|
|
203
|
+
* force-stops the work item (unless the lease was lost, in which case the item
|
|
204
|
+
* is left to whoever holds it now), cleans up the downloaded skills, and loops
|
|
205
|
+
* to the next one. The lease heartbeat reports `state === "stopping"` / a lost
|
|
206
|
+
* lease back into the run by aborting the session runner.
|
|
207
|
+
*
|
|
208
|
+
* The `environmentKey` is the worker's standing credential. When a claimed
|
|
209
|
+
* work item carries a per-item `secret` (a short-lived payload the poll
|
|
210
|
+
* response may populate), the sessions token extracted from it is preferred
|
|
211
|
+
* over the environment key for that item's heartbeat / force-stop /
|
|
212
|
+
* skill-download / session calls; polling itself always uses the environment
|
|
213
|
+
* key, and items without a usable secret fall back to it entirely.
|
|
121
214
|
*
|
|
122
215
|
* Use {@link EnvironmentWorker.handleItem} if you already hold a claimed work
|
|
123
216
|
* item (e.g. a `worker poll --on-work` script handed one to a fresh process) and
|
|
@@ -144,22 +237,42 @@ export class EnvironmentWorker {
|
|
|
144
237
|
readonly environmentKey: string | undefined;
|
|
145
238
|
readonly tools: EnvironmentWorkerTools | undefined;
|
|
146
239
|
readonly workdir: string;
|
|
240
|
+
/** @deprecated Never set; see {@link EnvironmentWorkerOptions.unrestrictedPaths}. */
|
|
147
241
|
readonly unrestrictedPaths: boolean | undefined;
|
|
148
242
|
readonly maxFileBytes: number | null | undefined;
|
|
149
243
|
readonly maxIdleMs: number | undefined;
|
|
244
|
+
readonly memorySyncIntervalMs: number | null | undefined;
|
|
245
|
+
readonly memorySyncDeletions: MemoryDeleteMode;
|
|
150
246
|
readonly workerId: string | undefined;
|
|
151
247
|
readonly requestOptions: BetaToolRunnerRequestOptions | undefined;
|
|
152
248
|
readonly #signal: AbortSignal | undefined;
|
|
153
249
|
|
|
250
|
+
constructor(opts: Omit<EnvironmentWorkerOptions, 'unrestrictedPaths'>);
|
|
251
|
+
/** @deprecated `unrestrictedPaths` is no longer accepted — see {@link EnvironmentWorkerOptions.unrestrictedPaths}. */
|
|
252
|
+
constructor(opts: Omit<EnvironmentWorkerOptions, 'unrestrictedPaths'> & { unrestrictedPaths: boolean }); // help language servers see deprecation
|
|
154
253
|
constructor(opts: EnvironmentWorkerOptions) {
|
|
254
|
+
if (opts.unrestrictedPaths !== undefined) {
|
|
255
|
+
throw new AnthropicError(
|
|
256
|
+
'The `unrestrictedPaths` option you passed to EnvironmentWorker (or ' +
|
|
257
|
+
'client.beta.environments.work.worker()) is no longer supported. ' +
|
|
258
|
+
"The worker's file tools (read, write, edit, glob, grep) are now always confined to `workdir` " +
|
|
259
|
+
"plus the session's memory folders. Remove `unrestrictedPaths` from your options; to let the " +
|
|
260
|
+
'file tools reach any other directory, add it to `AgentToolContext.allowedRoots` from a ' +
|
|
261
|
+
'`tools` factory.',
|
|
262
|
+
);
|
|
263
|
+
}
|
|
155
264
|
this.client = opts.client;
|
|
156
265
|
this.environmentId = opts.environmentId;
|
|
157
266
|
this.environmentKey = opts.environmentKey;
|
|
158
267
|
this.tools = opts.tools;
|
|
159
268
|
this.workdir = opts.workdir ?? process.cwd();
|
|
160
|
-
this.unrestrictedPaths = opts.unrestrictedPaths;
|
|
161
269
|
this.maxFileBytes = opts.maxFileBytes;
|
|
162
270
|
this.maxIdleMs = opts.maxIdleMs;
|
|
271
|
+
if (opts.memorySyncIntervalMs != null) {
|
|
272
|
+
checkMemorySyncInterval(opts.memorySyncIntervalMs, 'memorySyncIntervalMs');
|
|
273
|
+
}
|
|
274
|
+
this.memorySyncIntervalMs = opts.memorySyncIntervalMs;
|
|
275
|
+
this.memorySyncDeletions = opts.memorySyncDeletions ?? 'enabled';
|
|
163
276
|
this.workerId = opts.workerId;
|
|
164
277
|
this.requestOptions = opts.requestOptions;
|
|
165
278
|
this.#signal = opts.signal;
|
|
@@ -185,13 +298,23 @@ export class EnvironmentWorker {
|
|
|
185
298
|
...(this.workerId !== undefined ? { workerId: this.workerId } : {}),
|
|
186
299
|
...(externalSignal ? { signal: externalSignal } : {}),
|
|
187
300
|
...(this.requestOptions !== undefined ? { requestOptions: this.requestOptions } : {}),
|
|
188
|
-
// The per-item handler
|
|
189
|
-
// single owner of `work.stop` rather than double-posting from the
|
|
301
|
+
// The per-item handler stops or releases every work item on exit; let it
|
|
302
|
+
// be the single owner of `work.stop` rather than double-posting from the
|
|
303
|
+
// poller.
|
|
190
304
|
autoStop: false,
|
|
191
305
|
});
|
|
192
306
|
|
|
193
307
|
for await (const work of poller) {
|
|
194
|
-
|
|
308
|
+
try {
|
|
309
|
+
await this.#handleItem(work, environmentKey, poller.signal);
|
|
310
|
+
} catch (e) {
|
|
311
|
+
// One bad item fails that item, not the worker: the handler's teardown
|
|
312
|
+
// already stopped or released it, so the next poll claims the next
|
|
313
|
+
// item. A store directory left behind by a killed worker would
|
|
314
|
+
// otherwise crashloop this process forever.
|
|
315
|
+
if (poller.signal?.aborted) throw e;
|
|
316
|
+
loggerFor(this.client).error('work item failed', { work_id: work.id, error: String(e) });
|
|
317
|
+
}
|
|
195
318
|
}
|
|
196
319
|
}
|
|
197
320
|
|
|
@@ -201,7 +324,9 @@ export class EnvironmentWorker {
|
|
|
201
324
|
* download the session agent's skills (`setupSkills`), run a
|
|
202
325
|
* {@link SessionToolRunner} for the session while heartbeating the work-item
|
|
203
326
|
* lease, and force-stop the work item on exit (whether the runner finishes
|
|
204
|
-
* normally, throws, or the
|
|
327
|
+
* normally, throws, or the control plane signals shutdown). The one
|
|
328
|
+
* exception is a lost lease: the item then belongs to the queue or another
|
|
329
|
+
* worker and is left alone.
|
|
205
330
|
*
|
|
206
331
|
* Use this when something else does the claiming — e.g. a `worker poll
|
|
207
332
|
* --on-work` script that hands an already-claimed item to a fresh process. The
|
|
@@ -211,7 +336,16 @@ export class EnvironmentWorker {
|
|
|
211
336
|
* option, then the worker's own `environmentKey`, then
|
|
212
337
|
* `ANTHROPIC_ENVIRONMENT_KEY`. With no arguments inside that command it just
|
|
213
338
|
* works. Throws a clear error naming the first of the four required values
|
|
214
|
-
* still missing after resolution.
|
|
339
|
+
* still missing after resolution. Throws `SessionMemoryError` when the
|
|
340
|
+
* session has memory stores attached but they cannot be mounted — the work
|
|
341
|
+
* item carried no sessions token (unless `memorySyncIntervalMs` turned
|
|
342
|
+
* memory off), or a store failed to download.
|
|
343
|
+
*
|
|
344
|
+
* `workSecret` is the work item's per-item `secret` payload from the poll
|
|
345
|
+
* response, falling back to `ANTHROPIC_WORK_SECRET`; unlike the others it is
|
|
346
|
+
* optional — when present, the sessions token extracted from it is preferred
|
|
347
|
+
* as the Bearer credential for this item's heartbeat / force-stop / session
|
|
348
|
+
* calls; when absent (or undecodable) those calls use the environment key.
|
|
215
349
|
*/
|
|
216
350
|
async handleItem(opts?: HandleItemOptions): Promise<void> {
|
|
217
351
|
const workId = opts?.workId ?? readEnv('ANTHROPIC_WORK_ID');
|
|
@@ -219,6 +353,9 @@ export class EnvironmentWorker {
|
|
|
219
353
|
const sessionId = opts?.sessionId ?? readEnv('ANTHROPIC_SESSION_ID');
|
|
220
354
|
const environmentKey =
|
|
221
355
|
opts?.environmentKey ?? this.environmentKey ?? readEnv('ANTHROPIC_ENVIRONMENT_KEY');
|
|
356
|
+
// `||` rather than `??` so an empty option still falls through to the env
|
|
357
|
+
// var and then to null (matching how `readEnv` treats empty values).
|
|
358
|
+
const workSecret = opts?.workSecret || readEnv('ANTHROPIC_WORK_SECRET') || null;
|
|
222
359
|
|
|
223
360
|
if (!workId) {
|
|
224
361
|
throw new AnthropicError('handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID');
|
|
@@ -240,6 +377,7 @@ export class EnvironmentWorker {
|
|
|
240
377
|
const work: ClaimedWork = {
|
|
241
378
|
id: workId,
|
|
242
379
|
environment_id: environmentId,
|
|
380
|
+
secret: workSecret,
|
|
243
381
|
data: { type: 'session', id: sessionId },
|
|
244
382
|
};
|
|
245
383
|
await this.#handleItem(work, environmentKey, opts?.signal ?? this.#signal);
|
|
@@ -248,8 +386,14 @@ export class EnvironmentWorker {
|
|
|
248
386
|
/**
|
|
249
387
|
* The per-item body shared by {@link EnvironmentWorker.run}'s poll loop and
|
|
250
388
|
* {@link EnvironmentWorker.handleItem}: run a {@link SessionToolRunner} for the
|
|
251
|
-
* work item's session while heartbeating its lease, force-stopping on exit
|
|
252
|
-
* Non-session work items are ignored.
|
|
389
|
+
* work item's session while heartbeating its lease, force-stopping on exit
|
|
390
|
+
* unless the lease was lost. Non-session work items are ignored.
|
|
391
|
+
*
|
|
392
|
+
* When the poll response carried a per-item `secret` (a short-lived payload
|
|
393
|
+
* scoped to this work item), the sessions token extracted from it is
|
|
394
|
+
* preferred over `environmentKey` as the Bearer credential for those
|
|
395
|
+
* per-item calls; a missing/undecodable secret falls back to
|
|
396
|
+
* `environmentKey` unchanged.
|
|
253
397
|
*/
|
|
254
398
|
async #handleItem(
|
|
255
399
|
work: ClaimedWork,
|
|
@@ -257,14 +401,27 @@ export class EnvironmentWorker {
|
|
|
257
401
|
externalSignal: AbortSignal | undefined,
|
|
258
402
|
): Promise<void> {
|
|
259
403
|
const log = loggerFor(this.client);
|
|
404
|
+
// The per-item credential: the sessions token carried inside the work
|
|
405
|
+
// item's secret payload when the server issued one, otherwise the
|
|
406
|
+
// environment key. Never log this value.
|
|
407
|
+
const sessionsToken = sessionsTokenFromSecret(work.secret);
|
|
408
|
+
if (work.secret && sessionsToken === null) {
|
|
409
|
+
log.warn(
|
|
410
|
+
'work item carried a secret payload but no sessions token could be extracted; ' +
|
|
411
|
+
'falling back to the environment key',
|
|
412
|
+
{ work_id: work.id },
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
const itemCredential = sessionsToken ?? environmentKey;
|
|
260
416
|
// Every per-session call — the SessionToolRunner event stream/list/send, the
|
|
261
|
-
// lease heartbeat, and the work force-stop —
|
|
262
|
-
//
|
|
263
|
-
// `copyClientForHelper` also clears the parent's
|
|
264
|
-
// emits *only* the bearer credential on the
|
|
265
|
-
// `withOptions({authToken})` would leave `X-Api-Key` set as
|
|
417
|
+
// lease heartbeat, the skill download, and the work force-stop —
|
|
418
|
+
// authenticates with the per-item credential. Scope a client to it once and
|
|
419
|
+
// thread that through. `copyClientForHelper` also clears the parent's
|
|
420
|
+
// `apiKey`, so the sub-client emits *only* the bearer credential on the
|
|
421
|
+
// wire (a plain `withOptions({authToken})` would leave `X-Api-Key` set as
|
|
422
|
+
// well).
|
|
266
423
|
const sessionClient = copyClientForHelper(this.client, {
|
|
267
|
-
authToken:
|
|
424
|
+
authToken: itemCredential,
|
|
268
425
|
helper: 'environments-worker',
|
|
269
426
|
});
|
|
270
427
|
|
|
@@ -272,68 +429,191 @@ export class EnvironmentWorker {
|
|
|
272
429
|
// single owner of `work.stop` for every claimed item.
|
|
273
430
|
const sessionId = work.data.id;
|
|
274
431
|
|
|
275
|
-
const ctx: AgentToolContext = {
|
|
276
|
-
workdir: this.workdir,
|
|
277
|
-
client: this.client,
|
|
278
|
-
sessionId,
|
|
279
|
-
...(this.unrestrictedPaths !== undefined ? { unrestrictedPaths: this.unrestrictedPaths } : {}),
|
|
280
|
-
...(this.maxFileBytes !== undefined ? { maxFileBytes: this.maxFileBytes } : {}),
|
|
281
|
-
};
|
|
282
|
-
// Lazily load the Node-only toolset module — see the import note at the top.
|
|
283
|
-
const agentToolset = await import('../../tools/agent-toolset/node');
|
|
284
|
-
let cleanupSkills: () => Promise<void> = async () => {};
|
|
285
|
-
try {
|
|
286
|
-
cleanupSkills = await agentToolset.setupSkills(ctx);
|
|
287
|
-
} catch (e) {
|
|
288
|
-
log.warn('skill setup failed', { session_id: sessionId, work_id: work.id, error: String(e) });
|
|
289
|
-
}
|
|
290
|
-
const tools =
|
|
291
|
-
typeof this.tools === 'function' ?
|
|
292
|
-
this.tools(ctx)
|
|
293
|
-
: this.tools ?? agentToolset.betaAgentToolset20260401(ctx);
|
|
294
|
-
|
|
295
432
|
// A per-session controller: aborts when the supplied signal aborts, when the
|
|
296
433
|
// session runner finishes, or when the lease heartbeat says to stop.
|
|
297
434
|
const ctrl = new AbortController();
|
|
298
435
|
const detachExternal = linkAbort(externalSignal, ctrl);
|
|
436
|
+
const lease = new Lease(ctrl);
|
|
299
437
|
|
|
300
|
-
//
|
|
301
|
-
const
|
|
302
|
-
client: sessionClient,
|
|
303
|
-
tools,
|
|
304
|
-
...(this.maxIdleMs !== undefined ? { maxIdleMs: this.maxIdleMs } : {}),
|
|
305
|
-
...(this.requestOptions !== undefined ? { requestOptions: this.requestOptions } : {}),
|
|
306
|
-
signal: ctrl.signal,
|
|
307
|
-
});
|
|
438
|
+
// Lazily load the Node-only toolset module — see the import note at the top.
|
|
439
|
+
const agentToolset = await import('../../tools/agent-toolset/node');
|
|
308
440
|
|
|
441
|
+
// Start the lease heartbeat BEFORE the session fetch and the skill /
|
|
442
|
+
// memory downloads: those can take longer than the lease TTL, and an
|
|
443
|
+
// unheartbeated lease lapsing mid-download would let another worker
|
|
444
|
+
// reclaim the item and serve the same session (split-brain).
|
|
445
|
+
//
|
|
309
446
|
// Each heartbeat reports the lease TTL the server is enforcing; it becomes
|
|
310
447
|
// the runner's tool-result send retry window so a send keeps retrying
|
|
311
|
-
// exactly as long as the lease could still be live.
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
448
|
+
// exactly as long as the lease could still be live. The runner is only
|
|
449
|
+
// built after the downloads, so hold the latest TTL until then.
|
|
450
|
+
let leaseTtlMs: number | undefined;
|
|
451
|
+
let runner: SessionToolRunner | undefined;
|
|
452
|
+
const heartbeatPromise = heartbeatLoop(sessionClient, work, lease, log, this.requestOptions, (ttlMs) => {
|
|
453
|
+
leaseTtlMs = ttlMs;
|
|
454
|
+
runner?._setSendRetryWindow(ttlMs);
|
|
455
|
+
}).catch((e) => {
|
|
315
456
|
if (!ctrl.signal.aborted) log.error('heartbeat loop failed', { work_id: work.id, error: String(e) });
|
|
316
457
|
ctrl.abort();
|
|
317
458
|
});
|
|
318
459
|
|
|
460
|
+
let cleanupSkills: () => Promise<void> = async () => {};
|
|
461
|
+
let stores: SessionMemoryStores | undefined;
|
|
462
|
+
let cleanEnd = false;
|
|
319
463
|
try {
|
|
464
|
+
if (work.data.type !== 'session') {
|
|
465
|
+
log.debug('skipping non-session work item', { work_id: work.id, type: work.data.type });
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
// One session fetch, shared by the skills download and the memory-store
|
|
469
|
+
// download — two fetches could disagree about the attached resources.
|
|
470
|
+
// A failed fetch fails the work item (the teardown below still stops
|
|
471
|
+
// or releases it).
|
|
472
|
+
const session: BetaManagedAgentsSession = await sessionClient.beta.sessions.retrieve(sessionId);
|
|
473
|
+
// Only with the session in hand can we tell one that simply has no
|
|
474
|
+
// memory from one whose memory we cannot mount. Turning memory off
|
|
475
|
+
// with the interval knob is a deliberate opt-out and stays quiet.
|
|
476
|
+
if (sessionsToken === null && this.memorySyncIntervalMs !== null && hasMemoryStore(session)) {
|
|
477
|
+
throw new agentToolset.SessionMemoryError(
|
|
478
|
+
`cannot mount the session's memories: the work item carried no sessions token ` +
|
|
479
|
+
`(work_id=${work.id}, session_id=${sessionId}); ` +
|
|
480
|
+
'the memory endpoints reject the environment key, so the poller must issue a per-item ' +
|
|
481
|
+
'`secret` carrying `sessions_token`, or set `memorySyncIntervalMs: null` to run without memory',
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
const ctx: AgentToolContext = {
|
|
486
|
+
workdir: this.workdir,
|
|
487
|
+
// The scoped sub-client, not the parent: the skill download
|
|
488
|
+
// `setupSkills` performs for this session rides the same per-item
|
|
489
|
+
// credential as every other per-item call.
|
|
490
|
+
client: sessionClient,
|
|
491
|
+
session,
|
|
492
|
+
...(this.maxFileBytes !== undefined ? { maxFileBytes: this.maxFileBytes } : {}),
|
|
493
|
+
};
|
|
494
|
+
try {
|
|
495
|
+
cleanupSkills = await agentToolset.setupSkills(ctx);
|
|
496
|
+
} catch (e) {
|
|
497
|
+
log.warn('skill setup failed', { session_id: sessionId, work_id: work.id, error: String(e) });
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// Memory stores: the memory_stores endpoints accept the per-item sessions
|
|
501
|
+
// token but reject the environment key, so download and sync only run when
|
|
502
|
+
// the item carried a usable secret (and the interval is set).
|
|
503
|
+
// `sessionClient` is already scoped to that token then, so the memory
|
|
504
|
+
// calls ride the same sub-client. A store that cannot be materialised
|
|
505
|
+
// throws `SessionMemoryError` out of `download` and fails the item.
|
|
506
|
+
if (sessionsToken !== null && this.memorySyncIntervalMs !== null) {
|
|
507
|
+
stores = new agentToolset.SessionMemoryStores(sessionClient, {
|
|
508
|
+
workdir: this.workdir,
|
|
509
|
+
...(this.memorySyncIntervalMs !== undefined ? { syncIntervalMs: this.memorySyncIntervalMs } : {}),
|
|
510
|
+
syncDeletions: this.memorySyncDeletions,
|
|
511
|
+
});
|
|
512
|
+
await stores.download(session);
|
|
513
|
+
// A store mounted outside the workdir must stay reachable by the file
|
|
514
|
+
// tools; read-only stores still refuse writes.
|
|
515
|
+
ctx.allowedRoots = stores.roots;
|
|
516
|
+
ctx.readOnlyRoots = stores.readOnlyRoots;
|
|
517
|
+
} else {
|
|
518
|
+
log.debug('memory stores disabled for this item', { work_id: work.id });
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const tools =
|
|
522
|
+
typeof this.tools === 'function' ?
|
|
523
|
+
this.tools(ctx)
|
|
524
|
+
: this.tools ?? agentToolset.betaAgentToolset20260401(ctx);
|
|
525
|
+
|
|
526
|
+
runner = new SessionToolRunner(sessionId, {
|
|
527
|
+
client: sessionClient,
|
|
528
|
+
tools,
|
|
529
|
+
...(this.maxIdleMs !== undefined ? { maxIdleMs: this.maxIdleMs } : {}),
|
|
530
|
+
...(this.requestOptions !== undefined ? { requestOptions: this.requestOptions } : {}),
|
|
531
|
+
signal: ctrl.signal,
|
|
532
|
+
});
|
|
533
|
+
if (leaseTtlMs !== undefined) runner._setSendRetryWindow(leaseTtlMs);
|
|
320
534
|
for await (const _ of runner) {
|
|
321
535
|
// Drive the runner to completion; per-call observability is not part
|
|
322
536
|
// of this composition's surface — use `SessionToolRunner` directly
|
|
323
537
|
// (via `client.beta.sessions.events.toolRunner`) if you want it.
|
|
538
|
+
if (stores) await stores.syncIfDue();
|
|
324
539
|
}
|
|
540
|
+
// Only a clean stream end earns the last full sync; it runs in the
|
|
541
|
+
// teardown below.
|
|
542
|
+
cleanEnd = !ctrl.signal.aborted;
|
|
325
543
|
} finally {
|
|
326
|
-
|
|
544
|
+
// The heartbeat keeps the lease alive until this teardown is done.
|
|
545
|
+
try {
|
|
546
|
+
// cleanupSkills first, so its failure cannot skip the memory flush.
|
|
547
|
+
await cleanupSkills().catch((e) => {
|
|
548
|
+
log.warn('skill cleanup failed', { session_id: sessionId, work_id: work.id, error: String(e) });
|
|
549
|
+
});
|
|
550
|
+
} finally {
|
|
551
|
+
if (stores) {
|
|
552
|
+
const boundMs = agentToolset.MEMORY_FLUSH_TIMEOUT_MS;
|
|
553
|
+
if (cleanEnd) {
|
|
554
|
+
const finishCutOff = await withTimeout(stores.finish(), boundMs);
|
|
555
|
+
if (finishCutOff) {
|
|
556
|
+
log.warn(
|
|
557
|
+
`final memory sync cut off after ${boundMs}ms; the flush that follows still uploads changed files`,
|
|
558
|
+
{ session_id: sessionId, work_id: work.id },
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
// Also after finish(): it swallows its own failures, and a
|
|
563
|
+
// clean flush is a no-op.
|
|
564
|
+
const flushBound = new AbortController();
|
|
565
|
+
const flushCutOff = await withTimeout(stores.flushWrites(flushBound.signal), boundMs);
|
|
566
|
+
if (flushCutOff) {
|
|
567
|
+
flushBound.abort();
|
|
568
|
+
log.warn(
|
|
569
|
+
`memory flush cut off after ${boundMs}ms; changed files it had not uploaded yet are not saved`,
|
|
570
|
+
{ session_id: sessionId, work_id: work.id },
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
await stores.dispose().catch((e) => {
|
|
574
|
+
log.warn('memory store cleanup failed', {
|
|
575
|
+
session_id: sessionId,
|
|
576
|
+
work_id: work.id,
|
|
577
|
+
error: String(e),
|
|
578
|
+
});
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
lease.finish('runner_done');
|
|
327
583
|
detachExternal();
|
|
328
584
|
await heartbeatPromise;
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
585
|
+
// Stop only an item this worker still holds — after a lost lease it
|
|
586
|
+
// belongs to the queue or another worker.
|
|
587
|
+
if (lease.lost) {
|
|
588
|
+
log.info('lease lost; released without stopping it', { session_id: sessionId, work_id: work.id });
|
|
589
|
+
} else {
|
|
590
|
+
await forceStop(sessionClient, work, log, this.requestOptions);
|
|
591
|
+
}
|
|
333
592
|
}
|
|
334
593
|
}
|
|
335
594
|
}
|
|
336
595
|
|
|
596
|
+
/**
|
|
597
|
+
* Resolve when `p` settles or `ms` elapses — `true` when `ms` elapsed
|
|
598
|
+
* first. A timed-out `p` keeps running — JS cannot cancel a promise.
|
|
599
|
+
*/
|
|
600
|
+
async function withTimeout(p: Promise<void>, ms: number): Promise<boolean> {
|
|
601
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
602
|
+
try {
|
|
603
|
+
return await Promise.race([
|
|
604
|
+
p.then(
|
|
605
|
+
() => false,
|
|
606
|
+
() => false,
|
|
607
|
+
),
|
|
608
|
+
new Promise<boolean>((resolve) => {
|
|
609
|
+
timer = setTimeout(() => resolve(true), ms);
|
|
610
|
+
}),
|
|
611
|
+
]);
|
|
612
|
+
} finally {
|
|
613
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
337
617
|
/** Force-stop a claimed work item, swallowing the 409 that means it's already stopped. */
|
|
338
618
|
async function forceStop(
|
|
339
619
|
client: Anthropic,
|
|
@@ -357,18 +637,67 @@ async function forceStop(
|
|
|
357
637
|
}
|
|
358
638
|
}
|
|
359
639
|
|
|
640
|
+
/** Why heartbeating of a work item ended, as recorded on its {@link Lease}. */
|
|
641
|
+
type LeaseEndReason =
|
|
642
|
+
| 'runner_done'
|
|
643
|
+
| 'control_plane_stop'
|
|
644
|
+
| 'lease_lost'
|
|
645
|
+
| 'heartbeat_rejected'
|
|
646
|
+
| 'assumed_lost';
|
|
647
|
+
|
|
360
648
|
/**
|
|
361
|
-
*
|
|
362
|
-
*
|
|
363
|
-
*
|
|
649
|
+
* This worker's view of one work-item lease: the per-item abort signal plus
|
|
650
|
+
* why heartbeating ended. The first recorded reason wins, so a run aborted
|
|
651
|
+
* *because* the lease was lost still reads as lost afterwards; an abort with
|
|
652
|
+
* no recorded reason (the external signal) is not lost.
|
|
653
|
+
*/
|
|
654
|
+
class Lease {
|
|
655
|
+
readonly #ctrl: AbortController;
|
|
656
|
+
#endReason: LeaseEndReason | undefined;
|
|
657
|
+
|
|
658
|
+
constructor(ctrl: AbortController) {
|
|
659
|
+
this.#ctrl = ctrl;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
get signal(): AbortSignal {
|
|
663
|
+
return this.#ctrl.signal;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
finish(reason: LeaseEndReason): void {
|
|
667
|
+
this.#endReason ??= reason;
|
|
668
|
+
this.#ctrl.abort();
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** True once the item belongs to the queue or another worker. */
|
|
672
|
+
get lost(): boolean {
|
|
673
|
+
return this.#endReason === 'lease_lost' || this.#endReason === 'assumed_lost';
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/** The server's view of the lease carried by a 412 heartbeat response, or empty if absent. */
|
|
678
|
+
function serverLeaseState(e: unknown): Record<string, unknown> {
|
|
679
|
+
let node: unknown = e instanceof APIError ? e.error : undefined;
|
|
680
|
+
for (const key of ['error', 'details', 'current_state']) {
|
|
681
|
+
if (!isObj(node)) return {};
|
|
682
|
+
node = node[key];
|
|
683
|
+
}
|
|
684
|
+
return isObj(node) ? node : {};
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Keep the work-item lease alive while a session is being served. Runs until
|
|
689
|
+
* `lease` ends, and ends it itself when the control plane reports the work is
|
|
690
|
+
* `stopping`/`stopped` or no longer extends the lease, when a heartbeat is
|
|
691
|
+
* rejected (a 412 means the lease already belongs to someone else), or when no
|
|
364
692
|
* heartbeat has succeeded for longer than the lease ttl (the lease is assumed
|
|
365
|
-
* lost
|
|
366
|
-
*
|
|
693
|
+
* lost, so two runners don't end up serving the same work). Each heartbeat
|
|
694
|
+
* call is cut off after the current beat interval so a hung request cannot
|
|
695
|
+
* outlive the lease it is meant to renew.
|
|
367
696
|
*/
|
|
368
697
|
async function heartbeatLoop(
|
|
369
698
|
client: Anthropic,
|
|
370
699
|
work: Pick<BetaSelfHostedWork, 'id' | 'environment_id'>,
|
|
371
|
-
|
|
700
|
+
lease: Lease,
|
|
372
701
|
logger: Logger,
|
|
373
702
|
requestOptions?: BetaToolRunnerRequestOptions,
|
|
374
703
|
/** Called with the server-reported lease TTL after every successful beat. */
|
|
@@ -382,7 +711,7 @@ async function heartbeatLoop(
|
|
|
382
711
|
// Not the request `timeout` option: the core client retries timeouts, so
|
|
383
712
|
// it would not bound the call as a whole.
|
|
384
713
|
const beatCtrl = new AbortController();
|
|
385
|
-
const detach = linkAbort(
|
|
714
|
+
const detach = linkAbort(lease.signal, beatCtrl);
|
|
386
715
|
const cutoff = setTimeout(() => beatCtrl.abort(), intervalMs);
|
|
387
716
|
try {
|
|
388
717
|
const resp = await client.beta.environments.work.heartbeat(
|
|
@@ -399,19 +728,30 @@ async function heartbeatLoop(
|
|
|
399
728
|
}
|
|
400
729
|
if (resp.state === 'stopping' || resp.state === 'stopped') {
|
|
401
730
|
logger.info('heartbeat signals shutdown', { work_id: work.id, state: resp.state });
|
|
402
|
-
|
|
731
|
+
lease.finish('control_plane_stop');
|
|
403
732
|
}
|
|
404
733
|
if (!resp.lease_extended) {
|
|
405
734
|
logger.warn('lease not extended, shutting down', { work_id: work.id });
|
|
406
|
-
|
|
735
|
+
lease.finish('control_plane_stop');
|
|
407
736
|
}
|
|
408
737
|
} catch (e) {
|
|
409
738
|
// An abort throws to unwind the caller (the `heartbeatLoop(...).catch`
|
|
410
739
|
// in `#handleItem`) rather than returning early.
|
|
411
|
-
|
|
740
|
+
lease.signal.throwIfAborted();
|
|
741
|
+
if (isStatus(e, 412)) {
|
|
742
|
+
const server = serverLeaseState(e);
|
|
743
|
+
logger.error('lease lost: heartbeat precondition failed', {
|
|
744
|
+
work_id: work.id,
|
|
745
|
+
server_state: server['state'],
|
|
746
|
+
server_ttl_seconds: server['ttl_seconds'],
|
|
747
|
+
server_last_heartbeat: server['last_heartbeat'],
|
|
748
|
+
});
|
|
749
|
+
lease.finish('lease_lost');
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
412
752
|
if (isFatal4xx(e)) {
|
|
413
753
|
logger.error('permanent heartbeat failure', { work_id: work.id, error: String(e) });
|
|
414
|
-
|
|
754
|
+
lease.finish('heartbeat_rejected');
|
|
415
755
|
throw e;
|
|
416
756
|
}
|
|
417
757
|
if (Date.now() - lastSuccessMs > ttlMs) {
|
|
@@ -420,7 +760,7 @@ async function heartbeatLoop(
|
|
|
420
760
|
ttl_ms: ttlMs,
|
|
421
761
|
error: String(e),
|
|
422
762
|
});
|
|
423
|
-
|
|
763
|
+
lease.finish('assumed_lost');
|
|
424
764
|
return;
|
|
425
765
|
}
|
|
426
766
|
logger.warn('transient heartbeat failure', { work_id: work.id, error: String(e) });
|
|
@@ -431,9 +771,9 @@ async function heartbeatLoop(
|
|
|
431
771
|
};
|
|
432
772
|
|
|
433
773
|
await beat();
|
|
434
|
-
while (!
|
|
435
|
-
await sleep(intervalMs,
|
|
436
|
-
|
|
774
|
+
while (!lease.signal.aborted) {
|
|
775
|
+
await sleep(intervalMs, lease.signal);
|
|
776
|
+
lease.signal.throwIfAborted();
|
|
437
777
|
await beat();
|
|
438
778
|
}
|
|
439
779
|
}
|