@anhlp/alp-runtime 0.0.1-beta.4 → 0.0.1-beta.5
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 +65 -6
- 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 +25 -1
- package/dist/index.d.ts +9 -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 +605 -45
- 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 +11 -4
- package/dist/workspace.js +29 -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 +71 -6
- package/src/compact.ts +62 -0
- package/src/configure.ts +3 -3
- package/src/contracts.ts +22 -1
- package/src/index.ts +9 -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 +650 -46
- 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 +42 -15
package/src/claude-transport.ts
CHANGED
|
@@ -5,7 +5,9 @@ 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';
|
|
@@ -27,6 +29,13 @@ type ClaudeQuery = AsyncGenerator<SDKMessage, void> & {
|
|
|
27
29
|
initializationResult?(): Promise<unknown>;
|
|
28
30
|
};
|
|
29
31
|
|
|
32
|
+
/** A field whose size is checked before zod walks it; its JSON Schema is the inner schema's (input-limits.ts). */
|
|
33
|
+
const bounded = <T extends z.ZodType>(schema: T, limits: InputLimits) => z.preprocess((value, ctx) => {
|
|
34
|
+
const error = inputLimitError(value, limits);
|
|
35
|
+
if (error) ctx.addIssue({ code: 'custom', message: error });
|
|
36
|
+
return value;
|
|
37
|
+
}, schema);
|
|
38
|
+
|
|
30
39
|
// Zod mirrors of the provider's dynamic tool schemas; the provider validates again.
|
|
31
40
|
const handoffList = z.array(z.string().min(1)).max(100).optional();
|
|
32
41
|
const taskIds = z.array(z.string().min(1)).max(50).optional();
|
|
@@ -62,6 +71,15 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
|
|
|
62
71
|
scope: z.enum(['project', 'user']),
|
|
63
72
|
lesson: z.string().min(1).max(600),
|
|
64
73
|
},
|
|
74
|
+
alp_lesson_curate: {
|
|
75
|
+
changes: z.array(z.object({
|
|
76
|
+
scope: z.enum(['project', 'user']),
|
|
77
|
+
remove: z.array(z.string().min(1).max(600)).min(1).max(50),
|
|
78
|
+
add: z.string().min(1).max(600).optional(),
|
|
79
|
+
reason: z.string().max(300).optional(),
|
|
80
|
+
}).strict()).min(1).max(50),
|
|
81
|
+
requestId: z.string().min(1).max(100).optional(),
|
|
82
|
+
},
|
|
65
83
|
alp_skill: {
|
|
66
84
|
name: z.string().min(1),
|
|
67
85
|
description: z.string().min(1).max(300),
|
|
@@ -107,9 +125,10 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
|
|
|
107
125
|
kind: z.enum(GATE_KINDS as [string, ...string[]]).optional(),
|
|
108
126
|
until: z.string().min(1).optional(),
|
|
109
127
|
ref: z.string().min(1).optional(),
|
|
128
|
+
options: z.array(z.string().min(1).max(200)).max(10).optional(),
|
|
110
129
|
gate: z.string().min(1).optional(),
|
|
111
130
|
formula: z.string().min(1).optional(),
|
|
112
|
-
vars: z.record(z.string(), z.string()).optional(),
|
|
131
|
+
vars: bounded(z.record(z.string().regex(VAR_NAME), z.string().max(POUR_VARS.string)), POUR_VARS).optional(),
|
|
113
132
|
summary: z.string().min(1).max(2000).optional(),
|
|
114
133
|
unverified: z.string().min(1).max(2000).optional(),
|
|
115
134
|
note: z.string().min(1).max(2000).optional(),
|
|
@@ -120,17 +139,22 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
|
|
|
120
139
|
alp_discard: {
|
|
121
140
|
assignmentId: z.string().min(1),
|
|
122
141
|
},
|
|
142
|
+
alp_resolve: {
|
|
143
|
+
assignmentId: z.string().min(1),
|
|
144
|
+
outcome: z.enum(RESULT_OUTCOMES),
|
|
145
|
+
note: z.string().min(1).max(2000).optional(),
|
|
146
|
+
},
|
|
123
147
|
alp_cancel: {
|
|
124
148
|
assignmentId: z.string().min(1),
|
|
125
149
|
reason: z.string().optional(),
|
|
126
150
|
},
|
|
127
151
|
alp_pin: {
|
|
128
152
|
kind: z.enum(PIN_KINDS),
|
|
129
|
-
body: z.string().min(1),
|
|
130
|
-
paths: z.array(z.string().min(1)).optional(),
|
|
153
|
+
body: z.string().min(1).max(PIN_BODY_CHARS),
|
|
154
|
+
paths: bounded(z.array(z.string().min(1).max(PIN_PATH_CHARS)).max(PIN_PATHS), PIN_PATHS_INPUT).optional(),
|
|
131
155
|
},
|
|
132
156
|
alp_board: {
|
|
133
|
-
kinds: z.array(z.enum(PIN_KINDS)).optional(),
|
|
157
|
+
kinds: bounded(z.array(z.enum(PIN_KINDS)).max(PIN_KINDS.length), BOARD_KINDS_INPUT).optional(),
|
|
134
158
|
limit: z.number().int().positive().optional(),
|
|
135
159
|
},
|
|
136
160
|
alp_unpin: {
|
|
@@ -303,8 +327,18 @@ export function claudePermissions(sandbox: string, currentSandbox?: () => string
|
|
|
303
327
|
// Ask rules make Claude consult canUseTool in every mode, which asks the user.
|
|
304
328
|
...(rules?.ask?.length ? { settings: { permissions: { ask: rules.ask } } } : {}),
|
|
305
329
|
// The floor: Bash runs in the OS sandbox, which writes only the workspace (or nothing, read-only) and temp files, offline.
|
|
330
|
+
// Keep the SDK's restrictive host-network defaults. Broad Unix socket/localhost
|
|
331
|
+
// access lets host services act outside this floor; the SDK cannot scope local
|
|
332
|
+
// binding to a test server, and scoped Unix sockets are not portable to Linux.
|
|
306
333
|
// A command leaves it only with dangerouslyDisableSandbox, which Claude allows itself for allow rules and asks canUseTool otherwise.
|
|
307
|
-
...(rules?.floor ? {
|
|
334
|
+
...(rules?.floor ? {
|
|
335
|
+
sandbox: {
|
|
336
|
+
enabled: true,
|
|
337
|
+
autoAllowBashIfSandboxed: false,
|
|
338
|
+
allowUnsandboxedCommands: true,
|
|
339
|
+
...(rules.floor === 'read-only' && rules.floorRoot ? { filesystem: { denyWrite: [rules.floorRoot] } } : {}),
|
|
340
|
+
},
|
|
341
|
+
} : {}),
|
|
308
342
|
canUseTool: async (name: string, input: Record<string, unknown>, context?: { decisionReasonType?: string; suggestions?: unknown }) => {
|
|
309
343
|
const mode = currentSandbox ? currentSandbox() : sandbox;
|
|
310
344
|
const leaving = Boolean(rules?.floor) && name === 'Bash' && input.dangerouslyDisableSandbox === true;
|
|
@@ -427,6 +461,23 @@ export class ClaudeTransport {
|
|
|
427
461
|
}
|
|
428
462
|
async initialize() {}
|
|
429
463
|
|
|
464
|
+
/** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
|
|
465
|
+
async probeModels(signal?: AbortSignal) {
|
|
466
|
+
const { query } = await import(CLAUDE_SDK);
|
|
467
|
+
if (signal?.aborted) throw new Error('aborted');
|
|
468
|
+
const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } }) as ClaudeQuery;
|
|
469
|
+
// A probe that outlives its bound is closed, so a hanging Claude process never stays behind.
|
|
470
|
+
const stop = () => probe.close();
|
|
471
|
+
signal?.addEventListener('abort', stop);
|
|
472
|
+
try {
|
|
473
|
+
const models = await probe.supportedModels();
|
|
474
|
+
return models.map(model => ({ id: model.value, label: model.displayName, description: model.description, efforts: model.supportedEffortLevels ?? undefined }));
|
|
475
|
+
} finally {
|
|
476
|
+
signal?.removeEventListener('abort', stop);
|
|
477
|
+
probe.close();
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
430
481
|
/** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
|
|
431
482
|
private async probeUsage() {
|
|
432
483
|
if (this.closed) return undefined;
|
|
@@ -516,6 +567,20 @@ export class ClaudeTransport {
|
|
|
516
567
|
return method === 'turn/start' ? { turn: { id: turnId } } : {};
|
|
517
568
|
}
|
|
518
569
|
|
|
570
|
+
// t-0e56: Claude compacts on its /compact command, a turn of its own with what the summary must keep.
|
|
571
|
+
if (method === 'thread/compact/start') {
|
|
572
|
+
if (!this.query) throw new Error('Claude thread is not initialized');
|
|
573
|
+
if (this.activeTurn) throw new Error('A turn is running');
|
|
574
|
+
const turnId = randomUUID();
|
|
575
|
+
this.clearAssistantText();
|
|
576
|
+
this.activeTurn = turnId;
|
|
577
|
+
this.turnsStarted = true;
|
|
578
|
+
this.emit('turn/started', { threadId: this.threadId, turn: { id: turnId } });
|
|
579
|
+
const instructions = typeof params.instructions === 'string' ? ` ${params.instructions.trim()}` : '';
|
|
580
|
+
this.input.push({ type: 'user', message: { role: 'user', content: `/compact${instructions}` }, parent_tool_use_id: null, uuid: turnId, session_id: this.threadId });
|
|
581
|
+
return {};
|
|
582
|
+
}
|
|
583
|
+
|
|
519
584
|
if (method === 'turn/interrupt') {
|
|
520
585
|
this.streamingMessage = undefined;
|
|
521
586
|
await this.query?.interrupt();
|
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). */
|
|
@@ -162,7 +171,9 @@ export type AlpRuntime = {
|
|
|
162
171
|
/** Questions agents asked the user that wait for an answer. */
|
|
163
172
|
questions(): UserQuestion[];
|
|
164
173
|
/** Answers or dismisses a question to the user. */
|
|
165
|
-
answer(questionId: string, reply: { text?: string; dismiss?: boolean; reason?: string }): void;
|
|
174
|
+
answer(questionId: string, reply: { text?: string; dismiss?: boolean; reason?: string; /** Where the user answered a gate card: paseo or web. */ channel?: 'paseo' | 'web' }): void;
|
|
175
|
+
/** Mirrors the project's open human gates as cards on its main session and tells main of the user's gate decisions, once each (t-ccac). */
|
|
176
|
+
syncGates?(projectRoot: string): Promise<void>;
|
|
166
177
|
/** Mails a note from the user to any live session, such as an assignment the user wants to redirect. */
|
|
167
178
|
message(sessionId: string, text: string): void;
|
|
168
179
|
/** The project board: live claims, then decisions and findings, oldest first. */
|
|
@@ -171,6 +182,14 @@ export type AlpRuntime = {
|
|
|
171
182
|
pause(input?: { runtime?: RuntimeKind; now?: boolean; reason?: string }): PauseState;
|
|
172
183
|
/** Lifts a pause and continues the assignments it parked. Without a runtime, lifts every pause. */
|
|
173
184
|
resume(input?: { runtime?: RuntimeKind }): PauseState;
|
|
185
|
+
/** alpd's disk takes no writes (t-2831): pauses all of ALP and parks running assignments, unless all of ALP is paused already. */
|
|
186
|
+
holdForDisk(reason: string): PauseState;
|
|
187
|
+
/** Lifts the pause holdForDisk made, keeping usage-limit pauses; a pause the user made stays. */
|
|
188
|
+
releaseDisk(by: string): PauseState;
|
|
189
|
+
/** Whether alpd's disk pause holds ALP now. */
|
|
190
|
+
diskHeld(): boolean;
|
|
191
|
+
/** Tells every open root that disk space runs low. */
|
|
192
|
+
diskLow(free: string): void;
|
|
174
193
|
/** Current pauses and parked assignments. */
|
|
175
194
|
pauses(): PauseState;
|
|
176
195
|
/** Read-only, cached account usage for the web and desktop viewers. */
|
|
@@ -212,6 +231,8 @@ export type AlpRuntime = {
|
|
|
212
231
|
* Emits session.updated.
|
|
213
232
|
*/
|
|
214
233
|
reload?(sessionId: string): Promise<SessionSnapshot>;
|
|
234
|
+
/** Compacts a root's context at its next turn boundary, with a checkpoint main writes by skill compact (t-0e56). */
|
|
235
|
+
compact?(sessionId: string): { status: 'started' | 'deferred' | 'running' };
|
|
215
236
|
/**
|
|
216
237
|
* Holds the turns the runtime would start by itself on this session (mail wakes) while a lifecycle
|
|
217
238
|
* 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,12 @@ 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';
|
|
22
26
|
export { OWN_START, processStartedAt, sameProcessAlive } from './process-info.js';
|
|
23
27
|
export type { Worktree, WorktreeChange } from './workspace.js';
|
|
24
28
|
export { PIN_KINDS, renderBoard, renderPin } from './board.js';
|
|
29
|
+
export { inputLimitError, TOOL_INPUT, POUR_VARS } from './input-limits.js';
|
|
30
|
+
export type { InputLimits } from './input-limits.js';
|
|
25
31
|
export { CHOICES, isVietnamese, languageInstruction, words } from './language.js';
|
|
26
32
|
export type { Words } from './language.js';
|
|
27
33
|
export type { Pin, PinKind } from './board.js';
|
|
@@ -30,3 +36,4 @@ export { ProviderRegistry, createProviderRegistry } from './providers.js';
|
|
|
30
36
|
export type { ProviderContext, ProviderFactory, ProviderFactories } from './providers.js';
|
|
31
37
|
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
38
|
export type { AcpCall, ClaudeResult, CodexToolCall, ToolCallDetail } from './tool-detail.js';
|
|
39
|
+
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
|
+
}
|
package/src/language.ts
CHANGED
|
@@ -18,6 +18,11 @@ const en = {
|
|
|
18
18
|
`${agent} wants to ${create ? `open an issue in ${where}` : `comment on issue #${issue} in ${where}`}. ` +
|
|
19
19
|
'It is posted with your GitHub account, and anyone who can see the repository can read it.',
|
|
20
20
|
issueTitle: 'Title',
|
|
21
|
+
lessonCurate: (agent: string, changes: string) =>
|
|
22
|
+
`${agent} proposes to curate the lessons files. Approve to apply every change below at once; nothing else changes.\n\n${changes}`,
|
|
23
|
+
lessonRemove: 'Remove',
|
|
24
|
+
lessonAdd: 'Add',
|
|
25
|
+
lessonScope: (scope: string, file: string) => `${scope === 'user' ? 'User lessons' : 'Project lessons'} (${file})`,
|
|
21
26
|
issueLabels: 'Labels',
|
|
22
27
|
trust: (project: string, names: string) => `This project's hooks run shell commands from ${project} on your machine: ${names}. ` +
|
|
23
28
|
'Trust this workspace\'s hooks? ALP asks once: after you agree, its hooks run without asking, including hooks added or changed later.',
|
|
@@ -33,10 +38,14 @@ const en = {
|
|
|
33
38
|
limitReached: (runtime: string, resetsAt: string | undefined, other: string | undefined, autoResume: boolean, kind: string) =>
|
|
34
39
|
`${runtime} usage limit reached${resetsAt ? `; it resets ${resetsAt}` : ''}. ALP paused delegation to ${runtime} agents and parked their assignments${other ? `; ${other} agents keep working` : ''}. ${autoResume ? `ALP asks ${runtime} every minute and resumes it as soon as the limit lifts.` : `ALP asks ${runtime} every minute and tells you when the limit lifts; then run alp resume ${kind}.`}`,
|
|
35
40
|
limitLifted: (runtime: string, kind: string) => `${runtime} says its usage limit has lifted. Run alp resume ${kind} to continue its work.`,
|
|
41
|
+
compacted: (native: boolean) => `Main's context was compacted${native ? '' : ' into a fresh conversation'}; it keeps its checkpoint and carries on.`,
|
|
42
|
+
compactFailed: (reason: string) => `Compacting main's context failed (${reason}); ALP tries again later.`,
|
|
36
43
|
usageWarning: (runtime: string, used: string, resetsAt: string | undefined) => `${runtime} has used ${used} of a usage window${resetsAt ? ` that resets ${resetsAt}` : ''}.`,
|
|
37
44
|
/** The web app's answer to a Paseo feature ALP has not got yet (ALPD §62). */
|
|
38
45
|
inDevelopment: 'This feature is in development',
|
|
39
46
|
resumed: (what: string, by: string, parked: boolean) => `${what} resumed by ${by}.${parked ? ' Parked assignments continue.' : ''}`,
|
|
47
|
+
diskFull: (reason: string) => `Disk full: ${reason}. ALP paused its work and parked running assignments; it keeps answering. Free some space (alp doctor lists leftover worktrees); ALP checks every minute and continues by itself, or run alp resume.`,
|
|
48
|
+
diskLow: (free: string) => `Disk space is low: ${free} free. Free some space before it fills (alp doctor lists leftover worktrees); when it is full, ALP pauses its work.`,
|
|
40
49
|
paused: (what: string, reason: string | undefined, runtime: string | undefined, now: boolean) =>
|
|
41
50
|
`${what} paused by the user${reason ? `: ${reason}` : ''}. Delegation${runtime ? ` to ${runtime} agents` : ''} waits${now ? ', and running assignments park where they are' : '; running turns finish'}. alp resume continues.`,
|
|
42
51
|
};
|
|
@@ -58,6 +67,11 @@ const vi: Words = {
|
|
|
58
67
|
`${agent} muốn ${create ? `mở một issue trong ${where}` : `bình luận vào issue #${issue} trong ${where}`}. ` +
|
|
59
68
|
'Nội dung được đăng bằng tài khoản GitHub của bạn, ai xem được repository đều đọc được.',
|
|
60
69
|
issueTitle: 'Tiêu đề',
|
|
70
|
+
lessonCurate: (agent, changes) =>
|
|
71
|
+
`${agent} đề xuất rà soát file bài học. Duyệt để áp dụng cùng lúc mọi thay đổi dưới đây; không thay đổi gì khác.\n\n${changes}`,
|
|
72
|
+
lessonRemove: 'Bỏ',
|
|
73
|
+
lessonAdd: 'Thêm',
|
|
74
|
+
lessonScope: (scope, file) => `${scope === 'user' ? 'Bài học của người dùng' : 'Bài học của project'} (${file})`,
|
|
61
75
|
issueLabels: 'Nhãn',
|
|
62
76
|
trust: (project, names) => `Các hook của project này chạy lệnh shell từ ${project} trên máy của bạn: ${names}. ` +
|
|
63
77
|
'Tin cậy các hook của workspace này? ALP chỉ hỏi một lần: khi bạn đồng ý, các hook chạy mà không hỏi lại, kể cả hook thêm hoặc sửa sau này.',
|
|
@@ -73,9 +87,13 @@ const vi: Words = {
|
|
|
73
87
|
limitReached: (runtime, resetsAt, other, autoResume, kind) =>
|
|
74
88
|
`${runtime} đã hết hạn mức sử dụng${resetsAt ? `; hạn mức đặt lại lúc ${resetsAt}` : ''}. ALP tạm dừng giao việc cho các agent ${runtime} và tạm giữ việc của chúng${other ? `; các agent ${other} vẫn làm tiếp` : ''}. ${autoResume ? `ALP hỏi ${runtime} mỗi phút và tự chạy lại ngay khi có hạn mức.` : `ALP hỏi ${runtime} mỗi phút và báo khi có hạn mức trở lại; khi đó chạy alp resume ${kind}.`}`,
|
|
75
89
|
limitLifted: (runtime, kind) => `${runtime} báo đã có hạn mức trở lại. Chạy alp resume ${kind} để làm tiếp việc của nó.`,
|
|
90
|
+
compacted: native => `Context của main đã được compact${native ? '' : ' sang một cuộc hội thoại mới'}; main giữ checkpoint và làm tiếp.`,
|
|
91
|
+
compactFailed: reason => `Compact context của main thất bại (${reason}); ALP sẽ thử lại sau.`,
|
|
76
92
|
usageWarning: (runtime, used, resetsAt) => `${runtime} đã dùng ${used} hạn mức của kỳ này${resetsAt ? `, kỳ đặt lại lúc ${resetsAt}` : ''}.`,
|
|
77
93
|
inDevelopment: 'Tính năng đang phát triển',
|
|
78
94
|
resumed: (what, by, parked) => `${what} đã chạy lại, bởi ${by}.${parked ? ' Các việc đang tạm giữ được làm tiếp.' : ''}`,
|
|
95
|
+
diskFull: reason => `Đĩa đầy: ${reason === 'the disk is full' ? 'đĩa hết dung lượng' : reason === 'the disk is read-only' ? 'đĩa chỉ đọc' : reason}. ALP đã tạm dừng công việc và tạm giữ các việc đang chạy; ALP vẫn trả lời. Hãy giải phóng dung lượng (alp doctor liệt kê các worktree còn sót); ALP kiểm tra mỗi phút và tự làm tiếp, hoặc chạy alp resume.`,
|
|
96
|
+
diskLow: free => `Đĩa sắp đầy: còn ${free} trống. Hãy giải phóng dung lượng trước khi đầy (alp doctor liệt kê các worktree còn sót); khi đĩa đầy, ALP sẽ tạm dừng công việc.`,
|
|
79
97
|
paused: (what, reason, runtime, now) =>
|
|
80
98
|
`${what} đã bị người dùng tạm dừng${reason ? `: ${reason}` : ''}. Việc giao${runtime ? ` cho các agent ${runtime}` : ''} phải chờ${now ? ', các việc đang chạy được tạm giữ tại chỗ' : '; các lượt đang chạy vẫn chạy hết'}. Chạy alp resume để tiếp tục.`,
|
|
81
99
|
};
|
package/src/mcp-tools.ts
CHANGED
|
@@ -3,9 +3,37 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
|
3
3
|
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
4
4
|
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
5
5
|
|
|
6
|
+
import { inputLimitError, type InputLimits } from './input-limits.js';
|
|
7
|
+
|
|
6
8
|
type Tool = { name: string; description: string; inputSchema: unknown };
|
|
7
9
|
type Server = { command?: string; args?: string[]; env?: Record<string, string>; cwd?: string; url?: string; http_headers?: Record<string, string> };
|
|
8
10
|
|
|
11
|
+
/** What one external MCP server may list: pages of tools/list, and tools over all of them. */
|
|
12
|
+
export const MCP_TOOLS = { pages: 20, tools: 500 };
|
|
13
|
+
/** One tools/list result, checked before the MCP SDK parses it with ListToolsResultSchema. */
|
|
14
|
+
export const MCP_TOOLS_PAGE: InputLimits = { bytes: 4 * 1024 * 1024, items: 100_000, depth: 32, string: 64 * 1024 };
|
|
15
|
+
|
|
16
|
+
/** Turns an oversized tools/list result into an error response before the client parses it.
|
|
17
|
+
* Called after connect, which installs the client's own onmessage. */
|
|
18
|
+
function limitToolPages(transport: Wire) {
|
|
19
|
+
const listing = new Set<string | number>();
|
|
20
|
+
const send = transport.send.bind(transport);
|
|
21
|
+
transport.send = (message, ...rest) => {
|
|
22
|
+
if ('method' in message && message.method === 'tools/list' && 'id' in message) listing.add(message.id);
|
|
23
|
+
return send(message, ...rest);
|
|
24
|
+
};
|
|
25
|
+
const deliver = transport.onmessage;
|
|
26
|
+
transport.onmessage = (message, ...rest) => {
|
|
27
|
+
if ('id' in message && 'result' in message && listing.delete(message.id)) {
|
|
28
|
+
const error = inputLimitError(message.result, MCP_TOOLS_PAGE, 'A tools/list page');
|
|
29
|
+
if (error) return deliver?.({ jsonrpc: '2.0', id: message.id, error: { code: -32600, message: error } }, ...rest);
|
|
30
|
+
}
|
|
31
|
+
deliver?.(message, ...rest);
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
type Message = Parameters<StdioClientTransport['send']>[0];
|
|
35
|
+
type Wire = { send(message: Message, ...rest: unknown[]): Promise<void>; onmessage?(message: Message, ...rest: unknown[]): void };
|
|
36
|
+
|
|
9
37
|
/** Client.connect starts cleanup without awaiting it on initialization failure.
|
|
10
38
|
* Keep that promise so session shutdown waits for the same process cleanup.
|
|
11
39
|
*/
|
|
@@ -38,10 +66,15 @@ export async function openMcpTools(servers: Record<string, Server>, cwd: string,
|
|
|
38
66
|
try {
|
|
39
67
|
await client.connect(transport, { timeout: 20_000, signal });
|
|
40
68
|
if (!client.getServerCapabilities()?.tools) continue;
|
|
69
|
+
limitToolPages(transport);
|
|
41
70
|
let cursor: string | undefined;
|
|
42
71
|
const seen = new Set<string>();
|
|
72
|
+
let listed = 0;
|
|
43
73
|
do {
|
|
74
|
+
if (seen.size >= MCP_TOOLS.pages) throw new Error(`More than ${MCP_TOOLS.pages} pages of MCP tools`);
|
|
44
75
|
const page = await client.listTools(cursor ? { cursor } : {}, { timeout: 20_000, signal });
|
|
76
|
+
listed += page.tools.length;
|
|
77
|
+
if (listed > MCP_TOOLS.tools) throw new Error(`More than ${MCP_TOOLS.tools} MCP tools`);
|
|
45
78
|
for (const tool of page.tools) {
|
|
46
79
|
const hash = createHash('sha256').update(JSON.stringify([name, tool.name])).digest('hex').slice(0, 10);
|
|
47
80
|
const clean = (value: string, length: number) => value.replace(/[^\w-]/g, '_').slice(0, length);
|