apphx 1.0.0 → 2.0.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 (126) hide show
  1. package/README.md +52 -138
  2. package/benchmarks/peer-context-worker.mjs +186 -0
  3. package/benchmarks/peer-context.mjs +150 -0
  4. package/dist/apple-types.js.map +1 -1
  5. package/dist/cli.js +373 -121
  6. package/dist/cli.js.map +1 -1
  7. package/dist/config.js +42 -4
  8. package/dist/config.js.map +1 -1
  9. package/dist/dependencies.js +455 -16
  10. package/dist/dependencies.js.map +1 -1
  11. package/dist/export-options.js +44 -2
  12. package/dist/export-options.js.map +1 -1
  13. package/dist/flutter.js +13 -25
  14. package/dist/flutter.js.map +1 -1
  15. package/dist/go-dependencies.js +389 -0
  16. package/dist/go-dependencies.js.map +1 -0
  17. package/dist/inbox.js +7 -8
  18. package/dist/inbox.js.map +1 -1
  19. package/dist/integrations.js +29 -29
  20. package/dist/integrations.js.map +1 -1
  21. package/dist/isolation.js +190 -0
  22. package/dist/isolation.js.map +1 -0
  23. package/dist/macos.js +57 -0
  24. package/dist/macos.js.map +1 -0
  25. package/dist/mygo-build.js +55 -0
  26. package/dist/mygo-build.js.map +1 -0
  27. package/dist/policy.js +35 -0
  28. package/dist/policy.js.map +1 -0
  29. package/dist/preflight.js +1 -1
  30. package/dist/process.js +3 -3
  31. package/dist/project-profiles.js +163 -0
  32. package/dist/project-profiles.js.map +1 -0
  33. package/dist/proof.js +33 -0
  34. package/dist/proof.js.map +1 -0
  35. package/dist/remote.js +1 -1
  36. package/dist/runner.js +269 -287
  37. package/dist/runner.js.map +1 -1
  38. package/dist/scheduler.js +0 -3
  39. package/dist/scheduler.js.map +1 -1
  40. package/dist/schemas.js +156 -44
  41. package/dist/schemas.js.map +1 -1
  42. package/dist/store.js +166 -44
  43. package/dist/store.js.map +1 -1
  44. package/dist/vendor/obfuscator/dist/cli.js +72 -0
  45. package/dist/vendor/obfuscator/dist/cli.js.map +1 -0
  46. package/dist/vendor/obfuscator/dist/code.js +585 -0
  47. package/dist/vendor/obfuscator/dist/code.js.map +1 -0
  48. package/dist/vendor/obfuscator/dist/common.js +262 -0
  49. package/dist/vendor/obfuscator/dist/common.js.map +1 -0
  50. package/dist/vendor/obfuscator/dist/config.js +123 -0
  51. package/dist/vendor/obfuscator/dist/config.js.map +1 -0
  52. package/dist/vendor/obfuscator/dist/content.js +89 -0
  53. package/dist/vendor/obfuscator/dist/content.js.map +1 -0
  54. package/dist/vendor/obfuscator/dist/obfuscate.js +93 -0
  55. package/dist/vendor/obfuscator/dist/obfuscate.js.map +1 -0
  56. package/dist/vendor/obfuscator/dist/png.js +283 -0
  57. package/dist/vendor/obfuscator/dist/png.js.map +1 -0
  58. package/dist/vendor/obfuscator/dist/project.js +159 -0
  59. package/dist/vendor/obfuscator/dist/project.js.map +1 -0
  60. package/dist/vendor/obfuscator/dist/resources.js +335 -0
  61. package/dist/vendor/obfuscator/dist/resources.js.map +1 -0
  62. package/dist/vendor/obfuscator/package.json +22 -0
  63. package/dist/workspace.js +113 -0
  64. package/dist/workspace.js.map +1 -0
  65. package/evals/control.mjs +73 -0
  66. package/evals/expectations.mjs +37 -0
  67. package/evals/host.mjs +51 -0
  68. package/evals/oracle.mjs +80 -0
  69. package/evals/policy.mjs +268 -0
  70. package/examples/android-java.factory.json +18 -0
  71. package/examples/android-java.json +16 -0
  72. package/examples/existing-project.factory.json +18 -0
  73. package/examples/existing-project.json +17 -0
  74. package/examples/expo.eas.json +17 -0
  75. package/examples/expo.factory.json +18 -0
  76. package/examples/expo.json +16 -0
  77. package/examples/factory.json +0 -2
  78. package/examples/flutter.factory.json +13 -0
  79. package/examples/flutter.json +16 -0
  80. package/examples/luggage.json +5 -3
  81. package/examples/mygo-web.factory.json +18 -0
  82. package/examples/mygo-web.json +16 -0
  83. package/examples/mygo.factory.json +18 -0
  84. package/examples/mygo.json +16 -0
  85. package/examples/react-native.factory.json +18 -0
  86. package/examples/react-native.json +16 -0
  87. package/examples/remote.json +1 -1
  88. package/examples/runtime/android-java/app/build.gradle +7 -0
  89. package/examples/runtime/android-java/app/src/main/AndroidManifest.xml +8 -0
  90. package/examples/runtime/android-java/app/src/main/java/dev/apphx/runtime/MainActivity.java +44 -0
  91. package/examples/runtime/android-java/sdk-build.mjs +29 -0
  92. package/examples/runtime/android-java/settings.gradle +2 -0
  93. package/examples/runtime/android-ui.mjs +70 -0
  94. package/examples/runtime/mygo-native/go.mod +13 -0
  95. package/examples/runtime/mygo-native/go.sum +10 -0
  96. package/examples/runtime/mygo-native/main.go +173 -0
  97. package/examples/runtime/mygo-native/main_test.go +14 -0
  98. package/examples/runtime/mygo-native/mygo.json +1 -0
  99. package/examples/runtime/mygo-web/bun.lock +15 -0
  100. package/examples/runtime/mygo-web/go.mod +9 -0
  101. package/examples/runtime/mygo-web/go.sum +8 -0
  102. package/examples/runtime/mygo-web/index.html +1 -0
  103. package/examples/runtime/mygo-web/main.go +60 -0
  104. package/examples/runtime/mygo-web/mygo.config.ts +10 -0
  105. package/examples/runtime/mygo-web/package.json +1 -0
  106. package/examples/runtime/mygo-web/src/main.ts +23 -0
  107. package/examples/runtime/mygo-web/src/mygo.ts +14 -0
  108. package/examples/swift.factory.json +18 -0
  109. package/examples/swift.json +16 -0
  110. package/examples/uni-app.factory.json +18 -0
  111. package/examples/uni-app.json +16 -0
  112. package/package.json +12 -5
  113. package/scripts/bundle-obfuscator.mjs +19 -0
  114. package/scripts/runtime-smoke.mjs +209 -0
  115. package/skills/apphx/SKILL.md +180 -0
  116. package/skills/apphx/resources/google-play-research-result.json +6 -0
  117. package/skills/apphx/resources/local-research-result.json +6 -0
  118. package/skills/{apple-app-factory → apphx}/resources/requirement.json +5 -8
  119. package/skills/apphx/resources/research-result.json +12 -0
  120. package/skills/apphx/resources/review-result.json +7 -0
  121. package/dist/apple.js +0 -900
  122. package/dist/apple.js.map +0 -1
  123. package/skills/apple-app-factory/SKILL.md +0 -103
  124. package/skills/apple-app-factory/resources/research-result.json +0 -21
  125. package/skills/apple-app-factory/resources/review-result.json +0 -7
  126. /package/skills/{apple-app-factory → apphx}/LICENSE +0 -0
@@ -1,87 +1,87 @@
1
1
  import { z } from "zod";
2
- import { createHash } from "node:crypto";
3
- import { homedir } from "node:os";
4
- import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
5
2
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
4
+ import { homedir } from "node:os";
6
5
  import { fileURLToPath } from "node:url";
6
+ import { createHash } from "node:crypto";
7
7
  // src/integrations.ts
8
- const skill = "apple-app-factory";
9
- const marker = ".apple-app-factory-install.json";
10
- const owner = "apple-app-factory";
11
- const bundledDirectory = fileURLToPath(new URL("../skills/apple-app-factory/", import.meta.url));
8
+ const skill = "apphx";
9
+ const marker = ".apphx-install.json";
10
+ const owner = "apphx";
11
+ const bundledDirectory = fileURLToPath(new URL("../skills/apphx/", import.meta.url));
12
12
  const packageFile = fileURLToPath(new URL("../package.json", import.meta.url));
13
13
  const hosts = Object.freeze([
14
14
  {
15
15
  id: "codex",
16
16
  name: "Codex",
17
- invocation: "$apple-app-factory",
17
+ invocation: "$apphx",
18
18
  projectDirectory: ".agents/skills",
19
19
  globalDirectory: "~/.agents/skills",
20
20
  source: "https://developers.openai.com/codex/skills",
21
- instructions: "Use $apple-app-factory in Codex CLI or the IDE extension; /skills lists skills. Restart if discovery has not refreshed."
21
+ instructions: "Use $apphx in Codex CLI or the IDE extension; /skills lists skills. Restart if discovery has not refreshed."
22
22
  },
23
23
  {
24
24
  id: "claude",
25
25
  name: "Claude Code",
26
- invocation: "/apple-app-factory",
26
+ invocation: "/apphx",
27
27
  projectDirectory: ".claude/skills",
28
28
  globalDirectory: "$CLAUDE_CONFIG_DIR/skills (default ~/.claude/skills)",
29
29
  source: "https://code.claude.com/docs/en/skills",
30
- instructions: "Use /apple-app-factory in a local Claude Code session. Start a new session if the skill is not listed. Cloud sessions do not inherit local user skills."
30
+ instructions: "Use /apphx in a local Claude Code session. Start a new session if the skill is not listed. Cloud sessions do not inherit local user skills."
31
31
  },
32
32
  {
33
33
  id: "cursor",
34
34
  name: "Cursor",
35
- invocation: "/apple-app-factory",
35
+ invocation: "/apphx",
36
36
  projectDirectory: ".cursor/skills",
37
37
  globalDirectory: "~/.cursor/skills",
38
38
  source: "https://cursor.com/docs/skills",
39
- instructions: "In Agent chat, type / and select apple-app-factory. Restart or reopen the project if necessary. Global installation is local, not a Cloud Agent sync."
39
+ instructions: "In Agent chat, type / and select apphx. Restart or reopen the project if necessary. Global installation is local, not a Cloud Agent sync."
40
40
  },
41
41
  {
42
42
  id: "pi",
43
43
  name: "Pi",
44
- invocation: "/skill:apple-app-factory",
44
+ invocation: "/skill:apphx",
45
45
  projectDirectory: ".pi/skills",
46
46
  globalDirectory: "$PI_CODING_AGENT_DIR/skills (default ~/.pi/agent/skills)",
47
47
  source: "https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/skills.md",
48
- instructions: "Grant project trust before using project skills, then /reload and /skill:apple-app-factory. Stock Pi has no native subagents: use a separate human-started reviewer session, not a spawned coding-agent CLI."
48
+ instructions: "Grant project trust before using project skills, then /reload and /skill:apphx. Stock Pi has no native subagents: use a separate human-started reviewer session, not a spawned coding-agent CLI."
49
49
  },
50
50
  {
51
51
  id: "gemini",
52
52
  name: "Gemini CLI",
53
- invocation: "Use the apple-app-factory skill",
53
+ invocation: "Use the apphx skill",
54
54
  projectDirectory: ".gemini/skills",
55
55
  globalDirectory: "$GEMINI_CLI_HOME/.gemini/skills (default ~/.gemini/skills)",
56
56
  source: "https://geminicli.com/docs/cli/skills/",
57
- instructions: "Run /skills reload and /skills list, then ask: Use the apple-app-factory skill. Gemini calls activate_skill; approve its consent prompt. This is not a /apple-app-factory command."
57
+ instructions: "Run /skills reload and /skills list, then ask: Use the apphx skill. Gemini calls activate_skill; approve its consent prompt. This is not a /apphx command."
58
58
  },
59
59
  {
60
60
  id: "opencode",
61
61
  name: "OpenCode",
62
- invocation: "Use the apple-app-factory skill",
62
+ invocation: "Use the apphx skill",
63
63
  projectDirectory: ".opencode/skills",
64
64
  globalDirectory: "$XDG_CONFIG_HOME/opencode/skills (default ~/.config/opencode/skills)",
65
65
  source: "https://opencode.ai/docs/skills/",
66
- instructions: "Ask OpenCode to use apple-app-factory; the agent loads it with its native skill({ name: \"apple-app-factory\" }) tool. Skill permissions must permit loading. Restart if necessary; no custom slash command is installed."
66
+ instructions: "Ask OpenCode to use apphx; the agent loads it with its native skill({ name: \"apphx\" }) tool. Skill permissions must permit loading. Restart if necessary; no custom slash command is installed."
67
67
  },
68
68
  {
69
69
  id: "deepseek",
70
70
  name: "DeepSeek Harness",
71
- invocation: "Use the apple-app-factory skill",
71
+ invocation: "Use the apphx skill",
72
72
  projectDirectory: ".dsh/skills (nearest Git root, otherwise selected project)",
73
73
  globalDirectory: "$DSH_HOME/skills (default ~/.dsh/skills)",
74
74
  source: "https://deepseek-harness.github.io/deepseek-harness/en/reference/subsystems/skills",
75
- instructions: "Ask DeepSeek Harness to use apple-app-factory; its native skill({ name: \"apple-app-factory\" }) tool loads it. Requires the shipped filesystem skill provider and skill tool, with default roots enabled. Custom provider configurations are not modified."
75
+ instructions: "Ask DeepSeek Harness to use apphx; its native skill({ name: \"apphx\" }) tool loads it. Requires the shipped filesystem skill provider and skill tool, with default roots enabled. Custom provider configurations are not modified."
76
76
  },
77
77
  {
78
78
  id: "hermes",
79
79
  name: "Hermes Agent",
80
- invocation: "/apple-app-factory",
80
+ invocation: "/apphx",
81
81
  projectDirectory: ".hermes/skills",
82
82
  globalDirectory: "$HERMES_HOME/skills (default ~/.hermes/skills)",
83
83
  source: "https://hermes-agent.nousresearch.com/docs/user-guide/features/skills",
84
- instructions: "Use /apple-app-factory. Project installation requires a Git root and a separate owner-approved hermes skills trust decision; this installer never grants trust. For non-Git projects or profile-wide cron use --global in the same HERMES_HOME as Hermes. Confirm discovery with hermes skills list; cron must attach the skill and an absolute workdir."
84
+ instructions: "Use /apphx. Project installation requires a Git root and a separate owner-approved hermes skills trust decision; this installer never grants trust. For non-Git projects or profile-wide cron use --global in the same HERMES_HOME as Hermes. Confirm discovery with hermes skills list; cron must attach the skill and an absolute workdir."
85
85
  }
86
86
  ].map((host) => Object.freeze(host)));
87
87
  const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
@@ -260,7 +260,7 @@ function details(target) {
260
260
  }
261
261
  function bundle(host) {
262
262
  const tree = readTree(bundledDirectory, true);
263
- if (!tree.files["SKILL.md"] || tree.files[marker]) throw new Error("Invalid bundled apple-app-factory skill");
263
+ if (!tree.files["SKILL.md"] || tree.files[marker]) throw new Error("Invalid bundled apphx skill");
264
264
  const files = fileDigests(tree);
265
265
  if (!Object.keys(files).every(safeRelative) || JSON.stringify(tree.directories.sort()) !== JSON.stringify(directoriesFor(files))) throw new Error("Invalid bundled skill resource paths");
266
266
  const version = JSON.parse(readRegular(packageFile, true).toString("utf8")).version;
@@ -315,7 +315,7 @@ function withLock(target, action) {
315
315
  assertPath(directory);
316
316
  mkdirSync(directory, { recursive: true });
317
317
  assertPath(directory);
318
- const lock = join(directory, ".apple-app-factory-install.lock");
318
+ const lock = join(directory, ".apphx-install.lock");
319
319
  let descriptor;
320
320
  try {
321
321
  descriptor = openSync(lock, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 384);
@@ -333,11 +333,11 @@ function applyIntegration(host, options, operation) {
333
333
  const target = location(host, options);
334
334
  const next = bundle(host);
335
335
  assertPath(target.path);
336
- if (operation === "update" && !lstatSync(target.path, { throwIfNoEntry: false })) throw new Error(`No installation at ${target.path}; run app-factory install ${host} first with the same scope`);
336
+ if (operation === "update" && !lstatSync(target.path, { throwIfNoEntry: false })) throw new Error(`No installation at ${target.path}; run apphx install ${host} first with the same scope`);
337
337
  return withLock(target, () => {
338
338
  assertPath(target.path);
339
339
  const previous = lstatSync(target.path, { throwIfNoEntry: false }) ? readOwned(target.path, host) : void 0;
340
- if (operation === "update" && !previous) throw new Error(`No installation at ${target.path}; run app-factory install ${host} first with the same scope`);
340
+ if (operation === "update" && !previous) throw new Error(`No installation at ${target.path}; run apphx install ${host} first with the same scope`);
341
341
  const result = {
342
342
  ...details(target),
343
343
  installed: true,
@@ -349,10 +349,10 @@ function applyIntegration(host, options, operation) {
349
349
  ...result,
350
350
  changed: false
351
351
  };
352
- if (operation === "install" && previous) throw new Error(`An older or different workflow is installed at ${target.path}; use app-factory update ${host} with the same scope`);
352
+ if (operation === "install" && previous) throw new Error(`An older or different workflow is installed at ${target.path}; use apphx update ${host} with the same scope`);
353
353
  const parent = dirname(target.path);
354
354
  mkdirSync(parent, { recursive: true });
355
- const staging = mkdtempSync(join(dirname(parent), ".apple-app-factory-stage-"));
355
+ const staging = mkdtempSync(join(dirname(parent), ".apphx-stage-"));
356
356
  const replacement = join(staging, skill);
357
357
  const backup = join(staging, "previous");
358
358
  let moved = false;
@@ -1 +1 @@
1
- {"version":3,"file":"integrations.js","names":[],"sources":["../src/integrations.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { closeSync, constants, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { z } from 'zod';\n\n// Installation identity follows the skill, not the npm distribution name.\nconst skill = 'apple-app-factory';\nconst marker = '.apple-app-factory-install.json';\nconst owner = 'apple-app-factory';\nconst bundledDirectory = fileURLToPath(new URL('../skills/apple-app-factory/', import.meta.url));\nconst packageFile = fileURLToPath(new URL('../package.json', import.meta.url));\n\nexport const hosts = Object.freeze([\n { id: 'codex', name: 'Codex', invocation: '$apple-app-factory', projectDirectory: '.agents/skills', globalDirectory: '~/.agents/skills', source: 'https://developers.openai.com/codex/skills', instructions: 'Use $apple-app-factory in Codex CLI or the IDE extension; /skills lists skills. Restart if discovery has not refreshed.' },\n { id: 'claude', name: 'Claude Code', invocation: '/apple-app-factory', projectDirectory: '.claude/skills', globalDirectory: '$CLAUDE_CONFIG_DIR/skills (default ~/.claude/skills)', source: 'https://code.claude.com/docs/en/skills', instructions: 'Use /apple-app-factory in a local Claude Code session. Start a new session if the skill is not listed. Cloud sessions do not inherit local user skills.' },\n { id: 'cursor', name: 'Cursor', invocation: '/apple-app-factory', projectDirectory: '.cursor/skills', globalDirectory: '~/.cursor/skills', source: 'https://cursor.com/docs/skills', instructions: 'In Agent chat, type / and select apple-app-factory. Restart or reopen the project if necessary. Global installation is local, not a Cloud Agent sync.' },\n { id: 'pi', name: 'Pi', invocation: '/skill:apple-app-factory', projectDirectory: '.pi/skills', globalDirectory: '$PI_CODING_AGENT_DIR/skills (default ~/.pi/agent/skills)', source: 'https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/skills.md', instructions: 'Grant project trust before using project skills, then /reload and /skill:apple-app-factory. Stock Pi has no native subagents: use a separate human-started reviewer session, not a spawned coding-agent CLI.' },\n { id: 'gemini', name: 'Gemini CLI', invocation: 'Use the apple-app-factory skill', projectDirectory: '.gemini/skills', globalDirectory: '$GEMINI_CLI_HOME/.gemini/skills (default ~/.gemini/skills)', source: 'https://geminicli.com/docs/cli/skills/', instructions: 'Run /skills reload and /skills list, then ask: Use the apple-app-factory skill. Gemini calls activate_skill; approve its consent prompt. This is not a /apple-app-factory command.' },\n { id: 'opencode', name: 'OpenCode', invocation: 'Use the apple-app-factory skill', projectDirectory: '.opencode/skills', globalDirectory: '$XDG_CONFIG_HOME/opencode/skills (default ~/.config/opencode/skills)', source: 'https://opencode.ai/docs/skills/', instructions: 'Ask OpenCode to use apple-app-factory; the agent loads it with its native skill({ name: \"apple-app-factory\" }) tool. Skill permissions must permit loading. Restart if necessary; no custom slash command is installed.' },\n { id: 'deepseek', name: 'DeepSeek Harness', invocation: 'Use the apple-app-factory skill', projectDirectory: '.dsh/skills (nearest Git root, otherwise selected project)', globalDirectory: '$DSH_HOME/skills (default ~/.dsh/skills)', source: 'https://deepseek-harness.github.io/deepseek-harness/en/reference/subsystems/skills', instructions: 'Ask DeepSeek Harness to use apple-app-factory; its native skill({ name: \"apple-app-factory\" }) tool loads it. Requires the shipped filesystem skill provider and skill tool, with default roots enabled. Custom provider configurations are not modified.' },\n { id: 'hermes', name: 'Hermes Agent', invocation: '/apple-app-factory', projectDirectory: '.hermes/skills', globalDirectory: '$HERMES_HOME/skills (default ~/.hermes/skills)', source: 'https://hermes-agent.nousresearch.com/docs/user-guide/features/skills', instructions: 'Use /apple-app-factory. Project installation requires a Git root and a separate owner-approved hermes skills trust decision; this installer never grants trust. For non-Git projects or profile-wide cron use --global in the same HERMES_HOME as Hermes. Confirm discovery with hermes skills list; cron must attach the skill and an absolute workdir.' },\n].map(host => Object.freeze(host)));\n\nexport type IntegrationOptions = { project?: string; global?: boolean };\ntype Host = (typeof hosts)[number];\ntype Location = { host: Host; scope: 'project' | 'global'; path: string };\nexport type IntegrationInspection = {\n host: string; name: string; scope: 'project' | 'global'; path: string;\n invocation: string; instructions: string; source: string;\n installed: boolean; status: 'missing' | 'installed' | 'conflict';\n version?: string; current?: boolean; reason?: string;\n};\n\ntype Tree = { files: Record<string, Buffer>; directories: string[] };\nconst digest = (bytes: string | Buffer) => createHash('sha256').update(bytes).digest('hex');\nconst safeRelative = (path: string) => /^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(path) && path.split('/').every(part => part !== '.' && part !== '..' && part.length > 0) && path !== marker;\nconst digestSchema = z.string().regex(/^[a-f0-9]{64}$/);\nconst manifestSchema = z.strictObject({\n format: z.literal(1), owner: z.literal(owner), skill: z.literal(skill), host: z.string(),\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+(?:-[\\w.-]+)?(?:\\+[\\w.-]+)?$/),\n files: z.record(z.string().refine(safeRelative), digestSchema), metadataDigest: digestSchema,\n});\ntype Manifest = z.infer<typeof manifestSchema>;\n\n// Never follow a symlink, including an existing ancestor of a not-yet-created target.\nfunction assertPath(path: string): void {\n const absolute = resolve(path);\n let current = parse(absolute).root;\n const parts = absolute.slice(current.length).split(sep).filter(Boolean);\n for (let i = 0; i < parts.length; i++) {\n current = join(current, parts[i]!);\n const info = lstatSync(current, { throwIfNoEntry: false });\n if (!info) return;\n if (info.isSymbolicLink()) throw new Error(`Refusing symlink path: ${current}. Select its real directory explicitly.`);\n if (i < parts.length - 1 && !info.isDirectory()) throw new Error(`Not a directory: ${current}`);\n }\n}\n\nfunction readRegular(path: string, packageSource = false): Buffer {\n assertPath(path);\n const descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n try {\n const info = fstatSync(descriptor);\n if (!info.isFile() || (!packageSource && info.nlink !== 1)) throw new Error(`Refusing non-regular or hard-linked installation file: ${path}`);\n return readFileSync(descriptor);\n } finally { closeSync(descriptor); }\n}\n\nfunction readTree(root: string, packageSource = false): Tree {\n assertPath(root);\n if (!lstatSync(root).isDirectory()) throw new Error(`Not a skill directory: ${root}`);\n const tree: Tree = { files: Object.create(null), directories: [] };\n function visit(directory: string, prefix: string): void {\n for (const name of readdirSync(directory).sort()) {\n const path = join(directory, name);\n const relative = prefix ? `${prefix}/${name}` : name;\n const info = lstatSync(path);\n if (info.isSymbolicLink()) throw new Error(`Refusing symlink installation entry: ${path}`);\n if (info.isDirectory()) { tree.directories.push(relative); visit(path, relative); }\n else tree.files[relative] = readRegular(path, packageSource);\n }\n }\n visit(root, '');\n return tree;\n}\n\nfunction fileDigests(tree: Tree): Record<string, string> {\n return Object.fromEntries(Object.entries(tree.files).filter(([path]) => path !== marker).map(([path, bytes]) => [path, digest(bytes)]));\n}\n\nfunction metadataDigest(value: Omit<Manifest, 'metadataDigest'>): string {\n return digest(JSON.stringify([value.format, value.owner, value.skill, value.host, value.version, Object.entries(value.files).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)]));\n}\n\nfunction directoriesFor(files: Record<string, unknown>): string[] {\n const directories = new Set<string>();\n for (const file of Object.keys(files)) {\n let parent = file.slice(0, file.lastIndexOf('/'));\n if (!file.includes('/')) continue;\n while (parent) { directories.add(parent); parent = parent.includes('/') ? parent.slice(0, parent.lastIndexOf('/')) : ''; }\n }\n return [...directories].sort();\n}\n\nfunction readOwned(path: string, host: string): Manifest {\n const tree = readTree(path);\n if (!tree.files[marker]) throw new Error(`Foreign skill directory has no ${marker}: ${path}`);\n let manifest: Manifest;\n try { manifest = manifestSchema.parse(JSON.parse(tree.files[marker].toString('utf8'))); }\n catch { throw new Error(`Invalid ownership metadata: ${path}`); }\n if (manifest.host !== host || manifest.metadataDigest !== metadataDigest(manifest)) throw new Error(`Foreign or edited ownership metadata: ${path}`);\n if (!manifest.files['SKILL.md'] || JSON.stringify(Object.keys(tree.files).filter(file => file !== marker).sort()) !== JSON.stringify(Object.keys(manifest.files).sort())) throw new Error(`Added or missing files in owned skill: ${path}`);\n for (const [file, expected] of Object.entries(manifest.files)) {\n if (digest(tree.files[file]!) !== expected) throw new Error(`User-edited skill file: ${join(path, file)}`);\n }\n if (JSON.stringify(tree.directories.sort()) !== JSON.stringify(directoriesFor(manifest.files))) throw new Error(`Unowned directories in skill: ${path}`);\n return manifest;\n}\n\nfunction selectedHost(id: string): Host {\n const host = hosts.find(value => value.id === id);\n if (!host) throw new Error(`Unsupported host ${JSON.stringify(id)}. Supported hosts: ${hosts.map(value => value.id).join(', ')}`);\n return host;\n}\n\nfunction environmentDirectory(name: string, fallback: string): string {\n const configured = process.env[name];\n if (!configured) return fallback;\n const expanded = configured === '~' ? homedir() : configured.startsWith('~/') ? join(homedir(), configured.slice(2)) : configured;\n if (!isAbsolute(expanded)) throw new Error(`${name} must be an absolute directory for installation`);\n return resolve(expanded);\n}\n\nfunction location(id: string, options: IntegrationOptions): Location {\n const host = selectedHost(id);\n if (options.global && options.project !== undefined) throw new Error('Choose either project or global installation, not both');\n if (options.global) {\n let directory: string;\n switch (id) {\n case 'claude': directory = join(environmentDirectory('CLAUDE_CONFIG_DIR', join(homedir(), '.claude')), 'skills'); break;\n case 'gemini': directory = join(environmentDirectory('GEMINI_CLI_HOME', homedir()), '.gemini', 'skills'); break;\n case 'pi': directory = join(environmentDirectory('PI_CODING_AGENT_DIR', join(homedir(), '.pi', 'agent')), 'skills'); break;\n case 'opencode': directory = join(environmentDirectory('XDG_CONFIG_HOME', join(homedir(), '.config')), 'opencode', 'skills'); break;\n case 'deepseek': directory = join(environmentDirectory('DSH_HOME', join(homedir(), '.dsh')), 'skills'); break;\n case 'hermes': directory = join(environmentDirectory('HERMES_HOME', join(homedir(), '.hermes')), 'skills'); break;\n default: directory = join(homedir(), host.projectDirectory);\n }\n return { host, scope: 'global', path: join(directory, skill) };\n }\n if (options.project !== undefined && !options.project.trim()) throw new Error('Project directory must not be empty');\n let project = resolve(options.project ?? process.cwd());\n assertPath(project);\n if (!lstatSync(project, { throwIfNoEntry: false })?.isDirectory()) throw new Error(`Project directory does not exist: ${project}`);\n if (id === 'deepseek' || id === 'hermes') {\n let found = false;\n for (let candidate = project; ; candidate = dirname(candidate)) {\n if (lstatSync(join(candidate, '.git'), { throwIfNoEntry: false })) { project = candidate; found = true; break; }\n if (dirname(candidate) === candidate) break;\n }\n if (id === 'hermes' && !found) throw new Error('Hermes project skills require a Git root; use --global for a profile-level installation instead');\n }\n return { host, scope: 'project', path: join(project, id === 'deepseek' ? '.dsh/skills' : host.projectDirectory, skill) };\n}\n\nfunction details(target: Location) {\n return { host: target.host.id, name: target.host.name, scope: target.scope, path: target.path, invocation: target.host.invocation, instructions: target.host.instructions, source: target.host.source };\n}\n\nfunction bundle(host: string): { tree: Tree; manifest: Manifest } {\n // Package stores may hard-link read-only resources; owned installation targets may not.\n const tree = readTree(bundledDirectory, true);\n if (!tree.files['SKILL.md'] || tree.files[marker]) throw new Error('Invalid bundled apple-app-factory skill');\n const files = fileDigests(tree);\n if (!Object.keys(files).every(safeRelative) || JSON.stringify(tree.directories.sort()) !== JSON.stringify(directoriesFor(files))) throw new Error('Invalid bundled skill resource paths');\n const version = JSON.parse(readRegular(packageFile, true).toString('utf8')).version;\n const value: Omit<Manifest, 'metadataDigest'> = { format: 1, owner, skill, host, version, files };\n const manifest = manifestSchema.parse({ ...value, metadataDigest: metadataDigest(value) });\n tree.files[marker] = Buffer.from(`${JSON.stringify(manifest, null, 2)}\\n`);\n return { tree, manifest };\n}\n\nexport function inspectIntegration(host: string, options: IntegrationOptions = {}): IntegrationInspection {\n const target = location(host, options);\n const result = details(target);\n try {\n assertPath(target.path);\n if (!lstatSync(target.path, { throwIfNoEntry: false })) return { ...result, installed: false, status: 'missing' };\n const manifest = readOwned(target.path, host);\n const current = bundle(host).manifest.metadataDigest === manifest.metadataDigest;\n return { ...result, installed: true, status: 'installed', version: manifest.version, current };\n } catch (error) {\n return { ...result, installed: false, status: 'conflict', reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\nfunction withLock<T>(target: Location, action: () => T): T {\n const directory = dirname(dirname(target.path));\n assertPath(directory);\n mkdirSync(directory, { recursive: true });\n assertPath(directory);\n const lock = join(directory, '.apple-app-factory-install.lock');\n let descriptor: number;\n try { descriptor = openSync(lock, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); }\n catch { throw new Error(`Installation is locked at ${lock}; if an earlier installer stopped, inspect it before removing its lock`); }\n try { return action(); }\n finally { closeSync(descriptor); unlinkSync(lock); }\n}\n\nfunction applyIntegration(host: string, options: IntegrationOptions, operation: 'install' | 'update'): IntegrationInspection & { changed: boolean } {\n const target = location(host, options);\n const next = bundle(host);\n assertPath(target.path);\n if (operation === 'update' && !lstatSync(target.path, { throwIfNoEntry: false })) throw new Error(`No installation at ${target.path}; run app-factory install ${host} first with the same scope`);\n return withLock(target, () => {\n assertPath(target.path);\n const previous = lstatSync(target.path, { throwIfNoEntry: false }) ? readOwned(target.path, host) : undefined;\n if (operation === 'update' && !previous) throw new Error(`No installation at ${target.path}; run app-factory install ${host} first with the same scope`);\n const result = { ...details(target), installed: true, status: 'installed' as const, version: next.manifest.version, current: true };\n if (previous?.metadataDigest === next.manifest.metadataDigest) return { ...result, changed: false };\n if (operation === 'install' && previous) throw new Error(`An older or different workflow is installed at ${target.path}; use app-factory update ${host} with the same scope`);\n const parent = dirname(target.path);\n mkdirSync(parent, { recursive: true });\n const staging = mkdtempSync(join(dirname(parent), '.apple-app-factory-stage-'));\n const replacement = join(staging, skill);\n const backup = join(staging, 'previous');\n let moved = false;\n try {\n mkdirSync(replacement);\n for (const [file, bytes] of Object.entries(next.tree.files)) {\n const path = join(replacement, file);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, bytes, { flag: 'wx', mode: 0o644 });\n }\n assertPath(target.path);\n if (previous) {\n if (readOwned(target.path, host).metadataDigest !== previous.metadataDigest) throw new Error('Installation changed during upgrade');\n renameSync(target.path, backup);\n moved = true;\n } else if (lstatSync(target.path, { throwIfNoEntry: false })) throw new Error('Skill appeared during installation; refusing overwrite');\n try { renameSync(replacement, target.path); }\n catch (error) { if (moved) { renameSync(backup, target.path); moved = false; } throw error; }\n if (moved) { readOwned(backup, host); rmSync(backup, { recursive: true }); moved = false; }\n return { ...result, changed: true };\n } finally {\n // Keep a displaced install intact if rollback or cleanup was interrupted.\n if (!moved) rmSync(staging, { recursive: true, force: true });\n }\n });\n}\n\nexport function installIntegration(host: string, options: IntegrationOptions = {}): IntegrationInspection & { changed: boolean } {\n return applyIntegration(host, options, 'install');\n}\n\nexport function updateIntegration(host: string, options: IntegrationOptions = {}): IntegrationInspection & { changed: boolean } {\n return applyIntegration(host, options, 'update');\n}\n\nexport function uninstallIntegration(host: string, options: IntegrationOptions = {}): IntegrationInspection & { changed: boolean } {\n const target = location(host, options);\n assertPath(target.path);\n const result = { ...details(target), installed: false, status: 'missing' as const };\n if (!lstatSync(target.path, { throwIfNoEntry: false })) return { ...result, changed: false };\n return withLock(target, () => {\n assertPath(target.path);\n if (!lstatSync(target.path, { throwIfNoEntry: false })) return { ...result, changed: false };\n readOwned(target.path, host);\n rmSync(target.path, { recursive: true });\n return { ...result, changed: true };\n });\n}\n"],"mappings":";;;;;;;AAQA,MAAM,QAAQ;AACd,MAAM,SAAS;AACf,MAAM,QAAQ;AACd,MAAM,mBAAmB,cAAc,IAAI,IAAI,gCAAgC,YAAY,GAAG,CAAC;AAC/F,MAAM,cAAc,cAAc,IAAI,IAAI,mBAAmB,YAAY,GAAG,CAAC;AAE7E,MAAa,QAAQ,OAAO,OAAO;CACjC;EAAE,IAAI;EAAS,MAAM;EAAS,YAAY;EAAsB,kBAAkB;EAAkB,iBAAiB;EAAoB,QAAQ;EAA8C,cAAc;CAA0H;CACvU;EAAE,IAAI;EAAU,MAAM;EAAe,YAAY;EAAsB,kBAAkB;EAAkB,iBAAiB;EAAwD,QAAQ;EAA0C,cAAc;CAA0J;CAC9Y;EAAE,IAAI;EAAU,MAAM;EAAU,YAAY;EAAsB,kBAAkB;EAAkB,iBAAiB;EAAoB,QAAQ;EAAkC,cAAc;CAAwJ;CAC3V;EAAE,IAAI;EAAM,MAAM;EAAM,YAAY;EAA4B,kBAAkB;EAAc,iBAAiB;EAA4D,QAAQ;EAAsF,cAAc;CAA+M;CACxe;EAAE,IAAI;EAAU,MAAM;EAAc,YAAY;EAAmC,kBAAkB;EAAkB,iBAAiB;EAA8D,QAAQ;EAA0C,cAAc;CAAqL;CAC3b;EAAE,IAAI;EAAY,MAAM;EAAY,YAAY;EAAmC,kBAAkB;EAAoB,iBAAiB;EAAwE,QAAQ;EAAoC,cAAc;CAA0N;CACte;EAAE,IAAI;EAAY,MAAM;EAAoB,YAAY;EAAmC,kBAAkB;EAA8D,iBAAiB;EAA4C,QAAQ;EAAsF,cAAc;CAA4P;CAChlB;EAAE,IAAI;EAAU,MAAM;EAAgB,YAAY;EAAsB,kBAAkB;EAAkB,iBAAiB;EAAkD,QA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Sync, constants, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { z } from 'zod';\n\nconst skill = 'apphx';\nconst marker = '.apphx-install.json';\nconst owner = 'apphx';\nconst bundledDirectory = fileURLToPath(new URL('../skills/apphx/', import.meta.url));\nconst packageFile = fileURLToPath(new URL('../package.json', import.meta.url));\n\nexport const hosts = Object.freeze([\n { id: 'codex', name: 'Codex', invocation: '$apphx', projectDirectory: '.agents/skills', globalDirectory: '~/.agents/skills', source: 'https://developers.openai.com/codex/skills', instructions: 'Use $apphx in Codex CLI or the IDE extension; /skills lists skills. Restart if discovery has not refreshed.' },\n { id: 'claude', name: 'Claude Code', invocation: '/apphx', projectDirectory: '.claude/skills', globalDirectory: '$CLAUDE_CONFIG_DIR/skills (default ~/.claude/skills)', source: 'https://code.claude.com/docs/en/skills', instructions: 'Use /apphx in a local Claude Code session. Start a new session if the skill is not listed. Cloud sessions do not inherit local user skills.' },\n { id: 'cursor', name: 'Cursor', invocation: '/apphx', projectDirectory: '.cursor/skills', globalDirectory: '~/.cursor/skills', source: 'https://cursor.com/docs/skills', instructions: 'In Agent chat, type / and select apphx. Restart or reopen the project if necessary. Global installation is local, not a Cloud Agent sync.' },\n { id: 'pi', name: 'Pi', invocation: '/skill:apphx', projectDirectory: '.pi/skills', globalDirectory: '$PI_CODING_AGENT_DIR/skills (default ~/.pi/agent/skills)', source: 'https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/skills.md', instructions: 'Grant project trust before using project skills, then /reload and /skill:apphx. Stock Pi has no native subagents: use a separate human-started reviewer session, not a spawned coding-agent CLI.' },\n { id: 'gemini', name: 'Gemini CLI', invocation: 'Use the apphx skill', projectDirectory: '.gemini/skills', globalDirectory: '$GEMINI_CLI_HOME/.gemini/skills (default ~/.gemini/skills)', source: 'https://geminicli.com/docs/cli/skills/', instructions: 'Run /skills reload and /skills list, then ask: Use the apphx skill. Gemini calls activate_skill; approve its consent prompt. This is not a /apphx command.' },\n { id: 'opencode', name: 'OpenCode', invocation: 'Use the apphx skill', projectDirectory: '.opencode/skills', globalDirectory: '$XDG_CONFIG_HOME/opencode/skills (default ~/.config/opencode/skills)', source: 'https://opencode.ai/docs/skills/', instructions: 'Ask OpenCode to use apphx; the agent loads it with its native skill({ name: \"apphx\" }) tool. Skill permissions must permit loading. Restart if necessary; no custom slash command is installed.' },\n { id: 'deepseek', name: 'DeepSeek Harness', invocation: 'Use the apphx skill', projectDirectory: '.dsh/skills (nearest Git root, otherwise selected project)', globalDirectory: '$DSH_HOME/skills (default ~/.dsh/skills)', source: 'https://deepseek-harness.github.io/deepseek-harness/en/reference/subsystems/skills', instructions: 'Ask DeepSeek Harness to use apphx; its native skill({ name: \"apphx\" }) tool loads it. Requires the shipped filesystem skill provider and skill tool, with default roots enabled. Custom provider configurations are not modified.' },\n { id: 'hermes', name: 'Hermes Agent', invocation: '/apphx', projectDirectory: '.hermes/skills', globalDirectory: '$HERMES_HOME/skills (default ~/.hermes/skills)', source: 'https://hermes-agent.nousresearch.com/docs/user-guide/features/skills', instructions: 'Use /apphx. Project installation requires a Git root and a separate owner-approved hermes skills trust decision; this installer never grants trust. For non-Git projects or profile-wide cron use --global in the same HERMES_HOME as Hermes. Confirm discovery with hermes skills list; cron must attach the skill and an absolute workdir.' },\n].map(host => Object.freeze(host)));\n\nexport type IntegrationOptions = { project?: string; global?: boolean };\ntype Host = (typeof hosts)[number];\ntype Location = { host: Host; scope: 'project' | 'global'; path: string };\nexport type IntegrationInspection = {\n host: string; name: string; scope: 'project' | 'global'; path: string;\n invocation: string; instructions: string; source: string;\n installed: boolean; status: 'missing' | 'installed' | 'conflict';\n version?: string; current?: boolean; reason?: string;\n};\n\ntype Tree = { files: Record<string, Buffer>; directories: string[] };\nconst digest = (bytes: string | Buffer) => createHash('sha256').update(bytes).digest('hex');\nconst safeRelative = (path: string) => /^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(path) && path.split('/').every(part => part !== '.' && part !== '..' && part.length > 0) && path !== marker;\nconst digestSchema = z.string().regex(/^[a-f0-9]{64}$/);\nconst manifestSchema = z.strictObject({\n format: z.literal(1), owner: z.literal(owner), skill: z.literal(skill), host: z.string(),\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+(?:-[\\w.-]+)?(?:\\+[\\w.-]+)?$/),\n files: z.record(z.string().refine(safeRelative), digestSchema), metadataDigest: digestSchema,\n});\ntype Manifest = z.infer<typeof manifestSchema>;\n\n// Never follow a symlink, including an existing ancestor of a not-yet-created target.\nfunction assertPath(path: string): void {\n const absolute = resolve(path);\n let current = parse(absolute).root;\n const parts = absolute.slice(current.length).split(sep).filter(Boolean);\n for (let i = 0; i < parts.length; i++) {\n current = join(current, parts[i]!);\n const info = lstatSync(current, { throwIfNoEntry: false });\n if (!info) return;\n if (info.isSymbolicLink()) throw new Error(`Refusing symlink path: ${current}. Select its real directory explicitly.`);\n if (i < parts.length - 1 && !info.isDirectory()) throw new Error(`Not a directory: ${current}`);\n }\n}\n\nfunction readRegular(path: string, packageSource = false): Buffer {\n assertPath(path);\n const descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n try {\n const info = fstatSync(descriptor);\n if (!info.isFile() || (!packageSource && info.nlink !== 1)) throw new Error(`Refusing non-regular or hard-linked installation file: ${path}`);\n return readFileSync(descriptor);\n } finally { closeSync(descriptor); }\n}\n\nfunction readTree(root: string, packageSource = false): Tree {\n assertPath(root);\n if (!lstatSync(root).isDirectory()) throw new Error(`Not a skill directory: ${root}`);\n const tree: Tree = { files: Object.create(null), directories: [] };\n function visit(directory: string, prefix: string): void {\n for (const name of readdirSync(directory).sort()) {\n const path = join(directory, name);\n const relative = prefix ? `${prefix}/${name}` : name;\n const info = lstatSync(path);\n if (info.isSymbolicLink()) throw new Error(`Refusing symlink installation entry: ${path}`);\n if (info.isDirectory()) { tree.directories.push(relative); visit(path, relative); }\n else tree.files[relative] = readRegular(path, packageSource);\n }\n }\n visit(root, '');\n return tree;\n}\n\nfunction fileDigests(tree: Tree): Record<string, string> {\n return Object.fromEntries(Object.entries(tree.files).filter(([path]) => path !== marker).map(([path, bytes]) => [path, digest(bytes)]));\n}\n\nfunction metadataDigest(value: Omit<Manifest, 'metadataDigest'>): string {\n return digest(JSON.stringify([value.format, value.owner, value.skill, value.host, value.version, Object.entries(value.files).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)]));\n}\n\nfunction directoriesFor(files: Record<string, unknown>): string[] {\n const directories = new Set<string>();\n for (const file of Object.keys(files)) {\n let parent = file.slice(0, file.lastIndexOf('/'));\n if (!file.includes('/')) continue;\n while (parent) { directories.add(parent); parent = parent.includes('/') ? parent.slice(0, parent.lastIndexOf('/')) : ''; }\n }\n return [...directories].sort();\n}\n\nfunction readOwned(path: string, host: string): Manifest {\n const tree = readTree(path);\n if (!tree.files[marker]) throw new Error(`Foreign skill directory has no ${marker}: ${path}`);\n let manifest: Manifest;\n try { manifest = manifestSchema.parse(JSON.parse(tree.files[marker].toString('utf8'))); }\n catch { throw new Error(`Invalid ownership metadata: ${path}`); }\n if (manifest.host !== host || manifest.metadataDigest !== metadataDigest(manifest)) throw new Error(`Foreign or edited ownership metadata: ${path}`);\n if (!manifest.files['SKILL.md'] || JSON.stringify(Object.keys(tree.files).filter(file => file !== marker).sort()) !== JSON.stringify(Object.keys(manifest.files).sort())) throw new Error(`Added or missing files in owned skill: ${path}`);\n for (const [file, expected] of Object.entries(manifest.files)) {\n if (digest(tree.files[file]!) !== expected) throw new Error(`User-edited skill file: ${join(path, file)}`);\n }\n if (JSON.stringify(tree.directories.sort()) !== JSON.stringify(directoriesFor(manifest.files))) throw new Error(`Unowned directories in skill: ${path}`);\n return manifest;\n}\n\nfunction selectedHost(id: string): Host {\n const host = hosts.find(value => value.id === id);\n if (!host) throw new Error(`Unsupported host ${JSON.stringify(id)}. Supported hosts: ${hosts.map(value => value.id).join(', ')}`);\n return host;\n}\n\nfunction environmentDirectory(name: string, fallback: string): string {\n const configured = process.env[name];\n if (!configured) return fallback;\n const expanded = configured === '~' ? homedir() : configured.startsWith('~/') ? join(homedir(), configured.slice(2)) : configured;\n if (!isAbsolute(expanded)) throw new Error(`${name} must be an absolute directory for installation`);\n return resolve(expanded);\n}\n\nfunction location(id: string, options: IntegrationOptions): Location {\n const host = selectedHost(id);\n if (options.global && options.project !== undefined) throw new Error('Choose either project or global installation, not both');\n if (options.global) {\n let directory: string;\n switch (id) {\n case 'claude': directory = join(environmentDirectory('CLAUDE_CONFIG_DIR', join(homedir(), '.claude')), 'skills'); break;\n case 'gemini': directory = join(environmentDirectory('GEMINI_CLI_HOME', homedir()), '.gemini', 'skills'); break;\n case 'pi': directory = join(environmentDirectory('PI_CODING_AGENT_DIR', join(homedir(), '.pi', 'agent')), 'skills'); break;\n case 'opencode': directory = join(environmentDirectory('XDG_CONFIG_HOME', join(homedir(), '.config')), 'opencode', 'skills'); break;\n case 'deepseek': directory = join(environmentDirectory('DSH_HOME', join(homedir(), '.dsh')), 'skills'); break;\n case 'hermes': directory = join(environmentDirectory('HERMES_HOME', join(homedir(), '.hermes')), 'skills'); break;\n default: directory = join(homedir(), host.projectDirectory);\n }\n return { host, scope: 'global', path: join(directory, skill) };\n }\n if (options.project !== undefined && !options.project.trim()) throw new Error('Project directory must not be empty');\n let project = resolve(options.project ?? process.cwd());\n assertPath(project);\n if (!lstatSync(project, { throwIfNoEntry: false })?.isDirectory()) throw new Error(`Project directory does not exist: ${project}`);\n if (id === 'deepseek' || id === 'hermes') {\n let found = false;\n for (let candidate = project; ; candidate = dirname(candidate)) {\n if (lstatSync(join(candidate, '.git'), { throwIfNoEntry: false })) { project = candidate; found = true; break; }\n if (dirname(candidate) === candidate) break;\n }\n if (id === 'hermes' && !found) throw new Error('Hermes project skills require a Git root; use --global for a profile-level installation instead');\n }\n return { host, scope: 'project', path: join(project, id === 'deepseek' ? '.dsh/skills' : host.projectDirectory, skill) };\n}\n\nfunction details(target: Location) {\n return { host: target.host.id, name: target.host.name, scope: target.scope, path: target.path, invocation: target.host.invocation, instructions: target.host.instructions, source: target.host.source };\n}\n\nfunction bundle(host: string): { tree: Tree; manifest: Manifest } {\n // Package stores may hard-link read-only resources; owned installation targets may not.\n const tree = readTree(bundledDirectory, true);\n if (!tree.files['SKILL.md'] || tree.files[marker]) throw new Error('Invalid bundled apphx skill');\n const files = fileDigests(tree);\n if (!Object.keys(files).every(safeRelative) || JSON.stringify(tree.directories.sort()) !== JSON.stringify(directoriesFor(files))) throw new Error('Invalid bundled skill resource paths');\n const version = JSON.parse(readRegular(packageFile, true).toString('utf8')).version;\n const value: Omit<Manifest, 'metadataDigest'> = { format: 1, owner, skill, host, version, files };\n const manifest = manifestSchema.parse({ ...value, metadataDigest: metadataDigest(value) });\n tree.files[marker] = Buffer.from(`${JSON.stringify(manifest, null, 2)}\\n`);\n return { tree, manifest };\n}\n\nexport function inspectIntegration(host: string, options: IntegrationOptions = {}): IntegrationInspection {\n const target = location(host, options);\n const result = details(target);\n try {\n assertPath(target.path);\n if (!lstatSync(target.path, { throwIfNoEntry: false })) return { ...result, installed: false, status: 'missing' };\n const manifest = readOwned(target.path, host);\n const current = bundle(host).manifest.metadataDigest === manifest.metadataDigest;\n return { ...result, installed: true, status: 'installed', version: manifest.version, current };\n } catch (error) {\n return { ...result, installed: false, status: 'conflict', reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\nfunction withLock<T>(target: Location, action: () => T): T {\n const directory = dirname(dirname(target.path));\n assertPath(directory);\n mkdirSync(directory, { recursive: true });\n assertPath(directory);\n const lock = join(directory, '.apphx-install.lock');\n let descriptor: number;\n try { descriptor = openSync(lock, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); }\n catch { throw new Error(`Installation is locked at ${lock}; if an earlier installer stopped, inspect it before removing its lock`); }\n try { return action(); }\n finally { closeSync(descriptor); unlinkSync(lock); }\n}\n\nfunction applyIntegration(host: string, options: IntegrationOptions, operation: 'install' | 'update'): IntegrationInspection & { changed: boolean } {\n const target = location(host, options);\n const next = bundle(host);\n assertPath(target.path);\n if (operation === 'update' && !lstatSync(target.path, { throwIfNoEntry: false })) throw new Error(`No installation at ${target.path}; run apphx install ${host} first with the same scope`);\n return withLock(target, () => {\n assertPath(target.path);\n const previous = lstatSync(target.path, { throwIfNoEntry: false }) ? readOwned(target.path, host) : undefined;\n if (operation === 'update' && !previous) throw new Error(`No installation at ${target.path}; run apphx install ${host} first with the same scope`);\n const result = { ...details(target), installed: true, status: 'installed' as const, version: next.manifest.version, current: true };\n if (previous?.metadataDigest === next.manifest.metadataDigest) return { ...result, changed: false };\n if (operation === 'install' && previous) throw new Error(`An older or different workflow is installed at ${target.path}; use apphx update ${host} with the same scope`);\n const parent = dirname(target.path);\n mkdirSync(parent, { recursive: true });\n const staging = mkdtempSync(join(dirname(parent), '.apphx-stage-'));\n const replacement = join(staging, skill);\n const backup = join(staging, 'previous');\n let moved = false;\n try {\n mkdirSync(replacement);\n for (const [file, bytes] of Object.entries(next.tree.files)) {\n const path = join(replacement, file);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, bytes, { flag: 'wx', mode: 0o644 });\n }\n assertPath(target.path);\n if (previous) {\n if (readOwned(target.path, host).metadataDigest !== previous.metadataDigest) throw new Error('Installation changed during upgrade');\n renameSync(target.path, backup);\n moved = true;\n } else if (lstatSync(target.path, { throwIfNoEntry: false })) throw new Error('Skill appeared during installation; refusing overwrite');\n try { renameSync(replacement, target.path); }\n catch (error) { if (moved) { renameSync(backup, target.path); moved = false; } throw error; }\n if (moved) { readOwned(backup, host); rmSync(backup, { recursive: true }); moved = false; }\n return { ...result, changed: true };\n } finally {\n // Keep a displaced install intact if rollback or cleanup was interrupted.\n if (!moved) rmSync(staging, { recursive: true, force: true });\n }\n });\n}\n\nexport function installIntegration(host: string, options: IntegrationOptions = {}): IntegrationInspection & { changed: boolean } {\n return applyIntegration(host, options, 'install');\n}\n\nexport function updateIntegration(host: string, options: IntegrationOptions = {}): IntegrationInspection & { changed: boolean } {\n return applyIntegration(host, options, 'update');\n}\n\nexport function uninstallIntegration(host: string, options: IntegrationOptions = {}): IntegrationInspection & { changed: boolean } {\n const target = location(host, options);\n assertPath(target.path);\n const result = { ...details(target), installed: false, status: 'missing' as const };\n if (!lstatSync(target.path, { throwIfNoEntry: false })) return { ...result, changed: false };\n return withLock(target, () => {\n assertPath(target.path);\n if (!lstatSync(target.path, { throwIfNoEntry: false })) return { ...result, changed: false };\n readOwned(target.path, host);\n rmSync(target.path, { recursive: true });\n return { ...result, changed: true };\n });\n}\n"],"mappings":";;;;;;;AAOA,MAAM,QAAQ;AACd,MAAM,SAAS;AACf,MAAM,QAAQ;AACd,MAAM,mBAAmB,cAAc,IAAI,IAAI,oBAAoB,YAAY,GAAG,CAAC;AACnF,MAAM,cAAc,cAAc,IAAI,IAAI,mBAAmB,YAAY,GAAG,CAAC;AAE7E,MAAa,QAAQ,OAAO,OAAO;CACjC;EAAE,IAAI;EAAS,MAAM;EAAS,YAAY;EAAU,kBAAkB;EAAkB,iBAAiB;EAAoB,QAAQ;EAA8C,cAAc;CAA8G;CAC/S;EAAE,IAAI;EAAU,MAAM;EAAe,YAAY;EAAU,kBAAkB;EAAkB,iBAAiB;EAAwD,QAAQ;EAA0C,cAAc;CAA8I;CACtX;EAAE,IAAI;EAAU,MAAM;EAAU,YAAY;EAAU,kBAAkB;EAAkB,iBAAiB;EAAoB,QAAQ;EAAkC,cAAc;CAA4I;CACnU;EAAE,IAAI;EAAM,MAAM;EAAM,YAAY;EAAgB,kBAAkB;EAAc,iBAAiB;EAA4D,QAAQ;EAAsF,cAAc;CAAmM;CAChd;EAAE,IAAI;EAAU,MAAM;EAAc,YAAY;EAAuB,kBAAkB;EAAkB,iBAAiB;EAA8D,QAAQ;EAA0C,cAAc;CA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AM,EAAE,gBAAgB,MAAM,CAAC,GAAG,OAAO;GAAE,GAAG;GAAQ,SAAS;EAAM;EAC3F,UAAU,OAAO,MAAM,IAAI;EAC3B,OAAO,OAAO,MAAM,EAAE,WAAW,KAAK,CAAC;EACvC,OAAO;GAAE,GAAG;GAAQ,SAAS;EAAK;CACpC,CAAC;AACH"}
@@ -0,0 +1,190 @@
1
+ import { canonicalPath, normalizeIsolationPaths } from "./config.js";
2
+ import { accessSync, constants, existsSync, lstatSync, mkdirSync, mkdtempSync, realpathSync } from "node:fs";
3
+ import { spawnSync } from "node:child_process";
4
+ import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ // src/isolation.ts
6
+ function failure(message) {
7
+ return Object.assign(new Error(message), { code: "SETUP_REQUIRED" });
8
+ }
9
+ function contains(parent, child) {
10
+ const path = relative(parent, child);
11
+ return path === "" || path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path);
12
+ }
13
+ function executablePath(command, cwd, env) {
14
+ const candidates = command.includes("/") ? [resolve(cwd, command)] : (env.PATH ?? "").split(delimiter).filter(Boolean).map((path) => resolve(cwd, path, command));
15
+ for (const candidate of candidates) try {
16
+ accessSync(candidate, constants.X_OK);
17
+ const path = realpathSync(candidate);
18
+ if (lstatSync(path).isFile()) return path;
19
+ } catch {}
20
+ throw failure(`Cannot resolve isolated executable ${command}; select an existing executable in the approved worker PATH`);
21
+ }
22
+ function pathRule(path) {
23
+ const info = lstatSync(path);
24
+ if (info.isSymbolicLink() || !info.isFile() && !info.isDirectory()) throw failure(`Isolation grant requires a regular canonical file or directory: ${path}`);
25
+ return `(${info.isDirectory() ? "subpath" : "literal"} ${JSON.stringify(path)})`;
26
+ }
27
+ /** Keep deletion authority on the original trusted root, never a re-resolved target or its parent. */
28
+ function removeConfinedPath(path, root) {
29
+ if (process.platform !== "darwin") throw failure("Confined cleanup requires the selected macOS backend");
30
+ const boundary = resolve(root), target = resolve(path);
31
+ if (boundary === "/" || !contains(boundary, target)) throw failure("Cleanup target must stay within its original isolation root");
32
+ const ancestors = /* @__PURE__ */ new Set([
33
+ "/",
34
+ "/bin",
35
+ "/usr",
36
+ "/System"
37
+ ]);
38
+ for (let parent = dirname(boundary); !ancestors.has(parent); parent = dirname(parent)) ancestors.add(parent);
39
+ const profile = [
40
+ "(version 1)",
41
+ "(deny default)",
42
+ "(allow process-exec)",
43
+ "(allow sysctl-read)",
44
+ "(allow file-read* (literal \"/\") (literal \"/bin/rm\") (subpath \"/System/Library\") (subpath \"/usr/lib\") (literal \"/dev/null\"))",
45
+ `(allow file-read-metadata ${[...ancestors].map((parent) => `(literal ${JSON.stringify(parent)})`).join(" ")})`,
46
+ `(allow file-read* file-write* (subpath ${JSON.stringify(boundary)}))`,
47
+ "(allow file-write* (literal \"/dev/null\"))"
48
+ ].join("\n");
49
+ const result = spawnSync("/usr/bin/sandbox-exec", [
50
+ "-p",
51
+ profile,
52
+ "/bin/rm",
53
+ "-rf",
54
+ "--",
55
+ target
56
+ ], {
57
+ cwd: "/",
58
+ env: {
59
+ PATH: "/usr/bin:/bin",
60
+ LANG: "C"
61
+ },
62
+ encoding: "utf8",
63
+ timeout: 1e4,
64
+ maxBuffer: 65536
65
+ });
66
+ if (result.error || result.signal || result.status !== 0) throw Object.assign(/* @__PURE__ */ new Error(`Confined cleanup did not complete; outside paths were not granted: ${result.error?.message ?? result.stderr ?? result.signal}`), { code: "PROCESS_CLEANUP_BLOCKED" });
67
+ }
68
+ /** This confines spawned commands, not the host agent, resource consumption or GUI/device services. */
69
+ function prepareIsolatedCommand(argv, context) {
70
+ if (!context.config.isolation) throw failure("No subprocess isolation mode was selected");
71
+ if (process.platform !== "darwin") throw failure("macos-sandbox isolation requires macOS; execution was not downgraded to trusted mode");
72
+ try {
73
+ accessSync("/usr/bin/sandbox-exec", constants.X_OK);
74
+ } catch {
75
+ throw failure("The selected macos-sandbox backend is unavailable; no command was started");
76
+ }
77
+ const config = {
78
+ ...context.config,
79
+ isolation: {
80
+ ...context.config.isolation,
81
+ readOnlyPaths: [...context.config.isolation.readOnlyPaths]
82
+ }
83
+ };
84
+ normalizeIsolationPaths(config);
85
+ for (let index = 0; index < config.isolation.readOnlyPaths.length; index++) if (config.isolation.readOnlyPaths[index] !== context.config.isolation.readOnlyPaths[index]) throw failure("An isolation read-only path changed identity; review the owner configuration before retrying");
86
+ const workspaceInfo = lstatSync(context.workspace);
87
+ if (!workspaceInfo.isDirectory() || workspaceInfo.isSymbolicLink()) throw failure("Isolation requires a real owned workspace directory");
88
+ const workspace = realpathSync(context.workspace);
89
+ const state = canonicalPath(config.stateDir), workspaceRoot = canonicalPath(config.workspaceRoot);
90
+ if (workspace === workspaceRoot || contains(workspace, state) || contains(state, workspace)) throw failure("Isolation workspace must not expose control state or the whole workspace root");
91
+ const cwd = realpathSync(context.cwd);
92
+ if (![workspace, ...config.isolation.readOnlyPaths].some((path) => contains(path, cwd))) throw failure("Isolated command cwd must stay in its workspace or an approved read-only root");
93
+ const executable = executablePath(argv[0] ?? "", cwd, context.env);
94
+ if (contains(state, executable) || contains(workspaceRoot, executable) && !contains(workspace, executable)) throw failure("An isolated command cannot execute control state or another task workspace");
95
+ const readable = [
96
+ ...config.isolation.readOnlyPaths,
97
+ executable,
98
+ realpathSync(process.execPath)
99
+ ];
100
+ for (const file of context.readableFiles ?? []) {
101
+ if (!lstatSync(file).isFile() || lstatSync(file).isSymbolicLink()) throw failure(`Harness isolation capability requires a regular file: ${file}`);
102
+ readable.push(realpathSync(file));
103
+ }
104
+ const extraWritable = (context.writableDirectories ?? []).map((path) => {
105
+ if (!lstatSync(path).isDirectory() || lstatSync(path).isSymbolicLink()) throw failure(`Harness isolation capability requires a real directory: ${path}`);
106
+ return realpathSync(path);
107
+ });
108
+ const scratchParent = context.scratchParent ?? state;
109
+ mkdirSync(scratchParent, {
110
+ recursive: true,
111
+ mode: 448
112
+ });
113
+ const scratch = realpathSync(mkdtempSync(join(scratchParent, "isolated-command-")));
114
+ const cleanup = () => removeConfinedPath(scratch, scratch);
115
+ try {
116
+ const home = join(scratch, "home"), temporary = join(scratch, "tmp"), cache = join(scratch, "cache");
117
+ for (const path of [
118
+ home,
119
+ temporary,
120
+ cache
121
+ ]) mkdirSync(path, { mode: 448 });
122
+ const env = {
123
+ ...context.env,
124
+ HOME: home,
125
+ TMPDIR: `${temporary}${sep}`,
126
+ TMP: temporary,
127
+ TEMP: temporary,
128
+ XDG_CACHE_HOME: cache,
129
+ GRADLE_USER_HOME: join(cache, "gradle"),
130
+ npm_config_cache: join(cache, "npm")
131
+ };
132
+ for (const [name, fallback] of [["GOCACHE", join(cache, "go-build")], ["GOMODCACHE", join(cache, "go-mod")]]) if (!env[name] || contains(state, canonicalPath(resolve(cwd, env[name])))) env[name] = fallback;
133
+ const systemPaths = ["/System/Library", "/usr/lib"].filter(existsSync);
134
+ const devices = [
135
+ "/dev/urandom",
136
+ "/dev/random",
137
+ "/dev/null"
138
+ ].filter(existsSync);
139
+ const readablePaths = [.../* @__PURE__ */ new Set([...systemPaths, ...readable])];
140
+ const writablePaths = [.../* @__PURE__ */ new Set([
141
+ workspace,
142
+ scratch,
143
+ ...extraWritable
144
+ ])];
145
+ const ancestors = /* @__PURE__ */ new Set(["/"]);
146
+ for (const path of [
147
+ ...readablePaths,
148
+ ...writablePaths,
149
+ ...devices,
150
+ cwd
151
+ ]) {
152
+ let parent = dirname(path);
153
+ while (true) {
154
+ ancestors.add(parent);
155
+ const next = dirname(parent);
156
+ if (next === parent) break;
157
+ parent = next;
158
+ }
159
+ }
160
+ return {
161
+ argv: [
162
+ "/usr/bin/sandbox-exec",
163
+ "-p",
164
+ [
165
+ "(version 1)",
166
+ "(deny default)",
167
+ "(allow process-exec)",
168
+ "(allow process-fork)",
169
+ "(allow sysctl-read)",
170
+ "(allow file-read* (literal \"/\"))",
171
+ `(allow file-read-metadata ${[...ancestors].map((path) => `(literal ${JSON.stringify(path)})`).join(" ")})`,
172
+ `(allow file-read* ${readablePaths.map(pathRule).join(" ")} ${devices.map((path) => `(literal ${JSON.stringify(path)})`).join(" ")})`,
173
+ `(allow file-read* file-write* ${writablePaths.map(pathRule).join(" ")})`,
174
+ "(allow file-write* (literal \"/dev/null\"))",
175
+ ...config.isolation.network === "allow" ? ["(allow network*)"] : []
176
+ ].join("\n"),
177
+ executable,
178
+ ...argv.slice(1)
179
+ ],
180
+ env,
181
+ cleanup
182
+ };
183
+ } catch (cause) {
184
+ cleanup();
185
+ throw cause;
186
+ }
187
+ }
188
+ export { prepareIsolatedCommand, removeConfinedPath };
189
+
190
+ //# sourceMappingURL=isolation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isolation.js","names":[],"sources":["../src/isolation.ts"],"sourcesContent":["import { accessSync, constants, existsSync, lstatSync, mkdirSync, mkdtempSync, realpathSync } from 'node:fs';\nimport { spawnSync } from 'node:child_process';\nimport { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { canonicalPath, normalizeIsolationPaths } from './config.js';\nimport type { Config } from './schemas.js';\n\nexport interface IsolationCapabilities {\n /** Narrow capabilities for trusted harness utilities; never populated from project command data. */\n readableFiles?: readonly string[];\n writableDirectories?: readonly string[];\n}\n\nexport interface IsolationContext extends IsolationCapabilities {\n config: Config;\n workspace: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n scratchParent?: string;\n}\n\nexport interface IsolatedCommand {\n argv: string[];\n env: NodeJS.ProcessEnv;\n cleanup(): void;\n}\n\nfunction failure(message: string): Error & { code: string } {\n return Object.assign(new Error(message), { code: 'SETUP_REQUIRED' });\n}\n\nfunction contains(parent: string, child: string): boolean {\n const path = relative(parent, child);\n return path === '' || path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path);\n}\n\nfunction executablePath(command: string, cwd: string, env: NodeJS.ProcessEnv): string {\n const candidates = command.includes('/') ? [resolve(cwd, command)] : (env.PATH ?? '').split(delimiter).filter(Boolean).map(path => resolve(cwd, path, command));\n for (const candidate of candidates) {\n try {\n accessSync(candidate, constants.X_OK);\n const path = realpathSync(candidate);\n if (lstatSync(path).isFile()) return path;\n } catch {}\n }\n throw failure(`Cannot resolve isolated executable ${command}; select an existing executable in the approved worker PATH`);\n}\n\nfunction pathRule(path: string): string {\n const info = lstatSync(path);\n if (info.isSymbolicLink() || !info.isFile() && !info.isDirectory()) throw failure(`Isolation grant requires a regular canonical file or directory: ${path}`);\n return `(${info.isDirectory() ? 'subpath' : 'literal'} ${JSON.stringify(path)})`;\n}\n\n/** Keep deletion authority on the original trusted root, never a re-resolved target or its parent. */\nexport function removeConfinedPath(path: string, root: string): void {\n if (process.platform !== 'darwin') throw failure('Confined cleanup requires the selected macOS backend');\n const boundary = resolve(root), target = resolve(path);\n if (boundary === '/' || !contains(boundary, target)) throw failure('Cleanup target must stay within its original isolation root');\n const ancestors = new Set<string>(['/', '/bin', '/usr', '/System']);\n for (let parent = dirname(boundary); !ancestors.has(parent); parent = dirname(parent)) ancestors.add(parent);\n const profile = [\n '(version 1)', '(deny default)', '(allow process-exec)', '(allow sysctl-read)',\n '(allow file-read* (literal \"/\") (literal \"/bin/rm\") (subpath \"/System/Library\") (subpath \"/usr/lib\") (literal \"/dev/null\"))',\n `(allow file-read-metadata ${[...ancestors].map(parent => `(literal ${JSON.stringify(parent)})`).join(' ')})`,\n `(allow file-read* file-write* (subpath ${JSON.stringify(boundary)}))`,\n '(allow file-write* (literal \"/dev/null\"))',\n ].join('\\n');\n const result = spawnSync('/usr/bin/sandbox-exec', ['-p', profile, '/bin/rm', '-rf', '--', target], {\n cwd: '/', env: { PATH: '/usr/bin:/bin', LANG: 'C' }, encoding: 'utf8', timeout: 10000, maxBuffer: 65536,\n });\n if (result.error || result.signal || result.status !== 0) throw Object.assign(new Error(`Confined cleanup did not complete; outside paths were not granted: ${result.error?.message ?? result.stderr ?? result.signal}`), { code: 'PROCESS_CLEANUP_BLOCKED' });\n}\n\n/** This confines spawned commands, not the host agent, resource consumption or GUI/device services. */\nexport function prepareIsolatedCommand(argv: string[], context: IsolationContext): IsolatedCommand {\n if (!context.config.isolation) throw failure('No subprocess isolation mode was selected');\n if (process.platform !== 'darwin') throw failure('macos-sandbox isolation requires macOS; execution was not downgraded to trusted mode');\n try { accessSync('/usr/bin/sandbox-exec', constants.X_OK); }\n catch { throw failure('The selected macos-sandbox backend is unavailable; no command was started'); }\n const config = { ...context.config, isolation: { ...context.config.isolation, readOnlyPaths: [...context.config.isolation.readOnlyPaths] } };\n normalizeIsolationPaths(config);\n for (let index = 0; index < config.isolation.readOnlyPaths.length; index++) {\n if (config.isolation.readOnlyPaths[index] !== context.config.isolation.readOnlyPaths[index]) throw failure('An isolation read-only path changed identity; review the owner configuration before retrying');\n }\n const workspaceInfo = lstatSync(context.workspace);\n if (!workspaceInfo.isDirectory() || workspaceInfo.isSymbolicLink()) throw failure('Isolation requires a real owned workspace directory');\n const workspace = realpathSync(context.workspace);\n const state = canonicalPath(config.stateDir), workspaceRoot = canonicalPath(config.workspaceRoot);\n if (workspace === workspaceRoot || contains(workspace, state) || contains(state, workspace)) throw failure('Isolation workspace must not expose control state or the whole workspace root');\n const cwd = realpathSync(context.cwd);\n const approved = [workspace, ...config.isolation.readOnlyPaths];\n if (!approved.some(path => contains(path, cwd))) throw failure('Isolated command cwd must stay in its workspace or an approved read-only root');\n const executable = executablePath(argv[0] ?? '', cwd, context.env);\n if (contains(state, executable) || contains(workspaceRoot, executable) && !contains(workspace, executable)) throw failure('An isolated command cannot execute control state or another task workspace');\n const readable = [...config.isolation.readOnlyPaths, executable, realpathSync(process.execPath)];\n for (const file of context.readableFiles ?? []) {\n if (!lstatSync(file).isFile() || lstatSync(file).isSymbolicLink()) throw failure(`Harness isolation capability requires a regular file: ${file}`);\n readable.push(realpathSync(file));\n }\n const extraWritable = (context.writableDirectories ?? []).map(path => {\n if (!lstatSync(path).isDirectory() || lstatSync(path).isSymbolicLink()) throw failure(`Harness isolation capability requires a real directory: ${path}`);\n return realpathSync(path);\n });\n const scratchParent = context.scratchParent ?? state;\n mkdirSync(scratchParent, { recursive: true, mode: 0o700 });\n const scratch = realpathSync(mkdtempSync(join(scratchParent, 'isolated-command-')));\n const cleanup = () => removeConfinedPath(scratch, scratch);\n try {\n const home = join(scratch, 'home'), temporary = join(scratch, 'tmp'), cache = join(scratch, 'cache');\n for (const path of [home, temporary, cache]) mkdirSync(path, { mode: 0o700 });\n const env: NodeJS.ProcessEnv = { ...context.env, HOME: home, TMPDIR: `${temporary}${sep}`, TMP: temporary, TEMP: temporary, XDG_CACHE_HOME: cache, GRADLE_USER_HOME: join(cache, 'gradle'), npm_config_cache: join(cache, 'npm') };\n for (const [name, fallback] of [['GOCACHE', join(cache, 'go-build')], ['GOMODCACHE', join(cache, 'go-mod')]] as const) {\n if (!env[name] || contains(state, canonicalPath(resolve(cwd, env[name]!)))) env[name] = fallback;\n }\n const systemPaths = ['/System/Library', '/usr/lib'].filter(existsSync);\n const devices = ['/dev/urandom', '/dev/random', '/dev/null'].filter(existsSync);\n const readablePaths = [...new Set([...systemPaths, ...readable])];\n const writablePaths = [...new Set([workspace, scratch, ...extraWritable])];\n const ancestors = new Set<string>(['/']);\n for (const path of [...readablePaths, ...writablePaths, ...devices, cwd]) {\n let parent = dirname(path);\n while (true) {\n ancestors.add(parent);\n const next = dirname(parent);\n if (next === parent) break;\n parent = next;\n }\n }\n const profile = [\n '(version 1)', '(deny default)', '(allow process-exec)', '(allow process-fork)', '(allow sysctl-read)',\n '(allow file-read* (literal \"/\"))',\n `(allow file-read-metadata ${[...ancestors].map(path => `(literal ${JSON.stringify(path)})`).join(' ')})`,\n `(allow file-read* ${readablePaths.map(pathRule).join(' ')} ${devices.map(path => `(literal ${JSON.stringify(path)})`).join(' ')})`,\n `(allow file-read* file-write* ${writablePaths.map(pathRule).join(' ')})`,\n '(allow file-write* (literal \"/dev/null\"))',\n ...(config.isolation.network === 'allow' ? ['(allow network*)'] : []),\n ].join('\\n');\n return { argv: ['/usr/bin/sandbox-exec', '-p', profile, executable, ...argv.slice(1)], env, cleanup };\n } catch (c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,IAAY,CAAC,GAAG,CAAC;EACvC,KAAK,MAAM,QAAQ;GAAC,GAAG;GAAe,GAAG;GAAe,GAAG;GAAS;EAAG,GAAG;GACxE,IAAI,SAAS,QAAQ,IAAI;GACzB,OAAO,MAAM;IACX,UAAU,IAAI,MAAM;IACpB,MAAM,OAAO,QAAQ,MAAM;IAC3B,IAAI,SAAS,QAAQ;IACrB,SAAS;GACX;EACF;EAUA,OAAO;GAAE,MAAM;IAAC;IAAyB;IATzB;KACd;KAAe;KAAkB;KAAwB;KAAwB;KACjF;KACA,6BAA6B,CAAC,GAAG,SAAS,CAAC,CAAC,KAAI,SAAQ,YAAY,KAAK,UAAU,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,GAAG,EAAE;KACvG,qBAAqB,cAAc,IAAI,QAAQ,CAAC,CAAC,KAAK,GAAG,EAAE,GAAG,QAAQ,KAAI,SAAQ,YAAY,KAAK,UAAU,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,GAAG,EAAE;KACjI,iCAAiC,cAAc,IAAI,QAAQ,CAAC,CAAC,KAAK,GAAG,EAAE;KACvE;KACA,GAAI,OAAO,UAAU,YAAY,UAAU,CAAC,kBAAkB,IAAI,CAAC;IACrE,CAAC,CAAC,KAAK,IAC8C;IAAG;IAAY,GAAG,KAAK,MAAM,CAAC;GAAC;GAAG;GAAK;EAAQ;CACtG,SAAS,OAAO;EACd,QAAQ;EACR,MAAM;CACR;AACF"}
package/dist/macos.js ADDED
@@ -0,0 +1,57 @@
1
+ import { artifactOutputPath } from "./workspace.js";
2
+ import { closeSync, lstatSync, openSync, readSync } from "node:fs";
3
+ import { basename, join } from "node:path";
4
+ // src/macos.ts
5
+ /** Validate native output with system tooling, not just the file extension. */
6
+ async function validateMacOSArtifact(path, target, exec) {
7
+ if (target === "dmg") {
8
+ const result = await exec([
9
+ "/usr/bin/hdiutil",
10
+ "verify",
11
+ path
12
+ ]);
13
+ if (result.code !== 0) throw new Error(`Invalid macOS disk image: ${result.stderr || result.stdout}`);
14
+ return;
15
+ }
16
+ const info = artifactOutputPath(path, "Contents/Info.plist");
17
+ if (!lstatSync(info).isFile()) throw new Error("macOS application requires a regular Contents/Info.plist");
18
+ const result = await exec([
19
+ "/usr/bin/plutil",
20
+ "-extract",
21
+ "CFBundleExecutable",
22
+ "raw",
23
+ "-o",
24
+ "-",
25
+ info
26
+ ]);
27
+ const executable = result.stdout.trim();
28
+ if (result.code !== 0 || !executable || executable === "." || executable === ".." || basename(executable) !== executable || executable.includes("\\")) throw new Error("macOS Info.plist must identify an in-bundle executable by file name");
29
+ const binary = artifactOutputPath(path, join("Contents", "MacOS", executable));
30
+ const stat = lstatSync(binary);
31
+ if (!stat.isFile() || stat.size < 32 || !(stat.mode & 73)) throw new Error("macOS application executable is missing, empty or not executable");
32
+ const header = Buffer.allocUnsafe(4);
33
+ const descriptor = openSync(binary, "r");
34
+ try {
35
+ if (readSync(descriptor, header, 0, 4, 0) !== 4 || ![
36
+ "feedfacf",
37
+ "cffaedfe",
38
+ "cafebabe",
39
+ "bebafeca",
40
+ "cafebabf",
41
+ "bfbafeca"
42
+ ].includes(header.toString("hex"))) throw new Error("macOS application executable must be a Mach-O binary, not a script or placeholder");
43
+ } finally {
44
+ closeSync(descriptor);
45
+ }
46
+ const signed = await exec([
47
+ "/usr/bin/codesign",
48
+ "--verify",
49
+ "--deep",
50
+ "--strict",
51
+ path
52
+ ]);
53
+ if (signed.code !== 0) throw new Error(`macOS local application signature is invalid: ${signed.stderr || signed.stdout}`);
54
+ }
55
+ export { validateMacOSArtifact };
56
+
57
+ //# sourceMappingURL=macos.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"macos.js","names":[],"sources":["../src/macos.ts"],"sourcesContent":["import { basename, join } from 'node:path';\nimport { closeSync, lstatSync, openSync, readSync } from 'node:fs';\nimport { artifactOutputPath } from './workspace.js';\nimport type { Run } from './process.js';\n\n\n/** Validate native output with system tooling, not just the file extension. */\nexport async function validateMacOSArtifact(path: string, target: 'app' | 'dmg', exec: Run): Promise<void> {\n if (target === 'dmg') {\n const result = await exec(['/usr/bin/hdiutil', 'verify', path]);\n if (result.code !== 0) throw new Error(`Invalid macOS disk image: ${result.stderr || result.stdout}`);\n return;\n }\n const info = artifactOutputPath(path, 'Contents/Info.plist');\n if (!lstatSync(info).isFile()) throw new Error('macOS application requires a regular Contents/Info.plist');\n const result = await exec(['/usr/bin/plutil', '-extract', 'CFBundleExecutable', 'raw', '-o', '-', info]);\n const executable = result.stdout.trim();\n if (result.code !== 0 || !executable || executable === '.' || executable === '..' || basename(executable) !== executable || executable.includes('\\\\')) throw new Error('macOS Info.plist must identify an in-bundle executable by file name');\n const binary = artifactOutputPath(path, join('Contents', 'MacOS', executable));\n const stat = lstatSync(binary);\n if (!stat.isFile() || stat.size < 32 || !(stat.mode & 0o111)) throw new Error('macOS application executable is missing, empty or not executable');\n const header = Buffer.allocUnsafe(4);\n const descriptor = openSync(binary, 'r');\n try {\n if (readSync(descriptor, header, 0, 4, 0) !== 4 || !['feedfacf', 'cffaedfe', 'cafebabe', 'bebafeca', 'cafebabf', 'bfbafeca'].includes(header.toString('hex'))) throw new Error('macOS application executable must be a Mach-O binary, not a script or placeholder');\n } finally { closeSync(descriptor); }\n const signed = await exec(['/usr/bin/codesign', '--verify', '--deep', '--strict', path]);\n if (signed.code !== 0) throw new Error(`macOS local application signature is invalid: ${signed.stderr || signed.stdout}`);\n}\n"],"mappings":";;;;;AAOA,eAAsB,sBAAsB,MAAc,QAAuB,MAA0B;CACzG,IAAI,WAAW,OAAO;EACpB,MAAM,SAAS,MAAM,KAAK;GAAC;GAAoB;GAAU;EAAI,CAAC;EAC9D,IAAI,OAAO,SAAS,GAAG,MAAM,IAAI,MAAM,6BAA6B,OAAO,UAAU,OAAO,QAAQ;EACpG;CACF;CACA,MAAM,OAAO,mBAAmB,MAAM,qBAAqB;CAC3D,IAAI,CAAC,UAAU,IAAI,CAAC,CAAC,OAAO,GAAG,MAAM,IAAI,MAAM,0DAA0D;C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