@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
@@ -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
  export type RuntimeTransport = {
11
12
  request(method: string, params: any): Promise<any>;
12
13
  initialize(): Promise<void>;
@@ -42,6 +43,8 @@ export type RuntimeOptions = {
42
43
  checkInMs?: number;
43
44
  /** How often the watchdog looks at running assignments; derived from silentForMs and checkInMs when omitted. */
44
45
  watchMs?: number;
46
+ /** How often the project tasks are read for gate changes made without alpd, in ms; 0 turns the timer off. Default 5000. */
47
+ gateSyncMs?: number;
45
48
  /** How long alp_ask waits for the requester before returning unanswered. */
46
49
  askTimeoutMs?: number;
47
50
  /** How long alp_ask waits for the user before returning unanswered. Default 30 minutes. */
@@ -54,6 +57,11 @@ export type RuntimeOptions = {
54
57
  worktreeDir?: string;
55
58
  /** Where assignments whose profile has workdir copy get their disposable copies. Default: a directory in the temp directory. */
56
59
  copyDir?: string;
60
+ /**
61
+ * Where the runtime stages read-only copies of attached files for its sessions' tools (§12.6):
62
+ * alpd's `<ALP_HOME>/state/staged`. Omitted, no session takes attachment parts.
63
+ */
64
+ attachmentStageDir?: string;
57
65
  /** Where project boards are kept (JSONL per project). Omitted keeps them in memory only. */
58
66
  boardDir?: string;
59
67
  /** The user's skill library and lessons (ALP_HOME). Omitted: only skills inside the project, and project lessons. */
@@ -62,6 +70,8 @@ export type RuntimeOptions = {
62
70
  language?: string;
63
71
  /** Where finished assignments' native threads are recorded for alp_recall. Omitted keeps the record in memory. */
64
72
  recallFile?: string;
73
+ /** Permanent assignment ownership; unlike recall, results never expire. */
74
+ assignmentResultFile?: string;
65
75
  /** Where pauses are kept across restarts. Omitted keeps them in memory. */
66
76
  pauseFile?: string;
67
77
  /**
@@ -85,21 +95,57 @@ export type RuntimeOptions = {
85
95
  /** Runs the GitHub CLI for alp_issue. Default: `gh` (or ALP_GH_BIN) on PATH. */
86
96
  github?: GitHubRunner;
87
97
  };
88
- import type { OpenOptions, PromptInput } from '@anhlp/alp-protocol/session';
89
- export type { OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
98
+ import type { NativeBase, OpenOptions, PromptInput } from '@anhlp/alp-protocol/session';
99
+ export type { NativeBase, OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
100
+ export type ScheduleHandler = (action: 'create' | 'list' | 'get' | 'cancel', params: Record<string, unknown>) => Promise<unknown>;
90
101
  export type AlpRuntime = {
102
+ /** The daemon supplies its persistent schedule operations; standalone runtimes have none. */
103
+ bindSchedules?: (handler: ScheduleHandler | undefined) => void;
104
+ /** alpd hands over its attachment reader (§12.6) once, at start; with a staging directory, Codex and Claude sessions then take attachment parts. */
105
+ bindAttachments?: (reader: AttachmentReader | undefined) => void;
106
+ /** Whether this live session's runtime takes `{ type: 'attachment' }` parts (RuntimeAttachment) now. */
107
+ takesAttachments?: (sessionId: string) => boolean;
108
+ /** Removes the staged copy of an attachment alpd no longer keeps. */
109
+ dropAttachment?: (attachmentId: string) => Promise<void>;
91
110
  onEvent(listener: (envelope: Envelope) => void): () => void;
111
+ /** Certifies a brand-new generated checkout; never use to adopt an existing workspace. */
112
+ registerWorkspace(directory: string): Promise<void>;
113
+ /** Reserves runtime admission while an external checkout mutation runs. */
114
+ withWorkspaceMutation<T>(directory: string, run: () => Promise<T>): Promise<T>;
115
+ /**
116
+ * Owner-audited adoption of a checkout that predates birth certification (t-c1ba). Under the
117
+ * removal guard's reservation and ownership checks, `verify` must prove the checkout's identity
118
+ * (it throws otherwise); only then is the canonical directory certified. Never call it without
119
+ * the owner's explicit confirmation of the facts `verify` checks.
120
+ */
121
+ adoptWorkspace?(directory: string, verify: (canonical: string) => Promise<void>): Promise<void>;
92
122
  /** Opens a root session under a client-chosen id. */
93
123
  open(sessionId: string, spec: SessionSpec, options?: OpenOptions): Promise<SessionSnapshot>;
94
124
  /** What a new root would run as, before it opens, and the teams it may choose (ALPD §60). */
95
125
  preview(spec: SessionSpec): Promise<SessionPreview>;
96
126
  /** Failures are reported as prompt.failed, once per clientMessageId. */
97
127
  prompt(sessionId: string, input: PromptInput): Promise<void>;
128
+ /**
129
+ * Atomically admits an idle scheduled prompt in the runtime queue. Busy leaves all preparation
130
+ * untouched. The callback may persist its attempt/receipt, then use its single-use sender;
131
+ * the sender is valid only during the callback. Do not enqueue runtime operations in the callback.
132
+ */
133
+ withIdlePrompt?<T>(sessionId: string, run: (send: (input: PromptInput) => Promise<void>) => Promise<T>): Promise<{
134
+ busy: true;
135
+ } | {
136
+ busy: false;
137
+ value: T;
138
+ }>;
98
139
  /** Cancels the running turn and closes the whole subtree. */
99
140
  interrupt(sessionId: string): Promise<void>;
100
- /** Changes permission mode while idle; undefined keeps the current mode. */
141
+ /** Atomically cancels only this active turn; false leaves the session and subtree untouched. */
142
+ interruptTurn?(sessionId: string, turnId: string): Promise<boolean>;
143
+ /** Changes permission mode while idle; undefined keeps the current mode.
144
+ * onApplied is awaited after apply and before session.updated; failure does not roll back permissions. */
101
145
  configure(sessionId: string, changes: {
102
146
  mode?: string;
147
+ }, options?: {
148
+ onApplied?: (session: SessionSnapshot) => Promise<void>;
103
149
  }): Promise<SessionSnapshot>;
104
150
  close(sessionId: string): Promise<void>;
105
151
  snapshot(sessionId: string): SessionSnapshot | undefined;
@@ -113,8 +159,11 @@ export type AlpRuntime = {
113
159
  answer(questionId: string, reply: {
114
160
  text?: string;
115
161
  dismiss?: boolean;
116
- reason?: string;
162
+ reason?: string; /** Where the user answered a gate card: paseo or web. */
163
+ channel?: 'paseo' | 'web';
117
164
  }): void;
165
+ /** 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). */
166
+ syncGates?(projectRoot: string): Promise<void>;
118
167
  /** Mails a note from the user to any live session, such as an assignment the user wants to redirect. */
119
168
  message(sessionId: string, text: string): void;
120
169
  /** The project board: live claims, then decisions and findings, oldest first. */
@@ -129,6 +178,14 @@ export type AlpRuntime = {
129
178
  resume(input?: {
130
179
  runtime?: RuntimeKind;
131
180
  }): PauseState;
181
+ /** alpd's disk takes no writes (t-2831): pauses all of ALP and parks running assignments, unless all of ALP is paused already. */
182
+ holdForDisk(reason: string): PauseState;
183
+ /** Lifts the pause holdForDisk made, keeping usage-limit pauses; a pause the user made stays. */
184
+ releaseDisk(by: string): PauseState;
185
+ /** Whether alpd's disk pause holds ALP now. */
186
+ diskHeld(): boolean;
187
+ /** Tells every open root that disk space runs low. */
188
+ diskLow(free: string): void;
132
189
  /** Current pauses and parked assignments. */
133
190
  pauses(): PauseState;
134
191
  /** Read-only, cached account usage for the web and desktop viewers. */
@@ -155,7 +212,131 @@ export type AlpRuntime = {
155
212
  abandon(rootId: string, reason: string): Promise<RecoveryOutcome[]>;
156
213
  /** Closes everything; assignments still running stay in the live file, so the next alpd continues them. */
157
214
  shutdown(): Promise<void>;
215
+ /**
216
+ * Makes the native conversation a fork or rewind continues (docs/protocol/alp-json-rpc-v1.md §12.7): the
217
+ * source's conversation cut at a completed turn, persisted by the runtime and leaving the source
218
+ * unchanged. Touches no live session. Codex forks natively now (thread/fork); Claude validates the
219
+ * cut against the transcript and answers a binding the first prompt forks (NativeBinding.base).
220
+ * Refusals throw a ConversationError; one the runtime may or may not have acted on carries
221
+ * `outcomeUnknown: true`. Absent: the host cannot fork or rewind.
222
+ */
223
+ branch?(request: BranchRequest): Promise<NativeBinding>;
224
+ /**
225
+ * Moves an idle live root to another native conversation (a rewind), or reopens its own (a reload):
226
+ * its native process restarts and resumes `binding`, keeping the session id, its configuration and
227
+ * attached viewers. Refused (ConversationError session_busy) unless the whole tree is idle: no turn,
228
+ * pending prompt, child, assignment, question, mail or parked work. Emits session.updated.
229
+ * When the new binding cannot be opened, the old one is reopened and the error thrown; when neither
230
+ * opens, the session fails as a provider failure does.
231
+ */
232
+ rebind?(sessionId: string, binding: NativeBinding): Promise<SessionSnapshot>;
233
+ /**
234
+ * Restarts an idle live root's native process on the conversation it runs now (a reload, §12.8):
235
+ * the same binding, the session's own configuration, id and viewers. Refused as rebind is. The new
236
+ * process must resume that very conversation (a Claude one is refused unless its transcript, or its
237
+ * base, exists), never an empty one in its place; when it cannot, the session closes with its
238
+ * conversation kept (a later open resumes it) and a ConversationError native_refused is thrown.
239
+ * Emits session.updated.
240
+ */
241
+ reload?(sessionId: string): Promise<SessionSnapshot>;
242
+ /** Compacts a root's context at its next turn boundary, with a checkpoint main writes by skill compact (t-0e56). */
243
+ compact?(sessionId: string): {
244
+ status: 'started' | 'deferred' | 'running';
245
+ };
246
+ /**
247
+ * Holds the turns the runtime would start by itself on this session (mail wakes) while a lifecycle
248
+ * operation changes its conversation (a rewind, later a reload or live configure): mail stays queued
249
+ * and is delivered when the last hold is released, to whatever conversation the session runs then.
250
+ * rebind does not refuse for mail a hold keeps. Client prompts are not held here; alpd holds them.
251
+ * Undefined when the session is not open.
252
+ */
253
+ hold?(sessionId: string): (() => void) | undefined;
254
+ /**
255
+ * Whether an open session may begin a turn it has no id for yet: its turn/start (a prompt or a mail
256
+ * wake) is reserved, queued or on its way to the native runtime, or its process is opening or restarting. Such a
257
+ * turn shows in `activeTurnId` only once the runtime answers, and a hold taken meanwhile does not
258
+ * stop it. False when the session is not open.
259
+ */
260
+ starting?(sessionId: string): boolean;
261
+ /**
262
+ * What a live root would run with after a change of model, thinking, team or mode (§12.9), and whether
263
+ * reconfigure would take it now; reads only. `teams` are the teams the host defines for its project.
264
+ */
265
+ previewConfigure?(sessionId: string, changes: ConfigureChanges): Promise<ConfigurePreview>;
266
+ /**
267
+ * Changes an idle live root's model, thinking, team or mode (§12.9): resolves the new configuration
268
+ * as session.create would (same runtime, agent and conversation; never more permissions or new
269
+ * executable resources), then restarts its native process with it on the same conversation (`fresh`:
270
+ * a root with no turn yet starts a new, empty one). The session takes the new configuration only
271
+ * once the runtime took it (Codex echoes the model it resumed with); otherwise the old one is
272
+ * restarted and a ConversationError thrown (`outcomeUnknown` when the runtime may have acted). A
273
+ * new team also replaces the root's supervisor. Refused as rebind is while the tree is not idle.
274
+ * `onApplied` lets a host persist the configuration the runtime took before session.updated is
275
+ * emitted. It is awaited only for an applied change; its failure leaves the runtime configured
276
+ * and reports outcomeUnknown (never a rollback or a known native refusal).
277
+ * Emits session.updated after that persistence succeeds.
278
+ */
279
+ reconfigure?(sessionId: string, changes: ConfigureChanges, options?: {
280
+ fresh?: boolean;
281
+ onApplied?: (result: ConfigureResult) => Promise<void>;
282
+ }): Promise<ConfigureResult>;
158
283
  };
284
+ import type { ConfigureChanges, EffectiveConfig } from './configure.js';
285
+ export type { ConfigureChanges, EffectiveConfig } from './configure.js';
286
+ import type { ConfigurePreview } from '@anhlp/alp-protocol/session';
287
+ export type { ConfigurePreview } from '@anhlp/alp-protocol/session';
288
+ /** What reconfigure did: the session as it runs now, its effective configuration, and whether its process restarted. */
289
+ export type ConfigureResult = {
290
+ session: SessionSnapshot;
291
+ effective: EffectiveConfig;
292
+ status: 'applied' | 'unchanged';
293
+ restarted: boolean;
294
+ /** What the native runtime answered it runs with (Codex: the resumed thread's model and effort). */
295
+ native?: {
296
+ model?: string;
297
+ reasoningEffort?: string;
298
+ };
299
+ };
300
+ /** The native conversation a session continues: its thread, or for Claude one its first prompt makes from `base`. */
301
+ export type NativeBinding = {
302
+ threadId: string;
303
+ base?: NativeBase;
304
+ };
305
+ export type BranchRequest = {
306
+ runtime: RuntimeKind;
307
+ /** The conversation to branch: the source session's binding. */
308
+ source: NativeBinding;
309
+ /** Where the source session runs (Claude keeps its transcripts by this directory). */
310
+ cwd: string;
311
+ /** Where the branch will run; the source's cwd when absent. */
312
+ targetCwd?: string;
313
+ /** The configuration the branch keeps: Codex otherwise forks with its default model and settings. */
314
+ model: string;
315
+ thinking: string;
316
+ mode: string;
317
+ /**
318
+ * The cut, by ALP turn id (a Codex turn id; a Claude prompt uuid): keep through a completed turn, or
319
+ * everything before a turn. Absent: the whole conversation.
320
+ */
321
+ cutoff?: {
322
+ throughTurnId: string;
323
+ } | {
324
+ beforeTurnId: string;
325
+ };
326
+ /** The source root's turns in order, as ALP's timeline has them, for the cut's validation. */
327
+ turns: string[];
328
+ };
329
+ export type ConversationErrorReason = 'runtime_unsupported' | 'boundary_unmapped' | 'empty_prefix' | 'native_refused' | 'session_busy' | 'runtime_mismatch' | 'agent_mismatch' | 'permission_escalation' | 'team_not_found' | 'invalid_params' | 'not_root';
330
+ /** A fork, rewind or rebind the runtime refused; `outcomeUnknown` when the native runtime may have acted. */
331
+ export declare class ConversationError extends Error {
332
+ readonly data: {
333
+ reason: ConversationErrorReason;
334
+ };
335
+ readonly outcomeUnknown: boolean;
336
+ constructor(reason: ConversationErrorReason, message: string, { outcomeUnknown }?: {
337
+ outcomeUnknown?: boolean | undefined;
338
+ });
339
+ }
159
340
  import type { SessionPreview } from '@anhlp/alp-protocol/session';
160
341
  export type { SessionPreview } from '@anhlp/alp-protocol/session';
161
342
  /**
package/dist/contracts.js CHANGED
@@ -1,5 +1,16 @@
1
1
  // packages/runtime/src/contracts.ts
2
2
  import { INIT_TEAM } from "@anhlp/alp-core/workflow";
3
+ var ConversationError = class extends Error {
4
+ data;
5
+ outcomeUnknown;
6
+ constructor(reason, message, { outcomeUnknown = false } = {}) {
7
+ super(message);
8
+ this.name = "ConversationError";
9
+ this.data = { reason };
10
+ this.outcomeUnknown = outcomeUnknown;
11
+ }
12
+ };
3
13
  export {
14
+ ConversationError,
4
15
  INIT_TEAM as DEFAULT_TEAM
5
16
  };
@@ -0,0 +1,45 @@
1
+ import { ConversationError, type BranchRequest } from './contracts.js';
2
+ /**
3
+ * Conversation cuts for fork and rewind (docs/protocol/alp-json-rpc-v1.md §12.7). Pure helpers of
4
+ * runtime.ts's branch(): where a Claude transcript is cut, which Codex turn a fork must end at, and
5
+ * what a Codex refusal means.
6
+ */
7
+ /** One entry of a Claude session's main chain, as the Agent SDK reads it from the transcript. */
8
+ export type ChainEntry = {
9
+ uuid: string;
10
+ type: 'user' | 'assistant';
11
+ toolResult?: boolean;
12
+ };
13
+ /** The turn a Codex fork must end at, after ALP's own validation of the cut against its timeline. */
14
+ export declare function codexForkEnd(request: Pick<BranchRequest, 'cutoff' | 'turns'>): {
15
+ last: string;
16
+ params: {
17
+ beforeTurnId?: undefined;
18
+ lastTurnId?: undefined;
19
+ };
20
+ } | {
21
+ last: string;
22
+ params: {
23
+ beforeTurnId: string;
24
+ lastTurnId?: undefined;
25
+ };
26
+ } | {
27
+ last: string;
28
+ params: {
29
+ lastTurnId: string;
30
+ beforeTurnId?: undefined;
31
+ };
32
+ };
33
+ /** What a refused thread/fork means; one written but unanswered may have forked. */
34
+ export declare function codexForkRefusal(error: unknown): ConversationError;
35
+ /**
36
+ * The chain uuid a Claude fork resumes at (`resumeSessionAt`): the last entry kept. ALP turn ids are
37
+ * the prompt uuids it gave Claude, so a turn starts at its prompt entry and runs to the next ALP turn's
38
+ * prompt; entries of a turn Claude started itself belong to the turn before it. Always a pinned entry,
39
+ * never "everything", so turns the source adds later never reach a branch made before them.
40
+ */
41
+ export declare function claudeCut(chain: ChainEntry[], request: Pick<BranchRequest, 'cutoff' | 'turns'>): string;
42
+ /** The chain a binding stands for: a pending fork is its base cut at `at`, until its first prompt makes it. */
43
+ export declare function pendingChain(base: {
44
+ at?: string;
45
+ }, chain: ChainEntry[]): ChainEntry[];
@@ -0,0 +1,62 @@
1
+ // packages/runtime/src/conversation.ts
2
+ import { ConversationError } from "./contracts.js";
3
+ var refuse = (reason, message, outcomeUnknown = false) => new ConversationError(reason, message, { outcomeUnknown });
4
+ function codexForkEnd(request) {
5
+ const { cutoff, turns } = request;
6
+ if (!cutoff) {
7
+ if (!turns.length) throw refuse("empty_prefix", "The conversation has no turn to fork");
8
+ return { last: turns.at(-1), params: {} };
9
+ }
10
+ const id = "beforeTurnId" in cutoff ? cutoff.beforeTurnId : cutoff.throughTurnId;
11
+ const index = turns.indexOf(id);
12
+ if (index < 0) throw refuse("boundary_unmapped", `Turn ${id} is not a turn of this conversation`);
13
+ if ("beforeTurnId" in cutoff) {
14
+ if (index === 0) throw refuse("empty_prefix", "Nothing comes before the first turn");
15
+ return { last: turns[index - 1], params: { beforeTurnId: id } };
16
+ }
17
+ return { last: id, params: { lastTurnId: id } };
18
+ }
19
+ function codexForkRefusal(error) {
20
+ if (error instanceof ConversationError) return error;
21
+ const message = error instanceof Error ? error.message : String(error);
22
+ if (error?.outcomeUnknown) return refuse("native_refused", `Codex did not answer the fork: ${message}`, true);
23
+ if (/^turn not found\b/i.test(message)) return refuse("boundary_unmapped", `Codex does not know that turn: ${message}`);
24
+ if (/identifies an in-progress turn/i.test(message)) return refuse("session_busy", `The turn is still running: ${message}`);
25
+ return refuse("native_refused", `Codex refused the fork: ${message}`);
26
+ }
27
+ function claudeCut(chain, request) {
28
+ const { cutoff, turns } = request;
29
+ const position = new Map(chain.map((entry, index) => [entry.uuid, index]));
30
+ const prompt = (id2) => {
31
+ const index = position.get(id2);
32
+ return index !== void 0 && chain[index].type === "user" && !chain[index].toolResult ? index : void 0;
33
+ };
34
+ if (!cutoff) {
35
+ if (!chain.length) throw refuse("empty_prefix", "The conversation has no turn to fork");
36
+ return chain.at(-1).uuid;
37
+ }
38
+ const id = "beforeTurnId" in cutoff ? cutoff.beforeTurnId : cutoff.throughTurnId;
39
+ const turn = turns.indexOf(id);
40
+ const at = prompt(id);
41
+ if (turn < 0 || at === void 0) throw refuse("boundary_unmapped", `Turn ${id} is not a turn of this conversation's transcript`);
42
+ const found = turns.map(prompt).filter((index) => index !== void 0);
43
+ if (found.some((index, i) => i > 0 && index <= found[i - 1])) throw refuse("boundary_unmapped", "The transcript orders turns differently from ALP");
44
+ if ("beforeTurnId" in cutoff) {
45
+ if (turn === 0 || at === 0) throw refuse("empty_prefix", "Nothing comes before the first turn");
46
+ return chain[at - 1].uuid;
47
+ }
48
+ const next = turns.slice(turn + 1).map(prompt).find((index) => index !== void 0);
49
+ return chain[(next ?? chain.length) - 1].uuid;
50
+ }
51
+ function pendingChain(base, chain) {
52
+ if (!base.at) return chain;
53
+ const index = chain.findIndex((entry) => entry.uuid === base.at);
54
+ if (index < 0) throw refuse("native_refused", `The conversation no longer has the entry ${base.at} it was cut at`);
55
+ return chain.slice(0, index + 1);
56
+ }
57
+ export {
58
+ claudeCut,
59
+ codexForkEnd,
60
+ codexForkRefusal,
61
+ pendingChain
62
+ };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,18 @@
1
- export { createAlpRuntime, DEFAULT_TEAM } from './runtime.js';
2
- export type { AlpRuntime, RuntimeOptions, OpenOptions, RuntimeTransport, PromptInput, PromptContent, SessionPreview } from './runtime.js';
1
+ export { createAlpRuntime, DEFAULT_TEAM, WorkspaceMutationError } from './runtime.js';
2
+ export type { WorkspaceMutationReason, AlpRuntime, RuntimeOptions, OpenOptions, RuntimeTransport, PromptInput, PromptContent, SessionPreview } from './runtime.js';
3
+ export { ConversationError } from './contracts.js';
4
+ export type { BranchRequest, ConversationErrorReason, NativeBase, NativeBinding, ConfigureChanges, ConfigureResult, ConfigurePreview, EffectiveConfig } from './contracts.js';
3
5
  export type { AlpEvent, AlpError, Envelope, SessionSnapshot, TimelineItem, TurnOrigin, AssignmentSnapshot, UserQuestion, TreeStatus, SessionState } from './events.js';
4
6
  export { resolveSession, InstructionsAdapter, skillDescription } from './resolve.js';
5
7
  export type { SessionSpec, HostMcpServer, ResolvedSession, RuntimeKind } from './resolve.js';
6
- export { DEFAULT_MODEL, DEFAULT_CLAUDE_MODEL, models, modes, thinkingOptions, thinkingOptionsFor } from './catalog.js';
8
+ export { DEFAULT_MODEL, DEFAULT_CLAUDE_MODEL, entries as catalogEntries, models, modes, thinkingOptions, thinkingOptionsFor } from './catalog.js';
9
+ export type { CatalogEntry } from './catalog.js';
10
+ export { ModelCatalog, mergeCatalog, liveFromContext, feedCatalog, setActiveCatalog, activeCatalog, POLICY as CATALOG_POLICY, REFRESH_MS as CATALOG_REFRESH_MS } from './model-catalog.js';
11
+ export type { CatalogSnapshot, CatalogRuntime, LiveModel, Probe as CatalogProbe } from './model-catalog.js';
12
+ export { liveProbes, codexProbe, claudeProbe, antigravityProbe, parseAgyModels } from './model-probes.js';
7
13
  export { CodexTransport } from './transport.js';
14
+ export { ATTACHMENT_HEADER, ATTACHMENT_ROUTES, attachmentStageDir, createAttachmentStager, stagingExposure } from './attachments.js';
15
+ export type { AttachmentReader, AttachmentRoute } from './attachments.js';
8
16
  export { usageAllows } from './runtime-context.js';
9
17
  export { AcpTransport, acpDecision, acpEnv, acpPermission } from './acp-transport.js';
10
18
  export type { AcpProvider } from './acp-transport.js';
@@ -13,10 +21,12 @@ export type { AntigravityProvider } from './antigravity-transport.js';
13
21
  export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, skillPlugin, SKILL_PLUGIN, toolShapes as claudeToolShapes } from './claude-transport.js';
14
22
  export { MAIL_BATCH_CHARS, MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from './mailbox.js';
15
23
  export type { MailEvent, MailKind } from './mailbox.js';
16
- export { createCopy, gitEnvironment, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
24
+ export { createCopy, gitEnvironment, reattachWorktree, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
17
25
  export { OWN_START, processStartedAt, sameProcessAlive } from './process-info.js';
18
26
  export type { Worktree, WorktreeChange } from './workspace.js';
19
27
  export { PIN_KINDS, renderBoard, renderPin } from './board.js';
28
+ export { inputLimitError, TOOL_INPUT, POUR_VARS } from './input-limits.js';
29
+ export type { InputLimits } from './input-limits.js';
20
30
  export { CHOICES, isVietnamese, languageInstruction, words } from './language.js';
21
31
  export type { Words } from './language.js';
22
32
  export type { Pin, PinKind } from './board.js';
@@ -24,3 +34,4 @@ export { ProviderRegistry, createProviderRegistry } from './providers.js';
24
34
  export type { ProviderContext, ProviderFactory, ProviderFactories } from './providers.js';
25
35
  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';
26
36
  export type { AcpCall, ClaudeResult, CodexToolCall, ToolCallDetail } from './tool-detail.js';
37
+ export { checkpointPrompt, compactDue, compactSettings, contextFill, seedPrompt, COMPACT_DEFAULTS } from './compact.js';
package/dist/index.js CHANGED
@@ -1,25 +1,37 @@
1
1
  // packages/runtime/src/index.ts
2
- import { createAlpRuntime, DEFAULT_TEAM } from "./runtime.js";
2
+ import { createAlpRuntime, DEFAULT_TEAM, WorkspaceMutationError } from "./runtime.js";
3
+ import { ConversationError } from "./contracts.js";
3
4
  import { resolveSession, InstructionsAdapter, skillDescription } from "./resolve.js";
4
- import { DEFAULT_MODEL, DEFAULT_CLAUDE_MODEL, models, modes, thinkingOptions, thinkingOptionsFor } from "./catalog.js";
5
+ import { DEFAULT_MODEL, DEFAULT_CLAUDE_MODEL, entries, models, modes, thinkingOptions, thinkingOptionsFor } from "./catalog.js";
6
+ import { ModelCatalog, mergeCatalog, liveFromContext, feedCatalog, setActiveCatalog, activeCatalog, POLICY, REFRESH_MS } from "./model-catalog.js";
7
+ import { liveProbes, codexProbe, claudeProbe, antigravityProbe, parseAgyModels } from "./model-probes.js";
5
8
  import { CodexTransport } from "./transport.js";
9
+ import { ATTACHMENT_HEADER, ATTACHMENT_ROUTES, attachmentStageDir, createAttachmentStager, stagingExposure } from "./attachments.js";
6
10
  import { usageAllows } from "./runtime-context.js";
7
11
  import { AcpTransport, acpDecision, acpEnv, acpPermission } from "./acp-transport.js";
8
12
  import { AntigravityTransport } from "./antigravity-transport.js";
9
13
  import { ClaudeTransport, claudePermissions, claudeSandboxAvailable, skillPlugin, SKILL_PLUGIN, toolShapes } from "./claude-transport.js";
10
14
  import { MAIL_BATCH_CHARS, MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from "./mailbox.js";
11
- import { createCopy, gitEnvironment, reclaimCopies, reclaimWorktrees, removeCopy } from "./workspace.js";
15
+ import { createCopy, gitEnvironment, reattachWorktree, reclaimCopies, reclaimWorktrees, removeCopy } from "./workspace.js";
12
16
  import { OWN_START, processStartedAt, sameProcessAlive } from "./process-info.js";
13
17
  import { PIN_KINDS, renderBoard, renderPin } from "./board.js";
18
+ import { inputLimitError, TOOL_INPUT, POUR_VARS } from "./input-limits.js";
14
19
  import { CHOICES, isVietnamese, languageInstruction, words } from "./language.js";
15
20
  import { ProviderRegistry, createProviderRegistry } from "./providers.js";
16
21
  import { 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";
22
+ import { checkpointPrompt, compactDue, compactSettings, contextFill, seedPrompt, COMPACT_DEFAULTS } from "./compact.js";
17
23
  export {
24
+ ATTACHMENT_HEADER,
25
+ ATTACHMENT_ROUTES,
18
26
  AcpTransport,
19
27
  AntigravityTransport,
28
+ POLICY as CATALOG_POLICY,
29
+ REFRESH_MS as CATALOG_REFRESH_MS,
20
30
  CHOICES,
31
+ COMPACT_DEFAULTS,
21
32
  ClaudeTransport,
22
33
  CodexTransport,
34
+ ConversationError,
23
35
  DEFAULT_CLAUDE_MODEL,
24
36
  DEFAULT_MODEL,
25
37
  DEFAULT_TEAM,
@@ -30,34 +42,56 @@ export {
30
42
  InstructionsAdapter,
31
43
  MAIL_BATCH_CHARS,
32
44
  MAIL_BODY_CHARS,
45
+ ModelCatalog,
33
46
  OWN_START,
34
47
  PIN_KINDS,
48
+ POUR_VARS,
35
49
  ProviderRegistry,
36
50
  SKILL_PLUGIN,
37
51
  TOOL_FAILED,
52
+ TOOL_INPUT,
38
53
  USER,
54
+ WorkspaceMutationError,
39
55
  acpDecision,
40
56
  acpEnv,
41
57
  acpPermission,
42
58
  acpToolDetail,
59
+ activeCatalog,
60
+ antigravityProbe,
43
61
  antigravityToolDetail,
62
+ attachmentStageDir,
44
63
  boundDetail,
64
+ entries as catalogEntries,
65
+ checkpointPrompt,
45
66
  claudePermissions,
67
+ claudeProbe,
46
68
  claudeSandboxAvailable,
47
69
  claudeToolDetail,
48
70
  toolShapes as claudeToolShapes,
49
71
  clipText,
72
+ codexProbe,
50
73
  codexToolCall,
74
+ compactDue,
75
+ compactSettings,
76
+ contextFill,
51
77
  createAlpRuntime,
78
+ createAttachmentStager,
52
79
  createCopy,
53
80
  createProviderRegistry,
81
+ feedCatalog,
54
82
  gitEnvironment,
83
+ inputLimitError,
55
84
  isVietnamese,
56
85
  languageInstruction,
86
+ liveFromContext,
87
+ liveProbes,
88
+ mergeCatalog,
57
89
  models,
58
90
  modes,
91
+ parseAgyModels,
59
92
  processStartedAt,
60
93
  publicEvent,
94
+ reattachWorktree,
61
95
  reclaimCopies,
62
96
  reclaimWorktrees,
63
97
  removeCopy,
@@ -66,8 +100,11 @@ export {
66
100
  renderPin,
67
101
  resolveSession,
68
102
  sameProcessAlive,
103
+ seedPrompt,
104
+ setActiveCatalog,
69
105
  skillDescription,
70
106
  skillPlugin,
107
+ stagingExposure,
71
108
  stripReadGutter,
72
109
  takeBatch,
73
110
  thinkingOptions,
@@ -0,0 +1,25 @@
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
+ /** The arguments of any ALP tool. The longest declared field is alp_delegate's 32,000-character task. */
19
+ export declare const TOOL_INPUT: InputLimits;
20
+ /** alp_task pour's vars: a flat object of text, one value per variable the formula declares. */
21
+ export declare const POUR_VARS: InputLimits;
22
+ /** A formula variable's name, as validateFormula admits it. */
23
+ export declare const VAR_NAME: RegExp;
24
+ /** The first cap `value` passes, as an error that names `what`, or undefined within them. */
25
+ export declare function inputLimitError(value: unknown, limits: InputLimits, what?: string): string | undefined;
@@ -0,0 +1,48 @@
1
+ // packages/runtime/src/input-limits.ts
2
+ var TOOL_INPUT = { bytes: 1024 * 1024, items: 5e3, depth: 8, string: 128 * 1024 };
3
+ var POUR_VARS = { bytes: 128 * 1024, items: 50, depth: 1, string: 2e3 };
4
+ var VAR_NAME = /^[\w-]{1,64}$/;
5
+ function inputLimitError(value, limits, what = "The input") {
6
+ let bytes = 0;
7
+ let items = 0;
8
+ const stack = [[value, 0]];
9
+ const tooLarge = `${what} is too large: over ${limits.bytes} bytes`;
10
+ const text = (string) => {
11
+ if (string.length > limits.string) return `${what} is too large: a text over ${limits.string} characters`;
12
+ bytes += Buffer.byteLength(string) + 2;
13
+ return bytes > limits.bytes ? tooLarge : void 0;
14
+ };
15
+ while (stack.length) {
16
+ const [current, depth] = stack.pop();
17
+ if (typeof current === "string") {
18
+ const error = text(current);
19
+ if (error) return error;
20
+ } else if (current !== null && typeof current === "object") {
21
+ if (depth >= limits.depth) return `${what} is too large: nested over ${limits.depth} levels deep`;
22
+ bytes += 2;
23
+ const list = Array.isArray(current);
24
+ const keys = list ? void 0 : Object.keys(current);
25
+ const size = list ? current.length : keys.length;
26
+ if (items + size > limits.items) return `${what} is too large: over ${limits.items} values`;
27
+ items += size;
28
+ for (let index = 0; index < size; index++) {
29
+ if (keys) {
30
+ const error = text(keys[index]);
31
+ if (error) return error;
32
+ }
33
+ bytes += 1;
34
+ stack.push([list ? current[index] : current[keys[index]], depth + 1]);
35
+ }
36
+ } else {
37
+ bytes += String(current).length;
38
+ }
39
+ if (bytes > limits.bytes) return tooLarge;
40
+ }
41
+ return void 0;
42
+ }
43
+ export {
44
+ POUR_VARS,
45
+ TOOL_INPUT,
46
+ VAR_NAME,
47
+ inputLimitError
48
+ };
@@ -11,6 +11,10 @@ declare const en: {
11
11
  skill: (agent: string, replacing: boolean, file: string, roles: string, lessons: string[]) => string;
12
12
  issue: (agent: string, create: boolean, issue: number | undefined, where: string) => string;
13
13
  issueTitle: string;
14
+ lessonCurate: (agent: string, changes: string) => string;
15
+ lessonRemove: string;
16
+ lessonAdd: string;
17
+ lessonScope: (scope: string, file: string) => string;
14
18
  issueLabels: string;
15
19
  trust: (project: string, names: string) => string;
16
20
  trustYes: string;
@@ -21,10 +25,14 @@ declare const en: {
21
25
  permission: (agent: string, what: string, byRule: boolean, profile: string | undefined, mode: string, always: string | undefined) => string;
22
26
  limitReached: (runtime: string, resetsAt: string | undefined, other: string | undefined, autoResume: boolean, kind: string) => string;
23
27
  limitLifted: (runtime: string, kind: string) => string;
28
+ compacted: (native: boolean) => string;
29
+ compactFailed: (reason: string) => string;
24
30
  usageWarning: (runtime: string, used: string, resetsAt: string | undefined) => string;
25
31
  /** The web app's answer to a Paseo feature ALP has not got yet (ALPD §62). */
26
32
  inDevelopment: string;
27
33
  resumed: (what: string, by: string, parked: boolean) => string;
34
+ diskFull: (reason: string) => string;
35
+ diskLow: (free: string) => string;
28
36
  paused: (what: string, reason: string | undefined, runtime: string | undefined, now: boolean) => string;
29
37
  };
30
38
  export type Words = typeof en;