@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.
Files changed (80) hide show
  1. package/dist/acp-transport.js +5 -36
  2. package/dist/antigravity-transport.d.ts +17 -0
  3. package/dist/antigravity-transport.js +82 -58
  4. package/dist/assignment-results.d.ts +52 -0
  5. package/dist/assignment-results.js +169 -0
  6. package/dist/attachments.d.ts +84 -0
  7. package/dist/attachments.js +213 -0
  8. package/dist/board-domain.js +2 -2
  9. package/dist/board.d.ts +6 -0
  10. package/dist/board.js +7 -0
  11. package/dist/catalog.d.ts +13 -0
  12. package/dist/catalog.js +9 -1
  13. package/dist/claude-transport.d.ts +35 -0
  14. package/dist/claude-transport.js +152 -10
  15. package/dist/compact.d.ts +29 -0
  16. package/dist/compact.js +49 -0
  17. package/dist/configure.d.ts +44 -0
  18. package/dist/configure.js +64 -0
  19. package/dist/contracts.d.ts +185 -4
  20. package/dist/contracts.js +11 -0
  21. package/dist/conversation.d.ts +45 -0
  22. package/dist/conversation.js +62 -0
  23. package/dist/index.d.ts +15 -4
  24. package/dist/index.js +40 -3
  25. package/dist/input-limits.d.ts +25 -0
  26. package/dist/input-limits.js +48 -0
  27. package/dist/language.d.ts +8 -0
  28. package/dist/language.js +20 -0
  29. package/dist/mailbox.d.ts +2 -0
  30. package/dist/mailbox.js +3 -1
  31. package/dist/mcp-tools.d.ts +8 -0
  32. package/dist/mcp-tools.js +26 -0
  33. package/dist/model-catalog.d.ts +76 -0
  34. package/dist/model-catalog.js +193 -0
  35. package/dist/model-probes.d.ts +7 -0
  36. package/dist/model-probes.js +69 -0
  37. package/dist/providers.js +2 -0
  38. package/dist/resolve.d.ts +1 -0
  39. package/dist/resolve.js +3 -1
  40. package/dist/runtime.d.ts +9 -0
  41. package/dist/runtime.js +1547 -142
  42. package/dist/session-config.d.ts +279 -0
  43. package/dist/session-config.js +10 -10
  44. package/dist/session-state.d.ts +44 -6
  45. package/dist/tools.d.ts +119 -0
  46. package/dist/tools.js +72 -5
  47. package/dist/transport.js +3 -1
  48. package/dist/workspace.d.ts +11 -4
  49. package/dist/workspace.js +29 -11
  50. package/dist/worktree-domain.d.ts +2 -1
  51. package/dist/worktree-domain.js +4 -1
  52. package/package.json +11 -3
  53. package/src/acp-transport.ts +7 -37
  54. package/src/antigravity-transport.ts +95 -53
  55. package/src/assignment-results.ts +146 -0
  56. package/src/attachments.ts +254 -0
  57. package/src/board-domain.ts +2 -2
  58. package/src/board.ts +7 -0
  59. package/src/catalog.ts +10 -1
  60. package/src/claude-transport.ts +171 -11
  61. package/src/compact.ts +62 -0
  62. package/src/configure.ts +93 -0
  63. package/src/contracts.ts +172 -5
  64. package/src/conversation.ts +81 -0
  65. package/src/index.ts +15 -4
  66. package/src/input-limits.ts +65 -0
  67. package/src/language.ts +18 -0
  68. package/src/mailbox.ts +4 -1
  69. package/src/mcp-tools.ts +33 -0
  70. package/src/model-catalog.ts +166 -0
  71. package/src/model-probes.ts +58 -0
  72. package/src/providers.ts +3 -0
  73. package/src/resolve.ts +4 -2
  74. package/src/runtime.ts +1681 -151
  75. package/src/session-config.ts +9 -9
  76. package/src/session-state.ts +29 -2
  77. package/src/tools.ts +69 -5
  78. package/src/transport.ts +3 -1
  79. package/src/workspace.ts +42 -15
  80. package/src/worktree-domain.ts +5 -1
package/src/contracts.ts CHANGED
@@ -7,6 +7,7 @@ import type { ProviderUsage } from './usage.js';
7
7
  import type { AcpProvider } from './acp-transport.js';
8
8
  import type { AntigravityProvider } from './antigravity-transport.js';
9
9
  import type { GitHubRunner } from './github.js';
10
+ import type { AttachmentReader } from './attachments.js';
10
11
 
11
12
  export type RuntimeTransport = {
12
13
  request(method: string, params: any): Promise<any>;
@@ -50,6 +51,8 @@ export type RuntimeOptions = {
50
51
  checkInMs?: number;
51
52
  /** How often the watchdog looks at running assignments; derived from silentForMs and checkInMs when omitted. */
52
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;
53
56
  /** How long alp_ask waits for the requester before returning unanswered. */
54
57
  askTimeoutMs?: number;
55
58
  /** How long alp_ask waits for the user before returning unanswered. Default 30 minutes. */
@@ -67,6 +70,12 @@ export type RuntimeOptions = {
67
70
  /** Where assignments whose profile has workdir copy get their disposable copies. Default: a directory in the temp directory. */
68
71
  copyDir?: string;
69
72
 
73
+ /**
74
+ * Where the runtime stages read-only copies of attached files for its sessions' tools (§12.6):
75
+ * alpd's `<ALP_HOME>/state/staged`. Omitted, no session takes attachment parts.
76
+ */
77
+ attachmentStageDir?: string;
78
+
70
79
  /** Where project boards are kept (JSONL per project). Omitted keeps them in memory only. */
71
80
  boardDir?: string;
72
81
 
@@ -78,6 +87,8 @@ export type RuntimeOptions = {
78
87
 
79
88
  /** Where finished assignments' native threads are recorded for alp_recall. Omitted keeps the record in memory. */
80
89
  recallFile?: string;
90
+ /** Permanent assignment ownership; unlike recall, results never expire. */
91
+ assignmentResultFile?: string;
81
92
 
82
93
  /** Where pauses are kept across restarts. Omitted keeps them in memory. */
83
94
  pauseFile?: string;
@@ -106,21 +117,51 @@ export type RuntimeOptions = {
106
117
  github?: GitHubRunner;
107
118
  };
108
119
 
109
- import type { OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
110
- export type { OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
120
+ import type { NativeBase, OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
121
+ export type { NativeBase, OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
122
+
123
+ export type ScheduleHandler = (action: 'create' | 'list' | 'get' | 'cancel', params: Record<string, unknown>) => Promise<unknown>;
111
124
 
112
125
  export type AlpRuntime = {
126
+ /** The daemon supplies its persistent schedule operations; standalone runtimes have none. */
127
+ bindSchedules?: (handler: ScheduleHandler | undefined) => void;
128
+ /** alpd hands over its attachment reader (§12.6) once, at start; with a staging directory, Codex and Claude sessions then take attachment parts. */
129
+ bindAttachments?: (reader: AttachmentReader | undefined) => void;
130
+ /** Whether this live session's runtime takes `{ type: 'attachment' }` parts (RuntimeAttachment) now. */
131
+ takesAttachments?: (sessionId: string) => boolean;
132
+ /** Removes the staged copy of an attachment alpd no longer keeps. */
133
+ dropAttachment?: (attachmentId: string) => Promise<void>;
113
134
  onEvent(listener: (envelope: Envelope) => void): () => void;
135
+ /** Certifies a brand-new generated checkout; never use to adopt an existing workspace. */
136
+ registerWorkspace(directory: string): Promise<void>;
137
+ /** Reserves runtime admission while an external checkout mutation runs. */
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>;
114
146
  /** Opens a root session under a client-chosen id. */
115
147
  open(sessionId: string, spec: SessionSpec, options?: OpenOptions): Promise<SessionSnapshot>;
116
148
  /** What a new root would run as, before it opens, and the teams it may choose (ALPD §60). */
117
149
  preview(spec: SessionSpec): Promise<SessionPreview>;
118
150
  /** Failures are reported as prompt.failed, once per clientMessageId. */
119
151
  prompt(sessionId: string, input: PromptInput): Promise<void>;
152
+ /**
153
+ * Atomically admits an idle scheduled prompt in the runtime queue. Busy leaves all preparation
154
+ * untouched. The callback may persist its attempt/receipt, then use its single-use sender;
155
+ * the sender is valid only during the callback. Do not enqueue runtime operations in the callback.
156
+ */
157
+ withIdlePrompt?<T>(sessionId: string, run: (send: (input: PromptInput) => Promise<void>) => Promise<T>): Promise<{ busy: true } | { busy: false; value: T }>;
120
158
  /** Cancels the running turn and closes the whole subtree. */
121
159
  interrupt(sessionId: string): Promise<void>;
122
- /** Changes permission mode while idle; undefined keeps the current mode. */
123
- configure(sessionId: string, changes: { mode?: string }): Promise<SessionSnapshot>;
160
+ /** Atomically cancels only this active turn; false leaves the session and subtree untouched. */
161
+ interruptTurn?(sessionId: string, turnId: string): Promise<boolean>;
162
+ /** Changes permission mode while idle; undefined keeps the current mode.
163
+ * onApplied is awaited after apply and before session.updated; failure does not roll back permissions. */
164
+ configure(sessionId: string, changes: { mode?: string }, options?: { onApplied?: (session: SessionSnapshot) => Promise<void> }): Promise<SessionSnapshot>;
124
165
  close(sessionId: string): Promise<void>;
125
166
  snapshot(sessionId: string): SessionSnapshot | undefined;
126
167
  /** Live sessions, roots before their children. */
@@ -130,7 +171,9 @@ export type AlpRuntime = {
130
171
  /** Questions agents asked the user that wait for an answer. */
131
172
  questions(): UserQuestion[];
132
173
  /** Answers or dismisses a question to the user. */
133
- 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>;
134
177
  /** Mails a note from the user to any live session, such as an assignment the user wants to redirect. */
135
178
  message(sessionId: string, text: string): void;
136
179
  /** The project board: live claims, then decisions and findings, oldest first. */
@@ -139,6 +182,14 @@ export type AlpRuntime = {
139
182
  pause(input?: { runtime?: RuntimeKind; now?: boolean; reason?: string }): PauseState;
140
183
  /** Lifts a pause and continues the assignments it parked. Without a runtime, lifts every pause. */
141
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;
142
193
  /** Current pauses and parked assignments. */
143
194
  pauses(): PauseState;
144
195
  /** Read-only, cached account usage for the web and desktop viewers. */
@@ -153,8 +204,124 @@ export type AlpRuntime = {
153
204
  abandon(rootId: string, reason: string): Promise<RecoveryOutcome[]>;
154
205
  /** Closes everything; assignments still running stay in the live file, so the next alpd continues them. */
155
206
  shutdown(): Promise<void>;
207
+ /**
208
+ * Makes the native conversation a fork or rewind continues (docs/protocol/alp-json-rpc-v1.md §12.7): the
209
+ * source's conversation cut at a completed turn, persisted by the runtime and leaving the source
210
+ * unchanged. Touches no live session. Codex forks natively now (thread/fork); Claude validates the
211
+ * cut against the transcript and answers a binding the first prompt forks (NativeBinding.base).
212
+ * Refusals throw a ConversationError; one the runtime may or may not have acted on carries
213
+ * `outcomeUnknown: true`. Absent: the host cannot fork or rewind.
214
+ */
215
+ branch?(request: BranchRequest): Promise<NativeBinding>;
216
+ /**
217
+ * Moves an idle live root to another native conversation (a rewind), or reopens its own (a reload):
218
+ * its native process restarts and resumes `binding`, keeping the session id, its configuration and
219
+ * attached viewers. Refused (ConversationError session_busy) unless the whole tree is idle: no turn,
220
+ * pending prompt, child, assignment, question, mail or parked work. Emits session.updated.
221
+ * When the new binding cannot be opened, the old one is reopened and the error thrown; when neither
222
+ * opens, the session fails as a provider failure does.
223
+ */
224
+ rebind?(sessionId: string, binding: NativeBinding): Promise<SessionSnapshot>;
225
+ /**
226
+ * Restarts an idle live root's native process on the conversation it runs now (a reload, §12.8):
227
+ * the same binding, the session's own configuration, id and viewers. Refused as rebind is. The new
228
+ * process must resume that very conversation (a Claude one is refused unless its transcript, or its
229
+ * base, exists), never an empty one in its place; when it cannot, the session closes with its
230
+ * conversation kept (a later open resumes it) and a ConversationError native_refused is thrown.
231
+ * Emits session.updated.
232
+ */
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' };
236
+ /**
237
+ * Holds the turns the runtime would start by itself on this session (mail wakes) while a lifecycle
238
+ * operation changes its conversation (a rewind, later a reload or live configure): mail stays queued
239
+ * and is delivered when the last hold is released, to whatever conversation the session runs then.
240
+ * rebind does not refuse for mail a hold keeps. Client prompts are not held here; alpd holds them.
241
+ * Undefined when the session is not open.
242
+ */
243
+ hold?(sessionId: string): (() => void) | undefined;
244
+ /**
245
+ * Whether an open session may begin a turn it has no id for yet: its turn/start (a prompt or a mail
246
+ * wake) is reserved, queued or on its way to the native runtime, or its process is opening or restarting. Such a
247
+ * turn shows in `activeTurnId` only once the runtime answers, and a hold taken meanwhile does not
248
+ * stop it. False when the session is not open.
249
+ */
250
+ starting?(sessionId: string): boolean;
251
+ /**
252
+ * What a live root would run with after a change of model, thinking, team or mode (§12.9), and whether
253
+ * reconfigure would take it now; reads only. `teams` are the teams the host defines for its project.
254
+ */
255
+ previewConfigure?(sessionId: string, changes: ConfigureChanges): Promise<ConfigurePreview>;
256
+ /**
257
+ * Changes an idle live root's model, thinking, team or mode (§12.9): resolves the new configuration
258
+ * as session.create would (same runtime, agent and conversation; never more permissions or new
259
+ * executable resources), then restarts its native process with it on the same conversation (`fresh`:
260
+ * a root with no turn yet starts a new, empty one). The session takes the new configuration only
261
+ * once the runtime took it (Codex echoes the model it resumed with); otherwise the old one is
262
+ * restarted and a ConversationError thrown (`outcomeUnknown` when the runtime may have acted). A
263
+ * new team also replaces the root's supervisor. Refused as rebind is while the tree is not idle.
264
+ * `onApplied` lets a host persist the configuration the runtime took before session.updated is
265
+ * emitted. It is awaited only for an applied change; its failure leaves the runtime configured
266
+ * and reports outcomeUnknown (never a rollback or a known native refusal).
267
+ * Emits session.updated after that persistence succeeds.
268
+ */
269
+ reconfigure?(sessionId: string, changes: ConfigureChanges, options?: { fresh?: boolean; onApplied?: (result: ConfigureResult) => Promise<void> }): Promise<ConfigureResult>;
156
270
  };
157
271
 
272
+ import type { ConfigureChanges, EffectiveConfig } from './configure.js';
273
+ export type { ConfigureChanges, EffectiveConfig } from './configure.js';
274
+ import type { ConfigurePreview } from '@anhlp/alp-protocol/session';
275
+ export type { ConfigurePreview } from '@anhlp/alp-protocol/session';
276
+ /** What reconfigure did: the session as it runs now, its effective configuration, and whether its process restarted. */
277
+ export type ConfigureResult = {
278
+ session: SessionSnapshot;
279
+ effective: EffectiveConfig;
280
+ status: 'applied' | 'unchanged';
281
+ restarted: boolean;
282
+ /** What the native runtime answered it runs with (Codex: the resumed thread's model and effort). */
283
+ native?: { model?: string; reasoningEffort?: string };
284
+ };
285
+
286
+ /** The native conversation a session continues: its thread, or for Claude one its first prompt makes from `base`. */
287
+ export type NativeBinding = { threadId: string; base?: NativeBase };
288
+
289
+ export type BranchRequest = {
290
+ runtime: RuntimeKind;
291
+ /** The conversation to branch: the source session's binding. */
292
+ source: NativeBinding;
293
+ /** Where the source session runs (Claude keeps its transcripts by this directory). */
294
+ cwd: string;
295
+ /** Where the branch will run; the source's cwd when absent. */
296
+ targetCwd?: string;
297
+ /** The configuration the branch keeps: Codex otherwise forks with its default model and settings. */
298
+ model: string;
299
+ thinking: string;
300
+ mode: string;
301
+ /**
302
+ * The cut, by ALP turn id (a Codex turn id; a Claude prompt uuid): keep through a completed turn, or
303
+ * everything before a turn. Absent: the whole conversation.
304
+ */
305
+ cutoff?: { throughTurnId: string } | { beforeTurnId: string };
306
+ /** The source root's turns in order, as ALP's timeline has them, for the cut's validation. */
307
+ turns: string[];
308
+ };
309
+
310
+ export type ConversationErrorReason = 'runtime_unsupported' | 'boundary_unmapped' | 'empty_prefix' | 'native_refused' | 'session_busy'
311
+ // A live configure (§12.9).
312
+ | 'runtime_mismatch' | 'agent_mismatch' | 'permission_escalation' | 'team_not_found' | 'invalid_params' | 'not_root';
313
+ /** A fork, rewind or rebind the runtime refused; `outcomeUnknown` when the native runtime may have acted. */
314
+ export class ConversationError extends Error {
315
+ readonly data: { reason: ConversationErrorReason };
316
+ readonly outcomeUnknown: boolean;
317
+ constructor(reason: ConversationErrorReason, message: string, { outcomeUnknown = false } = {}) {
318
+ super(message);
319
+ this.name = 'ConversationError';
320
+ this.data = { reason };
321
+ this.outcomeUnknown = outcomeUnknown;
322
+ }
323
+ }
324
+
158
325
  import type { SessionPreview } from '@anhlp/alp-protocol/session';
159
326
  export type { SessionPreview } from '@anhlp/alp-protocol/session';
160
327
 
@@ -0,0 +1,81 @@
1
+ import { ConversationError, type BranchRequest } from './contracts.js';
2
+
3
+ /**
4
+ * Conversation cuts for fork and rewind (docs/protocol/alp-json-rpc-v1.md §12.7). Pure helpers of
5
+ * runtime.ts's branch(): where a Claude transcript is cut, which Codex turn a fork must end at, and
6
+ * what a Codex refusal means.
7
+ */
8
+
9
+ /** One entry of a Claude session's main chain, as the Agent SDK reads it from the transcript. */
10
+ export type ChainEntry = { uuid: string; type: 'user' | 'assistant'; toolResult?: boolean };
11
+
12
+ const refuse = (reason: ConstructorParameters<typeof ConversationError>[0], message: string, outcomeUnknown = false) =>
13
+ new ConversationError(reason, message, { outcomeUnknown });
14
+
15
+ /** The turn a Codex fork must end at, after ALP's own validation of the cut against its timeline. */
16
+ export function codexForkEnd(request: Pick<BranchRequest, 'cutoff' | 'turns'>) {
17
+ const { cutoff, turns } = request;
18
+ if (!cutoff) {
19
+ if (!turns.length) throw refuse('empty_prefix', 'The conversation has no turn to fork');
20
+ return { last: turns.at(-1)!, params: {} };
21
+ }
22
+ const id = 'beforeTurnId' in cutoff ? cutoff.beforeTurnId : cutoff.throughTurnId;
23
+ const index = turns.indexOf(id);
24
+ if (index < 0) throw refuse('boundary_unmapped', `Turn ${id} is not a turn of this conversation`);
25
+ if ('beforeTurnId' in cutoff) {
26
+ if (index === 0) throw refuse('empty_prefix', 'Nothing comes before the first turn');
27
+ return { last: turns[index - 1], params: { beforeTurnId: id } };
28
+ }
29
+ return { last: id, params: { lastTurnId: id } };
30
+ }
31
+
32
+ /** What a refused thread/fork means; one written but unanswered may have forked. */
33
+ export function codexForkRefusal(error: unknown) {
34
+ if (error instanceof ConversationError) return error;
35
+ const message = error instanceof Error ? error.message : String(error);
36
+ if ((error as { outcomeUnknown?: boolean })?.outcomeUnknown) return refuse('native_refused', `Codex did not answer the fork: ${message}`, true);
37
+ if (/^turn not found\b/i.test(message)) return refuse('boundary_unmapped', `Codex does not know that turn: ${message}`);
38
+ if (/identifies an in-progress turn/i.test(message)) return refuse('session_busy', `The turn is still running: ${message}`);
39
+ return refuse('native_refused', `Codex refused the fork: ${message}`);
40
+ }
41
+
42
+ /**
43
+ * The chain uuid a Claude fork resumes at (`resumeSessionAt`): the last entry kept. ALP turn ids are
44
+ * the prompt uuids it gave Claude, so a turn starts at its prompt entry and runs to the next ALP turn's
45
+ * prompt; entries of a turn Claude started itself belong to the turn before it. Always a pinned entry,
46
+ * never "everything", so turns the source adds later never reach a branch made before them.
47
+ */
48
+ export function claudeCut(chain: ChainEntry[], request: Pick<BranchRequest, 'cutoff' | 'turns'>): string {
49
+ const { cutoff, turns } = request;
50
+ const position = new Map(chain.map((entry, index) => [entry.uuid, index]));
51
+ const prompt = (id: string) => {
52
+ const index = position.get(id);
53
+ return index !== undefined && chain[index].type === 'user' && !chain[index].toolResult ? index : undefined;
54
+ };
55
+ if (!cutoff) {
56
+ if (!chain.length) throw refuse('empty_prefix', 'The conversation has no turn to fork');
57
+ return chain.at(-1)!.uuid;
58
+ }
59
+ const id = 'beforeTurnId' in cutoff ? cutoff.beforeTurnId : cutoff.throughTurnId;
60
+ const turn = turns.indexOf(id);
61
+ const at = prompt(id);
62
+ if (turn < 0 || at === undefined) throw refuse('boundary_unmapped', `Turn ${id} is not a turn of this conversation's transcript`);
63
+ // ALP's turns found in the transcript must come in ALP's order, or the cut would not be what ALP shows.
64
+ const found = turns.map(prompt).filter((index): index is number => index !== undefined);
65
+ if (found.some((index, i) => i > 0 && index <= found[i - 1])) throw refuse('boundary_unmapped', 'The transcript orders turns differently from ALP');
66
+ if ('beforeTurnId' in cutoff) {
67
+ if (turn === 0 || at === 0) throw refuse('empty_prefix', 'Nothing comes before the first turn');
68
+ return chain[at - 1].uuid;
69
+ }
70
+ // Through a turn: up to the prompt of the next ALP turn the transcript has, else its end.
71
+ const next = turns.slice(turn + 1).map(prompt).find(index => index !== undefined);
72
+ return chain[(next ?? chain.length) - 1].uuid;
73
+ }
74
+
75
+ /** The chain a binding stands for: a pending fork is its base cut at `at`, until its first prompt makes it. */
76
+ export function pendingChain(base: { at?: string }, chain: ChainEntry[]) {
77
+ if (!base.at) return chain;
78
+ const index = chain.findIndex(entry => entry.uuid === base.at);
79
+ if (index < 0) throw refuse('native_refused', `The conversation no longer has the entry ${base.at} it was cut at`);
80
+ return chain.slice(0, index + 1);
81
+ }
package/src/index.ts CHANGED
@@ -1,11 +1,19 @@
1
1
  // The ALP runtime: native harnesses, sessions, delegation and mail. Viewer-neutral; never imports a viewer SDK.
2
- export { createAlpRuntime, DEFAULT_TEAM } from './runtime.js';
3
- export type { AlpRuntime, RuntimeOptions, OpenOptions, RuntimeTransport, PromptInput, PromptContent, SessionPreview } from './runtime.js';
2
+ export { createAlpRuntime, DEFAULT_TEAM, WorkspaceMutationError } from './runtime.js';
3
+ export type { WorkspaceMutationReason, AlpRuntime, RuntimeOptions, OpenOptions, RuntimeTransport, PromptInput, PromptContent, SessionPreview } from './runtime.js';
4
+ export { ConversationError } from './contracts.js';
5
+ export type { BranchRequest, ConversationErrorReason, NativeBase, NativeBinding, ConfigureChanges, ConfigureResult, ConfigurePreview, EffectiveConfig } from './contracts.js';
4
6
  export type { AlpEvent, AlpError, Envelope, SessionSnapshot, TimelineItem, TurnOrigin, AssignmentSnapshot, UserQuestion, TreeStatus, SessionState } from './events.js';
5
7
  export { resolveSession, InstructionsAdapter, skillDescription } from './resolve.js';
6
8
  export type { SessionSpec, HostMcpServer, ResolvedSession, RuntimeKind } from './resolve.js';
7
- 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';
8
14
  export { CodexTransport } from './transport.js';
15
+ export { ATTACHMENT_HEADER, ATTACHMENT_ROUTES, attachmentStageDir, createAttachmentStager, stagingExposure } from './attachments.js';
16
+ export type { AttachmentReader, AttachmentRoute } from './attachments.js';
9
17
  export { usageAllows } from './runtime-context.js';
10
18
  export { AcpTransport, acpDecision, acpEnv, acpPermission } from './acp-transport.js';
11
19
  export type { AcpProvider } from './acp-transport.js';
@@ -14,10 +22,12 @@ export type { AntigravityProvider } from './antigravity-transport.js';
14
22
  export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, skillPlugin, SKILL_PLUGIN, toolShapes as claudeToolShapes } from './claude-transport.js';
15
23
  export { MAIL_BATCH_CHARS, MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from './mailbox.js';
16
24
  export type { MailEvent, MailKind } from './mailbox.js';
17
- export { createCopy, gitEnvironment, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
25
+ export { createCopy, gitEnvironment, reattachWorktree, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
18
26
  export { OWN_START, processStartedAt, sameProcessAlive } from './process-info.js';
19
27
  export type { Worktree, WorktreeChange } from './workspace.js';
20
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';
21
31
  export { CHOICES, isVietnamese, languageInstruction, words } from './language.js';
22
32
  export type { Words } from './language.js';
23
33
  export type { Pin, PinKind } from './board.js';
@@ -26,3 +36,4 @@ export { ProviderRegistry, createProviderRegistry } from './providers.js';
26
36
  export type { ProviderContext, ProviderFactory, ProviderFactories } from './providers.js';
27
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';
28
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/mailbox.ts CHANGED
@@ -27,8 +27,11 @@ export function takeBatch(mail: MailEvent[], accept: (event: MailEvent) => boole
27
27
  return batch;
28
28
  }
29
29
 
30
+ /** How rendered mail begins, so a replayed prompt can tell ALP's mail from the user's words. */
31
+ export const MAIL_HEADER = 'ALP mail from other agents.';
32
+
30
33
  export function renderMail(events: MailEvent[], requester?: string) {
31
- const header = 'ALP mail from other agents. ' +
34
+ const header = `${MAIL_HEADER} ` +
32
35
  (events.some(event => event.from === USER)
33
36
  ? 'Mail sent by "user" is the user writing to you directly: follow it as a user instruction. ' +
34
37
  (requester ? `ALP has told ${requester} about it. You may now ask the user with alp_ask to: "user"; your handoff must say what the user asked and what you did. ` : '')
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);