@anhlp/alp-runtime 0.0.0-beta.2 → 0.0.1-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/acp-transport.js +7 -36
  2. package/dist/antigravity-transport.d.ts +27 -2
  3. package/dist/antigravity-transport.js +104 -58
  4. package/dist/assignment-results.d.ts +55 -0
  5. package/dist/assignment-results.js +181 -0
  6. package/dist/attachments.d.ts +84 -0
  7. package/dist/attachments.js +213 -0
  8. package/dist/board-domain.js +2 -2
  9. package/dist/board.d.ts +6 -0
  10. package/dist/board.js +7 -0
  11. package/dist/catalog.d.ts +13 -0
  12. package/dist/catalog.js +11 -2
  13. package/dist/claude-transport.d.ts +80 -0
  14. package/dist/claude-transport.js +271 -23
  15. package/dist/compact.d.ts +29 -0
  16. package/dist/compact.js +49 -0
  17. package/dist/configure.d.ts +44 -0
  18. package/dist/configure.js +64 -0
  19. package/dist/contracts.d.ts +216 -7
  20. package/dist/contracts.js +11 -0
  21. package/dist/conversation.d.ts +45 -0
  22. package/dist/conversation.js +62 -0
  23. package/dist/index.d.ts +18 -5
  24. package/dist/index.js +48 -4
  25. package/dist/input-limits.d.ts +25 -0
  26. package/dist/input-limits.js +48 -0
  27. package/dist/language.d.ts +10 -0
  28. package/dist/language.js +26 -0
  29. package/dist/live.d.ts +2 -2
  30. package/dist/live.js +7 -2
  31. package/dist/mailbox.d.ts +2 -0
  32. package/dist/mailbox.js +3 -1
  33. package/dist/mcp-tools.d.ts +8 -0
  34. package/dist/mcp-tools.js +26 -0
  35. package/dist/model-catalog.d.ts +162 -0
  36. package/dist/model-catalog.js +338 -0
  37. package/dist/model-probes.d.ts +7 -0
  38. package/dist/model-probes.js +69 -0
  39. package/dist/providers.js +2 -0
  40. package/dist/recall.d.ts +2 -2
  41. package/dist/recall.js +4 -3
  42. package/dist/resolve.d.ts +2 -0
  43. package/dist/resolve.js +9 -5
  44. package/dist/runtime-context.d.ts +1 -1
  45. package/dist/runtime-context.js +1 -1
  46. package/dist/runtime.d.ts +9 -0
  47. package/dist/runtime.js +2078 -269
  48. package/dist/session-config.d.ts +378 -6
  49. package/dist/session-config.js +19 -15
  50. package/dist/session-state.d.ts +54 -7
  51. package/dist/skill-resources.d.ts +30 -0
  52. package/dist/skill-resources.js +55 -0
  53. package/dist/tool-detail.js +4 -1
  54. package/dist/tools.d.ts +154 -1
  55. package/dist/tools.js +99 -11
  56. package/dist/transport.js +3 -1
  57. package/dist/workspace.d.ts +31 -5
  58. package/dist/workspace.js +92 -11
  59. package/dist/worktree-domain.d.ts +2 -1
  60. package/dist/worktree-domain.js +4 -1
  61. package/dist/write-error.d.ts +2 -0
  62. package/dist/write-error.js +10 -0
  63. package/package.json +12 -4
  64. package/src/acp-transport.ts +10 -37
  65. package/src/antigravity-transport.ts +128 -55
  66. package/src/assignment-results.ts +154 -0
  67. package/src/attachments.ts +254 -0
  68. package/src/board-domain.ts +2 -2
  69. package/src/board.ts +7 -0
  70. package/src/catalog.ts +13 -2
  71. package/src/claude-transport.ts +333 -23
  72. package/src/compact.ts +62 -0
  73. package/src/configure.ts +93 -0
  74. package/src/contracts.ts +199 -8
  75. package/src/conversation.ts +81 -0
  76. package/src/index.ts +18 -5
  77. package/src/input-limits.ts +65 -0
  78. package/src/language.ts +28 -0
  79. package/src/live.ts +7 -3
  80. package/src/mailbox.ts +4 -1
  81. package/src/mcp-tools.ts +33 -0
  82. package/src/model-catalog.ts +316 -0
  83. package/src/model-probes.ts +58 -0
  84. package/src/providers.ts +3 -0
  85. package/src/recall.ts +4 -3
  86. package/src/resolve.ts +15 -7
  87. package/src/runtime-context.ts +2 -2
  88. package/src/runtime.ts +2253 -264
  89. package/src/session-config.ts +25 -14
  90. package/src/session-state.ts +39 -3
  91. package/src/skill-resources.ts +73 -0
  92. package/src/tool-detail.ts +4 -1
  93. package/src/tools.ts +97 -10
  94. package/src/transport.ts +3 -1
  95. package/src/workspace.ts +124 -18
  96. package/src/worktree-domain.ts +5 -1
  97. package/src/write-error.ts +4 -0
package/src/language.ts CHANGED
@@ -18,6 +18,15 @@ 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.` : ''),
25
+ lessonCurate: (agent: string, changes: string) =>
26
+ `${agent} proposes to curate the lessons files. Approve to apply every change below at once; nothing else changes.\n\n${changes}`,
27
+ lessonRemove: 'Remove',
28
+ lessonAdd: 'Add',
29
+ lessonScope: (scope: string, file: string) => `${scope === 'user' ? 'User lessons' : 'Project lessons'} (${file})`,
21
30
  issueLabels: 'Labels',
22
31
  trust: (project: string, names: string) => `This project's hooks run shell commands from ${project} on your machine: ${names}. ` +
23
32
  'Trust this workspace\'s hooks? ALP asks once: after you agree, its hooks run without asking, including hooks added or changed later.',
@@ -33,10 +42,15 @@ const en = {
33
42
  limitReached: (runtime: string, resetsAt: string | undefined, other: string | undefined, autoResume: boolean, kind: string) =>
34
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}.`}`,
35
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.',
46
+ compacted: (native: boolean) => `Main's context was compacted${native ? '' : ' into a fresh conversation'}; it keeps its checkpoint and carries on.`,
47
+ compactFailed: (reason: string) => `Compacting main's context failed (${reason}); ALP tries again later.`,
36
48
  usageWarning: (runtime: string, used: string, resetsAt: string | undefined) => `${runtime} has used ${used} of a usage window${resetsAt ? ` that resets ${resetsAt}` : ''}.`,
37
49
  /** The web app's answer to a Paseo feature ALP has not got yet (ALPD §62). */
38
50
  inDevelopment: 'This feature is in development',
39
51
  resumed: (what: string, by: string, parked: boolean) => `${what} resumed by ${by}.${parked ? ' Parked assignments continue.' : ''}`,
52
+ diskFull: (reason: string) => `Disk full: ${reason}. ALP paused its work and parked running assignments; it keeps answering. Free some space (alp doctor lists leftover worktrees); ALP checks every minute and continues by itself, or run alp resume.`,
53
+ diskLow: (free: string) => `Disk space is low: ${free} free. Free some space before it fills (alp doctor lists leftover worktrees); when it is full, ALP pauses its work.`,
40
54
  paused: (what: string, reason: string | undefined, runtime: string | undefined, now: boolean) =>
41
55
  `${what} paused by the user${reason ? `: ${reason}` : ''}. Delegation${runtime ? ` to ${runtime} agents` : ''} waits${now ? ', and running assignments park where they are' : '; running turns finish'}. alp resume continues.`,
42
56
  };
@@ -58,6 +72,15 @@ const vi: Words = {
58
72
  `${agent} muốn ${create ? `mở một issue trong ${where}` : `bình luận vào issue #${issue} trong ${where}`}. ` +
59
73
  'Nội dung được đăng bằng tài khoản GitHub của bạn, ai xem được repository đều đọc được.',
60
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ó.` : ''),
79
+ lessonCurate: (agent, changes) =>
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}`,
81
+ lessonRemove: 'Bỏ',
82
+ lessonAdd: 'Thêm',
83
+ lessonScope: (scope, file) => `${scope === 'user' ? 'Bài học của người dùng' : 'Bài học của project'} (${file})`,
61
84
  issueLabels: 'Nhãn',
62
85
  trust: (project, names) => `Các hook của project này chạy lệnh shell từ ${project} trên máy của bạn: ${names}. ` +
63
86
  'Tin cậy các hook của workspace này? ALP chỉ hỏi một lần: khi bạn đồng ý, các hook chạy mà không hỏi lại, kể cả hook thêm hoặc sửa sau này.',
@@ -73,9 +96,14 @@ const vi: Words = {
73
96
  limitReached: (runtime, resetsAt, other, autoResume, kind) =>
74
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}.`}`,
75
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.',
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.`,
101
+ compactFailed: reason => `Compact context của main thất bại (${reason}); ALP sẽ thử lại sau.`,
76
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}` : ''}.`,
77
103
  inDevelopment: 'Tính năng đang phát triển',
78
104
  resumed: (what, by, parked) => `${what} đã chạy lại, bởi ${by}.${parked ? ' Các việc đang tạm giữ được làm tiếp.' : ''}`,
105
+ diskFull: reason => `Đĩa đầy: ${reason === 'the disk is full' ? 'đĩa hết dung lượng' : reason === 'the disk is read-only' ? 'đĩa chỉ đọc' : reason}. ALP đã tạm dừng công việc và tạm giữ các việc đang chạy; ALP vẫn trả lời. Hãy giải phóng dung lượng (alp doctor liệt kê các worktree còn sót); ALP kiểm tra mỗi phút và tự làm tiếp, hoặc chạy alp resume.`,
106
+ diskLow: free => `Đĩa sắp đầy: còn ${free} trống. Hãy giải phóng dung lượng trước khi đầy (alp doctor liệt kê các worktree còn sót); khi đĩa đầy, ALP sẽ tạm dừng công việc.`,
79
107
  paused: (what, reason, runtime, now) =>
80
108
  `${what} đã bị người dùng tạm dừng${reason ? `: ${reason}` : ''}. Việc giao${runtime ? ` cho các agent ${runtime}` : ''} phải chờ${now ? ', các việc đang chạy được tạm giữ tại chỗ' : '; các lượt đang chạy vẫn chạy hết'}. Chạy alp resume để tiếp tục.`,
81
109
  };
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 {
package/src/mailbox.ts CHANGED
@@ -27,8 +27,11 @@ export function takeBatch(mail: MailEvent[], accept: (event: MailEvent) => boole
27
27
  return batch;
28
28
  }
29
29
 
30
+ /** How rendered mail begins, so a replayed prompt can tell ALP's mail from the user's words. */
31
+ export const MAIL_HEADER = 'ALP mail from other agents.';
32
+
30
33
  export function renderMail(events: MailEvent[], requester?: string) {
31
- const header = 'ALP mail from other agents. ' +
34
+ const header = `${MAIL_HEADER} ` +
32
35
  (events.some(event => event.from === USER)
33
36
  ? 'Mail sent by "user" is the user writing to you directly: follow it as a user instruction. ' +
34
37
  (requester ? `ALP has told ${requester} about it. You may now ask the user with alp_ask to: "user"; your handoff must say what the user asked and what you did. ` : '')
package/src/mcp-tools.ts CHANGED
@@ -3,9 +3,37 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
3
3
  import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
4
4
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
5
5
 
6
+ import { inputLimitError, type InputLimits } from './input-limits.js';
7
+
6
8
  type Tool = { name: string; description: string; inputSchema: unknown };
7
9
  type Server = { command?: string; args?: string[]; env?: Record<string, string>; cwd?: string; url?: string; http_headers?: Record<string, string> };
8
10
 
11
+ /** What one external MCP server may list: pages of tools/list, and tools over all of them. */
12
+ export const MCP_TOOLS = { pages: 20, tools: 500 };
13
+ /** One tools/list result, checked before the MCP SDK parses it with ListToolsResultSchema. */
14
+ export const MCP_TOOLS_PAGE: InputLimits = { bytes: 4 * 1024 * 1024, items: 100_000, depth: 32, string: 64 * 1024 };
15
+
16
+ /** Turns an oversized tools/list result into an error response before the client parses it.
17
+ * Called after connect, which installs the client's own onmessage. */
18
+ function limitToolPages(transport: Wire) {
19
+ const listing = new Set<string | number>();
20
+ const send = transport.send.bind(transport);
21
+ transport.send = (message, ...rest) => {
22
+ if ('method' in message && message.method === 'tools/list' && 'id' in message) listing.add(message.id);
23
+ return send(message, ...rest);
24
+ };
25
+ const deliver = transport.onmessage;
26
+ transport.onmessage = (message, ...rest) => {
27
+ if ('id' in message && 'result' in message && listing.delete(message.id)) {
28
+ const error = inputLimitError(message.result, MCP_TOOLS_PAGE, 'A tools/list page');
29
+ if (error) return deliver?.({ jsonrpc: '2.0', id: message.id, error: { code: -32600, message: error } }, ...rest);
30
+ }
31
+ deliver?.(message, ...rest);
32
+ };
33
+ }
34
+ type Message = Parameters<StdioClientTransport['send']>[0];
35
+ type Wire = { send(message: Message, ...rest: unknown[]): Promise<void>; onmessage?(message: Message, ...rest: unknown[]): void };
36
+
9
37
  /** Client.connect starts cleanup without awaiting it on initialization failure.
10
38
  * Keep that promise so session shutdown waits for the same process cleanup.
11
39
  */
@@ -38,10 +66,15 @@ export async function openMcpTools(servers: Record<string, Server>, cwd: string,
38
66
  try {
39
67
  await client.connect(transport, { timeout: 20_000, signal });
40
68
  if (!client.getServerCapabilities()?.tools) continue;
69
+ limitToolPages(transport);
41
70
  let cursor: string | undefined;
42
71
  const seen = new Set<string>();
72
+ let listed = 0;
43
73
  do {
74
+ if (seen.size >= MCP_TOOLS.pages) throw new Error(`More than ${MCP_TOOLS.pages} pages of MCP tools`);
44
75
  const page = await client.listTools(cursor ? { cursor } : {}, { timeout: 20_000, signal });
76
+ listed += page.tools.length;
77
+ if (listed > MCP_TOOLS.tools) throw new Error(`More than ${MCP_TOOLS.tools} MCP tools`);
45
78
  for (const tool of page.tools) {
46
79
  const hash = createHash('sha256').update(JSON.stringify([name, tool.name])).digest('hex').slice(0, 10);
47
80
  const clean = (value: string, length: number) => value.replace(/[^\w-]/g, '_').slice(0, length);
@@ -0,0 +1,316 @@
1
+ /**
2
+ * The live model catalog (t-e5ee): ALP serves core MODELS at once, then asks each provider which
3
+ * models it offers now and merges the answer over the static rows. A probe that fails keeps the
4
+ * previous list; the merged answer is cached in ALP_HOME/cache/models.json for the next start.
5
+ */
6
+ import { mkdir, readFile } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { MODELS, MODEL_POLICY, catalogCacheFile, mergeCatalog as mergeCatalogRows } from '@anhlp/alp-core/models';
9
+ import { writeAtomic } from '@anhlp/alp-core/atomic';
10
+ import { applyCatalog, type CatalogEntry } from './catalog.js';
11
+
12
+ export type CatalogRuntime = 'codex' | 'claude' | 'antigravity';
13
+ /** A model as a provider reports it. */
14
+ export type LiveModel = { id: string; label?: string; description?: string; efforts?: string[]; effort?: string };
15
+ export type ProviderState = { status: 'ok' | 'failed' | 'static'; fetchedAt?: string; error?: string; models: LiveModel[] };
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> };
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 };
28
+
29
+ const RUNTIMES: CatalogRuntime[] = ['codex', 'claude', 'antigravity'];
30
+ export const REFRESH_MS = 6 * 60 * 60 * 1000;
31
+ export const PROBE_TIMEOUT_MS = 15_000;
32
+
33
+ export const POLICY = MODEL_POLICY;
34
+ export const mergeCatalog = mergeCatalogRows as (base: CatalogEntry[], live: Partial<Record<CatalogRuntime, LiveModel[] | undefined>>) => CatalogEntry[];
35
+
36
+ const staticRows = (): CatalogEntry[] => MODELS.map(entry => ({ ...entry, source: 'static' as const })) as CatalogEntry[];
37
+
38
+ const bounded = <T>(work: (signal: AbortSignal) => Promise<T>, ms: number) => {
39
+ const controller = new AbortController();
40
+ let timer: NodeJS.Timeout | undefined;
41
+ return Promise.race([
42
+ work(controller.signal),
43
+ new Promise<never>((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(new Error(`timed out after ${ms} ms`)); }, ms); }),
44
+ ]).finally(() => clearTimeout(timer));
45
+ };
46
+
47
+ const strings = (value: unknown) => Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : undefined;
48
+ /** Only well-formed rows: a string id, string label/description/effort, string efforts. */
49
+ export function sanitizeModels(value: unknown): LiveModel[] {
50
+ if (!Array.isArray(value)) return [];
51
+ return value.filter(model => model && typeof model === 'object' && typeof model.id === 'string' && model.id.trim()).map(model => ({
52
+ id: model.id,
53
+ ...(typeof model.label === 'string' ? { label: model.label } : {}),
54
+ ...(typeof model.description === 'string' ? { description: model.description } : {}),
55
+ ...(strings(model.efforts) ? { efforts: strings(model.efforts) } : {}),
56
+ ...(typeof model.effort === 'string' ? { effort: model.effort } : {}),
57
+ }));
58
+ }
59
+ /** A cache file read back: known runtimes only, each with a list of well-formed rows. */
60
+ function sanitize(value: any): CatalogSnapshot {
61
+ const providers: CatalogSnapshot['providers'] = {};
62
+ for (const runtime of RUNTIMES) {
63
+ const state = value?.providers?.[runtime];
64
+ if (!state || typeof state !== 'object') continue;
65
+ providers[runtime] = { status: state.status === 'ok' ? 'ok' : 'failed', ...(typeof state.fetchedAt === 'string' ? { fetchedAt: state.fetchedAt } : {}), models: sanitizeModels(state.models) };
66
+ }
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 } : {}) })));
81
+ }
82
+
83
+ type Listener = (snapshot: CatalogSnapshot, entries: CatalogEntry[]) => void;
84
+
85
+ export class ModelCatalog {
86
+ private snapshot: CatalogSnapshot = { providers: {} };
87
+ private current: CatalogEntry[] = staticRows();
88
+ private listeners = new Set<Listener>();
89
+ private timer?: NodeJS.Timeout;
90
+ private running?: Promise<CatalogSnapshot>;
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;
100
+
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 }) {
108
+ this.file = options.home ? catalogCacheFile(options.home) : undefined;
109
+ }
110
+
111
+ entries() { return this.current; }
112
+ state() { return this.snapshot; }
113
+ onUpdated(listener: Listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
114
+
115
+ /** Loads the cache, then refreshes in the background and every refreshMs. Never blocks on a provider. */
116
+ async start() {
117
+ this.stopped = false;
118
+ await this.load();
119
+ await this.loadAcp().catch(() => {});
120
+ void this.refresh().catch(() => {});
121
+ const every = this.options.refreshMs ?? REFRESH_MS;
122
+ if (every > 0) { this.timer = setInterval(() => { void this.refresh().catch(() => {}); }, every); this.timer.unref?.(); }
123
+ }
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
+ }
138
+
139
+ async load() {
140
+ if (!this.file) return;
141
+ try {
142
+ this.snapshot = sanitize(JSON.parse(await readFile(this.file, 'utf8')));
143
+ await this.publish(false);
144
+ } catch { this.snapshot = { providers: {} }; /* no cache, or unreadable: static rows serve */ }
145
+ }
146
+
147
+ /** Asks every provider (or the named ones; a refresh already running answers instead) at once; each answer is bounded, and a failure keeps that provider's previous list. */
148
+ refresh(runtimes: CatalogRuntime[] = RUNTIMES): Promise<CatalogSnapshot> {
149
+ if (this.running) return this.running;
150
+ this.running = (async () => {
151
+ const now = () => (this.options.now?.() ?? new Date()).toISOString();
152
+ const results = await Promise.all(runtimes.filter(runtime => this.options.probes[runtime]).map(async runtime => {
153
+ try { return [runtime, { status: 'ok', fetchedAt: now(), models: sanitizeModels(await bounded(this.options.probes[runtime]!, this.options.timeoutMs ?? PROBE_TIMEOUT_MS)) }] as const; }
154
+ catch (error) {
155
+ const prior = this.snapshot.providers[runtime];
156
+ return [runtime, { status: 'failed', fetchedAt: prior?.fetchedAt, error: error instanceof Error ? error.message : String(error), models: prior?.models ?? [] }] as const;
157
+ }
158
+ }));
159
+ for (const [runtime, state] of results) {
160
+ // An empty answer is no answer: keep what we had.
161
+ if (state.status === 'ok' && !state.models.length) { this.snapshot.providers[runtime] = { ...(this.snapshot.providers[runtime] ?? { models: [] }), status: 'failed', error: 'provider reported no models' }; continue; }
162
+ this.snapshot.providers[runtime] = state as ProviderState;
163
+ }
164
+ this.snapshot.fetchedAt = now();
165
+ await this.publish(true);
166
+ return this.snapshot;
167
+ })().finally(() => { this.running = undefined; });
168
+ return this.running;
169
+ }
170
+
171
+ /**
172
+ * A list a session reported on its own (each turn's orchestration context). Additive: it only adds
173
+ * models the catalog does not list yet, after the ones it has, so it never narrows or reshapes what a
174
+ * probe answered; a list with nothing new changes nothing.
175
+ */
176
+ async ingest(runtime: CatalogRuntime, models: LiveModel[]) {
177
+ const prior = this.snapshot.providers[runtime];
178
+ const known = new Set((prior?.models ?? []).map(model => model.id));
179
+ const added = sanitizeModels(models).filter(model => !known.has(model.id));
180
+ if (!added.length) return false;
181
+ this.snapshot.providers[runtime] = { ...(prior ?? { status: 'ok' }), status: prior?.status ?? 'ok', fetchedAt: prior?.fetchedAt ?? (this.options.now?.() ?? new Date()).toISOString(), models: [...(prior?.models ?? []), ...added] };
182
+ await this.publish(true);
183
+ return true;
184
+ }
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
+
274
+ private async publish(save: boolean) {
275
+ const next = mergeCatalog(staticRows(), Object.fromEntries(Object.entries(this.snapshot.providers).map(([runtime, state]) => [runtime, state?.models])));
276
+ const changed = JSON.stringify(next) !== JSON.stringify(this.current);
277
+ this.current = next;
278
+ if (this.options.apply !== false) applyCatalog(next);
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); }
286
+ }
287
+ if (save) for (const listener of this.listeners) { try { listener(this.snapshot, next); } catch { /* a listener never stops the catalog */ } }
288
+ return changed;
289
+ }
290
+ }
291
+
292
+ /** Reads a session's orchestration context models (`runtime:id`, label, description, thinking) as live models. */
293
+ export function liveFromContext(context: any): { runtime: CatalogRuntime; models: LiveModel[] } | undefined {
294
+ if (!context?.catalogAvailable || !RUNTIMES.includes(context.runtime) || !Array.isArray(context.models)) return undefined;
295
+ if (context.catalogComplete === false) return undefined;
296
+ const prefix = `${context.runtime}:`;
297
+ const models = context.models.filter((model: any) => typeof model?.id === 'string' && model.id.startsWith(prefix)).map((model: any) => ({
298
+ id: model.id.slice(prefix.length), label: model.label, description: model.description,
299
+ efforts: Array.isArray(model.thinking) ? model.thinking.map((effort: any) => typeof effort === 'string' ? effort : effort?.reasoningEffort ?? effort?.id).filter((effort: unknown) => typeof effort === 'string') : undefined,
300
+ }));
301
+ return { runtime: context.runtime, models };
302
+ }
303
+
304
+ let active: ModelCatalog | undefined;
305
+ /** The daemon's catalog, which sessions feed opportunistically. */
306
+ export function setActiveCatalog(catalog: ModelCatalog | undefined) { active = catalog; }
307
+ export function activeCatalog() { return active; }
308
+ export function feedCatalog(context: unknown) {
309
+ const live = liveFromContext(context);
310
+ if (live && active) void active.ingest(live.runtime, live.models).catch(() => {});
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
+ }
@@ -0,0 +1,58 @@
1
+ /** Live model probes for the catalog (t-e5ee): each asks a provider's own CLI, read-only, and closes it. */
2
+ import { spawn } from 'node:child_process';
3
+ import os from 'node:os';
4
+ import { CodexTransport } from './transport.js';
5
+ import { ClaudeTransport } from './claude-transport.js';
6
+ import type { CatalogRuntime, LiveModel, Probe } from './model-catalog.js';
7
+
8
+ export function codexProbe(command = process.env.ALP_CODEX_BIN ?? 'codex', env: NodeJS.ProcessEnv = process.env): Probe {
9
+ return async signal => {
10
+ const transport = new CodexTransport(command, os.tmpdir(), env);
11
+ const stop = () => { void transport.close(); };
12
+ signal.addEventListener('abort', stop);
13
+ try {
14
+ await transport.initialize();
15
+ const models: LiveModel[] = [];
16
+ let cursor: string | undefined;
17
+ for (let page = 0; page < 10; page++) {
18
+ const result = await transport.request('model/list', { limit: 100, includeHidden: false, ...(cursor ? { cursor } : {}) }, 10_000, false);
19
+ for (const model of result?.data ?? []) {
20
+ if (typeof model?.model !== 'string' || model.hidden) continue;
21
+ models.push({ id: model.model, label: model.displayName, description: model.description,
22
+ efforts: (model.supportedReasoningEfforts ?? []).map((effort: any) => typeof effort === 'string' ? effort : effort?.reasoningEffort).filter((effort: unknown) => typeof effort === 'string'),
23
+ effort: model.defaultReasoningEffort });
24
+ }
25
+ cursor = result?.nextCursor ?? undefined;
26
+ if (!cursor) break;
27
+ }
28
+ return models;
29
+ } finally { signal.removeEventListener('abort', stop); await transport.close(); }
30
+ };
31
+ }
32
+
33
+ export function claudeProbe(command = process.env.ALP_CLAUDE_BIN ?? 'claude', env: NodeJS.ProcessEnv = process.env): Probe {
34
+ return async signal => new ClaudeTransport(command, os.tmpdir(), env).probeModels(signal);
35
+ }
36
+
37
+ /** `agy models` prints one model per line, `id<TAB>label`. */
38
+ export function parseAgyModels(stdout: string): LiveModel[] {
39
+ return stdout.split(/\r?\n/).map(line => line.trim()).filter(Boolean).map(line => {
40
+ const [id, label] = line.split('\t').map(part => part.trim());
41
+ return { id, label: label || id };
42
+ }).filter(model => model.id && /^[A-Za-z0-9][\w.:\-\[\]/]*$/.test(model.id));
43
+ }
44
+
45
+ export function antigravityProbe(command = process.env.ALP_ANTIGRAVITY_BIN ?? 'agy', env: NodeJS.ProcessEnv = process.env, args: string[] = []): Probe {
46
+ return signal => new Promise((resolve, reject) => {
47
+ const child = spawn(command, [...args, 'models'], { cwd: os.tmpdir(), env, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, signal });
48
+ let stdout = '';
49
+ // A model list is small; more than this is not one.
50
+ child.stdout.on('data', chunk => { stdout += chunk; if (stdout.length > 256 * 1024) child.kill('SIGKILL'); });
51
+ child.on('error', reject);
52
+ child.on('close', code => code === 0 ? resolve(parseAgyModels(stdout)) : reject(new Error(`${command} models exited with ${code}`)));
53
+ });
54
+ }
55
+
56
+ export function liveProbes(env: NodeJS.ProcessEnv = process.env): Record<CatalogRuntime, Probe> {
57
+ return { codex: codexProbe(undefined, env), claude: claudeProbe(undefined, env), antigravity: antigravityProbe(undefined, env) };
58
+ }
package/src/providers.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { AGENT_MARKER } from '@anhlp/alp-core/tasks';
1
2
  import { CodexTransport } from './transport.js';
2
3
  import { ClaudeTransport } from './claude-transport.js';
3
4
  import { AcpTransport, type AcpProvider } from './acp-transport.js';
@@ -12,6 +13,8 @@ export function nativeEnvironment(options: RuntimeOptions, extra: Record<string,
12
13
  // Markers of an enclosing Paseo, Codex or Claude Code session would make the native harness think it is nested.
13
14
  if (/^(PASEO_|CODEX_THREAD_ID$|CODEX_INTERNAL_|CODEX_PARENT_|CLAUDECODE$|CLAUDE_CODE_|ANTHROPIC_AGENT_)/.test(key)) delete environment[key];
14
15
  }
16
+ // Every process the agent runs inherits it: the CLI and alpd refuse it what only the user may do (t-ca1f).
17
+ environment[AGENT_MARKER] = '1';
15
18
  return environment;
16
19
  }
17
20
 
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 {