@abelxiaoxing/cadence 2.0.36 → 2.0.37

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.
@@ -271,7 +271,6 @@ function effectiveWorkspace(requested, stateHome, _home) {
271
271
  }
272
272
 
273
273
  // src/worker-public.mjs
274
- var IMAGE_COUNT = 4;
275
274
  var SERVICE_PROTOCOL = 1;
276
275
  var WORKER_PROTOCOL = 2;
277
276
  var GRAPH_SCHEMA = "cadence-graph/2";
@@ -1168,7 +1167,7 @@ function decodeWorkerPublicRequest(v) {
1168
1167
  context: text(o.context, 32768),
1169
1168
  instructions: text(o.instructions, LIMITS.instructionsBytes, true),
1170
1169
  prompt: text(o.prompt, 32768, o.imageCount === undefined),
1171
- ...o.imageCount === undefined ? {} : { imageCount: integer(o.imageCount, 1, IMAGE_COUNT) },
1170
+ ...o.imageCount === undefined ? {} : { imageCount: integer(o.imageCount, 1) },
1172
1171
  handoff: decodeHandoff(o.handoff)
1173
1172
  };
1174
1173
  if (result.handoff.inputs.some((i) => i.assignmentId !== result.assignmentId))
@@ -5147,36 +5146,26 @@ function loadWebAssets(directory = fileURLToPath(new URL("../web/dist/", import.
5147
5146
 
5148
5147
  // src/image-content.mjs
5149
5148
  var IMAGE_LIMITS = Object.freeze({
5150
- count: IMAGE_COUNT,
5151
- bytes: 4 * 1024 * 1024,
5152
- totalBytes: 8 * 1024 * 1024,
5153
5149
  chunkChars: 256 * 1024,
5154
- stagedBytes: 64 * 1024 * 1024,
5155
- stagedCount: 64,
5156
- idleMs: 10 * 60 * 1000,
5157
- pixels: 32 * 1024 * 1024,
5158
- dimension: 16384,
5159
- wireBytes: 12 * 1024 * 1024
5150
+ idleMs: 10 * 60 * 1000
5160
5151
  });
5161
5152
  var IMAGE_TYPES = Object.freeze([
5162
5153
  "image/png",
5163
5154
  "image/jpeg",
5164
5155
  "image/webp"
5165
5156
  ]);
5166
- function decodeImageBase64(data, maxBytes = IMAGE_LIMITS.bytes) {
5167
- if (typeof data !== "string" || !data.length || data.length % 4 || data.length > 4 * Math.ceil(maxBytes / 3) || !/^[A-Za-z0-9+/]*={0,2}$/.test(data))
5157
+ function decodeImageBase64(data) {
5158
+ if (typeof data !== "string" || !data.length || data.length % 4 || !/^[A-Za-z0-9+/]*={0,2}$/.test(data))
5168
5159
  throw new Error("Invalid image encoding");
5169
5160
  const raw = atob(data);
5170
- if (raw.length > maxBytes)
5171
- throw new Error("Image is too large");
5172
5161
  const bytes = new Uint8Array(raw.length);
5173
5162
  for (let i = 0;i < raw.length; i++)
5174
5163
  bytes[i] = raw.charCodeAt(i);
5175
5164
  return bytes;
5176
5165
  }
5177
5166
  function validateImageBytes(bytes, mimeType) {
5178
- if (!IMAGE_TYPES.includes(mimeType) || !bytes.length || bytes.length > IMAGE_LIMITS.bytes)
5179
- throw new Error("Unsupported image or size");
5167
+ if (!IMAGE_TYPES.includes(mimeType) || !bytes.length)
5168
+ throw new Error("Unsupported or empty image");
5180
5169
  const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
5181
5170
  const ascii = (at, value) => [...value].every((c, i) => bytes[at + i] === c.charCodeAt(0));
5182
5171
  let width = 0, height = 0;
@@ -5235,7 +5224,7 @@ function validateImageBytes(bytes, mimeType) {
5235
5224
  height = 1 + (bits >>> 14 & 16383);
5236
5225
  }
5237
5226
  }
5238
- if (!width || !height || width > IMAGE_LIMITS.dimension || height > IMAGE_LIMITS.dimension || width * height > IMAGE_LIMITS.pixels)
5227
+ if (!width || !height)
5239
5228
  throw new Error("Invalid image dimensions or header");
5240
5229
  return { width, height };
5241
5230
  }
@@ -5775,7 +5764,7 @@ function decodeWorkbenchRead(v) {
5775
5764
  "offset",
5776
5765
  ...Object.hasOwn(v ?? {}, "live") ? ["live"] : []
5777
5766
  ]);
5778
- const offset = integer(o.offset, 0, 4 * Math.ceil(IMAGE_LIMITS.bytes / 3));
5767
+ const offset = integer(o.offset, 0);
5779
5768
  if (offset % IMAGE_LIMITS.chunkChars || o.live !== undefined && o.live !== true)
5780
5769
  throw new ContractError("invalid");
5781
5770
  return {
@@ -5784,7 +5773,7 @@ function decodeWorkbenchRead(v) {
5784
5773
  leaf: nullable(o.leaf, decodeEntryId),
5785
5774
  ...o.live === undefined ? {} : { live: true },
5786
5775
  entry: decodeEntryId(o.entry),
5787
- index: integer(o.index, 0, 1024),
5776
+ index: integer(o.index, 0),
5788
5777
  offset
5789
5778
  };
5790
5779
  }
@@ -5944,8 +5933,8 @@ function decodeWorkbenchCommand(v) {
5944
5933
  imageId: decodeId(o2.imageId),
5945
5934
  send,
5946
5935
  mimeType: oneOf(o2.mimeType, IMAGE_TYPES),
5947
- size: integer(o2.size, 1, IMAGE_LIMITS.bytes),
5948
- offset: integer(o2.offset, 0, 4 * Math.ceil(IMAGE_LIMITS.bytes / 3)),
5936
+ size: integer(o2.size, 1),
5937
+ offset: integer(o2.offset, 0),
5949
5938
  data: text(o2.data, IMAGE_LIMITS.chunkChars, true)
5950
5939
  };
5951
5940
  }
@@ -5967,7 +5956,7 @@ function decodeWorkbenchCommand(v) {
5967
5956
  conversationId: decodeSessionId(o2.conversationId),
5968
5957
  head: nullable(o2.head, decodeEntryId),
5969
5958
  text: text(o2.text, CONVERSATION_SEND_BYTES),
5970
- ...o2.images === undefined ? {} : { images: list(o2.images, IMAGE_LIMITS.count, decodeId) },
5959
+ ...o2.images === undefined ? {} : { images: list(o2.images, Number.MAX_SAFE_INTEGER, decodeId) },
5971
5960
  model: decodeChoiceVersion(o2.model),
5972
5961
  revision: integer(o2.revision, 0),
5973
5962
  intent: oneOf(o2.intent, ["message", "enter", "exit"])
@@ -6017,7 +6006,7 @@ function decodeWorkbenchCommand(v) {
6017
6006
  conversationId: decodeSessionId(o2.conversationId),
6018
6007
  head: nullable(o2.head, decodeEntryId),
6019
6008
  text: text(o2.text, CONVERSATION_SEND_BYTES),
6020
- ...o2.images === undefined ? {} : { images: list(o2.images, IMAGE_LIMITS.count, decodeId) },
6009
+ ...o2.images === undefined ? {} : { images: list(o2.images, Number.MAX_SAFE_INTEGER, decodeId) },
6021
6010
  model: decodeChoiceVersion(o2.model)
6022
6011
  };
6023
6012
  }
@@ -6073,7 +6062,7 @@ function decodeChatTurn(v) {
6073
6062
  };
6074
6063
  }
6075
6064
  function decodeChatImages(v) {
6076
- return list(v, IMAGE_LIMITS.count, (value) => {
6065
+ return list(v, Number.MAX_SAFE_INTEGER, (value) => {
6077
6066
  const o = closed(value, [
6078
6067
  "entry",
6079
6068
  "index",
@@ -6085,7 +6074,7 @@ function decodeChatImages(v) {
6085
6074
  return {
6086
6075
  ...o.live === undefined ? {} : { live: true },
6087
6076
  entry: decodeEntryId(o.entry),
6088
- index: integer(o.index, 0, 1024),
6077
+ index: integer(o.index, 0),
6089
6078
  mimeType: oneOf(o.mimeType, IMAGE_TYPES)
6090
6079
  };
6091
6080
  });
@@ -6225,7 +6214,7 @@ function decodeWorkbenchResult(v) {
6225
6214
  kind: k,
6226
6215
  commandId: decodeId(o2.commandId),
6227
6216
  imageId: decodeId(o2.imageId),
6228
- offset: integer(o2.offset, 0, 4 * Math.ceil(IMAGE_LIMITS.bytes / 3))
6217
+ offset: integer(o2.offset, 0)
6229
6218
  };
6230
6219
  }
6231
6220
  if (k === "conversation-image") {
@@ -6234,7 +6223,7 @@ function decodeWorkbenchResult(v) {
6234
6223
  kind: k,
6235
6224
  mimeType: oneOf(o2.mimeType, IMAGE_TYPES),
6236
6225
  data: text(o2.data, IMAGE_LIMITS.chunkChars, true),
6237
- next: nullable(o2.next, (n) => integer(n, 0, 4 * Math.ceil(IMAGE_LIMITS.bytes / 3)))
6226
+ next: nullable(o2.next, (n) => integer(n, 0))
6238
6227
  };
6239
6228
  }
6240
6229
  if (k === "conversation-context") {
@@ -7438,6 +7427,15 @@ function serviceName(s) {
7438
7427
  function serviceConfigPath(s) {
7439
7428
  return serverConfigPath(s.home, serviceName(s));
7440
7429
  }
7430
+ function expandHome(value, home) {
7431
+ if (value === "~")
7432
+ return home;
7433
+ return value.startsWith("~/") ? join7(home, value.slice(2)) : value;
7434
+ }
7435
+ function agentDirectory(s) {
7436
+ const selected2 = s.env.PI_CODING_AGENT_DIR;
7437
+ return resolve3(selected2 ? expandHome(selected2, s.home) : join7(s.home, ".pi", "agent"));
7438
+ }
7441
7439
  function unitPath(s) {
7442
7440
  serviceName(s);
7443
7441
  if (s.scope === "system")
@@ -7482,10 +7480,10 @@ function generatedUnit(s) {
7482
7480
  }
7483
7481
 
7484
7482
  // src/service/cli.ts
7485
- import { spawn as spawn2 } from "node:child_process";
7483
+ import { spawn as spawn3 } from "node:child_process";
7486
7484
  import { request } from "node:http";
7487
7485
  import { homedir as homedir4 } from "node:os";
7488
- import { dirname as dirname12, join as join16, resolve as resolve6 } from "node:path";
7486
+ import { dirname as dirname12, join as join17, resolve as resolve6 } from "node:path";
7489
7487
  import { fileURLToPath as fileURLToPath2 } from "node:url";
7490
7488
 
7491
7489
  // src/sdk-network.ts
@@ -7696,6 +7694,9 @@ function decodeMaintenanceJob(value) {
7696
7694
  endedAt: o.endedAt === null ? null : integer(o.endedAt, 0)
7697
7695
  };
7698
7696
  }
7697
+ function canUpgrade(route) {
7698
+ return route === "npm" || route === "bun" || route === "pi-npm" || route === "pi-bun" || route === "npm-local" || route === "bun-local";
7699
+ }
7699
7700
 
7700
7701
  // src/service/coordination.ts
7701
7702
  import { randomBytes as randomBytes3, randomUUID as randomUUID5 } from "node:crypto";
@@ -10040,14 +10041,170 @@ function decodeStartupReport(value) {
10040
10041
  };
10041
10042
  }
10042
10043
 
10043
- // src/service/maintenance.ts
10044
- import { spawn, spawnSync as spawnSync4 } from "node:child_process";
10045
- import { accessSync, constants as constants5, readFileSync as readFileSync3, realpathSync as realpathSync5 } from "node:fs";
10046
- import { dirname as dirname11, join as join15 } from "node:path";
10044
+ // src/service/installation.ts
10045
+ import { spawn } from "node:child_process";
10046
+ import {
10047
+ accessSync,
10048
+ constants as constants5,
10049
+ existsSync as existsSync2,
10050
+ lstatSync as lstatSync11,
10051
+ mkdtempSync,
10052
+ readFileSync as readFileSync3,
10053
+ realpathSync as realpathSync5,
10054
+ rmSync as rmSync4,
10055
+ writeFileSync as writeFileSync4
10056
+ } from "node:fs";
10057
+ import { basename as basename2, dirname as dirname11, isAbsolute as isAbsolute7, join as join15 } from "node:path";
10047
10058
  var PACKAGE = "@abelxiaoxing/cadence";
10048
- var JOB_SECONDS = 1800;
10049
10059
  var VIEW_MS = 30000;
10050
10060
  var INSTALL_MS = 15 * 60000;
10061
+ function packageCommands(s) {
10062
+ const command = (name) => (args, show = false, options) => new Promise((resolve6) => {
10063
+ const child = spawn(name, args, {
10064
+ cwd: options?.cwd ?? s.home,
10065
+ env: { ...s.env, HOME: s.home, ...options?.env },
10066
+ stdio: ["ignore", show ? 2 : "pipe", show ? 2 : "ignore"],
10067
+ timeout: show ? INSTALL_MS : VIEW_MS,
10068
+ windowsHide: true
10069
+ });
10070
+ let stdout = "";
10071
+ child.stdout?.setEncoding("utf8").on("data", (chunk) => {
10072
+ if (stdout.length < 1 << 20)
10073
+ stdout += chunk;
10074
+ });
10075
+ child.once("error", () => resolve6({ status: null, stdout: "" }));
10076
+ child.once("close", (status) => resolve6({ status, stdout }));
10077
+ });
10078
+ return { npm: command("npm"), bun: command("bun") };
10079
+ }
10080
+ var unsupported = () => ({
10081
+ route: "unsupported-install"
10082
+ });
10083
+ function sameCopy(modules, root) {
10084
+ try {
10085
+ const path = join15(modules, ...PACKAGE.split("/"));
10086
+ return !lstatSync11(path).isSymbolicLink() && realpathSync5(path) === realpathSync5(root) && realpathSync5(path) === join15(realpathSync5(modules), ...PACKAGE.split("/"));
10087
+ } catch {
10088
+ return false;
10089
+ }
10090
+ }
10091
+ function prefixManager(prefix) {
10092
+ const npm = existsSync2(join15(prefix, "package-lock.json")) || existsSync2(join15(prefix, "npm-shrinkwrap.json"));
10093
+ const bun = existsSync2(join15(prefix, "bun.lock")) || existsSync2(join15(prefix, "bun.lockb"));
10094
+ return npm === bun ? undefined : bun ? "bun" : "npm";
10095
+ }
10096
+ function writable(installation, modules, root) {
10097
+ if (installation.manager === "bun" && [".npmrc", "bunfig.toml", ".bunfig.toml"].some((name) => existsSync2(join15(installation.prefix, name))))
10098
+ return unsupported();
10099
+ try {
10100
+ for (const path of [installation.prefix, modules, dirname11(root), root])
10101
+ accessSync(path, constants5.W_OK);
10102
+ for (const name of [
10103
+ "package.json",
10104
+ "package-lock.json",
10105
+ "npm-shrinkwrap.json",
10106
+ "bun.lock",
10107
+ "bun.lockb"
10108
+ ])
10109
+ if (existsSync2(join15(installation.prefix, name)))
10110
+ accessSync(join15(installation.prefix, name), constants5.W_OK);
10111
+ return installation;
10112
+ } catch {
10113
+ return { route: "not-writable" };
10114
+ }
10115
+ }
10116
+ async function installation(s, commands) {
10117
+ const agent = agentDirectory(s), piPrefix = join15(agent, "npm");
10118
+ if (sameCopy(join15(piPrefix, "node_modules"), s.root)) {
10119
+ try {
10120
+ const settings2 = JSON.parse(readFileSync3(join15(agent, "settings.json"), "utf8"));
10121
+ if (!settings2 || !Array.isArray(settings2.packages))
10122
+ return unsupported();
10123
+ const sources = settings2.packages.map((p) => typeof p === "string" ? p : p && typeof p === "object" && ("source" in p) ? p.source : undefined).filter((source) => typeof source === "string" && (source === `npm:${PACKAGE}` || source.startsWith(`npm:${PACKAGE}@`)));
10124
+ if (sources.length !== 1)
10125
+ return unsupported();
10126
+ if (sources[0] !== `npm:${PACKAGE}`)
10127
+ return { route: "pinned" };
10128
+ const command = settings2.npmCommand ?? ["npm"];
10129
+ if (!Array.isArray(command) || command.length !== 1 || !["npm", "bun"].includes(command[0]))
10130
+ return unsupported();
10131
+ const manager = command[0];
10132
+ return writable({
10133
+ route: manager === "npm" ? "pi-npm" : "pi-bun",
10134
+ manager,
10135
+ prefix: piPrefix
10136
+ }, join15(piPrefix, "node_modules"), s.root);
10137
+ } catch {
10138
+ return unsupported();
10139
+ }
10140
+ }
10141
+ const localModules = dirname11(dirname11(s.root)), local = dirname11(localModules);
10142
+ const manifest = (() => {
10143
+ try {
10144
+ return JSON.parse(readFileSync3(join15(local, "package.json"), "utf8"));
10145
+ } catch {
10146
+ return;
10147
+ }
10148
+ })();
10149
+ if (manifest?.name === "pi-extensions" || basename2(dirname11(local)) === ".pi" || basename2(local) === "npm" && existsSync2(join15(dirname11(local), "settings.json")))
10150
+ return unsupported();
10151
+ const bun = await commands.bun(["pm", "ls", "--global"]);
10152
+ const bunPrefix = bun.status === 0 ? /^(\/[^\r\n]+) node_modules(?: \(\d+(?: installed)?\))?\r?$/.exec(bun.stdout.split(`
10153
+ `)[0])?.[1] : undefined;
10154
+ if (bunPrefix && sameCopy(join15(bunPrefix, "node_modules"), s.root)) {
10155
+ const manager = prefixManager(bunPrefix);
10156
+ if (manager === "bun")
10157
+ return writable({ route: "bun", manager: "bun", prefix: bunPrefix }, join15(bunPrefix, "node_modules"), s.root);
10158
+ if (!manager)
10159
+ return unsupported();
10160
+ }
10161
+ const npm = await commands.npm(["root", "--global"]);
10162
+ const modules = npm.status === 0 ? npm.stdout.trim() : "";
10163
+ const prefix = dirname11(dirname11(modules));
10164
+ if (isAbsolute7(modules) && modules === join15(prefix, "lib", "node_modules") && sameCopy(modules, s.root))
10165
+ return writable({ route: "npm", manager: "npm", prefix }, modules, s.root);
10166
+ if (basename2(localModules) !== "node_modules" || !sameCopy(localModules, s.root))
10167
+ return unsupported();
10168
+ try {
10169
+ if (![
10170
+ manifest.dependencies,
10171
+ manifest.devDependencies,
10172
+ manifest.optionalDependencies
10173
+ ].some((deps) => deps && typeof deps[PACKAGE] === "string" && /^(?:[~^]?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?|latest)$/.test(deps[PACKAGE])))
10174
+ return unsupported();
10175
+ const manager = prefixManager(local);
10176
+ if (!manager)
10177
+ return unsupported();
10178
+ if (manifest.packageManager !== undefined && (typeof manifest.packageManager !== "string" || !manifest.packageManager.startsWith(`${manager}@`)))
10179
+ return unsupported();
10180
+ return writable({
10181
+ route: manager === "bun" ? "bun-local" : "npm-local",
10182
+ manager,
10183
+ prefix: local
10184
+ }, localModules, s.root);
10185
+ } catch {
10186
+ return unsupported();
10187
+ }
10188
+ }
10189
+ async function upgradeRoute(s, commands = packageCommands(s)) {
10190
+ return (await installation(s, commands)).route;
10191
+ }
10192
+ function npmScope(i) {
10193
+ return [
10194
+ i.route === "npm" ? "--global" : "--global=false",
10195
+ "--prefix",
10196
+ i.prefix
10197
+ ];
10198
+ }
10199
+ function registryCommand(i, commands) {
10200
+ return (args, show) => commands[i.manager](i.manager === "npm" ? [args[0], ...npmScope(i), ...args.slice(1)] : args, show, { cwd: i.prefix });
10201
+ }
10202
+
10203
+ // src/service/maintenance.ts
10204
+ import { spawn as spawn2, spawnSync as spawnSync4 } from "node:child_process";
10205
+ import { readFileSync as readFileSync4 } from "node:fs";
10206
+ import { join as join16 } from "node:path";
10207
+ var JOB_SECONDS = 1800;
10051
10208
  var RESTART_MS = 5 * 60000;
10052
10209
  function cgroupPath(text2) {
10053
10210
  const lines = text2?.split(`
@@ -10074,7 +10231,7 @@ function maintenanceUnit(s) {
10074
10231
  return s.unit.replace(/\.service$/, ".maintenance.service");
10075
10232
  }
10076
10233
  function installedVersion(root) {
10077
- const value = JSON.parse(readFileSync3(join15(root, "package.json"), "utf8"));
10234
+ const value = JSON.parse(readFileSync4(join16(root, "package.json"), "utf8"));
10078
10235
  if (!value || typeof value !== "object" || !("name" in value))
10079
10236
  throw new ContractError("invalid");
10080
10237
  literal(value.name, PACKAGE);
@@ -10128,7 +10285,7 @@ function launchJob(s, job2) {
10128
10285
  ...[...new Map([["HOME", s.home], ...unitEnvironment(text2)])].map(([key, value]) => `--setenv=${key}=${value}`),
10129
10286
  "--",
10130
10287
  s.node,
10131
- join15(s.root, "src", "service-cli.mjs"),
10288
+ join16(s.root, "src", "service-cli.mjs"),
10132
10289
  "server",
10133
10290
  job2.action,
10134
10291
  scope,
@@ -10142,54 +10299,22 @@ function launchJob(s, job2) {
10142
10299
  function jobRunning(s) {
10143
10300
  return s.systemctl(["is-active", "--quiet", maintenanceUnit(s)]).status === 0;
10144
10301
  }
10145
- var npm = (args, show = false) => run("npm", args, show ? INSTALL_MS : VIEW_MS, show);
10146
- function run(command, args, timeout, show = false) {
10147
- return new Promise((resolve6) => {
10148
- const child = spawn(command, args, {
10149
- stdio: ["ignore", show ? 2 : "pipe", show ? 2 : "ignore"],
10150
- timeout,
10151
- windowsHide: true
10152
- });
10153
- let stdout = "";
10154
- child.stdout?.setEncoding("utf8").on("data", (chunk) => {
10155
- if (stdout.length < 1 << 20)
10156
- stdout += chunk;
10157
- });
10158
- child.once("error", () => resolve6({ status: null, stdout: "" }));
10159
- child.once("close", (status) => resolve6({ status, stdout }));
10160
- });
10161
- }
10162
- async function upgradeRoute(root, npmRun = npm) {
10163
- const result = await npmRun(["root", "--global"]);
10164
- const global = result.status === 0 ? result.stdout.trim() : "";
10165
- let installed;
10166
- try {
10167
- installed = realpathSync5(join15(global, ...PACKAGE.split("/")));
10168
- if (!global || installed !== realpathSync5(root))
10169
- return "not-npm-global";
10170
- } catch {
10171
- return "not-npm-global";
10172
- }
10173
- try {
10174
- accessSync(dirname11(installed), constants5.W_OK);
10175
- accessSync(global, constants5.W_OK);
10176
- } catch {
10177
- return "not-writable";
10178
- }
10179
- return "npm";
10180
- }
10181
- async function release(spec = "latest", npmRun = npm) {
10182
- const result = await npmRun([
10183
- "view",
10184
- `${PACKAGE}@${spec}`,
10185
- "version",
10186
- "deprecated",
10187
- "--json"
10188
- ]);
10302
+ async function release(spec, command, manager = "npm") {
10303
+ const name = `${PACKAGE}@${spec ?? "latest"}`;
10304
+ const result = await command(manager === "bun" ? ["info", name, "--json"] : ["view", name, "version", "deprecated", "--json"]);
10189
10305
  if (result.status !== 0)
10190
10306
  return;
10191
10307
  try {
10192
10308
  let value = JSON.parse(result.stdout);
10309
+ if (manager === "bun") {
10310
+ if (!value || typeof value !== "object" || Array.isArray(value) || !("name" in value) || !("version" in value))
10311
+ return;
10312
+ literal(value.name, PACKAGE);
10313
+ return {
10314
+ version: decodeVersion(value.version),
10315
+ deprecated: "deprecated" in value && typeof value.deprecated === "string"
10316
+ };
10317
+ }
10193
10318
  if (Array.isArray(value)) {
10194
10319
  if (value.length !== 1)
10195
10320
  return;
@@ -10206,6 +10331,9 @@ async function release(spec = "latest", npmRun = npm) {
10206
10331
  return;
10207
10332
  }
10208
10333
  }
10334
+ function releaseForInstallation(selected2, commands, spec) {
10335
+ return "manager" in selected2 ? release(spec, registryCommand(selected2, commands), selected2.manager) : Promise.resolve(undefined);
10336
+ }
10209
10337
 
10210
10338
  // src/service/cli.ts
10211
10339
  function nativeCall(c, operation, reveal = false, controlBody) {
@@ -10369,10 +10497,10 @@ function startupGuidance(result, input) {
10369
10497
  return `Pi's agent directory ${agent} must be an existing real directory (not a symlink) owned by you.
10370
10498
  `;
10371
10499
  case "pi-auth":
10372
- return `${join16(agent, "auth.json")} must be your own single-link regular file holding valid Pi credentials; log in to Pi first.
10500
+ return `${join17(agent, "auth.json")} must be your own single-link regular file holding valid Pi credentials; log in to Pi first.
10373
10501
  `;
10374
10502
  case "pi-models":
10375
- return `${join16(agent, "models.json")} must be your own single-link regular file using only fields Cadence's pinned Pi SDK supports; a field only newer Pi understands is refused.
10503
+ return `${join17(agent, "models.json")} must be your own single-link regular file using only fields Cadence's pinned Pi SDK supports; a field only newer Pi understands is refused.
10376
10504
  `;
10377
10505
  case "pi-runtime":
10378
10506
  return `Loading Pi's SDK model runtime failed (optional SDK packages missing, or sources the SDK refuses). Fix that and start again; the next start recovers the owner's registration automatically.
@@ -10432,7 +10560,7 @@ async function launchHost(input, c, foreground, hostUrl, cwd, env, network) {
10432
10560
  throw new ContractError("oversize");
10433
10561
  if (!sameNetwork(network, networkSnapshot(process.env)))
10434
10562
  throw new ContractError("stale");
10435
- const child = spawn2(process.execPath, [
10563
+ const child = spawn3(process.execPath, [
10436
10564
  ...env.NODE_USE_ENV_PROXY === "1" ? ["--use-env-proxy"] : [],
10437
10565
  fileURLToPath2(hostUrl)
10438
10566
  ], {
@@ -10580,22 +10708,22 @@ async function openProjectDirectory(workspace, stateHome, agentDir, hostUrl) {
10580
10708
 
10581
10709
  // src/service/conversation-contexts.ts
10582
10710
  import { randomUUID as randomUUID9 } from "node:crypto";
10583
- import { join as join20, resolve as resolve9 } from "node:path";
10711
+ import { join as join21, resolve as resolve9 } from "node:path";
10584
10712
 
10585
10713
  // src/cadence-preferences.ts
10586
10714
  import { realpathSync as realpathSync6 } from "node:fs";
10587
- import { basename as basename2, dirname as dirname13, join as join17, resolve as resolve7 } from "node:path";
10715
+ import { basename as basename3, dirname as dirname13, join as join18, resolve as resolve7 } from "node:path";
10588
10716
  function agentNamespace(agentDir) {
10589
10717
  let at = resolve7(agentDir);
10590
10718
  const missing2 = [];
10591
10719
  for (;; ) {
10592
10720
  try {
10593
- return join17(realpathSync6(at), ...missing2.reverse());
10721
+ return join18(realpathSync6(at), ...missing2.reverse());
10594
10722
  } catch {
10595
10723
  const parent = dirname13(at);
10596
10724
  if (parent === at)
10597
10725
  return resolve7(agentDir);
10598
- missing2.push(basename2(at));
10726
+ missing2.push(basename3(at));
10599
10727
  at = parent;
10600
10728
  }
10601
10729
  }
@@ -10606,7 +10734,7 @@ class CadencePreferences {
10606
10734
  files;
10607
10735
  constructor(agentDir) {
10608
10736
  const namespace = agentNamespace(agentDir);
10609
- this.path = join17(namespace, "cadence", "settings.json");
10737
+ this.path = join18(namespace, "cadence", "settings.json");
10610
10738
  this.files = new PrivateFiles(namespace, false);
10611
10739
  }
10612
10740
  read() {
@@ -11112,8 +11240,8 @@ class DetailSanitizer {
11112
11240
  }
11113
11241
 
11114
11242
  // src/service/conversation-records.ts
11115
- import { lstatSync as lstatSync12 } from "node:fs";
11116
- import { join as join19 } from "node:path";
11243
+ import { lstatSync as lstatSync13 } from "node:fs";
11244
+ import { join as join20 } from "node:path";
11117
11245
 
11118
11246
  // src/service/pi-sessions.ts
11119
11247
  import { createHash as createHash10 } from "node:crypto";
@@ -11121,14 +11249,14 @@ import {
11121
11249
  closeSync as closeSync6,
11122
11250
  constants as constants6,
11123
11251
  fstatSync as fstatSync5,
11124
- lstatSync as lstatSync11,
11252
+ lstatSync as lstatSync12,
11125
11253
  openSync as openSync6,
11126
11254
  readdirSync as readdirSync2,
11127
11255
  readSync as readSync4,
11128
11256
  realpathSync as realpathSync7
11129
11257
  } from "node:fs";
11130
11258
  import { homedir as homedir5 } from "node:os";
11131
- import { basename as basename3, isAbsolute as isAbsolute7, join as join18, resolve as resolve8 } from "node:path";
11259
+ import { basename as basename4, isAbsolute as isAbsolute8, join as join19, resolve as resolve8 } from "node:path";
11132
11260
 
11133
11261
  // src/session-entries.mjs
11134
11262
  var CADENCE_MODE_ENTRY = "cadence-conversation-mode/1";
@@ -11151,16 +11279,16 @@ var PART_ARGS_BYTES = 48 * 1024;
11151
11279
  var TARGET_ARGS = 1024 * 1024;
11152
11280
  function sessionDirectory(cwd, agentDir, env = process.env) {
11153
11281
  const expand = (value) => {
11154
- const home = value === "~" ? homedir5() : value.startsWith("~/") ? join18(homedir5(), value.slice(2)) : value;
11155
- return isAbsolute7(home) ? resolve8(home) : resolve8(cwd, home);
11282
+ const home = value === "~" ? homedir5() : value.startsWith("~/") ? join19(homedir5(), value.slice(2)) : value;
11283
+ return isAbsolute8(home) ? resolve8(home) : resolve8(cwd, home);
11156
11284
  };
11157
11285
  const fromEnv = env.PI_CODING_AGENT_SESSION_DIR;
11158
11286
  if (fromEnv)
11159
11287
  return expand(fromEnv);
11160
11288
  let configured;
11161
11289
  for (const file of [
11162
- join18(agentDir, "settings.json"),
11163
- join18(cwd, ".pi", "settings.json")
11290
+ join19(agentDir, "settings.json"),
11291
+ join19(cwd, ".pi", "settings.json")
11164
11292
  ]) {
11165
11293
  const value = settingsSessionDir(file);
11166
11294
  if (value)
@@ -11168,7 +11296,7 @@ function sessionDirectory(cwd, agentDir, env = process.env) {
11168
11296
  }
11169
11297
  if (configured)
11170
11298
  return expand(configured);
11171
- return join18(agentDir, "sessions", `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`);
11299
+ return join19(agentDir, "sessions", `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`);
11172
11300
  }
11173
11301
  function settingsSessionDir(file) {
11174
11302
  let fd;
@@ -11310,7 +11438,7 @@ function imageDescriptors(entry) {
11310
11438
  const content = message(entry)?.content;
11311
11439
  if (!isUser(entry) || !Array.isArray(content))
11312
11440
  return [];
11313
- return content.flatMap((b, index) => b?.type === "image" && IMAGE_TYPES.includes(b.mimeType) && typeof b.data === "string" && b.data.length > 0 && b.data.length <= 4 * Math.ceil(IMAGE_LIMITS.bytes / 3) && index <= 1024 ? [{ entry: entry.id, index, mimeType: b.mimeType }] : []).slice(0, IMAGE_LIMITS.count);
11441
+ return content.flatMap((b, index) => b?.type === "image" && IMAGE_TYPES.includes(b.mimeType) && typeof b.data === "string" && b.data.length > 0 ? [{ entry: entry.id, index, mimeType: b.mimeType }] : []);
11314
11442
  }
11315
11443
  function sessionImage(session, leaf, entry, index, offset) {
11316
11444
  if (!session.contains(leaf, entry))
@@ -11769,12 +11897,12 @@ class PiSessions {
11769
11897
  paths.add(this.directoryFor(this.project.defaultCwd));
11770
11898
  for (const path of this.directories.values())
11771
11899
  paths.add(path);
11772
- const home = join18(this.project.agentDir, "sessions");
11900
+ const home = join19(this.project.agentDir, "sessions");
11773
11901
  const prefix = `--${this.cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}`;
11774
11902
  try {
11775
11903
  for (const entry of readdirSync2(home, { withFileTypes: true }))
11776
11904
  if (entry.isDirectory() && entry.name.startsWith(`${prefix}-`))
11777
- paths.add(join18(home, entry.name));
11905
+ paths.add(join19(home, entry.name));
11778
11906
  } catch (error) {
11779
11907
  if (error.code !== "ENOENT")
11780
11908
  throw new ContractError("unavailable");
@@ -11797,7 +11925,7 @@ class PiSessions {
11797
11925
  const seenDirectories = new Set;
11798
11926
  for (const directory of this.roots()) {
11799
11927
  try {
11800
- if (!lstatSync11(directory).isDirectory() || lstatSync11(directory).isSymbolicLink())
11928
+ if (!lstatSync12(directory).isDirectory() || lstatSync12(directory).isSymbolicLink())
11801
11929
  throw new ContractError("forbidden");
11802
11930
  const canonical = realpathSync7(directory);
11803
11931
  if (seenDirectories.has(canonical))
@@ -11805,13 +11933,13 @@ class PiSessions {
11805
11933
  seenDirectories.add(canonical);
11806
11934
  for (const d of readdirSync2(canonical, { withFileTypes: true }))
11807
11935
  if (d.isFile() && d.name.endsWith(".jsonl"))
11808
- names2.push(join18(canonical, d.name));
11936
+ names2.push(join19(canonical, d.name));
11809
11937
  } catch (error) {
11810
11938
  if (error.code !== "ENOENT")
11811
11939
  throw new ContractError("unavailable");
11812
11940
  }
11813
11941
  }
11814
- names2.sort((a, b) => basename3(b).localeCompare(basename3(a)));
11942
+ names2.sort((a, b) => basename4(b).localeCompare(basename4(a)));
11815
11943
  names2.splice(LISTED_FILES);
11816
11944
  const seen = new Set;
11817
11945
  const out = [];
@@ -11834,7 +11962,7 @@ class PiSessions {
11834
11962
  return out.sort((a, b) => b.mtimeMs - a.mtimeMs || (a.summary.id < b.summary.id ? -1 : 1));
11835
11963
  }
11836
11964
  summary(path) {
11837
- const st = lstatSync11(path);
11965
+ const st = lstatSync12(path);
11838
11966
  assertSessionFile(st);
11839
11967
  const cached = this.listed.get(path);
11840
11968
  if (st.size > SESSION_BYTES) {
@@ -11938,9 +12066,9 @@ class PiSessions {
11938
12066
  nativeRuns() {
11939
12067
  const out = new Map;
11940
12068
  for (const listed of this.list())
11941
- for (const run2 of listed.summary.runs)
11942
- if (!out.has(run2))
11943
- out.set(run2, listed.summary.id);
12069
+ for (const run of listed.summary.runs)
12070
+ if (!out.has(run))
12071
+ out.set(run, listed.summary.id);
11944
12072
  return out;
11945
12073
  }
11946
12074
  }
@@ -11964,7 +12092,7 @@ var INTERRUPTED = "Interrupted: Cadence stopped before this reply finished. Noth
11964
12092
  var LIVE = ["queued", "running"];
11965
12093
  function observedFile(path) {
11966
12094
  try {
11967
- const s = lstatSync12(path);
12095
+ const s = lstatSync13(path);
11968
12096
  return [s.dev, s.ino, s.size, s.mode, s.nlink, s.ctimeMs, s.mtimeMs].join(":");
11969
12097
  } catch (error) {
11970
12098
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
@@ -11975,8 +12103,8 @@ function observedFile(path) {
11975
12103
  function retiredConversation(c, id) {
11976
12104
  decodeSessionId(id);
11977
12105
  return ["identities", "sessions"].some((kind) => {
11978
- const directory = join19(c.directory, "conversations-v1", kind);
11979
- return c.files.directory(directory) && observedFile(join19(directory, `${id}.json`)) !== "absent";
12106
+ const directory = join20(c.directory, "conversations-v1", kind);
12107
+ return c.files.directory(directory) && observedFile(join20(directory, `${id}.json`)) !== "absent";
11980
12108
  });
11981
12109
  }
11982
12110
  function assertSupportedConversation(c, id) {
@@ -12042,8 +12170,8 @@ class ConversationRecords {
12042
12170
  states = new Map;
12043
12171
  constructor(o) {
12044
12172
  this.o = o;
12045
- this.root = join19(o.coordination.directory, "conversation-commands-v1");
12046
- this.bindings = join19(o.coordination.directory, "conversations-v1");
12173
+ this.root = join20(o.coordination.directory, "conversation-commands-v1");
12174
+ this.bindings = join20(o.coordination.directory, "conversations-v1");
12047
12175
  this.active = o.active ?? new Map;
12048
12176
  this.sessions = checkoutSessions(o.coordination.store.root, o.cwd, o.agentDir, o.sessionDir);
12049
12177
  }
@@ -12060,14 +12188,14 @@ class ConversationRecords {
12060
12188
  return this.knownSecrets;
12061
12189
  }
12062
12190
  path(commandId, name) {
12063
- return join19(this.root, "commands", decodeId(commandId), name);
12191
+ return join20(this.root, "commands", decodeId(commandId), name);
12064
12192
  }
12065
12193
  assertSupported(id) {
12066
12194
  assertSupportedConversation(this.o.coordination, id);
12067
12195
  }
12068
12196
  indexPath(id) {
12069
12197
  this.assertSupported(id);
12070
- return join19(this.root, "sessions", `${decodeSessionId(id)}.json`);
12198
+ return join20(this.root, "sessions", `${decodeSessionId(id)}.json`);
12071
12199
  }
12072
12200
  read(path, max = META_BYTES) {
12073
12201
  const value = this.files.read(path, max);
@@ -12126,7 +12254,7 @@ class ConversationRecords {
12126
12254
  }
12127
12255
  controlPath(id) {
12128
12256
  this.assertSupported(id);
12129
- return join19(this.bindings, "control-links", `${decodeSessionId(id)}.json`);
12257
+ return join20(this.bindings, "control-links", `${decodeSessionId(id)}.json`);
12130
12258
  }
12131
12259
  controlKey(id) {
12132
12260
  return observedFile(this.controlPath(id));
@@ -12472,7 +12600,7 @@ class ConversationContextRecords {
12472
12600
  this.sessions = sessions;
12473
12601
  }
12474
12602
  path(id) {
12475
- return join20(this.c.directory, "conversations-v1", "contexts", `${decodeSessionId(id)}.json`);
12603
+ return join21(this.c.directory, "conversations-v1", "contexts", `${decodeSessionId(id)}.json`);
12476
12604
  }
12477
12605
  read(location) {
12478
12606
  const input = decodeConversationLocation(location);
@@ -12642,7 +12770,7 @@ class ConversationContexts {
12642
12770
  import { homedir as homedir6 } from "node:os";
12643
12771
 
12644
12772
  // src/service/conversation-controls.ts
12645
- import { dirname as dirname14, join as join21 } from "node:path";
12773
+ import { dirname as dirname14, join as join22 } from "node:path";
12646
12774
  var CONTROL_BYTES = 384 * 1024;
12647
12775
  var CONTROL_SCHEMA = "cadence-conversation-workflow/1";
12648
12776
  var CACHE = 512;
@@ -12679,11 +12807,11 @@ class ConversationControls {
12679
12807
  cache = new Map;
12680
12808
  constructor(o) {
12681
12809
  this.o = o;
12682
- this.root = join21(o.directory, "conversation-workflows-v1");
12810
+ this.root = join22(o.directory, "conversation-workflows-v1");
12683
12811
  }
12684
12812
  path(id) {
12685
12813
  this.o.conversations.assertSupported(id);
12686
- return join21(this.root, decodeSessionId(id), "state.json");
12814
+ return join22(this.root, decodeSessionId(id), "state.json");
12687
12815
  }
12688
12816
  read(id) {
12689
12817
  this.o.assertCurrent();
@@ -12756,8 +12884,8 @@ class ConversationControls {
12756
12884
  }
12757
12885
 
12758
12886
  // src/service/model-config.ts
12759
- import { lstatSync as lstatSync13, realpathSync as realpathSync8 } from "node:fs";
12760
- import { dirname as dirname15, isAbsolute as isAbsolute8, join as join22, resolve as resolve10 } from "node:path";
12887
+ import { lstatSync as lstatSync14, realpathSync as realpathSync8 } from "node:fs";
12888
+ import { dirname as dirname15, isAbsolute as isAbsolute9, join as join23, resolve as resolve10 } from "node:path";
12761
12889
  var CONFIG_BYTES2 = 1024 * 1024;
12762
12890
  var ENTRY_LIMIT = 256;
12763
12891
  function refuse() {
@@ -12822,16 +12950,16 @@ function captureEnvironment(value) {
12822
12950
  return Object.freeze(out);
12823
12951
  }
12824
12952
  function piSource(agentDir, home, cwd, env) {
12825
- if (!isAbsolute8(home) || !isAbsolute8(cwd))
12953
+ if (!isAbsolute9(home) || !isAbsolute9(cwd))
12826
12954
  refuse();
12827
- let selected2 = agentDir ?? env.PI_CODING_AGENT_DIR ?? join22(home, ".pi", "agent");
12955
+ let selected2 = agentDir ?? env.PI_CODING_AGENT_DIR ?? join23(home, ".pi", "agent");
12828
12956
  if (!selected2 || selected2.includes("\x00"))
12829
12957
  refuse();
12830
12958
  if (selected2 === "~" || selected2.startsWith("~/"))
12831
12959
  selected2 = home + selected2.slice(1);
12832
12960
  selected2 = resolve10(cwd, selected2);
12833
- const directory = join22(realpathSync8(dirname15(selected2)), selected2.slice(dirname15(selected2).length + 1));
12834
- if (!lstatSync13(directory).isDirectory() || lstatSync13(directory).isSymbolicLink())
12961
+ const directory = join23(realpathSync8(dirname15(selected2)), selected2.slice(dirname15(selected2).length + 1));
12962
+ if (!lstatSync14(directory).isDirectory() || lstatSync14(directory).isSymbolicLink())
12835
12963
  refuse();
12836
12964
  const files = new PrivateFiles(directory, false);
12837
12965
  if (!files.directory(directory))
@@ -12839,8 +12967,8 @@ function piSource(agentDir, home, cwd, env) {
12839
12967
  return {
12840
12968
  directory,
12841
12969
  files,
12842
- authPath: join22(directory, "auth.json"),
12843
- modelsPath: join22(directory, "models.json")
12970
+ authPath: join23(directory, "auth.json"),
12971
+ modelsPath: join23(directory, "models.json")
12844
12972
  };
12845
12973
  }
12846
12974
  function templateNames(value) {
@@ -14379,17 +14507,17 @@ import {
14379
14507
  closeSync as closeSync7,
14380
14508
  constants as constants7,
14381
14509
  fstatSync as fstatSync6,
14382
- lstatSync as lstatSync14,
14510
+ lstatSync as lstatSync15,
14383
14511
  opendirSync as opendirSync6,
14384
14512
  openSync as openSync7,
14385
14513
  readSync as readSync5,
14386
14514
  realpathSync as realpathSync9
14387
14515
  } from "node:fs";
14388
14516
  import { homedir as homedir7 } from "node:os";
14389
- import { dirname as dirname16, isAbsolute as isAbsolute9, join as join23, relative as relative5, resolve as resolve11, sep as sep5 } from "node:path";
14517
+ import { dirname as dirname16, isAbsolute as isAbsolute10, join as join24, relative as relative5, resolve as resolve11, sep as sep5 } from "node:path";
14390
14518
  function inside(root, path) {
14391
14519
  const r = relative5(root, path);
14392
- return r === "" || !isAbsolute9(r) && r !== ".." && !r.startsWith(`..${sep5}`);
14520
+ return r === "" || !isAbsolute10(r) && r !== ".." && !r.startsWith(`..${sep5}`);
14393
14521
  }
14394
14522
  var sensitive2 = (name) => /^\.(?:git|ssh|aws|azure|gnupg|kube|npmrc|pypirc|netrc)$/i.test(name) || /^\.env(?:\.|$)/i.test(name) || /^(?:auth|models|credentials|service-account)\.json$/i.test(name) || /^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.|$)/i.test(name) || /\.(?:pem|key|p12|pfx)$/i.test(name);
14395
14523
 
@@ -14408,30 +14536,30 @@ class WorkbenchFiles {
14408
14536
  allowed(path) {
14409
14537
  if (path.split(/[\\/]/).some(sensitive2) || this.excluded.some((root) => inside(root, path)))
14410
14538
  throw new ContractError("forbidden");
14411
- const stat = lstatSync14(path);
14539
+ const stat = lstatSync15(path);
14412
14540
  if (stat.isSymbolicLink() || stat.isFile() && stat.nlink !== 1 || process.platform !== "win32" && process.getuid && stat.uid !== process.getuid())
14413
14541
  throw new ContractError("forbidden");
14414
14542
  }
14415
14543
  directory(path) {
14416
- if (!isAbsolute9(path) || !safeDirectory(path))
14544
+ if (!isAbsolute10(path) || !safeDirectory(path))
14417
14545
  throw new ContractError("invalid");
14418
14546
  const canonical = realpathSync9(path);
14419
14547
  this.allowed(canonical);
14420
14548
  return canonical;
14421
14549
  }
14422
14550
  selected(path) {
14423
- if (isAbsolute9(path) || path.split(/[\\/]/).some((part) => part === ".." || sensitive2(part)))
14551
+ if (isAbsolute10(path) || path.split(/[\\/]/).some((part) => part === ".." || sensitive2(part)))
14424
14552
  throw new ContractError("forbidden");
14425
14553
  const target = resolve11(this.root, path);
14426
14554
  if (!inside(this.root, target) || !safeDirectory(dirname16(target)))
14427
14555
  throw new ContractError("forbidden");
14428
14556
  this.allowed(target);
14429
- if (lstatSync14(target).isSymbolicLink())
14557
+ if (lstatSync15(target).isSymbolicLink())
14430
14558
  throw new ContractError("forbidden");
14431
14559
  return target;
14432
14560
  }
14433
14561
  browsed(path) {
14434
- const full = /^~(?:[\\/]|$)/.test(path) ? join23(homedir7(), path.slice(1)) : path || this.root;
14562
+ const full = /^~(?:[\\/]|$)/.test(path) ? join24(homedir7(), path.slice(1)) : path || this.root;
14435
14563
  try {
14436
14564
  return this.directory(full);
14437
14565
  } catch (error) {
@@ -14454,7 +14582,7 @@ class WorkbenchFiles {
14454
14582
  }
14455
14583
  if (sensitive2(entry.name) || entry.isSymbolicLink() || !entry.isFile() && !entry.isDirectory() || directories && !entry.isDirectory())
14456
14584
  continue;
14457
- const absolute2 = join23(selected2, entry.name);
14585
+ const absolute2 = join24(selected2, entry.name);
14458
14586
  try {
14459
14587
  this.allowed(absolute2);
14460
14588
  } catch {
@@ -14487,7 +14615,7 @@ class WorkbenchFiles {
14487
14615
  };
14488
14616
  }
14489
14617
  read(path) {
14490
- const selected2 = this.selected(path), before = lstatSync14(selected2);
14618
+ const selected2 = this.selected(path), before = lstatSync15(selected2);
14491
14619
  if (!before.isFile())
14492
14620
  throw new ContractError("forbidden");
14493
14621
  const fd = openSync7(selected2, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0));
@@ -14503,7 +14631,7 @@ class WorkbenchFiles {
14503
14631
  break;
14504
14632
  at += n;
14505
14633
  }
14506
- const after = fstatSync6(fd), current = lstatSync14(selected2);
14634
+ const after = fstatSync6(fd), current = lstatSync15(selected2);
14507
14635
  if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.nlink !== 1 || current.isSymbolicLink() || current.nlink !== 1 || current.ino !== opened.ino || current.dev !== opened.dev)
14508
14636
  throw new ContractError("stale");
14509
14637
  const decoded2 = new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, at), { stream: at < opened.size });
@@ -14542,7 +14670,7 @@ async function createGateway(value, hostUrl, source) {
14542
14670
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
14543
14671
  const web = loadWebAssets(source?.webDirectory);
14544
14672
  const build2 = {
14545
- contractHash: "2d78a97c9d5db70709e390e26fa315b5fdd3539f5a36e040593943f06ee5469a",
14673
+ contractHash: "5d0366db40ab791c6a27b4b1cb323b88b14bf6c6cbd0fef76fd9433853d4f051",
14546
14674
  assets: {
14547
14675
  sourceHash: web.manifest.sourceHash,
14548
14676
  contractHash: web.manifest.contractHash,
@@ -14664,6 +14792,8 @@ Content-Length: 0\r
14664
14792
  const s = supervisingUnit(process.env, (selection) => hostSystem(root, ownerControl, selection));
14665
14793
  return s && serviceConfigPath(s) === input.serverConfig ? s : undefined;
14666
14794
  })();
14795
+ const packageSystem = managed ?? hostSystem(root, ownerControl, {});
14796
+ const commands = packageCommands(packageSystem);
14667
14797
  let route, requesting = false;
14668
14798
  async function associatedWork() {
14669
14799
  const counts = await Promise.all([
@@ -14683,7 +14813,7 @@ Content-Length: 0\r
14683
14813
  return job2?.state === "running" && managed && !jobRunning(managed) ? { ...job2, state: "failed", reason: "interrupted" } : job2;
14684
14814
  }
14685
14815
  async function serviceEntry() {
14686
- route ??= upgradeRoute(root);
14816
+ route ??= upgradeRoute(packageSystem, commands);
14687
14817
  return {
14688
14818
  kind: "service",
14689
14819
  version,
@@ -14702,8 +14832,8 @@ Content-Length: 0\r
14702
14832
  throw new ContractError("stale");
14703
14833
  if (!managed)
14704
14834
  throw new ContractError("unsupported-context");
14705
- route ??= upgradeRoute(root);
14706
- if (action === "upgrade" && await route !== "npm")
14835
+ route = upgradeRoute(packageSystem, commands);
14836
+ if (action === "upgrade" && !canUpgrade(await route))
14707
14837
  throw new ContractError("unsupported-context");
14708
14838
  if (requesting || jobRunning(managed))
14709
14839
  throw new ContractError("conflict");
@@ -14819,9 +14949,9 @@ Content-Length: 0\r
14819
14949
  throw new ContractError("capacity");
14820
14950
  if (preparations.size >= 128)
14821
14951
  throw new ContractError("capacity");
14822
- const commands = store.path("commands");
14823
- if (store.files.directory(commands)) {
14824
- const dir = opendirSync7(commands);
14952
+ const commands2 = store.path("commands");
14953
+ if (store.files.directory(commands2)) {
14954
+ const dir = opendirSync7(commands2);
14825
14955
  let count = 0;
14826
14956
  try {
14827
14957
  while (dir.readSync())
@@ -15237,7 +15367,9 @@ Content-Length: 0\r
15237
15367
  return;
15238
15368
  }
15239
15369
  if (raw === "/workbench/v1/service/release" && req.method === "GET") {
15240
- const latest = await release();
15370
+ const selected2 = await installation(packageSystem, commands);
15371
+ route = Promise.resolve(selected2.route);
15372
+ const latest = await releaseForInstallation(selected2, commands);
15241
15373
  if (!latest)
15242
15374
  throw new ContractError("unavailable");
15243
15375
  reply(res, 200, { kind: "release", ...latest });
@@ -15370,9 +15502,9 @@ Content-Length: 0\r
15370
15502
  }
15371
15503
 
15372
15504
  // src/service/host.ts
15373
- import { spawn as spawn5 } from "node:child_process";
15374
- import { lstatSync as lstatSync22, opendirSync as opendirSync13 } from "node:fs";
15375
- import { join as join38 } from "node:path";
15505
+ import { spawn as spawn6 } from "node:child_process";
15506
+ import { lstatSync as lstatSync23, opendirSync as opendirSync13 } from "node:fs";
15507
+ import { join as join39 } from "node:path";
15376
15508
  import { fileURLToPath as fileURLToPath7 } from "node:url";
15377
15509
 
15378
15510
  // src/agent-registry.ts
@@ -15404,12 +15536,12 @@ function loadAgentDefinitions() {
15404
15536
  function scopedSnapshot(source, scope) {
15405
15537
  if (scope.kind === "task" || source.scope.kind === "child")
15406
15538
  return;
15407
- if (!source.runs.some((run2) => scope.kind === "run" ? run2.runId === scope.id && run2.childRunId === null : run2.childRunId === scope.id))
15539
+ if (!source.runs.some((run) => scope.kind === "run" ? run.runId === scope.id && run.childRunId === null : run.childRunId === scope.id))
15408
15540
  return;
15409
15541
  return decodeSnapshot({
15410
15542
  ...source,
15411
15543
  scope,
15412
- runs: source.runs.filter((run2) => scope.kind === "run" ? run2.runId === scope.id : run2.childRunId === scope.id),
15544
+ runs: source.runs.filter((run) => scope.kind === "run" ? run.runId === scope.id : run.childRunId === scope.id),
15413
15545
  horizon: {
15414
15546
  ...source.horizon,
15415
15547
  historicalRuns: { ...source.horizon.historicalRuns, scope }
@@ -15649,12 +15781,12 @@ class HistoryLive {
15649
15781
 
15650
15782
  // src/history/navigation.ts
15651
15783
  import { createHash as createHash13 } from "node:crypto";
15652
- import { lstatSync as lstatSync16 } from "node:fs";
15653
- import { dirname as dirname18, join as join25 } from "node:path";
15784
+ import { lstatSync as lstatSync17 } from "node:fs";
15785
+ import { dirname as dirname18, join as join26 } from "node:path";
15654
15786
 
15655
15787
  // src/history/index-tree.ts
15656
- import { lstatSync as lstatSync15 } from "node:fs";
15657
- import { join as join24 } from "node:path";
15788
+ import { lstatSync as lstatSync16 } from "node:fs";
15789
+ import { join as join25 } from "node:path";
15658
15790
  var MAX_NODE = 16 * 1024;
15659
15791
  var ACTIVE_KEY = "active";
15660
15792
  function chainHash(seq, previous, previousHash) {
@@ -15697,7 +15829,7 @@ class IndexTree {
15697
15829
  this.files = files;
15698
15830
  }
15699
15831
  path(id) {
15700
- return join24(this.files.directory, "indexes", "nodes", id.slice(0, 2), `${id}.json`);
15832
+ return join25(this.files.directory, "indexes", "nodes", id.slice(0, 2), `${id}.json`);
15701
15833
  }
15702
15834
  load(id, budget, unit) {
15703
15835
  decodeHash(id);
@@ -15712,7 +15844,7 @@ class IndexTree {
15712
15844
  if (budget) {
15713
15845
  const path = this.path(id);
15714
15846
  budget.reserve(0);
15715
- const selected2 = lstatSync15(path).size;
15847
+ const selected2 = lstatSync16(path).size;
15716
15848
  if (selected2 > MAX_NODE)
15717
15849
  throw new ContractError("receipt-inconclusive");
15718
15850
  bytes = readRange(this.files, path, 0, selected2, budget);
@@ -16513,7 +16645,7 @@ class HistoryNavigation {
16513
16645
  cacheBytes = 0;
16514
16646
  blocks = new Map;
16515
16647
  block(path, at, size2, budget) {
16516
- const start = Math.floor(at / (1024 * 1024)) * 1024 * 1024, key = `${path}/${start}`, st = stamp3(lstatSync16(path));
16648
+ const start = Math.floor(at / (1024 * 1024)) * 1024 * 1024, key = `${path}/${start}`, st = stamp3(lstatSync17(path));
16517
16649
  let old = this.blocks.get(key);
16518
16650
  if (!old || old.budget !== budget || old.stamp !== st) {
16519
16651
  const bytes = readRange(this.files, path, start, Math.min(1024 * 1024, size2 - start), budget);
@@ -16551,9 +16683,9 @@ class HistoryNavigation {
16551
16683
  if (row.value.kind === "auth-preparation")
16552
16684
  auth.set(row.value.intent.operationId, row.value.intent.runId);
16553
16685
  if (row.value.kind === "auth-settlement") {
16554
- const run2 = auth.get(row.value.result.operationId);
16555
- if (run2)
16556
- keys3.add(run2);
16686
+ const run = auth.get(row.value.result.operationId);
16687
+ if (run)
16688
+ keys3.add(run);
16557
16689
  auth.delete(row.value.result.operationId);
16558
16690
  }
16559
16691
  }
@@ -16591,7 +16723,7 @@ class HistoryNavigation {
16591
16723
  }
16592
16724
  }
16593
16725
  indexPath(group, id) {
16594
- return join25(this.files.directory, "indexes", group, `${id}.json`);
16726
+ return join26(this.files.directory, "indexes", group, `${id}.json`);
16595
16727
  }
16596
16728
  hintKey(group, id) {
16597
16729
  return `${this.files.directory}/${this.files.format.storeId}/${group}/${id}`;
@@ -16650,7 +16782,7 @@ class HistoryNavigation {
16650
16782
  try {
16651
16783
  if (!this.files.files.directory(dirname18(path), false, budget.walks))
16652
16784
  return source ? structuredClone(source.value) : undefined;
16653
- const size2 = lstatSync16(path).size;
16785
+ const size2 = lstatSync17(path).size;
16654
16786
  if (size2 > RECORD_BYTES)
16655
16787
  return source ? structuredClone(source.value) : undefined;
16656
16788
  return parseWireJson(readRange(this.files, path, 0, size2, budget).toString("utf8"), RECORD_BYTES);
@@ -16729,10 +16861,10 @@ class HistoryNavigation {
16729
16861
  if (row.value.kind === "auth-preparation")
16730
16862
  this.authRuns.set(row.value.intent.operationId, row.value.intent.runId);
16731
16863
  if (row.value.kind === "auth-settlement") {
16732
- const run2 = this.authRuns.get(row.value.result.operationId);
16733
- if (run2) {
16734
- keys3.add(run2);
16735
- runKeys.add(run2);
16864
+ const run = this.authRuns.get(row.value.result.operationId);
16865
+ if (run) {
16866
+ keys3.add(run);
16867
+ runKeys.add(run);
16736
16868
  }
16737
16869
  this.authRuns.delete(row.value.result.operationId);
16738
16870
  }
@@ -16782,7 +16914,7 @@ class HistoryNavigation {
16782
16914
  }
16783
16915
  batch(p, budget) {
16784
16916
  const key = canonicalJson(p), cached = this.cache.get(key), path = this.files.segmentPath(p.segment);
16785
- if (cached && cached.budget === budget && cached.stamp === stamp3(lstatSync16(path))) {
16917
+ if (cached && cached.budget === budget && cached.stamp === stamp3(lstatSync17(path))) {
16786
16918
  this.validateBridge(cached.batch.rows, p, budget);
16787
16919
  this.rememberBoundary(p, cached.batch.navigationRoot, budget);
16788
16920
  return cached.batch;
@@ -16793,7 +16925,7 @@ class HistoryNavigation {
16793
16925
  if (cached.identity !== identity)
16794
16926
  bad2();
16795
16927
  cached.budget = budget;
16796
- cached.stamp = stamp3(lstatSync16(path));
16928
+ cached.stamp = stamp3(lstatSync17(path));
16797
16929
  this.files.assertPublished(p.segment, p.offset + p.bytes, p.seq);
16798
16930
  this.validateBridge(cached.batch.rows, p, budget);
16799
16931
  this.rememberBoundary(p, cached.batch.navigationRoot, budget);
@@ -16844,7 +16976,7 @@ class HistoryNavigation {
16844
16976
  identity,
16845
16977
  batch,
16846
16978
  bytes: bytes.length,
16847
- stamp: stamp3(lstatSync16(path)),
16979
+ stamp: stamp3(lstatSync17(path)),
16848
16980
  budget
16849
16981
  });
16850
16982
  this.cacheBytes += bytes.length;
@@ -16861,7 +16993,7 @@ class HistoryNavigation {
16861
16993
  const path = this.files.segmentPath(segment);
16862
16994
  let size2;
16863
16995
  try {
16864
- size2 = lstatSync16(path).size;
16996
+ size2 = lstatSync17(path).size;
16865
16997
  } catch (e) {
16866
16998
  if (e instanceof Error && "code" in e && e.code === "ENOENT")
16867
16999
  return null;
@@ -17722,7 +17854,7 @@ function materializeEntity(s, sources) {
17722
17854
 
17723
17855
  // src/history/export.ts
17724
17856
  import { createHash as createHash17, randomUUID as randomUUID12 } from "node:crypto";
17725
- import { readFileSync as readFileSync4 } from "node:fs";
17857
+ import { readFileSync as readFileSync5 } from "node:fs";
17726
17858
 
17727
17859
  // src/history/search.ts
17728
17860
  import { createHash as createHash16 } from "node:crypto";
@@ -19575,7 +19707,7 @@ async function searchQuantum(reader, value, limit = LIMITS.pageEntries) {
19575
19707
  // src/history/export.ts
19576
19708
  var exporterIdentity;
19577
19709
  function buildIdentity() {
19578
- exporterIdentity ??= createHash17("sha256").update(readFileSync4(new URL(import.meta.url))).digest("hex");
19710
+ exporterIdentity ??= createHash17("sha256").update(readFileSync5(new URL(import.meta.url))).digest("hex");
19579
19711
  return exporterIdentity;
19580
19712
  }
19581
19713
  function aborted(signal) {
@@ -20310,14 +20442,14 @@ function decodeState2(value) {
20310
20442
  legacyIdentity: o.legacyIdentity
20311
20443
  };
20312
20444
  }
20313
- function target(entity, run2, stop = null) {
20445
+ function target(entity, run, stop = null) {
20314
20446
  return {
20315
20447
  phase: "scan",
20316
20448
  proof: freshValidator(),
20317
20449
  row: 0,
20318
20450
  event: 0,
20319
20451
  entity,
20320
- run: run2,
20452
+ run,
20321
20453
  stop
20322
20454
  };
20323
20455
  }
@@ -21420,8 +21552,8 @@ class HistoryProjection {
21420
21552
 
21421
21553
  // src/history/reader.ts
21422
21554
  import { createHash as createHash20 } from "node:crypto";
21423
- import { existsSync as existsSync2 } from "node:fs";
21424
- import { join as join26 } from "node:path";
21555
+ import { existsSync as existsSync3 } from "node:fs";
21556
+ import { join as join27 } from "node:path";
21425
21557
 
21426
21558
  // src/history/saved-graph-state.ts
21427
21559
  var freshSavedGraph = () => ({
@@ -21820,12 +21952,12 @@ class HistoryReader {
21820
21952
  }
21821
21953
  reviewSelection(taskId2, runId, snapshotSeq) {
21822
21954
  const budget = HistoryReadBudget.authority();
21823
- const run2 = this.reviewRun(taskId2, runId, snapshotSeq, budget);
21824
- if (!run2.admission)
21955
+ const run = this.reviewRun(taskId2, runId, snapshotSeq, budget);
21956
+ if (!run.admission)
21825
21957
  throw new ContractError("corrupt-selected");
21826
- const { graph } = this.files.readAdmission(runId, run2.admission, budget);
21958
+ const { graph } = this.files.readAdmission(runId, run.admission, budget);
21827
21959
  if (!graph)
21828
- return { run: run2, graph, readablePlan: "" };
21960
+ return { run, graph, readablePlan: "" };
21829
21961
  const ref = graph.plan;
21830
21962
  const { detail, bytes } = this.planText({
21831
21963
  storeId: this.storeId,
@@ -21839,7 +21971,7 @@ class HistoryReader {
21839
21971
  }, budget);
21840
21972
  if (ref.bytes > 32768 || canonicalJson(detail.content) !== canonicalJson(ref) || detail.owner.taskId !== taskId2 || detail.owner.runId !== null || detail.owner.childRunId !== null || detail.owner.entity.kind !== "task" || detail.owner.entity.id !== taskId2 || detail.owner.entity.version !== graph.planRevision)
21841
21973
  throw new ContractError("corrupt-selected");
21842
- return { run: run2, graph, readablePlan: bytes.toString("utf8") };
21974
+ return { run, graph, readablePlan: bytes.toString("utf8") };
21843
21975
  }
21844
21976
  async graph(value) {
21845
21977
  const request3 = decodeGraphReadRequest(value);
@@ -22189,7 +22321,7 @@ class HistoryReader {
22189
22321
  }
22190
22322
  async readDetail(value) {
22191
22323
  const cursor = decodeCursor(value);
22192
- if (cursor.navigation !== undefined || this.files.format.schema === FORMAT && !existsSync2(join26(this.files.directory, "indexes", "heads", "latest.json")))
22324
+ if (cursor.navigation !== undefined || this.files.format.schema === FORMAT && !existsSync3(join27(this.files.directory, "indexes", "heads", "latest.json")))
22193
22325
  return readRetainedDetail(this, cursor);
22194
22326
  if (this.files.format.schema !== FORMAT)
22195
22327
  return this.detail(cursor);
@@ -22391,12 +22523,12 @@ class HistoryReader {
22391
22523
 
22392
22524
  // src/history/recovery.ts
22393
22525
  import { createHash as createHash24, randomUUID as randomUUID16 } from "node:crypto";
22394
- import { lstatSync as lstatSync17, opendirSync as opendirSync8 } from "node:fs";
22395
- import { join as join30, relative as relative7 } from "node:path";
22526
+ import { lstatSync as lstatSync18, opendirSync as opendirSync8 } from "node:fs";
22527
+ import { join as join31, relative as relative7 } from "node:path";
22396
22528
 
22397
22529
  // src/history/writer.ts
22398
22530
  import { createHash as createHash23, randomUUID as randomUUID15 } from "node:crypto";
22399
- import { join as join29 } from "node:path";
22531
+ import { join as join30 } from "node:path";
22400
22532
 
22401
22533
  // src/task-store.ts
22402
22534
  import { createHash as createHash21, randomUUID as randomUUID13 } from "node:crypto";
@@ -22407,10 +22539,10 @@ import {
22407
22539
  readdirSync as readdirSync3,
22408
22540
  renameSync as renameSync4,
22409
22541
  unlinkSync as unlinkSync3,
22410
- writeFileSync as writeFileSync4
22542
+ writeFileSync as writeFileSync5
22411
22543
  } from "node:fs";
22412
22544
  import { hostname as hostname6 } from "node:os";
22413
- import { join as join27 } from "node:path";
22545
+ import { join as join28 } from "node:path";
22414
22546
  // src/task-types.ts
22415
22547
  var TASK_SCHEMA = "cadence-workflow-assistant/1";
22416
22548
  var MAX_RECORD_BYTES = 128 * 1024;
@@ -22497,7 +22629,7 @@ class TaskStore extends CheckoutStore {
22497
22629
  tasks;
22498
22630
  constructor(root, stateHome = defaultStateHome()) {
22499
22631
  super(root, stateHome);
22500
- this.tasks = join27(this.root, ".cadence", "assistant", "tasks");
22632
+ this.tasks = join28(this.root, ".cadence", "assistant", "tasks");
22501
22633
  }
22502
22634
  recover(expected, acknowledgeEscapedProcesses) {
22503
22635
  if (!acknowledgeEscapedProcesses || expected.host !== hostname6())
@@ -22520,10 +22652,10 @@ class TaskStore extends CheckoutStore {
22520
22652
  loadSnapshot(id) {
22521
22653
  if (!validId(id))
22522
22654
  throw new Error("Invalid task id");
22523
- const directory = join27(this.tasks, id);
22655
+ const directory = join28(this.tasks, id);
22524
22656
  if (safeDirectory(directory) && readdirSync3(directory).some((name) => name !== "task.json"))
22525
22657
  throw new Error("Unknown task directory content; preserved without reset");
22526
- const data2 = readBounded(join27(this.tasks, id, "task.json"), MAX_RECORD_BYTES);
22658
+ const data2 = readBounded(join28(this.tasks, id, "task.json"), MAX_RECORD_BYTES);
22527
22659
  if (!data2)
22528
22660
  return;
22529
22661
  const record2 = decodeTask(parseRecord(data2));
@@ -22561,25 +22693,25 @@ class TaskStore extends CheckoutStore {
22561
22693
  throw new Error("Revision conflict");
22562
22694
  if (current2?.identity !== expectedIdentity)
22563
22695
  throw new Error("Task content changed; reopen it");
22564
- const dir = join27(this.tasks, next.id);
22696
+ const dir = join28(this.tasks, next.id);
22565
22697
  safeDirectory(dir, true);
22566
22698
  if (!current2 && readdirSync3(dir).length)
22567
22699
  throw new Error("Unknown task directory");
22568
- const temporary = join27(dir, `task.${randomUUID13()}.tmp`);
22700
+ const temporary = join28(dir, `task.${randomUUID13()}.tmp`);
22569
22701
  const fd = openSync8(temporary, "wx", 384);
22570
22702
  try {
22571
- writeFileSync4(fd, text2);
22703
+ writeFileSync5(fd, text2);
22572
22704
  fsyncSync4(fd);
22573
22705
  } finally {
22574
22706
  closeSync8(fd);
22575
22707
  }
22576
22708
  this.assertOwner(lock);
22577
- const latest = readBounded(join27(dir, "task.json"), MAX_RECORD_BYTES);
22709
+ const latest = readBounded(join28(dir, "task.json"), MAX_RECORD_BYTES);
22578
22710
  if ((latest ? contentIdentity(latest) : undefined) !== expectedIdentity)
22579
22711
  throw new Error("Task content changed; replacement preserved without overwrite");
22580
- retryWindowsFileOperation(() => renameSync4(temporary, join27(dir, "task.json")), () => {
22712
+ retryWindowsFileOperation(() => renameSync4(temporary, join28(dir, "task.json")), () => {
22581
22713
  this.assertOwner(lock);
22582
- const now = readBounded(join27(dir, "task.json"), MAX_RECORD_BYTES);
22714
+ const now = readBounded(join28(dir, "task.json"), MAX_RECORD_BYTES);
22583
22715
  if ((now ? contentIdentity(now) : undefined) !== expectedIdentity)
22584
22716
  throw new Error("Task content changed; replacement preserved without overwrite");
22585
22717
  });
@@ -22590,7 +22722,7 @@ class TaskStore extends CheckoutStore {
22590
22722
  }
22591
22723
  }
22592
22724
  checks() {
22593
- const data2 = readBounded(join27(this.root, ".cadence", "assistant", "config.json"), 32768);
22725
+ const data2 = readBounded(join28(this.root, ".cadence", "assistant", "config.json"), 32768);
22594
22726
  if (!data2)
22595
22727
  return [];
22596
22728
  const value = parseRecord(data2);
@@ -22604,8 +22736,8 @@ class TaskStore extends CheckoutStore {
22604
22736
  readLog(name) {
22605
22737
  if (!/^[a-f0-9-]{36}\.log$/.test(name))
22606
22738
  throw new Error("Invalid diagnostic name");
22607
- this.inspectPrivateFile(join27(this.privateRoot, name), 65536);
22608
- const data2 = readBounded(join27(this.privateRoot, name), 65536);
22739
+ this.inspectPrivateFile(join28(this.privateRoot, name), 65536);
22740
+ const data2 = readBounded(join28(this.privateRoot, name), 65536);
22609
22741
  return data2 ? diagnosticText(data2.toString("utf8"), 65536) : "Private diagnostic unavailable";
22610
22742
  }
22611
22743
  writeLog(lock, output) {
@@ -22613,7 +22745,7 @@ class TaskStore extends CheckoutStore {
22613
22745
  throw new Error("Not the lock owner");
22614
22746
  this.assertOwner(lock);
22615
22747
  const name = `${randomUUID13()}.log`;
22616
- writeFileSync4(join27(this.privateRoot, name), diagnosticText(output, 65536), {
22748
+ writeFileSync5(join28(this.privateRoot, name), diagnosticText(output, 65536), {
22617
22749
  flag: "wx",
22618
22750
  mode: 384
22619
22751
  });
@@ -22696,7 +22828,7 @@ import {
22696
22828
  openSync as openSync9,
22697
22829
  realpathSync as realpathSync10
22698
22830
  } from "node:fs";
22699
- import { dirname as dirname19, isAbsolute as isAbsolute10, join as join28, relative as relative6, sep as sep6 } from "node:path";
22831
+ import { dirname as dirname19, isAbsolute as isAbsolute11, join as join29, relative as relative6, sep as sep6 } from "node:path";
22700
22832
  function summary(text2, maximum, runId) {
22701
22833
  const label = `[Cadence summary${runId ? `; run ${runId}` : ""}; retained history is separate]
22702
22834
  `;
@@ -22711,12 +22843,12 @@ function summary(text2, maximum, runId) {
22711
22843
  end--;
22712
22844
  return label + bytes.subarray(0, end).toString("utf8") + tail;
22713
22845
  }
22714
- function publicationPhase(run2) {
22715
- if (!run2.settlement)
22846
+ function publicationPhase(run) {
22847
+ if (!run.settlement)
22716
22848
  return "running";
22717
- switch (settlementOutcome(run2.settlement)) {
22849
+ switch (settlementOutcome(run.settlement)) {
22718
22850
  case "completed":
22719
- return run2.admission?.kind === "generate-plan" ? "planning" : "review";
22851
+ return run.admission?.kind === "generate-plan" ? "planning" : "review";
22720
22852
  case "failed":
22721
22853
  case "blocked":
22722
22854
  return "failed";
@@ -22729,7 +22861,7 @@ function publicationPhase(run2) {
22729
22861
  function bad11() {
22730
22862
  throw new ContractError("conflict");
22731
22863
  }
22732
- function publicationRecord(store, reader, intent, link, run2, request3, expected, facts, snapshotSeq) {
22864
+ function publicationRecord(store, reader, intent, link, run, request3, expected, facts, snapshotSeq) {
22733
22865
  const identity = intent.identity;
22734
22866
  if (identity.kind !== "action")
22735
22867
  bad11();
@@ -22746,7 +22878,7 @@ function publicationRecord(store, reader, intent, link, run2, request3, expected
22746
22878
  if (action.kind !== "create" || !request3.cwd || store.list().length >= 1000)
22747
22879
  bad11();
22748
22880
  const cwd = realpathSync10(request3.cwd), within = relative6(store.root, cwd);
22749
- if (isAbsolute10(within) || within === ".." || within.startsWith(`..${sep6}`))
22881
+ if (isAbsolute11(within) || within === ".." || within.startsWith(`..${sep6}`))
22750
22882
  bad11();
22751
22883
  record2 = {
22752
22884
  schema: TASK_SCHEMA,
@@ -22779,7 +22911,7 @@ function publicationRecord(store, reader, intent, link, run2, request3, expected
22779
22911
  if (mode === "baseline") {
22780
22912
  if (!facts.some(({ link: l, fact: f }) => l.taskId === link.taskId && l.runId === link.runId && f.kind === "changes" && f.stage === "before" && canonicalJson(f.content) === canonicalJson(ref)))
22781
22913
  bad11();
22782
- } else if (!run2 || ![...run2.children.values()].some((c) => c.completion?.recording.status === "committed" && canonicalJson(c.completion.recording.detail.content) === canonicalJson(ref)))
22914
+ } else if (!run || ![...run.children.values()].some((c) => c.completion?.recording.status === "committed" && canonicalJson(c.completion.recording.detail.content) === canonicalJson(ref)))
22783
22915
  bad11();
22784
22916
  let preview = "";
22785
22917
  for (const part of reader.parts(detail, snapshotSeq))
@@ -22812,12 +22944,12 @@ function publicationRecord(store, reader, intent, link, run2, request3, expected
22812
22944
  record2.phase = "planning";
22813
22945
  delete record2.review;
22814
22946
  }
22815
- if (run2) {
22816
- record2.phase = publicationPhase(run2);
22947
+ if (run) {
22948
+ record2.phase = publicationPhase(run);
22817
22949
  delete record2.review;
22818
22950
  let result = request3.result ? retained(request3.result, "result") : "";
22819
22951
  if (!request3.result)
22820
- for (const child of run2.children.values()) {
22952
+ for (const child of run.children.values()) {
22821
22953
  if (child.completion?.recording.status === "committed") {
22822
22954
  const text2 = retained(child.completion.recording.detail.content, "result");
22823
22955
  if (Buffer.byteLength(result) < 32768)
@@ -22826,24 +22958,24 @@ ${text2}
22826
22958
  `;
22827
22959
  }
22828
22960
  }
22829
- if (run2.settlement)
22830
- result = `Execution: ${settlementOutcome(run2.settlement)} (checks and human review are separate).
22961
+ if (run.settlement)
22962
+ result = `Execution: ${settlementOutcome(run.settlement)} (checks and human review are separate).
22831
22963
  ${result}`;
22832
- if (run2.admission?.kind === "generate-plan")
22964
+ if (run.admission?.kind === "generate-plan")
22833
22965
  result = `Advisory plan proposal only; not saved or authorized for Start. Explicitly edit/accept and Save a plan before a separate Start.
22834
22966
  ${result}`;
22835
22967
  record2.result = summary(result, 16384, link.runId);
22836
- if (action.kind === "check" && run2.check && run2.settlement?.kind === "check") {
22968
+ if (action.kind === "check" && run.check && run.settlement?.kind === "check") {
22837
22969
  if (record2.checks.length >= 32)
22838
22970
  bad11();
22839
- const s = run2.settlement;
22971
+ const s = run.settlement;
22840
22972
  const fact = facts.findLast(({ link: l, fact: f }) => l.runId === link.runId && f.kind === "check-settled")?.fact;
22841
22973
  if (fact?.kind !== "check-settled")
22842
22974
  bad11();
22843
22975
  record2.checks.push({
22844
- name: run2.check.selection.name,
22845
- command: run2.check.selection.command,
22846
- timeoutMs: run2.check.selection.timeoutMs,
22976
+ name: run.check.selection.name,
22977
+ command: run.check.selection.command,
22978
+ timeoutMs: run.check.selection.timeoutMs,
22847
22979
  cwd: record2.cwd,
22848
22980
  exitCode: s.native.exitCode,
22849
22981
  durationMs: s.native.durationMs,
@@ -22881,7 +23013,7 @@ ${result}`;
22881
23013
  function syncTaskPublication(store, taskId2) {
22882
23014
  if (process.platform === "win32")
22883
23015
  return;
22884
- for (let path = join28(store.tasks, taskId2);; path = dirname19(path)) {
23016
+ for (let path = join29(store.tasks, taskId2);; path = dirname19(path)) {
22885
23017
  if (!safeDirectory(path))
22886
23018
  throw new ContractError("conflict");
22887
23019
  const fd = openSync9(path, constants8.O_RDONLY | constants8.O_DIRECTORY);
@@ -22898,11 +23030,11 @@ function syncTaskPublication(store, taskId2) {
22898
23030
  }
22899
23031
 
22900
23032
  // src/history/review.ts
22901
- function reviewIssues(run2, current2, code2, epoch) {
23033
+ function reviewIssues(run, current2, code2, epoch) {
22902
23034
  const issues = new Set;
22903
23035
  if (!current2.observation.complete)
22904
23036
  issues.add("incomplete-observation");
22905
- const projections = run2.projections(epoch);
23037
+ const projections = run.projections(epoch);
22906
23038
  if (projections.some((p) => p.outcome !== "completed"))
22907
23039
  issues.add("partial-results");
22908
23040
  if (projections.some((p) => p.coverage.observed !== "complete" || p.coverage.source !== "complete" || p.coverage.omissions.length))
@@ -23536,9 +23668,9 @@ class HistoryWriter {
23536
23668
  if (state.admission?.context.task)
23537
23669
  tasks.add(state.admission.context.task.id);
23538
23670
  for (const row of rows) {
23539
- const v = row.value, run2 = this.rowRunId(v);
23540
- if (run2)
23541
- runs.add(run2);
23671
+ const v = row.value, run = this.rowRunId(v);
23672
+ if (run)
23673
+ runs.add(run);
23542
23674
  if (v.kind === "owner" || v.kind === "capture" || v.kind === "launch" || v.kind === "settlement")
23543
23675
  tasks.add(v.link.taskId);
23544
23676
  if (v.kind === "admission" && v.intent.identity.kind === "action") {
@@ -23634,10 +23766,10 @@ class HistoryWriter {
23634
23766
  try {
23635
23767
  const budget = HistoryReadBudget.authority();
23636
23768
  const intent = this.files.readCommand(commandId, budget);
23637
- const directoryExists = this.files.files.directory(join29(this.files.directory, "commands", commandId));
23769
+ const directoryExists = this.files.files.directory(join30(this.files.directory, "commands", commandId));
23638
23770
  const wanted = intent ? decodeAdmissionIntent(json(intent, RECORD_BYTES)) : null;
23639
23771
  let found = null;
23640
- let run2 = null;
23772
+ let run = null;
23641
23773
  let operation = null;
23642
23774
  const scan = emptyScan();
23643
23775
  for (const batch of this.files.scan(scan, false, budget)) {
@@ -23647,19 +23779,19 @@ class HistoryWriter {
23647
23779
  return { status: "inconclusive" };
23648
23780
  found = row.value.record;
23649
23781
  if (row.value.intent.identity.kind === "action" && row.value.intent.runId)
23650
- run2 = new RunState(row.value.intent.runId);
23782
+ run = new RunState(row.value.intent.runId);
23651
23783
  else if (row.value.intent.identity.kind === "action")
23652
23784
  operation = new OperationState(row.value.intent.operationId);
23653
23785
  }
23654
23786
  for (const row of batch.rows) {
23655
- run2?.apply(row, batch.marker.last);
23787
+ run?.apply(row, batch.marker.last);
23656
23788
  operation?.apply(row, batch.marker.last);
23657
23789
  }
23658
23790
  }
23659
23791
  if (found)
23660
23792
  return {
23661
23793
  status: "found",
23662
- record: decodeStoredCommand(run2?.receipt() ?? operation?.receipt() ?? found)
23794
+ record: decodeStoredCommand(run?.receipt() ?? operation?.receipt() ?? found)
23663
23795
  };
23664
23796
  if (wanted || directoryExists || scan.tail)
23665
23797
  return { status: "inconclusive" };
@@ -23780,8 +23912,8 @@ class HistoryWriter {
23780
23912
  this.assertOrdinary();
23781
23913
  const bytes = encoded(intent);
23782
23914
  this.charge(Buffer.byteLength(bytes), intent.runId, true);
23783
- this.files.files.create(join29(this.files.directory, "commands", intent.commandId, "intent.json"), bytes, RECORD_BYTES);
23784
- this.files.syncParents(join29(this.files.directory, "commands", intent.commandId, "intent.json"));
23915
+ this.files.files.create(join30(this.files.directory, "commands", intent.commandId, "intent.json"), bytes, RECORD_BYTES);
23916
+ this.files.syncParents(join30(this.files.directory, "commands", intent.commandId, "intent.json"));
23785
23917
  await this.options.observeWrite?.("intent");
23786
23918
  const policy = this.resourcePolicy(intent.identity.kind === "action" ? intent.identity.expected.configRev : 1);
23787
23919
  return { kind: "admission", intent, record: record2, policy };
@@ -23915,11 +24047,11 @@ class HistoryWriter {
23915
24047
  continue;
23916
24048
  try {
23917
24049
  const checks = checkFold(this.files, taskId2, head.seq, HistoryReadBudget.authority()).state();
23918
- const run2 = latestTaskRun(this.files, taskId2, head.seq, HistoryReadBudget.authority());
24050
+ const run = latestTaskRun(this.files, taskId2, head.seq, HistoryReadBudget.authority());
23919
24051
  const plan = planFold(this.files, taskId2, head.seq, HistoryReadBudget.authority(), new HistoryNavigation(this.files), true).state();
23920
24052
  taskFoldMemory(this.files).remember(taskId2, head, {
23921
24053
  checks,
23922
- run: run2,
24054
+ run,
23923
24055
  plan
23924
24056
  });
23925
24057
  } catch {}
@@ -23979,10 +24111,10 @@ class HistoryWriter {
23979
24111
  }
23980
24112
  };
23981
24113
  assertContext();
23982
- const run2 = intent.runId ? this.retainedRun(intent.runId) : null;
23983
- if (run2 && !run2.admission)
24114
+ const run = intent.runId ? this.retainedRun(intent.runId) : null;
24115
+ if (run && !run.admission)
23984
24116
  throw new ContractError("conflict");
23985
- expected = run2 ? run2.publicationExpected() : operation.state.publicationExpected();
24117
+ expected = run ? run.publicationExpected() : operation.state.publicationExpected();
23986
24118
  link = {
23987
24119
  epoch: identity.expected.epoch,
23988
24120
  taskId: taskId2,
@@ -23992,7 +24124,7 @@ class HistoryWriter {
23992
24124
  const reader = HistoryReader.open(this.lease.coordination);
23993
24125
  if (!reader)
23994
24126
  throw new ContractError("unavailable");
23995
- record2 = publicationRecord(legacyTaskStore(this.lease.coordination), reader, intent, link, run2, request3, expected, operation.facts, this.state.committedSeq);
24127
+ record2 = publicationRecord(legacyTaskStore(this.lease.coordination), reader, intent, link, run, request3, expected, operation.facts, this.state.committedSeq);
23996
24128
  this.charge(2 * Buffer.byteLength(`${JSON.stringify(record2, null, 2)}
23997
24129
  `), intent.runId, true);
23998
24130
  return this.ownerValue({
@@ -24137,9 +24269,9 @@ class HistoryWriter {
24137
24269
  }
24138
24270
  childSlots() {
24139
24271
  let slots = 0;
24140
- for (const run2 of this.runs.values())
24141
- for (const auth of run2.auth.values()) {
24142
- const child = run2.children.get(auth.intent.childRunId);
24272
+ for (const run of this.runs.values())
24273
+ for (const auth of run.auth.values()) {
24274
+ const child = run.children.get(auth.intent.childRunId);
24143
24275
  if (child ? child.completion === null : auth.result === null || auth.result.outcome === "resolved" && !auth.result.admissionClosed)
24144
24276
  slots++;
24145
24277
  }
@@ -24515,10 +24647,10 @@ class HistoryWriter {
24515
24647
  const checks = decodeCheckObligations(review.checks);
24516
24648
  if (checks.taskId !== input.link.taskId || checks.revision !== fact.checksRevision || canonicalJson(review.observation) !== canonicalJson(changes.observation))
24517
24649
  throw new ContractError("conflict");
24518
- const run2 = this.retainedRun(fact.runId);
24519
- if (!run2.drained || run2.admission?.context.task?.id !== input.link.taskId)
24650
+ const run = this.retainedRun(fact.runId);
24651
+ if (!run.drained || run.admission?.context.task?.id !== input.link.taskId)
24520
24652
  throw new ContractError("conflict");
24521
- const issues = reviewIssues(run2, { ...review, checks }, identity.expected.task?.kind === "code", input.link.epoch);
24653
+ const issues = reviewIssues(run, { ...review, checks }, identity.expected.task?.kind === "code", input.link.epoch);
24522
24654
  if (issues.length && (fact.outcome !== "reviewed-with-issues" || !fact.acceptIssues))
24523
24655
  throw new ContractError("conflict");
24524
24656
  }
@@ -24576,11 +24708,11 @@ class HistoryWriter {
24576
24708
  throw new ContractError("conflict");
24577
24709
  }
24578
24710
  if (fact.kind === "gate" && fact.reservationId && fact.lane !== "check") {
24579
- const run2 = value.link.runId ? this.runs.get(value.link.runId) ?? this.retainedRun(value.link.runId) : null;
24580
- if (!run2?.admission)
24711
+ const run = value.link.runId ? this.runs.get(value.link.runId) ?? this.retainedRun(value.link.runId) : null;
24712
+ if (!run?.admission)
24581
24713
  throw new ContractError("conflict");
24582
- const selected2 = this.files.readAdmission(run2.runId, run2.admission);
24583
- const allocation = run2.admission.assignments.find((a) => a.childRunId === fact.reservationId);
24714
+ const selected2 = this.files.readAdmission(run.runId, run.admission);
24715
+ const allocation = run.admission.assignments.find((a) => a.childRunId === fact.reservationId);
24584
24716
  const assignment = selected2.graph?.assignments.find((a) => a.id === allocation?.assignmentId);
24585
24717
  if (!allocation || (assignment?.purpose === "edit" ? "writer" : "reader") !== fact.lane)
24586
24718
  throw new ContractError("conflict");
@@ -24684,7 +24816,7 @@ function digestHistory(files, exclude) {
24684
24816
  const walk = (path, depth) => {
24685
24817
  if (depth > 8 || !files.files.directory(path))
24686
24818
  throw new ContractError("corrupt-selected");
24687
- const directory = lstatSync17(path);
24819
+ const directory = lstatSync18(path);
24688
24820
  digest.update(`incarnation:${directory.dev}:${directory.ino}
24689
24821
  `);
24690
24822
  const dir = opendirSync8(path), names2 = [];
@@ -24698,11 +24830,11 @@ function digestHistory(files, exclude) {
24698
24830
  dir.closeSync();
24699
24831
  }
24700
24832
  for (const name of names2.sort()) {
24701
- const selected2 = join30(path, name);
24833
+ const selected2 = join31(path, name);
24702
24834
  if (selected2 === exclude)
24703
24835
  continue;
24704
24836
  const rel = relative7(files.directory, selected2);
24705
- if (lstatSync17(selected2).isDirectory()) {
24837
+ if (lstatSync18(selected2).isDirectory()) {
24706
24838
  digest.update(`directory:${Buffer.byteLength(rel)}:${rel}
24707
24839
  `);
24708
24840
  walk(selected2, depth + 1);
@@ -24759,7 +24891,7 @@ function damaged(error) {
24759
24891
  }
24760
24892
  async function healHistory(lease, log) {
24761
24893
  lease.assert();
24762
- const c = lease.coordination, directory = join30(c.directory, "history-v2");
24894
+ const c = lease.coordination, directory = join31(c.directory, "history-v2");
24763
24895
  let files;
24764
24896
  let broken = false;
24765
24897
  try {
@@ -24790,9 +24922,9 @@ async function healHistory(lease, log) {
24790
24922
  }
24791
24923
 
24792
24924
  // src/subagent-process.ts
24793
- import { spawn as spawn3 } from "node:child_process";
24925
+ import { spawn as spawn4 } from "node:child_process";
24794
24926
  import { createHash as createHash26, randomUUID as randomUUID18 } from "node:crypto";
24795
- import { join as join31 } from "node:path";
24927
+ import { join as join32 } from "node:path";
24796
24928
  import { StringDecoder } from "node:string_decoder";
24797
24929
  import { fileURLToPath as fileURLToPath5 } from "node:url";
24798
24930
  // src/worker-capture.mjs
@@ -25377,7 +25509,7 @@ class WorkerRecording {
25377
25509
  // src/subagent-process.ts
25378
25510
  function terminateWindowsTree(pid, fallback) {
25379
25511
  const root = process.env.SystemRoot;
25380
- const taskkill = spawn3(root ? join31(root, "System32", "taskkill.exe") : "taskkill.exe", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
25512
+ const taskkill = spawn4(root ? join32(root, "System32", "taskkill.exe") : "taskkill.exe", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
25381
25513
  taskkill.once("error", fallback);
25382
25514
  taskkill.once("close", (code2) => {
25383
25515
  if (code2 !== 0)
@@ -25415,10 +25547,8 @@ function runProcess(spec) {
25415
25547
  throw new Error("Invalid service check context");
25416
25548
  if (spec.input !== undefined && Buffer.byteLength(spec.input) > 128 * 1024)
25417
25549
  return Promise.resolve(early("failed", "Worker input exceeds bound"));
25418
- if (spec.imageInput !== undefined && Buffer.byteLength(spec.imageInput) > IMAGE_LIMITS.wireBytes)
25419
- return Promise.resolve(early("failed", "Image input exceeds bound"));
25420
25550
  return new Promise((resolve12) => {
25421
- const child = spawn3(spec.command, spec.args, {
25551
+ const child = spawn4(spec.command, spec.args, {
25422
25552
  cwd: spec.cwd,
25423
25553
  env: spec.env ?? safeChildEnv(),
25424
25554
  detached: process.platform !== "win32",
@@ -25559,7 +25689,6 @@ function runProcess(spec) {
25559
25689
  });
25560
25690
  ingressStop.abort();
25561
25691
  };
25562
- let bridgeCalls = 0;
25563
25692
  let bridgeBusy = false;
25564
25693
  if (spec.onCoordinator)
25565
25694
  child.on("message", (message2) => {
@@ -25580,7 +25709,7 @@ function runProcess(spec) {
25580
25709
  if (child.connected && !settled && !stopping)
25581
25710
  child.send({ id, ok: false }, () => {});
25582
25711
  };
25583
- if (++bridgeCalls > 16 || bridgeBusy || Buffer.byteLength(JSON.stringify(message2)) > 65536) {
25712
+ if (bridgeBusy || Buffer.byteLength(JSON.stringify(message2)) > 65536) {
25584
25713
  refuse3();
25585
25714
  return;
25586
25715
  }
@@ -25821,11 +25950,7 @@ function encodeEnvelope(material, timeoutMs, captured, roots = [material.cwd]) {
25821
25950
  ...literals(material.auth.env ?? {}),
25822
25951
  ...selected2.redactionLiterals
25823
25952
  ];
25824
- const investigation = {
25825
- roots,
25826
- timeoutMs,
25827
- deadlineMs: Number(process.hrtime.bigint() / 1000000n) + timeoutMs
25828
- };
25953
+ const investigation = { roots, timeoutMs };
25829
25954
  const input = JSON.stringify({ ...material, investigation });
25830
25955
  if (!sameNetwork(scoped, scopedNetwork(JSON.parse(input)), false))
25831
25956
  throw new Error("network");
@@ -27115,7 +27240,7 @@ class ServiceOwner {
27115
27240
 
27116
27241
  // src/service/workbench.ts
27117
27242
  import { opendirSync as opendirSync12 } from "node:fs";
27118
- import { join as join37 } from "node:path";
27243
+ import { join as join38 } from "node:path";
27119
27244
 
27120
27245
  // src/service/conversation-images.ts
27121
27246
  var binding = (send2) => {
@@ -27144,15 +27269,10 @@ class ConversationImages {
27144
27269
  this.staged.delete(id);
27145
27270
  let row = this.staged.get(c.imageId);
27146
27271
  if (!row) {
27147
- const rows = [...this.staged.values()];
27148
- const message2 = rows.filter((r) => r.commandId === c.send.commandId);
27149
27272
  if (c.offset !== 0)
27150
27273
  throw new ContractError("stale");
27151
- if (rows.length >= IMAGE_LIMITS.stagedCount || rows.reduce((n, r) => n + r.size, c.size) > IMAGE_LIMITS.stagedBytes || message2.length >= IMAGE_LIMITS.count || message2.reduce((n, r) => n + r.size, c.size) > IMAGE_LIMITS.totalBytes)
27152
- throw new ContractError("capacity");
27153
27274
  row = {
27154
27275
  binding: key2,
27155
- commandId: c.send.commandId,
27156
27276
  caller: who,
27157
27277
  mimeType: c.mimeType,
27158
27278
  size: c.size,
@@ -27193,16 +27313,12 @@ class ConversationImages {
27193
27313
  const who = identity(caller), key2 = binding(send2);
27194
27314
  if (new Set(send2.images).size !== send2.images.length)
27195
27315
  throw new ContractError("invalid");
27196
- let size2 = 0;
27197
27316
  const images = send2.images.map((id) => {
27198
27317
  const row = this.staged.get(id);
27199
27318
  if (!row?.ready || row.caller !== who || row.binding !== key2 || this.now() - row.at > IMAGE_LIMITS.idleMs)
27200
27319
  throw new ContractError("stale");
27201
- size2 += row.size;
27202
27320
  return { type: "image", data: row.data, mimeType: row.mimeType };
27203
27321
  });
27204
- if (size2 > IMAGE_LIMITS.totalBytes)
27205
- throw new ContractError("capacity");
27206
27322
  for (const id of send2.images)
27207
27323
  this.staged.delete(id);
27208
27324
  return images;
@@ -27211,7 +27327,7 @@ class ConversationImages {
27211
27327
 
27212
27328
  // src/service/conversation-workflow.ts
27213
27329
  import { randomUUID as randomUUID21 } from "node:crypto";
27214
- import { join as join32 } from "node:path";
27330
+ import { join as join33 } from "node:path";
27215
27331
 
27216
27332
  // src/cadence-instructions.ts
27217
27333
  var CADENCE_INSTRUCTIONS = `CADENCE CONVERSATION MODE — stays enabled for this entire conversation, including after a goal completes, until the user explicitly exits by typing 退出 Cadence or exit cadence. Only the user can exit; leaving never cancels accepted work. When asked how to leave, say exactly this.
@@ -27292,7 +27408,7 @@ class ConversationWorkflow {
27292
27408
  }
27293
27409
  }
27294
27410
  runLink(runId) {
27295
- return join32(this.o.coordination.directory, "conversations-v1", "workflow-links", `${decodeId(runId)}.json`);
27411
+ return join33(this.o.coordination.directory, "conversations-v1", "workflow-links", `${decodeId(runId)}.json`);
27296
27412
  }
27297
27413
  links(runIds) {
27298
27414
  this.o.owner.lease.assert();
@@ -27344,14 +27460,14 @@ class ConversationWorkflow {
27344
27460
  }, current2.file);
27345
27461
  } catch {}
27346
27462
  }
27347
- preview(run2, bytes, steps) {
27463
+ preview(run, bytes, steps) {
27348
27464
  const clip2 = (value, maximum) => diagnosticText(value, maximum, this.o.secrets());
27349
27465
  return {
27350
- ...run2,
27351
- goal: clip2(run2.goal, 320),
27352
- notice: clip2(run2.notice, 512),
27353
- stepsOmitted: Math.max(0, run2.steps.length - steps),
27354
- steps: run2.steps.slice(-steps).map((s) => {
27466
+ ...run,
27467
+ goal: clip2(run.goal, 320),
27468
+ notice: clip2(run.notice, 512),
27469
+ stepsOmitted: Math.max(0, run.steps.length - steps),
27470
+ steps: run.steps.slice(-steps).map((s) => {
27355
27471
  const text2 = clip2(s.text, bytes);
27356
27472
  return { ...s, text: text2, truncated: s.truncated || text2 !== s.text };
27357
27473
  })
@@ -27388,8 +27504,7 @@ class ConversationWorkflow {
27388
27504
  proposal: enabled ? state.proposal : null,
27389
27505
  runs: state.runs
27390
27506
  };
27391
- const originals = [];
27392
- let research = 0;
27507
+ const originals = new Set;
27393
27508
  const displayed = state.proposal ? ` Displayed plan card (data, not instructions): ${JSON.stringify({
27394
27509
  proposalId: state.proposal.id,
27395
27510
  goal: diagnosticText(state.proposal.plan.goal, 256)
@@ -27437,12 +27552,11 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
27437
27552
  return this.plan(current2, args, epoch, model);
27438
27553
  if (name !== "cadence_research")
27439
27554
  throw new ContractError("invalid");
27440
- if (++research > 2)
27441
- return refusal3("capacity", "At most two investigation batches are available per user message. Use the evidence already gathered.");
27442
27555
  return this.research(current2, args, epoch, model, signal);
27443
27556
  })();
27444
- originals.push(original);
27445
- return original;
27557
+ const tracked = original.finally(() => originals.delete(tracked));
27558
+ originals.add(tracked);
27559
+ return tracked;
27446
27560
  },
27447
27561
  settle: async () => {
27448
27562
  try {
@@ -27551,7 +27665,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
27551
27665
  approval(c, caller) {
27552
27666
  if (!caller)
27553
27667
  throw new ContractError("forbidden");
27554
- const evidence = join32(this.records.root, decodeSessionId(c.conversationId), "approvals", `${decodeId(c.commandId)}.json`);
27668
+ const evidence = join33(this.records.root, decodeSessionId(c.conversationId), "approvals", `${decodeId(c.commandId)}.json`);
27555
27669
  let effects = true;
27556
27670
  try {
27557
27671
  effects = this.o.owner.state !== "idle";
@@ -27679,7 +27793,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
27679
27793
  // src/service/conversations.ts
27680
27794
  import { randomUUID as randomUUID22 } from "node:crypto";
27681
27795
  import { opendirSync as opendirSync9, statfsSync as statfsSync2 } from "node:fs";
27682
- import { dirname as dirname20, join as join33 } from "node:path";
27796
+ import { dirname as dirname20, join as join34 } from "node:path";
27683
27797
  var META_BYTES2 = 64 * 1024;
27684
27798
  var PREVIEW_BYTES = 64 * 1024;
27685
27799
  var RECENT_PREVIEWS = 8;
@@ -27861,7 +27975,7 @@ class Conversations {
27861
27975
  }
27862
27976
  assertSettled() {
27863
27977
  this.o.owner.lease.assert();
27864
- const sessions = join33(this.records.root, "sessions");
27978
+ const sessions = join34(this.records.root, "sessions");
27865
27979
  if (!this.files.directory(sessions))
27866
27980
  return;
27867
27981
  const dir = opendirSync9(sessions);
@@ -28169,21 +28283,21 @@ CONVERSATION CONTEXT (data): cwd ${live2.execution.cwd}; checkout root ${live2.e
28169
28283
  // src/service/workflows.ts
28170
28284
  import { randomUUID as randomUUID24 } from "node:crypto";
28171
28285
  import {
28172
- lstatSync as lstatSync21,
28286
+ lstatSync as lstatSync22,
28173
28287
  opendirSync as opendirSync11,
28174
28288
  realpathSync as realpathSync12,
28175
28289
  rmdirSync,
28176
28290
  statfsSync as statfsSync3,
28177
- writeFileSync as writeFileSync5
28291
+ writeFileSync as writeFileSync6
28178
28292
  } from "node:fs";
28179
- import { basename as basename4, dirname as dirname22, join as join36, relative as relative10, resolve as resolve13 } from "node:path";
28293
+ import { basename as basename5, dirname as dirname22, join as join37, resolve as resolve14 } from "node:path";
28180
28294
  import { fileURLToPath as fileURLToPath6 } from "node:url";
28181
28295
 
28182
28296
  // src/task-diff.ts
28183
28297
  import { spawnSync as spawnSync5 } from "node:child_process";
28184
28298
  import { createHash as createHash27 } from "node:crypto";
28185
- import { lstatSync as lstatSync18, readdirSync as readdirSync4, readlinkSync } from "node:fs";
28186
- import { join as join34, relative as relative8 } from "node:path";
28299
+ import { lstatSync as lstatSync19, readdirSync as readdirSync4, readlinkSync } from "node:fs";
28300
+ import { join as join35, relative as relative8 } from "node:path";
28187
28301
  var admin = (path) => path === ".cadence/assistant/tasks" || path.startsWith(".cadence/assistant/tasks/");
28188
28302
  var GIT_OUTPUT_BYTES = 16 * 1024 * 1024;
28189
28303
  function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
@@ -28226,8 +28340,8 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
28226
28340
  return;
28227
28341
  }
28228
28342
  try {
28229
- const path = join34(root, name);
28230
- const st = lstatSync18(path);
28343
+ const path = join35(root, name);
28344
+ const st = lstatSync19(path);
28231
28345
  add(name, `${st.mode}:${st.size}`);
28232
28346
  if (st.isSymbolicLink()) {
28233
28347
  add(name, readlinkSync(path));
@@ -28367,7 +28481,7 @@ ${data2.toString("utf8")}`);
28367
28481
  return;
28368
28482
  }
28369
28483
  for (const name of names2) {
28370
- const path = join34(dir, name);
28484
+ const path = join35(dir, name);
28371
28485
  const rel = relative8(root, path).split("\\").join("/");
28372
28486
  if (rel === ".git" || admin(rel))
28373
28487
  continue;
@@ -28376,7 +28490,7 @@ ${data2.toString("utf8")}`);
28376
28490
  break;
28377
28491
  }
28378
28492
  try {
28379
- const st = lstatSync18(path);
28493
+ const st = lstatSync19(path);
28380
28494
  if (st.isDirectory())
28381
28495
  walk(path, depth + 1);
28382
28496
  else
@@ -28401,6 +28515,26 @@ ${data2.toString("utf8")}`);
28401
28515
  return { fingerprint: hash3.digest("hex"), text: text2, complete, git: isGit };
28402
28516
  }
28403
28517
 
28518
+ // src/worker-workspace.mjs
28519
+ import { isAbsolute as isAbsolute12, relative as relative9, resolve as resolve12, sep as sep7 } from "node:path";
28520
+ function withinRoot(root, path) {
28521
+ const part = relative9(root, path);
28522
+ return part === "" || !isAbsolute12(part) && part !== ".." && !part.startsWith(`..${sep7}`);
28523
+ }
28524
+ var absolute2 = (value) => {
28525
+ if (typeof value !== "string" || !isAbsolute12(value) || value.includes("\x00"))
28526
+ throw new Error("Invalid execution directory");
28527
+ return resolve12(value);
28528
+ };
28529
+ function executionDirectory(execution, tree) {
28530
+ const origin = absolute2(execution.checkoutRoot);
28531
+ const cwd = absolute2(execution.cwd);
28532
+ tree = absolute2(tree);
28533
+ if (!withinRoot(origin, cwd))
28534
+ throw new Error("Execution cwd escaped its checkout");
28535
+ return resolve12(tree, relative9(origin, cwd));
28536
+ }
28537
+
28404
28538
  // src/service/turn-capture.ts
28405
28539
  var TURN_BYTES = 384 * 1024;
28406
28540
  var OMITTED_FLAG2 = {
@@ -28522,13 +28656,13 @@ class TurnCapture {
28522
28656
  }
28523
28657
 
28524
28658
  // src/service/workflow-git.ts
28525
- import { spawn as spawn4, spawnSync as spawnSync6 } from "node:child_process";
28659
+ import { spawn as spawn5, spawnSync as spawnSync6 } from "node:child_process";
28526
28660
  import { createHash as createHash28 } from "node:crypto";
28527
28661
  import {
28528
28662
  closeSync as closeSync10,
28529
28663
  constants as constants9,
28530
28664
  fstatSync as fstatSync7,
28531
- lstatSync as lstatSync19,
28665
+ lstatSync as lstatSync20,
28532
28666
  openSync as openSync10,
28533
28667
  readdirSync as readdirSync5,
28534
28668
  readlinkSync as readlinkSync2,
@@ -28536,7 +28670,7 @@ import {
28536
28670
  realpathSync as realpathSync11
28537
28671
  } from "node:fs";
28538
28672
  import { lstat, open as open2, readdir, readlink } from "node:fs/promises";
28539
- import { dirname as dirname21, isAbsolute as isAbsolute11, join as join35, relative as relative9, resolve as resolve12, sep as sep7 } from "node:path";
28673
+ import { dirname as dirname21, isAbsolute as isAbsolute13, join as join36, relative as relative10, resolve as resolve13, sep as sep8 } from "node:path";
28540
28674
  var NAMES_BYTES = 64 * 1024 * 1024;
28541
28675
  var SYNC_MS = 30000;
28542
28676
  var READ_MS = 120000;
@@ -28579,7 +28713,7 @@ function gitAnswer(cwd, args) {
28579
28713
  }
28580
28714
  function gitRun(cwd, args, timeoutMs = READ_MS) {
28581
28715
  return new Promise((done, fail2) => {
28582
- const child = spawn4("git", gitArguments(args), {
28716
+ const child = spawn5("git", gitArguments(args), {
28583
28717
  cwd,
28584
28718
  env: gitEnvironment(),
28585
28719
  stdio: ["ignore", "pipe", "ignore"],
@@ -28621,20 +28755,20 @@ async function gitHead(cwd) {
28621
28755
  return (await gitText(cwd, ["rev-parse", "--verify", "HEAD"])).trim();
28622
28756
  }
28623
28757
  function contains2(root, path) {
28624
- const within = relative9(root, path);
28625
- return !within || !within.startsWith(`..${sep7}`) && within !== ".." && !isAbsolute11(within);
28758
+ const within = relative10(root, path);
28759
+ return !within || !within.startsWith(`..${sep8}`) && within !== ".." && !isAbsolute13(within);
28626
28760
  }
28627
28761
  function nested(a, b) {
28628
28762
  return contains2(a, b) || contains2(b, a);
28629
28763
  }
28630
28764
  function safeWorkflowFile(cwd, name) {
28631
28765
  workflowPath(name);
28632
- const p = resolve12(cwd, name);
28633
- if (relative9(cwd, p).startsWith(".."))
28766
+ const p = resolve13(cwd, name);
28767
+ if (relative10(cwd, p).startsWith(".."))
28634
28768
  throw new ContractError("forbidden");
28635
28769
  safeDirectory(dirname21(p));
28636
28770
  try {
28637
- const st = lstatSync19(p);
28771
+ const st = lstatSync20(p);
28638
28772
  if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
28639
28773
  throw new ContractError("forbidden");
28640
28774
  } catch (e) {
@@ -28645,12 +28779,12 @@ function safeWorkflowFile(cwd, name) {
28645
28779
  }
28646
28780
  function declaredTarget(cwd, name) {
28647
28781
  workflowPath(name);
28648
- const p = resolve12(cwd, name);
28649
- if (relative9(cwd, p).startsWith(".."))
28782
+ const p = resolve13(cwd, name);
28783
+ if (relative10(cwd, p).startsWith(".."))
28650
28784
  throw new ContractError("forbidden");
28651
28785
  safeDirectory(dirname21(p));
28652
28786
  try {
28653
- const st = lstatSync19(p);
28787
+ const st = lstatSync20(p);
28654
28788
  if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory() || st.isFile() && st.nlink !== 1)
28655
28789
  throw new ContractError("forbidden");
28656
28790
  } catch (e) {
@@ -28730,13 +28864,13 @@ function directoryIdentity(root, name) {
28730
28864
  continue;
28731
28865
  if (++count2 > DIRECTORY_ENTRIES)
28732
28866
  throw tooLarge(name);
28733
- const full = join35(directory, entry), relative10 = `${prefix}${entry}`;
28734
- const st = lstatSync19(full);
28867
+ const full = join36(directory, entry), relative11 = `${prefix}${entry}`;
28868
+ const st = lstatSync20(full);
28735
28869
  if (st.isDirectory()) {
28736
- rows.push(`${relative10}/`);
28737
- visit(full, `${relative10}/`);
28870
+ rows.push(`${relative11}/`);
28871
+ visit(full, `${relative11}/`);
28738
28872
  } else
28739
- rows.push(`${relative10}\x00${fileIdentity(full, st, DIRECTORY_HASH_BYTES)}`);
28873
+ rows.push(`${relative11}\x00${fileIdentity(full, st, DIRECTORY_HASH_BYTES)}`);
28740
28874
  }
28741
28875
  };
28742
28876
  visit(root, "");
@@ -28752,13 +28886,13 @@ async function directoryIdentityAsync(root, name) {
28752
28886
  continue;
28753
28887
  if (++count2 > DIRECTORY_ENTRIES)
28754
28888
  throw tooLarge(name);
28755
- const full = join35(directory, entry), relative10 = `${prefix}${entry}`;
28889
+ const full = join36(directory, entry), relative11 = `${prefix}${entry}`;
28756
28890
  const st = await lstat(full);
28757
28891
  if (st.isDirectory()) {
28758
- rows.push(`${relative10}/`);
28759
- await visit(full, `${relative10}/`);
28892
+ rows.push(`${relative11}/`);
28893
+ await visit(full, `${relative11}/`);
28760
28894
  } else
28761
- rows.push(`${relative10}\x00${await fileIdentityAsync(full, st, DIRECTORY_HASH_BYTES)}`);
28895
+ rows.push(`${relative11}\x00${await fileIdentityAsync(full, st, DIRECTORY_HASH_BYTES)}`);
28762
28896
  }
28763
28897
  };
28764
28898
  await visit(root, "");
@@ -28766,12 +28900,12 @@ async function directoryIdentityAsync(root, name) {
28766
28900
  `))}`;
28767
28901
  }
28768
28902
  function pathIdentity(cwd, name, walk = true) {
28769
- const p = resolve12(cwd, name);
28770
- if (relative9(cwd, p).startsWith(".."))
28903
+ const p = resolve13(cwd, name);
28904
+ if (relative10(cwd, p).startsWith(".."))
28771
28905
  throw new ContractError("forbidden");
28772
28906
  let st;
28773
28907
  try {
28774
- st = lstatSync19(p);
28908
+ st = lstatSync20(p);
28775
28909
  } catch (e) {
28776
28910
  if (absent2(e))
28777
28911
  return null;
@@ -28782,8 +28916,8 @@ function pathIdentity(cwd, name, walk = true) {
28782
28916
  return fileIdentity(p, st, HASH_BYTES);
28783
28917
  }
28784
28918
  async function pathIdentityAsync(cwd, name) {
28785
- const p = resolve12(cwd, name);
28786
- if (relative9(cwd, p).startsWith(".."))
28919
+ const p = resolve13(cwd, name);
28920
+ if (relative10(cwd, p).startsWith(".."))
28787
28921
  throw new ContractError("forbidden");
28788
28922
  let st;
28789
28923
  try {
@@ -28986,20 +29120,20 @@ ${block}
28986
29120
  async function assertWorktree(root, cwd) {
28987
29121
  if (!safeDirectory(cwd))
28988
29122
  throw new ContractError("stale");
28989
- const real = (p) => realpathSync11(resolve12(p));
29123
+ const real = (p) => realpathSync11(resolve13(p));
28990
29124
  if (real((await gitText(cwd, ["rev-parse", "--show-toplevel"])).trim()) !== real(cwd))
28991
29125
  throw new ContractError("stale");
28992
- const common = async (p) => real(resolve12(p, (await gitText(p, ["rev-parse", "--git-common-dir"])).trim()));
29126
+ const common = async (p) => real(resolve13(p, (await gitText(p, ["rev-parse", "--git-common-dir"])).trim()));
28993
29127
  if (await common(root) !== await common(cwd))
28994
29128
  throw new ContractError("stale");
28995
- const marker2 = resolve12(cwd, ".git");
28996
- if (!lstatSync19(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
29129
+ const marker2 = resolve13(cwd, ".git");
29130
+ if (!lstatSync20(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
28997
29131
  throw new ContractError("stale");
28998
29132
  }
28999
29133
 
29000
29134
  // src/service/workflow-history.ts
29001
29135
  import { randomUUID as randomUUID23 } from "node:crypto";
29002
- import { lstatSync as lstatSync20, opendirSync as opendirSync10 } from "node:fs";
29136
+ import { lstatSync as lstatSync21, opendirSync as opendirSync10 } from "node:fs";
29003
29137
  class WorkflowHistoryScanner {
29004
29138
  path;
29005
29139
  directory;
@@ -29010,7 +29144,7 @@ class WorkflowHistoryScanner {
29010
29144
  this.directory = directory;
29011
29145
  }
29012
29146
  incarnation() {
29013
- const st = lstatSync20(this.path, { bigint: true });
29147
+ const st = lstatSync21(this.path, { bigint: true });
29014
29148
  if (!st.isDirectory() || st.isSymbolicLink())
29015
29149
  throw new ContractError("corrupt-selected");
29016
29150
  return `${st.dev}:${st.ino}`;
@@ -29167,8 +29301,8 @@ function workflowResultDetail(value, secrets) {
29167
29301
 
29168
29302
  // src/service/workflows.ts
29169
29303
  var OWNER_RUNTIME = Object.freeze({
29170
- version: "2.0.36",
29171
- build: "a996fe94021d7ae65c3e8da45de2b5e98de031d12bb91a3bc029acdacdd9e8a5",
29304
+ version: "2.0.37",
29305
+ build: "2ef931cc3de86f929b9614b06d1e5b84c1244908bee9de2bfaf24395b1e85e58",
29172
29306
  entry: fileURLToPath6(import.meta.url),
29173
29307
  pid: process.pid,
29174
29308
  node: process.versions.node,
@@ -29373,12 +29507,12 @@ class Workflows {
29373
29507
  constructor(o) {
29374
29508
  this.o = o;
29375
29509
  this.contexts = o.contexts ?? new ConversationContexts(o);
29376
- this.root = join36(o.coordination.directory, "workflows-v1");
29510
+ this.root = join37(o.coordination.directory, "workflows-v1");
29377
29511
  this.cwd = realpathSync12(o.coordination.store.root);
29378
- this.worktreeRoot = join36(o.coordination.stateHome, "cadence-worktrees-v1", basename4(o.coordination.store.privateRoot));
29379
- this.historyScanner = new WorkflowHistoryScanner(join36(this.root, "runs"), () => {
29512
+ this.worktreeRoot = join37(o.coordination.stateHome, "cadence-worktrees-v1", basename5(o.coordination.store.privateRoot));
29513
+ this.historyScanner = new WorkflowHistoryScanner(join37(this.root, "runs"), () => {
29380
29514
  this.o.owner.lease.assert();
29381
- return this.files.directory(join36(this.root, "runs"));
29515
+ return this.files.directory(join37(this.root, "runs"));
29382
29516
  });
29383
29517
  this.recover();
29384
29518
  }
@@ -29386,7 +29520,7 @@ class Workflows {
29386
29520
  return this.o.coordination.files;
29387
29521
  }
29388
29522
  path(id, name) {
29389
- return join36(this.root, "runs", decodeId(id), name);
29523
+ return join37(this.root, "runs", decodeId(id), name);
29390
29524
  }
29391
29525
  write(path, value, expected, max = RECORD_BYTES2) {
29392
29526
  this.o.owner.lease.assert();
@@ -29403,7 +29537,7 @@ class Workflows {
29403
29537
  `), 2048, this.o.secrets());
29404
29538
  }
29405
29539
  recover() {
29406
- const runs = join36(this.root, "runs");
29540
+ const runs = join37(this.root, "runs");
29407
29541
  if (!this.files.directory(runs))
29408
29542
  return;
29409
29543
  const ids = [];
@@ -29438,7 +29572,7 @@ class Workflows {
29438
29572
  const accepted2 = this.retained(this.path(id, "accepted.json"));
29439
29573
  if (!accepted2)
29440
29574
  return;
29441
- let run3;
29575
+ let run2;
29442
29576
  try {
29443
29577
  const o = closed(parseWireJson(accepted2.bytes.toString("utf8"), RECORD_BYTES2), ["epoch", "request"]);
29444
29578
  const request3 = decodeWorkflowRequest(o.request);
@@ -29447,7 +29581,7 @@ class Workflows {
29447
29581
  try {
29448
29582
  goal = this.proposal(request3.proposalId).plan.goal;
29449
29583
  } catch {}
29450
- run3 = {
29584
+ run2 = {
29451
29585
  id,
29452
29586
  epoch: decodeId(o.epoch),
29453
29587
  goal,
@@ -29461,30 +29595,30 @@ class Workflows {
29461
29595
  } catch {
29462
29596
  return;
29463
29597
  }
29464
- this.write(path, run3);
29598
+ this.write(path, run2);
29465
29599
  return;
29466
29600
  }
29467
- let run2;
29601
+ let run;
29468
29602
  try {
29469
- run2 = decodeWorkflowRun(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
29603
+ run = decodeWorkflowRun(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
29470
29604
  } catch {
29471
29605
  return;
29472
29606
  }
29473
- if (run2.id !== id || !["queued", "running"].includes(run2.status) && run2.phase === "finished")
29607
+ if (run.id !== id || !["queued", "running"].includes(run.status) && run.phase === "finished")
29474
29608
  return;
29475
- const integrating = run2.phase === "integrating";
29476
- run2.status = "unknown";
29477
- run2.phase = "finished";
29478
- for (const step of run2.steps)
29609
+ const integrating = run.phase === "integrating";
29610
+ run.status = "unknown";
29611
+ run.phase = "finished";
29612
+ for (const step of run.steps)
29479
29613
  if (step.status === "running")
29480
29614
  step.status = "unknown";
29481
- run2.notice = diagnosticText([
29482
- run2.notice,
29615
+ run.notice = diagnosticText([
29616
+ run.notice,
29483
29617
  RESTARTED,
29484
29618
  integrating ? "Integration had started: inspect the target branch; a fast-forward may have completed." : ""
29485
29619
  ].filter(Boolean).join(`
29486
29620
  `), 2048);
29487
- this.write(path, run2, file);
29621
+ this.write(path, run, file);
29488
29622
  }
29489
29623
  current() {
29490
29624
  this.o.owner.lease.assert();
@@ -29503,7 +29637,14 @@ class Workflows {
29503
29637
  return execution.model;
29504
29638
  }
29505
29639
  executionCwd(live2, tree) {
29506
- const cwd = resolve13(tree, relative10(this.cwd, live2.execution.cwd));
29640
+ if (live2.execution.checkoutRoot !== this.cwd)
29641
+ throw new ContractError("stale");
29642
+ let cwd;
29643
+ try {
29644
+ cwd = executionDirectory(live2.execution, tree);
29645
+ } catch {
29646
+ throw new ContractError("stale");
29647
+ }
29507
29648
  if (!withinWorkspace(tree, cwd))
29508
29649
  throw new ContractError("stale");
29509
29650
  if (tree !== this.cwd) {
@@ -29526,7 +29667,7 @@ class Workflows {
29526
29667
  };
29527
29668
  }
29528
29669
  proposal(id) {
29529
- const file = this.files.read(join36(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES2);
29670
+ const file = this.files.read(join37(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES2);
29530
29671
  if (!file)
29531
29672
  throw new ContractError("unavailable");
29532
29673
  return decodeWorkflowProposal(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
@@ -29548,9 +29689,9 @@ class Workflows {
29548
29689
  this.o.owner.lease.assert();
29549
29690
  return {
29550
29691
  kind: "workflow-active",
29551
- runs: [...this.active.values()].map(({ run: run2 }) => ({
29552
- ...structuredClone(run2),
29553
- goal: clipUnits(run2.goal, 320),
29692
+ runs: [...this.active.values()].map(({ run }) => ({
29693
+ ...structuredClone(run),
29694
+ goal: clipUnits(run.goal, 320),
29554
29695
  steps: []
29555
29696
  }))
29556
29697
  };
@@ -29565,13 +29706,13 @@ class Workflows {
29565
29706
  const view = this.view(id);
29566
29707
  if (view.kind !== "workflow" || view.response.type !== "run")
29567
29708
  throw new ContractError("invalid");
29568
- const run2 = view.response.run;
29709
+ const run = view.response.run;
29569
29710
  return {
29570
29711
  id,
29571
29712
  run: {
29572
- ...run2,
29573
- goal: clipUnits(sanitizeText(run2.goal, this.o.secrets()), 320),
29574
- notice: this.notice(run2.notice),
29713
+ ...run,
29714
+ goal: clipUnits(sanitizeText(run.goal, this.o.secrets()), 320),
29715
+ notice: this.notice(run.notice),
29575
29716
  steps: []
29576
29717
  }
29577
29718
  };
@@ -29597,27 +29738,27 @@ class Workflows {
29597
29738
  const file = live2 ? undefined : this.files.read(this.path(id, "state.json"), RECORD_BYTES2);
29598
29739
  if (!live2 && !file)
29599
29740
  throw new ContractError("unavailable");
29600
- const run2 = decodeWorkflowRun(live2 ? live2.run : parseWireJson(file ? file.bytes.toString("utf8") : "null", RECORD_BYTES2));
29601
- if (run2.id !== id)
29741
+ const run = decodeWorkflowRun(live2 ? live2.run : parseWireJson(file ? file.bytes.toString("utf8") : "null", RECORD_BYTES2));
29742
+ if (run.id !== id)
29602
29743
  throw new ContractError("corrupt-selected");
29603
- if (!live2 && ["running", "queued"].includes(run2.status))
29604
- run2.status = "unknown";
29744
+ if (!live2 && ["running", "queued"].includes(run.status))
29745
+ run.status = "unknown";
29605
29746
  return {
29606
29747
  kind: "workflow",
29607
29748
  commandId: null,
29608
- response: { type: "run", run: run2 }
29749
+ response: { type: "run", run }
29609
29750
  };
29610
29751
  }
29611
29752
  transcript(id, stepId) {
29612
29753
  const view = this.view(id);
29613
29754
  if (view.kind !== "workflow" || view.response.type !== "run")
29614
29755
  throw new ContractError("unavailable");
29615
- const run2 = view.response.run, step = run2.steps.find((s) => s.id === stepId);
29756
+ const run = view.response.run, step = run.steps.find((s) => s.id === stepId);
29616
29757
  if (!step?.childRunId)
29617
29758
  throw new ContractError("unavailable");
29618
29759
  const file = this.files.read(this.path(id, `transcripts/${step.childRunId}.json`), RECORD_BYTES2);
29619
29760
  const turn = file ? decodeChatTurn(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2)) : null;
29620
- if (turn && (turn.id !== step.childRunId || turn.epoch !== run2.epoch))
29761
+ if (turn && (turn.id !== step.childRunId || turn.epoch !== run.epoch))
29621
29762
  throw new ContractError("corrupt-selected");
29622
29763
  if (turn) {
29623
29764
  const secrets = this.o.secrets();
@@ -29679,8 +29820,8 @@ class Workflows {
29679
29820
  if (action === "prepare")
29680
29821
  return [...this.grants.values()].some((g) => g.commandId === id && g.expiresAt >= Date.now());
29681
29822
  if (action === "propose")
29682
- return !!this.files.read(join36(this.root, "proposals", `${id}.json`), RECORD_BYTES2);
29683
- return this.files.directory(join36(this.root, "runs", id));
29823
+ return !!this.files.read(join37(this.root, "proposals", `${id}.json`), RECORD_BYTES2);
29824
+ return this.files.directory(join37(this.root, "runs", id));
29684
29825
  }
29685
29826
  admit(commandId, epoch, r, effect) {
29686
29827
  this.current();
@@ -29710,7 +29851,7 @@ class Workflows {
29710
29851
  };
29711
29852
  if (sanitizeData(p, secrets) !== canonicalJson(p))
29712
29853
  throw new ContractError("forbidden");
29713
- const target3 = join36(this.root, "proposals", `${commandId}.json`);
29854
+ const target3 = join37(this.root, "proposals", `${commandId}.json`);
29714
29855
  const previous = this.files.read(target3, RECORD_BYTES2);
29715
29856
  if (previous) {
29716
29857
  if (previous.bytes.toString("utf8") !== canonicalJson(p))
@@ -29792,7 +29933,7 @@ class Workflows {
29792
29933
  const execution = this.contexts.capture(proposal?.model ?? (request3.action === "research" ? request3.model : (() => {
29793
29934
  throw new ContractError("invalid");
29794
29935
  })()));
29795
- const run2 = {
29936
+ const run = {
29796
29937
  execution,
29797
29938
  id: commandId,
29798
29939
  epoch,
@@ -29815,12 +29956,12 @@ class Workflows {
29815
29956
  };
29816
29957
  const abort = new AbortController;
29817
29958
  let begin;
29818
- const ready2 = new Promise((resolve14) => {
29819
- begin = resolve14;
29959
+ const ready2 = new Promise((resolve15) => {
29960
+ begin = resolve15;
29820
29961
  });
29821
29962
  const live2 = {
29822
29963
  execution,
29823
- run: run2,
29964
+ run,
29824
29965
  abort,
29825
29966
  original: ready2.then(() => this.execute(live2, request3)),
29826
29967
  proposal,
@@ -29834,7 +29975,7 @@ class Workflows {
29834
29975
  this.o.owner.trackConversation(live2.original, () => abort.abort());
29835
29976
  try {
29836
29977
  this.write(acceptedPath, { epoch, request: request3 });
29837
- live2.file = this.write(this.path(commandId, "state.json"), run2);
29978
+ live2.file = this.write(this.path(commandId, "state.json"), run);
29838
29979
  } catch (e) {
29839
29980
  abort.abort();
29840
29981
  begin();
@@ -29844,7 +29985,7 @@ class Workflows {
29844
29985
  return {
29845
29986
  kind: "workflow",
29846
29987
  commandId,
29847
- response: { type: "run", run: structuredClone(run2) }
29988
+ response: { type: "run", run: structuredClone(run) }
29848
29989
  };
29849
29990
  }
29850
29991
  capacity() {
@@ -30029,7 +30170,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
30029
30170
  const running = Promise.resolve().then(() => launchWorkflowWorker(prepared.prepared, runCwd, live2.abort.signal, {
30030
30171
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
30031
30172
  ownerSecrets: this.o.secrets(),
30032
- roots: roots?.length ? roots.map((p) => resolve13(runCwd, p)) : [live2.run.phase === "research" ? runCwd : cwd],
30173
+ roots: roots?.length ? roots.map((p) => resolve14(runCwd, p)) : [live2.run.phase === "research" ? runCwd : cwd],
30033
30174
  onLifecycle: (event) => {
30034
30175
  if (!step.timing)
30035
30176
  return;
@@ -30126,7 +30267,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
30126
30267
  command: shell ? process.platform === "win32" ? environment2.COMSPEC ?? "cmd.exe" : "/bin/sh" : "git",
30127
30268
  args: shell ? process.platform === "win32" ? ["/d", "/s", "/c", `"${operation.check.command}"`] : ["-c", operation.check.command] : gitArguments([
30128
30269
  "-c",
30129
- `core.hooksPath=${join36(this.root, "empty-hooks")}`,
30270
+ `core.hooksPath=${join37(this.root, "empty-hooks")}`,
30130
30271
  "-c",
30131
30272
  "commit.gpgsign=false",
30132
30273
  "-c",
@@ -30435,7 +30576,7 @@ ${changed.map((p) => `- ${p}`).join(`
30435
30576
  const file = safeWorkflowFile(cwd, name);
30436
30577
  if (!safeDirectory(dirname22(file), true))
30437
30578
  throw new ContractError("forbidden");
30438
- writeFileSync5(file, this.documentBody(live2, cwd, plan, name, changed), {
30579
+ writeFileSync6(file, this.documentBody(live2, cwd, plan, name, changed), {
30439
30580
  flag: name === ".cadence/project.md" ? "w" : "wx"
30440
30581
  });
30441
30582
  }
@@ -30446,14 +30587,14 @@ ${changed.map((p) => `- ${p}`).join(`
30446
30587
  for (const directory of [dirname22(this.worktreeRoot), this.worktreeRoot]) {
30447
30588
  if (!safeDirectory(directory, true))
30448
30589
  throw new ContractError("forbidden");
30449
- const st = lstatSync21(directory);
30590
+ const st = lstatSync22(directory);
30450
30591
  if (process.platform !== "win32" && ((st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
30451
30592
  throw new ContractError("forbidden");
30452
30593
  }
30453
- const home = join36(this.worktreeRoot, decodeId(id));
30594
+ const home = join37(this.worktreeRoot, decodeId(id));
30454
30595
  if (safeDirectory(home))
30455
30596
  throw new ContractError("conflict");
30456
- safeDirectory(join36(home, "tasks"), true);
30597
+ safeDirectory(join37(home, "tasks"), true);
30457
30598
  return home;
30458
30599
  }
30459
30600
  async merge(live2, candidate) {
@@ -30521,7 +30662,7 @@ ${result.output}`}`);
30521
30662
  } finally {
30522
30663
  this.closeStep(live2, step);
30523
30664
  }
30524
- for (const directory of [join36(home, "tasks"), home])
30665
+ for (const directory of [join37(home, "tasks"), home])
30525
30666
  try {
30526
30667
  rmdirSync(directory);
30527
30668
  } catch {}
@@ -30553,8 +30694,8 @@ ${result.output}`}`);
30553
30694
  throw new ContractError("invalid");
30554
30695
  const base = target2.head;
30555
30696
  const home = this.worktreeHome(live2.run.id);
30556
- const taskHome = join36(home, "tasks");
30557
- const integration = join36(home, "integration");
30697
+ const taskHome = join37(home, "tasks");
30698
+ const integration = join37(home, "integration");
30558
30699
  await this.gitStep(live2, this.cwd, "worktree-integration", (git) => git(["worktree", "add", "--detach", integration, base]));
30559
30700
  await assertWorktree(this.cwd, integration);
30560
30701
  await this.setup(live2, integration, plan);
@@ -30571,7 +30712,7 @@ ${result.output}`}`);
30571
30712
  live2.run.phase = "implementing";
30572
30713
  this.save(live2);
30573
30714
  const outcomes2 = await Promise.allSettled(batch.map(async (task) => {
30574
- const cwd = join36(taskHome, task.id);
30715
+ const cwd = join37(taskHome, task.id);
30575
30716
  await this.gitStep(live2, this.cwd, `worktree-${task.id}`, (git) => git(["worktree", "add", "--detach", cwd, base]));
30576
30717
  const picks2 = workflowAncestors(plan.tasks, task.id).map((dep) => commits.get(dep.id)).filter((c) => !!c);
30577
30718
  if (picks2.length)
@@ -30637,7 +30778,7 @@ ${result.output}`}`);
30637
30778
  throw new WorkflowRefusal("conflict", `${name} changed during the run; the generated note was not written.`);
30638
30779
  if (!safeDirectory(dirname22(file), true))
30639
30780
  throw new ContractError("unavailable");
30640
- writeFileSync5(file, this.documentBody(live2, this.cwd, plan, name, [...live2.delivered].sort(), true), { flag: before ? "w" : "wx" });
30781
+ writeFileSync6(file, this.documentBody(live2, this.cwd, plan, name, [...live2.delivered].sort(), true), { flag: before ? "w" : "wx" });
30641
30782
  }
30642
30783
  if (!await this.checks(live2, this.cwd, plan))
30643
30784
  throw new Error("Local merge completed, but post-merge checks failed. No reset or rollback was attempted.");
@@ -30756,7 +30897,7 @@ class Workbench {
30756
30897
  });
30757
30898
  this.conversations.assertSettled();
30758
30899
  this.files = new WorkbenchFiles(o.coordination.store.root, [o.coordination.files.namespace, o.agentDir], o.secrets);
30759
- this.projectRoot = join37(o.coordination.files.namespace, "workbench-projects-v1");
30900
+ this.projectRoot = join38(o.coordination.files.namespace, "workbench-projects-v1");
30760
30901
  }
30761
30902
  closeReads() {
30762
30903
  this.images.clear();
@@ -30784,7 +30925,7 @@ class Workbench {
30784
30925
  };
30785
30926
  case "workflow-active": {
30786
30927
  const active2 = this.workflows.activeRuns();
30787
- const ids = active2.runs.map((run2) => run2.id);
30928
+ const ids = active2.runs.map((run) => run.id);
30788
30929
  const browser = this.cadence.links(ids);
30789
30930
  const terminal = this.conversations.records.nativeLinks(ids).filter((link) => !browser.some((b) => b.runId === link.runId));
30790
30931
  return { ...active2, links: [...browser, ...terminal] };
@@ -30878,7 +31019,7 @@ class Workbench {
30878
31019
  for (let e = directory.readSync();e; e = directory.readSync()) {
30879
31020
  if (!e.isFile() || !/^[a-f0-9]{64}\.json$/.test(e.name) || entries2.length > 128)
30880
31021
  throw new ContractError("corrupt-selected");
30881
- const saved = files.read(join37(this.projectRoot, e.name));
31022
+ const saved = files.read(join38(this.projectRoot, e.name));
30882
31023
  if (!saved)
30883
31024
  throw new ContractError("corrupt-selected");
30884
31025
  const row = closed(parseWireJson(saved.bytes.toString("utf8")), [
@@ -30966,7 +31107,7 @@ class Workbench {
30966
31107
  if (this.opening.size >= 64)
30967
31108
  throw new ContractError("capacity");
30968
31109
  const path = this.files.directory(request3.path);
30969
- const marker2 = join37(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
31110
+ const marker2 = join38(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
30970
31111
  const files = this.o.coordination.files;
30971
31112
  if (files.read(marker2))
30972
31113
  throw new ContractError("receipt-inconclusive");
@@ -30984,7 +31125,7 @@ class Workbench {
30984
31125
  }
30985
31126
  const opened = await openProjectDirectory(path, this.o.coordination.stateHome, this.o.agentDir, this.o.hostUrl);
30986
31127
  for (const root of [this.o.cwd, opened.path]) {
30987
- const entry = join37(this.projectRoot, `${hash(root)}.json`);
31128
+ const entry = join38(this.projectRoot, `${hash(root)}.json`);
30988
31129
  const saved = files.read(entry);
30989
31130
  if (!saved)
30990
31131
  files.create(entry, canonicalJson({ path: root }));
@@ -31014,7 +31155,7 @@ async function predecessorExited() {
31014
31155
  } catch {
31015
31156
  return;
31016
31157
  }
31017
- await new Promise((resolve14) => setTimeout(resolve14, 100));
31158
+ await new Promise((resolve15) => setTimeout(resolve15, 100));
31018
31159
  }
31019
31160
  }
31020
31161
  async function healBeforeStart(c) {
@@ -31052,8 +31193,8 @@ function legacy(store, budget, reader) {
31052
31193
  decodeId(entry.name);
31053
31194
  if (created.has(entry.name))
31054
31195
  continue;
31055
- const path = join38(store.tasks, entry.name, "task.json");
31056
- const size2 = lstatSync22(path).size;
31196
+ const path = join39(store.tasks, entry.name, "task.json");
31197
+ const size2 = lstatSync23(path).size;
31057
31198
  if (size2 > 128 * 1024)
31058
31199
  throw new ContractError("corrupt-selected");
31059
31200
  budget.reserve(size2);
@@ -31085,7 +31226,7 @@ var processLifetime = {
31085
31226
  const restarts = process.uptime() > 600 ? 0 : previous;
31086
31227
  if (!Number.isSafeInteger(restarts) || restarts >= SELF_RESTARTS)
31087
31228
  return;
31088
- const child = spawn5(process.execPath, [
31229
+ const child = spawn6(process.execPath, [
31089
31230
  ...process.execArgv,
31090
31231
  fileURLToPath7(new URL("./service-host.mjs", import.meta.url))
31091
31232
  ], {
@@ -31106,7 +31247,7 @@ var processLifetime = {
31106
31247
  }
31107
31248
  };
31108
31249
  async function createServiceHost(value, sourceBuild, lifetime) {
31109
- const embedded = "2d78a97c9d5db70709e390e26fa315b5fdd3539f5a36e040593943f06ee5469a";
31250
+ const embedded = "5d0366db40ab791c6a27b4b1cb323b88b14bf6c6cbd0fef76fd9433853d4f051";
31110
31251
  if (embedded && sourceBuild)
31111
31252
  throw new ContractError("unsupported-context");
31112
31253
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
@@ -31190,8 +31331,8 @@ async function createServiceHost(value, sourceBuild, lifetime) {
31190
31331
  let timer;
31191
31332
  await Promise.race([
31192
31333
  owner?.idle(),
31193
- new Promise((resolve14) => {
31194
- timer = setTimeout(resolve14, FAULT_SETTLE_MS);
31334
+ new Promise((resolve15) => {
31335
+ timer = setTimeout(resolve15, FAULT_SETTLE_MS);
31195
31336
  })
31196
31337
  ]);
31197
31338
  clearTimeout(timer);