@anhlp/alp-runtime 0.0.0-beta.2 → 0.0.1-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp-transport.js +7 -36
- package/dist/antigravity-transport.d.ts +27 -2
- package/dist/antigravity-transport.js +104 -58
- package/dist/assignment-results.d.ts +55 -0
- package/dist/assignment-results.js +181 -0
- package/dist/attachments.d.ts +84 -0
- package/dist/attachments.js +213 -0
- package/dist/board-domain.js +2 -2
- package/dist/board.d.ts +6 -0
- package/dist/board.js +7 -0
- package/dist/catalog.d.ts +13 -0
- package/dist/catalog.js +11 -2
- package/dist/claude-transport.d.ts +80 -0
- package/dist/claude-transport.js +271 -23
- package/dist/compact.d.ts +29 -0
- package/dist/compact.js +49 -0
- package/dist/configure.d.ts +44 -0
- package/dist/configure.js +64 -0
- package/dist/contracts.d.ts +216 -7
- package/dist/contracts.js +11 -0
- package/dist/conversation.d.ts +45 -0
- package/dist/conversation.js +62 -0
- package/dist/index.d.ts +18 -5
- package/dist/index.js +48 -4
- package/dist/input-limits.d.ts +25 -0
- package/dist/input-limits.js +48 -0
- package/dist/language.d.ts +10 -0
- package/dist/language.js +26 -0
- package/dist/live.d.ts +2 -2
- package/dist/live.js +7 -2
- package/dist/mailbox.d.ts +2 -0
- package/dist/mailbox.js +3 -1
- package/dist/mcp-tools.d.ts +8 -0
- package/dist/mcp-tools.js +26 -0
- package/dist/model-catalog.d.ts +162 -0
- package/dist/model-catalog.js +338 -0
- package/dist/model-probes.d.ts +7 -0
- package/dist/model-probes.js +69 -0
- package/dist/providers.js +2 -0
- package/dist/recall.d.ts +2 -2
- package/dist/recall.js +4 -3
- package/dist/resolve.d.ts +2 -0
- package/dist/resolve.js +9 -5
- package/dist/runtime-context.d.ts +1 -1
- package/dist/runtime-context.js +1 -1
- package/dist/runtime.d.ts +9 -0
- package/dist/runtime.js +2078 -269
- package/dist/session-config.d.ts +378 -6
- package/dist/session-config.js +19 -15
- package/dist/session-state.d.ts +54 -7
- package/dist/skill-resources.d.ts +30 -0
- package/dist/skill-resources.js +55 -0
- package/dist/tool-detail.js +4 -1
- package/dist/tools.d.ts +154 -1
- package/dist/tools.js +99 -11
- package/dist/transport.js +3 -1
- package/dist/workspace.d.ts +31 -5
- package/dist/workspace.js +92 -11
- package/dist/worktree-domain.d.ts +2 -1
- package/dist/worktree-domain.js +4 -1
- package/dist/write-error.d.ts +2 -0
- package/dist/write-error.js +10 -0
- package/package.json +12 -4
- package/src/acp-transport.ts +10 -37
- package/src/antigravity-transport.ts +128 -55
- package/src/assignment-results.ts +154 -0
- package/src/attachments.ts +254 -0
- package/src/board-domain.ts +2 -2
- package/src/board.ts +7 -0
- package/src/catalog.ts +13 -2
- package/src/claude-transport.ts +333 -23
- package/src/compact.ts +62 -0
- package/src/configure.ts +93 -0
- package/src/contracts.ts +199 -8
- package/src/conversation.ts +81 -0
- package/src/index.ts +18 -5
- package/src/input-limits.ts +65 -0
- package/src/language.ts +28 -0
- package/src/live.ts +7 -3
- package/src/mailbox.ts +4 -1
- package/src/mcp-tools.ts +33 -0
- package/src/model-catalog.ts +316 -0
- package/src/model-probes.ts +58 -0
- package/src/providers.ts +3 -0
- package/src/recall.ts +4 -3
- package/src/resolve.ts +15 -7
- package/src/runtime-context.ts +2 -2
- package/src/runtime.ts +2253 -264
- package/src/session-config.ts +25 -14
- package/src/session-state.ts +39 -3
- package/src/skill-resources.ts +73 -0
- package/src/tool-detail.ts +4 -1
- package/src/tools.ts +97 -10
- package/src/transport.ts +3 -1
- package/src/workspace.ts +124 -18
- package/src/worktree-domain.ts +5 -1
- package/src/write-error.ts +4 -0
package/src/runtime.ts
CHANGED
|
@@ -1,61 +1,115 @@
|
|
|
1
|
+
import { createAssignmentResults, RESULT_OUTCOMES } from './assignment-results.js';
|
|
1
2
|
import { constants as fsConstants } from 'node:fs';
|
|
2
3
|
import type { Session, Assignment, Waiter } from './session-state.js';
|
|
3
4
|
import { errorData, plainObject, toolResult } from './tool-results.js';
|
|
5
|
+
import { inputLimitError, POUR_VARS, TOOL_INPUT, VAR_NAME } from './input-limits.js';
|
|
4
6
|
import { createLogger } from '@anhlp/alp-core/log';
|
|
5
7
|
import { PROMPT_IMAGES, base64Bytes } from '@anhlp/alp-protocol';
|
|
6
8
|
import { createBoardDomain } from './board-domain.js';
|
|
9
|
+
import { ATTACHMENT_ROUTES, STAGED_PATH, attachmentPart, createAttachmentStager, runtimeAttachment, stagingExposure, type AttachmentReader, type AttachmentRoute } from './attachments.js';
|
|
10
|
+
import type { RuntimeAttachment } from '@anhlp/alp-protocol/session';
|
|
7
11
|
import { createWorktreeDomain } from './worktree-domain.js';
|
|
8
|
-
import { type RuntimeTransport, type RuntimeOptions, type OpenOptions, type PromptContent, type PromptInput, type AlpRuntime, type SessionPreview, type RecoveryOutcome, type Pause, type PauseState, type RecallAnswer } from './contracts.js';
|
|
12
|
+
import { type RuntimeTransport, type RuntimeOptions, type OpenOptions, type PromptContent, type PromptInput, type AlpRuntime, type SessionPreview, type RecoveryOutcome, type Pause, type PauseState, type RecallAnswer, type ScheduleHandler, type BranchRequest, type NativeBinding, type ConfigurePreview, type ConfigureResult, type ConversationErrorReason, type RuntimeCommand, ConversationError } from './contracts.js';
|
|
13
|
+
import { claudeCut, codexForkEnd, codexForkRefusal, pendingChain, type ChainEntry } from './conversation.js';
|
|
9
14
|
export type { RuntimeTransport, RuntimeOptions, OpenOptions, PromptContent, PromptInput, AlpRuntime, SessionPreview, RecoveryOutcome, Pause, PauseState, RecallAnswer } from './contracts.js';
|
|
10
15
|
export { DEFAULT_TEAM } from './contracts.js';
|
|
11
16
|
import { verdictLine, parseHandoff, type Handoff } from './handoff.js';
|
|
12
|
-
import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, roleOf, taskActions, taskBrief, type TaskAction } from './tools.js';
|
|
17
|
+
import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, readOnlyMember, roleOf, taskActions, taskBrief, type TaskAction } from './tools.js';
|
|
13
18
|
import { nativeEnvironment, createTransport } from './providers.js';
|
|
14
19
|
import { nativeMode, codexApproval, profileEfforts, nativeSessionConfig } from './session-config.js';
|
|
15
20
|
import { createHash, randomUUID } from 'node:crypto';
|
|
16
|
-
import { readFileSync, realpathSync } from 'node:fs';
|
|
17
|
-
import { appendFile, mkdir, open, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
|
|
18
|
-
import {
|
|
21
|
+
import { readFileSync, realpathSync, watch as watchFiles, type FSWatcher } from 'node:fs';
|
|
22
|
+
import { appendFile, mkdir, open, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
|
|
23
|
+
import { checkFrontmatter, skillReferences, splitSkill } from '@anhlp/alp-core/skill-validate';
|
|
24
|
+
import { resourceUses } from './skill-resources.js';
|
|
25
|
+
import { moveFile, writeAtomic } from '@anhlp/alp-core/atomic';
|
|
19
26
|
import os from 'node:os';
|
|
20
27
|
import path from 'node:path';
|
|
21
28
|
import { resolveDelegation } from '@anhlp/alp-core/delegation';
|
|
22
|
-
import { discoverAgents } from '@anhlp/alp-core/resolver';
|
|
29
|
+
import { agentSources, builtinText, discoverAgents } from '@anhlp/alp-core/resolver';
|
|
23
30
|
|
|
24
31
|
import { acpDecision, acpWhat, type AcpPermission } from './acp-transport.js';
|
|
25
32
|
|
|
26
33
|
import { models, modes, thinkingOptionsFor, withinMode, writes } from './catalog.js';
|
|
34
|
+
import { feedCatalog } from './model-catalog.js';
|
|
27
35
|
import { runHook } from '@anhlp/alp-core/hook-run';
|
|
28
36
|
import { hookMatches } from '@anhlp/alp-core/hooks';
|
|
29
37
|
import { isTrusted, trustProject } from '@anhlp/alp-core/trust';
|
|
30
|
-
import { listTeams } from '@anhlp/alp-core/teams';
|
|
38
|
+
import { listTeams, teamOf } from '@anhlp/alp-core/teams';
|
|
39
|
+
import { CONFIGURABLE, changesOf, effectiveOf, executablesOf, nativeModelOf, offered, type ConfigureChange, type ConfigureChanges, type EffectiveConfig } from './configure.js';
|
|
31
40
|
import { anyModel, offers, profileModel, selectedProfile } from '@anhlp/alp-core/profiles';
|
|
32
|
-
import { LESSONS_FILE,
|
|
33
|
-
import { MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER, type MailEvent } from './mailbox.js';
|
|
41
|
+
import { LESSONS_FILE, resolveSession, skillDescription, type ResolvedSession, type RuntimeKind, type SessionSpec } from './resolve.js';
|
|
42
|
+
import { MAIL_BODY_CHARS, MAIL_HEADER, publicEvent, renderMail, takeBatch, USER, type MailEvent } from './mailbox.js';
|
|
34
43
|
import type { AlpEvent, AssignmentSnapshot, Envelope, SessionSnapshot, TurnOrigin, UserQuestion } from './events.js';
|
|
35
44
|
import { live, normalizePaths, overlapping, renderBoard, type Pin } from './board.js';
|
|
36
45
|
import { verifyConfig } from '@anhlp/alp-core/verify';
|
|
37
46
|
import { createLiveBook, type LiveEntry } from './live.js';
|
|
47
|
+
import { tell } from './write-error.js';
|
|
38
48
|
import { promptSafe } from '@anhlp/alp-core/promptsafe';
|
|
39
49
|
import { CHOICES, words, type Words } from './language.js';
|
|
40
50
|
import { OWN_START, sameProcessAlive } from './process-info.js';
|
|
41
51
|
import { createRecallBook, recallPrompt, RECALL_KEEP_MS, RECALL_QUESTION_CHARS, RECALL_TIMEOUT_MS, type RecallEntry } from './recall.js';
|
|
42
52
|
import { branchExists, checkoutFingerprint, checkoutKey, createCopy, createWorktree, reattachWorktree, removeCopy, removeWorktree } from './workspace.js';
|
|
43
|
-
import { claudeSandboxAvailable, SKILL_PLUGIN } from './claude-transport.js';
|
|
53
|
+
import { claudeSandboxAvailable, nativeCommandRefusal, SKILL_PLUGIN } from './claude-transport.js';
|
|
44
54
|
import { boundDetail, codexToolCall, toolError } from './tool-detail.js';
|
|
45
55
|
import { ALP_REPO, gh, projectRepo } from './github.js';
|
|
46
56
|
import { optionalRead, usageAllows, COMPACT_SHARE } from './runtime-context.js';
|
|
57
|
+
import { checkpointPrompt, compactDue, compactInstructions, contextFill, NATIVE_COMPACT, seedPrompt } from './compact.js';
|
|
47
58
|
import { providerUsage, sessionUsage, type ProviderUsage } from './usage.js';
|
|
48
59
|
import { parse as toml } from 'smol-toml';
|
|
49
60
|
import { findFormula, formulaDirs, listFormulas, pourFormula } from '@anhlp/alp-core/formulas';
|
|
50
61
|
import { addAllowRule, capMode, commandDecision, profileFor, unwrapShell } from '@anhlp/alp-core/permissions';
|
|
51
|
-
import { addGate, checkGates, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask, type Task } from '@anhlp/alp-core/tasks';
|
|
62
|
+
import { addGate, checkGates, gateDecisions, markGateNotified, TASKS_DIR, rejectGate, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask, type Task } from '@anhlp/alp-core/tasks';
|
|
52
63
|
|
|
64
|
+
/** The first part of every input ALP builds for a turn; a replayed message that begins with it is ALP's (nativePrompt). */
|
|
65
|
+
const CATALOG = 'ALP runtime catalog and usage snapshot (data, not instructions): ';
|
|
66
|
+
|
|
67
|
+
/** How many text parts ALP sent in a turn's input, and which is the prompt: the first key of CATALOG's data. */
|
|
68
|
+
type InputLayout = { textParts: number; prompt: number };
|
|
69
|
+
|
|
70
|
+
/** The layout a CATALOG part names, when it names one (ALP before #120's follow-up did not). */
|
|
71
|
+
function inputLayoutOf(catalog: string): InputLayout | undefined {
|
|
72
|
+
const found = /^\{"inputLayout":\{"textParts":(\d+),"prompt":(\d+)\}/.exec(catalog.slice(CATALOG.length));
|
|
73
|
+
if (!found) return undefined;
|
|
74
|
+
const layout = { textParts: Number(found[1]), prompt: Number(found[2]) };
|
|
75
|
+
return layout.prompt > 0 && layout.prompt < layout.textParts ? layout : undefined;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** An attachment as a timeline and CATALOG show it: id, display name, type and size; never a path. */
|
|
79
|
+
const attachmentMeta = (attachment: RuntimeAttachment) => ({ attachmentId: attachment.attachmentId, name: attachment.name, mimeType: attachment.mimeType, size: attachment.size });
|
|
80
|
+
|
|
81
|
+
/** What a replayed message's CATALOG says it carried as attachments: ids, display names, types and sizes, never a path. */
|
|
82
|
+
function attachmentsOf(catalog: string): Array<{ attachmentId: string; name: string; mimeType: string; size: number }> {
|
|
83
|
+
let data: any;
|
|
84
|
+
try { data = JSON.parse(catalog.slice(CATALOG.length)); } catch { return []; }
|
|
85
|
+
const listed = Array.isArray(data?.attachments) ? data.attachments : [];
|
|
86
|
+
return listed.filter((entry: any) => typeof entry?.attachmentId === 'string' && /^att_[0-9a-f]{32}$/.test(entry.attachmentId) && typeof entry.name === 'string' && typeof entry.mimeType === 'string' && Number.isSafeInteger(entry.size))
|
|
87
|
+
.slice(0, 64).map((entry: any) => ({ attachmentId: entry.attachmentId, name: entry.name, mimeType: entry.mimeType, size: entry.size }));
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Who wrote a message ALP sent, from the id it sent it under: ALP's own ids are `alp-wake-`,
|
|
91
|
+
* `alp-mail-`, `alp-review-`, `alp-resume-`, `alp-recover-` and `task-`; any other id is a client's
|
|
92
|
+
* (the user's, or a job the user scheduled).
|
|
93
|
+
*/
|
|
94
|
+
function promptOrigin(clientMessageId: string, session: { parent?: string }): TurnOrigin {
|
|
95
|
+
if (/^alp-(wake|mail)-/.test(clientMessageId)) return 'wake';
|
|
96
|
+
if (/^(alp-review-|task-)/.test(clientMessageId)) return 'assignment';
|
|
97
|
+
if (/^alp-(resume|recover)-/.test(clientMessageId)) return session.parent ? 'assignment' : 'wake';
|
|
98
|
+
return 'user';
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* ALP's own compaction prompts (the checkpoint request and a fresh conversation's seed): they reach
|
|
102
|
+
* the model but are not user messages, so the timeline shows notices instead (t-b3cd #6).
|
|
103
|
+
*/
|
|
104
|
+
const COMPACT_PROMPT = 'alp-wake-compact-';
|
|
53
105
|
const MAX_WAKES = 8;
|
|
54
106
|
/** How long the user may wait for main's first words before its tool results remind it. */
|
|
55
107
|
const USER_REPLY_MS = 60_000;
|
|
56
108
|
|
|
57
109
|
/** What a waiting session hears when the user wrote to it. */
|
|
58
110
|
const USER_WROTE = 'The user just wrote to you; their message follows. Answer them first in a short message they can read (tool calls alone show them nothing), and steer an assignment with alp_send when their words change its brief. Your assignments keep running: then alp_wait again, or end your turn and ALP wakes you with their results.';
|
|
111
|
+
/** A wait cut short by the end of its turn: what it waited for goes on. */
|
|
112
|
+
const TURN_ENDED = 'Turn ended before the result arrived. Running assignments keep running; ALP wakes you with their results as mail.';
|
|
59
113
|
/** What a waiting session hears with a check-in, or mail from its requester or the user. */
|
|
60
114
|
const CHECKED_IN = 'Not a result: the assignment keeps running. Act on this mail first (a steer from your requester or the user\'s words may change what your assignments should do: pass that on with alp_send), then alp_wait again or end your turn.';
|
|
61
115
|
/** A session's native process is restarted at most RESTART_LIMIT times within RESTART_WINDOW_MS unless it makes progress meanwhile. */
|
|
@@ -73,21 +127,34 @@ const LIMIT_FRESH_MS = 15_000;
|
|
|
73
127
|
*/
|
|
74
128
|
const CONTEXT_SOON = 0.9;
|
|
75
129
|
const CONTEXT_RESET = 0.5;
|
|
130
|
+
/** After a failed compaction, how long the automatic one waits before it tries again (t-0e56). */
|
|
131
|
+
const COMPACT_RETRY_MS = 10 * 60_000;
|
|
132
|
+
const MAIL_WAITS = 'Mail waits for the session';
|
|
133
|
+
const REVIEWING = 'The supervisor is reviewing the session';
|
|
134
|
+
/** How long a runtime may take to report the compaction it was asked for (t-0e56). */
|
|
135
|
+
const COMPACT_NATIVE_MS = 5 * 60_000;
|
|
76
136
|
|
|
77
137
|
/** How much of an assignment's brief ALP repeats after a compaction. */
|
|
78
138
|
const BRIEF_CHARS = 8000;
|
|
139
|
+
/** How much of a writer's brief and of its handoff and output the result ledger keeps as evidence. */
|
|
140
|
+
const RESULT_EVIDENCE_CHARS = 2000;
|
|
141
|
+
const RESOLVE_NOTE_CHARS = 2000;
|
|
79
142
|
// Placeholder delivery marks while a steer or a woken turn is starting.
|
|
80
143
|
const STEERING = '\u0000steering';
|
|
81
144
|
const STARTING = '\u0000starting';
|
|
82
145
|
|
|
83
146
|
/** Answers that approve a proposal; anything else is feedback. */
|
|
84
147
|
const APPROVALS = ['approve', 'approved', 'yes', 'y', 'ok', 'đồng ý', 'duyệt', 'có'];
|
|
148
|
+
const CHOICES_REJECT = ['reject', 'từ chối'];
|
|
85
149
|
const SKILL_BODY_CHARS = 20_000;
|
|
86
150
|
const STARTER_ROLES = ['main', 'lead', 'peer', 'oracle', 'reviewer', 'supervisor'];
|
|
87
151
|
const ISSUE_BODY_CHARS = 20_000;
|
|
88
152
|
const ISSUE_FOOTER = '\n\n---\n_Drafted by an ALP agent and posted with the user\'s approval._';
|
|
89
153
|
|
|
90
154
|
const LESSON_CHARS = 600;
|
|
155
|
+
/** The monthly curate job's prompt starts with this marker, so main and ALP recognize it. */
|
|
156
|
+
export const CURATE_MARKER = '[alp-curate]';
|
|
157
|
+
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.`;
|
|
91
158
|
const DIGEST_CHARS = 12_000;
|
|
92
159
|
const JOURNAL_LINE_CHARS = 400;
|
|
93
160
|
/** Journal lines carry the local time, so the supervisor sees how long the user waited. */
|
|
@@ -117,8 +184,24 @@ const isolationOf = (args: { isolation?: string }) => args.isolation ?? 'shared'
|
|
|
117
184
|
|
|
118
185
|
const log = createLogger({ component: 'runtime' });
|
|
119
186
|
|
|
187
|
+
export type WorkspaceMutationReason = 'workspace_busy' | 'workspace_claimed' | 'workspace_leased' | 'workspace_assignment_result' | 'workspace_identity';
|
|
188
|
+
export class WorkspaceMutationError extends Error {
|
|
189
|
+
readonly data: { reason: WorkspaceMutationReason };
|
|
190
|
+
constructor(reason: WorkspaceMutationReason, message: string) {
|
|
191
|
+
super(message);
|
|
192
|
+
this.name = 'WorkspaceMutationError';
|
|
193
|
+
this.data = { reason };
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
120
197
|
export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
121
198
|
const sessions = new Map<string, Session>();
|
|
199
|
+
// Only internally initiated, accepted compact inputs may be hidden on replay.
|
|
200
|
+
// Keep ownership across native thread restarts; closing an owner releases all its records.
|
|
201
|
+
const compactEchoes = new Map<Session, Map<string, string>>();
|
|
202
|
+
const inputDigest = (parts: string[]) => createHash('sha256').update(JSON.stringify(parts)).digest('hex');
|
|
203
|
+
/** Queue slots preparing a scheduled prompt, before its native turn/start. */
|
|
204
|
+
const admittedPrompts = new Set<string>();
|
|
122
205
|
/** What ALP writes for the user of a session, in their language (ALPD §54). */
|
|
123
206
|
const wordsFor = (session: Session) => words(session.mapping.language);
|
|
124
207
|
|
|
@@ -138,10 +221,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
138
221
|
|
|
139
222
|
const listeners = new Set<(envelope: Envelope) => void>();
|
|
140
223
|
const epoch = randomUUID();
|
|
224
|
+
/** A failed write of alpd's own state reaches the host's disk guard at once (t-e80a). */
|
|
225
|
+
const writeFailed = (error: unknown) => { options.onWriteError?.(error); };
|
|
141
226
|
/** Finished assignments whose native threads alp_recall can question. */
|
|
142
|
-
const recalls = createRecallBook(options.recallFile);
|
|
227
|
+
const recalls = createRecallBook(options.recallFile, writeFailed);
|
|
228
|
+
const assignmentResults = createAssignmentResults(options.assignmentResultFile, writeFailed);
|
|
143
229
|
/** Running assignments, so the next alpd continues them (ALPD §31). */
|
|
144
|
-
const inFlight = createLiveBook(options.liveFile);
|
|
230
|
+
const inFlight = createLiveBook(options.liveFile, writeFailed);
|
|
145
231
|
/** Those an earlier alpd left running; recover() takes them once their root is open again. */
|
|
146
232
|
let inherited = inFlight.all().filter(entry => entry.epoch !== epoch);
|
|
147
233
|
/** Pauses by runtime, or of everything; kept in pauseFile across restarts. */
|
|
@@ -163,12 +249,37 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
163
249
|
const leases = new Map<string, { assignment: string; agent: string }>();
|
|
164
250
|
const worktreeRoot = options.worktreeDir ?? path.join(os.tmpdir(), 'alp-worktrees');
|
|
165
251
|
const copyRoot = options.copyDir ?? path.join(os.tmpdir(), 'alp-copies');
|
|
252
|
+
/** Non-image attachments (§12.6): staged copies when alpd gave a directory, read from alpd's reader once it binds one. */
|
|
253
|
+
const stager = options.attachmentStageDir ? createAttachmentStager(options.attachmentStageDir) : undefined;
|
|
254
|
+
let attachmentReader: AttachmentReader | undefined;
|
|
255
|
+
/** Sessions already warned that the staging directory is inside their workspace. */
|
|
256
|
+
const stagingWarned = new Set<string>();
|
|
257
|
+
if (stager) void stager.sweep();
|
|
166
258
|
const sequences = new Map<string, number>();
|
|
167
259
|
|
|
260
|
+
let workspaceMutation = false;
|
|
261
|
+
let admitting = 0;
|
|
262
|
+
const refuseMutation = (reason: WorkspaceMutationReason, message: string): never => { throw new WorkspaceMutationError(reason, message); };
|
|
263
|
+
/** Never exported: no caller of withWorkspaceMutation can skip the birth certificate but adoptWorkspace. */
|
|
264
|
+
const ADOPTION = Symbol('adoption');
|
|
265
|
+
// Admission registers synchronously, before resolving configuration or creating copies.
|
|
266
|
+
async function admission<T>(run: () => Promise<T>): Promise<T> {
|
|
267
|
+
if (workspaceMutation) refuseMutation('workspace_busy', 'A workspace mutation is in progress; retry after it finishes');
|
|
268
|
+
admitting++;
|
|
269
|
+
try { return await run(); } finally { admitting--; }
|
|
270
|
+
}
|
|
168
271
|
let closed = false;
|
|
169
272
|
let queue = Promise.resolve();
|
|
170
273
|
|
|
171
274
|
const emit = (sessionId: string, event: AlpEvent) => {
|
|
275
|
+
// The staging directory never reaches a timeline: a tool's command or output, or a reply, that names
|
|
276
|
+
// a staged copy shows it under STAGED_PATH (§12.6). Clients know attachments by id and name.
|
|
277
|
+
if (stager) {
|
|
278
|
+
const json = JSON.stringify(event);
|
|
279
|
+
const named = stager.spellings().map(root => JSON.stringify(root).slice(1, -1)).filter(root => json.includes(root));
|
|
280
|
+
// The directory itself, not a longer name that starts like it (`staged-old`, `staged.bak`); a period ending a sentence is not a name.
|
|
281
|
+
if (named.length) event = JSON.parse(named.reduce((text, root) => text.replace(new RegExp(`${root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![A-Za-z0-9_-]|\\.[A-Za-z0-9_-])`, 'g'), STAGED_PATH), json));
|
|
282
|
+
}
|
|
172
283
|
const seq = (sequences.get(sessionId) ?? 0) + 1;
|
|
173
284
|
sequences.set(sessionId, seq);
|
|
174
285
|
const envelope: Envelope = { sessionId, epoch, seq, ts: new Date().toISOString(), event };
|
|
@@ -190,6 +301,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
190
301
|
return session.runtime.takesImages ? session.runtime.takesImages() : session.runtimeKind === 'codex' || session.runtimeKind === 'claude';
|
|
191
302
|
}
|
|
192
303
|
|
|
304
|
+
/** How the session's runtime can use attached files (the capability matrix of §12.6); none without alpd's reader and a staging directory. */
|
|
305
|
+
function attachmentRoutes(session: Session): readonly AttachmentRoute[] {
|
|
306
|
+
return stager && attachmentReader ? ATTACHMENT_ROUTES[session.runtimeKind] ?? [] : [];
|
|
307
|
+
}
|
|
308
|
+
|
|
193
309
|
function snapshot(sessionId: string, session: Session): SessionSnapshot {
|
|
194
310
|
return {
|
|
195
311
|
id: sessionId,
|
|
@@ -206,11 +322,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
206
322
|
...(session.parent ? { parentId: session.parent } : {}),
|
|
207
323
|
...(session.toolCallId ? { toolCallId: session.toolCallId } : {}),
|
|
208
324
|
...(session.active ? { activeTurnId: session.active } : {}),
|
|
209
|
-
|
|
325
|
+
// turn.ended listeners persist the intent before terminal() finishes parking it.
|
|
326
|
+
...((session.parked?.reason ?? session.parkReason) ? { parked: session.parked?.reason ?? session.parkReason } : {}),
|
|
210
327
|
...(session.instructionsSha ? { instructionsSha: session.instructionsSha } : {}),
|
|
211
328
|
...(takesImages(session) ? { promptImages: true } : {}),
|
|
329
|
+
...(attachmentRoutes(session).length ? { promptAttachments: [...attachmentRoutes(session)] } : {}),
|
|
212
330
|
...(session.usage ? { usage: session.usage } : {}),
|
|
213
|
-
busy: !!(session.active || session.pending || session.children.size || session.assignments.size || hasActiveMail(session) || reviewing(session)),
|
|
331
|
+
busy: !!(session.active || session.pending || session.parked || session.parkReason || session.children.size || session.assignments.size || hasActiveMail(session) || reviewing(session)),
|
|
214
332
|
};
|
|
215
333
|
}
|
|
216
334
|
|
|
@@ -238,11 +356,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
238
356
|
clearTimeout(waiter.timer);
|
|
239
357
|
waiter.resolve(null);
|
|
240
358
|
}
|
|
241
|
-
cancelQuestions(sessionId);
|
|
359
|
+
cancelQuestions(sessionId, true);
|
|
242
360
|
if (session.parent) sessions.get(session.parent)?.assignments.get(sessionId)?.ask?.resolve(toolResult(false, { error: 'Turn ended' }));
|
|
243
361
|
|
|
244
362
|
// Mail is acknowledged only by a turn that completed; otherwise it is delivered again.
|
|
245
|
-
|
|
363
|
+
const taken = state === 'completed' ? session.mail.filter(event => event.deliveredTurn === turnId) : [];
|
|
364
|
+
session.mail = session.mail.filter(event => !taken.includes(event));
|
|
365
|
+
for (const event of taken) gateMail.get(event)?.taken();
|
|
246
366
|
for (const event of session.mail) {
|
|
247
367
|
if (event.deliveredTurn === turnId) { event.deliveredTurn = undefined; event.redelivered = true; }
|
|
248
368
|
}
|
|
@@ -260,7 +380,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
260
380
|
}
|
|
261
381
|
session.userStopped = false;
|
|
262
382
|
if (session.role === 'supervisor' && session.parent && sessions.get(session.parent)?.reviewPending) review(session.parent);
|
|
383
|
+
if (session.role === 'supervisor' && session.parent) { const root = sessions.get(session.parent); if (root) queueMicrotask(() => compactAtBoundary(session.parent!, root)); }
|
|
263
384
|
if (!session.parent) void showTasks(sessionId, session);
|
|
385
|
+
if (!session.parent && session.role !== 'supervisor') queueMicrotask(() => compactAtBoundary(sessionId, session, state));
|
|
264
386
|
|
|
265
387
|
// An assignment a limit or a pause stopped waits, open, to continue instead of ending.
|
|
266
388
|
if (session.parkReason && state !== 'completed') {
|
|
@@ -268,6 +390,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
268
390
|
return;
|
|
269
391
|
}
|
|
270
392
|
session.parkReason = undefined;
|
|
393
|
+
session.parkPause = undefined;
|
|
271
394
|
|
|
272
395
|
// A requester is not done while its assignments run or mail awaits it.
|
|
273
396
|
if (state === 'completed' && (session.assignments.size || hasActiveMail(session))) {
|
|
@@ -278,11 +401,39 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
278
401
|
session.settle?.(state, error);
|
|
279
402
|
}
|
|
280
403
|
|
|
404
|
+
/**
|
|
405
|
+
* A native user message as ALP sent it: Codex keeps the clientUserMessageId ALP gave it as
|
|
406
|
+
* `clientId`, and the parts of the input startPrompt built (CATALOG first, then the task digest,
|
|
407
|
+
* an interrupted turn's words, the prompt, its images and mail). The message is the prompt part
|
|
408
|
+
* alone, and its origin comes from its id: ALP's own (mail, briefs, resumes) never title a root.
|
|
409
|
+
* A message ALP sent without an id (an older Codex) has no origin anyone can trust; one ALP did not
|
|
410
|
+
* build (a thread started outside ALP) is the user's.
|
|
411
|
+
*/
|
|
412
|
+
function nativePrompt(item: any, session: Session): { text: string; clientMessageId?: string; origin?: TurnOrigin; attachments?: ReturnType<typeof attachmentsOf> } {
|
|
413
|
+
const parts: string[] = (item.content ?? []).filter((c: any) => c.type === 'text').map((c: any) => String(c.text ?? ''));
|
|
414
|
+
const clientMessageId = typeof item.clientId === 'string' && item.clientId ? item.clientId : undefined;
|
|
415
|
+
// Mail steered into a running turn is sent alone, without CATALOG.
|
|
416
|
+
if (!parts[0]?.startsWith(CATALOG)) return { text: parts.join('\n'), ...(clientMessageId ? { clientMessageId } : {}), origin: clientMessageId ? promptOrigin(clientMessageId, session) : parts[0]?.startsWith(MAIL_HEADER) ? 'wake' : 'user' };
|
|
417
|
+
const origin = clientMessageId ? promptOrigin(clientMessageId, session) : undefined;
|
|
418
|
+
const ids = { ...(clientMessageId ? { clientMessageId } : {}), ...(origin ? { origin } : {}) };
|
|
419
|
+
const layout = inputLayoutOf(parts[0]);
|
|
420
|
+
const attached = attachmentsOf(parts[0]);
|
|
421
|
+
// The prompt where CATALOG says it is. Every other part ALP sends has words, so a part missing
|
|
422
|
+
// is an empty prompt (an image alone) the runtime left out: its text is none, never a neighbour's.
|
|
423
|
+
if (layout) return { text: parts.length === layout.textParts ? parts[layout.prompt] ?? '' : '', ...ids, ...(attached.length ? { attachments: attached } : {}) };
|
|
424
|
+
// A message from before CATALOG named its layout: read by what its parts begin with.
|
|
425
|
+
const rest = parts.slice(1);
|
|
426
|
+
// Mail delivered with a prompt follows it; a mail wake's prompt is mail itself, after the task digest.
|
|
427
|
+
if (!clientMessageId?.startsWith('alp-wake-') && rest.length > 1 && rest.at(-1)!.startsWith(MAIL_HEADER)) rest.pop();
|
|
428
|
+
return { text: rest.at(-1) ?? '', ...ids };
|
|
429
|
+
}
|
|
430
|
+
|
|
281
431
|
function nativeItem(
|
|
282
432
|
sessionId: string,
|
|
283
433
|
session: Session,
|
|
284
434
|
item: any,
|
|
285
435
|
done = false,
|
|
436
|
+
turnId?: string,
|
|
286
437
|
) {
|
|
287
438
|
if (item.type === 'agentMessage') {
|
|
288
439
|
// The first words main shows after the user wrote: how long the user waited.
|
|
@@ -296,12 +447,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
296
447
|
}
|
|
297
448
|
|
|
298
449
|
if (item.type === 'userMessage') {
|
|
299
|
-
const text = (item
|
|
300
|
-
|
|
301
|
-
.map((
|
|
302
|
-
.
|
|
450
|
+
const { text, clientMessageId, origin, attachments } = nativePrompt(item, session);
|
|
451
|
+
if (turnId) {
|
|
452
|
+
const digest = inputDigest((item.content ?? []).filter((part: any) => part.type === 'text').map((part: any) => String(part.text ?? '')));
|
|
453
|
+
for (const echoes of compactEchoes.values()) if (echoes.get(`${session.threadId}:${turnId}`) === digest) return;
|
|
454
|
+
}
|
|
303
455
|
const images = (item.content ?? []).filter((c: any) => c.type === 'image' || c.type === 'localImage').length;
|
|
304
|
-
emit(sessionId, { type: 'item', item: { kind: 'user_message', id: item.id, text, ...(images ? { images } : {}) } });
|
|
456
|
+
emit(sessionId, { type: 'item', item: { kind: 'user_message', id: item.id, text, ...(clientMessageId ? { clientMessageId } : {}), ...(origin ? { origin } : {}), ...(images ? { images } : {}), ...(attachments ? { attachments } : {}) } });
|
|
305
457
|
return;
|
|
306
458
|
}
|
|
307
459
|
|
|
@@ -387,6 +539,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
387
539
|
params: any,
|
|
388
540
|
) {
|
|
389
541
|
if (session.closed) return;
|
|
542
|
+
// What the runtime says it runs with; the run log keeps it beside the configured model (§12.9).
|
|
543
|
+
if (method === 'alp/nativeModel') {
|
|
544
|
+
if (typeof params?.model === 'string') runLog(rootOf(sessionId), { event: 'session.native_model', sessionId, agent: session.mapping.agent.name, configured: session.mapping.model, model: params.model.slice(0, 200) });
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
390
547
|
|
|
391
548
|
touch(sessionId, session);
|
|
392
549
|
|
|
@@ -465,7 +622,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
465
622
|
|
|
466
623
|
// A usage limit pauses its runtime; an assignment it stopped is parked to continue later.
|
|
467
624
|
if (state === 'failed' && LIMIT_ERRORS.includes(params.turn.error?.codexErrorInfo)) {
|
|
468
|
-
if (session.
|
|
625
|
+
if (session.role !== 'supervisor') {
|
|
626
|
+
session.parkReason = `the ${label(session.runtimeKind)} usage limit was reached`;
|
|
627
|
+
session.parkPause = { scope: paused.all ? 'all' : session.runtimeKind, ...(paused.all?.cause === 'disk' ? { disk: true } : {}) };
|
|
628
|
+
}
|
|
469
629
|
void limitReached(session, params.turn.error);
|
|
470
630
|
}
|
|
471
631
|
|
|
@@ -478,42 +638,71 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
478
638
|
}
|
|
479
639
|
}
|
|
480
640
|
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
641
|
+
// Failure callbacks and an opening call's catch can both retire the same record.
|
|
642
|
+
// Keep the cleanup with that incarnation, even after its id has been reused.
|
|
643
|
+
const sessionClosures = new WeakMap<Session, Promise<void>>();
|
|
644
|
+
const openedSessions = new WeakSet<Session>();
|
|
645
|
+
/**
|
|
646
|
+
* Sessions whose first open is still running, with the process failure that came meanwhile: the
|
|
647
|
+
* open fails with it and reports it once it stopped using the session, rather than a failure
|
|
648
|
+
* callback closing the session under it (failSession while openSession still runs).
|
|
649
|
+
*/
|
|
650
|
+
const openings = new WeakMap<Session, { failure?: unknown }>();
|
|
651
|
+
const assignmentSessions = new WeakMap<Assignment, Session>();
|
|
652
|
+
function closeSession(sessionId: string, session = sessions.get(sessionId), notify = true): Promise<void> {
|
|
653
|
+
if (!session) return Promise.resolve();
|
|
654
|
+
const closing = sessionClosures.get(session);
|
|
655
|
+
if (closing) return closing;
|
|
656
|
+
if (session.closed) return Promise.resolve();
|
|
484
657
|
|
|
485
658
|
session.closed = true;
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
[
|
|
491
|
-
)
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
659
|
+
const current = sessions.get(sessionId) === session;
|
|
660
|
+
const opened = openedSessions.has(session);
|
|
661
|
+
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
662
|
+
const descendants = current ? [...session.children, ...(session.supervisor ? [session.supervisor] : [])]
|
|
663
|
+
.map(id => [id, sessions.get(id)] as const).filter((entry): entry is readonly [string, Session] => !!entry[1]) : [];
|
|
664
|
+
if (current) {
|
|
665
|
+
cancelQuestions(sessionId);
|
|
666
|
+
approvalLedger.delete(sessionId);
|
|
667
|
+
releaseClaims(sessionId, session.mapping.agent.projectRoot);
|
|
668
|
+
// terminal also touches questions and parent bookkeeping by id. Do it before
|
|
669
|
+
// yielding, while this is still the record registered under that id.
|
|
670
|
+
terminal(sessionId, session, 'canceled');
|
|
671
|
+
session.settle?.('canceled', 'Session closed');
|
|
672
|
+
}
|
|
495
673
|
|
|
496
|
-
|
|
674
|
+
const cleanup = (async () => {
|
|
675
|
+
await Promise.all(
|
|
676
|
+
descendants.map(([id, child]) => closeSession(id, child)),
|
|
677
|
+
);
|
|
678
|
+
await session.runtime.close();
|
|
497
679
|
|
|
498
|
-
|
|
499
|
-
|
|
680
|
+
// Copies of assignments that did not finish hold nothing to keep.
|
|
681
|
+
for (const assignment of session.assignments.values()) if (assignment.copy && !assignment.finished) await removeCopy(assignment.copy).catch(() => {});
|
|
500
682
|
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
683
|
+
for (const [assignmentId, { worktree }] of session.worktrees) {
|
|
684
|
+
await removeWorktree(worktree).catch(() => {});
|
|
685
|
+
runLog(rootOf(sessionId), { event: 'worktree.kept', assignmentId, branch: worktree.branch });
|
|
686
|
+
}
|
|
687
|
+
session.worktrees.clear();
|
|
506
688
|
|
|
507
|
-
|
|
689
|
+
compactEchoes.delete(session);
|
|
508
690
|
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
691
|
+
// Every id-based side effect belongs to this incarnation, including the
|
|
692
|
+
// parent's membership and the event that tells viewers it is no longer live.
|
|
693
|
+
if (sessions.get(sessionId) !== session) return;
|
|
694
|
+
sessions.delete(sessionId);
|
|
695
|
+
if (session.parent && parent && sessions.get(session.parent) === parent) {
|
|
696
|
+
parent.children.delete(sessionId);
|
|
697
|
+
if (parent.supervisor === sessionId) parent.supervisor = undefined;
|
|
698
|
+
}
|
|
514
699
|
|
|
515
|
-
|
|
516
|
-
|
|
700
|
+
// An opening failure has no live incarnation to close. Its failure callback
|
|
701
|
+
// reports session.failed; an ordinary startup rejection is the open error.
|
|
702
|
+
if (notify && opened) emit(sessionId, { type: 'session.closed' });
|
|
703
|
+
})();
|
|
704
|
+
sessionClosures.set(session, cleanup);
|
|
705
|
+
return cleanup;
|
|
517
706
|
}
|
|
518
707
|
|
|
519
708
|
let runLogWrites = Promise.resolve();
|
|
@@ -624,7 +813,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
624
813
|
const boards = new Map<string, Promise<Pin[]>>();
|
|
625
814
|
/** The same boards once loaded, for synchronous status. */
|
|
626
815
|
const loadedBoards = new Map<string, Pin[]>();
|
|
627
|
-
const userQuestions = new Map<string, { question: UserQuestion; settle: (outcome: 'answered' | 'dismissed' | 'timeout' | 'canceled', answer?: string, reason?: string, result?: unknown) => void }>();
|
|
816
|
+
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 }>();
|
|
628
817
|
let mailSequence = 0;
|
|
629
818
|
let watchdog: NodeJS.Timeout | undefined;
|
|
630
819
|
|
|
@@ -793,6 +982,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
793
982
|
: entry.event === 'task' ? `${entry.agent} ${TASK_PAST[entry.action] ?? entry.action} task ${entry.id} "${clip(entry.title, 120)}"${entry.status ? ` (now ${entry.status})` : ''}${entry.detail ? `: ${clip(entry.detail)}` : ''}`
|
|
794
983
|
: entry.event === 'epic.landed' ? `${entry.agent} closed ${entry.id} "${clip(entry.title, 120)}": ${entry.tasks} tasks, ${entry.reworked} reworked, ${entry.unverified?.length ?? 0} closed unverified`
|
|
795
984
|
: entry.event === 'recall' ? `${entry.agent} recalled ${entry.recalled} assignment ${entry.assignmentId}: ${clip(entry.question)}`
|
|
985
|
+
: entry.event === 'skill.approval' && !entry.saved ? `skill approval ${entry.approvalId} for ${entry.name}: not saved (${entry.error ?? entry.outcome})`
|
|
986
|
+
: entry.event === 'issue.approval' ? `issue approval ${entry.approvalId} in ${entry.repo}: ${entry.posted ? entry.url : entry.error ?? entry.outcome}`
|
|
796
987
|
: entry.event === 'issue' ? `${entry.action === 'create' ? `opened issue "${clip(entry.title, 200)}"` : `commented on issue #${entry.issue}`} in ${entry.repo} with the user's approval: ${entry.url}`
|
|
797
988
|
: entry.event?.startsWith('worktree.') ? `${entry.event.slice('worktree.'.length)} worktree of ${entry.assignmentId} (${entry.branch})${entry.status ? `: ${entry.status}` : ''}`
|
|
798
989
|
: undefined;
|
|
@@ -936,10 +1127,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
936
1127
|
return toolResult(true, { tasks: rows.slice(0, limit).map(task => summarize(task, tasks)), ...(rows.length > limit ? { more: rows.length - limit } : {}), ...warnings });
|
|
937
1128
|
}
|
|
938
1129
|
const { action: _action, id, note, reason, summary, unverified, add, remove, ...input } = args;
|
|
939
|
-
if (action === 'pour' && (typeof input.formula !== 'string' || (input.vars !== undefined && (!input.vars || typeof input.vars !== 'object' || Array.isArray(input.vars) || !Object.
|
|
940
|
-
return toolResult(false, { error:
|
|
1130
|
+
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'))))) {
|
|
1131
|
+
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` });
|
|
941
1132
|
}
|
|
942
|
-
const { kind, until, ref, gate, formula: _formula, vars: _vars, ...fields } = input;
|
|
1133
|
+
const { kind, until, ref, gate, options: gateChoices, formula: _formula, vars: _vars, ...fields } = input;
|
|
943
1134
|
if (action === 'clear') {
|
|
944
1135
|
const current = (await loadTasks(project)).tasks.find(candidate => candidate.id === id);
|
|
945
1136
|
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' });
|
|
@@ -947,6 +1138,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
947
1138
|
let poured: Awaited<ReturnType<typeof pourFormula>> | undefined;
|
|
948
1139
|
// A blocking task.close hook can refuse the close; its output is the reason.
|
|
949
1140
|
const hookedClose = async (id: string) => {
|
|
1141
|
+
// Refused before any hook runs: no agent closes around a human gate (t-f438); core checks again under the lock.
|
|
1142
|
+
const current = (await loadTasks(project)).tasks.find(candidate => candidate.id === id);
|
|
1143
|
+
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`);
|
|
950
1144
|
const refused = await runHooks(sessionId, session, 'task.close', { reason, ...(summary ? { summary } : {}) }, id);
|
|
951
1145
|
if (refused) throw new Error(`A task.close hook refused to close ${id}: ${refused}`);
|
|
952
1146
|
return closeTask(project, id, { reason, summary, unverified }, by);
|
|
@@ -955,13 +1149,14 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
955
1149
|
action === 'create' ? await createTask(project, fields as any, by)
|
|
956
1150
|
: action === 'update' ? await updateTask(project, id, { ...fields, note }, by)
|
|
957
1151
|
: action === 'pour' ? (poured = await pourFormula(project, (await findFormula(project, options.libraryDir, input.formula, { toml })).formula, input.vars, by, input.parent ? { parent: input.parent } : {})).epic
|
|
958
|
-
: action === 'gate' ? await addGate(project, id, { kind, note, until, ref }, by)
|
|
1152
|
+
: action === 'gate' ? await addGate(project, id, { kind, note, until, ref, ...(gateChoices !== undefined ? { options: gateChoices } : {}) }, by)
|
|
959
1153
|
: action === 'clear' ? await resolveGate(project, id, gate, { by, note })
|
|
960
1154
|
: action === 'link' ? await linkTask(project, id, { add, remove }, by)
|
|
961
1155
|
: action === 'start' ? await startTask(project, id, { agent: by, session: sessionId }, by)
|
|
962
1156
|
: action === 'close' ? await hookedClose(id)
|
|
963
1157
|
: await reopenTask(project, id, { note }, by);
|
|
964
1158
|
touchTask(rootOf(sessionId), task.id);
|
|
1159
|
+
if (action === 'gate' && kind === 'human') void syncGates(project);
|
|
965
1160
|
runLog(rootOf(sessionId), { event: 'task', action, agent: by, id: task.id, title: task.title, status: task.status, ...(summary ?? note ? { detail: summary ?? note } : {}) });
|
|
966
1161
|
const { tasks } = await loadTasks(project);
|
|
967
1162
|
const landed: Record<string, unknown> = {};
|
|
@@ -1071,6 +1266,49 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1071
1266
|
}
|
|
1072
1267
|
}
|
|
1073
1268
|
|
|
1269
|
+
/**
|
|
1270
|
+
* Records how the requester handled a finished writer's change in its checkout, then archives the
|
|
1271
|
+
* result: until then the removal guard keeps that checkout. Recall expiry never stands in for this.
|
|
1272
|
+
*/
|
|
1273
|
+
async function resolveTool(sessionId: string, session: Session, args: unknown) {
|
|
1274
|
+
if (!plainObject(args, ['assignmentId', 'outcome', 'note']) || typeof args.assignmentId !== 'string' || !RESULT_OUTCOMES.includes(args.outcome as any) ||
|
|
1275
|
+
(args.note !== undefined && (typeof args.note !== 'string' || args.note.length > RESOLVE_NOTE_CHARS))) {
|
|
1276
|
+
return toolResult(false, { error: `Pass assignmentId, outcome (${RESULT_OUTCOMES.join(', ')}), and optionally a note of at most ${RESOLVE_NOTE_CHARS} characters` });
|
|
1277
|
+
}
|
|
1278
|
+
const id = args.assignmentId;
|
|
1279
|
+
const outcome = args.outcome as typeof RESULT_OUTCOMES[number];
|
|
1280
|
+
const note = args.note as string | undefined;
|
|
1281
|
+
const live = [...sessions.values()];
|
|
1282
|
+
if (sessions.has(id) || live.some(other => other.assignments.has(id)) || inFlight.all().some(entry => entry.assignmentId === id) || inherited.some(entry => entry.assignmentId === id)) {
|
|
1283
|
+
return toolResult(false, { error: 'That assignment is still running or can still be recovered; wait for its result' });
|
|
1284
|
+
}
|
|
1285
|
+
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' });
|
|
1286
|
+
let ledger: Awaited<ReturnType<typeof assignmentResults.inspect>>;
|
|
1287
|
+
try { ledger = await assignmentResults.inspect(); } catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
1288
|
+
const entry = ledger.results.find(owner => owner.assignmentId === id && !owner.handled);
|
|
1289
|
+
const project = session.mapping.agent.projectRoot;
|
|
1290
|
+
const overlapping = async (a: string, b: string) => {
|
|
1291
|
+
const [x, y] = [await realpath(a).catch(() => a), await realpath(b).catch(() => b)];
|
|
1292
|
+
const within = (parent: string, child: string) => { const relative = path.relative(parent, child); return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); };
|
|
1293
|
+
return within(x, y) || within(y, x);
|
|
1294
|
+
};
|
|
1295
|
+
// Its requesters may resolve it, and so may a root of its project, so a closed requester never leaves it held for good.
|
|
1296
|
+
// An entry from before evidence was kept names only its checkout: a root working there may resolve it.
|
|
1297
|
+
const allowed = !!entry && (entry.result
|
|
1298
|
+
? entry.result.requesters.includes(sessionId) || (!session.parent && await sameDirectory(entry.result.project, project))
|
|
1299
|
+
: !session.parent && await overlapping(entry.checkout, project));
|
|
1300
|
+
if (!entry || !allowed) return toolResult(false, { error: `No unresolved assignment result ${id} of yours` });
|
|
1301
|
+
// A worktree still on disk holds work only a merge or discard may settle.
|
|
1302
|
+
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` });
|
|
1303
|
+
try {
|
|
1304
|
+
const archived = await assignmentResults.resolve(id, { outcome, by: `${session.mapping.agent.name} in ${sessionId}`, at: new Date().toISOString(), ...(note ? { note } : {}) });
|
|
1305
|
+
runLog(rootOf(sessionId), { event: 'result.resolved', assignmentId: id, agent: session.mapping.agent.name, outcome, ...(note ? { note: clip(note, 500) } : {}) });
|
|
1306
|
+
return toolResult(true, { resolved: id, outcome, archivedAt: archived.archivedAt });
|
|
1307
|
+
} catch (error) {
|
|
1308
|
+
return toolResult(false, { assignmentId: id, error: errorData(error).message });
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1074
1312
|
let forgetting = Promise.resolve();
|
|
1075
1313
|
|
|
1076
1314
|
/** Deletes the native threads of assignments past their recall time, one transport per runtime. */
|
|
@@ -1095,7 +1333,28 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1095
1333
|
const label = (kind: RuntimeKind) => kind === 'claude' ? 'Claude' : kind === 'acp' ? 'ACP agent' : kind === 'antigravity' ? 'Antigravity' : 'Codex';
|
|
1096
1334
|
const pauseOf = (kind: RuntimeKind) => paused.all ?? paused.runtimes[kind];
|
|
1097
1335
|
/** Whether a session may not start a turn by itself now: parked, or on a paused runtime. */
|
|
1098
|
-
const held = (session: Session) => !!session.parked || !!pauseOf(session.runtimeKind);
|
|
1336
|
+
const held = (session: Session) => !!session.parked || !!pauseOf(session.runtimeKind) || (session.lifecycleHolds ?? 0) > 0;
|
|
1337
|
+
/** Whether mail may not wake a session now: it is held, or it is a new assignment whose brief has not started. */
|
|
1338
|
+
// Mail waits while main compacts (t-0e56), so it never lands in the checkpoint or the compaction.
|
|
1339
|
+
const holdsWake = (session: Session) => held(session) || !!session.awaitingBrief || !!session.compacting;
|
|
1340
|
+
|
|
1341
|
+
/**
|
|
1342
|
+
* Marks a session pending (its native process restarting) with a fresh `acknowledged` that resolves
|
|
1343
|
+
* when the returned function clears it. Mail delivered meanwhile waits on that promise; with the old,
|
|
1344
|
+
* already resolved one it would retry in a microtask loop and stall the process.
|
|
1345
|
+
*/
|
|
1346
|
+
function beginPending(session: Session) {
|
|
1347
|
+
let done!: () => void;
|
|
1348
|
+
session.pending = true;
|
|
1349
|
+
session.acknowledged = new Promise<void>(resolve => { done = resolve; });
|
|
1350
|
+
let cleared = false;
|
|
1351
|
+
return () => {
|
|
1352
|
+
if (cleared) return;
|
|
1353
|
+
cleared = true;
|
|
1354
|
+
session.pending = false;
|
|
1355
|
+
done();
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1099
1358
|
const describePause = (pause: Pause, kind?: RuntimeKind) =>
|
|
1100
1359
|
`${kind ? label(kind) : 'ALP'} is paused (${pause.reason}${pause.by !== 'alpd' ? `, by ${pause.by}` : ''})${pause.resetsAt ? `; the limit resets ${pause.resetsAt}` : ''}`;
|
|
1101
1360
|
|
|
@@ -1118,7 +1377,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1118
1377
|
const temporary = `${file}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
|
|
1119
1378
|
await writeFile(temporary, body, { mode: 0o600 });
|
|
1120
1379
|
await moveFile(temporary, file);
|
|
1121
|
-
}).catch(
|
|
1380
|
+
}).catch(error => tell(writeFailed, error));
|
|
1122
1381
|
}
|
|
1123
1382
|
|
|
1124
1383
|
/** Tells every open root, or those of one project, and so the user in each viewer. */
|
|
@@ -1214,34 +1473,46 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1214
1473
|
if (now) {
|
|
1215
1474
|
for (const [id, session] of sessions) {
|
|
1216
1475
|
if (!session.parent || session.closed || !session.active || session.role === 'supervisor' || (scope !== 'all' && session.runtimeKind !== scope)) continue;
|
|
1217
|
-
|
|
1476
|
+
// A process restart already owns its continuation; this pause must not replace its cause.
|
|
1477
|
+
if (session.parkReason && !session.parkPause) continue;
|
|
1478
|
+
session.parkReason = pause.cause === 'disk' ? pause.reason : `paused by ${pause.by}`;
|
|
1479
|
+
session.parkPause = { scope, ...(pause.cause === 'disk' ? { disk: true } : {}) };
|
|
1218
1480
|
void session.runtime.request('turn/interrupt', { threadId: session.threadId, turnId: session.active }).catch(() => {});
|
|
1219
1481
|
runLog(rootOf(id), { event: 'assignment.parking', assignmentId: id, agent: session.mapping.agent.name, reason: session.parkReason });
|
|
1220
1482
|
}
|
|
1221
1483
|
}
|
|
1222
1484
|
}
|
|
1223
1485
|
|
|
1224
|
-
function resumeRuntime(scope: RuntimeKind | 'all', by: string) {
|
|
1225
|
-
|
|
1486
|
+
function resumeRuntime(scope: RuntimeKind | 'all', by: string, keepRuntimes = false) {
|
|
1487
|
+
// Lifting alpd's disk pause keeps the usage-limit pauses of single runtimes.
|
|
1488
|
+
if (scope === 'all') paused = keepRuntimes ? { runtimes: paused.runtimes } : { runtimes: {} };
|
|
1226
1489
|
else delete paused.runtimes[scope];
|
|
1227
1490
|
savePauses();
|
|
1228
1491
|
watchLimits();
|
|
1492
|
+
const matches = (pause: Session['parkPause']) => pause && (scope === 'all' || pause.scope === scope);
|
|
1493
|
+
const continuing = [...sessions.values()].some(session => !session.closed && !pauseOf(session.runtimeKind) && matches(session.parked?.pause));
|
|
1229
1494
|
const free = RUNTIMES.filter(kind => !pauseOf(kind));
|
|
1230
|
-
if (free.length) notice('info', say => say.resumed(scope === 'all' ? 'ALP' : label(scope), by,
|
|
1495
|
+
if (free.length) notice('info', say => say.resumed(scope === 'all' ? 'ALP' : label(scope), by, continuing));
|
|
1231
1496
|
for (const [id, session] of sessions) {
|
|
1232
|
-
if (session.closed ||
|
|
1233
|
-
if (session.
|
|
1234
|
-
|
|
1497
|
+
if (session.closed || (scope !== 'all' && session.runtimeKind !== scope)) continue;
|
|
1498
|
+
if (matches(session.parkPause)) session.parkPause!.resumed = true;
|
|
1499
|
+
if (pauseOf(session.runtimeKind)) continue;
|
|
1500
|
+
if (session.parked) {
|
|
1501
|
+
if (matches(session.parked.pause)) continueParked(id, session);
|
|
1502
|
+
} else if (session.wakeHeld) { session.wakeHeld = false; deliver(id, session); }
|
|
1235
1503
|
}
|
|
1236
1504
|
}
|
|
1237
1505
|
|
|
1238
1506
|
/** An assignment whose turn a limit or a pause ended stays open, and its requester learns why. */
|
|
1239
1507
|
function park(sessionId: string, session: Session) {
|
|
1240
|
-
session.parked = { reason: session.parkReason!, since: Date.now() };
|
|
1508
|
+
session.parked = { reason: session.parkReason!, since: Date.now(), ...(session.parkPause ? { pause: session.parkPause } : {}) };
|
|
1509
|
+
const resumed = session.parkPause?.resumed;
|
|
1510
|
+
session.parkPause = undefined;
|
|
1241
1511
|
const then = session.parkThen;
|
|
1242
1512
|
session.parkReason = undefined;
|
|
1243
1513
|
session.parkThen = undefined;
|
|
1244
1514
|
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
1515
|
+
if (resumed) continueParked(sessionId, session);
|
|
1245
1516
|
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
1246
1517
|
const assignment = parent?.assignments.get(sessionId);
|
|
1247
1518
|
runLog(rootOf(sessionId), { event: 'assignment.parked', assignmentId: sessionId, agent: session.mapping.agent.name, reason: session.parked.reason });
|
|
@@ -1249,24 +1520,50 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1249
1520
|
emit(session.parent!, { type: 'assignment', assignment: assignmentSnapshot(assignment, 'parked') });
|
|
1250
1521
|
// One that continues by itself is information; one held until the user resumes needs the requester's decision, so it wakes it.
|
|
1251
1522
|
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.` });
|
|
1523
|
+
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.` });
|
|
1252
1524
|
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.` });
|
|
1253
1525
|
}
|
|
1254
1526
|
|
|
1255
|
-
function continueParked(sessionId: string, session: Session) {
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1527
|
+
function continueParked(sessionId: string, session: Session, expected = session.parked) {
|
|
1528
|
+
void enqueue(async () => {
|
|
1529
|
+
if (session.closed || session.active || session.pending || !session.parked || session.parked !== expected) return;
|
|
1530
|
+
// This continuation owns only the captured park. A pause may have arrived while
|
|
1531
|
+
// it waited in the queue; retain the actual blocker for a matching later resume.
|
|
1532
|
+
if (pauseOf(session.runtimeKind)) {
|
|
1533
|
+
session.parked.pause = { scope: paused.all ? 'all' : session.runtimeKind };
|
|
1534
|
+
return;
|
|
1535
|
+
}
|
|
1536
|
+
// A lifecycle operation (a fork or rewind reading the conversation) holds the session: the work stays
|
|
1537
|
+
// parked and continues when the last hold releases, as held mail does.
|
|
1538
|
+
if (session.lifecycleHolds) { session.resumeHeld = session.parked; return; }
|
|
1539
|
+
const parked = session.parked;
|
|
1540
|
+
const { reason, prompt } = parked;
|
|
1541
|
+
session.parked = undefined;
|
|
1542
|
+
session.wakeHeld = false;
|
|
1543
|
+
session.lastActivity = Date.now();
|
|
1544
|
+
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
1545
|
+
const assignment = parent?.assignments.get(sessionId);
|
|
1546
|
+
runLog(rootOf(sessionId), { event: 'assignment.resumed', assignmentId: sessionId, agent: session.mapping.agent.name });
|
|
1547
|
+
if (assignment) emit(session.parent!, { type: 'assignment', assignment: assignmentSnapshot(assignment, 'running') });
|
|
1548
|
+
try {
|
|
1549
|
+
await startPrompt(sessionId, {
|
|
1550
|
+
clientMessageId: `alp-resume-${randomUUID()}`,
|
|
1551
|
+
delivery: 'auto',
|
|
1552
|
+
content: [{ type: 'text', text: prompt ?? (session.parent
|
|
1553
|
+
? `ALP resumed this assignment; it had stopped because ${reason}. Continue where you left off: your earlier work in this session and its files are intact. Finish with alp_handoff as before.`
|
|
1554
|
+
: `ALP resumed this session; it had stopped because ${reason}. Continue the user's request where you left off: your earlier work in this thread and its files are intact.`) }],
|
|
1555
|
+
}, session.parent ? 'assignment' : 'wake');
|
|
1556
|
+
session.resumedTurn = session.active;
|
|
1557
|
+
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
1558
|
+
} catch (error) {
|
|
1559
|
+
if (!session.closed && !session.active) {
|
|
1560
|
+
session.parked = parked;
|
|
1561
|
+
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
1562
|
+
if (assignment) emit(session.parent!, { type: 'assignment', assignment: assignmentSnapshot(assignment, 'parked') });
|
|
1563
|
+
}
|
|
1564
|
+
notice('warning', `Could not resume ${session.mapping.agent.name}: ${errorData(error).message}`);
|
|
1565
|
+
}
|
|
1566
|
+
});
|
|
1270
1567
|
}
|
|
1271
1568
|
|
|
1272
1569
|
/** When a limit resets, from what the runtime last reported: the latest reset of a window that is used up. */
|
|
@@ -1287,8 +1584,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1287
1584
|
/** A turn failed on a usage limit: pause that runtime for delegation and wakes, and tell the user. */
|
|
1288
1585
|
async function limitReached(session: Session, error: any) {
|
|
1289
1586
|
const kind = session.runtimeKind;
|
|
1290
|
-
if (
|
|
1587
|
+
if (pauseOf(kind)) return;
|
|
1291
1588
|
const resetsAt = await limitReset(session, error);
|
|
1589
|
+
// A user's pause made while the provider lookup awaited remains theirs to lift.
|
|
1590
|
+
if (closed || session.closed || pauseOf(kind)) return;
|
|
1292
1591
|
const pause: Pause = { since: new Date().toISOString(), by: 'alpd', reason: `${label(kind)} usage limit reached`, ...(resetsAt ? { resetsAt } : {}) };
|
|
1293
1592
|
pauseRuntime(kind, pause);
|
|
1294
1593
|
const other = RUNTIMES.find(candidate => candidate !== kind && !pauseOf(candidate));
|
|
@@ -1305,6 +1604,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1305
1604
|
const used = usage?.last?.totalTokens;
|
|
1306
1605
|
const window = usage?.modelContextWindow;
|
|
1307
1606
|
if (session.role === 'supervisor' || typeof used !== 'number' || typeof window !== 'number' || window <= 0) return;
|
|
1607
|
+
// Against the window main works in, as the advisory measures it; not from the old context right after a compaction.
|
|
1608
|
+
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) });
|
|
1308
1609
|
const compactAt = typeof usage.autoCompactTokens === 'number' && usage.autoCompactTokens > 0
|
|
1309
1610
|
? usage.autoCompactTokens
|
|
1310
1611
|
: session.runtimeKind === 'codex' && session.mapping.autocompact
|
|
@@ -1332,6 +1633,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1332
1633
|
const skills = session.mapping.agent.skills;
|
|
1333
1634
|
if (!skills.length || item.type === 'agentMessage' || item.type === 'reasoning') return;
|
|
1334
1635
|
const text = typeof item.command === 'string' ? item.command : JSON.stringify(item).slice(0, 20_000);
|
|
1636
|
+
skillResources(sessionId, session, item);
|
|
1335
1637
|
if (!text.includes('SKILL.md') && !text.includes('Skill')) return;
|
|
1336
1638
|
for (const skill of skills) {
|
|
1337
1639
|
if (session.skillsUsed?.has(skill.name)) continue;
|
|
@@ -1344,6 +1646,22 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1344
1646
|
}
|
|
1345
1647
|
}
|
|
1346
1648
|
|
|
1649
|
+
/**
|
|
1650
|
+
* Progressive disclosure evidence (skill-resources.ts): the first time a session's tool call reads or
|
|
1651
|
+
* runs one of its skills' files beyond SKILL.md, by what the call asked for (never by a tool's output;
|
|
1652
|
+
* writing, listing or merely naming a file is no opening). Logged once per session, file and action,
|
|
1653
|
+
* so the run log shows which resources were loaded on demand and that the rest were not.
|
|
1654
|
+
*/
|
|
1655
|
+
function skillResources(sessionId: string, session: Session, item: any) {
|
|
1656
|
+
if (typeof item.command !== 'string') return;
|
|
1657
|
+
for (const use of resourceUses(item.command, session.mapping.agent.skills)) {
|
|
1658
|
+
const key = `${use.action}:${use.skill}/${use.resource}`;
|
|
1659
|
+
if (session.skillResourcesUsed?.has(key)) continue;
|
|
1660
|
+
(session.skillResourcesUsed ??= new Set()).add(key);
|
|
1661
|
+
runLog(rootOf(sessionId), { event: 'skill-resource', sessionId, agent: session.mapping.agent.name, skill: use.skill, resource: use.resource, action: use.action });
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1347
1665
|
/**
|
|
1348
1666
|
* A compaction of the session's context, from its start to its end (ALPD §57): shown in
|
|
1349
1667
|
* its timeline and the run log; once done, ALP tells the session what it holds of its
|
|
@@ -1357,14 +1675,186 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1357
1675
|
if (!done) return;
|
|
1358
1676
|
const agent = session.mapping.agent.name;
|
|
1359
1677
|
runLog(rootOf(sessionId), { event: 'compacted', sessionId, agent, ...trigger, ...tokens, ...(failed ? { failed: true, ...(item.error ? { error: String(item.error) } : {}) } : {}) });
|
|
1360
|
-
if (failed) return;
|
|
1678
|
+
if (failed) { if (session.compacting?.phase === 'native') compactFailed(sessionId, session, item.error ? String(item.error) : 'the runtime could not compact'); return; }
|
|
1361
1679
|
session.contextLevel = 0;
|
|
1362
1680
|
if (session.supervisor) session.journal.push(stamp(`${agent}'s context was compacted`));
|
|
1363
|
-
|
|
1681
|
+
const checkpoint = session.compacting?.phase === 'native' ? session.compacting.checkpoint : undefined;
|
|
1682
|
+
if (session.role !== 'supervisor') void restoreAfterCompaction(sessionId, session, checkpoint).catch(() => {});
|
|
1683
|
+
if (checkpoint !== undefined) compactFinished(sessionId, session, 'native');
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
/**
|
|
1687
|
+
* Whether a root holds anything a compaction must not cut into (t-0e56): a turn, a restart,
|
|
1688
|
+
* a question to the user or a park. Before one starts, also mail that would wake it. The
|
|
1689
|
+
* supervisor's review does not hold it: its mail waits for the compaction's end like any other.
|
|
1690
|
+
*/
|
|
1691
|
+
function compactHeld(sessionId: string, session: Session, starting: boolean) {
|
|
1692
|
+
return session.closed || !!session.active || !!session.pending || session.waiters.length > 0
|
|
1693
|
+
|| !!session.parked || !!session.parkReason
|
|
1694
|
+
|| (starting && (hasActiveMail(session) || !!session.wakeHeld))
|
|
1695
|
+
|| [...userQuestions.values()].some(pending => pending.question.rootId === sessionId && !pending.gate);
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
/**
|
|
1699
|
+
* Main's compaction (t-0e56). Once its context fills to the threshold, or the user asked,
|
|
1700
|
+
* main writes a checkpoint by skill compact in a turn of its own; after that turn the
|
|
1701
|
+
* runtime compacts natively, or ALP starts a fresh conversation seeded with it. It starts
|
|
1702
|
+
* only at a turn boundary (`ended`, the state of the turn that just ended); without one it
|
|
1703
|
+
* is a retry, after a hold such as the supervisor's review or held mail clears.
|
|
1704
|
+
*/
|
|
1705
|
+
function compactAtBoundary(sessionId: string, session: Session, ended?: 'completed' | 'failed' | 'canceled') {
|
|
1706
|
+
if (session.closed || sessions.get(sessionId) !== session) return;
|
|
1707
|
+
const current = session.compacting;
|
|
1708
|
+
if (ended && current?.phase === 'checkpoint' && current.checkpoint === undefined && current.turn) {
|
|
1709
|
+
// The checkpoint turn just ended: its last words are the checkpoint.
|
|
1710
|
+
const written = [...session.text.values()].at(-1)?.trim();
|
|
1711
|
+
if (ended !== 'completed' || !written) { compactFailed(sessionId, session, ended !== 'completed' ? `the checkpoint turn ${ended}` : 'main wrote no checkpoint'); return; }
|
|
1712
|
+
current.checkpoint = written;
|
|
1713
|
+
// A hold that outlasts this (a question, a park) fails it, so the user's held words go on.
|
|
1714
|
+
const timer = setTimeout(() => { if (session.compacting === current && current.phase === 'checkpoint') compactFailed(sessionId, session, 'main stayed busy after its checkpoint'); }, COMPACT_NATIVE_MS);
|
|
1715
|
+
timer.unref?.();
|
|
1716
|
+
}
|
|
1717
|
+
// The compaction turn ended without the runtime reporting a compaction.
|
|
1718
|
+
if (ended && current?.phase === 'native' && current.requested) { compactFailed(sessionId, session, 'the runtime reported no compaction'); return; }
|
|
1719
|
+
if (current) {
|
|
1720
|
+
if (current.checkpoint !== undefined && current.phase === 'checkpoint' && !compactHeld(sessionId, session, false)) void compactNow(sessionId, session);
|
|
1721
|
+
return;
|
|
1722
|
+
}
|
|
1723
|
+
if (compactHeld(sessionId, session, true)) return;
|
|
1724
|
+
if (session.compactBuffer?.length) { flushCompactBuffer(sessionId, session); return; }
|
|
1725
|
+
const trigger = compactDue(session.mapping.compact ?? { auto: false, threshold: 1 }, session.contextFill, !!session.compactRequested);
|
|
1726
|
+
if (!trigger) return;
|
|
1727
|
+
if (trigger === 'auto' && session.compactFailedAt && Date.now() - session.compactFailedAt < COMPACT_RETRY_MS) return;
|
|
1728
|
+
session.compactRequested = false;
|
|
1729
|
+
const compacting: NonNullable<Session['compacting']> = { phase: 'checkpoint', trigger, startedAt: Date.now() };
|
|
1730
|
+
session.compacting = compacting;
|
|
1731
|
+
runLog(rootOf(sessionId), { event: 'compact.started', sessionId, agent: session.mapping.agent.name, trigger, ...(session.contextFill !== undefined ? { fill: Math.round(session.contextFill * 100) / 100 } : {}) });
|
|
1732
|
+
const work = queue.then(async () => {
|
|
1733
|
+
if (session.compacting !== compacting) return;
|
|
1734
|
+
if (session.closed || compactHeld(sessionId, session, true)) {
|
|
1735
|
+
session.compacting = undefined;
|
|
1736
|
+
if (trigger === 'manual') session.compactRequested = true;
|
|
1737
|
+
compactReleased(sessionId, session);
|
|
1738
|
+
return;
|
|
1739
|
+
}
|
|
1740
|
+
compacting.turn = true;
|
|
1741
|
+
await startPrompt(sessionId, { clientMessageId: `${COMPACT_PROMPT}${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: checkpointPrompt(trigger, session.contextFill) }] }, 'wake', undefined, true);
|
|
1742
|
+
emit(sessionId, { type: 'item', item: { kind: 'notice', id: `notice-${randomUUID().slice(0, 8)}`, level: 'info', text: wordsFor(session).compacting() } });
|
|
1743
|
+
}).catch(error => compactFailed(sessionId, session, errorData(error).message));
|
|
1744
|
+
queue = work.catch(() => {});
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
/** Compacts with the runtime's own mechanism, else a fresh conversation seeded with the checkpoint. */
|
|
1748
|
+
async function compactNow(sessionId: string, session: Session) {
|
|
1749
|
+
const current = session.compacting!;
|
|
1750
|
+
const checkpoint = current.checkpoint!;
|
|
1751
|
+
if (NATIVE_COMPACT.includes(session.runtimeKind)) {
|
|
1752
|
+
current.phase = 'native';
|
|
1753
|
+
try {
|
|
1754
|
+
// Codex takes the thread alone; its summary gets the checkpoint back from the note ALP sends after.
|
|
1755
|
+
await session.runtime.request('thread/compact/start', { threadId: session.threadId, ...(session.runtimeKind === 'codex' ? {} : { instructions: compactInstructions(checkpoint) }) });
|
|
1756
|
+
if (session.compacting !== current) return;
|
|
1757
|
+
current.requested = true;
|
|
1758
|
+
// A runtime that took the request but never reports a compaction does not hold main for good.
|
|
1759
|
+
const timer = setTimeout(() => { if (session.compacting === current) compactFailed(sessionId, session, 'the runtime reported no compaction in time'); }, COMPACT_NATIVE_MS);
|
|
1760
|
+
timer.unref?.();
|
|
1761
|
+
return;
|
|
1762
|
+
} catch (error) {
|
|
1763
|
+
if (session.compacting !== current) return;
|
|
1764
|
+
runLog(rootOf(sessionId), { event: 'compact.native_failed', sessionId, agent: session.mapping.agent.name, error: errorData(error).message });
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
current.phase = 'fresh';
|
|
1768
|
+
const work = queue.then(async () => {
|
|
1769
|
+
if (session.compacting !== current || session.closed) return;
|
|
1770
|
+
// A fresh conversation drops the old one: only when nothing runs that it would lose.
|
|
1771
|
+
// Held mail is no reason to wait: it reaches the new conversation after the seed; nor is the
|
|
1772
|
+
// supervisor's review, which reads main's journal, not its native conversation.
|
|
1773
|
+
const refusal = restartRefusal(sessionId, session);
|
|
1774
|
+
if (refusal && refusal !== MAIL_WAITS && refusal !== REVIEWING) { compactFailed(sessionId, session, `a fresh conversation cannot start now: ${refusal}`); return; }
|
|
1775
|
+
await restartNative(sessionId, session, undefined);
|
|
1776
|
+
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
1777
|
+
await startPrompt(sessionId, { clientMessageId: `${COMPACT_PROMPT}${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: seedPrompt(checkpoint, session.lastUserText) }] }, 'wake', undefined, true);
|
|
1778
|
+
compactFinished(sessionId, session, 'fresh');
|
|
1779
|
+
}).catch(error => compactFailed(sessionId, session, errorData(error).message));
|
|
1780
|
+
queue = work.catch(() => {});
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
function compactFinished(sessionId: string, session: Session, via: 'native' | 'fresh') {
|
|
1784
|
+
const current = session.compacting;
|
|
1785
|
+
if (!current) return;
|
|
1786
|
+
session.compacting = undefined;
|
|
1787
|
+
session.compactFailedAt = undefined;
|
|
1788
|
+
// Usage reported until main's next turn may still count the old context.
|
|
1789
|
+
session.contextFill = undefined;
|
|
1790
|
+
session.compactCooling = true;
|
|
1791
|
+
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 });
|
|
1792
|
+
const text = wordsFor(session).compacted(via === 'native');
|
|
1793
|
+
emit(sessionId, { type: 'item', item: { kind: 'notice', id: `notice-${randomUUID().slice(0, 8)}`, level: 'info', text } });
|
|
1794
|
+
compactReleased(sessionId, session);
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
function compactFailed(sessionId: string, session: Session, reason: string) {
|
|
1798
|
+
const current = session.compacting;
|
|
1799
|
+
session.compacting = undefined;
|
|
1800
|
+
session.compactFailedAt = Date.now();
|
|
1801
|
+
runLog(rootOf(sessionId), { event: 'compact.failed', sessionId, agent: session.mapping.agent.name, ...(current ? { trigger: current.trigger } : {}), error: reason });
|
|
1802
|
+
if (!session.closed) emit(sessionId, { type: 'item', item: { kind: 'notice', id: `notice-${randomUUID().slice(0, 8)}`, level: 'warning', text: wordsFor(session).compactFailed(reason) } });
|
|
1803
|
+
compactReleased(sessionId, session);
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
/** A compaction ended or never started: the user's held words and held mail go on (t-0e56). */
|
|
1807
|
+
function compactReleased(sessionId: string, session: Session) {
|
|
1808
|
+
queueMicrotask(() => {
|
|
1809
|
+
if (session.closed || session.compacting) return;
|
|
1810
|
+
flushCompactBuffer(sessionId, session);
|
|
1811
|
+
if (session.wakeHeld && !holdsWake(session)) { session.wakeHeld = false; deliver(sessionId, session); }
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
/** Sends the user's words held during a compaction, in order, once no turn runs (t-0e56). */
|
|
1816
|
+
function flushCompactBuffer(sessionId: string, session: Session) {
|
|
1817
|
+
if (session.compacting || session.active || !session.compactBuffer?.length) return;
|
|
1818
|
+
const held = session.compactBuffer.splice(0);
|
|
1819
|
+
session.compactBuffer = undefined;
|
|
1820
|
+
const work = queue.then(async () => {
|
|
1821
|
+
for (const [index, input] of held.entries()) {
|
|
1822
|
+
await promptSession(sessionId, { ...input, delivery: index === 0 && !session.active ? 'auto' : 'steer' }, true);
|
|
1823
|
+
}
|
|
1824
|
+
});
|
|
1825
|
+
queue = work.catch(() => {});
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
/** The user's request to compact a root (t-0e56): now if it is idle, else at its next turn boundary. */
|
|
1829
|
+
function requestCompact(sessionId: string) {
|
|
1830
|
+
const session = sessions.get(sessionId);
|
|
1831
|
+
if (!session || session.closed) throw new ConversationError('session_busy', 'The session is not open');
|
|
1832
|
+
if (session.parent || session.role === 'supervisor') throw new ConversationError('runtime_unsupported', 'Only a root session is compacted');
|
|
1833
|
+
if (session.compacting) return { status: 'running' as const };
|
|
1834
|
+
session.compactRequested = true;
|
|
1835
|
+
if (compactHeld(sessionId, session, true)) return { status: 'deferred' as const };
|
|
1836
|
+
compactAtBoundary(sessionId, session);
|
|
1837
|
+
return { status: 'started' as const };
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
/**
|
|
1841
|
+
* The composer's "/" list for a live session (t-f628): the agent's ALP skills, as Claude names them
|
|
1842
|
+
* (`alp:<name>`), and only the runtime's own commands and skills its team settings name (t-efa3).
|
|
1843
|
+
*/
|
|
1844
|
+
async function listCommands(sessionId: string): Promise<RuntimeCommand[]> {
|
|
1845
|
+
const session = sessions.get(sessionId);
|
|
1846
|
+
if (!session || session.closed) throw new ConversationError('session_busy', 'The session is not open');
|
|
1847
|
+
const prefix = session.runtimeKind === 'claude' ? `${SKILL_PLUGIN}:` : '';
|
|
1848
|
+
const offered = new Set([...session.mapping.commands ?? [], ...session.mapping.agent.skills.map(skill => prefix + skill.name)]);
|
|
1849
|
+
const listed = (session.runtime.commands ? await session.runtime.commands().catch(() => [] as RuntimeCommand[]) : []).filter(command => offered.has(command.name));
|
|
1850
|
+
const seen = new Set(listed.map(command => command.name));
|
|
1851
|
+
const skills = await Promise.all(session.mapping.agent.skills.filter(skill => !seen.has(prefix + skill.name))
|
|
1852
|
+
.map(async skill => ({ name: prefix + skill.name, description: await skillDescription(skill.path), kind: 'skill' as const })));
|
|
1853
|
+
return [...listed, ...skills];
|
|
1364
1854
|
}
|
|
1365
1855
|
|
|
1366
1856
|
/** What ALP holds of a session's work, told to it after a compaction (ALPD §57). */
|
|
1367
|
-
async function restoreAfterCompaction(sessionId: string, session: Session) {
|
|
1857
|
+
async function restoreAfterCompaction(sessionId: string, session: Session, checkpoint?: string) {
|
|
1368
1858
|
const parts = ['Your context was just compacted. In case the summary lost any of it, this is what ALP holds of your work now.'];
|
|
1369
1859
|
if (session.parent && session.brief) parts.push(`Your assignment from ${session.parentAgent ?? 'your requester'}, as it was given:\n${cut(session.brief, BRIEF_CHARS)}`);
|
|
1370
1860
|
const running = [...session.assignments.values()].filter(assignment => !assignment.finished);
|
|
@@ -1375,7 +1865,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1375
1865
|
if (session.worktrees.size) {
|
|
1376
1866
|
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'));
|
|
1377
1867
|
}
|
|
1378
|
-
const asked = [...userQuestions.values()].filter(pending => pending.question.sessionId === sessionId);
|
|
1868
|
+
const asked = [...userQuestions.values()].filter(pending => pending.question.sessionId === sessionId && !pending.gate);
|
|
1379
1869
|
if (asked.length) parts.push('Waiting for the user to answer:\n' + asked.map(pending => `- ${clip(pending.question.body, 300)}`).join('\n'));
|
|
1380
1870
|
if (!session.parent) {
|
|
1381
1871
|
const project = session.mapping.agent.projectRoot;
|
|
@@ -1384,6 +1874,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1384
1874
|
const board = renderBoard(await boardOf(project));
|
|
1385
1875
|
if (board) parts.push(board);
|
|
1386
1876
|
}
|
|
1877
|
+
if (checkpoint) parts.push(`The checkpoint you wrote before the compaction, by skill compact:\n${cut(checkpoint, BRIEF_CHARS)}`);
|
|
1387
1878
|
parts.push('Carry on where you were; alp_board and alp_task tell you more.');
|
|
1388
1879
|
if (session.closed) return;
|
|
1389
1880
|
post(sessionId, { kind: 'note', from: 'alp', assignment: sessionId, body: parts.join('\n\n'), ...(session.active ? {} : { passive: true }) });
|
|
@@ -1478,10 +1969,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1478
1969
|
* Asks the user to approve a proposal and waits for the answer. Only an approving
|
|
1479
1970
|
* answer approves; a dismissal, a timeout or another answer does not.
|
|
1480
1971
|
*/
|
|
1481
|
-
async function confirm(sessionId: string, session: Session, body: string): Promise<{ approved: boolean; feedback?: string; outcome?: string }> {
|
|
1482
|
-
if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId)) return { approved: false, outcome: 'busy', feedback: 'A question is already waiting for the user' };
|
|
1972
|
+
async function confirm(sessionId: string, session: Session, body: string, approval?: { id: string }): Promise<{ approved: boolean; feedback?: string; outcome?: string }> {
|
|
1973
|
+
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' };
|
|
1483
1974
|
const say = wordsFor(session);
|
|
1484
|
-
const result = await askUser(sessionId, session, undefined, body, [say.approve, say.reject]) as { contentItems: Array<{ text: string }> };
|
|
1975
|
+
const result = await askUser(sessionId, session, undefined, body, [say.approve, say.reject], approval) as { contentItems: Array<{ text: string }> };
|
|
1485
1976
|
let value: any;
|
|
1486
1977
|
try { value = JSON.parse(result.contentItems[0].text); } catch { value = {}; }
|
|
1487
1978
|
if (value.status !== 'answered') return { approved: false, outcome: value.status ?? 'canceled', ...(value.reason ? { feedback: value.reason } : {}) };
|
|
@@ -1489,18 +1980,25 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1489
1980
|
return APPROVALS.includes(answer.toLowerCase()) ? { approved: true } : { approved: false, outcome: 'answered', feedback: answer };
|
|
1490
1981
|
}
|
|
1491
1982
|
|
|
1492
|
-
const declined = (decision: { feedback?: string; outcome?: string }) => toolResult(true, {
|
|
1493
|
-
approved: false,
|
|
1494
|
-
outcome: decision.outcome,
|
|
1495
|
-
...(decision.feedback ? { feedback: decision.feedback } : {}),
|
|
1496
|
-
next: 'Nothing was saved or posted. Revise from the feedback and propose again, or drop it.',
|
|
1497
|
-
});
|
|
1498
|
-
|
|
1499
1983
|
const text = (value: unknown, limit: number) => typeof value === 'string' && !!value.trim() && value.length <= limit;
|
|
1500
1984
|
|
|
1985
|
+
// Approvals of alp_issue and alp_skill (#114, #116): the tool returns a pending id at once and the
|
|
1986
|
+
// decision comes as result mail. Draft identities stay until session close, so a replayed tool
|
|
1987
|
+
// call or turn never applies an approved draft twice. Interrupting a session cancels its approvals.
|
|
1988
|
+
const approvalCancellation = new WeakMap<Session, number>();
|
|
1989
|
+
const approvalLedger = new Map<string, Map<string, { approvalId: string; draftKey: string; result?: Record<string, unknown> }>>();
|
|
1990
|
+
const approvalsOf = (sessionId: string) => {
|
|
1991
|
+
let approvals = approvalLedger.get(sessionId);
|
|
1992
|
+
if (!approvals) approvalLedger.set(sessionId, approvals = new Map());
|
|
1993
|
+
return approvals;
|
|
1994
|
+
};
|
|
1995
|
+
const approvalCanceled = (session: Session, cancellation: number) => closed || session.closed || cancellation !== (approvalCancellation.get(session) ?? 0);
|
|
1996
|
+
|
|
1501
1997
|
async function skillTool(sessionId: string, session: Session, args: unknown) {
|
|
1998
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
1999
|
+
args = structuredClone(args);
|
|
1502
2000
|
if (
|
|
1503
|
-
!plainObject(args, ['name', 'description', 'body', 'roles', 'lessons', 'replace']) ||
|
|
2001
|
+
!plainObject(args, ['name', 'description', 'body', 'roles', 'lessons', 'replace', 'requestId']) ||
|
|
1504
2002
|
typeof args.name !== 'string' || !/^[a-z0-9][a-z0-9-]{1,62}$/.test(args.name) ||
|
|
1505
2003
|
!text(args.description, 300) || !text(args.body, SKILL_BODY_CHARS) ||
|
|
1506
2004
|
!Array.isArray(args.roles) || !args.roles.length || args.roles.length > 10 || !args.roles.every((role: unknown) => typeof role === 'string' && /^[\w.-]+$/.test(role) && role !== '.' && role !== '..') ||
|
|
@@ -1509,14 +2007,36 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1509
2007
|
) {
|
|
1510
2008
|
return toolResult(false, { error: `A skill needs a name (lowercase letters, digits, hyphens), a one-line description, a body of at most ${SKILL_BODY_CHARS} characters, and the roles that get it` });
|
|
1511
2009
|
}
|
|
1512
|
-
if (!
|
|
1513
|
-
const
|
|
2010
|
+
if (args.requestId !== undefined && !text(args.requestId, 100)) return toolResult(false, { error: 'requestId must be a nonempty string of at most 100 characters' });
|
|
2011
|
+
const library = options.libraryDir;
|
|
2012
|
+
if (!library) return toolResult(false, { error: 'This host keeps no user skill library' });
|
|
2013
|
+
const known = new Set([...STARTER_ROLES, ...await discoverAgents(session.mapping.agent.projectRoot, { library, templates: options.templates })]);
|
|
1514
2014
|
const unknown = args.roles.filter((role: string) => !known.has(role));
|
|
1515
2015
|
if (unknown.length) return toolResult(false, { error: `Unknown roles: ${unknown.join(', ')}. Roles are ${[...known].join(', ')}` });
|
|
1516
|
-
const file = path.join(
|
|
2016
|
+
const file = path.join(library, 'skills', args.name, 'SKILL.md');
|
|
2017
|
+
const content = `---\nname: ${args.name}\ndescription: ${JSON.stringify(args.description.replace(/\s+/g, ' ').trim())}\n---\n\n${args.body.trim()}\n`;
|
|
2018
|
+
const normalizeLesson = (lesson: string) => lesson.replace(/\s+/g, ' ').trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, '').trim();
|
|
2019
|
+
const lessons: string[] = [...new Set<string>((args.lessons ?? []).map(normalizeLesson))];
|
|
2020
|
+
// A replay of a proposed draft returns its approval, before anything it changed is checked again.
|
|
2021
|
+
const draftKey = JSON.stringify(['skill', content, args.roles, lessons, !!args.replace]);
|
|
2022
|
+
const key = `skill:${args.requestId ?? draftKey}`;
|
|
2023
|
+
const approvals = approvalsOf(sessionId);
|
|
2024
|
+
const previous = approvals.get(key);
|
|
2025
|
+
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: 'requestId was already used for a different draft' });
|
|
2026
|
+
if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId, file });
|
|
1517
2027
|
const existing = await readFile(file, 'utf8').catch(() => undefined);
|
|
1518
2028
|
if (existing !== undefined && !args.replace) return toolResult(false, { error: `The library already has a skill named ${args.name} (${file}); read it, then pass replace: true to propose a new version, or choose another name` });
|
|
1519
|
-
|
|
2029
|
+
// A new skill meets the Agent Skills format strictly (skill-validate.js). alp_skill writes only SKILL.md,
|
|
2030
|
+
// so the body may point only at files the skill's directory already holds (a replaced skill's references).
|
|
2031
|
+
const invalid = checkFrontmatter(splitSkill(content).frontmatter, args.name, { strict: true }).findings.filter(finding => finding.level === 'error');
|
|
2032
|
+
if (invalid.length) return toolResult(false, { error: `The skill does not meet the skill format: ${invalid.map(finding => finding.message).join('; ')}` });
|
|
2033
|
+
const missing: string[] = [];
|
|
2034
|
+
for (const target of skillReferences(args.body)) {
|
|
2035
|
+
const resolved = path.resolve(path.dirname(file), target);
|
|
2036
|
+
if (path.isAbsolute(target) || path.relative(path.dirname(file), resolved).startsWith('..') || !(await stat(resolved).then(() => true, () => false))) missing.push(target);
|
|
2037
|
+
}
|
|
2038
|
+
if (missing.length) return toolResult(false, { error: `The body points to ${missing.join(', ')}, which the skill would not have: alp_skill saves only SKILL.md. Put that content in the body, or ask the user to add the files to ${path.dirname(file)} first` });
|
|
2039
|
+
const rolesFile = path.join(library, 'role-skills.json');
|
|
1520
2040
|
const readRoles = async () => {
|
|
1521
2041
|
const raw = await readFile(rolesFile, 'utf8').catch(() => '{}');
|
|
1522
2042
|
const roles = JSON.parse(raw);
|
|
@@ -1524,49 +2044,394 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1524
2044
|
return roles as Record<string, unknown>;
|
|
1525
2045
|
};
|
|
1526
2046
|
try { await readRoles(); } catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
1527
|
-
|
|
1528
|
-
|
|
2047
|
+
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: 'Skill proposal canceled or session closed; no approval was created' });
|
|
2048
|
+
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' });
|
|
2049
|
+
const approvalId = `q-${randomUUID()}`;
|
|
2050
|
+
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
2051
|
+
approvals.set(key, record);
|
|
1529
2052
|
const say = wordsFor(session);
|
|
1530
|
-
|
|
2053
|
+
// The user sees the whole skill, as it will be saved.
|
|
2054
|
+
const decision = confirm(sessionId, session,
|
|
1531
2055
|
say.skill(session.mapping.agent.name, existing !== undefined, file, args.roles.join(', '), lessons) +
|
|
1532
|
-
`\n${say.answerLine(session.mapping.agent.name)}\n\n${content}
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
roles
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
2056
|
+
`\n${say.answerLine(session.mapping.agent.name)}\n\n${content}`, { id: approvalId });
|
|
2057
|
+
const save = async (): Promise<Record<string, unknown>> => {
|
|
2058
|
+
// A skill of this name saved meanwhile is not overwritten by a proposal that was not a replacement.
|
|
2059
|
+
if (existing === undefined && !args.replace && await readFile(file, 'utf8').then(() => true, () => false)) {
|
|
2060
|
+
return { approved: true, saved: false, error: `A skill named ${args.name} was saved meanwhile (${file}); nothing was overwritten`, next: 'Read it, then propose again with replace: true if yours should replace it.' };
|
|
2061
|
+
}
|
|
2062
|
+
try {
|
|
2063
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
2064
|
+
await writeFile(file, content);
|
|
2065
|
+
const roles = await readRoles();
|
|
2066
|
+
for (const role of args.roles) {
|
|
2067
|
+
const list = Array.isArray(roles[role]) ? roles[role] as string[] : [];
|
|
2068
|
+
if (!list.includes(args.name)) list.push(args.name);
|
|
2069
|
+
roles[role] = list;
|
|
2070
|
+
}
|
|
2071
|
+
// Atomic, as alp_skill_retire writes it: a reader never sees a half-written role-skills.json.
|
|
2072
|
+
await writeAtomic(rolesFile, JSON.stringify(roles, null, 2) + '\n');
|
|
2073
|
+
} catch (error) {
|
|
2074
|
+
return { approved: true, saved: false, error: errorData(error).message, next: 'Tell the user; nothing is retried automatically.' };
|
|
2075
|
+
}
|
|
2076
|
+
// Compare exact rule text after normalizing whitespace and the optional recorded date.
|
|
2077
|
+
const removed = new Set<string>();
|
|
2078
|
+
for (const lessonFile of lessonFiles(session.mapping)) {
|
|
2079
|
+
const current = await readFile(lessonFile, 'utf8').catch(() => undefined);
|
|
2080
|
+
if (current === undefined) continue;
|
|
2081
|
+
const kept = current.split('\n').filter(line => {
|
|
2082
|
+
const match = /^- \d{4}-\d\d-\d\d: (.*)$/.exec(line);
|
|
2083
|
+
if (!match) return true;
|
|
2084
|
+
const lesson = normalizeLesson(line);
|
|
2085
|
+
if (!lessons.includes(lesson)) return true;
|
|
2086
|
+
removed.add(lesson);
|
|
2087
|
+
return false;
|
|
2088
|
+
});
|
|
2089
|
+
if (kept.length !== current.split('\n').length) await writeFile(lessonFile, kept.join('\n')).catch(() => {});
|
|
2090
|
+
}
|
|
2091
|
+
runLog(rootOf(sessionId), { event: 'skill', agent: session.mapping.agent.name, name: args.name, roles: args.roles, replaced: existing !== undefined, lessons: [...removed] });
|
|
2092
|
+
return {
|
|
2093
|
+
approved: true, saved: file, roles: args.roles, lessonsRemoved: [...removed],
|
|
2094
|
+
...(lessons.length > removed.size ? { lessonsNotFound: lessons.filter(lesson => !removed.has(lesson)) } : {}),
|
|
2095
|
+
next: 'New sessions of those roles list the skill; read the file now if you need it in this one.',
|
|
2096
|
+
};
|
|
2097
|
+
};
|
|
2098
|
+
void (async () => {
|
|
2099
|
+
const answer = await decision;
|
|
2100
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
2101
|
+
const result = !answer.approved || canceled
|
|
2102
|
+
? { approved: false, saved: false, outcome: canceled ? 'canceled' : answer.outcome, ...(answer.feedback ? { feedback: answer.feedback } : {}), next: 'Nothing was saved. Revise from the feedback and propose again with a fresh requestId, or drop it.' }
|
|
2103
|
+
: await save();
|
|
2104
|
+
record.result = { status: 'resolved', approvalId, name: args.name, ...result };
|
|
2105
|
+
runLog(rootOf(sessionId), { event: 'skill.approval', agent: session.mapping.agent.name, ...record.result });
|
|
2106
|
+
if (!closed && !session.closed && sessions.get(sessionId) === session) {
|
|
2107
|
+
// Result mail renews the bounded wake allowance and reaches this main only.
|
|
2108
|
+
post(sessionId, { kind: 'result', from: 'ALP', assignment: approvalId, body: `Skill approval result: ${JSON.stringify(record.result)}` });
|
|
2109
|
+
}
|
|
2110
|
+
})();
|
|
2111
|
+
return toolResult(true, { status: 'pending_approval', approvalId, file, next: 'Continue other work or end your turn. ALP sends the user\'s decision, and whether the skill was saved, by mail; do not resubmit this draft.' });
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
/**
|
|
2115
|
+
* alp_skill_retire: the only way an agent removes a library skill. Through the same
|
|
2116
|
+
* approval as alp_skill, and only once the user approves, the skill directory moves to
|
|
2117
|
+
* <library>/retired-skills/<name>-<time> (kept, never deleted) and leaves role-skills.json.
|
|
2118
|
+
* A skill an agent.json still names stays, and the result says who uses it.
|
|
2119
|
+
*/
|
|
2120
|
+
async function skillRetireTool(sessionId: string, session: Session, args: unknown) {
|
|
2121
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
2122
|
+
args = structuredClone(args);
|
|
2123
|
+
if (!plainObject(args, ['name', 'reason', 'requestId']) || typeof args.name !== 'string' || !/^[a-z0-9][a-z0-9-]{1,62}$/.test(args.name) || !text(args.reason, 300)) {
|
|
2124
|
+
return toolResult(false, { error: 'Retiring a skill needs its name (lowercase letters, digits, hyphens) and a one-line reason of at most 300 characters' });
|
|
1546
2125
|
}
|
|
1547
|
-
|
|
1548
|
-
const
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
2126
|
+
if (args.requestId !== undefined && !text(args.requestId, 100)) return toolResult(false, { error: 'requestId must be a nonempty string of at most 100 characters' });
|
|
2127
|
+
const library = options.libraryDir;
|
|
2128
|
+
if (!library) return toolResult(false, { error: 'This host keeps no user skill library' });
|
|
2129
|
+
const directory = path.join(library, 'skills', args.name);
|
|
2130
|
+
const file = path.join(directory, 'SKILL.md');
|
|
2131
|
+
const reason = args.reason.replace(/\s+/g, ' ').trim();
|
|
2132
|
+
const draftKey = JSON.stringify(['skill.retire', args.name, reason]);
|
|
2133
|
+
const key = `skill.retire:${args.requestId ?? draftKey}`;
|
|
2134
|
+
const approvals = approvalsOf(sessionId);
|
|
2135
|
+
const previous = approvals.get(key);
|
|
2136
|
+
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: 'requestId was already used for a different draft' });
|
|
2137
|
+
if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId, file });
|
|
2138
|
+
const content = await readFile(file, 'utf8').catch(() => undefined);
|
|
2139
|
+
if (content === undefined) return toolResult(false, { error: `The library has no skill named ${args.name} (${file})` });
|
|
2140
|
+
const rolesFile = path.join(library, 'role-skills.json');
|
|
2141
|
+
const readRoles = async () => {
|
|
2142
|
+
const roles = JSON.parse(await readFile(rolesFile, 'utf8').catch(() => '{}'));
|
|
2143
|
+
if (!roles || typeof roles !== 'object' || Array.isArray(roles)) throw new Error(`${rolesFile} must be an object of role names to skill lists`);
|
|
2144
|
+
return roles as Record<string, unknown>;
|
|
2145
|
+
};
|
|
2146
|
+
const holders = (roles: Record<string, unknown>) => Object.keys(roles).filter(role => Array.isArray(roles[role]) && (roles[role] as unknown[]).includes(args.name)).sort();
|
|
2147
|
+
// Agents naming the skill in their own agent.json, read directly (not merged with
|
|
2148
|
+
// role-skills.json). An unreadable agent.json throws, so the check fails closed.
|
|
2149
|
+
const namedBy = async () => {
|
|
2150
|
+
const found: string[] = [];
|
|
2151
|
+
for (const [agent, source] of await agentSources(session.mapping.agent.projectRoot, { library, templates: options.templates })) {
|
|
2152
|
+
const where = source.directory ? path.join(source.directory, 'agent.json') : `built-in agents/${agent}/agent.json`;
|
|
2153
|
+
const body = source.directory
|
|
2154
|
+
? await readFile(path.join(source.directory, 'agent.json'), 'utf8').catch((error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT') return undefined; throw error; })
|
|
2155
|
+
: await builtinText(`agents/${agent}/agent.json`, options.templates);
|
|
2156
|
+
if (body === undefined) continue;
|
|
2157
|
+
let config: unknown;
|
|
2158
|
+
try { config = JSON.parse(body); } catch (error) { throw new Error(`${where}: ${errorData(error).message}`); }
|
|
2159
|
+
const skills = config && typeof config === 'object' ? (config as { skills?: unknown }).skills : undefined;
|
|
2160
|
+
if (Array.isArray(skills) && skills.includes(args.name)) found.push(`agent ${agent}`);
|
|
2161
|
+
}
|
|
2162
|
+
return found.sort();
|
|
2163
|
+
};
|
|
2164
|
+
// The whole skill directory, so a change to any file in it is seen at approval time.
|
|
2165
|
+
const digest = async () => {
|
|
2166
|
+
const hash = createHash('sha256');
|
|
2167
|
+
const walk = async (dir: string, rel: string): Promise<void> => {
|
|
2168
|
+
for (const entry of (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
2169
|
+
const name = rel ? `${rel}/${entry.name}` : entry.name;
|
|
2170
|
+
if (entry.isDirectory()) { hash.update(`d:${name}\0`); await walk(path.join(dir, entry.name), name); }
|
|
2171
|
+
else { hash.update(`f:${name}\0`); hash.update(await readFile(path.join(dir, entry.name))); hash.update('\0'); }
|
|
2172
|
+
}
|
|
2173
|
+
};
|
|
2174
|
+
await walk(directory, '');
|
|
2175
|
+
return hash.digest('hex');
|
|
2176
|
+
};
|
|
2177
|
+
let given: string[];
|
|
2178
|
+
let users: string[];
|
|
2179
|
+
let tree: string;
|
|
2180
|
+
try { given = holders(await readRoles()); users = await namedBy(); tree = await digest(); } catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
2181
|
+
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: 'Skill retirement canceled or session closed; no approval was created' });
|
|
2182
|
+
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 to retire a skill' });
|
|
2183
|
+
const retired = path.join(library, 'retired-skills', `${args.name}-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
|
2184
|
+
const restore = `The user restores it with: alp skill restore ${args.name} (or by moving ${retired} back to ${directory} and adding it to the roles again in role-skills.json).`;
|
|
2185
|
+
const approvalId = `q-${randomUUID()}`;
|
|
2186
|
+
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
2187
|
+
approvals.set(key, record);
|
|
2188
|
+
const say = wordsFor(session);
|
|
2189
|
+
const decision = confirm(sessionId, session,
|
|
2190
|
+
say.skillRetire(session.mapping.agent.name, args.name, file, retired, given.join(', '), users.join(', '), reason) +
|
|
2191
|
+
`\n${say.answerLine(session.mapping.agent.name)}\n\n${content}`, { id: approvalId });
|
|
2192
|
+
const retire = async (): Promise<Record<string, unknown>> => {
|
|
2193
|
+
const refuse = (error: string, next: string) => ({ approved: true, retired: false, error, next });
|
|
2194
|
+
let before: string | undefined;
|
|
2195
|
+
try {
|
|
2196
|
+
if (await digest().catch(() => undefined) !== tree) {
|
|
2197
|
+
return refuse(`The skill ${args.name} changed or was removed since it was proposed; nothing was retired`, 'Read it again and propose again if it should still go.');
|
|
2198
|
+
}
|
|
2199
|
+
const now = await namedBy();
|
|
2200
|
+
if (now.length) return refuse(`The skill ${args.name} is still named by ${now.join(', ')}; nothing was retired`, 'Tell the user; they change those agents first.');
|
|
2201
|
+
// Re-read just before writing, so the write starts from the current file.
|
|
2202
|
+
before = await readFile(rolesFile, 'utf8').catch((error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT') return undefined; throw error; });
|
|
2203
|
+
const roles = await readRoles();
|
|
2204
|
+
const lost = holders(roles);
|
|
2205
|
+
if (JSON.stringify(lost) !== JSON.stringify(given)) {
|
|
2206
|
+
return refuse(`The roles that have ${args.name} changed since it was proposed (proposed: ${given.join(', ') || 'none'}; now: ${lost.join(', ') || 'none'}); nothing was retired`, 'Propose again so the user sees the current roles.');
|
|
2207
|
+
}
|
|
2208
|
+
await mkdir(path.dirname(retired), { recursive: true, mode: 0o700 });
|
|
2209
|
+
if (lost.length) {
|
|
2210
|
+
for (const role of lost) roles[role] = (roles[role] as unknown[]).filter(name => name !== args.name);
|
|
2211
|
+
await writeAtomic(rolesFile, JSON.stringify(roles, null, 2) + '\n');
|
|
2212
|
+
}
|
|
2213
|
+
try {
|
|
2214
|
+
await moveFile(directory, retired);
|
|
2215
|
+
} catch (error) {
|
|
2216
|
+
// Put role-skills.json back as it was, so a failed move changes nothing.
|
|
2217
|
+
if (lost.length) {
|
|
2218
|
+
try { if (before === undefined) await rm(rolesFile, { force: true }); else await writeAtomic(rolesFile, before); }
|
|
2219
|
+
catch (undo) { return refuse(`${errorData(error).message}; restoring ${rolesFile} also failed: ${errorData(undo).message}`, `Tell the user: the skill is still in ${directory} but ${rolesFile} lost it for ${lost.join(', ')}.`); }
|
|
2220
|
+
}
|
|
2221
|
+
return refuse(`${errorData(error).message}; nothing was retired`, 'Tell the user; nothing is retried automatically.');
|
|
2222
|
+
}
|
|
2223
|
+
// What `alp skill restore` reads to give the skill back to the same roles. The skill is
|
|
2224
|
+
// retired either way; without the file a restore needs --roles.
|
|
2225
|
+
let metadata: string | undefined;
|
|
2226
|
+
try {
|
|
2227
|
+
await writeAtomic(path.join(retired, 'retired.json'), JSON.stringify({ name: args.name, roles: lost, retiredAt: new Date().toISOString(), agent: session.mapping.agent.name, path: directory }, null, 2) + '\n');
|
|
2228
|
+
} catch (error) { metadata = errorData(error).message; }
|
|
2229
|
+
runLog(rootOf(sessionId), { event: 'skill.retire', agent: session.mapping.agent.name, name: args.name, roles: lost, retiredTo: retired, ...(metadata ? { metadataError: metadata } : {}) });
|
|
2230
|
+
return { approved: true, retired, roles: lost, ...(metadata ? { metadataError: metadata } : {}), next: `New sessions no longer list the skill. ${restore}` };
|
|
2231
|
+
} catch (error) {
|
|
2232
|
+
return refuse(`${errorData(error).message}; nothing was retired`, 'Tell the user; nothing is retried automatically.');
|
|
2233
|
+
}
|
|
2234
|
+
};
|
|
2235
|
+
void (async () => {
|
|
2236
|
+
const answer = await decision;
|
|
2237
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
2238
|
+
const result = !answer.approved || canceled
|
|
2239
|
+
? { approved: false, retired: false, outcome: canceled ? 'canceled' : answer.outcome, ...(answer.feedback ? { feedback: answer.feedback } : {}), next: 'Nothing was retired. Revise from the feedback and propose again with a fresh requestId, or drop it.' }
|
|
2240
|
+
: await retire();
|
|
2241
|
+
record.result = { status: 'resolved', approvalId, name: args.name, ...result };
|
|
2242
|
+
runLog(rootOf(sessionId), { event: 'skill.retire.approval', agent: session.mapping.agent.name, ...record.result });
|
|
2243
|
+
if (!closed && !session.closed && sessions.get(sessionId) === session) {
|
|
2244
|
+
post(sessionId, { kind: 'result', from: 'ALP', assignment: approvalId, body: `Skill retirement result: ${JSON.stringify(record.result)}` });
|
|
2245
|
+
}
|
|
2246
|
+
})();
|
|
2247
|
+
return toolResult(true, { status: 'pending_approval', approvalId, file, next: 'Continue other work or end your turn. ALP sends the user\'s decision, and whether the skill was retired, by mail; do not resubmit this request.' });
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
let scheduleHandler: ScheduleHandler | undefined;
|
|
2251
|
+
|
|
2252
|
+
/**
|
|
2253
|
+
* alp_lesson_curate: merges, shortenings and removals of recorded lessons, all shown to
|
|
2254
|
+
* the user in one approval and applied only when approved. Lessons are matched by their
|
|
2255
|
+
* exact rule text; nothing else in a lessons file changes.
|
|
2256
|
+
*/
|
|
2257
|
+
async function lessonCurateTool(sessionId: string, session: Session, args: unknown) {
|
|
2258
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
2259
|
+
args = structuredClone(args);
|
|
2260
|
+
type Change = { scope: 'project' | 'user'; remove: string[]; add?: string; reason?: string };
|
|
2261
|
+
const validChange = (change: any) => plainObject(change, ['scope', 'remove', 'add', 'reason']) && ['project', 'user'].includes(change.scope) &&
|
|
2262
|
+
Array.isArray(change.remove) && change.remove.length > 0 && change.remove.length <= 50 && change.remove.every((lesson: unknown) => text(lesson, LESSON_CHARS)) &&
|
|
2263
|
+
(change.add === undefined || text(change.add, LESSON_CHARS)) && (change.reason === undefined || (typeof change.reason === 'string' && change.reason.length <= 300));
|
|
2264
|
+
if (!plainObject(args, ['changes', 'requestId']) || !Array.isArray(args.changes) || !args.changes.length || args.changes.length > 50 || !args.changes.every(validChange)) {
|
|
2265
|
+
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` });
|
|
1559
2266
|
}
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
});
|
|
2267
|
+
if (args.requestId !== undefined && !text(args.requestId, 100)) return toolResult(false, { error: 'requestId must be a nonempty string of at most 100 characters' });
|
|
2268
|
+
const changes = args.changes as Change[];
|
|
2269
|
+
if (changes.some(change => change.scope === 'user') && !options.libraryDir) return toolResult(false, { error: 'This host keeps no user lessons' });
|
|
2270
|
+
const fileOf = (scope: string) => scope === 'user' ? path.join(options.libraryDir!, LESSONS_FILE) : path.join(session.mapping.agent.projectRoot, '.alp', LESSONS_FILE);
|
|
2271
|
+
const normalizeLesson = (lesson: string) => lesson.replace(/\s+/g, ' ').trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, '').trim();
|
|
2272
|
+
const normalized = changes.map(change => ({ ...change, remove: [...new Set(change.remove.map(normalizeLesson))], add: change.add?.replace(/\s+/g, ' ').trim() }));
|
|
2273
|
+
const draftKey = JSON.stringify(['lessons', normalized]);
|
|
2274
|
+
const key = `lessons:${args.requestId ?? draftKey}`;
|
|
2275
|
+
const approvals = approvalsOf(sessionId);
|
|
2276
|
+
const previous = approvals.get(key);
|
|
2277
|
+
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: 'requestId was already used for a different draft' });
|
|
2278
|
+
if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId });
|
|
2279
|
+
// Every lesson to remove must be recorded now; a proposal never guesses.
|
|
2280
|
+
const readLessons = async (file: string) => (await readFile(file, 'utf8').catch(() => '')).split('\n').flatMap(line => /^- \d{4}-\d\d-\d\d: /.test(line) ? [normalizeLesson(line)] : []);
|
|
2281
|
+
const missing: string[] = [];
|
|
2282
|
+
for (const change of normalized) {
|
|
2283
|
+
const recorded = new Set(await readLessons(fileOf(change.scope)));
|
|
2284
|
+
for (const lesson of change.remove) if (!recorded.has(lesson)) missing.push(`${change.scope}: ${lesson}`);
|
|
2285
|
+
}
|
|
2286
|
+
if (missing.length) return toolResult(false, { error: 'These lessons are not recorded; copy their exact text from the lessons files', missing });
|
|
2287
|
+
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: 'Lesson proposal canceled or session closed; no approval was created' });
|
|
2288
|
+
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' });
|
|
2289
|
+
const approvalId = `q-${randomUUID()}`;
|
|
2290
|
+
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
2291
|
+
approvals.set(key, record);
|
|
2292
|
+
const say = wordsFor(session);
|
|
2293
|
+
const shown = normalized.map((change, index) =>
|
|
2294
|
+
`${index + 1}. ${say.lessonScope(change.scope, fileOf(change.scope))}${change.reason ? ` — ${change.reason}` : ''}\n` +
|
|
2295
|
+
change.remove.map(lesson => ` ${say.lessonRemove}: ${lesson}`).join('\n') +
|
|
2296
|
+
(change.add ? `\n ${say.lessonAdd}: ${change.add}` : '')).join('\n\n');
|
|
2297
|
+
const decision = confirm(sessionId, session, `${say.lessonCurate(session.mapping.agent.name, shown)}\n\n${say.answerLine(session.mapping.agent.name)}`, { id: approvalId });
|
|
2298
|
+
const apply = async (): Promise<Record<string, unknown>> => {
|
|
2299
|
+
const removed: string[] = [];
|
|
2300
|
+
const notFound: string[] = [];
|
|
2301
|
+
let added = 0;
|
|
2302
|
+
for (const scope of ['project', 'user'] as const) {
|
|
2303
|
+
const mine = normalized.filter(change => change.scope === scope);
|
|
2304
|
+
if (!mine.length) continue;
|
|
2305
|
+
const file = fileOf(scope);
|
|
2306
|
+
const write = (lessonWrites.get(file) ?? Promise.resolve()).catch(() => {}).then(async () => {
|
|
2307
|
+
const current = await readFile(file, 'utf8').catch(() => undefined);
|
|
2308
|
+
if (current === undefined) { for (const change of mine) notFound.push(...change.remove.map(lesson => `${scope}: ${lesson}`)); return; }
|
|
2309
|
+
const targets = new Set(mine.flatMap(change => change.remove));
|
|
2310
|
+
const seen = new Set<string>();
|
|
2311
|
+
const kept = current.split('\n').filter(line => {
|
|
2312
|
+
if (!/^- \d{4}-\d\d-\d\d: /.test(line)) return true;
|
|
2313
|
+
const lesson = normalizeLesson(line);
|
|
2314
|
+
if (!targets.has(lesson)) return true;
|
|
2315
|
+
seen.add(lesson);
|
|
2316
|
+
return false;
|
|
2317
|
+
});
|
|
2318
|
+
for (const lesson of targets) (seen.has(lesson) ? removed : notFound).push(`${scope}: ${lesson}`);
|
|
2319
|
+
const date = new Date().toISOString().slice(0, 10);
|
|
2320
|
+
// A replacement whose lessons are all gone meanwhile would only duplicate what replaced them.
|
|
2321
|
+
const additions = mine.filter(change => change.add && change.remove.some(lesson => seen.has(lesson))).map(change => `- ${date}: ${change.add}`);
|
|
2322
|
+
added += additions.length;
|
|
2323
|
+
let body = kept.join('\n');
|
|
2324
|
+
if (additions.length) body = body.replace(/\n*$/, '\n') + additions.join('\n') + '\n';
|
|
2325
|
+
await writeFile(file, body);
|
|
2326
|
+
});
|
|
2327
|
+
lessonWrites.set(file, write);
|
|
2328
|
+
await write;
|
|
2329
|
+
}
|
|
2330
|
+
runLog(rootOf(sessionId), { event: 'lesson.curate', agent: session.mapping.agent.name, removed, added, notFound });
|
|
2331
|
+
return { approved: true, applied: true, removed, added, ...(notFound.length ? { lessonsNotFound: notFound } : {}) };
|
|
2332
|
+
};
|
|
2333
|
+
void (async () => {
|
|
2334
|
+
const answer = await decision;
|
|
2335
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
2336
|
+
let result: Record<string, unknown>;
|
|
2337
|
+
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.' };
|
|
2338
|
+
else {
|
|
2339
|
+
try { result = await apply(); }
|
|
2340
|
+
catch (error) { result = { approved: true, applied: false, error: errorData(error).message, next: 'Tell the user; nothing is retried automatically.' }; }
|
|
2341
|
+
}
|
|
2342
|
+
record.result = { status: 'resolved', approvalId, ...result };
|
|
2343
|
+
runLog(rootOf(sessionId), { event: 'lesson.curate.approval', agent: session.mapping.agent.name, ...record.result });
|
|
2344
|
+
if (!closed && !session.closed && sessions.get(sessionId) === session) post(sessionId, { kind: 'result', from: 'ALP', assignment: approvalId, body: `Lesson curate result: ${JSON.stringify(record.result)}` });
|
|
2345
|
+
})();
|
|
2346
|
+
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.' });
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
/**
|
|
2350
|
+
* The monthly curate: a supervised main keeps one pending job that wakes it on the first
|
|
2351
|
+
* of next month to run the curate skill. A job left by an earlier session of the project
|
|
2352
|
+
* is replaced, since it could not be delivered. settings curate.monthly false turns it off.
|
|
2353
|
+
*/
|
|
2354
|
+
const curateSchedules = new Map<string, Promise<unknown>>();
|
|
2355
|
+
function ensureCurateSchedule(sessionId: string) {
|
|
2356
|
+
const root = sessions.get(sessionId);
|
|
2357
|
+
if (!scheduleHandler || !root || root.closed || root.parent) return Promise.resolve();
|
|
2358
|
+
// One project's opens take turns, so two at once never leave two jobs.
|
|
2359
|
+
const project = root.mapping.agent.projectRoot;
|
|
2360
|
+
const run = (curateSchedules.get(project) ?? Promise.resolve()).catch(() => {}).then(() => curateScheduleOf(sessionId, root, project));
|
|
2361
|
+
curateSchedules.set(project, run);
|
|
2362
|
+
// The chain is dropped once nothing follows it.
|
|
2363
|
+
void run.catch(() => {}).then(() => { if (curateSchedules.get(project) === run) curateSchedules.delete(project); });
|
|
2364
|
+
return run;
|
|
2365
|
+
}
|
|
2366
|
+
|
|
2367
|
+
async function curateScheduleOf(sessionId: string, root: Session, project: string) {
|
|
2368
|
+
const handler = scheduleHandler;
|
|
2369
|
+
if (!handler || root.closed || sessions.get(sessionId) !== root) return;
|
|
2370
|
+
for (const file of [path.join(project, '.alp', 'settings.json'), ...(options.libraryDir ? [path.join(options.libraryDir, 'settings.json')] : [])]) {
|
|
2371
|
+
const settings = await readFile(file, 'utf8').then(raw => { try { return JSON.parse(raw); } catch { return undefined; } }, () => undefined);
|
|
2372
|
+
const monthly = settings?.curate?.monthly;
|
|
2373
|
+
if (monthly === false) return;
|
|
2374
|
+
if (monthly === true) break;
|
|
2375
|
+
}
|
|
2376
|
+
const listed = await handler('list', { projectRoot: project, status: 'pending' }) as { jobs?: Array<{ id: string; sessionId: string; prompt: string }> };
|
|
2377
|
+
const curate = (listed?.jobs ?? []).filter(job => job.prompt.startsWith(CURATE_MARKER));
|
|
2378
|
+
if (curate.some(job => job.sessionId === sessionId)) return;
|
|
2379
|
+
for (const job of curate) await handler('cancel', { id: job.id, projectRoot: project }).catch(() => {});
|
|
2380
|
+
const now = new Date();
|
|
2381
|
+
const dueAt = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 2)).toISOString();
|
|
2382
|
+
// The monthly job never keeps main open; a closed session's job fails and the next open makes another.
|
|
2383
|
+
await handler('create', { projectRoot: project, sessionId, dueAt, prompt: CURATE_PROMPT, keepsSession: false });
|
|
2384
|
+
runLog(sessionId, { event: 'curate.scheduled', dueAt, replaced: curate.map(job => job.id) });
|
|
2385
|
+
}
|
|
2386
|
+
|
|
2387
|
+
async function scheduleTool(sessionId: string, session: Session, args: unknown) {
|
|
2388
|
+
if (session.parent || session.role === 'supervisor' || session.mapping.agent.name !== mainOf(session.mapping)) return toolResult(false, { error: 'Only the main root session schedules continuations' });
|
|
2389
|
+
if (!scheduleHandler) return toolResult(false, { error: 'This host does not support scheduled continuations' });
|
|
2390
|
+
if (!plainObject(args, ['action', 'dueAt', 'prompt', 'requestId', 'id', 'status']) || !['create', 'list', 'get', 'cancel'].includes(args.action)) return toolResult(false, { error: 'Unknown schedule action' });
|
|
2391
|
+
const action = args.action as 'create' | 'list' | 'get' | 'cancel';
|
|
2392
|
+
const fields = action === 'create' ? ['action', 'dueAt', 'prompt', 'requestId'] : action === 'list' ? ['action', 'status'] : ['action', 'id'];
|
|
2393
|
+
if (Object.keys(args).some(key => !fields.includes(key))) return toolResult(false, { error: 'Unexpected schedule argument' });
|
|
2394
|
+
const handler = scheduleHandler;
|
|
2395
|
+
const projectRoot = session.mapping.agent.projectRoot;
|
|
2396
|
+
const invoke = async (params: Record<string, unknown>) => {
|
|
2397
|
+
try { return toolResult(true, await handler(action, { ...params, projectRoot })); }
|
|
2398
|
+
catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
2399
|
+
};
|
|
2400
|
+
if (action !== 'create') return invoke(action === 'list' ? { ...(args.status ? { status: args.status } : {}) } : { id: args.id });
|
|
2401
|
+
if (!text(args.requestId, 200) || !text(args.prompt, 8000) || !text(args.dueAt, 80) ||
|
|
2402
|
+
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/.test(args.dueAt) || !Number.isFinite(Date.parse(args.dueAt))) return toolResult(false, { error: 'create needs requestId, prompt (1–8000 characters) and dueAt with an explicit UTC offset' });
|
|
2403
|
+
const draftKey = JSON.stringify([args.dueAt, args.prompt]);
|
|
2404
|
+
const key = `schedule:${args.requestId}`;
|
|
2405
|
+
const approvals = approvalsOf(sessionId);
|
|
2406
|
+
const previous = approvals.get(key);
|
|
2407
|
+
if (previous) return previous.draftKey !== draftKey
|
|
2408
|
+
? toolResult(false, { error: 'requestId already names another schedule draft' })
|
|
2409
|
+
: toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId });
|
|
2410
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
2411
|
+
const approvalId = `q-${randomUUID()}`;
|
|
2412
|
+
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
2413
|
+
approvals.set(key, record);
|
|
2414
|
+
const decision = confirm(sessionId, session,
|
|
2415
|
+
`Tạo lịch tiếp tục một lần?\nProject: ${projectRoot}\nSession: ${sessionId}\nThời gian: ${args.dueAt} (${new Date(args.dueAt).toISOString()})\n\n${args.prompt}`, { id: approvalId });
|
|
2416
|
+
void decision.then(async answer => {
|
|
2417
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
2418
|
+
let result: Record<string, unknown>;
|
|
2419
|
+
if (!answer.approved || canceled) result = { approved: false, created: false, outcome: canceled ? 'canceled' : answer.outcome, feedback: answer.feedback };
|
|
2420
|
+
else {
|
|
2421
|
+
try { result = { approved: true, created: true, ...await handler('create', { projectRoot, sessionId, dueAt: args.dueAt, prompt: args.prompt }) as object }; }
|
|
2422
|
+
catch (error) { result = { approved: true, created: false, error: errorData(error).message }; }
|
|
2423
|
+
}
|
|
2424
|
+
record.result = { status: 'resolved', approvalId, ...result };
|
|
2425
|
+
runLog(rootOf(sessionId), { event: 'schedule.approval', ...record.result });
|
|
2426
|
+
if (!session.closed) post(sessionId, { kind: 'result', from: 'ALP', assignment: approvalId, body: `Schedule approval result: ${JSON.stringify(record.result)}` });
|
|
2427
|
+
}).catch(error => { record.result = { status: 'resolved', approvalId, created: false, error: errorData(error).message }; });
|
|
2428
|
+
return toolResult(true, { status: 'pending_approval', approvalId, next: 'Continue other work or end your turn. ALP sends the decision and creation result by mail; do not resubmit this draft.' });
|
|
1566
2429
|
}
|
|
1567
2430
|
|
|
1568
2431
|
async function issueTool(sessionId: string, session: Session, args: unknown) {
|
|
1569
|
-
|
|
2432
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
2433
|
+
args = structuredClone(args);
|
|
2434
|
+
if (!plainObject(args, ['action', 'target', 'query', 'title', 'body', 'issue', 'labels', 'requestId']) || !['search', 'create', 'comment'].includes(args.action) || !['project', 'alp'].includes(args.target)) {
|
|
1570
2435
|
return toolResult(false, { error: 'An issue call needs action (search, create or comment) and target (project or alp)' });
|
|
1571
2436
|
}
|
|
1572
2437
|
const project = session.mapping.agent.projectRoot;
|
|
@@ -1589,6 +2454,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1589
2454
|
if (args.labels !== undefined && (args.action !== 'create' || !Array.isArray(args.labels) || args.labels.length > 10 || !args.labels.every((label: unknown) => text(label, 50)))) {
|
|
1590
2455
|
return toolResult(false, { error: 'labels are up to 10 existing label names, for create' });
|
|
1591
2456
|
}
|
|
2457
|
+
if (args.requestId !== undefined && !text(args.requestId, 100)) return toolResult(false, { error: 'requestId must be a nonempty string of at most 100 characters' });
|
|
1592
2458
|
// Resolve labels before approval, so a draft with an unknown label never
|
|
1593
2459
|
// consumes the user's approval and then fails during issue creation.
|
|
1594
2460
|
if (args.action === 'create' && args.labels?.length) {
|
|
@@ -1601,24 +2467,48 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1601
2467
|
return toolResult(false, { repo, error: `Could not validate issue labels: ${errorData(error).message}` });
|
|
1602
2468
|
}
|
|
1603
2469
|
}
|
|
2470
|
+
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: 'Issue proposal canceled or session closed; no approval was created' });
|
|
2471
|
+
const draftKey = JSON.stringify([repo, args.action, args.title ?? null, args.issue ?? null, args.body, [...(args.labels ?? [])].sort()]);
|
|
2472
|
+
const key = `issue:${args.requestId ?? draftKey}`;
|
|
2473
|
+
const approvals = approvalsOf(sessionId);
|
|
2474
|
+
const previous = approvals.get(key);
|
|
2475
|
+
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: 'requestId was already used for a different draft' });
|
|
2476
|
+
if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId, repo });
|
|
2477
|
+
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' });
|
|
2478
|
+
const approvalId = `q-${randomUUID()}`;
|
|
2479
|
+
const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
|
|
2480
|
+
approvals.set(key, record);
|
|
1604
2481
|
const where = `${repo}${args.target === 'alp' ? ' (ALP itself)' : ''}`;
|
|
1605
2482
|
const say = wordsFor(session);
|
|
1606
|
-
const decision =
|
|
2483
|
+
const decision = confirm(sessionId, session,
|
|
1607
2484
|
say.issue(session.mapping.agent.name, args.action === 'create', args.issue, where) + '\n' +
|
|
1608
2485
|
`${say.answerLine(session.mapping.agent.name)}\n\n` +
|
|
1609
|
-
(args.action === 'create' ? `${say.issueTitle}: ${args.title}\n${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(', ')}\n` : ''}\n` : '') + args.body);
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
const
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
2486
|
+
(args.action === 'create' ? `${say.issueTitle}: ${args.title}\n${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(', ')}\n` : ''}\n` : '') + args.body.trim() + ISSUE_FOOTER, { id: approvalId });
|
|
2487
|
+
void (async () => {
|
|
2488
|
+
const answer = await decision;
|
|
2489
|
+
let result: Record<string, unknown>;
|
|
2490
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
2491
|
+
if (!answer.approved || canceled) {
|
|
2492
|
+
result = { approved: false, posted: false, outcome: canceled ? 'canceled' : answer.outcome, ...(answer.feedback ? { feedback: answer.feedback } : {}) };
|
|
2493
|
+
} else {
|
|
2494
|
+
try {
|
|
2495
|
+
const body = args.body.trim() + ISSUE_FOOTER;
|
|
2496
|
+
const output = args.action === 'create'
|
|
2497
|
+
? await github(['issue', 'create', '-R', repo, '--title', args.title, '--body-file', '-', ...(args.labels ?? []).flatMap((label: string) => ['--label', label])], { cwd: project, input: body })
|
|
2498
|
+
: await github(['issue', 'comment', String(args.issue), '-R', repo, '--body-file', '-'], { cwd: project, input: body });
|
|
2499
|
+
result = { approved: true, posted: true, url: output.trim().split('\n').at(-1) ?? '' };
|
|
2500
|
+
} catch (error) {
|
|
2501
|
+
result = { approved: true, posted: false, error: errorData(error).message, next: 'Tell the user; do not retry this draft automatically: GitHub may have accepted it before reporting an error.' };
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
record.result = { status: 'resolved', approvalId, repo, ...result };
|
|
2505
|
+
runLog(rootOf(sessionId), { event: 'issue.approval', action: args.action, ...(args.title ? { title: args.title } : {}), ...(args.issue ? { issue: args.issue } : {}), ...record.result });
|
|
2506
|
+
if (!closed && !session.closed && sessions.get(sessionId) === session) {
|
|
2507
|
+
// Result mail renews the bounded wake allowance and reaches this main only.
|
|
2508
|
+
post(sessionId, { kind: 'result', from: 'ALP', assignment: approvalId, body: `Issue approval result: ${JSON.stringify(record.result)}` });
|
|
2509
|
+
}
|
|
2510
|
+
})();
|
|
2511
|
+
return toolResult(true, { status: 'pending_approval', approvalId, repo, next: 'Continue other work. ALP sends the decision and posting result by mail; do not resubmit this draft.' });
|
|
1622
2512
|
}
|
|
1623
2513
|
|
|
1624
2514
|
/** Activity anywhere in a subtree keeps its ancestors' assignments alive. */
|
|
@@ -1645,6 +2535,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1645
2535
|
if (session && !session.closed) {
|
|
1646
2536
|
emit(sessionId, { type: 'mail', mail: publicEvent(mail) });
|
|
1647
2537
|
session.mail.push(mail);
|
|
2538
|
+
// New assignment progress deserves a fresh delivery allowance. Reset here,
|
|
2539
|
+
// never on redelivery, so a failing turn cannot retry the same mail forever.
|
|
2540
|
+
if (mail.kind === 'result' || mail.kind === 'question') session.wakes = 0;
|
|
2541
|
+
if (mail.kind === 'result' || mail.kind === 'question' || mail.kind === 'checkin') session.wakeFailures = 0;
|
|
1648
2542
|
deliver(sessionId, session);
|
|
1649
2543
|
}
|
|
1650
2544
|
return mail;
|
|
@@ -1666,14 +2560,16 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1666
2560
|
// with the next one, but never wake an idle requester on their own.
|
|
1667
2561
|
// Once none runs, what is left must still reach it, or a finished requester would never end.
|
|
1668
2562
|
const waking = !session.assignments.size || session.mail.some(event => !event.deliveredTurn && !event.passive && !(event.kind === 'note' && event.assignment !== sessionId));
|
|
2563
|
+
// A held idle session (a lifecycle operation, a pause, parked work) keeps its mail for the release.
|
|
2564
|
+
if (!session.active && waking && holdsWake(session)) { session.wakeHeld = true; return; }
|
|
1669
2565
|
if (session.pending) {
|
|
1670
2566
|
void session.acknowledged.then(() => deliver(sessionId, session));
|
|
1671
2567
|
} else if (session.active) {
|
|
1672
2568
|
// Deferred mail waits for the turn to end.
|
|
1673
|
-
if (session.mail.some(event => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
|
|
2569
|
+
if (!session.compacting && session.mail.some(event => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
|
|
1674
2570
|
} else if (!waking) {
|
|
1675
2571
|
return;
|
|
1676
|
-
} else if (!session.wakeBlocked && session.wakes < MAX_WAKES) {
|
|
2572
|
+
} else if (!session.wakeBlocked && session.wakeFailures < MAX_WAKES && (session.wakes < MAX_WAKES || session.mail.some(event => !event.deliveredTurn && event.kind === 'checkin'))) {
|
|
1677
2573
|
autoWake(sessionId, session);
|
|
1678
2574
|
} else if (session.parent && !session.wakeBlocked && !held(session)) {
|
|
1679
2575
|
// A child never gets the user prompt that resets its wakes; report instead of waiting out the watchdog.
|
|
@@ -1692,7 +2588,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1692
2588
|
try {
|
|
1693
2589
|
await session.runtime.request('turn/steer', { threadId: session.threadId, expectedTurnId: turnId, clientUserMessageId: id, input: [{ type: 'text', text, text_elements: [] }] });
|
|
1694
2590
|
steered = true;
|
|
1695
|
-
emit(sessionId, { type: 'item', item: { kind: 'user_message', id: `user:${id}`, clientMessageId: id, text } });
|
|
2591
|
+
emit(sessionId, { type: 'item', item: { kind: 'user_message', id: `user:${id}`, clientMessageId: id, text, origin: 'wake' } });
|
|
1696
2592
|
} catch {}
|
|
1697
2593
|
// If the turn ended meanwhile, receipt is uncertain: deliver again rather than lose mail.
|
|
1698
2594
|
const received = steered && session.active === turnId;
|
|
@@ -1710,7 +2606,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1710
2606
|
/** Queued behind client operations, so a wake never races a user prompt or an interrupt. */
|
|
1711
2607
|
function autoWake(sessionId: string, session: Session) {
|
|
1712
2608
|
// Its runtime is paused or it is parked: the mail waits for resume.
|
|
1713
|
-
if (
|
|
2609
|
+
if (holdsWake(session)) { session.wakeHeld = true; return; }
|
|
2610
|
+
// A check-in authorizes delivery of older mail too: the capped first batch
|
|
2611
|
+
// may not reach the check-in itself. Keep that authorization through queuing.
|
|
2612
|
+
const checkIn = session.mail.find(event => !event.deliveredTurn && event.kind === 'checkin');
|
|
1714
2613
|
const batch = takeBatch(session.mail, () => true);
|
|
1715
2614
|
if (!batch.length) return;
|
|
1716
2615
|
for (const event of batch) event.deliveredTurn = STARTING;
|
|
@@ -1719,16 +2618,22 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1719
2618
|
};
|
|
1720
2619
|
const work = queue.then(async () => {
|
|
1721
2620
|
if (closed || session.closed) return release();
|
|
2621
|
+
// A hold taken after this wake was queued (a rewind) keeps the mail for its release.
|
|
2622
|
+
if (holdsWake(session)) { release(); session.wakeHeld = true; return; }
|
|
1722
2623
|
// Whatever ran first decides: a running turn gets the mail by steering, an interrupt holds it.
|
|
1723
2624
|
if (session.wakeBlocked || session.active || session.pending) {
|
|
1724
2625
|
release();
|
|
1725
2626
|
return deliver(sessionId, session);
|
|
1726
2627
|
}
|
|
2628
|
+
// Earlier queued attempts may have consumed the allowance since delivery
|
|
2629
|
+
// reserved this batch. Keep retries bounded at the actual start boundary.
|
|
2630
|
+
if (session.wakeFailures >= MAX_WAKES || (session.wakes >= MAX_WAKES && (!checkIn || !session.mail.includes(checkIn)))) return release();
|
|
1727
2631
|
if (!batch.every(event => event.kind === 'checkin')) session.wakes++;
|
|
1728
2632
|
const id = `alp-wake-${randomUUID()}`;
|
|
1729
2633
|
try {
|
|
1730
2634
|
await startPrompt(sessionId, { clientMessageId: id, delivery: 'auto', content: [{ type: 'text', text: renderMail(batch, session.parentAgent) }] }, 'wake', batch);
|
|
1731
2635
|
} catch {
|
|
2636
|
+
session.wakeFailures++;
|
|
1732
2637
|
release();
|
|
1733
2638
|
deliver(sessionId, session);
|
|
1734
2639
|
}
|
|
@@ -1842,6 +2747,21 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1842
2747
|
}
|
|
1843
2748
|
}
|
|
1844
2749
|
|
|
2750
|
+
/**
|
|
2751
|
+
* The user wrote in the chat while main's own alp_ask question to them waits (#116): the question
|
|
2752
|
+
* ends now, so the message reaches main. Approvals, permission prompts and the hook-trust
|
|
2753
|
+
* question keep waiting for the user's decision.
|
|
2754
|
+
*/
|
|
2755
|
+
function releaseQuestions(sessionId: string) {
|
|
2756
|
+
for (const { question, settle, asked } of [...userQuestions.values()]) {
|
|
2757
|
+
if (question.sessionId !== sessionId || !asked) continue;
|
|
2758
|
+
settle('canceled', undefined, 'the user wrote instead of answering', toolResult(true, {
|
|
2759
|
+
status: 'user_wrote', userMessage: true, question: question.id,
|
|
2760
|
+
next: `${USER_WROTE} Their message may be the answer to your question; if it is not, ask again later.`,
|
|
2761
|
+
}));
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
|
|
1845
2765
|
const assignmentSnapshot = (assignment: Assignment, status: string): AssignmentSnapshot => ({
|
|
1846
2766
|
id: assignment.id,
|
|
1847
2767
|
agent: assignment.agent,
|
|
@@ -1859,7 +2779,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1859
2779
|
}
|
|
1860
2780
|
|
|
1861
2781
|
const { settleWorktree, worktreeTool, inCheckout, verifyIn, verificationResult, noteVerification, continuedBrief, verifyTool } = createWorktreeDomain({
|
|
1862
|
-
options, leases, rootOf, lineage, runLog, runHooks, touchTask,
|
|
2782
|
+
options, leases, rootOf, lineage, runLog, runHooks, touchTask, releaseResult: assignmentId => assignmentResults.remove(assignmentId),
|
|
1863
2783
|
});
|
|
1864
2784
|
|
|
1865
2785
|
/**
|
|
@@ -1888,20 +2808,44 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1888
2808
|
async function finishAssignment(parentId: string, parent: Session, assignment: Assignment, state: string, error?: unknown, quiet = false) {
|
|
1889
2809
|
if (assignment.finished) return;
|
|
1890
2810
|
assignment.finished = true;
|
|
2811
|
+
const child = assignmentSessions.get(assignment);
|
|
1891
2812
|
// alpd is stopping: the assignment stays in the live file and its task stays in progress, for the next alpd to continue.
|
|
1892
2813
|
if (closed && inFlight.get(assignment.id)) {
|
|
1893
2814
|
runLog(assignment.rootId, { event: 'assignment.interrupted', assignmentId: assignment.id, agent: assignment.agent, reason: 'alpd stopped' });
|
|
1894
|
-
await closeSession(assignment.id);
|
|
2815
|
+
if (child) await closeSession(assignment.id, child);
|
|
1895
2816
|
if (assignment.lease && leases.get(assignment.lease)?.assignment === assignment.id) leases.delete(assignment.lease);
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
2817
|
+
if (!sessions.has(assignment.id) || sessions.get(assignment.id) === child) {
|
|
2818
|
+
childContexts.delete(assignment.id);
|
|
2819
|
+
parent.children.delete(assignment.id);
|
|
2820
|
+
}
|
|
2821
|
+
if (parent.assignments.get(assignment.id) === assignment) parent.assignments.delete(assignment.id);
|
|
2822
|
+
return;
|
|
2823
|
+
}
|
|
2824
|
+
// Ownership must reach durable storage before recovery evidence can disappear.
|
|
2825
|
+
const resultChild = child;
|
|
2826
|
+
try {
|
|
2827
|
+
if (assignment.worktree || writes(assignment.mode)) await assignmentResults.put({
|
|
2828
|
+
assignmentId: assignment.id,
|
|
2829
|
+
checkout: assignment.worktree?.checkout ?? assignment.writeCheckout ?? resultChild?.mapping.workdir ?? parent.mapping.workdir,
|
|
2830
|
+
...(assignment.worktree ? { worktree: assignment.worktree.path } : {}),
|
|
2831
|
+
// Outside a worktree, the change stays in the checkout: keep its evidence until the requester resolves it.
|
|
2832
|
+
...(!assignment.worktree ? { result: {
|
|
2833
|
+
agent: assignment.agent, status: state, finishedAt: new Date().toISOString(),
|
|
2834
|
+
project: (resultChild ?? parent).mapping.agent.projectRoot, requesters: lineage(parentId), ...(assignment.taskId ? { taskId: assignment.taskId } : {}),
|
|
2835
|
+
brief: cut(resultChild?.brief ?? '', RESULT_EVIDENCE_CHARS),
|
|
2836
|
+
summary: cut(JSON.stringify({ handoff: resultChild?.handoff ?? null, output: resultChild ? [...resultChild.text.values()].at(-1) ?? '' : '', ...(error ? { error: errorData(error).message } : {}) }), RESULT_EVIDENCE_CHARS),
|
|
2837
|
+
} } : {}),
|
|
2838
|
+
});
|
|
2839
|
+
} catch (failure) {
|
|
2840
|
+
// Keep both the assignment and its recovery evidence; never close away unrecorded ownership.
|
|
2841
|
+
assignment.finished = false;
|
|
2842
|
+
log.error('could not persist assignment result ownership', { assignmentId: assignment.id, error: failure });
|
|
2843
|
+
post(parentId, { kind: 'note', from: assignment.agent, assignment: assignment.id, passive: true, body: `Assignment result ownership could not be saved: ${errorData(failure).message}. Restore the assignment result ledger before completing or removing this workspace.` });
|
|
1899
2844
|
return;
|
|
1900
2845
|
}
|
|
1901
|
-
//
|
|
2846
|
+
// A crash while finishing never runs finished work again.
|
|
1902
2847
|
void inFlight.remove(assignment.id);
|
|
1903
|
-
|
|
1904
|
-
if (child && state === 'failed' && child.active) terminal(assignment.id, child, 'failed', error);
|
|
2848
|
+
if (child && sessions.get(assignment.id) === child && state === 'failed' && child.active) terminal(assignment.id, child, 'failed', error);
|
|
1905
2849
|
assignment.ask?.resolve(toolResult(false, { error: 'Assignment ended' }));
|
|
1906
2850
|
|
|
1907
2851
|
// Interim commentary stays in the child timeline; the final message is the answer.
|
|
@@ -1915,7 +2859,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1915
2859
|
...(error ? { error: errorData(error).message } : {}),
|
|
1916
2860
|
};
|
|
1917
2861
|
|
|
1918
|
-
await closeSession(assignment.id);
|
|
2862
|
+
if (child) await closeSession(assignment.id, child);
|
|
1919
2863
|
// Its native thread stays on disk, so its requesters can ask it about its work later.
|
|
1920
2864
|
// An ACP agent cannot fork a session to answer questions about it.
|
|
1921
2865
|
if (child?.threadId && child.mapping.keepThread && child.runtimeKind !== 'acp') {
|
|
@@ -1961,9 +2905,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1961
2905
|
});
|
|
1962
2906
|
if (!parent.closed) emit(parentId, { type: 'assignment', assignment: assignmentSnapshot(assignment, state) });
|
|
1963
2907
|
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
2908
|
+
if (!sessions.has(assignment.id) || sessions.get(assignment.id) === child) {
|
|
2909
|
+
childContexts.delete(assignment.id);
|
|
2910
|
+
parent.children.delete(assignment.id);
|
|
2911
|
+
}
|
|
2912
|
+
if (parent.assignments.get(assignment.id) === assignment) parent.assignments.delete(assignment.id);
|
|
1967
2913
|
if (roleOf(parent.mapping, assignment.agent) === 'peer') {
|
|
1968
2914
|
const root = sessions.get(assignment.rootId);
|
|
1969
2915
|
if (root) root.peerCount--;
|
|
@@ -1991,7 +2937,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
1991
2937
|
}
|
|
1992
2938
|
|
|
1993
2939
|
if (
|
|
1994
|
-
!['alp_delegate', 'alp_handoff', 'alp_wait', 'alp_cancel', 'alp_send', 'alp_ask', 'alp_merge', 'alp_discard', 'alp_recall', 'alp_verify', 'alp_pin', 'alp_board', 'alp_unpin', 'alp_lesson', 'alp_skill', 'alp_issue', 'alp_task'].includes(params.tool) ||
|
|
2940
|
+
!['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_skill_retire', 'alp_issue', 'alp_task', 'alp_schedule'].includes(params.tool) ||
|
|
1995
2941
|
params.namespace != null ||
|
|
1996
2942
|
typeof params.callId !== 'string'
|
|
1997
2943
|
) {
|
|
@@ -2004,14 +2950,20 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2004
2950
|
if (cached) return cached;
|
|
2005
2951
|
|
|
2006
2952
|
const args = params.arguments;
|
|
2953
|
+
// Every transport's arguments, before any tool walks them: the Codex, ACP and Antigravity paths have no schema of their own.
|
|
2954
|
+
const oversized = inputLimitError(args, TOOL_INPUT, `${params.tool} input`);
|
|
2955
|
+
if (oversized) return toolResult(false, { error: oversized });
|
|
2007
2956
|
// The supervisor only reads the board and tasks, and writes to main.
|
|
2008
2957
|
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' });
|
|
2009
|
-
if (
|
|
2958
|
+
if (['alp_lesson', 'alp_lesson_curate', 'alp_skill', 'alp_skill_retire'].includes(params.tool) && !supervises(session)) return toolResult(false, { error: 'Only a supervised main records lessons and skills' });
|
|
2010
2959
|
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' });
|
|
2011
2960
|
const work =
|
|
2012
2961
|
params.tool === 'alp_lesson' ? lessonTool(sessionId, session, args)
|
|
2962
|
+
: params.tool === 'alp_lesson_curate' ? lessonCurateTool(sessionId, session, args)
|
|
2013
2963
|
: params.tool === 'alp_skill' ? skillTool(sessionId, session, args)
|
|
2964
|
+
: params.tool === 'alp_skill_retire' ? skillRetireTool(sessionId, session, args)
|
|
2014
2965
|
: params.tool === 'alp_issue' ? issueTool(sessionId, session, args)
|
|
2966
|
+
: params.tool === 'alp_schedule' ? scheduleTool(sessionId, session, args)
|
|
2015
2967
|
: params.tool === 'alp_task' ? taskToolCall(sessionId, session, args)
|
|
2016
2968
|
: params.tool === 'alp_delegate' ? runDelegation(sessionId, session, params)
|
|
2017
2969
|
: params.tool === 'alp_wait' ? waitTool(sessionId, session, args)
|
|
@@ -2020,6 +2972,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2020
2972
|
: params.tool === 'alp_board' ? boardTool(session, args)
|
|
2021
2973
|
: params.tool === 'alp_unpin' ? unpinTool(sessionId, session, args)
|
|
2022
2974
|
: params.tool === 'alp_recall' ? recallTool(sessionId, session, args)
|
|
2975
|
+
: params.tool === 'alp_resolve' ? resolveTool(sessionId, session, args)
|
|
2023
2976
|
: params.tool === 'alp_verify' ? verifyTool(sessionId, session, args)
|
|
2024
2977
|
: params.tool === 'alp_cancel' ? cancelTool(sessionId, session, args)
|
|
2025
2978
|
: params.tool === 'alp_merge' || params.tool === 'alp_discard' ? worktreeTool(sessionId, session, args, params.tool === 'alp_merge' ? 'merge' : 'discard')
|
|
@@ -2107,7 +3060,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2107
3060
|
const pending = [...session.assignments.keys()].some(id => !ids || ids.has(id)) || takeBatch(session.mail, event => event.kind !== 'board' && !event.defer && accept(event)).length > 0;
|
|
2108
3061
|
const events = pending ? await waitFor(sessionId, session, accept, Math.min(args.timeoutMs ?? 300_000, 900_000)) : [];
|
|
2109
3062
|
if (events === 'user') return toolResult(true, { events: [], userMessage: true, running: running(session), next: USER_WROTE });
|
|
2110
|
-
if (!events) return toolResult(false, { error: 'Turn ended' });
|
|
3063
|
+
if (!events) return toolResult(false, session.closed || session.wakeBlocked ? { error: 'Turn ended' } : { error: TURN_ENDED, running: running(session) });
|
|
2111
3064
|
return toolResult(true, { events: events.map(publicEvent), running: running(session) });
|
|
2112
3065
|
}
|
|
2113
3066
|
|
|
@@ -2149,10 +3102,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2149
3102
|
}
|
|
2150
3103
|
|
|
2151
3104
|
/** Asks the user; viewers show the question, and answer() or a timeout resolves it. */
|
|
2152
|
-
function askUser(sessionId: string, session: Session, assignment: Assignment | undefined, body: string, options?: string[]) {
|
|
3105
|
+
function askUser(sessionId: string, session: Session, assignment: Assignment | undefined, body: string, options?: string[], approval?: { id: string }, asked = false) {
|
|
2153
3106
|
const rootId = rootOf(sessionId);
|
|
2154
3107
|
const question: UserQuestion = {
|
|
2155
|
-
id: `q-${randomUUID().slice(0, 8)}`,
|
|
3108
|
+
id: approval?.id ?? `q-${randomUUID().slice(0, 8)}`,
|
|
2156
3109
|
sessionId,
|
|
2157
3110
|
rootId,
|
|
2158
3111
|
agent: session.mapping.agent.name,
|
|
@@ -2180,7 +3133,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2180
3133
|
next: 'Decide, and record the assumption in your handoff or final message; or report that you are blocked.',
|
|
2181
3134
|
})));
|
|
2182
3135
|
};
|
|
2183
|
-
userQuestions.set(question.id, { question, settle });
|
|
3136
|
+
userQuestions.set(question.id, { question, settle, persistent: !!approval, asked });
|
|
2184
3137
|
// The watchdog does not count time spent waiting for an answer.
|
|
2185
3138
|
if (assignment) assignment.ask = { id: question.id, resolve: result => settle('canceled', undefined, undefined, result) };
|
|
2186
3139
|
emit(sessionId, { type: 'question', question });
|
|
@@ -2198,13 +3151,212 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2198
3151
|
post(session.parent, { kind: 'note', from: session.mapping.agent.name, assignment: sessionId, body: `[ALP, on behalf of ${session.mapping.agent.name}] ${body}` });
|
|
2199
3152
|
}
|
|
2200
3153
|
|
|
2201
|
-
/**
|
|
2202
|
-
function cancelQuestions(sessionId: string) {
|
|
2203
|
-
for (const { question, settle } of [...userQuestions.values()]) {
|
|
2204
|
-
|
|
3154
|
+
/** Ordinary questions end with their turn; issue approvals survive until decision or session cancellation. */
|
|
3155
|
+
function cancelQuestions(sessionId: string, turnOnly = false) {
|
|
3156
|
+
for (const { question, settle, persistent, gate } of [...userQuestions.values()]) {
|
|
3157
|
+
// A gate card ends only with its gate or its session; syncGates shows it again on the next main.
|
|
3158
|
+
if (gate && turnOnly) continue;
|
|
3159
|
+
if (question.sessionId === sessionId && (!turnOnly || !persistent)) settle('canceled', undefined, undefined, toolResult(false, { error: 'Turn ended' }));
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
|
|
3163
|
+
// Human gates (t-ccac): .alp/tasks stays the source of truth. Each open human gate of a project
|
|
3164
|
+
// shows as a card on its live main root session, without a timeout and outside the one-question
|
|
3165
|
+
// limit; syncGates rebuilds the cards from the files (on start, attach, a gate change, a change
|
|
3166
|
+
// to the task files and a timer, since the CLI and Paseo's local panel write the files without
|
|
3167
|
+
// alpd) and tells main of every decision at least once (t-595d): the mail goes first, and
|
|
3168
|
+
// markGateNotified marks the decision only once a completed turn of main took it. Until then
|
|
3169
|
+
// the mail on its way is not sent again; after a restart it is, and its body tells main a repeat
|
|
3170
|
+
// changes nothing. With no live main, the decision waits for the project's next main.
|
|
3171
|
+
const gateSyncs = new Map<string, Promise<void>>();
|
|
3172
|
+
/** Decision mail on its way to main, by the decision it reports. */
|
|
3173
|
+
const gateMail = new WeakMap<MailEvent, { key: string; taken: () => void }>();
|
|
3174
|
+
/** Decisions main took whose mark is being written, or was. */
|
|
3175
|
+
const gateTaken = new Set<string>();
|
|
3176
|
+
/** Marks being written; shutdown waits for them, so nothing writes the task files after it. */
|
|
3177
|
+
const gateMarks = new Set<Promise<unknown>>();
|
|
3178
|
+
const gateCardId = (taskId: string, gateId: string) => `gate-${taskId}-${gateId}`;
|
|
3179
|
+
|
|
3180
|
+
/** The project's live main root session, if any. */
|
|
3181
|
+
function mainSessionOf(projectRoot: string) {
|
|
3182
|
+
for (const [id, session] of sessions) {
|
|
3183
|
+
if (session.closed || session.parent || session.role === 'supervisor' || !session.threadId) continue;
|
|
3184
|
+
if (session.mapping.agent.name !== mainOf(session.mapping) || path.resolve(session.mapping.agent.projectRoot) !== projectRoot) continue;
|
|
3185
|
+
return { id, session };
|
|
3186
|
+
}
|
|
3187
|
+
return undefined;
|
|
3188
|
+
}
|
|
3189
|
+
|
|
3190
|
+
function syncGates(projectRoot: string): Promise<void> {
|
|
3191
|
+
const root = path.resolve(projectRoot);
|
|
3192
|
+
const previous = gateSyncs.get(root) ?? Promise.resolve();
|
|
3193
|
+
const next = previous.then(() => syncGatesNow(root)).catch(error => { runLog(mainSessionOf(root)?.id ?? root, { event: 'gate.sync.failed', projectRoot: root, error: errorData(error).message }); });
|
|
3194
|
+
gateSyncs.set(root, next);
|
|
3195
|
+
void next.finally(() => { if (gateSyncs.get(root) === next) gateSyncs.delete(root); });
|
|
3196
|
+
return next;
|
|
3197
|
+
}
|
|
3198
|
+
|
|
3199
|
+
async function syncGatesNow(projectRoot: string) {
|
|
3200
|
+
if (closed) return;
|
|
3201
|
+
const { tasks } = await loadTasks(projectRoot);
|
|
3202
|
+
const main = mainSessionOf(projectRoot);
|
|
3203
|
+
// The user's decisions, to main at least once each; without a live main they wait for the next one.
|
|
3204
|
+
if (main) for (const { task, gate, decision, record } of gateDecisions(tasks)) {
|
|
3205
|
+
const key = JSON.stringify([projectRoot, task.id, gate.id, decision, record.at]);
|
|
3206
|
+
if (gateTaken.has(key) || main.session.mail.some(event => gateMail.get(event)?.key === key)) continue;
|
|
3207
|
+
const choice = decision === 'approved' ? (record as { choice?: string }).choice : undefined;
|
|
3208
|
+
const words = decision === 'approved'
|
|
3209
|
+
? `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}` : ''}.`
|
|
3210
|
+
: `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.`;
|
|
3211
|
+
const mail = post(main.id, { kind: 'result', from: 'ALP', assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words} Task: ${task.title}. If this decision of ${gateCardId(task.id, gate.id)} was reported to you before, it is a repeat: act on it once.` });
|
|
3212
|
+
gateMail.set(mail, {
|
|
3213
|
+
key,
|
|
3214
|
+
taken: () => {
|
|
3215
|
+
gateTaken.add(key);
|
|
3216
|
+
const mark = markGateNotified(projectRoot, task.id, gate.id, decision, record.at).catch(error => {
|
|
3217
|
+
// Unmarked, it is mailed again: once more is better than never.
|
|
3218
|
+
gateTaken.delete(key);
|
|
3219
|
+
runLog(main.id, { event: 'gate.mark.failed', projectRoot, taskId: task.id, gateId: gate.id, error: errorData(error).message });
|
|
3220
|
+
});
|
|
3221
|
+
gateMarks.add(mark);
|
|
3222
|
+
void mark.finally(() => gateMarks.delete(mark));
|
|
3223
|
+
},
|
|
3224
|
+
});
|
|
3225
|
+
runLog(main.id, { event: 'gate.decision', projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record.channel, ...(choice ? { choice } : {}) });
|
|
3226
|
+
}
|
|
3227
|
+
// A card for each open human gate the user has not rejected; a rejected one stays open for main to follow up.
|
|
3228
|
+
const wanted = new Map<string, { task: Task; gate: Task['gates'][number] }>();
|
|
3229
|
+
for (const task of tasks) {
|
|
3230
|
+
if (task.status === 'closed') continue;
|
|
3231
|
+
for (const gate of task.gates ?? []) if (gate.kind === 'human' && !gate.resolved && !gate.rejected) wanted.set(gateCardId(task.id, gate.id), { task, gate });
|
|
3232
|
+
}
|
|
3233
|
+
for (const [id, pending] of [...userQuestions]) {
|
|
3234
|
+
if (pending.question.gate?.projectRoot !== projectRoot) continue;
|
|
3235
|
+
const want = wanted.get(id);
|
|
3236
|
+
if (!want || !main || pending.question.sessionId !== main.id) {
|
|
3237
|
+
const task = tasks.find(entry => entry.id === pending.question.gate!.taskId);
|
|
3238
|
+
const gate = task?.gates.find(entry => entry.id === pending.question.gate!.gateId);
|
|
3239
|
+
pending.settle(gate?.resolved ? 'answered' : gate?.rejected ? 'dismissed' : 'canceled', gate?.resolved?.choice, gate?.rejected?.reason);
|
|
3240
|
+
} else if (pending.gate) pending.gate.rev = want.task.rev;
|
|
3241
|
+
}
|
|
3242
|
+
if (!main) return;
|
|
3243
|
+
for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
|
|
3244
|
+
}
|
|
3245
|
+
|
|
3246
|
+
/**
|
|
3247
|
+
* The CLI and Paseo's local Tasks panel write gates without alpd: while a main is live, a change
|
|
3248
|
+
* to the project's task files syncs at once (t-595d), and a timer reads them too, where file
|
|
3249
|
+
* events are missing or lost.
|
|
3250
|
+
*/
|
|
3251
|
+
let gateWatch: NodeJS.Timeout | undefined;
|
|
3252
|
+
const gateFiles = new Map<string, { watcher: FSWatcher; timer?: NodeJS.Timeout }>();
|
|
3253
|
+
function startGateWatch(projectRoot: string) {
|
|
3254
|
+
if (options.gateSyncMs === 0) return;
|
|
3255
|
+
watchGateFiles(path.resolve(projectRoot));
|
|
3256
|
+
if (gateWatch) return;
|
|
3257
|
+
gateWatch = setInterval(() => {
|
|
3258
|
+
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)));
|
|
3259
|
+
for (const root of roots) { watchGateFiles(root); void syncGates(root); }
|
|
3260
|
+
for (const root of gateFiles.keys()) if (!roots.has(root)) unwatchGateFiles(root);
|
|
3261
|
+
if (!roots.size) { clearInterval(gateWatch); gateWatch = undefined; }
|
|
3262
|
+
}, options.gateSyncMs ?? 5_000);
|
|
3263
|
+
gateWatch.unref?.();
|
|
3264
|
+
}
|
|
3265
|
+
|
|
3266
|
+
function watchGateFiles(root: string) {
|
|
3267
|
+
if (closed || gateFiles.has(root)) return;
|
|
3268
|
+
try {
|
|
3269
|
+
const entry: { watcher: FSWatcher; timer?: NodeJS.Timeout } = {
|
|
3270
|
+
// A burst of writes (a save, its ledger, a mark) syncs once.
|
|
3271
|
+
watcher: watchFiles(path.join(root, TASKS_DIR), () => {
|
|
3272
|
+
if (entry.timer || closed) return;
|
|
3273
|
+
entry.timer = setTimeout(() => { entry.timer = undefined; void syncGates(root); }, 50);
|
|
3274
|
+
entry.timer.unref?.();
|
|
3275
|
+
}),
|
|
3276
|
+
};
|
|
3277
|
+
entry.watcher.on('error', () => unwatchGateFiles(root));
|
|
3278
|
+
entry.watcher.unref?.();
|
|
3279
|
+
gateFiles.set(root, entry);
|
|
3280
|
+
} catch {} // No task files yet, or no file events here: the timer tries again.
|
|
3281
|
+
}
|
|
3282
|
+
|
|
3283
|
+
function unwatchGateFiles(root: string) {
|
|
3284
|
+
const entry = gateFiles.get(root);
|
|
3285
|
+
if (!entry) return;
|
|
3286
|
+
gateFiles.delete(root);
|
|
3287
|
+
clearTimeout(entry.timer);
|
|
3288
|
+
entry.watcher.close();
|
|
3289
|
+
}
|
|
3290
|
+
|
|
3291
|
+
function showGateCard(sessionId: string, session: Session, projectRoot: string, task: Task, gate: Task['gates'][number]) {
|
|
3292
|
+
const say = wordsFor(session);
|
|
3293
|
+
const vietnamese = say.approve === words('vi').approve;
|
|
3294
|
+
const question: UserQuestion = {
|
|
3295
|
+
id: gateCardId(task.id, gate.id),
|
|
3296
|
+
sessionId,
|
|
3297
|
+
rootId: rootOf(sessionId),
|
|
3298
|
+
agent: 'ALP',
|
|
3299
|
+
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 ?? ''}`,
|
|
3300
|
+
// Options approve; Reject (added after them unless one of them is that word) keeps the gate open.
|
|
3301
|
+
options: gate.options?.length ? (gate.options.includes(say.reject) ? gate.options : [...gate.options, say.reject]) : [say.approve, say.reject],
|
|
3302
|
+
askedAt: gate.at ?? new Date().toISOString(),
|
|
3303
|
+
gate: { projectRoot, taskId: task.id, gateId: gate.id },
|
|
3304
|
+
};
|
|
3305
|
+
const card = { rev: task.rev, deciding: false };
|
|
3306
|
+
const settle = (outcome: 'answered' | 'dismissed' | 'timeout' | 'canceled', answer?: string) => {
|
|
3307
|
+
if (userQuestions.get(question.id)?.question !== question) return;
|
|
3308
|
+
userQuestions.delete(question.id);
|
|
3309
|
+
emit(sessionId, { type: 'question.resolved', questionId: question.id, outcome, ...(answer !== undefined ? { answer } : {}) });
|
|
3310
|
+
};
|
|
3311
|
+
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) }) });
|
|
3312
|
+
emit(sessionId, { type: 'question', question });
|
|
3313
|
+
runLog(rootOf(sessionId), { event: 'gate.card', questionId: question.id, taskId: task.id, gateId: gate.id });
|
|
3314
|
+
}
|
|
3315
|
+
|
|
3316
|
+
/**
|
|
3317
|
+
* The user answered a gate card: an option approves (with the default Approve/Reject, Reject or
|
|
3318
|
+
* other words reject), dismissing rejects. The card's task rev guards the write; a stale rev is
|
|
3319
|
+
* read again and retried only while the gate is still open and undecided, so a decision another
|
|
3320
|
+
* channel made first is never applied or mailed twice. An answer that decides nothing (a second
|
|
3321
|
+
* one while the first is written, one another channel beat, or a failed write) is refused to the
|
|
3322
|
+
* caller, never only logged (t-595d).
|
|
3323
|
+
*/
|
|
3324
|
+
async function decideGate(projectRoot: string, question: UserQuestion, card: { rev: number; deciding: boolean }, reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }, choices?: string[]) {
|
|
3325
|
+
const defaults = !choices;
|
|
3326
|
+
const { taskId, gateId } = question.gate!;
|
|
3327
|
+
if (card.deciding) throw gateRefusal('GATE_BUSY', `An answer to gate ${gateId} of ${taskId} is already being recorded`);
|
|
3328
|
+
card.deciding = true;
|
|
3329
|
+
const channel = reply.channel ?? 'web';
|
|
3330
|
+
const text = reply.text?.trim();
|
|
3331
|
+
const approve = !reply.dismiss && !!text && (defaults ? APPROVALS.includes(text.toLowerCase()) : choices.includes(text));
|
|
3332
|
+
const rejectReason = reply.dismiss ? reply.reason : text && CHOICES_REJECT.includes(text.toLowerCase()) ? undefined : text;
|
|
3333
|
+
const write = (ifRev: number) => approve
|
|
3334
|
+
? resolveGate(projectRoot, taskId, gateId, { by: 'user', ifRev, channel, ...(defaults ? {} : { choice: text }) })
|
|
3335
|
+
: rejectGate(projectRoot, taskId, gateId, { by: 'user', ifRev, channel, ...(rejectReason ? { reason: rejectReason.slice(0, 2000) } : {}) });
|
|
3336
|
+
try {
|
|
3337
|
+
try { await write(card.rev); }
|
|
3338
|
+
catch (error: any) {
|
|
3339
|
+
if (error?.code !== 'TASK_CHANGED') throw error;
|
|
3340
|
+
const current = (await loadTasks(projectRoot)).tasks.find(entry => entry.id === taskId);
|
|
3341
|
+
const gate = current?.gates.find(entry => entry.id === gateId);
|
|
3342
|
+
if (!current || current.status === 'closed' || !gate) throw gateRefusal('GATE_DECIDED', `Gate ${gateId} of ${taskId} is no longer open`);
|
|
3343
|
+
if (gate.resolved || gate.rejected) throw gateRefusal('GATE_DECIDED', `Gate ${gateId} of ${taskId} was already ${gate.resolved ? 'approved' : 'rejected'}${(gate.resolved ?? gate.rejected)?.channel ? ` in ${(gate.resolved ?? gate.rejected)!.channel}` : ''}`);
|
|
3344
|
+
await write(current.rev);
|
|
3345
|
+
}
|
|
3346
|
+
} catch (error) {
|
|
3347
|
+
runLog(question.rootId, { event: 'gate.answer.failed', questionId: question.id, error: errorData(error).message });
|
|
3348
|
+
throw error;
|
|
3349
|
+
} finally {
|
|
3350
|
+
card.deciding = false;
|
|
3351
|
+
// Settles the card whatever happened: decided here, by another channel, or gone.
|
|
3352
|
+
await syncGates(projectRoot);
|
|
2205
3353
|
}
|
|
2206
3354
|
}
|
|
2207
3355
|
|
|
3356
|
+
function gateRefusal(code: 'GATE_BUSY' | 'GATE_DECIDED', message: string) {
|
|
3357
|
+
return Object.assign(new Error(message), { code });
|
|
3358
|
+
}
|
|
3359
|
+
|
|
2208
3360
|
function askTool(sessionId: string, session: Session, args: unknown) {
|
|
2209
3361
|
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
2210
3362
|
const assignment = parent?.assignments.get(sessionId);
|
|
@@ -2216,14 +3368,14 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2216
3368
|
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))) {
|
|
2217
3369
|
return Promise.resolve(toolResult(false, { error: 'options are up to 10 short answers, for questions to the user' }));
|
|
2218
3370
|
}
|
|
2219
|
-
if (assignment?.ask || [...userQuestions.values()].some(pending => pending.question.sessionId === sessionId)) {
|
|
3371
|
+
if (assignment?.ask || [...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) {
|
|
2220
3372
|
return Promise.resolve(toolResult(false, { error: 'A question is already waiting for an answer' }));
|
|
2221
3373
|
}
|
|
2222
3374
|
// Only main talks to the user, unless the user has written to this assignment first.
|
|
2223
3375
|
if (to === 'user' && session.parent && !session.userOpened) {
|
|
2224
3376
|
return Promise.resolve(toolResult(false, { error: `Only main talks to the user; ask ${session.parentAgent ?? 'your requester'} with alp_ask instead` }));
|
|
2225
3377
|
}
|
|
2226
|
-
if (to === 'user') return askUser(sessionId, session, assignment, args.question, args.options);
|
|
3378
|
+
if (to === 'user') return askUser(sessionId, session, assignment, args.question, args.options, undefined, true);
|
|
2227
3379
|
if (!session.parent || !parent || !assignment) return Promise.resolve(toolResult(false, { error: 'This session has no requester; ask the user with to: "user"' }));
|
|
2228
3380
|
const parentId = session.parent;
|
|
2229
3381
|
return new Promise<unknown>(resolve => {
|
|
@@ -2247,10 +3399,19 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2247
3399
|
});
|
|
2248
3400
|
}
|
|
2249
3401
|
|
|
2250
|
-
async function runDelegation(
|
|
3402
|
+
async function runDelegation(sessionId: string, session: Session, params: any): Promise<unknown> {
|
|
3403
|
+
if (workspaceMutation) refuseMutation('workspace_busy', 'A workspace mutation is in progress; retry after it finishes');
|
|
3404
|
+
admitting++;
|
|
3405
|
+
let released = false;
|
|
3406
|
+
const release = () => { if (!released) { released = true; admitting--; } };
|
|
3407
|
+
try { return await runDelegationAdmitted(sessionId, session, params, release); }
|
|
3408
|
+
finally { release(); }
|
|
3409
|
+
}
|
|
3410
|
+
async function runDelegationAdmitted(
|
|
2251
3411
|
sessionId: string,
|
|
2252
3412
|
session: Session,
|
|
2253
3413
|
params: any,
|
|
3414
|
+
admitted: () => void,
|
|
2254
3415
|
): Promise<unknown> {
|
|
2255
3416
|
const args = params.arguments;
|
|
2256
3417
|
|
|
@@ -2292,14 +3453,36 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2292
3453
|
if (args.agent === 'oracle' && !session.mapping.oracleModels.includes(args.model)) return toolResult(false, { error: `Oracle runs on ${session.mapping.oracleModels.join(' or ')}; pass one as model. For two opinions, start one on each with wait: false` });
|
|
2293
3454
|
const configuredModels = args.agent === 'oracle' ? [] : session.mapping.modelProfiles[args.agent] ?? [];
|
|
2294
3455
|
const listed = configuredModels.map(profileModel).filter((id): id is string => Boolean(id));
|
|
3456
|
+
const allowed = listed.map(id => id.endsWith(':*') ? `any ${id.slice(0, -1)} model` : id).join(' or ');
|
|
2295
3457
|
// The requester picks a model and effort for each task among several profiles, or any model of a provider:*; one named profile needs no choice.
|
|
2296
3458
|
const choosing = configuredModels.length > 1 || configuredModels.some(anyModel);
|
|
2297
|
-
if (choosing && (args.model === undefined || args.thinking === undefined)) return toolResult(false, { error: `${args.agent} has several model profiles: choose one for this task as model, its effort as thinking, and say why in modelReason`, models: listed });
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
3459
|
+
if (choosing && (args.model === undefined || args.thinking === undefined)) return toolResult(false, { error: `${args.agent} has several model profiles: choose one for this task as model, its effort as thinking, and say why in modelReason. Pass ${allowed}`, models: listed });
|
|
3460
|
+
// The profiles that name a model are the target's allowlist, one as much as several (P2): one named profile means exactly that model.
|
|
3461
|
+
if (args.model !== undefined && listed.length && !offers(configuredModels, args.model)) {
|
|
3462
|
+
// Actionable in one step: what may be passed now, and where the user widens the list.
|
|
3463
|
+
const team = session.mapping.workflow.mode;
|
|
3464
|
+
const settingsFile = path.join(session.mapping.agent.projectRoot, '.alp', 'settings.json');
|
|
3465
|
+
// alp setup writes only Phở's and Cafe's profiles, and only Claude and Codex models: offer it where it can help.
|
|
3466
|
+
const provider = args.model.slice(0, args.model.indexOf(':'));
|
|
3467
|
+
const setup = ['pho', 'cafe'].includes(team) && ['claude', 'codex'].includes(provider)
|
|
3468
|
+
? `, or run alp setup ${session.mapping.agent.projectRoot} --runtime mix, which gives Phở's and Cafe's members both Claude and Codex profiles (it keeps profiles written by hand or set in a team.json)`
|
|
3469
|
+
: '';
|
|
3470
|
+
return toolResult(false, {
|
|
3471
|
+
error: `${args.model} is not one of ${args.agent}'s model profiles in team ${team}; pass ${allowed}${choosing ? '' : ', or omit model to run on it'}. ` +
|
|
3472
|
+
`The user can allow it by adding it to team.${team}.${args.agent}.profiles in ${settingsFile} ("provider:model" or "provider:model:effort", or "${provider}:*" for any model of that provider, which makes you choose model and effort per assignment)${setup}.`,
|
|
3473
|
+
models: listed,
|
|
3474
|
+
});
|
|
3475
|
+
}
|
|
2301
3476
|
const configuredDefault = !choosing && listed.length === 1 ? listed[0] : undefined;
|
|
2302
3477
|
const delegatedModel = args.model ?? configuredDefault ?? `${session.runtimeKind}:${session.mapping.model}`;
|
|
3478
|
+
// An effort is checked against the model's wherever the target has profiles; where ALP cannot check it
|
|
3479
|
+
// (a model the catalog lists without efforts, antigravity:, acp:, or a target without profiles) it is
|
|
3480
|
+
// passed on, and the answer says so instead of staying silent.
|
|
3481
|
+
const efforts = args.thinking !== undefined && listed.length ? profileEfforts(delegatedModel) : [];
|
|
3482
|
+
if (efforts.length && !efforts.includes(args.thinking)) return toolResult(false, { error: `${delegatedModel} takes effort ${efforts.join(', ')}`, efforts });
|
|
3483
|
+
const thinkingNote = args.thinking !== undefined && !efforts.length
|
|
3484
|
+
? (listed.length ? `effort ${args.thinking} was not checked: ALP does not know which efforts ${delegatedModel} takes` : `effort ${args.thinking} was not checked: no model profile of ${args.agent} names a model`)
|
|
3485
|
+
: undefined;
|
|
2303
3486
|
const delegatedThinking = args.thinking ?? selectedProfile(configuredModels, delegatedModel)?.effort ?? (args.model || configuredDefault ? undefined : session.mapping.thinking);
|
|
2304
3487
|
// A paused runtime takes no new assignments; another runtime may.
|
|
2305
3488
|
const childRuntime = delegatedModel.split(':')[0] as RuntimeKind;
|
|
@@ -2309,19 +3492,21 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2309
3492
|
if (hold) {
|
|
2310
3493
|
const other = RUNTIMES.find(kind => kind !== childRuntime && !pauseOf(kind));
|
|
2311
3494
|
const instead = listed.filter(id => other && id.startsWith(`${other}:`)).map(id => id.endsWith(':*') ? `any ${id.slice(0, -1)} model` : id);
|
|
3495
|
+
// Only a model the target's profiles allow can move it: a target without profiles takes any.
|
|
2312
3496
|
const next = !other ? 'Wait until the user resumes ALP'
|
|
2313
|
-
: !
|
|
3497
|
+
: !listed.length ? `Pass a model of ${other}: from the catalog to run it on ${label(other)}, or wait`
|
|
2314
3498
|
: instead.length ? `Pass ${instead.join(' or ')} to run it on ${label(other)}, or wait` : `None of ${args.agent}'s model profiles runs on ${label(other)}: wait`;
|
|
2315
3499
|
return toolResult(false, { error: describePause(hold, paused.all ? undefined : childRuntime), next });
|
|
2316
3500
|
}
|
|
2317
3501
|
// The child's permission profile caps its mode, as resolving its session will.
|
|
2318
3502
|
let childProfile;
|
|
2319
|
-
try { childProfile = await profileFor(session.mapping.agent.projectRoot, options.libraryDir, args.agent); }
|
|
3503
|
+
try { childProfile = await profileFor(session.mapping.agent.projectRoot, options.libraryDir, args.agent, { readOnly: readOnlyMember(session.mapping, args.agent) }); }
|
|
2320
3504
|
catch (error) { return toolResult(false, { error: errorData(error).message }); }
|
|
2321
3505
|
const childMode = childProfile ? capMode(args.mode ?? session.mapping.mode, childProfile.base) : args.mode ?? session.mapping.mode;
|
|
2322
3506
|
const capped = {
|
|
2323
3507
|
...(childProfile && childMode !== (args.mode ?? session.mapping.mode) ? { mode: childMode, modeNote: `${args.agent} runs ${childMode}: its permission profile ${childProfile.name} caps it` } : {}),
|
|
2324
3508
|
...(childProfile?.workdir === 'copy' && isolationOf(args) === 'shared' ? { workdirNote: `${args.agent} works in a disposable copy of your tree; nothing it changes reaches yours` } : {}),
|
|
3509
|
+
...(thinkingNote ? { thinkingNote } : {}),
|
|
2325
3510
|
};
|
|
2326
3511
|
let sharedContinuation: RecallEntry | undefined;
|
|
2327
3512
|
if (args.continueFrom !== undefined) {
|
|
@@ -2361,7 +3546,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2361
3546
|
let task: Task | undefined;
|
|
2362
3547
|
if (args.taskId !== undefined) {
|
|
2363
3548
|
if (session.parent || session.mapping.agent.name !== mainOf(session.mapping)) return toolResult(false, { error: 'Only main gives tasks to assignments' });
|
|
2364
|
-
if (
|
|
3549
|
+
if (readOnlyMember(session.mapping, args.agent)) return toolResult(false, { error: 'taskId gives a task to lead or peer; for advice about a task, name it in the brief' });
|
|
2365
3550
|
if (typeof args.taskId !== 'string') return toolResult(false, { error: 'taskId must be a task id' });
|
|
2366
3551
|
// Checked here for a clear refusal; the start below checks again under the task lock.
|
|
2367
3552
|
try {
|
|
@@ -2415,9 +3600,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2415
3600
|
const rootId = rootOf(sessionId);
|
|
2416
3601
|
const root = sessions.get(rootId)!;
|
|
2417
3602
|
|
|
2418
|
-
|
|
3603
|
+
const advisor = ['advisor', 'reviewer'].includes(roleOf(session.mapping, args.agent) ?? '') && childMode === 'read-only';
|
|
3604
|
+
const budget = advisor ? 'advisorCalls' : 'calls';
|
|
3605
|
+
if (root[budget] >= 16) {
|
|
2419
3606
|
return toolResult(false, {
|
|
2420
|
-
error: '
|
|
3607
|
+
error: `${advisor ? 'Advisor' : 'Implementation'} delegation budget exhausted (16 starts across the root session tree since its last new user turn). Mail wakes and child turns do not reset it; a new accepted user prompt in root (including steering) resets both budgets.`,
|
|
2421
3608
|
});
|
|
2422
3609
|
}
|
|
2423
3610
|
|
|
@@ -2432,7 +3619,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2432
3619
|
const continued = args.continueFrom !== undefined ? session.worktrees.get(args.continueFrom) : undefined;
|
|
2433
3620
|
if (args.continueFrom !== undefined && !continued && !sharedContinuation) return toolResult(false, { error: `${args.continueFrom} was merged or discarded meanwhile` });
|
|
2434
3621
|
if (continued) session.worktrees.delete(args.continueFrom);
|
|
2435
|
-
root
|
|
3622
|
+
root[budget]++;
|
|
2436
3623
|
if (peer) root.peerCount++;
|
|
2437
3624
|
|
|
2438
3625
|
const childId = `alp-child-${randomUUID()}`;
|
|
@@ -2478,6 +3665,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2478
3665
|
...(task ? { taskId: task.id } : {}),
|
|
2479
3666
|
});
|
|
2480
3667
|
try {
|
|
3668
|
+
// Persist ownership before native checkout creation or child execution. Recovery books may be lost.
|
|
3669
|
+
if (writes(childMode)) await assignmentResults.put({ assignmentId: childId, checkout });
|
|
2481
3670
|
if (task) {
|
|
2482
3671
|
const started = await startTask(project, task.id, { agent: args.agent, assignment: childId, pid: process.pid, pidStartedAt: OWN_START, epoch }, session.mapping.agent.name);
|
|
2483
3672
|
assignment.taskId = started.id;
|
|
@@ -2492,8 +3681,12 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2492
3681
|
if (continued) session.worktrees.set(args.continueFrom, continued);
|
|
2493
3682
|
throw error;
|
|
2494
3683
|
}
|
|
3684
|
+
await assignmentResults.put({ assignmentId: childId, checkout: assignment.worktree.checkout, worktree: assignment.worktree.path });
|
|
2495
3685
|
// The new branch holds the earlier change, so its worktree and branch can go.
|
|
2496
|
-
if (continued)
|
|
3686
|
+
if (continued) {
|
|
3687
|
+
await removeWorktree(continued.worktree, { deleteBranch: true });
|
|
3688
|
+
await assignmentResults.remove(args.continueFrom);
|
|
3689
|
+
}
|
|
2497
3690
|
runLog(rootId, { event: 'worktree.created', assignmentId: childId, branch: assignment.worktree.branch, base: assignment.worktree.base, ...(continued ? { continuedFrom: args.continueFrom } : {}) });
|
|
2498
3691
|
} else if (sharedWriter) {
|
|
2499
3692
|
assignment.fingerprint = await checkoutFingerprint(checkout).catch(() => undefined);
|
|
@@ -2519,9 +3712,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2519
3712
|
thinking,
|
|
2520
3713
|
mode: childMode,
|
|
2521
3714
|
};
|
|
2522
|
-
await openSession(childId, childSpec, 'skip', session.delegation);
|
|
3715
|
+
await openSession(childId, childSpec, 'skip', session.delegation, assignment);
|
|
3716
|
+
admitted();
|
|
2523
3717
|
|
|
2524
|
-
const child =
|
|
3718
|
+
const child = assignmentSessions.get(assignment);
|
|
3719
|
+
if (child && sessions.get(childId) !== child) throw new Error('Child session was replaced during open');
|
|
2525
3720
|
if (child) void runHooks(childId, child, 'assignment.start', { assignment: childId, brief: clip(args.task, 2000) }, args.taskId);
|
|
2526
3721
|
|
|
2527
3722
|
if (
|
|
@@ -2560,6 +3755,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2560
3755
|
addPin(childId, child, pins, { kind: 'claim', body: `Task ${task.id}: ${task.title}`, paths: task.paths, task: task.id });
|
|
2561
3756
|
}
|
|
2562
3757
|
|
|
3758
|
+
// Mail held for the brief goes with it: startPrompt takes what waits.
|
|
2563
3759
|
await startPrompt(childId, {
|
|
2564
3760
|
clientMessageId: `task-${childId}`,
|
|
2565
3761
|
delivery: 'auto',
|
|
@@ -2574,6 +3770,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2574
3770
|
},
|
|
2575
3771
|
],
|
|
2576
3772
|
}, 'assignment');
|
|
3773
|
+
// Held until the brief's turn started: what came since steers it, or wakes the child if it ended.
|
|
3774
|
+
// A brief that did not start leaves the hold; the child closes with its failed assignment.
|
|
3775
|
+
child.awaitingBrief = false;
|
|
3776
|
+
if (child.wakeHeld) { child.wakeHeld = false; deliver(childId, child); }
|
|
2577
3777
|
} catch (error) {
|
|
2578
3778
|
// A child that failed while starting may already have reported by mail; report once.
|
|
2579
3779
|
session.mail = session.mail.filter(event => event.deliveredTurn || event.kind !== 'result' || event.assignment !== childId);
|
|
@@ -2598,12 +3798,16 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2598
3798
|
if (events === 'user') return toolResult(true, { assignmentId: childId, agent: args.agent, status: 'running', userMessage: true, next: USER_WROTE });
|
|
2599
3799
|
|
|
2600
3800
|
if (!events) {
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
3801
|
+
// Only the user's stop or a closing session ends the assignment with the wait (#116).
|
|
3802
|
+
if (session.closed || session.wakeBlocked || !session.assignments.has(childId)) {
|
|
3803
|
+
return toolResult(false, {
|
|
3804
|
+
agent: args.agent,
|
|
3805
|
+
assignmentId: childId,
|
|
3806
|
+
status: 'canceled',
|
|
3807
|
+
error: 'Parent assignment stopped',
|
|
3808
|
+
});
|
|
3809
|
+
}
|
|
3810
|
+
return toolResult(false, { agent: args.agent, assignmentId: childId, status: 'running', error: TURN_ENDED });
|
|
2607
3811
|
}
|
|
2608
3812
|
|
|
2609
3813
|
// A result that came with a check-in makes the check-in moot.
|
|
@@ -2619,7 +3823,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2619
3823
|
});
|
|
2620
3824
|
}
|
|
2621
3825
|
|
|
2622
|
-
async function openSession(sessionId: string, spec: SessionSpec, history: 'replay' | 'skip', delegation = true): Promise<SessionSnapshot> {
|
|
3826
|
+
async function openSession(sessionId: string, spec: SessionSpec, history: 'replay' | 'skip', delegation = true, assignment?: Assignment): Promise<SessionSnapshot> {
|
|
3827
|
+
return admission(() => openSessionAdmitted(sessionId, spec, history, delegation, assignment));
|
|
3828
|
+
}
|
|
3829
|
+
async function openSessionAdmitted(sessionId: string, spec: SessionSpec, history: 'replay' | 'skip', delegation = true, assignment?: Assignment): Promise<SessionSnapshot> {
|
|
2623
3830
|
if (sessions.has(sessionId)) {
|
|
2624
3831
|
throw new Error(
|
|
2625
3832
|
'Session is already open',
|
|
@@ -2695,6 +3902,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2695
3902
|
? sessions.get(context.parent)?.mapping.agent.name
|
|
2696
3903
|
: undefined,
|
|
2697
3904
|
...(context?.role ? { role: context.role } : {}),
|
|
3905
|
+
// A new assignment's first turn is its brief; mail that comes sooner waits for it.
|
|
3906
|
+
...(context && !context.role && !context.recovered ? { awaitingBrief: true } : {}),
|
|
2698
3907
|
journal: [],
|
|
2699
3908
|
tasks: [],
|
|
2700
3909
|
|
|
@@ -2702,16 +3911,25 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2702
3911
|
peerCount: 0,
|
|
2703
3912
|
assignments: new Map(),
|
|
2704
3913
|
calls: 0,
|
|
3914
|
+
advisorCalls: 0,
|
|
2705
3915
|
mail: [],
|
|
2706
3916
|
waiters: [],
|
|
2707
3917
|
lastActivity: Date.now(),
|
|
2708
3918
|
wakes: 0,
|
|
3919
|
+
wakeFailures: 0,
|
|
2709
3920
|
wakeBlocked: false,
|
|
2710
3921
|
|
|
2711
3922
|
toolCalls: new Map(),
|
|
2712
3923
|
acknowledged: Promise.resolve(),
|
|
2713
3924
|
worktrees: new Map(),
|
|
2714
3925
|
};
|
|
3926
|
+
if (assignment) assignmentSessions.set(assignment, session);
|
|
3927
|
+
// Pending until its thread exists: mail posted meanwhile waits for it, as in a restart.
|
|
3928
|
+
const finishPending = beginPending(session);
|
|
3929
|
+
const opening: { failure?: unknown } = {};
|
|
3930
|
+
openings.set(session, opening);
|
|
3931
|
+
/** A process failure during the open fails it: the step that saw it settle need not have failed. */
|
|
3932
|
+
const failedMeanwhile = () => { if (opening.failure !== undefined) throw opening.failure; };
|
|
2715
3933
|
|
|
2716
3934
|
sessions.set(
|
|
2717
3935
|
sessionId,
|
|
@@ -2722,8 +3940,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2722
3940
|
|
|
2723
3941
|
try {
|
|
2724
3942
|
await runtime.initialize();
|
|
3943
|
+
failedMeanwhile();
|
|
2725
3944
|
|
|
2726
|
-
if (session.closed) {
|
|
3945
|
+
if (session.closed || sessions.get(sessionId) !== session) {
|
|
2727
3946
|
throw new Error(
|
|
2728
3947
|
'Session closed during initialization',
|
|
2729
3948
|
);
|
|
@@ -2750,6 +3969,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2750
3969
|
const nativeConfig = await configOf(session);
|
|
2751
3970
|
noteInstructions(sessionId, session, nativeConfig.developerInstructions);
|
|
2752
3971
|
|
|
3972
|
+
// A Claude fork or rewind that has not had its first prompt yet is made from its base (§12.7).
|
|
3973
|
+
const base = mapping.threadId ? spec.restore?.base : undefined;
|
|
3974
|
+
if (base && runtimeKind !== 'claude') throw new Error(`A ${label(runtimeKind)} session has no base conversation; only Claude makes a fork on its first prompt`);
|
|
3975
|
+
if (base) session.base = base;
|
|
2753
3976
|
const result = mapping.threadId
|
|
2754
3977
|
? await runtime.request(
|
|
2755
3978
|
'thread/resume',
|
|
@@ -2757,6 +3980,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2757
3980
|
...nativeConfig,
|
|
2758
3981
|
threadId:
|
|
2759
3982
|
mapping.threadId,
|
|
3983
|
+
...(base ? { base } : {}),
|
|
2760
3984
|
},
|
|
2761
3985
|
)
|
|
2762
3986
|
: await runtime.request(
|
|
@@ -2770,16 +3994,20 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2770
3994
|
|
|
2771
3995
|
session.threadId =
|
|
2772
3996
|
result.thread.id;
|
|
3997
|
+
failedMeanwhile();
|
|
2773
3998
|
|
|
2774
|
-
if (session.closed) {
|
|
3999
|
+
if (session.closed || sessions.get(sessionId) !== session) {
|
|
2775
4000
|
throw new Error(
|
|
2776
4001
|
'Session closed during thread creation',
|
|
2777
4002
|
);
|
|
2778
4003
|
}
|
|
2779
4004
|
|
|
2780
|
-
session
|
|
4005
|
+
// Open from here on: a process failure is the live session's (wire's onFailure).
|
|
4006
|
+
openings.delete(session);
|
|
2781
4007
|
session.buffered = [];
|
|
4008
|
+
finishPending();
|
|
2782
4009
|
|
|
4010
|
+
openedSessions.add(session);
|
|
2783
4011
|
emit(sessionId, {
|
|
2784
4012
|
type: 'session.opened',
|
|
2785
4013
|
session: snapshot(sessionId, session),
|
|
@@ -2789,6 +4017,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2789
4017
|
thinking: result.reasoningEffort ?? mapping.thinking,
|
|
2790
4018
|
},
|
|
2791
4019
|
});
|
|
4020
|
+
// A main root shows the project's open human gates and gets decisions made while none was live.
|
|
4021
|
+
if (!session.parent && session.role !== 'supervisor' && mapping.agent.name === mainOf(mapping)) { void syncGates(mapping.agent.projectRoot); startGateWatch(mapping.agent.projectRoot); }
|
|
2792
4022
|
|
|
2793
4023
|
if (
|
|
2794
4024
|
history === 'replay'
|
|
@@ -2805,6 +4035,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2805
4035
|
sessionId,
|
|
2806
4036
|
session,
|
|
2807
4037
|
item,
|
|
4038
|
+
false,
|
|
4039
|
+
turn.id,
|
|
2808
4040
|
);
|
|
2809
4041
|
}
|
|
2810
4042
|
}
|
|
@@ -2815,12 +4047,15 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2815
4047
|
return snapshot(sessionId, session);
|
|
2816
4048
|
} catch (error) {
|
|
2817
4049
|
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 });
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
);
|
|
2822
|
-
|
|
2823
|
-
|
|
4050
|
+
// A process failure while the open ran is reported now that the open is through, once.
|
|
4051
|
+
const failed = openings.get(session);
|
|
4052
|
+
openings.delete(session);
|
|
4053
|
+
if (failed?.failure !== undefined) failSession(sessionId, session, failed.failure);
|
|
4054
|
+
// Share the retirement the failure started, and never resolve the id to a
|
|
4055
|
+
// replacement record when this open finishes late.
|
|
4056
|
+
const cleanup = closeSession(sessionId, session, false);
|
|
4057
|
+
finishPending();
|
|
4058
|
+
await cleanup;
|
|
2824
4059
|
|
|
2825
4060
|
throw error;
|
|
2826
4061
|
}
|
|
@@ -2847,17 +4082,21 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2847
4082
|
});
|
|
2848
4083
|
transport.onFailure((error) => {
|
|
2849
4084
|
// A transport ALP already replaced reports nothing.
|
|
2850
|
-
if (session.closed || session.runtime !== transport) return;
|
|
4085
|
+
if (session.closed || session.runtime !== transport || sessions.get(sessionId) !== session) return;
|
|
4086
|
+
// The first open still runs: it fails with this, and reports it when it is through.
|
|
4087
|
+
const opening = openings.get(session);
|
|
4088
|
+
if (opening) { opening.failure ??= error; return; }
|
|
2851
4089
|
if (revivable(session)) void revive(sessionId, session, error);
|
|
2852
4090
|
else failSession(sessionId, session, error);
|
|
2853
4091
|
});
|
|
2854
4092
|
}
|
|
2855
4093
|
|
|
2856
4094
|
function failSession(sessionId: string, session: Session, error: unknown) {
|
|
4095
|
+
if (session.closed || sessions.get(sessionId) !== session) return;
|
|
2857
4096
|
log.error(`${session.mapping.agent.name}'s ${session.runtimeKind} session failed`, { code: 'ALP_PROVIDER_FAILED', sessionId, rootId: rootOf(sessionId), agent: session.mapping.agent.name, provider: session.runtimeKind, error });
|
|
2858
4097
|
terminal(sessionId, session, 'failed', error);
|
|
2859
4098
|
session.settle?.('failed', error);
|
|
2860
|
-
void closeSession(sessionId);
|
|
4099
|
+
void closeSession(sessionId, session);
|
|
2861
4100
|
emit(sessionId, { type: 'session.failed', error: errorData(error) });
|
|
2862
4101
|
}
|
|
2863
4102
|
|
|
@@ -2888,7 +4127,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2888
4127
|
session.role,
|
|
2889
4128
|
supervises(session),
|
|
2890
4129
|
lessonFiles(mapping),
|
|
2891
|
-
Object.fromEntries(await Promise.all(targets.map(async target => [target, await profileFor(mapping.agent.projectRoot, options.libraryDir, target).catch(() => null)] as const))),
|
|
4130
|
+
Object.fromEntries(await Promise.all(targets.map(async target => [target, await profileFor(mapping.agent.projectRoot, options.libraryDir, target, { readOnly: readOnlyMember(mapping, target) }).catch(() => null)] as const))),
|
|
2892
4131
|
);
|
|
2893
4132
|
if (session.spec.writeRoot && session.runtimeKind === 'claude' && mapping.mode === 'workspace-write' && claudeSandboxAvailable()) Object.assign(config, { floor: 'workspace-write' });
|
|
2894
4133
|
if (session.spec.writeRoot) config.developerInstructions += `\nWrite scope: change files only under ${session.spec.writeRoot}. Your working directory is there; the ALP project, tasks and board remain ${mapping.agent.projectRoot}. Board paths are project-relative or absolute; use absolute paths for this write root. This scope does not grant permission to write outside your mode.`;
|
|
@@ -2919,38 +4158,467 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2919
4158
|
const harness = label(session.runtimeKind);
|
|
2920
4159
|
log.warn(`${harness} process of ${session.mapping.agent.name} stopped; restarting it`, { code: 'ALP_PROVIDER_RESTARTED', sessionId, rootId: rootOf(sessionId), agent: session.mapping.agent.name, provider: session.runtimeKind, error });
|
|
2921
4160
|
runLog(rootOf(sessionId), { event: 'session.restarted', sessionId, agent: session.mapping.agent.name, error: errorData(error).message, restarts: session.restarts.length });
|
|
4161
|
+
let interrupted: Session['parked'];
|
|
2922
4162
|
if (session.active) {
|
|
2923
4163
|
session.parkReason = `its ${harness} process stopped`;
|
|
4164
|
+
session.parkPause = undefined;
|
|
2924
4165
|
session.parkThen = `ALP is restarting the ${harness} process; this assignment continues by itself.`;
|
|
2925
4166
|
terminal(sessionId, session, 'failed', error);
|
|
4167
|
+
interrupted = session.parked;
|
|
2926
4168
|
}
|
|
2927
4169
|
const old = session.runtime;
|
|
2928
4170
|
void old.close().catch(() => {});
|
|
4171
|
+
let finishPending = () => {};
|
|
2929
4172
|
try {
|
|
2930
4173
|
const transport = createTransport(options, session.runtimeKind, session.mapping.workdir, nativeEnvironment(options, session.mapping.env), session.mapping.acp, session.mapping.antigravity);
|
|
2931
4174
|
session.runtime = transport;
|
|
2932
|
-
|
|
4175
|
+
finishPending = beginPending(session);
|
|
2933
4176
|
wire(sessionId, session, transport);
|
|
2934
4177
|
await transport.initialize();
|
|
2935
4178
|
const config = await configOf(session);
|
|
2936
|
-
if (session.closed) return void transport.close().catch(() => {});
|
|
2937
|
-
await transport.request('thread/resume', { ...config, threadId: session.threadId });
|
|
2938
|
-
if (session.closed) return void transport.close().catch(() => {});
|
|
2939
|
-
session.pending = false;
|
|
4179
|
+
if (session.closed) { finishPending(); return void transport.close().catch(() => {}); }
|
|
4180
|
+
await transport.request('thread/resume', { ...config, threadId: session.threadId, ...(session.base ? { base: session.base } : {}) });
|
|
4181
|
+
if (session.closed) { finishPending(); return void transport.close().catch(() => {}); }
|
|
2940
4182
|
session.buffered = [];
|
|
4183
|
+
finishPending();
|
|
2941
4184
|
runLog(rootOf(sessionId), { event: 'session.revived', sessionId, agent: session.mapping.agent.name });
|
|
2942
|
-
if (session.parked &&
|
|
4185
|
+
if (session.parked && session.parked === interrupted) {
|
|
2943
4186
|
session.parked.prompt = `ALP restarted your ${harness} process after it stopped in the middle of your turn. Continue where you left off: your earlier work in this session and its files are intact.${session.parent ? ' Finish with alp_handoff as before.' : ''}`;
|
|
2944
4187
|
continueParked(sessionId, session);
|
|
2945
4188
|
}
|
|
2946
4189
|
} catch (failure) {
|
|
2947
|
-
|
|
4190
|
+
finishPending();
|
|
2948
4191
|
session.parked = undefined;
|
|
2949
4192
|
runLog(rootOf(sessionId), { event: 'session.revive_failed', sessionId, agent: session.mapping.agent.name, error: errorData(failure).message });
|
|
2950
4193
|
failSession(sessionId, session, error);
|
|
2951
4194
|
}
|
|
2952
4195
|
}
|
|
2953
4196
|
|
|
4197
|
+
/**
|
|
4198
|
+
* Why a root cannot have its native process restarted now, or undefined when it can: the seam that
|
|
4199
|
+
* rebind (a rewind), a reload (G2: rebind(id, its own binding)) and a live model or team change (D)
|
|
4200
|
+
* share. Its whole tree must be idle: an open root with no turn, opening or pending prompt, child,
|
|
4201
|
+
* assignment, question to the user, unread or held mail, parked work, or review by its supervisor.
|
|
4202
|
+
*/
|
|
4203
|
+
function restartRefusal(sessionId: string, session: Session | undefined): string | undefined {
|
|
4204
|
+
if (!session || session.closed) return 'The session is not open';
|
|
4205
|
+
if (session.parent || session.role === 'supervisor') return 'Only a root session can be restarted';
|
|
4206
|
+
if (session.pending) return 'The session is still opening or restarting';
|
|
4207
|
+
if (session.active) return 'A turn is running';
|
|
4208
|
+
if (session.children.size || session.assignments.size) return 'Assignments are still running';
|
|
4209
|
+
if ([...userQuestions.values()].some(pending => pending.question.rootId === sessionId && !pending.gate)) return 'A question to the user waits for an answer';
|
|
4210
|
+
// Mail a lifecycle hold keeps waits for its release, then reaches the session's new conversation.
|
|
4211
|
+
if ((hasActiveMail(session) || session.wakeHeld) && !session.lifecycleHolds) return MAIL_WAITS;
|
|
4212
|
+
if (session.parked || session.parkReason) return 'The session is parked';
|
|
4213
|
+
if (reviewing(session)) return REVIEWING;
|
|
4214
|
+
return undefined;
|
|
4215
|
+
}
|
|
4216
|
+
|
|
4217
|
+
/**
|
|
4218
|
+
* Restarts a live session's native process on `binding` (ALPD §31, as revive does): the old process
|
|
4219
|
+
* stops first, so no two processes ever hold the session's conversation, then a new one resumes
|
|
4220
|
+
* `binding` and replaces it, keeping the session id, configuration and viewers. Throws, leaving the
|
|
4221
|
+
* session without a process, when the new one cannot resume; the caller reopens or fails it. The
|
|
4222
|
+
* caller checks restartRefusal and runs this in the operation queue. `verify`: a Claude conversation
|
|
4223
|
+
* without a transcript (or base) is refused rather than left to Claude, which would refuse it at boot
|
|
4224
|
+
* or start it empty; reopening the binding a session already ran on resumes it as revive does.
|
|
4225
|
+
* `shape`: the configuration the new process runs with, when not the session's own (a live configure,
|
|
4226
|
+
* §12.9); the session itself keeps its own until its caller sees the restart through. No `binding`:
|
|
4227
|
+
* a new conversation starts (a root reconfigured before its first turn has none to keep). Answers
|
|
4228
|
+
* what the runtime answered (Codex: the model and effort it resumed the thread with).
|
|
4229
|
+
*/
|
|
4230
|
+
async function restartNative(sessionId: string, session: Session, binding: NativeBinding | undefined, verify = true, shape?: Pick<Session, 'mapping' | 'graph' | 'spec'>) {
|
|
4231
|
+
const old = session.runtime;
|
|
4232
|
+
const finishPending = beginPending(session);
|
|
4233
|
+
await old.close().catch(() => {});
|
|
4234
|
+
const transport = createTransport(options, session.runtimeKind, session.mapping.workdir, nativeEnvironment(options, session.mapping.env), session.mapping.acp, session.mapping.antigravity);
|
|
4235
|
+
// Not wired before it resumes: a failure now fails this restart, not the session.
|
|
4236
|
+
let failure: unknown;
|
|
4237
|
+
transport.onFailure(error => { failure ??= error; });
|
|
4238
|
+
session.runtime = transport;
|
|
4239
|
+
let result: any;
|
|
4240
|
+
try {
|
|
4241
|
+
await transport.initialize();
|
|
4242
|
+
const config = await configOf(shape ? { ...session, ...shape } : session);
|
|
4243
|
+
noteInstructions(sessionId, session, config.developerInstructions);
|
|
4244
|
+
if (session.closed) throw new Error('Session closed during restart');
|
|
4245
|
+
result = binding
|
|
4246
|
+
? await transport.request('thread/resume', {
|
|
4247
|
+
...config, threadId: binding.threadId,
|
|
4248
|
+
...(binding.base ? { base: binding.base } : verify && session.runtimeKind === 'claude' ? { requireHistory: true } : {}),
|
|
4249
|
+
})
|
|
4250
|
+
: await transport.request('thread/start', { ...config, ephemeral: !(shape ?? session).mapping.persist && !(shape ?? session).mapping.keepThread });
|
|
4251
|
+
if (failure) throw failure;
|
|
4252
|
+
if (session.closed) throw new Error('Session closed during restart');
|
|
4253
|
+
if (binding && result?.thread?.id !== undefined && result.thread.id !== binding.threadId) throw new Error(`${label(session.runtimeKind)} resumed ${result.thread.id} instead of ${binding.threadId}`);
|
|
4254
|
+
if (!binding && typeof result?.thread?.id !== 'string') throw new Error(`${label(session.runtimeKind)} started no conversation`);
|
|
4255
|
+
} catch (error) {
|
|
4256
|
+
await transport.close().catch(() => {});
|
|
4257
|
+
// Not pending any more: mail that waited runs again in the operation queue, after this restart's
|
|
4258
|
+
// caller (which reopens or fails the session) is through.
|
|
4259
|
+
finishPending();
|
|
4260
|
+
throw error;
|
|
4261
|
+
}
|
|
4262
|
+
session.threadId = binding ? binding.threadId : result.thread.id;
|
|
4263
|
+
if (binding?.base) session.base = binding.base;
|
|
4264
|
+
else delete session.base;
|
|
4265
|
+
session.buffered = [];
|
|
4266
|
+
wire(sessionId, session, transport);
|
|
4267
|
+
finishPending();
|
|
4268
|
+
return result;
|
|
4269
|
+
}
|
|
4270
|
+
|
|
4271
|
+
/** rebind(): moves an idle root to another native conversation, or reopens its own; see AlpRuntime.rebind. */
|
|
4272
|
+
async function rebindSession(sessionId: string, binding: NativeBinding) {
|
|
4273
|
+
const session = sessions.get(sessionId);
|
|
4274
|
+
const refusal = restartRefusal(sessionId, session);
|
|
4275
|
+
if (refusal) throw new ConversationError('session_busy', refusal);
|
|
4276
|
+
if (!plainObject(binding, ['threadId', 'base']) || typeof binding.threadId !== 'string' || !binding.threadId ||
|
|
4277
|
+
(binding.base !== undefined && (!plainObject(binding.base, ['threadId', 'at']) || typeof binding.base.threadId !== 'string' || !binding.base.threadId || (binding.base.at !== undefined && typeof binding.base.at !== 'string')))) {
|
|
4278
|
+
throw new Error('A binding needs a threadId, and a base only with a threadId and an optional at');
|
|
4279
|
+
}
|
|
4280
|
+
if (binding.base && session!.runtimeKind !== 'claude') throw new ConversationError('runtime_unsupported', `A ${label(session!.runtimeKind)} session has no base conversation`);
|
|
4281
|
+
const live = session!;
|
|
4282
|
+
const previous: NativeBinding = { threadId: live.threadId, ...(live.base ? { base: live.base } : {}) };
|
|
4283
|
+
try {
|
|
4284
|
+
await restartNative(sessionId, live, binding);
|
|
4285
|
+
} catch (error) {
|
|
4286
|
+
runLog(rootOf(sessionId), { event: 'session.rebind_failed', sessionId, agent: live.mapping.agent.name, threadId: binding.threadId, error: errorData(error).message });
|
|
4287
|
+
try {
|
|
4288
|
+
if (live.closed) throw error;
|
|
4289
|
+
await restartNative(sessionId, live, previous, false);
|
|
4290
|
+
} catch (reopen) {
|
|
4291
|
+
// Neither conversation opens: the session fails as a provider failure does.
|
|
4292
|
+
live.pending = false;
|
|
4293
|
+
if (!live.closed) failSession(sessionId, live, reopen);
|
|
4294
|
+
}
|
|
4295
|
+
if (error instanceof ConversationError) throw error;
|
|
4296
|
+
throw new ConversationError('native_refused', `The conversation could not be opened: ${errorData(error).message}`, { outcomeUnknown: !!(error as { outcomeUnknown?: boolean })?.outcomeUnknown });
|
|
4297
|
+
}
|
|
4298
|
+
runLog(rootOf(sessionId), { event: 'session.rebound', sessionId, agent: live.mapping.agent.name, from: previous.threadId, threadId: binding.threadId });
|
|
4299
|
+
const updated = snapshot(sessionId, live);
|
|
4300
|
+
emit(sessionId, { type: 'session.updated', session: updated });
|
|
4301
|
+
return updated;
|
|
4302
|
+
}
|
|
4303
|
+
|
|
4304
|
+
/** reload(): restarts an idle root's native process on its own conversation; see AlpRuntime.reload. */
|
|
4305
|
+
async function reloadSession(sessionId: string) {
|
|
4306
|
+
const session = sessions.get(sessionId);
|
|
4307
|
+
const refusal = restartRefusal(sessionId, session);
|
|
4308
|
+
if (refusal) throw new ConversationError('session_busy', refusal);
|
|
4309
|
+
const live = session!;
|
|
4310
|
+
if (!live.threadId) throw new ConversationError('runtime_unsupported', 'This session keeps no native conversation to reload');
|
|
4311
|
+
const binding: NativeBinding = { threadId: live.threadId, ...(live.base ? { base: live.base } : {}) };
|
|
4312
|
+
try {
|
|
4313
|
+
await restartNative(sessionId, live, binding);
|
|
4314
|
+
} catch (error) {
|
|
4315
|
+
runLog(rootOf(sessionId), { event: 'session.reload_failed', sessionId, agent: live.mapping.agent.name, threadId: binding.threadId, error: errorData(error).message });
|
|
4316
|
+
// No process holds the conversation now, and none is started without it: the session closes,
|
|
4317
|
+
// its record keeps the binding, and the next open resumes it.
|
|
4318
|
+
if (!live.closed) await closeSession(sessionId).catch(() => {});
|
|
4319
|
+
// Known either way: the session is closed now and its conversation was only read, never changed.
|
|
4320
|
+
throw new ConversationError('native_refused', `The agent could not be restarted on its conversation: ${errorData(error).message}`);
|
|
4321
|
+
}
|
|
4322
|
+
runLog(rootOf(sessionId), { event: 'session.reloaded', sessionId, agent: live.mapping.agent.name, threadId: binding.threadId });
|
|
4323
|
+
const updated = snapshot(sessionId, live);
|
|
4324
|
+
emit(sessionId, { type: 'session.updated', session: updated });
|
|
4325
|
+
return updated;
|
|
4326
|
+
}
|
|
4327
|
+
|
|
4328
|
+
// ------------------------------------------------------------------ live configure (§12.9)
|
|
4329
|
+
|
|
4330
|
+
type ConfigureShape = Pick<Session, 'mapping' | 'graph' | 'spec'>;
|
|
4331
|
+
type ConfigurePlan = {
|
|
4332
|
+
shape: ConfigureShape;
|
|
4333
|
+
current: EffectiveConfig;
|
|
4334
|
+
proposed: EffectiveConfig;
|
|
4335
|
+
changes: ConfigureChange[];
|
|
4336
|
+
refusal?: { reason: ConversationErrorReason; message: string };
|
|
4337
|
+
};
|
|
4338
|
+
|
|
4339
|
+
/** The effective configuration a root runs with, or would with `shape` (§12.9). */
|
|
4340
|
+
async function effectiveConfig(session: Session, shape?: ConfigureShape) {
|
|
4341
|
+
const view = shape ? { ...session, ...shape } : session;
|
|
4342
|
+
const config = await configOf(view);
|
|
4343
|
+
const name = view.mapping.agent.name;
|
|
4344
|
+
return effectiveOf(session.runtimeKind, view.mapping, {
|
|
4345
|
+
delegates: Object.hasOwn(view.graph, name) ? view.graph[name] : [],
|
|
4346
|
+
tools: ((config.dynamicTools ?? []) as Array<{ name?: unknown }>).map(tool => tool.name).filter((tool): tool is string => typeof tool === 'string'),
|
|
4347
|
+
supervisor: supervises(view),
|
|
4348
|
+
instructionsSha: createHash('sha256').update(config.developerInstructions).digest('hex').slice(0, 12),
|
|
4349
|
+
});
|
|
4350
|
+
}
|
|
4351
|
+
|
|
4352
|
+
/**
|
|
4353
|
+
* What a change of model, thinking, team or mode would make of a live root: the configuration resolved
|
|
4354
|
+
* as session.create resolves one (same runtime, agent and conversation), or why it is refused. Reads only.
|
|
4355
|
+
*/
|
|
4356
|
+
async function planConfigure(session: Session, changes: ConfigureChanges): Promise<ConfigurePlan> {
|
|
4357
|
+
const current = await effectiveConfig(session);
|
|
4358
|
+
const same: ConfigurePlan = { shape: { mapping: session.mapping, graph: session.graph, spec: session.spec }, current, proposed: current, changes: [] };
|
|
4359
|
+
const refuse = (reason: ConversationErrorReason, message: string): ConfigurePlan => ({ ...same, refusal: { reason, message } });
|
|
4360
|
+
if (session.parent || session.role === 'supervisor') return refuse('not_root', 'Only a root session is reconfigured; an assignment keeps the team and model it started with');
|
|
4361
|
+
if (!CONFIGURABLE.has(session.runtimeKind)) return refuse('runtime_unsupported', `alpd cannot change a running ${label(session.runtimeKind)} session's model or team; start a new session`);
|
|
4362
|
+
for (const key of ['model', 'thinking', 'team', 'mode'] as const) {
|
|
4363
|
+
const value = changes[key];
|
|
4364
|
+
if (value !== undefined && (typeof value !== 'string' || !value.trim() || value.length > 200)) return refuse('invalid_params', `${key} must be a nonempty name of at most 200 characters`);
|
|
4365
|
+
}
|
|
4366
|
+
const runtimeKind = session.runtimeKind;
|
|
4367
|
+
let model = session.mapping.model;
|
|
4368
|
+
if (changes.model !== undefined) {
|
|
4369
|
+
const named = nativeModelOf(runtimeKind, changes.model.trim());
|
|
4370
|
+
if ('runtime' in named) return refuse('runtime_mismatch', `A session keeps its runtime (${label(runtimeKind)}); to work with ${named.runtime}, start a new session with that model`);
|
|
4371
|
+
if (!offered(runtimeKind, named.model, session.mapping)) return refuse('invalid_params', `The daemon host does not offer ${runtimeKind}:${named.model}; choose one of its models`);
|
|
4372
|
+
model = named.model;
|
|
4373
|
+
}
|
|
4374
|
+
const projectRoot = session.mapping.agent.projectRoot;
|
|
4375
|
+
let team = session.mapping.workflow.mode;
|
|
4376
|
+
if (changes.team !== undefined) {
|
|
4377
|
+
const wanted = teamOf(changes.team.trim());
|
|
4378
|
+
const teams = await listTeams(projectRoot, { library: options.libraryDir, templates: options.templates });
|
|
4379
|
+
if (!teams.some(row => row.id === wanted && !row.error)) return refuse('team_not_found', `The daemon host defines no team '${changes.team.trim()}' for this project`);
|
|
4380
|
+
team = wanted;
|
|
4381
|
+
}
|
|
4382
|
+
const teamChanged = team !== session.mapping.workflow.mode;
|
|
4383
|
+
const mode = changes.mode ?? session.mapping.mode;
|
|
4384
|
+
if (!modes.some(candidate => candidate.id === mode)) return refuse('invalid_params', `Unsupported mode '${mode}'`);
|
|
4385
|
+
// The effort asked for; else the session's own while the model takes it; else the model's default.
|
|
4386
|
+
const takes = (effort: string) => { const efforts = thinkingOptionsFor(runtimeKind as 'codex' | 'claude', model); return !efforts.length || efforts.some(option => option.id === effort); };
|
|
4387
|
+
const thinking = changes.thinking ?? (takes(session.mapping.thinking) ? session.mapping.thinking : undefined);
|
|
4388
|
+
const { restore: _restore, thinking: _thinking, ...kept } = session.spec;
|
|
4389
|
+
const spec: SessionSpec = { ...kept, mode, ...(teamChanged ? { workflow: team } : {}), ...(thinking !== undefined ? { thinking } : {}) };
|
|
4390
|
+
let mapping: ResolvedSession;
|
|
4391
|
+
try {
|
|
4392
|
+
mapping = await resolveSession({
|
|
4393
|
+
...spec,
|
|
4394
|
+
restore: { agent: session.mapping.agent.name, threadId: session.threadId || 'unstarted', runtime: runtimeKind, model, ...(teamChanged ? {} : { workflow: session.mapping.workflow }) },
|
|
4395
|
+
}, { templates: options.templates, library: options.libraryDir, language: options.language, initialize: false });
|
|
4396
|
+
} catch (error) {
|
|
4397
|
+
const message = errorData(error).message;
|
|
4398
|
+
return refuse(/^Team '[^']*' not found/.test(message) ? 'team_not_found' : /different runtime/.test(message) ? 'runtime_mismatch' : /different ALP agent/.test(message) ? 'agent_mismatch' : 'invalid_params', message);
|
|
4399
|
+
}
|
|
4400
|
+
const graph = teamChanged ? (mapping.team ? mapping.team.delegation : await resolveDelegation(projectRoot)) : session.graph;
|
|
4401
|
+
const shape: ConfigureShape = { mapping, graph, spec };
|
|
4402
|
+
const proposed = await effectiveConfig(session, shape);
|
|
4403
|
+
const plan: ConfigurePlan = { shape, current, proposed, changes: changesOf(current, proposed) };
|
|
4404
|
+
const refused = (reason: ConversationErrorReason, message: string): ConfigurePlan => ({ ...plan, refusal: { reason, message } });
|
|
4405
|
+
if (mapping.runtimeKind !== runtimeKind) return refused('runtime_mismatch', `A session keeps its runtime (${label(runtimeKind)}); start a new session for another runtime`);
|
|
4406
|
+
if (mapping.agent.name !== session.mapping.agent.name) return refused('agent_mismatch', 'A session keeps its agent; start a new session for another agent');
|
|
4407
|
+
const agent = session.mapping.agent.name;
|
|
4408
|
+
if (teamChanged && agent === mainOf(session.mapping) && agent !== mainOf(mapping)) return refused('agent_mismatch', `Team ${mapping.team?.label ?? team}'s main agent is ${mainOf(mapping)}, not ${agent}; start a new session with that team`);
|
|
4409
|
+
// Never more permissions: the mode asked for stays within the profile and read-only members (readOnlyMember), and a
|
|
4410
|
+
// team or effort change never raises the mode the session runs with.
|
|
4411
|
+
if (changes.mode !== undefined && mapping.mode !== changes.mode) return refused('permission_escalation', readOnlyMember(mapping, 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'));
|
|
4412
|
+
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}`);
|
|
4413
|
+
const before = executablesOf(session.mapping);
|
|
4414
|
+
const added = [...executablesOf(mapping)].filter(entry => !before.has(entry));
|
|
4415
|
+
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`);
|
|
4416
|
+
if (proposed.delegates.length && !session.delegation) return refused('invalid_params', 'This session\'s client cannot show assignments, so it cannot take a team that delegates');
|
|
4417
|
+
return plan;
|
|
4418
|
+
}
|
|
4419
|
+
|
|
4420
|
+
/**
|
|
4421
|
+
* Whether the root's native runtime holds a conversation for it (Codex: a turn of its thread; Claude: a
|
|
4422
|
+
* transcript entry). Codex's answer for a thread before its first message ("not materialized yet", "no
|
|
4423
|
+
* rollout found") means none; any other failure to say is refused, never taken as none, so a held
|
|
4424
|
+
* conversation is never left for an empty one.
|
|
4425
|
+
*/
|
|
4426
|
+
async function nativeHistory(session: Session) {
|
|
4427
|
+
if (!session.threadId) return false;
|
|
4428
|
+
if (session.base) return true;
|
|
4429
|
+
const unknown = (error: unknown) => new ConversationError('native_refused', `${label(session.runtimeKind)} could not say whether it holds this session's conversation: ${errorData(error).message}`);
|
|
4430
|
+
if (session.runtimeKind === 'codex') {
|
|
4431
|
+
try {
|
|
4432
|
+
const page = await session.runtime.request('thread/turns/list', { threadId: session.threadId, limit: 1, sortDirection: 'desc' });
|
|
4433
|
+
return Array.isArray(page?.data) && page.data.length > 0;
|
|
4434
|
+
} catch (error) {
|
|
4435
|
+
if (/not materialized|no rollout found/i.test(errorData(error).message)) return false;
|
|
4436
|
+
throw unknown(error);
|
|
4437
|
+
}
|
|
4438
|
+
}
|
|
4439
|
+
if (session.runtimeKind === 'claude') {
|
|
4440
|
+
try {
|
|
4441
|
+
const chain = await session.runtime.request('thread/chain', { threadId: session.threadId, cwd: session.mapping.workdir });
|
|
4442
|
+
return Array.isArray(chain?.entries) && chain.entries.length > 0;
|
|
4443
|
+
} catch (error) { throw unknown(error); }
|
|
4444
|
+
}
|
|
4445
|
+
return true;
|
|
4446
|
+
}
|
|
4447
|
+
|
|
4448
|
+
/** previewConfigure(): see AlpRuntime.previewConfigure. */
|
|
4449
|
+
async function previewConfigureSession(sessionId: string, changes: ConfigureChanges): Promise<ConfigurePreview> {
|
|
4450
|
+
const session = sessions.get(sessionId);
|
|
4451
|
+
if (!session || session.closed) throw new ConversationError('session_busy', 'The session is not open');
|
|
4452
|
+
const plan = await planConfigure(session, changes ?? {});
|
|
4453
|
+
const busy = plan.changes.length ? restartRefusal(sessionId, session) : undefined;
|
|
4454
|
+
const teams = (await listTeams(session.mapping.agent.projectRoot, { library: options.libraryDir, templates: options.templates }))
|
|
4455
|
+
.filter(team => !team.error)
|
|
4456
|
+
.map(team => ({ id: team.id, label: team.label ?? team.id, ...(team.description ? { description: team.description } : {}) }));
|
|
4457
|
+
return {
|
|
4458
|
+
current: plan.current, proposed: plan.proposed, changes: plan.changes,
|
|
4459
|
+
restart: plan.changes.some(change => change !== 'mode'),
|
|
4460
|
+
allowed: !plan.refusal && !busy,
|
|
4461
|
+
...(plan.refusal ? { reason: plan.refusal.reason as ConfigurePreview['reason'], message: plan.refusal.message } : busy ? { reason: 'session_busy' as const, message: busy } : {}),
|
|
4462
|
+
teams,
|
|
4463
|
+
};
|
|
4464
|
+
}
|
|
4465
|
+
|
|
4466
|
+
/** reconfigure(): see AlpRuntime.reconfigure. */
|
|
4467
|
+
async function reconfigureSession(sessionId: string, changes: ConfigureChanges, { fresh = false, onApplied }: { fresh?: boolean; onApplied?: (result: ConfigureResult) => Promise<void> } = {}): Promise<ConfigureResult> {
|
|
4468
|
+
// Native apply has already succeeded when this runs. A host persistence failure must not enter
|
|
4469
|
+
// the native-refusal rollback path, nor claim that nothing happened.
|
|
4470
|
+
async function persist(result: ConfigureResult) {
|
|
4471
|
+
try { await onApplied?.(result); }
|
|
4472
|
+
catch (error) { throw new ConversationError('native_refused', `The runtime took the configuration but the host could not record it: ${errorData(error).message}`, { outcomeUnknown: true }); }
|
|
4473
|
+
}
|
|
4474
|
+
const session = sessions.get(sessionId);
|
|
4475
|
+
const busy = restartRefusal(sessionId, session);
|
|
4476
|
+
if (busy) throw new ConversationError(session && (session.parent || session.role === 'supervisor') ? 'not_root' : 'session_busy', busy);
|
|
4477
|
+
const live = session!;
|
|
4478
|
+
const plan = await planConfigure(live, changes ?? {});
|
|
4479
|
+
if (plan.refusal) throw new ConversationError(plan.refusal.reason, plan.refusal.message);
|
|
4480
|
+
// alpd's timeline says the root has no turn yet; the runtime must agree before a new conversation
|
|
4481
|
+
// replaces its own (a conversation it holds is resumed, never left behind).
|
|
4482
|
+
const starts = fresh && !(plan.changes.length && await nativeHistory(live));
|
|
4483
|
+
// Its files were read meanwhile: the tree must still be idle.
|
|
4484
|
+
const after = restartRefusal(sessionId, live);
|
|
4485
|
+
if (after) throw new ConversationError('session_busy', after);
|
|
4486
|
+
if (!plan.changes.length) return { session: snapshot(sessionId, live), effective: plan.current, status: 'unchanged', restarted: false };
|
|
4487
|
+
const agent = live.mapping.agent.name;
|
|
4488
|
+
if (plan.changes.every(change => change === 'mode')) {
|
|
4489
|
+
// Permissions alone change as session.configure { mode } changes them, without a restart.
|
|
4490
|
+
await configureSession(sessionId, { mode: plan.shape.mapping.mode }, updated => persist({ session: updated, effective: { ...plan.proposed, instructionsSha: plan.current.instructionsSha }, status: 'applied', restarted: false }));
|
|
4491
|
+
runLog(rootOf(sessionId), { event: 'session.configured', sessionId, agent, changes: plan.changes, mode: plan.shape.mapping.mode });
|
|
4492
|
+
return { session: snapshot(sessionId, live), effective: { ...plan.proposed, instructionsSha: plan.current.instructionsSha }, status: 'applied', restarted: false };
|
|
4493
|
+
}
|
|
4494
|
+
if (!starts && !live.threadId) throw new ConversationError('runtime_unsupported', 'This session keeps no native conversation to continue');
|
|
4495
|
+
const binding: NativeBinding | undefined = starts ? undefined : { threadId: live.threadId, ...(live.base ? { base: live.base } : {}) };
|
|
4496
|
+
const from = { model: live.mapping.model, thinking: live.mapping.thinking, team: live.mapping.workflow.mode, mode: live.mapping.mode };
|
|
4497
|
+
const to = { model: plan.shape.mapping.model, thinking: plan.shape.mapping.thinking, team: plan.shape.mapping.workflow.mode, mode: plan.shape.mapping.mode };
|
|
4498
|
+
let native: any;
|
|
4499
|
+
try {
|
|
4500
|
+
native = await restartNative(sessionId, live, binding, true, plan.shape);
|
|
4501
|
+
// The runtime's own word on what it took: Codex answers the model it resumed (or started) the thread with.
|
|
4502
|
+
if (live.runtimeKind === 'codex' && native?.model !== to.model) throw new ConversationError('native_refused', typeof native?.model === 'string' ? `Codex continued the conversation with ${native.model}, not ${to.model}` : `Codex did not say which model it continued the conversation with, so ${to.model} is not taken`);
|
|
4503
|
+
} catch (error) {
|
|
4504
|
+
runLog(rootOf(sessionId), { event: 'session.configure_failed', sessionId, agent, from, to, error: errorData(error).message });
|
|
4505
|
+
// The session keeps its configuration: a process with it restarts on the same conversation.
|
|
4506
|
+
try {
|
|
4507
|
+
if (live.closed) throw error;
|
|
4508
|
+
await restartNative(sessionId, live, binding, false);
|
|
4509
|
+
} catch (reopen) {
|
|
4510
|
+
// Neither starts: the session fails as a provider failure does; its record keeps the old configuration.
|
|
4511
|
+
live.pending = false;
|
|
4512
|
+
if (!live.closed) failSession(sessionId, live, reopen);
|
|
4513
|
+
}
|
|
4514
|
+
if (error instanceof ConversationError) throw error;
|
|
4515
|
+
throw new ConversationError('native_refused', `The runtime did not take the new configuration; the session keeps its own: ${errorData(error).message}`);
|
|
4516
|
+
}
|
|
4517
|
+
live.mapping = plan.shape.mapping;
|
|
4518
|
+
live.graph = plan.shape.graph;
|
|
4519
|
+
live.spec = plan.shape.spec;
|
|
4520
|
+
// Only Codex answers what it resumed with (its effort applies from the next turn/start); Claude's answer is ALP's own echo.
|
|
4521
|
+
const answered = live.runtimeKind === 'codex' ? { ...(typeof native?.model === 'string' ? { model: native.model } : {}), ...(typeof native?.reasoningEffort === 'string' ? { reasoningEffort: native.reasoningEffort } : {}) } : undefined;
|
|
4522
|
+
runLog(rootOf(sessionId), { event: 'session.configured', sessionId, agent, changes: plan.changes, from, to, threadId: live.threadId, ...(answered ? { native: answered } : {}) });
|
|
4523
|
+
if (plan.changes.includes('team')) {
|
|
4524
|
+
// The old team's supervisor ends at this boundary (it reviews nothing: restartRefusal saw to it);
|
|
4525
|
+
// the new team's, if it has one, starts beside the root as at open.
|
|
4526
|
+
const old = live.supervisor;
|
|
4527
|
+
if (old) { live.supervisor = undefined; await closeSession(old).catch(() => {}); }
|
|
4528
|
+
if (supervises(live)) void enqueue(() => openSupervisor(sessionId));
|
|
4529
|
+
}
|
|
4530
|
+
const updated = snapshot(sessionId, live);
|
|
4531
|
+
const result: ConfigureResult = {
|
|
4532
|
+
session: updated, effective: { ...plan.proposed, ...(live.instructionsSha ? { instructionsSha: live.instructionsSha } : {}) }, status: 'applied', restarted: true,
|
|
4533
|
+
...(answered ? { native: answered } : {}),
|
|
4534
|
+
};
|
|
4535
|
+
await persist(result);
|
|
4536
|
+
emit(sessionId, { type: 'session.updated', session: updated });
|
|
4537
|
+
return result;
|
|
4538
|
+
}
|
|
4539
|
+
|
|
4540
|
+
/** branch(): makes the native conversation a fork or rewind continues; see AlpRuntime.branch. */
|
|
4541
|
+
async function branchConversation(request: BranchRequest): Promise<NativeBinding> {
|
|
4542
|
+
if (closed) throw new Error('Runtime is closed');
|
|
4543
|
+
if (request.runtime !== 'codex' && request.runtime !== 'claude') throw new ConversationError('runtime_unsupported', `${label(request.runtime)} sessions cannot be forked or rewound`);
|
|
4544
|
+
if (!Array.isArray(request.turns) || !request.turns.every(turn => typeof turn === 'string')) throw new Error('branch needs the source turns in order');
|
|
4545
|
+
if (typeof request.source?.threadId !== 'string' || !request.source.threadId) throw new Error('branch needs the source thread');
|
|
4546
|
+
if (typeof request.model !== 'string' || !request.model || !modes.some(candidate => candidate.id === request.mode)) throw new Error('branch needs the model and mode the branch keeps');
|
|
4547
|
+
return request.runtime === 'codex' ? branchCodex(request) : branchClaude(request);
|
|
4548
|
+
}
|
|
4549
|
+
|
|
4550
|
+
/**
|
|
4551
|
+
* A Codex fork, persisted at once (thread/fork), in a short-lived app-server like recall's. The fork
|
|
4552
|
+
* keeps the request's model and settings (Codex otherwise forks with its defaults) and is verified to
|
|
4553
|
+
* end at the expected turn; one that does not is deleted. The source thread is never changed.
|
|
4554
|
+
*/
|
|
4555
|
+
async function branchCodex(request: BranchRequest): Promise<NativeBinding> {
|
|
4556
|
+
const end = codexForkEnd(request);
|
|
4557
|
+
const cwd = request.targetCwd ?? request.cwd;
|
|
4558
|
+
const mode = request.mode;
|
|
4559
|
+
const transport = createTransport(options, 'codex', cwd, nativeEnvironment(options));
|
|
4560
|
+
try {
|
|
4561
|
+
try { await transport.initialize(); }
|
|
4562
|
+
catch (error) { throw new ConversationError('native_refused', `Codex did not start: ${errorData(error).message}`); }
|
|
4563
|
+
let forked: any;
|
|
4564
|
+
try {
|
|
4565
|
+
forked = await transport.request('thread/fork', {
|
|
4566
|
+
threadId: request.source.threadId, ...end.params, ephemeral: false, excludeTurns: true, cwd,
|
|
4567
|
+
model: request.model.replace(/^codex:/, ''),
|
|
4568
|
+
sandbox: mode === 'full-access' ? 'danger-full-access' : nativeMode({ mode, copy: false }),
|
|
4569
|
+
approvalPolicy: codexApproval({ mode, permissions: null }),
|
|
4570
|
+
});
|
|
4571
|
+
} catch (error) { throw codexForkRefusal(error); }
|
|
4572
|
+
const id = forked?.thread?.id;
|
|
4573
|
+
// Forked, but under an id ALP cannot read: it may exist, and nothing can be said of it.
|
|
4574
|
+
if (typeof id !== 'string' || !id) throw new ConversationError('native_refused', 'Codex answered the fork without a thread id', { outcomeUnknown: true });
|
|
4575
|
+
let problem: string | undefined;
|
|
4576
|
+
try {
|
|
4577
|
+
if (forked.thread.forkedFromId != null && forked.thread.forkedFromId !== request.source.threadId) problem = `it was forked from ${forked.thread.forkedFromId}`;
|
|
4578
|
+
else {
|
|
4579
|
+
const page = await transport.request('thread/turns/list', { threadId: id, limit: 1, sortDirection: 'desc' });
|
|
4580
|
+
const last = page?.data?.[0];
|
|
4581
|
+
if (last?.id !== end.last) problem = `it ends at ${last?.id ?? 'no turn'}, not ${end.last}`;
|
|
4582
|
+
else if (last.status === 'inProgress') problem = `its last turn ${last.id} is still running`;
|
|
4583
|
+
}
|
|
4584
|
+
} catch (error) { problem = `it could not be read: ${errorData(error).message}`; }
|
|
4585
|
+
if (!problem) return { threadId: id };
|
|
4586
|
+
const deleted = await transport.request('thread/delete', { threadId: id }).then(() => true, () => false);
|
|
4587
|
+
throw new ConversationError('native_refused', `The Codex fork ${id} could not be verified (${problem}); ${deleted ? 'it was deleted' : 'deleting it failed'}`, { outcomeUnknown: !deleted });
|
|
4588
|
+
} finally {
|
|
4589
|
+
await transport.close().catch(() => {});
|
|
4590
|
+
}
|
|
4591
|
+
}
|
|
4592
|
+
|
|
4593
|
+
/**
|
|
4594
|
+
* A Claude branch, without touching Claude: the cut is validated against the transcript and returned
|
|
4595
|
+
* as a binding whose first prompt makes the fork (resume + forkSession at `at`, under the new id).
|
|
4596
|
+
* A source that is itself still a pending fork stands for its base cut at its own `at`.
|
|
4597
|
+
*/
|
|
4598
|
+
async function branchClaude(request: BranchRequest): Promise<NativeBinding> {
|
|
4599
|
+
const transport = createTransport(options, 'claude', request.cwd, nativeEnvironment(options));
|
|
4600
|
+
try {
|
|
4601
|
+
const read = async (threadId: string): Promise<ChainEntry[]> => {
|
|
4602
|
+
const answer = await transport.request('thread/chain', { threadId, cwd: request.cwd });
|
|
4603
|
+
if (!Array.isArray(answer?.entries)) throw new Error('Claude answered no transcript');
|
|
4604
|
+
return answer.entries;
|
|
4605
|
+
};
|
|
4606
|
+
await transport.initialize();
|
|
4607
|
+
let source = request.source.threadId;
|
|
4608
|
+
let chain = await read(source);
|
|
4609
|
+
if (!chain.length && request.source.base) {
|
|
4610
|
+
source = request.source.base.threadId;
|
|
4611
|
+
chain = pendingChain(request.source.base, await read(source));
|
|
4612
|
+
}
|
|
4613
|
+
return { threadId: randomUUID(), base: { threadId: source, at: claudeCut(chain, request) } };
|
|
4614
|
+
} catch (error) {
|
|
4615
|
+
if (error instanceof ConversationError) throw error;
|
|
4616
|
+
throw new ConversationError('native_refused', `The Claude transcript could not be read: ${errorData(error).message}`);
|
|
4617
|
+
} finally {
|
|
4618
|
+
await transport.close().catch(() => {});
|
|
4619
|
+
}
|
|
4620
|
+
}
|
|
4621
|
+
|
|
2954
4622
|
/** Why recovered sessions were reopened, for what they are told. */
|
|
2955
4623
|
const restartCause = () => options.previousExit?.kind === 'crash' ? 'alpd stopped unexpectedly' : 'alpd restarted';
|
|
2956
4624
|
|
|
@@ -2988,7 +4656,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2988
4656
|
if (assignment.lease && leases.get(assignment.lease)?.assignment === id) leases.delete(assignment.lease);
|
|
2989
4657
|
if (roleOf(parent.mapping, entry.agent) === 'peer') { const root = sessions.get(entry.rootId); if (root) root.peerCount--; }
|
|
2990
4658
|
if (assignment.copy) await removeCopy(assignment.copy).catch(() => {});
|
|
2991
|
-
|
|
4659
|
+
// The worktree predates this recovery and may hold uncommitted work: it stays (t-eae4).
|
|
2992
4660
|
};
|
|
2993
4661
|
try {
|
|
2994
4662
|
if (entry.lease) {
|
|
@@ -2996,7 +4664,14 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2996
4664
|
if (holder && !lineage(entry.parentId).includes(holder.assignment)) throw new Error(`${holder.agent} writes ${entry.lease} now`);
|
|
2997
4665
|
if (!holder) { assignment.lease = entry.lease; leases.set(entry.lease, { assignment: id, agent: entry.agent }); }
|
|
2998
4666
|
}
|
|
2999
|
-
if (entry.worktree)
|
|
4667
|
+
if (entry.worktree) {
|
|
4668
|
+
const { preserved, ...worktree } = await reattachWorktree(entry.worktree);
|
|
4669
|
+
assignment.worktree = worktree;
|
|
4670
|
+
if (preserved) {
|
|
4671
|
+
runLog(entry.rootId, { event: 'worktree.preserved', assignmentId: id, branch: worktree.branch, preserved });
|
|
4672
|
+
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}.` });
|
|
4673
|
+
}
|
|
4674
|
+
}
|
|
3000
4675
|
if (entry.copyOf) {
|
|
3001
4676
|
assignment.copy = await createCopy(entry.copyOf, copyRoot, id);
|
|
3002
4677
|
spec = { ...spec, workdir: assignment.copy.workdir };
|
|
@@ -3010,8 +4685,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3010
4685
|
assignment.taskId = entry.taskId;
|
|
3011
4686
|
touchTask(entry.rootId, entry.taskId);
|
|
3012
4687
|
}
|
|
3013
|
-
await openSession(id, { ...spec, restore: { agent: entry.agent, threadId: entry.threadId, runtime: entry.runtime, model: entry.model, workflow: parent.mapping.workflow } }, 'skip', entry.delegation);
|
|
3014
|
-
const child =
|
|
4688
|
+
await openSession(id, { ...spec, restore: { agent: entry.agent, threadId: entry.threadId, runtime: entry.runtime, model: entry.model, workflow: parent.mapping.workflow } }, 'skip', entry.delegation, assignment);
|
|
4689
|
+
const child = assignmentSessions.get(assignment)!;
|
|
4690
|
+
if (sessions.get(id) !== child) throw new Error('Child session was replaced during recovery');
|
|
3015
4691
|
child.settle = (state, error) => void finishAssignment(entry.parentId, parent, assignment, state, error);
|
|
3016
4692
|
if (entry.brief) child.brief = entry.brief;
|
|
3017
4693
|
if (assignment.taskId && writes(entry.mode)) {
|
|
@@ -3032,6 +4708,15 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3032
4708
|
|
|
3033
4709
|
/** An assignment an earlier alpd left running that cannot continue: its task goes back to open, its work stays on its branch. */
|
|
3034
4710
|
async function abandonEntry(entry: LiveEntry, reason: string) {
|
|
4711
|
+
if (entry.worktree || writes(entry.mode)) await assignmentResults.put({
|
|
4712
|
+
assignmentId: entry.assignmentId,
|
|
4713
|
+
checkout: entry.worktree?.checkout ?? entry.lease ?? entry.spec.writeRoot ?? entry.spec.workdir ?? entry.project,
|
|
4714
|
+
...(entry.worktree ? { worktree: entry.worktree.path } : {}),
|
|
4715
|
+
...(!entry.worktree ? { result: {
|
|
4716
|
+
agent: entry.agent, status: 'abandoned', finishedAt: new Date().toISOString(), project: entry.project, requesters: sessions.has(entry.parentId) ? lineage(entry.parentId) : [entry.parentId],
|
|
4717
|
+
...(entry.taskId ? { taskId: entry.taskId } : {}), brief: cut(entry.brief ?? '', RESULT_EVIDENCE_CHARS), summary: cut(JSON.stringify({ reason }), RESULT_EVIDENCE_CHARS),
|
|
4718
|
+
} } : {}),
|
|
4719
|
+
});
|
|
3035
4720
|
await inFlight.remove(entry.assignmentId);
|
|
3036
4721
|
const parent = sessions.get(entry.parentId);
|
|
3037
4722
|
let task: Record<string, unknown> | undefined;
|
|
@@ -3054,7 +4739,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3054
4739
|
* root first, since each assignment needs its requester open. Each one continues
|
|
3055
4740
|
* its turn, or waits parked when its runtime is paused or the user resumes recovery.
|
|
3056
4741
|
*/
|
|
3057
|
-
async function recoverTree(rootId: string, continueRoot: boolean): Promise<RecoveryOutcome[]> {
|
|
4742
|
+
async function recoverTree(rootId: string, continueRoot: boolean, parkedRoot?: string): Promise<RecoveryOutcome[]> {
|
|
3058
4743
|
const root = sessions.get(rootId);
|
|
3059
4744
|
if (!root || root.closed) throw new Error(`Session ${rootId} is not open`);
|
|
3060
4745
|
const entries = inherited.filter(entry => entry.rootId === rootId).sort((a, b) => a.ancestry.length - b.ancestry.length);
|
|
@@ -3078,7 +4763,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3078
4763
|
: '';
|
|
3079
4764
|
const proceed = (sessionId: string, session: Session, text: string) => {
|
|
3080
4765
|
if (options.recoveryResume === false || pauseOf(session.runtimeKind)) {
|
|
3081
|
-
session.parked = { reason: cause, since: Date.now(), prompt: text };
|
|
4766
|
+
session.parked = { reason: cause, since: Date.now(), prompt: text, ...(options.recoveryResume !== false ? { pause: { scope: paused.all ? 'all' as const : session.runtimeKind } } : {}) };
|
|
3082
4767
|
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
3083
4768
|
runLog(rootId, { event: 'assignment.parked', assignmentId: sessionId, agent: session.mapping.agent.name, reason: cause });
|
|
3084
4769
|
const outcome = outcomes.find(entry => entry.assignmentId === sessionId);
|
|
@@ -3094,15 +4779,27 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3094
4779
|
runLog(rootId, { event: 'assignment.recovered', assignmentId: entry.assignmentId, agent: entry.agent, ...(entry.taskId ? { taskId: entry.taskId } : {}) });
|
|
3095
4780
|
proceed(entry.assignmentId, child, `ALP: ${cause} while you worked on this assignment, and reopened this session. Your earlier work in it${entry.worktree ? ' and your worktree' : ''} is intact; check where you stopped (for example with git status), then continue. Finish with alp_handoff as before.${listed(resumed.get(entry.assignmentId))}`);
|
|
3096
4781
|
}
|
|
3097
|
-
if (
|
|
4782
|
+
if (parkedRoot) {
|
|
4783
|
+
root.parked = { reason: parkedRoot, since: Date.now() };
|
|
4784
|
+
emit(rootId, { type: 'session.updated', session: snapshot(rootId, root) });
|
|
4785
|
+
// Legacy persisted reasons carry no pause provenance. Only an explicit session prompt
|
|
4786
|
+
// can release them, including old quota/process parks; never infer scope from text or flags.
|
|
4787
|
+
} else if (continueRoot) proceed(rootId, root, `ALP: ${cause} during your turn, and reopened this session. Continue the user's request where you stopped.${listed(resumed.get(rootId))}`);
|
|
3098
4788
|
else for (const assignment of resumed.get(rootId) ?? []) post(rootId, { kind: 'note', from: assignment.agent, assignment: assignment.id, passive: true, body: `${cause}; ALP reopened this assignment and it continues. It reports when done.` });
|
|
3099
4789
|
const failed = outcomes.filter(outcome => outcome.outcome === 'failed');
|
|
3100
|
-
if (entries.length || continueRoot) {
|
|
3101
|
-
const parked = outcomes.
|
|
4790
|
+
if (entries.length || continueRoot || parkedRoot) {
|
|
4791
|
+
const parked = outcomes.flatMap(outcome => {
|
|
4792
|
+
const park = outcome.outcome === 'parked' ? sessions.get(outcome.assignmentId)?.parked : undefined;
|
|
4793
|
+
return park ? [park] : [];
|
|
4794
|
+
});
|
|
4795
|
+
if ((continueRoot || parkedRoot) && root.parked) parked.push(root.parked);
|
|
4796
|
+
const next = parked.some(park => !park.pause)
|
|
4797
|
+
? 'send an explicit prompt to each parked session to continue it: alp send <session> --prompt <text>'
|
|
4798
|
+
: 'run alp resume to continue them';
|
|
3102
4799
|
notice(failed.length ? 'warning' : 'info',
|
|
3103
4800
|
`ALP: ${cause}${options.previousExit?.at ? ` (around ${options.previousExit.at})` : ''}. ` +
|
|
3104
|
-
`${entries.length - failed.length} of ${entries.length} running assignments reopened${continueRoot ? ', and this session' : ''}` +
|
|
3105
|
-
`${parked ?
|
|
4801
|
+
`${entries.length - failed.length} of ${entries.length} running assignments reopened${continueRoot || parkedRoot ? ', and this session' : ''}` +
|
|
4802
|
+
`${parked.length ? `; they wait parked: ${next}` : ''}.` +
|
|
3106
4803
|
`${failed.length ? ` Could not continue: ${failed.map(outcome => `${outcome.agent} ${outcome.assignmentId} (${outcome.error})`).join('; ')}; their tasks went back to open.` : ''}`,
|
|
3107
4804
|
root.mapping.agent.projectRoot);
|
|
3108
4805
|
}
|
|
@@ -3124,22 +4821,22 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3124
4821
|
return session;
|
|
3125
4822
|
}
|
|
3126
4823
|
|
|
3127
|
-
async function configureSession(sessionId: string, changes: { mode?: string }) {
|
|
4824
|
+
async function configureSession(sessionId: string, changes: { mode?: string }, beforeUpdated?: (session: SessionSnapshot) => Promise<void>) {
|
|
3128
4825
|
const session = openOf(sessionId);
|
|
3129
4826
|
if (session.active || session.pending || session.children.size) throw new Error('Wait for the current turn and child sessions to finish before changing permissions');
|
|
3130
4827
|
const mode = changes.mode ?? session.mapping.mode;
|
|
3131
4828
|
if (!modes.some(candidate => candidate.id === mode)) throw new Error(`Unsupported mode '${mode}'`);
|
|
3132
4829
|
const profile = session.mapping.permissions;
|
|
3133
4830
|
if (profile && !withinMode(mode, profile.base)) {
|
|
3134
|
-
throw new Error(
|
|
4831
|
+
throw new Error(readOnlyMember(session.mapping, session.mapping.agent.name) ? 'Advisors and the supervisor must remain read-only' : `Permission profile ${profile.name} allows at most ${profile.base}`);
|
|
3135
4832
|
}
|
|
3136
4833
|
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
3137
4834
|
if (parent && !withinMode(mode, parent.mapping.mode)) throw new Error('Child cannot exceed parent permissions');
|
|
3138
|
-
if (session.runtimeKind === '
|
|
3139
|
-
if (session.runtimeKind === 'claude') await session.runtime.request('session/configure', { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
|
|
4835
|
+
if (session.runtimeKind === 'claude' || session.runtimeKind === 'antigravity') await session.runtime.request('session/configure', { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
|
|
3140
4836
|
session.mapping.mode = mode;
|
|
3141
4837
|
session.spec = { ...session.spec, mode };
|
|
3142
4838
|
const updated = snapshot(sessionId, session);
|
|
4839
|
+
if (beforeUpdated) await beforeUpdated(updated);
|
|
3143
4840
|
emit(sessionId, { type: 'session.updated', session: updated });
|
|
3144
4841
|
return updated;
|
|
3145
4842
|
}
|
|
@@ -3154,6 +4851,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3154
4851
|
|
|
3155
4852
|
session.wakeBlocked = true;
|
|
3156
4853
|
session.userStopped = true;
|
|
4854
|
+
session.parked = undefined;
|
|
4855
|
+
session.parkReason = undefined;
|
|
4856
|
+
session.parkPause = undefined;
|
|
4857
|
+
session.resumeHeld = undefined;
|
|
4858
|
+
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
4859
|
+
approvalCancellation.set(session, (approvalCancellation.get(session) ?? 0) + 1);
|
|
4860
|
+
cancelQuestions(sessionId);
|
|
3157
4861
|
// Codex keeps no output of an interrupted turn in its thread: remember what the user saw, by
|
|
3158
4862
|
// thread, since a client that leaves closes the session and the next prompt opens it again.
|
|
3159
4863
|
if (activeTurn && session.runtimeKind === 'codex' && session.threadId) {
|
|
@@ -3169,7 +4873,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3169
4873
|
|
|
3170
4874
|
await Promise.all(
|
|
3171
4875
|
[...session.children].map(
|
|
3172
|
-
closeSession,
|
|
4876
|
+
id => closeSession(id),
|
|
3173
4877
|
),
|
|
3174
4878
|
);
|
|
3175
4879
|
|
|
@@ -3188,8 +4892,33 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3188
4892
|
}
|
|
3189
4893
|
}
|
|
3190
4894
|
|
|
4895
|
+
// Shared by ordinary prompts and the scheduler's queue-scoped sender.
|
|
4896
|
+
async function promptSession(sessionId: string, input: PromptInput, flushing = false): Promise<void> {
|
|
4897
|
+
const session = sessions.get(sessionId);
|
|
4898
|
+
// While main writes its checkpoint and compacts, the user's words wait for the compaction's end (t-0e56).
|
|
4899
|
+
if (!flushing && session && !session.parent && (session.compacting || session.compactBuffer?.length)) {
|
|
4900
|
+
if (!session.seen.has(input.clientMessageId) && !session.compactBuffer?.some(held => held.clientMessageId === input.clientMessageId)) (session.compactBuffer ??= []).push(input);
|
|
4901
|
+
return;
|
|
4902
|
+
}
|
|
4903
|
+
const parked = session?.parked;
|
|
4904
|
+
try {
|
|
4905
|
+
const prompt = session?.active && session.resumedTurn === session.active && input.delivery === 'auto'
|
|
4906
|
+
? { ...input, delivery: 'steer' as const } : input;
|
|
4907
|
+
await startPrompt(sessionId, prompt, 'user');
|
|
4908
|
+
if (session && parked && session.parked === parked) {
|
|
4909
|
+
session.parked = undefined;
|
|
4910
|
+
emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
|
|
4911
|
+
}
|
|
4912
|
+
} catch (error) {
|
|
4913
|
+
const session = sessions.get(sessionId);
|
|
4914
|
+
if (session?.seen.has(input.clientMessageId)) return;
|
|
4915
|
+
session?.seen.add(input.clientMessageId);
|
|
4916
|
+
emit(sessionId, { type: 'prompt.failed', clientMessageId: input.clientMessageId, error: errorData(error) });
|
|
4917
|
+
}
|
|
4918
|
+
}
|
|
4919
|
+
|
|
3191
4920
|
/** Starts a turn or steers the running one; throws when the prompt was not delivered. */
|
|
3192
|
-
async function startPrompt(sessionId: string, prompt: PromptInput, origin: TurnOrigin, wake?: MailEvent[]) {
|
|
4921
|
+
async function startPrompt(sessionId: string, prompt: PromptInput, origin: TurnOrigin, wake?: MailEvent[], internalCompact = false) {
|
|
3193
4922
|
const session = openOf(sessionId);
|
|
3194
4923
|
|
|
3195
4924
|
if (
|
|
@@ -3200,9 +4929,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3200
4929
|
return;
|
|
3201
4930
|
}
|
|
3202
4931
|
|
|
3203
|
-
if (prompt.content.some(content => content.type !== 'text' && content.type !== 'image')) {
|
|
3204
|
-
throw new Error('Only text and
|
|
4932
|
+
if (prompt.content.some(content => content.type !== 'text' && content.type !== 'image' && content.type !== 'attachment')) {
|
|
4933
|
+
throw new Error('Only text, image and attachment prompts are supported');
|
|
3205
4934
|
}
|
|
4935
|
+
const refusal = origin === 'user' ? nativeCommandRefusal(session.runtimeKind, prompt.content, session.runtime.customCommands?.()) : undefined;
|
|
4936
|
+
if (refusal) throw new Error(refusal);
|
|
3206
4937
|
// Inline images only, never a path or URL: the native input gets a data URL ALP builds itself.
|
|
3207
4938
|
const images = prompt.content.filter(content => content.type === 'image') as Array<{ type: 'image'; mimeType: string; data: string }>;
|
|
3208
4939
|
if (images.length) {
|
|
@@ -3217,6 +4948,27 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3217
4948
|
}
|
|
3218
4949
|
}
|
|
3219
4950
|
|
|
4951
|
+
// Attachments (§12.6): descriptors alpd resolved and pinned for this session, never a path. Each
|
|
4952
|
+
// gets a read-only copy staged from alpd's verified bytes before the turn names it.
|
|
4953
|
+
const attached: Array<{ attachment: RuntimeAttachment; staged: string }> = [];
|
|
4954
|
+
const attachmentParts = prompt.content.filter(content => content.type === 'attachment');
|
|
4955
|
+
if (attachmentParts.length) {
|
|
4956
|
+
if (!attachmentRoutes(session).includes('file.path') || !stager || !attachmentReader) {
|
|
4957
|
+
throw new Error(`${session.runtimeKind === 'acp' ? 'This ACP agent' : session.runtimeKind[0].toUpperCase() + session.runtimeKind.slice(1)} cannot read attached files; they stay stored and the message was not sent`);
|
|
4958
|
+
}
|
|
4959
|
+
// Told once per session, when it first stages, never at alpd's start (its log stays quiet until there is something to say).
|
|
4960
|
+
if (!stagingWarned.has(sessionId)) {
|
|
4961
|
+
stagingWarned.add(sessionId);
|
|
4962
|
+
const exposed = stagingExposure(stager.root, [session.mapping.workdir, os.tmpdir(), '/tmp']);
|
|
4963
|
+
if (exposed) log.warn(`the attachment staging directory is inside ${exposed === session.mapping.workdir ? 'this session\'s workspace' : 'the temp directory'}, which sandboxed sessions may write: a tool could change a staged copy before it is read; keep ALP_HOME outside both (default ~/.alp)`, { code: 'ALP_ATTACHMENT_STAGE_EXPOSED', sessionId });
|
|
4964
|
+
}
|
|
4965
|
+
for (const part of attachmentParts) {
|
|
4966
|
+
const attachment = runtimeAttachment(part);
|
|
4967
|
+
if (!attachment) throw new Error('An attachment in a prompt must be one alpd resolved');
|
|
4968
|
+
attached.push({ attachment, staged: await stager.stage(attachmentReader, attachment, sessionId) });
|
|
4969
|
+
}
|
|
4970
|
+
}
|
|
4971
|
+
|
|
3220
4972
|
if (
|
|
3221
4973
|
prompt.delivery === 'steer' &&
|
|
3222
4974
|
!session.active
|
|
@@ -3258,23 +5010,23 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3258
5010
|
) {
|
|
3259
5011
|
session.text.clear();
|
|
3260
5012
|
session.toolCalls.clear();
|
|
5013
|
+
if (!internalCompact) session.compactCooling = false;
|
|
3261
5014
|
session.supervisorWake = !!wake?.length && wake.every(event => event.defer);
|
|
3262
5015
|
|
|
3263
5016
|
// A wake continues the same assignment: keep its handoff and limits.
|
|
3264
5017
|
if (!wake) {
|
|
3265
5018
|
session.handoff = undefined;
|
|
3266
5019
|
session.wakes = 0;
|
|
5020
|
+
session.wakeFailures = 0;
|
|
3267
5021
|
session.wakeBlocked = false;
|
|
3268
5022
|
session.userStopped = false;
|
|
3269
|
-
|
|
3270
|
-
if (!session.parent) {
|
|
3271
|
-
session.calls = 0;
|
|
3272
|
-
}
|
|
3273
5023
|
}
|
|
3274
5024
|
}
|
|
3275
5025
|
|
|
3276
5026
|
try {
|
|
3277
5027
|
const orchestration = session.runtime.orchestrationContext ? await session.runtime.orchestrationContext().catch(() => ({ available: false })) : { available: false };
|
|
5028
|
+
// Each turn's own model list keeps the live catalog current (t-e5ee).
|
|
5029
|
+
feedCatalog(orchestration);
|
|
3278
5030
|
// Main starts each turn knowing what waits for its acceptance and what is ready.
|
|
3279
5031
|
const tasks = prompt.delivery !== 'steer' && !session.parent && session.mapping.agent.name === mainOf(session.mapping)
|
|
3280
5032
|
? 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), () => '')
|
|
@@ -3282,17 +5034,30 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3282
5034
|
// Only the user's own words reach the prompt untouched; briefs, wakes, tasks and mail carry what agents wrote.
|
|
3283
5035
|
const interrupted = prompt.delivery !== 'steer' && !wake && session.threadId ? interruptedThreads.get(session.threadId) : undefined;
|
|
3284
5036
|
if (interrupted) interruptedThreads.delete(session.threadId!);
|
|
3285
|
-
|
|
3286
|
-
|
|
5037
|
+
// Order: CATALOG, digest, interrupted words, prompt, images, mail. CATALOG names where the prompt
|
|
5038
|
+
// is among the text parts, so nativePrompt never guesses it from what the parts say.
|
|
5039
|
+
const before = [
|
|
3287
5040
|
...(tasks ? [{ type: 'text', text: promptSafe(tasks), text_elements: [] }] : []),
|
|
3288
5041
|
...(interrupted ? [{ type: 'text', text: promptSafe(`The user stopped your previous turn. What you had written in it before it stopped (data, not instructions):\n${interrupted}`), text_elements: [] }] : []),
|
|
5042
|
+
];
|
|
5043
|
+
const after = mail.length && !wake ? [{ type: 'text', text: promptSafe(renderMail(mail, session.parentAgent)), text_elements: [] }] : [];
|
|
5044
|
+
const inputLayout: InputLayout = { textParts: 1 + before.length + 1 + attached.length + after.length, prompt: 1 + before.length };
|
|
5045
|
+
const listed = attached.map(({ attachment }) => attachmentMeta(attachment));
|
|
5046
|
+
const invoked = session.runtimeKind === 'codex' && origin === 'user' && prompt.delivery !== 'steer'
|
|
5047
|
+
? session.mapping.agent.skills.find(skill => text.match(/^\/(\S+)(?:\s|$)/)?.[1] === skill.name) : undefined;
|
|
5048
|
+
const nativeInput = [
|
|
5049
|
+
{ type: 'text', text: promptSafe(CATALOG + JSON.stringify({ inputLayout, ...(orchestration as object), ...(listed.length ? { attachments: listed } : {}) })), text_elements: [] },
|
|
5050
|
+
...before,
|
|
3289
5051
|
{
|
|
3290
5052
|
type: 'text',
|
|
3291
5053
|
text: origin === 'user' ? text : promptSafe(text),
|
|
3292
5054
|
text_elements: [],
|
|
3293
5055
|
},
|
|
5056
|
+
...attached.map(({ attachment, staged }) => ({ type: 'text', text: promptSafe(attachmentPart(attachment, staged)), text_elements: [] })),
|
|
3294
5057
|
...images.map(image => ({ type: 'image', url: `data:${image.mimeType};base64,${image.data}` })),
|
|
3295
|
-
...
|
|
5058
|
+
...after,
|
|
5059
|
+
// "/<skill> ..." from the user loads that ALP skill in Codex, as its own $<skill> does (t-efa3).
|
|
5060
|
+
...(invoked ? [{ type: 'skill', name: invoked.name, path: invoked.path }] : []),
|
|
3296
5061
|
];
|
|
3297
5062
|
|
|
3298
5063
|
const result =
|
|
@@ -3317,6 +5082,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3317
5082
|
clientUserMessageId:
|
|
3318
5083
|
prompt.clientMessageId,
|
|
3319
5084
|
input: nativeInput,
|
|
5085
|
+
// Codex keeps a turn's model and effort for later turns too; ALP names both on every turn (§12.9).
|
|
5086
|
+
...(session.runtimeKind === 'codex' ? { model: session.mapping.model } : {}),
|
|
3320
5087
|
effort:
|
|
3321
5088
|
session.mapping.thinking,
|
|
3322
5089
|
approvalPolicy: codexApproval(session.mapping),
|
|
@@ -3333,26 +5100,41 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3333
5100
|
? session.active!
|
|
3334
5101
|
: result.turn.id;
|
|
3335
5102
|
|
|
5103
|
+
if (internalCompact) {
|
|
5104
|
+
const echoes = compactEchoes.get(session) ?? new Map<string, string>();
|
|
5105
|
+
echoes.set(`${session.threadId}:${turnId}`, inputDigest(nativeInput.flatMap(part => 'text' in part ? [String(part.text)] : [])));
|
|
5106
|
+
compactEchoes.set(session, echoes);
|
|
5107
|
+
}
|
|
5108
|
+
|
|
3336
5109
|
for (const event of mail) event.deliveredTurn = turnId;
|
|
3337
5110
|
|
|
5111
|
+
// Only transport-accepted user input renews the root-tree budgets.
|
|
5112
|
+
if (!session.parent && origin === 'user') {
|
|
5113
|
+
session.calls = 0;
|
|
5114
|
+
session.advisorCalls = 0;
|
|
5115
|
+
}
|
|
5116
|
+
|
|
3338
5117
|
session.seen.add(
|
|
3339
5118
|
prompt.clientMessageId,
|
|
3340
5119
|
);
|
|
3341
5120
|
|
|
3342
|
-
emit(sessionId, {
|
|
5121
|
+
if (!internalCompact) emit(sessionId, {
|
|
3343
5122
|
type: 'item',
|
|
3344
5123
|
item: {
|
|
3345
5124
|
kind: 'user_message',
|
|
3346
5125
|
id: `user:${prompt.clientMessageId}`,
|
|
3347
5126
|
clientMessageId: prompt.clientMessageId,
|
|
3348
5127
|
text,
|
|
5128
|
+
origin,
|
|
3349
5129
|
...(images.length ? { images: images.length } : {}),
|
|
5130
|
+
...(listed.length ? { attachments: listed } : {}),
|
|
3350
5131
|
},
|
|
3351
5132
|
});
|
|
3352
5133
|
if (origin === 'user' && !session.parent) session.userWaiting ??= Date.now();
|
|
5134
|
+
if (origin === 'user' && !session.parent && text) session.lastUserText = clip(text, 16_000);
|
|
3353
5135
|
if (session.supervisor && origin === 'user') session.journal.push(stamp(`user ${prompt.delivery === 'steer' ? 'steered' : 'asked'} ${session.mapping.agent.name}: ${clip(text, 1500)}`));
|
|
3354
5136
|
// The steer reaches the model once its waiting tool returns; return it now, not when the work ends.
|
|
3355
|
-
if (prompt.delivery === 'steer' && origin === 'user' && !session.parent) releaseWaiters(session);
|
|
5137
|
+
if (prompt.delivery === 'steer' && origin === 'user' && !session.parent) { releaseWaiters(session); releaseQuestions(sessionId); }
|
|
3356
5138
|
|
|
3357
5139
|
emit(sessionId, {
|
|
3358
5140
|
type: 'prompt.accepted',
|
|
@@ -3394,7 +5176,103 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3394
5176
|
// Threads past their recall time go when the host starts, and after each assignment.
|
|
3395
5177
|
if (options.recallFile) void forgetExpired();
|
|
3396
5178
|
|
|
3397
|
-
|
|
5179
|
+
const api = {
|
|
5180
|
+
registerWorkspace: directory => enqueue(async () => {
|
|
5181
|
+
try { await assignmentResults.register(await realpath(directory)); }
|
|
5182
|
+
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot register workspace result ownership'); }
|
|
5183
|
+
}),
|
|
5184
|
+
withWorkspaceMutation: <T>(directory: string, run: () => Promise<T>, adoption?: typeof ADOPTION): Promise<T> => {
|
|
5185
|
+
// Reserve before enqueue/await: in-flight admission causes refusal, future admission cannot start.
|
|
5186
|
+
if (workspaceMutation || admitting) return Promise.reject(new WorkspaceMutationError('workspace_busy', 'A session or assignment is opening; retry after it finishes'));
|
|
5187
|
+
workspaceMutation = true;
|
|
5188
|
+
return enqueue(async () => {
|
|
5189
|
+
const target = await realpath(directory).catch(() => refuseMutation('workspace_busy', `Cannot resolve workspace ${directory}; inspect its directory before removing it`));
|
|
5190
|
+
let resultLedger: Awaited<ReturnType<typeof assignmentResults.inspect>>;
|
|
5191
|
+
try { resultLedger = await assignmentResults.inspect(); }
|
|
5192
|
+
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot inspect permanent assignment results'); }
|
|
5193
|
+
// Only adoptWorkspace passes ADOPTION, to certify an old checkout after every check below.
|
|
5194
|
+
if (!resultLedger!.workspaces.includes(target) && adoption !== ADOPTION) refuseMutation('workspace_assignment_result', 'Workspace predates authoritative assignment tracking; an audited migration is required before removal');
|
|
5195
|
+
const canonical = (value: string): string => {
|
|
5196
|
+
try { return realpathSync(value); }
|
|
5197
|
+
catch (error) {
|
|
5198
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') refuseMutation('workspace_assignment_result', `Cannot resolve assignment path ${value}; inspect it before removing the workspace`);
|
|
5199
|
+
const parent = path.dirname(value);
|
|
5200
|
+
if (parent === value) throw error;
|
|
5201
|
+
return path.join(canonical(parent), path.basename(value));
|
|
5202
|
+
}
|
|
5203
|
+
};
|
|
5204
|
+
const overlaps = (value: string | undefined) => {
|
|
5205
|
+
if (value === undefined) return false;
|
|
5206
|
+
if (typeof value !== 'string' || !value) refuseMutation('workspace_assignment_result', 'Invalid assignment path; repair runtime persistence before removing the workspace');
|
|
5207
|
+
if (!path.isAbsolute(value)) refuseMutation('workspace_assignment_result', 'Assignment path is not absolute; inspect runtime persistence before removing the workspace');
|
|
5208
|
+
const owner = canonical(value);
|
|
5209
|
+
const contains = (parent: string, child: string) => {
|
|
5210
|
+
const relative = path.relative(parent, child);
|
|
5211
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
5212
|
+
};
|
|
5213
|
+
return contains(target, owner) || contains(owner, target);
|
|
5214
|
+
};
|
|
5215
|
+
// A handled result no longer holds its paths; its evidence stays in the ledger until archived.
|
|
5216
|
+
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}`);
|
|
5217
|
+
// A recall entry outlives the result it describes by up to its own 14 days; once the result is handled, it holds nothing.
|
|
5218
|
+
const resolved = async (assignmentId: string) => {
|
|
5219
|
+
if (resultLedger!.results.some(owner => owner.assignmentId === assignmentId && owner.handled)) return true;
|
|
5220
|
+
try { return !!(await assignmentResults.archived(assignmentId)); }
|
|
5221
|
+
catch { return refuseMutation('workspace_assignment_result', 'Cannot inspect the assignment result archive; repair it before removing the workspace'); }
|
|
5222
|
+
};
|
|
5223
|
+
for (const [project, pins] of loadedBoards) for (const pin of pins) {
|
|
5224
|
+
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}`);
|
|
5225
|
+
}
|
|
5226
|
+
for (const [checkout, holder] of leases) if (overlaps(checkout)) refuseMutation('workspace_leased', `Assignment ${holder.assignment} holds a write lease in ${directory}`);
|
|
5227
|
+
for (const [id, session] of sessions) {
|
|
5228
|
+
for (const assignment of session.assignments.values()) {
|
|
5229
|
+
if (overlaps(assignment.worktree?.path) || overlaps(assignment.worktree?.checkout) || overlaps(assignment.copy?.path) || overlaps(assignment.copy?.checkout) || overlaps(assignment.writeCheckout) || overlaps(assignment.lease)) refuseMutation('workspace_assignment_result', `Resolve assignment ${assignment.id} before removing ${directory}`);
|
|
5230
|
+
}
|
|
5231
|
+
for (const [assignmentId, pending] of session.worktrees) if (overlaps(pending.worktree.path) || overlaps(pending.worktree.checkout) || overlaps(pending.worktree.workdir)) refuseMutation('workspace_assignment_result', `Merge or preserve assignment ${assignmentId} before removing ${directory}`);
|
|
5232
|
+
if (!session.closed && (overlaps(session.mapping.workdir) || overlaps(session.spec.writeRoot))) refuseMutation('workspace_busy', `Close session ${id} before removing ${directory}`);
|
|
5233
|
+
}
|
|
5234
|
+
const checkLive = (entry: LiveEntry) => {
|
|
5235
|
+
if (overlaps(entry.spec.workdir ?? entry.project) || overlaps(entry.spec.writeRoot) || overlaps(entry.copyOf) || overlaps(entry.lease) || overlaps(entry.worktree?.path) || overlaps(entry.worktree?.checkout) || overlaps(entry.worktree?.workdir)) refuseMutation('workspace_assignment_result', `Resolve recoverable assignment ${entry.assignmentId} before removing ${directory}`);
|
|
5236
|
+
};
|
|
5237
|
+
for (const entry of inFlight.all()) checkLive(entry);
|
|
5238
|
+
for (const entry of inherited) checkLive(entry);
|
|
5239
|
+
// Read disk strictly: the normal books intentionally tolerate damaged records.
|
|
5240
|
+
for (const [file, kind] of [[options.liveFile, 'live'], [options.recallFile, 'recall']] as const) {
|
|
5241
|
+
if (!file) continue;
|
|
5242
|
+
let entries: unknown;
|
|
5243
|
+
try { entries = JSON.parse(await readFile(file, 'utf8')); }
|
|
5244
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; throw new WorkspaceMutationError('workspace_assignment_result', `Cannot inspect ${file}; repair assignment persistence before removing the workspace`); }
|
|
5245
|
+
if (!Array.isArray(entries)) refuseMutation('workspace_assignment_result', `Invalid assignment book ${file}`);
|
|
5246
|
+
for (const entry of entries as any[]) {
|
|
5247
|
+
if (!entry || typeof entry.assignmentId !== 'string' || (kind === 'live' ? !entry.spec || typeof entry.spec !== 'object' || Array.isArray(entry.spec) || typeof entry.project !== 'string' : typeof entry.cwd !== 'string')) refuseMutation('workspace_assignment_result', `Invalid assignment record in ${file}`);
|
|
5248
|
+
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}`);
|
|
5249
|
+
if (entry.shared !== undefined && (!entry.shared || typeof entry.shared !== 'object' || Array.isArray(entry.shared))) refuseMutation('workspace_assignment_result', `Invalid shared result in ${file}`);
|
|
5250
|
+
if (kind === 'live') checkLive(entry);
|
|
5251
|
+
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}`);
|
|
5252
|
+
}
|
|
5253
|
+
}
|
|
5254
|
+
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}`);
|
|
5255
|
+
return await run();
|
|
5256
|
+
}).finally(() => { workspaceMutation = false; });
|
|
5257
|
+
},
|
|
5258
|
+
adoptWorkspace: (directory: string, verify: (canonical: string) => Promise<void>): Promise<void> => api.withWorkspaceMutation(directory, async () => {
|
|
5259
|
+
// A path through a symlink names whatever the link points at today; adopt only the canonical path.
|
|
5260
|
+
if (await realpath(directory) !== directory) refuseMutation('workspace_identity', `Adopt ${directory} by its canonical path`);
|
|
5261
|
+
await verify(directory);
|
|
5262
|
+
try { await assignmentResults.register(directory); }
|
|
5263
|
+
catch (error) { refuseMutation('workspace_assignment_result', error instanceof Error ? error.message : 'Cannot register workspace result ownership'); }
|
|
5264
|
+
}, ADOPTION),
|
|
5265
|
+
bindSchedules(handler: ScheduleHandler | undefined) { scheduleHandler = handler; },
|
|
5266
|
+
bindAttachments(reader: AttachmentReader | undefined) { attachmentReader = reader; },
|
|
5267
|
+
refusesPrompt(sessionId: string, content: PromptContent) {
|
|
5268
|
+
const session = sessions.get(sessionId);
|
|
5269
|
+
return session ? nativeCommandRefusal(session.runtimeKind, content, session.runtime.customCommands?.()) : undefined;
|
|
5270
|
+
},
|
|
5271
|
+
takesAttachments(sessionId: string) {
|
|
5272
|
+
const session = sessions.get(sessionId);
|
|
5273
|
+
return !!session && !session.closed && attachmentRoutes(session).includes('file.path');
|
|
5274
|
+
},
|
|
5275
|
+
async dropAttachment(attachmentId: string) { await stager?.drop(attachmentId); },
|
|
3398
5276
|
onEvent(listener) {
|
|
3399
5277
|
listeners.add(listener);
|
|
3400
5278
|
return () => {
|
|
@@ -3406,24 +5284,100 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3406
5284
|
const opened = await openSession(sessionId, spec, history, delegation);
|
|
3407
5285
|
const root = sessions.get(sessionId)!;
|
|
3408
5286
|
// Main starts its supervisor beside it, without delaying its own open.
|
|
3409
|
-
if (supervises(root))
|
|
5287
|
+
if (supervises(root)) {
|
|
5288
|
+
void enqueue(() => openSupervisor(sessionId));
|
|
5289
|
+
void ensureCurateSchedule(sessionId).catch(error => runLog(sessionId, { event: 'curate.schedule.failed', error: errorData(error).message }));
|
|
5290
|
+
}
|
|
3410
5291
|
return opened;
|
|
3411
5292
|
}),
|
|
3412
5293
|
|
|
3413
|
-
prompt: (sessionId, input) => enqueue(
|
|
3414
|
-
|
|
3415
|
-
|
|
3416
|
-
|
|
3417
|
-
const session =
|
|
3418
|
-
if (session
|
|
3419
|
-
|
|
3420
|
-
|
|
3421
|
-
|
|
5294
|
+
prompt: (sessionId, input) => enqueue(() => promptSession(sessionId, input)),
|
|
5295
|
+
|
|
5296
|
+
withIdlePrompt: (sessionId, run) => new Promise((resolve, reject) => {
|
|
5297
|
+
void enqueue(async () => {
|
|
5298
|
+
const session = openOf(sessionId);
|
|
5299
|
+
if (session.active || session.pending || session.lifecycleHolds || session.mail.some(event => event.deliveredTurn === STARTING)) { resolve({ busy: true }); return; }
|
|
5300
|
+
// Expose the reservation to lifecycle operations before any durable write can yield.
|
|
5301
|
+
admittedPrompts.add(sessionId);
|
|
5302
|
+
// Keep newly arriving mail unreserved until this admitted prompt has finished preparation.
|
|
5303
|
+
session.lifecycleHolds = (session.lifecycleHolds ?? 0) + 1;
|
|
5304
|
+
let valid = true;
|
|
5305
|
+
let used = false;
|
|
5306
|
+
let sending: Promise<void> | undefined;
|
|
5307
|
+
try {
|
|
5308
|
+
const value = await run(input => {
|
|
5309
|
+
if (!valid || used) return Promise.reject(new Error('The admitted prompt sender is no longer available'));
|
|
5310
|
+
used = true;
|
|
5311
|
+
sending = promptSession(sessionId, input);
|
|
5312
|
+
return sending;
|
|
5313
|
+
});
|
|
5314
|
+
resolve({ busy: false, value });
|
|
5315
|
+
} catch (error) {
|
|
5316
|
+
reject(error);
|
|
5317
|
+
} finally {
|
|
5318
|
+
valid = false;
|
|
5319
|
+
// A timeout of the caller cannot release the queue while its native start is outstanding.
|
|
5320
|
+
try { await sending; }
|
|
5321
|
+
finally {
|
|
5322
|
+
admittedPrompts.delete(sessionId);
|
|
5323
|
+
session.lifecycleHolds = Math.max(0, (session.lifecycleHolds ?? 1) - 1);
|
|
5324
|
+
if (!session.lifecycleHolds && !session.closed && session.wakeHeld) {
|
|
5325
|
+
session.wakeHeld = false;
|
|
5326
|
+
deliver(sessionId, session);
|
|
5327
|
+
}
|
|
5328
|
+
}
|
|
5329
|
+
}
|
|
5330
|
+
}).catch(reject);
|
|
3422
5331
|
}),
|
|
3423
5332
|
|
|
3424
5333
|
interrupt: sessionId => enqueue(() => interruptSession(sessionId)),
|
|
5334
|
+
interruptTurn: (sessionId, turnId) => enqueue(async () => {
|
|
5335
|
+
// Compare in the same admission slot as the cancellation, before any side effect or await.
|
|
5336
|
+
if (sessions.get(sessionId)?.active !== turnId) return false;
|
|
5337
|
+
await interruptSession(sessionId);
|
|
5338
|
+
return true;
|
|
5339
|
+
}),
|
|
5340
|
+
|
|
5341
|
+
configure: (sessionId, changes, options) => enqueue(() => configureSession(sessionId, changes, options?.onApplied)),
|
|
5342
|
+
|
|
5343
|
+
branch: request => branchConversation(request),
|
|
5344
|
+
|
|
5345
|
+
rebind: (sessionId, binding) => enqueue(() => rebindSession(sessionId, binding)),
|
|
5346
|
+
|
|
5347
|
+
reload: sessionId => enqueue(() => reloadSession(sessionId)),
|
|
5348
|
+
compact: (sessionId: string) => requestCompact(sessionId),
|
|
5349
|
+
commands: (sessionId: string) => listCommands(sessionId),
|
|
5350
|
+
|
|
5351
|
+
previewConfigure: (sessionId, changes) => previewConfigureSession(sessionId, changes),
|
|
5352
|
+
|
|
5353
|
+
reconfigure: (sessionId, changes, options) => enqueue(() => reconfigureSession(sessionId, changes, options)),
|
|
3425
5354
|
|
|
3426
|
-
|
|
5355
|
+
starting: sessionId => {
|
|
5356
|
+
const session = sessions.get(sessionId);
|
|
5357
|
+
return !!session && !session.closed && (admittedPrompts.has(sessionId) || !!session.pending || session.mail.some(event => event.deliveredTurn === STARTING));
|
|
5358
|
+
},
|
|
5359
|
+
|
|
5360
|
+
hold: sessionId => {
|
|
5361
|
+
const session = sessions.get(sessionId);
|
|
5362
|
+
if (!session || session.closed) return undefined;
|
|
5363
|
+
session.lifecycleHolds = (session.lifecycleHolds ?? 0) + 1;
|
|
5364
|
+
let released = false;
|
|
5365
|
+
return () => {
|
|
5366
|
+
if (released) return;
|
|
5367
|
+
released = true;
|
|
5368
|
+
session.lifecycleHolds = Math.max(0, (session.lifecycleHolds ?? 1) - 1);
|
|
5369
|
+
if (session.lifecycleHolds || session.closed) return;
|
|
5370
|
+
// Parked work a resume reached during the hold continues now; paused again, it waits for that resume.
|
|
5371
|
+
if (session.resumeHeld) {
|
|
5372
|
+
const expected = session.resumeHeld;
|
|
5373
|
+
session.resumeHeld = undefined;
|
|
5374
|
+
if (session.parked === expected) return continueParked(sessionId, session, expected);
|
|
5375
|
+
}
|
|
5376
|
+
if (session.parked || pauseOf(session.runtimeKind) || !session.wakeHeld) return;
|
|
5377
|
+
session.wakeHeld = false;
|
|
5378
|
+
deliver(sessionId, session);
|
|
5379
|
+
};
|
|
5380
|
+
},
|
|
3427
5381
|
|
|
3428
5382
|
close: sessionId => enqueue(async () => {
|
|
3429
5383
|
openOf(sessionId);
|
|
@@ -3450,7 +5404,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3450
5404
|
};
|
|
3451
5405
|
visit(rootId);
|
|
3452
5406
|
const questions = [...userQuestions.values()].map(pending => pending.question).filter(question => question.rootId === rootId);
|
|
3453
|
-
const asking = new Set(questions.map(question => question.sessionId));
|
|
5407
|
+
const asking = new Set(questions.filter(question => !question.gate).map(question => question.sessionId));
|
|
3454
5408
|
const ids = new Set(tree.map(([id]) => id));
|
|
3455
5409
|
return {
|
|
3456
5410
|
rootId,
|
|
@@ -3500,6 +5454,26 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3500
5454
|
},
|
|
3501
5455
|
|
|
3502
5456
|
pauses: () => pauseState(),
|
|
5457
|
+
|
|
5458
|
+
holdForDisk(reason) {
|
|
5459
|
+
// A pause of all ALP already holds the work; the user's stays theirs to lift.
|
|
5460
|
+
if (paused.all) return pauseState();
|
|
5461
|
+
pauseRuntime('all', { since: new Date().toISOString(), by: 'alpd', reason, cause: 'disk' }, true);
|
|
5462
|
+
notice('error', say => say.diskFull(reason));
|
|
5463
|
+
return pauseState();
|
|
5464
|
+
},
|
|
5465
|
+
|
|
5466
|
+
releaseDisk(by) {
|
|
5467
|
+
if (paused.all?.cause !== 'disk') return pauseState();
|
|
5468
|
+
resumeRuntime('all', by, true);
|
|
5469
|
+
return pauseState();
|
|
5470
|
+
},
|
|
5471
|
+
|
|
5472
|
+
diskHeld: () => paused.all?.cause === 'disk',
|
|
5473
|
+
|
|
5474
|
+
diskLow(free) {
|
|
5475
|
+
notice('warning', say => say.diskLow(free));
|
|
5476
|
+
},
|
|
3503
5477
|
async usage(refresh = false) {
|
|
3504
5478
|
const providers = await Promise.all((['codex', 'claude'] as const).map(kind => cachedUsage(kind, refresh)));
|
|
3505
5479
|
const state = pauseState();
|
|
@@ -3538,6 +5512,11 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3538
5512
|
};
|
|
3539
5513
|
},
|
|
3540
5514
|
|
|
5515
|
+
syncGates(projectRoot) {
|
|
5516
|
+
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) return Promise.reject(new Error('syncGates needs an absolute projectRoot'));
|
|
5517
|
+
return syncGates(projectRoot);
|
|
5518
|
+
},
|
|
5519
|
+
|
|
3541
5520
|
async board(projectRoot) {
|
|
3542
5521
|
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) throw new Error('board needs an absolute projectRoot');
|
|
3543
5522
|
return (await boardOf(path.resolve(projectRoot))).filter(live);
|
|
@@ -3559,6 +5538,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3559
5538
|
answer(questionId, reply) {
|
|
3560
5539
|
const pending = userQuestions.get(questionId);
|
|
3561
5540
|
if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
|
|
5541
|
+
if (pending.gate) {
|
|
5542
|
+
if (!reply.dismiss && (typeof reply.text !== 'string' || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error('An answer needs text');
|
|
5543
|
+
return pending.gate.decide(reply);
|
|
5544
|
+
}
|
|
3562
5545
|
if (reply.dismiss) {
|
|
3563
5546
|
pending.settle('dismissed', undefined, reply.reason);
|
|
3564
5547
|
return;
|
|
@@ -3578,8 +5561,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3578
5561
|
return [...inherited];
|
|
3579
5562
|
},
|
|
3580
5563
|
|
|
3581
|
-
recover(rootId, { continueRoot = false } = {}) {
|
|
3582
|
-
return enqueue(() => recoverTree(rootId, continueRoot));
|
|
5564
|
+
recover(rootId, { continueRoot = false, parkedRoot } = {}) {
|
|
5565
|
+
return enqueue(() => recoverTree(rootId, continueRoot, parkedRoot));
|
|
3583
5566
|
},
|
|
3584
5567
|
|
|
3585
5568
|
async abandon(rootId, reason) {
|
|
@@ -3590,17 +5573,22 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3590
5573
|
},
|
|
3591
5574
|
|
|
3592
5575
|
async shutdown() {
|
|
5576
|
+
compactEchoes.clear();
|
|
3593
5577
|
closed = true;
|
|
3594
5578
|
|
|
3595
5579
|
await queue;
|
|
3596
5580
|
|
|
3597
5581
|
await Promise.all(
|
|
3598
5582
|
[...sessions.keys()].map(
|
|
3599
|
-
closeSession,
|
|
5583
|
+
id => closeSession(id),
|
|
3600
5584
|
),
|
|
3601
5585
|
);
|
|
3602
5586
|
|
|
3603
5587
|
clearInterval(watchdog);
|
|
5588
|
+
if (gateWatch) clearInterval(gateWatch);
|
|
5589
|
+
for (const root of [...gateFiles.keys()]) unwatchGateFiles(root);
|
|
5590
|
+
await Promise.all(gateSyncs.values());
|
|
5591
|
+
await Promise.all(gateMarks);
|
|
3604
5592
|
|
|
3605
5593
|
// Claims released by the closes above are written before the board is left.
|
|
3606
5594
|
await Promise.all(boards.values());
|
|
@@ -3615,5 +5603,6 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3615
5603
|
|
|
3616
5604
|
listeners.clear();
|
|
3617
5605
|
},
|
|
3618
|
-
};
|
|
5606
|
+
} satisfies AlpRuntime;
|
|
5607
|
+
return api;
|
|
3619
5608
|
}
|