@anhlp/alp-runtime 0.0.0-stage → 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 (127) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +7 -0
  3. package/README.md +6 -2
  4. package/dist/acp-transport.d.ts +130 -0
  5. package/dist/acp-transport.js +482 -0
  6. package/dist/antigravity-transport.d.ts +107 -0
  7. package/dist/antigravity-transport.js +665 -0
  8. package/dist/assignment-results.d.ts +55 -0
  9. package/dist/assignment-results.js +181 -0
  10. package/dist/attachments.d.ts +84 -0
  11. package/dist/attachments.js +213 -0
  12. package/dist/board-domain.d.ts +56 -0
  13. package/dist/board-domain.js +157 -0
  14. package/dist/board.d.ts +27 -0
  15. package/dist/board.js +76 -0
  16. package/dist/catalog.d.ts +44 -0
  17. package/dist/catalog.js +47 -0
  18. package/dist/claude-transport.d.ts +251 -0
  19. package/dist/claude-transport.js +931 -0
  20. package/dist/compact.d.ts +29 -0
  21. package/dist/compact.js +49 -0
  22. package/dist/configure.d.ts +44 -0
  23. package/dist/configure.js +64 -0
  24. package/dist/contracts.d.ts +378 -0
  25. package/dist/contracts.js +16 -0
  26. package/dist/conversation.d.ts +45 -0
  27. package/dist/conversation.js +62 -0
  28. package/dist/events.d.ts +1 -0
  29. package/dist/events.js +0 -0
  30. package/dist/github.d.ts +10 -0
  31. package/dist/github.js +39 -0
  32. package/dist/handoff.d.ts +36 -0
  33. package/dist/handoff.js +73 -0
  34. package/dist/index.d.ts +39 -0
  35. package/dist/index.js +122 -0
  36. package/dist/input-limits.d.ts +25 -0
  37. package/dist/input-limits.js +48 -0
  38. package/dist/language.d.ts +51 -0
  39. package/dist/language.js +94 -0
  40. package/dist/live.d.ts +48 -0
  41. package/dist/live.js +50 -0
  42. package/dist/mailbox.d.ts +26 -0
  43. package/dist/mailbox.js +38 -0
  44. package/dist/mcp-tools.d.ts +123 -0
  45. package/dist/mcp-tools.js +97 -0
  46. package/dist/model-catalog.d.ts +162 -0
  47. package/dist/model-catalog.js +338 -0
  48. package/dist/model-probes.d.ts +7 -0
  49. package/dist/model-probes.js +69 -0
  50. package/dist/permission-path.d.ts +2 -0
  51. package/dist/permission-path.js +44 -0
  52. package/dist/process-info.d.ts +14 -0
  53. package/dist/process-info.js +32 -0
  54. package/dist/providers.d.ts +28 -0
  55. package/dist/providers.js +73 -0
  56. package/dist/recall.d.ts +42 -0
  57. package/dist/recall.js +61 -0
  58. package/dist/resolve.d.ts +123 -0
  59. package/dist/resolve.js +242 -0
  60. package/dist/runtime-context.d.ts +43 -0
  61. package/dist/runtime-context.js +61 -0
  62. package/dist/runtime.d.ts +13 -0
  63. package/dist/runtime.js +4818 -0
  64. package/dist/session-config.d.ts +2345 -0
  65. package/dist/session-config.js +209 -0
  66. package/dist/session-state.d.ts +190 -0
  67. package/dist/session-state.js +0 -0
  68. package/dist/skill-resources.d.ts +30 -0
  69. package/dist/skill-resources.js +55 -0
  70. package/dist/tool-detail.d.ts +81 -0
  71. package/dist/tool-detail.js +332 -0
  72. package/dist/tool-results.d.ts +12 -0
  73. package/dist/tool-results.js +25 -0
  74. package/dist/tools.d.ts +827 -0
  75. package/dist/tools.js +463 -0
  76. package/dist/transport.d.ts +47 -0
  77. package/dist/transport.js +171 -0
  78. package/dist/usage.d.ts +25 -0
  79. package/dist/usage.js +60 -0
  80. package/dist/workspace.d.ts +127 -0
  81. package/dist/workspace.js +340 -0
  82. package/dist/worktree-domain.d.ts +89 -0
  83. package/dist/worktree-domain.js +199 -0
  84. package/dist/write-error.d.ts +2 -0
  85. package/dist/write-error.js +10 -0
  86. package/package.json +262 -4
  87. package/src/acp-transport.ts +481 -0
  88. package/src/antigravity-transport.ts +740 -0
  89. package/src/assignment-results.ts +154 -0
  90. package/src/attachments.ts +254 -0
  91. package/src/board-domain.ts +185 -0
  92. package/src/board.ts +87 -0
  93. package/src/catalog.ts +43 -0
  94. package/src/claude-transport.ts +1097 -0
  95. package/src/compact.ts +62 -0
  96. package/src/configure.ts +93 -0
  97. package/src/contracts.ts +363 -0
  98. package/src/conversation.ts +81 -0
  99. package/src/events.ts +1 -0
  100. package/src/github.ts +37 -0
  101. package/src/handoff.ts +86 -0
  102. package/src/index.ts +41 -0
  103. package/src/input-limits.ts +65 -0
  104. package/src/language.ts +130 -0
  105. package/src/live.ts +90 -0
  106. package/src/mailbox.ts +49 -0
  107. package/src/mcp-tools.ts +106 -0
  108. package/src/model-catalog.ts +316 -0
  109. package/src/model-probes.ts +58 -0
  110. package/src/permission-path.ts +37 -0
  111. package/src/process-info.ts +40 -0
  112. package/src/providers.ts +87 -0
  113. package/src/recall.ts +86 -0
  114. package/src/resolve.ts +238 -0
  115. package/src/runtime-context.ts +49 -0
  116. package/src/runtime.ts +5608 -0
  117. package/src/session-config.ts +312 -0
  118. package/src/session-state.ts +180 -0
  119. package/src/skill-resources.ts +73 -0
  120. package/src/tool-detail.ts +397 -0
  121. package/src/tool-results.ts +26 -0
  122. package/src/tools.ts +466 -0
  123. package/src/transport.ts +118 -0
  124. package/src/usage.ts +79 -0
  125. package/src/workspace.ts +424 -0
  126. package/src/worktree-domain.ts +220 -0
  127. 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
+ };
@@ -0,0 +1,2 @@
1
+ /** ALP's permission gate, not an OS sandbox or protection against concurrent link swaps. */
2
+ export declare function writablePath(file: unknown, workdir: string): boolean;
@@ -0,0 +1,44 @@
1
+ // packages/runtime/src/permission-path.ts
2
+ import { lstatSync, realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+ import os from "node:os";
5
+ function canonical(file) {
6
+ const absolute = path.isAbsolute(file) ? file : `${process.cwd()}${path.sep}${file}`;
7
+ let current = path.parse(absolute).root;
8
+ for (const part of absolute.slice(current.length).split(process.platform === "win32" ? /[\\/]/ : /\//)) {
9
+ if (!part || part === ".") continue;
10
+ if (part === "..") {
11
+ current = path.dirname(current);
12
+ continue;
13
+ }
14
+ const candidate = path.join(current, part);
15
+ try {
16
+ current = realpathSync.native(candidate);
17
+ } catch (error) {
18
+ if (error?.code !== "ENOENT") throw error;
19
+ try {
20
+ if (lstatSync(candidate).isSymbolicLink()) throw new Error("Dangling symlink");
21
+ } catch (infoError) {
22
+ if (infoError?.code !== "ENOENT") throw infoError;
23
+ }
24
+ current = candidate;
25
+ }
26
+ }
27
+ return current;
28
+ }
29
+ var contains = (root, file) => {
30
+ const relative = path.relative(root, file);
31
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
32
+ };
33
+ function writablePath(file, workdir) {
34
+ if (typeof file !== "string" || !file.trim() || file.includes("\0")) return false;
35
+ try {
36
+ const target = canonical(path.isAbsolute(file) ? file : `${workdir}${path.sep}${file}`);
37
+ return contains(canonical(workdir), target) || contains(canonical(os.tmpdir()), target);
38
+ } catch {
39
+ return false;
40
+ }
41
+ }
42
+ export {
43
+ writablePath
44
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Telling a process from a later one that reuses its pid (ALPD §32): a pid alone
3
+ * can name an unrelated process once the first one is gone, so ALP also records
4
+ * when the process started, and compares that.
5
+ */
6
+ /** When this process started, in milliseconds since the epoch. */
7
+ export declare const OWN_START: number;
8
+ /** When process `pid` started, from ps (PowerShell on Windows); undefined where they cannot tell. */
9
+ export declare function processStartedAt(pid: number): number | undefined;
10
+ /**
11
+ * Whether the process that started at `startedAt` as `pid` still runs. Without a
12
+ * start time, or where ps cannot tell, a live pid counts as that process.
13
+ */
14
+ export declare function sameProcessAlive(pid: number, startedAt?: number): boolean;
@@ -0,0 +1,32 @@
1
+ // packages/runtime/src/process-info.ts
2
+ import { execFileSync } from "node:child_process";
3
+ var OWN_START = Math.round(Date.now() - process.uptime() * 1e3);
4
+ var START_TOLERANCE_MS = 2e3;
5
+ function processStartedAt(pid) {
6
+ try {
7
+ if (process.platform === "win32") {
8
+ const out = execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `[DateTimeOffset]::new((Get-Process -Id ${Math.trunc(pid)}).StartTime).ToUnixTimeMilliseconds()`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3, windowsHide: true }).trim();
9
+ return /^\d+$/.test(out) ? Number(out) : void 0;
10
+ }
11
+ const started = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3, env: { ...process.env, LC_ALL: "C" } }).trim();
12
+ const at = Date.parse(started);
13
+ return Number.isNaN(at) ? void 0 : at;
14
+ } catch {
15
+ return void 0;
16
+ }
17
+ }
18
+ function sameProcessAlive(pid, startedAt) {
19
+ try {
20
+ process.kill(pid, 0);
21
+ } catch (error) {
22
+ if (error?.code !== "EPERM") return false;
23
+ }
24
+ if (startedAt === void 0) return true;
25
+ const actual = processStartedAt(pid);
26
+ return actual === void 0 || Math.abs(actual - startedAt) < START_TOLERANCE_MS;
27
+ }
28
+ export {
29
+ OWN_START,
30
+ processStartedAt,
31
+ sameProcessAlive
32
+ };
@@ -0,0 +1,28 @@
1
+ import { type AcpProvider } from './acp-transport.js';
2
+ import { type AntigravityProvider } from './antigravity-transport.js';
3
+ import type { RuntimeKind } from './resolve.js';
4
+ import type { RuntimeOptions, RuntimeTransport } from './contracts.js';
5
+ /** The environment a native harness starts with: the host's, without variables that would tie it to the host's own agent session. */
6
+ export declare function nativeEnvironment(options: RuntimeOptions, extra?: Record<string, string>): NodeJS.ProcessEnv;
7
+ /** Provider factories adapt native harnesses to ALP's normalized transport contract. */
8
+ export type ProviderContext = {
9
+ options: RuntimeOptions;
10
+ runtime: RuntimeKind;
11
+ cwd: string;
12
+ environment: NodeJS.ProcessEnv;
13
+ acp?: AcpProvider;
14
+ antigravity?: AntigravityProvider;
15
+ };
16
+ export type ProviderFactory = (context: ProviderContext) => RuntimeTransport;
17
+ export type ProviderFactories = Partial<Record<RuntimeKind, ProviderFactory>>;
18
+ /** Explicit registry: each runtime instance can override adapters without global state. */
19
+ export declare class ProviderRegistry {
20
+ private readonly factories;
21
+ constructor(factories?: Record<string, ProviderFactory | undefined>);
22
+ register(id: string, factory: ProviderFactory): this;
23
+ create(id: string, context: ProviderContext): RuntimeTransport;
24
+ has(id: string): boolean;
25
+ list(): string[];
26
+ }
27
+ export declare function createProviderRegistry(overrides?: ProviderFactories): ProviderRegistry;
28
+ export declare function createTransport(options: RuntimeOptions, runtimeKind: RuntimeKind, cwd: string, environment: NodeJS.ProcessEnv, acp?: AcpProvider, antigravity?: AntigravityProvider): RuntimeTransport;
@@ -0,0 +1,73 @@
1
+ // packages/runtime/src/providers.ts
2
+ import { AGENT_MARKER } from "@anhlp/alp-core/tasks";
3
+ import { CodexTransport } from "./transport.js";
4
+ import { ClaudeTransport } from "./claude-transport.js";
5
+ import { AcpTransport } from "./acp-transport.js";
6
+ import { AntigravityTransport } from "./antigravity-transport.js";
7
+ function nativeEnvironment(options, extra = {}) {
8
+ const environment = { ...options.environment ?? process.env, ...extra };
9
+ for (const key of Object.keys(environment)) {
10
+ if (/^(PASEO_|CODEX_THREAD_ID$|CODEX_INTERNAL_|CODEX_PARENT_|CLAUDECODE$|CLAUDE_CODE_|ANTHROPIC_AGENT_)/.test(key)) delete environment[key];
11
+ }
12
+ environment[AGENT_MARKER] = "1";
13
+ return environment;
14
+ }
15
+ var ProviderRegistry = class {
16
+ factories = /* @__PURE__ */ new Map();
17
+ constructor(factories = {}) {
18
+ for (const [id, factory] of Object.entries(factories)) if (factory) this.register(id, factory);
19
+ }
20
+ register(id, factory) {
21
+ if (!id.trim()) throw new Error("A provider needs an id");
22
+ this.factories.set(id, factory);
23
+ return this;
24
+ }
25
+ create(id, context) {
26
+ const factory = this.factories.get(id);
27
+ if (!factory) throw new Error(`Unknown runtime provider: ${id}`);
28
+ return factory(context);
29
+ }
30
+ has(id) {
31
+ return this.factories.has(id);
32
+ }
33
+ list() {
34
+ return [...this.factories.keys()];
35
+ }
36
+ };
37
+ function createProviderRegistry(overrides = {}) {
38
+ return new ProviderRegistry({
39
+ codex: ({ options, cwd, environment }) => new CodexTransport(
40
+ options.codexCommand ?? process.env.ALP_CODEX_BIN ?? "codex",
41
+ cwd,
42
+ environment
43
+ ),
44
+ claude: ({ options, cwd, environment }) => new ClaudeTransport(
45
+ options.claudeCommand ?? process.env.ALP_CLAUDE_BIN ?? "claude",
46
+ cwd,
47
+ environment
48
+ ),
49
+ acp: ({ acp, cwd, environment }) => {
50
+ if (!acp) throw new Error("An ACP session needs its provider");
51
+ return new AcpTransport(acp, cwd, environment);
52
+ },
53
+ antigravity: ({ options, antigravity, cwd, environment }) => new AntigravityTransport(
54
+ options.antigravityCommand ?? process.env.ALP_ANTIGRAVITY_BIN ?? antigravity?.command ?? "agy",
55
+ cwd,
56
+ environment,
57
+ antigravity
58
+ ),
59
+ ...Object.fromEntries(Object.entries(overrides).filter(([, factory]) => factory !== void 0))
60
+ });
61
+ }
62
+ function createTransport(options, runtimeKind, cwd, environment, acp, antigravity) {
63
+ if (options.transport) return options.transport(cwd, environment, runtimeKind, acp, antigravity);
64
+ const registry = options.providerRegistry ?? createProviderRegistry(options.providers);
65
+ const providerId = runtimeKind === "acp" && acp && registry.has(`acp:${acp.id}`) ? `acp:${acp.id}` : runtimeKind;
66
+ return registry.create(providerId, { options, runtime: runtimeKind, cwd, environment, acp, antigravity });
67
+ }
68
+ export {
69
+ ProviderRegistry,
70
+ createProviderRegistry,
71
+ createTransport,
72
+ nativeEnvironment
73
+ };
@@ -0,0 +1,42 @@
1
+ import type { RuntimeKind } from './resolve.js';
2
+ /**
3
+ * Finished assignments whose native threads alp_recall can question (ALPD §27).
4
+ * The threads stay on disk for RECALL_KEEP_MS; then ALP deletes them.
5
+ */
6
+ export type RecallEntry = {
7
+ assignmentId: string;
8
+ rootId: string;
9
+ /** The requester and its requesters, nearest first: who may recall it besides a root of the project. */
10
+ requesters: string[];
11
+ agent: string;
12
+ project: string;
13
+ runtime: RuntimeKind;
14
+ threadId: string;
15
+ /** Where it worked: the project, or a worktree or copy that may be gone by now. */
16
+ cwd: string;
17
+ model: string;
18
+ thinking?: string;
19
+ taskId?: string;
20
+ status: string;
21
+ finishedAt: string;
22
+ /** Shared work remains in cwd; a new assignment can build on this brief and handoff. */
23
+ shared?: {
24
+ brief: string;
25
+ summary: string;
26
+ writeRoot?: string;
27
+ };
28
+ };
29
+ export declare const RECALL_KEEP_MS: number;
30
+ export declare const RECALL_MAX = 1000;
31
+ export declare const RECALL_QUESTION_CHARS = 4000;
32
+ export declare const RECALL_TIMEOUT_MS = 300000;
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
+ all(): Promise<RecallEntry[]>;
36
+ add(entry: RecallEntry): Promise<void>;
37
+ /** Removes and returns the entries past their time, and the oldest beyond RECALL_MAX. */
38
+ expire(now?: number): Promise<RecallEntry[]>;
39
+ flush: () => Promise<void>;
40
+ };
41
+ /** What a recalled assignment is told before the question. */
42
+ export declare function recallPrompt(asker: string, question: string): string;