@zvada/agent-server 0.3.23 → 0.3.25
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 +64 -0
- package/README.md +14 -5
- package/dist/accounts/chatgpt.js +144 -0
- package/dist/accounts/check.js +71 -0
- package/dist/accounts/claude.js +80 -0
- package/dist/accounts/endpoint.js +104 -0
- package/dist/accounts/http.js +58 -0
- package/dist/accounts/index.js +9 -0
- package/dist/client/client.js +745 -0
- package/dist/client/connection.js +338 -0
- package/dist/client/history.js +49 -0
- package/dist/client/index.js +6 -0
- package/dist/client/listeners.js +19 -0
- package/dist/client/logins.js +92 -0
- package/dist/client/rpc.js +105 -0
- package/dist/client/streams.js +432 -0
- package/dist/client/transports.js +118 -0
- package/dist/client/turns.js +122 -0
- package/dist/core/agents/acp/acp-agent.js +425 -0
- package/dist/core/agents/acp/adapter.js +231 -0
- package/dist/core/agents/acp/client.js +222 -0
- package/dist/core/agents/acp/known-agents.js +57 -0
- package/dist/core/agents/acp/mappings.js +164 -0
- package/dist/core/agents/acp/requests.js +79 -0
- package/dist/core/agents/attachments.js +14 -0
- package/dist/core/agents/base.js +64 -0
- package/dist/core/agents/claude-code/adapter.js +474 -0
- package/dist/core/agents/claude-code/approvals.js +245 -0
- package/dist/core/agents/claude-code/claude-agent.js +319 -0
- package/dist/core/agents/claude-code/credentials.js +142 -0
- package/dist/core/agents/claude-code/events.js +11 -0
- package/dist/core/agents/claude-code/login.js +217 -0
- package/dist/core/agents/claude-code/mcp.js +181 -0
- package/dist/core/agents/claude-code/models.js +74 -0
- package/dist/core/agents/claude-code/options.js +240 -0
- package/dist/core/agents/claude-code/outcome.js +204 -0
- package/dist/core/agents/claude-code/results.js +58 -0
- package/dist/core/agents/claude-code/sdk-pair.js +59 -0
- package/dist/core/agents/claude-code/session.js +593 -0
- package/dist/core/agents/claude-code/spawn.js +125 -0
- package/dist/core/agents/claude-code/spend.js +118 -0
- package/dist/core/agents/claude-code/tools.js +131 -0
- package/dist/core/agents/claude-code/turn-usage.js +121 -0
- package/dist/core/agents/claude-code/turn.js +199 -0
- package/dist/core/agents/codex-app-server/adapter.js +463 -0
- package/dist/core/agents/codex-app-server/client.js +338 -0
- package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
- package/dist/core/agents/codex-app-server/commands.js +184 -0
- package/dist/core/agents/codex-app-server/credentials.js +92 -0
- package/dist/core/agents/codex-app-server/effort.js +13 -0
- package/dist/core/agents/codex-app-server/events.js +18 -0
- package/dist/core/agents/codex-app-server/homes.js +118 -0
- package/dist/core/agents/codex-app-server/input.js +52 -0
- package/dist/core/agents/codex-app-server/items.js +307 -0
- package/dist/core/agents/codex-app-server/login.js +183 -0
- package/dist/core/agents/codex-app-server/mcp.js +323 -0
- package/dist/core/agents/codex-app-server/models.js +160 -0
- package/dist/core/agents/codex-app-server/options.js +155 -0
- package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
- package/dist/core/agents/codex-app-server/protocol.js +38 -0
- package/dist/core/agents/codex-app-server/requests.js +250 -0
- package/dist/core/agents/codex-app-server/session.js +278 -0
- package/dist/core/agents/codex-app-server/subagents.js +260 -0
- package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
- package/dist/core/agents/codex-app-server/turn-items.js +69 -0
- package/dist/core/agents/codex-app-server/turn.js +448 -0
- package/dist/core/agents/codex-app-server/user-login.js +78 -0
- package/dist/core/agents/config-fingerprint.js +10 -0
- package/dist/core/agents/credentials.js +71 -0
- package/dist/core/agents/diffs.js +27 -0
- package/dist/core/agents/elicitation.js +42 -0
- package/dist/core/agents/inherit-config.js +5 -0
- package/dist/core/agents/login.js +56 -0
- package/dist/core/agents/mcp-config.js +109 -0
- package/dist/core/agents/plan.js +6 -0
- package/dist/core/agents/process-pool.js +307 -0
- package/dist/core/agents/registry.js +49 -0
- package/dist/core/agents/scripted/adapter.js +86 -0
- package/dist/core/agents/scripted/mcp-call.js +74 -0
- package/dist/core/agents/scripted/scripted-agent.js +331 -0
- package/dist/core/agents/scripted/scripts.js +154 -0
- package/dist/core/agents/scripted/steps.js +87 -0
- package/dist/core/agents/session-agent.js +209 -0
- package/dist/core/agents/stderr-tail.js +71 -0
- package/dist/core/agents/thinking-levels.js +9 -0
- package/dist/core/agents/types.js +1 -0
- package/dist/core/diagnostics.js +23 -0
- package/dist/core/index.js +31 -0
- package/dist/core/presets.js +114 -0
- package/dist/core/processes/identity.js +92 -0
- package/dist/core/processes/lifeline.js +218 -0
- package/dist/core/processes/native-processes.js +299 -0
- package/dist/core/processes/process-table.js +164 -0
- package/dist/core/provision/cache-trust.js +121 -0
- package/dist/core/provision/cache-usage.js +61 -0
- package/dist/core/provision/checksums.js +22 -0
- package/dist/core/provision/extract.js +29 -0
- package/dist/core/provision/index.js +4 -0
- package/dist/core/provision/install-build.js +99 -0
- package/dist/core/provision/npm.js +316 -0
- package/dist/core/provision/pins.js +35 -0
- package/dist/core/provision/platform.js +65 -0
- package/dist/core/provision/provisioner.js +372 -0
- package/dist/core/provision/releases.js +68 -0
- package/dist/core/provision/tools.js +279 -0
- package/dist/core/proxy/anthropic-proxy.js +163 -0
- package/dist/core/proxy/api-key-store.js +30 -0
- package/dist/core/proxy/index.js +3 -0
- package/dist/core/proxy/loopback.js +86 -0
- package/dist/core/runtime/agent-runtime.js +437 -0
- package/dist/core/runtime/event-processor.js +379 -0
- package/dist/core/runtime/event-sink.js +65 -0
- package/dist/core/runtime/harness-clis.js +83 -0
- package/dist/core/runtime/harness-logins.js +313 -0
- package/dist/core/runtime/login-reads.js +71 -0
- package/dist/core/runtime/model-lists.js +160 -0
- package/dist/core/runtime/permission-policy.js +84 -0
- package/dist/core/runtime/request-broker.js +139 -0
- package/dist/core/runtime/steering.js +79 -0
- package/dist/core/runtime/turn-outcome.js +16 -0
- package/dist/core/runtime/turn.js +339 -0
- package/dist/core/utils/bounded.js +13 -0
- package/dist/core/utils/deadline.js +57 -0
- package/dist/core/utils/errors.js +176 -0
- package/dist/core/utils/is-record.js +4 -0
- package/dist/core/utils/loopback.js +11 -0
- package/dist/index.js +4 -0
- package/dist/operator/index.js +10 -0
- package/dist/operator/mcp.js +139 -0
- package/dist/operator/operator.js +499 -0
- package/dist/operator/render.js +408 -0
- package/dist/operator/view.js +35 -0
- package/dist/protocol/account.js +96 -0
- package/dist/protocol/async-queue.js +65 -0
- package/dist/protocol/auth.js +169 -0
- package/dist/protocol/canonical.js +18 -0
- package/dist/protocol/clis.js +63 -0
- package/dist/protocol/config.js +137 -0
- package/dist/protocol/conversation.js +231 -0
- package/dist/protocol/credentials.js +142 -0
- package/dist/protocol/errors.js +190 -0
- package/dist/protocol/execution.js +28 -0
- package/dist/protocol/factories.js +231 -0
- package/dist/protocol/guards.js +71 -0
- package/dist/protocol/harness.js +93 -0
- package/dist/protocol/history.js +201 -0
- package/dist/protocol/ids.js +37 -0
- package/dist/protocol/index.js +36 -0
- package/dist/protocol/lifecycle.js +562 -0
- package/dist/protocol/meta-keys.js +17 -0
- package/dist/protocol/meta.js +13 -0
- package/dist/protocol/model-catalog.js +223 -0
- package/dist/protocol/models.js +84 -0
- package/dist/protocol/part-input.js +94 -0
- package/dist/protocol/parts.js +166 -0
- package/dist/protocol/plan.js +31 -0
- package/dist/protocol/reduce.js +484 -0
- package/dist/protocol/selectors.js +136 -0
- package/dist/protocol/seq-cursor.js +37 -0
- package/dist/protocol/stop-reasons.js +41 -0
- package/dist/protocol/thinking.js +31 -0
- package/dist/protocol/time.js +21 -0
- package/dist/protocol/tokens.js +57 -0
- package/dist/protocol/tool-closure.js +70 -0
- package/dist/protocol/tool-state.js +153 -0
- package/dist/protocol/verify.js +467 -0
- package/dist/protocol/vocabulary.js +27 -0
- package/dist/protocol/wire-api.js +94 -0
- package/dist/protocol/wire.js +669 -0
- package/dist/server/acp/binding.js +251 -0
- package/dist/server/acp/session-records.js +53 -0
- package/dist/server/acp/translate.js +401 -0
- package/dist/server/agent-server.js +338 -0
- package/dist/server/bin.js +492 -0
- package/dist/server/feedback.js +216 -0
- package/dist/server/history.js +123 -0
- package/dist/server/index.js +8 -0
- package/dist/server/install.js +171 -0
- package/dist/server/open-parts.js +87 -0
- package/dist/server/routes.js +292 -0
- package/dist/server/secrets.js +19 -0
- package/dist/server/session-gate.js +54 -0
- package/dist/server/session-log.js +66 -0
- package/dist/server/session-store.js +243 -0
- package/dist/server/subscriptions.js +189 -0
- package/dist/server/transports.js +214 -0
- package/dist/server/wire-error.js +26 -0
- package/dist/sync/event-log.js +89 -0
- package/dist/sync/fit.js +202 -0
- package/dist/sync/history-reader.js +33 -0
- package/dist/sync/history-sqlite.js +281 -0
- package/dist/sync/history.js +163 -0
- package/dist/sync/index.js +5 -0
- package/dist/sync/journal-sqlite.js +316 -0
- package/dist/sync/journal.js +10 -0
- package/dist/sync/live-tails.js +85 -0
- package/dist/sync/node-sqlite.js +27 -0
- package/dist/sync/projection.js +32 -0
- package/dist/sync/recovery.js +117 -0
- package/dist/sync/retry.js +45 -0
- package/dist/sync/schema.js +73 -0
- package/dist/sync/sql.js +94 -0
- package/dist/sync/sqlite-file.js +31 -0
- package/dist/sync/sqlite.js +18 -0
- package/dist/sync/worker.js +212 -0
- package/dist/types/client/client.d.ts +6 -1
- package/dist/types/client/client.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
- package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/options.d.ts +28 -11
- package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/session.d.ts +8 -0
- package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
- package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
- package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
- package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
- package/dist/types/core/agents/process-pool.d.ts +8 -0
- package/dist/types/core/agents/process-pool.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/steps.d.ts +1 -1
- package/dist/types/core/presets.d.ts +2 -2
- package/dist/types/core/presets.d.ts.map +1 -1
- package/dist/types/core/processes/identity.d.ts.map +1 -1
- package/dist/types/core/processes/lifeline.d.ts.map +1 -1
- package/dist/types/core/processes/process-table.d.ts.map +1 -1
- package/dist/types/core/provision/extract.d.ts.map +1 -1
- package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
- package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
- package/dist/types/core/runtime/turn.d.ts +12 -7
- package/dist/types/core/runtime/turn.d.ts.map +1 -1
- package/dist/types/protocol/clis.d.ts +3 -3
- package/dist/types/protocol/conversation.d.ts +6 -6
- package/dist/types/protocol/credentials.d.ts +13 -1
- package/dist/types/protocol/credentials.d.ts.map +1 -1
- package/dist/types/protocol/errors.d.ts +6 -4
- package/dist/types/protocol/errors.d.ts.map +1 -1
- package/dist/types/protocol/lifecycle.d.ts +4 -4
- package/dist/types/protocol/wire-api.d.ts +12 -12
- package/dist/types/protocol/wire.d.ts +8 -8
- package/dist/types/server/bin.d.ts +3 -0
- package/dist/types/server/bin.d.ts.map +1 -0
- package/dist/types/server/routes.d.ts.map +1 -1
- package/dist/types/server/transports.d.ts +2 -1
- package/dist/types/server/transports.d.ts.map +1 -1
- package/dist/types/sync/node-sqlite.d.ts +4 -1
- package/dist/types/sync/node-sqlite.d.ts.map +1 -1
- package/docs/consuming.md +56 -7
- package/docs/deploy.md +35 -0
- package/docs/harnesses.md +30 -5
- package/package.json +43 -18
- package/src/client/client.ts +114 -44
- package/src/core/agents/claude-code/approvals.ts +5 -1
- package/src/core/agents/claude-code/claude-agent.ts +32 -5
- package/src/core/agents/claude-code/options.ts +28 -11
- package/src/core/agents/claude-code/session.ts +13 -0
- package/src/core/agents/codex-app-server/homes.ts +11 -2
- package/src/core/agents/codex-app-server/login.ts +30 -0
- package/src/core/agents/codex-app-server/requests.ts +7 -6
- package/src/core/agents/codex-app-server/session.ts +11 -2
- package/src/core/agents/process-pool.ts +30 -4
- package/src/core/agents/scripted/scripted-agent.ts +2 -1
- package/src/core/agents/scripted/steps.ts +1 -1
- package/src/core/presets.ts +3 -2
- package/src/core/processes/identity.ts +1 -0
- package/src/core/processes/lifeline.ts +10 -1
- package/src/core/processes/process-table.ts +1 -0
- package/src/core/provision/extract.ts +1 -0
- package/src/core/runtime/agent-runtime.ts +6 -3
- package/src/core/runtime/turn.ts +21 -9
- package/src/protocol/credentials.ts +19 -5
- package/src/protocol/errors.ts +12 -3
- package/src/server/bin.ts +25 -10
- package/src/server/routes.ts +3 -2
- package/src/server/transports.ts +6 -1
- package/src/sync/node-sqlite.ts +19 -3
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { untilAborted } from "../../utils/deadline.js";
|
|
2
|
+
const SDK = "@modelcontextprotocol/sdk";
|
|
3
|
+
let sdk;
|
|
4
|
+
/** The official MCP SDK, loaded once, when the first `call` step runs: an optional peer, as the agent SDKs are. */
|
|
5
|
+
function loadSdk() {
|
|
6
|
+
sdk ??= Promise.all([
|
|
7
|
+
import("@modelcontextprotocol/sdk/client/index.js"),
|
|
8
|
+
import("@modelcontextprotocol/sdk/client/streamableHttp.js"),
|
|
9
|
+
]).then(([client, http]) => ({
|
|
10
|
+
Client: client.Client,
|
|
11
|
+
StreamableHTTPClientTransport: http.StreamableHTTPClientTransport,
|
|
12
|
+
}), (error) => {
|
|
13
|
+
sdk = undefined;
|
|
14
|
+
throw new Error(`A call step needs the MCP SDK: install ${SDK} beside @zvada/agent-server (${error instanceof Error ? error.message : String(error)})`);
|
|
15
|
+
});
|
|
16
|
+
return sdk;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The turn's MCP server `name`, checked before its call opens a part: a server
|
|
20
|
+
* the turn does not have, one that is not `http`, or an SDK that is not
|
|
21
|
+
* installed fails the step.
|
|
22
|
+
*/
|
|
23
|
+
export async function callableServer(name, servers) {
|
|
24
|
+
const server = servers?.[name];
|
|
25
|
+
if (!server)
|
|
26
|
+
throw new Error(`A call step names MCP server ${name}, which this turn does not have`);
|
|
27
|
+
if (server.type !== "http")
|
|
28
|
+
throw new Error(`A call step calls only an http MCP server: ${name} is ${server.type}`);
|
|
29
|
+
return {
|
|
30
|
+
url: server.url,
|
|
31
|
+
...(server.headers && { headers: server.headers }),
|
|
32
|
+
sdk: await loadSdk(),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Call one tool over Streamable HTTP, on a connection of its own. A call that
|
|
37
|
+
* fails (the server down, an error it answers) answers `isError`.
|
|
38
|
+
*/
|
|
39
|
+
export async function callMcpTool(server, call, signal) {
|
|
40
|
+
const { Client, StreamableHTTPClientTransport } = server.sdk;
|
|
41
|
+
const client = new Client({ name: "agent-server-scripted", version: "1" });
|
|
42
|
+
try {
|
|
43
|
+
// The handshake takes no signal: the wait for it ends at a cancel, and
|
|
44
|
+
// the client is closed on the way out.
|
|
45
|
+
await untilAborted(client.connect(new StreamableHTTPClientTransport(new URL(server.url), {
|
|
46
|
+
...(server.headers && { requestInit: { headers: server.headers } }),
|
|
47
|
+
})), signal);
|
|
48
|
+
const result = await client.callTool({ name: call.tool, ...(call.arguments && { arguments: call.arguments }) }, undefined, { signal });
|
|
49
|
+
return { ...blocks(result.content), ...structured(result), isError: result.isError === true };
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
if (signal.aborted)
|
|
53
|
+
throw error;
|
|
54
|
+
return { output: error instanceof Error ? error.message : String(error), isError: true };
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
await client.close().catch(() => { });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** Text blocks into `output`; with an image, every block into `content` too, in order. */
|
|
61
|
+
function blocks(content) {
|
|
62
|
+
const list = Array.isArray(content) ? content : [];
|
|
63
|
+
const read = list.map((block) => block.type === "image" && typeof block.data === "string" && typeof block.mimeType === "string"
|
|
64
|
+
? { type: "image", data: block.data, mimeType: block.mimeType }
|
|
65
|
+
: { type: "text", text: typeof block.text === "string" ? block.text : JSON.stringify(block) });
|
|
66
|
+
const output = read.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n");
|
|
67
|
+
return read.some((block) => block.type === "image") ? { output, content: read } : { output };
|
|
68
|
+
}
|
|
69
|
+
function structured(result) {
|
|
70
|
+
const value = result.structuredContent;
|
|
71
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
72
|
+
? { metadata: { structuredContent: value } }
|
|
73
|
+
: {};
|
|
74
|
+
}
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
// @ref LLP 0016.000#the-scripted-harness — the worked example of a harness, under its own name
|
|
2
|
+
// The scripted harness: a script plays the agent, so a product can test its
|
|
3
|
+
// whole integration for nothing, and so the engine has one small, complete
|
|
4
|
+
// example of what a harness implements.
|
|
5
|
+
//
|
|
6
|
+
// What a harness fills in, and where it is here:
|
|
7
|
+
// - its declared support: `CAPABILITIES`;
|
|
8
|
+
// - a turn: `executeTurn`, which yields the harness's own events
|
|
9
|
+
// (`ScriptedEvent`), and the native session id it reports;
|
|
10
|
+
// - its adapter (`adapter.ts`): those events to the engine's;
|
|
11
|
+
// - permission requests and questions through the engine's brokers
|
|
12
|
+
// (`options.onPermissionRequest`, `options.onElicitationRequest`);
|
|
13
|
+
// - its login (`login`) and its models (`listModels`).
|
|
14
|
+
// It runs no process, so it has no process pool, no CLI to install and no
|
|
15
|
+
// credential to take.
|
|
16
|
+
//
|
|
17
|
+
// Not in it: Claude's or Codex's tool names and consent rules, sub-agents,
|
|
18
|
+
// steering, pending tools and input deltas, reasoning. The engine's own test
|
|
19
|
+
// fixture (`test/server/fixtures.ts`) keeps those.
|
|
20
|
+
import { inputToText, } from "../../../protocol/index.js";
|
|
21
|
+
import { onAbort, untilAborted } from "../../utils/deadline.js";
|
|
22
|
+
import { AgentServerError, InvalidRequestError } from "../../utils/errors.js";
|
|
23
|
+
import { NO_ANSWERS, questionRequest } from "../elicitation.js";
|
|
24
|
+
import { SessionAgent } from "../session-agent.js";
|
|
25
|
+
import { callMcpTool, callableServer } from "./mcp-call.js";
|
|
26
|
+
import { readStep } from "./steps.js";
|
|
27
|
+
const CAPABILITIES = {
|
|
28
|
+
multiTurn: true,
|
|
29
|
+
// Any id resumes: a script keeps no conversation to lose.
|
|
30
|
+
sessionResume: true,
|
|
31
|
+
// The model is never run; `echo: "config"` says which one was asked for.
|
|
32
|
+
modelSwitch: "unsupported",
|
|
33
|
+
thinkingLevels: false,
|
|
34
|
+
// Any input is taken; `echo: "input"` says its text.
|
|
35
|
+
images: true,
|
|
36
|
+
files: ["text", "pdf", "binary"],
|
|
37
|
+
// For `call` steps.
|
|
38
|
+
mcpServers: true,
|
|
39
|
+
permissionRequests: true,
|
|
40
|
+
// A rejected call's part says the user's words.
|
|
41
|
+
rejectionMessages: true,
|
|
42
|
+
turnScopedSubagents: false,
|
|
43
|
+
steering: false,
|
|
44
|
+
ignoredSettings: [
|
|
45
|
+
// `echo: "config"` says these; nothing else reads them.
|
|
46
|
+
"model",
|
|
47
|
+
"thinkingLevel",
|
|
48
|
+
"additionalDirectories",
|
|
49
|
+
"systemPromptAppend",
|
|
50
|
+
"maxTurns",
|
|
51
|
+
// The script says which calls ask (`ask: true`), whatever the mode.
|
|
52
|
+
"permissionMode",
|
|
53
|
+
"resumeSessionAt",
|
|
54
|
+
// It runs on no credential.
|
|
55
|
+
"apiKey",
|
|
56
|
+
// The script's tool calls are its own, never the agent's built-in tools.
|
|
57
|
+
"disableTools",
|
|
58
|
+
],
|
|
59
|
+
};
|
|
60
|
+
const STOP = { stop: true };
|
|
61
|
+
const done = (outcome) => ({ outcome });
|
|
62
|
+
/** The one model it lists: it runs none. */
|
|
63
|
+
const MODEL = {
|
|
64
|
+
id: "scripted",
|
|
65
|
+
harness: "scripted",
|
|
66
|
+
label: "Scripted",
|
|
67
|
+
isDefault: true,
|
|
68
|
+
thinking: { levels: [] },
|
|
69
|
+
};
|
|
70
|
+
/** What the user is told a rejected call did. */
|
|
71
|
+
const REJECTED = "The user rejected this tool call.";
|
|
72
|
+
const noLogin = () => new InvalidRequestError([{ path: "harness", message: "the scripted harness has no login" }]);
|
|
73
|
+
/** What a stopped turn throws: the engine reads it as the cancel it asked for. */
|
|
74
|
+
const stopped = () => new DOMException("The turn was cancelled.", "AbortError");
|
|
75
|
+
/** A pause of `ms`, cut short by `signal`. */
|
|
76
|
+
function sleep(ms, signal) {
|
|
77
|
+
return new Promise((resolve, reject) => {
|
|
78
|
+
const timer = setTimeout(() => {
|
|
79
|
+
off();
|
|
80
|
+
resolve();
|
|
81
|
+
}, ms);
|
|
82
|
+
const off = onAbort(signal, () => {
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
reject(stopped());
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/** The turn stops as the user asked: no step after it plays. */
|
|
89
|
+
async function* cancel() {
|
|
90
|
+
yield { type: "cancelled" };
|
|
91
|
+
return STOP;
|
|
92
|
+
}
|
|
93
|
+
/** The words of a text, each with the space after it, so they join back into the text. */
|
|
94
|
+
const words = (text) => text.match(/\s*\S+\s*/g) ?? [];
|
|
95
|
+
/** A harness that plays a script instead of a model (see the top of this file). */
|
|
96
|
+
export class ScriptedAgent extends SessionAgent {
|
|
97
|
+
options;
|
|
98
|
+
harness = "scripted";
|
|
99
|
+
capabilities = CAPABILITIES;
|
|
100
|
+
/** Signed in to nothing, and always able to run: there is no login to make or lose. */
|
|
101
|
+
login = {
|
|
102
|
+
methods: async () => [],
|
|
103
|
+
status: async () => ({ state: "signed_in" }),
|
|
104
|
+
start: async () => {
|
|
105
|
+
throw noLogin();
|
|
106
|
+
},
|
|
107
|
+
logout: async () => {
|
|
108
|
+
throw noLogin();
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
/** Turns each session has run in this engine. */
|
|
112
|
+
turns = new Map();
|
|
113
|
+
processes;
|
|
114
|
+
constructor(options) {
|
|
115
|
+
super();
|
|
116
|
+
this.options = options;
|
|
117
|
+
this.processes = options.processes;
|
|
118
|
+
}
|
|
119
|
+
async listModels() {
|
|
120
|
+
return [MODEL];
|
|
121
|
+
}
|
|
122
|
+
async *executeTurn(input, options, controller) {
|
|
123
|
+
const { signal } = controller;
|
|
124
|
+
if (signal.aborted)
|
|
125
|
+
throw stopped();
|
|
126
|
+
// A script runs nothing of its own: the abort stops it, so a cancel is confirmed at once.
|
|
127
|
+
this.cancelWith(options, async () => true);
|
|
128
|
+
const { sessionId, turnId } = options;
|
|
129
|
+
// A later turn of the session resumes the id its first one reported.
|
|
130
|
+
options.onNativeSession?.(options.resumeSessionId ?? `scripted-${sessionId}`, {
|
|
131
|
+
resumed: options.resumeSessionId !== undefined,
|
|
132
|
+
});
|
|
133
|
+
const turnIndex = this.turns.get(sessionId) ?? 0;
|
|
134
|
+
this.turns.set(sessionId, turnIndex + 1);
|
|
135
|
+
const { signal: _signal, modelThinking: _modelThinking, onNativeSession: _onNativeSession, onPermissionRequest: _onPermissionRequest, onElicitationRequest: _onElicitationRequest, onExecution: _onExecution, onWarning: _onWarning, sessionId: _sessionId, turnId: _turnId, ...config } = options;
|
|
136
|
+
const steps = this.options.turn({ sessionId, turnId, input, config, turnIndex, signal });
|
|
137
|
+
const iterator = Symbol.asyncIterator in steps ? steps[Symbol.asyncIterator]() : steps[Symbol.iterator]();
|
|
138
|
+
const turn = { input, options, signal, calls: 0 };
|
|
139
|
+
let outcome;
|
|
140
|
+
try {
|
|
141
|
+
for (let n = 1;; n++) {
|
|
142
|
+
// What the step before did is the value of its `yield` in a generator.
|
|
143
|
+
const next = await untilAborted(Promise.resolve(iterator.next(outcome)), signal);
|
|
144
|
+
if (next.done)
|
|
145
|
+
return;
|
|
146
|
+
const step = readStep(next.value, `Step ${n} of turn ${turnId}`);
|
|
147
|
+
const played = yield* this.play(step, turn);
|
|
148
|
+
if ("stop" in played || "end" in step)
|
|
149
|
+
return;
|
|
150
|
+
outcome = played.outcome;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
// Not awaited: a cancelled turn may have left a `next()` the test never releases.
|
|
155
|
+
void Promise.resolve(iterator.return?.()).catch(() => { });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async *play(step, turn) {
|
|
159
|
+
const { options, signal } = turn;
|
|
160
|
+
// A hang takes its `stopTakes` whenever the cancel came: a product's test cancels without a sleep.
|
|
161
|
+
if (signal.aborted && !("hang" in step))
|
|
162
|
+
throw stopped();
|
|
163
|
+
if ("say" in step)
|
|
164
|
+
yield { type: "text", text: step.say };
|
|
165
|
+
else if ("stream" in step) {
|
|
166
|
+
for (const [i, word] of words(step.stream).entries()) {
|
|
167
|
+
if (i > 0 && step.every)
|
|
168
|
+
await sleep(step.every, signal);
|
|
169
|
+
yield { type: "stream", text: word };
|
|
170
|
+
}
|
|
171
|
+
yield { type: "streamed" };
|
|
172
|
+
}
|
|
173
|
+
else if ("tool" in step) {
|
|
174
|
+
const toolCallId = `${options.turnId}-call-${++turn.calls}`;
|
|
175
|
+
const input = step.input ?? {};
|
|
176
|
+
const meta = {
|
|
177
|
+
...(step.kind && { kind: step.kind }),
|
|
178
|
+
...(step.mcp && { mcp: step.mcp }),
|
|
179
|
+
...(step.command !== undefined && { command: step.command }),
|
|
180
|
+
...(step.url !== undefined && { url: step.url }),
|
|
181
|
+
...(step.locations && { locations: step.locations }),
|
|
182
|
+
};
|
|
183
|
+
yield { type: "tool", toolCallId, toolName: step.tool, input, ...meta };
|
|
184
|
+
const allowed = step.ask
|
|
185
|
+
? await this.permit(options, signal, {
|
|
186
|
+
toolCallId,
|
|
187
|
+
toolName: step.tool,
|
|
188
|
+
input,
|
|
189
|
+
...meta,
|
|
190
|
+
...(step.reason !== undefined && { reason: step.reason }),
|
|
191
|
+
})
|
|
192
|
+
: { input };
|
|
193
|
+
if ("cancelled" in allowed)
|
|
194
|
+
return yield* cancel();
|
|
195
|
+
if ("error" in allowed) {
|
|
196
|
+
yield { type: "tool-result", toolCallId, error: allowed.error };
|
|
197
|
+
return done(allowed);
|
|
198
|
+
}
|
|
199
|
+
// What the part completes or fails with, and so what the step's yield gives back.
|
|
200
|
+
const metadata = step.metadata && { metadata: step.metadata };
|
|
201
|
+
const result = step.error !== undefined
|
|
202
|
+
? { error: step.error, ...metadata }
|
|
203
|
+
: {
|
|
204
|
+
output: step.output ?? "",
|
|
205
|
+
...(step.content && { content: step.content }),
|
|
206
|
+
...metadata,
|
|
207
|
+
};
|
|
208
|
+
yield {
|
|
209
|
+
type: "tool-result",
|
|
210
|
+
toolCallId,
|
|
211
|
+
...(allowed.input !== input && { input: allowed.input }),
|
|
212
|
+
...result,
|
|
213
|
+
};
|
|
214
|
+
return done(result);
|
|
215
|
+
}
|
|
216
|
+
else if ("call" in step) {
|
|
217
|
+
const { server, tool } = step.call;
|
|
218
|
+
const toolCallId = `${options.turnId}-call-${++turn.calls}`;
|
|
219
|
+
const input = step.call.arguments ?? {};
|
|
220
|
+
const mcp = { server, tool };
|
|
221
|
+
// Checked before the part opens: a step that cannot run fails the turn.
|
|
222
|
+
const callable = await callableServer(server, options.mcpServers);
|
|
223
|
+
yield { type: "tool", toolCallId, toolName: tool, input, mcp };
|
|
224
|
+
const allowed = step.ask
|
|
225
|
+
? await this.permit(options, signal, { toolCallId, toolName: tool, input, mcp })
|
|
226
|
+
: { input };
|
|
227
|
+
if ("cancelled" in allowed)
|
|
228
|
+
return yield* cancel();
|
|
229
|
+
if ("error" in allowed) {
|
|
230
|
+
yield { type: "tool-result", toolCallId, error: allowed.error };
|
|
231
|
+
return done(allowed);
|
|
232
|
+
}
|
|
233
|
+
const called = await callMcpTool(callable, { tool, arguments: allowed.input }, signal);
|
|
234
|
+
const result = called.isError
|
|
235
|
+
? { error: called.output }
|
|
236
|
+
: {
|
|
237
|
+
output: called.output,
|
|
238
|
+
...(called.content && { content: called.content }),
|
|
239
|
+
...(called.metadata && { metadata: called.metadata }),
|
|
240
|
+
};
|
|
241
|
+
yield {
|
|
242
|
+
type: "tool-result",
|
|
243
|
+
toolCallId,
|
|
244
|
+
...(allowed.input !== input && { input: allowed.input }),
|
|
245
|
+
...result,
|
|
246
|
+
};
|
|
247
|
+
return done(result);
|
|
248
|
+
}
|
|
249
|
+
else if ("ask" in step) {
|
|
250
|
+
// As Claude and Codex do: a client that answers no questions tells the agent so, and the turn goes on.
|
|
251
|
+
if (!options.onElicitationRequest) {
|
|
252
|
+
yield { type: "text", text: NO_ANSWERS };
|
|
253
|
+
return done();
|
|
254
|
+
}
|
|
255
|
+
const answer = await options.onElicitationRequest(questionRequest(step.ask), { signal });
|
|
256
|
+
if (signal.aborted)
|
|
257
|
+
throw stopped();
|
|
258
|
+
yield { type: "text", text: JSON.stringify(answer) };
|
|
259
|
+
return done({ answer });
|
|
260
|
+
}
|
|
261
|
+
else if ("echo" in step) {
|
|
262
|
+
yield {
|
|
263
|
+
type: "text",
|
|
264
|
+
text: step.echo === "input" ? inputToText(turn.input) : echoConfig(options),
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
else if ("wait" in step)
|
|
268
|
+
await sleep(step.wait, signal);
|
|
269
|
+
else if ("hang" in step) {
|
|
270
|
+
await new Promise((resolve) => onAbort(signal, resolve));
|
|
271
|
+
// A harness slow to stop: the cancel is confirmed, the turn ends later.
|
|
272
|
+
if (step.stopTakes)
|
|
273
|
+
await sleep(step.stopTakes);
|
|
274
|
+
throw stopped();
|
|
275
|
+
}
|
|
276
|
+
else if ("fail" in step) {
|
|
277
|
+
throw step.category
|
|
278
|
+
? new AgentServerError(step.fail, "scriptedFailure", step.category)
|
|
279
|
+
: new Error(step.fail);
|
|
280
|
+
}
|
|
281
|
+
else if ("end" in step) {
|
|
282
|
+
yield {
|
|
283
|
+
type: "end",
|
|
284
|
+
...(step.stopReason && { stopReason: step.stopReason }),
|
|
285
|
+
...(step.usage && { usage: step.usage }),
|
|
286
|
+
...(step.cost !== undefined && { cost: step.cost }),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
return done();
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Ask the engine's permission broker about a call: the input to run (the
|
|
293
|
+
* approved edit, when the answer edited it), why it was rejected, or that
|
|
294
|
+
* the user cancelled the turn.
|
|
295
|
+
*/
|
|
296
|
+
async permit(options, signal, call) {
|
|
297
|
+
const { input, ...toolCall } = call;
|
|
298
|
+
if (!options.onPermissionRequest)
|
|
299
|
+
return { error: "No one could approve this tool call." };
|
|
300
|
+
const decision = await options.onPermissionRequest({ ...toolCall, rawInput: input }, { signal });
|
|
301
|
+
if (signal.aborted)
|
|
302
|
+
throw stopped();
|
|
303
|
+
// Answered as a cancel, with no cancel of the turn asked for: the harness
|
|
304
|
+
// stops and says so, as Claude and Codex do (a throw would read as an error).
|
|
305
|
+
if (decision.decision === "cancel")
|
|
306
|
+
return { cancelled: true };
|
|
307
|
+
if (decision.decision === "deny") {
|
|
308
|
+
const why = decision.message ?? decision.reason;
|
|
309
|
+
return { error: why ? `${REJECTED} ${why}` : REJECTED, rejected: true };
|
|
310
|
+
}
|
|
311
|
+
return { input: decision.updatedInput ?? input };
|
|
312
|
+
}
|
|
313
|
+
async release(sessionId) {
|
|
314
|
+
this.turns.delete(sessionId);
|
|
315
|
+
await super.release(sessionId);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
/** The turn's config, as `echo: "config"` says it: MCP servers by name, `env` by its keys alone. */
|
|
319
|
+
function echoConfig(options) {
|
|
320
|
+
const { model, thinkingLevel, cwd, additionalDirectories, systemPromptAppend, permissionMode } = options;
|
|
321
|
+
return JSON.stringify({
|
|
322
|
+
model,
|
|
323
|
+
thinkingLevel,
|
|
324
|
+
cwd,
|
|
325
|
+
additionalDirectories,
|
|
326
|
+
systemPromptAppend,
|
|
327
|
+
permissionMode,
|
|
328
|
+
mcpServers: options.mcpServers && Object.keys(options.mcpServers),
|
|
329
|
+
env: options.env && Object.keys(options.env),
|
|
330
|
+
});
|
|
331
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { readStep } from "./steps.js";
|
|
4
|
+
/**
|
|
5
|
+
* Steps played one turn at a time: `end` closes a turn, and the next plays on
|
|
6
|
+
* from the step after it.
|
|
7
|
+
*/
|
|
8
|
+
class Queue {
|
|
9
|
+
steps;
|
|
10
|
+
name;
|
|
11
|
+
/** A turn is playing: another that starts now would take its steps. */
|
|
12
|
+
playing = false;
|
|
13
|
+
at;
|
|
14
|
+
saved;
|
|
15
|
+
kept;
|
|
16
|
+
constructor(steps, name, options = {}) {
|
|
17
|
+
this.steps = steps;
|
|
18
|
+
this.name = name;
|
|
19
|
+
const at = options.at ?? 0;
|
|
20
|
+
// An engine stopped inside a turn left that turn unended: it is skipped,
|
|
21
|
+
// as a turn that stops early is.
|
|
22
|
+
const inTurn = at > 0 && at < steps.length && !("end" in steps[at - 1]);
|
|
23
|
+
this.at = inTurn ? this.throughEnd(at) : at;
|
|
24
|
+
this.saved = options.saved ?? (() => { });
|
|
25
|
+
this.kept = options.kept;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* One turn's steps. A turn that stops before its `end` (a `fail`, a
|
|
29
|
+
* cancel) skips the rest of its steps through that `end`, so the next turn
|
|
30
|
+
* plays its own. A turn that starts while another plays fails.
|
|
31
|
+
*/
|
|
32
|
+
*turn() {
|
|
33
|
+
if (this.playing) {
|
|
34
|
+
throw new Error(`A turn is already playing ${this.name}: sessions that run at once need scriptedBySession`);
|
|
35
|
+
}
|
|
36
|
+
this.playing = true;
|
|
37
|
+
let ended = false;
|
|
38
|
+
try {
|
|
39
|
+
if (this.at >= this.steps.length) {
|
|
40
|
+
ended = true;
|
|
41
|
+
const kept = this.kept ? `; its position is kept in ${this.kept}` : "";
|
|
42
|
+
throw new Error(`The script ran out: ${this.name} has no step left for this turn${kept}`);
|
|
43
|
+
}
|
|
44
|
+
while (this.at < this.steps.length) {
|
|
45
|
+
const step = this.steps[this.at];
|
|
46
|
+
this.move(this.at + 1);
|
|
47
|
+
ended = "end" in step;
|
|
48
|
+
yield step;
|
|
49
|
+
if (ended)
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
ended = true;
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
if (!ended)
|
|
56
|
+
this.move(this.throughEnd(this.at));
|
|
57
|
+
this.playing = false;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** The position after the next `end` from `from`, or the queue's end. */
|
|
61
|
+
throughEnd(from) {
|
|
62
|
+
let at = from;
|
|
63
|
+
while (at < this.steps.length && !("end" in this.steps[at]))
|
|
64
|
+
at++;
|
|
65
|
+
return Math.min(at + 1, this.steps.length);
|
|
66
|
+
}
|
|
67
|
+
move(at) {
|
|
68
|
+
this.at = at;
|
|
69
|
+
this.saved(at);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const readAll = (steps, name) => steps.map((step, i) => readStep(step, `Step ${i + 1} of ${name}`));
|
|
73
|
+
/**
|
|
74
|
+
* One queue of steps for the whole runtime, consumed turn by turn whatever
|
|
75
|
+
* the session, one turn at a time: `{ end: true }` closes a turn, and the next
|
|
76
|
+
* turn plays on from the step after it. A turn that finds the queue empty
|
|
77
|
+
* fails, saying the script ran out, and so does one that starts while another
|
|
78
|
+
* plays (`scriptedBySession` serves sessions that run at once). Every step is
|
|
79
|
+
* read here: one the schema does not know throws now.
|
|
80
|
+
*/
|
|
81
|
+
export function scriptedQueue(steps) {
|
|
82
|
+
const queue = new Queue(readAll(steps, "the script"), "the script");
|
|
83
|
+
return () => queue.turn();
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* `scriptedQueue`, read from a JSONL file: one step per line (blank lines
|
|
87
|
+
* skipped), a bad line refused by its number. It plays from its start each
|
|
88
|
+
* time an engine reads it and writes nothing, unless `position` names a file
|
|
89
|
+
* that keeps how far it has played: then an engine restarted mid-script goes
|
|
90
|
+
* on where the last one stopped (inside a turn, from the next turn), and a
|
|
91
|
+
* changed script plays from its start.
|
|
92
|
+
*/
|
|
93
|
+
export function scriptedFile(path, options = {}) {
|
|
94
|
+
const text = readFileSync(path, "utf8");
|
|
95
|
+
const steps = text.split("\n").flatMap((line, i) => {
|
|
96
|
+
if (!line.trim())
|
|
97
|
+
return [];
|
|
98
|
+
const where = `Line ${i + 1} of ${path}`;
|
|
99
|
+
let value;
|
|
100
|
+
try {
|
|
101
|
+
value = JSON.parse(line);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
throw new Error(`${where} is not JSON: ${line.slice(0, 200)}`);
|
|
105
|
+
}
|
|
106
|
+
return [readStep(value, where)];
|
|
107
|
+
});
|
|
108
|
+
const { position } = options;
|
|
109
|
+
if (!position) {
|
|
110
|
+
const queue = new Queue(steps, path);
|
|
111
|
+
return () => queue.turn();
|
|
112
|
+
}
|
|
113
|
+
const sha256 = createHash("sha256").update(text).digest("hex");
|
|
114
|
+
const queue = new Queue(steps, path, {
|
|
115
|
+
at: playedSoFar(position, sha256, steps.length),
|
|
116
|
+
saved: (at) => writeFileSync(position, `${JSON.stringify({ sha256, at })}\n`),
|
|
117
|
+
kept: position,
|
|
118
|
+
});
|
|
119
|
+
return () => queue.turn();
|
|
120
|
+
}
|
|
121
|
+
/** Where an earlier engine left this script, or its start. */
|
|
122
|
+
function playedSoFar(file, sha256, length) {
|
|
123
|
+
if (!existsSync(file))
|
|
124
|
+
return 0;
|
|
125
|
+
try {
|
|
126
|
+
const saved = JSON.parse(readFileSync(file, "utf8"));
|
|
127
|
+
const at = saved.at;
|
|
128
|
+
return saved.sha256 === sha256 && Number.isInteger(at) ? Math.min(at, length) : 0;
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* A queue per session id, as `scriptedQueue` plays one; a session not named
|
|
136
|
+
* plays `otherwise` from its start, in a queue of its own. A session with
|
|
137
|
+
* neither fails its turn.
|
|
138
|
+
*/
|
|
139
|
+
export function scriptedBySession(scripts, otherwise) {
|
|
140
|
+
const named = new Map(Object.entries(scripts).map(([id, steps]) => [id, readAll(steps, `session ${id}'s script`)]));
|
|
141
|
+
const fallback = otherwise && readAll(otherwise, "the default script");
|
|
142
|
+
const queues = new Map();
|
|
143
|
+
return ({ sessionId }) => {
|
|
144
|
+
let queue = queues.get(sessionId);
|
|
145
|
+
if (!queue) {
|
|
146
|
+
const steps = named.get(sessionId) ?? fallback;
|
|
147
|
+
if (!steps)
|
|
148
|
+
throw new Error(`No script for session ${sessionId}, and no default`);
|
|
149
|
+
queue = new Queue(steps, `session ${sessionId}'s script`);
|
|
150
|
+
queues.set(sessionId, queue);
|
|
151
|
+
}
|
|
152
|
+
return queue.turn();
|
|
153
|
+
};
|
|
154
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { ElicitationQuestionSchema, ErrorCategorySchema, StopReasonSchema, TokenUsageSchema, ToolKindSchema, ToolResultContentSchema, } from "../../../protocol/index.js";
|
|
3
|
+
const Input = z.record(z.string(), z.unknown());
|
|
4
|
+
const Ms = z.number().int().nonnegative();
|
|
5
|
+
/**
|
|
6
|
+
* One step of a script: plain JSON, so a JSONL file is a script. Each form is
|
|
7
|
+
* strict, so a misspelt step or field is refused when the script is read,
|
|
8
|
+
* never skipped.
|
|
9
|
+
*/
|
|
10
|
+
export const ScriptStepSchema = z.union([
|
|
11
|
+
/** A complete text part. */
|
|
12
|
+
z.strictObject({ say: z.string() }),
|
|
13
|
+
/** A text part streamed a word at a time, `every` ms apart (0 by default), then its snapshot. */
|
|
14
|
+
z.strictObject({ stream: z.string(), every: Ms.optional() }),
|
|
15
|
+
/**
|
|
16
|
+
* A tool call the script answers itself: the part opens in progress and
|
|
17
|
+
* completes with `output` (empty by default), or fails with `error`. With
|
|
18
|
+
* `ask`, the engine's permission broker is asked first; a rejection fails
|
|
19
|
+
* the part as a rejected call and the turn goes on.
|
|
20
|
+
*
|
|
21
|
+
* What it acts on (`command`, `url`, `locations`) is on the part and on its
|
|
22
|
+
* request; `reason`, why it asks, is on the request only, so it needs
|
|
23
|
+
* `ask`. Its result's `metadata` (a command's `exitCode`) is kept completed
|
|
24
|
+
* or failed; its `content` (a `diff`) only when it completes, as a failed
|
|
25
|
+
* call shows nothing (LLP 0002, A tool call says what it acts on).
|
|
26
|
+
*/
|
|
27
|
+
z
|
|
28
|
+
.strictObject({
|
|
29
|
+
tool: z.string().min(1),
|
|
30
|
+
input: Input.optional(),
|
|
31
|
+
kind: ToolKindSchema.optional(),
|
|
32
|
+
mcp: z.strictObject({ server: z.string(), tool: z.string() }).optional(),
|
|
33
|
+
command: z.string().optional(),
|
|
34
|
+
url: z.string().optional(),
|
|
35
|
+
locations: z
|
|
36
|
+
.array(z.strictObject({ path: z.string(), line: z.number().optional() }))
|
|
37
|
+
.optional(),
|
|
38
|
+
reason: z.string().optional(),
|
|
39
|
+
output: z.string().optional(),
|
|
40
|
+
error: z.string().optional(),
|
|
41
|
+
content: z.array(ToolResultContentSchema).optional(),
|
|
42
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
43
|
+
ask: z.literal(true).optional(),
|
|
44
|
+
})
|
|
45
|
+
.refine((step) => step.reason === undefined || step.ask, {
|
|
46
|
+
message: "`reason` is said on a permission request: it needs `ask`",
|
|
47
|
+
}),
|
|
48
|
+
/**
|
|
49
|
+
* A real call to a tool of the turn's own MCP server `server` (an `http`
|
|
50
|
+
* one), its result in the tool part. With `ask`, as for `tool`.
|
|
51
|
+
*/
|
|
52
|
+
z.strictObject({
|
|
53
|
+
call: z.strictObject({ server: z.string(), tool: z.string(), arguments: Input.optional() }),
|
|
54
|
+
ask: z.literal(true).optional(),
|
|
55
|
+
}),
|
|
56
|
+
/** Questions to the person through the engine's question broker; the answer is said back as JSON. */
|
|
57
|
+
z.strictObject({ ask: z.array(ElicitationQuestionSchema).min(1) }),
|
|
58
|
+
/** Says the turn's input as the model would read it, or the turn's config as JSON. */
|
|
59
|
+
z.strictObject({ echo: z.enum(["input", "config"]) }),
|
|
60
|
+
/** A pause of this many ms. */
|
|
61
|
+
z.strictObject({ wait: Ms }),
|
|
62
|
+
/** Runs until the turn is cancelled, then `stopTakes` ms more before it stops, also when the cancel came first. */
|
|
63
|
+
z.strictObject({ hang: z.literal(true), stopTakes: Ms.optional() }),
|
|
64
|
+
/**
|
|
65
|
+
* Ends the turn in an error with this message: of `category` when given,
|
|
66
|
+
* else of whatever the engine's classifier makes of the text.
|
|
67
|
+
*/
|
|
68
|
+
z.strictObject({ fail: z.string(), category: ErrorCategorySchema.optional() }),
|
|
69
|
+
/**
|
|
70
|
+
* Ends the turn, `end_turn` with zero usage by default. In a queue of
|
|
71
|
+
* steps it is the turn's boundary: the next turn plays from the step after.
|
|
72
|
+
*/
|
|
73
|
+
z.strictObject({
|
|
74
|
+
end: z.literal(true),
|
|
75
|
+
stopReason: StopReasonSchema.optional(),
|
|
76
|
+
usage: TokenUsageSchema.optional(),
|
|
77
|
+
cost: z.number().nonnegative().optional(),
|
|
78
|
+
}),
|
|
79
|
+
]);
|
|
80
|
+
/** A step, read, or an error that says where it is and what is wrong with it. */
|
|
81
|
+
export function readStep(step, where) {
|
|
82
|
+
const parsed = ScriptStepSchema.safeParse(step);
|
|
83
|
+
if (parsed.success)
|
|
84
|
+
return parsed.data;
|
|
85
|
+
const shown = JSON.stringify(step) ?? String(step);
|
|
86
|
+
throw new Error(`${where} is not a script step: ${shown.length > 200 ? `${shown.slice(0, 200)}…` : shown}`);
|
|
87
|
+
}
|