@anhlp/alp-runtime 0.0.1-beta.3 → 0.0.1-beta.5

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 (80) hide show
  1. package/dist/acp-transport.js +5 -36
  2. package/dist/antigravity-transport.d.ts +17 -0
  3. package/dist/antigravity-transport.js +82 -58
  4. package/dist/assignment-results.d.ts +52 -0
  5. package/dist/assignment-results.js +169 -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 +9 -1
  13. package/dist/claude-transport.d.ts +35 -0
  14. package/dist/claude-transport.js +152 -10
  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 +185 -4
  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 +15 -4
  24. package/dist/index.js +40 -3
  25. package/dist/input-limits.d.ts +25 -0
  26. package/dist/input-limits.js +48 -0
  27. package/dist/language.d.ts +8 -0
  28. package/dist/language.js +20 -0
  29. package/dist/mailbox.d.ts +2 -0
  30. package/dist/mailbox.js +3 -1
  31. package/dist/mcp-tools.d.ts +8 -0
  32. package/dist/mcp-tools.js +26 -0
  33. package/dist/model-catalog.d.ts +76 -0
  34. package/dist/model-catalog.js +193 -0
  35. package/dist/model-probes.d.ts +7 -0
  36. package/dist/model-probes.js +69 -0
  37. package/dist/providers.js +2 -0
  38. package/dist/resolve.d.ts +1 -0
  39. package/dist/resolve.js +3 -1
  40. package/dist/runtime.d.ts +9 -0
  41. package/dist/runtime.js +1547 -142
  42. package/dist/session-config.d.ts +279 -0
  43. package/dist/session-config.js +10 -10
  44. package/dist/session-state.d.ts +44 -6
  45. package/dist/tools.d.ts +119 -0
  46. package/dist/tools.js +72 -5
  47. package/dist/transport.js +3 -1
  48. package/dist/workspace.d.ts +11 -4
  49. package/dist/workspace.js +29 -11
  50. package/dist/worktree-domain.d.ts +2 -1
  51. package/dist/worktree-domain.js +4 -1
  52. package/package.json +11 -3
  53. package/src/acp-transport.ts +7 -37
  54. package/src/antigravity-transport.ts +95 -53
  55. package/src/assignment-results.ts +146 -0
  56. package/src/attachments.ts +254 -0
  57. package/src/board-domain.ts +2 -2
  58. package/src/board.ts +7 -0
  59. package/src/catalog.ts +10 -1
  60. package/src/claude-transport.ts +171 -11
  61. package/src/compact.ts +62 -0
  62. package/src/configure.ts +93 -0
  63. package/src/contracts.ts +172 -5
  64. package/src/conversation.ts +81 -0
  65. package/src/index.ts +15 -4
  66. package/src/input-limits.ts +65 -0
  67. package/src/language.ts +18 -0
  68. package/src/mailbox.ts +4 -1
  69. package/src/mcp-tools.ts +33 -0
  70. package/src/model-catalog.ts +166 -0
  71. package/src/model-probes.ts +58 -0
  72. package/src/providers.ts +3 -0
  73. package/src/resolve.ts +4 -2
  74. package/src/runtime.ts +1681 -151
  75. package/src/session-config.ts +9 -9
  76. package/src/session-state.ts +29 -2
  77. package/src/tools.ts +69 -5
  78. package/src/transport.ts +3 -1
  79. package/src/workspace.ts +42 -15
  80. package/src/worktree-domain.ts +5 -1
@@ -6,11 +6,18 @@ 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";
13
15
  var CLAUDE_SDK = ["@anthropic-ai", "claude-agent-sdk"].join("/");
16
+ var bounded = (schema, limits) => z.preprocess((value, ctx) => {
17
+ const error = inputLimitError(value, limits);
18
+ if (error) ctx.addIssue({ code: "custom", message: error });
19
+ return value;
20
+ }, schema);
14
21
  var handoffList = z.array(z.string().min(1)).max(100).optional();
15
22
  var taskIds = z.array(z.string().min(1)).max(50).optional();
16
23
  var taskLinks = z.object({ blockedBy: taskIds, related: taskIds, parent: z.string().min(1).optional() }).strict().optional();
@@ -45,6 +52,15 @@ var toolShapes = {
45
52
  scope: z.enum(["project", "user"]),
46
53
  lesson: z.string().min(1).max(600)
47
54
  },
55
+ alp_lesson_curate: {
56
+ changes: z.array(z.object({
57
+ scope: z.enum(["project", "user"]),
58
+ remove: z.array(z.string().min(1).max(600)).min(1).max(50),
59
+ add: z.string().min(1).max(600).optional(),
60
+ reason: z.string().max(300).optional()
61
+ }).strict()).min(1).max(50),
62
+ requestId: z.string().min(1).max(100).optional()
63
+ },
48
64
  alp_skill: {
49
65
  name: z.string().min(1),
50
66
  description: z.string().min(1).max(300),
@@ -64,6 +80,14 @@ var toolShapes = {
64
80
  issue: z.number().int().positive().optional(),
65
81
  labels: z.array(z.string().min(1).max(50)).max(10).optional()
66
82
  },
83
+ alp_schedule: {
84
+ action: z.enum(["create", "list", "get", "cancel"]),
85
+ dueAt: z.string().min(1).max(80).optional(),
86
+ prompt: z.string().min(1).max(8e3).optional(),
87
+ requestId: z.string().min(1).max(200).optional(),
88
+ id: z.string().min(1).optional(),
89
+ status: z.enum(["pending", "delivered", "failed", "cancelled"]).optional()
90
+ },
67
91
  alp_task: {
68
92
  action: z.enum(["create", "update", "link", "start", "close", "reopen", "gate", "clear", "pour", "formulas", "show", "list", "ready"]),
69
93
  id: z.string().min(1).optional(),
@@ -82,9 +106,10 @@ var toolShapes = {
82
106
  kind: z.enum(GATE_KINDS).optional(),
83
107
  until: z.string().min(1).optional(),
84
108
  ref: z.string().min(1).optional(),
109
+ options: z.array(z.string().min(1).max(200)).max(10).optional(),
85
110
  gate: z.string().min(1).optional(),
86
111
  formula: z.string().min(1).optional(),
87
- vars: z.record(z.string(), z.string()).optional(),
112
+ vars: bounded(z.record(z.string().regex(VAR_NAME), z.string().max(POUR_VARS.string)), POUR_VARS).optional(),
88
113
  summary: z.string().min(1).max(2e3).optional(),
89
114
  unverified: z.string().min(1).max(2e3).optional(),
90
115
  note: z.string().min(1).max(2e3).optional(),
@@ -95,17 +120,22 @@ var toolShapes = {
95
120
  alp_discard: {
96
121
  assignmentId: z.string().min(1)
97
122
  },
123
+ alp_resolve: {
124
+ assignmentId: z.string().min(1),
125
+ outcome: z.enum(RESULT_OUTCOMES),
126
+ note: z.string().min(1).max(2e3).optional()
127
+ },
98
128
  alp_cancel: {
99
129
  assignmentId: z.string().min(1),
100
130
  reason: z.string().optional()
101
131
  },
102
132
  alp_pin: {
103
133
  kind: z.enum(PIN_KINDS),
104
- body: z.string().min(1),
105
- paths: z.array(z.string().min(1)).optional()
134
+ body: z.string().min(1).max(PIN_BODY_CHARS),
135
+ paths: bounded(z.array(z.string().min(1).max(PIN_PATH_CHARS)).max(PIN_PATHS), PIN_PATHS_INPUT).optional()
106
136
  },
107
137
  alp_board: {
108
- kinds: z.array(z.enum(PIN_KINDS)).optional(),
138
+ kinds: bounded(z.array(z.enum(PIN_KINDS)).max(PIN_KINDS.length), BOARD_KINDS_INPUT).optional(),
109
139
  limit: z.number().int().positive().optional()
110
140
  },
111
141
  alp_unpin: {
@@ -221,8 +251,18 @@ function claudePermissions(sandbox, currentSandbox, rules, ask) {
221
251
  // Ask rules make Claude consult canUseTool in every mode, which asks the user.
222
252
  ...rules?.ask?.length ? { settings: { permissions: { ask: rules.ask } } } : {},
223
253
  // The floor: Bash runs in the OS sandbox, which writes only the workspace (or nothing, read-only) and temp files, offline.
254
+ // Keep the SDK's restrictive host-network defaults. Broad Unix socket/localhost
255
+ // access lets host services act outside this floor; the SDK cannot scope local
256
+ // binding to a test server, and scoped Unix sockets are not portable to Linux.
224
257
  // A command leaves it only with dangerouslyDisableSandbox, which Claude allows itself for allow rules and asks canUseTool otherwise.
225
- ...rules?.floor ? { sandbox: { enabled: true, autoAllowBashIfSandboxed: false, allowUnsandboxedCommands: true, ...rules.floor === "read-only" && rules.floorRoot ? { filesystem: { denyWrite: [rules.floorRoot] } } : {} } } : {},
258
+ ...rules?.floor ? {
259
+ sandbox: {
260
+ enabled: true,
261
+ autoAllowBashIfSandboxed: false,
262
+ allowUnsandboxedCommands: true,
263
+ ...rules.floor === "read-only" && rules.floorRoot ? { filesystem: { denyWrite: [rules.floorRoot] } } : {}
264
+ }
265
+ } : {},
226
266
  canUseTool: async (name, input, context) => {
227
267
  const mode = currentSandbox ? currentSandbox() : sandbox;
228
268
  const leaving = Boolean(rules?.floor) && name === "Bash" && input.dangerouslyDisableSandbox === true;
@@ -251,6 +291,17 @@ function claudePermissions(sandbox, currentSandbox, rules, ask) {
251
291
  };
252
292
  }
253
293
  var claudeLimited = (info) => info?.status === "rejected" && info.overageStatus !== "allowed" && info.overageStatus !== "allowed_warning";
294
+ var BOOT_MS = 15e3;
295
+ async function claudeChain(sessionId, dir) {
296
+ const { getSessionMessages } = await import(CLAUDE_SDK);
297
+ let messages = dir ? await getSessionMessages(sessionId, { dir }) : [];
298
+ if (!messages.length) messages = await getSessionMessages(sessionId);
299
+ return messages.filter((message) => (message.type === "user" || message.type === "assistant") && typeof message.uuid === "string").map((message) => {
300
+ const content = message.message?.content;
301
+ const toolResult = message.type === "user" && Array.isArray(content) && content.length > 0 && content.every((block) => block?.type === "tool_result");
302
+ return { uuid: message.uuid, type: message.type, ...toolResult ? { toolResult: true } : {} };
303
+ });
304
+ }
254
305
  var ClaudeTransport = class {
255
306
  constructor(command, cwd, env) {
256
307
  this.command = command;
@@ -299,6 +350,12 @@ var ClaudeTransport = class {
299
350
  compaction;
300
351
  /** The plugin directory that loads the agent's skills, removed on close. */
301
352
  skillDirectory;
353
+ /** Whether a turn ran in this process; before one, an error result is a boot refusal. */
354
+ turnsStarted = false;
355
+ /** Rejects when the process fails, for a resume that waits for Claude to start. */
356
+ bootFailure;
357
+ rejectBoot;
358
+ bootError;
302
359
  async orchestrationContext() {
303
360
  const [catalog, usage] = await Promise.all([
304
361
  optionalRead(async () => this.query ? this.query.supportedModels() : void 0),
@@ -320,6 +377,21 @@ var ClaudeTransport = class {
320
377
  }
321
378
  async initialize() {
322
379
  }
380
+ /** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
381
+ async probeModels(signal) {
382
+ const { query } = await import(CLAUDE_SDK);
383
+ if (signal?.aborted) throw new Error("aborted");
384
+ const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } });
385
+ const stop = () => probe.close();
386
+ signal?.addEventListener("abort", stop);
387
+ try {
388
+ const models = await probe.supportedModels();
389
+ return models.map((model) => ({ id: model.value, label: model.displayName, description: model.description, efforts: model.supportedEffortLevels ?? void 0 }));
390
+ } finally {
391
+ signal?.removeEventListener("abort", stop);
392
+ probe.close();
393
+ }
394
+ }
323
395
  /** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
324
396
  async probeUsage() {
325
397
  if (this.closed) return void 0;
@@ -350,6 +422,7 @@ var ClaudeTransport = class {
350
422
  this.config.sandbox = params.sandbox;
351
423
  return {};
352
424
  }
425
+ if (method === "thread/chain") return { entries: await claudeChain(params.threadId, params.cwd ?? this.cwd) };
353
426
  if (method === "thread/delete") {
354
427
  const { deleteSession } = await import(CLAUDE_SDK);
355
428
  await deleteSession(params.threadId, params.cwd ? { dir: params.cwd } : {});
@@ -357,9 +430,12 @@ var ClaudeTransport = class {
357
430
  }
358
431
  if (method === "thread/start" || method === "thread/resume" || method === "thread/fork") {
359
432
  this.clearAssistantText();
360
- this.config = params;
433
+ const { base, requireHistory, ...config } = params;
434
+ this.config = config;
361
435
  this.threadId = method === "thread/resume" ? params.threadId : randomUUID();
362
- await this.start(method === "thread/start" ? void 0 : { resume: params.threadId, fork: method === "thread/fork" });
436
+ const from = method === "thread/start" ? void 0 : method === "thread/resume" ? await this.resumeFrom(params.threadId, base, requireHistory) : { resume: params.threadId, fork: true };
437
+ await this.start(from);
438
+ if (method === "thread/resume" && (base || requireHistory)) await this.booted();
363
439
  return {
364
440
  thread: { id: this.threadId, turns: [] },
365
441
  cwd: this.cwd,
@@ -373,6 +449,7 @@ var ClaudeTransport = class {
373
449
  if (method === "turn/start") {
374
450
  this.clearAssistantText();
375
451
  this.activeTurn = turnId;
452
+ this.turnsStarted = true;
376
453
  }
377
454
  this.input.push({
378
455
  type: "user",
@@ -381,11 +458,24 @@ var ClaudeTransport = class {
381
458
  content: params.input.map(claudeContent)
382
459
  },
383
460
  parent_tool_use_id: null,
384
- uuid: randomUUID(),
461
+ // A turn's prompt entry in the transcript carries the turn's id, so ALP can cut the conversation at it (§12.7).
462
+ uuid: method === "turn/start" ? turnId : randomUUID(),
385
463
  session_id: this.threadId
386
464
  });
387
465
  return method === "turn/start" ? { turn: { id: turnId } } : {};
388
466
  }
467
+ if (method === "thread/compact/start") {
468
+ if (!this.query) throw new Error("Claude thread is not initialized");
469
+ if (this.activeTurn) throw new Error("A turn is running");
470
+ const turnId = randomUUID();
471
+ this.clearAssistantText();
472
+ this.activeTurn = turnId;
473
+ this.turnsStarted = true;
474
+ this.emit("turn/started", { threadId: this.threadId, turn: { id: turnId } });
475
+ const instructions = typeof params.instructions === "string" ? ` ${params.instructions.trim()}` : "";
476
+ this.input.push({ type: "user", message: { role: "user", content: `/compact${instructions}` }, parent_tool_use_id: null, uuid: turnId, session_id: this.threadId });
477
+ return {};
478
+ }
389
479
  if (method === "turn/interrupt") {
390
480
  this.streamingMessage = void 0;
391
481
  await this.query?.interrupt();
@@ -393,6 +483,42 @@ var ClaudeTransport = class {
393
483
  }
394
484
  throw new Error(`Unsupported Claude runtime operation '${method}'`);
395
485
  }
486
+ /**
487
+ * How a resume starts. With a base, a session whose transcript does not exist yet is made from the
488
+ * base's conversation cut at `at` (a fork or rewind, §12.7): Claude writes it, under this session's
489
+ * id, only when its first prompt runs. Otherwise, the session's own transcript.
490
+ */
491
+ async resumeFrom(threadId, base, requireHistory) {
492
+ const own = base || requireHistory ? await claudeChain(threadId, this.config.cwd) : [];
493
+ if (!base || own.length) {
494
+ if (requireHistory && !own.length) throw new Error(`Claude session ${threadId} not found`);
495
+ return { resume: threadId, fork: false };
496
+ }
497
+ const source = await claudeChain(base.threadId, this.config.cwd);
498
+ if (!source.length) throw new Error(`Claude session ${base.threadId} not found`);
499
+ if (base.at && !source.some((entry) => entry.uuid === base.at)) throw new Error(`Claude session ${base.threadId} has no entry ${base.at}`);
500
+ return { resume: base.threadId, fork: true, at: base.at };
501
+ }
502
+ /**
503
+ * Waits until Claude has started: its answer to the SDK's initialize request, or the failure that
504
+ * ends it first. Past BOOT_MS ALP goes on, as any resume does, and a later refusal fails the session.
505
+ */
506
+ async booted() {
507
+ let timer;
508
+ try {
509
+ await Promise.race([
510
+ this.query.initializationResult?.().then(() => void 0, () => void 0),
511
+ this.bootFailure,
512
+ new Promise((resolve) => {
513
+ timer = setTimeout(resolve, BOOT_MS);
514
+ })
515
+ ]);
516
+ } finally {
517
+ clearTimeout(timer);
518
+ }
519
+ await new Promise((resolve) => setImmediate(resolve));
520
+ if (this.bootError) throw this.bootError;
521
+ }
396
522
  async start(from) {
397
523
  const { createSdkMcpServer, query, tool } = await import(CLAUDE_SDK);
398
524
  const config = this.config;
@@ -492,10 +618,15 @@ var ClaudeTransport = class {
492
618
  persistSession: !config.ephemeral,
493
619
  promptSuggestions: false,
494
620
  includePartialMessages: true,
495
- ...from ? { resume: from.resume, ...from.fork ? { forkSession: true, sessionId: this.threadId } : {} } : { sessionId: this.threadId },
621
+ ...from ? { resume: from.resume, ...from.fork ? { forkSession: true, sessionId: this.threadId } : {}, ...from.at ? { resumeSessionAt: from.at } : {} } : { sessionId: this.threadId },
496
622
  // Explicit native path avoids SDK optional binaries inside Electron app.asar.
497
623
  pathToClaudeCodeExecutable: this.command
498
624
  };
625
+ this.bootFailure = new Promise((_, reject) => {
626
+ this.rejectBoot = reject;
627
+ });
628
+ this.bootFailure.catch(() => {
629
+ });
499
630
  this.query = query({ prompt: this.input, options });
500
631
  this.pump = this.consume(this.query).catch((error) => this.fail(error));
501
632
  void this.measureContext();
@@ -566,6 +697,7 @@ var ClaudeTransport = class {
566
697
  return;
567
698
  }
568
699
  if (message.type === "assistant" && message.error === "rate_limit") this.limitedTurn = true;
700
+ if (message.type === "system" && message.subtype === "init" && typeof message.model === "string") this.emit("alp/nativeModel", { threadId: this.threadId, model: message.model });
569
701
  if (message.type === "system" && (message.subtype === "status" || message.subtype === "compact_boundary")) {
570
702
  const system = message;
571
703
  if (system.subtype === "status" && system.status === "compacting" && !this.compaction) {
@@ -662,6 +794,10 @@ var ClaudeTransport = class {
662
794
  }
663
795
  return;
664
796
  }
797
+ if (message.type === "result" && message.is_error && !this.activeTurn && !this.turnsStarted) {
798
+ this.refuseBoot(new Error(message.errors?.length ? message.errors.join("; ") : "Claude refused to start the session"));
799
+ return;
800
+ }
665
801
  if (message.type === "result") this.clearAssistantText();
666
802
  if (message.type === "result" && this.activeTurn) {
667
803
  const turnId = this.activeTurn;
@@ -682,6 +818,10 @@ var ClaudeTransport = class {
682
818
  });
683
819
  }
684
820
  }
821
+ refuseBoot(error) {
822
+ this.bootError ??= error;
823
+ this.rejectBoot?.(error);
824
+ }
685
825
  emit(method, params) {
686
826
  for (const listener of this.listeners) listener(method, params);
687
827
  }
@@ -698,6 +838,7 @@ var ClaudeTransport = class {
698
838
  if (this.closed) return;
699
839
  this.clearAssistantText();
700
840
  const error = value instanceof Error ? value : new Error(String(value));
841
+ this.refuseBoot(error);
701
842
  for (const listener of this.failures) listener(error);
702
843
  }
703
844
  async close() {
@@ -724,6 +865,7 @@ var ClaudeTransport = class {
724
865
  export {
725
866
  ClaudeTransport,
726
867
  SKILL_PLUGIN,
868
+ claudeChain,
727
869
  claudeContent,
728
870
  claudeLimited,
729
871
  claudePermissionMode,
@@ -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[];
@@ -0,0 +1,64 @@
1
+ // packages/runtime/src/configure.ts
2
+ import { createHash } from "node:crypto";
3
+ import { entries } from "./catalog.js";
4
+ import { profileModel } from "@anhlp/alp-core/profiles";
5
+ var CONFIGURABLE = /* @__PURE__ */ new Set(["codex", "claude"]);
6
+ var PREFIXED = /^(codex|claude|antigravity|acp)[:/](.*)$/s;
7
+ function nativeModelOf(runtime, model) {
8
+ const match = PREFIXED.exec(model);
9
+ if (!match) return { model };
10
+ return match[1] === runtime ? { model: match[2] } : { runtime: match[1] };
11
+ }
12
+ function offered(runtime, model, mapping) {
13
+ if (model === mapping.model) return true;
14
+ if (entries.some((entry) => entry.runtime === runtime && entry.id === model)) return true;
15
+ return Object.values(mapping.modelProfiles ?? {}).flat().some((profile) => profileModel(profile) === `${runtime}:${model}`);
16
+ }
17
+ function mcpOf(mapping) {
18
+ return Object.entries(mapping.mcp ?? {}).map(([name, server]) => ({ name, kind: server && typeof server === "object" && "command" in server ? "stdio" : "http" }));
19
+ }
20
+ var digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
21
+ function executablesOf(mapping) {
22
+ const found = /* @__PURE__ */ new Set();
23
+ for (const [name, server] of Object.entries(mapping.mcp ?? {})) {
24
+ if (server && typeof server === "object" && "command" in server) found.add(`mcp:${name}:${digest([server.command, server.args ?? [], Object.keys(server.env ?? {}).sort()])}`);
25
+ }
26
+ for (const hook of mapping.hooks ?? []) found.add(`hook:${hook.name ?? ""}:${digest([hook.event, hook.command])}`);
27
+ return found;
28
+ }
29
+ function effectiveOf(runtime, mapping, extra) {
30
+ return {
31
+ team: mapping.workflow.mode,
32
+ ...mapping.team?.label ? { teamLabel: mapping.team.label } : {},
33
+ agent: mapping.agent.name,
34
+ runtime,
35
+ model: mapping.model,
36
+ thinking: mapping.thinking,
37
+ mode: mapping.mode,
38
+ ...mapping.permissions?.name ? { permissionProfile: mapping.permissions.name } : {},
39
+ supervisor: extra.supervisor,
40
+ maxPeers: mapping.workflow.maxPeers,
41
+ delegates: [...extra.delegates],
42
+ tools: [...extra.tools],
43
+ mcpServers: mcpOf(mapping),
44
+ hooks: (mapping.hooks ?? []).length,
45
+ ...extra.instructionsSha ? { instructionsSha: extra.instructionsSha } : {}
46
+ };
47
+ }
48
+ function changesOf(current, proposed) {
49
+ const changes = [];
50
+ if (current.model !== proposed.model) changes.push("model");
51
+ if (current.thinking !== proposed.thinking) changes.push("thinking");
52
+ if (current.team !== proposed.team) changes.push("team");
53
+ if (current.mode !== proposed.mode) changes.push("mode");
54
+ return changes;
55
+ }
56
+ export {
57
+ CONFIGURABLE,
58
+ changesOf,
59
+ effectiveOf,
60
+ executablesOf,
61
+ mcpOf,
62
+ nativeModelOf,
63
+ offered
64
+ };