@anhlp/alp-runtime 0.0.1-beta.3 → 0.0.1-beta.5
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/dist/acp-transport.js +5 -36
- package/dist/antigravity-transport.d.ts +17 -0
- package/dist/antigravity-transport.js +82 -58
- package/dist/assignment-results.d.ts +52 -0
- package/dist/assignment-results.js +169 -0
- package/dist/attachments.d.ts +84 -0
- package/dist/attachments.js +213 -0
- package/dist/board-domain.js +2 -2
- package/dist/board.d.ts +6 -0
- package/dist/board.js +7 -0
- package/dist/catalog.d.ts +13 -0
- package/dist/catalog.js +9 -1
- package/dist/claude-transport.d.ts +35 -0
- package/dist/claude-transport.js +152 -10
- package/dist/compact.d.ts +29 -0
- package/dist/compact.js +49 -0
- package/dist/configure.d.ts +44 -0
- package/dist/configure.js +64 -0
- package/dist/contracts.d.ts +185 -4
- package/dist/contracts.js +11 -0
- package/dist/conversation.d.ts +45 -0
- package/dist/conversation.js +62 -0
- package/dist/index.d.ts +15 -4
- package/dist/index.js +40 -3
- package/dist/input-limits.d.ts +25 -0
- package/dist/input-limits.js +48 -0
- package/dist/language.d.ts +8 -0
- package/dist/language.js +20 -0
- package/dist/mailbox.d.ts +2 -0
- package/dist/mailbox.js +3 -1
- package/dist/mcp-tools.d.ts +8 -0
- package/dist/mcp-tools.js +26 -0
- package/dist/model-catalog.d.ts +76 -0
- package/dist/model-catalog.js +193 -0
- package/dist/model-probes.d.ts +7 -0
- package/dist/model-probes.js +69 -0
- package/dist/providers.js +2 -0
- package/dist/resolve.d.ts +1 -0
- package/dist/resolve.js +3 -1
- package/dist/runtime.d.ts +9 -0
- package/dist/runtime.js +1547 -142
- package/dist/session-config.d.ts +279 -0
- package/dist/session-config.js +10 -10
- package/dist/session-state.d.ts +44 -6
- package/dist/tools.d.ts +119 -0
- package/dist/tools.js +72 -5
- package/dist/transport.js +3 -1
- package/dist/workspace.d.ts +11 -4
- package/dist/workspace.js +29 -11
- package/dist/worktree-domain.d.ts +2 -1
- package/dist/worktree-domain.js +4 -1
- package/package.json +11 -3
- package/src/acp-transport.ts +7 -37
- package/src/antigravity-transport.ts +95 -53
- package/src/assignment-results.ts +146 -0
- package/src/attachments.ts +254 -0
- package/src/board-domain.ts +2 -2
- package/src/board.ts +7 -0
- package/src/catalog.ts +10 -1
- package/src/claude-transport.ts +171 -11
- package/src/compact.ts +62 -0
- package/src/configure.ts +93 -0
- package/src/contracts.ts +172 -5
- package/src/conversation.ts +81 -0
- package/src/index.ts +15 -4
- package/src/input-limits.ts +65 -0
- package/src/language.ts +18 -0
- package/src/mailbox.ts +4 -1
- package/src/mcp-tools.ts +33 -0
- package/src/model-catalog.ts +166 -0
- package/src/model-probes.ts +58 -0
- package/src/providers.ts +3 -0
- package/src/resolve.ts +4 -2
- package/src/runtime.ts +1681 -151
- package/src/session-config.ts +9 -9
- package/src/session-state.ts +29 -2
- package/src/tools.ts +69 -5
- package/src/transport.ts +3 -1
- package/src/workspace.ts +42 -15
- package/src/worktree-domain.ts +5 -1
package/src/runtime.ts
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
|
+
import { createAssignmentResults, RESULT_OUTCOMES } from './assignment-results.js';
|
|
1
2
|
import { constants as fsConstants } from 'node:fs';
|
|
2
3
|
import type { Session, Assignment, Waiter } from './session-state.js';
|
|
3
4
|
import { errorData, plainObject, toolResult } from './tool-results.js';
|
|
5
|
+
import { inputLimitError, POUR_VARS, TOOL_INPUT, VAR_NAME } from './input-limits.js';
|
|
4
6
|
import { createLogger } from '@anhlp/alp-core/log';
|
|
5
7
|
import { PROMPT_IMAGES, base64Bytes } from '@anhlp/alp-protocol';
|
|
6
8
|
import { createBoardDomain } from './board-domain.js';
|
|
9
|
+
import { ATTACHMENT_ROUTES, STAGED_PATH, attachmentPart, createAttachmentStager, runtimeAttachment, stagingExposure, type AttachmentReader, type AttachmentRoute } from './attachments.js';
|
|
10
|
+
import type { RuntimeAttachment } from '@anhlp/alp-protocol/session';
|
|
7
11
|
import { createWorktreeDomain } from './worktree-domain.js';
|
|
8
|
-
import { type RuntimeTransport, type RuntimeOptions, type OpenOptions, type PromptContent, type PromptInput, type AlpRuntime, type SessionPreview, type RecoveryOutcome, type Pause, type PauseState, type RecallAnswer } from './contracts.js';
|
|
12
|
+
import { type RuntimeTransport, type RuntimeOptions, type OpenOptions, type PromptContent, type PromptInput, type AlpRuntime, type SessionPreview, type RecoveryOutcome, type Pause, type PauseState, type RecallAnswer, type ScheduleHandler, type BranchRequest, type NativeBinding, type ConfigurePreview, type ConfigureResult, type ConversationErrorReason, ConversationError } from './contracts.js';
|
|
13
|
+
import { claudeCut, codexForkEnd, codexForkRefusal, pendingChain, type ChainEntry } from './conversation.js';
|
|
9
14
|
export type { RuntimeTransport, RuntimeOptions, OpenOptions, PromptContent, PromptInput, AlpRuntime, SessionPreview, RecoveryOutcome, Pause, PauseState, RecallAnswer } from './contracts.js';
|
|
10
15
|
export { DEFAULT_TEAM } from './contracts.js';
|
|
11
16
|
import { verdictLine, parseHandoff, type Handoff } from './handoff.js';
|
|
@@ -24,13 +29,15 @@ import { discoverAgents } from '@anhlp/alp-core/resolver';
|
|
|
24
29
|
import { acpDecision, acpWhat, type AcpPermission } from './acp-transport.js';
|
|
25
30
|
|
|
26
31
|
import { models, modes, thinkingOptionsFor, withinMode, writes } from './catalog.js';
|
|
32
|
+
import { feedCatalog } from './model-catalog.js';
|
|
27
33
|
import { runHook } from '@anhlp/alp-core/hook-run';
|
|
28
34
|
import { hookMatches } from '@anhlp/alp-core/hooks';
|
|
29
35
|
import { isTrusted, trustProject } from '@anhlp/alp-core/trust';
|
|
30
|
-
import { listTeams } from '@anhlp/alp-core/teams';
|
|
36
|
+
import { listTeams, teamOf } from '@anhlp/alp-core/teams';
|
|
37
|
+
import { CONFIGURABLE, changesOf, effectiveOf, executablesOf, nativeModelOf, offered, type ConfigureChange, type ConfigureChanges, type EffectiveConfig } from './configure.js';
|
|
31
38
|
import { anyModel, offers, profileModel, selectedProfile } from '@anhlp/alp-core/profiles';
|
|
32
39
|
import { LESSONS_FILE, READ_ONLY_AGENTS, resolveSession, type ResolvedSession, type RuntimeKind, type SessionSpec } from './resolve.js';
|
|
33
|
-
import { MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER, type MailEvent } from './mailbox.js';
|
|
40
|
+
import { MAIL_BODY_CHARS, MAIL_HEADER, publicEvent, renderMail, takeBatch, USER, type MailEvent } from './mailbox.js';
|
|
34
41
|
import type { AlpEvent, AssignmentSnapshot, Envelope, SessionSnapshot, TurnOrigin, UserQuestion } from './events.js';
|
|
35
42
|
import { live, normalizePaths, overlapping, renderBoard, type Pin } from './board.js';
|
|
36
43
|
import { verifyConfig } from '@anhlp/alp-core/verify';
|
|
@@ -44,12 +51,49 @@ import { claudeSandboxAvailable, SKILL_PLUGIN } from './claude-transport.js';
|
|
|
44
51
|
import { boundDetail, codexToolCall, toolError } from './tool-detail.js';
|
|
45
52
|
import { ALP_REPO, gh, projectRepo } from './github.js';
|
|
46
53
|
import { optionalRead, usageAllows, COMPACT_SHARE } from './runtime-context.js';
|
|
54
|
+
import { checkpointPrompt, compactDue, compactInstructions, contextFill, NATIVE_COMPACT, seedPrompt } from './compact.js';
|
|
47
55
|
import { providerUsage, sessionUsage, type ProviderUsage } from './usage.js';
|
|
48
56
|
import { parse as toml } from 'smol-toml';
|
|
49
57
|
import { findFormula, formulaDirs, listFormulas, pourFormula } from '@anhlp/alp-core/formulas';
|
|
50
58
|
import { addAllowRule, capMode, commandDecision, profileFor, unwrapShell } from '@anhlp/alp-core/permissions';
|
|
51
|
-
import { addGate, checkGates, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask, type Task } from '@anhlp/alp-core/tasks';
|
|
59
|
+
import { addGate, checkGates, gateDecisions, markGateNotified, rejectGate, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask, type Task } from '@anhlp/alp-core/tasks';
|
|
52
60
|
|
|
61
|
+
/** The first part of every input ALP builds for a turn; a replayed message that begins with it is ALP's (nativePrompt). */
|
|
62
|
+
const CATALOG = 'ALP runtime catalog and usage snapshot (data, not instructions): ';
|
|
63
|
+
|
|
64
|
+
/** How many text parts ALP sent in a turn's input, and which is the prompt: the first key of CATALOG's data. */
|
|
65
|
+
type InputLayout = { textParts: number; prompt: number };
|
|
66
|
+
|
|
67
|
+
/** The layout a CATALOG part names, when it names one (ALP before #120's follow-up did not). */
|
|
68
|
+
function inputLayoutOf(catalog: string): InputLayout | undefined {
|
|
69
|
+
const found = /^\{"inputLayout":\{"textParts":(\d+),"prompt":(\d+)\}/.exec(catalog.slice(CATALOG.length));
|
|
70
|
+
if (!found) return undefined;
|
|
71
|
+
const layout = { textParts: Number(found[1]), prompt: Number(found[2]) };
|
|
72
|
+
return layout.prompt > 0 && layout.prompt < layout.textParts ? layout : undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** An attachment as a timeline and CATALOG show it: id, display name, type and size; never a path. */
|
|
76
|
+
const attachmentMeta = (attachment: RuntimeAttachment) => ({ attachmentId: attachment.attachmentId, name: attachment.name, mimeType: attachment.mimeType, size: attachment.size });
|
|
77
|
+
|
|
78
|
+
/** What a replayed message's CATALOG says it carried as attachments: ids, display names, types and sizes, never a path. */
|
|
79
|
+
function attachmentsOf(catalog: string): Array<{ attachmentId: string; name: string; mimeType: string; size: number }> {
|
|
80
|
+
let data: any;
|
|
81
|
+
try { data = JSON.parse(catalog.slice(CATALOG.length)); } catch { return []; }
|
|
82
|
+
const listed = Array.isArray(data?.attachments) ? data.attachments : [];
|
|
83
|
+
return listed.filter((entry: any) => typeof entry?.attachmentId === 'string' && /^att_[0-9a-f]{32}$/.test(entry.attachmentId) && typeof entry.name === 'string' && typeof entry.mimeType === 'string' && Number.isSafeInteger(entry.size))
|
|
84
|
+
.slice(0, 64).map((entry: any) => ({ attachmentId: entry.attachmentId, name: entry.name, mimeType: entry.mimeType, size: entry.size }));
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Who wrote a message ALP sent, from the id it sent it under: ALP's own ids are `alp-wake-`,
|
|
88
|
+
* `alp-mail-`, `alp-review-`, `alp-resume-`, `alp-recover-` and `task-`; any other id is a client's
|
|
89
|
+
* (the user's, or a job the user scheduled).
|
|
90
|
+
*/
|
|
91
|
+
function promptOrigin(clientMessageId: string, session: { parent?: string }): TurnOrigin {
|
|
92
|
+
if (/^alp-(wake|mail)-/.test(clientMessageId)) return 'wake';
|
|
93
|
+
if (/^(alp-review-|task-)/.test(clientMessageId)) return 'assignment';
|
|
94
|
+
if (/^alp-(resume|recover)-/.test(clientMessageId)) return session.parent ? 'assignment' : 'wake';
|
|
95
|
+
return 'user';
|
|
96
|
+
}
|
|
53
97
|
const MAX_WAKES = 8;
|
|
54
98
|
/** How long the user may wait for main's first words before its tool results remind it. */
|
|
55
99
|
const USER_REPLY_MS = 60_000;
|
|
@@ -75,21 +119,34 @@ const LIMIT_FRESH_MS = 15_000;
|
|
|
75
119
|
*/
|
|
76
120
|
const CONTEXT_SOON = 0.9;
|
|
77
121
|
const CONTEXT_RESET = 0.5;
|
|
122
|
+
/** After a failed compaction, how long the automatic one waits before it tries again (t-0e56). */
|
|
123
|
+
const COMPACT_RETRY_MS = 10 * 60_000;
|
|
124
|
+
const MAIL_WAITS = 'Mail waits for the session';
|
|
125
|
+
const REVIEWING = 'The supervisor is reviewing the session';
|
|
126
|
+
/** How long a runtime may take to report the compaction it was asked for (t-0e56). */
|
|
127
|
+
const COMPACT_NATIVE_MS = 5 * 60_000;
|
|
78
128
|
|
|
79
129
|
/** How much of an assignment's brief ALP repeats after a compaction. */
|
|
80
130
|
const BRIEF_CHARS = 8000;
|
|
131
|
+
/** How much of a writer's brief and of its handoff and output the result ledger keeps as evidence. */
|
|
132
|
+
const RESULT_EVIDENCE_CHARS = 2000;
|
|
133
|
+
const RESOLVE_NOTE_CHARS = 2000;
|
|
81
134
|
// Placeholder delivery marks while a steer or a woken turn is starting.
|
|
82
135
|
const STEERING = '\u0000steering';
|
|
83
136
|
const STARTING = '\u0000starting';
|
|
84
137
|
|
|
85
138
|
/** Answers that approve a proposal; anything else is feedback. */
|
|
86
139
|
const APPROVALS = ['approve', 'approved', 'yes', 'y', 'ok', 'đồng ý', 'duyệt', 'có'];
|
|
140
|
+
const CHOICES_REJECT = ['reject', 'từ chối'];
|
|
87
141
|
const SKILL_BODY_CHARS = 20_000;
|
|
88
142
|
const STARTER_ROLES = ['main', 'lead', 'peer', 'oracle', 'reviewer', 'supervisor'];
|
|
89
143
|
const ISSUE_BODY_CHARS = 20_000;
|
|
90
144
|
const ISSUE_FOOTER = '\n\n---\n_Drafted by an ALP agent and posted with the user\'s approval._';
|
|
91
145
|
|
|
92
146
|
const LESSON_CHARS = 600;
|
|
147
|
+
/** The monthly curate job's prompt starts with this marker, so main and ALP recognize it. */
|
|
148
|
+
export const CURATE_MARKER = '[alp-curate]';
|
|
149
|
+
const CURATE_PROMPT = `${CURATE_MARKER} Monthly review of lessons and skills. Use the curate skill: read every lesson and skill, then propose to the user, in one message, the merges, shortenings and removals of lessons, the skills no longer needed, and what ALP itself should adopt. Change nothing before the user approves. To turn this off, set curate.monthly to false in .alp/settings.json.`;
|
|
93
150
|
const DIGEST_CHARS = 12_000;
|
|
94
151
|
const JOURNAL_LINE_CHARS = 400;
|
|
95
152
|
/** Journal lines carry the local time, so the supervisor sees how long the user waited. */
|
|
@@ -119,8 +176,20 @@ const isolationOf = (args: { isolation?: string }) => args.isolation ?? 'shared'
|
|
|
119
176
|
|
|
120
177
|
const log = createLogger({ component: 'runtime' });
|
|
121
178
|
|
|
179
|
+
export type WorkspaceMutationReason = 'workspace_busy' | 'workspace_claimed' | 'workspace_leased' | 'workspace_assignment_result' | 'workspace_identity';
|
|
180
|
+
export class WorkspaceMutationError extends Error {
|
|
181
|
+
readonly data: { reason: WorkspaceMutationReason };
|
|
182
|
+
constructor(reason: WorkspaceMutationReason, message: string) {
|
|
183
|
+
super(message);
|
|
184
|
+
this.name = 'WorkspaceMutationError';
|
|
185
|
+
this.data = { reason };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
122
189
|
export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
123
190
|
const sessions = new Map<string, Session>();
|
|
191
|
+
/** Queue slots preparing a scheduled prompt, before its native turn/start. */
|
|
192
|
+
const admittedPrompts = new Set<string>();
|
|
124
193
|
/** What ALP writes for the user of a session, in their language (ALPD §54). */
|
|
125
194
|
const wordsFor = (session: Session) => words(session.mapping.language);
|
|
126
195
|
|
|
@@ -142,6 +211,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
142
211
|
const epoch = randomUUID();
|
|
143
212
|
/** Finished assignments whose native threads alp_recall can question. */
|
|
144
213
|
const recalls = createRecallBook(options.recallFile);
|
|
214
|
+
const assignmentResults = createAssignmentResults(options.assignmentResultFile);
|
|
145
215
|
/** Running assignments, so the next alpd continues them (ALPD §31). */
|
|
146
216
|
const inFlight = createLiveBook(options.liveFile);
|
|
147
217
|
/** Those an earlier alpd left running; recover() takes them once their root is open again. */
|
|
@@ -165,12 +235,37 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
165
235
|
const leases = new Map<string, { assignment: string; agent: string }>();
|
|
166
236
|
const worktreeRoot = options.worktreeDir ?? path.join(os.tmpdir(), 'alp-worktrees');
|
|
167
237
|
const copyRoot = options.copyDir ?? path.join(os.tmpdir(), 'alp-copies');
|
|
238
|
+
/** Non-image attachments (§12.6): staged copies when alpd gave a directory, read from alpd's reader once it binds one. */
|
|
239
|
+
const stager = options.attachmentStageDir ? createAttachmentStager(options.attachmentStageDir) : undefined;
|
|
240
|
+
let attachmentReader: AttachmentReader | undefined;
|
|
241
|
+
/** Sessions already warned that the staging directory is inside their workspace. */
|
|
242
|
+
const stagingWarned = new Set<string>();
|
|
243
|
+
if (stager) void stager.sweep();
|
|
168
244
|
const sequences = new Map<string, number>();
|
|
169
245
|
|
|
246
|
+
let workspaceMutation = false;
|
|
247
|
+
let admitting = 0;
|
|
248
|
+
const refuseMutation = (reason: WorkspaceMutationReason, message: string): never => { throw new WorkspaceMutationError(reason, message); };
|
|
249
|
+
/** Never exported: no caller of withWorkspaceMutation can skip the birth certificate but adoptWorkspace. */
|
|
250
|
+
const ADOPTION = Symbol('adoption');
|
|
251
|
+
// Admission registers synchronously, before resolving configuration or creating copies.
|
|
252
|
+
async function admission<T>(run: () => Promise<T>): Promise<T> {
|
|
253
|
+
if (workspaceMutation) refuseMutation('workspace_busy', 'A workspace mutation is in progress; retry after it finishes');
|
|
254
|
+
admitting++;
|
|
255
|
+
try { return await run(); } finally { admitting--; }
|
|
256
|
+
}
|
|
170
257
|
let closed = false;
|
|
171
258
|
let queue = Promise.resolve();
|
|
172
259
|
|
|
173
260
|
const emit = (sessionId: string, event: AlpEvent) => {
|
|
261
|
+
// The staging directory never reaches a timeline: a tool's command or output, or a reply, that names
|
|
262
|
+
// a staged copy shows it under STAGED_PATH (§12.6). Clients know attachments by id and name.
|
|
263
|
+
if (stager) {
|
|
264
|
+
const json = JSON.stringify(event);
|
|
265
|
+
const named = stager.spellings().map(root => JSON.stringify(root).slice(1, -1)).filter(root => json.includes(root));
|
|
266
|
+
// The directory itself, not a longer name that starts like it (`staged-old`, `staged.bak`); a period ending a sentence is not a name.
|
|
267
|
+
if (named.length) event = JSON.parse(named.reduce((text, root) => text.replace(new RegExp(`${root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![A-Za-z0-9_-]|\\.[A-Za-z0-9_-])`, 'g'), STAGED_PATH), json));
|
|
268
|
+
}
|
|
174
269
|
const seq = (sequences.get(sessionId) ?? 0) + 1;
|
|
175
270
|
sequences.set(sessionId, seq);
|
|
176
271
|
const envelope: Envelope = { sessionId, epoch, seq, ts: new Date().toISOString(), event };
|
|
@@ -192,6 +287,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
192
287
|
return session.runtime.takesImages ? session.runtime.takesImages() : session.runtimeKind === 'codex' || session.runtimeKind === 'claude';
|
|
193
288
|
}
|
|
194
289
|
|
|
290
|
+
/** How the session's runtime can use attached files (the capability matrix of §12.6); none without alpd's reader and a staging directory. */
|
|
291
|
+
function attachmentRoutes(session: Session): readonly AttachmentRoute[] {
|
|
292
|
+
return stager && attachmentReader ? ATTACHMENT_ROUTES[session.runtimeKind] ?? [] : [];
|
|
293
|
+
}
|
|
294
|
+
|
|
195
295
|
function snapshot(sessionId: string, session: Session): SessionSnapshot {
|
|
196
296
|
return {
|
|
197
297
|
id: sessionId,
|
|
@@ -212,6 +312,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
212
312
|
...((session.parked?.reason ?? session.parkReason) ? { parked: session.parked?.reason ?? session.parkReason } : {}),
|
|
213
313
|
...(session.instructionsSha ? { instructionsSha: session.instructionsSha } : {}),
|
|
214
314
|
...(takesImages(session) ? { promptImages: true } : {}),
|
|
315
|
+
...(attachmentRoutes(session).length ? { promptAttachments: [...attachmentRoutes(session)] } : {}),
|
|
215
316
|
...(session.usage ? { usage: session.usage } : {}),
|
|
216
317
|
busy: !!(session.active || session.pending || session.parked || session.parkReason || session.children.size || session.assignments.size || hasActiveMail(session) || reviewing(session)),
|
|
217
318
|
};
|
|
@@ -263,7 +364,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
263
364
|
}
|
|
264
365
|
session.userStopped = false;
|
|
265
366
|
if (session.role === 'supervisor' && session.parent && sessions.get(session.parent)?.reviewPending) review(session.parent);
|
|
367
|
+
if (session.role === 'supervisor' && session.parent) { const root = sessions.get(session.parent); if (root) queueMicrotask(() => compactAtBoundary(session.parent!, root)); }
|
|
266
368
|
if (!session.parent) void showTasks(sessionId, session);
|
|
369
|
+
if (!session.parent && session.role !== 'supervisor') queueMicrotask(() => compactAtBoundary(sessionId, session, state));
|
|
267
370
|
|
|
268
371
|
// An assignment a limit or a pause stopped waits, open, to continue instead of ending.
|
|
269
372
|
if (session.parkReason && state !== 'completed') {
|
|
@@ -271,6 +374,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
271
374
|
return;
|
|
272
375
|
}
|
|
273
376
|
session.parkReason = undefined;
|
|
377
|
+
session.parkPause = undefined;
|
|
274
378
|
|
|
275
379
|
// A requester is not done while its assignments run or mail awaits it.
|
|
276
380
|
if (state === 'completed' && (session.assignments.size || hasActiveMail(session))) {
|
|
@@ -281,6 +385,33 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
281
385
|
session.settle?.(state, error);
|
|
282
386
|
}
|
|
283
387
|
|
|
388
|
+
/**
|
|
389
|
+
* A native user message as ALP sent it: Codex keeps the clientUserMessageId ALP gave it as
|
|
390
|
+
* `clientId`, and the parts of the input startPrompt built (CATALOG first, then the task digest,
|
|
391
|
+
* an interrupted turn's words, the prompt, its images and mail). The message is the prompt part
|
|
392
|
+
* alone, and its origin comes from its id: ALP's own (mail, briefs, resumes) never title a root.
|
|
393
|
+
* A message ALP sent without an id (an older Codex) has no origin anyone can trust; one ALP did not
|
|
394
|
+
* build (a thread started outside ALP) is the user's.
|
|
395
|
+
*/
|
|
396
|
+
function nativePrompt(item: any, session: Session): { text: string; clientMessageId?: string; origin?: TurnOrigin; attachments?: ReturnType<typeof attachmentsOf> } {
|
|
397
|
+
const parts: string[] = (item.content ?? []).filter((c: any) => c.type === 'text').map((c: any) => String(c.text ?? ''));
|
|
398
|
+
const clientMessageId = typeof item.clientId === 'string' && item.clientId ? item.clientId : undefined;
|
|
399
|
+
// Mail steered into a running turn is sent alone, without CATALOG.
|
|
400
|
+
if (!parts[0]?.startsWith(CATALOG)) return { text: parts.join('\n'), ...(clientMessageId ? { clientMessageId } : {}), origin: clientMessageId ? promptOrigin(clientMessageId, session) : parts[0]?.startsWith(MAIL_HEADER) ? 'wake' : 'user' };
|
|
401
|
+
const origin = clientMessageId ? promptOrigin(clientMessageId, session) : undefined;
|
|
402
|
+
const ids = { ...(clientMessageId ? { clientMessageId } : {}), ...(origin ? { origin } : {}) };
|
|
403
|
+
const layout = inputLayoutOf(parts[0]);
|
|
404
|
+
const attached = attachmentsOf(parts[0]);
|
|
405
|
+
// The prompt where CATALOG says it is. Every other part ALP sends has words, so a part missing
|
|
406
|
+
// is an empty prompt (an image alone) the runtime left out: its text is none, never a neighbour's.
|
|
407
|
+
if (layout) return { text: parts.length === layout.textParts ? parts[layout.prompt] ?? '' : '', ...ids, ...(attached.length ? { attachments: attached } : {}) };
|
|
408
|
+
// A message from before CATALOG named its layout: read by what its parts begin with.
|
|
409
|
+
const rest = parts.slice(1);
|
|
410
|
+
// Mail delivered with a prompt follows it; a mail wake's prompt is mail itself, after the task digest.
|
|
411
|
+
if (!clientMessageId?.startsWith('alp-wake-') && rest.length > 1 && rest.at(-1)!.startsWith(MAIL_HEADER)) rest.pop();
|
|
412
|
+
return { text: rest.at(-1) ?? '', ...ids };
|
|
413
|
+
}
|
|
414
|
+
|
|
284
415
|
function nativeItem(
|
|
285
416
|
sessionId: string,
|
|
286
417
|
session: Session,
|
|
@@ -299,12 +430,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
299
430
|
}
|
|
300
431
|
|
|
301
432
|
if (item.type === 'userMessage') {
|
|
302
|
-
const text = (item
|
|
303
|
-
.filter((c: any) => c.type === 'text')
|
|
304
|
-
.map((c: any) => c.text)
|
|
305
|
-
.join('\n');
|
|
433
|
+
const { text, clientMessageId, origin, attachments } = nativePrompt(item, session);
|
|
306
434
|
const images = (item.content ?? []).filter((c: any) => c.type === 'image' || c.type === 'localImage').length;
|
|
307
|
-
emit(sessionId, { type: 'item', item: { kind: 'user_message', id: item.id, text, ...(images ? { images } : {}) } });
|
|
435
|
+
emit(sessionId, { type: 'item', item: { kind: 'user_message', id: item.id, text, ...(clientMessageId ? { clientMessageId } : {}), ...(origin ? { origin } : {}), ...(images ? { images } : {}), ...(attachments ? { attachments } : {}) } });
|
|
308
436
|
return;
|
|
309
437
|
}
|
|
310
438
|
|
|
@@ -390,6 +518,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
390
518
|
params: any,
|
|
391
519
|
) {
|
|
392
520
|
if (session.closed) return;
|
|
521
|
+
// What the runtime says it runs with; the run log keeps it beside the configured model (§12.9).
|
|
522
|
+
if (method === 'alp/nativeModel') {
|
|
523
|
+
if (typeof params?.model === 'string') runLog(rootOf(sessionId), { event: 'session.native_model', sessionId, agent: session.mapping.agent.name, configured: session.mapping.model, model: params.model.slice(0, 200) });
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
393
526
|
|
|
394
527
|
touch(sessionId, session);
|
|
395
528
|
|
|
@@ -468,7 +601,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
468
601
|
|
|
469
602
|
// A usage limit pauses its runtime; an assignment it stopped is parked to continue later.
|
|
470
603
|
if (state === 'failed' && LIMIT_ERRORS.includes(params.turn.error?.codexErrorInfo)) {
|
|
471
|
-
if (session.role !== 'supervisor')
|
|
604
|
+
if (session.role !== 'supervisor') {
|
|
605
|
+
session.parkReason = `the ${label(session.runtimeKind)} usage limit was reached`;
|
|
606
|
+
session.parkPause = { scope: paused.all ? 'all' : session.runtimeKind, ...(paused.all?.cause === 'disk' ? { disk: true } : {}) };
|
|
607
|
+
}
|
|
472
608
|
void limitReached(session, params.turn.error);
|
|
473
609
|
}
|
|
474
610
|
|
|
@@ -481,43 +617,69 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
481
617
|
}
|
|
482
618
|
}
|
|
483
619
|
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
620
|
+
// Failure callbacks and an opening call's catch can both retire the same record.
|
|
621
|
+
// Keep the cleanup with that incarnation, even after its id has been reused.
|
|
622
|
+
const sessionClosures = new WeakMap<Session, Promise<void>>();
|
|
623
|
+
const openedSessions = new WeakSet<Session>();
|
|
624
|
+
/**
|
|
625
|
+
* Sessions whose first open is still running, with the process failure that came meanwhile: the
|
|
626
|
+
* open fails with it and reports it once it stopped using the session, rather than a failure
|
|
627
|
+
* callback closing the session under it (failSession while openSession still runs).
|
|
628
|
+
*/
|
|
629
|
+
const openings = new WeakMap<Session, { failure?: unknown }>();
|
|
630
|
+
const assignmentSessions = new WeakMap<Assignment, Session>();
|
|
631
|
+
function closeSession(sessionId: string, session = sessions.get(sessionId), notify = true): Promise<void> {
|
|
632
|
+
if (!session) return Promise.resolve();
|
|
633
|
+
const closing = sessionClosures.get(session);
|
|
634
|
+
if (closing) return closing;
|
|
635
|
+
if (session.closed) return Promise.resolve();
|
|
487
636
|
|
|
488
637
|
session.closed = true;
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
// Copies of assignments that did not finish hold nothing to keep.
|
|
503
|
-
for (const assignment of session.assignments.values()) if (assignment.copy && !assignment.finished) await removeCopy(assignment.copy).catch(() => {});
|
|
504
|
-
|
|
505
|
-
for (const [assignmentId, { worktree }] of session.worktrees) {
|
|
506
|
-
await removeWorktree(worktree).catch(() => {});
|
|
507
|
-
runLog(rootOf(sessionId), { event: 'worktree.kept', assignmentId, branch: worktree.branch });
|
|
638
|
+
const current = sessions.get(sessionId) === session;
|
|
639
|
+
const opened = openedSessions.has(session);
|
|
640
|
+
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
641
|
+
const descendants = current ? [...session.children, ...(session.supervisor ? [session.supervisor] : [])]
|
|
642
|
+
.map(id => [id, sessions.get(id)] as const).filter((entry): entry is readonly [string, Session] => !!entry[1]) : [];
|
|
643
|
+
if (current) {
|
|
644
|
+
cancelQuestions(sessionId);
|
|
645
|
+
approvalLedger.delete(sessionId);
|
|
646
|
+
releaseClaims(sessionId, session.mapping.agent.projectRoot);
|
|
647
|
+
// terminal also touches questions and parent bookkeeping by id. Do it before
|
|
648
|
+
// yielding, while this is still the record registered under that id.
|
|
649
|
+
terminal(sessionId, session, 'canceled');
|
|
650
|
+
session.settle?.('canceled', 'Session closed');
|
|
508
651
|
}
|
|
509
|
-
session.worktrees.clear();
|
|
510
652
|
|
|
511
|
-
|
|
653
|
+
const cleanup = (async () => {
|
|
654
|
+
await Promise.all(
|
|
655
|
+
descendants.map(([id, child]) => closeSession(id, child)),
|
|
656
|
+
);
|
|
657
|
+
await session.runtime.close();
|
|
658
|
+
|
|
659
|
+
// Copies of assignments that did not finish hold nothing to keep.
|
|
660
|
+
for (const assignment of session.assignments.values()) if (assignment.copy && !assignment.finished) await removeCopy(assignment.copy).catch(() => {});
|
|
512
661
|
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
662
|
+
for (const [assignmentId, { worktree }] of session.worktrees) {
|
|
663
|
+
await removeWorktree(worktree).catch(() => {});
|
|
664
|
+
runLog(rootOf(sessionId), { event: 'worktree.kept', assignmentId, branch: worktree.branch });
|
|
665
|
+
}
|
|
666
|
+
session.worktrees.clear();
|
|
667
|
+
|
|
668
|
+
// Every id-based side effect belongs to this incarnation, including the
|
|
669
|
+
// parent's membership and the event that tells viewers it is no longer live.
|
|
670
|
+
if (sessions.get(sessionId) !== session) return;
|
|
671
|
+
sessions.delete(sessionId);
|
|
672
|
+
if (session.parent && parent && sessions.get(session.parent) === parent) {
|
|
673
|
+
parent.children.delete(sessionId);
|
|
674
|
+
if (parent.supervisor === sessionId) parent.supervisor = undefined;
|
|
675
|
+
}
|
|
518
676
|
|
|
519
|
-
|
|
520
|
-
|
|
677
|
+
// An opening failure has no live incarnation to close. Its failure callback
|
|
678
|
+
// reports session.failed; an ordinary startup rejection is the open error.
|
|
679
|
+
if (notify && opened) emit(sessionId, { type: 'session.closed' });
|
|
680
|
+
})();
|
|
681
|
+
sessionClosures.set(session, cleanup);
|
|
682
|
+
return cleanup;
|
|
521
683
|
}
|
|
522
684
|
|
|
523
685
|
let runLogWrites = Promise.resolve();
|
|
@@ -628,7 +790,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
628
790
|
const boards = new Map<string, Promise<Pin[]>>();
|
|
629
791
|
/** The same boards once loaded, for synchronous status. */
|
|
630
792
|
const loadedBoards = new Map<string, Pin[]>();
|
|
631
|
-
const userQuestions = new Map<string, { question: UserQuestion; persistent?: boolean; /** From alp_ask: the user's words in the chat end it (#116). */ asked?: boolean; settle: (outcome: 'answered' | 'dismissed' | 'timeout' | 'canceled', answer?: string, reason?: string, result?: unknown) => void }>();
|
|
793
|
+
const userQuestions = new Map<string, { question: UserQuestion; persistent?: boolean; /** From alp_ask: the user's words in the chat end it (#116). */ asked?: boolean; /** A card mirroring a human gate (t-ccac). */ gate?: { rev: number; deciding: boolean; decide: (reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }) => Promise<void> }; settle: (outcome: 'answered' | 'dismissed' | 'timeout' | 'canceled', answer?: string, reason?: string, result?: unknown) => void }>();
|
|
632
794
|
let mailSequence = 0;
|
|
633
795
|
let watchdog: NodeJS.Timeout | undefined;
|
|
634
796
|
|
|
@@ -942,10 +1104,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
942
1104
|
return toolResult(true, { tasks: rows.slice(0, limit).map(task => summarize(task, tasks)), ...(rows.length > limit ? { more: rows.length - limit } : {}), ...warnings });
|
|
943
1105
|
}
|
|
944
1106
|
const { action: _action, id, note, reason, summary, unverified, add, remove, ...input } = args;
|
|
945
|
-
if (action === 'pour' && (typeof input.formula !== 'string' || (input.vars !== undefined && (!input.vars || typeof input.vars !== 'object' || Array.isArray(input.vars) || !Object.
|
|
946
|
-
return toolResult(false, { error:
|
|
1107
|
+
if (action === 'pour' && (typeof input.formula !== 'string' || (input.vars !== undefined && (!input.vars || typeof input.vars !== 'object' || Array.isArray(input.vars) || inputLimitError(input.vars, POUR_VARS) || !Object.entries(input.vars).every(([name, value]) => VAR_NAME.test(name) && typeof value === 'string'))))) {
|
|
1108
|
+
return toolResult(false, { error: `pour needs formula, and vars as an object of text values: at most ${POUR_VARS.items}, named like formula variables, each at most ${POUR_VARS.string} characters` });
|
|
947
1109
|
}
|
|
948
|
-
const { kind, until, ref, gate, formula: _formula, vars: _vars, ...fields } = input;
|
|
1110
|
+
const { kind, until, ref, gate, options: gateChoices, formula: _formula, vars: _vars, ...fields } = input;
|
|
949
1111
|
if (action === 'clear') {
|
|
950
1112
|
const current = (await loadTasks(project)).tasks.find(candidate => candidate.id === id);
|
|
951
1113
|
if (current?.gates.find(entry => entry.id === gate)?.kind === 'human') return toolResult(false, { error: 'Only the user clears a human gate; ask them, and they approve it with alp task gate clear or in Paseo' });
|
|
@@ -953,6 +1115,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
953
1115
|
let poured: Awaited<ReturnType<typeof pourFormula>> | undefined;
|
|
954
1116
|
// A blocking task.close hook can refuse the close; its output is the reason.
|
|
955
1117
|
const hookedClose = async (id: string) => {
|
|
1118
|
+
// Refused before any hook runs: no agent closes around a human gate (t-f438); core checks again under the lock.
|
|
1119
|
+
const current = (await loadTasks(project)).tasks.find(candidate => candidate.id === id);
|
|
1120
|
+
if (current && (current.step?.human || current.gates.some(gate => gate.kind === 'human' && !gate.resolved))) throw new Error(`Only the user closes ${id}: it waits on the user's decision. Ask the user to decide it`);
|
|
956
1121
|
const refused = await runHooks(sessionId, session, 'task.close', { reason, ...(summary ? { summary } : {}) }, id);
|
|
957
1122
|
if (refused) throw new Error(`A task.close hook refused to close ${id}: ${refused}`);
|
|
958
1123
|
return closeTask(project, id, { reason, summary, unverified }, by);
|
|
@@ -961,13 +1126,14 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
961
1126
|
action === 'create' ? await createTask(project, fields as any, by)
|
|
962
1127
|
: action === 'update' ? await updateTask(project, id, { ...fields, note }, by)
|
|
963
1128
|
: action === 'pour' ? (poured = await pourFormula(project, (await findFormula(project, options.libraryDir, input.formula, { toml })).formula, input.vars, by, input.parent ? { parent: input.parent } : {})).epic
|
|
964
|
-
: action === 'gate' ? await addGate(project, id, { kind, note, until, ref }, by)
|
|
1129
|
+
: action === 'gate' ? await addGate(project, id, { kind, note, until, ref, ...(gateChoices !== undefined ? { options: gateChoices } : {}) }, by)
|
|
965
1130
|
: action === 'clear' ? await resolveGate(project, id, gate, { by, note })
|
|
966
1131
|
: action === 'link' ? await linkTask(project, id, { add, remove }, by)
|
|
967
1132
|
: action === 'start' ? await startTask(project, id, { agent: by, session: sessionId }, by)
|
|
968
1133
|
: action === 'close' ? await hookedClose(id)
|
|
969
1134
|
: await reopenTask(project, id, { note }, by);
|
|
970
1135
|
touchTask(rootOf(sessionId), task.id);
|
|
1136
|
+
if (action === 'gate' && kind === 'human') void syncGates(project);
|
|
971
1137
|
runLog(rootOf(sessionId), { event: 'task', action, agent: by, id: task.id, title: task.title, status: task.status, ...(summary ?? note ? { detail: summary ?? note } : {}) });
|
|
972
1138
|
const { tasks } = await loadTasks(project);
|
|
973
1139
|
const landed: Record<string, unknown> = {};
|
|
@@ -1077,6 +1243,49 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1077
1243
|
}
|
|
1078
1244
|
}
|
|
1079
1245
|
|
|
1246
|
+
/**
|
|
1247
|
+
* Records how the requester handled a finished writer's change in its checkout, then archives the
|
|
1248
|
+
* result: until then the removal guard keeps that checkout. Recall expiry never stands in for this.
|
|
1249
|
+
*/
|
|
1250
|
+
async function resolveTool(sessionId: string, session: Session, args: unknown) {
|
|
1251
|
+
if (!plainObject(args, ['assignmentId', 'outcome', 'note']) || typeof args.assignmentId !== 'string' || !RESULT_OUTCOMES.includes(args.outcome as any) ||
|
|
1252
|
+
(args.note !== undefined && (typeof args.note !== 'string' || args.note.length > RESOLVE_NOTE_CHARS))) {
|
|
1253
|
+
return toolResult(false, { error: `Pass assignmentId, outcome (${RESULT_OUTCOMES.join(', ')}), and optionally a note of at most ${RESOLVE_NOTE_CHARS} characters` });
|
|
1254
|
+
}
|
|
1255
|
+
const id = args.assignmentId;
|
|
1256
|
+
const outcome = args.outcome as typeof RESULT_OUTCOMES[number];
|
|
1257
|
+
const note = args.note as string | undefined;
|
|
1258
|
+
const live = [...sessions.values()];
|
|
1259
|
+
if (sessions.has(id) || live.some(other => other.assignments.has(id)) || inFlight.all().some(entry => entry.assignmentId === id) || inherited.some(entry => entry.assignmentId === id)) {
|
|
1260
|
+
return toolResult(false, { error: 'That assignment is still running or can still be recovered; wait for its result' });
|
|
1261
|
+
}
|
|
1262
|
+
if (live.some(other => other.worktrees.has(id))) return toolResult(false, { error: 'Its change waits in a worktree; apply it with alp_merge or drop it with alp_discard' });
|
|
1263
|
+
let ledger: Awaited<ReturnType<typeof assignmentResults.inspect>>;
|
|
1264
|
+
try { ledger = await assignmentResults.inspect(); } catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
1265
|
+
const entry = ledger.results.find(owner => owner.assignmentId === id && !owner.handled);
|
|
1266
|
+
const project = session.mapping.agent.projectRoot;
|
|
1267
|
+
const overlapping = async (a: string, b: string) => {
|
|
1268
|
+
const [x, y] = [await realpath(a).catch(() => a), await realpath(b).catch(() => b)];
|
|
1269
|
+
const within = (parent: string, child: string) => { const relative = path.relative(parent, child); return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); };
|
|
1270
|
+
return within(x, y) || within(y, x);
|
|
1271
|
+
};
|
|
1272
|
+
// Its requesters may resolve it, and so may a root of its project, so a closed requester never leaves it held for good.
|
|
1273
|
+
// An entry from before evidence was kept names only its checkout: a root working there may resolve it.
|
|
1274
|
+
const allowed = !!entry && (entry.result
|
|
1275
|
+
? entry.result.requesters.includes(sessionId) || (!session.parent && await sameDirectory(entry.result.project, project))
|
|
1276
|
+
: !session.parent && await overlapping(entry.checkout, project));
|
|
1277
|
+
if (!entry || !allowed) return toolResult(false, { error: `No unresolved assignment result ${id} of yours` });
|
|
1278
|
+
// A worktree still on disk holds work only a merge or discard may settle.
|
|
1279
|
+
if (entry.worktree && await stat(entry.worktree).then(() => true, () => false)) return toolResult(false, { error: `Its worktree ${entry.worktree} still exists; merge or remove it first` });
|
|
1280
|
+
try {
|
|
1281
|
+
const archived = await assignmentResults.resolve(id, { outcome, by: `${session.mapping.agent.name} in ${sessionId}`, at: new Date().toISOString(), ...(note ? { note } : {}) });
|
|
1282
|
+
runLog(rootOf(sessionId), { event: 'result.resolved', assignmentId: id, agent: session.mapping.agent.name, outcome, ...(note ? { note: clip(note, 500) } : {}) });
|
|
1283
|
+
return toolResult(true, { resolved: id, outcome, archivedAt: archived.archivedAt });
|
|
1284
|
+
} catch (error) {
|
|
1285
|
+
return toolResult(false, { assignmentId: id, error: errorData(error).message });
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1080
1289
|
let forgetting = Promise.resolve();
|
|
1081
1290
|
|
|
1082
1291
|
/** Deletes the native threads of assignments past their recall time, one transport per runtime. */
|
|
@@ -1101,7 +1310,28 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1101
1310
|
const label = (kind: RuntimeKind) => kind === 'claude' ? 'Claude' : kind === 'acp' ? 'ACP agent' : kind === 'antigravity' ? 'Antigravity' : 'Codex';
|
|
1102
1311
|
const pauseOf = (kind: RuntimeKind) => paused.all ?? paused.runtimes[kind];
|
|
1103
1312
|
/** Whether a session may not start a turn by itself now: parked, or on a paused runtime. */
|
|
1104
|
-
const held = (session: Session) => !!session.parked || !!pauseOf(session.runtimeKind);
|
|
1313
|
+
const held = (session: Session) => !!session.parked || !!pauseOf(session.runtimeKind) || (session.lifecycleHolds ?? 0) > 0;
|
|
1314
|
+
/** Whether mail may not wake a session now: it is held, or it is a new assignment whose brief has not started. */
|
|
1315
|
+
// Mail waits while main compacts (t-0e56), so it never lands in the checkpoint or the compaction.
|
|
1316
|
+
const holdsWake = (session: Session) => held(session) || !!session.awaitingBrief || !!session.compacting;
|
|
1317
|
+
|
|
1318
|
+
/**
|
|
1319
|
+
* Marks a session pending (its native process restarting) with a fresh `acknowledged` that resolves
|
|
1320
|
+
* when the returned function clears it. Mail delivered meanwhile waits on that promise; with the old,
|
|
1321
|
+
* already resolved one it would retry in a microtask loop and stall the process.
|
|
1322
|
+
*/
|
|
1323
|
+
function beginPending(session: Session) {
|
|
1324
|
+
let done!: () => void;
|
|
1325
|
+
session.pending = true;
|
|
1326
|
+
session.acknowledged = new Promise<void>(resolve => { done = resolve; });
|
|
1327
|
+
let cleared = false;
|
|
1328
|
+
return () => {
|
|
1329
|
+
if (cleared) return;
|
|
1330
|
+
cleared = true;
|
|
1331
|
+
session.pending = false;
|
|
1332
|
+
done();
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1105
1335
|
const describePause = (pause: Pause, kind?: RuntimeKind) =>
|
|
1106
1336
|
`${kind ? label(kind) : 'ALP'} is paused (${pause.reason}${pause.by !== 'alpd' ? `, by ${pause.by}` : ''})${pause.resetsAt ? `; the limit resets ${pause.resetsAt}` : ''}`;
|
|
1107
1337
|
|
|
@@ -1220,34 +1450,46 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1220
1450
|
if (now) {
|
|
1221
1451
|
for (const [id, session] of sessions) {
|
|
1222
1452
|
if (!session.parent || session.closed || !session.active || session.role === 'supervisor' || (scope !== 'all' && session.runtimeKind !== scope)) continue;
|
|
1223
|
-
|
|
1453
|
+
// A process restart already owns its continuation; this pause must not replace its cause.
|
|
1454
|
+
if (session.parkReason && !session.parkPause) continue;
|
|
1455
|
+
session.parkReason = pause.cause === 'disk' ? pause.reason : `paused by ${pause.by}`;
|
|
1456
|
+
session.parkPause = { scope, ...(pause.cause === 'disk' ? { disk: true } : {}) };
|
|
1224
1457
|
void session.runtime.request('turn/interrupt', { threadId: session.threadId, turnId: session.active }).catch(() => {});
|
|
1225
1458
|
runLog(rootOf(id), { event: 'assignment.parking', assignmentId: id, agent: session.mapping.agent.name, reason: session.parkReason });
|
|
1226
1459
|
}
|
|
1227
1460
|
}
|
|
1228
1461
|
}
|
|
1229
1462
|
|
|
1230
|
-
function resumeRuntime(scope: RuntimeKind | 'all', by: string) {
|
|
1231
|
-
|
|
1463
|
+
function resumeRuntime(scope: RuntimeKind | 'all', by: string, keepRuntimes = false) {
|
|
1464
|
+
// Lifting alpd's disk pause keeps the usage-limit pauses of single runtimes.
|
|
1465
|
+
if (scope === 'all') paused = keepRuntimes ? { runtimes: paused.runtimes } : { runtimes: {} };
|
|
1232
1466
|
else delete paused.runtimes[scope];
|
|
1233
1467
|
savePauses();
|
|
1234
1468
|
watchLimits();
|
|
1469
|
+
const matches = (pause: Session['parkPause']) => pause && (scope === 'all' || pause.scope === scope);
|
|
1470
|
+
const continuing = [...sessions.values()].some(session => !session.closed && !pauseOf(session.runtimeKind) && matches(session.parked?.pause));
|
|
1235
1471
|
const free = RUNTIMES.filter(kind => !pauseOf(kind));
|
|
1236
|
-
if (free.length) notice('info', say => say.resumed(scope === 'all' ? 'ALP' : label(scope), by,
|
|
1472
|
+
if (free.length) notice('info', say => say.resumed(scope === 'all' ? 'ALP' : label(scope), by, continuing));
|
|
1237
1473
|
for (const [id, session] of sessions) {
|
|
1238
|
-
if (session.closed ||
|
|
1239
|
-
if (session.
|
|
1240
|
-
|
|
1474
|
+
if (session.closed || (scope !== 'all' && session.runtimeKind !== scope)) continue;
|
|
1475
|
+
if (matches(session.parkPause)) session.parkPause!.resumed = true;
|
|
1476
|
+
if (pauseOf(session.runtimeKind)) continue;
|
|
1477
|
+
if (session.parked) {
|
|
1478
|
+
if (matches(session.parked.pause)) continueParked(id, session);
|
|
1479
|
+
} else if (session.wakeHeld) { session.wakeHeld = false; deliver(id, session); }
|
|
1241
1480
|
}
|
|
1242
1481
|
}
|
|
1243
1482
|
|
|
1244
1483
|
/** An assignment whose turn a limit or a pause ended stays open, and its requester learns why. */
|
|
1245
1484
|
function park(sessionId: string, session: Session) {
|
|
1246
|
-
session.parked = { reason: session.parkReason!, since: Date.now() };
|
|
1485
|
+
session.parked = { reason: session.parkReason!, since: Date.now(), ...(session.parkPause ? { pause: session.parkPause } : {}) };
|
|
1486
|
+
const resumed = session.parkPause?.resumed;
|
|
1487
|
+
session.parkPause = undefined;
|
|
1247
1488
|
const then = session.parkThen;
|
|
1248
1489
|
session.parkReason = undefined;
|
|
1249
1490
|
session.parkThen = undefined;
|
|
1250
1491
|
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
1492
|
+
if (resumed) continueParked(sessionId, session);
|
|
1251
1493
|
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
1252
1494
|
const assignment = parent?.assignments.get(sessionId);
|
|
1253
1495
|
runLog(rootOf(sessionId), { event: 'assignment.parked', assignmentId: sessionId, agent: session.mapping.agent.name, reason: session.parked.reason });
|
|
@@ -1255,12 +1497,22 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1255
1497
|
emit(session.parent!, { type: 'assignment', assignment: assignmentSnapshot(assignment, 'parked') });
|
|
1256
1498
|
// One that continues by itself is information; one held until the user resumes needs the requester's decision, so it wakes it.
|
|
1257
1499
|
if (then) post(session.parent!, { kind: 'note', from: assignment.agent, assignment: sessionId, passive: true, body: `Parked: ${session.parked.reason}. ${then} Wait for it, or start other work.` });
|
|
1500
|
+
else if (session.parked.pause?.disk) post(session.parent!, { kind: 'stalled', from: assignment.agent, assignment: sessionId, body: `Parked: ${session.parked.reason}. ALP continues this assignment where it stopped as soon as the disk takes writes again (alpd checks every minute), or when the user frees space and runs alp resume. Wait for it, or tell the user the disk is full; what it changed stays in your checkout or its worktree.` });
|
|
1258
1501
|
else post(session.parent!, { kind: 'stalled', from: assignment.agent, assignment: sessionId, body: `Parked: ${session.parked.reason}. ALP continues this assignment where it stopped when ${label(session.runtimeKind)} is resumed (${options.autoResume !== false && (pauseOf(session.runtimeKind)?.by ?? 'alpd') === 'alpd' ? `ALP resumes it as soon as ${label(session.runtimeKind)} says the limit lifted` : 'the user runs alp resume'}). Wait for it, start other work, or stop it with alp_cancel and give the rest to an agent on another runtime (pass model claude:… or codex:…); what it changed stays in your checkout or its worktree.` });
|
|
1259
1502
|
}
|
|
1260
1503
|
|
|
1261
|
-
function continueParked(sessionId: string, session: Session) {
|
|
1504
|
+
function continueParked(sessionId: string, session: Session, expected = session.parked) {
|
|
1262
1505
|
void enqueue(async () => {
|
|
1263
|
-
if (session.closed || session.active || session.pending || !session.parked ||
|
|
1506
|
+
if (session.closed || session.active || session.pending || !session.parked || session.parked !== expected) return;
|
|
1507
|
+
// This continuation owns only the captured park. A pause may have arrived while
|
|
1508
|
+
// it waited in the queue; retain the actual blocker for a matching later resume.
|
|
1509
|
+
if (pauseOf(session.runtimeKind)) {
|
|
1510
|
+
session.parked.pause = { scope: paused.all ? 'all' : session.runtimeKind };
|
|
1511
|
+
return;
|
|
1512
|
+
}
|
|
1513
|
+
// A lifecycle operation (a fork or rewind reading the conversation) holds the session: the work stays
|
|
1514
|
+
// parked and continues when the last hold releases, as held mail does.
|
|
1515
|
+
if (session.lifecycleHolds) { session.resumeHeld = session.parked; return; }
|
|
1264
1516
|
const parked = session.parked;
|
|
1265
1517
|
const { reason, prompt } = parked;
|
|
1266
1518
|
session.parked = undefined;
|
|
@@ -1329,6 +1581,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1329
1581
|
const used = usage?.last?.totalTokens;
|
|
1330
1582
|
const window = usage?.modelContextWindow;
|
|
1331
1583
|
if (session.role === 'supervisor' || typeof used !== 'number' || typeof window !== 'number' || window <= 0) return;
|
|
1584
|
+
// Against the window main works in, as the advisory measures it; not from the old context right after a compaction.
|
|
1585
|
+
if (!session.compactCooling) session.contextFill = contextFill({ ...usage, modelContextWindow: Math.min(typeof session.mapping.autocompact === 'number' ? session.mapping.autocompact : typeof session.mapping.context === 'number' ? session.mapping.context : window, window) });
|
|
1332
1586
|
const compactAt = typeof usage.autoCompactTokens === 'number' && usage.autoCompactTokens > 0
|
|
1333
1587
|
? usage.autoCompactTokens
|
|
1334
1588
|
: session.runtimeKind === 'codex' && session.mapping.autocompact
|
|
@@ -1381,14 +1635,169 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1381
1635
|
if (!done) return;
|
|
1382
1636
|
const agent = session.mapping.agent.name;
|
|
1383
1637
|
runLog(rootOf(sessionId), { event: 'compacted', sessionId, agent, ...trigger, ...tokens, ...(failed ? { failed: true, ...(item.error ? { error: String(item.error) } : {}) } : {}) });
|
|
1384
|
-
if (failed) return;
|
|
1638
|
+
if (failed) { if (session.compacting?.phase === 'native') compactFailed(sessionId, session, item.error ? String(item.error) : 'the runtime could not compact'); return; }
|
|
1385
1639
|
session.contextLevel = 0;
|
|
1386
1640
|
if (session.supervisor) session.journal.push(stamp(`${agent}'s context was compacted`));
|
|
1387
|
-
|
|
1641
|
+
const checkpoint = session.compacting?.phase === 'native' ? session.compacting.checkpoint : undefined;
|
|
1642
|
+
if (session.role !== 'supervisor') void restoreAfterCompaction(sessionId, session, checkpoint).catch(() => {});
|
|
1643
|
+
if (checkpoint !== undefined) compactFinished(sessionId, session, 'native');
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
/**
|
|
1647
|
+
* Whether a root holds anything a compaction must not cut into (t-0e56): a turn, a restart,
|
|
1648
|
+
* a question to the user or a park. Before one starts, also mail that would wake it. The
|
|
1649
|
+
* supervisor's review does not hold it: its mail waits for the compaction's end like any other.
|
|
1650
|
+
*/
|
|
1651
|
+
function compactHeld(sessionId: string, session: Session, starting: boolean) {
|
|
1652
|
+
return session.closed || !!session.active || !!session.pending || session.waiters.length > 0
|
|
1653
|
+
|| !!session.parked || !!session.parkReason
|
|
1654
|
+
|| (starting && (hasActiveMail(session) || !!session.wakeHeld))
|
|
1655
|
+
|| [...userQuestions.values()].some(pending => pending.question.rootId === sessionId && !pending.gate);
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
/**
|
|
1659
|
+
* Main's compaction (t-0e56). Once its context fills to the threshold, or the user asked,
|
|
1660
|
+
* main writes a checkpoint by skill compact in a turn of its own; after that turn the
|
|
1661
|
+
* runtime compacts natively, or ALP starts a fresh conversation seeded with it. It starts
|
|
1662
|
+
* only at a turn boundary (`ended`, the state of the turn that just ended); without one it
|
|
1663
|
+
* is a retry, after a hold such as the supervisor's review or held mail clears.
|
|
1664
|
+
*/
|
|
1665
|
+
function compactAtBoundary(sessionId: string, session: Session, ended?: 'completed' | 'failed' | 'canceled') {
|
|
1666
|
+
if (session.closed || sessions.get(sessionId) !== session) return;
|
|
1667
|
+
const current = session.compacting;
|
|
1668
|
+
if (ended && current?.phase === 'checkpoint' && current.checkpoint === undefined && current.turn) {
|
|
1669
|
+
// The checkpoint turn just ended: its last words are the checkpoint.
|
|
1670
|
+
const written = [...session.text.values()].at(-1)?.trim();
|
|
1671
|
+
if (ended !== 'completed' || !written) { compactFailed(sessionId, session, ended !== 'completed' ? `the checkpoint turn ${ended}` : 'main wrote no checkpoint'); return; }
|
|
1672
|
+
current.checkpoint = written;
|
|
1673
|
+
// A hold that outlasts this (a question, a park) fails it, so the user's held words go on.
|
|
1674
|
+
const timer = setTimeout(() => { if (session.compacting === current && current.phase === 'checkpoint') compactFailed(sessionId, session, 'main stayed busy after its checkpoint'); }, COMPACT_NATIVE_MS);
|
|
1675
|
+
timer.unref?.();
|
|
1676
|
+
}
|
|
1677
|
+
// The compaction turn ended without the runtime reporting a compaction.
|
|
1678
|
+
if (ended && current?.phase === 'native' && current.requested) { compactFailed(sessionId, session, 'the runtime reported no compaction'); return; }
|
|
1679
|
+
if (current) {
|
|
1680
|
+
if (current.checkpoint !== undefined && current.phase === 'checkpoint' && !compactHeld(sessionId, session, false)) void compactNow(sessionId, session);
|
|
1681
|
+
return;
|
|
1682
|
+
}
|
|
1683
|
+
if (compactHeld(sessionId, session, true)) return;
|
|
1684
|
+
if (session.compactBuffer?.length) { flushCompactBuffer(sessionId, session); return; }
|
|
1685
|
+
const trigger = compactDue(session.mapping.compact ?? { auto: false, threshold: 1 }, session.contextFill, !!session.compactRequested);
|
|
1686
|
+
if (!trigger) return;
|
|
1687
|
+
if (trigger === 'auto' && session.compactFailedAt && Date.now() - session.compactFailedAt < COMPACT_RETRY_MS) return;
|
|
1688
|
+
session.compactRequested = false;
|
|
1689
|
+
const compacting: NonNullable<Session['compacting']> = { phase: 'checkpoint', trigger, startedAt: Date.now() };
|
|
1690
|
+
session.compacting = compacting;
|
|
1691
|
+
runLog(rootOf(sessionId), { event: 'compact.started', sessionId, agent: session.mapping.agent.name, trigger, ...(session.contextFill !== undefined ? { fill: Math.round(session.contextFill * 100) / 100 } : {}) });
|
|
1692
|
+
const work = queue.then(async () => {
|
|
1693
|
+
if (session.compacting !== compacting) return;
|
|
1694
|
+
if (session.closed || compactHeld(sessionId, session, true)) {
|
|
1695
|
+
session.compacting = undefined;
|
|
1696
|
+
if (trigger === 'manual') session.compactRequested = true;
|
|
1697
|
+
compactReleased(sessionId, session);
|
|
1698
|
+
return;
|
|
1699
|
+
}
|
|
1700
|
+
compacting.turn = true;
|
|
1701
|
+
await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: checkpointPrompt(trigger, session.contextFill) }] }, 'wake');
|
|
1702
|
+
}).catch(error => compactFailed(sessionId, session, errorData(error).message));
|
|
1703
|
+
queue = work.catch(() => {});
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
/** Compacts with the runtime's own mechanism, else a fresh conversation seeded with the checkpoint. */
|
|
1707
|
+
async function compactNow(sessionId: string, session: Session) {
|
|
1708
|
+
const current = session.compacting!;
|
|
1709
|
+
const checkpoint = current.checkpoint!;
|
|
1710
|
+
if (NATIVE_COMPACT.includes(session.runtimeKind)) {
|
|
1711
|
+
current.phase = 'native';
|
|
1712
|
+
try {
|
|
1713
|
+
// Codex takes the thread alone; its summary gets the checkpoint back from the note ALP sends after.
|
|
1714
|
+
await session.runtime.request('thread/compact/start', { threadId: session.threadId, ...(session.runtimeKind === 'codex' ? {} : { instructions: compactInstructions(checkpoint) }) });
|
|
1715
|
+
if (session.compacting !== current) return;
|
|
1716
|
+
current.requested = true;
|
|
1717
|
+
// A runtime that took the request but never reports a compaction does not hold main for good.
|
|
1718
|
+
const timer = setTimeout(() => { if (session.compacting === current) compactFailed(sessionId, session, 'the runtime reported no compaction in time'); }, COMPACT_NATIVE_MS);
|
|
1719
|
+
timer.unref?.();
|
|
1720
|
+
return;
|
|
1721
|
+
} catch (error) {
|
|
1722
|
+
if (session.compacting !== current) return;
|
|
1723
|
+
runLog(rootOf(sessionId), { event: 'compact.native_failed', sessionId, agent: session.mapping.agent.name, error: errorData(error).message });
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
current.phase = 'fresh';
|
|
1727
|
+
const work = queue.then(async () => {
|
|
1728
|
+
if (session.compacting !== current || session.closed) return;
|
|
1729
|
+
// A fresh conversation drops the old one: only when nothing runs that it would lose.
|
|
1730
|
+
// Held mail is no reason to wait: it reaches the new conversation after the seed; nor is the
|
|
1731
|
+
// supervisor's review, which reads main's journal, not its native conversation.
|
|
1732
|
+
const refusal = restartRefusal(sessionId, session);
|
|
1733
|
+
if (refusal && refusal !== MAIL_WAITS && refusal !== REVIEWING) { compactFailed(sessionId, session, `a fresh conversation cannot start now: ${refusal}`); return; }
|
|
1734
|
+
await restartNative(sessionId, session, undefined);
|
|
1735
|
+
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
1736
|
+
await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: seedPrompt(checkpoint, session.lastUserText) }] }, 'wake');
|
|
1737
|
+
compactFinished(sessionId, session, 'fresh');
|
|
1738
|
+
}).catch(error => compactFailed(sessionId, session, errorData(error).message));
|
|
1739
|
+
queue = work.catch(() => {});
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
function compactFinished(sessionId: string, session: Session, via: 'native' | 'fresh') {
|
|
1743
|
+
const current = session.compacting;
|
|
1744
|
+
if (!current) return;
|
|
1745
|
+
session.compacting = undefined;
|
|
1746
|
+
session.compactFailedAt = undefined;
|
|
1747
|
+
// Usage reported until main's next turn may still count the old context.
|
|
1748
|
+
session.contextFill = undefined;
|
|
1749
|
+
session.compactCooling = true;
|
|
1750
|
+
runLog(rootOf(sessionId), { event: 'compact', sessionId, agent: session.mapping.agent.name, trigger: current.trigger, via, checkpointChars: current.checkpoint?.length ?? 0, ms: Date.now() - current.startedAt });
|
|
1751
|
+
const text = wordsFor(session).compacted(via === 'native');
|
|
1752
|
+
emit(sessionId, { type: 'item', item: { kind: 'notice', id: `notice-${randomUUID().slice(0, 8)}`, level: 'info', text } });
|
|
1753
|
+
compactReleased(sessionId, session);
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
function compactFailed(sessionId: string, session: Session, reason: string) {
|
|
1757
|
+
const current = session.compacting;
|
|
1758
|
+
session.compacting = undefined;
|
|
1759
|
+
session.compactFailedAt = Date.now();
|
|
1760
|
+
runLog(rootOf(sessionId), { event: 'compact.failed', sessionId, agent: session.mapping.agent.name, ...(current ? { trigger: current.trigger } : {}), error: reason });
|
|
1761
|
+
if (!session.closed) emit(sessionId, { type: 'item', item: { kind: 'notice', id: `notice-${randomUUID().slice(0, 8)}`, level: 'warning', text: wordsFor(session).compactFailed(reason) } });
|
|
1762
|
+
compactReleased(sessionId, session);
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
/** A compaction ended or never started: the user's held words and held mail go on (t-0e56). */
|
|
1766
|
+
function compactReleased(sessionId: string, session: Session) {
|
|
1767
|
+
queueMicrotask(() => {
|
|
1768
|
+
if (session.closed || session.compacting) return;
|
|
1769
|
+
flushCompactBuffer(sessionId, session);
|
|
1770
|
+
if (session.wakeHeld && !holdsWake(session)) { session.wakeHeld = false; deliver(sessionId, session); }
|
|
1771
|
+
});
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
/** Sends the user's words held during a compaction, in order, once no turn runs (t-0e56). */
|
|
1775
|
+
function flushCompactBuffer(sessionId: string, session: Session) {
|
|
1776
|
+
if (session.compacting || session.active || !session.compactBuffer?.length) return;
|
|
1777
|
+
const held = session.compactBuffer.splice(0);
|
|
1778
|
+
session.compactBuffer = undefined;
|
|
1779
|
+
const work = queue.then(async () => {
|
|
1780
|
+
for (const [index, input] of held.entries()) {
|
|
1781
|
+
await promptSession(sessionId, { ...input, delivery: index === 0 && !session.active ? 'auto' : 'steer' }, true);
|
|
1782
|
+
}
|
|
1783
|
+
});
|
|
1784
|
+
queue = work.catch(() => {});
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
/** The user's request to compact a root (t-0e56): now if it is idle, else at its next turn boundary. */
|
|
1788
|
+
function requestCompact(sessionId: string) {
|
|
1789
|
+
const session = sessions.get(sessionId);
|
|
1790
|
+
if (!session || session.closed) throw new ConversationError('session_busy', 'The session is not open');
|
|
1791
|
+
if (session.parent || session.role === 'supervisor') throw new ConversationError('runtime_unsupported', 'Only a root session is compacted');
|
|
1792
|
+
if (session.compacting) return { status: 'running' as const };
|
|
1793
|
+
session.compactRequested = true;
|
|
1794
|
+
if (compactHeld(sessionId, session, true)) return { status: 'deferred' as const };
|
|
1795
|
+
compactAtBoundary(sessionId, session);
|
|
1796
|
+
return { status: 'started' as const };
|
|
1388
1797
|
}
|
|
1389
1798
|
|
|
1390
1799
|
/** What ALP holds of a session's work, told to it after a compaction (ALPD §57). */
|
|
1391
|
-
async function restoreAfterCompaction(sessionId: string, session: Session) {
|
|
1800
|
+
async function restoreAfterCompaction(sessionId: string, session: Session, checkpoint?: string) {
|
|
1392
1801
|
const parts = ['Your context was just compacted. In case the summary lost any of it, this is what ALP holds of your work now.'];
|
|
1393
1802
|
if (session.parent && session.brief) parts.push(`Your assignment from ${session.parentAgent ?? 'your requester'}, as it was given:\n${cut(session.brief, BRIEF_CHARS)}`);
|
|
1394
1803
|
const running = [...session.assignments.values()].filter(assignment => !assignment.finished);
|
|
@@ -1399,7 +1808,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1399
1808
|
if (session.worktrees.size) {
|
|
1400
1809
|
parts.push('Finished worktree changes waiting for alp_merge or alp_discard:\n' + [...session.worktrees].map(([id, change]) => `- ${id}: ${change.agent}${change.taskId ? ` on ${change.taskId}` : ''}`).join('\n'));
|
|
1401
1810
|
}
|
|
1402
|
-
const asked = [...userQuestions.values()].filter(pending => pending.question.sessionId === sessionId);
|
|
1811
|
+
const asked = [...userQuestions.values()].filter(pending => pending.question.sessionId === sessionId && !pending.gate);
|
|
1403
1812
|
if (asked.length) parts.push('Waiting for the user to answer:\n' + asked.map(pending => `- ${clip(pending.question.body, 300)}`).join('\n'));
|
|
1404
1813
|
if (!session.parent) {
|
|
1405
1814
|
const project = session.mapping.agent.projectRoot;
|
|
@@ -1408,6 +1817,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1408
1817
|
const board = renderBoard(await boardOf(project));
|
|
1409
1818
|
if (board) parts.push(board);
|
|
1410
1819
|
}
|
|
1820
|
+
if (checkpoint) parts.push(`The checkpoint you wrote before the compaction, by skill compact:\n${cut(checkpoint, BRIEF_CHARS)}`);
|
|
1411
1821
|
parts.push('Carry on where you were; alp_board and alp_task tell you more.');
|
|
1412
1822
|
if (session.closed) return;
|
|
1413
1823
|
post(sessionId, { kind: 'note', from: 'alp', assignment: sessionId, body: parts.join('\n\n'), ...(session.active ? {} : { passive: true }) });
|
|
@@ -1503,7 +1913,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1503
1913
|
* answer approves; a dismissal, a timeout or another answer does not.
|
|
1504
1914
|
*/
|
|
1505
1915
|
async function confirm(sessionId: string, session: Session, body: string, approval?: { id: string }): Promise<{ approved: boolean; feedback?: string; outcome?: string }> {
|
|
1506
|
-
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId)) return { approved: false, outcome: 'busy', feedback: 'A question is already waiting for the user' };
|
|
1916
|
+
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) return { approved: false, outcome: 'busy', feedback: 'A question is already waiting for the user' };
|
|
1507
1917
|
const say = wordsFor(session);
|
|
1508
1918
|
const result = await askUser(sessionId, session, undefined, body, [say.approve, say.reject], approval) as { contentItems: Array<{ text: string }> };
|
|
1509
1919
|
let value: any;
|
|
@@ -1548,7 +1958,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1548
1958
|
if (unknown.length) return toolResult(false, { error: `Unknown roles: ${unknown.join(', ')}. Roles are ${[...known].join(', ')}` });
|
|
1549
1959
|
const file = path.join(library, 'skills', args.name, 'SKILL.md');
|
|
1550
1960
|
const content = `---\nname: ${args.name}\ndescription: ${JSON.stringify(args.description.replace(/\s+/g, ' ').trim())}\n---\n\n${args.body.trim()}\n`;
|
|
1551
|
-
const
|
|
1961
|
+
const normalizeLesson = (lesson: string) => lesson.replace(/\s+/g, ' ').trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, '').trim();
|
|
1962
|
+
const lessons: string[] = [...new Set<string>((args.lessons ?? []).map(normalizeLesson))];
|
|
1552
1963
|
// A replay of a proposed draft returns its approval, before anything it changed is checked again.
|
|
1553
1964
|
const draftKey = JSON.stringify(['skill', content, args.roles, lessons, !!args.replace]);
|
|
1554
1965
|
const key = `skill:${args.requestId ?? draftKey}`;
|
|
@@ -1567,7 +1978,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1567
1978
|
};
|
|
1568
1979
|
try { await readRoles(); } catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
1569
1980
|
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: 'Skill proposal canceled or session closed; no approval was created' });
|
|
1570
|
-
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId)) return toolResult(false, { error: 'A question is already waiting for the user; finish it before proposing a skill' });
|
|
1981
|
+
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) return toolResult(false, { error: 'A question is already waiting for the user; finish it before proposing a skill' });
|
|
1571
1982
|
const approvalId = `q-${randomUUID()}`;
|
|
1572
1983
|
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
1573
1984
|
approvals.set(key, record);
|
|
@@ -1594,15 +2005,17 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1594
2005
|
} catch (error) {
|
|
1595
2006
|
return { approved: true, saved: false, error: errorData(error).message, next: 'Tell the user; nothing is retried automatically.' };
|
|
1596
2007
|
}
|
|
1597
|
-
//
|
|
2008
|
+
// Compare exact rule text after normalizing whitespace and the optional recorded date.
|
|
1598
2009
|
const removed = new Set<string>();
|
|
1599
2010
|
for (const lessonFile of lessonFiles(session.mapping)) {
|
|
1600
2011
|
const current = await readFile(lessonFile, 'utf8').catch(() => undefined);
|
|
1601
2012
|
if (current === undefined) continue;
|
|
1602
2013
|
const kept = current.split('\n').filter(line => {
|
|
1603
2014
|
const match = /^- \d{4}-\d\d-\d\d: (.*)$/.exec(line);
|
|
1604
|
-
if (!match
|
|
1605
|
-
|
|
2015
|
+
if (!match) return true;
|
|
2016
|
+
const lesson = normalizeLesson(line);
|
|
2017
|
+
if (!lessons.includes(lesson)) return true;
|
|
2018
|
+
removed.add(lesson);
|
|
1606
2019
|
return false;
|
|
1607
2020
|
});
|
|
1608
2021
|
if (kept.length !== current.split('\n').length) await writeFile(lessonFile, kept.join('\n')).catch(() => {});
|
|
@@ -1630,6 +2043,187 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1630
2043
|
return toolResult(true, { status: 'pending_approval', approvalId, file, next: 'Continue other work or end your turn. ALP sends the user\'s decision, and whether the skill was saved, by mail; do not resubmit this draft.' });
|
|
1631
2044
|
}
|
|
1632
2045
|
|
|
2046
|
+
let scheduleHandler: ScheduleHandler | undefined;
|
|
2047
|
+
|
|
2048
|
+
/**
|
|
2049
|
+
* alp_lesson_curate: merges, shortenings and removals of recorded lessons, all shown to
|
|
2050
|
+
* the user in one approval and applied only when approved. Lessons are matched by their
|
|
2051
|
+
* exact rule text; nothing else in a lessons file changes.
|
|
2052
|
+
*/
|
|
2053
|
+
async function lessonCurateTool(sessionId: string, session: Session, args: unknown) {
|
|
2054
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
2055
|
+
args = structuredClone(args);
|
|
2056
|
+
type Change = { scope: 'project' | 'user'; remove: string[]; add?: string; reason?: string };
|
|
2057
|
+
const validChange = (change: any) => plainObject(change, ['scope', 'remove', 'add', 'reason']) && ['project', 'user'].includes(change.scope) &&
|
|
2058
|
+
Array.isArray(change.remove) && change.remove.length > 0 && change.remove.length <= 50 && change.remove.every((lesson: unknown) => text(lesson, LESSON_CHARS)) &&
|
|
2059
|
+
(change.add === undefined || text(change.add, LESSON_CHARS)) && (change.reason === undefined || (typeof change.reason === 'string' && change.reason.length <= 300));
|
|
2060
|
+
if (!plainObject(args, ['changes', 'requestId']) || !Array.isArray(args.changes) || !args.changes.length || args.changes.length > 50 || !args.changes.every(validChange)) {
|
|
2061
|
+
return toolResult(false, { error: `changes needs 1 to 50 entries, each with scope (project or user), remove (the exact text of 1 to 50 lessons) and optionally add (one rule of at most ${LESSON_CHARS} characters) and reason` });
|
|
2062
|
+
}
|
|
2063
|
+
if (args.requestId !== undefined && !text(args.requestId, 100)) return toolResult(false, { error: 'requestId must be a nonempty string of at most 100 characters' });
|
|
2064
|
+
const changes = args.changes as Change[];
|
|
2065
|
+
if (changes.some(change => change.scope === 'user') && !options.libraryDir) return toolResult(false, { error: 'This host keeps no user lessons' });
|
|
2066
|
+
const fileOf = (scope: string) => scope === 'user' ? path.join(options.libraryDir!, LESSONS_FILE) : path.join(session.mapping.agent.projectRoot, '.alp', LESSONS_FILE);
|
|
2067
|
+
const normalizeLesson = (lesson: string) => lesson.replace(/\s+/g, ' ').trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, '').trim();
|
|
2068
|
+
const normalized = changes.map(change => ({ ...change, remove: [...new Set(change.remove.map(normalizeLesson))], add: change.add?.replace(/\s+/g, ' ').trim() }));
|
|
2069
|
+
const draftKey = JSON.stringify(['lessons', normalized]);
|
|
2070
|
+
const key = `lessons:${args.requestId ?? draftKey}`;
|
|
2071
|
+
const approvals = approvalsOf(sessionId);
|
|
2072
|
+
const previous = approvals.get(key);
|
|
2073
|
+
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: 'requestId was already used for a different draft' });
|
|
2074
|
+
if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId });
|
|
2075
|
+
// Every lesson to remove must be recorded now; a proposal never guesses.
|
|
2076
|
+
const readLessons = async (file: string) => (await readFile(file, 'utf8').catch(() => '')).split('\n').flatMap(line => /^- \d{4}-\d\d-\d\d: /.test(line) ? [normalizeLesson(line)] : []);
|
|
2077
|
+
const missing: string[] = [];
|
|
2078
|
+
for (const change of normalized) {
|
|
2079
|
+
const recorded = new Set(await readLessons(fileOf(change.scope)));
|
|
2080
|
+
for (const lesson of change.remove) if (!recorded.has(lesson)) missing.push(`${change.scope}: ${lesson}`);
|
|
2081
|
+
}
|
|
2082
|
+
if (missing.length) return toolResult(false, { error: 'These lessons are not recorded; copy their exact text from the lessons files', missing });
|
|
2083
|
+
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: 'Lesson proposal canceled or session closed; no approval was created' });
|
|
2084
|
+
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) return toolResult(false, { error: 'A question is already waiting for the user; finish it before proposing lesson changes' });
|
|
2085
|
+
const approvalId = `q-${randomUUID()}`;
|
|
2086
|
+
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
2087
|
+
approvals.set(key, record);
|
|
2088
|
+
const say = wordsFor(session);
|
|
2089
|
+
const shown = normalized.map((change, index) =>
|
|
2090
|
+
`${index + 1}. ${say.lessonScope(change.scope, fileOf(change.scope))}${change.reason ? ` — ${change.reason}` : ''}\n` +
|
|
2091
|
+
change.remove.map(lesson => ` ${say.lessonRemove}: ${lesson}`).join('\n') +
|
|
2092
|
+
(change.add ? `\n ${say.lessonAdd}: ${change.add}` : '')).join('\n\n');
|
|
2093
|
+
const decision = confirm(sessionId, session, `${say.lessonCurate(session.mapping.agent.name, shown)}\n\n${say.answerLine(session.mapping.agent.name)}`, { id: approvalId });
|
|
2094
|
+
const apply = async (): Promise<Record<string, unknown>> => {
|
|
2095
|
+
const removed: string[] = [];
|
|
2096
|
+
const notFound: string[] = [];
|
|
2097
|
+
let added = 0;
|
|
2098
|
+
for (const scope of ['project', 'user'] as const) {
|
|
2099
|
+
const mine = normalized.filter(change => change.scope === scope);
|
|
2100
|
+
if (!mine.length) continue;
|
|
2101
|
+
const file = fileOf(scope);
|
|
2102
|
+
const write = (lessonWrites.get(file) ?? Promise.resolve()).catch(() => {}).then(async () => {
|
|
2103
|
+
const current = await readFile(file, 'utf8').catch(() => undefined);
|
|
2104
|
+
if (current === undefined) { for (const change of mine) notFound.push(...change.remove.map(lesson => `${scope}: ${lesson}`)); return; }
|
|
2105
|
+
const targets = new Set(mine.flatMap(change => change.remove));
|
|
2106
|
+
const seen = new Set<string>();
|
|
2107
|
+
const kept = current.split('\n').filter(line => {
|
|
2108
|
+
if (!/^- \d{4}-\d\d-\d\d: /.test(line)) return true;
|
|
2109
|
+
const lesson = normalizeLesson(line);
|
|
2110
|
+
if (!targets.has(lesson)) return true;
|
|
2111
|
+
seen.add(lesson);
|
|
2112
|
+
return false;
|
|
2113
|
+
});
|
|
2114
|
+
for (const lesson of targets) (seen.has(lesson) ? removed : notFound).push(`${scope}: ${lesson}`);
|
|
2115
|
+
const date = new Date().toISOString().slice(0, 10);
|
|
2116
|
+
// A replacement whose lessons are all gone meanwhile would only duplicate what replaced them.
|
|
2117
|
+
const additions = mine.filter(change => change.add && change.remove.some(lesson => seen.has(lesson))).map(change => `- ${date}: ${change.add}`);
|
|
2118
|
+
added += additions.length;
|
|
2119
|
+
let body = kept.join('\n');
|
|
2120
|
+
if (additions.length) body = body.replace(/\n*$/, '\n') + additions.join('\n') + '\n';
|
|
2121
|
+
await writeFile(file, body);
|
|
2122
|
+
});
|
|
2123
|
+
lessonWrites.set(file, write);
|
|
2124
|
+
await write;
|
|
2125
|
+
}
|
|
2126
|
+
runLog(rootOf(sessionId), { event: 'lesson.curate', agent: session.mapping.agent.name, removed, added, notFound });
|
|
2127
|
+
return { approved: true, applied: true, removed, added, ...(notFound.length ? { lessonsNotFound: notFound } : {}) };
|
|
2128
|
+
};
|
|
2129
|
+
void (async () => {
|
|
2130
|
+
const answer = await decision;
|
|
2131
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
2132
|
+
let result: Record<string, unknown>;
|
|
2133
|
+
if (!answer.approved || canceled) result = { approved: false, applied: false, outcome: canceled ? 'canceled' : answer.outcome, ...(answer.feedback ? { feedback: answer.feedback } : {}), next: 'Nothing changed. Revise from the feedback and propose again with a fresh requestId, or drop it.' };
|
|
2134
|
+
else {
|
|
2135
|
+
try { result = await apply(); }
|
|
2136
|
+
catch (error) { result = { approved: true, applied: false, error: errorData(error).message, next: 'Tell the user; nothing is retried automatically.' }; }
|
|
2137
|
+
}
|
|
2138
|
+
record.result = { status: 'resolved', approvalId, ...result };
|
|
2139
|
+
runLog(rootOf(sessionId), { event: 'lesson.curate.approval', agent: session.mapping.agent.name, ...record.result });
|
|
2140
|
+
if (!closed && !session.closed && sessions.get(sessionId) === session) post(sessionId, { kind: 'result', from: 'ALP', assignment: approvalId, body: `Lesson curate result: ${JSON.stringify(record.result)}` });
|
|
2141
|
+
})();
|
|
2142
|
+
return toolResult(true, { status: 'pending_approval', approvalId, next: 'Continue other work or end your turn. ALP sends the decision and what changed by mail; do not resubmit this draft.' });
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
/**
|
|
2146
|
+
* The monthly curate: a supervised main keeps one pending job that wakes it on the first
|
|
2147
|
+
* of next month to run the curate skill. A job left by an earlier session of the project
|
|
2148
|
+
* is replaced, since it could not be delivered. settings curate.monthly false turns it off.
|
|
2149
|
+
*/
|
|
2150
|
+
const curateSchedules = new Map<string, Promise<unknown>>();
|
|
2151
|
+
function ensureCurateSchedule(sessionId: string) {
|
|
2152
|
+
const root = sessions.get(sessionId);
|
|
2153
|
+
if (!scheduleHandler || !root || root.closed || root.parent) return Promise.resolve();
|
|
2154
|
+
// One project's opens take turns, so two at once never leave two jobs.
|
|
2155
|
+
const project = root.mapping.agent.projectRoot;
|
|
2156
|
+
const run = (curateSchedules.get(project) ?? Promise.resolve()).catch(() => {}).then(() => curateScheduleOf(sessionId, root, project));
|
|
2157
|
+
curateSchedules.set(project, run);
|
|
2158
|
+
// The chain is dropped once nothing follows it.
|
|
2159
|
+
void run.catch(() => {}).then(() => { if (curateSchedules.get(project) === run) curateSchedules.delete(project); });
|
|
2160
|
+
return run;
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2163
|
+
async function curateScheduleOf(sessionId: string, root: Session, project: string) {
|
|
2164
|
+
const handler = scheduleHandler;
|
|
2165
|
+
if (!handler || root.closed || sessions.get(sessionId) !== root) return;
|
|
2166
|
+
for (const file of [path.join(project, '.alp', 'settings.json'), ...(options.libraryDir ? [path.join(options.libraryDir, 'settings.json')] : [])]) {
|
|
2167
|
+
const settings = await readFile(file, 'utf8').then(raw => { try { return JSON.parse(raw); } catch { return undefined; } }, () => undefined);
|
|
2168
|
+
const monthly = settings?.curate?.monthly;
|
|
2169
|
+
if (monthly === false) return;
|
|
2170
|
+
if (monthly === true) break;
|
|
2171
|
+
}
|
|
2172
|
+
const listed = await handler('list', { projectRoot: project, status: 'pending' }) as { jobs?: Array<{ id: string; sessionId: string; prompt: string }> };
|
|
2173
|
+
const curate = (listed?.jobs ?? []).filter(job => job.prompt.startsWith(CURATE_MARKER));
|
|
2174
|
+
if (curate.some(job => job.sessionId === sessionId)) return;
|
|
2175
|
+
for (const job of curate) await handler('cancel', { id: job.id, projectRoot: project }).catch(() => {});
|
|
2176
|
+
const now = new Date();
|
|
2177
|
+
const dueAt = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 2)).toISOString();
|
|
2178
|
+
// The monthly job never keeps main open; a closed session's job fails and the next open makes another.
|
|
2179
|
+
await handler('create', { projectRoot: project, sessionId, dueAt, prompt: CURATE_PROMPT, keepsSession: false });
|
|
2180
|
+
runLog(sessionId, { event: 'curate.scheduled', dueAt, replaced: curate.map(job => job.id) });
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2183
|
+
async function scheduleTool(sessionId: string, session: Session, args: unknown) {
|
|
2184
|
+
if (session.parent || session.role === 'supervisor' || session.mapping.agent.name !== mainOf(session.mapping)) return toolResult(false, { error: 'Only the main root session schedules continuations' });
|
|
2185
|
+
if (!scheduleHandler) return toolResult(false, { error: 'This host does not support scheduled continuations' });
|
|
2186
|
+
if (!plainObject(args, ['action', 'dueAt', 'prompt', 'requestId', 'id', 'status']) || !['create', 'list', 'get', 'cancel'].includes(args.action)) return toolResult(false, { error: 'Unknown schedule action' });
|
|
2187
|
+
const action = args.action as 'create' | 'list' | 'get' | 'cancel';
|
|
2188
|
+
const fields = action === 'create' ? ['action', 'dueAt', 'prompt', 'requestId'] : action === 'list' ? ['action', 'status'] : ['action', 'id'];
|
|
2189
|
+
if (Object.keys(args).some(key => !fields.includes(key))) return toolResult(false, { error: 'Unexpected schedule argument' });
|
|
2190
|
+
const handler = scheduleHandler;
|
|
2191
|
+
const projectRoot = session.mapping.agent.projectRoot;
|
|
2192
|
+
const invoke = async (params: Record<string, unknown>) => {
|
|
2193
|
+
try { return toolResult(true, await handler(action, { ...params, projectRoot })); }
|
|
2194
|
+
catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
2195
|
+
};
|
|
2196
|
+
if (action !== 'create') return invoke(action === 'list' ? { ...(args.status ? { status: args.status } : {}) } : { id: args.id });
|
|
2197
|
+
if (!text(args.requestId, 200) || !text(args.prompt, 8000) || !text(args.dueAt, 80) ||
|
|
2198
|
+
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/.test(args.dueAt) || !Number.isFinite(Date.parse(args.dueAt))) return toolResult(false, { error: 'create needs requestId, prompt (1–8000 characters) and dueAt with an explicit UTC offset' });
|
|
2199
|
+
const draftKey = JSON.stringify([args.dueAt, args.prompt]);
|
|
2200
|
+
const key = `schedule:${args.requestId}`;
|
|
2201
|
+
const approvals = approvalsOf(sessionId);
|
|
2202
|
+
const previous = approvals.get(key);
|
|
2203
|
+
if (previous) return previous.draftKey !== draftKey
|
|
2204
|
+
? toolResult(false, { error: 'requestId already names another schedule draft' })
|
|
2205
|
+
: toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId });
|
|
2206
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
2207
|
+
const approvalId = `q-${randomUUID()}`;
|
|
2208
|
+
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
2209
|
+
approvals.set(key, record);
|
|
2210
|
+
const decision = confirm(sessionId, session,
|
|
2211
|
+
`Tạo lịch tiếp tục một lần?\nProject: ${projectRoot}\nSession: ${sessionId}\nThời gian: ${args.dueAt} (${new Date(args.dueAt).toISOString()})\n\n${args.prompt}`, { id: approvalId });
|
|
2212
|
+
void decision.then(async answer => {
|
|
2213
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
2214
|
+
let result: Record<string, unknown>;
|
|
2215
|
+
if (!answer.approved || canceled) result = { approved: false, created: false, outcome: canceled ? 'canceled' : answer.outcome, feedback: answer.feedback };
|
|
2216
|
+
else {
|
|
2217
|
+
try { result = { approved: true, created: true, ...await handler('create', { projectRoot, sessionId, dueAt: args.dueAt, prompt: args.prompt }) as object }; }
|
|
2218
|
+
catch (error) { result = { approved: true, created: false, error: errorData(error).message }; }
|
|
2219
|
+
}
|
|
2220
|
+
record.result = { status: 'resolved', approvalId, ...result };
|
|
2221
|
+
runLog(rootOf(sessionId), { event: 'schedule.approval', ...record.result });
|
|
2222
|
+
if (!session.closed) post(sessionId, { kind: 'result', from: 'ALP', assignment: approvalId, body: `Schedule approval result: ${JSON.stringify(record.result)}` });
|
|
2223
|
+
}).catch(error => { record.result = { status: 'resolved', approvalId, created: false, error: errorData(error).message }; });
|
|
2224
|
+
return toolResult(true, { status: 'pending_approval', approvalId, next: 'Continue other work or end your turn. ALP sends the decision and creation result by mail; do not resubmit this draft.' });
|
|
2225
|
+
}
|
|
2226
|
+
|
|
1633
2227
|
async function issueTool(sessionId: string, session: Session, args: unknown) {
|
|
1634
2228
|
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
1635
2229
|
args = structuredClone(args);
|
|
@@ -1676,7 +2270,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1676
2270
|
const previous = approvals.get(key);
|
|
1677
2271
|
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: 'requestId was already used for a different draft' });
|
|
1678
2272
|
if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId, repo });
|
|
1679
|
-
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId)) return toolResult(false, { error: 'A question is already waiting for the user; finish it before proposing another issue draft' });
|
|
2273
|
+
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) return toolResult(false, { error: 'A question is already waiting for the user; finish it before proposing another issue draft' });
|
|
1680
2274
|
const approvalId = `q-${randomUUID()}`;
|
|
1681
2275
|
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
1682
2276
|
approvals.set(key, record);
|
|
@@ -1762,11 +2356,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1762
2356
|
// with the next one, but never wake an idle requester on their own.
|
|
1763
2357
|
// Once none runs, what is left must still reach it, or a finished requester would never end.
|
|
1764
2358
|
const waking = !session.assignments.size || session.mail.some(event => !event.deliveredTurn && !event.passive && !(event.kind === 'note' && event.assignment !== sessionId));
|
|
2359
|
+
// A held idle session (a lifecycle operation, a pause, parked work) keeps its mail for the release.
|
|
2360
|
+
if (!session.active && waking && holdsWake(session)) { session.wakeHeld = true; return; }
|
|
1765
2361
|
if (session.pending) {
|
|
1766
2362
|
void session.acknowledged.then(() => deliver(sessionId, session));
|
|
1767
2363
|
} else if (session.active) {
|
|
1768
2364
|
// Deferred mail waits for the turn to end.
|
|
1769
|
-
if (session.mail.some(event => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
|
|
2365
|
+
if (!session.compacting && session.mail.some(event => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
|
|
1770
2366
|
} else if (!waking) {
|
|
1771
2367
|
return;
|
|
1772
2368
|
} else if (!session.wakeBlocked && session.wakeFailures < MAX_WAKES && (session.wakes < MAX_WAKES || session.mail.some(event => !event.deliveredTurn && event.kind === 'checkin'))) {
|
|
@@ -1788,7 +2384,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1788
2384
|
try {
|
|
1789
2385
|
await session.runtime.request('turn/steer', { threadId: session.threadId, expectedTurnId: turnId, clientUserMessageId: id, input: [{ type: 'text', text, text_elements: [] }] });
|
|
1790
2386
|
steered = true;
|
|
1791
|
-
emit(sessionId, { type: 'item', item: { kind: 'user_message', id: `user:${id}`, clientMessageId: id, text } });
|
|
2387
|
+
emit(sessionId, { type: 'item', item: { kind: 'user_message', id: `user:${id}`, clientMessageId: id, text, origin: 'wake' } });
|
|
1792
2388
|
} catch {}
|
|
1793
2389
|
// If the turn ended meanwhile, receipt is uncertain: deliver again rather than lose mail.
|
|
1794
2390
|
const received = steered && session.active === turnId;
|
|
@@ -1806,7 +2402,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1806
2402
|
/** Queued behind client operations, so a wake never races a user prompt or an interrupt. */
|
|
1807
2403
|
function autoWake(sessionId: string, session: Session) {
|
|
1808
2404
|
// Its runtime is paused or it is parked: the mail waits for resume.
|
|
1809
|
-
if (
|
|
2405
|
+
if (holdsWake(session)) { session.wakeHeld = true; return; }
|
|
1810
2406
|
// A check-in authorizes delivery of older mail too: the capped first batch
|
|
1811
2407
|
// may not reach the check-in itself. Keep that authorization through queuing.
|
|
1812
2408
|
const checkIn = session.mail.find(event => !event.deliveredTurn && event.kind === 'checkin');
|
|
@@ -1818,6 +2414,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1818
2414
|
};
|
|
1819
2415
|
const work = queue.then(async () => {
|
|
1820
2416
|
if (closed || session.closed) return release();
|
|
2417
|
+
// A hold taken after this wake was queued (a rewind) keeps the mail for its release.
|
|
2418
|
+
if (holdsWake(session)) { release(); session.wakeHeld = true; return; }
|
|
1821
2419
|
// Whatever ran first decides: a running turn gets the mail by steering, an interrupt holds it.
|
|
1822
2420
|
if (session.wakeBlocked || session.active || session.pending) {
|
|
1823
2421
|
release();
|
|
@@ -1977,7 +2575,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1977
2575
|
}
|
|
1978
2576
|
|
|
1979
2577
|
const { settleWorktree, worktreeTool, inCheckout, verifyIn, verificationResult, noteVerification, continuedBrief, verifyTool } = createWorktreeDomain({
|
|
1980
|
-
options, leases, rootOf, lineage, runLog, runHooks, touchTask,
|
|
2578
|
+
options, leases, rootOf, lineage, runLog, runHooks, touchTask, releaseResult: assignmentId => assignmentResults.remove(assignmentId),
|
|
1981
2579
|
});
|
|
1982
2580
|
|
|
1983
2581
|
/**
|
|
@@ -2006,20 +2604,44 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2006
2604
|
async function finishAssignment(parentId: string, parent: Session, assignment: Assignment, state: string, error?: unknown, quiet = false) {
|
|
2007
2605
|
if (assignment.finished) return;
|
|
2008
2606
|
assignment.finished = true;
|
|
2607
|
+
const child = assignmentSessions.get(assignment);
|
|
2009
2608
|
// alpd is stopping: the assignment stays in the live file and its task stays in progress, for the next alpd to continue.
|
|
2010
2609
|
if (closed && inFlight.get(assignment.id)) {
|
|
2011
2610
|
runLog(assignment.rootId, { event: 'assignment.interrupted', assignmentId: assignment.id, agent: assignment.agent, reason: 'alpd stopped' });
|
|
2012
|
-
await closeSession(assignment.id);
|
|
2611
|
+
if (child) await closeSession(assignment.id, child);
|
|
2013
2612
|
if (assignment.lease && leases.get(assignment.lease)?.assignment === assignment.id) leases.delete(assignment.lease);
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2613
|
+
if (!sessions.has(assignment.id) || sessions.get(assignment.id) === child) {
|
|
2614
|
+
childContexts.delete(assignment.id);
|
|
2615
|
+
parent.children.delete(assignment.id);
|
|
2616
|
+
}
|
|
2617
|
+
if (parent.assignments.get(assignment.id) === assignment) parent.assignments.delete(assignment.id);
|
|
2618
|
+
return;
|
|
2619
|
+
}
|
|
2620
|
+
// Ownership must reach durable storage before recovery evidence can disappear.
|
|
2621
|
+
const resultChild = child;
|
|
2622
|
+
try {
|
|
2623
|
+
if (assignment.worktree || writes(assignment.mode)) await assignmentResults.put({
|
|
2624
|
+
assignmentId: assignment.id,
|
|
2625
|
+
checkout: assignment.worktree?.checkout ?? assignment.writeCheckout ?? resultChild?.mapping.workdir ?? parent.mapping.workdir,
|
|
2626
|
+
...(assignment.worktree ? { worktree: assignment.worktree.path } : {}),
|
|
2627
|
+
// Outside a worktree, the change stays in the checkout: keep its evidence until the requester resolves it.
|
|
2628
|
+
...(!assignment.worktree ? { result: {
|
|
2629
|
+
agent: assignment.agent, status: state, finishedAt: new Date().toISOString(),
|
|
2630
|
+
project: (resultChild ?? parent).mapping.agent.projectRoot, requesters: lineage(parentId), ...(assignment.taskId ? { taskId: assignment.taskId } : {}),
|
|
2631
|
+
brief: cut(resultChild?.brief ?? '', RESULT_EVIDENCE_CHARS),
|
|
2632
|
+
summary: cut(JSON.stringify({ handoff: resultChild?.handoff ?? null, output: resultChild ? [...resultChild.text.values()].at(-1) ?? '' : '', ...(error ? { error: errorData(error).message } : {}) }), RESULT_EVIDENCE_CHARS),
|
|
2633
|
+
} } : {}),
|
|
2634
|
+
});
|
|
2635
|
+
} catch (failure) {
|
|
2636
|
+
// Keep both the assignment and its recovery evidence; never close away unrecorded ownership.
|
|
2637
|
+
assignment.finished = false;
|
|
2638
|
+
log.error('could not persist assignment result ownership', { assignmentId: assignment.id, error: failure });
|
|
2639
|
+
post(parentId, { kind: 'note', from: assignment.agent, assignment: assignment.id, passive: true, body: `Assignment result ownership could not be saved: ${errorData(failure).message}. Restore the assignment result ledger before completing or removing this workspace.` });
|
|
2017
2640
|
return;
|
|
2018
2641
|
}
|
|
2019
|
-
//
|
|
2642
|
+
// A crash while finishing never runs finished work again.
|
|
2020
2643
|
void inFlight.remove(assignment.id);
|
|
2021
|
-
|
|
2022
|
-
if (child && state === 'failed' && child.active) terminal(assignment.id, child, 'failed', error);
|
|
2644
|
+
if (child && sessions.get(assignment.id) === child && state === 'failed' && child.active) terminal(assignment.id, child, 'failed', error);
|
|
2023
2645
|
assignment.ask?.resolve(toolResult(false, { error: 'Assignment ended' }));
|
|
2024
2646
|
|
|
2025
2647
|
// Interim commentary stays in the child timeline; the final message is the answer.
|
|
@@ -2033,7 +2655,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2033
2655
|
...(error ? { error: errorData(error).message } : {}),
|
|
2034
2656
|
};
|
|
2035
2657
|
|
|
2036
|
-
await closeSession(assignment.id);
|
|
2658
|
+
if (child) await closeSession(assignment.id, child);
|
|
2037
2659
|
// Its native thread stays on disk, so its requesters can ask it about its work later.
|
|
2038
2660
|
// An ACP agent cannot fork a session to answer questions about it.
|
|
2039
2661
|
if (child?.threadId && child.mapping.keepThread && child.runtimeKind !== 'acp') {
|
|
@@ -2079,9 +2701,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2079
2701
|
});
|
|
2080
2702
|
if (!parent.closed) emit(parentId, { type: 'assignment', assignment: assignmentSnapshot(assignment, state) });
|
|
2081
2703
|
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2704
|
+
if (!sessions.has(assignment.id) || sessions.get(assignment.id) === child) {
|
|
2705
|
+
childContexts.delete(assignment.id);
|
|
2706
|
+
parent.children.delete(assignment.id);
|
|
2707
|
+
}
|
|
2708
|
+
if (parent.assignments.get(assignment.id) === assignment) parent.assignments.delete(assignment.id);
|
|
2085
2709
|
if (roleOf(parent.mapping, assignment.agent) === 'peer') {
|
|
2086
2710
|
const root = sessions.get(assignment.rootId);
|
|
2087
2711
|
if (root) root.peerCount--;
|
|
@@ -2109,7 +2733,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2109
2733
|
}
|
|
2110
2734
|
|
|
2111
2735
|
if (
|
|
2112
|
-
!['alp_delegate', 'alp_handoff', 'alp_wait', 'alp_cancel', 'alp_send', 'alp_ask', 'alp_merge', 'alp_discard', 'alp_recall', 'alp_verify', 'alp_pin', 'alp_board', 'alp_unpin', 'alp_lesson', 'alp_skill', 'alp_issue', 'alp_task'].includes(params.tool) ||
|
|
2736
|
+
!['alp_delegate', 'alp_handoff', 'alp_wait', 'alp_cancel', 'alp_send', 'alp_ask', 'alp_merge', 'alp_discard', 'alp_resolve', 'alp_recall', 'alp_verify', 'alp_pin', 'alp_board', 'alp_unpin', 'alp_lesson', 'alp_lesson_curate', 'alp_skill', 'alp_issue', 'alp_task', 'alp_schedule'].includes(params.tool) ||
|
|
2113
2737
|
params.namespace != null ||
|
|
2114
2738
|
typeof params.callId !== 'string'
|
|
2115
2739
|
) {
|
|
@@ -2122,14 +2746,19 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2122
2746
|
if (cached) return cached;
|
|
2123
2747
|
|
|
2124
2748
|
const args = params.arguments;
|
|
2749
|
+
// Every transport's arguments, before any tool walks them: the Codex, ACP and Antigravity paths have no schema of their own.
|
|
2750
|
+
const oversized = inputLimitError(args, TOOL_INPUT, `${params.tool} input`);
|
|
2751
|
+
if (oversized) return toolResult(false, { error: oversized });
|
|
2125
2752
|
// The supervisor only reads the board and tasks, and writes to main.
|
|
2126
2753
|
if (session.role === 'supervisor' && !['alp_send', 'alp_board', 'alp_task'].includes(params.tool)) return toolResult(false, { error: 'The supervisor only uses alp_send, alp_board and alp_task' });
|
|
2127
|
-
if (
|
|
2754
|
+
if (['alp_lesson', 'alp_lesson_curate', 'alp_skill'].includes(params.tool) && !supervises(session)) return toolResult(false, { error: 'Only a supervised main records lessons and skills' });
|
|
2128
2755
|
if (params.tool === 'alp_issue' && (session.parent || session.mapping.agent.name !== mainOf(session.mapping))) return toolResult(false, { error: 'Only main files issues; report the problem to your requester' });
|
|
2129
2756
|
const work =
|
|
2130
2757
|
params.tool === 'alp_lesson' ? lessonTool(sessionId, session, args)
|
|
2758
|
+
: params.tool === 'alp_lesson_curate' ? lessonCurateTool(sessionId, session, args)
|
|
2131
2759
|
: params.tool === 'alp_skill' ? skillTool(sessionId, session, args)
|
|
2132
2760
|
: params.tool === 'alp_issue' ? issueTool(sessionId, session, args)
|
|
2761
|
+
: params.tool === 'alp_schedule' ? scheduleTool(sessionId, session, args)
|
|
2133
2762
|
: params.tool === 'alp_task' ? taskToolCall(sessionId, session, args)
|
|
2134
2763
|
: params.tool === 'alp_delegate' ? runDelegation(sessionId, session, params)
|
|
2135
2764
|
: params.tool === 'alp_wait' ? waitTool(sessionId, session, args)
|
|
@@ -2138,6 +2767,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2138
2767
|
: params.tool === 'alp_board' ? boardTool(session, args)
|
|
2139
2768
|
: params.tool === 'alp_unpin' ? unpinTool(sessionId, session, args)
|
|
2140
2769
|
: params.tool === 'alp_recall' ? recallTool(sessionId, session, args)
|
|
2770
|
+
: params.tool === 'alp_resolve' ? resolveTool(sessionId, session, args)
|
|
2141
2771
|
: params.tool === 'alp_verify' ? verifyTool(sessionId, session, args)
|
|
2142
2772
|
: params.tool === 'alp_cancel' ? cancelTool(sessionId, session, args)
|
|
2143
2773
|
: params.tool === 'alp_merge' || params.tool === 'alp_discard' ? worktreeTool(sessionId, session, args, params.tool === 'alp_merge' ? 'merge' : 'discard')
|
|
@@ -2318,11 +2948,147 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2318
2948
|
|
|
2319
2949
|
/** Ordinary questions end with their turn; issue approvals survive until decision or session cancellation. */
|
|
2320
2950
|
function cancelQuestions(sessionId: string, turnOnly = false) {
|
|
2321
|
-
for (const { question, settle, persistent } of [...userQuestions.values()]) {
|
|
2951
|
+
for (const { question, settle, persistent, gate } of [...userQuestions.values()]) {
|
|
2952
|
+
// A gate card ends only with its gate or its session; syncGates shows it again on the next main.
|
|
2953
|
+
if (gate && turnOnly) continue;
|
|
2322
2954
|
if (question.sessionId === sessionId && (!turnOnly || !persistent)) settle('canceled', undefined, undefined, toolResult(false, { error: 'Turn ended' }));
|
|
2323
2955
|
}
|
|
2324
2956
|
}
|
|
2325
2957
|
|
|
2958
|
+
// Human gates (t-ccac): .alp/tasks stays the source of truth. Each open human gate of a project
|
|
2959
|
+
// shows as a card on its live main root session, without a timeout and outside the one-question
|
|
2960
|
+
// limit; syncGates rebuilds the cards from the files (on start, attach, a gate change and a timer,
|
|
2961
|
+
// since the CLI and Paseo's local panel write the files without alpd) and tells main of every
|
|
2962
|
+
// decision once: markGateNotified marks it under the task lock, so card, panel and CLI racing on
|
|
2963
|
+
// one gate send one mail. With no live main, the decision waits for the project's next main.
|
|
2964
|
+
const gateSyncs = new Map<string, Promise<void>>();
|
|
2965
|
+
const gateCardId = (taskId: string, gateId: string) => `gate-${taskId}-${gateId}`;
|
|
2966
|
+
|
|
2967
|
+
/** The project's live main root session, if any. */
|
|
2968
|
+
function mainSessionOf(projectRoot: string) {
|
|
2969
|
+
for (const [id, session] of sessions) {
|
|
2970
|
+
if (session.closed || session.parent || session.role === 'supervisor' || !session.threadId) continue;
|
|
2971
|
+
if (session.mapping.agent.name !== mainOf(session.mapping) || path.resolve(session.mapping.agent.projectRoot) !== projectRoot) continue;
|
|
2972
|
+
return { id, session };
|
|
2973
|
+
}
|
|
2974
|
+
return undefined;
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
function syncGates(projectRoot: string): Promise<void> {
|
|
2978
|
+
const root = path.resolve(projectRoot);
|
|
2979
|
+
const previous = gateSyncs.get(root) ?? Promise.resolve();
|
|
2980
|
+
const next = previous.then(() => syncGatesNow(root)).catch(error => { runLog(mainSessionOf(root)?.id ?? root, { event: 'gate.sync.failed', projectRoot: root, error: errorData(error).message }); });
|
|
2981
|
+
gateSyncs.set(root, next);
|
|
2982
|
+
void next.finally(() => { if (gateSyncs.get(root) === next) gateSyncs.delete(root); });
|
|
2983
|
+
return next;
|
|
2984
|
+
}
|
|
2985
|
+
|
|
2986
|
+
async function syncGatesNow(projectRoot: string) {
|
|
2987
|
+
if (closed) return;
|
|
2988
|
+
const { tasks } = await loadTasks(projectRoot);
|
|
2989
|
+
const main = mainSessionOf(projectRoot);
|
|
2990
|
+
// The user's decisions, to main once each; without a live main they wait for the next one.
|
|
2991
|
+
if (main) for (const { task, gate, decision, record } of gateDecisions(tasks)) {
|
|
2992
|
+
if (!await markGateNotified(projectRoot, task.id, gate.id, decision)) continue;
|
|
2993
|
+
const choice = decision === 'approved' ? (record as { choice?: string }).choice : undefined;
|
|
2994
|
+
const words = decision === 'approved'
|
|
2995
|
+
? `The user approved human gate ${gate.id} of ${task.id} in ${record.channel}${choice ? `, choosing "${choice}"` : ''}${(record as { note?: string }).note ? `: ${(record as { note?: string }).note}` : ''}.`
|
|
2996
|
+
: `The user rejected human gate ${gate.id} of ${task.id} in ${record.channel}${(record as { reason?: string }).reason ? `: ${(record as { reason?: string }).reason}` : ''}. The gate stays open.`;
|
|
2997
|
+
post(main.id, { kind: 'result', from: 'ALP', assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words} Task: ${task.title}` });
|
|
2998
|
+
runLog(main.id, { event: 'gate.decision', projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record.channel, ...(choice ? { choice } : {}) });
|
|
2999
|
+
}
|
|
3000
|
+
// A card for each open human gate the user has not rejected; a rejected one stays open for main to follow up.
|
|
3001
|
+
const wanted = new Map<string, { task: Task; gate: Task['gates'][number] }>();
|
|
3002
|
+
for (const task of tasks) {
|
|
3003
|
+
if (task.status === 'closed') continue;
|
|
3004
|
+
for (const gate of task.gates ?? []) if (gate.kind === 'human' && !gate.resolved && !gate.rejected) wanted.set(gateCardId(task.id, gate.id), { task, gate });
|
|
3005
|
+
}
|
|
3006
|
+
for (const [id, pending] of [...userQuestions]) {
|
|
3007
|
+
if (pending.question.gate?.projectRoot !== projectRoot) continue;
|
|
3008
|
+
const want = wanted.get(id);
|
|
3009
|
+
if (!want || !main || pending.question.sessionId !== main.id) {
|
|
3010
|
+
const task = tasks.find(entry => entry.id === pending.question.gate!.taskId);
|
|
3011
|
+
const gate = task?.gates.find(entry => entry.id === pending.question.gate!.gateId);
|
|
3012
|
+
pending.settle(gate?.resolved ? 'answered' : gate?.rejected ? 'dismissed' : 'canceled', gate?.resolved?.choice, gate?.rejected?.reason);
|
|
3013
|
+
} else if (pending.gate) pending.gate.rev = want.task.rev;
|
|
3014
|
+
}
|
|
3015
|
+
if (!main) return;
|
|
3016
|
+
for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
|
|
3017
|
+
}
|
|
3018
|
+
|
|
3019
|
+
/** The CLI and Paseo's local Tasks panel write gates without alpd: a timer reads them while a main is live. */
|
|
3020
|
+
let gateWatch: NodeJS.Timeout | undefined;
|
|
3021
|
+
function startGateWatch() {
|
|
3022
|
+
if (gateWatch || options.gateSyncMs === 0) return;
|
|
3023
|
+
gateWatch = setInterval(() => {
|
|
3024
|
+
const roots = new Set([...sessions.values()].filter(session => !session.closed && !session.parent && session.role !== 'supervisor' && session.mapping.agent.name === mainOf(session.mapping)).map(session => path.resolve(session.mapping.agent.projectRoot)));
|
|
3025
|
+
for (const root of roots) void syncGates(root);
|
|
3026
|
+
if (!roots.size) { clearInterval(gateWatch); gateWatch = undefined; }
|
|
3027
|
+
}, options.gateSyncMs ?? 5_000);
|
|
3028
|
+
gateWatch.unref?.();
|
|
3029
|
+
}
|
|
3030
|
+
|
|
3031
|
+
function showGateCard(sessionId: string, session: Session, projectRoot: string, task: Task, gate: Task['gates'][number]) {
|
|
3032
|
+
const say = wordsFor(session);
|
|
3033
|
+
const vietnamese = say.approve === words('vi').approve;
|
|
3034
|
+
const question: UserQuestion = {
|
|
3035
|
+
id: gateCardId(task.id, gate.id),
|
|
3036
|
+
sessionId,
|
|
3037
|
+
rootId: rootOf(sessionId),
|
|
3038
|
+
agent: 'ALP',
|
|
3039
|
+
body: `${vietnamese ? `Cổng phê duyệt ${gate.id} của ${task.id}` : `Approval gate ${gate.id} of ${task.id}`} (${task.title}):\n${gate.note ?? ''}`,
|
|
3040
|
+
// Options approve; Reject (added after them unless one of them is that word) keeps the gate open.
|
|
3041
|
+
options: gate.options?.length ? (gate.options.includes(say.reject) ? gate.options : [...gate.options, say.reject]) : [say.approve, say.reject],
|
|
3042
|
+
askedAt: gate.at ?? new Date().toISOString(),
|
|
3043
|
+
gate: { projectRoot, taskId: task.id, gateId: gate.id },
|
|
3044
|
+
};
|
|
3045
|
+
const card = { rev: task.rev, deciding: false };
|
|
3046
|
+
const settle = (outcome: 'answered' | 'dismissed' | 'timeout' | 'canceled', answer?: string) => {
|
|
3047
|
+
if (userQuestions.get(question.id)?.question !== question) return;
|
|
3048
|
+
userQuestions.delete(question.id);
|
|
3049
|
+
emit(sessionId, { type: 'question.resolved', questionId: question.id, outcome, ...(answer !== undefined ? { answer } : {}) });
|
|
3050
|
+
};
|
|
3051
|
+
userQuestions.set(question.id, { question, settle, persistent: true, gate: Object.assign(card, { decide: (reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }) => decideGate(projectRoot, question, card, reply, gate.options?.length ? gate.options : undefined) }) });
|
|
3052
|
+
emit(sessionId, { type: 'question', question });
|
|
3053
|
+
runLog(rootOf(sessionId), { event: 'gate.card', questionId: question.id, taskId: task.id, gateId: gate.id });
|
|
3054
|
+
}
|
|
3055
|
+
|
|
3056
|
+
/**
|
|
3057
|
+
* The user answered a gate card: an option approves (with the default Approve/Reject, Reject or
|
|
3058
|
+
* other words reject), dismissing rejects. The card's task rev guards the write; a stale rev is
|
|
3059
|
+
* read again and retried only while the gate is still open and undecided, so a decision another
|
|
3060
|
+
* channel made first is never applied or mailed twice.
|
|
3061
|
+
*/
|
|
3062
|
+
async function decideGate(projectRoot: string, question: UserQuestion, card: { rev: number; deciding: boolean }, reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }, choices?: string[]) {
|
|
3063
|
+
const defaults = !choices;
|
|
3064
|
+
if (card.deciding) return;
|
|
3065
|
+
card.deciding = true;
|
|
3066
|
+
const { taskId, gateId } = question.gate!;
|
|
3067
|
+
const channel = reply.channel ?? 'web';
|
|
3068
|
+
const text = reply.text?.trim();
|
|
3069
|
+
const approve = !reply.dismiss && !!text && (defaults ? APPROVALS.includes(text.toLowerCase()) : choices.includes(text));
|
|
3070
|
+
const rejectReason = reply.dismiss ? reply.reason : text && CHOICES_REJECT.includes(text.toLowerCase()) ? undefined : text;
|
|
3071
|
+
const write = (ifRev: number) => approve
|
|
3072
|
+
? resolveGate(projectRoot, taskId, gateId, { by: 'user', ifRev, channel, ...(defaults ? {} : { choice: text }) })
|
|
3073
|
+
: rejectGate(projectRoot, taskId, gateId, { by: 'user', ifRev, channel, ...(rejectReason ? { reason: rejectReason.slice(0, 2000) } : {}) });
|
|
3074
|
+
try {
|
|
3075
|
+
try { await write(card.rev); }
|
|
3076
|
+
catch (error: any) {
|
|
3077
|
+
if (error?.code !== 'TASK_CHANGED') throw error;
|
|
3078
|
+
const current = (await loadTasks(projectRoot)).tasks.find(entry => entry.id === taskId);
|
|
3079
|
+
const gate = current?.gates.find(entry => entry.id === gateId);
|
|
3080
|
+
if (!current || current.status === 'closed' || !gate || gate.resolved || gate.rejected) return;
|
|
3081
|
+
await write(current.rev);
|
|
3082
|
+
}
|
|
3083
|
+
} catch (error) {
|
|
3084
|
+
// Already clear, or the task is gone: the other channel won; the sync below settles the card.
|
|
3085
|
+
runLog(question.rootId, { event: 'gate.answer.failed', questionId: question.id, error: errorData(error).message });
|
|
3086
|
+
} finally {
|
|
3087
|
+
card.deciding = false;
|
|
3088
|
+
await syncGates(projectRoot);
|
|
3089
|
+
}
|
|
3090
|
+
}
|
|
3091
|
+
|
|
2326
3092
|
function askTool(sessionId: string, session: Session, args: unknown) {
|
|
2327
3093
|
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
2328
3094
|
const assignment = parent?.assignments.get(sessionId);
|
|
@@ -2334,7 +3100,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2334
3100
|
if (args.options !== undefined && (to !== 'user' || !Array.isArray(args.options) || args.options.length > 10 || !args.options.every((option: unknown) => typeof option === 'string' && option.trim() && option.length <= 200))) {
|
|
2335
3101
|
return Promise.resolve(toolResult(false, { error: 'options are up to 10 short answers, for questions to the user' }));
|
|
2336
3102
|
}
|
|
2337
|
-
if (assignment?.ask || [...userQuestions.values()].some(pending => pending.question.sessionId === sessionId)) {
|
|
3103
|
+
if (assignment?.ask || [...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) {
|
|
2338
3104
|
return Promise.resolve(toolResult(false, { error: 'A question is already waiting for an answer' }));
|
|
2339
3105
|
}
|
|
2340
3106
|
// Only main talks to the user, unless the user has written to this assignment first.
|
|
@@ -2365,10 +3131,19 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2365
3131
|
});
|
|
2366
3132
|
}
|
|
2367
3133
|
|
|
2368
|
-
async function runDelegation(
|
|
3134
|
+
async function runDelegation(sessionId: string, session: Session, params: any): Promise<unknown> {
|
|
3135
|
+
if (workspaceMutation) refuseMutation('workspace_busy', 'A workspace mutation is in progress; retry after it finishes');
|
|
3136
|
+
admitting++;
|
|
3137
|
+
let released = false;
|
|
3138
|
+
const release = () => { if (!released) { released = true; admitting--; } };
|
|
3139
|
+
try { return await runDelegationAdmitted(sessionId, session, params, release); }
|
|
3140
|
+
finally { release(); }
|
|
3141
|
+
}
|
|
3142
|
+
async function runDelegationAdmitted(
|
|
2369
3143
|
sessionId: string,
|
|
2370
3144
|
session: Session,
|
|
2371
3145
|
params: any,
|
|
3146
|
+
admitted: () => void,
|
|
2372
3147
|
): Promise<unknown> {
|
|
2373
3148
|
const args = params.arguments;
|
|
2374
3149
|
|
|
@@ -2598,6 +3373,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2598
3373
|
...(task ? { taskId: task.id } : {}),
|
|
2599
3374
|
});
|
|
2600
3375
|
try {
|
|
3376
|
+
// Persist ownership before native checkout creation or child execution. Recovery books may be lost.
|
|
3377
|
+
if (writes(childMode)) await assignmentResults.put({ assignmentId: childId, checkout });
|
|
2601
3378
|
if (task) {
|
|
2602
3379
|
const started = await startTask(project, task.id, { agent: args.agent, assignment: childId, pid: process.pid, pidStartedAt: OWN_START, epoch }, session.mapping.agent.name);
|
|
2603
3380
|
assignment.taskId = started.id;
|
|
@@ -2612,8 +3389,12 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2612
3389
|
if (continued) session.worktrees.set(args.continueFrom, continued);
|
|
2613
3390
|
throw error;
|
|
2614
3391
|
}
|
|
3392
|
+
await assignmentResults.put({ assignmentId: childId, checkout: assignment.worktree.checkout, worktree: assignment.worktree.path });
|
|
2615
3393
|
// The new branch holds the earlier change, so its worktree and branch can go.
|
|
2616
|
-
if (continued)
|
|
3394
|
+
if (continued) {
|
|
3395
|
+
await removeWorktree(continued.worktree, { deleteBranch: true });
|
|
3396
|
+
await assignmentResults.remove(args.continueFrom);
|
|
3397
|
+
}
|
|
2617
3398
|
runLog(rootId, { event: 'worktree.created', assignmentId: childId, branch: assignment.worktree.branch, base: assignment.worktree.base, ...(continued ? { continuedFrom: args.continueFrom } : {}) });
|
|
2618
3399
|
} else if (sharedWriter) {
|
|
2619
3400
|
assignment.fingerprint = await checkoutFingerprint(checkout).catch(() => undefined);
|
|
@@ -2639,9 +3420,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2639
3420
|
thinking,
|
|
2640
3421
|
mode: childMode,
|
|
2641
3422
|
};
|
|
2642
|
-
await openSession(childId, childSpec, 'skip', session.delegation);
|
|
3423
|
+
await openSession(childId, childSpec, 'skip', session.delegation, assignment);
|
|
3424
|
+
admitted();
|
|
2643
3425
|
|
|
2644
|
-
const child =
|
|
3426
|
+
const child = assignmentSessions.get(assignment);
|
|
3427
|
+
if (child && sessions.get(childId) !== child) throw new Error('Child session was replaced during open');
|
|
2645
3428
|
if (child) void runHooks(childId, child, 'assignment.start', { assignment: childId, brief: clip(args.task, 2000) }, args.taskId);
|
|
2646
3429
|
|
|
2647
3430
|
if (
|
|
@@ -2680,6 +3463,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2680
3463
|
addPin(childId, child, pins, { kind: 'claim', body: `Task ${task.id}: ${task.title}`, paths: task.paths, task: task.id });
|
|
2681
3464
|
}
|
|
2682
3465
|
|
|
3466
|
+
// Mail held for the brief goes with it: startPrompt takes what waits.
|
|
2683
3467
|
await startPrompt(childId, {
|
|
2684
3468
|
clientMessageId: `task-${childId}`,
|
|
2685
3469
|
delivery: 'auto',
|
|
@@ -2694,6 +3478,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2694
3478
|
},
|
|
2695
3479
|
],
|
|
2696
3480
|
}, 'assignment');
|
|
3481
|
+
// Held until the brief's turn started: what came since steers it, or wakes the child if it ended.
|
|
3482
|
+
// A brief that did not start leaves the hold; the child closes with its failed assignment.
|
|
3483
|
+
child.awaitingBrief = false;
|
|
3484
|
+
if (child.wakeHeld) { child.wakeHeld = false; deliver(childId, child); }
|
|
2697
3485
|
} catch (error) {
|
|
2698
3486
|
// A child that failed while starting may already have reported by mail; report once.
|
|
2699
3487
|
session.mail = session.mail.filter(event => event.deliveredTurn || event.kind !== 'result' || event.assignment !== childId);
|
|
@@ -2743,7 +3531,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2743
3531
|
});
|
|
2744
3532
|
}
|
|
2745
3533
|
|
|
2746
|
-
async function openSession(sessionId: string, spec: SessionSpec, history: 'replay' | 'skip', delegation = true): Promise<SessionSnapshot> {
|
|
3534
|
+
async function openSession(sessionId: string, spec: SessionSpec, history: 'replay' | 'skip', delegation = true, assignment?: Assignment): Promise<SessionSnapshot> {
|
|
3535
|
+
return admission(() => openSessionAdmitted(sessionId, spec, history, delegation, assignment));
|
|
3536
|
+
}
|
|
3537
|
+
async function openSessionAdmitted(sessionId: string, spec: SessionSpec, history: 'replay' | 'skip', delegation = true, assignment?: Assignment): Promise<SessionSnapshot> {
|
|
2747
3538
|
if (sessions.has(sessionId)) {
|
|
2748
3539
|
throw new Error(
|
|
2749
3540
|
'Session is already open',
|
|
@@ -2819,6 +3610,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2819
3610
|
? sessions.get(context.parent)?.mapping.agent.name
|
|
2820
3611
|
: undefined,
|
|
2821
3612
|
...(context?.role ? { role: context.role } : {}),
|
|
3613
|
+
// A new assignment's first turn is its brief; mail that comes sooner waits for it.
|
|
3614
|
+
...(context && !context.role && !context.recovered ? { awaitingBrief: true } : {}),
|
|
2822
3615
|
journal: [],
|
|
2823
3616
|
tasks: [],
|
|
2824
3617
|
|
|
@@ -2838,6 +3631,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2838
3631
|
acknowledged: Promise.resolve(),
|
|
2839
3632
|
worktrees: new Map(),
|
|
2840
3633
|
};
|
|
3634
|
+
if (assignment) assignmentSessions.set(assignment, session);
|
|
3635
|
+
// Pending until its thread exists: mail posted meanwhile waits for it, as in a restart.
|
|
3636
|
+
const finishPending = beginPending(session);
|
|
3637
|
+
const opening: { failure?: unknown } = {};
|
|
3638
|
+
openings.set(session, opening);
|
|
3639
|
+
/** A process failure during the open fails it: the step that saw it settle need not have failed. */
|
|
3640
|
+
const failedMeanwhile = () => { if (opening.failure !== undefined) throw opening.failure; };
|
|
2841
3641
|
|
|
2842
3642
|
sessions.set(
|
|
2843
3643
|
sessionId,
|
|
@@ -2848,8 +3648,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2848
3648
|
|
|
2849
3649
|
try {
|
|
2850
3650
|
await runtime.initialize();
|
|
3651
|
+
failedMeanwhile();
|
|
2851
3652
|
|
|
2852
|
-
if (session.closed) {
|
|
3653
|
+
if (session.closed || sessions.get(sessionId) !== session) {
|
|
2853
3654
|
throw new Error(
|
|
2854
3655
|
'Session closed during initialization',
|
|
2855
3656
|
);
|
|
@@ -2876,6 +3677,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2876
3677
|
const nativeConfig = await configOf(session);
|
|
2877
3678
|
noteInstructions(sessionId, session, nativeConfig.developerInstructions);
|
|
2878
3679
|
|
|
3680
|
+
// A Claude fork or rewind that has not had its first prompt yet is made from its base (§12.7).
|
|
3681
|
+
const base = mapping.threadId ? spec.restore?.base : undefined;
|
|
3682
|
+
if (base && runtimeKind !== 'claude') throw new Error(`A ${label(runtimeKind)} session has no base conversation; only Claude makes a fork on its first prompt`);
|
|
3683
|
+
if (base) session.base = base;
|
|
2879
3684
|
const result = mapping.threadId
|
|
2880
3685
|
? await runtime.request(
|
|
2881
3686
|
'thread/resume',
|
|
@@ -2883,6 +3688,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2883
3688
|
...nativeConfig,
|
|
2884
3689
|
threadId:
|
|
2885
3690
|
mapping.threadId,
|
|
3691
|
+
...(base ? { base } : {}),
|
|
2886
3692
|
},
|
|
2887
3693
|
)
|
|
2888
3694
|
: await runtime.request(
|
|
@@ -2896,16 +3702,20 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2896
3702
|
|
|
2897
3703
|
session.threadId =
|
|
2898
3704
|
result.thread.id;
|
|
3705
|
+
failedMeanwhile();
|
|
2899
3706
|
|
|
2900
|
-
if (session.closed) {
|
|
3707
|
+
if (session.closed || sessions.get(sessionId) !== session) {
|
|
2901
3708
|
throw new Error(
|
|
2902
3709
|
'Session closed during thread creation',
|
|
2903
3710
|
);
|
|
2904
3711
|
}
|
|
2905
3712
|
|
|
2906
|
-
session
|
|
3713
|
+
// Open from here on: a process failure is the live session's (wire's onFailure).
|
|
3714
|
+
openings.delete(session);
|
|
2907
3715
|
session.buffered = [];
|
|
3716
|
+
finishPending();
|
|
2908
3717
|
|
|
3718
|
+
openedSessions.add(session);
|
|
2909
3719
|
emit(sessionId, {
|
|
2910
3720
|
type: 'session.opened',
|
|
2911
3721
|
session: snapshot(sessionId, session),
|
|
@@ -2915,6 +3725,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2915
3725
|
thinking: result.reasoningEffort ?? mapping.thinking,
|
|
2916
3726
|
},
|
|
2917
3727
|
});
|
|
3728
|
+
// A main root shows the project's open human gates and gets decisions made while none was live.
|
|
3729
|
+
if (!session.parent && session.role !== 'supervisor' && mapping.agent.name === mainOf(mapping)) { void syncGates(mapping.agent.projectRoot); startGateWatch(); }
|
|
2918
3730
|
|
|
2919
3731
|
if (
|
|
2920
3732
|
history === 'replay'
|
|
@@ -2941,12 +3753,15 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2941
3753
|
return snapshot(sessionId, session);
|
|
2942
3754
|
} catch (error) {
|
|
2943
3755
|
log.error(`${session.mapping.agent.name} could not start its ${session.runtimeKind} session`, { code: 'ALP_PROVIDER_START_FAILED', sessionId, rootId: rootOf(sessionId), agent: session.mapping.agent.name, provider: session.runtimeKind, error });
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
);
|
|
2948
|
-
|
|
2949
|
-
|
|
3756
|
+
// A process failure while the open ran is reported now that the open is through, once.
|
|
3757
|
+
const failed = openings.get(session);
|
|
3758
|
+
openings.delete(session);
|
|
3759
|
+
if (failed?.failure !== undefined) failSession(sessionId, session, failed.failure);
|
|
3760
|
+
// Share the retirement the failure started, and never resolve the id to a
|
|
3761
|
+
// replacement record when this open finishes late.
|
|
3762
|
+
const cleanup = closeSession(sessionId, session, false);
|
|
3763
|
+
finishPending();
|
|
3764
|
+
await cleanup;
|
|
2950
3765
|
|
|
2951
3766
|
throw error;
|
|
2952
3767
|
}
|
|
@@ -2973,17 +3788,21 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2973
3788
|
});
|
|
2974
3789
|
transport.onFailure((error) => {
|
|
2975
3790
|
// A transport ALP already replaced reports nothing.
|
|
2976
|
-
if (session.closed || session.runtime !== transport) return;
|
|
3791
|
+
if (session.closed || session.runtime !== transport || sessions.get(sessionId) !== session) return;
|
|
3792
|
+
// The first open still runs: it fails with this, and reports it when it is through.
|
|
3793
|
+
const opening = openings.get(session);
|
|
3794
|
+
if (opening) { opening.failure ??= error; return; }
|
|
2977
3795
|
if (revivable(session)) void revive(sessionId, session, error);
|
|
2978
3796
|
else failSession(sessionId, session, error);
|
|
2979
3797
|
});
|
|
2980
3798
|
}
|
|
2981
3799
|
|
|
2982
3800
|
function failSession(sessionId: string, session: Session, error: unknown) {
|
|
3801
|
+
if (session.closed || sessions.get(sessionId) !== session) return;
|
|
2983
3802
|
log.error(`${session.mapping.agent.name}'s ${session.runtimeKind} session failed`, { code: 'ALP_PROVIDER_FAILED', sessionId, rootId: rootOf(sessionId), agent: session.mapping.agent.name, provider: session.runtimeKind, error });
|
|
2984
3803
|
terminal(sessionId, session, 'failed', error);
|
|
2985
3804
|
session.settle?.('failed', error);
|
|
2986
|
-
void closeSession(sessionId);
|
|
3805
|
+
void closeSession(sessionId, session);
|
|
2987
3806
|
emit(sessionId, { type: 'session.failed', error: errorData(error) });
|
|
2988
3807
|
}
|
|
2989
3808
|
|
|
@@ -3045,38 +3864,467 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3045
3864
|
const harness = label(session.runtimeKind);
|
|
3046
3865
|
log.warn(`${harness} process of ${session.mapping.agent.name} stopped; restarting it`, { code: 'ALP_PROVIDER_RESTARTED', sessionId, rootId: rootOf(sessionId), agent: session.mapping.agent.name, provider: session.runtimeKind, error });
|
|
3047
3866
|
runLog(rootOf(sessionId), { event: 'session.restarted', sessionId, agent: session.mapping.agent.name, error: errorData(error).message, restarts: session.restarts.length });
|
|
3867
|
+
let interrupted: Session['parked'];
|
|
3048
3868
|
if (session.active) {
|
|
3049
3869
|
session.parkReason = `its ${harness} process stopped`;
|
|
3870
|
+
session.parkPause = undefined;
|
|
3050
3871
|
session.parkThen = `ALP is restarting the ${harness} process; this assignment continues by itself.`;
|
|
3051
3872
|
terminal(sessionId, session, 'failed', error);
|
|
3873
|
+
interrupted = session.parked;
|
|
3052
3874
|
}
|
|
3053
3875
|
const old = session.runtime;
|
|
3054
3876
|
void old.close().catch(() => {});
|
|
3877
|
+
let finishPending = () => {};
|
|
3055
3878
|
try {
|
|
3056
3879
|
const transport = createTransport(options, session.runtimeKind, session.mapping.workdir, nativeEnvironment(options, session.mapping.env), session.mapping.acp, session.mapping.antigravity);
|
|
3057
3880
|
session.runtime = transport;
|
|
3058
|
-
|
|
3881
|
+
finishPending = beginPending(session);
|
|
3059
3882
|
wire(sessionId, session, transport);
|
|
3060
3883
|
await transport.initialize();
|
|
3061
3884
|
const config = await configOf(session);
|
|
3062
|
-
if (session.closed) return void transport.close().catch(() => {});
|
|
3063
|
-
await transport.request('thread/resume', { ...config, threadId: session.threadId });
|
|
3064
|
-
if (session.closed) return void transport.close().catch(() => {});
|
|
3065
|
-
session.pending = false;
|
|
3885
|
+
if (session.closed) { finishPending(); return void transport.close().catch(() => {}); }
|
|
3886
|
+
await transport.request('thread/resume', { ...config, threadId: session.threadId, ...(session.base ? { base: session.base } : {}) });
|
|
3887
|
+
if (session.closed) { finishPending(); return void transport.close().catch(() => {}); }
|
|
3066
3888
|
session.buffered = [];
|
|
3889
|
+
finishPending();
|
|
3067
3890
|
runLog(rootOf(sessionId), { event: 'session.revived', sessionId, agent: session.mapping.agent.name });
|
|
3068
|
-
if (session.parked &&
|
|
3891
|
+
if (session.parked && session.parked === interrupted) {
|
|
3069
3892
|
session.parked.prompt = `ALP restarted your ${harness} process after it stopped in the middle of your turn. Continue where you left off: your earlier work in this session and its files are intact.${session.parent ? ' Finish with alp_handoff as before.' : ''}`;
|
|
3070
3893
|
continueParked(sessionId, session);
|
|
3071
3894
|
}
|
|
3072
3895
|
} catch (failure) {
|
|
3073
|
-
|
|
3896
|
+
finishPending();
|
|
3074
3897
|
session.parked = undefined;
|
|
3075
3898
|
runLog(rootOf(sessionId), { event: 'session.revive_failed', sessionId, agent: session.mapping.agent.name, error: errorData(failure).message });
|
|
3076
3899
|
failSession(sessionId, session, error);
|
|
3077
3900
|
}
|
|
3078
3901
|
}
|
|
3079
3902
|
|
|
3903
|
+
/**
|
|
3904
|
+
* Why a root cannot have its native process restarted now, or undefined when it can: the seam that
|
|
3905
|
+
* rebind (a rewind), a reload (G2: rebind(id, its own binding)) and a live model or team change (D)
|
|
3906
|
+
* share. Its whole tree must be idle: an open root with no turn, opening or pending prompt, child,
|
|
3907
|
+
* assignment, question to the user, unread or held mail, parked work, or review by its supervisor.
|
|
3908
|
+
*/
|
|
3909
|
+
function restartRefusal(sessionId: string, session: Session | undefined): string | undefined {
|
|
3910
|
+
if (!session || session.closed) return 'The session is not open';
|
|
3911
|
+
if (session.parent || session.role === 'supervisor') return 'Only a root session can be restarted';
|
|
3912
|
+
if (session.pending) return 'The session is still opening or restarting';
|
|
3913
|
+
if (session.active) return 'A turn is running';
|
|
3914
|
+
if (session.children.size || session.assignments.size) return 'Assignments are still running';
|
|
3915
|
+
if ([...userQuestions.values()].some(pending => pending.question.rootId === sessionId && !pending.gate)) return 'A question to the user waits for an answer';
|
|
3916
|
+
// Mail a lifecycle hold keeps waits for its release, then reaches the session's new conversation.
|
|
3917
|
+
if ((hasActiveMail(session) || session.wakeHeld) && !session.lifecycleHolds) return MAIL_WAITS;
|
|
3918
|
+
if (session.parked || session.parkReason) return 'The session is parked';
|
|
3919
|
+
if (reviewing(session)) return REVIEWING;
|
|
3920
|
+
return undefined;
|
|
3921
|
+
}
|
|
3922
|
+
|
|
3923
|
+
/**
|
|
3924
|
+
* Restarts a live session's native process on `binding` (ALPD §31, as revive does): the old process
|
|
3925
|
+
* stops first, so no two processes ever hold the session's conversation, then a new one resumes
|
|
3926
|
+
* `binding` and replaces it, keeping the session id, configuration and viewers. Throws, leaving the
|
|
3927
|
+
* session without a process, when the new one cannot resume; the caller reopens or fails it. The
|
|
3928
|
+
* caller checks restartRefusal and runs this in the operation queue. `verify`: a Claude conversation
|
|
3929
|
+
* without a transcript (or base) is refused rather than left to Claude, which would refuse it at boot
|
|
3930
|
+
* or start it empty; reopening the binding a session already ran on resumes it as revive does.
|
|
3931
|
+
* `shape`: the configuration the new process runs with, when not the session's own (a live configure,
|
|
3932
|
+
* §12.9); the session itself keeps its own until its caller sees the restart through. No `binding`:
|
|
3933
|
+
* a new conversation starts (a root reconfigured before its first turn has none to keep). Answers
|
|
3934
|
+
* what the runtime answered (Codex: the model and effort it resumed the thread with).
|
|
3935
|
+
*/
|
|
3936
|
+
async function restartNative(sessionId: string, session: Session, binding: NativeBinding | undefined, verify = true, shape?: Pick<Session, 'mapping' | 'graph' | 'spec'>) {
|
|
3937
|
+
const old = session.runtime;
|
|
3938
|
+
const finishPending = beginPending(session);
|
|
3939
|
+
await old.close().catch(() => {});
|
|
3940
|
+
const transport = createTransport(options, session.runtimeKind, session.mapping.workdir, nativeEnvironment(options, session.mapping.env), session.mapping.acp, session.mapping.antigravity);
|
|
3941
|
+
// Not wired before it resumes: a failure now fails this restart, not the session.
|
|
3942
|
+
let failure: unknown;
|
|
3943
|
+
transport.onFailure(error => { failure ??= error; });
|
|
3944
|
+
session.runtime = transport;
|
|
3945
|
+
let result: any;
|
|
3946
|
+
try {
|
|
3947
|
+
await transport.initialize();
|
|
3948
|
+
const config = await configOf(shape ? { ...session, ...shape } : session);
|
|
3949
|
+
noteInstructions(sessionId, session, config.developerInstructions);
|
|
3950
|
+
if (session.closed) throw new Error('Session closed during restart');
|
|
3951
|
+
result = binding
|
|
3952
|
+
? await transport.request('thread/resume', {
|
|
3953
|
+
...config, threadId: binding.threadId,
|
|
3954
|
+
...(binding.base ? { base: binding.base } : verify && session.runtimeKind === 'claude' ? { requireHistory: true } : {}),
|
|
3955
|
+
})
|
|
3956
|
+
: await transport.request('thread/start', { ...config, ephemeral: !(shape ?? session).mapping.persist && !(shape ?? session).mapping.keepThread });
|
|
3957
|
+
if (failure) throw failure;
|
|
3958
|
+
if (session.closed) throw new Error('Session closed during restart');
|
|
3959
|
+
if (binding && result?.thread?.id !== undefined && result.thread.id !== binding.threadId) throw new Error(`${label(session.runtimeKind)} resumed ${result.thread.id} instead of ${binding.threadId}`);
|
|
3960
|
+
if (!binding && typeof result?.thread?.id !== 'string') throw new Error(`${label(session.runtimeKind)} started no conversation`);
|
|
3961
|
+
} catch (error) {
|
|
3962
|
+
await transport.close().catch(() => {});
|
|
3963
|
+
// Not pending any more: mail that waited runs again in the operation queue, after this restart's
|
|
3964
|
+
// caller (which reopens or fails the session) is through.
|
|
3965
|
+
finishPending();
|
|
3966
|
+
throw error;
|
|
3967
|
+
}
|
|
3968
|
+
session.threadId = binding ? binding.threadId : result.thread.id;
|
|
3969
|
+
if (binding?.base) session.base = binding.base;
|
|
3970
|
+
else delete session.base;
|
|
3971
|
+
session.buffered = [];
|
|
3972
|
+
wire(sessionId, session, transport);
|
|
3973
|
+
finishPending();
|
|
3974
|
+
return result;
|
|
3975
|
+
}
|
|
3976
|
+
|
|
3977
|
+
/** rebind(): moves an idle root to another native conversation, or reopens its own; see AlpRuntime.rebind. */
|
|
3978
|
+
async function rebindSession(sessionId: string, binding: NativeBinding) {
|
|
3979
|
+
const session = sessions.get(sessionId);
|
|
3980
|
+
const refusal = restartRefusal(sessionId, session);
|
|
3981
|
+
if (refusal) throw new ConversationError('session_busy', refusal);
|
|
3982
|
+
if (!plainObject(binding, ['threadId', 'base']) || typeof binding.threadId !== 'string' || !binding.threadId ||
|
|
3983
|
+
(binding.base !== undefined && (!plainObject(binding.base, ['threadId', 'at']) || typeof binding.base.threadId !== 'string' || !binding.base.threadId || (binding.base.at !== undefined && typeof binding.base.at !== 'string')))) {
|
|
3984
|
+
throw new Error('A binding needs a threadId, and a base only with a threadId and an optional at');
|
|
3985
|
+
}
|
|
3986
|
+
if (binding.base && session!.runtimeKind !== 'claude') throw new ConversationError('runtime_unsupported', `A ${label(session!.runtimeKind)} session has no base conversation`);
|
|
3987
|
+
const live = session!;
|
|
3988
|
+
const previous: NativeBinding = { threadId: live.threadId, ...(live.base ? { base: live.base } : {}) };
|
|
3989
|
+
try {
|
|
3990
|
+
await restartNative(sessionId, live, binding);
|
|
3991
|
+
} catch (error) {
|
|
3992
|
+
runLog(rootOf(sessionId), { event: 'session.rebind_failed', sessionId, agent: live.mapping.agent.name, threadId: binding.threadId, error: errorData(error).message });
|
|
3993
|
+
try {
|
|
3994
|
+
if (live.closed) throw error;
|
|
3995
|
+
await restartNative(sessionId, live, previous, false);
|
|
3996
|
+
} catch (reopen) {
|
|
3997
|
+
// Neither conversation opens: the session fails as a provider failure does.
|
|
3998
|
+
live.pending = false;
|
|
3999
|
+
if (!live.closed) failSession(sessionId, live, reopen);
|
|
4000
|
+
}
|
|
4001
|
+
if (error instanceof ConversationError) throw error;
|
|
4002
|
+
throw new ConversationError('native_refused', `The conversation could not be opened: ${errorData(error).message}`, { outcomeUnknown: !!(error as { outcomeUnknown?: boolean })?.outcomeUnknown });
|
|
4003
|
+
}
|
|
4004
|
+
runLog(rootOf(sessionId), { event: 'session.rebound', sessionId, agent: live.mapping.agent.name, from: previous.threadId, threadId: binding.threadId });
|
|
4005
|
+
const updated = snapshot(sessionId, live);
|
|
4006
|
+
emit(sessionId, { type: 'session.updated', session: updated });
|
|
4007
|
+
return updated;
|
|
4008
|
+
}
|
|
4009
|
+
|
|
4010
|
+
/** reload(): restarts an idle root's native process on its own conversation; see AlpRuntime.reload. */
|
|
4011
|
+
async function reloadSession(sessionId: string) {
|
|
4012
|
+
const session = sessions.get(sessionId);
|
|
4013
|
+
const refusal = restartRefusal(sessionId, session);
|
|
4014
|
+
if (refusal) throw new ConversationError('session_busy', refusal);
|
|
4015
|
+
const live = session!;
|
|
4016
|
+
if (!live.threadId) throw new ConversationError('runtime_unsupported', 'This session keeps no native conversation to reload');
|
|
4017
|
+
const binding: NativeBinding = { threadId: live.threadId, ...(live.base ? { base: live.base } : {}) };
|
|
4018
|
+
try {
|
|
4019
|
+
await restartNative(sessionId, live, binding);
|
|
4020
|
+
} catch (error) {
|
|
4021
|
+
runLog(rootOf(sessionId), { event: 'session.reload_failed', sessionId, agent: live.mapping.agent.name, threadId: binding.threadId, error: errorData(error).message });
|
|
4022
|
+
// No process holds the conversation now, and none is started without it: the session closes,
|
|
4023
|
+
// its record keeps the binding, and the next open resumes it.
|
|
4024
|
+
if (!live.closed) await closeSession(sessionId).catch(() => {});
|
|
4025
|
+
// Known either way: the session is closed now and its conversation was only read, never changed.
|
|
4026
|
+
throw new ConversationError('native_refused', `The agent could not be restarted on its conversation: ${errorData(error).message}`);
|
|
4027
|
+
}
|
|
4028
|
+
runLog(rootOf(sessionId), { event: 'session.reloaded', sessionId, agent: live.mapping.agent.name, threadId: binding.threadId });
|
|
4029
|
+
const updated = snapshot(sessionId, live);
|
|
4030
|
+
emit(sessionId, { type: 'session.updated', session: updated });
|
|
4031
|
+
return updated;
|
|
4032
|
+
}
|
|
4033
|
+
|
|
4034
|
+
// ------------------------------------------------------------------ live configure (§12.9)
|
|
4035
|
+
|
|
4036
|
+
type ConfigureShape = Pick<Session, 'mapping' | 'graph' | 'spec'>;
|
|
4037
|
+
type ConfigurePlan = {
|
|
4038
|
+
shape: ConfigureShape;
|
|
4039
|
+
current: EffectiveConfig;
|
|
4040
|
+
proposed: EffectiveConfig;
|
|
4041
|
+
changes: ConfigureChange[];
|
|
4042
|
+
refusal?: { reason: ConversationErrorReason; message: string };
|
|
4043
|
+
};
|
|
4044
|
+
|
|
4045
|
+
/** The effective configuration a root runs with, or would with `shape` (§12.9). */
|
|
4046
|
+
async function effectiveConfig(session: Session, shape?: ConfigureShape) {
|
|
4047
|
+
const view = shape ? { ...session, ...shape } : session;
|
|
4048
|
+
const config = await configOf(view);
|
|
4049
|
+
const name = view.mapping.agent.name;
|
|
4050
|
+
return effectiveOf(session.runtimeKind, view.mapping, {
|
|
4051
|
+
delegates: Object.hasOwn(view.graph, name) ? view.graph[name] : [],
|
|
4052
|
+
tools: ((config.dynamicTools ?? []) as Array<{ name?: unknown }>).map(tool => tool.name).filter((tool): tool is string => typeof tool === 'string'),
|
|
4053
|
+
supervisor: supervises(view),
|
|
4054
|
+
instructionsSha: createHash('sha256').update(config.developerInstructions).digest('hex').slice(0, 12),
|
|
4055
|
+
});
|
|
4056
|
+
}
|
|
4057
|
+
|
|
4058
|
+
/**
|
|
4059
|
+
* What a change of model, thinking, team or mode would make of a live root: the configuration resolved
|
|
4060
|
+
* as session.create resolves one (same runtime, agent and conversation), or why it is refused. Reads only.
|
|
4061
|
+
*/
|
|
4062
|
+
async function planConfigure(session: Session, changes: ConfigureChanges): Promise<ConfigurePlan> {
|
|
4063
|
+
const current = await effectiveConfig(session);
|
|
4064
|
+
const same: ConfigurePlan = { shape: { mapping: session.mapping, graph: session.graph, spec: session.spec }, current, proposed: current, changes: [] };
|
|
4065
|
+
const refuse = (reason: ConversationErrorReason, message: string): ConfigurePlan => ({ ...same, refusal: { reason, message } });
|
|
4066
|
+
if (session.parent || session.role === 'supervisor') return refuse('not_root', 'Only a root session is reconfigured; an assignment keeps the team and model it started with');
|
|
4067
|
+
if (!CONFIGURABLE.has(session.runtimeKind)) return refuse('runtime_unsupported', `alpd cannot change a running ${label(session.runtimeKind)} session's model or team; start a new session`);
|
|
4068
|
+
for (const key of ['model', 'thinking', 'team', 'mode'] as const) {
|
|
4069
|
+
const value = changes[key];
|
|
4070
|
+
if (value !== undefined && (typeof value !== 'string' || !value.trim() || value.length > 200)) return refuse('invalid_params', `${key} must be a nonempty name of at most 200 characters`);
|
|
4071
|
+
}
|
|
4072
|
+
const runtimeKind = session.runtimeKind;
|
|
4073
|
+
let model = session.mapping.model;
|
|
4074
|
+
if (changes.model !== undefined) {
|
|
4075
|
+
const named = nativeModelOf(runtimeKind, changes.model.trim());
|
|
4076
|
+
if ('runtime' in named) return refuse('runtime_mismatch', `A session keeps its runtime (${label(runtimeKind)}); to work with ${named.runtime}, start a new session with that model`);
|
|
4077
|
+
if (!offered(runtimeKind, named.model, session.mapping)) return refuse('invalid_params', `The daemon host does not offer ${runtimeKind}:${named.model}; choose one of its models`);
|
|
4078
|
+
model = named.model;
|
|
4079
|
+
}
|
|
4080
|
+
const projectRoot = session.mapping.agent.projectRoot;
|
|
4081
|
+
let team = session.mapping.workflow.mode;
|
|
4082
|
+
if (changes.team !== undefined) {
|
|
4083
|
+
const wanted = teamOf(changes.team.trim());
|
|
4084
|
+
const teams = await listTeams(projectRoot, { library: options.libraryDir, templates: options.templates });
|
|
4085
|
+
if (!teams.some(row => row.id === wanted && !row.error)) return refuse('team_not_found', `The daemon host defines no team '${changes.team.trim()}' for this project`);
|
|
4086
|
+
team = wanted;
|
|
4087
|
+
}
|
|
4088
|
+
const teamChanged = team !== session.mapping.workflow.mode;
|
|
4089
|
+
const mode = changes.mode ?? session.mapping.mode;
|
|
4090
|
+
if (!modes.some(candidate => candidate.id === mode)) return refuse('invalid_params', `Unsupported mode '${mode}'`);
|
|
4091
|
+
// The effort asked for; else the session's own while the model takes it; else the model's default.
|
|
4092
|
+
const takes = (effort: string) => { const efforts = thinkingOptionsFor(runtimeKind as 'codex' | 'claude', model); return !efforts.length || efforts.some(option => option.id === effort); };
|
|
4093
|
+
const thinking = changes.thinking ?? (takes(session.mapping.thinking) ? session.mapping.thinking : undefined);
|
|
4094
|
+
const { restore: _restore, thinking: _thinking, ...kept } = session.spec;
|
|
4095
|
+
const spec: SessionSpec = { ...kept, mode, ...(teamChanged ? { workflow: team } : {}), ...(thinking !== undefined ? { thinking } : {}) };
|
|
4096
|
+
let mapping: ResolvedSession;
|
|
4097
|
+
try {
|
|
4098
|
+
mapping = await resolveSession({
|
|
4099
|
+
...spec,
|
|
4100
|
+
restore: { agent: session.mapping.agent.name, threadId: session.threadId || 'unstarted', runtime: runtimeKind, model, ...(teamChanged ? {} : { workflow: session.mapping.workflow }) },
|
|
4101
|
+
}, { templates: options.templates, library: options.libraryDir, language: options.language, initialize: false });
|
|
4102
|
+
} catch (error) {
|
|
4103
|
+
const message = errorData(error).message;
|
|
4104
|
+
return refuse(/^Team '[^']*' not found/.test(message) ? 'team_not_found' : /different runtime/.test(message) ? 'runtime_mismatch' : /different ALP agent/.test(message) ? 'agent_mismatch' : 'invalid_params', message);
|
|
4105
|
+
}
|
|
4106
|
+
const graph = teamChanged ? (mapping.team ? mapping.team.delegation : await resolveDelegation(projectRoot)) : session.graph;
|
|
4107
|
+
const shape: ConfigureShape = { mapping, graph, spec };
|
|
4108
|
+
const proposed = await effectiveConfig(session, shape);
|
|
4109
|
+
const plan: ConfigurePlan = { shape, current, proposed, changes: changesOf(current, proposed) };
|
|
4110
|
+
const refused = (reason: ConversationErrorReason, message: string): ConfigurePlan => ({ ...plan, refusal: { reason, message } });
|
|
4111
|
+
if (mapping.runtimeKind !== runtimeKind) return refused('runtime_mismatch', `A session keeps its runtime (${label(runtimeKind)}); start a new session for another runtime`);
|
|
4112
|
+
if (mapping.agent.name !== session.mapping.agent.name) return refused('agent_mismatch', 'A session keeps its agent; start a new session for another agent');
|
|
4113
|
+
const agent = session.mapping.agent.name;
|
|
4114
|
+
if (teamChanged && agent === mainOf(session.mapping) && agent !== mainOf(mapping)) return refused('agent_mismatch', `Team ${mapping.team?.label ?? team}'s main agent is ${mainOf(mapping)}, not ${agent}; start a new session with that team`);
|
|
4115
|
+
// Never more permissions: the mode asked for stays within the profile and READ_ONLY_AGENTS, and a
|
|
4116
|
+
// team or effort change never raises the mode the session runs with.
|
|
4117
|
+
if (changes.mode !== undefined && mapping.mode !== changes.mode) return refused('permission_escalation', READ_ONLY_AGENTS.includes(agent) ? 'Advisors and the supervisor must remain read-only' : `Permission profile ${mapping.permissions?.name ?? ''} allows at most ${mapping.permissions?.base ?? mapping.mode}`.replace('profile allows', 'profile allows'));
|
|
4118
|
+
if (changes.mode === undefined && !withinMode(mapping.mode, session.mapping.mode)) return refused('permission_escalation', `The change would run the session in ${mapping.mode}, beyond its ${session.mapping.mode}`);
|
|
4119
|
+
const before = executablesOf(session.mapping);
|
|
4120
|
+
const added = [...executablesOf(mapping)].filter(entry => !before.has(entry));
|
|
4121
|
+
if (added.length) return refused('permission_escalation', `The change would give the session commands it did not run (${added.map(entry => entry.split(':').slice(0, 2).join(' ')).join(', ')}); start a new session for it`);
|
|
4122
|
+
if (proposed.delegates.length && !session.delegation) return refused('invalid_params', 'This session\'s client cannot show assignments, so it cannot take a team that delegates');
|
|
4123
|
+
return plan;
|
|
4124
|
+
}
|
|
4125
|
+
|
|
4126
|
+
/**
|
|
4127
|
+
* Whether the root's native runtime holds a conversation for it (Codex: a turn of its thread; Claude: a
|
|
4128
|
+
* transcript entry). Codex's answer for a thread before its first message ("not materialized yet", "no
|
|
4129
|
+
* rollout found") means none; any other failure to say is refused, never taken as none, so a held
|
|
4130
|
+
* conversation is never left for an empty one.
|
|
4131
|
+
*/
|
|
4132
|
+
async function nativeHistory(session: Session) {
|
|
4133
|
+
if (!session.threadId) return false;
|
|
4134
|
+
if (session.base) return true;
|
|
4135
|
+
const unknown = (error: unknown) => new ConversationError('native_refused', `${label(session.runtimeKind)} could not say whether it holds this session's conversation: ${errorData(error).message}`);
|
|
4136
|
+
if (session.runtimeKind === 'codex') {
|
|
4137
|
+
try {
|
|
4138
|
+
const page = await session.runtime.request('thread/turns/list', { threadId: session.threadId, limit: 1, sortDirection: 'desc' });
|
|
4139
|
+
return Array.isArray(page?.data) && page.data.length > 0;
|
|
4140
|
+
} catch (error) {
|
|
4141
|
+
if (/not materialized|no rollout found/i.test(errorData(error).message)) return false;
|
|
4142
|
+
throw unknown(error);
|
|
4143
|
+
}
|
|
4144
|
+
}
|
|
4145
|
+
if (session.runtimeKind === 'claude') {
|
|
4146
|
+
try {
|
|
4147
|
+
const chain = await session.runtime.request('thread/chain', { threadId: session.threadId, cwd: session.mapping.workdir });
|
|
4148
|
+
return Array.isArray(chain?.entries) && chain.entries.length > 0;
|
|
4149
|
+
} catch (error) { throw unknown(error); }
|
|
4150
|
+
}
|
|
4151
|
+
return true;
|
|
4152
|
+
}
|
|
4153
|
+
|
|
4154
|
+
/** previewConfigure(): see AlpRuntime.previewConfigure. */
|
|
4155
|
+
async function previewConfigureSession(sessionId: string, changes: ConfigureChanges): Promise<ConfigurePreview> {
|
|
4156
|
+
const session = sessions.get(sessionId);
|
|
4157
|
+
if (!session || session.closed) throw new ConversationError('session_busy', 'The session is not open');
|
|
4158
|
+
const plan = await planConfigure(session, changes ?? {});
|
|
4159
|
+
const busy = plan.changes.length ? restartRefusal(sessionId, session) : undefined;
|
|
4160
|
+
const teams = (await listTeams(session.mapping.agent.projectRoot, { library: options.libraryDir, templates: options.templates }))
|
|
4161
|
+
.filter(team => !team.error)
|
|
4162
|
+
.map(team => ({ id: team.id, label: team.label ?? team.id, ...(team.description ? { description: team.description } : {}) }));
|
|
4163
|
+
return {
|
|
4164
|
+
current: plan.current, proposed: plan.proposed, changes: plan.changes,
|
|
4165
|
+
restart: plan.changes.some(change => change !== 'mode'),
|
|
4166
|
+
allowed: !plan.refusal && !busy,
|
|
4167
|
+
...(plan.refusal ? { reason: plan.refusal.reason as ConfigurePreview['reason'], message: plan.refusal.message } : busy ? { reason: 'session_busy' as const, message: busy } : {}),
|
|
4168
|
+
teams,
|
|
4169
|
+
};
|
|
4170
|
+
}
|
|
4171
|
+
|
|
4172
|
+
/** reconfigure(): see AlpRuntime.reconfigure. */
|
|
4173
|
+
async function reconfigureSession(sessionId: string, changes: ConfigureChanges, { fresh = false, onApplied }: { fresh?: boolean; onApplied?: (result: ConfigureResult) => Promise<void> } = {}): Promise<ConfigureResult> {
|
|
4174
|
+
// Native apply has already succeeded when this runs. A host persistence failure must not enter
|
|
4175
|
+
// the native-refusal rollback path, nor claim that nothing happened.
|
|
4176
|
+
async function persist(result: ConfigureResult) {
|
|
4177
|
+
try { await onApplied?.(result); }
|
|
4178
|
+
catch (error) { throw new ConversationError('native_refused', `The runtime took the configuration but the host could not record it: ${errorData(error).message}`, { outcomeUnknown: true }); }
|
|
4179
|
+
}
|
|
4180
|
+
const session = sessions.get(sessionId);
|
|
4181
|
+
const busy = restartRefusal(sessionId, session);
|
|
4182
|
+
if (busy) throw new ConversationError(session && (session.parent || session.role === 'supervisor') ? 'not_root' : 'session_busy', busy);
|
|
4183
|
+
const live = session!;
|
|
4184
|
+
const plan = await planConfigure(live, changes ?? {});
|
|
4185
|
+
if (plan.refusal) throw new ConversationError(plan.refusal.reason, plan.refusal.message);
|
|
4186
|
+
// alpd's timeline says the root has no turn yet; the runtime must agree before a new conversation
|
|
4187
|
+
// replaces its own (a conversation it holds is resumed, never left behind).
|
|
4188
|
+
const starts = fresh && !(plan.changes.length && await nativeHistory(live));
|
|
4189
|
+
// Its files were read meanwhile: the tree must still be idle.
|
|
4190
|
+
const after = restartRefusal(sessionId, live);
|
|
4191
|
+
if (after) throw new ConversationError('session_busy', after);
|
|
4192
|
+
if (!plan.changes.length) return { session: snapshot(sessionId, live), effective: plan.current, status: 'unchanged', restarted: false };
|
|
4193
|
+
const agent = live.mapping.agent.name;
|
|
4194
|
+
if (plan.changes.every(change => change === 'mode')) {
|
|
4195
|
+
// Permissions alone change as session.configure { mode } changes them, without a restart.
|
|
4196
|
+
await configureSession(sessionId, { mode: plan.shape.mapping.mode }, updated => persist({ session: updated, effective: { ...plan.proposed, instructionsSha: plan.current.instructionsSha }, status: 'applied', restarted: false }));
|
|
4197
|
+
runLog(rootOf(sessionId), { event: 'session.configured', sessionId, agent, changes: plan.changes, mode: plan.shape.mapping.mode });
|
|
4198
|
+
return { session: snapshot(sessionId, live), effective: { ...plan.proposed, instructionsSha: plan.current.instructionsSha }, status: 'applied', restarted: false };
|
|
4199
|
+
}
|
|
4200
|
+
if (!starts && !live.threadId) throw new ConversationError('runtime_unsupported', 'This session keeps no native conversation to continue');
|
|
4201
|
+
const binding: NativeBinding | undefined = starts ? undefined : { threadId: live.threadId, ...(live.base ? { base: live.base } : {}) };
|
|
4202
|
+
const from = { model: live.mapping.model, thinking: live.mapping.thinking, team: live.mapping.workflow.mode, mode: live.mapping.mode };
|
|
4203
|
+
const to = { model: plan.shape.mapping.model, thinking: plan.shape.mapping.thinking, team: plan.shape.mapping.workflow.mode, mode: plan.shape.mapping.mode };
|
|
4204
|
+
let native: any;
|
|
4205
|
+
try {
|
|
4206
|
+
native = await restartNative(sessionId, live, binding, true, plan.shape);
|
|
4207
|
+
// The runtime's own word on what it took: Codex answers the model it resumed (or started) the thread with.
|
|
4208
|
+
if (live.runtimeKind === 'codex' && native?.model !== to.model) throw new ConversationError('native_refused', typeof native?.model === 'string' ? `Codex continued the conversation with ${native.model}, not ${to.model}` : `Codex did not say which model it continued the conversation with, so ${to.model} is not taken`);
|
|
4209
|
+
} catch (error) {
|
|
4210
|
+
runLog(rootOf(sessionId), { event: 'session.configure_failed', sessionId, agent, from, to, error: errorData(error).message });
|
|
4211
|
+
// The session keeps its configuration: a process with it restarts on the same conversation.
|
|
4212
|
+
try {
|
|
4213
|
+
if (live.closed) throw error;
|
|
4214
|
+
await restartNative(sessionId, live, binding, false);
|
|
4215
|
+
} catch (reopen) {
|
|
4216
|
+
// Neither starts: the session fails as a provider failure does; its record keeps the old configuration.
|
|
4217
|
+
live.pending = false;
|
|
4218
|
+
if (!live.closed) failSession(sessionId, live, reopen);
|
|
4219
|
+
}
|
|
4220
|
+
if (error instanceof ConversationError) throw error;
|
|
4221
|
+
throw new ConversationError('native_refused', `The runtime did not take the new configuration; the session keeps its own: ${errorData(error).message}`);
|
|
4222
|
+
}
|
|
4223
|
+
live.mapping = plan.shape.mapping;
|
|
4224
|
+
live.graph = plan.shape.graph;
|
|
4225
|
+
live.spec = plan.shape.spec;
|
|
4226
|
+
// Only Codex answers what it resumed with (its effort applies from the next turn/start); Claude's answer is ALP's own echo.
|
|
4227
|
+
const answered = live.runtimeKind === 'codex' ? { ...(typeof native?.model === 'string' ? { model: native.model } : {}), ...(typeof native?.reasoningEffort === 'string' ? { reasoningEffort: native.reasoningEffort } : {}) } : undefined;
|
|
4228
|
+
runLog(rootOf(sessionId), { event: 'session.configured', sessionId, agent, changes: plan.changes, from, to, threadId: live.threadId, ...(answered ? { native: answered } : {}) });
|
|
4229
|
+
if (plan.changes.includes('team')) {
|
|
4230
|
+
// The old team's supervisor ends at this boundary (it reviews nothing: restartRefusal saw to it);
|
|
4231
|
+
// the new team's, if it has one, starts beside the root as at open.
|
|
4232
|
+
const old = live.supervisor;
|
|
4233
|
+
if (old) { live.supervisor = undefined; await closeSession(old).catch(() => {}); }
|
|
4234
|
+
if (supervises(live)) void enqueue(() => openSupervisor(sessionId));
|
|
4235
|
+
}
|
|
4236
|
+
const updated = snapshot(sessionId, live);
|
|
4237
|
+
const result: ConfigureResult = {
|
|
4238
|
+
session: updated, effective: { ...plan.proposed, ...(live.instructionsSha ? { instructionsSha: live.instructionsSha } : {}) }, status: 'applied', restarted: true,
|
|
4239
|
+
...(answered ? { native: answered } : {}),
|
|
4240
|
+
};
|
|
4241
|
+
await persist(result);
|
|
4242
|
+
emit(sessionId, { type: 'session.updated', session: updated });
|
|
4243
|
+
return result;
|
|
4244
|
+
}
|
|
4245
|
+
|
|
4246
|
+
/** branch(): makes the native conversation a fork or rewind continues; see AlpRuntime.branch. */
|
|
4247
|
+
async function branchConversation(request: BranchRequest): Promise<NativeBinding> {
|
|
4248
|
+
if (closed) throw new Error('Runtime is closed');
|
|
4249
|
+
if (request.runtime !== 'codex' && request.runtime !== 'claude') throw new ConversationError('runtime_unsupported', `${label(request.runtime)} sessions cannot be forked or rewound`);
|
|
4250
|
+
if (!Array.isArray(request.turns) || !request.turns.every(turn => typeof turn === 'string')) throw new Error('branch needs the source turns in order');
|
|
4251
|
+
if (typeof request.source?.threadId !== 'string' || !request.source.threadId) throw new Error('branch needs the source thread');
|
|
4252
|
+
if (typeof request.model !== 'string' || !request.model || !modes.some(candidate => candidate.id === request.mode)) throw new Error('branch needs the model and mode the branch keeps');
|
|
4253
|
+
return request.runtime === 'codex' ? branchCodex(request) : branchClaude(request);
|
|
4254
|
+
}
|
|
4255
|
+
|
|
4256
|
+
/**
|
|
4257
|
+
* A Codex fork, persisted at once (thread/fork), in a short-lived app-server like recall's. The fork
|
|
4258
|
+
* keeps the request's model and settings (Codex otherwise forks with its defaults) and is verified to
|
|
4259
|
+
* end at the expected turn; one that does not is deleted. The source thread is never changed.
|
|
4260
|
+
*/
|
|
4261
|
+
async function branchCodex(request: BranchRequest): Promise<NativeBinding> {
|
|
4262
|
+
const end = codexForkEnd(request);
|
|
4263
|
+
const cwd = request.targetCwd ?? request.cwd;
|
|
4264
|
+
const mode = request.mode;
|
|
4265
|
+
const transport = createTransport(options, 'codex', cwd, nativeEnvironment(options));
|
|
4266
|
+
try {
|
|
4267
|
+
try { await transport.initialize(); }
|
|
4268
|
+
catch (error) { throw new ConversationError('native_refused', `Codex did not start: ${errorData(error).message}`); }
|
|
4269
|
+
let forked: any;
|
|
4270
|
+
try {
|
|
4271
|
+
forked = await transport.request('thread/fork', {
|
|
4272
|
+
threadId: request.source.threadId, ...end.params, ephemeral: false, excludeTurns: true, cwd,
|
|
4273
|
+
model: request.model.replace(/^codex:/, ''),
|
|
4274
|
+
sandbox: mode === 'full-access' ? 'danger-full-access' : nativeMode({ mode, copy: false }),
|
|
4275
|
+
approvalPolicy: codexApproval({ mode, permissions: null }),
|
|
4276
|
+
});
|
|
4277
|
+
} catch (error) { throw codexForkRefusal(error); }
|
|
4278
|
+
const id = forked?.thread?.id;
|
|
4279
|
+
// Forked, but under an id ALP cannot read: it may exist, and nothing can be said of it.
|
|
4280
|
+
if (typeof id !== 'string' || !id) throw new ConversationError('native_refused', 'Codex answered the fork without a thread id', { outcomeUnknown: true });
|
|
4281
|
+
let problem: string | undefined;
|
|
4282
|
+
try {
|
|
4283
|
+
if (forked.thread.forkedFromId != null && forked.thread.forkedFromId !== request.source.threadId) problem = `it was forked from ${forked.thread.forkedFromId}`;
|
|
4284
|
+
else {
|
|
4285
|
+
const page = await transport.request('thread/turns/list', { threadId: id, limit: 1, sortDirection: 'desc' });
|
|
4286
|
+
const last = page?.data?.[0];
|
|
4287
|
+
if (last?.id !== end.last) problem = `it ends at ${last?.id ?? 'no turn'}, not ${end.last}`;
|
|
4288
|
+
else if (last.status === 'inProgress') problem = `its last turn ${last.id} is still running`;
|
|
4289
|
+
}
|
|
4290
|
+
} catch (error) { problem = `it could not be read: ${errorData(error).message}`; }
|
|
4291
|
+
if (!problem) return { threadId: id };
|
|
4292
|
+
const deleted = await transport.request('thread/delete', { threadId: id }).then(() => true, () => false);
|
|
4293
|
+
throw new ConversationError('native_refused', `The Codex fork ${id} could not be verified (${problem}); ${deleted ? 'it was deleted' : 'deleting it failed'}`, { outcomeUnknown: !deleted });
|
|
4294
|
+
} finally {
|
|
4295
|
+
await transport.close().catch(() => {});
|
|
4296
|
+
}
|
|
4297
|
+
}
|
|
4298
|
+
|
|
4299
|
+
/**
|
|
4300
|
+
* A Claude branch, without touching Claude: the cut is validated against the transcript and returned
|
|
4301
|
+
* as a binding whose first prompt makes the fork (resume + forkSession at `at`, under the new id).
|
|
4302
|
+
* A source that is itself still a pending fork stands for its base cut at its own `at`.
|
|
4303
|
+
*/
|
|
4304
|
+
async function branchClaude(request: BranchRequest): Promise<NativeBinding> {
|
|
4305
|
+
const transport = createTransport(options, 'claude', request.cwd, nativeEnvironment(options));
|
|
4306
|
+
try {
|
|
4307
|
+
const read = async (threadId: string): Promise<ChainEntry[]> => {
|
|
4308
|
+
const answer = await transport.request('thread/chain', { threadId, cwd: request.cwd });
|
|
4309
|
+
if (!Array.isArray(answer?.entries)) throw new Error('Claude answered no transcript');
|
|
4310
|
+
return answer.entries;
|
|
4311
|
+
};
|
|
4312
|
+
await transport.initialize();
|
|
4313
|
+
let source = request.source.threadId;
|
|
4314
|
+
let chain = await read(source);
|
|
4315
|
+
if (!chain.length && request.source.base) {
|
|
4316
|
+
source = request.source.base.threadId;
|
|
4317
|
+
chain = pendingChain(request.source.base, await read(source));
|
|
4318
|
+
}
|
|
4319
|
+
return { threadId: randomUUID(), base: { threadId: source, at: claudeCut(chain, request) } };
|
|
4320
|
+
} catch (error) {
|
|
4321
|
+
if (error instanceof ConversationError) throw error;
|
|
4322
|
+
throw new ConversationError('native_refused', `The Claude transcript could not be read: ${errorData(error).message}`);
|
|
4323
|
+
} finally {
|
|
4324
|
+
await transport.close().catch(() => {});
|
|
4325
|
+
}
|
|
4326
|
+
}
|
|
4327
|
+
|
|
3080
4328
|
/** Why recovered sessions were reopened, for what they are told. */
|
|
3081
4329
|
const restartCause = () => options.previousExit?.kind === 'crash' ? 'alpd stopped unexpectedly' : 'alpd restarted';
|
|
3082
4330
|
|
|
@@ -3114,7 +4362,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3114
4362
|
if (assignment.lease && leases.get(assignment.lease)?.assignment === id) leases.delete(assignment.lease);
|
|
3115
4363
|
if (roleOf(parent.mapping, entry.agent) === 'peer') { const root = sessions.get(entry.rootId); if (root) root.peerCount--; }
|
|
3116
4364
|
if (assignment.copy) await removeCopy(assignment.copy).catch(() => {});
|
|
3117
|
-
|
|
4365
|
+
// The worktree predates this recovery and may hold uncommitted work: it stays (t-eae4).
|
|
3118
4366
|
};
|
|
3119
4367
|
try {
|
|
3120
4368
|
if (entry.lease) {
|
|
@@ -3122,7 +4370,14 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3122
4370
|
if (holder && !lineage(entry.parentId).includes(holder.assignment)) throw new Error(`${holder.agent} writes ${entry.lease} now`);
|
|
3123
4371
|
if (!holder) { assignment.lease = entry.lease; leases.set(entry.lease, { assignment: id, agent: entry.agent }); }
|
|
3124
4372
|
}
|
|
3125
|
-
if (entry.worktree)
|
|
4373
|
+
if (entry.worktree) {
|
|
4374
|
+
const { preserved, ...worktree } = await reattachWorktree(entry.worktree);
|
|
4375
|
+
assignment.worktree = worktree;
|
|
4376
|
+
if (preserved) {
|
|
4377
|
+
runLog(entry.rootId, { event: 'worktree.preserved', assignmentId: id, branch: worktree.branch, preserved });
|
|
4378
|
+
post(entry.parentId, { kind: 'note', from: entry.agent, assignment: id, passive: true, body: `Reopening ${id}: its worktree ${worktree.path} had no valid git metadata after the restart, so it was moved aside unchanged to ${preserved} and ${worktree.branch} was checked out again. Recover any uncommitted work from ${preserved}.` });
|
|
4379
|
+
}
|
|
4380
|
+
}
|
|
3126
4381
|
if (entry.copyOf) {
|
|
3127
4382
|
assignment.copy = await createCopy(entry.copyOf, copyRoot, id);
|
|
3128
4383
|
spec = { ...spec, workdir: assignment.copy.workdir };
|
|
@@ -3136,8 +4391,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3136
4391
|
assignment.taskId = entry.taskId;
|
|
3137
4392
|
touchTask(entry.rootId, entry.taskId);
|
|
3138
4393
|
}
|
|
3139
|
-
await openSession(id, { ...spec, restore: { agent: entry.agent, threadId: entry.threadId, runtime: entry.runtime, model: entry.model, workflow: parent.mapping.workflow } }, 'skip', entry.delegation);
|
|
3140
|
-
const child =
|
|
4394
|
+
await openSession(id, { ...spec, restore: { agent: entry.agent, threadId: entry.threadId, runtime: entry.runtime, model: entry.model, workflow: parent.mapping.workflow } }, 'skip', entry.delegation, assignment);
|
|
4395
|
+
const child = assignmentSessions.get(assignment)!;
|
|
4396
|
+
if (sessions.get(id) !== child) throw new Error('Child session was replaced during recovery');
|
|
3141
4397
|
child.settle = (state, error) => void finishAssignment(entry.parentId, parent, assignment, state, error);
|
|
3142
4398
|
if (entry.brief) child.brief = entry.brief;
|
|
3143
4399
|
if (assignment.taskId && writes(entry.mode)) {
|
|
@@ -3158,6 +4414,15 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3158
4414
|
|
|
3159
4415
|
/** An assignment an earlier alpd left running that cannot continue: its task goes back to open, its work stays on its branch. */
|
|
3160
4416
|
async function abandonEntry(entry: LiveEntry, reason: string) {
|
|
4417
|
+
if (entry.worktree || writes(entry.mode)) await assignmentResults.put({
|
|
4418
|
+
assignmentId: entry.assignmentId,
|
|
4419
|
+
checkout: entry.worktree?.checkout ?? entry.lease ?? entry.spec.writeRoot ?? entry.spec.workdir ?? entry.project,
|
|
4420
|
+
...(entry.worktree ? { worktree: entry.worktree.path } : {}),
|
|
4421
|
+
...(!entry.worktree ? { result: {
|
|
4422
|
+
agent: entry.agent, status: 'abandoned', finishedAt: new Date().toISOString(), project: entry.project, requesters: sessions.has(entry.parentId) ? lineage(entry.parentId) : [entry.parentId],
|
|
4423
|
+
...(entry.taskId ? { taskId: entry.taskId } : {}), brief: cut(entry.brief ?? '', RESULT_EVIDENCE_CHARS), summary: cut(JSON.stringify({ reason }), RESULT_EVIDENCE_CHARS),
|
|
4424
|
+
} } : {}),
|
|
4425
|
+
});
|
|
3161
4426
|
await inFlight.remove(entry.assignmentId);
|
|
3162
4427
|
const parent = sessions.get(entry.parentId);
|
|
3163
4428
|
let task: Record<string, unknown> | undefined;
|
|
@@ -3204,7 +4469,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3204
4469
|
: '';
|
|
3205
4470
|
const proceed = (sessionId: string, session: Session, text: string) => {
|
|
3206
4471
|
if (options.recoveryResume === false || pauseOf(session.runtimeKind)) {
|
|
3207
|
-
session.parked = { reason: cause, since: Date.now(), prompt: text };
|
|
4472
|
+
session.parked = { reason: cause, since: Date.now(), prompt: text, ...(options.recoveryResume !== false ? { pause: { scope: paused.all ? 'all' as const : session.runtimeKind } } : {}) };
|
|
3208
4473
|
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
3209
4474
|
runLog(rootId, { event: 'assignment.parked', assignmentId: sessionId, agent: session.mapping.agent.name, reason: cause });
|
|
3210
4475
|
const outcome = outcomes.find(entry => entry.assignmentId === sessionId);
|
|
@@ -3223,16 +4488,24 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3223
4488
|
if (parkedRoot) {
|
|
3224
4489
|
root.parked = { reason: parkedRoot, since: Date.now() };
|
|
3225
4490
|
emit(rootId, { type: 'session.updated', session: snapshot(rootId, root) });
|
|
3226
|
-
|
|
4491
|
+
// Legacy persisted reasons carry no pause provenance. Only an explicit session prompt
|
|
4492
|
+
// can release them, including old quota/process parks; never infer scope from text or flags.
|
|
3227
4493
|
} else if (continueRoot) proceed(rootId, root, `ALP: ${cause} during your turn, and reopened this session. Continue the user's request where you stopped.${listed(resumed.get(rootId))}`);
|
|
3228
4494
|
else for (const assignment of resumed.get(rootId) ?? []) post(rootId, { kind: 'note', from: assignment.agent, assignment: assignment.id, passive: true, body: `${cause}; ALP reopened this assignment and it continues. It reports when done.` });
|
|
3229
4495
|
const failed = outcomes.filter(outcome => outcome.outcome === 'failed');
|
|
3230
|
-
if (entries.length || continueRoot) {
|
|
3231
|
-
const parked = outcomes.
|
|
4496
|
+
if (entries.length || continueRoot || parkedRoot) {
|
|
4497
|
+
const parked = outcomes.flatMap(outcome => {
|
|
4498
|
+
const park = outcome.outcome === 'parked' ? sessions.get(outcome.assignmentId)?.parked : undefined;
|
|
4499
|
+
return park ? [park] : [];
|
|
4500
|
+
});
|
|
4501
|
+
if ((continueRoot || parkedRoot) && root.parked) parked.push(root.parked);
|
|
4502
|
+
const next = parked.some(park => !park.pause)
|
|
4503
|
+
? 'send an explicit prompt to each parked session to continue it: alp send <session> --prompt <text>'
|
|
4504
|
+
: 'run alp resume to continue them';
|
|
3232
4505
|
notice(failed.length ? 'warning' : 'info',
|
|
3233
4506
|
`ALP: ${cause}${options.previousExit?.at ? ` (around ${options.previousExit.at})` : ''}. ` +
|
|
3234
|
-
`${entries.length - failed.length} of ${entries.length} running assignments reopened${continueRoot ? ', and this session' : ''}` +
|
|
3235
|
-
`${parked ?
|
|
4507
|
+
`${entries.length - failed.length} of ${entries.length} running assignments reopened${continueRoot || parkedRoot ? ', and this session' : ''}` +
|
|
4508
|
+
`${parked.length ? `; they wait parked: ${next}` : ''}.` +
|
|
3236
4509
|
`${failed.length ? ` Could not continue: ${failed.map(outcome => `${outcome.agent} ${outcome.assignmentId} (${outcome.error})`).join('; ')}; their tasks went back to open.` : ''}`,
|
|
3237
4510
|
root.mapping.agent.projectRoot);
|
|
3238
4511
|
}
|
|
@@ -3254,7 +4527,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3254
4527
|
return session;
|
|
3255
4528
|
}
|
|
3256
4529
|
|
|
3257
|
-
async function configureSession(sessionId: string, changes: { mode?: string }) {
|
|
4530
|
+
async function configureSession(sessionId: string, changes: { mode?: string }, beforeUpdated?: (session: SessionSnapshot) => Promise<void>) {
|
|
3258
4531
|
const session = openOf(sessionId);
|
|
3259
4532
|
if (session.active || session.pending || session.children.size) throw new Error('Wait for the current turn and child sessions to finish before changing permissions');
|
|
3260
4533
|
const mode = changes.mode ?? session.mapping.mode;
|
|
@@ -3265,11 +4538,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3265
4538
|
}
|
|
3266
4539
|
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
3267
4540
|
if (parent && !withinMode(mode, parent.mapping.mode)) throw new Error('Child cannot exceed parent permissions');
|
|
3268
|
-
if (session.runtimeKind === '
|
|
3269
|
-
if (session.runtimeKind === 'claude') await session.runtime.request('session/configure', { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
|
|
4541
|
+
if (session.runtimeKind === 'claude' || session.runtimeKind === 'antigravity') await session.runtime.request('session/configure', { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
|
|
3270
4542
|
session.mapping.mode = mode;
|
|
3271
4543
|
session.spec = { ...session.spec, mode };
|
|
3272
4544
|
const updated = snapshot(sessionId, session);
|
|
4545
|
+
if (beforeUpdated) await beforeUpdated(updated);
|
|
3273
4546
|
emit(sessionId, { type: 'session.updated', session: updated });
|
|
3274
4547
|
return updated;
|
|
3275
4548
|
}
|
|
@@ -3286,6 +4559,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3286
4559
|
session.userStopped = true;
|
|
3287
4560
|
session.parked = undefined;
|
|
3288
4561
|
session.parkReason = undefined;
|
|
4562
|
+
session.parkPause = undefined;
|
|
4563
|
+
session.resumeHeld = undefined;
|
|
3289
4564
|
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
3290
4565
|
approvalCancellation.set(session, (approvalCancellation.get(session) ?? 0) + 1);
|
|
3291
4566
|
cancelQuestions(sessionId);
|
|
@@ -3304,7 +4579,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3304
4579
|
|
|
3305
4580
|
await Promise.all(
|
|
3306
4581
|
[...session.children].map(
|
|
3307
|
-
closeSession,
|
|
4582
|
+
id => closeSession(id),
|
|
3308
4583
|
),
|
|
3309
4584
|
);
|
|
3310
4585
|
|
|
@@ -3323,6 +4598,31 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3323
4598
|
}
|
|
3324
4599
|
}
|
|
3325
4600
|
|
|
4601
|
+
// Shared by ordinary prompts and the scheduler's queue-scoped sender.
|
|
4602
|
+
async function promptSession(sessionId: string, input: PromptInput, flushing = false): Promise<void> {
|
|
4603
|
+
const session = sessions.get(sessionId);
|
|
4604
|
+
// While main writes its checkpoint and compacts, the user's words wait for the compaction's end (t-0e56).
|
|
4605
|
+
if (!flushing && session && !session.parent && (session.compacting || session.compactBuffer?.length)) {
|
|
4606
|
+
if (!session.seen.has(input.clientMessageId) && !session.compactBuffer?.some(held => held.clientMessageId === input.clientMessageId)) (session.compactBuffer ??= []).push(input);
|
|
4607
|
+
return;
|
|
4608
|
+
}
|
|
4609
|
+
const parked = session?.parked;
|
|
4610
|
+
try {
|
|
4611
|
+
const prompt = session?.active && session.resumedTurn === session.active && input.delivery === 'auto'
|
|
4612
|
+
? { ...input, delivery: 'steer' as const } : input;
|
|
4613
|
+
await startPrompt(sessionId, prompt, 'user');
|
|
4614
|
+
if (session && parked && session.parked === parked) {
|
|
4615
|
+
session.parked = undefined;
|
|
4616
|
+
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
4617
|
+
}
|
|
4618
|
+
} catch (error) {
|
|
4619
|
+
const session = sessions.get(sessionId);
|
|
4620
|
+
if (session?.seen.has(input.clientMessageId)) return;
|
|
4621
|
+
session?.seen.add(input.clientMessageId);
|
|
4622
|
+
emit(sessionId, { type: 'prompt.failed', clientMessageId: input.clientMessageId, error: errorData(error) });
|
|
4623
|
+
}
|
|
4624
|
+
}
|
|
4625
|
+
|
|
3326
4626
|
/** Starts a turn or steers the running one; throws when the prompt was not delivered. */
|
|
3327
4627
|
async function startPrompt(sessionId: string, prompt: PromptInput, origin: TurnOrigin, wake?: MailEvent[]) {
|
|
3328
4628
|
const session = openOf(sessionId);
|
|
@@ -3335,8 +4635,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3335
4635
|
return;
|
|
3336
4636
|
}
|
|
3337
4637
|
|
|
3338
|
-
if (prompt.content.some(content => content.type !== 'text' && content.type !== 'image')) {
|
|
3339
|
-
throw new Error('Only text and
|
|
4638
|
+
if (prompt.content.some(content => content.type !== 'text' && content.type !== 'image' && content.type !== 'attachment')) {
|
|
4639
|
+
throw new Error('Only text, image and attachment prompts are supported');
|
|
3340
4640
|
}
|
|
3341
4641
|
// Inline images only, never a path or URL: the native input gets a data URL ALP builds itself.
|
|
3342
4642
|
const images = prompt.content.filter(content => content.type === 'image') as Array<{ type: 'image'; mimeType: string; data: string }>;
|
|
@@ -3352,6 +4652,27 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3352
4652
|
}
|
|
3353
4653
|
}
|
|
3354
4654
|
|
|
4655
|
+
// Attachments (§12.6): descriptors alpd resolved and pinned for this session, never a path. Each
|
|
4656
|
+
// gets a read-only copy staged from alpd's verified bytes before the turn names it.
|
|
4657
|
+
const attached: Array<{ attachment: RuntimeAttachment; staged: string }> = [];
|
|
4658
|
+
const attachmentParts = prompt.content.filter(content => content.type === 'attachment');
|
|
4659
|
+
if (attachmentParts.length) {
|
|
4660
|
+
if (!attachmentRoutes(session).includes('file.path') || !stager || !attachmentReader) {
|
|
4661
|
+
throw new Error(`${session.runtimeKind === 'acp' ? 'This ACP agent' : session.runtimeKind[0].toUpperCase() + session.runtimeKind.slice(1)} cannot read attached files; they stay stored and the message was not sent`);
|
|
4662
|
+
}
|
|
4663
|
+
// Told once per session, when it first stages, never at alpd's start (its log stays quiet until there is something to say).
|
|
4664
|
+
if (!stagingWarned.has(sessionId)) {
|
|
4665
|
+
stagingWarned.add(sessionId);
|
|
4666
|
+
const exposed = stagingExposure(stager.root, [session.mapping.workdir, os.tmpdir(), '/tmp']);
|
|
4667
|
+
if (exposed) log.warn(`the attachment staging directory is inside ${exposed === session.mapping.workdir ? 'this session\'s workspace' : 'the temp directory'}, which sandboxed sessions may write: a tool could change a staged copy before it is read; keep ALP_HOME outside both (default ~/.alp)`, { code: 'ALP_ATTACHMENT_STAGE_EXPOSED', sessionId });
|
|
4668
|
+
}
|
|
4669
|
+
for (const part of attachmentParts) {
|
|
4670
|
+
const attachment = runtimeAttachment(part);
|
|
4671
|
+
if (!attachment) throw new Error('An attachment in a prompt must be one alpd resolved');
|
|
4672
|
+
attached.push({ attachment, staged: await stager.stage(attachmentReader, attachment, sessionId) });
|
|
4673
|
+
}
|
|
4674
|
+
}
|
|
4675
|
+
|
|
3355
4676
|
if (
|
|
3356
4677
|
prompt.delivery === 'steer' &&
|
|
3357
4678
|
!session.active
|
|
@@ -3393,6 +4714,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3393
4714
|
) {
|
|
3394
4715
|
session.text.clear();
|
|
3395
4716
|
session.toolCalls.clear();
|
|
4717
|
+
if (!/^alp-wake-compact-/.test(prompt.clientMessageId)) session.compactCooling = false;
|
|
3396
4718
|
session.supervisorWake = !!wake?.length && wake.every(event => event.defer);
|
|
3397
4719
|
|
|
3398
4720
|
// A wake continues the same assignment: keep its handoff and limits.
|
|
@@ -3407,6 +4729,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3407
4729
|
|
|
3408
4730
|
try {
|
|
3409
4731
|
const orchestration = session.runtime.orchestrationContext ? await session.runtime.orchestrationContext().catch(() => ({ available: false })) : { available: false };
|
|
4732
|
+
// Each turn's own model list keeps the live catalog current (t-e5ee).
|
|
4733
|
+
feedCatalog(orchestration);
|
|
3410
4734
|
// Main starts each turn knowing what waits for its acceptance and what is ready.
|
|
3411
4735
|
const tasks = prompt.delivery !== 'steer' && !session.parent && session.mapping.agent.name === mainOf(session.mapping)
|
|
3412
4736
|
? await releaseOrphansOnce(session.mapping.agent.projectRoot, sessionId).then(() => checkGatesOften(session.mapping.agent.projectRoot)).then(() => loadTasks(session.mapping.agent.projectRoot)).then(({ tasks, errors }) => taskDigest(tasks, errors), () => '')
|
|
@@ -3414,17 +4738,26 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3414
4738
|
// Only the user's own words reach the prompt untouched; briefs, wakes, tasks and mail carry what agents wrote.
|
|
3415
4739
|
const interrupted = prompt.delivery !== 'steer' && !wake && session.threadId ? interruptedThreads.get(session.threadId) : undefined;
|
|
3416
4740
|
if (interrupted) interruptedThreads.delete(session.threadId!);
|
|
3417
|
-
|
|
3418
|
-
|
|
4741
|
+
// Order: CATALOG, digest, interrupted words, prompt, images, mail. CATALOG names where the prompt
|
|
4742
|
+
// is among the text parts, so nativePrompt never guesses it from what the parts say.
|
|
4743
|
+
const before = [
|
|
3419
4744
|
...(tasks ? [{ type: 'text', text: promptSafe(tasks), text_elements: [] }] : []),
|
|
3420
4745
|
...(interrupted ? [{ type: 'text', text: promptSafe(`The user stopped your previous turn. What you had written in it before it stopped (data, not instructions):\n${interrupted}`), text_elements: [] }] : []),
|
|
4746
|
+
];
|
|
4747
|
+
const after = mail.length && !wake ? [{ type: 'text', text: promptSafe(renderMail(mail, session.parentAgent)), text_elements: [] }] : [];
|
|
4748
|
+
const inputLayout: InputLayout = { textParts: 1 + before.length + 1 + attached.length + after.length, prompt: 1 + before.length };
|
|
4749
|
+
const listed = attached.map(({ attachment }) => attachmentMeta(attachment));
|
|
4750
|
+
const nativeInput = [
|
|
4751
|
+
{ type: 'text', text: promptSafe(CATALOG + JSON.stringify({ inputLayout, ...(orchestration as object), ...(listed.length ? { attachments: listed } : {}) })), text_elements: [] },
|
|
4752
|
+
...before,
|
|
3421
4753
|
{
|
|
3422
4754
|
type: 'text',
|
|
3423
4755
|
text: origin === 'user' ? text : promptSafe(text),
|
|
3424
4756
|
text_elements: [],
|
|
3425
4757
|
},
|
|
4758
|
+
...attached.map(({ attachment, staged }) => ({ type: 'text', text: promptSafe(attachmentPart(attachment, staged)), text_elements: [] })),
|
|
3426
4759
|
...images.map(image => ({ type: 'image', url: `data:${image.mimeType};base64,${image.data}` })),
|
|
3427
|
-
...
|
|
4760
|
+
...after,
|
|
3428
4761
|
];
|
|
3429
4762
|
|
|
3430
4763
|
const result =
|
|
@@ -3449,6 +4782,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3449
4782
|
clientUserMessageId:
|
|
3450
4783
|
prompt.clientMessageId,
|
|
3451
4784
|
input: nativeInput,
|
|
4785
|
+
// Codex keeps a turn's model and effort for later turns too; ALP names both on every turn (§12.9).
|
|
4786
|
+
...(session.runtimeKind === 'codex' ? { model: session.mapping.model } : {}),
|
|
3452
4787
|
effort:
|
|
3453
4788
|
session.mapping.thinking,
|
|
3454
4789
|
approvalPolicy: codexApproval(session.mapping),
|
|
@@ -3484,10 +4819,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3484
4819
|
id: `user:${prompt.clientMessageId}`,
|
|
3485
4820
|
clientMessageId: prompt.clientMessageId,
|
|
3486
4821
|
text,
|
|
4822
|
+
origin,
|
|
3487
4823
|
...(images.length ? { images: images.length } : {}),
|
|
4824
|
+
...(listed.length ? { attachments: listed } : {}),
|
|
3488
4825
|
},
|
|
3489
4826
|
});
|
|
3490
4827
|
if (origin === 'user' && !session.parent) session.userWaiting ??= Date.now();
|
|
4828
|
+
if (origin === 'user' && !session.parent && text) session.lastUserText = clip(text, 16_000);
|
|
3491
4829
|
if (session.supervisor && origin === 'user') session.journal.push(stamp(`user ${prompt.delivery === 'steer' ? 'steered' : 'asked'} ${session.mapping.agent.name}: ${clip(text, 1500)}`));
|
|
3492
4830
|
// The steer reaches the model once its waiting tool returns; return it now, not when the work ends.
|
|
3493
4831
|
if (prompt.delivery === 'steer' && origin === 'user' && !session.parent) { releaseWaiters(session); releaseQuestions(sessionId); }
|
|
@@ -3532,7 +4870,99 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3532
4870
|
// Threads past their recall time go when the host starts, and after each assignment.
|
|
3533
4871
|
if (options.recallFile) void forgetExpired();
|
|
3534
4872
|
|
|
3535
|
-
|
|
4873
|
+
const api = {
|
|
4874
|
+
registerWorkspace: directory => enqueue(async () => {
|
|
4875
|
+
try { await assignmentResults.register(await realpath(directory)); }
|
|
4876
|
+
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot register workspace result ownership'); }
|
|
4877
|
+
}),
|
|
4878
|
+
withWorkspaceMutation: <T>(directory: string, run: () => Promise<T>, adoption?: typeof ADOPTION): Promise<T> => {
|
|
4879
|
+
// Reserve before enqueue/await: in-flight admission causes refusal, future admission cannot start.
|
|
4880
|
+
if (workspaceMutation || admitting) return Promise.reject(new WorkspaceMutationError('workspace_busy', 'A session or assignment is opening; retry after it finishes'));
|
|
4881
|
+
workspaceMutation = true;
|
|
4882
|
+
return enqueue(async () => {
|
|
4883
|
+
const target = await realpath(directory).catch(() => refuseMutation('workspace_busy', `Cannot resolve workspace ${directory}; inspect its directory before removing it`));
|
|
4884
|
+
let resultLedger: Awaited<ReturnType<typeof assignmentResults.inspect>>;
|
|
4885
|
+
try { resultLedger = await assignmentResults.inspect(); }
|
|
4886
|
+
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot inspect permanent assignment results'); }
|
|
4887
|
+
// Only adoptWorkspace passes ADOPTION, to certify an old checkout after every check below.
|
|
4888
|
+
if (!resultLedger!.workspaces.includes(target) && adoption !== ADOPTION) refuseMutation('workspace_assignment_result', 'Workspace predates authoritative assignment tracking; an audited migration is required before removal');
|
|
4889
|
+
const canonical = (value: string): string => {
|
|
4890
|
+
try { return realpathSync(value); }
|
|
4891
|
+
catch (error) {
|
|
4892
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') refuseMutation('workspace_assignment_result', `Cannot resolve assignment path ${value}; inspect it before removing the workspace`);
|
|
4893
|
+
const parent = path.dirname(value);
|
|
4894
|
+
if (parent === value) throw error;
|
|
4895
|
+
return path.join(canonical(parent), path.basename(value));
|
|
4896
|
+
}
|
|
4897
|
+
};
|
|
4898
|
+
const overlaps = (value: string | undefined) => {
|
|
4899
|
+
if (value === undefined) return false;
|
|
4900
|
+
if (typeof value !== 'string' || !value) refuseMutation('workspace_assignment_result', 'Invalid assignment path; repair runtime persistence before removing the workspace');
|
|
4901
|
+
if (!path.isAbsolute(value)) refuseMutation('workspace_assignment_result', 'Assignment path is not absolute; inspect runtime persistence before removing the workspace');
|
|
4902
|
+
const owner = canonical(value);
|
|
4903
|
+
const contains = (parent: string, child: string) => {
|
|
4904
|
+
const relative = path.relative(parent, child);
|
|
4905
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
4906
|
+
};
|
|
4907
|
+
return contains(target, owner) || contains(owner, target);
|
|
4908
|
+
};
|
|
4909
|
+
// A handled result no longer holds its paths; its evidence stays in the ledger until archived.
|
|
4910
|
+
for (const entry of resultLedger!.results) if (!entry.handled && (overlaps(entry.checkout) || overlaps(entry.worktree))) refuseMutation('workspace_assignment_result', `Resolve permanent assignment result ${entry.assignmentId} before removing ${directory}`);
|
|
4911
|
+
// A recall entry outlives the result it describes by up to its own 14 days; once the result is handled, it holds nothing.
|
|
4912
|
+
const resolved = async (assignmentId: string) => {
|
|
4913
|
+
if (resultLedger!.results.some(owner => owner.assignmentId === assignmentId && owner.handled)) return true;
|
|
4914
|
+
try { return !!(await assignmentResults.archived(assignmentId)); }
|
|
4915
|
+
catch { return refuseMutation('workspace_assignment_result', 'Cannot inspect the assignment result archive; repair it before removing the workspace'); }
|
|
4916
|
+
};
|
|
4917
|
+
for (const [project, pins] of loadedBoards) for (const pin of pins) {
|
|
4918
|
+
if (pin.kind === 'claim' && live(pin) && pin.paths?.some(value => overlaps(path.resolve(project, value)))) refuseMutation('workspace_claimed', `Release claim ${pin.id} before removing ${directory}`);
|
|
4919
|
+
}
|
|
4920
|
+
for (const [checkout, holder] of leases) if (overlaps(checkout)) refuseMutation('workspace_leased', `Assignment ${holder.assignment} holds a write lease in ${directory}`);
|
|
4921
|
+
for (const [id, session] of sessions) {
|
|
4922
|
+
for (const assignment of session.assignments.values()) {
|
|
4923
|
+
if (overlaps(assignment.worktree?.path) || overlaps(assignment.worktree?.checkout) || overlaps(assignment.copy?.path) || overlaps(assignment.copy?.checkout) || overlaps(assignment.writeCheckout) || overlaps(assignment.lease)) refuseMutation('workspace_assignment_result', `Resolve assignment ${assignment.id} before removing ${directory}`);
|
|
4924
|
+
}
|
|
4925
|
+
for (const [assignmentId, pending] of session.worktrees) if (overlaps(pending.worktree.path) || overlaps(pending.worktree.checkout) || overlaps(pending.worktree.workdir)) refuseMutation('workspace_assignment_result', `Merge or preserve assignment ${assignmentId} before removing ${directory}`);
|
|
4926
|
+
if (!session.closed && (overlaps(session.mapping.workdir) || overlaps(session.spec.writeRoot))) refuseMutation('workspace_busy', `Close session ${id} before removing ${directory}`);
|
|
4927
|
+
}
|
|
4928
|
+
const checkLive = (entry: LiveEntry) => {
|
|
4929
|
+
if (overlaps(entry.spec.workdir ?? entry.project) || overlaps(entry.spec.writeRoot) || overlaps(entry.copyOf) || overlaps(entry.lease) || overlaps(entry.worktree?.path) || overlaps(entry.worktree?.checkout) || overlaps(entry.worktree?.workdir)) refuseMutation('workspace_assignment_result', `Resolve recoverable assignment ${entry.assignmentId} before removing ${directory}`);
|
|
4930
|
+
};
|
|
4931
|
+
for (const entry of inFlight.all()) checkLive(entry);
|
|
4932
|
+
for (const entry of inherited) checkLive(entry);
|
|
4933
|
+
// Read disk strictly: the normal books intentionally tolerate damaged records.
|
|
4934
|
+
for (const [file, kind] of [[options.liveFile, 'live'], [options.recallFile, 'recall']] as const) {
|
|
4935
|
+
if (!file) continue;
|
|
4936
|
+
let entries: unknown;
|
|
4937
|
+
try { entries = JSON.parse(await readFile(file, 'utf8')); }
|
|
4938
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; throw new WorkspaceMutationError('workspace_assignment_result', `Cannot inspect ${file}; repair assignment persistence before removing the workspace`); }
|
|
4939
|
+
if (!Array.isArray(entries)) refuseMutation('workspace_assignment_result', `Invalid assignment book ${file}`);
|
|
4940
|
+
for (const entry of entries as any[]) {
|
|
4941
|
+
if (!entry || typeof entry.assignmentId !== 'string' || (kind === 'live' ? !entry.spec || typeof entry.spec !== 'object' || Array.isArray(entry.spec) || typeof entry.project !== 'string' : typeof entry.cwd !== 'string')) refuseMutation('workspace_assignment_result', `Invalid assignment record in ${file}`);
|
|
4942
|
+
if (entry.worktree !== undefined && (!entry.worktree || !['path', 'checkout', 'workdir'].every(key => typeof entry.worktree[key] === 'string'))) refuseMutation('workspace_assignment_result', `Invalid worktree result in ${file}`);
|
|
4943
|
+
if (entry.shared !== undefined && (!entry.shared || typeof entry.shared !== 'object' || Array.isArray(entry.shared))) refuseMutation('workspace_assignment_result', `Invalid shared result in ${file}`);
|
|
4944
|
+
if (kind === 'live') checkLive(entry);
|
|
4945
|
+
else if ((overlaps(entry.cwd) || overlaps(entry.shared?.writeRoot)) && !(await resolved(entry.assignmentId))) refuseMutation('workspace_assignment_result', `Preserve retained assignment ${entry.assignmentId} before removing ${directory}`);
|
|
4946
|
+
}
|
|
4947
|
+
}
|
|
4948
|
+
for (const entry of await recalls.all()) if ((overlaps(entry.cwd) || overlaps(entry.shared?.writeRoot)) && !(await resolved(entry.assignmentId))) refuseMutation('workspace_assignment_result', `Preserve retained assignment ${entry.assignmentId} before removing ${directory}`);
|
|
4949
|
+
return await run();
|
|
4950
|
+
}).finally(() => { workspaceMutation = false; });
|
|
4951
|
+
},
|
|
4952
|
+
adoptWorkspace: (directory: string, verify: (canonical: string) => Promise<void>): Promise<void> => api.withWorkspaceMutation(directory, async () => {
|
|
4953
|
+
// A path through a symlink names whatever the link points at today; adopt only the canonical path.
|
|
4954
|
+
if (await realpath(directory) !== directory) refuseMutation('workspace_identity', `Adopt ${directory} by its canonical path`);
|
|
4955
|
+
await verify(directory);
|
|
4956
|
+
try { await assignmentResults.register(directory); }
|
|
4957
|
+
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot register workspace result ownership'); }
|
|
4958
|
+
}, ADOPTION),
|
|
4959
|
+
bindSchedules(handler: ScheduleHandler | undefined) { scheduleHandler = handler; },
|
|
4960
|
+
bindAttachments(reader: AttachmentReader | undefined) { attachmentReader = reader; },
|
|
4961
|
+
takesAttachments(sessionId: string) {
|
|
4962
|
+
const session = sessions.get(sessionId);
|
|
4963
|
+
return !!session && !session.closed && attachmentRoutes(session).includes('file.path');
|
|
4964
|
+
},
|
|
4965
|
+
async dropAttachment(attachmentId: string) { await stager?.drop(attachmentId); },
|
|
3536
4966
|
onEvent(listener) {
|
|
3537
4967
|
listeners.add(listener);
|
|
3538
4968
|
return () => {
|
|
@@ -3544,32 +4974,99 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3544
4974
|
const opened = await openSession(sessionId, spec, history, delegation);
|
|
3545
4975
|
const root = sessions.get(sessionId)!;
|
|
3546
4976
|
// Main starts its supervisor beside it, without delaying its own open.
|
|
3547
|
-
if (supervises(root))
|
|
4977
|
+
if (supervises(root)) {
|
|
4978
|
+
void enqueue(() => openSupervisor(sessionId));
|
|
4979
|
+
void ensureCurateSchedule(sessionId).catch(error => runLog(sessionId, { event: 'curate.schedule.failed', error: errorData(error).message }));
|
|
4980
|
+
}
|
|
3548
4981
|
return opened;
|
|
3549
4982
|
}),
|
|
3550
4983
|
|
|
3551
|
-
prompt: (sessionId, input) => enqueue(
|
|
3552
|
-
|
|
3553
|
-
|
|
3554
|
-
|
|
3555
|
-
const
|
|
3556
|
-
|
|
3557
|
-
|
|
3558
|
-
|
|
3559
|
-
|
|
3560
|
-
|
|
4984
|
+
prompt: (sessionId, input) => enqueue(() => promptSession(sessionId, input)),
|
|
4985
|
+
|
|
4986
|
+
withIdlePrompt: (sessionId, run) => new Promise((resolve, reject) => {
|
|
4987
|
+
void enqueue(async () => {
|
|
4988
|
+
const session = openOf(sessionId);
|
|
4989
|
+
if (session.active || session.pending || session.lifecycleHolds || session.mail.some(event => event.deliveredTurn === STARTING)) { resolve({ busy: true }); return; }
|
|
4990
|
+
// Expose the reservation to lifecycle operations before any durable write can yield.
|
|
4991
|
+
admittedPrompts.add(sessionId);
|
|
4992
|
+
// Keep newly arriving mail unreserved until this admitted prompt has finished preparation.
|
|
4993
|
+
session.lifecycleHolds = (session.lifecycleHolds ?? 0) + 1;
|
|
4994
|
+
let valid = true;
|
|
4995
|
+
let used = false;
|
|
4996
|
+
let sending: Promise<void> | undefined;
|
|
4997
|
+
try {
|
|
4998
|
+
const value = await run(input => {
|
|
4999
|
+
if (!valid || used) return Promise.reject(new Error('The admitted prompt sender is no longer available'));
|
|
5000
|
+
used = true;
|
|
5001
|
+
sending = promptSession(sessionId, input);
|
|
5002
|
+
return sending;
|
|
5003
|
+
});
|
|
5004
|
+
resolve({ busy: false, value });
|
|
5005
|
+
} catch (error) {
|
|
5006
|
+
reject(error);
|
|
5007
|
+
} finally {
|
|
5008
|
+
valid = false;
|
|
5009
|
+
// A timeout of the caller cannot release the queue while its native start is outstanding.
|
|
5010
|
+
try { await sending; }
|
|
5011
|
+
finally {
|
|
5012
|
+
admittedPrompts.delete(sessionId);
|
|
5013
|
+
session.lifecycleHolds = Math.max(0, (session.lifecycleHolds ?? 1) - 1);
|
|
5014
|
+
if (!session.lifecycleHolds && !session.closed && session.wakeHeld) {
|
|
5015
|
+
session.wakeHeld = false;
|
|
5016
|
+
deliver(sessionId, session);
|
|
5017
|
+
}
|
|
5018
|
+
}
|
|
3561
5019
|
}
|
|
3562
|
-
}
|
|
3563
|
-
const session = sessions.get(sessionId);
|
|
3564
|
-
if (session?.seen.has(input.clientMessageId)) return;
|
|
3565
|
-
session?.seen.add(input.clientMessageId);
|
|
3566
|
-
emit(sessionId, { type: 'prompt.failed', clientMessageId: input.clientMessageId, error: errorData(error) });
|
|
3567
|
-
}
|
|
5020
|
+
}).catch(reject);
|
|
3568
5021
|
}),
|
|
3569
5022
|
|
|
3570
5023
|
interrupt: sessionId => enqueue(() => interruptSession(sessionId)),
|
|
5024
|
+
interruptTurn: (sessionId, turnId) => enqueue(async () => {
|
|
5025
|
+
// Compare in the same admission slot as the cancellation, before any side effect or await.
|
|
5026
|
+
if (sessions.get(sessionId)?.active !== turnId) return false;
|
|
5027
|
+
await interruptSession(sessionId);
|
|
5028
|
+
return true;
|
|
5029
|
+
}),
|
|
5030
|
+
|
|
5031
|
+
configure: (sessionId, changes, options) => enqueue(() => configureSession(sessionId, changes, options?.onApplied)),
|
|
5032
|
+
|
|
5033
|
+
branch: request => branchConversation(request),
|
|
5034
|
+
|
|
5035
|
+
rebind: (sessionId, binding) => enqueue(() => rebindSession(sessionId, binding)),
|
|
5036
|
+
|
|
5037
|
+
reload: sessionId => enqueue(() => reloadSession(sessionId)),
|
|
5038
|
+
compact: (sessionId: string) => requestCompact(sessionId),
|
|
5039
|
+
|
|
5040
|
+
previewConfigure: (sessionId, changes) => previewConfigureSession(sessionId, changes),
|
|
3571
5041
|
|
|
3572
|
-
|
|
5042
|
+
reconfigure: (sessionId, changes, options) => enqueue(() => reconfigureSession(sessionId, changes, options)),
|
|
5043
|
+
|
|
5044
|
+
starting: sessionId => {
|
|
5045
|
+
const session = sessions.get(sessionId);
|
|
5046
|
+
return !!session && !session.closed && (admittedPrompts.has(sessionId) || !!session.pending || session.mail.some(event => event.deliveredTurn === STARTING));
|
|
5047
|
+
},
|
|
5048
|
+
|
|
5049
|
+
hold: sessionId => {
|
|
5050
|
+
const session = sessions.get(sessionId);
|
|
5051
|
+
if (!session || session.closed) return undefined;
|
|
5052
|
+
session.lifecycleHolds = (session.lifecycleHolds ?? 0) + 1;
|
|
5053
|
+
let released = false;
|
|
5054
|
+
return () => {
|
|
5055
|
+
if (released) return;
|
|
5056
|
+
released = true;
|
|
5057
|
+
session.lifecycleHolds = Math.max(0, (session.lifecycleHolds ?? 1) - 1);
|
|
5058
|
+
if (session.lifecycleHolds || session.closed) return;
|
|
5059
|
+
// Parked work a resume reached during the hold continues now; paused again, it waits for that resume.
|
|
5060
|
+
if (session.resumeHeld) {
|
|
5061
|
+
const expected = session.resumeHeld;
|
|
5062
|
+
session.resumeHeld = undefined;
|
|
5063
|
+
if (session.parked === expected) return continueParked(sessionId, session, expected);
|
|
5064
|
+
}
|
|
5065
|
+
if (session.parked || pauseOf(session.runtimeKind) || !session.wakeHeld) return;
|
|
5066
|
+
session.wakeHeld = false;
|
|
5067
|
+
deliver(sessionId, session);
|
|
5068
|
+
};
|
|
5069
|
+
},
|
|
3573
5070
|
|
|
3574
5071
|
close: sessionId => enqueue(async () => {
|
|
3575
5072
|
openOf(sessionId);
|
|
@@ -3596,7 +5093,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3596
5093
|
};
|
|
3597
5094
|
visit(rootId);
|
|
3598
5095
|
const questions = [...userQuestions.values()].map(pending => pending.question).filter(question => question.rootId === rootId);
|
|
3599
|
-
const asking = new Set(questions.map(question => question.sessionId));
|
|
5096
|
+
const asking = new Set(questions.filter(question => !question.gate).map(question => question.sessionId));
|
|
3600
5097
|
const ids = new Set(tree.map(([id]) => id));
|
|
3601
5098
|
return {
|
|
3602
5099
|
rootId,
|
|
@@ -3646,6 +5143,26 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3646
5143
|
},
|
|
3647
5144
|
|
|
3648
5145
|
pauses: () => pauseState(),
|
|
5146
|
+
|
|
5147
|
+
holdForDisk(reason) {
|
|
5148
|
+
// A pause of all ALP already holds the work; the user's stays theirs to lift.
|
|
5149
|
+
if (paused.all) return pauseState();
|
|
5150
|
+
pauseRuntime('all', { since: new Date().toISOString(), by: 'alpd', reason, cause: 'disk' }, true);
|
|
5151
|
+
notice('error', say => say.diskFull(reason));
|
|
5152
|
+
return pauseState();
|
|
5153
|
+
},
|
|
5154
|
+
|
|
5155
|
+
releaseDisk(by) {
|
|
5156
|
+
if (paused.all?.cause !== 'disk') return pauseState();
|
|
5157
|
+
resumeRuntime('all', by, true);
|
|
5158
|
+
return pauseState();
|
|
5159
|
+
},
|
|
5160
|
+
|
|
5161
|
+
diskHeld: () => paused.all?.cause === 'disk',
|
|
5162
|
+
|
|
5163
|
+
diskLow(free) {
|
|
5164
|
+
notice('warning', say => say.diskLow(free));
|
|
5165
|
+
},
|
|
3649
5166
|
async usage(refresh = false) {
|
|
3650
5167
|
const providers = await Promise.all((['codex', 'claude'] as const).map(kind => cachedUsage(kind, refresh)));
|
|
3651
5168
|
const state = pauseState();
|
|
@@ -3684,6 +5201,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3684
5201
|
};
|
|
3685
5202
|
},
|
|
3686
5203
|
|
|
5204
|
+
syncGates(projectRoot) {
|
|
5205
|
+
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) return Promise.reject(new Error('syncGates needs an absolute projectRoot'));
|
|
5206
|
+
return syncGates(projectRoot);
|
|
5207
|
+
},
|
|
5208
|
+
|
|
3687
5209
|
async board(projectRoot) {
|
|
3688
5210
|
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) throw new Error('board needs an absolute projectRoot');
|
|
3689
5211
|
return (await boardOf(path.resolve(projectRoot))).filter(live);
|
|
@@ -3705,6 +5227,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3705
5227
|
answer(questionId, reply) {
|
|
3706
5228
|
const pending = userQuestions.get(questionId);
|
|
3707
5229
|
if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
|
|
5230
|
+
if (pending.gate) {
|
|
5231
|
+
if (!reply.dismiss && (typeof reply.text !== 'string' || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error('An answer needs text');
|
|
5232
|
+
void pending.gate.decide(reply);
|
|
5233
|
+
return;
|
|
5234
|
+
}
|
|
3708
5235
|
if (reply.dismiss) {
|
|
3709
5236
|
pending.settle('dismissed', undefined, reply.reason);
|
|
3710
5237
|
return;
|
|
@@ -3742,11 +5269,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3742
5269
|
|
|
3743
5270
|
await Promise.all(
|
|
3744
5271
|
[...sessions.keys()].map(
|
|
3745
|
-
closeSession,
|
|
5272
|
+
id => closeSession(id),
|
|
3746
5273
|
),
|
|
3747
5274
|
);
|
|
3748
5275
|
|
|
3749
5276
|
clearInterval(watchdog);
|
|
5277
|
+
if (gateWatch) clearInterval(gateWatch);
|
|
5278
|
+
await Promise.all(gateSyncs.values());
|
|
3750
5279
|
|
|
3751
5280
|
// Claims released by the closes above are written before the board is left.
|
|
3752
5281
|
await Promise.all(boards.values());
|
|
@@ -3761,5 +5290,6 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3761
5290
|
|
|
3762
5291
|
listeners.clear();
|
|
3763
5292
|
},
|
|
3764
|
-
};
|
|
5293
|
+
} satisfies AlpRuntime;
|
|
5294
|
+
return api;
|
|
3765
5295
|
}
|