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