@anhlp/alp-runtime 0.0.1-beta.6 → 0.0.1-beta.8

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.
Files changed (53) hide show
  1. package/dist/acp-transport.js +2 -0
  2. package/dist/antigravity-transport.d.ts +10 -2
  3. package/dist/antigravity-transport.js +26 -4
  4. package/dist/assignment-results.d.ts +5 -2
  5. package/dist/assignment-results.js +27 -15
  6. package/dist/catalog.js +2 -1
  7. package/dist/claude-transport.d.ts +42 -0
  8. package/dist/claude-transport.js +52 -2
  9. package/dist/contracts.d.ts +23 -1
  10. package/dist/index.d.ts +5 -4
  11. package/dist/index.js +9 -2
  12. package/dist/language.d.ts +2 -0
  13. package/dist/language.js +6 -0
  14. package/dist/live.d.ts +2 -2
  15. package/dist/live.js +7 -2
  16. package/dist/model-catalog.d.ts +87 -1
  17. package/dist/model-catalog.js +151 -6
  18. package/dist/model-probes.d.ts +1 -1
  19. package/dist/model-probes.js +2 -2
  20. package/dist/recall.d.ts +2 -2
  21. package/dist/recall.js +4 -3
  22. package/dist/resolve.d.ts +1 -0
  23. package/dist/resolve.js +6 -4
  24. package/dist/runtime.js +258 -34
  25. package/dist/session-config.d.ts +75 -6
  26. package/dist/session-config.js +9 -5
  27. package/dist/session-state.d.ts +2 -0
  28. package/dist/skill-resources.d.ts +30 -0
  29. package/dist/skill-resources.js +55 -0
  30. package/dist/tools.d.ts +27 -1
  31. package/dist/tools.js +20 -1
  32. package/dist/write-error.d.ts +2 -0
  33. package/dist/write-error.js +10 -0
  34. package/package.json +4 -4
  35. package/src/acp-transport.ts +3 -0
  36. package/src/antigravity-transport.ts +39 -8
  37. package/src/assignment-results.ts +23 -15
  38. package/src/catalog.ts +3 -1
  39. package/src/claude-transport.ts +85 -5
  40. package/src/contracts.ts +19 -0
  41. package/src/index.ts +5 -4
  42. package/src/language.ts +10 -0
  43. package/src/live.ts +7 -3
  44. package/src/model-catalog.ts +156 -6
  45. package/src/model-probes.ts +2 -2
  46. package/src/recall.ts +4 -3
  47. package/src/resolve.ts +11 -5
  48. package/src/runtime.ts +277 -30
  49. package/src/session-config.ts +13 -5
  50. package/src/session-state.ts +2 -0
  51. package/src/skill-resources.ts +73 -0
  52. package/src/tools.ts +22 -1
  53. package/src/write-error.ts +4 -0
package/src/runtime.ts CHANGED
@@ -9,22 +9,24 @@ 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';
16
16
  import { verdictLine, parseHandoff, type Handoff } from './handoff.js';
17
- import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, roleOf, taskActions, taskBrief, type TaskAction } from './tools.js';
17
+ import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, readOnlyMember, roleOf, taskActions, taskBrief, type TaskAction } from './tools.js';
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
21
  import { readFileSync, realpathSync, watch as watchFiles, type FSWatcher } from 'node:fs';
22
- import { appendFile, mkdir, open, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
23
- import { moveFile } from '@anhlp/alp-core/atomic';
22
+ import { appendFile, mkdir, open, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
23
+ import { checkFrontmatter, skillReferences, splitSkill } from '@anhlp/alp-core/skill-validate';
24
+ import { resourceUses } from './skill-resources.js';
25
+ import { moveFile, writeAtomic } from '@anhlp/alp-core/atomic';
24
26
  import os from 'node:os';
25
27
  import path from 'node:path';
26
28
  import { resolveDelegation } from '@anhlp/alp-core/delegation';
27
- import { discoverAgents } from '@anhlp/alp-core/resolver';
29
+ import { agentSources, builtinText, discoverAgents } from '@anhlp/alp-core/resolver';
28
30
 
29
31
  import { acpDecision, acpWhat, type AcpPermission } from './acp-transport.js';
30
32
 
@@ -36,18 +38,19 @@ import { isTrusted, trustProject } from '@anhlp/alp-core/trust';
36
38
  import { listTeams, teamOf } from '@anhlp/alp-core/teams';
37
39
  import { CONFIGURABLE, changesOf, effectiveOf, executablesOf, nativeModelOf, offered, type ConfigureChange, type ConfigureChanges, type EffectiveConfig } from './configure.js';
38
40
  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';
41
+ import { LESSONS_FILE, resolveSession, skillDescription, type ResolvedSession, type RuntimeKind, type SessionSpec } from './resolve.js';
40
42
  import { MAIL_BODY_CHARS, MAIL_HEADER, publicEvent, renderMail, takeBatch, USER, type MailEvent } from './mailbox.js';
41
43
  import type { AlpEvent, AssignmentSnapshot, Envelope, SessionSnapshot, TurnOrigin, UserQuestion } from './events.js';
42
44
  import { live, normalizePaths, overlapping, renderBoard, type Pin } from './board.js';
43
45
  import { verifyConfig } from '@anhlp/alp-core/verify';
44
46
  import { createLiveBook, type LiveEntry } from './live.js';
47
+ import { tell } from './write-error.js';
45
48
  import { promptSafe } from '@anhlp/alp-core/promptsafe';
46
49
  import { CHOICES, words, type Words } from './language.js';
47
50
  import { OWN_START, sameProcessAlive } from './process-info.js';
48
51
  import { createRecallBook, recallPrompt, RECALL_KEEP_MS, RECALL_QUESTION_CHARS, RECALL_TIMEOUT_MS, type RecallEntry } from './recall.js';
49
52
  import { branchExists, checkoutFingerprint, checkoutKey, createCopy, createWorktree, reattachWorktree, removeCopy, removeWorktree } from './workspace.js';
50
- import { claudeSandboxAvailable, SKILL_PLUGIN } from './claude-transport.js';
53
+ import { claudeSandboxAvailable, nativeCommandRefusal, SKILL_PLUGIN } from './claude-transport.js';
51
54
  import { boundDetail, codexToolCall, toolError } from './tool-detail.js';
52
55
  import { ALP_REPO, gh, projectRepo } from './github.js';
53
56
  import { optionalRead, usageAllows, COMPACT_SHARE } from './runtime-context.js';
@@ -94,6 +97,11 @@ function promptOrigin(clientMessageId: string, session: { parent?: string }): Tu
94
97
  if (/^alp-(resume|recover)-/.test(clientMessageId)) return session.parent ? 'assignment' : 'wake';
95
98
  return 'user';
96
99
  }
100
+ /**
101
+ * ALP's own compaction prompts (the checkpoint request and a fresh conversation's seed): they reach
102
+ * the model but are not user messages, so the timeline shows notices instead (t-b3cd #6).
103
+ */
104
+ const COMPACT_PROMPT = 'alp-wake-compact-';
97
105
  const MAX_WAKES = 8;
98
106
  /** How long the user may wait for main's first words before its tool results remind it. */
99
107
  const USER_REPLY_MS = 60_000;
@@ -188,6 +196,10 @@ export class WorkspaceMutationError extends Error {
188
196
 
189
197
  export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
190
198
  const sessions = new Map<string, Session>();
199
+ // Only internally initiated, accepted compact inputs may be hidden on replay.
200
+ // Keep ownership across native thread restarts; closing an owner releases all its records.
201
+ const compactEchoes = new Map<Session, Map<string, string>>();
202
+ const inputDigest = (parts: string[]) => createHash('sha256').update(JSON.stringify(parts)).digest('hex');
191
203
  /** Queue slots preparing a scheduled prompt, before its native turn/start. */
192
204
  const admittedPrompts = new Set<string>();
193
205
  /** What ALP writes for the user of a session, in their language (ALPD §54). */
@@ -209,11 +221,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
209
221
 
210
222
  const listeners = new Set<(envelope: Envelope) => void>();
211
223
  const epoch = randomUUID();
224
+ /** A failed write of alpd's own state reaches the host's disk guard at once (t-e80a). */
225
+ const writeFailed = (error: unknown) => { options.onWriteError?.(error); };
212
226
  /** Finished assignments whose native threads alp_recall can question. */
213
- const recalls = createRecallBook(options.recallFile);
214
- const assignmentResults = createAssignmentResults(options.assignmentResultFile);
227
+ const recalls = createRecallBook(options.recallFile, writeFailed);
228
+ const assignmentResults = createAssignmentResults(options.assignmentResultFile, writeFailed);
215
229
  /** Running assignments, so the next alpd continues them (ALPD §31). */
216
- const inFlight = createLiveBook(options.liveFile);
230
+ const inFlight = createLiveBook(options.liveFile, writeFailed);
217
231
  /** Those an earlier alpd left running; recover() takes them once their root is open again. */
218
232
  let inherited = inFlight.all().filter(entry => entry.epoch !== epoch);
219
233
  /** Pauses by runtime, or of everything; kept in pauseFile across restarts. */
@@ -419,6 +433,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
419
433
  session: Session,
420
434
  item: any,
421
435
  done = false,
436
+ turnId?: string,
422
437
  ) {
423
438
  if (item.type === 'agentMessage') {
424
439
  // The first words main shows after the user wrote: how long the user waited.
@@ -433,6 +448,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
433
448
 
434
449
  if (item.type === 'userMessage') {
435
450
  const { text, clientMessageId, origin, attachments } = nativePrompt(item, session);
451
+ if (turnId) {
452
+ const digest = inputDigest((item.content ?? []).filter((part: any) => part.type === 'text').map((part: any) => String(part.text ?? '')));
453
+ for (const echoes of compactEchoes.values()) if (echoes.get(`${session.threadId}:${turnId}`) === digest) return;
454
+ }
436
455
  const images = (item.content ?? []).filter((c: any) => c.type === 'image' || c.type === 'localImage').length;
437
456
  emit(sessionId, { type: 'item', item: { kind: 'user_message', id: item.id, text, ...(clientMessageId ? { clientMessageId } : {}), ...(origin ? { origin } : {}), ...(images ? { images } : {}), ...(attachments ? { attachments } : {}) } });
438
457
  return;
@@ -667,6 +686,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
667
686
  }
668
687
  session.worktrees.clear();
669
688
 
689
+ compactEchoes.delete(session);
690
+
670
691
  // Every id-based side effect belongs to this incarnation, including the
671
692
  // parent's membership and the event that tells viewers it is no longer live.
672
693
  if (sessions.get(sessionId) !== session) return;
@@ -1356,7 +1377,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
1356
1377
  const temporary = `${file}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
1357
1378
  await writeFile(temporary, body, { mode: 0o600 });
1358
1379
  await moveFile(temporary, file);
1359
- }).catch(() => {});
1380
+ }).catch(error => tell(writeFailed, error));
1360
1381
  }
1361
1382
 
1362
1383
  /** Tells every open root, or those of one project, and so the user in each viewer. */
@@ -1612,6 +1633,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
1612
1633
  const skills = session.mapping.agent.skills;
1613
1634
  if (!skills.length || item.type === 'agentMessage' || item.type === 'reasoning') return;
1614
1635
  const text = typeof item.command === 'string' ? item.command : JSON.stringify(item).slice(0, 20_000);
1636
+ skillResources(sessionId, session, item);
1615
1637
  if (!text.includes('SKILL.md') && !text.includes('Skill')) return;
1616
1638
  for (const skill of skills) {
1617
1639
  if (session.skillsUsed?.has(skill.name)) continue;
@@ -1624,6 +1646,22 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
1624
1646
  }
1625
1647
  }
1626
1648
 
1649
+ /**
1650
+ * Progressive disclosure evidence (skill-resources.ts): the first time a session's tool call reads or
1651
+ * runs one of its skills' files beyond SKILL.md, by what the call asked for (never by a tool's output;
1652
+ * writing, listing or merely naming a file is no opening). Logged once per session, file and action,
1653
+ * so the run log shows which resources were loaded on demand and that the rest were not.
1654
+ */
1655
+ function skillResources(sessionId: string, session: Session, item: any) {
1656
+ if (typeof item.command !== 'string') return;
1657
+ for (const use of resourceUses(item.command, session.mapping.agent.skills)) {
1658
+ const key = `${use.action}:${use.skill}/${use.resource}`;
1659
+ if (session.skillResourcesUsed?.has(key)) continue;
1660
+ (session.skillResourcesUsed ??= new Set()).add(key);
1661
+ runLog(rootOf(sessionId), { event: 'skill-resource', sessionId, agent: session.mapping.agent.name, skill: use.skill, resource: use.resource, action: use.action });
1662
+ }
1663
+ }
1664
+
1627
1665
  /**
1628
1666
  * A compaction of the session's context, from its start to its end (ALPD §57): shown in
1629
1667
  * its timeline and the run log; once done, ALP tells the session what it holds of its
@@ -1700,7 +1738,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
1700
1738
  return;
1701
1739
  }
1702
1740
  compacting.turn = true;
1703
- await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: checkpointPrompt(trigger, session.contextFill) }] }, 'wake');
1741
+ await startPrompt(sessionId, { clientMessageId: `${COMPACT_PROMPT}${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: checkpointPrompt(trigger, session.contextFill) }] }, 'wake', undefined, true);
1742
+ emit(sessionId, { type: 'item', item: { kind: 'notice', id: `notice-${randomUUID().slice(0, 8)}`, level: 'info', text: wordsFor(session).compacting() } });
1704
1743
  }).catch(error => compactFailed(sessionId, session, errorData(error).message));
1705
1744
  queue = work.catch(() => {});
1706
1745
  }
@@ -1735,7 +1774,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
1735
1774
  if (refusal && refusal !== MAIL_WAITS && refusal !== REVIEWING) { compactFailed(sessionId, session, `a fresh conversation cannot start now: ${refusal}`); return; }
1736
1775
  await restartNative(sessionId, session, undefined);
1737
1776
  emit(sessionId, { type: 'session.updated', session: snapshot(sessionId, session) });
1738
- await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: seedPrompt(checkpoint, session.lastUserText) }] }, 'wake');
1777
+ await startPrompt(sessionId, { clientMessageId: `${COMPACT_PROMPT}${randomUUID()}`, delivery: 'auto', content: [{ type: 'text', text: seedPrompt(checkpoint, session.lastUserText) }] }, 'wake', undefined, true);
1739
1778
  compactFinished(sessionId, session, 'fresh');
1740
1779
  }).catch(error => compactFailed(sessionId, session, errorData(error).message));
1741
1780
  queue = work.catch(() => {});
@@ -1798,6 +1837,22 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
1798
1837
  return { status: 'started' as const };
1799
1838
  }
1800
1839
 
1840
+ /**
1841
+ * The composer's "/" list for a live session (t-f628): the agent's ALP skills, as Claude names them
1842
+ * (`alp:<name>`), and only the runtime's own commands and skills its team settings name (t-efa3).
1843
+ */
1844
+ async function listCommands(sessionId: string): Promise<RuntimeCommand[]> {
1845
+ const session = sessions.get(sessionId);
1846
+ if (!session || session.closed) throw new ConversationError('session_busy', 'The session is not open');
1847
+ const prefix = session.runtimeKind === 'claude' ? `${SKILL_PLUGIN}:` : '';
1848
+ const offered = new Set([...session.mapping.commands ?? [], ...session.mapping.agent.skills.map(skill => prefix + skill.name)]);
1849
+ const listed = (session.runtime.commands ? await session.runtime.commands().catch(() => [] as RuntimeCommand[]) : []).filter(command => offered.has(command.name));
1850
+ const seen = new Set(listed.map(command => command.name));
1851
+ const skills = await Promise.all(session.mapping.agent.skills.filter(skill => !seen.has(prefix + skill.name))
1852
+ .map(async skill => ({ name: prefix + skill.name, description: await skillDescription(skill.path), kind: 'skill' as const })));
1853
+ return [...listed, ...skills];
1854
+ }
1855
+
1801
1856
  /** What ALP holds of a session's work, told to it after a compaction (ALPD §57). */
1802
1857
  async function restoreAfterCompaction(sessionId: string, session: Session, checkpoint?: string) {
1803
1858
  const parts = ['Your context was just compacted. In case the summary lost any of it, this is what ALP holds of your work now.'];
@@ -1971,6 +2026,16 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
1971
2026
  if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId, file });
1972
2027
  const existing = await readFile(file, 'utf8').catch(() => undefined);
1973
2028
  if (existing !== undefined && !args.replace) return toolResult(false, { error: `The library already has a skill named ${args.name} (${file}); read it, then pass replace: true to propose a new version, or choose another name` });
2029
+ // A new skill meets the Agent Skills format strictly (skill-validate.js). alp_skill writes only SKILL.md,
2030
+ // so the body may point only at files the skill's directory already holds (a replaced skill's references).
2031
+ const invalid = checkFrontmatter(splitSkill(content).frontmatter, args.name, { strict: true }).findings.filter(finding => finding.level === 'error');
2032
+ if (invalid.length) return toolResult(false, { error: `The skill does not meet the skill format: ${invalid.map(finding => finding.message).join('; ')}` });
2033
+ const missing: string[] = [];
2034
+ for (const target of skillReferences(args.body)) {
2035
+ const resolved = path.resolve(path.dirname(file), target);
2036
+ if (path.isAbsolute(target) || path.relative(path.dirname(file), resolved).startsWith('..') || !(await stat(resolved).then(() => true, () => false))) missing.push(target);
2037
+ }
2038
+ if (missing.length) return toolResult(false, { error: `The body points to ${missing.join(', ')}, which the skill would not have: alp_skill saves only SKILL.md. Put that content in the body, or ask the user to add the files to ${path.dirname(file)} first` });
1974
2039
  const rolesFile = path.join(library, 'role-skills.json');
1975
2040
  const readRoles = async () => {
1976
2041
  const raw = await readFile(rolesFile, 'utf8').catch(() => '{}');
@@ -2003,7 +2068,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
2003
2068
  if (!list.includes(args.name)) list.push(args.name);
2004
2069
  roles[role] = list;
2005
2070
  }
2006
- await writeFile(rolesFile, JSON.stringify(roles, null, 2) + '\n');
2071
+ // Atomic, as alp_skill_retire writes it: a reader never sees a half-written role-skills.json.
2072
+ await writeAtomic(rolesFile, JSON.stringify(roles, null, 2) + '\n');
2007
2073
  } catch (error) {
2008
2074
  return { approved: true, saved: false, error: errorData(error).message, next: 'Tell the user; nothing is retried automatically.' };
2009
2075
  }
@@ -2045,6 +2111,142 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
2045
2111
  return toolResult(true, { status: 'pending_approval', approvalId, file, next: 'Continue other work or end your turn. ALP sends the user\'s decision, and whether the skill was saved, by mail; do not resubmit this draft.' });
2046
2112
  }
2047
2113
 
2114
+ /**
2115
+ * alp_skill_retire: the only way an agent removes a library skill. Through the same
2116
+ * approval as alp_skill, and only once the user approves, the skill directory moves to
2117
+ * <library>/retired-skills/<name>-<time> (kept, never deleted) and leaves role-skills.json.
2118
+ * A skill an agent.json still names stays, and the result says who uses it.
2119
+ */
2120
+ async function skillRetireTool(sessionId: string, session: Session, args: unknown) {
2121
+ const cancellation = approvalCancellation.get(session) ?? 0;
2122
+ args = structuredClone(args);
2123
+ if (!plainObject(args, ['name', 'reason', 'requestId']) || typeof args.name !== 'string' || !/^[a-z0-9][a-z0-9-]{1,62}$/.test(args.name) || !text(args.reason, 300)) {
2124
+ return toolResult(false, { error: 'Retiring a skill needs its name (lowercase letters, digits, hyphens) and a one-line reason of at most 300 characters' });
2125
+ }
2126
+ if (args.requestId !== undefined && !text(args.requestId, 100)) return toolResult(false, { error: 'requestId must be a nonempty string of at most 100 characters' });
2127
+ const library = options.libraryDir;
2128
+ if (!library) return toolResult(false, { error: 'This host keeps no user skill library' });
2129
+ const directory = path.join(library, 'skills', args.name);
2130
+ const file = path.join(directory, 'SKILL.md');
2131
+ const reason = args.reason.replace(/\s+/g, ' ').trim();
2132
+ const draftKey = JSON.stringify(['skill.retire', args.name, reason]);
2133
+ const key = `skill.retire:${args.requestId ?? draftKey}`;
2134
+ const approvals = approvalsOf(sessionId);
2135
+ const previous = approvals.get(key);
2136
+ if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: 'requestId was already used for a different draft' });
2137
+ if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId, file });
2138
+ const content = await readFile(file, 'utf8').catch(() => undefined);
2139
+ if (content === undefined) return toolResult(false, { error: `The library has no skill named ${args.name} (${file})` });
2140
+ const rolesFile = path.join(library, 'role-skills.json');
2141
+ const readRoles = async () => {
2142
+ const roles = JSON.parse(await readFile(rolesFile, 'utf8').catch(() => '{}'));
2143
+ if (!roles || typeof roles !== 'object' || Array.isArray(roles)) throw new Error(`${rolesFile} must be an object of role names to skill lists`);
2144
+ return roles as Record<string, unknown>;
2145
+ };
2146
+ const holders = (roles: Record<string, unknown>) => Object.keys(roles).filter(role => Array.isArray(roles[role]) && (roles[role] as unknown[]).includes(args.name)).sort();
2147
+ // Agents naming the skill in their own agent.json, read directly (not merged with
2148
+ // role-skills.json). An unreadable agent.json throws, so the check fails closed.
2149
+ const namedBy = async () => {
2150
+ const found: string[] = [];
2151
+ for (const [agent, source] of await agentSources(session.mapping.agent.projectRoot, { library, templates: options.templates })) {
2152
+ const where = source.directory ? path.join(source.directory, 'agent.json') : `built-in agents/${agent}/agent.json`;
2153
+ const body = source.directory
2154
+ ? await readFile(path.join(source.directory, 'agent.json'), 'utf8').catch((error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT') return undefined; throw error; })
2155
+ : await builtinText(`agents/${agent}/agent.json`, options.templates);
2156
+ if (body === undefined) continue;
2157
+ let config: unknown;
2158
+ try { config = JSON.parse(body); } catch (error) { throw new Error(`${where}: ${errorData(error).message}`); }
2159
+ const skills = config && typeof config === 'object' ? (config as { skills?: unknown }).skills : undefined;
2160
+ if (Array.isArray(skills) && skills.includes(args.name)) found.push(`agent ${agent}`);
2161
+ }
2162
+ return found.sort();
2163
+ };
2164
+ // The whole skill directory, so a change to any file in it is seen at approval time.
2165
+ const digest = async () => {
2166
+ const hash = createHash('sha256');
2167
+ const walk = async (dir: string, rel: string): Promise<void> => {
2168
+ for (const entry of (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
2169
+ const name = rel ? `${rel}/${entry.name}` : entry.name;
2170
+ if (entry.isDirectory()) { hash.update(`d:${name}\0`); await walk(path.join(dir, entry.name), name); }
2171
+ else { hash.update(`f:${name}\0`); hash.update(await readFile(path.join(dir, entry.name))); hash.update('\0'); }
2172
+ }
2173
+ };
2174
+ await walk(directory, '');
2175
+ return hash.digest('hex');
2176
+ };
2177
+ let given: string[];
2178
+ let users: string[];
2179
+ let tree: string;
2180
+ try { given = holders(await readRoles()); users = await namedBy(); tree = await digest(); } catch (error) { return toolResult(false, { error: errorData(error).message }); }
2181
+ if (approvalCanceled(session, cancellation)) return toolResult(false, { error: 'Skill retirement canceled or session closed; no approval was created' });
2182
+ if ([...userQuestions.values()].some(pending => pending.question.sessionId === sessionId && !pending.gate)) return toolResult(false, { error: 'A question is already waiting for the user; finish it before proposing to retire a skill' });
2183
+ const retired = path.join(library, 'retired-skills', `${args.name}-${new Date().toISOString().replace(/[:.]/g, '-')}`);
2184
+ const restore = `The user restores it with: alp skill restore ${args.name} (or by moving ${retired} back to ${directory} and adding it to the roles again in role-skills.json).`;
2185
+ const approvalId = `q-${randomUUID()}`;
2186
+ const record: { approvalId: string; draftKey: string; result?: Record<string, unknown> } = { approvalId, draftKey };
2187
+ approvals.set(key, record);
2188
+ const say = wordsFor(session);
2189
+ const decision = confirm(sessionId, session,
2190
+ say.skillRetire(session.mapping.agent.name, args.name, file, retired, given.join(', '), users.join(', '), reason) +
2191
+ `\n${say.answerLine(session.mapping.agent.name)}\n\n${content}`, { id: approvalId });
2192
+ const retire = async (): Promise<Record<string, unknown>> => {
2193
+ const refuse = (error: string, next: string) => ({ approved: true, retired: false, error, next });
2194
+ let before: string | undefined;
2195
+ try {
2196
+ if (await digest().catch(() => undefined) !== tree) {
2197
+ return refuse(`The skill ${args.name} changed or was removed since it was proposed; nothing was retired`, 'Read it again and propose again if it should still go.');
2198
+ }
2199
+ const now = await namedBy();
2200
+ if (now.length) return refuse(`The skill ${args.name} is still named by ${now.join(', ')}; nothing was retired`, 'Tell the user; they change those agents first.');
2201
+ // Re-read just before writing, so the write starts from the current file.
2202
+ before = await readFile(rolesFile, 'utf8').catch((error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT') return undefined; throw error; });
2203
+ const roles = await readRoles();
2204
+ const lost = holders(roles);
2205
+ if (JSON.stringify(lost) !== JSON.stringify(given)) {
2206
+ return refuse(`The roles that have ${args.name} changed since it was proposed (proposed: ${given.join(', ') || 'none'}; now: ${lost.join(', ') || 'none'}); nothing was retired`, 'Propose again so the user sees the current roles.');
2207
+ }
2208
+ await mkdir(path.dirname(retired), { recursive: true, mode: 0o700 });
2209
+ if (lost.length) {
2210
+ for (const role of lost) roles[role] = (roles[role] as unknown[]).filter(name => name !== args.name);
2211
+ await writeAtomic(rolesFile, JSON.stringify(roles, null, 2) + '\n');
2212
+ }
2213
+ try {
2214
+ await moveFile(directory, retired);
2215
+ } catch (error) {
2216
+ // Put role-skills.json back as it was, so a failed move changes nothing.
2217
+ if (lost.length) {
2218
+ try { if (before === undefined) await rm(rolesFile, { force: true }); else await writeAtomic(rolesFile, before); }
2219
+ catch (undo) { return refuse(`${errorData(error).message}; restoring ${rolesFile} also failed: ${errorData(undo).message}`, `Tell the user: the skill is still in ${directory} but ${rolesFile} lost it for ${lost.join(', ')}.`); }
2220
+ }
2221
+ return refuse(`${errorData(error).message}; nothing was retired`, 'Tell the user; nothing is retried automatically.');
2222
+ }
2223
+ // What `alp skill restore` reads to give the skill back to the same roles. The skill is
2224
+ // retired either way; without the file a restore needs --roles.
2225
+ let metadata: string | undefined;
2226
+ try {
2227
+ await writeAtomic(path.join(retired, 'retired.json'), JSON.stringify({ name: args.name, roles: lost, retiredAt: new Date().toISOString(), agent: session.mapping.agent.name, path: directory }, null, 2) + '\n');
2228
+ } catch (error) { metadata = errorData(error).message; }
2229
+ runLog(rootOf(sessionId), { event: 'skill.retire', agent: session.mapping.agent.name, name: args.name, roles: lost, retiredTo: retired, ...(metadata ? { metadataError: metadata } : {}) });
2230
+ return { approved: true, retired, roles: lost, ...(metadata ? { metadataError: metadata } : {}), next: `New sessions no longer list the skill. ${restore}` };
2231
+ } catch (error) {
2232
+ return refuse(`${errorData(error).message}; nothing was retired`, 'Tell the user; nothing is retried automatically.');
2233
+ }
2234
+ };
2235
+ void (async () => {
2236
+ const answer = await decision;
2237
+ const canceled = approvalCanceled(session, cancellation);
2238
+ const result = !answer.approved || canceled
2239
+ ? { approved: false, retired: false, outcome: canceled ? 'canceled' : answer.outcome, ...(answer.feedback ? { feedback: answer.feedback } : {}), next: 'Nothing was retired. Revise from the feedback and propose again with a fresh requestId, or drop it.' }
2240
+ : await retire();
2241
+ record.result = { status: 'resolved', approvalId, name: args.name, ...result };
2242
+ runLog(rootOf(sessionId), { event: 'skill.retire.approval', agent: session.mapping.agent.name, ...record.result });
2243
+ if (!closed && !session.closed && sessions.get(sessionId) === session) {
2244
+ post(sessionId, { kind: 'result', from: 'ALP', assignment: approvalId, body: `Skill retirement result: ${JSON.stringify(record.result)}` });
2245
+ }
2246
+ })();
2247
+ return toolResult(true, { status: 'pending_approval', approvalId, file, next: 'Continue other work or end your turn. ALP sends the user\'s decision, and whether the skill was retired, by mail; do not resubmit this request.' });
2248
+ }
2249
+
2048
2250
  let scheduleHandler: ScheduleHandler | undefined;
2049
2251
 
2050
2252
  /**
@@ -2735,7 +2937,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
2735
2937
  }
2736
2938
 
2737
2939
  if (
2738
- !['alp_delegate', 'alp_handoff', 'alp_wait', 'alp_cancel', 'alp_send', 'alp_ask', 'alp_merge', 'alp_discard', 'alp_resolve', 'alp_recall', 'alp_verify', 'alp_pin', 'alp_board', 'alp_unpin', 'alp_lesson', 'alp_lesson_curate', 'alp_skill', 'alp_issue', 'alp_task', 'alp_schedule'].includes(params.tool) ||
2940
+ !['alp_delegate', 'alp_handoff', 'alp_wait', 'alp_cancel', 'alp_send', 'alp_ask', 'alp_merge', 'alp_discard', 'alp_resolve', 'alp_recall', 'alp_verify', 'alp_pin', 'alp_board', 'alp_unpin', 'alp_lesson', 'alp_lesson_curate', 'alp_skill', 'alp_skill_retire', 'alp_issue', 'alp_task', 'alp_schedule'].includes(params.tool) ||
2739
2941
  params.namespace != null ||
2740
2942
  typeof params.callId !== 'string'
2741
2943
  ) {
@@ -2753,12 +2955,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
2753
2955
  if (oversized) return toolResult(false, { error: oversized });
2754
2956
  // The supervisor only reads the board and tasks, and writes to main.
2755
2957
  if (session.role === 'supervisor' && !['alp_send', 'alp_board', 'alp_task'].includes(params.tool)) return toolResult(false, { error: 'The supervisor only uses alp_send, alp_board and alp_task' });
2756
- if (['alp_lesson', 'alp_lesson_curate', 'alp_skill'].includes(params.tool) && !supervises(session)) return toolResult(false, { error: 'Only a supervised main records lessons and skills' });
2958
+ if (['alp_lesson', 'alp_lesson_curate', 'alp_skill', 'alp_skill_retire'].includes(params.tool) && !supervises(session)) return toolResult(false, { error: 'Only a supervised main records lessons and skills' });
2757
2959
  if (params.tool === 'alp_issue' && (session.parent || session.mapping.agent.name !== mainOf(session.mapping))) return toolResult(false, { error: 'Only main files issues; report the problem to your requester' });
2758
2960
  const work =
2759
2961
  params.tool === 'alp_lesson' ? lessonTool(sessionId, session, args)
2760
2962
  : params.tool === 'alp_lesson_curate' ? lessonCurateTool(sessionId, session, args)
2761
2963
  : params.tool === 'alp_skill' ? skillTool(sessionId, session, args)
2964
+ : params.tool === 'alp_skill_retire' ? skillRetireTool(sessionId, session, args)
2762
2965
  : params.tool === 'alp_issue' ? issueTool(sessionId, session, args)
2763
2966
  : params.tool === 'alp_schedule' ? scheduleTool(sessionId, session, args)
2764
2967
  : params.tool === 'alp_task' ? taskToolCall(sessionId, session, args)
@@ -3250,14 +3453,36 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3250
3453
  if (args.agent === 'oracle' && !session.mapping.oracleModels.includes(args.model)) return toolResult(false, { error: `Oracle runs on ${session.mapping.oracleModels.join(' or ')}; pass one as model. For two opinions, start one on each with wait: false` });
3251
3454
  const configuredModels = args.agent === 'oracle' ? [] : session.mapping.modelProfiles[args.agent] ?? [];
3252
3455
  const listed = configuredModels.map(profileModel).filter((id): id is string => Boolean(id));
3456
+ const allowed = listed.map(id => id.endsWith(':*') ? `any ${id.slice(0, -1)} model` : id).join(' or ');
3253
3457
  // The requester picks a model and effort for each task among several profiles, or any model of a provider:*; one named profile needs no choice.
3254
3458
  const choosing = configuredModels.length > 1 || configuredModels.some(anyModel);
3255
- if (choosing && (args.model === undefined || args.thinking === undefined)) return toolResult(false, { error: `${args.agent} has several model profiles: choose one for this task as model, its effort as thinking, and say why in modelReason`, models: listed });
3256
- if (choosing && !offers(configuredModels, args.model)) return toolResult(false, { error: `${args.model} is not one of ${args.agent}'s model profiles`, models: listed });
3257
- const efforts = choosing ? profileEfforts(args.model) : [];
3258
- if (efforts.length && !efforts.includes(args.thinking)) return toolResult(false, { error: `${args.model} takes effort ${efforts.join(', ')}`, efforts });
3459
+ if (choosing && (args.model === undefined || args.thinking === undefined)) return toolResult(false, { error: `${args.agent} has several model profiles: choose one for this task as model, its effort as thinking, and say why in modelReason. Pass ${allowed}`, models: listed });
3460
+ // The profiles that name a model are the target's allowlist, one as much as several (P2): one named profile means exactly that model.
3461
+ if (args.model !== undefined && listed.length && !offers(configuredModels, args.model)) {
3462
+ // Actionable in one step: what may be passed now, and where the user widens the list.
3463
+ const team = session.mapping.workflow.mode;
3464
+ const settingsFile = path.join(session.mapping.agent.projectRoot, '.alp', 'settings.json');
3465
+ // alp setup writes only Phở's and Cafe's profiles, and only Claude and Codex models: offer it where it can help.
3466
+ const provider = args.model.slice(0, args.model.indexOf(':'));
3467
+ const setup = ['pho', 'cafe'].includes(team) && ['claude', 'codex'].includes(provider)
3468
+ ? `, or run alp setup ${session.mapping.agent.projectRoot} --runtime mix, which gives Phở's and Cafe's members both Claude and Codex profiles (it keeps profiles written by hand or set in a team.json)`
3469
+ : '';
3470
+ return toolResult(false, {
3471
+ error: `${args.model} is not one of ${args.agent}'s model profiles in team ${team}; pass ${allowed}${choosing ? '' : ', or omit model to run on it'}. ` +
3472
+ `The user can allow it by adding it to team.${team}.${args.agent}.profiles in ${settingsFile} ("provider:model" or "provider:model:effort", or "${provider}:*" for any model of that provider, which makes you choose model and effort per assignment)${setup}.`,
3473
+ models: listed,
3474
+ });
3475
+ }
3259
3476
  const configuredDefault = !choosing && listed.length === 1 ? listed[0] : undefined;
3260
3477
  const delegatedModel = args.model ?? configuredDefault ?? `${session.runtimeKind}:${session.mapping.model}`;
3478
+ // An effort is checked against the model's wherever the target has profiles; where ALP cannot check it
3479
+ // (a model the catalog lists without efforts, antigravity:, acp:, or a target without profiles) it is
3480
+ // passed on, and the answer says so instead of staying silent.
3481
+ const efforts = args.thinking !== undefined && listed.length ? profileEfforts(delegatedModel) : [];
3482
+ if (efforts.length && !efforts.includes(args.thinking)) return toolResult(false, { error: `${delegatedModel} takes effort ${efforts.join(', ')}`, efforts });
3483
+ const thinkingNote = args.thinking !== undefined && !efforts.length
3484
+ ? (listed.length ? `effort ${args.thinking} was not checked: ALP does not know which efforts ${delegatedModel} takes` : `effort ${args.thinking} was not checked: no model profile of ${args.agent} names a model`)
3485
+ : undefined;
3261
3486
  const delegatedThinking = args.thinking ?? selectedProfile(configuredModels, delegatedModel)?.effort ?? (args.model || configuredDefault ? undefined : session.mapping.thinking);
3262
3487
  // A paused runtime takes no new assignments; another runtime may.
3263
3488
  const childRuntime = delegatedModel.split(':')[0] as RuntimeKind;
@@ -3267,19 +3492,21 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3267
3492
  if (hold) {
3268
3493
  const other = RUNTIMES.find(kind => kind !== childRuntime && !pauseOf(kind));
3269
3494
  const instead = listed.filter(id => other && id.startsWith(`${other}:`)).map(id => id.endsWith(':*') ? `any ${id.slice(0, -1)} model` : id);
3495
+ // Only a model the target's profiles allow can move it: a target without profiles takes any.
3270
3496
  const next = !other ? 'Wait until the user resumes ALP'
3271
- : !choosing ? `Pass a model of ${other}: from the catalog to run it on ${label(other)}, or wait`
3497
+ : !listed.length ? `Pass a model of ${other}: from the catalog to run it on ${label(other)}, or wait`
3272
3498
  : instead.length ? `Pass ${instead.join(' or ')} to run it on ${label(other)}, or wait` : `None of ${args.agent}'s model profiles runs on ${label(other)}: wait`;
3273
3499
  return toolResult(false, { error: describePause(hold, paused.all ? undefined : childRuntime), next });
3274
3500
  }
3275
3501
  // The child's permission profile caps its mode, as resolving its session will.
3276
3502
  let childProfile;
3277
- try { childProfile = await profileFor(session.mapping.agent.projectRoot, options.libraryDir, args.agent); }
3503
+ try { childProfile = await profileFor(session.mapping.agent.projectRoot, options.libraryDir, args.agent, { readOnly: readOnlyMember(session.mapping, args.agent) }); }
3278
3504
  catch (error) { return toolResult(false, { error: errorData(error).message }); }
3279
3505
  const childMode = childProfile ? capMode(args.mode ?? session.mapping.mode, childProfile.base) : args.mode ?? session.mapping.mode;
3280
3506
  const capped = {
3281
3507
  ...(childProfile && childMode !== (args.mode ?? session.mapping.mode) ? { mode: childMode, modeNote: `${args.agent} runs ${childMode}: its permission profile ${childProfile.name} caps it` } : {}),
3282
3508
  ...(childProfile?.workdir === 'copy' && isolationOf(args) === 'shared' ? { workdirNote: `${args.agent} works in a disposable copy of your tree; nothing it changes reaches yours` } : {}),
3509
+ ...(thinkingNote ? { thinkingNote } : {}),
3283
3510
  };
3284
3511
  let sharedContinuation: RecallEntry | undefined;
3285
3512
  if (args.continueFrom !== undefined) {
@@ -3319,7 +3546,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3319
3546
  let task: Task | undefined;
3320
3547
  if (args.taskId !== undefined) {
3321
3548
  if (session.parent || session.mapping.agent.name !== mainOf(session.mapping)) return toolResult(false, { error: 'Only main gives tasks to assignments' });
3322
- if (READ_ONLY_AGENTS.includes(args.agent)) return toolResult(false, { error: 'taskId gives a task to lead or peer; for advice about a task, name it in the brief' });
3549
+ if (readOnlyMember(session.mapping, args.agent)) return toolResult(false, { error: 'taskId gives a task to lead or peer; for advice about a task, name it in the brief' });
3323
3550
  if (typeof args.taskId !== 'string') return toolResult(false, { error: 'taskId must be a task id' });
3324
3551
  // Checked here for a clear refusal; the start below checks again under the task lock.
3325
3552
  try {
@@ -3808,6 +4035,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3808
4035
  sessionId,
3809
4036
  session,
3810
4037
  item,
4038
+ false,
4039
+ turn.id,
3811
4040
  );
3812
4041
  }
3813
4042
  }
@@ -3898,7 +4127,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3898
4127
  session.role,
3899
4128
  supervises(session),
3900
4129
  lessonFiles(mapping),
3901
- Object.fromEntries(await Promise.all(targets.map(async target => [target, await profileFor(mapping.agent.projectRoot, options.libraryDir, target).catch(() => null)] as const))),
4130
+ Object.fromEntries(await Promise.all(targets.map(async target => [target, await profileFor(mapping.agent.projectRoot, options.libraryDir, target, { readOnly: readOnlyMember(mapping, target) }).catch(() => null)] as const))),
3902
4131
  );
3903
4132
  if (session.spec.writeRoot && session.runtimeKind === 'claude' && mapping.mode === 'workspace-write' && claudeSandboxAvailable()) Object.assign(config, { floor: 'workspace-write' });
3904
4133
  if (session.spec.writeRoot) config.developerInstructions += `\nWrite scope: change files only under ${session.spec.writeRoot}. Your working directory is there; the ALP project, tasks and board remain ${mapping.agent.projectRoot}. Board paths are project-relative or absolute; use absolute paths for this write root. This scope does not grant permission to write outside your mode.`;
@@ -4177,9 +4406,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4177
4406
  if (mapping.agent.name !== session.mapping.agent.name) return refused('agent_mismatch', 'A session keeps its agent; start a new session for another agent');
4178
4407
  const agent = session.mapping.agent.name;
4179
4408
  if (teamChanged && agent === mainOf(session.mapping) && agent !== mainOf(mapping)) return refused('agent_mismatch', `Team ${mapping.team?.label ?? team}'s main agent is ${mainOf(mapping)}, not ${agent}; start a new session with that team`);
4180
- // Never more permissions: the mode asked for stays within the profile and READ_ONLY_AGENTS, and a
4409
+ // Never more permissions: the mode asked for stays within the profile and read-only members (readOnlyMember), and a
4181
4410
  // team or effort change never raises the mode the session runs with.
4182
- if (changes.mode !== undefined && mapping.mode !== changes.mode) return refused('permission_escalation', READ_ONLY_AGENTS.includes(agent) ? 'Advisors and the supervisor must remain read-only' : `Permission profile ${mapping.permissions?.name ?? ''} allows at most ${mapping.permissions?.base ?? mapping.mode}`.replace('profile allows', 'profile allows'));
4411
+ if (changes.mode !== undefined && mapping.mode !== changes.mode) return refused('permission_escalation', readOnlyMember(mapping, agent) ? 'Advisors and the supervisor must remain read-only' : `Permission profile ${mapping.permissions?.name ?? ''} allows at most ${mapping.permissions?.base ?? mapping.mode}`.replace('profile allows', 'profile allows'));
4183
4412
  if (changes.mode === undefined && !withinMode(mapping.mode, session.mapping.mode)) return refused('permission_escalation', `The change would run the session in ${mapping.mode}, beyond its ${session.mapping.mode}`);
4184
4413
  const before = executablesOf(session.mapping);
4185
4414
  const added = [...executablesOf(mapping)].filter(entry => !before.has(entry));
@@ -4599,7 +4828,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4599
4828
  if (!modes.some(candidate => candidate.id === mode)) throw new Error(`Unsupported mode '${mode}'`);
4600
4829
  const profile = session.mapping.permissions;
4601
4830
  if (profile && !withinMode(mode, profile.base)) {
4602
- throw new Error(READ_ONLY_AGENTS.includes(session.mapping.agent.name) ? 'Advisors and the supervisor must remain read-only' : `Permission profile ${profile.name} allows at most ${profile.base}`);
4831
+ throw new Error(readOnlyMember(session.mapping, session.mapping.agent.name) ? 'Advisors and the supervisor must remain read-only' : `Permission profile ${profile.name} allows at most ${profile.base}`);
4603
4832
  }
4604
4833
  const parent = session.parent ? sessions.get(session.parent) : undefined;
4605
4834
  if (parent && !withinMode(mode, parent.mapping.mode)) throw new Error('Child cannot exceed parent permissions');
@@ -4689,7 +4918,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4689
4918
  }
4690
4919
 
4691
4920
  /** Starts a turn or steers the running one; throws when the prompt was not delivered. */
4692
- async function startPrompt(sessionId: string, prompt: PromptInput, origin: TurnOrigin, wake?: MailEvent[]) {
4921
+ async function startPrompt(sessionId: string, prompt: PromptInput, origin: TurnOrigin, wake?: MailEvent[], internalCompact = false) {
4693
4922
  const session = openOf(sessionId);
4694
4923
 
4695
4924
  if (
@@ -4703,6 +4932,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4703
4932
  if (prompt.content.some(content => content.type !== 'text' && content.type !== 'image' && content.type !== 'attachment')) {
4704
4933
  throw new Error('Only text, image and attachment prompts are supported');
4705
4934
  }
4935
+ const refusal = origin === 'user' ? nativeCommandRefusal(session.runtimeKind, prompt.content, session.runtime.customCommands?.()) : undefined;
4936
+ if (refusal) throw new Error(refusal);
4706
4937
  // Inline images only, never a path or URL: the native input gets a data URL ALP builds itself.
4707
4938
  const images = prompt.content.filter(content => content.type === 'image') as Array<{ type: 'image'; mimeType: string; data: string }>;
4708
4939
  if (images.length) {
@@ -4779,7 +5010,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4779
5010
  ) {
4780
5011
  session.text.clear();
4781
5012
  session.toolCalls.clear();
4782
- if (!/^alp-wake-compact-/.test(prompt.clientMessageId)) session.compactCooling = false;
5013
+ if (!internalCompact) session.compactCooling = false;
4783
5014
  session.supervisorWake = !!wake?.length && wake.every(event => event.defer);
4784
5015
 
4785
5016
  // A wake continues the same assignment: keep its handoff and limits.
@@ -4812,6 +5043,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4812
5043
  const after = mail.length && !wake ? [{ type: 'text', text: promptSafe(renderMail(mail, session.parentAgent)), text_elements: [] }] : [];
4813
5044
  const inputLayout: InputLayout = { textParts: 1 + before.length + 1 + attached.length + after.length, prompt: 1 + before.length };
4814
5045
  const listed = attached.map(({ attachment }) => attachmentMeta(attachment));
5046
+ const invoked = session.runtimeKind === 'codex' && origin === 'user' && prompt.delivery !== 'steer'
5047
+ ? session.mapping.agent.skills.find(skill => text.match(/^\/(\S+)(?:\s|$)/)?.[1] === skill.name) : undefined;
4815
5048
  const nativeInput = [
4816
5049
  { type: 'text', text: promptSafe(CATALOG + JSON.stringify({ inputLayout, ...(orchestration as object), ...(listed.length ? { attachments: listed } : {}) })), text_elements: [] },
4817
5050
  ...before,
@@ -4823,6 +5056,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4823
5056
  ...attached.map(({ attachment, staged }) => ({ type: 'text', text: promptSafe(attachmentPart(attachment, staged)), text_elements: [] })),
4824
5057
  ...images.map(image => ({ type: 'image', url: `data:${image.mimeType};base64,${image.data}` })),
4825
5058
  ...after,
5059
+ // "/<skill> ..." from the user loads that ALP skill in Codex, as its own $<skill> does (t-efa3).
5060
+ ...(invoked ? [{ type: 'skill', name: invoked.name, path: invoked.path }] : []),
4826
5061
  ];
4827
5062
 
4828
5063
  const result =
@@ -4865,6 +5100,12 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4865
5100
  ? session.active!
4866
5101
  : result.turn.id;
4867
5102
 
5103
+ if (internalCompact) {
5104
+ const echoes = compactEchoes.get(session) ?? new Map<string, string>();
5105
+ echoes.set(`${session.threadId}:${turnId}`, inputDigest(nativeInput.flatMap(part => 'text' in part ? [String(part.text)] : [])));
5106
+ compactEchoes.set(session, echoes);
5107
+ }
5108
+
4868
5109
  for (const event of mail) event.deliveredTurn = turnId;
4869
5110
 
4870
5111
  // Only transport-accepted user input renews the root-tree budgets.
@@ -4877,7 +5118,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4877
5118
  prompt.clientMessageId,
4878
5119
  );
4879
5120
 
4880
- emit(sessionId, {
5121
+ if (!internalCompact) emit(sessionId, {
4881
5122
  type: 'item',
4882
5123
  item: {
4883
5124
  kind: 'user_message',
@@ -5023,6 +5264,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
5023
5264
  }, ADOPTION),
5024
5265
  bindSchedules(handler: ScheduleHandler | undefined) { scheduleHandler = handler; },
5025
5266
  bindAttachments(reader: AttachmentReader | undefined) { attachmentReader = reader; },
5267
+ refusesPrompt(sessionId: string, content: PromptContent) {
5268
+ const session = sessions.get(sessionId);
5269
+ return session ? nativeCommandRefusal(session.runtimeKind, content, session.runtime.customCommands?.()) : undefined;
5270
+ },
5026
5271
  takesAttachments(sessionId: string) {
5027
5272
  const session = sessions.get(sessionId);
5028
5273
  return !!session && !session.closed && attachmentRoutes(session).includes('file.path');
@@ -5101,6 +5346,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
5101
5346
 
5102
5347
  reload: sessionId => enqueue(() => reloadSession(sessionId)),
5103
5348
  compact: (sessionId: string) => requestCompact(sessionId),
5349
+ commands: (sessionId: string) => listCommands(sessionId),
5104
5350
 
5105
5351
  previewConfigure: (sessionId, changes) => previewConfigureSession(sessionId, changes),
5106
5352
 
@@ -5327,6 +5573,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
5327
5573
  },
5328
5574
 
5329
5575
  async shutdown() {
5576
+ compactEchoes.clear();
5330
5577
  closed = true;
5331
5578
 
5332
5579
  await queue;