@abelxiaoxing/cadence 2.0.37 → 2.0.40

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 (48) hide show
  1. package/README.de.md +2 -2
  2. package/README.es.md +2 -2
  3. package/README.fr.md +2 -2
  4. package/README.ja.md +2 -2
  5. package/README.ko.md +2 -2
  6. package/README.md +9 -7
  7. package/README.pt-BR.md +2 -2
  8. package/README.ru.md +2 -2
  9. package/README.zh-CN.md +10 -8
  10. package/agents/design-explorer.md +4 -2
  11. package/agents/diagnosis-worker.md +5 -2
  12. package/agents/implementation-worker.md +19 -12
  13. package/docs/conversation-mode.md +73 -16
  14. package/docs/reuse-and-distribution.md +78 -0
  15. package/package.json +7 -2
  16. package/src/activity.ts +147 -0
  17. package/src/agent-browser/session-navigator.ts +33 -6
  18. package/src/agent-browser/source.ts +23 -19
  19. package/src/agent-panel-cadence.ts +147 -628
  20. package/src/agent-panel-model.ts +30 -19
  21. package/src/agent-panel.ts +12 -16
  22. package/src/cadence-instructions.ts +8 -7
  23. package/src/cadence-mode.ts +30 -9
  24. package/src/change-tools.mjs +268 -0
  25. package/src/coordinator-tools.mjs +2 -2
  26. package/src/git-environment.d.mts +2 -0
  27. package/src/git-environment.mjs +24 -0
  28. package/src/index.ts +3 -1
  29. package/src/native-build.ts +1 -1
  30. package/src/native-workflow-history.ts +20 -3
  31. package/src/operator-cli.mjs +22 -12
  32. package/src/research-scan.mjs +111 -31
  33. package/src/research-tools.mjs +75 -16
  34. package/src/sdk-worker.mjs +6 -1
  35. package/src/service/activity-files.ts +190 -0
  36. package/src/service/contracts/workbench.ts +11 -3
  37. package/src/service/contracts/workflow.ts +283 -16
  38. package/src/service/coordination.ts +13 -3
  39. package/src/service-cli.mjs +392 -93
  40. package/src/service-host.mjs +7635 -5682
  41. package/src/worker-capture.mjs +24 -1
  42. package/src/worker-public.mjs +18 -0
  43. package/src/worker-redaction.mjs +11 -0
  44. package/src/worker-toolkit.mjs +55 -2
  45. package/src/workspace.ts +62 -25
  46. package/web/dist/assets/cadence.css +1 -1
  47. package/web/dist/assets/cadence.js +19 -18
  48. package/web/dist/manifest.json +7 -7
@@ -6,7 +6,7 @@ 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 join19, 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,8 +1770,26 @@ 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
- import { spawnSync } from "node:child_process";
1792
+ import { execFile, spawnSync } from "node:child_process";
1775
1793
  import { createHash } from "node:crypto";
1776
1794
  import {
1777
1795
  closeSync as closeSync2,
@@ -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"]), {
@@ -1911,6 +1918,9 @@ function resolveWorkspace(cwd) {
1911
1918
  maxBuffer: 8192,
1912
1919
  windowsHide: true
1913
1920
  });
1921
+ return workspaceResult(actual, result);
1922
+ }
1923
+ function workspaceResult(actual, result) {
1914
1924
  const topLevel = result.stdout?.replace(process.platform === "win32" ? /\r?\n$/ : /\n$/, "");
1915
1925
  if (result.status === 0 && topLevel)
1916
1926
  return { root: realpathSync(topLevel), cwd: actual };
@@ -3404,7 +3414,7 @@ class ServiceCoordination {
3404
3414
  registryDirectory;
3405
3415
  stateHome;
3406
3416
  constructor(workspace, stateHome) {
3407
- this.project = workspace === null ? undefined : new CheckoutStore(resolveWorkspace(workspace).root, stateHome);
3417
+ this.project = workspace === null ? undefined : workspace instanceof CheckoutStore ? workspace : new CheckoutStore(resolveWorkspace(workspace).root, stateHome);
3408
3418
  this.stateHome = this.project ? dirname6(dirname6(this.project.privateRoot)) : canonicalAmbientRoot(stateHome ?? defaultStateHome());
3409
3419
  const namespace = join6(this.stateHome, "cadence-assistant-v1");
3410
3420
  this.files = new PrivateFiles(namespace);
@@ -3638,6 +3648,8 @@ class ServiceCoordination {
3638
3648
  }
3639
3649
  acquire(input, resolvedEndpoint = input.endpoint, initializeNew, reselectExisting) {
3640
3650
  this.store;
3651
+ if (rootsOverlap(this.store.root, join6(this.stateHome, "cadence-worktrees-v1")))
3652
+ throw new ContractError("forbidden");
3641
3653
  const config = decodeOwnerConfig(input);
3642
3654
  const bound = endpoint(resolvedEndpoint);
3643
3655
  if (!endpointMatches(config.endpoint, bound))
@@ -4673,10 +4685,10 @@ function strayTemporaries(directory2) {
4673
4685
  }
4674
4686
 
4675
4687
  // src/service/self-heal.ts
4676
- import { createHash as createHash4, randomUUID as randomUUID7 } from "node:crypto";
4677
- import { lstatSync as lstatSync7, opendirSync as opendirSync4 } from "node:fs";
4688
+ import { createHash as createHash4, randomUUID as randomUUID8 } from "node:crypto";
4689
+ import { lstatSync as lstatSync8, opendirSync as opendirSync5 } from "node:fs";
4678
4690
  import { hostname as hostname5 } from "node:os";
4679
- import { join as join11 } from "node:path";
4691
+ import { join as join12 } from "node:path";
4680
4692
 
4681
4693
  // src/service/process-ledger.ts
4682
4694
  import { rmSync as rmSync3 } from "node:fs";
@@ -4796,6 +4808,250 @@ class LiveLedger {
4796
4808
  }
4797
4809
  }
4798
4810
 
4811
+ // src/service/repository-coordination.ts
4812
+ import { randomUUID as randomUUID7 } from "node:crypto";
4813
+ import { lstatSync as lstatSync7, opendirSync as opendirSync4 } from "node:fs";
4814
+ import { isAbsolute as isAbsolute6, join as join11 } from "node:path";
4815
+ import { setTimeout as delay } from "node:timers/promises";
4816
+ var WAIT_MS = 30000;
4817
+ var POLL_MS = 50;
4818
+ var ACTIVE_RESOURCES = 256;
4819
+ function decode3(value) {
4820
+ const o = closed(value, [
4821
+ "schema",
4822
+ "kind",
4823
+ "resource",
4824
+ "root",
4825
+ "epoch",
4826
+ "run",
4827
+ "token",
4828
+ "identity",
4829
+ "holder"
4830
+ ]);
4831
+ if (o.schema !== "cadence-delivery-resource/1" || !["mutation", "workspace"].includes(String(o.kind)))
4832
+ throw new ContractError("corrupt-selected");
4833
+ for (const path2 of [o.resource, o.root])
4834
+ if (typeof path2 !== "string" || !isAbsolute6(path2) || path2.includes("\x00"))
4835
+ throw new ContractError("corrupt-selected");
4836
+ const h = closed(o.holder, ["pid", "host", "boot", "started"]);
4837
+ if (!Number.isSafeInteger(h.pid) || Number(h.pid) < 1 || typeof h.host !== "string" || ![h.boot, h.started].every((x) => x === null || typeof x === "string"))
4838
+ throw new ContractError("corrupt-selected");
4839
+ return {
4840
+ schema: "cadence-delivery-resource/1",
4841
+ kind: o.kind,
4842
+ resource: text(o.resource, 4096, true),
4843
+ root: text(o.root, 4096, true),
4844
+ epoch: decodeId(o.epoch),
4845
+ run: decodeId(o.run),
4846
+ token: decodeId(o.token),
4847
+ identity: o.identity === null ? null : decodeHash(o.identity),
4848
+ holder: h
4849
+ };
4850
+ }
4851
+ var directory2 = (files) => join11(files.namespace, "delivery-resources-v1");
4852
+ var resourcePath = (files, row) => join11(directory2(files), row.kind, `${hash(row.resource)}.json`);
4853
+ var ownerDirectory = (files, root, epoch) => join11(directory2(files), "owners", hash(root), decodeId(epoch));
4854
+ var indexPath = (files, row) => join11(ownerDirectory(files, row.root, row.epoch), `${row.kind}-${hash(row.resource)}.json`);
4855
+ function worktreeIdentity(path2) {
4856
+ const root = lstatSync7(path2), marker = lstatSync7(join11(path2, ".git"));
4857
+ if (!root.isDirectory() || root.isSymbolicLink() || !marker.isFile() || marker.nlink !== 1 || marker.size > 8192)
4858
+ throw new ContractError("stale");
4859
+ const body = readBounded(join11(path2, ".git"), 8192);
4860
+ const after = lstatSync7(join11(path2, ".git")), afterRoot = lstatSync7(path2);
4861
+ 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)
4862
+ throw new ContractError("stale");
4863
+ return hash(encoded([
4864
+ root.dev,
4865
+ root.ino,
4866
+ marker.dev,
4867
+ marker.ino,
4868
+ body.toString("utf8")
4869
+ ]));
4870
+ }
4871
+
4872
+ class RepositoryCoordination {
4873
+ c;
4874
+ root;
4875
+ epoch;
4876
+ run;
4877
+ assertOwner;
4878
+ fault;
4879
+ owned = new Map;
4880
+ constructor(c, root, epoch, run, assertOwner, fault) {
4881
+ this.c = c;
4882
+ this.root = root;
4883
+ this.epoch = epoch;
4884
+ this.run = run;
4885
+ this.assertOwner = assertOwner;
4886
+ this.fault = fault;
4887
+ }
4888
+ write(operation) {
4889
+ try {
4890
+ return operation();
4891
+ } catch (error) {
4892
+ this.fault();
4893
+ throw error;
4894
+ }
4895
+ }
4896
+ reserve(kind, resource) {
4897
+ this.assertOwner();
4898
+ const row = {
4899
+ schema: "cadence-delivery-resource/1",
4900
+ kind,
4901
+ resource,
4902
+ root: this.root,
4903
+ epoch: this.epoch,
4904
+ run: this.run,
4905
+ token: randomUUID7(),
4906
+ identity: null,
4907
+ holder: selfMark()
4908
+ };
4909
+ const target = resourcePath(this.c.files, row);
4910
+ if (this.c.files.read(target))
4911
+ return null;
4912
+ const index = this.write(() => this.c.files.create(indexPath(this.c.files, row), encoded(row)));
4913
+ let file;
4914
+ try {
4915
+ file = this.c.files.create(target, encoded(row));
4916
+ } catch (error) {
4917
+ if (error instanceof Error && "code" in error && error.code === "EEXIST") {
4918
+ this.write(() => this.c.files.remove(indexPath(this.c.files, row), index));
4919
+ return null;
4920
+ }
4921
+ this.fault();
4922
+ throw error;
4923
+ }
4924
+ const held = { row, file, index };
4925
+ this.owned.set(row.token, held);
4926
+ return held;
4927
+ }
4928
+ async mutate(repository, signal, operation, settled) {
4929
+ const deadline = performance.now() + WAIT_MS;
4930
+ let held;
4931
+ for (;; ) {
4932
+ this.assertOwner();
4933
+ if (signal.aborted)
4934
+ throw new ContractError("stale");
4935
+ held = this.reserve("mutation", repository);
4936
+ if (held)
4937
+ break;
4938
+ if (performance.now() >= deadline)
4939
+ throw new ContractError("conflict");
4940
+ await delay(POLL_MS, undefined, { signal });
4941
+ }
4942
+ try {
4943
+ return await operation();
4944
+ } finally {
4945
+ if (settled())
4946
+ this.release(held.row.token);
4947
+ }
4948
+ }
4949
+ reserveWorkspace(path2) {
4950
+ const held = this.reserve("workspace", path2);
4951
+ if (!held)
4952
+ throw new ContractError("conflict");
4953
+ return held.row.token;
4954
+ }
4955
+ confirmWorkspace(token) {
4956
+ const held = this.require(token);
4957
+ held.row = { ...held.row, identity: worktreeIdentity(held.row.resource) };
4958
+ 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" })));
4959
+ }
4960
+ assertWorkspace(token) {
4961
+ this.assertOwner();
4962
+ const held = this.require(token);
4963
+ this.c.files.assert(resourcePath(this.c.files, held.row), held.file);
4964
+ if (!held.row.identity || worktreeIdentity(held.row.resource) !== held.row.identity)
4965
+ throw new ContractError("stale");
4966
+ }
4967
+ require(token) {
4968
+ const held = this.owned.get(token);
4969
+ if (!held)
4970
+ throw new ContractError("stale");
4971
+ return held;
4972
+ }
4973
+ release(token) {
4974
+ this.assertOwner();
4975
+ const held = this.require(token);
4976
+ this.write(() => {
4977
+ this.c.files.remove(resourcePath(this.c.files, held.row), held.file);
4978
+ this.c.files.remove(indexPath(this.c.files, held.row), held.index);
4979
+ });
4980
+ this.owned.delete(token);
4981
+ }
4982
+ finish() {
4983
+ for (const held of [...this.owned.values()])
4984
+ if (held.row.kind === "workspace")
4985
+ this.release(held.row.token);
4986
+ }
4987
+ }
4988
+ function recoverDeliveryResources(files, root, epoch, options = {}) {
4989
+ const home = ownerDirectory(files, root, epoch);
4990
+ if (!files.directory(home))
4991
+ return 0;
4992
+ const dir = opendirSync4(home);
4993
+ const actions = [];
4994
+ let count = 0;
4995
+ const read = (path2) => {
4996
+ try {
4997
+ const snapshot = files.read(path2);
4998
+ if (!snapshot)
4999
+ return { snapshot, row: undefined, broken: false };
5000
+ try {
5001
+ return { snapshot, row: decode3(json(snapshot)), broken: false };
5002
+ } catch {
5003
+ return { snapshot, row: undefined, broken: true };
5004
+ }
5005
+ } catch {
5006
+ return { snapshot: undefined, row: undefined, broken: true };
5007
+ }
5008
+ };
5009
+ const archive = (path2) => {
5010
+ if (!options.archive)
5011
+ throw new ContractError("corrupt-selected");
5012
+ options.archive(path2);
5013
+ };
5014
+ try {
5015
+ for (let entry = dir.readSync();entry; entry = dir.readSync()) {
5016
+ if (++count > ACTIVE_RESOURCES)
5017
+ throw new ContractError("capacity");
5018
+ const match = /^(mutation|workspace)-([a-f0-9]{64})\.json$/u.exec(entry.name);
5019
+ const path2 = join11(home, entry.name);
5020
+ if (!match) {
5021
+ if (!options.takeOver)
5022
+ throw new ContractError("corrupt-selected");
5023
+ actions.push(() => archive(path2));
5024
+ continue;
5025
+ }
5026
+ const [, kind, key] = match;
5027
+ const index = read(path2), target = join11(directory2(files), kind, `${key}.json`), shared = read(target);
5028
+ const matches = (row) => row.kind === kind && hash(row.resource) === key && row.root === root && row.epoch === epoch;
5029
+ const ownerMatches = (row) => !options.expectedOwner || Object.entries(options.expectedOwner).every(([key2, value]) => value == null || row.holder[key2] === value);
5030
+ const badIndex = index.broken || !index.row || !matches(index.row) || !ownerMatches(index.row);
5031
+ 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)));
5032
+ if (badShared && !options.takeOver)
5033
+ throw new ContractError("corrupt-selected");
5034
+ actions.push(() => {
5035
+ if (badShared)
5036
+ archive(target);
5037
+ else if (shared.row && shared.snapshot && matches(shared.row) && (!index.row || badIndex || index.row.token === shared.row.token)) {
5038
+ files.remove(target, shared.snapshot);
5039
+ }
5040
+ if (badIndex)
5041
+ archive(path2);
5042
+ else if (index.snapshot)
5043
+ files.remove(path2, index.snapshot);
5044
+ });
5045
+ }
5046
+ } finally {
5047
+ dir.closeSync();
5048
+ }
5049
+ if (!options.inspect)
5050
+ for (const action of actions)
5051
+ action();
5052
+ return count;
5053
+ }
5054
+
4799
5055
  // src/service/self-heal.ts
4800
5056
  function attempt(read) {
4801
5057
  try {
@@ -4804,7 +5060,7 @@ function attempt(read) {
4804
5060
  return null;
4805
5061
  }
4806
5062
  }
4807
- function readFile(files, path2, decode3, maximum) {
5063
+ function readFile(files, path2, decode4, maximum) {
4808
5064
  let snapshot;
4809
5065
  try {
4810
5066
  snapshot = files.read(path2, maximum);
@@ -4817,7 +5073,7 @@ function readFile(files, path2, decode3, maximum) {
4817
5073
  return {
4818
5074
  path: path2,
4819
5075
  snapshot: bytes,
4820
- value: attempt(() => decode3(json(bytes, maximum)))
5076
+ value: attempt(() => decode4(json(bytes, maximum)))
4821
5077
  };
4822
5078
  }
4823
5079
  function decodeOwnerLock(value) {
@@ -4927,7 +5183,7 @@ class RegistryHealer {
4927
5183
  this.ledger = new ProcessLedger(c.files);
4928
5184
  }
4929
5185
  path(name) {
4930
- return join11(this.c.registryDirectory, name);
5186
+ return join12(this.c.registryDirectory, name);
4931
5187
  }
4932
5188
  async heal(options = {}) {
4933
5189
  const lockPath = this.path("registry.lock");
@@ -4938,7 +5194,7 @@ class RegistryHealer {
4938
5194
  lock = undefined;
4939
5195
  const age = (() => {
4940
5196
  try {
4941
- return Date.now() - lstatSync7(lockPath).mtimeMs;
5197
+ return Date.now() - lstatSync8(lockPath).mtimeMs;
4942
5198
  } catch {
4943
5199
  return 0;
4944
5200
  }
@@ -5044,7 +5300,7 @@ class RegistryHealer {
5044
5300
  const lockPath = this.path("registry.lock");
5045
5301
  const lock = this.c.files.create(lockPath, encoded({
5046
5302
  schema: "cadence-service-registry-lock/1",
5047
- token: randomUUID7(),
5303
+ token: randomUUID8(),
5048
5304
  pid: process.pid,
5049
5305
  host: hostname5()
5050
5306
  }));
@@ -5087,19 +5343,19 @@ class RegistryHealer {
5087
5343
  }
5088
5344
  function liveReservations(c) {
5089
5345
  const out = [];
5090
- const dir = opendirSync4(c.files.namespace);
5346
+ const dir = opendirSync5(c.files.namespace);
5091
5347
  try {
5092
5348
  for (let e = dir.readSync();e; e = dir.readSync()) {
5093
5349
  if (!/^[a-f0-9]{64}$/.test(e.name))
5094
5350
  continue;
5095
- const service = join11(c.files.namespace, e.name, "service-v1");
5096
- const registration2 = readFile(c.files, join11(service, "registration.json"), decodeRegistrationLenient);
5351
+ const service = join12(c.files.namespace, e.name, "service-v1");
5352
+ const registration2 = readFile(c.files, join12(service, "registration.json"), decodeRegistrationLenient);
5097
5353
  if (!registration2 || registration2 === "unreadable")
5098
5354
  continue;
5099
5355
  const r = registration2.value;
5100
5356
  if (!r || r.phase === "stopped")
5101
5357
  continue;
5102
- const owner = readFile(c.files, join11(service, "owner.lock"), decodeOwnerLock);
5358
+ const owner = readFile(c.files, join12(service, "owner.lock"), decodeOwnerLock);
5103
5359
  const mark = owner && owner !== "unreadable" && owner.value ? owner.value : r;
5104
5360
  if (holderState(mark, stampTime(registration2.snapshot.stamp)).state !== "live")
5105
5361
  continue;
@@ -5120,20 +5376,20 @@ function liveReservations(c) {
5120
5376
  return out;
5121
5377
  }
5122
5378
  function projectFiles(c, root) {
5123
- const privateRoot = join11(c.files.namespace, createHash4("sha256").update(root).digest("hex"));
5379
+ const privateRoot = join12(c.files.namespace, createHash4("sha256").update(root).digest("hex"));
5124
5380
  return {
5125
5381
  root,
5126
5382
  privateRoot,
5127
- service: join11(privateRoot, "service-v1"),
5128
- checkoutPath: join11(privateRoot, "checkout.lock")
5383
+ service: join12(privateRoot, "service-v1"),
5384
+ checkoutPath: join12(privateRoot, "checkout.lock")
5129
5385
  };
5130
5386
  }
5131
5387
  function snapshotProject(c, p) {
5132
5388
  const s = { temporaries: [] };
5133
- s.registration = readFile(c.files, join11(p.service, "registration.json"), decodeRegistrationLenient);
5134
- s.owner = readFile(c.files, join11(p.service, "owner.lock"), decodeOwnerLock);
5389
+ s.registration = readFile(c.files, join12(p.service, "registration.json"), decodeRegistrationLenient);
5390
+ s.owner = readFile(c.files, join12(p.service, "owner.lock"), decodeOwnerLock);
5135
5391
  try {
5136
- s.capability = c.files.read(join11(p.service, "local-capability.json"));
5392
+ s.capability = c.files.read(join12(p.service, "local-capability.json"));
5137
5393
  } catch {
5138
5394
  s.capability = "unreadable";
5139
5395
  }
@@ -5148,7 +5404,7 @@ function snapshotProject(c, p) {
5148
5404
  } catch {}
5149
5405
  s.temporaries = [
5150
5406
  ...strayTemporaries(p.service),
5151
- ...strayTemporaries(join11(p.service, "history-v2"))
5407
+ ...strayTemporaries(join12(p.service, "history-v2"))
5152
5408
  ];
5153
5409
  return s;
5154
5410
  }
@@ -5217,6 +5473,28 @@ async function healProjectAt(c, root, options = {}) {
5217
5473
  const workers = takenOver ? { stopped: 0, running: 0 } : await stopWorkers(ledger, epoch, holder.reboot, !!options.inspect);
5218
5474
  if (workers.running)
5219
5475
  return { status: "blocked", reason: "workers-running", pid };
5476
+ const selectedOwner = [
5477
+ s.owner && s.owner !== "unreadable" ? s.owner.value : null,
5478
+ s.registration && s.registration !== "unreadable" ? s.registration.value : null,
5479
+ s.row
5480
+ ].find((value) => value?.epoch === epoch);
5481
+ const expectedOwner = selectedOwner ? {
5482
+ pid: selectedOwner.pid,
5483
+ host: selectedOwner.host,
5484
+ ..."boot" in selectedOwner ? { boot: selectedOwner.boot ?? null } : {},
5485
+ ..."started" in selectedOwner ? { started: selectedOwner.started ?? null } : {}
5486
+ } : undefined;
5487
+ if (epoch) {
5488
+ try {
5489
+ recoverDeliveryResources(c.files, root, epoch, {
5490
+ inspect: true,
5491
+ takeOver: options.takeOver,
5492
+ expectedOwner
5493
+ });
5494
+ } catch {
5495
+ return { status: "blocked", reason: "holder-unknown", pid };
5496
+ }
5497
+ }
5220
5498
  const restarted = epoch ? ledger.restartRequested(epoch) : false;
5221
5499
  const cause = !active(s) ? "storage" : holder.reboot ? "reboot" : restarted ? "restart" : "crash";
5222
5500
  if (options.inspect)
@@ -5227,6 +5505,12 @@ async function healProjectAt(c, root, options = {}) {
5227
5505
  if (workers.stopped)
5228
5506
  actions.add("stopped-workers");
5229
5507
  const archive = log.archive();
5508
+ if (epoch && recoverDeliveryResources(c.files, root, epoch, {
5509
+ takeOver: options.takeOver,
5510
+ expectedOwner,
5511
+ archive: (path2) => archive.keep(path2)
5512
+ }))
5513
+ actions.add("released-locks");
5230
5514
  if (active(s)) {
5231
5515
  reclaim(c, p, s, archive);
5232
5516
  actions.add("released-locks");
@@ -5261,8 +5545,8 @@ function metadataDamaged(c, p) {
5261
5545
  return false;
5262
5546
  }
5263
5547
  try {
5264
- const format = c.files.read(join11(p.service, "format.json"));
5265
- const config = c.files.read(join11(p.service, "config.json"));
5548
+ const format = c.files.read(join12(p.service, "format.json"));
5549
+ const config = c.files.read(join12(p.service, "config.json"));
5266
5550
  if (!format || !config)
5267
5551
  return true;
5268
5552
  const f = closed(json(format), [
@@ -5274,10 +5558,10 @@ function metadataDamaged(c, p) {
5274
5558
  if (f.schema !== "cadence-service-format/1" || f.root !== p.root || f.stateHome !== c.stateHome || f.configIdentity !== config.identity)
5275
5559
  return true;
5276
5560
  const selected = decodeOwnerConfig(json(config));
5277
- const host = c.files.read(join11(p.service, "host-config.json"));
5561
+ const host = c.files.read(join12(p.service, "host-config.json"));
5278
5562
  if (host && host.identity !== selected.policyIdentity)
5279
5563
  return true;
5280
- const registration2 = c.files.read(join11(p.service, "registration.json"));
5564
+ const registration2 = c.files.read(join12(p.service, "registration.json"));
5281
5565
  if (registration2) {
5282
5566
  const r = decodeRegistration(json(registration2));
5283
5567
  if (r.root !== p.root || r.stateHome !== c.stateHome || r.configIdentity !== config.identity)
@@ -5300,7 +5584,7 @@ function reclaim(c, p, expected, archive) {
5300
5584
  mutate();
5301
5585
  const registration2 = s.registration;
5302
5586
  if (registration2 === "unreadable")
5303
- archive.keep(join11(p.service, "registration.json"));
5587
+ archive.keep(join12(p.service, "registration.json"));
5304
5588
  else if (registration2) {
5305
5589
  if (!registration2.value)
5306
5590
  archive.keep(registration2.path);
@@ -5308,7 +5592,7 @@ function reclaim(c, p, expected, archive) {
5308
5592
  c.files.replace(registration2.path, registration2.snapshot, encoded({ ...registration2.value, phase: "stopped" }));
5309
5593
  }
5310
5594
  if (s.row)
5311
- c.files.replace(join11(c.registryDirectory, "roots.json"), view.snapshot, encoded({
5595
+ c.files.replace(join12(c.registryDirectory, "roots.json"), view.snapshot, encoded({
5312
5596
  ...view.value,
5313
5597
  entries: view.value.entries.filter((row) => row.root !== p.root)
5314
5598
  }), 1024 * 1024);
@@ -5321,8 +5605,8 @@ function reclaim(c, p, expected, archive) {
5321
5605
  }
5322
5606
  c.files.remove(path2, "snapshot" in value ? value.snapshot : value, maximum);
5323
5607
  };
5324
- drop(join11(p.service, "local-capability.json"), s.capability);
5325
- drop(join11(p.service, "owner.lock"), s.owner);
5608
+ drop(join12(p.service, "local-capability.json"), s.capability);
5609
+ drop(join12(p.service, "owner.lock"), s.owner);
5326
5610
  drop(p.checkoutPath, s.checkout, 8192);
5327
5611
  });
5328
5612
  }
@@ -5660,16 +5944,16 @@ Cadence releases whatever the old project owner left behind automatically.
5660
5944
 
5661
5945
  // src/service/gateway-cli.ts
5662
5946
  import { homedir as homedir6 } from "node:os";
5663
- import { dirname as dirname9, join as join13, resolve as resolve6 } from "node:path";
5947
+ import { dirname as dirname9, join as join14, resolve as resolve6 } from "node:path";
5664
5948
  import { fileURLToPath } from "node:url";
5665
5949
 
5666
5950
  // src/service/runtime.ts
5667
5951
  import { homedir as homedir5 } from "node:os";
5668
- import { dirname as dirname8, isAbsolute as isAbsolute6, join as join12, resolve as resolve5 } from "node:path";
5952
+ import { dirname as dirname8, isAbsolute as isAbsolute7, join as join13, resolve as resolve5 } from "node:path";
5669
5953
  var STARTUP_INPUT_BYTES = 16 * 1024;
5670
5954
  function absolute(value) {
5671
5955
  const result = text(value, 4096, true);
5672
- if (!isAbsolute6(result))
5956
+ if (!isAbsolute7(result))
5673
5957
  throw new ContractError("invalid");
5674
5958
  return result;
5675
5959
  }
@@ -5765,7 +6049,7 @@ function selectStart(options, ambient) {
5765
6049
  port: options.port ?? 17423,
5766
6050
  proxy: null
5767
6051
  },
5768
- agentDir: resolve5(options.agentDir ?? ambient.PI_CODING_AGENT_DIR ?? join12(ambient.HOME ?? ambient.USERPROFILE ?? homedir5(), ".pi", "agent")),
6052
+ agentDir: resolve5(options.agentDir ?? ambient.PI_CODING_AGENT_DIR ?? join13(ambient.HOME ?? ambient.USERPROFILE ?? homedir5(), ".pi", "agent")),
5769
6053
  tokenSource: options.tokenFile ? "file" : env ? "environment" : "generated",
5770
6054
  tokenFile: options.tokenFile ? resolve5(options.tokenFile) : null
5771
6055
  });
@@ -5897,7 +6181,7 @@ async function gatewayMain(argv, hostUrl) {
5897
6181
  kind: "workbench",
5898
6182
  serverConfig: config,
5899
6183
  stateHome: store.stateHome,
5900
- agentDir: agentDir ?? selected?.agentDir ?? resolve6(process.env.PI_CODING_AGENT_DIR ?? join13(homedir6(), ".pi", "agent")),
6184
+ agentDir: agentDir ?? selected?.agentDir ?? resolve6(process.env.PI_CODING_AGENT_DIR ?? join14(homedir6(), ".pi", "agent")),
5901
6185
  policy: { ...policy, port: server.port }
5902
6186
  });
5903
6187
  const blocked = await healWorkbenchForStart(store, () => ownerResponsive(store));
@@ -5944,7 +6228,7 @@ import {
5944
6228
  accessSync,
5945
6229
  constants as constants4,
5946
6230
  existsSync as existsSync3,
5947
- lstatSync as lstatSync8,
6231
+ lstatSync as lstatSync9,
5948
6232
  mkdtempSync,
5949
6233
  readFileSync as readFileSync3,
5950
6234
  realpathSync as realpathSync5,
@@ -5952,7 +6236,7 @@ import {
5952
6236
  writeFileSync as writeFileSync4
5953
6237
  } from "node:fs";
5954
6238
  import { tmpdir } from "node:os";
5955
- import { basename as basename2, dirname as dirname10, isAbsolute as isAbsolute7, join as join14 } from "node:path";
6239
+ import { basename as basename2, dirname as dirname10, isAbsolute as isAbsolute8, join as join15 } from "node:path";
5956
6240
  var PACKAGE = "@abelxiaoxing/cadence";
5957
6241
  var VIEW_MS = 30000;
5958
6242
  var INSTALL_MS = 15 * 60000;
@@ -5980,19 +6264,19 @@ var unsupported = () => ({
5980
6264
  });
5981
6265
  function sameCopy(modules, root) {
5982
6266
  try {
5983
- const path2 = join14(modules, ...PACKAGE.split("/"));
5984
- return !lstatSync8(path2).isSymbolicLink() && realpathSync5(path2) === realpathSync5(root) && realpathSync5(path2) === join14(realpathSync5(modules), ...PACKAGE.split("/"));
6267
+ const path2 = join15(modules, ...PACKAGE.split("/"));
6268
+ return !lstatSync9(path2).isSymbolicLink() && realpathSync5(path2) === realpathSync5(root) && realpathSync5(path2) === join15(realpathSync5(modules), ...PACKAGE.split("/"));
5985
6269
  } catch {
5986
6270
  return false;
5987
6271
  }
5988
6272
  }
5989
6273
  function prefixManager(prefix) {
5990
- const npm = existsSync3(join14(prefix, "package-lock.json")) || existsSync3(join14(prefix, "npm-shrinkwrap.json"));
5991
- const bun = existsSync3(join14(prefix, "bun.lock")) || existsSync3(join14(prefix, "bun.lockb"));
6274
+ const npm = existsSync3(join15(prefix, "package-lock.json")) || existsSync3(join15(prefix, "npm-shrinkwrap.json"));
6275
+ const bun = existsSync3(join15(prefix, "bun.lock")) || existsSync3(join15(prefix, "bun.lockb"));
5992
6276
  return npm === bun ? undefined : bun ? "bun" : "npm";
5993
6277
  }
5994
6278
  function writable(installation, modules, root) {
5995
- if (installation.manager === "bun" && [".npmrc", "bunfig.toml", ".bunfig.toml"].some((name) => existsSync3(join14(installation.prefix, name))))
6279
+ if (installation.manager === "bun" && [".npmrc", "bunfig.toml", ".bunfig.toml"].some((name) => existsSync3(join15(installation.prefix, name))))
5996
6280
  return unsupported();
5997
6281
  try {
5998
6282
  for (const path2 of [installation.prefix, modules, dirname10(root), root])
@@ -6004,18 +6288,18 @@ function writable(installation, modules, root) {
6004
6288
  "bun.lock",
6005
6289
  "bun.lockb"
6006
6290
  ])
6007
- if (existsSync3(join14(installation.prefix, name)))
6008
- accessSync(join14(installation.prefix, name), constants4.W_OK);
6291
+ if (existsSync3(join15(installation.prefix, name)))
6292
+ accessSync(join15(installation.prefix, name), constants4.W_OK);
6009
6293
  return installation;
6010
6294
  } catch {
6011
6295
  return { route: "not-writable" };
6012
6296
  }
6013
6297
  }
6014
6298
  async function installation(s, commands) {
6015
- const agent = agentDirectory(s), piPrefix = join14(agent, "npm");
6016
- if (sameCopy(join14(piPrefix, "node_modules"), s.root)) {
6299
+ const agent = agentDirectory(s), piPrefix = join15(agent, "npm");
6300
+ if (sameCopy(join15(piPrefix, "node_modules"), s.root)) {
6017
6301
  try {
6018
- const settings2 = JSON.parse(readFileSync3(join14(agent, "settings.json"), "utf8"));
6302
+ const settings2 = JSON.parse(readFileSync3(join15(agent, "settings.json"), "utf8"));
6019
6303
  if (!settings2 || !Array.isArray(settings2.packages))
6020
6304
  return unsupported();
6021
6305
  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}@`)));
@@ -6031,7 +6315,7 @@ async function installation(s, commands) {
6031
6315
  route: manager === "npm" ? "pi-npm" : "pi-bun",
6032
6316
  manager,
6033
6317
  prefix: piPrefix
6034
- }, join14(piPrefix, "node_modules"), s.root);
6318
+ }, join15(piPrefix, "node_modules"), s.root);
6035
6319
  } catch {
6036
6320
  return unsupported();
6037
6321
  }
@@ -6039,27 +6323,27 @@ async function installation(s, commands) {
6039
6323
  const localModules = dirname10(dirname10(s.root)), local = dirname10(localModules);
6040
6324
  const manifest = (() => {
6041
6325
  try {
6042
- return JSON.parse(readFileSync3(join14(local, "package.json"), "utf8"));
6326
+ return JSON.parse(readFileSync3(join15(local, "package.json"), "utf8"));
6043
6327
  } catch {
6044
6328
  return;
6045
6329
  }
6046
6330
  })();
6047
- if (manifest?.name === "pi-extensions" || basename2(dirname10(local)) === ".pi" || basename2(local) === "npm" && existsSync3(join14(dirname10(local), "settings.json")))
6331
+ if (manifest?.name === "pi-extensions" || basename2(dirname10(local)) === ".pi" || basename2(local) === "npm" && existsSync3(join15(dirname10(local), "settings.json")))
6048
6332
  return unsupported();
6049
6333
  const bun = await commands.bun(["pm", "ls", "--global"]);
6050
6334
  const bunPrefix = bun.status === 0 ? /^(\/[^\r\n]+) node_modules(?: \(\d+(?: installed)?\))?\r?$/.exec(bun.stdout.split(`
6051
6335
  `)[0])?.[1] : undefined;
6052
- if (bunPrefix && sameCopy(join14(bunPrefix, "node_modules"), s.root)) {
6336
+ if (bunPrefix && sameCopy(join15(bunPrefix, "node_modules"), s.root)) {
6053
6337
  const manager = prefixManager(bunPrefix);
6054
6338
  if (manager === "bun")
6055
- return writable({ route: "bun", manager: "bun", prefix: bunPrefix }, join14(bunPrefix, "node_modules"), s.root);
6339
+ return writable({ route: "bun", manager: "bun", prefix: bunPrefix }, join15(bunPrefix, "node_modules"), s.root);
6056
6340
  if (!manager)
6057
6341
  return unsupported();
6058
6342
  }
6059
6343
  const npm = await commands.npm(["root", "--global"]);
6060
6344
  const modules = npm.status === 0 ? npm.stdout.trim() : "";
6061
6345
  const prefix = dirname10(dirname10(modules));
6062
- if (isAbsolute7(modules) && modules === join14(prefix, "lib", "node_modules") && sameCopy(modules, s.root))
6346
+ if (isAbsolute8(modules) && modules === join15(prefix, "lib", "node_modules") && sameCopy(modules, s.root))
6063
6347
  return writable({ route: "npm", manager: "npm", prefix }, modules, s.root);
6064
6348
  if (basename2(localModules) !== "node_modules" || !sameCopy(localModules, s.root))
6065
6349
  return unsupported();
@@ -6124,9 +6408,9 @@ async function fetchVersions(i, versions, commands) {
6124
6408
  })).status !== 0)
6125
6409
  return false;
6126
6410
  } else {
6127
- const stage = mkdtempSync(join14(tmpdir(), "cadence-upgrade-"));
6411
+ const stage = mkdtempSync(join15(tmpdir(), "cadence-upgrade-"));
6128
6412
  try {
6129
- writeFileSync4(join14(stage, "package.json"), JSON.stringify({ private: true }));
6413
+ writeFileSync4(join15(stage, "package.json"), JSON.stringify({ private: true }));
6130
6414
  if ((await commands.bun([
6131
6415
  "add",
6132
6416
  "--cwd",
@@ -6150,12 +6434,12 @@ async function fetchVersions(i, versions, commands) {
6150
6434
 
6151
6435
  // src/service/launchd.ts
6152
6436
  import { rmSync as rmSync5 } from "node:fs";
6153
- import { dirname as dirname11, join as join15 } from "node:path";
6437
+ import { dirname as dirname11, join as join16 } from "node:path";
6154
6438
  var LABEL = "com.abelxiaoxing.cadence";
6155
6439
  var MARKER2 = `<?xml version="1.0" encoding="UTF-8"?>
6156
6440
  <!-- Generated by @abelxiaoxing/cadence`;
6157
6441
  function plistPath(s) {
6158
- return join15(s.home, "Library", "LaunchAgents", `${LABEL}.plist`);
6442
+ return join16(s.home, "Library", "LaunchAgents", `${LABEL}.plist`);
6159
6443
  }
6160
6444
  var xml = (value) => checked(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
6161
6445
  function buildPlist(u) {
@@ -6235,11 +6519,11 @@ async function configureLaunchAgent(s, mode, requested) {
6235
6519
  s.launchctl(["bootout", target(s)]);
6236
6520
  write(path2, buildPlist({
6237
6521
  node: s.node,
6238
- cli: join15(s.root, "src", "service-cli.mjs"),
6522
+ cli: join16(s.root, "src", "service-cli.mjs"),
6239
6523
  workspace,
6240
6524
  serverConfig: serverConfigPath(s.home),
6241
6525
  environment: serviceEnvironment(s),
6242
- log: join15(s.home, "Library", "Logs", "cadence.log")
6526
+ log: join16(s.home, "Library", "Logs", "cadence.log")
6243
6527
  }));
6244
6528
  const result = {
6245
6529
  unit: path2,
@@ -6250,7 +6534,7 @@ async function configureLaunchAgent(s, mode, requested) {
6250
6534
  s.launchctl(["enable", target(s)]);
6251
6535
  else if (disabled(s))
6252
6536
  return { status: "disabled", ...result };
6253
- if (workspace !== null && !regularFile(join15(agentDirectory(s), "auth.json")))
6537
+ if (workspace !== null && !regularFile(join16(agentDirectory(s), "auth.json")))
6254
6538
  return { status: "waiting-for-pi-login", ...result };
6255
6539
  const started = s.launchctl(["bootstrap", domain(s), path2]).status === 0;
6256
6540
  return { status: started ? "started" : "failed", ...result };
@@ -6299,14 +6583,14 @@ function launchAgentStatus(s) {
6299
6583
 
6300
6584
  // src/service/login-run.ts
6301
6585
  import { rmSync as rmSync6 } from "node:fs";
6302
- import { dirname as dirname12, isAbsolute as isAbsolute8, join as join16 } from "node:path";
6586
+ import { dirname as dirname12, isAbsolute as isAbsolute9, join as join17 } from "node:path";
6303
6587
  var RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
6304
6588
  var APPROVED_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run";
6305
6589
  var RUN_VALUE = "Cadence";
6306
6590
  var MARKER3 = "' Generated by @abelxiaoxing/cadence";
6307
6591
  function launcherPath(s) {
6308
6592
  const local = s.env.LOCALAPPDATA;
6309
- return join16(local && isAbsolute8(local) ? local : join16(s.home, "AppData", "Local"), "cadence-server", "cadence.vbs");
6593
+ return join17(local && isAbsolute9(local) ? local : join17(s.home, "AppData", "Local"), "cadence-server", "cadence.vbs");
6310
6594
  }
6311
6595
  var literal2 = (value) => `"${checked(value).replaceAll('"', '""')}"`;
6312
6596
  function argument2(value) {
@@ -6362,7 +6646,7 @@ async function configureLoginRun(s, mode, requested) {
6362
6646
  const environment = s.env.PI_CODING_AGENT_DIR ? [["PI_CODING_AGENT_DIR", agentDirectory(s)]] : [];
6363
6647
  write(path2, utf16(buildLauncher({
6364
6648
  node: s.node,
6365
- cli: join16(s.root, "src", "service-cli.mjs"),
6649
+ cli: join17(s.root, "src", "service-cli.mjs"),
6366
6650
  workspace,
6367
6651
  serverConfig: serverConfigPath(s.home),
6368
6652
  environment
@@ -6378,7 +6662,7 @@ async function configureLoginRun(s, mode, requested) {
6378
6662
  return { status: "failed", ...result };
6379
6663
  s.reg(["delete", APPROVED_KEY, "/v", RUN_VALUE, "/f"]);
6380
6664
  }
6381
- if (workspace !== null && !regularFile(join16(agentDirectory(s), "auth.json")))
6665
+ if (workspace !== null && !regularFile(join17(agentDirectory(s), "auth.json")))
6382
6666
  return { status: "waiting-for-pi-login", ...result };
6383
6667
  return { status: s.launch(path2) ? "started" : "failed", ...result };
6384
6668
  }
@@ -6429,7 +6713,7 @@ async function loginRunStatus(s) {
6429
6713
  // src/service/maintenance.ts
6430
6714
  import { spawn as spawn2, spawnSync as spawnSync4 } from "node:child_process";
6431
6715
  import { readFileSync as readFileSync4 } from "node:fs";
6432
- import { join as join17 } from "node:path";
6716
+ import { join as join18 } from "node:path";
6433
6717
  var RESTART_MS = 5 * 60000;
6434
6718
  function cgroupPath(text2) {
6435
6719
  const lines = text2?.split(`
@@ -6447,7 +6731,7 @@ function insideUnit(s) {
6447
6731
  return unit !== "" && (own === unit || own.startsWith(`${unit}/`));
6448
6732
  }
6449
6733
  function installedVersion(root) {
6450
- const value = JSON.parse(readFileSync4(join17(root, "package.json"), "utf8"));
6734
+ const value = JSON.parse(readFileSync4(join18(root, "package.json"), "utf8"));
6451
6735
  if (!value || typeof value !== "object" || !("name" in value))
6452
6736
  throw new ContractError("invalid");
6453
6737
  literal(value.name, PACKAGE);
@@ -6539,7 +6823,7 @@ function releaseForInstallation(selected, commands, spec) {
6539
6823
  async function restartInstalled(s) {
6540
6824
  const name = serviceName(s);
6541
6825
  const result = await run(s.node, [
6542
- join17(s.root, "src", "service-cli.mjs"),
6826
+ join18(s.root, "src", "service-cli.mjs"),
6543
6827
  "server",
6544
6828
  "restart",
6545
6829
  s.scope === "system" ? "--system" : "--user",
@@ -6625,7 +6909,7 @@ function jobOutcome(action, result) {
6625
6909
 
6626
6910
  // src/service/system-service.ts
6627
6911
  import { existsSync as existsSync4, realpathSync as realpathSync6, rmSync as rmSync7 } from "node:fs";
6628
- import { isAbsolute as isAbsolute9, join as join18 } from "node:path";
6912
+ import { isAbsolute as isAbsolute10, join as join19 } from "node:path";
6629
6913
  var MARKER4 = "# Generated by @abelxiaoxing/cadence";
6630
6914
  function boundary(s) {
6631
6915
  if (s.platform !== "linux" || s.scope !== "system")
@@ -6639,7 +6923,7 @@ function legacyPath(s) {
6639
6923
  function observed(s) {
6640
6924
  const path2 = unitPath(s);
6641
6925
  let previous = readGenerated(path2, MARKER4);
6642
- if (typeof previous === "string" && (unitWorkspace(previous) !== null && !isAbsolute9(unitWorkspace(previous) ?? "") || !previous.includes(`
6926
+ if (typeof previous === "string" && (unitWorkspace(previous) !== null && !isAbsolute10(unitWorkspace(previous) ?? "") || !previous.includes(`
6643
6927
  User=root
6644
6928
  `)))
6645
6929
  previous = null;
@@ -6656,7 +6940,7 @@ function sameStateEnvironment(s, previous) {
6656
6940
  if (values.size !== kept.length)
6657
6941
  return false;
6658
6942
  const state = s.env.XDG_STATE_HOME;
6659
- return values.get("HOME") === s.home && values.get("XDG_STATE_HOME") === (state && isAbsolute9(state) ? state : undefined);
6943
+ return values.get("HOME") === s.home && values.get("XDG_STATE_HOME") === (state && isAbsolute10(state) ? state : undefined);
6660
6944
  } catch {
6661
6945
  return false;
6662
6946
  }
@@ -6699,7 +6983,7 @@ async function configureSystemService(s, mode, requested) {
6699
6983
  const content = buildUnit({
6700
6984
  system: true,
6701
6985
  node: s.node,
6702
- cli: join18(s.root, "src", "service-cli.mjs"),
6986
+ cli: join19(s.root, "src", "service-cli.mjs"),
6703
6987
  workspace: selected.workspace,
6704
6988
  serverConfig: serviceConfigPath(s),
6705
6989
  agentDir,
@@ -6748,7 +7032,7 @@ async function configureSystemService(s, mode, requested) {
6748
7032
  return { status: "failed", ...result, ...selected };
6749
7033
  if (mode === "install" && s.systemctl(["enable", s.unit]).status !== 0)
6750
7034
  return { status: "failed", ...result, ...selected };
6751
- if (selected.workspace !== null && !regularFile(join18(agentDir, "auth.json")))
7035
+ if (selected.workspace !== null && !regularFile(join19(agentDir, "auth.json")))
6752
7036
  return { status: "waiting-for-pi-login", ...result, ...selected };
6753
7037
  s.systemctl(["reset-failed", s.unit]);
6754
7038
  return {
@@ -6817,15 +7101,20 @@ function systemServiceStatus(s) {
6817
7101
  }
6818
7102
 
6819
7103
  // src/service/cli.ts
6820
- function nativeCall(c, operation, reveal = false, controlBody) {
7104
+ function nativeCall(c, operation, reveal = false, controlBody, signal) {
7105
+ if (signal?.aborted)
7106
+ return Promise.reject(new ContractError("unavailable"));
6821
7107
  const access = c.localAccess();
6822
7108
  const url = new URL(`${access.endpoint}/local/v1/admin/${operation}`);
6823
- const write2 = !["status", "diagnose"].includes(operation);
7109
+ const write2 = !["status", "diagnose", "activity"].includes(operation);
7110
+ const maximum = operation === "activity" ? 256 * 1024 : 16384;
6824
7111
  const body = write2 ? JSON.stringify(controlBody ?? (reveal ? { reveal: true } : {})) : undefined;
6825
7112
  return new Promise((resolve8, reject) => {
6826
7113
  let timer;
7114
+ let removeAbort = () => {};
6827
7115
  const fail = () => {
6828
7116
  clearTimeout(timer);
7117
+ removeAbort();
6829
7118
  reject(new ContractError("unavailable"));
6830
7119
  };
6831
7120
  const req = request(url, {
@@ -6845,7 +7134,7 @@ function nativeCall(c, operation, reveal = false, controlBody) {
6845
7134
  res.on("error", fail);
6846
7135
  res.on("data", (chunk) => {
6847
7136
  bytes += chunk.length;
6848
- if (bytes > 16384) {
7137
+ if (bytes > maximum) {
6849
7138
  res.destroy();
6850
7139
  fail();
6851
7140
  } else
@@ -6855,14 +7144,15 @@ function nativeCall(c, operation, reveal = false, controlBody) {
6855
7144
  try {
6856
7145
  if (res.statusCode !== 200)
6857
7146
  throw new ContractError("unavailable");
6858
- const reply = closed(parseWireJson(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)), 16384), ["kind", "value"]);
7147
+ const reply = closed(parseWireJson(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)), maximum), ["kind", "value"]);
6859
7148
  if (reply.kind !== "ok")
6860
7149
  throw new ContractError("unavailable");
6861
- if (["status", "diagnose", "stop"].includes(operation)) {
7150
+ if (["status", "diagnose", "stop", "activity"].includes(operation)) {
6862
7151
  if (!reply.value || typeof reply.value !== "object" || !("epoch" in reply.value) || reply.value.epoch !== access.epoch)
6863
7152
  throw new ContractError("stale");
6864
7153
  }
6865
7154
  clearTimeout(timer);
7155
+ removeAbort();
6866
7156
  resolve8(reply.value);
6867
7157
  } catch {
6868
7158
  fail();
@@ -6873,9 +7163,18 @@ function nativeCall(c, operation, reveal = false, controlBody) {
6873
7163
  fail();
6874
7164
  req.destroy();
6875
7165
  }, 2000);
7166
+ const cancel = () => {
7167
+ fail();
7168
+ req.destroy();
7169
+ };
7170
+ signal?.addEventListener("abort", cancel, { once: true });
7171
+ removeAbort = () => signal?.removeEventListener("abort", cancel);
6876
7172
  req.on("error", fail);
6877
7173
  req.on("close", fail);
6878
- req.end(body);
7174
+ if (signal?.aborted)
7175
+ cancel();
7176
+ else
7177
+ req.end(body);
6879
7178
  });
6880
7179
  }
6881
7180
  var pause = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
@@ -6988,10 +7287,10 @@ function startupGuidance(result, input) {
6988
7287
  return `Pi's agent directory ${agent} must be an existing real directory (not a symlink) owned by you.
6989
7288
  `;
6990
7289
  case "pi-auth":
6991
- return `${join19(agent, "auth.json")} must be your own single-link regular file holding valid Pi credentials; log in to Pi first.
7290
+ return `${join20(agent, "auth.json")} must be your own single-link regular file holding valid Pi credentials; log in to Pi first.
6992
7291
  `;
6993
7292
  case "pi-models":
6994
- return `${join19(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.
7293
+ 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.
6995
7294
  `;
6996
7295
  case "pi-runtime":
6997
7296
  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.
@@ -7228,7 +7527,7 @@ function upgrade(s, to) {
7228
7527
  });
7229
7528
  }
7230
7529
  function serverGuidance(s, action, result, link) {
7231
- const cli = piUserInstall(s) ? `node ${JSON.stringify(join19(s.root, "src", "service-cli.mjs"))}` : "cadence";
7530
+ const cli = piUserInstall(s) ? `node ${JSON.stringify(join20(s.root, "src", "service-cli.mjs"))}` : "cadence";
7232
7531
  const note = result.redirectedFrom ? `Cadence workspace: ${result.workspace} (${result.redirectedFrom} contains Cadence's private state)
7233
7532
  ` : "";
7234
7533
  return note + serverStatusGuidance(s, action, result, cli, link);
@@ -7335,7 +7634,7 @@ ${manage}
7335
7634
  ${linger}`;
7336
7635
  }
7337
7636
  case "waiting-for-pi-login":
7338
- return `Cadence is registered for ${result.workspace}; it starts once Pi has ${join19(agentDirectory(s), "auth.json")}.
7637
+ return `Cadence is registered for ${result.workspace}; it starts once Pi has ${join20(agentDirectory(s), "auth.json")}.
7339
7638
  Log in to Pi, then: ${cli} server restart${flags}
7340
7639
  ${config}
7341
7640
  ${lingerGuidance(result.linger)}`;