@anhlp/alp-runtime 0.0.0-beta.2 → 0.0.1-beta.10

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 (97) hide show
  1. package/dist/acp-transport.js +7 -36
  2. package/dist/antigravity-transport.d.ts +27 -2
  3. package/dist/antigravity-transport.js +104 -58
  4. package/dist/assignment-results.d.ts +55 -0
  5. package/dist/assignment-results.js +181 -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 +11 -2
  13. package/dist/claude-transport.d.ts +80 -0
  14. package/dist/claude-transport.js +271 -23
  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 +216 -7
  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 +18 -5
  24. package/dist/index.js +48 -4
  25. package/dist/input-limits.d.ts +25 -0
  26. package/dist/input-limits.js +48 -0
  27. package/dist/language.d.ts +10 -0
  28. package/dist/language.js +26 -0
  29. package/dist/live.d.ts +2 -2
  30. package/dist/live.js +7 -2
  31. package/dist/mailbox.d.ts +2 -0
  32. package/dist/mailbox.js +3 -1
  33. package/dist/mcp-tools.d.ts +8 -0
  34. package/dist/mcp-tools.js +26 -0
  35. package/dist/model-catalog.d.ts +162 -0
  36. package/dist/model-catalog.js +338 -0
  37. package/dist/model-probes.d.ts +7 -0
  38. package/dist/model-probes.js +69 -0
  39. package/dist/providers.js +2 -0
  40. package/dist/recall.d.ts +2 -2
  41. package/dist/recall.js +4 -3
  42. package/dist/resolve.d.ts +2 -0
  43. package/dist/resolve.js +9 -5
  44. package/dist/runtime-context.d.ts +1 -1
  45. package/dist/runtime-context.js +1 -1
  46. package/dist/runtime.d.ts +9 -0
  47. package/dist/runtime.js +2078 -269
  48. package/dist/session-config.d.ts +378 -6
  49. package/dist/session-config.js +19 -15
  50. package/dist/session-state.d.ts +54 -7
  51. package/dist/skill-resources.d.ts +30 -0
  52. package/dist/skill-resources.js +55 -0
  53. package/dist/tool-detail.js +4 -1
  54. package/dist/tools.d.ts +154 -1
  55. package/dist/tools.js +99 -11
  56. package/dist/transport.js +3 -1
  57. package/dist/workspace.d.ts +31 -5
  58. package/dist/workspace.js +92 -11
  59. package/dist/worktree-domain.d.ts +2 -1
  60. package/dist/worktree-domain.js +4 -1
  61. package/dist/write-error.d.ts +2 -0
  62. package/dist/write-error.js +10 -0
  63. package/package.json +12 -4
  64. package/src/acp-transport.ts +10 -37
  65. package/src/antigravity-transport.ts +128 -55
  66. package/src/assignment-results.ts +154 -0
  67. package/src/attachments.ts +254 -0
  68. package/src/board-domain.ts +2 -2
  69. package/src/board.ts +7 -0
  70. package/src/catalog.ts +13 -2
  71. package/src/claude-transport.ts +333 -23
  72. package/src/compact.ts +62 -0
  73. package/src/configure.ts +93 -0
  74. package/src/contracts.ts +199 -8
  75. package/src/conversation.ts +81 -0
  76. package/src/index.ts +18 -5
  77. package/src/input-limits.ts +65 -0
  78. package/src/language.ts +28 -0
  79. package/src/live.ts +7 -3
  80. package/src/mailbox.ts +4 -1
  81. package/src/mcp-tools.ts +33 -0
  82. package/src/model-catalog.ts +316 -0
  83. package/src/model-probes.ts +58 -0
  84. package/src/providers.ts +3 -0
  85. package/src/recall.ts +4 -3
  86. package/src/resolve.ts +15 -7
  87. package/src/runtime-context.ts +2 -2
  88. package/src/runtime.ts +2253 -264
  89. package/src/session-config.ts +25 -14
  90. package/src/session-state.ts +39 -3
  91. package/src/skill-resources.ts +73 -0
  92. package/src/tool-detail.ts +4 -1
  93. package/src/tools.ts +97 -10
  94. package/src/transport.ts +3 -1
  95. package/src/workspace.ts +124 -18
  96. package/src/worktree-domain.ts +5 -1
  97. package/src/write-error.ts +4 -0
@@ -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
+ }
package/src/contracts.ts CHANGED
@@ -7,11 +7,19 @@ 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';
11
+
12
+ /** A slash command or skill an agent's composer offers after "/" (t-f628). */
13
+ export type RuntimeCommand = { name: string; description: string; argumentHint?: string; kind: 'command' | 'skill' };
10
14
 
11
15
  export type RuntimeTransport = {
12
16
  request(method: string, params: any): Promise<any>;
13
17
  initialize(): Promise<void>;
14
18
  orchestrationContext?: () => Promise<unknown>;
19
+ /** The runtime's own slash commands and skills for the composer (t-f628); omitted, the runtime offers none. */
20
+ commands?: () => Promise<RuntimeCommand[]>;
21
+ /** Claude: the aliases of /clear (new, reset) that run a command of the user's, so they are not refused (t-5ac5). */
22
+ customCommands?: () => ReadonlySet<string>;
15
23
  onNotification(listener: (method: string, params: any) => void): void;
16
24
  onFailure(listener: (error: unknown) => void): void;
17
25
  close(): Promise<void>;
@@ -50,6 +58,8 @@ export type RuntimeOptions = {
50
58
  checkInMs?: number;
51
59
  /** How often the watchdog looks at running assignments; derived from silentForMs and checkInMs when omitted. */
52
60
  watchMs?: number;
61
+ /** How often the project tasks are read for gate changes made without alpd, in ms; 0 turns the timer off. Default 5000. */
62
+ gateSyncMs?: number;
53
63
  /** How long alp_ask waits for the requester before returning unanswered. */
54
64
  askTimeoutMs?: number;
55
65
  /** How long alp_ask waits for the user before returning unanswered. Default 30 minutes. */
@@ -67,6 +77,12 @@ export type RuntimeOptions = {
67
77
  /** Where assignments whose profile has workdir copy get their disposable copies. Default: a directory in the temp directory. */
68
78
  copyDir?: string;
69
79
 
80
+ /**
81
+ * Where the runtime stages read-only copies of attached files for its sessions' tools (§12.6):
82
+ * alpd's `<ALP_HOME>/state/staged`. Omitted, no session takes attachment parts.
83
+ */
84
+ attachmentStageDir?: string;
85
+
70
86
  /** Where project boards are kept (JSONL per project). Omitted keeps them in memory only. */
71
87
  boardDir?: string;
72
88
 
@@ -78,6 +94,8 @@ export type RuntimeOptions = {
78
94
 
79
95
  /** Where finished assignments' native threads are recorded for alp_recall. Omitted keeps the record in memory. */
80
96
  recallFile?: string;
97
+ /** Permanent assignment ownership; unlike recall, results never expire. */
98
+ assignmentResultFile?: string;
81
99
 
82
100
  /** Where pauses are kept across restarts. Omitted keeps them in memory. */
83
101
  pauseFile?: string;
@@ -93,6 +111,14 @@ export type RuntimeOptions = {
93
111
  /** Where running assignments are kept, so the next alpd continues them (ALPD §31). Omitted keeps them in memory. */
94
112
  liveFile?: string;
95
113
 
114
+ /**
115
+ * Told of every failed write to pauseFile, liveFile, recallFile and assignmentResultFile, as it
116
+ * happens, so the host's disk guard pauses work on a full disk at once (t-e80a). Each write still
117
+ * fails as before: pauses and recall go on in memory, live entries are logged, and result
118
+ * ownership is refused to its caller.
119
+ */
120
+ onWriteError?: (error: unknown) => void;
121
+
96
122
  /** False parks assignments an earlier alpd left running until the user runs alp resume. Default true: they continue. */
97
123
  recoveryResume?: boolean;
98
124
 
@@ -106,21 +132,53 @@ export type RuntimeOptions = {
106
132
  github?: GitHubRunner;
107
133
  };
108
134
 
109
- import type { OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
110
- export type { OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
135
+ import type { NativeBase, OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
136
+ export type { NativeBase, OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
137
+
138
+ export type ScheduleHandler = (action: 'create' | 'list' | 'get' | 'cancel', params: Record<string, unknown>) => Promise<unknown>;
111
139
 
112
140
  export type AlpRuntime = {
141
+ /** The daemon supplies its persistent schedule operations; standalone runtimes have none. */
142
+ bindSchedules?: (handler: ScheduleHandler | undefined) => void;
143
+ /** alpd hands over its attachment reader (§12.6) once, at start; with a staging directory, Codex and Claude sessions then take attachment parts. */
144
+ bindAttachments?: (reader: AttachmentReader | undefined) => void;
145
+ /** Whether this live session's runtime takes `{ type: 'attachment' }` parts (RuntimeAttachment) now. */
146
+ takesAttachments?: (sessionId: string) => boolean;
147
+ /** Why this live session's runtime refuses this prompt before it is sent (t-e906), or undefined. */
148
+ refusesPrompt?: (sessionId: string, content: PromptContent) => string | undefined;
149
+ /** Removes the staged copy of an attachment alpd no longer keeps. */
150
+ dropAttachment?: (attachmentId: string) => Promise<void>;
113
151
  onEvent(listener: (envelope: Envelope) => void): () => void;
152
+ /** Certifies a brand-new generated checkout; never use to adopt an existing workspace. */
153
+ registerWorkspace(directory: string): Promise<void>;
154
+ /** Reserves runtime admission while an external checkout mutation runs. */
155
+ withWorkspaceMutation<T>(directory: string, run: () => Promise<T>): Promise<T>;
156
+ /**
157
+ * Owner-audited adoption of a checkout that predates birth certification (t-c1ba). Under the
158
+ * removal guard's reservation and ownership checks, `verify` must prove the checkout's identity
159
+ * (it throws otherwise); only then is the canonical directory certified. Never call it without
160
+ * the owner's explicit confirmation of the facts `verify` checks.
161
+ */
162
+ adoptWorkspace?(directory: string, verify: (canonical: string) => Promise<void>): Promise<void>;
114
163
  /** Opens a root session under a client-chosen id. */
115
164
  open(sessionId: string, spec: SessionSpec, options?: OpenOptions): Promise<SessionSnapshot>;
116
165
  /** What a new root would run as, before it opens, and the teams it may choose (ALPD §60). */
117
166
  preview(spec: SessionSpec): Promise<SessionPreview>;
118
167
  /** Failures are reported as prompt.failed, once per clientMessageId. */
119
168
  prompt(sessionId: string, input: PromptInput): Promise<void>;
169
+ /**
170
+ * Atomically admits an idle scheduled prompt in the runtime queue. Busy leaves all preparation
171
+ * untouched. The callback may persist its attempt/receipt, then use its single-use sender;
172
+ * the sender is valid only during the callback. Do not enqueue runtime operations in the callback.
173
+ */
174
+ withIdlePrompt?<T>(sessionId: string, run: (send: (input: PromptInput) => Promise<void>) => Promise<T>): Promise<{ busy: true } | { busy: false; value: T }>;
120
175
  /** Cancels the running turn and closes the whole subtree. */
121
176
  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>;
177
+ /** Atomically cancels only this active turn; false leaves the session and subtree untouched. */
178
+ interruptTurn?(sessionId: string, turnId: string): Promise<boolean>;
179
+ /** Changes permission mode while idle; undefined keeps the current mode.
180
+ * onApplied is awaited after apply and before session.updated; failure does not roll back permissions. */
181
+ configure(sessionId: string, changes: { mode?: string }, options?: { onApplied?: (session: SessionSnapshot) => Promise<void> }): Promise<SessionSnapshot>;
124
182
  close(sessionId: string): Promise<void>;
125
183
  snapshot(sessionId: string): SessionSnapshot | undefined;
126
184
  /** Live sessions, roots before their children. */
@@ -129,8 +187,15 @@ export type AlpRuntime = {
129
187
  status(sessionId: string): TreeStatus | undefined;
130
188
  /** Questions agents asked the user that wait for an answer. */
131
189
  questions(): UserQuestion[];
132
- /** Answers or dismisses a question to the user. */
133
- answer(questionId: string, reply: { text?: string; dismiss?: boolean; reason?: string }): void;
190
+ /**
191
+ * Answers or dismisses a question to the user. A gate card's answer returns a promise that
192
+ * settles once the decision is written, and rejects when it decides nothing: another answer is
193
+ * being recorded or another channel decided first (code GATE_BUSY or GATE_DECIDED), or the
194
+ * write failed (t-595d).
195
+ */
196
+ answer(questionId: string, reply: { text?: string; dismiss?: boolean; reason?: string; /** Where the user answered a gate card: paseo or web. */ channel?: 'paseo' | 'web' }): void | Promise<void>;
197
+ /** Mirrors the project's open human gates as cards on its main session and tells main of the user's gate decisions, at least once each (t-ccac, t-595d). */
198
+ syncGates?(projectRoot: string): Promise<void>;
134
199
  /** Mails a note from the user to any live session, such as an assignment the user wants to redirect. */
135
200
  message(sessionId: string, text: string): void;
136
201
  /** The project board: live claims, then decisions and findings, oldest first. */
@@ -139,6 +204,14 @@ export type AlpRuntime = {
139
204
  pause(input?: { runtime?: RuntimeKind; now?: boolean; reason?: string }): PauseState;
140
205
  /** Lifts a pause and continues the assignments it parked. Without a runtime, lifts every pause. */
141
206
  resume(input?: { runtime?: RuntimeKind }): PauseState;
207
+ /** alpd's disk takes no writes (t-2831): pauses all of ALP and parks running assignments, unless all of ALP is paused already. */
208
+ holdForDisk(reason: string): PauseState;
209
+ /** Lifts the pause holdForDisk made, keeping usage-limit pauses; a pause the user made stays. */
210
+ releaseDisk(by: string): PauseState;
211
+ /** Whether alpd's disk pause holds ALP now. */
212
+ diskHeld(): boolean;
213
+ /** Tells every open root that disk space runs low. */
214
+ diskLow(free: string): void;
142
215
  /** Current pauses and parked assignments. */
143
216
  pauses(): PauseState;
144
217
  /** Read-only, cached account usage for the web and desktop viewers. */
@@ -147,14 +220,132 @@ export type AlpRuntime = {
147
220
  recall(target: { assignmentId?: string; taskId?: string; projectRoot?: string }, question: string): Promise<RecallAnswer>;
148
221
  /** Assignments an earlier alpd left running, which recover() can continue once their root is open again. */
149
222
  recoverable(): LiveEntry[];
150
- /** Continues the assignments an earlier alpd left running in an open root's tree; with continueRoot, the root's own turn too. */
151
- recover(rootId: string, options?: { continueRoot?: boolean }): Promise<RecoveryOutcome[]>;
223
+ /** Continues work in a reopened tree. continueRoot resumes its running turn; parkedRoot restores its held continuation intent. */
224
+ recover(rootId: string, options?: { continueRoot?: boolean; parkedRoot?: string }): Promise<RecoveryOutcome[]>;
152
225
  /** Gives up the assignments of a tree whose root cannot be opened again: their tasks go back to open. */
153
226
  abandon(rootId: string, reason: string): Promise<RecoveryOutcome[]>;
154
227
  /** Closes everything; assignments still running stay in the live file, so the next alpd continues them. */
155
228
  shutdown(): Promise<void>;
229
+ /**
230
+ * Makes the native conversation a fork or rewind continues (docs/protocol/alp-json-rpc-v1.md §12.7): the
231
+ * source's conversation cut at a completed turn, persisted by the runtime and leaving the source
232
+ * unchanged. Touches no live session. Codex forks natively now (thread/fork); Claude validates the
233
+ * cut against the transcript and answers a binding the first prompt forks (NativeBinding.base).
234
+ * Refusals throw a ConversationError; one the runtime may or may not have acted on carries
235
+ * `outcomeUnknown: true`. Absent: the host cannot fork or rewind.
236
+ */
237
+ branch?(request: BranchRequest): Promise<NativeBinding>;
238
+ /**
239
+ * Moves an idle live root to another native conversation (a rewind), or reopens its own (a reload):
240
+ * its native process restarts and resumes `binding`, keeping the session id, its configuration and
241
+ * attached viewers. Refused (ConversationError session_busy) unless the whole tree is idle: no turn,
242
+ * pending prompt, child, assignment, question, mail or parked work. Emits session.updated.
243
+ * When the new binding cannot be opened, the old one is reopened and the error thrown; when neither
244
+ * opens, the session fails as a provider failure does.
245
+ */
246
+ rebind?(sessionId: string, binding: NativeBinding): Promise<SessionSnapshot>;
247
+ /**
248
+ * Restarts an idle live root's native process on the conversation it runs now (a reload, §12.8):
249
+ * the same binding, the session's own configuration, id and viewers. Refused as rebind is. The new
250
+ * process must resume that very conversation (a Claude one is refused unless its transcript, or its
251
+ * base, exists), never an empty one in its place; when it cannot, the session closes with its
252
+ * conversation kept (a later open resumes it) and a ConversationError native_refused is thrown.
253
+ * Emits session.updated.
254
+ */
255
+ reload?(sessionId: string): Promise<SessionSnapshot>;
256
+ /** Compacts a root's context at its next turn boundary, with a checkpoint main writes by skill compact (t-0e56). */
257
+ compact?(sessionId: string): { status: 'started' | 'deferred' | 'running' };
258
+ /** The slash commands and skills a live session's composer offers (t-f628): its runtime's, then its ALP skills. */
259
+ commands?(sessionId: string): Promise<RuntimeCommand[]>;
260
+ /**
261
+ * Holds the turns the runtime would start by itself on this session (mail wakes) while a lifecycle
262
+ * operation changes its conversation (a rewind, later a reload or live configure): mail stays queued
263
+ * and is delivered when the last hold is released, to whatever conversation the session runs then.
264
+ * rebind does not refuse for mail a hold keeps. Client prompts are not held here; alpd holds them.
265
+ * Undefined when the session is not open.
266
+ */
267
+ hold?(sessionId: string): (() => void) | undefined;
268
+ /**
269
+ * Whether an open session may begin a turn it has no id for yet: its turn/start (a prompt or a mail
270
+ * wake) is reserved, queued or on its way to the native runtime, or its process is opening or restarting. Such a
271
+ * turn shows in `activeTurnId` only once the runtime answers, and a hold taken meanwhile does not
272
+ * stop it. False when the session is not open.
273
+ */
274
+ starting?(sessionId: string): boolean;
275
+ /**
276
+ * What a live root would run with after a change of model, thinking, team or mode (§12.9), and whether
277
+ * reconfigure would take it now; reads only. `teams` are the teams the host defines for its project.
278
+ */
279
+ previewConfigure?(sessionId: string, changes: ConfigureChanges): Promise<ConfigurePreview>;
280
+ /**
281
+ * Changes an idle live root's model, thinking, team or mode (§12.9): resolves the new configuration
282
+ * as session.create would (same runtime, agent and conversation; never more permissions or new
283
+ * executable resources), then restarts its native process with it on the same conversation (`fresh`:
284
+ * a root with no turn yet starts a new, empty one). The session takes the new configuration only
285
+ * once the runtime took it (Codex echoes the model it resumed with); otherwise the old one is
286
+ * restarted and a ConversationError thrown (`outcomeUnknown` when the runtime may have acted). A
287
+ * new team also replaces the root's supervisor. Refused as rebind is while the tree is not idle.
288
+ * `onApplied` lets a host persist the configuration the runtime took before session.updated is
289
+ * emitted. It is awaited only for an applied change; its failure leaves the runtime configured
290
+ * and reports outcomeUnknown (never a rollback or a known native refusal).
291
+ * Emits session.updated after that persistence succeeds.
292
+ */
293
+ reconfigure?(sessionId: string, changes: ConfigureChanges, options?: { fresh?: boolean; onApplied?: (result: ConfigureResult) => Promise<void> }): Promise<ConfigureResult>;
294
+ };
295
+
296
+ import type { ConfigureChanges, EffectiveConfig } from './configure.js';
297
+ export type { ConfigureChanges, EffectiveConfig } from './configure.js';
298
+ import type { ConfigurePreview } from '@anhlp/alp-protocol/session';
299
+ export type { ConfigurePreview } from '@anhlp/alp-protocol/session';
300
+ /** What reconfigure did: the session as it runs now, its effective configuration, and whether its process restarted. */
301
+ export type ConfigureResult = {
302
+ session: SessionSnapshot;
303
+ effective: EffectiveConfig;
304
+ status: 'applied' | 'unchanged';
305
+ restarted: boolean;
306
+ /** What the native runtime answered it runs with (Codex: the resumed thread's model and effort). */
307
+ native?: { model?: string; reasoningEffort?: string };
156
308
  };
157
309
 
310
+ /** The native conversation a session continues: its thread, or for Claude one its first prompt makes from `base`. */
311
+ export type NativeBinding = { threadId: string; base?: NativeBase };
312
+
313
+ export type BranchRequest = {
314
+ runtime: RuntimeKind;
315
+ /** The conversation to branch: the source session's binding. */
316
+ source: NativeBinding;
317
+ /** Where the source session runs (Claude keeps its transcripts by this directory). */
318
+ cwd: string;
319
+ /** Where the branch will run; the source's cwd when absent. */
320
+ targetCwd?: string;
321
+ /** The configuration the branch keeps: Codex otherwise forks with its default model and settings. */
322
+ model: string;
323
+ thinking: string;
324
+ mode: string;
325
+ /**
326
+ * The cut, by ALP turn id (a Codex turn id; a Claude prompt uuid): keep through a completed turn, or
327
+ * everything before a turn. Absent: the whole conversation.
328
+ */
329
+ cutoff?: { throughTurnId: string } | { beforeTurnId: string };
330
+ /** The source root's turns in order, as ALP's timeline has them, for the cut's validation. */
331
+ turns: string[];
332
+ };
333
+
334
+ export type ConversationErrorReason = 'runtime_unsupported' | 'boundary_unmapped' | 'empty_prefix' | 'native_refused' | 'session_busy'
335
+ // A live configure (§12.9).
336
+ | 'runtime_mismatch' | 'agent_mismatch' | 'permission_escalation' | 'team_not_found' | 'invalid_params' | 'not_root';
337
+ /** A fork, rewind or rebind the runtime refused; `outcomeUnknown` when the native runtime may have acted. */
338
+ export class ConversationError extends Error {
339
+ readonly data: { reason: ConversationErrorReason };
340
+ readonly outcomeUnknown: boolean;
341
+ constructor(reason: ConversationErrorReason, message: string, { outcomeUnknown = false } = {}) {
342
+ super(message);
343
+ this.name = 'ConversationError';
344
+ this.data = { reason };
345
+ this.outcomeUnknown = outcomeUnknown;
346
+ }
347
+ }
348
+
158
349
  import type { SessionPreview } from '@anhlp/alp-protocol/session';
159
350
  export type { SessionPreview } from '@anhlp/alp-protocol/session';
160
351
 
@@ -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,23 +1,35 @@
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 { RuntimeCommand, 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';
8
+ export { resourceUses, pathActions } from './skill-resources.js';
6
9
  export type { SessionSpec, HostMcpServer, ResolvedSession, RuntimeKind } from './resolve.js';
7
- export { DEFAULT_MODEL, DEFAULT_CLAUDE_MODEL, models, modes, thinkingOptions, thinkingOptionsFor } from './catalog.js';
10
+ export { DEFAULT_MODEL, DEFAULT_CLAUDE_MODEL, entries as catalogEntries, models, modes, thinkingOptions, thinkingOptionsFor } from './catalog.js';
11
+ export type { CatalogEntry } from './catalog.js';
12
+ export { ModelCatalog, mergeCatalog, liveFromContext, feedCatalog, feedAcpSession, acpSessionModels, setActiveCatalog, activeCatalog, POLICY as CATALOG_POLICY, REFRESH_MS as CATALOG_REFRESH_MS } from './model-catalog.js';
13
+ export type { CatalogSnapshot, CatalogRuntime, LiveModel, Probe as CatalogProbe, AcpProviderConfig, AcpProbe, AcpRow, AcpState } from './model-catalog.js';
14
+ export { liveProbes, codexProbe, claudeProbe, antigravityProbe, parseAgyModels } from './model-probes.js';
8
15
  export { CodexTransport } from './transport.js';
16
+ export { ATTACHMENT_HEADER, ATTACHMENT_ROUTES, attachmentStageDir, createAttachmentStager, stagingExposure } from './attachments.js';
17
+ export type { AttachmentReader, AttachmentRoute } from './attachments.js';
9
18
  export { usageAllows } from './runtime-context.js';
10
19
  export { AcpTransport, acpDecision, acpEnv, acpPermission } from './acp-transport.js';
11
20
  export type { AcpProvider } from './acp-transport.js';
12
21
  export { AntigravityTransport } from './antigravity-transport.js';
13
22
  export type { AntigravityProvider } from './antigravity-transport.js';
14
- export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, skillPlugin, SKILL_PLUGIN, toolShapes as claudeToolShapes } from './claude-transport.js';
23
+ export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, customClearAliases, nativeCommandRefusal, skillPlugin, SKILL_PLUGIN, toolShapes as claudeToolShapes } from './claude-transport.js';
15
24
  export { MAIL_BATCH_CHARS, MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from './mailbox.js';
16
25
  export type { MailEvent, MailKind } from './mailbox.js';
17
- export { createCopy, gitEnvironment, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
26
+ export { createCopy, gitEnvironment, reattachWorktree, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
27
+ export type { LeftWorktree } from './workspace.js';
18
28
  export { OWN_START, processStartedAt, sameProcessAlive } from './process-info.js';
19
29
  export type { Worktree, WorktreeChange } from './workspace.js';
20
30
  export { PIN_KINDS, renderBoard, renderPin } from './board.js';
31
+ export { inputLimitError, TOOL_INPUT, POUR_VARS } from './input-limits.js';
32
+ export type { InputLimits } from './input-limits.js';
21
33
  export { CHOICES, isVietnamese, languageInstruction, words } from './language.js';
22
34
  export type { Words } from './language.js';
23
35
  export type { Pin, PinKind } from './board.js';
@@ -26,3 +38,4 @@ export { ProviderRegistry, createProviderRegistry } from './providers.js';
26
38
  export type { ProviderContext, ProviderFactory, ProviderFactories } from './providers.js';
27
39
  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
40
  export type { AcpCall, ClaudeResult, CodexToolCall, ToolCallDetail } from './tool-detail.js';
41
+ 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
+ }