@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
@@ -11,20 +11,18 @@ import { inputLimitError, POUR_VARS, VAR_NAME, type InputLimits } from './input-
11
11
  import { claudeToolDetail, resultText } from './tool-detail.js';
12
12
  import { CLOSE_REASONS, GATE_KINDS, TASK_STATUSES, TASK_TYPES } from '@anhlp/alp-core/tasks';
13
13
  import { commandDecision } from '@anhlp/alp-core/permissions';
14
- import { packagedInfo } from '@anhlp/alp-core/packaged';
15
14
 
16
15
  // Keep the Claude SDK behind the runtime boundary. Paseo inspects static
17
16
  // imports while compiling plugin entrypoints, including their declaration
18
17
  // graph; the SDK is a daemon-only optional runtime dependency.
19
18
  const CLAUDE_SDK = ['@anthropic-ai', 'claude-agent-sdk'].join('/');
20
- // The ALP executable has no node_modules to resolve CLAUDE_SDK from: its entry embeds the SDK and
21
- // registers the import under the package name (scripts/build-binary.mjs).
22
- const claudeSdk = (): Promise<any> => packagedInfo()?.modules?.[CLAUDE_SDK]?.() ?? import(CLAUDE_SDK);
19
+ const claudeSdk = (): Promise<any> => import(CLAUDE_SDK);
23
20
 
24
21
  type SDKUserMessage = any;
25
22
  type SDKMessage = any;
26
23
  type ClaudeQuery = AsyncGenerator<SDKMessage, void> & {
27
24
  supportedModels(): Promise<Array<{ value: string; displayName: string; description: string; supportedEffortLevels?: string[] }>>;
25
+ supportedCommands(): Promise<Array<{ name: string; description: string; argumentHint?: string; builtin?: boolean }>>;
28
26
  usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(options: { skipBehaviors: boolean }): Promise<any>;
29
27
  getContextUsage(options: { detail: 'summary' | 'full' }): Promise<any>;
30
28
  interrupt(): Promise<unknown>;
@@ -33,7 +31,17 @@ type ClaudeQuery = AsyncGenerator<SDKMessage, void> & {
33
31
  initializationResult?(): Promise<unknown>;
34
32
  };
35
33
 
36
- /** A field whose size is checked before zod walks it; its JSON Schema is the inner schema's (input-limits.ts). */
34
+ /**
35
+ * A field whose size is checked before zod walks it; its JSON Schema is the inner schema's
36
+ * (input-limits.ts).
37
+ *
38
+ * Needed for any field zod's own cap does not protect. zod's GHSA-mrhx-c7xc-m3w5 fix (4.6.6) refuses
39
+ * a collection over its `.max()` before reading an element for `array`, `map` and `set` — and for
40
+ * NOTHING ELSE. `z.record` is NOT covered: a capped record is still read element by element, one
41
+ * issue kept per failure (t-5294.4). So a limited record must go through `bounded` (as `vars` below
42
+ * does), and turning a capped `z.array` field into a `z.record` silently drops that protection.
43
+ * docs/alp/zod-advisory.md has the repository-wide survey.
44
+ */
37
45
  const bounded = <T extends z.ZodType>(schema: T, limits: InputLimits) => z.preprocess((value, ctx) => {
38
46
  const error = inputLimitError(value, limits);
39
47
  if (error) ctx.addIssue({ code: 'custom', message: error });
@@ -93,6 +101,11 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
93
101
  replace: z.boolean().optional(),
94
102
  requestId: z.string().min(1).max(100).optional(),
95
103
  },
104
+ alp_skill_retire: {
105
+ name: z.string().min(1).max(64),
106
+ reason: z.string().min(1).max(300),
107
+ requestId: z.string().min(1).max(100).optional(),
108
+ },
96
109
  alp_issue: {
97
110
  action: z.enum(['search', 'create', 'comment']),
98
111
  target: z.enum(['project', 'alp']),
@@ -225,6 +238,47 @@ type NativeConfig = {
225
238
 
226
239
  /** The plugin name ALP's skills are loaded under, so Claude Code calls them alp:<name>. */
227
240
  export const SKILL_PLUGIN = 'alp';
241
+ /** Claude's /clear and its aliases (supportedCommands reports `clear [reset, new]`): each starts a new conversation. */
242
+ const NEW_CONVERSATION_COMMANDS = ['clear', 'reset', 'new'];
243
+ const NEW_CONVERSATION = new RegExp(`^\\s*\\/(${NEW_CONVERSATION_COMMANDS.join('|')})(?:\\s|$)`);
244
+ /** Claude's own commands the composer does not offer: ALP does their work its own way (t-efa3). */
245
+ const ALP_HANDLED_COMMANDS = new Set([...NEW_CONVERSATION_COMMANDS, 'compact', 'rewind']);
246
+ /** The aliases of /clear a command of the user's may take as its own name. */
247
+ const CLEAR_ALIASES = new Set(['reset', 'new']);
248
+
249
+ type ListedCommand = { name?: unknown; builtin?: unknown };
250
+ /**
251
+ * t-5ac5: the aliases of /clear (new, reset) that, in this listing, run a command of the user's,
252
+ * project, plugin or MCP server rather than Claude's /clear. The SDK marks Claude's own rows
253
+ * `builtin: true`; a marked row wins its name, and an alias runs a command that has it as its name
254
+ * (SlashCommand.builtin). So /new is the user's when an unmarked row is named new and no marked row is.
255
+ * A listing without the marker (an older Claude Code) cannot tell the two apart: nothing is the
256
+ * user's then, and ALP keeps refusing /new and /reset, since letting Claude's /clear through loses the
257
+ * conversation while refusing a custom command only costs the user its name. /clear itself is always
258
+ * Claude's: a marked row is named clear.
259
+ */
260
+ export function customClearAliases(listed: ReadonlyArray<ListedCommand> | undefined): Set<string> {
261
+ const rows = Array.isArray(listed) ? listed : [];
262
+ if (!rows.some(row => typeof row?.builtin === 'boolean')) return new Set();
263
+ const builtin = new Set(rows.filter(row => row?.builtin === true).map(row => row.name));
264
+ return new Set(rows.filter(row => row?.builtin !== true && typeof row?.name === 'string' && CLEAR_ALIASES.has(row.name) && !builtin.has(row.name)).map(row => row.name as string));
265
+ }
266
+
267
+ /**
268
+ * t-e906: Claude's /clear moves it to a new conversation under a new session id while ALP keeps the
269
+ * old thread, so resume, fork and rewind would point at the conversation from before. ALP refuses it
270
+ * rather than follow: its timeline, turn ids and rewinds belong to the old conversation. /reset and /new are
271
+ * the same command, unless the session lists a command of the user's under that name (`custom`,
272
+ * from customClearAliases).
273
+ */
274
+ export function nativeCommandRefusal(runtimeKind: string, content: ReadonlyArray<{ type: string; text?: string }>, custom?: ReadonlySet<string>) {
275
+ if (runtimeKind !== 'claude') return undefined;
276
+ // The text Claude gets: every text part, joined as startPrompt joins them.
277
+ const typed = content.filter(part => part.type === 'text').map(part => part.text ?? '').join('\n');
278
+ const named = NEW_CONVERSATION.exec(typed)?.[1];
279
+ if (!named || custom?.has(named)) return undefined;
280
+ return 'ALP does not pass /clear (or /new, /reset) to Claude: Claude would start a new conversation that this session does not follow. Start a new session in ALP for a fresh conversation, or compact this one (alp compact, or Compact in the app).';
281
+ }
228
282
 
229
283
  /**
230
284
  * A Claude Code plugin in `directory` holding the given skills, linked to their own
@@ -463,6 +517,30 @@ export class ClaudeTransport {
463
517
  models: (catalog ?? []).map(model => ({ id: `claude:${model.value}`, label: model.displayName,
464
518
  description: model.description, thinking: model.supportedEffortLevels })), usage: claudeUsage(usage) };
465
519
  }
520
+ /**
521
+ * Claude's slash commands, skills included, for the composer (t-f628); none before the session starts.
522
+ * Not the ones whose work ALP does itself (t-efa3): /clear (/reset, /new) moves Claude to a new conversation ALP does not
523
+ * follow, and /compact and /rewind skip ALP's checkpoint and its rewind of the timeline. A command of the user's
524
+ * named new or reset is offered (t-5ac5, customClearAliases); one named clear, compact or rewind never runs, Claude's wins.
525
+ */
526
+ async commands() {
527
+ const listed = await this.listCommands();
528
+ const custom = customClearAliases(listed);
529
+ return (Array.isArray(listed) ? listed : []).filter(command => typeof command?.name === 'string' && command.name
530
+ && (!ALP_HANDLED_COMMANDS.has(command.name) || (command.builtin !== true && custom.has(command.name)))).map(command => ({
531
+ name: command.name, description: typeof command.description === 'string' ? command.description : '',
532
+ ...(command.argumentHint ? { argumentHint: command.argumentHint } : {}),
533
+ kind: command.name.startsWith(`${SKILL_PLUGIN}:`) ? 'skill' as const : 'command' as const,
534
+ }));
535
+ }
536
+ /** The aliases of /clear that run a command of the user's, as the last listing said (t-5ac5); none before one. */
537
+ customCommands(): ReadonlySet<string> { return this.customAliases; }
538
+ private customAliases: ReadonlySet<string> = new Set();
539
+ private async listCommands() {
540
+ const listed = this.query ? await optionalRead(async () => this.query!.supportedCommands(), 10_000) : undefined;
541
+ if (Array.isArray(listed)) this.customAliases = customClearAliases(listed);
542
+ return listed;
543
+ }
466
544
  async initialize() {}
467
545
 
468
546
  /** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
@@ -741,6 +819,8 @@ export class ClaudeTransport {
741
819
  this.query = query({ prompt: this.input, options }) as ClaudeQuery;
742
820
  this.pump = this.consume(this.query).catch((error) => this.fail(error));
743
821
  void this.measureContext();
822
+ // The listing says which of /new and /reset are the user's own, before the first prompt is checked.
823
+ void this.listCommands();
744
824
  }
745
825
 
746
826
  /** Reads the window and the compaction threshold Claude resolved for this session, before any turn. */
package/src/contracts.ts CHANGED
@@ -9,10 +9,17 @@ import type { AntigravityProvider } from './antigravity-transport.js';
9
9
  import type { GitHubRunner } from './github.js';
10
10
  import type { AttachmentReader } from './attachments.js';
11
11
 
12
+ /** A slash command or skill an agent's composer offers after "/" (t-f628). */
13
+ export type RuntimeCommand = { name: string; description: string; argumentHint?: string; kind: 'command' | 'skill' };
14
+
12
15
  export type RuntimeTransport = {
13
16
  request(method: string, params: any): Promise<any>;
14
17
  initialize(): Promise<void>;
15
18
  orchestrationContext?: () => Promise<unknown>;
19
+ /** The runtime's own slash commands and skills for the composer (t-f628); omitted, the runtime offers none. */
20
+ commands?: () => Promise<RuntimeCommand[]>;
21
+ /** Claude: the aliases of /clear (new, reset) that run a command of the user's, so they are not refused (t-5ac5). */
22
+ customCommands?: () => ReadonlySet<string>;
16
23
  onNotification(listener: (method: string, params: any) => void): void;
17
24
  onFailure(listener: (error: unknown) => void): void;
18
25
  close(): Promise<void>;
@@ -104,6 +111,14 @@ export type RuntimeOptions = {
104
111
  /** Where running assignments are kept, so the next alpd continues them (ALPD §31). Omitted keeps them in memory. */
105
112
  liveFile?: string;
106
113
 
114
+ /**
115
+ * Told of every failed write to pauseFile, liveFile, recallFile and assignmentResultFile, as it
116
+ * happens, so the host's disk guard pauses work on a full disk at once (t-e80a). Each write still
117
+ * fails as before: pauses and recall go on in memory, live entries are logged, and result
118
+ * ownership is refused to its caller.
119
+ */
120
+ onWriteError?: (error: unknown) => void;
121
+
107
122
  /** False parks assignments an earlier alpd left running until the user runs alp resume. Default true: they continue. */
108
123
  recoveryResume?: boolean;
109
124
 
@@ -129,6 +144,8 @@ export type AlpRuntime = {
129
144
  bindAttachments?: (reader: AttachmentReader | undefined) => void;
130
145
  /** Whether this live session's runtime takes `{ type: 'attachment' }` parts (RuntimeAttachment) now. */
131
146
  takesAttachments?: (sessionId: string) => boolean;
147
+ /** Why this live session's runtime refuses this prompt before it is sent (t-e906), or undefined. */
148
+ refusesPrompt?: (sessionId: string, content: PromptContent) => string | undefined;
132
149
  /** Removes the staged copy of an attachment alpd no longer keeps. */
133
150
  dropAttachment?: (attachmentId: string) => Promise<void>;
134
151
  onEvent(listener: (envelope: Envelope) => void): () => void;
@@ -238,6 +255,8 @@ export type AlpRuntime = {
238
255
  reload?(sessionId: string): Promise<SessionSnapshot>;
239
256
  /** Compacts a root's context at its next turn boundary, with a checkpoint main writes by skill compact (t-0e56). */
240
257
  compact?(sessionId: string): { status: 'started' | 'deferred' | 'running' };
258
+ /** The slash commands and skills a live session's composer offers (t-f628): its runtime's, then its ALP skills. */
259
+ commands?(sessionId: string): Promise<RuntimeCommand[]>;
241
260
  /**
242
261
  * Holds the turns the runtime would start by itself on this session (mail wakes) while a lifecycle
243
262
  * operation changes its conversation (a rewind, later a reload or live configure): mail stays queued
package/src/index.ts CHANGED
@@ -2,14 +2,15 @@
2
2
  export { createAlpRuntime, DEFAULT_TEAM, WorkspaceMutationError } from './runtime.js';
3
3
  export type { WorkspaceMutationReason, AlpRuntime, RuntimeOptions, OpenOptions, RuntimeTransport, PromptInput, PromptContent, SessionPreview } from './runtime.js';
4
4
  export { ConversationError } from './contracts.js';
5
- export type { BranchRequest, ConversationErrorReason, NativeBase, NativeBinding, ConfigureChanges, ConfigureResult, ConfigurePreview, EffectiveConfig } from './contracts.js';
5
+ export type { RuntimeCommand, BranchRequest, ConversationErrorReason, NativeBase, NativeBinding, ConfigureChanges, ConfigureResult, ConfigurePreview, EffectiveConfig } from './contracts.js';
6
6
  export type { AlpEvent, AlpError, Envelope, SessionSnapshot, TimelineItem, TurnOrigin, AssignmentSnapshot, UserQuestion, TreeStatus, SessionState } from './events.js';
7
7
  export { resolveSession, InstructionsAdapter, skillDescription } from './resolve.js';
8
+ export { resourceUses, pathActions } from './skill-resources.js';
8
9
  export type { SessionSpec, HostMcpServer, ResolvedSession, RuntimeKind } from './resolve.js';
9
10
  export { DEFAULT_MODEL, DEFAULT_CLAUDE_MODEL, entries as catalogEntries, models, modes, thinkingOptions, thinkingOptionsFor } from './catalog.js';
10
11
  export type { CatalogEntry } from './catalog.js';
11
- export { ModelCatalog, mergeCatalog, liveFromContext, feedCatalog, setActiveCatalog, activeCatalog, POLICY as CATALOG_POLICY, REFRESH_MS as CATALOG_REFRESH_MS } from './model-catalog.js';
12
- export type { CatalogSnapshot, CatalogRuntime, LiveModel, Probe as CatalogProbe } from './model-catalog.js';
12
+ export { ModelCatalog, mergeCatalog, liveFromContext, feedCatalog, feedAcpSession, acpSessionModels, setActiveCatalog, activeCatalog, POLICY as CATALOG_POLICY, REFRESH_MS as CATALOG_REFRESH_MS } from './model-catalog.js';
13
+ export type { CatalogSnapshot, CatalogRuntime, LiveModel, Probe as CatalogProbe, AcpProviderConfig, AcpProbe, AcpRow, AcpState } from './model-catalog.js';
13
14
  export { liveProbes, codexProbe, claudeProbe, antigravityProbe, parseAgyModels } from './model-probes.js';
14
15
  export { CodexTransport } from './transport.js';
15
16
  export { ATTACHMENT_HEADER, ATTACHMENT_ROUTES, attachmentStageDir, createAttachmentStager, stagingExposure } from './attachments.js';
@@ -19,7 +20,7 @@ export { AcpTransport, acpDecision, acpEnv, acpPermission } from './acp-transpor
19
20
  export type { AcpProvider } from './acp-transport.js';
20
21
  export { AntigravityTransport } from './antigravity-transport.js';
21
22
  export type { AntigravityProvider } from './antigravity-transport.js';
22
- export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, skillPlugin, SKILL_PLUGIN, toolShapes as claudeToolShapes } from './claude-transport.js';
23
+ export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, customClearAliases, nativeCommandRefusal, skillPlugin, SKILL_PLUGIN, toolShapes as claudeToolShapes } from './claude-transport.js';
23
24
  export { MAIL_BATCH_CHARS, MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from './mailbox.js';
24
25
  export type { MailEvent, MailKind } from './mailbox.js';
25
26
  export { createCopy, gitEnvironment, reattachWorktree, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
package/src/language.ts CHANGED
@@ -18,6 +18,10 @@ const en = {
18
18
  `${agent} wants to ${create ? `open an issue in ${where}` : `comment on issue #${issue} in ${where}`}. ` +
19
19
  'It is posted with your GitHub account, and anyone who can see the repository can read it.',
20
20
  issueTitle: 'Title',
21
+ skillRetire: (agent: string, name: string, file: string, retired: string, roles: string, users: string, reason: string) =>
22
+ `${agent} proposes to retire the skill ${name} (${file}): ${reason}\n` +
23
+ `Approve to move it to ${retired}, where it is kept and can be restored, and remove it from ${roles ? `the roles that have it: ${roles}` : 'role-skills.json (no role has it)'}. Nothing else changes.` +
24
+ (users ? ` It is still named in agent.json by ${users}; it is not retired until they stop naming it.` : ''),
21
25
  lessonCurate: (agent: string, changes: string) =>
22
26
  `${agent} proposes to curate the lessons files. Approve to apply every change below at once; nothing else changes.\n\n${changes}`,
23
27
  lessonRemove: 'Remove',
@@ -38,6 +42,7 @@ const en = {
38
42
  limitReached: (runtime: string, resetsAt: string | undefined, other: string | undefined, autoResume: boolean, kind: string) =>
39
43
  `${runtime} usage limit reached${resetsAt ? `; it resets ${resetsAt}` : ''}. ALP paused delegation to ${runtime} agents and parked their assignments${other ? `; ${other} agents keep working` : ''}. ${autoResume ? `ALP asks ${runtime} every minute and resumes it as soon as the limit lifts.` : `ALP asks ${runtime} every minute and tells you when the limit lifts; then run alp resume ${kind}.`}`,
40
44
  limitLifted: (runtime: string, kind: string) => `${runtime} says its usage limit has lifted. Run alp resume ${kind} to continue its work.`,
45
+ compacting: () => 'Compacting main\'s context: main writes a checkpoint first.',
41
46
  compacted: (native: boolean) => `Main's context was compacted${native ? '' : ' into a fresh conversation'}; it keeps its checkpoint and carries on.`,
42
47
  compactFailed: (reason: string) => `Compacting main's context failed (${reason}); ALP tries again later.`,
43
48
  usageWarning: (runtime: string, used: string, resetsAt: string | undefined) => `${runtime} has used ${used} of a usage window${resetsAt ? ` that resets ${resetsAt}` : ''}.`,
@@ -67,6 +72,10 @@ const vi: Words = {
67
72
  `${agent} muốn ${create ? `mở một issue trong ${where}` : `bình luận vào issue #${issue} trong ${where}`}. ` +
68
73
  'Nội dung được đăng bằng tài khoản GitHub của bạn, ai xem được repository đều đọc được.',
69
74
  issueTitle: 'Tiêu đề',
75
+ skillRetire: (agent, name, file, retired, roles, users, reason) =>
76
+ `${agent} đề xuất cho skill ${name} (${file}) nghỉ: ${reason}\n` +
77
+ `Duyệt để chuyển nó sang ${retired}, nơi nó vẫn được giữ và có thể khôi phục, và bỏ nó khỏi ${roles ? `các vai đang dùng: ${roles}` : 'role-skills.json (không vai nào dùng)'}. Không thay đổi gì khác.` +
78
+ (users ? ` Nó vẫn được nêu trong agent.json của ${users}; nó chỉ được cho nghỉ khi các agent đó thôi nêu nó.` : ''),
70
79
  lessonCurate: (agent, changes) =>
71
80
  `${agent} đề xuất rà soát file bài học. Duyệt để áp dụng cùng lúc mọi thay đổi dưới đây; không thay đổi gì khác.\n\n${changes}`,
72
81
  lessonRemove: 'Bỏ',
@@ -87,6 +96,7 @@ const vi: Words = {
87
96
  limitReached: (runtime, resetsAt, other, autoResume, kind) =>
88
97
  `${runtime} đã hết hạn mức sử dụng${resetsAt ? `; hạn mức đặt lại lúc ${resetsAt}` : ''}. ALP tạm dừng giao việc cho các agent ${runtime} và tạm giữ việc của chúng${other ? `; các agent ${other} vẫn làm tiếp` : ''}. ${autoResume ? `ALP hỏi ${runtime} mỗi phút và tự chạy lại ngay khi có hạn mức.` : `ALP hỏi ${runtime} mỗi phút và báo khi có hạn mức trở lại; khi đó chạy alp resume ${kind}.`}`,
89
98
  limitLifted: (runtime, kind) => `${runtime} báo đã có hạn mức trở lại. Chạy alp resume ${kind} để làm tiếp việc của nó.`,
99
+ compacting: () => 'Đang compact context của main: main viết checkpoint trước.',
90
100
  compacted: native => `Context của main đã được compact${native ? '' : ' sang một cuộc hội thoại mới'}; main giữ checkpoint và làm tiếp.`,
91
101
  compactFailed: reason => `Compact context của main thất bại (${reason}); ALP sẽ thử lại sau.`,
92
102
  usageWarning: (runtime, used, resetsAt) => `${runtime} đã dùng ${used} hạn mức của kỳ này${resetsAt ? `, kỳ đặt lại lúc ${resetsAt}` : ''}.`,
package/src/live.ts CHANGED
@@ -5,6 +5,7 @@ import path from 'node:path';
5
5
  import { createLogger } from '@anhlp/alp-core/log';
6
6
  import type { RuntimeKind, SessionSpec } from './resolve.js';
7
7
  import type { Worktree } from './workspace.js';
8
+ import { tell } from './write-error.js';
8
9
 
9
10
  /**
10
11
  * Assignments that are running, kept on disk so the next alpd can continue them
@@ -49,8 +50,8 @@ const valid = (entry: any): entry is LiveEntry => !!entry && typeof entry === 'o
49
50
  ['assignmentId', 'rootId', 'parentId', 'agent', 'project', 'runtime', 'model', 'threadId', 'mode', 'isolation', 'epoch'].every(key => typeof entry[key] === 'string') &&
50
51
  Array.isArray(entry.ancestry) && !!entry.spec && typeof entry.spec === 'object' && typeof entry.startedAt === 'number';
51
52
 
52
- /** The book of running assignments, in `file` when given, else in memory. */
53
- export function createLiveBook(file?: string) {
53
+ /** The book of running assignments, in `file` when given, else in memory; `onError` hears of each failed write. */
54
+ export function createLiveBook(file?: string, onError: (error: unknown) => void = () => {}) {
54
55
  let entries: LiveEntry[] = [];
55
56
  if (file) {
56
57
  try { entries = (JSON.parse(readFileSync(file, 'utf8')) as unknown[]).filter(valid); } catch {}
@@ -64,7 +65,10 @@ export function createLiveBook(file?: string) {
64
65
  const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
65
66
  await writeFile(temporary, body, { mode: 0o600 });
66
67
  await rename(temporary, file);
67
- }).catch(error => createLogger({ component: 'runtime' }).error('could not save the live assignments', { code: 'ALP_PERSISTENCE_WRITE_FAILED', operation: 'live assignments', error }));
68
+ }).catch(error => {
69
+ tell(onError, error);
70
+ createLogger({ component: 'runtime' }).error('could not save the live assignments', { code: 'ALP_PERSISTENCE_WRITE_FAILED', operation: 'live assignments', error });
71
+ });
68
72
  return writes;
69
73
  };
70
74
  return {
@@ -13,8 +13,18 @@ export type CatalogRuntime = 'codex' | 'claude' | 'antigravity';
13
13
  /** A model as a provider reports it. */
14
14
  export type LiveModel = { id: string; label?: string; description?: string; efforts?: string[]; effort?: string };
15
15
  export type ProviderState = { status: 'ok' | 'failed' | 'static'; fetchedAt?: string; error?: string; models: LiveModel[] };
16
- export type CatalogSnapshot = { fetchedAt?: string; providers: Partial<Record<CatalogRuntime, ProviderState>> };
16
+ /** What ALP learned of an ACP provider's models (t-d0b0): nothing until a session or an explicit probe tells it. */
17
+ export type AcpStatus = 'unprobed' | 'ok' | 'failed';
18
+ export type AcpState = { status: AcpStatus; fetchedAt?: string; error?: string; models: LiveModel[] };
19
+ export type CatalogSnapshot = { fetchedAt?: string; providers: Partial<Record<CatalogRuntime, ProviderState>>; acp?: Record<string, AcpState> };
17
20
  export type Probe = (signal: AbortSignal) => Promise<LiveModel[]>;
21
+ /** A provider of the library (providers/<id>.json), as loadProvider reads it. */
22
+ export type AcpProviderConfig = { id: string; kind?: string; label?: string; description?: string; enabled?: boolean;
23
+ models?: Array<{ id: string; label?: string; description?: string }>; additionalModels?: Array<{ id: string; label?: string; description?: string }> };
24
+ export type AcpProbe = (provider: AcpProviderConfig, signal: AbortSignal) => Promise<LiveModel[]>;
25
+ /** An ACP row of the catalog: `acp:<provider>` (the agent's own default) and `acp:<provider>/<model>`. */
26
+ export type AcpRow = { runtime: 'acp'; provider: string; id: string; label: string; description: string; efforts: string[];
27
+ source: 'configured' | 'live'; enabled: boolean; status: AcpStatus };
18
28
 
19
29
  const RUNTIMES: CatalogRuntime[] = ['codex', 'claude', 'antigravity'];
20
30
  export const REFRESH_MS = 6 * 60 * 60 * 1000;
@@ -54,7 +64,20 @@ function sanitize(value: any): CatalogSnapshot {
54
64
  if (!state || typeof state !== 'object') continue;
55
65
  providers[runtime] = { status: state.status === 'ok' ? 'ok' : 'failed', ...(typeof state.fetchedAt === 'string' ? { fetchedAt: state.fetchedAt } : {}), models: sanitizeModels(state.models) };
56
66
  }
57
- return { ...(typeof value?.fetchedAt === 'string' ? { fetchedAt: value.fetchedAt } : {}), providers };
67
+ const acp: Record<string, AcpState> = {};
68
+ if (value?.acp && typeof value.acp === 'object') for (const [id, state] of Object.entries<any>(value.acp)) {
69
+ if (!/^[\w.-]+$/.test(id) || !state || typeof state !== 'object') continue;
70
+ acp[id] = { status: state.status === 'ok' ? 'ok' : state.status === 'failed' ? 'failed' : 'unprobed', ...(typeof state.fetchedAt === 'string' ? { fetchedAt: state.fetchedAt } : {}), ...(typeof state.error === 'string' ? { error: state.error } : {}), models: sanitizeModels(state.models) };
71
+ }
72
+ return { ...(typeof value?.fetchedAt === 'string' ? { fetchedAt: value.fetchedAt } : {}), providers, ...(Object.keys(acp).length ? { acp } : {}) };
73
+ }
74
+
75
+ /** The models a `session/new` answer offers (ACP `models.availableModels`, or a model select config option). */
76
+ export function acpSessionModels(result: any): LiveModel[] {
77
+ const config = Array.isArray(result?.configOptions) ? result.configOptions.find((option: any) => option?.category === 'model' && option?.type === 'select') : undefined;
78
+ const listed = Array.isArray(result?.models?.availableModels) ? result.models.availableModels
79
+ : config ? (config.options ?? []).flatMap((option: any) => option?.options ?? [option]).map((option: any) => ({ modelId: option?.value, name: option?.name, description: option?.description })) : [];
80
+ return sanitizeModels(listed.map((model: any) => ({ id: model?.modelId ?? model?.id, ...(typeof model?.name === 'string' && model.name ? { label: model.name } : {}), ...(typeof model?.description === 'string' && model.description ? { description: model.description } : {}) })));
58
81
  }
59
82
 
60
83
  type Listener = (snapshot: CatalogSnapshot, entries: CatalogEntry[]) => void;
@@ -66,8 +89,22 @@ export class ModelCatalog {
66
89
  private timer?: NodeJS.Timeout;
67
90
  private running?: Promise<CatalogSnapshot>;
68
91
  private readonly file?: string;
92
+ private acpConfigs: AcpProviderConfig[] = [];
93
+ private acpRunning?: Promise<CatalogSnapshot>;
94
+ private acpError?: string;
95
+ private acpLearning = new Map<string, Set<string>>();
96
+ /** Cache writes under way: stop() waits for them, so whoever stopped the catalog may remove its home. */
97
+ private writes = new Set<Promise<void>>();
98
+ /** Set once stop() has drained: a late answer (a session's models, an ingest) still updates memory but writes nothing. */
99
+ private stopped = false;
69
100
 
70
- constructor(private readonly options: { home?: string; probes: Partial<Record<CatalogRuntime, Probe>>; timeoutMs?: number; refreshMs?: number; now?: () => Date; apply?: boolean }) {
101
+ /**
102
+ * ACP providers (t-d0b0) come from `acpProviders` (the library's providers/<id>.json) without starting
103
+ * them; their models are learned from sessions (learnAcp) and probed (acpProbe) only by refreshAcp,
104
+ * which alpd calls on catalog.refresh and when the user enables a provider. Never at start or on the timer.
105
+ */
106
+ constructor(private readonly options: { home?: string; probes: Partial<Record<CatalogRuntime, Probe>>; timeoutMs?: number; refreshMs?: number; now?: () => Date; apply?: boolean;
107
+ acpProviders?: () => Promise<AcpProviderConfig[] | { providers: AcpProviderConfig[]; error?: string }>; acpProbe?: AcpProbe }) {
71
108
  this.file = options.home ? catalogCacheFile(options.home) : undefined;
72
109
  }
73
110
 
@@ -77,12 +114,27 @@ export class ModelCatalog {
77
114
 
78
115
  /** Loads the cache, then refreshes in the background and every refreshMs. Never blocks on a provider. */
79
116
  async start() {
117
+ this.stopped = false;
80
118
  await this.load();
119
+ await this.loadAcp().catch(() => {});
81
120
  void this.refresh().catch(() => {});
82
121
  const every = this.options.refreshMs ?? REFRESH_MS;
83
122
  if (every > 0) { this.timer = setInterval(() => { void this.refresh().catch(() => {}); }, every); this.timer.unref?.(); }
84
123
  }
85
- stop() { if (this.timer) clearInterval(this.timer); this.timer = undefined; this.listeners.clear(); }
124
+ /**
125
+ * Stops the timer and the listeners, then waits for what already started (a background refresh, a
126
+ * refreshAcp a saved provider asked for, a learned model's cache write) to finish writing the cache
127
+ * (t-5294.2). After that it writes the cache no more, until start() again. A caller that only stops may
128
+ * ignore the promise; one that removes the home awaits it.
129
+ */
130
+ async stop() {
131
+ if (this.timer) clearInterval(this.timer);
132
+ this.timer = undefined;
133
+ this.listeners.clear();
134
+ // A refreshAcp queued behind a running one starts when it ends: wait until nothing runs.
135
+ while (this.running || this.acpRunning || this.writes.size) await Promise.allSettled([this.running, this.acpRunning, ...this.writes]);
136
+ this.stopped = true;
137
+ }
86
138
 
87
139
  async load() {
88
140
  if (!this.file) return;
@@ -131,13 +183,106 @@ export class ModelCatalog {
131
183
  return true;
132
184
  }
133
185
 
186
+ /** Rereads the ACP providers' files; starts none of them. */
187
+ async loadAcp() {
188
+ if (!this.options.acpProviders) return;
189
+ // A listing that fails (an unreadable providers directory) keeps the rows ALP had and records why.
190
+ try {
191
+ const loaded = await this.options.acpProviders();
192
+ this.acpConfigs = (Array.isArray(loaded) ? loaded : loaded.providers).filter(provider => provider.kind !== 'antigravity');
193
+ this.acpError = Array.isArray(loaded) ? undefined : loaded.error;
194
+ } catch (error) { this.acpError = error instanceof Error ? error.message : String(error); }
195
+ }
196
+ /** Why the last reading of the ACP providers failed, if it did. */
197
+ acpLoadError(): string | undefined { return this.acpError; }
198
+
199
+ /** The ACP rows: each provider's default, then its models (the file's `models` replace learned ones; `additionalModels` add). */
200
+ acpRows(): AcpRow[] {
201
+ const rows: AcpRow[] = [];
202
+ for (const provider of this.acpConfigs) {
203
+ const state = this.snapshot.acp?.[provider.id];
204
+ const status = state?.status ?? 'unprobed';
205
+ const enabled = provider.enabled !== false;
206
+ const label = provider.label ?? provider.id;
207
+ const row = (id: string, text: string, description: string, source: AcpRow['source']): AcpRow => ({ runtime: 'acp', provider: provider.id, id, label: text, description, efforts: [], source, enabled, status });
208
+ rows.push(row(provider.id, `${label} · agent default`, provider.description ?? '', 'configured'));
209
+ const seen = new Set<string>();
210
+ const add = (models: Array<{ id: string; label?: string; description?: string }>, source: AcpRow['source']) => {
211
+ for (const model of models) if (!seen.has(model.id)) { seen.add(model.id); rows.push(row(`${provider.id}/${model.id}`, `${label} · ${model.label ?? model.id}`, model.description ?? '', source)); }
212
+ };
213
+ add(provider.models ?? state?.models ?? [], provider.models ? 'configured' : 'live');
214
+ add(provider.additionalModels ?? [], 'configured');
215
+ }
216
+ return rows;
217
+ }
218
+ /** The models ALP learned or probed for one ACP provider. */
219
+ acpModels(provider: string): LiveModel[] { return this.snapshot.acp?.[provider]?.models ?? []; }
220
+
221
+ /**
222
+ * A list an ACP session's `session/new` reported (t-d0b0). Additive, as ingest: it never removes a model
223
+ * a probe answered; a list with nothing new changes nothing.
224
+ */
225
+ async learnAcp(provider: string, models: LiveModel[]) {
226
+ if (!/^[\w.-]+$/.test(provider)) return false;
227
+ const reported = sanitizeModels(models);
228
+ for (const model of reported) this.acpLearning.get(provider)?.add(model.id);
229
+ const prior = this.snapshot.acp?.[provider];
230
+ const known = new Set((prior?.models ?? []).map(model => model.id));
231
+ const added = reported.filter(model => !known.has(model.id));
232
+ if (!added.length) return false;
233
+ this.snapshot.acp = { ...this.snapshot.acp, [provider]: { status: 'ok', fetchedAt: (this.options.now?.() ?? new Date()).toISOString(), models: [...(prior?.models ?? []), ...added] } };
234
+ await this.publish(true);
235
+ return true;
236
+ }
237
+
238
+ /**
239
+ * Starts each enabled ACP provider (or the named ones) once to read its models: only on an explicit
240
+ * catalog.refresh or when the user enables a provider. A failure keeps what ALP knew and records why.
241
+ */
242
+ refreshAcp(ids?: string[]): Promise<CatalogSnapshot> {
243
+ if (this.acpRunning) return this.acpRunning.then(() => this.refreshAcp(ids));
244
+ this.acpRunning = (async () => {
245
+ await this.loadAcp();
246
+ const probe = this.options.acpProbe;
247
+ const targets = this.acpConfigs.filter(provider => provider.enabled !== false && (!ids || ids.includes(provider.id)));
248
+ if (!probe || !targets.length) return this.snapshot;
249
+ const now = () => (this.options.now?.() ?? new Date()).toISOString();
250
+ await Promise.all(targets.map(async provider => {
251
+ const learned = new Set<string>();
252
+ this.acpLearning.set(provider.id, learned);
253
+ let outcome: { ok: true; models: LiveModel[] } | { ok: false; error: string };
254
+ try { outcome = { ok: true, models: sanitizeModels(await bounded(signal => probe(provider, signal), this.options.timeoutMs ?? PROBE_TIMEOUT_MS)) }; }
255
+ catch (error) { outcome = { ok: false, error: error instanceof Error ? error.message : String(error) }; }
256
+ this.acpLearning.delete(provider.id);
257
+ // Read at write time: what a session's learnAcp reported during the probe stays.
258
+ const current = this.snapshot.acp?.[provider.id];
259
+ const known = current?.models ?? [];
260
+ let next: AcpState;
261
+ if (outcome.ok) {
262
+ const ids = new Set(outcome.models.map(model => model.id));
263
+ // A successful probe replaces old choices, retaining only learning concurrent with this probe.
264
+ next = { status: 'ok', fetchedAt: now(), models: [...outcome.models, ...known.filter(model => learned.has(model.id) && !ids.has(model.id))] };
265
+ } else next = { status: 'failed', ...(current?.fetchedAt ? { fetchedAt: current.fetchedAt } : {}), error: outcome.error, models: known };
266
+ this.snapshot.acp = { ...this.snapshot.acp, [provider.id]: next };
267
+ }));
268
+ await this.publish(true);
269
+ return this.snapshot;
270
+ })().finally(() => { this.acpRunning = undefined; });
271
+ return this.acpRunning;
272
+ }
273
+
134
274
  private async publish(save: boolean) {
135
275
  const next = mergeCatalog(staticRows(), Object.fromEntries(Object.entries(this.snapshot.providers).map(([runtime, state]) => [runtime, state?.models])));
136
276
  const changed = JSON.stringify(next) !== JSON.stringify(this.current);
137
277
  this.current = next;
138
278
  if (this.options.apply !== false) applyCatalog(next);
139
- if (save && this.file) {
140
- try { await mkdir(path.dirname(this.file), { recursive: true }); await writeAtomic(this.file, JSON.stringify(this.snapshot, null, 2)); } catch { /* the cache is best effort */ }
279
+ if (save && this.file && !this.stopped) {
280
+ const file = this.file;
281
+ const write = (async () => {
282
+ try { await mkdir(path.dirname(file), { recursive: true }); await writeAtomic(file, JSON.stringify(this.snapshot, null, 2)); } catch { /* the cache is best effort */ }
283
+ })();
284
+ this.writes.add(write);
285
+ try { await write; } finally { this.writes.delete(write); }
141
286
  }
142
287
  if (save) for (const listener of this.listeners) { try { listener(this.snapshot, next); } catch { /* a listener never stops the catalog */ } }
143
288
  return changed;
@@ -164,3 +309,8 @@ export function feedCatalog(context: unknown) {
164
309
  const live = liveFromContext(context);
165
310
  if (live && active) void active.ingest(live.runtime, live.models).catch(() => {});
166
311
  }
312
+ /** An ACP session's `session/new` answer teaches the daemon's catalog that provider's models (t-d0b0). */
313
+ export function feedAcpSession(provider: string, result: unknown) {
314
+ const models = acpSessionModels(result);
315
+ if (models.length && active) void active.learnAcp(provider, models).catch(() => {});
316
+ }
@@ -42,9 +42,9 @@ export function parseAgyModels(stdout: string): LiveModel[] {
42
42
  }).filter(model => model.id && /^[A-Za-z0-9][\w.:\-\[\]/]*$/.test(model.id));
43
43
  }
44
44
 
45
- export function antigravityProbe(command = process.env.ALP_ANTIGRAVITY_BIN ?? 'agy', env: NodeJS.ProcessEnv = process.env): Probe {
45
+ export function antigravityProbe(command = process.env.ALP_ANTIGRAVITY_BIN ?? 'agy', env: NodeJS.ProcessEnv = process.env, args: string[] = []): Probe {
46
46
  return signal => new Promise((resolve, reject) => {
47
- const child = spawn(command, ['models'], { cwd: os.tmpdir(), env, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, signal });
47
+ const child = spawn(command, [...args, 'models'], { cwd: os.tmpdir(), env, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, signal });
48
48
  let stdout = '';
49
49
  // A model list is small; more than this is not one.
50
50
  child.stdout.on('data', chunk => { stdout += chunk; if (stdout.length > 256 * 1024) child.kill('SIGKILL'); });
package/src/recall.ts CHANGED
@@ -2,6 +2,7 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
2
  import { randomBytes } from 'node:crypto';
3
3
  import path from 'node:path';
4
4
  import type { RuntimeKind } from './resolve.js';
5
+ import { tell } from './write-error.js';
5
6
 
6
7
  /**
7
8
  * Finished assignments whose native threads alp_recall can question (ALPD §27).
@@ -37,8 +38,8 @@ const valid = (entry: any): entry is RecallEntry => !!entry && typeof entry ===
37
38
  ['assignmentId', 'rootId', 'agent', 'project', 'runtime', 'threadId', 'cwd', 'model', 'status', 'finishedAt'].every(key => typeof entry[key] === 'string') &&
38
39
  Array.isArray(entry.requesters);
39
40
 
40
- /** The record of recallable threads, kept in `file` when given, else in memory. */
41
- export function createRecallBook(file?: string) {
41
+ /** The record of recallable threads, kept in `file` when given, else in memory; `onError` hears of each failed write. */
42
+ export function createRecallBook(file?: string, onError: (error: unknown) => void = () => {}) {
42
43
  let entries: Promise<RecallEntry[]> | undefined;
43
44
  let writes = Promise.resolve();
44
45
  const load = () => entries ??= file
@@ -52,7 +53,7 @@ export function createRecallBook(file?: string) {
52
53
  const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
53
54
  await writeFile(temporary, body, { mode: 0o600 });
54
55
  await rename(temporary, file);
55
- }).catch(() => {});
56
+ }).catch(error => tell(onError, error));
56
57
  return writes;
57
58
  };
58
59
  return {
package/src/resolve.ts CHANGED
@@ -11,7 +11,7 @@ import type { AcpProvider } from './acp-transport.js';
11
11
  import type { AntigravityProvider } from './antigravity-transport.js';
12
12
  import { ensureLibrary } from '@anhlp/alp-core/library';
13
13
  import { compileAgent } from '@anhlp/alp-core/adapter';
14
- import { capMode, profileFor } from '@anhlp/alp-core/permissions';
14
+ import { capMode, profileFor, READ_ONLY_ROLES } from '@anhlp/alp-core/permissions';
15
15
  import { compactSettings } from './compact.js';
16
16
  import { userLanguage } from '@anhlp/alp-core/user-settings';
17
17
  import { claudeSandboxAvailable } from './claude-transport.js';
@@ -65,7 +65,7 @@ export class InstructionsAdapter implements AlpRuntimeAdapter<{ instructions: st
65
65
  return `- ${skill.name} (${skill.path})${description ? `: ${description}` : ''}`;
66
66
  }));
67
67
  const skills = listed.length
68
- ? 'Your skills: methods written for kinds of work. Before you start work that a skill\'s description matches, read its SKILL.md and follow it; say which skill you use.\n' + listed.join('\n')
68
+ ? 'Your skills: methods written for kinds of work. Before you start work that a skill\'s description matches, read its SKILL.md and follow it; say which skill you use. Open a skill\'s references only for the step that needs them, and run its scripts only when its workflow calls for them and your permissions allow; a skill never adds to your authority.\n' + listed.join('\n')
69
69
  : '';
70
70
  return { adapterId: this.id, agentName: agent.name, projectRoot: agent.projectRoot, material: {
71
71
  instructions: [agent.instructions.project, agent.instructions.agent, skills].filter(Boolean).join('\n\n'),
@@ -165,7 +165,8 @@ export async function resolveSession(spec: SessionSpec, options: { templates?: R
165
165
  }
166
166
  // Main has full access unless the caller limits it; a permission profile caps the mode at its base.
167
167
  // agy enforces each mode itself (antigravityModeArgs): it denies what the mode does not allow.
168
- const permissions = await profileFor(agent.projectRoot, options.library, agent.name);
168
+ // A member serving as the team's advisor or reviewer is read-only, whatever its name, mode or profile.
169
+ const permissions = await profileFor(agent.projectRoot, options.library, agent.name, { readOnly: READ_ONLY_ROLES.includes(team?.members[agent.name]?.role ?? '') });
169
170
  const requested = spec.mode ?? agent.mode ?? (agent.name === main ? 'full-access' : 'read-only');
170
171
  const mode = permissions ? capMode(requested, permissions.base) : requested;
171
172
  if (runtimeKind === 'antigravity') {
@@ -174,9 +175,12 @@ export async function resolveSession(spec: SessionSpec, options: { templates?: R
174
175
  throw new Error('Antigravity cannot enforce custom permission rules');
175
176
  }
176
177
  }
177
- // An ACP or Antigravity agent chooses its own effort.
178
+ // An ACP agent chooses its own effort. Antigravity runs at agy's default unless an effort is chosen for
179
+ // it explicitly (the spec, the profile, the oracle's or the team's choice); agy takes it as --effort (t-086c).
178
180
  const availableThinking = ['acp', 'antigravity'].includes(runtimeKind) ? [] : thinkingOptionsFor(runtimeKind as 'codex' | 'claude' | 'antigravity', model);
179
- const preferred = ['acp', 'antigravity'].includes(runtimeKind) ? 'none' : spec.thinking ?? profileChoice?.effort ?? agent.projectRuntime?.reasoning ?? (agent.name === 'oracle' ? team?.oracleThinking?.[`${runtimeKind}:${model}`] ?? team?.oracleThinking?.[runtimeKind] : undefined) ?? teamChoice?.thinking ?? agent.runtime.reasoning ??
181
+ const preferred = runtimeKind === 'acp' ? 'none'
182
+ : runtimeKind === 'antigravity' ? spec.thinking ?? profileChoice?.effort ?? (agent.name === 'oracle' ? team?.oracleThinking?.[`${runtimeKind}:${model}`] ?? team?.oracleThinking?.[runtimeKind] : undefined) ?? teamChoice?.thinking ?? 'none'
183
+ : spec.thinking ?? profileChoice?.effort ?? agent.projectRuntime?.reasoning ?? (agent.name === 'oracle' ? team?.oracleThinking?.[`${runtimeKind}:${model}`] ?? team?.oracleThinking?.[runtimeKind] : undefined) ?? teamChoice?.thinking ?? agent.runtime.reasoning ??
180
184
  (agent.name === 'oracle' ? ORACLE_THINKING : availableThinking.length ? 'medium' : 'none');
181
185
  // A default the model does not take gives way to the model's own (GPT-6 Astra runs at low only); an explicit choice is checked below.
182
186
  const thinking = spec.thinking === undefined && availableThinking.length && !availableThinking.some(candidate => candidate.id === preferred)
@@ -223,6 +227,8 @@ export async function resolveSession(spec: SessionSpec, options: { templates?: R
223
227
  mcp, env: { ...spec.env }, persist: spec.persist ?? false, keepThread: spec.keepThread ?? false,
224
228
  // ALPD §57: the window the agent works in before its runtime compacts; absent, the model's.
225
229
  ...(agent.context ? { context: agent.context } : {}),
230
+ // t-efa3: the runtime's own commands and skills the "/" list offers; its ALP skills always.
231
+ commands: Array.isArray(profile?.commands) ? profile.commands.filter((name: unknown): name is string => typeof name === 'string') : [] as string[],
226
232
  autocompact: typeof profile?.autocompact === 'number' ? profile.autocompact as number : typeof agent.autocompact === 'number' ? agent.autocompact : undefined,
227
233
  // t-0e56: when main's context is compacted at a turn boundary.
228
234
  compact: compactSettings(projectSettings.compact),