@anhlp/alp-runtime 0.0.0-stage → 0.0.1-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +7 -0
  3. package/README.md +6 -2
  4. package/dist/acp-transport.d.ts +130 -0
  5. package/dist/acp-transport.js +482 -0
  6. package/dist/antigravity-transport.d.ts +107 -0
  7. package/dist/antigravity-transport.js +665 -0
  8. package/dist/assignment-results.d.ts +55 -0
  9. package/dist/assignment-results.js +181 -0
  10. package/dist/attachments.d.ts +84 -0
  11. package/dist/attachments.js +213 -0
  12. package/dist/board-domain.d.ts +56 -0
  13. package/dist/board-domain.js +157 -0
  14. package/dist/board.d.ts +27 -0
  15. package/dist/board.js +76 -0
  16. package/dist/catalog.d.ts +44 -0
  17. package/dist/catalog.js +47 -0
  18. package/dist/claude-transport.d.ts +251 -0
  19. package/dist/claude-transport.js +931 -0
  20. package/dist/compact.d.ts +29 -0
  21. package/dist/compact.js +49 -0
  22. package/dist/configure.d.ts +44 -0
  23. package/dist/configure.js +64 -0
  24. package/dist/contracts.d.ts +378 -0
  25. package/dist/contracts.js +16 -0
  26. package/dist/conversation.d.ts +45 -0
  27. package/dist/conversation.js +62 -0
  28. package/dist/events.d.ts +1 -0
  29. package/dist/events.js +0 -0
  30. package/dist/github.d.ts +10 -0
  31. package/dist/github.js +39 -0
  32. package/dist/handoff.d.ts +36 -0
  33. package/dist/handoff.js +73 -0
  34. package/dist/index.d.ts +39 -0
  35. package/dist/index.js +122 -0
  36. package/dist/input-limits.d.ts +25 -0
  37. package/dist/input-limits.js +48 -0
  38. package/dist/language.d.ts +51 -0
  39. package/dist/language.js +94 -0
  40. package/dist/live.d.ts +48 -0
  41. package/dist/live.js +50 -0
  42. package/dist/mailbox.d.ts +26 -0
  43. package/dist/mailbox.js +38 -0
  44. package/dist/mcp-tools.d.ts +123 -0
  45. package/dist/mcp-tools.js +97 -0
  46. package/dist/model-catalog.d.ts +162 -0
  47. package/dist/model-catalog.js +338 -0
  48. package/dist/model-probes.d.ts +7 -0
  49. package/dist/model-probes.js +69 -0
  50. package/dist/permission-path.d.ts +2 -0
  51. package/dist/permission-path.js +44 -0
  52. package/dist/process-info.d.ts +14 -0
  53. package/dist/process-info.js +32 -0
  54. package/dist/providers.d.ts +28 -0
  55. package/dist/providers.js +73 -0
  56. package/dist/recall.d.ts +42 -0
  57. package/dist/recall.js +61 -0
  58. package/dist/resolve.d.ts +123 -0
  59. package/dist/resolve.js +242 -0
  60. package/dist/runtime-context.d.ts +43 -0
  61. package/dist/runtime-context.js +61 -0
  62. package/dist/runtime.d.ts +13 -0
  63. package/dist/runtime.js +4818 -0
  64. package/dist/session-config.d.ts +2345 -0
  65. package/dist/session-config.js +209 -0
  66. package/dist/session-state.d.ts +190 -0
  67. package/dist/session-state.js +0 -0
  68. package/dist/skill-resources.d.ts +30 -0
  69. package/dist/skill-resources.js +55 -0
  70. package/dist/tool-detail.d.ts +81 -0
  71. package/dist/tool-detail.js +332 -0
  72. package/dist/tool-results.d.ts +12 -0
  73. package/dist/tool-results.js +25 -0
  74. package/dist/tools.d.ts +827 -0
  75. package/dist/tools.js +463 -0
  76. package/dist/transport.d.ts +47 -0
  77. package/dist/transport.js +171 -0
  78. package/dist/usage.d.ts +25 -0
  79. package/dist/usage.js +60 -0
  80. package/dist/workspace.d.ts +127 -0
  81. package/dist/workspace.js +340 -0
  82. package/dist/worktree-domain.d.ts +89 -0
  83. package/dist/worktree-domain.js +199 -0
  84. package/dist/write-error.d.ts +2 -0
  85. package/dist/write-error.js +10 -0
  86. package/package.json +262 -4
  87. package/src/acp-transport.ts +481 -0
  88. package/src/antigravity-transport.ts +740 -0
  89. package/src/assignment-results.ts +154 -0
  90. package/src/attachments.ts +254 -0
  91. package/src/board-domain.ts +185 -0
  92. package/src/board.ts +87 -0
  93. package/src/catalog.ts +43 -0
  94. package/src/claude-transport.ts +1097 -0
  95. package/src/compact.ts +62 -0
  96. package/src/configure.ts +93 -0
  97. package/src/contracts.ts +363 -0
  98. package/src/conversation.ts +81 -0
  99. package/src/events.ts +1 -0
  100. package/src/github.ts +37 -0
  101. package/src/handoff.ts +86 -0
  102. package/src/index.ts +41 -0
  103. package/src/input-limits.ts +65 -0
  104. package/src/language.ts +130 -0
  105. package/src/live.ts +90 -0
  106. package/src/mailbox.ts +49 -0
  107. package/src/mcp-tools.ts +106 -0
  108. package/src/model-catalog.ts +316 -0
  109. package/src/model-probes.ts +58 -0
  110. package/src/permission-path.ts +37 -0
  111. package/src/process-info.ts +40 -0
  112. package/src/providers.ts +87 -0
  113. package/src/recall.ts +86 -0
  114. package/src/resolve.ts +238 -0
  115. package/src/runtime-context.ts +49 -0
  116. package/src/runtime.ts +5608 -0
  117. package/src/session-config.ts +312 -0
  118. package/src/session-state.ts +180 -0
  119. package/src/skill-resources.ts +73 -0
  120. package/src/tool-detail.ts +397 -0
  121. package/src/tool-results.ts +26 -0
  122. package/src/tools.ts +466 -0
  123. package/src/transport.ts +118 -0
  124. package/src/usage.ts +79 -0
  125. package/src/workspace.ts +424 -0
  126. package/src/worktree-domain.ts +220 -0
  127. package/src/write-error.ts +4 -0
@@ -0,0 +1,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
+ };
@@ -0,0 +1,378 @@
1
+ import type { ProviderFactories, ProviderRegistry } from './providers.js';
2
+ import type { RuntimeKind, SessionSpec } from './resolve.js';
3
+ import type { Envelope, SessionSnapshot, TreeStatus, UserQuestion } from './events.js';
4
+ import type { Pin } from './board.js';
5
+ import type { LiveEntry } from './live.js';
6
+ import type { ProviderUsage } from './usage.js';
7
+ import type { AcpProvider } from './acp-transport.js';
8
+ import type { AntigravityProvider } from './antigravity-transport.js';
9
+ import type { GitHubRunner } from './github.js';
10
+ import type { AttachmentReader } from './attachments.js';
11
+ /** A slash command or skill an agent's composer offers after "/" (t-f628). */
12
+ export type RuntimeCommand = {
13
+ name: string;
14
+ description: string;
15
+ argumentHint?: string;
16
+ kind: 'command' | 'skill';
17
+ };
18
+ export type RuntimeTransport = {
19
+ request(method: string, params: any): Promise<any>;
20
+ initialize(): Promise<void>;
21
+ orchestrationContext?: () => Promise<unknown>;
22
+ /** The runtime's own slash commands and skills for the composer (t-f628); omitted, the runtime offers none. */
23
+ commands?: () => Promise<RuntimeCommand[]>;
24
+ /** Claude: the aliases of /clear (new, reset) that run a command of the user's, so they are not refused (t-5ac5). */
25
+ customCommands?: () => ReadonlySet<string>;
26
+ onNotification(listener: (method: string, params: any) => void): void;
27
+ onFailure(listener: (error: unknown) => void): void;
28
+ close(): Promise<void>;
29
+ onRequest?: (listener: (method: string, params: any) => Promise<unknown>) => void;
30
+ /** Whether turn input may hold images (`{ type: 'image', url: 'data:…' }`); omitted, Codex and Claude do. */
31
+ takesImages?: () => boolean;
32
+ };
33
+ export type RuntimeOptions = {
34
+ /** Native adapter overrides, isolated to this runtime; the legacy transport hook takes precedence. */
35
+ providers?: ProviderFactories;
36
+ /** An explicit registry, including custom adapter factories registered by the host. */
37
+ providerRegistry?: ProviderRegistry;
38
+ codexCommand?: string;
39
+ claudeCommand?: string;
40
+ antigravityCommand?: string;
41
+ environment?: NodeJS.ProcessEnv;
42
+ /**
43
+ * Optional transport factory for tests/custom runtimes.
44
+ * When omitted, ALP creates CodexTransport, ClaudeTransport, or AntigravityTransport itself.
45
+ */
46
+ transport?: (cwd: string, env: NodeJS.ProcessEnv, runtime?: RuntimeKind,
47
+ /** The ACP provider, when runtime is acp. */
48
+ acp?: AcpProvider,
49
+ /** The Antigravity provider, when runtime is antigravity. */
50
+ antigravity?: AntigravityProvider) => RuntimeTransport;
51
+ /** An assignment with no activity this long is reported stalled; twice this long, it fails. */
52
+ silentForMs?: number;
53
+ /** How often main gets a check-in on its running assignments. Default 10 minutes; 0 turns it off. */
54
+ checkInMs?: number;
55
+ /** How often the watchdog looks at running assignments; derived from silentForMs and checkInMs when omitted. */
56
+ watchMs?: number;
57
+ /** How often the project tasks are read for gate changes made without alpd, in ms; 0 turns the timer off. Default 5000. */
58
+ gateSyncMs?: number;
59
+ /** How long alp_ask waits for the requester before returning unanswered. */
60
+ askTimeoutMs?: number;
61
+ /** How long alp_ask waits for the user before returning unanswered. Default 30 minutes. */
62
+ userAskTimeoutMs?: number;
63
+ /** Directory for per-root-session assignment logs (JSONL). Omitted disables logging. */
64
+ runLogDir?: string;
65
+ /** Starter files for projects without ALP; omitted reads the repository templates. */
66
+ templates?: Record<string, string>;
67
+ /** Where isolated assignments get their git worktrees. Default: a directory in the temp directory. */
68
+ worktreeDir?: string;
69
+ /** Where assignments whose profile has workdir copy get their disposable copies. Default: a directory in the temp directory. */
70
+ copyDir?: string;
71
+ /**
72
+ * Where the runtime stages read-only copies of attached files for its sessions' tools (§12.6):
73
+ * alpd's `<ALP_HOME>/state/staged`. Omitted, no session takes attachment parts.
74
+ */
75
+ attachmentStageDir?: string;
76
+ /** Where project boards are kept (JSONL per project). Omitted keeps them in memory only. */
77
+ boardDir?: string;
78
+ /** The user's skill library and lessons (ALP_HOME). Omitted: only skills inside the project, and project lessons. */
79
+ libraryDir?: string;
80
+ /** The language the user reads; omitted, their settings.json's language, else Vietnamese (ALPD §54). */
81
+ language?: string;
82
+ /** Where finished assignments' native threads are recorded for alp_recall. Omitted keeps the record in memory. */
83
+ recallFile?: string;
84
+ /** Permanent assignment ownership; unlike recall, results never expire. */
85
+ assignmentResultFile?: string;
86
+ /** Where pauses are kept across restarts. Omitted keeps them in memory. */
87
+ pauseFile?: string;
88
+ /**
89
+ * Resume a runtime a usage limit paused as soon as the runtime says the limit lifted
90
+ * (ALPD §58). Default true; false tells the user instead, who resumes it.
91
+ */
92
+ autoResume?: boolean;
93
+ /** How often alpd asks a runtime a usage limit paused whether the limit lifted. Default LIMIT_CHECK_MS. */
94
+ limitCheckMs?: number;
95
+ /** Where running assignments are kept, so the next alpd continues them (ALPD §31). Omitted keeps them in memory. */
96
+ liveFile?: string;
97
+ /**
98
+ * Told of every failed write to pauseFile, liveFile, recallFile and assignmentResultFile, as it
99
+ * happens, so the host's disk guard pauses work on a full disk at once (t-e80a). Each write still
100
+ * fails as before: pauses and recall go on in memory, live entries are logged, and result
101
+ * ownership is refused to its caller.
102
+ */
103
+ onWriteError?: (error: unknown) => void;
104
+ /** False parks assignments an earlier alpd left running until the user runs alp resume. Default true: they continue. */
105
+ recoveryResume?: boolean;
106
+ /** How the previous alpd ended, for what recovered sessions are told. */
107
+ previousExit?: {
108
+ kind: 'clean' | 'crash';
109
+ at?: string;
110
+ };
111
+ /** False starts no supervisors, for hosts and tests that do not want them. Default true. */
112
+ supervisor?: boolean;
113
+ /** Runs the GitHub CLI for alp_issue. Default: `gh` (or ALP_GH_BIN) on PATH. */
114
+ github?: GitHubRunner;
115
+ };
116
+ import type { NativeBase, OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
117
+ export type { NativeBase, OpenOptions, PromptContent, PromptInput } from '@anhlp/alp-protocol/session';
118
+ export type ScheduleHandler = (action: 'create' | 'list' | 'get' | 'cancel', params: Record<string, unknown>) => Promise<unknown>;
119
+ export type AlpRuntime = {
120
+ /** The daemon supplies its persistent schedule operations; standalone runtimes have none. */
121
+ bindSchedules?: (handler: ScheduleHandler | undefined) => void;
122
+ /** alpd hands over its attachment reader (§12.6) once, at start; with a staging directory, Codex and Claude sessions then take attachment parts. */
123
+ bindAttachments?: (reader: AttachmentReader | undefined) => void;
124
+ /** Whether this live session's runtime takes `{ type: 'attachment' }` parts (RuntimeAttachment) now. */
125
+ takesAttachments?: (sessionId: string) => boolean;
126
+ /** Why this live session's runtime refuses this prompt before it is sent (t-e906), or undefined. */
127
+ refusesPrompt?: (sessionId: string, content: PromptContent) => string | undefined;
128
+ /** Removes the staged copy of an attachment alpd no longer keeps. */
129
+ dropAttachment?: (attachmentId: string) => Promise<void>;
130
+ onEvent(listener: (envelope: Envelope) => void): () => void;
131
+ /** Certifies a brand-new generated checkout; never use to adopt an existing workspace. */
132
+ registerWorkspace(directory: string): Promise<void>;
133
+ /** Reserves runtime admission while an external checkout mutation runs. */
134
+ withWorkspaceMutation<T>(directory: string, run: () => Promise<T>): Promise<T>;
135
+ /**
136
+ * Owner-audited adoption of a checkout that predates birth certification (t-c1ba). Under the
137
+ * removal guard's reservation and ownership checks, `verify` must prove the checkout's identity
138
+ * (it throws otherwise); only then is the canonical directory certified. Never call it without
139
+ * the owner's explicit confirmation of the facts `verify` checks.
140
+ */
141
+ adoptWorkspace?(directory: string, verify: (canonical: string) => Promise<void>): Promise<void>;
142
+ /** Opens a root session under a client-chosen id. */
143
+ open(sessionId: string, spec: SessionSpec, options?: OpenOptions): Promise<SessionSnapshot>;
144
+ /** What a new root would run as, before it opens, and the teams it may choose (ALPD §60). */
145
+ preview(spec: SessionSpec): Promise<SessionPreview>;
146
+ /** Failures are reported as prompt.failed, once per clientMessageId. */
147
+ prompt(sessionId: string, input: PromptInput): Promise<void>;
148
+ /**
149
+ * Atomically admits an idle scheduled prompt in the runtime queue. Busy leaves all preparation
150
+ * untouched. The callback may persist its attempt/receipt, then use its single-use sender;
151
+ * the sender is valid only during the callback. Do not enqueue runtime operations in the callback.
152
+ */
153
+ withIdlePrompt?<T>(sessionId: string, run: (send: (input: PromptInput) => Promise<void>) => Promise<T>): Promise<{
154
+ busy: true;
155
+ } | {
156
+ busy: false;
157
+ value: T;
158
+ }>;
159
+ /** Cancels the running turn and closes the whole subtree. */
160
+ interrupt(sessionId: string): Promise<void>;
161
+ /** Atomically cancels only this active turn; false leaves the session and subtree untouched. */
162
+ interruptTurn?(sessionId: string, turnId: string): Promise<boolean>;
163
+ /** Changes permission mode while idle; undefined keeps the current mode.
164
+ * onApplied is awaited after apply and before session.updated; failure does not roll back permissions. */
165
+ configure(sessionId: string, changes: {
166
+ mode?: string;
167
+ }, options?: {
168
+ onApplied?: (session: SessionSnapshot) => Promise<void>;
169
+ }): Promise<SessionSnapshot>;
170
+ close(sessionId: string): Promise<void>;
171
+ snapshot(sessionId: string): SessionSnapshot | undefined;
172
+ /** Live sessions, roots before their children. */
173
+ list(): SessionSnapshot[];
174
+ /** The live tree containing a session: sessions, assignments, questions, worktrees and leases. */
175
+ status(sessionId: string): TreeStatus | undefined;
176
+ /** Questions agents asked the user that wait for an answer. */
177
+ questions(): UserQuestion[];
178
+ /**
179
+ * Answers or dismisses a question to the user. A gate card's answer returns a promise that
180
+ * settles once the decision is written, and rejects when it decides nothing: another answer is
181
+ * being recorded or another channel decided first (code GATE_BUSY or GATE_DECIDED), or the
182
+ * write failed (t-595d).
183
+ */
184
+ answer(questionId: string, reply: {
185
+ text?: string;
186
+ dismiss?: boolean;
187
+ reason?: string; /** Where the user answered a gate card: paseo or web. */
188
+ channel?: 'paseo' | 'web';
189
+ }): void | Promise<void>;
190
+ /** Mirrors the project's open human gates as cards on its main session and tells main of the user's gate decisions, at least once each (t-ccac, t-595d). */
191
+ syncGates?(projectRoot: string): Promise<void>;
192
+ /** Mails a note from the user to any live session, such as an assignment the user wants to redirect. */
193
+ message(sessionId: string, text: string): void;
194
+ /** The project board: live claims, then decisions and findings, oldest first. */
195
+ board(projectRoot: string): Promise<Pin[]>;
196
+ /** Holds delegation and wakes on one runtime, or all; now also parks running assignments there. */
197
+ pause(input?: {
198
+ runtime?: RuntimeKind;
199
+ now?: boolean;
200
+ reason?: string;
201
+ }): PauseState;
202
+ /** Lifts a pause and continues the assignments it parked. Without a runtime, lifts every pause. */
203
+ resume(input?: {
204
+ runtime?: RuntimeKind;
205
+ }): PauseState;
206
+ /** alpd's disk takes no writes (t-2831): pauses all of ALP and parks running assignments, unless all of ALP is paused already. */
207
+ holdForDisk(reason: string): PauseState;
208
+ /** Lifts the pause holdForDisk made, keeping usage-limit pauses; a pause the user made stays. */
209
+ releaseDisk(by: string): PauseState;
210
+ /** Whether alpd's disk pause holds ALP now. */
211
+ diskHeld(): boolean;
212
+ /** Tells every open root that disk space runs low. */
213
+ diskLow(free: string): void;
214
+ /** Current pauses and parked assignments. */
215
+ pauses(): PauseState;
216
+ /** Read-only, cached account usage for the web and desktop viewers. */
217
+ usage(refresh?: boolean): Promise<{
218
+ providers: Array<ProviderUsage & {
219
+ pause: Pause | null;
220
+ parked: number;
221
+ }>;
222
+ }>;
223
+ /** The user asks a finished assignment, or the last one on a task of the project, about its work. */
224
+ recall(target: {
225
+ assignmentId?: string;
226
+ taskId?: string;
227
+ projectRoot?: string;
228
+ }, question: string): Promise<RecallAnswer>;
229
+ /** Assignments an earlier alpd left running, which recover() can continue once their root is open again. */
230
+ recoverable(): LiveEntry[];
231
+ /** Continues work in a reopened tree. continueRoot resumes its running turn; parkedRoot restores its held continuation intent. */
232
+ recover(rootId: string, options?: {
233
+ continueRoot?: boolean;
234
+ parkedRoot?: string;
235
+ }): Promise<RecoveryOutcome[]>;
236
+ /** Gives up the assignments of a tree whose root cannot be opened again: their tasks go back to open. */
237
+ abandon(rootId: string, reason: string): Promise<RecoveryOutcome[]>;
238
+ /** Closes everything; assignments still running stay in the live file, so the next alpd continues them. */
239
+ shutdown(): Promise<void>;
240
+ /**
241
+ * Makes the native conversation a fork or rewind continues (docs/protocol/alp-json-rpc-v1.md §12.7): the
242
+ * source's conversation cut at a completed turn, persisted by the runtime and leaving the source
243
+ * unchanged. Touches no live session. Codex forks natively now (thread/fork); Claude validates the
244
+ * cut against the transcript and answers a binding the first prompt forks (NativeBinding.base).
245
+ * Refusals throw a ConversationError; one the runtime may or may not have acted on carries
246
+ * `outcomeUnknown: true`. Absent: the host cannot fork or rewind.
247
+ */
248
+ branch?(request: BranchRequest): Promise<NativeBinding>;
249
+ /**
250
+ * Moves an idle live root to another native conversation (a rewind), or reopens its own (a reload):
251
+ * its native process restarts and resumes `binding`, keeping the session id, its configuration and
252
+ * attached viewers. Refused (ConversationError session_busy) unless the whole tree is idle: no turn,
253
+ * pending prompt, child, assignment, question, mail or parked work. Emits session.updated.
254
+ * When the new binding cannot be opened, the old one is reopened and the error thrown; when neither
255
+ * opens, the session fails as a provider failure does.
256
+ */
257
+ rebind?(sessionId: string, binding: NativeBinding): Promise<SessionSnapshot>;
258
+ /**
259
+ * Restarts an idle live root's native process on the conversation it runs now (a reload, §12.8):
260
+ * the same binding, the session's own configuration, id and viewers. Refused as rebind is. The new
261
+ * process must resume that very conversation (a Claude one is refused unless its transcript, or its
262
+ * base, exists), never an empty one in its place; when it cannot, the session closes with its
263
+ * conversation kept (a later open resumes it) and a ConversationError native_refused is thrown.
264
+ * Emits session.updated.
265
+ */
266
+ reload?(sessionId: string): Promise<SessionSnapshot>;
267
+ /** Compacts a root's context at its next turn boundary, with a checkpoint main writes by skill compact (t-0e56). */
268
+ compact?(sessionId: string): {
269
+ status: 'started' | 'deferred' | 'running';
270
+ };
271
+ /** The slash commands and skills a live session's composer offers (t-f628): its runtime's, then its ALP skills. */
272
+ commands?(sessionId: string): Promise<RuntimeCommand[]>;
273
+ /**
274
+ * Holds the turns the runtime would start by itself on this session (mail wakes) while a lifecycle
275
+ * operation changes its conversation (a rewind, later a reload or live configure): mail stays queued
276
+ * and is delivered when the last hold is released, to whatever conversation the session runs then.
277
+ * rebind does not refuse for mail a hold keeps. Client prompts are not held here; alpd holds them.
278
+ * Undefined when the session is not open.
279
+ */
280
+ hold?(sessionId: string): (() => void) | undefined;
281
+ /**
282
+ * Whether an open session may begin a turn it has no id for yet: its turn/start (a prompt or a mail
283
+ * wake) is reserved, queued or on its way to the native runtime, or its process is opening or restarting. Such a
284
+ * turn shows in `activeTurnId` only once the runtime answers, and a hold taken meanwhile does not
285
+ * stop it. False when the session is not open.
286
+ */
287
+ starting?(sessionId: string): boolean;
288
+ /**
289
+ * What a live root would run with after a change of model, thinking, team or mode (§12.9), and whether
290
+ * reconfigure would take it now; reads only. `teams` are the teams the host defines for its project.
291
+ */
292
+ previewConfigure?(sessionId: string, changes: ConfigureChanges): Promise<ConfigurePreview>;
293
+ /**
294
+ * Changes an idle live root's model, thinking, team or mode (§12.9): resolves the new configuration
295
+ * as session.create would (same runtime, agent and conversation; never more permissions or new
296
+ * executable resources), then restarts its native process with it on the same conversation (`fresh`:
297
+ * a root with no turn yet starts a new, empty one). The session takes the new configuration only
298
+ * once the runtime took it (Codex echoes the model it resumed with); otherwise the old one is
299
+ * restarted and a ConversationError thrown (`outcomeUnknown` when the runtime may have acted). A
300
+ * new team also replaces the root's supervisor. Refused as rebind is while the tree is not idle.
301
+ * `onApplied` lets a host persist the configuration the runtime took before session.updated is
302
+ * emitted. It is awaited only for an applied change; its failure leaves the runtime configured
303
+ * and reports outcomeUnknown (never a rollback or a known native refusal).
304
+ * Emits session.updated after that persistence succeeds.
305
+ */
306
+ reconfigure?(sessionId: string, changes: ConfigureChanges, options?: {
307
+ fresh?: boolean;
308
+ onApplied?: (result: ConfigureResult) => Promise<void>;
309
+ }): Promise<ConfigureResult>;
310
+ };
311
+ import type { ConfigureChanges, EffectiveConfig } from './configure.js';
312
+ export type { ConfigureChanges, EffectiveConfig } from './configure.js';
313
+ import type { ConfigurePreview } from '@anhlp/alp-protocol/session';
314
+ export type { ConfigurePreview } from '@anhlp/alp-protocol/session';
315
+ /** What reconfigure did: the session as it runs now, its effective configuration, and whether its process restarted. */
316
+ export type ConfigureResult = {
317
+ session: SessionSnapshot;
318
+ effective: EffectiveConfig;
319
+ status: 'applied' | 'unchanged';
320
+ restarted: boolean;
321
+ /** What the native runtime answered it runs with (Codex: the resumed thread's model and effort). */
322
+ native?: {
323
+ model?: string;
324
+ reasoningEffort?: string;
325
+ };
326
+ };
327
+ /** The native conversation a session continues: its thread, or for Claude one its first prompt makes from `base`. */
328
+ export type NativeBinding = {
329
+ threadId: string;
330
+ base?: NativeBase;
331
+ };
332
+ export type BranchRequest = {
333
+ runtime: RuntimeKind;
334
+ /** The conversation to branch: the source session's binding. */
335
+ source: NativeBinding;
336
+ /** Where the source session runs (Claude keeps its transcripts by this directory). */
337
+ cwd: string;
338
+ /** Where the branch will run; the source's cwd when absent. */
339
+ targetCwd?: string;
340
+ /** The configuration the branch keeps: Codex otherwise forks with its default model and settings. */
341
+ model: string;
342
+ thinking: string;
343
+ mode: string;
344
+ /**
345
+ * The cut, by ALP turn id (a Codex turn id; a Claude prompt uuid): keep through a completed turn, or
346
+ * everything before a turn. Absent: the whole conversation.
347
+ */
348
+ cutoff?: {
349
+ throughTurnId: string;
350
+ } | {
351
+ beforeTurnId: string;
352
+ };
353
+ /** The source root's turns in order, as ALP's timeline has them, for the cut's validation. */
354
+ turns: string[];
355
+ };
356
+ export type ConversationErrorReason = 'runtime_unsupported' | 'boundary_unmapped' | 'empty_prefix' | 'native_refused' | 'session_busy' | 'runtime_mismatch' | 'agent_mismatch' | 'permission_escalation' | 'team_not_found' | 'invalid_params' | 'not_root';
357
+ /** A fork, rewind or rebind the runtime refused; `outcomeUnknown` when the native runtime may have acted. */
358
+ export declare class ConversationError extends Error {
359
+ readonly data: {
360
+ reason: ConversationErrorReason;
361
+ };
362
+ readonly outcomeUnknown: boolean;
363
+ constructor(reason: ConversationErrorReason, message: string, { outcomeUnknown }?: {
364
+ outcomeUnknown?: boolean | undefined;
365
+ });
366
+ }
367
+ import type { SessionPreview } from '@anhlp/alp-protocol/session';
368
+ export type { SessionPreview } from '@anhlp/alp-protocol/session';
369
+ /**
370
+ * The team `alp init` names in a new project's settings (core INIT_TEAM). Kept for compatibility;
371
+ * it is not the default of a session: preview and create both resolve that through core
372
+ * `defaultTeam` (settings without workflow.mode run `custom`).
373
+ */
374
+ export { INIT_TEAM as DEFAULT_TEAM } from '@anhlp/alp-core/workflow';
375
+ import type { RecoveryOutcome, Pause, PauseState } from '@anhlp/alp-protocol/session';
376
+ export type { RecoveryOutcome, Pause, PauseState } from '@anhlp/alp-protocol/session';
377
+ import type { RecallAnswer } from '@anhlp/alp-protocol/session';
378
+ export type { RecallAnswer } from '@anhlp/alp-protocol/session';
@@ -0,0 +1,16 @@
1
+ // packages/runtime/src/contracts.ts
2
+ import { INIT_TEAM } from "@anhlp/alp-core/workflow";
3
+ var ConversationError = class extends Error {
4
+ data;
5
+ outcomeUnknown;
6
+ constructor(reason, message, { outcomeUnknown = false } = {}) {
7
+ super(message);
8
+ this.name = "ConversationError";
9
+ this.data = { reason };
10
+ this.outcomeUnknown = outcomeUnknown;
11
+ }
12
+ };
13
+ export {
14
+ ConversationError,
15
+ INIT_TEAM as DEFAULT_TEAM
16
+ };
@@ -0,0 +1,45 @@
1
+ import { ConversationError, type BranchRequest } from './contracts.js';
2
+ /**
3
+ * Conversation cuts for fork and rewind (docs/protocol/alp-json-rpc-v1.md §12.7). Pure helpers of
4
+ * runtime.ts's branch(): where a Claude transcript is cut, which Codex turn a fork must end at, and
5
+ * what a Codex refusal means.
6
+ */
7
+ /** One entry of a Claude session's main chain, as the Agent SDK reads it from the transcript. */
8
+ export type ChainEntry = {
9
+ uuid: string;
10
+ type: 'user' | 'assistant';
11
+ toolResult?: boolean;
12
+ };
13
+ /** The turn a Codex fork must end at, after ALP's own validation of the cut against its timeline. */
14
+ export declare function codexForkEnd(request: Pick<BranchRequest, 'cutoff' | 'turns'>): {
15
+ last: string;
16
+ params: {
17
+ beforeTurnId?: undefined;
18
+ lastTurnId?: undefined;
19
+ };
20
+ } | {
21
+ last: string;
22
+ params: {
23
+ beforeTurnId: string;
24
+ lastTurnId?: undefined;
25
+ };
26
+ } | {
27
+ last: string;
28
+ params: {
29
+ lastTurnId: string;
30
+ beforeTurnId?: undefined;
31
+ };
32
+ };
33
+ /** What a refused thread/fork means; one written but unanswered may have forked. */
34
+ export declare function codexForkRefusal(error: unknown): ConversationError;
35
+ /**
36
+ * The chain uuid a Claude fork resumes at (`resumeSessionAt`): the last entry kept. ALP turn ids are
37
+ * the prompt uuids it gave Claude, so a turn starts at its prompt entry and runs to the next ALP turn's
38
+ * prompt; entries of a turn Claude started itself belong to the turn before it. Always a pinned entry,
39
+ * never "everything", so turns the source adds later never reach a branch made before them.
40
+ */
41
+ export declare function claudeCut(chain: ChainEntry[], request: Pick<BranchRequest, 'cutoff' | 'turns'>): string;
42
+ /** The chain a binding stands for: a pending fork is its base cut at `at`, until its first prompt makes it. */
43
+ export declare function pendingChain(base: {
44
+ at?: string;
45
+ }, chain: ChainEntry[]): ChainEntry[];