@anhlp/alp-runtime 0.0.1-beta.7 → 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 (52) 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 +33 -2
  8. package/dist/claude-transport.js +41 -5
  9. package/dist/contracts.d.ts +12 -1
  10. package/dist/index.d.ts +4 -3
  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.js +4 -4
  23. package/dist/runtime.js +243 -33
  24. package/dist/session-config.d.ts +75 -6
  25. package/dist/session-config.js +9 -5
  26. package/dist/session-state.d.ts +2 -0
  27. package/dist/skill-resources.d.ts +30 -0
  28. package/dist/skill-resources.js +55 -0
  29. package/dist/tools.d.ts +27 -1
  30. package/dist/tools.js +20 -1
  31. package/dist/write-error.d.ts +2 -0
  32. package/dist/write-error.js +10 -0
  33. package/package.json +4 -4
  34. package/src/acp-transport.ts +3 -0
  35. package/src/antigravity-transport.ts +39 -8
  36. package/src/assignment-results.ts +23 -15
  37. package/src/catalog.ts +3 -1
  38. package/src/claude-transport.ts +74 -7
  39. package/src/contracts.ts +12 -0
  40. package/src/index.ts +4 -3
  41. package/src/language.ts +10 -0
  42. package/src/live.ts +7 -3
  43. package/src/model-catalog.ts +156 -6
  44. package/src/model-probes.ts +2 -2
  45. package/src/recall.ts +4 -3
  46. package/src/resolve.ts +9 -5
  47. package/src/runtime.ts +255 -29
  48. package/src/session-config.ts +13 -5
  49. package/src/session-state.ts +2 -0
  50. package/src/skill-resources.ts +73 -0
  51. package/src/tools.ts +22 -1
  52. package/src/write-error.ts +4 -0
package/src/runtime.ts CHANGED
@@ -14,17 +14,19 @@ import { claudeCut, codexForkEnd, codexForkRefusal, pendingChain, type ChainEntr
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, skillDescription, 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(() => {});
@@ -1987,6 +2026,16 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
1987
2026
  if (previous) return toolResult(true, previous.result ?? { status: 'pending_approval', approvalId: previous.approvalId, file });
1988
2027
  const existing = await readFile(file, 'utf8').catch(() => undefined);
1989
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` });
1990
2039
  const rolesFile = path.join(library, 'role-skills.json');
1991
2040
  const readRoles = async () => {
1992
2041
  const raw = await readFile(rolesFile, 'utf8').catch(() => '{}');
@@ -2019,7 +2068,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
2019
2068
  if (!list.includes(args.name)) list.push(args.name);
2020
2069
  roles[role] = list;
2021
2070
  }
2022
- 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');
2023
2073
  } catch (error) {
2024
2074
  return { approved: true, saved: false, error: errorData(error).message, next: 'Tell the user; nothing is retried automatically.' };
2025
2075
  }
@@ -2061,6 +2111,142 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
2061
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.' });
2062
2112
  }
2063
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
+
2064
2250
  let scheduleHandler: ScheduleHandler | undefined;
2065
2251
 
2066
2252
  /**
@@ -2751,7 +2937,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
2751
2937
  }
2752
2938
 
2753
2939
  if (
2754
- !['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) ||
2755
2941
  params.namespace != null ||
2756
2942
  typeof params.callId !== 'string'
2757
2943
  ) {
@@ -2769,12 +2955,13 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
2769
2955
  if (oversized) return toolResult(false, { error: oversized });
2770
2956
  // The supervisor only reads the board and tasks, and writes to main.
2771
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' });
2772
- 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' });
2773
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' });
2774
2960
  const work =
2775
2961
  params.tool === 'alp_lesson' ? lessonTool(sessionId, session, args)
2776
2962
  : params.tool === 'alp_lesson_curate' ? lessonCurateTool(sessionId, session, args)
2777
2963
  : params.tool === 'alp_skill' ? skillTool(sessionId, session, args)
2964
+ : params.tool === 'alp_skill_retire' ? skillRetireTool(sessionId, session, args)
2778
2965
  : params.tool === 'alp_issue' ? issueTool(sessionId, session, args)
2779
2966
  : params.tool === 'alp_schedule' ? scheduleTool(sessionId, session, args)
2780
2967
  : params.tool === 'alp_task' ? taskToolCall(sessionId, session, args)
@@ -3266,14 +3453,36 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3266
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` });
3267
3454
  const configuredModels = args.agent === 'oracle' ? [] : session.mapping.modelProfiles[args.agent] ?? [];
3268
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 ');
3269
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.
3270
3458
  const choosing = configuredModels.length > 1 || configuredModels.some(anyModel);
3271
- 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 });
3272
- if (choosing && !offers(configuredModels, args.model)) return toolResult(false, { error: `${args.model} is not one of ${args.agent}'s model profiles`, models: listed });
3273
- const efforts = choosing ? profileEfforts(args.model) : [];
3274
- 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
+ }
3275
3476
  const configuredDefault = !choosing && listed.length === 1 ? listed[0] : undefined;
3276
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;
3277
3486
  const delegatedThinking = args.thinking ?? selectedProfile(configuredModels, delegatedModel)?.effort ?? (args.model || configuredDefault ? undefined : session.mapping.thinking);
3278
3487
  // A paused runtime takes no new assignments; another runtime may.
3279
3488
  const childRuntime = delegatedModel.split(':')[0] as RuntimeKind;
@@ -3283,19 +3492,21 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3283
3492
  if (hold) {
3284
3493
  const other = RUNTIMES.find(kind => kind !== childRuntime && !pauseOf(kind));
3285
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.
3286
3496
  const next = !other ? 'Wait until the user resumes ALP'
3287
- : !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`
3288
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`;
3289
3499
  return toolResult(false, { error: describePause(hold, paused.all ? undefined : childRuntime), next });
3290
3500
  }
3291
3501
  // The child's permission profile caps its mode, as resolving its session will.
3292
3502
  let childProfile;
3293
- 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) }); }
3294
3504
  catch (error) { return toolResult(false, { error: errorData(error).message }); }
3295
3505
  const childMode = childProfile ? capMode(args.mode ?? session.mapping.mode, childProfile.base) : args.mode ?? session.mapping.mode;
3296
3506
  const capped = {
3297
3507
  ...(childProfile && childMode !== (args.mode ?? session.mapping.mode) ? { mode: childMode, modeNote: `${args.agent} runs ${childMode}: its permission profile ${childProfile.name} caps it` } : {}),
3298
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 } : {}),
3299
3510
  };
3300
3511
  let sharedContinuation: RecallEntry | undefined;
3301
3512
  if (args.continueFrom !== undefined) {
@@ -3335,7 +3546,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3335
3546
  let task: Task | undefined;
3336
3547
  if (args.taskId !== undefined) {
3337
3548
  if (session.parent || session.mapping.agent.name !== mainOf(session.mapping)) return toolResult(false, { error: 'Only main gives tasks to assignments' });
3338
- 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' });
3339
3550
  if (typeof args.taskId !== 'string') return toolResult(false, { error: 'taskId must be a task id' });
3340
3551
  // Checked here for a clear refusal; the start below checks again under the task lock.
3341
3552
  try {
@@ -3824,6 +4035,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3824
4035
  sessionId,
3825
4036
  session,
3826
4037
  item,
4038
+ false,
4039
+ turn.id,
3827
4040
  );
3828
4041
  }
3829
4042
  }
@@ -3914,7 +4127,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
3914
4127
  session.role,
3915
4128
  supervises(session),
3916
4129
  lessonFiles(mapping),
3917
- 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))),
3918
4131
  );
3919
4132
  if (session.spec.writeRoot && session.runtimeKind === 'claude' && mapping.mode === 'workspace-write' && claudeSandboxAvailable()) Object.assign(config, { floor: 'workspace-write' });
3920
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.`;
@@ -4193,9 +4406,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4193
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');
4194
4407
  const agent = session.mapping.agent.name;
4195
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`);
4196
- // 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
4197
4410
  // team or effort change never raises the mode the session runs with.
4198
- 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'));
4199
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}`);
4200
4413
  const before = executablesOf(session.mapping);
4201
4414
  const added = [...executablesOf(mapping)].filter(entry => !before.has(entry));
@@ -4615,7 +4828,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4615
4828
  if (!modes.some(candidate => candidate.id === mode)) throw new Error(`Unsupported mode '${mode}'`);
4616
4829
  const profile = session.mapping.permissions;
4617
4830
  if (profile && !withinMode(mode, profile.base)) {
4618
- 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}`);
4619
4832
  }
4620
4833
  const parent = session.parent ? sessions.get(session.parent) : undefined;
4621
4834
  if (parent && !withinMode(mode, parent.mapping.mode)) throw new Error('Child cannot exceed parent permissions');
@@ -4705,7 +4918,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4705
4918
  }
4706
4919
 
4707
4920
  /** Starts a turn or steers the running one; throws when the prompt was not delivered. */
4708
- 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) {
4709
4922
  const session = openOf(sessionId);
4710
4923
 
4711
4924
  if (
@@ -4719,6 +4932,8 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4719
4932
  if (prompt.content.some(content => content.type !== 'text' && content.type !== 'image' && content.type !== 'attachment')) {
4720
4933
  throw new Error('Only text, image and attachment prompts are supported');
4721
4934
  }
4935
+ const refusal = origin === 'user' ? nativeCommandRefusal(session.runtimeKind, prompt.content, session.runtime.customCommands?.()) : undefined;
4936
+ if (refusal) throw new Error(refusal);
4722
4937
  // Inline images only, never a path or URL: the native input gets a data URL ALP builds itself.
4723
4938
  const images = prompt.content.filter(content => content.type === 'image') as Array<{ type: 'image'; mimeType: string; data: string }>;
4724
4939
  if (images.length) {
@@ -4795,7 +5010,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4795
5010
  ) {
4796
5011
  session.text.clear();
4797
5012
  session.toolCalls.clear();
4798
- if (!/^alp-wake-compact-/.test(prompt.clientMessageId)) session.compactCooling = false;
5013
+ if (!internalCompact) session.compactCooling = false;
4799
5014
  session.supervisorWake = !!wake?.length && wake.every(event => event.defer);
4800
5015
 
4801
5016
  // A wake continues the same assignment: keep its handoff and limits.
@@ -4885,6 +5100,12 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4885
5100
  ? session.active!
4886
5101
  : result.turn.id;
4887
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
+
4888
5109
  for (const event of mail) event.deliveredTurn = turnId;
4889
5110
 
4890
5111
  // Only transport-accepted user input renews the root-tree budgets.
@@ -4897,7 +5118,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
4897
5118
  prompt.clientMessageId,
4898
5119
  );
4899
5120
 
4900
- emit(sessionId, {
5121
+ if (!internalCompact) emit(sessionId, {
4901
5122
  type: 'item',
4902
5123
  item: {
4903
5124
  kind: 'user_message',
@@ -5043,6 +5264,10 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
5043
5264
  }, ADOPTION),
5044
5265
  bindSchedules(handler: ScheduleHandler | undefined) { scheduleHandler = handler; },
5045
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
+ },
5046
5271
  takesAttachments(sessionId: string) {
5047
5272
  const session = sessions.get(sessionId);
5048
5273
  return !!session && !session.closed && attachmentRoutes(session).includes('file.path');
@@ -5348,6 +5573,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
5348
5573
  },
5349
5574
 
5350
5575
  async shutdown() {
5576
+ compactEchoes.clear();
5351
5577
  closed = true;
5352
5578
 
5353
5579
  await queue;
@@ -6,7 +6,7 @@ import { models, thinkingOptionsFor } from './catalog.js';
6
6
  import { claudeSandboxAvailable, SKILL_PLUGIN } from './claude-transport.js';
7
7
  import { languageInstruction } from './language.js';
8
8
  import { antigravityModeText } from './antigravity-transport.js';
9
- import { HANDOFF_TOOL, WAIT_TOOL, SEND_TOOL, MERGE_TOOL, VERIFY_TOOL, DISCARD_TOOL, RESOLVE_TOOL, CANCEL_TOOL, RECALL_TOOL, PIN_TOOL, BOARD_TOOL, UNPIN_TOOL, ASK_TOOL, LESSON_TOOL, LESSON_CURATE_TOOL, SKILL_TOOL, ISSUE_TOOL, SCHEDULE_TOOL, mainOf, taskActions, taskTool } from './tools.js';
9
+ import { HANDOFF_TOOL, WAIT_TOOL, SEND_TOOL, MERGE_TOOL, VERIFY_TOOL, DISCARD_TOOL, RESOLVE_TOOL, CANCEL_TOOL, RECALL_TOOL, PIN_TOOL, BOARD_TOOL, UNPIN_TOOL, ASK_TOOL, LESSON_TOOL, LESSON_CURATE_TOOL, SKILL_TOOL, SKILL_RETIRE_TOOL, ISSUE_TOOL, SCHEDULE_TOOL, mainOf, taskActions, taskTool } from './tools.js';
10
10
 
11
11
  import { COMPACT_SHARE } from './runtime-context.js';
12
12
 
@@ -83,7 +83,7 @@ export function modelProfileNote(mapping: ResolvedSession, targets: string[]) {
83
83
  const options = (profile: import('@anhlp/alp-core/types').AgentModelConfig) => anyModel(profile)
84
84
  ? `any ${profile.provider} model (the runtime catalog snapshot lists what ${profile.provider} offers when you run on it), such as ${models.filter(model => model.id.startsWith(`${profile.provider}:`)).map(model => option(model.id)).join('; ')}`
85
85
  : option(profileModel(profile)!, profile.effort);
86
- return ['Model profiles of your targets. An agent with one named profile runs on it unless you pass another model. For an agent with several, or with any model of a provider, you choose both for each assignment: weigh the task\'s difficulty, ambiguity, risk and the autonomy it needs against speed and cost, pass the model with alp_delegate model and the effort with thinking, and say why in modelReason. There is no default, and a model outside its profiles is refused. ' +
86
+ return ['Model profiles of your targets are the models you may pass for them; a model outside them is refused. An agent with one named profile runs on exactly that model: omit model, or pass that one. For an agent with several, or with any model of a provider, you choose both for each assignment: weigh the task\'s difficulty, ambiguity, risk and the autonomy it needs against speed and cost, pass the model with alp_delegate model and the effort with thinking, and say why in modelReason; there is no default. An effort ALP cannot check for a model is passed on as given, and the answer says so. ' +
87
87
  choices.map(([agent, profiles]) => profiles.length === 1 && !anyModel(profiles[0]) ? `${agent}: ${one(profiles[0])}` : `${agent}, choose a model and effort: ${profiles.map(options).join('; ')}`).join('. ') + '.'];
88
88
  }
89
89
 
@@ -193,7 +193,15 @@ export function nativeSessionConfig(
193
193
  ...modelProfileNote(mapping, targets),
194
194
  // The team's house rules (ALPD §42); Phở and Cafe's are the text this line held before teams.
195
195
  `Profile: ${mapping.workflow.mode}; fixed for this session.${mapping.houseRules ? ` ${mapping.houseRules}` : ''}`,
196
- `Oracle runs on ${mapping.oracleModels.join(' or ')}; pass one as model (effort follows the team's oracle settings, otherwise high). For two independent opinions, start one oracle on each model with wait: false and compare their advice. If the model you need is unavailable, say so rather than choosing another. Usage context is advisory, may be unavailable or stale; never infer quota from token counts. Respect known exhausted limits and report them.`,
196
+ // Only an agent that can delegate to oracle is told how to; two opinions need two oracle models.
197
+ [
198
+ ...(targets.includes('oracle')
199
+ ? [`Oracle runs on ${mapping.oracleModels.join(' or ')}; pass one as model (effort follows the team's oracle settings, otherwise high).` +
200
+ (mapping.oracleModels.length > 1 ? ' For two independent opinions, start one oracle on each model with wait: false and compare their advice.' : '') +
201
+ ' If the model you need is unavailable, say so rather than choosing another.']
202
+ : []),
203
+ 'Usage context is advisory, may be unavailable or stale; never infer quota from token counts. Respect known exhausted limits and report them.',
204
+ ].join(' '),
197
205
  ...(supervised
198
206
  ? ['A supervisor reviews your process after each turn. Its notes ask about process mistakes: answer them in your reply, then record each lesson with alp_lesson (scope project for this project, user for every project). Do not argue a note away; when it is wrong, say why in one line. ' +
199
207
  'When three or more lessons cover one theme, or a lesson recurs, distill them into a skill with alp_skill: a method with steps and checks, listing the lessons it replaces. Scope it to the roles whose work it guides: yourself, lead, peer, oracle, reviewer, supervisor, or a custom agent; a lesson about briefing peers is yours, a lesson about verifying a change belongs to whoever makes it. The user approves it first. To merge, shorten or remove lessons use alp_lesson_curate (the curate skill), never a file edit.']
@@ -266,7 +274,7 @@ export function nativeSessionConfig(
266
274
  description:
267
275
  'Complete brief: objective, scope, constraints, verification, handoff.',
268
276
  },
269
- model: { type: 'string', description: `Explicit runtime-prefixed model ID from the available catalog. Oracle: ${mapping.oracleModels.join(' or ')}.` },
277
+ model: { type: 'string', description: `Explicit runtime-prefixed model ID from the available catalog.${targets.includes('oracle') ? ` Oracle: ${mapping.oracleModels.join(' or ')}.` : ''}` },
270
278
  thinking: { type: 'string', description: 'Effort supported by the selected model.' },
271
279
  modelReason: { type: 'string', description: 'Why this model suits the task.' },
272
280
  mode: {
@@ -292,7 +300,7 @@ export function nativeSessionConfig(
292
300
  ...(targets.length ? [WAIT_TOOL, CANCEL_TOOL, MERGE_TOOL, DISCARD_TOOL, RESOLVE_TOOL, VERIFY_TOOL, RECALL_TOOL] : []),
293
301
  ...(targets.length || parentAgent ? [SEND_TOOL] : []),
294
302
  ...(parentAgent ? [HANDOFF_TOOL] : []),
295
- ...(supervised ? [LESSON_TOOL, LESSON_CURATE_TOOL, SKILL_TOOL] : []),
303
+ ...(supervised ? [LESSON_TOOL, LESSON_CURATE_TOOL, SKILL_TOOL, SKILL_RETIRE_TOOL] : []),
296
304
  ...(!parentAgent && mapping.agent.name === mainOf(mapping) ? [ISSUE_TOOL, SCHEDULE_TOOL] : []),
297
305
  ASK_TOOL,
298
306
  PIN_TOOL,
@@ -88,6 +88,8 @@ export type Session = {
88
88
  brief?: string;
89
89
  /** The skills it has used, each logged once (ALPD §59). */
90
90
  skillsUsed?: Set<string>;
91
+ /** Skill files beyond SKILL.md the session has read or run, as `<read|run>:<skill>/<relative path>` (skill-resource events). */
92
+ skillResourcesUsed?: Set<string>;
91
93
  /** Why the running turn is being stopped, so its end parks the assignment instead of ending it. */
92
94
  parkReason?: string;
93
95
  parkPause?: ParkPause;