@anhlp/alp-runtime 0.0.0-stage → 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 (127) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +7 -0
  3. package/README.md +6 -2
  4. package/dist/acp-transport.d.ts +130 -0
  5. package/dist/acp-transport.js +482 -0
  6. package/dist/antigravity-transport.d.ts +107 -0
  7. package/dist/antigravity-transport.js +665 -0
  8. package/dist/assignment-results.d.ts +55 -0
  9. package/dist/assignment-results.js +181 -0
  10. package/dist/attachments.d.ts +84 -0
  11. package/dist/attachments.js +213 -0
  12. package/dist/board-domain.d.ts +56 -0
  13. package/dist/board-domain.js +157 -0
  14. package/dist/board.d.ts +27 -0
  15. package/dist/board.js +76 -0
  16. package/dist/catalog.d.ts +44 -0
  17. package/dist/catalog.js +47 -0
  18. package/dist/claude-transport.d.ts +251 -0
  19. package/dist/claude-transport.js +931 -0
  20. package/dist/compact.d.ts +29 -0
  21. package/dist/compact.js +49 -0
  22. package/dist/configure.d.ts +44 -0
  23. package/dist/configure.js +64 -0
  24. package/dist/contracts.d.ts +378 -0
  25. package/dist/contracts.js +16 -0
  26. package/dist/conversation.d.ts +45 -0
  27. package/dist/conversation.js +62 -0
  28. package/dist/events.d.ts +1 -0
  29. package/dist/events.js +0 -0
  30. package/dist/github.d.ts +10 -0
  31. package/dist/github.js +39 -0
  32. package/dist/handoff.d.ts +36 -0
  33. package/dist/handoff.js +73 -0
  34. package/dist/index.d.ts +39 -0
  35. package/dist/index.js +122 -0
  36. package/dist/input-limits.d.ts +25 -0
  37. package/dist/input-limits.js +48 -0
  38. package/dist/language.d.ts +51 -0
  39. package/dist/language.js +94 -0
  40. package/dist/live.d.ts +48 -0
  41. package/dist/live.js +50 -0
  42. package/dist/mailbox.d.ts +26 -0
  43. package/dist/mailbox.js +38 -0
  44. package/dist/mcp-tools.d.ts +123 -0
  45. package/dist/mcp-tools.js +97 -0
  46. package/dist/model-catalog.d.ts +162 -0
  47. package/dist/model-catalog.js +338 -0
  48. package/dist/model-probes.d.ts +7 -0
  49. package/dist/model-probes.js +69 -0
  50. package/dist/permission-path.d.ts +2 -0
  51. package/dist/permission-path.js +44 -0
  52. package/dist/process-info.d.ts +14 -0
  53. package/dist/process-info.js +32 -0
  54. package/dist/providers.d.ts +28 -0
  55. package/dist/providers.js +73 -0
  56. package/dist/recall.d.ts +42 -0
  57. package/dist/recall.js +61 -0
  58. package/dist/resolve.d.ts +123 -0
  59. package/dist/resolve.js +242 -0
  60. package/dist/runtime-context.d.ts +43 -0
  61. package/dist/runtime-context.js +61 -0
  62. package/dist/runtime.d.ts +13 -0
  63. package/dist/runtime.js +4818 -0
  64. package/dist/session-config.d.ts +2345 -0
  65. package/dist/session-config.js +209 -0
  66. package/dist/session-state.d.ts +190 -0
  67. package/dist/session-state.js +0 -0
  68. package/dist/skill-resources.d.ts +30 -0
  69. package/dist/skill-resources.js +55 -0
  70. package/dist/tool-detail.d.ts +81 -0
  71. package/dist/tool-detail.js +332 -0
  72. package/dist/tool-results.d.ts +12 -0
  73. package/dist/tool-results.js +25 -0
  74. package/dist/tools.d.ts +827 -0
  75. package/dist/tools.js +463 -0
  76. package/dist/transport.d.ts +47 -0
  77. package/dist/transport.js +171 -0
  78. package/dist/usage.d.ts +25 -0
  79. package/dist/usage.js +60 -0
  80. package/dist/workspace.d.ts +127 -0
  81. package/dist/workspace.js +340 -0
  82. package/dist/worktree-domain.d.ts +89 -0
  83. package/dist/worktree-domain.js +199 -0
  84. package/dist/write-error.d.ts +2 -0
  85. package/dist/write-error.js +10 -0
  86. package/package.json +262 -4
  87. package/src/acp-transport.ts +481 -0
  88. package/src/antigravity-transport.ts +740 -0
  89. package/src/assignment-results.ts +154 -0
  90. package/src/attachments.ts +254 -0
  91. package/src/board-domain.ts +185 -0
  92. package/src/board.ts +87 -0
  93. package/src/catalog.ts +43 -0
  94. package/src/claude-transport.ts +1097 -0
  95. package/src/compact.ts +62 -0
  96. package/src/configure.ts +93 -0
  97. package/src/contracts.ts +363 -0
  98. package/src/conversation.ts +81 -0
  99. package/src/events.ts +1 -0
  100. package/src/github.ts +37 -0
  101. package/src/handoff.ts +86 -0
  102. package/src/index.ts +41 -0
  103. package/src/input-limits.ts +65 -0
  104. package/src/language.ts +130 -0
  105. package/src/live.ts +90 -0
  106. package/src/mailbox.ts +49 -0
  107. package/src/mcp-tools.ts +106 -0
  108. package/src/model-catalog.ts +316 -0
  109. package/src/model-probes.ts +58 -0
  110. package/src/permission-path.ts +37 -0
  111. package/src/process-info.ts +40 -0
  112. package/src/providers.ts +87 -0
  113. package/src/recall.ts +86 -0
  114. package/src/resolve.ts +238 -0
  115. package/src/runtime-context.ts +49 -0
  116. package/src/runtime.ts +5608 -0
  117. package/src/session-config.ts +312 -0
  118. package/src/session-state.ts +180 -0
  119. package/src/skill-resources.ts +73 -0
  120. package/src/tool-detail.ts +397 -0
  121. package/src/tool-results.ts +26 -0
  122. package/src/tools.ts +466 -0
  123. package/src/transport.ts +118 -0
  124. package/src/usage.ts +79 -0
  125. package/src/workspace.ts +424 -0
  126. package/src/worktree-domain.ts +220 -0
  127. package/src/write-error.ts +4 -0
@@ -0,0 +1,1097 @@
1
+ import { writablePath } from './permission-path.js';
2
+ import { accessSync, constants, existsSync, mkdirSync, realpathSync, rmdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { optionalRead, claudeUsage } from './runtime-context.js';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { z } from 'zod';
8
+ import { BOARD_KINDS_INPUT, PIN_BODY_CHARS, PIN_KINDS, PIN_PATH_CHARS, PIN_PATHS, PIN_PATHS_INPUT } from './board.js';
9
+ import { RESULT_OUTCOMES } from './assignment-results.js';
10
+ import { inputLimitError, POUR_VARS, VAR_NAME, type InputLimits } from './input-limits.js';
11
+ import { claudeToolDetail, resultText } from './tool-detail.js';
12
+ import { CLOSE_REASONS, GATE_KINDS, TASK_STATUSES, TASK_TYPES } from '@anhlp/alp-core/tasks';
13
+ import { commandDecision } from '@anhlp/alp-core/permissions';
14
+ import { isScript, nativeDaemon, nodeExecutable } from '@anhlp/alp-core/packaged';
15
+
16
+ // Keep the Claude SDK behind the runtime boundary. Paseo inspects static
17
+ // imports while compiling plugin entrypoints, including their declaration
18
+ // graph; the SDK is a daemon-only optional runtime dependency.
19
+ // The native alpd (t-81b0.9) carries the SDK inside its executable: there is no node_modules to import
20
+ // it from by name, so its entry registers it.
21
+ const CLAUDE_SDK = ['@anthropic-ai', 'claude-agent-sdk'].join('/');
22
+ const claudeSdk = (): Promise<any> => nativeDaemon()?.modules.claudeAgentSdk?.() ?? import(CLAUDE_SDK);
23
+ /**
24
+ * A JavaScript `claude` (a test's fake, an npm install's cli.js) runs under Node. The SDK would pick
25
+ * `bun` inside the native alpd, so name the Node there.
26
+ */
27
+ // The SDK treats .js/.mjs/.cjs/.ts/.tsx/.jsx as scripts.
28
+ const scriptExecutable = (command: string): { executable?: any } => nativeDaemon() && (isScript(command) || /\.(ts|tsx|jsx)$/i.test(command)) ? { executable: nodeExecutable() } : {};
29
+
30
+ type SDKUserMessage = any;
31
+ type SDKMessage = any;
32
+ type ClaudeQuery = AsyncGenerator<SDKMessage, void> & {
33
+ supportedModels(): Promise<Array<{ value: string; displayName: string; description: string; supportedEffortLevels?: string[] }>>;
34
+ supportedCommands(): Promise<Array<{ name: string; description: string; argumentHint?: string; builtin?: boolean }>>;
35
+ usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(options: { skipBehaviors: boolean }): Promise<any>;
36
+ getContextUsage(options: { detail: 'summary' | 'full' }): Promise<any>;
37
+ interrupt(): Promise<unknown>;
38
+ setPermissionMode(mode: 'default' | 'acceptEdits' | 'bypassPermissions'): Promise<void>;
39
+ close(): void;
40
+ initializationResult?(): Promise<unknown>;
41
+ };
42
+
43
+ /**
44
+ * A field whose size is checked before zod walks it; its JSON Schema is the inner schema's
45
+ * (input-limits.ts).
46
+ *
47
+ * Needed for any field zod's own cap does not protect. zod's GHSA-mrhx-c7xc-m3w5 fix (4.6.6) refuses
48
+ * a collection over its `.max()` before reading an element for `array`, `map` and `set` — and for
49
+ * NOTHING ELSE. `z.record` is NOT covered: a capped record is still read element by element, one
50
+ * issue kept per failure (t-5294.4). So a limited record must go through `bounded` (as `vars` below
51
+ * does), and turning a capped `z.array` field into a `z.record` silently drops that protection.
52
+ * docs/alp/zod-advisory.md has the repository-wide survey.
53
+ */
54
+ const bounded = <T extends z.ZodType>(schema: T, limits: InputLimits) => z.preprocess((value, ctx) => {
55
+ const error = inputLimitError(value, limits);
56
+ if (error) ctx.addIssue({ code: 'custom', message: error });
57
+ return value;
58
+ }, schema);
59
+
60
+ // Zod mirrors of the provider's dynamic tool schemas; the provider validates again.
61
+ const handoffList = z.array(z.string().min(1)).max(100).optional();
62
+ const taskIds = z.array(z.string().min(1)).max(50).optional();
63
+ const taskLinks = z.object({ blockedBy: taskIds, related: taskIds, parent: z.string().min(1).optional() }).strict().optional();
64
+ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
65
+ alp_delegate: {
66
+ agent: z.string().min(1),
67
+ task: z.string().min(1).max(32_000),
68
+ model: z.string().min(1).optional(),
69
+ thinking: z.string().min(1).optional(),
70
+ modelReason: z.string().min(1).optional(),
71
+ mode: z.enum(['read-only', 'workspace-write', 'full-access']).optional(),
72
+ isolation: z.enum(['shared', 'worktree']).optional(),
73
+ writeRoot: z.string().min(1).optional(),
74
+ wait: z.boolean().optional(),
75
+ etaMinutes: z.number().int().min(1).max(1440).optional(),
76
+ taskId: z.string().min(1).optional(),
77
+ continueFrom: z.string().min(1).optional(),
78
+ },
79
+ alp_merge: {
80
+ assignmentId: z.string().min(1),
81
+ skipVerify: z.string().min(1).max(2000).optional(),
82
+ },
83
+ alp_verify: {
84
+ taskId: z.string().min(1).optional(),
85
+ },
86
+ alp_recall: {
87
+ assignmentId: z.string().min(1).optional(),
88
+ taskId: z.string().min(1).optional(),
89
+ question: z.string().min(1).max(4000),
90
+ },
91
+ alp_lesson: {
92
+ scope: z.enum(['project', 'user']),
93
+ lesson: z.string().min(1).max(600),
94
+ },
95
+ alp_lesson_curate: {
96
+ changes: z.array(z.object({
97
+ scope: z.enum(['project', 'user']),
98
+ remove: z.array(z.string().min(1).max(600)).min(1).max(50),
99
+ add: z.string().min(1).max(600).optional(),
100
+ reason: z.string().max(300).optional(),
101
+ }).strict()).min(1).max(50),
102
+ requestId: z.string().min(1).max(100).optional(),
103
+ },
104
+ alp_skill: {
105
+ name: z.string().min(1),
106
+ description: z.string().min(1).max(300),
107
+ body: z.string().min(1).max(20_000),
108
+ roles: z.array(z.string().min(1)).min(1).max(10),
109
+ lessons: z.array(z.string().min(1).max(600)).max(50).optional(),
110
+ replace: z.boolean().optional(),
111
+ requestId: z.string().min(1).max(100).optional(),
112
+ },
113
+ alp_skill_retire: {
114
+ name: z.string().min(1).max(64),
115
+ reason: z.string().min(1).max(300),
116
+ requestId: z.string().min(1).max(100).optional(),
117
+ },
118
+ alp_issue: {
119
+ action: z.enum(['search', 'create', 'comment']),
120
+ target: z.enum(['project', 'alp']),
121
+ query: z.string().min(1).max(200).optional(),
122
+ requestId: z.string().min(1).max(100).optional(),
123
+ title: z.string().min(1).max(200).optional(),
124
+ body: z.string().min(1).max(20_000).optional(),
125
+ issue: z.number().int().positive().optional(),
126
+ labels: z.array(z.string().min(1).max(50)).max(10).optional(),
127
+ },
128
+ alp_schedule: {
129
+ action: z.enum(['create', 'list', 'get', 'cancel']),
130
+ dueAt: z.string().min(1).max(80).optional(),
131
+ prompt: z.string().min(1).max(8000).optional(),
132
+ requestId: z.string().min(1).max(200).optional(),
133
+ id: z.string().min(1).optional(),
134
+ status: z.enum(['pending', 'delivered', 'failed', 'cancelled']).optional(),
135
+ },
136
+ alp_task: {
137
+ action: z.enum(['create', 'update', 'link', 'start', 'close', 'reopen', 'gate', 'clear', 'pour', 'formulas', 'show', 'list', 'ready']),
138
+ id: z.string().min(1).optional(),
139
+ title: z.string().min(1).max(200).optional(),
140
+ description: z.string().max(8000).optional(),
141
+ type: z.enum(TASK_TYPES as [string, ...string[]]).optional(),
142
+ priority: z.number().int().min(0).max(4).optional(),
143
+ labels: z.array(z.string().min(1).max(50)).max(10).optional(),
144
+ paths: z.array(z.string().min(1)).max(50).optional(),
145
+ parent: z.string().min(1).optional(),
146
+ blockedBy: taskIds,
147
+ discoveredFrom: z.string().min(1).optional(),
148
+ add: taskLinks,
149
+ remove: taskLinks,
150
+ reason: z.enum(CLOSE_REASONS as [string, ...string[]]).optional(),
151
+ kind: z.enum(GATE_KINDS as [string, ...string[]]).optional(),
152
+ until: z.string().min(1).optional(),
153
+ ref: z.string().min(1).optional(),
154
+ options: z.array(z.string().min(1).max(200)).max(10).optional(),
155
+ gate: z.string().min(1).optional(),
156
+ formula: z.string().min(1).optional(),
157
+ vars: bounded(z.record(z.string().regex(VAR_NAME), z.string().max(POUR_VARS.string)), POUR_VARS).optional(),
158
+ summary: z.string().min(1).max(2000).optional(),
159
+ unverified: z.string().min(1).max(2000).optional(),
160
+ note: z.string().min(1).max(2000).optional(),
161
+ status: z.enum(TASK_STATUSES as [string, ...string[]]).optional(),
162
+ label: z.string().min(1).optional(),
163
+ limit: z.number().int().positive().optional(),
164
+ },
165
+ alp_discard: {
166
+ assignmentId: z.string().min(1),
167
+ },
168
+ alp_resolve: {
169
+ assignmentId: z.string().min(1),
170
+ outcome: z.enum(RESULT_OUTCOMES),
171
+ note: z.string().min(1).max(2000).optional(),
172
+ },
173
+ alp_cancel: {
174
+ assignmentId: z.string().min(1),
175
+ reason: z.string().optional(),
176
+ },
177
+ alp_pin: {
178
+ kind: z.enum(PIN_KINDS),
179
+ body: z.string().min(1).max(PIN_BODY_CHARS),
180
+ paths: bounded(z.array(z.string().min(1).max(PIN_PATH_CHARS)).max(PIN_PATHS), PIN_PATHS_INPUT).optional(),
181
+ },
182
+ alp_board: {
183
+ kinds: bounded(z.array(z.enum(PIN_KINDS)).max(PIN_KINDS.length), BOARD_KINDS_INPUT).optional(),
184
+ limit: z.number().int().positive().optional(),
185
+ },
186
+ alp_unpin: {
187
+ pinId: z.string().min(1),
188
+ },
189
+ alp_wait: {
190
+ assignments: z.array(z.string().min(1)).max(32).optional(),
191
+ timeoutMs: z.number().int().positive().optional(),
192
+ },
193
+ alp_send: {
194
+ to: z.string().min(1),
195
+ kind: z.enum(['answer', 'note', 'steer']),
196
+ body: z.string().min(1).max(8000),
197
+ replyTo: z.string().min(1).optional(),
198
+ },
199
+ alp_ask: {
200
+ question: z.string().min(1).max(8000),
201
+ to: z.enum(['parent', 'user']).optional(),
202
+ options: z.array(z.string().min(1).max(200)).max(10).optional(),
203
+ },
204
+ alp_handoff: {
205
+ outcome: z.enum(['complete', 'partial', 'blocked', 'reconsider']),
206
+ summary: z.string().min(1),
207
+ candidate: handoffList,
208
+ scope: handoffList,
209
+ verification: handoffList,
210
+ risks: handoffList,
211
+ discovered: handoffList,
212
+ ownership: z.string().optional(),
213
+ // ALP checks that the result follows from the criteria and findings (ALPD §38).
214
+ verdict: z.object({
215
+ result: z.enum(['pass', 'pass_with_findings', 'fail', 'blocked']),
216
+ criteria: z.array(z.object({ criterion: z.string().min(1), result: z.enum(['pass', 'fail', 'not_checked']), evidence: z.string().min(1) }).strict()).min(1).max(50),
217
+ findings: z.array(z.object({ severity: z.enum(['critical', 'high', 'medium', 'low']), where: z.string().min(1), problem: z.string().min(1), fix: z.string().min(1).optional() }).strict()).max(100).optional(),
218
+ }).strict().optional(),
219
+ },
220
+ };
221
+
222
+ type Listener = (method: string, params: any) => void;
223
+ type RequestHandler = (method: string, params: any) => Promise<unknown>;
224
+
225
+ type NativeConfig = {
226
+ cwd: string;
227
+ model: string;
228
+ sandbox: string;
229
+ developerInstructions: string;
230
+ mcpServers: Record<string, any>;
231
+ thinking: string;
232
+ dynamicTools: Array<{
233
+ name: string;
234
+ description: string;
235
+ }>;
236
+ ephemeral?: boolean;
237
+ threadId?: string;
238
+ /** The session's permission profile: rules Claude enforces itself, in every permission mode. */
239
+ permissions?: PermissionRules | null;
240
+ /** The OS sandbox for Bash, when ALP chose one. */
241
+ floor?: 'read-only' | 'workspace-write';
242
+ /** The context window the session works in before Claude compacts it, in tokens; absent: the model's (ALPD §57). */
243
+ context?: number;
244
+ /** The agent's skills, each a SKILL.md, loaded as Claude Code skills alp:<name> (ALPD §59). */
245
+ skills?: Array<{ name: string; path: string }>;
246
+ };
247
+
248
+ /** The plugin name ALP's skills are loaded under, so Claude Code calls them alp:<name>. */
249
+ export const SKILL_PLUGIN = 'alp';
250
+ /** Claude's /clear and its aliases (supportedCommands reports `clear [reset, new]`): each starts a new conversation. */
251
+ const NEW_CONVERSATION_COMMANDS = ['clear', 'reset', 'new'];
252
+ const NEW_CONVERSATION = new RegExp(`^\\s*\\/(${NEW_CONVERSATION_COMMANDS.join('|')})(?:\\s|$)`);
253
+ /** Claude's own commands the composer does not offer: ALP does their work its own way (t-efa3). */
254
+ const ALP_HANDLED_COMMANDS = new Set([...NEW_CONVERSATION_COMMANDS, 'compact', 'rewind']);
255
+ /** The aliases of /clear a command of the user's may take as its own name. */
256
+ const CLEAR_ALIASES = new Set(['reset', 'new']);
257
+
258
+ type ListedCommand = { name?: unknown; builtin?: unknown };
259
+ /**
260
+ * t-5ac5: the aliases of /clear (new, reset) that, in this listing, run a command of the user's,
261
+ * project, plugin or MCP server rather than Claude's /clear. The SDK marks Claude's own rows
262
+ * `builtin: true`; a marked row wins its name, and an alias runs a command that has it as its name
263
+ * (SlashCommand.builtin). So /new is the user's when an unmarked row is named new and no marked row is.
264
+ * A listing without the marker (an older Claude Code) cannot tell the two apart: nothing is the
265
+ * user's then, and ALP keeps refusing /new and /reset, since letting Claude's /clear through loses the
266
+ * conversation while refusing a custom command only costs the user its name. /clear itself is always
267
+ * Claude's: a marked row is named clear.
268
+ */
269
+ export function customClearAliases(listed: ReadonlyArray<ListedCommand> | undefined): Set<string> {
270
+ const rows = Array.isArray(listed) ? listed : [];
271
+ if (!rows.some(row => typeof row?.builtin === 'boolean')) return new Set();
272
+ const builtin = new Set(rows.filter(row => row?.builtin === true).map(row => row.name));
273
+ return new Set(rows.filter(row => row?.builtin !== true && typeof row?.name === 'string' && CLEAR_ALIASES.has(row.name) && !builtin.has(row.name)).map(row => row.name as string));
274
+ }
275
+
276
+ /**
277
+ * t-e906: Claude's /clear moves it to a new conversation under a new session id while ALP keeps the
278
+ * old thread, so resume, fork and rewind would point at the conversation from before. ALP refuses it
279
+ * rather than follow: its timeline, turn ids and rewinds belong to the old conversation. /reset and /new are
280
+ * the same command, unless the session lists a command of the user's under that name (`custom`,
281
+ * from customClearAliases).
282
+ */
283
+ export function nativeCommandRefusal(runtimeKind: string, content: ReadonlyArray<{ type: string; text?: string }>, custom?: ReadonlySet<string>) {
284
+ if (runtimeKind !== 'claude') return undefined;
285
+ // The text Claude gets: every text part, joined as startPrompt joins them.
286
+ const typed = content.filter(part => part.type === 'text').map(part => part.text ?? '').join('\n');
287
+ const named = NEW_CONVERSATION.exec(typed)?.[1];
288
+ if (!named || custom?.has(named)) return undefined;
289
+ return 'ALP does not pass /clear (or /new, /reset) to Claude: Claude would start a new conversation that this session does not follow. Start a new session in ALP for a fresh conversation, or compact this one (alp compact, or Compact in the app).';
290
+ }
291
+
292
+ /**
293
+ * A Claude Code plugin in `directory` holding the given skills, linked to their own
294
+ * directories so an edit to a skill reaches the next session (ALPD §59).
295
+ */
296
+ export function skillPlugin(directory: string, skills: Array<{ name: string; path: string }>) {
297
+ rmSync(directory, { recursive: true, force: true });
298
+ mkdirSync(path.join(directory, '.claude-plugin'), { recursive: true });
299
+ mkdirSync(path.join(directory, 'skills'));
300
+ writeFileSync(path.join(directory, '.claude-plugin', 'plugin.json'), JSON.stringify({ name: SKILL_PLUGIN, description: "The agent's ALP skills" }));
301
+ for (const skill of skills) symlinkSync(path.dirname(skill.path), path.join(directory, 'skills', skill.name), 'dir');
302
+ return directory;
303
+ }
304
+
305
+ type PermissionRules = {
306
+ allow: string[]; ask?: string[]; deny: string[]; beyondMode?: 'refuse' | 'ask';
307
+ /** The OS sandbox ALP puts Bash in, and the directory it may write besides temp files. */
308
+ floor?: 'read-only' | 'workspace-write'; floorRoot?: string;
309
+ };
310
+
311
+ /** Whether Claude Code can sandbox Bash here: Seatbelt on macOS, bubblewrap and socat on Linux. ALP_CLAUDE_SANDBOX=0 turns it off, =1 claims it (tests). */
312
+ export function claudeSandboxAvailable() {
313
+ if (process.env.ALP_CLAUDE_SANDBOX === '0') return false;
314
+ if (process.env.ALP_CLAUDE_SANDBOX === '1') return true;
315
+ if (process.platform === 'darwin') return existsSync('/usr/bin/sandbox-exec');
316
+ if (process.platform !== 'linux') return false;
317
+ const onPath = (name: string) => (process.env.PATH ?? '').split(path.delimiter).some(dir => dir && existsSync(path.join(dir, name)));
318
+ return onPath('bwrap') && onPath('socat');
319
+ }
320
+
321
+ const WRITERS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'];
322
+ /** What ALP asks the user for a permission Claude would otherwise not have. */
323
+ /** One turn-input part as Claude's: text, or a data-URL image as a base64 image block. */
324
+ export function claudeContent(part: any) {
325
+ const image = part?.type === 'image' && typeof part.url === 'string' ? /^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec(part.url) : null;
326
+ if (part?.type === 'image' && !image) throw new Error('Claude takes images as inline base64 PNG, JPEG, GIF or WebP only');
327
+ return image ? { type: 'image', source: { type: 'base64', media_type: image[1], data: image[2] } } : { type: 'text', text: part.text };
328
+ }
329
+
330
+ export type PermissionRequest = { tool: string; input: Record<string, unknown>; reason: 'rule' | 'mode'; rule?: string };
331
+ export type PermissionAnswer = { allow: boolean; always?: boolean; message?: string };
332
+
333
+ /** The rule an "always allow" adds: Claude's own suggestion, else the exact command or path. */
334
+ function suggestedRule(tool: string, input: Record<string, unknown>, suggestions: any) {
335
+ const suggestion = (Array.isArray(suggestions) ? suggestions : []).find((entry: any) => entry?.type === 'addRules' && entry.behavior === 'allow' && entry.rules?.length);
336
+ const rule = suggestion?.rules[0];
337
+ if (rule?.toolName) return rule.ruleContent ? `${rule.toolName}(${rule.ruleContent})` : rule.toolName;
338
+ if (tool === 'Bash' && typeof input.command === 'string' && !input.command.includes(')')) return `Bash(${input.command})`;
339
+ if (typeof input.file_path === 'string' && !input.file_path.includes(')')) return `${tool}(${input.file_path})`;
340
+ return undefined;
341
+ }
342
+
343
+ class InputQueue implements AsyncIterable<SDKUserMessage> {
344
+ private values: SDKUserMessage[] = [];
345
+ private waiters: Array<(value: IteratorResult<SDKUserMessage>) => void> = [];
346
+ private ended = false;
347
+
348
+ push(value: SDKUserMessage) {
349
+ if (this.ended) throw new Error('Claude input is closed');
350
+ const waiter = this.waiters.shift();
351
+ if (waiter) waiter({ value, done: false });
352
+ else this.values.push(value);
353
+ }
354
+
355
+ close() {
356
+ this.ended = true;
357
+ for (const waiter of this.waiters.splice(0)) {
358
+ waiter({ value: undefined, done: true });
359
+ }
360
+ }
361
+
362
+ [Symbol.asyncIterator](): AsyncIterator<SDKUserMessage> {
363
+ return {
364
+ next: () => {
365
+ const value = this.values.shift();
366
+ if (value) return Promise.resolve({ value, done: false });
367
+ if (this.ended) {
368
+ return Promise.resolve({ value: undefined, done: true });
369
+ }
370
+ return new Promise((resolve) => this.waiters.push(resolve));
371
+ },
372
+ };
373
+ }
374
+ }
375
+
376
+ /** Claude's permission mode for an ALP mode; full-access skips every permission check. */
377
+ export const claudePermissionMode = (sandbox: string) => sandbox === 'read-only' ? 'default' : sandbox === 'full-access' ? 'bypassPermissions' : 'acceptEdits';
378
+
379
+ export function claudePermissions(sandbox: string, currentSandbox?: () => string, rules?: PermissionRules | null, ask?: (request: PermissionRequest) => Promise<PermissionAnswer>) {
380
+ const readOnly = sandbox === 'read-only';
381
+ // A skill only adds instructions; what they lead to is checked as itself (ALPD §59).
382
+ const readers = ['Read', 'Glob', 'Grep', 'WebSearch', 'WebFetch', 'Skill'];
383
+ return {
384
+ // Plan mode permits writes to plan files and requires ExitPlanMode approval.
385
+ // Fixed read-only callers restrict the tool surface; live sessions keep
386
+ // tools available and consult the current sandbox at the permission gate.
387
+ permissionMode: claudePermissionMode(sandbox),
388
+ // Lets a live session switch to full-access later; it bypasses nothing by itself.
389
+ allowDangerouslySkipPermissions: true,
390
+ ...(readOnly && !currentSandbox ? { tools: [...readers, ...(rules?.floor === 'read-only' ? ['Bash'] : [])] } : {}),
391
+ // Allow rules run without asking, even in a read-only session; deny rules hold even with full access.
392
+ ...(rules?.allow.length ? { allowedTools: rules.allow } : {}),
393
+ disallowedTools: ['Agent', 'Task', 'TeamCreate', 'EnterPlanMode', 'ExitPlanMode', ...(rules?.deny ?? [])],
394
+ // Ask rules make Claude consult canUseTool in every mode, which asks the user.
395
+ ...(rules?.ask?.length ? { settings: { permissions: { ask: rules.ask } } } : {}),
396
+ // The floor: Bash runs in the OS sandbox, which writes only the workspace (or nothing, read-only) and temp files, offline.
397
+ // Keep the SDK's restrictive host-network defaults. Broad Unix socket/localhost
398
+ // access lets host services act outside this floor; the SDK cannot scope local
399
+ // binding to a test server, and scoped Unix sockets are not portable to Linux.
400
+ // A command leaves it only with dangerouslyDisableSandbox, which Claude allows itself for allow rules and asks canUseTool otherwise.
401
+ ...(rules?.floor ? {
402
+ sandbox: {
403
+ enabled: true,
404
+ autoAllowBashIfSandboxed: false,
405
+ allowUnsandboxedCommands: true,
406
+ ...(rules.floor === 'read-only' && rules.floorRoot ? { filesystem: { denyWrite: [rules.floorRoot] } } : {}),
407
+ },
408
+ } : {}),
409
+ canUseTool: async (name: string, input: Record<string, unknown>, context?: { decisionReasonType?: string; suggestions?: unknown }) => {
410
+ const mode = currentSandbox ? currentSandbox() : sandbox;
411
+ const leaving = Boolean(rules?.floor) && name === 'Bash' && input.dangerouslyDisableSandbox === true;
412
+ // Inside a read-only floor the OS keeps Bash from writing, so it may run.
413
+ const sandboxed = rules?.floor === 'read-only' && name === 'Bash' && !leaving;
414
+ const beyond = (mode === 'read-only' && !readers.includes(name) && !name.startsWith('mcp__alp__') && !sandboxed) ||
415
+ // With a floor, file tools write only the workspace and temp files, like Bash.
416
+ (Boolean(rules?.floor && rules.floorRoot) && WRITERS.includes(name) && !writablePath(name === 'NotebookEdit' ? input.notebook_path : input.file_path, rules!.floorRoot!)) ||
417
+ (leaving && mode !== 'full-access');
418
+ if (leaving && typeof input.command === 'string' && rules) {
419
+ const decision = commandDecision(rules, input.command);
420
+ if (decision === 'deny') return { behavior: 'deny', message: 'A deny rule of your permission profile covers it' };
421
+ if (decision === 'allow') return { behavior: 'allow', updatedInput: input };
422
+ if (decision === 'ask' && ask) context = { ...context, decisionReasonType: 'rule' };
423
+ }
424
+ const reason = context?.decisionReasonType === 'rule' && (rules?.ask?.length || leaving) ? 'rule' : beyond && rules?.beyondMode === 'ask' ? 'mode' : undefined;
425
+ if (reason && ask) {
426
+ const rule = reason === 'mode' ? suggestedRule(name, input, context?.suggestions) : undefined;
427
+ const answer = await ask({ tool: name, input, reason, ...(rule ? { rule } : {}) });
428
+ if (!answer.allow) return { behavior: 'deny', message: answer.message ?? 'The user did not allow it' };
429
+ const [, toolName, ruleContent] = /^([^(]+)(?:\((.*)\))?$/s.exec(rule ?? '') ?? [];
430
+ // The read-only floor would refuse the very write the user just allowed: run that command outside it.
431
+ const approved = sandboxed && reason === 'rule' ? { ...input, dangerouslyDisableSandbox: true } : input;
432
+ return { behavior: 'allow', updatedInput: approved, ...(answer.always && toolName ? { updatedPermissions: [{ type: 'addRules', rules: [{ toolName, ...(ruleContent ? { ruleContent } : {}) }], behavior: 'allow', destination: 'session' }] } : {}) };
433
+ }
434
+ if (leaving && beyond) return { behavior: 'deny', message: 'Bash runs inside the sandbox; leaving it needs an allow rule in your permission profile' };
435
+ if (beyond) return { behavior: 'deny', message: mode === 'read-only' ? 'ALP session is read-only' : 'Outside your workspace' };
436
+ return { behavior: 'allow', updatedInput: input };
437
+ },
438
+ };
439
+ }
440
+
441
+ /** Whether Claude's last rate limit report means requests are refused: rejected, with no overage to fall back on. */
442
+ export const claudeLimited = (info?: { status: string; overageStatus?: string }) =>
443
+ info?.status === 'rejected' && info.overageStatus !== 'allowed' && info.overageStatus !== 'allowed_warning';
444
+
445
+ /** How long a resume waits for Claude to start before it goes on (ClaudeTransport.booted). */
446
+ const BOOT_MS = 15_000;
447
+
448
+ /**
449
+ * A Claude session's main chain, read from its transcript by the Agent SDK: user and assistant entries
450
+ * in order, with their transcript uuids. Found under `dir`'s project, else in any project (a session
451
+ * resumed or forked from another directory). Empty when the session has no transcript yet.
452
+ */
453
+ export async function claudeChain(sessionId: string, dir?: string): Promise<Array<{ uuid: string; type: 'user' | 'assistant'; toolResult?: boolean }>> {
454
+ const { getSessionMessages } = await claudeSdk();
455
+ let messages: any[] = dir ? await getSessionMessages(sessionId, { dir }) : [];
456
+ if (!messages.length) messages = await getSessionMessages(sessionId);
457
+ return messages.filter(message => (message.type === 'user' || message.type === 'assistant') && typeof message.uuid === 'string').map(message => {
458
+ const content = message.message?.content;
459
+ const toolResult = message.type === 'user' && Array.isArray(content) && content.length > 0 && content.every((block: any) => block?.type === 'tool_result');
460
+ return { uuid: message.uuid, type: message.type, ...(toolResult ? { toolResult: true } : {}) };
461
+ });
462
+ }
463
+
464
+ /** Maps Claude Agent SDK streaming sessions to the normalized runtime protocol. */
465
+ export class ClaudeTransport {
466
+ private listeners = new Set<Listener>();
467
+ private failures = new Set<(error: Error) => void>();
468
+ private requestHandler?: RequestHandler;
469
+ /** Whether the workspace had a .claude directory before a sandboxed session started. */
470
+ private claudeDirectory?: boolean;
471
+ private input = new InputQueue();
472
+ private query?: ClaudeQuery;
473
+ private pump?: Promise<void>;
474
+ private config?: NativeConfig;
475
+ private threadId = '';
476
+ private activeTurn?: string;
477
+ private closed = false;
478
+ private assistantText = new Map<string, { blocks: Map<number, { text: string; final: boolean }>; seen: Set<string> }>();
479
+ private streamingMessage?: string;
480
+ private toolCalls = new Map<string, { name: string; command: string; input: unknown }>();
481
+ /** The last rate limit Claude reported, and whether the running turn hit one. */
482
+ private rateLimit?: { status: string; resetsAt?: number; overageStatus?: string; rateLimitType?: string; utilization?: number };
483
+ private limitedTurn = false;
484
+ /** The model's context window and the fill at which Claude compacts it, as Claude reports them (ALPD §57). */
485
+ private contextWindow?: number;
486
+ private compactAt?: number;
487
+ /** The compaction running now, from its start to its boundary. */
488
+ private compaction?: string;
489
+ /** The plugin directory that loads the agent's skills, removed on close. */
490
+ private skillDirectory?: string;
491
+ /** Whether a turn ran in this process; before one, an error result is a boot refusal. */
492
+ private turnsStarted = false;
493
+ /** Rejects when the process fails, for a resume that waits for Claude to start. */
494
+ private bootFailure?: Promise<never>;
495
+ private rejectBoot?: (error: Error) => void;
496
+ private bootError?: Error;
497
+
498
+ constructor(
499
+ private readonly command: string,
500
+ private readonly cwd: string,
501
+ private readonly env: NodeJS.ProcessEnv,
502
+ ) {
503
+ if (!path.isAbsolute(command)) {
504
+ const names = process.platform === 'win32' && !path.extname(command) ? [command, `${command}.exe`] : [command];
505
+ const candidates = (env.PATH ?? '').split(path.delimiter).filter(Boolean).flatMap(directory => names.map(name => path.resolve(directory, name)));
506
+ const executable = candidates.find(candidate => {
507
+ try { accessSync(candidate, constants.X_OK); return statSync(candidate).isFile(); } catch { return false; }
508
+ });
509
+ if (!executable) throw new Error('Claude executable not found on PATH; set ALP_CLAUDE_BIN to an absolute native executable');
510
+ this.command = realpathSync(executable);
511
+ }
512
+ if (/\.(cmd|bat|ps1)$/i.test(this.command)) {
513
+ throw new Error('Claude executable must be a native binary, not a shell launcher');
514
+ }
515
+ }
516
+
517
+ async orchestrationContext() {
518
+ const [catalog, usage] = await Promise.all([
519
+ optionalRead(async () => this.query ? this.query.supportedModels() : undefined),
520
+ // Without a session yet, a short-lived Claude process answers (ALPD §58); it takes a second or two.
521
+ this.query
522
+ ? optionalRead(async () => this.query!.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true }))
523
+ : optionalRead(() => this.probeUsage(), 15_000),
524
+ ]);
525
+ return { runtime: 'claude', observedAt: new Date().toISOString(), catalogAvailable: Array.isArray(catalog),
526
+ models: (catalog ?? []).map(model => ({ id: `claude:${model.value}`, label: model.displayName,
527
+ description: model.description, thinking: model.supportedEffortLevels })), usage: claudeUsage(usage) };
528
+ }
529
+ /**
530
+ * Claude's slash commands, skills included, for the composer (t-f628); none before the session starts.
531
+ * Not the ones whose work ALP does itself (t-efa3): /clear (/reset, /new) moves Claude to a new conversation ALP does not
532
+ * follow, and /compact and /rewind skip ALP's checkpoint and its rewind of the timeline. A command of the user's
533
+ * named new or reset is offered (t-5ac5, customClearAliases); one named clear, compact or rewind never runs, Claude's wins.
534
+ */
535
+ async commands() {
536
+ const listed = await this.listCommands();
537
+ const custom = customClearAliases(listed);
538
+ return (Array.isArray(listed) ? listed : []).filter(command => typeof command?.name === 'string' && command.name
539
+ && (!ALP_HANDLED_COMMANDS.has(command.name) || (command.builtin !== true && custom.has(command.name)))).map(command => ({
540
+ name: command.name, description: typeof command.description === 'string' ? command.description : '',
541
+ ...(command.argumentHint ? { argumentHint: command.argumentHint } : {}),
542
+ kind: command.name.startsWith(`${SKILL_PLUGIN}:`) ? 'skill' as const : 'command' as const,
543
+ }));
544
+ }
545
+ /** The aliases of /clear that run a command of the user's, as the last listing said (t-5ac5); none before one. */
546
+ customCommands(): ReadonlySet<string> { return this.customAliases; }
547
+ private customAliases: ReadonlySet<string> = new Set();
548
+ private async listCommands() {
549
+ const listed = this.query ? await optionalRead(async () => this.query!.supportedCommands(), 10_000) : undefined;
550
+ if (Array.isArray(listed)) this.customAliases = customClearAliases(listed);
551
+ return listed;
552
+ }
553
+ async initialize() {}
554
+
555
+ /** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
556
+ async probeModels(signal?: AbortSignal) {
557
+ const { query } = await claudeSdk();
558
+ if (signal?.aborted) throw new Error('aborted');
559
+ const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command, ...scriptExecutable(this.command) } }) as ClaudeQuery;
560
+ // A probe that outlives its bound is closed, so a hanging Claude process never stays behind.
561
+ const stop = () => probe.close();
562
+ signal?.addEventListener('abort', stop);
563
+ try {
564
+ const models = await probe.supportedModels();
565
+ return models.map(model => ({ id: model.value, label: model.displayName, description: model.description, efforts: model.supportedEffortLevels ?? undefined }));
566
+ } finally {
567
+ signal?.removeEventListener('abort', stop);
568
+ probe.close();
569
+ }
570
+ }
571
+
572
+ /** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
573
+ private async probeUsage() {
574
+ if (this.closed) return undefined;
575
+ const { query } = await claudeSdk();
576
+ const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command, ...scriptExecutable(this.command) } }) as ClaudeQuery;
577
+ try {
578
+ return await probe.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
579
+ } finally {
580
+ probe.close();
581
+ }
582
+ }
583
+
584
+ onNotification(listener: Listener) {
585
+ this.listeners.add(listener);
586
+ return () => this.listeners.delete(listener);
587
+ }
588
+
589
+ onFailure(listener: (error: Error) => void) {
590
+ this.failures.add(listener);
591
+ return () => this.failures.delete(listener);
592
+ }
593
+
594
+ onRequest(handler: RequestHandler) {
595
+ this.requestHandler = handler;
596
+ }
597
+
598
+ async request(method: string, params: any): Promise<any> {
599
+ if (this.closed) throw new Error('Runtime is closed');
600
+
601
+ if (method === 'session/configure') {
602
+ if (!this.query || !this.config) throw new Error('Claude thread is not initialized');
603
+ await this.query.setPermissionMode(claudePermissionMode(params.sandbox));
604
+ this.config.sandbox = params.sandbox;
605
+ return {};
606
+ }
607
+
608
+ if (method === 'thread/chain') return { entries: await claudeChain(params.threadId, params.cwd ?? this.cwd) };
609
+
610
+ if (method === 'thread/delete') {
611
+ const { deleteSession } = await claudeSdk();
612
+ await deleteSession(params.threadId, params.cwd ? { dir: params.cwd } : {});
613
+ return {};
614
+ }
615
+
616
+ if (method === 'thread/start' || method === 'thread/resume' || method === 'thread/fork') {
617
+ this.clearAssistantText();
618
+ const { base, requireHistory, ...config } = params as NativeConfig & { base?: { threadId: string; at?: string }; requireHistory?: boolean };
619
+ this.config = config as NativeConfig;
620
+ this.threadId =
621
+ method === 'thread/resume' ? params.threadId : randomUUID();
622
+ // A fork resumes the thread's history under a new id, leaving the thread itself unchanged.
623
+ const from = method === 'thread/start' ? undefined
624
+ : method === 'thread/resume' ? await this.resumeFrom(params.threadId, base, requireHistory)
625
+ : { resume: params.threadId, fork: true };
626
+ await this.start(from);
627
+ // A resume Claude refuses at boot (a missing session, a cut it cannot make) fails this request, not a later turn.
628
+ if (method === 'thread/resume' && (base || requireHistory)) await this.booted();
629
+ return {
630
+ thread: { id: this.threadId, turns: [] },
631
+ cwd: this.cwd,
632
+ model: params.model,
633
+ reasoningEffort: params.thinking,
634
+ };
635
+ }
636
+
637
+ if (method === 'turn/start' || method === 'turn/steer') {
638
+ if (!this.query) throw new Error('Claude thread is not initialized');
639
+ const turnId = method === 'turn/steer'
640
+ ? params.expectedTurnId
641
+ : randomUUID();
642
+ if (method === 'turn/start') {
643
+ this.clearAssistantText();
644
+ this.activeTurn = turnId;
645
+ this.turnsStarted = true;
646
+ }
647
+ this.input.push({
648
+ type: 'user',
649
+ message: {
650
+ role: 'user',
651
+ content: params.input.map(claudeContent),
652
+ },
653
+ parent_tool_use_id: null,
654
+ // A turn's prompt entry in the transcript carries the turn's id, so ALP can cut the conversation at it (§12.7).
655
+ uuid: method === 'turn/start' ? turnId : randomUUID(),
656
+ session_id: this.threadId,
657
+ });
658
+ return method === 'turn/start' ? { turn: { id: turnId } } : {};
659
+ }
660
+
661
+ // t-0e56: Claude compacts on its /compact command, a turn of its own with what the summary must keep.
662
+ if (method === 'thread/compact/start') {
663
+ if (!this.query) throw new Error('Claude thread is not initialized');
664
+ if (this.activeTurn) throw new Error('A turn is running');
665
+ const turnId = randomUUID();
666
+ this.clearAssistantText();
667
+ this.activeTurn = turnId;
668
+ this.turnsStarted = true;
669
+ this.emit('turn/started', { threadId: this.threadId, turn: { id: turnId } });
670
+ const instructions = typeof params.instructions === 'string' ? ` ${params.instructions.trim()}` : '';
671
+ this.input.push({ type: 'user', message: { role: 'user', content: `/compact${instructions}` }, parent_tool_use_id: null, uuid: turnId, session_id: this.threadId });
672
+ return {};
673
+ }
674
+
675
+ if (method === 'turn/interrupt') {
676
+ this.streamingMessage = undefined;
677
+ await this.query?.interrupt();
678
+ return {};
679
+ }
680
+
681
+ throw new Error(`Unsupported Claude runtime operation '${method}'`);
682
+ }
683
+
684
+ /**
685
+ * How a resume starts. With a base, a session whose transcript does not exist yet is made from the
686
+ * base's conversation cut at `at` (a fork or rewind, §12.7): Claude writes it, under this session's
687
+ * id, only when its first prompt runs. Otherwise, the session's own transcript.
688
+ */
689
+ private async resumeFrom(threadId: string, base?: { threadId: string; at?: string }, requireHistory?: boolean) {
690
+ const own = base || requireHistory ? await claudeChain(threadId, this.config!.cwd) : [];
691
+ if (!base || own.length) {
692
+ if (requireHistory && !own.length) throw new Error(`Claude session ${threadId} not found`);
693
+ return { resume: threadId, fork: false };
694
+ }
695
+ const source = await claudeChain(base.threadId, this.config!.cwd);
696
+ if (!source.length) throw new Error(`Claude session ${base.threadId} not found`);
697
+ if (base.at && !source.some(entry => entry.uuid === base.at)) throw new Error(`Claude session ${base.threadId} has no entry ${base.at}`);
698
+ return { resume: base.threadId, fork: true, at: base.at };
699
+ }
700
+
701
+ /**
702
+ * Waits until Claude has started: its answer to the SDK's initialize request, or the failure that
703
+ * ends it first. Past BOOT_MS ALP goes on, as any resume does, and a later refusal fails the session.
704
+ */
705
+ private async booted() {
706
+ let timer: NodeJS.Timeout | undefined;
707
+ try {
708
+ await Promise.race([
709
+ this.query!.initializationResult?.().then(() => undefined, () => undefined),
710
+ this.bootFailure,
711
+ new Promise<void>(resolve => { timer = setTimeout(resolve, BOOT_MS); }),
712
+ ]);
713
+ } finally { clearTimeout(timer); }
714
+ // A refusal can arrive with the answer itself; let the stream deliver it.
715
+ await new Promise(resolve => setImmediate(resolve));
716
+ if (this.bootError) throw this.bootError;
717
+ }
718
+
719
+ private async start(from?: { resume: string; fork: boolean; at?: string }) {
720
+ const { createSdkMcpServer, query, tool } = await claudeSdk();
721
+ const config = this.config!;
722
+ const mcpServers = this.convertMcp(config.mcpServers);
723
+
724
+ if (config.dynamicTools.length) {
725
+ const tools = config.dynamicTools.map(definition => {
726
+ const base = toolShapes[definition.name];
727
+ if (!base) throw new Error(`Unsupported ALP tool '${definition.name}'`);
728
+ // A role's definition may offer fewer actions (alp_task) and fewer fields than the full shape.
729
+ const schema = (definition as { inputSchema?: { properties?: Record<string, { enum?: string[] }> } }).inputSchema?.properties;
730
+ const actions = schema?.action?.enum;
731
+ const shape = Object.fromEntries(Object.entries(base)
732
+ .filter(([key]) => !schema || key in schema)
733
+ .map(([key, value]) => [key, key === 'action' && actions?.length ? z.enum(actions as [string, ...string[]]) : value]));
734
+ return tool(definition.name, definition.description, shape, async (args: Record<string, unknown>) => {
735
+ if (!this.requestHandler || !this.activeTurn) {
736
+ return {
737
+ content: [{ type: 'text', text: 'ALP tools are unavailable' }],
738
+ isError: true,
739
+ };
740
+ }
741
+ const callId = `claude-tool-${randomUUID()}`;
742
+ this.emit('item/started', {
743
+ threadId: this.threadId,
744
+ item: {
745
+ type: 'dynamicToolCall',
746
+ id: callId,
747
+ callId,
748
+ tool: definition.name,
749
+ arguments: args,
750
+ status: 'inProgress',
751
+ },
752
+ });
753
+ const result: any = await this.requestHandler('item/tool/call', {
754
+ threadId: this.threadId,
755
+ turnId: this.activeTurn,
756
+ callId,
757
+ namespace: null,
758
+ tool: definition.name,
759
+ arguments: args,
760
+ });
761
+ this.emit('item/completed', {
762
+ threadId: this.threadId,
763
+ item: {
764
+ type: 'dynamicToolCall',
765
+ id: callId,
766
+ callId,
767
+ tool: definition.name,
768
+ arguments: args,
769
+ status: result?.success === false ? 'failed' : 'completed',
770
+ success: result?.success !== false,
771
+ contentItems: result?.contentItems ?? [],
772
+ },
773
+ });
774
+ return {
775
+ content: (result?.contentItems ?? []).map((item: any) => ({
776
+ type: 'text' as const,
777
+ text: item.text ?? JSON.stringify(item),
778
+ })),
779
+ isError: result?.success === false,
780
+ };
781
+ });
782
+ });
783
+ mcpServers.alp = createSdkMcpServer({
784
+ name: 'alp',
785
+ version: '0.0.0',
786
+ tools,
787
+ });
788
+ }
789
+
790
+ if (config.floor) this.claudeDirectory ??= existsSync(path.join(config.cwd, '.claude'));
791
+ const rules = config.permissions || config.floor ? { allow: [], deny: [], ...config.permissions, ...(config.floor ? { floor: config.floor, floorRoot: config.cwd } : {}) } : null;
792
+ const { settings: ruleSettings, ...permissions } = claudePermissions(config.sandbox, () => config.sandbox, rules,
793
+ async request => (this.requestHandler ? await this.requestHandler('item/permission/request', request) as PermissionAnswer : { allow: false, message: 'No one can approve it' }));
794
+ const settings = { ...(config.thinking === 'ultracode' ? { ultracode: true } : {}), ...(config.context ? { autoCompactWindow: config.context } : {}), ...ruleSettings };
795
+ // The agent's skills as Claude Code's own, so Claude lists them with their descriptions and calls them with Skill.
796
+ const plugins: Array<{ type: 'local'; path: string; skipMcpDiscovery: boolean }> = [];
797
+ if (config.skills?.length) {
798
+ try {
799
+ this.skillDirectory ??= path.join(os.tmpdir(), 'alp-skills', randomUUID());
800
+ plugins.push({ type: 'local', path: skillPlugin(this.skillDirectory, config.skills), skipMcpDiscovery: true });
801
+ } catch {
802
+ // The skills stay listed in the instructions by file.
803
+ }
804
+ }
805
+ const options = {
806
+ cwd: config.cwd,
807
+ env: this.env,
808
+ model: config.model,
809
+ effort: ['none', 'off', 'ultracode'].includes(config.thinking) ? undefined : config.thinking,
810
+ thinking: ['none', 'off'].includes(config.thinking) ? { type: 'disabled' } : { type: 'adaptive' },
811
+ systemPrompt: config.developerInstructions,
812
+ ...permissions,
813
+ ...(Object.keys(settings).length ? { settings } : {}),
814
+ mcpServers,
815
+ strictMcpConfig: true,
816
+ settingSources: [],
817
+ ...(plugins.length ? { plugins } : {}),
818
+ persistSession: !config.ephemeral,
819
+ promptSuggestions: false,
820
+ includePartialMessages: true,
821
+ ...(from ? { resume: from.resume, ...(from.fork ? { forkSession: true, sessionId: this.threadId } : {}), ...(from.at ? { resumeSessionAt: from.at } : {}) } : { sessionId: this.threadId }),
822
+ // Explicit native path avoids SDK optional binaries inside Electron app.asar.
823
+ pathToClaudeCodeExecutable: this.command,
824
+ ...scriptExecutable(this.command),
825
+ };
826
+
827
+ this.bootFailure = new Promise<never>((_, reject) => { this.rejectBoot = reject; });
828
+ this.bootFailure.catch(() => {});
829
+ this.query = query({ prompt: this.input, options }) as ClaudeQuery;
830
+ this.pump = this.consume(this.query).catch((error) => this.fail(error));
831
+ void this.measureContext();
832
+ // The listing says which of /new and /reset are the user's own, before the first prompt is checked.
833
+ void this.listCommands();
834
+ }
835
+
836
+ /** Reads the window and the compaction threshold Claude resolved for this session, before any turn. */
837
+ private async measureContext() {
838
+ // The first read waits for Claude to start; a reply from usage lets ALP guess meanwhile.
839
+ const usage: any = await optionalRead(async () => this.query?.getContextUsage({ detail: 'summary' }), 60_000);
840
+ if (!usage) return;
841
+ const window = usage.rawMaxTokens ?? usage.maxTokens;
842
+ if (typeof window === 'number' && window > 0) this.contextWindow = window;
843
+ this.compactAt = usage.isAutoCompactEnabled !== false && typeof usage.autoCompactThreshold === 'number' && usage.autoCompactThreshold > 0 ? usage.autoCompactThreshold : undefined;
844
+ }
845
+
846
+ private convertMcp(values: Record<string, any>) {
847
+ const result: Record<string, any> = {};
848
+ for (const [name, value] of Object.entries(values)) {
849
+ result[name] = value.url
850
+ ? {
851
+ type: 'http',
852
+ url: value.url,
853
+ headers: value.http_headers ?? {},
854
+ }
855
+ : {
856
+ type: 'stdio',
857
+ command: value.command,
858
+ args: value.args ?? [],
859
+ env: value.env ?? {},
860
+ };
861
+ }
862
+ return result;
863
+ }
864
+
865
+ private async consume(stream: ClaudeQuery) {
866
+ for await (const message of stream) this.handle(message);
867
+ if (!this.closed) this.fail(new Error('Claude session exited'));
868
+ }
869
+
870
+ private handle(message: SDKMessage) {
871
+ if (this.closed) return;
872
+ if (message.type === 'rate_limit_event') {
873
+ this.rateLimit = message.rate_limit_info;
874
+ this.emit('account/rateLimits/updated', { claude: message.rate_limit_info });
875
+ return;
876
+ }
877
+ // Claude starts a turn by itself when a background task it ran ends (ALPD §56). Adopt it, so
878
+ // ALP's tools work in it and its end is reported like any other turn's.
879
+ const streamStart = message.type === 'stream_event' && message.event?.type === 'message_start';
880
+ if ((message.type === 'assistant' || streamStart) && !message.parent_tool_use_id && !this.activeTurn) {
881
+ this.activeTurn = randomUUID();
882
+ this.emit('turn/started', { threadId: this.threadId, turn: { id: this.activeTurn } });
883
+ }
884
+ if (message.type === 'stream_event') {
885
+ if (message.parent_tool_use_id) return;
886
+ const event = message.event;
887
+ if (event.type === 'message_start') {
888
+ this.streamingMessage = event.message.id;
889
+ } else if (event.type === 'message_stop') {
890
+ this.streamingMessage = undefined;
891
+ } else if (this.streamingMessage) {
892
+ const id = this.streamingMessage;
893
+ const state = this.assistantState(id);
894
+ let delta: string | undefined;
895
+ if (event.type === 'content_block_start' && event.content_block.type === 'text') {
896
+ state.blocks.set(event.index, { text: event.content_block.text, final: false });
897
+ delta = event.content_block.text;
898
+ } else if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
899
+ const block = state.blocks.get(event.index);
900
+ if (block && !block.final) {
901
+ block.text += event.delta.text;
902
+ delta = event.delta.text;
903
+ }
904
+ }
905
+ if (delta) this.emit('item/agentMessage/delta', { threadId: this.threadId, turnId: this.activeTurn, itemId: id, delta });
906
+ }
907
+ return;
908
+ }
909
+ if (message.type === 'assistant' && message.error === 'rate_limit') this.limitedTurn = true;
910
+ // The model Claude Code says it runs this query with (its init message), so ALP can show it took a configured one (§12.9).
911
+ if (message.type === 'system' && message.subtype === 'init' && typeof (message as any).model === 'string') this.emit('alp/nativeModel', { threadId: this.threadId, model: (message as any).model });
912
+ // A compaction, reported as Codex reports one: a contextCompaction item from start to end (ALPD §57).
913
+ if (message.type === 'system' && (message.subtype === 'status' || message.subtype === 'compact_boundary')) {
914
+ const system = message as any;
915
+ if (system.subtype === 'status' && system.status === 'compacting' && !this.compaction) {
916
+ this.compaction = randomUUID();
917
+ this.emit('item/started', { threadId: this.threadId, turnId: this.activeTurn, item: { type: 'contextCompaction', id: this.compaction } });
918
+ } else if (system.subtype === 'status' && system.compact_result === 'failed') {
919
+ this.emit('item/completed', { threadId: this.threadId, turnId: this.activeTurn, item: { type: 'contextCompaction', id: this.compaction ?? randomUUID(), status: 'failed', error: system.compact_error } });
920
+ this.compaction = undefined;
921
+ } else if (system.subtype === 'compact_boundary') {
922
+ const meta = system.compact_metadata ?? {};
923
+ this.emit('item/completed', {
924
+ threadId: this.threadId, turnId: this.activeTurn,
925
+ item: { type: 'contextCompaction', id: this.compaction ?? randomUUID(), status: 'completed', trigger: meta.trigger, preTokens: meta.pre_tokens, postTokens: meta.post_tokens },
926
+ });
927
+ this.compaction = undefined;
928
+ }
929
+ return;
930
+ }
931
+ // How full the context is, reported as Codex does: the tokens of the latest model call against the window.
932
+ // Until Claude has said what its window is, ALP does not guess one (ALPD §57).
933
+ const usage = message.type === 'assistant' && !message.parent_tool_use_id ? (message.message as any).usage : undefined;
934
+ if (usage) {
935
+ const totalTokens = (usage.input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.output_tokens ?? 0);
936
+ const last = { totalTokens, inputTokens: usage.input_tokens ?? 0, cachedInputTokens: usage.cache_read_input_tokens ?? 0, outputTokens: usage.output_tokens ?? 0 };
937
+ this.emit('thread/tokenUsage/updated', {
938
+ threadId: this.threadId, turnId: this.activeTurn,
939
+ tokenUsage: { last, total: last, modelContextWindow: this.contextWindow ?? null, ...(this.compactAt ? { autoCompactTokens: this.compactAt } : {}) },
940
+ });
941
+ }
942
+ if (message.type === 'result') {
943
+ // The session's cost so far, as Claude counts it; a viewer shows it with the context meter.
944
+ const cost = (message as any).total_cost_usd;
945
+ if (typeof cost === 'number' && Number.isFinite(cost) && cost >= 0) this.emit('thread/tokenUsage/updated', { threadId: this.threadId, turnId: this.activeTurn, tokenUsage: { totalCostUsd: cost } });
946
+ const windows = Object.values((message as any).modelUsage ?? {}).map((entry: any) => entry?.contextWindow).filter((value): value is number => typeof value === 'number' && value > 0);
947
+ // Only when it was not measured: the measured window may be the setting's, smaller than the model's.
948
+ if (windows.length && !this.compactAt) this.contextWindow = Math.max(...windows);
949
+ }
950
+ if (message.type === 'assistant' && !message.parent_tool_use_id) {
951
+ const id = message.message.id;
952
+ const state = this.assistantState(id);
953
+ if (message.uuid && state.seen.has(message.uuid)) return;
954
+ if (message.uuid) state.seen.add(message.uuid);
955
+ for (const block of message.message.content as any[]) {
956
+ if (block.type === 'text') {
957
+ // SDK 0.3.292 delivers one authoritative assistant event per completed
958
+ // block, sharing message.id. Replace that block's draft, never append
959
+ // the final text to its streamed draft or replace earlier final blocks.
960
+ const pending = [...state.blocks.entries()].sort(([a], [b]) => a - b).find(([, value]) => !value.final);
961
+ const index = pending?.[0] ?? Math.max(-1, ...state.blocks.keys()) + 1;
962
+ state.blocks.set(index, { text: block.text, final: true });
963
+ this.emit('item/completed', {
964
+ threadId: this.threadId,
965
+ item: { type: 'agentMessage', id, text: [...state.blocks.entries()].sort(([a], [b]) => a - b).map(([, block]) => block.text).join('') },
966
+ });
967
+ } else if (block.type === 'tool_use') {
968
+ const command = block.name === 'Bash'
969
+ ? String(block.input?.command ?? '')
970
+ : `${block.name} ${JSON.stringify(block.input ?? {})}`;
971
+ this.toolCalls.set(block.id, { name: block.name, command, input: block.input });
972
+ // The command stays what skill use, copy escapes and the journal read; the typed detail rides along.
973
+ const detail = claudeToolDetail(block.name, block.input);
974
+ this.emit('item/started', {
975
+ threadId: this.threadId,
976
+ item: {
977
+ type: 'commandExecution',
978
+ id: block.id,
979
+ command,
980
+ cwd: this.cwd,
981
+ status: 'inProgress',
982
+ aggregatedOutput: '',
983
+ ...(detail ? { tool: block.name, detail } : {}),
984
+ },
985
+ });
986
+ }
987
+ }
988
+ return;
989
+ }
990
+
991
+ if (message.type === 'user') {
992
+ const content = Array.isArray(message.message.content)
993
+ ? message.message.content as any[]
994
+ : [];
995
+ // The SDK's structured output belongs to the message's one tool result.
996
+ const results = content.filter(block => block.type === 'tool_result');
997
+ const structured = results.length === 1 ? (message as any).tool_use_result : undefined;
998
+ for (const block of results) {
999
+ const call = this.toolCalls.get(block.tool_use_id);
1000
+ if (!call) continue;
1001
+ const output = typeof block.content === 'string'
1002
+ ? block.content
1003
+ : JSON.stringify(block.content ?? '');
1004
+ const text = resultText(block.content);
1005
+ const detail = claudeToolDetail(call.name, call.input, { text, structured, error: Boolean(block.is_error) });
1006
+ this.emit('item/completed', {
1007
+ threadId: this.threadId,
1008
+ item: {
1009
+ type: 'commandExecution',
1010
+ id: block.tool_use_id,
1011
+ command: call.command,
1012
+ cwd: this.cwd,
1013
+ status: block.is_error ? 'failed' : 'completed',
1014
+ exitCode: block.is_error ? 1 : 0,
1015
+ aggregatedOutput: output,
1016
+ ...(detail ? { tool: call.name, detail, ...(block.is_error ? { error: text } : {}) } : {}),
1017
+ },
1018
+ });
1019
+ this.toolCalls.delete(block.tool_use_id);
1020
+ }
1021
+ return;
1022
+ }
1023
+
1024
+ // Before any turn, an error result is Claude refusing to start the session (a resume it rejected).
1025
+ // The SDK then ends the stream with this error, which fails the transport as before.
1026
+ if (message.type === 'result' && message.is_error && !this.activeTurn && !this.turnsStarted) {
1027
+ this.refuseBoot(new Error(message.errors?.length ? message.errors.join('; ') : 'Claude refused to start the session'));
1028
+ return;
1029
+ }
1030
+ if (message.type === 'result') this.clearAssistantText();
1031
+ if (message.type === 'result' && this.activeTurn) {
1032
+ const turnId = this.activeTurn;
1033
+ this.activeTurn = undefined;
1034
+ // A usage limit ends the turn with an error message or a failed result; report it as Codex does.
1035
+ const limited = this.limitedTurn || (message.is_error && claudeLimited(this.rateLimit));
1036
+ this.limitedTurn = false;
1037
+ const failed = message.is_error || limited;
1038
+ this.emit('turn/completed', {
1039
+ threadId: this.threadId,
1040
+ turn: {
1041
+ id: turnId,
1042
+ status: failed ? 'failed' : 'completed',
1043
+ ...(failed
1044
+ ? { error: {
1045
+ message: limited ? `Claude usage limit reached${this.rateLimit?.resetsAt ? `; resets ${new Date(this.rateLimit.resetsAt * 1000).toISOString()}` : ''}` : 'errors' in message && message.errors?.length ? message.errors.join('; ') : 'Claude turn failed',
1046
+ ...(limited ? { codexErrorInfo: 'usageLimitExceeded', ...(this.rateLimit?.resetsAt ? { resetsAt: this.rateLimit.resetsAt } : {}) } : {}),
1047
+ } }
1048
+ : {}),
1049
+ },
1050
+ });
1051
+ }
1052
+ }
1053
+
1054
+ private refuseBoot(error: Error) {
1055
+ this.bootError ??= error;
1056
+ this.rejectBoot?.(error);
1057
+ }
1058
+
1059
+ private emit(method: string, params: any) {
1060
+ for (const listener of this.listeners) listener(method, params);
1061
+ }
1062
+
1063
+ private assistantState(id: string) {
1064
+ let state = this.assistantText.get(id);
1065
+ if (!state) this.assistantText.set(id, state = { blocks: new Map(), seen: new Set() });
1066
+ return state;
1067
+ }
1068
+
1069
+ private clearAssistantText() {
1070
+ this.streamingMessage = undefined;
1071
+ this.assistantText.clear();
1072
+ }
1073
+
1074
+ private fail(value: unknown) {
1075
+ if (this.closed) return;
1076
+ this.clearAssistantText();
1077
+ const error = value instanceof Error ? value : new Error(String(value));
1078
+ this.refuseBoot(error);
1079
+ for (const listener of this.failures) listener(error);
1080
+ }
1081
+
1082
+ async close() {
1083
+ if (this.closed) return;
1084
+ this.closed = true;
1085
+ this.clearAssistantText();
1086
+ this.input.close();
1087
+ this.query?.close();
1088
+ await this.pump?.catch(() => {});
1089
+ this.listeners.clear();
1090
+ this.failures.clear();
1091
+ if (this.skillDirectory) rmSync(this.skillDirectory, { recursive: true, force: true });
1092
+ // Claude's sandbox leaves an empty .claude/.cc-writes in the workspace; remove what it created.
1093
+ if (this.claudeDirectory === false && this.config) {
1094
+ for (const directory of ['.claude/.cc-writes', '.claude']) { try { rmdirSync(path.join(this.config.cwd, directory)); } catch {} }
1095
+ }
1096
+ }
1097
+ }