@anhlp/alp-daemon 0.0.0-beta.2 → 0.0.1-beta.10
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/README.md +4 -0
- package/dist/THIRD-PARTY-NOTICES.txt +27 -2
- package/dist/alpd.js +39374 -17503
- package/dist/attachments.d.ts +187 -0
- package/dist/attachments.js +856 -0
- package/dist/build-manifest.json +41 -2
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +688 -0
- package/dist/disk.d.ts +67 -0
- package/dist/disk.js +152 -0
- package/dist/files.d.ts +156 -3
- package/dist/files.js +402 -59
- package/dist/git.d.ts +98 -0
- package/dist/git.js +1246 -0
- package/dist/gitignore.d.ts +5 -0
- package/dist/gitignore.js +26 -7
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +21 -1
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/main.js +146 -21
- package/dist/model-catalog.d.ts +2 -0
- package/dist/model-catalog.js +44 -0
- package/dist/native-entry.d.ts +2 -0
- package/dist/native-entry.js +3 -0
- package/dist/native-register.d.ts +1 -0
- package/dist/native-register.js +13 -0
- package/dist/native-terminal.d.ts +45 -0
- package/dist/native-terminal.js +201 -0
- package/dist/operations.d.ts +20 -3
- package/dist/operations.js +62 -21
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +298 -0
- package/dist/schedules.d.ts +70 -0
- package/dist/schedules.js +246 -0
- package/dist/server.d.ts +14 -2
- package/dist/server.js +903 -97
- package/dist/store.d.ts +72 -2
- package/dist/store.js +111 -4
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal-screen.d.ts +24 -0
- package/dist/terminal-screen.js +99 -0
- package/dist/terminals.d.ts +203 -0
- package/dist/terminals.js +570 -0
- package/dist/windows-terminal.d.ts +32 -0
- package/dist/windows-terminal.js +79 -0
- package/dist/worktrees.d.ts +65 -0
- package/dist/worktrees.js +318 -0
- package/native/README.md +201 -0
- package/native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/native/prebuilt/darwin-x64/manifest.json +11 -0
- package/native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/native/terminal-owner.c +389 -0
- package/package.json +71 -8
- package/src/attachments.ts +908 -0
- package/src/conversation.ts +857 -0
- package/src/disk.ts +175 -0
- package/src/files.ts +535 -71
- package/src/git.ts +1220 -0
- package/src/gitignore.ts +25 -8
- package/src/history.ts +118 -0
- package/src/index.ts +7 -0
- package/src/lifecycle.ts +283 -0
- package/src/main.ts +154 -23
- package/src/model-catalog.ts +36 -0
- package/src/native-entry.ts +5 -0
- package/src/native-register.ts +21 -0
- package/src/native-terminal.ts +127 -0
- package/src/operations.ts +53 -22
- package/src/registry.ts +238 -0
- package/src/scheduler.ts +438 -0
- package/src/schedules.ts +297 -0
- package/src/server.ts +1019 -109
- package/src/store.ts +117 -4
- package/src/terminal-screen.ts +74 -0
- package/src/terminals.ts +653 -0
- package/src/windows-terminal.ts +74 -0
- package/src/worktrees.ts +382 -0
|
@@ -0,0 +1,688 @@
|
|
|
1
|
+
// packages/daemon/src/conversation.ts
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { realpath } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { ERROR, RPC_ERROR, resumeCommandOf } from "@anhlp/alp-protocol";
|
|
6
|
+
import { RegistryError } from "./registry.js";
|
|
7
|
+
import { createLifecycle } from "./lifecycle.js";
|
|
8
|
+
import { RpcError } from "./rpc-error.js";
|
|
9
|
+
var CONVERSATION = /* @__PURE__ */ new Set(["item", "turn.started", "turn.ended", "prompt.accepted", "prompt.failed"]);
|
|
10
|
+
var SUPPORTED = /* @__PURE__ */ new Set(["codex", "claude"]);
|
|
11
|
+
var LISTED_BRANCHES = 100;
|
|
12
|
+
function defaultForkTitle(sourceTitle, sameWorkspace) {
|
|
13
|
+
return sameWorkspace ? `${sourceTitle ?? "Session"} (fork)`.slice(0, 200) : "Fork of a session";
|
|
14
|
+
}
|
|
15
|
+
function turnsOf(log, root) {
|
|
16
|
+
const prompts = /* @__PURE__ */ new Map();
|
|
17
|
+
const turns = /* @__PURE__ */ new Map();
|
|
18
|
+
const order = [];
|
|
19
|
+
for (const envelope of log) {
|
|
20
|
+
if (envelope.sessionId !== root || envelope.cursor === void 0) continue;
|
|
21
|
+
const { event } = envelope;
|
|
22
|
+
const cursor = envelope.cursor;
|
|
23
|
+
if (event.type === "item" && event.item.kind === "user_message" && event.item.clientMessageId && !prompts.has(event.item.clientMessageId)) prompts.set(event.item.clientMessageId, cursor);
|
|
24
|
+
else if (event.type === "prompt.accepted" && event.result === "turn" || event.type === "turn.started") {
|
|
25
|
+
if (turns.has(event.turnId)) continue;
|
|
26
|
+
const start = event.type === "prompt.accepted" ? Math.min(prompts.get(event.clientMessageId) ?? cursor, cursor) : cursor;
|
|
27
|
+
const turn = { id: event.turnId, start };
|
|
28
|
+
turns.set(turn.id, turn);
|
|
29
|
+
order.push(turn);
|
|
30
|
+
} else if (event.type === "turn.ended") {
|
|
31
|
+
const turn = turns.get(event.turnId);
|
|
32
|
+
if (turn && turn.state === void 0) Object.assign(turn, { state: event.state, end: cursor });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return order;
|
|
36
|
+
}
|
|
37
|
+
var busy = (rootId, why) => new RpcError(ERROR.conflict, `Session ${rootId} is busy: ${why}; try again when it is idle`, { reason: "session_busy" });
|
|
38
|
+
function refusal(error) {
|
|
39
|
+
if (error instanceof RpcError) return error;
|
|
40
|
+
const reason = error?.data?.reason;
|
|
41
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
42
|
+
if (error?.outcomeUnknown === true) return Object.assign(new RpcError(ERROR.conflict, message, { reason: "outcome_unknown" }), { outcomeUnknown: true });
|
|
43
|
+
if (reason === "session_busy") return new RpcError(ERROR.conflict, message, { reason });
|
|
44
|
+
if (reason === "runtime_unsupported" || reason === "boundary_unmapped" || reason === "empty_prefix" || reason === "native_refused") return new RpcError(ERROR.unavailable, message, { reason });
|
|
45
|
+
return new RpcError(ERROR.unavailable, `The runtime refused it: ${message}`, { reason: "native_refused" });
|
|
46
|
+
}
|
|
47
|
+
function configureRefusal(error) {
|
|
48
|
+
if (error instanceof RpcError) return error;
|
|
49
|
+
const reason = error?.data?.reason;
|
|
50
|
+
const message = error instanceof Error ? error.message : String(error?.message ?? error);
|
|
51
|
+
if (error?.outcomeUnknown === true) return refusal(error);
|
|
52
|
+
if (reason === "runtime_mismatch" || reason === "agent_mismatch") return new RpcError(ERROR.unavailable, message, { reason, action: "session.create" });
|
|
53
|
+
if (reason === "permission_escalation") return new RpcError(ERROR.forbidden, message, { reason });
|
|
54
|
+
if (reason === "team_not_found") return new RpcError(ERROR.notFound, message, { reason });
|
|
55
|
+
if (reason === "invalid_params" || reason === "not_root") return new RpcError(RPC_ERROR.invalidParams, message, { reason: "invalid_params" });
|
|
56
|
+
if (reason === "session_busy" && /not open/.test(message)) return new RpcError(ERROR.unavailable, "The session is not open; open it (session.create { resume: true }), then change its configuration", { reason: "session_closed" });
|
|
57
|
+
return refusal(error);
|
|
58
|
+
}
|
|
59
|
+
function createConversation(ctx) {
|
|
60
|
+
const { runtime, store, journal, records } = ctx;
|
|
61
|
+
const lifecycle = createLifecycle(journal, { crashPoint: ctx.crashPoint, completed });
|
|
62
|
+
const reservedForkIds = /* @__PURE__ */ new Set();
|
|
63
|
+
async function completed(entry) {
|
|
64
|
+
if (entry.state !== "applied") return void 0;
|
|
65
|
+
const saved = (await store.get(entry.resource))?.lifecycleCommits?.[entry.key];
|
|
66
|
+
return saved?.createdAt === entry.createdAt && saved.fingerprint === entry.fingerprint && saved.attemptId === entry.attemptId ? { result: saved.result } : void 0;
|
|
67
|
+
}
|
|
68
|
+
async function commitRecord(record, entry, result) {
|
|
69
|
+
const previous = record.lifecycleCommits;
|
|
70
|
+
const receipts = { ...previous };
|
|
71
|
+
for (const [key, receipt] of Object.entries(receipts)) {
|
|
72
|
+
try {
|
|
73
|
+
const saved = await journal.get(record.id, receipt.operation, receipt.requestId);
|
|
74
|
+
if (!saved || saved.createdAt !== receipt.createdAt || saved.fingerprint !== receipt.fingerprint || saved.attemptId !== receipt.attemptId || saved.state === "committed") delete receipts[key];
|
|
75
|
+
} catch {
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
receipts[entry.key] = { operation: entry.operation, requestId: entry.requestId, createdAt: entry.createdAt, fingerprint: entry.fingerprint, attemptId: entry.attemptId, result };
|
|
79
|
+
record.lifecycleCommits = receipts;
|
|
80
|
+
await store.put(record);
|
|
81
|
+
}
|
|
82
|
+
const enabled = typeof runtime.branch === "function" && typeof runtime.rebind === "function" && process.platform !== "win32";
|
|
83
|
+
const reloads = typeof runtime.reload === "function" && process.platform !== "win32";
|
|
84
|
+
const configures = typeof runtime.reconfigure === "function" && typeof runtime.previewConfigure === "function" && process.platform !== "win32";
|
|
85
|
+
function support(record, session) {
|
|
86
|
+
const no = { fork: false, rewind: false, ...reloads ? { reload: false } : {}, ...configures ? { configure: false } : {} };
|
|
87
|
+
if (record.rootId !== record.id || session?.parentId) return { ...no, reason: "not_root" };
|
|
88
|
+
if (!session || !SUPPORTED.has(session.runtime) || !enabled && !reloads && !configures) return { ...no, reason: "runtime_unsupported" };
|
|
89
|
+
if (!session.persistent || !session.threadId || !record.spec) return { ...no, reason: "not_persistent" };
|
|
90
|
+
return { fork: enabled, rewind: enabled, ...reloads ? { reload: true } : {}, ...configures ? { configure: true } : {}, ...enabled ? {} : { reason: "runtime_unsupported" } };
|
|
91
|
+
}
|
|
92
|
+
function rootOf(sessionId) {
|
|
93
|
+
const record = records.get(sessionId);
|
|
94
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: "not_found" });
|
|
95
|
+
const live = runtime.snapshot(sessionId);
|
|
96
|
+
const allowed = support(record, live ?? record.session);
|
|
97
|
+
if (allowed?.reason === "not_root") throw new RpcError(RPC_ERROR.invalidParams, "Only a root session's conversation can be forked or rewound", { reason: "invalid_params" });
|
|
98
|
+
if (allowed?.reason === "runtime_unsupported") throw new RpcError(ERROR.unavailable, `alpd cannot fork or rewind a ${(live ?? record.session)?.runtime ?? "session"} conversation`, { reason: "runtime_unsupported" });
|
|
99
|
+
if (allowed?.reason === "not_persistent") throw new RpcError(ERROR.unavailable, "This session keeps no native conversation to fork or rewind", { reason: "runtime_unsupported" });
|
|
100
|
+
return record;
|
|
101
|
+
}
|
|
102
|
+
function bindingOf(record) {
|
|
103
|
+
const threadId = runtime.snapshot(record.id)?.threadId || record.session.threadId;
|
|
104
|
+
return { threadId, ...record.base ? { base: record.base } : {} };
|
|
105
|
+
}
|
|
106
|
+
async function generationOf(root) {
|
|
107
|
+
return (await store.history(root, root, { limit: 1 })).generation;
|
|
108
|
+
}
|
|
109
|
+
async function checkGeneration(root, expected) {
|
|
110
|
+
if (await generationOf(root) !== expected) throw new RpcError(ERROR.conflict, "The conversation changed since this view (history generation); refresh and try again", { reason: "stale_generation" });
|
|
111
|
+
}
|
|
112
|
+
const turnNotFound = (turnId) => new RpcError(ERROR.notFound, `No turn ${turnId} in this conversation`, { reason: "turn_not_found" });
|
|
113
|
+
const inProgress = (turnId) => new RpcError(ERROR.conflict, turnId ? `Turn ${turnId} has not ended` : "A turn of this conversation has not ended", { reason: "turn_in_progress" });
|
|
114
|
+
const begun = (sessionId) => !!runtime.snapshot(sessionId)?.activeTurnId || !!runtime.starting?.(sessionId);
|
|
115
|
+
const emptyPrefix = () => new RpcError(ERROR.unavailable, "Nothing comes before the first turn; start a new session instead", { reason: "empty_prefix" });
|
|
116
|
+
async function timelineOf(root, branch) {
|
|
117
|
+
return branch ? store.branchTimeline(root, branch.branchId) : store.timeline(root);
|
|
118
|
+
}
|
|
119
|
+
const fences = /* @__PURE__ */ new Map();
|
|
120
|
+
async function rewind(params) {
|
|
121
|
+
const { sessionId, requestId, ifGeneration, beforeTurnId } = params;
|
|
122
|
+
const fingerprint = ctx.digest({ beforeTurnId });
|
|
123
|
+
const release = ctx.holdPrompts(sessionId);
|
|
124
|
+
let releaseWakes;
|
|
125
|
+
try {
|
|
126
|
+
const { result, duplicate, entry } = await lifecycle.run(
|
|
127
|
+
{ resource: sessionId, operation: "rewind", requestId, fingerprint },
|
|
128
|
+
{
|
|
129
|
+
async prepare() {
|
|
130
|
+
const record = rootOf(sessionId);
|
|
131
|
+
const unsettled = ctx.unsettled(sessionId);
|
|
132
|
+
if (unsettled) throw busy(sessionId, unsettled);
|
|
133
|
+
const live = runtime.snapshot(sessionId);
|
|
134
|
+
if (live?.busy) throw busy(sessionId, "a turn, child, assignment, mail or parked work is in progress");
|
|
135
|
+
if (runtime.questions().some((question) => question.rootId === sessionId)) throw busy(sessionId, "a question waits for an answer");
|
|
136
|
+
releaseWakes = runtime.hold?.(sessionId);
|
|
137
|
+
await checkGeneration(sessionId, ifGeneration);
|
|
138
|
+
const turns = turnsOf(await store.timeline(sessionId), sessionId);
|
|
139
|
+
const index = turns.findIndex((turn) => turn.id === beforeTurnId);
|
|
140
|
+
if (index < 0) throw turnNotFound(beforeTurnId);
|
|
141
|
+
if (index === 0) throw emptyPrefix();
|
|
142
|
+
const running = turns.find((turn) => turn.state === void 0);
|
|
143
|
+
if (running) throw inProgress(running.id);
|
|
144
|
+
if (begun(sessionId) || runtime.questions().some((question) => question.rootId === sessionId)) throw busy(sessionId, "a turn or question began meanwhile");
|
|
145
|
+
return {
|
|
146
|
+
root: sessionId,
|
|
147
|
+
beforeTurnId,
|
|
148
|
+
cut: turns[index].start,
|
|
149
|
+
branchId: `br_${randomBytes(8).toString("hex")}`,
|
|
150
|
+
turns: turns.length - index,
|
|
151
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
152
|
+
previous: bindingOf(record),
|
|
153
|
+
cwd: record.spec.cwd,
|
|
154
|
+
turnIds: turns.map((turn) => turn.id)
|
|
155
|
+
};
|
|
156
|
+
},
|
|
157
|
+
async apply(plan) {
|
|
158
|
+
const record = records.get(plan.root);
|
|
159
|
+
const session = runtime.snapshot(plan.root) ?? record.session;
|
|
160
|
+
try {
|
|
161
|
+
return await runtime.branch({ runtime: session.runtime, source: plan.previous, cwd: plan.cwd, model: session.model, thinking: session.thinking, mode: session.mode, cutoff: { beforeTurnId: plan.beforeTurnId }, turns: plan.turnIds });
|
|
162
|
+
} catch (error) {
|
|
163
|
+
throw refusal(error);
|
|
164
|
+
}
|
|
165
|
+
},
|
|
166
|
+
commit: commitRewind,
|
|
167
|
+
repeat: (entry2) => ({ ...entry2.result, session: ctx.summary(entry2.plan.root) ?? entry2.result.session })
|
|
168
|
+
}
|
|
169
|
+
);
|
|
170
|
+
if (fences.get(sessionId) === requestId) fences.delete(sessionId);
|
|
171
|
+
if (!duplicate) await afterRewind(entry);
|
|
172
|
+
return { ...result, session: ctx.summary(sessionId) ?? result.session, ...duplicate ? { duplicate: true } : {} };
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if ((await journal.get(sessionId, "rewind", requestId).catch(() => void 0))?.state === "applied") await fence(sessionId, requestId);
|
|
175
|
+
throw error;
|
|
176
|
+
} finally {
|
|
177
|
+
releaseWakes?.();
|
|
178
|
+
release();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
async function fence(root, requestId) {
|
|
182
|
+
fences.set(root, requestId);
|
|
183
|
+
ctx.log.warn(`the rewind ${requestId} of ${root} is applied but not committed; the session waits for it to be sent again`, { code: "ALPD_REWIND_FENCED", sessionId: root });
|
|
184
|
+
if (runtime.snapshot(root)) await runtime.close(root).catch(() => {
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
async function commitRewind(entry) {
|
|
188
|
+
const plan = entry.plan;
|
|
189
|
+
const native = entry.native;
|
|
190
|
+
const record = records.get(plan.root);
|
|
191
|
+
if (!record?.session) throw new Error(`session ${plan.root} is gone`);
|
|
192
|
+
if (plan.marker === void 0) {
|
|
193
|
+
const stored = await store.timeline(plan.root);
|
|
194
|
+
plan.marker = Math.max(ctx.cursors.get(plan.root) ?? 0, stored.at(-1)?.cursor ?? 0) + 1;
|
|
195
|
+
ctx.cursors.set(plan.root, plan.marker);
|
|
196
|
+
await journal.put(entry);
|
|
197
|
+
} else if ((ctx.cursors.get(plan.root) ?? 0) < plan.marker) ctx.cursors.set(plan.root, plan.marker);
|
|
198
|
+
ctx.crashPoint("rewind.before-timeline");
|
|
199
|
+
await store.rewind(plan.root, { cut: plan.cut, branchId: plan.branchId, marker: rewindMarker(plan) });
|
|
200
|
+
ctx.crashPoint("rewind.after-timeline");
|
|
201
|
+
const branch = { branchId: plan.branchId, beforeTurnId: plan.beforeTurnId, turns: plan.turns, at: plan.at, threadId: plan.previous.threadId, ...plan.previous.base ? { base: plan.previous.base } : {}, cut: plan.cut, marker: plan.marker };
|
|
202
|
+
if (!(record.branches ?? []).some((candidate) => candidate.branchId === plan.branchId)) record.branches = [...record.branches ?? [], branch];
|
|
203
|
+
record.session = { ...record.session, threadId: native.threadId };
|
|
204
|
+
if (native.base) record.base = native.base;
|
|
205
|
+
else delete record.base;
|
|
206
|
+
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
207
|
+
const result = { session: ctx.summary(plan.root), generation: await generationOf(plan.root), branch: publicBranch(branch) };
|
|
208
|
+
await commitRecord(record, entry, result);
|
|
209
|
+
if (ctx.logs.has(plan.root)) ctx.logs.set(plan.root, (await store.timeline(plan.root)).slice(-ctx.treeLogLimit));
|
|
210
|
+
return result;
|
|
211
|
+
}
|
|
212
|
+
function rewindMarker(plan) {
|
|
213
|
+
return {
|
|
214
|
+
sessionId: plan.root,
|
|
215
|
+
epoch: `rewind-${plan.branchId}`,
|
|
216
|
+
seq: 0,
|
|
217
|
+
ts: plan.at,
|
|
218
|
+
cursor: plan.marker,
|
|
219
|
+
event: { type: "item", item: { kind: "notice", id: `rewind:${plan.branchId}`, level: "info", text: `Conversation rewound to before a message: ${plan.turns} later turn${plan.turns === 1 ? "" : "s"} moved to a recoverable branch. Files were not changed.` } }
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
async function afterRewind(entry) {
|
|
223
|
+
const plan = entry.plan;
|
|
224
|
+
const generation = entry.result?.generation;
|
|
225
|
+
if (generation) ctx.broadcast(plan.root, { sessionId: plan.root, epoch: `rewind-${plan.branchId}`, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event: { type: "history.reset", generation, reason: "rewind", branchId: plan.branchId } });
|
|
226
|
+
ctx.broadcast(plan.root, rewindMarker(plan));
|
|
227
|
+
if (!runtime.snapshot(plan.root)) return;
|
|
228
|
+
try {
|
|
229
|
+
await runtime.rebind(plan.root, entry.native);
|
|
230
|
+
} catch (error) {
|
|
231
|
+
ctx.log.warn(`could not move ${plan.root} to its rewound conversation; closing it`, { code: "ALPD_REWIND_REBIND_FAILED", sessionId: plan.root, error });
|
|
232
|
+
await runtime.close(plan.root).catch(() => {
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
async function reload(params) {
|
|
237
|
+
const { sessionId, requestId, ifGeneration } = params;
|
|
238
|
+
const fingerprint = ctx.digest({ reload: sessionId });
|
|
239
|
+
const release = ctx.holdPrompts(sessionId);
|
|
240
|
+
let releaseWakes;
|
|
241
|
+
try {
|
|
242
|
+
const { result, duplicate } = await lifecycle.run(
|
|
243
|
+
{ resource: sessionId, operation: "reload", requestId, fingerprint },
|
|
244
|
+
{
|
|
245
|
+
async prepare() {
|
|
246
|
+
const record = records.get(sessionId);
|
|
247
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: "not_found" });
|
|
248
|
+
const live = runtime.snapshot(sessionId);
|
|
249
|
+
const allowed = support(record, live ?? record.session);
|
|
250
|
+
if (allowed?.reason === "not_root") throw new RpcError(RPC_ERROR.invalidParams, "Only a root session can be reloaded; an assignment restarts with its requester", { reason: "invalid_params" });
|
|
251
|
+
if (!allowed?.reload) throw new RpcError(ERROR.unavailable, allowed?.reason === "not_persistent" ? "This session keeps no native conversation to reload" : `alpd cannot reload a ${(live ?? record.session)?.runtime ?? "session"} session`, { reason: "runtime_unsupported" });
|
|
252
|
+
const unsettled = ctx.unsettled(sessionId);
|
|
253
|
+
if (unsettled) throw busy(sessionId, unsettled);
|
|
254
|
+
if (!live) throw new RpcError(ERROR.unavailable, "The session is not open; open it (session.create { resume: true }) and its agent starts on its conversation", { reason: "session_closed" });
|
|
255
|
+
if (live.busy) throw busy(sessionId, "a turn, child, assignment, mail or parked work is in progress");
|
|
256
|
+
if (runtime.questions().some((question) => question.rootId === sessionId)) throw busy(sessionId, "a question waits for an answer");
|
|
257
|
+
releaseWakes = runtime.hold?.(sessionId);
|
|
258
|
+
await checkGeneration(sessionId, ifGeneration);
|
|
259
|
+
const turns = turnsOf(await store.timeline(sessionId), sessionId);
|
|
260
|
+
if (!turns.length) throw new RpcError(ERROR.unavailable, "The agent has no conversation to keep yet; send it a message first, or start a new session", { reason: "no_history" });
|
|
261
|
+
const running = turns.find((turn) => turn.state === void 0);
|
|
262
|
+
if (running) throw inProgress(running.id);
|
|
263
|
+
const now = runtime.snapshot(sessionId);
|
|
264
|
+
if (!now) throw new RpcError(ERROR.unavailable, "The session closed; open it (session.create { resume: true }) and its agent starts on its conversation", { reason: "session_closed" });
|
|
265
|
+
if (begun(sessionId) || runtime.questions().some((question) => question.rootId === sessionId)) throw busy(sessionId, "a turn or question began meanwhile");
|
|
266
|
+
return { root: sessionId, threadId: live.threadId, at: (/* @__PURE__ */ new Date()).toISOString() };
|
|
267
|
+
},
|
|
268
|
+
async apply(plan) {
|
|
269
|
+
try {
|
|
270
|
+
const session = await runtime.reload(plan.root);
|
|
271
|
+
return { threadId: session.threadId };
|
|
272
|
+
} catch (error) {
|
|
273
|
+
throw refusal(error);
|
|
274
|
+
}
|
|
275
|
+
},
|
|
276
|
+
commit: commitReload,
|
|
277
|
+
repeat: (entry) => ({ session: ctx.summary(entry.plan.root) ?? entry.result.session })
|
|
278
|
+
}
|
|
279
|
+
);
|
|
280
|
+
return { ...result, session: ctx.summary(sessionId) ?? result.session, ...duplicate ? { duplicate: true } : {} };
|
|
281
|
+
} finally {
|
|
282
|
+
releaseWakes?.();
|
|
283
|
+
release();
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
async function commitReload(entry) {
|
|
287
|
+
const plan = entry.plan;
|
|
288
|
+
const record = records.get(plan.root);
|
|
289
|
+
if (!record?.session) throw new Error(`session ${plan.root} is gone`);
|
|
290
|
+
return { session: ctx.summary(plan.root) };
|
|
291
|
+
}
|
|
292
|
+
function resumeCommand(sessionId) {
|
|
293
|
+
if (!records.has(sessionId) && !runtime.snapshot(sessionId)) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: "not_found" });
|
|
294
|
+
return resumeCommandOf(sessionId, process.platform === "win32" ? "windows" : "posix");
|
|
295
|
+
}
|
|
296
|
+
async function configure(params) {
|
|
297
|
+
const { sessionId, requestId, ifGeneration } = params;
|
|
298
|
+
const requested = {};
|
|
299
|
+
for (const key of ["model", "thinking", "team", "mode"]) {
|
|
300
|
+
const value = params[key];
|
|
301
|
+
if (value === void 0) continue;
|
|
302
|
+
if (typeof value !== "string" || !value.trim() || value.length > 200) throw new RpcError(RPC_ERROR.invalidParams, `${key} must be a nonempty name of at most 200 characters`, { reason: "invalid_params" });
|
|
303
|
+
requested[key] = value.trim();
|
|
304
|
+
}
|
|
305
|
+
if (typeof requestId !== "string" || !requestId || typeof ifGeneration !== "string") throw new RpcError(RPC_ERROR.invalidParams, "A change of model, thinking or team needs requestId and ifGeneration", { reason: "invalid_params" });
|
|
306
|
+
const fingerprint = ctx.digest({ configure: sessionId, ...requested });
|
|
307
|
+
const release = ctx.holdPrompts(sessionId);
|
|
308
|
+
let releaseWakes;
|
|
309
|
+
try {
|
|
310
|
+
const { result, duplicate } = await lifecycle.run(
|
|
311
|
+
{ resource: sessionId, operation: "configure", requestId, fingerprint },
|
|
312
|
+
{
|
|
313
|
+
async prepare() {
|
|
314
|
+
const record = records.get(sessionId);
|
|
315
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: "not_found" });
|
|
316
|
+
const live = runtime.snapshot(sessionId);
|
|
317
|
+
const allowed = support(record, live ?? record.session);
|
|
318
|
+
if (allowed?.reason === "not_root") throw new RpcError(RPC_ERROR.invalidParams, "Only a root session is reconfigured; an assignment keeps the team and model it started with", { reason: "invalid_params" });
|
|
319
|
+
if (!allowed?.configure) throw new RpcError(ERROR.unavailable, allowed?.reason === "not_persistent" ? "This session keeps no native conversation to continue with a new configuration" : `alpd cannot change a running ${(live ?? record.session)?.runtime ?? ""} session's model or team; start a new session`.replace("running session", "running session"), { reason: "runtime_unsupported" });
|
|
320
|
+
const unsettled = ctx.unsettled(sessionId);
|
|
321
|
+
if (unsettled) throw busy(sessionId, unsettled);
|
|
322
|
+
if (!live) throw new RpcError(ERROR.unavailable, "The session is not open; open it (session.create { resume: true }), then change its configuration", { reason: "session_closed" });
|
|
323
|
+
if (live.busy) throw busy(sessionId, "a turn, child, assignment, mail or parked work is in progress");
|
|
324
|
+
if (runtime.questions().some((question) => question.rootId === sessionId)) throw busy(sessionId, "a question waits for an answer");
|
|
325
|
+
releaseWakes = runtime.hold?.(sessionId);
|
|
326
|
+
await checkGeneration(sessionId, ifGeneration);
|
|
327
|
+
const turns = turnsOf(await store.timeline(sessionId), sessionId);
|
|
328
|
+
const running = turns.find((turn) => turn.state === void 0);
|
|
329
|
+
if (running) throw inProgress(running.id);
|
|
330
|
+
const preview = await runtime.previewConfigure(sessionId, requested).catch((error) => {
|
|
331
|
+
throw configureRefusal(error);
|
|
332
|
+
});
|
|
333
|
+
if (!preview.allowed) throw configureRefusal({ data: { reason: preview.reason }, message: preview.message ?? "The change was refused" });
|
|
334
|
+
const now = runtime.snapshot(sessionId);
|
|
335
|
+
if (!now) throw new RpcError(ERROR.unavailable, "The session closed; open it (session.create { resume: true }), then change its configuration", { reason: "session_closed" });
|
|
336
|
+
if (begun(sessionId) || runtime.questions().some((question) => question.rootId === sessionId)) throw busy(sessionId, "a turn or question began meanwhile");
|
|
337
|
+
return { root: sessionId, requested, fresh: !turns.length && !record.base, previous: preview.current, proposed: preview.proposed, at: (/* @__PURE__ */ new Date()).toISOString() };
|
|
338
|
+
},
|
|
339
|
+
async apply(plan) {
|
|
340
|
+
try {
|
|
341
|
+
const done = await runtime.reconfigure(plan.root, plan.requested, { fresh: plan.fresh, onApplied: async (done2) => {
|
|
342
|
+
const record = records.get(plan.root);
|
|
343
|
+
if (!record?.spec || !record.session) throw new Error(`session ${plan.root} is gone`);
|
|
344
|
+
writeConfiguration(record, done2.effective, done2.session);
|
|
345
|
+
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
346
|
+
await store.put(record);
|
|
347
|
+
} });
|
|
348
|
+
return { status: done.status, restarted: done.restarted, effective: done.effective, threadId: done.session.threadId, workflow: done.session.workflow, ...done.session.teamLabel ? { teamLabel: done.session.teamLabel } : {}, ...done.native ? { native: done.native } : {} };
|
|
349
|
+
} catch (error) {
|
|
350
|
+
throw configureRefusal(error);
|
|
351
|
+
}
|
|
352
|
+
},
|
|
353
|
+
commit: commitConfigure,
|
|
354
|
+
repeat: (entry) => ({ session: ctx.summary(entry.plan.root) ?? entry.result.session, configured: entry.result.configured })
|
|
355
|
+
}
|
|
356
|
+
);
|
|
357
|
+
return { ...result, session: ctx.summary(sessionId) ?? result.session, ...duplicate ? { duplicate: true } : {} };
|
|
358
|
+
} finally {
|
|
359
|
+
releaseWakes?.();
|
|
360
|
+
release();
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
async function commitConfigure(entry) {
|
|
364
|
+
const plan = entry.plan;
|
|
365
|
+
const native = entry.native;
|
|
366
|
+
const record = records.get(plan.root);
|
|
367
|
+
if (!record?.session || !record.spec) throw new Error(`session ${plan.root} is gone`);
|
|
368
|
+
if (native.status === "applied") writeConfiguration(record, native.effective, { threadId: native.threadId, workflow: native.workflow, teamLabel: native.teamLabel });
|
|
369
|
+
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
370
|
+
const result = { session: ctx.summary(plan.root), configured: { status: native.status, requested: plan.requested, effective: native.effective, restarted: native.restarted } };
|
|
371
|
+
await commitRecord(record, entry, result);
|
|
372
|
+
return result;
|
|
373
|
+
}
|
|
374
|
+
function writeConfiguration(record, effective, session) {
|
|
375
|
+
const { thinking: _thinking, ...spec } = record.spec;
|
|
376
|
+
record.spec = { ...spec, thinking: effective.thinking, mode: effective.mode, ...effective.team !== "custom" ? { workflow: effective.team } : {} };
|
|
377
|
+
const teamLabel = session.teamLabel ?? effective.teamLabel;
|
|
378
|
+
const { teamLabel: _label, ...snapshot } = record.session;
|
|
379
|
+
record.session = {
|
|
380
|
+
...snapshot,
|
|
381
|
+
model: effective.model,
|
|
382
|
+
thinking: effective.thinking,
|
|
383
|
+
mode: effective.mode,
|
|
384
|
+
workflow: session.workflow ?? { mode: effective.team, maxPeers: effective.maxPeers ?? record.session.workflow.maxPeers, supervisor: effective.supervisor },
|
|
385
|
+
...teamLabel ? { teamLabel } : {},
|
|
386
|
+
...session.threadId ? { threadId: session.threadId } : {}
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
async function configurePreview(params) {
|
|
390
|
+
const { sessionId } = params;
|
|
391
|
+
const requested = {};
|
|
392
|
+
for (const key of ["model", "thinking", "team", "mode"]) {
|
|
393
|
+
const value = params[key];
|
|
394
|
+
if (value === void 0) continue;
|
|
395
|
+
if (typeof value !== "string" || !value.trim() || value.length > 200) throw new RpcError(RPC_ERROR.invalidParams, `${key} must be a nonempty name of at most 200 characters`, { reason: "invalid_params" });
|
|
396
|
+
requested[key] = value.trim();
|
|
397
|
+
}
|
|
398
|
+
const record = records.get(sessionId);
|
|
399
|
+
if (!record && !runtime.snapshot(sessionId)) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: "not_found" });
|
|
400
|
+
const live = runtime.snapshot(sessionId);
|
|
401
|
+
if (!live) throw new RpcError(ERROR.unavailable, "The session is not open; open it to see what it would run with", { reason: "session_closed" });
|
|
402
|
+
const preview = await runtime.previewConfigure(sessionId, requested).catch((error) => {
|
|
403
|
+
throw configureRefusal(error);
|
|
404
|
+
});
|
|
405
|
+
const allowed = record ? support(record, live) : void 0;
|
|
406
|
+
if (preview.allowed && !allowed?.configure) return { ...preview, allowed: false, reason: allowed?.reason === "not_root" ? "not_root" : allowed?.reason === "not_persistent" ? "not_persistent" : "runtime_unsupported" };
|
|
407
|
+
const unsettled = preview.allowed && preview.changes.length ? ctx.unsettled(sessionId) : void 0;
|
|
408
|
+
return unsettled ? { ...preview, allowed: false, reason: "session_busy", message: `Session ${sessionId} is busy: ${unsettled}` } : preview;
|
|
409
|
+
}
|
|
410
|
+
async function fork(params) {
|
|
411
|
+
const { sessionId, requestId, ifGeneration, boundary, branchId, workspaceId, newSessionId, title, principal } = params;
|
|
412
|
+
const fingerprint = ctx.digest({ boundary: boundary ?? null, branchId: branchId ?? null, workspaceId: workspaceId ?? null, newSessionId: newSessionId ?? null, title: title ?? null });
|
|
413
|
+
let release;
|
|
414
|
+
let releaseWakes;
|
|
415
|
+
let reservedId;
|
|
416
|
+
try {
|
|
417
|
+
const { result, duplicate } = await lifecycle.run(
|
|
418
|
+
{ resource: sessionId, operation: "fork", requestId, fingerprint },
|
|
419
|
+
{
|
|
420
|
+
async prepare() {
|
|
421
|
+
const record = rootOf(sessionId);
|
|
422
|
+
await checkGeneration(sessionId, ifGeneration);
|
|
423
|
+
const branch = branchId === void 0 ? void 0 : record.branches?.find((candidate) => candidate.branchId === branchId);
|
|
424
|
+
if (branchId !== void 0 && !branch) throw new RpcError(ERROR.notFound, `No branch ${branchId} of this session`, { reason: "branch_not_found" });
|
|
425
|
+
const log = await timelineOf(sessionId, branch);
|
|
426
|
+
const turns = turnsOf(log, sessionId);
|
|
427
|
+
const last = log.at(-1)?.cursor ?? 0;
|
|
428
|
+
let cut;
|
|
429
|
+
let kind = "whole";
|
|
430
|
+
let turnId;
|
|
431
|
+
if (boundary && "throughTurnId" in boundary) {
|
|
432
|
+
const index = turns.findIndex((turn) => turn.id === boundary.throughTurnId);
|
|
433
|
+
if (index < 0) throw turnNotFound(boundary.throughTurnId);
|
|
434
|
+
if (turns.slice(0, index + 1).some((turn) => turn.state === void 0)) throw inProgress(boundary.throughTurnId);
|
|
435
|
+
cut = turns[index + 1]?.start ?? last + 1;
|
|
436
|
+
kind = "through";
|
|
437
|
+
turnId = boundary.throughTurnId;
|
|
438
|
+
} else if (boundary && "beforeTurnId" in boundary) {
|
|
439
|
+
const index = turns.findIndex((turn) => turn.id === boundary.beforeTurnId);
|
|
440
|
+
if (index < 0) throw turnNotFound(boundary.beforeTurnId);
|
|
441
|
+
if (index === 0) throw emptyPrefix();
|
|
442
|
+
if (turns.slice(0, index).some((turn) => turn.state === void 0)) throw inProgress();
|
|
443
|
+
cut = turns[index].start;
|
|
444
|
+
kind = "before";
|
|
445
|
+
turnId = boundary.beforeTurnId;
|
|
446
|
+
} else {
|
|
447
|
+
if (!turns.length) throw emptyPrefix();
|
|
448
|
+
const running = turns.find((turn) => turn.state === void 0);
|
|
449
|
+
if (running) throw inProgress(running.id);
|
|
450
|
+
cut = last + 1;
|
|
451
|
+
}
|
|
452
|
+
const latest = !branch && cut > (turns.at(-1)?.start ?? 0);
|
|
453
|
+
if (latest) {
|
|
454
|
+
release = ctx.holdPrompts(sessionId);
|
|
455
|
+
const unsettled = ctx.unsettled(sessionId);
|
|
456
|
+
if (unsettled) throw busy(sessionId, unsettled);
|
|
457
|
+
if (begun(sessionId)) throw inProgress();
|
|
458
|
+
releaseWakes = runtime.hold?.(sessionId);
|
|
459
|
+
const now = turnsOf(await timelineOf(sessionId, branch), sessionId);
|
|
460
|
+
if (now.length !== turns.length || now.some((turn, index) => turn.id !== turns[index].id)) throw busy(sessionId, "its conversation changed while the fork was prepared");
|
|
461
|
+
}
|
|
462
|
+
const latestTurn = turns.at(-1)?.id;
|
|
463
|
+
const cutoff = kind === "through" ? { throughTurnId: turnId } : kind === "before" ? { beforeTurnId: turnId } : latestTurn ? { throughTurnId: latestTurn } : void 0;
|
|
464
|
+
const pendingIds = new Set((await journal.list()).filter((entry) => entry.operation === "fork" && ["prepared", "applied", "unknown"].includes(entry.state)).map((entry) => entry.plan.newSessionId));
|
|
465
|
+
let id = newSessionId;
|
|
466
|
+
if (id !== void 0) {
|
|
467
|
+
if (records.has(id) || runtime.snapshot(id) || reservedForkIds.has(id) || pendingIds.has(id)) throw new RpcError(ERROR.conflict, `Session ${id} already exists`, { reason: "request_conflict" });
|
|
468
|
+
} else {
|
|
469
|
+
do {
|
|
470
|
+
id = `ses_${randomBytes(8).toString("hex")}`;
|
|
471
|
+
} while (records.has(id) || runtime.snapshot(id) || reservedForkIds.has(id) || pendingIds.has(id));
|
|
472
|
+
}
|
|
473
|
+
reservedForkIds.add(id);
|
|
474
|
+
reservedId = id;
|
|
475
|
+
const cwd = await destinationOf(record, workspaceId);
|
|
476
|
+
const attachmentIds = await reauthorize(sessionId, log, cut, principal);
|
|
477
|
+
if (latest && begun(sessionId)) throw busy(sessionId, "a turn began meanwhile");
|
|
478
|
+
return {
|
|
479
|
+
recoveryVersion: 1,
|
|
480
|
+
source: sessionId,
|
|
481
|
+
newSessionId: id,
|
|
482
|
+
...branchId ? { branchId } : {},
|
|
483
|
+
cut,
|
|
484
|
+
boundary: kind,
|
|
485
|
+
...turnId ? { turnId } : {},
|
|
486
|
+
cwd,
|
|
487
|
+
...workspaceId ? { workspaceId } : {},
|
|
488
|
+
title: title ?? defaultForkTitle(record.title, cwd === record.spec.cwd),
|
|
489
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
490
|
+
attachmentIds,
|
|
491
|
+
turnIds: turns.map((turn) => turn.id),
|
|
492
|
+
...cutoff ? { cutoff } : {}
|
|
493
|
+
};
|
|
494
|
+
},
|
|
495
|
+
async apply(plan) {
|
|
496
|
+
const record = records.get(plan.source);
|
|
497
|
+
const session = runtime.snapshot(plan.source) ?? record.session;
|
|
498
|
+
const branch = plan.branchId ? record.branches?.find((candidate) => candidate.branchId === plan.branchId) : void 0;
|
|
499
|
+
const source = branch ? { threadId: branch.threadId, ...branch.base ? { base: branch.base } : {} } : bindingOf(record);
|
|
500
|
+
try {
|
|
501
|
+
return await runtime.branch({ runtime: session.runtime, source, cwd: record.spec.cwd, ...plan.cwd !== record.spec.cwd ? { targetCwd: plan.cwd } : {}, model: session.model, thinking: session.thinking, mode: session.mode, ...plan.cutoff ? { cutoff: plan.cutoff } : {}, turns: plan.turnIds });
|
|
502
|
+
} catch (error) {
|
|
503
|
+
throw refusal(error);
|
|
504
|
+
}
|
|
505
|
+
},
|
|
506
|
+
commit: commitFork,
|
|
507
|
+
repeat: (entry) => ({ ...entry.result, session: ctx.summary(entry.plan.newSessionId) ?? entry.result.session })
|
|
508
|
+
}
|
|
509
|
+
);
|
|
510
|
+
return { ...result, ...duplicate ? { duplicate: true } : {} };
|
|
511
|
+
} finally {
|
|
512
|
+
if (reservedId && !records.has(reservedId)) {
|
|
513
|
+
const entry = await journal.get(sessionId, "fork", requestId).catch(() => ({ state: "unknown" }));
|
|
514
|
+
if (!entry || entry.state === "failed") reservedForkIds.delete(reservedId);
|
|
515
|
+
}
|
|
516
|
+
releaseWakes?.();
|
|
517
|
+
release?.();
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
async function destinationOf(record, workspaceId) {
|
|
521
|
+
if (workspaceId === void 0) return record.spec.cwd;
|
|
522
|
+
const registry = ctx.registry;
|
|
523
|
+
if (!registry) throw new RpcError(RPC_ERROR.invalidParams, "This alpd keeps no workspace registry", { reason: "invalid_params" });
|
|
524
|
+
try {
|
|
525
|
+
const cwd = await registry.resolve(workspaceId);
|
|
526
|
+
const snapshot = await registry.snapshot();
|
|
527
|
+
const target = snapshot.workspaces.find((candidate) => candidate.id === workspaceId);
|
|
528
|
+
const placed = snapshot.sessions[record.id];
|
|
529
|
+
const from = placed ? snapshot.workspaces.find((candidate) => candidate.id === placed) : void 0;
|
|
530
|
+
if (from && target && from.projectId !== target.projectId) throw new RpcError(ERROR.conflict, "A fork stays in the project of its source", { reason: "workspace_mismatch" });
|
|
531
|
+
await ctx.worktrees?.assertAvailable(cwd);
|
|
532
|
+
return cwd;
|
|
533
|
+
} catch (error) {
|
|
534
|
+
if (error instanceof RegistryError) throw new RpcError(error.code, error.message, error.data);
|
|
535
|
+
throw error;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
async function reauthorize(source, log, cut, principal) {
|
|
539
|
+
if (!ctx.attachments) return [];
|
|
540
|
+
const lineage = [];
|
|
541
|
+
for (let id = source; id && !lineage.includes(id) && lineage.length < 32; id = records.get(id)?.forkedFrom?.sessionId) lineage.push(id);
|
|
542
|
+
const holders = [];
|
|
543
|
+
const named = /* @__PURE__ */ new Set();
|
|
544
|
+
for (const { sessionId, cursor, event } of log) {
|
|
545
|
+
if (sessionId !== source || (cursor ?? 0) >= cut || event.type !== "item" || event.item.kind !== "user_message" || !event.item.clientMessageId) continue;
|
|
546
|
+
for (const id of lineage) holders.push(`prompt:${ctx.digest(["prompt", id, event.item.clientMessageId])}`);
|
|
547
|
+
for (const attachment of Array.isArray(event.item.attachments) ? event.item.attachments : []) if (typeof attachment?.attachmentId === "string") named.add(attachment.attachmentId);
|
|
548
|
+
}
|
|
549
|
+
const found = new Set(await ctx.attachments.heldBy(holders));
|
|
550
|
+
if (named.size) {
|
|
551
|
+
for (const id of await ctx.attachments.heldBy(lineage.map((id2) => `fork:${id2}`))) if (named.has(id)) found.add(id);
|
|
552
|
+
}
|
|
553
|
+
const ids = [...found];
|
|
554
|
+
if (!ids.length) return [];
|
|
555
|
+
try {
|
|
556
|
+
await ctx.attachments.authorize(principal, ids, lineage);
|
|
557
|
+
} catch {
|
|
558
|
+
throw new RpcError(ERROR.forbidden, "The conversation holds attachments this caller may not use", { reason: "attachment_forbidden" });
|
|
559
|
+
}
|
|
560
|
+
return ids;
|
|
561
|
+
}
|
|
562
|
+
async function commitFork(entry) {
|
|
563
|
+
const plan = entry.plan;
|
|
564
|
+
const native = entry.native;
|
|
565
|
+
const source = records.get(plan.source);
|
|
566
|
+
if (!source?.session || !source.spec) throw new Error(`session ${plan.source} is gone`);
|
|
567
|
+
const forkedFrom = { sessionId: plan.source, ...plan.turnId ? { turnId: plan.turnId } : {}, boundary: plan.boundary, ...plan.branchId ? { branchId: plan.branchId } : {}, at: plan.at };
|
|
568
|
+
const target = records.get(plan.newSessionId);
|
|
569
|
+
const owner = target?.forkAttempt;
|
|
570
|
+
if (target && (owner ? owner.key !== entry.key || owner.attemptId !== entry.attemptId || owner.createdAt !== entry.createdAt || owner.fingerprint !== entry.fingerprint : plan.recoveryVersion === 1 || target.rootId !== plan.newSessionId || target.forkedFrom?.sessionId !== plan.source || target.forkedFrom.at !== plan.at || target.forkedFrom.boundary !== plan.boundary || target.forkedFrom.turnId !== plan.turnId || target.forkedFrom.branchId !== plan.branchId)) {
|
|
571
|
+
throw new RpcError(ERROR.failed, "The fork target does not belong to this journal attempt", { reason: "persistence_failed" });
|
|
572
|
+
}
|
|
573
|
+
if (!target && plan.recoveryVersion !== 1) {
|
|
574
|
+
throw new RpcError(ERROR.failed, "The legacy fork target is gone; its completion cannot be established", { reason: "persistence_failed" });
|
|
575
|
+
}
|
|
576
|
+
if (!target) {
|
|
577
|
+
const branch = plan.branchId ? source.branches?.find((candidate) => candidate.branchId === plan.branchId) : void 0;
|
|
578
|
+
const kept = (await timelineOf(plan.source, branch)).filter((envelope) => envelope.sessionId === plan.source && (envelope.cursor ?? 0) < plan.cut && CONVERSATION.has(envelope.event.type));
|
|
579
|
+
const envelopes = kept.map((envelope, index) => ({ ...envelope, sessionId: plan.newSessionId, cursor: index + 1 }));
|
|
580
|
+
envelopes.push({
|
|
581
|
+
sessionId: plan.newSessionId,
|
|
582
|
+
epoch: `fork-${plan.newSessionId}`,
|
|
583
|
+
seq: 0,
|
|
584
|
+
ts: plan.at,
|
|
585
|
+
cursor: envelopes.length + 1,
|
|
586
|
+
// No source title or id here: a viewer granted the fork but not its source must not learn them.
|
|
587
|
+
event: { type: "item", item: { kind: "notice", id: `fork:${plan.newSessionId}`, level: "info", text: `Forked from another session${plan.boundary === "whole" ? "" : plan.boundary === "through" ? " through a turn" : " before a turn"}. Files were not copied or changed.` } }
|
|
588
|
+
});
|
|
589
|
+
ctx.crashPoint("fork.before-timeline");
|
|
590
|
+
await store.createTimeline(plan.newSessionId, envelopes);
|
|
591
|
+
const { activeTurnId: _active, parked: _parked, usage: _usage, toolCallId: _call, parentId: _parent, ...kept_ } = source.session;
|
|
592
|
+
const moved = plan.cwd !== source.spec.cwd;
|
|
593
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
594
|
+
const record = {
|
|
595
|
+
version: 1,
|
|
596
|
+
id: plan.newSessionId,
|
|
597
|
+
rootId: plan.newSessionId,
|
|
598
|
+
spec: { ...source.spec, cwd: plan.cwd },
|
|
599
|
+
...source.delegation !== void 0 ? { delegation: source.delegation } : {},
|
|
600
|
+
session: { ...kept_, id: plan.newSessionId, threadId: native.threadId, busy: false, ...moved ? { projectRoot: await realpath(plan.cwd).catch(() => path.resolve(plan.cwd)) } : {} },
|
|
601
|
+
status: "closed",
|
|
602
|
+
title: plan.title,
|
|
603
|
+
forkedFrom,
|
|
604
|
+
forkAttempt: { key: entry.key, attemptId: entry.attemptId, createdAt: entry.createdAt, fingerprint: entry.fingerprint },
|
|
605
|
+
...native.base ? { base: native.base } : {},
|
|
606
|
+
createdAt: now,
|
|
607
|
+
updatedAt: now
|
|
608
|
+
};
|
|
609
|
+
ctx.crashPoint("fork.before-record");
|
|
610
|
+
await store.put(record);
|
|
611
|
+
records.set(record.id, record);
|
|
612
|
+
}
|
|
613
|
+
reservedForkIds.delete(plan.newSessionId);
|
|
614
|
+
await place(plan, entry.key);
|
|
615
|
+
if (plan.attachmentIds.length) await ctx.attachments?.pin(`fork:${plan.newSessionId}`, plan.newSessionId, plan.attachmentIds, "fork");
|
|
616
|
+
const result = { session: ctx.summary(plan.newSessionId), forkedFrom };
|
|
617
|
+
await commitRecord(source, entry, result);
|
|
618
|
+
return result;
|
|
619
|
+
}
|
|
620
|
+
async function place(plan, key) {
|
|
621
|
+
const registry = ctx.registry;
|
|
622
|
+
if (!registry) return;
|
|
623
|
+
try {
|
|
624
|
+
const snapshot = await registry.snapshot();
|
|
625
|
+
if (Object.hasOwn(snapshot.sessions, plan.newSessionId)) return;
|
|
626
|
+
const workspaceId = plan.workspaceId ?? (Object.hasOwn(snapshot.sessions, plan.source) ? snapshot.sessions[plan.source] : void 0);
|
|
627
|
+
if (workspaceId) await registry.mutate("placement.assign", { sessionId: plan.newSessionId, workspaceId }, { requestId: `fork:${key}` });
|
|
628
|
+
else await registry.mutate("placement.prepare", { sessions: [{ id: plan.newSessionId, projectRoot: plan.cwd }] }, { requestId: `fork:${key}` });
|
|
629
|
+
} catch (error) {
|
|
630
|
+
if (error instanceof RegistryError) throw new RpcError(error.code, error.message, error.data);
|
|
631
|
+
throw error;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
function publicBranch({ branchId, beforeTurnId, turns, at }) {
|
|
635
|
+
return { branchId, beforeTurnId, turns, at };
|
|
636
|
+
}
|
|
637
|
+
return {
|
|
638
|
+
enabled,
|
|
639
|
+
reloads,
|
|
640
|
+
configures,
|
|
641
|
+
/** The fields session summaries carry for a record (§12.7, §12.8). */
|
|
642
|
+
fields(record, session) {
|
|
643
|
+
if (!enabled) return reloads || configures ? { conversation: support(record, session) } : {};
|
|
644
|
+
return {
|
|
645
|
+
conversation: support(record, session),
|
|
646
|
+
...record.forkedFrom ? { forkedFrom: record.forkedFrom } : {},
|
|
647
|
+
...record.branches?.length ? { branches: record.branches.slice(-LISTED_BRANCHES).map(publicBranch) } : {}
|
|
648
|
+
};
|
|
649
|
+
},
|
|
650
|
+
/** Whether `after` lies in history a rewind set aside: such a client must start over (attach reset). */
|
|
651
|
+
discarded(record, after) {
|
|
652
|
+
return !!record?.branches?.some((branch) => after >= branch.cut && after < branch.marker);
|
|
653
|
+
},
|
|
654
|
+
fork,
|
|
655
|
+
rewind,
|
|
656
|
+
reload,
|
|
657
|
+
resumeCommand,
|
|
658
|
+
configure,
|
|
659
|
+
configurePreview,
|
|
660
|
+
/** The requestId of a rewind whose commit is unfinished for this root: prompts and reopens wait for it. */
|
|
661
|
+
fenced: (root) => fences.get(root),
|
|
662
|
+
/** At start, before requests: finish or settle what a crash left (lifecycle.recover); a rewind left applied fences its root. */
|
|
663
|
+
async recover() {
|
|
664
|
+
const unfinished = await lifecycle.recover(
|
|
665
|
+
{ rewind: (entry) => commitRewind(entry), fork: (entry) => commitFork(entry), reload: (entry) => commitReload(entry), configure: (entry) => commitConfigure(entry) },
|
|
666
|
+
(message, fields) => ctx.log.warn(message, fields)
|
|
667
|
+
);
|
|
668
|
+
for (const entry of unfinished) if (entry.operation === "rewind") fences.set(entry.resource, entry.requestId);
|
|
669
|
+
},
|
|
670
|
+
lifecycle,
|
|
671
|
+
/** Retention cannot erase an unfinished fork or its completion witness owner. */
|
|
672
|
+
async retainsFork(root) {
|
|
673
|
+
for (const entry of await journal.list((_name, error) => {
|
|
674
|
+
throw error;
|
|
675
|
+
})) {
|
|
676
|
+
if (entry.operation !== "fork" || entry.state !== "applied") continue;
|
|
677
|
+
if (entry.resource === root) return true;
|
|
678
|
+
if (entry.plan.newSessionId === root && !await completed(entry)) return true;
|
|
679
|
+
}
|
|
680
|
+
return false;
|
|
681
|
+
}
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
export {
|
|
685
|
+
createConversation,
|
|
686
|
+
defaultForkTitle,
|
|
687
|
+
turnsOf
|
|
688
|
+
};
|