@anhlp/alp-runtime 0.0.1-beta.4 → 0.0.1-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp-transport.js +5 -36
- package/dist/antigravity-transport.d.ts +17 -0
- package/dist/antigravity-transport.js +82 -58
- package/dist/assignment-results.d.ts +34 -0
- package/dist/assignment-results.js +94 -2
- package/dist/board-domain.js +2 -2
- package/dist/board.d.ts +6 -0
- package/dist/board.js +7 -0
- package/dist/catalog.d.ts +13 -0
- package/dist/catalog.js +9 -1
- package/dist/claude-transport.d.ts +7 -0
- package/dist/claude-transport.js +71 -10
- package/dist/compact.d.ts +29 -0
- package/dist/compact.js +49 -0
- package/dist/configure.d.ts +1 -1
- package/dist/configure.js +2 -2
- package/dist/contracts.d.ts +32 -3
- package/dist/index.d.ts +10 -2
- package/dist/index.js +30 -2
- package/dist/input-limits.d.ts +25 -0
- package/dist/input-limits.js +48 -0
- package/dist/language.d.ts +8 -0
- package/dist/language.js +20 -0
- package/dist/mcp-tools.d.ts +8 -0
- package/dist/mcp-tools.js +26 -0
- package/dist/model-catalog.d.ts +76 -0
- package/dist/model-catalog.js +193 -0
- package/dist/model-probes.d.ts +7 -0
- package/dist/model-probes.js +69 -0
- package/dist/providers.js +2 -0
- package/dist/resolve.d.ts +1 -0
- package/dist/resolve.js +3 -1
- package/dist/runtime.d.ts +3 -1
- package/dist/runtime.js +665 -47
- package/dist/session-config.d.ts +174 -0
- package/dist/session-config.js +9 -9
- package/dist/session-state.d.ts +23 -1
- package/dist/tools.d.ts +82 -0
- package/dist/tools.js +53 -5
- package/dist/transport.js +3 -1
- package/dist/workspace.d.ts +31 -5
- package/dist/workspace.js +92 -11
- package/package.json +3 -3
- package/src/acp-transport.ts +7 -37
- package/src/antigravity-transport.ts +95 -53
- package/src/assignment-results.ts +85 -3
- package/src/board-domain.ts +2 -2
- package/src/board.ts +7 -0
- package/src/catalog.ts +10 -1
- package/src/claude-transport.ts +79 -10
- package/src/compact.ts +62 -0
- package/src/configure.ts +3 -3
- package/src/contracts.ts +28 -2
- package/src/index.ts +10 -2
- package/src/input-limits.ts +65 -0
- package/src/language.ts +18 -0
- package/src/mcp-tools.ts +33 -0
- package/src/model-catalog.ts +166 -0
- package/src/model-probes.ts +58 -0
- package/src/providers.ts +3 -0
- package/src/resolve.ts +4 -2
- package/src/runtime.ts +718 -48
- package/src/session-config.ts +8 -8
- package/src/session-state.ts +15 -1
- package/src/tools.ts +53 -5
- package/src/transport.ts +3 -1
- package/src/workspace.ts +124 -18
|
@@ -1,19 +1,38 @@
|
|
|
1
|
-
import { readFile, mkdir, writeFile } from 'node:fs/promises';
|
|
1
|
+
import { readFile, readdir, mkdir, writeFile, open, rm } from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { writeAtomic } from '@anhlp/alp-core/atomic';
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
/** What a finished writer outside a worktree left in its checkout, kept until its requester handles it (recall entries expire, this does not). */
|
|
6
|
+
export type AssignmentResultEvidence = { agent: string; status: string; finishedAt: string; project: string; requesters: string[]; taskId?: string; brief: string; summary: string };
|
|
7
|
+
export const RESULT_OUTCOMES = ['applied', 'discarded', 'acknowledged'] as const;
|
|
8
|
+
export type AssignmentResultHandling = { outcome: typeof RESULT_OUTCOMES[number]; by: string; at: string; note?: string };
|
|
9
|
+
/** No `handled`: produced (or still running), and the removal guard refuses its paths. `handled`: the guard lets them go; archiving removes it from the ledger. */
|
|
10
|
+
export type AssignmentResultOwner = { assignmentId: string; checkout: string; worktree?: string; result?: AssignmentResultEvidence; handled?: AssignmentResultHandling };
|
|
11
|
+
export type ArchivedAssignmentResult = AssignmentResultOwner & { handled: AssignmentResultHandling; archivedAt: string };
|
|
6
12
|
type Ledger = { version: 1; workspaces: string[]; results: AssignmentResultOwner[] };
|
|
13
|
+
/** Archived results stay this long after the month they were archived in ends; ledger entries never expire. */
|
|
14
|
+
export const ARCHIVE_KEEP_MS = 365 * 24 * 60 * 60 * 1000;
|
|
7
15
|
const empty = (): Ledger => ({ version: 1, workspaces: [], results: [] });
|
|
8
16
|
const absolute = (value: unknown): value is string => typeof value === 'string' && path.isAbsolute(value);
|
|
17
|
+
const text = (value: unknown): value is string => typeof value === 'string';
|
|
18
|
+
const evidence = (value: any) => value === undefined || (!!value && typeof value === 'object' && !Array.isArray(value) &&
|
|
19
|
+
[value.agent, value.status, value.finishedAt, value.project, value.brief, value.summary].every(text) &&
|
|
20
|
+
Array.isArray(value.requesters) && value.requesters.every(text) && (value.taskId === undefined || text(value.taskId)));
|
|
21
|
+
const handling = (value: any) => value === undefined || (!!value && typeof value === 'object' && !Array.isArray(value) &&
|
|
22
|
+
RESULT_OUTCOMES.includes(value.outcome) && text(value.by) && text(value.at) && (value.note === undefined || text(value.note)));
|
|
9
23
|
const valid = (value: any): value is Ledger => value?.version === 1 && Array.isArray(value.workspaces) && value.workspaces.every(absolute) &&
|
|
10
|
-
Array.isArray(value.results) && value.results.every((entry: any) => entry && typeof entry.assignmentId === 'string' && absolute(entry.checkout) && (entry.worktree === undefined || absolute(entry.worktree))
|
|
24
|
+
Array.isArray(value.results) && value.results.every((entry: any) => entry && typeof entry.assignmentId === 'string' && absolute(entry.checkout) && (entry.worktree === undefined || absolute(entry.worktree)) &&
|
|
25
|
+
evidence(entry.result) && handling(entry.handled));
|
|
26
|
+
const MONTH = /^(\d{4})-(\d{2})\.jsonl$/;
|
|
11
27
|
|
|
12
28
|
/** Permanent ownership, independent of native-thread recall expiry. Missing initialized data is never recreated. */
|
|
13
29
|
export function createAssignmentResults(file?: string) {
|
|
14
30
|
let memory = empty();
|
|
31
|
+
let archivedInMemory: ArchivedAssignmentResult[] = [];
|
|
15
32
|
let queue = Promise.resolve();
|
|
16
33
|
const marker = file ? `${file}.initialized` : undefined;
|
|
34
|
+
// One JSON line per handled result, in a file per month of archiving.
|
|
35
|
+
const archiveDir = file ? path.join(path.dirname(file), 'assignment-archive') : undefined;
|
|
17
36
|
async function load(initialize = false): Promise<Ledger> {
|
|
18
37
|
if (!file) return memory;
|
|
19
38
|
let value: unknown;
|
|
@@ -42,6 +61,41 @@ export function createAssignmentResults(file?: string) {
|
|
|
42
61
|
queue = result.then(() => {}, () => {});
|
|
43
62
|
return result;
|
|
44
63
|
}
|
|
64
|
+
/** Appends a record and syncs it before its ledger entry may go; a crash in between archives it again, never loses it. */
|
|
65
|
+
async function append(record: ArchivedAssignmentResult) {
|
|
66
|
+
if (!archiveDir) { archivedInMemory.push(record); return; }
|
|
67
|
+
await mkdir(archiveDir, { recursive: true, mode: 0o700 });
|
|
68
|
+
const handle = await open(path.join(archiveDir, `${record.archivedAt.slice(0, 7)}.jsonl`), 'a+', 0o600);
|
|
69
|
+
try {
|
|
70
|
+
const { size } = await handle.stat();
|
|
71
|
+
const last = Buffer.alloc(1);
|
|
72
|
+
// A line cut short by a crash must not swallow the next record.
|
|
73
|
+
const torn = size > 0 && (await handle.read(last, 0, 1, size - 1)).bytesRead === 1 && last[0] !== 0x0a;
|
|
74
|
+
await handle.appendFile(`${torn ? '\n' : ''}${JSON.stringify(record)}\n`);
|
|
75
|
+
await handle.sync();
|
|
76
|
+
} finally { await handle.close(); }
|
|
77
|
+
}
|
|
78
|
+
async function archived(): Promise<ArchivedAssignmentResult[]> {
|
|
79
|
+
if (!archiveDir) return archivedInMemory;
|
|
80
|
+
let names: string[];
|
|
81
|
+
try { names = (await readdir(archiveDir)).filter(name => MONTH.test(name)).sort(); }
|
|
82
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; }
|
|
83
|
+
const records: ArchivedAssignmentResult[] = [];
|
|
84
|
+
for (const name of names) {
|
|
85
|
+
for (const line of (await readFile(path.join(archiveDir, name), 'utf8')).split('\n')) {
|
|
86
|
+
try { const record = JSON.parse(line); if (typeof record?.assignmentId === 'string') records.push(record); } catch {}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return records;
|
|
90
|
+
}
|
|
91
|
+
/** Deletes the archive months that ended more than ARCHIVE_KEEP_MS ago. */
|
|
92
|
+
async function prune(now: number) {
|
|
93
|
+
if (!archiveDir) { archivedInMemory = archivedInMemory.filter(record => now - Date.parse(record.archivedAt) < ARCHIVE_KEEP_MS); return; }
|
|
94
|
+
for (const name of await readdir(archiveDir).catch(() => [] as string[])) {
|
|
95
|
+
const month = MONTH.exec(name);
|
|
96
|
+
if (month && now - Date.UTC(Number(month[1]), Number(month[2])) > ARCHIVE_KEEP_MS) await rm(path.join(archiveDir, name), { force: true });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
45
99
|
return {
|
|
46
100
|
register(directory: string) { return serialize(async () => {
|
|
47
101
|
const value = await load(true);
|
|
@@ -59,6 +113,34 @@ export function createAssignmentResults(file?: string) {
|
|
|
59
113
|
value.results = value.results.filter(entry => entry.assignmentId !== assignmentId);
|
|
60
114
|
await save(value);
|
|
61
115
|
}); },
|
|
116
|
+
/**
|
|
117
|
+
* Records how a produced result was handled, then archives every handled entry and drops it from the ledger.
|
|
118
|
+
* The mark is saved first: from then on the guard lets the checkout go, while the ledger still holds the evidence.
|
|
119
|
+
*/
|
|
120
|
+
resolve(assignmentId: string, handled: AssignmentResultHandling) { return serialize(async () => {
|
|
121
|
+
if (!handling(handled)) throw new Error('Invalid result handling');
|
|
122
|
+
const value = await load();
|
|
123
|
+
const entry = value.results.find(owner => owner.assignmentId === assignmentId);
|
|
124
|
+
if (!entry) throw new Error(`No retained assignment result ${assignmentId}`);
|
|
125
|
+
if (!entry.handled) {
|
|
126
|
+
entry.handled = handled;
|
|
127
|
+
await save(value);
|
|
128
|
+
}
|
|
129
|
+
const now = Date.now();
|
|
130
|
+
const records: ArchivedAssignmentResult[] = [];
|
|
131
|
+
for (const owner of value.results) {
|
|
132
|
+
if (!owner.handled) continue;
|
|
133
|
+
const record = { ...owner, handled: owner.handled, archivedAt: new Date(now).toISOString() };
|
|
134
|
+
await append(record);
|
|
135
|
+
records.push(record);
|
|
136
|
+
}
|
|
137
|
+
value.results = value.results.filter(owner => !owner.handled);
|
|
138
|
+
await save(value);
|
|
139
|
+
await prune(now).catch(() => {});
|
|
140
|
+
return records.find(record => record.assignmentId === assignmentId)!;
|
|
141
|
+
}); },
|
|
142
|
+
/** The newest archived record of an assignment, if its archive month is still kept. */
|
|
143
|
+
archived(assignmentId: string) { return serialize(async () => (await archived()).filter(record => record.assignmentId === assignmentId).at(-1)); },
|
|
62
144
|
inspect() { return serialize(() => load()); },
|
|
63
145
|
};
|
|
64
146
|
}
|
package/src/board-domain.ts
CHANGED
|
@@ -143,8 +143,8 @@ export function createBoardDomain({ options, sessions, boards, loadedBoards, roo
|
|
|
143
143
|
}
|
|
144
144
|
|
|
145
145
|
async function boardTool(session: Session, args: unknown) {
|
|
146
|
-
if (!plainObject(args, ['kinds', 'limit']) || (args.kinds !== undefined && (!Array.isArray(args.kinds) || !args.kinds.every((kind: unknown) => PIN_KINDS.includes(kind as PinKind)))) || (args.limit !== undefined && (!Number.isSafeInteger(args.limit) || args.limit < 1))) {
|
|
147
|
-
return toolResult(false, { error:
|
|
146
|
+
if (!plainObject(args, ['kinds', 'limit']) || (args.kinds !== undefined && (!Array.isArray(args.kinds) || args.kinds.length > PIN_KINDS.length || !args.kinds.every((kind: unknown) => PIN_KINDS.includes(kind as PinKind)))) || (args.limit !== undefined && (!Number.isSafeInteger(args.limit) || args.limit < 1))) {
|
|
147
|
+
return toolResult(false, { error: `kinds lists at most ${PIN_KINDS.length} of claim, decision and finding; limit is a positive integer` });
|
|
148
148
|
}
|
|
149
149
|
const kinds: string[] = args.kinds ?? [...PIN_KINDS];
|
|
150
150
|
const pins = (await boardOf(session.mapping.agent.projectRoot)).filter(pin => live(pin) && kinds.includes(pin.kind));
|
package/src/board.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { realpathSync } from 'node:fs';
|
|
3
|
+
import type { InputLimits } from './input-limits.js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* The project board (plans/reference/ALPD.md §18): one group channel per project that every
|
|
@@ -16,6 +17,11 @@ export type { PinKind, Pin } from '@anhlp/alp-protocol/dto';
|
|
|
16
17
|
|
|
17
18
|
export const PIN_BODY_CHARS = 2000;
|
|
18
19
|
export const PIN_PATHS = 50;
|
|
20
|
+
/** One claimed path; macOS's PATH_MAX. Each segment of a path is one more realpath call. */
|
|
21
|
+
export const PIN_PATH_CHARS = 1024;
|
|
22
|
+
/** alp_pin's paths and alp_board's kinds, checked before any schema walks them. */
|
|
23
|
+
export const PIN_PATHS_INPUT: InputLimits = { bytes: PIN_PATHS * (3 * PIN_PATH_CHARS + 3), items: PIN_PATHS, depth: 1, string: PIN_PATH_CHARS };
|
|
24
|
+
export const BOARD_KINDS_INPUT: InputLimits = { bytes: 64, items: PIN_KINDS.length, depth: 1, string: 16 };
|
|
19
25
|
/** Decisions and findings kept per project; live claims are always kept. */
|
|
20
26
|
export const BOARD_KEEP = 200;
|
|
21
27
|
const DIGEST_CHARS = 3000;
|
|
@@ -38,6 +44,7 @@ export function normalizePaths(paths: unknown, project: string, roots: string[]
|
|
|
38
44
|
const normalized: string[] = [];
|
|
39
45
|
for (const entry of paths) {
|
|
40
46
|
if (typeof entry !== 'string' || !entry.trim()) return 'paths must be nonempty strings';
|
|
47
|
+
if (entry.length > PIN_PATH_CHARS) return `paths must be at most ${PIN_PATH_CHARS} characters each`;
|
|
41
48
|
const absolute = canonicalPath(path.resolve(project, entry.trim()));
|
|
42
49
|
if (!roots.some(root => containsPath(canonicalPath(root), absolute))) return `${entry} is outside the project or declared write root`;
|
|
43
50
|
const relative = path.relative(canonicalPath(project), absolute).split(path.sep).join('/');
|
package/src/catalog.ts
CHANGED
|
@@ -25,7 +25,16 @@ const model = (runtime: 'codex' | 'claude' | 'antigravity', id: string, label: s
|
|
|
25
25
|
...(defaultThinkingOptionId ? { defaultThinkingOptionId } : {}),
|
|
26
26
|
});
|
|
27
27
|
|
|
28
|
-
export
|
|
28
|
+
export type CatalogEntry = { runtime: 'codex' | 'claude' | 'antigravity'; id: string; label: string; description: string; efforts: string[]; effort?: string; source?: 'live' | 'fallback' | 'static' };
|
|
29
|
+
const toModel = (entry: CatalogEntry) => model(entry.runtime, entry.id, entry.label, entry.description, options(entry.efforts), entry.effort);
|
|
30
|
+
/** The rows every consumer reads: core MODELS at start, replaced in place by the live catalog (model-catalog.ts). */
|
|
31
|
+
export const entries: CatalogEntry[] = MODELS.map(entry => ({ ...entry, source: 'static' as const })) as CatalogEntry[];
|
|
32
|
+
export const models = entries.map(toModel);
|
|
33
|
+
/** Replaces the catalog in place so every module holding `models`/`entries` sees the new rows. */
|
|
34
|
+
export function applyCatalog(next: CatalogEntry[]) {
|
|
35
|
+
entries.splice(0, entries.length, ...next);
|
|
36
|
+
models.splice(0, models.length, ...next.map(toModel));
|
|
37
|
+
}
|
|
29
38
|
|
|
30
39
|
export function thinkingOptionsFor(runtime: 'codex' | 'claude' | 'antigravity', nativeModel: string) {
|
|
31
40
|
return models.find(candidate => candidate.id === `${runtime}:${nativeModel}`)?.thinkingOptions ?? thinkingOptions;
|
package/src/claude-transport.ts
CHANGED
|
@@ -5,15 +5,21 @@ import path from 'node:path';
|
|
|
5
5
|
import { optionalRead, claudeUsage } from './runtime-context.js';
|
|
6
6
|
import { randomUUID } from 'node:crypto';
|
|
7
7
|
import { z } from 'zod';
|
|
8
|
-
import { PIN_KINDS } from './board.js';
|
|
8
|
+
import { BOARD_KINDS_INPUT, PIN_BODY_CHARS, PIN_KINDS, PIN_PATH_CHARS, PIN_PATHS, PIN_PATHS_INPUT } from './board.js';
|
|
9
|
+
import { RESULT_OUTCOMES } from './assignment-results.js';
|
|
10
|
+
import { inputLimitError, POUR_VARS, VAR_NAME, type InputLimits } from './input-limits.js';
|
|
9
11
|
import { claudeToolDetail, resultText } from './tool-detail.js';
|
|
10
12
|
import { CLOSE_REASONS, GATE_KINDS, TASK_STATUSES, TASK_TYPES } from '@anhlp/alp-core/tasks';
|
|
11
13
|
import { commandDecision } from '@anhlp/alp-core/permissions';
|
|
14
|
+
import { packagedInfo } from '@anhlp/alp-core/packaged';
|
|
12
15
|
|
|
13
16
|
// Keep the Claude SDK behind the runtime boundary. Paseo inspects static
|
|
14
17
|
// imports while compiling plugin entrypoints, including their declaration
|
|
15
18
|
// graph; the SDK is a daemon-only optional runtime dependency.
|
|
16
19
|
const CLAUDE_SDK = ['@anthropic-ai', 'claude-agent-sdk'].join('/');
|
|
20
|
+
// The ALP executable has no node_modules to resolve CLAUDE_SDK from: its entry embeds the SDK and
|
|
21
|
+
// registers the import under the package name (scripts/build-binary.mjs).
|
|
22
|
+
const claudeSdk = (): Promise<any> => packagedInfo()?.modules?.[CLAUDE_SDK]?.() ?? import(CLAUDE_SDK);
|
|
17
23
|
|
|
18
24
|
type SDKUserMessage = any;
|
|
19
25
|
type SDKMessage = any;
|
|
@@ -27,6 +33,13 @@ type ClaudeQuery = AsyncGenerator<SDKMessage, void> & {
|
|
|
27
33
|
initializationResult?(): Promise<unknown>;
|
|
28
34
|
};
|
|
29
35
|
|
|
36
|
+
/** A field whose size is checked before zod walks it; its JSON Schema is the inner schema's (input-limits.ts). */
|
|
37
|
+
const bounded = <T extends z.ZodType>(schema: T, limits: InputLimits) => z.preprocess((value, ctx) => {
|
|
38
|
+
const error = inputLimitError(value, limits);
|
|
39
|
+
if (error) ctx.addIssue({ code: 'custom', message: error });
|
|
40
|
+
return value;
|
|
41
|
+
}, schema);
|
|
42
|
+
|
|
30
43
|
// Zod mirrors of the provider's dynamic tool schemas; the provider validates again.
|
|
31
44
|
const handoffList = z.array(z.string().min(1)).max(100).optional();
|
|
32
45
|
const taskIds = z.array(z.string().min(1)).max(50).optional();
|
|
@@ -62,6 +75,15 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
|
|
|
62
75
|
scope: z.enum(['project', 'user']),
|
|
63
76
|
lesson: z.string().min(1).max(600),
|
|
64
77
|
},
|
|
78
|
+
alp_lesson_curate: {
|
|
79
|
+
changes: z.array(z.object({
|
|
80
|
+
scope: z.enum(['project', 'user']),
|
|
81
|
+
remove: z.array(z.string().min(1).max(600)).min(1).max(50),
|
|
82
|
+
add: z.string().min(1).max(600).optional(),
|
|
83
|
+
reason: z.string().max(300).optional(),
|
|
84
|
+
}).strict()).min(1).max(50),
|
|
85
|
+
requestId: z.string().min(1).max(100).optional(),
|
|
86
|
+
},
|
|
65
87
|
alp_skill: {
|
|
66
88
|
name: z.string().min(1),
|
|
67
89
|
description: z.string().min(1).max(300),
|
|
@@ -107,9 +129,10 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
|
|
|
107
129
|
kind: z.enum(GATE_KINDS as [string, ...string[]]).optional(),
|
|
108
130
|
until: z.string().min(1).optional(),
|
|
109
131
|
ref: z.string().min(1).optional(),
|
|
132
|
+
options: z.array(z.string().min(1).max(200)).max(10).optional(),
|
|
110
133
|
gate: z.string().min(1).optional(),
|
|
111
134
|
formula: z.string().min(1).optional(),
|
|
112
|
-
vars: z.record(z.string(), z.string()).optional(),
|
|
135
|
+
vars: bounded(z.record(z.string().regex(VAR_NAME), z.string().max(POUR_VARS.string)), POUR_VARS).optional(),
|
|
113
136
|
summary: z.string().min(1).max(2000).optional(),
|
|
114
137
|
unverified: z.string().min(1).max(2000).optional(),
|
|
115
138
|
note: z.string().min(1).max(2000).optional(),
|
|
@@ -120,17 +143,22 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
|
|
|
120
143
|
alp_discard: {
|
|
121
144
|
assignmentId: z.string().min(1),
|
|
122
145
|
},
|
|
146
|
+
alp_resolve: {
|
|
147
|
+
assignmentId: z.string().min(1),
|
|
148
|
+
outcome: z.enum(RESULT_OUTCOMES),
|
|
149
|
+
note: z.string().min(1).max(2000).optional(),
|
|
150
|
+
},
|
|
123
151
|
alp_cancel: {
|
|
124
152
|
assignmentId: z.string().min(1),
|
|
125
153
|
reason: z.string().optional(),
|
|
126
154
|
},
|
|
127
155
|
alp_pin: {
|
|
128
156
|
kind: z.enum(PIN_KINDS),
|
|
129
|
-
body: z.string().min(1),
|
|
130
|
-
paths: z.array(z.string().min(1)).optional(),
|
|
157
|
+
body: z.string().min(1).max(PIN_BODY_CHARS),
|
|
158
|
+
paths: bounded(z.array(z.string().min(1).max(PIN_PATH_CHARS)).max(PIN_PATHS), PIN_PATHS_INPUT).optional(),
|
|
131
159
|
},
|
|
132
160
|
alp_board: {
|
|
133
|
-
kinds: z.array(z.enum(PIN_KINDS)).optional(),
|
|
161
|
+
kinds: bounded(z.array(z.enum(PIN_KINDS)).max(PIN_KINDS.length), BOARD_KINDS_INPUT).optional(),
|
|
134
162
|
limit: z.number().int().positive().optional(),
|
|
135
163
|
},
|
|
136
164
|
alp_unpin: {
|
|
@@ -303,8 +331,18 @@ export function claudePermissions(sandbox: string, currentSandbox?: () => string
|
|
|
303
331
|
// Ask rules make Claude consult canUseTool in every mode, which asks the user.
|
|
304
332
|
...(rules?.ask?.length ? { settings: { permissions: { ask: rules.ask } } } : {}),
|
|
305
333
|
// The floor: Bash runs in the OS sandbox, which writes only the workspace (or nothing, read-only) and temp files, offline.
|
|
334
|
+
// Keep the SDK's restrictive host-network defaults. Broad Unix socket/localhost
|
|
335
|
+
// access lets host services act outside this floor; the SDK cannot scope local
|
|
336
|
+
// binding to a test server, and scoped Unix sockets are not portable to Linux.
|
|
306
337
|
// A command leaves it only with dangerouslyDisableSandbox, which Claude allows itself for allow rules and asks canUseTool otherwise.
|
|
307
|
-
...(rules?.floor ? {
|
|
338
|
+
...(rules?.floor ? {
|
|
339
|
+
sandbox: {
|
|
340
|
+
enabled: true,
|
|
341
|
+
autoAllowBashIfSandboxed: false,
|
|
342
|
+
allowUnsandboxedCommands: true,
|
|
343
|
+
...(rules.floor === 'read-only' && rules.floorRoot ? { filesystem: { denyWrite: [rules.floorRoot] } } : {}),
|
|
344
|
+
},
|
|
345
|
+
} : {}),
|
|
308
346
|
canUseTool: async (name: string, input: Record<string, unknown>, context?: { decisionReasonType?: string; suggestions?: unknown }) => {
|
|
309
347
|
const mode = currentSandbox ? currentSandbox() : sandbox;
|
|
310
348
|
const leaving = Boolean(rules?.floor) && name === 'Bash' && input.dangerouslyDisableSandbox === true;
|
|
@@ -350,7 +388,7 @@ const BOOT_MS = 15_000;
|
|
|
350
388
|
* resumed or forked from another directory). Empty when the session has no transcript yet.
|
|
351
389
|
*/
|
|
352
390
|
export async function claudeChain(sessionId: string, dir?: string): Promise<Array<{ uuid: string; type: 'user' | 'assistant'; toolResult?: boolean }>> {
|
|
353
|
-
const { getSessionMessages } = await
|
|
391
|
+
const { getSessionMessages } = await claudeSdk();
|
|
354
392
|
let messages: any[] = dir ? await getSessionMessages(sessionId, { dir }) : [];
|
|
355
393
|
if (!messages.length) messages = await getSessionMessages(sessionId);
|
|
356
394
|
return messages.filter(message => (message.type === 'user' || message.type === 'assistant') && typeof message.uuid === 'string').map(message => {
|
|
@@ -427,10 +465,27 @@ export class ClaudeTransport {
|
|
|
427
465
|
}
|
|
428
466
|
async initialize() {}
|
|
429
467
|
|
|
468
|
+
/** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
|
|
469
|
+
async probeModels(signal?: AbortSignal) {
|
|
470
|
+
const { query } = await claudeSdk();
|
|
471
|
+
if (signal?.aborted) throw new Error('aborted');
|
|
472
|
+
const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } }) as ClaudeQuery;
|
|
473
|
+
// A probe that outlives its bound is closed, so a hanging Claude process never stays behind.
|
|
474
|
+
const stop = () => probe.close();
|
|
475
|
+
signal?.addEventListener('abort', stop);
|
|
476
|
+
try {
|
|
477
|
+
const models = await probe.supportedModels();
|
|
478
|
+
return models.map(model => ({ id: model.value, label: model.displayName, description: model.description, efforts: model.supportedEffortLevels ?? undefined }));
|
|
479
|
+
} finally {
|
|
480
|
+
signal?.removeEventListener('abort', stop);
|
|
481
|
+
probe.close();
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
430
485
|
/** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
|
|
431
486
|
private async probeUsage() {
|
|
432
487
|
if (this.closed) return undefined;
|
|
433
|
-
const { query } = await
|
|
488
|
+
const { query } = await claudeSdk();
|
|
434
489
|
const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } }) as ClaudeQuery;
|
|
435
490
|
try {
|
|
436
491
|
return await probe.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
|
|
@@ -466,7 +521,7 @@ export class ClaudeTransport {
|
|
|
466
521
|
if (method === 'thread/chain') return { entries: await claudeChain(params.threadId, params.cwd ?? this.cwd) };
|
|
467
522
|
|
|
468
523
|
if (method === 'thread/delete') {
|
|
469
|
-
const { deleteSession } = await
|
|
524
|
+
const { deleteSession } = await claudeSdk();
|
|
470
525
|
await deleteSession(params.threadId, params.cwd ? { dir: params.cwd } : {});
|
|
471
526
|
return {};
|
|
472
527
|
}
|
|
@@ -516,6 +571,20 @@ export class ClaudeTransport {
|
|
|
516
571
|
return method === 'turn/start' ? { turn: { id: turnId } } : {};
|
|
517
572
|
}
|
|
518
573
|
|
|
574
|
+
// t-0e56: Claude compacts on its /compact command, a turn of its own with what the summary must keep.
|
|
575
|
+
if (method === 'thread/compact/start') {
|
|
576
|
+
if (!this.query) throw new Error('Claude thread is not initialized');
|
|
577
|
+
if (this.activeTurn) throw new Error('A turn is running');
|
|
578
|
+
const turnId = randomUUID();
|
|
579
|
+
this.clearAssistantText();
|
|
580
|
+
this.activeTurn = turnId;
|
|
581
|
+
this.turnsStarted = true;
|
|
582
|
+
this.emit('turn/started', { threadId: this.threadId, turn: { id: turnId } });
|
|
583
|
+
const instructions = typeof params.instructions === 'string' ? ` ${params.instructions.trim()}` : '';
|
|
584
|
+
this.input.push({ type: 'user', message: { role: 'user', content: `/compact${instructions}` }, parent_tool_use_id: null, uuid: turnId, session_id: this.threadId });
|
|
585
|
+
return {};
|
|
586
|
+
}
|
|
587
|
+
|
|
519
588
|
if (method === 'turn/interrupt') {
|
|
520
589
|
this.streamingMessage = undefined;
|
|
521
590
|
await this.query?.interrupt();
|
|
@@ -561,7 +630,7 @@ export class ClaudeTransport {
|
|
|
561
630
|
}
|
|
562
631
|
|
|
563
632
|
private async start(from?: { resume: string; fork: boolean; at?: string }) {
|
|
564
|
-
const { createSdkMcpServer, query, tool } = await
|
|
633
|
+
const { createSdkMcpServer, query, tool } = await claudeSdk();
|
|
565
634
|
const config = this.config!;
|
|
566
635
|
const mcpServers = this.convertMcp(config.mcpServers);
|
|
567
636
|
|
package/src/compact.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Main's compaction (t-0e56): at a turn boundary, once main's context fills to the
|
|
3
|
+
* threshold (or the user asks), ALP has main write a checkpoint by skill `compact`,
|
|
4
|
+
* then compacts with the runtime's own mechanism (Claude's /compact, Codex's
|
|
5
|
+
* thread/compact/start), or else starts a fresh conversation seeded with the checkpoint.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export interface CompactSettings { auto: boolean; threshold: number }
|
|
9
|
+
|
|
10
|
+
export const COMPACT_DEFAULTS: CompactSettings = Object.freeze({ auto: true, threshold: 0.7 });
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* settings.json `compact`: { auto?: boolean, threshold?: number in (0, 1) }; anything else keeps the default.
|
|
14
|
+
* The threshold is a share of the window main works in: the agent's autocompact or context setting when
|
|
15
|
+
* set, else the model's context window, as the context advisory measures it.
|
|
16
|
+
*/
|
|
17
|
+
export function compactSettings(raw: unknown): CompactSettings {
|
|
18
|
+
const value = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw as Record<string, unknown> : {};
|
|
19
|
+
const auto = typeof value.auto === 'boolean' ? value.auto : COMPACT_DEFAULTS.auto;
|
|
20
|
+
const threshold = typeof value.threshold === 'number' && Number.isFinite(value.threshold) && value.threshold > 0 && value.threshold < 1 ? value.threshold : COMPACT_DEFAULTS.threshold;
|
|
21
|
+
return { auto, threshold };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** How full the context is, 0..1, from a runtime's token usage; undefined when the window is unknown. */
|
|
25
|
+
export function contextFill(usage: any): number | undefined {
|
|
26
|
+
const used = usage?.last?.totalTokens;
|
|
27
|
+
const window = usage?.modelContextWindow;
|
|
28
|
+
if (typeof used !== 'number' || typeof window !== 'number' || window <= 0) return undefined;
|
|
29
|
+
return used / window;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Whether an idle root should compact now. */
|
|
33
|
+
export function compactDue(settings: CompactSettings, fill: number | undefined, requested: boolean): 'auto' | 'manual' | undefined {
|
|
34
|
+
if (requested) return 'manual';
|
|
35
|
+
if (settings.auto && typeof fill === 'number' && fill >= settings.threshold) return 'auto';
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Runtimes that compact a conversation in place. */
|
|
40
|
+
export const NATIVE_COMPACT = ['claude', 'codex'];
|
|
41
|
+
|
|
42
|
+
export const CHECKPOINT_MARK = 'ALP compact checkpoint';
|
|
43
|
+
|
|
44
|
+
export function checkpointPrompt(trigger: 'auto' | 'manual', fill?: number) {
|
|
45
|
+
const why = trigger === 'manual' ? 'The user asked to compact your context.' : `Your context is about ${Math.round((fill ?? 0) * 100)}% full.`;
|
|
46
|
+
return `${CHECKPOINT_MARK}: ${why} ALP compacts it after this turn. Write a checkpoint now following skill compact (read its SKILL.md): check the facts with alp_task, alp_board and gh where it applies, then reply with the checkpoint alone, in its sections: skip the skill's notice to the user, ALP posts it. Do not start new work, delegate, wait or ask in this turn.`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What the runtime's native compaction is told to keep. */
|
|
50
|
+
export function compactInstructions(checkpoint: string) {
|
|
51
|
+
return `Keep this checkpoint verbatim in the summary; it is the state of the work:\n${checkpoint}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The first prompt of a fresh conversation that replaces a full one. */
|
|
55
|
+
export function seedPrompt(checkpoint: string, lastUser?: string) {
|
|
56
|
+
return [
|
|
57
|
+
'Your context was compacted: ALP started this conversation fresh. Your instructions are unchanged. This is the checkpoint you wrote before, by skill compact:',
|
|
58
|
+
checkpoint,
|
|
59
|
+
...(lastUser ? [`The user's last message before the compaction, verbatim:\n${lastUser}`] : []),
|
|
60
|
+
'Read alp_task and alp_board again (and gh for PR/CI) before reporting status, then carry on. If nothing waits for you, end the turn.',
|
|
61
|
+
].join('\n\n');
|
|
62
|
+
}
|
package/src/configure.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* the effective configuration a resolved session runs with, and what of it can run commands.
|
|
5
5
|
*/
|
|
6
6
|
import { createHash } from 'node:crypto';
|
|
7
|
-
import {
|
|
7
|
+
import { entries } from './catalog.js';
|
|
8
8
|
import { profileModel } from '@anhlp/alp-core/profiles';
|
|
9
9
|
import type { ConfigureChange, EffectiveConfig } from '@anhlp/alp-protocol/session';
|
|
10
10
|
import type { ResolvedSession, RuntimeKind } from './resolve.js';
|
|
@@ -30,13 +30,13 @@ export function nativeModelOf(runtime: RuntimeKind, model: string): { model: str
|
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
/**
|
|
33
|
-
* Whether the host offers `model` on `runtime`: ALP's catalog (
|
|
33
|
+
* Whether the host offers `model` on `runtime`: ALP's live catalog (catalog.ts entries, what library.models and
|
|
34
34
|
* catalog.get list), a model the project's settings give an agent of the team, or the model the session
|
|
35
35
|
* runs already. Never an arbitrary string.
|
|
36
36
|
*/
|
|
37
37
|
export function offered(runtime: RuntimeKind, model: string, mapping: ResolvedSession) {
|
|
38
38
|
if (model === mapping.model) return true;
|
|
39
|
-
if (
|
|
39
|
+
if (entries.some(entry => entry.runtime === runtime && entry.id === model)) return true;
|
|
40
40
|
return Object.values(mapping.modelProfiles ?? {}).flat().some(profile => profileModel(profile) === `${runtime}:${model}`);
|
|
41
41
|
}
|
|
42
42
|
|
package/src/contracts.ts
CHANGED
|
@@ -51,6 +51,8 @@ export type RuntimeOptions = {
|
|
|
51
51
|
checkInMs?: number;
|
|
52
52
|
/** How often the watchdog looks at running assignments; derived from silentForMs and checkInMs when omitted. */
|
|
53
53
|
watchMs?: number;
|
|
54
|
+
/** How often the project tasks are read for gate changes made without alpd, in ms; 0 turns the timer off. Default 5000. */
|
|
55
|
+
gateSyncMs?: number;
|
|
54
56
|
/** How long alp_ask waits for the requester before returning unanswered. */
|
|
55
57
|
askTimeoutMs?: number;
|
|
56
58
|
/** How long alp_ask waits for the user before returning unanswered. Default 30 minutes. */
|
|
@@ -134,6 +136,13 @@ export type AlpRuntime = {
|
|
|
134
136
|
registerWorkspace(directory: string): Promise<void>;
|
|
135
137
|
/** Reserves runtime admission while an external checkout mutation runs. */
|
|
136
138
|
withWorkspaceMutation<T>(directory: string, run: () => Promise<T>): Promise<T>;
|
|
139
|
+
/**
|
|
140
|
+
* Owner-audited adoption of a checkout that predates birth certification (t-c1ba). Under the
|
|
141
|
+
* removal guard's reservation and ownership checks, `verify` must prove the checkout's identity
|
|
142
|
+
* (it throws otherwise); only then is the canonical directory certified. Never call it without
|
|
143
|
+
* the owner's explicit confirmation of the facts `verify` checks.
|
|
144
|
+
*/
|
|
145
|
+
adoptWorkspace?(directory: string, verify: (canonical: string) => Promise<void>): Promise<void>;
|
|
137
146
|
/** Opens a root session under a client-chosen id. */
|
|
138
147
|
open(sessionId: string, spec: SessionSpec, options?: OpenOptions): Promise<SessionSnapshot>;
|
|
139
148
|
/** What a new root would run as, before it opens, and the teams it may choose (ALPD §60). */
|
|
@@ -161,8 +170,15 @@ export type AlpRuntime = {
|
|
|
161
170
|
status(sessionId: string): TreeStatus | undefined;
|
|
162
171
|
/** Questions agents asked the user that wait for an answer. */
|
|
163
172
|
questions(): UserQuestion[];
|
|
164
|
-
/**
|
|
165
|
-
|
|
173
|
+
/**
|
|
174
|
+
* Answers or dismisses a question to the user. A gate card's answer returns a promise that
|
|
175
|
+
* settles once the decision is written, and rejects when it decides nothing: another answer is
|
|
176
|
+
* being recorded or another channel decided first (code GATE_BUSY or GATE_DECIDED), or the
|
|
177
|
+
* write failed (t-595d).
|
|
178
|
+
*/
|
|
179
|
+
answer(questionId: string, reply: { text?: string; dismiss?: boolean; reason?: string; /** Where the user answered a gate card: paseo or web. */ channel?: 'paseo' | 'web' }): void | Promise<void>;
|
|
180
|
+
/** Mirrors the project's open human gates as cards on its main session and tells main of the user's gate decisions, at least once each (t-ccac, t-595d). */
|
|
181
|
+
syncGates?(projectRoot: string): Promise<void>;
|
|
166
182
|
/** Mails a note from the user to any live session, such as an assignment the user wants to redirect. */
|
|
167
183
|
message(sessionId: string, text: string): void;
|
|
168
184
|
/** The project board: live claims, then decisions and findings, oldest first. */
|
|
@@ -171,6 +187,14 @@ export type AlpRuntime = {
|
|
|
171
187
|
pause(input?: { runtime?: RuntimeKind; now?: boolean; reason?: string }): PauseState;
|
|
172
188
|
/** Lifts a pause and continues the assignments it parked. Without a runtime, lifts every pause. */
|
|
173
189
|
resume(input?: { runtime?: RuntimeKind }): PauseState;
|
|
190
|
+
/** alpd's disk takes no writes (t-2831): pauses all of ALP and parks running assignments, unless all of ALP is paused already. */
|
|
191
|
+
holdForDisk(reason: string): PauseState;
|
|
192
|
+
/** Lifts the pause holdForDisk made, keeping usage-limit pauses; a pause the user made stays. */
|
|
193
|
+
releaseDisk(by: string): PauseState;
|
|
194
|
+
/** Whether alpd's disk pause holds ALP now. */
|
|
195
|
+
diskHeld(): boolean;
|
|
196
|
+
/** Tells every open root that disk space runs low. */
|
|
197
|
+
diskLow(free: string): void;
|
|
174
198
|
/** Current pauses and parked assignments. */
|
|
175
199
|
pauses(): PauseState;
|
|
176
200
|
/** Read-only, cached account usage for the web and desktop viewers. */
|
|
@@ -212,6 +236,8 @@ export type AlpRuntime = {
|
|
|
212
236
|
* Emits session.updated.
|
|
213
237
|
*/
|
|
214
238
|
reload?(sessionId: string): Promise<SessionSnapshot>;
|
|
239
|
+
/** Compacts a root's context at its next turn boundary, with a checkpoint main writes by skill compact (t-0e56). */
|
|
240
|
+
compact?(sessionId: string): { status: 'started' | 'deferred' | 'running' };
|
|
215
241
|
/**
|
|
216
242
|
* Holds the turns the runtime would start by itself on this session (mail wakes) while a lifecycle
|
|
217
243
|
* operation changes its conversation (a rewind, later a reload or live configure): mail stays queued
|
package/src/index.ts
CHANGED
|
@@ -6,7 +6,11 @@ export type { BranchRequest, ConversationErrorReason, NativeBase, NativeBinding,
|
|
|
6
6
|
export type { AlpEvent, AlpError, Envelope, SessionSnapshot, TimelineItem, TurnOrigin, AssignmentSnapshot, UserQuestion, TreeStatus, SessionState } from './events.js';
|
|
7
7
|
export { resolveSession, InstructionsAdapter, skillDescription } from './resolve.js';
|
|
8
8
|
export type { SessionSpec, HostMcpServer, ResolvedSession, RuntimeKind } from './resolve.js';
|
|
9
|
-
export { DEFAULT_MODEL, DEFAULT_CLAUDE_MODEL, models, modes, thinkingOptions, thinkingOptionsFor } from './catalog.js';
|
|
9
|
+
export { DEFAULT_MODEL, DEFAULT_CLAUDE_MODEL, entries as catalogEntries, models, modes, thinkingOptions, thinkingOptionsFor } from './catalog.js';
|
|
10
|
+
export type { CatalogEntry } from './catalog.js';
|
|
11
|
+
export { ModelCatalog, mergeCatalog, liveFromContext, feedCatalog, setActiveCatalog, activeCatalog, POLICY as CATALOG_POLICY, REFRESH_MS as CATALOG_REFRESH_MS } from './model-catalog.js';
|
|
12
|
+
export type { CatalogSnapshot, CatalogRuntime, LiveModel, Probe as CatalogProbe } from './model-catalog.js';
|
|
13
|
+
export { liveProbes, codexProbe, claudeProbe, antigravityProbe, parseAgyModels } from './model-probes.js';
|
|
10
14
|
export { CodexTransport } from './transport.js';
|
|
11
15
|
export { ATTACHMENT_HEADER, ATTACHMENT_ROUTES, attachmentStageDir, createAttachmentStager, stagingExposure } from './attachments.js';
|
|
12
16
|
export type { AttachmentReader, AttachmentRoute } from './attachments.js';
|
|
@@ -18,10 +22,13 @@ export type { AntigravityProvider } from './antigravity-transport.js';
|
|
|
18
22
|
export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, skillPlugin, SKILL_PLUGIN, toolShapes as claudeToolShapes } from './claude-transport.js';
|
|
19
23
|
export { MAIL_BATCH_CHARS, MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from './mailbox.js';
|
|
20
24
|
export type { MailEvent, MailKind } from './mailbox.js';
|
|
21
|
-
export { createCopy, gitEnvironment, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
|
|
25
|
+
export { createCopy, gitEnvironment, reattachWorktree, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
|
|
26
|
+
export type { LeftWorktree } from './workspace.js';
|
|
22
27
|
export { OWN_START, processStartedAt, sameProcessAlive } from './process-info.js';
|
|
23
28
|
export type { Worktree, WorktreeChange } from './workspace.js';
|
|
24
29
|
export { PIN_KINDS, renderBoard, renderPin } from './board.js';
|
|
30
|
+
export { inputLimitError, TOOL_INPUT, POUR_VARS } from './input-limits.js';
|
|
31
|
+
export type { InputLimits } from './input-limits.js';
|
|
25
32
|
export { CHOICES, isVietnamese, languageInstruction, words } from './language.js';
|
|
26
33
|
export type { Words } from './language.js';
|
|
27
34
|
export type { Pin, PinKind } from './board.js';
|
|
@@ -30,3 +37,4 @@ export { ProviderRegistry, createProviderRegistry } from './providers.js';
|
|
|
30
37
|
export type { ProviderContext, ProviderFactory, ProviderFactories } from './providers.js';
|
|
31
38
|
export { acpToolDetail, antigravityToolDetail, boundDetail, claudeToolDetail, clipText, codexToolCall, stripReadGutter, toolError, DETAIL_FILE_PATHS, DETAIL_TEXT_CHARS, DETAIL_WEB_RESULTS, ERROR_CHARS, TOOL_FAILED } from './tool-detail.js';
|
|
32
39
|
export type { AcpCall, ClaudeResult, CodexToolCall, ToolCallDetail } from './tool-detail.js';
|
|
40
|
+
export { checkpointPrompt, compactDue, compactSettings, contextFill, seedPrompt, COMPACT_DEFAULTS } from './compact.js';
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Size caps for values that reach ALP from a provider or an external MCP server, checked
|
|
3
|
+
* before any schema walks them. Zod before 4.6.6 walks every element of an array before it
|
|
4
|
+
* reports the array's .max(), and a record has no bound at all, so a cap stated only in a
|
|
5
|
+
* schema still costs time and memory in proportion to the input. This walk stops at the first
|
|
6
|
+
* cap the value passes, so its own cost is bounded by the caps, not by the value.
|
|
7
|
+
*/
|
|
8
|
+
export type InputLimits = {
|
|
9
|
+
/** UTF-8 bytes of the value as JSON, roughly: strings, keys and separators. */
|
|
10
|
+
bytes: number;
|
|
11
|
+
/** Array elements and object keys, counted over the whole value. */
|
|
12
|
+
items: number;
|
|
13
|
+
/** Arrays and objects inside each other; 1 admits a flat list or object of scalars. */
|
|
14
|
+
depth: number;
|
|
15
|
+
/** Characters in any one string, keys included. */
|
|
16
|
+
string: number;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** The arguments of any ALP tool. The longest declared field is alp_delegate's 32,000-character task. */
|
|
20
|
+
export const TOOL_INPUT: InputLimits = { bytes: 1024 * 1024, items: 5_000, depth: 8, string: 128 * 1024 };
|
|
21
|
+
|
|
22
|
+
/** alp_task pour's vars: a flat object of text, one value per variable the formula declares. */
|
|
23
|
+
export const POUR_VARS: InputLimits = { bytes: 128 * 1024, items: 50, depth: 1, string: 2_000 };
|
|
24
|
+
/** A formula variable's name, as validateFormula admits it. */
|
|
25
|
+
export const VAR_NAME = /^[\w-]{1,64}$/;
|
|
26
|
+
|
|
27
|
+
/** The first cap `value` passes, as an error that names `what`, or undefined within them. */
|
|
28
|
+
export function inputLimitError(value: unknown, limits: InputLimits, what = 'The input'): string | undefined {
|
|
29
|
+
let bytes = 0;
|
|
30
|
+
let items = 0;
|
|
31
|
+
const stack: Array<[unknown, number]> = [[value, 0]];
|
|
32
|
+
const tooLarge = `${what} is too large: over ${limits.bytes} bytes`;
|
|
33
|
+
const text = (string: string) => {
|
|
34
|
+
if (string.length > limits.string) return `${what} is too large: a text over ${limits.string} characters`;
|
|
35
|
+
bytes += Buffer.byteLength(string) + 2;
|
|
36
|
+
return bytes > limits.bytes ? tooLarge : undefined;
|
|
37
|
+
};
|
|
38
|
+
while (stack.length) {
|
|
39
|
+
const [current, depth] = stack.pop()!;
|
|
40
|
+
if (typeof current === 'string') {
|
|
41
|
+
const error = text(current);
|
|
42
|
+
if (error) return error;
|
|
43
|
+
} else if (current !== null && typeof current === 'object') {
|
|
44
|
+
if (depth >= limits.depth) return `${what} is too large: nested over ${limits.depth} levels deep`;
|
|
45
|
+
bytes += 2;
|
|
46
|
+
const list = Array.isArray(current);
|
|
47
|
+
const keys = list ? undefined : Object.keys(current);
|
|
48
|
+
const size = list ? current.length : keys!.length;
|
|
49
|
+
if (items + size > limits.items) return `${what} is too large: over ${limits.items} values`;
|
|
50
|
+
items += size;
|
|
51
|
+
for (let index = 0; index < size; index++) {
|
|
52
|
+
if (keys) {
|
|
53
|
+
const error = text(keys[index]);
|
|
54
|
+
if (error) return error;
|
|
55
|
+
}
|
|
56
|
+
bytes += 1;
|
|
57
|
+
stack.push([list ? current[index] : (current as Record<string, unknown>)[keys![index]], depth + 1]);
|
|
58
|
+
}
|
|
59
|
+
} else {
|
|
60
|
+
bytes += String(current).length;
|
|
61
|
+
}
|
|
62
|
+
if (bytes > limits.bytes) return tooLarge;
|
|
63
|
+
}
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|