stitchkit 0.128.0 → 0.130.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 +83 -0
- package/dist/agent-executor/acp/v1-connect.d.ts +87 -19
- package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-driver.d.ts +4 -2
- package/dist/agent-executor/acp/v1-driver.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-handlers.d.ts +56 -0
- package/dist/agent-executor/acp/v1-handlers.d.ts.map +1 -0
- package/dist/agent-executor/acp/v1-map.d.ts +13 -2
- package/dist/agent-executor/acp/v1-map.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-permission.d.ts +44 -0
- package/dist/agent-executor/acp/v1-permission.d.ts.map +1 -0
- package/dist/agent-executor/acp/v1-protocol.d.ts +63 -10
- package/dist/agent-executor/acp/v1-protocol.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-session.d.ts +34 -7
- package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-turn.d.ts +51 -13
- package/dist/agent-executor/acp/v1-turn.d.ts.map +1 -1
- package/dist/agent-executor/claude/classify.d.ts +10 -0
- package/dist/agent-executor/claude/classify.d.ts.map +1 -1
- package/dist/agent-executor/claude/cli-driver.d.ts +4 -1
- package/dist/agent-executor/claude/cli-driver.d.ts.map +1 -1
- package/dist/agent-executor/claude/events.d.ts +146 -0
- package/dist/agent-executor/claude/events.d.ts.map +1 -0
- package/dist/agent-executor/claude/limits.d.ts +7 -1
- package/dist/agent-executor/claude/limits.d.ts.map +1 -1
- package/dist/agent-executor/claude/protocol.d.ts +49 -9
- package/dist/agent-executor/claude/protocol.d.ts.map +1 -1
- package/dist/agent-executor/claude/session.d.ts +2 -0
- package/dist/agent-executor/claude/session.d.ts.map +1 -1
- package/dist/agent-executor/claude/transcript.d.ts +2 -2
- package/dist/agent-executor/claude/transcript.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/controls.d.ts +28 -0
- package/dist/agent-executor/claude-sdk/controls.d.ts.map +1 -0
- package/dist/agent-executor/claude-sdk/driver.d.ts +208 -4
- package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/probe.d.ts +29 -0
- package/dist/agent-executor/claude-sdk/probe.d.ts.map +1 -0
- package/dist/agent-executor/claude-sdk/query-loop.d.ts +94 -0
- package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -0
- package/dist/agent-executor/claude-sdk/query-options.d.ts +29 -0
- package/dist/agent-executor/claude-sdk/query-options.d.ts.map +1 -0
- package/dist/agent-executor/claude-sdk/session.d.ts +5 -5
- package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/turn-usage.d.ts +81 -0
- package/dist/agent-executor/claude-sdk/turn-usage.d.ts.map +1 -0
- package/dist/agent-executor/codex/classify.d.ts +4 -0
- package/dist/agent-executor/codex/classify.d.ts.map +1 -1
- package/dist/agent-executor/codex/connect.d.ts +46 -0
- package/dist/agent-executor/codex/connect.d.ts.map +1 -0
- package/dist/agent-executor/codex/control-client.d.ts +168 -0
- package/dist/agent-executor/codex/control-client.d.ts.map +1 -0
- package/dist/agent-executor/codex/driver.d.ts +71 -10
- package/dist/agent-executor/codex/driver.d.ts.map +1 -1
- package/dist/agent-executor/codex/handlers.d.ts +47 -0
- package/dist/agent-executor/codex/handlers.d.ts.map +1 -0
- package/dist/agent-executor/codex/limits.d.ts +11 -2
- package/dist/agent-executor/codex/limits.d.ts.map +1 -1
- package/dist/agent-executor/codex/protocol.d.ts +173 -4
- package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
- package/dist/agent-executor/codex/request-answers.d.ts +101 -0
- package/dist/agent-executor/codex/request-answers.d.ts.map +1 -0
- package/dist/agent-executor/codex/session-controls.d.ts +195 -0
- package/dist/agent-executor/codex/session-controls.d.ts.map +1 -0
- package/dist/agent-executor/codex/session.d.ts +55 -37
- package/dist/agent-executor/codex/session.d.ts.map +1 -1
- package/dist/agent-executor/codex/shared-server.d.ts +29 -0
- package/dist/agent-executor/codex/shared-server.d.ts.map +1 -0
- package/dist/agent-executor/codex/shared-thread.d.ts +46 -0
- package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -0
- package/dist/agent-executor/codex/thread-controls.d.ts +128 -0
- package/dist/agent-executor/codex/thread-controls.d.ts.map +1 -0
- package/dist/agent-executor/codex/turn-input.d.ts +30 -0
- package/dist/agent-executor/codex/turn-input.d.ts.map +1 -0
- package/dist/agent-executor/codex/unix-socket-target.d.ts +26 -0
- package/dist/agent-executor/codex/unix-socket-target.d.ts.map +1 -0
- package/dist/agent-executor/codex/unix-socket.d.ts +26 -0
- package/dist/agent-executor/codex/unix-socket.d.ts.map +1 -0
- package/dist/agent-executor/codex/ws-frame.d.ts +15 -0
- package/dist/agent-executor/codex/ws-frame.d.ts.map +1 -0
- package/dist/agent-executor/contract.d.ts +79 -0
- package/dist/agent-executor/contract.d.ts.map +1 -1
- package/dist/agent-executor/engine-process.d.ts +9 -0
- package/dist/agent-executor/engine-process.d.ts.map +1 -1
- package/dist/agent-executor/engine.d.ts +6 -2
- package/dist/agent-executor/engine.d.ts.map +1 -1
- package/dist/agent-executor/executor-contract.d.ts +54 -0
- package/dist/agent-executor/executor-contract.d.ts.map +1 -1
- package/dist/agent-executor/handoff-schemas.d.ts +407 -0
- package/dist/agent-executor/handoff-schemas.d.ts.map +1 -0
- package/dist/agent-executor/handoff.d.ts +12 -0
- package/dist/agent-executor/handoff.d.ts.map +1 -0
- package/dist/agent-executor/hello.d.ts +80 -0
- package/dist/agent-executor/hello.d.ts.map +1 -1
- package/dist/agent-executor/image-input.d.ts +22 -0
- package/dist/agent-executor/image-input.d.ts.map +1 -1
- package/dist/agent-executor/projection.d.ts +2 -2
- package/dist/agent-executor/projection.d.ts.map +1 -1
- package/dist/agent-executor/session-primitives.d.ts +10 -1
- package/dist/agent-executor/session-primitives.d.ts.map +1 -1
- package/dist/agent-executor/testing/conformance.d.ts.map +1 -1
- package/dist/agent-executor/testing/replay-driver.d.ts +41 -0
- package/dist/agent-executor/testing/replay-driver.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-gate.d.ts +11 -0
- package/dist/agent-executor/testing/replay-gate.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-runner.d.ts +27 -0
- package/dist/agent-executor/testing/replay-runner.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-scenarios.d.ts +21 -0
- package/dist/agent-executor/testing/replay-scenarios.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-transcript.d.ts +296 -0
- package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -0
- package/dist/agent-executor/vocabulary.d.ts +135 -0
- package/dist/agent-executor/vocabulary.d.ts.map +1 -1
- package/dist/agent-runtime/branch-observations.d.ts +5 -5
- package/dist/agent-runtime/deferred-tool-selection.d.ts.map +1 -1
- package/dist/agent-runtime/sql-rows.d.ts +10 -10
- package/dist/agent-runtime/terminal-commit.d.ts +10 -10
- package/dist/entrypoints/agent-executor/acp.d.ts +4 -1
- package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/acp.js +852 -219
- package/dist/entrypoints/agent-executor/claude-sdk.d.ts +5 -1
- package/dist/entrypoints/agent-executor/claude-sdk.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/claude-sdk.js +1075 -136
- package/dist/entrypoints/agent-executor/claude.js +48 -23
- package/dist/entrypoints/agent-executor/codex.d.ts +11 -0
- package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/codex.js +3067 -388
- package/dist/entrypoints/agent-executor/testing.d.ts +4 -0
- package/dist/entrypoints/agent-executor/testing.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/testing.js +1002 -2
- package/dist/entrypoints/agent-executor.d.ts +4 -2
- package/dist/entrypoints/agent-executor.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor.js +416 -28
- package/dist/entrypoints/agent-runtime/browser.js +1 -1
- package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
- package/dist/entrypoints/agent-runtime/harness.js +8 -8
- package/dist/entrypoints/agent-runtime/openrouter.js +2 -2
- package/dist/entrypoints/agent-runtime/postgres.js +6 -6
- package/dist/entrypoints/agent-runtime/realtime.js +4 -4
- package/dist/entrypoints/agent-runtime/sandbox.js +5 -5
- package/dist/entrypoints/agent-runtime/sqlite/bun.js +6 -6
- package/dist/entrypoints/agent-runtime/sqlite/node.js +6 -6
- package/dist/entrypoints/agent-runtime/testing.js +5 -5
- package/dist/entrypoints/agent-runtime.js +21 -40
- package/dist/entrypoints/application/directory-inbox.js +2 -2
- package/dist/entrypoints/application/opentelemetry.js +2 -2
- package/dist/entrypoints/application.js +2 -2
- package/dist/entrypoints/cli/publish.js +3 -3
- package/dist/entrypoints/cli.js +8 -8
- package/dist/entrypoints/contract.js +2 -2
- package/dist/entrypoints/files/packaging.js +2 -2
- package/dist/entrypoints/files.js +7 -7
- package/dist/entrypoints/handler.js +4 -4
- package/dist/entrypoints/http.js +5 -5
- package/dist/entrypoints/index.js +7 -7
- package/dist/entrypoints/node.js +5 -5
- package/dist/entrypoints/observability.js +4 -4
- package/dist/entrypoints/primitives.js +2 -2
- package/dist/entrypoints/process.js +5 -5
- package/dist/entrypoints/react.js +1 -1
- package/dist/entrypoints/remote.js +2 -2
- package/dist/entrypoints/server.js +6 -6
- package/dist/entrypoints/service-host/macos.js +5 -5
- package/dist/entrypoints/service-host.js +7 -7
- package/dist/entrypoints/spend.js +1 -1
- package/dist/entrypoints/sync/postgres.js +1 -1
- package/dist/entrypoints/sync.js +2 -2
- package/dist/entrypoints/telegram.js +2 -2
- package/dist/entrypoints/testing.js +5 -5
- package/dist/entrypoints/tools/agent.js +5 -5
- package/dist/entrypoints/tools/connections.js +2 -2
- package/dist/entrypoints/tools/invoker.js +4 -4
- package/dist/entrypoints/tools/mcp.d.ts +1 -0
- package/dist/entrypoints/tools/mcp.d.ts.map +1 -1
- package/dist/entrypoints/tools/mcp.js +5 -5
- package/dist/entrypoints/tools/toolkit.js +8 -8
- package/dist/entrypoints/tools.js +12 -12
- package/dist/entrypoints/tracking/contract.js +1 -1
- package/dist/entrypoints/xlsx.js +1 -1
- package/dist/{index-prf6ayhf.js → index-13wmzpa6.js} +1 -1
- package/dist/{index-n7f89hjw.js → index-17qgm6xe.js} +3 -3
- package/dist/{index-wv8dqy7q.js → index-205456mf.js} +1 -1
- package/dist/{index-pwskmywy.js → index-21cfxc4z.js} +1 -1
- package/dist/{index-13dnv6d0.js → index-2s8sy57y.js} +37 -104
- package/dist/{index-d4svrknj.js → index-39c2hj6h.js} +2 -2
- package/dist/{index-sfzfd2m2.js → index-39rmc00v.js} +1 -1
- package/dist/{index-ky3ardqn.js → index-3fym4j8n.js} +1 -1
- package/dist/{index-c5gp2gh6.js → index-5tdc0q43.js} +1 -1
- package/dist/{index-3ypvpkwr.js → index-669374qc.js} +1 -1
- package/dist/{index-5jyjb4s0.js → index-80acsm27.js} +1 -1
- package/dist/{index-xmr47znh.js → index-827bgv33.js} +1 -1
- package/dist/{index-v1mxss62.js → index-93n6jwy0.js} +3 -3
- package/dist/{index-d54npte7.js → index-9kpxz49v.js} +2 -2
- package/dist/{index-xv9jb84s.js → index-9sfhje6y.js} +3 -3
- package/dist/{index-9y0afd5f.js → index-apf5g7y9.js} +1 -1
- package/dist/{index-bh4pmtr9.js → index-dbp6xemn.js} +78 -8
- package/dist/{index-g3e57qj6.js → index-dcsxj68j.js} +2 -2
- package/dist/{index-waa6t4zx.js → index-dnzxxf8a.js} +1 -1
- package/dist/{index-gf92hc87.js → index-fgahdc7s.js} +2 -2
- package/dist/{index-kzavdze2.js → index-gr0kxymw.js} +5 -1
- package/dist/{index-e06z0tkb.js → index-gya4hwh3.js} +2 -2
- package/dist/{index-gzny6zsw.js → index-hab790s6.js} +5 -5
- package/dist/{index-bz3gn6cs.js → index-j0ef04jw.js} +2 -2
- package/dist/{index-rhb33thr.js → index-jcge9tx3.js} +1 -1
- package/dist/{index-4qvyhn23.js → index-jrn3prgm.js} +1 -1
- package/dist/index-kne9g2c5.js +30 -0
- package/dist/{index-pn5b11ce.js → index-mkfhpk11.js} +1 -1
- package/dist/{index-1qwrczr1.js → index-mttkdm5a.js} +1 -1
- package/dist/{index-rxnyygke.js → index-n3bm7zqq.js} +1 -1
- package/dist/{index-6wp4dn9d.js → index-p06z7g7w.js} +3 -3
- package/dist/{index-kt6dh1n6.js → index-p16q492v.js} +1 -1
- package/dist/index-p1qmpq0p.js +1300 -0
- package/dist/{index-t7wa7k12.js → index-pp97q86a.js} +1 -1
- package/dist/{index-39n02e0q.js → index-psye60qn.js} +1 -1
- package/dist/{index-5ptwb6ka.js → index-pzhqydxb.js} +1 -1
- package/dist/{index-7kfcb576.js → index-qa2jjb65.js} +1 -1
- package/dist/{index-rzeezh79.js → index-qhjmmsm2.js} +2 -2
- package/dist/{index-7grgs8cx.js → index-qpzyahe3.js} +2 -2
- package/dist/{index-jfecdk1e.js → index-r97ppg0g.js} +2 -2
- package/dist/{index-bmaz3jzy.js → index-rjs94dny.js} +1 -1
- package/dist/{index-5v5vg85s.js → index-rxh3qy4x.js} +32 -5
- package/dist/{index-en8e5zsj.js → index-ryxb427v.js} +1 -1
- package/dist/{index-y065r8g5.js → index-sd4e5x5j.js} +7 -7
- package/dist/{index-g56ht6qf.js → index-t3qcac2a.js} +1 -1
- package/dist/{index-m18xm96h.js → index-v759mzed.js} +156 -6
- package/dist/{index-4j8efqr3.js → index-x2fb37t0.js} +2 -2
- package/dist/{index-cbhxhma2.js → index-x5ayy5bn.js} +1 -0
- package/dist/index-y0a4gt1s.js +142 -0
- package/dist/{index-wavv538x.js → index-ybdq8kk2.js} +3 -3
- package/dist/{index-4gk6k3zc.js → index-ycr4pk0z.js} +1 -1
- package/dist/{index-0tyt97nk.js → index-yrr3n391.js} +1 -1
- package/dist/{index-v37b2cd6.js → index-z20pdxeb.js} +2 -2
- package/dist/{index-8x22nprv.js → index-z9d74jmb.js} +3 -3
- package/dist/{index-3tnwtz38.js → index-zhshhxew.js} +1 -1
- package/dist/{index-hj1zq7mh.js → index-znd1b57f.js} +3 -3
- package/dist/internal/positive-integer.d.ts +2 -0
- package/dist/internal/positive-integer.d.ts.map +1 -1
- package/dist/internal/unix-socket.d.ts +7 -0
- package/dist/internal/unix-socket.d.ts.map +1 -1
- package/dist/tools/internal/rank-tools.d.ts +10 -0
- package/dist/tools/internal/rank-tools.d.ts.map +1 -0
- package/dist/tools/mcp/handler.d.ts +7 -3
- package/dist/tools/mcp/handler.d.ts.map +1 -1
- package/dist/tools/mcp/lazy-discovery.d.ts +47 -0
- package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -0
- package/dist/tools/mcp/mount.d.ts +7 -0
- package/dist/tools/mcp/mount.d.ts.map +1 -1
- package/dist/tools/mcp/register.d.ts +2 -2
- package/dist/tools/mcp/register.d.ts.map +1 -1
- package/llms/agent-executor-acp.txt +7 -8
- package/llms/agent-executor-claude-sdk.txt +15 -10
- package/llms/agent-executor-claude.txt +1 -1
- package/llms/agent-executor-codex.txt +13 -3
- package/llms/agent-executor-testing.txt +5 -1
- package/llms/agent-executor.txt +9 -8
- package/llms/stitchkit.txt +74 -74
- package/llms/tools-mcp.txt +3 -2
- package/llms/tools.txt +24 -0
- package/llms/{upgrading-0.128.0.txt → upgrading-0.128.0-0.130.0.txt} +58 -3
- package/llms/upgrading.txt +1 -1
- package/llms-full.txt +206 -107
- package/llms.txt +10 -10
- package/package.json +1 -1
- package/dist/index-0gqs8ght.js +0 -558
|
@@ -1,49 +1,344 @@
|
|
|
1
|
+
import"../../index-09f7w2qq.js";
|
|
2
|
+
import"../../index-v59pxmf1.js";
|
|
3
|
+
import"../../index-qa2jjb65.js";
|
|
4
|
+
import"../../index-6kec3b14.js";
|
|
1
5
|
import"../../index-2rf33y2h.js";
|
|
2
6
|
import {
|
|
3
|
-
|
|
7
|
+
ExecutorModelUsageSchema2,
|
|
8
|
+
PlanLimitsSchema2,
|
|
4
9
|
engineProfile,
|
|
5
10
|
engineEnvironment2
|
|
6
|
-
} from "../../index-
|
|
7
|
-
import"../../index-09f7w2qq.js";
|
|
8
|
-
import"../../index-v59pxmf1.js";
|
|
9
|
-
import"../../index-7kfcb576.js";
|
|
10
|
-
import"../../index-6kec3b14.js";
|
|
11
|
+
} from "../../index-dbp6xemn.js";
|
|
11
12
|
import {
|
|
12
13
|
nonEmptyString,
|
|
13
14
|
createTurnDeltaChannel,
|
|
14
15
|
offerTurnDelta,
|
|
15
16
|
sessionAbort,
|
|
16
17
|
safeJsonValue,
|
|
17
|
-
|
|
18
|
-
|
|
18
|
+
invokeSafely,
|
|
19
|
+
emitStartupPhase,
|
|
19
20
|
holdEngineRequest,
|
|
20
21
|
answerEngineRequest,
|
|
21
22
|
drainEngineRequests,
|
|
22
23
|
endEngineTurn,
|
|
23
24
|
loseEngineTurn
|
|
24
|
-
} from "../../index-
|
|
25
|
+
} from "../../index-2s8sy57y.js";
|
|
25
26
|
import {
|
|
27
|
+
ClaudeTaskUsageSchema2,
|
|
28
|
+
ClaudeRuntimeEventSchema2,
|
|
26
29
|
claudeUserContent,
|
|
30
|
+
resolveClaudePermissionReply,
|
|
27
31
|
newClaudeTurnState,
|
|
28
32
|
classifyClaudeRecord,
|
|
33
|
+
claudeUsagePlanLimits,
|
|
29
34
|
claudePlanWindows2,
|
|
30
35
|
claudeTranscriptPath2,
|
|
31
36
|
claudeTranscriptExists,
|
|
32
37
|
findTranscriptInput
|
|
33
|
-
} from "../../index-
|
|
34
|
-
import"../../index-5ptwb6ka.js";
|
|
38
|
+
} from "../../index-p1qmpq0p.js";
|
|
35
39
|
import {
|
|
40
|
+
validateImageOptions,
|
|
41
|
+
imageTurnStarter
|
|
42
|
+
} from "../../index-y0a4gt1s.js";
|
|
43
|
+
import"../../index-pzhqydxb.js";
|
|
44
|
+
import {
|
|
45
|
+
planLimitsReadFailed2,
|
|
36
46
|
mergeRateLimitEvent2
|
|
37
|
-
} from "../../index-
|
|
47
|
+
} from "../../index-jrn3prgm.js";
|
|
48
|
+
import {
|
|
49
|
+
isPositiveSafeInteger
|
|
50
|
+
} from "../../index-gr0kxymw.js";
|
|
38
51
|
import {
|
|
39
|
-
|
|
52
|
+
assertTimerMs,
|
|
53
|
+
withSignalDeadline
|
|
54
|
+
} from "../../index-agy5fqgf.js";
|
|
55
|
+
import {
|
|
56
|
+
abortReason,
|
|
57
|
+
raceAbort
|
|
40
58
|
} from "../../index-rptj3qnc.js";
|
|
59
|
+
// src/agent-executor/claude-sdk/controls.ts
|
|
60
|
+
function unpublishedClaudeSdkUsageRead(now = new Date) {
|
|
61
|
+
return {
|
|
62
|
+
supported: false,
|
|
63
|
+
planLimits: PlanLimitsSchema2.parse({
|
|
64
|
+
answer: "unpublished",
|
|
65
|
+
windows: [],
|
|
66
|
+
observedAt: now.toISOString()
|
|
67
|
+
})
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function normalizeClaudeSdkUsageRead(raw, recordPlanLimits, now = new Date) {
|
|
71
|
+
const planLimits = claudeUsagePlanLimits(raw, now);
|
|
72
|
+
if (planLimits.answer === "known" || planLimits.answer === "no-plan-limit") {
|
|
73
|
+
recordPlanLimits?.(planLimits);
|
|
74
|
+
}
|
|
75
|
+
return { supported: true, planLimits, raw };
|
|
76
|
+
}
|
|
77
|
+
function requireMethod(query, name) {
|
|
78
|
+
const fn = query[name];
|
|
79
|
+
if (typeof fn !== "function") {
|
|
80
|
+
throw new Error(`The configured Claude SDK query does not support ${String(name)}()`);
|
|
81
|
+
}
|
|
82
|
+
return fn;
|
|
83
|
+
}
|
|
84
|
+
function createClaudeSdkControls(host) {
|
|
85
|
+
const activeQuery = async () => {
|
|
86
|
+
if (host.isClosed())
|
|
87
|
+
throw new Error("The Claude SDK session is closed");
|
|
88
|
+
const active = await raceAbort(host.ensureQuery(), host.signal);
|
|
89
|
+
if (host.isClosed())
|
|
90
|
+
throw new Error("The Claude SDK session is closed");
|
|
91
|
+
return active.query;
|
|
92
|
+
};
|
|
93
|
+
const guarded = (promise) => raceAbort(promise, host.signal);
|
|
94
|
+
return {
|
|
95
|
+
async setModel(model) {
|
|
96
|
+
const query = await activeQuery();
|
|
97
|
+
await guarded(requireMethod(query, "setModel").call(query, model));
|
|
98
|
+
host.setActiveModel(model);
|
|
99
|
+
},
|
|
100
|
+
async setPermissionMode(mode) {
|
|
101
|
+
const query = await activeQuery();
|
|
102
|
+
await guarded(requireMethod(query, "setPermissionMode").call(query, mode));
|
|
103
|
+
host.setActivePermissionMode(mode);
|
|
104
|
+
},
|
|
105
|
+
async applyFlagSettings(settings) {
|
|
106
|
+
const query = await activeQuery();
|
|
107
|
+
await guarded(requireMethod(query, "applyFlagSettings").call(query, settings));
|
|
108
|
+
host.recordFlagSettings(settings);
|
|
109
|
+
},
|
|
110
|
+
async initializationResult() {
|
|
111
|
+
const query = await activeQuery();
|
|
112
|
+
return guarded(requireMethod(query, "initializationResult").call(query));
|
|
113
|
+
},
|
|
114
|
+
async supportedModels() {
|
|
115
|
+
const query = await activeQuery();
|
|
116
|
+
return guarded(requireMethod(query, "supportedModels").call(query));
|
|
117
|
+
},
|
|
118
|
+
async supportedCommands() {
|
|
119
|
+
const query = await activeQuery();
|
|
120
|
+
return guarded(requireMethod(query, "supportedCommands").call(query));
|
|
121
|
+
},
|
|
122
|
+
async accountInfo() {
|
|
123
|
+
const query = await activeQuery();
|
|
124
|
+
return guarded(requireMethod(query, "accountInfo").call(query));
|
|
125
|
+
},
|
|
126
|
+
async getContextUsage(opts) {
|
|
127
|
+
const query = await activeQuery();
|
|
128
|
+
return guarded(requireMethod(query, "getContextUsage").call(query, opts));
|
|
129
|
+
},
|
|
130
|
+
async readUsage(opts) {
|
|
131
|
+
const query = await activeQuery();
|
|
132
|
+
const fn = query.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET;
|
|
133
|
+
if (typeof fn !== "function") {
|
|
134
|
+
return unpublishedClaudeSdkUsageRead();
|
|
135
|
+
}
|
|
136
|
+
let raw;
|
|
137
|
+
try {
|
|
138
|
+
raw = await guarded(fn.call(query, opts));
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (!host.isClosed() && !host.signal.aborted) {
|
|
141
|
+
host.recordPlanLimitsFailure(error);
|
|
142
|
+
}
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
if (host.isClosed())
|
|
146
|
+
throw new Error("The Claude SDK session is closed");
|
|
147
|
+
return normalizeClaudeSdkUsageRead(raw, host.recordPlanLimits);
|
|
148
|
+
},
|
|
149
|
+
async mcpServerStatus() {
|
|
150
|
+
const query = await activeQuery();
|
|
151
|
+
return guarded(requireMethod(query, "mcpServerStatus").call(query));
|
|
152
|
+
},
|
|
153
|
+
async setMcpServers(servers) {
|
|
154
|
+
const query = await activeQuery();
|
|
155
|
+
return guarded(requireMethod(query, "setMcpServers").call(query, servers));
|
|
156
|
+
},
|
|
157
|
+
async toggleMcpServer(serverName, enabled) {
|
|
158
|
+
const query = await activeQuery();
|
|
159
|
+
await guarded(requireMethod(query, "toggleMcpServer").call(query, serverName, enabled));
|
|
160
|
+
},
|
|
161
|
+
async reconnectMcpServer(serverName) {
|
|
162
|
+
const query = await activeQuery();
|
|
163
|
+
await guarded(requireMethod(query, "reconnectMcpServer").call(query, serverName));
|
|
164
|
+
},
|
|
165
|
+
async stopTask(taskId) {
|
|
166
|
+
if (typeof taskId !== "string" || taskId.trim().length === 0) {
|
|
167
|
+
throw new TypeError("Claude SDK stopTask requires a non-empty taskId");
|
|
168
|
+
}
|
|
169
|
+
const query = await activeQuery();
|
|
170
|
+
await guarded(requireMethod(query, "stopTask").call(query, taskId));
|
|
171
|
+
},
|
|
172
|
+
async backgroundTasks(toolUseId) {
|
|
173
|
+
if (toolUseId !== undefined && (typeof toolUseId !== "string" || toolUseId.trim().length === 0)) {
|
|
174
|
+
throw new TypeError("Claude SDK backgroundTasks toolUseId must be a non-empty string when provided");
|
|
175
|
+
}
|
|
176
|
+
const query = await activeQuery();
|
|
177
|
+
return guarded(requireMethod(query, "backgroundTasks").call(query, toolUseId));
|
|
178
|
+
},
|
|
179
|
+
async rewindFiles(userMessageId, options) {
|
|
180
|
+
const query = await activeQuery();
|
|
181
|
+
return guarded(requireMethod(query, "rewindFiles").call(query, userMessageId, options));
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
}
|
|
41
185
|
|
|
42
|
-
// src/agent-executor/claude-sdk/
|
|
186
|
+
// src/agent-executor/claude-sdk/query-loop.ts
|
|
43
187
|
import { randomUUID } from "node:crypto";
|
|
44
|
-
|
|
45
|
-
|
|
188
|
+
|
|
189
|
+
// src/agent-executor/claude-sdk/turn-usage.ts
|
|
190
|
+
import { z } from "zod";
|
|
191
|
+
var MAX_MODEL_USAGE_ENTRIES = 64;
|
|
192
|
+
var ClaudeSdkTokenPairSchema = z.strictObject({
|
|
193
|
+
inputTokens: z.int().nonnegative(),
|
|
194
|
+
outputTokens: z.int().nonnegative()
|
|
195
|
+
});
|
|
196
|
+
var ClaudeSdkTurnUsageSchema = z.strictObject({
|
|
197
|
+
turnId: z.string().min(1),
|
|
198
|
+
primaryModel: z.string().min(1).max(256).optional(),
|
|
199
|
+
modelUsageDelta: z.record(z.string().min(1).max(256), ExecutorModelUsageSchema2).refine((entries) => Object.keys(entries).length <= MAX_MODEL_USAGE_ENTRIES, `modelUsageDelta must carry at most ${MAX_MODEL_USAGE_ENTRIES} models`).optional(),
|
|
200
|
+
otherUsage: ClaudeSdkTokenPairSchema.optional(),
|
|
201
|
+
cumulativeModelUsage: z.record(z.string().min(1).max(256), ExecutorModelUsageSchema2).refine((entries) => Object.keys(entries).length <= MAX_MODEL_USAGE_ENTRIES, `cumulativeModelUsage must carry at most ${MAX_MODEL_USAGE_ENTRIES} models`).optional()
|
|
202
|
+
});
|
|
203
|
+
function diffOptionalCounter(before, after, isNewModel) {
|
|
204
|
+
if (isNewModel)
|
|
205
|
+
return { ok: true, value: after };
|
|
206
|
+
if (before === undefined) {
|
|
207
|
+
return { ok: true, value: undefined };
|
|
208
|
+
}
|
|
209
|
+
if (after === undefined || after < before)
|
|
210
|
+
return { ok: false, value: undefined };
|
|
211
|
+
return { ok: true, value: after - before };
|
|
212
|
+
}
|
|
213
|
+
function diffModelRow(before, after) {
|
|
214
|
+
const isNewModel = before === undefined;
|
|
215
|
+
const baseInput = isNewModel ? 0 : before.inputTokens;
|
|
216
|
+
const baseOutput = isNewModel ? 0 : before.outputTokens;
|
|
217
|
+
if (after.inputTokens < baseInput || after.outputTokens < baseOutput)
|
|
218
|
+
return;
|
|
219
|
+
const cacheRead = diffOptionalCounter(before?.cacheReadInputTokens, after.cacheReadInputTokens, isNewModel);
|
|
220
|
+
const cacheCreate = diffOptionalCounter(before?.cacheCreationInputTokens, after.cacheCreationInputTokens, isNewModel);
|
|
221
|
+
const thinking = diffOptionalCounter(before?.thinkingTokens, after.thinkingTokens, isNewModel);
|
|
222
|
+
const cache5m = diffOptionalCounter(before?.cacheCreationEphemeral5mInputTokens, after.cacheCreationEphemeral5mInputTokens, isNewModel);
|
|
223
|
+
const cache1h = diffOptionalCounter(before?.cacheCreationEphemeral1hInputTokens, after.cacheCreationEphemeral1hInputTokens, isNewModel);
|
|
224
|
+
const webSearch = diffOptionalCounter(before?.webSearchRequests, after.webSearchRequests, isNewModel);
|
|
225
|
+
const cost = diffOptionalCounter(before?.costUsd, after.costUsd, isNewModel);
|
|
226
|
+
if (!cacheRead.ok || !cacheCreate.ok || !thinking.ok || !cache5m.ok || !cache1h.ok || !webSearch.ok || !cost.ok) {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const inputDelta = after.inputTokens - baseInput;
|
|
230
|
+
const outputDelta = after.outputTokens - baseOutput;
|
|
231
|
+
const missingCacheBaseline = !isNewModel && before.cacheReadInputTokens === undefined && after.cacheReadInputTokens !== undefined || !isNewModel && before.cacheCreationInputTokens === undefined && after.cacheCreationInputTokens !== undefined;
|
|
232
|
+
const ledgerInput = missingCacheBaseline ? undefined : inputDelta + (cacheRead.value ?? 0) + (cacheCreate.value ?? 0);
|
|
233
|
+
return {
|
|
234
|
+
ledgerInput,
|
|
235
|
+
row: {
|
|
236
|
+
inputTokens: inputDelta,
|
|
237
|
+
outputTokens: outputDelta,
|
|
238
|
+
...cacheRead.value !== undefined && { cacheReadInputTokens: cacheRead.value },
|
|
239
|
+
...cacheCreate.value !== undefined && { cacheCreationInputTokens: cacheCreate.value },
|
|
240
|
+
...thinking.value !== undefined && { thinkingTokens: thinking.value },
|
|
241
|
+
...cache5m.value !== undefined && {
|
|
242
|
+
cacheCreationEphemeral5mInputTokens: cache5m.value
|
|
243
|
+
},
|
|
244
|
+
...cache1h.value !== undefined && {
|
|
245
|
+
cacheCreationEphemeral1hInputTokens: cache1h.value
|
|
246
|
+
},
|
|
247
|
+
...webSearch.value !== undefined && { webSearchRequests: webSearch.value },
|
|
248
|
+
...cost.value !== undefined && { costUsd: cost.value },
|
|
249
|
+
...after.contextWindow !== undefined && { contextWindow: after.contextWindow },
|
|
250
|
+
...after.maxOutputTokens !== undefined && { maxOutputTokens: after.maxOutputTokens },
|
|
251
|
+
...after.canonicalModel !== undefined && { canonicalModel: after.canonicalModel },
|
|
252
|
+
...after.provider !== undefined && { provider: after.provider },
|
|
253
|
+
...after.costBasis !== undefined && { costBasis: after.costBasis }
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
function computeDeltaMap(baseline, current) {
|
|
258
|
+
for (const model of baseline.keys()) {
|
|
259
|
+
if (!Object.hasOwn(current, model))
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
const deltaEntries = new Map;
|
|
263
|
+
let totalLedgerInput = 0;
|
|
264
|
+
let totalLedgerOutput = 0;
|
|
265
|
+
let hasCompleteLedgerInput = true;
|
|
266
|
+
for (const [model, after] of Object.entries(current)) {
|
|
267
|
+
const diff = diffModelRow(baseline.get(model), after);
|
|
268
|
+
if (diff === undefined)
|
|
269
|
+
return;
|
|
270
|
+
deltaEntries.set(model, diff.row);
|
|
271
|
+
if (diff.ledgerInput === undefined)
|
|
272
|
+
hasCompleteLedgerInput = false;
|
|
273
|
+
else
|
|
274
|
+
totalLedgerInput += diff.ledgerInput;
|
|
275
|
+
totalLedgerOutput += diff.row.outputTokens;
|
|
276
|
+
}
|
|
277
|
+
return {
|
|
278
|
+
modelUsageDelta: Object.fromEntries(deltaEntries),
|
|
279
|
+
ledgerTotals: hasCompleteLedgerInput ? { inputTokens: totalLedgerInput, outputTokens: totalLedgerOutput } : undefined
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
function computeOtherUsage(ledgerTotals, usageDelta) {
|
|
283
|
+
if (ledgerTotals === undefined || usageDelta === undefined)
|
|
284
|
+
return;
|
|
285
|
+
if (usageDelta.inputTokens === undefined || usageDelta.outputTokens === undefined) {
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const mainInput = usageDelta.inputTokens + (usageDelta.cachedInputTokens ?? 0) + (usageDelta.cacheCreationInputTokens ?? 0);
|
|
289
|
+
const mainOutput = usageDelta.outputTokens;
|
|
290
|
+
if (ledgerTotals.inputTokens < mainInput || ledgerTotals.outputTokens < mainOutput) {
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
return {
|
|
294
|
+
inputTokens: ledgerTotals.inputTokens - mainInput,
|
|
295
|
+
outputTokens: ledgerTotals.outputTokens - mainOutput
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
function createClaudeSdkTurnUsageTracker() {
|
|
299
|
+
let baseline = new Map;
|
|
300
|
+
return {
|
|
301
|
+
recordTurn({ turnId, primaryModel, usageDelta }) {
|
|
302
|
+
const cumulative = usageDelta?.modelUsage;
|
|
303
|
+
if (cumulative === undefined || Object.keys(cumulative).length === 0) {
|
|
304
|
+
baseline = undefined;
|
|
305
|
+
return {
|
|
306
|
+
turnId,
|
|
307
|
+
...primaryModel !== undefined && { primaryModel }
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
const nextSnapshot = new Map(Object.entries(cumulative));
|
|
311
|
+
if (baseline === undefined) {
|
|
312
|
+
baseline = nextSnapshot;
|
|
313
|
+
return {
|
|
314
|
+
turnId,
|
|
315
|
+
...primaryModel !== undefined && { primaryModel },
|
|
316
|
+
cumulativeModelUsage: cumulative
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
const computed = computeDeltaMap(baseline, cumulative);
|
|
320
|
+
if (computed === undefined) {
|
|
321
|
+
baseline = undefined;
|
|
322
|
+
return {
|
|
323
|
+
turnId,
|
|
324
|
+
...primaryModel !== undefined && { primaryModel },
|
|
325
|
+
cumulativeModelUsage: cumulative
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
baseline = nextSnapshot;
|
|
329
|
+
const otherUsage = computeOtherUsage(computed.ledgerTotals, usageDelta);
|
|
330
|
+
return {
|
|
331
|
+
turnId,
|
|
332
|
+
...primaryModel !== undefined && { primaryModel },
|
|
333
|
+
modelUsageDelta: computed.modelUsageDelta,
|
|
334
|
+
...otherUsage !== undefined && { otherUsage },
|
|
335
|
+
cumulativeModelUsage: cumulative
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
};
|
|
46
339
|
}
|
|
340
|
+
|
|
341
|
+
// src/agent-executor/claude-sdk/query-loop.ts
|
|
47
342
|
var SDK_ANSWER = { source: "claude-sdk", type: "PermissionResult" };
|
|
48
343
|
var stoppedPermission = (message) => () => ({
|
|
49
344
|
behavior: "deny",
|
|
@@ -51,14 +346,7 @@ var stoppedPermission = (message) => () => ({
|
|
|
51
346
|
interrupt: true
|
|
52
347
|
});
|
|
53
348
|
function closeQuerySafely(query) {
|
|
54
|
-
|
|
55
|
-
const closing = query?.close?.();
|
|
56
|
-
if (typeof closing === "object" && closing !== null && "then" in closing && typeof closing.then === "function") {
|
|
57
|
-
Promise.resolve(closing).catch(() => {
|
|
58
|
-
return;
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
} catch {}
|
|
349
|
+
invokeSafely(() => query?.close?.());
|
|
62
350
|
}
|
|
63
351
|
function pushablePrompt() {
|
|
64
352
|
const queue = [];
|
|
@@ -110,26 +398,69 @@ function createSdkCanUseTool(state) {
|
|
|
110
398
|
});
|
|
111
399
|
};
|
|
112
400
|
const callId = nonEmptyString(options.toolUseID);
|
|
401
|
+
const rawToolName = nonEmptyString(toolName);
|
|
402
|
+
let safeInputSnapshot;
|
|
113
403
|
holdEngineRequest(turn, {
|
|
114
404
|
interactionId,
|
|
115
|
-
detail: {
|
|
405
|
+
detail: {
|
|
406
|
+
input: toolInput,
|
|
407
|
+
toolName: rawToolName,
|
|
408
|
+
suppressSessionRule: options.suppressAlwaysAllowRule === true
|
|
409
|
+
},
|
|
116
410
|
answeredBy: SDK_ANSWER,
|
|
117
|
-
delta: () =>
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
411
|
+
delta: () => {
|
|
412
|
+
const safeInput = safeJsonValue(toolInput);
|
|
413
|
+
if (typeof safeInput === "object" && safeInput !== null && !Array.isArray(safeInput)) {
|
|
414
|
+
safeInputSnapshot = safeInput;
|
|
415
|
+
}
|
|
416
|
+
return {
|
|
417
|
+
type: "request",
|
|
418
|
+
turnId: turn.state.turnId,
|
|
419
|
+
itemId: `request:${interactionId}`,
|
|
420
|
+
raw: { source: "claude-sdk", type: "canUseTool" },
|
|
421
|
+
interactionId,
|
|
422
|
+
kind: "approval",
|
|
423
|
+
toolName: rawToolName ?? "tool",
|
|
424
|
+
...callId !== undefined && { callId },
|
|
425
|
+
input: safeInput
|
|
426
|
+
};
|
|
427
|
+
},
|
|
128
428
|
refusal: { behavior: "deny", message: "The turn was interrupted", interrupt: true },
|
|
129
429
|
resolve: finish
|
|
130
430
|
});
|
|
131
|
-
if (turn.pending.has(interactionId))
|
|
431
|
+
if (turn.pending.has(interactionId)) {
|
|
132
432
|
options.signal.addEventListener("abort", onToolAbort, { once: true });
|
|
433
|
+
if (state.onPermissionRequest !== undefined) {
|
|
434
|
+
const meta = {
|
|
435
|
+
turnId: turn.state.turnId,
|
|
436
|
+
interactionId,
|
|
437
|
+
toolName,
|
|
438
|
+
input: safeInputSnapshot ?? {},
|
|
439
|
+
toolUseID: options.toolUseID,
|
|
440
|
+
...options.requestId !== undefined && { requestId: options.requestId },
|
|
441
|
+
...options.decisionReason !== undefined && {
|
|
442
|
+
decisionReason: options.decisionReason
|
|
443
|
+
},
|
|
444
|
+
...options.blockedPath !== undefined && { blockedPath: options.blockedPath },
|
|
445
|
+
...options.title !== undefined && { title: options.title },
|
|
446
|
+
...options.displayName !== undefined && { displayName: options.displayName },
|
|
447
|
+
...options.description !== undefined && { description: options.description },
|
|
448
|
+
...options.suggestions !== undefined && {
|
|
449
|
+
suggestions: [...options.suggestions]
|
|
450
|
+
},
|
|
451
|
+
...options.agentID !== undefined && { agentID: options.agentID },
|
|
452
|
+
...options.mcpServer !== undefined && { mcpServer: { ...options.mcpServer } },
|
|
453
|
+
...options.defaultToNo !== undefined && { defaultToNo: options.defaultToNo },
|
|
454
|
+
...options.suppressAlwaysAllowRule !== undefined && {
|
|
455
|
+
suppressAlwaysAllowRule: options.suppressAlwaysAllowRule
|
|
456
|
+
},
|
|
457
|
+
...options.matchedAskRule !== undefined && {
|
|
458
|
+
matchedAskRule: { ...options.matchedAskRule }
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
invokeSafely(() => state.onPermissionRequest?.(meta));
|
|
462
|
+
}
|
|
463
|
+
}
|
|
133
464
|
});
|
|
134
465
|
}
|
|
135
466
|
function sdkTurnHandle(turn, query) {
|
|
@@ -141,149 +472,725 @@ function sdkTurnHandle(turn, query) {
|
|
|
141
472
|
await query.interrupt();
|
|
142
473
|
},
|
|
143
474
|
async respond(interactionId, rawReply) {
|
|
144
|
-
const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
|
|
145
475
|
const waiting = turn.pending.get(interactionId);
|
|
146
|
-
if (waiting === undefined)
|
|
476
|
+
if (waiting === undefined) {
|
|
147
477
|
throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
|
|
148
|
-
if (reply.kind === "input") {
|
|
149
|
-
throw new TypeError("A Claude permission request is approved or denied, not answered with input");
|
|
150
478
|
}
|
|
151
|
-
|
|
479
|
+
const decision = resolveClaudePermissionReply(waiting.detail, rawReply);
|
|
480
|
+
if (decision.behavior === "allow") {
|
|
481
|
+
answerEngineRequest(turn, interactionId, {
|
|
482
|
+
behavior: "allow",
|
|
483
|
+
updatedInput: decision.input,
|
|
484
|
+
...decision.updatedPermissions !== undefined && {
|
|
485
|
+
updatedPermissions: decision.updatedPermissions.map((rule) => ({
|
|
486
|
+
type: rule.type,
|
|
487
|
+
rules: rule.rules.map((entry) => ({ toolName: entry.toolName })),
|
|
488
|
+
behavior: rule.behavior,
|
|
489
|
+
destination: rule.destination
|
|
490
|
+
}))
|
|
491
|
+
}
|
|
492
|
+
});
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
answerEngineRequest(turn, interactionId, decision);
|
|
152
496
|
}
|
|
153
497
|
};
|
|
154
498
|
}
|
|
155
|
-
|
|
156
|
-
const
|
|
499
|
+
function runSdkQueryLoop(input) {
|
|
500
|
+
const turnUsageTracker = createClaudeSdkTurnUsageTracker();
|
|
501
|
+
let sessionModel;
|
|
502
|
+
(async () => {
|
|
503
|
+
try {
|
|
504
|
+
for await (const record of input.handle.query) {
|
|
505
|
+
const turn = input.getTurn();
|
|
506
|
+
const verdict = classifyClaudeRecord(record, turn?.state ?? newClaudeTurnState("between-turns"));
|
|
507
|
+
if (verdict.kind === "session") {
|
|
508
|
+
if (verdict.model !== undefined)
|
|
509
|
+
sessionModel = verdict.model;
|
|
510
|
+
} else if (verdict.kind === "limits") {
|
|
511
|
+
input.limits.set(input.profileId, mergeRateLimitEvent2({
|
|
512
|
+
previous: input.limits.get(input.profileId),
|
|
513
|
+
windows: claudePlanWindows2(verdict.info),
|
|
514
|
+
now: new Date
|
|
515
|
+
}));
|
|
516
|
+
} else if (verdict.kind === "event") {
|
|
517
|
+
if (input.onEvent !== undefined) {
|
|
518
|
+
invokeSafely(() => input.onEvent?.(verdict.event));
|
|
519
|
+
}
|
|
520
|
+
} else if (verdict.kind === "deltas") {
|
|
521
|
+
for (const delta of verdict.deltas)
|
|
522
|
+
offerTurnDelta(turn?.channel, delta);
|
|
523
|
+
} else if (verdict.kind === "end") {
|
|
524
|
+
const usageDelta = verdict.deltas.find((delta) => delta.type === "usage");
|
|
525
|
+
const primaryModel = turn?.state.primaryModel ?? sessionModel;
|
|
526
|
+
const summary = turnUsageTracker.recordTurn({
|
|
527
|
+
turnId: turn?.state.turnId ?? "between-turns",
|
|
528
|
+
...primaryModel !== undefined && { primaryModel },
|
|
529
|
+
...usageDelta?.type === "usage" && { usageDelta }
|
|
530
|
+
});
|
|
531
|
+
if (turn !== undefined && input.onTurnUsage !== undefined) {
|
|
532
|
+
invokeSafely(() => input.onTurnUsage?.(summary));
|
|
533
|
+
}
|
|
534
|
+
endEngineTurn(turn, stoppedPermission("The turn ended"), verdict.deltas);
|
|
535
|
+
input.clearTurn();
|
|
536
|
+
} else if (verdict.kind === "unhandled") {
|
|
537
|
+
offerTurnDelta(turn?.channel, verdict.delta);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
throw new Error(input.getTurn() !== undefined ? "The Agent SDK query ended during the turn" : "The Agent SDK query ended while idle");
|
|
541
|
+
} catch (error) {
|
|
542
|
+
input.onExit(input.handle, error);
|
|
543
|
+
}
|
|
544
|
+
})();
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// src/agent-executor/claude-sdk/probe.ts
|
|
548
|
+
var DEFAULT_PROBE_TIMEOUT_MS = 30000;
|
|
549
|
+
function createNeverYieldingPrompt(signal) {
|
|
550
|
+
return {
|
|
551
|
+
[Symbol.asyncIterator]() {
|
|
552
|
+
return {
|
|
553
|
+
next() {
|
|
554
|
+
if (signal.aborted) {
|
|
555
|
+
return Promise.resolve({ value: undefined, done: true });
|
|
556
|
+
}
|
|
557
|
+
return new Promise((resolve) => {
|
|
558
|
+
signal.addEventListener("abort", () => resolve({ value: undefined, done: true }), {
|
|
559
|
+
once: true
|
|
560
|
+
});
|
|
561
|
+
});
|
|
562
|
+
},
|
|
563
|
+
return() {
|
|
564
|
+
return Promise.resolve({ value: undefined, done: true });
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
function buildProbeOptions(input) {
|
|
571
|
+
const { config } = input;
|
|
572
|
+
return {
|
|
573
|
+
cwd: input.cwd,
|
|
574
|
+
env: input.env,
|
|
575
|
+
abortController: input.abortController,
|
|
576
|
+
persistSession: false,
|
|
577
|
+
settings: { disableAllHooks: true },
|
|
578
|
+
strictMcpConfig: true,
|
|
579
|
+
mcpServers: {},
|
|
580
|
+
allowedTools: [],
|
|
581
|
+
canUseTool: async () => ({
|
|
582
|
+
behavior: "deny",
|
|
583
|
+
message: "Capability probe does not execute tools",
|
|
584
|
+
interrupt: true
|
|
585
|
+
}),
|
|
586
|
+
...config.pathToClaudeCodeExecutable !== undefined && {
|
|
587
|
+
pathToClaudeCodeExecutable: config.pathToClaudeCodeExecutable
|
|
588
|
+
},
|
|
589
|
+
...config.settingSources !== undefined && { settingSources: config.settingSources },
|
|
590
|
+
...config.extraArgs !== undefined && { extraArgs: config.extraArgs },
|
|
591
|
+
...config.stderr !== undefined && { stderr: config.stderr },
|
|
592
|
+
...config.spawnClaudeCodeProcess !== undefined && {
|
|
593
|
+
spawnClaudeCodeProcess: config.spawnClaudeCodeProcess
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
async function probeClaudeSdkCapabilities(config, limits, input) {
|
|
157
598
|
const profile = engineProfile("claude-sdk", input.profile);
|
|
599
|
+
if (input.timeoutMs !== undefined) {
|
|
600
|
+
assertTimerMs("timeoutMs", input.timeoutMs);
|
|
601
|
+
}
|
|
158
602
|
input.signal?.throwIfAborted();
|
|
159
|
-
const
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
603
|
+
const timeoutMs = input.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
|
|
604
|
+
const ambient = config.ambient ?? process.env;
|
|
605
|
+
const env = engineEnvironment2(profile, ambient);
|
|
606
|
+
return withSignalDeadline(timeoutMs, input.signal, () => new Error(`Claude SDK capability probe timed out after ${timeoutMs} ms`), async (deadlineSignal) => {
|
|
607
|
+
const probeAbort = new AbortController;
|
|
608
|
+
const onDeadlineAbort = () => probeAbort.abort(deadlineSignal.reason);
|
|
609
|
+
if (deadlineSignal.aborted) {
|
|
610
|
+
onDeadlineAbort();
|
|
611
|
+
} else {
|
|
612
|
+
deadlineSignal.addEventListener("abort", onDeadlineAbort, { once: true });
|
|
613
|
+
}
|
|
614
|
+
let query;
|
|
615
|
+
try {
|
|
616
|
+
query = config.query({
|
|
617
|
+
prompt: createNeverYieldingPrompt(probeAbort.signal),
|
|
618
|
+
options: buildProbeOptions({
|
|
619
|
+
config,
|
|
620
|
+
cwd: input.cwd,
|
|
621
|
+
env,
|
|
622
|
+
abortController: probeAbort
|
|
623
|
+
})
|
|
624
|
+
});
|
|
625
|
+
const initFn = query.initializationResult;
|
|
626
|
+
const modelsFn = query.supportedModels;
|
|
627
|
+
const commandsFn = query.supportedCommands;
|
|
628
|
+
const accountFn = query.accountInfo;
|
|
629
|
+
if (typeof initFn !== "function" && typeof modelsFn !== "function" && typeof commandsFn !== "function" && typeof accountFn !== "function") {
|
|
630
|
+
throw new Error("The configured Claude SDK query does not expose capability probe RPCs");
|
|
631
|
+
}
|
|
632
|
+
const initializationResult = typeof initFn === "function" ? await raceAbort(initFn.call(query), deadlineSignal) : undefined;
|
|
633
|
+
const usageFn = input.includeUsage === true ? query.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET : undefined;
|
|
634
|
+
const [models, commands, account, rawUsage] = await Promise.all([
|
|
635
|
+
typeof modelsFn === "function" ? raceAbort(modelsFn.call(query), deadlineSignal) : Promise.resolve(initializationResult?.models),
|
|
636
|
+
typeof commandsFn === "function" ? raceAbort(commandsFn.call(query), deadlineSignal) : Promise.resolve(initializationResult?.commands),
|
|
637
|
+
typeof accountFn === "function" ? raceAbort(accountFn.call(query), deadlineSignal) : Promise.resolve(initializationResult?.account),
|
|
638
|
+
typeof usageFn === "function" ? raceAbort(usageFn.call(query, { skipBehaviors: true }), deadlineSignal) : Promise.resolve(undefined)
|
|
639
|
+
]);
|
|
640
|
+
let usage;
|
|
641
|
+
if (input.includeUsage === true) {
|
|
642
|
+
usage = typeof usageFn === "function" && rawUsage !== undefined ? normalizeClaudeSdkUsageRead(rawUsage, (planLimits) => {
|
|
643
|
+
limits.set(profile.profileId, planLimits);
|
|
644
|
+
}) : unpublishedClaudeSdkUsageRead();
|
|
196
645
|
}
|
|
646
|
+
return {
|
|
647
|
+
...initializationResult !== undefined && { initializationResult },
|
|
648
|
+
...models !== undefined && { models },
|
|
649
|
+
...commands !== undefined && { commands },
|
|
650
|
+
...account !== undefined && { account },
|
|
651
|
+
...usage !== undefined && { usage }
|
|
652
|
+
};
|
|
653
|
+
} finally {
|
|
654
|
+
deadlineSignal.removeEventListener("abort", onDeadlineAbort);
|
|
655
|
+
if (!probeAbort.signal.aborted)
|
|
656
|
+
probeAbort.abort();
|
|
657
|
+
closeQuerySafely(query);
|
|
658
|
+
}
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// src/agent-executor/claude-sdk/query-options.ts
|
|
663
|
+
import { spawn } from "node:child_process";
|
|
664
|
+
import { StringDecoder } from "node:string_decoder";
|
|
665
|
+
var DEFAULT_DELEGATION_TIMEOUT_MS = 30000;
|
|
666
|
+
var FLAG_SETTINGS_REPLAY_TIMEOUT_MS = 30000;
|
|
667
|
+
function validateClaudeSdkConfig(config) {
|
|
668
|
+
validateImageOptions(config);
|
|
669
|
+
if (config.supportedDialogKinds !== undefined && config.supportedDialogKinds.length > 0 && config.onUserDialog === undefined) {
|
|
670
|
+
throw new TypeError("ClaudeSdkDriverConfig.supportedDialogKinds requires onUserDialog when non-empty");
|
|
671
|
+
}
|
|
672
|
+
if (config.verifyDelegation?.timeoutMs !== undefined) {
|
|
673
|
+
assertTimerMs("verifyDelegation.timeoutMs", config.verifyDelegation.timeoutMs);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
function hasDelegationVerification(check) {
|
|
677
|
+
return check?.requireHooksApplied === true || check?.requireNoMcpServers === true;
|
|
678
|
+
}
|
|
679
|
+
function readPositivePid(spawned) {
|
|
680
|
+
if (typeof spawned !== "object" || spawned === null)
|
|
681
|
+
return;
|
|
682
|
+
const raw = Reflect.get(spawned, "pid");
|
|
683
|
+
return isPositiveSafeInteger(raw) ? raw : undefined;
|
|
684
|
+
}
|
|
685
|
+
function createDefaultSpawner(stderrCallback) {
|
|
686
|
+
return (opts) => {
|
|
687
|
+
const child = spawn(opts.command, opts.args, {
|
|
688
|
+
cwd: opts.cwd,
|
|
689
|
+
env: opts.env,
|
|
690
|
+
signal: opts.signal,
|
|
691
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
692
|
+
shell: false,
|
|
693
|
+
windowsHide: true
|
|
197
694
|
});
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
695
|
+
if (child.stderr !== null) {
|
|
696
|
+
const decoder = new StringDecoder("utf8");
|
|
697
|
+
const emit = (text) => {
|
|
698
|
+
if (text.length === 0 || stderrCallback === undefined)
|
|
699
|
+
return;
|
|
700
|
+
try {
|
|
701
|
+
stderrCallback(text);
|
|
702
|
+
} catch {}
|
|
703
|
+
};
|
|
704
|
+
child.stderr.on("error", () => {
|
|
201
705
|
return;
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
706
|
+
});
|
|
707
|
+
child.stderr.on("data", (chunk) => {
|
|
708
|
+
emit(typeof chunk === "string" ? chunk : decoder.write(chunk));
|
|
709
|
+
});
|
|
710
|
+
child.stderr.on("end", () => {
|
|
711
|
+
emit(decoder.end());
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
return child;
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
function buildSpawnHook(config, recordPid, onPidExit) {
|
|
718
|
+
if (config.spawnClaudeCodeProcess === undefined && config.onProviderPid === undefined) {
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
const baseSpawner = config.spawnClaudeCodeProcess ?? createDefaultSpawner(config.stderr);
|
|
722
|
+
return (spawnOpts) => {
|
|
723
|
+
const proc = baseSpawner(spawnOpts);
|
|
724
|
+
const pid = readPositivePid(proc);
|
|
725
|
+
recordPid(pid);
|
|
726
|
+
if (pid !== undefined && typeof proc.once === "function") {
|
|
727
|
+
proc.once("exit", () => onPidExit(pid));
|
|
728
|
+
}
|
|
729
|
+
if (pid !== undefined && config.onProviderPid !== undefined) {
|
|
210
730
|
try {
|
|
211
|
-
|
|
212
|
-
const turn = current;
|
|
213
|
-
const verdict = classifyClaudeRecord(record, turn?.state ?? newClaudeTurnState("between-turns"));
|
|
214
|
-
if (verdict.kind === "limits") {
|
|
215
|
-
limits.set(profile.profileId, mergeRateLimitEvent2({
|
|
216
|
-
previous: limits.get(profile.profileId),
|
|
217
|
-
windows: claudePlanWindows2(verdict.info),
|
|
218
|
-
now: new Date
|
|
219
|
-
}));
|
|
220
|
-
} else if (verdict.kind === "deltas") {
|
|
221
|
-
for (const delta of verdict.deltas)
|
|
222
|
-
offerTurnDelta(turn?.channel, delta);
|
|
223
|
-
} else if (verdict.kind === "end") {
|
|
224
|
-
endEngineTurn(turn, stoppedPermission("The turn ended"), verdict.deltas);
|
|
225
|
-
current = undefined;
|
|
226
|
-
} else if (verdict.kind === "unhandled") {
|
|
227
|
-
offerTurnDelta(turn?.channel, verdict.delta);
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
throw new Error("The Agent SDK query ended during the turn");
|
|
731
|
+
config.onProviderPid(pid);
|
|
231
732
|
} catch (error) {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
}
|
|
238
|
-
loseEngineTurn(turn, stoppedPermission("The Claude SDK query ended"), error);
|
|
239
|
-
closeHandle();
|
|
733
|
+
try {
|
|
734
|
+
proc.kill("SIGTERM");
|
|
735
|
+
} catch {}
|
|
736
|
+
recordPid(undefined);
|
|
737
|
+
throw error;
|
|
240
738
|
}
|
|
241
|
-
}
|
|
242
|
-
return
|
|
739
|
+
}
|
|
740
|
+
return proc;
|
|
243
741
|
};
|
|
244
|
-
|
|
742
|
+
}
|
|
743
|
+
function buildClaudeSdkQueryOptions(input) {
|
|
744
|
+
const { config } = input;
|
|
745
|
+
const spawnHook = buildSpawnHook(config, input.recordPid, input.onPidExit);
|
|
746
|
+
return {
|
|
747
|
+
cwd: input.cwd,
|
|
748
|
+
env: input.env,
|
|
749
|
+
includePartialMessages: true,
|
|
750
|
+
permissionMode: input.activePermissionMode,
|
|
751
|
+
canUseTool: input.canUseTool,
|
|
752
|
+
...input.activeModel !== undefined && { model: input.activeModel },
|
|
753
|
+
...config.allowDangerouslySkipPermissions !== undefined && {
|
|
754
|
+
allowDangerouslySkipPermissions: config.allowDangerouslySkipPermissions
|
|
755
|
+
},
|
|
756
|
+
...config.pathToClaudeCodeExecutable !== undefined && {
|
|
757
|
+
pathToClaudeCodeExecutable: config.pathToClaudeCodeExecutable
|
|
758
|
+
},
|
|
759
|
+
...config.systemPrompt !== undefined && { systemPrompt: config.systemPrompt },
|
|
760
|
+
...config.settingSources !== undefined && { settingSources: config.settingSources },
|
|
761
|
+
...config.enableFileCheckpointing !== undefined && {
|
|
762
|
+
enableFileCheckpointing: config.enableFileCheckpointing
|
|
763
|
+
},
|
|
764
|
+
...config.supportedDialogKinds !== undefined && {
|
|
765
|
+
supportedDialogKinds: [...config.supportedDialogKinds]
|
|
766
|
+
},
|
|
767
|
+
...config.onUserDialog !== undefined && { onUserDialog: config.onUserDialog },
|
|
768
|
+
...config.onElicitation !== undefined && { onElicitation: config.onElicitation },
|
|
769
|
+
...config.hooks !== undefined && { hooks: config.hooks },
|
|
770
|
+
...config.tools !== undefined && { tools: config.tools },
|
|
771
|
+
...config.allowedTools !== undefined && { allowedTools: config.allowedTools },
|
|
772
|
+
...config.disallowedTools !== undefined && { disallowedTools: config.disallowedTools },
|
|
773
|
+
...config.mcpServers !== undefined && { mcpServers: config.mcpServers },
|
|
774
|
+
...config.mcpServersDelivery !== undefined && {
|
|
775
|
+
mcpServersDelivery: config.mcpServersDelivery
|
|
776
|
+
},
|
|
777
|
+
...config.strictMcpConfig !== undefined && { strictMcpConfig: config.strictMcpConfig },
|
|
778
|
+
...config.plugins !== undefined && { plugins: config.plugins },
|
|
779
|
+
...config.agents !== undefined && { agents: config.agents },
|
|
780
|
+
...config.extraArgs !== undefined && { extraArgs: config.extraArgs },
|
|
781
|
+
...config.stderr !== undefined && { stderr: config.stderr },
|
|
782
|
+
...spawnHook !== undefined && { spawnClaudeCodeProcess: spawnHook },
|
|
783
|
+
...input.resume ? {
|
|
784
|
+
resume: input.sessionId,
|
|
785
|
+
...input.resumeSessionAt !== undefined && {
|
|
786
|
+
resumeSessionAt: input.resumeSessionAt
|
|
787
|
+
},
|
|
788
|
+
...input.resumeDropsTurn !== undefined && {
|
|
789
|
+
resumeDropsTurn: input.resumeDropsTurn
|
|
790
|
+
}
|
|
791
|
+
} : { sessionId: input.sessionId }
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
async function verifyClaudeSdkDelegation(query, check, signal) {
|
|
795
|
+
const timeoutMs = check.timeoutMs ?? DEFAULT_DELEGATION_TIMEOUT_MS;
|
|
796
|
+
await withSignalDeadline(timeoutMs, signal, () => new Error(`Claude SDK delegation verification timed out after ${timeoutMs} ms`), async (deadlineSignal) => {
|
|
797
|
+
if (check.requireHooksApplied === true) {
|
|
798
|
+
if (typeof query.initializationResult !== "function") {
|
|
799
|
+
throw new Error("Claude SDK delegation verification requires query.initializationResult()");
|
|
800
|
+
}
|
|
801
|
+
const initialized = await raceAbort(query.initializationResult(), deadlineSignal);
|
|
802
|
+
if (typeof initialized !== "object" || initialized === null || Reflect.get(initialized, "hooks_applied") !== true) {
|
|
803
|
+
throw new Error("Claude SDK did not acknowledge delegation hooks (initializationResult().hooks_applied !== true)");
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
if (check.requireNoMcpServers === true) {
|
|
807
|
+
if (typeof query.mcpServerStatus !== "function") {
|
|
808
|
+
throw new Error("Claude SDK delegation verification requires query.mcpServerStatus()");
|
|
809
|
+
}
|
|
810
|
+
const servers = await raceAbort(query.mcpServerStatus(), deadlineSignal);
|
|
811
|
+
if (!Array.isArray(servers)) {
|
|
812
|
+
throw new Error("Claude SDK delegation verification refused non-array mcpServerStatus() response");
|
|
813
|
+
}
|
|
814
|
+
if (servers.length > 0) {
|
|
815
|
+
throw new Error(`Claude SDK exposed ${servers.length} MCP server(s) under delegated policy`);
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
async function replayClaudeSdkFlagSettings(query, overlay, signal) {
|
|
821
|
+
if (typeof query.applyFlagSettings !== "function") {
|
|
822
|
+
throw new Error("Claude SDK cannot replay flag settings on restart: query does not support applyFlagSettings()");
|
|
823
|
+
}
|
|
824
|
+
const applySettings = query.applyFlagSettings.bind(query);
|
|
825
|
+
await withSignalDeadline(FLAG_SETTINGS_REPLAY_TIMEOUT_MS, signal, () => new Error(`Claude SDK flag settings replay timed out after ${FLAG_SETTINGS_REPLAY_TIMEOUT_MS} ms`), (replaySignal) => raceAbort(applySettings(overlay), replaySignal).catch((error) => {
|
|
826
|
+
if (replaySignal.aborted)
|
|
827
|
+
throw abortReason(replaySignal);
|
|
828
|
+
throw error;
|
|
829
|
+
}));
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// src/agent-executor/claude-sdk/session.ts
|
|
833
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
834
|
+
function isUuid(value) {
|
|
835
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
|
|
836
|
+
}
|
|
837
|
+
function createSdkStartTurn(input) {
|
|
838
|
+
return imageTurnStarter({
|
|
245
839
|
driverLabel: "The Agent SDK driver",
|
|
246
840
|
busyMessage: "A turn is already running in this Claude session",
|
|
247
|
-
imageOptions: config,
|
|
248
|
-
signal:
|
|
841
|
+
imageOptions: input.config,
|
|
842
|
+
signal: input.signal,
|
|
249
843
|
check(turnInput) {
|
|
250
|
-
if (
|
|
844
|
+
if (input.isClosed())
|
|
251
845
|
throw new Error("The Claude SDK session is closed");
|
|
252
|
-
if (
|
|
846
|
+
if (input.getTurn() !== undefined || input.isStarting())
|
|
253
847
|
throw new Error("A turn is already running in this Claude session");
|
|
254
848
|
if (!isUuid(turnInput.clientId))
|
|
255
849
|
throw new TypeError("The Agent SDK driver needs a UUID client id");
|
|
256
850
|
},
|
|
257
|
-
dispatch(turnInput, parts) {
|
|
851
|
+
async dispatch(turnInput, parts) {
|
|
258
852
|
const clientId = turnInput.clientId;
|
|
259
853
|
if (!isUuid(clientId))
|
|
260
854
|
throw new TypeError("The Agent SDK driver needs a UUID client id");
|
|
855
|
+
input.setStarting(true);
|
|
856
|
+
let active;
|
|
857
|
+
try {
|
|
858
|
+
active = await input.ensureQuery(false);
|
|
859
|
+
} finally {
|
|
860
|
+
input.setStarting(false);
|
|
861
|
+
}
|
|
862
|
+
if (input.isClosed())
|
|
863
|
+
throw new Error("The Claude SDK session is closed");
|
|
864
|
+
if (input.getTurn() !== undefined)
|
|
865
|
+
throw new Error("A turn is already running in this Claude session");
|
|
261
866
|
const turn = {
|
|
262
867
|
state: newClaudeTurnState(turnInput.turnId),
|
|
263
868
|
channel: createTurnDeltaChannel(),
|
|
264
869
|
pending: new Map
|
|
265
870
|
};
|
|
266
|
-
|
|
871
|
+
input.setTurn(turn);
|
|
267
872
|
try {
|
|
268
|
-
const active = running ?? start();
|
|
269
873
|
active.send({
|
|
270
874
|
type: "user",
|
|
271
875
|
message: { role: "user", content: claudeUserContent(parts) },
|
|
272
876
|
parent_tool_use_id: null,
|
|
273
877
|
uuid: clientId,
|
|
274
|
-
session_id: sessionId
|
|
878
|
+
session_id: input.sessionId
|
|
275
879
|
});
|
|
880
|
+
input.markResumable();
|
|
881
|
+
active.startLoop();
|
|
276
882
|
return sdkTurnHandle(turn, active.query);
|
|
277
883
|
} catch (error) {
|
|
278
|
-
if (
|
|
279
|
-
|
|
884
|
+
if (input.getTurn() === turn)
|
|
885
|
+
input.setTurn(undefined);
|
|
280
886
|
throw error;
|
|
281
887
|
}
|
|
282
888
|
}
|
|
283
889
|
});
|
|
890
|
+
}
|
|
891
|
+
async function launchSingleSdkQuery(input) {
|
|
892
|
+
if (input.isClosed())
|
|
893
|
+
throw new Error("The Claude SDK session is closed");
|
|
894
|
+
input.signal.throwIfAborted();
|
|
895
|
+
emitStartupPhase(input.onStartupPhase, "spawning");
|
|
896
|
+
const pushed = pushablePrompt();
|
|
897
|
+
let query;
|
|
898
|
+
try {
|
|
899
|
+
query = input.config.query({
|
|
900
|
+
prompt: pushed.prompt,
|
|
901
|
+
options: buildClaudeSdkQueryOptions({
|
|
902
|
+
config: input.config,
|
|
903
|
+
cwd: input.cwd,
|
|
904
|
+
env: input.env,
|
|
905
|
+
canUseTool: input.canUseTool,
|
|
906
|
+
sessionId: input.sessionId,
|
|
907
|
+
resume: input.resume,
|
|
908
|
+
...input.resumeSessionAt !== undefined && {
|
|
909
|
+
resumeSessionAt: input.resumeSessionAt
|
|
910
|
+
},
|
|
911
|
+
...input.resumeDropsTurn !== undefined && {
|
|
912
|
+
resumeDropsTurn: input.resumeDropsTurn
|
|
913
|
+
},
|
|
914
|
+
activeModel: input.activeModel,
|
|
915
|
+
activePermissionMode: input.activePermissionMode,
|
|
916
|
+
recordPid: input.recordPid,
|
|
917
|
+
onPidExit: input.onPidExit
|
|
918
|
+
})
|
|
919
|
+
});
|
|
920
|
+
} catch (error) {
|
|
921
|
+
input.recordPid(undefined);
|
|
922
|
+
pushed.end();
|
|
923
|
+
throw error;
|
|
924
|
+
}
|
|
925
|
+
let closedOnce = false;
|
|
926
|
+
let loopStarted = false;
|
|
927
|
+
const closeHandle = () => {
|
|
928
|
+
if (closedOnce)
|
|
929
|
+
return;
|
|
930
|
+
closedOnce = true;
|
|
931
|
+
pushed.end();
|
|
932
|
+
closeQuerySafely(query);
|
|
933
|
+
};
|
|
934
|
+
const handle = {
|
|
935
|
+
query,
|
|
936
|
+
send: pushed.send,
|
|
937
|
+
startLoop() {
|
|
938
|
+
if (loopStarted || closedOnce)
|
|
939
|
+
return;
|
|
940
|
+
loopStarted = true;
|
|
941
|
+
runSdkQueryLoop({
|
|
942
|
+
handle,
|
|
943
|
+
profileId: input.profileId,
|
|
944
|
+
limits: input.limits,
|
|
945
|
+
getTurn: input.getTurn,
|
|
946
|
+
clearTurn: input.clearTurn,
|
|
947
|
+
...input.config.onEvent !== undefined && { onEvent: input.config.onEvent },
|
|
948
|
+
...input.config.onTurnUsage !== undefined && {
|
|
949
|
+
onTurnUsage: input.config.onTurnUsage
|
|
950
|
+
},
|
|
951
|
+
onExit: input.onExit
|
|
952
|
+
});
|
|
953
|
+
},
|
|
954
|
+
close: closeHandle
|
|
955
|
+
};
|
|
956
|
+
input.setInFlightClose(closeHandle);
|
|
957
|
+
try {
|
|
958
|
+
if (hasDelegationVerification(input.config.verifyDelegation)) {
|
|
959
|
+
emitStartupPhase(input.onStartupPhase, "verifying");
|
|
960
|
+
await verifyClaudeSdkDelegation(query, input.config.verifyDelegation, input.signal);
|
|
961
|
+
}
|
|
962
|
+
if (input.flagSettingsOverlay !== undefined) {
|
|
963
|
+
await replayClaudeSdkFlagSettings(query, input.flagSettingsOverlay, input.signal);
|
|
964
|
+
}
|
|
965
|
+
if (input.isClosed() || input.signal.aborted) {
|
|
966
|
+
throw input.isClosed() ? new Error("The Claude SDK session is closed") : abortReason(input.signal);
|
|
967
|
+
}
|
|
968
|
+
} catch (error) {
|
|
969
|
+
input.setInFlightClose(undefined);
|
|
970
|
+
input.recordPid(undefined);
|
|
971
|
+
closeHandle();
|
|
972
|
+
throw error;
|
|
973
|
+
}
|
|
974
|
+
input.setInFlightClose(undefined);
|
|
975
|
+
return handle;
|
|
976
|
+
}
|
|
977
|
+
function notifyQueryExit(callback, error, context) {
|
|
978
|
+
if (callback === undefined)
|
|
979
|
+
return;
|
|
980
|
+
invokeSafely(() => callback(error, context));
|
|
981
|
+
}
|
|
982
|
+
function validateClaudeSdkOpenInput(input) {
|
|
983
|
+
const hasNativeThreadId = typeof input.nativeThreadId === "string" && input.nativeThreadId.trim().length > 0;
|
|
984
|
+
if (input.resumeSessionAt !== undefined) {
|
|
985
|
+
if (typeof input.resumeSessionAt !== "string" || input.resumeSessionAt.trim().length === 0) {
|
|
986
|
+
throw new TypeError("Claude SDK open() requires a non-empty resumeSessionAt UUID when provided");
|
|
987
|
+
}
|
|
988
|
+
if (!hasNativeThreadId) {
|
|
989
|
+
throw new TypeError("Claude SDK open() requires nativeThreadId when resumeSessionAt is provided");
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
if (input.resumeDropsTurn !== undefined) {
|
|
993
|
+
if (typeof input.resumeDropsTurn !== "string" || input.resumeDropsTurn.trim().length === 0) {
|
|
994
|
+
throw new TypeError("Claude SDK open() requires a non-empty resumeDropsTurn prompt UUID when provided");
|
|
995
|
+
}
|
|
996
|
+
if (!hasNativeThreadId) {
|
|
997
|
+
throw new TypeError("Claude SDK open() requires nativeThreadId when resumeDropsTurn is provided");
|
|
998
|
+
}
|
|
999
|
+
if (input.resumeSessionAt === undefined) {
|
|
1000
|
+
throw new TypeError("Claude SDK open() requires resumeSessionAt when resumeDropsTurn is provided");
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
function recordSdkPlanLimitsFailure(limits, profileId, error) {
|
|
1005
|
+
const rawMessage = error instanceof Error ? error.message : String(error);
|
|
1006
|
+
const boundedMessage = rawMessage.trim().length > 0 ? rawMessage.slice(0, 4096) : "Plan limits read failed";
|
|
1007
|
+
limits.set(profileId, planLimitsReadFailed2({
|
|
1008
|
+
previous: limits.get(profileId),
|
|
1009
|
+
error: boundedMessage,
|
|
1010
|
+
now: new Date
|
|
1011
|
+
}));
|
|
1012
|
+
}
|
|
1013
|
+
async function openClaudeSdkSession(config, limits, input) {
|
|
1014
|
+
validateClaudeSdkOpenInput(input);
|
|
1015
|
+
const ambient = config.ambient ?? process.env;
|
|
1016
|
+
const profile = engineProfile("claude-sdk", input.profile);
|
|
1017
|
+
input.signal?.throwIfAborted();
|
|
1018
|
+
const sessionId = input.nativeThreadId ?? randomUUID2();
|
|
1019
|
+
const transcript = claudeTranscriptPath2({ home: profile.home, cwd: input.cwd, sessionId });
|
|
1020
|
+
const transcriptExists = input.nativeThreadId !== undefined && await claudeTranscriptExists(transcript);
|
|
1021
|
+
let resume = transcriptExists || input.resumeSessionAt !== undefined;
|
|
1022
|
+
let pendingResumeSessionAt = input.resumeSessionAt;
|
|
1023
|
+
let pendingResumeDropsTurn = input.resumeDropsTurn;
|
|
1024
|
+
let current;
|
|
1025
|
+
let startingTurn = false;
|
|
1026
|
+
let opened = false;
|
|
1027
|
+
let closed = false;
|
|
1028
|
+
let providerPid;
|
|
1029
|
+
let activeModel = config.model;
|
|
1030
|
+
let activePermissionMode = config.permissionMode ?? "default";
|
|
1031
|
+
let flagSettingsOverlay;
|
|
1032
|
+
let running;
|
|
1033
|
+
let opening;
|
|
1034
|
+
let inFlightClose;
|
|
1035
|
+
const shutdown = (reason) => {
|
|
1036
|
+
if (closed)
|
|
1037
|
+
return;
|
|
1038
|
+
closed = true;
|
|
1039
|
+
providerPid = undefined;
|
|
1040
|
+
const turn = current;
|
|
1041
|
+
current = undefined;
|
|
1042
|
+
loseEngineTurn(turn, stoppedPermission("The session was closed"), reason);
|
|
1043
|
+
const pendingClose = inFlightClose;
|
|
1044
|
+
inFlightClose = undefined;
|
|
1045
|
+
pendingClose?.();
|
|
1046
|
+
const active = running;
|
|
1047
|
+
running = undefined;
|
|
1048
|
+
active?.close();
|
|
1049
|
+
};
|
|
1050
|
+
const linked = sessionAbort(input.signal);
|
|
1051
|
+
linked.signal.addEventListener("abort", () => shutdown(abortReason(linked.signal)), {
|
|
1052
|
+
once: true
|
|
1053
|
+
});
|
|
1054
|
+
const canUseTool = createSdkCanUseTool({
|
|
1055
|
+
getTurn: () => current,
|
|
1056
|
+
isClosed: () => closed,
|
|
1057
|
+
...config.onPermissionRequest !== undefined && {
|
|
1058
|
+
onPermissionRequest: config.onPermissionRequest
|
|
1059
|
+
}
|
|
1060
|
+
});
|
|
1061
|
+
const ensureQuery = async (startLoopImmediately) => {
|
|
1062
|
+
if (closed)
|
|
1063
|
+
throw new Error("The Claude SDK session is closed");
|
|
1064
|
+
if (running !== undefined) {
|
|
1065
|
+
if (startLoopImmediately)
|
|
1066
|
+
running.startLoop();
|
|
1067
|
+
return running;
|
|
1068
|
+
}
|
|
1069
|
+
if (opening === undefined) {
|
|
1070
|
+
const promise = launchSingleSdkQuery({
|
|
1071
|
+
config,
|
|
1072
|
+
cwd: input.cwd,
|
|
1073
|
+
env: engineEnvironment2(profile, ambient),
|
|
1074
|
+
profileId: profile.profileId,
|
|
1075
|
+
limits,
|
|
1076
|
+
sessionId,
|
|
1077
|
+
resume,
|
|
1078
|
+
...pendingResumeSessionAt !== undefined && {
|
|
1079
|
+
resumeSessionAt: pendingResumeSessionAt
|
|
1080
|
+
},
|
|
1081
|
+
...pendingResumeDropsTurn !== undefined && {
|
|
1082
|
+
resumeDropsTurn: pendingResumeDropsTurn
|
|
1083
|
+
},
|
|
1084
|
+
activeModel,
|
|
1085
|
+
activePermissionMode,
|
|
1086
|
+
flagSettingsOverlay,
|
|
1087
|
+
signal: linked.signal,
|
|
1088
|
+
canUseTool,
|
|
1089
|
+
isClosed: () => closed,
|
|
1090
|
+
getTurn: () => current,
|
|
1091
|
+
clearTurn: () => {
|
|
1092
|
+
current = undefined;
|
|
1093
|
+
},
|
|
1094
|
+
setInFlightClose: (fn) => {
|
|
1095
|
+
inFlightClose = fn;
|
|
1096
|
+
},
|
|
1097
|
+
recordPid: (pid) => {
|
|
1098
|
+
providerPid = pid;
|
|
1099
|
+
},
|
|
1100
|
+
onPidExit: (exitedPid) => {
|
|
1101
|
+
if (providerPid === exitedPid)
|
|
1102
|
+
providerPid = undefined;
|
|
1103
|
+
},
|
|
1104
|
+
...input.onStartupPhase !== undefined && { onStartupPhase: input.onStartupPhase },
|
|
1105
|
+
onExit: (exited, error) => {
|
|
1106
|
+
const ownsSession = running === exited;
|
|
1107
|
+
const shouldNotify = ownsSession && opened && !closed && !linked.signal.aborted;
|
|
1108
|
+
const turn = ownsSession ? current : undefined;
|
|
1109
|
+
const duringTurn = turn !== undefined;
|
|
1110
|
+
if (ownsSession) {
|
|
1111
|
+
running = undefined;
|
|
1112
|
+
current = undefined;
|
|
1113
|
+
providerPid = undefined;
|
|
1114
|
+
}
|
|
1115
|
+
loseEngineTurn(turn, stoppedPermission("The Claude SDK query ended"), error);
|
|
1116
|
+
exited.close();
|
|
1117
|
+
if (shouldNotify) {
|
|
1118
|
+
notifyQueryExit(config.onQueryExit, error, {
|
|
1119
|
+
duringTurn,
|
|
1120
|
+
nativeThreadId: sessionId
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
}).then((handle) => {
|
|
1125
|
+
running = handle;
|
|
1126
|
+
return handle;
|
|
1127
|
+
}).finally(() => {
|
|
1128
|
+
if (opening === promise)
|
|
1129
|
+
opening = undefined;
|
|
1130
|
+
});
|
|
1131
|
+
opening = promise;
|
|
1132
|
+
}
|
|
1133
|
+
const handle = await opening;
|
|
1134
|
+
if (startLoopImmediately)
|
|
1135
|
+
handle.startLoop();
|
|
1136
|
+
return handle;
|
|
1137
|
+
};
|
|
1138
|
+
if (hasDelegationVerification(config.verifyDelegation)) {
|
|
1139
|
+
try {
|
|
1140
|
+
await ensureQuery(true);
|
|
1141
|
+
} catch (error) {
|
|
1142
|
+
shutdown(error);
|
|
1143
|
+
linked.abort();
|
|
1144
|
+
linked.release();
|
|
1145
|
+
throw error;
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
const startTurn = createSdkStartTurn({
|
|
1149
|
+
config,
|
|
1150
|
+
sessionId,
|
|
1151
|
+
signal: linked.signal,
|
|
1152
|
+
isClosed: () => closed,
|
|
1153
|
+
getTurn: () => current,
|
|
1154
|
+
setTurn: (turn) => {
|
|
1155
|
+
current = turn;
|
|
1156
|
+
},
|
|
1157
|
+
isStarting: () => startingTurn,
|
|
1158
|
+
setStarting: (value) => {
|
|
1159
|
+
startingTurn = value;
|
|
1160
|
+
},
|
|
1161
|
+
markResumable: () => {
|
|
1162
|
+
resume = true;
|
|
1163
|
+
pendingResumeSessionAt = undefined;
|
|
1164
|
+
pendingResumeDropsTurn = undefined;
|
|
1165
|
+
},
|
|
1166
|
+
ensureQuery
|
|
1167
|
+
});
|
|
1168
|
+
const controls = createClaudeSdkControls({
|
|
1169
|
+
signal: linked.signal,
|
|
1170
|
+
isClosed: () => closed,
|
|
1171
|
+
ensureQuery: () => ensureQuery(true),
|
|
1172
|
+
setActiveModel: (model) => {
|
|
1173
|
+
activeModel = model;
|
|
1174
|
+
},
|
|
1175
|
+
setActivePermissionMode: (mode) => {
|
|
1176
|
+
activePermissionMode = mode;
|
|
1177
|
+
},
|
|
1178
|
+
recordFlagSettings: (settings) => {
|
|
1179
|
+
flagSettingsOverlay = { ...flagSettingsOverlay, ...settings };
|
|
1180
|
+
},
|
|
1181
|
+
recordPlanLimits: (next) => {
|
|
1182
|
+
limits.set(profile.profileId, next);
|
|
1183
|
+
},
|
|
1184
|
+
recordPlanLimitsFailure: (error) => recordSdkPlanLimitsFailure(limits, profile.profileId, error)
|
|
1185
|
+
});
|
|
1186
|
+
opened = true;
|
|
284
1187
|
return {
|
|
285
1188
|
nativeThreadId: sessionId,
|
|
1189
|
+
get providerPid() {
|
|
1190
|
+
return providerPid;
|
|
1191
|
+
},
|
|
286
1192
|
startTurn,
|
|
1193
|
+
...controls,
|
|
287
1194
|
async close() {
|
|
288
1195
|
shutdown(new Error("The Claude SDK session closed"));
|
|
289
1196
|
linked.abort();
|
|
@@ -294,17 +1201,35 @@ async function openClaudeSdkSession(config, limits, input) {
|
|
|
294
1201
|
|
|
295
1202
|
// src/agent-executor/claude-sdk/driver.ts
|
|
296
1203
|
function createClaudeSdkDriver(config) {
|
|
297
|
-
|
|
1204
|
+
validateClaudeSdkConfig(config);
|
|
298
1205
|
const limits = new Map;
|
|
1206
|
+
const capabilities = {
|
|
1207
|
+
runtimePolicyEnforcement: "native",
|
|
1208
|
+
sessionApproval: true,
|
|
1209
|
+
interruptOnDeny: true,
|
|
1210
|
+
updatedToolInput: true,
|
|
1211
|
+
structuredInput: false,
|
|
1212
|
+
steer: false,
|
|
1213
|
+
fork: config.forkSession !== undefined,
|
|
1214
|
+
revert: false,
|
|
1215
|
+
compact: false,
|
|
1216
|
+
injectItems: false,
|
|
1217
|
+
backgroundWorkOutlivesTurn: config.onEvent !== undefined,
|
|
1218
|
+
multiThreadPerProcess: false,
|
|
1219
|
+
images: config.resolveFile !== undefined,
|
|
1220
|
+
planLimits: "pull"
|
|
1221
|
+
};
|
|
299
1222
|
return {
|
|
300
1223
|
engine: "claude-sdk",
|
|
301
1224
|
reconcile: "client-id",
|
|
1225
|
+
capabilities,
|
|
302
1226
|
async info() {
|
|
303
1227
|
return {
|
|
304
1228
|
engine: "claude-sdk",
|
|
305
1229
|
version: config.sdkVersion,
|
|
306
1230
|
reconcile: "client-id",
|
|
307
|
-
models: { answer: "not-asked" }
|
|
1231
|
+
models: { answer: "not-asked" },
|
|
1232
|
+
capabilities
|
|
308
1233
|
};
|
|
309
1234
|
},
|
|
310
1235
|
async status(rawProfile) {
|
|
@@ -317,9 +1242,23 @@ function createClaudeSdkDriver(config) {
|
|
|
317
1242
|
};
|
|
318
1243
|
},
|
|
319
1244
|
findInput: (input) => findTranscriptInput("claude-sdk", input),
|
|
320
|
-
open: (input) => openClaudeSdkSession(config, limits, input)
|
|
1245
|
+
open: (input) => openClaudeSdkSession(config, limits, input),
|
|
1246
|
+
async forkSession(sessionId, options) {
|
|
1247
|
+
if (sessionId.trim().length === 0) {
|
|
1248
|
+
throw new TypeError("Claude SDK forkSession requires a non-empty sessionId");
|
|
1249
|
+
}
|
|
1250
|
+
if (config.forkSession === undefined) {
|
|
1251
|
+
throw new Error("Claude SDK driver was not configured with forkSession");
|
|
1252
|
+
}
|
|
1253
|
+
return config.forkSession(sessionId, options);
|
|
1254
|
+
},
|
|
1255
|
+
probeCapabilities: (input) => probeClaudeSdkCapabilities(config, limits, input)
|
|
321
1256
|
};
|
|
322
1257
|
}
|
|
323
1258
|
export {
|
|
1259
|
+
ClaudeRuntimeEventSchema2 as ClaudeRuntimeEventSchema,
|
|
1260
|
+
ClaudeSdkTokenPairSchema,
|
|
1261
|
+
ClaudeSdkTurnUsageSchema,
|
|
1262
|
+
ClaudeTaskUsageSchema2 as ClaudeTaskUsageSchema,
|
|
324
1263
|
createClaudeSdkDriver
|
|
325
1264
|
};
|