@anhlp/alp-runtime 0.0.1-beta.5 → 0.0.1-beta.7

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.
@@ -168,6 +168,17 @@ export declare class ClaudeTransport {
168
168
  }[];
169
169
  };
170
170
  }>;
171
+ /**
172
+ * Claude's slash commands, skills included, for the composer (t-f628); none before the session starts.
173
+ * Not the ones whose work ALP does itself (t-efa3): /clear moves Claude to a new conversation ALP does not
174
+ * follow, and /compact and /rewind skip ALP's checkpoint and its rewind of the timeline.
175
+ */
176
+ commands(): Promise<{
177
+ kind: "skill" | "command";
178
+ argumentHint?: string | undefined;
179
+ name: string;
180
+ description: string;
181
+ }[]>;
171
182
  initialize(): Promise<void>;
172
183
  /** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
173
184
  probeModels(signal?: AbortSignal): Promise<{
@@ -13,6 +13,7 @@ import { claudeToolDetail, resultText } from "./tool-detail.js";
13
13
  import { CLOSE_REASONS, GATE_KINDS, TASK_STATUSES, TASK_TYPES } from "@anhlp/alp-core/tasks";
14
14
  import { commandDecision } from "@anhlp/alp-core/permissions";
15
15
  var CLAUDE_SDK = ["@anthropic-ai", "claude-agent-sdk"].join("/");
16
+ var claudeSdk = () => import(CLAUDE_SDK);
16
17
  var bounded = (schema, limits) => z.preprocess((value, ctx) => {
17
18
  const error = inputLimitError(value, limits);
18
19
  if (error) ctx.addIssue({ code: "custom", message: error });
@@ -174,6 +175,7 @@ var toolShapes = {
174
175
  }
175
176
  };
176
177
  var SKILL_PLUGIN = "alp";
178
+ var ALP_HANDLED_COMMANDS = /* @__PURE__ */ new Set(["clear", "compact", "rewind"]);
177
179
  function skillPlugin(directory, skills) {
178
180
  rmSync(directory, { recursive: true, force: true });
179
181
  mkdirSync(path.join(directory, ".claude-plugin"), { recursive: true });
@@ -293,7 +295,7 @@ function claudePermissions(sandbox, currentSandbox, rules, ask) {
293
295
  var claudeLimited = (info) => info?.status === "rejected" && info.overageStatus !== "allowed" && info.overageStatus !== "allowed_warning";
294
296
  var BOOT_MS = 15e3;
295
297
  async function claudeChain(sessionId, dir) {
296
- const { getSessionMessages } = await import(CLAUDE_SDK);
298
+ const { getSessionMessages } = await claudeSdk();
297
299
  let messages = dir ? await getSessionMessages(sessionId, { dir }) : [];
298
300
  if (!messages.length) messages = await getSessionMessages(sessionId);
299
301
  return messages.filter((message) => (message.type === "user" || message.type === "assistant") && typeof message.uuid === "string").map((message) => {
@@ -375,11 +377,25 @@ var ClaudeTransport = class {
375
377
  usage: claudeUsage(usage)
376
378
  };
377
379
  }
380
+ /**
381
+ * Claude's slash commands, skills included, for the composer (t-f628); none before the session starts.
382
+ * Not the ones whose work ALP does itself (t-efa3): /clear moves Claude to a new conversation ALP does not
383
+ * follow, and /compact and /rewind skip ALP's checkpoint and its rewind of the timeline.
384
+ */
385
+ async commands() {
386
+ const listed = this.query ? await optionalRead(async () => this.query.supportedCommands(), 1e4) : void 0;
387
+ return (Array.isArray(listed) ? listed : []).filter((command) => typeof command?.name === "string" && command.name && !ALP_HANDLED_COMMANDS.has(command.name)).map((command) => ({
388
+ name: command.name,
389
+ description: typeof command.description === "string" ? command.description : "",
390
+ ...command.argumentHint ? { argumentHint: command.argumentHint } : {},
391
+ kind: command.name.startsWith(`${SKILL_PLUGIN}:`) ? "skill" : "command"
392
+ }));
393
+ }
378
394
  async initialize() {
379
395
  }
380
396
  /** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
381
397
  async probeModels(signal) {
382
- const { query } = await import(CLAUDE_SDK);
398
+ const { query } = await claudeSdk();
383
399
  if (signal?.aborted) throw new Error("aborted");
384
400
  const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } });
385
401
  const stop = () => probe.close();
@@ -395,7 +411,7 @@ var ClaudeTransport = class {
395
411
  /** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
396
412
  async probeUsage() {
397
413
  if (this.closed) return void 0;
398
- const { query } = await import(CLAUDE_SDK);
414
+ const { query } = await claudeSdk();
399
415
  const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } });
400
416
  try {
401
417
  return await probe.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
@@ -424,7 +440,7 @@ var ClaudeTransport = class {
424
440
  }
425
441
  if (method === "thread/chain") return { entries: await claudeChain(params.threadId, params.cwd ?? this.cwd) };
426
442
  if (method === "thread/delete") {
427
- const { deleteSession } = await import(CLAUDE_SDK);
443
+ const { deleteSession } = await claudeSdk();
428
444
  await deleteSession(params.threadId, params.cwd ? { dir: params.cwd } : {});
429
445
  return {};
430
446
  }
@@ -520,7 +536,7 @@ var ClaudeTransport = class {
520
536
  if (this.bootError) throw this.bootError;
521
537
  }
522
538
  async start(from) {
523
- const { createSdkMcpServer, query, tool } = await import(CLAUDE_SDK);
539
+ const { createSdkMcpServer, query, tool } = await claudeSdk();
524
540
  const config = this.config;
525
541
  const mcpServers = this.convertMcp(config.mcpServers);
526
542
  if (config.dynamicTools.length) {
@@ -8,10 +8,19 @@ import type { AcpProvider } from './acp-transport.js';
8
8
  import type { AntigravityProvider } from './antigravity-transport.js';
9
9
  import type { GitHubRunner } from './github.js';
10
10
  import type { AttachmentReader } from './attachments.js';
11
+ /** A slash command or skill an agent's composer offers after "/" (t-f628). */
12
+ export type RuntimeCommand = {
13
+ name: string;
14
+ description: string;
15
+ argumentHint?: string;
16
+ kind: 'command' | 'skill';
17
+ };
11
18
  export type RuntimeTransport = {
12
19
  request(method: string, params: any): Promise<any>;
13
20
  initialize(): Promise<void>;
14
21
  orchestrationContext?: () => Promise<unknown>;
22
+ /** The runtime's own slash commands and skills for the composer (t-f628); omitted, the runtime offers none. */
23
+ commands?: () => Promise<RuntimeCommand[]>;
15
24
  onNotification(listener: (method: string, params: any) => void): void;
16
25
  onFailure(listener: (error: unknown) => void): void;
17
26
  close(): Promise<void>;
@@ -155,14 +164,19 @@ export type AlpRuntime = {
155
164
  status(sessionId: string): TreeStatus | undefined;
156
165
  /** Questions agents asked the user that wait for an answer. */
157
166
  questions(): UserQuestion[];
158
- /** Answers or dismisses a question to the user. */
167
+ /**
168
+ * Answers or dismisses a question to the user. A gate card's answer returns a promise that
169
+ * settles once the decision is written, and rejects when it decides nothing: another answer is
170
+ * being recorded or another channel decided first (code GATE_BUSY or GATE_DECIDED), or the
171
+ * write failed (t-595d).
172
+ */
159
173
  answer(questionId: string, reply: {
160
174
  text?: string;
161
175
  dismiss?: boolean;
162
176
  reason?: string; /** Where the user answered a gate card: paseo or web. */
163
177
  channel?: 'paseo' | 'web';
164
- }): void;
165
- /** Mirrors the project's open human gates as cards on its main session and tells main of the user's gate decisions, once each (t-ccac). */
178
+ }): void | Promise<void>;
179
+ /** Mirrors the project's open human gates as cards on its main session and tells main of the user's gate decisions, at least once each (t-ccac, t-595d). */
166
180
  syncGates?(projectRoot: string): Promise<void>;
167
181
  /** Mails a note from the user to any live session, such as an assignment the user wants to redirect. */
168
182
  message(sessionId: string, text: string): void;
@@ -243,6 +257,8 @@ export type AlpRuntime = {
243
257
  compact?(sessionId: string): {
244
258
  status: 'started' | 'deferred' | 'running';
245
259
  };
260
+ /** The slash commands and skills a live session's composer offers (t-f628): its runtime's, then its ALP skills. */
261
+ commands?(sessionId: string): Promise<RuntimeCommand[]>;
246
262
  /**
247
263
  * Holds the turns the runtime would start by itself on this session (mail wakes) while a lifecycle
248
264
  * operation changes its conversation (a rewind, later a reload or live configure): mail stays queued
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { createAlpRuntime, DEFAULT_TEAM, WorkspaceMutationError } from './runtime.js';
2
2
  export type { WorkspaceMutationReason, AlpRuntime, RuntimeOptions, OpenOptions, RuntimeTransport, PromptInput, PromptContent, SessionPreview } from './runtime.js';
3
3
  export { ConversationError } from './contracts.js';
4
- export type { BranchRequest, ConversationErrorReason, NativeBase, NativeBinding, ConfigureChanges, ConfigureResult, ConfigurePreview, EffectiveConfig } from './contracts.js';
4
+ export type { RuntimeCommand, BranchRequest, ConversationErrorReason, NativeBase, NativeBinding, ConfigureChanges, ConfigureResult, ConfigurePreview, EffectiveConfig } from './contracts.js';
5
5
  export type { AlpEvent, AlpError, Envelope, SessionSnapshot, TimelineItem, TurnOrigin, AssignmentSnapshot, UserQuestion, TreeStatus, SessionState } from './events.js';
6
6
  export { resolveSession, InstructionsAdapter, skillDescription } from './resolve.js';
7
7
  export type { SessionSpec, HostMcpServer, ResolvedSession, RuntimeKind } from './resolve.js';
@@ -22,6 +22,7 @@ export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, skillPlugin
22
22
  export { MAIL_BATCH_CHARS, MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from './mailbox.js';
23
23
  export type { MailEvent, MailKind } from './mailbox.js';
24
24
  export { createCopy, gitEnvironment, reattachWorktree, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
25
+ export type { LeftWorktree } from './workspace.js';
25
26
  export { OWN_START, processStartedAt, sameProcessAlive } from './process-info.js';
26
27
  export type { Worktree, WorktreeChange } from './workspace.js';
27
28
  export { PIN_KINDS, renderBoard, renderPin } from './board.js';
package/dist/resolve.d.ts CHANGED
@@ -52,6 +52,7 @@ export declare function resolveSession(spec: SessionSpec, options?: {
52
52
  language?: string; /** False for a preview: it writes nothing (D31). */
53
53
  initialize?: boolean;
54
54
  }): Promise<{
55
+ commands: string[];
55
56
  autocompact: number | undefined;
56
57
  compact: import("./compact.js").CompactSettings;
57
58
  language: string;
package/dist/resolve.js CHANGED
@@ -224,6 +224,8 @@ ${project}` : "");
224
224
  keepThread: spec.keepThread ?? false,
225
225
  // ALPD §57: the window the agent works in before its runtime compacts; absent, the model's.
226
226
  ...agent.context ? { context: agent.context } : {},
227
+ // t-efa3: the runtime's own commands and skills the "/" list offers; its ALP skills always.
228
+ commands: Array.isArray(profile?.commands) ? profile.commands.filter((name) => typeof name === "string") : [],
227
229
  autocompact: typeof profile?.autocompact === "number" ? profile.autocompact : typeof agent.autocompact === "number" ? agent.autocompact : void 0,
228
230
  // t-0e56: when main's context is compacted at a turn boundary.
229
231
  compact: compactSettings(projectSettings.compact),
package/dist/runtime.js CHANGED
@@ -16,7 +16,7 @@ import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, roleOf, taskActions, task
16
16
  import { nativeEnvironment, createTransport } from "./providers.js";
17
17
  import { nativeMode, codexApproval, profileEfforts, nativeSessionConfig } from "./session-config.js";
18
18
  import { createHash, randomUUID } from "node:crypto";
19
- import { readFileSync, realpathSync } from "node:fs";
19
+ import { readFileSync, realpathSync, watch as watchFiles } from "node:fs";
20
20
  import { appendFile, mkdir, open, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
21
21
  import { moveFile } from "@anhlp/alp-core/atomic";
22
22
  import os from "node:os";
@@ -32,7 +32,7 @@ import { isTrusted, trustProject } from "@anhlp/alp-core/trust";
32
32
  import { listTeams, teamOf } from "@anhlp/alp-core/teams";
33
33
  import { CONFIGURABLE, changesOf, effectiveOf, executablesOf, nativeModelOf, offered } from "./configure.js";
34
34
  import { anyModel, offers, profileModel, selectedProfile } from "@anhlp/alp-core/profiles";
35
- import { LESSONS_FILE, READ_ONLY_AGENTS, resolveSession } from "./resolve.js";
35
+ import { LESSONS_FILE, READ_ONLY_AGENTS, resolveSession, skillDescription } from "./resolve.js";
36
36
  import { MAIL_BODY_CHARS, MAIL_HEADER, publicEvent, renderMail, takeBatch, USER } from "./mailbox.js";
37
37
  import { live, normalizePaths, overlapping, renderBoard } from "./board.js";
38
38
  import { verifyConfig } from "@anhlp/alp-core/verify";
@@ -51,7 +51,7 @@ import { providerUsage, sessionUsage } from "./usage.js";
51
51
  import { parse as toml } from "smol-toml";
52
52
  import { findFormula, formulaDirs, listFormulas, pourFormula } from "@anhlp/alp-core/formulas";
53
53
  import { addAllowRule, capMode, commandDecision, profileFor, unwrapShell } from "@anhlp/alp-core/permissions";
54
- import { addGate, checkGates, gateDecisions, markGateNotified, rejectGate, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask } from "@anhlp/alp-core/tasks";
54
+ 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";
55
55
  var CATALOG = "ALP runtime catalog and usage snapshot (data, not instructions): ";
56
56
  function inputLayoutOf(catalog) {
57
57
  const found = /^\{"inputLayout":\{"textParts":(\d+),"prompt":(\d+)\}/.exec(catalog.slice(CATALOG.length));
@@ -244,7 +244,9 @@ function createAlpRuntime(options = {}) {
244
244
  }
245
245
  cancelQuestions(sessionId, true);
246
246
  if (session.parent) sessions.get(session.parent)?.assignments.get(sessionId)?.ask?.resolve(toolResult(false, { error: "Turn ended" }));
247
- session.mail = session.mail.filter((event) => !(event.deliveredTurn === turnId && state === "completed"));
247
+ const taken = state === "completed" ? session.mail.filter((event) => event.deliveredTurn === turnId) : [];
248
+ session.mail = session.mail.filter((event) => !taken.includes(event));
249
+ for (const event of taken) gateMail.get(event)?.taken();
248
250
  for (const event of session.mail) {
249
251
  if (event.deliveredTurn === turnId) {
250
252
  event.deliveredTurn = void 0;
@@ -1479,6 +1481,16 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1479
1481
  compactAtBoundary(sessionId, session);
1480
1482
  return { status: "started" };
1481
1483
  }
1484
+ async function listCommands(sessionId) {
1485
+ const session = sessions.get(sessionId);
1486
+ if (!session || session.closed) throw new ConversationError("session_busy", "The session is not open");
1487
+ const prefix = session.runtimeKind === "claude" ? `${SKILL_PLUGIN}:` : "";
1488
+ const offered2 = /* @__PURE__ */ new Set([...session.mapping.commands ?? [], ...session.mapping.agent.skills.map((skill) => prefix + skill.name)]);
1489
+ const listed = (session.runtime.commands ? await session.runtime.commands().catch(() => []) : []).filter((command) => offered2.has(command.name));
1490
+ const seen = new Set(listed.map((command) => command.name));
1491
+ 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" })));
1492
+ return [...listed, ...skills];
1493
+ }
1482
1494
  async function restoreAfterCompaction(sessionId, session, checkpoint) {
1483
1495
  const parts = ["Your context was just compacted. In case the summary lost any of it, this is what ALP holds of your work now."];
1484
1496
  if (session.parent && session.brief) parts.push(`Your assignment from ${session.parentAgent ?? "your requester"}, as it was given:
@@ -2521,6 +2533,9 @@ The user answered: "${answer}"`);
2521
2533
  }
2522
2534
  }
2523
2535
  const gateSyncs = /* @__PURE__ */ new Map();
2536
+ const gateMail = /* @__PURE__ */ new WeakMap();
2537
+ const gateTaken = /* @__PURE__ */ new Set();
2538
+ const gateMarks = /* @__PURE__ */ new Set();
2524
2539
  const gateCardId = (taskId, gateId) => `gate-${taskId}-${gateId}`;
2525
2540
  function mainSessionOf(projectRoot) {
2526
2541
  for (const [id, session] of sessions) {
@@ -2547,10 +2562,23 @@ The user answered: "${answer}"`);
2547
2562
  const { tasks } = await loadTasks(projectRoot);
2548
2563
  const main = mainSessionOf(projectRoot);
2549
2564
  if (main) for (const { task, gate, decision, record: record2 } of gateDecisions(tasks)) {
2550
- if (!await markGateNotified(projectRoot, task.id, gate.id, decision)) continue;
2565
+ const key = JSON.stringify([projectRoot, task.id, gate.id, decision, record2.at]);
2566
+ if (gateTaken.has(key) || main.session.mail.some((event) => gateMail.get(event)?.key === key)) continue;
2551
2567
  const choice = decision === "approved" ? record2.choice : void 0;
2552
2568
  const words2 = decision === "approved" ? `The user approved human gate ${gate.id} of ${task.id} in ${record2.channel}${choice ? `, choosing "${choice}"` : ""}${record2.note ? `: ${record2.note}` : ""}.` : `The user rejected human gate ${gate.id} of ${task.id} in ${record2.channel}${record2.reason ? `: ${record2.reason}` : ""}. The gate stays open.`;
2553
- post(main.id, { kind: "result", from: "ALP", assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words2} Task: ${task.title}` });
2569
+ 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.` });
2570
+ gateMail.set(mail, {
2571
+ key,
2572
+ taken: () => {
2573
+ gateTaken.add(key);
2574
+ const mark = markGateNotified(projectRoot, task.id, gate.id, decision, record2.at).catch((error) => {
2575
+ gateTaken.delete(key);
2576
+ runLog(main.id, { event: "gate.mark.failed", projectRoot, taskId: task.id, gateId: gate.id, error: errorData(error).message });
2577
+ });
2578
+ gateMarks.add(mark);
2579
+ void mark.finally(() => gateMarks.delete(mark));
2580
+ }
2581
+ });
2554
2582
  runLog(main.id, { event: "gate.decision", projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record2.channel, ...choice ? { choice } : {} });
2555
2583
  }
2556
2584
  const wanted = /* @__PURE__ */ new Map();
@@ -2571,11 +2599,18 @@ The user answered: "${answer}"`);
2571
2599
  for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
2572
2600
  }
2573
2601
  let gateWatch;
2574
- function startGateWatch() {
2575
- if (gateWatch || options.gateSyncMs === 0) return;
2602
+ const gateFiles = /* @__PURE__ */ new Map();
2603
+ function startGateWatch(projectRoot) {
2604
+ if (options.gateSyncMs === 0) return;
2605
+ watchGateFiles(path.resolve(projectRoot));
2606
+ if (gateWatch) return;
2576
2607
  gateWatch = setInterval(() => {
2577
2608
  const roots = new Set([...sessions.values()].filter((session) => !session.closed && !session.parent && session.role !== "supervisor" && session.mapping.agent.name === mainOf(session.mapping)).map((session) => path.resolve(session.mapping.agent.projectRoot)));
2578
- for (const root of roots) void syncGates(root);
2609
+ for (const root of roots) {
2610
+ watchGateFiles(root);
2611
+ void syncGates(root);
2612
+ }
2613
+ for (const root of gateFiles.keys()) if (!roots.has(root)) unwatchGateFiles(root);
2579
2614
  if (!roots.size) {
2580
2615
  clearInterval(gateWatch);
2581
2616
  gateWatch = void 0;
@@ -2583,6 +2618,33 @@ The user answered: "${answer}"`);
2583
2618
  }, options.gateSyncMs ?? 5e3);
2584
2619
  gateWatch.unref?.();
2585
2620
  }
2621
+ function watchGateFiles(root) {
2622
+ if (closed || gateFiles.has(root)) return;
2623
+ try {
2624
+ const entry = {
2625
+ // A burst of writes (a save, its ledger, a mark) syncs once.
2626
+ watcher: watchFiles(path.join(root, TASKS_DIR), () => {
2627
+ if (entry.timer || closed) return;
2628
+ entry.timer = setTimeout(() => {
2629
+ entry.timer = void 0;
2630
+ void syncGates(root);
2631
+ }, 50);
2632
+ entry.timer.unref?.();
2633
+ })
2634
+ };
2635
+ entry.watcher.on("error", () => unwatchGateFiles(root));
2636
+ entry.watcher.unref?.();
2637
+ gateFiles.set(root, entry);
2638
+ } catch {
2639
+ }
2640
+ }
2641
+ function unwatchGateFiles(root) {
2642
+ const entry = gateFiles.get(root);
2643
+ if (!entry) return;
2644
+ gateFiles.delete(root);
2645
+ clearTimeout(entry.timer);
2646
+ entry.watcher.close();
2647
+ }
2586
2648
  function showGateCard(sessionId, session, projectRoot, task, gate) {
2587
2649
  const say = wordsFor(session);
2588
2650
  const vietnamese = say.approve === words("vi").approve;
@@ -2610,9 +2672,9 @@ ${gate.note ?? ""}`,
2610
2672
  }
2611
2673
  async function decideGate(projectRoot, question, card, reply, choices) {
2612
2674
  const defaults = !choices;
2613
- if (card.deciding) return;
2614
- card.deciding = true;
2615
2675
  const { taskId, gateId } = question.gate;
2676
+ if (card.deciding) throw gateRefusal("GATE_BUSY", `An answer to gate ${gateId} of ${taskId} is already being recorded`);
2677
+ card.deciding = true;
2616
2678
  const channel = reply.channel ?? "web";
2617
2679
  const text2 = reply.text?.trim();
2618
2680
  const approve2 = !reply.dismiss && !!text2 && (defaults ? APPROVALS.includes(text2.toLowerCase()) : choices.includes(text2));
@@ -2625,16 +2687,21 @@ ${gate.note ?? ""}`,
2625
2687
  if (error?.code !== "TASK_CHANGED") throw error;
2626
2688
  const current = (await loadTasks(projectRoot)).tasks.find((entry) => entry.id === taskId);
2627
2689
  const gate = current?.gates.find((entry) => entry.id === gateId);
2628
- if (!current || current.status === "closed" || !gate || gate.resolved || gate.rejected) return;
2690
+ if (!current || current.status === "closed" || !gate) throw gateRefusal("GATE_DECIDED", `Gate ${gateId} of ${taskId} is no longer open`);
2691
+ 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}` : ""}`);
2629
2692
  await write(current.rev);
2630
2693
  }
2631
2694
  } catch (error) {
2632
2695
  runLog(question.rootId, { event: "gate.answer.failed", questionId: question.id, error: errorData(error).message });
2696
+ throw error;
2633
2697
  } finally {
2634
2698
  card.deciding = false;
2635
2699
  await syncGates(projectRoot);
2636
2700
  }
2637
2701
  }
2702
+ function gateRefusal(code, message) {
2703
+ return Object.assign(new Error(message), { code });
2704
+ }
2638
2705
  function askTool(sessionId, session, args) {
2639
2706
  const parent = session.parent ? sessions.get(session.parent) : void 0;
2640
2707
  const assignment = parent?.assignments.get(sessionId);
@@ -3164,7 +3231,7 @@ ${digest}` : "")
3164
3231
  });
3165
3232
  if (!session.parent && session.role !== "supervisor" && mapping.agent.name === mainOf(mapping)) {
3166
3233
  void syncGates(mapping.agent.projectRoot);
3167
- startGateWatch();
3234
+ startGateWatch(mapping.agent.projectRoot);
3168
3235
  }
3169
3236
  if (history === "replay") {
3170
3237
  for (const turn of result.thread.turns ?? []) {
@@ -4043,6 +4110,7 @@ ${interrupted}`), text_elements: [] }] : []
4043
4110
  const after = mail.length && !wake ? [{ type: "text", text: promptSafe(renderMail(mail, session.parentAgent)), text_elements: [] }] : [];
4044
4111
  const inputLayout = { textParts: 1 + before.length + 1 + attached.length + after.length, prompt: 1 + before.length };
4045
4112
  const listed = attached.map(({ attachment }) => attachmentMeta(attachment));
4113
+ 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;
4046
4114
  const nativeInput = [
4047
4115
  { type: "text", text: promptSafe(CATALOG + JSON.stringify({ inputLayout, ...orchestration, ...listed.length ? { attachments: listed } : {} })), text_elements: [] },
4048
4116
  ...before,
@@ -4053,7 +4121,9 @@ ${interrupted}`), text_elements: [] }] : []
4053
4121
  },
4054
4122
  ...attached.map(({ attachment, staged }) => ({ type: "text", text: promptSafe(attachmentPart(attachment, staged)), text_elements: [] })),
4055
4123
  ...images.map((image) => ({ type: "image", url: `data:${image.mimeType};base64,${image.data}` })),
4056
- ...after
4124
+ ...after,
4125
+ // "/<skill> ..." from the user loads that ALP skill in Codex, as its own $<skill> does (t-efa3).
4126
+ ...invoked ? [{ type: "skill", name: invoked.name, path: invoked.path }] : []
4057
4127
  ];
4058
4128
  const result = prompt.delivery === "steer" ? await session.runtime.request(
4059
4129
  "turn/steer",
@@ -4306,6 +4376,7 @@ ${interrupted}`), text_elements: [] }] : []
4306
4376
  rebind: (sessionId, binding) => enqueue(() => rebindSession(sessionId, binding)),
4307
4377
  reload: (sessionId) => enqueue(() => reloadSession(sessionId)),
4308
4378
  compact: (sessionId) => requestCompact(sessionId),
4379
+ commands: (sessionId) => listCommands(sessionId),
4309
4380
  previewConfigure: (sessionId, changes) => previewConfigureSession(sessionId, changes),
4310
4381
  reconfigure: (sessionId, changes, options2) => enqueue(() => reconfigureSession(sessionId, changes, options2)),
4311
4382
  starting: (sessionId) => {
@@ -4475,8 +4546,7 @@ ${interrupted}`), text_elements: [] }] : []
4475
4546
  if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
4476
4547
  if (pending.gate) {
4477
4548
  if (!reply.dismiss && (typeof reply.text !== "string" || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error("An answer needs text");
4478
- void pending.gate.decide(reply);
4479
- return;
4549
+ return pending.gate.decide(reply);
4480
4550
  }
4481
4551
  if (reply.dismiss) {
4482
4552
  pending.settle("dismissed", void 0, reply.reason);
@@ -4513,7 +4583,9 @@ ${interrupted}`), text_elements: [] }] : []
4513
4583
  );
4514
4584
  clearInterval(watchdog);
4515
4585
  if (gateWatch) clearInterval(gateWatch);
4586
+ for (const root of [...gateFiles.keys()]) unwatchGateFiles(root);
4516
4587
  await Promise.all(gateSyncs.values());
4588
+ await Promise.all(gateMarks);
4517
4589
  await Promise.all(boards.values());
4518
4590
  await boardDomain.flush();
4519
4591
  await runLogWrites;
@@ -81,14 +81,33 @@ export declare function mergeWorktree(worktree: Worktree, change: WorktreeChange
81
81
  export declare function removeWorktree(worktree: Worktree, { deleteBranch }?: {
82
82
  deleteBranch?: boolean | undefined;
83
83
  }): Promise<void>;
84
+ /**
85
+ * Why reclaimWorktrees left a directory in place: `invalid`, not the top level of a working git
86
+ * worktree; `not-linked`, a repository of its own rather than a worktree of one; `other-branch`,
87
+ * another branch or a detached HEAD, which does not hold this work; `commit-failed`, its work could
88
+ * not be committed (`detail` says why); `uncommitted`, something was still not committed after
89
+ * that; `ignored-files`, its work is committed but it holds ignored files that exist nowhere else.
90
+ */
91
+ export type LeftWorktree = {
92
+ name: string;
93
+ path: string;
94
+ reason: 'invalid' | 'not-linked' | 'other-branch' | 'commit-failed' | 'uncommitted' | 'ignored-files';
95
+ branch?: string;
96
+ detail?: string;
97
+ files?: string[];
98
+ };
84
99
  /**
85
100
  * After a crash: commits work left in worktrees under `root` to their branches and
86
- * removes the directories. Returns the branches that were kept. A directory is removed
87
- * only once everything in it is committed to its own `alp/<name>` branch; any other one
88
- * (invalid git metadata, a failed commit, another branch checked out, a detached HEAD)
89
- * stays untouched, so recovery reuses or preserves it and nothing uncommitted is lost.
101
+ * removes the directories. Returns the branches that were kept, and the directories left in
102
+ * place with the reason. A directory is removed only once everything in it is committed to
103
+ * its own `alp/<name>` branch and it holds no ignored file to keep (`.env*`); any other one
104
+ * stays, so recovery reuses or preserves it and nothing uncommitted is lost. Stale locks a
105
+ * killed git command left in such a worktree are removed first (clearStaleLocks).
90
106
  */
91
- export declare function reclaimWorktrees(root: string): Promise<string[]>;
107
+ export declare function reclaimWorktrees(root: string): Promise<{
108
+ kept: string[];
109
+ left: LeftWorktree[];
110
+ }>;
92
111
  /**
93
112
  * A disposable copy of a checkout for an assignment that may build and test but
94
113
  * must not touch the requester's tree (ALPD §26): a detached worktree at the
package/dist/workspace.js CHANGED
@@ -112,8 +112,8 @@ async function validWorktree(directory) {
112
112
  async function reattachWorktree(worktree) {
113
113
  const exists = !!await stat(worktree.path).catch(() => void 0);
114
114
  if (exists && await validWorktree(worktree.path)) {
115
- const gitdir = await git(worktree.path, ["rev-parse", "--absolute-git-dir"]);
116
- if (gitdir.code === 0) await rm(path.join(gitdir.stdout.trim(), "index.lock"), { force: true });
115
+ const dirs = await gitDirs(worktree.path);
116
+ if (dirs) await clearStaleLocks(dirs, worktree.branch);
117
117
  return worktree;
118
118
  }
119
119
  if (!await branchExists(worktree.checkout, worktree.branch)) throw new Error(`Branch ${worktree.branch} of the worktree no longer exists`);
@@ -191,29 +191,92 @@ async function removeWorktree(worktree, { deleteBranch = false } = {}) {
191
191
  await git(worktree.checkout, ["worktree", "prune"]);
192
192
  if (deleteBranch) await git(worktree.checkout, ["branch", "-D", worktree.branch]);
193
193
  }
194
+ async function gitDirs(target) {
195
+ const result = await git(target, ["rev-parse", "--path-format=absolute", "--absolute-git-dir", "--git-common-dir"]);
196
+ if (result.code !== 0) return void 0;
197
+ const [own, common] = result.stdout.trim().split("\n").map((line) => path.resolve(line.trim()));
198
+ return own && common ? { own, common } : void 0;
199
+ }
200
+ var SHARED_LOCK_STALE_MS = 1e4;
201
+ async function clearStaleLocks(dirs, branch) {
202
+ if (dirs.own === dirs.common) return;
203
+ const own = (await readdir(dirs.own).catch(() => [])).filter((name) => name.endsWith(".lock"));
204
+ const refs = (await readdir(path.join(dirs.own, "refs"), { recursive: true }).catch(() => [])).filter((name) => name.endsWith(".lock")).map((name) => path.join("refs", name));
205
+ for (const name of [...own, ...refs]) await unlink(path.join(dirs.own, name)).catch(() => {
206
+ });
207
+ const shared = `${path.join(dirs.common, "refs", "heads", ...branch.split("/"))}.lock`;
208
+ const info = await lstat(shared).catch(() => void 0);
209
+ if (info?.isFile() && Date.now() - info.mtimeMs >= SHARED_LOCK_STALE_MS) await unlink(shared).catch(() => {
210
+ });
211
+ }
212
+ var KEEP_IGNORED = /^\.env/;
213
+ async function ignoredToKeep(target) {
214
+ const result = await git(target, ["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"]);
215
+ if (result.code !== 0) return void 0;
216
+ return result.stdout.split("\0").filter(Boolean).map((entry) => entry.replace(/\/$/, "")).filter((entry) => KEEP_IGNORED.test(path.posix.basename(entry))).sort();
217
+ }
218
+ var firstLine = (result) => (result.stderr || result.stdout).trim().split("\n")[0] ?? "";
194
219
  async function reclaimWorktrees(root) {
195
220
  const kept = [];
221
+ const left = [];
196
222
  const entries = await readdir(root).catch(() => []);
197
223
  for (const name of entries) {
198
224
  const target = path.join(root, name);
225
+ const leave = (reason, extra = {}) => {
226
+ left.push({ name, path: target, reason, ...extra });
227
+ };
199
228
  if (!(await stat(target).catch(() => void 0))?.isDirectory()) continue;
200
- if (!await validWorktree(target)) continue;
201
- const common = await git(target, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
202
- if (common.code !== 0) continue;
203
- const checkout = path.dirname(common.stdout.trim());
229
+ if (!await validWorktree(target)) {
230
+ leave("invalid");
231
+ continue;
232
+ }
233
+ const dirs = await gitDirs(target);
234
+ if (!dirs) {
235
+ leave("invalid");
236
+ continue;
237
+ }
238
+ if (dirs.own === dirs.common) {
239
+ leave("not-linked");
240
+ continue;
241
+ }
242
+ const checkout = path.dirname(dirs.common);
204
243
  const ref = await git(target, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
205
244
  const branch = ref.stdout.trim();
206
- if (ref.code !== 0 || branch !== `alp/${name}`) continue;
207
- if ((await git(target, ["add", "-A"])).code !== 0) continue;
245
+ if (ref.code !== 0 || branch !== `alp/${name}`) {
246
+ leave("other-branch", ref.code === 0 && branch ? { branch } : {});
247
+ continue;
248
+ }
249
+ await clearStaleLocks(dirs, branch);
250
+ const added = await git(target, ["add", "-A"]);
251
+ if (added.code !== 0) {
252
+ leave("commit-failed", { branch, detail: firstLine(added) });
253
+ continue;
254
+ }
208
255
  if ((await git(target, ["diff", "--cached", "--quiet"])).code === 1) {
209
- if ((await git(target, [...IDENTITY, "commit", "--quiet", "--no-verify", "-m", "alp: work left by an interrupted assignment"])).code !== 0) continue;
256
+ const committed = await git(target, [...IDENTITY, "commit", "--quiet", "--no-verify", "-m", "alp: work left by an interrupted assignment"]);
257
+ if (committed.code !== 0) {
258
+ leave("commit-failed", { branch, detail: firstLine(committed) });
259
+ continue;
260
+ }
210
261
  }
211
262
  const status = await git(target, ["status", "--porcelain", "--ignored=no"]);
212
- if (status.code !== 0 || status.stdout.trim()) continue;
263
+ if (status.code !== 0 || status.stdout.trim()) {
264
+ leave("uncommitted", { branch });
265
+ continue;
266
+ }
267
+ const ignored = await ignoredToKeep(target);
268
+ if (!ignored) {
269
+ leave("ignored-files", { branch, detail: "git could not list its ignored files" });
270
+ continue;
271
+ }
272
+ if (ignored.length) {
273
+ leave("ignored-files", { branch, files: ignored });
274
+ continue;
275
+ }
213
276
  await removeWorktree({ checkout, path: target, workdir: target, branch, base: "" });
214
277
  kept.push(branch);
215
278
  }
216
- return kept;
279
+ return { kept, left };
217
280
  }
218
281
  async function createCopy(workdir, root, id) {
219
282
  const checkout = await checkoutOf(workdir);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-runtime",
3
- "version": "0.0.1-beta.5",
3
+ "version": "0.0.1-beta.7",
4
4
  "type": "module",
5
5
  "description": "ALP runtime module",
6
6
  "files": [
@@ -230,8 +230,8 @@
230
230
  "node": ">=22.12"
231
231
  },
232
232
  "dependencies": {
233
- "@anhlp/alp-core": "0.0.1-beta.5",
234
- "@anhlp/alp-protocol": "0.0.1-beta.5",
233
+ "@anhlp/alp-core": "0.0.1-beta.7",
234
+ "@anhlp/alp-protocol": "0.0.1-beta.7",
235
235
  "@anthropic-ai/claude-agent-sdk": "^0.3.292",
236
236
  "@modelcontextprotocol/sdk": "^1.32.1",
237
237
  "@agentclientprotocol/sdk": "1.7.0",
@@ -16,11 +16,13 @@ import { commandDecision } from '@anhlp/alp-core/permissions';
16
16
  // imports while compiling plugin entrypoints, including their declaration
17
17
  // graph; the SDK is a daemon-only optional runtime dependency.
18
18
  const CLAUDE_SDK = ['@anthropic-ai', 'claude-agent-sdk'].join('/');
19
+ const claudeSdk = (): Promise<any> => import(CLAUDE_SDK);
19
20
 
20
21
  type SDKUserMessage = any;
21
22
  type SDKMessage = any;
22
23
  type ClaudeQuery = AsyncGenerator<SDKMessage, void> & {
23
24
  supportedModels(): Promise<Array<{ value: string; displayName: string; description: string; supportedEffortLevels?: string[] }>>;
25
+ supportedCommands(): Promise<Array<{ name: string; description: string; argumentHint?: string }>>;
24
26
  usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(options: { skipBehaviors: boolean }): Promise<any>;
25
27
  getContextUsage(options: { detail: 'summary' | 'full' }): Promise<any>;
26
28
  interrupt(): Promise<unknown>;
@@ -221,6 +223,8 @@ type NativeConfig = {
221
223
 
222
224
  /** The plugin name ALP's skills are loaded under, so Claude Code calls them alp:<name>. */
223
225
  export const SKILL_PLUGIN = 'alp';
226
+ /** Claude's own commands the composer does not offer: ALP does their work its own way (t-efa3). */
227
+ const ALP_HANDLED_COMMANDS = new Set(['clear', 'compact', 'rewind']);
224
228
 
225
229
  /**
226
230
  * A Claude Code plugin in `directory` holding the given skills, linked to their own
@@ -384,7 +388,7 @@ const BOOT_MS = 15_000;
384
388
  * resumed or forked from another directory). Empty when the session has no transcript yet.
385
389
  */
386
390
  export async function claudeChain(sessionId: string, dir?: string): Promise<Array<{ uuid: string; type: 'user' | 'assistant'; toolResult?: boolean }>> {
387
- const { getSessionMessages } = await import(CLAUDE_SDK);
391
+ const { getSessionMessages } = await claudeSdk();
388
392
  let messages: any[] = dir ? await getSessionMessages(sessionId, { dir }) : [];
389
393
  if (!messages.length) messages = await getSessionMessages(sessionId);
390
394
  return messages.filter(message => (message.type === 'user' || message.type === 'assistant') && typeof message.uuid === 'string').map(message => {
@@ -459,11 +463,24 @@ export class ClaudeTransport {
459
463
  models: (catalog ?? []).map(model => ({ id: `claude:${model.value}`, label: model.displayName,
460
464
  description: model.description, thinking: model.supportedEffortLevels })), usage: claudeUsage(usage) };
461
465
  }
466
+ /**
467
+ * Claude's slash commands, skills included, for the composer (t-f628); none before the session starts.
468
+ * Not the ones whose work ALP does itself (t-efa3): /clear moves Claude to a new conversation ALP does not
469
+ * follow, and /compact and /rewind skip ALP's checkpoint and its rewind of the timeline.
470
+ */
471
+ async commands() {
472
+ const listed = this.query ? await optionalRead(async () => this.query!.supportedCommands(), 10_000) : undefined;
473
+ return (Array.isArray(listed) ? listed : []).filter(command => typeof command?.name === 'string' && command.name && !ALP_HANDLED_COMMANDS.has(command.name)).map(command => ({
474
+ name: command.name, description: typeof command.description === 'string' ? command.description : '',
475
+ ...(command.argumentHint ? { argumentHint: command.argumentHint } : {}),
476
+ kind: command.name.startsWith(`${SKILL_PLUGIN}:`) ? 'skill' as const : 'command' as const,
477
+ }));
478
+ }
462
479
  async initialize() {}
463
480
 
464
481
  /** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
465
482
  async probeModels(signal?: AbortSignal) {
466
- const { query } = await import(CLAUDE_SDK);
483
+ const { query } = await claudeSdk();
467
484
  if (signal?.aborted) throw new Error('aborted');
468
485
  const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } }) as ClaudeQuery;
469
486
  // A probe that outlives its bound is closed, so a hanging Claude process never stays behind.
@@ -481,7 +498,7 @@ export class ClaudeTransport {
481
498
  /** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
482
499
  private async probeUsage() {
483
500
  if (this.closed) return undefined;
484
- const { query } = await import(CLAUDE_SDK);
501
+ const { query } = await claudeSdk();
485
502
  const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } }) as ClaudeQuery;
486
503
  try {
487
504
  return await probe.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
@@ -517,7 +534,7 @@ export class ClaudeTransport {
517
534
  if (method === 'thread/chain') return { entries: await claudeChain(params.threadId, params.cwd ?? this.cwd) };
518
535
 
519
536
  if (method === 'thread/delete') {
520
- const { deleteSession } = await import(CLAUDE_SDK);
537
+ const { deleteSession } = await claudeSdk();
521
538
  await deleteSession(params.threadId, params.cwd ? { dir: params.cwd } : {});
522
539
  return {};
523
540
  }
@@ -626,7 +643,7 @@ export class ClaudeTransport {
626
643
  }
627
644
 
628
645
  private async start(from?: { resume: string; fork: boolean; at?: string }) {
629
- const { createSdkMcpServer, query, tool } = await import(CLAUDE_SDK);
646
+ const { createSdkMcpServer, query, tool } = await claudeSdk();
630
647
  const config = this.config!;
631
648
  const mcpServers = this.convertMcp(config.mcpServers);
632
649
 
package/src/contracts.ts CHANGED
@@ -9,10 +9,15 @@ import type { AntigravityProvider } from './antigravity-transport.js';
9
9
  import type { GitHubRunner } from './github.js';
10
10
  import type { AttachmentReader } from './attachments.js';
11
11
 
12
+ /** A slash command or skill an agent's composer offers after "/" (t-f628). */
13
+ export type RuntimeCommand = { name: string; description: string; argumentHint?: string; kind: 'command' | 'skill' };
14
+
12
15
  export type RuntimeTransport = {
13
16
  request(method: string, params: any): Promise<any>;
14
17
  initialize(): Promise<void>;
15
18
  orchestrationContext?: () => Promise<unknown>;
19
+ /** The runtime's own slash commands and skills for the composer (t-f628); omitted, the runtime offers none. */
20
+ commands?: () => Promise<RuntimeCommand[]>;
16
21
  onNotification(listener: (method: string, params: any) => void): void;
17
22
  onFailure(listener: (error: unknown) => void): void;
18
23
  close(): Promise<void>;
@@ -170,9 +175,14 @@ export type AlpRuntime = {
170
175
  status(sessionId: string): TreeStatus | undefined;
171
176
  /** Questions agents asked the user that wait for an answer. */
172
177
  questions(): UserQuestion[];
173
- /** Answers or dismisses a question to the user. */
174
- answer(questionId: string, reply: { text?: string; dismiss?: boolean; reason?: string; /** Where the user answered a gate card: paseo or web. */ channel?: 'paseo' | 'web' }): void;
175
- /** Mirrors the project's open human gates as cards on its main session and tells main of the user's gate decisions, once each (t-ccac). */
178
+ /**
179
+ * Answers or dismisses a question to the user. A gate card's answer returns a promise that
180
+ * settles once the decision is written, and rejects when it decides nothing: another answer is
181
+ * being recorded or another channel decided first (code GATE_BUSY or GATE_DECIDED), or the
182
+ * write failed (t-595d).
183
+ */
184
+ answer(questionId: string, reply: { text?: string; dismiss?: boolean; reason?: string; /** Where the user answered a gate card: paseo or web. */ channel?: 'paseo' | 'web' }): void | Promise<void>;
185
+ /** Mirrors the project's open human gates as cards on its main session and tells main of the user's gate decisions, at least once each (t-ccac, t-595d). */
176
186
  syncGates?(projectRoot: string): Promise<void>;
177
187
  /** Mails a note from the user to any live session, such as an assignment the user wants to redirect. */
178
188
  message(sessionId: string, text: string): void;
@@ -233,6 +243,8 @@ export type AlpRuntime = {
233
243
  reload?(sessionId: string): Promise<SessionSnapshot>;
234
244
  /** Compacts a root's context at its next turn boundary, with a checkpoint main writes by skill compact (t-0e56). */
235
245
  compact?(sessionId: string): { status: 'started' | 'deferred' | 'running' };
246
+ /** The slash commands and skills a live session's composer offers (t-f628): its runtime's, then its ALP skills. */
247
+ commands?(sessionId: string): Promise<RuntimeCommand[]>;
236
248
  /**
237
249
  * Holds the turns the runtime would start by itself on this session (mail wakes) while a lifecycle
238
250
  * operation changes its conversation (a rewind, later a reload or live configure): mail stays queued
package/src/index.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  export { createAlpRuntime, DEFAULT_TEAM, WorkspaceMutationError } from './runtime.js';
3
3
  export type { WorkspaceMutationReason, AlpRuntime, RuntimeOptions, OpenOptions, RuntimeTransport, PromptInput, PromptContent, SessionPreview } from './runtime.js';
4
4
  export { ConversationError } from './contracts.js';
5
- export type { BranchRequest, ConversationErrorReason, NativeBase, NativeBinding, ConfigureChanges, ConfigureResult, ConfigurePreview, EffectiveConfig } from './contracts.js';
5
+ export type { RuntimeCommand, BranchRequest, ConversationErrorReason, NativeBase, NativeBinding, ConfigureChanges, ConfigureResult, ConfigurePreview, EffectiveConfig } from './contracts.js';
6
6
  export type { AlpEvent, AlpError, Envelope, SessionSnapshot, TimelineItem, TurnOrigin, AssignmentSnapshot, UserQuestion, TreeStatus, SessionState } from './events.js';
7
7
  export { resolveSession, InstructionsAdapter, skillDescription } from './resolve.js';
8
8
  export type { SessionSpec, HostMcpServer, ResolvedSession, RuntimeKind } from './resolve.js';
@@ -23,6 +23,7 @@ export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, skillPlugin
23
23
  export { MAIL_BATCH_CHARS, MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from './mailbox.js';
24
24
  export type { MailEvent, MailKind } from './mailbox.js';
25
25
  export { createCopy, gitEnvironment, reattachWorktree, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
26
+ export type { LeftWorktree } from './workspace.js';
26
27
  export { OWN_START, processStartedAt, sameProcessAlive } from './process-info.js';
27
28
  export type { Worktree, WorktreeChange } from './workspace.js';
28
29
  export { PIN_KINDS, renderBoard, renderPin } from './board.js';
package/src/resolve.ts CHANGED
@@ -223,6 +223,8 @@ export async function resolveSession(spec: SessionSpec, options: { templates?: R
223
223
  mcp, env: { ...spec.env }, persist: spec.persist ?? false, keepThread: spec.keepThread ?? false,
224
224
  // ALPD §57: the window the agent works in before its runtime compacts; absent, the model's.
225
225
  ...(agent.context ? { context: agent.context } : {}),
226
+ // t-efa3: the runtime's own commands and skills the "/" list offers; its ALP skills always.
227
+ commands: Array.isArray(profile?.commands) ? profile.commands.filter((name: unknown): name is string => typeof name === 'string') : [] as string[],
226
228
  autocompact: typeof profile?.autocompact === 'number' ? profile.autocompact as number : typeof agent.autocompact === 'number' ? agent.autocompact : undefined,
227
229
  // t-0e56: when main's context is compacted at a turn boundary.
228
230
  compact: compactSettings(projectSettings.compact),
package/src/runtime.ts CHANGED
@@ -9,7 +9,7 @@ import { createBoardDomain } from './board-domain.js';
9
9
  import { ATTACHMENT_ROUTES, STAGED_PATH, attachmentPart, createAttachmentStager, runtimeAttachment, stagingExposure, type AttachmentReader, type AttachmentRoute } from './attachments.js';
10
10
  import type { RuntimeAttachment } from '@anhlp/alp-protocol/session';
11
11
  import { createWorktreeDomain } from './worktree-domain.js';
12
- import { type RuntimeTransport, type RuntimeOptions, type OpenOptions, type PromptContent, type PromptInput, type AlpRuntime, type SessionPreview, type RecoveryOutcome, type Pause, type PauseState, type RecallAnswer, type ScheduleHandler, type BranchRequest, type NativeBinding, type ConfigurePreview, type ConfigureResult, type ConversationErrorReason, ConversationError } from './contracts.js';
12
+ import { type RuntimeTransport, type RuntimeOptions, type OpenOptions, type PromptContent, type PromptInput, type AlpRuntime, type SessionPreview, type RecoveryOutcome, type Pause, type PauseState, type RecallAnswer, type ScheduleHandler, type BranchRequest, type NativeBinding, type ConfigurePreview, type ConfigureResult, type ConversationErrorReason, type RuntimeCommand, ConversationError } from './contracts.js';
13
13
  import { claudeCut, codexForkEnd, codexForkRefusal, pendingChain, type ChainEntry } from './conversation.js';
14
14
  export type { RuntimeTransport, RuntimeOptions, OpenOptions, PromptContent, PromptInput, AlpRuntime, SessionPreview, RecoveryOutcome, Pause, PauseState, RecallAnswer } from './contracts.js';
15
15
  export { DEFAULT_TEAM } from './contracts.js';
@@ -18,7 +18,7 @@ import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, roleOf, taskActions, task
18
18
  import { nativeEnvironment, createTransport } from './providers.js';
19
19
  import { nativeMode, codexApproval, profileEfforts, nativeSessionConfig } from './session-config.js';
20
20
  import { createHash, randomUUID } from 'node:crypto';
21
- import { readFileSync, realpathSync } from 'node:fs';
21
+ import { readFileSync, realpathSync, watch as watchFiles, type FSWatcher } from 'node:fs';
22
22
  import { appendFile, mkdir, open, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
23
23
  import { moveFile } from '@anhlp/alp-core/atomic';
24
24
  import os from 'node:os';
@@ -36,7 +36,7 @@ import { isTrusted, trustProject } from '@anhlp/alp-core/trust';
36
36
  import { listTeams, teamOf } from '@anhlp/alp-core/teams';
37
37
  import { CONFIGURABLE, changesOf, effectiveOf, executablesOf, nativeModelOf, offered, type ConfigureChange, type ConfigureChanges, type EffectiveConfig } from './configure.js';
38
38
  import { anyModel, offers, profileModel, selectedProfile } from '@anhlp/alp-core/profiles';
39
- import { LESSONS_FILE, READ_ONLY_AGENTS, resolveSession, type ResolvedSession, type RuntimeKind, type SessionSpec } from './resolve.js';
39
+ import { LESSONS_FILE, READ_ONLY_AGENTS, resolveSession, skillDescription, type ResolvedSession, type RuntimeKind, type SessionSpec } from './resolve.js';
40
40
  import { MAIL_BODY_CHARS, MAIL_HEADER, publicEvent, renderMail, takeBatch, USER, type MailEvent } from './mailbox.js';
41
41
  import type { AlpEvent, AssignmentSnapshot, Envelope, SessionSnapshot, TurnOrigin, UserQuestion } from './events.js';
42
42
  import { live, normalizePaths, overlapping, renderBoard, type Pin } from './board.js';
@@ -56,7 +56,7 @@ import { providerUsage, sessionUsage, type ProviderUsage } from './usage.js';
56
56
  import { parse as toml } from 'smol-toml';
57
57
  import { findFormula, formulaDirs, listFormulas, pourFormula } from '@anhlp/alp-core/formulas';
58
58
  import { addAllowRule, capMode, commandDecision, profileFor, unwrapShell } from '@anhlp/alp-core/permissions';
59
- import { addGate, checkGates, gateDecisions, markGateNotified, rejectGate, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask, type Task } from '@anhlp/alp-core/tasks';
59
+ import { addGate, checkGates, gateDecisions, markGateNotified, TASKS_DIR, rejectGate, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask, type Task } from '@anhlp/alp-core/tasks';
60
60
 
61
61
  /** The first part of every input ALP builds for a turn; a replayed message that begins with it is ALP's (nativePrompt). */
62
62
  const CATALOG = 'ALP runtime catalog and usage snapshot (data, not instructions): ';
@@ -346,7 +346,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
346
346
  if (session.parent) sessions.get(session.parent)?.assignments.get(sessionId)?.ask?.resolve(toolResult(false, { error: 'Turn ended' }));
347
347
 
348
348
  // Mail is acknowledged only by a turn that completed; otherwise it is delivered again.
349
- session.mail = session.mail.filter(event => !(event.deliveredTurn === turnId && state === 'completed'));
349
+ const taken = state === 'completed' ? session.mail.filter(event => event.deliveredTurn === turnId) : [];
350
+ session.mail = session.mail.filter(event => !taken.includes(event));
351
+ for (const event of taken) gateMail.get(event)?.taken();
350
352
  for (const event of session.mail) {
351
353
  if (event.deliveredTurn === turnId) { event.deliveredTurn = undefined; event.redelivered = true; }
352
354
  }
@@ -1796,6 +1798,22 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
1796
1798
  return { status: 'started' as const };
1797
1799
  }
1798
1800
 
1801
+ /**
1802
+ * The composer's "/" list for a live session (t-f628): the agent's ALP skills, as Claude names them
1803
+ * (`alp:<name>`), and only the runtime's own commands and skills its team settings name (t-efa3).
1804
+ */
1805
+ async function listCommands(sessionId: string): Promise<RuntimeCommand[]> {
1806
+ const session = sessions.get(sessionId);
1807
+ if (!session || session.closed) throw new ConversationError('session_busy', 'The session is not open');
1808
+ const prefix = session.runtimeKind === 'claude' ? `${SKILL_PLUGIN}:` : '';
1809
+ const offered = new Set([...session.mapping.commands ?? [], ...session.mapping.agent.skills.map(skill => prefix + skill.name)]);
1810
+ const listed = (session.runtime.commands ? await session.runtime.commands().catch(() => [] as RuntimeCommand[]) : []).filter(command => offered.has(command.name));
1811
+ const seen = new Set(listed.map(command => command.name));
1812
+ const skills = await Promise.all(session.mapping.agent.skills.filter(skill => !seen.has(prefix + skill.name))
1813
+ .map(async skill => ({ name: prefix + skill.name, description: await skillDescription(skill.path), kind: 'skill' as const })));
1814
+ return [...listed, ...skills];
1815
+ }
1816
+
1799
1817
  /** What ALP holds of a session's work, told to it after a compaction (ALPD §57). */
1800
1818
  async function restoreAfterCompaction(sessionId: string, session: Session, checkpoint?: string) {
1801
1819
  const parts = ['Your context was just compacted. In case the summary lost any of it, this is what ALP holds of your work now.'];
@@ -2957,11 +2975,19 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
2957
2975
 
2958
2976
  // Human gates (t-ccac): .alp/tasks stays the source of truth. Each open human gate of a project
2959
2977
  // shows as a card on its live main root session, without a timeout and outside the one-question
2960
- // limit; syncGates rebuilds the cards from the files (on start, attach, a gate change and a timer,
2961
- // since the CLI and Paseo's local panel write the files without alpd) and tells main of every
2962
- // decision once: markGateNotified marks it under the task lock, so card, panel and CLI racing on
2963
- // one gate send one mail. With no live main, the decision waits for the project's next main.
2978
+ // limit; syncGates rebuilds the cards from the files (on start, attach, a gate change, a change
2979
+ // to the task files and a timer, since the CLI and Paseo's local panel write the files without
2980
+ // alpd) and tells main of every decision at least once (t-595d): the mail goes first, and
2981
+ // markGateNotified marks the decision only once a completed turn of main took it. Until then
2982
+ // the mail on its way is not sent again; after a restart it is, and its body tells main a repeat
2983
+ // changes nothing. With no live main, the decision waits for the project's next main.
2964
2984
  const gateSyncs = new Map<string, Promise<void>>();
2985
+ /** Decision mail on its way to main, by the decision it reports. */
2986
+ const gateMail = new WeakMap<MailEvent, { key: string; taken: () => void }>();
2987
+ /** Decisions main took whose mark is being written, or was. */
2988
+ const gateTaken = new Set<string>();
2989
+ /** Marks being written; shutdown waits for them, so nothing writes the task files after it. */
2990
+ const gateMarks = new Set<Promise<unknown>>();
2965
2991
  const gateCardId = (taskId: string, gateId: string) => `gate-${taskId}-${gateId}`;
2966
2992
 
2967
2993
  /** The project's live main root session, if any. */
@@ -2987,14 +3013,28 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
2987
3013
  if (closed) return;
2988
3014
  const { tasks } = await loadTasks(projectRoot);
2989
3015
  const main = mainSessionOf(projectRoot);
2990
- // The user's decisions, to main once each; without a live main they wait for the next one.
3016
+ // The user's decisions, to main at least once each; without a live main they wait for the next one.
2991
3017
  if (main) for (const { task, gate, decision, record } of gateDecisions(tasks)) {
2992
- if (!await markGateNotified(projectRoot, task.id, gate.id, decision)) continue;
3018
+ const key = JSON.stringify([projectRoot, task.id, gate.id, decision, record.at]);
3019
+ if (gateTaken.has(key) || main.session.mail.some(event => gateMail.get(event)?.key === key)) continue;
2993
3020
  const choice = decision === 'approved' ? (record as { choice?: string }).choice : undefined;
2994
3021
  const words = decision === 'approved'
2995
3022
  ? `The user approved human gate ${gate.id} of ${task.id} in ${record.channel}${choice ? `, choosing "${choice}"` : ''}${(record as { note?: string }).note ? `: ${(record as { note?: string }).note}` : ''}.`
2996
3023
  : `The user rejected human gate ${gate.id} of ${task.id} in ${record.channel}${(record as { reason?: string }).reason ? `: ${(record as { reason?: string }).reason}` : ''}. The gate stays open.`;
2997
- post(main.id, { kind: 'result', from: 'ALP', assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words} Task: ${task.title}` });
3024
+ const mail = post(main.id, { kind: 'result', from: 'ALP', assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words} Task: ${task.title}. If this decision of ${gateCardId(task.id, gate.id)} was reported to you before, it is a repeat: act on it once.` });
3025
+ gateMail.set(mail, {
3026
+ key,
3027
+ taken: () => {
3028
+ gateTaken.add(key);
3029
+ const mark = markGateNotified(projectRoot, task.id, gate.id, decision, record.at).catch(error => {
3030
+ // Unmarked, it is mailed again: once more is better than never.
3031
+ gateTaken.delete(key);
3032
+ runLog(main.id, { event: 'gate.mark.failed', projectRoot, taskId: task.id, gateId: gate.id, error: errorData(error).message });
3033
+ });
3034
+ gateMarks.add(mark);
3035
+ void mark.finally(() => gateMarks.delete(mark));
3036
+ },
3037
+ });
2998
3038
  runLog(main.id, { event: 'gate.decision', projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record.channel, ...(choice ? { choice } : {}) });
2999
3039
  }
3000
3040
  // A card for each open human gate the user has not rejected; a rejected one stays open for main to follow up.
@@ -3016,18 +3056,51 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3016
3056
  for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
3017
3057
  }
3018
3058
 
3019
- /** The CLI and Paseo's local Tasks panel write gates without alpd: a timer reads them while a main is live. */
3059
+ /**
3060
+ * The CLI and Paseo's local Tasks panel write gates without alpd: while a main is live, a change
3061
+ * to the project's task files syncs at once (t-595d), and a timer reads them too, where file
3062
+ * events are missing or lost.
3063
+ */
3020
3064
  let gateWatch: NodeJS.Timeout | undefined;
3021
- function startGateWatch() {
3022
- if (gateWatch || options.gateSyncMs === 0) return;
3065
+ const gateFiles = new Map<string, { watcher: FSWatcher; timer?: NodeJS.Timeout }>();
3066
+ function startGateWatch(projectRoot: string) {
3067
+ if (options.gateSyncMs === 0) return;
3068
+ watchGateFiles(path.resolve(projectRoot));
3069
+ if (gateWatch) return;
3023
3070
  gateWatch = setInterval(() => {
3024
3071
  const roots = new Set([...sessions.values()].filter(session => !session.closed && !session.parent && session.role !== 'supervisor' && session.mapping.agent.name === mainOf(session.mapping)).map(session => path.resolve(session.mapping.agent.projectRoot)));
3025
- for (const root of roots) void syncGates(root);
3072
+ for (const root of roots) { watchGateFiles(root); void syncGates(root); }
3073
+ for (const root of gateFiles.keys()) if (!roots.has(root)) unwatchGateFiles(root);
3026
3074
  if (!roots.size) { clearInterval(gateWatch); gateWatch = undefined; }
3027
3075
  }, options.gateSyncMs ?? 5_000);
3028
3076
  gateWatch.unref?.();
3029
3077
  }
3030
3078
 
3079
+ function watchGateFiles(root: string) {
3080
+ if (closed || gateFiles.has(root)) return;
3081
+ try {
3082
+ const entry: { watcher: FSWatcher; timer?: NodeJS.Timeout } = {
3083
+ // A burst of writes (a save, its ledger, a mark) syncs once.
3084
+ watcher: watchFiles(path.join(root, TASKS_DIR), () => {
3085
+ if (entry.timer || closed) return;
3086
+ entry.timer = setTimeout(() => { entry.timer = undefined; void syncGates(root); }, 50);
3087
+ entry.timer.unref?.();
3088
+ }),
3089
+ };
3090
+ entry.watcher.on('error', () => unwatchGateFiles(root));
3091
+ entry.watcher.unref?.();
3092
+ gateFiles.set(root, entry);
3093
+ } catch {} // No task files yet, or no file events here: the timer tries again.
3094
+ }
3095
+
3096
+ function unwatchGateFiles(root: string) {
3097
+ const entry = gateFiles.get(root);
3098
+ if (!entry) return;
3099
+ gateFiles.delete(root);
3100
+ clearTimeout(entry.timer);
3101
+ entry.watcher.close();
3102
+ }
3103
+
3031
3104
  function showGateCard(sessionId: string, session: Session, projectRoot: string, task: Task, gate: Task['gates'][number]) {
3032
3105
  const say = wordsFor(session);
3033
3106
  const vietnamese = say.approve === words('vi').approve;
@@ -3057,13 +3130,15 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3057
3130
  * The user answered a gate card: an option approves (with the default Approve/Reject, Reject or
3058
3131
  * other words reject), dismissing rejects. The card's task rev guards the write; a stale rev is
3059
3132
  * read again and retried only while the gate is still open and undecided, so a decision another
3060
- * channel made first is never applied or mailed twice.
3133
+ * channel made first is never applied or mailed twice. An answer that decides nothing (a second
3134
+ * one while the first is written, one another channel beat, or a failed write) is refused to the
3135
+ * caller, never only logged (t-595d).
3061
3136
  */
3062
3137
  async function decideGate(projectRoot: string, question: UserQuestion, card: { rev: number; deciding: boolean }, reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }, choices?: string[]) {
3063
3138
  const defaults = !choices;
3064
- if (card.deciding) return;
3065
- card.deciding = true;
3066
3139
  const { taskId, gateId } = question.gate!;
3140
+ if (card.deciding) throw gateRefusal('GATE_BUSY', `An answer to gate ${gateId} of ${taskId} is already being recorded`);
3141
+ card.deciding = true;
3067
3142
  const channel = reply.channel ?? 'web';
3068
3143
  const text = reply.text?.trim();
3069
3144
  const approve = !reply.dismiss && !!text && (defaults ? APPROVALS.includes(text.toLowerCase()) : choices.includes(text));
@@ -3077,18 +3152,24 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3077
3152
  if (error?.code !== 'TASK_CHANGED') throw error;
3078
3153
  const current = (await loadTasks(projectRoot)).tasks.find(entry => entry.id === taskId);
3079
3154
  const gate = current?.gates.find(entry => entry.id === gateId);
3080
- if (!current || current.status === 'closed' || !gate || gate.resolved || gate.rejected) return;
3155
+ if (!current || current.status === 'closed' || !gate) throw gateRefusal('GATE_DECIDED', `Gate ${gateId} of ${taskId} is no longer open`);
3156
+ 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}` : ''}`);
3081
3157
  await write(current.rev);
3082
3158
  }
3083
3159
  } catch (error) {
3084
- // Already clear, or the task is gone: the other channel won; the sync below settles the card.
3085
3160
  runLog(question.rootId, { event: 'gate.answer.failed', questionId: question.id, error: errorData(error).message });
3161
+ throw error;
3086
3162
  } finally {
3087
3163
  card.deciding = false;
3164
+ // Settles the card whatever happened: decided here, by another channel, or gone.
3088
3165
  await syncGates(projectRoot);
3089
3166
  }
3090
3167
  }
3091
3168
 
3169
+ function gateRefusal(code: 'GATE_BUSY' | 'GATE_DECIDED', message: string) {
3170
+ return Object.assign(new Error(message), { code });
3171
+ }
3172
+
3092
3173
  function askTool(sessionId: string, session: Session, args: unknown) {
3093
3174
  const parent = session.parent ? sessions.get(session.parent) : undefined;
3094
3175
  const assignment = parent?.assignments.get(sessionId);
@@ -3726,7 +3807,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3726
3807
  },
3727
3808
  });
3728
3809
  // A main root shows the project's open human gates and gets decisions made while none was live.
3729
- if (!session.parent && session.role !== 'supervisor' && mapping.agent.name === mainOf(mapping)) { void syncGates(mapping.agent.projectRoot); startGateWatch(); }
3810
+ if (!session.parent && session.role !== 'supervisor' && mapping.agent.name === mainOf(mapping)) { void syncGates(mapping.agent.projectRoot); startGateWatch(mapping.agent.projectRoot); }
3730
3811
 
3731
3812
  if (
3732
3813
  history === 'replay'
@@ -4747,6 +4828,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4747
4828
  const after = mail.length && !wake ? [{ type: 'text', text: promptSafe(renderMail(mail, session.parentAgent)), text_elements: [] }] : [];
4748
4829
  const inputLayout: InputLayout = { textParts: 1 + before.length + 1 + attached.length + after.length, prompt: 1 + before.length };
4749
4830
  const listed = attached.map(({ attachment }) => attachmentMeta(attachment));
4831
+ const invoked = session.runtimeKind === 'codex' && origin === 'user' && prompt.delivery !== 'steer'
4832
+ ? session.mapping.agent.skills.find(skill => text.match(/^\/(\S+)(?:\s|$)/)?.[1] === skill.name) : undefined;
4750
4833
  const nativeInput = [
4751
4834
  { type: 'text', text: promptSafe(CATALOG + JSON.stringify({ inputLayout, ...(orchestration as object), ...(listed.length ? { attachments: listed } : {}) })), text_elements: [] },
4752
4835
  ...before,
@@ -4758,6 +4841,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4758
4841
  ...attached.map(({ attachment, staged }) => ({ type: 'text', text: promptSafe(attachmentPart(attachment, staged)), text_elements: [] })),
4759
4842
  ...images.map(image => ({ type: 'image', url: `data:${image.mimeType};base64,${image.data}` })),
4760
4843
  ...after,
4844
+ // "/<skill> ..." from the user loads that ALP skill in Codex, as its own $<skill> does (t-efa3).
4845
+ ...(invoked ? [{ type: 'skill', name: invoked.name, path: invoked.path }] : []),
4761
4846
  ];
4762
4847
 
4763
4848
  const result =
@@ -5036,6 +5121,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
5036
5121
 
5037
5122
  reload: sessionId => enqueue(() => reloadSession(sessionId)),
5038
5123
  compact: (sessionId: string) => requestCompact(sessionId),
5124
+ commands: (sessionId: string) => listCommands(sessionId),
5039
5125
 
5040
5126
  previewConfigure: (sessionId, changes) => previewConfigureSession(sessionId, changes),
5041
5127
 
@@ -5229,8 +5315,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
5229
5315
  if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
5230
5316
  if (pending.gate) {
5231
5317
  if (!reply.dismiss && (typeof reply.text !== 'string' || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error('An answer needs text');
5232
- void pending.gate.decide(reply);
5233
- return;
5318
+ return pending.gate.decide(reply);
5234
5319
  }
5235
5320
  if (reply.dismiss) {
5236
5321
  pending.settle('dismissed', undefined, reply.reason);
@@ -5275,7 +5360,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
5275
5360
 
5276
5361
  clearInterval(watchdog);
5277
5362
  if (gateWatch) clearInterval(gateWatch);
5363
+ for (const root of [...gateFiles.keys()]) unwatchGateFiles(root);
5278
5364
  await Promise.all(gateSyncs.values());
5365
+ await Promise.all(gateMarks);
5279
5366
 
5280
5367
  // Claims released by the closes above are written before the board is left.
5281
5368
  await Promise.all(boards.values());
package/src/workspace.ts CHANGED
@@ -157,10 +157,11 @@ async function validWorktree(directory: string) {
157
157
  export async function reattachWorktree(worktree: Worktree): Promise<Worktree & { preserved?: string }> {
158
158
  const exists = !!await stat(worktree.path).catch(() => undefined);
159
159
  if (exists && await validWorktree(worktree.path)) {
160
- // A crash mid `git add`/`commit` leaves the index locked; nothing else writes this worktree
161
- // while its assignment reopens, so the lock is stale and would block every later commit.
162
- const gitdir = await git(worktree.path, ['rev-parse', '--absolute-git-dir']);
163
- if (gitdir.code === 0) await rm(path.join(gitdir.stdout.trim(), 'index.lock'), { force: true });
160
+ // A crash mid `git add`/`commit` leaves the index, HEAD or the branch locked; nothing else
161
+ // writes this worktree while its assignment reopens, so the locks are stale and would block
162
+ // every later commit.
163
+ const dirs = await gitDirs(worktree.path);
164
+ if (dirs) await clearStaleLocks(dirs, worktree.branch);
164
165
  return worktree;
165
166
  }
166
167
  if (!await branchExists(worktree.checkout, worktree.branch)) throw new Error(`Branch ${worktree.branch} of the worktree no longer exists`);
@@ -254,36 +255,114 @@ export async function removeWorktree(worktree: Worktree, { deleteBranch = false
254
255
  if (deleteBranch) await git(worktree.checkout, ['branch', '-D', worktree.branch]);
255
256
  }
256
257
 
258
+ /** A linked worktree's own git directory and the repository's common one, both absolute. */
259
+ type GitDirs = { own: string; common: string };
260
+
261
+ async function gitDirs(target: string): Promise<GitDirs | undefined> {
262
+ const result = await git(target, ['rev-parse', '--path-format=absolute', '--absolute-git-dir', '--git-common-dir']);
263
+ if (result.code !== 0) return undefined;
264
+ const [own, common] = result.stdout.trim().split('\n').map(line => path.resolve(line.trim()));
265
+ return own && common ? { own, common } : undefined;
266
+ }
267
+
268
+ /**
269
+ * How old the branch's lock in the shared repository must be before ALP treats it as left by
270
+ * a crash. The user's own git commands in their checkout lock that ref too (`git gc`, `git branch
271
+ * -D`), but only for the moment a ref update takes.
272
+ */
273
+ const SHARED_LOCK_STALE_MS = 10_000;
274
+
275
+ /**
276
+ * Removes the locks a git command killed mid-write left in a worktree, which would fail every
277
+ * later `git add` or `git commit` there: `index.lock`, `HEAD.lock` and any other lock directly in
278
+ * the worktree's own git directory, and every `*.lock` under its `refs/`. Callers run this only
279
+ * where no ALP git command can be at work in that worktree (alpd's start, once it has stopped what
280
+ * a crashed alpd left running, and an assignment reopening): only ALP works in its worktrees, so
281
+ * those locks are stale, as `index.lock` always was. In the repository the worktree shares with
282
+ * the user's checkout, only the lock of the worktree's own branch is touched, and only once it is
283
+ * older than SHARED_LOCK_STALE_MS; every other lock there is the user's business.
284
+ */
285
+ async function clearStaleLocks(dirs: GitDirs, branch: string) {
286
+ if (dirs.own === dirs.common) return;
287
+ const own = (await readdir(dirs.own).catch(() => [] as string[])).filter(name => name.endsWith('.lock'));
288
+ const refs = (await readdir(path.join(dirs.own, 'refs'), { recursive: true }).catch(() => [] as string[])).filter(name => name.endsWith('.lock')).map(name => path.join('refs', name));
289
+ for (const name of [...own, ...refs]) await unlink(path.join(dirs.own, name)).catch(() => {});
290
+ const shared = `${path.join(dirs.common, 'refs', 'heads', ...branch.split('/'))}.lock`;
291
+ const info = await lstat(shared).catch(() => undefined);
292
+ if (info?.isFile() && Date.now() - info.mtimeMs >= SHARED_LOCK_STALE_MS) await unlink(shared).catch(() => {});
293
+ }
294
+
295
+ /** Ignored files that may hold what exists nowhere else, such as credentials: `.env`, `.env.local`. */
296
+ const KEEP_IGNORED = /^\.env/;
297
+
298
+ /**
299
+ * The ignored entries of a worktree that removing it would lose for good. git lists them, and an
300
+ * ignored directory (node_modules, build output) is one entry it does not look into.
301
+ */
302
+ async function ignoredToKeep(target: string) {
303
+ const result = await git(target, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory']);
304
+ if (result.code !== 0) return undefined;
305
+ return result.stdout.split('\0').filter(Boolean).map(entry => entry.replace(/\/$/, '')).filter(entry => KEEP_IGNORED.test(path.posix.basename(entry))).sort();
306
+ }
307
+
308
+ /**
309
+ * Why reclaimWorktrees left a directory in place: `invalid`, not the top level of a working git
310
+ * worktree; `not-linked`, a repository of its own rather than a worktree of one; `other-branch`,
311
+ * another branch or a detached HEAD, which does not hold this work; `commit-failed`, its work could
312
+ * not be committed (`detail` says why); `uncommitted`, something was still not committed after
313
+ * that; `ignored-files`, its work is committed but it holds ignored files that exist nowhere else.
314
+ */
315
+ export type LeftWorktree = {
316
+ name: string;
317
+ path: string;
318
+ reason: 'invalid' | 'not-linked' | 'other-branch' | 'commit-failed' | 'uncommitted' | 'ignored-files';
319
+ branch?: string;
320
+ detail?: string;
321
+ files?: string[];
322
+ };
323
+
324
+ const firstLine = (result: GitResult) => (result.stderr || result.stdout).trim().split('\n')[0] ?? '';
325
+
257
326
  /**
258
327
  * After a crash: commits work left in worktrees under `root` to their branches and
259
- * removes the directories. Returns the branches that were kept. A directory is removed
260
- * only once everything in it is committed to its own `alp/<name>` branch; any other one
261
- * (invalid git metadata, a failed commit, another branch checked out, a detached HEAD)
262
- * stays untouched, so recovery reuses or preserves it and nothing uncommitted is lost.
328
+ * removes the directories. Returns the branches that were kept, and the directories left in
329
+ * place with the reason. A directory is removed only once everything in it is committed to
330
+ * its own `alp/<name>` branch and it holds no ignored file to keep (`.env*`); any other one
331
+ * stays, so recovery reuses or preserves it and nothing uncommitted is lost. Stale locks a
332
+ * killed git command left in such a worktree are removed first (clearStaleLocks).
263
333
  */
264
- export async function reclaimWorktrees(root: string) {
334
+ export async function reclaimWorktrees(root: string): Promise<{ kept: string[]; left: LeftWorktree[] }> {
265
335
  const kept: string[] = [];
336
+ const left: LeftWorktree[] = [];
266
337
  const entries = await readdir(root).catch(() => [] as string[]);
267
338
  for (const name of entries) {
268
339
  const target = path.join(root, name);
340
+ const leave = (reason: LeftWorktree['reason'], extra: Omit<LeftWorktree, 'name' | 'path' | 'reason'> = {}) => { left.push({ name, path: target, reason, ...extra }); };
269
341
  if (!(await stat(target).catch(() => undefined))?.isDirectory()) continue;
270
- if (!await validWorktree(target)) continue;
271
- const common = await git(target, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
272
- if (common.code !== 0) continue;
273
- const checkout = path.dirname(common.stdout.trim());
342
+ if (!await validWorktree(target)) { leave('invalid'); continue; }
343
+ const dirs = await gitDirs(target);
344
+ if (!dirs) { leave('invalid'); continue; }
345
+ if (dirs.own === dirs.common) { leave('not-linked'); continue; }
346
+ const checkout = path.dirname(dirs.common);
274
347
  const ref = await git(target, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
275
348
  const branch = ref.stdout.trim();
276
- if (ref.code !== 0 || branch !== `alp/${name}`) continue;
277
- if ((await git(target, ['add', '-A'])).code !== 0) continue;
349
+ if (ref.code !== 0 || branch !== `alp/${name}`) { leave('other-branch', ref.code === 0 && branch ? { branch } : {}); continue; }
350
+ await clearStaleLocks(dirs, branch);
351
+ const added = await git(target, ['add', '-A']);
352
+ if (added.code !== 0) { leave('commit-failed', { branch, detail: firstLine(added) }); continue; }
278
353
  if ((await git(target, ['diff', '--cached', '--quiet'])).code === 1) {
279
- if ((await git(target, [...IDENTITY, 'commit', '--quiet', '--no-verify', '-m', 'alp: work left by an interrupted assignment'])).code !== 0) continue;
354
+ const committed = await git(target, [...IDENTITY, 'commit', '--quiet', '--no-verify', '-m', 'alp: work left by an interrupted assignment']);
355
+ if (committed.code !== 0) { leave('commit-failed', { branch, detail: firstLine(committed) }); continue; }
280
356
  }
281
357
  const status = await git(target, ['status', '--porcelain', '--ignored=no']);
282
- if (status.code !== 0 || status.stdout.trim()) continue;
358
+ if (status.code !== 0 || status.stdout.trim()) { leave('uncommitted', { branch }); continue; }
359
+ const ignored = await ignoredToKeep(target);
360
+ if (!ignored) { leave('ignored-files', { branch, detail: 'git could not list its ignored files' }); continue; }
361
+ if (ignored.length) { leave('ignored-files', { branch, files: ignored }); continue; }
283
362
  await removeWorktree({ checkout, path: target, workdir: target, branch, base: '' });
284
363
  kept.push(branch);
285
364
  }
286
- return kept;
365
+ return { kept, left };
287
366
  }
288
367
 
289
368
  /**