@abelxiaoxing/cadence 2.0.36 → 2.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.de.md +4 -4
  2. package/README.es.md +4 -4
  3. package/README.fr.md +4 -4
  4. package/README.ja.md +4 -4
  5. package/README.ko.md +4 -4
  6. package/README.md +11 -9
  7. package/README.pt-BR.md +4 -4
  8. package/README.ru.md +4 -4
  9. package/README.zh-CN.md +12 -10
  10. package/THIRD_PARTY_NOTICES.md +9 -1
  11. package/agents/design-explorer.md +4 -2
  12. package/agents/diagnosis-worker.md +5 -2
  13. package/agents/implementation-worker.md +19 -12
  14. package/docs/conversation-mode.md +46 -18
  15. package/docs/reuse-and-distribution.md +1 -1
  16. package/docs/service-management.md +35 -9
  17. package/package.json +16 -8
  18. package/src/agent-browser/labeled-rule.ts +74 -0
  19. package/src/agent-browser/session-navigator.ts +214 -0
  20. package/src/agent-browser/source.ts +174 -0
  21. package/src/agent-browser/transcript-content.ts +442 -0
  22. package/src/agent-browser/transcript-pane.ts +324 -0
  23. package/src/agent-panel-cadence.ts +147 -628
  24. package/src/agent-panel-model.ts +34 -267
  25. package/src/agent-panel.ts +139 -437
  26. package/src/cadence-instructions.ts +8 -7
  27. package/src/cadence-mode.ts +30 -9
  28. package/src/change-tools.mjs +268 -0
  29. package/src/coordinator-tools.mjs +44 -16
  30. package/src/git-environment.d.mts +2 -0
  31. package/src/git-environment.mjs +24 -0
  32. package/src/image-content.mjs +7 -28
  33. package/src/index.ts +1 -1
  34. package/src/native-build.ts +1 -1
  35. package/src/native-workflow-history.ts +20 -3
  36. package/src/operator-cli.mjs +18 -11
  37. package/src/research-scan.mjs +393 -0
  38. package/src/research-tools.mjs +406 -342
  39. package/src/sdk-worker.mjs +42 -55
  40. package/src/service/contracts/core.ts +0 -1
  41. package/src/service/contracts/workbench.ts +21 -19
  42. package/src/service/contracts/workflow.ts +283 -16
  43. package/src/service/coordination.ts +7 -0
  44. package/src/service-cli.mjs +652 -149
  45. package/src/service-host.mjs +2745 -1137
  46. package/src/worker-capture.mjs +24 -1
  47. package/src/worker-public.mjs +19 -2
  48. package/src/worker-redaction.mjs +11 -0
  49. package/src/worker-toolkit.mjs +157 -0
  50. package/src/worker-workspace.d.mts +13 -0
  51. package/src/worker-workspace.mjs +48 -0
  52. package/src/workspace.ts +4 -24
  53. package/web/dist/assets/cadence.css +1 -1
  54. package/web/dist/assets/cadence.js +18 -17
  55. package/web/dist/manifest.json +7 -7
@@ -2,11 +2,11 @@
2
2
  // Generated by scripts/build-service.mjs; edit the entry and source modules.
3
3
 
4
4
  // src/service/cli.ts
5
- import { spawn as spawn2 } from "node:child_process";
5
+ import { spawn as spawn3 } from "node:child_process";
6
6
  import { mkdirSync as mkdirSync6 } from "node:fs";
7
7
  import { request } from "node:http";
8
8
  import { homedir as homedir7 } from "node:os";
9
- import { dirname as dirname13, join as join18, resolve as resolve7 } from "node:path";
9
+ import { dirname as dirname13, join as join20, resolve as resolve7 } from "node:path";
10
10
  import { fileURLToPath as fileURLToPath2 } from "node:url";
11
11
 
12
12
  // src/install-config.mjs
@@ -1770,6 +1770,24 @@ class CaptureBudgetLease {
1770
1770
  this.forget();
1771
1771
  }
1772
1772
  }
1773
+ // src/git-environment.mjs
1774
+ function gitEnvironment() {
1775
+ const root = process.getuid?.() === 0;
1776
+ return {
1777
+ ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_") && !(root && name === "SUDO_UID"))),
1778
+ GIT_OPTIONAL_LOCKS: "0",
1779
+ GIT_NO_LAZY_FETCH: "1",
1780
+ LC_ALL: "C"
1781
+ };
1782
+ }
1783
+ function gitArguments(args) {
1784
+ return [
1785
+ "--no-replace-objects",
1786
+ ...process.platform !== "win32" && process.getuid?.() === 0 ? ["-c", "safe.directory=", "-c", "core.fsmonitor=false"] : [],
1787
+ ...args
1788
+ ];
1789
+ }
1790
+
1773
1791
  // src/workspace.ts
1774
1792
  import { spawnSync } from "node:child_process";
1775
1793
  import { createHash } from "node:crypto";
@@ -1890,17 +1908,6 @@ function readBounded(path2, max, packaged = false) {
1890
1908
  closeSync2(fd);
1891
1909
  }
1892
1910
  }
1893
- function gitEnvironment() {
1894
- const root = process.getuid?.() === 0;
1895
- return {
1896
- ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_") && !(root && name === "SUDO_UID"))),
1897
- GIT_OPTIONAL_LOCKS: "0",
1898
- LC_ALL: "C"
1899
- };
1900
- }
1901
- function gitArguments(args) {
1902
- return process.platform !== "win32" && process.getuid?.() === 0 ? ["-c", "safe.directory=", "-c", "core.fsmonitor=false", ...args] : args;
1903
- }
1904
1911
  function resolveWorkspace(cwd) {
1905
1912
  const actual = realpathSync(cwd);
1906
1913
  const result = spawnSync("git", gitArguments(["rev-parse", "--show-toplevel"]), {
@@ -2668,6 +2675,20 @@ function serviceEnvironment(s) {
2668
2675
  out.push(["XDG_STATE_HOME", state]);
2669
2676
  if (s.env.PI_CODING_AGENT_DIR)
2670
2677
  out.push(["PI_CODING_AGENT_DIR", agentDirectory(s)]);
2678
+ for (const key of [
2679
+ "XDG_CONFIG_HOME",
2680
+ "BUN_INSTALL",
2681
+ "BUN_INSTALL_GLOBAL_DIR",
2682
+ "BUN_INSTALL_BIN",
2683
+ "npm_config_prefix",
2684
+ "NPM_CONFIG_PREFIX",
2685
+ "npm_config_userconfig",
2686
+ "NPM_CONFIG_USERCONFIG"
2687
+ ]) {
2688
+ const value = s.env[key];
2689
+ if (value && isAbsolute3(value))
2690
+ out.push([key, value]);
2691
+ }
2671
2692
  return out;
2672
2693
  }
2673
2694
  function checked(value) {
@@ -3624,6 +3645,8 @@ class ServiceCoordination {
3624
3645
  }
3625
3646
  acquire(input, resolvedEndpoint = input.endpoint, initializeNew, reselectExisting) {
3626
3647
  this.store;
3648
+ if (rootsOverlap(this.store.root, join6(this.stateHome, "cadence-worktrees-v1")))
3649
+ throw new ContractError("forbidden");
3627
3650
  const config = decodeOwnerConfig(input);
3628
3651
  const bound = endpoint(resolvedEndpoint);
3629
3652
  if (!endpointMatches(config.endpoint, bound))
@@ -4659,10 +4682,10 @@ function strayTemporaries(directory2) {
4659
4682
  }
4660
4683
 
4661
4684
  // src/service/self-heal.ts
4662
- import { createHash as createHash4, randomUUID as randomUUID7 } from "node:crypto";
4663
- import { lstatSync as lstatSync7, opendirSync as opendirSync4 } from "node:fs";
4685
+ import { createHash as createHash4, randomUUID as randomUUID8 } from "node:crypto";
4686
+ import { lstatSync as lstatSync8, opendirSync as opendirSync5 } from "node:fs";
4664
4687
  import { hostname as hostname5 } from "node:os";
4665
- import { join as join11 } from "node:path";
4688
+ import { join as join12 } from "node:path";
4666
4689
 
4667
4690
  // src/service/process-ledger.ts
4668
4691
  import { rmSync as rmSync3 } from "node:fs";
@@ -4782,6 +4805,250 @@ class LiveLedger {
4782
4805
  }
4783
4806
  }
4784
4807
 
4808
+ // src/service/repository-coordination.ts
4809
+ import { randomUUID as randomUUID7 } from "node:crypto";
4810
+ import { lstatSync as lstatSync7, opendirSync as opendirSync4 } from "node:fs";
4811
+ import { isAbsolute as isAbsolute6, join as join11 } from "node:path";
4812
+ import { setTimeout as delay } from "node:timers/promises";
4813
+ var WAIT_MS = 30000;
4814
+ var POLL_MS = 50;
4815
+ var ACTIVE_RESOURCES = 256;
4816
+ function decode3(value) {
4817
+ const o = closed(value, [
4818
+ "schema",
4819
+ "kind",
4820
+ "resource",
4821
+ "root",
4822
+ "epoch",
4823
+ "run",
4824
+ "token",
4825
+ "identity",
4826
+ "holder"
4827
+ ]);
4828
+ if (o.schema !== "cadence-delivery-resource/1" || !["mutation", "workspace"].includes(String(o.kind)))
4829
+ throw new ContractError("corrupt-selected");
4830
+ for (const path2 of [o.resource, o.root])
4831
+ if (typeof path2 !== "string" || !isAbsolute6(path2) || path2.includes("\x00"))
4832
+ throw new ContractError("corrupt-selected");
4833
+ const h = closed(o.holder, ["pid", "host", "boot", "started"]);
4834
+ if (!Number.isSafeInteger(h.pid) || Number(h.pid) < 1 || typeof h.host !== "string" || ![h.boot, h.started].every((x) => x === null || typeof x === "string"))
4835
+ throw new ContractError("corrupt-selected");
4836
+ return {
4837
+ schema: "cadence-delivery-resource/1",
4838
+ kind: o.kind,
4839
+ resource: text(o.resource, 4096, true),
4840
+ root: text(o.root, 4096, true),
4841
+ epoch: decodeId(o.epoch),
4842
+ run: decodeId(o.run),
4843
+ token: decodeId(o.token),
4844
+ identity: o.identity === null ? null : decodeHash(o.identity),
4845
+ holder: h
4846
+ };
4847
+ }
4848
+ var directory2 = (files) => join11(files.namespace, "delivery-resources-v1");
4849
+ var resourcePath = (files, row) => join11(directory2(files), row.kind, `${hash(row.resource)}.json`);
4850
+ var ownerDirectory = (files, root, epoch) => join11(directory2(files), "owners", hash(root), decodeId(epoch));
4851
+ var indexPath = (files, row) => join11(ownerDirectory(files, row.root, row.epoch), `${row.kind}-${hash(row.resource)}.json`);
4852
+ function worktreeIdentity(path2) {
4853
+ const root = lstatSync7(path2), marker = lstatSync7(join11(path2, ".git"));
4854
+ if (!root.isDirectory() || root.isSymbolicLink() || !marker.isFile() || marker.nlink !== 1 || marker.size > 8192)
4855
+ throw new ContractError("stale");
4856
+ const body = readBounded(join11(path2, ".git"), 8192);
4857
+ const after = lstatSync7(join11(path2, ".git")), afterRoot = lstatSync7(path2);
4858
+ if (!body || after.dev !== marker.dev || after.ino !== marker.ino || after.ctimeMs !== marker.ctimeMs || after.size !== marker.size || afterRoot.dev !== root.dev || afterRoot.ino !== root.ino)
4859
+ throw new ContractError("stale");
4860
+ return hash(encoded([
4861
+ root.dev,
4862
+ root.ino,
4863
+ marker.dev,
4864
+ marker.ino,
4865
+ body.toString("utf8")
4866
+ ]));
4867
+ }
4868
+
4869
+ class RepositoryCoordination {
4870
+ c;
4871
+ root;
4872
+ epoch;
4873
+ run;
4874
+ assertOwner;
4875
+ fault;
4876
+ owned = new Map;
4877
+ constructor(c, root, epoch, run, assertOwner, fault) {
4878
+ this.c = c;
4879
+ this.root = root;
4880
+ this.epoch = epoch;
4881
+ this.run = run;
4882
+ this.assertOwner = assertOwner;
4883
+ this.fault = fault;
4884
+ }
4885
+ write(operation) {
4886
+ try {
4887
+ return operation();
4888
+ } catch (error) {
4889
+ this.fault();
4890
+ throw error;
4891
+ }
4892
+ }
4893
+ reserve(kind, resource) {
4894
+ this.assertOwner();
4895
+ const row = {
4896
+ schema: "cadence-delivery-resource/1",
4897
+ kind,
4898
+ resource,
4899
+ root: this.root,
4900
+ epoch: this.epoch,
4901
+ run: this.run,
4902
+ token: randomUUID7(),
4903
+ identity: null,
4904
+ holder: selfMark()
4905
+ };
4906
+ const target = resourcePath(this.c.files, row);
4907
+ if (this.c.files.read(target))
4908
+ return null;
4909
+ const index = this.write(() => this.c.files.create(indexPath(this.c.files, row), encoded(row)));
4910
+ let file;
4911
+ try {
4912
+ file = this.c.files.create(target, encoded(row));
4913
+ } catch (error) {
4914
+ if (error instanceof Error && "code" in error && error.code === "EEXIST") {
4915
+ this.write(() => this.c.files.remove(indexPath(this.c.files, row), index));
4916
+ return null;
4917
+ }
4918
+ this.fault();
4919
+ throw error;
4920
+ }
4921
+ const held = { row, file, index };
4922
+ this.owned.set(row.token, held);
4923
+ return held;
4924
+ }
4925
+ async mutate(repository, signal, operation, settled) {
4926
+ const deadline = performance.now() + WAIT_MS;
4927
+ let held;
4928
+ for (;; ) {
4929
+ this.assertOwner();
4930
+ if (signal.aborted)
4931
+ throw new ContractError("stale");
4932
+ held = this.reserve("mutation", repository);
4933
+ if (held)
4934
+ break;
4935
+ if (performance.now() >= deadline)
4936
+ throw new ContractError("conflict");
4937
+ await delay(POLL_MS, undefined, { signal });
4938
+ }
4939
+ try {
4940
+ return await operation();
4941
+ } finally {
4942
+ if (settled())
4943
+ this.release(held.row.token);
4944
+ }
4945
+ }
4946
+ reserveWorkspace(path2) {
4947
+ const held = this.reserve("workspace", path2);
4948
+ if (!held)
4949
+ throw new ContractError("conflict");
4950
+ return held.row.token;
4951
+ }
4952
+ confirmWorkspace(token) {
4953
+ const held = this.require(token);
4954
+ held.row = { ...held.row, identity: worktreeIdentity(held.row.resource) };
4955
+ this.write(() => this.c.files.create(join11(this.c.directory, "workflows-v1", "runs", this.run, "ownership", `${token}.json`), encoded({ ...held.row, schema: "cadence-workspace-observation/1" })));
4956
+ }
4957
+ assertWorkspace(token) {
4958
+ this.assertOwner();
4959
+ const held = this.require(token);
4960
+ this.c.files.assert(resourcePath(this.c.files, held.row), held.file);
4961
+ if (!held.row.identity || worktreeIdentity(held.row.resource) !== held.row.identity)
4962
+ throw new ContractError("stale");
4963
+ }
4964
+ require(token) {
4965
+ const held = this.owned.get(token);
4966
+ if (!held)
4967
+ throw new ContractError("stale");
4968
+ return held;
4969
+ }
4970
+ release(token) {
4971
+ this.assertOwner();
4972
+ const held = this.require(token);
4973
+ this.write(() => {
4974
+ this.c.files.remove(resourcePath(this.c.files, held.row), held.file);
4975
+ this.c.files.remove(indexPath(this.c.files, held.row), held.index);
4976
+ });
4977
+ this.owned.delete(token);
4978
+ }
4979
+ finish() {
4980
+ for (const held of [...this.owned.values()])
4981
+ if (held.row.kind === "workspace")
4982
+ this.release(held.row.token);
4983
+ }
4984
+ }
4985
+ function recoverDeliveryResources(files, root, epoch, options = {}) {
4986
+ const home = ownerDirectory(files, root, epoch);
4987
+ if (!files.directory(home))
4988
+ return 0;
4989
+ const dir = opendirSync4(home);
4990
+ const actions = [];
4991
+ let count = 0;
4992
+ const read = (path2) => {
4993
+ try {
4994
+ const snapshot = files.read(path2);
4995
+ if (!snapshot)
4996
+ return { snapshot, row: undefined, broken: false };
4997
+ try {
4998
+ return { snapshot, row: decode3(json(snapshot)), broken: false };
4999
+ } catch {
5000
+ return { snapshot, row: undefined, broken: true };
5001
+ }
5002
+ } catch {
5003
+ return { snapshot: undefined, row: undefined, broken: true };
5004
+ }
5005
+ };
5006
+ const archive = (path2) => {
5007
+ if (!options.archive)
5008
+ throw new ContractError("corrupt-selected");
5009
+ options.archive(path2);
5010
+ };
5011
+ try {
5012
+ for (let entry = dir.readSync();entry; entry = dir.readSync()) {
5013
+ if (++count > ACTIVE_RESOURCES)
5014
+ throw new ContractError("capacity");
5015
+ const match = /^(mutation|workspace)-([a-f0-9]{64})\.json$/u.exec(entry.name);
5016
+ const path2 = join11(home, entry.name);
5017
+ if (!match) {
5018
+ if (!options.takeOver)
5019
+ throw new ContractError("corrupt-selected");
5020
+ actions.push(() => archive(path2));
5021
+ continue;
5022
+ }
5023
+ const [, kind, key] = match;
5024
+ const index = read(path2), target = join11(directory2(files), kind, `${key}.json`), shared = read(target);
5025
+ const matches = (row) => row.kind === kind && hash(row.resource) === key && row.root === root && row.epoch === epoch;
5026
+ const ownerMatches = (row) => !options.expectedOwner || Object.entries(options.expectedOwner).every(([key2, value]) => value == null || row.holder[key2] === value);
5027
+ const badIndex = index.broken || !index.row || !matches(index.row) || !ownerMatches(index.row);
5028
+ const badShared = shared.broken || shared.row && (shared.row.kind !== kind || hash(shared.row.resource) !== key || matches(shared.row) && (!ownerMatches(shared.row) || index.row && !badIndex && index.row.token === shared.row.token && encoded(index.row.holder) !== encoded(shared.row.holder)));
5029
+ if (badShared && !options.takeOver)
5030
+ throw new ContractError("corrupt-selected");
5031
+ actions.push(() => {
5032
+ if (badShared)
5033
+ archive(target);
5034
+ else if (shared.row && shared.snapshot && matches(shared.row) && (!index.row || badIndex || index.row.token === shared.row.token)) {
5035
+ files.remove(target, shared.snapshot);
5036
+ }
5037
+ if (badIndex)
5038
+ archive(path2);
5039
+ else if (index.snapshot)
5040
+ files.remove(path2, index.snapshot);
5041
+ });
5042
+ }
5043
+ } finally {
5044
+ dir.closeSync();
5045
+ }
5046
+ if (!options.inspect)
5047
+ for (const action of actions)
5048
+ action();
5049
+ return count;
5050
+ }
5051
+
4785
5052
  // src/service/self-heal.ts
4786
5053
  function attempt(read) {
4787
5054
  try {
@@ -4790,7 +5057,7 @@ function attempt(read) {
4790
5057
  return null;
4791
5058
  }
4792
5059
  }
4793
- function readFile(files, path2, decode3, maximum) {
5060
+ function readFile(files, path2, decode4, maximum) {
4794
5061
  let snapshot;
4795
5062
  try {
4796
5063
  snapshot = files.read(path2, maximum);
@@ -4803,7 +5070,7 @@ function readFile(files, path2, decode3, maximum) {
4803
5070
  return {
4804
5071
  path: path2,
4805
5072
  snapshot: bytes,
4806
- value: attempt(() => decode3(json(bytes, maximum)))
5073
+ value: attempt(() => decode4(json(bytes, maximum)))
4807
5074
  };
4808
5075
  }
4809
5076
  function decodeOwnerLock(value) {
@@ -4913,7 +5180,7 @@ class RegistryHealer {
4913
5180
  this.ledger = new ProcessLedger(c.files);
4914
5181
  }
4915
5182
  path(name) {
4916
- return join11(this.c.registryDirectory, name);
5183
+ return join12(this.c.registryDirectory, name);
4917
5184
  }
4918
5185
  async heal(options = {}) {
4919
5186
  const lockPath = this.path("registry.lock");
@@ -4924,7 +5191,7 @@ class RegistryHealer {
4924
5191
  lock = undefined;
4925
5192
  const age = (() => {
4926
5193
  try {
4927
- return Date.now() - lstatSync7(lockPath).mtimeMs;
5194
+ return Date.now() - lstatSync8(lockPath).mtimeMs;
4928
5195
  } catch {
4929
5196
  return 0;
4930
5197
  }
@@ -5030,7 +5297,7 @@ class RegistryHealer {
5030
5297
  const lockPath = this.path("registry.lock");
5031
5298
  const lock = this.c.files.create(lockPath, encoded({
5032
5299
  schema: "cadence-service-registry-lock/1",
5033
- token: randomUUID7(),
5300
+ token: randomUUID8(),
5034
5301
  pid: process.pid,
5035
5302
  host: hostname5()
5036
5303
  }));
@@ -5073,19 +5340,19 @@ class RegistryHealer {
5073
5340
  }
5074
5341
  function liveReservations(c) {
5075
5342
  const out = [];
5076
- const dir = opendirSync4(c.files.namespace);
5343
+ const dir = opendirSync5(c.files.namespace);
5077
5344
  try {
5078
5345
  for (let e = dir.readSync();e; e = dir.readSync()) {
5079
5346
  if (!/^[a-f0-9]{64}$/.test(e.name))
5080
5347
  continue;
5081
- const service = join11(c.files.namespace, e.name, "service-v1");
5082
- const registration2 = readFile(c.files, join11(service, "registration.json"), decodeRegistrationLenient);
5348
+ const service = join12(c.files.namespace, e.name, "service-v1");
5349
+ const registration2 = readFile(c.files, join12(service, "registration.json"), decodeRegistrationLenient);
5083
5350
  if (!registration2 || registration2 === "unreadable")
5084
5351
  continue;
5085
5352
  const r = registration2.value;
5086
5353
  if (!r || r.phase === "stopped")
5087
5354
  continue;
5088
- const owner = readFile(c.files, join11(service, "owner.lock"), decodeOwnerLock);
5355
+ const owner = readFile(c.files, join12(service, "owner.lock"), decodeOwnerLock);
5089
5356
  const mark = owner && owner !== "unreadable" && owner.value ? owner.value : r;
5090
5357
  if (holderState(mark, stampTime(registration2.snapshot.stamp)).state !== "live")
5091
5358
  continue;
@@ -5106,20 +5373,20 @@ function liveReservations(c) {
5106
5373
  return out;
5107
5374
  }
5108
5375
  function projectFiles(c, root) {
5109
- const privateRoot = join11(c.files.namespace, createHash4("sha256").update(root).digest("hex"));
5376
+ const privateRoot = join12(c.files.namespace, createHash4("sha256").update(root).digest("hex"));
5110
5377
  return {
5111
5378
  root,
5112
5379
  privateRoot,
5113
- service: join11(privateRoot, "service-v1"),
5114
- checkoutPath: join11(privateRoot, "checkout.lock")
5380
+ service: join12(privateRoot, "service-v1"),
5381
+ checkoutPath: join12(privateRoot, "checkout.lock")
5115
5382
  };
5116
5383
  }
5117
5384
  function snapshotProject(c, p) {
5118
5385
  const s = { temporaries: [] };
5119
- s.registration = readFile(c.files, join11(p.service, "registration.json"), decodeRegistrationLenient);
5120
- s.owner = readFile(c.files, join11(p.service, "owner.lock"), decodeOwnerLock);
5386
+ s.registration = readFile(c.files, join12(p.service, "registration.json"), decodeRegistrationLenient);
5387
+ s.owner = readFile(c.files, join12(p.service, "owner.lock"), decodeOwnerLock);
5121
5388
  try {
5122
- s.capability = c.files.read(join11(p.service, "local-capability.json"));
5389
+ s.capability = c.files.read(join12(p.service, "local-capability.json"));
5123
5390
  } catch {
5124
5391
  s.capability = "unreadable";
5125
5392
  }
@@ -5134,7 +5401,7 @@ function snapshotProject(c, p) {
5134
5401
  } catch {}
5135
5402
  s.temporaries = [
5136
5403
  ...strayTemporaries(p.service),
5137
- ...strayTemporaries(join11(p.service, "history-v2"))
5404
+ ...strayTemporaries(join12(p.service, "history-v2"))
5138
5405
  ];
5139
5406
  return s;
5140
5407
  }
@@ -5203,6 +5470,28 @@ async function healProjectAt(c, root, options = {}) {
5203
5470
  const workers = takenOver ? { stopped: 0, running: 0 } : await stopWorkers(ledger, epoch, holder.reboot, !!options.inspect);
5204
5471
  if (workers.running)
5205
5472
  return { status: "blocked", reason: "workers-running", pid };
5473
+ const selectedOwner = [
5474
+ s.owner && s.owner !== "unreadable" ? s.owner.value : null,
5475
+ s.registration && s.registration !== "unreadable" ? s.registration.value : null,
5476
+ s.row
5477
+ ].find((value) => value?.epoch === epoch);
5478
+ const expectedOwner = selectedOwner ? {
5479
+ pid: selectedOwner.pid,
5480
+ host: selectedOwner.host,
5481
+ ..."boot" in selectedOwner ? { boot: selectedOwner.boot ?? null } : {},
5482
+ ..."started" in selectedOwner ? { started: selectedOwner.started ?? null } : {}
5483
+ } : undefined;
5484
+ if (epoch) {
5485
+ try {
5486
+ recoverDeliveryResources(c.files, root, epoch, {
5487
+ inspect: true,
5488
+ takeOver: options.takeOver,
5489
+ expectedOwner
5490
+ });
5491
+ } catch {
5492
+ return { status: "blocked", reason: "holder-unknown", pid };
5493
+ }
5494
+ }
5206
5495
  const restarted = epoch ? ledger.restartRequested(epoch) : false;
5207
5496
  const cause = !active(s) ? "storage" : holder.reboot ? "reboot" : restarted ? "restart" : "crash";
5208
5497
  if (options.inspect)
@@ -5213,6 +5502,12 @@ async function healProjectAt(c, root, options = {}) {
5213
5502
  if (workers.stopped)
5214
5503
  actions.add("stopped-workers");
5215
5504
  const archive = log.archive();
5505
+ if (epoch && recoverDeliveryResources(c.files, root, epoch, {
5506
+ takeOver: options.takeOver,
5507
+ expectedOwner,
5508
+ archive: (path2) => archive.keep(path2)
5509
+ }))
5510
+ actions.add("released-locks");
5216
5511
  if (active(s)) {
5217
5512
  reclaim(c, p, s, archive);
5218
5513
  actions.add("released-locks");
@@ -5247,8 +5542,8 @@ function metadataDamaged(c, p) {
5247
5542
  return false;
5248
5543
  }
5249
5544
  try {
5250
- const format = c.files.read(join11(p.service, "format.json"));
5251
- const config = c.files.read(join11(p.service, "config.json"));
5545
+ const format = c.files.read(join12(p.service, "format.json"));
5546
+ const config = c.files.read(join12(p.service, "config.json"));
5252
5547
  if (!format || !config)
5253
5548
  return true;
5254
5549
  const f = closed(json(format), [
@@ -5260,10 +5555,10 @@ function metadataDamaged(c, p) {
5260
5555
  if (f.schema !== "cadence-service-format/1" || f.root !== p.root || f.stateHome !== c.stateHome || f.configIdentity !== config.identity)
5261
5556
  return true;
5262
5557
  const selected = decodeOwnerConfig(json(config));
5263
- const host = c.files.read(join11(p.service, "host-config.json"));
5558
+ const host = c.files.read(join12(p.service, "host-config.json"));
5264
5559
  if (host && host.identity !== selected.policyIdentity)
5265
5560
  return true;
5266
- const registration2 = c.files.read(join11(p.service, "registration.json"));
5561
+ const registration2 = c.files.read(join12(p.service, "registration.json"));
5267
5562
  if (registration2) {
5268
5563
  const r = decodeRegistration(json(registration2));
5269
5564
  if (r.root !== p.root || r.stateHome !== c.stateHome || r.configIdentity !== config.identity)
@@ -5286,7 +5581,7 @@ function reclaim(c, p, expected, archive) {
5286
5581
  mutate();
5287
5582
  const registration2 = s.registration;
5288
5583
  if (registration2 === "unreadable")
5289
- archive.keep(join11(p.service, "registration.json"));
5584
+ archive.keep(join12(p.service, "registration.json"));
5290
5585
  else if (registration2) {
5291
5586
  if (!registration2.value)
5292
5587
  archive.keep(registration2.path);
@@ -5294,7 +5589,7 @@ function reclaim(c, p, expected, archive) {
5294
5589
  c.files.replace(registration2.path, registration2.snapshot, encoded({ ...registration2.value, phase: "stopped" }));
5295
5590
  }
5296
5591
  if (s.row)
5297
- c.files.replace(join11(c.registryDirectory, "roots.json"), view.snapshot, encoded({
5592
+ c.files.replace(join12(c.registryDirectory, "roots.json"), view.snapshot, encoded({
5298
5593
  ...view.value,
5299
5594
  entries: view.value.entries.filter((row) => row.root !== p.root)
5300
5595
  }), 1024 * 1024);
@@ -5307,8 +5602,8 @@ function reclaim(c, p, expected, archive) {
5307
5602
  }
5308
5603
  c.files.remove(path2, "snapshot" in value ? value.snapshot : value, maximum);
5309
5604
  };
5310
- drop(join11(p.service, "local-capability.json"), s.capability);
5311
- drop(join11(p.service, "owner.lock"), s.owner);
5605
+ drop(join12(p.service, "local-capability.json"), s.capability);
5606
+ drop(join12(p.service, "owner.lock"), s.owner);
5312
5607
  drop(p.checkoutPath, s.checkout, 8192);
5313
5608
  });
5314
5609
  }
@@ -5646,16 +5941,16 @@ Cadence releases whatever the old project owner left behind automatically.
5646
5941
 
5647
5942
  // src/service/gateway-cli.ts
5648
5943
  import { homedir as homedir6 } from "node:os";
5649
- import { dirname as dirname9, join as join13, resolve as resolve6 } from "node:path";
5944
+ import { dirname as dirname9, join as join14, resolve as resolve6 } from "node:path";
5650
5945
  import { fileURLToPath } from "node:url";
5651
5946
 
5652
5947
  // src/service/runtime.ts
5653
5948
  import { homedir as homedir5 } from "node:os";
5654
- import { dirname as dirname8, isAbsolute as isAbsolute6, join as join12, resolve as resolve5 } from "node:path";
5949
+ import { dirname as dirname8, isAbsolute as isAbsolute7, join as join13, resolve as resolve5 } from "node:path";
5655
5950
  var STARTUP_INPUT_BYTES = 16 * 1024;
5656
5951
  function absolute(value) {
5657
5952
  const result = text(value, 4096, true);
5658
- if (!isAbsolute6(result))
5953
+ if (!isAbsolute7(result))
5659
5954
  throw new ContractError("invalid");
5660
5955
  return result;
5661
5956
  }
@@ -5751,7 +6046,7 @@ function selectStart(options, ambient) {
5751
6046
  port: options.port ?? 17423,
5752
6047
  proxy: null
5753
6048
  },
5754
- agentDir: resolve5(options.agentDir ?? ambient.PI_CODING_AGENT_DIR ?? join12(ambient.HOME ?? ambient.USERPROFILE ?? homedir5(), ".pi", "agent")),
6049
+ agentDir: resolve5(options.agentDir ?? ambient.PI_CODING_AGENT_DIR ?? join13(ambient.HOME ?? ambient.USERPROFILE ?? homedir5(), ".pi", "agent")),
5755
6050
  tokenSource: options.tokenFile ? "file" : env ? "environment" : "generated",
5756
6051
  tokenFile: options.tokenFile ? resolve5(options.tokenFile) : null
5757
6052
  });
@@ -5883,7 +6178,7 @@ async function gatewayMain(argv, hostUrl) {
5883
6178
  kind: "workbench",
5884
6179
  serverConfig: config,
5885
6180
  stateHome: store.stateHome,
5886
- agentDir: agentDir ?? selected?.agentDir ?? resolve6(process.env.PI_CODING_AGENT_DIR ?? join13(homedir6(), ".pi", "agent")),
6181
+ agentDir: agentDir ?? selected?.agentDir ?? resolve6(process.env.PI_CODING_AGENT_DIR ?? join14(homedir6(), ".pi", "agent")),
5887
6182
  policy: { ...policy, port: server.port }
5888
6183
  });
5889
6184
  const blocked = await healWorkbenchForStart(store, () => ownerResponsive(store));
@@ -5924,14 +6219,224 @@ No project or default workspace was created.
5924
6219
  `);
5925
6220
  }
5926
6221
 
6222
+ // src/service/installation.ts
6223
+ import { spawn } from "node:child_process";
6224
+ import {
6225
+ accessSync,
6226
+ constants as constants4,
6227
+ existsSync as existsSync3,
6228
+ lstatSync as lstatSync9,
6229
+ mkdtempSync,
6230
+ readFileSync as readFileSync3,
6231
+ realpathSync as realpathSync5,
6232
+ rmSync as rmSync4,
6233
+ writeFileSync as writeFileSync4
6234
+ } from "node:fs";
6235
+ import { tmpdir } from "node:os";
6236
+ import { basename as basename2, dirname as dirname10, isAbsolute as isAbsolute8, join as join15 } from "node:path";
6237
+ var PACKAGE = "@abelxiaoxing/cadence";
6238
+ var VIEW_MS = 30000;
6239
+ var INSTALL_MS = 15 * 60000;
6240
+ function packageCommands(s) {
6241
+ const command = (name) => (args, show = false, options) => new Promise((resolve7) => {
6242
+ const child = spawn(name, args, {
6243
+ cwd: options?.cwd ?? s.home,
6244
+ env: { ...s.env, HOME: s.home, ...options?.env },
6245
+ stdio: ["ignore", show ? 2 : "pipe", show ? 2 : "ignore"],
6246
+ timeout: show ? INSTALL_MS : VIEW_MS,
6247
+ windowsHide: true
6248
+ });
6249
+ let stdout = "";
6250
+ child.stdout?.setEncoding("utf8").on("data", (chunk) => {
6251
+ if (stdout.length < 1 << 20)
6252
+ stdout += chunk;
6253
+ });
6254
+ child.once("error", () => resolve7({ status: null, stdout: "" }));
6255
+ child.once("close", (status) => resolve7({ status, stdout }));
6256
+ });
6257
+ return { npm: command("npm"), bun: command("bun") };
6258
+ }
6259
+ var unsupported = () => ({
6260
+ route: "unsupported-install"
6261
+ });
6262
+ function sameCopy(modules, root) {
6263
+ try {
6264
+ const path2 = join15(modules, ...PACKAGE.split("/"));
6265
+ return !lstatSync9(path2).isSymbolicLink() && realpathSync5(path2) === realpathSync5(root) && realpathSync5(path2) === join15(realpathSync5(modules), ...PACKAGE.split("/"));
6266
+ } catch {
6267
+ return false;
6268
+ }
6269
+ }
6270
+ function prefixManager(prefix) {
6271
+ const npm = existsSync3(join15(prefix, "package-lock.json")) || existsSync3(join15(prefix, "npm-shrinkwrap.json"));
6272
+ const bun = existsSync3(join15(prefix, "bun.lock")) || existsSync3(join15(prefix, "bun.lockb"));
6273
+ return npm === bun ? undefined : bun ? "bun" : "npm";
6274
+ }
6275
+ function writable(installation, modules, root) {
6276
+ if (installation.manager === "bun" && [".npmrc", "bunfig.toml", ".bunfig.toml"].some((name) => existsSync3(join15(installation.prefix, name))))
6277
+ return unsupported();
6278
+ try {
6279
+ for (const path2 of [installation.prefix, modules, dirname10(root), root])
6280
+ accessSync(path2, constants4.W_OK);
6281
+ for (const name of [
6282
+ "package.json",
6283
+ "package-lock.json",
6284
+ "npm-shrinkwrap.json",
6285
+ "bun.lock",
6286
+ "bun.lockb"
6287
+ ])
6288
+ if (existsSync3(join15(installation.prefix, name)))
6289
+ accessSync(join15(installation.prefix, name), constants4.W_OK);
6290
+ return installation;
6291
+ } catch {
6292
+ return { route: "not-writable" };
6293
+ }
6294
+ }
6295
+ async function installation(s, commands) {
6296
+ const agent = agentDirectory(s), piPrefix = join15(agent, "npm");
6297
+ if (sameCopy(join15(piPrefix, "node_modules"), s.root)) {
6298
+ try {
6299
+ const settings2 = JSON.parse(readFileSync3(join15(agent, "settings.json"), "utf8"));
6300
+ if (!settings2 || !Array.isArray(settings2.packages))
6301
+ return unsupported();
6302
+ 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}@`)));
6303
+ if (sources.length !== 1)
6304
+ return unsupported();
6305
+ if (sources[0] !== `npm:${PACKAGE}`)
6306
+ return { route: "pinned" };
6307
+ const command = settings2.npmCommand ?? ["npm"];
6308
+ if (!Array.isArray(command) || command.length !== 1 || !["npm", "bun"].includes(command[0]))
6309
+ return unsupported();
6310
+ const manager = command[0];
6311
+ return writable({
6312
+ route: manager === "npm" ? "pi-npm" : "pi-bun",
6313
+ manager,
6314
+ prefix: piPrefix
6315
+ }, join15(piPrefix, "node_modules"), s.root);
6316
+ } catch {
6317
+ return unsupported();
6318
+ }
6319
+ }
6320
+ const localModules = dirname10(dirname10(s.root)), local = dirname10(localModules);
6321
+ const manifest = (() => {
6322
+ try {
6323
+ return JSON.parse(readFileSync3(join15(local, "package.json"), "utf8"));
6324
+ } catch {
6325
+ return;
6326
+ }
6327
+ })();
6328
+ if (manifest?.name === "pi-extensions" || basename2(dirname10(local)) === ".pi" || basename2(local) === "npm" && existsSync3(join15(dirname10(local), "settings.json")))
6329
+ return unsupported();
6330
+ const bun = await commands.bun(["pm", "ls", "--global"]);
6331
+ const bunPrefix = bun.status === 0 ? /^(\/[^\r\n]+) node_modules(?: \(\d+(?: installed)?\))?\r?$/.exec(bun.stdout.split(`
6332
+ `)[0])?.[1] : undefined;
6333
+ if (bunPrefix && sameCopy(join15(bunPrefix, "node_modules"), s.root)) {
6334
+ const manager = prefixManager(bunPrefix);
6335
+ if (manager === "bun")
6336
+ return writable({ route: "bun", manager: "bun", prefix: bunPrefix }, join15(bunPrefix, "node_modules"), s.root);
6337
+ if (!manager)
6338
+ return unsupported();
6339
+ }
6340
+ const npm = await commands.npm(["root", "--global"]);
6341
+ const modules = npm.status === 0 ? npm.stdout.trim() : "";
6342
+ const prefix = dirname10(dirname10(modules));
6343
+ if (isAbsolute8(modules) && modules === join15(prefix, "lib", "node_modules") && sameCopy(modules, s.root))
6344
+ return writable({ route: "npm", manager: "npm", prefix }, modules, s.root);
6345
+ if (basename2(localModules) !== "node_modules" || !sameCopy(localModules, s.root))
6346
+ return unsupported();
6347
+ try {
6348
+ if (![
6349
+ manifest.dependencies,
6350
+ manifest.devDependencies,
6351
+ manifest.optionalDependencies
6352
+ ].some((deps) => deps && typeof deps[PACKAGE] === "string" && /^(?:[~^]?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?|latest)$/.test(deps[PACKAGE])))
6353
+ return unsupported();
6354
+ const manager = prefixManager(local);
6355
+ if (!manager)
6356
+ return unsupported();
6357
+ if (manifest.packageManager !== undefined && (typeof manifest.packageManager !== "string" || !manifest.packageManager.startsWith(`${manager}@`)))
6358
+ return unsupported();
6359
+ return writable({
6360
+ route: manager === "bun" ? "bun-local" : "npm-local",
6361
+ manager,
6362
+ prefix: local
6363
+ }, localModules, s.root);
6364
+ } catch {
6365
+ return unsupported();
6366
+ }
6367
+ }
6368
+ function npmScope(i) {
6369
+ return [
6370
+ i.route === "npm" ? "--global" : "--global=false",
6371
+ "--prefix",
6372
+ i.prefix
6373
+ ];
6374
+ }
6375
+ function registryCommand(i, commands) {
6376
+ return (args, show) => commands[i.manager](i.manager === "npm" ? [args[0], ...npmScope(i), ...args.slice(1)] : args, show, { cwd: i.prefix });
6377
+ }
6378
+ function installVersion(i, version, commands) {
6379
+ const spec = `${PACKAGE}@${version}`;
6380
+ if (i.manager === "npm")
6381
+ return commands.npm([
6382
+ "install",
6383
+ ...npmScope(i),
6384
+ ...i.route === "pi-npm" ? ["--legacy-peer-deps"] : [],
6385
+ "--no-audit",
6386
+ "--no-fund",
6387
+ spec
6388
+ ], true, { cwd: i.prefix });
6389
+ return commands.bun([
6390
+ "add",
6391
+ ...i.route === "bun" ? ["--global"] : i.route === "pi-bun" ? ["--omit=peer"] : [],
6392
+ "--cwd",
6393
+ i.prefix,
6394
+ "--exact",
6395
+ spec
6396
+ ], true, { env: i.route === "bun" ? { BUN_INSTALL_GLOBAL_DIR: i.prefix } : {} });
6397
+ }
6398
+ async function fetchVersions(i, versions, commands) {
6399
+ try {
6400
+ for (const version of versions) {
6401
+ const spec = `${PACKAGE}@${version}`;
6402
+ if (i.manager === "npm") {
6403
+ if ((await commands.npm(["cache", "add", ...npmScope(i), spec], true, {
6404
+ cwd: i.prefix
6405
+ })).status !== 0)
6406
+ return false;
6407
+ } else {
6408
+ const stage = mkdtempSync(join15(tmpdir(), "cadence-upgrade-"));
6409
+ try {
6410
+ writeFileSync4(join15(stage, "package.json"), JSON.stringify({ private: true }));
6411
+ if ((await commands.bun([
6412
+ "add",
6413
+ "--cwd",
6414
+ stage,
6415
+ "--ignore-scripts",
6416
+ "--no-save",
6417
+ ...i.route === "pi-bun" ? ["--omit=peer"] : [],
6418
+ spec
6419
+ ], true)).status !== 0)
6420
+ return false;
6421
+ } finally {
6422
+ rmSync4(stage, { recursive: true, force: true });
6423
+ }
6424
+ }
6425
+ }
6426
+ return true;
6427
+ } catch {
6428
+ return false;
6429
+ }
6430
+ }
6431
+
5927
6432
  // src/service/launchd.ts
5928
- import { rmSync as rmSync4 } from "node:fs";
5929
- import { dirname as dirname10, join as join14 } from "node:path";
6433
+ import { rmSync as rmSync5 } from "node:fs";
6434
+ import { dirname as dirname11, join as join16 } from "node:path";
5930
6435
  var LABEL = "com.abelxiaoxing.cadence";
5931
6436
  var MARKER2 = `<?xml version="1.0" encoding="UTF-8"?>
5932
6437
  <!-- Generated by @abelxiaoxing/cadence`;
5933
6438
  function plistPath(s) {
5934
- return join14(s.home, "Library", "LaunchAgents", `${LABEL}.plist`);
6439
+ return join16(s.home, "Library", "LaunchAgents", `${LABEL}.plist`);
5935
6440
  }
5936
6441
  var xml = (value) => checked(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
5937
6442
  function buildPlist(u) {
@@ -5956,7 +6461,7 @@ function buildPlist(u) {
5956
6461
  "\t</array>",
5957
6462
  ...u.workspace === null ? ["<!-- Cadence workbench gateway; no project workspace -->"] : [],
5958
6463
  "\t<key>WorkingDirectory</key>",
5959
- ` <string>${xml(u.workspace ?? dirname10(dirname10(u.cli)))}</string>`,
6464
+ ` <string>${xml(u.workspace ?? dirname11(dirname11(u.cli)))}</string>`,
5960
6465
  "\t<key>EnvironmentVariables</key>",
5961
6466
  "\t<dict>",
5962
6467
  ...u.environment.flatMap(([k, v]) => [
@@ -6011,11 +6516,11 @@ async function configureLaunchAgent(s, mode, requested) {
6011
6516
  s.launchctl(["bootout", target(s)]);
6012
6517
  write(path2, buildPlist({
6013
6518
  node: s.node,
6014
- cli: join14(s.root, "src", "service-cli.mjs"),
6519
+ cli: join16(s.root, "src", "service-cli.mjs"),
6015
6520
  workspace,
6016
6521
  serverConfig: serverConfigPath(s.home),
6017
6522
  environment: serviceEnvironment(s),
6018
- log: join14(s.home, "Library", "Logs", "cadence.log")
6523
+ log: join16(s.home, "Library", "Logs", "cadence.log")
6019
6524
  }));
6020
6525
  const result = {
6021
6526
  unit: path2,
@@ -6026,7 +6531,7 @@ async function configureLaunchAgent(s, mode, requested) {
6026
6531
  s.launchctl(["enable", target(s)]);
6027
6532
  else if (disabled(s))
6028
6533
  return { status: "disabled", ...result };
6029
- if (workspace !== null && !regularFile(join14(agentDirectory(s), "auth.json")))
6534
+ if (workspace !== null && !regularFile(join16(agentDirectory(s), "auth.json")))
6030
6535
  return { status: "waiting-for-pi-login", ...result };
6031
6536
  const started = s.launchctl(["bootstrap", domain(s), path2]).status === 0;
6032
6537
  return { status: started ? "started" : "failed", ...result };
@@ -6054,7 +6559,7 @@ async function removeLaunchAgent(s) {
6054
6559
  return { ...refused2, unit: path2 };
6055
6560
  if (s.uid !== undefined && loaded(s))
6056
6561
  s.launchctl(["bootout", target(s)]);
6057
- rmSync4(path2);
6562
+ rmSync5(path2);
6058
6563
  return { status: "removed", unit: path2 };
6059
6564
  }
6060
6565
  function launchAgentStatus(s) {
@@ -6074,15 +6579,15 @@ function launchAgentStatus(s) {
6074
6579
  }
6075
6580
 
6076
6581
  // src/service/login-run.ts
6077
- import { rmSync as rmSync5 } from "node:fs";
6078
- import { dirname as dirname11, isAbsolute as isAbsolute7, join as join15 } from "node:path";
6582
+ import { rmSync as rmSync6 } from "node:fs";
6583
+ import { dirname as dirname12, isAbsolute as isAbsolute9, join as join17 } from "node:path";
6079
6584
  var RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
6080
6585
  var APPROVED_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run";
6081
6586
  var RUN_VALUE = "Cadence";
6082
6587
  var MARKER3 = "' Generated by @abelxiaoxing/cadence";
6083
6588
  function launcherPath(s) {
6084
6589
  const local = s.env.LOCALAPPDATA;
6085
- return join15(local && isAbsolute7(local) ? local : join15(s.home, "AppData", "Local"), "cadence-server", "cadence.vbs");
6590
+ return join17(local && isAbsolute9(local) ? local : join17(s.home, "AppData", "Local"), "cadence-server", "cadence.vbs");
6086
6591
  }
6087
6592
  var literal2 = (value) => `"${checked(value).replaceAll('"', '""')}"`;
6088
6593
  function argument2(value) {
@@ -6099,7 +6604,7 @@ function buildLauncher(u) {
6099
6604
  ...u.environment.length ? ['Set env = shell.Environment("Process")'] : [],
6100
6605
  ...u.environment.map(([k, v]) => `env(${literal2(k)}) = ${literal2(v)}`),
6101
6606
  ...u.workspace === null ? ["' Cadence workbench gateway; no project workspace"] : [],
6102
- `shell.CurrentDirectory = ${literal2(u.workspace ?? dirname11(dirname11(u.cli)))}`,
6607
+ `shell.CurrentDirectory = ${literal2(u.workspace ?? dirname12(dirname12(u.cli)))}`,
6103
6608
  `shell.Run ${literal2(command)}, 0, False`,
6104
6609
  ""
6105
6610
  ].join(`\r
@@ -6138,7 +6643,7 @@ async function configureLoginRun(s, mode, requested) {
6138
6643
  const environment = s.env.PI_CODING_AGENT_DIR ? [["PI_CODING_AGENT_DIR", agentDirectory(s)]] : [];
6139
6644
  write(path2, utf16(buildLauncher({
6140
6645
  node: s.node,
6141
- cli: join15(s.root, "src", "service-cli.mjs"),
6646
+ cli: join17(s.root, "src", "service-cli.mjs"),
6142
6647
  workspace,
6143
6648
  serverConfig: serverConfigPath(s.home),
6144
6649
  environment
@@ -6154,7 +6659,7 @@ async function configureLoginRun(s, mode, requested) {
6154
6659
  return { status: "failed", ...result };
6155
6660
  s.reg(["delete", APPROVED_KEY, "/v", RUN_VALUE, "/f"]);
6156
6661
  }
6157
- if (workspace !== null && !regularFile(join15(agentDirectory(s), "auth.json")))
6662
+ if (workspace !== null && !regularFile(join17(agentDirectory(s), "auth.json")))
6158
6663
  return { status: "waiting-for-pi-login", ...result };
6159
6664
  return { status: s.launch(path2) ? "started" : "failed", ...result };
6160
6665
  }
@@ -6182,7 +6687,7 @@ async function removeLoginRun(s) {
6182
6687
  for (const key of [RUN_KEY, APPROVED_KEY])
6183
6688
  if (present(s, key))
6184
6689
  s.reg(["delete", key, "/v", RUN_VALUE, "/f"]);
6185
- rmSync5(path2);
6690
+ rmSync6(path2);
6186
6691
  return { status: "removed", unit: path2 };
6187
6692
  }
6188
6693
  async function loginRunStatus(s) {
@@ -6203,12 +6708,9 @@ async function loginRunStatus(s) {
6203
6708
  }
6204
6709
 
6205
6710
  // src/service/maintenance.ts
6206
- import { spawn, spawnSync as spawnSync4 } from "node:child_process";
6207
- import { accessSync, constants as constants4, readFileSync as readFileSync3, realpathSync as realpathSync5 } from "node:fs";
6208
- import { dirname as dirname12, join as join16 } from "node:path";
6209
- var PACKAGE = "@abelxiaoxing/cadence";
6210
- var VIEW_MS = 30000;
6211
- var INSTALL_MS = 15 * 60000;
6711
+ import { spawn as spawn2, spawnSync as spawnSync4 } from "node:child_process";
6712
+ import { readFileSync as readFileSync4 } from "node:fs";
6713
+ import { join as join18 } from "node:path";
6212
6714
  var RESTART_MS = 5 * 60000;
6213
6715
  function cgroupPath(text2) {
6214
6716
  const lines = text2?.split(`
@@ -6226,7 +6728,7 @@ function insideUnit(s) {
6226
6728
  return unit !== "" && (own === unit || own.startsWith(`${unit}/`));
6227
6729
  }
6228
6730
  function installedVersion(root) {
6229
- const value = JSON.parse(readFileSync3(join16(root, "package.json"), "utf8"));
6731
+ const value = JSON.parse(readFileSync4(join18(root, "package.json"), "utf8"));
6230
6732
  if (!value || typeof value !== "object" || !("name" in value))
6231
6733
  throw new ContractError("invalid");
6232
6734
  literal(value.name, PACKAGE);
@@ -6264,11 +6766,10 @@ class MaintenanceRecord {
6264
6766
  this.write({ ...job2, state, reason, version, endedAt: Date.now() });
6265
6767
  }
6266
6768
  }
6267
- var npm = (args, show = false) => run("npm", args, show ? INSTALL_MS : VIEW_MS, show);
6268
- function run(command, args, timeout, show = false) {
6769
+ function run(command, args, timeout) {
6269
6770
  return new Promise((resolve7) => {
6270
- const child = spawn(command, args, {
6271
- stdio: ["ignore", show ? 2 : "pipe", show ? 2 : "ignore"],
6771
+ const child = spawn2(command, args, {
6772
+ stdio: ["ignore", "pipe", "ignore"],
6272
6773
  timeout,
6273
6774
  windowsHide: true
6274
6775
  });
@@ -6281,37 +6782,22 @@ function run(command, args, timeout, show = false) {
6281
6782
  child.once("close", (status) => resolve7({ status, stdout }));
6282
6783
  });
6283
6784
  }
6284
- async function upgradeRoute(root, npmRun = npm) {
6285
- const result = await npmRun(["root", "--global"]);
6286
- const global = result.status === 0 ? result.stdout.trim() : "";
6287
- let installed;
6288
- try {
6289
- installed = realpathSync5(join16(global, ...PACKAGE.split("/")));
6290
- if (!global || installed !== realpathSync5(root))
6291
- return "not-npm-global";
6292
- } catch {
6293
- return "not-npm-global";
6294
- }
6295
- try {
6296
- accessSync(dirname12(installed), constants4.W_OK);
6297
- accessSync(global, constants4.W_OK);
6298
- } catch {
6299
- return "not-writable";
6300
- }
6301
- return "npm";
6302
- }
6303
- async function release(spec = "latest", npmRun = npm) {
6304
- const result = await npmRun([
6305
- "view",
6306
- `${PACKAGE}@${spec}`,
6307
- "version",
6308
- "deprecated",
6309
- "--json"
6310
- ]);
6785
+ async function release(spec, command, manager = "npm") {
6786
+ const name = `${PACKAGE}@${spec ?? "latest"}`;
6787
+ const result = await command(manager === "bun" ? ["info", name, "--json"] : ["view", name, "version", "deprecated", "--json"]);
6311
6788
  if (result.status !== 0)
6312
6789
  return;
6313
6790
  try {
6314
6791
  let value = JSON.parse(result.stdout);
6792
+ if (manager === "bun") {
6793
+ if (!value || typeof value !== "object" || Array.isArray(value) || !("name" in value) || !("version" in value))
6794
+ return;
6795
+ literal(value.name, PACKAGE);
6796
+ return {
6797
+ version: decodeVersion(value.version),
6798
+ deprecated: "deprecated" in value && typeof value.deprecated === "string"
6799
+ };
6800
+ }
6315
6801
  if (Array.isArray(value)) {
6316
6802
  if (value.length !== 1)
6317
6803
  return;
@@ -6328,15 +6814,20 @@ async function release(spec = "latest", npmRun = npm) {
6328
6814
  return;
6329
6815
  }
6330
6816
  }
6817
+ function releaseForInstallation(selected, commands, spec) {
6818
+ return "manager" in selected ? release(spec, registryCommand(selected, commands), selected.manager) : Promise.resolve(undefined);
6819
+ }
6331
6820
  async function restartInstalled(s) {
6332
6821
  const name = serviceName(s);
6333
6822
  const result = await run(s.node, [
6334
- join16(s.root, "src", "service-cli.mjs"),
6823
+ join18(s.root, "src", "service-cli.mjs"),
6335
6824
  "server",
6336
6825
  "restart",
6337
6826
  s.scope === "system" ? "--system" : "--user",
6338
6827
  ...name ? ["--name", name] : []
6339
6828
  ], RESTART_MS);
6829
+ if (result.status !== 0)
6830
+ return false;
6340
6831
  try {
6341
6832
  const value = JSON.parse(result.stdout.trim().split(`
6342
6833
  `).at(-1) ?? "");
@@ -6346,46 +6837,54 @@ async function restartInstalled(s) {
6346
6837
  }
6347
6838
  }
6348
6839
  async function upgradeService(s, to, ports) {
6349
- const route = await upgradeRoute(s.root, ports.npm);
6350
- if (route !== "npm")
6351
- return { status: route };
6840
+ const selected = await installation(s, ports.commands);
6841
+ if (!("manager" in selected))
6842
+ return { status: selected.route };
6843
+ const currentVersion = () => {
6844
+ try {
6845
+ return installedVersion(s.root);
6846
+ } catch {
6847
+ return;
6848
+ }
6849
+ };
6352
6850
  const from = installedVersion(s.root);
6353
- const target2 = await release(to, ports.npm);
6354
- if (!target2)
6851
+ const target2 = await releaseForInstallation(selected, ports.commands, to);
6852
+ if (!target2 || to !== undefined && target2.version !== to)
6355
6853
  return { status: "failed", reason: "fetch-failed", from };
6356
6854
  const versions = { from, to: target2.version };
6357
6855
  if (target2.version === from)
6358
6856
  return { status: "current", version: from, ...versions };
6359
6857
  if (target2.deprecated)
6360
6858
  return { status: "deprecated", ...versions };
6361
- const spec = `${PACKAGE}@${target2.version}`;
6362
- if ((await ports.npm(["cache", "add", spec], true)).status !== 0)
6859
+ if (!await fetchVersions(selected, [target2.version, from], ports.commands))
6363
6860
  return { status: "failed", reason: "fetch-failed", ...versions };
6861
+ if (currentVersion() !== from || JSON.stringify(await installation(s, ports.commands)) !== JSON.stringify(selected))
6862
+ return { status: "failed", reason: "refused", ...versions };
6364
6863
  const stopped = await ports.stop();
6365
6864
  if (stopped.status !== "stopped")
6366
6865
  return { ...stopped, reason: "stop-unconfirmed", ...versions };
6367
- const install = (version) => ports.npm([
6368
- "install",
6369
- "--global",
6370
- "--no-audit",
6371
- "--no-fund",
6372
- `${PACKAGE}@${version}`
6373
- ], true);
6374
- const settled = (status, reason) => ({
6866
+ const install = (version) => installVersion(selected, version, ports.commands);
6867
+ const settled = (status, reason2) => ({
6375
6868
  status,
6376
- ...reason ? { reason } : {},
6869
+ ...reason2 ? { reason: reason2 } : {},
6377
6870
  ...versions,
6378
- version: installedVersion(s.root)
6871
+ version: currentVersion()
6379
6872
  });
6380
- if ((await install(target2.version)).status !== 0) {
6381
- await ports.restart();
6382
- return settled("failed", "install-failed");
6873
+ const installed = (await install(target2.version)).status === 0 && currentVersion() === target2.version;
6874
+ if (installed) {
6875
+ if (await ports.restart())
6876
+ return settled("upgraded");
6877
+ const stoppedNew = await ports.stop();
6878
+ if (stoppedNew.status !== "stopped")
6879
+ return {
6880
+ ...stoppedNew,
6881
+ ...settled(stoppedNew.status, "stop-unconfirmed")
6882
+ };
6383
6883
  }
6384
- if (await ports.restart())
6385
- return settled("upgraded");
6386
- if ((await install(from)).status === 0 && await ports.restart())
6387
- return settled("rolled-back", "not-ready");
6388
- return settled("failed", "not-ready");
6884
+ const reason = installed ? "not-ready" : "install-failed";
6885
+ if ((await install(from)).status === 0 && currentVersion() === from && await ports.restart())
6886
+ return settled(installed ? "rolled-back" : "failed", reason);
6887
+ return settled("failed", reason);
6389
6888
  }
6390
6889
  function jobOutcome(action, result) {
6391
6890
  if (action === "upgrade") {
@@ -6406,8 +6905,8 @@ function jobOutcome(action, result) {
6406
6905
  }
6407
6906
 
6408
6907
  // src/service/system-service.ts
6409
- import { existsSync as existsSync3, realpathSync as realpathSync6, rmSync as rmSync6 } from "node:fs";
6410
- import { isAbsolute as isAbsolute8, join as join17 } from "node:path";
6908
+ import { existsSync as existsSync4, realpathSync as realpathSync6, rmSync as rmSync7 } from "node:fs";
6909
+ import { isAbsolute as isAbsolute10, join as join19 } from "node:path";
6411
6910
  var MARKER4 = "# Generated by @abelxiaoxing/cadence";
6412
6911
  function boundary(s) {
6413
6912
  if (s.platform !== "linux" || s.scope !== "system")
@@ -6421,7 +6920,7 @@ function legacyPath(s) {
6421
6920
  function observed(s) {
6422
6921
  const path2 = unitPath(s);
6423
6922
  let previous = readGenerated(path2, MARKER4);
6424
- if (typeof previous === "string" && (unitWorkspace(previous) !== null && !isAbsolute8(unitWorkspace(previous) ?? "") || !previous.includes(`
6923
+ if (typeof previous === "string" && (unitWorkspace(previous) !== null && !isAbsolute10(unitWorkspace(previous) ?? "") || !previous.includes(`
6425
6924
  User=root
6426
6925
  `)))
6427
6926
  previous = null;
@@ -6438,7 +6937,7 @@ function sameStateEnvironment(s, previous) {
6438
6937
  if (values.size !== kept.length)
6439
6938
  return false;
6440
6939
  const state = s.env.XDG_STATE_HOME;
6441
- return values.get("HOME") === s.home && values.get("XDG_STATE_HOME") === (state && isAbsolute8(state) ? state : undefined);
6940
+ return values.get("HOME") === s.home && values.get("XDG_STATE_HOME") === (state && isAbsolute10(state) ? state : undefined);
6442
6941
  } catch {
6443
6942
  return false;
6444
6943
  }
@@ -6459,7 +6958,7 @@ async function configureSystemService(s, mode, requested) {
6459
6958
  const refused2 = boundary(s);
6460
6959
  if (refused2)
6461
6960
  return refused2;
6462
- if (existsSync3(legacyPath(s)))
6961
+ if (existsSync4(legacyPath(s)))
6463
6962
  return { status: "scope-conflict", unit: legacyPath(s), scope: "system" };
6464
6963
  if (s.systemctl(["show-environment"]).status !== 0)
6465
6964
  return { status: "unavailable", scope: "system" };
@@ -6471,17 +6970,17 @@ async function configureSystemService(s, mode, requested) {
6471
6970
  if (mode === "restart" && previous === undefined)
6472
6971
  return { status: "absent", scope: "system" };
6473
6972
  const sdk = sdkPackages(s.root);
6474
- if (previous && unitWorkspace(previous) && !existsSync3(unitWorkspace(previous)))
6973
+ if (previous && unitWorkspace(previous) && !existsSync4(unitWorkspace(previous)))
6475
6974
  return { status: "workspace-changed", ...result };
6476
6975
  const selected = selectWorkspace(s, requested, mode === "install" && requested === undefined ? null : unitWorkspace(previous), false);
6477
6976
  if (selected.workspace !== null && !sdk)
6478
6977
  return { status: "missing-pi-sdk", scope: "system" };
6479
- const selectedReal = selected.workspace && existsSync3(selected.workspace) ? realpathSync6(selected.workspace) : undefined;
6978
+ const selectedReal = selected.workspace && existsSync4(selected.workspace) ? realpathSync6(selected.workspace) : undefined;
6480
6979
  const agentDir = agentDirectory(s);
6481
6980
  const content = buildUnit({
6482
6981
  system: true,
6483
6982
  node: s.node,
6484
- cli: join17(s.root, "src", "service-cli.mjs"),
6983
+ cli: join19(s.root, "src", "service-cli.mjs"),
6485
6984
  workspace: selected.workspace,
6486
6985
  serverConfig: serviceConfigPath(s),
6487
6986
  agentDir,
@@ -6530,7 +7029,7 @@ async function configureSystemService(s, mode, requested) {
6530
7029
  return { status: "failed", ...result, ...selected };
6531
7030
  if (mode === "install" && s.systemctl(["enable", s.unit]).status !== 0)
6532
7031
  return { status: "failed", ...result, ...selected };
6533
- if (selected.workspace !== null && !regularFile(join17(agentDir, "auth.json")))
7032
+ if (selected.workspace !== null && !regularFile(join19(agentDir, "auth.json")))
6534
7033
  return { status: "waiting-for-pi-login", ...result, ...selected };
6535
7034
  s.systemctl(["reset-failed", s.unit]);
6536
7035
  return {
@@ -6572,7 +7071,7 @@ async function stopSystemService(s, remove = false) {
6572
7071
  return { status: "failed", workspace, ...result };
6573
7072
  if (readGenerated(path2, MARKER4) !== previous)
6574
7073
  return { status: "foreign", ...result };
6575
- rmSync6(path2);
7074
+ rmSync7(path2);
6576
7075
  if (s.systemctl(["daemon-reload"]).status !== 0)
6577
7076
  return { status: "failed", ...result };
6578
7077
  s.systemctl(["reset-failed", s.unit]);
@@ -6770,10 +7269,10 @@ function startupGuidance(result, input) {
6770
7269
  return `Pi's agent directory ${agent} must be an existing real directory (not a symlink) owned by you.
6771
7270
  `;
6772
7271
  case "pi-auth":
6773
- return `${join18(agent, "auth.json")} must be your own single-link regular file holding valid Pi credentials; log in to Pi first.
7272
+ return `${join20(agent, "auth.json")} must be your own single-link regular file holding valid Pi credentials; log in to Pi first.
6774
7273
  `;
6775
7274
  case "pi-models":
6776
- return `${join18(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.
7275
+ return `${join20(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.
6777
7276
  `;
6778
7277
  case "pi-runtime":
6779
7278
  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.
@@ -6833,7 +7332,7 @@ async function launchHost(input, c, foreground, hostUrl, cwd, env, network) {
6833
7332
  throw new ContractError("oversize");
6834
7333
  if (!sameNetwork(network, networkSnapshot(process.env)))
6835
7334
  throw new ContractError("stale");
6836
- const child = spawn2(process.execPath, [
7335
+ const child = spawn3(process.execPath, [
6837
7336
  ...env.NODE_USE_ENV_PROXY === "1" ? ["--use-env-proxy"] : [],
6838
7337
  fileURLToPath2(hostUrl)
6839
7338
  ], {
@@ -7004,13 +7503,13 @@ function upgrade(s, to) {
7004
7503
  if (s.platform !== "linux")
7005
7504
  return Promise.resolve({ status: "unsupported" });
7006
7505
  return upgradeService(s, to, {
7007
- npm,
7506
+ commands: packageCommands(s),
7008
7507
  stop: () => serverAction(s, "stop", undefined, false),
7009
7508
  restart: () => restartInstalled(s)
7010
7509
  });
7011
7510
  }
7012
7511
  function serverGuidance(s, action, result, link) {
7013
- const cli = piUserInstall(s) ? `node ${JSON.stringify(join18(s.root, "src", "service-cli.mjs"))}` : "cadence";
7512
+ const cli = piUserInstall(s) ? `node ${JSON.stringify(join20(s.root, "src", "service-cli.mjs"))}` : "cadence";
7014
7513
  const note = result.redirectedFrom ? `Cadence workspace: ${result.workspace} (${result.redirectedFrom} contains Cadence's private state)
7015
7514
  ` : "";
7016
7515
  return note + serverStatusGuidance(s, action, result, cli, link);
@@ -7043,7 +7542,7 @@ function managerDetail(s) {
7043
7542
  var REASONS = {
7044
7543
  "fetch-failed": "the release could not be fetched; the service kept running",
7045
7544
  "stop-unconfirmed": "the running service did not confirm its orderly Stop",
7046
- "install-failed": "npm could not install it",
7545
+ "install-failed": "the package manager could not install it",
7047
7546
  "not-ready": "the new version did not become ready"
7048
7547
  };
7049
7548
  function serverStatusGuidance(s, action, result, cli, link) {
@@ -7066,17 +7565,20 @@ function serverStatusGuidance(s, action, result, cli, link) {
7066
7565
  case "rolled-back":
7067
7566
  return `Cadence ${result.to} did not become ready, so ${result.from} was reinstalled and is running; ${managerDetail(s)}.
7068
7567
  `;
7069
- case "not-npm-global":
7070
- return `This copy of Cadence (${s.root}) was not installed with npm install -g, so it cannot upgrade itself. ${terminal}
7568
+ case "unsupported-install":
7569
+ return `The installation method for this copy of Cadence (${s.root}) could not be safely identified. ${terminal}
7570
+ `;
7571
+ case "pinned":
7572
+ return `Pi pins this package version; change its package declaration explicitly before upgrading. ${terminal}
7071
7573
  `;
7072
7574
  case "not-writable":
7073
- return `npm cannot write ${s.root} as this account. ${terminal}
7575
+ return `The package manager cannot write ${s.root} as this account. ${terminal}
7074
7576
  `;
7075
7577
  case "unsupported":
7076
- return `Cadence upgrades itself only on Linux. Run npm install -g ${PACKAGE}@latest, then: ${cli} server restart
7578
+ return `Cadence upgrades itself only on Linux. ${terminal}
7077
7579
  `;
7078
7580
  case "failed":
7079
- return `Cadence was not upgraded: ${REASONS[result.reason ?? ""] ?? result.reason}. Running now: ${result.version ?? result.from}; ${managerDetail(s)}.
7581
+ return `Cadence was not upgraded: ${REASONS[result.reason ?? ""] ?? result.reason}. Installed version: ${result.version ?? "not confirmed"}; ${managerDetail(s)}.
7080
7582
  `;
7081
7583
  }
7082
7584
  }
@@ -7114,7 +7616,7 @@ ${manage}
7114
7616
  ${linger}`;
7115
7617
  }
7116
7618
  case "waiting-for-pi-login":
7117
- return `Cadence is registered for ${result.workspace}; it starts once Pi has ${join18(agentDirectory(s), "auth.json")}.
7619
+ return `Cadence is registered for ${result.workspace}; it starts once Pi has ${join20(agentDirectory(s), "auth.json")}.
7118
7620
  Log in to Pi, then: ${cli} server restart${flags}
7119
7621
  ${config}
7120
7622
  ${lingerGuidance(result.linger)}`;
@@ -7306,7 +7808,7 @@ async function serverMain(argv, hostUrl) {
7306
7808
  if (job2 && (action === "restart" || action === "upgrade")) {
7307
7809
  const { state, reason } = jobOutcome(action, result);
7308
7810
  try {
7309
- new MaintenanceRecord(new GatewayStore(serviceConfigPath(s))).finish(job2, state, reason, installedVersion(s.root));
7811
+ new MaintenanceRecord(new GatewayStore(serviceConfigPath(s))).finish(job2, state, reason, action === "upgrade" ? result.version ?? null : installedVersion(s.root));
7310
7812
  } catch {}
7311
7813
  }
7312
7814
  process.stderr.write(vanished ?? serverGuidance(s, action, result, link));
@@ -7326,7 +7828,8 @@ async function serverMain(argv, hostUrl) {
7326
7828
  "project-running",
7327
7829
  "environment-changed",
7328
7830
  "inside-service",
7329
- "not-npm-global",
7831
+ "unsupported-install",
7832
+ "pinned",
7330
7833
  "not-writable",
7331
7834
  "deprecated",
7332
7835
  "rolled-back"
@@ -7494,7 +7997,7 @@ cadence workbench start|status|diagnose|stop|token-link --reveal|token-rotate [-
7494
7997
  cadence doctor [--fix] [--yes] [--workspace PATH] [--state-home PATH] [--server-config PATH]
7495
7998
  Start recovers automatically from an unclean shutdown or crash. Doctor shows the state readonly; --fix also stops an unresponsive Cadence or takes over state it cannot observe, after one confirmation (--yes skips it). recover inspect|resolve are aliases of doctor and doctor --fix.
7496
7999
  cadence server install [--workspace PATH] [--no-linger]|status|restart|stop|uninstall|upgrade [--to VERSION]
7497
- Upgrade (Linux, npm global installs) fetches the release while the service runs, then stops it, installs the release and restarts; a release that does not become ready is replaced by the previous version. Server commands that change the service refuse to run inside it; use the WebUI or a terminal.
8000
+ Upgrade (Linux, identified Pi/npm/Bun installs) fetches the release while the service runs, then stops it, installs the release and restarts; a release that does not become ready is replaced by the previous version. Server commands that change the service refuse to run inside it; use the WebUI or a terminal.
7498
8001
  Linux server options: --system (root, no linger) or --user; --name NAME selects an independent service; install also accepts --port PORT (required for a new named service). Root defaults to --system. No automatic sudo or profile migration.
7499
8002
  cadence project open [PATH] [--create] [--agent-dir PATH] [--state-home PATH]
7500
8003
  Project open explicitly starts/reuses that checkout owner, selecting a private free port for a new project. It never creates or starts a task.