@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
@@ -5,27 +5,58 @@ import path from 'node:path';
5
5
  import { optionalRead, claudeUsage } from './runtime-context.js';
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { z } from 'zod';
8
- import { PIN_KINDS } from './board.js';
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';
9
11
  import { claudeToolDetail, resultText } from './tool-detail.js';
10
12
  import { CLOSE_REASONS, GATE_KINDS, TASK_STATUSES, TASK_TYPES } from '@anhlp/alp-core/tasks';
11
13
  import { commandDecision } from '@anhlp/alp-core/permissions';
14
+ import { isScript, nativeDaemon, nodeExecutable } from '@anhlp/alp-core/packaged';
12
15
 
13
16
  // Keep the Claude SDK behind the runtime boundary. Paseo inspects static
14
17
  // imports while compiling plugin entrypoints, including their declaration
15
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.
16
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() } : {};
17
29
 
18
30
  type SDKUserMessage = any;
19
31
  type SDKMessage = any;
20
32
  type ClaudeQuery = AsyncGenerator<SDKMessage, void> & {
21
33
  supportedModels(): Promise<Array<{ value: string; displayName: string; description: string; supportedEffortLevels?: string[] }>>;
34
+ supportedCommands(): Promise<Array<{ name: string; description: string; argumentHint?: string; builtin?: boolean }>>;
22
35
  usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(options: { skipBehaviors: boolean }): Promise<any>;
23
36
  getContextUsage(options: { detail: 'summary' | 'full' }): Promise<any>;
24
37
  interrupt(): Promise<unknown>;
25
38
  setPermissionMode(mode: 'default' | 'acceptEdits' | 'bypassPermissions'): Promise<void>;
26
39
  close(): void;
40
+ initializationResult?(): Promise<unknown>;
27
41
  };
28
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
+
29
60
  // Zod mirrors of the provider's dynamic tool schemas; the provider validates again.
30
61
  const handoffList = z.array(z.string().min(1)).max(100).optional();
31
62
  const taskIds = z.array(z.string().min(1)).max(50).optional();
@@ -61,6 +92,15 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
61
92
  scope: z.enum(['project', 'user']),
62
93
  lesson: z.string().min(1).max(600),
63
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
+ },
64
104
  alp_skill: {
65
105
  name: z.string().min(1),
66
106
  description: z.string().min(1).max(300),
@@ -68,16 +108,31 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
68
108
  roles: z.array(z.string().min(1)).min(1).max(10),
69
109
  lessons: z.array(z.string().min(1).max(600)).max(50).optional(),
70
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(),
71
117
  },
72
118
  alp_issue: {
73
119
  action: z.enum(['search', 'create', 'comment']),
74
120
  target: z.enum(['project', 'alp']),
75
121
  query: z.string().min(1).max(200).optional(),
122
+ requestId: z.string().min(1).max(100).optional(),
76
123
  title: z.string().min(1).max(200).optional(),
77
124
  body: z.string().min(1).max(20_000).optional(),
78
125
  issue: z.number().int().positive().optional(),
79
126
  labels: z.array(z.string().min(1).max(50)).max(10).optional(),
80
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
+ },
81
136
  alp_task: {
82
137
  action: z.enum(['create', 'update', 'link', 'start', 'close', 'reopen', 'gate', 'clear', 'pour', 'formulas', 'show', 'list', 'ready']),
83
138
  id: z.string().min(1).optional(),
@@ -96,9 +151,10 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
96
151
  kind: z.enum(GATE_KINDS as [string, ...string[]]).optional(),
97
152
  until: z.string().min(1).optional(),
98
153
  ref: z.string().min(1).optional(),
154
+ options: z.array(z.string().min(1).max(200)).max(10).optional(),
99
155
  gate: z.string().min(1).optional(),
100
156
  formula: z.string().min(1).optional(),
101
- vars: z.record(z.string(), z.string()).optional(),
157
+ vars: bounded(z.record(z.string().regex(VAR_NAME), z.string().max(POUR_VARS.string)), POUR_VARS).optional(),
102
158
  summary: z.string().min(1).max(2000).optional(),
103
159
  unverified: z.string().min(1).max(2000).optional(),
104
160
  note: z.string().min(1).max(2000).optional(),
@@ -109,17 +165,22 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
109
165
  alp_discard: {
110
166
  assignmentId: z.string().min(1),
111
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
+ },
112
173
  alp_cancel: {
113
174
  assignmentId: z.string().min(1),
114
175
  reason: z.string().optional(),
115
176
  },
116
177
  alp_pin: {
117
178
  kind: z.enum(PIN_KINDS),
118
- body: z.string().min(1),
119
- paths: z.array(z.string().min(1)).optional(),
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(),
120
181
  },
121
182
  alp_board: {
122
- kinds: z.array(z.enum(PIN_KINDS)).optional(),
183
+ kinds: bounded(z.array(z.enum(PIN_KINDS)).max(PIN_KINDS.length), BOARD_KINDS_INPUT).optional(),
123
184
  limit: z.number().int().positive().optional(),
124
185
  },
125
186
  alp_unpin: {
@@ -186,6 +247,47 @@ type NativeConfig = {
186
247
 
187
248
  /** The plugin name ALP's skills are loaded under, so Claude Code calls them alp:<name>. */
188
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
+ }
189
291
 
190
292
  /**
191
293
  * A Claude Code plugin in `directory` holding the given skills, linked to their own
@@ -292,8 +394,18 @@ export function claudePermissions(sandbox: string, currentSandbox?: () => string
292
394
  // Ask rules make Claude consult canUseTool in every mode, which asks the user.
293
395
  ...(rules?.ask?.length ? { settings: { permissions: { ask: rules.ask } } } : {}),
294
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.
295
400
  // A command leaves it only with dangerouslyDisableSandbox, which Claude allows itself for allow rules and asks canUseTool otherwise.
296
- ...(rules?.floor ? { sandbox: { enabled: true, autoAllowBashIfSandboxed: false, allowUnsandboxedCommands: true, ...(rules.floor === 'read-only' && rules.floorRoot ? { filesystem: { denyWrite: [rules.floorRoot] } } : {}) } } : {}),
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
+ } : {}),
297
409
  canUseTool: async (name: string, input: Record<string, unknown>, context?: { decisionReasonType?: string; suggestions?: unknown }) => {
298
410
  const mode = currentSandbox ? currentSandbox() : sandbox;
299
411
  const leaving = Boolean(rules?.floor) && name === 'Bash' && input.dangerouslyDisableSandbox === true;
@@ -330,6 +442,25 @@ export function claudePermissions(sandbox: string, currentSandbox?: () => string
330
442
  export const claudeLimited = (info?: { status: string; overageStatus?: string }) =>
331
443
  info?.status === 'rejected' && info.overageStatus !== 'allowed' && info.overageStatus !== 'allowed_warning';
332
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
+
333
464
  /** Maps Claude Agent SDK streaming sessions to the normalized runtime protocol. */
334
465
  export class ClaudeTransport {
335
466
  private listeners = new Set<Listener>();
@@ -344,7 +475,8 @@ export class ClaudeTransport {
344
475
  private threadId = '';
345
476
  private activeTurn?: string;
346
477
  private closed = false;
347
- private assistantText = new Map<string, string>();
478
+ private assistantText = new Map<string, { blocks: Map<number, { text: string; final: boolean }>; seen: Set<string> }>();
479
+ private streamingMessage?: string;
348
480
  private toolCalls = new Map<string, { name: string; command: string; input: unknown }>();
349
481
  /** The last rate limit Claude reported, and whether the running turn hit one. */
350
482
  private rateLimit?: { status: string; resetsAt?: number; overageStatus?: string; rateLimitType?: string; utilization?: number };
@@ -356,6 +488,12 @@ export class ClaudeTransport {
356
488
  private compaction?: string;
357
489
  /** The plugin directory that loads the agent's skills, removed on close. */
358
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;
359
497
 
360
498
  constructor(
361
499
  private readonly command: string,
@@ -388,13 +526,54 @@ export class ClaudeTransport {
388
526
  models: (catalog ?? []).map(model => ({ id: `claude:${model.value}`, label: model.displayName,
389
527
  description: model.description, thinking: model.supportedEffortLevels })), usage: claudeUsage(usage) };
390
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
+ }
391
553
  async initialize() {}
392
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
+
393
572
  /** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
394
573
  private async probeUsage() {
395
574
  if (this.closed) return undefined;
396
- const { query } = await import(CLAUDE_SDK);
397
- const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } }) as ClaudeQuery;
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;
398
577
  try {
399
578
  return await probe.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
400
579
  } finally {
@@ -426,18 +605,27 @@ export class ClaudeTransport {
426
605
  return {};
427
606
  }
428
607
 
608
+ if (method === 'thread/chain') return { entries: await claudeChain(params.threadId, params.cwd ?? this.cwd) };
609
+
429
610
  if (method === 'thread/delete') {
430
- const { deleteSession } = await import(CLAUDE_SDK);
611
+ const { deleteSession } = await claudeSdk();
431
612
  await deleteSession(params.threadId, params.cwd ? { dir: params.cwd } : {});
432
613
  return {};
433
614
  }
434
615
 
435
616
  if (method === 'thread/start' || method === 'thread/resume' || method === 'thread/fork') {
436
- this.config = params as NativeConfig;
617
+ this.clearAssistantText();
618
+ const { base, requireHistory, ...config } = params as NativeConfig & { base?: { threadId: string; at?: string }; requireHistory?: boolean };
619
+ this.config = config as NativeConfig;
437
620
  this.threadId =
438
621
  method === 'thread/resume' ? params.threadId : randomUUID();
439
622
  // A fork resumes the thread's history under a new id, leaving the thread itself unchanged.
440
- await this.start(method === 'thread/start' ? undefined : { resume: params.threadId, fork: method === 'thread/fork' });
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();
441
629
  return {
442
630
  thread: { id: this.threadId, turns: [] },
443
631
  cwd: this.cwd,
@@ -451,7 +639,11 @@ export class ClaudeTransport {
451
639
  const turnId = method === 'turn/steer'
452
640
  ? params.expectedTurnId
453
641
  : randomUUID();
454
- if (method === 'turn/start') this.activeTurn = turnId;
642
+ if (method === 'turn/start') {
643
+ this.clearAssistantText();
644
+ this.activeTurn = turnId;
645
+ this.turnsStarted = true;
646
+ }
455
647
  this.input.push({
456
648
  type: 'user',
457
649
  message: {
@@ -459,13 +651,29 @@ export class ClaudeTransport {
459
651
  content: params.input.map(claudeContent),
460
652
  },
461
653
  parent_tool_use_id: null,
462
- uuid: randomUUID(),
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(),
463
656
  session_id: this.threadId,
464
657
  });
465
658
  return method === 'turn/start' ? { turn: { id: turnId } } : {};
466
659
  }
467
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
+
468
675
  if (method === 'turn/interrupt') {
676
+ this.streamingMessage = undefined;
469
677
  await this.query?.interrupt();
470
678
  return {};
471
679
  }
@@ -473,8 +681,43 @@ export class ClaudeTransport {
473
681
  throw new Error(`Unsupported Claude runtime operation '${method}'`);
474
682
  }
475
683
 
476
- private async start(from?: { resume: string; fork: boolean }) {
477
- const { createSdkMcpServer, query, tool } = await import(CLAUDE_SDK);
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();
478
721
  const config = this.config!;
479
722
  const mcpServers = this.convertMcp(config.mcpServers);
480
723
 
@@ -574,15 +817,20 @@ export class ClaudeTransport {
574
817
  ...(plugins.length ? { plugins } : {}),
575
818
  persistSession: !config.ephemeral,
576
819
  promptSuggestions: false,
577
- includePartialMessages: false,
578
- ...(from ? { resume: from.resume, ...(from.fork ? { forkSession: true, sessionId: this.threadId } : {}) } : { sessionId: this.threadId }),
820
+ includePartialMessages: true,
821
+ ...(from ? { resume: from.resume, ...(from.fork ? { forkSession: true, sessionId: this.threadId } : {}), ...(from.at ? { resumeSessionAt: from.at } : {}) } : { sessionId: this.threadId }),
579
822
  // Explicit native path avoids SDK optional binaries inside Electron app.asar.
580
823
  pathToClaudeCodeExecutable: this.command,
824
+ ...scriptExecutable(this.command),
581
825
  };
582
826
 
827
+ this.bootFailure = new Promise<never>((_, reject) => { this.rejectBoot = reject; });
828
+ this.bootFailure.catch(() => {});
583
829
  this.query = query({ prompt: this.input, options }) as ClaudeQuery;
584
830
  this.pump = this.consume(this.query).catch((error) => this.fail(error));
585
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();
586
834
  }
587
835
 
588
836
  /** Reads the window and the compaction threshold Claude resolved for this session, before any turn. */
@@ -620,6 +868,7 @@ export class ClaudeTransport {
620
868
  }
621
869
 
622
870
  private handle(message: SDKMessage) {
871
+ if (this.closed) return;
623
872
  if (message.type === 'rate_limit_event') {
624
873
  this.rateLimit = message.rate_limit_info;
625
874
  this.emit('account/rateLimits/updated', { claude: message.rate_limit_info });
@@ -627,11 +876,39 @@ export class ClaudeTransport {
627
876
  }
628
877
  // Claude starts a turn by itself when a background task it ran ends (ALPD §56). Adopt it, so
629
878
  // ALP's tools work in it and its end is reported like any other turn's.
630
- if (message.type === 'assistant' && !message.parent_tool_use_id && !this.activeTurn && !this.closed) {
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) {
631
881
  this.activeTurn = randomUUID();
632
882
  this.emit('turn/started', { threadId: this.threadId, turn: { id: this.activeTurn } });
633
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
+ }
634
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 });
635
912
  // A compaction, reported as Codex reports one: a contextCompaction item from start to end (ALPD §57).
636
913
  if (message.type === 'system' && (message.subtype === 'status' || message.subtype === 'compact_boundary')) {
637
914
  const system = message as any;
@@ -671,14 +948,21 @@ export class ClaudeTransport {
671
948
  if (windows.length && !this.compactAt) this.contextWindow = Math.max(...windows);
672
949
  }
673
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);
674
955
  for (const block of message.message.content as any[]) {
675
956
  if (block.type === 'text') {
676
- const id = message.message.id;
677
- const text = (this.assistantText.get(id) ?? '') + block.text;
678
- this.assistantText.set(id, 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 });
679
963
  this.emit('item/completed', {
680
964
  threadId: this.threadId,
681
- item: { type: 'agentMessage', id, text },
965
+ item: { type: 'agentMessage', id, text: [...state.blocks.entries()].sort(([a], [b]) => a - b).map(([, block]) => block.text).join('') },
682
966
  });
683
967
  } else if (block.type === 'tool_use') {
684
968
  const command = block.name === 'Bash'
@@ -737,6 +1021,13 @@ export class ClaudeTransport {
737
1021
  return;
738
1022
  }
739
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();
740
1031
  if (message.type === 'result' && this.activeTurn) {
741
1032
  const turnId = this.activeTurn;
742
1033
  this.activeTurn = undefined;
@@ -760,19 +1051,38 @@ export class ClaudeTransport {
760
1051
  }
761
1052
  }
762
1053
 
1054
+ private refuseBoot(error: Error) {
1055
+ this.bootError ??= error;
1056
+ this.rejectBoot?.(error);
1057
+ }
1058
+
763
1059
  private emit(method: string, params: any) {
764
1060
  for (const listener of this.listeners) listener(method, params);
765
1061
  }
766
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
+
767
1074
  private fail(value: unknown) {
768
1075
  if (this.closed) return;
1076
+ this.clearAssistantText();
769
1077
  const error = value instanceof Error ? value : new Error(String(value));
1078
+ this.refuseBoot(error);
770
1079
  for (const listener of this.failures) listener(error);
771
1080
  }
772
1081
 
773
1082
  async close() {
774
1083
  if (this.closed) return;
775
1084
  this.closed = true;
1085
+ this.clearAssistantText();
776
1086
  this.input.close();
777
1087
  this.query?.close();
778
1088
  await this.pump?.catch(() => {});
package/src/compact.ts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Main's compaction (t-0e56): at a turn boundary, once main's context fills to the
3
+ * threshold (or the user asks), ALP has main write a checkpoint by skill `compact`,
4
+ * then compacts with the runtime's own mechanism (Claude's /compact, Codex's
5
+ * thread/compact/start), or else starts a fresh conversation seeded with the checkpoint.
6
+ */
7
+
8
+ export interface CompactSettings { auto: boolean; threshold: number }
9
+
10
+ export const COMPACT_DEFAULTS: CompactSettings = Object.freeze({ auto: true, threshold: 0.7 });
11
+
12
+ /**
13
+ * settings.json `compact`: { auto?: boolean, threshold?: number in (0, 1) }; anything else keeps the default.
14
+ * The threshold is a share of the window main works in: the agent's autocompact or context setting when
15
+ * set, else the model's context window, as the context advisory measures it.
16
+ */
17
+ export function compactSettings(raw: unknown): CompactSettings {
18
+ const value = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw as Record<string, unknown> : {};
19
+ const auto = typeof value.auto === 'boolean' ? value.auto : COMPACT_DEFAULTS.auto;
20
+ const threshold = typeof value.threshold === 'number' && Number.isFinite(value.threshold) && value.threshold > 0 && value.threshold < 1 ? value.threshold : COMPACT_DEFAULTS.threshold;
21
+ return { auto, threshold };
22
+ }
23
+
24
+ /** How full the context is, 0..1, from a runtime's token usage; undefined when the window is unknown. */
25
+ export function contextFill(usage: any): number | undefined {
26
+ const used = usage?.last?.totalTokens;
27
+ const window = usage?.modelContextWindow;
28
+ if (typeof used !== 'number' || typeof window !== 'number' || window <= 0) return undefined;
29
+ return used / window;
30
+ }
31
+
32
+ /** Whether an idle root should compact now. */
33
+ export function compactDue(settings: CompactSettings, fill: number | undefined, requested: boolean): 'auto' | 'manual' | undefined {
34
+ if (requested) return 'manual';
35
+ if (settings.auto && typeof fill === 'number' && fill >= settings.threshold) return 'auto';
36
+ return undefined;
37
+ }
38
+
39
+ /** Runtimes that compact a conversation in place. */
40
+ export const NATIVE_COMPACT = ['claude', 'codex'];
41
+
42
+ export const CHECKPOINT_MARK = 'ALP compact checkpoint';
43
+
44
+ export function checkpointPrompt(trigger: 'auto' | 'manual', fill?: number) {
45
+ const why = trigger === 'manual' ? 'The user asked to compact your context.' : `Your context is about ${Math.round((fill ?? 0) * 100)}% full.`;
46
+ return `${CHECKPOINT_MARK}: ${why} ALP compacts it after this turn. Write a checkpoint now following skill compact (read its SKILL.md): check the facts with alp_task, alp_board and gh where it applies, then reply with the checkpoint alone, in its sections: skip the skill's notice to the user, ALP posts it. Do not start new work, delegate, wait or ask in this turn.`;
47
+ }
48
+
49
+ /** What the runtime's native compaction is told to keep. */
50
+ export function compactInstructions(checkpoint: string) {
51
+ return `Keep this checkpoint verbatim in the summary; it is the state of the work:\n${checkpoint}`;
52
+ }
53
+
54
+ /** The first prompt of a fresh conversation that replaces a full one. */
55
+ export function seedPrompt(checkpoint: string, lastUser?: string) {
56
+ return [
57
+ 'Your context was compacted: ALP started this conversation fresh. Your instructions are unchanged. This is the checkpoint you wrote before, by skill compact:',
58
+ checkpoint,
59
+ ...(lastUser ? [`The user's last message before the compaction, verbatim:\n${lastUser}`] : []),
60
+ 'Read alp_task and alp_board again (and gh for PR/CI) before reporting status, then carry on. If nothing waits for you, end the turn.',
61
+ ].join('\n\n');
62
+ }