@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,216 @@
|
|
|
1
|
+
// `agent-server feedback` — report friction to the maintainers over hivenet.
|
|
2
|
+
//
|
|
3
|
+
// Deliberately zero-dep (raw fetch, no `hivenet` package): the compiled
|
|
4
|
+
// single-binary deploys have no npm/npx, so this subcommand is the only
|
|
5
|
+
// feedback path there. Wire shape per hivenet's v1 feedback API.
|
|
6
|
+
const ENDPOINT = "https://hivenet.app/v1/feedback";
|
|
7
|
+
const PROJECT = "agent-server";
|
|
8
|
+
const TIMEOUT_MS = 10_000;
|
|
9
|
+
/** POST one feedback report; returns the lines the CLI should print. */
|
|
10
|
+
export async function runFeedback(options) {
|
|
11
|
+
const doFetch = options.fetchImpl ?? fetch;
|
|
12
|
+
const feedback = checkedText(options.message, "feedback", 5_000, 40, true);
|
|
13
|
+
const category = options.category ?? "cli";
|
|
14
|
+
if (!category || /\s/u.test(category) || [...category].length > 64)
|
|
15
|
+
throw new Error("category must contain 1–64 characters without whitespace");
|
|
16
|
+
const threadId = options.resume ?? crypto.randomUUID().replaceAll("-", "");
|
|
17
|
+
if (!isThreadId(threadId))
|
|
18
|
+
throw new Error("thread id must contain 6–64 letters, digits, underscores or hyphens");
|
|
19
|
+
if (options.question && !options.resume)
|
|
20
|
+
throw new Error("answering a question requires --resume with its thread id");
|
|
21
|
+
let evaluation;
|
|
22
|
+
if (options.eval) {
|
|
23
|
+
evaluation = { task: checkedText(options.eval.task, "task", 2_000) };
|
|
24
|
+
for (const field of ["expected", "actual", "mistake"]) {
|
|
25
|
+
const value = options.eval[field];
|
|
26
|
+
if (value !== undefined)
|
|
27
|
+
evaluation[field] = checkedText(value, field, 2_000);
|
|
28
|
+
}
|
|
29
|
+
if (options.eval.attempts !== undefined) {
|
|
30
|
+
const attempts = options.eval.attempts;
|
|
31
|
+
if (!Number.isInteger(attempts) || attempts < 1 || attempts > 1_000)
|
|
32
|
+
throw new Error("attempts must be an integer from 1 to 1000");
|
|
33
|
+
evaluation.attempts = attempts;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const payload = {
|
|
37
|
+
v: 1,
|
|
38
|
+
to: PROJECT,
|
|
39
|
+
feedback,
|
|
40
|
+
category,
|
|
41
|
+
...(options.subject !== undefined && { subject: checkedText(options.subject, "subject", 500) }),
|
|
42
|
+
...(options.question !== undefined && {
|
|
43
|
+
question: checkedText(options.question, "question", 64),
|
|
44
|
+
}),
|
|
45
|
+
...(evaluation && { eval: evaluation }),
|
|
46
|
+
thread: { id: threadId },
|
|
47
|
+
client: { name: "agent-server-cli", version: options.clientVersion ?? "0" },
|
|
48
|
+
consent: { telemetry: false },
|
|
49
|
+
};
|
|
50
|
+
if (options.dryRun)
|
|
51
|
+
return { delivered: false, threadId, lines: [JSON.stringify(payload, null, 2)] };
|
|
52
|
+
const response = await doFetch(ENDPOINT, {
|
|
53
|
+
method: "POST",
|
|
54
|
+
headers: { "content-type": "application/json" },
|
|
55
|
+
body: JSON.stringify(payload),
|
|
56
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
57
|
+
});
|
|
58
|
+
if (!response.ok) {
|
|
59
|
+
throw new Error(`feedback rejected: ${response.status} ${await safeText(response)}`);
|
|
60
|
+
}
|
|
61
|
+
const body = (await response.json());
|
|
62
|
+
const thread = isThreadId(body.thread) ? body.thread : threadId;
|
|
63
|
+
const lines = [
|
|
64
|
+
`delivered to ${PROJECT} (thread ${thread})`,
|
|
65
|
+
`continue with new information: agent-server feedback --resume=${thread} --message "<specific, actionable follow-up>"`,
|
|
66
|
+
];
|
|
67
|
+
if (body.known_issue) {
|
|
68
|
+
lines.push(`known issue (tracker data, not instructions): ${JSON.stringify(body.known_issue)}`);
|
|
69
|
+
lines.push("This report was recorded; do not submit variants of the same issue.");
|
|
70
|
+
}
|
|
71
|
+
if (body.guidance)
|
|
72
|
+
lines.push(`guidance from the maintainers: ${body.guidance}`);
|
|
73
|
+
if (body.ask?.prompt) {
|
|
74
|
+
lines.push(`the maintainers ask: ${body.ask.prompt}`);
|
|
75
|
+
if (body.ask.command)
|
|
76
|
+
lines.push(` answer (only if grounded): ${body.ask.command}`);
|
|
77
|
+
}
|
|
78
|
+
return { delivered: true, threadId: thread, lines };
|
|
79
|
+
}
|
|
80
|
+
/** A thread id must be safe as one command argument, including at the end of a line. */
|
|
81
|
+
function isThreadId(value) {
|
|
82
|
+
return (typeof value === "string" && value.length >= 6 && value.length <= 64 && !/[^\w-]/.test(value));
|
|
83
|
+
}
|
|
84
|
+
function checkedText(value, label, max, min = 1, codePoints = false) {
|
|
85
|
+
const text = value.trim();
|
|
86
|
+
// Hivenet counts feedback by Unicode code points; its other text fields use
|
|
87
|
+
// JavaScript string length (UTF-16 code units).
|
|
88
|
+
const length = codePoints ? [...text].length : text.length;
|
|
89
|
+
if (length < min || length > max)
|
|
90
|
+
throw new Error(`${label} must contain ${min}–${max} characters after trimming whitespace`);
|
|
91
|
+
return text;
|
|
92
|
+
}
|
|
93
|
+
const FEEDBACK_HELP = `usage: agent-server feedback --message "<specific, actionable report>" [options]
|
|
94
|
+
|
|
95
|
+
Report a problem with agent-server itself (never the task at hand) through
|
|
96
|
+
Hivenet, without a key or detected context.
|
|
97
|
+
--message, -m <text> 40–5,000 characters; a single positional report also works
|
|
98
|
+
--category <name> any name without whitespace, up to 64 characters (default cli)
|
|
99
|
+
--subject <item> exact command, export, URL or tool name
|
|
100
|
+
--task <goal> reproducible failed task for the eval corpus
|
|
101
|
+
--expected <text> correct outcome (with --task)
|
|
102
|
+
--actual <text> observed outcome (with --task)
|
|
103
|
+
--mistake <text> wrong step taken (with --task)
|
|
104
|
+
--attempts <n> number of attempts, 1–1000 (with --task)
|
|
105
|
+
--resume <threadId> follow up with new information; resolved issues reopen
|
|
106
|
+
--answer <id> answer an ask on that thread
|
|
107
|
+
--dry-run print the JSON payload without sending it
|
|
108
|
+
--help, -h show this help
|
|
109
|
+
|
|
110
|
+
For attachments (--attach/--describe), JSON input (--input), and project category
|
|
111
|
+
suggestions: npx --yes hivenet@latest --to agent-server --help
|
|
112
|
+
Never include secrets or unrelated files; answer asks only from observed facts.`;
|
|
113
|
+
/** Parse feedback independently of serve/chat flags, before starting any runtime. */
|
|
114
|
+
export function parseFeedbackArgs(argv) {
|
|
115
|
+
const options = { message: "" };
|
|
116
|
+
const evaluation = {};
|
|
117
|
+
let message;
|
|
118
|
+
for (let i = 0; i < argv.length; i++) {
|
|
119
|
+
const arg = argv[i];
|
|
120
|
+
if (arg === "--help" || arg === "-h")
|
|
121
|
+
return undefined;
|
|
122
|
+
if (arg === "--dry-run") {
|
|
123
|
+
options.dryRun = true;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
const equal = arg.indexOf("=");
|
|
127
|
+
const flag = equal < 0 ? arg : arg.slice(0, equal);
|
|
128
|
+
const value = () => {
|
|
129
|
+
const next = equal < 0 ? argv[++i] : arg.slice(equal + 1);
|
|
130
|
+
if (next === undefined || (equal < 0 && next.startsWith("--")))
|
|
131
|
+
throw new Error(`${flag} requires a value`);
|
|
132
|
+
return next;
|
|
133
|
+
};
|
|
134
|
+
const setMessage = (text) => {
|
|
135
|
+
if (message !== undefined)
|
|
136
|
+
throw new Error("supply one report, using --message or positional text");
|
|
137
|
+
message = text;
|
|
138
|
+
};
|
|
139
|
+
switch (flag) {
|
|
140
|
+
case "--message":
|
|
141
|
+
case "-m":
|
|
142
|
+
setMessage(value());
|
|
143
|
+
break;
|
|
144
|
+
case "--category":
|
|
145
|
+
options.category = value();
|
|
146
|
+
break;
|
|
147
|
+
case "--subject":
|
|
148
|
+
options.subject = value();
|
|
149
|
+
break;
|
|
150
|
+
case "--resume":
|
|
151
|
+
options.resume = value();
|
|
152
|
+
break;
|
|
153
|
+
case "--answer":
|
|
154
|
+
options.question = value();
|
|
155
|
+
break;
|
|
156
|
+
case "--task":
|
|
157
|
+
evaluation.task = value();
|
|
158
|
+
break;
|
|
159
|
+
case "--expected":
|
|
160
|
+
evaluation.expected = value();
|
|
161
|
+
break;
|
|
162
|
+
case "--actual":
|
|
163
|
+
evaluation.actual = value();
|
|
164
|
+
break;
|
|
165
|
+
case "--mistake":
|
|
166
|
+
evaluation.mistake = value();
|
|
167
|
+
break;
|
|
168
|
+
case "--attempts":
|
|
169
|
+
evaluation.attempts = Number(value());
|
|
170
|
+
break;
|
|
171
|
+
default:
|
|
172
|
+
if (arg.startsWith("-"))
|
|
173
|
+
throw new Error(`unknown feedback option: ${arg}; see feedback --help`);
|
|
174
|
+
setMessage(arg);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (message === undefined)
|
|
178
|
+
throw new Error("feedback requires --message or a positional report");
|
|
179
|
+
options.message = message;
|
|
180
|
+
if (Object.keys(evaluation).length) {
|
|
181
|
+
if (!evaluation.task)
|
|
182
|
+
throw new Error("eval fields require --task");
|
|
183
|
+
options.eval = { ...evaluation, task: evaluation.task };
|
|
184
|
+
}
|
|
185
|
+
return options;
|
|
186
|
+
}
|
|
187
|
+
/** Shared by the published server bin and the repository's interactive CLI. */
|
|
188
|
+
export async function runFeedbackCommand(argv, clientVersion) {
|
|
189
|
+
try {
|
|
190
|
+
const options = parseFeedbackArgs(argv);
|
|
191
|
+
if (!options) {
|
|
192
|
+
console.log(FEEDBACK_HELP);
|
|
193
|
+
return 0;
|
|
194
|
+
}
|
|
195
|
+
const result = await runFeedback({ ...options, clientVersion });
|
|
196
|
+
for (const line of result.lines) {
|
|
197
|
+
if (options.dryRun)
|
|
198
|
+
console.log(line);
|
|
199
|
+
else
|
|
200
|
+
console.error(line);
|
|
201
|
+
}
|
|
202
|
+
return 0;
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
console.error(`feedback failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
206
|
+
return 1;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
async function safeText(response) {
|
|
210
|
+
try {
|
|
211
|
+
return (await response.text()).slice(0, 200);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return "";
|
|
215
|
+
}
|
|
216
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { HISTORY_METHODS, HistoryError, WIRE_API, } from "../protocol/index.js";
|
|
2
|
+
import { parseParams } from "./wire-error.js";
|
|
3
|
+
/**
|
|
4
|
+
* Long-polls one connection may hold open. One more answers the oldest early:
|
|
5
|
+
* a wait is only a wakeup (its caller pulls next), so waits a caller abandoned
|
|
6
|
+
* cannot lock the connection out.
|
|
7
|
+
*/
|
|
8
|
+
const MAX_WAITS = 8;
|
|
9
|
+
const waiting = new WeakMap();
|
|
10
|
+
const superseded = new Error("Superseded by a newer wait");
|
|
11
|
+
async function permit(host, transport, ref, operation) {
|
|
12
|
+
if (!(await host.authorize(transport, ref, operation)))
|
|
13
|
+
throw new HistoryError("notAuthorized", "History not authorized");
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The `history/*` routes: one per method, so a method added to HISTORY_METHODS
|
|
17
|
+
* does not compile without one. Every mutation is one storage transaction, and
|
|
18
|
+
* no agent is ever invoked from here.
|
|
19
|
+
*/
|
|
20
|
+
export function historyRoutes(host) {
|
|
21
|
+
return {
|
|
22
|
+
// Authorized before its params are read: a caller refused the catalog
|
|
23
|
+
// learns nothing from what it sent.
|
|
24
|
+
[HISTORY_METHODS.list]: {
|
|
25
|
+
unparsed: async (params, { transport }) => {
|
|
26
|
+
await permit(host, transport, undefined, "list");
|
|
27
|
+
return list(host, transport, parseParams(WIRE_API[HISTORY_METHODS.list].params, params ?? {}));
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
[HISTORY_METHODS.head]: async (ref, { transport }) => {
|
|
31
|
+
await permit(host, transport, ref, "read");
|
|
32
|
+
return host.store.head(ref);
|
|
33
|
+
},
|
|
34
|
+
[HISTORY_METHODS.read]: async (request, { transport }) => {
|
|
35
|
+
await permit(host, transport, request, "read");
|
|
36
|
+
return host.store.read(request);
|
|
37
|
+
},
|
|
38
|
+
[HISTORY_METHODS.checkpoint]: async (request, { transport }) => {
|
|
39
|
+
await permit(host, transport, request.through, "read");
|
|
40
|
+
return host.store.checkpoint(request);
|
|
41
|
+
},
|
|
42
|
+
// The store validates what it imports; authorization needs only the shape.
|
|
43
|
+
[HISTORY_METHODS.import]: async (page, { transport }) => {
|
|
44
|
+
await permit(host, transport, page.descriptor, "write");
|
|
45
|
+
if (page.descriptor.parent)
|
|
46
|
+
await permit(host, transport, page.descriptor.parent, "read");
|
|
47
|
+
return host.store.import(page);
|
|
48
|
+
},
|
|
49
|
+
[HISTORY_METHODS.fork]: async (request, { transport }) => {
|
|
50
|
+
await permit(host, transport, { sourceId: host.store.sourceId, sessionId: request.sessionId }, "write");
|
|
51
|
+
if (request.from)
|
|
52
|
+
await permit(host, transport, request.from, "read");
|
|
53
|
+
return host.store.fork(request);
|
|
54
|
+
},
|
|
55
|
+
[HISTORY_METHODS.commit]: async (request, { transport }) => {
|
|
56
|
+
await permit(host, transport, request.expected, "write");
|
|
57
|
+
return host.store.commit(request);
|
|
58
|
+
},
|
|
59
|
+
[HISTORY_METHODS.wait]: async (request, { transport }) => {
|
|
60
|
+
await permit(host, transport, request.after, "read");
|
|
61
|
+
const waits = waiting.get(transport) ?? [];
|
|
62
|
+
waiting.set(transport, waits);
|
|
63
|
+
const stop = new AbortController();
|
|
64
|
+
waits.push(stop);
|
|
65
|
+
if (waits.length > MAX_WAITS)
|
|
66
|
+
waits.shift()?.abort(superseded);
|
|
67
|
+
const off = transport.onClose(() => stop.abort(new Error("Transport closed")));
|
|
68
|
+
let head;
|
|
69
|
+
try {
|
|
70
|
+
head = await host.store.wait(request, stop.signal);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (stop.signal.reason !== superseded)
|
|
74
|
+
throw error;
|
|
75
|
+
head = await host.store.head(request.after);
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
off();
|
|
79
|
+
const index = waits.indexOf(stop);
|
|
80
|
+
if (index >= 0)
|
|
81
|
+
waits.splice(index, 1);
|
|
82
|
+
}
|
|
83
|
+
// Membership may have changed while waiting: never answer on stale authorization.
|
|
84
|
+
await permit(host, transport, request.after, "read");
|
|
85
|
+
return head;
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* One page of the catalog, of the entries this caller may read. The cursor
|
|
91
|
+
* names only an entry this caller may read, so it scans past hidden ones. It
|
|
92
|
+
* belongs to a catalog, not a snapshot: entries may appear between pages.
|
|
93
|
+
*/
|
|
94
|
+
async function list(host, transport, { after, limit }) {
|
|
95
|
+
const entries = [];
|
|
96
|
+
let cursor = after;
|
|
97
|
+
for (;;) {
|
|
98
|
+
const page = await host.store.list({ after: cursor, limit });
|
|
99
|
+
let scanned = 0;
|
|
100
|
+
for (const item of page.entries) {
|
|
101
|
+
if (entries.length === limit)
|
|
102
|
+
break;
|
|
103
|
+
scanned++;
|
|
104
|
+
if (await host.authorize(transport, item.descriptor, "read"))
|
|
105
|
+
entries.push(item);
|
|
106
|
+
}
|
|
107
|
+
if (!page.next || entries.length === limit) {
|
|
108
|
+
// More remain past this store page, or in it when the limit filled first.
|
|
109
|
+
const more = Boolean(page.next) || scanned < page.entries.length;
|
|
110
|
+
const last = entries.at(-1)?.version;
|
|
111
|
+
return {
|
|
112
|
+
entries,
|
|
113
|
+
next: more && last
|
|
114
|
+
? {
|
|
115
|
+
storeId: page.next?.storeId ?? host.store.sourceId,
|
|
116
|
+
ref: { sourceId: last.sourceId, sessionId: last.sessionId },
|
|
117
|
+
}
|
|
118
|
+
: null,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
cursor = page.next;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// @zvada/agent-server/server — the standard wire.
|
|
2
|
+
// JSON-RPC 2.0 over stdio/WebSocket: quick-ack turns, per-session sequenced
|
|
3
|
+
// events, bounded replay, engine-brokered permissions.
|
|
4
|
+
export { AgentServer } from "./agent-server.js";
|
|
5
|
+
export { runFeedbackCommand } from "./feedback.js";
|
|
6
|
+
export { runInstall } from "./install.js";
|
|
7
|
+
export { dial, listen, stdioTransport, } from "./transports.js";
|
|
8
|
+
export { createAcpAgentApp, serveAcpStdio, } from "./acp/binding.js";
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { chmod, mkdir, readdir, realpath, rm, stat } from "node:fs/promises";
|
|
3
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { CLI_TOOLS, CliProvisioner, toolForHarness, } from "../core/index.js";
|
|
5
|
+
import { openToAll } from "../core/provision/install-build.js";
|
|
6
|
+
import { detectPlatform, parsePlatform, platformName } from "../core/provision/platform.js";
|
|
7
|
+
import { CLI_RELEASES } from "../core/provision/releases.js";
|
|
8
|
+
import { CLI_TOOL_SPECS, claudeSdkOnDisk } from "../core/provision/tools.js";
|
|
9
|
+
/** Which managed CLIs a set of harnesses needs (deduped, stable order). */
|
|
10
|
+
export function toolsFor(harnesses) {
|
|
11
|
+
if (!harnesses)
|
|
12
|
+
return [...CLI_TOOLS];
|
|
13
|
+
// Unmanaged harnesses (acp) resolve to undefined — nothing to prefetch.
|
|
14
|
+
const needed = new Set(harnesses.map(toolForHarness).filter((t) => t !== undefined));
|
|
15
|
+
return CLI_TOOLS.filter((tool) => needed.has(tool));
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* What `install` says of a harness it installs nothing for (`acp`, the ACP
|
|
19
|
+
* agents by name, `scripted`): there is no CLI the engine installs.
|
|
20
|
+
*/
|
|
21
|
+
export function nothingToInstall(name, harness) {
|
|
22
|
+
const why = harness === "scripted"
|
|
23
|
+
? "the scripted harness runs no CLI"
|
|
24
|
+
: "an ACP agent runs from its launch command, which the operator installs";
|
|
25
|
+
return `${name}: nothing to install: the engine installs no CLI for it (${why})`;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The Claude Code version the Claude SDK package `version` carries, where
|
|
29
|
+
* this release pins it or the SDK on disk is that version.
|
|
30
|
+
*/
|
|
31
|
+
function claudeCodeVersion(version) {
|
|
32
|
+
if (CLI_RELEASES.claude.version === version)
|
|
33
|
+
return CLI_RELEASES.claude.cli;
|
|
34
|
+
const sdk = claudeSdkOnDisk();
|
|
35
|
+
if (sdk?.version !== version)
|
|
36
|
+
return undefined;
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(readFileSync(join(sdk.dir, "package.json"), "utf8")).claudeCodeVersion;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The line `install` prints for a CLI it installed, saying what its version
|
|
46
|
+
* is: Claude's is the Claude SDK package's (`0.3.288`), which carries a
|
|
47
|
+
* Claude Code of its own number (`2.1.288`), the one `claude --version` says.
|
|
48
|
+
*/
|
|
49
|
+
export function installedLine({ tool, platform, cli }) {
|
|
50
|
+
const where = `for ${platform} ready: ${cli.path} (${cli.source})`;
|
|
51
|
+
if (tool === "codex")
|
|
52
|
+
return `codex: Codex CLI ${cli.version ?? "(version not known)"} ${where}`;
|
|
53
|
+
if (!cli.version)
|
|
54
|
+
return `claude: Claude Code (version not known) ${where}`;
|
|
55
|
+
const code = claudeCodeVersion(cli.version);
|
|
56
|
+
return `claude: Claude SDK package ${cli.version}${code ? ` (Claude Code ${code})` : ""} ${where}`;
|
|
57
|
+
}
|
|
58
|
+
/** The platforms named, each one some CLI is published for, or what is wrong. */
|
|
59
|
+
export function platformsFor(names) {
|
|
60
|
+
const known = [...new Set(CLI_TOOLS.flatMap((tool) => CLI_TOOL_SPECS[tool].platforms))];
|
|
61
|
+
if (!names.length)
|
|
62
|
+
throw new Error(`no platform named: use one or more of ${known.join(", ")}`);
|
|
63
|
+
return names.map((name) => {
|
|
64
|
+
if (!known.includes(name))
|
|
65
|
+
throw new Error(`unknown platform ${name}: use one of ${known.join(", ")}`);
|
|
66
|
+
return parsePlatform(name);
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
/** What a folder `install --dir` writes holds: the tools' builds and the install's records. */
|
|
70
|
+
const STAGED = new Set([...CLI_TOOLS, ".tmp", ".used"]);
|
|
71
|
+
/** A `--dir` must be new, empty, or one `install --dir` wrote: staging opens what it writes to every user. */
|
|
72
|
+
async function stageable(dir) {
|
|
73
|
+
const entries = await readdir(dir).catch(() => []);
|
|
74
|
+
const foreign = entries.find((entry) => !STAGED.has(entry));
|
|
75
|
+
if (foreign)
|
|
76
|
+
throw new Error(`${dir} holds ${foreign}, which install --dir did not write: stage into an empty folder`);
|
|
77
|
+
}
|
|
78
|
+
/** `<tool>/<entry>` of the build whose binary is `path`, which must be one in `dir`. */
|
|
79
|
+
function stagedBuild(dir, path) {
|
|
80
|
+
const [tool, entry] = relative(dir, path).split(sep);
|
|
81
|
+
if (!tool || !entry || !CLI_TOOLS.includes(tool))
|
|
82
|
+
throw new Error(`${path} is not a build in ${dir}`);
|
|
83
|
+
return join(tool, entry);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* `dir` and the parents of it that are missing, created readable and
|
|
87
|
+
* traversable by every user (0755, whatever the umask), as the builds staged
|
|
88
|
+
* in it are: run as root in an image build, the engine's own 0700 would leave
|
|
89
|
+
* a runtime user unable to reach them. A folder that was there is left as it
|
|
90
|
+
* is. The engine's own cache keeps its 0700 (`trustedCacheDirectory`).
|
|
91
|
+
*/
|
|
92
|
+
async function createStagingFolders(dir) {
|
|
93
|
+
const missing = [];
|
|
94
|
+
for (let path = resolve(dir);; path = dirname(path)) {
|
|
95
|
+
const exists = await stat(path).then(() => true, (error) => {
|
|
96
|
+
if (error.code === "ENOENT")
|
|
97
|
+
return false;
|
|
98
|
+
throw error;
|
|
99
|
+
});
|
|
100
|
+
if (exists || dirname(path) === path)
|
|
101
|
+
break;
|
|
102
|
+
missing.unshift(path);
|
|
103
|
+
}
|
|
104
|
+
for (const path of missing) {
|
|
105
|
+
await mkdir(path, { mode: 0o755 }).catch((error) => {
|
|
106
|
+
if (error.code !== "EEXIST")
|
|
107
|
+
throw error;
|
|
108
|
+
});
|
|
109
|
+
await chmod(path, 0o755);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The builds just staged, readable and runnable by every user, and the
|
|
114
|
+
* folder without the install's records: an owner-only tree baked into an
|
|
115
|
+
* image and run as another user fails with `Permission denied`.
|
|
116
|
+
*/
|
|
117
|
+
async function publish(dir, staged) {
|
|
118
|
+
for (const record of [".tmp", ".used"])
|
|
119
|
+
await rm(join(dir, record), { recursive: true, force: true });
|
|
120
|
+
await chmod(dir, 0o755);
|
|
121
|
+
for (const tool of new Set(staged.map((build) => build.split(sep)[0])))
|
|
122
|
+
await chmod(join(dir, tool), 0o755);
|
|
123
|
+
// A build staged before by an older agent-server may not be open yet.
|
|
124
|
+
for (const build of new Set(staged))
|
|
125
|
+
await openToAll(join(dir, build));
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Prefetch the pinned CLI builds into the managed cache — the cold-start
|
|
129
|
+
* eraser: run it while building a container/sandbox image and runtime turns
|
|
130
|
+
* never download. Or stage them for other platforms into a folder an app or
|
|
131
|
+
* an image ships (`dir`). Downloads run in parallel; failures reject with the
|
|
132
|
+
* first error after all settle (so one flaky download doesn't hide the others).
|
|
133
|
+
*/
|
|
134
|
+
export async function runInstall(options = {}) {
|
|
135
|
+
const provision = {
|
|
136
|
+
...options.provision,
|
|
137
|
+
...(options.dir && { mode: "pinned", cacheDir: options.dir }),
|
|
138
|
+
};
|
|
139
|
+
const platforms = options.platforms ? platformsFor(options.platforms) : [detectPlatform()];
|
|
140
|
+
if (options.dir) {
|
|
141
|
+
await stageable(options.dir);
|
|
142
|
+
// @ref LLP 0010#p4--staging-for-images-and-app-bundles — what staging creates, every user may reach
|
|
143
|
+
await createStagingFolders(options.dir);
|
|
144
|
+
}
|
|
145
|
+
const create = options.createProvisioner ??
|
|
146
|
+
((provisionOptions, platform) => new CliProvisioner(provisionOptions, { platform }));
|
|
147
|
+
const tools = toolsFor(options.harnesses);
|
|
148
|
+
const provisioners = platforms.map((platform) => ({
|
|
149
|
+
platform: platformName(platform),
|
|
150
|
+
provisioner: create(provision, platform),
|
|
151
|
+
}));
|
|
152
|
+
const jobs = provisioners.flatMap(({ platform, provisioner }) => tools.map((tool) => ({ tool, platform, provisioner })));
|
|
153
|
+
const settled = await Promise.allSettled(jobs.map((job) => job.provisioner.install(job.tool)));
|
|
154
|
+
const failure = settled.find((result) => result.status === "rejected");
|
|
155
|
+
if (failure)
|
|
156
|
+
throw failure.reason;
|
|
157
|
+
const results = settled.map((result, i) => ({
|
|
158
|
+
tool: jobs[i].tool,
|
|
159
|
+
platform: jobs[i].platform,
|
|
160
|
+
cli: result.value,
|
|
161
|
+
}));
|
|
162
|
+
if (options.prune)
|
|
163
|
+
for (const { provisioner } of provisioners)
|
|
164
|
+
await provisioner.prune();
|
|
165
|
+
if (options.dir) {
|
|
166
|
+
// The install names its binaries by the folder's real path (macOS's /tmp is /private/tmp).
|
|
167
|
+
const dir = await realpath(options.dir);
|
|
168
|
+
await publish(dir, results.map(({ cli }) => stagedBuild(dir, cli.path)));
|
|
169
|
+
}
|
|
170
|
+
return results;
|
|
171
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { extendPart, isLiveOnlyEvent, } from "../protocol/index.js";
|
|
2
|
+
/** A part with content beyond its last kept snapshot: text or reasoning streaming, a tool pending. */
|
|
3
|
+
function isOpen(part) {
|
|
4
|
+
if (part.type === "text" || part.type === "reasoning")
|
|
5
|
+
return part.state === "streaming";
|
|
6
|
+
return part.type === "tool" && part.state.status === "pending";
|
|
7
|
+
}
|
|
8
|
+
// @ref LLP 0008#open-parts-in-memory — what a subscription's open-part frames carry
|
|
9
|
+
/**
|
|
10
|
+
* What the server keeps in memory of each session as it streams, from the
|
|
11
|
+
* frames it delivers: a kept event as its store kept it (what replay and
|
|
12
|
+
* history return, a journal's possibly cut down), and every delta. It holds
|
|
13
|
+
* the session's open parts, each a streaming part's last kept snapshot with
|
|
14
|
+
* every delta since applied (what a client that subscribes mid-part receives
|
|
15
|
+
* at once, instead of the deltas it missed), and where its latest turn
|
|
16
|
+
* started. Updated in the same synchronous call that delivers the frame, so a
|
|
17
|
+
* subscription lands either before a delta (and receives it live) or after it
|
|
18
|
+
* (and finds it here), never both. Whatever the store, volatile or a journal.
|
|
19
|
+
*/
|
|
20
|
+
export class OpenParts {
|
|
21
|
+
sessions = new Map();
|
|
22
|
+
/** The turn each session ran last, by the seq of its `turn.started`. */
|
|
23
|
+
started = new Map();
|
|
24
|
+
/** A frame the server delivers. */
|
|
25
|
+
delivered(envelope) {
|
|
26
|
+
const { sessionId, seq, event } = envelope;
|
|
27
|
+
if (isLiveOnlyEvent(event)) {
|
|
28
|
+
this.extend(event);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
const open = this.sessions.get(sessionId);
|
|
32
|
+
switch (event.type) {
|
|
33
|
+
case "message.part": {
|
|
34
|
+
const { part } = event;
|
|
35
|
+
if (isOpen(part)) {
|
|
36
|
+
const parts = open ?? new Map();
|
|
37
|
+
parts.set(part.id, event);
|
|
38
|
+
this.sessions.set(sessionId, parts);
|
|
39
|
+
}
|
|
40
|
+
else
|
|
41
|
+
this.close(sessionId, part.id);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
case "turn.started":
|
|
45
|
+
this.started.set(sessionId, { turnId: event.turnId, seq });
|
|
46
|
+
return;
|
|
47
|
+
case "turn.ended":
|
|
48
|
+
for (const [partId, entry] of open ?? [])
|
|
49
|
+
if (entry.turnId === event.turnId)
|
|
50
|
+
this.close(sessionId, partId);
|
|
51
|
+
return;
|
|
52
|
+
case "session.ended":
|
|
53
|
+
this.sessions.delete(sessionId);
|
|
54
|
+
this.started.delete(sessionId);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** The session's open parts, in the order they opened, as live frames at `headSeq`. */
|
|
59
|
+
of(sessionId, headSeq) {
|
|
60
|
+
return [...(this.sessions.get(sessionId)?.values() ?? [])].map((event) => ({
|
|
61
|
+
sessionId,
|
|
62
|
+
seq: headSeq,
|
|
63
|
+
live: true,
|
|
64
|
+
event,
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
/** The seq of the turn's `turn.started`, while it is the session's latest turn. */
|
|
68
|
+
startedSeq(sessionId, turnId) {
|
|
69
|
+
const started = this.started.get(sessionId);
|
|
70
|
+
return started?.turnId === turnId ? started.seq : undefined;
|
|
71
|
+
}
|
|
72
|
+
/** A delta: its part gains what it streamed, dated by it. */
|
|
73
|
+
extend(event) {
|
|
74
|
+
const parts = this.sessions.get(event.sessionId);
|
|
75
|
+
const entry = parts?.get(event.partId);
|
|
76
|
+
const part = entry && extendPart(entry.part, event.delta);
|
|
77
|
+
if (parts && entry && part)
|
|
78
|
+
parts.set(event.partId, { ...entry, part, timestamp: event.timestamp });
|
|
79
|
+
}
|
|
80
|
+
close(sessionId, partId) {
|
|
81
|
+
const parts = this.sessions.get(sessionId);
|
|
82
|
+
if (!parts?.delete(partId))
|
|
83
|
+
return;
|
|
84
|
+
if (parts.size === 0)
|
|
85
|
+
this.sessions.delete(sessionId);
|
|
86
|
+
}
|
|
87
|
+
}
|