@koed-labs/server 0.10.3 → 1.0.0

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 (56) hide show
  1. package/README.md +3 -3
  2. package/bin/koed.js +1 -1
  3. package/package.json +2 -2
  4. package/vendor/chunk-273NMYXE.js +605 -0
  5. package/vendor/{chunk-VPC5NLZG.js → chunk-4DHYSJJT.js} +1 -1
  6. package/vendor/{chunk-HK2H3MVE.js → chunk-53ZFCDHP.js} +4 -0
  7. package/vendor/{chunk-YCDEMYY6.js → chunk-54UL4U2E.js} +261 -110
  8. package/vendor/{chunk-X6M525ZJ.js → chunk-64AST7WZ.js} +5 -5
  9. package/vendor/{chunk-JKOG52PE.js → chunk-7FSHVVTZ.js} +1 -1
  10. package/vendor/chunk-7HLNJ2BI.js +1669 -0
  11. package/vendor/chunk-ALJUSOF7.js +175 -0
  12. package/vendor/{chunk-A6WMU2GG.js → chunk-AOZ3LMTF.js} +5 -4
  13. package/vendor/{chunk-KUIWH33N.js → chunk-AVQCUFYQ.js} +1 -1
  14. package/vendor/{chunk-JJNLH5GA.js → chunk-BYN6KXNP.js} +21 -19
  15. package/vendor/{chunk-PY5LYLV7.js → chunk-DWWMBGHX.js} +26 -21
  16. package/vendor/chunk-E6YVGIEW.js +12518 -0
  17. package/vendor/{chunk-C3N4N5HR.js → chunk-EEBIYWTE.js} +26 -21
  18. package/vendor/{chunk-YOFI4PCH.js → chunk-F77ZTTNS.js} +7 -1
  19. package/vendor/{chunk-RVYJKKWA.js → chunk-F7AMEDDU.js} +5 -4
  20. package/vendor/{chunk-473OA62O.js → chunk-FSNLU46W.js} +218 -12497
  21. package/vendor/{chunk-2S3OGPUC.js → chunk-GY5GATZL.js} +2 -2
  22. package/vendor/chunk-ILQVLZ2I.js +50 -0
  23. package/vendor/{chunk-QIIKMG3M.js → chunk-IY2HRXOZ.js} +1 -5
  24. package/vendor/{chunk-ZUGNCQZE.js → chunk-JYK6UL6D.js} +22 -8
  25. package/vendor/chunk-KG3RANR4.js +75 -0
  26. package/vendor/{chunk-YJ6XUZT6.js → chunk-KRBZZ6GS.js} +23 -16
  27. package/vendor/{chunk-AFLKCQHF.js → chunk-L4RD3TAZ.js} +2 -2
  28. package/vendor/{chunk-XNFVSVBS.js → chunk-LHUMBHG7.js} +1 -1
  29. package/vendor/{chunk-J2L726BC.js → chunk-NGV45YWB.js} +3 -3
  30. package/vendor/{chunk-A4NKL2PK.js → chunk-OG7G6DIR.js} +1 -1
  31. package/vendor/{chunk-DXTAWHY3.js → chunk-OZU6JFB4.js} +8 -7
  32. package/vendor/chunk-QV3WPU7A.js +8 -0
  33. package/vendor/{chunk-ZXX4ZNJY.js → chunk-S6HD3MDU.js} +3 -2
  34. package/vendor/{chunk-NEWIOOM6.js → chunk-SQZ2OSP6.js} +3 -2
  35. package/vendor/{chunk-G4IIVVJO.js → chunk-T6UB5PNX.js} +70 -2
  36. package/vendor/{chunk-SKVYP7NY.js → chunk-T7OGE5E5.js} +8 -8
  37. package/vendor/{chunk-GELDEJJ2.js → chunk-TIBYKMRW.js} +173 -51
  38. package/vendor/{chunk-HFM6ROJL.js → chunk-TISYUUEJ.js} +1 -1
  39. package/vendor/{chunk-K2EIFEQF.js → chunk-TSAYTRX3.js} +1 -1
  40. package/vendor/{chunk-PT3AUPGE.js → chunk-UB6JCVQ3.js} +3 -1
  41. package/vendor/{chunk-NM5NXCVM.js → chunk-UCOHFZ77.js} +626 -996
  42. package/vendor/{chunk-2BWTLF7A.js → chunk-UIMUUIH7.js} +45 -21
  43. package/vendor/{chunk-HZJK5RWC.js → chunk-USHFSJT7.js} +695 -280
  44. package/vendor/chunk-VGL5AZN5.js +152 -0
  45. package/vendor/{chunk-TSRPHKAC.js → chunk-VLP72QWX.js} +16 -42
  46. package/vendor/chunk-W6632NOX.js +14 -0
  47. package/vendor/{chunk-YJWREXN6.js → chunk-WBMO7YCO.js} +1 -1
  48. package/vendor/chunk-XCO3RV3Z.js +11 -0
  49. package/vendor/chunk-XKXSC6YS.js +373 -0
  50. package/vendor/{chunk-YK4F4VY2.js → chunk-Y6GE52OP.js} +51 -30
  51. package/vendor/{chunk-UI5RLBKQ.js → chunk-YZLQZU5E.js} +17 -1
  52. package/vendor/chunk-ZKKWLLPU.js +18 -0
  53. package/vendor/cli.js +1 -1
  54. package/vendor/component-manifest-catalog.js +2 -1
  55. package/vendor/control-plane.js +11 -6
  56. package/vendor/chunk-2DA7EFZV.js +0 -924
@@ -7,7 +7,34 @@ import {
7
7
  } from "./chunk-QT24SAW6.js";
8
8
  import {
9
9
  applyPersistedLocalPorts
10
- } from "./chunk-HFM6ROJL.js";
10
+ } from "./chunk-TISYUUEJ.js";
11
+ import {
12
+ resolveKoedServerConfig,
13
+ writeCodexGlobalMemoryGuidancePreference
14
+ } from "./chunk-ALJUSOF7.js";
15
+ import {
16
+ inspectDeviceIdentityStatus
17
+ } from "./chunk-LHUMBHG7.js";
18
+ import {
19
+ ensureKoedHome,
20
+ resolveKoedServerPaths
21
+ } from "./chunk-TSAYTRX3.js";
22
+ import {
23
+ canUseSourceCheckoutFallback,
24
+ resolvePackagedKoedRuntimeRoot
25
+ } from "./chunk-YZLQZU5E.js";
26
+ import {
27
+ loadRepoEnv,
28
+ resolveApiUrl
29
+ } from "./chunk-W2HNI6AA.js";
30
+ import {
31
+ assertKoedAppRuntimeAvailable,
32
+ resolveKoedAppRuntime,
33
+ resolveKoedAppRuntimeExecution,
34
+ resolveKoedAppRuntimeForExecution,
35
+ resolveKoedControlPlaneVersion,
36
+ resolveKoedRuntimeOwner
37
+ } from "./chunk-OG7G6DIR.js";
11
38
  import {
12
39
  pinDesktopBundleGenerationForStart,
13
40
  pinGenerationForStart,
@@ -15,45 +42,23 @@ import {
15
42
  readCurrentGenerationForOwner,
16
43
  readDesktopBundleGeneration,
17
44
  resolveDesktopRuntimeOwner,
18
- resolveKoedServerConfig,
19
- validateDesktopRuntimeCapability,
20
- writeCodexGlobalMemoryGuidancePreference
21
- } from "./chunk-NM5NXCVM.js";
45
+ validateDesktopRuntimeCapability
46
+ } from "./chunk-UCOHFZ77.js";
22
47
  import {
23
48
  applyActiveRuntimeUrls,
24
49
  isProcessRunning,
25
50
  readActiveRuntimeState
26
- } from "./chunk-G4IIVVJO.js";
51
+ } from "./chunk-T6UB5PNX.js";
27
52
  import {
28
- assertKoedAppRuntimeAvailable,
29
- resolveKoedAppRuntime,
30
- resolveKoedAppRuntimeExecution,
31
- resolveKoedAppRuntimeForExecution,
32
- resolveKoedControlPlaneVersion,
33
- resolveKoedRuntimeOwner
34
- } from "./chunk-A4NKL2PK.js";
53
+ require_proper_lockfile
54
+ } from "./chunk-7NXKPDF3.js";
35
55
  import {
36
56
  collectPrivacyModelStatus,
37
57
  resolvePrivacyModelPaths
38
- } from "./chunk-VPC5NLZG.js";
58
+ } from "./chunk-4DHYSJJT.js";
39
59
  import {
40
60
  collectUpstreamRegistryStatus
41
- } from "./chunk-YJWREXN6.js";
42
- import {
43
- inspectDeviceIdentityStatus
44
- } from "./chunk-XNFVSVBS.js";
45
- import {
46
- ensureKoedHome,
47
- resolveKoedServerPaths
48
- } from "./chunk-K2EIFEQF.js";
49
- import {
50
- canUseSourceCheckoutFallback,
51
- resolvePackagedKoedRuntimeRoot
52
- } from "./chunk-UI5RLBKQ.js";
53
- import {
54
- loadRepoEnv,
55
- resolveApiUrl
56
- } from "./chunk-W2HNI6AA.js";
61
+ } from "./chunk-WBMO7YCO.js";
57
62
  import {
58
63
  DESKTOP_LOCAL_CREDENTIAL_OPERATION_FAMILIES,
59
64
  LOCAL_PERSONAL_USER_EMAIL,
@@ -67,17 +72,177 @@ import {
67
72
  readDesktopLocalCredentialAuthorization,
68
73
  resolveTeamCollaborationEnabled,
69
74
  storeDesktopLocalCredential,
75
+ summarizeHistoricalIngestionState,
70
76
  upgradeDesktopLocalCredential
71
- } from "./chunk-473OA62O.js";
77
+ } from "./chunk-E6YVGIEW.js";
78
+ import {
79
+ __toESM
80
+ } from "./chunk-BTS4ZTF3.js";
72
81
 
73
82
  // packages/koed-server/dist/status.js
74
- import { existsSync as existsSync10, readFileSync as readFileSync5 } from "node:fs";
83
+ import { existsSync as existsSync11, readFileSync as readFileSync6 } from "node:fs";
75
84
  import { homedir as homedir4 } from "node:os";
76
85
  import { resolve as resolve12 } from "node:path";
77
86
  import { spawnSync as nodeSpawnSync4 } from "node:child_process";
78
87
 
88
+ // packages/shared/src/ai-client-connections.ts
89
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
90
+ import { randomUUID } from "node:crypto";
91
+ import {
92
+ existsSync,
93
+ mkdirSync,
94
+ readFileSync,
95
+ renameSync,
96
+ rmSync,
97
+ writeFileSync
98
+ } from "node:fs";
99
+ import path from "node:path";
100
+ var AI_CLIENT_CONNECTION_IDS = [
101
+ "codex",
102
+ "claude",
103
+ "pi"
104
+ ];
105
+ var aiClientConnectionsPath = (koedHome) => path.join(koedHome, "state", "ai-client-connections.json");
106
+ var parseEntry = (value) => {
107
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
108
+ const entry = value;
109
+ return typeof entry.connected === "boolean" && Number.isSafeInteger(entry.revision) && entry.revision >= 0 && typeof entry.updatedAt === "string" ? {
110
+ connected: entry.connected,
111
+ revision: entry.revision,
112
+ updatedAt: entry.updatedAt
113
+ } : null;
114
+ };
115
+ var parse = (koedHome) => {
116
+ let text;
117
+ try {
118
+ text = readFileSync(aiClientConnectionsPath(koedHome), "utf8");
119
+ } catch (error) {
120
+ return error.code === "ENOENT" ? { kind: "missing" } : { kind: "invalid" };
121
+ }
122
+ try {
123
+ const value = JSON.parse(text);
124
+ if (value.version !== 2 || typeof value.updatedAt !== "string" || !value.clients || typeof value.clients !== "object" || Array.isArray(value.clients))
125
+ return { kind: "invalid" };
126
+ const clients = {};
127
+ for (const id of AI_CLIENT_CONNECTION_IDS) {
128
+ const raw = value.clients[id];
129
+ if (raw === void 0) continue;
130
+ const entry = parseEntry(raw);
131
+ if (!entry) return { kind: "invalid" };
132
+ clients[id] = entry;
133
+ }
134
+ return {
135
+ kind: "valid",
136
+ record: { version: 2, updatedAt: value.updatedAt, clients }
137
+ };
138
+ } catch {
139
+ return { kind: "invalid" };
140
+ }
141
+ };
142
+ var readAiClientConnections = (koedHome) => {
143
+ const parsed = parse(koedHome);
144
+ return parsed.kind === "valid" ? parsed.record : null;
145
+ };
146
+ var aiClientConnectionRevision = (koedHome, id) => {
147
+ const parsed = parse(koedHome);
148
+ if (parsed.kind === "invalid")
149
+ throw new Error(
150
+ "The AI Client connection record could not be read; connect the AI Client again after Koed Server repairs it."
151
+ );
152
+ return parsed.kind === "valid" ? parsed.record.clients[id]?.revision ?? 0 : 0;
153
+ };
154
+ var lockTimeoutMs = 5e3;
155
+ var withConnectionsLock = (koedHome, operation) => {
156
+ const target = aiClientConnectionsPath(koedHome);
157
+ mkdirSync(path.dirname(target), { recursive: true, mode: 448 });
158
+ const deadline = Date.now() + lockTimeoutMs;
159
+ let release;
160
+ while (true) {
161
+ try {
162
+ release = import_proper_lockfile.default.lockSync(target, { realpath: false, stale: 3e4 });
163
+ break;
164
+ } catch (error) {
165
+ if (error.code !== "ELOCKED" || Date.now() >= deadline)
166
+ throw error;
167
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
168
+ }
169
+ }
170
+ try {
171
+ return operation();
172
+ } finally {
173
+ release();
174
+ }
175
+ };
176
+ var write = (koedHome, record) => {
177
+ const target = aiClientConnectionsPath(koedHome);
178
+ const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`;
179
+ try {
180
+ writeFileSync(temporary, `${JSON.stringify(record)}
181
+ `, {
182
+ mode: 384,
183
+ flag: "wx"
184
+ });
185
+ renameSync(temporary, target);
186
+ } finally {
187
+ if (existsSync(temporary)) rmSync(temporary, { force: true });
188
+ }
189
+ };
190
+ var change = (koedHome, id, decide, now) => withConnectionsLock(koedHome, () => {
191
+ const parsed = parse(koedHome);
192
+ const record = parsed.kind === "valid" ? parsed.record : { version: 2, updatedAt: now.toISOString(), clients: {} };
193
+ const current = record.clients[id];
194
+ const connected = decide(current, parsed.kind !== "invalid");
195
+ if (connected === null) return false;
196
+ const updatedAt = now.toISOString();
197
+ write(koedHome, {
198
+ version: 2,
199
+ updatedAt,
200
+ clients: {
201
+ ...record.clients,
202
+ [id]: {
203
+ connected,
204
+ revision: (current?.revision ?? 0) + 1,
205
+ updatedAt
206
+ }
207
+ }
208
+ });
209
+ return true;
210
+ });
211
+ var grantAiClientConnection = (koedHome, id, expectedRevision, now = /* @__PURE__ */ new Date()) => {
212
+ let granted = false;
213
+ change(
214
+ koedHome,
215
+ id,
216
+ (current, readable) => {
217
+ if (!readable)
218
+ throw new Error(
219
+ "The AI Client connection record could not be read; the AI Client was not connected."
220
+ );
221
+ if (current?.connected === true) {
222
+ granted = true;
223
+ return null;
224
+ }
225
+ if ((current?.revision ?? 0) !== expectedRevision) return null;
226
+ granted = true;
227
+ return true;
228
+ },
229
+ now
230
+ );
231
+ return granted;
232
+ };
233
+ var revokeAiClientConnection = (koedHome, id, options = {}) => change(
234
+ koedHome,
235
+ id,
236
+ (current) => {
237
+ if (options.ifRevision === void 0) return false;
238
+ if (current?.connected !== true) return null;
239
+ return (current.revision ?? 0) === options.ifRevision ? false : null;
240
+ },
241
+ options.now ?? /* @__PURE__ */ new Date()
242
+ );
243
+
79
244
  // packages/koed-server/dist/service-runtime-selection.js
80
- import { existsSync } from "node:fs";
245
+ import { existsSync as existsSync2 } from "node:fs";
81
246
  var runtimeOwner = (paths, capability) => {
82
247
  if (capability === void 0)
83
248
  return resolveKoedRuntimeOwner();
@@ -86,7 +251,7 @@ var runtimeOwner = (paths, capability) => {
86
251
  }
87
252
  return resolveDesktopRuntimeOwner(capability, paths.koedHome);
88
253
  };
89
- async function resolveVerifiedPackagedRuntime(paths, environment, requirements, exists = existsSync, capability) {
254
+ async function resolveVerifiedPackagedRuntime(paths, environment, requirements, exists = existsSync2, capability) {
90
255
  let generation;
91
256
  try {
92
257
  if (capability) {
@@ -113,7 +278,7 @@ async function resolveVerifiedPackagedRuntime(paths, environment, requirements,
113
278
  assertKoedAppRuntimeAvailable(runtime, paths);
114
279
  return runtime;
115
280
  }
116
- async function pinAndResolvePackagedRuntime(paths, environment, requirements, exists = existsSync, capability) {
281
+ async function pinAndResolvePackagedRuntime(paths, environment, requirements, exists = existsSync2, capability) {
117
282
  let pin;
118
283
  try {
119
284
  pin = capability ? await pinDesktopBundleGenerationForStart(paths, capability) : await pinGenerationForStart(paths, runtimeOwner(paths));
@@ -202,7 +367,7 @@ var stripCodexOwnershipBlock = (content) => {
202
367
  };
203
368
 
204
369
  // packages/koed-server/dist/local-embedding-runtime.js
205
- import { existsSync as existsSync2, statSync } from "node:fs";
370
+ import { existsSync as existsSync3, statSync } from "node:fs";
206
371
  import { spawn as nodeSpawn } from "node:child_process";
207
372
  import { dirname, resolve } from "node:path";
208
373
  var DOCKER_LLAMA_SERVER_BINARY = "/opt/llama.cpp/llama-server";
@@ -225,7 +390,7 @@ var nativeLlamaServerOverride = (environment) => {
225
390
  }
226
391
  return void 0;
227
392
  };
228
- var chooseRuntimePath = (candidates, defaultPath, defaultSource, exists = existsSync2) => {
393
+ var chooseRuntimePath = (candidates, defaultPath, defaultSource, exists = existsSync3) => {
229
394
  for (const candidate of candidates) {
230
395
  if (exists(candidate.path)) {
231
396
  return candidate;
@@ -234,7 +399,7 @@ var chooseRuntimePath = (candidates, defaultPath, defaultSource, exists = exists
234
399
  return { path: defaultPath, artifactSource: defaultSource };
235
400
  };
236
401
  var combinedArtifactSource = (sources) => sources.every((source) => source === sources[0]) ? sources[0] : "explicit-override";
237
- var resolveLocalEmbeddingRuntimePaths = (paths, environment = process.env, exists = existsSync2, selectedRuntime) => {
402
+ var resolveLocalEmbeddingRuntimePaths = (paths, environment = process.env, exists = existsSync3, selectedRuntime) => {
238
403
  const koedRuntimeAppDir = resolve(paths.koedHome, "runtime", "embedding-service");
239
404
  const repoAppDir = resolve(paths.repoRoot, "apps", "embedding-service");
240
405
  const appRuntime = selectedRuntime ?? resolveKoedAppRuntime(paths, environment, exists);
@@ -271,13 +436,16 @@ var resolveLocalEmbeddingRuntimePaths = (paths, environment = process.env, exist
271
436
  const appDir = dirname(dirname(serviceEntry));
272
437
  const host = trim(environment.KOED_EMBEDDING_HOST) ?? "127.0.0.1";
273
438
  const port = trim(environment.KOED_EMBEDDING_PORT) ?? trim(environment.EMBEDDING_SERVICE_HOST_PORT) ?? "3800";
274
- const koedRuntimeLlamaServer = resolve(paths.koedHome, "runtime", "llama.cpp", "llama-server");
439
+ const koedRuntimeLlamaServer = resolve(paths.nativeSelectionRoot ?? resolve(paths.koedHome, "runtime"), "llama.cpp", "llama-server");
275
440
  const packagedLlamaServer = packagedRuntimeRoot ? resolve(packagedRuntimeRoot, "llama.cpp", "llama-server") : void 0;
276
441
  const vendorLlamaServer = resolve(paths.repoRoot, "vendor", "llama.cpp", "llama-server");
277
442
  const llamaOverride = nativeLlamaServerOverride(environment);
278
443
  const llama = llamaOverride ? {
279
444
  path: resolve(llamaOverride),
280
445
  artifactSource: "explicit-override"
446
+ } : paths.nativeSelectionRoot ? {
447
+ path: koedRuntimeLlamaServer,
448
+ artifactSource: "koed-home-runtime"
281
449
  } : chooseRuntimePath([
282
450
  {
283
451
  path: koedRuntimeLlamaServer,
@@ -326,9 +494,9 @@ var missingRuntime = (runtime, missing) => ({
326
494
  },
327
495
  paths: runtime
328
496
  });
329
- var isExecutable = (path) => {
497
+ var isExecutable = (path2) => {
330
498
  try {
331
- return (statSync(path).mode & 73) !== 0;
499
+ return (statSync(path2).mode & 73) !== 0;
332
500
  } catch {
333
501
  return true;
334
502
  }
@@ -353,7 +521,7 @@ var localEmbeddingEnv = (runtime) => ({
353
521
  EMBEDDING_LLAMA_SERVER_BINARY: runtime.llamaServerBin
354
522
  });
355
523
  var collectLocalEmbeddingRuntimeStatus = async (paths, environment = process.env, dependencies = {}) => {
356
- const exists = dependencies.existsSync ?? existsSync2;
524
+ const exists = dependencies.existsSync ?? existsSync3;
357
525
  const fetcher = dependencies.fetch ?? globalThis.fetch.bind(globalThis);
358
526
  const runtime = resolveLocalEmbeddingRuntimePaths(paths, environment, exists, dependencies.appRuntime);
359
527
  const missing = runtimeMissing(runtime, exists);
@@ -405,7 +573,7 @@ var collectLocalEmbeddingRuntimeStatus = async (paths, environment = process.env
405
573
  }
406
574
  };
407
575
  var startLocalEmbeddingRuntime = (paths, environment = process.env, dependencies = {}) => {
408
- const exists = dependencies.existsSync ?? existsSync2;
576
+ const exists = dependencies.existsSync ?? existsSync3;
409
577
  const spawn = dependencies.spawn ?? nodeSpawn;
410
578
  const runtime = resolveLocalEmbeddingRuntimePaths(paths, environment, exists, dependencies.appRuntime);
411
579
  const env = {
@@ -419,6 +587,8 @@ var startLocalEmbeddingRuntime = (paths, environment = process.env, dependencies
419
587
  }
420
588
  const child = spawn(process.execPath, [runtime.serviceEntry], {
421
589
  cwd: runtime.appDir,
590
+ // The release supervisor can stop its owned llama-server descendants together.
591
+ ...paths.nativeSelectionRoot ? { detached: true } : {},
422
592
  env,
423
593
  stdio: "inherit"
424
594
  });
@@ -445,12 +615,12 @@ var startLocalEmbeddingRuntime = (paths, environment = process.env, dependencies
445
615
  };
446
616
 
447
617
  // packages/koed-server/dist/local-privacy-runtime.js
448
- import { existsSync as existsSync3 } from "node:fs";
618
+ import { existsSync as existsSync4 } from "node:fs";
449
619
  import { spawn as nodeSpawn2 } from "node:child_process";
450
620
  import { dirname as dirname2, resolve as resolve3 } from "node:path";
451
621
 
452
622
  // packages/koed-server/dist/privacy-installation-record.js
453
- import { closeSync, constants, fstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
623
+ import { closeSync, constants, fstatSync, mkdirSync as mkdirSync2, openSync, readFileSync as readFileSync2, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
454
624
  import { resolve as resolve2 } from "node:path";
455
625
 
456
626
  // packages/koed-server/dist/privacy-inference.js
@@ -474,7 +644,7 @@ function readPrivacyInstallationRecord(paths, generationId, manifestDigest) {
474
644
  const stat = fstatSync(descriptor);
475
645
  if (!stat.isFile() || stat.size > 32768)
476
646
  return null;
477
- const value = JSON.parse(readFileSync(descriptor, "utf8"));
647
+ const value = JSON.parse(readFileSync2(descriptor, "utf8"));
478
648
  if (value.schemaVersion !== 1 || value.generationId !== generationId || value.manifestDigest !== manifestDigest || value.modelRevision !== PINNED_PRIVACY_MODEL_REVISION || typeof value.verifiedAt !== "string" || !Number.isFinite(Date.parse(value.verifiedAt)) || !value.compatibility || !isPrivacyInferenceVerification(value.verification))
479
649
  return null;
480
650
  return value;
@@ -514,13 +684,13 @@ var runtimePaths = (paths, environment, selectedRuntime) => {
514
684
  };
515
685
  };
516
686
  var collectLocalPrivacyHealth = async (paths, environment = process.env, dependencies = {}, modelPath, includeDiagnostics = true) => {
517
- const exists = dependencies.existsSync ?? existsSync3;
687
+ const exists = dependencies.existsSync ?? existsSync4;
518
688
  const env = localPrivacyEnv(paths, environment, dependencies.appRuntime);
519
689
  const runtime = runtimePaths(paths, environment, dependencies.appRuntime);
520
690
  const missing = [
521
691
  ...runtime.entry ? [runtime.entry] : ["authenticated privacy generation"],
522
692
  runtime.bootstrap
523
- ].filter((path) => path.startsWith("authenticated ") || !exists(path));
693
+ ].filter((path2) => path2.startsWith("authenticated ") || !exists(path2));
524
694
  if (missing.length > 0) {
525
695
  return {
526
696
  runtime: "native-privacy",
@@ -576,12 +746,12 @@ var collectLocalPrivacyHealth = async (paths, environment = process.env, depende
576
746
  };
577
747
  var collectLocalPrivacyRuntimeHealthStatus = async (paths, environment = process.env, dependencies = {}) => collectLocalPrivacyHealth(paths, environment, dependencies, void 0, false);
578
748
  var collectLocalPrivacyRuntimeStatus = async (paths, environment = process.env, dependencies = {}) => {
579
- const exists = dependencies.existsSync ?? existsSync3;
749
+ const exists = dependencies.existsSync ?? existsSync4;
580
750
  const runtime = runtimePaths(paths, environment, dependencies.appRuntime);
581
751
  const missing = [
582
752
  ...runtime.entry ? [runtime.entry] : ["authenticated privacy generation"],
583
753
  runtime.bootstrap
584
- ].filter((path) => path.startsWith("authenticated ") || !exists(path));
754
+ ].filter((path2) => path2.startsWith("authenticated ") || !exists(path2));
585
755
  if (missing.length > 0) {
586
756
  return {
587
757
  runtime: "native-privacy",
@@ -609,7 +779,7 @@ var startLocalPrivacyRuntime = async (paths, environment = process.env, dependen
609
779
  ...localPrivacyEnv(paths, environment, dependencies.appRuntime)
610
780
  };
611
781
  const runtime = runtimePaths(paths, environment, dependencies.appRuntime);
612
- const exists = dependencies.existsSync ?? existsSync3;
782
+ const exists = dependencies.existsSync ?? existsSync4;
613
783
  if (!runtime.entry || !exists(runtime.entry) || !exists(runtime.bootstrap)) {
614
784
  const status = await collectLocalPrivacyRuntimeStatus(paths, env, {
615
785
  existsSync: exists,
@@ -646,21 +816,26 @@ var startLocalPrivacyRuntime = async (paths, environment = process.env, dependen
646
816
  };
647
817
 
648
818
  // packages/koed-server/dist/local-postgres-runtime.js
649
- import { existsSync as existsSync4, mkdirSync as mkdirSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
819
+ import { existsSync as existsSync5, mkdirSync as mkdirSync3, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "node:fs";
650
820
  import { dirname as dirname3, resolve as resolve4 } from "node:path";
651
821
  import { spawnSync as nodeSpawnSync } from "node:child_process";
652
822
  var trim3 = (value) => {
653
823
  const trimmed = value?.trim();
654
824
  return trimmed ? trimmed : void 0;
655
825
  };
656
- var hasAnyPostgresBinary = (binDir, exists = existsSync4) => ["initdb", "pg_ctl", "psql"].some((name) => exists(resolve4(binDir, name)));
657
- var resolvePostgresBinDir = (paths, environment = process.env, exists = existsSync4) => {
826
+ var hasCompletePostgresOverride = (environment) => Boolean(trim3(environment.KOED_POSTGRES_BIN_DIR) || [
827
+ environment.KOED_POSTGRES_INITDB_BIN,
828
+ environment.KOED_POSTGRES_PG_CTL_BIN,
829
+ environment.KOED_POSTGRES_PSQL_BIN
830
+ ].every(trim3));
831
+ var hasAnyPostgresBinary = (binDir, exists = existsSync5) => ["initdb", "pg_ctl", "psql"].some((name) => exists(resolve4(binDir, name)));
832
+ var resolvePostgresBinDir = (paths, environment = process.env, exists = existsSync5) => {
658
833
  const override = trim3(environment.KOED_POSTGRES_BIN_DIR);
659
834
  if (override) {
660
835
  return { binDir: resolve4(override), artifactSource: "explicit-override" };
661
836
  }
662
- const koedRuntimeDir = resolve4(paths.koedHome, "runtime", "postgres", "bin");
663
- if (hasAnyPostgresBinary(koedRuntimeDir, exists)) {
837
+ const koedRuntimeDir = resolve4(paths.nativeSelectionRoot ?? resolve4(paths.koedHome, "runtime"), "postgres", "bin");
838
+ if (paths.nativeSelectionRoot || hasAnyPostgresBinary(koedRuntimeDir, exists)) {
664
839
  return { binDir: koedRuntimeDir, artifactSource: "koed-home-runtime" };
665
840
  }
666
841
  const packagedRuntimeRoot = resolvePackagedKoedRuntimeRoot(environment);
@@ -674,7 +849,7 @@ var resolvePostgresBinDir = (paths, environment = process.env, exists = existsSy
674
849
  }
675
850
  return { binDir: koedRuntimeDir, artifactSource: "koed-home-runtime" };
676
851
  };
677
- var resolveLocalPostgresRuntimePaths = (paths, environment = process.env, exists = existsSync4) => {
852
+ var resolveLocalPostgresRuntimePaths = (paths, environment = process.env, exists = existsSync5) => {
678
853
  const { binDir, artifactSource } = resolvePostgresBinDir(paths, environment, exists);
679
854
  const hasBinaryOverride = Boolean(trim3(environment.KOED_POSTGRES_INITDB_BIN) ?? trim3(environment.KOED_POSTGRES_PG_CTL_BIN) ?? trim3(environment.KOED_POSTGRES_PSQL_BIN));
680
855
  const bin = (name, override) => resolve4(trim3(override) ?? resolve4(binDir, name));
@@ -767,7 +942,7 @@ var healthyStatus = (runtime, message) => ({
767
942
  paths: safeRuntimePaths(runtime)
768
943
  });
769
944
  var collectLocalPostgresRuntimeStatus = (paths, environment = process.env, dependencies = {}) => {
770
- const exists = dependencies.existsSync ?? existsSync4;
945
+ const exists = dependencies.existsSync ?? existsSync5;
771
946
  const spawnSync = dependencies.spawnSync ?? nodeSpawnSync;
772
947
  const runtime = resolveLocalPostgresRuntimePaths(paths, environment, exists);
773
948
  const missing = runtimeMissing2(runtime, exists);
@@ -796,7 +971,7 @@ var collectLocalPostgresRuntimeStatus = (paths, environment = process.env, depen
796
971
  };
797
972
  };
798
973
  var stopLocalPostgresRuntime = (paths, environment = process.env, dependencies = {}) => {
799
- const exists = dependencies.existsSync ?? existsSync4;
974
+ const exists = dependencies.existsSync ?? existsSync5;
800
975
  const spawnSync = dependencies.spawnSync ?? nodeSpawnSync;
801
976
  const runtime = resolveLocalPostgresRuntimePaths(paths, environment, exists);
802
977
  if (!exists(runtime.pgCtlBin)) {
@@ -838,7 +1013,7 @@ var stopLocalPostgresRuntime = (paths, environment = process.env, dependencies =
838
1013
  };
839
1014
  };
840
1015
  var startLocalPostgresRuntime = (paths, environment = process.env, dependencies = {}) => {
841
- const exists = dependencies.existsSync ?? existsSync4;
1016
+ const exists = dependencies.existsSync ?? existsSync5;
842
1017
  const spawnSync = dependencies.spawnSync ?? nodeSpawnSync;
843
1018
  const runtime = resolveLocalPostgresRuntimePaths(paths, environment, exists);
844
1019
  const env = {
@@ -860,12 +1035,12 @@ var startLocalPostgresRuntime = (paths, environment = process.env, dependencies
860
1035
  if (versionStatus) {
861
1036
  return { ok: false, started: false, status: versionStatus, env };
862
1037
  }
863
- mkdirSync2(runtime.dataDir, { recursive: true, mode: 448 });
864
- mkdirSync2(runtime.runDir, { recursive: true, mode: 448 });
865
- mkdirSync2(dirname3(runtime.logPath), { recursive: true, mode: 448 });
1038
+ mkdirSync3(runtime.dataDir, { recursive: true, mode: 448 });
1039
+ mkdirSync3(runtime.runDir, { recursive: true, mode: 448 });
1040
+ mkdirSync3(dirname3(runtime.logPath), { recursive: true, mode: 448 });
866
1041
  if (!exists(resolve4(runtime.dataDir, "PG_VERSION"))) {
867
1042
  const pwfile = resolve4(runtime.runDir, "postgres.pw");
868
- writeFileSync2(pwfile, `${runtime.password}
1043
+ writeFileSync3(pwfile, `${runtime.password}
869
1044
  `, { mode: 384 });
870
1045
  const init = run(runtime.initdbBin, [
871
1046
  "-D",
@@ -876,7 +1051,7 @@ var startLocalPostgresRuntime = (paths, environment = process.env, dependencies
876
1051
  "--pwfile",
877
1052
  pwfile
878
1053
  ], env, spawnSync);
879
- rmSync2(pwfile, { force: true });
1054
+ rmSync3(pwfile, { force: true });
880
1055
  if (init.status !== 0) {
881
1056
  return {
882
1057
  ok: false,
@@ -1017,24 +1192,24 @@ var startLocalPostgresRuntime = (paths, environment = process.env, dependencies
1017
1192
 
1018
1193
  // packages/koed-server/dist/pi-setup.js
1019
1194
  import { spawnSync as nodeSpawnSync2 } from "node:child_process";
1020
- import { accessSync as accessSync2, constants as constants3, cpSync as cpSync2, existsSync as existsSync7, realpathSync, rmSync as rmSync4, statSync as statSync3 } from "node:fs";
1195
+ import { accessSync as accessSync2, constants as constants3, cpSync as cpSync2, existsSync as existsSync8, realpathSync, rmSync as rmSync5, statSync as statSync3 } from "node:fs";
1021
1196
  import { dirname as dirname6, delimiter as delimiter2, isAbsolute as isAbsolute2, join as join2, resolve as resolve7 } from "node:path";
1022
1197
 
1023
1198
  // packages/koed-server/dist/pi-package-transaction.mjs
1024
- import { randomUUID } from "node:crypto";
1025
- import { cpSync, existsSync as existsSync5, mkdirSync as mkdirSync3, renameSync as renameSync2, rmSync as rmSync3 } from "node:fs";
1199
+ import { randomUUID as randomUUID2 } from "node:crypto";
1200
+ import { cpSync, existsSync as existsSync6, mkdirSync as mkdirSync4, renameSync as renameSync3, rmSync as rmSync4 } from "node:fs";
1026
1201
  import { dirname as dirname4, resolve as resolve5 } from "node:path";
1027
1202
  var piPackageFileSystem = {
1028
1203
  copy: (source, target) => cpSync(source, target, { recursive: true }),
1029
- exists: existsSync5,
1030
- mkdir: (target) => mkdirSync3(target, { recursive: true, mode: 448 }),
1031
- rename: renameSync2,
1032
- remove: (target) => rmSync3(target, { recursive: true, force: true })
1204
+ exists: existsSync6,
1205
+ mkdir: (target) => mkdirSync4(target, { recursive: true, mode: 448 }),
1206
+ rename: renameSync3,
1207
+ remove: (target) => rmSync4(target, { recursive: true, force: true })
1033
1208
  };
1034
1209
  var errorMessage = (error) => error instanceof Error ? error.message : String(error);
1035
1210
  var installPiPackageTransaction = (input) => {
1036
1211
  const fileSystem = input.fileSystem ?? piPackageFileSystem;
1037
- const suffix = input.suffix ?? `${Date.now()}-${randomUUID()}`;
1212
+ const suffix = input.suffix ?? `${Date.now()}-${randomUUID2()}`;
1038
1213
  const staged = `${input.target}.stage-${suffix}`;
1039
1214
  const backup = `${input.target}.backup-${suffix}`;
1040
1215
  let previousMoved = false;
@@ -1122,8 +1297,8 @@ var installPiPackageTransaction = (input) => {
1122
1297
  };
1123
1298
 
1124
1299
  // packages/koed-server/dist/ai-client-registry.js
1125
- import { accessSync, chmodSync, constants as constants2, existsSync as existsSync6, lstatSync, mkdirSync as mkdirSync4, readFileSync as readFileSync2, renameSync as renameSync3, statSync as statSync2, unlinkSync, writeFileSync as writeFileSync3 } from "node:fs";
1126
- import { randomUUID as randomUUID2 } from "node:crypto";
1300
+ import { accessSync, chmodSync, constants as constants2, existsSync as existsSync7, lstatSync, mkdirSync as mkdirSync5, readFileSync as readFileSync3, renameSync as renameSync4, statSync as statSync2, unlinkSync, writeFileSync as writeFileSync4 } from "node:fs";
1301
+ import { randomUUID as randomUUID3 } from "node:crypto";
1127
1302
  import { homedir } from "node:os";
1128
1303
  import { delimiter, dirname as dirname5, isAbsolute, join, resolve as resolve6 } from "node:path";
1129
1304
  var platformExecutableSearchDirectories = (environment, platform = process.platform) => platform === "darwin" ? [
@@ -1153,7 +1328,7 @@ var resolveExecutablePath = (requestedPath, environment, dependencies = {}, addi
1153
1328
  if (!requested)
1154
1329
  throw new Error("AI Client executable path is empty.");
1155
1330
  const fs = {
1156
- existsSync: existsSync6,
1331
+ existsSync: existsSync7,
1157
1332
  statSync: statSync2,
1158
1333
  accessSync,
1159
1334
  ...dependencies
@@ -1195,7 +1370,7 @@ var captureAiClientRegistry = (environment) => {
1195
1370
  }
1196
1371
  return {
1197
1372
  exists: true,
1198
- content: readFileSync2(target, "utf8"),
1373
+ content: readFileSync3(target, "utf8"),
1199
1374
  mode: stats.mode & 511
1200
1375
  };
1201
1376
  } catch (error) {
@@ -1221,8 +1396,8 @@ var restoreAiClientRegistry = (environment, snapshot) => {
1221
1396
  }
1222
1397
  if (snapshot.content === null)
1223
1398
  throw new Error("Registry snapshot is empty.");
1224
- mkdirSync4(dirname5(target), { recursive: true, mode: 448 });
1225
- writeFileSync3(target, snapshot.content, { mode: snapshot.mode ?? 384 });
1399
+ mkdirSync5(dirname5(target), { recursive: true, mode: 448 });
1400
+ writeFileSync4(target, snapshot.content, { mode: snapshot.mode ?? 384 });
1226
1401
  chmodSync(target, snapshot.mode ?? 384);
1227
1402
  };
1228
1403
  var readRegistry = (target) => {
@@ -1238,7 +1413,7 @@ var readRegistry = (target) => {
1238
1413
  }
1239
1414
  let parsed;
1240
1415
  try {
1241
- parsed = JSON.parse(readFileSync2(target, "utf8"));
1416
+ parsed = JSON.parse(readFileSync3(target, "utf8"));
1242
1417
  } catch (error) {
1243
1418
  throw new Error(`AI Client instance registry is malformed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1244
1419
  }
@@ -1263,7 +1438,7 @@ var assertAiClientRegistryWritable = (environment) => {
1263
1438
  readRegistry(registryPath(environment));
1264
1439
  };
1265
1440
  var writeRegistry = (target, root) => {
1266
- mkdirSync4(dirname5(target), { recursive: true, mode: 448 });
1441
+ mkdirSync5(dirname5(target), { recursive: true, mode: 448 });
1267
1442
  try {
1268
1443
  if (lstatSync(target).isSymbolicLink()) {
1269
1444
  throw new Error("AI Client instance registry must not be a symbolic link.");
@@ -1272,14 +1447,14 @@ var writeRegistry = (target, root) => {
1272
1447
  if (error.code !== "ENOENT")
1273
1448
  throw error;
1274
1449
  }
1275
- const temporary = `${target}.${process.pid}.${randomUUID2()}.tmp`;
1276
- writeFileSync3(temporary, `${JSON.stringify(root, null, 2)}
1450
+ const temporary = `${target}.${process.pid}.${randomUUID3()}.tmp`;
1451
+ writeFileSync4(temporary, `${JSON.stringify(root, null, 2)}
1277
1452
  `, {
1278
1453
  mode: 384,
1279
1454
  flag: "wx"
1280
1455
  });
1281
1456
  chmodSync(temporary, 384);
1282
- renameSync3(temporary, target);
1457
+ renameSync4(temporary, target);
1283
1458
  chmodSync(target, 384);
1284
1459
  };
1285
1460
  var removeExplicitAiClient = (input) => {
@@ -1303,7 +1478,7 @@ var registerExplicitAiClient = (input) => {
1303
1478
  driverId: input.driverId,
1304
1479
  displayName: input.displayName,
1305
1480
  executablePath,
1306
- ...input.configHome && existsSync6(input.configHome) ? { configHome: resolve6(input.configHome) } : {}
1481
+ ...input.configHome && existsSync7(input.configHome) ? { configHome: resolve6(input.configHome) } : {}
1307
1482
  };
1308
1483
  writeRegistry(target, {
1309
1484
  version: 1,
@@ -1334,9 +1509,9 @@ var migrateKoedOwnedCodexRegistration = (input) => {
1334
1509
  return false;
1335
1510
  }
1336
1511
  const configPath = resolve6(environment.CODEX_CONFIG_PATH ?? join(environment.CODEX_HOME ?? join(homedir(), ".codex"), "config.toml"));
1337
- if (!existsSync6(configPath))
1512
+ if (!existsSync7(configPath))
1338
1513
  return false;
1339
- const content = (input.readFileSync ?? readFileSync2)(configPath, "utf8");
1514
+ const content = (input.readFileSync ?? readFileSync3)(configPath, "utf8");
1340
1515
  if (parseCodexOwnershipBlock(content).kind !== "valid")
1341
1516
  return false;
1342
1517
  const executablePath = resolveCodexExecutablePath(environment);
@@ -1419,7 +1594,7 @@ var resolvePiSetupNodeEntry = (candidate, platform = process.platform) => {
1419
1594
  if (platform !== "win32" || !WINDOWS_PI_SHIM_EXTENSIONS.has(candidate.slice(candidate.lastIndexOf(".")).toLowerCase()))
1420
1595
  return candidate;
1421
1596
  const entry = join2(dirname6(candidate), "node_modules", "@earendil-works", "pi-coding-agent", "dist", "cli.js");
1422
- if (existsSync7(entry) && statSync3(entry).isFile())
1597
+ if (existsSync8(entry) && statSync3(entry).isFile())
1423
1598
  return realpathSync(entry);
1424
1599
  throw new Error(`Pi launcher ${candidate} cannot be executed safely. Install Pi through npm with a verifiable package entry or configure a native executable.`);
1425
1600
  };
@@ -1439,9 +1614,9 @@ var resolvePiSetupLauncher = (environment = process.env, platform = process.plat
1439
1614
  for (const directory of directories) {
1440
1615
  if (!isAbsolute2(directory))
1441
1616
  continue;
1442
- candidate = executableNames(platform).map((name) => join2(directory, name)).find((path) => {
1617
+ candidate = executableNames(platform).map((name) => join2(directory, name)).find((path2) => {
1443
1618
  try {
1444
- return statSync3(path).isFile();
1619
+ return statSync3(path2).isFile();
1445
1620
  } catch {
1446
1621
  return false;
1447
1622
  }
@@ -1491,7 +1666,7 @@ var removePi = (environment = process.env, spawnSync = nodeSpawnSync2) => {
1491
1666
  });
1492
1667
  };
1493
1668
  runPiForRollback = runPi;
1494
- if (existsSync7(target)) {
1669
+ if (existsSync8(target)) {
1495
1670
  backup = `${target}.remove-backup-${process.pid}-${Date.now()}`;
1496
1671
  cpSync2(target, backup, { recursive: true });
1497
1672
  profileRemovalAttempted = true;
@@ -1508,9 +1683,9 @@ var removePi = (environment = process.env, spawnSync = nodeSpawnSync2) => {
1508
1683
  if (piPackageIsListed(listed.stdout ?? "", target)) {
1509
1684
  throw new Error("Pi active profile still references Koed package after removal.");
1510
1685
  }
1511
- if (existsSync7(target))
1512
- rmSync4(target, { recursive: true, force: false });
1513
- if (existsSync7(target)) {
1686
+ if (existsSync8(target))
1687
+ rmSync5(target, { recursive: true, force: false });
1688
+ if (existsSync8(target)) {
1514
1689
  throw new Error("Koed Pi package directory could not be removed.");
1515
1690
  }
1516
1691
  removeExplicitAiClient({
@@ -1518,7 +1693,7 @@ var removePi = (environment = process.env, spawnSync = nodeSpawnSync2) => {
1518
1693
  driverId: "pi"
1519
1694
  });
1520
1695
  if (backup) {
1521
- rmSync4(backup, { recursive: true, force: false });
1696
+ rmSync5(backup, { recursive: true, force: false });
1522
1697
  backup = null;
1523
1698
  }
1524
1699
  return {
@@ -1536,10 +1711,10 @@ var removePi = (environment = process.env, spawnSync = nodeSpawnSync2) => {
1536
1711
  ];
1537
1712
  if (backup) {
1538
1713
  try {
1539
- if (existsSync7(target))
1540
- rmSync4(target, { recursive: true, force: true });
1714
+ if (existsSync8(target))
1715
+ rmSync5(target, { recursive: true, force: true });
1541
1716
  cpSync2(backup, target, { recursive: true });
1542
- rmSync4(backup, { recursive: true, force: true });
1717
+ rmSync5(backup, { recursive: true, force: true });
1543
1718
  } catch (restoreError) {
1544
1719
  failures.push(`Pi package rollback failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`);
1545
1720
  }
@@ -1603,10 +1778,10 @@ var setupPi = async (environment = process.env, spawnSync = nodeSpawnSync2, opti
1603
1778
  models: []
1604
1779
  }, void 0, options.desktopRuntimeCapability) : resolveKoedAppRuntime(paths, environment);
1605
1780
  const sourceCandidates = runtime.kind === "source" ? [resolve7(runtime.root, "packages/mcp-server/integrations/pi")] : [
1606
- resolve7(runtime.root, "node_modules/@koed/mcp-server/integrations/pi"),
1781
+ resolve7(runtime.root, "node_modules/@koed-labs/mcp-server/integrations/pi"),
1607
1782
  resolve7(runtime.root, "mcp-server/integrations/pi")
1608
1783
  ];
1609
- const source = sourceCandidates.find(existsSync7);
1784
+ const source = sourceCandidates.find(existsSync8);
1610
1785
  const target = resolve7(paths.koedHome, "integrations/pi");
1611
1786
  const requestedExecutable = environment.KOED_PI_EXECUTABLE?.trim() || "pi";
1612
1787
  const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -1731,14 +1906,14 @@ var setupPi = async (environment = process.env, spawnSync = nodeSpawnSync2, opti
1731
1906
 
1732
1907
  // packages/koed-server/dist/claude-setup.js
1733
1908
  import { spawnSync as nodeSpawnSync3 } from "node:child_process";
1734
- import { chmodSync as chmodSync2, existsSync as existsSync9, mkdirSync as mkdirSync6, readFileSync as readFileSync4, unlinkSync as unlinkSync3, writeFileSync as writeFileSync5 } from "node:fs";
1909
+ import { chmodSync as chmodSync2, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync5, unlinkSync as unlinkSync3, writeFileSync as writeFileSync6 } from "node:fs";
1735
1910
  import { homedir as homedir2 } from "node:os";
1736
1911
  import { dirname as dirname8, resolve as resolve10 } from "node:path";
1737
1912
 
1738
1913
  // packages/koed-server/dist/claude-background-settings.mjs
1739
- import { randomUUID as randomUUID3 } from "node:crypto";
1914
+ import { randomUUID as randomUUID4 } from "node:crypto";
1740
1915
  import { Buffer } from "node:buffer";
1741
- import { closeSync as closeSync2, constants as constants4, existsSync as existsSync8, fstatSync as fstatSync2, lstatSync as lstatSync2, mkdirSync as mkdirSync5, openSync as openSync2, readFileSync as readFileSync3, renameSync as renameSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "node:fs";
1916
+ import { closeSync as closeSync2, constants as constants4, existsSync as existsSync9, fstatSync as fstatSync2, lstatSync as lstatSync2, mkdirSync as mkdirSync6, openSync as openSync2, readFileSync as readFileSync4, renameSync as renameSync5, unlinkSync as unlinkSync2, writeFileSync as writeFileSync5 } from "node:fs";
1742
1917
  import { basename, dirname as dirname7, join as join3, resolve as resolve8 } from "node:path";
1743
1918
  import process2 from "node:process";
1744
1919
  var CLAUDE_BACKGROUND_THRESHOLD = "CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS";
@@ -1746,10 +1921,10 @@ var disableKey = "CLAUDE_CODE_DISABLE_BACKGROUND_TASKS";
1746
1921
  var disabled = (value) => ["1", "true", "yes", "on"].includes(String(value ?? "").trim().toLowerCase());
1747
1922
  var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
1748
1923
  var object = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
1749
- var assertTarget = (path, privateFile) => {
1924
+ var assertTarget = (path2, privateFile) => {
1750
1925
  let stat;
1751
1926
  try {
1752
- stat = lstatSync2(path);
1927
+ stat = lstatSync2(path2);
1753
1928
  } catch (error) {
1754
1929
  if (error.code === "ENOENT")
1755
1930
  return;
@@ -1758,39 +1933,39 @@ var assertTarget = (path, privateFile) => {
1758
1933
  if (!stat.isFile() || stat.isSymbolicLink() || typeof process2.getuid === "function" && stat.uid !== process2.getuid() || privateFile && process2.platform !== "win32" && (stat.mode & 63) !== 0)
1759
1934
  throw new Error("Claude configuration target is not a protected owned regular file");
1760
1935
  };
1761
- var readProtectedJournal = (path) => {
1762
- assertTarget(path, true);
1763
- if (!existsSync8(path))
1936
+ var readProtectedJournal = (path2) => {
1937
+ assertTarget(path2, true);
1938
+ if (!existsSync9(path2))
1764
1939
  return null;
1765
- const fd = openSync2(path, constants4.O_RDONLY | (process2.platform === "win32" ? 0 : constants4.O_NOFOLLOW));
1940
+ const fd = openSync2(path2, constants4.O_RDONLY | (process2.platform === "win32" ? 0 : constants4.O_NOFOLLOW));
1766
1941
  try {
1767
1942
  const stat = fstatSync2(fd);
1768
1943
  if (!stat.isFile() || stat.size > 65536 || typeof process2.getuid === "function" && stat.uid !== process2.getuid() || process2.platform !== "win32" && (stat.mode & 63) !== 0)
1769
1944
  throw new Error("Claude background recall journal is not a bounded protected owned file");
1770
- return readFileSync3(fd, "utf8");
1945
+ return readFileSync4(fd, "utf8");
1771
1946
  } finally {
1772
1947
  closeSync2(fd);
1773
1948
  }
1774
1949
  };
1775
- var writeAtomic = (path, content, privateFile) => {
1776
- assertTarget(path, privateFile);
1777
- mkdirSync5(dirname7(path), { recursive: true, mode: 448 });
1778
- const temporary = join3(dirname7(path), `.${basename(path)}.${randomUUID3()}.tmp`);
1950
+ var writeAtomic = (path2, content, privateFile) => {
1951
+ assertTarget(path2, privateFile);
1952
+ mkdirSync6(dirname7(path2), { recursive: true, mode: 448 });
1953
+ const temporary = join3(dirname7(path2), `.${basename(path2)}.${randomUUID4()}.tmp`);
1779
1954
  try {
1780
- writeFileSync4(temporary, content, { mode: 384, flag: "wx" });
1781
- assertTarget(path, privateFile);
1782
- renameSync4(temporary, path);
1955
+ writeFileSync5(temporary, content, { mode: 384, flag: "wx" });
1956
+ assertTarget(path2, privateFile);
1957
+ renameSync5(temporary, path2);
1783
1958
  } finally {
1784
- if (existsSync8(temporary))
1959
+ if (existsSync9(temporary))
1785
1960
  unlinkSync2(temporary);
1786
1961
  }
1787
1962
  };
1788
- function writeClaudeSettingsFileAtomic(path, content) {
1789
- writeAtomic(path, content, false);
1963
+ function writeClaudeSettingsFileAtomic(path2, content) {
1964
+ writeAtomic(path2, content, false);
1790
1965
  }
1791
1966
  function captureClaudeBackgroundJournal(koedHome) {
1792
- const path = join3(koedHome, "config", "claude-background-recall.json");
1793
- return { path, content: readProtectedJournal(path) };
1967
+ const path2 = join3(koedHome, "config", "claude-background-recall.json");
1968
+ return { path: path2, content: readProtectedJournal(path2) };
1794
1969
  }
1795
1970
  function records(snapshot) {
1796
1971
  if (snapshot.content === null)
@@ -1810,7 +1985,7 @@ function writeClaudeBackgroundJournal(snapshot, content) {
1810
1985
  }
1811
1986
  readProtectedJournal(snapshot.path);
1812
1987
  if (content === null) {
1813
- if (existsSync8(snapshot.path))
1988
+ if (existsSync9(snapshot.path))
1814
1989
  unlinkSync2(snapshot.path);
1815
1990
  return;
1816
1991
  }
@@ -1903,12 +2078,12 @@ function parseClaudeOwnedMcpEntry(output, expectedMcpCli, expectedKoedHome) {
1903
2078
  }
1904
2079
 
1905
2080
  // packages/koed-server/dist/claude-setup.js
1906
- var writeClaudeSettings = (path, content, atomic) => {
2081
+ var writeClaudeSettings = (path2, content, atomic) => {
1907
2082
  if (atomic)
1908
- writeClaudeSettingsFileAtomic(path, content);
2083
+ writeClaudeSettingsFileAtomic(path2, content);
1909
2084
  else {
1910
- writeFileSync5(path, content, { mode: 384 });
1911
- chmodSync2(path, 384);
2085
+ writeFileSync6(path2, content, { mode: 384 });
2086
+ chmodSync2(path2, 384);
1912
2087
  }
1913
2088
  };
1914
2089
  var resolveClaudeExecutablePath = (environment, dependencies = {}, platform = process.platform) => resolveExecutablePathWithPlatformFallbacks(environment.KOED_CLAUDE_CODE_EXECUTABLE?.trim() || "claude", environment, dependencies, platform);
@@ -2030,7 +2205,7 @@ var removeClaude = (environment = process.env, spawnSync = nodeSpawnSync3) => {
2030
2205
  assertAiClientRegistryWritable(environment);
2031
2206
  executable = resolveClaudeExecutablePath(environment);
2032
2207
  registrySnapshot = captureAiClientRegistry(environment);
2033
- originalSettings = existsSync9(settingsPath) ? readFileSync4(settingsPath, "utf8") : null;
2208
+ originalSettings = existsSync10(settingsPath) ? readFileSync5(settingsPath, "utf8") : null;
2034
2209
  const settings = originalSettings ? JSON.parse(originalSettings) : {};
2035
2210
  backgroundSnapshot = captureClaudeBackgroundJournal(paths.koedHome);
2036
2211
  const backgroundRemoval = removeClaudeBackgroundRecall(settings, settingsPath, backgroundSnapshot);
@@ -2068,7 +2243,7 @@ var removeClaude = (environment = process.env, spawnSync = nodeSpawnSync3) => {
2068
2243
  if (settings.hooks && Object.keys(settings.hooks).length === 0) {
2069
2244
  delete settings.hooks;
2070
2245
  }
2071
- if (existsSync9(settingsPath)) {
2246
+ if (existsSync10(settingsPath)) {
2072
2247
  writeClaudeSettings(settingsPath, `${JSON.stringify(settings, null, 2)}
2073
2248
  `, backgroundSnapshot.content !== null);
2074
2249
  }
@@ -2167,7 +2342,7 @@ var setupClaude = async (environment = process.env, spawnSync = nodeSpawnSync3,
2167
2342
  try {
2168
2343
  assertAiClientRegistryWritable(environment);
2169
2344
  executable = resolveClaudeExecutablePath(environment);
2170
- if (!existsSync9(runtime.mcpCli) || !existsSync9(runtime.captureHook)) {
2345
+ if (!existsSync10(runtime.mcpCli) || !existsSync10(runtime.captureHook)) {
2171
2346
  return failure("Koed's Claude Code integration artifacts are missing.", "Repair Koed, then set up Claude Code integration again.");
2172
2347
  }
2173
2348
  const childEnvironment = claudeProcessEnvironment(environment);
@@ -2186,7 +2361,7 @@ var setupClaude = async (environment = process.env, spawnSync = nodeSpawnSync3,
2186
2361
  });
2187
2362
  const authenticationState = claudeAuthenticationState(auth);
2188
2363
  registrySnapshot = captureAiClientRegistry(environment);
2189
- originalSettings = existsSync9(settingsPath) ? readFileSync4(settingsPath, "utf8") : null;
2364
+ originalSettings = existsSync10(settingsPath) ? readFileSync5(settingsPath, "utf8") : null;
2190
2365
  const settings = originalSettings ? JSON.parse(originalSettings) : {};
2191
2366
  const background = options.backgroundRecall ? (() => {
2192
2367
  backgroundSnapshot = captureClaudeBackgroundJournal(paths.koedHome);
@@ -2211,8 +2386,8 @@ var setupClaude = async (environment = process.env, spawnSync = nodeSpawnSync3,
2211
2386
  if (existingMcp.status === 0) {
2212
2387
  const configPath = environment.CLAUDE_CONFIG_DIR?.trim() ? resolve10(environment.CLAUDE_CONFIG_DIR, ".claude.json") : resolve10(environment.HOME?.trim() || homedir2(), ".claude.json");
2213
2388
  previousMcpConfigPath = configPath;
2214
- if (existsSync9(configPath)) {
2215
- const config = JSON.parse(readFileSync4(configPath, "utf8"));
2389
+ if (existsSync10(configPath)) {
2390
+ const config = JSON.parse(readFileSync5(configPath, "utf8"));
2216
2391
  const entry = config.mcpServers?.[mcpName];
2217
2392
  if (entry)
2218
2393
  previousMcpJson = JSON.stringify(entry);
@@ -2260,7 +2435,7 @@ var setupClaude = async (environment = process.env, spawnSync = nodeSpawnSync3,
2260
2435
  }
2261
2436
  ];
2262
2437
  }
2263
- mkdirSync6(dirname8(settingsPath), { recursive: true, mode: 448 });
2438
+ mkdirSync7(dirname8(settingsPath), { recursive: true, mode: 448 });
2264
2439
  if (backgroundSnapshot && background)
2265
2440
  writeClaudeBackgroundJournal(backgroundSnapshot, background.journal);
2266
2441
  writeClaudeSettings(settingsPath, `${JSON.stringify(settings, null, 2)}
@@ -2304,7 +2479,7 @@ var setupClaude = async (environment = process.env, spawnSync = nodeSpawnSync3,
2304
2479
  let previousMcpUnchanged = false;
2305
2480
  if (!attemptedMcpAdd && previousMcpJson && previousMcpConfigPath) {
2306
2481
  try {
2307
- const config = JSON.parse(readFileSync4(previousMcpConfigPath, "utf8"));
2482
+ const config = JSON.parse(readFileSync5(previousMcpConfigPath, "utf8"));
2308
2483
  previousMcpUnchanged = JSON.stringify(config.mcpServers?.[mcpName]) === previousMcpJson;
2309
2484
  } catch {
2310
2485
  }
@@ -2343,7 +2518,7 @@ var setupClaude = async (environment = process.env, spawnSync = nodeSpawnSync3,
2343
2518
  } catch (restoreError) {
2344
2519
  failures.push(`Claude settings rollback failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`);
2345
2520
  }
2346
- } else if (existsSync9(settingsPath)) {
2521
+ } else if (existsSync10(settingsPath)) {
2347
2522
  try {
2348
2523
  unlinkSync3(settingsPath);
2349
2524
  } catch (restoreError) {
@@ -2462,15 +2637,41 @@ var defaultDependencies = () => ({
2462
2637
  desktopRuntimeCapability: null,
2463
2638
  fetch: globalThis.fetch.bind(globalThis),
2464
2639
  spawnSync: nodeSpawnSync4,
2465
- existsSync: existsSync10,
2466
- readFileSync: readFileSync5,
2640
+ existsSync: existsSync11,
2641
+ readFileSync: readFileSync6,
2467
2642
  resolvePiExecutable: resolvePiSetupExecutable,
2468
2643
  resolveClaudeExecutable: resolveClaudeExecutablePath,
2469
2644
  resolveCodexExecutable: resolveCodexExecutablePath,
2470
2645
  checkPid: isProcessRunning,
2471
2646
  delay: (milliseconds) => new Promise((resolve16) => setTimeout(resolve16, milliseconds)),
2472
- now: () => /* @__PURE__ */ new Date()
2647
+ now: () => /* @__PURE__ */ new Date(),
2648
+ revokeAiClientConnection
2473
2649
  });
2650
+ var captureConnectionNames = {
2651
+ codex: "Codex",
2652
+ claude: "Claude Code",
2653
+ pi: "Pi"
2654
+ };
2655
+ var captureConnectionStatus = (id, component, connections) => {
2656
+ const captureConnected = connections?.clients[id]?.connected === true;
2657
+ const details = {
2658
+ ...component.details ?? {},
2659
+ captureConnected
2660
+ };
2661
+ if (captureConnected || component.configured !== true)
2662
+ return { ...component, details };
2663
+ const state = component.state;
2664
+ if (state !== "healthy")
2665
+ return { ...component, details };
2666
+ const name = captureConnectionNames[id];
2667
+ return {
2668
+ ...component,
2669
+ state: "needs_attention",
2670
+ message: `${name} is set up, but Koed is not reading its conversations until you connect it.`,
2671
+ action: `Connect ${name} again in Koed Desktop, or run \`koed setup ${id}\`.`,
2672
+ details
2673
+ };
2674
+ };
2474
2675
  var runtimeSelections = /* @__PURE__ */ new WeakMap();
2475
2676
  var withDefaults = (dependencies = {}) => {
2476
2677
  const deps = { ...defaultDependencies(), ...dependencies };
@@ -2499,9 +2700,9 @@ var starting = (message, details) => ({
2499
2700
  message,
2500
2701
  ...details ? { details } : {}
2501
2702
  });
2502
- var readJsonFile = (path, reader = readFileSync5) => {
2703
+ var readJsonFile = (path2, reader = readFileSync6) => {
2503
2704
  try {
2504
- return JSON.parse(reader(path, "utf8"));
2705
+ return JSON.parse(reader(path2, "utf8"));
2505
2706
  } catch {
2506
2707
  return null;
2507
2708
  }
@@ -2539,7 +2740,7 @@ var inspectPi = (environment, paths, deps, refreshed) => {
2539
2740
  const versionText = version.stdout?.trim() ?? "";
2540
2741
  if (version.error || version.status !== 0) {
2541
2742
  return {
2542
- ...notConfigured("Pi is not installed or could not be started.", `Install Pi ${MINIMUM_PI_VERSION} or newer, then set up Pi integration.`),
2743
+ ...notConfigured("Pi is not installed or could not be started.", `Install Pi ${MINIMUM_PI_VERSION} or newer, then set up Pi integration.`, { inspectionState: "unknown" }),
2543
2744
  configured: false,
2544
2745
  detected: detectedFromConfig
2545
2746
  };
@@ -2694,7 +2895,7 @@ var inspectClaudeCode = async (environment, paths, deps) => {
2694
2895
  const versionText = version.stdout?.trim() ?? "";
2695
2896
  if (version.error || version.status !== 0) {
2696
2897
  return {
2697
- ...notConfigured("Claude Code is not installed or could not be started.", `Install Claude Code ${MINIMUM_CLAUDE_CODE_VERSION} or newer, then set up its integration.`),
2898
+ ...notConfigured("Claude Code is not installed or could not be started.", `Install Claude Code ${MINIMUM_CLAUDE_CODE_VERSION} or newer, then set up its integration.`, { inspectionState: "unknown" }),
2698
2899
  configured: false,
2699
2900
  detected: detectedFromConfig
2700
2901
  };
@@ -2741,6 +2942,21 @@ var inspectClaudeCode = async (environment, paths, deps) => {
2741
2942
  }
2742
2943
  const mcpConfigured = !mcp.error && mcp.status === 0;
2743
2944
  const captureConfigured = missingHooks.length === 0;
2945
+ const mcpAbsent = !mcp.error && mcp.status !== 0 && /(?:not found|does not exist|no .*mcp|unknown .*server|not configured)/i.test(`${mcp.stdout ?? ""}
2946
+ ${mcp.stderr ?? ""}`);
2947
+ if (!mcpConfigured && !mcpAbsent && captureConfigured) {
2948
+ return {
2949
+ ...needsAttention("Claude Code's MCP configuration could not be verified.", "Check again. If this persists, run `claude mcp get` in your terminal to diagnose the configuration.", {
2950
+ executable,
2951
+ version: versionText,
2952
+ settingsPath,
2953
+ mcpName,
2954
+ inspectionState: "unknown"
2955
+ }),
2956
+ configured: false,
2957
+ detected: true
2958
+ };
2959
+ }
2744
2960
  if (!mcpConfigured || !captureConfigured) {
2745
2961
  return {
2746
2962
  ...notConfigured("Claude Code's Koed MCP or Capture Hook configuration is incomplete.", "Set up Claude Code integration from Koed Desktop.", {
@@ -2792,7 +3008,10 @@ var withFetchTimeout = (fetcher, timeoutMs = 5e3) => {
2792
3008
  const controller = new AbortController();
2793
3009
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
2794
3010
  try {
2795
- return await fetcher(url, { ...init, signal: controller.signal });
3011
+ return await fetcher(url, {
3012
+ ...init,
3013
+ signal: init?.signal ? AbortSignal.any([controller.signal, init.signal]) : controller.signal
3014
+ });
2796
3015
  } catch (error) {
2797
3016
  if (error instanceof Error && error.name === "AbortError") {
2798
3017
  throw new Error(`API request timeout after ${timeoutMs}ms. Is koed-server running?`, { cause: error });
@@ -3121,7 +3340,16 @@ var inspectCodex = async (environment, paths, deps, memoryGuidanceEnabled) => {
3121
3340
  } catch {
3122
3341
  return authenticatedRuntimeUnavailable();
3123
3342
  }
3124
- const hasExpectedAdapter = mcpBlock.includes(JSON.stringify(runtime.mcpCli));
3343
+ const assignments = (key) => mcpBlock.split(/\r?\n/).filter((line) => new RegExp(`^\\s*${key}\\s*=`).test(line));
3344
+ const matchesAssignment = (key, value) => {
3345
+ const lines = assignments(key);
3346
+ if (lines.length !== 1)
3347
+ return false;
3348
+ const assignment = lines[0].trim();
3349
+ const expected = `${key} = ${value}`;
3350
+ return assignment.startsWith(expected) && /^(?:\s*(?:#.*)?)$/.test(assignment.slice(expected.length));
3351
+ };
3352
+ const hasExpectedAdapter = matchesAssignment("command", JSON.stringify(environment.MEMORY_NODE_COMMAND ?? "node")) && matchesAssignment("args", `[${JSON.stringify(runtime.mcpCli)}]`);
3125
3353
  const containsRetiredCredentials = tomlStringValue(mcpEnvBlock, "MEMORY_API_URL") !== null || tomlStringValue(mcpEnvBlock, "MEMORY_API_TOKEN") !== null;
3126
3354
  if (configuredKoedHome !== paths.koedHome || !hasExpectedAdapter) {
3127
3355
  return {
@@ -3129,7 +3357,8 @@ var inspectCodex = async (environment, paths, deps, memoryGuidanceEnabled) => {
3129
3357
  configuredKoedHome: configuredKoedHome ?? null,
3130
3358
  expectedKoedHome: paths.koedHome,
3131
3359
  expectedMcpAdapter: runtime.mcpCli,
3132
- codexConfigPath
3360
+ codexConfigPath,
3361
+ currentHomeAuthorized: false
3133
3362
  }),
3134
3363
  configured: true
3135
3364
  };
@@ -3234,7 +3463,7 @@ var inspectMcp = async (environment, paths, deps) => {
3234
3463
  const cliPath = appRuntime.mcpCli;
3235
3464
  if (!deps.existsSync(cliPath)) {
3236
3465
  const authenticatedGenerationMissing = appRuntime.missing.some((entry) => entry.startsWith("authenticated "));
3237
- return notConfigured(authenticatedGenerationMissing ? "No active authenticated Koed app-runtime generation is available." : appRuntime.kind === "packaged" ? "Packaged MCP Server artifact was not found." : "MCP Server build output was not found.", authenticatedGenerationMissing ? "Install and activate a compatible signed Koed app-runtime generation; status does not install or activate components." : appRuntime.kind === "packaged" ? "Install a compatible signed Koed app-runtime generation containing MCP Server and Supported Capture Hook artifacts." : "Run pnpm --filter @koed/mcp-server build or koed setup core --json.", {
3466
+ return notConfigured(authenticatedGenerationMissing ? "No active authenticated Koed app-runtime generation is available." : appRuntime.kind === "packaged" ? "Packaged MCP Server artifact was not found." : "MCP Server build output was not found.", authenticatedGenerationMissing ? "Install and activate a compatible signed Koed app-runtime generation; status does not install or activate components." : appRuntime.kind === "packaged" ? "Install a compatible signed Koed app-runtime generation containing MCP Server and Supported Capture Hook artifacts." : "Run pnpm --filter @koed-labs/mcp-server build or koed setup core --json.", {
3238
3467
  artifactSource: appRuntime.artifactSource,
3239
3468
  runtimeRoot: appRuntime.root,
3240
3469
  missing: appRuntime.missing
@@ -3441,6 +3670,95 @@ var localSynthesisReadiness = (snapshot, descriptor, profileAuthentication) => {
3441
3670
  }
3442
3671
  return current;
3443
3672
  };
3673
+ var historicalIngestionClients = ["codex", "claude", "pi"];
3674
+ var inspectHistoricalIngestion = (paths, deps) => {
3675
+ const now = deps.now().getTime();
3676
+ return Object.fromEntries(historicalIngestionClients.map((client) => {
3677
+ const file = resolve12(paths.koedHome, "state", `${client}-historical-ingestion.json`);
3678
+ let value;
3679
+ try {
3680
+ if (deps.existsSync(file))
3681
+ value = JSON.parse(String(deps.readFileSync(file, "utf8")));
3682
+ } catch {
3683
+ value = void 0;
3684
+ }
3685
+ return [client, summarizeHistoricalIngestionState(value, now)];
3686
+ }));
3687
+ };
3688
+ async function fetchHistoricalActivity(input) {
3689
+ const controller = new AbortController();
3690
+ let timer;
3691
+ try {
3692
+ return await Promise.race([
3693
+ lookupHistoricalActivity(input, controller.signal),
3694
+ new Promise((resolve16) => {
3695
+ timer = setTimeout(() => {
3696
+ controller.abort();
3697
+ resolve16(null);
3698
+ }, 2e3);
3699
+ })
3700
+ ]);
3701
+ } finally {
3702
+ clearTimeout(timer);
3703
+ }
3704
+ }
3705
+ async function lookupHistoricalActivity(input, signal) {
3706
+ try {
3707
+ const selected = /* @__PURE__ */ new Map();
3708
+ for (const client of historicalIngestionClients) {
3709
+ try {
3710
+ const state = JSON.parse(input.readFile(resolve12(input.koedHome, "state", `${client}-historical-ingestion.json`)));
3711
+ if (state.selectionFrozen === true && Array.isArray(state.selections))
3712
+ selected.set(client, new Set(state.selections.map((selection) => selection.candidateId).filter((id) => typeof id === "string")));
3713
+ } catch {
3714
+ }
3715
+ }
3716
+ if (!selected.size)
3717
+ return null;
3718
+ const headers = { authorization: `Bearer ${input.token}` };
3719
+ const listUrl = new URL("/v1/historical-imports?limit=20", input.apiUrl);
3720
+ const list = await input.fetcher(listUrl, { headers, signal });
3721
+ if (signal.aborted || !list.ok)
3722
+ return null;
3723
+ const body = await list.json();
3724
+ if (signal.aborted)
3725
+ return null;
3726
+ if (!Array.isArray(body.runs) || body.runs.length >= 20 || body.runs.some((run2) => typeof run2.id !== "string"))
3727
+ return null;
3728
+ const totals = {};
3729
+ for (const client of selected.keys())
3730
+ totals[client] = { recordsRead: 0, embedded: 0, eligible: 0 };
3731
+ const seen = /* @__PURE__ */ new Set();
3732
+ for (const run2 of body.runs) {
3733
+ const result = await input.fetcher(new URL(`/v1/historical-imports/${encodeURIComponent(run2.id)}`, input.apiUrl), { headers, signal });
3734
+ if (signal.aborted || !result.ok)
3735
+ return null;
3736
+ const detail = await result.json();
3737
+ if (signal.aborted || !Array.isArray(detail.run?.sources))
3738
+ return null;
3739
+ for (const source of detail.run.sources) {
3740
+ const { aiClient, sourceSessionId, id, rawIngestedRecordCount, embeddedEventCount, embeddingEligibleEventCount } = source;
3741
+ if (typeof aiClient !== "string" || typeof sourceSessionId !== "string" || !selected.get(aiClient)?.has(sourceSessionId))
3742
+ continue;
3743
+ if (typeof id !== "string" || seen.has(id))
3744
+ continue;
3745
+ if (![
3746
+ rawIngestedRecordCount,
3747
+ embeddedEventCount,
3748
+ embeddingEligibleEventCount
3749
+ ].every((n) => Number.isSafeInteger(n) && Number(n) >= 0))
3750
+ return null;
3751
+ seen.add(id);
3752
+ totals[aiClient].recordsRead += Number(rawIngestedRecordCount);
3753
+ totals[aiClient].embedded += Number(embeddedEventCount);
3754
+ totals[aiClient].eligible += Number(embeddingEligibleEventCount);
3755
+ }
3756
+ }
3757
+ return totals;
3758
+ } catch {
3759
+ return null;
3760
+ }
3761
+ }
3444
3762
  var inspectAiClientReadiness = (input) => {
3445
3763
  const clients = [
3446
3764
  {
@@ -3952,6 +4270,7 @@ var collectKoedServerStatus = async (environment = process.env, dependencies = {
3952
4270
  const capabilityReadModel = await fetchAiClientCapabilityReadModel(paths, runtimeEnvironment, repoEnv, apiUrl, fetcher);
3953
4271
  const embeddingState = !waitingForManagedRuntime ? await fetchEmbeddingState(paths, runtimeEnvironment, repoEnv, apiUrl, fetcher) : null;
3954
4272
  const localAiRuntime = inspectLocalAiRuntime(runtime, runtimeProcessRunning, serverConfig.runtimeMode, deps);
4273
+ const connectionsBefore = readAiClientConnections(paths.koedHome);
3955
4274
  const codex = await inspectSafely("Codex", () => inspectCodex(runtimeEnvironment, paths, deps, serverConfig.codexGlobalMemoryGuidanceEnabled), { state: "needs_attention", configured: false });
3956
4275
  const claudeCode = await inspectSafely("Claude Code", () => inspectClaudeCode(runtimeEnvironment, paths, deps), { state: "needs_attention", configured: false, detected: false });
3957
4276
  const pi = await inspectSafely("Pi", () => inspectPi(runtimeEnvironment, paths, deps, {
@@ -3959,6 +4278,30 @@ var collectKoedServerStatus = async (environment = process.env, dependencies = {
3959
4278
  refreshedSince: options.capabilitiesRefreshedSince,
3960
4279
  now: deps.now().toISOString()
3961
4280
  }), { state: "needs_attention", configured: false, detected: false });
4281
+ const observedConnection = (inspected) => {
4282
+ const details = inspected.details;
4283
+ if (details?.currentHomeAuthorized === false)
4284
+ return false;
4285
+ return details?.kind === "inspection_error" || details?.inspectionState === "unknown" ? void 0 : inspected.configured === true;
4286
+ };
4287
+ const inspectedClients = { codex, claude: claudeCode, pi };
4288
+ for (const id of Object.keys(inspectedClients)) {
4289
+ const before = connectionsBefore?.clients[id];
4290
+ if (before?.connected === true && observedConnection(inspectedClients[id]) === false) {
4291
+ try {
4292
+ deps.revokeAiClientConnection(paths.koedHome, id, {
4293
+ ifRevision: before.revision,
4294
+ now: deps.now()
4295
+ });
4296
+ } catch {
4297
+ }
4298
+ }
4299
+ }
4300
+ const connections = readAiClientConnections(paths.koedHome);
4301
+ const withCaptureConnection = (id, component) => captureConnectionStatus(id, component, connections);
4302
+ const codexStatus = withCaptureConnection("codex", codex);
4303
+ const claudeCodeStatus = withCaptureConnection("claude", claudeCode);
4304
+ const piStatus = withCaptureConnection("pi", pi);
3962
4305
  const captureHook = await inspectSafely("Supported Capture Hook", () => inspectCaptureHook(runtimeEnvironment, paths, deps), { state: "needs_attention" });
3963
4306
  const codexTranscriptWatcher = inspectCodexTranscriptWatcher(serverConfig.codexTranscriptWatcherEnabled, runtime, runtimeProcessRunning, deps);
3964
4307
  const mcpServer = await inspectMcp(runtimeEnvironment, paths, deps).catch(() => needsAttention("MCP Server status could not be inspected.", "Repair MCP Server integration, then refresh status.", { kind: "inspection_error" }));
@@ -4031,9 +4374,9 @@ var collectKoedServerStatus = async (environment = process.env, dependencies = {
4031
4374
  const readinessInput = {
4032
4375
  localAiClientInstances,
4033
4376
  localAiClientRegistryError,
4034
- codex,
4035
- claudeCode,
4036
- pi,
4377
+ codex: codexStatus,
4378
+ claudeCode: claudeCodeStatus,
4379
+ pi: piStatus,
4037
4380
  codexTranscriptWatcher,
4038
4381
  claudeTranscriptWatcher,
4039
4382
  piTranscriptWatcher,
@@ -4053,6 +4396,20 @@ var collectKoedServerStatus = async (environment = process.env, dependencies = {
4053
4396
  inspectDeviceIdentity(paths, environment),
4054
4397
  Promise.resolve(inspectUpstreamBackends(paths, deps))
4055
4398
  ]);
4399
+ const historicalIngestion = inspectHistoricalIngestion(paths, deps);
4400
+ const historicalToken = resolveActiveIntegrationApiToken(paths, runtimeEnvironment, repoEnv);
4401
+ const activity = historicalToken && runtimeProcessRunning ? await fetchHistoricalActivity({
4402
+ koedHome: paths.koedHome,
4403
+ apiUrl,
4404
+ token: historicalToken.token,
4405
+ fetcher,
4406
+ readFile: (file) => String(deps.readFileSync(file, "utf8"))
4407
+ }) : null;
4408
+ if (activity)
4409
+ for (const client of historicalIngestionClients) {
4410
+ if (activity[client])
4411
+ historicalIngestion[client].activity = activity[client];
4412
+ }
4056
4413
  const statusWithoutState = {
4057
4414
  ok: false,
4058
4415
  state: "starting",
@@ -4073,13 +4430,14 @@ var collectKoedServerStatus = async (environment = process.env, dependencies = {
4073
4430
  codexTranscriptWatcher,
4074
4431
  claudeTranscriptWatcher,
4075
4432
  piTranscriptWatcher,
4076
- codex,
4077
- claudeCode,
4078
- pi,
4433
+ codex: codexStatus,
4434
+ claudeCode: claudeCodeStatus,
4435
+ pi: piStatus,
4079
4436
  aiClients,
4080
4437
  aiClientInstances,
4081
4438
  aiClientFlowReadiness,
4082
4439
  lcmSummaryService,
4440
+ historicalIngestion,
4083
4441
  embeddingState,
4084
4442
  deviceIdentity,
4085
4443
  upstreamBackends,
@@ -4157,15 +4515,126 @@ var collectKoedServerDoctor = async (environment = process.env, dependencies = {
4157
4515
  };
4158
4516
  };
4159
4517
 
4518
+ // packages/koed-server/dist/codex-config-block.mjs
4519
+ import { basename as basename2, dirname as dirname10, isAbsolute as isAbsolute3, join as join4 } from "node:path";
4520
+ function codexConfigSections({ nodeCommand, mcpName, mcpCliPath, captureHookPath, koedHome }) {
4521
+ const hookCommand = [
4522
+ nodeCommand,
4523
+ captureHookPath,
4524
+ "--koed-home",
4525
+ koedHome,
4526
+ "--memory-tool",
4527
+ `mcp__${mcpName}__memory_answer`
4528
+ ].map((value) => JSON.stringify(value)).join(" ");
4529
+ const hookEvents = [
4530
+ ["PreToolUse", 10],
4531
+ ["SessionStart", 10],
4532
+ ["UserPromptSubmit", 10],
4533
+ ["PostToolUse", 10],
4534
+ ["Stop", 30],
4535
+ ["SubagentStart", 10],
4536
+ ["SubagentStop", 30]
4537
+ ];
4538
+ const hookBlocks = hookEvents.map(([eventName, timeout]) => `[[hooks.${eventName}]]
4539
+ ${eventName === "PreToolUse" ? `matcher = ${JSON.stringify(`mcp__${mcpName}__memory_answer`)}
4540
+ ` : ""}[[hooks.${eventName}.hooks]]
4541
+ type = "command"
4542
+ command = ${JSON.stringify(hookCommand)}
4543
+ timeout = ${timeout}`).join("\n\n");
4544
+ const header = `mcp_servers.${mcpName}`;
4545
+ const tables = [
4546
+ `[${header}]
4547
+ command = ${JSON.stringify(nodeCommand)}
4548
+ args = [${JSON.stringify(mcpCliPath)}]
4549
+ enabled = true`,
4550
+ ...[
4551
+ "memory_answer",
4552
+ "memory_answer_result",
4553
+ "memory_answer_cancel",
4554
+ "memory_workspaces"
4555
+ ].map((tool) => `[${header}.tools.${tool}]
4556
+ approval_mode = "approve"`),
4557
+ `[${header}.env]
4558
+ KOED_HOME = ${JSON.stringify(koedHome)}`
4559
+ ];
4560
+ return { tables, hooks: hookBlocks };
4561
+ }
4562
+ function renderCodexBlock(config) {
4563
+ const { tables, hooks } = codexConfigSections(config);
4564
+ return `# >>> koed
4565
+ ${tables.join("\n\n")}
4566
+
4567
+ ${hooks}
4568
+ # <<< koed
4569
+ `;
4570
+ }
4571
+ function stripReorderedCodexBlock(content, config) {
4572
+ if (!content.trimEnd().endsWith("# <<< koed") || /^\s*# >>> koed\s*$/m.test(content))
4573
+ return content;
4574
+ if ((content.match(/^[\t ]*# <<< koed[\t ]*\r?$/gm) ?? []).length !== 1 || /"""|'''/.test(content))
4575
+ return content;
4576
+ const header = `[mcp_servers.${config.mcpName}]`;
4577
+ const tables = content.split(/(?=^\[)/m);
4578
+ const server = tables.find((table) => table.split(/\r?\n/, 1)[0] === header);
4579
+ if (!server)
4580
+ return content;
4581
+ let cli;
4582
+ let command;
4583
+ try {
4584
+ const args = JSON.parse(/^args = (.+)$/m.exec(server)?.[1] ?? "");
4585
+ command = JSON.parse(/^command = (.+)$/m.exec(server)?.[1] ?? "");
4586
+ if (!Array.isArray(args) || args.length !== 1 || typeof command !== "string")
4587
+ return content;
4588
+ cli = args[0];
4589
+ } catch {
4590
+ return content;
4591
+ }
4592
+ if (typeof cli !== "string" || !isAbsolute3(cli) || basename2(cli) !== "cli.js" || basename2(dirname10(cli)) !== "dist" || basename2(dirname10(dirname10(cli))) !== "mcp-server")
4593
+ return content;
4594
+ const captureHookPath = join4(dirname10(cli), "capture-hook.js");
4595
+ const expected = codexConfigSections({
4596
+ ...config,
4597
+ nodeCommand: command,
4598
+ mcpCliPath: cli,
4599
+ captureHookPath
4600
+ });
4601
+ const newline = server.includes("\r\n") ? "\r\n" : "\n";
4602
+ const hooks = (expected.hooks + "\n# <<< koed").replaceAll("\n", newline);
4603
+ const trimmed = content.trimEnd();
4604
+ if (!trimmed.endsWith(newline + hooks))
4605
+ return content;
4606
+ const beforeHooks = content.slice(0, trimmed.length - hooks.length);
4607
+ if (beforeHooks.includes(captureHookPath))
4608
+ return content;
4609
+ const expectedTables = new Map(expected.tables.map((table) => [table.split("\n", 1)[0], table]));
4610
+ const retained = [];
4611
+ for (const table of beforeHooks.split(/(?=^\[)/m)) {
4612
+ const name = table.split(/\r?\n/, 1)[0];
4613
+ if (name !== header && !name.startsWith(header.slice(0, -1) + ".")) {
4614
+ retained.push(table);
4615
+ continue;
4616
+ }
4617
+ const expectedTable = expectedTables.get(name);
4618
+ const actual = table.trimEnd().replaceAll("\r\n", "\n");
4619
+ if (!expectedTable)
4620
+ return content;
4621
+ const matchesImplicitEnabled = name === header && actual === expectedTable.replace("\nenabled = true", "");
4622
+ if (actual !== expectedTable && !matchesImplicitEnabled)
4623
+ return content;
4624
+ expectedTables.delete(name);
4625
+ }
4626
+ return expectedTables.size === 0 ? retained.join("") : content;
4627
+ }
4628
+
4160
4629
  // packages/koed-server/dist/setup.js
4161
4630
  import { spawnSync as nodeSpawnSync5 } from "node:child_process";
4162
4631
  import { chmodSync as nodeChmodSync, existsSync as nodeExistsSync, mkdirSync as nodeMkdirSync, readFileSync as nodeReadFileSync, statSync as nodeStatSync, unlinkSync as nodeUnlinkSync, writeFileSync as nodeWriteFileSync } from "node:fs";
4163
4632
  import { homedir as homedir5 } from "node:os";
4164
- import { dirname as dirname10, resolve as resolve15 } from "node:path";
4633
+ import { dirname as dirname11, resolve as resolve15 } from "node:path";
4165
4634
 
4166
4635
  // packages/koed-server/dist/local-service-secrets.js
4167
4636
  import { randomBytes } from "node:crypto";
4168
- import { existsSync as existsSync11, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "node:fs";
4637
+ import { existsSync as existsSync12, readFileSync as readFileSync7, writeFileSync as writeFileSync7 } from "node:fs";
4169
4638
  import { resolve as resolve13 } from "node:path";
4170
4639
  var secretNames = [
4171
4640
  "POSTGRES_PASSWORD",
@@ -4198,15 +4667,15 @@ var parseLocalServiceSecrets = (value) => {
4198
4667
  };
4199
4668
  var localServiceSecretsPath = (paths) => resolve13(paths.configDir, "local-service-secrets.json");
4200
4669
  var readLocalServiceSecrets = (paths, dependencies = {}) => {
4201
- const path = localServiceSecretsPath(paths);
4202
- const exists = dependencies.existsSync ?? existsSync11;
4203
- if (!exists(path))
4204
- return { state: "absent", path };
4670
+ const path2 = localServiceSecretsPath(paths);
4671
+ const exists = dependencies.existsSync ?? existsSync12;
4672
+ if (!exists(path2))
4673
+ return { state: "absent", path: path2 };
4205
4674
  try {
4206
- const parsed = parseLocalServiceSecrets(JSON.parse(String((dependencies.readFileSync ?? readFileSync6)(path, "utf8"))));
4207
- return typeof parsed === "string" ? { state: "invalid", path, error: parsed } : { state: "valid", path, secrets: parsed };
4675
+ const parsed = parseLocalServiceSecrets(JSON.parse(String((dependencies.readFileSync ?? readFileSync7)(path2, "utf8"))));
4676
+ return typeof parsed === "string" ? { state: "invalid", path: path2, error: parsed } : { state: "valid", path: path2, secrets: parsed };
4208
4677
  } catch {
4209
- return { state: "invalid", path, error: "expected valid JSON" };
4678
+ return { state: "invalid", path: path2, error: "expected valid JSON" };
4210
4679
  }
4211
4680
  };
4212
4681
  var generatedSecrets = (existing, random) => ({
@@ -4228,7 +4697,7 @@ var ensurePackagedLocalServiceSecrets = (paths, packaged, environment, dependenc
4228
4697
  const readResult = readLocalServiceSecrets(paths, dependencies);
4229
4698
  const existing = readResult.state === "valid" ? readResult.secrets : {};
4230
4699
  const secrets = generatedSecrets(existing, dependencies.randomBytes ?? randomBytes);
4231
- (dependencies.writeFileSync ?? writeFileSync6)(localServiceSecretsPath(paths), `${JSON.stringify(secrets, null, 2)}
4700
+ (dependencies.writeFileSync ?? writeFileSync7)(localServiceSecretsPath(paths), `${JSON.stringify(secrets, null, 2)}
4232
4701
  `, { mode: 384 });
4233
4702
  return { ...secrets, ...environment };
4234
4703
  };
@@ -4366,25 +4835,25 @@ var provisionDesktopApiToken = async (paths, runtime, environment, repoEnv = {},
4366
4835
  };
4367
4836
 
4368
4837
  // packages/koed-server/dist/setup.js
4369
- var captureManagedFile = (path, existsSync12, readFileSync7) => existsSync12(path) ? {
4370
- content: String(readFileSync7(path, "utf8")),
4371
- mode: nodeStatSync(path).mode & 511
4838
+ var captureManagedFile = (path2, existsSync13, readFileSync8) => existsSync13(path2) ? {
4839
+ content: String(readFileSync8(path2, "utf8")),
4840
+ mode: nodeStatSync(path2).mode & 511
4372
4841
  } : { content: null, mode: null };
4373
- var restoreManagedFile = (path, snapshot, existsSync12, writeFileSync7, mkdirSync7) => {
4842
+ var restoreManagedFile = (path2, snapshot, existsSync13, writeFileSync8, mkdirSync8) => {
4374
4843
  if (snapshot.content === null) {
4375
- if (existsSync12(path))
4376
- nodeUnlinkSync(path);
4844
+ if (existsSync13(path2))
4845
+ nodeUnlinkSync(path2);
4377
4846
  return;
4378
4847
  }
4379
- mkdirSync7(dirname10(path), { recursive: true, mode: 448 });
4380
- writeFileSync7(path, snapshot.content, { mode: snapshot.mode ?? 384 });
4848
+ mkdirSync8(dirname11(path2), { recursive: true, mode: 448 });
4849
+ writeFileSync8(path2, snapshot.content, { mode: snapshot.mode ?? 384 });
4381
4850
  if (snapshot.mode !== null)
4382
- nodeChmodSync(path, snapshot.mode);
4851
+ nodeChmodSync(path2, snapshot.mode);
4383
4852
  };
4384
4853
  var tomlString = (value) => JSON.stringify(value);
4385
- var configureCodexIntegration = ({ paths, environment, apiUrl, readFileSync: readFileSync7, writeFileSync: writeFileSync7, mkdirSync: mkdirSync7, existsSync: existsSync12, memoryGuidanceEnabled, resolveRuntime }) => {
4386
- const runtime = resolveRuntime(paths, environment, existsSync12);
4387
- const missing = [runtime.mcpCli, runtime.captureHook].filter((path) => !existsSync12(path));
4854
+ var configureCodexIntegration = ({ paths, environment, apiUrl, readFileSync: readFileSync8, writeFileSync: writeFileSync8, mkdirSync: mkdirSync8, existsSync: existsSync13, memoryGuidanceEnabled, resolveRuntime }) => {
4855
+ const runtime = resolveRuntime(paths, environment, existsSync13);
4856
+ const missing = [runtime.mcpCli, runtime.captureHook].filter((path2) => !existsSync13(path2));
4388
4857
  const command = `write Codex config using ${runtime.root}`;
4389
4858
  if (missing.length > 0) {
4390
4859
  throw new Error(`Koed MCP Server artifacts are missing: ${missing.join(", ")}. Rebuild Koed Desktop packaging so koed-runtime contains the MCP Server and Supported Capture Hook artifacts.`);
@@ -4393,78 +4862,37 @@ var configureCodexIntegration = ({ paths, environment, apiUrl, readFileSync: rea
4393
4862
  const mcpName = environment.MEMORY_MCP_NAME ?? "koed";
4394
4863
  const codexConfigPath = resolve15(environment.CODEX_CONFIG_PATH ?? `${environment.CODEX_HOME ?? `${homedir5()}/.codex`}/config.toml`);
4395
4864
  const codexInstructionsPath = resolveCodexGlobalInstructionsPath(environment);
4396
- const existing = existsSync12(codexConfigPath) ? String(readFileSync7(codexConfigPath, "utf8")) : "";
4397
- const withoutPrevious = stripCodexOwnershipBlock(existing);
4865
+ const existing = existsSync13(codexConfigPath) ? String(readFileSync8(codexConfigPath, "utf8")) : "";
4398
4866
  if (!/^[A-Za-z0-9_-]+$/.test(mcpName))
4399
4867
  throw new Error("MEMORY_MCP_NAME must be a TOML bare server name.");
4400
4868
  const guidancePath = resolveCodexGuidancePath(runtime.mcpCli);
4401
- const existingInstructions = existsSync12(codexInstructionsPath) ? String(readFileSync7(codexInstructionsPath, "utf8")) : "";
4869
+ const existingInstructions = existsSync13(codexInstructionsPath) ? String(readFileSync8(codexInstructionsPath, "utf8")) : "";
4402
4870
  let nextInstructions;
4403
4871
  if (memoryGuidanceEnabled) {
4404
- if (!existsSync12(guidancePath)) {
4872
+ if (!existsSync13(guidancePath)) {
4405
4873
  throw new Error(`Packaged Codex memory guidance is missing: ${guidancePath}. Rebuild Koed so the MCP Server prompt assets are complete.`);
4406
4874
  }
4407
- const guidance = String(readFileSync7(guidancePath, "utf8"));
4875
+ const guidance = String(readFileSync8(guidancePath, "utf8"));
4408
4876
  nextInstructions = reconcileManagedCodexGuidance(existingInstructions, guidance);
4409
4877
  } else {
4410
4878
  nextInstructions = removeManagedCodexGuidance(existingInstructions);
4411
4879
  }
4412
- const markerStart = "# >>> koed";
4413
- const markerEnd = "# <<< koed";
4414
- const hookCommand = [
4880
+ const config = {
4415
4881
  nodeCommand,
4416
- runtime.captureHook,
4417
- "--koed-home",
4418
- paths.koedHome,
4419
- "--memory-tool",
4420
- `mcp__${mcpName}__memory_answer`
4421
- ].map(tomlString).join(" ");
4422
- const hookEvents = [
4423
- ["PreToolUse", 10],
4424
- ["SessionStart", 10],
4425
- ["UserPromptSubmit", 10],
4426
- ["PostToolUse", 10],
4427
- ["Stop", 30],
4428
- ["SubagentStart", 10],
4429
- ["SubagentStop", 30]
4430
- ];
4431
- const hookBlocks = hookEvents.map(([eventName, timeout]) => `[[hooks.${eventName}]]
4432
- ${eventName === "PreToolUse" ? `matcher = ${tomlString(`mcp__${mcpName}__memory_answer`)}
4433
- ` : ""}[[hooks.${eventName}.hooks]]
4434
- type = "command"
4435
- command = ${tomlString(hookCommand)}
4436
- timeout = ${timeout}`).join("\n\n");
4437
- const koedBlock = `${markerStart}
4438
- [mcp_servers.${mcpName}]
4439
- command = ${tomlString(nodeCommand)}
4440
- args = [${tomlString(runtime.mcpCli)}]
4441
- enabled = true
4442
-
4443
- [mcp_servers.${mcpName}.tools.memory_answer]
4444
- approval_mode = "approve"
4445
-
4446
- [mcp_servers.${mcpName}.tools.memory_answer_result]
4447
- approval_mode = "approve"
4448
-
4449
- [mcp_servers.${mcpName}.tools.memory_answer_cancel]
4450
- approval_mode = "approve"
4451
-
4452
- [mcp_servers.${mcpName}.tools.memory_workspaces]
4453
- approval_mode = "approve"
4454
-
4455
- [mcp_servers.${mcpName}.env]
4456
- KOED_HOME = ${tomlString(paths.koedHome)}
4457
-
4458
- ${hookBlocks}
4459
- ${markerEnd}
4460
- `;
4461
- mkdirSync7(dirname10(codexConfigPath), { recursive: true, mode: 448 });
4462
- writeFileSync7(codexConfigPath, `${withoutPrevious.trimEnd()}
4882
+ mcpName,
4883
+ mcpCliPath: runtime.mcpCli,
4884
+ captureHookPath: runtime.captureHook,
4885
+ koedHome: paths.koedHome
4886
+ };
4887
+ const withoutPrevious = stripCodexOwnershipBlock(stripReorderedCodexBlock(existing, config));
4888
+ const koedBlock = renderCodexBlock(config);
4889
+ mkdirSync8(dirname11(codexConfigPath), { recursive: true, mode: 448 });
4890
+ writeFileSync8(codexConfigPath, `${withoutPrevious.trimEnd()}
4463
4891
 
4464
4892
  ${koedBlock}`);
4465
- mkdirSync7(dirname10(codexInstructionsPath), { recursive: true, mode: 448 });
4893
+ mkdirSync8(dirname11(codexInstructionsPath), { recursive: true, mode: 448 });
4466
4894
  if (nextInstructions !== existingInstructions) {
4467
- writeFileSync7(codexInstructionsPath, nextInstructions, { mode: 384 });
4895
+ writeFileSync8(codexInstructionsPath, nextInstructions, { mode: 384 });
4468
4896
  }
4469
4897
  return {
4470
4898
  command,
@@ -4496,7 +4924,7 @@ var codexBlockIsExpectedKoedOwned = (block, environment, paths) => {
4496
4924
  ];
4497
4925
  return block.includes(mcpHeader) && block.includes(`command = ${tomlString(nodeCommand)}`) && block.includes(`args = [${tomlString(runtime.mcpCli)}]`) && block.includes(`[mcp_servers.${mcpName}.env]`) && block.includes(`KOED_HOME = ${tomlString(paths.koedHome)}`) && requiredHooks.every((eventName) => block.includes(`[[hooks.${eventName}]]`) && block.includes(runtime.captureHook));
4498
4926
  };
4499
- var removeCodexIntegration = ({ environment = process.env, readFileSync: readFileSync7 = nodeReadFileSync, writeFileSync: writeFileSync7 = nodeWriteFileSync, mkdirSync: mkdirSync7 = nodeMkdirSync, existsSync: existsSync12 = nodeExistsSync, now = () => /* @__PURE__ */ new Date() } = {}) => {
4927
+ var removeCodexIntegration = ({ environment = process.env, readFileSync: readFileSync8 = nodeReadFileSync, writeFileSync: writeFileSync8 = nodeWriteFileSync, mkdirSync: mkdirSync8 = nodeMkdirSync, existsSync: existsSync13 = nodeExistsSync, now = () => /* @__PURE__ */ new Date() } = {}) => {
4500
4928
  const paths = resolveKoedServerPaths(environment);
4501
4929
  ensureKoedHome(paths);
4502
4930
  const codexConfigPath = resolve15(environment.CODEX_CONFIG_PATH ?? `${environment.CODEX_HOME ?? `${homedir5()}/.codex`}/config.toml`);
@@ -4514,8 +4942,8 @@ var removeCodexIntegration = ({ environment = process.env, readFileSync: readFil
4514
4942
  try {
4515
4943
  assertAiClientRegistryWritable(environment);
4516
4944
  registrySnapshot = captureAiClientRegistry(environment);
4517
- configSnapshot = captureManagedFile(codexConfigPath, existsSync12, readFileSync7);
4518
- instructionsSnapshot = captureManagedFile(codexInstructionsPath, existsSync12, readFileSync7);
4945
+ configSnapshot = captureManagedFile(codexConfigPath, existsSync13, readFileSync8);
4946
+ instructionsSnapshot = captureManagedFile(codexInstructionsPath, existsSync13, readFileSync8);
4519
4947
  let nextConfig = configSnapshot.content;
4520
4948
  if (configSnapshot.content !== null) {
4521
4949
  const parsed = parseCodexOwnershipBlock(configSnapshot.content);
@@ -4531,17 +4959,17 @@ var removeCodexIntegration = ({ environment = process.env, readFileSync: readFil
4531
4959
  }
4532
4960
  const nextInstructions = instructionsSnapshot.content === null ? null : removeManagedCodexGuidance(instructionsSnapshot.content);
4533
4961
  if (nextConfig !== configSnapshot.content && nextConfig !== null) {
4534
- mkdirSync7(dirname10(codexConfigPath), { recursive: true, mode: 448 });
4535
- writeFileSync7(codexConfigPath, nextConfig, {
4962
+ mkdirSync8(dirname11(codexConfigPath), { recursive: true, mode: 448 });
4963
+ writeFileSync8(codexConfigPath, nextConfig, {
4536
4964
  mode: configSnapshot.mode ?? 384
4537
4965
  });
4538
4966
  }
4539
4967
  if (nextInstructions !== instructionsSnapshot.content && nextInstructions !== null) {
4540
- mkdirSync7(dirname10(codexInstructionsPath), {
4968
+ mkdirSync8(dirname11(codexInstructionsPath), {
4541
4969
  recursive: true,
4542
4970
  mode: 448
4543
4971
  });
4544
- writeFileSync7(codexInstructionsPath, nextInstructions, {
4972
+ writeFileSync8(codexInstructionsPath, nextInstructions, {
4545
4973
  mode: instructionsSnapshot.mode ?? 384
4546
4974
  });
4547
4975
  }
@@ -4557,14 +4985,14 @@ var removeCodexIntegration = ({ environment = process.env, readFileSync: readFil
4557
4985
  const failures = [error instanceof Error ? error.message : String(error)];
4558
4986
  if (configSnapshot) {
4559
4987
  try {
4560
- restoreManagedFile(codexConfigPath, configSnapshot, existsSync12, writeFileSync7, mkdirSync7);
4988
+ restoreManagedFile(codexConfigPath, configSnapshot, existsSync13, writeFileSync8, mkdirSync8);
4561
4989
  } catch (restoreError) {
4562
4990
  failures.push(`Codex configuration rollback failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`);
4563
4991
  }
4564
4992
  }
4565
4993
  if (instructionsSnapshot) {
4566
4994
  try {
4567
- restoreManagedFile(codexInstructionsPath, instructionsSnapshot, existsSync12, writeFileSync7, mkdirSync7);
4995
+ restoreManagedFile(codexInstructionsPath, instructionsSnapshot, existsSync13, writeFileSync8, mkdirSync8);
4568
4996
  } catch (restoreError) {
4569
4997
  failures.push(`Codex global instructions rollback failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`);
4570
4998
  }
@@ -4588,12 +5016,12 @@ var removeCodexIntegration = ({ environment = process.env, readFileSync: readFil
4588
5016
  var repairCodexIntegration = async (options = {}) => {
4589
5017
  if (resolveKoedAppRuntimeExecution() !== "packaged")
4590
5018
  return configureCodexProfile(options);
4591
- const readFileSync7 = options.readFileSync ?? nodeReadFileSync;
4592
- const existsSync12 = options.existsSync ?? nodeExistsSync;
5019
+ const readFileSync8 = options.readFileSync ?? nodeReadFileSync;
5020
+ const existsSync13 = options.existsSync ?? nodeExistsSync;
4593
5021
  let environment = options.environment ?? process.env;
4594
5022
  const paths = resolveKoedServerPaths(environment);
4595
5023
  ensureKoedHome(paths);
4596
- environment = applyActiveRuntimeUrls(applyPersistedLocalPorts(paths, environment), readActiveRuntimeState(paths.runtimeStatePath, readFileSync7, options.checkPid ?? isProcessRunning));
5024
+ environment = applyActiveRuntimeUrls(applyPersistedLocalPorts(paths, environment), readActiveRuntimeState(paths.runtimeStatePath, readFileSync8, options.checkPid ?? isProcessRunning));
4597
5025
  const repoEnv = loadRepoEnv(paths.repoRoot);
4598
5026
  if (!resolveActiveIntegrationApiToken(paths, environment, repoEnv))
4599
5027
  return configureCodexProfile({ ...options, environment });
@@ -4603,7 +5031,7 @@ var repairCodexIntegration = async (options = {}) => {
4603
5031
  queue: "bullmq",
4604
5032
  native: [],
4605
5033
  models: []
4606
- }, existsSync12, options.desktopRuntimeCapability);
5034
+ }, existsSync13, options.desktopRuntimeCapability);
4607
5035
  return configureCodexProfile({
4608
5036
  ...options,
4609
5037
  environment,
@@ -4611,11 +5039,11 @@ var repairCodexIntegration = async (options = {}) => {
4611
5039
  });
4612
5040
  };
4613
5041
  var configureCodexIntegrationForRemoteBackend = (options) => configureCodexProfile(options, options);
4614
- var configureCodexProfile = ({ environment = process.env, readFileSync: readFileSync7 = nodeReadFileSync, writeFileSync: writeFileSync7 = nodeWriteFileSync, mkdirSync: mkdirSync7 = nodeMkdirSync, existsSync: existsSync12 = nodeExistsSync, checkPid = isProcessRunning, resolveRuntime = resolveKoedAppRuntime, registerAiClient = registerExplicitAiClient, resolveCodexExecutable = resolveCodexExecutablePath, now = () => /* @__PURE__ */ new Date() }, remote) => {
5042
+ var configureCodexProfile = ({ environment = process.env, readFileSync: readFileSync8 = nodeReadFileSync, writeFileSync: writeFileSync8 = nodeWriteFileSync, mkdirSync: mkdirSync8 = nodeMkdirSync, existsSync: existsSync13 = nodeExistsSync, checkPid = isProcessRunning, resolveRuntime = resolveKoedAppRuntime, registerAiClient = registerExplicitAiClient, resolveCodexExecutable = resolveCodexExecutablePath, now = () => /* @__PURE__ */ new Date() }, remote) => {
4615
5043
  const paths = resolveKoedServerPaths(environment);
4616
5044
  ensureKoedHome(paths);
4617
5045
  if (!remote) {
4618
- environment = applyActiveRuntimeUrls(applyPersistedLocalPorts(paths, environment), readActiveRuntimeState(paths.runtimeStatePath, readFileSync7, checkPid));
5046
+ environment = applyActiveRuntimeUrls(applyPersistedLocalPorts(paths, environment), readActiveRuntimeState(paths.runtimeStatePath, readFileSync8, checkPid));
4619
5047
  }
4620
5048
  const repoEnv = remote ? {} : loadRepoEnv(paths.repoRoot);
4621
5049
  const apiUrl = remote?.apiUrl ?? resolveApiUrl(environment, repoEnv);
@@ -4646,18 +5074,18 @@ var configureCodexProfile = ({ environment = process.env, readFileSync: readFile
4646
5074
  try {
4647
5075
  assertAiClientRegistryWritable(integrationEnvironment);
4648
5076
  registrySnapshot = captureAiClientRegistry(integrationEnvironment);
4649
- configSnapshot = captureManagedFile(codexConfigPath, existsSync12, readFileSync7);
4650
- instructionsSnapshot = captureManagedFile(codexInstructionsPath, existsSync12, readFileSync7);
5077
+ configSnapshot = captureManagedFile(codexConfigPath, existsSync13, readFileSync8);
5078
+ instructionsSnapshot = captureManagedFile(codexInstructionsPath, existsSync13, readFileSync8);
4651
5079
  const codexExecutablePath = resolveCodexExecutable(integrationEnvironment);
4652
5080
  const result = configureCodexIntegration({
4653
5081
  paths,
4654
5082
  environment: integrationEnvironment,
4655
5083
  apiUrl,
4656
- readFileSync: readFileSync7,
4657
- writeFileSync: writeFileSync7,
4658
- mkdirSync: mkdirSync7,
4659
- existsSync: existsSync12,
4660
- memoryGuidanceEnabled: resolveKoedServerConfig(paths, { ...repoEnv, ...environment }, { existsSync: existsSync12, readFileSync: readFileSync7 }).codexGlobalMemoryGuidanceEnabled,
5084
+ readFileSync: readFileSync8,
5085
+ writeFileSync: writeFileSync8,
5086
+ mkdirSync: mkdirSync8,
5087
+ existsSync: existsSync13,
5088
+ memoryGuidanceEnabled: resolveKoedServerConfig(paths, { ...repoEnv, ...environment }, { existsSync: existsSync13, readFileSync: readFileSync8 }).codexGlobalMemoryGuidanceEnabled,
4661
5089
  resolveRuntime
4662
5090
  });
4663
5091
  const registered = registerAiClient({
@@ -4679,20 +5107,19 @@ var configureCodexProfile = ({ environment = process.env, readFileSync: readFile
4679
5107
  stdout: result.stdout,
4680
5108
  action: "Restart Codex and trust updated hooks if prompted. New sessions will be captured after Codex reloads this config."
4681
5109
  };
4682
- writeSetupVerification(paths, repaired, writeFileSync7);
4683
5110
  return repaired;
4684
5111
  } catch (error) {
4685
5112
  const failures = [error instanceof Error ? error.message : String(error)];
4686
5113
  if (configSnapshot) {
4687
5114
  try {
4688
- restoreManagedFile(codexConfigPath, configSnapshot, existsSync12, writeFileSync7, mkdirSync7);
5115
+ restoreManagedFile(codexConfigPath, configSnapshot, existsSync13, writeFileSync8, mkdirSync8);
4689
5116
  } catch (restoreError) {
4690
5117
  failures.push(`Codex profile rollback failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`);
4691
5118
  }
4692
5119
  }
4693
5120
  if (instructionsSnapshot) {
4694
5121
  try {
4695
- restoreManagedFile(codexInstructionsPath, instructionsSnapshot, existsSync12, writeFileSync7, mkdirSync7);
5122
+ restoreManagedFile(codexInstructionsPath, instructionsSnapshot, existsSync13, writeFileSync8, mkdirSync8);
4696
5123
  } catch (restoreError) {
4697
5124
  failures.push(`Codex global instructions rollback failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`);
4698
5125
  }
@@ -4714,7 +5141,6 @@ var configureCodexProfile = ({ environment = process.env, readFileSync: readFile
4714
5141
  error: failures.join(" "),
4715
5142
  action: "Review the reported failure, fix the Codex integration artifacts, then run the Codex-specific repair action again."
4716
5143
  };
4717
- writeSetupVerification(paths, failed, writeFileSync7);
4718
5144
  return failed;
4719
5145
  }
4720
5146
  };
@@ -4883,18 +5309,10 @@ var runSetupBootstrap = (context, spawnSync) => {
4883
5309
  ...output,
4884
5310
  ok: false,
4885
5311
  state: "needs_attention",
4886
- error: `Codex setup failed with exit code ${result.status ?? 1}.`,
5312
+ error: output.stderr?.includes("Codex Koed ownership markers are duplicated or incomplete.") ? "Codex config.toml has incomplete or duplicate Koed markers. Review the Koed MCP Server and Capture Hook entries before retrying." : `Codex setup failed with exit code ${result.status ?? 1}.`,
4887
5313
  action: "Review stdout/stderr, fix the reported client setup failure, then rerun koed setup codex --json."
4888
5314
  };
4889
5315
  };
4890
- var writeSetupVerification = (paths, result, writeFileSync7, successMessage = "Koed core setup completed.") => {
4891
- writeFileSync7(paths.lastVerificationPath, `${JSON.stringify({
4892
- ok: result.ok,
4893
- checkedAt: result.checkedAt,
4894
- message: result.ok ? successMessage : result.error
4895
- }, null, 2)}
4896
- `, { mode: 384 });
4897
- };
4898
5316
  var setupCore = async (options = {}) => {
4899
5317
  const environment = options.environment ?? process.env;
4900
5318
  const prepared = prepareSetupCodex(environment, options, "core");
@@ -4945,12 +5363,9 @@ var setupCore = async (options = {}) => {
4945
5363
  };
4946
5364
  var setupCodex = async (options = {}) => {
4947
5365
  const core = await setupCore(options);
4948
- const writeFileSync7 = options.writeFileSync ?? nodeWriteFileSync;
4949
- if (!core.ok) {
4950
- const paths2 = resolveKoedServerPaths(options.environment ?? process.env);
4951
- writeSetupVerification(paths2, core, writeFileSync7, "Codex setup completed.");
5366
+ const writeFileSync8 = options.writeFileSync ?? nodeWriteFileSync;
5367
+ if (!core.ok)
4952
5368
  return core;
4953
- }
4954
5369
  const environment = options.environment ?? process.env;
4955
5370
  const paths = resolveKoedServerPaths(environment);
4956
5371
  if (environment.KOED_CODEX_GLOBAL_MEMORY_GUIDANCE_ENABLED === "true" || environment.KOED_CODEX_GLOBAL_MEMORY_GUIDANCE_ENABLED === "false") {
@@ -4961,7 +5376,7 @@ var setupCodex = async (options = {}) => {
4961
5376
  writeCodexGlobalMemoryGuidancePreference(paths, config.codexGlobalMemoryGuidanceEnabled, {
4962
5377
  existsSync: options.existsSync,
4963
5378
  readFileSync: options.readFileSync,
4964
- writeFileSync: writeFileSync7
5379
+ writeFileSync: writeFileSync8
4965
5380
  });
4966
5381
  }
4967
5382
  const runtime = options.resolveRuntime ? options.resolveRuntime(paths, environment, options.existsSync ?? nodeExistsSync) : resolveKoedAppRuntimeExecution() === "packaged" ? await resolveVerifiedPackagedRuntime(paths, environment, {
@@ -4987,10 +5402,8 @@ var setupCodex = async (options = {}) => {
4987
5402
  });
4988
5403
  }
4989
5404
  const prepared = prepareSetupCodex(environment, options);
4990
- if (!prepared.ok) {
4991
- writeSetupVerification(prepared.paths, prepared.result, writeFileSync7);
5405
+ if (!prepared.ok)
4992
5406
  return prepared.result;
4993
- }
4994
5407
  const { context } = prepared;
4995
5408
  try {
4996
5409
  assertAiClientRegistryWritable(context.childEnv);
@@ -5005,7 +5418,6 @@ var setupCodex = async (options = {}) => {
5005
5418
  error: error instanceof Error ? error.message : String(error),
5006
5419
  action: "Fix malformed AI Client registry, then rerun Codex setup."
5007
5420
  };
5008
- writeSetupVerification(context.paths, failed, writeFileSync7, "Codex setup completed.");
5009
5421
  return failed;
5010
5422
  }
5011
5423
  let codexExecutablePath;
@@ -5022,7 +5434,6 @@ var setupCodex = async (options = {}) => {
5022
5434
  error: error instanceof Error ? error.message : String(error),
5023
5435
  action: "Install Codex or set MEMORY_CODEX_APP_SERVER_BINARY, then rerun Codex setup."
5024
5436
  };
5025
- writeSetupVerification(context.paths, failed, writeFileSync7, "Codex setup completed.");
5026
5437
  return failed;
5027
5438
  }
5028
5439
  persistSetupApiToken(context);
@@ -5047,17 +5458,17 @@ var setupCodex = async (options = {}) => {
5047
5458
  error: error instanceof Error ? error.message : String(error),
5048
5459
  action: "Fix the Codex-specific registration, then rerun koed setup codex --json."
5049
5460
  };
5050
- writeSetupVerification(context.paths, failed, writeFileSync7, "Codex setup completed.");
5051
5461
  return failed;
5052
5462
  }
5053
5463
  }
5054
- writeSetupVerification(context.paths, result, writeFileSync7, "Codex setup completed.");
5055
5464
  return result;
5056
5465
  };
5057
5466
 
5058
5467
  export {
5468
+ hasCompletePostgresOverride,
5059
5469
  stopLocalPostgresRuntime,
5060
5470
  startLocalPostgresRuntime,
5471
+ localServiceSecretsPath,
5061
5472
  ensurePackagedLocalServiceSecrets,
5062
5473
  pinAndResolvePackagedRuntime,
5063
5474
  resolveCodexExecutablePath,
@@ -5075,6 +5486,10 @@ export {
5075
5486
  resolveClaudeExecutablePath,
5076
5487
  removeClaude,
5077
5488
  setupClaude,
5489
+ aiClientConnectionRevision,
5490
+ grantAiClientConnection,
5491
+ revokeAiClientConnection,
5492
+ nativeLlamaServerOverride,
5078
5493
  startLocalEmbeddingRuntime,
5079
5494
  startLocalPrivacyRuntime,
5080
5495
  inspectPi,