@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
@@ -0,0 +1,338 @@
1
+ // packages/runtime/src/model-catalog.ts
2
+ import { mkdir, readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { MODELS, MODEL_POLICY, catalogCacheFile, mergeCatalog as mergeCatalogRows } from "@anhlp/alp-core/models";
5
+ import { writeAtomic } from "@anhlp/alp-core/atomic";
6
+ import { applyCatalog } from "./catalog.js";
7
+ var RUNTIMES = ["codex", "claude", "antigravity"];
8
+ var REFRESH_MS = 6 * 60 * 60 * 1e3;
9
+ var PROBE_TIMEOUT_MS = 15e3;
10
+ var POLICY = MODEL_POLICY;
11
+ var mergeCatalog = mergeCatalogRows;
12
+ var staticRows = () => MODELS.map((entry) => ({ ...entry, source: "static" }));
13
+ var bounded = (work, ms) => {
14
+ const controller = new AbortController();
15
+ let timer;
16
+ return Promise.race([
17
+ work(controller.signal),
18
+ new Promise((_, reject) => {
19
+ timer = setTimeout(() => {
20
+ controller.abort();
21
+ reject(new Error(`timed out after ${ms} ms`));
22
+ }, ms);
23
+ })
24
+ ]).finally(() => clearTimeout(timer));
25
+ };
26
+ var strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : void 0;
27
+ function sanitizeModels(value) {
28
+ if (!Array.isArray(value)) return [];
29
+ return value.filter((model) => model && typeof model === "object" && typeof model.id === "string" && model.id.trim()).map((model) => ({
30
+ id: model.id,
31
+ ...typeof model.label === "string" ? { label: model.label } : {},
32
+ ...typeof model.description === "string" ? { description: model.description } : {},
33
+ ...strings(model.efforts) ? { efforts: strings(model.efforts) } : {},
34
+ ...typeof model.effort === "string" ? { effort: model.effort } : {}
35
+ }));
36
+ }
37
+ function sanitize(value) {
38
+ const providers = {};
39
+ for (const runtime of RUNTIMES) {
40
+ const state = value?.providers?.[runtime];
41
+ if (!state || typeof state !== "object") continue;
42
+ providers[runtime] = { status: state.status === "ok" ? "ok" : "failed", ...typeof state.fetchedAt === "string" ? { fetchedAt: state.fetchedAt } : {}, models: sanitizeModels(state.models) };
43
+ }
44
+ const acp = {};
45
+ if (value?.acp && typeof value.acp === "object") for (const [id, state] of Object.entries(value.acp)) {
46
+ if (!/^[\w.-]+$/.test(id) || !state || typeof state !== "object") continue;
47
+ 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) };
48
+ }
49
+ return { ...typeof value?.fetchedAt === "string" ? { fetchedAt: value.fetchedAt } : {}, providers, ...Object.keys(acp).length ? { acp } : {} };
50
+ }
51
+ function acpSessionModels(result) {
52
+ const config = Array.isArray(result?.configOptions) ? result.configOptions.find((option) => option?.category === "model" && option?.type === "select") : void 0;
53
+ const listed = Array.isArray(result?.models?.availableModels) ? result.models.availableModels : config ? (config.options ?? []).flatMap((option) => option?.options ?? [option]).map((option) => ({ modelId: option?.value, name: option?.name, description: option?.description })) : [];
54
+ return sanitizeModels(listed.map((model) => ({ id: model?.modelId ?? model?.id, ...typeof model?.name === "string" && model.name ? { label: model.name } : {}, ...typeof model?.description === "string" && model.description ? { description: model.description } : {} })));
55
+ }
56
+ var ModelCatalog = class {
57
+ /**
58
+ * ACP providers (t-d0b0) come from `acpProviders` (the library's providers/<id>.json) without starting
59
+ * them; their models are learned from sessions (learnAcp) and probed (acpProbe) only by refreshAcp,
60
+ * which alpd calls on catalog.refresh and when the user enables a provider. Never at start or on the timer.
61
+ */
62
+ constructor(options) {
63
+ this.options = options;
64
+ this.file = options.home ? catalogCacheFile(options.home) : void 0;
65
+ }
66
+ snapshot = { providers: {} };
67
+ current = staticRows();
68
+ listeners = /* @__PURE__ */ new Set();
69
+ timer;
70
+ running;
71
+ file;
72
+ acpConfigs = [];
73
+ acpRunning;
74
+ acpError;
75
+ acpLearning = /* @__PURE__ */ new Map();
76
+ /** Cache writes under way: stop() waits for them, so whoever stopped the catalog may remove its home. */
77
+ writes = /* @__PURE__ */ new Set();
78
+ /** Set once stop() has drained: a late answer (a session's models, an ingest) still updates memory but writes nothing. */
79
+ stopped = false;
80
+ entries() {
81
+ return this.current;
82
+ }
83
+ state() {
84
+ return this.snapshot;
85
+ }
86
+ onUpdated(listener) {
87
+ this.listeners.add(listener);
88
+ return () => this.listeners.delete(listener);
89
+ }
90
+ /** Loads the cache, then refreshes in the background and every refreshMs. Never blocks on a provider. */
91
+ async start() {
92
+ this.stopped = false;
93
+ await this.load();
94
+ await this.loadAcp().catch(() => {
95
+ });
96
+ void this.refresh().catch(() => {
97
+ });
98
+ const every = this.options.refreshMs ?? REFRESH_MS;
99
+ if (every > 0) {
100
+ this.timer = setInterval(() => {
101
+ void this.refresh().catch(() => {
102
+ });
103
+ }, every);
104
+ this.timer.unref?.();
105
+ }
106
+ }
107
+ /**
108
+ * Stops the timer and the listeners, then waits for what already started (a background refresh, a
109
+ * refreshAcp a saved provider asked for, a learned model's cache write) to finish writing the cache
110
+ * (t-5294.2). After that it writes the cache no more, until start() again. A caller that only stops may
111
+ * ignore the promise; one that removes the home awaits it.
112
+ */
113
+ async stop() {
114
+ if (this.timer) clearInterval(this.timer);
115
+ this.timer = void 0;
116
+ this.listeners.clear();
117
+ while (this.running || this.acpRunning || this.writes.size) await Promise.allSettled([this.running, this.acpRunning, ...this.writes]);
118
+ this.stopped = true;
119
+ }
120
+ async load() {
121
+ if (!this.file) return;
122
+ try {
123
+ this.snapshot = sanitize(JSON.parse(await readFile(this.file, "utf8")));
124
+ await this.publish(false);
125
+ } catch {
126
+ this.snapshot = { providers: {} };
127
+ }
128
+ }
129
+ /** 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. */
130
+ refresh(runtimes = RUNTIMES) {
131
+ if (this.running) return this.running;
132
+ this.running = (async () => {
133
+ const now = () => (this.options.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
134
+ const results = await Promise.all(runtimes.filter((runtime) => this.options.probes[runtime]).map(async (runtime) => {
135
+ try {
136
+ return [runtime, { status: "ok", fetchedAt: now(), models: sanitizeModels(await bounded(this.options.probes[runtime], this.options.timeoutMs ?? PROBE_TIMEOUT_MS)) }];
137
+ } catch (error) {
138
+ const prior = this.snapshot.providers[runtime];
139
+ return [runtime, { status: "failed", fetchedAt: prior?.fetchedAt, error: error instanceof Error ? error.message : String(error), models: prior?.models ?? [] }];
140
+ }
141
+ }));
142
+ for (const [runtime, state] of results) {
143
+ if (state.status === "ok" && !state.models.length) {
144
+ this.snapshot.providers[runtime] = { ...this.snapshot.providers[runtime] ?? { models: [] }, status: "failed", error: "provider reported no models" };
145
+ continue;
146
+ }
147
+ this.snapshot.providers[runtime] = state;
148
+ }
149
+ this.snapshot.fetchedAt = now();
150
+ await this.publish(true);
151
+ return this.snapshot;
152
+ })().finally(() => {
153
+ this.running = void 0;
154
+ });
155
+ return this.running;
156
+ }
157
+ /**
158
+ * A list a session reported on its own (each turn's orchestration context). Additive: it only adds
159
+ * models the catalog does not list yet, after the ones it has, so it never narrows or reshapes what a
160
+ * probe answered; a list with nothing new changes nothing.
161
+ */
162
+ async ingest(runtime, models) {
163
+ const prior = this.snapshot.providers[runtime];
164
+ const known = new Set((prior?.models ?? []).map((model) => model.id));
165
+ const added = sanitizeModels(models).filter((model) => !known.has(model.id));
166
+ if (!added.length) return false;
167
+ this.snapshot.providers[runtime] = { ...prior ?? { status: "ok" }, status: prior?.status ?? "ok", fetchedAt: prior?.fetchedAt ?? (this.options.now?.() ?? /* @__PURE__ */ new Date()).toISOString(), models: [...prior?.models ?? [], ...added] };
168
+ await this.publish(true);
169
+ return true;
170
+ }
171
+ /** Rereads the ACP providers' files; starts none of them. */
172
+ async loadAcp() {
173
+ if (!this.options.acpProviders) return;
174
+ try {
175
+ const loaded = await this.options.acpProviders();
176
+ this.acpConfigs = (Array.isArray(loaded) ? loaded : loaded.providers).filter((provider) => provider.kind !== "antigravity");
177
+ this.acpError = Array.isArray(loaded) ? void 0 : loaded.error;
178
+ } catch (error) {
179
+ this.acpError = error instanceof Error ? error.message : String(error);
180
+ }
181
+ }
182
+ /** Why the last reading of the ACP providers failed, if it did. */
183
+ acpLoadError() {
184
+ return this.acpError;
185
+ }
186
+ /** The ACP rows: each provider's default, then its models (the file's `models` replace learned ones; `additionalModels` add). */
187
+ acpRows() {
188
+ const rows = [];
189
+ for (const provider of this.acpConfigs) {
190
+ const state = this.snapshot.acp?.[provider.id];
191
+ const status = state?.status ?? "unprobed";
192
+ const enabled = provider.enabled !== false;
193
+ const label = provider.label ?? provider.id;
194
+ const row = (id, text, description, source) => ({ runtime: "acp", provider: provider.id, id, label: text, description, efforts: [], source, enabled, status });
195
+ rows.push(row(provider.id, `${label} \xB7 agent default`, provider.description ?? "", "configured"));
196
+ const seen = /* @__PURE__ */ new Set();
197
+ const add = (models, source) => {
198
+ for (const model of models) if (!seen.has(model.id)) {
199
+ seen.add(model.id);
200
+ rows.push(row(`${provider.id}/${model.id}`, `${label} \xB7 ${model.label ?? model.id}`, model.description ?? "", source));
201
+ }
202
+ };
203
+ add(provider.models ?? state?.models ?? [], provider.models ? "configured" : "live");
204
+ add(provider.additionalModels ?? [], "configured");
205
+ }
206
+ return rows;
207
+ }
208
+ /** The models ALP learned or probed for one ACP provider. */
209
+ acpModels(provider) {
210
+ return this.snapshot.acp?.[provider]?.models ?? [];
211
+ }
212
+ /**
213
+ * A list an ACP session's `session/new` reported (t-d0b0). Additive, as ingest: it never removes a model
214
+ * a probe answered; a list with nothing new changes nothing.
215
+ */
216
+ async learnAcp(provider, models) {
217
+ if (!/^[\w.-]+$/.test(provider)) return false;
218
+ const reported = sanitizeModels(models);
219
+ for (const model of reported) this.acpLearning.get(provider)?.add(model.id);
220
+ const prior = this.snapshot.acp?.[provider];
221
+ const known = new Set((prior?.models ?? []).map((model) => model.id));
222
+ const added = reported.filter((model) => !known.has(model.id));
223
+ if (!added.length) return false;
224
+ this.snapshot.acp = { ...this.snapshot.acp, [provider]: { status: "ok", fetchedAt: (this.options.now?.() ?? /* @__PURE__ */ new Date()).toISOString(), models: [...prior?.models ?? [], ...added] } };
225
+ await this.publish(true);
226
+ return true;
227
+ }
228
+ /**
229
+ * Starts each enabled ACP provider (or the named ones) once to read its models: only on an explicit
230
+ * catalog.refresh or when the user enables a provider. A failure keeps what ALP knew and records why.
231
+ */
232
+ refreshAcp(ids) {
233
+ if (this.acpRunning) return this.acpRunning.then(() => this.refreshAcp(ids));
234
+ this.acpRunning = (async () => {
235
+ await this.loadAcp();
236
+ const probe = this.options.acpProbe;
237
+ const targets = this.acpConfigs.filter((provider) => provider.enabled !== false && (!ids || ids.includes(provider.id)));
238
+ if (!probe || !targets.length) return this.snapshot;
239
+ const now = () => (this.options.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
240
+ await Promise.all(targets.map(async (provider) => {
241
+ const learned = /* @__PURE__ */ new Set();
242
+ this.acpLearning.set(provider.id, learned);
243
+ let outcome;
244
+ try {
245
+ outcome = { ok: true, models: sanitizeModels(await bounded((signal) => probe(provider, signal), this.options.timeoutMs ?? PROBE_TIMEOUT_MS)) };
246
+ } catch (error) {
247
+ outcome = { ok: false, error: error instanceof Error ? error.message : String(error) };
248
+ }
249
+ this.acpLearning.delete(provider.id);
250
+ const current = this.snapshot.acp?.[provider.id];
251
+ const known = current?.models ?? [];
252
+ let next;
253
+ if (outcome.ok) {
254
+ const ids2 = new Set(outcome.models.map((model) => model.id));
255
+ next = { status: "ok", fetchedAt: now(), models: [...outcome.models, ...known.filter((model) => learned.has(model.id) && !ids2.has(model.id))] };
256
+ } else next = { status: "failed", ...current?.fetchedAt ? { fetchedAt: current.fetchedAt } : {}, error: outcome.error, models: known };
257
+ this.snapshot.acp = { ...this.snapshot.acp, [provider.id]: next };
258
+ }));
259
+ await this.publish(true);
260
+ return this.snapshot;
261
+ })().finally(() => {
262
+ this.acpRunning = void 0;
263
+ });
264
+ return this.acpRunning;
265
+ }
266
+ async publish(save) {
267
+ const next = mergeCatalog(staticRows(), Object.fromEntries(Object.entries(this.snapshot.providers).map(([runtime, state]) => [runtime, state?.models])));
268
+ const changed = JSON.stringify(next) !== JSON.stringify(this.current);
269
+ this.current = next;
270
+ if (this.options.apply !== false) applyCatalog(next);
271
+ if (save && this.file && !this.stopped) {
272
+ const file = this.file;
273
+ const write = (async () => {
274
+ try {
275
+ await mkdir(path.dirname(file), { recursive: true });
276
+ await writeAtomic(file, JSON.stringify(this.snapshot, null, 2));
277
+ } catch {
278
+ }
279
+ })();
280
+ this.writes.add(write);
281
+ try {
282
+ await write;
283
+ } finally {
284
+ this.writes.delete(write);
285
+ }
286
+ }
287
+ if (save) for (const listener of this.listeners) {
288
+ try {
289
+ listener(this.snapshot, next);
290
+ } catch {
291
+ }
292
+ }
293
+ return changed;
294
+ }
295
+ };
296
+ function liveFromContext(context) {
297
+ if (!context?.catalogAvailable || !RUNTIMES.includes(context.runtime) || !Array.isArray(context.models)) return void 0;
298
+ if (context.catalogComplete === false) return void 0;
299
+ const prefix = `${context.runtime}:`;
300
+ const models = context.models.filter((model) => typeof model?.id === "string" && model.id.startsWith(prefix)).map((model) => ({
301
+ id: model.id.slice(prefix.length),
302
+ label: model.label,
303
+ description: model.description,
304
+ efforts: Array.isArray(model.thinking) ? model.thinking.map((effort) => typeof effort === "string" ? effort : effort?.reasoningEffort ?? effort?.id).filter((effort) => typeof effort === "string") : void 0
305
+ }));
306
+ return { runtime: context.runtime, models };
307
+ }
308
+ var active;
309
+ function setActiveCatalog(catalog) {
310
+ active = catalog;
311
+ }
312
+ function activeCatalog() {
313
+ return active;
314
+ }
315
+ function feedCatalog(context) {
316
+ const live = liveFromContext(context);
317
+ if (live && active) void active.ingest(live.runtime, live.models).catch(() => {
318
+ });
319
+ }
320
+ function feedAcpSession(provider, result) {
321
+ const models = acpSessionModels(result);
322
+ if (models.length && active) void active.learnAcp(provider, models).catch(() => {
323
+ });
324
+ }
325
+ export {
326
+ ModelCatalog,
327
+ POLICY,
328
+ PROBE_TIMEOUT_MS,
329
+ REFRESH_MS,
330
+ acpSessionModels,
331
+ activeCatalog,
332
+ feedAcpSession,
333
+ feedCatalog,
334
+ liveFromContext,
335
+ mergeCatalog,
336
+ sanitizeModels,
337
+ setActiveCatalog
338
+ };
@@ -0,0 +1,7 @@
1
+ import type { CatalogRuntime, LiveModel, Probe } from './model-catalog.js';
2
+ export declare function codexProbe(command?: string, env?: NodeJS.ProcessEnv): Probe;
3
+ export declare function claudeProbe(command?: string, env?: NodeJS.ProcessEnv): Probe;
4
+ /** `agy models` prints one model per line, `id<TAB>label`. */
5
+ export declare function parseAgyModels(stdout: string): LiveModel[];
6
+ export declare function antigravityProbe(command?: string, env?: NodeJS.ProcessEnv, args?: string[]): Probe;
7
+ export declare function liveProbes(env?: NodeJS.ProcessEnv): Record<CatalogRuntime, Probe>;
@@ -0,0 +1,69 @@
1
+ // packages/runtime/src/model-probes.ts
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
+ function codexProbe(command = process.env.ALP_CODEX_BIN ?? "codex", env = process.env) {
7
+ return async (signal) => {
8
+ const transport = new CodexTransport(command, os.tmpdir(), env);
9
+ const stop = () => {
10
+ void transport.close();
11
+ };
12
+ signal.addEventListener("abort", stop);
13
+ try {
14
+ await transport.initialize();
15
+ const models = [];
16
+ let cursor;
17
+ for (let page = 0; page < 10; page++) {
18
+ const result = await transport.request("model/list", { limit: 100, includeHidden: false, ...cursor ? { cursor } : {} }, 1e4, false);
19
+ for (const model of result?.data ?? []) {
20
+ if (typeof model?.model !== "string" || model.hidden) continue;
21
+ models.push({
22
+ id: model.model,
23
+ label: model.displayName,
24
+ description: model.description,
25
+ efforts: (model.supportedReasoningEfforts ?? []).map((effort) => typeof effort === "string" ? effort : effort?.reasoningEffort).filter((effort) => typeof effort === "string"),
26
+ effort: model.defaultReasoningEffort
27
+ });
28
+ }
29
+ cursor = result?.nextCursor ?? void 0;
30
+ if (!cursor) break;
31
+ }
32
+ return models;
33
+ } finally {
34
+ signal.removeEventListener("abort", stop);
35
+ await transport.close();
36
+ }
37
+ };
38
+ }
39
+ function claudeProbe(command = process.env.ALP_CLAUDE_BIN ?? "claude", env = process.env) {
40
+ return async (signal) => new ClaudeTransport(command, os.tmpdir(), env).probeModels(signal);
41
+ }
42
+ function parseAgyModels(stdout) {
43
+ return stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => {
44
+ const [id, label] = line.split(" ").map((part) => part.trim());
45
+ return { id, label: label || id };
46
+ }).filter((model) => model.id && /^[A-Za-z0-9][\w.:\-\[\]/]*$/.test(model.id));
47
+ }
48
+ function antigravityProbe(command = process.env.ALP_ANTIGRAVITY_BIN ?? "agy", env = process.env, args = []) {
49
+ return (signal) => new Promise((resolve, reject) => {
50
+ const child = spawn(command, [...args, "models"], { cwd: os.tmpdir(), env, stdio: ["ignore", "pipe", "ignore"], windowsHide: true, signal });
51
+ let stdout = "";
52
+ child.stdout.on("data", (chunk) => {
53
+ stdout += chunk;
54
+ if (stdout.length > 256 * 1024) child.kill("SIGKILL");
55
+ });
56
+ child.on("error", reject);
57
+ child.on("close", (code) => code === 0 ? resolve(parseAgyModels(stdout)) : reject(new Error(`${command} models exited with ${code}`)));
58
+ });
59
+ }
60
+ function liveProbes(env = process.env) {
61
+ return { codex: codexProbe(void 0, env), claude: claudeProbe(void 0, env), antigravity: antigravityProbe(void 0, env) };
62
+ }
63
+ export {
64
+ antigravityProbe,
65
+ claudeProbe,
66
+ codexProbe,
67
+ liveProbes,
68
+ parseAgyModels
69
+ };
package/dist/providers.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // packages/runtime/src/providers.ts
2
+ import { AGENT_MARKER } from "@anhlp/alp-core/tasks";
2
3
  import { CodexTransport } from "./transport.js";
3
4
  import { ClaudeTransport } from "./claude-transport.js";
4
5
  import { AcpTransport } from "./acp-transport.js";
@@ -8,6 +9,7 @@ function nativeEnvironment(options, extra = {}) {
8
9
  for (const key of Object.keys(environment)) {
9
10
  if (/^(PASEO_|CODEX_THREAD_ID$|CODEX_INTERNAL_|CODEX_PARENT_|CLAUDECODE$|CLAUDE_CODE_|ANTHROPIC_AGENT_)/.test(key)) delete environment[key];
10
11
  }
12
+ environment[AGENT_MARKER] = "1";
11
13
  return environment;
12
14
  }
13
15
  var ProviderRegistry = class {
package/dist/recall.d.ts CHANGED
@@ -30,8 +30,8 @@ export declare const RECALL_KEEP_MS: number;
30
30
  export declare const RECALL_MAX = 1000;
31
31
  export declare const RECALL_QUESTION_CHARS = 4000;
32
32
  export declare const RECALL_TIMEOUT_MS = 300000;
33
- /** The record of recallable threads, kept in `file` when given, else in memory. */
34
- export declare function createRecallBook(file?: string): {
33
+ /** The record of recallable threads, kept in `file` when given, else in memory; `onError` hears of each failed write. */
34
+ export declare function createRecallBook(file?: string, onError?: (error: unknown) => void): {
35
35
  all(): Promise<RecallEntry[]>;
36
36
  add(entry: RecallEntry): Promise<void>;
37
37
  /** Removes and returns the entries past their time, and the oldest beyond RECALL_MAX. */
package/dist/recall.js CHANGED
@@ -2,12 +2,14 @@
2
2
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
3
  import { randomBytes } from "node:crypto";
4
4
  import path from "node:path";
5
+ import { tell } from "./write-error.js";
5
6
  var RECALL_KEEP_MS = 14 * 24 * 60 * 60 * 1e3;
6
7
  var RECALL_MAX = 1e3;
7
8
  var RECALL_QUESTION_CHARS = 4e3;
8
9
  var RECALL_TIMEOUT_MS = 3e5;
9
10
  var valid = (entry) => !!entry && typeof entry === "object" && ["assignmentId", "rootId", "agent", "project", "runtime", "threadId", "cwd", "model", "status", "finishedAt"].every((key) => typeof entry[key] === "string") && Array.isArray(entry.requesters);
10
- function createRecallBook(file) {
11
+ function createRecallBook(file, onError = () => {
12
+ }) {
11
13
  let entries;
12
14
  let writes = Promise.resolve();
13
15
  const load = () => entries ??= file ? readFile(file, "utf8").then((text) => JSON.parse(text).filter(valid), () => []) : Promise.resolve([]);
@@ -19,8 +21,7 @@ function createRecallBook(file) {
19
21
  const temporary = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
20
22
  await writeFile(temporary, body, { mode: 384 });
21
23
  await rename(temporary, file);
22
- }).catch(() => {
23
- });
24
+ }).catch((error) => tell(onError, error));
24
25
  return writes;
25
26
  };
26
27
  return {
package/dist/resolve.d.ts CHANGED
@@ -52,7 +52,9 @@ export declare function resolveSession(spec: SessionSpec, options?: {
52
52
  language?: string; /** False for a preview: it writes nothing (D31). */
53
53
  initialize?: boolean;
54
54
  }): Promise<{
55
+ commands: string[];
55
56
  autocompact: number | undefined;
57
+ compact: import("./compact.js").CompactSettings;
56
58
  language: string;
57
59
  context?: number | undefined;
58
60
  instructions: string;
package/dist/resolve.js CHANGED
@@ -10,7 +10,8 @@ import { loadHooks } from "@anhlp/alp-core/hooks";
10
10
  import { acpModel, loadProvider } from "@anhlp/alp-core/providers";
11
11
  import { ensureLibrary } from "@anhlp/alp-core/library";
12
12
  import { compileAgent } from "@anhlp/alp-core/adapter";
13
- import { capMode, profileFor } from "@anhlp/alp-core/permissions";
13
+ import { capMode, profileFor, READ_ONLY_ROLES } from "@anhlp/alp-core/permissions";
14
+ import { compactSettings } from "./compact.js";
14
15
  import { userLanguage } from "@anhlp/alp-core/user-settings";
15
16
  import { claudeSandboxAvailable } from "./claude-transport.js";
16
17
  import { DEFAULT_ANTIGRAVITY_MODEL, DEFAULT_CLAUDE_MODEL, DEFAULT_MODEL, ORACLE_MODELS, ORACLE_THINKING, models, modes, thinkingOptions, thinkingOptionsFor } from "./catalog.js";
@@ -42,7 +43,7 @@ var InstructionsAdapter = class {
42
43
  const description = await skillDescription(skill.path);
43
44
  return `- ${skill.name} (${skill.path})${description ? `: ${description}` : ""}`;
44
45
  }));
45
- const skills = listed.length ? "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") : "";
46
+ const skills = listed.length ? "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") : "";
46
47
  return { adapterId: this.id, agentName: agent.name, projectRoot: agent.projectRoot, material: {
47
48
  instructions: [agent.instructions.project, agent.instructions.agent, skills].filter(Boolean).join("\n\n"),
48
49
  mcp: agent.mcp,
@@ -152,18 +153,17 @@ async function resolveSession(spec, options = {}) {
152
153
  if (antigravity.enabled === false) throw new Error("Antigravity provider 'antigravity' is turned off; turn it on in the web app's Providers settings or in providers/antigravity.json");
153
154
  }
154
155
  }
155
- const permissions = await profileFor(agent.projectRoot, options.library, agent.name);
156
+ const permissions = await profileFor(agent.projectRoot, options.library, agent.name, { readOnly: READ_ONLY_ROLES.includes(team?.members[agent.name]?.role ?? "") });
156
157
  const requested = spec.mode ?? agent.mode ?? (agent.name === main ? "full-access" : "read-only");
157
158
  const mode = permissions ? capMode(requested, permissions.base) : requested;
158
159
  if (runtimeKind === "antigravity") {
159
- 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');
160
160
  if (spec.copy || permissions?.workdir === "copy") throw new Error("Antigravity cannot enforce isolation for a review copy");
161
161
  if (permissions && (permissions.deny.length || permissions.ask.length || permissions.allow.length || permissions.beyondMode === "ask")) {
162
162
  throw new Error("Antigravity cannot enforce custom permission rules");
163
163
  }
164
164
  }
165
165
  const availableThinking = ["acp", "antigravity"].includes(runtimeKind) ? [] : thinkingOptionsFor(runtimeKind, model);
166
- const preferred = ["acp", "antigravity"].includes(runtimeKind) ? "none" : spec.thinking ?? profileChoice?.effort ?? agent.projectRuntime?.reasoning ?? (agent.name === "oracle" ? team?.oracleThinking?.[`${runtimeKind}:${model}`] ?? team?.oracleThinking?.[runtimeKind] : void 0) ?? teamChoice?.thinking ?? agent.runtime.reasoning ?? (agent.name === "oracle" ? ORACLE_THINKING : availableThinking.length ? "medium" : "none");
166
+ const preferred = runtimeKind === "acp" ? "none" : runtimeKind === "antigravity" ? spec.thinking ?? profileChoice?.effort ?? (agent.name === "oracle" ? team?.oracleThinking?.[`${runtimeKind}:${model}`] ?? team?.oracleThinking?.[runtimeKind] : void 0) ?? teamChoice?.thinking ?? "none" : spec.thinking ?? profileChoice?.effort ?? agent.projectRuntime?.reasoning ?? (agent.name === "oracle" ? team?.oracleThinking?.[`${runtimeKind}:${model}`] ?? team?.oracleThinking?.[runtimeKind] : void 0) ?? teamChoice?.thinking ?? agent.runtime.reasoning ?? (agent.name === "oracle" ? ORACLE_THINKING : availableThinking.length ? "medium" : "none");
167
167
  const thinking = spec.thinking === void 0 && availableThinking.length && !availableThinking.some((candidate) => candidate.id === preferred) ? models.find((candidate) => candidate.id === `${runtimeKind}:${model}`)?.defaultThinkingOptionId ?? availableThinking[0].id : preferred;
168
168
  if (!model.trim()) throw new Error("Model must be nonempty");
169
169
  if (!modes.some((m) => m.id === mode)) throw new Error(`Unsupported mode '${mode}'`);
@@ -224,7 +224,11 @@ ${project}` : "");
224
224
  keepThread: spec.keepThread ?? false,
225
225
  // ALPD §57: the window the agent works in before its runtime compacts; absent, the model's.
226
226
  ...agent.context ? { context: agent.context } : {},
227
+ // t-efa3: the runtime's own commands and skills the "/" list offers; its ALP skills always.
228
+ commands: Array.isArray(profile?.commands) ? profile.commands.filter((name) => typeof name === "string") : [],
227
229
  autocompact: typeof profile?.autocompact === "number" ? profile.autocompact : typeof agent.autocompact === "number" ? agent.autocompact : void 0,
230
+ // t-0e56: when main's context is compacted at a turn boundary.
231
+ compact: compactSettings(projectSettings.compact),
228
232
  // ALPD §54: the language everything the user reads is written in.
229
233
  language: options.language ?? await userLanguage(options.library)
230
234
  };
@@ -37,7 +37,7 @@ export declare function claudeUsage(result: any): {
37
37
  };
38
38
  /**
39
39
  * Whether a runtime's usage report (codexUsage or claudeUsage) lets it work again (ALPD §58):
40
- * true when every window has room, false when one is used up or spending is capped, and
40
+ * true when every window has room, false on explicit provider denial, a used-up window or spending cap, and
41
41
  * undefined when the report says nothing either way.
42
42
  */
43
43
  export declare function usageAllows(usage: any): boolean | undefined;
@@ -46,7 +46,7 @@ function claudeUsage(result) {
46
46
  function usageAllows(usage) {
47
47
  if (!usage?.available) return void 0;
48
48
  const limits = Array.isArray(usage.limits) ? usage.limits : [];
49
- if (limits.some((limit) => limit?.spendControlReached === true)) return false;
49
+ if (usage.ordinaryUsageAllowed === false || limits.some((limit) => limit?.spendControlReached === true)) return false;
50
50
  const windows = limits.length ? limits.flatMap((limit) => limit?.windows ?? []) : usage.windows ?? [];
51
51
  const known = windows.filter((window) => typeof window?.usedPercent === "number");
52
52
  if (!known.length) return void 0;
package/dist/runtime.d.ts CHANGED
@@ -1,4 +1,13 @@
1
1
  import { type RuntimeOptions, type AlpRuntime } from './contracts.js';
2
2
  export type { RuntimeTransport, RuntimeOptions, OpenOptions, PromptContent, PromptInput, AlpRuntime, SessionPreview, RecoveryOutcome, Pause, PauseState, RecallAnswer } from './contracts.js';
3
3
  export { DEFAULT_TEAM } from './contracts.js';
4
+ /** The monthly curate job's prompt starts with this marker, so main and ALP recognize it. */
5
+ export declare const CURATE_MARKER = "[alp-curate]";
6
+ export type WorkspaceMutationReason = 'workspace_busy' | 'workspace_claimed' | 'workspace_leased' | 'workspace_assignment_result' | 'workspace_identity';
7
+ export declare class WorkspaceMutationError extends Error {
8
+ readonly data: {
9
+ reason: WorkspaceMutationReason;
10
+ };
11
+ constructor(reason: WorkspaceMutationReason, message: string);
12
+ }
4
13
  export declare function createAlpRuntime(options?: RuntimeOptions): AlpRuntime;