@anhlp/alp-runtime 0.0.1-beta.3 → 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 +52 -0
- package/dist/assignment-results.js +169 -0
- package/dist/attachments.d.ts +84 -0
- package/dist/attachments.js +213 -0
- 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 +35 -0
- package/dist/claude-transport.js +152 -10
- 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 +185 -4
- package/dist/contracts.js +11 -0
- package/dist/conversation.d.ts +45 -0
- package/dist/conversation.js +62 -0
- package/dist/index.d.ts +15 -4
- package/dist/index.js +40 -3
- 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/mailbox.d.ts +2 -0
- package/dist/mailbox.js +3 -1
- 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 +9 -0
- package/dist/runtime.js +1547 -142
- package/dist/session-config.d.ts +279 -0
- package/dist/session-config.js +10 -10
- package/dist/session-state.d.ts +44 -6
- package/dist/tools.d.ts +119 -0
- package/dist/tools.js +72 -5
- package/dist/transport.js +3 -1
- package/dist/workspace.d.ts +11 -4
- package/dist/workspace.js +29 -11
- package/dist/worktree-domain.d.ts +2 -1
- package/dist/worktree-domain.js +4 -1
- package/package.json +11 -3
- package/src/acp-transport.ts +7 -37
- package/src/antigravity-transport.ts +95 -53
- package/src/assignment-results.ts +146 -0
- package/src/attachments.ts +254 -0
- package/src/board-domain.ts +2 -2
- package/src/board.ts +7 -0
- package/src/catalog.ts +10 -1
- package/src/claude-transport.ts +171 -11
- package/src/compact.ts +62 -0
- package/src/configure.ts +93 -0
- package/src/contracts.ts +172 -5
- package/src/conversation.ts +81 -0
- package/src/index.ts +15 -4
- package/src/input-limits.ts +65 -0
- package/src/language.ts +18 -0
- package/src/mailbox.ts +4 -1
- 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 +1681 -151
- package/src/session-config.ts +9 -9
- package/src/session-state.ts +29 -2
- package/src/tools.ts +69 -5
- package/src/transport.ts +3 -1
- package/src/workspace.ts +42 -15
- package/src/worktree-domain.ts +5 -1
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,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';
|
|
@@ -24,8 +26,16 @@ type ClaudeQuery = AsyncGenerator<SDKMessage, void> & {
|
|
|
24
26
|
interrupt(): Promise<unknown>;
|
|
25
27
|
setPermissionMode(mode: 'default' | 'acceptEdits' | 'bypassPermissions'): Promise<void>;
|
|
26
28
|
close(): void;
|
|
29
|
+
initializationResult?(): Promise<unknown>;
|
|
27
30
|
};
|
|
28
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
|
+
|
|
29
39
|
// Zod mirrors of the provider's dynamic tool schemas; the provider validates again.
|
|
30
40
|
const handoffList = z.array(z.string().min(1)).max(100).optional();
|
|
31
41
|
const taskIds = z.array(z.string().min(1)).max(50).optional();
|
|
@@ -61,6 +71,15 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
|
|
|
61
71
|
scope: z.enum(['project', 'user']),
|
|
62
72
|
lesson: z.string().min(1).max(600),
|
|
63
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
|
+
},
|
|
64
83
|
alp_skill: {
|
|
65
84
|
name: z.string().min(1),
|
|
66
85
|
description: z.string().min(1).max(300),
|
|
@@ -80,6 +99,14 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
|
|
|
80
99
|
issue: z.number().int().positive().optional(),
|
|
81
100
|
labels: z.array(z.string().min(1).max(50)).max(10).optional(),
|
|
82
101
|
},
|
|
102
|
+
alp_schedule: {
|
|
103
|
+
action: z.enum(['create', 'list', 'get', 'cancel']),
|
|
104
|
+
dueAt: z.string().min(1).max(80).optional(),
|
|
105
|
+
prompt: z.string().min(1).max(8000).optional(),
|
|
106
|
+
requestId: z.string().min(1).max(200).optional(),
|
|
107
|
+
id: z.string().min(1).optional(),
|
|
108
|
+
status: z.enum(['pending', 'delivered', 'failed', 'cancelled']).optional(),
|
|
109
|
+
},
|
|
83
110
|
alp_task: {
|
|
84
111
|
action: z.enum(['create', 'update', 'link', 'start', 'close', 'reopen', 'gate', 'clear', 'pour', 'formulas', 'show', 'list', 'ready']),
|
|
85
112
|
id: z.string().min(1).optional(),
|
|
@@ -98,9 +125,10 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
|
|
|
98
125
|
kind: z.enum(GATE_KINDS as [string, ...string[]]).optional(),
|
|
99
126
|
until: z.string().min(1).optional(),
|
|
100
127
|
ref: z.string().min(1).optional(),
|
|
128
|
+
options: z.array(z.string().min(1).max(200)).max(10).optional(),
|
|
101
129
|
gate: z.string().min(1).optional(),
|
|
102
130
|
formula: z.string().min(1).optional(),
|
|
103
|
-
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(),
|
|
104
132
|
summary: z.string().min(1).max(2000).optional(),
|
|
105
133
|
unverified: z.string().min(1).max(2000).optional(),
|
|
106
134
|
note: z.string().min(1).max(2000).optional(),
|
|
@@ -111,17 +139,22 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
|
|
|
111
139
|
alp_discard: {
|
|
112
140
|
assignmentId: z.string().min(1),
|
|
113
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
|
+
},
|
|
114
147
|
alp_cancel: {
|
|
115
148
|
assignmentId: z.string().min(1),
|
|
116
149
|
reason: z.string().optional(),
|
|
117
150
|
},
|
|
118
151
|
alp_pin: {
|
|
119
152
|
kind: z.enum(PIN_KINDS),
|
|
120
|
-
body: z.string().min(1),
|
|
121
|
-
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(),
|
|
122
155
|
},
|
|
123
156
|
alp_board: {
|
|
124
|
-
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(),
|
|
125
158
|
limit: z.number().int().positive().optional(),
|
|
126
159
|
},
|
|
127
160
|
alp_unpin: {
|
|
@@ -294,8 +327,18 @@ export function claudePermissions(sandbox: string, currentSandbox?: () => string
|
|
|
294
327
|
// Ask rules make Claude consult canUseTool in every mode, which asks the user.
|
|
295
328
|
...(rules?.ask?.length ? { settings: { permissions: { ask: rules.ask } } } : {}),
|
|
296
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.
|
|
297
333
|
// A command leaves it only with dangerouslyDisableSandbox, which Claude allows itself for allow rules and asks canUseTool otherwise.
|
|
298
|
-
...(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
|
+
} : {}),
|
|
299
342
|
canUseTool: async (name: string, input: Record<string, unknown>, context?: { decisionReasonType?: string; suggestions?: unknown }) => {
|
|
300
343
|
const mode = currentSandbox ? currentSandbox() : sandbox;
|
|
301
344
|
const leaving = Boolean(rules?.floor) && name === 'Bash' && input.dangerouslyDisableSandbox === true;
|
|
@@ -332,6 +375,25 @@ export function claudePermissions(sandbox: string, currentSandbox?: () => string
|
|
|
332
375
|
export const claudeLimited = (info?: { status: string; overageStatus?: string }) =>
|
|
333
376
|
info?.status === 'rejected' && info.overageStatus !== 'allowed' && info.overageStatus !== 'allowed_warning';
|
|
334
377
|
|
|
378
|
+
/** How long a resume waits for Claude to start before it goes on (ClaudeTransport.booted). */
|
|
379
|
+
const BOOT_MS = 15_000;
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* A Claude session's main chain, read from its transcript by the Agent SDK: user and assistant entries
|
|
383
|
+
* in order, with their transcript uuids. Found under `dir`'s project, else in any project (a session
|
|
384
|
+
* resumed or forked from another directory). Empty when the session has no transcript yet.
|
|
385
|
+
*/
|
|
386
|
+
export async function claudeChain(sessionId: string, dir?: string): Promise<Array<{ uuid: string; type: 'user' | 'assistant'; toolResult?: boolean }>> {
|
|
387
|
+
const { getSessionMessages } = await import(CLAUDE_SDK);
|
|
388
|
+
let messages: any[] = dir ? await getSessionMessages(sessionId, { dir }) : [];
|
|
389
|
+
if (!messages.length) messages = await getSessionMessages(sessionId);
|
|
390
|
+
return messages.filter(message => (message.type === 'user' || message.type === 'assistant') && typeof message.uuid === 'string').map(message => {
|
|
391
|
+
const content = message.message?.content;
|
|
392
|
+
const toolResult = message.type === 'user' && Array.isArray(content) && content.length > 0 && content.every((block: any) => block?.type === 'tool_result');
|
|
393
|
+
return { uuid: message.uuid, type: message.type, ...(toolResult ? { toolResult: true } : {}) };
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
|
|
335
397
|
/** Maps Claude Agent SDK streaming sessions to the normalized runtime protocol. */
|
|
336
398
|
export class ClaudeTransport {
|
|
337
399
|
private listeners = new Set<Listener>();
|
|
@@ -359,6 +421,12 @@ export class ClaudeTransport {
|
|
|
359
421
|
private compaction?: string;
|
|
360
422
|
/** The plugin directory that loads the agent's skills, removed on close. */
|
|
361
423
|
private skillDirectory?: string;
|
|
424
|
+
/** Whether a turn ran in this process; before one, an error result is a boot refusal. */
|
|
425
|
+
private turnsStarted = false;
|
|
426
|
+
/** Rejects when the process fails, for a resume that waits for Claude to start. */
|
|
427
|
+
private bootFailure?: Promise<never>;
|
|
428
|
+
private rejectBoot?: (error: Error) => void;
|
|
429
|
+
private bootError?: Error;
|
|
362
430
|
|
|
363
431
|
constructor(
|
|
364
432
|
private readonly command: string,
|
|
@@ -393,6 +461,23 @@ export class ClaudeTransport {
|
|
|
393
461
|
}
|
|
394
462
|
async initialize() {}
|
|
395
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
|
+
|
|
396
481
|
/** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
|
|
397
482
|
private async probeUsage() {
|
|
398
483
|
if (this.closed) return undefined;
|
|
@@ -429,6 +514,8 @@ export class ClaudeTransport {
|
|
|
429
514
|
return {};
|
|
430
515
|
}
|
|
431
516
|
|
|
517
|
+
if (method === 'thread/chain') return { entries: await claudeChain(params.threadId, params.cwd ?? this.cwd) };
|
|
518
|
+
|
|
432
519
|
if (method === 'thread/delete') {
|
|
433
520
|
const { deleteSession } = await import(CLAUDE_SDK);
|
|
434
521
|
await deleteSession(params.threadId, params.cwd ? { dir: params.cwd } : {});
|
|
@@ -437,11 +524,17 @@ export class ClaudeTransport {
|
|
|
437
524
|
|
|
438
525
|
if (method === 'thread/start' || method === 'thread/resume' || method === 'thread/fork') {
|
|
439
526
|
this.clearAssistantText();
|
|
440
|
-
|
|
527
|
+
const { base, requireHistory, ...config } = params as NativeConfig & { base?: { threadId: string; at?: string }; requireHistory?: boolean };
|
|
528
|
+
this.config = config as NativeConfig;
|
|
441
529
|
this.threadId =
|
|
442
530
|
method === 'thread/resume' ? params.threadId : randomUUID();
|
|
443
531
|
// A fork resumes the thread's history under a new id, leaving the thread itself unchanged.
|
|
444
|
-
|
|
532
|
+
const from = method === 'thread/start' ? undefined
|
|
533
|
+
: method === 'thread/resume' ? await this.resumeFrom(params.threadId, base, requireHistory)
|
|
534
|
+
: { resume: params.threadId, fork: true };
|
|
535
|
+
await this.start(from);
|
|
536
|
+
// A resume Claude refuses at boot (a missing session, a cut it cannot make) fails this request, not a later turn.
|
|
537
|
+
if (method === 'thread/resume' && (base || requireHistory)) await this.booted();
|
|
445
538
|
return {
|
|
446
539
|
thread: { id: this.threadId, turns: [] },
|
|
447
540
|
cwd: this.cwd,
|
|
@@ -458,6 +551,7 @@ export class ClaudeTransport {
|
|
|
458
551
|
if (method === 'turn/start') {
|
|
459
552
|
this.clearAssistantText();
|
|
460
553
|
this.activeTurn = turnId;
|
|
554
|
+
this.turnsStarted = true;
|
|
461
555
|
}
|
|
462
556
|
this.input.push({
|
|
463
557
|
type: 'user',
|
|
@@ -466,12 +560,27 @@ export class ClaudeTransport {
|
|
|
466
560
|
content: params.input.map(claudeContent),
|
|
467
561
|
},
|
|
468
562
|
parent_tool_use_id: null,
|
|
469
|
-
|
|
563
|
+
// A turn's prompt entry in the transcript carries the turn's id, so ALP can cut the conversation at it (§12.7).
|
|
564
|
+
uuid: method === 'turn/start' ? turnId : randomUUID(),
|
|
470
565
|
session_id: this.threadId,
|
|
471
566
|
});
|
|
472
567
|
return method === 'turn/start' ? { turn: { id: turnId } } : {};
|
|
473
568
|
}
|
|
474
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
|
+
|
|
475
584
|
if (method === 'turn/interrupt') {
|
|
476
585
|
this.streamingMessage = undefined;
|
|
477
586
|
await this.query?.interrupt();
|
|
@@ -481,7 +590,42 @@ export class ClaudeTransport {
|
|
|
481
590
|
throw new Error(`Unsupported Claude runtime operation '${method}'`);
|
|
482
591
|
}
|
|
483
592
|
|
|
484
|
-
|
|
593
|
+
/**
|
|
594
|
+
* How a resume starts. With a base, a session whose transcript does not exist yet is made from the
|
|
595
|
+
* base's conversation cut at `at` (a fork or rewind, §12.7): Claude writes it, under this session's
|
|
596
|
+
* id, only when its first prompt runs. Otherwise, the session's own transcript.
|
|
597
|
+
*/
|
|
598
|
+
private async resumeFrom(threadId: string, base?: { threadId: string; at?: string }, requireHistory?: boolean) {
|
|
599
|
+
const own = base || requireHistory ? await claudeChain(threadId, this.config!.cwd) : [];
|
|
600
|
+
if (!base || own.length) {
|
|
601
|
+
if (requireHistory && !own.length) throw new Error(`Claude session ${threadId} not found`);
|
|
602
|
+
return { resume: threadId, fork: false };
|
|
603
|
+
}
|
|
604
|
+
const source = await claudeChain(base.threadId, this.config!.cwd);
|
|
605
|
+
if (!source.length) throw new Error(`Claude session ${base.threadId} not found`);
|
|
606
|
+
if (base.at && !source.some(entry => entry.uuid === base.at)) throw new Error(`Claude session ${base.threadId} has no entry ${base.at}`);
|
|
607
|
+
return { resume: base.threadId, fork: true, at: base.at };
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Waits until Claude has started: its answer to the SDK's initialize request, or the failure that
|
|
612
|
+
* ends it first. Past BOOT_MS ALP goes on, as any resume does, and a later refusal fails the session.
|
|
613
|
+
*/
|
|
614
|
+
private async booted() {
|
|
615
|
+
let timer: NodeJS.Timeout | undefined;
|
|
616
|
+
try {
|
|
617
|
+
await Promise.race([
|
|
618
|
+
this.query!.initializationResult?.().then(() => undefined, () => undefined),
|
|
619
|
+
this.bootFailure,
|
|
620
|
+
new Promise<void>(resolve => { timer = setTimeout(resolve, BOOT_MS); }),
|
|
621
|
+
]);
|
|
622
|
+
} finally { clearTimeout(timer); }
|
|
623
|
+
// A refusal can arrive with the answer itself; let the stream deliver it.
|
|
624
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
625
|
+
if (this.bootError) throw this.bootError;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
private async start(from?: { resume: string; fork: boolean; at?: string }) {
|
|
485
629
|
const { createSdkMcpServer, query, tool } = await import(CLAUDE_SDK);
|
|
486
630
|
const config = this.config!;
|
|
487
631
|
const mcpServers = this.convertMcp(config.mcpServers);
|
|
@@ -583,11 +727,13 @@ export class ClaudeTransport {
|
|
|
583
727
|
persistSession: !config.ephemeral,
|
|
584
728
|
promptSuggestions: false,
|
|
585
729
|
includePartialMessages: true,
|
|
586
|
-
...(from ? { resume: from.resume, ...(from.fork ? { forkSession: true, sessionId: this.threadId } : {}) } : { sessionId: this.threadId }),
|
|
730
|
+
...(from ? { resume: from.resume, ...(from.fork ? { forkSession: true, sessionId: this.threadId } : {}), ...(from.at ? { resumeSessionAt: from.at } : {}) } : { sessionId: this.threadId }),
|
|
587
731
|
// Explicit native path avoids SDK optional binaries inside Electron app.asar.
|
|
588
732
|
pathToClaudeCodeExecutable: this.command,
|
|
589
733
|
};
|
|
590
734
|
|
|
735
|
+
this.bootFailure = new Promise<never>((_, reject) => { this.rejectBoot = reject; });
|
|
736
|
+
this.bootFailure.catch(() => {});
|
|
591
737
|
this.query = query({ prompt: this.input, options }) as ClaudeQuery;
|
|
592
738
|
this.pump = this.consume(this.query).catch((error) => this.fail(error));
|
|
593
739
|
void this.measureContext();
|
|
@@ -667,6 +813,8 @@ export class ClaudeTransport {
|
|
|
667
813
|
return;
|
|
668
814
|
}
|
|
669
815
|
if (message.type === 'assistant' && message.error === 'rate_limit') this.limitedTurn = true;
|
|
816
|
+
// The model Claude Code says it runs this query with (its init message), so ALP can show it took a configured one (§12.9).
|
|
817
|
+
if (message.type === 'system' && message.subtype === 'init' && typeof (message as any).model === 'string') this.emit('alp/nativeModel', { threadId: this.threadId, model: (message as any).model });
|
|
670
818
|
// A compaction, reported as Codex reports one: a contextCompaction item from start to end (ALPD §57).
|
|
671
819
|
if (message.type === 'system' && (message.subtype === 'status' || message.subtype === 'compact_boundary')) {
|
|
672
820
|
const system = message as any;
|
|
@@ -779,6 +927,12 @@ export class ClaudeTransport {
|
|
|
779
927
|
return;
|
|
780
928
|
}
|
|
781
929
|
|
|
930
|
+
// Before any turn, an error result is Claude refusing to start the session (a resume it rejected).
|
|
931
|
+
// The SDK then ends the stream with this error, which fails the transport as before.
|
|
932
|
+
if (message.type === 'result' && message.is_error && !this.activeTurn && !this.turnsStarted) {
|
|
933
|
+
this.refuseBoot(new Error(message.errors?.length ? message.errors.join('; ') : 'Claude refused to start the session'));
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
782
936
|
if (message.type === 'result') this.clearAssistantText();
|
|
783
937
|
if (message.type === 'result' && this.activeTurn) {
|
|
784
938
|
const turnId = this.activeTurn;
|
|
@@ -803,6 +957,11 @@ export class ClaudeTransport {
|
|
|
803
957
|
}
|
|
804
958
|
}
|
|
805
959
|
|
|
960
|
+
private refuseBoot(error: Error) {
|
|
961
|
+
this.bootError ??= error;
|
|
962
|
+
this.rejectBoot?.(error);
|
|
963
|
+
}
|
|
964
|
+
|
|
806
965
|
private emit(method: string, params: any) {
|
|
807
966
|
for (const listener of this.listeners) listener(method, params);
|
|
808
967
|
}
|
|
@@ -822,6 +981,7 @@ export class ClaudeTransport {
|
|
|
822
981
|
if (this.closed) return;
|
|
823
982
|
this.clearAssistantText();
|
|
824
983
|
const error = value instanceof Error ? value : new Error(String(value));
|
|
984
|
+
this.refuseBoot(error);
|
|
825
985
|
for (const listener of this.failures) listener(error);
|
|
826
986
|
}
|
|
827
987
|
|
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
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live configure of a root (docs/protocol/alp-json-rpc-v1.md §12.9, issue #121 branch D): the pure
|
|
3
|
+
* parts. What a model a client names means for a session's runtime, which models the host offers,
|
|
4
|
+
* the effective configuration a resolved session runs with, and what of it can run commands.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { entries } from './catalog.js';
|
|
8
|
+
import { profileModel } from '@anhlp/alp-core/profiles';
|
|
9
|
+
import type { ConfigureChange, EffectiveConfig } from '@anhlp/alp-protocol/session';
|
|
10
|
+
import type { ResolvedSession, RuntimeKind } from './resolve.js';
|
|
11
|
+
|
|
12
|
+
export type { ConfigureChange, EffectiveConfig } from '@anhlp/alp-protocol/session';
|
|
13
|
+
|
|
14
|
+
/** What a client may change on a live root; each absent field keeps the session's own. */
|
|
15
|
+
export type ConfigureChanges = { model?: string; thinking?: string; team?: string; mode?: string };
|
|
16
|
+
|
|
17
|
+
/** Runtimes whose roots alpd reconfigures live (macOS and Linux; Codex and Claude, issue #121 closure scope). */
|
|
18
|
+
export const CONFIGURABLE: ReadonlySet<RuntimeKind> = new Set(['codex', 'claude'] as RuntimeKind[]);
|
|
19
|
+
|
|
20
|
+
const PREFIXED = /^(codex|claude|antigravity|acp)[:/](.*)$/s;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The native model `model` names for a session of `runtime`: unprefixed, or prefixed with that runtime
|
|
24
|
+
* (`codex:`, `claude:`, or with a slash). A prefix of another runtime is a migration, never taken.
|
|
25
|
+
*/
|
|
26
|
+
export function nativeModelOf(runtime: RuntimeKind, model: string): { model: string } | { runtime: string } {
|
|
27
|
+
const match = PREFIXED.exec(model);
|
|
28
|
+
if (!match) return { model };
|
|
29
|
+
return match[1] === runtime ? { model: match[2] } : { runtime: match[1] };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Whether the host offers `model` on `runtime`: ALP's live catalog (catalog.ts entries, what library.models and
|
|
34
|
+
* catalog.get list), a model the project's settings give an agent of the team, or the model the session
|
|
35
|
+
* runs already. Never an arbitrary string.
|
|
36
|
+
*/
|
|
37
|
+
export function offered(runtime: RuntimeKind, model: string, mapping: ResolvedSession) {
|
|
38
|
+
if (model === mapping.model) return true;
|
|
39
|
+
if (entries.some(entry => entry.runtime === runtime && entry.id === model)) return true;
|
|
40
|
+
return Object.values(mapping.modelProfiles ?? {}).flat().some(profile => profileModel(profile) === `${runtime}:${model}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** MCP servers of a resolved session by name and kind: a stdio one runs a command on the host. */
|
|
44
|
+
export function mcpOf(mapping: ResolvedSession): EffectiveConfig['mcpServers'] {
|
|
45
|
+
return Object.entries(mapping.mcp ?? {}).map(([name, server]) => ({ name, kind: server && typeof server === 'object' && 'command' in (server as object) ? 'stdio' as const : 'http' as const }));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* What of a resolved session runs commands on the daemon host: its stdio MCP servers (command, args,
|
|
52
|
+
* env names) and its hooks (event and command), each as a digest. A change may keep or drop these,
|
|
53
|
+
* never add one (a team change that brings an executable resource is refused).
|
|
54
|
+
*/
|
|
55
|
+
export function executablesOf(mapping: ResolvedSession): Set<string> {
|
|
56
|
+
const found = new Set<string>();
|
|
57
|
+
for (const [name, server] of Object.entries(mapping.mcp ?? {}) as Array<[string, any]>) {
|
|
58
|
+
if (server && typeof server === 'object' && 'command' in server) found.add(`mcp:${name}:${digest([server.command, server.args ?? [], Object.keys(server.env ?? {}).sort()])}`);
|
|
59
|
+
}
|
|
60
|
+
for (const hook of (mapping.hooks ?? []) as Array<{ name?: string; event?: unknown; command?: unknown }>) found.add(`hook:${hook.name ?? ''}:${digest([hook.event, hook.command])}`);
|
|
61
|
+
return found;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The effective configuration of a resolved root, with its delegation targets, ALP tools and instructions digest. */
|
|
65
|
+
export function effectiveOf(runtime: RuntimeKind, mapping: ResolvedSession, extra: { delegates: string[]; tools: string[]; supervisor: boolean; instructionsSha?: string }): EffectiveConfig {
|
|
66
|
+
return {
|
|
67
|
+
team: mapping.workflow.mode,
|
|
68
|
+
...(mapping.team?.label ? { teamLabel: mapping.team.label } : {}),
|
|
69
|
+
agent: mapping.agent.name,
|
|
70
|
+
runtime,
|
|
71
|
+
model: mapping.model,
|
|
72
|
+
thinking: mapping.thinking,
|
|
73
|
+
mode: mapping.mode,
|
|
74
|
+
...(mapping.permissions?.name ? { permissionProfile: mapping.permissions.name } : {}),
|
|
75
|
+
supervisor: extra.supervisor,
|
|
76
|
+
maxPeers: mapping.workflow.maxPeers,
|
|
77
|
+
delegates: [...extra.delegates],
|
|
78
|
+
tools: [...extra.tools],
|
|
79
|
+
mcpServers: mcpOf(mapping),
|
|
80
|
+
hooks: (mapping.hooks ?? []).length,
|
|
81
|
+
...(extra.instructionsSha ? { instructionsSha: extra.instructionsSha } : {}),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Which of model, thinking, team and mode differ between two effective configurations. */
|
|
86
|
+
export function changesOf(current: EffectiveConfig, proposed: EffectiveConfig): ConfigureChange[] {
|
|
87
|
+
const changes: ConfigureChange[] = [];
|
|
88
|
+
if (current.model !== proposed.model) changes.push('model');
|
|
89
|
+
if (current.thinking !== proposed.thinking) changes.push('thinking');
|
|
90
|
+
if (current.team !== proposed.team) changes.push('team');
|
|
91
|
+
if (current.mode !== proposed.mode) changes.push('mode');
|
|
92
|
+
return changes;
|
|
93
|
+
}
|