@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,292 @@
|
|
|
1
|
+
import { WIRE_METHODS, WIRE_PROTOCOL_VERSION, WireRefusal, generateUUIDv7, } from "../protocol/index.js";
|
|
2
|
+
function assertHarness(runtime, harness) {
|
|
3
|
+
if (!runtime.harnesses.includes(harness))
|
|
4
|
+
throw new WireRefusal("harnessNotAvailable", `harness not available: ${harness}`, {
|
|
5
|
+
available: runtime.harnesses,
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
/** A settled turn's end, from the summary the runtime converges a retry on. */
|
|
9
|
+
function endedOf(summary) {
|
|
10
|
+
return {
|
|
11
|
+
type: "turn.ended",
|
|
12
|
+
sessionId: summary.sessionId,
|
|
13
|
+
turnId: summary.turnId,
|
|
14
|
+
stopReason: summary.stopReason,
|
|
15
|
+
finishReason: summary.finishReason,
|
|
16
|
+
tokens: summary.usage,
|
|
17
|
+
cost: summary.cost,
|
|
18
|
+
execution: summary.execution,
|
|
19
|
+
error: summary.error,
|
|
20
|
+
...(summary.undeliveredSteers?.length && { undeliveredSteers: summary.undeliveredSteers }),
|
|
21
|
+
timestamp: Date.now(),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** The routes every server has, one per method: a method without one does not compile. */
|
|
25
|
+
export function executionRoutes(host) {
|
|
26
|
+
const { runtime, store, openParts, gate, subscriptions } = host;
|
|
27
|
+
/** A retried start the runtime converges on: a volatile store holds no receipts, only its log. */
|
|
28
|
+
const converged = (request) => {
|
|
29
|
+
const admission = runtime.admission(request);
|
|
30
|
+
if (admission.status === "new")
|
|
31
|
+
return undefined;
|
|
32
|
+
// Its `turn.ended` may be out before the runtime settles it.
|
|
33
|
+
const terminal = store.terminal(request.sessionId, request.turnId) ??
|
|
34
|
+
(admission.status === "completed" ? endedOf(admission.summary) : undefined);
|
|
35
|
+
return terminal ? { terminal } : {};
|
|
36
|
+
};
|
|
37
|
+
/** Where a subscription to the session starts now, with the turn it runs. */
|
|
38
|
+
const pointOf = (sessionId) => {
|
|
39
|
+
const point = store.point(sessionId);
|
|
40
|
+
if (!point)
|
|
41
|
+
return undefined;
|
|
42
|
+
const active = gate.activeTurn(sessionId);
|
|
43
|
+
const startedSeq = active && openParts.startedSeq(sessionId, active.turnId);
|
|
44
|
+
return {
|
|
45
|
+
...point,
|
|
46
|
+
...(active && {
|
|
47
|
+
activeTurn: { turnId: active.turnId, ...(startedSeq !== undefined && { startedSeq }) },
|
|
48
|
+
}),
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
// @ref LLP 0008#ordering-joining-without-a-gap-or-a-duplicate — read, register, answer, send: one synchronous block
|
|
52
|
+
/**
|
|
53
|
+
* Subscribe the connection at `headSeq`, the point its answer marks; the
|
|
54
|
+
* session's open parts follow the answer. All of it before any other frame
|
|
55
|
+
* can be sent, so each of the session's frames reaches the connection once:
|
|
56
|
+
* kept events up to the point by replay, after it pushed, deltas before it
|
|
57
|
+
* folded into an open part, after it pushed.
|
|
58
|
+
*/
|
|
59
|
+
const subscribeAt = (context, sessionId, headSeq, scope) => {
|
|
60
|
+
subscriptions.subscribe(context.transport, sessionId, headSeq, scope);
|
|
61
|
+
const open = openParts.of(sessionId, headSeq);
|
|
62
|
+
if (open.length)
|
|
63
|
+
context.afterResponse(() => subscriptions.sendTo(context.transport, open));
|
|
64
|
+
};
|
|
65
|
+
const runs = (sessionId, turnId) => gate.activeTurn(sessionId)?.turnId === turnId;
|
|
66
|
+
return {
|
|
67
|
+
[WIRE_METHODS.initialize]: ({ protocolVersion }) => {
|
|
68
|
+
if (protocolVersion !== WIRE_PROTOCOL_VERSION)
|
|
69
|
+
throw new WireRefusal("protocolVersionMismatch", `unsupported protocol version: ${protocolVersion}`, { supported: [WIRE_PROTOCOL_VERSION] });
|
|
70
|
+
const harnesses = {};
|
|
71
|
+
for (const harness of runtime.harnesses)
|
|
72
|
+
harnesses[harness] = runtime.capabilities(harness);
|
|
73
|
+
return { protocolVersion: WIRE_PROTOCOL_VERSION, ...host.identity, harnesses };
|
|
74
|
+
},
|
|
75
|
+
[WIRE_METHODS.turnStart]: (parsed, context) => {
|
|
76
|
+
if (!host.accepting())
|
|
77
|
+
throw new WireRefusal("shuttingDown", "server is shutting down");
|
|
78
|
+
const { config, input } = parsed;
|
|
79
|
+
assertHarness(runtime, config.harness);
|
|
80
|
+
const sessionId = parsed.sessionId ?? generateUUIDv7();
|
|
81
|
+
const turnId = parsed.turnId ?? generateUUIDv7();
|
|
82
|
+
// Refused in this order: a session closing, then a retry (which
|
|
83
|
+
// converges instead), another harness, a running turn.
|
|
84
|
+
gate.assertOpen(sessionId);
|
|
85
|
+
// The caller wants the turn's stream (unless it says otherwise), until
|
|
86
|
+
// the turn ends. Never refused: the cap bounds what a connection
|
|
87
|
+
// watches, not the turns it runs.
|
|
88
|
+
const subscribe = parsed.subscribe !== false;
|
|
89
|
+
// Idempotent admission: a retried start (same turnId, identical
|
|
90
|
+
// input) converges — ack again, never run twice, and subscribe its
|
|
91
|
+
// caller to the turn while it runs. A durable store remembers every
|
|
92
|
+
// turn it admitted, the runtime only its recent ones. The same turnId
|
|
93
|
+
// with different input is a caller bug → turnConflict.
|
|
94
|
+
const request = { sessionId, turnId, input, config };
|
|
95
|
+
const duplicate = store.duplicateOf(request) ?? converged(request);
|
|
96
|
+
if (duplicate) {
|
|
97
|
+
const headSeq = store.point(sessionId)?.headSeq;
|
|
98
|
+
if (subscribe && headSeq !== undefined && runs(sessionId, turnId))
|
|
99
|
+
subscribeAt(context, sessionId, headSeq, { turnId });
|
|
100
|
+
const startedSeq = duplicate.terminal ? undefined : openParts.startedSeq(sessionId, turnId);
|
|
101
|
+
return {
|
|
102
|
+
sessionId,
|
|
103
|
+
turnId,
|
|
104
|
+
deduplicated: true,
|
|
105
|
+
headSeq: headSeq ?? 0,
|
|
106
|
+
...(startedSeq !== undefined && { startedSeq }),
|
|
107
|
+
...(duplicate.terminal && { terminal: duplicate.terminal }),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
const bound = store.harnessOf(sessionId);
|
|
111
|
+
if (bound && bound !== config.harness)
|
|
112
|
+
throw new WireRefusal("invalidParams", `session ${sessionId} is bound to harness ${bound}`);
|
|
113
|
+
gate.assertIdle(sessionId);
|
|
114
|
+
store.open(request);
|
|
115
|
+
gate.begin(sessionId, { turnId, harness: config.harness });
|
|
116
|
+
// The point before the turn's first event: its caller downloads no history.
|
|
117
|
+
const headSeq = store.point(sessionId)?.headSeq ?? 0;
|
|
118
|
+
if (subscribe)
|
|
119
|
+
subscriptions.subscribe(context.transport, sessionId, headSeq, { turnId });
|
|
120
|
+
// Quick-ack before the first event can possibly be emitted. The turn
|
|
121
|
+
// runs (and releases its session) even if the requester is gone.
|
|
122
|
+
context.afterResponse(() => host.executeTurn(request));
|
|
123
|
+
return { sessionId, turnId, headSeq };
|
|
124
|
+
},
|
|
125
|
+
[WIRE_METHODS.turnCancel]: async ({ sessionId, turnId }) => {
|
|
126
|
+
const active = gate.activeTurn(sessionId);
|
|
127
|
+
if (!active)
|
|
128
|
+
return { outcome: "no_active_turn" };
|
|
129
|
+
// Turn-stamped cancel for a turn that is no longer the active one —
|
|
130
|
+
// refuse to kill its successor; report who IS active instead.
|
|
131
|
+
if (turnId && turnId !== active.turnId)
|
|
132
|
+
return { outcome: "no_active_turn", activeTurnId: active.turnId };
|
|
133
|
+
const { confirmed, hadTurn } = await runtime.cancel(active.harness, sessionId);
|
|
134
|
+
// An unacknowledged interrupt is NOT a cancel: the agent may still be
|
|
135
|
+
// running and `turn.ended` stays the source of truth. `hadTurn: false`
|
|
136
|
+
// while the server tracks an active turn is the pre-first-yield window
|
|
137
|
+
// (between the turn/start quick-ack and the harness registering its
|
|
138
|
+
// abortable turn): the turn keeps the cancel and its harness begins it
|
|
139
|
+
// stopped, but nothing has confirmed a stop yet, so it reports
|
|
140
|
+
// `unconfirmed`, never a clean cancel, and `turn.ended` says `cancelled`.
|
|
141
|
+
return {
|
|
142
|
+
outcome: confirmed && hadTurn ? "cancelled" : "unconfirmed",
|
|
143
|
+
turnId: active.turnId,
|
|
144
|
+
};
|
|
145
|
+
},
|
|
146
|
+
// @ref LLP 0001#d13--input-while-a-turn-runs-steers-it — the runtime decides
|
|
147
|
+
[WIRE_METHODS.turnSteer]: ({ sessionId, turnId, steerId, input }) => runtime.steer(sessionId, { turnId, steerId: steerId ?? generateUUIDv7(), input }),
|
|
148
|
+
[WIRE_METHODS.sessionClose]: async ({ sessionId }) => {
|
|
149
|
+
gate.assertIdle(sessionId);
|
|
150
|
+
const harness = store.closing(sessionId);
|
|
151
|
+
if (!harness)
|
|
152
|
+
return { closed: false };
|
|
153
|
+
return gate.whileClosing(sessionId, "closing", async () => {
|
|
154
|
+
await runtime.closeSession(harness, sessionId);
|
|
155
|
+
// The terminal fact for CONNECTED subscribers: they learn the
|
|
156
|
+
// session is over from the stream, not from the RPC result (which
|
|
157
|
+
// only the closer sees). Appending it retires the session.
|
|
158
|
+
host.broadcast(store.append(sessionId, {
|
|
159
|
+
type: "session.ended",
|
|
160
|
+
sessionId,
|
|
161
|
+
reason: "closed",
|
|
162
|
+
timestamp: Date.now(),
|
|
163
|
+
}));
|
|
164
|
+
return { closed: true };
|
|
165
|
+
});
|
|
166
|
+
},
|
|
167
|
+
[WIRE_METHODS.permissionRespond]: ({ sessionId, requestId, outcome }) => ({
|
|
168
|
+
accepted: runtime.respondPermission(sessionId, requestId, outcome),
|
|
169
|
+
}),
|
|
170
|
+
[WIRE_METHODS.elicitationRespond]: ({ sessionId, requestId, outcome }) => ({
|
|
171
|
+
accepted: runtime.respondElicitation(sessionId, requestId, outcome),
|
|
172
|
+
}),
|
|
173
|
+
[WIRE_METHODS.sessionSubscribe]: ({ sessionId, turnId }, context) => {
|
|
174
|
+
const point = pointOf(sessionId);
|
|
175
|
+
if (!point)
|
|
176
|
+
throw new WireRefusal("unknownSession", `unknown session: ${sessionId}`);
|
|
177
|
+
// A turn that is not running subscribes nothing: its events, its end
|
|
178
|
+
// included, are kept up to the point (the answer's `activeTurn` tells).
|
|
179
|
+
if (turnId === undefined)
|
|
180
|
+
subscribeAt(context, sessionId, point.headSeq, "watch");
|
|
181
|
+
else if (runs(sessionId, turnId))
|
|
182
|
+
subscribeAt(context, sessionId, point.headSeq, { turnId });
|
|
183
|
+
return point;
|
|
184
|
+
},
|
|
185
|
+
[WIRE_METHODS.sessionUnsubscribe]: ({ sessionId }, { transport }) => ({
|
|
186
|
+
unsubscribed: subscriptions.unsubscribe(transport, sessionId),
|
|
187
|
+
}),
|
|
188
|
+
[WIRE_METHODS.sessionSubscribeAll]: (_params, context) => {
|
|
189
|
+
subscriptions.subscribeAll(context.transport);
|
|
190
|
+
const sessions = gate.running().flatMap((sessionId) => {
|
|
191
|
+
const point = pointOf(sessionId);
|
|
192
|
+
return point ? [{ sessionId, ...point }] : [];
|
|
193
|
+
});
|
|
194
|
+
const open = sessions.flatMap(({ sessionId, headSeq }) => openParts.of(sessionId, headSeq));
|
|
195
|
+
if (open.length)
|
|
196
|
+
context.afterResponse(() => subscriptions.sendTo(context.transport, open));
|
|
197
|
+
return { sessions };
|
|
198
|
+
},
|
|
199
|
+
[WIRE_METHODS.sessionUnsubscribeAll]: (_params, { transport }) => ({
|
|
200
|
+
unsubscribed: subscriptions.unsubscribeAll(transport),
|
|
201
|
+
}),
|
|
202
|
+
[WIRE_METHODS.eventsReplay]: ({ sessionId, fromSeq }) => {
|
|
203
|
+
const replayed = store.replay(sessionId, fromSeq);
|
|
204
|
+
if (!replayed)
|
|
205
|
+
throw new WireRefusal("unknownSession", `unknown session: ${sessionId}`);
|
|
206
|
+
return replayed;
|
|
207
|
+
},
|
|
208
|
+
[WIRE_METHODS.modelsList]: (parsed) => {
|
|
209
|
+
assertHarness(runtime, parsed.harness);
|
|
210
|
+
return runtime.models(parsed);
|
|
211
|
+
},
|
|
212
|
+
[WIRE_METHODS.clisList]: async ({ harnesses }) => {
|
|
213
|
+
for (const harness of harnesses ?? [])
|
|
214
|
+
assertHarness(runtime, harness);
|
|
215
|
+
return { clis: await runtime.listClis(harnesses) };
|
|
216
|
+
},
|
|
217
|
+
// @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — an install outlasts any request's deadline
|
|
218
|
+
[WIRE_METHODS.clisPrepare]: async ({ harnesses }) => {
|
|
219
|
+
for (const harness of harnesses ?? [])
|
|
220
|
+
assertHarness(runtime, harness);
|
|
221
|
+
// Started, and answered at once: what is not ready yet is `installing`,
|
|
222
|
+
// and `clis/progress` and `clis/list` say how it ends.
|
|
223
|
+
void runtime.prepareClis(harnesses).catch(() => { });
|
|
224
|
+
return { clis: await runtime.listClis(harnesses) };
|
|
225
|
+
},
|
|
226
|
+
[WIRE_METHODS.authStatus]: async ({ harnesses, env }) => {
|
|
227
|
+
for (const harness of harnesses ?? [])
|
|
228
|
+
assertHarness(runtime, harness);
|
|
229
|
+
return { auth: await runtime.authStatus(harnesses, env) };
|
|
230
|
+
},
|
|
231
|
+
// @ref LLP 0011#the-wire — answered once the CLI says where to sign in; `auth/updated` says how it ended
|
|
232
|
+
[WIRE_METHODS.authLogin]: (params) => {
|
|
233
|
+
assertHarness(runtime, params.harness);
|
|
234
|
+
return runtime.login(params);
|
|
235
|
+
},
|
|
236
|
+
[WIRE_METHODS.authComplete]: ({ loginId, code }) => runtime.completeLogin(loginId, code),
|
|
237
|
+
[WIRE_METHODS.authCancel]: ({ loginId }) => ({ outcome: runtime.cancelLogin(loginId) }),
|
|
238
|
+
[WIRE_METHODS.authLogout]: ({ harness, env }) => {
|
|
239
|
+
assertHarness(runtime, harness);
|
|
240
|
+
return runtime.logout(harness, env);
|
|
241
|
+
},
|
|
242
|
+
[WIRE_METHODS.shutdown]: async (_params, { afterResponse }) => {
|
|
243
|
+
// Answer once the turns drained, so the client that asked hears their
|
|
244
|
+
// turn.ended (cancelled) before the answer, then close. A drain that
|
|
245
|
+
// throws still gets its one answer: shutting down reports nothing more.
|
|
246
|
+
await host.drainTurns().catch(() => { });
|
|
247
|
+
afterResponse(() => void host.shutdown().catch(() => { }));
|
|
248
|
+
return {};
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* The routes only a server with a journal has: a volatile session has no
|
|
254
|
+
* receipt, no fence to lift and no journal to ask its next turn for a
|
|
255
|
+
* conversation it let go (`session/close` frees it), so a volatile server
|
|
256
|
+
* answers these `methodNotFound`.
|
|
257
|
+
*/
|
|
258
|
+
export function durableRoutes(store, { runtime, gate }) {
|
|
259
|
+
return {
|
|
260
|
+
[WIRE_METHODS.turnGet]: ({ sessionId, turnId }) => {
|
|
261
|
+
const receipt = store.receipt(sessionId, turnId);
|
|
262
|
+
if (receipt)
|
|
263
|
+
return receipt;
|
|
264
|
+
throw store.session(sessionId)
|
|
265
|
+
? new WireRefusal("unknownTurn", `unknown turn: ${turnId}`)
|
|
266
|
+
: new WireRefusal("unknownSession", `unknown session: ${sessionId}`);
|
|
267
|
+
},
|
|
268
|
+
[WIRE_METHODS.sessionGet]: ({ sessionId }) => {
|
|
269
|
+
const session = store.session(sessionId);
|
|
270
|
+
if (!session)
|
|
271
|
+
throw new WireRefusal("unknownSession", `unknown session: ${sessionId}`);
|
|
272
|
+
return session;
|
|
273
|
+
},
|
|
274
|
+
[WIRE_METHODS.sessionConfirmStopped]: ({ sessionId, expectedHeadSeq }) => ({
|
|
275
|
+
recovered: store.confirmStopped(sessionId, expectedHeadSeq),
|
|
276
|
+
}),
|
|
277
|
+
// @ref LLP 0003#releasing-without-closing — free the agent, keep the session
|
|
278
|
+
[WIRE_METHODS.sessionRelease]: async ({ sessionId }) => {
|
|
279
|
+
gate.assertIdle(sessionId);
|
|
280
|
+
const harness = store.harnessOf(sessionId);
|
|
281
|
+
if (!harness)
|
|
282
|
+
return { released: false };
|
|
283
|
+
return gate.whileClosing(sessionId, "releasing", async () => {
|
|
284
|
+
// First, so no turn admitted later runs without naming its
|
|
285
|
+
// conversation: the runtime is about to forget which one it was.
|
|
286
|
+
store.releaseNative(sessionId);
|
|
287
|
+
await runtime.closeSession(harness, sessionId);
|
|
288
|
+
return { released: true };
|
|
289
|
+
});
|
|
290
|
+
},
|
|
291
|
+
};
|
|
292
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The secrets the server reads from its environment: what a listener, `--dial` and `--credentials-url` present. */
|
|
2
|
+
const SERVER_SECRETS = [
|
|
3
|
+
"AGENT_SERVER_TOKEN",
|
|
4
|
+
"AGENT_SERVER_DIAL_TOKEN",
|
|
5
|
+
"AGENT_SERVER_CREDENTIALS_TOKEN",
|
|
6
|
+
];
|
|
7
|
+
/**
|
|
8
|
+
* Take this server's secrets out of its environment, answering them: every
|
|
9
|
+
* CLI the server starts inherits the environment, and the tools those run
|
|
10
|
+
* with it, so a secret left there is one an agent can read. An empty one
|
|
11
|
+
* stays empty, for its user to refuse.
|
|
12
|
+
*/
|
|
13
|
+
export function takeSecrets(env = process.env) {
|
|
14
|
+
return Object.fromEntries(SERVER_SECRETS.map((name) => {
|
|
15
|
+
const value = env[name]?.trim();
|
|
16
|
+
delete env[name];
|
|
17
|
+
return [name, value];
|
|
18
|
+
}));
|
|
19
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { WireRefusal } from "../protocol/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Which sessions are busy: running their one turn, or letting their native
|
|
4
|
+
* state go (`session/close`, `session/release`). A request that would race
|
|
5
|
+
* either is refused before it touches the session.
|
|
6
|
+
*/
|
|
7
|
+
export class SessionGate {
|
|
8
|
+
turns = new Map();
|
|
9
|
+
closing = new Map();
|
|
10
|
+
/** The turn the session runs, if any. */
|
|
11
|
+
activeTurn(sessionId) {
|
|
12
|
+
return this.turns.get(sessionId);
|
|
13
|
+
}
|
|
14
|
+
/** The sessions running a turn. */
|
|
15
|
+
running() {
|
|
16
|
+
return [...this.turns.keys()];
|
|
17
|
+
}
|
|
18
|
+
/** Refuse a session whose native state is going: it is idle, not busy, so retry shortly. */
|
|
19
|
+
assertOpen(sessionId) {
|
|
20
|
+
const closing = this.closing.get(sessionId);
|
|
21
|
+
if (closing)
|
|
22
|
+
throw new WireRefusal("sessionClosing", `session ${sessionId} is ${closing}`);
|
|
23
|
+
}
|
|
24
|
+
/** Refuse a session that runs a turn, or whose native state is going. */
|
|
25
|
+
assertIdle(sessionId) {
|
|
26
|
+
this.assertOpen(sessionId);
|
|
27
|
+
const turn = this.turns.get(sessionId);
|
|
28
|
+
if (turn)
|
|
29
|
+
throw new WireRefusal("turnActive", `session ${sessionId} has an active turn`, {
|
|
30
|
+
turnId: turn.turnId,
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
begin(sessionId, turn) {
|
|
34
|
+
this.turns.set(sessionId, turn);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The turn ended: its session is idle — unless a newer turn was admitted
|
|
38
|
+
* between this one's `turn.ended` and its run settling, whose mark stays.
|
|
39
|
+
*/
|
|
40
|
+
settle(sessionId, turnId) {
|
|
41
|
+
if (this.turns.get(sessionId)?.turnId === turnId)
|
|
42
|
+
this.turns.delete(sessionId);
|
|
43
|
+
}
|
|
44
|
+
/** Let the session's native state go with `release`; no turn starts meanwhile. */
|
|
45
|
+
async whileClosing(sessionId, kind, release) {
|
|
46
|
+
this.closing.set(sessionId, kind);
|
|
47
|
+
try {
|
|
48
|
+
return await release();
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
this.closing.delete(sessionId);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export const DEFAULT_BUFFER_SIZE = 4096;
|
|
2
|
+
// @ref LLP 0001#d7--reliability-lives-at-the-wire-binding — seq and bounded replay
|
|
3
|
+
/**
|
|
4
|
+
* Per-session monotonic sequence + bounded replay buffer. Every
|
|
5
|
+
* outbound event is stamped with `seq` (starting at 1) and kept in a ring
|
|
6
|
+
* buffer so a reconnecting client can `events/replay({fromSeq})`. Eviction is
|
|
7
|
+
* visible to clients via `firstAvailableSeq`.
|
|
8
|
+
*
|
|
9
|
+
* Eviction advances a head index (O(1) amortized) instead of shifting the
|
|
10
|
+
* array; the dead prefix is compacted away once it reaches one full capacity,
|
|
11
|
+
* bounding memory at ~2x `maxBuffer` envelopes.
|
|
12
|
+
*/
|
|
13
|
+
export class SessionLog {
|
|
14
|
+
sessionId;
|
|
15
|
+
harness;
|
|
16
|
+
buffer = [];
|
|
17
|
+
head = 0;
|
|
18
|
+
nextSeq;
|
|
19
|
+
maxBuffer;
|
|
20
|
+
constructor(sessionId,
|
|
21
|
+
/** The harness this session is bound to (first turn wins). */
|
|
22
|
+
harness, maxBuffer = DEFAULT_BUFFER_SIZE,
|
|
23
|
+
/** First seq to assign — a session reused after `session/close` continues
|
|
24
|
+
* where its previous incarnation stopped, so peers never see seq go
|
|
25
|
+
* backwards (a backwards seq reads as a duplicate and masks event loss). */
|
|
26
|
+
startSeq = 1) {
|
|
27
|
+
this.sessionId = sessionId;
|
|
28
|
+
this.harness = harness;
|
|
29
|
+
// A NaN or non-positive cap would silently disable eviction and grow
|
|
30
|
+
// the buffer without bound — normalize rather than trust the caller.
|
|
31
|
+
this.maxBuffer = Number.isInteger(maxBuffer) && maxBuffer > 0 ? maxBuffer : DEFAULT_BUFFER_SIZE;
|
|
32
|
+
this.nextSeq = Number.isInteger(startSeq) && startSeq > 0 ? startSeq : 1;
|
|
33
|
+
}
|
|
34
|
+
append(event) {
|
|
35
|
+
const envelope = { sessionId: this.sessionId, seq: this.nextSeq++, event };
|
|
36
|
+
this.buffer.push(envelope);
|
|
37
|
+
if (this.buffer.length - this.head > this.maxBuffer) {
|
|
38
|
+
this.head += 1;
|
|
39
|
+
if (this.head >= this.maxBuffer) {
|
|
40
|
+
this.buffer = this.buffer.slice(this.head);
|
|
41
|
+
this.head = 0;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return envelope;
|
|
45
|
+
}
|
|
46
|
+
/** A live-only event's envelope: the seq of the last kept event, nothing buffered.
|
|
47
|
+
* A delta follows its turn's `turn.started`, so there always is one. */
|
|
48
|
+
live(event) {
|
|
49
|
+
return { sessionId: this.sessionId, seq: this.nextSeq - 1, event };
|
|
50
|
+
}
|
|
51
|
+
/** Buffered envelopes with `seq >= fromSeq` (seq is contiguous — index math). */
|
|
52
|
+
replay(fromSeq) {
|
|
53
|
+
const first = this.firstAvailableSeq;
|
|
54
|
+
if (first === null)
|
|
55
|
+
return [];
|
|
56
|
+
return this.buffer.slice(this.head + Math.max(0, fromSeq - first));
|
|
57
|
+
}
|
|
58
|
+
/** Oldest seq still buffered, or null when nothing has been emitted. */
|
|
59
|
+
get firstAvailableSeq() {
|
|
60
|
+
return this.buffer[this.head]?.seq ?? null;
|
|
61
|
+
}
|
|
62
|
+
/** Newest seq assigned, or null when nothing has been emitted. */
|
|
63
|
+
get latestSeq() {
|
|
64
|
+
return this.nextSeq > 1 ? this.nextSeq - 1 : null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { EventSinkError } from "../core/index.js";
|
|
2
|
+
import { JournalError } from "../sync/journal.js";
|
|
3
|
+
import { DEFAULT_BUFFER_SIZE, SessionLog } from "./session-log.js";
|
|
4
|
+
/** A bounded replay ring per session, gone with the process. */
|
|
5
|
+
export class MemorySessionStore {
|
|
6
|
+
bufferSize;
|
|
7
|
+
sessions = new Map();
|
|
8
|
+
/** Last assigned seq of closed sessions, so a reused id continues
|
|
9
|
+
* monotonically. Memory: one number per closed-and-never-reused session id —
|
|
10
|
+
* unbounded only across a server lifetime with unbounded distinct ids, the
|
|
11
|
+
* same order of growth already accepted for `sessions`. */
|
|
12
|
+
retiredSeqs = new Map();
|
|
13
|
+
constructor(bufferSize = DEFAULT_BUFFER_SIZE) {
|
|
14
|
+
this.bufferSize = bufferSize;
|
|
15
|
+
}
|
|
16
|
+
harnessOf(sessionId) {
|
|
17
|
+
return this.sessions.get(sessionId)?.harness;
|
|
18
|
+
}
|
|
19
|
+
/** The runtime's own admission converges retries of volatile turns. */
|
|
20
|
+
duplicateOf() {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
open({ sessionId, config }) {
|
|
24
|
+
if (this.sessions.has(sessionId))
|
|
25
|
+
return;
|
|
26
|
+
const startSeq = (this.retiredSeqs.get(sessionId) ?? 0) + 1;
|
|
27
|
+
this.sessions.set(sessionId, new SessionLog(sessionId, config.harness, this.bufferSize, startSeq));
|
|
28
|
+
this.retiredSeqs.delete(sessionId);
|
|
29
|
+
}
|
|
30
|
+
append(sessionId, event) {
|
|
31
|
+
const log = this.log(sessionId);
|
|
32
|
+
const envelope = log.append(event);
|
|
33
|
+
// `session.ended` is deliberately NOT replayable: a subscriber detached
|
|
34
|
+
// during the close gets `unknownSession` from `events/replay`, and that
|
|
35
|
+
// answer IS its terminal signal (nothing more will ever be appended).
|
|
36
|
+
if (event.type === "session.ended") {
|
|
37
|
+
if (log.latestSeq !== null)
|
|
38
|
+
this.retiredSeqs.set(sessionId, log.latestSeq);
|
|
39
|
+
this.sessions.delete(sessionId);
|
|
40
|
+
}
|
|
41
|
+
return envelope;
|
|
42
|
+
}
|
|
43
|
+
live(sessionId, event) {
|
|
44
|
+
return this.log(sessionId).live(event);
|
|
45
|
+
}
|
|
46
|
+
replay(sessionId, fromSeq) {
|
|
47
|
+
const log = this.sessions.get(sessionId);
|
|
48
|
+
if (!log)
|
|
49
|
+
return undefined;
|
|
50
|
+
return {
|
|
51
|
+
events: log.replay(fromSeq),
|
|
52
|
+
firstAvailableSeq: log.firstAvailableSeq,
|
|
53
|
+
latestSeq: log.latestSeq,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
point(sessionId) {
|
|
57
|
+
const log = this.sessions.get(sessionId);
|
|
58
|
+
return log && { headSeq: log.latestSeq ?? 0, firstAvailableSeq: log.firstAvailableSeq };
|
|
59
|
+
}
|
|
60
|
+
terminal(sessionId, turnId) {
|
|
61
|
+
for (const { event } of this.sessions.get(sessionId)?.replay(1) ?? [])
|
|
62
|
+
if (event.type === "turn.ended" && event.turnId === turnId)
|
|
63
|
+
return event;
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
closing(sessionId) {
|
|
67
|
+
return this.harnessOf(sessionId);
|
|
68
|
+
}
|
|
69
|
+
relinquish() { }
|
|
70
|
+
log(sessionId) {
|
|
71
|
+
const log = this.sessions.get(sessionId);
|
|
72
|
+
if (!log)
|
|
73
|
+
throw new Error(`session ${sessionId} has no log`);
|
|
74
|
+
return log;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Every admission and event committed to a journal before it is acknowledged
|
|
79
|
+
* or delivered, so sessions survive restarts. A journal that fails to write
|
|
80
|
+
* fails this store for good, and `onFault` stops the server: restart recovery,
|
|
81
|
+
* not this process, decides what the cut-off turns did.
|
|
82
|
+
*/
|
|
83
|
+
export class JournalSessionStore {
|
|
84
|
+
journal;
|
|
85
|
+
onFault;
|
|
86
|
+
fault;
|
|
87
|
+
releaseClaim;
|
|
88
|
+
/** After shutdown, a turn that ignored its abort must not write behind a new owner. */
|
|
89
|
+
relinquished = false;
|
|
90
|
+
/** The seq of each open session's last kept event, which its deltas carry. */
|
|
91
|
+
heads = new Map();
|
|
92
|
+
/** The journal's id for each live native process's record. */
|
|
93
|
+
recordIds = new Map();
|
|
94
|
+
constructor(journal, onFault, swept) {
|
|
95
|
+
this.journal = journal;
|
|
96
|
+
this.onFault = onFault;
|
|
97
|
+
this.releaseClaim = journal.claim(swept);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Keep a native process's record from its start until it is seen gone. A
|
|
101
|
+
* record that cannot be written fails its spawn, and the store with it: an
|
|
102
|
+
* agent nobody recorded must get no work. One that cannot be dropped stays
|
|
103
|
+
* for the next start, which finds its process gone.
|
|
104
|
+
*/
|
|
105
|
+
recordNative(event) {
|
|
106
|
+
if (event.type === "started") {
|
|
107
|
+
this.recordIds.set(event.record, this.write(() => this.journal.recordNative(event.record)));
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const id = this.recordIds.get(event.record);
|
|
111
|
+
if (id === undefined)
|
|
112
|
+
return;
|
|
113
|
+
this.recordIds.delete(event.record);
|
|
114
|
+
try {
|
|
115
|
+
this.write(() => this.journal.forgetNative(id));
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
// Kept: the next start finds it gone.
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
harnessOf(sessionId) {
|
|
122
|
+
const session = this.journal.session(sessionId);
|
|
123
|
+
return session && !session.closed ? session.harness : undefined;
|
|
124
|
+
}
|
|
125
|
+
duplicateOf(request) {
|
|
126
|
+
if (this.journal.admission(request) === "new")
|
|
127
|
+
return undefined;
|
|
128
|
+
return { terminal: this.journal.turn(request.sessionId, request.turnId)?.terminal };
|
|
129
|
+
}
|
|
130
|
+
open(request) {
|
|
131
|
+
this.write(() => this.journal.admit(request));
|
|
132
|
+
}
|
|
133
|
+
append(sessionId, event) {
|
|
134
|
+
return this.sink(() => {
|
|
135
|
+
// Only a pre-session `error` may lack its session; this one has one.
|
|
136
|
+
const envelope = this.journal.append(event.sessionId === undefined ? { ...event, sessionId } : event);
|
|
137
|
+
if (event.type === "session.ended")
|
|
138
|
+
this.heads.delete(sessionId);
|
|
139
|
+
else
|
|
140
|
+
this.heads.set(sessionId, envelope.seq);
|
|
141
|
+
// What the journal stored, as replay and history return it: what the
|
|
142
|
+
// server delivers, and keeps of the session's open parts.
|
|
143
|
+
return envelope;
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
live(sessionId, event) {
|
|
147
|
+
// What a delta streamed is kept until its part's next snapshot, for recovery.
|
|
148
|
+
this.sink(() => this.journal.keepTail(event));
|
|
149
|
+
// A delta follows its turn's `turn.started`, which this store kept.
|
|
150
|
+
const seq = this.heads.get(sessionId);
|
|
151
|
+
if (seq === undefined)
|
|
152
|
+
throw new Error(`session ${sessionId} has no kept event to follow`);
|
|
153
|
+
return { sessionId, seq, event };
|
|
154
|
+
}
|
|
155
|
+
replay(sessionId, fromSeq) {
|
|
156
|
+
const session = this.journal.session(sessionId);
|
|
157
|
+
if (!session || session.closed)
|
|
158
|
+
return undefined;
|
|
159
|
+
const page = this.journal.replay(sessionId, fromSeq);
|
|
160
|
+
return {
|
|
161
|
+
events: page.events,
|
|
162
|
+
firstAvailableSeq: session.headSeq ? 1 : null,
|
|
163
|
+
latestSeq: session.headSeq || null,
|
|
164
|
+
hasMore: page.hasMore,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
point(sessionId) {
|
|
168
|
+
const session = this.journal.session(sessionId);
|
|
169
|
+
if (!session || session.closed)
|
|
170
|
+
return undefined;
|
|
171
|
+
return { headSeq: session.headSeq, firstAvailableSeq: session.headSeq ? 1 : null };
|
|
172
|
+
}
|
|
173
|
+
terminal(sessionId, turnId) {
|
|
174
|
+
return this.journal.turn(sessionId, turnId)?.terminal;
|
|
175
|
+
}
|
|
176
|
+
closing(sessionId) {
|
|
177
|
+
const session = this.journal.session(sessionId);
|
|
178
|
+
if (!session || session.closed)
|
|
179
|
+
return undefined;
|
|
180
|
+
if (session.recoveryRequired)
|
|
181
|
+
throw new JournalError("recoveryRequired", "Confirm the native process stopped before closing", { headSeq: session.headSeq, reason: session.recoveryReason ?? "not_verified" });
|
|
182
|
+
return session.harness;
|
|
183
|
+
}
|
|
184
|
+
receipt(sessionId, turnId) {
|
|
185
|
+
return this.journal.turn(sessionId, turnId);
|
|
186
|
+
}
|
|
187
|
+
// @ref LLP 0003#commit-before-acknowledging — the latest turn is read for `session/get` alone
|
|
188
|
+
/** `session/get`'s answer: the journal's summary and its latest turn. */
|
|
189
|
+
session(sessionId) {
|
|
190
|
+
const session = this.journal.session(sessionId);
|
|
191
|
+
const lastTurn = session && this.journal.lastTurn(sessionId);
|
|
192
|
+
return session && { ...session, ...(lastTurn && { lastTurn }) };
|
|
193
|
+
}
|
|
194
|
+
confirmStopped(sessionId, expectedHeadSeq) {
|
|
195
|
+
return this.write(() => this.journal.confirmStopped(sessionId, expectedHeadSeq));
|
|
196
|
+
}
|
|
197
|
+
/** The session's native conversation was let go: its next turn must name it. */
|
|
198
|
+
releaseNative(sessionId) {
|
|
199
|
+
this.journal.releaseNative(sessionId);
|
|
200
|
+
}
|
|
201
|
+
relinquish() {
|
|
202
|
+
if (this.relinquished)
|
|
203
|
+
return;
|
|
204
|
+
this.relinquished = true;
|
|
205
|
+
this.releaseClaim();
|
|
206
|
+
}
|
|
207
|
+
/** A request's write: a refusal answers it, and any other failure fails the store. */
|
|
208
|
+
write(operation) {
|
|
209
|
+
if (this.relinquished)
|
|
210
|
+
throw new Error("Journal ownership was released");
|
|
211
|
+
if (this.fault)
|
|
212
|
+
throw new Error("Journal failed; restart and recover before executing");
|
|
213
|
+
try {
|
|
214
|
+
return operation();
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
if (error instanceof JournalError)
|
|
218
|
+
throw error;
|
|
219
|
+
this.failed(error);
|
|
220
|
+
throw error;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/** An event's write: one that fails stops its turn (`EventSinkError`) and fails the store. */
|
|
224
|
+
sink(operation) {
|
|
225
|
+
if (this.relinquished)
|
|
226
|
+
throw new EventSinkError(new Error("Journal ownership was released"));
|
|
227
|
+
if (this.fault)
|
|
228
|
+
throw new EventSinkError(this.fault.error);
|
|
229
|
+
try {
|
|
230
|
+
return operation();
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
this.failed(error);
|
|
234
|
+
throw new EventSinkError(error);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
failed(error) {
|
|
238
|
+
if (this.fault)
|
|
239
|
+
return;
|
|
240
|
+
this.fault = { error };
|
|
241
|
+
this.onFault(error);
|
|
242
|
+
}
|
|
243
|
+
}
|