pi-web-ui 0.115.0 → 0.117.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +65 -2
  2. package/bin/device-hub-cli.mjs +26 -3
  3. package/bin/pi-web-ui.mjs +159 -71
  4. package/dist/server/agent-service-daemon.js +136 -8
  5. package/dist/server/agent-service.js +594 -159
  6. package/dist/server/canvas/canvas-workspace.js +18 -86
  7. package/dist/server/client-state.js +52 -8
  8. package/dist/server/compaction-markers.js +43 -24
  9. package/dist/server/dangling-tools.js +172 -16
  10. package/dist/server/device-center/bot-execution.js +77 -2
  11. package/dist/server/device-center/collab-service.js +61 -12
  12. package/dist/server/device-center/collab-tool.js +482 -21
  13. package/dist/server/device-center/connector.js +107 -37
  14. package/dist/server/device-center/delivery-authority.js +98 -0
  15. package/dist/server/device-center/delivery-subject.js +30 -0
  16. package/dist/server/device-center/device-integration.js +453 -183
  17. package/dist/server/device-center/execution-guides.js +17 -7
  18. package/dist/server/device-center/execution-instructions.js +2 -1
  19. package/dist/server/device-center/execution-settings.js +138 -25
  20. package/dist/server/device-center/executor.js +51 -6
  21. package/dist/server/device-center/file-sync.js +14 -13
  22. package/dist/server/device-center/group-context-message.js +3 -1
  23. package/dist/server/device-center/group-context.js +73 -3
  24. package/dist/server/device-center/hub-conversations.js +71 -6
  25. package/dist/server/device-center/hub-deliveries.js +120 -15
  26. package/dist/server/device-center/hub-integration.js +655 -334
  27. package/dist/server/device-center/hub-locks.js +320 -0
  28. package/dist/server/device-center/hub-page.js +16 -35
  29. package/dist/server/device-center/hub-setup.js +23 -1
  30. package/dist/server/device-center/hub-transaction-log.js +197 -0
  31. package/dist/server/device-center/hub-webhooks.js +165 -0
  32. package/dist/server/device-center/hub.js +1531 -305
  33. package/dist/server/device-center/integration-verification.js +113 -0
  34. package/dist/server/device-center/local-hub.js +8 -3
  35. package/dist/server/device-center/local-publication.js +423 -0
  36. package/dist/server/device-center/local-verification-job.js +97 -0
  37. package/dist/server/device-center/local-verification.js +274 -0
  38. package/dist/server/device-center/local.js +181 -13
  39. package/dist/server/device-center/main.js +4 -1
  40. package/dist/server/device-center/partition-log.js +330 -0
  41. package/dist/server/device-center/publication-journal.js +312 -0
  42. package/dist/server/device-center/publish-intent.js +379 -0
  43. package/dist/server/device-center/relay.js +134 -24
  44. package/dist/server/device-center/runtime.js +475 -42
  45. package/dist/server/device-center/store.js +366 -89
  46. package/dist/server/device-center/task-outcome.js +81 -0
  47. package/dist/server/device-center/task-recovery.js +603 -178
  48. package/dist/server/device-center/task-scheduler.js +48 -3
  49. package/dist/server/device-center/task-settlement.js +353 -0
  50. package/dist/server/device-center/task-workspace.js +443 -0
  51. package/dist/server/device-center/transfers.js +41 -15
  52. package/dist/server/device-center/verification-limits.js +10 -0
  53. package/dist/server/device-center/work-contract.js +995 -0
  54. package/dist/server/dispatch-domain-handlers.js +29 -3
  55. package/dist/server/dsh/dsh-agent-service.js +9 -2
  56. package/dist/server/engine-probe.js +112 -1
  57. package/dist/server/global-loader.js +119 -19
  58. package/dist/server/index.js +159 -17
  59. package/dist/server/managed.js +2 -0
  60. package/dist/server/model-admin.js +48 -6
  61. package/dist/server/model-enrich.js +10 -1
  62. package/dist/server/patch-node-pty.js +3 -2
  63. package/dist/server/patch-remote-catalog.js +3 -2
  64. package/dist/server/plugins.js +64 -7
  65. package/dist/server/preset-fields.js +17 -1
  66. package/dist/server/preset-share.js +1 -0
  67. package/dist/server/prompt-composer.js +39 -0
  68. package/dist/server/protocol-version.js +1 -1
  69. package/dist/server/quick-ask-settings.js +28 -0
  70. package/dist/server/quick-ask.js +164 -0
  71. package/dist/server/reasoning-registry.js +207 -0
  72. package/dist/server/resolve-global-sdk.js +61 -11
  73. package/dist/server/scheduler-tasks.js +35 -8
  74. package/dist/server/session-list-scan.js +223 -0
  75. package/dist/server/session-open.js +93 -0
  76. package/dist/server/session-parser.js +4 -0
  77. package/dist/server/session-scan.js +90 -38
  78. package/dist/server/settings-service.js +9 -1
  79. package/dist/server/soft-cap.js +5 -0
  80. package/dist/server/startup-banner.js +35 -0
  81. package/dist/server/subagents.js +2 -1
  82. package/dist/server/tool-manager.js +17 -9
  83. package/dist/server/transcript-prepare.js +73 -0
  84. package/dist/server/unauthorized-page.js +319 -0
  85. package/dist/server/universal/drivers/claude-code.js +98 -34
  86. package/dist/server/universal/universal-session.js +4 -0
  87. package/dist/server/workspace-handle.js +428 -0
  88. package/docs/architecture-plugins.md +959 -0
  89. package/docs/device-center.md +34 -20
  90. package/package.json +4 -4
  91. package/plugin-sdk/README.md +16 -8
  92. package/plugin-sdk/client.d.ts +27 -0
  93. package/plugin-sdk/client.mjs +82 -0
  94. package/plugin-sdk/index.d.ts +10 -0
  95. package/plugin-sdk/index.mjs +4 -683
  96. package/plugin-sdk/package.json +15 -4
  97. package/plugin-sdk/testing.d.ts +10 -0
  98. package/plugin-sdk/testing.mjs +566 -0
  99. package/themes/flow-cristallo.css +168 -0
  100. package/themes/flow-ink.css +169 -0
  101. package/themes/flow-obsidian.css +169 -0
  102. package/themes/flow-zurich.css +169 -0
  103. package/web/dist/.build-assets.json +1 -1
  104. package/web/dist/assets/{BgTasksModal-BYzPgmoq.js → BgTasksModal-BjNRIUIc.js} +1 -1
  105. package/web/dist/assets/{BgTasksModal-ni0VTmAQ.js → BgTasksModal-C0zuU8FE.js} +1 -1
  106. package/web/dist/assets/{CanvasStudio-DNmDNBod.js → CanvasStudio-BWvdmJ0M.js} +3 -3
  107. package/web/dist/assets/{CanvasStudio-BCUeEf25.js → CanvasStudio-VQFjmTGq.js} +3 -3
  108. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
  109. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
  110. package/web/dist/assets/DeviceExecutionSettings-BLP1Su5G.js +1 -0
  111. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
  112. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
  113. package/web/dist/assets/{Dropdown-CGXD0DfT.js → Dropdown-CQtstPGv.js} +1 -1
  114. package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
  115. package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
  116. package/web/dist/assets/{GlobalSearchModal-mevF-ySi.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
  117. package/web/dist/assets/{GlobalSearchModal-qL99FN_F.js → GlobalSearchModal-DGv_WINq.js} +1 -1
  118. package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
  119. package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
  120. package/web/dist/assets/{HintTip-LHwkS2jV.js → HintTip-ChTW8o1m.js} +1 -1
  121. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
  122. package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
  123. package/web/dist/assets/{PiSetupModal-DE5-gEtI.js → PiSetupModal-BX5rUuoI.js} +1 -1
  124. package/web/dist/assets/{ProviderOAuthControls-6UMARucA.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
  125. package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
  126. package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
  127. package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
  128. package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
  129. package/web/dist/assets/{TerminalPanel-CTp_BZ4S.js → TerminalPanel-D4By_RVc.js} +2 -2
  130. package/web/dist/assets/{TerminalPanel-CkYxC-Gh.js → TerminalPanel-lZw8-i3j.js} +2 -2
  131. package/web/dist/assets/{TuiOverlayModal-1cRLP8IF.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
  132. package/web/dist/assets/{TuiOverlayModal-2xlptqWX.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
  133. package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
  134. package/web/dist/assets/{canvas-client-Bye9nSFO.js → canvas-client-BY6ojmle.js} +1 -1
  135. package/web/dist/assets/{desktop-kjBoE3Nu.js → desktop-CV6KKp9R.js} +1 -1
  136. package/web/dist/assets/index-BawF7ZP5.js +397 -0
  137. package/web/dist/assets/index-BoGCoq5X.js +397 -0
  138. package/web/dist/assets/index-CVW9FoY2.css +1 -0
  139. package/web/dist/assets/{plugin-host-C8mNgghx.js → plugin-host-Dn8Dd6SC.js} +1 -1
  140. package/web/dist/assets/{remote-ssh-client-CeP3CLUW.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
  141. package/web/dist/assets/{theme-BXGpyTMh.js → theme-D_bihpdN.js} +1 -1
  142. package/web/dist/index.html +11 -11
  143. package/web/dist/sw.js +1 -1
  144. package/dist/server/patch-turn-end-boundary.js +0 -77
  145. package/web/dist/assets/DeviceCenter-BcBhRgL6.js +0 -3
  146. package/web/dist/assets/DeviceCenter-CmL5FZmt.js +0 -3
  147. package/web/dist/assets/DeviceGroups-CLdpdnI7.js +0 -1
  148. package/web/dist/assets/DeviceGroups-CgBaDPrD.js +0 -1
  149. package/web/dist/assets/FilePreview-B8iqnBjy.js +0 -2
  150. package/web/dist/assets/FilePreview-BqviZKCN.js +0 -2
  151. package/web/dist/assets/GroupConversation-B88Yy-lt.js +0 -3
  152. package/web/dist/assets/GroupConversation-BwP5NVOE.js +0 -3
  153. package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +0 -2
  154. package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +0 -2
  155. package/web/dist/assets/SCMPanel-ezY_ZtCu.js +0 -2
  156. package/web/dist/assets/SettingsModal-6HgeEsJ8.js +0 -20
  157. package/web/dist/assets/SettingsModal-CF-7MwqS.js +0 -20
  158. package/web/dist/assets/app-globals-DZNa9v8u.js +0 -325
  159. package/web/dist/assets/index-CsFs_HMb.css +0 -1
  160. package/web/dist/assets/index-DHeeHS_l.js +0 -85
  161. package/web/dist/assets/index-DTZch8uz.js +0 -85
@@ -8,6 +8,7 @@
8
8
  * 4. 无缝复用宿主 FilesService(文件树/预览/SCM/上传)、TerminalManager(终端)与 BgServerTracker(后台服务)。
9
9
  */
10
10
  import { startTurnTiming, finishTurnTiming } from "../turn-timing.js";
11
+ import { normalizeQuickAskSettings } from "../quick-ask-settings.js";
11
12
  import { randomUUID } from "node:crypto";
12
13
  import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
13
14
  import { homedir } from "node:os";
@@ -1993,6 +1994,7 @@ export class UniversalSession {
1993
1994
  pushSettings() {
1994
1995
  const s = this.stateStore?.getSettings(this.clientId);
1995
1996
  const settings = {
1997
+ ...normalizeQuickAskSettings(s ?? {}),
1996
1998
  steeringMode: s?.steeringMode ?? "all",
1997
1999
  followUpMode: s?.followUpMode ?? "all",
1998
2000
  promptMode: s?.promptMode ?? "append",
@@ -2016,6 +2018,7 @@ export class UniversalSession {
2016
2018
  retryMaxAttempts: 0,
2017
2019
  softCapTokens: 0,
2018
2020
  softCapByModel: {},
2021
+ autoCompactionInstructions: "",
2019
2022
  questionnaireEnabled: false,
2020
2023
  toolApprovalEnabled: true,
2021
2024
  approvalPolicy: { allowAll: false, categories: [] },
@@ -2223,6 +2226,7 @@ export class UniversalSession {
2223
2226
  retryMaxAttempts: s.retryMaxAttempts,
2224
2227
  softCapTokens: s.softCapTokens,
2225
2228
  softCapByModel: s.softCapByModel,
2229
+ autoCompactionInstructions: s.autoCompactionInstructions ?? "",
2226
2230
  });
2227
2231
  this.stateStore.savePresets(this.clientId, filtered);
2228
2232
  this.pushSettings();
@@ -0,0 +1,428 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { lstat, mkdir, readFile, readlink, realpath, rm } from "node:fs/promises";
4
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ export function checkSignal(signal) {
6
+ signal?.throwIfAborted();
7
+ }
8
+ export function safeId(value, context = "workspace") {
9
+ if (!/^[a-zA-Z0-9_-][a-zA-Z0-9_.-]{0,127}$/.test(value) || value === "." || value === "..") {
10
+ throw new Error(`Invalid ${context} identifier: ${value}`);
11
+ }
12
+ return value;
13
+ }
14
+ export function inside(root, path) {
15
+ const rel = relative(root, path);
16
+ return !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
17
+ }
18
+ function quoteGitPath(path) {
19
+ return `"${path.replace(/[\\"\x00-\x1f\x7f]/g, (character) => character === "\\" || character === '"'
20
+ ? `\\${character}`
21
+ : `\\${character.charCodeAt(0).toString(8).padStart(3, "0")}`)}"`;
22
+ }
23
+ export async function canonicalPath(path) {
24
+ try {
25
+ return await realpath(path);
26
+ }
27
+ catch (error) {
28
+ if (error.code !== "ENOENT")
29
+ throw error;
30
+ const parent = resolve(path, "..");
31
+ if (parent === path)
32
+ throw error;
33
+ return join(await canonicalPath(parent), relative(parent, path));
34
+ }
35
+ }
36
+ /**
37
+ * Execute Git asynchronously with isolated environment, no hooks, and strict timeout.
38
+ * Strips any inherited GIT_* environment variables to prevent leaking caller context.
39
+ */
40
+ export async function git(cwd, args, signal, index, input) {
41
+ checkSignal(signal);
42
+ const env = { ...process.env };
43
+ for (const key of Object.keys(env)) {
44
+ if (/^GIT_/i.test(key))
45
+ delete env[key];
46
+ }
47
+ if (index)
48
+ env.GIT_INDEX_FILE = index;
49
+ const execute = (command, stdin, overrides = []) => new Promise((done, reject) => {
50
+ const child = execFile("git", [
51
+ "-c",
52
+ "core.hooksPath=/dev/null",
53
+ "-c",
54
+ "core.fsmonitor=false",
55
+ "-c",
56
+ "core.longpaths=true",
57
+ "-c",
58
+ "commit.gpgsign=false",
59
+ ...overrides,
60
+ ...command,
61
+ ], {
62
+ cwd,
63
+ signal,
64
+ windowsHide: true,
65
+ timeout: 60_000,
66
+ maxBuffer: 64 * 1024 * 1024,
67
+ env,
68
+ }, (error, stdout) => (error ? reject(error) : done(stdout)));
69
+ child.stdin?.on("error", () => {
70
+ /* execFile reports process failure */
71
+ });
72
+ child.stdin?.end(stdin);
73
+ });
74
+ // Inspect all config scopes and disable every configured command filter.
75
+ // This includes globally installed LFS; snapshots contain exact local bytes.
76
+ let filters;
77
+ try {
78
+ filters = await execute(["config", "--null", "--get-regexp", "^filter\\..*\\.(clean|smudge|process)$"]);
79
+ }
80
+ catch (error) {
81
+ checkSignal(signal);
82
+ if (error.code !== 1)
83
+ throw error;
84
+ filters = "";
85
+ }
86
+ const drivers = new Set(filters
87
+ .split("\0")
88
+ .filter(Boolean)
89
+ .map((entry) => entry.slice(0, entry.indexOf("\n")).replace(/\.(clean|smudge|process)$/, "")));
90
+ const overrides = [...drivers].flatMap((driver) => ["clean", "smudge", "process", "required"].flatMap((setting) => [
91
+ "-c",
92
+ `${driver}.${setting}=${setting === "required" ? "false" : ""}`,
93
+ ]));
94
+ const stdout = await execute(args, input, overrides);
95
+ checkSignal(signal);
96
+ return stdout;
97
+ }
98
+ /**
99
+ * Build a Git tree without touching the user's index, branch, or commit history.
100
+ * Uses a scratch index in dataDir. Gitignored files are excluded.
101
+ */
102
+ export async function snapshotTree(cwd, dataDir, signal, namespace = join("canvas", "indexes"), seed = "HEAD") {
103
+ if (seed !== "HEAD" &&
104
+ (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(seed) ||
105
+ (await git(cwd, ["cat-file", "-t", seed], signal)).trim() !== "tree"))
106
+ throw new Error("Snapshot seed must be HEAD or a Git tree object ID");
107
+ const scratch = join(resolve(dataDir), namespace);
108
+ await mkdir(scratch, { recursive: true });
109
+ const index = join(scratch, randomUUID());
110
+ try {
111
+ // Hash exact bytes, never `git add`: attributes (text/eol/ident/encoding)
112
+ // otherwise silently change the contents of a captured artifact.
113
+ await git(cwd, ["read-tree", seed], signal, index);
114
+ const tracked = await git(cwd, ["ls-files", "--stage", "-z"], signal, index);
115
+ const files = new Map();
116
+ for (const entry of tracked.split("\0").filter(Boolean)) {
117
+ const match = /^(\d+) ([a-f0-9]+) (\d)\t([\s\S]+)$/.exec(entry);
118
+ if (!match || match[3] !== "0")
119
+ throw new Error("Cannot snapshot an unmerged Git index");
120
+ files.set(match[4], { mode: match[1], oid: match[2] });
121
+ }
122
+ const untracked = await git(cwd, ["ls-files", "--others", "--exclude-standard", "-z"], signal, index);
123
+ for (const path of untracked.split("\0").filter(Boolean))
124
+ files.set(path, { mode: "100644", oid: "" });
125
+ let filemode = "true";
126
+ try {
127
+ filemode = (await git(cwd, ["config", "--get", "core.filemode"], signal)).trim();
128
+ }
129
+ catch (error) {
130
+ checkSignal(signal);
131
+ if (error.code !== 1)
132
+ throw error;
133
+ }
134
+ const entries = [];
135
+ const rawFiles = [];
136
+ for (const [path, original] of files) {
137
+ checkSignal(signal);
138
+ const absolute = join(cwd, path);
139
+ const parent = resolve(absolute, "..");
140
+ if ((await canonicalPath(parent)) !== parent)
141
+ throw new Error(`Snapshot path is redirected: ${path}`);
142
+ const stat = await lstat(absolute).catch((error) => {
143
+ if (error.code === "ENOENT")
144
+ return undefined;
145
+ throw error;
146
+ });
147
+ if (!stat)
148
+ continue;
149
+ let mode = original.mode;
150
+ let oid;
151
+ if (mode === "160000" && stat.isDirectory()) {
152
+ // Snapshot only the gitlink, never submodule contents. Uninitialized
153
+ // submodules resolve to the parent repository and retain their base oid.
154
+ const [top, head] = (await git(absolute, ["rev-parse", "--show-toplevel", "HEAD"], signal))
155
+ .trim()
156
+ .split(/\r?\n/);
157
+ oid = (await canonicalPath(top)) === absolute ? head : original.oid;
158
+ }
159
+ else {
160
+ if (!stat.isFile() && !stat.isSymbolicLink())
161
+ throw new Error(`Unsupported snapshot file: ${path}`);
162
+ mode = stat.isSymbolicLink()
163
+ ? "120000"
164
+ : filemode === "false"
165
+ ? mode === "100755"
166
+ ? mode
167
+ : "100644"
168
+ : stat.mode & 0o111
169
+ ? "100755"
170
+ : "100644";
171
+ if (!stat.isSymbolicLink()) {
172
+ rawFiles.push({ path, absolute, mode });
173
+ continue;
174
+ }
175
+ const bytes = Buffer.from(await readlink(absolute));
176
+ oid = (await git(cwd, ["hash-object", "-w", "--no-filters", "--stdin"], signal, undefined, bytes)).trim();
177
+ }
178
+ entries.push(`${mode} ${oid}\t${path}\0`);
179
+ }
180
+ // One Git process hashes the ordinary files. C-quoted paths support spaces,
181
+ // tabs and newlines without passing filenames through a shell.
182
+ if (rawFiles.length) {
183
+ const paths = rawFiles
184
+ .map(({ absolute }) => quoteGitPath(sep === "\\" ? absolute.replace(/\\/g, "/") : absolute))
185
+ .join("\n") + "\n";
186
+ const oids = (await git(cwd, ["hash-object", "-w", "--no-filters", "--stdin-paths"], signal, undefined, Buffer.from(paths)))
187
+ .trim()
188
+ .split(/\r?\n/);
189
+ if (oids.length !== rawFiles.length)
190
+ throw new Error("Incomplete raw Git snapshot");
191
+ for (const [i, file] of rawFiles.entries())
192
+ entries.push(`${file.mode} ${oids[i]}\t${file.path}\0`);
193
+ }
194
+ await git(cwd, ["read-tree", "--empty"], signal, index);
195
+ await git(cwd, ["update-index", "-z", "--index-info"], signal, index, Buffer.from(entries.join("")));
196
+ return (await git(cwd, ["write-tree"], signal, index)).trim();
197
+ }
198
+ finally {
199
+ await rm(index, { force: true });
200
+ await rm(`${index}.lock`, { force: true });
201
+ }
202
+ }
203
+ /**
204
+ * Verifies that candidatePath is a valid local Git repository and returns its canonical root.
205
+ */
206
+ export async function verifyRepoRoot(candidatePath, signal) {
207
+ checkSignal(signal);
208
+ const canonical = await canonicalPath(resolve(candidatePath));
209
+ let top;
210
+ try {
211
+ top = (await git(canonical, ["rev-parse", "--show-toplevel"], signal)).trim();
212
+ }
213
+ catch (error) {
214
+ checkSignal(signal);
215
+ throw new Error(`Directory is not a Git repository: ${candidatePath}`, { cause: error });
216
+ }
217
+ const canonicalTop = await canonicalPath(top);
218
+ const common = (await git(canonicalTop, ["rev-parse", "--path-format=absolute", "--git-common-dir"], signal)).trim();
219
+ const canonicalCommon = await canonicalPath(common);
220
+ return { repoRoot: canonicalTop, commonDir: canonicalCommon };
221
+ }
222
+ /**
223
+ * Network remote identity: preserve case-sensitive paths and strip credentials.
224
+ * Default-port SSH/SCP and HTTPS share host/path identity; other transports,
225
+ * local paths and file URLs are rejected rather than advertised across devices.
226
+ * No URL redirects, host aliases, percent-decoding or path case-folding is inferred.
227
+ */
228
+ export function canonicalRemoteIdentity(remote) {
229
+ const value = remote.trim();
230
+ let host;
231
+ let path;
232
+ let transport = "hosted";
233
+ if (value.includes("://")) {
234
+ const url = new URL(value);
235
+ if (!["ssh:", "https:", "http:", "git:"].includes(url.protocol) || url.search || url.hash) {
236
+ throw new Error("Unsupported repository remote identity transport or query/fragment");
237
+ }
238
+ host = url.hostname.toLowerCase();
239
+ path = url.pathname;
240
+ const defaultPort = { "ssh:": "22", "https:": "443", "http:": "80", "git:": "9418" }[url.protocol];
241
+ if (url.port && url.port !== defaultPort)
242
+ transport = `${url.protocol}${url.port}`;
243
+ else if (url.protocol !== "ssh:" && url.protocol !== "https:")
244
+ transport = url.protocol;
245
+ }
246
+ else {
247
+ const match = /^(?:[^@/\s]+@)?(\[[^\]]+\]|[^:/\\\s]+):(.+)$/.exec(value);
248
+ if (!match || /^[a-zA-Z]:/.test(value) || /^[a-zA-Z][a-zA-Z0-9+.-]*::/.test(value))
249
+ throw new Error("Unsupported local repository remote identity");
250
+ host = match[1].toLowerCase();
251
+ path = match[2];
252
+ }
253
+ path = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "");
254
+ if (!host || !path || path.split("/").some((part) => part === "." || part === "..")) {
255
+ throw new Error("Invalid repository remote identity path");
256
+ }
257
+ return JSON.stringify([transport, host, path]);
258
+ }
259
+ /** Public discovery API. Remote-less identity hashes all sorted reachable root commits, never local paths. */
260
+ export async function computeCanonicalRepositoryId(repoRoot, signal) {
261
+ checkSignal(signal);
262
+ const canonical = await canonicalPath(resolve(repoRoot));
263
+ let remote = "";
264
+ try {
265
+ remote = (await git(canonical, ["config", "--get", "remote.origin.url"], signal)).trim();
266
+ }
267
+ catch (error) {
268
+ checkSignal(signal);
269
+ if (error.code !== 1)
270
+ throw error;
271
+ }
272
+ let identity;
273
+ if (remote) {
274
+ identity = `remote:${canonicalRemoteIdentity(remote)}`;
275
+ }
276
+ else {
277
+ const roots = (await git(canonical, ["rev-list", "--max-parents=0", "--all"], signal))
278
+ .trim()
279
+ .split(/\s+/)
280
+ .filter(Boolean)
281
+ .sort();
282
+ if (!roots.length)
283
+ throw new Error("Cannot discover transportable identity for an empty repository without a remote");
284
+ identity = `roots:${[...new Set(roots)].join("\n")}`;
285
+ }
286
+ return `repo-${createHash("sha256").update(identity).digest("hex")}`;
287
+ }
288
+ /**
289
+ * Deeply validates worktree identity:
290
+ * - worktree path is absolute and canonical
291
+ * - show-toplevel matches expected worktree path
292
+ * - git-common-dir matches repoRoot git-common-dir
293
+ * - gitdir file points back to worktree .git
294
+ * - worktree is detached, not attached to any branch
295
+ * - worktree is not the main repository
296
+ * - if expectedGitDir is specified, strictly verifies gitDir matches
297
+ */
298
+ export async function verifyWorktreeIdentity(worktreePath, expectedRepoRoot, signal, expectedGitDir, expectedCommonDir) {
299
+ checkSignal(signal);
300
+ const resolvedWorktree = resolve(worktreePath);
301
+ const canonicalWorktree = await canonicalPath(resolvedWorktree);
302
+ const canonicalRepoRoot = await canonicalPath(resolve(expectedRepoRoot));
303
+ let top;
304
+ try {
305
+ top = (await git(canonicalWorktree, ["rev-parse", "--show-toplevel"], signal)).trim();
306
+ }
307
+ catch (error) {
308
+ throw new Error(`Worktree identity error: directory is not a valid Git worktree (${worktreePath})`, {
309
+ cause: error,
310
+ });
311
+ }
312
+ const canonicalTop = await canonicalPath(top);
313
+ if (canonicalTop !== canonicalWorktree) {
314
+ throw new Error(`Worktree identity mismatch: toplevel (${canonicalTop}) does not match expected (${canonicalWorktree})`);
315
+ }
316
+ const common = (await git(canonicalWorktree, ["rev-parse", "--path-format=absolute", "--git-common-dir"], signal)).trim();
317
+ const canonicalCommon = await canonicalPath(common);
318
+ const sourceCommon = (await git(canonicalRepoRoot, ["rev-parse", "--path-format=absolute", "--git-common-dir"], signal)).trim();
319
+ const canonicalSourceCommon = await canonicalPath(sourceCommon);
320
+ if (expectedCommonDir && canonicalCommon !== expectedCommonDir) {
321
+ throw new Error("Worktree git-common-dir changed since registration");
322
+ }
323
+ if (canonicalCommon !== canonicalSourceCommon) {
324
+ throw new Error("Worktree git-common-dir mismatch: worktree does not belong to expected repository");
325
+ }
326
+ const gitDir = (await git(canonicalWorktree, ["rev-parse", "--absolute-git-dir"], signal)).trim();
327
+ const canonicalGitDir = await canonicalPath(gitDir);
328
+ if (canonicalGitDir === canonicalCommon) {
329
+ throw new Error("Worktree identity error: path is the main repository, not an isolated worktree");
330
+ }
331
+ if (!inside(join(canonicalCommon, "worktrees"), canonicalGitDir)) {
332
+ throw new Error("Worktree gitdir is not inside repository worktrees metadata directory");
333
+ }
334
+ if (expectedGitDir) {
335
+ if (canonicalGitDir !== expectedGitDir) {
336
+ throw new Error("Worktree gitdir mismatch: worktree pointer has been substituted");
337
+ }
338
+ }
339
+ const gitdirContent = (await readFile(join(canonicalGitDir, "gitdir"), "utf8")).trim();
340
+ if (resolve(gitdirContent) !== join(canonicalWorktree, ".git")) {
341
+ throw new Error("Worktree gitdir pointer mismatch: .git file redirect is altered");
342
+ }
343
+ // Verify detached HEAD
344
+ const currentBranch = (await git(canonicalWorktree, ["branch", "--show-current"], signal)).trim();
345
+ if (currentBranch.length > 0) {
346
+ throw new Error(`Worktree is attached to branch '${currentBranch}'; detached HEAD is strictly required`);
347
+ }
348
+ const headCommit = (await git(canonicalWorktree, ["rev-parse", "HEAD"], signal)).trim();
349
+ if (!/^[0-9a-fA-F]{40}$/.test(headCommit)) {
350
+ throw new Error(`Worktree HEAD is invalid: ${headCommit}`);
351
+ }
352
+ const status = (await git(canonicalWorktree, ["status", "--porcelain", "--untracked-files=all"], signal)).trim();
353
+ const isClean = status.length === 0;
354
+ return {
355
+ toplevel: canonicalTop,
356
+ commonDir: canonicalCommon,
357
+ gitDir: canonicalGitDir,
358
+ headCommit,
359
+ isClean,
360
+ };
361
+ }
362
+ /**
363
+ * Applies a binary patch to a target worktree using git apply --binary.
364
+ * Validates with --check first.
365
+ */
366
+ export async function applyBinaryPatch(worktreePath, patchBytes, signal) {
367
+ checkSignal(signal);
368
+ if (!patchBytes.length)
369
+ return;
370
+ try {
371
+ await git(worktreePath, ["apply", "--binary", "--check", "-"], signal, undefined, patchBytes);
372
+ await git(worktreePath, ["apply", "--binary", "-"], signal, undefined, patchBytes);
373
+ }
374
+ catch (error) {
375
+ checkSignal(signal);
376
+ throw new Error(`Failed to apply binary patch to worktree ${worktreePath}`, { cause: error });
377
+ }
378
+ }
379
+ /**
380
+ * Verifies with a scratch Git index in repoRoot that applying patchBytes to baseCommit
381
+ * produces exactly the expectedOutputTree.
382
+ */
383
+ export async function verifyPatchProducesTree(repoRoot, baseCommit, patchBytes, expectedOutputTree, dataDir, signal) {
384
+ checkSignal(signal);
385
+ const scratch = join(resolve(dataDir), "task-workspaces", "verify-indexes");
386
+ await mkdir(scratch, { recursive: true });
387
+ const index = join(scratch, randomUUID());
388
+ try {
389
+ await git(repoRoot, ["read-tree", `${baseCommit}^{tree}`], signal, index);
390
+ if (patchBytes.length > 0) {
391
+ await git(repoRoot, ["apply", "--cached", "--binary", "-"], signal, index, patchBytes);
392
+ }
393
+ const computedTree = (await git(repoRoot, ["write-tree"], signal, index)).trim();
394
+ if (computedTree.toLowerCase() !== expectedOutputTree.toLowerCase()) {
395
+ throw new Error(`Artifact patch does not produce declared outputTree: expected ${expectedOutputTree}, computed ${computedTree}`);
396
+ }
397
+ }
398
+ finally {
399
+ await rm(index, { force: true });
400
+ await rm(`${index}.lock`, { force: true });
401
+ }
402
+ }
403
+ /**
404
+ * Creates a detached worktree at worktreePath checked out at baseCommit.
405
+ */
406
+ export async function createDetachedWorktree(repoRoot, worktreePath, baseCommit, signal) {
407
+ checkSignal(signal);
408
+ const resolvedWorktree = resolve(worktreePath);
409
+ await mkdir(resolve(resolvedWorktree, ".."), { recursive: true });
410
+ if ((await canonicalPath(resolvedWorktree)) !== resolvedWorktree) {
411
+ throw new Error(`Worktree path is redirected: ${resolvedWorktree}`);
412
+ }
413
+ // Conditional includes can enable additional filters only inside the new
414
+ // worktree. Create metadata first, then inspect its own config before checkout.
415
+ await git(repoRoot, ["worktree", "add", "--detach", "--no-checkout", resolvedWorktree, baseCommit], signal);
416
+ await git(resolvedWorktree, ["reset", "--hard", baseCommit], signal);
417
+ }
418
+ /**
419
+ * Removes a detached worktree cleanly or with force.
420
+ */
421
+ export async function removeDetachedWorktree(repoRoot, worktreePath, options = {}) {
422
+ checkSignal(options.signal);
423
+ const args = ["worktree", "remove"];
424
+ if (options.force)
425
+ args.push("--force");
426
+ args.push(resolve(worktreePath));
427
+ await git(repoRoot, args, options.signal);
428
+ }