@kirkchinese/harness-forge 0.0.0-stage → 0.5.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 (279) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/assets/icon.svg +12 -0
  4. package/cordis.patch.yml +28 -0
  5. package/docs/DETAIL.zh.md +47 -0
  6. package/lib/agents/presets.d.ts +98 -0
  7. package/lib/agents/presets.js +292 -0
  8. package/lib/agents/profiles.d.ts +58 -0
  9. package/lib/agents/profiles.js +279 -0
  10. package/lib/agents/row.d.ts +17 -0
  11. package/lib/agents/row.js +148 -0
  12. package/lib/client/paths.d.ts +12 -0
  13. package/lib/client/paths.js +68 -0
  14. package/lib/client/styles.d.ts +8 -0
  15. package/lib/client/styles.js +89 -0
  16. package/lib/client/typert.d.ts +25 -0
  17. package/lib/client/typert.js +158 -0
  18. package/lib/client.js +23823 -0
  19. package/lib/commands/definition.d.ts +40 -0
  20. package/lib/commands/definition.js +113 -0
  21. package/lib/commands/output-styles.d.ts +42 -0
  22. package/lib/commands/output-styles.js +152 -0
  23. package/lib/commands/row.d.ts +9 -0
  24. package/lib/commands/row.js +157 -0
  25. package/lib/context/instructions.d.ts +32 -0
  26. package/lib/context/instructions.js +88 -0
  27. package/lib/context/row.d.ts +16 -0
  28. package/lib/context/row.js +17 -0
  29. package/lib/dsh/commands.d.ts +30 -0
  30. package/lib/dsh/commands.js +61 -0
  31. package/lib/dsh/host.d.ts +110 -0
  32. package/lib/dsh/host.js +217 -0
  33. package/lib/dsh/model-route.d.ts +21 -0
  34. package/lib/dsh/model-route.js +37 -0
  35. package/lib/dsh/session-records.d.ts +78 -0
  36. package/lib/dsh/session-records.js +36 -0
  37. package/lib/dsh/subagents.d.ts +46 -0
  38. package/lib/dsh/subagents.js +14 -0
  39. package/lib/forge/contract.d.ts +271 -0
  40. package/lib/forge/contract.js +45 -0
  41. package/lib/forge/follow.d.ts +30 -0
  42. package/lib/forge/follow.js +73 -0
  43. package/lib/forge/ledger.d.ts +206 -0
  44. package/lib/forge/ledger.js +1005 -0
  45. package/lib/forge/live-mounts.d.ts +45 -0
  46. package/lib/forge/live-mounts.js +78 -0
  47. package/lib/forge/npm.d.ts +31 -0
  48. package/lib/forge/npm.js +60 -0
  49. package/lib/forge/projects.d.ts +97 -0
  50. package/lib/forge/projects.js +343 -0
  51. package/lib/forge/receipts.d.ts +5 -0
  52. package/lib/forge/receipts.js +31 -0
  53. package/lib/forge/remote/archive.d.ts +65 -0
  54. package/lib/forge/remote/archive.js +565 -0
  55. package/lib/forge/remote/code-parts.d.ts +18 -0
  56. package/lib/forge/remote/code-parts.js +76 -0
  57. package/lib/forge/remote/fetch.d.ts +265 -0
  58. package/lib/forge/remote/fetch.js +1133 -0
  59. package/lib/forge/remote/service.d.ts +256 -0
  60. package/lib/forge/remote/service.js +868 -0
  61. package/lib/forge/row.d.ts +32 -0
  62. package/lib/forge/row.js +59 -0
  63. package/lib/forge/service.d.ts +115 -0
  64. package/lib/forge/service.js +290 -0
  65. package/lib/forge/settings.d.ts +43 -0
  66. package/lib/forge/settings.js +122 -0
  67. package/lib/forge/state.d.ts +129 -0
  68. package/lib/forge/state.js +266 -0
  69. package/lib/forge/trust.d.ts +48 -0
  70. package/lib/forge/trust.js +107 -0
  71. package/lib/forge/turns.d.ts +13 -0
  72. package/lib/forge/turns.js +56 -0
  73. package/lib/hooks/broker/engine.d.ts +112 -0
  74. package/lib/hooks/broker/engine.js +722 -0
  75. package/lib/hooks/broker/helpers.d.ts +10 -0
  76. package/lib/hooks/broker/helpers.js +22 -0
  77. package/lib/hooks/broker/lifecycle.d.ts +65 -0
  78. package/lib/hooks/broker/lifecycle.js +342 -0
  79. package/lib/hooks/broker/session-events.d.ts +27 -0
  80. package/lib/hooks/broker/session-events.js +205 -0
  81. package/lib/hooks/broker/tools.d.ts +52 -0
  82. package/lib/hooks/broker/tools.js +424 -0
  83. package/lib/hooks/broker/types.d.ts +264 -0
  84. package/lib/hooks/broker/types.js +1 -0
  85. package/lib/hooks/broker.d.ts +80 -0
  86. package/lib/hooks/broker.js +95 -0
  87. package/lib/hooks/codex-user.d.ts +5 -0
  88. package/lib/hooks/codex-user.js +109 -0
  89. package/lib/hooks/condition.d.ts +87 -0
  90. package/lib/hooks/condition.js +602 -0
  91. package/lib/hooks/config.d.ts +85 -0
  92. package/lib/hooks/config.js +154 -0
  93. package/lib/hooks/glob.d.ts +41 -0
  94. package/lib/hooks/glob.js +114 -0
  95. package/lib/hooks/matcher.d.ts +20 -0
  96. package/lib/hooks/matcher.js +39 -0
  97. package/lib/hooks/notice.d.ts +17 -0
  98. package/lib/hooks/notice.js +39 -0
  99. package/lib/hooks/output.d.ts +56 -0
  100. package/lib/hooks/output.js +214 -0
  101. package/lib/hooks/permissions.d.ts +19 -0
  102. package/lib/hooks/permissions.js +202 -0
  103. package/lib/hooks/powershell-aliases.d.ts +19 -0
  104. package/lib/hooks/powershell-aliases.js +58 -0
  105. package/lib/hooks/process.d.ts +64 -0
  106. package/lib/hooks/process.js +289 -0
  107. package/lib/hooks/row.d.ts +17 -0
  108. package/lib/hooks/row.js +96 -0
  109. package/lib/hooks/runner.d.ts +98 -0
  110. package/lib/hooks/runner.js +322 -0
  111. package/lib/hooks/shell-commands.d.ts +28 -0
  112. package/lib/hooks/shell-commands.js +241 -0
  113. package/lib/hooks/shell.d.ts +44 -0
  114. package/lib/hooks/shell.js +129 -0
  115. package/lib/hooks/transcript.d.ts +28 -0
  116. package/lib/hooks/transcript.js +141 -0
  117. package/lib/hooks/vocabulary.d.ts +57 -0
  118. package/lib/hooks/vocabulary.js +366 -0
  119. package/lib/index.d.ts +31 -0
  120. package/lib/index.js +287 -0
  121. package/lib/mcp/auth.d.ts +35 -0
  122. package/lib/mcp/auth.js +178 -0
  123. package/lib/mcp/catalog.d.ts +39 -0
  124. package/lib/mcp/catalog.js +69 -0
  125. package/lib/mcp/mount.d.ts +113 -0
  126. package/lib/mcp/mount.js +317 -0
  127. package/lib/mcp/policy.d.ts +42 -0
  128. package/lib/mcp/policy.js +43 -0
  129. package/lib/mcp/remote.d.ts +45 -0
  130. package/lib/mcp/remote.js +133 -0
  131. package/lib/mcp/row.d.ts +9 -0
  132. package/lib/mcp/row.js +225 -0
  133. package/lib/mods/bundler.d.ts +38 -0
  134. package/lib/mods/bundler.js +157 -0
  135. package/lib/mods/chain.d.ts +103 -0
  136. package/lib/mods/chain.js +436 -0
  137. package/lib/mods/claude.d.ts +27 -0
  138. package/lib/mods/claude.js +56 -0
  139. package/lib/mods/engine.d.ts +160 -0
  140. package/lib/mods/engine.js +701 -0
  141. package/lib/mods/expect.d.ts +8 -0
  142. package/lib/mods/expect.js +248 -0
  143. package/lib/mods/host.d.ts +105 -0
  144. package/lib/mods/host.js +462 -0
  145. package/lib/mods/loader.d.ts +53 -0
  146. package/lib/mods/loader.js +231 -0
  147. package/lib/mods/ops.d.ts +13 -0
  148. package/lib/mods/ops.js +117 -0
  149. package/lib/mods/row.d.ts +9 -0
  150. package/lib/mods/row.js +77 -0
  151. package/lib/mods/runtime.d.ts +60 -0
  152. package/lib/mods/runtime.js +133 -0
  153. package/lib/mods/service/commands.d.ts +17 -0
  154. package/lib/mods/service/commands.js +121 -0
  155. package/lib/mods/service/drawings.d.ts +36 -0
  156. package/lib/mods/service/drawings.js +64 -0
  157. package/lib/mods/service/sessions.d.ts +63 -0
  158. package/lib/mods/service/sessions.js +345 -0
  159. package/lib/mods/service/tools.d.ts +32 -0
  160. package/lib/mods/service/tools.js +253 -0
  161. package/lib/mods/service/turns.d.ts +33 -0
  162. package/lib/mods/service/turns.js +136 -0
  163. package/lib/mods/service/types.d.ts +151 -0
  164. package/lib/mods/service/types.js +1 -0
  165. package/lib/mods/service.d.ts +72 -0
  166. package/lib/mods/service.js +104 -0
  167. package/lib/mods/surfaces.d.ts +93 -0
  168. package/lib/mods/surfaces.js +309 -0
  169. package/lib/mods/values.d.ts +30 -0
  170. package/lib/mods/values.js +95 -0
  171. package/lib/opencode/bun.d.ts +40 -0
  172. package/lib/opencode/bun.js +168 -0
  173. package/lib/opencode/convert.d.ts +53 -0
  174. package/lib/opencode/convert.js +255 -0
  175. package/lib/opencode/row.d.ts +22 -0
  176. package/lib/opencode/row.js +104 -0
  177. package/lib/opencode/runtime/core.d.ts +74 -0
  178. package/lib/opencode/runtime/core.js +249 -0
  179. package/lib/opencode/runtime/events.d.ts +80 -0
  180. package/lib/opencode/runtime/events.js +281 -0
  181. package/lib/opencode/runtime/mount.d.ts +27 -0
  182. package/lib/opencode/runtime/mount.js +283 -0
  183. package/lib/opencode/runtime/server.d.ts +27 -0
  184. package/lib/opencode/runtime/server.js +354 -0
  185. package/lib/opencode/runtime/types.d.ts +109 -0
  186. package/lib/opencode/runtime/types.js +1 -0
  187. package/lib/opencode/runtime.d.ts +55 -0
  188. package/lib/opencode/runtime.js +79 -0
  189. package/lib/porting/adapter-paths.d.ts +13 -0
  190. package/lib/porting/adapter-paths.js +120 -0
  191. package/lib/porting/port-gap.d.ts +36 -0
  192. package/lib/porting/port-gap.js +158 -0
  193. package/lib/porting/port-sessions.d.ts +41 -0
  194. package/lib/porting/port-sessions.js +98 -0
  195. package/lib/porting/prompt.d.ts +23 -0
  196. package/lib/porting/prompt.js +51 -0
  197. package/lib/porting/row.d.ts +16 -0
  198. package/lib/porting/row.js +27 -0
  199. package/lib/porting/verify-port.d.ts +46 -0
  200. package/lib/porting/verify-port.js +82 -0
  201. package/lib/presets/fs-search.d.ts +25 -0
  202. package/lib/presets/fs-search.js +17 -0
  203. package/lib/presets/tool-filter.d.ts +35 -0
  204. package/lib/presets/tool-filter.js +91 -0
  205. package/lib/sessions/chat-import.d.ts +48 -0
  206. package/lib/sessions/chat-import.js +44 -0
  207. package/lib/sessions/claude.d.ts +35 -0
  208. package/lib/sessions/claude.js +104 -0
  209. package/lib/sessions/codex-discover.d.ts +34 -0
  210. package/lib/sessions/codex-discover.js +205 -0
  211. package/lib/sessions/codex-meta.d.ts +63 -0
  212. package/lib/sessions/codex-meta.js +148 -0
  213. package/lib/sessions/codex-text.d.ts +9 -0
  214. package/lib/sessions/codex-text.js +44 -0
  215. package/lib/sessions/codex.d.ts +42 -0
  216. package/lib/sessions/codex.js +270 -0
  217. package/lib/sessions/opencode.d.ts +38 -0
  218. package/lib/sessions/opencode.js +339 -0
  219. package/lib/sessions/persist.d.ts +162 -0
  220. package/lib/sessions/persist.js +377 -0
  221. package/lib/sessions/row.d.ts +15 -0
  222. package/lib/sessions/row.js +101 -0
  223. package/lib/sessions/turns.d.ts +31 -0
  224. package/lib/sessions/turns.js +63 -0
  225. package/lib/sessions/zstd.d.ts +15 -0
  226. package/lib/sessions/zstd.js +152 -0
  227. package/lib/shared/invocation.d.ts +169 -0
  228. package/lib/shared/invocation.js +325 -0
  229. package/lib/shared/render.d.ts +101 -0
  230. package/lib/shared/render.js +1353 -0
  231. package/lib/shared/util.d.ts +21 -0
  232. package/lib/shared/util.js +32 -0
  233. package/lib/skills/bundled.d.ts +3 -0
  234. package/lib/skills/bundled.js +42 -0
  235. package/lib/skills/provider.d.ts +74 -0
  236. package/lib/skills/provider.js +346 -0
  237. package/lib/skills/row.d.ts +22 -0
  238. package/lib/skills/row.js +204 -0
  239. package/lib/workbench/adapter-coverage.d.ts +65 -0
  240. package/lib/workbench/adapter-coverage.js +141 -0
  241. package/lib/workbench/model-tools.d.ts +10 -0
  242. package/lib/workbench/model-tools.js +122 -0
  243. package/lib/workbench/overview.d.ts +153 -0
  244. package/lib/workbench/overview.js +246 -0
  245. package/lib/workbench/remote.d.ts +161 -0
  246. package/lib/workbench/remote.js +561 -0
  247. package/lib/workbench/row.d.ts +15 -0
  248. package/lib/workbench/row.js +16 -0
  249. package/lib/workbench/settings.d.ts +19 -0
  250. package/lib/workbench/settings.js +60 -0
  251. package/lib/workbench/workbench.d.ts +130 -0
  252. package/lib/workbench/workbench.js +361 -0
  253. package/locale/agents/en.json +6 -0
  254. package/locale/agents/zh.json +6 -0
  255. package/locale/commands/en.json +6 -0
  256. package/locale/commands/zh.json +6 -0
  257. package/locale/context/en.json +6 -0
  258. package/locale/context/zh.json +6 -0
  259. package/locale/en.json +6 -0
  260. package/locale/hooks/en.json +6 -0
  261. package/locale/hooks/zh.json +6 -0
  262. package/locale/mcp/en.json +6 -0
  263. package/locale/mcp/zh.json +6 -0
  264. package/locale/mods/en.json +6 -0
  265. package/locale/mods/zh.json +6 -0
  266. package/locale/opencode/en.json +6 -0
  267. package/locale/opencode/zh.json +6 -0
  268. package/locale/porter/en.json +6 -0
  269. package/locale/porter/zh.json +6 -0
  270. package/locale/sessions/en.json +6 -0
  271. package/locale/sessions/zh.json +6 -0
  272. package/locale/skills/en.json +6 -0
  273. package/locale/skills/zh.json +6 -0
  274. package/locale/workbench/en.json +6 -0
  275. package/locale/workbench/zh.json +6 -0
  276. package/locale/zh.json +7 -0
  277. package/package.json +247 -3
  278. package/runtime/opencode-host.mjs +270 -0
  279. package/skills/harness-forge/SKILL.md +47 -0
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Receipt persistence. A receipt is the durable record of what apply actually
3
+ * did; it is small, JSON-serializable and safe to expose in diagnostics.
4
+ * @module @kirkchinese/harness-forge
5
+ */
6
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ /** Write one receipt atomically under `dir/<id>.json`. */
9
+ export function writeReceipt(receipt, dir) {
10
+ mkdirSync(dir, { recursive: true });
11
+ const path = join(dir, `${receipt.id}.json`);
12
+ const temporary = `${path}.tmp`;
13
+ writeFileSync(temporary, `${JSON.stringify(receipt, null, 2)}\n`, 'utf8');
14
+ renameSync(temporary, path);
15
+ return path;
16
+ }
17
+ /** Read one receipt, or undefined when absent/malformed. */
18
+ export function readReceipt(id, dir) {
19
+ try {
20
+ const value = JSON.parse(readFileSync(join(dir, `${id}.json`), 'utf8'));
21
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
22
+ return undefined;
23
+ const receipt = value;
24
+ if (typeof receipt['id'] !== 'string' || typeof receipt['pluginId'] !== 'string')
25
+ return undefined;
26
+ return value;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
@@ -0,0 +1,65 @@
1
+ /** Bounds on what one unpack or copy may write. */
2
+ export interface TreeLimits {
3
+ /** Total bytes of file content. */
4
+ readonly maxBytes: number;
5
+ /** Files, directories and links together (for a tar, every header record). */
6
+ readonly maxEntries: number;
7
+ }
8
+ /** Claude Code's bounds on a plugin copied into its cache: 256 MiB, 20,000 entries. */
9
+ export declare const PLUGIN_LIMITS: TreeLimits;
10
+ /** A whole repository unpacked to read its marketplace: larger, since only part of it is a plugin. */
11
+ export declare const REPOSITORY_LIMITS: TreeLimits;
12
+ /** Options of an unpack. */
13
+ export interface UnpackOptions {
14
+ readonly limits?: TreeLimits;
15
+ /** Aborting stops the unpack with the signal's reason. */
16
+ readonly signal?: AbortSignal;
17
+ }
18
+ /**
19
+ * How a destination is told apart from others: in Unicode NFC (macOS treats
20
+ * other normalizations of a name as the same file), and case-insensitively
21
+ * where the file system is (macOS, Windows).
22
+ */
23
+ export declare function destinationKey(path: string, platform?: NodeJS.Platform): string;
24
+ /**
25
+ * Unpack a `.tar.gz` into `dest` (which must not exist yet or be empty).
26
+ * @returns the commit SHA a `git archive` tarball records (GitHub's pax `comment`), when there is one.
27
+ */
28
+ export declare function extractTarGz(archive: Buffer, dest: string, options?: UnpackOptions & {
29
+ readonly strip?: number;
30
+ }): Promise<{
31
+ commit?: string;
32
+ }>;
33
+ /** Unpack a zip into `dest`: stored and deflated members, without ZIP64. */
34
+ export declare function extractZip(archive: Buffer, dest: string, options?: UnpackOptions): Promise<void>;
35
+ /**
36
+ * Copy a plugin directory to `dest`, leaving out `.git` and every link (a
37
+ * link is not followed, so nothing outside the checkout is read). The
38
+ * directory itself must be a real directory inside `boundary`, reached through
39
+ * no link, and so must every directory under it when it is read. Returns the
40
+ * links and anything else that is not a regular file (a FIFO, a device) left
41
+ * out. Used for every source, a folder on this computer included, so what is
42
+ * shown and installed is this copy.
43
+ *
44
+ * A parent directory replaced by a link between a directory's real-path check
45
+ * and the open of a file in it is not caught: that takes a process running
46
+ * now, on this computer, with write access to the user's own folders, which
47
+ * could as well change the plugin's files before they are listed.
48
+ */
49
+ export declare function copyTree(source: string, dest: string, boundary?: string, limits?: TreeLimits): string[];
50
+ /**
51
+ * A SHA-256 over a directory or file as installed: every path (sorted), its
52
+ * type, whether it is executable, a file's bytes and a link's target. Equal
53
+ * digests are the same files; what a confirmation showed is bound to one.
54
+ */
55
+ export declare function treeDigest(path: string): string;
56
+ /** Refuse a checkout directory whose manifests (or the folders holding them) are links. */
57
+ export declare function refuseLinkedManifests(dir: string): void;
58
+ /** Bytes and entries under a directory (`.git` included), stopping once past the limits. */
59
+ export declare function treeSize(directory: string, limits: TreeLimits): {
60
+ bytes: number;
61
+ entries: number;
62
+ over: boolean;
63
+ };
64
+ /** The single top-level directory of an unpacked zip ("the plugin root may be at the top of the zip or one directory down"). */
65
+ export declare function zipRoot(directory: string): string;
@@ -0,0 +1,565 @@
1
+ /**
2
+ * Unpacking what Harness Forge downloads (a GitHub `.tar.gz` when git is
3
+ * missing, a zip `archive` source, an npm tarball) and copying a plugin out of
4
+ * a checkout, with Node alone. Plugins are files and directories: links,
5
+ * hard links, devices and other special entries are refused, every path must
6
+ * stay inside its destination, and what is written is bounded as it is written.
7
+ * Unpacking yields to the event loop as it goes, so the operation's deadline
8
+ * and cancellation interrupt it.
9
+ * @module @kirkchinese/harness-forge
10
+ */
11
+ import { createHash } from 'node:crypto';
12
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, realpathSync, writeFileSync } from 'node:fs';
13
+ import { dirname, join, relative, resolve } from 'node:path';
14
+ import { Readable } from 'node:stream';
15
+ import { pipeline } from 'node:stream/promises';
16
+ import { createGunzip, createInflateRaw } from 'node:zlib';
17
+ import { HarnessError, isInside } from '@kirkchinese/harness-forge-core';
18
+ /** Claude Code's bounds on a plugin copied into its cache: 256 MiB, 20,000 entries. */
19
+ export const PLUGIN_LIMITS = { maxBytes: 256 * 1024 * 1024, maxEntries: 20_000 };
20
+ /** A whole repository unpacked to read its marketplace: larger, since only part of it is a plugin. */
21
+ export const REPOSITORY_LIMITS = { maxBytes: 512 * 1024 * 1024, maxEntries: 100_000 };
22
+ function tooLarge(what, limits) {
23
+ return new HarnessError('fetch-failed', `${what} is larger than Harness Forge accepts (${String(Math.round(limits.maxBytes / 1024 / 1024))} MiB or ${String(limits.maxEntries)} files)`);
24
+ }
25
+ function damaged(kind, why) {
26
+ return new HarnessError('fetch-failed', `the download is not a ${kind} archive Harness Forge can read: ${why}`);
27
+ }
28
+ function special(name) {
29
+ return new HarnessError('fetch-failed', `the archive contains a link or special file (${name}); plugins are plain files, so Harness Forge does not unpack it`);
30
+ }
31
+ /** Stop when cancellation (or the deadline) has fired, with its reason. */
32
+ function stopIfAborted(signal) {
33
+ if (signal?.aborted === true)
34
+ throw signal.reason instanceof Error ? signal.reason : new HarnessError('fetch-failed', 'cancelled');
35
+ }
36
+ /** Let timers (the deadline) and cancellation in, and stop when they fired. */
37
+ async function checkpoint(signal) {
38
+ await new Promise((resolvePromise) => { setImmediate(resolvePromise); });
39
+ stopIfAborted(signal);
40
+ }
41
+ /** Raised inside {@link decompress} when the output passes its bound. */
42
+ class OutputTooLarge extends Error {
43
+ }
44
+ /**
45
+ * Decompress `input` as a stream, chunk by chunk, so cancellation stops it
46
+ * part-way and its output is bounded as it grows.
47
+ * @throws {OutputTooLarge} once more than `maxOutput` bytes come out.
48
+ */
49
+ async function decompress(input, inflater, maxOutput, signal) {
50
+ stopIfAborted(signal);
51
+ const chunks = [];
52
+ let length = 0;
53
+ try {
54
+ await pipeline(Readable.from([input]), inflater, async (source) => {
55
+ for await (const chunk of source) {
56
+ length += chunk.length;
57
+ if (length > maxOutput)
58
+ throw new OutputTooLarge();
59
+ chunks.push(chunk);
60
+ }
61
+ }, ...(signal !== undefined ? [{ signal }] : []));
62
+ }
63
+ catch (error) {
64
+ stopIfAborted(signal);
65
+ throw error;
66
+ }
67
+ return Buffer.concat(chunks, length);
68
+ }
69
+ /** Windows device names, reserved in any folder and with any extension. */
70
+ const RESERVED = /^(?:con|prn|aux|nul|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3])(?:\..*)?$/iu;
71
+ /**
72
+ * Where an archive member goes, or undefined when its name leaves the
73
+ * destination. A name no folder can hold everywhere, or that Windows would
74
+ * read as another, is refused: a `:` (an alternate data stream or a drive),
75
+ * a device name, or a trailing dot or space (which Windows drops).
76
+ */
77
+ function memberPath(dest, name, strip) {
78
+ const parts = name.replace(/\\/gu, '/').split('/').filter(part => part.length > 0 && part !== '.');
79
+ if (parts.length <= strip)
80
+ return undefined;
81
+ const kept = parts.slice(strip);
82
+ if (kept.some(part => part === '..'))
83
+ return undefined;
84
+ const bad = kept.find(part => part.includes(':') || /[ .]$/u.test(part) || RESERVED.test(part));
85
+ if (bad !== undefined)
86
+ throw new HarnessError('fetch-failed', `the archive has a name Windows cannot hold (${bad}); Harness Forge does not unpack it`);
87
+ const target = resolve(dest, ...kept);
88
+ return isInside(dest, target) && target !== resolve(dest) ? target : undefined;
89
+ }
90
+ /**
91
+ * How a destination is told apart from others: in Unicode NFC (macOS treats
92
+ * other normalizations of a name as the same file), and case-insensitively
93
+ * where the file system is (macOS, Windows).
94
+ */
95
+ export function destinationKey(path, platform = process.platform) {
96
+ const normal = path.normalize('NFC');
97
+ return platform === 'win32' || platform === 'darwin' ? normal.toLowerCase() : normal;
98
+ }
99
+ /**
100
+ * What one unpack has written: every file and directory (the ones made for
101
+ * a file's parents included) counts toward the entry bound, and no two
102
+ * members may land on the same path.
103
+ */
104
+ class Destination {
105
+ root;
106
+ limits;
107
+ signal;
108
+ paths = new Map();
109
+ entries = 0;
110
+ constructor(root, limits, signal) {
111
+ this.root = root;
112
+ this.limits = limits;
113
+ this.signal = signal;
114
+ }
115
+ /** Count `n` more entries (records an unpack reads without writing). */
116
+ charge(n = 1) {
117
+ this.entries += n;
118
+ if (this.entries > this.limits.maxEntries)
119
+ throw tooLarge('the archive', this.limits);
120
+ }
121
+ claim(path, kind) {
122
+ const key = destinationKey(path);
123
+ const was = this.paths.get(key);
124
+ if (was !== undefined) {
125
+ if (was === 'dir' && kind === 'dir')
126
+ return false;
127
+ throw new HarnessError('fetch-failed', `the archive has two members for ${relative(this.root, path).replace(/\\/gu, '/')}; Harness Forge does not unpack it`);
128
+ }
129
+ this.paths.set(key, kind);
130
+ this.charge();
131
+ return true;
132
+ }
133
+ /** A directory, with its parents. */
134
+ directory(path) {
135
+ const chain = [];
136
+ for (let dir = path; dir !== this.root && isInside(this.root, dir); dir = dirname(dir))
137
+ chain.unshift(dir);
138
+ for (const dir of chain)
139
+ this.claim(dir, 'dir');
140
+ mkdirSync(path, { recursive: true });
141
+ }
142
+ /** A file, with its parents; created, never written over (whatever name the file system takes as the same). */
143
+ file(path, data, mode) {
144
+ // Nothing more is written once the unpack is cancelled.
145
+ stopIfAborted(this.signal);
146
+ this.directory(dirname(path));
147
+ this.claim(path, 'file');
148
+ try {
149
+ writeFileSync(path, data, { mode, flag: 'wx' });
150
+ }
151
+ catch (error) {
152
+ if (error.code !== 'EEXIST')
153
+ throw error;
154
+ throw new HarnessError('fetch-failed', `the archive has two members for ${relative(this.root, path).replace(/\\/gu, '/')}; Harness Forge does not unpack it`);
155
+ }
156
+ }
157
+ }
158
+ /** What a tar header field holds, up to its first NUL. */
159
+ function field(block, start, length) {
160
+ const slice = block.subarray(start, start + length);
161
+ const end = slice.indexOf(0);
162
+ return slice.subarray(0, end < 0 ? slice.length : end).toString('utf8');
163
+ }
164
+ /** A tar size field: octal digits only (no base-256, no sign), else undefined. */
165
+ function octal(block, start, length) {
166
+ const text = field(block, start, length).trim();
167
+ if (!/^[0-7]{1,12}$/u.test(text))
168
+ return text.length === 0 ? 0 : undefined;
169
+ return Number.parseInt(text, 8);
170
+ }
171
+ /** A pax header block's records (`<len> key=value\n`). */
172
+ function paxRecords(data) {
173
+ const records = new Map();
174
+ let offset = 0;
175
+ while (offset < data.length) {
176
+ const space = data.indexOf(0x20, offset);
177
+ if (space < 0)
178
+ break;
179
+ const length = Number.parseInt(data.subarray(offset, space).toString('utf8'), 10);
180
+ if (!Number.isFinite(length) || length <= 0 || offset + length > data.length)
181
+ break;
182
+ const record = data.subarray(space + 1, offset + length - 1).toString('utf8');
183
+ const equals = record.indexOf('=');
184
+ if (equals > 0)
185
+ records.set(record.slice(0, equals), record.slice(equals + 1));
186
+ offset += length;
187
+ }
188
+ return records;
189
+ }
190
+ /**
191
+ * Unpack a `.tar.gz` into `dest` (which must not exist yet or be empty).
192
+ * @returns the commit SHA a `git archive` tarball records (GitHub's pax `comment`), when there is one.
193
+ */
194
+ export async function extractTarGz(archive, dest, options = {}) {
195
+ const limits = options.limits ?? REPOSITORY_LIMITS;
196
+ let tar;
197
+ try {
198
+ tar = await decompress(archive, createGunzip(), limits.maxBytes + limits.maxEntries * 1024, options.signal);
199
+ }
200
+ catch (error) {
201
+ if (error instanceof OutputTooLarge)
202
+ throw tooLarge('the archive', limits);
203
+ if (error instanceof HarnessError || options.signal?.aborted === true)
204
+ throw error;
205
+ throw new HarnessError('fetch-failed', 'the download is not a valid .tar.gz archive', { cause: error });
206
+ }
207
+ stopIfAborted(options.signal);
208
+ mkdirSync(dest, { recursive: true });
209
+ const root = resolve(dest);
210
+ const out = new Destination(root, limits, options.signal);
211
+ const strip = options.strip ?? 0;
212
+ let commit;
213
+ let bytes = 0;
214
+ let records = 0;
215
+ let longName;
216
+ let pax = new Map();
217
+ for (let offset = 0; offset + 512 <= tar.length;) {
218
+ const header = tar.subarray(offset, offset + 512);
219
+ if (header.every(byte => byte === 0))
220
+ break;
221
+ // Every record counts, extension records included: a stream of them is no cheaper to read.
222
+ records += 1;
223
+ // Every header record counts, whatever it is or becomes (repeated, skipped, an extension), and so does every output.
224
+ out.charge();
225
+ if (records % 256 === 0)
226
+ await checkpoint(options.signal);
227
+ const size = octal(header, 124, 12);
228
+ if (size === undefined)
229
+ throw damaged('tar', 'a member has a malformed size');
230
+ const type = String.fromCharCode(header[156] ?? 0);
231
+ const dataStart = offset + 512;
232
+ if (dataStart + size > tar.length)
233
+ throw damaged('tar', 'it ends inside a member');
234
+ const data = tar.subarray(dataStart, dataStart + size);
235
+ offset = dataStart + Math.ceil(size / 512) * 512;
236
+ if (type === 'g') {
237
+ const comment = paxRecords(data).get('comment');
238
+ if (comment !== undefined && /^[0-9a-f]{40}$/u.test(comment))
239
+ commit = comment;
240
+ continue;
241
+ }
242
+ if (type === 'x') {
243
+ pax = paxRecords(data);
244
+ continue;
245
+ }
246
+ if (type === 'L') {
247
+ longName = field(data, 0, data.length);
248
+ continue;
249
+ }
250
+ const prefix = field(header, 345, 155);
251
+ const name = pax.get('path') ?? longName ?? (prefix.length > 0 ? `${prefix}/${field(header, 0, 100)}` : field(header, 0, 100));
252
+ pax = new Map();
253
+ longName = undefined;
254
+ if (type !== '0' && type !== '\0' && type !== '7' && type !== '5')
255
+ throw special(name);
256
+ const target = memberPath(root, name, strip);
257
+ if (target === undefined)
258
+ continue;
259
+ if (type === '5') {
260
+ out.directory(target);
261
+ continue;
262
+ }
263
+ bytes += data.length;
264
+ if (bytes > limits.maxBytes)
265
+ throw tooLarge('the archive', limits);
266
+ const mode = octal(header, 100, 8) ?? 0o644;
267
+ out.file(target, data, (mode & 0o755) | 0o600);
268
+ }
269
+ // A cancelled unpack is not reported done, however short the archive.
270
+ await checkpoint(options.signal);
271
+ return commit === undefined ? {} : { commit };
272
+ }
273
+ /** Unpack a zip into `dest`: stored and deflated members, without ZIP64. */
274
+ export async function extractZip(archive, dest, options = {}) {
275
+ const limits = options.limits ?? PLUGIN_LIMITS;
276
+ const invalid = (why) => damaged('zip', why);
277
+ stopIfAborted(options.signal);
278
+ let end = -1;
279
+ for (let index = archive.length - 22; index >= Math.max(0, archive.length - 22 - 65_535); index -= 1) {
280
+ if (archive.readUInt32LE(index) === 0x06054b50) {
281
+ end = index;
282
+ break;
283
+ }
284
+ }
285
+ if (end < 0)
286
+ throw invalid('no end of central directory');
287
+ const count = archive.readUInt16LE(end + 10);
288
+ const directoryStart = archive.readUInt32LE(end + 16);
289
+ if (count === 0xffff || directoryStart === 0xffffffff)
290
+ throw invalid('ZIP64 archives are not supported');
291
+ if (count > limits.maxEntries)
292
+ throw tooLarge('the archive', limits);
293
+ if (directoryStart > end)
294
+ throw invalid('a central directory outside the archive');
295
+ mkdirSync(dest, { recursive: true });
296
+ const root = resolve(dest);
297
+ const out = new Destination(root, limits, options.signal);
298
+ /** Byte ranges of the members' local records and data: no two may overlap, nor reach into the central directory. */
299
+ const ranges = [];
300
+ let bytes = 0;
301
+ let offset = directoryStart;
302
+ for (let index = 0; index < count; index += 1) {
303
+ if (index % 64 === 63)
304
+ await checkpoint(options.signal);
305
+ if (offset + 46 > end || archive.readUInt32LE(offset) !== 0x02014b50)
306
+ throw invalid('a damaged central directory');
307
+ const method = archive.readUInt16LE(offset + 10);
308
+ const compressed = archive.readUInt32LE(offset + 20);
309
+ const size = archive.readUInt32LE(offset + 24);
310
+ const nameLength = archive.readUInt16LE(offset + 28);
311
+ const extraLength = archive.readUInt16LE(offset + 30);
312
+ const commentLength = archive.readUInt16LE(offset + 32);
313
+ const mode = archive.readUInt32LE(offset + 38) >>> 16;
314
+ const local = archive.readUInt32LE(offset + 42);
315
+ const name = archive.subarray(offset + 46, offset + 46 + nameLength).toString('utf8');
316
+ offset += 46 + nameLength + extraLength + commentLength;
317
+ const type = mode & 0o170000;
318
+ const directory = name.endsWith('/');
319
+ if (type !== 0 && type !== 0o100000 && !(directory && type === 0o040000))
320
+ throw special(name);
321
+ const target = memberPath(root, name, 0);
322
+ if (target === undefined)
323
+ continue;
324
+ if (directory) {
325
+ out.directory(target);
326
+ continue;
327
+ }
328
+ if (local + 30 > directoryStart || archive.readUInt32LE(local) !== 0x04034b50)
329
+ throw invalid('a damaged member header');
330
+ const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);
331
+ const stop = start + compressed;
332
+ if (stop > directoryStart)
333
+ throw invalid(`${name} reaches past its data`);
334
+ if (ranges.some(([from, to]) => local < to && from < stop))
335
+ throw invalid(`${name} overlaps another member`);
336
+ ranges.push([local, stop]);
337
+ const raw = archive.subarray(start, stop);
338
+ let content;
339
+ if (method === 0) {
340
+ if (compressed !== size)
341
+ throw invalid(`${name} is stored with two different sizes`);
342
+ content = raw;
343
+ }
344
+ else if (method === 8) {
345
+ try {
346
+ content = await decompress(raw, createInflateRaw(), Math.min(size, limits.maxBytes - bytes), options.signal);
347
+ }
348
+ catch (error) {
349
+ if (options.signal?.aborted === true)
350
+ throw error;
351
+ throw bytes + size > limits.maxBytes ? tooLarge('the archive', limits) : invalid(`${name} does not inflate to its size`);
352
+ }
353
+ if (content.length !== size)
354
+ throw invalid(`${name} does not inflate to its size`);
355
+ }
356
+ else {
357
+ throw invalid(`compression method ${String(method)}`);
358
+ }
359
+ // What is written counts, whatever the header says.
360
+ bytes += content.length;
361
+ if (bytes > limits.maxBytes)
362
+ throw tooLarge('the archive', limits);
363
+ out.file(target, content, (mode & 0o755) | 0o600);
364
+ }
365
+ await checkpoint(options.signal);
366
+ }
367
+ /**
368
+ * How a source file is opened: read-only, without following a link, and
369
+ * without waiting. A FIFO or device put in a listed file's place would
370
+ * otherwise block the synchronous open (a FIFO until something writes to it),
371
+ * and with it DSH; non-blocking, it opens at once, and `fstat` then turns it
372
+ * away before anything is read. Neither flag exists on Windows, where
373
+ * `fs.constants` leaves them out: creating links there needs privileges the
374
+ * plugin's folder does not grant, and named pipes live under `\\.\pipe\`,
375
+ * never in a folder.
376
+ */
377
+ const SOURCE_FILE_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
378
+ /**
379
+ * Read a regular file without following a link, even one put in its place
380
+ * after it was listed (a folder another program refreshes): undefined when it
381
+ * is not a regular file now. Everything is read from the one descriptor whose
382
+ * type was checked. At most `size` bytes are read, the size its listing gave,
383
+ * so the copy's budget holds while the file grows.
384
+ */
385
+ function readPlainFile(path, size) {
386
+ let fd;
387
+ try {
388
+ fd = openSync(path, SOURCE_FILE_FLAGS);
389
+ }
390
+ catch (error) {
391
+ if (error.code === 'ELOOP')
392
+ return undefined;
393
+ throw error;
394
+ }
395
+ try {
396
+ const stat = fstatSync(fd);
397
+ if (!stat.isFile())
398
+ return undefined;
399
+ const data = Buffer.alloc(Math.min(size, stat.size));
400
+ let read = 0;
401
+ while (read < data.length) {
402
+ const n = readSync(fd, data, read, data.length - read, read);
403
+ if (n === 0)
404
+ break;
405
+ read += n;
406
+ }
407
+ return { data: data.subarray(0, read), mode: stat.mode };
408
+ }
409
+ finally {
410
+ closeSync(fd);
411
+ }
412
+ }
413
+ /**
414
+ * Copy a plugin directory to `dest`, leaving out `.git` and every link (a
415
+ * link is not followed, so nothing outside the checkout is read). The
416
+ * directory itself must be a real directory inside `boundary`, reached through
417
+ * no link, and so must every directory under it when it is read. Returns the
418
+ * links and anything else that is not a regular file (a FIFO, a device) left
419
+ * out. Used for every source, a folder on this computer included, so what is
420
+ * shown and installed is this copy.
421
+ *
422
+ * A parent directory replaced by a link between a directory's real-path check
423
+ * and the open of a file in it is not caught: that takes a process running
424
+ * now, on this computer, with write access to the user's own folders, which
425
+ * could as well change the plugin's files before they are listed.
426
+ */
427
+ export function copyTree(source, dest, boundary = source, limits = PLUGIN_LIMITS) {
428
+ const top = lstatSync(source);
429
+ if (top.isSymbolicLink() || !top.isDirectory())
430
+ throw new HarnessError('path-escape', `the plugin directory is a link or not a directory: ${relative(boundary, source) || '.'}`);
431
+ // Through no link: its real path sits where its path says, inside the checkout.
432
+ const real = realpathSync(source);
433
+ const realBoundary = realpathSync(boundary);
434
+ if ((real !== realBoundary && !isInside(realBoundary, real)) || relative(realBoundary, real) !== relative(resolve(boundary), resolve(source))) {
435
+ throw new HarnessError('path-escape', `the plugin directory is reached through a link: ${relative(boundary, source) || '.'}`);
436
+ }
437
+ let bytes = 0;
438
+ let entries = 0;
439
+ const skipped = [];
440
+ const visit = (from, realFrom, to) => {
441
+ // Still where it was listed, not a link swapped in since.
442
+ if (realpathSync(from) !== realFrom)
443
+ throw new HarnessError('path-escape', `the plugin folder changed into a link while it was copied: ${relative(source, from) || '.'}`);
444
+ mkdirSync(to, { recursive: true });
445
+ for (const name of readdirSync(from)) {
446
+ if (name === '.git')
447
+ continue;
448
+ const path = join(from, name);
449
+ const relativePath = relative(source, path).replace(/\\/gu, '/');
450
+ entries += 1;
451
+ if (entries > limits.maxEntries)
452
+ throw tooLarge('the plugin', limits);
453
+ const stat = lstatSync(path);
454
+ if (stat.isDirectory()) {
455
+ visit(path, join(realFrom, name), join(to, name));
456
+ continue;
457
+ }
458
+ if (stat.isFile() && bytes + stat.size > limits.maxBytes)
459
+ throw tooLarge('the plugin', limits);
460
+ const file = stat.isFile() ? readPlainFile(path, stat.size) : undefined;
461
+ if (file === undefined) {
462
+ skipped.push(relativePath);
463
+ continue;
464
+ }
465
+ bytes += file.data.length;
466
+ if (bytes > limits.maxBytes)
467
+ throw tooLarge('the plugin', limits);
468
+ writeFileSync(join(to, name), file.data, { mode: file.mode & 0o777, flag: 'wx' });
469
+ }
470
+ };
471
+ visit(source, real, dest);
472
+ return skipped;
473
+ }
474
+ /**
475
+ * A SHA-256 over a directory or file as installed: every path (sorted), its
476
+ * type, whether it is executable, a file's bytes and a link's target. Equal
477
+ * digests are the same files; what a confirmation showed is bound to one.
478
+ */
479
+ export function treeDigest(path) {
480
+ const hash = createHash('sha256');
481
+ const visit = (absolute, relativePath) => {
482
+ const stat = lstatSync(absolute);
483
+ if (stat.isSymbolicLink()) {
484
+ hash.update(`L\0${relativePath}\0${readlinkSync(absolute)}\0`);
485
+ }
486
+ else if (stat.isDirectory()) {
487
+ hash.update(`D\0${relativePath}\0`);
488
+ for (const name of readdirSync(absolute).sort())
489
+ visit(join(absolute, name), relativePath.length > 0 ? `${relativePath}/${name}` : name);
490
+ }
491
+ else if (stat.isFile()) {
492
+ hash.update(`F\0${relativePath}\0${(stat.mode & 0o111) !== 0 ? 'x' : '-'}\0${String(stat.size)}\0`);
493
+ hash.update(readFileSync(absolute));
494
+ hash.update('\0');
495
+ }
496
+ };
497
+ visit(path, '');
498
+ return hash.digest('hex');
499
+ }
500
+ /** The files that say what a plugin or marketplace is: read before the plugin is copied, so never through a link. */
501
+ const MANIFESTS = [
502
+ '.claude-plugin/plugin.json', '.claude-plugin/marketplace.json', '.codex-plugin/plugin.json', '.agents/plugins/marketplace.json',
503
+ 'plugin.json', 'package.json', 'opencode.json', 'opencode.jsonc', 'hooks/hooks.json', '.mcp.json',
504
+ ];
505
+ /** Refuse a checkout directory whose manifests (or the folders holding them) are links. */
506
+ export function refuseLinkedManifests(dir) {
507
+ for (const manifest of MANIFESTS) {
508
+ let path = dir;
509
+ for (const part of manifest.split('/')) {
510
+ path = join(path, part);
511
+ let link;
512
+ try {
513
+ link = lstatSync(path).isSymbolicLink();
514
+ }
515
+ catch {
516
+ break;
517
+ }
518
+ if (link)
519
+ throw new HarnessError('path-escape', `${relative(dir, path).replace(/\\/gu, '/')} is a link; Harness Forge does not follow links in what it fetches`);
520
+ }
521
+ }
522
+ }
523
+ /** Bytes and entries under a directory (`.git` included), stopping once past the limits. */
524
+ export function treeSize(directory, limits) {
525
+ let bytes = 0;
526
+ let entries = 0;
527
+ const stack = [directory];
528
+ while (stack.length > 0) {
529
+ const dir = stack.pop();
530
+ let names;
531
+ try {
532
+ names = readdirSync(dir);
533
+ }
534
+ catch {
535
+ continue;
536
+ }
537
+ for (const name of names) {
538
+ const path = join(dir, name);
539
+ let stat;
540
+ try {
541
+ stat = lstatSync(path);
542
+ }
543
+ catch {
544
+ // Renamed or deleted while git or npm writes: counted on the next look.
545
+ continue;
546
+ }
547
+ entries += 1;
548
+ if (stat.isDirectory())
549
+ stack.push(path);
550
+ else
551
+ bytes += stat.size;
552
+ if (bytes > limits.maxBytes || entries > limits.maxEntries)
553
+ return { bytes, entries, over: true };
554
+ }
555
+ }
556
+ return { bytes, entries, over: false };
557
+ }
558
+ /** The single top-level directory of an unpacked zip ("the plugin root may be at the top of the zip or one directory down"). */
559
+ export function zipRoot(directory) {
560
+ const children = readdirSync(directory).filter(name => !name.startsWith('__MACOSX'));
561
+ if (children.length !== 1)
562
+ return directory;
563
+ const only = join(directory, children[0]);
564
+ return lstatSync(only).isDirectory() ? only : directory;
565
+ }
@@ -0,0 +1,18 @@
1
+ import { type ForeignPlugin, type Gap } from '@kirkchinese/harness-forge-core';
2
+ import { type OverviewPart } from '../../workbench/overview.js';
3
+ /** What runs: the Client words each in the person's language. */
4
+ export type CodeRunner = 'hooks' | 'mcp' | 'shell' | 'script' | 'code' | 'environment' | 'agent';
5
+ /** One part that would run code. */
6
+ export interface CodePart {
7
+ readonly kind: string;
8
+ readonly name: string;
9
+ readonly what: CodeRunner;
10
+ /** The events, command, shell lines, script or runtime, as the plugin declares them. */
11
+ readonly detail: string;
12
+ /** Whether it runs in DSH once installed; a gap runs nothing. */
13
+ readonly runs: boolean;
14
+ /** Why it does not run, as the overview gives it. */
15
+ readonly reasons?: OverviewPart['reasons'];
16
+ }
17
+ /** The parts of a plugin that would run code, and whether each runs in DSH once installed. */
18
+ export declare function codePartsOf(plugin: ForeignPlugin, gaps: readonly Gap[]): CodePart[];