@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.
- package/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +6 -2
- package/dist/acp-transport.d.ts +130 -0
- package/dist/acp-transport.js +482 -0
- package/dist/antigravity-transport.d.ts +107 -0
- package/dist/antigravity-transport.js +665 -0
- package/dist/assignment-results.d.ts +55 -0
- package/dist/assignment-results.js +181 -0
- package/dist/attachments.d.ts +84 -0
- package/dist/attachments.js +213 -0
- package/dist/board-domain.d.ts +56 -0
- package/dist/board-domain.js +157 -0
- package/dist/board.d.ts +27 -0
- package/dist/board.js +76 -0
- package/dist/catalog.d.ts +44 -0
- package/dist/catalog.js +47 -0
- package/dist/claude-transport.d.ts +251 -0
- package/dist/claude-transport.js +931 -0
- package/dist/compact.d.ts +29 -0
- package/dist/compact.js +49 -0
- package/dist/configure.d.ts +44 -0
- package/dist/configure.js +64 -0
- package/dist/contracts.d.ts +378 -0
- package/dist/contracts.js +16 -0
- package/dist/conversation.d.ts +45 -0
- package/dist/conversation.js +62 -0
- package/dist/events.d.ts +1 -0
- package/dist/events.js +0 -0
- package/dist/github.d.ts +10 -0
- package/dist/github.js +39 -0
- package/dist/handoff.d.ts +36 -0
- package/dist/handoff.js +73 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.js +122 -0
- package/dist/input-limits.d.ts +25 -0
- package/dist/input-limits.js +48 -0
- package/dist/language.d.ts +51 -0
- package/dist/language.js +94 -0
- package/dist/live.d.ts +48 -0
- package/dist/live.js +50 -0
- package/dist/mailbox.d.ts +26 -0
- package/dist/mailbox.js +38 -0
- package/dist/mcp-tools.d.ts +123 -0
- package/dist/mcp-tools.js +97 -0
- package/dist/model-catalog.d.ts +162 -0
- package/dist/model-catalog.js +338 -0
- package/dist/model-probes.d.ts +7 -0
- package/dist/model-probes.js +69 -0
- package/dist/permission-path.d.ts +2 -0
- package/dist/permission-path.js +44 -0
- package/dist/process-info.d.ts +14 -0
- package/dist/process-info.js +32 -0
- package/dist/providers.d.ts +28 -0
- package/dist/providers.js +73 -0
- package/dist/recall.d.ts +42 -0
- package/dist/recall.js +61 -0
- package/dist/resolve.d.ts +123 -0
- package/dist/resolve.js +242 -0
- package/dist/runtime-context.d.ts +43 -0
- package/dist/runtime-context.js +61 -0
- package/dist/runtime.d.ts +13 -0
- package/dist/runtime.js +4818 -0
- package/dist/session-config.d.ts +2345 -0
- package/dist/session-config.js +209 -0
- package/dist/session-state.d.ts +190 -0
- package/dist/session-state.js +0 -0
- package/dist/skill-resources.d.ts +30 -0
- package/dist/skill-resources.js +55 -0
- package/dist/tool-detail.d.ts +81 -0
- package/dist/tool-detail.js +332 -0
- package/dist/tool-results.d.ts +12 -0
- package/dist/tool-results.js +25 -0
- package/dist/tools.d.ts +827 -0
- package/dist/tools.js +463 -0
- package/dist/transport.d.ts +47 -0
- package/dist/transport.js +171 -0
- package/dist/usage.d.ts +25 -0
- package/dist/usage.js +60 -0
- package/dist/workspace.d.ts +127 -0
- package/dist/workspace.js +340 -0
- package/dist/worktree-domain.d.ts +89 -0
- package/dist/worktree-domain.js +199 -0
- package/dist/write-error.d.ts +2 -0
- package/dist/write-error.js +10 -0
- package/package.json +262 -4
- package/src/acp-transport.ts +481 -0
- package/src/antigravity-transport.ts +740 -0
- package/src/assignment-results.ts +154 -0
- package/src/attachments.ts +254 -0
- package/src/board-domain.ts +185 -0
- package/src/board.ts +87 -0
- package/src/catalog.ts +43 -0
- package/src/claude-transport.ts +1097 -0
- package/src/compact.ts +62 -0
- package/src/configure.ts +93 -0
- package/src/contracts.ts +363 -0
- package/src/conversation.ts +81 -0
- package/src/events.ts +1 -0
- package/src/github.ts +37 -0
- package/src/handoff.ts +86 -0
- package/src/index.ts +41 -0
- package/src/input-limits.ts +65 -0
- package/src/language.ts +130 -0
- package/src/live.ts +90 -0
- package/src/mailbox.ts +49 -0
- package/src/mcp-tools.ts +106 -0
- package/src/model-catalog.ts +316 -0
- package/src/model-probes.ts +58 -0
- package/src/permission-path.ts +37 -0
- package/src/process-info.ts +40 -0
- package/src/providers.ts +87 -0
- package/src/recall.ts +86 -0
- package/src/resolve.ts +238 -0
- package/src/runtime-context.ts +49 -0
- package/src/runtime.ts +5608 -0
- package/src/session-config.ts +312 -0
- package/src/session-state.ts +180 -0
- package/src/skill-resources.ts +73 -0
- package/src/tool-detail.ts +397 -0
- package/src/tool-results.ts +26 -0
- package/src/tools.ts +466 -0
- package/src/transport.ts +118 -0
- package/src/usage.ts +79 -0
- package/src/workspace.ts +424 -0
- package/src/worktree-domain.ts +220 -0
- package/src/write-error.ts +4 -0
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live model catalog (t-e5ee): ALP serves core MODELS at once, then asks each provider which
|
|
3
|
+
* models it offers now and merges the answer over the static rows. A probe that fails keeps the
|
|
4
|
+
* previous list; the merged answer is cached in ALP_HOME/cache/models.json for the next start.
|
|
5
|
+
*/
|
|
6
|
+
import { mkdir, readFile } from 'node:fs/promises';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { MODELS, MODEL_POLICY, catalogCacheFile, mergeCatalog as mergeCatalogRows } from '@anhlp/alp-core/models';
|
|
9
|
+
import { writeAtomic } from '@anhlp/alp-core/atomic';
|
|
10
|
+
import { applyCatalog, type CatalogEntry } from './catalog.js';
|
|
11
|
+
|
|
12
|
+
export type CatalogRuntime = 'codex' | 'claude' | 'antigravity';
|
|
13
|
+
/** A model as a provider reports it. */
|
|
14
|
+
export type LiveModel = { id: string; label?: string; description?: string; efforts?: string[]; effort?: string };
|
|
15
|
+
export type ProviderState = { status: 'ok' | 'failed' | 'static'; fetchedAt?: string; error?: string; models: LiveModel[] };
|
|
16
|
+
/** What ALP learned of an ACP provider's models (t-d0b0): nothing until a session or an explicit probe tells it. */
|
|
17
|
+
export type AcpStatus = 'unprobed' | 'ok' | 'failed';
|
|
18
|
+
export type AcpState = { status: AcpStatus; fetchedAt?: string; error?: string; models: LiveModel[] };
|
|
19
|
+
export type CatalogSnapshot = { fetchedAt?: string; providers: Partial<Record<CatalogRuntime, ProviderState>>; acp?: Record<string, AcpState> };
|
|
20
|
+
export type Probe = (signal: AbortSignal) => Promise<LiveModel[]>;
|
|
21
|
+
/** A provider of the library (providers/<id>.json), as loadProvider reads it. */
|
|
22
|
+
export type AcpProviderConfig = { id: string; kind?: string; label?: string; description?: string; enabled?: boolean;
|
|
23
|
+
models?: Array<{ id: string; label?: string; description?: string }>; additionalModels?: Array<{ id: string; label?: string; description?: string }> };
|
|
24
|
+
export type AcpProbe = (provider: AcpProviderConfig, signal: AbortSignal) => Promise<LiveModel[]>;
|
|
25
|
+
/** An ACP row of the catalog: `acp:<provider>` (the agent's own default) and `acp:<provider>/<model>`. */
|
|
26
|
+
export type AcpRow = { runtime: 'acp'; provider: string; id: string; label: string; description: string; efforts: string[];
|
|
27
|
+
source: 'configured' | 'live'; enabled: boolean; status: AcpStatus };
|
|
28
|
+
|
|
29
|
+
const RUNTIMES: CatalogRuntime[] = ['codex', 'claude', 'antigravity'];
|
|
30
|
+
export const REFRESH_MS = 6 * 60 * 60 * 1000;
|
|
31
|
+
export const PROBE_TIMEOUT_MS = 15_000;
|
|
32
|
+
|
|
33
|
+
export const POLICY = MODEL_POLICY;
|
|
34
|
+
export const mergeCatalog = mergeCatalogRows as (base: CatalogEntry[], live: Partial<Record<CatalogRuntime, LiveModel[] | undefined>>) => CatalogEntry[];
|
|
35
|
+
|
|
36
|
+
const staticRows = (): CatalogEntry[] => MODELS.map(entry => ({ ...entry, source: 'static' as const })) as CatalogEntry[];
|
|
37
|
+
|
|
38
|
+
const bounded = <T>(work: (signal: AbortSignal) => Promise<T>, ms: number) => {
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
let timer: NodeJS.Timeout | undefined;
|
|
41
|
+
return Promise.race([
|
|
42
|
+
work(controller.signal),
|
|
43
|
+
new Promise<never>((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(new Error(`timed out after ${ms} ms`)); }, ms); }),
|
|
44
|
+
]).finally(() => clearTimeout(timer));
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const strings = (value: unknown) => Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : undefined;
|
|
48
|
+
/** Only well-formed rows: a string id, string label/description/effort, string efforts. */
|
|
49
|
+
export function sanitizeModels(value: unknown): LiveModel[] {
|
|
50
|
+
if (!Array.isArray(value)) return [];
|
|
51
|
+
return value.filter(model => model && typeof model === 'object' && typeof model.id === 'string' && model.id.trim()).map(model => ({
|
|
52
|
+
id: model.id,
|
|
53
|
+
...(typeof model.label === 'string' ? { label: model.label } : {}),
|
|
54
|
+
...(typeof model.description === 'string' ? { description: model.description } : {}),
|
|
55
|
+
...(strings(model.efforts) ? { efforts: strings(model.efforts) } : {}),
|
|
56
|
+
...(typeof model.effort === 'string' ? { effort: model.effort } : {}),
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
/** A cache file read back: known runtimes only, each with a list of well-formed rows. */
|
|
60
|
+
function sanitize(value: any): CatalogSnapshot {
|
|
61
|
+
const providers: CatalogSnapshot['providers'] = {};
|
|
62
|
+
for (const runtime of RUNTIMES) {
|
|
63
|
+
const state = value?.providers?.[runtime];
|
|
64
|
+
if (!state || typeof state !== 'object') continue;
|
|
65
|
+
providers[runtime] = { status: state.status === 'ok' ? 'ok' : 'failed', ...(typeof state.fetchedAt === 'string' ? { fetchedAt: state.fetchedAt } : {}), models: sanitizeModels(state.models) };
|
|
66
|
+
}
|
|
67
|
+
const acp: Record<string, AcpState> = {};
|
|
68
|
+
if (value?.acp && typeof value.acp === 'object') for (const [id, state] of Object.entries<any>(value.acp)) {
|
|
69
|
+
if (!/^[\w.-]+$/.test(id) || !state || typeof state !== 'object') continue;
|
|
70
|
+
acp[id] = { status: state.status === 'ok' ? 'ok' : state.status === 'failed' ? 'failed' : 'unprobed', ...(typeof state.fetchedAt === 'string' ? { fetchedAt: state.fetchedAt } : {}), ...(typeof state.error === 'string' ? { error: state.error } : {}), models: sanitizeModels(state.models) };
|
|
71
|
+
}
|
|
72
|
+
return { ...(typeof value?.fetchedAt === 'string' ? { fetchedAt: value.fetchedAt } : {}), providers, ...(Object.keys(acp).length ? { acp } : {}) };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The models a `session/new` answer offers (ACP `models.availableModels`, or a model select config option). */
|
|
76
|
+
export function acpSessionModels(result: any): LiveModel[] {
|
|
77
|
+
const config = Array.isArray(result?.configOptions) ? result.configOptions.find((option: any) => option?.category === 'model' && option?.type === 'select') : undefined;
|
|
78
|
+
const listed = Array.isArray(result?.models?.availableModels) ? result.models.availableModels
|
|
79
|
+
: config ? (config.options ?? []).flatMap((option: any) => option?.options ?? [option]).map((option: any) => ({ modelId: option?.value, name: option?.name, description: option?.description })) : [];
|
|
80
|
+
return sanitizeModels(listed.map((model: any) => ({ id: model?.modelId ?? model?.id, ...(typeof model?.name === 'string' && model.name ? { label: model.name } : {}), ...(typeof model?.description === 'string' && model.description ? { description: model.description } : {}) })));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
type Listener = (snapshot: CatalogSnapshot, entries: CatalogEntry[]) => void;
|
|
84
|
+
|
|
85
|
+
export class ModelCatalog {
|
|
86
|
+
private snapshot: CatalogSnapshot = { providers: {} };
|
|
87
|
+
private current: CatalogEntry[] = staticRows();
|
|
88
|
+
private listeners = new Set<Listener>();
|
|
89
|
+
private timer?: NodeJS.Timeout;
|
|
90
|
+
private running?: Promise<CatalogSnapshot>;
|
|
91
|
+
private readonly file?: string;
|
|
92
|
+
private acpConfigs: AcpProviderConfig[] = [];
|
|
93
|
+
private acpRunning?: Promise<CatalogSnapshot>;
|
|
94
|
+
private acpError?: string;
|
|
95
|
+
private acpLearning = new Map<string, Set<string>>();
|
|
96
|
+
/** Cache writes under way: stop() waits for them, so whoever stopped the catalog may remove its home. */
|
|
97
|
+
private writes = new Set<Promise<void>>();
|
|
98
|
+
/** Set once stop() has drained: a late answer (a session's models, an ingest) still updates memory but writes nothing. */
|
|
99
|
+
private stopped = false;
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* ACP providers (t-d0b0) come from `acpProviders` (the library's providers/<id>.json) without starting
|
|
103
|
+
* them; their models are learned from sessions (learnAcp) and probed (acpProbe) only by refreshAcp,
|
|
104
|
+
* which alpd calls on catalog.refresh and when the user enables a provider. Never at start or on the timer.
|
|
105
|
+
*/
|
|
106
|
+
constructor(private readonly options: { home?: string; probes: Partial<Record<CatalogRuntime, Probe>>; timeoutMs?: number; refreshMs?: number; now?: () => Date; apply?: boolean;
|
|
107
|
+
acpProviders?: () => Promise<AcpProviderConfig[] | { providers: AcpProviderConfig[]; error?: string }>; acpProbe?: AcpProbe }) {
|
|
108
|
+
this.file = options.home ? catalogCacheFile(options.home) : undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
entries() { return this.current; }
|
|
112
|
+
state() { return this.snapshot; }
|
|
113
|
+
onUpdated(listener: Listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
|
|
114
|
+
|
|
115
|
+
/** Loads the cache, then refreshes in the background and every refreshMs. Never blocks on a provider. */
|
|
116
|
+
async start() {
|
|
117
|
+
this.stopped = false;
|
|
118
|
+
await this.load();
|
|
119
|
+
await this.loadAcp().catch(() => {});
|
|
120
|
+
void this.refresh().catch(() => {});
|
|
121
|
+
const every = this.options.refreshMs ?? REFRESH_MS;
|
|
122
|
+
if (every > 0) { this.timer = setInterval(() => { void this.refresh().catch(() => {}); }, every); this.timer.unref?.(); }
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Stops the timer and the listeners, then waits for what already started (a background refresh, a
|
|
126
|
+
* refreshAcp a saved provider asked for, a learned model's cache write) to finish writing the cache
|
|
127
|
+
* (t-5294.2). After that it writes the cache no more, until start() again. A caller that only stops may
|
|
128
|
+
* ignore the promise; one that removes the home awaits it.
|
|
129
|
+
*/
|
|
130
|
+
async stop() {
|
|
131
|
+
if (this.timer) clearInterval(this.timer);
|
|
132
|
+
this.timer = undefined;
|
|
133
|
+
this.listeners.clear();
|
|
134
|
+
// A refreshAcp queued behind a running one starts when it ends: wait until nothing runs.
|
|
135
|
+
while (this.running || this.acpRunning || this.writes.size) await Promise.allSettled([this.running, this.acpRunning, ...this.writes]);
|
|
136
|
+
this.stopped = true;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async load() {
|
|
140
|
+
if (!this.file) return;
|
|
141
|
+
try {
|
|
142
|
+
this.snapshot = sanitize(JSON.parse(await readFile(this.file, 'utf8')));
|
|
143
|
+
await this.publish(false);
|
|
144
|
+
} catch { this.snapshot = { providers: {} }; /* no cache, or unreadable: static rows serve */ }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Asks every provider (or the named ones; a refresh already running answers instead) at once; each answer is bounded, and a failure keeps that provider's previous list. */
|
|
148
|
+
refresh(runtimes: CatalogRuntime[] = RUNTIMES): Promise<CatalogSnapshot> {
|
|
149
|
+
if (this.running) return this.running;
|
|
150
|
+
this.running = (async () => {
|
|
151
|
+
const now = () => (this.options.now?.() ?? new Date()).toISOString();
|
|
152
|
+
const results = await Promise.all(runtimes.filter(runtime => this.options.probes[runtime]).map(async runtime => {
|
|
153
|
+
try { return [runtime, { status: 'ok', fetchedAt: now(), models: sanitizeModels(await bounded(this.options.probes[runtime]!, this.options.timeoutMs ?? PROBE_TIMEOUT_MS)) }] as const; }
|
|
154
|
+
catch (error) {
|
|
155
|
+
const prior = this.snapshot.providers[runtime];
|
|
156
|
+
return [runtime, { status: 'failed', fetchedAt: prior?.fetchedAt, error: error instanceof Error ? error.message : String(error), models: prior?.models ?? [] }] as const;
|
|
157
|
+
}
|
|
158
|
+
}));
|
|
159
|
+
for (const [runtime, state] of results) {
|
|
160
|
+
// An empty answer is no answer: keep what we had.
|
|
161
|
+
if (state.status === 'ok' && !state.models.length) { this.snapshot.providers[runtime] = { ...(this.snapshot.providers[runtime] ?? { models: [] }), status: 'failed', error: 'provider reported no models' }; continue; }
|
|
162
|
+
this.snapshot.providers[runtime] = state as ProviderState;
|
|
163
|
+
}
|
|
164
|
+
this.snapshot.fetchedAt = now();
|
|
165
|
+
await this.publish(true);
|
|
166
|
+
return this.snapshot;
|
|
167
|
+
})().finally(() => { this.running = undefined; });
|
|
168
|
+
return this.running;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* A list a session reported on its own (each turn's orchestration context). Additive: it only adds
|
|
173
|
+
* models the catalog does not list yet, after the ones it has, so it never narrows or reshapes what a
|
|
174
|
+
* probe answered; a list with nothing new changes nothing.
|
|
175
|
+
*/
|
|
176
|
+
async ingest(runtime: CatalogRuntime, models: LiveModel[]) {
|
|
177
|
+
const prior = this.snapshot.providers[runtime];
|
|
178
|
+
const known = new Set((prior?.models ?? []).map(model => model.id));
|
|
179
|
+
const added = sanitizeModels(models).filter(model => !known.has(model.id));
|
|
180
|
+
if (!added.length) return false;
|
|
181
|
+
this.snapshot.providers[runtime] = { ...(prior ?? { status: 'ok' }), status: prior?.status ?? 'ok', fetchedAt: prior?.fetchedAt ?? (this.options.now?.() ?? new Date()).toISOString(), models: [...(prior?.models ?? []), ...added] };
|
|
182
|
+
await this.publish(true);
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Rereads the ACP providers' files; starts none of them. */
|
|
187
|
+
async loadAcp() {
|
|
188
|
+
if (!this.options.acpProviders) return;
|
|
189
|
+
// A listing that fails (an unreadable providers directory) keeps the rows ALP had and records why.
|
|
190
|
+
try {
|
|
191
|
+
const loaded = await this.options.acpProviders();
|
|
192
|
+
this.acpConfigs = (Array.isArray(loaded) ? loaded : loaded.providers).filter(provider => provider.kind !== 'antigravity');
|
|
193
|
+
this.acpError = Array.isArray(loaded) ? undefined : loaded.error;
|
|
194
|
+
} catch (error) { this.acpError = error instanceof Error ? error.message : String(error); }
|
|
195
|
+
}
|
|
196
|
+
/** Why the last reading of the ACP providers failed, if it did. */
|
|
197
|
+
acpLoadError(): string | undefined { return this.acpError; }
|
|
198
|
+
|
|
199
|
+
/** The ACP rows: each provider's default, then its models (the file's `models` replace learned ones; `additionalModels` add). */
|
|
200
|
+
acpRows(): AcpRow[] {
|
|
201
|
+
const rows: AcpRow[] = [];
|
|
202
|
+
for (const provider of this.acpConfigs) {
|
|
203
|
+
const state = this.snapshot.acp?.[provider.id];
|
|
204
|
+
const status = state?.status ?? 'unprobed';
|
|
205
|
+
const enabled = provider.enabled !== false;
|
|
206
|
+
const label = provider.label ?? provider.id;
|
|
207
|
+
const row = (id: string, text: string, description: string, source: AcpRow['source']): AcpRow => ({ runtime: 'acp', provider: provider.id, id, label: text, description, efforts: [], source, enabled, status });
|
|
208
|
+
rows.push(row(provider.id, `${label} · agent default`, provider.description ?? '', 'configured'));
|
|
209
|
+
const seen = new Set<string>();
|
|
210
|
+
const add = (models: Array<{ id: string; label?: string; description?: string }>, source: AcpRow['source']) => {
|
|
211
|
+
for (const model of models) if (!seen.has(model.id)) { seen.add(model.id); rows.push(row(`${provider.id}/${model.id}`, `${label} · ${model.label ?? model.id}`, model.description ?? '', source)); }
|
|
212
|
+
};
|
|
213
|
+
add(provider.models ?? state?.models ?? [], provider.models ? 'configured' : 'live');
|
|
214
|
+
add(provider.additionalModels ?? [], 'configured');
|
|
215
|
+
}
|
|
216
|
+
return rows;
|
|
217
|
+
}
|
|
218
|
+
/** The models ALP learned or probed for one ACP provider. */
|
|
219
|
+
acpModels(provider: string): LiveModel[] { return this.snapshot.acp?.[provider]?.models ?? []; }
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* A list an ACP session's `session/new` reported (t-d0b0). Additive, as ingest: it never removes a model
|
|
223
|
+
* a probe answered; a list with nothing new changes nothing.
|
|
224
|
+
*/
|
|
225
|
+
async learnAcp(provider: string, models: LiveModel[]) {
|
|
226
|
+
if (!/^[\w.-]+$/.test(provider)) return false;
|
|
227
|
+
const reported = sanitizeModels(models);
|
|
228
|
+
for (const model of reported) this.acpLearning.get(provider)?.add(model.id);
|
|
229
|
+
const prior = this.snapshot.acp?.[provider];
|
|
230
|
+
const known = new Set((prior?.models ?? []).map(model => model.id));
|
|
231
|
+
const added = reported.filter(model => !known.has(model.id));
|
|
232
|
+
if (!added.length) return false;
|
|
233
|
+
this.snapshot.acp = { ...this.snapshot.acp, [provider]: { status: 'ok', fetchedAt: (this.options.now?.() ?? new Date()).toISOString(), models: [...(prior?.models ?? []), ...added] } };
|
|
234
|
+
await this.publish(true);
|
|
235
|
+
return true;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Starts each enabled ACP provider (or the named ones) once to read its models: only on an explicit
|
|
240
|
+
* catalog.refresh or when the user enables a provider. A failure keeps what ALP knew and records why.
|
|
241
|
+
*/
|
|
242
|
+
refreshAcp(ids?: string[]): Promise<CatalogSnapshot> {
|
|
243
|
+
if (this.acpRunning) return this.acpRunning.then(() => this.refreshAcp(ids));
|
|
244
|
+
this.acpRunning = (async () => {
|
|
245
|
+
await this.loadAcp();
|
|
246
|
+
const probe = this.options.acpProbe;
|
|
247
|
+
const targets = this.acpConfigs.filter(provider => provider.enabled !== false && (!ids || ids.includes(provider.id)));
|
|
248
|
+
if (!probe || !targets.length) return this.snapshot;
|
|
249
|
+
const now = () => (this.options.now?.() ?? new Date()).toISOString();
|
|
250
|
+
await Promise.all(targets.map(async provider => {
|
|
251
|
+
const learned = new Set<string>();
|
|
252
|
+
this.acpLearning.set(provider.id, learned);
|
|
253
|
+
let outcome: { ok: true; models: LiveModel[] } | { ok: false; error: string };
|
|
254
|
+
try { outcome = { ok: true, models: sanitizeModels(await bounded(signal => probe(provider, signal), this.options.timeoutMs ?? PROBE_TIMEOUT_MS)) }; }
|
|
255
|
+
catch (error) { outcome = { ok: false, error: error instanceof Error ? error.message : String(error) }; }
|
|
256
|
+
this.acpLearning.delete(provider.id);
|
|
257
|
+
// Read at write time: what a session's learnAcp reported during the probe stays.
|
|
258
|
+
const current = this.snapshot.acp?.[provider.id];
|
|
259
|
+
const known = current?.models ?? [];
|
|
260
|
+
let next: AcpState;
|
|
261
|
+
if (outcome.ok) {
|
|
262
|
+
const ids = new Set(outcome.models.map(model => model.id));
|
|
263
|
+
// A successful probe replaces old choices, retaining only learning concurrent with this probe.
|
|
264
|
+
next = { status: 'ok', fetchedAt: now(), models: [...outcome.models, ...known.filter(model => learned.has(model.id) && !ids.has(model.id))] };
|
|
265
|
+
} else next = { status: 'failed', ...(current?.fetchedAt ? { fetchedAt: current.fetchedAt } : {}), error: outcome.error, models: known };
|
|
266
|
+
this.snapshot.acp = { ...this.snapshot.acp, [provider.id]: next };
|
|
267
|
+
}));
|
|
268
|
+
await this.publish(true);
|
|
269
|
+
return this.snapshot;
|
|
270
|
+
})().finally(() => { this.acpRunning = undefined; });
|
|
271
|
+
return this.acpRunning;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private async publish(save: boolean) {
|
|
275
|
+
const next = mergeCatalog(staticRows(), Object.fromEntries(Object.entries(this.snapshot.providers).map(([runtime, state]) => [runtime, state?.models])));
|
|
276
|
+
const changed = JSON.stringify(next) !== JSON.stringify(this.current);
|
|
277
|
+
this.current = next;
|
|
278
|
+
if (this.options.apply !== false) applyCatalog(next);
|
|
279
|
+
if (save && this.file && !this.stopped) {
|
|
280
|
+
const file = this.file;
|
|
281
|
+
const write = (async () => {
|
|
282
|
+
try { await mkdir(path.dirname(file), { recursive: true }); await writeAtomic(file, JSON.stringify(this.snapshot, null, 2)); } catch { /* the cache is best effort */ }
|
|
283
|
+
})();
|
|
284
|
+
this.writes.add(write);
|
|
285
|
+
try { await write; } finally { this.writes.delete(write); }
|
|
286
|
+
}
|
|
287
|
+
if (save) for (const listener of this.listeners) { try { listener(this.snapshot, next); } catch { /* a listener never stops the catalog */ } }
|
|
288
|
+
return changed;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Reads a session's orchestration context models (`runtime:id`, label, description, thinking) as live models. */
|
|
293
|
+
export function liveFromContext(context: any): { runtime: CatalogRuntime; models: LiveModel[] } | undefined {
|
|
294
|
+
if (!context?.catalogAvailable || !RUNTIMES.includes(context.runtime) || !Array.isArray(context.models)) return undefined;
|
|
295
|
+
if (context.catalogComplete === false) return undefined;
|
|
296
|
+
const prefix = `${context.runtime}:`;
|
|
297
|
+
const models = context.models.filter((model: any) => typeof model?.id === 'string' && model.id.startsWith(prefix)).map((model: any) => ({
|
|
298
|
+
id: model.id.slice(prefix.length), label: model.label, description: model.description,
|
|
299
|
+
efforts: Array.isArray(model.thinking) ? model.thinking.map((effort: any) => typeof effort === 'string' ? effort : effort?.reasoningEffort ?? effort?.id).filter((effort: unknown) => typeof effort === 'string') : undefined,
|
|
300
|
+
}));
|
|
301
|
+
return { runtime: context.runtime, models };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
let active: ModelCatalog | undefined;
|
|
305
|
+
/** The daemon's catalog, which sessions feed opportunistically. */
|
|
306
|
+
export function setActiveCatalog(catalog: ModelCatalog | undefined) { active = catalog; }
|
|
307
|
+
export function activeCatalog() { return active; }
|
|
308
|
+
export function feedCatalog(context: unknown) {
|
|
309
|
+
const live = liveFromContext(context);
|
|
310
|
+
if (live && active) void active.ingest(live.runtime, live.models).catch(() => {});
|
|
311
|
+
}
|
|
312
|
+
/** An ACP session's `session/new` answer teaches the daemon's catalog that provider's models (t-d0b0). */
|
|
313
|
+
export function feedAcpSession(provider: string, result: unknown) {
|
|
314
|
+
const models = acpSessionModels(result);
|
|
315
|
+
if (models.length && active) void active.learnAcp(provider, models).catch(() => {});
|
|
316
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Live model probes for the catalog (t-e5ee): each asks a provider's own CLI, read-only, and closes it. */
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { CodexTransport } from './transport.js';
|
|
5
|
+
import { ClaudeTransport } from './claude-transport.js';
|
|
6
|
+
import type { CatalogRuntime, LiveModel, Probe } from './model-catalog.js';
|
|
7
|
+
|
|
8
|
+
export function codexProbe(command = process.env.ALP_CODEX_BIN ?? 'codex', env: NodeJS.ProcessEnv = process.env): Probe {
|
|
9
|
+
return async signal => {
|
|
10
|
+
const transport = new CodexTransport(command, os.tmpdir(), env);
|
|
11
|
+
const stop = () => { void transport.close(); };
|
|
12
|
+
signal.addEventListener('abort', stop);
|
|
13
|
+
try {
|
|
14
|
+
await transport.initialize();
|
|
15
|
+
const models: LiveModel[] = [];
|
|
16
|
+
let cursor: string | undefined;
|
|
17
|
+
for (let page = 0; page < 10; page++) {
|
|
18
|
+
const result = await transport.request('model/list', { limit: 100, includeHidden: false, ...(cursor ? { cursor } : {}) }, 10_000, false);
|
|
19
|
+
for (const model of result?.data ?? []) {
|
|
20
|
+
if (typeof model?.model !== 'string' || model.hidden) continue;
|
|
21
|
+
models.push({ id: model.model, label: model.displayName, description: model.description,
|
|
22
|
+
efforts: (model.supportedReasoningEfforts ?? []).map((effort: any) => typeof effort === 'string' ? effort : effort?.reasoningEffort).filter((effort: unknown) => typeof effort === 'string'),
|
|
23
|
+
effort: model.defaultReasoningEffort });
|
|
24
|
+
}
|
|
25
|
+
cursor = result?.nextCursor ?? undefined;
|
|
26
|
+
if (!cursor) break;
|
|
27
|
+
}
|
|
28
|
+
return models;
|
|
29
|
+
} finally { signal.removeEventListener('abort', stop); await transport.close(); }
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function claudeProbe(command = process.env.ALP_CLAUDE_BIN ?? 'claude', env: NodeJS.ProcessEnv = process.env): Probe {
|
|
34
|
+
return async signal => new ClaudeTransport(command, os.tmpdir(), env).probeModels(signal);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `agy models` prints one model per line, `id<TAB>label`. */
|
|
38
|
+
export function parseAgyModels(stdout: string): LiveModel[] {
|
|
39
|
+
return stdout.split(/\r?\n/).map(line => line.trim()).filter(Boolean).map(line => {
|
|
40
|
+
const [id, label] = line.split('\t').map(part => part.trim());
|
|
41
|
+
return { id, label: label || id };
|
|
42
|
+
}).filter(model => model.id && /^[A-Za-z0-9][\w.:\-\[\]/]*$/.test(model.id));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function antigravityProbe(command = process.env.ALP_ANTIGRAVITY_BIN ?? 'agy', env: NodeJS.ProcessEnv = process.env, args: string[] = []): Probe {
|
|
46
|
+
return signal => new Promise((resolve, reject) => {
|
|
47
|
+
const child = spawn(command, [...args, 'models'], { cwd: os.tmpdir(), env, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, signal });
|
|
48
|
+
let stdout = '';
|
|
49
|
+
// A model list is small; more than this is not one.
|
|
50
|
+
child.stdout.on('data', chunk => { stdout += chunk; if (stdout.length > 256 * 1024) child.kill('SIGKILL'); });
|
|
51
|
+
child.on('error', reject);
|
|
52
|
+
child.on('close', code => code === 0 ? resolve(parseAgyModels(stdout)) : reject(new Error(`${command} models exited with ${code}`)));
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function liveProbes(env: NodeJS.ProcessEnv = process.env): Record<CatalogRuntime, Probe> {
|
|
57
|
+
return { codex: codexProbe(undefined, env), claude: claudeProbe(undefined, env), antigravity: antigravityProbe(undefined, env) };
|
|
58
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { lstatSync, realpathSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
|
|
5
|
+
/** Resolve each component before '..', matching filesystem traversal through links.
|
|
6
|
+
* Missing leaves are allowed for creation; dangling links and other errors fail closed. */
|
|
7
|
+
function canonical(file: string): string {
|
|
8
|
+
const absolute = path.isAbsolute(file) ? file : `${process.cwd()}${path.sep}${file}`;
|
|
9
|
+
let current = path.parse(absolute).root;
|
|
10
|
+
for (const part of absolute.slice(current.length).split(process.platform === 'win32' ? /[\\/]/ : /\//)) {
|
|
11
|
+
if (!part || part === '.') continue;
|
|
12
|
+
if (part === '..') { current = path.dirname(current); continue; }
|
|
13
|
+
const candidate = path.join(current, part);
|
|
14
|
+
try { current = realpathSync.native(candidate); }
|
|
15
|
+
catch (error: any) {
|
|
16
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
17
|
+
try {
|
|
18
|
+
if (lstatSync(candidate).isSymbolicLink()) throw new Error('Dangling symlink');
|
|
19
|
+
} catch (infoError: any) { if (infoError?.code !== 'ENOENT') throw infoError; }
|
|
20
|
+
current = candidate;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return current;
|
|
24
|
+
}
|
|
25
|
+
const contains = (root: string, file: string) => {
|
|
26
|
+
const relative = path.relative(root, file);
|
|
27
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** ALP's permission gate, not an OS sandbox or protection against concurrent link swaps. */
|
|
31
|
+
export function writablePath(file: unknown, workdir: string): boolean {
|
|
32
|
+
if (typeof file !== 'string' || !file.trim() || file.includes('\0')) return false;
|
|
33
|
+
try {
|
|
34
|
+
const target = canonical(path.isAbsolute(file) ? file : `${workdir}${path.sep}${file}`);
|
|
35
|
+
return contains(canonical(workdir), target) || contains(canonical(os.tmpdir()), target);
|
|
36
|
+
} catch { return false; }
|
|
37
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Telling a process from a later one that reuses its pid (ALPD §32): a pid alone
|
|
5
|
+
* can name an unrelated process once the first one is gone, so ALP also records
|
|
6
|
+
* when the process started, and compares that.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** When this process started, in milliseconds since the epoch. */
|
|
10
|
+
export const OWN_START = Math.round(Date.now() - process.uptime() * 1000);
|
|
11
|
+
|
|
12
|
+
/** ps reports start times to the second; PowerShell's are exact. */
|
|
13
|
+
const START_TOLERANCE_MS = 2000;
|
|
14
|
+
|
|
15
|
+
/** When process `pid` started, from ps (PowerShell on Windows); undefined where they cannot tell. */
|
|
16
|
+
export function processStartedAt(pid: number): number | undefined {
|
|
17
|
+
try {
|
|
18
|
+
if (process.platform === 'win32') {
|
|
19
|
+
// No ps: ask PowerShell (about 200 ms). A process of another user hides its start time, which reads as unknown.
|
|
20
|
+
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: 5000, windowsHide: true }).trim();
|
|
21
|
+
return /^\d+$/.test(out) ? Number(out) : undefined;
|
|
22
|
+
}
|
|
23
|
+
const started = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000, env: { ...process.env, LC_ALL: 'C' } }).trim();
|
|
24
|
+
const at = Date.parse(started);
|
|
25
|
+
return Number.isNaN(at) ? undefined : at;
|
|
26
|
+
} catch {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Whether the process that started at `startedAt` as `pid` still runs. Without a
|
|
33
|
+
* start time, or where ps cannot tell, a live pid counts as that process.
|
|
34
|
+
*/
|
|
35
|
+
export function sameProcessAlive(pid: number, startedAt?: number) {
|
|
36
|
+
try { process.kill(pid, 0); } catch (error: any) { if (error?.code !== 'EPERM') return false; }
|
|
37
|
+
if (startedAt === undefined) return true;
|
|
38
|
+
const actual = processStartedAt(pid);
|
|
39
|
+
return actual === undefined || Math.abs(actual - startedAt) < START_TOLERANCE_MS;
|
|
40
|
+
}
|
package/src/providers.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { AGENT_MARKER } from '@anhlp/alp-core/tasks';
|
|
2
|
+
import { CodexTransport } from './transport.js';
|
|
3
|
+
import { ClaudeTransport } from './claude-transport.js';
|
|
4
|
+
import { AcpTransport, type AcpProvider } from './acp-transport.js';
|
|
5
|
+
import { AntigravityTransport, type AntigravityProvider } from './antigravity-transport.js';
|
|
6
|
+
import type { RuntimeKind } from './resolve.js';
|
|
7
|
+
import type { RuntimeOptions, RuntimeTransport } from './contracts.js';
|
|
8
|
+
|
|
9
|
+
/** The environment a native harness starts with: the host's, without variables that would tie it to the host's own agent session. */
|
|
10
|
+
export function nativeEnvironment(options: RuntimeOptions, extra: Record<string, string> = {}) {
|
|
11
|
+
const environment: NodeJS.ProcessEnv = { ...(options.environment ?? process.env), ...extra };
|
|
12
|
+
for (const key of Object.keys(environment)) {
|
|
13
|
+
// Markers of an enclosing Paseo, Codex or Claude Code session would make the native harness think it is nested.
|
|
14
|
+
if (/^(PASEO_|CODEX_THREAD_ID$|CODEX_INTERNAL_|CODEX_PARENT_|CLAUDECODE$|CLAUDE_CODE_|ANTHROPIC_AGENT_)/.test(key)) delete environment[key];
|
|
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';
|
|
18
|
+
return environment;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Provider factories adapt native harnesses to ALP's normalized transport contract. */
|
|
22
|
+
export type ProviderContext = {
|
|
23
|
+
options: RuntimeOptions;
|
|
24
|
+
runtime: RuntimeKind;
|
|
25
|
+
cwd: string;
|
|
26
|
+
environment: NodeJS.ProcessEnv;
|
|
27
|
+
acp?: AcpProvider;
|
|
28
|
+
antigravity?: AntigravityProvider;
|
|
29
|
+
};
|
|
30
|
+
export type ProviderFactory = (context: ProviderContext) => RuntimeTransport;
|
|
31
|
+
export type ProviderFactories = Partial<Record<RuntimeKind, ProviderFactory>>;
|
|
32
|
+
|
|
33
|
+
/** Explicit registry: each runtime instance can override adapters without global state. */
|
|
34
|
+
export class ProviderRegistry {
|
|
35
|
+
private readonly factories = new Map<string, ProviderFactory>();
|
|
36
|
+
|
|
37
|
+
constructor(factories: Record<string, ProviderFactory | undefined> = {}) {
|
|
38
|
+
for (const [id, factory] of Object.entries(factories)) if (factory) this.register(id, factory);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
register(id: string, factory: ProviderFactory): this {
|
|
42
|
+
if (!id.trim()) throw new Error('A provider needs an id');
|
|
43
|
+
this.factories.set(id, factory);
|
|
44
|
+
return this;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
create(id: string, context: ProviderContext): RuntimeTransport {
|
|
48
|
+
const factory = this.factories.get(id);
|
|
49
|
+
if (!factory) throw new Error(`Unknown runtime provider: ${id}`);
|
|
50
|
+
return factory(context);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
has(id: string): boolean { return this.factories.has(id); }
|
|
54
|
+
list(): string[] { return [...this.factories.keys()]; }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function createProviderRegistry(overrides: ProviderFactories = {}): ProviderRegistry {
|
|
58
|
+
return new ProviderRegistry({
|
|
59
|
+
codex: ({ options, cwd, environment }) => new CodexTransport(
|
|
60
|
+
options.codexCommand ?? process.env.ALP_CODEX_BIN ?? 'codex', cwd, environment),
|
|
61
|
+
claude: ({ options, cwd, environment }) => new ClaudeTransport(
|
|
62
|
+
options.claudeCommand ?? process.env.ALP_CLAUDE_BIN ?? 'claude', cwd, environment),
|
|
63
|
+
acp: ({ acp, cwd, environment }) => {
|
|
64
|
+
if (!acp) throw new Error('An ACP session needs its provider');
|
|
65
|
+
return new AcpTransport(acp, cwd, environment);
|
|
66
|
+
},
|
|
67
|
+
antigravity: ({ options, antigravity, cwd, environment }) => new AntigravityTransport(
|
|
68
|
+
options.antigravityCommand ?? process.env.ALP_ANTIGRAVITY_BIN ?? antigravity?.command ?? 'agy',
|
|
69
|
+
cwd, environment, antigravity),
|
|
70
|
+
...Object.fromEntries(Object.entries(overrides).filter(([, factory]) => factory !== undefined)),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function createTransport(
|
|
75
|
+
options: RuntimeOptions,
|
|
76
|
+
runtimeKind: RuntimeKind,
|
|
77
|
+
cwd: string,
|
|
78
|
+
environment: NodeJS.ProcessEnv,
|
|
79
|
+
acp?: AcpProvider,
|
|
80
|
+
antigravity?: AntigravityProvider,
|
|
81
|
+
): RuntimeTransport {
|
|
82
|
+
// Preserve the existing test/custom host hook and its positional argument contract.
|
|
83
|
+
if (options.transport) return options.transport(cwd, environment, runtimeKind, acp, antigravity);
|
|
84
|
+
const registry = options.providerRegistry ?? createProviderRegistry(options.providers);
|
|
85
|
+
const providerId = runtimeKind === 'acp' && acp && registry.has(`acp:${acp.id}`) ? `acp:${acp.id}` : runtimeKind;
|
|
86
|
+
return registry.create(providerId, { options, runtime: runtimeKind, cwd, environment, acp, antigravity });
|
|
87
|
+
}
|
package/src/recall.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import type { RuntimeKind } from './resolve.js';
|
|
5
|
+
import { tell } from './write-error.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Finished assignments whose native threads alp_recall can question (ALPD §27).
|
|
9
|
+
* The threads stay on disk for RECALL_KEEP_MS; then ALP deletes them.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export type RecallEntry = {
|
|
13
|
+
assignmentId: string;
|
|
14
|
+
rootId: string;
|
|
15
|
+
/** The requester and its requesters, nearest first: who may recall it besides a root of the project. */
|
|
16
|
+
requesters: string[];
|
|
17
|
+
agent: string;
|
|
18
|
+
project: string;
|
|
19
|
+
runtime: RuntimeKind;
|
|
20
|
+
threadId: string;
|
|
21
|
+
/** Where it worked: the project, or a worktree or copy that may be gone by now. */
|
|
22
|
+
cwd: string;
|
|
23
|
+
model: string;
|
|
24
|
+
thinking?: string;
|
|
25
|
+
taskId?: string;
|
|
26
|
+
status: string;
|
|
27
|
+
finishedAt: string;
|
|
28
|
+
/** Shared work remains in cwd; a new assignment can build on this brief and handoff. */
|
|
29
|
+
shared?: { brief: string; summary: string; writeRoot?: string };
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export const RECALL_KEEP_MS = 14 * 24 * 60 * 60 * 1000;
|
|
33
|
+
export const RECALL_MAX = 1000;
|
|
34
|
+
export const RECALL_QUESTION_CHARS = 4000;
|
|
35
|
+
export const RECALL_TIMEOUT_MS = 300_000;
|
|
36
|
+
|
|
37
|
+
const valid = (entry: any): entry is RecallEntry => !!entry && typeof entry === 'object' &&
|
|
38
|
+
['assignmentId', 'rootId', 'agent', 'project', 'runtime', 'threadId', 'cwd', 'model', 'status', 'finishedAt'].every(key => typeof entry[key] === 'string') &&
|
|
39
|
+
Array.isArray(entry.requesters);
|
|
40
|
+
|
|
41
|
+
/** The record of recallable threads, kept in `file` when given, else in memory; `onError` hears of each failed write. */
|
|
42
|
+
export function createRecallBook(file?: string, onError: (error: unknown) => void = () => {}) {
|
|
43
|
+
let entries: Promise<RecallEntry[]> | undefined;
|
|
44
|
+
let writes = Promise.resolve();
|
|
45
|
+
const load = () => entries ??= file
|
|
46
|
+
? readFile(file, 'utf8').then(text => (JSON.parse(text) as unknown[]).filter(valid), () => [] as RecallEntry[])
|
|
47
|
+
: Promise.resolve([]);
|
|
48
|
+
const save = (list: RecallEntry[]) => {
|
|
49
|
+
if (!file) return writes;
|
|
50
|
+
const body = JSON.stringify(list, null, 2) + '\n';
|
|
51
|
+
writes = writes.then(async () => {
|
|
52
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
53
|
+
const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
54
|
+
await writeFile(temporary, body, { mode: 0o600 });
|
|
55
|
+
await rename(temporary, file);
|
|
56
|
+
}).catch(error => tell(onError, error));
|
|
57
|
+
return writes;
|
|
58
|
+
};
|
|
59
|
+
return {
|
|
60
|
+
async all() { return [...await load()]; },
|
|
61
|
+
async add(entry: RecallEntry) {
|
|
62
|
+
const list = await load();
|
|
63
|
+
list.push(entry);
|
|
64
|
+
await save(list);
|
|
65
|
+
},
|
|
66
|
+
/** Removes and returns the entries past their time, and the oldest beyond RECALL_MAX. */
|
|
67
|
+
async expire(now = Date.now()) {
|
|
68
|
+
const list = await load();
|
|
69
|
+
const kept = list.filter(entry => now - Date.parse(entry.finishedAt) < RECALL_KEEP_MS).slice(-RECALL_MAX);
|
|
70
|
+
if (kept.length === list.length) return [];
|
|
71
|
+
const gone = list.filter(entry => !kept.includes(entry));
|
|
72
|
+
list.splice(0, list.length, ...kept);
|
|
73
|
+
await save(list);
|
|
74
|
+
return gone;
|
|
75
|
+
},
|
|
76
|
+
flush: () => writes,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** What a recalled assignment is told before the question. */
|
|
81
|
+
export function recallPrompt(asker: string, question: string) {
|
|
82
|
+
return `ALP recall: ${asker} asks about the assignment you finished in this conversation. ` +
|
|
83
|
+
'Answer from what you did, saw and decided then; read files only to check a detail. ' +
|
|
84
|
+
'This is a read-only copy of your session: change nothing, and do not call ALP tools; they are unavailable. ' +
|
|
85
|
+
`Answer briefly and concretely.\n\nQuestion: ${question}`;
|
|
86
|
+
}
|