@anhlp/alp-runtime 0.0.1-beta.4 → 0.0.1-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp-transport.js +5 -36
- package/dist/antigravity-transport.d.ts +17 -0
- package/dist/antigravity-transport.js +82 -58
- package/dist/assignment-results.d.ts +34 -0
- package/dist/assignment-results.js +94 -2
- package/dist/board-domain.js +2 -2
- package/dist/board.d.ts +6 -0
- package/dist/board.js +7 -0
- package/dist/catalog.d.ts +13 -0
- package/dist/catalog.js +9 -1
- package/dist/claude-transport.d.ts +7 -0
- package/dist/claude-transport.js +71 -10
- package/dist/compact.d.ts +29 -0
- package/dist/compact.js +49 -0
- package/dist/configure.d.ts +1 -1
- package/dist/configure.js +2 -2
- package/dist/contracts.d.ts +32 -3
- package/dist/index.d.ts +10 -2
- package/dist/index.js +30 -2
- package/dist/input-limits.d.ts +25 -0
- package/dist/input-limits.js +48 -0
- package/dist/language.d.ts +8 -0
- package/dist/language.js +20 -0
- package/dist/mcp-tools.d.ts +8 -0
- package/dist/mcp-tools.js +26 -0
- package/dist/model-catalog.d.ts +76 -0
- package/dist/model-catalog.js +193 -0
- package/dist/model-probes.d.ts +7 -0
- package/dist/model-probes.js +69 -0
- package/dist/providers.js +2 -0
- package/dist/resolve.d.ts +1 -0
- package/dist/resolve.js +3 -1
- package/dist/runtime.d.ts +3 -1
- package/dist/runtime.js +665 -47
- package/dist/session-config.d.ts +174 -0
- package/dist/session-config.js +9 -9
- package/dist/session-state.d.ts +23 -1
- package/dist/tools.d.ts +82 -0
- package/dist/tools.js +53 -5
- package/dist/transport.js +3 -1
- package/dist/workspace.d.ts +31 -5
- package/dist/workspace.js +92 -11
- package/package.json +3 -3
- package/src/acp-transport.ts +7 -37
- package/src/antigravity-transport.ts +95 -53
- package/src/assignment-results.ts +85 -3
- package/src/board-domain.ts +2 -2
- package/src/board.ts +7 -0
- package/src/catalog.ts +10 -1
- package/src/claude-transport.ts +79 -10
- package/src/compact.ts +62 -0
- package/src/configure.ts +3 -3
- package/src/contracts.ts +28 -2
- package/src/index.ts +10 -2
- package/src/input-limits.ts +65 -0
- package/src/language.ts +18 -0
- package/src/mcp-tools.ts +33 -0
- package/src/model-catalog.ts +166 -0
- package/src/model-probes.ts +58 -0
- package/src/providers.ts +3 -0
- package/src/resolve.ts +4 -2
- package/src/runtime.ts +718 -48
- package/src/session-config.ts +8 -8
- package/src/session-state.ts +15 -1
- package/src/tools.ts +53 -5
- package/src/transport.ts +3 -1
- package/src/workspace.ts +124 -18
package/src/runtime.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { createAssignmentResults } from './assignment-results.js';
|
|
1
|
+
import { createAssignmentResults, RESULT_OUTCOMES } from './assignment-results.js';
|
|
2
2
|
import { constants as fsConstants } from 'node:fs';
|
|
3
3
|
import type { Session, Assignment, Waiter } from './session-state.js';
|
|
4
4
|
import { errorData, plainObject, toolResult } from './tool-results.js';
|
|
5
|
+
import { inputLimitError, POUR_VARS, TOOL_INPUT, VAR_NAME } from './input-limits.js';
|
|
5
6
|
import { createLogger } from '@anhlp/alp-core/log';
|
|
6
7
|
import { PROMPT_IMAGES, base64Bytes } from '@anhlp/alp-protocol';
|
|
7
8
|
import { createBoardDomain } from './board-domain.js';
|
|
@@ -17,7 +18,7 @@ import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, roleOf, taskActions, task
|
|
|
17
18
|
import { nativeEnvironment, createTransport } from './providers.js';
|
|
18
19
|
import { nativeMode, codexApproval, profileEfforts, nativeSessionConfig } from './session-config.js';
|
|
19
20
|
import { createHash, randomUUID } from 'node:crypto';
|
|
20
|
-
import { readFileSync, realpathSync } from 'node:fs';
|
|
21
|
+
import { readFileSync, realpathSync, watch as watchFiles, type FSWatcher } from 'node:fs';
|
|
21
22
|
import { appendFile, mkdir, open, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
|
|
22
23
|
import { moveFile } from '@anhlp/alp-core/atomic';
|
|
23
24
|
import os from 'node:os';
|
|
@@ -28,6 +29,7 @@ import { discoverAgents } from '@anhlp/alp-core/resolver';
|
|
|
28
29
|
import { acpDecision, acpWhat, type AcpPermission } from './acp-transport.js';
|
|
29
30
|
|
|
30
31
|
import { models, modes, thinkingOptionsFor, withinMode, writes } from './catalog.js';
|
|
32
|
+
import { feedCatalog } from './model-catalog.js';
|
|
31
33
|
import { runHook } from '@anhlp/alp-core/hook-run';
|
|
32
34
|
import { hookMatches } from '@anhlp/alp-core/hooks';
|
|
33
35
|
import { isTrusted, trustProject } from '@anhlp/alp-core/trust';
|
|
@@ -49,11 +51,12 @@ import { claudeSandboxAvailable, SKILL_PLUGIN } from './claude-transport.js';
|
|
|
49
51
|
import { boundDetail, codexToolCall, toolError } from './tool-detail.js';
|
|
50
52
|
import { ALP_REPO, gh, projectRepo } from './github.js';
|
|
51
53
|
import { optionalRead, usageAllows, COMPACT_SHARE } from './runtime-context.js';
|
|
54
|
+
import { checkpointPrompt, compactDue, compactInstructions, contextFill, NATIVE_COMPACT, seedPrompt } from './compact.js';
|
|
52
55
|
import { providerUsage, sessionUsage, type ProviderUsage } from './usage.js';
|
|
53
56
|
import { parse as toml } from 'smol-toml';
|
|
54
57
|
import { findFormula, formulaDirs, listFormulas, pourFormula } from '@anhlp/alp-core/formulas';
|
|
55
58
|
import { addAllowRule, capMode, commandDecision, profileFor, unwrapShell } from '@anhlp/alp-core/permissions';
|
|
56
|
-
import { addGate, checkGates, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask, type Task } from '@anhlp/alp-core/tasks';
|
|
59
|
+
import { addGate, checkGates, gateDecisions, markGateNotified, TASKS_DIR, rejectGate, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask, type Task } from '@anhlp/alp-core/tasks';
|
|
57
60
|
|
|
58
61
|
/** The first part of every input ALP builds for a turn; a replayed message that begins with it is ALP's (nativePrompt). */
|
|
59
62
|
const CATALOG = 'ALP runtime catalog and usage snapshot (data, not instructions): ';
|
|
@@ -116,21 +119,34 @@ const LIMIT_FRESH_MS = 15_000;
|
|
|
116
119
|
*/
|
|
117
120
|
const CONTEXT_SOON = 0.9;
|
|
118
121
|
const CONTEXT_RESET = 0.5;
|
|
122
|
+
/** After a failed compaction, how long the automatic one waits before it tries again (t-0e56). */
|
|
123
|
+
const COMPACT_RETRY_MS = 10 * 60_000;
|
|
124
|
+
const MAIL_WAITS = 'Mail waits for the session';
|
|
125
|
+
const REVIEWING = 'The supervisor is reviewing the session';
|
|
126
|
+
/** How long a runtime may take to report the compaction it was asked for (t-0e56). */
|
|
127
|
+
const COMPACT_NATIVE_MS = 5 * 60_000;
|
|
119
128
|
|
|
120
129
|
/** How much of an assignment's brief ALP repeats after a compaction. */
|
|
121
130
|
const BRIEF_CHARS = 8000;
|
|
131
|
+
/** How much of a writer's brief and of its handoff and output the result ledger keeps as evidence. */
|
|
132
|
+
const RESULT_EVIDENCE_CHARS = 2000;
|
|
133
|
+
const RESOLVE_NOTE_CHARS = 2000;
|
|
122
134
|
// Placeholder delivery marks while a steer or a woken turn is starting.
|
|
123
135
|
const STEERING = '\u0000steering';
|
|
124
136
|
const STARTING = '\u0000starting';
|
|
125
137
|
|
|
126
138
|
/** Answers that approve a proposal; anything else is feedback. */
|
|
127
139
|
const APPROVALS = ['approve', 'approved', 'yes', 'y', 'ok', 'đồng ý', 'duyệt', 'có'];
|
|
140
|
+
const CHOICES_REJECT = ['reject', 'từ chối'];
|
|
128
141
|
const SKILL_BODY_CHARS = 20_000;
|
|
129
142
|
const STARTER_ROLES = ['main', 'lead', 'peer', 'oracle', 'reviewer', 'supervisor'];
|
|
130
143
|
const ISSUE_BODY_CHARS = 20_000;
|
|
131
144
|
const ISSUE_FOOTER = '\n\n---\n_Drafted by an ALP agent and posted with the user\'s approval._';
|
|
132
145
|
|
|
133
146
|
const LESSON_CHARS = 600;
|
|
147
|
+
/** The monthly curate job's prompt starts with this marker, so main and ALP recognize it. */
|
|
148
|
+
export const CURATE_MARKER = '[alp-curate]';
|
|
149
|
+
const CURATE_PROMPT = `${CURATE_MARKER} Monthly review of lessons and skills. Use the curate skill: read every lesson and skill, then propose to the user, in one message, the merges, shortenings and removals of lessons, the skills no longer needed, and what ALP itself should adopt. Change nothing before the user approves. To turn this off, set curate.monthly to false in .alp/settings.json.`;
|
|
134
150
|
const DIGEST_CHARS = 12_000;
|
|
135
151
|
const JOURNAL_LINE_CHARS = 400;
|
|
136
152
|
/** Journal lines carry the local time, so the supervisor sees how long the user waited. */
|
|
@@ -160,7 +176,7 @@ const isolationOf = (args: { isolation?: string }) => args.isolation ?? 'shared'
|
|
|
160
176
|
|
|
161
177
|
const log = createLogger({ component: 'runtime' });
|
|
162
178
|
|
|
163
|
-
export type WorkspaceMutationReason = 'workspace_busy' | 'workspace_claimed' | 'workspace_leased' | 'workspace_assignment_result';
|
|
179
|
+
export type WorkspaceMutationReason = 'workspace_busy' | 'workspace_claimed' | 'workspace_leased' | 'workspace_assignment_result' | 'workspace_identity';
|
|
164
180
|
export class WorkspaceMutationError extends Error {
|
|
165
181
|
readonly data: { reason: WorkspaceMutationReason };
|
|
166
182
|
constructor(reason: WorkspaceMutationReason, message: string) {
|
|
@@ -230,6 +246,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
230
246
|
let workspaceMutation = false;
|
|
231
247
|
let admitting = 0;
|
|
232
248
|
const refuseMutation = (reason: WorkspaceMutationReason, message: string): never => { throw new WorkspaceMutationError(reason, message); };
|
|
249
|
+
/** Never exported: no caller of withWorkspaceMutation can skip the birth certificate but adoptWorkspace. */
|
|
250
|
+
const ADOPTION = Symbol('adoption');
|
|
233
251
|
// Admission registers synchronously, before resolving configuration or creating copies.
|
|
234
252
|
async function admission<T>(run: () => Promise<T>): Promise<T> {
|
|
235
253
|
if (workspaceMutation) refuseMutation('workspace_busy', 'A workspace mutation is in progress; retry after it finishes');
|
|
@@ -328,7 +346,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
328
346
|
if (session.parent) sessions.get(session.parent)?.assignments.get(sessionId)?.ask?.resolve(toolResult(false, { error: 'Turn ended' }));
|
|
329
347
|
|
|
330
348
|
// Mail is acknowledged only by a turn that completed; otherwise it is delivered again.
|
|
331
|
-
|
|
349
|
+
const taken = state === 'completed' ? session.mail.filter(event => event.deliveredTurn === turnId) : [];
|
|
350
|
+
session.mail = session.mail.filter(event => !taken.includes(event));
|
|
351
|
+
for (const event of taken) gateMail.get(event)?.taken();
|
|
332
352
|
for (const event of session.mail) {
|
|
333
353
|
if (event.deliveredTurn === turnId) { event.deliveredTurn = undefined; event.redelivered = true; }
|
|
334
354
|
}
|
|
@@ -346,7 +366,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
346
366
|
}
|
|
347
367
|
session.userStopped = false;
|
|
348
368
|
if (session.role === 'supervisor' && session.parent && sessions.get(session.parent)?.reviewPending) review(session.parent);
|
|
369
|
+
if (session.role === 'supervisor' && session.parent) { const root = sessions.get(session.parent); if (root) queueMicrotask(() => compactAtBoundary(session.parent!, root)); }
|
|
349
370
|
if (!session.parent) void showTasks(sessionId, session);
|
|
371
|
+
if (!session.parent && session.role !== 'supervisor') queueMicrotask(() => compactAtBoundary(sessionId, session, state));
|
|
350
372
|
|
|
351
373
|
// An assignment a limit or a pause stopped waits, open, to continue instead of ending.
|
|
352
374
|
if (session.parkReason && state !== 'completed') {
|
|
@@ -583,7 +605,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
583
605
|
if (state === 'failed' && LIMIT_ERRORS.includes(params.turn.error?.codexErrorInfo)) {
|
|
584
606
|
if (session.role !== 'supervisor') {
|
|
585
607
|
session.parkReason = `the ${label(session.runtimeKind)} usage limit was reached`;
|
|
586
|
-
session.parkPause = { scope: paused.all ? 'all' : session.runtimeKind };
|
|
608
|
+
session.parkPause = { scope: paused.all ? 'all' : session.runtimeKind, ...(paused.all?.cause === 'disk' ? { disk: true } : {}) };
|
|
587
609
|
}
|
|
588
610
|
void limitReached(session, params.turn.error);
|
|
589
611
|
}
|
|
@@ -601,6 +623,12 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
601
623
|
// Keep the cleanup with that incarnation, even after its id has been reused.
|
|
602
624
|
const sessionClosures = new WeakMap<Session, Promise<void>>();
|
|
603
625
|
const openedSessions = new WeakSet<Session>();
|
|
626
|
+
/**
|
|
627
|
+
* Sessions whose first open is still running, with the process failure that came meanwhile: the
|
|
628
|
+
* open fails with it and reports it once it stopped using the session, rather than a failure
|
|
629
|
+
* callback closing the session under it (failSession while openSession still runs).
|
|
630
|
+
*/
|
|
631
|
+
const openings = new WeakMap<Session, { failure?: unknown }>();
|
|
604
632
|
const assignmentSessions = new WeakMap<Assignment, Session>();
|
|
605
633
|
function closeSession(sessionId: string, session = sessions.get(sessionId), notify = true): Promise<void> {
|
|
606
634
|
if (!session) return Promise.resolve();
|
|
@@ -764,7 +792,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
764
792
|
const boards = new Map<string, Promise<Pin[]>>();
|
|
765
793
|
/** The same boards once loaded, for synchronous status. */
|
|
766
794
|
const loadedBoards = new Map<string, Pin[]>();
|
|
767
|
-
const userQuestions = new Map<string, { question: UserQuestion; persistent?: boolean; /** From alp_ask: the user's words in the chat end it (#116). */ asked?: boolean; settle: (outcome: 'answered' | 'dismissed' | 'timeout' | 'canceled', answer?: string, reason?: string, result?: unknown) => void }>();
|
|
795
|
+
const userQuestions = new Map<string, { question: UserQuestion; persistent?: boolean; /** From alp_ask: the user's words in the chat end it (#116). */ asked?: boolean; /** A card mirroring a human gate (t-ccac). */ gate?: { rev: number; deciding: boolean; decide: (reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }) => Promise<void> }; settle: (outcome: 'answered' | 'dismissed' | 'timeout' | 'canceled', answer?: string, reason?: string, result?: unknown) => void }>();
|
|
768
796
|
let mailSequence = 0;
|
|
769
797
|
let watchdog: NodeJS.Timeout | undefined;
|
|
770
798
|
|
|
@@ -1078,10 +1106,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1078
1106
|
return toolResult(true, { tasks: rows.slice(0, limit).map(task => summarize(task, tasks)), ...(rows.length > limit ? { more: rows.length - limit } : {}), ...warnings });
|
|
1079
1107
|
}
|
|
1080
1108
|
const { action: _action, id, note, reason, summary, unverified, add, remove, ...input } = args;
|
|
1081
|
-
if (action === 'pour' && (typeof input.formula !== 'string' || (input.vars !== undefined && (!input.vars || typeof input.vars !== 'object' || Array.isArray(input.vars) || !Object.
|
|
1082
|
-
return toolResult(false, { error:
|
|
1109
|
+
if (action === 'pour' && (typeof input.formula !== 'string' || (input.vars !== undefined && (!input.vars || typeof input.vars !== 'object' || Array.isArray(input.vars) || inputLimitError(input.vars, POUR_VARS) || !Object.entries(input.vars).every(([name, value]) => VAR_NAME.test(name) && typeof value === 'string'))))) {
|
|
1110
|
+
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` });
|
|
1083
1111
|
}
|
|
1084
|
-
const { kind, until, ref, gate, formula: _formula, vars: _vars, ...fields } = input;
|
|
1112
|
+
const { kind, until, ref, gate, options: gateChoices, formula: _formula, vars: _vars, ...fields } = input;
|
|
1085
1113
|
if (action === 'clear') {
|
|
1086
1114
|
const current = (await loadTasks(project)).tasks.find(candidate => candidate.id === id);
|
|
1087
1115
|
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' });
|
|
@@ -1089,6 +1117,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1089
1117
|
let poured: Awaited<ReturnType<typeof pourFormula>> | undefined;
|
|
1090
1118
|
// A blocking task.close hook can refuse the close; its output is the reason.
|
|
1091
1119
|
const hookedClose = async (id: string) => {
|
|
1120
|
+
// Refused before any hook runs: no agent closes around a human gate (t-f438); core checks again under the lock.
|
|
1121
|
+
const current = (await loadTasks(project)).tasks.find(candidate => candidate.id === id);
|
|
1122
|
+
if (current && (current.step?.human || current.gates.some(gate => gate.kind === 'human' && !gate.resolved))) throw new Error(`Only the user closes ${id}: it waits on the user's decision. Ask the user to decide it`);
|
|
1092
1123
|
const refused = await runHooks(sessionId, session, 'task.close', { reason, ...(summary ? { summary } : {}) }, id);
|
|
1093
1124
|
if (refused) throw new Error(`A task.close hook refused to close ${id}: ${refused}`);
|
|
1094
1125
|
return closeTask(project, id, { reason, summary, unverified }, by);
|
|
@@ -1097,13 +1128,14 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1097
1128
|
action === 'create' ? await createTask(project, fields as any, by)
|
|
1098
1129
|
: action === 'update' ? await updateTask(project, id, { ...fields, note }, by)
|
|
1099
1130
|
: action === 'pour' ? (poured = await pourFormula(project, (await findFormula(project, options.libraryDir, input.formula, { toml })).formula, input.vars, by, input.parent ? { parent: input.parent } : {})).epic
|
|
1100
|
-
: action === 'gate' ? await addGate(project, id, { kind, note, until, ref }, by)
|
|
1131
|
+
: action === 'gate' ? await addGate(project, id, { kind, note, until, ref, ...(gateChoices !== undefined ? { options: gateChoices } : {}) }, by)
|
|
1101
1132
|
: action === 'clear' ? await resolveGate(project, id, gate, { by, note })
|
|
1102
1133
|
: action === 'link' ? await linkTask(project, id, { add, remove }, by)
|
|
1103
1134
|
: action === 'start' ? await startTask(project, id, { agent: by, session: sessionId }, by)
|
|
1104
1135
|
: action === 'close' ? await hookedClose(id)
|
|
1105
1136
|
: await reopenTask(project, id, { note }, by);
|
|
1106
1137
|
touchTask(rootOf(sessionId), task.id);
|
|
1138
|
+
if (action === 'gate' && kind === 'human') void syncGates(project);
|
|
1107
1139
|
runLog(rootOf(sessionId), { event: 'task', action, agent: by, id: task.id, title: task.title, status: task.status, ...(summary ?? note ? { detail: summary ?? note } : {}) });
|
|
1108
1140
|
const { tasks } = await loadTasks(project);
|
|
1109
1141
|
const landed: Record<string, unknown> = {};
|
|
@@ -1213,6 +1245,49 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1213
1245
|
}
|
|
1214
1246
|
}
|
|
1215
1247
|
|
|
1248
|
+
/**
|
|
1249
|
+
* Records how the requester handled a finished writer's change in its checkout, then archives the
|
|
1250
|
+
* result: until then the removal guard keeps that checkout. Recall expiry never stands in for this.
|
|
1251
|
+
*/
|
|
1252
|
+
async function resolveTool(sessionId: string, session: Session, args: unknown) {
|
|
1253
|
+
if (!plainObject(args, ['assignmentId', 'outcome', 'note']) || typeof args.assignmentId !== 'string' || !RESULT_OUTCOMES.includes(args.outcome as any) ||
|
|
1254
|
+
(args.note !== undefined && (typeof args.note !== 'string' || args.note.length > RESOLVE_NOTE_CHARS))) {
|
|
1255
|
+
return toolResult(false, { error: `Pass assignmentId, outcome (${RESULT_OUTCOMES.join(', ')}), and optionally a note of at most ${RESOLVE_NOTE_CHARS} characters` });
|
|
1256
|
+
}
|
|
1257
|
+
const id = args.assignmentId;
|
|
1258
|
+
const outcome = args.outcome as typeof RESULT_OUTCOMES[number];
|
|
1259
|
+
const note = args.note as string | undefined;
|
|
1260
|
+
const live = [...sessions.values()];
|
|
1261
|
+
if (sessions.has(id) || live.some(other => other.assignments.has(id)) || inFlight.all().some(entry => entry.assignmentId === id) || inherited.some(entry => entry.assignmentId === id)) {
|
|
1262
|
+
return toolResult(false, { error: 'That assignment is still running or can still be recovered; wait for its result' });
|
|
1263
|
+
}
|
|
1264
|
+
if (live.some(other => other.worktrees.has(id))) return toolResult(false, { error: 'Its change waits in a worktree; apply it with alp_merge or drop it with alp_discard' });
|
|
1265
|
+
let ledger: Awaited<ReturnType<typeof assignmentResults.inspect>>;
|
|
1266
|
+
try { ledger = await assignmentResults.inspect(); } catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
1267
|
+
const entry = ledger.results.find(owner => owner.assignmentId === id && !owner.handled);
|
|
1268
|
+
const project = session.mapping.agent.projectRoot;
|
|
1269
|
+
const overlapping = async (a: string, b: string) => {
|
|
1270
|
+
const [x, y] = [await realpath(a).catch(() => a), await realpath(b).catch(() => b)];
|
|
1271
|
+
const within = (parent: string, child: string) => { const relative = path.relative(parent, child); return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); };
|
|
1272
|
+
return within(x, y) || within(y, x);
|
|
1273
|
+
};
|
|
1274
|
+
// Its requesters may resolve it, and so may a root of its project, so a closed requester never leaves it held for good.
|
|
1275
|
+
// An entry from before evidence was kept names only its checkout: a root working there may resolve it.
|
|
1276
|
+
const allowed = !!entry && (entry.result
|
|
1277
|
+
? entry.result.requesters.includes(sessionId) || (!session.parent && await sameDirectory(entry.result.project, project))
|
|
1278
|
+
: !session.parent && await overlapping(entry.checkout, project));
|
|
1279
|
+
if (!entry || !allowed) return toolResult(false, { error: `No unresolved assignment result ${id} of yours` });
|
|
1280
|
+
// A worktree still on disk holds work only a merge or discard may settle.
|
|
1281
|
+
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` });
|
|
1282
|
+
try {
|
|
1283
|
+
const archived = await assignmentResults.resolve(id, { outcome, by: `${session.mapping.agent.name} in ${sessionId}`, at: new Date().toISOString(), ...(note ? { note } : {}) });
|
|
1284
|
+
runLog(rootOf(sessionId), { event: 'result.resolved', assignmentId: id, agent: session.mapping.agent.name, outcome, ...(note ? { note: clip(note, 500) } : {}) });
|
|
1285
|
+
return toolResult(true, { resolved: id, outcome, archivedAt: archived.archivedAt });
|
|
1286
|
+
} catch (error) {
|
|
1287
|
+
return toolResult(false, { assignmentId: id, error: errorData(error).message });
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1216
1291
|
let forgetting = Promise.resolve();
|
|
1217
1292
|
|
|
1218
1293
|
/** Deletes the native threads of assignments past their recall time, one transport per runtime. */
|
|
@@ -1239,7 +1314,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1239
1314
|
/** Whether a session may not start a turn by itself now: parked, or on a paused runtime. */
|
|
1240
1315
|
const held = (session: Session) => !!session.parked || !!pauseOf(session.runtimeKind) || (session.lifecycleHolds ?? 0) > 0;
|
|
1241
1316
|
/** Whether mail may not wake a session now: it is held, or it is a new assignment whose brief has not started. */
|
|
1242
|
-
|
|
1317
|
+
// Mail waits while main compacts (t-0e56), so it never lands in the checkpoint or the compaction.
|
|
1318
|
+
const holdsWake = (session: Session) => held(session) || !!session.awaitingBrief || !!session.compacting;
|
|
1243
1319
|
|
|
1244
1320
|
/**
|
|
1245
1321
|
* Marks a session pending (its native process restarting) with a fresh `acknowledged` that resolves
|
|
@@ -1378,16 +1454,17 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1378
1454
|
if (!session.parent || session.closed || !session.active || session.role === 'supervisor' || (scope !== 'all' && session.runtimeKind !== scope)) continue;
|
|
1379
1455
|
// A process restart already owns its continuation; this pause must not replace its cause.
|
|
1380
1456
|
if (session.parkReason && !session.parkPause) continue;
|
|
1381
|
-
session.parkReason = `paused by ${pause.by}`;
|
|
1382
|
-
session.parkPause = { scope };
|
|
1457
|
+
session.parkReason = pause.cause === 'disk' ? pause.reason : `paused by ${pause.by}`;
|
|
1458
|
+
session.parkPause = { scope, ...(pause.cause === 'disk' ? { disk: true } : {}) };
|
|
1383
1459
|
void session.runtime.request('turn/interrupt', { threadId: session.threadId, turnId: session.active }).catch(() => {});
|
|
1384
1460
|
runLog(rootOf(id), { event: 'assignment.parking', assignmentId: id, agent: session.mapping.agent.name, reason: session.parkReason });
|
|
1385
1461
|
}
|
|
1386
1462
|
}
|
|
1387
1463
|
}
|
|
1388
1464
|
|
|
1389
|
-
function resumeRuntime(scope: RuntimeKind | 'all', by: string) {
|
|
1390
|
-
|
|
1465
|
+
function resumeRuntime(scope: RuntimeKind | 'all', by: string, keepRuntimes = false) {
|
|
1466
|
+
// Lifting alpd's disk pause keeps the usage-limit pauses of single runtimes.
|
|
1467
|
+
if (scope === 'all') paused = keepRuntimes ? { runtimes: paused.runtimes } : { runtimes: {} };
|
|
1391
1468
|
else delete paused.runtimes[scope];
|
|
1392
1469
|
savePauses();
|
|
1393
1470
|
watchLimits();
|
|
@@ -1422,6 +1499,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1422
1499
|
emit(session.parent!, { type: 'assignment', assignment: assignmentSnapshot(assignment, 'parked') });
|
|
1423
1500
|
// One that continues by itself is information; one held until the user resumes needs the requester's decision, so it wakes it.
|
|
1424
1501
|
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.` });
|
|
1502
|
+
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.` });
|
|
1425
1503
|
else post(session.parent!, { kind: 'stalled', from: assignment.agent, assignment: sessionId, body: `Parked: ${session.parked.reason}. ALP continues this assignment where it stopped when ${label(session.runtimeKind)} is resumed (${options.autoResume !== false && (pauseOf(session.runtimeKind)?.by ?? 'alpd') === 'alpd' ? `ALP resumes it as soon as ${label(session.runtimeKind)} says the limit lifted` : 'the user runs alp resume'}). Wait for it, start other work, or stop it with alp_cancel and give the rest to an agent on another runtime (pass model claude:… or codex:…); what it changed stays in your checkout or its worktree.` });
|
|
1426
1504
|
}
|
|
1427
1505
|
|
|
@@ -1505,6 +1583,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1505
1583
|
const used = usage?.last?.totalTokens;
|
|
1506
1584
|
const window = usage?.modelContextWindow;
|
|
1507
1585
|
if (session.role === 'supervisor' || typeof used !== 'number' || typeof window !== 'number' || window <= 0) return;
|
|
1586
|
+
// Against the window main works in, as the advisory measures it; not from the old context right after a compaction.
|
|
1587
|
+
if (!session.compactCooling) session.contextFill = contextFill({ ...usage, modelContextWindow: Math.min(typeof session.mapping.autocompact === 'number' ? session.mapping.autocompact : typeof session.mapping.context === 'number' ? session.mapping.context : window, window) });
|
|
1508
1588
|
const compactAt = typeof usage.autoCompactTokens === 'number' && usage.autoCompactTokens > 0
|
|
1509
1589
|
? usage.autoCompactTokens
|
|
1510
1590
|
: session.runtimeKind === 'codex' && session.mapping.autocompact
|
|
@@ -1557,14 +1637,169 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1557
1637
|
if (!done) return;
|
|
1558
1638
|
const agent = session.mapping.agent.name;
|
|
1559
1639
|
runLog(rootOf(sessionId), { event: 'compacted', sessionId, agent, ...trigger, ...tokens, ...(failed ? { failed: true, ...(item.error ? { error: String(item.error) } : {}) } : {}) });
|
|
1560
|
-
if (failed) return;
|
|
1640
|
+
if (failed) { if (session.compacting?.phase === 'native') compactFailed(sessionId, session, item.error ? String(item.error) : 'the runtime could not compact'); return; }
|
|
1561
1641
|
session.contextLevel = 0;
|
|
1562
1642
|
if (session.supervisor) session.journal.push(stamp(`${agent}'s context was compacted`));
|
|
1563
|
-
|
|
1643
|
+
const checkpoint = session.compacting?.phase === 'native' ? session.compacting.checkpoint : undefined;
|
|
1644
|
+
if (session.role !== 'supervisor') void restoreAfterCompaction(sessionId, session, checkpoint).catch(() => {});
|
|
1645
|
+
if (checkpoint !== undefined) compactFinished(sessionId, session, 'native');
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
/**
|
|
1649
|
+
* Whether a root holds anything a compaction must not cut into (t-0e56): a turn, a restart,
|
|
1650
|
+
* a question to the user or a park. Before one starts, also mail that would wake it. The
|
|
1651
|
+
* supervisor's review does not hold it: its mail waits for the compaction's end like any other.
|
|
1652
|
+
*/
|
|
1653
|
+
function compactHeld(sessionId: string, session: Session, starting: boolean) {
|
|
1654
|
+
return session.closed || !!session.active || !!session.pending || session.waiters.length > 0
|
|
1655
|
+
|| !!session.parked || !!session.parkReason
|
|
1656
|
+
|| (starting && (hasActiveMail(session) || !!session.wakeHeld))
|
|
1657
|
+
|| [...userQuestions.values()].some(pending => pending.question.rootId === sessionId && !pending.gate);
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
/**
|
|
1661
|
+
* Main's compaction (t-0e56). Once its context fills to the threshold, or the user asked,
|
|
1662
|
+
* main writes a checkpoint by skill compact in a turn of its own; after that turn the
|
|
1663
|
+
* runtime compacts natively, or ALP starts a fresh conversation seeded with it. It starts
|
|
1664
|
+
* only at a turn boundary (`ended`, the state of the turn that just ended); without one it
|
|
1665
|
+
* is a retry, after a hold such as the supervisor's review or held mail clears.
|
|
1666
|
+
*/
|
|
1667
|
+
function compactAtBoundary(sessionId: string, session: Session, ended?: 'completed' | 'failed' | 'canceled') {
|
|
1668
|
+
if (session.closed || sessions.get(sessionId) !== session) return;
|
|
1669
|
+
const current = session.compacting;
|
|
1670
|
+
if (ended && current?.phase === 'checkpoint' && current.checkpoint === undefined && current.turn) {
|
|
1671
|
+
// The checkpoint turn just ended: its last words are the checkpoint.
|
|
1672
|
+
const written = [...session.text.values()].at(-1)?.trim();
|
|
1673
|
+
if (ended !== 'completed' || !written) { compactFailed(sessionId, session, ended !== 'completed' ? `the checkpoint turn ${ended}` : 'main wrote no checkpoint'); return; }
|
|
1674
|
+
current.checkpoint = written;
|
|
1675
|
+
// A hold that outlasts this (a question, a park) fails it, so the user's held words go on.
|
|
1676
|
+
const timer = setTimeout(() => { if (session.compacting === current && current.phase === 'checkpoint') compactFailed(sessionId, session, 'main stayed busy after its checkpoint'); }, COMPACT_NATIVE_MS);
|
|
1677
|
+
timer.unref?.();
|
|
1678
|
+
}
|
|
1679
|
+
// The compaction turn ended without the runtime reporting a compaction.
|
|
1680
|
+
if (ended && current?.phase === 'native' && current.requested) { compactFailed(sessionId, session, 'the runtime reported no compaction'); return; }
|
|
1681
|
+
if (current) {
|
|
1682
|
+
if (current.checkpoint !== undefined && current.phase === 'checkpoint' && !compactHeld(sessionId, session, false)) void compactNow(sessionId, session);
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
if (compactHeld(sessionId, session, true)) return;
|
|
1686
|
+
if (session.compactBuffer?.length) { flushCompactBuffer(sessionId, session); return; }
|
|
1687
|
+
const trigger = compactDue(session.mapping.compact ?? { auto: false, threshold: 1 }, session.contextFill, !!session.compactRequested);
|
|
1688
|
+
if (!trigger) return;
|
|
1689
|
+
if (trigger === 'auto' && session.compactFailedAt && Date.now() - session.compactFailedAt < COMPACT_RETRY_MS) return;
|
|
1690
|
+
session.compactRequested = false;
|
|
1691
|
+
const compacting: NonNullable<Session['compacting']> = { phase: 'checkpoint', trigger, startedAt: Date.now() };
|
|
1692
|
+
session.compacting = compacting;
|
|
1693
|
+
runLog(rootOf(sessionId), { event: 'compact.started', sessionId, agent: session.mapping.agent.name, trigger, ...(session.contextFill !== undefined ? { fill: Math.round(session.contextFill * 100) / 100 } : {}) });
|
|
1694
|
+
const work = queue.then(async () => {
|
|
1695
|
+
if (session.compacting !== compacting) return;
|
|
1696
|
+
if (session.closed || compactHeld(sessionId, session, true)) {
|
|
1697
|
+
session.compacting = undefined;
|
|
1698
|
+
if (trigger === 'manual') session.compactRequested = true;
|
|
1699
|
+
compactReleased(sessionId, session);
|
|
1700
|
+
return;
|
|
1701
|
+
}
|
|
1702
|
+
compacting.turn = true;
|
|
1703
|
+
await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: checkpointPrompt(trigger, session.contextFill) }] }, 'wake');
|
|
1704
|
+
}).catch(error => compactFailed(sessionId, session, errorData(error).message));
|
|
1705
|
+
queue = work.catch(() => {});
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
/** Compacts with the runtime's own mechanism, else a fresh conversation seeded with the checkpoint. */
|
|
1709
|
+
async function compactNow(sessionId: string, session: Session) {
|
|
1710
|
+
const current = session.compacting!;
|
|
1711
|
+
const checkpoint = current.checkpoint!;
|
|
1712
|
+
if (NATIVE_COMPACT.includes(session.runtimeKind)) {
|
|
1713
|
+
current.phase = 'native';
|
|
1714
|
+
try {
|
|
1715
|
+
// Codex takes the thread alone; its summary gets the checkpoint back from the note ALP sends after.
|
|
1716
|
+
await session.runtime.request('thread/compact/start', { threadId: session.threadId, ...(session.runtimeKind === 'codex' ? {} : { instructions: compactInstructions(checkpoint) }) });
|
|
1717
|
+
if (session.compacting !== current) return;
|
|
1718
|
+
current.requested = true;
|
|
1719
|
+
// A runtime that took the request but never reports a compaction does not hold main for good.
|
|
1720
|
+
const timer = setTimeout(() => { if (session.compacting === current) compactFailed(sessionId, session, 'the runtime reported no compaction in time'); }, COMPACT_NATIVE_MS);
|
|
1721
|
+
timer.unref?.();
|
|
1722
|
+
return;
|
|
1723
|
+
} catch (error) {
|
|
1724
|
+
if (session.compacting !== current) return;
|
|
1725
|
+
runLog(rootOf(sessionId), { event: 'compact.native_failed', sessionId, agent: session.mapping.agent.name, error: errorData(error).message });
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
current.phase = 'fresh';
|
|
1729
|
+
const work = queue.then(async () => {
|
|
1730
|
+
if (session.compacting !== current || session.closed) return;
|
|
1731
|
+
// A fresh conversation drops the old one: only when nothing runs that it would lose.
|
|
1732
|
+
// Held mail is no reason to wait: it reaches the new conversation after the seed; nor is the
|
|
1733
|
+
// supervisor's review, which reads main's journal, not its native conversation.
|
|
1734
|
+
const refusal = restartRefusal(sessionId, session);
|
|
1735
|
+
if (refusal && refusal !== MAIL_WAITS && refusal !== REVIEWING) { compactFailed(sessionId, session, `a fresh conversation cannot start now: ${refusal}`); return; }
|
|
1736
|
+
await restartNative(sessionId, session, undefined);
|
|
1737
|
+
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
1738
|
+
await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: seedPrompt(checkpoint, session.lastUserText) }] }, 'wake');
|
|
1739
|
+
compactFinished(sessionId, session, 'fresh');
|
|
1740
|
+
}).catch(error => compactFailed(sessionId, session, errorData(error).message));
|
|
1741
|
+
queue = work.catch(() => {});
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
function compactFinished(sessionId: string, session: Session, via: 'native' | 'fresh') {
|
|
1745
|
+
const current = session.compacting;
|
|
1746
|
+
if (!current) return;
|
|
1747
|
+
session.compacting = undefined;
|
|
1748
|
+
session.compactFailedAt = undefined;
|
|
1749
|
+
// Usage reported until main's next turn may still count the old context.
|
|
1750
|
+
session.contextFill = undefined;
|
|
1751
|
+
session.compactCooling = true;
|
|
1752
|
+
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 });
|
|
1753
|
+
const text = wordsFor(session).compacted(via === 'native');
|
|
1754
|
+
emit(sessionId, { type: 'item', item: { kind: 'notice', id: `notice-${randomUUID().slice(0, 8)}`, level: 'info', text } });
|
|
1755
|
+
compactReleased(sessionId, session);
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
function compactFailed(sessionId: string, session: Session, reason: string) {
|
|
1759
|
+
const current = session.compacting;
|
|
1760
|
+
session.compacting = undefined;
|
|
1761
|
+
session.compactFailedAt = Date.now();
|
|
1762
|
+
runLog(rootOf(sessionId), { event: 'compact.failed', sessionId, agent: session.mapping.agent.name, ...(current ? { trigger: current.trigger } : {}), error: reason });
|
|
1763
|
+
if (!session.closed) emit(sessionId, { type: 'item', item: { kind: 'notice', id: `notice-${randomUUID().slice(0, 8)}`, level: 'warning', text: wordsFor(session).compactFailed(reason) } });
|
|
1764
|
+
compactReleased(sessionId, session);
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
/** A compaction ended or never started: the user's held words and held mail go on (t-0e56). */
|
|
1768
|
+
function compactReleased(sessionId: string, session: Session) {
|
|
1769
|
+
queueMicrotask(() => {
|
|
1770
|
+
if (session.closed || session.compacting) return;
|
|
1771
|
+
flushCompactBuffer(sessionId, session);
|
|
1772
|
+
if (session.wakeHeld && !holdsWake(session)) { session.wakeHeld = false; deliver(sessionId, session); }
|
|
1773
|
+
});
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
/** Sends the user's words held during a compaction, in order, once no turn runs (t-0e56). */
|
|
1777
|
+
function flushCompactBuffer(sessionId: string, session: Session) {
|
|
1778
|
+
if (session.compacting || session.active || !session.compactBuffer?.length) return;
|
|
1779
|
+
const held = session.compactBuffer.splice(0);
|
|
1780
|
+
session.compactBuffer = undefined;
|
|
1781
|
+
const work = queue.then(async () => {
|
|
1782
|
+
for (const [index, input] of held.entries()) {
|
|
1783
|
+
await promptSession(sessionId, { ...input, delivery: index === 0 && !session.active ? 'auto' : 'steer' }, true);
|
|
1784
|
+
}
|
|
1785
|
+
});
|
|
1786
|
+
queue = work.catch(() => {});
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
/** The user's request to compact a root (t-0e56): now if it is idle, else at its next turn boundary. */
|
|
1790
|
+
function requestCompact(sessionId: string) {
|
|
1791
|
+
const session = sessions.get(sessionId);
|
|
1792
|
+
if (!session || session.closed) throw new ConversationError('session_busy', 'The session is not open');
|
|
1793
|
+
if (session.parent || session.role === 'supervisor') throw new ConversationError('runtime_unsupported', 'Only a root session is compacted');
|
|
1794
|
+
if (session.compacting) return { status: 'running' as const };
|
|
1795
|
+
session.compactRequested = true;
|
|
1796
|
+
if (compactHeld(sessionId, session, true)) return { status: 'deferred' as const };
|
|
1797
|
+
compactAtBoundary(sessionId, session);
|
|
1798
|
+
return { status: 'started' as const };
|
|
1564
1799
|
}
|
|
1565
1800
|
|
|
1566
1801
|
/** What ALP holds of a session's work, told to it after a compaction (ALPD §57). */
|
|
1567
|
-
async function restoreAfterCompaction(sessionId: string, session: Session) {
|
|
1802
|
+
async function restoreAfterCompaction(sessionId: string, session: Session, checkpoint?: string) {
|
|
1568
1803
|
const parts = ['Your context was just compacted. In case the summary lost any of it, this is what ALP holds of your work now.'];
|
|
1569
1804
|
if (session.parent && session.brief) parts.push(`Your assignment from ${session.parentAgent ?? 'your requester'}, as it was given:\n${cut(session.brief, BRIEF_CHARS)}`);
|
|
1570
1805
|
const running = [...session.assignments.values()].filter(assignment => !assignment.finished);
|
|
@@ -1575,7 +1810,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1575
1810
|
if (session.worktrees.size) {
|
|
1576
1811
|
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'));
|
|
1577
1812
|
}
|
|
1578
|
-
const asked = [...userQuestions.values()].filter(pending => pending.question.sessionId === sessionId);
|
|
1813
|
+
const asked = [...userQuestions.values()].filter(pending => pending.question.sessionId === sessionId && !pending.gate);
|
|
1579
1814
|
if (asked.length) parts.push('Waiting for the user to answer:\n' + asked.map(pending => `- ${clip(pending.question.body, 300)}`).join('\n'));
|
|
1580
1815
|
if (!session.parent) {
|
|
1581
1816
|
const project = session.mapping.agent.projectRoot;
|
|
@@ -1584,6 +1819,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1584
1819
|
const board = renderBoard(await boardOf(project));
|
|
1585
1820
|
if (board) parts.push(board);
|
|
1586
1821
|
}
|
|
1822
|
+
if (checkpoint) parts.push(`The checkpoint you wrote before the compaction, by skill compact:\n${cut(checkpoint, BRIEF_CHARS)}`);
|
|
1587
1823
|
parts.push('Carry on where you were; alp_board and alp_task tell you more.');
|
|
1588
1824
|
if (session.closed) return;
|
|
1589
1825
|
post(sessionId, { kind: 'note', from: 'alp', assignment: sessionId, body: parts.join('\n\n'), ...(session.active ? {} : { passive: true }) });
|
|
@@ -1679,7 +1915,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1679
1915
|
* answer approves; a dismissal, a timeout or another answer does not.
|
|
1680
1916
|
*/
|
|
1681
1917
|
async function confirm(sessionId: string, session: Session, body: string, approval?: { id: string }): Promise<{ approved: boolean; feedback?: string; outcome?: string }> {
|
|
1682
|
-
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId)) return { approved: false, outcome: 'busy', feedback: 'A question is already waiting for the user' };
|
|
1918
|
+
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' };
|
|
1683
1919
|
const say = wordsFor(session);
|
|
1684
1920
|
const result = await askUser(sessionId, session, undefined, body, [say.approve, say.reject], approval) as { contentItems: Array<{ text: string }> };
|
|
1685
1921
|
let value: any;
|
|
@@ -1744,7 +1980,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1744
1980
|
};
|
|
1745
1981
|
try { await readRoles(); } catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
1746
1982
|
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: 'Skill proposal canceled or session closed; no approval was created' });
|
|
1747
|
-
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' });
|
|
1983
|
+
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' });
|
|
1748
1984
|
const approvalId = `q-${randomUUID()}`;
|
|
1749
1985
|
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
1750
1986
|
approvals.set(key, record);
|
|
@@ -1811,6 +2047,141 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1811
2047
|
|
|
1812
2048
|
let scheduleHandler: ScheduleHandler | undefined;
|
|
1813
2049
|
|
|
2050
|
+
/**
|
|
2051
|
+
* alp_lesson_curate: merges, shortenings and removals of recorded lessons, all shown to
|
|
2052
|
+
* the user in one approval and applied only when approved. Lessons are matched by their
|
|
2053
|
+
* exact rule text; nothing else in a lessons file changes.
|
|
2054
|
+
*/
|
|
2055
|
+
async function lessonCurateTool(sessionId: string, session: Session, args: unknown) {
|
|
2056
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
2057
|
+
args = structuredClone(args);
|
|
2058
|
+
type Change = { scope: 'project' | 'user'; remove: string[]; add?: string; reason?: string };
|
|
2059
|
+
const validChange = (change: any) => plainObject(change, ['scope', 'remove', 'add', 'reason']) && ['project', 'user'].includes(change.scope) &&
|
|
2060
|
+
Array.isArray(change.remove) && change.remove.length > 0 && change.remove.length <= 50 && change.remove.every((lesson: unknown) => text(lesson, LESSON_CHARS)) &&
|
|
2061
|
+
(change.add === undefined || text(change.add, LESSON_CHARS)) && (change.reason === undefined || (typeof change.reason === 'string' && change.reason.length <= 300));
|
|
2062
|
+
if (!plainObject(args, ['changes', 'requestId']) || !Array.isArray(args.changes) || !args.changes.length || args.changes.length > 50 || !args.changes.every(validChange)) {
|
|
2063
|
+
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` });
|
|
2064
|
+
}
|
|
2065
|
+
if (args.requestId !== undefined && !text(args.requestId, 100)) return toolResult(false, { error: 'requestId must be a nonempty string of at most 100 characters' });
|
|
2066
|
+
const changes = args.changes as Change[];
|
|
2067
|
+
if (changes.some(change => change.scope === 'user') && !options.libraryDir) return toolResult(false, { error: 'This host keeps no user lessons' });
|
|
2068
|
+
const fileOf = (scope: string) => scope === 'user' ? path.join(options.libraryDir!, LESSONS_FILE) : path.join(session.mapping.agent.projectRoot, '.alp', LESSONS_FILE);
|
|
2069
|
+
const normalizeLesson = (lesson: string) => lesson.replace(/\s+/g, ' ').trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, '').trim();
|
|
2070
|
+
const normalized = changes.map(change => ({ ...change, remove: [...new Set(change.remove.map(normalizeLesson))], add: change.add?.replace(/\s+/g, ' ').trim() }));
|
|
2071
|
+
const draftKey = JSON.stringify(['lessons', normalized]);
|
|
2072
|
+
const key = `lessons:${args.requestId ?? draftKey}`;
|
|
2073
|
+
const approvals = approvalsOf(sessionId);
|
|
2074
|
+
const previous = approvals.get(key);
|
|
2075
|
+
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: 'requestId was already used for a different draft' });
|
|
2076
|
+
if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId });
|
|
2077
|
+
// Every lesson to remove must be recorded now; a proposal never guesses.
|
|
2078
|
+
const readLessons = async (file: string) => (await readFile(file, 'utf8').catch(() => '')).split('\n').flatMap(line => /^- \d{4}-\d\d-\d\d: /.test(line) ? [normalizeLesson(line)] : []);
|
|
2079
|
+
const missing: string[] = [];
|
|
2080
|
+
for (const change of normalized) {
|
|
2081
|
+
const recorded = new Set(await readLessons(fileOf(change.scope)));
|
|
2082
|
+
for (const lesson of change.remove) if (!recorded.has(lesson)) missing.push(`${change.scope}: ${lesson}`);
|
|
2083
|
+
}
|
|
2084
|
+
if (missing.length) return toolResult(false, { error: 'These lessons are not recorded; copy their exact text from the lessons files', missing });
|
|
2085
|
+
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: 'Lesson proposal canceled or session closed; no approval was created' });
|
|
2086
|
+
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' });
|
|
2087
|
+
const approvalId = `q-${randomUUID()}`;
|
|
2088
|
+
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
2089
|
+
approvals.set(key, record);
|
|
2090
|
+
const say = wordsFor(session);
|
|
2091
|
+
const shown = normalized.map((change, index) =>
|
|
2092
|
+
`${index + 1}. ${say.lessonScope(change.scope, fileOf(change.scope))}${change.reason ? ` — ${change.reason}` : ''}\n` +
|
|
2093
|
+
change.remove.map(lesson => ` ${say.lessonRemove}: ${lesson}`).join('\n') +
|
|
2094
|
+
(change.add ? `\n ${say.lessonAdd}: ${change.add}` : '')).join('\n\n');
|
|
2095
|
+
const decision = confirm(sessionId, session, `${say.lessonCurate(session.mapping.agent.name, shown)}\n\n${say.answerLine(session.mapping.agent.name)}`, { id: approvalId });
|
|
2096
|
+
const apply = async (): Promise<Record<string, unknown>> => {
|
|
2097
|
+
const removed: string[] = [];
|
|
2098
|
+
const notFound: string[] = [];
|
|
2099
|
+
let added = 0;
|
|
2100
|
+
for (const scope of ['project', 'user'] as const) {
|
|
2101
|
+
const mine = normalized.filter(change => change.scope === scope);
|
|
2102
|
+
if (!mine.length) continue;
|
|
2103
|
+
const file = fileOf(scope);
|
|
2104
|
+
const write = (lessonWrites.get(file) ?? Promise.resolve()).catch(() => {}).then(async () => {
|
|
2105
|
+
const current = await readFile(file, 'utf8').catch(() => undefined);
|
|
2106
|
+
if (current === undefined) { for (const change of mine) notFound.push(...change.remove.map(lesson => `${scope}: ${lesson}`)); return; }
|
|
2107
|
+
const targets = new Set(mine.flatMap(change => change.remove));
|
|
2108
|
+
const seen = new Set<string>();
|
|
2109
|
+
const kept = current.split('\n').filter(line => {
|
|
2110
|
+
if (!/^- \d{4}-\d\d-\d\d: /.test(line)) return true;
|
|
2111
|
+
const lesson = normalizeLesson(line);
|
|
2112
|
+
if (!targets.has(lesson)) return true;
|
|
2113
|
+
seen.add(lesson);
|
|
2114
|
+
return false;
|
|
2115
|
+
});
|
|
2116
|
+
for (const lesson of targets) (seen.has(lesson) ? removed : notFound).push(`${scope}: ${lesson}`);
|
|
2117
|
+
const date = new Date().toISOString().slice(0, 10);
|
|
2118
|
+
// A replacement whose lessons are all gone meanwhile would only duplicate what replaced them.
|
|
2119
|
+
const additions = mine.filter(change => change.add && change.remove.some(lesson => seen.has(lesson))).map(change => `- ${date}: ${change.add}`);
|
|
2120
|
+
added += additions.length;
|
|
2121
|
+
let body = kept.join('\n');
|
|
2122
|
+
if (additions.length) body = body.replace(/\n*$/, '\n') + additions.join('\n') + '\n';
|
|
2123
|
+
await writeFile(file, body);
|
|
2124
|
+
});
|
|
2125
|
+
lessonWrites.set(file, write);
|
|
2126
|
+
await write;
|
|
2127
|
+
}
|
|
2128
|
+
runLog(rootOf(sessionId), { event: 'lesson.curate', agent: session.mapping.agent.name, removed, added, notFound });
|
|
2129
|
+
return { approved: true, applied: true, removed, added, ...(notFound.length ? { lessonsNotFound: notFound } : {}) };
|
|
2130
|
+
};
|
|
2131
|
+
void (async () => {
|
|
2132
|
+
const answer = await decision;
|
|
2133
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
2134
|
+
let result: Record<string, unknown>;
|
|
2135
|
+
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.' };
|
|
2136
|
+
else {
|
|
2137
|
+
try { result = await apply(); }
|
|
2138
|
+
catch (error) { result = { approved: true, applied: false, error: errorData(error).message, next: 'Tell the user; nothing is retried automatically.' }; }
|
|
2139
|
+
}
|
|
2140
|
+
record.result = { status: 'resolved', approvalId, ...result };
|
|
2141
|
+
runLog(rootOf(sessionId), { event: 'lesson.curate.approval', agent: session.mapping.agent.name, ...record.result });
|
|
2142
|
+
if (!closed && !session.closed && sessions.get(sessionId) === session) post(sessionId, { kind: 'result', from: 'ALP', assignment: approvalId, body: `Lesson curate result: ${JSON.stringify(record.result)}` });
|
|
2143
|
+
})();
|
|
2144
|
+
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.' });
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
/**
|
|
2148
|
+
* The monthly curate: a supervised main keeps one pending job that wakes it on the first
|
|
2149
|
+
* of next month to run the curate skill. A job left by an earlier session of the project
|
|
2150
|
+
* is replaced, since it could not be delivered. settings curate.monthly false turns it off.
|
|
2151
|
+
*/
|
|
2152
|
+
const curateSchedules = new Map<string, Promise<unknown>>();
|
|
2153
|
+
function ensureCurateSchedule(sessionId: string) {
|
|
2154
|
+
const root = sessions.get(sessionId);
|
|
2155
|
+
if (!scheduleHandler || !root || root.closed || root.parent) return Promise.resolve();
|
|
2156
|
+
// One project's opens take turns, so two at once never leave two jobs.
|
|
2157
|
+
const project = root.mapping.agent.projectRoot;
|
|
2158
|
+
const run = (curateSchedules.get(project) ?? Promise.resolve()).catch(() => {}).then(() => curateScheduleOf(sessionId, root, project));
|
|
2159
|
+
curateSchedules.set(project, run);
|
|
2160
|
+
// The chain is dropped once nothing follows it.
|
|
2161
|
+
void run.catch(() => {}).then(() => { if (curateSchedules.get(project) === run) curateSchedules.delete(project); });
|
|
2162
|
+
return run;
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
async function curateScheduleOf(sessionId: string, root: Session, project: string) {
|
|
2166
|
+
const handler = scheduleHandler;
|
|
2167
|
+
if (!handler || root.closed || sessions.get(sessionId) !== root) return;
|
|
2168
|
+
for (const file of [path.join(project, '.alp', 'settings.json'), ...(options.libraryDir ? [path.join(options.libraryDir, 'settings.json')] : [])]) {
|
|
2169
|
+
const settings = await readFile(file, 'utf8').then(raw => { try { return JSON.parse(raw); } catch { return undefined; } }, () => undefined);
|
|
2170
|
+
const monthly = settings?.curate?.monthly;
|
|
2171
|
+
if (monthly === false) return;
|
|
2172
|
+
if (monthly === true) break;
|
|
2173
|
+
}
|
|
2174
|
+
const listed = await handler('list', { projectRoot: project, status: 'pending' }) as { jobs?: Array<{ id: string; sessionId: string; prompt: string }> };
|
|
2175
|
+
const curate = (listed?.jobs ?? []).filter(job => job.prompt.startsWith(CURATE_MARKER));
|
|
2176
|
+
if (curate.some(job => job.sessionId === sessionId)) return;
|
|
2177
|
+
for (const job of curate) await handler('cancel', { id: job.id, projectRoot: project }).catch(() => {});
|
|
2178
|
+
const now = new Date();
|
|
2179
|
+
const dueAt = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 2)).toISOString();
|
|
2180
|
+
// The monthly job never keeps main open; a closed session's job fails and the next open makes another.
|
|
2181
|
+
await handler('create', { projectRoot: project, sessionId, dueAt, prompt: CURATE_PROMPT, keepsSession: false });
|
|
2182
|
+
runLog(sessionId, { event: 'curate.scheduled', dueAt, replaced: curate.map(job => job.id) });
|
|
2183
|
+
}
|
|
2184
|
+
|
|
1814
2185
|
async function scheduleTool(sessionId: string, session: Session, args: unknown) {
|
|
1815
2186
|
if (session.parent || session.role === 'supervisor' || session.mapping.agent.name !== mainOf(session.mapping)) return toolResult(false, { error: 'Only the main root session schedules continuations' });
|
|
1816
2187
|
if (!scheduleHandler) return toolResult(false, { error: 'This host does not support scheduled continuations' });
|
|
@@ -1901,7 +2272,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1901
2272
|
const previous = approvals.get(key);
|
|
1902
2273
|
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: 'requestId was already used for a different draft' });
|
|
1903
2274
|
if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId, repo });
|
|
1904
|
-
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' });
|
|
2275
|
+
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' });
|
|
1905
2276
|
const approvalId = `q-${randomUUID()}`;
|
|
1906
2277
|
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
1907
2278
|
approvals.set(key, record);
|
|
@@ -1993,7 +2364,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1993
2364
|
void session.acknowledged.then(() => deliver(sessionId, session));
|
|
1994
2365
|
} else if (session.active) {
|
|
1995
2366
|
// Deferred mail waits for the turn to end.
|
|
1996
|
-
if (session.mail.some(event => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
|
|
2367
|
+
if (!session.compacting && session.mail.some(event => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
|
|
1997
2368
|
} else if (!waking) {
|
|
1998
2369
|
return;
|
|
1999
2370
|
} else if (!session.wakeBlocked && session.wakeFailures < MAX_WAKES && (session.wakes < MAX_WAKES || session.mail.some(event => !event.deliveredTurn && event.kind === 'checkin'))) {
|
|
@@ -2255,6 +2626,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2255
2626
|
assignmentId: assignment.id,
|
|
2256
2627
|
checkout: assignment.worktree?.checkout ?? assignment.writeCheckout ?? resultChild?.mapping.workdir ?? parent.mapping.workdir,
|
|
2257
2628
|
...(assignment.worktree ? { worktree: assignment.worktree.path } : {}),
|
|
2629
|
+
// Outside a worktree, the change stays in the checkout: keep its evidence until the requester resolves it.
|
|
2630
|
+
...(!assignment.worktree ? { result: {
|
|
2631
|
+
agent: assignment.agent, status: state, finishedAt: new Date().toISOString(),
|
|
2632
|
+
project: (resultChild ?? parent).mapping.agent.projectRoot, requesters: lineage(parentId), ...(assignment.taskId ? { taskId: assignment.taskId } : {}),
|
|
2633
|
+
brief: cut(resultChild?.brief ?? '', RESULT_EVIDENCE_CHARS),
|
|
2634
|
+
summary: cut(JSON.stringify({ handoff: resultChild?.handoff ?? null, output: resultChild ? [...resultChild.text.values()].at(-1) ?? '' : '', ...(error ? { error: errorData(error).message } : {}) }), RESULT_EVIDENCE_CHARS),
|
|
2635
|
+
} } : {}),
|
|
2258
2636
|
});
|
|
2259
2637
|
} catch (failure) {
|
|
2260
2638
|
// Keep both the assignment and its recovery evidence; never close away unrecorded ownership.
|
|
@@ -2357,7 +2735,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2357
2735
|
}
|
|
2358
2736
|
|
|
2359
2737
|
if (
|
|
2360
|
-
!['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', 'alp_schedule'].includes(params.tool) ||
|
|
2738
|
+
!['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) ||
|
|
2361
2739
|
params.namespace != null ||
|
|
2362
2740
|
typeof params.callId !== 'string'
|
|
2363
2741
|
) {
|
|
@@ -2370,12 +2748,16 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2370
2748
|
if (cached) return cached;
|
|
2371
2749
|
|
|
2372
2750
|
const args = params.arguments;
|
|
2751
|
+
// Every transport's arguments, before any tool walks them: the Codex, ACP and Antigravity paths have no schema of their own.
|
|
2752
|
+
const oversized = inputLimitError(args, TOOL_INPUT, `${params.tool} input`);
|
|
2753
|
+
if (oversized) return toolResult(false, { error: oversized });
|
|
2373
2754
|
// The supervisor only reads the board and tasks, and writes to main.
|
|
2374
2755
|
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' });
|
|
2375
|
-
if (
|
|
2756
|
+
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' });
|
|
2376
2757
|
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' });
|
|
2377
2758
|
const work =
|
|
2378
2759
|
params.tool === 'alp_lesson' ? lessonTool(sessionId, session, args)
|
|
2760
|
+
: params.tool === 'alp_lesson_curate' ? lessonCurateTool(sessionId, session, args)
|
|
2379
2761
|
: params.tool === 'alp_skill' ? skillTool(sessionId, session, args)
|
|
2380
2762
|
: params.tool === 'alp_issue' ? issueTool(sessionId, session, args)
|
|
2381
2763
|
: params.tool === 'alp_schedule' ? scheduleTool(sessionId, session, args)
|
|
@@ -2387,6 +2769,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2387
2769
|
: params.tool === 'alp_board' ? boardTool(session, args)
|
|
2388
2770
|
: params.tool === 'alp_unpin' ? unpinTool(sessionId, session, args)
|
|
2389
2771
|
: params.tool === 'alp_recall' ? recallTool(sessionId, session, args)
|
|
2772
|
+
: params.tool === 'alp_resolve' ? resolveTool(sessionId, session, args)
|
|
2390
2773
|
: params.tool === 'alp_verify' ? verifyTool(sessionId, session, args)
|
|
2391
2774
|
: params.tool === 'alp_cancel' ? cancelTool(sessionId, session, args)
|
|
2392
2775
|
: params.tool === 'alp_merge' || params.tool === 'alp_discard' ? worktreeTool(sessionId, session, args, params.tool === 'alp_merge' ? 'merge' : 'discard')
|
|
@@ -2567,11 +2950,210 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2567
2950
|
|
|
2568
2951
|
/** Ordinary questions end with their turn; issue approvals survive until decision or session cancellation. */
|
|
2569
2952
|
function cancelQuestions(sessionId: string, turnOnly = false) {
|
|
2570
|
-
for (const { question, settle, persistent } of [...userQuestions.values()]) {
|
|
2953
|
+
for (const { question, settle, persistent, gate } of [...userQuestions.values()]) {
|
|
2954
|
+
// A gate card ends only with its gate or its session; syncGates shows it again on the next main.
|
|
2955
|
+
if (gate && turnOnly) continue;
|
|
2571
2956
|
if (question.sessionId === sessionId && (!turnOnly || !persistent)) settle('canceled', undefined, undefined, toolResult(false, { error: 'Turn ended' }));
|
|
2572
2957
|
}
|
|
2573
2958
|
}
|
|
2574
2959
|
|
|
2960
|
+
// Human gates (t-ccac): .alp/tasks stays the source of truth. Each open human gate of a project
|
|
2961
|
+
// shows as a card on its live main root session, without a timeout and outside the one-question
|
|
2962
|
+
// limit; syncGates rebuilds the cards from the files (on start, attach, a gate change, a change
|
|
2963
|
+
// to the task files and a timer, since the CLI and Paseo's local panel write the files without
|
|
2964
|
+
// alpd) and tells main of every decision at least once (t-595d): the mail goes first, and
|
|
2965
|
+
// markGateNotified marks the decision only once a completed turn of main took it. Until then
|
|
2966
|
+
// the mail on its way is not sent again; after a restart it is, and its body tells main a repeat
|
|
2967
|
+
// changes nothing. With no live main, the decision waits for the project's next main.
|
|
2968
|
+
const gateSyncs = new Map<string, Promise<void>>();
|
|
2969
|
+
/** Decision mail on its way to main, by the decision it reports. */
|
|
2970
|
+
const gateMail = new WeakMap<MailEvent, { key: string; taken: () => void }>();
|
|
2971
|
+
/** Decisions main took whose mark is being written, or was. */
|
|
2972
|
+
const gateTaken = new Set<string>();
|
|
2973
|
+
/** Marks being written; shutdown waits for them, so nothing writes the task files after it. */
|
|
2974
|
+
const gateMarks = new Set<Promise<unknown>>();
|
|
2975
|
+
const gateCardId = (taskId: string, gateId: string) => `gate-${taskId}-${gateId}`;
|
|
2976
|
+
|
|
2977
|
+
/** The project's live main root session, if any. */
|
|
2978
|
+
function mainSessionOf(projectRoot: string) {
|
|
2979
|
+
for (const [id, session] of sessions) {
|
|
2980
|
+
if (session.closed || session.parent || session.role === 'supervisor' || !session.threadId) continue;
|
|
2981
|
+
if (session.mapping.agent.name !== mainOf(session.mapping) || path.resolve(session.mapping.agent.projectRoot) !== projectRoot) continue;
|
|
2982
|
+
return { id, session };
|
|
2983
|
+
}
|
|
2984
|
+
return undefined;
|
|
2985
|
+
}
|
|
2986
|
+
|
|
2987
|
+
function syncGates(projectRoot: string): Promise<void> {
|
|
2988
|
+
const root = path.resolve(projectRoot);
|
|
2989
|
+
const previous = gateSyncs.get(root) ?? Promise.resolve();
|
|
2990
|
+
const next = previous.then(() => syncGatesNow(root)).catch(error => { runLog(mainSessionOf(root)?.id ?? root, { event: 'gate.sync.failed', projectRoot: root, error: errorData(error).message }); });
|
|
2991
|
+
gateSyncs.set(root, next);
|
|
2992
|
+
void next.finally(() => { if (gateSyncs.get(root) === next) gateSyncs.delete(root); });
|
|
2993
|
+
return next;
|
|
2994
|
+
}
|
|
2995
|
+
|
|
2996
|
+
async function syncGatesNow(projectRoot: string) {
|
|
2997
|
+
if (closed) return;
|
|
2998
|
+
const { tasks } = await loadTasks(projectRoot);
|
|
2999
|
+
const main = mainSessionOf(projectRoot);
|
|
3000
|
+
// The user's decisions, to main at least once each; without a live main they wait for the next one.
|
|
3001
|
+
if (main) for (const { task, gate, decision, record } of gateDecisions(tasks)) {
|
|
3002
|
+
const key = JSON.stringify([projectRoot, task.id, gate.id, decision, record.at]);
|
|
3003
|
+
if (gateTaken.has(key) || main.session.mail.some(event => gateMail.get(event)?.key === key)) continue;
|
|
3004
|
+
const choice = decision === 'approved' ? (record as { choice?: string }).choice : undefined;
|
|
3005
|
+
const words = decision === 'approved'
|
|
3006
|
+
? `The user approved human gate ${gate.id} of ${task.id} in ${record.channel}${choice ? `, choosing "${choice}"` : ''}${(record as { note?: string }).note ? `: ${(record as { note?: string }).note}` : ''}.`
|
|
3007
|
+
: `The user rejected human gate ${gate.id} of ${task.id} in ${record.channel}${(record as { reason?: string }).reason ? `: ${(record as { reason?: string }).reason}` : ''}. The gate stays open.`;
|
|
3008
|
+
const mail = post(main.id, { kind: 'result', from: 'ALP', assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words} Task: ${task.title}. If this decision of ${gateCardId(task.id, gate.id)} was reported to you before, it is a repeat: act on it once.` });
|
|
3009
|
+
gateMail.set(mail, {
|
|
3010
|
+
key,
|
|
3011
|
+
taken: () => {
|
|
3012
|
+
gateTaken.add(key);
|
|
3013
|
+
const mark = markGateNotified(projectRoot, task.id, gate.id, decision, record.at).catch(error => {
|
|
3014
|
+
// Unmarked, it is mailed again: once more is better than never.
|
|
3015
|
+
gateTaken.delete(key);
|
|
3016
|
+
runLog(main.id, { event: 'gate.mark.failed', projectRoot, taskId: task.id, gateId: gate.id, error: errorData(error).message });
|
|
3017
|
+
});
|
|
3018
|
+
gateMarks.add(mark);
|
|
3019
|
+
void mark.finally(() => gateMarks.delete(mark));
|
|
3020
|
+
},
|
|
3021
|
+
});
|
|
3022
|
+
runLog(main.id, { event: 'gate.decision', projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record.channel, ...(choice ? { choice } : {}) });
|
|
3023
|
+
}
|
|
3024
|
+
// A card for each open human gate the user has not rejected; a rejected one stays open for main to follow up.
|
|
3025
|
+
const wanted = new Map<string, { task: Task; gate: Task['gates'][number] }>();
|
|
3026
|
+
for (const task of tasks) {
|
|
3027
|
+
if (task.status === 'closed') continue;
|
|
3028
|
+
for (const gate of task.gates ?? []) if (gate.kind === 'human' && !gate.resolved && !gate.rejected) wanted.set(gateCardId(task.id, gate.id), { task, gate });
|
|
3029
|
+
}
|
|
3030
|
+
for (const [id, pending] of [...userQuestions]) {
|
|
3031
|
+
if (pending.question.gate?.projectRoot !== projectRoot) continue;
|
|
3032
|
+
const want = wanted.get(id);
|
|
3033
|
+
if (!want || !main || pending.question.sessionId !== main.id) {
|
|
3034
|
+
const task = tasks.find(entry => entry.id === pending.question.gate!.taskId);
|
|
3035
|
+
const gate = task?.gates.find(entry => entry.id === pending.question.gate!.gateId);
|
|
3036
|
+
pending.settle(gate?.resolved ? 'answered' : gate?.rejected ? 'dismissed' : 'canceled', gate?.resolved?.choice, gate?.rejected?.reason);
|
|
3037
|
+
} else if (pending.gate) pending.gate.rev = want.task.rev;
|
|
3038
|
+
}
|
|
3039
|
+
if (!main) return;
|
|
3040
|
+
for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
|
|
3041
|
+
}
|
|
3042
|
+
|
|
3043
|
+
/**
|
|
3044
|
+
* The CLI and Paseo's local Tasks panel write gates without alpd: while a main is live, a change
|
|
3045
|
+
* to the project's task files syncs at once (t-595d), and a timer reads them too, where file
|
|
3046
|
+
* events are missing or lost.
|
|
3047
|
+
*/
|
|
3048
|
+
let gateWatch: NodeJS.Timeout | undefined;
|
|
3049
|
+
const gateFiles = new Map<string, { watcher: FSWatcher; timer?: NodeJS.Timeout }>();
|
|
3050
|
+
function startGateWatch(projectRoot: string) {
|
|
3051
|
+
if (options.gateSyncMs === 0) return;
|
|
3052
|
+
watchGateFiles(path.resolve(projectRoot));
|
|
3053
|
+
if (gateWatch) return;
|
|
3054
|
+
gateWatch = setInterval(() => {
|
|
3055
|
+
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)));
|
|
3056
|
+
for (const root of roots) { watchGateFiles(root); void syncGates(root); }
|
|
3057
|
+
for (const root of gateFiles.keys()) if (!roots.has(root)) unwatchGateFiles(root);
|
|
3058
|
+
if (!roots.size) { clearInterval(gateWatch); gateWatch = undefined; }
|
|
3059
|
+
}, options.gateSyncMs ?? 5_000);
|
|
3060
|
+
gateWatch.unref?.();
|
|
3061
|
+
}
|
|
3062
|
+
|
|
3063
|
+
function watchGateFiles(root: string) {
|
|
3064
|
+
if (closed || gateFiles.has(root)) return;
|
|
3065
|
+
try {
|
|
3066
|
+
const entry: { watcher: FSWatcher; timer?: NodeJS.Timeout } = {
|
|
3067
|
+
// A burst of writes (a save, its ledger, a mark) syncs once.
|
|
3068
|
+
watcher: watchFiles(path.join(root, TASKS_DIR), () => {
|
|
3069
|
+
if (entry.timer || closed) return;
|
|
3070
|
+
entry.timer = setTimeout(() => { entry.timer = undefined; void syncGates(root); }, 50);
|
|
3071
|
+
entry.timer.unref?.();
|
|
3072
|
+
}),
|
|
3073
|
+
};
|
|
3074
|
+
entry.watcher.on('error', () => unwatchGateFiles(root));
|
|
3075
|
+
entry.watcher.unref?.();
|
|
3076
|
+
gateFiles.set(root, entry);
|
|
3077
|
+
} catch {} // No task files yet, or no file events here: the timer tries again.
|
|
3078
|
+
}
|
|
3079
|
+
|
|
3080
|
+
function unwatchGateFiles(root: string) {
|
|
3081
|
+
const entry = gateFiles.get(root);
|
|
3082
|
+
if (!entry) return;
|
|
3083
|
+
gateFiles.delete(root);
|
|
3084
|
+
clearTimeout(entry.timer);
|
|
3085
|
+
entry.watcher.close();
|
|
3086
|
+
}
|
|
3087
|
+
|
|
3088
|
+
function showGateCard(sessionId: string, session: Session, projectRoot: string, task: Task, gate: Task['gates'][number]) {
|
|
3089
|
+
const say = wordsFor(session);
|
|
3090
|
+
const vietnamese = say.approve === words('vi').approve;
|
|
3091
|
+
const question: UserQuestion = {
|
|
3092
|
+
id: gateCardId(task.id, gate.id),
|
|
3093
|
+
sessionId,
|
|
3094
|
+
rootId: rootOf(sessionId),
|
|
3095
|
+
agent: 'ALP',
|
|
3096
|
+
body: `${vietnamese ? `Cổng phê duyệt ${gate.id} của ${task.id}` : `Approval gate ${gate.id} of ${task.id}`} (${task.title}):\n${gate.note ?? ''}`,
|
|
3097
|
+
// Options approve; Reject (added after them unless one of them is that word) keeps the gate open.
|
|
3098
|
+
options: gate.options?.length ? (gate.options.includes(say.reject) ? gate.options : [...gate.options, say.reject]) : [say.approve, say.reject],
|
|
3099
|
+
askedAt: gate.at ?? new Date().toISOString(),
|
|
3100
|
+
gate: { projectRoot, taskId: task.id, gateId: gate.id },
|
|
3101
|
+
};
|
|
3102
|
+
const card = { rev: task.rev, deciding: false };
|
|
3103
|
+
const settle = (outcome: 'answered' | 'dismissed' | 'timeout' | 'canceled', answer?: string) => {
|
|
3104
|
+
if (userQuestions.get(question.id)?.question !== question) return;
|
|
3105
|
+
userQuestions.delete(question.id);
|
|
3106
|
+
emit(sessionId, { type: 'question.resolved', questionId: question.id, outcome, ...(answer !== undefined ? { answer } : {}) });
|
|
3107
|
+
};
|
|
3108
|
+
userQuestions.set(question.id, { question, settle, persistent: true, gate: Object.assign(card, { decide: (reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }) => decideGate(projectRoot, question, card, reply, gate.options?.length ? gate.options : undefined) }) });
|
|
3109
|
+
emit(sessionId, { type: 'question', question });
|
|
3110
|
+
runLog(rootOf(sessionId), { event: 'gate.card', questionId: question.id, taskId: task.id, gateId: gate.id });
|
|
3111
|
+
}
|
|
3112
|
+
|
|
3113
|
+
/**
|
|
3114
|
+
* The user answered a gate card: an option approves (with the default Approve/Reject, Reject or
|
|
3115
|
+
* other words reject), dismissing rejects. The card's task rev guards the write; a stale rev is
|
|
3116
|
+
* read again and retried only while the gate is still open and undecided, so a decision another
|
|
3117
|
+
* channel made first is never applied or mailed twice. An answer that decides nothing (a second
|
|
3118
|
+
* one while the first is written, one another channel beat, or a failed write) is refused to the
|
|
3119
|
+
* caller, never only logged (t-595d).
|
|
3120
|
+
*/
|
|
3121
|
+
async function decideGate(projectRoot: string, question: UserQuestion, card: { rev: number; deciding: boolean }, reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }, choices?: string[]) {
|
|
3122
|
+
const defaults = !choices;
|
|
3123
|
+
const { taskId, gateId } = question.gate!;
|
|
3124
|
+
if (card.deciding) throw gateRefusal('GATE_BUSY', `An answer to gate ${gateId} of ${taskId} is already being recorded`);
|
|
3125
|
+
card.deciding = true;
|
|
3126
|
+
const channel = reply.channel ?? 'web';
|
|
3127
|
+
const text = reply.text?.trim();
|
|
3128
|
+
const approve = !reply.dismiss && !!text && (defaults ? APPROVALS.includes(text.toLowerCase()) : choices.includes(text));
|
|
3129
|
+
const rejectReason = reply.dismiss ? reply.reason : text && CHOICES_REJECT.includes(text.toLowerCase()) ? undefined : text;
|
|
3130
|
+
const write = (ifRev: number) => approve
|
|
3131
|
+
? resolveGate(projectRoot, taskId, gateId, { by: 'user', ifRev, channel, ...(defaults ? {} : { choice: text }) })
|
|
3132
|
+
: rejectGate(projectRoot, taskId, gateId, { by: 'user', ifRev, channel, ...(rejectReason ? { reason: rejectReason.slice(0, 2000) } : {}) });
|
|
3133
|
+
try {
|
|
3134
|
+
try { await write(card.rev); }
|
|
3135
|
+
catch (error: any) {
|
|
3136
|
+
if (error?.code !== 'TASK_CHANGED') throw error;
|
|
3137
|
+
const current = (await loadTasks(projectRoot)).tasks.find(entry => entry.id === taskId);
|
|
3138
|
+
const gate = current?.gates.find(entry => entry.id === gateId);
|
|
3139
|
+
if (!current || current.status === 'closed' || !gate) throw gateRefusal('GATE_DECIDED', `Gate ${gateId} of ${taskId} is no longer open`);
|
|
3140
|
+
if (gate.resolved || gate.rejected) throw gateRefusal('GATE_DECIDED', `Gate ${gateId} of ${taskId} was already ${gate.resolved ? 'approved' : 'rejected'}${(gate.resolved ?? gate.rejected)?.channel ? ` in ${(gate.resolved ?? gate.rejected)!.channel}` : ''}`);
|
|
3141
|
+
await write(current.rev);
|
|
3142
|
+
}
|
|
3143
|
+
} catch (error) {
|
|
3144
|
+
runLog(question.rootId, { event: 'gate.answer.failed', questionId: question.id, error: errorData(error).message });
|
|
3145
|
+
throw error;
|
|
3146
|
+
} finally {
|
|
3147
|
+
card.deciding = false;
|
|
3148
|
+
// Settles the card whatever happened: decided here, by another channel, or gone.
|
|
3149
|
+
await syncGates(projectRoot);
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
|
|
3153
|
+
function gateRefusal(code: 'GATE_BUSY' | 'GATE_DECIDED', message: string) {
|
|
3154
|
+
return Object.assign(new Error(message), { code });
|
|
3155
|
+
}
|
|
3156
|
+
|
|
2575
3157
|
function askTool(sessionId: string, session: Session, args: unknown) {
|
|
2576
3158
|
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
2577
3159
|
const assignment = parent?.assignments.get(sessionId);
|
|
@@ -2583,7 +3165,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2583
3165
|
if (args.options !== undefined && (to !== 'user' || !Array.isArray(args.options) || args.options.length > 10 || !args.options.every((option: unknown) => typeof option === 'string' && option.trim() && option.length <= 200))) {
|
|
2584
3166
|
return Promise.resolve(toolResult(false, { error: 'options are up to 10 short answers, for questions to the user' }));
|
|
2585
3167
|
}
|
|
2586
|
-
if (assignment?.ask || [...userQuestions.values()].some(pending => pending.question.sessionId === sessionId)) {
|
|
3168
|
+
if (assignment?.ask || [...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) {
|
|
2587
3169
|
return Promise.resolve(toolResult(false, { error: 'A question is already waiting for an answer' }));
|
|
2588
3170
|
}
|
|
2589
3171
|
// Only main talks to the user, unless the user has written to this assignment first.
|
|
@@ -3117,6 +3699,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3117
3699
|
if (assignment) assignmentSessions.set(assignment, session);
|
|
3118
3700
|
// Pending until its thread exists: mail posted meanwhile waits for it, as in a restart.
|
|
3119
3701
|
const finishPending = beginPending(session);
|
|
3702
|
+
const opening: { failure?: unknown } = {};
|
|
3703
|
+
openings.set(session, opening);
|
|
3704
|
+
/** A process failure during the open fails it: the step that saw it settle need not have failed. */
|
|
3705
|
+
const failedMeanwhile = () => { if (opening.failure !== undefined) throw opening.failure; };
|
|
3120
3706
|
|
|
3121
3707
|
sessions.set(
|
|
3122
3708
|
sessionId,
|
|
@@ -3127,6 +3713,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3127
3713
|
|
|
3128
3714
|
try {
|
|
3129
3715
|
await runtime.initialize();
|
|
3716
|
+
failedMeanwhile();
|
|
3130
3717
|
|
|
3131
3718
|
if (session.closed || sessions.get(sessionId) !== session) {
|
|
3132
3719
|
throw new Error(
|
|
@@ -3180,6 +3767,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3180
3767
|
|
|
3181
3768
|
session.threadId =
|
|
3182
3769
|
result.thread.id;
|
|
3770
|
+
failedMeanwhile();
|
|
3183
3771
|
|
|
3184
3772
|
if (session.closed || sessions.get(sessionId) !== session) {
|
|
3185
3773
|
throw new Error(
|
|
@@ -3187,6 +3775,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3187
3775
|
);
|
|
3188
3776
|
}
|
|
3189
3777
|
|
|
3778
|
+
// Open from here on: a process failure is the live session's (wire's onFailure).
|
|
3779
|
+
openings.delete(session);
|
|
3190
3780
|
session.buffered = [];
|
|
3191
3781
|
finishPending();
|
|
3192
3782
|
|
|
@@ -3200,6 +3790,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3200
3790
|
thinking: result.reasoningEffort ?? mapping.thinking,
|
|
3201
3791
|
},
|
|
3202
3792
|
});
|
|
3793
|
+
// A main root shows the project's open human gates and gets decisions made while none was live.
|
|
3794
|
+
if (!session.parent && session.role !== 'supervisor' && mapping.agent.name === mainOf(mapping)) { void syncGates(mapping.agent.projectRoot); startGateWatch(mapping.agent.projectRoot); }
|
|
3203
3795
|
|
|
3204
3796
|
if (
|
|
3205
3797
|
history === 'replay'
|
|
@@ -3226,8 +3818,12 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3226
3818
|
return snapshot(sessionId, session);
|
|
3227
3819
|
} catch (error) {
|
|
3228
3820
|
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 });
|
|
3229
|
-
//
|
|
3230
|
-
|
|
3821
|
+
// A process failure while the open ran is reported now that the open is through, once.
|
|
3822
|
+
const failed = openings.get(session);
|
|
3823
|
+
openings.delete(session);
|
|
3824
|
+
if (failed?.failure !== undefined) failSession(sessionId, session, failed.failure);
|
|
3825
|
+
// Share the retirement the failure started, and never resolve the id to a
|
|
3826
|
+
// replacement record when this open finishes late.
|
|
3231
3827
|
const cleanup = closeSession(sessionId, session, false);
|
|
3232
3828
|
finishPending();
|
|
3233
3829
|
await cleanup;
|
|
@@ -3258,6 +3854,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3258
3854
|
transport.onFailure((error) => {
|
|
3259
3855
|
// A transport ALP already replaced reports nothing.
|
|
3260
3856
|
if (session.closed || session.runtime !== transport || sessions.get(sessionId) !== session) return;
|
|
3857
|
+
// The first open still runs: it fails with this, and reports it when it is through.
|
|
3858
|
+
const opening = openings.get(session);
|
|
3859
|
+
if (opening) { opening.failure ??= error; return; }
|
|
3261
3860
|
if (revivable(session)) void revive(sessionId, session, error);
|
|
3262
3861
|
else failSession(sessionId, session, error);
|
|
3263
3862
|
});
|
|
@@ -3378,11 +3977,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3378
3977
|
if (session.pending) return 'The session is still opening or restarting';
|
|
3379
3978
|
if (session.active) return 'A turn is running';
|
|
3380
3979
|
if (session.children.size || session.assignments.size) return 'Assignments are still running';
|
|
3381
|
-
if ([...userQuestions.values()].some(pending => pending.question.rootId === sessionId)) return 'A question to the user waits for an answer';
|
|
3980
|
+
if ([...userQuestions.values()].some(pending => pending.question.rootId === sessionId && !pending.gate)) return 'A question to the user waits for an answer';
|
|
3382
3981
|
// Mail a lifecycle hold keeps waits for its release, then reaches the session's new conversation.
|
|
3383
|
-
if ((hasActiveMail(session) || session.wakeHeld) && !session.lifecycleHolds) return
|
|
3982
|
+
if ((hasActiveMail(session) || session.wakeHeld) && !session.lifecycleHolds) return MAIL_WAITS;
|
|
3384
3983
|
if (session.parked || session.parkReason) return 'The session is parked';
|
|
3385
|
-
if (reviewing(session)) return
|
|
3984
|
+
if (reviewing(session)) return REVIEWING;
|
|
3386
3985
|
return undefined;
|
|
3387
3986
|
}
|
|
3388
3987
|
|
|
@@ -3582,7 +4181,6 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3582
4181
|
// team or effort change never raises the mode the session runs with.
|
|
3583
4182
|
if (changes.mode !== undefined && mapping.mode !== changes.mode) return refused('permission_escalation', READ_ONLY_AGENTS.includes(agent) ? 'Advisors and the supervisor must remain read-only' : `Permission profile ${mapping.permissions?.name ?? ''} allows at most ${mapping.permissions?.base ?? mapping.mode}`.replace('profile allows', 'profile allows'));
|
|
3584
4183
|
if (changes.mode === undefined && !withinMode(mapping.mode, session.mapping.mode)) return refused('permission_escalation', `The change would run the session in ${mapping.mode}, beyond its ${session.mapping.mode}`);
|
|
3585
|
-
if (runtimeKind === 'antigravity' && mapping.mode !== session.mapping.mode) return refused('runtime_unsupported', 'Antigravity sessions keep their mode');
|
|
3586
4184
|
const before = executablesOf(session.mapping);
|
|
3587
4185
|
const added = [...executablesOf(mapping)].filter(entry => !before.has(entry));
|
|
3588
4186
|
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`);
|
|
@@ -3829,7 +4427,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3829
4427
|
if (assignment.lease && leases.get(assignment.lease)?.assignment === id) leases.delete(assignment.lease);
|
|
3830
4428
|
if (roleOf(parent.mapping, entry.agent) === 'peer') { const root = sessions.get(entry.rootId); if (root) root.peerCount--; }
|
|
3831
4429
|
if (assignment.copy) await removeCopy(assignment.copy).catch(() => {});
|
|
3832
|
-
|
|
4430
|
+
// The worktree predates this recovery and may hold uncommitted work: it stays (t-eae4).
|
|
3833
4431
|
};
|
|
3834
4432
|
try {
|
|
3835
4433
|
if (entry.lease) {
|
|
@@ -3837,7 +4435,14 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3837
4435
|
if (holder && !lineage(entry.parentId).includes(holder.assignment)) throw new Error(`${holder.agent} writes ${entry.lease} now`);
|
|
3838
4436
|
if (!holder) { assignment.lease = entry.lease; leases.set(entry.lease, { assignment: id, agent: entry.agent }); }
|
|
3839
4437
|
}
|
|
3840
|
-
if (entry.worktree)
|
|
4438
|
+
if (entry.worktree) {
|
|
4439
|
+
const { preserved, ...worktree } = await reattachWorktree(entry.worktree);
|
|
4440
|
+
assignment.worktree = worktree;
|
|
4441
|
+
if (preserved) {
|
|
4442
|
+
runLog(entry.rootId, { event: 'worktree.preserved', assignmentId: id, branch: worktree.branch, preserved });
|
|
4443
|
+
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}.` });
|
|
4444
|
+
}
|
|
4445
|
+
}
|
|
3841
4446
|
if (entry.copyOf) {
|
|
3842
4447
|
assignment.copy = await createCopy(entry.copyOf, copyRoot, id);
|
|
3843
4448
|
spec = { ...spec, workdir: assignment.copy.workdir };
|
|
@@ -3878,6 +4483,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3878
4483
|
assignmentId: entry.assignmentId,
|
|
3879
4484
|
checkout: entry.worktree?.checkout ?? entry.lease ?? entry.spec.writeRoot ?? entry.spec.workdir ?? entry.project,
|
|
3880
4485
|
...(entry.worktree ? { worktree: entry.worktree.path } : {}),
|
|
4486
|
+
...(!entry.worktree ? { result: {
|
|
4487
|
+
agent: entry.agent, status: 'abandoned', finishedAt: new Date().toISOString(), project: entry.project, requesters: sessions.has(entry.parentId) ? lineage(entry.parentId) : [entry.parentId],
|
|
4488
|
+
...(entry.taskId ? { taskId: entry.taskId } : {}), brief: cut(entry.brief ?? '', RESULT_EVIDENCE_CHARS), summary: cut(JSON.stringify({ reason }), RESULT_EVIDENCE_CHARS),
|
|
4489
|
+
} } : {}),
|
|
3881
4490
|
});
|
|
3882
4491
|
await inFlight.remove(entry.assignmentId);
|
|
3883
4492
|
const parent = sessions.get(entry.parentId);
|
|
@@ -3994,8 +4603,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3994
4603
|
}
|
|
3995
4604
|
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
3996
4605
|
if (parent && !withinMode(mode, parent.mapping.mode)) throw new Error('Child cannot exceed parent permissions');
|
|
3997
|
-
if (session.runtimeKind === '
|
|
3998
|
-
if (session.runtimeKind === 'claude') await session.runtime.request('session/configure', { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
|
|
4606
|
+
if (session.runtimeKind === 'claude' || session.runtimeKind === 'antigravity') await session.runtime.request('session/configure', { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
|
|
3999
4607
|
session.mapping.mode = mode;
|
|
4000
4608
|
session.spec = { ...session.spec, mode };
|
|
4001
4609
|
const updated = snapshot(sessionId, session);
|
|
@@ -4056,8 +4664,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4056
4664
|
}
|
|
4057
4665
|
|
|
4058
4666
|
// Shared by ordinary prompts and the scheduler's queue-scoped sender.
|
|
4059
|
-
async function promptSession(sessionId: string, input: PromptInput): Promise<void> {
|
|
4667
|
+
async function promptSession(sessionId: string, input: PromptInput, flushing = false): Promise<void> {
|
|
4060
4668
|
const session = sessions.get(sessionId);
|
|
4669
|
+
// While main writes its checkpoint and compacts, the user's words wait for the compaction's end (t-0e56).
|
|
4670
|
+
if (!flushing && session && !session.parent && (session.compacting || session.compactBuffer?.length)) {
|
|
4671
|
+
if (!session.seen.has(input.clientMessageId) && !session.compactBuffer?.some(held => held.clientMessageId === input.clientMessageId)) (session.compactBuffer ??= []).push(input);
|
|
4672
|
+
return;
|
|
4673
|
+
}
|
|
4061
4674
|
const parked = session?.parked;
|
|
4062
4675
|
try {
|
|
4063
4676
|
const prompt = session?.active && session.resumedTurn === session.active && input.delivery === 'auto'
|
|
@@ -4166,6 +4779,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4166
4779
|
) {
|
|
4167
4780
|
session.text.clear();
|
|
4168
4781
|
session.toolCalls.clear();
|
|
4782
|
+
if (!/^alp-wake-compact-/.test(prompt.clientMessageId)) session.compactCooling = false;
|
|
4169
4783
|
session.supervisorWake = !!wake?.length && wake.every(event => event.defer);
|
|
4170
4784
|
|
|
4171
4785
|
// A wake continues the same assignment: keep its handoff and limits.
|
|
@@ -4180,6 +4794,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4180
4794
|
|
|
4181
4795
|
try {
|
|
4182
4796
|
const orchestration = session.runtime.orchestrationContext ? await session.runtime.orchestrationContext().catch(() => ({ available: false })) : { available: false };
|
|
4797
|
+
// Each turn's own model list keeps the live catalog current (t-e5ee).
|
|
4798
|
+
feedCatalog(orchestration);
|
|
4183
4799
|
// Main starts each turn knowing what waits for its acceptance and what is ready.
|
|
4184
4800
|
const tasks = prompt.delivery !== 'steer' && !session.parent && session.mapping.agent.name === mainOf(session.mapping)
|
|
4185
4801
|
? await releaseOrphansOnce(session.mapping.agent.projectRoot, sessionId).then(() => checkGatesOften(session.mapping.agent.projectRoot)).then(() => loadTasks(session.mapping.agent.projectRoot)).then(({ tasks, errors }) => taskDigest(tasks, errors), () => '')
|
|
@@ -4274,6 +4890,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4274
4890
|
},
|
|
4275
4891
|
});
|
|
4276
4892
|
if (origin === 'user' && !session.parent) session.userWaiting ??= Date.now();
|
|
4893
|
+
if (origin === 'user' && !session.parent && text) session.lastUserText = clip(text, 16_000);
|
|
4277
4894
|
if (session.supervisor && origin === 'user') session.journal.push(stamp(`user ${prompt.delivery === 'steer' ? 'steered' : 'asked'} ${session.mapping.agent.name}: ${clip(text, 1500)}`));
|
|
4278
4895
|
// The steer reaches the model once its waiting tool returns; return it now, not when the work ends.
|
|
4279
4896
|
if (prompt.delivery === 'steer' && origin === 'user' && !session.parent) { releaseWaiters(session); releaseQuestions(sessionId); }
|
|
@@ -4318,12 +4935,12 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4318
4935
|
// Threads past their recall time go when the host starts, and after each assignment.
|
|
4319
4936
|
if (options.recallFile) void forgetExpired();
|
|
4320
4937
|
|
|
4321
|
-
|
|
4938
|
+
const api = {
|
|
4322
4939
|
registerWorkspace: directory => enqueue(async () => {
|
|
4323
4940
|
try { await assignmentResults.register(await realpath(directory)); }
|
|
4324
4941
|
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot register workspace result ownership'); }
|
|
4325
4942
|
}),
|
|
4326
|
-
withWorkspaceMutation: <T>(directory: string, run: () => Promise<T
|
|
4943
|
+
withWorkspaceMutation: <T>(directory: string, run: () => Promise<T>, adoption?: typeof ADOPTION): Promise<T> => {
|
|
4327
4944
|
// Reserve before enqueue/await: in-flight admission causes refusal, future admission cannot start.
|
|
4328
4945
|
if (workspaceMutation || admitting) return Promise.reject(new WorkspaceMutationError('workspace_busy', 'A session or assignment is opening; retry after it finishes'));
|
|
4329
4946
|
workspaceMutation = true;
|
|
@@ -4332,7 +4949,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4332
4949
|
let resultLedger: Awaited<ReturnType<typeof assignmentResults.inspect>>;
|
|
4333
4950
|
try { resultLedger = await assignmentResults.inspect(); }
|
|
4334
4951
|
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot inspect permanent assignment results'); }
|
|
4335
|
-
|
|
4952
|
+
// Only adoptWorkspace passes ADOPTION, to certify an old checkout after every check below.
|
|
4953
|
+
if (!resultLedger!.workspaces.includes(target) && adoption !== ADOPTION) refuseMutation('workspace_assignment_result', 'Workspace predates authoritative assignment tracking; an audited migration is required before removal');
|
|
4336
4954
|
const canonical = (value: string): string => {
|
|
4337
4955
|
try { return realpathSync(value); }
|
|
4338
4956
|
catch (error) {
|
|
@@ -4353,7 +4971,14 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4353
4971
|
};
|
|
4354
4972
|
return contains(target, owner) || contains(owner, target);
|
|
4355
4973
|
};
|
|
4356
|
-
|
|
4974
|
+
// A handled result no longer holds its paths; its evidence stays in the ledger until archived.
|
|
4975
|
+
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}`);
|
|
4976
|
+
// A recall entry outlives the result it describes by up to its own 14 days; once the result is handled, it holds nothing.
|
|
4977
|
+
const resolved = async (assignmentId: string) => {
|
|
4978
|
+
if (resultLedger!.results.some(owner => owner.assignmentId === assignmentId && owner.handled)) return true;
|
|
4979
|
+
try { return !!(await assignmentResults.archived(assignmentId)); }
|
|
4980
|
+
catch { return refuseMutation('workspace_assignment_result', 'Cannot inspect the assignment result archive; repair it before removing the workspace'); }
|
|
4981
|
+
};
|
|
4357
4982
|
for (const [project, pins] of loadedBoards) for (const pin of pins) {
|
|
4358
4983
|
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}`);
|
|
4359
4984
|
}
|
|
@@ -4382,13 +5007,20 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4382
5007
|
if (entry.worktree !== undefined && (!entry.worktree || !['path', 'checkout', 'workdir'].every(key => typeof entry.worktree[key] === 'string'))) refuseMutation('workspace_assignment_result', `Invalid worktree result in ${file}`);
|
|
4383
5008
|
if (entry.shared !== undefined && (!entry.shared || typeof entry.shared !== 'object' || Array.isArray(entry.shared))) refuseMutation('workspace_assignment_result', `Invalid shared result in ${file}`);
|
|
4384
5009
|
if (kind === 'live') checkLive(entry);
|
|
4385
|
-
else if (overlaps(entry.cwd) || overlaps(entry.shared?.writeRoot)) refuseMutation('workspace_assignment_result', `Preserve retained assignment ${entry.assignmentId} before removing ${directory}`);
|
|
5010
|
+
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}`);
|
|
4386
5011
|
}
|
|
4387
5012
|
}
|
|
4388
|
-
for (const entry of await recalls.all()) if (overlaps(entry.cwd) || overlaps(entry.shared?.writeRoot)) refuseMutation('workspace_assignment_result', `Preserve retained assignment ${entry.assignmentId} before removing ${directory}`);
|
|
5013
|
+
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}`);
|
|
4389
5014
|
return await run();
|
|
4390
5015
|
}).finally(() => { workspaceMutation = false; });
|
|
4391
5016
|
},
|
|
5017
|
+
adoptWorkspace: (directory: string, verify: (canonical: string) => Promise<void>): Promise<void> => api.withWorkspaceMutation(directory, async () => {
|
|
5018
|
+
// A path through a symlink names whatever the link points at today; adopt only the canonical path.
|
|
5019
|
+
if (await realpath(directory) !== directory) refuseMutation('workspace_identity', `Adopt ${directory} by its canonical path`);
|
|
5020
|
+
await verify(directory);
|
|
5021
|
+
try { await assignmentResults.register(directory); }
|
|
5022
|
+
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot register workspace result ownership'); }
|
|
5023
|
+
}, ADOPTION),
|
|
4392
5024
|
bindSchedules(handler: ScheduleHandler | undefined) { scheduleHandler = handler; },
|
|
4393
5025
|
bindAttachments(reader: AttachmentReader | undefined) { attachmentReader = reader; },
|
|
4394
5026
|
takesAttachments(sessionId: string) {
|
|
@@ -4407,7 +5039,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4407
5039
|
const opened = await openSession(sessionId, spec, history, delegation);
|
|
4408
5040
|
const root = sessions.get(sessionId)!;
|
|
4409
5041
|
// Main starts its supervisor beside it, without delaying its own open.
|
|
4410
|
-
if (supervises(root))
|
|
5042
|
+
if (supervises(root)) {
|
|
5043
|
+
void enqueue(() => openSupervisor(sessionId));
|
|
5044
|
+
void ensureCurateSchedule(sessionId).catch(error => runLog(sessionId, { event: 'curate.schedule.failed', error: errorData(error).message }));
|
|
5045
|
+
}
|
|
4411
5046
|
return opened;
|
|
4412
5047
|
}),
|
|
4413
5048
|
|
|
@@ -4465,6 +5100,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4465
5100
|
rebind: (sessionId, binding) => enqueue(() => rebindSession(sessionId, binding)),
|
|
4466
5101
|
|
|
4467
5102
|
reload: sessionId => enqueue(() => reloadSession(sessionId)),
|
|
5103
|
+
compact: (sessionId: string) => requestCompact(sessionId),
|
|
4468
5104
|
|
|
4469
5105
|
previewConfigure: (sessionId, changes) => previewConfigureSession(sessionId, changes),
|
|
4470
5106
|
|
|
@@ -4522,7 +5158,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4522
5158
|
};
|
|
4523
5159
|
visit(rootId);
|
|
4524
5160
|
const questions = [...userQuestions.values()].map(pending => pending.question).filter(question => question.rootId === rootId);
|
|
4525
|
-
const asking = new Set(questions.map(question => question.sessionId));
|
|
5161
|
+
const asking = new Set(questions.filter(question => !question.gate).map(question => question.sessionId));
|
|
4526
5162
|
const ids = new Set(tree.map(([id]) => id));
|
|
4527
5163
|
return {
|
|
4528
5164
|
rootId,
|
|
@@ -4572,6 +5208,26 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4572
5208
|
},
|
|
4573
5209
|
|
|
4574
5210
|
pauses: () => pauseState(),
|
|
5211
|
+
|
|
5212
|
+
holdForDisk(reason) {
|
|
5213
|
+
// A pause of all ALP already holds the work; the user's stays theirs to lift.
|
|
5214
|
+
if (paused.all) return pauseState();
|
|
5215
|
+
pauseRuntime('all', { since: new Date().toISOString(), by: 'alpd', reason, cause: 'disk' }, true);
|
|
5216
|
+
notice('error', say => say.diskFull(reason));
|
|
5217
|
+
return pauseState();
|
|
5218
|
+
},
|
|
5219
|
+
|
|
5220
|
+
releaseDisk(by) {
|
|
5221
|
+
if (paused.all?.cause !== 'disk') return pauseState();
|
|
5222
|
+
resumeRuntime('all', by, true);
|
|
5223
|
+
return pauseState();
|
|
5224
|
+
},
|
|
5225
|
+
|
|
5226
|
+
diskHeld: () => paused.all?.cause === 'disk',
|
|
5227
|
+
|
|
5228
|
+
diskLow(free) {
|
|
5229
|
+
notice('warning', say => say.diskLow(free));
|
|
5230
|
+
},
|
|
4575
5231
|
async usage(refresh = false) {
|
|
4576
5232
|
const providers = await Promise.all((['codex', 'claude'] as const).map(kind => cachedUsage(kind, refresh)));
|
|
4577
5233
|
const state = pauseState();
|
|
@@ -4610,6 +5266,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4610
5266
|
};
|
|
4611
5267
|
},
|
|
4612
5268
|
|
|
5269
|
+
syncGates(projectRoot) {
|
|
5270
|
+
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) return Promise.reject(new Error('syncGates needs an absolute projectRoot'));
|
|
5271
|
+
return syncGates(projectRoot);
|
|
5272
|
+
},
|
|
5273
|
+
|
|
4613
5274
|
async board(projectRoot) {
|
|
4614
5275
|
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) throw new Error('board needs an absolute projectRoot');
|
|
4615
5276
|
return (await boardOf(path.resolve(projectRoot))).filter(live);
|
|
@@ -4631,6 +5292,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4631
5292
|
answer(questionId, reply) {
|
|
4632
5293
|
const pending = userQuestions.get(questionId);
|
|
4633
5294
|
if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
|
|
5295
|
+
if (pending.gate) {
|
|
5296
|
+
if (!reply.dismiss && (typeof reply.text !== 'string' || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error('An answer needs text');
|
|
5297
|
+
return pending.gate.decide(reply);
|
|
5298
|
+
}
|
|
4634
5299
|
if (reply.dismiss) {
|
|
4635
5300
|
pending.settle('dismissed', undefined, reply.reason);
|
|
4636
5301
|
return;
|
|
@@ -4673,6 +5338,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4673
5338
|
);
|
|
4674
5339
|
|
|
4675
5340
|
clearInterval(watchdog);
|
|
5341
|
+
if (gateWatch) clearInterval(gateWatch);
|
|
5342
|
+
for (const root of [...gateFiles.keys()]) unwatchGateFiles(root);
|
|
5343
|
+
await Promise.all(gateSyncs.values());
|
|
5344
|
+
await Promise.all(gateMarks);
|
|
4676
5345
|
|
|
4677
5346
|
// Claims released by the closes above are written before the board is left.
|
|
4678
5347
|
await Promise.all(boards.values());
|
|
@@ -4687,5 +5356,6 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4687
5356
|
|
|
4688
5357
|
listeners.clear();
|
|
4689
5358
|
},
|
|
4690
|
-
};
|
|
5359
|
+
} satisfies AlpRuntime;
|
|
5360
|
+
return api;
|
|
4691
5361
|
}
|