@anhlp/alp-daemon 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 (104) hide show
  1. package/README.md +4 -0
  2. package/dist/THIRD-PARTY-NOTICES.txt +27 -2
  3. package/dist/alpd.js +39374 -17503
  4. package/dist/attachments.d.ts +187 -0
  5. package/dist/attachments.js +856 -0
  6. package/dist/build-manifest.json +41 -2
  7. package/dist/conversation.d.ts +119 -0
  8. package/dist/conversation.js +688 -0
  9. package/dist/disk.d.ts +67 -0
  10. package/dist/disk.js +152 -0
  11. package/dist/files.d.ts +156 -3
  12. package/dist/files.js +402 -59
  13. package/dist/git.d.ts +98 -0
  14. package/dist/git.js +1246 -0
  15. package/dist/gitignore.d.ts +5 -0
  16. package/dist/gitignore.js +26 -7
  17. package/dist/history.d.ts +24 -0
  18. package/dist/history.js +149 -0
  19. package/dist/index.d.ts +7 -0
  20. package/dist/index.js +21 -1
  21. package/dist/lifecycle.d.ts +101 -0
  22. package/dist/lifecycle.js +239 -0
  23. package/dist/main.js +146 -21
  24. package/dist/model-catalog.d.ts +2 -0
  25. package/dist/model-catalog.js +44 -0
  26. package/dist/native-entry.d.ts +2 -0
  27. package/dist/native-entry.js +3 -0
  28. package/dist/native-register.d.ts +1 -0
  29. package/dist/native-register.js +13 -0
  30. package/dist/native-terminal.d.ts +45 -0
  31. package/dist/native-terminal.js +201 -0
  32. package/dist/operations.d.ts +20 -3
  33. package/dist/operations.js +62 -21
  34. package/dist/registry.d.ts +89 -0
  35. package/dist/registry.js +343 -0
  36. package/dist/scheduler.d.ts +96 -0
  37. package/dist/scheduler.js +298 -0
  38. package/dist/schedules.d.ts +70 -0
  39. package/dist/schedules.js +246 -0
  40. package/dist/server.d.ts +14 -2
  41. package/dist/server.js +903 -97
  42. package/dist/store.d.ts +72 -2
  43. package/dist/store.js +111 -4
  44. package/dist/terminal-native/README.md +201 -0
  45. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  46. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  47. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  48. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  49. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  50. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  51. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  52. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  53. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  54. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  55. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  56. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  57. package/dist/terminal-native/terminal-owner.c +389 -0
  58. package/dist/terminal-screen.d.ts +24 -0
  59. package/dist/terminal-screen.js +99 -0
  60. package/dist/terminals.d.ts +203 -0
  61. package/dist/terminals.js +570 -0
  62. package/dist/windows-terminal.d.ts +32 -0
  63. package/dist/windows-terminal.js +79 -0
  64. package/dist/worktrees.d.ts +65 -0
  65. package/dist/worktrees.js +318 -0
  66. package/native/README.md +201 -0
  67. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  68. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  69. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  70. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  71. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  72. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  73. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  74. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  75. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  76. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  77. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  78. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  79. package/native/terminal-owner.c +389 -0
  80. package/package.json +71 -8
  81. package/src/attachments.ts +908 -0
  82. package/src/conversation.ts +857 -0
  83. package/src/disk.ts +175 -0
  84. package/src/files.ts +535 -71
  85. package/src/git.ts +1220 -0
  86. package/src/gitignore.ts +25 -8
  87. package/src/history.ts +118 -0
  88. package/src/index.ts +7 -0
  89. package/src/lifecycle.ts +283 -0
  90. package/src/main.ts +154 -23
  91. package/src/model-catalog.ts +36 -0
  92. package/src/native-entry.ts +5 -0
  93. package/src/native-register.ts +21 -0
  94. package/src/native-terminal.ts +127 -0
  95. package/src/operations.ts +53 -22
  96. package/src/registry.ts +238 -0
  97. package/src/scheduler.ts +438 -0
  98. package/src/schedules.ts +297 -0
  99. package/src/server.ts +1019 -109
  100. package/src/store.ts +117 -4
  101. package/src/terminal-screen.ts +74 -0
  102. package/src/terminals.ts +653 -0
  103. package/src/windows-terminal.ts +74 -0
  104. package/src/worktrees.ts +382 -0
@@ -0,0 +1,2 @@
1
+ import { ModelCatalog } from '@anhlp/alp-runtime/index';
2
+ export declare function createModelCatalog(home: string, warn?: (message: string) => void): ModelCatalog;
@@ -0,0 +1,44 @@
1
+ // packages/daemon/src/model-catalog.ts
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { loadProvider, listProviders } from "@anhlp/alp-core/providers";
6
+ import { probeAcp } from "@anhlp/alp-client/acp-probe";
7
+ import { antigravityProbe, liveProbes, ModelCatalog } from "@anhlp/alp-runtime/index";
8
+ function createModelCatalog(home, warn = console.error) {
9
+ let warnings = /* @__PURE__ */ new Set();
10
+ const probes = liveProbes();
11
+ probes.antigravity = async (signal) => {
12
+ const provider = await loadProvider(home, "antigravity");
13
+ if (provider?.enabled === false) return [];
14
+ return antigravityProbe(provider?.command, { ...process.env, ...provider?.env }, provider?.args)(signal);
15
+ };
16
+ return new ModelCatalog({
17
+ home,
18
+ probes,
19
+ acpProviders: async () => {
20
+ const errors = [];
21
+ const current = /* @__PURE__ */ new Set();
22
+ const providers = await listProviders(home, { onError: (error, name) => {
23
+ const message = `skipping provider ${name}: ${error instanceof Error ? error.message : String(error)}`;
24
+ errors.push(message);
25
+ current.add(message);
26
+ if (!warnings.has(message)) warn(`alpd: ${message}`);
27
+ } });
28
+ warnings = current;
29
+ return { providers, ...errors.length ? { error: errors.join("\n") } : {} };
30
+ },
31
+ acpProbe: async (provider, signal) => {
32
+ signal.throwIfAborted();
33
+ const cwd = await mkdtemp(path.join(os.tmpdir(), "alp-model-probe-"));
34
+ try {
35
+ return (await probeAcp(provider, { cwd, signal, discover: true, timeoutMs: 15e3 })).models ?? [];
36
+ } finally {
37
+ await rm(cwd, { recursive: true, force: true });
38
+ }
39
+ }
40
+ });
41
+ }
42
+ export {
43
+ createModelCatalog
44
+ };
@@ -0,0 +1,2 @@
1
+ import './native-register.js';
2
+ import './main.js';
@@ -0,0 +1,3 @@
1
+ // packages/daemon/src/native-entry.ts
2
+ import "./native-register.js";
3
+ import "./main.js";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ // packages/daemon/src/native-register.ts
2
+ import { bundleDist, bundleInfo, registerNativeDaemon } from "@anhlp/alp-core/packaged";
3
+ if (process.argv.length === 3 && process.argv[2] === "--version") {
4
+ process.stdout.write(`${true ? "0.0.1-beta.10" : "0.0.0-dev"}
5
+ `);
6
+ process.exit(0);
7
+ }
8
+ var bundle = bundleInfo();
9
+ registerNativeDaemon({
10
+ modules: { claudeAgentSdk: () => import("@anthropic-ai/claude-agent-sdk") },
11
+ // The terminal helper (native-terminal.ts) lies in the bundle's @anhlp/alp-cli dist, not beside alpd.
12
+ distDir: () => bundle ? bundleDist(bundle) : void 0
13
+ });
@@ -0,0 +1,45 @@
1
+ export type CleanupResult = {
2
+ observed: number;
3
+ live: number;
4
+ uncertain: number;
5
+ coverage?: 'root-only';
6
+ outputOpen?: boolean;
7
+ };
8
+ type Exit = {
9
+ exitCode: number | null;
10
+ signal?: number;
11
+ };
12
+ type Listener<T> = (event: T) => void;
13
+ /** Only an authenticated helper's exact capability record can select compatibility. */
14
+ export declare function nativeCapabilityOf(probe: {
15
+ status: number | null;
16
+ stdout: string;
17
+ }, platform: NodeJS.Platform): {
18
+ available: boolean;
19
+ protection?: 'root-only';
20
+ reason?: string;
21
+ };
22
+ export declare function nativeTerminalCapability(): ReturnType<typeof nativeCapabilityOf>;
23
+ export declare function nativePtySpawn(file: string, args: string[], options: {
24
+ name: string;
25
+ cols: number;
26
+ rows: number;
27
+ cwd: string;
28
+ env: Record<string, string>;
29
+ killGraceMs?: number;
30
+ signal?: AbortSignal;
31
+ protection?: 'root-only' | 'none';
32
+ }): Promise<{
33
+ pid: number;
34
+ write(value: string): void;
35
+ resize(cols: number, rows: number): void;
36
+ kill(): void;
37
+ cleanup(): Promise<CleanupResult>;
38
+ onData(listener: Listener<string>): {
39
+ dispose(): void;
40
+ };
41
+ onExit(listener: Listener<Exit>): {
42
+ dispose(): void;
43
+ };
44
+ }>;
45
+ export {};
@@ -0,0 +1,201 @@
1
+ // packages/daemon/src/native-terminal.ts
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { existsSync, readFileSync, statSync } from "node:fs";
5
+ import { fileURLToPath } from "node:url";
6
+ import path from "node:path";
7
+ import { StringDecoder } from "node:string_decoder";
8
+ var sha = (value) => createHash("sha256").update(value).digest("hex");
9
+ function binary() {
10
+ const libc = process.platform === "linux" ? process.report?.getReport()?.header?.glibcVersionRuntime ? "glibc" : "musl" : void 0;
11
+ const slot = [process.platform, process.arch, libc].filter(Boolean).join("-");
12
+ const native = globalThis[Symbol.for("alp.nativeDaemon")];
13
+ const bundled = native?.distDir?.();
14
+ if (native && !bundled) throw new Error("The native alpd runs outside an ALP bundle: no terminal helper");
15
+ const here = bundled ?? path.dirname(fileURLToPath(import.meta.url));
16
+ const adjacent = path.join(here, "terminal-native");
17
+ const dir = existsSync(adjacent) || bundled ? adjacent : path.resolve(here, "../native");
18
+ const file = path.join(dir, "prebuilt", slot, "terminal-owner");
19
+ const manifest = JSON.parse(readFileSync(path.join(path.dirname(file), "manifest.json"), "utf8"));
20
+ if (!statSync(file).isFile() || manifest.protocol !== 1 || manifest.slot !== slot || manifest.source !== sha(readFileSync(path.join(dir, "terminal-owner.c"))) || manifest.sha256 !== sha(readFileSync(file))) throw new Error("Native helper manifest mismatch");
21
+ return file;
22
+ }
23
+ function nativeCapabilityOf(probe, platform) {
24
+ if (probe.status === 0 && probe.stdout.trim() === "alp-terminal-owner:1") return { available: true };
25
+ if (platform === "linux" && probe.status === 0 && probe.stdout.trim() === "alp-terminal-owner:1:root-only") return { available: true, protection: "root-only", reason: "bound_signal_unavailable" };
26
+ return { available: false, reason: "native_capability_unavailable" };
27
+ }
28
+ function nativeTerminalCapability() {
29
+ try {
30
+ const probe = spawnSync(binary(), ["--capability"], { encoding: "utf8", timeout: 2e3, maxBuffer: 4096 });
31
+ return nativeCapabilityOf(probe, process.platform);
32
+ } catch {
33
+ return { available: false, reason: "native_prebuilt_unavailable" };
34
+ }
35
+ }
36
+ async function nativePtySpawn(file, args, options) {
37
+ if (options.signal?.aborted) throw new Error("Native terminal startup cancelled");
38
+ const child = spawn(binary(), [...options.protection === "root-only" ? ["--root-only"] : [], String(options.cols), String(options.rows), String(options.killGraceMs ?? 1e3), options.cwd, file, ...args], { env: options.env, stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"] });
39
+ const control = child.stdio[4];
40
+ const events = child.stdio[3];
41
+ const data = /* @__PURE__ */ new Set(), exits = /* @__PURE__ */ new Set();
42
+ const decoder = new StringDecoder("utf8");
43
+ let buffered = "", protocol = "", exit, pid = 0;
44
+ let readyResolve, readyReject, finish;
45
+ const ready = new Promise((resolve, reject) => {
46
+ readyResolve = resolve;
47
+ readyReject = reject;
48
+ });
49
+ const finished = new Promise((resolve) => {
50
+ finish = resolve;
51
+ });
52
+ let result, completed = false, closing = false, adapterFailed = false;
53
+ let controlBlocked = false, pendingResize;
54
+ const resizeCommand = (command) => {
55
+ if (closing || result) return;
56
+ if (controlBlocked) {
57
+ pendingResize = command;
58
+ return;
59
+ }
60
+ controlBlocked = !control.write(command);
61
+ };
62
+ control.on("drain", () => {
63
+ controlBlocked = false;
64
+ const next = pendingResize;
65
+ pendingResize = void 0;
66
+ if (next) resizeCommand(next);
67
+ });
68
+ const closeOwner = () => {
69
+ if (closing || result) return;
70
+ closing = true;
71
+ pendingResize = void 0;
72
+ control.destroy();
73
+ child.stdin?.end();
74
+ };
75
+ const fail = (reason) => {
76
+ adapterFailed = true;
77
+ readyReject(new Error(reason));
78
+ closeOwner();
79
+ };
80
+ const timer = setTimeout(() => fail("Native terminal startup timed out"), 5e3);
81
+ const complete = (value) => {
82
+ if (!completed) {
83
+ completed = true;
84
+ result = adapterFailed ? { ...value, uncertain: Math.max(1, value.uncertain) } : value;
85
+ finish(result);
86
+ }
87
+ };
88
+ child.on("error", (error) => {
89
+ fail(error.message);
90
+ complete({ observed: 0, live: 0, uncertain: 1 });
91
+ });
92
+ child.on("close", () => {
93
+ clearTimeout(timer);
94
+ if (!pid) readyReject(new Error("Native terminal refused startup"));
95
+ exit ??= { exitCode: null };
96
+ for (const listener of exits) listener(exit);
97
+ complete(result ?? { observed: 0, live: 0, uncertain: 1 });
98
+ });
99
+ child.stderr?.resume();
100
+ child.stdin?.on("error", () => {
101
+ });
102
+ control.on("error", () => {
103
+ });
104
+ child.stdout?.on("data", (chunk) => {
105
+ const text = decoder.write(chunk);
106
+ if (data.size) for (const listener of data) listener(text);
107
+ else if (Buffer.byteLength(buffered) + Buffer.byteLength(text) <= 1024 * 1024) buffered += text;
108
+ else fail("Native terminal output limit exceeded");
109
+ });
110
+ events.on("data", (chunk) => {
111
+ protocol += chunk.toString("utf8");
112
+ if (protocol.length > 8192) {
113
+ fail("Invalid native protocol");
114
+ return;
115
+ }
116
+ let newline;
117
+ while ((newline = protocol.indexOf("\n")) >= 0) {
118
+ const line = protocol.slice(0, newline);
119
+ protocol = protocol.slice(newline + 1);
120
+ try {
121
+ const value = JSON.parse(line);
122
+ if (value.ready && value.protocol === 1 && Number.isSafeInteger(value.ready) && value.ready > 1) {
123
+ pid = value.ready;
124
+ clearTimeout(timer);
125
+ readyResolve();
126
+ } else if ("exitCode" in value) {
127
+ exit = { exitCode: value.exitCode, signal: value.signal };
128
+ } else if (value.cleanup === true && ["observed", "live", "uncertain"].every((key) => Number.isSafeInteger(value[key]) && value[key] >= 0)) result = value;
129
+ else if (value.refused === "terminal_protection_ack_required" || value.refused === "terminal_unsupported") {
130
+ readyReject(Object.assign(new Error("Native terminal capability changed before startup"), { terminalReason: value.refused }));
131
+ } else if (value.error) fail(String(value.error));
132
+ else fail("Invalid native event");
133
+ } catch {
134
+ fail("Invalid native JSON");
135
+ }
136
+ }
137
+ });
138
+ const abort = () => fail("Native terminal startup cancelled");
139
+ options.signal?.addEventListener("abort", abort, { once: true });
140
+ if (options.signal?.aborted) abort();
141
+ try {
142
+ await ready;
143
+ } catch (error) {
144
+ const cleanupResult = await finished;
145
+ throw Object.assign(error instanceof Error ? error : new Error(String(error)), { cleanupResult });
146
+ } finally {
147
+ options.signal?.removeEventListener("abort", abort);
148
+ }
149
+ return {
150
+ pid,
151
+ write(value) {
152
+ if (closing || result) return;
153
+ if ((child.stdin?.writableLength ?? 0) + Buffer.byteLength(value) > 1024 * 1024) {
154
+ fail("Native input limit exceeded");
155
+ return;
156
+ }
157
+ child.stdin?.write(value);
158
+ },
159
+ resize(cols, rows) {
160
+ if (Number.isInteger(cols) && Number.isInteger(rows) && cols > 0 && cols <= 1e3 && rows > 0 && rows <= 1e3) resizeCommand(`R ${cols} ${rows}
161
+ `);
162
+ },
163
+ kill() {
164
+ closeOwner();
165
+ },
166
+ cleanup() {
167
+ closeOwner();
168
+ return finished;
169
+ },
170
+ onData(listener) {
171
+ data.add(listener);
172
+ if (buffered) {
173
+ const value = buffered;
174
+ buffered = "";
175
+ queueMicrotask(() => {
176
+ if (data.has(listener)) listener(value);
177
+ });
178
+ }
179
+ return { dispose() {
180
+ data.delete(listener);
181
+ } };
182
+ },
183
+ onExit(listener) {
184
+ exits.add(listener);
185
+ if (exit && completed) {
186
+ const value = exit;
187
+ queueMicrotask(() => {
188
+ if (exits.has(listener)) listener(value);
189
+ });
190
+ }
191
+ return { dispose() {
192
+ exits.delete(listener);
193
+ } };
194
+ }
195
+ };
196
+ }
197
+ export {
198
+ nativeCapabilityOf,
199
+ nativePtySpawn,
200
+ nativeTerminalCapability
201
+ };
@@ -12,12 +12,29 @@ export type OperationsOptions = {
12
12
  templates?: Record<string, string>;
13
13
  /** Project roots the daemon knows from its session records, for a team save's sync. */
14
14
  knownProjects?: () => Iterable<string>;
15
+ /** A gate changed through task.gate.resolve: the runtime syncs the project's gate cards and mail. */
16
+ onGateChange?: (projectRoot: string) => Promise<void> | void;
17
+ /** A provider file was written or removed; `enabled` when this save turned it from off to on (t-d0b0). */
18
+ onProviderSaved?: (id: string, enabled: boolean) => void;
19
+ /** The models alpd's catalog learned or probed for an ACP provider (t-d0b0). */
20
+ learnedModels?: (id: string) => Array<{
21
+ id: string;
22
+ label?: string;
23
+ }>;
15
24
  };
16
- type Handler = (params: any) => Promise<unknown>;
17
- export declare function createOperations({ home, templates, knownProjects }?: OperationsOptions): {
25
+ /** `caller.agent`: the connection said in daemon.hello that an ALP agent started it (t-ca1f). */
26
+ export type Caller = {
27
+ agent?: boolean;
28
+ };
29
+ type Handler = (params: any, caller?: Caller) => Promise<unknown>;
30
+ /** Core refusals (AlpError codes) as protocol errors; `context` decides what an ambiguous one means. */
31
+ export declare function fromCore(error: any, context?: {
32
+ notFound?: 'not_found' | 'invalid_entry';
33
+ }): unknown;
34
+ export declare function createOperations({ home, templates, knownProjects, onGateChange, onProviderSaved, learnedModels }?: OperationsOptions): {
18
35
  handlers: {
19
36
  [x: string]: Handler;
20
37
  };
21
- capabilities: ("library" | "team" | "task" | "settings.language")[];
38
+ capabilities: ("library" | "team" | "task" | "library.project.write" | "settings.language")[];
22
39
  };
23
40
  export {};
@@ -3,11 +3,11 @@ import { createHash, createHmac, randomBytes } from "node:crypto";
3
3
  import { lstat, stat } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { CAPABILITY, ERROR, RPC_ERROR } from "@anhlp/alp-protocol";
6
- import { closeTask, createTask, epicReport, loadTasks, reopenTask, resolveGate } from "@anhlp/alp-core/tasks";
6
+ import { closeTask, createTask, epicReport, loadTasks, rejectGate, reopenTask, resolveGate } from "@anhlp/alp-core/tasks";
7
7
  import { taskRows } from "@anhlp/alp-core/task-rows";
8
8
  import { deleteEntry, duplicateEntry, getEntry, listEntries, renameEntry, saveEntry, setGivenSkills } from "@anhlp/alp-core/library-edit";
9
9
  import { listTeams } from "@anhlp/alp-core/teams";
10
- import { MODELS } from "@anhlp/alp-core/models";
10
+ import { catalogEntries } from "@anhlp/alp-runtime/index";
11
11
  import { listProviders } from "@anhlp/alp-core/providers";
12
12
  import { languageSetting, setLanguage, LANGUAGE_CHARS } from "@anhlp/alp-core/user-settings";
13
13
  import { syncProjectSettings } from "@anhlp/alp-core/init";
@@ -25,6 +25,8 @@ function fromCore(error, context = {}) {
25
25
  if (error instanceof RpcError || typeof error?.code !== "string" || error?.name !== "AlpError") return error;
26
26
  const message = error.message;
27
27
  switch (error.code) {
28
+ case "UNSAFE_LIBRARY_WRITE":
29
+ return failure(ERROR.forbidden, "library_policy", message);
28
30
  case "UNSAFE_PATH":
29
31
  return failure(ERROR.forbidden, "unsafe_path", message);
30
32
  case "TASK_NOT_FOUND":
@@ -37,6 +39,8 @@ function fromCore(error, context = {}) {
37
39
  case "TASK_TAKEN":
38
40
  case "TASK_UNVERIFIED":
39
41
  return failure(ERROR.conflict, "task_state", message);
42
+ case "GATE_USER_ONLY":
43
+ return failure(ERROR.forbidden, "user_only", message);
40
44
  case "TASKS_LOCKED":
41
45
  return failure(ERROR.unavailable, "busy", message);
42
46
  case "IN_USE":
@@ -100,7 +104,7 @@ function unredact(kind, content, previous) {
100
104
  if (found !== void 0) throw failure(RPC_ERROR.invalidParams, "secret_marker", `${found || "content"} holds a secret marker where no secret is kept`);
101
105
  return next;
102
106
  }
103
- function createOperations({ home, templates, knownProjects = () => [] } = {}) {
107
+ function createOperations({ home, templates, knownProjects = () => [], onGateChange, onProviderSaved, learnedModels } = {}) {
104
108
  const revisionKey = randomBytes(32);
105
109
  const toWire = (revision) => revision == null ? null : `r${createHmac("sha256", revisionKey).update(revision).digest("base64url").slice(0, 22)}`;
106
110
  let writes = Promise.resolve();
@@ -131,9 +135,9 @@ function createOperations({ home, templates, knownProjects = () => [] } = {}) {
131
135
  throw error;
132
136
  }
133
137
  }
134
- const guard = (handler, context) => async (params) => {
138
+ const guard = (handler, context) => async (params, caller) => {
135
139
  try {
136
- return await handler(params);
140
+ return await handler(params, caller);
137
141
  } catch (error) {
138
142
  throw fromCore(error, context);
139
143
  }
@@ -165,21 +169,29 @@ function createOperations({ home, templates, knownProjects = () => [] } = {}) {
165
169
  });
166
170
  return result;
167
171
  }),
168
- "task.update": guard(async ({ projectRoot, id, action, note, ifRev }) => {
172
+ "task.update": guard(async ({ projectRoot, id, action, note, ifRev }, caller) => {
169
173
  const root = await project(projectRoot);
170
174
  const options = ifRev !== void 0 ? { ifRev } : void 0;
171
175
  if (action === "reopen") {
172
176
  const task2 = await reopenTask(root, id, { ...note ? { note } : {} }, "user", options);
173
177
  return { id: task2.id, status: task2.status, rev: task2.rev };
174
178
  }
175
- const task = await closeTask(root, id, { reason: "done", ...note ? { summary: note } : {} }, "user", options);
179
+ const task = await closeTask(root, id, { reason: "done", ...note ? { summary: note } : {}, agent: caller?.agent === true, channel: "web" }, "user", options);
176
180
  const { tasks } = await loadTasks(root);
177
181
  const landed = tasks.some((entry) => entry.parent === task.id) ? epicReport(task.id, tasks).text.split("\n")[0] : void 0;
178
182
  return { id: task.id, status: task.status, rev: task.rev, ...landed ? { landed } : {} };
179
183
  }),
180
- "task.gate.resolve": guard(async ({ projectRoot, id, gate, note, ifRev }) => {
184
+ // Approves a gate, or with reject records the user's rejection and leaves it open. Either way
185
+ // the runtime is told, so main gets the decision by mail (at least once) and the gate's card settles.
186
+ "task.gate.resolve": guard(async ({ projectRoot, id, gate, note, ifRev, choice, reject, channel = "web" }, caller) => {
181
187
  const root = await project(projectRoot);
182
- const task = await resolveGate(root, id, gate, { by: "user", ...note ? { note } : {}, ...ifRev !== void 0 ? { ifRev } : {} });
188
+ if (caller?.agent) {
189
+ const { tasks } = await loadTasks(root);
190
+ if (tasks.find((task2) => task2.id === id)?.gates.find((entry) => entry.id === gate)?.kind === "human") throw failure(ERROR.forbidden, "user_only", "Only the user decides a human gate; this connection was opened by an ALP agent");
191
+ }
192
+ const guarded = ifRev !== void 0 ? { ifRev } : {};
193
+ const task = reject === true ? await rejectGate(root, id, gate, { by: "user", channel, ...note ? { reason: note } : {}, ...guarded }) : await resolveGate(root, id, gate, { by: "user", channel, ...note ? { note } : {}, ...choice !== void 0 ? { choice } : {}, ...guarded });
194
+ await onGateChange?.(root);
183
195
  return { id: task.id, status: task.status, rev: task.rev };
184
196
  })
185
197
  };
@@ -200,7 +212,8 @@ function createOperations({ home, templates, knownProjects = () => [] } = {}) {
200
212
  const { content, secrets } = redact(kind, entry.content);
201
213
  return { ...entry, content, revision: toWire(entry.revision), ...secrets.length ? { secrets } : {} };
202
214
  }),
203
- "library.save": guard(({ kind, name, scope, projectRoot, content, revision, sync = "none" }) => serial(async () => {
215
+ "library.save": guard(({ kind, name, scope, projectRoot, content, revision, policy, sync = "none" }) => serial(async () => {
216
+ if (policy === "project-data" && sync !== "none") throw failure(ERROR.forbidden, "library_policy", "Project-data writes cannot synchronize projects");
204
217
  const options = await where(projectRoot, scope);
205
218
  const current = await layer(kind, name, options, scope);
206
219
  if (revision !== void 0 && revision !== toWire(current?.revision ?? null)) {
@@ -208,7 +221,13 @@ function createOperations({ home, templates, knownProjects = () => [] } = {}) {
208
221
  }
209
222
  const previous = current?.content ?? (await layer(kind, name, options))?.content;
210
223
  const next = unredact(kind, content, previous);
211
- const saved = await saveEntry(kind, name, next, { ...options, scope, ...revision !== void 0 ? { revision: current?.revision ?? null } : {} });
224
+ const saved = await saveEntry(kind, name, next, { ...options, scope, policy, ...revision !== void 0 ? { revision: current?.revision ?? null } : {} });
225
+ if (kind === "providers") {
226
+ try {
227
+ onProviderSaved?.(name, previous?.provider?.enabled === false && next?.provider?.enabled !== false);
228
+ } catch {
229
+ }
230
+ }
212
231
  if (kind !== "teams" || sync !== "known-projects") return { revision: toWire(saved.revision) };
213
232
  const roots = new Set(options.root ? [options.root] : []);
214
233
  if (scope === "library") {
@@ -225,33 +244,54 @@ function createOperations({ home, templates, knownProjects = () => [] } = {}) {
225
244
  }
226
245
  return { revision: toWire(saved.revision), syncedProjects, syncErrors };
227
246
  }), { notFound: "invalid_entry" }),
228
- "library.delete": guard(({ kind, name, scope, projectRoot, revision }) => serial(async () => {
247
+ "library.delete": guard(({ kind, name, scope, projectRoot, revision, policy }) => serial(async () => {
229
248
  const options = await where(projectRoot, scope);
230
249
  const current = await layer(kind, name, options, scope);
231
250
  if (!current) throw failure(ERROR.notFound, "not_found", `No ${kind} entry '${name}' in the ${scope}`);
232
251
  if (revision !== void 0 && revision !== toWire(current.revision)) throw failure(ERROR.conflict, "revision_conflict", `${kind} '${name}' changed in the ${scope} since you opened it`);
233
- return deleteEntry(kind, name, { ...options, scope, ...revision !== void 0 ? { revision: current.revision } : {} });
252
+ const deleted = await deleteEntry(kind, name, { ...options, scope, policy, ...revision !== void 0 ? { revision: current.revision } : {} });
253
+ if (kind === "providers") {
254
+ try {
255
+ onProviderSaved?.(name, false);
256
+ } catch {
257
+ }
258
+ }
259
+ return deleted;
234
260
  })),
235
- "library.duplicate": guard(({ kind, from, to, scope, projectRoot }) => serial(async () => {
261
+ "library.duplicate": guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
236
262
  const options = await where(projectRoot, scope);
237
263
  try {
238
264
  await getEntry(kind, from, options);
239
265
  } catch (error) {
240
266
  throw fromCore(error, { notFound: "not_found" });
241
267
  }
242
- return { revision: toWire((await duplicateEntry(kind, from, to, { ...options, scope })).revision) };
268
+ const result = { revision: toWire((await duplicateEntry(kind, from, to, { ...options, scope, policy })).revision) };
269
+ if (kind === "providers") {
270
+ try {
271
+ onProviderSaved?.(to, false);
272
+ } catch {
273
+ }
274
+ }
275
+ return result;
243
276
  }), { notFound: "invalid_entry" }),
244
- "library.rename": guard(({ kind, from, to, scope, projectRoot }) => serial(async () => {
277
+ "library.rename": guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
245
278
  const options = await where(projectRoot, scope);
246
- return { revision: toWire((await renameEntry(kind, from, to, { ...options, scope })).revision) };
279
+ const renamed = await renameEntry(kind, from, to, { ...options, scope, policy });
280
+ if (kind === "providers") {
281
+ try {
282
+ onProviderSaved?.(to, false);
283
+ } catch {
284
+ }
285
+ }
286
+ return { revision: toWire(renamed.revision) };
247
287
  })),
248
288
  "library.skills.set": guard(({ agent, skills }) => serial(() => setGivenSkills(agent, skills, { library: home })), { notFound: "invalid_entry" }),
249
289
  "library.models": guard(async () => {
250
- const models = MODELS.map((model) => ({ id: `${model.runtime}:${model.id}`, label: `${model.runtime} \xB7 ${model.label}`, efforts: model.efforts, ...model.effort ? { effort: model.effort } : {} }));
290
+ const models = catalogEntries.map((model) => ({ id: `${model.runtime}:${model.id}`, label: `${model.runtime} \xB7 ${model.label}`, efforts: model.efforts, ...model.effort ? { effort: model.effort } : {} }));
251
291
  for (const provider of await listProviders(home)) {
252
292
  if (provider.enabled === false || provider.kind === "antigravity") continue;
253
293
  models.push({ id: `acp:${provider.id}`, label: `${provider.label} \xB7 Provider default`, efforts: [] });
254
- for (const model of [...provider.models ?? [], ...provider.additionalModels ?? []]) models.push({ id: `acp:${provider.id}/${model.id}`, label: `${provider.label} \xB7 ${model.label ?? model.id}`, efforts: [] });
294
+ for (const model of [...provider.models ?? learnedModels?.(provider.id) ?? [], ...provider.additionalModels ?? []]) models.push({ id: `acp:${provider.id}/${model.id}`, label: `${provider.label} \xB7 ${model.label ?? model.id}`, efforts: [] });
255
295
  }
256
296
  return { models: [...new Map(models.map((model) => [model.id, model])).values()] };
257
297
  }),
@@ -264,9 +304,10 @@ function createOperations({ home, templates, knownProjects = () => [] } = {}) {
264
304
  const library = home !== void 0;
265
305
  return {
266
306
  handlers: { ...taskHandlers, ...library ? libraryHandlers : {} },
267
- capabilities: [CAPABILITY.task, ...library ? [CAPABILITY.team, CAPABILITY.library, CAPABILITY.settingsLanguage] : []]
307
+ capabilities: [CAPABILITY.task, ...library ? [CAPABILITY.team, CAPABILITY.library, CAPABILITY.libraryProjectWrite, CAPABILITY.settingsLanguage] : []]
268
308
  };
269
309
  }
270
310
  export {
271
- createOperations
311
+ createOperations,
312
+ fromCore
272
313
  };
@@ -0,0 +1,89 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ export type ProjectRecord = {
3
+ id: string;
4
+ root: string;
5
+ canonical?: string;
6
+ customName?: string | null;
7
+ addedAt: string;
8
+ removedAt?: string | null;
9
+ };
10
+ export type WorkspaceRecord = {
11
+ id: string;
12
+ projectId: string;
13
+ directory: string;
14
+ canonical?: string;
15
+ title?: string | null;
16
+ pinnedAt?: string | null;
17
+ labels: string[];
18
+ createdAt: string;
19
+ archivedAt?: string | null;
20
+ idempotencyKey?: string;
21
+ worktree?: ManagedWorktree;
22
+ };
23
+ export type ManagedWorktree = {
24
+ kind: 'user';
25
+ sourceWorkspaceId: string;
26
+ source: string;
27
+ commonDir: string;
28
+ gitDir: string;
29
+ mappingId: string;
30
+ principalId: string;
31
+ grantEpoch: string;
32
+ requestId?: string;
33
+ ifRevision?: number;
34
+ branch: string;
35
+ head: string;
36
+ removedAt?: string;
37
+ };
38
+ export type Registry = {
39
+ version: 1;
40
+ revision: number;
41
+ projects: ProjectRecord[];
42
+ workspaces: WorkspaceRecord[];
43
+ sessions: Record<string, string>;
44
+ labels: {
45
+ generation: string;
46
+ seq: number;
47
+ catalog: {
48
+ name: string;
49
+ color: string;
50
+ }[];
51
+ };
52
+ worktreeJournal?: Record<string, {
53
+ fingerprint: string;
54
+ intent: any;
55
+ }>;
56
+ receipts: Record<string, {
57
+ fingerprint: string;
58
+ result: unknown;
59
+ }>;
60
+ };
61
+ export declare class RegistryError extends Error {
62
+ readonly code: number;
63
+ readonly data: {
64
+ reason: string;
65
+ };
66
+ constructor(code: number, message: string, data: {
67
+ reason: string;
68
+ });
69
+ }
70
+ /** Sole mutable owner. Failed writes never publish the draft or consume a requestId. */
71
+ export declare function createRegistry(home: string, options?: {
72
+ write?: typeof writeFile;
73
+ }): {
74
+ /** Native intent and receipt share the sole registry writer and atomic persistence boundary. */
75
+ nativeMutation: (method: string, args: any, context: {
76
+ actor: string;
77
+ requestId: string;
78
+ ifRevision: number;
79
+ }, prepare: (r: Registry) => Promise<any>, apply: (intent: any, draft: Registry) => Promise<any>) => Promise<any>;
80
+ snapshot: () => Promise<Registry>;
81
+ mutate: (method: string, args: any, context: {
82
+ actor?: string;
83
+ allowedRoots?: string[];
84
+ ifRevision?: number;
85
+ requestId: string;
86
+ }) => Promise<any>;
87
+ resolve(workspaceId: string, cwd?: string, includeArchived?: boolean): Promise<string>;
88
+ };
89
+ export type RegistryService = ReturnType<typeof createRegistry>;