@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
@@ -6,11 +6,21 @@ import path from "node:path";
6
6
  import { optionalRead, claudeUsage } from "./runtime-context.js";
7
7
  import { randomUUID } from "node:crypto";
8
8
  import { z } from "zod";
9
- import { PIN_KINDS } from "./board.js";
9
+ import { BOARD_KINDS_INPUT, PIN_BODY_CHARS, PIN_KINDS, PIN_PATH_CHARS, PIN_PATHS, PIN_PATHS_INPUT } from "./board.js";
10
+ import { RESULT_OUTCOMES } from "./assignment-results.js";
11
+ import { inputLimitError, POUR_VARS, VAR_NAME } from "./input-limits.js";
10
12
  import { claudeToolDetail, resultText } from "./tool-detail.js";
11
13
  import { CLOSE_REASONS, GATE_KINDS, TASK_STATUSES, TASK_TYPES } from "@anhlp/alp-core/tasks";
12
14
  import { commandDecision } from "@anhlp/alp-core/permissions";
15
+ import { isScript, nativeDaemon, nodeExecutable } from "@anhlp/alp-core/packaged";
13
16
  var CLAUDE_SDK = ["@anthropic-ai", "claude-agent-sdk"].join("/");
17
+ var claudeSdk = () => nativeDaemon()?.modules.claudeAgentSdk?.() ?? import(CLAUDE_SDK);
18
+ var scriptExecutable = (command) => nativeDaemon() && (isScript(command) || /\.(ts|tsx|jsx)$/i.test(command)) ? { executable: nodeExecutable() } : {};
19
+ var bounded = (schema, limits) => z.preprocess((value, ctx) => {
20
+ const error = inputLimitError(value, limits);
21
+ if (error) ctx.addIssue({ code: "custom", message: error });
22
+ return value;
23
+ }, schema);
14
24
  var handoffList = z.array(z.string().min(1)).max(100).optional();
15
25
  var taskIds = z.array(z.string().min(1)).max(50).optional();
16
26
  var taskLinks = z.object({ blockedBy: taskIds, related: taskIds, parent: z.string().min(1).optional() }).strict().optional();
@@ -45,23 +55,47 @@ var toolShapes = {
45
55
  scope: z.enum(["project", "user"]),
46
56
  lesson: z.string().min(1).max(600)
47
57
  },
58
+ alp_lesson_curate: {
59
+ changes: z.array(z.object({
60
+ scope: z.enum(["project", "user"]),
61
+ remove: z.array(z.string().min(1).max(600)).min(1).max(50),
62
+ add: z.string().min(1).max(600).optional(),
63
+ reason: z.string().max(300).optional()
64
+ }).strict()).min(1).max(50),
65
+ requestId: z.string().min(1).max(100).optional()
66
+ },
48
67
  alp_skill: {
49
68
  name: z.string().min(1),
50
69
  description: z.string().min(1).max(300),
51
70
  body: z.string().min(1).max(2e4),
52
71
  roles: z.array(z.string().min(1)).min(1).max(10),
53
72
  lessons: z.array(z.string().min(1).max(600)).max(50).optional(),
54
- replace: z.boolean().optional()
73
+ replace: z.boolean().optional(),
74
+ requestId: z.string().min(1).max(100).optional()
75
+ },
76
+ alp_skill_retire: {
77
+ name: z.string().min(1).max(64),
78
+ reason: z.string().min(1).max(300),
79
+ requestId: z.string().min(1).max(100).optional()
55
80
  },
56
81
  alp_issue: {
57
82
  action: z.enum(["search", "create", "comment"]),
58
83
  target: z.enum(["project", "alp"]),
59
84
  query: z.string().min(1).max(200).optional(),
85
+ requestId: z.string().min(1).max(100).optional(),
60
86
  title: z.string().min(1).max(200).optional(),
61
87
  body: z.string().min(1).max(2e4).optional(),
62
88
  issue: z.number().int().positive().optional(),
63
89
  labels: z.array(z.string().min(1).max(50)).max(10).optional()
64
90
  },
91
+ alp_schedule: {
92
+ action: z.enum(["create", "list", "get", "cancel"]),
93
+ dueAt: z.string().min(1).max(80).optional(),
94
+ prompt: z.string().min(1).max(8e3).optional(),
95
+ requestId: z.string().min(1).max(200).optional(),
96
+ id: z.string().min(1).optional(),
97
+ status: z.enum(["pending", "delivered", "failed", "cancelled"]).optional()
98
+ },
65
99
  alp_task: {
66
100
  action: z.enum(["create", "update", "link", "start", "close", "reopen", "gate", "clear", "pour", "formulas", "show", "list", "ready"]),
67
101
  id: z.string().min(1).optional(),
@@ -80,9 +114,10 @@ var toolShapes = {
80
114
  kind: z.enum(GATE_KINDS).optional(),
81
115
  until: z.string().min(1).optional(),
82
116
  ref: z.string().min(1).optional(),
117
+ options: z.array(z.string().min(1).max(200)).max(10).optional(),
83
118
  gate: z.string().min(1).optional(),
84
119
  formula: z.string().min(1).optional(),
85
- vars: z.record(z.string(), z.string()).optional(),
120
+ vars: bounded(z.record(z.string().regex(VAR_NAME), z.string().max(POUR_VARS.string)), POUR_VARS).optional(),
86
121
  summary: z.string().min(1).max(2e3).optional(),
87
122
  unverified: z.string().min(1).max(2e3).optional(),
88
123
  note: z.string().min(1).max(2e3).optional(),
@@ -93,17 +128,22 @@ var toolShapes = {
93
128
  alp_discard: {
94
129
  assignmentId: z.string().min(1)
95
130
  },
131
+ alp_resolve: {
132
+ assignmentId: z.string().min(1),
133
+ outcome: z.enum(RESULT_OUTCOMES),
134
+ note: z.string().min(1).max(2e3).optional()
135
+ },
96
136
  alp_cancel: {
97
137
  assignmentId: z.string().min(1),
98
138
  reason: z.string().optional()
99
139
  },
100
140
  alp_pin: {
101
141
  kind: z.enum(PIN_KINDS),
102
- body: z.string().min(1),
103
- paths: z.array(z.string().min(1)).optional()
142
+ body: z.string().min(1).max(PIN_BODY_CHARS),
143
+ paths: bounded(z.array(z.string().min(1).max(PIN_PATH_CHARS)).max(PIN_PATHS), PIN_PATHS_INPUT).optional()
104
144
  },
105
145
  alp_board: {
106
- kinds: z.array(z.enum(PIN_KINDS)).optional(),
146
+ kinds: bounded(z.array(z.enum(PIN_KINDS)).max(PIN_KINDS.length), BOARD_KINDS_INPUT).optional(),
107
147
  limit: z.number().int().positive().optional()
108
148
  },
109
149
  alp_unpin: {
@@ -142,6 +182,23 @@ var toolShapes = {
142
182
  }
143
183
  };
144
184
  var SKILL_PLUGIN = "alp";
185
+ var NEW_CONVERSATION_COMMANDS = ["clear", "reset", "new"];
186
+ var NEW_CONVERSATION = new RegExp(`^\\s*\\/(${NEW_CONVERSATION_COMMANDS.join("|")})(?:\\s|$)`);
187
+ var ALP_HANDLED_COMMANDS = /* @__PURE__ */ new Set([...NEW_CONVERSATION_COMMANDS, "compact", "rewind"]);
188
+ var CLEAR_ALIASES = /* @__PURE__ */ new Set(["reset", "new"]);
189
+ function customClearAliases(listed) {
190
+ const rows = Array.isArray(listed) ? listed : [];
191
+ if (!rows.some((row) => typeof row?.builtin === "boolean")) return /* @__PURE__ */ new Set();
192
+ const builtin = new Set(rows.filter((row) => row?.builtin === true).map((row) => row.name));
193
+ 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));
194
+ }
195
+ function nativeCommandRefusal(runtimeKind, content, custom) {
196
+ if (runtimeKind !== "claude") return void 0;
197
+ const typed = content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n");
198
+ const named = NEW_CONVERSATION.exec(typed)?.[1];
199
+ if (!named || custom?.has(named)) return void 0;
200
+ 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).";
201
+ }
145
202
  function skillPlugin(directory, skills) {
146
203
  rmSync(directory, { recursive: true, force: true });
147
204
  mkdirSync(path.join(directory, ".claude-plugin"), { recursive: true });
@@ -219,8 +276,18 @@ function claudePermissions(sandbox, currentSandbox, rules, ask) {
219
276
  // Ask rules make Claude consult canUseTool in every mode, which asks the user.
220
277
  ...rules?.ask?.length ? { settings: { permissions: { ask: rules.ask } } } : {},
221
278
  // The floor: Bash runs in the OS sandbox, which writes only the workspace (or nothing, read-only) and temp files, offline.
279
+ // Keep the SDK's restrictive host-network defaults. Broad Unix socket/localhost
280
+ // access lets host services act outside this floor; the SDK cannot scope local
281
+ // binding to a test server, and scoped Unix sockets are not portable to Linux.
222
282
  // A command leaves it only with dangerouslyDisableSandbox, which Claude allows itself for allow rules and asks canUseTool otherwise.
223
- ...rules?.floor ? { sandbox: { enabled: true, autoAllowBashIfSandboxed: false, allowUnsandboxedCommands: true, ...rules.floor === "read-only" && rules.floorRoot ? { filesystem: { denyWrite: [rules.floorRoot] } } : {} } } : {},
283
+ ...rules?.floor ? {
284
+ sandbox: {
285
+ enabled: true,
286
+ autoAllowBashIfSandboxed: false,
287
+ allowUnsandboxedCommands: true,
288
+ ...rules.floor === "read-only" && rules.floorRoot ? { filesystem: { denyWrite: [rules.floorRoot] } } : {}
289
+ }
290
+ } : {},
224
291
  canUseTool: async (name, input, context) => {
225
292
  const mode = currentSandbox ? currentSandbox() : sandbox;
226
293
  const leaving = Boolean(rules?.floor) && name === "Bash" && input.dangerouslyDisableSandbox === true;
@@ -249,6 +316,17 @@ function claudePermissions(sandbox, currentSandbox, rules, ask) {
249
316
  };
250
317
  }
251
318
  var claudeLimited = (info) => info?.status === "rejected" && info.overageStatus !== "allowed" && info.overageStatus !== "allowed_warning";
319
+ var BOOT_MS = 15e3;
320
+ async function claudeChain(sessionId, dir) {
321
+ const { getSessionMessages } = await claudeSdk();
322
+ let messages = dir ? await getSessionMessages(sessionId, { dir }) : [];
323
+ if (!messages.length) messages = await getSessionMessages(sessionId);
324
+ return messages.filter((message) => (message.type === "user" || message.type === "assistant") && typeof message.uuid === "string").map((message) => {
325
+ const content = message.message?.content;
326
+ const toolResult = message.type === "user" && Array.isArray(content) && content.length > 0 && content.every((block) => block?.type === "tool_result");
327
+ return { uuid: message.uuid, type: message.type, ...toolResult ? { toolResult: true } : {} };
328
+ });
329
+ }
252
330
  var ClaudeTransport = class {
253
331
  constructor(command, cwd, env) {
254
332
  this.command = command;
@@ -285,6 +363,7 @@ var ClaudeTransport = class {
285
363
  activeTurn;
286
364
  closed = false;
287
365
  assistantText = /* @__PURE__ */ new Map();
366
+ streamingMessage;
288
367
  toolCalls = /* @__PURE__ */ new Map();
289
368
  /** The last rate limit Claude reported, and whether the running turn hit one. */
290
369
  rateLimit;
@@ -296,6 +375,12 @@ var ClaudeTransport = class {
296
375
  compaction;
297
376
  /** The plugin directory that loads the agent's skills, removed on close. */
298
377
  skillDirectory;
378
+ /** Whether a turn ran in this process; before one, an error result is a boot refusal. */
379
+ turnsStarted = false;
380
+ /** Rejects when the process fails, for a resume that waits for Claude to start. */
381
+ bootFailure;
382
+ rejectBoot;
383
+ bootError;
299
384
  async orchestrationContext() {
300
385
  const [catalog, usage] = await Promise.all([
301
386
  optionalRead(async () => this.query ? this.query.supportedModels() : void 0),
@@ -315,13 +400,54 @@ var ClaudeTransport = class {
315
400
  usage: claudeUsage(usage)
316
401
  };
317
402
  }
403
+ /**
404
+ * Claude's slash commands, skills included, for the composer (t-f628); none before the session starts.
405
+ * Not the ones whose work ALP does itself (t-efa3): /clear (/reset, /new) moves Claude to a new conversation ALP does not
406
+ * follow, and /compact and /rewind skip ALP's checkpoint and its rewind of the timeline. A command of the user's
407
+ * named new or reset is offered (t-5ac5, customClearAliases); one named clear, compact or rewind never runs, Claude's wins.
408
+ */
409
+ async commands() {
410
+ const listed = await this.listCommands();
411
+ const custom = customClearAliases(listed);
412
+ return (Array.isArray(listed) ? listed : []).filter((command) => typeof command?.name === "string" && command.name && (!ALP_HANDLED_COMMANDS.has(command.name) || command.builtin !== true && custom.has(command.name))).map((command) => ({
413
+ name: command.name,
414
+ description: typeof command.description === "string" ? command.description : "",
415
+ ...command.argumentHint ? { argumentHint: command.argumentHint } : {},
416
+ kind: command.name.startsWith(`${SKILL_PLUGIN}:`) ? "skill" : "command"
417
+ }));
418
+ }
419
+ /** The aliases of /clear that run a command of the user's, as the last listing said (t-5ac5); none before one. */
420
+ customCommands() {
421
+ return this.customAliases;
422
+ }
423
+ customAliases = /* @__PURE__ */ new Set();
424
+ async listCommands() {
425
+ const listed = this.query ? await optionalRead(async () => this.query.supportedCommands(), 1e4) : void 0;
426
+ if (Array.isArray(listed)) this.customAliases = customClearAliases(listed);
427
+ return listed;
428
+ }
318
429
  async initialize() {
319
430
  }
431
+ /** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
432
+ async probeModels(signal) {
433
+ const { query } = await claudeSdk();
434
+ if (signal?.aborted) throw new Error("aborted");
435
+ 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) } });
436
+ const stop = () => probe.close();
437
+ signal?.addEventListener("abort", stop);
438
+ try {
439
+ const models = await probe.supportedModels();
440
+ return models.map((model) => ({ id: model.value, label: model.displayName, description: model.description, efforts: model.supportedEffortLevels ?? void 0 }));
441
+ } finally {
442
+ signal?.removeEventListener("abort", stop);
443
+ probe.close();
444
+ }
445
+ }
320
446
  /** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
321
447
  async probeUsage() {
322
448
  if (this.closed) return void 0;
323
- const { query } = await import(CLAUDE_SDK);
324
- const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } });
449
+ const { query } = await claudeSdk();
450
+ 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) } });
325
451
  try {
326
452
  return await probe.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
327
453
  } finally {
@@ -347,15 +473,20 @@ var ClaudeTransport = class {
347
473
  this.config.sandbox = params.sandbox;
348
474
  return {};
349
475
  }
476
+ if (method === "thread/chain") return { entries: await claudeChain(params.threadId, params.cwd ?? this.cwd) };
350
477
  if (method === "thread/delete") {
351
- const { deleteSession } = await import(CLAUDE_SDK);
478
+ const { deleteSession } = await claudeSdk();
352
479
  await deleteSession(params.threadId, params.cwd ? { dir: params.cwd } : {});
353
480
  return {};
354
481
  }
355
482
  if (method === "thread/start" || method === "thread/resume" || method === "thread/fork") {
356
- this.config = params;
483
+ this.clearAssistantText();
484
+ const { base, requireHistory, ...config } = params;
485
+ this.config = config;
357
486
  this.threadId = method === "thread/resume" ? params.threadId : randomUUID();
358
- await this.start(method === "thread/start" ? void 0 : { resume: params.threadId, fork: method === "thread/fork" });
487
+ const from = method === "thread/start" ? void 0 : method === "thread/resume" ? await this.resumeFrom(params.threadId, base, requireHistory) : { resume: params.threadId, fork: true };
488
+ await this.start(from);
489
+ if (method === "thread/resume" && (base || requireHistory)) await this.booted();
359
490
  return {
360
491
  thread: { id: this.threadId, turns: [] },
361
492
  cwd: this.cwd,
@@ -366,7 +497,11 @@ var ClaudeTransport = class {
366
497
  if (method === "turn/start" || method === "turn/steer") {
367
498
  if (!this.query) throw new Error("Claude thread is not initialized");
368
499
  const turnId = method === "turn/steer" ? params.expectedTurnId : randomUUID();
369
- if (method === "turn/start") this.activeTurn = turnId;
500
+ if (method === "turn/start") {
501
+ this.clearAssistantText();
502
+ this.activeTurn = turnId;
503
+ this.turnsStarted = true;
504
+ }
370
505
  this.input.push({
371
506
  type: "user",
372
507
  message: {
@@ -374,19 +509,69 @@ var ClaudeTransport = class {
374
509
  content: params.input.map(claudeContent)
375
510
  },
376
511
  parent_tool_use_id: null,
377
- uuid: randomUUID(),
512
+ // A turn's prompt entry in the transcript carries the turn's id, so ALP can cut the conversation at it (§12.7).
513
+ uuid: method === "turn/start" ? turnId : randomUUID(),
378
514
  session_id: this.threadId
379
515
  });
380
516
  return method === "turn/start" ? { turn: { id: turnId } } : {};
381
517
  }
518
+ if (method === "thread/compact/start") {
519
+ if (!this.query) throw new Error("Claude thread is not initialized");
520
+ if (this.activeTurn) throw new Error("A turn is running");
521
+ const turnId = randomUUID();
522
+ this.clearAssistantText();
523
+ this.activeTurn = turnId;
524
+ this.turnsStarted = true;
525
+ this.emit("turn/started", { threadId: this.threadId, turn: { id: turnId } });
526
+ const instructions = typeof params.instructions === "string" ? ` ${params.instructions.trim()}` : "";
527
+ this.input.push({ type: "user", message: { role: "user", content: `/compact${instructions}` }, parent_tool_use_id: null, uuid: turnId, session_id: this.threadId });
528
+ return {};
529
+ }
382
530
  if (method === "turn/interrupt") {
531
+ this.streamingMessage = void 0;
383
532
  await this.query?.interrupt();
384
533
  return {};
385
534
  }
386
535
  throw new Error(`Unsupported Claude runtime operation '${method}'`);
387
536
  }
537
+ /**
538
+ * How a resume starts. With a base, a session whose transcript does not exist yet is made from the
539
+ * base's conversation cut at `at` (a fork or rewind, §12.7): Claude writes it, under this session's
540
+ * id, only when its first prompt runs. Otherwise, the session's own transcript.
541
+ */
542
+ async resumeFrom(threadId, base, requireHistory) {
543
+ const own = base || requireHistory ? await claudeChain(threadId, this.config.cwd) : [];
544
+ if (!base || own.length) {
545
+ if (requireHistory && !own.length) throw new Error(`Claude session ${threadId} not found`);
546
+ return { resume: threadId, fork: false };
547
+ }
548
+ const source = await claudeChain(base.threadId, this.config.cwd);
549
+ if (!source.length) throw new Error(`Claude session ${base.threadId} not found`);
550
+ if (base.at && !source.some((entry) => entry.uuid === base.at)) throw new Error(`Claude session ${base.threadId} has no entry ${base.at}`);
551
+ return { resume: base.threadId, fork: true, at: base.at };
552
+ }
553
+ /**
554
+ * Waits until Claude has started: its answer to the SDK's initialize request, or the failure that
555
+ * ends it first. Past BOOT_MS ALP goes on, as any resume does, and a later refusal fails the session.
556
+ */
557
+ async booted() {
558
+ let timer;
559
+ try {
560
+ await Promise.race([
561
+ this.query.initializationResult?.().then(() => void 0, () => void 0),
562
+ this.bootFailure,
563
+ new Promise((resolve) => {
564
+ timer = setTimeout(resolve, BOOT_MS);
565
+ })
566
+ ]);
567
+ } finally {
568
+ clearTimeout(timer);
569
+ }
570
+ await new Promise((resolve) => setImmediate(resolve));
571
+ if (this.bootError) throw this.bootError;
572
+ }
388
573
  async start(from) {
389
- const { createSdkMcpServer, query, tool } = await import(CLAUDE_SDK);
574
+ const { createSdkMcpServer, query, tool } = await claudeSdk();
390
575
  const config = this.config;
391
576
  const mcpServers = this.convertMcp(config.mcpServers);
392
577
  if (config.dynamicTools.length) {
@@ -483,14 +668,21 @@ var ClaudeTransport = class {
483
668
  ...plugins.length ? { plugins } : {},
484
669
  persistSession: !config.ephemeral,
485
670
  promptSuggestions: false,
486
- includePartialMessages: false,
487
- ...from ? { resume: from.resume, ...from.fork ? { forkSession: true, sessionId: this.threadId } : {} } : { sessionId: this.threadId },
671
+ includePartialMessages: true,
672
+ ...from ? { resume: from.resume, ...from.fork ? { forkSession: true, sessionId: this.threadId } : {}, ...from.at ? { resumeSessionAt: from.at } : {} } : { sessionId: this.threadId },
488
673
  // Explicit native path avoids SDK optional binaries inside Electron app.asar.
489
- pathToClaudeCodeExecutable: this.command
674
+ pathToClaudeCodeExecutable: this.command,
675
+ ...scriptExecutable(this.command)
490
676
  };
677
+ this.bootFailure = new Promise((_, reject) => {
678
+ this.rejectBoot = reject;
679
+ });
680
+ this.bootFailure.catch(() => {
681
+ });
491
682
  this.query = query({ prompt: this.input, options });
492
683
  this.pump = this.consume(this.query).catch((error) => this.fail(error));
493
684
  void this.measureContext();
685
+ void this.listCommands();
494
686
  }
495
687
  /** Reads the window and the compaction threshold Claude resolved for this session, before any turn. */
496
688
  async measureContext() {
@@ -521,16 +713,44 @@ var ClaudeTransport = class {
521
713
  if (!this.closed) this.fail(new Error("Claude session exited"));
522
714
  }
523
715
  handle(message) {
716
+ if (this.closed) return;
524
717
  if (message.type === "rate_limit_event") {
525
718
  this.rateLimit = message.rate_limit_info;
526
719
  this.emit("account/rateLimits/updated", { claude: message.rate_limit_info });
527
720
  return;
528
721
  }
529
- if (message.type === "assistant" && !message.parent_tool_use_id && !this.activeTurn && !this.closed) {
722
+ const streamStart = message.type === "stream_event" && message.event?.type === "message_start";
723
+ if ((message.type === "assistant" || streamStart) && !message.parent_tool_use_id && !this.activeTurn) {
530
724
  this.activeTurn = randomUUID();
531
725
  this.emit("turn/started", { threadId: this.threadId, turn: { id: this.activeTurn } });
532
726
  }
727
+ if (message.type === "stream_event") {
728
+ if (message.parent_tool_use_id) return;
729
+ const event = message.event;
730
+ if (event.type === "message_start") {
731
+ this.streamingMessage = event.message.id;
732
+ } else if (event.type === "message_stop") {
733
+ this.streamingMessage = void 0;
734
+ } else if (this.streamingMessage) {
735
+ const id = this.streamingMessage;
736
+ const state = this.assistantState(id);
737
+ let delta;
738
+ if (event.type === "content_block_start" && event.content_block.type === "text") {
739
+ state.blocks.set(event.index, { text: event.content_block.text, final: false });
740
+ delta = event.content_block.text;
741
+ } else if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
742
+ const block = state.blocks.get(event.index);
743
+ if (block && !block.final) {
744
+ block.text += event.delta.text;
745
+ delta = event.delta.text;
746
+ }
747
+ }
748
+ if (delta) this.emit("item/agentMessage/delta", { threadId: this.threadId, turnId: this.activeTurn, itemId: id, delta });
749
+ }
750
+ return;
751
+ }
533
752
  if (message.type === "assistant" && message.error === "rate_limit") this.limitedTurn = true;
753
+ if (message.type === "system" && message.subtype === "init" && typeof message.model === "string") this.emit("alp/nativeModel", { threadId: this.threadId, model: message.model });
534
754
  if (message.type === "system" && (message.subtype === "status" || message.subtype === "compact_boundary")) {
535
755
  const system = message;
536
756
  if (system.subtype === "status" && system.status === "compacting" && !this.compaction) {
@@ -567,14 +787,18 @@ var ClaudeTransport = class {
567
787
  if (windows.length && !this.compactAt) this.contextWindow = Math.max(...windows);
568
788
  }
569
789
  if (message.type === "assistant" && !message.parent_tool_use_id) {
790
+ const id = message.message.id;
791
+ const state = this.assistantState(id);
792
+ if (message.uuid && state.seen.has(message.uuid)) return;
793
+ if (message.uuid) state.seen.add(message.uuid);
570
794
  for (const block of message.message.content) {
571
795
  if (block.type === "text") {
572
- const id = message.message.id;
573
- const text = (this.assistantText.get(id) ?? "") + block.text;
574
- this.assistantText.set(id, text);
796
+ const pending = [...state.blocks.entries()].sort(([a], [b]) => a - b).find(([, value]) => !value.final);
797
+ const index = pending?.[0] ?? Math.max(-1, ...state.blocks.keys()) + 1;
798
+ state.blocks.set(index, { text: block.text, final: true });
575
799
  this.emit("item/completed", {
576
800
  threadId: this.threadId,
577
- item: { type: "agentMessage", id, text }
801
+ item: { type: "agentMessage", id, text: [...state.blocks.entries()].sort(([a], [b]) => a - b).map(([, block2]) => block2.text).join("") }
578
802
  });
579
803
  } else if (block.type === "tool_use") {
580
804
  const command = block.name === "Bash" ? String(block.input?.command ?? "") : `${block.name} ${JSON.stringify(block.input ?? {})}`;
@@ -623,6 +847,11 @@ var ClaudeTransport = class {
623
847
  }
624
848
  return;
625
849
  }
850
+ if (message.type === "result" && message.is_error && !this.activeTurn && !this.turnsStarted) {
851
+ this.refuseBoot(new Error(message.errors?.length ? message.errors.join("; ") : "Claude refused to start the session"));
852
+ return;
853
+ }
854
+ if (message.type === "result") this.clearAssistantText();
626
855
  if (message.type === "result" && this.activeTurn) {
627
856
  const turnId = this.activeTurn;
628
857
  this.activeTurn = void 0;
@@ -642,17 +871,33 @@ var ClaudeTransport = class {
642
871
  });
643
872
  }
644
873
  }
874
+ refuseBoot(error) {
875
+ this.bootError ??= error;
876
+ this.rejectBoot?.(error);
877
+ }
645
878
  emit(method, params) {
646
879
  for (const listener of this.listeners) listener(method, params);
647
880
  }
881
+ assistantState(id) {
882
+ let state = this.assistantText.get(id);
883
+ if (!state) this.assistantText.set(id, state = { blocks: /* @__PURE__ */ new Map(), seen: /* @__PURE__ */ new Set() });
884
+ return state;
885
+ }
886
+ clearAssistantText() {
887
+ this.streamingMessage = void 0;
888
+ this.assistantText.clear();
889
+ }
648
890
  fail(value) {
649
891
  if (this.closed) return;
892
+ this.clearAssistantText();
650
893
  const error = value instanceof Error ? value : new Error(String(value));
894
+ this.refuseBoot(error);
651
895
  for (const listener of this.failures) listener(error);
652
896
  }
653
897
  async close() {
654
898
  if (this.closed) return;
655
899
  this.closed = true;
900
+ this.clearAssistantText();
656
901
  this.input.close();
657
902
  this.query?.close();
658
903
  await this.pump?.catch(() => {
@@ -673,11 +918,14 @@ var ClaudeTransport = class {
673
918
  export {
674
919
  ClaudeTransport,
675
920
  SKILL_PLUGIN,
921
+ claudeChain,
676
922
  claudeContent,
677
923
  claudeLimited,
678
924
  claudePermissionMode,
679
925
  claudePermissions,
680
926
  claudeSandboxAvailable,
927
+ customClearAliases,
928
+ nativeCommandRefusal,
681
929
  skillPlugin,
682
930
  toolShapes
683
931
  };
@@ -0,0 +1,29 @@
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
+ export interface CompactSettings {
8
+ auto: boolean;
9
+ threshold: number;
10
+ }
11
+ export declare const COMPACT_DEFAULTS: CompactSettings;
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 declare function compactSettings(raw: unknown): CompactSettings;
18
+ /** How full the context is, 0..1, from a runtime's token usage; undefined when the window is unknown. */
19
+ export declare function contextFill(usage: any): number | undefined;
20
+ /** Whether an idle root should compact now. */
21
+ export declare function compactDue(settings: CompactSettings, fill: number | undefined, requested: boolean): 'auto' | 'manual' | undefined;
22
+ /** Runtimes that compact a conversation in place. */
23
+ export declare const NATIVE_COMPACT: string[];
24
+ export declare const CHECKPOINT_MARK = "ALP compact checkpoint";
25
+ export declare function checkpointPrompt(trigger: 'auto' | 'manual', fill?: number): string;
26
+ /** What the runtime's native compaction is told to keep. */
27
+ export declare function compactInstructions(checkpoint: string): string;
28
+ /** The first prompt of a fresh conversation that replaces a full one. */
29
+ export declare function seedPrompt(checkpoint: string, lastUser?: string): string;
@@ -0,0 +1,49 @@
1
+ // packages/runtime/src/compact.ts
2
+ var COMPACT_DEFAULTS = Object.freeze({ auto: true, threshold: 0.7 });
3
+ function compactSettings(raw) {
4
+ const value = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
5
+ const auto = typeof value.auto === "boolean" ? value.auto : COMPACT_DEFAULTS.auto;
6
+ const threshold = typeof value.threshold === "number" && Number.isFinite(value.threshold) && value.threshold > 0 && value.threshold < 1 ? value.threshold : COMPACT_DEFAULTS.threshold;
7
+ return { auto, threshold };
8
+ }
9
+ function contextFill(usage) {
10
+ const used = usage?.last?.totalTokens;
11
+ const window = usage?.modelContextWindow;
12
+ if (typeof used !== "number" || typeof window !== "number" || window <= 0) return void 0;
13
+ return used / window;
14
+ }
15
+ function compactDue(settings, fill, requested) {
16
+ if (requested) return "manual";
17
+ if (settings.auto && typeof fill === "number" && fill >= settings.threshold) return "auto";
18
+ return void 0;
19
+ }
20
+ var NATIVE_COMPACT = ["claude", "codex"];
21
+ var CHECKPOINT_MARK = "ALP compact checkpoint";
22
+ function checkpointPrompt(trigger, fill) {
23
+ const why = trigger === "manual" ? "The user asked to compact your context." : `Your context is about ${Math.round((fill ?? 0) * 100)}% full.`;
24
+ 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.`;
25
+ }
26
+ function compactInstructions(checkpoint) {
27
+ return `Keep this checkpoint verbatim in the summary; it is the state of the work:
28
+ ${checkpoint}`;
29
+ }
30
+ function seedPrompt(checkpoint, lastUser) {
31
+ return [
32
+ "Your context was compacted: ALP started this conversation fresh. Your instructions are unchanged. This is the checkpoint you wrote before, by skill compact:",
33
+ checkpoint,
34
+ ...lastUser ? [`The user's last message before the compaction, verbatim:
35
+ ${lastUser}`] : [],
36
+ "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."
37
+ ].join("\n\n");
38
+ }
39
+ export {
40
+ CHECKPOINT_MARK,
41
+ COMPACT_DEFAULTS,
42
+ NATIVE_COMPACT,
43
+ checkpointPrompt,
44
+ compactDue,
45
+ compactInstructions,
46
+ compactSettings,
47
+ contextFill,
48
+ seedPrompt
49
+ };
@@ -0,0 +1,44 @@
1
+ import type { ConfigureChange, EffectiveConfig } from '@anhlp/alp-protocol/session';
2
+ import type { ResolvedSession, RuntimeKind } from './resolve.js';
3
+ export type { ConfigureChange, EffectiveConfig } from '@anhlp/alp-protocol/session';
4
+ /** What a client may change on a live root; each absent field keeps the session's own. */
5
+ export type ConfigureChanges = {
6
+ model?: string;
7
+ thinking?: string;
8
+ team?: string;
9
+ mode?: string;
10
+ };
11
+ /** Runtimes whose roots alpd reconfigures live (macOS and Linux; Codex and Claude, issue #121 closure scope). */
12
+ export declare const CONFIGURABLE: ReadonlySet<RuntimeKind>;
13
+ /**
14
+ * The native model `model` names for a session of `runtime`: unprefixed, or prefixed with that runtime
15
+ * (`codex:`, `claude:`, or with a slash). A prefix of another runtime is a migration, never taken.
16
+ */
17
+ export declare function nativeModelOf(runtime: RuntimeKind, model: string): {
18
+ model: string;
19
+ } | {
20
+ runtime: string;
21
+ };
22
+ /**
23
+ * Whether the host offers `model` on `runtime`: ALP's live catalog (catalog.ts entries, what library.models and
24
+ * catalog.get list), a model the project's settings give an agent of the team, or the model the session
25
+ * runs already. Never an arbitrary string.
26
+ */
27
+ export declare function offered(runtime: RuntimeKind, model: string, mapping: ResolvedSession): boolean;
28
+ /** MCP servers of a resolved session by name and kind: a stdio one runs a command on the host. */
29
+ export declare function mcpOf(mapping: ResolvedSession): EffectiveConfig['mcpServers'];
30
+ /**
31
+ * What of a resolved session runs commands on the daemon host: its stdio MCP servers (command, args,
32
+ * env names) and its hooks (event and command), each as a digest. A change may keep or drop these,
33
+ * never add one (a team change that brings an executable resource is refused).
34
+ */
35
+ export declare function executablesOf(mapping: ResolvedSession): Set<string>;
36
+ /** The effective configuration of a resolved root, with its delegation targets, ALP tools and instructions digest. */
37
+ export declare function effectiveOf(runtime: RuntimeKind, mapping: ResolvedSession, extra: {
38
+ delegates: string[];
39
+ tools: string[];
40
+ supervisor: boolean;
41
+ instructionsSha?: string;
42
+ }): EffectiveConfig;
43
+ /** Which of model, thinking, team and mode differ between two effective configurations. */
44
+ export declare function changesOf(current: EffectiveConfig, proposed: EffectiveConfig): ConfigureChange[];