@staix/agent-hub 0.51.0 → 0.52.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 (299) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +24 -2
  4. package/docs/agent-notes/adapters.md +1 -0
  5. package/docs/agent-notes/budget.md +8 -2
  6. package/docs/agent-notes/daemon.md +13 -8
  7. package/docs/agent-notes/security-review.md +6 -5
  8. package/docs/agent-notes/tasks.md +5 -2
  9. package/docs/agent-notes/tests.md +4 -3
  10. package/docs/cooperbench.md +1 -1
  11. package/docs/design/adapters.md +4 -0
  12. package/docs/design/cli-output-inventory.md +162 -152
  13. package/docs/design/cli-output.md +4 -3
  14. package/docs/design/guidance-probes.md +1 -0
  15. package/docs/design/roadmap.md +2 -0
  16. package/docs/design/task-board.md +1 -0
  17. package/docs/dogfood.md +14 -0
  18. package/docs/events.md +4 -2
  19. package/docs/memory.md +5 -3
  20. package/docs/operations.md +210 -16
  21. package/docs/quickstart.md +12 -2
  22. package/docs/roles.md +1 -1
  23. package/docs/sdlc.md +26 -3
  24. package/docs/security.md +11 -5
  25. package/docs/specs/2026-09-19-agent-hub-design.md +43 -0
  26. package/docs/specs/2026-09-19-multi-project-design.md +4 -0
  27. package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
  28. package/docs/specs/mcp-endpoint.md +63 -0
  29. package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
  30. package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
  31. package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
  32. package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
  33. package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
  34. package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
  35. package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
  36. package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
  37. package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
  38. package/docs/verification/2026-12-03-0.52.0.md +150 -0
  39. package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
  40. package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
  41. package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
  42. package/docs/verification/agy/README.md +17 -0
  43. package/docs/verification/agy/cli-surface.ts +68 -0
  44. package/docs/verification/agy/interactive-bridge.ts +92 -0
  45. package/docs/verification/agy/interactive-session.ts +131 -0
  46. package/docs/verification/agy/launcher-nonce.ts +215 -0
  47. package/docs/verification/agy/native-hooks.ts +210 -0
  48. package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
  49. package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
  50. package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
  51. package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
  52. package/docs/verification/agy/originals.json +25 -0
  53. package/docs/verification/agy/permission-new-functions.ts +128 -0
  54. package/docs/verification/agy/run-probe.py +108 -0
  55. package/docs/verification/agy/runtime.ts +171 -0
  56. package/docs/verification/agy/tmux-helper-control.ts +6 -0
  57. package/docs/verification/agy/tmux-session.ts +235 -0
  58. package/docs/verified.json +82 -41
  59. package/package.json +3 -3
  60. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  61. package/plugins/agent-hub/compat.json +157 -0
  62. package/plugins/agent-hub/kimi-hook.js +621 -865
  63. package/plugins/agent-hub/server.js +17423 -32962
  64. package/src/adapters/agy/definition.ts +7 -24
  65. package/src/adapters/channel-peer.ts +3 -1
  66. package/src/adapters/claude-channel.ts +38 -257
  67. package/src/adapters/claude-implementer.ts +3 -1
  68. package/src/adapters/codex-appserver.ts +77 -15
  69. package/src/adapters/compat.ts +74 -11
  70. package/src/adapters/configured-acp.ts +23 -163
  71. package/src/adapters/configured-adapter-policy.ts +160 -0
  72. package/src/adapters/configured-pull-entry.ts +53 -0
  73. package/src/adapters/configured-pull.ts +38 -0
  74. package/src/adapters/conformance/fakes/app-server.ts +9 -2
  75. package/src/adapters/declaration-catalog.ts +25 -0
  76. package/src/adapters/declaration-data.ts +342 -0
  77. package/src/adapters/declaration-resolution.ts +53 -0
  78. package/src/adapters/definitions/builtin-metadata.ts +61 -83
  79. package/src/adapters/definitions/jcode-launch.ts +13 -0
  80. package/src/adapters/definitions/native-adapter-policy.ts +390 -0
  81. package/src/adapters/definitions/native-cli-claude-launch.ts +3 -2
  82. package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
  83. package/src/adapters/definitions/native-cli-entry-jcode.ts +4 -2
  84. package/src/adapters/definitions/native-cli-entry-types.ts +9 -2
  85. package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
  86. package/src/adapters/definitions/native-cli-retained.ts +1 -1
  87. package/src/adapters/definitions/native-configuration.ts +18 -0
  88. package/src/adapters/definitions/native-help.ts +24 -0
  89. package/src/adapters/definitions/native-launch-declarations.ts +34 -0
  90. package/src/adapters/definitions/native-launch-policy.ts +4 -0
  91. package/src/adapters/definitions/native-launch-settings.ts +72 -0
  92. package/src/adapters/definitions/native-light-cli.ts +18 -0
  93. package/src/adapters/definitions/native-light-preview.ts +10 -0
  94. package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
  95. package/src/adapters/definitions/qwen.ts +6 -29
  96. package/src/adapters/definitions/reviewer-variants.ts +7 -8
  97. package/src/adapters/external-declarations.ts +31 -0
  98. package/src/adapters/external-modules.ts +4 -29
  99. package/src/adapters/jcode.ts +3 -12
  100. package/src/adapters/native-capabilities.ts +18 -8
  101. package/src/adapters/native-proof-ports.ts +1 -1
  102. package/src/adapters/presets.ts +136 -0
  103. package/src/adapters/qwen-dual.ts +2 -2
  104. package/src/adapters/registry-types.ts +3 -0
  105. package/src/adapters/registry.ts +20 -81
  106. package/src/adapters/reviewer-print.ts +26 -9
  107. package/src/adapters/role-eligibility.ts +2 -1
  108. package/src/cli/accounts-import.ts +72 -0
  109. package/src/cli/agents-latest-table.ts +88 -0
  110. package/src/cli/agents-latest.ts +22 -0
  111. package/src/cli/agents-output.ts +10 -0
  112. package/src/cli/agents-presets.ts +100 -0
  113. package/src/cli/agents.ts +1 -1
  114. package/src/cli/attention.ts +3 -2
  115. package/src/cli/autonomy-homes.ts +7 -2
  116. package/src/cli/budget-renew-guidance.ts +129 -0
  117. package/src/cli/claude-homes.ts +9 -5
  118. package/src/cli/command-context.ts +3 -0
  119. package/src/cli/command-table.ts +123 -0
  120. package/src/cli/commands/accounts.ts +8 -0
  121. package/src/cli/commands/agents.ts +18 -0
  122. package/src/cli/commands/answer.ts +28 -0
  123. package/src/cli/commands/ask.ts +17 -0
  124. package/src/cli/commands/autonomy.ts +83 -0
  125. package/src/cli/commands/backlog.ts +46 -0
  126. package/src/cli/commands/bench.ts +60 -0
  127. package/src/cli/commands/board.ts +48 -0
  128. package/src/cli/commands/broker.ts +9 -0
  129. package/src/cli/commands/budget.ts +96 -0
  130. package/src/cli/commands/capabilities.ts +12 -0
  131. package/src/cli/commands/check-path.ts +55 -0
  132. package/src/cli/commands/completion.ts +8 -0
  133. package/src/cli/commands/console.ts +12 -0
  134. package/src/cli/commands/daemon.ts +8 -0
  135. package/src/cli/commands/deliverables.ts +25 -0
  136. package/src/cli/commands/doctor.ts +249 -0
  137. package/src/cli/commands/down.ts +3 -0
  138. package/src/cli/commands/export.ts +15 -0
  139. package/src/cli/commands/facts.ts +15 -0
  140. package/src/cli/commands/goal.ts +22 -0
  141. package/src/cli/commands/guidance.ts +102 -0
  142. package/src/cli/commands/help.ts +17 -0
  143. package/src/cli/commands/host.ts +45 -0
  144. package/src/cli/commands/init.ts +121 -0
  145. package/src/cli/commands/instructed.ts +19 -0
  146. package/src/cli/commands/instruction-hook.ts +15 -0
  147. package/src/cli/commands/intake.ts +24 -0
  148. package/src/cli/commands/kill.ts +15 -0
  149. package/src/cli/commands/learn.ts +23 -0
  150. package/src/cli/commands/lineage.ts +30 -0
  151. package/src/cli/commands/logs.ts +21 -0
  152. package/src/cli/commands/manager.ts +15 -0
  153. package/src/cli/commands/memory.ts +21 -0
  154. package/src/cli/commands/model.ts +25 -0
  155. package/src/cli/commands/models.ts +40 -0
  156. package/src/cli/commands/native.ts +39 -0
  157. package/src/cli/commands/pause.ts +5 -0
  158. package/src/cli/commands/peer.ts +32 -0
  159. package/src/cli/commands/permission.ts +26 -0
  160. package/src/cli/commands/permit.ts +12 -0
  161. package/src/cli/commands/pet.ts +24 -0
  162. package/src/cli/commands/projects.ts +49 -0
  163. package/src/cli/commands/queue.ts +70 -0
  164. package/src/cli/commands/recovery-run.ts +13 -0
  165. package/src/cli/commands/recovery.ts +130 -0
  166. package/src/cli/commands/release.ts +23 -0
  167. package/src/cli/commands/releases.ts +9 -0
  168. package/src/cli/commands/remember.ts +6 -0
  169. package/src/cli/commands/report.ts +27 -0
  170. package/src/cli/commands/research.ts +53 -0
  171. package/src/cli/commands/reset.ts +89 -0
  172. package/src/cli/commands/restart.ts +5 -0
  173. package/src/cli/commands/results.ts +31 -0
  174. package/src/cli/commands/resume.ts +5 -0
  175. package/src/cli/commands/review.ts +24 -0
  176. package/src/cli/commands/roadmap.ts +21 -0
  177. package/src/cli/commands/role.ts +34 -0
  178. package/src/cli/commands/roles.ts +30 -0
  179. package/src/cli/commands/room.ts +14 -0
  180. package/src/cli/commands/roster.ts +48 -0
  181. package/src/cli/commands/route.ts +9 -0
  182. package/src/cli/commands/say.ts +21 -0
  183. package/src/cli/commands/schedule.ts +17 -0
  184. package/src/cli/commands/sdlc.ts +321 -0
  185. package/src/cli/commands/settings.ts +148 -0
  186. package/src/cli/commands/setup.ts +89 -0
  187. package/src/cli/commands/shared-refusals.ts +25 -0
  188. package/src/cli/commands/smoke.ts +44 -0
  189. package/src/cli/commands/source.ts +64 -0
  190. package/src/cli/commands/specs.ts +13 -0
  191. package/src/cli/commands/status.ts +28 -0
  192. package/src/cli/commands/stop.ts +17 -0
  193. package/src/cli/commands/structure.ts +60 -0
  194. package/src/cli/commands/study.ts +39 -0
  195. package/src/cli/commands/tail.ts +19 -0
  196. package/src/cli/commands/task.ts +114 -0
  197. package/src/cli/commands/title.ts +17 -0
  198. package/src/cli/commands/turns.ts +10 -0
  199. package/src/cli/commands/ui.ts +47 -0
  200. package/src/cli/commands/undo.ts +77 -0
  201. package/src/cli/commands/up.ts +39 -0
  202. package/src/cli/commands/upgrade.ts +5 -0
  203. package/src/cli/commands/usage.ts +33 -0
  204. package/src/cli/commands/version.ts +5 -0
  205. package/src/cli/commands/watch.ts +30 -0
  206. package/src/cli/commands/worktrees.ts +31 -0
  207. package/src/cli/console-state.ts +5 -138
  208. package/src/cli/console-versions.ts +1 -1
  209. package/src/cli/help.ts +37 -15
  210. package/src/cli/identity.ts +23 -4
  211. package/src/cli/launch-check.ts +1 -2
  212. package/src/cli/launch.ts +13 -82
  213. package/src/cli/light-dispatch.ts +29 -0
  214. package/src/cli/main.js +8 -1
  215. package/src/cli/main.ts +233 -2816
  216. package/src/cli/orca-probe.ts +119 -0
  217. package/src/cli/output.ts +31 -2
  218. package/src/cli/preview.ts +10 -5
  219. package/src/cli/recovery-version-preflight.ts +28 -9
  220. package/src/cli/replace-process.ts +22 -0
  221. package/src/cli/report-layout.ts +142 -0
  222. package/src/cli/roadmap-usage.ts +16 -0
  223. package/src/cli/roadmap.ts +3 -16
  224. package/src/cli/sdlc-doctor.ts +27 -0
  225. package/src/cli/sdlc-output.ts +55 -1
  226. package/src/cli/setup-homes.ts +1 -1
  227. package/src/cli/start-agents-run.ts +1 -1
  228. package/src/cli/statusline-tee.ts +25 -4
  229. package/src/cli/terminal-recovery.ts +53 -10
  230. package/src/cli/upgrade-interactive.ts +1 -0
  231. package/src/cli/upgrade-runtime.ts +11 -0
  232. package/src/cli/upgrade.ts +4 -15
  233. package/src/hub/accounts.ts +148 -0
  234. package/src/hub/addons.ts +20 -0
  235. package/src/hub/agent-drift.ts +2 -1
  236. package/src/hub/budget-projection.ts +39 -7
  237. package/src/hub/budget.ts +231 -16
  238. package/src/hub/channel-project.ts +3 -3
  239. package/src/hub/conductor-peer.ts +24 -0
  240. package/src/hub/conductor.ts +2 -21
  241. package/src/hub/config-apply.ts +24 -13
  242. package/src/hub/config-edit.ts +1 -1
  243. package/src/hub/config-tier.ts +2 -0
  244. package/src/hub/config.ts +31 -14
  245. package/src/hub/control-client.ts +48 -0
  246. package/src/hub/daemon.ts +421 -61
  247. package/src/hub/events.ts +3 -0
  248. package/src/hub/home-tag.ts +12 -0
  249. package/src/hub/host.ts +217 -0
  250. package/src/hub/hub-tools.ts +2 -1
  251. package/src/hub/instance-budget.ts +2 -2
  252. package/src/hub/instance-config.ts +15 -126
  253. package/src/hub/instances.ts +22 -6
  254. package/src/hub/instruction-receipt.ts +2 -2
  255. package/src/hub/kimi-usage.ts +38 -11
  256. package/src/hub/lifecycle.ts +86 -4
  257. package/src/hub/mcp-bridge-core.ts +98 -0
  258. package/src/hub/mcp-channel-push.ts +20 -0
  259. package/src/hub/mcp-endpoint-serve.ts +178 -0
  260. package/src/hub/mcp-endpoint.ts +226 -0
  261. package/src/hub/mcp-tool-call.ts +181 -0
  262. package/src/hub/operational-settings.ts +2 -0
  263. package/src/hub/orca-env.ts +6 -0
  264. package/src/hub/orca-state.ts +84 -0
  265. package/src/hub/peers.ts +5 -1
  266. package/src/hub/permission-mode.ts +2 -1
  267. package/src/hub/project.ts +20 -0
  268. package/src/hub/protocol-window.ts +58 -0
  269. package/src/hub/quota-origin.ts +20 -0
  270. package/src/hub/registry.ts +36 -2
  271. package/src/hub/report.ts +1 -1
  272. package/src/hub/research.ts +1 -1
  273. package/src/hub/review-brief.ts +47 -2
  274. package/src/hub/roster.ts +6 -3
  275. package/src/hub/routing.ts +9 -2
  276. package/src/hub/sdlc-check.ts +205 -0
  277. package/src/hub/sdlc-sync.ts +146 -0
  278. package/src/hub/sdlc.ts +33 -4
  279. package/src/hub/settings.ts +7 -4
  280. package/src/hub/start-agents.ts +1 -1
  281. package/src/hub/start-mode.ts +11 -4
  282. package/src/hub/structure-budget.ts +131 -0
  283. package/src/hub/structure-scan.ts +149 -0
  284. package/src/hub/tasks-experiment.ts +455 -0
  285. package/src/hub/tasks-guidance.ts +606 -0
  286. package/src/hub/tasks-roadmap-plan.ts +419 -0
  287. package/src/hub/tasks-roadmap.ts +491 -0
  288. package/src/hub/tasks-study.ts +661 -0
  289. package/src/hub/tasks-survey.ts +192 -0
  290. package/src/hub/tasks.ts +319 -2548
  291. package/src/hub/terminal-open.ts +5 -3
  292. package/src/hub/tooling.ts +3 -19
  293. package/src/hub/usage-rollup.ts +9 -3
  294. package/src/local/tools.ts +5 -0
  295. package/src/ui/index.html +1 -1
  296. package/src/ui/needs.ts +17 -5
  297. package/src/ui/peer-palette.ts +2 -4
  298. package/templates/presets/agents.json +60 -0
  299. package/templates/presets/confirmation-matrix.json +8 -8
@@ -0,0 +1,91 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { homedir, tmpdir, userInfo } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { profile } from "<worktree>/src/local/sandbox.ts";
7
+ import { sbplString as q } from "<worktree>/src/local/deny.ts";
8
+ import { realPath } from "<worktree>/src/hub/project.ts";
9
+ import { peerChildEnv, stopOwnedProcess, trackGroup } from "<worktree>/src/hub/child-process.ts";
10
+ const out = "<scratch>";
11
+ const digest = (b: Buffer|string) => createHash("sha256").update(b).digest("hex");
12
+ const personHome = "<home>"; // Real controller home; Bun userInfo follows the isolated HOME.
13
+ const configs = [
14
+ ["agy-settings",join(personHome,".gemini/antigravity-cli/settings.json")],
15
+ ["agy-config",join(personHome,".gemini/config/config.json")], ["agy-mcp",join(personHome,".gemini/config/mcp_config.json")],
16
+ ["agy-imports",join(personHome,".gemini/config/import_manifest.json")], ["gemini-legacy-settings",join(personHome,".gemini/settings.json")],
17
+ ];
18
+ function hashes() { return Object.fromEntries(configs.map(([id,file])=>{
19
+ try { const stat=lstatSync(file!); if(!stat.isFile()&&!stat.isSymbolicLink()) throw new Error("not a config file"); const b=readFileSync(file!);if(b.length>524288)throw new Error("config bound"); return [id,{present:true,sha256:digest(b)}]; }
20
+ catch(error){if((error as NodeJS.ErrnoException).code==="ENOENT")return[id,{present:false}];throw new Error(`config hash unavailable: ${id}`);}
21
+ })); }
22
+ async function run(argv:string[],cwd:string,env:NodeJS.ProcessEnv,policy:string) {
23
+ return await new Promise<{code:number|null;stdout:string;stderr:string}>((ok,bad)=>{
24
+ const child=spawn("/usr/bin/sandbox-exec",["-p",policy,...argv],{cwd,env,detached:true,stdio:["ignore","pipe","pipe"]});
25
+ let stdout="",stderr="",size=0,done=false,failed=false;
26
+ const finish=async(code:number|null)=>{if(done)return;done=true;clearTimeout(timer);try{await stopOwnedProcess(child,{group:true,termMs:100,killMs:1000});}catch{bad(new Error("owned process cleanup unconfirmed"));return;}ok({code:failed?null:code,stdout,stderr});};
27
+ const timer=setTimeout(()=>{failed=true;void finish(null);},25000);
28
+ const take=(kind:"stdout"|"stderr",data:Buffer)=>{size+=data.length;if(size>65536){failed=true;void finish(null);return;}if(kind==="stdout")stdout+=data.toString();else stderr+=data.toString();};
29
+ child.once("spawn",()=>trackGroup(child));child.stdout.on("data",d=>take("stdout",d));child.stderr.on("data",d=>take("stderr",d));
30
+ child.once("error",()=>{failed=true;void finish(null);});child.once("close",code=>{void finish(code);});
31
+ });
32
+ }
33
+ const before=hashes(), root=realPath(mkdtempSync(join(tmpdir(),"ahub-485-hooks-")));
34
+ const receipt:Record<string,any>={createdAt:new Date().toISOString(),accountFree:true,tools:[]};
35
+ let requests:any[]=[];
36
+ const server=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(req){
37
+ if(req.headers.has("origin"))return new Response("forbidden",{status:403});
38
+ const url=new URL(req.url);const raw=await req.text();if(raw.length>262144||requests.length>12)return new Response("bound",{status:413});
39
+ let body:any;try{body=raw?JSON.parse(raw):{};}catch{return new Response("json",{status:400});}
40
+ requests.push({method:req.method,path:url.pathname,keys:Object.keys(body),tools:body.tools,messages:body.messages,contents:body.contents,systemInstruction:body.systemInstruction});
41
+ if(url.pathname.endsWith("/chat/completions")){
42
+ const chunk=(delta:any,finish_reason:any)=>({id:"chatcmpl-fixture",object:"chat.completion.chunk",created:0,model:"fixture-review",choices:[{index:0,delta,finish_reason}]});
43
+ return new Response(`data: ${JSON.stringify(chunk({role:"assistant",content:"R0_OK"},null))}\n\ndata: ${JSON.stringify(chunk({},"stop"))}\n\ndata: [DONE]\n\n`,{headers:{"content-type":"text/event-stream"}});
44
+ }
45
+ const functionNames=(body.tools??[]).flatMap((t:any)=>t.functionDeclarations??[]).map((f:any)=>f.name);
46
+ const toolTurn=requests.filter(r=>r.tools?.length).length;
47
+ const parts=functionNames.includes("call_mcp_tool")&&toolTurn<=3?[{functionCall:{name:toolTurn===3?"read_file":"call_mcp_tool",args:toolTurn===3?{Path:join(root,"agy/cwd/canary.txt"),StartLine:1,EndLine:1}:{ServerName:"agent-hub_agent-hub",ToolName:toolTurn===1?"hub_task_show":"hub_review",Arguments:JSON.stringify(toolTurn===1?{id:1}:{id:1,verdict:"approved",note:"fixture only"})}}}]:[{text:"R0_OK"}];
48
+ const gemini={candidates:[{content:{role:"model",parts},finishReason:"STOP",index:0}],usageMetadata:{promptTokenCount:1,candidatesTokenCount:1,totalTokenCount:2}};
49
+ if(url.pathname.includes("streamGenerateContent"))return new Response(`data: ${JSON.stringify(gemini)}\n\n`,{headers:{"content-type":"text/event-stream"}});
50
+ if(url.pathname.includes("generateContent"))return Response.json(gemini);
51
+ if(url.pathname.includes("/models"))return Response.json({models:[{name:"models/gemini-2.5-flash",displayName:"fixture",supportedGenerationMethods:["generateContent","streamGenerateContent"]}]});
52
+ return new Response("unexpected",{status:404});
53
+ }});
54
+ try{
55
+ const project=join(root,"project");mkdirSync(project);writeFileSync(join(project,"canary.txt"),"unchanged");
56
+ for(const [kind,binary] of [["agy",join(personHome,".local/bin/agy")]]){
57
+ requests=[];const home=join(root,kind!,"home"),toolHome=join(root,kind!,"tool"),ownTmp=join(root,kind!,"tmp"),cwd=join(root,kind!,"cwd"),skills=join(root,kind!,"empty-skills");
58
+ for(const dir of [home,toolHome,ownTmp,cwd,skills])mkdirSync(dir,{recursive:true}); writeFileSync(join(cwd,"canary.txt"),"T0_READ_CANARY");
59
+ const executable=realPath(binary!);const denyHomes=[...new Set([homedir(),personHome].flatMap(h=>[h,realPath(h)]))];
60
+ const policy=[profile(project,{proxyPort:server.port!},[home,toolHome,ownTmp,cwd,skills,executable],[],["."]),
61
+ `(deny file-read* file-write* ${denyHomes.map(h=>`(subpath ${q(h)})`).join(" ")})`,
62
+ `(allow file-read* process-exec (literal ${q(executable)}))`,
63
+ `(allow mach-lookup (global-name "com.apple.FSEvents"))`,
64
+ ...(kind === "agy" ? ['(allow network-bind (local ip "localhost:*"))','(allow network-inbound (local ip "localhost:*"))'] : []),
65
+ `(allow file-read* file-write* process-exec ${[home,toolHome,ownTmp,cwd,skills].map(h=>`(subpath ${q(h)})`).join(" ")})`,
66
+ ].join("\n");
67
+ const env=peerChildEnv(`${kind}-review-probe`,{PATH:"/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin",HOME:home,USER:"reviewer-probe",LANG:"en_US.UTF-8",TERM:"dumb",TMPDIR:ownTmp+"/",AGY_CLI_DISABLE_AUTO_UPDATE:"1",AGENTHUB_HOME:join(home,".agenthub"),AGENTHUB_PROJECT_DIR:cwd,AGENTHUB_STATE_DIR:join(root,"state"),XDG_CONFIG_HOME:join(home,".config"),KIMI_CODE_HOME:toolHome});
68
+ let args:string[];
69
+ if(kind==="kimi"){
70
+ Object.assign(env,{KIMI_MODEL_NAME:"fixture-review",KIMI_MODEL_PROVIDER_TYPE:"openai",KIMI_MODEL_BASE_URL:`http://127.0.0.1:${server.port}/v1`,KIMI_MODEL_API_KEY:"fixture-key",KIMI_MODEL_CAPABILITIES:"tool_use"});
71
+ const agent=join(cwd,"reviewer.md");writeFileSync(agent,"---\nname: hub-reviewer\ndescription: Read-only agent-hub reviewer\ntools: []\nsubagents: []\n---\n\nReturn the requested fixture response.\n");
72
+ args=["-p","R0 inventory probe. Return R0_OK.","--output-format","stream-json","--agent-file",agent,"--skills-dir",skills];
73
+ }else{
74
+ const shim=join(cwd,"mcp-fixture.js"),log=join(ownTmp,"mcp-log.ndjson");
75
+ writeFileSync(shim,`const fs=require('node:fs');const rl=require('node:readline').createInterface({input:process.stdin});rl.on('line',line=>{let r;try{r=JSON.parse(line)}catch{return}fs.appendFileSync(${JSON.stringify(log)},JSON.stringify({method:r.method,params:r.params})+'\\n');if(r.id===undefined)return;let result={};if(r.method==='initialize')result={protocolVersion:'2024-11-05',capabilities:{tools:{}},serverInfo:{name:'fixture-hub',version:'1'}};else if(r.method==='tools/list')result={tools:['hub_task_show','hub_review'].map(name=>({name,description:'Fixture only',inputSchema:{type:'object',properties:{id:{type:'integer'},verdict:{type:'string'},note:{type:'string'}},required:['id']}}))};else if(r.method==='tools/call')result={content:[{type:'text',text:'fixture '+r.params.name+' OK'}]};console.log(JSON.stringify({jsonrpc:'2.0',id:r.id,result}));});`);
76
+ const mcpDir=join(cwd,".agents/plugins/agent-hub");mkdirSync(mcpDir,{recursive:true});writeFileSync(join(mcpDir,"plugin.json"),JSON.stringify({name:"agent-hub",version:"0.0.1"}));writeFileSync(join(mcpDir,"mcp_config.json"),JSON.stringify({mcpServers:{"agent-hub":{command:"/opt/homebrew/Cellar/bun/1.4.3/bin/bun",args:[shim]}}}));
77
+ const hookFile=join(ownTmp,"hook.ts"),hookLog=join(ownTmp,"hooks.ndjson");
78
+ writeFileSync(hookFile,`import {appendFileSync} from 'node:fs';const phase=process.argv[2];const input=await Bun.stdin.text();const output=phase==='SessionStart'||phase==='PreInvocation'?{injectSteps:[{ephemeralMessage:'T0_HOOK_'+phase}]}:phase==='PreToolUse'?{decision:'allow'}:{};appendFileSync(process.argv[3],JSON.stringify({phase,input:JSON.parse(input),output})+'\\n');console.log(JSON.stringify(output));`);
79
+ const hooks=Object.fromEntries(["SessionStart","PreInvocation","PostInvocation","PreToolUse","PostToolUse","Stop"].map(phase=>[phase,[{type:"command",command:"/opt/homebrew/Cellar/bun/1.4.3/bin/bun "+hookFile+" "+phase+" "+hookLog,timeout:5}]]));
80
+ for(const phase of ["PreToolUse","PostToolUse"]){const entries=hooks[phase];hooks[phase]=[{matcher:".*",hooks:entries}] as any;} writeFileSync(join(mcpDir,"hooks.json"),JSON.stringify({"t0-hook":hooks}));
81
+ const settings=join(home,".gemini/antigravity-cli");mkdirSync(settings,{recursive:true});writeFileSync(join(settings,"settings.json"),JSON.stringify({modelProvider:"gemini",permissions:{allow:["mcp(agent-hub_agent-hub/hub_review)","mcp(agent-hub_agent-hub/hub_task_show)"]}}));
82
+ Object.assign(env,{GEMINI_API_KEY:"fixture-key",GOOGLE_GEMINI_BASE_URL:`http://127.0.0.1:${server.port}`});
83
+ args=["-p","R0 inventory probe. Return R0_OK.","--output-format","stream-json","--disable-slash-commands"];
84
+ }
85
+ const mcpInventory=await run([executable,"mcp","list"],cwd,env,policy); const result=await run([executable,...args],cwd,env,policy);
86
+ receipt.tools.push({kind,mcpInventory,...result,requests,hookLog:existsSync(join(ownTmp,"hooks.ndjson"))?readFileSync(join(ownTmp,"hooks.ndjson"),"utf8"):"absent",mcpLog:existsSync(join(ownTmp,"mcp-log.ndjson"))?readFileSync(join(ownTmp,"mcp-log.ndjson"),"utf8"):"absent"});
87
+ if(JSON.stringify(hashes())!==JSON.stringify(before)){receipt.stopped="real config changed; attribution unknown";break;}
88
+ }
89
+ receipt.realConfigUnchanged=JSON.stringify(hashes())===JSON.stringify(before);
90
+ }finally{server.stop(true);rmSync(root,{recursive:true,force:true});receipt.temporaryRootRemoved=!existsSync(root);writeFileSync(join(out,"native-hooks-adapted.json"),JSON.stringify(receipt,null,2)+"\n");}
91
+ console.log(JSON.stringify({tools:receipt.tools.map((t:any)=>({kind:t.kind,code:t.code,stderr:t.stderr,mcpLog:t.mcpLog,hookLog:t.hookLog,requests:t.requests.map((r:any)=>({path:r.path,tools:r.tools?.flatMap((t:any)=>t.functionDeclarations??[]).map((f:any)=>f.name)})),stdoutBytes:t.stdout.length})),realConfigUnchanged:receipt.realConfigUnchanged,temporaryRootRemoved:receipt.temporaryRootRemoved}));
@@ -0,0 +1,200 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { homedir, tmpdir, userInfo } from "node:os";
5
+ import { join } from "node:path";
6
+ import { DEFAULT_CONFIG, startDaemon } from "<worktree>/src/hub/daemon.ts";
7
+ import { profile } from "<worktree>/src/local/sandbox.ts";
8
+ import { sbplString as q } from "<worktree>/src/local/deny.ts";
9
+ import { realPath } from "<worktree>/src/hub/project.ts";
10
+ import { peerChildEnv, stopOwnedProcess, trackGroup } from "<worktree>/src/hub/child-process.ts";
11
+
12
+ const out = "<scratch>";
13
+ const bun = "/opt/homebrew/Cellar/bun/1.4.3/bin/bun";
14
+ const agyPath = "<agy>";
15
+ const bundle = "<worktree>/plugins/agent-hub/server.js";
16
+ const digest = (value: Buffer | string) => createHash("sha256").update(value).digest("hex");
17
+ const personHome = "<home>"; // Real controller home; Bun userInfo follows the isolated HOME.
18
+ const realConfigs: [string, string][] = [
19
+ ["agy-settings", join(personHome, ".gemini/antigravity-cli/settings.json")],
20
+ ["agy-config", join(personHome, ".gemini/config/config.json")],
21
+ ["agy-mcp", join(personHome, ".gemini/config/mcp_config.json")],
22
+ ["agy-imports", join(personHome, ".gemini/config/import_manifest.json")],
23
+ ["gemini-legacy-settings", join(personHome, ".gemini/settings.json")],
24
+ ];
25
+
26
+ function hashes() {
27
+ return Object.fromEntries(realConfigs.map(([id, file]) => {
28
+ try {
29
+ const stat = lstatSync(file);
30
+ if (!stat.isFile() && !stat.isSymbolicLink()) throw new Error("not a config file");
31
+ const bytes = readFileSync(file);
32
+ if (bytes.length > 524288) throw new Error("config bound");
33
+ return [id, { present: true, sha256: digest(bytes) }];
34
+ } catch (error) {
35
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [id, { present: false }];
36
+ throw new Error(`config hash unavailable: ${id}`);
37
+ }
38
+ }));
39
+ }
40
+
41
+
42
+ async function runTty(argv: string[], cwd: string, env: NodeJS.ProcessEnv, policy: string, ms: number) {
43
+ let out = ""; const snaps: string[] = [];
44
+ const clean = (s: string) => s.replace(/\x1b\[[0-9;?<>]*[ -\/]*[@-~]/g, "").replace(/\x1b\][^\x07]*\x07/g, "");
45
+ const proc = Bun.spawn(["/usr/bin/sandbox-exec", "-p", policy, ...argv], { cwd, env, terminal: { cols: 110, rows: 40, data(_t: any, d: any) { if (out.length < 400000) out += Buffer.from(d).toString("utf8"); } } } as any);
46
+ const steps: [number, string][] = JSON.parse(process.env.TUI_KEYS ?? "[]");
47
+ await new Promise(r => setTimeout(r, ms));
48
+ for (const [wait, key] of steps) { snaps.push(clean(out).slice(-900)); out = ""; try { (proc as any).terminal?.write(key); } catch {} await new Promise(r => setTimeout(r, wait)); }
49
+ snaps.push(clean(out).slice(-3500));
50
+ let code: number | string = await Promise.race([proc.exited, Bun.sleep(3000).then(() => "timeout")]);
51
+ const signalFallbackNeeded = code === "timeout";
52
+ if (signalFallbackNeeded) {
53
+ // Signal only this still-running owned child; fallback cannot count as normal close.
54
+ proc.kill("SIGTERM");
55
+ code = await Promise.race([proc.exited, Bun.sleep(1000).then(() => "timeout")]);
56
+ if (code === "timeout") { proc.kill("SIGKILL"); code = await proc.exited; }
57
+ }
58
+ return { code: code as any, stdout: snaps.join("\n=====STEP=====\n"), stderr: "", cleanup: code !== "timeout", signalFallbackNeeded };
59
+ }
60
+
61
+ async function run(argv: string[], cwd: string, env: NodeJS.ProcessEnv, policy: string) {
62
+ return await new Promise<{ code: number | null; stdout: string; stderr: string; cleanup: boolean }>((resolve, reject) => {
63
+ const child = spawn("/usr/bin/sandbox-exec", ["-p", policy, ...argv], { cwd, env, detached: true, stdio: ["ignore", "pipe", "pipe"] });
64
+ let stdout = "", stderr = "", size = 0, done = false, failed = false;
65
+ const finish = async (code: number | null) => {
66
+ if (done) return;
67
+ done = true;
68
+ clearTimeout(timer);
69
+ try { await stopOwnedProcess(child, { group: true, termMs: 100, killMs: 1000 }); }
70
+ catch { reject(new Error("owned process cleanup unconfirmed")); return; }
71
+ resolve({ code: failed ? null : code, stdout, stderr, cleanup: true });
72
+ };
73
+ const timer = setTimeout(() => { failed = true; void finish(null); }, 25000);
74
+ const take = (kind: "stdout" | "stderr", data: Buffer) => {
75
+ size += data.length;
76
+ if (size > 65536) { failed = true; void finish(null); return; }
77
+ if (kind === "stdout") stdout += data.toString(); else stderr += data.toString();
78
+ };
79
+ child.once("spawn", () => trackGroup(child));
80
+ child.stdout.on("data", data => take("stdout", data));
81
+ child.stderr.on("data", data => take("stderr", data));
82
+ child.once("error", () => { failed = true; void finish(null); });
83
+ child.once("close", code => { void finish(code); });
84
+ });
85
+ }
86
+
87
+ const before = hashes();
88
+ const root = realPath(mkdtempSync(join(tmpdir(), "ahub-485-actual-hub-")));
89
+ const receipt: Record<string, unknown> = { createdAt: new Date().toISOString(), bunVersion: Bun.version, agyVersion: "1.4.12" };
90
+ const nonce = `T0_ACTUAL_HUB_${crypto.randomUUID()}`;
91
+ const originalEnv = { HOME: process.env.HOME, AGENTHUB_HOME: process.env.AGENTHUB_HOME, AGENTHUB_PROJECT_DIR: process.env.AGENTHUB_PROJECT_DIR, AGENTHUB_STATE_DIR: process.env.AGENTHUB_STATE_DIR };
92
+ let daemon: Awaited<ReturnType<typeof startDaemon>> | undefined;
93
+ let fake: ReturnType<typeof Bun.serve> | undefined;
94
+ let rootRemoved = false;
95
+
96
+ try {
97
+ const project = join(root, "project"), stateDir = join(root, "state"), home = join(root, "home"), toolHome = join(root, "tool-home"), ownTmp = join(root, "tmp");
98
+ for (const dir of [project, stateDir, home, toolHome, ownTmp]) mkdirSync(dir, { recursive: true });
99
+ const configDir = join(project, ".agents/plugins/agent-hub");
100
+ const hooksDir = configDir;
101
+ mkdirSync(configDir, { recursive: true });
102
+ const hookLog = join(ownTmp, "hooks.ndjson"), hookFile = join(ownTmp, "hook.ts");
103
+ writeFileSync(join(configDir, "plugin.json"), JSON.stringify({ name: "agent-hub", version: "0.12.37" }));
104
+ writeFileSync(join(configDir, "mcp_config.json"), JSON.stringify({
105
+ mcpServers: { "agent-hub": { command: bun, args: ["--cwd", project, "run", bundle], env: { AGENTHUB_PEER_ID: "agy", AGENTHUB_PROJECT_DIR: project, AGENTHUB_STATE_DIR: stateDir } } },
106
+ }));
107
+ writeFileSync(hookFile, String.raw`import {appendFileSync} from 'node:fs';const phase=process.argv[2];const input=await Bun.stdin.text();const output=phase==='SessionStart'||phase==='PreInvocation'?{injectSteps:[{ephemeralMessage:'T0_HOOK_'+phase}]}:phase==='PreToolUse'?{decision:'allow'}:{};appendFileSync(process.argv[3],JSON.stringify({phase,input:JSON.parse(input),output})+'\n');console.log(JSON.stringify(output));`);
108
+ const hooks = Object.fromEntries(["SessionStart", "PreInvocation", "PostInvocation", "PreToolUse", "PostToolUse", "Stop"].map(phase => [phase, [
109
+ { type: "command", command: `${bun} ${hookFile} ${phase} ${hookLog}`, timeout: 5 },
110
+ ]]));
111
+ for (const phase of ["PreToolUse", "PostToolUse"]) hooks[phase] = [{ matcher: ".*", hooks: hooks[phase] }];
112
+ writeFileSync(join(hooksDir, "hooks.json"), JSON.stringify({ "t0-hook": hooks }));
113
+ const settingsDir = join(home, ".gemini/antigravity-cli");
114
+ mkdirSync(settingsDir, { recursive: true });
115
+ writeFileSync(join(settingsDir, "settings.json"), JSON.stringify({ modelProvider: "gemini", permissions: { allow: ["mcp(agent-hub_agent-hub/hub_inbox)"] } }));
116
+
117
+ const declared: string[][] = []; let requestCount = 0, mcpCallCount = 0, nonceInModelRequest = false, observedTool: string | undefined;
118
+ fake = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) {
119
+ if (req.headers.has("origin")) return new Response("forbidden", { status: 403 });
120
+ const url = new URL(req.url), raw = await req.text();
121
+ if (raw.length > 262144 || requestCount >= 12) return new Response("bound", { status: 413 });
122
+ let body: any;
123
+ try { body = raw ? JSON.parse(raw) : {}; } catch { return new Response("json", { status: 400 }); }
124
+ requestCount++;
125
+ const serialized = JSON.stringify(body);
126
+ if (serialized.includes(nonce)) nonceInModelRequest = true;
127
+ if (url.pathname.endsWith("/models")) return Response.json({ models: [{ name: "models/gemini-3.1-flash-lite-preview", displayName: "fixture", supportedGenerationMethods: ["generateContent", "streamGenerateContent"] }] });
128
+ const declarations = (body.tools ?? []).flatMap((tool: any) => tool.functionDeclarations ?? []);
129
+ declared.push(declarations.map((item: any) => item.name));
130
+ const hasMcpTool = declarations.some((item: any) => item.name === "call_mcp_tool");
131
+ let parts: unknown[];
132
+ if (hasMcpTool && mcpCallCount === 0) {
133
+ mcpCallCount++;
134
+ observedTool = "hub_inbox";
135
+ parts = [{ functionCall: { name: "call_mcp_tool", args: { ServerName: "agent-hub_agent-hub", ToolName: "hub_inbox", Arguments: {} } } }];
136
+ } else parts = [{ text: "R0_ACTUAL_HUB_OK" }];
137
+ const result = { candidates: [{ content: { role: "model", parts }, finishReason: "STOP", index: 0 }], usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 1, totalTokenCount: 2 } };
138
+ if (url.pathname.includes("streamGenerateContent")) return new Response(`data: ${JSON.stringify(result)}\n\n`, { headers: { "content-type": "text/event-stream" } });
139
+ if (url.pathname.includes("generateContent")) return Response.json(result);
140
+ return new Response("unexpected", { status: 404 });
141
+ } });
142
+
143
+ process.env.HOME = home;
144
+ process.env.AGENTHUB_HOME = join(home, ".agenthub");
145
+ process.env.AGENTHUB_PROJECT_DIR = project;
146
+ process.env.AGENTHUB_STATE_DIR = stateDir;
147
+ daemon = await startDaemon({ cwd: project, stateDir, controlPort: 0, codexAppPort: 0, codexProxyPort: 0, switchyardPort: 0,
148
+ config: { ...DEFAULT_CONFIG, roster: { ...DEFAULT_CONFIG.roster, agy: true }, batch_ms: 0, specs: { ...DEFAULT_CONFIG.specs, enabled: false },
149
+ memory: { ...DEFAULT_CONFIG.memory, enabled: false, native: false }, inference: { ...DEFAULT_CONFIG.inference, enabled: false, triage: false },
150
+ snapshots: { ...DEFAULT_CONFIG.snapshots, enabled: false }, mlx: { ...DEFAULT_CONFIG.mlx, enabled: false }, pi: { ...DEFAULT_CONFIG.pi, enabled: false, auto_start: false } } });
151
+ daemon.bus.preface("agy", `Actual MCP readback marker: ${nonce}`);
152
+
153
+ const executable = realPath(agyPath), bunPath = realPath(bun), bundlePath = realPath(bundle);
154
+ const cwd = project;
155
+ const denyHomes = [...new Set([homedir(), personHome].flatMap(h => [h, realPath(h)]))];
156
+ const policy = [profile(project, { proxyPort: fake.port! }, [home, toolHome, ownTmp, executable, bunPath, bundlePath], [], ["."]),
157
+ `(deny file-read* file-write* ${denyHomes.map(h => `(subpath ${q(h)})`).join(" ")})`,
158
+ `(allow file-read* process-exec (literal ${q(executable)}) (literal ${q(bunPath)}))`,
159
+ `(allow mach-lookup (global-name "com.apple.FSEvents"))`,
160
+ `(allow file-read* (subpath ${q(join(bundlePath, ".."))}) (subpath ${q(stateDir)}))`,
161
+ `(allow network-bind (local ip "localhost:*"))`,
162
+ `(allow network-inbound (local ip "localhost:*"))`,
163
+ `(allow network-outbound (remote ip ${q(`localhost:${daemon.port}`)}))`,
164
+ `(allow file-read* file-write* process-exec ${[home, toolHome, ownTmp].map(h => `(subpath ${q(h)})`).join(" ")})`,
165
+ ].join("\n");
166
+ const env = peerChildEnv("agy-actual-hub-probe", { PATH: "/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin", HOME: home, USER: "agy-probe", LANG: "en_US.UTF-8", TERM: "dumb", TMPDIR: ownTmp + "/", AGY_CLI_DISABLE_AUTO_UPDATE: "1", AGENTHUB_HOME: join(home, ".agenthub"), AGENTHUB_PROJECT_DIR: project, AGENTHUB_STATE_DIR: join(root, "state"), XDG_CONFIG_HOME: join(home, ".config"), GEMINI_API_KEY: "fixture-key", GOOGLE_GEMINI_BASE_URL: `http://127.0.0.1:${fake.port}` });
167
+ const validation = await run(["/usr/bin/true"], cwd, env, policy); receipt.sandboxValidation = validation; if(validation.code!==0) throw new Error("sandbox profile refused: "+validation.stderr);
168
+ const result = await runTty([executable, "--log-file", join(ownTmp, "agy.log")], cwd, env, policy, 8000);
169
+ const hooksText = existsSync(hookLog) ? readFileSync(hookLog, "utf8") : "";
170
+ const hookRows = hooksText.trim().split("\n").filter(Boolean).map(line => JSON.parse(line));
171
+ const hookPhases = [...new Set(hookRows.map(row => row.phase))];
172
+ const transcriptPath = hookRows.map(row => row.input?.transcriptPath).find((value): value is string => typeof value === "string" && value.startsWith(root + "/"));
173
+ let transcriptTail: Record<string, unknown> = { present: false };
174
+ if (transcriptPath && existsSync(transcriptPath)) {
175
+ const bytes = readFileSync(transcriptPath);
176
+ const tail = bytes.subarray(Math.max(0, bytes.length - 65536));
177
+ transcriptTail = { present: true, pathWithinTempRoot: true, bytes: tail.length, sha256: digest(tail), text: tail.toString("utf8") };
178
+ }
179
+ receipt.agyLog = existsSync(join(ownTmp, "agy.log")) ? readFileSync(join(ownTmp, "agy.log"), "utf8").slice(-12000) : "absent"; receipt.declared = declared;
180
+ receipt.hookRows = hookRows; receipt.run = { code: result.code, cleanup: result.cleanup, signalFallbackNeeded: result.signalFallbackNeeded, stdoutBytes: result.stdout.length, stdoutSha256: digest(result.stdout), stderr: result.stderr, stdout:result.stdout, stderrBytes: result.stderr.length, stderrSha256: digest(result.stderr), requestCount, mcpCallCount, observedTool, nonceInModelRequest, hookPhases, transcriptTail, pluginHooksPresent: existsSync(join(hooksDir, "hooks.json")) };
181
+ receipt.realConfigUnchanged = JSON.stringify(hashes()) === JSON.stringify(before);
182
+ } catch (error) {
183
+ receipt.error = error instanceof Error ? error.message.slice(0, 500) : "unknown failure";
184
+ } finally {
185
+ if (daemon) {
186
+ try { await daemon.stop(); await daemon.stopped; receipt.daemonStopped = true; }
187
+ catch (error) { receipt.daemonStopped = false; receipt.daemonStopError = error instanceof Error ? error.message.slice(0, 300) : "unknown failure"; }
188
+ }
189
+ fake?.stop(true);
190
+ process.env.HOME = originalEnv.HOME;
191
+ process.env.AGENTHUB_HOME = originalEnv.AGENTHUB_HOME;
192
+ process.env.AGENTHUB_PROJECT_DIR = originalEnv.AGENTHUB_PROJECT_DIR;
193
+ process.env.AGENTHUB_STATE_DIR = originalEnv.AGENTHUB_STATE_DIR;
194
+ rmSync(root, { recursive: true, force: true });
195
+ rootRemoved = !existsSync(root);
196
+ receipt.temporaryRootRemoved = rootRemoved;
197
+ receipt.realConfigUnchanged = JSON.stringify(hashes()) === JSON.stringify(before);
198
+ writeFileSync(join(out, process.env.TUI_OUT ?? "tui-actual.json"), JSON.stringify(receipt, null, 2) + "\n");
199
+ }
200
+ console.log(JSON.stringify({ run: receipt.run, error: receipt.error, daemonStopped: receipt.daemonStopped, realConfigUnchanged: receipt.realConfigUnchanged, temporaryRootRemoved: rootRemoved }));
@@ -0,0 +1,107 @@
1
+ // #684 / #888: agy 1.4.12 actual-hub nonce leg driven through the hub launcher (`ahub --live-test --project <scratch> agy`).
2
+ // The daemon runs in this process (so the nonce can go into the bus preface); agy runs under Seatbelt via a PATH shim.
3
+ import { createHash } from "node:crypto";
4
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync, chmodSync, rmSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { userInfo } from "node:os";
7
+
8
+ const WT = "<worktree>";
9
+ const here = "<scratch>";
10
+ const S = readFileSync(join(here, "root.txt"), "utf8").trim();
11
+ const project = join(S, "project"), home = join(S, "home"), stateDir = join(project, ".agenthub/state"), ownTmp = join(S, "tmp"), shim = join(S, "shim");
12
+ const personHome = userInfo().homedir;
13
+ const agyReal = join(personHome, ".local/bin/agy");
14
+ const digest = (v: Buffer | string) => createHash("sha256").update(v).digest("hex");
15
+ const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));
16
+ const clean = (s: string) => s.replace(/\x1b\[[0-9;?<>]*[ -\/]*[@-~]/g, "").replace(/\x1b\][^\x07]*\x07/g, "");
17
+
18
+ const realFiles: [string, string][] = ["antigravity-cli/settings.json", "config/config.json", "config/mcp_config.json", "config/import_manifest.json", "settings.json"].map(f => [f, join(personHome, ".gemini", f)]);
19
+ const hashReal = () => Object.fromEntries(realFiles.map(([id, f]) => { try { lstatSync(f); return [id, digest(readFileSync(f))]; } catch { return [id, "absent"]; } }));
20
+ const binState = () => ({ agySha256: digest(readFileSync(agyReal)), localBin: readdirSync(join(personHome, ".local/bin")).filter(n => n.startsWith("agy")).sort() });
21
+
22
+ for (const d of [project, home, ownTmp, shim, join(S, "ahome")]) mkdirSync(d, { recursive: true });
23
+ process.env.HOME = home; process.env.AGENTHUB_HOME = join(S, "ahome"); process.env.AMEM_HOME = join(S, "amem");
24
+ process.env.AGENTHUB_PROJECT_DIR = project; process.env.AGENTHUB_STATE_DIR = stateDir; process.env.TMPDIR = ownTmp + "/";
25
+ const { DEFAULT_CONFIG, startDaemon } = await import(join(WT, "src/hub/daemon.ts"));
26
+ const { profile } = await import(join(WT, "src/local/sandbox.ts"));
27
+ const { sbplString: q } = await import(join(WT, "src/local/deny.ts"));
28
+ const { realPath } = await import(join(WT, "src/hub/project.ts"));
29
+
30
+ const receipt: Record<string, any> = { probe: "agy 1.4.12 launcher nonce leg", version: Bun.spawnSync([agyReal, "--version"], { env: { AGY_CLI_DISABLE_AUTO_UPDATE: "1", HOME: home, PATH: "/usr/bin:/bin" } }).stdout.toString().trim() };
31
+ const before = hashReal(), binBefore = binState();
32
+ receipt.realBefore = before; receipt.binBefore = binBefore;
33
+ const nonce = `T0_LAUNCHER_NONCE_${crypto.randomUUID()}`;
34
+ let nonceInModelRequest = false, requests = 0, mcpCalls = 0; const declared: number[] = [];
35
+ const fake = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) {
36
+ const url = new URL(req.url), raw = await req.text(); let body: any = {}; try { body = raw ? JSON.parse(raw) : {}; } catch {}
37
+ if (requests >= 40) return new Response("bound", { status: 413 });
38
+ requests++;
39
+ if (raw.includes(nonce)) nonceInModelRequest = true;
40
+ if (url.pathname.endsWith("/models")) return Response.json({ models: [{ name: "models/gemini-3.1-flash-lite-preview", displayName: "fixture", supportedGenerationMethods: ["generateContent", "streamGenerateContent"] }] });
41
+ const decl = (body.tools ?? []).flatMap((t: any) => t.functionDeclarations ?? []); declared.push(decl.length);
42
+ let parts: unknown[];
43
+ if (decl.some((d: any) => d.name === "call_mcp_tool") && mcpCalls === 0) { mcpCalls++; parts = [{ functionCall: { name: "call_mcp_tool", args: { ServerName: "agent-hub_agent-hub", ToolName: "hub_inbox", Arguments: {} } } }]; }
44
+ else parts = [{ text: "R0_LAUNCHER_OK" }];
45
+ const result = { candidates: [{ content: { role: "model", parts }, finishReason: "STOP", index: 0 }], usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 1, totalTokenCount: 2 } };
46
+ if (url.pathname.includes("streamGenerateContent")) return new Response(`data: ${JSON.stringify(result)}\n\n`, { headers: { "content-type": "text/event-stream" } });
47
+ return Response.json(result);
48
+ } });
49
+
50
+ let daemon: any; let code: any = "n/a"; let out = "";
51
+ try {
52
+ mkdirSync(join(home, ".gemini/antigravity-cli"), { recursive: true });
53
+ writeFileSync(join(home, ".gemini/antigravity-cli/settings.json"), JSON.stringify({ modelProvider: "gemini", permissions: { allow: ["mcp(agent-hub_agent-hub/hub_inbox)"] } }));
54
+ daemon = await startDaemon({ cwd: project, stateDir, controlPort: 0, codexAppPort: 0, codexProxyPort: 0, switchyardPort: 0,
55
+ config: { ...DEFAULT_CONFIG, roster: { ...DEFAULT_CONFIG.roster, agy: true }, batch_ms: 0, specs: { ...DEFAULT_CONFIG.specs, enabled: false },
56
+ memory: { ...DEFAULT_CONFIG.memory, enabled: false, native: false }, inference: { ...DEFAULT_CONFIG.inference, enabled: false, triage: false },
57
+ snapshots: { ...DEFAULT_CONFIG.snapshots, enabled: false }, mlx: { ...DEFAULT_CONFIG.mlx, enabled: false }, pi: { ...DEFAULT_CONFIG.pi, enabled: false, auto_start: false } } });
58
+ daemon.bus.preface("agy", `Launcher MCP readback marker: ${nonce}`);
59
+ receipt.daemonPort = daemon.port;
60
+
61
+ const executable = realPath(agyReal), bunPath = realPath("/opt/homebrew/bin/bun"), wt = realPath(WT);
62
+ const denyHomes = [...new Set([personHome, realPath(personHome)])];
63
+ const policy = [profile(project, { proxyPort: fake.port! }, [home, ownTmp, executable, bunPath, wt], [], ["."]),
64
+ `(deny file-read* file-write* ${denyHomes.map(h => `(subpath ${q(h)})`).join(" ")})`,
65
+ `(allow file-read* process-exec (literal ${q(executable)}) (literal ${q(bunPath)}))`,
66
+ `(allow mach-lookup (global-name "com.apple.FSEvents"))`,
67
+ `(allow file-read* (subpath ${q(wt)}) (subpath ${q(stateDir)}))`,
68
+ `(allow network-bind (local ip "localhost:*"))`, `(allow network-inbound (local ip "localhost:*"))`,
69
+ `(allow network-outbound (remote ip ${q(`localhost:${daemon.port}`)}))`,
70
+ `(allow file-read* file-write* process-exec ${[home, ownTmp].map(h => `(subpath ${q(h)})`).join(" ")})`,
71
+ ].join("\n");
72
+ writeFileSync(join(S, "agy.sb"), policy);
73
+ writeFileSync(join(shim, "agy"), `#!/bin/bash\nexec /usr/bin/sandbox-exec -f ${S}/agy.sb ${executable} "$@"\n`); chmodSync(join(shim, "agy"), 0o755);
74
+ // the sandbox profile itself must be accepted and must refuse the real home
75
+ receipt.sandboxValidation = Bun.spawnSync(["/usr/bin/sandbox-exec", "-f", join(S, "agy.sb"), "/bin/cat", join(personHome, ".gemini/config/config.json")], { env: {} });
76
+ receipt.sandboxValidation = { realConfigReadExit: receipt.sandboxValidation.exitCode, stderr: receipt.sandboxValidation.stderr.toString().trim().slice(0, 120) };
77
+ const okRun = Bun.spawnSync(["/usr/bin/sandbox-exec", "-f", join(S, "agy.sb"), "/usr/bin/true"], { env: {} }); receipt.sandboxValidation.trueExit = okRun.exitCode;
78
+
79
+ const env: Record<string, string> = { PATH: `${shim}:${personHome}/.bun/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin`, HOME: home, AGENTHUB_HOME: join(S, "ahome"), AMEM_HOME: join(S, "amem"),
80
+ AGENTHUB_STATE_DIR: stateDir, AGENTHUB_PROJECT_DIR: project, TMPDIR: ownTmp + "/", XDG_CONFIG_HOME: join(home, ".config"), LANG: "en_US.UTF-8", TERM: "xterm-256color",
81
+ AGY_CLI_DISABLE_AUTO_UPDATE: "1", GEMINI_API_KEY: "fixture-key", GOOGLE_GEMINI_BASE_URL: `http://127.0.0.1:${fake.port}`,
82
+ ...Object.fromEntries(["AGENTHUB_PEER_ID", "CLAUDECODE", "CLAUDE_CODE_SESSION_ID"].filter(k => process.env[k] !== undefined || (globalThis as any).__markers?.[k]).map(k => [k, process.env[k]!])) };
83
+ Object.assign(env, JSON.parse(process.env.MARKERS ?? "{}"));
84
+ const argv = [process.execPath, join(WT, "src/cli/main.js"), "--live-test", "--project", project, "agy"];
85
+ const proc = Bun.spawn(argv, { cwd: project, env, terminal: { cols: 110, rows: 40, data(_t: any, d: any) { if (out.length < 400000) out += Buffer.from(d).toString("utf8"); } } } as any);
86
+ await sleep(12000);
87
+ const keys: [number, string][] = [[1500, "\r"], [1500, "\x1b[B"], [1500, "\x1b[C"], [1500, "\r"], [3000, "\r"], [5000, "hello\r"], [9000, "again\r"], [12000, ""]];
88
+ for (const [w, k] of keys) { try { (proc as any).terminal?.write(k); } catch {} await sleep(w); }
89
+ receipt.filesDuringTui = existsSync(join(project, ".agents/plugins/agent-hub")) ? readdirSync(join(project, ".agents/plugins/agent-hub")).sort() : "absent";
90
+ receipt.beforeExit = { requests, mcpCalls, declared: [...declared], nonceInModelRequest };
91
+ receipt.peersDuringTui = Object.fromEntries([...daemon.bus.peers.keys()].map((k: string) => [k, daemon.bus.stateOf(k)]));
92
+ try { (proc as any).terminal?.write("/exit"); } catch {} await sleep(800); try { (proc as any).terminal?.write("\r"); } catch {}
93
+ code = await Promise.race([proc.exited, sleep(45000).then(() => "timeout")]);
94
+ if (code === "timeout") { try { proc.kill("SIGTERM"); } catch {} }
95
+ receipt.filesAfter = existsSync(join(project, ".agents/plugins/agent-hub")) ? readdirSync(join(project, ".agents/plugins/agent-hub")).sort() : "absent";
96
+ } catch (e) { receipt.error = String(e instanceof Error ? e.stack : e).slice(0, 800); }
97
+ receipt.exit = code; receipt.requests = requests; receipt.mcpCalls = mcpCalls; receipt.declared = declared; receipt.nonceInModelRequest = nonceInModelRequest;
98
+ receipt.tail = clean(out).slice(-1500);
99
+ const hubLog = existsSync(join(stateDir, "hub.log")) ? readFileSync(join(stateDir, "hub.log"), "utf8").split("\n").filter(l => /agy/.test(l)).slice(-25) : [];
100
+ receipt.hubLogAgy = hubLog;
101
+ try { await daemon?.stop(); await daemon?.stopped; receipt.daemonStopped = true; } catch (e) { receipt.daemonStopped = false; }
102
+ fake.stop(true);
103
+ receipt.realAfter = hashReal(); receipt.binAfter = binState();
104
+ receipt.realUnchanged = JSON.stringify(before) === JSON.stringify(receipt.realAfter);
105
+ receipt.binUnchanged = JSON.stringify(binBefore) === JSON.stringify(receipt.binAfter);
106
+ writeFileSync(join(here, process.env.OUT ?? "receipt.json"), JSON.stringify(receipt, null, 2) + "\n");
107
+ console.log(JSON.stringify(receipt, null, 2).slice(0, 9000));
@@ -0,0 +1,25 @@
1
+ {
2
+ "note": "Absolute personal paths in the originals were replaced with <worktree>, <scratch>, <agy>, <home> and <path>. originalSha256 is the hash recorded in the 1.5.3 receipt, scrubbedSha256 is the committed file. Producers verify scrubbedSha256.",
3
+ "originals": [
4
+ {
5
+ "file": "agent-hub-681/cli-surface.ts",
6
+ "originalSha256": "6cf627ea4be789cb3f9c63b31da43b28cc7fb6ba4dc290ac54f667356d411d16",
7
+ "scrubbedSha256": "2d0f8c64d2753f3b5833c8aa4db14e82f28dab215891bf0f6bf0aff531901a5d"
8
+ },
9
+ {
10
+ "file": "agent-hub-681/native-hooks-adapted.ts",
11
+ "originalSha256": "d74c422afa386c66389e33a94d511200c18a8b3519a51b45421f4a1c045cf384",
12
+ "scrubbedSha256": "4dc00169c8b9f4dde6e94af2a555244d2e14d354d0da237dbed38a677ad890f2"
13
+ },
14
+ {
15
+ "file": "agent-hub-681/tui-actual.ts",
16
+ "originalSha256": "998f9a3742f8ef2ea42a03b74f58065406b290c48f9c4355b7e4a258f062c3ea",
17
+ "scrubbedSha256": "1ec5866492dc2ce4ae3a0f9be6cc2b7b1823d420ba9f2e7b649c3e8e8eb393ab"
18
+ },
19
+ {
20
+ "file": "agent-hub-684/probe.ts",
21
+ "originalSha256": "7b5d2a10e7806024eb343d7fd924fcd2cae951d0691c3e4397b3d847a7c5597e",
22
+ "scrubbedSha256": "de9807cf407d0cd08eec7bf06416018913e2a65f73913778e527c83aace90e20"
23
+ }
24
+ ]
25
+ }
@@ -0,0 +1,128 @@
1
+ // Permission leg for the provider declarations run_workflow and swarm (agy 1.5.21, #843). Model-free: the fixture provider asks agy to call each once. Do not run outside run-probe.py.
2
+ import { assertEnvironment, guardPolicy, runOwned, runOwnedTty, safeReceipt, removeOwnedRoot } from "./runtime.ts";
3
+ assertEnvironment();
4
+ import { createHash } from "node:crypto";
5
+ import { spawn } from "node:child_process";
6
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
7
+ import { homedir, tmpdir, userInfo } from "node:os";
8
+ import { dirname, join } from "node:path";
9
+ import { shellQuote } from "../../../src/cli/shell-quote.ts";
10
+ import { profile } from "../../../src/local/sandbox.ts";
11
+ import { sbplString as q } from "../../../src/local/deny.ts";
12
+ import { realPath } from "../../../src/hub/project.ts";
13
+ import { peerChildEnv, stopOwnedProcess, trackGroup } from "../../../src/hub/child-process.ts";
14
+ const out = process.env.TASK801_RESULTS!;
15
+ const digest = (b: Buffer|string) => createHash("sha256").update(b).digest("hex");
16
+ const personHome = process.env.TASK801_REAL_HOME!; // Real controller home; Bun userInfo follows the isolated HOME.
17
+ const configs = [
18
+ ["agy-settings",join(personHome,".gemini/antigravity-cli/settings.json")],
19
+ ["agy-config",join(personHome,".gemini/config/config.json")], ["agy-mcp",join(personHome,".gemini/config/mcp_config.json")],
20
+ ["agy-imports",join(personHome,".gemini/config/import_manifest.json")], ["gemini-legacy-settings",join(personHome,".gemini/settings.json")],
21
+ ];
22
+ function hashes() { return Object.fromEntries(configs.map(([id,file])=>{
23
+ try { const stat=lstatSync(file!); if(!stat.isFile()&&!stat.isSymbolicLink()) throw new Error("not a config file"); const b=readFileSync(file!);if(b.length>524288)throw new Error("config bound"); return [id,{present:true,sha256:digest(b)}]; }
24
+ catch(error){if((error as NodeJS.ErrnoException).code==="ENOENT")return[id,{present:false}];throw new Error(`config hash unavailable: ${id}`);}
25
+ })); }
26
+ const run = runOwned;
27
+ const before=hashes(), root=realPath(mkdtempSync(join(tmpdir(),"ahub-agy-permission-")));
28
+ const receipt:Record<string,any>={createdAt:new Date().toISOString(),accountFree:true,tools:[]};
29
+ let requests:any[]=[], rejectedProviderRequests = 0;
30
+ const server=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(req){
31
+ if(req.headers.has("origin")){ rejectedProviderRequests++; return new Response("forbidden",{status:403}); }
32
+ const url=new URL(req.url);
33
+ const keys = [req.headers.get("x-goog-api-key"), url.searchParams.get("key"), req.headers.get("authorization")?.replace(/^Bearer /, "")].filter(value => value !== null && value !== undefined);
34
+ if(!keys.length || keys.some(value => value !== "fixture-key")){ rejectedProviderRequests++; return new Response("fixture authentication required",{status:401}); }
35
+ if(requests.length>=12)return new Response("bound",{status:413});
36
+ const reader = req.body?.getReader(), chunks: Uint8Array[] = []; let total = 0;
37
+ if(reader) for(;;){ const {done,value}=await reader.read(); if(done) break; total += value.byteLength; if(total>262144){await reader.cancel();return new Response("bound",{status:413});} chunks.push(value); }
38
+ const raw = new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks,total));
39
+ let body:any;try{body=raw?JSON.parse(raw):{};}catch{return new Response("json",{status:400});}
40
+ requests.push({method:req.method,path:url.pathname,keys:Object.keys(body),tools:body.tools,messages:body.messages,contents:body.contents,systemInstruction:body.systemInstruction});
41
+ if(url.pathname.endsWith("/chat/completions")){
42
+ const chunk=(delta:any,finish_reason:any)=>({id:"chatcmpl-fixture",object:"chat.completion.chunk",created:0,model:"fixture-review",choices:[{index:0,delta,finish_reason}]});
43
+ return new Response(`data: ${JSON.stringify(chunk({role:"assistant",content:"R0_OK"},null))}\n\ndata: ${JSON.stringify(chunk({},"stop"))}\n\ndata: [DONE]\n\n`,{headers:{"content-type":"text/event-stream"}});
44
+ }
45
+ const declarations:any[]=(body.tools??[]).flatMap((t:any)=>t.functionDeclarations??[]);
46
+ const functionNames=declarations.map((f:any)=>f.name);
47
+ const toolTurn=requests.filter(r=>r.tools?.length).length;
48
+ const wanted=["run_workflow","swarm","update_steps"][toolTurn-1];
49
+ const declared=declarations.find((f:any)=>f.name===wanted);
50
+ const synth=(schema:any):any=>{ const type=String(schema?.type??"string").toLowerCase(); if(Array.isArray(schema?.enum)&&schema.enum.length)return schema.enum[0]; if(type==="object"){ const out:any={}; for(const key of schema?.required??[])out[key]=synth(schema.properties?.[key]); return out; } if(type==="array")return []; if(type==="integer"||type==="number")return 1; if(type==="boolean")return false; return "fixture"; };
51
+ const parts=wanted&&declared?[{functionCall:{name:wanted,args:synth(declared.parameters??declared.parametersJsonSchema)}}]:[{text:"R0_OK"}];
52
+ const gemini={candidates:[{content:{role:"model",parts},finishReason:"STOP",index:0}],usageMetadata:{promptTokenCount:1,candidatesTokenCount:1,totalTokenCount:2}};
53
+ if(url.pathname.includes("streamGenerateContent"))return new Response(`data: ${JSON.stringify(gemini)}\n\n`,{headers:{"content-type":"text/event-stream"}});
54
+ if(url.pathname.includes("generateContent"))return Response.json(gemini);
55
+ if(url.pathname.includes("/models"))return Response.json({models:[{name:"models/gemini-2.5-flash",displayName:"fixture",supportedGenerationMethods:["generateContent","streamGenerateContent"]}]});
56
+ return new Response("unexpected",{status:404});
57
+ }});
58
+ try{
59
+ const project=join(root,"project");mkdirSync(project);writeFileSync(join(project,"canary.txt"),"unchanged");
60
+ for(const [kind,binary] of [["agy",process.env.TASK801_AGY!]]){
61
+ requests=[];const home=join(root,kind!,"home"),toolHome=join(root,kind!,"tool"),ownTmp=join(root,kind!,"tmp"),cwd=join(root,kind!,"cwd"),skills=join(root,kind!,"empty-skills");
62
+ for(const dir of [home,toolHome,ownTmp,cwd,skills])mkdirSync(dir,{recursive:true}); writeFileSync(join(cwd,"canary.txt"),"T0_READ_CANARY");
63
+ const executable=realPath(binary!), pinnedBun=realPath(process.env.TASK801_BUN!);const denyHomes=[...new Set([personHome,process.env.TASK801_REAL_HOME_TYPED!].flatMap(h=>[h,realPath(h)]))];
64
+ const policy=[profile(project,{proxyPort:server.port!},[home,toolHome,ownTmp,cwd,skills,executable],[],["."]),
65
+ `(deny file-read* file-write* ${denyHomes.map(h=>`(subpath ${q(h)})`).join(" ")})`,
66
+ `(allow file-read* process-exec (literal ${q(executable)}) (literal ${q(pinnedBun)}))`,
67
+ `(allow mach-lookup (global-name "com.apple.FSEvents"))`,
68
+ ...(kind === "agy" ? ['(allow network-bind (local ip "localhost:*"))','(allow network-inbound (local ip "localhost:*"))'] : []),
69
+ `(allow file-read* file-write* process-exec ${[home,toolHome,ownTmp,cwd,skills].map(h=>`(subpath ${q(h)})`).join(" ")})`,
70
+ ].join("\n");
71
+ const env=peerChildEnv(`${kind}-review-probe`,{PATH:process.env.PATH!,HOME:home,USER:"reviewer-probe",LANG:"en_US.UTF-8",TERM:"dumb",TMPDIR:ownTmp+"/",AGY_CLI_DISABLE_AUTO_UPDATE:"1",AGENTHUB_HOME:join(home,".agenthub"),AGENTHUB_PROJECT_DIR:cwd,AGENTHUB_STATE_DIR:join(root,"state"),AMEM_HOME: process.env.AMEM_HOME!, XDG_CACHE_HOME: process.env.XDG_CACHE_HOME!, XDG_DATA_HOME: process.env.XDG_DATA_HOME!, XDG_STATE_HOME: process.env.XDG_STATE_HOME!, XDG_CONFIG_HOME:join(home,".config"),KIMI_CODE_HOME:toolHome});
72
+ const policyFile = join(ownTmp,"native.sb"); writeFileSync(policyFile,policy,{mode:0o600});
73
+ writeFileSync(join(process.env.TASK801_PATH_BIN!,"agy"), `#!/bin/sh\nexec /usr/bin/sandbox-exec -f ${shellQuote(policyFile)} ${shellQuote(executable)} "$@"\n`, {mode:0o700});
74
+ receipt.profileGuards = await guardPolicy(policy,cwd,env);
75
+ const decoy = Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("owned decoy")});
76
+ try {
77
+ const code = "import socket,sys; s=socket.socket(); s.settimeout(2); s.connect(('127.0.0.1',int(sys.argv[1]))); s.close()";
78
+ const allowed = await run(["/usr/bin/python3","-c",code,String(server.port)],cwd,env,policy);
79
+ const denied = await run(["/usr/bin/python3","-c",code,String(decoy.port)],cwd,env,policy);
80
+ receipt.loopbackGuards = {allowedProviderConnect:allowed.code===0,otherOwnedLoopbackDenied:denied.code!==0 && denied.stderr.includes("Operation not permitted")};
81
+ if (!Object.values(receipt.loopbackGuards).every(value=>value===true)) throw new Error("task801 loopback-only policy guard failed");
82
+ } finally { decoy.stop(true); }
83
+ const helper = await run([pinnedBun,"-e","process.stdout.write('TASK801_HELPER_OK')"],cwd,env,policy);
84
+ receipt.pinnedBunHelperAvailable = helper.code === 0 && helper.stdout === "TASK801_HELPER_OK" && helper.stderr === "" && helper.cleanup && !helper.signalFallbackNeeded;
85
+ if (!receipt.pinnedBunHelperAvailable) throw new Error("task801 pinned Bun helper was denied or unavailable");
86
+ receipt.version = await run([executable,"--version"],cwd,env,policy); const hookFile=join(ownTmp,"hook.ts"),hookLog=join(ownTmp,"hooks.ndjson");
87
+ // Mirrors the hub's own agy hook: it observes every phase and returns no decision, so native permission handling is left alone.
88
+ writeFileSync(hookFile,`import {appendFileSync} from 'node:fs';const phase=process.argv[2];const input=await Bun.stdin.text();appendFileSync(process.argv[3],JSON.stringify({phase,input:JSON.parse(input)})+'\\n');console.log('{}');`);
89
+ const pluginDir=join(cwd,".agents/plugins/agent-hub");mkdirSync(pluginDir,{recursive:true});writeFileSync(join(pluginDir,"plugin.json"),JSON.stringify({name:"agent-hub",version:"0.0.1"}));
90
+ const hooks:any=Object.fromEntries(["SessionStart","PreInvocation","PostInvocation","PreToolUse","PostToolUse","Stop"].map(phase=>[phase,[{type:"command",command:[process.env.TASK801_BUN!,hookFile,phase,hookLog].map(shellQuote).join(" "),timeout:5}]]));
91
+ for(const phase of ["PreToolUse","PostToolUse"])hooks[phase]=[{matcher:".*",hooks:hooks[phase]}];
92
+ writeFileSync(join(pluginDir,"hooks.json"),JSON.stringify({"t0-hook":hooks}));
93
+ const settings=join(home,".gemini/antigravity-cli");mkdirSync(settings,{recursive:true});writeFileSync(join(settings,"settings.json"),JSON.stringify({modelProvider:"gemini"}));
94
+ Object.assign(env,{GEMINI_API_KEY:"fixture-key",GOOGLE_GEMINI_BASE_URL:`http://127.0.0.1:${server.port}`});
95
+ const inventory=(dirs:string[])=>{const rows:string[]=[];const walk=(dir:string)=>{for(const name of readdirSync(dir).sort()){const path=join(dir,name),stat=lstatSync(path);if(stat.isDirectory())walk(path);else rows.push(path+":"+stat.size+":"+digest(stat.isFile()?readFileSync(path):""));}};for(const dir of dirs)walk(dir);return rows;};
96
+ const watched=[project,cwd];const effectsBefore=inventory(watched);
97
+ const result=await run([executable,"-p","R0 permission probe. Return R0_OK.","--output-format","stream-json","--disable-slash-commands"],cwd,env,policy);
98
+ const effectsAfter=inventory(watched);
99
+ const processRows=await import("node:child_process").then(m=>m.execFileSync("/bin/ps",["-axo","pid=,command="],{encoding:"utf8",env:{LC_ALL:"C",PATH:"/usr/bin:/bin"}}).split("\n"));
100
+ // The controller's own command line names the binary as an argument, so only a process that runs it (directly or under sandbox-exec) or runs from the owned root counts.
101
+ const extraAgyProcesses=processRows.map(line=>line.trim().match(/^(\d+)\s+(.*)$/)).filter((match):match is RegExpMatchArray=>match!==null&&Number(match[1])!==process.pid&&!match[2]!.includes("run-probe.py")).filter(match=>match[2]!.startsWith(executable)||(match[2]!.includes("sandbox-exec")&&match[2]!.includes(executable))||match[2]!.includes(root)).length;
102
+ const hookRows=existsSync(hookLog)?readFileSync(hookLog,"utf8").trim().split("\n").filter(Boolean).map(line=>JSON.parse(line)):[];
103
+ const wantedNames=["run_workflow","swarm","update_steps"];
104
+ const declaredNames=new Set(requests.flatMap(request=>(request.tools??[]).flatMap((tool:any)=>tool.functionDeclarations??[]).map((fn:any)=>fn.name)));
105
+ const refusal=/denied|refus|reject|not permitted|not allowed|permission|approv|cancel|declin/i;
106
+ const perCall=wantedNames.map((name,index)=>{
107
+ const pre=hookRows.filter((row:any)=>row.phase==="PreToolUse"&&row.input?.toolCall?.name===name),post=hookRows.filter((row:any)=>row.phase==="PostToolUse"&&row.input?.toolCall?.name===name);
108
+ const followUp=requests.filter(request=>request.tools?.length)[index+1];const last=followUp?.contents?.at?.(-1);
109
+ return {name,hookPre:pre.length===1,hookPost:post.length>=1,refusalObserved:Boolean(last)&&refusal.test(JSON.stringify(last)),providerRequestedOnce:requests.filter(request=>JSON.stringify(request.contents??"").includes(`"name":"${name}"`)).length>0};
110
+ });
111
+ const requirements={
112
+ pinnedBunHelperAvailable:receipt.pinnedBunHelperAvailable===true,
113
+ nativeVersionExact:receipt.version.code===0&&receipt.version.stdout.trim()===process.env.TASK801_VERSION,
114
+ newFunctionsDeclared:wantedNames.every(name=>declaredNames.has(name)),
115
+ providerAuthenticated:requests.length>0&&rejectedProviderRequests===0,
116
+ loopbackOnlyGuards:receipt.loopbackGuards?.allowedProviderConnect===true&&receipt.loopbackGuards?.otherOwnedLoopbackDenied===true,
117
+ printExitedCleanly:result.code===0&&result.cleanup&&!result.signalFallbackNeeded,
118
+ everyCallGatedBeforeEffect:perCall.every(call=>call.hookPre||call.refusalObserved),
119
+ noFileEffect:JSON.stringify(effectsBefore)===JSON.stringify(effectsAfter),
120
+ noExtraAgyProcess:extraAgyProcesses===0,
121
+ providerRequestsBounded:requests.length>0&&requests.length<=8,
122
+ };
123
+ receipt.permissionLeg={perCall,requirements,providerRequests:requests.length,hookRows:hookRows.length,extraAgyProcesses,fileEffects:!requirements.noFileEffect,requirementsPassed:Object.values(requirements).every(value=>value===true)};
124
+ if(!receipt.permissionLeg.requirementsPassed)process.exitCode=1;
125
+ }
126
+ receipt.realConfigUnchanged=JSON.stringify(hashes())===JSON.stringify(before);
127
+ }finally{server.stop(true);removeOwnedRoot(root);receipt.temporaryRootRemoved=!existsSync(root);writeFileSync(join(out,"permission-new-functions.json"),JSON.stringify(safeReceipt(receipt),null,2)+"\n");}
128
+ console.log(JSON.stringify(safeReceipt(receipt)));