@anhlp/alp-daemon 0.0.0-stage → 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/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +14 -2
- package/dist/THIRD-PARTY-NOTICES.txt +456 -0
- package/dist/alp-templates.d.ts +5 -0
- package/dist/alpd.js +64050 -0
- package/dist/attachments.d.ts +187 -0
- package/dist/attachments.js +856 -0
- package/dist/build-manifest.json +150 -0
- 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 +262 -0
- package/dist/files.js +674 -0
- package/dist/git.d.ts +98 -0
- package/dist/git.js +1246 -0
- package/dist/gitignore.d.ts +62 -0
- package/dist/gitignore.js +254 -0
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +28 -0
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/lock.d.ts +21 -0
- package/dist/lock.js +42 -0
- package/dist/main.d.ts +1 -0
- package/dist/main.js +363 -0
- 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 +40 -0
- package/dist/operations.js +313 -0
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/rpc-error.d.ts +6 -0
- package/dist/rpc-error.js +11 -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 +60 -0
- package/dist/server.js +1958 -0
- package/dist/store.d.ts +178 -0
- package/dist/store.js +386 -0
- 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 +163 -4
- package/src/alp-templates.d.ts +5 -0
- package/src/attachments.ts +908 -0
- package/src/conversation.ts +857 -0
- package/src/disk.ts +175 -0
- package/src/files.ts +884 -0
- package/src/git.ts +1220 -0
- package/src/gitignore.ts +277 -0
- package/src/history.ts +118 -0
- package/src/index.ts +12 -0
- package/src/lifecycle.ts +283 -0
- package/src/lock.ts +53 -0
- package/src/main.ts +381 -0
- 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 +329 -0
- package/src/registry.ts +238 -0
- package/src/rpc-error.ts +4 -0
- package/src/scheduler.ts +438 -0
- package/src/schedules.ts +297 -0
- package/src/server.ts +2238 -0
- package/src/store.ts +449 -0
- 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,857 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { realpath } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { ERROR, RPC_ERROR, resumeCommandOf } from '@anhlp/alp-protocol';
|
|
5
|
+
import type { AlpRuntime, ConfigureChanges, EffectiveConfig, Envelope, NativeBinding, SessionSnapshot } from '@anhlp/alp-runtime/index';
|
|
6
|
+
import type { ConfigureOutcome, ConfigurePreview, ConversationBranch, ForkProvenance, SessionSummary } from '@anhlp/alp-protocol/session';
|
|
7
|
+
import type { RpcMethodMap } from '@anhlp/alp-protocol/rpc';
|
|
8
|
+
import type { SessionRecord, Store, StoredBranch } from './store.js';
|
|
9
|
+
import type { RegistryService } from './registry.js';
|
|
10
|
+
import { RegistryError } from './registry.js';
|
|
11
|
+
import type { Principal } from './attachments.js';
|
|
12
|
+
import { createLifecycle, type LifecycleEntry, type LifecycleJournal } from './lifecycle.js';
|
|
13
|
+
import { RpcError } from './rpc-error.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* session.fork and session.rewind (docs/protocol/alp-json-rpc-v1.md §12.7): a root's conversation cut
|
|
17
|
+
* at a turn becomes a new root (fork), or the root itself continues from before a turn (rewind) while
|
|
18
|
+
* the later turns stay a recoverable branch. Only the conversation changes: no file is copied, restored
|
|
19
|
+
* or changed. Both run through the lifecycle journal (lifecycle.ts) and never send the native step twice.
|
|
20
|
+
*
|
|
21
|
+
* A turn of a root is what its timeline holds: `prompt.accepted` (result turn) or `turn.started`, from
|
|
22
|
+
* the turn's user message on; its end is `turn.ended`. A cut keeps the timeline's lines before the
|
|
23
|
+
* first line of the turn that is cut away.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** Events of a conversation; a fork's timeline holds these of the source root only. */
|
|
27
|
+
const CONVERSATION = new Set(['item', 'turn.started', 'turn.ended', 'prompt.accepted', 'prompt.failed']);
|
|
28
|
+
/** Runtimes whose native conversations alpd forks and rewinds (Codex and Claude, macOS and Linux). */
|
|
29
|
+
const SUPPORTED = new Set(['codex', 'claude']);
|
|
30
|
+
/** How many branches a summary lists; all stay recoverable by id. */
|
|
31
|
+
const LISTED_BRANCHES = 100;
|
|
32
|
+
|
|
33
|
+
export type Turn = { id: string; start: number; end?: number; state?: 'completed' | 'failed' | 'canceled' };
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A fork's title when its creator gave none: the source's with " (fork)" where the fork stays in the
|
|
37
|
+
* source's workspace (the same grants see both); a neutral one in another workspace, whose viewers may
|
|
38
|
+
* not see the source (main's decision, 2026-10-23).
|
|
39
|
+
*/
|
|
40
|
+
export function defaultForkTitle(sourceTitle: string | undefined, sameWorkspace: boolean) {
|
|
41
|
+
return sameWorkspace ? `${sourceTitle ?? 'Session'} (fork)`.slice(0, 200) : 'Fork of a session';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The turns of `root` in a timeline, in order: where each begins and how it ended. */
|
|
45
|
+
export function turnsOf(log: Envelope[], root: string): Turn[] {
|
|
46
|
+
const prompts = new Map<string, number>();
|
|
47
|
+
const turns = new Map<string, Turn>();
|
|
48
|
+
const order: Turn[] = [];
|
|
49
|
+
for (const envelope of log) {
|
|
50
|
+
if (envelope.sessionId !== root || envelope.cursor === undefined) continue;
|
|
51
|
+
const { event } = envelope;
|
|
52
|
+
const cursor = envelope.cursor;
|
|
53
|
+
if (event.type === 'item' && event.item.kind === 'user_message' && event.item.clientMessageId && !prompts.has(event.item.clientMessageId)) prompts.set(event.item.clientMessageId, cursor);
|
|
54
|
+
else if ((event.type === 'prompt.accepted' && event.result === 'turn') || event.type === 'turn.started') {
|
|
55
|
+
if (turns.has(event.turnId)) continue;
|
|
56
|
+
const start = event.type === 'prompt.accepted' ? Math.min(prompts.get(event.clientMessageId) ?? cursor, cursor) : cursor;
|
|
57
|
+
const turn: Turn = { id: event.turnId, start };
|
|
58
|
+
turns.set(turn.id, turn);
|
|
59
|
+
order.push(turn);
|
|
60
|
+
} else if (event.type === 'turn.ended') {
|
|
61
|
+
const turn = turns.get(event.turnId);
|
|
62
|
+
if (turn && turn.state === undefined) Object.assign(turn, { state: event.state, end: cursor });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return order;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
type Busy = { rootId: string } & Record<string, unknown>;
|
|
69
|
+
|
|
70
|
+
export type ConversationContext = {
|
|
71
|
+
runtime: AlpRuntime;
|
|
72
|
+
store: Store;
|
|
73
|
+
journal: LifecycleJournal;
|
|
74
|
+
records: Map<string, SessionRecord>;
|
|
75
|
+
cursors: Map<string, number>;
|
|
76
|
+
logs: Map<string, Envelope[]>;
|
|
77
|
+
treeLogLimit: number;
|
|
78
|
+
summary(sessionId: string): SessionSummary | undefined;
|
|
79
|
+
/** A stable digest of JSON data (the prompt receipt key's). */
|
|
80
|
+
digest(value: unknown): string;
|
|
81
|
+
/** Why a root cannot be mutated now (opening, recovering, prompts in flight), or undefined. */
|
|
82
|
+
unsettled(rootId: string): string | undefined;
|
|
83
|
+
/** Holds prompts, schedule deliveries and reopens of a root until `release` is called. */
|
|
84
|
+
holdPrompts(rootId: string): () => void;
|
|
85
|
+
/** Envelopes to every connection attached to a root's tree, live only. */
|
|
86
|
+
broadcast(rootId: string, envelope: Envelope): void;
|
|
87
|
+
registry?: RegistryService;
|
|
88
|
+
worktrees?: { assertAvailable(directory: string): Promise<void> };
|
|
89
|
+
attachments?: {
|
|
90
|
+
heldBy(holders: string[]): Promise<string[]>;
|
|
91
|
+
authorize(principal: Principal, attachmentIds: string[], forks?: string[]): Promise<void>;
|
|
92
|
+
pin(holder: string, sessionId: string, attachmentIds: string[], kind?: string): Promise<void>;
|
|
93
|
+
};
|
|
94
|
+
crashPoint(name: string): void;
|
|
95
|
+
log: { warn(message: string, fields?: Record<string, unknown>): void; info(message: string, fields?: Record<string, unknown>): void };
|
|
96
|
+
startedAt: string;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
type ForkParams = RpcMethodMap['session.fork']['params'];
|
|
100
|
+
type RewindParams = RpcMethodMap['session.rewind']['params'];
|
|
101
|
+
type ReloadParams = RpcMethodMap['session.reload']['params'];
|
|
102
|
+
type ReloadPlan = { root: string; threadId: string; at: string };
|
|
103
|
+
type ConfigureParams = RpcMethodMap['session.configure']['params'];
|
|
104
|
+
type ConfigurePreviewParams = RpcMethodMap['session.configure.preview']['params'];
|
|
105
|
+
type ConfigurePlan = {
|
|
106
|
+
root: string; requested: ConfigureChanges;
|
|
107
|
+
/** No turn yet: the restart starts a new conversation, there is none to keep. */
|
|
108
|
+
fresh: boolean;
|
|
109
|
+
/** What the root ran with, and what prepare resolved it would run with (journal audit). */
|
|
110
|
+
previous: EffectiveConfig; proposed: EffectiveConfig;
|
|
111
|
+
at: string;
|
|
112
|
+
};
|
|
113
|
+
type ConfigureNative = {
|
|
114
|
+
status: 'applied' | 'unchanged'; restarted: boolean; effective: EffectiveConfig; threadId: string;
|
|
115
|
+
workflow: SessionSnapshot['workflow']; teamLabel?: string; native?: { model?: string; reasoningEffort?: string };
|
|
116
|
+
};
|
|
117
|
+
type ConfigureAnswer = { session: SessionSummary; configured: ConfigureOutcome };
|
|
118
|
+
|
|
119
|
+
type RewindPlan = {
|
|
120
|
+
root: string; beforeTurnId: string; cut: number; branchId: string; turns: number; at: string;
|
|
121
|
+
previous: NativeBinding; cwd: string; marker?: number;
|
|
122
|
+
/** The root's turn ids prepare checked, in order: the native step cuts against these, never a later read. */
|
|
123
|
+
turnIds: string[];
|
|
124
|
+
};
|
|
125
|
+
type ForkPlan = {
|
|
126
|
+
/** New attempts distinguish recoverable pre-record crashes from ambiguous legacy absence. */
|
|
127
|
+
recoveryVersion?: 1;
|
|
128
|
+
source: string; newSessionId: string; branchId?: string; cut: number; boundary: ForkProvenance['boundary']; turnId?: string;
|
|
129
|
+
cwd: string; workspaceId?: string; title: string; at: string; attachmentIds: string[];
|
|
130
|
+
/** The source's turn ids prepare checked, and the runtime cut (a whole fork is cut through its last turn). */
|
|
131
|
+
turnIds: string[]; cutoff?: { throughTurnId: string } | { beforeTurnId: string };
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const busy = (rootId: string, why: string) => new RpcError(ERROR.conflict, `Session ${rootId} is busy: ${why}; try again when it is idle`, { reason: 'session_busy' } satisfies { reason: string });
|
|
135
|
+
|
|
136
|
+
/** A runtime's refusal as a protocol error; an unknown outcome stays marked so the journal records it. */
|
|
137
|
+
function refusal(error: any) {
|
|
138
|
+
if (error instanceof RpcError) return error;
|
|
139
|
+
const reason = error?.data?.reason;
|
|
140
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
141
|
+
if (error?.outcomeUnknown === true) return Object.assign(new RpcError(ERROR.conflict, message, { reason: 'outcome_unknown' }), { outcomeUnknown: true });
|
|
142
|
+
if (reason === 'session_busy') return new RpcError(ERROR.conflict, message, { reason });
|
|
143
|
+
if (reason === 'runtime_unsupported' || reason === 'boundary_unmapped' || reason === 'empty_prefix' || reason === 'native_refused') return new RpcError(ERROR.unavailable, message, { reason });
|
|
144
|
+
return new RpcError(ERROR.unavailable, `The runtime refused it: ${message}`, { reason: 'native_refused' });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* A refusal of a live configure as a protocol error (§12.9): another runtime or agent is unavailable with
|
|
149
|
+
* a way on (a new session), more permissions forbidden, an unknown team not found, a malformed change
|
|
150
|
+
* invalid; the rest as refusal() maps them.
|
|
151
|
+
*/
|
|
152
|
+
function configureRefusal(error: any) {
|
|
153
|
+
if (error instanceof RpcError) return error;
|
|
154
|
+
const reason = error?.data?.reason;
|
|
155
|
+
const message = error instanceof Error ? error.message : String(error?.message ?? error);
|
|
156
|
+
if (error?.outcomeUnknown === true) return refusal(error);
|
|
157
|
+
if (reason === 'runtime_mismatch' || reason === 'agent_mismatch') return new RpcError(ERROR.unavailable, message, { reason, action: 'session.create' });
|
|
158
|
+
if (reason === 'permission_escalation') return new RpcError(ERROR.forbidden, message, { reason });
|
|
159
|
+
if (reason === 'team_not_found') return new RpcError(ERROR.notFound, message, { reason });
|
|
160
|
+
if (reason === 'invalid_params' || reason === 'not_root') return new RpcError(RPC_ERROR.invalidParams, message, { reason: 'invalid_params' });
|
|
161
|
+
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' });
|
|
162
|
+
return refusal(error);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function createConversation(ctx: ConversationContext) {
|
|
166
|
+
const { runtime, store, journal, records } = ctx;
|
|
167
|
+
const lifecycle = createLifecycle(journal, { crashPoint: ctx.crashPoint, completed });
|
|
168
|
+
const reservedForkIds = new Set<string>();
|
|
169
|
+
|
|
170
|
+
async function completed(entry: LifecycleEntry) {
|
|
171
|
+
if (entry.state !== 'applied') return undefined;
|
|
172
|
+
const saved = (await store.get(entry.resource))?.lifecycleCommits?.[entry.key];
|
|
173
|
+
return saved?.createdAt === entry.createdAt && saved.fingerprint === entry.fingerprint && saved.attemptId === entry.attemptId ? { result: saved.result } : undefined;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Publish the result with the final record mutation, never inferred from a later snapshot. */
|
|
177
|
+
async function commitRecord(record: SessionRecord, entry: LifecycleEntry, result: unknown) {
|
|
178
|
+
const previous = record.lifecycleCommits;
|
|
179
|
+
const receipts = { ...previous };
|
|
180
|
+
// Only discard witnesses whose exact journal attempt no longer needs replay protection.
|
|
181
|
+
for (const [key, receipt] of Object.entries(receipts)) {
|
|
182
|
+
try {
|
|
183
|
+
const saved = await journal.get(record.id, receipt.operation, receipt.requestId);
|
|
184
|
+
if (!saved || saved.createdAt !== receipt.createdAt || saved.fingerprint !== receipt.fingerprint || saved.attemptId !== receipt.attemptId || saved.state === 'committed') delete receipts[key];
|
|
185
|
+
} catch { /* A read failure is not proof that its witness can be removed. */ }
|
|
186
|
+
}
|
|
187
|
+
receipts[entry.key] = { operation: entry.operation, requestId: entry.requestId, createdAt: entry.createdAt, fingerprint: entry.fingerprint, attemptId: entry.attemptId, result };
|
|
188
|
+
record.lifecycleCommits = receipts;
|
|
189
|
+
// Keep the witness in every subsequent shared-record snapshot, even when this put fails:
|
|
190
|
+
// an event save already queued with it can still durably complete the mutation. Only
|
|
191
|
+
// completed()'s persisted read may use that witness to skip work.
|
|
192
|
+
await store.put(record);
|
|
193
|
+
}
|
|
194
|
+
// Proven on macOS and Linux only (issue #121 closure scope); Windows does not list the capabilities.
|
|
195
|
+
const enabled = typeof runtime.branch === 'function' && typeof runtime.rebind === 'function' && process.platform !== 'win32';
|
|
196
|
+
/** session.reload (§12.8): a runtime that restarts a root on its own conversation, on macOS and Linux. */
|
|
197
|
+
const reloads = typeof runtime.reload === 'function' && process.platform !== 'win32';
|
|
198
|
+
/** session.configure with model, thinking or team (§12.9): a runtime that restarts a root with a new configuration, on macOS and Linux. */
|
|
199
|
+
const configures = typeof runtime.reconfigure === 'function' && typeof runtime.previewConfigure === 'function' && process.platform !== 'win32';
|
|
200
|
+
|
|
201
|
+
/** A root alpd can fork or rewind, or the reason it cannot. */
|
|
202
|
+
function support(record: SessionRecord, session: SessionSnapshot | undefined): SessionSummary['conversation'] {
|
|
203
|
+
const no = { fork: false, rewind: false, ...(reloads ? { reload: false } : {}), ...(configures ? { configure: false } : {}) };
|
|
204
|
+
if (record.rootId !== record.id || session?.parentId) return { ...no, reason: 'not_root' };
|
|
205
|
+
if (!session || !SUPPORTED.has(session.runtime) || (!enabled && !reloads && !configures)) return { ...no, reason: 'runtime_unsupported' };
|
|
206
|
+
if (!session.persistent || !session.threadId || !record.spec) return { ...no, reason: 'not_persistent' };
|
|
207
|
+
return { fork: enabled, rewind: enabled, ...(reloads ? { reload: true } : {}), ...(configures ? { configure: true } : {}), ...(enabled ? {} : { reason: 'runtime_unsupported' as const }) };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** The record of a root alpd may fork or rewind, refused with the reason otherwise. */
|
|
211
|
+
function rootOf(sessionId: string) {
|
|
212
|
+
const record = records.get(sessionId);
|
|
213
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: 'not_found' });
|
|
214
|
+
const live = runtime.snapshot(sessionId);
|
|
215
|
+
const allowed = support(record, live ?? record.session);
|
|
216
|
+
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' });
|
|
217
|
+
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' });
|
|
218
|
+
if (allowed?.reason === 'not_persistent') throw new RpcError(ERROR.unavailable, 'This session keeps no native conversation to fork or rewind', { reason: 'runtime_unsupported' });
|
|
219
|
+
return record;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** The binding the root continues now: the live session's thread, else the record's. */
|
|
223
|
+
function bindingOf(record: SessionRecord): NativeBinding {
|
|
224
|
+
const threadId = runtime.snapshot(record.id)?.threadId || record.session!.threadId;
|
|
225
|
+
return { threadId, ...(record.base ? { base: record.base } : {}) };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async function generationOf(root: string) {
|
|
229
|
+
return (await store.history(root, root, { limit: 1 })).generation;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function checkGeneration(root: string, expected: string) {
|
|
233
|
+
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' });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const turnNotFound = (turnId: string) => new RpcError(ERROR.notFound, `No turn ${turnId} in this conversation`, { reason: 'turn_not_found' });
|
|
237
|
+
const inProgress = (turnId?: string) => new RpcError(ERROR.conflict, turnId ? `Turn ${turnId} has not ended` : 'A turn of this conversation has not ended', { reason: 'turn_in_progress' });
|
|
238
|
+
/**
|
|
239
|
+
* A turn of the session runs, or one is starting that has no id yet: its turn/start (a mail wake) is on
|
|
240
|
+
* its way, or its process is restarting. A lifecycle hold keeps later wakes back, but not one already
|
|
241
|
+
* sent, so every idle check of a lifecycle prepare asks both.
|
|
242
|
+
*/
|
|
243
|
+
const begun = (sessionId: string) => !!runtime.snapshot(sessionId)?.activeTurnId || !!runtime.starting?.(sessionId);
|
|
244
|
+
const emptyPrefix = () => new RpcError(ERROR.unavailable, 'Nothing comes before the first turn; start a new session instead', { reason: 'empty_prefix' });
|
|
245
|
+
|
|
246
|
+
/** The timeline a fork or rewind reads: the root's, or a branch's. */
|
|
247
|
+
async function timelineOf(root: string, branch?: StoredBranch) {
|
|
248
|
+
return branch ? store.branchTimeline(root, branch.branchId) : store.timeline(root);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ------------------------------------------------------------------ rewind
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Roots whose rewind answered from the runtime but whose commit alpd could not finish: the root's
|
|
255
|
+
* timeline may already be cut while its record still names the old conversation. Prompts and reopens
|
|
256
|
+
* are refused until the same request is sent again (or alpd's next start) finishes the commit.
|
|
257
|
+
*/
|
|
258
|
+
const fences = new Map<string, string>();
|
|
259
|
+
|
|
260
|
+
async function rewind(params: RewindParams) {
|
|
261
|
+
const { sessionId, requestId, ifGeneration, beforeTurnId } = params;
|
|
262
|
+
const fingerprint = ctx.digest({ beforeTurnId });
|
|
263
|
+
const release = ctx.holdPrompts(sessionId);
|
|
264
|
+
let releaseWakes: (() => void) | undefined;
|
|
265
|
+
try {
|
|
266
|
+
const { result, duplicate, entry } = await lifecycle.run<RewindPlan, NativeBinding, RpcMethodMap['session.rewind']['result']>(
|
|
267
|
+
{ resource: sessionId, operation: 'rewind', requestId, fingerprint }, {
|
|
268
|
+
async prepare() {
|
|
269
|
+
const record = rootOf(sessionId);
|
|
270
|
+
const unsettled = ctx.unsettled(sessionId);
|
|
271
|
+
if (unsettled) throw busy(sessionId, unsettled);
|
|
272
|
+
const live = runtime.snapshot(sessionId);
|
|
273
|
+
if (live?.busy) throw busy(sessionId, 'a turn, child, assignment, mail or parked work is in progress');
|
|
274
|
+
if (runtime.questions().some(question => question.rootId === sessionId)) throw busy(sessionId, 'a question waits for an answer');
|
|
275
|
+
// Taken in the same tick as the idle check: from here to the rebind the runtime starts no turn of
|
|
276
|
+
// its own on the root (mail waits). A wake during the reads below would otherwise start a turn
|
|
277
|
+
// that the cut, read from a timeline without it, runs over.
|
|
278
|
+
releaseWakes = runtime.hold?.(sessionId);
|
|
279
|
+
await checkGeneration(sessionId, ifGeneration);
|
|
280
|
+
const turns = turnsOf(await store.timeline(sessionId), sessionId);
|
|
281
|
+
const index = turns.findIndex(turn => turn.id === beforeTurnId);
|
|
282
|
+
if (index < 0) throw turnNotFound(beforeTurnId);
|
|
283
|
+
if (index === 0) throw emptyPrefix();
|
|
284
|
+
const running = turns.find(turn => turn.state === undefined);
|
|
285
|
+
if (running) throw inProgress(running.id);
|
|
286
|
+
// Held mail may wait (rebind does not refuse for it); a turn or question that began anyway may not.
|
|
287
|
+
if (begun(sessionId) || runtime.questions().some(question => question.rootId === sessionId)) throw busy(sessionId, 'a turn or question began meanwhile');
|
|
288
|
+
return {
|
|
289
|
+
root: sessionId, beforeTurnId, cut: turns[index].start, branchId: `br_${randomBytes(8).toString('hex')}`, turns: turns.length - index,
|
|
290
|
+
at: new Date().toISOString(), previous: bindingOf(record), cwd: record.spec!.cwd, turnIds: turns.map(turn => turn.id),
|
|
291
|
+
};
|
|
292
|
+
},
|
|
293
|
+
async apply(plan) {
|
|
294
|
+
const record = records.get(plan.root)!;
|
|
295
|
+
const session = runtime.snapshot(plan.root) ?? record.session!;
|
|
296
|
+
try {
|
|
297
|
+
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 });
|
|
298
|
+
} catch (error) { throw refusal(error); }
|
|
299
|
+
},
|
|
300
|
+
commit: commitRewind,
|
|
301
|
+
repeat: entry => ({ ...entry.result!, session: ctx.summary(entry.plan.root) ?? entry.result!.session }),
|
|
302
|
+
});
|
|
303
|
+
// Only the rewind that fenced the root lifts the fence: a repeat of an older one does not.
|
|
304
|
+
if (fences.get(sessionId) === requestId) fences.delete(sessionId);
|
|
305
|
+
if (!duplicate) await afterRewind(entry);
|
|
306
|
+
// The session as it is now: after afterRewind a live root runs the new conversation.
|
|
307
|
+
return { ...result, session: ctx.summary(sessionId) ?? result.session, ...(duplicate ? { duplicate: true as const } : {}) };
|
|
308
|
+
} catch (error) {
|
|
309
|
+
// The runtime answered but alpd's commit did not finish: no prompt may reach the old conversation now.
|
|
310
|
+
if ((await journal.get(sessionId, 'rewind', requestId).catch(() => undefined))?.state === 'applied') await fence(sessionId, requestId);
|
|
311
|
+
throw error;
|
|
312
|
+
} finally {
|
|
313
|
+
releaseWakes?.();
|
|
314
|
+
release();
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Fences a root whose rewind commit is unfinished: a live root closes, prompts and reopens are refused. */
|
|
319
|
+
async function fence(root: string, requestId: string) {
|
|
320
|
+
fences.set(root, requestId);
|
|
321
|
+
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 });
|
|
322
|
+
if (runtime.snapshot(root)) await runtime.close(root).catch(() => {});
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** alpd's side of a rewind, from its journal entry alone: idempotent, so a restart finishes it. */
|
|
326
|
+
async function commitRewind(entry: LifecycleEntry<RewindPlan, NativeBinding>) {
|
|
327
|
+
const plan = entry.plan;
|
|
328
|
+
const native = entry.native!;
|
|
329
|
+
const record = records.get(plan.root);
|
|
330
|
+
if (!record?.session) throw new Error(`session ${plan.root} is gone`);
|
|
331
|
+
if (plan.marker === undefined) {
|
|
332
|
+
// The marker's cursor follows every cursor this tree has had, and is journaled before the timeline
|
|
333
|
+
// changes, so a crash in between finishes with the same one.
|
|
334
|
+
const stored = await store.timeline(plan.root);
|
|
335
|
+
plan.marker = Math.max(ctx.cursors.get(plan.root) ?? 0, stored.at(-1)?.cursor ?? 0) + 1;
|
|
336
|
+
ctx.cursors.set(plan.root, plan.marker);
|
|
337
|
+
await journal.put(entry);
|
|
338
|
+
} else if ((ctx.cursors.get(plan.root) ?? 0) < plan.marker) ctx.cursors.set(plan.root, plan.marker);
|
|
339
|
+
ctx.crashPoint('rewind.before-timeline');
|
|
340
|
+
await store.rewind(plan.root, { cut: plan.cut, branchId: plan.branchId, marker: rewindMarker(plan) });
|
|
341
|
+
ctx.crashPoint('rewind.after-timeline');
|
|
342
|
+
const branch: StoredBranch = { 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 };
|
|
343
|
+
if (!(record.branches ?? []).some(candidate => candidate.branchId === plan.branchId)) record.branches = [...(record.branches ?? []), branch];
|
|
344
|
+
record.session = { ...record.session, threadId: native.threadId };
|
|
345
|
+
if (native.base) record.base = native.base; else delete record.base;
|
|
346
|
+
record.updatedAt = new Date().toISOString();
|
|
347
|
+
const result = { session: ctx.summary(plan.root)!, generation: await generationOf(plan.root), branch: publicBranch(branch) };
|
|
348
|
+
await commitRecord(record, entry, result);
|
|
349
|
+
if (ctx.logs.has(plan.root)) ctx.logs.set(plan.root, (await store.timeline(plan.root)).slice(-ctx.treeLogLimit));
|
|
350
|
+
return result;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function rewindMarker(plan: RewindPlan): Envelope {
|
|
354
|
+
return {
|
|
355
|
+
sessionId: plan.root, epoch: `rewind-${plan.branchId}`, seq: 0, ts: plan.at, cursor: plan.marker!,
|
|
356
|
+
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.` } },
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** After a rewind is committed: attached clients reset their history; a live root moves to the new conversation. */
|
|
361
|
+
async function afterRewind(entry: LifecycleEntry<RewindPlan, NativeBinding>) {
|
|
362
|
+
const plan = entry.plan;
|
|
363
|
+
const generation = (entry.result as any)?.generation as string | undefined;
|
|
364
|
+
if (generation) ctx.broadcast(plan.root, { sessionId: plan.root, epoch: `rewind-${plan.branchId}`, seq: 0, ts: new Date().toISOString(), event: { type: 'history.reset', generation, reason: 'rewind', branchId: plan.branchId } });
|
|
365
|
+
ctx.broadcast(plan.root, rewindMarker(plan));
|
|
366
|
+
if (!runtime.snapshot(plan.root)) return;
|
|
367
|
+
try {
|
|
368
|
+
await runtime.rebind!(plan.root, entry.native!);
|
|
369
|
+
} catch (error) {
|
|
370
|
+
// The record already names the new conversation; a live session left on the old one would write
|
|
371
|
+
// there, so it closes, and the next open continues the new conversation.
|
|
372
|
+
ctx.log.warn(`could not move ${plan.root} to its rewound conversation; closing it`, { code: 'ALPD_REWIND_REBIND_FAILED', sessionId: plan.root, error });
|
|
373
|
+
await runtime.close(plan.root).catch(() => {});
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// ------------------------------------------------------------------ reload
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* session.reload (§12.8): the live root's native process restarts on the conversation it runs now,
|
|
381
|
+
* with its own configuration, at the idle barrier a rewind waits for; its id, timeline and receipts
|
|
382
|
+
* are not touched. Journaled as fork and rewind are; the native step is never sent twice. A root
|
|
383
|
+
* with no turn yet has no conversation to keep (a Claude one has no transcript): refused, as is a
|
|
384
|
+
* closed root (session.create { resume: true } opens it).
|
|
385
|
+
*/
|
|
386
|
+
async function reload(params: ReloadParams) {
|
|
387
|
+
const { sessionId, requestId, ifGeneration } = params;
|
|
388
|
+
const fingerprint = ctx.digest({ reload: sessionId });
|
|
389
|
+
const release = ctx.holdPrompts(sessionId);
|
|
390
|
+
let releaseWakes: (() => void) | undefined;
|
|
391
|
+
try {
|
|
392
|
+
const { result, duplicate } = await lifecycle.run<ReloadPlan, { threadId: string }, RpcMethodMap['session.reload']['result']>(
|
|
393
|
+
{ resource: sessionId, operation: 'reload', requestId, fingerprint }, {
|
|
394
|
+
async prepare() {
|
|
395
|
+
const record = records.get(sessionId);
|
|
396
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: 'not_found' });
|
|
397
|
+
const live = runtime.snapshot(sessionId);
|
|
398
|
+
const allowed = support(record, live ?? record.session);
|
|
399
|
+
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' });
|
|
400
|
+
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' });
|
|
401
|
+
const unsettled = ctx.unsettled(sessionId);
|
|
402
|
+
if (unsettled) throw busy(sessionId, unsettled);
|
|
403
|
+
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' });
|
|
404
|
+
if (live.busy) throw busy(sessionId, 'a turn, child, assignment, mail or parked work is in progress');
|
|
405
|
+
if (runtime.questions().some(question => question.rootId === sessionId)) throw busy(sessionId, 'a question waits for an answer');
|
|
406
|
+
// Taken in the same tick as the idle check: from here to the restart the runtime starts no turn of
|
|
407
|
+
// its own on the root (mail waits, then reaches the new process). A wake during the reads below
|
|
408
|
+
// would otherwise make the restart refuse busy after `prepared`, journaling a transient refusal.
|
|
409
|
+
releaseWakes = runtime.hold?.(sessionId);
|
|
410
|
+
await checkGeneration(sessionId, ifGeneration);
|
|
411
|
+
const turns = turnsOf(await store.timeline(sessionId), sessionId);
|
|
412
|
+
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' });
|
|
413
|
+
const running = turns.find(turn => turn.state === undefined);
|
|
414
|
+
if (running) throw inProgress(running.id);
|
|
415
|
+
// Held mail may wait (restartRefusal lets it); a turn or question that began anyway may not.
|
|
416
|
+
const now = runtime.snapshot(sessionId);
|
|
417
|
+
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' });
|
|
418
|
+
if (begun(sessionId) || runtime.questions().some(question => question.rootId === sessionId)) throw busy(sessionId, 'a turn or question began meanwhile');
|
|
419
|
+
return { root: sessionId, threadId: live.threadId!, at: new Date().toISOString() };
|
|
420
|
+
},
|
|
421
|
+
async apply(plan) {
|
|
422
|
+
try {
|
|
423
|
+
const session = await runtime.reload!(plan.root);
|
|
424
|
+
return { threadId: session.threadId! };
|
|
425
|
+
} catch (error) { throw refusal(error); }
|
|
426
|
+
},
|
|
427
|
+
commit: commitReload,
|
|
428
|
+
repeat: entry => ({ session: ctx.summary(entry.plan.root) ?? entry.result!.session }),
|
|
429
|
+
});
|
|
430
|
+
return { ...result, session: ctx.summary(sessionId) ?? result.session, ...(duplicate ? { duplicate: true as const } : {}) };
|
|
431
|
+
} finally {
|
|
432
|
+
releaseWakes?.();
|
|
433
|
+
release();
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** alpd's side of a reload: nothing to write, its conversation and record are unchanged (idempotent). */
|
|
438
|
+
async function commitReload(entry: LifecycleEntry<ReloadPlan, { threadId: string }>) {
|
|
439
|
+
const plan = entry.plan;
|
|
440
|
+
const record = records.get(plan.root);
|
|
441
|
+
if (!record?.session) throw new Error(`session ${plan.root} is gone`);
|
|
442
|
+
return { session: ctx.summary(plan.root)! };
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* session.resumeCommand (§12.8): the ALP CLI command that follows this session in a terminal on the
|
|
447
|
+
* daemon host. Built here, from the session id only: no native runtime command (ALP's orchestration,
|
|
448
|
+
* mail and assignments would be lost), credential, env or path.
|
|
449
|
+
*/
|
|
450
|
+
function resumeCommand(sessionId: string) {
|
|
451
|
+
if (!records.has(sessionId) && !runtime.snapshot(sessionId)) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: 'not_found' });
|
|
452
|
+
return resumeCommandOf(sessionId, process.platform === 'win32' ? 'windows' : 'posix');
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// ------------------------------------------------------------------ live configure
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* session.configure with model, thinking or team (§12.9): the live root's native process restarts with
|
|
459
|
+
* the new configuration on the same conversation, at the idle barrier a reload waits for; alpd writes
|
|
460
|
+
* it to the session's record only once the runtime took it. Journaled as reload is; the native step is
|
|
461
|
+
* never sent twice, and a repeat answers the first result. A refusal before `prepared` (validation, a
|
|
462
|
+
* busy tree, a stale generation) records nothing.
|
|
463
|
+
*/
|
|
464
|
+
async function configure(params: ConfigureParams) {
|
|
465
|
+
const { sessionId, requestId, ifGeneration } = params;
|
|
466
|
+
const requested: ConfigureChanges = {};
|
|
467
|
+
for (const key of ['model', 'thinking', 'team', 'mode'] as const) {
|
|
468
|
+
const value = params[key];
|
|
469
|
+
if (value === undefined) continue;
|
|
470
|
+
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' });
|
|
471
|
+
requested[key] = value.trim();
|
|
472
|
+
}
|
|
473
|
+
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' });
|
|
474
|
+
const fingerprint = ctx.digest({ configure: sessionId, ...requested });
|
|
475
|
+
const release = ctx.holdPrompts(sessionId);
|
|
476
|
+
let releaseWakes: (() => void) | undefined;
|
|
477
|
+
try {
|
|
478
|
+
const { result, duplicate } = await lifecycle.run<ConfigurePlan, ConfigureNative, ConfigureAnswer>(
|
|
479
|
+
{ resource: sessionId, operation: 'configure', requestId, fingerprint }, {
|
|
480
|
+
async prepare() {
|
|
481
|
+
const record = records.get(sessionId);
|
|
482
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: 'not_found' });
|
|
483
|
+
const live = runtime.snapshot(sessionId);
|
|
484
|
+
const allowed = support(record, live ?? record.session);
|
|
485
|
+
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' });
|
|
486
|
+
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' });
|
|
487
|
+
const unsettled = ctx.unsettled(sessionId);
|
|
488
|
+
if (unsettled) throw busy(sessionId, unsettled);
|
|
489
|
+
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' });
|
|
490
|
+
if (live.busy) throw busy(sessionId, 'a turn, child, assignment, mail or parked work is in progress');
|
|
491
|
+
if (runtime.questions().some(question => question.rootId === sessionId)) throw busy(sessionId, 'a question waits for an answer');
|
|
492
|
+
// Taken in the same tick as the idle check, as a reload takes it (t-15b0.17): no wake starts a
|
|
493
|
+
// turn while the reads below run; held mail reaches the restarted process.
|
|
494
|
+
releaseWakes = runtime.hold?.(sessionId);
|
|
495
|
+
await checkGeneration(sessionId, ifGeneration);
|
|
496
|
+
const turns = turnsOf(await store.timeline(sessionId), sessionId);
|
|
497
|
+
const running = turns.find(turn => turn.state === undefined);
|
|
498
|
+
if (running) throw inProgress(running.id);
|
|
499
|
+
// Resolved now, so a change the runtime would refuse (another runtime, more permissions, an
|
|
500
|
+
// unknown model or team) is refused here and journals nothing.
|
|
501
|
+
const preview = await runtime.previewConfigure!(sessionId, requested).catch(error => { throw configureRefusal(error); });
|
|
502
|
+
if (!preview.allowed) throw configureRefusal({ data: { reason: preview.reason }, message: preview.message ?? 'The change was refused' });
|
|
503
|
+
const now = runtime.snapshot(sessionId);
|
|
504
|
+
if (!now) throw new RpcError(ERROR.unavailable, 'The session closed; open it (session.create { resume: true }), then change its configuration', { reason: 'session_closed' });
|
|
505
|
+
if (begun(sessionId) || runtime.questions().some(question => question.rootId === sessionId)) throw busy(sessionId, 'a turn or question began meanwhile');
|
|
506
|
+
return { root: sessionId, requested, fresh: !turns.length && !record.base, previous: preview.current, proposed: preview.proposed, at: new Date().toISOString() };
|
|
507
|
+
},
|
|
508
|
+
async apply(plan) {
|
|
509
|
+
try {
|
|
510
|
+
const done = await runtime.reconfigure!(plan.root, plan.requested, { fresh: plan.fresh, onApplied: async done => {
|
|
511
|
+
// This callback belongs to this exact runtime apply, before its successful update.
|
|
512
|
+
// Persist now so a lost answer needs no inference from a later snapshot at startup.
|
|
513
|
+
const record = records.get(plan.root);
|
|
514
|
+
if (!record?.spec || !record.session) throw new Error(`session ${plan.root} is gone`);
|
|
515
|
+
writeConfiguration(record, done.effective, done.session);
|
|
516
|
+
record.updatedAt = new Date().toISOString();
|
|
517
|
+
await store.put(record);
|
|
518
|
+
} });
|
|
519
|
+
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 } : {}) };
|
|
520
|
+
} catch (error) { throw configureRefusal(error); }
|
|
521
|
+
},
|
|
522
|
+
commit: commitConfigure,
|
|
523
|
+
repeat: entry => ({ session: ctx.summary(entry.plan.root) ?? entry.result!.session, configured: entry.result!.configured }),
|
|
524
|
+
});
|
|
525
|
+
return { ...result, session: ctx.summary(sessionId) ?? result.session, ...(duplicate ? { duplicate: true as const } : {}) };
|
|
526
|
+
} finally {
|
|
527
|
+
releaseWakes?.();
|
|
528
|
+
release();
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* alpd's side of a live configure, from the journal entry alone (idempotent): the session's record runs
|
|
534
|
+
* with what the runtime took, and a reopen resumes with it (its spec's effort, team and mode; its
|
|
535
|
+
* snapshot's model, team and thread).
|
|
536
|
+
*/
|
|
537
|
+
async function commitConfigure(entry: LifecycleEntry<ConfigurePlan, ConfigureNative>): Promise<ConfigureAnswer> {
|
|
538
|
+
const plan = entry.plan;
|
|
539
|
+
const native = entry.native!;
|
|
540
|
+
const record = records.get(plan.root);
|
|
541
|
+
if (!record?.session || !record.spec) throw new Error(`session ${plan.root} is gone`);
|
|
542
|
+
if (native.status === 'applied') writeConfiguration(record, native.effective, { threadId: native.threadId, workflow: native.workflow, teamLabel: native.teamLabel });
|
|
543
|
+
record.updatedAt = new Date().toISOString();
|
|
544
|
+
const result = { session: ctx.summary(plan.root)!, configured: { status: native.status, requested: plan.requested, effective: native.effective, restarted: native.restarted } };
|
|
545
|
+
await commitRecord(record, entry, result);
|
|
546
|
+
return result;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Writes an effective configuration to a session's record: what a reopen resumes with. */
|
|
550
|
+
function writeConfiguration(record: SessionRecord, effective: EffectiveConfig, session: { threadId?: string; workflow?: SessionSnapshot['workflow']; teamLabel?: string }) {
|
|
551
|
+
const { thinking: _thinking, ...spec } = record.spec!;
|
|
552
|
+
record.spec = { ...spec, thinking: effective.thinking, mode: effective.mode, ...(effective.team !== 'custom' ? { workflow: effective.team } : {}) };
|
|
553
|
+
const teamLabel = session.teamLabel ?? effective.teamLabel;
|
|
554
|
+
const { teamLabel: _label, ...snapshot } = record.session!;
|
|
555
|
+
record.session = {
|
|
556
|
+
...snapshot, model: effective.model, thinking: effective.thinking, mode: effective.mode,
|
|
557
|
+
workflow: session.workflow ?? { mode: effective.team, maxPeers: effective.maxPeers ?? record.session!.workflow.maxPeers, supervisor: effective.supervisor },
|
|
558
|
+
...(teamLabel ? { teamLabel } : {}),
|
|
559
|
+
...(session.threadId ? { threadId: session.threadId } : {}),
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** session.configure.preview (§12.9): what a change would run the live root with, and whether it would be taken now. */
|
|
564
|
+
async function configurePreview(params: ConfigurePreviewParams): Promise<ConfigurePreview> {
|
|
565
|
+
const { sessionId } = params;
|
|
566
|
+
const requested: ConfigureChanges = {};
|
|
567
|
+
for (const key of ['model', 'thinking', 'team', 'mode'] as const) {
|
|
568
|
+
const value = params[key];
|
|
569
|
+
if (value === undefined) continue;
|
|
570
|
+
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' });
|
|
571
|
+
requested[key] = value.trim();
|
|
572
|
+
}
|
|
573
|
+
const record = records.get(sessionId);
|
|
574
|
+
if (!record && !runtime.snapshot(sessionId)) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: 'not_found' });
|
|
575
|
+
const live = runtime.snapshot(sessionId);
|
|
576
|
+
if (!live) throw new RpcError(ERROR.unavailable, 'The session is not open; open it to see what it would run with', { reason: 'session_closed' });
|
|
577
|
+
const preview = await runtime.previewConfigure!(sessionId, requested).catch(error => { throw configureRefusal(error); });
|
|
578
|
+
const allowed = record ? support(record, live) : undefined;
|
|
579
|
+
if (preview.allowed && !allowed?.configure) return { ...preview, allowed: false, reason: allowed?.reason === 'not_root' ? 'not_root' : allowed?.reason === 'not_persistent' ? 'not_persistent' : 'runtime_unsupported' };
|
|
580
|
+
const unsettled = preview.allowed && preview.changes.length ? ctx.unsettled(sessionId) : undefined;
|
|
581
|
+
return unsettled ? { ...preview, allowed: false, reason: 'session_busy', message: `Session ${sessionId} is busy: ${unsettled}` } : preview;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// ------------------------------------------------------------------ fork
|
|
585
|
+
|
|
586
|
+
async function fork(params: ForkParams & { principal: Principal }) {
|
|
587
|
+
const { sessionId, requestId, ifGeneration, boundary, branchId, workspaceId, newSessionId, title, principal } = params;
|
|
588
|
+
const fingerprint = ctx.digest({ boundary: boundary ?? null, branchId: branchId ?? null, workspaceId: workspaceId ?? null, newSessionId: newSessionId ?? null, title: title ?? null });
|
|
589
|
+
// A fork that keeps the latest turn reads the source up to its end: from its prepare on, no prompt,
|
|
590
|
+
// reopen or wake may land in between (released when it answers).
|
|
591
|
+
let release: (() => void) | undefined;
|
|
592
|
+
let releaseWakes: (() => void) | undefined;
|
|
593
|
+
let reservedId: string | undefined;
|
|
594
|
+
try {
|
|
595
|
+
const { result, duplicate } = await lifecycle.run<ForkPlan, NativeBinding, RpcMethodMap['session.fork']['result']>(
|
|
596
|
+
{ resource: sessionId, operation: 'fork', requestId, fingerprint }, {
|
|
597
|
+
async prepare() {
|
|
598
|
+
const record = rootOf(sessionId);
|
|
599
|
+
await checkGeneration(sessionId, ifGeneration);
|
|
600
|
+
const branch = branchId === undefined ? undefined : record.branches?.find(candidate => candidate.branchId === branchId);
|
|
601
|
+
if (branchId !== undefined && !branch) throw new RpcError(ERROR.notFound, `No branch ${branchId} of this session`, { reason: 'branch_not_found' });
|
|
602
|
+
const log = await timelineOf(sessionId, branch);
|
|
603
|
+
const turns = turnsOf(log, sessionId);
|
|
604
|
+
const last = log.at(-1)?.cursor ?? 0;
|
|
605
|
+
let cut: number;
|
|
606
|
+
let kind: ForkProvenance['boundary'] = 'whole';
|
|
607
|
+
let turnId: string | undefined;
|
|
608
|
+
if (boundary && 'throughTurnId' in boundary) {
|
|
609
|
+
const index = turns.findIndex(turn => turn.id === boundary.throughTurnId);
|
|
610
|
+
if (index < 0) throw turnNotFound(boundary.throughTurnId);
|
|
611
|
+
if (turns.slice(0, index + 1).some(turn => turn.state === undefined)) throw inProgress(boundary.throughTurnId);
|
|
612
|
+
cut = turns[index + 1]?.start ?? last + 1;
|
|
613
|
+
kind = 'through'; turnId = boundary.throughTurnId;
|
|
614
|
+
} else if (boundary && 'beforeTurnId' in boundary) {
|
|
615
|
+
const index = turns.findIndex(turn => turn.id === boundary.beforeTurnId);
|
|
616
|
+
if (index < 0) throw turnNotFound(boundary.beforeTurnId);
|
|
617
|
+
if (index === 0) throw emptyPrefix();
|
|
618
|
+
if (turns.slice(0, index).some(turn => turn.state === undefined)) throw inProgress();
|
|
619
|
+
cut = turns[index].start;
|
|
620
|
+
kind = 'before'; turnId = boundary.beforeTurnId;
|
|
621
|
+
} else {
|
|
622
|
+
if (!turns.length) throw emptyPrefix();
|
|
623
|
+
const running = turns.find(turn => turn.state === undefined);
|
|
624
|
+
if (running) throw inProgress(running.id);
|
|
625
|
+
cut = last + 1;
|
|
626
|
+
}
|
|
627
|
+
// The cut keeps the source's latest turn (a whole fork, or through its last one): the live source
|
|
628
|
+
// must stay idle until the native step read it, as for a rewind.
|
|
629
|
+
const latest = !branch && cut > (turns.at(-1)?.start ?? 0);
|
|
630
|
+
if (latest) {
|
|
631
|
+
release = ctx.holdPrompts(sessionId);
|
|
632
|
+
const unsettled = ctx.unsettled(sessionId);
|
|
633
|
+
if (unsettled) throw busy(sessionId, unsettled);
|
|
634
|
+
if (begun(sessionId)) throw inProgress();
|
|
635
|
+
// Taken in the same tick as the idle check, before the read below: a wake during that read would
|
|
636
|
+
// otherwise start a turn the cut, read from a timeline without it, does not see.
|
|
637
|
+
releaseWakes = runtime.hold?.(sessionId);
|
|
638
|
+
// A turn that started and ended before the hold: the cut no longer keeps the latest turn.
|
|
639
|
+
const now = turnsOf(await timelineOf(sessionId, branch), sessionId);
|
|
640
|
+
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');
|
|
641
|
+
}
|
|
642
|
+
const latestTurn = turns.at(-1)?.id;
|
|
643
|
+
const cutoff: ForkPlan['cutoff'] = kind === 'through' ? { throughTurnId: turnId! } : kind === 'before' ? { beforeTurnId: turnId! } : latestTurn ? { throughTurnId: latestTurn } : undefined;
|
|
644
|
+
// A restart loses the in-memory reservations. Unfinished native attempts still
|
|
645
|
+
// own their targets, even when no target record was durably written yet.
|
|
646
|
+
const pendingIds = new Set((await journal.list())
|
|
647
|
+
.filter(entry => entry.operation === 'fork' && ['prepared', 'applied', 'unknown'].includes(entry.state))
|
|
648
|
+
.map(entry => (entry.plan as ForkPlan).newSessionId));
|
|
649
|
+
let id = newSessionId;
|
|
650
|
+
if (id !== undefined) {
|
|
651
|
+
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' });
|
|
652
|
+
} else {
|
|
653
|
+
do { id = `ses_${randomBytes(8).toString('hex')}`; } while (records.has(id) || runtime.snapshot(id) || reservedForkIds.has(id) || pendingIds.has(id));
|
|
654
|
+
}
|
|
655
|
+
reservedForkIds.add(id);
|
|
656
|
+
reservedId = id;
|
|
657
|
+
const cwd = await destinationOf(record, workspaceId);
|
|
658
|
+
const attachmentIds = await reauthorize(sessionId, log, cut, principal);
|
|
659
|
+
// Last, after every read of prepare: held mail may wait; a turn that began anyway may not.
|
|
660
|
+
if (latest && begun(sessionId)) throw busy(sessionId, 'a turn began meanwhile');
|
|
661
|
+
return {
|
|
662
|
+
recoveryVersion: 1, source: sessionId, newSessionId: id, ...(branchId ? { branchId } : {}), cut, boundary: kind, ...(turnId ? { turnId } : {}),
|
|
663
|
+
cwd, ...(workspaceId ? { workspaceId } : {}), title: title ?? defaultForkTitle(record.title, cwd === record.spec!.cwd), at: new Date().toISOString(), attachmentIds,
|
|
664
|
+
turnIds: turns.map(turn => turn.id), ...(cutoff ? { cutoff } : {}),
|
|
665
|
+
};
|
|
666
|
+
},
|
|
667
|
+
async apply(plan) {
|
|
668
|
+
const record = records.get(plan.source)!;
|
|
669
|
+
const session = runtime.snapshot(plan.source) ?? record.session!;
|
|
670
|
+
const branch = plan.branchId ? record.branches?.find(candidate => candidate.branchId === plan.branchId) : undefined;
|
|
671
|
+
const source: NativeBinding = branch ? { threadId: branch.threadId, ...(branch.base ? { base: branch.base } : {}) } : bindingOf(record);
|
|
672
|
+
try {
|
|
673
|
+
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 });
|
|
674
|
+
} catch (error) { throw refusal(error); }
|
|
675
|
+
},
|
|
676
|
+
commit: commitFork,
|
|
677
|
+
repeat: entry => ({ ...entry.result!, session: ctx.summary(entry.plan.newSessionId) ?? entry.result!.session }),
|
|
678
|
+
});
|
|
679
|
+
return { ...result, ...(duplicate ? { duplicate: true as const } : {}) };
|
|
680
|
+
} finally {
|
|
681
|
+
if (reservedId && !records.has(reservedId)) {
|
|
682
|
+
// A failed commit or unknown native outcome must keep ownership for retry.
|
|
683
|
+
// A refusal (or preparation failure before journaling) changed nothing.
|
|
684
|
+
const entry = await journal.get(sessionId, 'fork', requestId).catch(() => ({ state: 'unknown' }));
|
|
685
|
+
if (!entry || entry.state === 'failed') reservedForkIds.delete(reservedId);
|
|
686
|
+
}
|
|
687
|
+
releaseWakes?.();
|
|
688
|
+
release?.();
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/** Where a fork runs: the source's directory, or a registered workspace of the same project. */
|
|
693
|
+
async function destinationOf(record: SessionRecord, workspaceId: string | undefined) {
|
|
694
|
+
if (workspaceId === undefined) return record.spec!.cwd;
|
|
695
|
+
const registry = ctx.registry;
|
|
696
|
+
if (!registry) throw new RpcError(RPC_ERROR.invalidParams, 'This alpd keeps no workspace registry', { reason: 'invalid_params' });
|
|
697
|
+
try {
|
|
698
|
+
const cwd = await registry.resolve(workspaceId);
|
|
699
|
+
const snapshot = await registry.snapshot();
|
|
700
|
+
const target = snapshot.workspaces.find(candidate => candidate.id === workspaceId);
|
|
701
|
+
const placed = snapshot.sessions[record.id];
|
|
702
|
+
const from = placed ? snapshot.workspaces.find(candidate => candidate.id === placed) : undefined;
|
|
703
|
+
if (from && target && from.projectId !== target.projectId) throw new RpcError(ERROR.conflict, 'A fork stays in the project of its source', { reason: 'workspace_mismatch' });
|
|
704
|
+
await ctx.worktrees?.assertAvailable(cwd);
|
|
705
|
+
return cwd;
|
|
706
|
+
} catch (error) {
|
|
707
|
+
if (error instanceof RegistryError) throw new RpcError(error.code, error.message, error.data);
|
|
708
|
+
throw error;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* The attachments the kept prompts pinned, re-authorized for the caller (each committed and bound to
|
|
714
|
+
* this principal and an authorized project), so the fork may pin them too (§12.6). Refused otherwise.
|
|
715
|
+
*/
|
|
716
|
+
async function reauthorize(source: string, log: Envelope[], cut: number, principal: Principal) {
|
|
717
|
+
if (!ctx.attachments) return [];
|
|
718
|
+
// A prompt copied into a fork keeps the receipt holder of the session it was first sent to: the kept
|
|
719
|
+
// prompts are looked up under the source and every session it was forked from.
|
|
720
|
+
const lineage: string[] = [];
|
|
721
|
+
for (let id: string | undefined = source; id && !lineage.includes(id) && lineage.length < 32; id = records.get(id)?.forkedFrom?.sessionId) lineage.push(id);
|
|
722
|
+
const holders: string[] = [];
|
|
723
|
+
// What the kept messages say they carried (ids alone): a fork's own holder pins every attachment it
|
|
724
|
+
// inherited, so only these of them go on, whichever ancestor is gone by now.
|
|
725
|
+
const named = new Set<string>();
|
|
726
|
+
for (const { sessionId, cursor, event } of log) {
|
|
727
|
+
if (sessionId !== source || (cursor ?? 0) >= cut || event.type !== 'item' || event.item.kind !== 'user_message' || !event.item.clientMessageId) continue;
|
|
728
|
+
for (const id of lineage) holders.push(`prompt:${ctx.digest(['prompt', id, event.item.clientMessageId])}`);
|
|
729
|
+
for (const attachment of Array.isArray(event.item.attachments) ? event.item.attachments : []) if (typeof attachment?.attachmentId === 'string') named.add(attachment.attachmentId);
|
|
730
|
+
}
|
|
731
|
+
const found = new Set(await ctx.attachments.heldBy(holders));
|
|
732
|
+
// A fork of a fork: the prompts' own holders went with an ancestor's deleted history, the forks' hold on.
|
|
733
|
+
if (named.size) for (const id of await ctx.attachments.heldBy(lineage.map(id => `fork:${id}`))) if (named.has(id)) found.add(id);
|
|
734
|
+
const ids = [...found];
|
|
735
|
+
if (!ids.length) return [];
|
|
736
|
+
try { await ctx.attachments.authorize(principal, ids, lineage); }
|
|
737
|
+
catch { throw new RpcError(ERROR.forbidden, 'The conversation holds attachments this caller may not use', { reason: 'attachment_forbidden' }); }
|
|
738
|
+
return ids;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/** alpd's side of a fork, from its journal entry alone: the new root's timeline, record, placement and attachment references. */
|
|
742
|
+
async function commitFork(entry: LifecycleEntry<ForkPlan, NativeBinding>) {
|
|
743
|
+
const plan = entry.plan;
|
|
744
|
+
const native = entry.native!;
|
|
745
|
+
const source = records.get(plan.source);
|
|
746
|
+
if (!source?.session || !source.spec) throw new Error(`session ${plan.source} is gone`);
|
|
747
|
+
const forkedFrom: ForkProvenance = { sessionId: plan.source, ...(plan.turnId ? { turnId: plan.turnId } : {}), boundary: plan.boundary, ...(plan.branchId ? { branchId: plan.branchId } : {}), at: plan.at };
|
|
748
|
+
const target = records.get(plan.newSessionId);
|
|
749
|
+
const owner = target?.forkAttempt;
|
|
750
|
+
if (target && (owner
|
|
751
|
+
? owner.key !== entry.key || owner.attemptId !== entry.attemptId || owner.createdAt !== entry.createdAt || owner.fingerprint !== entry.fingerprint
|
|
752
|
+
: plan.recoveryVersion === 1 || target.rootId !== plan.newSessionId || target.forkedFrom?.sessionId !== plan.source
|
|
753
|
+
|| target.forkedFrom.at !== plan.at || target.forkedFrom.boundary !== plan.boundary
|
|
754
|
+
|| target.forkedFrom.turnId !== plan.turnId || target.forkedFrom.branchId !== plan.branchId)) {
|
|
755
|
+
throw new RpcError(ERROR.failed, 'The fork target does not belong to this journal attempt', { reason: 'persistence_failed' });
|
|
756
|
+
}
|
|
757
|
+
if (!target && plan.recoveryVersion !== 1) {
|
|
758
|
+
// Pre-upgrade absence cannot distinguish a pre-record crash from a completed fork
|
|
759
|
+
// whose target retention already removed. Never recreate that ambiguous target.
|
|
760
|
+
throw new RpcError(ERROR.failed, 'The legacy fork target is gone; its completion cannot be established', { reason: 'persistence_failed' });
|
|
761
|
+
}
|
|
762
|
+
if (!target) {
|
|
763
|
+
const branch = plan.branchId ? source.branches?.find(candidate => candidate.branchId === plan.branchId) : undefined;
|
|
764
|
+
const kept = (await timelineOf(plan.source, branch)).filter(envelope => envelope.sessionId === plan.source && (envelope.cursor ?? 0) < plan.cut && CONVERSATION.has(envelope.event.type));
|
|
765
|
+
const envelopes: Envelope[] = kept.map((envelope, index) => ({ ...envelope, sessionId: plan.newSessionId, cursor: index + 1 }));
|
|
766
|
+
envelopes.push({
|
|
767
|
+
sessionId: plan.newSessionId, epoch: `fork-${plan.newSessionId}`, seq: 0, ts: plan.at, cursor: envelopes.length + 1,
|
|
768
|
+
// No source title or id here: a viewer granted the fork but not its source must not learn them.
|
|
769
|
+
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.` } },
|
|
770
|
+
});
|
|
771
|
+
ctx.crashPoint('fork.before-timeline');
|
|
772
|
+
await store.createTimeline(plan.newSessionId, envelopes);
|
|
773
|
+
const { activeTurnId: _active, parked: _parked, usage: _usage, toolCallId: _call, parentId: _parent, ...kept_ } = source.session;
|
|
774
|
+
const moved = plan.cwd !== source.spec.cwd;
|
|
775
|
+
const now = new Date().toISOString();
|
|
776
|
+
const record: SessionRecord = {
|
|
777
|
+
version: 1, id: plan.newSessionId, rootId: plan.newSessionId, spec: { ...source.spec, cwd: plan.cwd }, ...(source.delegation !== undefined ? { delegation: source.delegation } : {}),
|
|
778
|
+
session: { ...kept_, id: plan.newSessionId, threadId: native.threadId, busy: false, ...(moved ? { projectRoot: await realpath(plan.cwd).catch(() => path.resolve(plan.cwd)) } : {}) },
|
|
779
|
+
status: 'closed', title: plan.title, forkedFrom, forkAttempt: { key: entry.key, attemptId: entry.attemptId, createdAt: entry.createdAt, fingerprint: entry.fingerprint }, ...(native.base ? { base: native.base } : {}), createdAt: now, updatedAt: now,
|
|
780
|
+
};
|
|
781
|
+
ctx.crashPoint('fork.before-record');
|
|
782
|
+
await store.put(record);
|
|
783
|
+
records.set(record.id, record);
|
|
784
|
+
}
|
|
785
|
+
reservedForkIds.delete(plan.newSessionId);
|
|
786
|
+
await place(plan, entry.key);
|
|
787
|
+
if (plan.attachmentIds.length) await ctx.attachments?.pin(`fork:${plan.newSessionId}`, plan.newSessionId, plan.attachmentIds, 'fork');
|
|
788
|
+
const result = { session: ctx.summary(plan.newSessionId)!, forkedFrom };
|
|
789
|
+
// The source outlives an independently expired target. Only this final persisted
|
|
790
|
+
// witness, after placement and pins, proves that replay must not create it again.
|
|
791
|
+
await commitRecord(source, entry, result);
|
|
792
|
+
return result;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/** The fork's place in the registry: the destination workspace, else its source's, else its directory's. */
|
|
796
|
+
async function place(plan: ForkPlan, key: string) {
|
|
797
|
+
const registry = ctx.registry;
|
|
798
|
+
if (!registry) return;
|
|
799
|
+
try {
|
|
800
|
+
const snapshot = await registry.snapshot();
|
|
801
|
+
if (Object.hasOwn(snapshot.sessions, plan.newSessionId)) return;
|
|
802
|
+
const workspaceId = plan.workspaceId ?? (Object.hasOwn(snapshot.sessions, plan.source) ? snapshot.sessions[plan.source] : undefined);
|
|
803
|
+
if (workspaceId) await registry.mutate('placement.assign', { sessionId: plan.newSessionId, workspaceId }, { requestId: `fork:${key}` });
|
|
804
|
+
else await registry.mutate('placement.prepare', { sessions: [{ id: plan.newSessionId, projectRoot: plan.cwd }] }, { requestId: `fork:${key}` });
|
|
805
|
+
} catch (error) {
|
|
806
|
+
if (error instanceof RegistryError) throw new RpcError(error.code, error.message, error.data);
|
|
807
|
+
throw error;
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
function publicBranch({ branchId, beforeTurnId, turns, at }: StoredBranch): ConversationBranch {
|
|
812
|
+
return { branchId, beforeTurnId, turns, at };
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
return {
|
|
816
|
+
enabled,
|
|
817
|
+
reloads,
|
|
818
|
+
configures,
|
|
819
|
+
/** The fields session summaries carry for a record (§12.7, §12.8). */
|
|
820
|
+
fields(record: SessionRecord, session: SessionSnapshot | undefined): Partial<SessionSummary> {
|
|
821
|
+
if (!enabled) return reloads || configures ? { conversation: support(record, session) } : {};
|
|
822
|
+
return {
|
|
823
|
+
conversation: support(record, session),
|
|
824
|
+
...(record.forkedFrom ? { forkedFrom: record.forkedFrom } : {}),
|
|
825
|
+
...(record.branches?.length ? { branches: record.branches.slice(-LISTED_BRANCHES).map(publicBranch) } : {}),
|
|
826
|
+
};
|
|
827
|
+
},
|
|
828
|
+
/** Whether `after` lies in history a rewind set aside: such a client must start over (attach reset). */
|
|
829
|
+
discarded(record: SessionRecord | undefined, after: number) {
|
|
830
|
+
return !!record?.branches?.some(branch => after >= branch.cut && after < branch.marker);
|
|
831
|
+
},
|
|
832
|
+
fork,
|
|
833
|
+
rewind,
|
|
834
|
+
reload,
|
|
835
|
+
resumeCommand,
|
|
836
|
+
configure,
|
|
837
|
+
configurePreview,
|
|
838
|
+
/** The requestId of a rewind whose commit is unfinished for this root: prompts and reopens wait for it. */
|
|
839
|
+
fenced: (root: string) => fences.get(root),
|
|
840
|
+
/** At start, before requests: finish or settle what a crash left (lifecycle.recover); a rewind left applied fences its root. */
|
|
841
|
+
async recover() {
|
|
842
|
+
const unfinished = await lifecycle.recover({ rewind: entry => commitRewind(entry as LifecycleEntry<RewindPlan, NativeBinding>), fork: entry => commitFork(entry as LifecycleEntry<ForkPlan, NativeBinding>), reload: entry => commitReload(entry as LifecycleEntry<ReloadPlan, { threadId: string }>), configure: entry => commitConfigure(entry as LifecycleEntry<ConfigurePlan, ConfigureNative>) },
|
|
843
|
+
(message, fields) => ctx.log.warn(message, fields));
|
|
844
|
+
for (const entry of unfinished) if (entry.operation === 'rewind') fences.set(entry.resource, entry.requestId);
|
|
845
|
+
},
|
|
846
|
+
lifecycle,
|
|
847
|
+
/** Retention cannot erase an unfinished fork or its completion witness owner. */
|
|
848
|
+
async retainsFork(root: string) {
|
|
849
|
+
for (const entry of await journal.list((_name, error) => { throw error; })) {
|
|
850
|
+
if (entry.operation !== 'fork' || entry.state !== 'applied') continue;
|
|
851
|
+
if (entry.resource === root) return true;
|
|
852
|
+
if (entry.plan.newSessionId === root && !await completed(entry)) return true;
|
|
853
|
+
}
|
|
854
|
+
return false;
|
|
855
|
+
},
|
|
856
|
+
};
|
|
857
|
+
}
|