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

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 (67) hide show
  1. package/dist/acp-transport.js +5 -36
  2. package/dist/antigravity-transport.d.ts +17 -0
  3. package/dist/antigravity-transport.js +82 -58
  4. package/dist/assignment-results.d.ts +34 -0
  5. package/dist/assignment-results.js +94 -2
  6. package/dist/board-domain.js +2 -2
  7. package/dist/board.d.ts +6 -0
  8. package/dist/board.js +7 -0
  9. package/dist/catalog.d.ts +13 -0
  10. package/dist/catalog.js +9 -1
  11. package/dist/claude-transport.d.ts +7 -0
  12. package/dist/claude-transport.js +71 -10
  13. package/dist/compact.d.ts +29 -0
  14. package/dist/compact.js +49 -0
  15. package/dist/configure.d.ts +1 -1
  16. package/dist/configure.js +2 -2
  17. package/dist/contracts.d.ts +32 -3
  18. package/dist/index.d.ts +10 -2
  19. package/dist/index.js +30 -2
  20. package/dist/input-limits.d.ts +25 -0
  21. package/dist/input-limits.js +48 -0
  22. package/dist/language.d.ts +8 -0
  23. package/dist/language.js +20 -0
  24. package/dist/mcp-tools.d.ts +8 -0
  25. package/dist/mcp-tools.js +26 -0
  26. package/dist/model-catalog.d.ts +76 -0
  27. package/dist/model-catalog.js +193 -0
  28. package/dist/model-probes.d.ts +7 -0
  29. package/dist/model-probes.js +69 -0
  30. package/dist/providers.js +2 -0
  31. package/dist/resolve.d.ts +1 -0
  32. package/dist/resolve.js +3 -1
  33. package/dist/runtime.d.ts +3 -1
  34. package/dist/runtime.js +665 -47
  35. package/dist/session-config.d.ts +174 -0
  36. package/dist/session-config.js +9 -9
  37. package/dist/session-state.d.ts +23 -1
  38. package/dist/tools.d.ts +82 -0
  39. package/dist/tools.js +53 -5
  40. package/dist/transport.js +3 -1
  41. package/dist/workspace.d.ts +31 -5
  42. package/dist/workspace.js +92 -11
  43. package/package.json +3 -3
  44. package/src/acp-transport.ts +7 -37
  45. package/src/antigravity-transport.ts +95 -53
  46. package/src/assignment-results.ts +85 -3
  47. package/src/board-domain.ts +2 -2
  48. package/src/board.ts +7 -0
  49. package/src/catalog.ts +10 -1
  50. package/src/claude-transport.ts +79 -10
  51. package/src/compact.ts +62 -0
  52. package/src/configure.ts +3 -3
  53. package/src/contracts.ts +28 -2
  54. package/src/index.ts +10 -2
  55. package/src/input-limits.ts +65 -0
  56. package/src/language.ts +18 -0
  57. package/src/mcp-tools.ts +33 -0
  58. package/src/model-catalog.ts +166 -0
  59. package/src/model-probes.ts +58 -0
  60. package/src/providers.ts +3 -0
  61. package/src/resolve.ts +4 -2
  62. package/src/runtime.ts +718 -48
  63. package/src/session-config.ts +8 -8
  64. package/src/session-state.ts +15 -1
  65. package/src/tools.ts +53 -5
  66. package/src/transport.ts +3 -1
  67. package/src/workspace.ts +124 -18
package/src/language.ts CHANGED
@@ -18,6 +18,11 @@ 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
+ lessonCurate: (agent: string, changes: string) =>
22
+ `${agent} proposes to curate the lessons files. Approve to apply every change below at once; nothing else changes.\n\n${changes}`,
23
+ lessonRemove: 'Remove',
24
+ lessonAdd: 'Add',
25
+ lessonScope: (scope: string, file: string) => `${scope === 'user' ? 'User lessons' : 'Project lessons'} (${file})`,
21
26
  issueLabels: 'Labels',
22
27
  trust: (project: string, names: string) => `This project's hooks run shell commands from ${project} on your machine: ${names}. ` +
23
28
  'Trust this workspace\'s hooks? ALP asks once: after you agree, its hooks run without asking, including hooks added or changed later.',
@@ -33,10 +38,14 @@ const en = {
33
38
  limitReached: (runtime: string, resetsAt: string | undefined, other: string | undefined, autoResume: boolean, kind: string) =>
34
39
  `${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
40
  limitLifted: (runtime: string, kind: string) => `${runtime} says its usage limit has lifted. Run alp resume ${kind} to continue its work.`,
41
+ compacted: (native: boolean) => `Main's context was compacted${native ? '' : ' into a fresh conversation'}; it keeps its checkpoint and carries on.`,
42
+ compactFailed: (reason: string) => `Compacting main's context failed (${reason}); ALP tries again later.`,
36
43
  usageWarning: (runtime: string, used: string, resetsAt: string | undefined) => `${runtime} has used ${used} of a usage window${resetsAt ? ` that resets ${resetsAt}` : ''}.`,
37
44
  /** The web app's answer to a Paseo feature ALP has not got yet (ALPD §62). */
38
45
  inDevelopment: 'This feature is in development',
39
46
  resumed: (what: string, by: string, parked: boolean) => `${what} resumed by ${by}.${parked ? ' Parked assignments continue.' : ''}`,
47
+ 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.`,
48
+ 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
49
  paused: (what: string, reason: string | undefined, runtime: string | undefined, now: boolean) =>
41
50
  `${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
51
  };
@@ -58,6 +67,11 @@ const vi: Words = {
58
67
  `${agent} muốn ${create ? `mở một issue trong ${where}` : `bình luận vào issue #${issue} trong ${where}`}. ` +
59
68
  'Nội dung được đăng bằng tài khoản GitHub của bạn, ai xem được repository đều đọc được.',
60
69
  issueTitle: 'Tiêu đề',
70
+ lessonCurate: (agent, changes) =>
71
+ `${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
+ lessonRemove: 'Bỏ',
73
+ lessonAdd: 'Thêm',
74
+ lessonScope: (scope, file) => `${scope === 'user' ? 'Bài học của người dùng' : 'Bài học của project'} (${file})`,
61
75
  issueLabels: 'Nhãn',
62
76
  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
77
  '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 +87,13 @@ const vi: Words = {
73
87
  limitReached: (runtime, resetsAt, other, autoResume, kind) =>
74
88
  `${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
89
  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ó.`,
90
+ 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
+ compactFailed: reason => `Compact context của main thất bại (${reason}); ALP sẽ thử lại sau.`,
76
92
  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
93
  inDevelopment: 'Tính năng đang phát triển',
78
94
  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.' : ''}`,
95
+ 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.`,
96
+ 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
97
  paused: (what, reason, runtime, now) =>
80
98
  `${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
99
  };
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,166 @@
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
+ export type CatalogSnapshot = { fetchedAt?: string; providers: Partial<Record<CatalogRuntime, ProviderState>> };
17
+ export type Probe = (signal: AbortSignal) => Promise<LiveModel[]>;
18
+
19
+ const RUNTIMES: CatalogRuntime[] = ['codex', 'claude', 'antigravity'];
20
+ export const REFRESH_MS = 6 * 60 * 60 * 1000;
21
+ export const PROBE_TIMEOUT_MS = 15_000;
22
+
23
+ export const POLICY = MODEL_POLICY;
24
+ export const mergeCatalog = mergeCatalogRows as (base: CatalogEntry[], live: Partial<Record<CatalogRuntime, LiveModel[] | undefined>>) => CatalogEntry[];
25
+
26
+ const staticRows = (): CatalogEntry[] => MODELS.map(entry => ({ ...entry, source: 'static' as const })) as CatalogEntry[];
27
+
28
+ const bounded = <T>(work: (signal: AbortSignal) => Promise<T>, ms: number) => {
29
+ const controller = new AbortController();
30
+ let timer: NodeJS.Timeout | undefined;
31
+ return Promise.race([
32
+ work(controller.signal),
33
+ new Promise<never>((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(new Error(`timed out after ${ms} ms`)); }, ms); }),
34
+ ]).finally(() => clearTimeout(timer));
35
+ };
36
+
37
+ const strings = (value: unknown) => Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : undefined;
38
+ /** Only well-formed rows: a string id, string label/description/effort, string efforts. */
39
+ export function sanitizeModels(value: unknown): LiveModel[] {
40
+ if (!Array.isArray(value)) return [];
41
+ return value.filter(model => model && typeof model === 'object' && typeof model.id === 'string' && model.id.trim()).map(model => ({
42
+ id: model.id,
43
+ ...(typeof model.label === 'string' ? { label: model.label } : {}),
44
+ ...(typeof model.description === 'string' ? { description: model.description } : {}),
45
+ ...(strings(model.efforts) ? { efforts: strings(model.efforts) } : {}),
46
+ ...(typeof model.effort === 'string' ? { effort: model.effort } : {}),
47
+ }));
48
+ }
49
+ /** A cache file read back: known runtimes only, each with a list of well-formed rows. */
50
+ function sanitize(value: any): CatalogSnapshot {
51
+ const providers: CatalogSnapshot['providers'] = {};
52
+ for (const runtime of RUNTIMES) {
53
+ const state = value?.providers?.[runtime];
54
+ if (!state || typeof state !== 'object') continue;
55
+ providers[runtime] = { status: state.status === 'ok' ? 'ok' : 'failed', ...(typeof state.fetchedAt === 'string' ? { fetchedAt: state.fetchedAt } : {}), models: sanitizeModels(state.models) };
56
+ }
57
+ return { ...(typeof value?.fetchedAt === 'string' ? { fetchedAt: value.fetchedAt } : {}), providers };
58
+ }
59
+
60
+ type Listener = (snapshot: CatalogSnapshot, entries: CatalogEntry[]) => void;
61
+
62
+ export class ModelCatalog {
63
+ private snapshot: CatalogSnapshot = { providers: {} };
64
+ private current: CatalogEntry[] = staticRows();
65
+ private listeners = new Set<Listener>();
66
+ private timer?: NodeJS.Timeout;
67
+ private running?: Promise<CatalogSnapshot>;
68
+ private readonly file?: string;
69
+
70
+ constructor(private readonly options: { home?: string; probes: Partial<Record<CatalogRuntime, Probe>>; timeoutMs?: number; refreshMs?: number; now?: () => Date; apply?: boolean }) {
71
+ this.file = options.home ? catalogCacheFile(options.home) : undefined;
72
+ }
73
+
74
+ entries() { return this.current; }
75
+ state() { return this.snapshot; }
76
+ onUpdated(listener: Listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
77
+
78
+ /** Loads the cache, then refreshes in the background and every refreshMs. Never blocks on a provider. */
79
+ async start() {
80
+ await this.load();
81
+ void this.refresh().catch(() => {});
82
+ const every = this.options.refreshMs ?? REFRESH_MS;
83
+ if (every > 0) { this.timer = setInterval(() => { void this.refresh().catch(() => {}); }, every); this.timer.unref?.(); }
84
+ }
85
+ stop() { if (this.timer) clearInterval(this.timer); this.timer = undefined; this.listeners.clear(); }
86
+
87
+ async load() {
88
+ if (!this.file) return;
89
+ try {
90
+ this.snapshot = sanitize(JSON.parse(await readFile(this.file, 'utf8')));
91
+ await this.publish(false);
92
+ } catch { this.snapshot = { providers: {} }; /* no cache, or unreadable: static rows serve */ }
93
+ }
94
+
95
+ /** 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. */
96
+ refresh(runtimes: CatalogRuntime[] = RUNTIMES): Promise<CatalogSnapshot> {
97
+ if (this.running) return this.running;
98
+ this.running = (async () => {
99
+ const now = () => (this.options.now?.() ?? new Date()).toISOString();
100
+ const results = await Promise.all(runtimes.filter(runtime => this.options.probes[runtime]).map(async runtime => {
101
+ try { return [runtime, { status: 'ok', fetchedAt: now(), models: sanitizeModels(await bounded(this.options.probes[runtime]!, this.options.timeoutMs ?? PROBE_TIMEOUT_MS)) }] as const; }
102
+ catch (error) {
103
+ const prior = this.snapshot.providers[runtime];
104
+ return [runtime, { status: 'failed', fetchedAt: prior?.fetchedAt, error: error instanceof Error ? error.message : String(error), models: prior?.models ?? [] }] as const;
105
+ }
106
+ }));
107
+ for (const [runtime, state] of results) {
108
+ // An empty answer is no answer: keep what we had.
109
+ if (state.status === 'ok' && !state.models.length) { this.snapshot.providers[runtime] = { ...(this.snapshot.providers[runtime] ?? { models: [] }), status: 'failed', error: 'provider reported no models' }; continue; }
110
+ this.snapshot.providers[runtime] = state as ProviderState;
111
+ }
112
+ this.snapshot.fetchedAt = now();
113
+ await this.publish(true);
114
+ return this.snapshot;
115
+ })().finally(() => { this.running = undefined; });
116
+ return this.running;
117
+ }
118
+
119
+ /**
120
+ * A list a session reported on its own (each turn's orchestration context). Additive: it only adds
121
+ * models the catalog does not list yet, after the ones it has, so it never narrows or reshapes what a
122
+ * probe answered; a list with nothing new changes nothing.
123
+ */
124
+ async ingest(runtime: CatalogRuntime, models: LiveModel[]) {
125
+ const prior = this.snapshot.providers[runtime];
126
+ const known = new Set((prior?.models ?? []).map(model => model.id));
127
+ const added = sanitizeModels(models).filter(model => !known.has(model.id));
128
+ if (!added.length) return false;
129
+ this.snapshot.providers[runtime] = { ...(prior ?? { status: 'ok' }), status: prior?.status ?? 'ok', fetchedAt: prior?.fetchedAt ?? (this.options.now?.() ?? new Date()).toISOString(), models: [...(prior?.models ?? []), ...added] };
130
+ await this.publish(true);
131
+ return true;
132
+ }
133
+
134
+ private async publish(save: boolean) {
135
+ const next = mergeCatalog(staticRows(), Object.fromEntries(Object.entries(this.snapshot.providers).map(([runtime, state]) => [runtime, state?.models])));
136
+ const changed = JSON.stringify(next) !== JSON.stringify(this.current);
137
+ this.current = next;
138
+ 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 */ }
141
+ }
142
+ if (save) for (const listener of this.listeners) { try { listener(this.snapshot, next); } catch { /* a listener never stops the catalog */ } }
143
+ return changed;
144
+ }
145
+ }
146
+
147
+ /** Reads a session's orchestration context models (`runtime:id`, label, description, thinking) as live models. */
148
+ export function liveFromContext(context: any): { runtime: CatalogRuntime; models: LiveModel[] } | undefined {
149
+ if (!context?.catalogAvailable || !RUNTIMES.includes(context.runtime) || !Array.isArray(context.models)) return undefined;
150
+ if (context.catalogComplete === false) return undefined;
151
+ const prefix = `${context.runtime}:`;
152
+ const models = context.models.filter((model: any) => typeof model?.id === 'string' && model.id.startsWith(prefix)).map((model: any) => ({
153
+ id: model.id.slice(prefix.length), label: model.label, description: model.description,
154
+ 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,
155
+ }));
156
+ return { runtime: context.runtime, models };
157
+ }
158
+
159
+ let active: ModelCatalog | undefined;
160
+ /** The daemon's catalog, which sessions feed opportunistically. */
161
+ export function setActiveCatalog(catalog: ModelCatalog | undefined) { active = catalog; }
162
+ export function activeCatalog() { return active; }
163
+ export function feedCatalog(context: unknown) {
164
+ const live = liveFromContext(context);
165
+ if (live && active) void active.ingest(live.runtime, live.models).catch(() => {});
166
+ }
@@ -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): Probe {
46
+ return signal => new Promise((resolve, reject) => {
47
+ const child = spawn(command, ['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/resolve.ts CHANGED
@@ -12,6 +12,7 @@ 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
14
  import { capMode, profileFor } from '@anhlp/alp-core/permissions';
15
+ import { compactSettings } from './compact.js';
15
16
  import { userLanguage } from '@anhlp/alp-core/user-settings';
16
17
  import { claudeSandboxAvailable } from './claude-transport.js';
17
18
  import type { ResolvedAgent } from '@anhlp/alp-core/types';
@@ -163,12 +164,11 @@ export async function resolveSession(spec: SessionSpec, options: { templates?: R
163
164
  }
164
165
  }
165
166
  // Main has full access unless the caller limits it; a permission profile caps the mode at its base.
166
- // agy runs natively with full access; read-only instructions require an explicit opt-in.
167
+ // agy enforces each mode itself (antigravityModeArgs): it denies what the mode does not allow.
167
168
  const permissions = await profileFor(agent.projectRoot, options.library, agent.name);
168
169
  const requested = spec.mode ?? agent.mode ?? (agent.name === main ? 'full-access' : 'read-only');
169
170
  const mode = permissions ? capMode(requested, permissions.base) : requested;
170
171
  if (runtimeKind === 'antigravity') {
171
- if (mode !== 'full-access' && !(mode === 'read-only' && antigravity?.readOnlyMode === 'instructions')) throw new Error('Antigravity currently supports only full-access; read-only requires explicit readOnlyMode: "instructions" and is not sandboxed');
172
172
  if (spec.copy || permissions?.workdir === 'copy') throw new Error('Antigravity cannot enforce isolation for a review copy');
173
173
  if (permissions && (permissions.deny.length || permissions.ask.length || permissions.allow.length || permissions.beyondMode === 'ask')) {
174
174
  throw new Error('Antigravity cannot enforce custom permission rules');
@@ -224,6 +224,8 @@ export async function resolveSession(spec: SessionSpec, options: { templates?: R
224
224
  // ALPD §57: the window the agent works in before its runtime compacts; absent, the model's.
225
225
  ...(agent.context ? { context: agent.context } : {}),
226
226
  autocompact: typeof profile?.autocompact === 'number' ? profile.autocompact as number : typeof agent.autocompact === 'number' ? agent.autocompact : undefined,
227
+ // t-0e56: when main's context is compacted at a turn boundary.
228
+ compact: compactSettings(projectSettings.compact),
227
229
  // ALPD §54: the language everything the user reads is written in.
228
230
  language: options.language ?? await userLanguage(options.library),
229
231
  };