@zvada/agent-server 0.3.23 → 0.3.24
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 +34 -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 +686 -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 +330 -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 +91 -0
- package/dist/core/processes/lifeline.js +210 -0
- package/dist/core/processes/native-processes.js +299 -0
- package/dist/core/processes/process-table.js +163 -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 +28 -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 +434 -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 +329 -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 +141 -0
- package/dist/protocol/errors.js +181 -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 +291 -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/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 +24 -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/presets.d.ts +2 -2
- package/dist/types/core/presets.d.ts.map +1 -1
- package/dist/types/server/bin.d.ts +3 -0
- package/dist/types/server/bin.d.ts.map +1 -0
- 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 +30 -4
- package/docs/deploy.md +28 -0
- package/docs/harnesses.md +13 -1
- package/package.json +43 -18
- 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 +24 -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/presets.ts +3 -2
- package/src/server/bin.ts +25 -10
- package/src/server/transports.ts +6 -1
- package/src/sync/node-sqlite.ts +19 -3
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { HISTORY_MAX_RECORDS, canonicalJson as canonical, generateUUIDv7, isLiveOnlyEvent, turnIdentity, } from "../protocol/index.js";
|
|
2
|
+
import { EventLog, sha256 } from "./event-log.js";
|
|
3
|
+
import { MAX_EVENT_BYTES, REPLAY_PAGE_BYTES, recordable } from "./fit.js";
|
|
4
|
+
import { SqliteHistory } from "./history-sqlite.js";
|
|
5
|
+
import { JournalError, } from "./journal.js";
|
|
6
|
+
import { LiveTails } from "./live-tails.js";
|
|
7
|
+
import { recoveryFacts } from "./recovery.js";
|
|
8
|
+
import { openSchema } from "./schema.js";
|
|
9
|
+
import { Db } from "./sql.js";
|
|
10
|
+
const fingerprint = (request) => sha256(canonical(turnIdentity(request)));
|
|
11
|
+
/** Ids name histories, whose wire schema bounds them. */
|
|
12
|
+
const storableId = (value) => value.length > 0 && value.length <= 512;
|
|
13
|
+
/** Which reason a session's fence names when several of its records leave it fenced. */
|
|
14
|
+
const REASON_WEIGHT = {
|
|
15
|
+
not_owned: 1,
|
|
16
|
+
not_verified: 2,
|
|
17
|
+
not_stopped: 3,
|
|
18
|
+
};
|
|
19
|
+
/** The journal over any synchronous SQLite connection: the Bun and Node
|
|
20
|
+
* adapters open a private, exclusively locked file for it (`openJournalFile`).
|
|
21
|
+
* Native agent execution is never reconstructed by replaying this database. */
|
|
22
|
+
export class SqliteJournal {
|
|
23
|
+
sourceId;
|
|
24
|
+
/** Every history in this file, the executed sessions' included, read-only for those. */
|
|
25
|
+
history;
|
|
26
|
+
db;
|
|
27
|
+
log;
|
|
28
|
+
claimed = false;
|
|
29
|
+
/** Sessions whose native conversation this owner has started or resumed. */
|
|
30
|
+
live = new Set();
|
|
31
|
+
tails;
|
|
32
|
+
constructor(connection) {
|
|
33
|
+
this.db = new Db(connection);
|
|
34
|
+
try {
|
|
35
|
+
this.sourceId = openSchema(this.db, generateUUIDv7);
|
|
36
|
+
this.log = new EventLog(this.db);
|
|
37
|
+
this.history = new SqliteHistory(this.sourceId, this.db, this.log);
|
|
38
|
+
this.tails = new LiveTails(this.db);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
this.db.close();
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
ref(sessionId) {
|
|
46
|
+
return { sourceId: this.sourceId, sessionId };
|
|
47
|
+
}
|
|
48
|
+
claim(options = {}) {
|
|
49
|
+
if (this.claimed)
|
|
50
|
+
throw new Error("Journal already has an executing owner");
|
|
51
|
+
this.recoverInterrupted(options);
|
|
52
|
+
this.claimed = true;
|
|
53
|
+
this.live.clear();
|
|
54
|
+
return () => {
|
|
55
|
+
this.claimed = false;
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
session(sessionId) {
|
|
59
|
+
const row = this.db.one("SELECT s.*, h.head_seq FROM sessions s JOIN histories h ON h.source_id=? AND h.session_id=s.session_id WHERE s.session_id=?", this.sourceId, sessionId);
|
|
60
|
+
return (row && {
|
|
61
|
+
sessionId: row.session_id,
|
|
62
|
+
harness: row.harness,
|
|
63
|
+
headSeq: row.head_seq,
|
|
64
|
+
nativeSessionId: row.native_id,
|
|
65
|
+
closed: Boolean(row.closed),
|
|
66
|
+
recoveryRequired: Boolean(row.recovery_required),
|
|
67
|
+
...(row.recovery_required &&
|
|
68
|
+
row.recovery_reason && { recoveryReason: row.recovery_reason }),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
lastTurn(sessionId) {
|
|
72
|
+
// An admitted turn has no terminal yet: it sorts first, then the latest ended.
|
|
73
|
+
const row = this.db.one("SELECT t.turn_id, e.body AS terminal FROM turns t LEFT JOIN events e ON e.source_id=? AND e.session_id=t.session_id AND e.seq=t.terminal_seq WHERE t.session_id=? ORDER BY t.state='admitted' DESC, t.terminal_seq DESC LIMIT 1", this.sourceId, sessionId);
|
|
74
|
+
if (!row)
|
|
75
|
+
return undefined;
|
|
76
|
+
if (row.terminal === null)
|
|
77
|
+
return { turnId: row.turn_id };
|
|
78
|
+
const { stopReason, error } = JSON.parse(row.terminal);
|
|
79
|
+
return { turnId: row.turn_id, stopReason, ...(error && { error }) };
|
|
80
|
+
}
|
|
81
|
+
turn(sessionId, turnId) {
|
|
82
|
+
const row = this.db.one("SELECT t.state, t.input, e.body AS terminal FROM turns t LEFT JOIN events e ON e.source_id=? AND e.session_id=t.session_id AND e.seq=t.terminal_seq WHERE t.session_id=? AND t.turn_id=?", this.sourceId, sessionId, turnId);
|
|
83
|
+
return (row && {
|
|
84
|
+
sessionId,
|
|
85
|
+
turnId,
|
|
86
|
+
state: row.state,
|
|
87
|
+
input: JSON.parse(row.input),
|
|
88
|
+
...(row.terminal !== null && { terminal: JSON.parse(row.terminal) }),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
admission(request) {
|
|
92
|
+
const row = this.db.one("SELECT fingerprint FROM turns WHERE session_id=? AND turn_id=?", request.sessionId, request.turnId);
|
|
93
|
+
if (!row)
|
|
94
|
+
return "new";
|
|
95
|
+
if (row.fingerprint !== fingerprint(request))
|
|
96
|
+
throw new JournalError("turnConflict", "Turn ID already belongs to a different request", {
|
|
97
|
+
turnId: request.turnId,
|
|
98
|
+
});
|
|
99
|
+
return "duplicate";
|
|
100
|
+
}
|
|
101
|
+
admit(request) {
|
|
102
|
+
const { sessionId, turnId, config } = request;
|
|
103
|
+
if (!storableId(sessionId) || !storableId(turnId))
|
|
104
|
+
throw new JournalError("invalidParams", "Durable session and turn IDs are 1-512 characters");
|
|
105
|
+
if (this.history.isBranch(sessionId))
|
|
106
|
+
throw new JournalError("invalidParams", "History branch is not a native execution session; prepare provider context explicitly");
|
|
107
|
+
const input = canonical(request.input);
|
|
108
|
+
const bytes = Buffer.byteLength(input);
|
|
109
|
+
if (bytes > MAX_EVENT_BYTES)
|
|
110
|
+
// `invalidParams` carries no data on the wire (`WIRE_REFUSAL_DATA`): the words say it.
|
|
111
|
+
throw new JournalError("invalidParams", `Input is ${bytes} bytes; the durable record limit is ${MAX_EVENT_BYTES} bytes`);
|
|
112
|
+
return this.db.atomic(() => {
|
|
113
|
+
if (this.admission(request) === "duplicate")
|
|
114
|
+
return "duplicate";
|
|
115
|
+
const state = this.session(sessionId);
|
|
116
|
+
if (state?.closed)
|
|
117
|
+
throw new JournalError("sessionClosed", "Closed durable session IDs cannot be reused");
|
|
118
|
+
if (state?.recoveryRequired)
|
|
119
|
+
throw new JournalError("recoveryRequired", "Confirm the interrupted native execution stopped before starting another turn", { headSeq: state.headSeq, reason: state.recoveryReason ?? "not_verified" });
|
|
120
|
+
// Without its native conversation, a turn would silently start a new one.
|
|
121
|
+
if (state?.nativeSessionId &&
|
|
122
|
+
!this.live.has(sessionId) &&
|
|
123
|
+
config.resumeSessionId !== state.nativeSessionId)
|
|
124
|
+
throw new JournalError("resumeRequired", "This session was restored; explicitly pass its nativeSessionId as config.resumeSessionId, or start a new session", { nativeSessionId: state.nativeSessionId });
|
|
125
|
+
if (state && state.harness !== config.harness)
|
|
126
|
+
throw new JournalError("invalidParams", "Session harness cannot change");
|
|
127
|
+
if (config.includeRaw)
|
|
128
|
+
throw new JournalError("invalidParams", "Durable sessions require includeRaw=false");
|
|
129
|
+
const active = this.activeTurn(sessionId);
|
|
130
|
+
if (active)
|
|
131
|
+
throw new JournalError("turnActive", "Session already has an admitted turn", {
|
|
132
|
+
turnId: active,
|
|
133
|
+
});
|
|
134
|
+
if (!state) {
|
|
135
|
+
this.db.run("INSERT INTO sessions(session_id,harness) VALUES (?,?)", sessionId, config.harness);
|
|
136
|
+
this.log.create({ ...this.ref(sessionId), format: 1, kind: "execution" });
|
|
137
|
+
}
|
|
138
|
+
this.db.run("INSERT INTO turns(session_id,turn_id,fingerprint,input,state) VALUES (?,?,?,?,'admitted')", sessionId, turnId, fingerprint(request), input);
|
|
139
|
+
return "new";
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
activeTurn(sessionId) {
|
|
143
|
+
return this.db.one("SELECT turn_id FROM turns WHERE session_id=? AND state='admitted'", sessionId)?.turn_id;
|
|
144
|
+
}
|
|
145
|
+
append(event) {
|
|
146
|
+
const { sessionId } = event;
|
|
147
|
+
if (!sessionId)
|
|
148
|
+
throw new JournalError("invalidParams", "Durable events require a session ID");
|
|
149
|
+
if (isLiveOnlyEvent(event))
|
|
150
|
+
throw new JournalError("invalidParams", "Token deltas are live only; a journal never stores them");
|
|
151
|
+
const stored = recordable({ ...event, sessionId });
|
|
152
|
+
const envelope = this.db.atomic(() => {
|
|
153
|
+
const recorded = this.record(stored.event, stored.body);
|
|
154
|
+
this.apply(recorded.event, recorded.seq);
|
|
155
|
+
return recorded;
|
|
156
|
+
});
|
|
157
|
+
if (envelope.event.type === "session.created")
|
|
158
|
+
this.live.add(sessionId);
|
|
159
|
+
this.history.changed(this.ref(sessionId));
|
|
160
|
+
return envelope;
|
|
161
|
+
}
|
|
162
|
+
keepTail(event) {
|
|
163
|
+
this.tails.keep(event);
|
|
164
|
+
}
|
|
165
|
+
/** Inside a transaction: record one storable event of an open session. */
|
|
166
|
+
record(event, body) {
|
|
167
|
+
const { sessionId } = event;
|
|
168
|
+
const state = this.session(sessionId);
|
|
169
|
+
if (!state || state.closed)
|
|
170
|
+
throw new JournalError("sessionClosed", "Cannot append to an unknown or closed session");
|
|
171
|
+
if (event.type === "session.ended" && (state.recoveryRequired || this.activeTurn(sessionId)))
|
|
172
|
+
throw new JournalError("recoveryRequired", "Cannot close a session with unconfirmed execution");
|
|
173
|
+
const head = this.log.head(this.ref(sessionId)).version;
|
|
174
|
+
const { seq } = this.log.append(head, [body]);
|
|
175
|
+
return { sessionId, seq, event: JSON.parse(body) };
|
|
176
|
+
}
|
|
177
|
+
/** What a recorded event changes beyond the history. */
|
|
178
|
+
apply(event, seq) {
|
|
179
|
+
switch (event.type) {
|
|
180
|
+
case "session.created":
|
|
181
|
+
this.db.run("UPDATE sessions SET native_id=? WHERE session_id=?", event.nativeSessionId, event.sessionId);
|
|
182
|
+
break;
|
|
183
|
+
case "message.part":
|
|
184
|
+
// A kept snapshot holds what its part streamed so far.
|
|
185
|
+
this.tails.dropPart(event.sessionId, event.part.id);
|
|
186
|
+
break;
|
|
187
|
+
case "turn.ended":
|
|
188
|
+
this.settle(event.sessionId, event.turnId, "completed", seq);
|
|
189
|
+
this.tails.dropTurn(event.sessionId, event.turnId);
|
|
190
|
+
break;
|
|
191
|
+
case "session.ended":
|
|
192
|
+
this.db.run("UPDATE sessions SET closed=1 WHERE session_id=?", event.sessionId);
|
|
193
|
+
// A closed session's processes were released with it.
|
|
194
|
+
this.db.run("DELETE FROM native_processes WHERE session_id=?", event.sessionId);
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
settle(sessionId, turnId, state, terminalSeq) {
|
|
199
|
+
this.db.run("UPDATE turns SET state=?, terminal_seq=? WHERE session_id=? AND turn_id=? AND state='admitted'", state, terminalSeq, sessionId, turnId);
|
|
200
|
+
}
|
|
201
|
+
replay(sessionId, fromSeq, limit = HISTORY_MAX_RECORDS) {
|
|
202
|
+
const ref = this.ref(sessionId);
|
|
203
|
+
const head = this.log.head(ref)?.version.seq ?? 0;
|
|
204
|
+
// Each envelope: {"sessionId":…,"seq":…,"event":BODY} and its comma.
|
|
205
|
+
const envelope = Buffer.byteLength(JSON.stringify(sessionId)) + 48;
|
|
206
|
+
const rows = this.log.page(ref, fromSeq - 1, head, {
|
|
207
|
+
limit: Math.min(limit, HISTORY_MAX_RECORDS),
|
|
208
|
+
maxBytes: REPLAY_PAGE_BYTES,
|
|
209
|
+
overhead: () => envelope,
|
|
210
|
+
// Every stored event fits a page alone; a page holds as many as fit together.
|
|
211
|
+
oversizedFirst: true,
|
|
212
|
+
});
|
|
213
|
+
return {
|
|
214
|
+
events: rows.map((row) => ({
|
|
215
|
+
sessionId,
|
|
216
|
+
seq: row.seq,
|
|
217
|
+
event: JSON.parse(row.body),
|
|
218
|
+
})),
|
|
219
|
+
hasMore: (rows.at(-1)?.seq ?? fromSeq - 1) < head,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
/** End each turn a previous owner left admitted, closing what it left open first,
|
|
223
|
+
* so its history stays a valid stream; fence its session until confirmed
|
|
224
|
+
* unless the restart sweep stopped every process it recorded for it. */
|
|
225
|
+
recoverInterrupted(options) {
|
|
226
|
+
this.db.atomic(() => {
|
|
227
|
+
const fences = this.sweptFences(options);
|
|
228
|
+
const admitted = this.db.all("SELECT t.session_id, t.turn_id, s.harness FROM turns t JOIN sessions s USING (session_id) WHERE t.state='admitted'");
|
|
229
|
+
for (const { session_id: sessionId, turn_id: turnId, harness } of admitted) {
|
|
230
|
+
const history = [...this.log.records(this.ref(sessionId), 0, Number.MAX_SAFE_INTEGER)].map((row) => JSON.parse(row.body));
|
|
231
|
+
const tails = this.tails.ofTurn(sessionId, turnId);
|
|
232
|
+
// @ref LLP 0007#records-and-the-restart-sweep — fenced only when its agent was not seen stopped
|
|
233
|
+
const unrecorded = options.recorded && !options.recorded.has(harness);
|
|
234
|
+
const fence = fences && !unrecorded ? fences.get(sessionId) : "not_verified";
|
|
235
|
+
let seq = 0;
|
|
236
|
+
for (const fact of recoveryFacts(history, {
|
|
237
|
+
sessionId,
|
|
238
|
+
turnId,
|
|
239
|
+
harness,
|
|
240
|
+
at: Date.now(),
|
|
241
|
+
tails,
|
|
242
|
+
...(fence && { fence }),
|
|
243
|
+
})) {
|
|
244
|
+
const stored = recordable(fact);
|
|
245
|
+
seq = this.record(stored.event, stored.body).seq;
|
|
246
|
+
}
|
|
247
|
+
this.settle(sessionId, turnId, "interrupted", seq);
|
|
248
|
+
if (fence)
|
|
249
|
+
this.db.run("UPDATE sessions SET recovery_required=1, recovery_reason=? WHERE session_id=?", fence, sessionId);
|
|
250
|
+
}
|
|
251
|
+
this.tails.clear();
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
/** Inside a transaction: drop the records the sweep saw stopped, and say which
|
|
255
|
+
* sessions the others leave fenced, and why. Undefined: no sweep ran. */
|
|
256
|
+
sweptFences(options) {
|
|
257
|
+
if (!options.stopped)
|
|
258
|
+
return undefined;
|
|
259
|
+
const fences = new Map();
|
|
260
|
+
for (const row of this.db.all("SELECT * FROM native_processes")) {
|
|
261
|
+
if (options.stopped.has(row.id)) {
|
|
262
|
+
this.db.run("DELETE FROM native_processes WHERE id=?", row.id);
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
const reason = row.pid === null
|
|
266
|
+
? "not_owned"
|
|
267
|
+
: options.notStopped?.has(row.id)
|
|
268
|
+
? "not_stopped"
|
|
269
|
+
: "not_verified";
|
|
270
|
+
const known = fences.get(row.session_id);
|
|
271
|
+
if (!known || REASON_WEIGHT[reason] > REASON_WEIGHT[known])
|
|
272
|
+
fences.set(row.session_id, reason);
|
|
273
|
+
}
|
|
274
|
+
return fences;
|
|
275
|
+
}
|
|
276
|
+
confirmStopped(sessionId, expectedHeadSeq) {
|
|
277
|
+
return this.db.atomic(() => {
|
|
278
|
+
const state = this.session(sessionId);
|
|
279
|
+
if (!state || state.headSeq !== expectedHeadSeq)
|
|
280
|
+
throw new JournalError(state ? "historyConflict" : "unknownSession", state ? "Recovery confirmation names an old history position" : "Unknown durable session", state && { headSeq: state.headSeq });
|
|
281
|
+
if (!state.recoveryRequired)
|
|
282
|
+
return false;
|
|
283
|
+
this.db.run("UPDATE sessions SET recovery_required=0, recovery_reason=NULL WHERE session_id=?", sessionId);
|
|
284
|
+
// The host's word covers what the sweep could not verify.
|
|
285
|
+
this.db.run("DELETE FROM native_processes WHERE session_id=?", sessionId);
|
|
286
|
+
return true;
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
releaseNative(sessionId) {
|
|
290
|
+
this.live.delete(sessionId);
|
|
291
|
+
}
|
|
292
|
+
recordNative(record) {
|
|
293
|
+
const row = this.db.one("INSERT INTO native_processes(session_id,harness,pid,boot,started,executable) VALUES (?,?,?,?,?,?) RETURNING id", record.sessionId, record.harness, record.pid, record.boot, record.started, record.executable);
|
|
294
|
+
if (!row)
|
|
295
|
+
throw new Error("The journal kept no record of the native process");
|
|
296
|
+
return row.id;
|
|
297
|
+
}
|
|
298
|
+
forgetNative(id) {
|
|
299
|
+
this.db.run("DELETE FROM native_processes WHERE id=?", id);
|
|
300
|
+
}
|
|
301
|
+
nativeProcesses() {
|
|
302
|
+
return this.db.all("SELECT * FROM native_processes ORDER BY id").map((row) => ({
|
|
303
|
+
id: row.id,
|
|
304
|
+
sessionId: row.session_id,
|
|
305
|
+
harness: row.harness,
|
|
306
|
+
pid: row.pid,
|
|
307
|
+
boot: row.boot,
|
|
308
|
+
started: row.started,
|
|
309
|
+
executable: row.executable,
|
|
310
|
+
}));
|
|
311
|
+
}
|
|
312
|
+
close() {
|
|
313
|
+
this.history.close();
|
|
314
|
+
this.db.close();
|
|
315
|
+
}
|
|
316
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { WireRefusal, } from "../protocol/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* What a journal refuses, as opposed to failing to store: the request itself
|
|
4
|
+
* is the problem, nothing was written, and the journal stays usable. Any other
|
|
5
|
+
* error a journal throws means its storage failed. Its code is the wire error
|
|
6
|
+
* the server answers with.
|
|
7
|
+
*/
|
|
8
|
+
export class JournalError extends WireRefusal {
|
|
9
|
+
name = "JournalError";
|
|
10
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
const keyOf = (sessionId, partId) => `${sessionId}\u0000${partId}`;
|
|
2
|
+
/**
|
|
3
|
+
* Each streaming part's tail, kept outside every history so recovery closes
|
|
4
|
+
* the part with what was shown: one row per delta. The only code that touches
|
|
5
|
+
* the `live_tails` table, as `EventLog` is for the histories; which parts
|
|
6
|
+
* have rows is kept in memory too, to number the next row and drop a turn's.
|
|
7
|
+
*/
|
|
8
|
+
export class LiveTails {
|
|
9
|
+
db;
|
|
10
|
+
tails = new Map();
|
|
11
|
+
constructor(db) {
|
|
12
|
+
this.db = db;
|
|
13
|
+
}
|
|
14
|
+
// @ref LLP 0003#a-crash-keeps-what-was-shown — written before the delta is delivered
|
|
15
|
+
// @ref LLP 0008#the-journal-live_tails-becomes-append-only — a row per delta, never the whole part again
|
|
16
|
+
/** Append what `event` streamed to its part's tail. */
|
|
17
|
+
keep(event) {
|
|
18
|
+
const key = keyOf(event.sessionId, event.partId);
|
|
19
|
+
let tail = this.tails.get(key);
|
|
20
|
+
if (!tail) {
|
|
21
|
+
tail = { sessionId: event.sessionId, turnId: event.turnId, partId: event.partId, rows: 0 };
|
|
22
|
+
this.tails.set(key, tail);
|
|
23
|
+
}
|
|
24
|
+
// Every delta, as kept events are committed before delivery: a model can
|
|
25
|
+
// stream hundreds of characters in one burst, and what a client was
|
|
26
|
+
// shown must not depend on a timer. A row of its own: the tail is the
|
|
27
|
+
// whole part now that no checkpoint is kept, and rewriting it per delta
|
|
28
|
+
// grows with the square of its length (250 MB written for a 100 KB tool
|
|
29
|
+
// input, where appending costs a flat 14 µs). Without an fsync: a
|
|
30
|
+
// committed write survives the process dying at any `synchronous` level
|
|
31
|
+
// (only power loss could lose it), and the next kept event's commit
|
|
32
|
+
// flushes it; an fsync'd write took 60 µs on a laptop and a millisecond
|
|
33
|
+
// on cloud disks, on the server's one thread.
|
|
34
|
+
const level = this.relaxSync();
|
|
35
|
+
try {
|
|
36
|
+
this.db.run("INSERT INTO live_tails(session_id,turn_id,part_id,n,body) VALUES (?,?,?,?,?)", tail.sessionId, tail.turnId, tail.partId, tail.rows, event.delta.type === "tool_input" ? event.delta.input : event.delta.text);
|
|
37
|
+
tail.rows++;
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
if (level !== undefined)
|
|
41
|
+
this.db.exec(`PRAGMA synchronous=${level}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** The part's kept snapshot holds what it streamed so far. */
|
|
45
|
+
dropPart(sessionId, partId) {
|
|
46
|
+
if (!this.tails.delete(keyOf(sessionId, partId)))
|
|
47
|
+
return;
|
|
48
|
+
this.db.run("DELETE FROM live_tails WHERE session_id=? AND part_id=?", sessionId, partId);
|
|
49
|
+
}
|
|
50
|
+
/** The turn ended: its parts stream no more. */
|
|
51
|
+
dropTurn(sessionId, turnId) {
|
|
52
|
+
for (const tail of [...this.tails.values()])
|
|
53
|
+
if (tail.sessionId === sessionId && tail.turnId === turnId)
|
|
54
|
+
this.dropPart(sessionId, tail.partId);
|
|
55
|
+
}
|
|
56
|
+
/** What the turn's parts streamed after their last kept snapshots, by part id: their rows joined in order. */
|
|
57
|
+
ofTurn(sessionId, turnId) {
|
|
58
|
+
const tails = new Map();
|
|
59
|
+
for (const row of this.db.all("SELECT part_id,body FROM live_tails WHERE session_id=? AND turn_id=? ORDER BY part_id,n", sessionId, turnId))
|
|
60
|
+
tails.set(row.part_id, (tails.get(row.part_id) ?? "") + row.body);
|
|
61
|
+
return tails;
|
|
62
|
+
}
|
|
63
|
+
/** Forget every tail: only an interrupted turn's mean anything, and recovery took them. */
|
|
64
|
+
clear() {
|
|
65
|
+
this.tails.clear();
|
|
66
|
+
this.db.run("DELETE FROM live_tails");
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Set the connection to NORMAL for one write, returning the level to put
|
|
70
|
+
* back: read each time, as SQLite moves an unset level by itself. Best
|
|
71
|
+
* effort: a host that refuses the pragma gets the write as it stands.
|
|
72
|
+
*/
|
|
73
|
+
relaxSync() {
|
|
74
|
+
try {
|
|
75
|
+
const level = this.db.one("PRAGMA synchronous")?.synchronous;
|
|
76
|
+
if (level === undefined || level <= 1)
|
|
77
|
+
return undefined;
|
|
78
|
+
this.db.exec("PRAGMA synchronous=NORMAL");
|
|
79
|
+
return level;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { SqliteJournal } from "./journal-sqlite.js";
|
|
2
|
+
import { openJournalFile } from "./sqlite-file.js";
|
|
3
|
+
/** Node >=22.16 adapter (node:sqlite). Same schema and guarantees as Bun.
|
|
4
|
+
* `node:sqlite` loads when a journal opens, not when this module does: a
|
|
5
|
+
* bundle holding both adapters (the bin, compiled by Bun into one binary)
|
|
6
|
+
* hoists a static import of it, which Bun, without the module, refuses at
|
|
7
|
+
* start; and Node 22 warns that it is experimental on its first load. */
|
|
8
|
+
export class NodeSqliteSessionJournal extends SqliteJournal {
|
|
9
|
+
constructor(path) {
|
|
10
|
+
super(openJournalFile(path, (file) => {
|
|
11
|
+
const db = new (nodeSqlite().DatabaseSync)(file);
|
|
12
|
+
return {
|
|
13
|
+
exec: (sql) => db.exec(sql),
|
|
14
|
+
prepare: (sql) => db.prepare(sql),
|
|
15
|
+
close: () => db.close(),
|
|
16
|
+
};
|
|
17
|
+
}));
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** `node:sqlite`, loaded now: Bun answers undefined for a module it does not have. */
|
|
21
|
+
function nodeSqlite() {
|
|
22
|
+
// @ref LLP 0001#d24--bun-runs-the-packages-sources-every-other-runtime-its-compiled-javascript — loaded when a journal opens
|
|
23
|
+
const sqlite = process.getBuiltinModule("node:sqlite");
|
|
24
|
+
if (!sqlite)
|
|
25
|
+
throw new Error("this runtime has no node:sqlite: use Node >=22.16, or under Bun the bun:sqlite journal (./sync/sqlite)");
|
|
26
|
+
return sqlite;
|
|
27
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { HISTORY_MAX_BYTES, HistoryError, decodeLifecycleEvent, jsonBytes, reduceConversation, } from "../protocol/index.js";
|
|
2
|
+
import { omitBinaries } from "./fit.js";
|
|
3
|
+
/** The most events a projection folds unless its caller says otherwise: it is built in memory. */
|
|
4
|
+
const MAX_PROJECTION_RECORDS = 100_000;
|
|
5
|
+
/**
|
|
6
|
+
* A fold of history events into a conversation that takes at most
|
|
7
|
+
* `maxRecords` of them, across every call: past that it throws, and a longer
|
|
8
|
+
* history is read in pages instead.
|
|
9
|
+
*/
|
|
10
|
+
export function projectionFold(maxRecords = MAX_PROJECTION_RECORDS) {
|
|
11
|
+
if (!Number.isSafeInteger(maxRecords) || maxRecords < 0)
|
|
12
|
+
throw new Error("maxRecords must be a nonnegative safe integer");
|
|
13
|
+
let left = maxRecords;
|
|
14
|
+
return (conversation, event) => {
|
|
15
|
+
if (--left < 0)
|
|
16
|
+
throw new Error("History projection limit exceeded; use paged reads");
|
|
17
|
+
return reduceConversation(conversation, decodeLifecycleEvent(event));
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* `checkpoint` with its largest images and files replaced by text saying what
|
|
22
|
+
* they were until it fits a history page (`omitBinaries`): binaries alone never
|
|
23
|
+
* make a checkpoint too large to keep. The events keep what they kept.
|
|
24
|
+
*/
|
|
25
|
+
export function fitCheckpoint(checkpoint) {
|
|
26
|
+
return omitBinaries(checkpoint, HISTORY_MAX_BYTES, "this checkpoint");
|
|
27
|
+
}
|
|
28
|
+
/** A checkpoint fits a history page, as all history does: no store keeps, and no reader takes, a larger one. */
|
|
29
|
+
export function checkCheckpointBytes(checkpoint) {
|
|
30
|
+
if (jsonBytes(checkpoint) > HISTORY_MAX_BYTES)
|
|
31
|
+
throw new HistoryError("invalidParams", "Checkpoint exceeds byte limit; use paged history");
|
|
32
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { closeToolLeftOpen, decodeLifecycleEvent, emptyConversation, isUnknownEvent, reduceConversation, } from "../protocol/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* The facts that end a turn a server restart cut off, in the order to commit
|
|
4
|
+
* them, so its history stays a valid stream: its `turn.started` when it was
|
|
5
|
+
* cut off before its first event; then what it left open closed (pending
|
|
6
|
+
* permissions and questions cancelled, running tools failed as interrupted,
|
|
7
|
+
* streaming parts done with their tails, open messages ended); then its
|
|
8
|
+
* `turn.ended`. `history` is the session's committed events, oldest first.
|
|
9
|
+
*/
|
|
10
|
+
export function recoveryFacts(history, turn) {
|
|
11
|
+
const { sessionId, turnId, at } = turn;
|
|
12
|
+
let state = emptyConversation();
|
|
13
|
+
const address = new Map();
|
|
14
|
+
for (const raw of history) {
|
|
15
|
+
const event = decodeLifecycleEvent(raw);
|
|
16
|
+
state = reduceConversation(state, event);
|
|
17
|
+
if (!isUnknownEvent(event) && event.type === "message.part" && event.turnId === turnId)
|
|
18
|
+
address.set(event.part.id, {
|
|
19
|
+
messageId: event.messageId,
|
|
20
|
+
outputIndex: event.outputIndex,
|
|
21
|
+
partIndex: event.partIndex,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
const facts = [];
|
|
25
|
+
if (!state.turns.some((t) => t.turnId === turnId))
|
|
26
|
+
facts.push({
|
|
27
|
+
type: "turn.started",
|
|
28
|
+
sessionId,
|
|
29
|
+
turnId,
|
|
30
|
+
execution: { harness: turn.harness },
|
|
31
|
+
timestamp: at,
|
|
32
|
+
});
|
|
33
|
+
for (const permission of state.permissions)
|
|
34
|
+
if (permission.turnId === turnId && permission.outcome === undefined)
|
|
35
|
+
facts.push({
|
|
36
|
+
type: "permission.resolved",
|
|
37
|
+
sessionId,
|
|
38
|
+
turnId,
|
|
39
|
+
requestId: permission.requestId,
|
|
40
|
+
outcome: { outcome: "cancelled" },
|
|
41
|
+
timestamp: at,
|
|
42
|
+
});
|
|
43
|
+
for (const elicitation of state.elicitations)
|
|
44
|
+
if (elicitation.turnId === turnId && elicitation.outcome === undefined)
|
|
45
|
+
facts.push({
|
|
46
|
+
type: "elicitation.resolved",
|
|
47
|
+
sessionId,
|
|
48
|
+
turnId,
|
|
49
|
+
requestId: elicitation.requestId,
|
|
50
|
+
outcome: { action: "cancel" },
|
|
51
|
+
timestamp: at,
|
|
52
|
+
});
|
|
53
|
+
// Whether a tool that may have run was open at the cut: only then is its outcome unknown.
|
|
54
|
+
let toolRan = false;
|
|
55
|
+
for (const entry of state.timeline) {
|
|
56
|
+
if (entry.kind !== "message" || entry.turnId !== turnId)
|
|
57
|
+
continue;
|
|
58
|
+
// A tool keeps running after the model message that called it ends, and
|
|
59
|
+
// its later states update the part under that ended message.
|
|
60
|
+
for (const part of entry.parts) {
|
|
61
|
+
if ("raw" in part)
|
|
62
|
+
continue;
|
|
63
|
+
const where = address.get(part.id);
|
|
64
|
+
const closed = where && closePart(state, turnId, part, at, turn.tails.get(part.id));
|
|
65
|
+
if (closed?.type === "tool" && closed.state.status === "failed")
|
|
66
|
+
toolRan ||= closed.state.closure === "interrupted";
|
|
67
|
+
if (where && closed)
|
|
68
|
+
facts.push({
|
|
69
|
+
type: "message.part",
|
|
70
|
+
sessionId,
|
|
71
|
+
turnId,
|
|
72
|
+
...where,
|
|
73
|
+
part: closed,
|
|
74
|
+
timestamp: at,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (entry.endedAt === undefined)
|
|
78
|
+
facts.push({
|
|
79
|
+
type: "message.ended",
|
|
80
|
+
sessionId,
|
|
81
|
+
turnId,
|
|
82
|
+
messageId: entry.messageId,
|
|
83
|
+
timestamp: at,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
// @ref LLP 0003#commit-before-acknowledging — what the restart found, never what to do:
|
|
87
|
+
// the history outlives a fence, which `recoveryRequired` alone says is still up.
|
|
88
|
+
const agent = turn.fence
|
|
89
|
+
? `Its agent could not be confirmed stopped at restart (${turn.fence})`
|
|
90
|
+
: "Its agent was stopped at restart";
|
|
91
|
+
facts.push({
|
|
92
|
+
type: "turn.ended",
|
|
93
|
+
sessionId,
|
|
94
|
+
turnId,
|
|
95
|
+
stopReason: "error",
|
|
96
|
+
error: {
|
|
97
|
+
category: "server_restart",
|
|
98
|
+
message: `Server restarted before the turn settled. ${agent}${toolRan ? "; what its running tool did is unknown" : ""}.`,
|
|
99
|
+
},
|
|
100
|
+
timestamp: at,
|
|
101
|
+
});
|
|
102
|
+
return facts;
|
|
103
|
+
}
|
|
104
|
+
// A tool closes as the reducer closes it, interrupted where it may have run.
|
|
105
|
+
// A streaming part keeps what it streamed after its last kept snapshot.
|
|
106
|
+
function closePart(state, turnId, part, at, tail = "") {
|
|
107
|
+
if (part.type === "tool")
|
|
108
|
+
return closeToolLeftOpen(state, turnId, part, {
|
|
109
|
+
at,
|
|
110
|
+
cancelled: false,
|
|
111
|
+
outcomeUnknown: "interrupted",
|
|
112
|
+
tail,
|
|
113
|
+
});
|
|
114
|
+
if ((part.type === "text" || part.type === "reasoning") && part.state === "streaming")
|
|
115
|
+
return { ...part, text: part.text + tail, state: "done" };
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** Resolves after `ms`, or as soon as `signal` aborts (without throwing). */
|
|
2
|
+
export function pause(ms, signal) {
|
|
3
|
+
if (signal?.aborted)
|
|
4
|
+
return Promise.resolve();
|
|
5
|
+
return new Promise((resolve) => {
|
|
6
|
+
const done = () => {
|
|
7
|
+
clearTimeout(timer);
|
|
8
|
+
signal?.removeEventListener("abort", done);
|
|
9
|
+
resolve();
|
|
10
|
+
};
|
|
11
|
+
const timer = setTimeout(done, ms);
|
|
12
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
/** The shortest time between two waits that brought nothing. */
|
|
16
|
+
const IDLE_FLOOR_MS = 100;
|
|
17
|
+
/** After a wait that brought nothing, pause what remains of the idle floor: a
|
|
18
|
+
* wait answered at once (a zero timeout, or one a short request timeout clamps)
|
|
19
|
+
* must not spin. */
|
|
20
|
+
export function idleAfter(waitStartedAt, signal) {
|
|
21
|
+
return pause(Math.max(0, IDLE_FLOOR_MS - (Date.now() - waitStartedAt)), signal);
|
|
22
|
+
}
|
|
23
|
+
/** Consecutive failures under a retry policy. Only progress puts them behind:
|
|
24
|
+
* a read that changes nothing does not repair a channel that keeps failing. */
|
|
25
|
+
export class RetryBudget {
|
|
26
|
+
policy;
|
|
27
|
+
consecutive = 0;
|
|
28
|
+
constructor(policy) {
|
|
29
|
+
this.policy = policy;
|
|
30
|
+
}
|
|
31
|
+
get failures() {
|
|
32
|
+
return this.consecutive;
|
|
33
|
+
}
|
|
34
|
+
/** The delay before retrying (at most a minute), or `error` rethrown when
|
|
35
|
+
* the policy gives up. */
|
|
36
|
+
fail(error) {
|
|
37
|
+
const ms = this.policy?.(error, ++this.consecutive);
|
|
38
|
+
if (ms === undefined || !Number.isFinite(ms) || ms < 0)
|
|
39
|
+
throw error;
|
|
40
|
+
return Math.min(ms, 60_000);
|
|
41
|
+
}
|
|
42
|
+
progressed() {
|
|
43
|
+
this.consecutive = 0;
|
|
44
|
+
}
|
|
45
|
+
}
|