@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/dist/runtime.js
CHANGED
|
@@ -1,52 +1,89 @@
|
|
|
1
1
|
// packages/runtime/src/runtime.ts
|
|
2
|
+
import { createAssignmentResults, RESULT_OUTCOMES } from "./assignment-results.js";
|
|
2
3
|
import { constants as fsConstants } from "node:fs";
|
|
3
4
|
import { errorData, plainObject, toolResult } from "./tool-results.js";
|
|
5
|
+
import { inputLimitError, POUR_VARS, TOOL_INPUT, VAR_NAME } from "./input-limits.js";
|
|
4
6
|
import { createLogger } from "@anhlp/alp-core/log";
|
|
5
7
|
import { PROMPT_IMAGES, base64Bytes } from "@anhlp/alp-protocol";
|
|
6
8
|
import { createBoardDomain } from "./board-domain.js";
|
|
9
|
+
import { ATTACHMENT_ROUTES, STAGED_PATH, attachmentPart, createAttachmentStager, runtimeAttachment, stagingExposure } from "./attachments.js";
|
|
7
10
|
import { createWorktreeDomain } from "./worktree-domain.js";
|
|
11
|
+
import { ConversationError } from "./contracts.js";
|
|
12
|
+
import { claudeCut, codexForkEnd, codexForkRefusal, pendingChain } from "./conversation.js";
|
|
8
13
|
import { DEFAULT_TEAM } from "./contracts.js";
|
|
9
14
|
import { verdictLine, parseHandoff } from "./handoff.js";
|
|
10
|
-
import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, roleOf, taskActions, taskBrief } from "./tools.js";
|
|
15
|
+
import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, readOnlyMember, roleOf, taskActions, taskBrief } from "./tools.js";
|
|
11
16
|
import { nativeEnvironment, createTransport } from "./providers.js";
|
|
12
17
|
import { nativeMode, codexApproval, profileEfforts, nativeSessionConfig } from "./session-config.js";
|
|
13
18
|
import { createHash, randomUUID } from "node:crypto";
|
|
14
|
-
import { readFileSync, realpathSync } from "node:fs";
|
|
15
|
-
import { appendFile, mkdir, open, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
|
|
16
|
-
import {
|
|
19
|
+
import { readFileSync, realpathSync, watch as watchFiles } from "node:fs";
|
|
20
|
+
import { appendFile, mkdir, open, readdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
|
|
21
|
+
import { checkFrontmatter, skillReferences, splitSkill } from "@anhlp/alp-core/skill-validate";
|
|
22
|
+
import { resourceUses } from "./skill-resources.js";
|
|
23
|
+
import { moveFile, writeAtomic } from "@anhlp/alp-core/atomic";
|
|
17
24
|
import os from "node:os";
|
|
18
25
|
import path from "node:path";
|
|
19
26
|
import { resolveDelegation } from "@anhlp/alp-core/delegation";
|
|
20
|
-
import { discoverAgents } from "@anhlp/alp-core/resolver";
|
|
27
|
+
import { agentSources, builtinText, discoverAgents } from "@anhlp/alp-core/resolver";
|
|
21
28
|
import { acpDecision, acpWhat } from "./acp-transport.js";
|
|
22
29
|
import { models, modes, thinkingOptionsFor, withinMode, writes } from "./catalog.js";
|
|
30
|
+
import { feedCatalog } from "./model-catalog.js";
|
|
23
31
|
import { runHook } from "@anhlp/alp-core/hook-run";
|
|
24
32
|
import { hookMatches } from "@anhlp/alp-core/hooks";
|
|
25
33
|
import { isTrusted, trustProject } from "@anhlp/alp-core/trust";
|
|
26
|
-
import { listTeams } from "@anhlp/alp-core/teams";
|
|
34
|
+
import { listTeams, teamOf } from "@anhlp/alp-core/teams";
|
|
35
|
+
import { CONFIGURABLE, changesOf, effectiveOf, executablesOf, nativeModelOf, offered } from "./configure.js";
|
|
27
36
|
import { anyModel, offers, profileModel, selectedProfile } from "@anhlp/alp-core/profiles";
|
|
28
|
-
import { LESSONS_FILE,
|
|
29
|
-
import { MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from "./mailbox.js";
|
|
37
|
+
import { LESSONS_FILE, resolveSession, skillDescription } from "./resolve.js";
|
|
38
|
+
import { MAIL_BODY_CHARS, MAIL_HEADER, publicEvent, renderMail, takeBatch, USER } from "./mailbox.js";
|
|
30
39
|
import { live, normalizePaths, overlapping, renderBoard } from "./board.js";
|
|
31
40
|
import { verifyConfig } from "@anhlp/alp-core/verify";
|
|
32
41
|
import { createLiveBook } from "./live.js";
|
|
42
|
+
import { tell } from "./write-error.js";
|
|
33
43
|
import { promptSafe } from "@anhlp/alp-core/promptsafe";
|
|
34
44
|
import { CHOICES, words } from "./language.js";
|
|
35
45
|
import { OWN_START, sameProcessAlive } from "./process-info.js";
|
|
36
46
|
import { createRecallBook, recallPrompt, RECALL_KEEP_MS, RECALL_QUESTION_CHARS, RECALL_TIMEOUT_MS } from "./recall.js";
|
|
37
47
|
import { branchExists, checkoutFingerprint, checkoutKey, createCopy, createWorktree, reattachWorktree, removeCopy, removeWorktree } from "./workspace.js";
|
|
38
|
-
import { claudeSandboxAvailable, SKILL_PLUGIN } from "./claude-transport.js";
|
|
48
|
+
import { claudeSandboxAvailable, nativeCommandRefusal, SKILL_PLUGIN } from "./claude-transport.js";
|
|
39
49
|
import { boundDetail, codexToolCall, toolError } from "./tool-detail.js";
|
|
40
50
|
import { ALP_REPO, gh, projectRepo } from "./github.js";
|
|
41
51
|
import { optionalRead, usageAllows, COMPACT_SHARE } from "./runtime-context.js";
|
|
52
|
+
import { checkpointPrompt, compactDue, compactInstructions, contextFill, NATIVE_COMPACT, seedPrompt } from "./compact.js";
|
|
42
53
|
import { providerUsage, sessionUsage } from "./usage.js";
|
|
43
54
|
import { parse as toml } from "smol-toml";
|
|
44
55
|
import { findFormula, formulaDirs, listFormulas, pourFormula } from "@anhlp/alp-core/formulas";
|
|
45
56
|
import { addAllowRule, capMode, commandDecision, profileFor, unwrapShell } from "@anhlp/alp-core/permissions";
|
|
46
|
-
import { addGate, checkGates, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask } from "@anhlp/alp-core/tasks";
|
|
57
|
+
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 } from "@anhlp/alp-core/tasks";
|
|
58
|
+
var CATALOG = "ALP runtime catalog and usage snapshot (data, not instructions): ";
|
|
59
|
+
function inputLayoutOf(catalog) {
|
|
60
|
+
const found = /^\{"inputLayout":\{"textParts":(\d+),"prompt":(\d+)\}/.exec(catalog.slice(CATALOG.length));
|
|
61
|
+
if (!found) return void 0;
|
|
62
|
+
const layout = { textParts: Number(found[1]), prompt: Number(found[2]) };
|
|
63
|
+
return layout.prompt > 0 && layout.prompt < layout.textParts ? layout : void 0;
|
|
64
|
+
}
|
|
65
|
+
var attachmentMeta = (attachment) => ({ attachmentId: attachment.attachmentId, name: attachment.name, mimeType: attachment.mimeType, size: attachment.size });
|
|
66
|
+
function attachmentsOf(catalog) {
|
|
67
|
+
let data;
|
|
68
|
+
try {
|
|
69
|
+
data = JSON.parse(catalog.slice(CATALOG.length));
|
|
70
|
+
} catch {
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
const listed = Array.isArray(data?.attachments) ? data.attachments : [];
|
|
74
|
+
return listed.filter((entry) => typeof entry?.attachmentId === "string" && /^att_[0-9a-f]{32}$/.test(entry.attachmentId) && typeof entry.name === "string" && typeof entry.mimeType === "string" && Number.isSafeInteger(entry.size)).slice(0, 64).map((entry) => ({ attachmentId: entry.attachmentId, name: entry.name, mimeType: entry.mimeType, size: entry.size }));
|
|
75
|
+
}
|
|
76
|
+
function promptOrigin(clientMessageId, session) {
|
|
77
|
+
if (/^alp-(wake|mail)-/.test(clientMessageId)) return "wake";
|
|
78
|
+
if (/^(alp-review-|task-)/.test(clientMessageId)) return "assignment";
|
|
79
|
+
if (/^alp-(resume|recover)-/.test(clientMessageId)) return session.parent ? "assignment" : "wake";
|
|
80
|
+
return "user";
|
|
81
|
+
}
|
|
82
|
+
var COMPACT_PROMPT = "alp-wake-compact-";
|
|
47
83
|
var MAX_WAKES = 8;
|
|
48
84
|
var USER_REPLY_MS = 6e4;
|
|
49
85
|
var USER_WROTE = "The user just wrote to you; their message follows. Answer them first in a short message they can read (tool calls alone show them nothing), and steer an assignment with alp_send when their words change its brief. Your assignments keep running: then alp_wait again, or end your turn and ALP wakes you with their results.";
|
|
86
|
+
var TURN_ENDED = "Turn ended before the result arrived. Running assignments keep running; ALP wakes you with their results as mail.";
|
|
50
87
|
var 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.";
|
|
51
88
|
var RESTART_LIMIT = 3;
|
|
52
89
|
var RESTART_WINDOW_MS = 10 * 6e4;
|
|
@@ -54,15 +91,24 @@ var LIMIT_CHECK_MS = 6e4;
|
|
|
54
91
|
var LIMIT_FRESH_MS = 15e3;
|
|
55
92
|
var CONTEXT_SOON = 0.9;
|
|
56
93
|
var CONTEXT_RESET = 0.5;
|
|
94
|
+
var COMPACT_RETRY_MS = 10 * 6e4;
|
|
95
|
+
var MAIL_WAITS = "Mail waits for the session";
|
|
96
|
+
var REVIEWING = "The supervisor is reviewing the session";
|
|
97
|
+
var COMPACT_NATIVE_MS = 5 * 6e4;
|
|
57
98
|
var BRIEF_CHARS = 8e3;
|
|
99
|
+
var RESULT_EVIDENCE_CHARS = 2e3;
|
|
100
|
+
var RESOLVE_NOTE_CHARS = 2e3;
|
|
58
101
|
var STEERING = "\0steering";
|
|
59
102
|
var STARTING = "\0starting";
|
|
60
103
|
var APPROVALS = ["approve", "approved", "yes", "y", "ok", "\u0111\u1ED3ng \xFD", "duy\u1EC7t", "c\xF3"];
|
|
104
|
+
var CHOICES_REJECT = ["reject", "t\u1EEB ch\u1ED1i"];
|
|
61
105
|
var SKILL_BODY_CHARS = 2e4;
|
|
62
106
|
var STARTER_ROLES = ["main", "lead", "peer", "oracle", "reviewer", "supervisor"];
|
|
63
107
|
var ISSUE_BODY_CHARS = 2e4;
|
|
64
108
|
var ISSUE_FOOTER = "\n\n---\n_Drafted by an ALP agent and posted with the user's approval._";
|
|
65
109
|
var LESSON_CHARS = 600;
|
|
110
|
+
var CURATE_MARKER = "[alp-curate]";
|
|
111
|
+
var CURATE_PROMPT = `${CURATE_MARKER} Monthly review of lessons and skills. Use the curate skill: read every lesson and skill, then propose to the user, in one message, the merges, shortenings and removals of lessons, the skills no longer needed, and what ALP itself should adopt. Change nothing before the user approves. To turn this off, set curate.monthly to false in .alp/settings.json.`;
|
|
66
112
|
var DIGEST_CHARS = 12e3;
|
|
67
113
|
var JOURNAL_LINE_CHARS = 400;
|
|
68
114
|
var clock = (at = Date.now()) => new Date(at).toTimeString().slice(0, 8);
|
|
@@ -77,14 +123,29 @@ var clip = (text, limit = JOURNAL_LINE_CHARS) => {
|
|
|
77
123
|
};
|
|
78
124
|
var isolationOf = (args) => args.isolation ?? "shared";
|
|
79
125
|
var log = createLogger({ component: "runtime" });
|
|
126
|
+
var WorkspaceMutationError = class extends Error {
|
|
127
|
+
data;
|
|
128
|
+
constructor(reason, message) {
|
|
129
|
+
super(message);
|
|
130
|
+
this.name = "WorkspaceMutationError";
|
|
131
|
+
this.data = { reason };
|
|
132
|
+
}
|
|
133
|
+
};
|
|
80
134
|
function createAlpRuntime(options = {}) {
|
|
81
135
|
const sessions = /* @__PURE__ */ new Map();
|
|
136
|
+
const compactEchoes = /* @__PURE__ */ new Map();
|
|
137
|
+
const inputDigest = (parts) => createHash("sha256").update(JSON.stringify(parts)).digest("hex");
|
|
138
|
+
const admittedPrompts = /* @__PURE__ */ new Set();
|
|
82
139
|
const wordsFor = (session) => words(session.mapping.language);
|
|
83
140
|
const childContexts = /* @__PURE__ */ new Map();
|
|
84
141
|
const listeners = /* @__PURE__ */ new Set();
|
|
85
142
|
const epoch = randomUUID();
|
|
86
|
-
const
|
|
87
|
-
|
|
143
|
+
const writeFailed = (error) => {
|
|
144
|
+
options.onWriteError?.(error);
|
|
145
|
+
};
|
|
146
|
+
const recalls = createRecallBook(options.recallFile, writeFailed);
|
|
147
|
+
const assignmentResults = createAssignmentResults(options.assignmentResultFile, writeFailed);
|
|
148
|
+
const inFlight = createLiveBook(options.liveFile, writeFailed);
|
|
88
149
|
let inherited = inFlight.all().filter((entry) => entry.epoch !== epoch);
|
|
89
150
|
let paused = { runtimes: {} };
|
|
90
151
|
try {
|
|
@@ -101,10 +162,34 @@ function createAlpRuntime(options = {}) {
|
|
|
101
162
|
const leases = /* @__PURE__ */ new Map();
|
|
102
163
|
const worktreeRoot = options.worktreeDir ?? path.join(os.tmpdir(), "alp-worktrees");
|
|
103
164
|
const copyRoot = options.copyDir ?? path.join(os.tmpdir(), "alp-copies");
|
|
165
|
+
const stager = options.attachmentStageDir ? createAttachmentStager(options.attachmentStageDir) : void 0;
|
|
166
|
+
let attachmentReader;
|
|
167
|
+
const stagingWarned = /* @__PURE__ */ new Set();
|
|
168
|
+
if (stager) void stager.sweep();
|
|
104
169
|
const sequences = /* @__PURE__ */ new Map();
|
|
170
|
+
let workspaceMutation = false;
|
|
171
|
+
let admitting = 0;
|
|
172
|
+
const refuseMutation = (reason, message) => {
|
|
173
|
+
throw new WorkspaceMutationError(reason, message);
|
|
174
|
+
};
|
|
175
|
+
const ADOPTION = Symbol("adoption");
|
|
176
|
+
async function admission(run) {
|
|
177
|
+
if (workspaceMutation) refuseMutation("workspace_busy", "A workspace mutation is in progress; retry after it finishes");
|
|
178
|
+
admitting++;
|
|
179
|
+
try {
|
|
180
|
+
return await run();
|
|
181
|
+
} finally {
|
|
182
|
+
admitting--;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
105
185
|
let closed = false;
|
|
106
186
|
let queue = Promise.resolve();
|
|
107
187
|
const emit = (sessionId, event) => {
|
|
188
|
+
if (stager) {
|
|
189
|
+
const json = JSON.stringify(event);
|
|
190
|
+
const named = stager.spellings().map((root) => JSON.stringify(root).slice(1, -1)).filter((root) => json.includes(root));
|
|
191
|
+
if (named.length) event = JSON.parse(named.reduce((text2, root) => text2.replace(new RegExp(`${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![A-Za-z0-9_-]|\\.[A-Za-z0-9_-])`, "g"), STAGED_PATH), json));
|
|
192
|
+
}
|
|
108
193
|
const seq = (sequences.get(sessionId) ?? 0) + 1;
|
|
109
194
|
sequences.set(sessionId, seq);
|
|
110
195
|
const envelope = { sessionId, epoch, seq, ts: (/* @__PURE__ */ new Date()).toISOString(), event };
|
|
@@ -123,6 +208,9 @@ function createAlpRuntime(options = {}) {
|
|
|
123
208
|
function takesImages(session) {
|
|
124
209
|
return session.runtime.takesImages ? session.runtime.takesImages() : session.runtimeKind === "codex" || session.runtimeKind === "claude";
|
|
125
210
|
}
|
|
211
|
+
function attachmentRoutes(session) {
|
|
212
|
+
return stager && attachmentReader ? ATTACHMENT_ROUTES[session.runtimeKind] ?? [] : [];
|
|
213
|
+
}
|
|
126
214
|
function snapshot(sessionId, session) {
|
|
127
215
|
return {
|
|
128
216
|
id: sessionId,
|
|
@@ -139,11 +227,13 @@ function createAlpRuntime(options = {}) {
|
|
|
139
227
|
...session.parent ? { parentId: session.parent } : {},
|
|
140
228
|
...session.toolCallId ? { toolCallId: session.toolCallId } : {},
|
|
141
229
|
...session.active ? { activeTurnId: session.active } : {},
|
|
142
|
-
|
|
230
|
+
// turn.ended listeners persist the intent before terminal() finishes parking it.
|
|
231
|
+
...session.parked?.reason ?? session.parkReason ? { parked: session.parked?.reason ?? session.parkReason } : {},
|
|
143
232
|
...session.instructionsSha ? { instructionsSha: session.instructionsSha } : {},
|
|
144
233
|
...takesImages(session) ? { promptImages: true } : {},
|
|
234
|
+
...attachmentRoutes(session).length ? { promptAttachments: [...attachmentRoutes(session)] } : {},
|
|
145
235
|
...session.usage ? { usage: session.usage } : {},
|
|
146
|
-
busy: !!(session.active || session.pending || session.children.size || session.assignments.size || hasActiveMail(session) || reviewing(session))
|
|
236
|
+
busy: !!(session.active || session.pending || session.parked || session.parkReason || session.children.size || session.assignments.size || hasActiveMail(session) || reviewing(session))
|
|
147
237
|
};
|
|
148
238
|
}
|
|
149
239
|
function terminal(sessionId, session, state, error) {
|
|
@@ -161,9 +251,11 @@ function createAlpRuntime(options = {}) {
|
|
|
161
251
|
clearTimeout(waiter.timer);
|
|
162
252
|
waiter.resolve(null);
|
|
163
253
|
}
|
|
164
|
-
cancelQuestions(sessionId);
|
|
254
|
+
cancelQuestions(sessionId, true);
|
|
165
255
|
if (session.parent) sessions.get(session.parent)?.assignments.get(sessionId)?.ask?.resolve(toolResult(false, { error: "Turn ended" }));
|
|
166
|
-
|
|
256
|
+
const taken = state === "completed" ? session.mail.filter((event) => event.deliveredTurn === turnId) : [];
|
|
257
|
+
session.mail = session.mail.filter((event) => !taken.includes(event));
|
|
258
|
+
for (const event of taken) gateMail.get(event)?.taken();
|
|
167
259
|
for (const event of session.mail) {
|
|
168
260
|
if (event.deliveredTurn === turnId) {
|
|
169
261
|
event.deliveredTurn = void 0;
|
|
@@ -180,19 +272,38 @@ function createAlpRuntime(options = {}) {
|
|
|
180
272
|
}
|
|
181
273
|
session.userStopped = false;
|
|
182
274
|
if (session.role === "supervisor" && session.parent && sessions.get(session.parent)?.reviewPending) review(session.parent);
|
|
275
|
+
if (session.role === "supervisor" && session.parent) {
|
|
276
|
+
const root = sessions.get(session.parent);
|
|
277
|
+
if (root) queueMicrotask(() => compactAtBoundary(session.parent, root));
|
|
278
|
+
}
|
|
183
279
|
if (!session.parent) void showTasks(sessionId, session);
|
|
280
|
+
if (!session.parent && session.role !== "supervisor") queueMicrotask(() => compactAtBoundary(sessionId, session, state));
|
|
184
281
|
if (session.parkReason && state !== "completed") {
|
|
185
282
|
park(sessionId, session);
|
|
186
283
|
return;
|
|
187
284
|
}
|
|
188
285
|
session.parkReason = void 0;
|
|
286
|
+
session.parkPause = void 0;
|
|
189
287
|
if (state === "completed" && (session.assignments.size || hasActiveMail(session))) {
|
|
190
288
|
queueMicrotask(() => deliver(sessionId, session));
|
|
191
289
|
return;
|
|
192
290
|
}
|
|
193
291
|
session.settle?.(state, error);
|
|
194
292
|
}
|
|
195
|
-
function
|
|
293
|
+
function nativePrompt(item, session) {
|
|
294
|
+
const parts = (item.content ?? []).filter((c) => c.type === "text").map((c) => String(c.text ?? ""));
|
|
295
|
+
const clientMessageId = typeof item.clientId === "string" && item.clientId ? item.clientId : void 0;
|
|
296
|
+
if (!parts[0]?.startsWith(CATALOG)) return { text: parts.join("\n"), ...clientMessageId ? { clientMessageId } : {}, origin: clientMessageId ? promptOrigin(clientMessageId, session) : parts[0]?.startsWith(MAIL_HEADER) ? "wake" : "user" };
|
|
297
|
+
const origin = clientMessageId ? promptOrigin(clientMessageId, session) : void 0;
|
|
298
|
+
const ids = { ...clientMessageId ? { clientMessageId } : {}, ...origin ? { origin } : {} };
|
|
299
|
+
const layout = inputLayoutOf(parts[0]);
|
|
300
|
+
const attached = attachmentsOf(parts[0]);
|
|
301
|
+
if (layout) return { text: parts.length === layout.textParts ? parts[layout.prompt] ?? "" : "", ...ids, ...attached.length ? { attachments: attached } : {} };
|
|
302
|
+
const rest = parts.slice(1);
|
|
303
|
+
if (!clientMessageId?.startsWith("alp-wake-") && rest.length > 1 && rest.at(-1).startsWith(MAIL_HEADER)) rest.pop();
|
|
304
|
+
return { text: rest.at(-1) ?? "", ...ids };
|
|
305
|
+
}
|
|
306
|
+
function nativeItem(sessionId, session, item, done = false, turnId) {
|
|
196
307
|
if (item.type === "agentMessage") {
|
|
197
308
|
if (session.userWaiting !== void 0 && String(item.text ?? "").trim()) {
|
|
198
309
|
if (session.supervisor) session.journal.push(stamp(`${session.mapping.agent.name} answered the user ${span(Date.now() - session.userWaiting)} after their message of ${clock(session.userWaiting)}`));
|
|
@@ -203,9 +314,13 @@ function createAlpRuntime(options = {}) {
|
|
|
203
314
|
return;
|
|
204
315
|
}
|
|
205
316
|
if (item.type === "userMessage") {
|
|
206
|
-
const
|
|
317
|
+
const { text: text2, clientMessageId, origin, attachments } = nativePrompt(item, session);
|
|
318
|
+
if (turnId) {
|
|
319
|
+
const digest = inputDigest((item.content ?? []).filter((part) => part.type === "text").map((part) => String(part.text ?? "")));
|
|
320
|
+
for (const echoes of compactEchoes.values()) if (echoes.get(`${session.threadId}:${turnId}`) === digest) return;
|
|
321
|
+
}
|
|
207
322
|
const images = (item.content ?? []).filter((c) => c.type === "image" || c.type === "localImage").length;
|
|
208
|
-
emit(sessionId, { type: "item", item: { kind: "user_message", id: item.id, text: text2, ...images ? { images } : {} } });
|
|
323
|
+
emit(sessionId, { type: "item", item: { kind: "user_message", id: item.id, text: text2, ...clientMessageId ? { clientMessageId } : {}, ...origin ? { origin } : {}, ...images ? { images } : {}, ...attachments ? { attachments } : {} } });
|
|
209
324
|
return;
|
|
210
325
|
}
|
|
211
326
|
if (item.type === "dynamicToolCall") {
|
|
@@ -267,6 +382,10 @@ function createAlpRuntime(options = {}) {
|
|
|
267
382
|
}
|
|
268
383
|
function notification(sessionId, session, method, params) {
|
|
269
384
|
if (session.closed) return;
|
|
385
|
+
if (method === "alp/nativeModel") {
|
|
386
|
+
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) });
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
270
389
|
touch(sessionId, session);
|
|
271
390
|
if (session.pending) {
|
|
272
391
|
session.buffered.push([method, params]);
|
|
@@ -319,7 +438,10 @@ function createAlpRuntime(options = {}) {
|
|
|
319
438
|
if (method === "turn/completed" && params.turn.id === session.active) {
|
|
320
439
|
const state = params.turn.status === "completed" ? "completed" : params.turn.status === "interrupted" ? "canceled" : "failed";
|
|
321
440
|
if (state === "failed" && LIMIT_ERRORS.includes(params.turn.error?.codexErrorInfo)) {
|
|
322
|
-
if (session.
|
|
441
|
+
if (session.role !== "supervisor") {
|
|
442
|
+
session.parkReason = `the ${label(session.runtimeKind)} usage limit was reached`;
|
|
443
|
+
session.parkPause = { scope: paused.all ? "all" : session.runtimeKind, ...paused.all?.cause === "disk" ? { disk: true } : {} };
|
|
444
|
+
}
|
|
323
445
|
void limitReached(session, params.turn.error);
|
|
324
446
|
}
|
|
325
447
|
terminal(
|
|
@@ -330,33 +452,51 @@ function createAlpRuntime(options = {}) {
|
|
|
330
452
|
);
|
|
331
453
|
}
|
|
332
454
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
455
|
+
const sessionClosures = /* @__PURE__ */ new WeakMap();
|
|
456
|
+
const openedSessions = /* @__PURE__ */ new WeakSet();
|
|
457
|
+
const openings = /* @__PURE__ */ new WeakMap();
|
|
458
|
+
const assignmentSessions = /* @__PURE__ */ new WeakMap();
|
|
459
|
+
function closeSession(sessionId, session = sessions.get(sessionId), notify = true) {
|
|
460
|
+
if (!session) return Promise.resolve();
|
|
461
|
+
const closing = sessionClosures.get(session);
|
|
462
|
+
if (closing) return closing;
|
|
463
|
+
if (session.closed) return Promise.resolve();
|
|
336
464
|
session.closed = true;
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
)
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
465
|
+
const current = sessions.get(sessionId) === session;
|
|
466
|
+
const opened = openedSessions.has(session);
|
|
467
|
+
const parent = session.parent ? sessions.get(session.parent) : void 0;
|
|
468
|
+
const descendants = current ? [...session.children, ...session.supervisor ? [session.supervisor] : []].map((id) => [id, sessions.get(id)]).filter((entry) => !!entry[1]) : [];
|
|
469
|
+
if (current) {
|
|
470
|
+
cancelQuestions(sessionId);
|
|
471
|
+
approvalLedger.delete(sessionId);
|
|
472
|
+
releaseClaims(sessionId, session.mapping.agent.projectRoot);
|
|
473
|
+
terminal(sessionId, session, "canceled");
|
|
474
|
+
session.settle?.("canceled", "Session closed");
|
|
475
|
+
}
|
|
476
|
+
const cleanup = (async () => {
|
|
477
|
+
await Promise.all(
|
|
478
|
+
descendants.map(([id, child]) => closeSession(id, child))
|
|
479
|
+
);
|
|
480
|
+
await session.runtime.close();
|
|
481
|
+
for (const assignment of session.assignments.values()) if (assignment.copy && !assignment.finished) await removeCopy(assignment.copy).catch(() => {
|
|
349
482
|
});
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
if (
|
|
358
|
-
|
|
359
|
-
|
|
483
|
+
for (const [assignmentId, { worktree }] of session.worktrees) {
|
|
484
|
+
await removeWorktree(worktree).catch(() => {
|
|
485
|
+
});
|
|
486
|
+
runLog(rootOf(sessionId), { event: "worktree.kept", assignmentId, branch: worktree.branch });
|
|
487
|
+
}
|
|
488
|
+
session.worktrees.clear();
|
|
489
|
+
compactEchoes.delete(session);
|
|
490
|
+
if (sessions.get(sessionId) !== session) return;
|
|
491
|
+
sessions.delete(sessionId);
|
|
492
|
+
if (session.parent && parent && sessions.get(session.parent) === parent) {
|
|
493
|
+
parent.children.delete(sessionId);
|
|
494
|
+
if (parent.supervisor === sessionId) parent.supervisor = void 0;
|
|
495
|
+
}
|
|
496
|
+
if (notify && opened) emit(sessionId, { type: "session.closed" });
|
|
497
|
+
})();
|
|
498
|
+
sessionClosures.set(session, cleanup);
|
|
499
|
+
return cleanup;
|
|
360
500
|
}
|
|
361
501
|
let runLogWrites = Promise.resolve();
|
|
362
502
|
const rootFor = (sessionId, session) => sessions.has(sessionId) ? rootOf(sessionId) : session.parent ? rootOf(session.parent) : sessionId;
|
|
@@ -601,7 +741,7 @@ ${output.slice(0, 4e3)}` : ""}`;
|
|
|
601
741
|
const root = sessions.get(rootId);
|
|
602
742
|
const watcher = root?.mapping.team?.supervisor ? root.mapping.team.supervisor.agent : "supervisor";
|
|
603
743
|
if (!root?.supervisor || entry.from === "supervisor" || entry.agent === watcher) return;
|
|
604
|
-
const line = entry.event === "assignment.started" ? `${entry.parentAgent} \u2192 ${entry.agent} assignment ${entry.assignmentId}${entry.taskId ? ` for task ${entry.taskId}` : ""} (${entry.model}, ${entry.thinking ?? "default effort"}, ${entry.mode}, ${entry.isolation}${entry.wait ? "" : ", async"}): ${clip(entry.task)}` : entry.event === "assignment.finished" ? `${entry.agent} assignment ${entry.assignmentId} ${entry.status}${entry.handoff ? `, handoff ${entry.handoff.outcome}${entry.handoff.verdict ? `, ${verdictLine(entry.handoff.verdict)}` : ""}: ${clip(entry.handoff.summary)}` : ", no handoff"}${entry.error ? ` (${clip(entry.error, 200)})` : ""}${entry.handoff?.discovered?.length ? `; discovered: ${clip(entry.handoff.discovered.join("; "))}` : ""}` : entry.event === "mail" && entry.kind !== "result" && entry.kind !== "board" ? `mail ${entry.kind} from ${entry.from}${entry.replyTo ? ` (reply to ${entry.replyTo})` : ""}: ${clip(entry.body ?? "")}` : entry.event === "human.question" ? `${entry.agent} asked the user: ${clip(entry.body)}` : entry.event === "human.answer" ? `user ${entry.outcome} ${entry.questionId}${entry.answer ? `: ${clip(entry.answer)}` : ""}` : entry.event === "board.pin" ? `${entry.agent} pinned ${entry.kind}${entry.paths ? ` ${entry.paths.join(", ")}` : ""}: ${clip(entry.body)}` : entry.event === "lesson" ? `${entry.agent} recorded a ${entry.scope} lesson: ${clip(entry.lesson)}` : entry.event === "skill" && Array.isArray(entry.roles) ? `${entry.agent} saved skill ${entry.name} for ${entry.roles.join(", ")} with the user's approval` : 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)}` : ""}` : 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` : entry.event === "recall" ? `${entry.agent} recalled ${entry.recalled} assignment ${entry.assignmentId}: ${clip(entry.question)}` : 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}` : entry.event?.startsWith("worktree.") ? `${entry.event.slice("worktree.".length)} worktree of ${entry.assignmentId} (${entry.branch})${entry.status ? `: ${entry.status}` : ""}` : void 0;
|
|
744
|
+
const line = entry.event === "assignment.started" ? `${entry.parentAgent} \u2192 ${entry.agent} assignment ${entry.assignmentId}${entry.taskId ? ` for task ${entry.taskId}` : ""} (${entry.model}, ${entry.thinking ?? "default effort"}, ${entry.mode}, ${entry.isolation}${entry.wait ? "" : ", async"}): ${clip(entry.task)}` : entry.event === "assignment.finished" ? `${entry.agent} assignment ${entry.assignmentId} ${entry.status}${entry.handoff ? `, handoff ${entry.handoff.outcome}${entry.handoff.verdict ? `, ${verdictLine(entry.handoff.verdict)}` : ""}: ${clip(entry.handoff.summary)}` : ", no handoff"}${entry.error ? ` (${clip(entry.error, 200)})` : ""}${entry.handoff?.discovered?.length ? `; discovered: ${clip(entry.handoff.discovered.join("; "))}` : ""}` : entry.event === "mail" && entry.kind !== "result" && entry.kind !== "board" ? `mail ${entry.kind} from ${entry.from}${entry.replyTo ? ` (reply to ${entry.replyTo})` : ""}: ${clip(entry.body ?? "")}` : entry.event === "human.question" ? `${entry.agent} asked the user: ${clip(entry.body)}` : entry.event === "human.answer" ? `user ${entry.outcome} ${entry.questionId}${entry.answer ? `: ${clip(entry.answer)}` : ""}` : entry.event === "board.pin" ? `${entry.agent} pinned ${entry.kind}${entry.paths ? ` ${entry.paths.join(", ")}` : ""}: ${clip(entry.body)}` : entry.event === "lesson" ? `${entry.agent} recorded a ${entry.scope} lesson: ${clip(entry.lesson)}` : entry.event === "skill" && Array.isArray(entry.roles) ? `${entry.agent} saved skill ${entry.name} for ${entry.roles.join(", ")} with the user's approval` : 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)}` : ""}` : 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` : entry.event === "recall" ? `${entry.agent} recalled ${entry.recalled} assignment ${entry.assignmentId}: ${clip(entry.question)}` : entry.event === "skill.approval" && !entry.saved ? `skill approval ${entry.approvalId} for ${entry.name}: not saved (${entry.error ?? entry.outcome})` : entry.event === "issue.approval" ? `issue approval ${entry.approvalId} in ${entry.repo}: ${entry.posted ? entry.url : entry.error ?? entry.outcome}` : 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}` : entry.event?.startsWith("worktree.") ? `${entry.event.slice("worktree.".length)} worktree of ${entry.assignmentId} (${entry.branch})${entry.status ? `: ${entry.status}` : ""}` : void 0;
|
|
605
745
|
if (line) root.journal.push(stamp(line));
|
|
606
746
|
}
|
|
607
747
|
const eventful = (journal) => journal.some((line) => !unstamped(line).startsWith("turn ended:"));
|
|
@@ -729,22 +869,25 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
|
|
|
729
869
|
return toolResult(true, { tasks: rows.slice(0, limit).map((task2) => summarize(task2, tasks2)), ...rows.length > limit ? { more: rows.length - limit } : {}, ...warnings });
|
|
730
870
|
}
|
|
731
871
|
const { action: _action, id, note, reason, summary, unverified, add, remove, ...input } = args;
|
|
732
|
-
if (action === "pour" && (typeof input.formula !== "string" || input.vars !== void 0 && (!input.vars || typeof input.vars !== "object" || Array.isArray(input.vars) || !Object.
|
|
733
|
-
return toolResult(false, { error:
|
|
872
|
+
if (action === "pour" && (typeof input.formula !== "string" || input.vars !== void 0 && (!input.vars || typeof input.vars !== "object" || Array.isArray(input.vars) || inputLimitError(input.vars, POUR_VARS) || !Object.entries(input.vars).every(([name, value]) => VAR_NAME.test(name) && typeof value === "string")))) {
|
|
873
|
+
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` });
|
|
734
874
|
}
|
|
735
|
-
const { kind, until, ref, gate, formula: _formula, vars: _vars, ...fields } = input;
|
|
875
|
+
const { kind, until, ref, gate, options: gateChoices, formula: _formula, vars: _vars, ...fields } = input;
|
|
736
876
|
if (action === "clear") {
|
|
737
877
|
const current = (await loadTasks(project)).tasks.find((candidate) => candidate.id === id);
|
|
738
878
|
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" });
|
|
739
879
|
}
|
|
740
880
|
let poured;
|
|
741
881
|
const hookedClose = async (id2) => {
|
|
882
|
+
const current = (await loadTasks(project)).tasks.find((candidate) => candidate.id === id2);
|
|
883
|
+
if (current && (current.step?.human || current.gates.some((gate2) => gate2.kind === "human" && !gate2.resolved))) throw new Error(`Only the user closes ${id2}: it waits on the user's decision. Ask the user to decide it`);
|
|
742
884
|
const refused = await runHooks(sessionId, session, "task.close", { reason, ...summary ? { summary } : {} }, id2);
|
|
743
885
|
if (refused) throw new Error(`A task.close hook refused to close ${id2}: ${refused}`);
|
|
744
886
|
return closeTask(project, id2, { reason, summary, unverified }, by);
|
|
745
887
|
};
|
|
746
|
-
const task = action === "create" ? await createTask(project, fields, by) : action === "update" ? await updateTask(project, id, { ...fields, note }, by) : action === "pour" ? (poured = await pourFormula(project, (await findFormula(project, options.libraryDir, input.formula, { toml })).formula, input.vars, by, input.parent ? { parent: input.parent } : {})).epic : action === "gate" ? await addGate(project, id, { kind, note, until, ref }, by) : action === "clear" ? await resolveGate(project, id, gate, { by, note }) : action === "link" ? await linkTask(project, id, { add, remove }, by) : action === "start" ? await startTask(project, id, { agent: by, session: sessionId }, by) : action === "close" ? await hookedClose(id) : await reopenTask(project, id, { note }, by);
|
|
888
|
+
const task = action === "create" ? await createTask(project, fields, by) : action === "update" ? await updateTask(project, id, { ...fields, note }, by) : action === "pour" ? (poured = await pourFormula(project, (await findFormula(project, options.libraryDir, input.formula, { toml })).formula, input.vars, by, input.parent ? { parent: input.parent } : {})).epic : action === "gate" ? await addGate(project, id, { kind, note, until, ref, ...gateChoices !== void 0 ? { options: gateChoices } : {} }, by) : action === "clear" ? await resolveGate(project, id, gate, { by, note }) : action === "link" ? await linkTask(project, id, { add, remove }, by) : action === "start" ? await startTask(project, id, { agent: by, session: sessionId }, by) : action === "close" ? await hookedClose(id) : await reopenTask(project, id, { note }, by);
|
|
747
889
|
touchTask(rootOf(sessionId), task.id);
|
|
890
|
+
if (action === "gate" && kind === "human") void syncGates(project);
|
|
748
891
|
runLog(rootOf(sessionId), { event: "task", action, agent: by, id: task.id, title: task.title, status: task.status, ...summary ?? note ? { detail: summary ?? note } : {} });
|
|
749
892
|
const { tasks } = await loadTasks(project);
|
|
750
893
|
const landed = {};
|
|
@@ -851,6 +994,45 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
|
|
|
851
994
|
return toolResult(false, { assignmentId: entry.assignmentId, error: errorData(error).message });
|
|
852
995
|
}
|
|
853
996
|
}
|
|
997
|
+
async function resolveTool(sessionId, session, args) {
|
|
998
|
+
if (!plainObject(args, ["assignmentId", "outcome", "note"]) || typeof args.assignmentId !== "string" || !RESULT_OUTCOMES.includes(args.outcome) || args.note !== void 0 && (typeof args.note !== "string" || args.note.length > RESOLVE_NOTE_CHARS)) {
|
|
999
|
+
return toolResult(false, { error: `Pass assignmentId, outcome (${RESULT_OUTCOMES.join(", ")}), and optionally a note of at most ${RESOLVE_NOTE_CHARS} characters` });
|
|
1000
|
+
}
|
|
1001
|
+
const id = args.assignmentId;
|
|
1002
|
+
const outcome = args.outcome;
|
|
1003
|
+
const note = args.note;
|
|
1004
|
+
const live2 = [...sessions.values()];
|
|
1005
|
+
if (sessions.has(id) || live2.some((other) => other.assignments.has(id)) || inFlight.all().some((entry2) => entry2.assignmentId === id) || inherited.some((entry2) => entry2.assignmentId === id)) {
|
|
1006
|
+
return toolResult(false, { error: "That assignment is still running or can still be recovered; wait for its result" });
|
|
1007
|
+
}
|
|
1008
|
+
if (live2.some((other) => other.worktrees.has(id))) return toolResult(false, { error: "Its change waits in a worktree; apply it with alp_merge or drop it with alp_discard" });
|
|
1009
|
+
let ledger;
|
|
1010
|
+
try {
|
|
1011
|
+
ledger = await assignmentResults.inspect();
|
|
1012
|
+
} catch (error) {
|
|
1013
|
+
return toolResult(false, { error: errorData(error).message });
|
|
1014
|
+
}
|
|
1015
|
+
const entry = ledger.results.find((owner) => owner.assignmentId === id && !owner.handled);
|
|
1016
|
+
const project = session.mapping.agent.projectRoot;
|
|
1017
|
+
const overlapping2 = async (a, b) => {
|
|
1018
|
+
const [x, y] = [await realpath(a).catch(() => a), await realpath(b).catch(() => b)];
|
|
1019
|
+
const within = (parent, child) => {
|
|
1020
|
+
const relative = path.relative(parent, child);
|
|
1021
|
+
return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
1022
|
+
};
|
|
1023
|
+
return within(x, y) || within(y, x);
|
|
1024
|
+
};
|
|
1025
|
+
const allowed = !!entry && (entry.result ? entry.result.requesters.includes(sessionId) || !session.parent && await sameDirectory(entry.result.project, project) : !session.parent && await overlapping2(entry.checkout, project));
|
|
1026
|
+
if (!entry || !allowed) return toolResult(false, { error: `No unresolved assignment result ${id} of yours` });
|
|
1027
|
+
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` });
|
|
1028
|
+
try {
|
|
1029
|
+
const archived = await assignmentResults.resolve(id, { outcome, by: `${session.mapping.agent.name} in ${sessionId}`, at: (/* @__PURE__ */ new Date()).toISOString(), ...note ? { note } : {} });
|
|
1030
|
+
runLog(rootOf(sessionId), { event: "result.resolved", assignmentId: id, agent: session.mapping.agent.name, outcome, ...note ? { note: clip(note, 500) } : {} });
|
|
1031
|
+
return toolResult(true, { resolved: id, outcome, archivedAt: archived.archivedAt });
|
|
1032
|
+
} catch (error) {
|
|
1033
|
+
return toolResult(false, { assignmentId: id, error: errorData(error).message });
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
854
1036
|
let forgetting = Promise.resolve();
|
|
855
1037
|
function forgetExpired() {
|
|
856
1038
|
forgetting = forgetting.then(async () => {
|
|
@@ -877,7 +1059,22 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
|
|
|
877
1059
|
const LIMIT_ERRORS = ["usageLimitExceeded", "rateLimitExceeded"];
|
|
878
1060
|
const label = (kind) => kind === "claude" ? "Claude" : kind === "acp" ? "ACP agent" : kind === "antigravity" ? "Antigravity" : "Codex";
|
|
879
1061
|
const pauseOf = (kind) => paused.all ?? paused.runtimes[kind];
|
|
880
|
-
const held = (session) => !!session.parked || !!pauseOf(session.runtimeKind);
|
|
1062
|
+
const held = (session) => !!session.parked || !!pauseOf(session.runtimeKind) || (session.lifecycleHolds ?? 0) > 0;
|
|
1063
|
+
const holdsWake = (session) => held(session) || !!session.awaitingBrief || !!session.compacting;
|
|
1064
|
+
function beginPending(session) {
|
|
1065
|
+
let done;
|
|
1066
|
+
session.pending = true;
|
|
1067
|
+
session.acknowledged = new Promise((resolve) => {
|
|
1068
|
+
done = resolve;
|
|
1069
|
+
});
|
|
1070
|
+
let cleared = false;
|
|
1071
|
+
return () => {
|
|
1072
|
+
if (cleared) return;
|
|
1073
|
+
cleared = true;
|
|
1074
|
+
session.pending = false;
|
|
1075
|
+
done();
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
881
1078
|
const describePause = (pause, kind) => `${kind ? label(kind) : "ALP"} is paused (${pause.reason}${pause.by !== "alpd" ? `, by ${pause.by}` : ""})${pause.resetsAt ? `; the limit resets ${pause.resetsAt}` : ""}`;
|
|
882
1079
|
function pauseState() {
|
|
883
1080
|
return {
|
|
@@ -902,8 +1099,7 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
|
|
|
902
1099
|
const temporary = `${file}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
|
|
903
1100
|
await writeFile(temporary, body, { mode: 384 });
|
|
904
1101
|
await moveFile(temporary, file);
|
|
905
|
-
}).catch(() =>
|
|
906
|
-
});
|
|
1102
|
+
}).catch((error) => tell(writeFailed, error));
|
|
907
1103
|
}
|
|
908
1104
|
function notice(level, message, project) {
|
|
909
1105
|
for (const [id, session] of sessions) {
|
|
@@ -998,58 +1194,91 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
|
|
|
998
1194
|
if (now) {
|
|
999
1195
|
for (const [id, session] of sessions) {
|
|
1000
1196
|
if (!session.parent || session.closed || !session.active || session.role === "supervisor" || scope !== "all" && session.runtimeKind !== scope) continue;
|
|
1001
|
-
session.parkReason
|
|
1197
|
+
if (session.parkReason && !session.parkPause) continue;
|
|
1198
|
+
session.parkReason = pause.cause === "disk" ? pause.reason : `paused by ${pause.by}`;
|
|
1199
|
+
session.parkPause = { scope, ...pause.cause === "disk" ? { disk: true } : {} };
|
|
1002
1200
|
void session.runtime.request("turn/interrupt", { threadId: session.threadId, turnId: session.active }).catch(() => {
|
|
1003
1201
|
});
|
|
1004
1202
|
runLog(rootOf(id), { event: "assignment.parking", assignmentId: id, agent: session.mapping.agent.name, reason: session.parkReason });
|
|
1005
1203
|
}
|
|
1006
1204
|
}
|
|
1007
1205
|
}
|
|
1008
|
-
function resumeRuntime(scope, by) {
|
|
1009
|
-
if (scope === "all") paused = { runtimes: {} };
|
|
1206
|
+
function resumeRuntime(scope, by, keepRuntimes = false) {
|
|
1207
|
+
if (scope === "all") paused = keepRuntimes ? { runtimes: paused.runtimes } : { runtimes: {} };
|
|
1010
1208
|
else delete paused.runtimes[scope];
|
|
1011
1209
|
savePauses();
|
|
1012
1210
|
watchLimits();
|
|
1211
|
+
const matches = (pause) => pause && (scope === "all" || pause.scope === scope);
|
|
1212
|
+
const continuing = [...sessions.values()].some((session) => !session.closed && !pauseOf(session.runtimeKind) && matches(session.parked?.pause));
|
|
1013
1213
|
const free = RUNTIMES.filter((kind) => !pauseOf(kind));
|
|
1014
|
-
if (free.length) notice("info", (say) => say.resumed(scope === "all" ? "ALP" : label(scope), by,
|
|
1214
|
+
if (free.length) notice("info", (say) => say.resumed(scope === "all" ? "ALP" : label(scope), by, continuing));
|
|
1015
1215
|
for (const [id, session] of sessions) {
|
|
1016
|
-
if (session.closed ||
|
|
1017
|
-
if (session.
|
|
1018
|
-
|
|
1216
|
+
if (session.closed || scope !== "all" && session.runtimeKind !== scope) continue;
|
|
1217
|
+
if (matches(session.parkPause)) session.parkPause.resumed = true;
|
|
1218
|
+
if (pauseOf(session.runtimeKind)) continue;
|
|
1219
|
+
if (session.parked) {
|
|
1220
|
+
if (matches(session.parked.pause)) continueParked(id, session);
|
|
1221
|
+
} else if (session.wakeHeld) {
|
|
1019
1222
|
session.wakeHeld = false;
|
|
1020
1223
|
deliver(id, session);
|
|
1021
1224
|
}
|
|
1022
1225
|
}
|
|
1023
1226
|
}
|
|
1024
1227
|
function park(sessionId, session) {
|
|
1025
|
-
session.parked = { reason: session.parkReason, since: Date.now() };
|
|
1228
|
+
session.parked = { reason: session.parkReason, since: Date.now(), ...session.parkPause ? { pause: session.parkPause } : {} };
|
|
1229
|
+
const resumed = session.parkPause?.resumed;
|
|
1230
|
+
session.parkPause = void 0;
|
|
1026
1231
|
const then = session.parkThen;
|
|
1027
1232
|
session.parkReason = void 0;
|
|
1028
1233
|
session.parkThen = void 0;
|
|
1029
1234
|
emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
|
|
1235
|
+
if (resumed) continueParked(sessionId, session);
|
|
1030
1236
|
const parent = session.parent ? sessions.get(session.parent) : void 0;
|
|
1031
1237
|
const assignment = parent?.assignments.get(sessionId);
|
|
1032
1238
|
runLog(rootOf(sessionId), { event: "assignment.parked", assignmentId: sessionId, agent: session.mapping.agent.name, reason: session.parked.reason });
|
|
1033
1239
|
if (!parent || !assignment) return;
|
|
1034
1240
|
emit(session.parent, { type: "assignment", assignment: assignmentSnapshot(assignment, "parked") });
|
|
1035
1241
|
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.` });
|
|
1242
|
+
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.` });
|
|
1036
1243
|
else post(session.parent, { kind: "stalled", from: assignment.agent, assignment: sessionId, body: `Parked: ${session.parked.reason}. ALP continues this assignment where it stopped when ${label(session.runtimeKind)} is resumed (${options.autoResume !== false && (pauseOf(session.runtimeKind)?.by ?? "alpd") === "alpd" ? `ALP resumes it as soon as ${label(session.runtimeKind)} says the limit lifted` : "the user runs alp resume"}). Wait for it, start other work, or stop it with alp_cancel and give the rest to an agent on another runtime (pass model claude:\u2026 or codex:\u2026); what it changed stays in your checkout or its worktree.` });
|
|
1037
1244
|
}
|
|
1038
|
-
function continueParked(sessionId, session) {
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1245
|
+
function continueParked(sessionId, session, expected = session.parked) {
|
|
1246
|
+
void enqueue(async () => {
|
|
1247
|
+
if (session.closed || session.active || session.pending || !session.parked || session.parked !== expected) return;
|
|
1248
|
+
if (pauseOf(session.runtimeKind)) {
|
|
1249
|
+
session.parked.pause = { scope: paused.all ? "all" : session.runtimeKind };
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
if (session.lifecycleHolds) {
|
|
1253
|
+
session.resumeHeld = session.parked;
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
const parked = session.parked;
|
|
1257
|
+
const { reason, prompt } = parked;
|
|
1258
|
+
session.parked = void 0;
|
|
1259
|
+
session.wakeHeld = false;
|
|
1260
|
+
session.lastActivity = Date.now();
|
|
1261
|
+
const parent = session.parent ? sessions.get(session.parent) : void 0;
|
|
1262
|
+
const assignment = parent?.assignments.get(sessionId);
|
|
1263
|
+
runLog(rootOf(sessionId), { event: "assignment.resumed", assignmentId: sessionId, agent: session.mapping.agent.name });
|
|
1264
|
+
if (assignment) emit(session.parent, { type: "assignment", assignment: assignmentSnapshot(assignment, "running") });
|
|
1265
|
+
try {
|
|
1266
|
+
await startPrompt(sessionId, {
|
|
1267
|
+
clientMessageId: `alp-resume-${randomUUID()}`,
|
|
1268
|
+
delivery: "auto",
|
|
1269
|
+
content: [{ type: "text", text: prompt ?? (session.parent ? `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.` : `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.`) }]
|
|
1270
|
+
}, session.parent ? "assignment" : "wake");
|
|
1271
|
+
session.resumedTurn = session.active;
|
|
1272
|
+
emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
|
|
1273
|
+
} catch (error) {
|
|
1274
|
+
if (!session.closed && !session.active) {
|
|
1275
|
+
session.parked = parked;
|
|
1276
|
+
emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
|
|
1277
|
+
if (assignment) emit(session.parent, { type: "assignment", assignment: assignmentSnapshot(assignment, "parked") });
|
|
1278
|
+
}
|
|
1279
|
+
notice("warning", `Could not resume ${session.mapping.agent.name}: ${errorData(error).message}`);
|
|
1280
|
+
}
|
|
1281
|
+
});
|
|
1053
1282
|
}
|
|
1054
1283
|
async function limitReset(session, error) {
|
|
1055
1284
|
const at = (seconds) => typeof seconds === "number" && seconds > 0 ? new Date(seconds * 1e3).toISOString() : void 0;
|
|
@@ -1066,8 +1295,9 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
|
|
|
1066
1295
|
}
|
|
1067
1296
|
async function limitReached(session, error) {
|
|
1068
1297
|
const kind = session.runtimeKind;
|
|
1069
|
-
if (
|
|
1298
|
+
if (pauseOf(kind)) return;
|
|
1070
1299
|
const resetsAt = await limitReset(session, error);
|
|
1300
|
+
if (closed || session.closed || pauseOf(kind)) return;
|
|
1071
1301
|
const pause = { since: (/* @__PURE__ */ new Date()).toISOString(), by: "alpd", reason: `${label(kind)} usage limit reached`, ...resetsAt ? { resetsAt } : {} };
|
|
1072
1302
|
pauseRuntime(kind, pause);
|
|
1073
1303
|
const other = RUNTIMES.find((candidate) => candidate !== kind && !pauseOf(candidate));
|
|
@@ -1077,6 +1307,7 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
|
|
|
1077
1307
|
const used = usage2?.last?.totalTokens;
|
|
1078
1308
|
const window = usage2?.modelContextWindow;
|
|
1079
1309
|
if (session.role === "supervisor" || typeof used !== "number" || typeof window !== "number" || window <= 0) return;
|
|
1310
|
+
if (!session.compactCooling) session.contextFill = contextFill({ ...usage2, modelContextWindow: Math.min(typeof session.mapping.autocompact === "number" ? session.mapping.autocompact : typeof session.mapping.context === "number" ? session.mapping.context : window, window) });
|
|
1080
1311
|
const compactAt = typeof usage2.autoCompactTokens === "number" && usage2.autoCompactTokens > 0 ? usage2.autoCompactTokens : session.runtimeKind === "codex" && session.mapping.autocompact ? Math.min(session.mapping.autocompact, Math.round(window * COMPACT_SHARE)) : Math.round(Math.min(session.mapping.autocompact ?? session.mapping.context ?? window, window) * COMPACT_SHARE);
|
|
1081
1312
|
const fill = used / compactAt;
|
|
1082
1313
|
if (fill < CONTEXT_RESET) {
|
|
@@ -1094,6 +1325,7 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
|
|
|
1094
1325
|
const skills = session.mapping.agent.skills;
|
|
1095
1326
|
if (!skills.length || item.type === "agentMessage" || item.type === "reasoning") return;
|
|
1096
1327
|
const text2 = typeof item.command === "string" ? item.command : JSON.stringify(item).slice(0, 2e4);
|
|
1328
|
+
skillResources(sessionId, session, item);
|
|
1097
1329
|
if (!text2.includes("SKILL.md") && !text2.includes("Skill")) return;
|
|
1098
1330
|
for (const skill of skills) {
|
|
1099
1331
|
if (session.skillsUsed?.has(skill.name)) continue;
|
|
@@ -1105,6 +1337,15 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
|
|
|
1105
1337
|
if (session.supervisor) session.journal.push(stamp(`${session.mapping.agent.name} used skill ${skill.name}`));
|
|
1106
1338
|
}
|
|
1107
1339
|
}
|
|
1340
|
+
function skillResources(sessionId, session, item) {
|
|
1341
|
+
if (typeof item.command !== "string") return;
|
|
1342
|
+
for (const use of resourceUses(item.command, session.mapping.agent.skills)) {
|
|
1343
|
+
const key = `${use.action}:${use.skill}/${use.resource}`;
|
|
1344
|
+
if (session.skillResourcesUsed?.has(key)) continue;
|
|
1345
|
+
(session.skillResourcesUsed ??= /* @__PURE__ */ new Set()).add(key);
|
|
1346
|
+
runLog(rootOf(sessionId), { event: "skill-resource", sessionId, agent: session.mapping.agent.name, skill: use.skill, resource: use.resource, action: use.action });
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1108
1349
|
function compaction(sessionId, session, item, done) {
|
|
1109
1350
|
const failed = done && item.status === "failed";
|
|
1110
1351
|
const tokens = { ...typeof item.preTokens === "number" ? { preTokens: item.preTokens } : {}, ...typeof item.postTokens === "number" ? { postTokens: item.postTokens } : {} };
|
|
@@ -1113,13 +1354,168 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
|
|
|
1113
1354
|
if (!done) return;
|
|
1114
1355
|
const agent = session.mapping.agent.name;
|
|
1115
1356
|
runLog(rootOf(sessionId), { event: "compacted", sessionId, agent, ...trigger, ...tokens, ...failed ? { failed: true, ...item.error ? { error: String(item.error) } : {} } : {} });
|
|
1116
|
-
if (failed)
|
|
1357
|
+
if (failed) {
|
|
1358
|
+
if (session.compacting?.phase === "native") compactFailed(sessionId, session, item.error ? String(item.error) : "the runtime could not compact");
|
|
1359
|
+
return;
|
|
1360
|
+
}
|
|
1117
1361
|
session.contextLevel = 0;
|
|
1118
1362
|
if (session.supervisor) session.journal.push(stamp(`${agent}'s context was compacted`));
|
|
1119
|
-
|
|
1363
|
+
const checkpoint = session.compacting?.phase === "native" ? session.compacting.checkpoint : void 0;
|
|
1364
|
+
if (session.role !== "supervisor") void restoreAfterCompaction(sessionId, session, checkpoint).catch(() => {
|
|
1365
|
+
});
|
|
1366
|
+
if (checkpoint !== void 0) compactFinished(sessionId, session, "native");
|
|
1367
|
+
}
|
|
1368
|
+
function compactHeld(sessionId, session, starting) {
|
|
1369
|
+
return session.closed || !!session.active || !!session.pending || session.waiters.length > 0 || !!session.parked || !!session.parkReason || starting && (hasActiveMail(session) || !!session.wakeHeld) || [...userQuestions.values()].some((pending) => pending.question.rootId === sessionId && !pending.gate);
|
|
1370
|
+
}
|
|
1371
|
+
function compactAtBoundary(sessionId, session, ended) {
|
|
1372
|
+
if (session.closed || sessions.get(sessionId) !== session) return;
|
|
1373
|
+
const current = session.compacting;
|
|
1374
|
+
if (ended && current?.phase === "checkpoint" && current.checkpoint === void 0 && current.turn) {
|
|
1375
|
+
const written = [...session.text.values()].at(-1)?.trim();
|
|
1376
|
+
if (ended !== "completed" || !written) {
|
|
1377
|
+
compactFailed(sessionId, session, ended !== "completed" ? `the checkpoint turn ${ended}` : "main wrote no checkpoint");
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
current.checkpoint = written;
|
|
1381
|
+
const timer = setTimeout(() => {
|
|
1382
|
+
if (session.compacting === current && current.phase === "checkpoint") compactFailed(sessionId, session, "main stayed busy after its checkpoint");
|
|
1383
|
+
}, COMPACT_NATIVE_MS);
|
|
1384
|
+
timer.unref?.();
|
|
1385
|
+
}
|
|
1386
|
+
if (ended && current?.phase === "native" && current.requested) {
|
|
1387
|
+
compactFailed(sessionId, session, "the runtime reported no compaction");
|
|
1388
|
+
return;
|
|
1389
|
+
}
|
|
1390
|
+
if (current) {
|
|
1391
|
+
if (current.checkpoint !== void 0 && current.phase === "checkpoint" && !compactHeld(sessionId, session, false)) void compactNow(sessionId, session);
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
if (compactHeld(sessionId, session, true)) return;
|
|
1395
|
+
if (session.compactBuffer?.length) {
|
|
1396
|
+
flushCompactBuffer(sessionId, session);
|
|
1397
|
+
return;
|
|
1398
|
+
}
|
|
1399
|
+
const trigger = compactDue(session.mapping.compact ?? { auto: false, threshold: 1 }, session.contextFill, !!session.compactRequested);
|
|
1400
|
+
if (!trigger) return;
|
|
1401
|
+
if (trigger === "auto" && session.compactFailedAt && Date.now() - session.compactFailedAt < COMPACT_RETRY_MS) return;
|
|
1402
|
+
session.compactRequested = false;
|
|
1403
|
+
const compacting = { phase: "checkpoint", trigger, startedAt: Date.now() };
|
|
1404
|
+
session.compacting = compacting;
|
|
1405
|
+
runLog(rootOf(sessionId), { event: "compact.started", sessionId, agent: session.mapping.agent.name, trigger, ...session.contextFill !== void 0 ? { fill: Math.round(session.contextFill * 100) / 100 } : {} });
|
|
1406
|
+
const work = queue.then(async () => {
|
|
1407
|
+
if (session.compacting !== compacting) return;
|
|
1408
|
+
if (session.closed || compactHeld(sessionId, session, true)) {
|
|
1409
|
+
session.compacting = void 0;
|
|
1410
|
+
if (trigger === "manual") session.compactRequested = true;
|
|
1411
|
+
compactReleased(sessionId, session);
|
|
1412
|
+
return;
|
|
1413
|
+
}
|
|
1414
|
+
compacting.turn = true;
|
|
1415
|
+
await startPrompt(sessionId, { clientMessageId: `${COMPACT_PROMPT}${randomUUID()}`, delivery: "auto", content: [{ type: "text", text: checkpointPrompt(trigger, session.contextFill) }] }, "wake", void 0, true);
|
|
1416
|
+
emit(sessionId, { type: "item", item: { kind: "notice", id: `notice-${randomUUID().slice(0, 8)}`, level: "info", text: wordsFor(session).compacting() } });
|
|
1417
|
+
}).catch((error) => compactFailed(sessionId, session, errorData(error).message));
|
|
1418
|
+
queue = work.catch(() => {
|
|
1419
|
+
});
|
|
1420
|
+
}
|
|
1421
|
+
async function compactNow(sessionId, session) {
|
|
1422
|
+
const current = session.compacting;
|
|
1423
|
+
const checkpoint = current.checkpoint;
|
|
1424
|
+
if (NATIVE_COMPACT.includes(session.runtimeKind)) {
|
|
1425
|
+
current.phase = "native";
|
|
1426
|
+
try {
|
|
1427
|
+
await session.runtime.request("thread/compact/start", { threadId: session.threadId, ...session.runtimeKind === "codex" ? {} : { instructions: compactInstructions(checkpoint) } });
|
|
1428
|
+
if (session.compacting !== current) return;
|
|
1429
|
+
current.requested = true;
|
|
1430
|
+
const timer = setTimeout(() => {
|
|
1431
|
+
if (session.compacting === current) compactFailed(sessionId, session, "the runtime reported no compaction in time");
|
|
1432
|
+
}, COMPACT_NATIVE_MS);
|
|
1433
|
+
timer.unref?.();
|
|
1434
|
+
return;
|
|
1435
|
+
} catch (error) {
|
|
1436
|
+
if (session.compacting !== current) return;
|
|
1437
|
+
runLog(rootOf(sessionId), { event: "compact.native_failed", sessionId, agent: session.mapping.agent.name, error: errorData(error).message });
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
current.phase = "fresh";
|
|
1441
|
+
const work = queue.then(async () => {
|
|
1442
|
+
if (session.compacting !== current || session.closed) return;
|
|
1443
|
+
const refusal = restartRefusal(sessionId, session);
|
|
1444
|
+
if (refusal && refusal !== MAIL_WAITS && refusal !== REVIEWING) {
|
|
1445
|
+
compactFailed(sessionId, session, `a fresh conversation cannot start now: ${refusal}`);
|
|
1446
|
+
return;
|
|
1447
|
+
}
|
|
1448
|
+
await restartNative(sessionId, session, void 0);
|
|
1449
|
+
emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
|
|
1450
|
+
await startPrompt(sessionId, { clientMessageId: `${COMPACT_PROMPT}${randomUUID()}`, delivery: "auto", content: [{ type: "text", text: seedPrompt(checkpoint, session.lastUserText) }] }, "wake", void 0, true);
|
|
1451
|
+
compactFinished(sessionId, session, "fresh");
|
|
1452
|
+
}).catch((error) => compactFailed(sessionId, session, errorData(error).message));
|
|
1453
|
+
queue = work.catch(() => {
|
|
1454
|
+
});
|
|
1455
|
+
}
|
|
1456
|
+
function compactFinished(sessionId, session, via) {
|
|
1457
|
+
const current = session.compacting;
|
|
1458
|
+
if (!current) return;
|
|
1459
|
+
session.compacting = void 0;
|
|
1460
|
+
session.compactFailedAt = void 0;
|
|
1461
|
+
session.contextFill = void 0;
|
|
1462
|
+
session.compactCooling = true;
|
|
1463
|
+
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 });
|
|
1464
|
+
const text2 = wordsFor(session).compacted(via === "native");
|
|
1465
|
+
emit(sessionId, { type: "item", item: { kind: "notice", id: `notice-${randomUUID().slice(0, 8)}`, level: "info", text: text2 } });
|
|
1466
|
+
compactReleased(sessionId, session);
|
|
1467
|
+
}
|
|
1468
|
+
function compactFailed(sessionId, session, reason) {
|
|
1469
|
+
const current = session.compacting;
|
|
1470
|
+
session.compacting = void 0;
|
|
1471
|
+
session.compactFailedAt = Date.now();
|
|
1472
|
+
runLog(rootOf(sessionId), { event: "compact.failed", sessionId, agent: session.mapping.agent.name, ...current ? { trigger: current.trigger } : {}, error: reason });
|
|
1473
|
+
if (!session.closed) emit(sessionId, { type: "item", item: { kind: "notice", id: `notice-${randomUUID().slice(0, 8)}`, level: "warning", text: wordsFor(session).compactFailed(reason) } });
|
|
1474
|
+
compactReleased(sessionId, session);
|
|
1475
|
+
}
|
|
1476
|
+
function compactReleased(sessionId, session) {
|
|
1477
|
+
queueMicrotask(() => {
|
|
1478
|
+
if (session.closed || session.compacting) return;
|
|
1479
|
+
flushCompactBuffer(sessionId, session);
|
|
1480
|
+
if (session.wakeHeld && !holdsWake(session)) {
|
|
1481
|
+
session.wakeHeld = false;
|
|
1482
|
+
deliver(sessionId, session);
|
|
1483
|
+
}
|
|
1484
|
+
});
|
|
1485
|
+
}
|
|
1486
|
+
function flushCompactBuffer(sessionId, session) {
|
|
1487
|
+
if (session.compacting || session.active || !session.compactBuffer?.length) return;
|
|
1488
|
+
const held2 = session.compactBuffer.splice(0);
|
|
1489
|
+
session.compactBuffer = void 0;
|
|
1490
|
+
const work = queue.then(async () => {
|
|
1491
|
+
for (const [index, input] of held2.entries()) {
|
|
1492
|
+
await promptSession(sessionId, { ...input, delivery: index === 0 && !session.active ? "auto" : "steer" }, true);
|
|
1493
|
+
}
|
|
1494
|
+
});
|
|
1495
|
+
queue = work.catch(() => {
|
|
1120
1496
|
});
|
|
1121
1497
|
}
|
|
1122
|
-
|
|
1498
|
+
function requestCompact(sessionId) {
|
|
1499
|
+
const session = sessions.get(sessionId);
|
|
1500
|
+
if (!session || session.closed) throw new ConversationError("session_busy", "The session is not open");
|
|
1501
|
+
if (session.parent || session.role === "supervisor") throw new ConversationError("runtime_unsupported", "Only a root session is compacted");
|
|
1502
|
+
if (session.compacting) return { status: "running" };
|
|
1503
|
+
session.compactRequested = true;
|
|
1504
|
+
if (compactHeld(sessionId, session, true)) return { status: "deferred" };
|
|
1505
|
+
compactAtBoundary(sessionId, session);
|
|
1506
|
+
return { status: "started" };
|
|
1507
|
+
}
|
|
1508
|
+
async function listCommands(sessionId) {
|
|
1509
|
+
const session = sessions.get(sessionId);
|
|
1510
|
+
if (!session || session.closed) throw new ConversationError("session_busy", "The session is not open");
|
|
1511
|
+
const prefix = session.runtimeKind === "claude" ? `${SKILL_PLUGIN}:` : "";
|
|
1512
|
+
const offered2 = /* @__PURE__ */ new Set([...session.mapping.commands ?? [], ...session.mapping.agent.skills.map((skill) => prefix + skill.name)]);
|
|
1513
|
+
const listed = (session.runtime.commands ? await session.runtime.commands().catch(() => []) : []).filter((command) => offered2.has(command.name));
|
|
1514
|
+
const seen = new Set(listed.map((command) => command.name));
|
|
1515
|
+
const skills = await Promise.all(session.mapping.agent.skills.filter((skill) => !seen.has(prefix + skill.name)).map(async (skill) => ({ name: prefix + skill.name, description: await skillDescription(skill.path), kind: "skill" })));
|
|
1516
|
+
return [...listed, ...skills];
|
|
1517
|
+
}
|
|
1518
|
+
async function restoreAfterCompaction(sessionId, session, checkpoint) {
|
|
1123
1519
|
const parts = ["Your context was just compacted. In case the summary lost any of it, this is what ALP holds of your work now."];
|
|
1124
1520
|
if (session.parent && session.brief) parts.push(`Your assignment from ${session.parentAgent ?? "your requester"}, as it was given:
|
|
1125
1521
|
${cut(session.brief, BRIEF_CHARS)}`);
|
|
@@ -1130,7 +1526,7 @@ ${cut(session.brief, BRIEF_CHARS)}`);
|
|
|
1130
1526
|
if (session.worktrees.size) {
|
|
1131
1527
|
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"));
|
|
1132
1528
|
}
|
|
1133
|
-
const asked = [...userQuestions.values()].filter((pending) => pending.question.sessionId === sessionId);
|
|
1529
|
+
const asked = [...userQuestions.values()].filter((pending) => pending.question.sessionId === sessionId && !pending.gate);
|
|
1134
1530
|
if (asked.length) parts.push("Waiting for the user to answer:\n" + asked.map((pending) => `- ${clip(pending.question.body, 300)}`).join("\n"));
|
|
1135
1531
|
if (!session.parent) {
|
|
1136
1532
|
const project = session.mapping.agent.projectRoot;
|
|
@@ -1139,6 +1535,8 @@ ${cut(session.brief, BRIEF_CHARS)}`);
|
|
|
1139
1535
|
const board = renderBoard(await boardOf(project));
|
|
1140
1536
|
if (board) parts.push(board);
|
|
1141
1537
|
}
|
|
1538
|
+
if (checkpoint) parts.push(`The checkpoint you wrote before the compaction, by skill compact:
|
|
1539
|
+
${cut(checkpoint, BRIEF_CHARS)}`);
|
|
1142
1540
|
parts.push("Carry on where you were; alp_board and alp_task tell you more.");
|
|
1143
1541
|
if (session.closed) return;
|
|
1144
1542
|
post(sessionId, { kind: "note", from: "alp", assignment: sessionId, body: parts.join("\n\n"), ...session.active ? {} : { passive: true } });
|
|
@@ -1208,10 +1606,10 @@ ${cut(session.brief, BRIEF_CHARS)}`);
|
|
|
1208
1606
|
function lessonFiles(mapping) {
|
|
1209
1607
|
return [path.join(mapping.agent.projectRoot, ".alp", LESSONS_FILE), ...options.libraryDir ? [path.join(options.libraryDir, LESSONS_FILE)] : []];
|
|
1210
1608
|
}
|
|
1211
|
-
async function confirm(sessionId, session, body) {
|
|
1212
|
-
if ([...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId)) return { approved: false, outcome: "busy", feedback: "A question is already waiting for the user" };
|
|
1609
|
+
async function confirm(sessionId, session, body, approval) {
|
|
1610
|
+
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" };
|
|
1213
1611
|
const say = wordsFor(session);
|
|
1214
|
-
const result = await askUser(sessionId, session, void 0, body, [say.approve, say.reject]);
|
|
1612
|
+
const result = await askUser(sessionId, session, void 0, body, [say.approve, say.reject], approval);
|
|
1215
1613
|
let value;
|
|
1216
1614
|
try {
|
|
1217
1615
|
value = JSON.parse(result.contentItems[0].text);
|
|
@@ -1222,25 +1620,54 @@ ${cut(session.brief, BRIEF_CHARS)}`);
|
|
|
1222
1620
|
const answer = String(value.answer).trim();
|
|
1223
1621
|
return APPROVALS.includes(answer.toLowerCase()) ? { approved: true } : { approved: false, outcome: "answered", feedback: answer };
|
|
1224
1622
|
}
|
|
1225
|
-
const declined = (decision) => toolResult(true, {
|
|
1226
|
-
approved: false,
|
|
1227
|
-
outcome: decision.outcome,
|
|
1228
|
-
...decision.feedback ? { feedback: decision.feedback } : {},
|
|
1229
|
-
next: "Nothing was saved or posted. Revise from the feedback and propose again, or drop it."
|
|
1230
|
-
});
|
|
1231
1623
|
const text = (value, limit) => typeof value === "string" && !!value.trim() && value.length <= limit;
|
|
1624
|
+
const approvalCancellation = /* @__PURE__ */ new WeakMap();
|
|
1625
|
+
const approvalLedger = /* @__PURE__ */ new Map();
|
|
1626
|
+
const approvalsOf = (sessionId) => {
|
|
1627
|
+
let approvals = approvalLedger.get(sessionId);
|
|
1628
|
+
if (!approvals) approvalLedger.set(sessionId, approvals = /* @__PURE__ */ new Map());
|
|
1629
|
+
return approvals;
|
|
1630
|
+
};
|
|
1631
|
+
const approvalCanceled = (session, cancellation) => closed || session.closed || cancellation !== (approvalCancellation.get(session) ?? 0);
|
|
1232
1632
|
async function skillTool(sessionId, session, args) {
|
|
1233
|
-
|
|
1633
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
1634
|
+
args = structuredClone(args);
|
|
1635
|
+
if (!plainObject(args, ["name", "description", "body", "roles", "lessons", "replace", "requestId"]) || typeof args.name !== "string" || !/^[a-z0-9][a-z0-9-]{1,62}$/.test(args.name) || !text(args.description, 300) || !text(args.body, SKILL_BODY_CHARS) || !Array.isArray(args.roles) || !args.roles.length || args.roles.length > 10 || !args.roles.every((role) => typeof role === "string" && /^[\w.-]+$/.test(role) && role !== "." && role !== "..") || args.lessons !== void 0 && (!Array.isArray(args.lessons) || args.lessons.length > 50 || !args.lessons.every((lesson) => text(lesson, LESSON_CHARS))) || args.replace !== void 0 && typeof args.replace !== "boolean") {
|
|
1234
1636
|
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` });
|
|
1235
1637
|
}
|
|
1236
|
-
if (!
|
|
1237
|
-
const
|
|
1638
|
+
if (args.requestId !== void 0 && !text(args.requestId, 100)) return toolResult(false, { error: "requestId must be a nonempty string of at most 100 characters" });
|
|
1639
|
+
const library = options.libraryDir;
|
|
1640
|
+
if (!library) return toolResult(false, { error: "This host keeps no user skill library" });
|
|
1641
|
+
const known = /* @__PURE__ */ new Set([...STARTER_ROLES, ...await discoverAgents(session.mapping.agent.projectRoot, { library, templates: options.templates })]);
|
|
1238
1642
|
const unknown = args.roles.filter((role) => !known.has(role));
|
|
1239
1643
|
if (unknown.length) return toolResult(false, { error: `Unknown roles: ${unknown.join(", ")}. Roles are ${[...known].join(", ")}` });
|
|
1240
|
-
const file = path.join(
|
|
1644
|
+
const file = path.join(library, "skills", args.name, "SKILL.md");
|
|
1645
|
+
const content = `---
|
|
1646
|
+
name: ${args.name}
|
|
1647
|
+
description: ${JSON.stringify(args.description.replace(/\s+/g, " ").trim())}
|
|
1648
|
+
---
|
|
1649
|
+
|
|
1650
|
+
${args.body.trim()}
|
|
1651
|
+
`;
|
|
1652
|
+
const normalizeLesson = (lesson) => lesson.replace(/\s+/g, " ").trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, "").trim();
|
|
1653
|
+
const lessons = [...new Set((args.lessons ?? []).map(normalizeLesson))];
|
|
1654
|
+
const draftKey = JSON.stringify(["skill", content, args.roles, lessons, !!args.replace]);
|
|
1655
|
+
const key = `skill:${args.requestId ?? draftKey}`;
|
|
1656
|
+
const approvals = approvalsOf(sessionId);
|
|
1657
|
+
const previous = approvals.get(key);
|
|
1658
|
+
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: "requestId was already used for a different draft" });
|
|
1659
|
+
if (previous) return toolResult(true, previous.result ?? { status: "pending_approval", approvalId: previous.approvalId, file });
|
|
1241
1660
|
const existing = await readFile(file, "utf8").catch(() => void 0);
|
|
1242
1661
|
if (existing !== void 0 && !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` });
|
|
1243
|
-
const
|
|
1662
|
+
const invalid = checkFrontmatter(splitSkill(content).frontmatter, args.name, { strict: true }).findings.filter((finding) => finding.level === "error");
|
|
1663
|
+
if (invalid.length) return toolResult(false, { error: `The skill does not meet the skill format: ${invalid.map((finding) => finding.message).join("; ")}` });
|
|
1664
|
+
const missing = [];
|
|
1665
|
+
for (const target of skillReferences(args.body)) {
|
|
1666
|
+
const resolved = path.resolve(path.dirname(file), target);
|
|
1667
|
+
if (path.isAbsolute(target) || path.relative(path.dirname(file), resolved).startsWith("..") || !await stat(resolved).then(() => true, () => false)) missing.push(target);
|
|
1668
|
+
}
|
|
1669
|
+
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` });
|
|
1670
|
+
const rolesFile = path.join(library, "role-skills.json");
|
|
1244
1671
|
const readRoles = async () => {
|
|
1245
1672
|
const raw = await readFile(rolesFile, "utf8").catch(() => "{}");
|
|
1246
1673
|
const roles = JSON.parse(raw);
|
|
@@ -1252,62 +1679,422 @@ ${cut(session.brief, BRIEF_CHARS)}`);
|
|
|
1252
1679
|
} catch (error) {
|
|
1253
1680
|
return toolResult(false, { error: errorData(error).message });
|
|
1254
1681
|
}
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
${args.body.trim()}
|
|
1261
|
-
`;
|
|
1262
|
-
const lessons = (args.lessons ?? []).map((lesson) => lesson.replace(/\s+/g, " ").trim());
|
|
1682
|
+
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: "Skill proposal canceled or session closed; no approval was created" });
|
|
1683
|
+
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" });
|
|
1684
|
+
const approvalId = `q-${randomUUID()}`;
|
|
1685
|
+
const record2 = { approvalId, draftKey };
|
|
1686
|
+
approvals.set(key, record2);
|
|
1263
1687
|
const say = wordsFor(session);
|
|
1264
|
-
const decision =
|
|
1688
|
+
const decision = confirm(
|
|
1265
1689
|
sessionId,
|
|
1266
1690
|
session,
|
|
1267
1691
|
say.skill(session.mapping.agent.name, existing !== void 0, file, args.roles.join(", "), lessons) + `
|
|
1268
1692
|
${say.answerLine(session.mapping.agent.name)}
|
|
1269
1693
|
|
|
1270
|
-
${content}
|
|
1694
|
+
${content}`,
|
|
1695
|
+
{ id: approvalId }
|
|
1271
1696
|
);
|
|
1272
|
-
|
|
1697
|
+
const save = async () => {
|
|
1698
|
+
if (existing === void 0 && !args.replace && await readFile(file, "utf8").then(() => true, () => false)) {
|
|
1699
|
+
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." };
|
|
1700
|
+
}
|
|
1701
|
+
try {
|
|
1702
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
1703
|
+
await writeFile(file, content);
|
|
1704
|
+
const roles = await readRoles();
|
|
1705
|
+
for (const role of args.roles) {
|
|
1706
|
+
const list = Array.isArray(roles[role]) ? roles[role] : [];
|
|
1707
|
+
if (!list.includes(args.name)) list.push(args.name);
|
|
1708
|
+
roles[role] = list;
|
|
1709
|
+
}
|
|
1710
|
+
await writeAtomic(rolesFile, JSON.stringify(roles, null, 2) + "\n");
|
|
1711
|
+
} catch (error) {
|
|
1712
|
+
return { approved: true, saved: false, error: errorData(error).message, next: "Tell the user; nothing is retried automatically." };
|
|
1713
|
+
}
|
|
1714
|
+
const removed = /* @__PURE__ */ new Set();
|
|
1715
|
+
for (const lessonFile of lessonFiles(session.mapping)) {
|
|
1716
|
+
const current = await readFile(lessonFile, "utf8").catch(() => void 0);
|
|
1717
|
+
if (current === void 0) continue;
|
|
1718
|
+
const kept = current.split("\n").filter((line) => {
|
|
1719
|
+
const match = /^- \d{4}-\d\d-\d\d: (.*)$/.exec(line);
|
|
1720
|
+
if (!match) return true;
|
|
1721
|
+
const lesson = normalizeLesson(line);
|
|
1722
|
+
if (!lessons.includes(lesson)) return true;
|
|
1723
|
+
removed.add(lesson);
|
|
1724
|
+
return false;
|
|
1725
|
+
});
|
|
1726
|
+
if (kept.length !== current.split("\n").length) await writeFile(lessonFile, kept.join("\n")).catch(() => {
|
|
1727
|
+
});
|
|
1728
|
+
}
|
|
1729
|
+
runLog(rootOf(sessionId), { event: "skill", agent: session.mapping.agent.name, name: args.name, roles: args.roles, replaced: existing !== void 0, lessons: [...removed] });
|
|
1730
|
+
return {
|
|
1731
|
+
approved: true,
|
|
1732
|
+
saved: file,
|
|
1733
|
+
roles: args.roles,
|
|
1734
|
+
lessonsRemoved: [...removed],
|
|
1735
|
+
...lessons.length > removed.size ? { lessonsNotFound: lessons.filter((lesson) => !removed.has(lesson)) } : {},
|
|
1736
|
+
next: "New sessions of those roles list the skill; read the file now if you need it in this one."
|
|
1737
|
+
};
|
|
1738
|
+
};
|
|
1739
|
+
void (async () => {
|
|
1740
|
+
const answer = await decision;
|
|
1741
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
1742
|
+
const result = !answer.approved || canceled ? { 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." } : await save();
|
|
1743
|
+
record2.result = { status: "resolved", approvalId, name: args.name, ...result };
|
|
1744
|
+
runLog(rootOf(sessionId), { event: "skill.approval", agent: session.mapping.agent.name, ...record2.result });
|
|
1745
|
+
if (!closed && !session.closed && sessions.get(sessionId) === session) {
|
|
1746
|
+
post(sessionId, { kind: "result", from: "ALP", assignment: approvalId, body: `Skill approval result: ${JSON.stringify(record2.result)}` });
|
|
1747
|
+
}
|
|
1748
|
+
})();
|
|
1749
|
+
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." });
|
|
1750
|
+
}
|
|
1751
|
+
async function skillRetireTool(sessionId, session, args) {
|
|
1752
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
1753
|
+
args = structuredClone(args);
|
|
1754
|
+
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)) {
|
|
1755
|
+
return toolResult(false, { error: "Retiring a skill needs its name (lowercase letters, digits, hyphens) and a one-line reason of at most 300 characters" });
|
|
1756
|
+
}
|
|
1757
|
+
if (args.requestId !== void 0 && !text(args.requestId, 100)) return toolResult(false, { error: "requestId must be a nonempty string of at most 100 characters" });
|
|
1758
|
+
const library = options.libraryDir;
|
|
1759
|
+
if (!library) return toolResult(false, { error: "This host keeps no user skill library" });
|
|
1760
|
+
const directory = path.join(library, "skills", args.name);
|
|
1761
|
+
const file = path.join(directory, "SKILL.md");
|
|
1762
|
+
const reason = args.reason.replace(/\s+/g, " ").trim();
|
|
1763
|
+
const draftKey = JSON.stringify(["skill.retire", args.name, reason]);
|
|
1764
|
+
const key = `skill.retire:${args.requestId ?? draftKey}`;
|
|
1765
|
+
const approvals = approvalsOf(sessionId);
|
|
1766
|
+
const previous = approvals.get(key);
|
|
1767
|
+
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: "requestId was already used for a different draft" });
|
|
1768
|
+
if (previous) return toolResult(true, previous.result ?? { status: "pending_approval", approvalId: previous.approvalId, file });
|
|
1769
|
+
const content = await readFile(file, "utf8").catch(() => void 0);
|
|
1770
|
+
if (content === void 0) return toolResult(false, { error: `The library has no skill named ${args.name} (${file})` });
|
|
1771
|
+
const rolesFile = path.join(library, "role-skills.json");
|
|
1772
|
+
const readRoles = async () => {
|
|
1773
|
+
const roles = JSON.parse(await readFile(rolesFile, "utf8").catch(() => "{}"));
|
|
1774
|
+
if (!roles || typeof roles !== "object" || Array.isArray(roles)) throw new Error(`${rolesFile} must be an object of role names to skill lists`);
|
|
1775
|
+
return roles;
|
|
1776
|
+
};
|
|
1777
|
+
const holders = (roles) => Object.keys(roles).filter((role) => Array.isArray(roles[role]) && roles[role].includes(args.name)).sort();
|
|
1778
|
+
const namedBy = async () => {
|
|
1779
|
+
const found = [];
|
|
1780
|
+
for (const [agent, source] of await agentSources(session.mapping.agent.projectRoot, { library, templates: options.templates })) {
|
|
1781
|
+
const where = source.directory ? path.join(source.directory, "agent.json") : `built-in agents/${agent}/agent.json`;
|
|
1782
|
+
const body = source.directory ? await readFile(path.join(source.directory, "agent.json"), "utf8").catch((error) => {
|
|
1783
|
+
if (error.code === "ENOENT") return void 0;
|
|
1784
|
+
throw error;
|
|
1785
|
+
}) : await builtinText(`agents/${agent}/agent.json`, options.templates);
|
|
1786
|
+
if (body === void 0) continue;
|
|
1787
|
+
let config;
|
|
1788
|
+
try {
|
|
1789
|
+
config = JSON.parse(body);
|
|
1790
|
+
} catch (error) {
|
|
1791
|
+
throw new Error(`${where}: ${errorData(error).message}`);
|
|
1792
|
+
}
|
|
1793
|
+
const skills = config && typeof config === "object" ? config.skills : void 0;
|
|
1794
|
+
if (Array.isArray(skills) && skills.includes(args.name)) found.push(`agent ${agent}`);
|
|
1795
|
+
}
|
|
1796
|
+
return found.sort();
|
|
1797
|
+
};
|
|
1798
|
+
const digest = async () => {
|
|
1799
|
+
const hash = createHash("sha256");
|
|
1800
|
+
const walk = async (dir, rel) => {
|
|
1801
|
+
for (const entry of (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
1802
|
+
const name = rel ? `${rel}/${entry.name}` : entry.name;
|
|
1803
|
+
if (entry.isDirectory()) {
|
|
1804
|
+
hash.update(`d:${name}\0`);
|
|
1805
|
+
await walk(path.join(dir, entry.name), name);
|
|
1806
|
+
} else {
|
|
1807
|
+
hash.update(`f:${name}\0`);
|
|
1808
|
+
hash.update(await readFile(path.join(dir, entry.name)));
|
|
1809
|
+
hash.update("\0");
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
};
|
|
1813
|
+
await walk(directory, "");
|
|
1814
|
+
return hash.digest("hex");
|
|
1815
|
+
};
|
|
1816
|
+
let given;
|
|
1817
|
+
let users;
|
|
1818
|
+
let tree;
|
|
1273
1819
|
try {
|
|
1274
|
-
await
|
|
1275
|
-
await
|
|
1276
|
-
|
|
1277
|
-
for (const role of args.roles) {
|
|
1278
|
-
const list = Array.isArray(roles[role]) ? roles[role] : [];
|
|
1279
|
-
if (!list.includes(args.name)) list.push(args.name);
|
|
1280
|
-
roles[role] = list;
|
|
1281
|
-
}
|
|
1282
|
-
await writeFile(rolesFile, JSON.stringify(roles, null, 2) + "\n");
|
|
1820
|
+
given = holders(await readRoles());
|
|
1821
|
+
users = await namedBy();
|
|
1822
|
+
tree = await digest();
|
|
1283
1823
|
} catch (error) {
|
|
1284
1824
|
return toolResult(false, { error: errorData(error).message });
|
|
1285
1825
|
}
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1826
|
+
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: "Skill retirement canceled or session closed; no approval was created" });
|
|
1827
|
+
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" });
|
|
1828
|
+
const retired = path.join(library, "retired-skills", `${args.name}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`);
|
|
1829
|
+
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).`;
|
|
1830
|
+
const approvalId = `q-${randomUUID()}`;
|
|
1831
|
+
const record2 = { approvalId, draftKey };
|
|
1832
|
+
approvals.set(key, record2);
|
|
1833
|
+
const say = wordsFor(session);
|
|
1834
|
+
const decision = confirm(
|
|
1835
|
+
sessionId,
|
|
1836
|
+
session,
|
|
1837
|
+
say.skillRetire(session.mapping.agent.name, args.name, file, retired, given.join(", "), users.join(", "), reason) + `
|
|
1838
|
+
${say.answerLine(session.mapping.agent.name)}
|
|
1839
|
+
|
|
1840
|
+
${content}`,
|
|
1841
|
+
{ id: approvalId }
|
|
1842
|
+
);
|
|
1843
|
+
const retire = async () => {
|
|
1844
|
+
const refuse = (error, next) => ({ approved: true, retired: false, error, next });
|
|
1845
|
+
let before;
|
|
1846
|
+
try {
|
|
1847
|
+
if (await digest().catch(() => void 0) !== tree) {
|
|
1848
|
+
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.");
|
|
1849
|
+
}
|
|
1850
|
+
const now = await namedBy();
|
|
1851
|
+
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.");
|
|
1852
|
+
before = await readFile(rolesFile, "utf8").catch((error) => {
|
|
1853
|
+
if (error.code === "ENOENT") return void 0;
|
|
1854
|
+
throw error;
|
|
1855
|
+
});
|
|
1856
|
+
const roles = await readRoles();
|
|
1857
|
+
const lost = holders(roles);
|
|
1858
|
+
if (JSON.stringify(lost) !== JSON.stringify(given)) {
|
|
1859
|
+
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.");
|
|
1860
|
+
}
|
|
1861
|
+
await mkdir(path.dirname(retired), { recursive: true, mode: 448 });
|
|
1862
|
+
if (lost.length) {
|
|
1863
|
+
for (const role of lost) roles[role] = roles[role].filter((name) => name !== args.name);
|
|
1864
|
+
await writeAtomic(rolesFile, JSON.stringify(roles, null, 2) + "\n");
|
|
1865
|
+
}
|
|
1866
|
+
try {
|
|
1867
|
+
await moveFile(directory, retired);
|
|
1868
|
+
} catch (error) {
|
|
1869
|
+
if (lost.length) {
|
|
1870
|
+
try {
|
|
1871
|
+
if (before === void 0) await rm(rolesFile, { force: true });
|
|
1872
|
+
else await writeAtomic(rolesFile, before);
|
|
1873
|
+
} catch (undo) {
|
|
1874
|
+
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(", ")}.`);
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
return refuse(`${errorData(error).message}; nothing was retired`, "Tell the user; nothing is retried automatically.");
|
|
1878
|
+
}
|
|
1879
|
+
let metadata;
|
|
1880
|
+
try {
|
|
1881
|
+
await writeAtomic(path.join(retired, "retired.json"), JSON.stringify({ name: args.name, roles: lost, retiredAt: (/* @__PURE__ */ new Date()).toISOString(), agent: session.mapping.agent.name, path: directory }, null, 2) + "\n");
|
|
1882
|
+
} catch (error) {
|
|
1883
|
+
metadata = errorData(error).message;
|
|
1884
|
+
}
|
|
1885
|
+
runLog(rootOf(sessionId), { event: "skill.retire", agent: session.mapping.agent.name, name: args.name, roles: lost, retiredTo: retired, ...metadata ? { metadataError: metadata } : {} });
|
|
1886
|
+
return { approved: true, retired, roles: lost, ...metadata ? { metadataError: metadata } : {}, next: `New sessions no longer list the skill. ${restore}` };
|
|
1887
|
+
} catch (error) {
|
|
1888
|
+
return refuse(`${errorData(error).message}; nothing was retired`, "Tell the user; nothing is retried automatically.");
|
|
1889
|
+
}
|
|
1890
|
+
};
|
|
1891
|
+
void (async () => {
|
|
1892
|
+
const answer = await decision;
|
|
1893
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
1894
|
+
const result = !answer.approved || canceled ? { 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." } : await retire();
|
|
1895
|
+
record2.result = { status: "resolved", approvalId, name: args.name, ...result };
|
|
1896
|
+
runLog(rootOf(sessionId), { event: "skill.retire.approval", agent: session.mapping.agent.name, ...record2.result });
|
|
1897
|
+
if (!closed && !session.closed && sessions.get(sessionId) === session) {
|
|
1898
|
+
post(sessionId, { kind: "result", from: "ALP", assignment: approvalId, body: `Skill retirement result: ${JSON.stringify(record2.result)}` });
|
|
1899
|
+
}
|
|
1900
|
+
})();
|
|
1901
|
+
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." });
|
|
1902
|
+
}
|
|
1903
|
+
let scheduleHandler;
|
|
1904
|
+
async function lessonCurateTool(sessionId, session, args) {
|
|
1905
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
1906
|
+
args = structuredClone(args);
|
|
1907
|
+
const validChange = (change) => plainObject(change, ["scope", "remove", "add", "reason"]) && ["project", "user"].includes(change.scope) && Array.isArray(change.remove) && change.remove.length > 0 && change.remove.length <= 50 && change.remove.every((lesson) => text(lesson, LESSON_CHARS)) && (change.add === void 0 || text(change.add, LESSON_CHARS)) && (change.reason === void 0 || typeof change.reason === "string" && change.reason.length <= 300);
|
|
1908
|
+
if (!plainObject(args, ["changes", "requestId"]) || !Array.isArray(args.changes) || !args.changes.length || args.changes.length > 50 || !args.changes.every(validChange)) {
|
|
1909
|
+
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` });
|
|
1910
|
+
}
|
|
1911
|
+
if (args.requestId !== void 0 && !text(args.requestId, 100)) return toolResult(false, { error: "requestId must be a nonempty string of at most 100 characters" });
|
|
1912
|
+
const changes = args.changes;
|
|
1913
|
+
if (changes.some((change) => change.scope === "user") && !options.libraryDir) return toolResult(false, { error: "This host keeps no user lessons" });
|
|
1914
|
+
const fileOf = (scope) => scope === "user" ? path.join(options.libraryDir, LESSONS_FILE) : path.join(session.mapping.agent.projectRoot, ".alp", LESSONS_FILE);
|
|
1915
|
+
const normalizeLesson = (lesson) => lesson.replace(/\s+/g, " ").trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, "").trim();
|
|
1916
|
+
const normalized = changes.map((change) => ({ ...change, remove: [...new Set(change.remove.map(normalizeLesson))], add: change.add?.replace(/\s+/g, " ").trim() }));
|
|
1917
|
+
const draftKey = JSON.stringify(["lessons", normalized]);
|
|
1918
|
+
const key = `lessons:${args.requestId ?? draftKey}`;
|
|
1919
|
+
const approvals = approvalsOf(sessionId);
|
|
1920
|
+
const previous = approvals.get(key);
|
|
1921
|
+
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: "requestId was already used for a different draft" });
|
|
1922
|
+
if (previous) return toolResult(true, previous.result ?? { status: "pending_approval", approvalId: previous.approvalId });
|
|
1923
|
+
const readLessons = async (file) => (await readFile(file, "utf8").catch(() => "")).split("\n").flatMap((line) => /^- \d{4}-\d\d-\d\d: /.test(line) ? [normalizeLesson(line)] : []);
|
|
1924
|
+
const missing = [];
|
|
1925
|
+
for (const change of normalized) {
|
|
1926
|
+
const recorded = new Set(await readLessons(fileOf(change.scope)));
|
|
1927
|
+
for (const lesson of change.remove) if (!recorded.has(lesson)) missing.push(`${change.scope}: ${lesson}`);
|
|
1928
|
+
}
|
|
1929
|
+
if (missing.length) return toolResult(false, { error: "These lessons are not recorded; copy their exact text from the lessons files", missing });
|
|
1930
|
+
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: "Lesson proposal canceled or session closed; no approval was created" });
|
|
1931
|
+
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" });
|
|
1932
|
+
const approvalId = `q-${randomUUID()}`;
|
|
1933
|
+
const record2 = { approvalId, draftKey };
|
|
1934
|
+
approvals.set(key, record2);
|
|
1935
|
+
const say = wordsFor(session);
|
|
1936
|
+
const shown = normalized.map((change, index) => `${index + 1}. ${say.lessonScope(change.scope, fileOf(change.scope))}${change.reason ? ` \u2014 ${change.reason}` : ""}
|
|
1937
|
+
` + change.remove.map((lesson) => ` ${say.lessonRemove}: ${lesson}`).join("\n") + (change.add ? `
|
|
1938
|
+
${say.lessonAdd}: ${change.add}` : "")).join("\n\n");
|
|
1939
|
+
const decision = confirm(sessionId, session, `${say.lessonCurate(session.mapping.agent.name, shown)}
|
|
1940
|
+
|
|
1941
|
+
${say.answerLine(session.mapping.agent.name)}`, { id: approvalId });
|
|
1942
|
+
const apply = async () => {
|
|
1943
|
+
const removed = [];
|
|
1944
|
+
const notFound = [];
|
|
1945
|
+
let added = 0;
|
|
1946
|
+
for (const scope of ["project", "user"]) {
|
|
1947
|
+
const mine = normalized.filter((change) => change.scope === scope);
|
|
1948
|
+
if (!mine.length) continue;
|
|
1949
|
+
const file = fileOf(scope);
|
|
1950
|
+
const write = (lessonWrites.get(file) ?? Promise.resolve()).catch(() => {
|
|
1951
|
+
}).then(async () => {
|
|
1952
|
+
const current = await readFile(file, "utf8").catch(() => void 0);
|
|
1953
|
+
if (current === void 0) {
|
|
1954
|
+
for (const change of mine) notFound.push(...change.remove.map((lesson) => `${scope}: ${lesson}`));
|
|
1955
|
+
return;
|
|
1956
|
+
}
|
|
1957
|
+
const targets = new Set(mine.flatMap((change) => change.remove));
|
|
1958
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1959
|
+
const kept = current.split("\n").filter((line) => {
|
|
1960
|
+
if (!/^- \d{4}-\d\d-\d\d: /.test(line)) return true;
|
|
1961
|
+
const lesson = normalizeLesson(line);
|
|
1962
|
+
if (!targets.has(lesson)) return true;
|
|
1963
|
+
seen.add(lesson);
|
|
1964
|
+
return false;
|
|
1965
|
+
});
|
|
1966
|
+
for (const lesson of targets) (seen.has(lesson) ? removed : notFound).push(`${scope}: ${lesson}`);
|
|
1967
|
+
const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
1968
|
+
const additions = mine.filter((change) => change.add && change.remove.some((lesson) => seen.has(lesson))).map((change) => `- ${date}: ${change.add}`);
|
|
1969
|
+
added += additions.length;
|
|
1970
|
+
let body = kept.join("\n");
|
|
1971
|
+
if (additions.length) body = body.replace(/\n*$/, "\n") + additions.join("\n") + "\n";
|
|
1972
|
+
await writeFile(file, body);
|
|
1973
|
+
});
|
|
1974
|
+
lessonWrites.set(file, write);
|
|
1975
|
+
await write;
|
|
1976
|
+
}
|
|
1977
|
+
runLog(rootOf(sessionId), { event: "lesson.curate", agent: session.mapping.agent.name, removed, added, notFound });
|
|
1978
|
+
return { approved: true, applied: true, removed, added, ...notFound.length ? { lessonsNotFound: notFound } : {} };
|
|
1979
|
+
};
|
|
1980
|
+
void (async () => {
|
|
1981
|
+
const answer = await decision;
|
|
1982
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
1983
|
+
let result;
|
|
1984
|
+
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." };
|
|
1985
|
+
else {
|
|
1986
|
+
try {
|
|
1987
|
+
result = await apply();
|
|
1988
|
+
} catch (error) {
|
|
1989
|
+
result = { approved: true, applied: false, error: errorData(error).message, next: "Tell the user; nothing is retried automatically." };
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
record2.result = { status: "resolved", approvalId, ...result };
|
|
1993
|
+
runLog(rootOf(sessionId), { event: "lesson.curate.approval", agent: session.mapping.agent.name, ...record2.result });
|
|
1994
|
+
if (!closed && !session.closed && sessions.get(sessionId) === session) post(sessionId, { kind: "result", from: "ALP", assignment: approvalId, body: `Lesson curate result: ${JSON.stringify(record2.result)}` });
|
|
1995
|
+
})();
|
|
1996
|
+
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." });
|
|
1997
|
+
}
|
|
1998
|
+
const curateSchedules = /* @__PURE__ */ new Map();
|
|
1999
|
+
function ensureCurateSchedule(sessionId) {
|
|
2000
|
+
const root = sessions.get(sessionId);
|
|
2001
|
+
if (!scheduleHandler || !root || root.closed || root.parent) return Promise.resolve();
|
|
2002
|
+
const project = root.mapping.agent.projectRoot;
|
|
2003
|
+
const run = (curateSchedules.get(project) ?? Promise.resolve()).catch(() => {
|
|
2004
|
+
}).then(() => curateScheduleOf(sessionId, root, project));
|
|
2005
|
+
curateSchedules.set(project, run);
|
|
2006
|
+
void run.catch(() => {
|
|
2007
|
+
}).then(() => {
|
|
2008
|
+
if (curateSchedules.get(project) === run) curateSchedules.delete(project);
|
|
2009
|
+
});
|
|
2010
|
+
return run;
|
|
2011
|
+
}
|
|
2012
|
+
async function curateScheduleOf(sessionId, root, project) {
|
|
2013
|
+
const handler = scheduleHandler;
|
|
2014
|
+
if (!handler || root.closed || sessions.get(sessionId) !== root) return;
|
|
2015
|
+
for (const file of [path.join(project, ".alp", "settings.json"), ...options.libraryDir ? [path.join(options.libraryDir, "settings.json")] : []]) {
|
|
2016
|
+
const settings = await readFile(file, "utf8").then((raw) => {
|
|
2017
|
+
try {
|
|
2018
|
+
return JSON.parse(raw);
|
|
2019
|
+
} catch {
|
|
2020
|
+
return void 0;
|
|
2021
|
+
}
|
|
2022
|
+
}, () => void 0);
|
|
2023
|
+
const monthly = settings?.curate?.monthly;
|
|
2024
|
+
if (monthly === false) return;
|
|
2025
|
+
if (monthly === true) break;
|
|
2026
|
+
}
|
|
2027
|
+
const listed = await handler("list", { projectRoot: project, status: "pending" });
|
|
2028
|
+
const curate = (listed?.jobs ?? []).filter((job) => job.prompt.startsWith(CURATE_MARKER));
|
|
2029
|
+
if (curate.some((job) => job.sessionId === sessionId)) return;
|
|
2030
|
+
for (const job of curate) await handler("cancel", { id: job.id, projectRoot: project }).catch(() => {
|
|
2031
|
+
});
|
|
2032
|
+
const now = /* @__PURE__ */ new Date();
|
|
2033
|
+
const dueAt = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 2)).toISOString();
|
|
2034
|
+
await handler("create", { projectRoot: project, sessionId, dueAt, prompt: CURATE_PROMPT, keepsSession: false });
|
|
2035
|
+
runLog(sessionId, { event: "curate.scheduled", dueAt, replaced: curate.map((job) => job.id) });
|
|
2036
|
+
}
|
|
2037
|
+
async function scheduleTool(sessionId, session, args) {
|
|
2038
|
+
if (session.parent || session.role === "supervisor" || session.mapping.agent.name !== mainOf(session.mapping)) return toolResult(false, { error: "Only the main root session schedules continuations" });
|
|
2039
|
+
if (!scheduleHandler) return toolResult(false, { error: "This host does not support scheduled continuations" });
|
|
2040
|
+
if (!plainObject(args, ["action", "dueAt", "prompt", "requestId", "id", "status"]) || !["create", "list", "get", "cancel"].includes(args.action)) return toolResult(false, { error: "Unknown schedule action" });
|
|
2041
|
+
const action = args.action;
|
|
2042
|
+
const fields = action === "create" ? ["action", "dueAt", "prompt", "requestId"] : action === "list" ? ["action", "status"] : ["action", "id"];
|
|
2043
|
+
if (Object.keys(args).some((key2) => !fields.includes(key2))) return toolResult(false, { error: "Unexpected schedule argument" });
|
|
2044
|
+
const handler = scheduleHandler;
|
|
2045
|
+
const projectRoot = session.mapping.agent.projectRoot;
|
|
2046
|
+
const invoke = async (params) => {
|
|
2047
|
+
try {
|
|
2048
|
+
return toolResult(true, await handler(action, { ...params, projectRoot }));
|
|
2049
|
+
} catch (error) {
|
|
2050
|
+
return toolResult(false, { error: errorData(error).message });
|
|
2051
|
+
}
|
|
2052
|
+
};
|
|
2053
|
+
if (action !== "create") return invoke(action === "list" ? { ...args.status ? { status: args.status } : {} } : { id: args.id });
|
|
2054
|
+
if (!text(args.requestId, 200) || !text(args.prompt, 8e3) || !text(args.dueAt, 80) || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/.test(args.dueAt) || !Number.isFinite(Date.parse(args.dueAt))) return toolResult(false, { error: "create needs requestId, prompt (1\u20138000 characters) and dueAt with an explicit UTC offset" });
|
|
2055
|
+
const draftKey = JSON.stringify([args.dueAt, args.prompt]);
|
|
2056
|
+
const key = `schedule:${args.requestId}`;
|
|
2057
|
+
const approvals = approvalsOf(sessionId);
|
|
2058
|
+
const previous = approvals.get(key);
|
|
2059
|
+
if (previous) return previous.draftKey !== draftKey ? toolResult(false, { error: "requestId already names another schedule draft" }) : toolResult(true, previous.result ?? { status: "pending_approval", approvalId: previous.approvalId });
|
|
2060
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
2061
|
+
const approvalId = `q-${randomUUID()}`;
|
|
2062
|
+
const record2 = { approvalId, draftKey };
|
|
2063
|
+
approvals.set(key, record2);
|
|
2064
|
+
const decision = confirm(
|
|
2065
|
+
sessionId,
|
|
2066
|
+
session,
|
|
2067
|
+
`T\u1EA1o l\u1ECBch ti\u1EBFp t\u1EE5c m\u1ED9t l\u1EA7n?
|
|
2068
|
+
Project: ${projectRoot}
|
|
2069
|
+
Session: ${sessionId}
|
|
2070
|
+
Th\u1EDDi gian: ${args.dueAt} (${new Date(args.dueAt).toISOString()})
|
|
2071
|
+
|
|
2072
|
+
${args.prompt}`,
|
|
2073
|
+
{ id: approvalId }
|
|
2074
|
+
);
|
|
2075
|
+
void decision.then(async (answer) => {
|
|
2076
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
2077
|
+
let result;
|
|
2078
|
+
if (!answer.approved || canceled) result = { approved: false, created: false, outcome: canceled ? "canceled" : answer.outcome, feedback: answer.feedback };
|
|
2079
|
+
else {
|
|
2080
|
+
try {
|
|
2081
|
+
result = { approved: true, created: true, ...await handler("create", { projectRoot, sessionId, dueAt: args.dueAt, prompt: args.prompt }) };
|
|
2082
|
+
} catch (error) {
|
|
2083
|
+
result = { approved: true, created: false, error: errorData(error).message };
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
record2.result = { status: "resolved", approvalId, ...result };
|
|
2087
|
+
runLog(rootOf(sessionId), { event: "schedule.approval", ...record2.result });
|
|
2088
|
+
if (!session.closed) post(sessionId, { kind: "result", from: "ALP", assignment: approvalId, body: `Schedule approval result: ${JSON.stringify(record2.result)}` });
|
|
2089
|
+
}).catch((error) => {
|
|
2090
|
+
record2.result = { status: "resolved", approvalId, created: false, error: errorData(error).message };
|
|
1307
2091
|
});
|
|
2092
|
+
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." });
|
|
1308
2093
|
}
|
|
1309
2094
|
async function issueTool(sessionId, session, args) {
|
|
1310
|
-
|
|
2095
|
+
const cancellation = approvalCancellation.get(session) ?? 0;
|
|
2096
|
+
args = structuredClone(args);
|
|
2097
|
+
if (!plainObject(args, ["action", "target", "query", "title", "body", "issue", "labels", "requestId"]) || !["search", "create", "comment"].includes(args.action) || !["project", "alp"].includes(args.target)) {
|
|
1311
2098
|
return toolResult(false, { error: "An issue call needs action (search, create or comment) and target (project or alp)" });
|
|
1312
2099
|
}
|
|
1313
2100
|
const project = session.mapping.agent.projectRoot;
|
|
@@ -1333,6 +2120,7 @@ ${content}`
|
|
|
1333
2120
|
if (args.labels !== void 0 && (args.action !== "create" || !Array.isArray(args.labels) || args.labels.length > 10 || !args.labels.every((label2) => text(label2, 50)))) {
|
|
1334
2121
|
return toolResult(false, { error: "labels are up to 10 existing label names, for create" });
|
|
1335
2122
|
}
|
|
2123
|
+
if (args.requestId !== void 0 && !text(args.requestId, 100)) return toolResult(false, { error: "requestId must be a nonempty string of at most 100 characters" });
|
|
1336
2124
|
if (args.action === "create" && args.labels?.length) {
|
|
1337
2125
|
try {
|
|
1338
2126
|
const labels = JSON.parse(await github(["label", "list", "-R", repo, "--limit", "1000", "--json", "name"], { cwd: project }));
|
|
@@ -1343,9 +2131,20 @@ ${content}`
|
|
|
1343
2131
|
return toolResult(false, { repo, error: `Could not validate issue labels: ${errorData(error).message}` });
|
|
1344
2132
|
}
|
|
1345
2133
|
}
|
|
2134
|
+
if (approvalCanceled(session, cancellation)) return toolResult(false, { error: "Issue proposal canceled or session closed; no approval was created" });
|
|
2135
|
+
const draftKey = JSON.stringify([repo, args.action, args.title ?? null, args.issue ?? null, args.body, [...args.labels ?? []].sort()]);
|
|
2136
|
+
const key = `issue:${args.requestId ?? draftKey}`;
|
|
2137
|
+
const approvals = approvalsOf(sessionId);
|
|
2138
|
+
const previous = approvals.get(key);
|
|
2139
|
+
if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: "requestId was already used for a different draft" });
|
|
2140
|
+
if (previous) return toolResult(true, previous.result ?? { status: "pending_approval", approvalId: previous.approvalId, repo });
|
|
2141
|
+
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" });
|
|
2142
|
+
const approvalId = `q-${randomUUID()}`;
|
|
2143
|
+
const record2 = { approvalId, draftKey };
|
|
2144
|
+
approvals.set(key, record2);
|
|
1346
2145
|
const where = `${repo}${args.target === "alp" ? " (ALP itself)" : ""}`;
|
|
1347
2146
|
const say = wordsFor(session);
|
|
1348
|
-
const decision =
|
|
2147
|
+
const decision = confirm(
|
|
1349
2148
|
sessionId,
|
|
1350
2149
|
session,
|
|
1351
2150
|
say.issue(session.mapping.agent.name, args.action === "create", args.issue, where) + `
|
|
@@ -1354,18 +2153,31 @@ ${say.answerLine(session.mapping.agent.name)}
|
|
|
1354
2153
|
` + (args.action === "create" ? `${say.issueTitle}: ${args.title}
|
|
1355
2154
|
${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
1356
2155
|
` : ""}
|
|
1357
|
-
` : "") + args.body
|
|
2156
|
+
` : "") + args.body.trim() + ISSUE_FOOTER,
|
|
2157
|
+
{ id: approvalId }
|
|
1358
2158
|
);
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
const
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
2159
|
+
void (async () => {
|
|
2160
|
+
const answer = await decision;
|
|
2161
|
+
let result;
|
|
2162
|
+
const canceled = approvalCanceled(session, cancellation);
|
|
2163
|
+
if (!answer.approved || canceled) {
|
|
2164
|
+
result = { approved: false, posted: false, outcome: canceled ? "canceled" : answer.outcome, ...answer.feedback ? { feedback: answer.feedback } : {} };
|
|
2165
|
+
} else {
|
|
2166
|
+
try {
|
|
2167
|
+
const body = args.body.trim() + ISSUE_FOOTER;
|
|
2168
|
+
const output = args.action === "create" ? await github(["issue", "create", "-R", repo, "--title", args.title, "--body-file", "-", ...(args.labels ?? []).flatMap((label2) => ["--label", label2])], { cwd: project, input: body }) : await github(["issue", "comment", String(args.issue), "-R", repo, "--body-file", "-"], { cwd: project, input: body });
|
|
2169
|
+
result = { approved: true, posted: true, url: output.trim().split("\n").at(-1) ?? "" };
|
|
2170
|
+
} catch (error) {
|
|
2171
|
+
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." };
|
|
2172
|
+
}
|
|
2173
|
+
}
|
|
2174
|
+
record2.result = { status: "resolved", approvalId, repo, ...result };
|
|
2175
|
+
runLog(rootOf(sessionId), { event: "issue.approval", action: args.action, ...args.title ? { title: args.title } : {}, ...args.issue ? { issue: args.issue } : {}, ...record2.result });
|
|
2176
|
+
if (!closed && !session.closed && sessions.get(sessionId) === session) {
|
|
2177
|
+
post(sessionId, { kind: "result", from: "ALP", assignment: approvalId, body: `Issue approval result: ${JSON.stringify(record2.result)}` });
|
|
2178
|
+
}
|
|
2179
|
+
})();
|
|
2180
|
+
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." });
|
|
1369
2181
|
}
|
|
1370
2182
|
function touch(sessionId, session) {
|
|
1371
2183
|
const now = Date.now();
|
|
@@ -1389,6 +2201,8 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1389
2201
|
if (session && !session.closed) {
|
|
1390
2202
|
emit(sessionId, { type: "mail", mail: publicEvent(mail) });
|
|
1391
2203
|
session.mail.push(mail);
|
|
2204
|
+
if (mail.kind === "result" || mail.kind === "question") session.wakes = 0;
|
|
2205
|
+
if (mail.kind === "result" || mail.kind === "question" || mail.kind === "checkin") session.wakeFailures = 0;
|
|
1392
2206
|
deliver(sessionId, session);
|
|
1393
2207
|
}
|
|
1394
2208
|
return mail;
|
|
@@ -1405,13 +2219,17 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1405
2219
|
}
|
|
1406
2220
|
if (!hasActiveMail(session)) return;
|
|
1407
2221
|
const waking = !session.assignments.size || session.mail.some((event) => !event.deliveredTurn && !event.passive && !(event.kind === "note" && event.assignment !== sessionId));
|
|
2222
|
+
if (!session.active && waking && holdsWake(session)) {
|
|
2223
|
+
session.wakeHeld = true;
|
|
2224
|
+
return;
|
|
2225
|
+
}
|
|
1408
2226
|
if (session.pending) {
|
|
1409
2227
|
void session.acknowledged.then(() => deliver(sessionId, session));
|
|
1410
2228
|
} else if (session.active) {
|
|
1411
|
-
if (session.mail.some((event) => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
|
|
2229
|
+
if (!session.compacting && session.mail.some((event) => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
|
|
1412
2230
|
} else if (!waking) {
|
|
1413
2231
|
return;
|
|
1414
|
-
} else if (!session.wakeBlocked && session.wakes < MAX_WAKES) {
|
|
2232
|
+
} else if (!session.wakeBlocked && session.wakeFailures < MAX_WAKES && (session.wakes < MAX_WAKES || session.mail.some((event) => !event.deliveredTurn && event.kind === "checkin"))) {
|
|
1415
2233
|
autoWake(sessionId, session);
|
|
1416
2234
|
} else if (session.parent && !session.wakeBlocked && !held(session)) {
|
|
1417
2235
|
session.settle?.("failed", `Wake limit (${MAX_WAKES}) reached with mail outstanding`);
|
|
@@ -1428,7 +2246,7 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1428
2246
|
try {
|
|
1429
2247
|
await session.runtime.request("turn/steer", { threadId: session.threadId, expectedTurnId: turnId, clientUserMessageId: id, input: [{ type: "text", text: text2, text_elements: [] }] });
|
|
1430
2248
|
steered = true;
|
|
1431
|
-
emit(sessionId, { type: "item", item: { kind: "user_message", id: `user:${id}`, clientMessageId: id, text: text2 } });
|
|
2249
|
+
emit(sessionId, { type: "item", item: { kind: "user_message", id: `user:${id}`, clientMessageId: id, text: text2, origin: "wake" } });
|
|
1432
2250
|
} catch {
|
|
1433
2251
|
}
|
|
1434
2252
|
const received = steered && session.active === turnId;
|
|
@@ -1441,10 +2259,11 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1441
2259
|
if (!received) deliver(sessionId, session);
|
|
1442
2260
|
}
|
|
1443
2261
|
function autoWake(sessionId, session) {
|
|
1444
|
-
if (
|
|
2262
|
+
if (holdsWake(session)) {
|
|
1445
2263
|
session.wakeHeld = true;
|
|
1446
2264
|
return;
|
|
1447
2265
|
}
|
|
2266
|
+
const checkIn2 = session.mail.find((event) => !event.deliveredTurn && event.kind === "checkin");
|
|
1448
2267
|
const batch = takeBatch(session.mail, () => true);
|
|
1449
2268
|
if (!batch.length) return;
|
|
1450
2269
|
for (const event of batch) event.deliveredTurn = STARTING;
|
|
@@ -1453,15 +2272,22 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1453
2272
|
};
|
|
1454
2273
|
const work = queue.then(async () => {
|
|
1455
2274
|
if (closed || session.closed) return release();
|
|
2275
|
+
if (holdsWake(session)) {
|
|
2276
|
+
release();
|
|
2277
|
+
session.wakeHeld = true;
|
|
2278
|
+
return;
|
|
2279
|
+
}
|
|
1456
2280
|
if (session.wakeBlocked || session.active || session.pending) {
|
|
1457
2281
|
release();
|
|
1458
2282
|
return deliver(sessionId, session);
|
|
1459
2283
|
}
|
|
2284
|
+
if (session.wakeFailures >= MAX_WAKES || session.wakes >= MAX_WAKES && (!checkIn2 || !session.mail.includes(checkIn2))) return release();
|
|
1460
2285
|
if (!batch.every((event) => event.kind === "checkin")) session.wakes++;
|
|
1461
2286
|
const id = `alp-wake-${randomUUID()}`;
|
|
1462
2287
|
try {
|
|
1463
2288
|
await startPrompt(sessionId, { clientMessageId: id, delivery: "auto", content: [{ type: "text", text: renderMail(batch, session.parentAgent) }] }, "wake", batch);
|
|
1464
2289
|
} catch {
|
|
2290
|
+
session.wakeFailures++;
|
|
1465
2291
|
release();
|
|
1466
2292
|
deliver(sessionId, session);
|
|
1467
2293
|
}
|
|
@@ -1561,6 +2387,17 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1561
2387
|
waiter.resolve("user");
|
|
1562
2388
|
}
|
|
1563
2389
|
}
|
|
2390
|
+
function releaseQuestions(sessionId) {
|
|
2391
|
+
for (const { question, settle, asked } of [...userQuestions.values()]) {
|
|
2392
|
+
if (question.sessionId !== sessionId || !asked) continue;
|
|
2393
|
+
settle("canceled", void 0, "the user wrote instead of answering", toolResult(true, {
|
|
2394
|
+
status: "user_wrote",
|
|
2395
|
+
userMessage: true,
|
|
2396
|
+
question: question.id,
|
|
2397
|
+
next: `${USER_WROTE} Their message may be the answer to your question; if it is not, ask again later.`
|
|
2398
|
+
}));
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
1564
2401
|
const assignmentSnapshot = (assignment, status) => ({
|
|
1565
2402
|
id: assignment.id,
|
|
1566
2403
|
agent: assignment.agent,
|
|
@@ -1581,7 +2418,8 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1581
2418
|
lineage,
|
|
1582
2419
|
runLog,
|
|
1583
2420
|
runHooks,
|
|
1584
|
-
touchTask
|
|
2421
|
+
touchTask,
|
|
2422
|
+
releaseResult: (assignmentId) => assignmentResults.remove(assignmentId)
|
|
1585
2423
|
});
|
|
1586
2424
|
async function settleTask(parent, assignment, state, handoff) {
|
|
1587
2425
|
const project = parent.mapping.agent.projectRoot;
|
|
@@ -1601,21 +2439,47 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1601
2439
|
async function finishAssignment(parentId, parent, assignment, state, error, quiet = false) {
|
|
1602
2440
|
if (assignment.finished) return;
|
|
1603
2441
|
assignment.finished = true;
|
|
2442
|
+
const child = assignmentSessions.get(assignment);
|
|
1604
2443
|
if (closed && inFlight.get(assignment.id)) {
|
|
1605
2444
|
runLog(assignment.rootId, { event: "assignment.interrupted", assignmentId: assignment.id, agent: assignment.agent, reason: "alpd stopped" });
|
|
1606
|
-
await closeSession(assignment.id);
|
|
2445
|
+
if (child) await closeSession(assignment.id, child);
|
|
1607
2446
|
if (assignment.lease && leases.get(assignment.lease)?.assignment === assignment.id) leases.delete(assignment.lease);
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
2447
|
+
if (!sessions.has(assignment.id) || sessions.get(assignment.id) === child) {
|
|
2448
|
+
childContexts.delete(assignment.id);
|
|
2449
|
+
parent.children.delete(assignment.id);
|
|
2450
|
+
}
|
|
2451
|
+
if (parent.assignments.get(assignment.id) === assignment) parent.assignments.delete(assignment.id);
|
|
1611
2452
|
return;
|
|
1612
2453
|
}
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
2454
|
+
const resultChild = child;
|
|
2455
|
+
try {
|
|
2456
|
+
if (assignment.worktree || writes(assignment.mode)) await assignmentResults.put({
|
|
2457
|
+
assignmentId: assignment.id,
|
|
2458
|
+
checkout: assignment.worktree?.checkout ?? assignment.writeCheckout ?? resultChild?.mapping.workdir ?? parent.mapping.workdir,
|
|
2459
|
+
...assignment.worktree ? { worktree: assignment.worktree.path } : {},
|
|
2460
|
+
// Outside a worktree, the change stays in the checkout: keep its evidence until the requester resolves it.
|
|
2461
|
+
...!assignment.worktree ? { result: {
|
|
2462
|
+
agent: assignment.agent,
|
|
2463
|
+
status: state,
|
|
2464
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2465
|
+
project: (resultChild ?? parent).mapping.agent.projectRoot,
|
|
2466
|
+
requesters: lineage(parentId),
|
|
2467
|
+
...assignment.taskId ? { taskId: assignment.taskId } : {},
|
|
2468
|
+
brief: cut(resultChild?.brief ?? "", RESULT_EVIDENCE_CHARS),
|
|
2469
|
+
summary: cut(JSON.stringify({ handoff: resultChild?.handoff ?? null, output: resultChild ? [...resultChild.text.values()].at(-1) ?? "" : "", ...error ? { error: errorData(error).message } : {} }), RESULT_EVIDENCE_CHARS)
|
|
2470
|
+
} } : {}
|
|
2471
|
+
});
|
|
2472
|
+
} catch (failure) {
|
|
2473
|
+
assignment.finished = false;
|
|
2474
|
+
log.error("could not persist assignment result ownership", { assignmentId: assignment.id, error: failure });
|
|
2475
|
+
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.` });
|
|
2476
|
+
return;
|
|
2477
|
+
}
|
|
2478
|
+
void inFlight.remove(assignment.id);
|
|
2479
|
+
if (child && sessions.get(assignment.id) === child && state === "failed" && child.active) terminal(assignment.id, child, "failed", error);
|
|
2480
|
+
assignment.ask?.resolve(toolResult(false, { error: "Assignment ended" }));
|
|
2481
|
+
const result = {
|
|
2482
|
+
agent: assignment.agent,
|
|
1619
2483
|
...child ? { runtime: child.runtimeKind, threadId: child.threadId } : {},
|
|
1620
2484
|
sessionId: assignment.id,
|
|
1621
2485
|
status: state,
|
|
@@ -1623,7 +2487,7 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1623
2487
|
output: child ? [...child.text.values()].at(-1) ?? "" : "",
|
|
1624
2488
|
...error ? { error: errorData(error).message } : {}
|
|
1625
2489
|
};
|
|
1626
|
-
await closeSession(assignment.id);
|
|
2490
|
+
if (child) await closeSession(assignment.id, child);
|
|
1627
2491
|
if (child?.threadId && child.mapping.keepThread && child.runtimeKind !== "acp") {
|
|
1628
2492
|
void recalls.add({
|
|
1629
2493
|
assignmentId: assignment.id,
|
|
@@ -1674,9 +2538,11 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1674
2538
|
...result
|
|
1675
2539
|
});
|
|
1676
2540
|
if (!parent.closed) emit(parentId, { type: "assignment", assignment: assignmentSnapshot(assignment, state) });
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
2541
|
+
if (!sessions.has(assignment.id) || sessions.get(assignment.id) === child) {
|
|
2542
|
+
childContexts.delete(assignment.id);
|
|
2543
|
+
parent.children.delete(assignment.id);
|
|
2544
|
+
}
|
|
2545
|
+
if (parent.assignments.get(assignment.id) === assignment) parent.assignments.delete(assignment.id);
|
|
1680
2546
|
if (roleOf(parent.mapping, assignment.agent) === "peer") {
|
|
1681
2547
|
const root = sessions.get(assignment.rootId);
|
|
1682
2548
|
if (root) root.peerCount--;
|
|
@@ -1691,7 +2557,7 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1691
2557
|
error: "ALP tools require the current active turn"
|
|
1692
2558
|
});
|
|
1693
2559
|
}
|
|
1694
|
-
if (!["alp_delegate", "alp_handoff", "alp_wait", "alp_cancel", "alp_send", "alp_ask", "alp_merge", "alp_discard", "alp_recall", "alp_verify", "alp_pin", "alp_board", "alp_unpin", "alp_lesson", "alp_skill", "alp_issue", "alp_task"].includes(params.tool) || params.namespace != null || typeof params.callId !== "string") {
|
|
2560
|
+
if (!["alp_delegate", "alp_handoff", "alp_wait", "alp_cancel", "alp_send", "alp_ask", "alp_merge", "alp_discard", "alp_resolve", "alp_recall", "alp_verify", "alp_pin", "alp_board", "alp_unpin", "alp_lesson", "alp_lesson_curate", "alp_skill", "alp_skill_retire", "alp_issue", "alp_task", "alp_schedule"].includes(params.tool) || params.namespace != null || typeof params.callId !== "string") {
|
|
1695
2561
|
return toolResult(false, {
|
|
1696
2562
|
error: "Unknown ALP tool"
|
|
1697
2563
|
});
|
|
@@ -1699,10 +2565,12 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
|
|
|
1699
2565
|
const cached = session.toolCalls.get(params.callId);
|
|
1700
2566
|
if (cached) return cached;
|
|
1701
2567
|
const args = params.arguments;
|
|
2568
|
+
const oversized = inputLimitError(args, TOOL_INPUT, `${params.tool} input`);
|
|
2569
|
+
if (oversized) return toolResult(false, { error: oversized });
|
|
1702
2570
|
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" });
|
|
1703
|
-
if (
|
|
2571
|
+
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" });
|
|
1704
2572
|
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" });
|
|
1705
|
-
const work = params.tool === "alp_lesson" ? lessonTool(sessionId, session, args) : params.tool === "alp_skill" ? skillTool(sessionId, session, args) : params.tool === "alp_issue" ? issueTool(sessionId, session, args) : params.tool === "alp_task" ? taskToolCall(sessionId, session, args) : params.tool === "alp_delegate" ? runDelegation(sessionId, session, params) : params.tool === "alp_wait" ? waitTool(sessionId, session, args) : params.tool === "alp_ask" ? askTool(sessionId, session, args) : params.tool === "alp_pin" ? pinTool(sessionId, session, args) : params.tool === "alp_board" ? boardTool(session, args) : params.tool === "alp_unpin" ? unpinTool(sessionId, session, args) : params.tool === "alp_recall" ? recallTool(sessionId, session, args) : params.tool === "alp_verify" ? verifyTool(sessionId, session, args) : params.tool === "alp_cancel" ? cancelTool(sessionId, session, args) : params.tool === "alp_merge" || params.tool === "alp_discard" ? worktreeTool(sessionId, session, args, params.tool === "alp_merge" ? "merge" : "discard") : params.tool === "alp_send" ? Promise.resolve(sendTool(sessionId, session, args)) : hookedHandoff(sessionId, session, args);
|
|
2573
|
+
const work = params.tool === "alp_lesson" ? lessonTool(sessionId, session, args) : params.tool === "alp_lesson_curate" ? lessonCurateTool(sessionId, session, args) : params.tool === "alp_skill" ? skillTool(sessionId, session, args) : params.tool === "alp_skill_retire" ? skillRetireTool(sessionId, session, args) : params.tool === "alp_issue" ? issueTool(sessionId, session, args) : params.tool === "alp_schedule" ? scheduleTool(sessionId, session, args) : params.tool === "alp_task" ? taskToolCall(sessionId, session, args) : params.tool === "alp_delegate" ? runDelegation(sessionId, session, params) : params.tool === "alp_wait" ? waitTool(sessionId, session, args) : params.tool === "alp_ask" ? askTool(sessionId, session, args) : params.tool === "alp_pin" ? pinTool(sessionId, session, args) : params.tool === "alp_board" ? boardTool(session, args) : params.tool === "alp_unpin" ? unpinTool(sessionId, session, args) : params.tool === "alp_recall" ? recallTool(sessionId, session, args) : params.tool === "alp_resolve" ? resolveTool(sessionId, session, args) : params.tool === "alp_verify" ? verifyTool(sessionId, session, args) : params.tool === "alp_cancel" ? cancelTool(sessionId, session, args) : params.tool === "alp_merge" || params.tool === "alp_discard" ? worktreeTool(sessionId, session, args, params.tool === "alp_merge" ? "merge" : "discard") : params.tool === "alp_send" ? Promise.resolve(sendTool(sessionId, session, args)) : hookedHandoff(sessionId, session, args);
|
|
1706
2574
|
const reminded = !session.parent && params.tool !== "alp_ask" ? work.then((result) => remindUser(session, result)) : work;
|
|
1707
2575
|
session.toolCalls.set(params.callId, reminded);
|
|
1708
2576
|
return reminded;
|
|
@@ -1770,7 +2638,7 @@ ${refused}`, next: "Fix what it reports, then call alp_handoff again." });
|
|
|
1770
2638
|
const pending = [...session.assignments.keys()].some((id) => !ids || ids.has(id)) || takeBatch(session.mail, (event) => event.kind !== "board" && !event.defer && accept(event)).length > 0;
|
|
1771
2639
|
const events = pending ? await waitFor(sessionId, session, accept, Math.min(args.timeoutMs ?? 3e5, 9e5)) : [];
|
|
1772
2640
|
if (events === "user") return toolResult(true, { events: [], userMessage: true, running: running(session), next: USER_WROTE });
|
|
1773
|
-
if (!events) return toolResult(false, { error: "Turn ended" });
|
|
2641
|
+
if (!events) return toolResult(false, session.closed || session.wakeBlocked ? { error: "Turn ended" } : { error: TURN_ENDED, running: running(session) });
|
|
1774
2642
|
return toolResult(true, { events: events.map(publicEvent), running: running(session) });
|
|
1775
2643
|
}
|
|
1776
2644
|
function sendTool(sessionId, session, args) {
|
|
@@ -1800,10 +2668,10 @@ ${refused}`, next: "Fix what it reports, then call alp_handoff again." });
|
|
|
1800
2668
|
}
|
|
1801
2669
|
return toolResult(true, { sent: post(assignment.id, { kind: args.kind, from, assignment: assignment.id, body: args.body, ...args.replyTo ? { replyTo: args.replyTo } : {} }).id });
|
|
1802
2670
|
}
|
|
1803
|
-
function askUser(sessionId, session, assignment, body, options2) {
|
|
2671
|
+
function askUser(sessionId, session, assignment, body, options2, approval, asked = false) {
|
|
1804
2672
|
const rootId = rootOf(sessionId);
|
|
1805
2673
|
const question = {
|
|
1806
|
-
id: `q-${randomUUID().slice(0, 8)}`,
|
|
2674
|
+
id: approval?.id ?? `q-${randomUUID().slice(0, 8)}`,
|
|
1807
2675
|
sessionId,
|
|
1808
2676
|
rootId,
|
|
1809
2677
|
agent: session.mapping.agent.name,
|
|
@@ -1829,7 +2697,7 @@ The user answered: "${answer}"`);
|
|
|
1829
2697
|
next: "Decide, and record the assumption in your handoff or final message; or report that you are blocked."
|
|
1830
2698
|
})));
|
|
1831
2699
|
};
|
|
1832
|
-
userQuestions.set(question.id, { question, settle });
|
|
2700
|
+
userQuestions.set(question.id, { question, settle, persistent: !!approval, asked });
|
|
1833
2701
|
if (assignment) assignment.ask = { id: question.id, resolve: (result) => settle("canceled", void 0, void 0, result) };
|
|
1834
2702
|
emit(sessionId, { type: "question", question });
|
|
1835
2703
|
runLog(rootId, { event: "human.question", questionId: question.id, sessionId, agent: question.agent, body, ...options2?.length ? { options: options2 } : {} });
|
|
@@ -1842,11 +2710,182 @@ The user answered: "${answer}"`);
|
|
|
1842
2710
|
if (!session.parent || !sessions.has(session.parent)) return;
|
|
1843
2711
|
post(session.parent, { kind: "note", from: session.mapping.agent.name, assignment: sessionId, body: `[ALP, on behalf of ${session.mapping.agent.name}] ${body}` });
|
|
1844
2712
|
}
|
|
1845
|
-
function cancelQuestions(sessionId) {
|
|
1846
|
-
for (const { question, settle } of [...userQuestions.values()]) {
|
|
1847
|
-
if (
|
|
2713
|
+
function cancelQuestions(sessionId, turnOnly = false) {
|
|
2714
|
+
for (const { question, settle, persistent, gate } of [...userQuestions.values()]) {
|
|
2715
|
+
if (gate && turnOnly) continue;
|
|
2716
|
+
if (question.sessionId === sessionId && (!turnOnly || !persistent)) settle("canceled", void 0, void 0, toolResult(false, { error: "Turn ended" }));
|
|
1848
2717
|
}
|
|
1849
2718
|
}
|
|
2719
|
+
const gateSyncs = /* @__PURE__ */ new Map();
|
|
2720
|
+
const gateMail = /* @__PURE__ */ new WeakMap();
|
|
2721
|
+
const gateTaken = /* @__PURE__ */ new Set();
|
|
2722
|
+
const gateMarks = /* @__PURE__ */ new Set();
|
|
2723
|
+
const gateCardId = (taskId, gateId) => `gate-${taskId}-${gateId}`;
|
|
2724
|
+
function mainSessionOf(projectRoot) {
|
|
2725
|
+
for (const [id, session] of sessions) {
|
|
2726
|
+
if (session.closed || session.parent || session.role === "supervisor" || !session.threadId) continue;
|
|
2727
|
+
if (session.mapping.agent.name !== mainOf(session.mapping) || path.resolve(session.mapping.agent.projectRoot) !== projectRoot) continue;
|
|
2728
|
+
return { id, session };
|
|
2729
|
+
}
|
|
2730
|
+
return void 0;
|
|
2731
|
+
}
|
|
2732
|
+
function syncGates(projectRoot) {
|
|
2733
|
+
const root = path.resolve(projectRoot);
|
|
2734
|
+
const previous = gateSyncs.get(root) ?? Promise.resolve();
|
|
2735
|
+
const next = previous.then(() => syncGatesNow(root)).catch((error) => {
|
|
2736
|
+
runLog(mainSessionOf(root)?.id ?? root, { event: "gate.sync.failed", projectRoot: root, error: errorData(error).message });
|
|
2737
|
+
});
|
|
2738
|
+
gateSyncs.set(root, next);
|
|
2739
|
+
void next.finally(() => {
|
|
2740
|
+
if (gateSyncs.get(root) === next) gateSyncs.delete(root);
|
|
2741
|
+
});
|
|
2742
|
+
return next;
|
|
2743
|
+
}
|
|
2744
|
+
async function syncGatesNow(projectRoot) {
|
|
2745
|
+
if (closed) return;
|
|
2746
|
+
const { tasks } = await loadTasks(projectRoot);
|
|
2747
|
+
const main = mainSessionOf(projectRoot);
|
|
2748
|
+
if (main) for (const { task, gate, decision, record: record2 } of gateDecisions(tasks)) {
|
|
2749
|
+
const key = JSON.stringify([projectRoot, task.id, gate.id, decision, record2.at]);
|
|
2750
|
+
if (gateTaken.has(key) || main.session.mail.some((event) => gateMail.get(event)?.key === key)) continue;
|
|
2751
|
+
const choice = decision === "approved" ? record2.choice : void 0;
|
|
2752
|
+
const words2 = decision === "approved" ? `The user approved human gate ${gate.id} of ${task.id} in ${record2.channel}${choice ? `, choosing "${choice}"` : ""}${record2.note ? `: ${record2.note}` : ""}.` : `The user rejected human gate ${gate.id} of ${task.id} in ${record2.channel}${record2.reason ? `: ${record2.reason}` : ""}. The gate stays open.`;
|
|
2753
|
+
const mail = post(main.id, { kind: "result", from: "ALP", assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words2} 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.` });
|
|
2754
|
+
gateMail.set(mail, {
|
|
2755
|
+
key,
|
|
2756
|
+
taken: () => {
|
|
2757
|
+
gateTaken.add(key);
|
|
2758
|
+
const mark = markGateNotified(projectRoot, task.id, gate.id, decision, record2.at).catch((error) => {
|
|
2759
|
+
gateTaken.delete(key);
|
|
2760
|
+
runLog(main.id, { event: "gate.mark.failed", projectRoot, taskId: task.id, gateId: gate.id, error: errorData(error).message });
|
|
2761
|
+
});
|
|
2762
|
+
gateMarks.add(mark);
|
|
2763
|
+
void mark.finally(() => gateMarks.delete(mark));
|
|
2764
|
+
}
|
|
2765
|
+
});
|
|
2766
|
+
runLog(main.id, { event: "gate.decision", projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record2.channel, ...choice ? { choice } : {} });
|
|
2767
|
+
}
|
|
2768
|
+
const wanted = /* @__PURE__ */ new Map();
|
|
2769
|
+
for (const task of tasks) {
|
|
2770
|
+
if (task.status === "closed") continue;
|
|
2771
|
+
for (const gate of task.gates ?? []) if (gate.kind === "human" && !gate.resolved && !gate.rejected) wanted.set(gateCardId(task.id, gate.id), { task, gate });
|
|
2772
|
+
}
|
|
2773
|
+
for (const [id, pending] of [...userQuestions]) {
|
|
2774
|
+
if (pending.question.gate?.projectRoot !== projectRoot) continue;
|
|
2775
|
+
const want = wanted.get(id);
|
|
2776
|
+
if (!want || !main || pending.question.sessionId !== main.id) {
|
|
2777
|
+
const task = tasks.find((entry) => entry.id === pending.question.gate.taskId);
|
|
2778
|
+
const gate = task?.gates.find((entry) => entry.id === pending.question.gate.gateId);
|
|
2779
|
+
pending.settle(gate?.resolved ? "answered" : gate?.rejected ? "dismissed" : "canceled", gate?.resolved?.choice, gate?.rejected?.reason);
|
|
2780
|
+
} else if (pending.gate) pending.gate.rev = want.task.rev;
|
|
2781
|
+
}
|
|
2782
|
+
if (!main) return;
|
|
2783
|
+
for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
|
|
2784
|
+
}
|
|
2785
|
+
let gateWatch;
|
|
2786
|
+
const gateFiles = /* @__PURE__ */ new Map();
|
|
2787
|
+
function startGateWatch(projectRoot) {
|
|
2788
|
+
if (options.gateSyncMs === 0) return;
|
|
2789
|
+
watchGateFiles(path.resolve(projectRoot));
|
|
2790
|
+
if (gateWatch) return;
|
|
2791
|
+
gateWatch = setInterval(() => {
|
|
2792
|
+
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)));
|
|
2793
|
+
for (const root of roots) {
|
|
2794
|
+
watchGateFiles(root);
|
|
2795
|
+
void syncGates(root);
|
|
2796
|
+
}
|
|
2797
|
+
for (const root of gateFiles.keys()) if (!roots.has(root)) unwatchGateFiles(root);
|
|
2798
|
+
if (!roots.size) {
|
|
2799
|
+
clearInterval(gateWatch);
|
|
2800
|
+
gateWatch = void 0;
|
|
2801
|
+
}
|
|
2802
|
+
}, options.gateSyncMs ?? 5e3);
|
|
2803
|
+
gateWatch.unref?.();
|
|
2804
|
+
}
|
|
2805
|
+
function watchGateFiles(root) {
|
|
2806
|
+
if (closed || gateFiles.has(root)) return;
|
|
2807
|
+
try {
|
|
2808
|
+
const entry = {
|
|
2809
|
+
// A burst of writes (a save, its ledger, a mark) syncs once.
|
|
2810
|
+
watcher: watchFiles(path.join(root, TASKS_DIR), () => {
|
|
2811
|
+
if (entry.timer || closed) return;
|
|
2812
|
+
entry.timer = setTimeout(() => {
|
|
2813
|
+
entry.timer = void 0;
|
|
2814
|
+
void syncGates(root);
|
|
2815
|
+
}, 50);
|
|
2816
|
+
entry.timer.unref?.();
|
|
2817
|
+
})
|
|
2818
|
+
};
|
|
2819
|
+
entry.watcher.on("error", () => unwatchGateFiles(root));
|
|
2820
|
+
entry.watcher.unref?.();
|
|
2821
|
+
gateFiles.set(root, entry);
|
|
2822
|
+
} catch {
|
|
2823
|
+
}
|
|
2824
|
+
}
|
|
2825
|
+
function unwatchGateFiles(root) {
|
|
2826
|
+
const entry = gateFiles.get(root);
|
|
2827
|
+
if (!entry) return;
|
|
2828
|
+
gateFiles.delete(root);
|
|
2829
|
+
clearTimeout(entry.timer);
|
|
2830
|
+
entry.watcher.close();
|
|
2831
|
+
}
|
|
2832
|
+
function showGateCard(sessionId, session, projectRoot, task, gate) {
|
|
2833
|
+
const say = wordsFor(session);
|
|
2834
|
+
const vietnamese = say.approve === words("vi").approve;
|
|
2835
|
+
const question = {
|
|
2836
|
+
id: gateCardId(task.id, gate.id),
|
|
2837
|
+
sessionId,
|
|
2838
|
+
rootId: rootOf(sessionId),
|
|
2839
|
+
agent: "ALP",
|
|
2840
|
+
body: `${vietnamese ? `C\u1ED5ng ph\xEA duy\u1EC7t ${gate.id} c\u1EE7a ${task.id}` : `Approval gate ${gate.id} of ${task.id}`} (${task.title}):
|
|
2841
|
+
${gate.note ?? ""}`,
|
|
2842
|
+
// Options approve; Reject (added after them unless one of them is that word) keeps the gate open.
|
|
2843
|
+
options: gate.options?.length ? gate.options.includes(say.reject) ? gate.options : [...gate.options, say.reject] : [say.approve, say.reject],
|
|
2844
|
+
askedAt: gate.at ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
2845
|
+
gate: { projectRoot, taskId: task.id, gateId: gate.id }
|
|
2846
|
+
};
|
|
2847
|
+
const card = { rev: task.rev, deciding: false };
|
|
2848
|
+
const settle = (outcome, answer) => {
|
|
2849
|
+
if (userQuestions.get(question.id)?.question !== question) return;
|
|
2850
|
+
userQuestions.delete(question.id);
|
|
2851
|
+
emit(sessionId, { type: "question.resolved", questionId: question.id, outcome, ...answer !== void 0 ? { answer } : {} });
|
|
2852
|
+
};
|
|
2853
|
+
userQuestions.set(question.id, { question, settle, persistent: true, gate: Object.assign(card, { decide: (reply) => decideGate(projectRoot, question, card, reply, gate.options?.length ? gate.options : void 0) }) });
|
|
2854
|
+
emit(sessionId, { type: "question", question });
|
|
2855
|
+
runLog(rootOf(sessionId), { event: "gate.card", questionId: question.id, taskId: task.id, gateId: gate.id });
|
|
2856
|
+
}
|
|
2857
|
+
async function decideGate(projectRoot, question, card, reply, choices) {
|
|
2858
|
+
const defaults = !choices;
|
|
2859
|
+
const { taskId, gateId } = question.gate;
|
|
2860
|
+
if (card.deciding) throw gateRefusal("GATE_BUSY", `An answer to gate ${gateId} of ${taskId} is already being recorded`);
|
|
2861
|
+
card.deciding = true;
|
|
2862
|
+
const channel = reply.channel ?? "web";
|
|
2863
|
+
const text2 = reply.text?.trim();
|
|
2864
|
+
const approve2 = !reply.dismiss && !!text2 && (defaults ? APPROVALS.includes(text2.toLowerCase()) : choices.includes(text2));
|
|
2865
|
+
const rejectReason = reply.dismiss ? reply.reason : text2 && CHOICES_REJECT.includes(text2.toLowerCase()) ? void 0 : text2;
|
|
2866
|
+
const write = (ifRev) => approve2 ? resolveGate(projectRoot, taskId, gateId, { by: "user", ifRev, channel, ...defaults ? {} : { choice: text2 } }) : rejectGate(projectRoot, taskId, gateId, { by: "user", ifRev, channel, ...rejectReason ? { reason: rejectReason.slice(0, 2e3) } : {} });
|
|
2867
|
+
try {
|
|
2868
|
+
try {
|
|
2869
|
+
await write(card.rev);
|
|
2870
|
+
} catch (error) {
|
|
2871
|
+
if (error?.code !== "TASK_CHANGED") throw error;
|
|
2872
|
+
const current = (await loadTasks(projectRoot)).tasks.find((entry) => entry.id === taskId);
|
|
2873
|
+
const gate = current?.gates.find((entry) => entry.id === gateId);
|
|
2874
|
+
if (!current || current.status === "closed" || !gate) throw gateRefusal("GATE_DECIDED", `Gate ${gateId} of ${taskId} is no longer open`);
|
|
2875
|
+
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}` : ""}`);
|
|
2876
|
+
await write(current.rev);
|
|
2877
|
+
}
|
|
2878
|
+
} catch (error) {
|
|
2879
|
+
runLog(question.rootId, { event: "gate.answer.failed", questionId: question.id, error: errorData(error).message });
|
|
2880
|
+
throw error;
|
|
2881
|
+
} finally {
|
|
2882
|
+
card.deciding = false;
|
|
2883
|
+
await syncGates(projectRoot);
|
|
2884
|
+
}
|
|
2885
|
+
}
|
|
2886
|
+
function gateRefusal(code, message) {
|
|
2887
|
+
return Object.assign(new Error(message), { code });
|
|
2888
|
+
}
|
|
1850
2889
|
function askTool(sessionId, session, args) {
|
|
1851
2890
|
const parent = session.parent ? sessions.get(session.parent) : void 0;
|
|
1852
2891
|
const assignment = parent?.assignments.get(sessionId);
|
|
@@ -1858,13 +2897,13 @@ The user answered: "${answer}"`);
|
|
|
1858
2897
|
if (args.options !== void 0 && (to !== "user" || !Array.isArray(args.options) || args.options.length > 10 || !args.options.every((option) => typeof option === "string" && option.trim() && option.length <= 200))) {
|
|
1859
2898
|
return Promise.resolve(toolResult(false, { error: "options are up to 10 short answers, for questions to the user" }));
|
|
1860
2899
|
}
|
|
1861
|
-
if (assignment?.ask || [...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId)) {
|
|
2900
|
+
if (assignment?.ask || [...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId && !pending.gate)) {
|
|
1862
2901
|
return Promise.resolve(toolResult(false, { error: "A question is already waiting for an answer" }));
|
|
1863
2902
|
}
|
|
1864
2903
|
if (to === "user" && session.parent && !session.userOpened) {
|
|
1865
2904
|
return Promise.resolve(toolResult(false, { error: `Only main talks to the user; ask ${session.parentAgent ?? "your requester"} with alp_ask instead` }));
|
|
1866
2905
|
}
|
|
1867
|
-
if (to === "user") return askUser(sessionId, session, assignment, args.question, args.options);
|
|
2906
|
+
if (to === "user") return askUser(sessionId, session, assignment, args.question, args.options, void 0, true);
|
|
1868
2907
|
if (!session.parent || !parent || !assignment) return Promise.resolve(toolResult(false, { error: 'This session has no requester; ask the user with to: "user"' }));
|
|
1869
2908
|
const parentId = session.parent;
|
|
1870
2909
|
return new Promise((resolve) => {
|
|
@@ -1887,6 +2926,22 @@ The user answered: "${answer}"`);
|
|
|
1887
2926
|
});
|
|
1888
2927
|
}
|
|
1889
2928
|
async function runDelegation(sessionId, session, params) {
|
|
2929
|
+
if (workspaceMutation) refuseMutation("workspace_busy", "A workspace mutation is in progress; retry after it finishes");
|
|
2930
|
+
admitting++;
|
|
2931
|
+
let released = false;
|
|
2932
|
+
const release = () => {
|
|
2933
|
+
if (!released) {
|
|
2934
|
+
released = true;
|
|
2935
|
+
admitting--;
|
|
2936
|
+
}
|
|
2937
|
+
};
|
|
2938
|
+
try {
|
|
2939
|
+
return await runDelegationAdmitted(sessionId, session, params, release);
|
|
2940
|
+
} finally {
|
|
2941
|
+
release();
|
|
2942
|
+
}
|
|
2943
|
+
}
|
|
2944
|
+
async function runDelegationAdmitted(sessionId, session, params, admitted) {
|
|
1890
2945
|
const args = params.arguments;
|
|
1891
2946
|
const targets = Object.hasOwn(
|
|
1892
2947
|
session.graph,
|
|
@@ -1906,13 +2961,24 @@ The user answered: "${answer}"`);
|
|
|
1906
2961
|
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` });
|
|
1907
2962
|
const configuredModels = args.agent === "oracle" ? [] : session.mapping.modelProfiles[args.agent] ?? [];
|
|
1908
2963
|
const listed = configuredModels.map(profileModel).filter((id) => Boolean(id));
|
|
2964
|
+
const allowed = listed.map((id) => id.endsWith(":*") ? `any ${id.slice(0, -1)} model` : id).join(" or ");
|
|
1909
2965
|
const choosing = configuredModels.length > 1 || configuredModels.some(anyModel);
|
|
1910
|
-
if (choosing && (args.model === void 0 || args.thinking === void 0)) 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 });
|
|
1911
|
-
if (
|
|
1912
|
-
|
|
1913
|
-
|
|
2966
|
+
if (choosing && (args.model === void 0 || args.thinking === void 0)) 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 });
|
|
2967
|
+
if (args.model !== void 0 && listed.length && !offers(configuredModels, args.model)) {
|
|
2968
|
+
const team = session.mapping.workflow.mode;
|
|
2969
|
+
const settingsFile = path.join(session.mapping.agent.projectRoot, ".alp", "settings.json");
|
|
2970
|
+
const provider = args.model.slice(0, args.model.indexOf(":"));
|
|
2971
|
+
const setup = ["pho", "cafe"].includes(team) && ["claude", "codex"].includes(provider) ? `, or run alp setup ${session.mapping.agent.projectRoot} --runtime mix, which gives Ph\u1EDF's and Cafe's members both Claude and Codex profiles (it keeps profiles written by hand or set in a team.json)` : "";
|
|
2972
|
+
return toolResult(false, {
|
|
2973
|
+
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"}. 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}.`,
|
|
2974
|
+
models: listed
|
|
2975
|
+
});
|
|
2976
|
+
}
|
|
1914
2977
|
const configuredDefault = !choosing && listed.length === 1 ? listed[0] : void 0;
|
|
1915
2978
|
const delegatedModel = args.model ?? configuredDefault ?? `${session.runtimeKind}:${session.mapping.model}`;
|
|
2979
|
+
const efforts = args.thinking !== void 0 && listed.length ? profileEfforts(delegatedModel) : [];
|
|
2980
|
+
if (efforts.length && !efforts.includes(args.thinking)) return toolResult(false, { error: `${delegatedModel} takes effort ${efforts.join(", ")}`, efforts });
|
|
2981
|
+
const thinkingNote = args.thinking !== void 0 && !efforts.length ? 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` : void 0;
|
|
1916
2982
|
const delegatedThinking = args.thinking ?? selectedProfile(configuredModels, delegatedModel)?.effort ?? (args.model || configuredDefault ? void 0 : session.mapping.thinking);
|
|
1917
2983
|
const childRuntime = delegatedModel.split(":")[0];
|
|
1918
2984
|
if (!paused.all && paused.runtimes[childRuntime]?.by === "alpd") await checkLimit(childRuntime, LIMIT_FRESH_MS);
|
|
@@ -1920,19 +2986,20 @@ The user answered: "${answer}"`);
|
|
|
1920
2986
|
if (hold) {
|
|
1921
2987
|
const other = RUNTIMES.find((kind) => kind !== childRuntime && !pauseOf(kind));
|
|
1922
2988
|
const instead = listed.filter((id) => other && id.startsWith(`${other}:`)).map((id) => id.endsWith(":*") ? `any ${id.slice(0, -1)} model` : id);
|
|
1923
|
-
const next = !other ? "Wait until the user resumes ALP" : !
|
|
2989
|
+
const next = !other ? "Wait until the user resumes ALP" : !listed.length ? `Pass a model of ${other}: from the catalog to run it on ${label(other)}, or wait` : 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`;
|
|
1924
2990
|
return toolResult(false, { error: describePause(hold, paused.all ? void 0 : childRuntime), next });
|
|
1925
2991
|
}
|
|
1926
2992
|
let childProfile;
|
|
1927
2993
|
try {
|
|
1928
|
-
childProfile = await profileFor(session.mapping.agent.projectRoot, options.libraryDir, args.agent);
|
|
2994
|
+
childProfile = await profileFor(session.mapping.agent.projectRoot, options.libraryDir, args.agent, { readOnly: readOnlyMember(session.mapping, args.agent) });
|
|
1929
2995
|
} catch (error) {
|
|
1930
2996
|
return toolResult(false, { error: errorData(error).message });
|
|
1931
2997
|
}
|
|
1932
2998
|
const childMode = childProfile ? capMode(args.mode ?? session.mapping.mode, childProfile.base) : args.mode ?? session.mapping.mode;
|
|
1933
2999
|
const capped = {
|
|
1934
3000
|
...childProfile && childMode !== (args.mode ?? session.mapping.mode) ? { mode: childMode, modeNote: `${args.agent} runs ${childMode}: its permission profile ${childProfile.name} caps it` } : {},
|
|
1935
|
-
...childProfile?.workdir === "copy" && isolationOf(args) === "shared" ? { workdirNote: `${args.agent} works in a disposable copy of your tree; nothing it changes reaches yours` } : {}
|
|
3001
|
+
...childProfile?.workdir === "copy" && isolationOf(args) === "shared" ? { workdirNote: `${args.agent} works in a disposable copy of your tree; nothing it changes reaches yours` } : {},
|
|
3002
|
+
...thinkingNote ? { thinkingNote } : {}
|
|
1936
3003
|
};
|
|
1937
3004
|
let sharedContinuation;
|
|
1938
3005
|
if (args.continueFrom !== void 0) {
|
|
@@ -1972,7 +3039,7 @@ The user answered: "${answer}"`);
|
|
|
1972
3039
|
let task;
|
|
1973
3040
|
if (args.taskId !== void 0) {
|
|
1974
3041
|
if (session.parent || session.mapping.agent.name !== mainOf(session.mapping)) return toolResult(false, { error: "Only main gives tasks to assignments" });
|
|
1975
|
-
if (
|
|
3042
|
+
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" });
|
|
1976
3043
|
if (typeof args.taskId !== "string") return toolResult(false, { error: "taskId must be a task id" });
|
|
1977
3044
|
try {
|
|
1978
3045
|
const { tasks } = await loadTasks(project);
|
|
@@ -2011,9 +3078,11 @@ The user answered: "${answer}"`);
|
|
|
2011
3078
|
}
|
|
2012
3079
|
const rootId = rootOf(sessionId);
|
|
2013
3080
|
const root = sessions.get(rootId);
|
|
2014
|
-
|
|
3081
|
+
const advisor = ["advisor", "reviewer"].includes(roleOf(session.mapping, args.agent) ?? "") && childMode === "read-only";
|
|
3082
|
+
const budget = advisor ? "advisorCalls" : "calls";
|
|
3083
|
+
if (root[budget] >= 16) {
|
|
2015
3084
|
return toolResult(false, {
|
|
2016
|
-
error: "
|
|
3085
|
+
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.`
|
|
2017
3086
|
});
|
|
2018
3087
|
}
|
|
2019
3088
|
const peer = roleOf(session.mapping, args.agent) === "peer";
|
|
@@ -2026,7 +3095,7 @@ The user answered: "${answer}"`);
|
|
|
2026
3095
|
const continued = args.continueFrom !== void 0 ? session.worktrees.get(args.continueFrom) : void 0;
|
|
2027
3096
|
if (args.continueFrom !== void 0 && !continued && !sharedContinuation) return toolResult(false, { error: `${args.continueFrom} was merged or discarded meanwhile` });
|
|
2028
3097
|
if (continued) session.worktrees.delete(args.continueFrom);
|
|
2029
|
-
root
|
|
3098
|
+
root[budget]++;
|
|
2030
3099
|
if (peer) root.peerCount++;
|
|
2031
3100
|
const childId = `alp-child-${randomUUID()}`;
|
|
2032
3101
|
const startedAt = Date.now();
|
|
@@ -2067,6 +3136,7 @@ The user answered: "${answer}"`);
|
|
|
2067
3136
|
...task ? { taskId: task.id } : {}
|
|
2068
3137
|
});
|
|
2069
3138
|
try {
|
|
3139
|
+
if (writes(childMode)) await assignmentResults.put({ assignmentId: childId, checkout });
|
|
2070
3140
|
if (task) {
|
|
2071
3141
|
const started = await startTask(project, task.id, { agent: args.agent, assignment: childId, pid: process.pid, pidStartedAt: OWN_START, epoch }, session.mapping.agent.name);
|
|
2072
3142
|
assignment.taskId = started.id;
|
|
@@ -2081,8 +3151,11 @@ The user answered: "${answer}"`);
|
|
|
2081
3151
|
if (continued) session.worktrees.set(args.continueFrom, continued);
|
|
2082
3152
|
throw error;
|
|
2083
3153
|
}
|
|
2084
|
-
|
|
2085
|
-
|
|
3154
|
+
await assignmentResults.put({ assignmentId: childId, checkout: assignment.worktree.checkout, worktree: assignment.worktree.path });
|
|
3155
|
+
if (continued) {
|
|
3156
|
+
await removeWorktree(continued.worktree, { deleteBranch: true });
|
|
3157
|
+
await assignmentResults.remove(args.continueFrom);
|
|
3158
|
+
}
|
|
2086
3159
|
runLog(rootId, { event: "worktree.created", assignmentId: childId, branch: assignment.worktree.branch, base: assignment.worktree.base, ...continued ? { continuedFrom: args.continueFrom } : {} });
|
|
2087
3160
|
} else if (sharedWriter) {
|
|
2088
3161
|
assignment.fingerprint = await checkoutFingerprint(checkout).catch(() => void 0);
|
|
@@ -2106,8 +3179,10 @@ The user answered: "${answer}"`);
|
|
|
2106
3179
|
thinking,
|
|
2107
3180
|
mode: childMode
|
|
2108
3181
|
};
|
|
2109
|
-
await openSession(childId, childSpec, "skip", session.delegation);
|
|
2110
|
-
|
|
3182
|
+
await openSession(childId, childSpec, "skip", session.delegation, assignment);
|
|
3183
|
+
admitted();
|
|
3184
|
+
const child = assignmentSessions.get(assignment);
|
|
3185
|
+
if (child && sessions.get(childId) !== child) throw new Error("Child session was replaced during open");
|
|
2111
3186
|
if (child) void runHooks(childId, child, "assignment.start", { assignment: childId, brief: clip(args.task, 2e3) }, args.taskId);
|
|
2112
3187
|
if (!child || session.closed || session.active !== params.turnId) {
|
|
2113
3188
|
throw new Error(
|
|
@@ -2171,6 +3246,11 @@ ${digest}` : "")
|
|
|
2171
3246
|
}
|
|
2172
3247
|
]
|
|
2173
3248
|
}, "assignment");
|
|
3249
|
+
child.awaitingBrief = false;
|
|
3250
|
+
if (child.wakeHeld) {
|
|
3251
|
+
child.wakeHeld = false;
|
|
3252
|
+
deliver(childId, child);
|
|
3253
|
+
}
|
|
2174
3254
|
} catch (error) {
|
|
2175
3255
|
session.mail = session.mail.filter((event2) => event2.deliveredTurn || event2.kind !== "result" || event2.assignment !== childId);
|
|
2176
3256
|
await finishAssignment(sessionId, session, assignment, "failed", error, true);
|
|
@@ -2186,12 +3266,15 @@ ${digest}` : "")
|
|
|
2186
3266
|
const events = await waitFor(sessionId, session, (event2) => event2.assignment === childId && (event2.kind === "result" || event2.kind === "question"), void 0, true);
|
|
2187
3267
|
if (events === "user") return toolResult(true, { assignmentId: childId, agent: args.agent, status: "running", userMessage: true, next: USER_WROTE });
|
|
2188
3268
|
if (!events) {
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
3269
|
+
if (session.closed || session.wakeBlocked || !session.assignments.has(childId)) {
|
|
3270
|
+
return toolResult(false, {
|
|
3271
|
+
agent: args.agent,
|
|
3272
|
+
assignmentId: childId,
|
|
3273
|
+
status: "canceled",
|
|
3274
|
+
error: "Parent assignment stopped"
|
|
3275
|
+
});
|
|
3276
|
+
}
|
|
3277
|
+
return toolResult(false, { agent: args.agent, assignmentId: childId, status: "running", error: TURN_ENDED });
|
|
2195
3278
|
}
|
|
2196
3279
|
const event = events.find((candidate) => candidate.kind === "result") ?? events.find((candidate) => candidate.kind === "question");
|
|
2197
3280
|
if (!event) return toolResult(true, { assignmentId: childId, agent: args.agent, status: "running", events: events.map(publicEvent), next: CHECKED_IN });
|
|
@@ -2204,7 +3287,10 @@ ${digest}` : "")
|
|
|
2204
3287
|
next: "Answer with alp_send kind answer, then alp_wait for this assignment."
|
|
2205
3288
|
});
|
|
2206
3289
|
}
|
|
2207
|
-
async function openSession(sessionId, spec, history, delegation = true) {
|
|
3290
|
+
async function openSession(sessionId, spec, history, delegation = true, assignment) {
|
|
3291
|
+
return admission(() => openSessionAdmitted(sessionId, spec, history, delegation, assignment));
|
|
3292
|
+
}
|
|
3293
|
+
async function openSessionAdmitted(sessionId, spec, history, delegation = true, assignment) {
|
|
2208
3294
|
if (sessions.has(sessionId)) {
|
|
2209
3295
|
throw new Error(
|
|
2210
3296
|
"Session is already open"
|
|
@@ -2251,21 +3337,32 @@ ${digest}` : "")
|
|
|
2251
3337
|
toolCallId: context?.callId,
|
|
2252
3338
|
parentAgent: context ? sessions.get(context.parent)?.mapping.agent.name : void 0,
|
|
2253
3339
|
...context?.role ? { role: context.role } : {},
|
|
3340
|
+
// A new assignment's first turn is its brief; mail that comes sooner waits for it.
|
|
3341
|
+
...context && !context.role && !context.recovered ? { awaitingBrief: true } : {},
|
|
2254
3342
|
journal: [],
|
|
2255
3343
|
tasks: [],
|
|
2256
3344
|
children: /* @__PURE__ */ new Set(),
|
|
2257
3345
|
peerCount: 0,
|
|
2258
3346
|
assignments: /* @__PURE__ */ new Map(),
|
|
2259
3347
|
calls: 0,
|
|
3348
|
+
advisorCalls: 0,
|
|
2260
3349
|
mail: [],
|
|
2261
3350
|
waiters: [],
|
|
2262
3351
|
lastActivity: Date.now(),
|
|
2263
3352
|
wakes: 0,
|
|
3353
|
+
wakeFailures: 0,
|
|
2264
3354
|
wakeBlocked: false,
|
|
2265
3355
|
toolCalls: /* @__PURE__ */ new Map(),
|
|
2266
3356
|
acknowledged: Promise.resolve(),
|
|
2267
3357
|
worktrees: /* @__PURE__ */ new Map()
|
|
2268
3358
|
};
|
|
3359
|
+
if (assignment) assignmentSessions.set(assignment, session);
|
|
3360
|
+
const finishPending = beginPending(session);
|
|
3361
|
+
const opening = {};
|
|
3362
|
+
openings.set(session, opening);
|
|
3363
|
+
const failedMeanwhile = () => {
|
|
3364
|
+
if (opening.failure !== void 0) throw opening.failure;
|
|
3365
|
+
};
|
|
2269
3366
|
sessions.set(
|
|
2270
3367
|
sessionId,
|
|
2271
3368
|
session
|
|
@@ -2273,7 +3370,8 @@ ${digest}` : "")
|
|
|
2273
3370
|
wire(sessionId, session, runtime);
|
|
2274
3371
|
try {
|
|
2275
3372
|
await runtime.initialize();
|
|
2276
|
-
|
|
3373
|
+
failedMeanwhile();
|
|
3374
|
+
if (session.closed || sessions.get(sessionId) !== session) {
|
|
2277
3375
|
throw new Error(
|
|
2278
3376
|
"Session closed during initialization"
|
|
2279
3377
|
);
|
|
@@ -2290,11 +3388,15 @@ ${digest}` : "")
|
|
|
2290
3388
|
}
|
|
2291
3389
|
const nativeConfig = await configOf(session);
|
|
2292
3390
|
noteInstructions(sessionId, session, nativeConfig.developerInstructions);
|
|
3391
|
+
const base = mapping.threadId ? spec.restore?.base : void 0;
|
|
3392
|
+
if (base && runtimeKind !== "claude") throw new Error(`A ${label(runtimeKind)} session has no base conversation; only Claude makes a fork on its first prompt`);
|
|
3393
|
+
if (base) session.base = base;
|
|
2293
3394
|
const result = mapping.threadId ? await runtime.request(
|
|
2294
3395
|
"thread/resume",
|
|
2295
3396
|
{
|
|
2296
3397
|
...nativeConfig,
|
|
2297
|
-
threadId: mapping.threadId
|
|
3398
|
+
threadId: mapping.threadId,
|
|
3399
|
+
...base ? { base } : {}
|
|
2298
3400
|
}
|
|
2299
3401
|
) : await runtime.request(
|
|
2300
3402
|
"thread/start",
|
|
@@ -2304,13 +3406,16 @@ ${digest}` : "")
|
|
|
2304
3406
|
}
|
|
2305
3407
|
);
|
|
2306
3408
|
session.threadId = result.thread.id;
|
|
2307
|
-
|
|
3409
|
+
failedMeanwhile();
|
|
3410
|
+
if (session.closed || sessions.get(sessionId) !== session) {
|
|
2308
3411
|
throw new Error(
|
|
2309
3412
|
"Session closed during thread creation"
|
|
2310
3413
|
);
|
|
2311
3414
|
}
|
|
2312
|
-
session
|
|
3415
|
+
openings.delete(session);
|
|
2313
3416
|
session.buffered = [];
|
|
3417
|
+
finishPending();
|
|
3418
|
+
openedSessions.add(session);
|
|
2314
3419
|
emit(sessionId, {
|
|
2315
3420
|
type: "session.opened",
|
|
2316
3421
|
session: snapshot(sessionId, session),
|
|
@@ -2320,13 +3425,19 @@ ${digest}` : "")
|
|
|
2320
3425
|
thinking: result.reasoningEffort ?? mapping.thinking
|
|
2321
3426
|
}
|
|
2322
3427
|
});
|
|
3428
|
+
if (!session.parent && session.role !== "supervisor" && mapping.agent.name === mainOf(mapping)) {
|
|
3429
|
+
void syncGates(mapping.agent.projectRoot);
|
|
3430
|
+
startGateWatch(mapping.agent.projectRoot);
|
|
3431
|
+
}
|
|
2323
3432
|
if (history === "replay") {
|
|
2324
3433
|
for (const turn of result.thread.turns ?? []) {
|
|
2325
3434
|
for (const item of turn.items ?? []) {
|
|
2326
3435
|
nativeItem(
|
|
2327
3436
|
sessionId,
|
|
2328
3437
|
session,
|
|
2329
|
-
item
|
|
3438
|
+
item,
|
|
3439
|
+
false,
|
|
3440
|
+
turn.id
|
|
2330
3441
|
);
|
|
2331
3442
|
}
|
|
2332
3443
|
}
|
|
@@ -2336,11 +3447,12 @@ ${digest}` : "")
|
|
|
2336
3447
|
return snapshot(sessionId, session);
|
|
2337
3448
|
} catch (error) {
|
|
2338
3449
|
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 });
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
);
|
|
2343
|
-
|
|
3450
|
+
const failed = openings.get(session);
|
|
3451
|
+
openings.delete(session);
|
|
3452
|
+
if (failed?.failure !== void 0) failSession(sessionId, session, failed.failure);
|
|
3453
|
+
const cleanup = closeSession(sessionId, session, false);
|
|
3454
|
+
finishPending();
|
|
3455
|
+
await cleanup;
|
|
2344
3456
|
throw error;
|
|
2345
3457
|
}
|
|
2346
3458
|
}
|
|
@@ -2360,16 +3472,22 @@ ${digest}` : "")
|
|
|
2360
3472
|
}
|
|
2361
3473
|
});
|
|
2362
3474
|
transport.onFailure((error) => {
|
|
2363
|
-
if (session.closed || session.runtime !== transport) return;
|
|
3475
|
+
if (session.closed || session.runtime !== transport || sessions.get(sessionId) !== session) return;
|
|
3476
|
+
const opening = openings.get(session);
|
|
3477
|
+
if (opening) {
|
|
3478
|
+
opening.failure ??= error;
|
|
3479
|
+
return;
|
|
3480
|
+
}
|
|
2364
3481
|
if (revivable(session)) void revive(sessionId, session, error);
|
|
2365
3482
|
else failSession(sessionId, session, error);
|
|
2366
3483
|
});
|
|
2367
3484
|
}
|
|
2368
3485
|
function failSession(sessionId, session, error) {
|
|
3486
|
+
if (session.closed || sessions.get(sessionId) !== session) return;
|
|
2369
3487
|
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 });
|
|
2370
3488
|
terminal(sessionId, session, "failed", error);
|
|
2371
3489
|
session.settle?.("failed", error);
|
|
2372
|
-
void closeSession(sessionId);
|
|
3490
|
+
void closeSession(sessionId, session);
|
|
2373
3491
|
emit(sessionId, { type: "session.failed", error: errorData(error) });
|
|
2374
3492
|
}
|
|
2375
3493
|
function noteInstructions(sessionId, session, instructions) {
|
|
@@ -2396,7 +3514,7 @@ ${digest}` : "")
|
|
|
2396
3514
|
session.role,
|
|
2397
3515
|
supervises(session),
|
|
2398
3516
|
lessonFiles(mapping),
|
|
2399
|
-
Object.fromEntries(await Promise.all(targets.map(async (target) => [target, await profileFor(mapping.agent.projectRoot, options.libraryDir, target).catch(() => null)])))
|
|
3517
|
+
Object.fromEntries(await Promise.all(targets.map(async (target) => [target, await profileFor(mapping.agent.projectRoot, options.libraryDir, target, { readOnly: readOnlyMember(mapping, target) }).catch(() => null)])))
|
|
2400
3518
|
);
|
|
2401
3519
|
if (session.spec.writeRoot && session.runtimeKind === "claude" && mapping.mode === "workspace-write" && claudeSandboxAvailable()) Object.assign(config, { floor: "workspace-write" });
|
|
2402
3520
|
if (session.spec.writeRoot) config.developerInstructions += `
|
|
@@ -2419,40 +3537,415 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2419
3537
|
const harness = label(session.runtimeKind);
|
|
2420
3538
|
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 });
|
|
2421
3539
|
runLog(rootOf(sessionId), { event: "session.restarted", sessionId, agent: session.mapping.agent.name, error: errorData(error).message, restarts: session.restarts.length });
|
|
3540
|
+
let interrupted;
|
|
2422
3541
|
if (session.active) {
|
|
2423
3542
|
session.parkReason = `its ${harness} process stopped`;
|
|
3543
|
+
session.parkPause = void 0;
|
|
2424
3544
|
session.parkThen = `ALP is restarting the ${harness} process; this assignment continues by itself.`;
|
|
2425
3545
|
terminal(sessionId, session, "failed", error);
|
|
3546
|
+
interrupted = session.parked;
|
|
2426
3547
|
}
|
|
2427
3548
|
const old = session.runtime;
|
|
2428
3549
|
void old.close().catch(() => {
|
|
2429
3550
|
});
|
|
3551
|
+
let finishPending = () => {
|
|
3552
|
+
};
|
|
2430
3553
|
try {
|
|
2431
3554
|
const transport = createTransport(options, session.runtimeKind, session.mapping.workdir, nativeEnvironment(options, session.mapping.env), session.mapping.acp, session.mapping.antigravity);
|
|
2432
3555
|
session.runtime = transport;
|
|
2433
|
-
|
|
3556
|
+
finishPending = beginPending(session);
|
|
2434
3557
|
wire(sessionId, session, transport);
|
|
2435
3558
|
await transport.initialize();
|
|
2436
3559
|
const config = await configOf(session);
|
|
2437
|
-
if (session.closed)
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
}
|
|
2442
|
-
session.
|
|
3560
|
+
if (session.closed) {
|
|
3561
|
+
finishPending();
|
|
3562
|
+
return void transport.close().catch(() => {
|
|
3563
|
+
});
|
|
3564
|
+
}
|
|
3565
|
+
await transport.request("thread/resume", { ...config, threadId: session.threadId, ...session.base ? { base: session.base } : {} });
|
|
3566
|
+
if (session.closed) {
|
|
3567
|
+
finishPending();
|
|
3568
|
+
return void transport.close().catch(() => {
|
|
3569
|
+
});
|
|
3570
|
+
}
|
|
2443
3571
|
session.buffered = [];
|
|
3572
|
+
finishPending();
|
|
2444
3573
|
runLog(rootOf(sessionId), { event: "session.revived", sessionId, agent: session.mapping.agent.name });
|
|
2445
|
-
if (session.parked &&
|
|
3574
|
+
if (session.parked && session.parked === interrupted) {
|
|
2446
3575
|
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." : ""}`;
|
|
2447
3576
|
continueParked(sessionId, session);
|
|
2448
3577
|
}
|
|
2449
3578
|
} catch (failure) {
|
|
2450
|
-
|
|
3579
|
+
finishPending();
|
|
2451
3580
|
session.parked = void 0;
|
|
2452
3581
|
runLog(rootOf(sessionId), { event: "session.revive_failed", sessionId, agent: session.mapping.agent.name, error: errorData(failure).message });
|
|
2453
3582
|
failSession(sessionId, session, error);
|
|
2454
3583
|
}
|
|
2455
3584
|
}
|
|
3585
|
+
function restartRefusal(sessionId, session) {
|
|
3586
|
+
if (!session || session.closed) return "The session is not open";
|
|
3587
|
+
if (session.parent || session.role === "supervisor") return "Only a root session can be restarted";
|
|
3588
|
+
if (session.pending) return "The session is still opening or restarting";
|
|
3589
|
+
if (session.active) return "A turn is running";
|
|
3590
|
+
if (session.children.size || session.assignments.size) return "Assignments are still running";
|
|
3591
|
+
if ([...userQuestions.values()].some((pending) => pending.question.rootId === sessionId && !pending.gate)) return "A question to the user waits for an answer";
|
|
3592
|
+
if ((hasActiveMail(session) || session.wakeHeld) && !session.lifecycleHolds) return MAIL_WAITS;
|
|
3593
|
+
if (session.parked || session.parkReason) return "The session is parked";
|
|
3594
|
+
if (reviewing(session)) return REVIEWING;
|
|
3595
|
+
return void 0;
|
|
3596
|
+
}
|
|
3597
|
+
async function restartNative(sessionId, session, binding, verify = true, shape) {
|
|
3598
|
+
const old = session.runtime;
|
|
3599
|
+
const finishPending = beginPending(session);
|
|
3600
|
+
await old.close().catch(() => {
|
|
3601
|
+
});
|
|
3602
|
+
const transport = createTransport(options, session.runtimeKind, session.mapping.workdir, nativeEnvironment(options, session.mapping.env), session.mapping.acp, session.mapping.antigravity);
|
|
3603
|
+
let failure;
|
|
3604
|
+
transport.onFailure((error) => {
|
|
3605
|
+
failure ??= error;
|
|
3606
|
+
});
|
|
3607
|
+
session.runtime = transport;
|
|
3608
|
+
let result;
|
|
3609
|
+
try {
|
|
3610
|
+
await transport.initialize();
|
|
3611
|
+
const config = await configOf(shape ? { ...session, ...shape } : session);
|
|
3612
|
+
noteInstructions(sessionId, session, config.developerInstructions);
|
|
3613
|
+
if (session.closed) throw new Error("Session closed during restart");
|
|
3614
|
+
result = binding ? await transport.request("thread/resume", {
|
|
3615
|
+
...config,
|
|
3616
|
+
threadId: binding.threadId,
|
|
3617
|
+
...binding.base ? { base: binding.base } : verify && session.runtimeKind === "claude" ? { requireHistory: true } : {}
|
|
3618
|
+
}) : await transport.request("thread/start", { ...config, ephemeral: !(shape ?? session).mapping.persist && !(shape ?? session).mapping.keepThread });
|
|
3619
|
+
if (failure) throw failure;
|
|
3620
|
+
if (session.closed) throw new Error("Session closed during restart");
|
|
3621
|
+
if (binding && result?.thread?.id !== void 0 && result.thread.id !== binding.threadId) throw new Error(`${label(session.runtimeKind)} resumed ${result.thread.id} instead of ${binding.threadId}`);
|
|
3622
|
+
if (!binding && typeof result?.thread?.id !== "string") throw new Error(`${label(session.runtimeKind)} started no conversation`);
|
|
3623
|
+
} catch (error) {
|
|
3624
|
+
await transport.close().catch(() => {
|
|
3625
|
+
});
|
|
3626
|
+
finishPending();
|
|
3627
|
+
throw error;
|
|
3628
|
+
}
|
|
3629
|
+
session.threadId = binding ? binding.threadId : result.thread.id;
|
|
3630
|
+
if (binding?.base) session.base = binding.base;
|
|
3631
|
+
else delete session.base;
|
|
3632
|
+
session.buffered = [];
|
|
3633
|
+
wire(sessionId, session, transport);
|
|
3634
|
+
finishPending();
|
|
3635
|
+
return result;
|
|
3636
|
+
}
|
|
3637
|
+
async function rebindSession(sessionId, binding) {
|
|
3638
|
+
const session = sessions.get(sessionId);
|
|
3639
|
+
const refusal = restartRefusal(sessionId, session);
|
|
3640
|
+
if (refusal) throw new ConversationError("session_busy", refusal);
|
|
3641
|
+
if (!plainObject(binding, ["threadId", "base"]) || typeof binding.threadId !== "string" || !binding.threadId || binding.base !== void 0 && (!plainObject(binding.base, ["threadId", "at"]) || typeof binding.base.threadId !== "string" || !binding.base.threadId || binding.base.at !== void 0 && typeof binding.base.at !== "string")) {
|
|
3642
|
+
throw new Error("A binding needs a threadId, and a base only with a threadId and an optional at");
|
|
3643
|
+
}
|
|
3644
|
+
if (binding.base && session.runtimeKind !== "claude") throw new ConversationError("runtime_unsupported", `A ${label(session.runtimeKind)} session has no base conversation`);
|
|
3645
|
+
const live2 = session;
|
|
3646
|
+
const previous = { threadId: live2.threadId, ...live2.base ? { base: live2.base } : {} };
|
|
3647
|
+
try {
|
|
3648
|
+
await restartNative(sessionId, live2, binding);
|
|
3649
|
+
} catch (error) {
|
|
3650
|
+
runLog(rootOf(sessionId), { event: "session.rebind_failed", sessionId, agent: live2.mapping.agent.name, threadId: binding.threadId, error: errorData(error).message });
|
|
3651
|
+
try {
|
|
3652
|
+
if (live2.closed) throw error;
|
|
3653
|
+
await restartNative(sessionId, live2, previous, false);
|
|
3654
|
+
} catch (reopen) {
|
|
3655
|
+
live2.pending = false;
|
|
3656
|
+
if (!live2.closed) failSession(sessionId, live2, reopen);
|
|
3657
|
+
}
|
|
3658
|
+
if (error instanceof ConversationError) throw error;
|
|
3659
|
+
throw new ConversationError("native_refused", `The conversation could not be opened: ${errorData(error).message}`, { outcomeUnknown: !!error?.outcomeUnknown });
|
|
3660
|
+
}
|
|
3661
|
+
runLog(rootOf(sessionId), { event: "session.rebound", sessionId, agent: live2.mapping.agent.name, from: previous.threadId, threadId: binding.threadId });
|
|
3662
|
+
const updated = snapshot(sessionId, live2);
|
|
3663
|
+
emit(sessionId, { type: "session.updated", session: updated });
|
|
3664
|
+
return updated;
|
|
3665
|
+
}
|
|
3666
|
+
async function reloadSession(sessionId) {
|
|
3667
|
+
const session = sessions.get(sessionId);
|
|
3668
|
+
const refusal = restartRefusal(sessionId, session);
|
|
3669
|
+
if (refusal) throw new ConversationError("session_busy", refusal);
|
|
3670
|
+
const live2 = session;
|
|
3671
|
+
if (!live2.threadId) throw new ConversationError("runtime_unsupported", "This session keeps no native conversation to reload");
|
|
3672
|
+
const binding = { threadId: live2.threadId, ...live2.base ? { base: live2.base } : {} };
|
|
3673
|
+
try {
|
|
3674
|
+
await restartNative(sessionId, live2, binding);
|
|
3675
|
+
} catch (error) {
|
|
3676
|
+
runLog(rootOf(sessionId), { event: "session.reload_failed", sessionId, agent: live2.mapping.agent.name, threadId: binding.threadId, error: errorData(error).message });
|
|
3677
|
+
if (!live2.closed) await closeSession(sessionId).catch(() => {
|
|
3678
|
+
});
|
|
3679
|
+
throw new ConversationError("native_refused", `The agent could not be restarted on its conversation: ${errorData(error).message}`);
|
|
3680
|
+
}
|
|
3681
|
+
runLog(rootOf(sessionId), { event: "session.reloaded", sessionId, agent: live2.mapping.agent.name, threadId: binding.threadId });
|
|
3682
|
+
const updated = snapshot(sessionId, live2);
|
|
3683
|
+
emit(sessionId, { type: "session.updated", session: updated });
|
|
3684
|
+
return updated;
|
|
3685
|
+
}
|
|
3686
|
+
async function effectiveConfig(session, shape) {
|
|
3687
|
+
const view = shape ? { ...session, ...shape } : session;
|
|
3688
|
+
const config = await configOf(view);
|
|
3689
|
+
const name = view.mapping.agent.name;
|
|
3690
|
+
return effectiveOf(session.runtimeKind, view.mapping, {
|
|
3691
|
+
delegates: Object.hasOwn(view.graph, name) ? view.graph[name] : [],
|
|
3692
|
+
tools: (config.dynamicTools ?? []).map((tool) => tool.name).filter((tool) => typeof tool === "string"),
|
|
3693
|
+
supervisor: supervises(view),
|
|
3694
|
+
instructionsSha: createHash("sha256").update(config.developerInstructions).digest("hex").slice(0, 12)
|
|
3695
|
+
});
|
|
3696
|
+
}
|
|
3697
|
+
async function planConfigure(session, changes) {
|
|
3698
|
+
const current = await effectiveConfig(session);
|
|
3699
|
+
const same = { shape: { mapping: session.mapping, graph: session.graph, spec: session.spec }, current, proposed: current, changes: [] };
|
|
3700
|
+
const refuse = (reason, message) => ({ ...same, refusal: { reason, message } });
|
|
3701
|
+
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");
|
|
3702
|
+
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`);
|
|
3703
|
+
for (const key of ["model", "thinking", "team", "mode"]) {
|
|
3704
|
+
const value = changes[key];
|
|
3705
|
+
if (value !== void 0 && (typeof value !== "string" || !value.trim() || value.length > 200)) return refuse("invalid_params", `${key} must be a nonempty name of at most 200 characters`);
|
|
3706
|
+
}
|
|
3707
|
+
const runtimeKind = session.runtimeKind;
|
|
3708
|
+
let model = session.mapping.model;
|
|
3709
|
+
if (changes.model !== void 0) {
|
|
3710
|
+
const named = nativeModelOf(runtimeKind, changes.model.trim());
|
|
3711
|
+
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`);
|
|
3712
|
+
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`);
|
|
3713
|
+
model = named.model;
|
|
3714
|
+
}
|
|
3715
|
+
const projectRoot = session.mapping.agent.projectRoot;
|
|
3716
|
+
let team = session.mapping.workflow.mode;
|
|
3717
|
+
if (changes.team !== void 0) {
|
|
3718
|
+
const wanted = teamOf(changes.team.trim());
|
|
3719
|
+
const teams = await listTeams(projectRoot, { library: options.libraryDir, templates: options.templates });
|
|
3720
|
+
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`);
|
|
3721
|
+
team = wanted;
|
|
3722
|
+
}
|
|
3723
|
+
const teamChanged = team !== session.mapping.workflow.mode;
|
|
3724
|
+
const mode = changes.mode ?? session.mapping.mode;
|
|
3725
|
+
if (!modes.some((candidate) => candidate.id === mode)) return refuse("invalid_params", `Unsupported mode '${mode}'`);
|
|
3726
|
+
const takes = (effort) => {
|
|
3727
|
+
const efforts = thinkingOptionsFor(runtimeKind, model);
|
|
3728
|
+
return !efforts.length || efforts.some((option) => option.id === effort);
|
|
3729
|
+
};
|
|
3730
|
+
const thinking = changes.thinking ?? (takes(session.mapping.thinking) ? session.mapping.thinking : void 0);
|
|
3731
|
+
const { restore: _restore, thinking: _thinking, ...kept } = session.spec;
|
|
3732
|
+
const spec = { ...kept, mode, ...teamChanged ? { workflow: team } : {}, ...thinking !== void 0 ? { thinking } : {} };
|
|
3733
|
+
let mapping;
|
|
3734
|
+
try {
|
|
3735
|
+
mapping = await resolveSession({
|
|
3736
|
+
...spec,
|
|
3737
|
+
restore: { agent: session.mapping.agent.name, threadId: session.threadId || "unstarted", runtime: runtimeKind, model, ...teamChanged ? {} : { workflow: session.mapping.workflow } }
|
|
3738
|
+
}, { templates: options.templates, library: options.libraryDir, language: options.language, initialize: false });
|
|
3739
|
+
} catch (error) {
|
|
3740
|
+
const message = errorData(error).message;
|
|
3741
|
+
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);
|
|
3742
|
+
}
|
|
3743
|
+
const graph = teamChanged ? mapping.team ? mapping.team.delegation : await resolveDelegation(projectRoot) : session.graph;
|
|
3744
|
+
const shape = { mapping, graph, spec };
|
|
3745
|
+
const proposed = await effectiveConfig(session, shape);
|
|
3746
|
+
const plan = { shape, current, proposed, changes: changesOf(current, proposed) };
|
|
3747
|
+
const refused = (reason, message) => ({ ...plan, refusal: { reason, message } });
|
|
3748
|
+
if (mapping.runtimeKind !== runtimeKind) return refused("runtime_mismatch", `A session keeps its runtime (${label(runtimeKind)}); start a new session for another runtime`);
|
|
3749
|
+
if (mapping.agent.name !== session.mapping.agent.name) return refused("agent_mismatch", "A session keeps its agent; start a new session for another agent");
|
|
3750
|
+
const agent = session.mapping.agent.name;
|
|
3751
|
+
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`);
|
|
3752
|
+
if (changes.mode !== void 0 && 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"));
|
|
3753
|
+
if (changes.mode === void 0 && !withinMode(mapping.mode, session.mapping.mode)) return refused("permission_escalation", `The change would run the session in ${mapping.mode}, beyond its ${session.mapping.mode}`);
|
|
3754
|
+
const before = executablesOf(session.mapping);
|
|
3755
|
+
const added = [...executablesOf(mapping)].filter((entry) => !before.has(entry));
|
|
3756
|
+
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`);
|
|
3757
|
+
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");
|
|
3758
|
+
return plan;
|
|
3759
|
+
}
|
|
3760
|
+
async function nativeHistory(session) {
|
|
3761
|
+
if (!session.threadId) return false;
|
|
3762
|
+
if (session.base) return true;
|
|
3763
|
+
const unknown = (error) => new ConversationError("native_refused", `${label(session.runtimeKind)} could not say whether it holds this session's conversation: ${errorData(error).message}`);
|
|
3764
|
+
if (session.runtimeKind === "codex") {
|
|
3765
|
+
try {
|
|
3766
|
+
const page = await session.runtime.request("thread/turns/list", { threadId: session.threadId, limit: 1, sortDirection: "desc" });
|
|
3767
|
+
return Array.isArray(page?.data) && page.data.length > 0;
|
|
3768
|
+
} catch (error) {
|
|
3769
|
+
if (/not materialized|no rollout found/i.test(errorData(error).message)) return false;
|
|
3770
|
+
throw unknown(error);
|
|
3771
|
+
}
|
|
3772
|
+
}
|
|
3773
|
+
if (session.runtimeKind === "claude") {
|
|
3774
|
+
try {
|
|
3775
|
+
const chain = await session.runtime.request("thread/chain", { threadId: session.threadId, cwd: session.mapping.workdir });
|
|
3776
|
+
return Array.isArray(chain?.entries) && chain.entries.length > 0;
|
|
3777
|
+
} catch (error) {
|
|
3778
|
+
throw unknown(error);
|
|
3779
|
+
}
|
|
3780
|
+
}
|
|
3781
|
+
return true;
|
|
3782
|
+
}
|
|
3783
|
+
async function previewConfigureSession(sessionId, changes) {
|
|
3784
|
+
const session = sessions.get(sessionId);
|
|
3785
|
+
if (!session || session.closed) throw new ConversationError("session_busy", "The session is not open");
|
|
3786
|
+
const plan = await planConfigure(session, changes ?? {});
|
|
3787
|
+
const busy = plan.changes.length ? restartRefusal(sessionId, session) : void 0;
|
|
3788
|
+
const teams = (await listTeams(session.mapping.agent.projectRoot, { library: options.libraryDir, templates: options.templates })).filter((team) => !team.error).map((team) => ({ id: team.id, label: team.label ?? team.id, ...team.description ? { description: team.description } : {} }));
|
|
3789
|
+
return {
|
|
3790
|
+
current: plan.current,
|
|
3791
|
+
proposed: plan.proposed,
|
|
3792
|
+
changes: plan.changes,
|
|
3793
|
+
restart: plan.changes.some((change) => change !== "mode"),
|
|
3794
|
+
allowed: !plan.refusal && !busy,
|
|
3795
|
+
...plan.refusal ? { reason: plan.refusal.reason, message: plan.refusal.message } : busy ? { reason: "session_busy", message: busy } : {},
|
|
3796
|
+
teams
|
|
3797
|
+
};
|
|
3798
|
+
}
|
|
3799
|
+
async function reconfigureSession(sessionId, changes, { fresh = false, onApplied } = {}) {
|
|
3800
|
+
async function persist(result2) {
|
|
3801
|
+
try {
|
|
3802
|
+
await onApplied?.(result2);
|
|
3803
|
+
} catch (error) {
|
|
3804
|
+
throw new ConversationError("native_refused", `The runtime took the configuration but the host could not record it: ${errorData(error).message}`, { outcomeUnknown: true });
|
|
3805
|
+
}
|
|
3806
|
+
}
|
|
3807
|
+
const session = sessions.get(sessionId);
|
|
3808
|
+
const busy = restartRefusal(sessionId, session);
|
|
3809
|
+
if (busy) throw new ConversationError(session && (session.parent || session.role === "supervisor") ? "not_root" : "session_busy", busy);
|
|
3810
|
+
const live2 = session;
|
|
3811
|
+
const plan = await planConfigure(live2, changes ?? {});
|
|
3812
|
+
if (plan.refusal) throw new ConversationError(plan.refusal.reason, plan.refusal.message);
|
|
3813
|
+
const starts = fresh && !(plan.changes.length && await nativeHistory(live2));
|
|
3814
|
+
const after = restartRefusal(sessionId, live2);
|
|
3815
|
+
if (after) throw new ConversationError("session_busy", after);
|
|
3816
|
+
if (!plan.changes.length) return { session: snapshot(sessionId, live2), effective: plan.current, status: "unchanged", restarted: false };
|
|
3817
|
+
const agent = live2.mapping.agent.name;
|
|
3818
|
+
if (plan.changes.every((change) => change === "mode")) {
|
|
3819
|
+
await configureSession(sessionId, { mode: plan.shape.mapping.mode }, (updated2) => persist({ session: updated2, effective: { ...plan.proposed, instructionsSha: plan.current.instructionsSha }, status: "applied", restarted: false }));
|
|
3820
|
+
runLog(rootOf(sessionId), { event: "session.configured", sessionId, agent, changes: plan.changes, mode: plan.shape.mapping.mode });
|
|
3821
|
+
return { session: snapshot(sessionId, live2), effective: { ...plan.proposed, instructionsSha: plan.current.instructionsSha }, status: "applied", restarted: false };
|
|
3822
|
+
}
|
|
3823
|
+
if (!starts && !live2.threadId) throw new ConversationError("runtime_unsupported", "This session keeps no native conversation to continue");
|
|
3824
|
+
const binding = starts ? void 0 : { threadId: live2.threadId, ...live2.base ? { base: live2.base } : {} };
|
|
3825
|
+
const from = { model: live2.mapping.model, thinking: live2.mapping.thinking, team: live2.mapping.workflow.mode, mode: live2.mapping.mode };
|
|
3826
|
+
const to = { model: plan.shape.mapping.model, thinking: plan.shape.mapping.thinking, team: plan.shape.mapping.workflow.mode, mode: plan.shape.mapping.mode };
|
|
3827
|
+
let native;
|
|
3828
|
+
try {
|
|
3829
|
+
native = await restartNative(sessionId, live2, binding, true, plan.shape);
|
|
3830
|
+
if (live2.runtimeKind === "codex" && native?.model !== to.model) throw new ConversationError("native_refused", typeof native?.model === "string" ? `Codex continued the conversation with ${native.model}, not ${to.model}` : `Codex did not say which model it continued the conversation with, so ${to.model} is not taken`);
|
|
3831
|
+
} catch (error) {
|
|
3832
|
+
runLog(rootOf(sessionId), { event: "session.configure_failed", sessionId, agent, from, to, error: errorData(error).message });
|
|
3833
|
+
try {
|
|
3834
|
+
if (live2.closed) throw error;
|
|
3835
|
+
await restartNative(sessionId, live2, binding, false);
|
|
3836
|
+
} catch (reopen) {
|
|
3837
|
+
live2.pending = false;
|
|
3838
|
+
if (!live2.closed) failSession(sessionId, live2, reopen);
|
|
3839
|
+
}
|
|
3840
|
+
if (error instanceof ConversationError) throw error;
|
|
3841
|
+
throw new ConversationError("native_refused", `The runtime did not take the new configuration; the session keeps its own: ${errorData(error).message}`);
|
|
3842
|
+
}
|
|
3843
|
+
live2.mapping = plan.shape.mapping;
|
|
3844
|
+
live2.graph = plan.shape.graph;
|
|
3845
|
+
live2.spec = plan.shape.spec;
|
|
3846
|
+
const answered = live2.runtimeKind === "codex" ? { ...typeof native?.model === "string" ? { model: native.model } : {}, ...typeof native?.reasoningEffort === "string" ? { reasoningEffort: native.reasoningEffort } : {} } : void 0;
|
|
3847
|
+
runLog(rootOf(sessionId), { event: "session.configured", sessionId, agent, changes: plan.changes, from, to, threadId: live2.threadId, ...answered ? { native: answered } : {} });
|
|
3848
|
+
if (plan.changes.includes("team")) {
|
|
3849
|
+
const old = live2.supervisor;
|
|
3850
|
+
if (old) {
|
|
3851
|
+
live2.supervisor = void 0;
|
|
3852
|
+
await closeSession(old).catch(() => {
|
|
3853
|
+
});
|
|
3854
|
+
}
|
|
3855
|
+
if (supervises(live2)) void enqueue(() => openSupervisor(sessionId));
|
|
3856
|
+
}
|
|
3857
|
+
const updated = snapshot(sessionId, live2);
|
|
3858
|
+
const result = {
|
|
3859
|
+
session: updated,
|
|
3860
|
+
effective: { ...plan.proposed, ...live2.instructionsSha ? { instructionsSha: live2.instructionsSha } : {} },
|
|
3861
|
+
status: "applied",
|
|
3862
|
+
restarted: true,
|
|
3863
|
+
...answered ? { native: answered } : {}
|
|
3864
|
+
};
|
|
3865
|
+
await persist(result);
|
|
3866
|
+
emit(sessionId, { type: "session.updated", session: updated });
|
|
3867
|
+
return result;
|
|
3868
|
+
}
|
|
3869
|
+
async function branchConversation(request) {
|
|
3870
|
+
if (closed) throw new Error("Runtime is closed");
|
|
3871
|
+
if (request.runtime !== "codex" && request.runtime !== "claude") throw new ConversationError("runtime_unsupported", `${label(request.runtime)} sessions cannot be forked or rewound`);
|
|
3872
|
+
if (!Array.isArray(request.turns) || !request.turns.every((turn) => typeof turn === "string")) throw new Error("branch needs the source turns in order");
|
|
3873
|
+
if (typeof request.source?.threadId !== "string" || !request.source.threadId) throw new Error("branch needs the source thread");
|
|
3874
|
+
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");
|
|
3875
|
+
return request.runtime === "codex" ? branchCodex(request) : branchClaude(request);
|
|
3876
|
+
}
|
|
3877
|
+
async function branchCodex(request) {
|
|
3878
|
+
const end = codexForkEnd(request);
|
|
3879
|
+
const cwd = request.targetCwd ?? request.cwd;
|
|
3880
|
+
const mode = request.mode;
|
|
3881
|
+
const transport = createTransport(options, "codex", cwd, nativeEnvironment(options));
|
|
3882
|
+
try {
|
|
3883
|
+
try {
|
|
3884
|
+
await transport.initialize();
|
|
3885
|
+
} catch (error) {
|
|
3886
|
+
throw new ConversationError("native_refused", `Codex did not start: ${errorData(error).message}`);
|
|
3887
|
+
}
|
|
3888
|
+
let forked;
|
|
3889
|
+
try {
|
|
3890
|
+
forked = await transport.request("thread/fork", {
|
|
3891
|
+
threadId: request.source.threadId,
|
|
3892
|
+
...end.params,
|
|
3893
|
+
ephemeral: false,
|
|
3894
|
+
excludeTurns: true,
|
|
3895
|
+
cwd,
|
|
3896
|
+
model: request.model.replace(/^codex:/, ""),
|
|
3897
|
+
sandbox: mode === "full-access" ? "danger-full-access" : nativeMode({ mode, copy: false }),
|
|
3898
|
+
approvalPolicy: codexApproval({ mode, permissions: null })
|
|
3899
|
+
});
|
|
3900
|
+
} catch (error) {
|
|
3901
|
+
throw codexForkRefusal(error);
|
|
3902
|
+
}
|
|
3903
|
+
const id = forked?.thread?.id;
|
|
3904
|
+
if (typeof id !== "string" || !id) throw new ConversationError("native_refused", "Codex answered the fork without a thread id", { outcomeUnknown: true });
|
|
3905
|
+
let problem;
|
|
3906
|
+
try {
|
|
3907
|
+
if (forked.thread.forkedFromId != null && forked.thread.forkedFromId !== request.source.threadId) problem = `it was forked from ${forked.thread.forkedFromId}`;
|
|
3908
|
+
else {
|
|
3909
|
+
const page = await transport.request("thread/turns/list", { threadId: id, limit: 1, sortDirection: "desc" });
|
|
3910
|
+
const last = page?.data?.[0];
|
|
3911
|
+
if (last?.id !== end.last) problem = `it ends at ${last?.id ?? "no turn"}, not ${end.last}`;
|
|
3912
|
+
else if (last.status === "inProgress") problem = `its last turn ${last.id} is still running`;
|
|
3913
|
+
}
|
|
3914
|
+
} catch (error) {
|
|
3915
|
+
problem = `it could not be read: ${errorData(error).message}`;
|
|
3916
|
+
}
|
|
3917
|
+
if (!problem) return { threadId: id };
|
|
3918
|
+
const deleted = await transport.request("thread/delete", { threadId: id }).then(() => true, () => false);
|
|
3919
|
+
throw new ConversationError("native_refused", `The Codex fork ${id} could not be verified (${problem}); ${deleted ? "it was deleted" : "deleting it failed"}`, { outcomeUnknown: !deleted });
|
|
3920
|
+
} finally {
|
|
3921
|
+
await transport.close().catch(() => {
|
|
3922
|
+
});
|
|
3923
|
+
}
|
|
3924
|
+
}
|
|
3925
|
+
async function branchClaude(request) {
|
|
3926
|
+
const transport = createTransport(options, "claude", request.cwd, nativeEnvironment(options));
|
|
3927
|
+
try {
|
|
3928
|
+
const read = async (threadId) => {
|
|
3929
|
+
const answer = await transport.request("thread/chain", { threadId, cwd: request.cwd });
|
|
3930
|
+
if (!Array.isArray(answer?.entries)) throw new Error("Claude answered no transcript");
|
|
3931
|
+
return answer.entries;
|
|
3932
|
+
};
|
|
3933
|
+
await transport.initialize();
|
|
3934
|
+
let source = request.source.threadId;
|
|
3935
|
+
let chain = await read(source);
|
|
3936
|
+
if (!chain.length && request.source.base) {
|
|
3937
|
+
source = request.source.base.threadId;
|
|
3938
|
+
chain = pendingChain(request.source.base, await read(source));
|
|
3939
|
+
}
|
|
3940
|
+
return { threadId: randomUUID(), base: { threadId: source, at: claudeCut(chain, request) } };
|
|
3941
|
+
} catch (error) {
|
|
3942
|
+
if (error instanceof ConversationError) throw error;
|
|
3943
|
+
throw new ConversationError("native_refused", `The Claude transcript could not be read: ${errorData(error).message}`);
|
|
3944
|
+
} finally {
|
|
3945
|
+
await transport.close().catch(() => {
|
|
3946
|
+
});
|
|
3947
|
+
}
|
|
3948
|
+
}
|
|
2456
3949
|
const restartCause = () => options.previousExit?.kind === "crash" ? "alpd stopped unexpectedly" : "alpd restarted";
|
|
2457
3950
|
async function resumeAssignment(entry) {
|
|
2458
3951
|
const parent = sessions.get(entry.parentId);
|
|
@@ -2492,8 +3985,6 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2492
3985
|
}
|
|
2493
3986
|
if (assignment.copy) await removeCopy(assignment.copy).catch(() => {
|
|
2494
3987
|
});
|
|
2495
|
-
if (assignment.worktree) await removeWorktree(assignment.worktree).catch(() => {
|
|
2496
|
-
});
|
|
2497
3988
|
};
|
|
2498
3989
|
try {
|
|
2499
3990
|
if (entry.lease) {
|
|
@@ -2504,7 +3995,14 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2504
3995
|
leases.set(entry.lease, { assignment: id, agent: entry.agent });
|
|
2505
3996
|
}
|
|
2506
3997
|
}
|
|
2507
|
-
if (entry.worktree)
|
|
3998
|
+
if (entry.worktree) {
|
|
3999
|
+
const { preserved, ...worktree } = await reattachWorktree(entry.worktree);
|
|
4000
|
+
assignment.worktree = worktree;
|
|
4001
|
+
if (preserved) {
|
|
4002
|
+
runLog(entry.rootId, { event: "worktree.preserved", assignmentId: id, branch: worktree.branch, preserved });
|
|
4003
|
+
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}.` });
|
|
4004
|
+
}
|
|
4005
|
+
}
|
|
2508
4006
|
if (entry.copyOf) {
|
|
2509
4007
|
assignment.copy = await createCopy(entry.copyOf, copyRoot, id);
|
|
2510
4008
|
spec = { ...spec, workdir: assignment.copy.workdir };
|
|
@@ -2521,8 +4019,9 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2521
4019
|
assignment.taskId = entry.taskId;
|
|
2522
4020
|
touchTask(entry.rootId, entry.taskId);
|
|
2523
4021
|
}
|
|
2524
|
-
await openSession(id, { ...spec, restore: { agent: entry.agent, threadId: entry.threadId, runtime: entry.runtime, model: entry.model, workflow: parent.mapping.workflow } }, "skip", entry.delegation);
|
|
2525
|
-
const child =
|
|
4022
|
+
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);
|
|
4023
|
+
const child = assignmentSessions.get(assignment);
|
|
4024
|
+
if (sessions.get(id) !== child) throw new Error("Child session was replaced during recovery");
|
|
2526
4025
|
child.settle = (state, error) => void finishAssignment(entry.parentId, parent, assignment, state, error);
|
|
2527
4026
|
if (entry.brief) child.brief = entry.brief;
|
|
2528
4027
|
if (assignment.taskId && writes(entry.mode)) {
|
|
@@ -2541,6 +4040,21 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2541
4040
|
return assignment;
|
|
2542
4041
|
}
|
|
2543
4042
|
async function abandonEntry(entry, reason) {
|
|
4043
|
+
if (entry.worktree || writes(entry.mode)) await assignmentResults.put({
|
|
4044
|
+
assignmentId: entry.assignmentId,
|
|
4045
|
+
checkout: entry.worktree?.checkout ?? entry.lease ?? entry.spec.writeRoot ?? entry.spec.workdir ?? entry.project,
|
|
4046
|
+
...entry.worktree ? { worktree: entry.worktree.path } : {},
|
|
4047
|
+
...!entry.worktree ? { result: {
|
|
4048
|
+
agent: entry.agent,
|
|
4049
|
+
status: "abandoned",
|
|
4050
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
4051
|
+
project: entry.project,
|
|
4052
|
+
requesters: sessions.has(entry.parentId) ? lineage(entry.parentId) : [entry.parentId],
|
|
4053
|
+
...entry.taskId ? { taskId: entry.taskId } : {},
|
|
4054
|
+
brief: cut(entry.brief ?? "", RESULT_EVIDENCE_CHARS),
|
|
4055
|
+
summary: cut(JSON.stringify({ reason }), RESULT_EVIDENCE_CHARS)
|
|
4056
|
+
} } : {}
|
|
4057
|
+
});
|
|
2544
4058
|
await inFlight.remove(entry.assignmentId);
|
|
2545
4059
|
const parent = sessions.get(entry.parentId);
|
|
2546
4060
|
let task;
|
|
@@ -2565,7 +4079,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2565
4079
|
runLog(entry.rootId, { event: "assignment.finished", assignmentId: entry.assignmentId, reconciled: true, ...result });
|
|
2566
4080
|
if (parent && !parent.closed) post(entry.parentId, { kind: "result", from: entry.agent, assignment: entry.assignmentId, result });
|
|
2567
4081
|
}
|
|
2568
|
-
async function recoverTree(rootId, continueRoot) {
|
|
4082
|
+
async function recoverTree(rootId, continueRoot, parkedRoot) {
|
|
2569
4083
|
const root = sessions.get(rootId);
|
|
2570
4084
|
if (!root || root.closed) throw new Error(`Session ${rootId} is not open`);
|
|
2571
4085
|
const entries = inherited.filter((entry) => entry.rootId === rootId).sort((a, b) => a.ancestry.length - b.ancestry.length);
|
|
@@ -2587,7 +4101,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2587
4101
|
const listed = (assignments = []) => assignments.length ? ` These assignments of yours continue and report to you: ${assignments.map((assignment) => `${assignment.id} (${assignment.agent}${assignment.taskId ? `, task ${assignment.taskId}` : ""})`).join(", ")}. Wait for them with alp_wait, or keep working.` : "";
|
|
2588
4102
|
const proceed = (sessionId, session, text2) => {
|
|
2589
4103
|
if (options.recoveryResume === false || pauseOf(session.runtimeKind)) {
|
|
2590
|
-
session.parked = { reason: cause, since: Date.now(), prompt: text2 };
|
|
4104
|
+
session.parked = { reason: cause, since: Date.now(), prompt: text2, ...options.recoveryResume !== false ? { pause: { scope: paused.all ? "all" : session.runtimeKind } } : {} };
|
|
2591
4105
|
emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
|
|
2592
4106
|
runLog(rootId, { event: "assignment.parked", assignmentId: sessionId, agent: session.mapping.agent.name, reason: cause });
|
|
2593
4107
|
const outcome = outcomes.find((entry) => entry.assignmentId === sessionId);
|
|
@@ -2602,14 +4116,22 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2602
4116
|
runLog(rootId, { event: "assignment.recovered", assignmentId: entry.assignmentId, agent: entry.agent, ...entry.taskId ? { taskId: entry.taskId } : {} });
|
|
2603
4117
|
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))}`);
|
|
2604
4118
|
}
|
|
2605
|
-
if (
|
|
4119
|
+
if (parkedRoot) {
|
|
4120
|
+
root.parked = { reason: parkedRoot, since: Date.now() };
|
|
4121
|
+
emit(rootId, { type: "session.updated", session: snapshot(rootId, root) });
|
|
4122
|
+
} 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))}`);
|
|
2606
4123
|
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.` });
|
|
2607
4124
|
const failed = outcomes.filter((outcome) => outcome.outcome === "failed");
|
|
2608
|
-
if (entries.length || continueRoot) {
|
|
2609
|
-
const parked = outcomes.
|
|
4125
|
+
if (entries.length || continueRoot || parkedRoot) {
|
|
4126
|
+
const parked = outcomes.flatMap((outcome) => {
|
|
4127
|
+
const park2 = outcome.outcome === "parked" ? sessions.get(outcome.assignmentId)?.parked : void 0;
|
|
4128
|
+
return park2 ? [park2] : [];
|
|
4129
|
+
});
|
|
4130
|
+
if ((continueRoot || parkedRoot) && root.parked) parked.push(root.parked);
|
|
4131
|
+
const next = parked.some((park2) => !park2.pause) ? "send an explicit prompt to each parked session to continue it: alp send <session> --prompt <text>" : "run alp resume to continue them";
|
|
2610
4132
|
notice(
|
|
2611
4133
|
failed.length ? "warning" : "info",
|
|
2612
|
-
`ALP: ${cause}${options.previousExit?.at ? ` (around ${options.previousExit.at})` : ""}. ${entries.length - failed.length} of ${entries.length} running assignments reopened${continueRoot ? ", and this session" : ""}${parked ?
|
|
4134
|
+
`ALP: ${cause}${options.previousExit?.at ? ` (around ${options.previousExit.at})` : ""}. ${entries.length - failed.length} of ${entries.length} running assignments reopened${continueRoot || parkedRoot ? ", and this session" : ""}${parked.length ? `; they wait parked: ${next}` : ""}.${failed.length ? ` Could not continue: ${failed.map((outcome) => `${outcome.agent} ${outcome.assignmentId} (${outcome.error})`).join("; ")}; their tasks went back to open.` : ""}`,
|
|
2613
4135
|
root.mapping.agent.projectRoot
|
|
2614
4136
|
);
|
|
2615
4137
|
}
|
|
@@ -2624,22 +4146,22 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2624
4146
|
}
|
|
2625
4147
|
return session;
|
|
2626
4148
|
}
|
|
2627
|
-
async function configureSession(sessionId, changes) {
|
|
4149
|
+
async function configureSession(sessionId, changes, beforeUpdated) {
|
|
2628
4150
|
const session = openOf(sessionId);
|
|
2629
4151
|
if (session.active || session.pending || session.children.size) throw new Error("Wait for the current turn and child sessions to finish before changing permissions");
|
|
2630
4152
|
const mode = changes.mode ?? session.mapping.mode;
|
|
2631
4153
|
if (!modes.some((candidate) => candidate.id === mode)) throw new Error(`Unsupported mode '${mode}'`);
|
|
2632
4154
|
const profile = session.mapping.permissions;
|
|
2633
4155
|
if (profile && !withinMode(mode, profile.base)) {
|
|
2634
|
-
throw new Error(
|
|
4156
|
+
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}`);
|
|
2635
4157
|
}
|
|
2636
4158
|
const parent = session.parent ? sessions.get(session.parent) : void 0;
|
|
2637
4159
|
if (parent && !withinMode(mode, parent.mapping.mode)) throw new Error("Child cannot exceed parent permissions");
|
|
2638
|
-
if (session.runtimeKind === "
|
|
2639
|
-
if (session.runtimeKind === "claude") await session.runtime.request("session/configure", { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
|
|
4160
|
+
if (session.runtimeKind === "claude" || session.runtimeKind === "antigravity") await session.runtime.request("session/configure", { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
|
|
2640
4161
|
session.mapping.mode = mode;
|
|
2641
4162
|
session.spec = { ...session.spec, mode };
|
|
2642
4163
|
const updated = snapshot(sessionId, session);
|
|
4164
|
+
if (beforeUpdated) await beforeUpdated(updated);
|
|
2643
4165
|
emit(sessionId, { type: "session.updated", session: updated });
|
|
2644
4166
|
return updated;
|
|
2645
4167
|
}
|
|
@@ -2649,6 +4171,13 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2649
4171
|
const activeTurn = session.active;
|
|
2650
4172
|
session.wakeBlocked = true;
|
|
2651
4173
|
session.userStopped = true;
|
|
4174
|
+
session.parked = void 0;
|
|
4175
|
+
session.parkReason = void 0;
|
|
4176
|
+
session.parkPause = void 0;
|
|
4177
|
+
session.resumeHeld = void 0;
|
|
4178
|
+
emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
|
|
4179
|
+
approvalCancellation.set(session, (approvalCancellation.get(session) ?? 0) + 1);
|
|
4180
|
+
cancelQuestions(sessionId);
|
|
2652
4181
|
if (activeTurn && session.runtimeKind === "codex" && session.threadId) {
|
|
2653
4182
|
const partial = [...session.text.values()].join("\n").trim();
|
|
2654
4183
|
if (partial) interruptedThreads.set(session.threadId, partial.slice(-4e3));
|
|
@@ -2660,7 +4189,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2660
4189
|
);
|
|
2661
4190
|
await Promise.all(
|
|
2662
4191
|
[...session.children].map(
|
|
2663
|
-
closeSession
|
|
4192
|
+
(id) => closeSession(id)
|
|
2664
4193
|
)
|
|
2665
4194
|
);
|
|
2666
4195
|
if (!activeTurn) session.settle?.("canceled", "Interrupted");
|
|
@@ -2674,16 +4203,39 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2674
4203
|
);
|
|
2675
4204
|
}
|
|
2676
4205
|
}
|
|
2677
|
-
async function
|
|
4206
|
+
async function promptSession(sessionId, input, flushing = false) {
|
|
4207
|
+
const session = sessions.get(sessionId);
|
|
4208
|
+
if (!flushing && session && !session.parent && (session.compacting || session.compactBuffer?.length)) {
|
|
4209
|
+
if (!session.seen.has(input.clientMessageId) && !session.compactBuffer?.some((held2) => held2.clientMessageId === input.clientMessageId)) (session.compactBuffer ??= []).push(input);
|
|
4210
|
+
return;
|
|
4211
|
+
}
|
|
4212
|
+
const parked = session?.parked;
|
|
4213
|
+
try {
|
|
4214
|
+
const prompt = session?.active && session.resumedTurn === session.active && input.delivery === "auto" ? { ...input, delivery: "steer" } : input;
|
|
4215
|
+
await startPrompt(sessionId, prompt, "user");
|
|
4216
|
+
if (session && parked && session.parked === parked) {
|
|
4217
|
+
session.parked = void 0;
|
|
4218
|
+
emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
|
|
4219
|
+
}
|
|
4220
|
+
} catch (error) {
|
|
4221
|
+
const session2 = sessions.get(sessionId);
|
|
4222
|
+
if (session2?.seen.has(input.clientMessageId)) return;
|
|
4223
|
+
session2?.seen.add(input.clientMessageId);
|
|
4224
|
+
emit(sessionId, { type: "prompt.failed", clientMessageId: input.clientMessageId, error: errorData(error) });
|
|
4225
|
+
}
|
|
4226
|
+
}
|
|
4227
|
+
async function startPrompt(sessionId, prompt, origin, wake, internalCompact = false) {
|
|
2678
4228
|
const session = openOf(sessionId);
|
|
2679
4229
|
if (session.seen.has(
|
|
2680
4230
|
prompt.clientMessageId
|
|
2681
4231
|
)) {
|
|
2682
4232
|
return;
|
|
2683
4233
|
}
|
|
2684
|
-
if (prompt.content.some((content) => content.type !== "text" && content.type !== "image")) {
|
|
2685
|
-
throw new Error("Only text and
|
|
4234
|
+
if (prompt.content.some((content) => content.type !== "text" && content.type !== "image" && content.type !== "attachment")) {
|
|
4235
|
+
throw new Error("Only text, image and attachment prompts are supported");
|
|
2686
4236
|
}
|
|
4237
|
+
const refusal = origin === "user" ? nativeCommandRefusal(session.runtimeKind, prompt.content, session.runtime.customCommands?.()) : void 0;
|
|
4238
|
+
if (refusal) throw new Error(refusal);
|
|
2687
4239
|
const images = prompt.content.filter((content) => content.type === "image");
|
|
2688
4240
|
if (images.length) {
|
|
2689
4241
|
if (!takesImages(session)) throw new Error(`${session.runtimeKind === "acp" ? "This ACP agent" : session.runtimeKind[0].toUpperCase() + session.runtimeKind.slice(1)} takes no images; send the message as text`);
|
|
@@ -2696,6 +4248,23 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2696
4248
|
}
|
|
2697
4249
|
}
|
|
2698
4250
|
}
|
|
4251
|
+
const attached = [];
|
|
4252
|
+
const attachmentParts = prompt.content.filter((content) => content.type === "attachment");
|
|
4253
|
+
if (attachmentParts.length) {
|
|
4254
|
+
if (!attachmentRoutes(session).includes("file.path") || !stager || !attachmentReader) {
|
|
4255
|
+
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`);
|
|
4256
|
+
}
|
|
4257
|
+
if (!stagingWarned.has(sessionId)) {
|
|
4258
|
+
stagingWarned.add(sessionId);
|
|
4259
|
+
const exposed = stagingExposure(stager.root, [session.mapping.workdir, os.tmpdir(), "/tmp"]);
|
|
4260
|
+
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 });
|
|
4261
|
+
}
|
|
4262
|
+
for (const part of attachmentParts) {
|
|
4263
|
+
const attachment = runtimeAttachment(part);
|
|
4264
|
+
if (!attachment) throw new Error("An attachment in a prompt must be one alpd resolved");
|
|
4265
|
+
attached.push({ attachment, staged: await stager.stage(attachmentReader, attachment, sessionId) });
|
|
4266
|
+
}
|
|
4267
|
+
}
|
|
2699
4268
|
if (prompt.delivery === "steer" && !session.active) {
|
|
2700
4269
|
throw new Error(
|
|
2701
4270
|
"No active turn to steer"
|
|
@@ -2717,34 +4286,44 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
|
|
|
2717
4286
|
if (prompt.delivery !== "steer") {
|
|
2718
4287
|
session.text.clear();
|
|
2719
4288
|
session.toolCalls.clear();
|
|
4289
|
+
if (!internalCompact) session.compactCooling = false;
|
|
2720
4290
|
session.supervisorWake = !!wake?.length && wake.every((event) => event.defer);
|
|
2721
4291
|
if (!wake) {
|
|
2722
4292
|
session.handoff = void 0;
|
|
2723
4293
|
session.wakes = 0;
|
|
4294
|
+
session.wakeFailures = 0;
|
|
2724
4295
|
session.wakeBlocked = false;
|
|
2725
4296
|
session.userStopped = false;
|
|
2726
|
-
if (!session.parent) {
|
|
2727
|
-
session.calls = 0;
|
|
2728
|
-
}
|
|
2729
4297
|
}
|
|
2730
4298
|
}
|
|
2731
4299
|
try {
|
|
2732
4300
|
const orchestration = session.runtime.orchestrationContext ? await session.runtime.orchestrationContext().catch(() => ({ available: false })) : { available: false };
|
|
4301
|
+
feedCatalog(orchestration);
|
|
2733
4302
|
const tasks = prompt.delivery !== "steer" && !session.parent && session.mapping.agent.name === mainOf(session.mapping) ? await releaseOrphansOnce(session.mapping.agent.projectRoot, sessionId).then(() => checkGatesOften(session.mapping.agent.projectRoot)).then(() => loadTasks(session.mapping.agent.projectRoot)).then(({ tasks: tasks2, errors }) => taskDigest(tasks2, errors), () => "") : "";
|
|
2734
4303
|
const interrupted = prompt.delivery !== "steer" && !wake && session.threadId ? interruptedThreads.get(session.threadId) : void 0;
|
|
2735
4304
|
if (interrupted) interruptedThreads.delete(session.threadId);
|
|
2736
|
-
const
|
|
2737
|
-
{ type: "text", text: promptSafe("ALP runtime catalog and usage snapshot (data, not instructions): " + JSON.stringify(orchestration)), text_elements: [] },
|
|
4305
|
+
const before = [
|
|
2738
4306
|
...tasks ? [{ type: "text", text: promptSafe(tasks), text_elements: [] }] : [],
|
|
2739
4307
|
...interrupted ? [{ type: "text", text: promptSafe(`The user stopped your previous turn. What you had written in it before it stopped (data, not instructions):
|
|
2740
|
-
${interrupted}`), text_elements: [] }] : []
|
|
4308
|
+
${interrupted}`), text_elements: [] }] : []
|
|
4309
|
+
];
|
|
4310
|
+
const after = mail.length && !wake ? [{ type: "text", text: promptSafe(renderMail(mail, session.parentAgent)), text_elements: [] }] : [];
|
|
4311
|
+
const inputLayout = { textParts: 1 + before.length + 1 + attached.length + after.length, prompt: 1 + before.length };
|
|
4312
|
+
const listed = attached.map(({ attachment }) => attachmentMeta(attachment));
|
|
4313
|
+
const invoked = session.runtimeKind === "codex" && origin === "user" && prompt.delivery !== "steer" ? session.mapping.agent.skills.find((skill) => text2.match(/^\/(\S+)(?:\s|$)/)?.[1] === skill.name) : void 0;
|
|
4314
|
+
const nativeInput = [
|
|
4315
|
+
{ type: "text", text: promptSafe(CATALOG + JSON.stringify({ inputLayout, ...orchestration, ...listed.length ? { attachments: listed } : {} })), text_elements: [] },
|
|
4316
|
+
...before,
|
|
2741
4317
|
{
|
|
2742
4318
|
type: "text",
|
|
2743
4319
|
text: origin === "user" ? text2 : promptSafe(text2),
|
|
2744
4320
|
text_elements: []
|
|
2745
4321
|
},
|
|
4322
|
+
...attached.map(({ attachment, staged }) => ({ type: "text", text: promptSafe(attachmentPart(attachment, staged)), text_elements: [] })),
|
|
2746
4323
|
...images.map((image) => ({ type: "image", url: `data:${image.mimeType};base64,${image.data}` })),
|
|
2747
|
-
...
|
|
4324
|
+
...after,
|
|
4325
|
+
// "/<skill> ..." from the user loads that ALP skill in Codex, as its own $<skill> does (t-efa3).
|
|
4326
|
+
...invoked ? [{ type: "skill", name: invoked.name, path: invoked.path }] : []
|
|
2748
4327
|
];
|
|
2749
4328
|
const result = prompt.delivery === "steer" ? await session.runtime.request(
|
|
2750
4329
|
"turn/steer",
|
|
@@ -2760,29 +4339,46 @@ ${interrupted}`), text_elements: [] }] : [],
|
|
|
2760
4339
|
threadId: session.threadId,
|
|
2761
4340
|
clientUserMessageId: prompt.clientMessageId,
|
|
2762
4341
|
input: nativeInput,
|
|
4342
|
+
// Codex keeps a turn's model and effort for later turns too; ALP names both on every turn (§12.9).
|
|
4343
|
+
...session.runtimeKind === "codex" ? { model: session.mapping.model } : {},
|
|
2763
4344
|
effort: session.mapping.thinking,
|
|
2764
4345
|
approvalPolicy: codexApproval(session.mapping),
|
|
2765
4346
|
sandboxPolicy: nativeMode(session.mapping) === "read-only" ? { type: "readOnly", networkAccess: false } : nativeMode(session.mapping) === "full-access" ? { type: "dangerFullAccess" } : { type: "workspaceWrite", writableRoots: [session.mapping.workdir], networkAccess: false, excludeTmpdirEnvVar: false, excludeSlashTmp: false }
|
|
2766
4347
|
}
|
|
2767
4348
|
);
|
|
2768
4349
|
const turnId = prompt.delivery === "steer" ? session.active : result.turn.id;
|
|
4350
|
+
if (internalCompact) {
|
|
4351
|
+
const echoes = compactEchoes.get(session) ?? /* @__PURE__ */ new Map();
|
|
4352
|
+
echoes.set(`${session.threadId}:${turnId}`, inputDigest(nativeInput.flatMap((part) => "text" in part ? [String(part.text)] : [])));
|
|
4353
|
+
compactEchoes.set(session, echoes);
|
|
4354
|
+
}
|
|
2769
4355
|
for (const event of mail) event.deliveredTurn = turnId;
|
|
4356
|
+
if (!session.parent && origin === "user") {
|
|
4357
|
+
session.calls = 0;
|
|
4358
|
+
session.advisorCalls = 0;
|
|
4359
|
+
}
|
|
2770
4360
|
session.seen.add(
|
|
2771
4361
|
prompt.clientMessageId
|
|
2772
4362
|
);
|
|
2773
|
-
emit(sessionId, {
|
|
4363
|
+
if (!internalCompact) emit(sessionId, {
|
|
2774
4364
|
type: "item",
|
|
2775
4365
|
item: {
|
|
2776
4366
|
kind: "user_message",
|
|
2777
4367
|
id: `user:${prompt.clientMessageId}`,
|
|
2778
4368
|
clientMessageId: prompt.clientMessageId,
|
|
2779
4369
|
text: text2,
|
|
2780
|
-
|
|
4370
|
+
origin,
|
|
4371
|
+
...images.length ? { images: images.length } : {},
|
|
4372
|
+
...listed.length ? { attachments: listed } : {}
|
|
2781
4373
|
}
|
|
2782
4374
|
});
|
|
2783
4375
|
if (origin === "user" && !session.parent) session.userWaiting ??= Date.now();
|
|
4376
|
+
if (origin === "user" && !session.parent && text2) session.lastUserText = clip(text2, 16e3);
|
|
2784
4377
|
if (session.supervisor && origin === "user") session.journal.push(stamp(`user ${prompt.delivery === "steer" ? "steered" : "asked"} ${session.mapping.agent.name}: ${clip(text2, 1500)}`));
|
|
2785
|
-
if (prompt.delivery === "steer" && origin === "user" && !session.parent)
|
|
4378
|
+
if (prompt.delivery === "steer" && origin === "user" && !session.parent) {
|
|
4379
|
+
releaseWaiters(session);
|
|
4380
|
+
releaseQuestions(sessionId);
|
|
4381
|
+
}
|
|
2786
4382
|
emit(sessionId, {
|
|
2787
4383
|
type: "prompt.accepted",
|
|
2788
4384
|
clientMessageId: prompt.clientMessageId,
|
|
@@ -2809,7 +4405,122 @@ ${interrupted}`), text_elements: [] }] : [],
|
|
|
2809
4405
|
}
|
|
2810
4406
|
}
|
|
2811
4407
|
if (options.recallFile) void forgetExpired();
|
|
2812
|
-
|
|
4408
|
+
const api = {
|
|
4409
|
+
registerWorkspace: (directory) => enqueue(async () => {
|
|
4410
|
+
try {
|
|
4411
|
+
await assignmentResults.register(await realpath(directory));
|
|
4412
|
+
} catch (error) {
|
|
4413
|
+
refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot register workspace result ownership");
|
|
4414
|
+
}
|
|
4415
|
+
}),
|
|
4416
|
+
withWorkspaceMutation: (directory, run, adoption) => {
|
|
4417
|
+
if (workspaceMutation || admitting) return Promise.reject(new WorkspaceMutationError("workspace_busy", "A session or assignment is opening; retry after it finishes"));
|
|
4418
|
+
workspaceMutation = true;
|
|
4419
|
+
return enqueue(async () => {
|
|
4420
|
+
const target = await realpath(directory).catch(() => refuseMutation("workspace_busy", `Cannot resolve workspace ${directory}; inspect its directory before removing it`));
|
|
4421
|
+
let resultLedger;
|
|
4422
|
+
try {
|
|
4423
|
+
resultLedger = await assignmentResults.inspect();
|
|
4424
|
+
} catch (error) {
|
|
4425
|
+
refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot inspect permanent assignment results");
|
|
4426
|
+
}
|
|
4427
|
+
if (!resultLedger.workspaces.includes(target) && adoption !== ADOPTION) refuseMutation("workspace_assignment_result", "Workspace predates authoritative assignment tracking; an audited migration is required before removal");
|
|
4428
|
+
const canonical = (value) => {
|
|
4429
|
+
try {
|
|
4430
|
+
return realpathSync(value);
|
|
4431
|
+
} catch (error) {
|
|
4432
|
+
if (error.code !== "ENOENT") refuseMutation("workspace_assignment_result", `Cannot resolve assignment path ${value}; inspect it before removing the workspace`);
|
|
4433
|
+
const parent = path.dirname(value);
|
|
4434
|
+
if (parent === value) throw error;
|
|
4435
|
+
return path.join(canonical(parent), path.basename(value));
|
|
4436
|
+
}
|
|
4437
|
+
};
|
|
4438
|
+
const overlaps = (value) => {
|
|
4439
|
+
if (value === void 0) return false;
|
|
4440
|
+
if (typeof value !== "string" || !value) refuseMutation("workspace_assignment_result", "Invalid assignment path; repair runtime persistence before removing the workspace");
|
|
4441
|
+
if (!path.isAbsolute(value)) refuseMutation("workspace_assignment_result", "Assignment path is not absolute; inspect runtime persistence before removing the workspace");
|
|
4442
|
+
const owner = canonical(value);
|
|
4443
|
+
const contains = (parent, child) => {
|
|
4444
|
+
const relative = path.relative(parent, child);
|
|
4445
|
+
return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
4446
|
+
};
|
|
4447
|
+
return contains(target, owner) || contains(owner, target);
|
|
4448
|
+
};
|
|
4449
|
+
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}`);
|
|
4450
|
+
const resolved = async (assignmentId) => {
|
|
4451
|
+
if (resultLedger.results.some((owner) => owner.assignmentId === assignmentId && owner.handled)) return true;
|
|
4452
|
+
try {
|
|
4453
|
+
return !!await assignmentResults.archived(assignmentId);
|
|
4454
|
+
} catch {
|
|
4455
|
+
return refuseMutation("workspace_assignment_result", "Cannot inspect the assignment result archive; repair it before removing the workspace");
|
|
4456
|
+
}
|
|
4457
|
+
};
|
|
4458
|
+
for (const [project, pins] of loadedBoards) for (const pin of pins) {
|
|
4459
|
+
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}`);
|
|
4460
|
+
}
|
|
4461
|
+
for (const [checkout, holder] of leases) if (overlaps(checkout)) refuseMutation("workspace_leased", `Assignment ${holder.assignment} holds a write lease in ${directory}`);
|
|
4462
|
+
for (const [id, session] of sessions) {
|
|
4463
|
+
for (const assignment of session.assignments.values()) {
|
|
4464
|
+
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}`);
|
|
4465
|
+
}
|
|
4466
|
+
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}`);
|
|
4467
|
+
if (!session.closed && (overlaps(session.mapping.workdir) || overlaps(session.spec.writeRoot))) refuseMutation("workspace_busy", `Close session ${id} before removing ${directory}`);
|
|
4468
|
+
}
|
|
4469
|
+
const checkLive = (entry) => {
|
|
4470
|
+
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}`);
|
|
4471
|
+
};
|
|
4472
|
+
for (const entry of inFlight.all()) checkLive(entry);
|
|
4473
|
+
for (const entry of inherited) checkLive(entry);
|
|
4474
|
+
for (const [file, kind] of [[options.liveFile, "live"], [options.recallFile, "recall"]]) {
|
|
4475
|
+
if (!file) continue;
|
|
4476
|
+
let entries;
|
|
4477
|
+
try {
|
|
4478
|
+
entries = JSON.parse(await readFile(file, "utf8"));
|
|
4479
|
+
} catch (error) {
|
|
4480
|
+
if (error.code === "ENOENT") continue;
|
|
4481
|
+
throw new WorkspaceMutationError("workspace_assignment_result", `Cannot inspect ${file}; repair assignment persistence before removing the workspace`);
|
|
4482
|
+
}
|
|
4483
|
+
if (!Array.isArray(entries)) refuseMutation("workspace_assignment_result", `Invalid assignment book ${file}`);
|
|
4484
|
+
for (const entry of entries) {
|
|
4485
|
+
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}`);
|
|
4486
|
+
if (entry.worktree !== void 0 && (!entry.worktree || !["path", "checkout", "workdir"].every((key) => typeof entry.worktree[key] === "string"))) refuseMutation("workspace_assignment_result", `Invalid worktree result in ${file}`);
|
|
4487
|
+
if (entry.shared !== void 0 && (!entry.shared || typeof entry.shared !== "object" || Array.isArray(entry.shared))) refuseMutation("workspace_assignment_result", `Invalid shared result in ${file}`);
|
|
4488
|
+
if (kind === "live") checkLive(entry);
|
|
4489
|
+
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}`);
|
|
4490
|
+
}
|
|
4491
|
+
}
|
|
4492
|
+
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}`);
|
|
4493
|
+
return await run();
|
|
4494
|
+
}).finally(() => {
|
|
4495
|
+
workspaceMutation = false;
|
|
4496
|
+
});
|
|
4497
|
+
},
|
|
4498
|
+
adoptWorkspace: (directory, verify) => api.withWorkspaceMutation(directory, async () => {
|
|
4499
|
+
if (await realpath(directory) !== directory) refuseMutation("workspace_identity", `Adopt ${directory} by its canonical path`);
|
|
4500
|
+
await verify(directory);
|
|
4501
|
+
try {
|
|
4502
|
+
await assignmentResults.register(directory);
|
|
4503
|
+
} catch (error) {
|
|
4504
|
+
refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot register workspace result ownership");
|
|
4505
|
+
}
|
|
4506
|
+
}, ADOPTION),
|
|
4507
|
+
bindSchedules(handler) {
|
|
4508
|
+
scheduleHandler = handler;
|
|
4509
|
+
},
|
|
4510
|
+
bindAttachments(reader) {
|
|
4511
|
+
attachmentReader = reader;
|
|
4512
|
+
},
|
|
4513
|
+
refusesPrompt(sessionId, content) {
|
|
4514
|
+
const session = sessions.get(sessionId);
|
|
4515
|
+
return session ? nativeCommandRefusal(session.runtimeKind, content, session.runtime.customCommands?.()) : void 0;
|
|
4516
|
+
},
|
|
4517
|
+
takesAttachments(sessionId) {
|
|
4518
|
+
const session = sessions.get(sessionId);
|
|
4519
|
+
return !!session && !session.closed && attachmentRoutes(session).includes("file.path");
|
|
4520
|
+
},
|
|
4521
|
+
async dropAttachment(attachmentId) {
|
|
4522
|
+
await stager?.drop(attachmentId);
|
|
4523
|
+
},
|
|
2813
4524
|
onEvent(listener) {
|
|
2814
4525
|
listeners.add(listener);
|
|
2815
4526
|
return () => {
|
|
@@ -2819,21 +4530,88 @@ ${interrupted}`), text_elements: [] }] : [],
|
|
|
2819
4530
|
open: (sessionId, spec, { history = "skip", delegation = true } = {}) => enqueue(async () => {
|
|
2820
4531
|
const opened = await openSession(sessionId, spec, history, delegation);
|
|
2821
4532
|
const root = sessions.get(sessionId);
|
|
2822
|
-
if (supervises(root))
|
|
4533
|
+
if (supervises(root)) {
|
|
4534
|
+
void enqueue(() => openSupervisor(sessionId));
|
|
4535
|
+
void ensureCurateSchedule(sessionId).catch((error) => runLog(sessionId, { event: "curate.schedule.failed", error: errorData(error).message }));
|
|
4536
|
+
}
|
|
2823
4537
|
return opened;
|
|
2824
4538
|
}),
|
|
2825
|
-
prompt: (sessionId, input) => enqueue(
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
4539
|
+
prompt: (sessionId, input) => enqueue(() => promptSession(sessionId, input)),
|
|
4540
|
+
withIdlePrompt: (sessionId, run) => new Promise((resolve, reject) => {
|
|
4541
|
+
void enqueue(async () => {
|
|
4542
|
+
const session = openOf(sessionId);
|
|
4543
|
+
if (session.active || session.pending || session.lifecycleHolds || session.mail.some((event) => event.deliveredTurn === STARTING)) {
|
|
4544
|
+
resolve({ busy: true });
|
|
4545
|
+
return;
|
|
4546
|
+
}
|
|
4547
|
+
admittedPrompts.add(sessionId);
|
|
4548
|
+
session.lifecycleHolds = (session.lifecycleHolds ?? 0) + 1;
|
|
4549
|
+
let valid = true;
|
|
4550
|
+
let used = false;
|
|
4551
|
+
let sending;
|
|
4552
|
+
try {
|
|
4553
|
+
const value = await run((input) => {
|
|
4554
|
+
if (!valid || used) return Promise.reject(new Error("The admitted prompt sender is no longer available"));
|
|
4555
|
+
used = true;
|
|
4556
|
+
sending = promptSession(sessionId, input);
|
|
4557
|
+
return sending;
|
|
4558
|
+
});
|
|
4559
|
+
resolve({ busy: false, value });
|
|
4560
|
+
} catch (error) {
|
|
4561
|
+
reject(error);
|
|
4562
|
+
} finally {
|
|
4563
|
+
valid = false;
|
|
4564
|
+
try {
|
|
4565
|
+
await sending;
|
|
4566
|
+
} finally {
|
|
4567
|
+
admittedPrompts.delete(sessionId);
|
|
4568
|
+
session.lifecycleHolds = Math.max(0, (session.lifecycleHolds ?? 1) - 1);
|
|
4569
|
+
if (!session.lifecycleHolds && !session.closed && session.wakeHeld) {
|
|
4570
|
+
session.wakeHeld = false;
|
|
4571
|
+
deliver(sessionId, session);
|
|
4572
|
+
}
|
|
4573
|
+
}
|
|
4574
|
+
}
|
|
4575
|
+
}).catch(reject);
|
|
2834
4576
|
}),
|
|
2835
4577
|
interrupt: (sessionId) => enqueue(() => interruptSession(sessionId)),
|
|
2836
|
-
|
|
4578
|
+
interruptTurn: (sessionId, turnId) => enqueue(async () => {
|
|
4579
|
+
if (sessions.get(sessionId)?.active !== turnId) return false;
|
|
4580
|
+
await interruptSession(sessionId);
|
|
4581
|
+
return true;
|
|
4582
|
+
}),
|
|
4583
|
+
configure: (sessionId, changes, options2) => enqueue(() => configureSession(sessionId, changes, options2?.onApplied)),
|
|
4584
|
+
branch: (request) => branchConversation(request),
|
|
4585
|
+
rebind: (sessionId, binding) => enqueue(() => rebindSession(sessionId, binding)),
|
|
4586
|
+
reload: (sessionId) => enqueue(() => reloadSession(sessionId)),
|
|
4587
|
+
compact: (sessionId) => requestCompact(sessionId),
|
|
4588
|
+
commands: (sessionId) => listCommands(sessionId),
|
|
4589
|
+
previewConfigure: (sessionId, changes) => previewConfigureSession(sessionId, changes),
|
|
4590
|
+
reconfigure: (sessionId, changes, options2) => enqueue(() => reconfigureSession(sessionId, changes, options2)),
|
|
4591
|
+
starting: (sessionId) => {
|
|
4592
|
+
const session = sessions.get(sessionId);
|
|
4593
|
+
return !!session && !session.closed && (admittedPrompts.has(sessionId) || !!session.pending || session.mail.some((event) => event.deliveredTurn === STARTING));
|
|
4594
|
+
},
|
|
4595
|
+
hold: (sessionId) => {
|
|
4596
|
+
const session = sessions.get(sessionId);
|
|
4597
|
+
if (!session || session.closed) return void 0;
|
|
4598
|
+
session.lifecycleHolds = (session.lifecycleHolds ?? 0) + 1;
|
|
4599
|
+
let released = false;
|
|
4600
|
+
return () => {
|
|
4601
|
+
if (released) return;
|
|
4602
|
+
released = true;
|
|
4603
|
+
session.lifecycleHolds = Math.max(0, (session.lifecycleHolds ?? 1) - 1);
|
|
4604
|
+
if (session.lifecycleHolds || session.closed) return;
|
|
4605
|
+
if (session.resumeHeld) {
|
|
4606
|
+
const expected = session.resumeHeld;
|
|
4607
|
+
session.resumeHeld = void 0;
|
|
4608
|
+
if (session.parked === expected) return continueParked(sessionId, session, expected);
|
|
4609
|
+
}
|
|
4610
|
+
if (session.parked || pauseOf(session.runtimeKind) || !session.wakeHeld) return;
|
|
4611
|
+
session.wakeHeld = false;
|
|
4612
|
+
deliver(sessionId, session);
|
|
4613
|
+
};
|
|
4614
|
+
},
|
|
2837
4615
|
close: (sessionId) => enqueue(async () => {
|
|
2838
4616
|
openOf(sessionId);
|
|
2839
4617
|
await closeSession(sessionId);
|
|
@@ -2857,7 +4635,7 @@ ${interrupted}`), text_elements: [] }] : [],
|
|
|
2857
4635
|
};
|
|
2858
4636
|
visit(rootId);
|
|
2859
4637
|
const questions = [...userQuestions.values()].map((pending) => pending.question).filter((question) => question.rootId === rootId);
|
|
2860
|
-
const asking = new Set(questions.map((question) => question.sessionId));
|
|
4638
|
+
const asking = new Set(questions.filter((question) => !question.gate).map((question) => question.sessionId));
|
|
2861
4639
|
const ids = new Set(tree.map(([id]) => id));
|
|
2862
4640
|
return {
|
|
2863
4641
|
rootId,
|
|
@@ -2909,6 +4687,21 @@ ${interrupted}`), text_elements: [] }] : [],
|
|
|
2909
4687
|
return pauseState();
|
|
2910
4688
|
},
|
|
2911
4689
|
pauses: () => pauseState(),
|
|
4690
|
+
holdForDisk(reason) {
|
|
4691
|
+
if (paused.all) return pauseState();
|
|
4692
|
+
pauseRuntime("all", { since: (/* @__PURE__ */ new Date()).toISOString(), by: "alpd", reason, cause: "disk" }, true);
|
|
4693
|
+
notice("error", (say) => say.diskFull(reason));
|
|
4694
|
+
return pauseState();
|
|
4695
|
+
},
|
|
4696
|
+
releaseDisk(by) {
|
|
4697
|
+
if (paused.all?.cause !== "disk") return pauseState();
|
|
4698
|
+
resumeRuntime("all", by, true);
|
|
4699
|
+
return pauseState();
|
|
4700
|
+
},
|
|
4701
|
+
diskHeld: () => paused.all?.cause === "disk",
|
|
4702
|
+
diskLow(free) {
|
|
4703
|
+
notice("warning", (say) => say.diskLow(free));
|
|
4704
|
+
},
|
|
2912
4705
|
async usage(refresh = false) {
|
|
2913
4706
|
const providers = await Promise.all(["codex", "claude"].map((kind) => cachedUsage(kind, refresh)));
|
|
2914
4707
|
const state = pauseState();
|
|
@@ -2939,6 +4732,10 @@ ${interrupted}`), text_elements: [] }] : [],
|
|
|
2939
4732
|
thinking: mapping.thinking
|
|
2940
4733
|
};
|
|
2941
4734
|
},
|
|
4735
|
+
syncGates(projectRoot) {
|
|
4736
|
+
if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) return Promise.reject(new Error("syncGates needs an absolute projectRoot"));
|
|
4737
|
+
return syncGates(projectRoot);
|
|
4738
|
+
},
|
|
2942
4739
|
async board(projectRoot) {
|
|
2943
4740
|
if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) throw new Error("board needs an absolute projectRoot");
|
|
2944
4741
|
return (await boardOf(path.resolve(projectRoot))).filter(live);
|
|
@@ -2956,6 +4753,10 @@ ${interrupted}`), text_elements: [] }] : [],
|
|
|
2956
4753
|
answer(questionId, reply) {
|
|
2957
4754
|
const pending = userQuestions.get(questionId);
|
|
2958
4755
|
if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
|
|
4756
|
+
if (pending.gate) {
|
|
4757
|
+
if (!reply.dismiss && (typeof reply.text !== "string" || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error("An answer needs text");
|
|
4758
|
+
return pending.gate.decide(reply);
|
|
4759
|
+
}
|
|
2959
4760
|
if (reply.dismiss) {
|
|
2960
4761
|
pending.settle("dismissed", void 0, reply.reason);
|
|
2961
4762
|
return;
|
|
@@ -2972,8 +4773,8 @@ ${interrupted}`), text_elements: [] }] : [],
|
|
|
2972
4773
|
recoverable() {
|
|
2973
4774
|
return [...inherited];
|
|
2974
4775
|
},
|
|
2975
|
-
recover(rootId, { continueRoot = false } = {}) {
|
|
2976
|
-
return enqueue(() => recoverTree(rootId, continueRoot));
|
|
4776
|
+
recover(rootId, { continueRoot = false, parkedRoot } = {}) {
|
|
4777
|
+
return enqueue(() => recoverTree(rootId, continueRoot, parkedRoot));
|
|
2977
4778
|
},
|
|
2978
4779
|
async abandon(rootId, reason) {
|
|
2979
4780
|
const entries = inherited.filter((entry) => entry.rootId === rootId);
|
|
@@ -2982,14 +4783,19 @@ ${interrupted}`), text_elements: [] }] : [],
|
|
|
2982
4783
|
return entries.map((entry) => ({ assignmentId: entry.assignmentId, agent: entry.agent, outcome: "failed", error: reason }));
|
|
2983
4784
|
},
|
|
2984
4785
|
async shutdown() {
|
|
4786
|
+
compactEchoes.clear();
|
|
2985
4787
|
closed = true;
|
|
2986
4788
|
await queue;
|
|
2987
4789
|
await Promise.all(
|
|
2988
4790
|
[...sessions.keys()].map(
|
|
2989
|
-
closeSession
|
|
4791
|
+
(id) => closeSession(id)
|
|
2990
4792
|
)
|
|
2991
4793
|
);
|
|
2992
4794
|
clearInterval(watchdog);
|
|
4795
|
+
if (gateWatch) clearInterval(gateWatch);
|
|
4796
|
+
for (const root of [...gateFiles.keys()]) unwatchGateFiles(root);
|
|
4797
|
+
await Promise.all(gateSyncs.values());
|
|
4798
|
+
await Promise.all(gateMarks);
|
|
2993
4799
|
await Promise.all(boards.values());
|
|
2994
4800
|
await boardDomain.flush();
|
|
2995
4801
|
await runLogWrites;
|
|
@@ -3002,8 +4808,11 @@ ${interrupted}`), text_elements: [] }] : [],
|
|
|
3002
4808
|
listeners.clear();
|
|
3003
4809
|
}
|
|
3004
4810
|
};
|
|
4811
|
+
return api;
|
|
3005
4812
|
}
|
|
3006
4813
|
export {
|
|
4814
|
+
CURATE_MARKER,
|
|
3007
4815
|
DEFAULT_TEAM,
|
|
4816
|
+
WorkspaceMutationError,
|
|
3008
4817
|
createAlpRuntime
|
|
3009
4818
|
};
|