@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.
Files changed (80) hide show
  1. package/dist/acp-transport.js +5 -36
  2. package/dist/antigravity-transport.d.ts +17 -0
  3. package/dist/antigravity-transport.js +82 -58
  4. package/dist/assignment-results.d.ts +52 -0
  5. package/dist/assignment-results.js +169 -0
  6. package/dist/attachments.d.ts +84 -0
  7. package/dist/attachments.js +213 -0
  8. package/dist/board-domain.js +2 -2
  9. package/dist/board.d.ts +6 -0
  10. package/dist/board.js +7 -0
  11. package/dist/catalog.d.ts +13 -0
  12. package/dist/catalog.js +9 -1
  13. package/dist/claude-transport.d.ts +35 -0
  14. package/dist/claude-transport.js +152 -10
  15. package/dist/compact.d.ts +29 -0
  16. package/dist/compact.js +49 -0
  17. package/dist/configure.d.ts +44 -0
  18. package/dist/configure.js +64 -0
  19. package/dist/contracts.d.ts +185 -4
  20. package/dist/contracts.js +11 -0
  21. package/dist/conversation.d.ts +45 -0
  22. package/dist/conversation.js +62 -0
  23. package/dist/index.d.ts +15 -4
  24. package/dist/index.js +40 -3
  25. package/dist/input-limits.d.ts +25 -0
  26. package/dist/input-limits.js +48 -0
  27. package/dist/language.d.ts +8 -0
  28. package/dist/language.js +20 -0
  29. package/dist/mailbox.d.ts +2 -0
  30. package/dist/mailbox.js +3 -1
  31. package/dist/mcp-tools.d.ts +8 -0
  32. package/dist/mcp-tools.js +26 -0
  33. package/dist/model-catalog.d.ts +76 -0
  34. package/dist/model-catalog.js +193 -0
  35. package/dist/model-probes.d.ts +7 -0
  36. package/dist/model-probes.js +69 -0
  37. package/dist/providers.js +2 -0
  38. package/dist/resolve.d.ts +1 -0
  39. package/dist/resolve.js +3 -1
  40. package/dist/runtime.d.ts +9 -0
  41. package/dist/runtime.js +1547 -142
  42. package/dist/session-config.d.ts +279 -0
  43. package/dist/session-config.js +10 -10
  44. package/dist/session-state.d.ts +44 -6
  45. package/dist/tools.d.ts +119 -0
  46. package/dist/tools.js +72 -5
  47. package/dist/transport.js +3 -1
  48. package/dist/workspace.d.ts +11 -4
  49. package/dist/workspace.js +29 -11
  50. package/dist/worktree-domain.d.ts +2 -1
  51. package/dist/worktree-domain.js +4 -1
  52. package/package.json +11 -3
  53. package/src/acp-transport.ts +7 -37
  54. package/src/antigravity-transport.ts +95 -53
  55. package/src/assignment-results.ts +146 -0
  56. package/src/attachments.ts +254 -0
  57. package/src/board-domain.ts +2 -2
  58. package/src/board.ts +7 -0
  59. package/src/catalog.ts +10 -1
  60. package/src/claude-transport.ts +171 -11
  61. package/src/compact.ts +62 -0
  62. package/src/configure.ts +93 -0
  63. package/src/contracts.ts +172 -5
  64. package/src/conversation.ts +81 -0
  65. package/src/index.ts +15 -4
  66. package/src/input-limits.ts +65 -0
  67. package/src/language.ts +18 -0
  68. package/src/mailbox.ts +4 -1
  69. package/src/mcp-tools.ts +33 -0
  70. package/src/model-catalog.ts +166 -0
  71. package/src/model-probes.ts +58 -0
  72. package/src/providers.ts +3 -0
  73. package/src/resolve.ts +4 -2
  74. package/src/runtime.ts +1681 -151
  75. package/src/session-config.ts +9 -9
  76. package/src/session-state.ts +29 -2
  77. package/src/tools.ts +69 -5
  78. package/src/transport.ts +3 -1
  79. package/src/workspace.ts +42 -15
  80. package/src/worktree-domain.ts +5 -1
package/dist/runtime.js CHANGED
@@ -1,10 +1,15 @@
1
1
  // packages/runtime/src/runtime.ts
2
+ import { createAssignmentResults, RESULT_OUTCOMES } from "./assignment-results.js";
2
3
  import { constants as fsConstants } from "node:fs";
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 } from "./attachments.js";
7
10
  import { createWorktreeDomain } from "./worktree-domain.js";
11
+ import { ConversationError } from "./contracts.js";
12
+ import { claudeCut, codexForkEnd, codexForkRefusal, pendingChain } from "./conversation.js";
8
13
  import { DEFAULT_TEAM } from "./contracts.js";
9
14
  import { verdictLine, parseHandoff } from "./handoff.js";
10
15
  import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, roleOf, taskActions, taskBrief } from "./tools.js";
@@ -20,13 +25,15 @@ import { resolveDelegation } from "@anhlp/alp-core/delegation";
20
25
  import { discoverAgents } from "@anhlp/alp-core/resolver";
21
26
  import { acpDecision, acpWhat } from "./acp-transport.js";
22
27
  import { models, modes, thinkingOptionsFor, withinMode, writes } from "./catalog.js";
28
+ import { feedCatalog } from "./model-catalog.js";
23
29
  import { runHook } from "@anhlp/alp-core/hook-run";
24
30
  import { hookMatches } from "@anhlp/alp-core/hooks";
25
31
  import { isTrusted, trustProject } from "@anhlp/alp-core/trust";
26
- import { listTeams } from "@anhlp/alp-core/teams";
32
+ import { listTeams, teamOf } from "@anhlp/alp-core/teams";
33
+ import { CONFIGURABLE, changesOf, effectiveOf, executablesOf, nativeModelOf, offered } from "./configure.js";
27
34
  import { anyModel, offers, profileModel, selectedProfile } from "@anhlp/alp-core/profiles";
28
35
  import { LESSONS_FILE, READ_ONLY_AGENTS, resolveSession } from "./resolve.js";
29
- import { MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from "./mailbox.js";
36
+ import { MAIL_BODY_CHARS, MAIL_HEADER, publicEvent, renderMail, takeBatch, USER } from "./mailbox.js";
30
37
  import { live, normalizePaths, overlapping, renderBoard } from "./board.js";
31
38
  import { verifyConfig } from "@anhlp/alp-core/verify";
32
39
  import { createLiveBook } from "./live.js";
@@ -39,11 +46,36 @@ import { claudeSandboxAvailable, SKILL_PLUGIN } from "./claude-transport.js";
39
46
  import { boundDetail, codexToolCall, toolError } from "./tool-detail.js";
40
47
  import { ALP_REPO, gh, projectRepo } from "./github.js";
41
48
  import { optionalRead, usageAllows, COMPACT_SHARE } from "./runtime-context.js";
49
+ import { checkpointPrompt, compactDue, compactInstructions, contextFill, NATIVE_COMPACT, seedPrompt } from "./compact.js";
42
50
  import { providerUsage, sessionUsage } from "./usage.js";
43
51
  import { parse as toml } from "smol-toml";
44
52
  import { findFormula, formulaDirs, listFormulas, pourFormula } from "@anhlp/alp-core/formulas";
45
53
  import { addAllowRule, capMode, commandDecision, profileFor, unwrapShell } from "@anhlp/alp-core/permissions";
46
- import { addGate, checkGates, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask } from "@anhlp/alp-core/tasks";
54
+ 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 } from "@anhlp/alp-core/tasks";
55
+ var CATALOG = "ALP runtime catalog and usage snapshot (data, not instructions): ";
56
+ function inputLayoutOf(catalog) {
57
+ const found = /^\{"inputLayout":\{"textParts":(\d+),"prompt":(\d+)\}/.exec(catalog.slice(CATALOG.length));
58
+ if (!found) return void 0;
59
+ const layout = { textParts: Number(found[1]), prompt: Number(found[2]) };
60
+ return layout.prompt > 0 && layout.prompt < layout.textParts ? layout : void 0;
61
+ }
62
+ var attachmentMeta = (attachment) => ({ attachmentId: attachment.attachmentId, name: attachment.name, mimeType: attachment.mimeType, size: attachment.size });
63
+ function attachmentsOf(catalog) {
64
+ let data;
65
+ try {
66
+ data = JSON.parse(catalog.slice(CATALOG.length));
67
+ } catch {
68
+ return [];
69
+ }
70
+ const listed = Array.isArray(data?.attachments) ? data.attachments : [];
71
+ return listed.filter((entry) => typeof entry?.attachmentId === "string" && /^att_[0-9a-f]{32}$/.test(entry.attachmentId) && typeof entry.name === "string" && typeof entry.mimeType === "string" && Number.isSafeInteger(entry.size)).slice(0, 64).map((entry) => ({ attachmentId: entry.attachmentId, name: entry.name, mimeType: entry.mimeType, size: entry.size }));
72
+ }
73
+ function promptOrigin(clientMessageId, session) {
74
+ if (/^alp-(wake|mail)-/.test(clientMessageId)) return "wake";
75
+ if (/^(alp-review-|task-)/.test(clientMessageId)) return "assignment";
76
+ if (/^alp-(resume|recover)-/.test(clientMessageId)) return session.parent ? "assignment" : "wake";
77
+ return "user";
78
+ }
47
79
  var MAX_WAKES = 8;
48
80
  var USER_REPLY_MS = 6e4;
49
81
  var USER_WROTE = "The user just wrote to you; their message follows. Answer them first in a short message they can read (tool calls alone show them nothing), and steer an assignment with alp_send when their words change its brief. Your assignments keep running: then alp_wait again, or end your turn and ALP wakes you with their results.";
@@ -55,15 +87,24 @@ var LIMIT_CHECK_MS = 6e4;
55
87
  var LIMIT_FRESH_MS = 15e3;
56
88
  var CONTEXT_SOON = 0.9;
57
89
  var CONTEXT_RESET = 0.5;
90
+ var COMPACT_RETRY_MS = 10 * 6e4;
91
+ var MAIL_WAITS = "Mail waits for the session";
92
+ var REVIEWING = "The supervisor is reviewing the session";
93
+ var COMPACT_NATIVE_MS = 5 * 6e4;
58
94
  var BRIEF_CHARS = 8e3;
95
+ var RESULT_EVIDENCE_CHARS = 2e3;
96
+ var RESOLVE_NOTE_CHARS = 2e3;
59
97
  var STEERING = "\0steering";
60
98
  var STARTING = "\0starting";
61
99
  var APPROVALS = ["approve", "approved", "yes", "y", "ok", "\u0111\u1ED3ng \xFD", "duy\u1EC7t", "c\xF3"];
100
+ var CHOICES_REJECT = ["reject", "t\u1EEB ch\u1ED1i"];
62
101
  var SKILL_BODY_CHARS = 2e4;
63
102
  var STARTER_ROLES = ["main", "lead", "peer", "oracle", "reviewer", "supervisor"];
64
103
  var ISSUE_BODY_CHARS = 2e4;
65
104
  var ISSUE_FOOTER = "\n\n---\n_Drafted by an ALP agent and posted with the user's approval._";
66
105
  var LESSON_CHARS = 600;
106
+ var CURATE_MARKER = "[alp-curate]";
107
+ var 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.`;
67
108
  var DIGEST_CHARS = 12e3;
68
109
  var JOURNAL_LINE_CHARS = 400;
69
110
  var clock = (at = Date.now()) => new Date(at).toTimeString().slice(0, 8);
@@ -78,13 +119,23 @@ var clip = (text, limit = JOURNAL_LINE_CHARS) => {
78
119
  };
79
120
  var isolationOf = (args) => args.isolation ?? "shared";
80
121
  var log = createLogger({ component: "runtime" });
122
+ var WorkspaceMutationError = class extends Error {
123
+ data;
124
+ constructor(reason, message) {
125
+ super(message);
126
+ this.name = "WorkspaceMutationError";
127
+ this.data = { reason };
128
+ }
129
+ };
81
130
  function createAlpRuntime(options = {}) {
82
131
  const sessions = /* @__PURE__ */ new Map();
132
+ const admittedPrompts = /* @__PURE__ */ new Set();
83
133
  const wordsFor = (session) => words(session.mapping.language);
84
134
  const childContexts = /* @__PURE__ */ new Map();
85
135
  const listeners = /* @__PURE__ */ new Set();
86
136
  const epoch = randomUUID();
87
137
  const recalls = createRecallBook(options.recallFile);
138
+ const assignmentResults = createAssignmentResults(options.assignmentResultFile);
88
139
  const inFlight = createLiveBook(options.liveFile);
89
140
  let inherited = inFlight.all().filter((entry) => entry.epoch !== epoch);
90
141
  let paused = { runtimes: {} };
@@ -102,10 +153,34 @@ function createAlpRuntime(options = {}) {
102
153
  const leases = /* @__PURE__ */ new Map();
103
154
  const worktreeRoot = options.worktreeDir ?? path.join(os.tmpdir(), "alp-worktrees");
104
155
  const copyRoot = options.copyDir ?? path.join(os.tmpdir(), "alp-copies");
156
+ const stager = options.attachmentStageDir ? createAttachmentStager(options.attachmentStageDir) : void 0;
157
+ let attachmentReader;
158
+ const stagingWarned = /* @__PURE__ */ new Set();
159
+ if (stager) void stager.sweep();
105
160
  const sequences = /* @__PURE__ */ new Map();
161
+ let workspaceMutation = false;
162
+ let admitting = 0;
163
+ const refuseMutation = (reason, message) => {
164
+ throw new WorkspaceMutationError(reason, message);
165
+ };
166
+ const ADOPTION = Symbol("adoption");
167
+ async function admission(run) {
168
+ if (workspaceMutation) refuseMutation("workspace_busy", "A workspace mutation is in progress; retry after it finishes");
169
+ admitting++;
170
+ try {
171
+ return await run();
172
+ } finally {
173
+ admitting--;
174
+ }
175
+ }
106
176
  let closed = false;
107
177
  let queue = Promise.resolve();
108
178
  const emit = (sessionId, event) => {
179
+ if (stager) {
180
+ const json = JSON.stringify(event);
181
+ const named = stager.spellings().map((root) => JSON.stringify(root).slice(1, -1)).filter((root) => json.includes(root));
182
+ if (named.length) event = JSON.parse(named.reduce((text2, root) => text2.replace(new RegExp(`${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![A-Za-z0-9_-]|\\.[A-Za-z0-9_-])`, "g"), STAGED_PATH), json));
183
+ }
109
184
  const seq = (sequences.get(sessionId) ?? 0) + 1;
110
185
  sequences.set(sessionId, seq);
111
186
  const envelope = { sessionId, epoch, seq, ts: (/* @__PURE__ */ new Date()).toISOString(), event };
@@ -124,6 +199,9 @@ function createAlpRuntime(options = {}) {
124
199
  function takesImages(session) {
125
200
  return session.runtime.takesImages ? session.runtime.takesImages() : session.runtimeKind === "codex" || session.runtimeKind === "claude";
126
201
  }
202
+ function attachmentRoutes(session) {
203
+ return stager && attachmentReader ? ATTACHMENT_ROUTES[session.runtimeKind] ?? [] : [];
204
+ }
127
205
  function snapshot(sessionId, session) {
128
206
  return {
129
207
  id: sessionId,
@@ -144,6 +222,7 @@ function createAlpRuntime(options = {}) {
144
222
  ...session.parked?.reason ?? session.parkReason ? { parked: session.parked?.reason ?? session.parkReason } : {},
145
223
  ...session.instructionsSha ? { instructionsSha: session.instructionsSha } : {},
146
224
  ...takesImages(session) ? { promptImages: true } : {},
225
+ ...attachmentRoutes(session).length ? { promptAttachments: [...attachmentRoutes(session)] } : {},
147
226
  ...session.usage ? { usage: session.usage } : {},
148
227
  busy: !!(session.active || session.pending || session.parked || session.parkReason || session.children.size || session.assignments.size || hasActiveMail(session) || reviewing(session))
149
228
  };
@@ -182,18 +261,37 @@ function createAlpRuntime(options = {}) {
182
261
  }
183
262
  session.userStopped = false;
184
263
  if (session.role === "supervisor" && session.parent && sessions.get(session.parent)?.reviewPending) review(session.parent);
264
+ if (session.role === "supervisor" && session.parent) {
265
+ const root = sessions.get(session.parent);
266
+ if (root) queueMicrotask(() => compactAtBoundary(session.parent, root));
267
+ }
185
268
  if (!session.parent) void showTasks(sessionId, session);
269
+ if (!session.parent && session.role !== "supervisor") queueMicrotask(() => compactAtBoundary(sessionId, session, state));
186
270
  if (session.parkReason && state !== "completed") {
187
271
  park(sessionId, session);
188
272
  return;
189
273
  }
190
274
  session.parkReason = void 0;
275
+ session.parkPause = void 0;
191
276
  if (state === "completed" && (session.assignments.size || hasActiveMail(session))) {
192
277
  queueMicrotask(() => deliver(sessionId, session));
193
278
  return;
194
279
  }
195
280
  session.settle?.(state, error);
196
281
  }
282
+ function nativePrompt(item, session) {
283
+ const parts = (item.content ?? []).filter((c) => c.type === "text").map((c) => String(c.text ?? ""));
284
+ const clientMessageId = typeof item.clientId === "string" && item.clientId ? item.clientId : void 0;
285
+ if (!parts[0]?.startsWith(CATALOG)) return { text: parts.join("\n"), ...clientMessageId ? { clientMessageId } : {}, origin: clientMessageId ? promptOrigin(clientMessageId, session) : parts[0]?.startsWith(MAIL_HEADER) ? "wake" : "user" };
286
+ const origin = clientMessageId ? promptOrigin(clientMessageId, session) : void 0;
287
+ const ids = { ...clientMessageId ? { clientMessageId } : {}, ...origin ? { origin } : {} };
288
+ const layout = inputLayoutOf(parts[0]);
289
+ const attached = attachmentsOf(parts[0]);
290
+ if (layout) return { text: parts.length === layout.textParts ? parts[layout.prompt] ?? "" : "", ...ids, ...attached.length ? { attachments: attached } : {} };
291
+ const rest = parts.slice(1);
292
+ if (!clientMessageId?.startsWith("alp-wake-") && rest.length > 1 && rest.at(-1).startsWith(MAIL_HEADER)) rest.pop();
293
+ return { text: rest.at(-1) ?? "", ...ids };
294
+ }
197
295
  function nativeItem(sessionId, session, item, done = false) {
198
296
  if (item.type === "agentMessage") {
199
297
  if (session.userWaiting !== void 0 && String(item.text ?? "").trim()) {
@@ -205,9 +303,9 @@ function createAlpRuntime(options = {}) {
205
303
  return;
206
304
  }
207
305
  if (item.type === "userMessage") {
208
- const text2 = (item.content ?? []).filter((c) => c.type === "text").map((c) => c.text).join("\n");
306
+ const { text: text2, clientMessageId, origin, attachments } = nativePrompt(item, session);
209
307
  const images = (item.content ?? []).filter((c) => c.type === "image" || c.type === "localImage").length;
210
- emit(sessionId, { type: "item", item: { kind: "user_message", id: item.id, text: text2, ...images ? { images } : {} } });
308
+ emit(sessionId, { type: "item", item: { kind: "user_message", id: item.id, text: text2, ...clientMessageId ? { clientMessageId } : {}, ...origin ? { origin } : {}, ...images ? { images } : {}, ...attachments ? { attachments } : {} } });
211
309
  return;
212
310
  }
213
311
  if (item.type === "dynamicToolCall") {
@@ -269,6 +367,10 @@ function createAlpRuntime(options = {}) {
269
367
  }
270
368
  function notification(sessionId, session, method, params) {
271
369
  if (session.closed) return;
370
+ if (method === "alp/nativeModel") {
371
+ 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) });
372
+ return;
373
+ }
272
374
  touch(sessionId, session);
273
375
  if (session.pending) {
274
376
  session.buffered.push([method, params]);
@@ -321,7 +423,10 @@ function createAlpRuntime(options = {}) {
321
423
  if (method === "turn/completed" && params.turn.id === session.active) {
322
424
  const state = params.turn.status === "completed" ? "completed" : params.turn.status === "interrupted" ? "canceled" : "failed";
323
425
  if (state === "failed" && LIMIT_ERRORS.includes(params.turn.error?.codexErrorInfo)) {
324
- if (session.role !== "supervisor") session.parkReason = `the ${label(session.runtimeKind)} usage limit was reached`;
426
+ if (session.role !== "supervisor") {
427
+ session.parkReason = `the ${label(session.runtimeKind)} usage limit was reached`;
428
+ session.parkPause = { scope: paused.all ? "all" : session.runtimeKind, ...paused.all?.cause === "disk" ? { disk: true } : {} };
429
+ }
325
430
  void limitReached(session, params.turn.error);
326
431
  }
327
432
  terminal(
@@ -332,34 +437,50 @@ function createAlpRuntime(options = {}) {
332
437
  );
333
438
  }
334
439
  }
335
- async function closeSession(sessionId) {
336
- const session = sessions.get(sessionId);
337
- if (!session || session.closed) return;
440
+ const sessionClosures = /* @__PURE__ */ new WeakMap();
441
+ const openedSessions = /* @__PURE__ */ new WeakSet();
442
+ const openings = /* @__PURE__ */ new WeakMap();
443
+ const assignmentSessions = /* @__PURE__ */ new WeakMap();
444
+ function closeSession(sessionId, session = sessions.get(sessionId), notify = true) {
445
+ if (!session) return Promise.resolve();
446
+ const closing = sessionClosures.get(session);
447
+ if (closing) return closing;
448
+ if (session.closed) return Promise.resolve();
338
449
  session.closed = true;
339
- cancelQuestions(sessionId);
340
- approvalLedger.delete(sessionId);
341
- releaseClaims(sessionId, session.mapping.agent.projectRoot);
342
- await Promise.all(
343
- [...session.children, ...session.supervisor ? [session.supervisor] : []].map(closeSession)
344
- );
345
- terminal(sessionId, session, "canceled");
346
- session.settle?.("canceled", "Session closed");
347
- await session.runtime.close();
348
- for (const assignment of session.assignments.values()) if (assignment.copy && !assignment.finished) await removeCopy(assignment.copy).catch(() => {
349
- });
350
- for (const [assignmentId, { worktree }] of session.worktrees) {
351
- await removeWorktree(worktree).catch(() => {
450
+ const current = sessions.get(sessionId) === session;
451
+ const opened = openedSessions.has(session);
452
+ const parent = session.parent ? sessions.get(session.parent) : void 0;
453
+ const descendants = current ? [...session.children, ...session.supervisor ? [session.supervisor] : []].map((id) => [id, sessions.get(id)]).filter((entry) => !!entry[1]) : [];
454
+ if (current) {
455
+ cancelQuestions(sessionId);
456
+ approvalLedger.delete(sessionId);
457
+ releaseClaims(sessionId, session.mapping.agent.projectRoot);
458
+ terminal(sessionId, session, "canceled");
459
+ session.settle?.("canceled", "Session closed");
460
+ }
461
+ const cleanup = (async () => {
462
+ await Promise.all(
463
+ descendants.map(([id, child]) => closeSession(id, child))
464
+ );
465
+ await session.runtime.close();
466
+ for (const assignment of session.assignments.values()) if (assignment.copy && !assignment.finished) await removeCopy(assignment.copy).catch(() => {
352
467
  });
353
- runLog(rootOf(sessionId), { event: "worktree.kept", assignmentId, branch: worktree.branch });
354
- }
355
- session.worktrees.clear();
356
- sessions.delete(sessionId);
357
- if (session.parent) {
358
- const parent = sessions.get(session.parent);
359
- parent?.children.delete(sessionId);
360
- if (parent?.supervisor === sessionId) parent.supervisor = void 0;
361
- }
362
- emit(sessionId, { type: "session.closed" });
468
+ for (const [assignmentId, { worktree }] of session.worktrees) {
469
+ await removeWorktree(worktree).catch(() => {
470
+ });
471
+ runLog(rootOf(sessionId), { event: "worktree.kept", assignmentId, branch: worktree.branch });
472
+ }
473
+ session.worktrees.clear();
474
+ if (sessions.get(sessionId) !== session) return;
475
+ sessions.delete(sessionId);
476
+ if (session.parent && parent && sessions.get(session.parent) === parent) {
477
+ parent.children.delete(sessionId);
478
+ if (parent.supervisor === sessionId) parent.supervisor = void 0;
479
+ }
480
+ if (notify && opened) emit(sessionId, { type: "session.closed" });
481
+ })();
482
+ sessionClosures.set(session, cleanup);
483
+ return cleanup;
363
484
  }
364
485
  let runLogWrites = Promise.resolve();
365
486
  const rootFor = (sessionId, session) => sessions.has(sessionId) ? rootOf(sessionId) : session.parent ? rootOf(session.parent) : sessionId;
@@ -732,22 +853,25 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
732
853
  return toolResult(true, { tasks: rows.slice(0, limit).map((task2) => summarize(task2, tasks2)), ...rows.length > limit ? { more: rows.length - limit } : {}, ...warnings });
733
854
  }
734
855
  const { action: _action, id, note, reason, summary, unverified, add, remove, ...input } = args;
735
- if (action === "pour" && (typeof input.formula !== "string" || input.vars !== void 0 && (!input.vars || typeof input.vars !== "object" || Array.isArray(input.vars) || !Object.values(input.vars).every((value) => typeof value === "string")))) {
736
- return toolResult(false, { error: "pour needs formula, and vars as an object of text values" });
856
+ if (action === "pour" && (typeof input.formula !== "string" || input.vars !== void 0 && (!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")))) {
857
+ 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` });
737
858
  }
738
- const { kind, until, ref, gate, formula: _formula, vars: _vars, ...fields } = input;
859
+ const { kind, until, ref, gate, options: gateChoices, formula: _formula, vars: _vars, ...fields } = input;
739
860
  if (action === "clear") {
740
861
  const current = (await loadTasks(project)).tasks.find((candidate) => candidate.id === id);
741
862
  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" });
742
863
  }
743
864
  let poured;
744
865
  const hookedClose = async (id2) => {
866
+ const current = (await loadTasks(project)).tasks.find((candidate) => candidate.id === id2);
867
+ if (current && (current.step?.human || current.gates.some((gate2) => gate2.kind === "human" && !gate2.resolved))) throw new Error(`Only the user closes ${id2}: it waits on the user's decision. Ask the user to decide it`);
745
868
  const refused = await runHooks(sessionId, session, "task.close", { reason, ...summary ? { summary } : {} }, id2);
746
869
  if (refused) throw new Error(`A task.close hook refused to close ${id2}: ${refused}`);
747
870
  return closeTask(project, id2, { reason, summary, unverified }, by);
748
871
  };
749
- const task = action === "create" ? await createTask(project, fields, by) : action === "update" ? await updateTask(project, id, { ...fields, note }, by) : action === "pour" ? (poured = await pourFormula(project, (await findFormula(project, options.libraryDir, input.formula, { toml })).formula, input.vars, by, input.parent ? { parent: input.parent } : {})).epic : action === "gate" ? await addGate(project, id, { kind, note, until, ref }, by) : action === "clear" ? await resolveGate(project, id, gate, { by, note }) : action === "link" ? await linkTask(project, id, { add, remove }, by) : action === "start" ? await startTask(project, id, { agent: by, session: sessionId }, by) : action === "close" ? await hookedClose(id) : await reopenTask(project, id, { note }, by);
872
+ const task = action === "create" ? await createTask(project, fields, by) : action === "update" ? await updateTask(project, id, { ...fields, note }, by) : action === "pour" ? (poured = await pourFormula(project, (await findFormula(project, options.libraryDir, input.formula, { toml })).formula, input.vars, by, input.parent ? { parent: input.parent } : {})).epic : action === "gate" ? await addGate(project, id, { kind, note, until, ref, ...gateChoices !== void 0 ? { options: gateChoices } : {} }, by) : action === "clear" ? await resolveGate(project, id, gate, { by, note }) : action === "link" ? await linkTask(project, id, { add, remove }, by) : action === "start" ? await startTask(project, id, { agent: by, session: sessionId }, by) : action === "close" ? await hookedClose(id) : await reopenTask(project, id, { note }, by);
750
873
  touchTask(rootOf(sessionId), task.id);
874
+ if (action === "gate" && kind === "human") void syncGates(project);
751
875
  runLog(rootOf(sessionId), { event: "task", action, agent: by, id: task.id, title: task.title, status: task.status, ...summary ?? note ? { detail: summary ?? note } : {} });
752
876
  const { tasks } = await loadTasks(project);
753
877
  const landed = {};
@@ -854,6 +978,45 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
854
978
  return toolResult(false, { assignmentId: entry.assignmentId, error: errorData(error).message });
855
979
  }
856
980
  }
981
+ async function resolveTool(sessionId, session, args) {
982
+ if (!plainObject(args, ["assignmentId", "outcome", "note"]) || typeof args.assignmentId !== "string" || !RESULT_OUTCOMES.includes(args.outcome) || args.note !== void 0 && (typeof args.note !== "string" || args.note.length > RESOLVE_NOTE_CHARS)) {
983
+ return toolResult(false, { error: `Pass assignmentId, outcome (${RESULT_OUTCOMES.join(", ")}), and optionally a note of at most ${RESOLVE_NOTE_CHARS} characters` });
984
+ }
985
+ const id = args.assignmentId;
986
+ const outcome = args.outcome;
987
+ const note = args.note;
988
+ const live2 = [...sessions.values()];
989
+ if (sessions.has(id) || live2.some((other) => other.assignments.has(id)) || inFlight.all().some((entry2) => entry2.assignmentId === id) || inherited.some((entry2) => entry2.assignmentId === id)) {
990
+ return toolResult(false, { error: "That assignment is still running or can still be recovered; wait for its result" });
991
+ }
992
+ if (live2.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" });
993
+ let ledger;
994
+ try {
995
+ ledger = await assignmentResults.inspect();
996
+ } catch (error) {
997
+ return toolResult(false, { error: errorData(error).message });
998
+ }
999
+ const entry = ledger.results.find((owner) => owner.assignmentId === id && !owner.handled);
1000
+ const project = session.mapping.agent.projectRoot;
1001
+ const overlapping2 = async (a, b) => {
1002
+ const [x, y] = [await realpath(a).catch(() => a), await realpath(b).catch(() => b)];
1003
+ const within = (parent, child) => {
1004
+ const relative = path.relative(parent, child);
1005
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
1006
+ };
1007
+ return within(x, y) || within(y, x);
1008
+ };
1009
+ const allowed = !!entry && (entry.result ? entry.result.requesters.includes(sessionId) || !session.parent && await sameDirectory(entry.result.project, project) : !session.parent && await overlapping2(entry.checkout, project));
1010
+ if (!entry || !allowed) return toolResult(false, { error: `No unresolved assignment result ${id} of yours` });
1011
+ 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` });
1012
+ try {
1013
+ const archived = await assignmentResults.resolve(id, { outcome, by: `${session.mapping.agent.name} in ${sessionId}`, at: (/* @__PURE__ */ new Date()).toISOString(), ...note ? { note } : {} });
1014
+ runLog(rootOf(sessionId), { event: "result.resolved", assignmentId: id, agent: session.mapping.agent.name, outcome, ...note ? { note: clip(note, 500) } : {} });
1015
+ return toolResult(true, { resolved: id, outcome, archivedAt: archived.archivedAt });
1016
+ } catch (error) {
1017
+ return toolResult(false, { assignmentId: id, error: errorData(error).message });
1018
+ }
1019
+ }
857
1020
  let forgetting = Promise.resolve();
858
1021
  function forgetExpired() {
859
1022
  forgetting = forgetting.then(async () => {
@@ -880,7 +1043,22 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
880
1043
  const LIMIT_ERRORS = ["usageLimitExceeded", "rateLimitExceeded"];
881
1044
  const label = (kind) => kind === "claude" ? "Claude" : kind === "acp" ? "ACP agent" : kind === "antigravity" ? "Antigravity" : "Codex";
882
1045
  const pauseOf = (kind) => paused.all ?? paused.runtimes[kind];
883
- const held = (session) => !!session.parked || !!pauseOf(session.runtimeKind);
1046
+ const held = (session) => !!session.parked || !!pauseOf(session.runtimeKind) || (session.lifecycleHolds ?? 0) > 0;
1047
+ const holdsWake = (session) => held(session) || !!session.awaitingBrief || !!session.compacting;
1048
+ function beginPending(session) {
1049
+ let done;
1050
+ session.pending = true;
1051
+ session.acknowledged = new Promise((resolve) => {
1052
+ done = resolve;
1053
+ });
1054
+ let cleared = false;
1055
+ return () => {
1056
+ if (cleared) return;
1057
+ cleared = true;
1058
+ session.pending = false;
1059
+ done();
1060
+ };
1061
+ }
884
1062
  const describePause = (pause, kind) => `${kind ? label(kind) : "ALP"} is paused (${pause.reason}${pause.by !== "alpd" ? `, by ${pause.by}` : ""})${pause.resetsAt ? `; the limit resets ${pause.resetsAt}` : ""}`;
885
1063
  function pauseState() {
886
1064
  return {
@@ -1001,46 +1179,65 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1001
1179
  if (now) {
1002
1180
  for (const [id, session] of sessions) {
1003
1181
  if (!session.parent || session.closed || !session.active || session.role === "supervisor" || scope !== "all" && session.runtimeKind !== scope) continue;
1004
- session.parkReason = `paused by ${pause.by}`;
1182
+ if (session.parkReason && !session.parkPause) continue;
1183
+ session.parkReason = pause.cause === "disk" ? pause.reason : `paused by ${pause.by}`;
1184
+ session.parkPause = { scope, ...pause.cause === "disk" ? { disk: true } : {} };
1005
1185
  void session.runtime.request("turn/interrupt", { threadId: session.threadId, turnId: session.active }).catch(() => {
1006
1186
  });
1007
1187
  runLog(rootOf(id), { event: "assignment.parking", assignmentId: id, agent: session.mapping.agent.name, reason: session.parkReason });
1008
1188
  }
1009
1189
  }
1010
1190
  }
1011
- function resumeRuntime(scope, by) {
1012
- if (scope === "all") paused = { runtimes: {} };
1191
+ function resumeRuntime(scope, by, keepRuntimes = false) {
1192
+ if (scope === "all") paused = keepRuntimes ? { runtimes: paused.runtimes } : { runtimes: {} };
1013
1193
  else delete paused.runtimes[scope];
1014
1194
  savePauses();
1015
1195
  watchLimits();
1196
+ const matches = (pause) => pause && (scope === "all" || pause.scope === scope);
1197
+ const continuing = [...sessions.values()].some((session) => !session.closed && !pauseOf(session.runtimeKind) && matches(session.parked?.pause));
1016
1198
  const free = RUNTIMES.filter((kind) => !pauseOf(kind));
1017
- if (free.length) notice("info", (say) => say.resumed(scope === "all" ? "ALP" : label(scope), by, pauseState().parked.length > 0));
1199
+ if (free.length) notice("info", (say) => say.resumed(scope === "all" ? "ALP" : label(scope), by, continuing));
1018
1200
  for (const [id, session] of sessions) {
1019
- if (session.closed || pauseOf(session.runtimeKind)) continue;
1020
- if (session.parked) continueParked(id, session);
1021
- else if (session.wakeHeld) {
1201
+ if (session.closed || scope !== "all" && session.runtimeKind !== scope) continue;
1202
+ if (matches(session.parkPause)) session.parkPause.resumed = true;
1203
+ if (pauseOf(session.runtimeKind)) continue;
1204
+ if (session.parked) {
1205
+ if (matches(session.parked.pause)) continueParked(id, session);
1206
+ } else if (session.wakeHeld) {
1022
1207
  session.wakeHeld = false;
1023
1208
  deliver(id, session);
1024
1209
  }
1025
1210
  }
1026
1211
  }
1027
1212
  function park(sessionId, session) {
1028
- session.parked = { reason: session.parkReason, since: Date.now() };
1213
+ session.parked = { reason: session.parkReason, since: Date.now(), ...session.parkPause ? { pause: session.parkPause } : {} };
1214
+ const resumed = session.parkPause?.resumed;
1215
+ session.parkPause = void 0;
1029
1216
  const then = session.parkThen;
1030
1217
  session.parkReason = void 0;
1031
1218
  session.parkThen = void 0;
1032
1219
  emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
1220
+ if (resumed) continueParked(sessionId, session);
1033
1221
  const parent = session.parent ? sessions.get(session.parent) : void 0;
1034
1222
  const assignment = parent?.assignments.get(sessionId);
1035
1223
  runLog(rootOf(sessionId), { event: "assignment.parked", assignmentId: sessionId, agent: session.mapping.agent.name, reason: session.parked.reason });
1036
1224
  if (!parent || !assignment) return;
1037
1225
  emit(session.parent, { type: "assignment", assignment: assignmentSnapshot(assignment, "parked") });
1038
1226
  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.` });
1227
+ 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.` });
1039
1228
  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:\u2026 or codex:\u2026); what it changed stays in your checkout or its worktree.` });
1040
1229
  }
1041
- function continueParked(sessionId, session) {
1230
+ function continueParked(sessionId, session, expected = session.parked) {
1042
1231
  void enqueue(async () => {
1043
- if (session.closed || session.active || session.pending || !session.parked || pauseOf(session.runtimeKind)) return;
1232
+ if (session.closed || session.active || session.pending || !session.parked || session.parked !== expected) return;
1233
+ if (pauseOf(session.runtimeKind)) {
1234
+ session.parked.pause = { scope: paused.all ? "all" : session.runtimeKind };
1235
+ return;
1236
+ }
1237
+ if (session.lifecycleHolds) {
1238
+ session.resumeHeld = session.parked;
1239
+ return;
1240
+ }
1044
1241
  const parked = session.parked;
1045
1242
  const { reason, prompt } = parked;
1046
1243
  session.parked = void 0;
@@ -1095,6 +1292,7 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1095
1292
  const used = usage2?.last?.totalTokens;
1096
1293
  const window = usage2?.modelContextWindow;
1097
1294
  if (session.role === "supervisor" || typeof used !== "number" || typeof window !== "number" || window <= 0) return;
1295
+ if (!session.compactCooling) session.contextFill = contextFill({ ...usage2, modelContextWindow: Math.min(typeof session.mapping.autocompact === "number" ? session.mapping.autocompact : typeof session.mapping.context === "number" ? session.mapping.context : window, window) });
1098
1296
  const compactAt = typeof usage2.autoCompactTokens === "number" && usage2.autoCompactTokens > 0 ? usage2.autoCompactTokens : session.runtimeKind === "codex" && session.mapping.autocompact ? Math.min(session.mapping.autocompact, Math.round(window * COMPACT_SHARE)) : Math.round(Math.min(session.mapping.autocompact ?? session.mapping.context ?? window, window) * COMPACT_SHARE);
1099
1297
  const fill = used / compactAt;
1100
1298
  if (fill < CONTEXT_RESET) {
@@ -1131,13 +1329,157 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1131
1329
  if (!done) return;
1132
1330
  const agent = session.mapping.agent.name;
1133
1331
  runLog(rootOf(sessionId), { event: "compacted", sessionId, agent, ...trigger, ...tokens, ...failed ? { failed: true, ...item.error ? { error: String(item.error) } : {} } : {} });
1134
- if (failed) return;
1332
+ if (failed) {
1333
+ if (session.compacting?.phase === "native") compactFailed(sessionId, session, item.error ? String(item.error) : "the runtime could not compact");
1334
+ return;
1335
+ }
1135
1336
  session.contextLevel = 0;
1136
1337
  if (session.supervisor) session.journal.push(stamp(`${agent}'s context was compacted`));
1137
- if (session.role !== "supervisor") void restoreAfterCompaction(sessionId, session).catch(() => {
1338
+ const checkpoint = session.compacting?.phase === "native" ? session.compacting.checkpoint : void 0;
1339
+ if (session.role !== "supervisor") void restoreAfterCompaction(sessionId, session, checkpoint).catch(() => {
1340
+ });
1341
+ if (checkpoint !== void 0) compactFinished(sessionId, session, "native");
1342
+ }
1343
+ function compactHeld(sessionId, session, starting) {
1344
+ return session.closed || !!session.active || !!session.pending || session.waiters.length > 0 || !!session.parked || !!session.parkReason || starting && (hasActiveMail(session) || !!session.wakeHeld) || [...userQuestions.values()].some((pending) => pending.question.rootId === sessionId && !pending.gate);
1345
+ }
1346
+ function compactAtBoundary(sessionId, session, ended) {
1347
+ if (session.closed || sessions.get(sessionId) !== session) return;
1348
+ const current = session.compacting;
1349
+ if (ended && current?.phase === "checkpoint" && current.checkpoint === void 0 && current.turn) {
1350
+ const written = [...session.text.values()].at(-1)?.trim();
1351
+ if (ended !== "completed" || !written) {
1352
+ compactFailed(sessionId, session, ended !== "completed" ? `the checkpoint turn ${ended}` : "main wrote no checkpoint");
1353
+ return;
1354
+ }
1355
+ current.checkpoint = written;
1356
+ const timer = setTimeout(() => {
1357
+ if (session.compacting === current && current.phase === "checkpoint") compactFailed(sessionId, session, "main stayed busy after its checkpoint");
1358
+ }, COMPACT_NATIVE_MS);
1359
+ timer.unref?.();
1360
+ }
1361
+ if (ended && current?.phase === "native" && current.requested) {
1362
+ compactFailed(sessionId, session, "the runtime reported no compaction");
1363
+ return;
1364
+ }
1365
+ if (current) {
1366
+ if (current.checkpoint !== void 0 && current.phase === "checkpoint" && !compactHeld(sessionId, session, false)) void compactNow(sessionId, session);
1367
+ return;
1368
+ }
1369
+ if (compactHeld(sessionId, session, true)) return;
1370
+ if (session.compactBuffer?.length) {
1371
+ flushCompactBuffer(sessionId, session);
1372
+ return;
1373
+ }
1374
+ const trigger = compactDue(session.mapping.compact ?? { auto: false, threshold: 1 }, session.contextFill, !!session.compactRequested);
1375
+ if (!trigger) return;
1376
+ if (trigger === "auto" && session.compactFailedAt && Date.now() - session.compactFailedAt < COMPACT_RETRY_MS) return;
1377
+ session.compactRequested = false;
1378
+ const compacting = { phase: "checkpoint", trigger, startedAt: Date.now() };
1379
+ session.compacting = compacting;
1380
+ runLog(rootOf(sessionId), { event: "compact.started", sessionId, agent: session.mapping.agent.name, trigger, ...session.contextFill !== void 0 ? { fill: Math.round(session.contextFill * 100) / 100 } : {} });
1381
+ const work = queue.then(async () => {
1382
+ if (session.compacting !== compacting) return;
1383
+ if (session.closed || compactHeld(sessionId, session, true)) {
1384
+ session.compacting = void 0;
1385
+ if (trigger === "manual") session.compactRequested = true;
1386
+ compactReleased(sessionId, session);
1387
+ return;
1388
+ }
1389
+ compacting.turn = true;
1390
+ await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: "auto", content: [{ type: "text", text: checkpointPrompt(trigger, session.contextFill) }] }, "wake");
1391
+ }).catch((error) => compactFailed(sessionId, session, errorData(error).message));
1392
+ queue = work.catch(() => {
1138
1393
  });
1139
1394
  }
1140
- async function restoreAfterCompaction(sessionId, session) {
1395
+ async function compactNow(sessionId, session) {
1396
+ const current = session.compacting;
1397
+ const checkpoint = current.checkpoint;
1398
+ if (NATIVE_COMPACT.includes(session.runtimeKind)) {
1399
+ current.phase = "native";
1400
+ try {
1401
+ await session.runtime.request("thread/compact/start", { threadId: session.threadId, ...session.runtimeKind === "codex" ? {} : { instructions: compactInstructions(checkpoint) } });
1402
+ if (session.compacting !== current) return;
1403
+ current.requested = true;
1404
+ const timer = setTimeout(() => {
1405
+ if (session.compacting === current) compactFailed(sessionId, session, "the runtime reported no compaction in time");
1406
+ }, COMPACT_NATIVE_MS);
1407
+ timer.unref?.();
1408
+ return;
1409
+ } catch (error) {
1410
+ if (session.compacting !== current) return;
1411
+ runLog(rootOf(sessionId), { event: "compact.native_failed", sessionId, agent: session.mapping.agent.name, error: errorData(error).message });
1412
+ }
1413
+ }
1414
+ current.phase = "fresh";
1415
+ const work = queue.then(async () => {
1416
+ if (session.compacting !== current || session.closed) return;
1417
+ const refusal = restartRefusal(sessionId, session);
1418
+ if (refusal && refusal !== MAIL_WAITS && refusal !== REVIEWING) {
1419
+ compactFailed(sessionId, session, `a fresh conversation cannot start now: ${refusal}`);
1420
+ return;
1421
+ }
1422
+ await restartNative(sessionId, session, void 0);
1423
+ emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
1424
+ await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: "auto", content: [{ type: "text", text: seedPrompt(checkpoint, session.lastUserText) }] }, "wake");
1425
+ compactFinished(sessionId, session, "fresh");
1426
+ }).catch((error) => compactFailed(sessionId, session, errorData(error).message));
1427
+ queue = work.catch(() => {
1428
+ });
1429
+ }
1430
+ function compactFinished(sessionId, session, via) {
1431
+ const current = session.compacting;
1432
+ if (!current) return;
1433
+ session.compacting = void 0;
1434
+ session.compactFailedAt = void 0;
1435
+ session.contextFill = void 0;
1436
+ session.compactCooling = true;
1437
+ 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 });
1438
+ const text2 = wordsFor(session).compacted(via === "native");
1439
+ emit(sessionId, { type: "item", item: { kind: "notice", id: `notice-${randomUUID().slice(0, 8)}`, level: "info", text: text2 } });
1440
+ compactReleased(sessionId, session);
1441
+ }
1442
+ function compactFailed(sessionId, session, reason) {
1443
+ const current = session.compacting;
1444
+ session.compacting = void 0;
1445
+ session.compactFailedAt = Date.now();
1446
+ runLog(rootOf(sessionId), { event: "compact.failed", sessionId, agent: session.mapping.agent.name, ...current ? { trigger: current.trigger } : {}, error: reason });
1447
+ if (!session.closed) emit(sessionId, { type: "item", item: { kind: "notice", id: `notice-${randomUUID().slice(0, 8)}`, level: "warning", text: wordsFor(session).compactFailed(reason) } });
1448
+ compactReleased(sessionId, session);
1449
+ }
1450
+ function compactReleased(sessionId, session) {
1451
+ queueMicrotask(() => {
1452
+ if (session.closed || session.compacting) return;
1453
+ flushCompactBuffer(sessionId, session);
1454
+ if (session.wakeHeld && !holdsWake(session)) {
1455
+ session.wakeHeld = false;
1456
+ deliver(sessionId, session);
1457
+ }
1458
+ });
1459
+ }
1460
+ function flushCompactBuffer(sessionId, session) {
1461
+ if (session.compacting || session.active || !session.compactBuffer?.length) return;
1462
+ const held2 = session.compactBuffer.splice(0);
1463
+ session.compactBuffer = void 0;
1464
+ const work = queue.then(async () => {
1465
+ for (const [index, input] of held2.entries()) {
1466
+ await promptSession(sessionId, { ...input, delivery: index === 0 && !session.active ? "auto" : "steer" }, true);
1467
+ }
1468
+ });
1469
+ queue = work.catch(() => {
1470
+ });
1471
+ }
1472
+ function requestCompact(sessionId) {
1473
+ const session = sessions.get(sessionId);
1474
+ if (!session || session.closed) throw new ConversationError("session_busy", "The session is not open");
1475
+ if (session.parent || session.role === "supervisor") throw new ConversationError("runtime_unsupported", "Only a root session is compacted");
1476
+ if (session.compacting) return { status: "running" };
1477
+ session.compactRequested = true;
1478
+ if (compactHeld(sessionId, session, true)) return { status: "deferred" };
1479
+ compactAtBoundary(sessionId, session);
1480
+ return { status: "started" };
1481
+ }
1482
+ async function restoreAfterCompaction(sessionId, session, checkpoint) {
1141
1483
  const parts = ["Your context was just compacted. In case the summary lost any of it, this is what ALP holds of your work now."];
1142
1484
  if (session.parent && session.brief) parts.push(`Your assignment from ${session.parentAgent ?? "your requester"}, as it was given:
1143
1485
  ${cut(session.brief, BRIEF_CHARS)}`);
@@ -1148,7 +1490,7 @@ ${cut(session.brief, BRIEF_CHARS)}`);
1148
1490
  if (session.worktrees.size) {
1149
1491
  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"));
1150
1492
  }
1151
- const asked = [...userQuestions.values()].filter((pending) => pending.question.sessionId === sessionId);
1493
+ const asked = [...userQuestions.values()].filter((pending) => pending.question.sessionId === sessionId && !pending.gate);
1152
1494
  if (asked.length) parts.push("Waiting for the user to answer:\n" + asked.map((pending) => `- ${clip(pending.question.body, 300)}`).join("\n"));
1153
1495
  if (!session.parent) {
1154
1496
  const project = session.mapping.agent.projectRoot;
@@ -1157,6 +1499,8 @@ ${cut(session.brief, BRIEF_CHARS)}`);
1157
1499
  const board = renderBoard(await boardOf(project));
1158
1500
  if (board) parts.push(board);
1159
1501
  }
1502
+ if (checkpoint) parts.push(`The checkpoint you wrote before the compaction, by skill compact:
1503
+ ${cut(checkpoint, BRIEF_CHARS)}`);
1160
1504
  parts.push("Carry on where you were; alp_board and alp_task tell you more.");
1161
1505
  if (session.closed) return;
1162
1506
  post(sessionId, { kind: "note", from: "alp", assignment: sessionId, body: parts.join("\n\n"), ...session.active ? {} : { passive: true } });
@@ -1227,7 +1571,7 @@ ${cut(session.brief, BRIEF_CHARS)}`);
1227
1571
  return [path.join(mapping.agent.projectRoot, ".alp", LESSONS_FILE), ...options.libraryDir ? [path.join(options.libraryDir, LESSONS_FILE)] : []];
1228
1572
  }
1229
1573
  async function confirm(sessionId, session, body, approval) {
1230
- if ([...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId)) return { approved: false, outcome: "busy", feedback: "A question is already waiting for the user" };
1574
+ 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" };
1231
1575
  const say = wordsFor(session);
1232
1576
  const result = await askUser(sessionId, session, void 0, body, [say.approve, say.reject], approval);
1233
1577
  let value;
@@ -1269,7 +1613,8 @@ description: ${JSON.stringify(args.description.replace(/\s+/g, " ").trim())}
1269
1613
 
1270
1614
  ${args.body.trim()}
1271
1615
  `;
1272
- const lessons = (args.lessons ?? []).map((lesson) => lesson.replace(/\s+/g, " ").trim());
1616
+ const normalizeLesson = (lesson) => lesson.replace(/\s+/g, " ").trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, "").trim();
1617
+ const lessons = [...new Set((args.lessons ?? []).map(normalizeLesson))];
1273
1618
  const draftKey = JSON.stringify(["skill", content, args.roles, lessons, !!args.replace]);
1274
1619
  const key = `skill:${args.requestId ?? draftKey}`;
1275
1620
  const approvals = approvalsOf(sessionId);
@@ -1291,7 +1636,7 @@ ${args.body.trim()}
1291
1636
  return toolResult(false, { error: errorData(error).message });
1292
1637
  }
1293
1638
  if (approvalCanceled(session, cancellation)) return toolResult(false, { error: "Skill proposal canceled or session closed; no approval was created" });
1294
- 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" });
1639
+ 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" });
1295
1640
  const approvalId = `q-${randomUUID()}`;
1296
1641
  const record2 = { approvalId, draftKey };
1297
1642
  approvals.set(key, record2);
@@ -1328,8 +1673,10 @@ ${content}`,
1328
1673
  if (current === void 0) continue;
1329
1674
  const kept = current.split("\n").filter((line) => {
1330
1675
  const match = /^- \d{4}-\d\d-\d\d: (.*)$/.exec(line);
1331
- if (!match || !lessons.includes(match[1].trim())) return true;
1332
- removed.add(match[1].trim());
1676
+ if (!match) return true;
1677
+ const lesson = normalizeLesson(line);
1678
+ if (!lessons.includes(lesson)) return true;
1679
+ removed.add(lesson);
1333
1680
  return false;
1334
1681
  });
1335
1682
  if (kept.length !== current.split("\n").length) await writeFile(lessonFile, kept.join("\n")).catch(() => {
@@ -1357,6 +1704,197 @@ ${content}`,
1357
1704
  })();
1358
1705
  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." });
1359
1706
  }
1707
+ let scheduleHandler;
1708
+ async function lessonCurateTool(sessionId, session, args) {
1709
+ const cancellation = approvalCancellation.get(session) ?? 0;
1710
+ args = structuredClone(args);
1711
+ const validChange = (change) => plainObject(change, ["scope", "remove", "add", "reason"]) && ["project", "user"].includes(change.scope) && Array.isArray(change.remove) && change.remove.length > 0 && change.remove.length <= 50 && change.remove.every((lesson) => text(lesson, LESSON_CHARS)) && (change.add === void 0 || text(change.add, LESSON_CHARS)) && (change.reason === void 0 || typeof change.reason === "string" && change.reason.length <= 300);
1712
+ if (!plainObject(args, ["changes", "requestId"]) || !Array.isArray(args.changes) || !args.changes.length || args.changes.length > 50 || !args.changes.every(validChange)) {
1713
+ 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` });
1714
+ }
1715
+ if (args.requestId !== void 0 && !text(args.requestId, 100)) return toolResult(false, { error: "requestId must be a nonempty string of at most 100 characters" });
1716
+ const changes = args.changes;
1717
+ if (changes.some((change) => change.scope === "user") && !options.libraryDir) return toolResult(false, { error: "This host keeps no user lessons" });
1718
+ const fileOf = (scope) => scope === "user" ? path.join(options.libraryDir, LESSONS_FILE) : path.join(session.mapping.agent.projectRoot, ".alp", LESSONS_FILE);
1719
+ const normalizeLesson = (lesson) => lesson.replace(/\s+/g, " ").trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, "").trim();
1720
+ const normalized = changes.map((change) => ({ ...change, remove: [...new Set(change.remove.map(normalizeLesson))], add: change.add?.replace(/\s+/g, " ").trim() }));
1721
+ const draftKey = JSON.stringify(["lessons", normalized]);
1722
+ const key = `lessons:${args.requestId ?? draftKey}`;
1723
+ const approvals = approvalsOf(sessionId);
1724
+ const previous = approvals.get(key);
1725
+ if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: "requestId was already used for a different draft" });
1726
+ if (previous) return toolResult(true, previous.result ?? { status: "pending_approval", approvalId: previous.approvalId });
1727
+ const readLessons = async (file) => (await readFile(file, "utf8").catch(() => "")).split("\n").flatMap((line) => /^- \d{4}-\d\d-\d\d: /.test(line) ? [normalizeLesson(line)] : []);
1728
+ const missing = [];
1729
+ for (const change of normalized) {
1730
+ const recorded = new Set(await readLessons(fileOf(change.scope)));
1731
+ for (const lesson of change.remove) if (!recorded.has(lesson)) missing.push(`${change.scope}: ${lesson}`);
1732
+ }
1733
+ if (missing.length) return toolResult(false, { error: "These lessons are not recorded; copy their exact text from the lessons files", missing });
1734
+ if (approvalCanceled(session, cancellation)) return toolResult(false, { error: "Lesson proposal canceled or session closed; no approval was created" });
1735
+ 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" });
1736
+ const approvalId = `q-${randomUUID()}`;
1737
+ const record2 = { approvalId, draftKey };
1738
+ approvals.set(key, record2);
1739
+ const say = wordsFor(session);
1740
+ const shown = normalized.map((change, index) => `${index + 1}. ${say.lessonScope(change.scope, fileOf(change.scope))}${change.reason ? ` \u2014 ${change.reason}` : ""}
1741
+ ` + change.remove.map((lesson) => ` ${say.lessonRemove}: ${lesson}`).join("\n") + (change.add ? `
1742
+ ${say.lessonAdd}: ${change.add}` : "")).join("\n\n");
1743
+ const decision = confirm(sessionId, session, `${say.lessonCurate(session.mapping.agent.name, shown)}
1744
+
1745
+ ${say.answerLine(session.mapping.agent.name)}`, { id: approvalId });
1746
+ const apply = async () => {
1747
+ const removed = [];
1748
+ const notFound = [];
1749
+ let added = 0;
1750
+ for (const scope of ["project", "user"]) {
1751
+ const mine = normalized.filter((change) => change.scope === scope);
1752
+ if (!mine.length) continue;
1753
+ const file = fileOf(scope);
1754
+ const write = (lessonWrites.get(file) ?? Promise.resolve()).catch(() => {
1755
+ }).then(async () => {
1756
+ const current = await readFile(file, "utf8").catch(() => void 0);
1757
+ if (current === void 0) {
1758
+ for (const change of mine) notFound.push(...change.remove.map((lesson) => `${scope}: ${lesson}`));
1759
+ return;
1760
+ }
1761
+ const targets = new Set(mine.flatMap((change) => change.remove));
1762
+ const seen = /* @__PURE__ */ new Set();
1763
+ const kept = current.split("\n").filter((line) => {
1764
+ if (!/^- \d{4}-\d\d-\d\d: /.test(line)) return true;
1765
+ const lesson = normalizeLesson(line);
1766
+ if (!targets.has(lesson)) return true;
1767
+ seen.add(lesson);
1768
+ return false;
1769
+ });
1770
+ for (const lesson of targets) (seen.has(lesson) ? removed : notFound).push(`${scope}: ${lesson}`);
1771
+ const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1772
+ const additions = mine.filter((change) => change.add && change.remove.some((lesson) => seen.has(lesson))).map((change) => `- ${date}: ${change.add}`);
1773
+ added += additions.length;
1774
+ let body = kept.join("\n");
1775
+ if (additions.length) body = body.replace(/\n*$/, "\n") + additions.join("\n") + "\n";
1776
+ await writeFile(file, body);
1777
+ });
1778
+ lessonWrites.set(file, write);
1779
+ await write;
1780
+ }
1781
+ runLog(rootOf(sessionId), { event: "lesson.curate", agent: session.mapping.agent.name, removed, added, notFound });
1782
+ return { approved: true, applied: true, removed, added, ...notFound.length ? { lessonsNotFound: notFound } : {} };
1783
+ };
1784
+ void (async () => {
1785
+ const answer = await decision;
1786
+ const canceled = approvalCanceled(session, cancellation);
1787
+ let result;
1788
+ 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." };
1789
+ else {
1790
+ try {
1791
+ result = await apply();
1792
+ } catch (error) {
1793
+ result = { approved: true, applied: false, error: errorData(error).message, next: "Tell the user; nothing is retried automatically." };
1794
+ }
1795
+ }
1796
+ record2.result = { status: "resolved", approvalId, ...result };
1797
+ runLog(rootOf(sessionId), { event: "lesson.curate.approval", agent: session.mapping.agent.name, ...record2.result });
1798
+ if (!closed && !session.closed && sessions.get(sessionId) === session) post(sessionId, { kind: "result", from: "ALP", assignment: approvalId, body: `Lesson curate result: ${JSON.stringify(record2.result)}` });
1799
+ })();
1800
+ 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." });
1801
+ }
1802
+ const curateSchedules = /* @__PURE__ */ new Map();
1803
+ function ensureCurateSchedule(sessionId) {
1804
+ const root = sessions.get(sessionId);
1805
+ if (!scheduleHandler || !root || root.closed || root.parent) return Promise.resolve();
1806
+ const project = root.mapping.agent.projectRoot;
1807
+ const run = (curateSchedules.get(project) ?? Promise.resolve()).catch(() => {
1808
+ }).then(() => curateScheduleOf(sessionId, root, project));
1809
+ curateSchedules.set(project, run);
1810
+ void run.catch(() => {
1811
+ }).then(() => {
1812
+ if (curateSchedules.get(project) === run) curateSchedules.delete(project);
1813
+ });
1814
+ return run;
1815
+ }
1816
+ async function curateScheduleOf(sessionId, root, project) {
1817
+ const handler = scheduleHandler;
1818
+ if (!handler || root.closed || sessions.get(sessionId) !== root) return;
1819
+ for (const file of [path.join(project, ".alp", "settings.json"), ...options.libraryDir ? [path.join(options.libraryDir, "settings.json")] : []]) {
1820
+ const settings = await readFile(file, "utf8").then((raw) => {
1821
+ try {
1822
+ return JSON.parse(raw);
1823
+ } catch {
1824
+ return void 0;
1825
+ }
1826
+ }, () => void 0);
1827
+ const monthly = settings?.curate?.monthly;
1828
+ if (monthly === false) return;
1829
+ if (monthly === true) break;
1830
+ }
1831
+ const listed = await handler("list", { projectRoot: project, status: "pending" });
1832
+ const curate = (listed?.jobs ?? []).filter((job) => job.prompt.startsWith(CURATE_MARKER));
1833
+ if (curate.some((job) => job.sessionId === sessionId)) return;
1834
+ for (const job of curate) await handler("cancel", { id: job.id, projectRoot: project }).catch(() => {
1835
+ });
1836
+ const now = /* @__PURE__ */ new Date();
1837
+ const dueAt = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 2)).toISOString();
1838
+ await handler("create", { projectRoot: project, sessionId, dueAt, prompt: CURATE_PROMPT, keepsSession: false });
1839
+ runLog(sessionId, { event: "curate.scheduled", dueAt, replaced: curate.map((job) => job.id) });
1840
+ }
1841
+ async function scheduleTool(sessionId, session, args) {
1842
+ if (session.parent || session.role === "supervisor" || session.mapping.agent.name !== mainOf(session.mapping)) return toolResult(false, { error: "Only the main root session schedules continuations" });
1843
+ if (!scheduleHandler) return toolResult(false, { error: "This host does not support scheduled continuations" });
1844
+ if (!plainObject(args, ["action", "dueAt", "prompt", "requestId", "id", "status"]) || !["create", "list", "get", "cancel"].includes(args.action)) return toolResult(false, { error: "Unknown schedule action" });
1845
+ const action = args.action;
1846
+ const fields = action === "create" ? ["action", "dueAt", "prompt", "requestId"] : action === "list" ? ["action", "status"] : ["action", "id"];
1847
+ if (Object.keys(args).some((key2) => !fields.includes(key2))) return toolResult(false, { error: "Unexpected schedule argument" });
1848
+ const handler = scheduleHandler;
1849
+ const projectRoot = session.mapping.agent.projectRoot;
1850
+ const invoke = async (params) => {
1851
+ try {
1852
+ return toolResult(true, await handler(action, { ...params, projectRoot }));
1853
+ } catch (error) {
1854
+ return toolResult(false, { error: errorData(error).message });
1855
+ }
1856
+ };
1857
+ if (action !== "create") return invoke(action === "list" ? { ...args.status ? { status: args.status } : {} } : { id: args.id });
1858
+ if (!text(args.requestId, 200) || !text(args.prompt, 8e3) || !text(args.dueAt, 80) || !/^\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\u20138000 characters) and dueAt with an explicit UTC offset" });
1859
+ const draftKey = JSON.stringify([args.dueAt, args.prompt]);
1860
+ const key = `schedule:${args.requestId}`;
1861
+ const approvals = approvalsOf(sessionId);
1862
+ const previous = approvals.get(key);
1863
+ if (previous) return previous.draftKey !== draftKey ? toolResult(false, { error: "requestId already names another schedule draft" }) : toolResult(true, previous.result ?? { status: "pending_approval", approvalId: previous.approvalId });
1864
+ const cancellation = approvalCancellation.get(session) ?? 0;
1865
+ const approvalId = `q-${randomUUID()}`;
1866
+ const record2 = { approvalId, draftKey };
1867
+ approvals.set(key, record2);
1868
+ const decision = confirm(
1869
+ sessionId,
1870
+ session,
1871
+ `T\u1EA1o l\u1ECBch ti\u1EBFp t\u1EE5c m\u1ED9t l\u1EA7n?
1872
+ Project: ${projectRoot}
1873
+ Session: ${sessionId}
1874
+ Th\u1EDDi gian: ${args.dueAt} (${new Date(args.dueAt).toISOString()})
1875
+
1876
+ ${args.prompt}`,
1877
+ { id: approvalId }
1878
+ );
1879
+ void decision.then(async (answer) => {
1880
+ const canceled = approvalCanceled(session, cancellation);
1881
+ let result;
1882
+ if (!answer.approved || canceled) result = { approved: false, created: false, outcome: canceled ? "canceled" : answer.outcome, feedback: answer.feedback };
1883
+ else {
1884
+ try {
1885
+ result = { approved: true, created: true, ...await handler("create", { projectRoot, sessionId, dueAt: args.dueAt, prompt: args.prompt }) };
1886
+ } catch (error) {
1887
+ result = { approved: true, created: false, error: errorData(error).message };
1888
+ }
1889
+ }
1890
+ record2.result = { status: "resolved", approvalId, ...result };
1891
+ runLog(rootOf(sessionId), { event: "schedule.approval", ...record2.result });
1892
+ if (!session.closed) post(sessionId, { kind: "result", from: "ALP", assignment: approvalId, body: `Schedule approval result: ${JSON.stringify(record2.result)}` });
1893
+ }).catch((error) => {
1894
+ record2.result = { status: "resolved", approvalId, created: false, error: errorData(error).message };
1895
+ });
1896
+ 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." });
1897
+ }
1360
1898
  async function issueTool(sessionId, session, args) {
1361
1899
  const cancellation = approvalCancellation.get(session) ?? 0;
1362
1900
  args = structuredClone(args);
@@ -1404,7 +1942,7 @@ ${content}`,
1404
1942
  const previous = approvals.get(key);
1405
1943
  if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: "requestId was already used for a different draft" });
1406
1944
  if (previous) return toolResult(true, previous.result ?? { status: "pending_approval", approvalId: previous.approvalId, repo });
1407
- 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" });
1945
+ 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" });
1408
1946
  const approvalId = `q-${randomUUID()}`;
1409
1947
  const record2 = { approvalId, draftKey };
1410
1948
  approvals.set(key, record2);
@@ -1485,10 +2023,14 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1485
2023
  }
1486
2024
  if (!hasActiveMail(session)) return;
1487
2025
  const waking = !session.assignments.size || session.mail.some((event) => !event.deliveredTurn && !event.passive && !(event.kind === "note" && event.assignment !== sessionId));
2026
+ if (!session.active && waking && holdsWake(session)) {
2027
+ session.wakeHeld = true;
2028
+ return;
2029
+ }
1488
2030
  if (session.pending) {
1489
2031
  void session.acknowledged.then(() => deliver(sessionId, session));
1490
2032
  } else if (session.active) {
1491
- if (session.mail.some((event) => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
2033
+ if (!session.compacting && session.mail.some((event) => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
1492
2034
  } else if (!waking) {
1493
2035
  return;
1494
2036
  } else if (!session.wakeBlocked && session.wakeFailures < MAX_WAKES && (session.wakes < MAX_WAKES || session.mail.some((event) => !event.deliveredTurn && event.kind === "checkin"))) {
@@ -1508,7 +2050,7 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1508
2050
  try {
1509
2051
  await session.runtime.request("turn/steer", { threadId: session.threadId, expectedTurnId: turnId, clientUserMessageId: id, input: [{ type: "text", text: text2, text_elements: [] }] });
1510
2052
  steered = true;
1511
- emit(sessionId, { type: "item", item: { kind: "user_message", id: `user:${id}`, clientMessageId: id, text: text2 } });
2053
+ emit(sessionId, { type: "item", item: { kind: "user_message", id: `user:${id}`, clientMessageId: id, text: text2, origin: "wake" } });
1512
2054
  } catch {
1513
2055
  }
1514
2056
  const received = steered && session.active === turnId;
@@ -1521,7 +2063,7 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1521
2063
  if (!received) deliver(sessionId, session);
1522
2064
  }
1523
2065
  function autoWake(sessionId, session) {
1524
- if (held(session)) {
2066
+ if (holdsWake(session)) {
1525
2067
  session.wakeHeld = true;
1526
2068
  return;
1527
2069
  }
@@ -1534,6 +2076,11 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1534
2076
  };
1535
2077
  const work = queue.then(async () => {
1536
2078
  if (closed || session.closed) return release();
2079
+ if (holdsWake(session)) {
2080
+ release();
2081
+ session.wakeHeld = true;
2082
+ return;
2083
+ }
1537
2084
  if (session.wakeBlocked || session.active || session.pending) {
1538
2085
  release();
1539
2086
  return deliver(sessionId, session);
@@ -1675,7 +2222,8 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1675
2222
  lineage,
1676
2223
  runLog,
1677
2224
  runHooks,
1678
- touchTask
2225
+ touchTask,
2226
+ releaseResult: (assignmentId) => assignmentResults.remove(assignmentId)
1679
2227
  });
1680
2228
  async function settleTask(parent, assignment, state, handoff) {
1681
2229
  const project = parent.mapping.agent.projectRoot;
@@ -1695,18 +2243,44 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1695
2243
  async function finishAssignment(parentId, parent, assignment, state, error, quiet = false) {
1696
2244
  if (assignment.finished) return;
1697
2245
  assignment.finished = true;
2246
+ const child = assignmentSessions.get(assignment);
1698
2247
  if (closed && inFlight.get(assignment.id)) {
1699
2248
  runLog(assignment.rootId, { event: "assignment.interrupted", assignmentId: assignment.id, agent: assignment.agent, reason: "alpd stopped" });
1700
- await closeSession(assignment.id);
2249
+ if (child) await closeSession(assignment.id, child);
1701
2250
  if (assignment.lease && leases.get(assignment.lease)?.assignment === assignment.id) leases.delete(assignment.lease);
1702
- childContexts.delete(assignment.id);
1703
- parent.children.delete(assignment.id);
1704
- parent.assignments.delete(assignment.id);
2251
+ if (!sessions.has(assignment.id) || sessions.get(assignment.id) === child) {
2252
+ childContexts.delete(assignment.id);
2253
+ parent.children.delete(assignment.id);
2254
+ }
2255
+ if (parent.assignments.get(assignment.id) === assignment) parent.assignments.delete(assignment.id);
2256
+ return;
2257
+ }
2258
+ const resultChild = child;
2259
+ try {
2260
+ if (assignment.worktree || writes(assignment.mode)) await assignmentResults.put({
2261
+ assignmentId: assignment.id,
2262
+ checkout: assignment.worktree?.checkout ?? assignment.writeCheckout ?? resultChild?.mapping.workdir ?? parent.mapping.workdir,
2263
+ ...assignment.worktree ? { worktree: assignment.worktree.path } : {},
2264
+ // Outside a worktree, the change stays in the checkout: keep its evidence until the requester resolves it.
2265
+ ...!assignment.worktree ? { result: {
2266
+ agent: assignment.agent,
2267
+ status: state,
2268
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
2269
+ project: (resultChild ?? parent).mapping.agent.projectRoot,
2270
+ requesters: lineage(parentId),
2271
+ ...assignment.taskId ? { taskId: assignment.taskId } : {},
2272
+ brief: cut(resultChild?.brief ?? "", RESULT_EVIDENCE_CHARS),
2273
+ summary: cut(JSON.stringify({ handoff: resultChild?.handoff ?? null, output: resultChild ? [...resultChild.text.values()].at(-1) ?? "" : "", ...error ? { error: errorData(error).message } : {} }), RESULT_EVIDENCE_CHARS)
2274
+ } } : {}
2275
+ });
2276
+ } catch (failure) {
2277
+ assignment.finished = false;
2278
+ log.error("could not persist assignment result ownership", { assignmentId: assignment.id, error: failure });
2279
+ 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.` });
1705
2280
  return;
1706
2281
  }
1707
2282
  void inFlight.remove(assignment.id);
1708
- const child = sessions.get(assignment.id);
1709
- if (child && state === "failed" && child.active) terminal(assignment.id, child, "failed", error);
2283
+ if (child && sessions.get(assignment.id) === child && state === "failed" && child.active) terminal(assignment.id, child, "failed", error);
1710
2284
  assignment.ask?.resolve(toolResult(false, { error: "Assignment ended" }));
1711
2285
  const result = {
1712
2286
  agent: assignment.agent,
@@ -1717,7 +2291,7 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1717
2291
  output: child ? [...child.text.values()].at(-1) ?? "" : "",
1718
2292
  ...error ? { error: errorData(error).message } : {}
1719
2293
  };
1720
- await closeSession(assignment.id);
2294
+ if (child) await closeSession(assignment.id, child);
1721
2295
  if (child?.threadId && child.mapping.keepThread && child.runtimeKind !== "acp") {
1722
2296
  void recalls.add({
1723
2297
  assignmentId: assignment.id,
@@ -1768,9 +2342,11 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1768
2342
  ...result
1769
2343
  });
1770
2344
  if (!parent.closed) emit(parentId, { type: "assignment", assignment: assignmentSnapshot(assignment, state) });
1771
- childContexts.delete(assignment.id);
1772
- parent.children.delete(assignment.id);
1773
- parent.assignments.delete(assignment.id);
2345
+ if (!sessions.has(assignment.id) || sessions.get(assignment.id) === child) {
2346
+ childContexts.delete(assignment.id);
2347
+ parent.children.delete(assignment.id);
2348
+ }
2349
+ if (parent.assignments.get(assignment.id) === assignment) parent.assignments.delete(assignment.id);
1774
2350
  if (roleOf(parent.mapping, assignment.agent) === "peer") {
1775
2351
  const root = sessions.get(assignment.rootId);
1776
2352
  if (root) root.peerCount--;
@@ -1785,7 +2361,7 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1785
2361
  error: "ALP tools require the current active turn"
1786
2362
  });
1787
2363
  }
1788
- if (!["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) || params.namespace != null || typeof params.callId !== "string") {
2364
+ if (!["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) || params.namespace != null || typeof params.callId !== "string") {
1789
2365
  return toolResult(false, {
1790
2366
  error: "Unknown ALP tool"
1791
2367
  });
@@ -1793,10 +2369,12 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1793
2369
  const cached = session.toolCalls.get(params.callId);
1794
2370
  if (cached) return cached;
1795
2371
  const args = params.arguments;
2372
+ const oversized = inputLimitError(args, TOOL_INPUT, `${params.tool} input`);
2373
+ if (oversized) return toolResult(false, { error: oversized });
1796
2374
  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" });
1797
- if ((params.tool === "alp_lesson" || params.tool === "alp_skill") && !supervises(session)) return toolResult(false, { error: "Only a supervised main records lessons and skills" });
2375
+ 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" });
1798
2376
  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" });
1799
- const work = params.tool === "alp_lesson" ? lessonTool(sessionId, session, args) : params.tool === "alp_skill" ? skillTool(sessionId, session, args) : params.tool === "alp_issue" ? issueTool(sessionId, session, args) : params.tool === "alp_task" ? taskToolCall(sessionId, session, args) : params.tool === "alp_delegate" ? runDelegation(sessionId, session, params) : params.tool === "alp_wait" ? waitTool(sessionId, session, args) : params.tool === "alp_ask" ? askTool(sessionId, session, args) : params.tool === "alp_pin" ? pinTool(sessionId, session, args) : params.tool === "alp_board" ? boardTool(session, args) : params.tool === "alp_unpin" ? unpinTool(sessionId, session, args) : params.tool === "alp_recall" ? recallTool(sessionId, session, args) : params.tool === "alp_verify" ? verifyTool(sessionId, session, args) : params.tool === "alp_cancel" ? cancelTool(sessionId, session, args) : params.tool === "alp_merge" || params.tool === "alp_discard" ? worktreeTool(sessionId, session, args, params.tool === "alp_merge" ? "merge" : "discard") : params.tool === "alp_send" ? Promise.resolve(sendTool(sessionId, session, args)) : hookedHandoff(sessionId, session, args);
2377
+ const work = params.tool === "alp_lesson" ? lessonTool(sessionId, session, args) : params.tool === "alp_lesson_curate" ? lessonCurateTool(sessionId, session, args) : params.tool === "alp_skill" ? skillTool(sessionId, session, args) : params.tool === "alp_issue" ? issueTool(sessionId, session, args) : params.tool === "alp_schedule" ? scheduleTool(sessionId, session, args) : params.tool === "alp_task" ? taskToolCall(sessionId, session, args) : params.tool === "alp_delegate" ? runDelegation(sessionId, session, params) : params.tool === "alp_wait" ? waitTool(sessionId, session, args) : params.tool === "alp_ask" ? askTool(sessionId, session, args) : params.tool === "alp_pin" ? pinTool(sessionId, session, args) : params.tool === "alp_board" ? boardTool(session, args) : params.tool === "alp_unpin" ? unpinTool(sessionId, session, args) : params.tool === "alp_recall" ? recallTool(sessionId, session, args) : params.tool === "alp_resolve" ? resolveTool(sessionId, session, args) : params.tool === "alp_verify" ? verifyTool(sessionId, session, args) : params.tool === "alp_cancel" ? cancelTool(sessionId, session, args) : params.tool === "alp_merge" || params.tool === "alp_discard" ? worktreeTool(sessionId, session, args, params.tool === "alp_merge" ? "merge" : "discard") : params.tool === "alp_send" ? Promise.resolve(sendTool(sessionId, session, args)) : hookedHandoff(sessionId, session, args);
1800
2378
  const reminded = !session.parent && params.tool !== "alp_ask" ? work.then((result) => remindUser(session, result)) : work;
1801
2379
  session.toolCalls.set(params.callId, reminded);
1802
2380
  return reminded;
@@ -1937,10 +2515,126 @@ The user answered: "${answer}"`);
1937
2515
  post(session.parent, { kind: "note", from: session.mapping.agent.name, assignment: sessionId, body: `[ALP, on behalf of ${session.mapping.agent.name}] ${body}` });
1938
2516
  }
1939
2517
  function cancelQuestions(sessionId, turnOnly = false) {
1940
- for (const { question, settle, persistent } of [...userQuestions.values()]) {
2518
+ for (const { question, settle, persistent, gate } of [...userQuestions.values()]) {
2519
+ if (gate && turnOnly) continue;
1941
2520
  if (question.sessionId === sessionId && (!turnOnly || !persistent)) settle("canceled", void 0, void 0, toolResult(false, { error: "Turn ended" }));
1942
2521
  }
1943
2522
  }
2523
+ const gateSyncs = /* @__PURE__ */ new Map();
2524
+ const gateCardId = (taskId, gateId) => `gate-${taskId}-${gateId}`;
2525
+ function mainSessionOf(projectRoot) {
2526
+ for (const [id, session] of sessions) {
2527
+ if (session.closed || session.parent || session.role === "supervisor" || !session.threadId) continue;
2528
+ if (session.mapping.agent.name !== mainOf(session.mapping) || path.resolve(session.mapping.agent.projectRoot) !== projectRoot) continue;
2529
+ return { id, session };
2530
+ }
2531
+ return void 0;
2532
+ }
2533
+ function syncGates(projectRoot) {
2534
+ const root = path.resolve(projectRoot);
2535
+ const previous = gateSyncs.get(root) ?? Promise.resolve();
2536
+ const next = previous.then(() => syncGatesNow(root)).catch((error) => {
2537
+ runLog(mainSessionOf(root)?.id ?? root, { event: "gate.sync.failed", projectRoot: root, error: errorData(error).message });
2538
+ });
2539
+ gateSyncs.set(root, next);
2540
+ void next.finally(() => {
2541
+ if (gateSyncs.get(root) === next) gateSyncs.delete(root);
2542
+ });
2543
+ return next;
2544
+ }
2545
+ async function syncGatesNow(projectRoot) {
2546
+ if (closed) return;
2547
+ const { tasks } = await loadTasks(projectRoot);
2548
+ const main = mainSessionOf(projectRoot);
2549
+ if (main) for (const { task, gate, decision, record: record2 } of gateDecisions(tasks)) {
2550
+ if (!await markGateNotified(projectRoot, task.id, gate.id, decision)) continue;
2551
+ const choice = decision === "approved" ? record2.choice : void 0;
2552
+ const words2 = decision === "approved" ? `The user approved human gate ${gate.id} of ${task.id} in ${record2.channel}${choice ? `, choosing "${choice}"` : ""}${record2.note ? `: ${record2.note}` : ""}.` : `The user rejected human gate ${gate.id} of ${task.id} in ${record2.channel}${record2.reason ? `: ${record2.reason}` : ""}. The gate stays open.`;
2553
+ post(main.id, { kind: "result", from: "ALP", assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words2} Task: ${task.title}` });
2554
+ runLog(main.id, { event: "gate.decision", projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record2.channel, ...choice ? { choice } : {} });
2555
+ }
2556
+ const wanted = /* @__PURE__ */ new Map();
2557
+ for (const task of tasks) {
2558
+ if (task.status === "closed") continue;
2559
+ for (const gate of task.gates ?? []) if (gate.kind === "human" && !gate.resolved && !gate.rejected) wanted.set(gateCardId(task.id, gate.id), { task, gate });
2560
+ }
2561
+ for (const [id, pending] of [...userQuestions]) {
2562
+ if (pending.question.gate?.projectRoot !== projectRoot) continue;
2563
+ const want = wanted.get(id);
2564
+ if (!want || !main || pending.question.sessionId !== main.id) {
2565
+ const task = tasks.find((entry) => entry.id === pending.question.gate.taskId);
2566
+ const gate = task?.gates.find((entry) => entry.id === pending.question.gate.gateId);
2567
+ pending.settle(gate?.resolved ? "answered" : gate?.rejected ? "dismissed" : "canceled", gate?.resolved?.choice, gate?.rejected?.reason);
2568
+ } else if (pending.gate) pending.gate.rev = want.task.rev;
2569
+ }
2570
+ if (!main) return;
2571
+ for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
2572
+ }
2573
+ let gateWatch;
2574
+ function startGateWatch() {
2575
+ if (gateWatch || options.gateSyncMs === 0) return;
2576
+ gateWatch = setInterval(() => {
2577
+ 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)));
2578
+ for (const root of roots) void syncGates(root);
2579
+ if (!roots.size) {
2580
+ clearInterval(gateWatch);
2581
+ gateWatch = void 0;
2582
+ }
2583
+ }, options.gateSyncMs ?? 5e3);
2584
+ gateWatch.unref?.();
2585
+ }
2586
+ function showGateCard(sessionId, session, projectRoot, task, gate) {
2587
+ const say = wordsFor(session);
2588
+ const vietnamese = say.approve === words("vi").approve;
2589
+ const question = {
2590
+ id: gateCardId(task.id, gate.id),
2591
+ sessionId,
2592
+ rootId: rootOf(sessionId),
2593
+ agent: "ALP",
2594
+ body: `${vietnamese ? `C\u1ED5ng ph\xEA duy\u1EC7t ${gate.id} c\u1EE7a ${task.id}` : `Approval gate ${gate.id} of ${task.id}`} (${task.title}):
2595
+ ${gate.note ?? ""}`,
2596
+ // Options approve; Reject (added after them unless one of them is that word) keeps the gate open.
2597
+ options: gate.options?.length ? gate.options.includes(say.reject) ? gate.options : [...gate.options, say.reject] : [say.approve, say.reject],
2598
+ askedAt: gate.at ?? (/* @__PURE__ */ new Date()).toISOString(),
2599
+ gate: { projectRoot, taskId: task.id, gateId: gate.id }
2600
+ };
2601
+ const card = { rev: task.rev, deciding: false };
2602
+ const settle = (outcome, answer) => {
2603
+ if (userQuestions.get(question.id)?.question !== question) return;
2604
+ userQuestions.delete(question.id);
2605
+ emit(sessionId, { type: "question.resolved", questionId: question.id, outcome, ...answer !== void 0 ? { answer } : {} });
2606
+ };
2607
+ userQuestions.set(question.id, { question, settle, persistent: true, gate: Object.assign(card, { decide: (reply) => decideGate(projectRoot, question, card, reply, gate.options?.length ? gate.options : void 0) }) });
2608
+ emit(sessionId, { type: "question", question });
2609
+ runLog(rootOf(sessionId), { event: "gate.card", questionId: question.id, taskId: task.id, gateId: gate.id });
2610
+ }
2611
+ async function decideGate(projectRoot, question, card, reply, choices) {
2612
+ const defaults = !choices;
2613
+ if (card.deciding) return;
2614
+ card.deciding = true;
2615
+ const { taskId, gateId } = question.gate;
2616
+ const channel = reply.channel ?? "web";
2617
+ const text2 = reply.text?.trim();
2618
+ const approve2 = !reply.dismiss && !!text2 && (defaults ? APPROVALS.includes(text2.toLowerCase()) : choices.includes(text2));
2619
+ const rejectReason = reply.dismiss ? reply.reason : text2 && CHOICES_REJECT.includes(text2.toLowerCase()) ? void 0 : text2;
2620
+ const write = (ifRev) => approve2 ? resolveGate(projectRoot, taskId, gateId, { by: "user", ifRev, channel, ...defaults ? {} : { choice: text2 } }) : rejectGate(projectRoot, taskId, gateId, { by: "user", ifRev, channel, ...rejectReason ? { reason: rejectReason.slice(0, 2e3) } : {} });
2621
+ try {
2622
+ try {
2623
+ await write(card.rev);
2624
+ } catch (error) {
2625
+ if (error?.code !== "TASK_CHANGED") throw error;
2626
+ const current = (await loadTasks(projectRoot)).tasks.find((entry) => entry.id === taskId);
2627
+ const gate = current?.gates.find((entry) => entry.id === gateId);
2628
+ if (!current || current.status === "closed" || !gate || gate.resolved || gate.rejected) return;
2629
+ await write(current.rev);
2630
+ }
2631
+ } catch (error) {
2632
+ runLog(question.rootId, { event: "gate.answer.failed", questionId: question.id, error: errorData(error).message });
2633
+ } finally {
2634
+ card.deciding = false;
2635
+ await syncGates(projectRoot);
2636
+ }
2637
+ }
1944
2638
  function askTool(sessionId, session, args) {
1945
2639
  const parent = session.parent ? sessions.get(session.parent) : void 0;
1946
2640
  const assignment = parent?.assignments.get(sessionId);
@@ -1952,7 +2646,7 @@ The user answered: "${answer}"`);
1952
2646
  if (args.options !== void 0 && (to !== "user" || !Array.isArray(args.options) || args.options.length > 10 || !args.options.every((option) => typeof option === "string" && option.trim() && option.length <= 200))) {
1953
2647
  return Promise.resolve(toolResult(false, { error: "options are up to 10 short answers, for questions to the user" }));
1954
2648
  }
1955
- if (assignment?.ask || [...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId)) {
2649
+ if (assignment?.ask || [...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId && !pending.gate)) {
1956
2650
  return Promise.resolve(toolResult(false, { error: "A question is already waiting for an answer" }));
1957
2651
  }
1958
2652
  if (to === "user" && session.parent && !session.userOpened) {
@@ -1981,6 +2675,22 @@ The user answered: "${answer}"`);
1981
2675
  });
1982
2676
  }
1983
2677
  async function runDelegation(sessionId, session, params) {
2678
+ if (workspaceMutation) refuseMutation("workspace_busy", "A workspace mutation is in progress; retry after it finishes");
2679
+ admitting++;
2680
+ let released = false;
2681
+ const release = () => {
2682
+ if (!released) {
2683
+ released = true;
2684
+ admitting--;
2685
+ }
2686
+ };
2687
+ try {
2688
+ return await runDelegationAdmitted(sessionId, session, params, release);
2689
+ } finally {
2690
+ release();
2691
+ }
2692
+ }
2693
+ async function runDelegationAdmitted(sessionId, session, params, admitted) {
1984
2694
  const args = params.arguments;
1985
2695
  const targets = Object.hasOwn(
1986
2696
  session.graph,
@@ -2163,6 +2873,7 @@ The user answered: "${answer}"`);
2163
2873
  ...task ? { taskId: task.id } : {}
2164
2874
  });
2165
2875
  try {
2876
+ if (writes(childMode)) await assignmentResults.put({ assignmentId: childId, checkout });
2166
2877
  if (task) {
2167
2878
  const started = await startTask(project, task.id, { agent: args.agent, assignment: childId, pid: process.pid, pidStartedAt: OWN_START, epoch }, session.mapping.agent.name);
2168
2879
  assignment.taskId = started.id;
@@ -2177,8 +2888,11 @@ The user answered: "${answer}"`);
2177
2888
  if (continued) session.worktrees.set(args.continueFrom, continued);
2178
2889
  throw error;
2179
2890
  }
2180
- if (continued) await removeWorktree(continued.worktree, { deleteBranch: true }).catch(() => {
2181
- });
2891
+ await assignmentResults.put({ assignmentId: childId, checkout: assignment.worktree.checkout, worktree: assignment.worktree.path });
2892
+ if (continued) {
2893
+ await removeWorktree(continued.worktree, { deleteBranch: true });
2894
+ await assignmentResults.remove(args.continueFrom);
2895
+ }
2182
2896
  runLog(rootId, { event: "worktree.created", assignmentId: childId, branch: assignment.worktree.branch, base: assignment.worktree.base, ...continued ? { continuedFrom: args.continueFrom } : {} });
2183
2897
  } else if (sharedWriter) {
2184
2898
  assignment.fingerprint = await checkoutFingerprint(checkout).catch(() => void 0);
@@ -2202,8 +2916,10 @@ The user answered: "${answer}"`);
2202
2916
  thinking,
2203
2917
  mode: childMode
2204
2918
  };
2205
- await openSession(childId, childSpec, "skip", session.delegation);
2206
- const child = sessions.get(childId);
2919
+ await openSession(childId, childSpec, "skip", session.delegation, assignment);
2920
+ admitted();
2921
+ const child = assignmentSessions.get(assignment);
2922
+ if (child && sessions.get(childId) !== child) throw new Error("Child session was replaced during open");
2207
2923
  if (child) void runHooks(childId, child, "assignment.start", { assignment: childId, brief: clip(args.task, 2e3) }, args.taskId);
2208
2924
  if (!child || session.closed || session.active !== params.turnId) {
2209
2925
  throw new Error(
@@ -2267,6 +2983,11 @@ ${digest}` : "")
2267
2983
  }
2268
2984
  ]
2269
2985
  }, "assignment");
2986
+ child.awaitingBrief = false;
2987
+ if (child.wakeHeld) {
2988
+ child.wakeHeld = false;
2989
+ deliver(childId, child);
2990
+ }
2270
2991
  } catch (error) {
2271
2992
  session.mail = session.mail.filter((event2) => event2.deliveredTurn || event2.kind !== "result" || event2.assignment !== childId);
2272
2993
  await finishAssignment(sessionId, session, assignment, "failed", error, true);
@@ -2303,7 +3024,10 @@ ${digest}` : "")
2303
3024
  next: "Answer with alp_send kind answer, then alp_wait for this assignment."
2304
3025
  });
2305
3026
  }
2306
- async function openSession(sessionId, spec, history, delegation = true) {
3027
+ async function openSession(sessionId, spec, history, delegation = true, assignment) {
3028
+ return admission(() => openSessionAdmitted(sessionId, spec, history, delegation, assignment));
3029
+ }
3030
+ async function openSessionAdmitted(sessionId, spec, history, delegation = true, assignment) {
2307
3031
  if (sessions.has(sessionId)) {
2308
3032
  throw new Error(
2309
3033
  "Session is already open"
@@ -2350,6 +3074,8 @@ ${digest}` : "")
2350
3074
  toolCallId: context?.callId,
2351
3075
  parentAgent: context ? sessions.get(context.parent)?.mapping.agent.name : void 0,
2352
3076
  ...context?.role ? { role: context.role } : {},
3077
+ // A new assignment's first turn is its brief; mail that comes sooner waits for it.
3078
+ ...context && !context.role && !context.recovered ? { awaitingBrief: true } : {},
2353
3079
  journal: [],
2354
3080
  tasks: [],
2355
3081
  children: /* @__PURE__ */ new Set(),
@@ -2367,6 +3093,13 @@ ${digest}` : "")
2367
3093
  acknowledged: Promise.resolve(),
2368
3094
  worktrees: /* @__PURE__ */ new Map()
2369
3095
  };
3096
+ if (assignment) assignmentSessions.set(assignment, session);
3097
+ const finishPending = beginPending(session);
3098
+ const opening = {};
3099
+ openings.set(session, opening);
3100
+ const failedMeanwhile = () => {
3101
+ if (opening.failure !== void 0) throw opening.failure;
3102
+ };
2370
3103
  sessions.set(
2371
3104
  sessionId,
2372
3105
  session
@@ -2374,7 +3107,8 @@ ${digest}` : "")
2374
3107
  wire(sessionId, session, runtime);
2375
3108
  try {
2376
3109
  await runtime.initialize();
2377
- if (session.closed) {
3110
+ failedMeanwhile();
3111
+ if (session.closed || sessions.get(sessionId) !== session) {
2378
3112
  throw new Error(
2379
3113
  "Session closed during initialization"
2380
3114
  );
@@ -2391,11 +3125,15 @@ ${digest}` : "")
2391
3125
  }
2392
3126
  const nativeConfig = await configOf(session);
2393
3127
  noteInstructions(sessionId, session, nativeConfig.developerInstructions);
3128
+ const base = mapping.threadId ? spec.restore?.base : void 0;
3129
+ if (base && runtimeKind !== "claude") throw new Error(`A ${label(runtimeKind)} session has no base conversation; only Claude makes a fork on its first prompt`);
3130
+ if (base) session.base = base;
2394
3131
  const result = mapping.threadId ? await runtime.request(
2395
3132
  "thread/resume",
2396
3133
  {
2397
3134
  ...nativeConfig,
2398
- threadId: mapping.threadId
3135
+ threadId: mapping.threadId,
3136
+ ...base ? { base } : {}
2399
3137
  }
2400
3138
  ) : await runtime.request(
2401
3139
  "thread/start",
@@ -2405,13 +3143,16 @@ ${digest}` : "")
2405
3143
  }
2406
3144
  );
2407
3145
  session.threadId = result.thread.id;
2408
- if (session.closed) {
3146
+ failedMeanwhile();
3147
+ if (session.closed || sessions.get(sessionId) !== session) {
2409
3148
  throw new Error(
2410
3149
  "Session closed during thread creation"
2411
3150
  );
2412
3151
  }
2413
- session.pending = false;
3152
+ openings.delete(session);
2414
3153
  session.buffered = [];
3154
+ finishPending();
3155
+ openedSessions.add(session);
2415
3156
  emit(sessionId, {
2416
3157
  type: "session.opened",
2417
3158
  session: snapshot(sessionId, session),
@@ -2421,6 +3162,10 @@ ${digest}` : "")
2421
3162
  thinking: result.reasoningEffort ?? mapping.thinking
2422
3163
  }
2423
3164
  });
3165
+ if (!session.parent && session.role !== "supervisor" && mapping.agent.name === mainOf(mapping)) {
3166
+ void syncGates(mapping.agent.projectRoot);
3167
+ startGateWatch();
3168
+ }
2424
3169
  if (history === "replay") {
2425
3170
  for (const turn of result.thread.turns ?? []) {
2426
3171
  for (const item of turn.items ?? []) {
@@ -2437,11 +3182,12 @@ ${digest}` : "")
2437
3182
  return snapshot(sessionId, session);
2438
3183
  } catch (error) {
2439
3184
  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 });
2440
- session.closed = true;
2441
- sessions.delete(
2442
- sessionId
2443
- );
2444
- await runtime.close();
3185
+ const failed = openings.get(session);
3186
+ openings.delete(session);
3187
+ if (failed?.failure !== void 0) failSession(sessionId, session, failed.failure);
3188
+ const cleanup = closeSession(sessionId, session, false);
3189
+ finishPending();
3190
+ await cleanup;
2445
3191
  throw error;
2446
3192
  }
2447
3193
  }
@@ -2461,16 +3207,22 @@ ${digest}` : "")
2461
3207
  }
2462
3208
  });
2463
3209
  transport.onFailure((error) => {
2464
- if (session.closed || session.runtime !== transport) return;
3210
+ if (session.closed || session.runtime !== transport || sessions.get(sessionId) !== session) return;
3211
+ const opening = openings.get(session);
3212
+ if (opening) {
3213
+ opening.failure ??= error;
3214
+ return;
3215
+ }
2465
3216
  if (revivable(session)) void revive(sessionId, session, error);
2466
3217
  else failSession(sessionId, session, error);
2467
3218
  });
2468
3219
  }
2469
3220
  function failSession(sessionId, session, error) {
3221
+ if (session.closed || sessions.get(sessionId) !== session) return;
2470
3222
  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 });
2471
3223
  terminal(sessionId, session, "failed", error);
2472
3224
  session.settle?.("failed", error);
2473
- void closeSession(sessionId);
3225
+ void closeSession(sessionId, session);
2474
3226
  emit(sessionId, { type: "session.failed", error: errorData(error) });
2475
3227
  }
2476
3228
  function noteInstructions(sessionId, session, instructions) {
@@ -2520,40 +3272,415 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2520
3272
  const harness = label(session.runtimeKind);
2521
3273
  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 });
2522
3274
  runLog(rootOf(sessionId), { event: "session.restarted", sessionId, agent: session.mapping.agent.name, error: errorData(error).message, restarts: session.restarts.length });
3275
+ let interrupted;
2523
3276
  if (session.active) {
2524
3277
  session.parkReason = `its ${harness} process stopped`;
3278
+ session.parkPause = void 0;
2525
3279
  session.parkThen = `ALP is restarting the ${harness} process; this assignment continues by itself.`;
2526
3280
  terminal(sessionId, session, "failed", error);
3281
+ interrupted = session.parked;
2527
3282
  }
2528
3283
  const old = session.runtime;
2529
3284
  void old.close().catch(() => {
2530
3285
  });
3286
+ let finishPending = () => {
3287
+ };
2531
3288
  try {
2532
3289
  const transport = createTransport(options, session.runtimeKind, session.mapping.workdir, nativeEnvironment(options, session.mapping.env), session.mapping.acp, session.mapping.antigravity);
2533
3290
  session.runtime = transport;
2534
- session.pending = true;
3291
+ finishPending = beginPending(session);
2535
3292
  wire(sessionId, session, transport);
2536
3293
  await transport.initialize();
2537
3294
  const config = await configOf(session);
2538
- if (session.closed) return void transport.close().catch(() => {
2539
- });
2540
- await transport.request("thread/resume", { ...config, threadId: session.threadId });
2541
- if (session.closed) return void transport.close().catch(() => {
2542
- });
2543
- session.pending = false;
3295
+ if (session.closed) {
3296
+ finishPending();
3297
+ return void transport.close().catch(() => {
3298
+ });
3299
+ }
3300
+ await transport.request("thread/resume", { ...config, threadId: session.threadId, ...session.base ? { base: session.base } : {} });
3301
+ if (session.closed) {
3302
+ finishPending();
3303
+ return void transport.close().catch(() => {
3304
+ });
3305
+ }
2544
3306
  session.buffered = [];
3307
+ finishPending();
2545
3308
  runLog(rootOf(sessionId), { event: "session.revived", sessionId, agent: session.mapping.agent.name });
2546
- if (session.parked && !pauseOf(session.runtimeKind)) {
3309
+ if (session.parked && session.parked === interrupted) {
2547
3310
  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." : ""}`;
2548
3311
  continueParked(sessionId, session);
2549
3312
  }
2550
3313
  } catch (failure) {
2551
- session.pending = false;
3314
+ finishPending();
2552
3315
  session.parked = void 0;
2553
3316
  runLog(rootOf(sessionId), { event: "session.revive_failed", sessionId, agent: session.mapping.agent.name, error: errorData(failure).message });
2554
3317
  failSession(sessionId, session, error);
2555
3318
  }
2556
3319
  }
3320
+ function restartRefusal(sessionId, session) {
3321
+ if (!session || session.closed) return "The session is not open";
3322
+ if (session.parent || session.role === "supervisor") return "Only a root session can be restarted";
3323
+ if (session.pending) return "The session is still opening or restarting";
3324
+ if (session.active) return "A turn is running";
3325
+ if (session.children.size || session.assignments.size) return "Assignments are still running";
3326
+ if ([...userQuestions.values()].some((pending) => pending.question.rootId === sessionId && !pending.gate)) return "A question to the user waits for an answer";
3327
+ if ((hasActiveMail(session) || session.wakeHeld) && !session.lifecycleHolds) return MAIL_WAITS;
3328
+ if (session.parked || session.parkReason) return "The session is parked";
3329
+ if (reviewing(session)) return REVIEWING;
3330
+ return void 0;
3331
+ }
3332
+ async function restartNative(sessionId, session, binding, verify = true, shape) {
3333
+ const old = session.runtime;
3334
+ const finishPending = beginPending(session);
3335
+ await old.close().catch(() => {
3336
+ });
3337
+ const transport = createTransport(options, session.runtimeKind, session.mapping.workdir, nativeEnvironment(options, session.mapping.env), session.mapping.acp, session.mapping.antigravity);
3338
+ let failure;
3339
+ transport.onFailure((error) => {
3340
+ failure ??= error;
3341
+ });
3342
+ session.runtime = transport;
3343
+ let result;
3344
+ try {
3345
+ await transport.initialize();
3346
+ const config = await configOf(shape ? { ...session, ...shape } : session);
3347
+ noteInstructions(sessionId, session, config.developerInstructions);
3348
+ if (session.closed) throw new Error("Session closed during restart");
3349
+ result = binding ? await transport.request("thread/resume", {
3350
+ ...config,
3351
+ threadId: binding.threadId,
3352
+ ...binding.base ? { base: binding.base } : verify && session.runtimeKind === "claude" ? { requireHistory: true } : {}
3353
+ }) : await transport.request("thread/start", { ...config, ephemeral: !(shape ?? session).mapping.persist && !(shape ?? session).mapping.keepThread });
3354
+ if (failure) throw failure;
3355
+ if (session.closed) throw new Error("Session closed during restart");
3356
+ if (binding && result?.thread?.id !== void 0 && result.thread.id !== binding.threadId) throw new Error(`${label(session.runtimeKind)} resumed ${result.thread.id} instead of ${binding.threadId}`);
3357
+ if (!binding && typeof result?.thread?.id !== "string") throw new Error(`${label(session.runtimeKind)} started no conversation`);
3358
+ } catch (error) {
3359
+ await transport.close().catch(() => {
3360
+ });
3361
+ finishPending();
3362
+ throw error;
3363
+ }
3364
+ session.threadId = binding ? binding.threadId : result.thread.id;
3365
+ if (binding?.base) session.base = binding.base;
3366
+ else delete session.base;
3367
+ session.buffered = [];
3368
+ wire(sessionId, session, transport);
3369
+ finishPending();
3370
+ return result;
3371
+ }
3372
+ async function rebindSession(sessionId, binding) {
3373
+ const session = sessions.get(sessionId);
3374
+ const refusal = restartRefusal(sessionId, session);
3375
+ if (refusal) throw new ConversationError("session_busy", refusal);
3376
+ if (!plainObject(binding, ["threadId", "base"]) || typeof binding.threadId !== "string" || !binding.threadId || binding.base !== void 0 && (!plainObject(binding.base, ["threadId", "at"]) || typeof binding.base.threadId !== "string" || !binding.base.threadId || binding.base.at !== void 0 && typeof binding.base.at !== "string")) {
3377
+ throw new Error("A binding needs a threadId, and a base only with a threadId and an optional at");
3378
+ }
3379
+ if (binding.base && session.runtimeKind !== "claude") throw new ConversationError("runtime_unsupported", `A ${label(session.runtimeKind)} session has no base conversation`);
3380
+ const live2 = session;
3381
+ const previous = { threadId: live2.threadId, ...live2.base ? { base: live2.base } : {} };
3382
+ try {
3383
+ await restartNative(sessionId, live2, binding);
3384
+ } catch (error) {
3385
+ runLog(rootOf(sessionId), { event: "session.rebind_failed", sessionId, agent: live2.mapping.agent.name, threadId: binding.threadId, error: errorData(error).message });
3386
+ try {
3387
+ if (live2.closed) throw error;
3388
+ await restartNative(sessionId, live2, previous, false);
3389
+ } catch (reopen) {
3390
+ live2.pending = false;
3391
+ if (!live2.closed) failSession(sessionId, live2, reopen);
3392
+ }
3393
+ if (error instanceof ConversationError) throw error;
3394
+ throw new ConversationError("native_refused", `The conversation could not be opened: ${errorData(error).message}`, { outcomeUnknown: !!error?.outcomeUnknown });
3395
+ }
3396
+ runLog(rootOf(sessionId), { event: "session.rebound", sessionId, agent: live2.mapping.agent.name, from: previous.threadId, threadId: binding.threadId });
3397
+ const updated = snapshot(sessionId, live2);
3398
+ emit(sessionId, { type: "session.updated", session: updated });
3399
+ return updated;
3400
+ }
3401
+ async function reloadSession(sessionId) {
3402
+ const session = sessions.get(sessionId);
3403
+ const refusal = restartRefusal(sessionId, session);
3404
+ if (refusal) throw new ConversationError("session_busy", refusal);
3405
+ const live2 = session;
3406
+ if (!live2.threadId) throw new ConversationError("runtime_unsupported", "This session keeps no native conversation to reload");
3407
+ const binding = { threadId: live2.threadId, ...live2.base ? { base: live2.base } : {} };
3408
+ try {
3409
+ await restartNative(sessionId, live2, binding);
3410
+ } catch (error) {
3411
+ runLog(rootOf(sessionId), { event: "session.reload_failed", sessionId, agent: live2.mapping.agent.name, threadId: binding.threadId, error: errorData(error).message });
3412
+ if (!live2.closed) await closeSession(sessionId).catch(() => {
3413
+ });
3414
+ throw new ConversationError("native_refused", `The agent could not be restarted on its conversation: ${errorData(error).message}`);
3415
+ }
3416
+ runLog(rootOf(sessionId), { event: "session.reloaded", sessionId, agent: live2.mapping.agent.name, threadId: binding.threadId });
3417
+ const updated = snapshot(sessionId, live2);
3418
+ emit(sessionId, { type: "session.updated", session: updated });
3419
+ return updated;
3420
+ }
3421
+ async function effectiveConfig(session, shape) {
3422
+ const view = shape ? { ...session, ...shape } : session;
3423
+ const config = await configOf(view);
3424
+ const name = view.mapping.agent.name;
3425
+ return effectiveOf(session.runtimeKind, view.mapping, {
3426
+ delegates: Object.hasOwn(view.graph, name) ? view.graph[name] : [],
3427
+ tools: (config.dynamicTools ?? []).map((tool) => tool.name).filter((tool) => typeof tool === "string"),
3428
+ supervisor: supervises(view),
3429
+ instructionsSha: createHash("sha256").update(config.developerInstructions).digest("hex").slice(0, 12)
3430
+ });
3431
+ }
3432
+ async function planConfigure(session, changes) {
3433
+ const current = await effectiveConfig(session);
3434
+ const same = { shape: { mapping: session.mapping, graph: session.graph, spec: session.spec }, current, proposed: current, changes: [] };
3435
+ const refuse = (reason, message) => ({ ...same, refusal: { reason, message } });
3436
+ 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");
3437
+ 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`);
3438
+ for (const key of ["model", "thinking", "team", "mode"]) {
3439
+ const value = changes[key];
3440
+ if (value !== void 0 && (typeof value !== "string" || !value.trim() || value.length > 200)) return refuse("invalid_params", `${key} must be a nonempty name of at most 200 characters`);
3441
+ }
3442
+ const runtimeKind = session.runtimeKind;
3443
+ let model = session.mapping.model;
3444
+ if (changes.model !== void 0) {
3445
+ const named = nativeModelOf(runtimeKind, changes.model.trim());
3446
+ 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`);
3447
+ 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`);
3448
+ model = named.model;
3449
+ }
3450
+ const projectRoot = session.mapping.agent.projectRoot;
3451
+ let team = session.mapping.workflow.mode;
3452
+ if (changes.team !== void 0) {
3453
+ const wanted = teamOf(changes.team.trim());
3454
+ const teams = await listTeams(projectRoot, { library: options.libraryDir, templates: options.templates });
3455
+ 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`);
3456
+ team = wanted;
3457
+ }
3458
+ const teamChanged = team !== session.mapping.workflow.mode;
3459
+ const mode = changes.mode ?? session.mapping.mode;
3460
+ if (!modes.some((candidate) => candidate.id === mode)) return refuse("invalid_params", `Unsupported mode '${mode}'`);
3461
+ const takes = (effort) => {
3462
+ const efforts = thinkingOptionsFor(runtimeKind, model);
3463
+ return !efforts.length || efforts.some((option) => option.id === effort);
3464
+ };
3465
+ const thinking = changes.thinking ?? (takes(session.mapping.thinking) ? session.mapping.thinking : void 0);
3466
+ const { restore: _restore, thinking: _thinking, ...kept } = session.spec;
3467
+ const spec = { ...kept, mode, ...teamChanged ? { workflow: team } : {}, ...thinking !== void 0 ? { thinking } : {} };
3468
+ let mapping;
3469
+ try {
3470
+ mapping = await resolveSession({
3471
+ ...spec,
3472
+ restore: { agent: session.mapping.agent.name, threadId: session.threadId || "unstarted", runtime: runtimeKind, model, ...teamChanged ? {} : { workflow: session.mapping.workflow } }
3473
+ }, { templates: options.templates, library: options.libraryDir, language: options.language, initialize: false });
3474
+ } catch (error) {
3475
+ const message = errorData(error).message;
3476
+ 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);
3477
+ }
3478
+ const graph = teamChanged ? mapping.team ? mapping.team.delegation : await resolveDelegation(projectRoot) : session.graph;
3479
+ const shape = { mapping, graph, spec };
3480
+ const proposed = await effectiveConfig(session, shape);
3481
+ const plan = { shape, current, proposed, changes: changesOf(current, proposed) };
3482
+ const refused = (reason, message) => ({ ...plan, refusal: { reason, message } });
3483
+ if (mapping.runtimeKind !== runtimeKind) return refused("runtime_mismatch", `A session keeps its runtime (${label(runtimeKind)}); start a new session for another runtime`);
3484
+ if (mapping.agent.name !== session.mapping.agent.name) return refused("agent_mismatch", "A session keeps its agent; start a new session for another agent");
3485
+ const agent = session.mapping.agent.name;
3486
+ 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`);
3487
+ if (changes.mode !== void 0 && 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"));
3488
+ if (changes.mode === void 0 && !withinMode(mapping.mode, session.mapping.mode)) return refused("permission_escalation", `The change would run the session in ${mapping.mode}, beyond its ${session.mapping.mode}`);
3489
+ const before = executablesOf(session.mapping);
3490
+ const added = [...executablesOf(mapping)].filter((entry) => !before.has(entry));
3491
+ 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`);
3492
+ 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");
3493
+ return plan;
3494
+ }
3495
+ async function nativeHistory(session) {
3496
+ if (!session.threadId) return false;
3497
+ if (session.base) return true;
3498
+ const unknown = (error) => new ConversationError("native_refused", `${label(session.runtimeKind)} could not say whether it holds this session's conversation: ${errorData(error).message}`);
3499
+ if (session.runtimeKind === "codex") {
3500
+ try {
3501
+ const page = await session.runtime.request("thread/turns/list", { threadId: session.threadId, limit: 1, sortDirection: "desc" });
3502
+ return Array.isArray(page?.data) && page.data.length > 0;
3503
+ } catch (error) {
3504
+ if (/not materialized|no rollout found/i.test(errorData(error).message)) return false;
3505
+ throw unknown(error);
3506
+ }
3507
+ }
3508
+ if (session.runtimeKind === "claude") {
3509
+ try {
3510
+ const chain = await session.runtime.request("thread/chain", { threadId: session.threadId, cwd: session.mapping.workdir });
3511
+ return Array.isArray(chain?.entries) && chain.entries.length > 0;
3512
+ } catch (error) {
3513
+ throw unknown(error);
3514
+ }
3515
+ }
3516
+ return true;
3517
+ }
3518
+ async function previewConfigureSession(sessionId, changes) {
3519
+ const session = sessions.get(sessionId);
3520
+ if (!session || session.closed) throw new ConversationError("session_busy", "The session is not open");
3521
+ const plan = await planConfigure(session, changes ?? {});
3522
+ const busy = plan.changes.length ? restartRefusal(sessionId, session) : void 0;
3523
+ const teams = (await listTeams(session.mapping.agent.projectRoot, { library: options.libraryDir, templates: options.templates })).filter((team) => !team.error).map((team) => ({ id: team.id, label: team.label ?? team.id, ...team.description ? { description: team.description } : {} }));
3524
+ return {
3525
+ current: plan.current,
3526
+ proposed: plan.proposed,
3527
+ changes: plan.changes,
3528
+ restart: plan.changes.some((change) => change !== "mode"),
3529
+ allowed: !plan.refusal && !busy,
3530
+ ...plan.refusal ? { reason: plan.refusal.reason, message: plan.refusal.message } : busy ? { reason: "session_busy", message: busy } : {},
3531
+ teams
3532
+ };
3533
+ }
3534
+ async function reconfigureSession(sessionId, changes, { fresh = false, onApplied } = {}) {
3535
+ async function persist(result2) {
3536
+ try {
3537
+ await onApplied?.(result2);
3538
+ } catch (error) {
3539
+ throw new ConversationError("native_refused", `The runtime took the configuration but the host could not record it: ${errorData(error).message}`, { outcomeUnknown: true });
3540
+ }
3541
+ }
3542
+ const session = sessions.get(sessionId);
3543
+ const busy = restartRefusal(sessionId, session);
3544
+ if (busy) throw new ConversationError(session && (session.parent || session.role === "supervisor") ? "not_root" : "session_busy", busy);
3545
+ const live2 = session;
3546
+ const plan = await planConfigure(live2, changes ?? {});
3547
+ if (plan.refusal) throw new ConversationError(plan.refusal.reason, plan.refusal.message);
3548
+ const starts = fresh && !(plan.changes.length && await nativeHistory(live2));
3549
+ const after = restartRefusal(sessionId, live2);
3550
+ if (after) throw new ConversationError("session_busy", after);
3551
+ if (!plan.changes.length) return { session: snapshot(sessionId, live2), effective: plan.current, status: "unchanged", restarted: false };
3552
+ const agent = live2.mapping.agent.name;
3553
+ if (plan.changes.every((change) => change === "mode")) {
3554
+ await configureSession(sessionId, { mode: plan.shape.mapping.mode }, (updated2) => persist({ session: updated2, effective: { ...plan.proposed, instructionsSha: plan.current.instructionsSha }, status: "applied", restarted: false }));
3555
+ runLog(rootOf(sessionId), { event: "session.configured", sessionId, agent, changes: plan.changes, mode: plan.shape.mapping.mode });
3556
+ return { session: snapshot(sessionId, live2), effective: { ...plan.proposed, instructionsSha: plan.current.instructionsSha }, status: "applied", restarted: false };
3557
+ }
3558
+ if (!starts && !live2.threadId) throw new ConversationError("runtime_unsupported", "This session keeps no native conversation to continue");
3559
+ const binding = starts ? void 0 : { threadId: live2.threadId, ...live2.base ? { base: live2.base } : {} };
3560
+ const from = { model: live2.mapping.model, thinking: live2.mapping.thinking, team: live2.mapping.workflow.mode, mode: live2.mapping.mode };
3561
+ const to = { model: plan.shape.mapping.model, thinking: plan.shape.mapping.thinking, team: plan.shape.mapping.workflow.mode, mode: plan.shape.mapping.mode };
3562
+ let native;
3563
+ try {
3564
+ native = await restartNative(sessionId, live2, binding, true, plan.shape);
3565
+ if (live2.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`);
3566
+ } catch (error) {
3567
+ runLog(rootOf(sessionId), { event: "session.configure_failed", sessionId, agent, from, to, error: errorData(error).message });
3568
+ try {
3569
+ if (live2.closed) throw error;
3570
+ await restartNative(sessionId, live2, binding, false);
3571
+ } catch (reopen) {
3572
+ live2.pending = false;
3573
+ if (!live2.closed) failSession(sessionId, live2, reopen);
3574
+ }
3575
+ if (error instanceof ConversationError) throw error;
3576
+ throw new ConversationError("native_refused", `The runtime did not take the new configuration; the session keeps its own: ${errorData(error).message}`);
3577
+ }
3578
+ live2.mapping = plan.shape.mapping;
3579
+ live2.graph = plan.shape.graph;
3580
+ live2.spec = plan.shape.spec;
3581
+ const answered = live2.runtimeKind === "codex" ? { ...typeof native?.model === "string" ? { model: native.model } : {}, ...typeof native?.reasoningEffort === "string" ? { reasoningEffort: native.reasoningEffort } : {} } : void 0;
3582
+ runLog(rootOf(sessionId), { event: "session.configured", sessionId, agent, changes: plan.changes, from, to, threadId: live2.threadId, ...answered ? { native: answered } : {} });
3583
+ if (plan.changes.includes("team")) {
3584
+ const old = live2.supervisor;
3585
+ if (old) {
3586
+ live2.supervisor = void 0;
3587
+ await closeSession(old).catch(() => {
3588
+ });
3589
+ }
3590
+ if (supervises(live2)) void enqueue(() => openSupervisor(sessionId));
3591
+ }
3592
+ const updated = snapshot(sessionId, live2);
3593
+ const result = {
3594
+ session: updated,
3595
+ effective: { ...plan.proposed, ...live2.instructionsSha ? { instructionsSha: live2.instructionsSha } : {} },
3596
+ status: "applied",
3597
+ restarted: true,
3598
+ ...answered ? { native: answered } : {}
3599
+ };
3600
+ await persist(result);
3601
+ emit(sessionId, { type: "session.updated", session: updated });
3602
+ return result;
3603
+ }
3604
+ async function branchConversation(request) {
3605
+ if (closed) throw new Error("Runtime is closed");
3606
+ if (request.runtime !== "codex" && request.runtime !== "claude") throw new ConversationError("runtime_unsupported", `${label(request.runtime)} sessions cannot be forked or rewound`);
3607
+ if (!Array.isArray(request.turns) || !request.turns.every((turn) => typeof turn === "string")) throw new Error("branch needs the source turns in order");
3608
+ if (typeof request.source?.threadId !== "string" || !request.source.threadId) throw new Error("branch needs the source thread");
3609
+ 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");
3610
+ return request.runtime === "codex" ? branchCodex(request) : branchClaude(request);
3611
+ }
3612
+ async function branchCodex(request) {
3613
+ const end = codexForkEnd(request);
3614
+ const cwd = request.targetCwd ?? request.cwd;
3615
+ const mode = request.mode;
3616
+ const transport = createTransport(options, "codex", cwd, nativeEnvironment(options));
3617
+ try {
3618
+ try {
3619
+ await transport.initialize();
3620
+ } catch (error) {
3621
+ throw new ConversationError("native_refused", `Codex did not start: ${errorData(error).message}`);
3622
+ }
3623
+ let forked;
3624
+ try {
3625
+ forked = await transport.request("thread/fork", {
3626
+ threadId: request.source.threadId,
3627
+ ...end.params,
3628
+ ephemeral: false,
3629
+ excludeTurns: true,
3630
+ cwd,
3631
+ model: request.model.replace(/^codex:/, ""),
3632
+ sandbox: mode === "full-access" ? "danger-full-access" : nativeMode({ mode, copy: false }),
3633
+ approvalPolicy: codexApproval({ mode, permissions: null })
3634
+ });
3635
+ } catch (error) {
3636
+ throw codexForkRefusal(error);
3637
+ }
3638
+ const id = forked?.thread?.id;
3639
+ if (typeof id !== "string" || !id) throw new ConversationError("native_refused", "Codex answered the fork without a thread id", { outcomeUnknown: true });
3640
+ let problem;
3641
+ try {
3642
+ if (forked.thread.forkedFromId != null && forked.thread.forkedFromId !== request.source.threadId) problem = `it was forked from ${forked.thread.forkedFromId}`;
3643
+ else {
3644
+ const page = await transport.request("thread/turns/list", { threadId: id, limit: 1, sortDirection: "desc" });
3645
+ const last = page?.data?.[0];
3646
+ if (last?.id !== end.last) problem = `it ends at ${last?.id ?? "no turn"}, not ${end.last}`;
3647
+ else if (last.status === "inProgress") problem = `its last turn ${last.id} is still running`;
3648
+ }
3649
+ } catch (error) {
3650
+ problem = `it could not be read: ${errorData(error).message}`;
3651
+ }
3652
+ if (!problem) return { threadId: id };
3653
+ const deleted = await transport.request("thread/delete", { threadId: id }).then(() => true, () => false);
3654
+ throw new ConversationError("native_refused", `The Codex fork ${id} could not be verified (${problem}); ${deleted ? "it was deleted" : "deleting it failed"}`, { outcomeUnknown: !deleted });
3655
+ } finally {
3656
+ await transport.close().catch(() => {
3657
+ });
3658
+ }
3659
+ }
3660
+ async function branchClaude(request) {
3661
+ const transport = createTransport(options, "claude", request.cwd, nativeEnvironment(options));
3662
+ try {
3663
+ const read = async (threadId) => {
3664
+ const answer = await transport.request("thread/chain", { threadId, cwd: request.cwd });
3665
+ if (!Array.isArray(answer?.entries)) throw new Error("Claude answered no transcript");
3666
+ return answer.entries;
3667
+ };
3668
+ await transport.initialize();
3669
+ let source = request.source.threadId;
3670
+ let chain = await read(source);
3671
+ if (!chain.length && request.source.base) {
3672
+ source = request.source.base.threadId;
3673
+ chain = pendingChain(request.source.base, await read(source));
3674
+ }
3675
+ return { threadId: randomUUID(), base: { threadId: source, at: claudeCut(chain, request) } };
3676
+ } catch (error) {
3677
+ if (error instanceof ConversationError) throw error;
3678
+ throw new ConversationError("native_refused", `The Claude transcript could not be read: ${errorData(error).message}`);
3679
+ } finally {
3680
+ await transport.close().catch(() => {
3681
+ });
3682
+ }
3683
+ }
2557
3684
  const restartCause = () => options.previousExit?.kind === "crash" ? "alpd stopped unexpectedly" : "alpd restarted";
2558
3685
  async function resumeAssignment(entry) {
2559
3686
  const parent = sessions.get(entry.parentId);
@@ -2593,8 +3720,6 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2593
3720
  }
2594
3721
  if (assignment.copy) await removeCopy(assignment.copy).catch(() => {
2595
3722
  });
2596
- if (assignment.worktree) await removeWorktree(assignment.worktree).catch(() => {
2597
- });
2598
3723
  };
2599
3724
  try {
2600
3725
  if (entry.lease) {
@@ -2605,7 +3730,14 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2605
3730
  leases.set(entry.lease, { assignment: id, agent: entry.agent });
2606
3731
  }
2607
3732
  }
2608
- if (entry.worktree) assignment.worktree = await reattachWorktree(entry.worktree);
3733
+ if (entry.worktree) {
3734
+ const { preserved, ...worktree } = await reattachWorktree(entry.worktree);
3735
+ assignment.worktree = worktree;
3736
+ if (preserved) {
3737
+ runLog(entry.rootId, { event: "worktree.preserved", assignmentId: id, branch: worktree.branch, preserved });
3738
+ 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}.` });
3739
+ }
3740
+ }
2609
3741
  if (entry.copyOf) {
2610
3742
  assignment.copy = await createCopy(entry.copyOf, copyRoot, id);
2611
3743
  spec = { ...spec, workdir: assignment.copy.workdir };
@@ -2622,8 +3754,9 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2622
3754
  assignment.taskId = entry.taskId;
2623
3755
  touchTask(entry.rootId, entry.taskId);
2624
3756
  }
2625
- await openSession(id, { ...spec, restore: { agent: entry.agent, threadId: entry.threadId, runtime: entry.runtime, model: entry.model, workflow: parent.mapping.workflow } }, "skip", entry.delegation);
2626
- const child = sessions.get(id);
3757
+ 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);
3758
+ const child = assignmentSessions.get(assignment);
3759
+ if (sessions.get(id) !== child) throw new Error("Child session was replaced during recovery");
2627
3760
  child.settle = (state, error) => void finishAssignment(entry.parentId, parent, assignment, state, error);
2628
3761
  if (entry.brief) child.brief = entry.brief;
2629
3762
  if (assignment.taskId && writes(entry.mode)) {
@@ -2642,6 +3775,21 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2642
3775
  return assignment;
2643
3776
  }
2644
3777
  async function abandonEntry(entry, reason) {
3778
+ if (entry.worktree || writes(entry.mode)) await assignmentResults.put({
3779
+ assignmentId: entry.assignmentId,
3780
+ checkout: entry.worktree?.checkout ?? entry.lease ?? entry.spec.writeRoot ?? entry.spec.workdir ?? entry.project,
3781
+ ...entry.worktree ? { worktree: entry.worktree.path } : {},
3782
+ ...!entry.worktree ? { result: {
3783
+ agent: entry.agent,
3784
+ status: "abandoned",
3785
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
3786
+ project: entry.project,
3787
+ requesters: sessions.has(entry.parentId) ? lineage(entry.parentId) : [entry.parentId],
3788
+ ...entry.taskId ? { taskId: entry.taskId } : {},
3789
+ brief: cut(entry.brief ?? "", RESULT_EVIDENCE_CHARS),
3790
+ summary: cut(JSON.stringify({ reason }), RESULT_EVIDENCE_CHARS)
3791
+ } } : {}
3792
+ });
2645
3793
  await inFlight.remove(entry.assignmentId);
2646
3794
  const parent = sessions.get(entry.parentId);
2647
3795
  let task;
@@ -2688,7 +3836,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2688
3836
  const listed = (assignments = []) => assignments.length ? ` These assignments of yours continue and report to you: ${assignments.map((assignment) => `${assignment.id} (${assignment.agent}${assignment.taskId ? `, task ${assignment.taskId}` : ""})`).join(", ")}. Wait for them with alp_wait, or keep working.` : "";
2689
3837
  const proceed = (sessionId, session, text2) => {
2690
3838
  if (options.recoveryResume === false || pauseOf(session.runtimeKind)) {
2691
- session.parked = { reason: cause, since: Date.now(), prompt: text2 };
3839
+ session.parked = { reason: cause, since: Date.now(), prompt: text2, ...options.recoveryResume !== false ? { pause: { scope: paused.all ? "all" : session.runtimeKind } } : {} };
2692
3840
  emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
2693
3841
  runLog(rootId, { event: "assignment.parked", assignmentId: sessionId, agent: session.mapping.agent.name, reason: cause });
2694
3842
  const outcome = outcomes.find((entry) => entry.assignmentId === sessionId);
@@ -2706,15 +3854,19 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2706
3854
  if (parkedRoot) {
2707
3855
  root.parked = { reason: parkedRoot, since: Date.now() };
2708
3856
  emit(rootId, { type: "session.updated", session: snapshot(rootId, root) });
2709
- if (options.autoResume !== false && options.recoveryResume !== false && !pauseOf(root.runtimeKind)) continueParked(rootId, root);
2710
3857
  } 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))}`);
2711
3858
  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.` });
2712
3859
  const failed = outcomes.filter((outcome) => outcome.outcome === "failed");
2713
- if (entries.length || continueRoot) {
2714
- const parked = outcomes.some((outcome) => outcome.outcome === "parked") || continueRoot && !!root.parked;
3860
+ if (entries.length || continueRoot || parkedRoot) {
3861
+ const parked = outcomes.flatMap((outcome) => {
3862
+ const park2 = outcome.outcome === "parked" ? sessions.get(outcome.assignmentId)?.parked : void 0;
3863
+ return park2 ? [park2] : [];
3864
+ });
3865
+ if ((continueRoot || parkedRoot) && root.parked) parked.push(root.parked);
3866
+ const next = parked.some((park2) => !park2.pause) ? "send an explicit prompt to each parked session to continue it: alp send <session> --prompt <text>" : "run alp resume to continue them";
2715
3867
  notice(
2716
3868
  failed.length ? "warning" : "info",
2717
- `ALP: ${cause}${options.previousExit?.at ? ` (around ${options.previousExit.at})` : ""}. ${entries.length - failed.length} of ${entries.length} running assignments reopened${continueRoot ? ", and this session" : ""}${parked ? "; they wait parked: run alp resume to continue them" : ""}.${failed.length ? ` Could not continue: ${failed.map((outcome) => `${outcome.agent} ${outcome.assignmentId} (${outcome.error})`).join("; ")}; their tasks went back to open.` : ""}`,
3869
+ `ALP: ${cause}${options.previousExit?.at ? ` (around ${options.previousExit.at})` : ""}. ${entries.length - failed.length} of ${entries.length} running assignments reopened${continueRoot || parkedRoot ? ", and this session" : ""}${parked.length ? `; they wait parked: ${next}` : ""}.${failed.length ? ` Could not continue: ${failed.map((outcome) => `${outcome.agent} ${outcome.assignmentId} (${outcome.error})`).join("; ")}; their tasks went back to open.` : ""}`,
2718
3870
  root.mapping.agent.projectRoot
2719
3871
  );
2720
3872
  }
@@ -2729,7 +3881,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2729
3881
  }
2730
3882
  return session;
2731
3883
  }
2732
- async function configureSession(sessionId, changes) {
3884
+ async function configureSession(sessionId, changes, beforeUpdated) {
2733
3885
  const session = openOf(sessionId);
2734
3886
  if (session.active || session.pending || session.children.size) throw new Error("Wait for the current turn and child sessions to finish before changing permissions");
2735
3887
  const mode = changes.mode ?? session.mapping.mode;
@@ -2740,11 +3892,11 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2740
3892
  }
2741
3893
  const parent = session.parent ? sessions.get(session.parent) : void 0;
2742
3894
  if (parent && !withinMode(mode, parent.mapping.mode)) throw new Error("Child cannot exceed parent permissions");
2743
- if (session.runtimeKind === "antigravity" && mode !== session.mapping.mode) throw new Error("Antigravity uses full-access natively; its permission instructions are fixed for the session. Open a new session to change mode");
2744
- if (session.runtimeKind === "claude") await session.runtime.request("session/configure", { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
3895
+ if (session.runtimeKind === "claude" || session.runtimeKind === "antigravity") await session.runtime.request("session/configure", { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
2745
3896
  session.mapping.mode = mode;
2746
3897
  session.spec = { ...session.spec, mode };
2747
3898
  const updated = snapshot(sessionId, session);
3899
+ if (beforeUpdated) await beforeUpdated(updated);
2748
3900
  emit(sessionId, { type: "session.updated", session: updated });
2749
3901
  return updated;
2750
3902
  }
@@ -2756,6 +3908,8 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2756
3908
  session.userStopped = true;
2757
3909
  session.parked = void 0;
2758
3910
  session.parkReason = void 0;
3911
+ session.parkPause = void 0;
3912
+ session.resumeHeld = void 0;
2759
3913
  emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
2760
3914
  approvalCancellation.set(session, (approvalCancellation.get(session) ?? 0) + 1);
2761
3915
  cancelQuestions(sessionId);
@@ -2770,7 +3924,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2770
3924
  );
2771
3925
  await Promise.all(
2772
3926
  [...session.children].map(
2773
- closeSession
3927
+ (id) => closeSession(id)
2774
3928
  )
2775
3929
  );
2776
3930
  if (!activeTurn) session.settle?.("canceled", "Interrupted");
@@ -2784,6 +3938,27 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2784
3938
  );
2785
3939
  }
2786
3940
  }
3941
+ async function promptSession(sessionId, input, flushing = false) {
3942
+ const session = sessions.get(sessionId);
3943
+ if (!flushing && session && !session.parent && (session.compacting || session.compactBuffer?.length)) {
3944
+ if (!session.seen.has(input.clientMessageId) && !session.compactBuffer?.some((held2) => held2.clientMessageId === input.clientMessageId)) (session.compactBuffer ??= []).push(input);
3945
+ return;
3946
+ }
3947
+ const parked = session?.parked;
3948
+ try {
3949
+ const prompt = session?.active && session.resumedTurn === session.active && input.delivery === "auto" ? { ...input, delivery: "steer" } : input;
3950
+ await startPrompt(sessionId, prompt, "user");
3951
+ if (session && parked && session.parked === parked) {
3952
+ session.parked = void 0;
3953
+ emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
3954
+ }
3955
+ } catch (error) {
3956
+ const session2 = sessions.get(sessionId);
3957
+ if (session2?.seen.has(input.clientMessageId)) return;
3958
+ session2?.seen.add(input.clientMessageId);
3959
+ emit(sessionId, { type: "prompt.failed", clientMessageId: input.clientMessageId, error: errorData(error) });
3960
+ }
3961
+ }
2787
3962
  async function startPrompt(sessionId, prompt, origin, wake) {
2788
3963
  const session = openOf(sessionId);
2789
3964
  if (session.seen.has(
@@ -2791,8 +3966,8 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2791
3966
  )) {
2792
3967
  return;
2793
3968
  }
2794
- if (prompt.content.some((content) => content.type !== "text" && content.type !== "image")) {
2795
- throw new Error("Only text and image prompts are supported");
3969
+ if (prompt.content.some((content) => content.type !== "text" && content.type !== "image" && content.type !== "attachment")) {
3970
+ throw new Error("Only text, image and attachment prompts are supported");
2796
3971
  }
2797
3972
  const images = prompt.content.filter((content) => content.type === "image");
2798
3973
  if (images.length) {
@@ -2806,6 +3981,23 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2806
3981
  }
2807
3982
  }
2808
3983
  }
3984
+ const attached = [];
3985
+ const attachmentParts = prompt.content.filter((content) => content.type === "attachment");
3986
+ if (attachmentParts.length) {
3987
+ if (!attachmentRoutes(session).includes("file.path") || !stager || !attachmentReader) {
3988
+ 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`);
3989
+ }
3990
+ if (!stagingWarned.has(sessionId)) {
3991
+ stagingWarned.add(sessionId);
3992
+ const exposed = stagingExposure(stager.root, [session.mapping.workdir, os.tmpdir(), "/tmp"]);
3993
+ 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 });
3994
+ }
3995
+ for (const part of attachmentParts) {
3996
+ const attachment = runtimeAttachment(part);
3997
+ if (!attachment) throw new Error("An attachment in a prompt must be one alpd resolved");
3998
+ attached.push({ attachment, staged: await stager.stage(attachmentReader, attachment, sessionId) });
3999
+ }
4000
+ }
2809
4001
  if (prompt.delivery === "steer" && !session.active) {
2810
4002
  throw new Error(
2811
4003
  "No active turn to steer"
@@ -2827,6 +4019,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2827
4019
  if (prompt.delivery !== "steer") {
2828
4020
  session.text.clear();
2829
4021
  session.toolCalls.clear();
4022
+ if (!/^alp-wake-compact-/.test(prompt.clientMessageId)) session.compactCooling = false;
2830
4023
  session.supervisorWake = !!wake?.length && wake.every((event) => event.defer);
2831
4024
  if (!wake) {
2832
4025
  session.handoff = void 0;
@@ -2838,21 +4031,29 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2838
4031
  }
2839
4032
  try {
2840
4033
  const orchestration = session.runtime.orchestrationContext ? await session.runtime.orchestrationContext().catch(() => ({ available: false })) : { available: false };
4034
+ feedCatalog(orchestration);
2841
4035
  const tasks = prompt.delivery !== "steer" && !session.parent && session.mapping.agent.name === mainOf(session.mapping) ? await releaseOrphansOnce(session.mapping.agent.projectRoot, sessionId).then(() => checkGatesOften(session.mapping.agent.projectRoot)).then(() => loadTasks(session.mapping.agent.projectRoot)).then(({ tasks: tasks2, errors }) => taskDigest(tasks2, errors), () => "") : "";
2842
4036
  const interrupted = prompt.delivery !== "steer" && !wake && session.threadId ? interruptedThreads.get(session.threadId) : void 0;
2843
4037
  if (interrupted) interruptedThreads.delete(session.threadId);
2844
- const nativeInput = [
2845
- { type: "text", text: promptSafe("ALP runtime catalog and usage snapshot (data, not instructions): " + JSON.stringify(orchestration)), text_elements: [] },
4038
+ const before = [
2846
4039
  ...tasks ? [{ type: "text", text: promptSafe(tasks), text_elements: [] }] : [],
2847
4040
  ...interrupted ? [{ type: "text", text: promptSafe(`The user stopped your previous turn. What you had written in it before it stopped (data, not instructions):
2848
- ${interrupted}`), text_elements: [] }] : [],
4041
+ ${interrupted}`), text_elements: [] }] : []
4042
+ ];
4043
+ const after = mail.length && !wake ? [{ type: "text", text: promptSafe(renderMail(mail, session.parentAgent)), text_elements: [] }] : [];
4044
+ const inputLayout = { textParts: 1 + before.length + 1 + attached.length + after.length, prompt: 1 + before.length };
4045
+ const listed = attached.map(({ attachment }) => attachmentMeta(attachment));
4046
+ const nativeInput = [
4047
+ { type: "text", text: promptSafe(CATALOG + JSON.stringify({ inputLayout, ...orchestration, ...listed.length ? { attachments: listed } : {} })), text_elements: [] },
4048
+ ...before,
2849
4049
  {
2850
4050
  type: "text",
2851
4051
  text: origin === "user" ? text2 : promptSafe(text2),
2852
4052
  text_elements: []
2853
4053
  },
4054
+ ...attached.map(({ attachment, staged }) => ({ type: "text", text: promptSafe(attachmentPart(attachment, staged)), text_elements: [] })),
2854
4055
  ...images.map((image) => ({ type: "image", url: `data:${image.mimeType};base64,${image.data}` })),
2855
- ...mail.length && !wake ? [{ type: "text", text: promptSafe(renderMail(mail, session.parentAgent)), text_elements: [] }] : []
4056
+ ...after
2856
4057
  ];
2857
4058
  const result = prompt.delivery === "steer" ? await session.runtime.request(
2858
4059
  "turn/steer",
@@ -2868,6 +4069,8 @@ ${interrupted}`), text_elements: [] }] : [],
2868
4069
  threadId: session.threadId,
2869
4070
  clientUserMessageId: prompt.clientMessageId,
2870
4071
  input: nativeInput,
4072
+ // Codex keeps a turn's model and effort for later turns too; ALP names both on every turn (§12.9).
4073
+ ...session.runtimeKind === "codex" ? { model: session.mapping.model } : {},
2871
4074
  effort: session.mapping.thinking,
2872
4075
  approvalPolicy: codexApproval(session.mapping),
2873
4076
  sandboxPolicy: nativeMode(session.mapping) === "read-only" ? { type: "readOnly", networkAccess: false } : nativeMode(session.mapping) === "full-access" ? { type: "dangerFullAccess" } : { type: "workspaceWrite", writableRoots: [session.mapping.workdir], networkAccess: false, excludeTmpdirEnvVar: false, excludeSlashTmp: false }
@@ -2889,10 +4092,13 @@ ${interrupted}`), text_elements: [] }] : [],
2889
4092
  id: `user:${prompt.clientMessageId}`,
2890
4093
  clientMessageId: prompt.clientMessageId,
2891
4094
  text: text2,
2892
- ...images.length ? { images: images.length } : {}
4095
+ origin,
4096
+ ...images.length ? { images: images.length } : {},
4097
+ ...listed.length ? { attachments: listed } : {}
2893
4098
  }
2894
4099
  });
2895
4100
  if (origin === "user" && !session.parent) session.userWaiting ??= Date.now();
4101
+ if (origin === "user" && !session.parent && text2) session.lastUserText = clip(text2, 16e3);
2896
4102
  if (session.supervisor && origin === "user") session.journal.push(stamp(`user ${prompt.delivery === "steer" ? "steered" : "asked"} ${session.mapping.agent.name}: ${clip(text2, 1500)}`));
2897
4103
  if (prompt.delivery === "steer" && origin === "user" && !session.parent) {
2898
4104
  releaseWaiters(session);
@@ -2924,7 +4130,118 @@ ${interrupted}`), text_elements: [] }] : [],
2924
4130
  }
2925
4131
  }
2926
4132
  if (options.recallFile) void forgetExpired();
2927
- return {
4133
+ const api = {
4134
+ registerWorkspace: (directory) => enqueue(async () => {
4135
+ try {
4136
+ await assignmentResults.register(await realpath(directory));
4137
+ } catch (error) {
4138
+ refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot register workspace result ownership");
4139
+ }
4140
+ }),
4141
+ withWorkspaceMutation: (directory, run, adoption) => {
4142
+ if (workspaceMutation || admitting) return Promise.reject(new WorkspaceMutationError("workspace_busy", "A session or assignment is opening; retry after it finishes"));
4143
+ workspaceMutation = true;
4144
+ return enqueue(async () => {
4145
+ const target = await realpath(directory).catch(() => refuseMutation("workspace_busy", `Cannot resolve workspace ${directory}; inspect its directory before removing it`));
4146
+ let resultLedger;
4147
+ try {
4148
+ resultLedger = await assignmentResults.inspect();
4149
+ } catch (error) {
4150
+ refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot inspect permanent assignment results");
4151
+ }
4152
+ if (!resultLedger.workspaces.includes(target) && adoption !== ADOPTION) refuseMutation("workspace_assignment_result", "Workspace predates authoritative assignment tracking; an audited migration is required before removal");
4153
+ const canonical = (value) => {
4154
+ try {
4155
+ return realpathSync(value);
4156
+ } catch (error) {
4157
+ if (error.code !== "ENOENT") refuseMutation("workspace_assignment_result", `Cannot resolve assignment path ${value}; inspect it before removing the workspace`);
4158
+ const parent = path.dirname(value);
4159
+ if (parent === value) throw error;
4160
+ return path.join(canonical(parent), path.basename(value));
4161
+ }
4162
+ };
4163
+ const overlaps = (value) => {
4164
+ if (value === void 0) return false;
4165
+ if (typeof value !== "string" || !value) refuseMutation("workspace_assignment_result", "Invalid assignment path; repair runtime persistence before removing the workspace");
4166
+ if (!path.isAbsolute(value)) refuseMutation("workspace_assignment_result", "Assignment path is not absolute; inspect runtime persistence before removing the workspace");
4167
+ const owner = canonical(value);
4168
+ const contains = (parent, child) => {
4169
+ const relative = path.relative(parent, child);
4170
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
4171
+ };
4172
+ return contains(target, owner) || contains(owner, target);
4173
+ };
4174
+ 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}`);
4175
+ const resolved = async (assignmentId) => {
4176
+ if (resultLedger.results.some((owner) => owner.assignmentId === assignmentId && owner.handled)) return true;
4177
+ try {
4178
+ return !!await assignmentResults.archived(assignmentId);
4179
+ } catch {
4180
+ return refuseMutation("workspace_assignment_result", "Cannot inspect the assignment result archive; repair it before removing the workspace");
4181
+ }
4182
+ };
4183
+ for (const [project, pins] of loadedBoards) for (const pin of pins) {
4184
+ 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}`);
4185
+ }
4186
+ for (const [checkout, holder] of leases) if (overlaps(checkout)) refuseMutation("workspace_leased", `Assignment ${holder.assignment} holds a write lease in ${directory}`);
4187
+ for (const [id, session] of sessions) {
4188
+ for (const assignment of session.assignments.values()) {
4189
+ 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}`);
4190
+ }
4191
+ 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}`);
4192
+ if (!session.closed && (overlaps(session.mapping.workdir) || overlaps(session.spec.writeRoot))) refuseMutation("workspace_busy", `Close session ${id} before removing ${directory}`);
4193
+ }
4194
+ const checkLive = (entry) => {
4195
+ 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}`);
4196
+ };
4197
+ for (const entry of inFlight.all()) checkLive(entry);
4198
+ for (const entry of inherited) checkLive(entry);
4199
+ for (const [file, kind] of [[options.liveFile, "live"], [options.recallFile, "recall"]]) {
4200
+ if (!file) continue;
4201
+ let entries;
4202
+ try {
4203
+ entries = JSON.parse(await readFile(file, "utf8"));
4204
+ } catch (error) {
4205
+ if (error.code === "ENOENT") continue;
4206
+ throw new WorkspaceMutationError("workspace_assignment_result", `Cannot inspect ${file}; repair assignment persistence before removing the workspace`);
4207
+ }
4208
+ if (!Array.isArray(entries)) refuseMutation("workspace_assignment_result", `Invalid assignment book ${file}`);
4209
+ for (const entry of entries) {
4210
+ 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}`);
4211
+ if (entry.worktree !== void 0 && (!entry.worktree || !["path", "checkout", "workdir"].every((key) => typeof entry.worktree[key] === "string"))) refuseMutation("workspace_assignment_result", `Invalid worktree result in ${file}`);
4212
+ if (entry.shared !== void 0 && (!entry.shared || typeof entry.shared !== "object" || Array.isArray(entry.shared))) refuseMutation("workspace_assignment_result", `Invalid shared result in ${file}`);
4213
+ if (kind === "live") checkLive(entry);
4214
+ 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}`);
4215
+ }
4216
+ }
4217
+ 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}`);
4218
+ return await run();
4219
+ }).finally(() => {
4220
+ workspaceMutation = false;
4221
+ });
4222
+ },
4223
+ adoptWorkspace: (directory, verify) => api.withWorkspaceMutation(directory, async () => {
4224
+ if (await realpath(directory) !== directory) refuseMutation("workspace_identity", `Adopt ${directory} by its canonical path`);
4225
+ await verify(directory);
4226
+ try {
4227
+ await assignmentResults.register(directory);
4228
+ } catch (error) {
4229
+ refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot register workspace result ownership");
4230
+ }
4231
+ }, ADOPTION),
4232
+ bindSchedules(handler) {
4233
+ scheduleHandler = handler;
4234
+ },
4235
+ bindAttachments(reader) {
4236
+ attachmentReader = reader;
4237
+ },
4238
+ takesAttachments(sessionId) {
4239
+ const session = sessions.get(sessionId);
4240
+ return !!session && !session.closed && attachmentRoutes(session).includes("file.path");
4241
+ },
4242
+ async dropAttachment(attachmentId) {
4243
+ await stager?.drop(attachmentId);
4244
+ },
2928
4245
  onEvent(listener) {
2929
4246
  listeners.add(listener);
2930
4247
  return () => {
@@ -2934,28 +4251,87 @@ ${interrupted}`), text_elements: [] }] : [],
2934
4251
  open: (sessionId, spec, { history = "skip", delegation = true } = {}) => enqueue(async () => {
2935
4252
  const opened = await openSession(sessionId, spec, history, delegation);
2936
4253
  const root = sessions.get(sessionId);
2937
- if (supervises(root)) void enqueue(() => openSupervisor(sessionId));
4254
+ if (supervises(root)) {
4255
+ void enqueue(() => openSupervisor(sessionId));
4256
+ void ensureCurateSchedule(sessionId).catch((error) => runLog(sessionId, { event: "curate.schedule.failed", error: errorData(error).message }));
4257
+ }
2938
4258
  return opened;
2939
4259
  }),
2940
- prompt: (sessionId, input) => enqueue(async () => {
2941
- const session = sessions.get(sessionId);
2942
- const parked = session?.parked;
2943
- try {
2944
- const prompt = session?.active && session.resumedTurn === session.active && input.delivery === "auto" ? { ...input, delivery: "steer" } : input;
2945
- await startPrompt(sessionId, prompt, "user");
2946
- if (session && parked && session.parked === parked) {
2947
- session.parked = void 0;
2948
- emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
4260
+ prompt: (sessionId, input) => enqueue(() => promptSession(sessionId, input)),
4261
+ withIdlePrompt: (sessionId, run) => new Promise((resolve, reject) => {
4262
+ void enqueue(async () => {
4263
+ const session = openOf(sessionId);
4264
+ if (session.active || session.pending || session.lifecycleHolds || session.mail.some((event) => event.deliveredTurn === STARTING)) {
4265
+ resolve({ busy: true });
4266
+ return;
2949
4267
  }
2950
- } catch (error) {
2951
- const session2 = sessions.get(sessionId);
2952
- if (session2?.seen.has(input.clientMessageId)) return;
2953
- session2?.seen.add(input.clientMessageId);
2954
- emit(sessionId, { type: "prompt.failed", clientMessageId: input.clientMessageId, error: errorData(error) });
2955
- }
4268
+ admittedPrompts.add(sessionId);
4269
+ session.lifecycleHolds = (session.lifecycleHolds ?? 0) + 1;
4270
+ let valid = true;
4271
+ let used = false;
4272
+ let sending;
4273
+ try {
4274
+ const value = await run((input) => {
4275
+ if (!valid || used) return Promise.reject(new Error("The admitted prompt sender is no longer available"));
4276
+ used = true;
4277
+ sending = promptSession(sessionId, input);
4278
+ return sending;
4279
+ });
4280
+ resolve({ busy: false, value });
4281
+ } catch (error) {
4282
+ reject(error);
4283
+ } finally {
4284
+ valid = false;
4285
+ try {
4286
+ await sending;
4287
+ } finally {
4288
+ admittedPrompts.delete(sessionId);
4289
+ session.lifecycleHolds = Math.max(0, (session.lifecycleHolds ?? 1) - 1);
4290
+ if (!session.lifecycleHolds && !session.closed && session.wakeHeld) {
4291
+ session.wakeHeld = false;
4292
+ deliver(sessionId, session);
4293
+ }
4294
+ }
4295
+ }
4296
+ }).catch(reject);
2956
4297
  }),
2957
4298
  interrupt: (sessionId) => enqueue(() => interruptSession(sessionId)),
2958
- configure: (sessionId, changes) => enqueue(() => configureSession(sessionId, changes)),
4299
+ interruptTurn: (sessionId, turnId) => enqueue(async () => {
4300
+ if (sessions.get(sessionId)?.active !== turnId) return false;
4301
+ await interruptSession(sessionId);
4302
+ return true;
4303
+ }),
4304
+ configure: (sessionId, changes, options2) => enqueue(() => configureSession(sessionId, changes, options2?.onApplied)),
4305
+ branch: (request) => branchConversation(request),
4306
+ rebind: (sessionId, binding) => enqueue(() => rebindSession(sessionId, binding)),
4307
+ reload: (sessionId) => enqueue(() => reloadSession(sessionId)),
4308
+ compact: (sessionId) => requestCompact(sessionId),
4309
+ previewConfigure: (sessionId, changes) => previewConfigureSession(sessionId, changes),
4310
+ reconfigure: (sessionId, changes, options2) => enqueue(() => reconfigureSession(sessionId, changes, options2)),
4311
+ starting: (sessionId) => {
4312
+ const session = sessions.get(sessionId);
4313
+ return !!session && !session.closed && (admittedPrompts.has(sessionId) || !!session.pending || session.mail.some((event) => event.deliveredTurn === STARTING));
4314
+ },
4315
+ hold: (sessionId) => {
4316
+ const session = sessions.get(sessionId);
4317
+ if (!session || session.closed) return void 0;
4318
+ session.lifecycleHolds = (session.lifecycleHolds ?? 0) + 1;
4319
+ let released = false;
4320
+ return () => {
4321
+ if (released) return;
4322
+ released = true;
4323
+ session.lifecycleHolds = Math.max(0, (session.lifecycleHolds ?? 1) - 1);
4324
+ if (session.lifecycleHolds || session.closed) return;
4325
+ if (session.resumeHeld) {
4326
+ const expected = session.resumeHeld;
4327
+ session.resumeHeld = void 0;
4328
+ if (session.parked === expected) return continueParked(sessionId, session, expected);
4329
+ }
4330
+ if (session.parked || pauseOf(session.runtimeKind) || !session.wakeHeld) return;
4331
+ session.wakeHeld = false;
4332
+ deliver(sessionId, session);
4333
+ };
4334
+ },
2959
4335
  close: (sessionId) => enqueue(async () => {
2960
4336
  openOf(sessionId);
2961
4337
  await closeSession(sessionId);
@@ -2979,7 +4355,7 @@ ${interrupted}`), text_elements: [] }] : [],
2979
4355
  };
2980
4356
  visit(rootId);
2981
4357
  const questions = [...userQuestions.values()].map((pending) => pending.question).filter((question) => question.rootId === rootId);
2982
- const asking = new Set(questions.map((question) => question.sessionId));
4358
+ const asking = new Set(questions.filter((question) => !question.gate).map((question) => question.sessionId));
2983
4359
  const ids = new Set(tree.map(([id]) => id));
2984
4360
  return {
2985
4361
  rootId,
@@ -3031,6 +4407,21 @@ ${interrupted}`), text_elements: [] }] : [],
3031
4407
  return pauseState();
3032
4408
  },
3033
4409
  pauses: () => pauseState(),
4410
+ holdForDisk(reason) {
4411
+ if (paused.all) return pauseState();
4412
+ pauseRuntime("all", { since: (/* @__PURE__ */ new Date()).toISOString(), by: "alpd", reason, cause: "disk" }, true);
4413
+ notice("error", (say) => say.diskFull(reason));
4414
+ return pauseState();
4415
+ },
4416
+ releaseDisk(by) {
4417
+ if (paused.all?.cause !== "disk") return pauseState();
4418
+ resumeRuntime("all", by, true);
4419
+ return pauseState();
4420
+ },
4421
+ diskHeld: () => paused.all?.cause === "disk",
4422
+ diskLow(free) {
4423
+ notice("warning", (say) => say.diskLow(free));
4424
+ },
3034
4425
  async usage(refresh = false) {
3035
4426
  const providers = await Promise.all(["codex", "claude"].map((kind) => cachedUsage(kind, refresh)));
3036
4427
  const state = pauseState();
@@ -3061,6 +4452,10 @@ ${interrupted}`), text_elements: [] }] : [],
3061
4452
  thinking: mapping.thinking
3062
4453
  };
3063
4454
  },
4455
+ syncGates(projectRoot) {
4456
+ if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) return Promise.reject(new Error("syncGates needs an absolute projectRoot"));
4457
+ return syncGates(projectRoot);
4458
+ },
3064
4459
  async board(projectRoot) {
3065
4460
  if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) throw new Error("board needs an absolute projectRoot");
3066
4461
  return (await boardOf(path.resolve(projectRoot))).filter(live);
@@ -3078,6 +4473,11 @@ ${interrupted}`), text_elements: [] }] : [],
3078
4473
  answer(questionId, reply) {
3079
4474
  const pending = userQuestions.get(questionId);
3080
4475
  if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
4476
+ if (pending.gate) {
4477
+ if (!reply.dismiss && (typeof reply.text !== "string" || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error("An answer needs text");
4478
+ void pending.gate.decide(reply);
4479
+ return;
4480
+ }
3081
4481
  if (reply.dismiss) {
3082
4482
  pending.settle("dismissed", void 0, reply.reason);
3083
4483
  return;
@@ -3108,10 +4508,12 @@ ${interrupted}`), text_elements: [] }] : [],
3108
4508
  await queue;
3109
4509
  await Promise.all(
3110
4510
  [...sessions.keys()].map(
3111
- closeSession
4511
+ (id) => closeSession(id)
3112
4512
  )
3113
4513
  );
3114
4514
  clearInterval(watchdog);
4515
+ if (gateWatch) clearInterval(gateWatch);
4516
+ await Promise.all(gateSyncs.values());
3115
4517
  await Promise.all(boards.values());
3116
4518
  await boardDomain.flush();
3117
4519
  await runLogWrites;
@@ -3124,8 +4526,11 @@ ${interrupted}`), text_elements: [] }] : [],
3124
4526
  listeners.clear();
3125
4527
  }
3126
4528
  };
4529
+ return api;
3127
4530
  }
3128
4531
  export {
4532
+ CURATE_MARKER,
3129
4533
  DEFAULT_TEAM,
4534
+ WorkspaceMutationError,
3130
4535
  createAlpRuntime
3131
4536
  };