@anhlp/alp-runtime 0.0.1-beta.4 → 0.0.1-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp-transport.js +5 -36
- package/dist/antigravity-transport.d.ts +17 -0
- package/dist/antigravity-transport.js +82 -58
- package/dist/assignment-results.d.ts +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 +65 -6
- 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 +25 -1
- package/dist/index.d.ts +9 -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 +605 -45
- 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 +11 -4
- package/dist/workspace.js +29 -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 +71 -6
- package/src/compact.ts +62 -0
- package/src/configure.ts +3 -3
- package/src/contracts.ts +22 -1
- package/src/index.ts +9 -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 +650 -46
- 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 +42 -15
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';
|
|
@@ -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, 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');
|
|
@@ -346,7 +364,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
346
364
|
}
|
|
347
365
|
session.userStopped = false;
|
|
348
366
|
if (session.role === 'supervisor' && session.parent && sessions.get(session.parent)?.reviewPending) review(session.parent);
|
|
367
|
+
if (session.role === 'supervisor' && session.parent) { const root = sessions.get(session.parent); if (root) queueMicrotask(() => compactAtBoundary(session.parent!, root)); }
|
|
349
368
|
if (!session.parent) void showTasks(sessionId, session);
|
|
369
|
+
if (!session.parent && session.role !== 'supervisor') queueMicrotask(() => compactAtBoundary(sessionId, session, state));
|
|
350
370
|
|
|
351
371
|
// An assignment a limit or a pause stopped waits, open, to continue instead of ending.
|
|
352
372
|
if (session.parkReason && state !== 'completed') {
|
|
@@ -583,7 +603,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
583
603
|
if (state === 'failed' && LIMIT_ERRORS.includes(params.turn.error?.codexErrorInfo)) {
|
|
584
604
|
if (session.role !== 'supervisor') {
|
|
585
605
|
session.parkReason = `the ${label(session.runtimeKind)} usage limit was reached`;
|
|
586
|
-
session.parkPause = { scope: paused.all ? 'all' : session.runtimeKind };
|
|
606
|
+
session.parkPause = { scope: paused.all ? 'all' : session.runtimeKind, ...(paused.all?.cause === 'disk' ? { disk: true } : {}) };
|
|
587
607
|
}
|
|
588
608
|
void limitReached(session, params.turn.error);
|
|
589
609
|
}
|
|
@@ -601,6 +621,12 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
601
621
|
// Keep the cleanup with that incarnation, even after its id has been reused.
|
|
602
622
|
const sessionClosures = new WeakMap<Session, Promise<void>>();
|
|
603
623
|
const openedSessions = new WeakSet<Session>();
|
|
624
|
+
/**
|
|
625
|
+
* Sessions whose first open is still running, with the process failure that came meanwhile: the
|
|
626
|
+
* open fails with it and reports it once it stopped using the session, rather than a failure
|
|
627
|
+
* callback closing the session under it (failSession while openSession still runs).
|
|
628
|
+
*/
|
|
629
|
+
const openings = new WeakMap<Session, { failure?: unknown }>();
|
|
604
630
|
const assignmentSessions = new WeakMap<Assignment, Session>();
|
|
605
631
|
function closeSession(sessionId: string, session = sessions.get(sessionId), notify = true): Promise<void> {
|
|
606
632
|
if (!session) return Promise.resolve();
|
|
@@ -764,7 +790,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
764
790
|
const boards = new Map<string, Promise<Pin[]>>();
|
|
765
791
|
/** The same boards once loaded, for synchronous status. */
|
|
766
792
|
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 }>();
|
|
793
|
+
const userQuestions = new Map<string, { question: UserQuestion; persistent?: boolean; /** From alp_ask: the user's words in the chat end it (#116). */ asked?: boolean; /** A card mirroring a human gate (t-ccac). */ gate?: { rev: number; deciding: boolean; decide: (reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }) => Promise<void> }; settle: (outcome: 'answered' | 'dismissed' | 'timeout' | 'canceled', answer?: string, reason?: string, result?: unknown) => void }>();
|
|
768
794
|
let mailSequence = 0;
|
|
769
795
|
let watchdog: NodeJS.Timeout | undefined;
|
|
770
796
|
|
|
@@ -1078,10 +1104,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1078
1104
|
return toolResult(true, { tasks: rows.slice(0, limit).map(task => summarize(task, tasks)), ...(rows.length > limit ? { more: rows.length - limit } : {}), ...warnings });
|
|
1079
1105
|
}
|
|
1080
1106
|
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:
|
|
1107
|
+
if (action === 'pour' && (typeof input.formula !== 'string' || (input.vars !== undefined && (!input.vars || typeof input.vars !== 'object' || Array.isArray(input.vars) || inputLimitError(input.vars, POUR_VARS) || !Object.entries(input.vars).every(([name, value]) => VAR_NAME.test(name) && typeof value === 'string'))))) {
|
|
1108
|
+
return toolResult(false, { error: `pour needs formula, and vars as an object of text values: at most ${POUR_VARS.items}, named like formula variables, each at most ${POUR_VARS.string} characters` });
|
|
1083
1109
|
}
|
|
1084
|
-
const { kind, until, ref, gate, formula: _formula, vars: _vars, ...fields } = input;
|
|
1110
|
+
const { kind, until, ref, gate, options: gateChoices, formula: _formula, vars: _vars, ...fields } = input;
|
|
1085
1111
|
if (action === 'clear') {
|
|
1086
1112
|
const current = (await loadTasks(project)).tasks.find(candidate => candidate.id === id);
|
|
1087
1113
|
if (current?.gates.find(entry => entry.id === gate)?.kind === 'human') return toolResult(false, { error: 'Only the user clears a human gate; ask them, and they approve it with alp task gate clear or in Paseo' });
|
|
@@ -1089,6 +1115,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1089
1115
|
let poured: Awaited<ReturnType<typeof pourFormula>> | undefined;
|
|
1090
1116
|
// A blocking task.close hook can refuse the close; its output is the reason.
|
|
1091
1117
|
const hookedClose = async (id: string) => {
|
|
1118
|
+
// Refused before any hook runs: no agent closes around a human gate (t-f438); core checks again under the lock.
|
|
1119
|
+
const current = (await loadTasks(project)).tasks.find(candidate => candidate.id === id);
|
|
1120
|
+
if (current && (current.step?.human || current.gates.some(gate => gate.kind === 'human' && !gate.resolved))) throw new Error(`Only the user closes ${id}: it waits on the user's decision. Ask the user to decide it`);
|
|
1092
1121
|
const refused = await runHooks(sessionId, session, 'task.close', { reason, ...(summary ? { summary } : {}) }, id);
|
|
1093
1122
|
if (refused) throw new Error(`A task.close hook refused to close ${id}: ${refused}`);
|
|
1094
1123
|
return closeTask(project, id, { reason, summary, unverified }, by);
|
|
@@ -1097,13 +1126,14 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1097
1126
|
action === 'create' ? await createTask(project, fields as any, by)
|
|
1098
1127
|
: action === 'update' ? await updateTask(project, id, { ...fields, note }, by)
|
|
1099
1128
|
: action === 'pour' ? (poured = await pourFormula(project, (await findFormula(project, options.libraryDir, input.formula, { toml })).formula, input.vars, by, input.parent ? { parent: input.parent } : {})).epic
|
|
1100
|
-
: action === 'gate' ? await addGate(project, id, { kind, note, until, ref }, by)
|
|
1129
|
+
: action === 'gate' ? await addGate(project, id, { kind, note, until, ref, ...(gateChoices !== undefined ? { options: gateChoices } : {}) }, by)
|
|
1101
1130
|
: action === 'clear' ? await resolveGate(project, id, gate, { by, note })
|
|
1102
1131
|
: action === 'link' ? await linkTask(project, id, { add, remove }, by)
|
|
1103
1132
|
: action === 'start' ? await startTask(project, id, { agent: by, session: sessionId }, by)
|
|
1104
1133
|
: action === 'close' ? await hookedClose(id)
|
|
1105
1134
|
: await reopenTask(project, id, { note }, by);
|
|
1106
1135
|
touchTask(rootOf(sessionId), task.id);
|
|
1136
|
+
if (action === 'gate' && kind === 'human') void syncGates(project);
|
|
1107
1137
|
runLog(rootOf(sessionId), { event: 'task', action, agent: by, id: task.id, title: task.title, status: task.status, ...(summary ?? note ? { detail: summary ?? note } : {}) });
|
|
1108
1138
|
const { tasks } = await loadTasks(project);
|
|
1109
1139
|
const landed: Record<string, unknown> = {};
|
|
@@ -1213,6 +1243,49 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1213
1243
|
}
|
|
1214
1244
|
}
|
|
1215
1245
|
|
|
1246
|
+
/**
|
|
1247
|
+
* Records how the requester handled a finished writer's change in its checkout, then archives the
|
|
1248
|
+
* result: until then the removal guard keeps that checkout. Recall expiry never stands in for this.
|
|
1249
|
+
*/
|
|
1250
|
+
async function resolveTool(sessionId: string, session: Session, args: unknown) {
|
|
1251
|
+
if (!plainObject(args, ['assignmentId', 'outcome', 'note']) || typeof args.assignmentId !== 'string' || !RESULT_OUTCOMES.includes(args.outcome as any) ||
|
|
1252
|
+
(args.note !== undefined && (typeof args.note !== 'string' || args.note.length > RESOLVE_NOTE_CHARS))) {
|
|
1253
|
+
return toolResult(false, { error: `Pass assignmentId, outcome (${RESULT_OUTCOMES.join(', ')}), and optionally a note of at most ${RESOLVE_NOTE_CHARS} characters` });
|
|
1254
|
+
}
|
|
1255
|
+
const id = args.assignmentId;
|
|
1256
|
+
const outcome = args.outcome as typeof RESULT_OUTCOMES[number];
|
|
1257
|
+
const note = args.note as string | undefined;
|
|
1258
|
+
const live = [...sessions.values()];
|
|
1259
|
+
if (sessions.has(id) || live.some(other => other.assignments.has(id)) || inFlight.all().some(entry => entry.assignmentId === id) || inherited.some(entry => entry.assignmentId === id)) {
|
|
1260
|
+
return toolResult(false, { error: 'That assignment is still running or can still be recovered; wait for its result' });
|
|
1261
|
+
}
|
|
1262
|
+
if (live.some(other => other.worktrees.has(id))) return toolResult(false, { error: 'Its change waits in a worktree; apply it with alp_merge or drop it with alp_discard' });
|
|
1263
|
+
let ledger: Awaited<ReturnType<typeof assignmentResults.inspect>>;
|
|
1264
|
+
try { ledger = await assignmentResults.inspect(); } catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
1265
|
+
const entry = ledger.results.find(owner => owner.assignmentId === id && !owner.handled);
|
|
1266
|
+
const project = session.mapping.agent.projectRoot;
|
|
1267
|
+
const overlapping = async (a: string, b: string) => {
|
|
1268
|
+
const [x, y] = [await realpath(a).catch(() => a), await realpath(b).catch(() => b)];
|
|
1269
|
+
const within = (parent: string, child: string) => { const relative = path.relative(parent, child); return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); };
|
|
1270
|
+
return within(x, y) || within(y, x);
|
|
1271
|
+
};
|
|
1272
|
+
// Its requesters may resolve it, and so may a root of its project, so a closed requester never leaves it held for good.
|
|
1273
|
+
// An entry from before evidence was kept names only its checkout: a root working there may resolve it.
|
|
1274
|
+
const allowed = !!entry && (entry.result
|
|
1275
|
+
? entry.result.requesters.includes(sessionId) || (!session.parent && await sameDirectory(entry.result.project, project))
|
|
1276
|
+
: !session.parent && await overlapping(entry.checkout, project));
|
|
1277
|
+
if (!entry || !allowed) return toolResult(false, { error: `No unresolved assignment result ${id} of yours` });
|
|
1278
|
+
// A worktree still on disk holds work only a merge or discard may settle.
|
|
1279
|
+
if (entry.worktree && await stat(entry.worktree).then(() => true, () => false)) return toolResult(false, { error: `Its worktree ${entry.worktree} still exists; merge or remove it first` });
|
|
1280
|
+
try {
|
|
1281
|
+
const archived = await assignmentResults.resolve(id, { outcome, by: `${session.mapping.agent.name} in ${sessionId}`, at: new Date().toISOString(), ...(note ? { note } : {}) });
|
|
1282
|
+
runLog(rootOf(sessionId), { event: 'result.resolved', assignmentId: id, agent: session.mapping.agent.name, outcome, ...(note ? { note: clip(note, 500) } : {}) });
|
|
1283
|
+
return toolResult(true, { resolved: id, outcome, archivedAt: archived.archivedAt });
|
|
1284
|
+
} catch (error) {
|
|
1285
|
+
return toolResult(false, { assignmentId: id, error: errorData(error).message });
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1216
1289
|
let forgetting = Promise.resolve();
|
|
1217
1290
|
|
|
1218
1291
|
/** Deletes the native threads of assignments past their recall time, one transport per runtime. */
|
|
@@ -1239,7 +1312,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1239
1312
|
/** Whether a session may not start a turn by itself now: parked, or on a paused runtime. */
|
|
1240
1313
|
const held = (session: Session) => !!session.parked || !!pauseOf(session.runtimeKind) || (session.lifecycleHolds ?? 0) > 0;
|
|
1241
1314
|
/** Whether mail may not wake a session now: it is held, or it is a new assignment whose brief has not started. */
|
|
1242
|
-
|
|
1315
|
+
// Mail waits while main compacts (t-0e56), so it never lands in the checkpoint or the compaction.
|
|
1316
|
+
const holdsWake = (session: Session) => held(session) || !!session.awaitingBrief || !!session.compacting;
|
|
1243
1317
|
|
|
1244
1318
|
/**
|
|
1245
1319
|
* Marks a session pending (its native process restarting) with a fresh `acknowledged` that resolves
|
|
@@ -1378,16 +1452,17 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1378
1452
|
if (!session.parent || session.closed || !session.active || session.role === 'supervisor' || (scope !== 'all' && session.runtimeKind !== scope)) continue;
|
|
1379
1453
|
// A process restart already owns its continuation; this pause must not replace its cause.
|
|
1380
1454
|
if (session.parkReason && !session.parkPause) continue;
|
|
1381
|
-
session.parkReason = `paused by ${pause.by}`;
|
|
1382
|
-
session.parkPause = { scope };
|
|
1455
|
+
session.parkReason = pause.cause === 'disk' ? pause.reason : `paused by ${pause.by}`;
|
|
1456
|
+
session.parkPause = { scope, ...(pause.cause === 'disk' ? { disk: true } : {}) };
|
|
1383
1457
|
void session.runtime.request('turn/interrupt', { threadId: session.threadId, turnId: session.active }).catch(() => {});
|
|
1384
1458
|
runLog(rootOf(id), { event: 'assignment.parking', assignmentId: id, agent: session.mapping.agent.name, reason: session.parkReason });
|
|
1385
1459
|
}
|
|
1386
1460
|
}
|
|
1387
1461
|
}
|
|
1388
1462
|
|
|
1389
|
-
function resumeRuntime(scope: RuntimeKind | 'all', by: string) {
|
|
1390
|
-
|
|
1463
|
+
function resumeRuntime(scope: RuntimeKind | 'all', by: string, keepRuntimes = false) {
|
|
1464
|
+
// Lifting alpd's disk pause keeps the usage-limit pauses of single runtimes.
|
|
1465
|
+
if (scope === 'all') paused = keepRuntimes ? { runtimes: paused.runtimes } : { runtimes: {} };
|
|
1391
1466
|
else delete paused.runtimes[scope];
|
|
1392
1467
|
savePauses();
|
|
1393
1468
|
watchLimits();
|
|
@@ -1422,6 +1497,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1422
1497
|
emit(session.parent!, { type: 'assignment', assignment: assignmentSnapshot(assignment, 'parked') });
|
|
1423
1498
|
// One that continues by itself is information; one held until the user resumes needs the requester's decision, so it wakes it.
|
|
1424
1499
|
if (then) post(session.parent!, { kind: 'note', from: assignment.agent, assignment: sessionId, passive: true, body: `Parked: ${session.parked.reason}. ${then} Wait for it, or start other work.` });
|
|
1500
|
+
else if (session.parked.pause?.disk) post(session.parent!, { kind: 'stalled', from: assignment.agent, assignment: sessionId, body: `Parked: ${session.parked.reason}. ALP continues this assignment where it stopped as soon as the disk takes writes again (alpd checks every minute), or when the user frees space and runs alp resume. Wait for it, or tell the user the disk is full; what it changed stays in your checkout or its worktree.` });
|
|
1425
1501
|
else post(session.parent!, { kind: 'stalled', from: assignment.agent, assignment: sessionId, body: `Parked: ${session.parked.reason}. ALP continues this assignment where it stopped when ${label(session.runtimeKind)} is resumed (${options.autoResume !== false && (pauseOf(session.runtimeKind)?.by ?? 'alpd') === 'alpd' ? `ALP resumes it as soon as ${label(session.runtimeKind)} says the limit lifted` : 'the user runs alp resume'}). Wait for it, start other work, or stop it with alp_cancel and give the rest to an agent on another runtime (pass model claude:… or codex:…); what it changed stays in your checkout or its worktree.` });
|
|
1426
1502
|
}
|
|
1427
1503
|
|
|
@@ -1505,6 +1581,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1505
1581
|
const used = usage?.last?.totalTokens;
|
|
1506
1582
|
const window = usage?.modelContextWindow;
|
|
1507
1583
|
if (session.role === 'supervisor' || typeof used !== 'number' || typeof window !== 'number' || window <= 0) return;
|
|
1584
|
+
// Against the window main works in, as the advisory measures it; not from the old context right after a compaction.
|
|
1585
|
+
if (!session.compactCooling) session.contextFill = contextFill({ ...usage, modelContextWindow: Math.min(typeof session.mapping.autocompact === 'number' ? session.mapping.autocompact : typeof session.mapping.context === 'number' ? session.mapping.context : window, window) });
|
|
1508
1586
|
const compactAt = typeof usage.autoCompactTokens === 'number' && usage.autoCompactTokens > 0
|
|
1509
1587
|
? usage.autoCompactTokens
|
|
1510
1588
|
: session.runtimeKind === 'codex' && session.mapping.autocompact
|
|
@@ -1557,14 +1635,169 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1557
1635
|
if (!done) return;
|
|
1558
1636
|
const agent = session.mapping.agent.name;
|
|
1559
1637
|
runLog(rootOf(sessionId), { event: 'compacted', sessionId, agent, ...trigger, ...tokens, ...(failed ? { failed: true, ...(item.error ? { error: String(item.error) } : {}) } : {}) });
|
|
1560
|
-
if (failed) return;
|
|
1638
|
+
if (failed) { if (session.compacting?.phase === 'native') compactFailed(sessionId, session, item.error ? String(item.error) : 'the runtime could not compact'); return; }
|
|
1561
1639
|
session.contextLevel = 0;
|
|
1562
1640
|
if (session.supervisor) session.journal.push(stamp(`${agent}'s context was compacted`));
|
|
1563
|
-
|
|
1641
|
+
const checkpoint = session.compacting?.phase === 'native' ? session.compacting.checkpoint : undefined;
|
|
1642
|
+
if (session.role !== 'supervisor') void restoreAfterCompaction(sessionId, session, checkpoint).catch(() => {});
|
|
1643
|
+
if (checkpoint !== undefined) compactFinished(sessionId, session, 'native');
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
/**
|
|
1647
|
+
* Whether a root holds anything a compaction must not cut into (t-0e56): a turn, a restart,
|
|
1648
|
+
* a question to the user or a park. Before one starts, also mail that would wake it. The
|
|
1649
|
+
* supervisor's review does not hold it: its mail waits for the compaction's end like any other.
|
|
1650
|
+
*/
|
|
1651
|
+
function compactHeld(sessionId: string, session: Session, starting: boolean) {
|
|
1652
|
+
return session.closed || !!session.active || !!session.pending || session.waiters.length > 0
|
|
1653
|
+
|| !!session.parked || !!session.parkReason
|
|
1654
|
+
|| (starting && (hasActiveMail(session) || !!session.wakeHeld))
|
|
1655
|
+
|| [...userQuestions.values()].some(pending => pending.question.rootId === sessionId && !pending.gate);
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
/**
|
|
1659
|
+
* Main's compaction (t-0e56). Once its context fills to the threshold, or the user asked,
|
|
1660
|
+
* main writes a checkpoint by skill compact in a turn of its own; after that turn the
|
|
1661
|
+
* runtime compacts natively, or ALP starts a fresh conversation seeded with it. It starts
|
|
1662
|
+
* only at a turn boundary (`ended`, the state of the turn that just ended); without one it
|
|
1663
|
+
* is a retry, after a hold such as the supervisor's review or held mail clears.
|
|
1664
|
+
*/
|
|
1665
|
+
function compactAtBoundary(sessionId: string, session: Session, ended?: 'completed' | 'failed' | 'canceled') {
|
|
1666
|
+
if (session.closed || sessions.get(sessionId) !== session) return;
|
|
1667
|
+
const current = session.compacting;
|
|
1668
|
+
if (ended && current?.phase === 'checkpoint' && current.checkpoint === undefined && current.turn) {
|
|
1669
|
+
// The checkpoint turn just ended: its last words are the checkpoint.
|
|
1670
|
+
const written = [...session.text.values()].at(-1)?.trim();
|
|
1671
|
+
if (ended !== 'completed' || !written) { compactFailed(sessionId, session, ended !== 'completed' ? `the checkpoint turn ${ended}` : 'main wrote no checkpoint'); return; }
|
|
1672
|
+
current.checkpoint = written;
|
|
1673
|
+
// A hold that outlasts this (a question, a park) fails it, so the user's held words go on.
|
|
1674
|
+
const timer = setTimeout(() => { if (session.compacting === current && current.phase === 'checkpoint') compactFailed(sessionId, session, 'main stayed busy after its checkpoint'); }, COMPACT_NATIVE_MS);
|
|
1675
|
+
timer.unref?.();
|
|
1676
|
+
}
|
|
1677
|
+
// The compaction turn ended without the runtime reporting a compaction.
|
|
1678
|
+
if (ended && current?.phase === 'native' && current.requested) { compactFailed(sessionId, session, 'the runtime reported no compaction'); return; }
|
|
1679
|
+
if (current) {
|
|
1680
|
+
if (current.checkpoint !== undefined && current.phase === 'checkpoint' && !compactHeld(sessionId, session, false)) void compactNow(sessionId, session);
|
|
1681
|
+
return;
|
|
1682
|
+
}
|
|
1683
|
+
if (compactHeld(sessionId, session, true)) return;
|
|
1684
|
+
if (session.compactBuffer?.length) { flushCompactBuffer(sessionId, session); return; }
|
|
1685
|
+
const trigger = compactDue(session.mapping.compact ?? { auto: false, threshold: 1 }, session.contextFill, !!session.compactRequested);
|
|
1686
|
+
if (!trigger) return;
|
|
1687
|
+
if (trigger === 'auto' && session.compactFailedAt && Date.now() - session.compactFailedAt < COMPACT_RETRY_MS) return;
|
|
1688
|
+
session.compactRequested = false;
|
|
1689
|
+
const compacting: NonNullable<Session['compacting']> = { phase: 'checkpoint', trigger, startedAt: Date.now() };
|
|
1690
|
+
session.compacting = compacting;
|
|
1691
|
+
runLog(rootOf(sessionId), { event: 'compact.started', sessionId, agent: session.mapping.agent.name, trigger, ...(session.contextFill !== undefined ? { fill: Math.round(session.contextFill * 100) / 100 } : {}) });
|
|
1692
|
+
const work = queue.then(async () => {
|
|
1693
|
+
if (session.compacting !== compacting) return;
|
|
1694
|
+
if (session.closed || compactHeld(sessionId, session, true)) {
|
|
1695
|
+
session.compacting = undefined;
|
|
1696
|
+
if (trigger === 'manual') session.compactRequested = true;
|
|
1697
|
+
compactReleased(sessionId, session);
|
|
1698
|
+
return;
|
|
1699
|
+
}
|
|
1700
|
+
compacting.turn = true;
|
|
1701
|
+
await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: checkpointPrompt(trigger, session.contextFill) }] }, 'wake');
|
|
1702
|
+
}).catch(error => compactFailed(sessionId, session, errorData(error).message));
|
|
1703
|
+
queue = work.catch(() => {});
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
/** Compacts with the runtime's own mechanism, else a fresh conversation seeded with the checkpoint. */
|
|
1707
|
+
async function compactNow(sessionId: string, session: Session) {
|
|
1708
|
+
const current = session.compacting!;
|
|
1709
|
+
const checkpoint = current.checkpoint!;
|
|
1710
|
+
if (NATIVE_COMPACT.includes(session.runtimeKind)) {
|
|
1711
|
+
current.phase = 'native';
|
|
1712
|
+
try {
|
|
1713
|
+
// Codex takes the thread alone; its summary gets the checkpoint back from the note ALP sends after.
|
|
1714
|
+
await session.runtime.request('thread/compact/start', { threadId: session.threadId, ...(session.runtimeKind === 'codex' ? {} : { instructions: compactInstructions(checkpoint) }) });
|
|
1715
|
+
if (session.compacting !== current) return;
|
|
1716
|
+
current.requested = true;
|
|
1717
|
+
// A runtime that took the request but never reports a compaction does not hold main for good.
|
|
1718
|
+
const timer = setTimeout(() => { if (session.compacting === current) compactFailed(sessionId, session, 'the runtime reported no compaction in time'); }, COMPACT_NATIVE_MS);
|
|
1719
|
+
timer.unref?.();
|
|
1720
|
+
return;
|
|
1721
|
+
} catch (error) {
|
|
1722
|
+
if (session.compacting !== current) return;
|
|
1723
|
+
runLog(rootOf(sessionId), { event: 'compact.native_failed', sessionId, agent: session.mapping.agent.name, error: errorData(error).message });
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
current.phase = 'fresh';
|
|
1727
|
+
const work = queue.then(async () => {
|
|
1728
|
+
if (session.compacting !== current || session.closed) return;
|
|
1729
|
+
// A fresh conversation drops the old one: only when nothing runs that it would lose.
|
|
1730
|
+
// Held mail is no reason to wait: it reaches the new conversation after the seed; nor is the
|
|
1731
|
+
// supervisor's review, which reads main's journal, not its native conversation.
|
|
1732
|
+
const refusal = restartRefusal(sessionId, session);
|
|
1733
|
+
if (refusal && refusal !== MAIL_WAITS && refusal !== REVIEWING) { compactFailed(sessionId, session, `a fresh conversation cannot start now: ${refusal}`); return; }
|
|
1734
|
+
await restartNative(sessionId, session, undefined);
|
|
1735
|
+
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
1736
|
+
await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: seedPrompt(checkpoint, session.lastUserText) }] }, 'wake');
|
|
1737
|
+
compactFinished(sessionId, session, 'fresh');
|
|
1738
|
+
}).catch(error => compactFailed(sessionId, session, errorData(error).message));
|
|
1739
|
+
queue = work.catch(() => {});
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
function compactFinished(sessionId: string, session: Session, via: 'native' | 'fresh') {
|
|
1743
|
+
const current = session.compacting;
|
|
1744
|
+
if (!current) return;
|
|
1745
|
+
session.compacting = undefined;
|
|
1746
|
+
session.compactFailedAt = undefined;
|
|
1747
|
+
// Usage reported until main's next turn may still count the old context.
|
|
1748
|
+
session.contextFill = undefined;
|
|
1749
|
+
session.compactCooling = true;
|
|
1750
|
+
runLog(rootOf(sessionId), { event: 'compact', sessionId, agent: session.mapping.agent.name, trigger: current.trigger, via, checkpointChars: current.checkpoint?.length ?? 0, ms: Date.now() - current.startedAt });
|
|
1751
|
+
const text = wordsFor(session).compacted(via === 'native');
|
|
1752
|
+
emit(sessionId, { type: 'item', item: { kind: 'notice', id: `notice-${randomUUID().slice(0, 8)}`, level: 'info', text } });
|
|
1753
|
+
compactReleased(sessionId, session);
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
function compactFailed(sessionId: string, session: Session, reason: string) {
|
|
1757
|
+
const current = session.compacting;
|
|
1758
|
+
session.compacting = undefined;
|
|
1759
|
+
session.compactFailedAt = Date.now();
|
|
1760
|
+
runLog(rootOf(sessionId), { event: 'compact.failed', sessionId, agent: session.mapping.agent.name, ...(current ? { trigger: current.trigger } : {}), error: reason });
|
|
1761
|
+
if (!session.closed) emit(sessionId, { type: 'item', item: { kind: 'notice', id: `notice-${randomUUID().slice(0, 8)}`, level: 'warning', text: wordsFor(session).compactFailed(reason) } });
|
|
1762
|
+
compactReleased(sessionId, session);
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
/** A compaction ended or never started: the user's held words and held mail go on (t-0e56). */
|
|
1766
|
+
function compactReleased(sessionId: string, session: Session) {
|
|
1767
|
+
queueMicrotask(() => {
|
|
1768
|
+
if (session.closed || session.compacting) return;
|
|
1769
|
+
flushCompactBuffer(sessionId, session);
|
|
1770
|
+
if (session.wakeHeld && !holdsWake(session)) { session.wakeHeld = false; deliver(sessionId, session); }
|
|
1771
|
+
});
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
/** Sends the user's words held during a compaction, in order, once no turn runs (t-0e56). */
|
|
1775
|
+
function flushCompactBuffer(sessionId: string, session: Session) {
|
|
1776
|
+
if (session.compacting || session.active || !session.compactBuffer?.length) return;
|
|
1777
|
+
const held = session.compactBuffer.splice(0);
|
|
1778
|
+
session.compactBuffer = undefined;
|
|
1779
|
+
const work = queue.then(async () => {
|
|
1780
|
+
for (const [index, input] of held.entries()) {
|
|
1781
|
+
await promptSession(sessionId, { ...input, delivery: index === 0 && !session.active ? 'auto' : 'steer' }, true);
|
|
1782
|
+
}
|
|
1783
|
+
});
|
|
1784
|
+
queue = work.catch(() => {});
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
/** The user's request to compact a root (t-0e56): now if it is idle, else at its next turn boundary. */
|
|
1788
|
+
function requestCompact(sessionId: string) {
|
|
1789
|
+
const session = sessions.get(sessionId);
|
|
1790
|
+
if (!session || session.closed) throw new ConversationError('session_busy', 'The session is not open');
|
|
1791
|
+
if (session.parent || session.role === 'supervisor') throw new ConversationError('runtime_unsupported', 'Only a root session is compacted');
|
|
1792
|
+
if (session.compacting) return { status: 'running' as const };
|
|
1793
|
+
session.compactRequested = true;
|
|
1794
|
+
if (compactHeld(sessionId, session, true)) return { status: 'deferred' as const };
|
|
1795
|
+
compactAtBoundary(sessionId, session);
|
|
1796
|
+
return { status: 'started' as const };
|
|
1564
1797
|
}
|
|
1565
1798
|
|
|
1566
1799
|
/** What ALP holds of a session's work, told to it after a compaction (ALPD §57). */
|
|
1567
|
-
async function restoreAfterCompaction(sessionId: string, session: Session) {
|
|
1800
|
+
async function restoreAfterCompaction(sessionId: string, session: Session, checkpoint?: string) {
|
|
1568
1801
|
const parts = ['Your context was just compacted. In case the summary lost any of it, this is what ALP holds of your work now.'];
|
|
1569
1802
|
if (session.parent && session.brief) parts.push(`Your assignment from ${session.parentAgent ?? 'your requester'}, as it was given:\n${cut(session.brief, BRIEF_CHARS)}`);
|
|
1570
1803
|
const running = [...session.assignments.values()].filter(assignment => !assignment.finished);
|
|
@@ -1575,7 +1808,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1575
1808
|
if (session.worktrees.size) {
|
|
1576
1809
|
parts.push('Finished worktree changes waiting for alp_merge or alp_discard:\n' + [...session.worktrees].map(([id, change]) => `- ${id}: ${change.agent}${change.taskId ? ` on ${change.taskId}` : ''}`).join('\n'));
|
|
1577
1810
|
}
|
|
1578
|
-
const asked = [...userQuestions.values()].filter(pending => pending.question.sessionId === sessionId);
|
|
1811
|
+
const asked = [...userQuestions.values()].filter(pending => pending.question.sessionId === sessionId && !pending.gate);
|
|
1579
1812
|
if (asked.length) parts.push('Waiting for the user to answer:\n' + asked.map(pending => `- ${clip(pending.question.body, 300)}`).join('\n'));
|
|
1580
1813
|
if (!session.parent) {
|
|
1581
1814
|
const project = session.mapping.agent.projectRoot;
|
|
@@ -1584,6 +1817,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1584
1817
|
const board = renderBoard(await boardOf(project));
|
|
1585
1818
|
if (board) parts.push(board);
|
|
1586
1819
|
}
|
|
1820
|
+
if (checkpoint) parts.push(`The checkpoint you wrote before the compaction, by skill compact:\n${cut(checkpoint, BRIEF_CHARS)}`);
|
|
1587
1821
|
parts.push('Carry on where you were; alp_board and alp_task tell you more.');
|
|
1588
1822
|
if (session.closed) return;
|
|
1589
1823
|
post(sessionId, { kind: 'note', from: 'alp', assignment: sessionId, body: parts.join('\n\n'), ...(session.active ? {} : { passive: true }) });
|
|
@@ -1679,7 +1913,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1679
1913
|
* answer approves; a dismissal, a timeout or another answer does not.
|
|
1680
1914
|
*/
|
|
1681
1915
|
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' };
|
|
1916
|
+
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) return { approved: false, outcome: 'busy', feedback: 'A question is already waiting for the user' };
|
|
1683
1917
|
const say = wordsFor(session);
|
|
1684
1918
|
const result = await askUser(sessionId, session, undefined, body, [say.approve, say.reject], approval) as { contentItems: Array<{ text: string }> };
|
|
1685
1919
|
let value: any;
|
|
@@ -1744,7 +1978,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1744
1978
|
};
|
|
1745
1979
|
try { await readRoles(); } catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
1746
1980
|
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' });
|
|
1981
|
+
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) return toolResult(false, { error: 'A question is already waiting for the user; finish it before proposing a skill' });
|
|
1748
1982
|
const approvalId = `q-${randomUUID()}`;
|
|
1749
1983
|
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
1750
1984
|
approvals.set(key, record);
|
|
@@ -1811,6 +2045,141 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1811
2045
|
|
|
1812
2046
|
let scheduleHandler: ScheduleHandler | undefined;
|
|
1813
2047
|
|
|
2048
|
+
/**
|
|
2049
|
+
* alp_lesson_curate: merges, shortenings and removals of recorded lessons, all shown to
|
|
2050
|
+
* the user in one approval and applied only when approved. Lessons are matched by their
|
|
2051
|
+
* exact rule text; nothing else in a lessons file changes.
|
|
2052
|
+
*/
|
|
2053
|
+
async function lessonCurateTool(sessionId: string, session: Session, args: unknown) {
|
|
2054
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
2055
|
+
args = structuredClone(args);
|
|
2056
|
+
type Change = { scope: 'project' | 'user'; remove: string[]; add?: string; reason?: string };
|
|
2057
|
+
const validChange = (change: any) => plainObject(change, ['scope', 'remove', 'add', 'reason']) && ['project', 'user'].includes(change.scope) &&
|
|
2058
|
+
Array.isArray(change.remove) && change.remove.length > 0 && change.remove.length <= 50 && change.remove.every((lesson: unknown) => text(lesson, LESSON_CHARS)) &&
|
|
2059
|
+
(change.add === undefined || text(change.add, LESSON_CHARS)) && (change.reason === undefined || (typeof change.reason === 'string' && change.reason.length <= 300));
|
|
2060
|
+
if (!plainObject(args, ['changes', 'requestId']) || !Array.isArray(args.changes) || !args.changes.length || args.changes.length > 50 || !args.changes.every(validChange)) {
|
|
2061
|
+
return toolResult(false, { error: `changes needs 1 to 50 entries, each with scope (project or user), remove (the exact text of 1 to 50 lessons) and optionally add (one rule of at most ${LESSON_CHARS} characters) and reason` });
|
|
2062
|
+
}
|
|
2063
|
+
if (args.requestId !== undefined && !text(args.requestId, 100)) return toolResult(false, { error: 'requestId must be a nonempty string of at most 100 characters' });
|
|
2064
|
+
const changes = args.changes as Change[];
|
|
2065
|
+
if (changes.some(change => change.scope === 'user') && !options.libraryDir) return toolResult(false, { error: 'This host keeps no user lessons' });
|
|
2066
|
+
const fileOf = (scope: string) => scope === 'user' ? path.join(options.libraryDir!, LESSONS_FILE) : path.join(session.mapping.agent.projectRoot, '.alp', LESSONS_FILE);
|
|
2067
|
+
const normalizeLesson = (lesson: string) => lesson.replace(/\s+/g, ' ').trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, '').trim();
|
|
2068
|
+
const normalized = changes.map(change => ({ ...change, remove: [...new Set(change.remove.map(normalizeLesson))], add: change.add?.replace(/\s+/g, ' ').trim() }));
|
|
2069
|
+
const draftKey = JSON.stringify(['lessons', normalized]);
|
|
2070
|
+
const key = `lessons:${args.requestId ?? draftKey}`;
|
|
2071
|
+
const approvals = approvalsOf(sessionId);
|
|
2072
|
+
const previous = approvals.get(key);
|
|
2073
|
+
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: 'requestId was already used for a different draft' });
|
|
2074
|
+
if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId });
|
|
2075
|
+
// Every lesson to remove must be recorded now; a proposal never guesses.
|
|
2076
|
+
const readLessons = async (file: string) => (await readFile(file, 'utf8').catch(() => '')).split('\n').flatMap(line => /^- \d{4}-\d\d-\d\d: /.test(line) ? [normalizeLesson(line)] : []);
|
|
2077
|
+
const missing: string[] = [];
|
|
2078
|
+
for (const change of normalized) {
|
|
2079
|
+
const recorded = new Set(await readLessons(fileOf(change.scope)));
|
|
2080
|
+
for (const lesson of change.remove) if (!recorded.has(lesson)) missing.push(`${change.scope}: ${lesson}`);
|
|
2081
|
+
}
|
|
2082
|
+
if (missing.length) return toolResult(false, { error: 'These lessons are not recorded; copy their exact text from the lessons files', missing });
|
|
2083
|
+
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: 'Lesson proposal canceled or session closed; no approval was created' });
|
|
2084
|
+
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) return toolResult(false, { error: 'A question is already waiting for the user; finish it before proposing lesson changes' });
|
|
2085
|
+
const approvalId = `q-${randomUUID()}`;
|
|
2086
|
+
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
2087
|
+
approvals.set(key, record);
|
|
2088
|
+
const say = wordsFor(session);
|
|
2089
|
+
const shown = normalized.map((change, index) =>
|
|
2090
|
+
`${index + 1}. ${say.lessonScope(change.scope, fileOf(change.scope))}${change.reason ? ` — ${change.reason}` : ''}\n` +
|
|
2091
|
+
change.remove.map(lesson => ` ${say.lessonRemove}: ${lesson}`).join('\n') +
|
|
2092
|
+
(change.add ? `\n ${say.lessonAdd}: ${change.add}` : '')).join('\n\n');
|
|
2093
|
+
const decision = confirm(sessionId, session, `${say.lessonCurate(session.mapping.agent.name, shown)}\n\n${say.answerLine(session.mapping.agent.name)}`, { id: approvalId });
|
|
2094
|
+
const apply = async (): Promise<Record<string, unknown>> => {
|
|
2095
|
+
const removed: string[] = [];
|
|
2096
|
+
const notFound: string[] = [];
|
|
2097
|
+
let added = 0;
|
|
2098
|
+
for (const scope of ['project', 'user'] as const) {
|
|
2099
|
+
const mine = normalized.filter(change => change.scope === scope);
|
|
2100
|
+
if (!mine.length) continue;
|
|
2101
|
+
const file = fileOf(scope);
|
|
2102
|
+
const write = (lessonWrites.get(file) ?? Promise.resolve()).catch(() => {}).then(async () => {
|
|
2103
|
+
const current = await readFile(file, 'utf8').catch(() => undefined);
|
|
2104
|
+
if (current === undefined) { for (const change of mine) notFound.push(...change.remove.map(lesson => `${scope}: ${lesson}`)); return; }
|
|
2105
|
+
const targets = new Set(mine.flatMap(change => change.remove));
|
|
2106
|
+
const seen = new Set<string>();
|
|
2107
|
+
const kept = current.split('\n').filter(line => {
|
|
2108
|
+
if (!/^- \d{4}-\d\d-\d\d: /.test(line)) return true;
|
|
2109
|
+
const lesson = normalizeLesson(line);
|
|
2110
|
+
if (!targets.has(lesson)) return true;
|
|
2111
|
+
seen.add(lesson);
|
|
2112
|
+
return false;
|
|
2113
|
+
});
|
|
2114
|
+
for (const lesson of targets) (seen.has(lesson) ? removed : notFound).push(`${scope}: ${lesson}`);
|
|
2115
|
+
const date = new Date().toISOString().slice(0, 10);
|
|
2116
|
+
// A replacement whose lessons are all gone meanwhile would only duplicate what replaced them.
|
|
2117
|
+
const additions = mine.filter(change => change.add && change.remove.some(lesson => seen.has(lesson))).map(change => `- ${date}: ${change.add}`);
|
|
2118
|
+
added += additions.length;
|
|
2119
|
+
let body = kept.join('\n');
|
|
2120
|
+
if (additions.length) body = body.replace(/\n*$/, '\n') + additions.join('\n') + '\n';
|
|
2121
|
+
await writeFile(file, body);
|
|
2122
|
+
});
|
|
2123
|
+
lessonWrites.set(file, write);
|
|
2124
|
+
await write;
|
|
2125
|
+
}
|
|
2126
|
+
runLog(rootOf(sessionId), { event: 'lesson.curate', agent: session.mapping.agent.name, removed, added, notFound });
|
|
2127
|
+
return { approved: true, applied: true, removed, added, ...(notFound.length ? { lessonsNotFound: notFound } : {}) };
|
|
2128
|
+
};
|
|
2129
|
+
void (async () => {
|
|
2130
|
+
const answer = await decision;
|
|
2131
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
2132
|
+
let result: Record<string, unknown>;
|
|
2133
|
+
if (!answer.approved || canceled) result = { approved: false, applied: false, outcome: canceled ? 'canceled' : answer.outcome, ...(answer.feedback ? { feedback: answer.feedback } : {}), next: 'Nothing changed. Revise from the feedback and propose again with a fresh requestId, or drop it.' };
|
|
2134
|
+
else {
|
|
2135
|
+
try { result = await apply(); }
|
|
2136
|
+
catch (error) { result = { approved: true, applied: false, error: errorData(error).message, next: 'Tell the user; nothing is retried automatically.' }; }
|
|
2137
|
+
}
|
|
2138
|
+
record.result = { status: 'resolved', approvalId, ...result };
|
|
2139
|
+
runLog(rootOf(sessionId), { event: 'lesson.curate.approval', agent: session.mapping.agent.name, ...record.result });
|
|
2140
|
+
if (!closed && !session.closed && sessions.get(sessionId) === session) post(sessionId, { kind: 'result', from: 'ALP', assignment: approvalId, body: `Lesson curate result: ${JSON.stringify(record.result)}` });
|
|
2141
|
+
})();
|
|
2142
|
+
return toolResult(true, { status: 'pending_approval', approvalId, next: 'Continue other work or end your turn. ALP sends the decision and what changed by mail; do not resubmit this draft.' });
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
/**
|
|
2146
|
+
* The monthly curate: a supervised main keeps one pending job that wakes it on the first
|
|
2147
|
+
* of next month to run the curate skill. A job left by an earlier session of the project
|
|
2148
|
+
* is replaced, since it could not be delivered. settings curate.monthly false turns it off.
|
|
2149
|
+
*/
|
|
2150
|
+
const curateSchedules = new Map<string, Promise<unknown>>();
|
|
2151
|
+
function ensureCurateSchedule(sessionId: string) {
|
|
2152
|
+
const root = sessions.get(sessionId);
|
|
2153
|
+
if (!scheduleHandler || !root || root.closed || root.parent) return Promise.resolve();
|
|
2154
|
+
// One project's opens take turns, so two at once never leave two jobs.
|
|
2155
|
+
const project = root.mapping.agent.projectRoot;
|
|
2156
|
+
const run = (curateSchedules.get(project) ?? Promise.resolve()).catch(() => {}).then(() => curateScheduleOf(sessionId, root, project));
|
|
2157
|
+
curateSchedules.set(project, run);
|
|
2158
|
+
// The chain is dropped once nothing follows it.
|
|
2159
|
+
void run.catch(() => {}).then(() => { if (curateSchedules.get(project) === run) curateSchedules.delete(project); });
|
|
2160
|
+
return run;
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2163
|
+
async function curateScheduleOf(sessionId: string, root: Session, project: string) {
|
|
2164
|
+
const handler = scheduleHandler;
|
|
2165
|
+
if (!handler || root.closed || sessions.get(sessionId) !== root) return;
|
|
2166
|
+
for (const file of [path.join(project, '.alp', 'settings.json'), ...(options.libraryDir ? [path.join(options.libraryDir, 'settings.json')] : [])]) {
|
|
2167
|
+
const settings = await readFile(file, 'utf8').then(raw => { try { return JSON.parse(raw); } catch { return undefined; } }, () => undefined);
|
|
2168
|
+
const monthly = settings?.curate?.monthly;
|
|
2169
|
+
if (monthly === false) return;
|
|
2170
|
+
if (monthly === true) break;
|
|
2171
|
+
}
|
|
2172
|
+
const listed = await handler('list', { projectRoot: project, status: 'pending' }) as { jobs?: Array<{ id: string; sessionId: string; prompt: string }> };
|
|
2173
|
+
const curate = (listed?.jobs ?? []).filter(job => job.prompt.startsWith(CURATE_MARKER));
|
|
2174
|
+
if (curate.some(job => job.sessionId === sessionId)) return;
|
|
2175
|
+
for (const job of curate) await handler('cancel', { id: job.id, projectRoot: project }).catch(() => {});
|
|
2176
|
+
const now = new Date();
|
|
2177
|
+
const dueAt = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 2)).toISOString();
|
|
2178
|
+
// The monthly job never keeps main open; a closed session's job fails and the next open makes another.
|
|
2179
|
+
await handler('create', { projectRoot: project, sessionId, dueAt, prompt: CURATE_PROMPT, keepsSession: false });
|
|
2180
|
+
runLog(sessionId, { event: 'curate.scheduled', dueAt, replaced: curate.map(job => job.id) });
|
|
2181
|
+
}
|
|
2182
|
+
|
|
1814
2183
|
async function scheduleTool(sessionId: string, session: Session, args: unknown) {
|
|
1815
2184
|
if (session.parent || session.role === 'supervisor' || session.mapping.agent.name !== mainOf(session.mapping)) return toolResult(false, { error: 'Only the main root session schedules continuations' });
|
|
1816
2185
|
if (!scheduleHandler) return toolResult(false, { error: 'This host does not support scheduled continuations' });
|
|
@@ -1901,7 +2270,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1901
2270
|
const previous = approvals.get(key);
|
|
1902
2271
|
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: 'requestId was already used for a different draft' });
|
|
1903
2272
|
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' });
|
|
2273
|
+
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) return toolResult(false, { error: 'A question is already waiting for the user; finish it before proposing another issue draft' });
|
|
1905
2274
|
const approvalId = `q-${randomUUID()}`;
|
|
1906
2275
|
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
1907
2276
|
approvals.set(key, record);
|
|
@@ -1993,7 +2362,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1993
2362
|
void session.acknowledged.then(() => deliver(sessionId, session));
|
|
1994
2363
|
} else if (session.active) {
|
|
1995
2364
|
// Deferred mail waits for the turn to end.
|
|
1996
|
-
if (session.mail.some(event => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
|
|
2365
|
+
if (!session.compacting && session.mail.some(event => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
|
|
1997
2366
|
} else if (!waking) {
|
|
1998
2367
|
return;
|
|
1999
2368
|
} else if (!session.wakeBlocked && session.wakeFailures < MAX_WAKES && (session.wakes < MAX_WAKES || session.mail.some(event => !event.deliveredTurn && event.kind === 'checkin'))) {
|
|
@@ -2255,6 +2624,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2255
2624
|
assignmentId: assignment.id,
|
|
2256
2625
|
checkout: assignment.worktree?.checkout ?? assignment.writeCheckout ?? resultChild?.mapping.workdir ?? parent.mapping.workdir,
|
|
2257
2626
|
...(assignment.worktree ? { worktree: assignment.worktree.path } : {}),
|
|
2627
|
+
// Outside a worktree, the change stays in the checkout: keep its evidence until the requester resolves it.
|
|
2628
|
+
...(!assignment.worktree ? { result: {
|
|
2629
|
+
agent: assignment.agent, status: state, finishedAt: new Date().toISOString(),
|
|
2630
|
+
project: (resultChild ?? parent).mapping.agent.projectRoot, requesters: lineage(parentId), ...(assignment.taskId ? { taskId: assignment.taskId } : {}),
|
|
2631
|
+
brief: cut(resultChild?.brief ?? '', RESULT_EVIDENCE_CHARS),
|
|
2632
|
+
summary: cut(JSON.stringify({ handoff: resultChild?.handoff ?? null, output: resultChild ? [...resultChild.text.values()].at(-1) ?? '' : '', ...(error ? { error: errorData(error).message } : {}) }), RESULT_EVIDENCE_CHARS),
|
|
2633
|
+
} } : {}),
|
|
2258
2634
|
});
|
|
2259
2635
|
} catch (failure) {
|
|
2260
2636
|
// Keep both the assignment and its recovery evidence; never close away unrecorded ownership.
|
|
@@ -2357,7 +2733,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2357
2733
|
}
|
|
2358
2734
|
|
|
2359
2735
|
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) ||
|
|
2736
|
+
!['alp_delegate', 'alp_handoff', 'alp_wait', 'alp_cancel', 'alp_send', 'alp_ask', 'alp_merge', 'alp_discard', 'alp_resolve', 'alp_recall', 'alp_verify', 'alp_pin', 'alp_board', 'alp_unpin', 'alp_lesson', 'alp_lesson_curate', 'alp_skill', 'alp_issue', 'alp_task', 'alp_schedule'].includes(params.tool) ||
|
|
2361
2737
|
params.namespace != null ||
|
|
2362
2738
|
typeof params.callId !== 'string'
|
|
2363
2739
|
) {
|
|
@@ -2370,12 +2746,16 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2370
2746
|
if (cached) return cached;
|
|
2371
2747
|
|
|
2372
2748
|
const args = params.arguments;
|
|
2749
|
+
// Every transport's arguments, before any tool walks them: the Codex, ACP and Antigravity paths have no schema of their own.
|
|
2750
|
+
const oversized = inputLimitError(args, TOOL_INPUT, `${params.tool} input`);
|
|
2751
|
+
if (oversized) return toolResult(false, { error: oversized });
|
|
2373
2752
|
// The supervisor only reads the board and tasks, and writes to main.
|
|
2374
2753
|
if (session.role === 'supervisor' && !['alp_send', 'alp_board', 'alp_task'].includes(params.tool)) return toolResult(false, { error: 'The supervisor only uses alp_send, alp_board and alp_task' });
|
|
2375
|
-
if (
|
|
2754
|
+
if (['alp_lesson', 'alp_lesson_curate', 'alp_skill'].includes(params.tool) && !supervises(session)) return toolResult(false, { error: 'Only a supervised main records lessons and skills' });
|
|
2376
2755
|
if (params.tool === 'alp_issue' && (session.parent || session.mapping.agent.name !== mainOf(session.mapping))) return toolResult(false, { error: 'Only main files issues; report the problem to your requester' });
|
|
2377
2756
|
const work =
|
|
2378
2757
|
params.tool === 'alp_lesson' ? lessonTool(sessionId, session, args)
|
|
2758
|
+
: params.tool === 'alp_lesson_curate' ? lessonCurateTool(sessionId, session, args)
|
|
2379
2759
|
: params.tool === 'alp_skill' ? skillTool(sessionId, session, args)
|
|
2380
2760
|
: params.tool === 'alp_issue' ? issueTool(sessionId, session, args)
|
|
2381
2761
|
: params.tool === 'alp_schedule' ? scheduleTool(sessionId, session, args)
|
|
@@ -2387,6 +2767,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2387
2767
|
: params.tool === 'alp_board' ? boardTool(session, args)
|
|
2388
2768
|
: params.tool === 'alp_unpin' ? unpinTool(sessionId, session, args)
|
|
2389
2769
|
: params.tool === 'alp_recall' ? recallTool(sessionId, session, args)
|
|
2770
|
+
: params.tool === 'alp_resolve' ? resolveTool(sessionId, session, args)
|
|
2390
2771
|
: params.tool === 'alp_verify' ? verifyTool(sessionId, session, args)
|
|
2391
2772
|
: params.tool === 'alp_cancel' ? cancelTool(sessionId, session, args)
|
|
2392
2773
|
: params.tool === 'alp_merge' || params.tool === 'alp_discard' ? worktreeTool(sessionId, session, args, params.tool === 'alp_merge' ? 'merge' : 'discard')
|
|
@@ -2567,11 +2948,147 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2567
2948
|
|
|
2568
2949
|
/** Ordinary questions end with their turn; issue approvals survive until decision or session cancellation. */
|
|
2569
2950
|
function cancelQuestions(sessionId: string, turnOnly = false) {
|
|
2570
|
-
for (const { question, settle, persistent } of [...userQuestions.values()]) {
|
|
2951
|
+
for (const { question, settle, persistent, gate } of [...userQuestions.values()]) {
|
|
2952
|
+
// A gate card ends only with its gate or its session; syncGates shows it again on the next main.
|
|
2953
|
+
if (gate && turnOnly) continue;
|
|
2571
2954
|
if (question.sessionId === sessionId && (!turnOnly || !persistent)) settle('canceled', undefined, undefined, toolResult(false, { error: 'Turn ended' }));
|
|
2572
2955
|
}
|
|
2573
2956
|
}
|
|
2574
2957
|
|
|
2958
|
+
// Human gates (t-ccac): .alp/tasks stays the source of truth. Each open human gate of a project
|
|
2959
|
+
// shows as a card on its live main root session, without a timeout and outside the one-question
|
|
2960
|
+
// limit; syncGates rebuilds the cards from the files (on start, attach, a gate change and a timer,
|
|
2961
|
+
// since the CLI and Paseo's local panel write the files without alpd) and tells main of every
|
|
2962
|
+
// decision once: markGateNotified marks it under the task lock, so card, panel and CLI racing on
|
|
2963
|
+
// one gate send one mail. With no live main, the decision waits for the project's next main.
|
|
2964
|
+
const gateSyncs = new Map<string, Promise<void>>();
|
|
2965
|
+
const gateCardId = (taskId: string, gateId: string) => `gate-${taskId}-${gateId}`;
|
|
2966
|
+
|
|
2967
|
+
/** The project's live main root session, if any. */
|
|
2968
|
+
function mainSessionOf(projectRoot: string) {
|
|
2969
|
+
for (const [id, session] of sessions) {
|
|
2970
|
+
if (session.closed || session.parent || session.role === 'supervisor' || !session.threadId) continue;
|
|
2971
|
+
if (session.mapping.agent.name !== mainOf(session.mapping) || path.resolve(session.mapping.agent.projectRoot) !== projectRoot) continue;
|
|
2972
|
+
return { id, session };
|
|
2973
|
+
}
|
|
2974
|
+
return undefined;
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
function syncGates(projectRoot: string): Promise<void> {
|
|
2978
|
+
const root = path.resolve(projectRoot);
|
|
2979
|
+
const previous = gateSyncs.get(root) ?? Promise.resolve();
|
|
2980
|
+
const next = previous.then(() => syncGatesNow(root)).catch(error => { runLog(mainSessionOf(root)?.id ?? root, { event: 'gate.sync.failed', projectRoot: root, error: errorData(error).message }); });
|
|
2981
|
+
gateSyncs.set(root, next);
|
|
2982
|
+
void next.finally(() => { if (gateSyncs.get(root) === next) gateSyncs.delete(root); });
|
|
2983
|
+
return next;
|
|
2984
|
+
}
|
|
2985
|
+
|
|
2986
|
+
async function syncGatesNow(projectRoot: string) {
|
|
2987
|
+
if (closed) return;
|
|
2988
|
+
const { tasks } = await loadTasks(projectRoot);
|
|
2989
|
+
const main = mainSessionOf(projectRoot);
|
|
2990
|
+
// The user's decisions, to main once each; without a live main they wait for the next one.
|
|
2991
|
+
if (main) for (const { task, gate, decision, record } of gateDecisions(tasks)) {
|
|
2992
|
+
if (!await markGateNotified(projectRoot, task.id, gate.id, decision)) continue;
|
|
2993
|
+
const choice = decision === 'approved' ? (record as { choice?: string }).choice : undefined;
|
|
2994
|
+
const words = decision === 'approved'
|
|
2995
|
+
? `The user approved human gate ${gate.id} of ${task.id} in ${record.channel}${choice ? `, choosing "${choice}"` : ''}${(record as { note?: string }).note ? `: ${(record as { note?: string }).note}` : ''}.`
|
|
2996
|
+
: `The user rejected human gate ${gate.id} of ${task.id} in ${record.channel}${(record as { reason?: string }).reason ? `: ${(record as { reason?: string }).reason}` : ''}. The gate stays open.`;
|
|
2997
|
+
post(main.id, { kind: 'result', from: 'ALP', assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words} Task: ${task.title}` });
|
|
2998
|
+
runLog(main.id, { event: 'gate.decision', projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record.channel, ...(choice ? { choice } : {}) });
|
|
2999
|
+
}
|
|
3000
|
+
// A card for each open human gate the user has not rejected; a rejected one stays open for main to follow up.
|
|
3001
|
+
const wanted = new Map<string, { task: Task; gate: Task['gates'][number] }>();
|
|
3002
|
+
for (const task of tasks) {
|
|
3003
|
+
if (task.status === 'closed') continue;
|
|
3004
|
+
for (const gate of task.gates ?? []) if (gate.kind === 'human' && !gate.resolved && !gate.rejected) wanted.set(gateCardId(task.id, gate.id), { task, gate });
|
|
3005
|
+
}
|
|
3006
|
+
for (const [id, pending] of [...userQuestions]) {
|
|
3007
|
+
if (pending.question.gate?.projectRoot !== projectRoot) continue;
|
|
3008
|
+
const want = wanted.get(id);
|
|
3009
|
+
if (!want || !main || pending.question.sessionId !== main.id) {
|
|
3010
|
+
const task = tasks.find(entry => entry.id === pending.question.gate!.taskId);
|
|
3011
|
+
const gate = task?.gates.find(entry => entry.id === pending.question.gate!.gateId);
|
|
3012
|
+
pending.settle(gate?.resolved ? 'answered' : gate?.rejected ? 'dismissed' : 'canceled', gate?.resolved?.choice, gate?.rejected?.reason);
|
|
3013
|
+
} else if (pending.gate) pending.gate.rev = want.task.rev;
|
|
3014
|
+
}
|
|
3015
|
+
if (!main) return;
|
|
3016
|
+
for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
|
|
3017
|
+
}
|
|
3018
|
+
|
|
3019
|
+
/** The CLI and Paseo's local Tasks panel write gates without alpd: a timer reads them while a main is live. */
|
|
3020
|
+
let gateWatch: NodeJS.Timeout | undefined;
|
|
3021
|
+
function startGateWatch() {
|
|
3022
|
+
if (gateWatch || options.gateSyncMs === 0) return;
|
|
3023
|
+
gateWatch = setInterval(() => {
|
|
3024
|
+
const roots = new Set([...sessions.values()].filter(session => !session.closed && !session.parent && session.role !== 'supervisor' && session.mapping.agent.name === mainOf(session.mapping)).map(session => path.resolve(session.mapping.agent.projectRoot)));
|
|
3025
|
+
for (const root of roots) void syncGates(root);
|
|
3026
|
+
if (!roots.size) { clearInterval(gateWatch); gateWatch = undefined; }
|
|
3027
|
+
}, options.gateSyncMs ?? 5_000);
|
|
3028
|
+
gateWatch.unref?.();
|
|
3029
|
+
}
|
|
3030
|
+
|
|
3031
|
+
function showGateCard(sessionId: string, session: Session, projectRoot: string, task: Task, gate: Task['gates'][number]) {
|
|
3032
|
+
const say = wordsFor(session);
|
|
3033
|
+
const vietnamese = say.approve === words('vi').approve;
|
|
3034
|
+
const question: UserQuestion = {
|
|
3035
|
+
id: gateCardId(task.id, gate.id),
|
|
3036
|
+
sessionId,
|
|
3037
|
+
rootId: rootOf(sessionId),
|
|
3038
|
+
agent: 'ALP',
|
|
3039
|
+
body: `${vietnamese ? `Cổng phê duyệt ${gate.id} của ${task.id}` : `Approval gate ${gate.id} of ${task.id}`} (${task.title}):\n${gate.note ?? ''}`,
|
|
3040
|
+
// Options approve; Reject (added after them unless one of them is that word) keeps the gate open.
|
|
3041
|
+
options: gate.options?.length ? (gate.options.includes(say.reject) ? gate.options : [...gate.options, say.reject]) : [say.approve, say.reject],
|
|
3042
|
+
askedAt: gate.at ?? new Date().toISOString(),
|
|
3043
|
+
gate: { projectRoot, taskId: task.id, gateId: gate.id },
|
|
3044
|
+
};
|
|
3045
|
+
const card = { rev: task.rev, deciding: false };
|
|
3046
|
+
const settle = (outcome: 'answered' | 'dismissed' | 'timeout' | 'canceled', answer?: string) => {
|
|
3047
|
+
if (userQuestions.get(question.id)?.question !== question) return;
|
|
3048
|
+
userQuestions.delete(question.id);
|
|
3049
|
+
emit(sessionId, { type: 'question.resolved', questionId: question.id, outcome, ...(answer !== undefined ? { answer } : {}) });
|
|
3050
|
+
};
|
|
3051
|
+
userQuestions.set(question.id, { question, settle, persistent: true, gate: Object.assign(card, { decide: (reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }) => decideGate(projectRoot, question, card, reply, gate.options?.length ? gate.options : undefined) }) });
|
|
3052
|
+
emit(sessionId, { type: 'question', question });
|
|
3053
|
+
runLog(rootOf(sessionId), { event: 'gate.card', questionId: question.id, taskId: task.id, gateId: gate.id });
|
|
3054
|
+
}
|
|
3055
|
+
|
|
3056
|
+
/**
|
|
3057
|
+
* The user answered a gate card: an option approves (with the default Approve/Reject, Reject or
|
|
3058
|
+
* other words reject), dismissing rejects. The card's task rev guards the write; a stale rev is
|
|
3059
|
+
* read again and retried only while the gate is still open and undecided, so a decision another
|
|
3060
|
+
* channel made first is never applied or mailed twice.
|
|
3061
|
+
*/
|
|
3062
|
+
async function decideGate(projectRoot: string, question: UserQuestion, card: { rev: number; deciding: boolean }, reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }, choices?: string[]) {
|
|
3063
|
+
const defaults = !choices;
|
|
3064
|
+
if (card.deciding) return;
|
|
3065
|
+
card.deciding = true;
|
|
3066
|
+
const { taskId, gateId } = question.gate!;
|
|
3067
|
+
const channel = reply.channel ?? 'web';
|
|
3068
|
+
const text = reply.text?.trim();
|
|
3069
|
+
const approve = !reply.dismiss && !!text && (defaults ? APPROVALS.includes(text.toLowerCase()) : choices.includes(text));
|
|
3070
|
+
const rejectReason = reply.dismiss ? reply.reason : text && CHOICES_REJECT.includes(text.toLowerCase()) ? undefined : text;
|
|
3071
|
+
const write = (ifRev: number) => approve
|
|
3072
|
+
? resolveGate(projectRoot, taskId, gateId, { by: 'user', ifRev, channel, ...(defaults ? {} : { choice: text }) })
|
|
3073
|
+
: rejectGate(projectRoot, taskId, gateId, { by: 'user', ifRev, channel, ...(rejectReason ? { reason: rejectReason.slice(0, 2000) } : {}) });
|
|
3074
|
+
try {
|
|
3075
|
+
try { await write(card.rev); }
|
|
3076
|
+
catch (error: any) {
|
|
3077
|
+
if (error?.code !== 'TASK_CHANGED') throw error;
|
|
3078
|
+
const current = (await loadTasks(projectRoot)).tasks.find(entry => entry.id === taskId);
|
|
3079
|
+
const gate = current?.gates.find(entry => entry.id === gateId);
|
|
3080
|
+
if (!current || current.status === 'closed' || !gate || gate.resolved || gate.rejected) return;
|
|
3081
|
+
await write(current.rev);
|
|
3082
|
+
}
|
|
3083
|
+
} catch (error) {
|
|
3084
|
+
// Already clear, or the task is gone: the other channel won; the sync below settles the card.
|
|
3085
|
+
runLog(question.rootId, { event: 'gate.answer.failed', questionId: question.id, error: errorData(error).message });
|
|
3086
|
+
} finally {
|
|
3087
|
+
card.deciding = false;
|
|
3088
|
+
await syncGates(projectRoot);
|
|
3089
|
+
}
|
|
3090
|
+
}
|
|
3091
|
+
|
|
2575
3092
|
function askTool(sessionId: string, session: Session, args: unknown) {
|
|
2576
3093
|
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
2577
3094
|
const assignment = parent?.assignments.get(sessionId);
|
|
@@ -2583,7 +3100,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2583
3100
|
if (args.options !== undefined && (to !== 'user' || !Array.isArray(args.options) || args.options.length > 10 || !args.options.every((option: unknown) => typeof option === 'string' && option.trim() && option.length <= 200))) {
|
|
2584
3101
|
return Promise.resolve(toolResult(false, { error: 'options are up to 10 short answers, for questions to the user' }));
|
|
2585
3102
|
}
|
|
2586
|
-
if (assignment?.ask || [...userQuestions.values()].some(pending => pending.question.sessionId === sessionId)) {
|
|
3103
|
+
if (assignment?.ask || [...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) {
|
|
2587
3104
|
return Promise.resolve(toolResult(false, { error: 'A question is already waiting for an answer' }));
|
|
2588
3105
|
}
|
|
2589
3106
|
// Only main talks to the user, unless the user has written to this assignment first.
|
|
@@ -3117,6 +3634,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3117
3634
|
if (assignment) assignmentSessions.set(assignment, session);
|
|
3118
3635
|
// Pending until its thread exists: mail posted meanwhile waits for it, as in a restart.
|
|
3119
3636
|
const finishPending = beginPending(session);
|
|
3637
|
+
const opening: { failure?: unknown } = {};
|
|
3638
|
+
openings.set(session, opening);
|
|
3639
|
+
/** A process failure during the open fails it: the step that saw it settle need not have failed. */
|
|
3640
|
+
const failedMeanwhile = () => { if (opening.failure !== undefined) throw opening.failure; };
|
|
3120
3641
|
|
|
3121
3642
|
sessions.set(
|
|
3122
3643
|
sessionId,
|
|
@@ -3127,6 +3648,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3127
3648
|
|
|
3128
3649
|
try {
|
|
3129
3650
|
await runtime.initialize();
|
|
3651
|
+
failedMeanwhile();
|
|
3130
3652
|
|
|
3131
3653
|
if (session.closed || sessions.get(sessionId) !== session) {
|
|
3132
3654
|
throw new Error(
|
|
@@ -3180,6 +3702,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3180
3702
|
|
|
3181
3703
|
session.threadId =
|
|
3182
3704
|
result.thread.id;
|
|
3705
|
+
failedMeanwhile();
|
|
3183
3706
|
|
|
3184
3707
|
if (session.closed || sessions.get(sessionId) !== session) {
|
|
3185
3708
|
throw new Error(
|
|
@@ -3187,6 +3710,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3187
3710
|
);
|
|
3188
3711
|
}
|
|
3189
3712
|
|
|
3713
|
+
// Open from here on: a process failure is the live session's (wire's onFailure).
|
|
3714
|
+
openings.delete(session);
|
|
3190
3715
|
session.buffered = [];
|
|
3191
3716
|
finishPending();
|
|
3192
3717
|
|
|
@@ -3200,6 +3725,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3200
3725
|
thinking: result.reasoningEffort ?? mapping.thinking,
|
|
3201
3726
|
},
|
|
3202
3727
|
});
|
|
3728
|
+
// A main root shows the project's open human gates and gets decisions made while none was live.
|
|
3729
|
+
if (!session.parent && session.role !== 'supervisor' && mapping.agent.name === mainOf(mapping)) { void syncGates(mapping.agent.projectRoot); startGateWatch(); }
|
|
3203
3730
|
|
|
3204
3731
|
if (
|
|
3205
3732
|
history === 'replay'
|
|
@@ -3226,8 +3753,12 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3226
3753
|
return snapshot(sessionId, session);
|
|
3227
3754
|
} catch (error) {
|
|
3228
3755
|
log.error(`${session.mapping.agent.name} could not start its ${session.runtimeKind} session`, { code: 'ALP_PROVIDER_START_FAILED', sessionId, rootId: rootOf(sessionId), agent: session.mapping.agent.name, provider: session.runtimeKind, error });
|
|
3229
|
-
//
|
|
3230
|
-
|
|
3756
|
+
// A process failure while the open ran is reported now that the open is through, once.
|
|
3757
|
+
const failed = openings.get(session);
|
|
3758
|
+
openings.delete(session);
|
|
3759
|
+
if (failed?.failure !== undefined) failSession(sessionId, session, failed.failure);
|
|
3760
|
+
// Share the retirement the failure started, and never resolve the id to a
|
|
3761
|
+
// replacement record when this open finishes late.
|
|
3231
3762
|
const cleanup = closeSession(sessionId, session, false);
|
|
3232
3763
|
finishPending();
|
|
3233
3764
|
await cleanup;
|
|
@@ -3258,6 +3789,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3258
3789
|
transport.onFailure((error) => {
|
|
3259
3790
|
// A transport ALP already replaced reports nothing.
|
|
3260
3791
|
if (session.closed || session.runtime !== transport || sessions.get(sessionId) !== session) return;
|
|
3792
|
+
// The first open still runs: it fails with this, and reports it when it is through.
|
|
3793
|
+
const opening = openings.get(session);
|
|
3794
|
+
if (opening) { opening.failure ??= error; return; }
|
|
3261
3795
|
if (revivable(session)) void revive(sessionId, session, error);
|
|
3262
3796
|
else failSession(sessionId, session, error);
|
|
3263
3797
|
});
|
|
@@ -3378,11 +3912,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3378
3912
|
if (session.pending) return 'The session is still opening or restarting';
|
|
3379
3913
|
if (session.active) return 'A turn is running';
|
|
3380
3914
|
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';
|
|
3915
|
+
if ([...userQuestions.values()].some(pending => pending.question.rootId === sessionId && !pending.gate)) return 'A question to the user waits for an answer';
|
|
3382
3916
|
// 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
|
|
3917
|
+
if ((hasActiveMail(session) || session.wakeHeld) && !session.lifecycleHolds) return MAIL_WAITS;
|
|
3384
3918
|
if (session.parked || session.parkReason) return 'The session is parked';
|
|
3385
|
-
if (reviewing(session)) return
|
|
3919
|
+
if (reviewing(session)) return REVIEWING;
|
|
3386
3920
|
return undefined;
|
|
3387
3921
|
}
|
|
3388
3922
|
|
|
@@ -3582,7 +4116,6 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3582
4116
|
// team or effort change never raises the mode the session runs with.
|
|
3583
4117
|
if (changes.mode !== undefined && mapping.mode !== changes.mode) return refused('permission_escalation', READ_ONLY_AGENTS.includes(agent) ? 'Advisors and the supervisor must remain read-only' : `Permission profile ${mapping.permissions?.name ?? ''} allows at most ${mapping.permissions?.base ?? mapping.mode}`.replace('profile allows', 'profile allows'));
|
|
3584
4118
|
if (changes.mode === undefined && !withinMode(mapping.mode, session.mapping.mode)) return refused('permission_escalation', `The change would run the session in ${mapping.mode}, beyond its ${session.mapping.mode}`);
|
|
3585
|
-
if (runtimeKind === 'antigravity' && mapping.mode !== session.mapping.mode) return refused('runtime_unsupported', 'Antigravity sessions keep their mode');
|
|
3586
4119
|
const before = executablesOf(session.mapping);
|
|
3587
4120
|
const added = [...executablesOf(mapping)].filter(entry => !before.has(entry));
|
|
3588
4121
|
if (added.length) return refused('permission_escalation', `The change would give the session commands it did not run (${added.map(entry => entry.split(':').slice(0, 2).join(' ')).join(', ')}); start a new session for it`);
|
|
@@ -3829,7 +4362,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3829
4362
|
if (assignment.lease && leases.get(assignment.lease)?.assignment === id) leases.delete(assignment.lease);
|
|
3830
4363
|
if (roleOf(parent.mapping, entry.agent) === 'peer') { const root = sessions.get(entry.rootId); if (root) root.peerCount--; }
|
|
3831
4364
|
if (assignment.copy) await removeCopy(assignment.copy).catch(() => {});
|
|
3832
|
-
|
|
4365
|
+
// The worktree predates this recovery and may hold uncommitted work: it stays (t-eae4).
|
|
3833
4366
|
};
|
|
3834
4367
|
try {
|
|
3835
4368
|
if (entry.lease) {
|
|
@@ -3837,7 +4370,14 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3837
4370
|
if (holder && !lineage(entry.parentId).includes(holder.assignment)) throw new Error(`${holder.agent} writes ${entry.lease} now`);
|
|
3838
4371
|
if (!holder) { assignment.lease = entry.lease; leases.set(entry.lease, { assignment: id, agent: entry.agent }); }
|
|
3839
4372
|
}
|
|
3840
|
-
if (entry.worktree)
|
|
4373
|
+
if (entry.worktree) {
|
|
4374
|
+
const { preserved, ...worktree } = await reattachWorktree(entry.worktree);
|
|
4375
|
+
assignment.worktree = worktree;
|
|
4376
|
+
if (preserved) {
|
|
4377
|
+
runLog(entry.rootId, { event: 'worktree.preserved', assignmentId: id, branch: worktree.branch, preserved });
|
|
4378
|
+
post(entry.parentId, { kind: 'note', from: entry.agent, assignment: id, passive: true, body: `Reopening ${id}: its worktree ${worktree.path} had no valid git metadata after the restart, so it was moved aside unchanged to ${preserved} and ${worktree.branch} was checked out again. Recover any uncommitted work from ${preserved}.` });
|
|
4379
|
+
}
|
|
4380
|
+
}
|
|
3841
4381
|
if (entry.copyOf) {
|
|
3842
4382
|
assignment.copy = await createCopy(entry.copyOf, copyRoot, id);
|
|
3843
4383
|
spec = { ...spec, workdir: assignment.copy.workdir };
|
|
@@ -3878,6 +4418,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3878
4418
|
assignmentId: entry.assignmentId,
|
|
3879
4419
|
checkout: entry.worktree?.checkout ?? entry.lease ?? entry.spec.writeRoot ?? entry.spec.workdir ?? entry.project,
|
|
3880
4420
|
...(entry.worktree ? { worktree: entry.worktree.path } : {}),
|
|
4421
|
+
...(!entry.worktree ? { result: {
|
|
4422
|
+
agent: entry.agent, status: 'abandoned', finishedAt: new Date().toISOString(), project: entry.project, requesters: sessions.has(entry.parentId) ? lineage(entry.parentId) : [entry.parentId],
|
|
4423
|
+
...(entry.taskId ? { taskId: entry.taskId } : {}), brief: cut(entry.brief ?? '', RESULT_EVIDENCE_CHARS), summary: cut(JSON.stringify({ reason }), RESULT_EVIDENCE_CHARS),
|
|
4424
|
+
} } : {}),
|
|
3881
4425
|
});
|
|
3882
4426
|
await inFlight.remove(entry.assignmentId);
|
|
3883
4427
|
const parent = sessions.get(entry.parentId);
|
|
@@ -3994,8 +4538,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3994
4538
|
}
|
|
3995
4539
|
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
3996
4540
|
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 }) });
|
|
4541
|
+
if (session.runtimeKind === 'claude' || session.runtimeKind === 'antigravity') await session.runtime.request('session/configure', { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
|
|
3999
4542
|
session.mapping.mode = mode;
|
|
4000
4543
|
session.spec = { ...session.spec, mode };
|
|
4001
4544
|
const updated = snapshot(sessionId, session);
|
|
@@ -4056,8 +4599,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4056
4599
|
}
|
|
4057
4600
|
|
|
4058
4601
|
// Shared by ordinary prompts and the scheduler's queue-scoped sender.
|
|
4059
|
-
async function promptSession(sessionId: string, input: PromptInput): Promise<void> {
|
|
4602
|
+
async function promptSession(sessionId: string, input: PromptInput, flushing = false): Promise<void> {
|
|
4060
4603
|
const session = sessions.get(sessionId);
|
|
4604
|
+
// While main writes its checkpoint and compacts, the user's words wait for the compaction's end (t-0e56).
|
|
4605
|
+
if (!flushing && session && !session.parent && (session.compacting || session.compactBuffer?.length)) {
|
|
4606
|
+
if (!session.seen.has(input.clientMessageId) && !session.compactBuffer?.some(held => held.clientMessageId === input.clientMessageId)) (session.compactBuffer ??= []).push(input);
|
|
4607
|
+
return;
|
|
4608
|
+
}
|
|
4061
4609
|
const parked = session?.parked;
|
|
4062
4610
|
try {
|
|
4063
4611
|
const prompt = session?.active && session.resumedTurn === session.active && input.delivery === 'auto'
|
|
@@ -4166,6 +4714,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4166
4714
|
) {
|
|
4167
4715
|
session.text.clear();
|
|
4168
4716
|
session.toolCalls.clear();
|
|
4717
|
+
if (!/^alp-wake-compact-/.test(prompt.clientMessageId)) session.compactCooling = false;
|
|
4169
4718
|
session.supervisorWake = !!wake?.length && wake.every(event => event.defer);
|
|
4170
4719
|
|
|
4171
4720
|
// A wake continues the same assignment: keep its handoff and limits.
|
|
@@ -4180,6 +4729,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4180
4729
|
|
|
4181
4730
|
try {
|
|
4182
4731
|
const orchestration = session.runtime.orchestrationContext ? await session.runtime.orchestrationContext().catch(() => ({ available: false })) : { available: false };
|
|
4732
|
+
// Each turn's own model list keeps the live catalog current (t-e5ee).
|
|
4733
|
+
feedCatalog(orchestration);
|
|
4183
4734
|
// Main starts each turn knowing what waits for its acceptance and what is ready.
|
|
4184
4735
|
const tasks = prompt.delivery !== 'steer' && !session.parent && session.mapping.agent.name === mainOf(session.mapping)
|
|
4185
4736
|
? await releaseOrphansOnce(session.mapping.agent.projectRoot, sessionId).then(() => checkGatesOften(session.mapping.agent.projectRoot)).then(() => loadTasks(session.mapping.agent.projectRoot)).then(({ tasks, errors }) => taskDigest(tasks, errors), () => '')
|
|
@@ -4274,6 +4825,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4274
4825
|
},
|
|
4275
4826
|
});
|
|
4276
4827
|
if (origin === 'user' && !session.parent) session.userWaiting ??= Date.now();
|
|
4828
|
+
if (origin === 'user' && !session.parent && text) session.lastUserText = clip(text, 16_000);
|
|
4277
4829
|
if (session.supervisor && origin === 'user') session.journal.push(stamp(`user ${prompt.delivery === 'steer' ? 'steered' : 'asked'} ${session.mapping.agent.name}: ${clip(text, 1500)}`));
|
|
4278
4830
|
// The steer reaches the model once its waiting tool returns; return it now, not when the work ends.
|
|
4279
4831
|
if (prompt.delivery === 'steer' && origin === 'user' && !session.parent) { releaseWaiters(session); releaseQuestions(sessionId); }
|
|
@@ -4318,12 +4870,12 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4318
4870
|
// Threads past their recall time go when the host starts, and after each assignment.
|
|
4319
4871
|
if (options.recallFile) void forgetExpired();
|
|
4320
4872
|
|
|
4321
|
-
|
|
4873
|
+
const api = {
|
|
4322
4874
|
registerWorkspace: directory => enqueue(async () => {
|
|
4323
4875
|
try { await assignmentResults.register(await realpath(directory)); }
|
|
4324
4876
|
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot register workspace result ownership'); }
|
|
4325
4877
|
}),
|
|
4326
|
-
withWorkspaceMutation: <T>(directory: string, run: () => Promise<T
|
|
4878
|
+
withWorkspaceMutation: <T>(directory: string, run: () => Promise<T>, adoption?: typeof ADOPTION): Promise<T> => {
|
|
4327
4879
|
// Reserve before enqueue/await: in-flight admission causes refusal, future admission cannot start.
|
|
4328
4880
|
if (workspaceMutation || admitting) return Promise.reject(new WorkspaceMutationError('workspace_busy', 'A session or assignment is opening; retry after it finishes'));
|
|
4329
4881
|
workspaceMutation = true;
|
|
@@ -4332,7 +4884,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4332
4884
|
let resultLedger: Awaited<ReturnType<typeof assignmentResults.inspect>>;
|
|
4333
4885
|
try { resultLedger = await assignmentResults.inspect(); }
|
|
4334
4886
|
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot inspect permanent assignment results'); }
|
|
4335
|
-
|
|
4887
|
+
// Only adoptWorkspace passes ADOPTION, to certify an old checkout after every check below.
|
|
4888
|
+
if (!resultLedger!.workspaces.includes(target) && adoption !== ADOPTION) refuseMutation('workspace_assignment_result', 'Workspace predates authoritative assignment tracking; an audited migration is required before removal');
|
|
4336
4889
|
const canonical = (value: string): string => {
|
|
4337
4890
|
try { return realpathSync(value); }
|
|
4338
4891
|
catch (error) {
|
|
@@ -4353,7 +4906,14 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4353
4906
|
};
|
|
4354
4907
|
return contains(target, owner) || contains(owner, target);
|
|
4355
4908
|
};
|
|
4356
|
-
|
|
4909
|
+
// A handled result no longer holds its paths; its evidence stays in the ledger until archived.
|
|
4910
|
+
for (const entry of resultLedger!.results) if (!entry.handled && (overlaps(entry.checkout) || overlaps(entry.worktree))) refuseMutation('workspace_assignment_result', `Resolve permanent assignment result ${entry.assignmentId} before removing ${directory}`);
|
|
4911
|
+
// A recall entry outlives the result it describes by up to its own 14 days; once the result is handled, it holds nothing.
|
|
4912
|
+
const resolved = async (assignmentId: string) => {
|
|
4913
|
+
if (resultLedger!.results.some(owner => owner.assignmentId === assignmentId && owner.handled)) return true;
|
|
4914
|
+
try { return !!(await assignmentResults.archived(assignmentId)); }
|
|
4915
|
+
catch { return refuseMutation('workspace_assignment_result', 'Cannot inspect the assignment result archive; repair it before removing the workspace'); }
|
|
4916
|
+
};
|
|
4357
4917
|
for (const [project, pins] of loadedBoards) for (const pin of pins) {
|
|
4358
4918
|
if (pin.kind === 'claim' && live(pin) && pin.paths?.some(value => overlaps(path.resolve(project, value)))) refuseMutation('workspace_claimed', `Release claim ${pin.id} before removing ${directory}`);
|
|
4359
4919
|
}
|
|
@@ -4382,13 +4942,20 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4382
4942
|
if (entry.worktree !== undefined && (!entry.worktree || !['path', 'checkout', 'workdir'].every(key => typeof entry.worktree[key] === 'string'))) refuseMutation('workspace_assignment_result', `Invalid worktree result in ${file}`);
|
|
4383
4943
|
if (entry.shared !== undefined && (!entry.shared || typeof entry.shared !== 'object' || Array.isArray(entry.shared))) refuseMutation('workspace_assignment_result', `Invalid shared result in ${file}`);
|
|
4384
4944
|
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}`);
|
|
4945
|
+
else if ((overlaps(entry.cwd) || overlaps(entry.shared?.writeRoot)) && !(await resolved(entry.assignmentId))) refuseMutation('workspace_assignment_result', `Preserve retained assignment ${entry.assignmentId} before removing ${directory}`);
|
|
4386
4946
|
}
|
|
4387
4947
|
}
|
|
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}`);
|
|
4948
|
+
for (const entry of await recalls.all()) if ((overlaps(entry.cwd) || overlaps(entry.shared?.writeRoot)) && !(await resolved(entry.assignmentId))) refuseMutation('workspace_assignment_result', `Preserve retained assignment ${entry.assignmentId} before removing ${directory}`);
|
|
4389
4949
|
return await run();
|
|
4390
4950
|
}).finally(() => { workspaceMutation = false; });
|
|
4391
4951
|
},
|
|
4952
|
+
adoptWorkspace: (directory: string, verify: (canonical: string) => Promise<void>): Promise<void> => api.withWorkspaceMutation(directory, async () => {
|
|
4953
|
+
// A path through a symlink names whatever the link points at today; adopt only the canonical path.
|
|
4954
|
+
if (await realpath(directory) !== directory) refuseMutation('workspace_identity', `Adopt ${directory} by its canonical path`);
|
|
4955
|
+
await verify(directory);
|
|
4956
|
+
try { await assignmentResults.register(directory); }
|
|
4957
|
+
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot register workspace result ownership'); }
|
|
4958
|
+
}, ADOPTION),
|
|
4392
4959
|
bindSchedules(handler: ScheduleHandler | undefined) { scheduleHandler = handler; },
|
|
4393
4960
|
bindAttachments(reader: AttachmentReader | undefined) { attachmentReader = reader; },
|
|
4394
4961
|
takesAttachments(sessionId: string) {
|
|
@@ -4407,7 +4974,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4407
4974
|
const opened = await openSession(sessionId, spec, history, delegation);
|
|
4408
4975
|
const root = sessions.get(sessionId)!;
|
|
4409
4976
|
// Main starts its supervisor beside it, without delaying its own open.
|
|
4410
|
-
if (supervises(root))
|
|
4977
|
+
if (supervises(root)) {
|
|
4978
|
+
void enqueue(() => openSupervisor(sessionId));
|
|
4979
|
+
void ensureCurateSchedule(sessionId).catch(error => runLog(sessionId, { event: 'curate.schedule.failed', error: errorData(error).message }));
|
|
4980
|
+
}
|
|
4411
4981
|
return opened;
|
|
4412
4982
|
}),
|
|
4413
4983
|
|
|
@@ -4465,6 +5035,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4465
5035
|
rebind: (sessionId, binding) => enqueue(() => rebindSession(sessionId, binding)),
|
|
4466
5036
|
|
|
4467
5037
|
reload: sessionId => enqueue(() => reloadSession(sessionId)),
|
|
5038
|
+
compact: (sessionId: string) => requestCompact(sessionId),
|
|
4468
5039
|
|
|
4469
5040
|
previewConfigure: (sessionId, changes) => previewConfigureSession(sessionId, changes),
|
|
4470
5041
|
|
|
@@ -4522,7 +5093,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4522
5093
|
};
|
|
4523
5094
|
visit(rootId);
|
|
4524
5095
|
const questions = [...userQuestions.values()].map(pending => pending.question).filter(question => question.rootId === rootId);
|
|
4525
|
-
const asking = new Set(questions.map(question => question.sessionId));
|
|
5096
|
+
const asking = new Set(questions.filter(question => !question.gate).map(question => question.sessionId));
|
|
4526
5097
|
const ids = new Set(tree.map(([id]) => id));
|
|
4527
5098
|
return {
|
|
4528
5099
|
rootId,
|
|
@@ -4572,6 +5143,26 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4572
5143
|
},
|
|
4573
5144
|
|
|
4574
5145
|
pauses: () => pauseState(),
|
|
5146
|
+
|
|
5147
|
+
holdForDisk(reason) {
|
|
5148
|
+
// A pause of all ALP already holds the work; the user's stays theirs to lift.
|
|
5149
|
+
if (paused.all) return pauseState();
|
|
5150
|
+
pauseRuntime('all', { since: new Date().toISOString(), by: 'alpd', reason, cause: 'disk' }, true);
|
|
5151
|
+
notice('error', say => say.diskFull(reason));
|
|
5152
|
+
return pauseState();
|
|
5153
|
+
},
|
|
5154
|
+
|
|
5155
|
+
releaseDisk(by) {
|
|
5156
|
+
if (paused.all?.cause !== 'disk') return pauseState();
|
|
5157
|
+
resumeRuntime('all', by, true);
|
|
5158
|
+
return pauseState();
|
|
5159
|
+
},
|
|
5160
|
+
|
|
5161
|
+
diskHeld: () => paused.all?.cause === 'disk',
|
|
5162
|
+
|
|
5163
|
+
diskLow(free) {
|
|
5164
|
+
notice('warning', say => say.diskLow(free));
|
|
5165
|
+
},
|
|
4575
5166
|
async usage(refresh = false) {
|
|
4576
5167
|
const providers = await Promise.all((['codex', 'claude'] as const).map(kind => cachedUsage(kind, refresh)));
|
|
4577
5168
|
const state = pauseState();
|
|
@@ -4610,6 +5201,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4610
5201
|
};
|
|
4611
5202
|
},
|
|
4612
5203
|
|
|
5204
|
+
syncGates(projectRoot) {
|
|
5205
|
+
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) return Promise.reject(new Error('syncGates needs an absolute projectRoot'));
|
|
5206
|
+
return syncGates(projectRoot);
|
|
5207
|
+
},
|
|
5208
|
+
|
|
4613
5209
|
async board(projectRoot) {
|
|
4614
5210
|
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) throw new Error('board needs an absolute projectRoot');
|
|
4615
5211
|
return (await boardOf(path.resolve(projectRoot))).filter(live);
|
|
@@ -4631,6 +5227,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4631
5227
|
answer(questionId, reply) {
|
|
4632
5228
|
const pending = userQuestions.get(questionId);
|
|
4633
5229
|
if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
|
|
5230
|
+
if (pending.gate) {
|
|
5231
|
+
if (!reply.dismiss && (typeof reply.text !== 'string' || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error('An answer needs text');
|
|
5232
|
+
void pending.gate.decide(reply);
|
|
5233
|
+
return;
|
|
5234
|
+
}
|
|
4634
5235
|
if (reply.dismiss) {
|
|
4635
5236
|
pending.settle('dismissed', undefined, reply.reason);
|
|
4636
5237
|
return;
|
|
@@ -4673,6 +5274,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4673
5274
|
);
|
|
4674
5275
|
|
|
4675
5276
|
clearInterval(watchdog);
|
|
5277
|
+
if (gateWatch) clearInterval(gateWatch);
|
|
5278
|
+
await Promise.all(gateSyncs.values());
|
|
4676
5279
|
|
|
4677
5280
|
// Claims released by the closes above are written before the board is left.
|
|
4678
5281
|
await Promise.all(boards.values());
|
|
@@ -4687,5 +5290,6 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
4687
5290
|
|
|
4688
5291
|
listeners.clear();
|
|
4689
5292
|
},
|
|
4690
|
-
};
|
|
5293
|
+
} satisfies AlpRuntime;
|
|
5294
|
+
return api;
|
|
4691
5295
|
}
|