synabun 2.4.4 → 2.4.6

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 (129) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +5 -4
  4. package/docs/whatsapp.md +19 -3
  5. package/hooks/claude-code/session-start.mjs +21 -18
  6. package/lib/claude-global-config.js +214 -0
  7. package/lib/client-config-repair.js +17 -3
  8. package/mcp-server/dist/index.d.ts.map +1 -1
  9. package/mcp-server/dist/index.js +6 -1
  10. package/mcp-server/dist/index.js.map +1 -1
  11. package/mcp-server/dist/services/neural-interface.d.ts +1 -0
  12. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  13. package/mcp-server/dist/services/neural-interface.js +1 -0
  14. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  15. package/mcp-server/dist/services/tool-catalog.js +1 -1
  16. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  17. package/mcp-server/dist/tools/agents.d.ts +18 -3
  18. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  19. package/mcp-server/dist/tools/agents.js +85 -16
  20. package/mcp-server/dist/tools/agents.js.map +1 -1
  21. package/mcp-server/dist/tools/skill-tools.d.ts +24 -5
  22. package/mcp-server/dist/tools/skill-tools.d.ts.map +1 -1
  23. package/mcp-server/dist/tools/skill-tools.js +88 -8
  24. package/mcp-server/dist/tools/skill-tools.js.map +1 -1
  25. package/mcp-server/dist/tools/tool-groups.d.ts.map +1 -1
  26. package/mcp-server/dist/tools/tool-groups.js +19 -4
  27. package/mcp-server/dist/tools/tool-groups.js.map +1 -1
  28. package/mcp-server/package-lock.json +2 -2
  29. package/mcp-server/package.json +1 -1
  30. package/mcp-server/src/index.ts +6 -1
  31. package/mcp-server/src/services/neural-interface.ts +2 -1
  32. package/mcp-server/src/services/tool-catalog.ts +1 -1
  33. package/mcp-server/src/tools/agents.ts +78 -16
  34. package/mcp-server/src/tools/skill-tools.ts +82 -9
  35. package/mcp-server/src/tools/tool-groups.ts +19 -4
  36. package/neural-interface/i18n/en.json +484 -19
  37. package/neural-interface/i18n/pt-BR.json +484 -19
  38. package/neural-interface/lib/agents-studio-api.js +7 -2
  39. package/neural-interface/lib/antigravity/home.js +43 -8
  40. package/neural-interface/lib/antigravity/panel-bridge.js +7 -3
  41. package/neural-interface/lib/antigravity/tool-call.js +14 -0
  42. package/neural-interface/lib/assistant-brains/antigravity.js +4 -2
  43. package/neural-interface/lib/assistant-dispatch.js +15 -1
  44. package/neural-interface/lib/assistant-persona.js +8 -3
  45. package/neural-interface/lib/assistant-route-gate.js +11 -2
  46. package/neural-interface/lib/assistant-runtime.js +95 -13
  47. package/neural-interface/lib/assistant-spilled-output.js +53 -0
  48. package/neural-interface/lib/assistant-user-context.js +7 -3
  49. package/neural-interface/lib/browser-default.js +22 -2
  50. package/neural-interface/lib/browser-extension-bridge.js +50 -3
  51. package/neural-interface/lib/browser-extension-pin.json +7 -7
  52. package/neural-interface/lib/browser-extension-protocol.js +30 -1
  53. package/neural-interface/lib/browser-extension-setup.js +204 -36
  54. package/neural-interface/lib/claude-agent-bridge.js +13 -2
  55. package/neural-interface/lib/codex-thread-history.js +144 -7
  56. package/neural-interface/lib/codex-worker-app-server.js +84 -30
  57. package/neural-interface/lib/db.js +26 -0
  58. package/neural-interface/lib/greeting/sources.js +7 -3
  59. package/neural-interface/lib/jsonl-lines.js +10 -11
  60. package/neural-interface/lib/line-buffer.js +88 -0
  61. package/neural-interface/lib/loop-stall.js +15 -1
  62. package/neural-interface/lib/memory-list-read.js +105 -0
  63. package/neural-interface/lib/memory-timers.js +4 -1
  64. package/neural-interface/lib/native-loop-runtime.js +7 -3
  65. package/neural-interface/lib/provider-panel-api-key-auth.js +33 -6
  66. package/neural-interface/lib/remote-policy.js +24 -7
  67. package/neural-interface/lib/skills/api-v2.js +18 -3
  68. package/neural-interface/lib/skills/bundle.js +2 -2
  69. package/neural-interface/lib/skills/deploy.js +169 -34
  70. package/neural-interface/lib/skills/digest.js +57 -3
  71. package/neural-interface/lib/skills/health.js +55 -1
  72. package/neural-interface/lib/skills/known-bridge-digests.json +12 -0
  73. package/neural-interface/lib/skills/runtime-checks.js +7 -4
  74. package/neural-interface/lib/skills/scan-shell.js +56 -7
  75. package/neural-interface/lib/skills/scan.js +13 -12
  76. package/neural-interface/lib/skills/service.js +7 -2
  77. package/neural-interface/lib/skills/telemetry.js +2 -2
  78. package/neural-interface/lib/teams/README.md +34 -6
  79. package/neural-interface/lib/teams/api.js +94 -10
  80. package/neural-interface/lib/teams/index.js +4 -0
  81. package/neural-interface/lib/teams/landing.js +195 -75
  82. package/neural-interface/lib/teams/recovery.js +68 -0
  83. package/neural-interface/lib/teams/scheduler.js +380 -61
  84. package/neural-interface/lib/teams/worktrees.js +123 -30
  85. package/neural-interface/lib/terminal-token-redaction.js +228 -58
  86. package/neural-interface/lib/terminal-tokens.js +18 -0
  87. package/neural-interface/lib/whatsapp/brain.js +21 -0
  88. package/neural-interface/lib/whatsapp/bridge.js +40 -4
  89. package/neural-interface/package-lock.json +2 -2
  90. package/neural-interface/package.json +1 -1
  91. package/neural-interface/public/extension-setup.html +6 -2
  92. package/neural-interface/public/index.html +117 -37
  93. package/neural-interface/public/shared/agents/studio/ax-api.js +27 -0
  94. package/neural-interface/public/shared/agents/studio/ax-create-view.js +1 -1
  95. package/neural-interface/public/shared/agents/studio/ax-icons.js +1 -0
  96. package/neural-interface/public/shared/agents/studio/ax-library-view.js +3 -2
  97. package/neural-interface/public/shared/agents/studio/ax-main.js +127 -41
  98. package/neural-interface/public/shared/agents/studio/ax-review-view.js +3 -2
  99. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +436 -33
  100. package/neural-interface/public/shared/agents/studio/ax-teams.js +357 -10
  101. package/neural-interface/public/shared/agents/studio/ax-ui.js +31 -0
  102. package/neural-interface/public/shared/agents/studio/ax-views.js +67 -69
  103. package/neural-interface/public/shared/agents/studio/ax-work-answer.js +86 -0
  104. package/neural-interface/public/shared/agents/studio/ax-work-view.js +305 -0
  105. package/neural-interface/public/shared/agents/studio/ax-work.css +74 -0
  106. package/neural-interface/public/shared/agents/studio/ax-work.js +300 -0
  107. package/neural-interface/public/shared/browser-extension-updates.js +3 -1
  108. package/neural-interface/public/shared/cdx/cdx-deferred.js +90 -0
  109. package/neural-interface/public/shared/cdx/cdx-render.js +18 -7
  110. package/neural-interface/public/shared/cdx/cdx-tabs.js +2 -1
  111. package/neural-interface/public/shared/extension-setup/es-page.js +23 -4
  112. package/neural-interface/public/shared/extension-setup/es-view.js +51 -11
  113. package/neural-interface/public/shared/extension-update-view.js +1 -1
  114. package/neural-interface/public/shared/loading-diagnostic-entry.js +16 -1
  115. package/neural-interface/public/shared/settings/settings-ai-browser.js +23 -3
  116. package/neural-interface/public/shared/settings/settings-browser-extension.js +575 -197
  117. package/neural-interface/public/shared/settings/settings-extension-diagrams.js +116 -0
  118. package/neural-interface/public/shared/settings/settings-extension-guide.js +222 -0
  119. package/neural-interface/public/shared/settings/settings-ia.js +2 -2
  120. package/neural-interface/public/shared/settings/settings-shell.js +5 -0
  121. package/neural-interface/public/shared/skills/studio/sx-operations-view.js +5 -0
  122. package/neural-interface/public/shared/skills/studio/sx-plan.js +42 -3
  123. package/neural-interface/public/shared/skills/studio/sx-publish-view.js +20 -4
  124. package/neural-interface/public/shared/styles.css +196 -13
  125. package/neural-interface/public/shared/ui-settings.js +48 -11
  126. package/neural-interface/server.js +336 -253
  127. package/npm-shrinkwrap.json +2 -2
  128. package/package.json +2 -1
  129. package/skills/skill-forge/SKILL.md +7 -3
@@ -43,6 +43,10 @@ export const AGENTS_STUDIO_VERSION = 1;
43
43
  export const AGENTS_STUDIO_CAPABILITIES = Object.freeze([
44
44
  'agents', 'drafts', 'validate', 'lint', 'reviews', 'revisions', 'diff', 'copy', 'export', 'import', 'import-claude-agent', 'resolve', 'runs', 'test-run',
45
45
  'teams', // agents-p4: GET /teams, GET /teams/:id, POST /teams/:id/land, POST /teams/:id/discard
46
+ 'teams-cleanup', // POST /teams/:id/cleanup (the owner cleans up a landed team's worktrees and branches)
47
+ 'teams-remove', // DELETE /teams/:id, POST /teams/clear-finished, `removable` / `removal` in the answers
48
+ 'teams-on-target', // `alreadyOnTarget` in the answers, POST /teams/:id/cleanup-merged (a ready team merged outside land)
49
+ 'teams-quick-discard', // `liveRuns` / `left` on the list's open rows, POST /teams/:id/discard with `remove: true`
46
50
  // agents-p6: agent-forge and native export (the routes of the agents-p6 block below)
47
51
  'guide', 'forge-catalog', 'checks', 'native-export', 'native-import',
48
52
  ]);
@@ -396,8 +400,9 @@ export function registerAgentsStudioRoutes(app, {
396
400
  }));
397
401
 
398
402
  // ── agents-p4 BEGIN: teams (lib/teams/api.js) ──────────────────────────────
399
- // The list and one team for whoever reads the library; landing and discarding are the owner's, from SynaBun's own
400
- // page only (the `owner` tier above: no agent header, X-SynaBun-UI, the page secret, the owner route guard).
403
+ // The list and one team for whoever reads the library; landing, discarding, cleaning up and removing are the
404
+ // owner's, from SynaBun's own page only (the `owner` tier above: no agent header, X-SynaBun-UI, the page secret,
405
+ // the owner route guard).
401
406
  registerTeamStudioRoutes({ route, reader, owner, json, scheduler: teams });
402
407
  // ── agents-p4 END ──────────────────────────────────────────────────────────
403
408
  // ════ agents-p6 BEGIN: agent-forge and native export (docs/agents.md → agent-forge, Native export) ════
@@ -30,6 +30,8 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, st
30
30
  import { homedir } from 'node:os';
31
31
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
32
32
  import { createHash } from 'node:crypto';
33
+ import { fileURLToPath } from 'node:url';
34
+ import { ownSpilledFile } from '../assistant-spilled-output.js';
33
35
 
34
36
  /** The settings keys of the user's own Antigravity settings a SynaBun home keeps: how they sign in and which models they get. */
35
37
  export const KEPT_USER_SETTINGS = Object.freeze(['modelProvider', 'customModelsConfig', 'gcp', 'useG1Credits']);
@@ -242,19 +244,52 @@ export function assertSafeAntigravityProject(cwd) {
242
244
  }
243
245
  }
244
246
 
245
- /** The only automatic reads in a managed home are MCP tool schemas. Config/settings copy credentials.
246
- * null for a call outside the home; deny mixed reads so a safe schema cannot mask another file.
247
- */
248
- export function antigravityHomeReadPolicy(call, { homeDir, cwd } = {}) {
249
- if (!homeDir || !acpReadOnlyKind(call.kind)) return null;
250
- const paths = acpToolPaths(call).map((raw) => {
247
+ // A tool output Antigravity cuts short in the model's context is written whole to
248
+ // <App Data Dir>/brain/<conversation>/.system_generated/steps/<n>/output.txt, and the model is told to read it there
249
+ // ("The tool's output was truncated due to being too long. You can find the full output in a file at file://…").
250
+ // Measured on agy 1.4.12: outputs above about 10 KB (a SynaBun recall, agent_list or agent_dispatch among them).
251
+ const SPILLED_OUTPUT_RE = /^antigravity-cli[\\/]brain[\\/][A-Za-z0-9_-]{1,128}[\\/]\.system_generated[\\/]steps[\\/]\d{1,9}[\\/]output\.txt$/;
252
+ const SCHEMA_RE = /^antigravity-cli[\\/]mcp[\\/][^\\/]+[\\/][^\\/]+\.json$/;
253
+
254
+ /** Every path a call names, absolute: `~`, `$HOME` and `file://` URLs read as the model meant them, the rest from cwd. */
255
+ function homeCallPaths(call, cwd) {
256
+ return acpToolPaths(call).map((raw) => {
251
257
  const path = raw.trim();
252
258
  if (path === '~' || path.startsWith('~/')) return resolve(homedir(), path.slice(2));
253
259
  if (/^\$\{?HOME\}?(\/|$)/.test(path)) return resolve(homedir(), path.replace(/^\$\{?HOME\}?\/?/, ''));
260
+ if (/^file:\/\//i.test(path)) { try { return resolve(fileURLToPath(path)); } catch { /* not a local file URL: read as written */ } }
254
261
  return resolve(cwd || process.cwd(), path);
255
262
  });
263
+ }
264
+
265
+ /**
266
+ * Whether `path` is one of the home's own spilled tool outputs: exactly the shape above, a regular file with one name
267
+ * (no hard link), and no symbolic link between the home and the file (its real path is that path under the home's
268
+ * real path). Anything else, a missing file included, is not.
269
+ */
270
+ export function isAntigravitySpilledOutput(path, homeDir) {
271
+ return ownSpilledFile(path, homeDir, SPILLED_OUTPUT_RE);
272
+ }
273
+
274
+ /**
275
+ * Whether a call only reads the home's own spilled tool outputs (every path it names is one). The route gate lets
276
+ * it through: the file holds the output of a tool the model already ran, and an unrouted turn runs only the
277
+ * always-allowed ones.
278
+ */
279
+ export function antigravitySpilledOutputRead(call, { homeDir, cwd } = {}) {
280
+ if (!homeDir || !call || call.mcp || (call.kind !== 'read' && call.kind !== 'search')) return false;
281
+ const paths = homeCallPaths(call, cwd);
282
+ return paths.length > 0 && paths.every((path) => isAntigravitySpilledOutput(path, homeDir));
283
+ }
284
+
285
+ /** The only automatic reads in a managed home are MCP tool schemas and the tool outputs Antigravity spilled there.
286
+ * Config/settings copy credentials. null for a call outside the home; deny mixed reads so a safe file cannot mask another.
287
+ */
288
+ export function antigravityHomeReadPolicy(call, { homeDir, cwd } = {}) {
289
+ if (!homeDir || !acpReadOnlyKind(call.kind)) return null;
290
+ const paths = homeCallPaths(call, cwd);
256
291
  const inside = (path) => { const rel = relative(resolve(homeDir), path); return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)); };
257
292
  if (!paths.some(inside)) return null;
258
- if (paths.every((path) => inside(path) && /^antigravity-cli[\\/]mcp[\\/][^\\/]+[\\/][^\\/]+\.json$/.test(relative(resolve(homeDir), path)))) return { decision: 'allow' };
259
- return { decision: 'deny', reason: 'SynaBun refuses reads of its Antigravity home configuration: it can contain MCP credentials and sign-in settings. Only tool schemas may be read here.' };
293
+ if (paths.every((path) => inside(path) && (SCHEMA_RE.test(relative(resolve(homeDir), path)) || isAntigravitySpilledOutput(path, homeDir)))) return { decision: 'allow' };
294
+ return { decision: 'deny', reason: 'SynaBun refuses reads of its Antigravity home configuration: it can contain MCP credentials and sign-in settings. Only tool schemas and the tool outputs Antigravity saved under brain/<conversation>/.system_generated/steps/ may be read here.' };
260
295
  }
@@ -59,6 +59,7 @@ import { createHash, randomBytes } from 'node:crypto';
59
59
  import { lstatSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
60
60
  import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
61
61
  import { pathToFileURL } from 'node:url';
62
+ import { timeBlockingWork } from '../loop-stall.js';
62
63
  import { createAcpClientHost } from './acp-client-host.js';
63
64
  import { acpErrorInfo, createAcpConnection, isAuthRequired } from './acp-connection.js';
64
65
  import { allowOnceOption, bypassRail, rejectOnceOption } from './bypass.js';
@@ -627,9 +628,12 @@ export function createAntigravityPanelBridge({
627
628
  onLog: (line) => log(`[antigravity] ${line}`),
628
629
  onUpdate: (params) => {
629
630
  if (!params || typeof params.sessionId !== 'string') return;
630
- const session = sessions.get(params.sessionId);
631
- noteSubagent(params.sessionId, params.update);
632
- send({ type: 'session:update', sessionId: params.sessionId, update: params.update, replay: !!session?.replaying });
631
+ // One ACP update handed on to the page, on the server's own thread: timed by name (lib/loop-stall.js).
632
+ timeBlockingWork('antigravity:acp-update', () => {
633
+ const session = sessions.get(params.sessionId);
634
+ noteSubagent(params.sessionId, params.update);
635
+ send({ type: 'session:update', sessionId: params.sessionId, update: params.update, replay: !!session?.replaying });
636
+ });
633
637
  },
634
638
  onPermission: (params) => new Promise((resolve) => {
635
639
  const requestId = randomBytes(8).toString('hex');
@@ -129,9 +129,23 @@ export function acpWebTool(value) {
129
129
  return WEB_TOOLS.has(named) || /^browser_/.test(named) || (!named && call.kind === 'fetch');
130
130
  }
131
131
 
132
+ /**
133
+ * A path as agy may write it: its transcript keeps arguments JSON-encoded ("\"/Users/…/output.txt\""), so a value
134
+ * that is a JSON string literal is read as the string it encodes; anything else as written.
135
+ */
136
+ function unquotedPath(value) {
137
+ const path = String(value).trim();
138
+ if (path.length < 2 || path[0] !== '"' || path[path.length - 1] !== '"') return path;
139
+ try { const inner = JSON.parse(path); return typeof inner === 'string' ? inner.trim() : path; } catch { return path; }
140
+ }
141
+
132
142
  /** Every path the call names, including nested path-like values in an MCP call's arguments. */
133
143
  export function acpToolPaths(value) {
134
144
  const call = value?.args && 'mcp' in value ? value : acpCall(value);
145
+ return [...new Set(rawToolPaths(call).map(unquotedPath).filter(Boolean))];
146
+ }
147
+
148
+ function rawToolPaths(call) {
135
149
  const out = [];
136
150
  for (const location of call.locations) if (typeof location?.path === 'string' && location.path) out.push(location.path);
137
151
  if (call.mcp) {
@@ -18,7 +18,7 @@
18
18
  import { randomUUID } from 'node:crypto';
19
19
  import { fileURLToPath } from 'node:url';
20
20
  import { acpErrorInfo, createAcpConnection, isAuthRequired } from '../antigravity/acp-connection.js';
21
- import { assertSafeAntigravityProject, antigravityHomeReadPolicy, antigravityHomeSettings, homeMcpTools, policyHookCommand, prepareAntigravityHome, toAntigravityMcpEntry, userAntigravityMcpServers, userAntigravitySettings, userGeminiDir } from '../antigravity/home.js';
21
+ import { assertSafeAntigravityProject, antigravityHomeReadPolicy, antigravityHomeSettings, antigravitySpilledOutputRead, homeMcpTools, policyHookCommand, prepareAntigravityHome, toAntigravityMcpEntry, userAntigravityMcpServers, userAntigravitySettings, userGeminiDir } from '../antigravity/home.js';
22
22
  import { acpCall, acpReadOnlyKind, acpToolPaths, acpUiToolName } from '../antigravity/tool-call.js';
23
23
  import { splitAntigravityModel } from '../antigravity/catalog.js';
24
24
  import { acpTurnUsage } from '../antigravity/usage.js';
@@ -130,7 +130,9 @@ export function createAntigravityBrain({ session, sink, deps = {}, persona = ''
130
130
  */
131
131
  function policyCheck(call) {
132
132
  let verdict = null;
133
- try { verdict = typeof deps.policyCheck === 'function' ? deps.policyCheck(call) : null; } catch (error) { return { decision: 'deny', reason: `SynaBun could not check this call (${error?.message || error}).` }; }
133
+ // A read of a tool output Antigravity spilled into this brain's home: the route gate lets it through (the runtime's other checks still apply).
134
+ const spilledOutput = antigravitySpilledOutputRead(call, { homeDir, cwd });
135
+ try { verdict = typeof deps.policyCheck === 'function' ? deps.policyCheck(call, { spilledOutput }) : null; } catch (error) { return { decision: 'deny', reason: `SynaBun could not check this call (${error?.message || error}).` }; }
134
136
  if (verdict?.decision === 'deny') return verdict;
135
137
  const homeRead = antigravityHomeReadPolicy(call, { homeDir, cwd });
136
138
  if (homeRead) return homeRead;
@@ -2743,7 +2743,8 @@ export function createAssistantDispatcher({
2743
2743
  liveState.steer = null;
2744
2744
  const steerPrompt = buildFollowUpPrompt(steer.text, state, { turn: liveState.turnCounter + 1, maxTurns: entry.maxTurns, origin: 'steer', testDensity: changedTestDensity(entry) });
2745
2745
  const followPrompt = out.notSent && out.prompt ? `${out.prompt}\n\n${steerPrompt}` : steerPrompt;
2746
- out = await runInnerTurn(followPrompt, meta, { origin: 'steer', label: clip(steer.text, 80), followUp: steer.text, taskId: steer.taskId || entry.taskId || null, outboxId: steer.outboxId || null });
2746
+ try { out = await runInnerTurn(followPrompt, meta, { origin: 'steer', label: clip(steer.text, 80), followUp: steer.text, taskId: steer.taskId || entry.taskId || null, outboxId: steer.outboxId || null }); }
2747
+ catch (error) { throw undeliveredSteer(entry, liveState, error); }
2747
2748
  }
2748
2749
  return out;
2749
2750
  };
@@ -2944,6 +2945,19 @@ export function createAssistantDispatcher({
2944
2945
  // The provider never had the cut turn's prompt (it was still starting): the steer's turn carries it again.
2945
2946
  return { steered: true, turn: turnNumber, notSent: error?.notSent === true, prompt };
2946
2947
  }
2948
+ /**
2949
+ * The turn that carries a steer after the turn it cut failed (the provider is gone, or ended that turn by itself):
2950
+ * the run fails and says so (completionReason `steer_undelivered`, its error names the steer), never ends
2951
+ * as completed with no outcome, which is how an unexplained AbortError reads (handleTurnError). A stop, a shutdown
2952
+ * and a budget's cap keep their own error. What the error carries (cost, usage) is kept for the booking.
2953
+ */
2954
+ function undeliveredSteer(entry, liveState, error) {
2955
+ if (liveState.abortReason || liveState.suspending || liveState.dead || error?.code === 'BUDGET_CAP' || budgetStopReason(entry.completionReason)) return error;
2956
+ entry.completionReason = 'steer_undelivered';
2957
+ const why = clip(error?.message || String(error), 300);
2958
+ return Object.assign(new Error(`The steer could not be delivered: the turn that carries it failed (${why}).`, { cause: error }),
2959
+ error && typeof error === 'object' ? { ...error } : {}, { name: 'Error', code: 'STEER_UNDELIVERED' });
2960
+ }
2947
2961
  /**
2948
2962
  * Steer a run: the user changed what it is doing. A turn in flight is interrupted at the provider (the session stays
2949
2963
  * warm, its context kept, tool calls already done stay done), a pending permission or question is denied, and the
@@ -309,7 +309,7 @@ export function agentForgePersonaLines(t = toolNames()) {
309
309
  * rules, loaded into a Claude brain, say "Ask clarifying questions with
310
310
  * AskUserQuestion, never as plain text".
311
311
  */
312
- function whatsappChannelLines(t, { hasAskUserQuestion = true, computer = null } = {}) {
312
+ function whatsappChannelLines(t, { hasAskUserQuestion = true, computer = null, autonomous = false } = {}) {
313
313
  const askTools = [hasAskUserQuestion ? 'AskUserQuestion' : null, t.choice, t.clarify].filter(Boolean).join(', ');
314
314
  return [
315
315
  '## Channel: WhatsApp',
@@ -317,7 +317,10 @@ function whatsappChannelLines(t, { hasAskUserQuestion = true, computer = null }
317
317
  '- These channel rules win over every other instruction about how to ask, wait or report: the sections above, your CLAUDE.md and rules files (a rule such as "Ask clarifying questions with AskUserQuestion, never as plain text" does not apply here), and tool descriptions.',
318
318
  `- Asking: ask in your reply, in plain words, as a person would: one short question, the options named inside the sentence only when they help, then end your turn. The user's next message is the answer. Never call ${askTools} on this channel, and never write numbered choices or "reply 1/2/3". Ask only when a wrong guess would waste the work; otherwise act and say what you assumed.`,
319
319
  `- No ${FOLLOWUPS_FENCE} block on this channel (it only turns into buttons in SynaBun's panel): name what you offer in your sentence.`,
320
- `- Approvals: when something needs the user's OK (a tool, a plan, where a task runs), SynaBun asks them in the chat as a yes / no and gives you the answer; do not ask for it yourself as well. A request that comes back not approved, cancelled or expired with "the user sent a new message instead" means exactly that: do not retry it or work around it, end your turn at once without a reply; their message is your next prompt.`,
320
+ ...(autonomous ? [
321
+ `- Autonomous (the level the user set for this channel): act without asking. Never ask the user to confirm, approve or choose the model, agent or worker for a task, and never ask "shall I go ahead?" or "which model should I use?": ${t.route} approves every task at once (a saved route for the task class binds, otherwise your own pick runs), so pick the best fit yourself and say in a line what you started and on what. Ask a question only when the work cannot be done right without the answer (which of two projects, destructive or irreversible scope, spending money).`,
322
+ ] : []),
323
+ `- Approvals: when something needs the user's OK (${autonomous ? 'a tool or the Mac in a turn that carries a picture or forwarded text, a plan' : 'a tool, a plan, where a task runs'}), SynaBun asks them in the chat as a yes / no and gives you the answer; do not ask for it yourself as well. A request that comes back not approved, cancelled or expired with "the user sent a new message instead" means exactly that: do not retry it or work around it, end your turn at once without a reply; their message is your next prompt.`,
321
324
  `- Chat while work runs: never hold a turn open for workers. Dispatch, say in one line what you started, and end your turn; the user keeps talking to you meanwhile and you answer them. Results come to you as [SynaBun Mailbox] events: tell the user then, in a line or two. ${t.wait} returns at once here; do not call it to wait, and never poll ${t.status} in a loop.`,
322
325
  '- Sound like a person: short, natural messages in the user\'s language. No run tables, no "#1 provider/model · status · cost" lines, no headings, no "Outcome / Changes / Follow-ups" report unless they ask for the details; say what happened and what, if anything, you need from them.',
323
326
  '- Write for a phone: short paragraphs, no tables; code blocks only when needed and kept narrow. Put URLs in plain text (no markdown links).',
@@ -382,6 +385,7 @@ function whatsappComputerLines(t, computer) {
382
385
  * @param {object} [input.taskClasses] TASK_CLASS_META
383
386
  * @param {boolean} [input.clarify] agent_clarify is wired (assistant-clarify.js)
384
387
  * @param {string} [input.channel] where the user talks to you: 'whatsapp' (WhatsApp Link) or null (the panel)
388
+ * @param {string} [input.remoteLevel] a remote session's level as its brain starts (lib/remote-policy.js effectiveLevel): 'autonomous' tells a WhatsApp brain never to ask for confirmations
385
389
  * @param {string} [input.testDensity] the session's Test density (assistant-test-density.js); null leaves the prompt without it
386
390
  * @param {string} [input.agentDensity] agents-p4: the session's Agent density (lib/agents/density.js); null leaves the prompt without it and without the teams section
387
391
  * @param {object} [input.budget] the session budget as the brain starts: { unlimited, amountUsd, version, view } (null: no budget lines)
@@ -405,6 +409,7 @@ export function buildAssistantPersona({
405
409
  taskClasses = null,
406
410
  clarify = false,
407
411
  channel = null,
412
+ remoteLevel = null,
408
413
  testDensity = null,
409
414
  agentDensity = null, // agents-p4
410
415
  budget = null,
@@ -573,7 +578,7 @@ export function buildAssistantPersona({
573
578
  if (defaults?.provider || defaults?.model) {
574
579
  lines.splice(lines.indexOf('## What you know'), 0, `Defaults for new dispatches when the route leaves them open: ${[defaults.provider, defaults.model, defaults.effort].filter(Boolean).join(' / ')}.`, '');
575
580
  }
576
- if (chat) lines.push('', ...whatsappChannelLines(t, { hasAskUserQuestion, computer }));
581
+ if (chat) lines.push('', ...whatsappChannelLines(t, { hasAskUserQuestion, computer, autonomous: remoteLevel === 'autonomous' }));
577
582
  if (extra && String(extra).trim()) lines.push('', '## Additional instructions from the user', String(extra).trim());
578
583
  return lines.filter((line) => line !== null && line !== undefined).join('\n').replace(/\n{3,}/g, '\n\n');
579
584
  }
@@ -171,14 +171,18 @@ export function createRouteGate({ sessionId = null, routeTool = () => 'agent_rou
171
171
  let taskKey = '';
172
172
  let unavailable = null;
173
173
  let cli = false;
174
+ let decided = [];
174
175
 
175
176
  /**
176
177
  * `carry` keeps the refusal count (the reactive fallback's follow-up turn still counts toward the loop guard).
177
178
  * `cli`: Claude Code started this turn by itself (a background task, agent or wakeup reported back).
179
+ * `decided`: the routes the user decided for a worker that this (mailbox) turn carries ([{ routeId, target }]). The
180
+ * turn stays unrouted (those routes open no tools here); its refusals name them instead of saying nothing was routed.
178
181
  */
179
- function startTurn({ open = false, carry = false, taskId: currentTask = taskId, cli: byCli = false } = {}) {
182
+ function startTurn({ open = false, carry = false, taskId: currentTask = taskId, cli: byCli = false, decided: decidedRoutes = null } = {}) {
180
183
  turn += 1;
181
184
  cli = byCli === true;
185
+ decided = Array.isArray(decidedRoutes) ? decidedRoutes.filter((route) => route && route.routeId).slice(0, 5) : [];
182
186
  taskId = currentTask;
183
187
  taskKey = '';
184
188
  state = open ? 'open' : 'unrouted';
@@ -219,6 +223,11 @@ export function createRouteGate({ sessionId = null, routeTool = () => 'agent_rou
219
223
  const cliNote = cli ? ' This turn was started by Claude Code itself (a background task, agent or wakeup reported back): route the task it belongs to again with its task_key, then read that job\'s output and carry the task on.' : '';
220
224
  // OpenCode's Code Mode tool: a model that went looking for SynaBun's tools inside it is told where they are.
221
225
  const codeMode = name.toLowerCase() === 'execute' ? ` SynaBun's own tools, ${routeTool()} included, are separate tools in your tool list: call them directly, never through execute.` : '';
226
+ // A mailbox turn that carries a route the user decided for a worker: that route is the worker's, not this turn's.
227
+ if (decided.length) {
228
+ const routes = decided.map((route) => `${route.routeId} → ${targetLabel(route.target)}`).join(', ');
229
+ return `SynaBun route gate: ${name} was refused. The route the user decided (${routes}) is a worker's: it opens no tools in this turn. Dispatch it with agent_dispatch and its route_id if you have not yet, then end your turn with one short line; read the worker's progress with agent_status / agent_read / agent_wait. Other work in this turn needs its own route: call ${routeTool()} first${sessionId ? ` (assistant_session_id "${sessionId}")` : ''}. Memory tools, agent_* tools and asking the user work without routing.${codeMode}`;
230
+ }
222
231
  return `SynaBun route gate: ${name} was refused because this turn is not routed. Call ${routeTool()} first (task_class, one-line summary, confidence, 1-3 proposals${sessionId ? `, assistant_session_id "${sessionId}"` : ''}) and follow its status: approved + direct opens every tool for this turn. To resume an approved task, route again with the same task_key; a consumed continuation returns approved with continuation:false. Memory tools, agent_* tools and asking the user work without routing. For plain conversation, just answer in text.${cliNote}${codeMode}`;
223
232
  }
224
233
  /**
@@ -237,7 +246,7 @@ export function createRouteGate({ sessionId = null, routeTool = () => 'agent_rou
237
246
  if (abort) aborted = true;
238
247
  return { allow: false, state, refusals, abort, reason: refusalText(tool) };
239
248
  }
240
- function snapshot() { return { state, turn, refusals, routeId, taskId, taskKey, held: heldText, aborted, unavailable, cli }; }
249
+ function snapshot() { return { state, turn, refusals, routeId, taskId, taskKey, held: heldText, aborted, unavailable, cli, decided: decided.map((route) => route.routeId) }; }
241
250
 
242
251
  return { startTurn, onRouteResult, onRouteError, onClarify, setUnavailable, check, snapshot, isOpen: () => !!unavailable || state === 'open' || state === 'failed' };
243
252
  }
@@ -36,6 +36,7 @@ import { chooseUsageAccount } from './account-usage.js';
36
36
  import { defaultIsHidden, enabledStandIn, findModel, providerAllHidden, selectSheetModels } from './assistant-catalog.js';
37
37
  import { EFFORT_OFF, normalizeEffort } from './effort-levels.js';
38
38
  import { claudeRouteAvailability, createRouteGate, isReplyTool, mcpStatusRouteAvailability, ROUTE_GATE_LOOP_MESSAGE } from './assistant-route-gate.js';
39
+ import { claudeSpilledResultRead } from './assistant-spilled-output.js';
39
40
  import { claudeReadOnlyPermission, planDenyMessage, planToolDecision, readOnlyDenyMessage, readOnlyToolDecision } from './assistant-plan-permissions.js';
40
41
  import { codexRouteGateBootstrap } from './assistant-route-gate-codex.js';
41
42
  import { proposedPlanText } from './assistant-envelope.js';
@@ -2222,6 +2223,8 @@ export function createAssistantRuntime({
2222
2223
  budget: budgetSetting ? { ...budgetSetting, view: money } : null,
2223
2224
  clarify: !!clarifier,
2224
2225
  channel: live.record.channel || live.record.remote?.channel || null,
2226
+ // The configured level (a turn's untrusted cap aside): a change of Autonomous restarts the brain (needsRestart).
2227
+ remoteLevel: (() => { const policy = remotePolicyFor(live); return policy ? effectiveLevel(policy, { now: now() }) : null; })(),
2225
2228
  });
2226
2229
  }
2227
2230
  /**
@@ -2290,9 +2293,8 @@ export function createAssistantRuntime({
2290
2293
  // (lib/skills/api-v2.js principalOf) take it; whatsapp_send_file takes it and then only the active WhatsApp
2291
2294
  // conversation's session (lib/whatsapp/service.js sendFile).
2292
2295
  live.brainCredential = mintBrainCredential();
2293
- // The brain's own pin (its session id, for the brains that name it) is proven by this same credential: its MCP
2294
- // presents it with X-Synabun-Terminal, and a process that only names the session gets nothing (lib/terminal-tokens.js).
2295
- if (BRAIN_PIN_PROVIDERS.has(brain.provider)) { try { terminalTokens?.bind?.(live.record.id, live.brainCredential); } catch { /* the brain starts; its pin stays as it was */ } }
2296
+ // (It becomes the proof of the brain's own pin right before the brain is made, below: nothing is bound for a
2297
+ // launch that fails while its options are still being put together.)
2296
2298
  const cliCap = brain.provider === 'claude-code' ? brainCliCap(live) : null;
2297
2299
  const deps = {
2298
2300
  ClaudeSession, sdkVersion, PACKAGE_ROOT, handleCodexSkinWebSocket, ensureIsolatedServe, stopIsolatedServe, setupOpencodeSidepanelConfig,
@@ -2359,7 +2361,20 @@ export function createAssistantRuntime({
2359
2361
  live.brainCliCap = cliCap;
2360
2362
  live.brainBudgetVersion = budgetSettingNow()?.version ?? null;
2361
2363
  startMeter(live, brain.provider);
2362
- const created = factory({ session: live.record, sink, deps, persona, hooks });
2364
+ // The brain's own pin (its session id, for the brains that name it) is proven by this launch's credential: its MCP
2365
+ // presents it with X-Synabun-Terminal, and a process that only names the session gets nothing (lib/terminal-tokens.js).
2366
+ const pinned = BRAIN_PIN_PROVIDERS.has(brain.provider);
2367
+ if (pinned) { try { terminalTokens?.bind?.(live.record.id, live.brainCredential); } catch { /* the brain starts; its pin stays as it was */ } }
2368
+ let created;
2369
+ try {
2370
+ created = factory({ session: live.record, sink, deps, persona, hooks });
2371
+ } catch (error) {
2372
+ // No brain was made, so disposeBrain has nothing to dispose and would leave the credential bound (and known to
2373
+ // the scrubbers) for as long as the server runs: it ends here.
2374
+ live.brainCredential = null;
2375
+ if (pinned) { try { terminalTokens?.revoke?.(live.record.id); } catch { /* the failure goes on */ } }
2376
+ throw error;
2377
+ }
2363
2378
  live.brain = created;
2364
2379
  live.brainSkipAllowed = remote ? deps.remoteLevel === 'autonomous' : null;
2365
2380
  live.brainComputerMode = computerMode;
@@ -2548,7 +2563,7 @@ export function createAssistantRuntime({
2548
2563
  // `offerPlan`: a system turn that revises a plan still ends with a plan card.
2549
2564
  // `work`: the scheduler entry this system turn is; `request`: { id, reply } of a
2550
2565
  // prompt a socket sent (refuse); `turnGen`: the generation runQuery entered in.
2551
- async function runTurn(live, { text, images = [], cwd = null, model = null, effort = null, permissionMode = null, planMode = null, system = false, taskId = null, turnModel = null, turnEffort = null, gateOpen = false, gateCarry = false, origin = null, authority = null, untrusted = false, offerPlan = false, work = null, request = null, turnGen = live.gen, computerRoutes = null, typed = null, greetingId = null } = {}) {
2566
+ async function runTurn(live, { text, images = [], cwd = null, model = null, effort = null, permissionMode = null, planMode = null, system = false, taskId = null, turnModel = null, turnEffort = null, gateOpen = false, gateCarry = false, gateDecided = null, origin = null, authority = null, untrusted = false, offerPlan = false, work = null, request = null, turnGen = live.gen, computerRoutes = null, typed = null, greetingId = null } = {}) {
2552
2567
  const prompt = String(text || '').trim();
2553
2568
  if (!prompt && !(Array.isArray(images) && images.length)) return refuse(live, 'EMPTY_PROMPT', 'No prompt provided', { packet: { type: 'error', message: 'No prompt provided' }, request });
2554
2569
  // The scheduler's turn goes once a Stop, the session closing or a newer
@@ -2579,6 +2594,24 @@ export function createAssistantRuntime({
2579
2594
  if (budgetBlock) return refuse(live, budgetBlock.code, budgetBlock.message, { request });
2580
2595
  if (live.switching) await live.switching;
2581
2596
  if (cancelled()) return dropTurn(live, request);
2597
+ // A refusal for the account names the soonest reset when every subscription is limited.
2598
+ const accountRefusal = (error) => ({ ...refuse(live, error.code || 'ACCOUNT_UNAVAILABLE', error.message, { request }), ...(error.resetsAt ? { resetsAt: error.resetsAt } : {}) });
2599
+ // A WhatsApp conversation on an account nothing put on Auto: it moves to Auto when the account
2600
+ // cannot run, or when the Default account starts a provider conversation (phoneAccountMoves).
2601
+ if (live.record.brain.accountPolicy !== 'auto' && isPhoneSession(live) && ['claude-code', 'codex'].includes(live.record.brain.provider)) {
2602
+ await accountUsage?.refresh(live.record.brain.provider);
2603
+ if (cancelled()) return dropTurn(live, request);
2604
+ const rows = conversationAccounts(live.record.brain, live);
2605
+ if (rows.length && phoneAccountMoves(live, rows)) {
2606
+ try { await updateSession(live.record.id, { brain: { accountId: 'auto' } }, { fromTurn: true }); }
2607
+ catch (error) {
2608
+ // No signed-in subscription at all (only API keys, or all signed out): the account stays as
2609
+ // it is, and runs (a key) or is refused below with why (signed out, removed).
2610
+ if (error?.code !== 'ACCOUNT_NO_SUBSCRIPTION') return accountRefusal(error);
2611
+ }
2612
+ if (cancelled()) return dropTurn(live, request);
2613
+ }
2614
+ }
2582
2615
  if (live.record.brain.accountPolicy === 'auto') {
2583
2616
  await accountUsage?.refresh(live.record.brain.provider);
2584
2617
  if (cancelled()) return dropTurn(live, request);
@@ -2586,7 +2619,7 @@ export function createAssistantRuntime({
2586
2619
  const active = rows.find(row => row.id === live.record.brain.accountId);
2587
2620
  if (!active || active.signedIn !== true || active.mode !== 'subscription' || active.usage?.limited) {
2588
2621
  try { await updateSession(live.record.id, { brain: { accountId: 'auto' } }, { fromTurn: true }); }
2589
- catch (error) { return refuse(live, error.code || 'ACCOUNT_UNAVAILABLE', error.message, { request }); }
2622
+ catch (error) { return accountRefusal(error); }
2590
2623
  if (cancelled()) return dropTurn(live, request);
2591
2624
  }
2592
2625
  }
@@ -2840,7 +2873,7 @@ export function createAssistantRuntime({
2840
2873
  // Every turn starts unrouted; a continuation or a route_decided "here" turn starts open.
2841
2874
  // Plan mode never routes: the brain explores read-only (the plan policy) and
2842
2875
  // the approved plan is routed on the next turn.
2843
- ensureGate(live)?.startTurn({ open: gateOpen || live.record.brain?.planMode === true, carry: gateCarry, taskId });
2876
+ ensureGate(live)?.startTurn({ open: gateOpen || live.record.brain?.planMode === true, carry: gateCarry, taskId, decided: gateDecided });
2844
2877
  // What this turn runs on, as the router compares a re-routed task with it (routerSession `turn`). The
2845
2878
  // brain process keeps it: a turn the CLI starts by itself afterwards (a task notification) runs on it too.
2846
2879
  const previousRun = live.turnRun;
@@ -3042,8 +3075,10 @@ export function createAssistantRuntime({
3042
3075
  const taskId = firstRun?.taskId || firstRun?.run?.turns?.find((turn) => turn.n === firstRun.turn)?.taskId || firstRun?.run?.taskId || live.record.taskId || null;
3043
3076
  // The decided "here" routes this turn carries out (one of them may hold the owner's computer approval).
3044
3077
  const computerRoutes = items.filter((item) => item.kind === 'route_decided' && item.route?.target?.kind === 'direct' && !(item.runIds || []).length).map((item) => String(item.route?.routeId || '')).filter(Boolean);
3078
+ // The routes the user decided for a worker: the turn stays unrouted, and its refusals name them (assistant-route-gate.js).
3079
+ const gateDecided = items.filter((item) => item.kind === 'route_decided' && item.route?.target?.kind === 'dispatch' && item.route?.routeId).map((item) => ({ routeId: String(item.route.routeId), target: item.route.target }));
3045
3080
  let result = null;
3046
- try { result = await runQuery(live, { text, system: true, taskId, gateOpen: decidedHere, computerRoutes }); }
3081
+ try { result = await runQuery(live, { text, system: true, taskId, gateOpen: decidedHere, gateDecided, computerRoutes }); }
3047
3082
  catch (error) {
3048
3083
  // A start that threw is a start that failed: its events stay open and the retry rules below apply (never a spin).
3049
3084
  log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`);
@@ -3235,12 +3270,49 @@ export function createAssistantRuntime({
3235
3270
  }
3236
3271
  return { ...brain, accountId: row.id, accountPolicy: 'auto' };
3237
3272
  }
3273
+ /** A conversation held from WhatsApp (bridge-made: `channel`, `remote.channel`). */
3274
+ function isPhoneSession(live) { return (live.record.channel || live.record.remote?.channel || null) === 'whatsapp'; }
3275
+ /**
3276
+ * Whether a WhatsApp conversation's account (Claude Code, Codex; not on Auto) moves to Auto · most
3277
+ * usage left before this turn. Nobody on a phone can switch an account that ran out, so there the
3278
+ * account follows usage within what was chosen (docs/whatsapp.md → The account):
3279
+ * - an account that cannot run moves: removed, signed out, or limited (its usage reading, or a limit
3280
+ * this conversation hit: conversationAccounts);
3281
+ * - the Default account moves while there is no provider conversation yet (a new conversation, or
3282
+ * one just switched to this provider): the panel's untouched brain names Default too, so it is
3283
+ * no deliberate choice, and Auto keeps it whenever it has the most usage left;
3284
+ * - an API-key account stays (a configuration, with no quota), and so does a named subscription
3285
+ * with usage left, and Default once its provider conversation exists (continuity).
3286
+ */
3287
+ function phoneAccountMoves(live, rows) {
3288
+ const active = rows.find(row => row.id === (live.record.brain.accountId || 'default'));
3289
+ if (!active) return true;
3290
+ if (active.mode === 'apiKey' || active.mode === 'api') return false;
3291
+ if (active.signedIn === false || active.usage?.limited === true) return true;
3292
+ const fresh = !live.brain && !live.record.providerSessionId && !live.record.providerThreadId;
3293
+ return fresh && active.id === 'default' && active.mode === 'subscription' && active.signedIn === true;
3294
+ }
3295
+ /**
3296
+ * The account a new session starts on. Auto picks the subscription with the most usage left
3297
+ * now, also when the brain names an account an earlier pick chose (the panel's last-used
3298
+ * brain, which "Same as the Assistant" on WhatsApp copies): a new session has no provider
3299
+ * conversation to keep. When nothing can be picked now (no signed-in subscription, all
3300
+ * limited) the named account stays, and the first turn's account check says why it cannot run.
3301
+ */
3302
+ async function startingAccount(brain) {
3303
+ if (brain.accountPolicy !== 'auto' || brain.accountId === 'auto' || !['claude-code', 'codex'].includes(brain.provider)) return resolveAutoAccount(brain);
3304
+ try { return await resolveAutoAccount({ ...brain, accountId: 'auto' }); }
3305
+ catch (error) {
3306
+ if (error?.code !== 'ACCOUNT_NO_SUBSCRIPTION' && error?.code !== 'ACCOUNTS_ALL_LIMITED') throw error;
3307
+ return brain;
3308
+ }
3309
+ }
3238
3310
  async function createSession({ brain = {}, label = null, cwd = null, windowId = null, fallback = false, channel = null, draft = false } = {}, internal = {}) {
3239
3311
  if (brain?.mcpProfile !== undefined) throw Object.assign(new Error('Use tools: [group ids].'), { code: 'MCP_PROFILE_REMOVED', status: 400 });
3240
3312
  const id = `assistant-${randomUUID()}`;
3241
3313
  const requested = normalizeSessionBrain({ ...brain, cwd: brain?.cwd || cwd || settings.defaultBrain.cwd || PACKAGE_ROOT }, settings.defaultBrain, { catalog: catalog?.peek?.() || null });
3242
3314
  const enabled = await enabledBrain(requested, { fallback: fallback === true, named: !!brain?.model });
3243
- const normalized = await resolveAutoAccount(enabled.brain);
3315
+ const normalized = await startingAccount(enabled.brain);
3244
3316
  const record = {
3245
3317
  id, brain: normalized, title: label ? clip(label, 60) : DEFAULT_SESSION_TITLE, project: detectProject(normalized.cwd) || 'global',
3246
3318
  createdAt: iso(now()), updatedAt: iso(now()), lastActiveAt: null, status: 'idle', providerSessionId: null, providerThreadId: null,
@@ -3328,9 +3400,13 @@ export function createAssistantRuntime({
3328
3400
  if ('agentDensity' in patch) applyAgentDensity(live, patch.agentDensity); // agents-p4
3329
3401
  if (patch.brain && typeof patch.brain === 'object') {
3330
3402
  // A provider switch that names no model starts from the new provider's
3331
- // default, never from the old provider's model id.
3403
+ // default, never from the old provider's model id. The same for the account: an
3404
+ // id is one provider's (a Claude account id means nothing to Codex), so a switch
3405
+ // that names none runs on the new provider's Default account.
3332
3406
  const switching = BRAIN_PROVIDERS.has(patch.brain.provider) && patch.brain.provider !== live.record.brain.provider;
3333
- const base = switching && !patch.brain.model ? { ...live.record.brain, model: null } : live.record.brain;
3407
+ const base = switching
3408
+ ? { ...live.record.brain, ...(!patch.brain.model ? { model: null } : {}), accountId: null, accountPolicy: 'manual' }
3409
+ : live.record.brain;
3334
3410
  // Public picker updates use arrays; stored records still convert on read.
3335
3411
  const input = { ...base, ...patch.brain, model: patch.brain.model || base.model };
3336
3412
  if (patch.brain.mcpProfile !== undefined) throw Object.assign(new Error('Use tools: [group ids].'), { code: 'MCP_PROFILE_REMOVED', status: 400 });
@@ -4298,8 +4374,10 @@ export function createAssistantRuntime({
4298
4374
  * the browser policy (every session, plan mode and subagents included), then the route gate. → { decision:
4299
4375
  * 'deny', reason } or null (no objection: the brain's approval mode decides). `call`: lib/antigravity/tool-call.js
4300
4376
  * acpCall. Antigravity's own bookkeeping steps (task boundaries, notes to the user) are never routed.
4377
+ * `spilledOutput`: the brain found the call reads only tool outputs Antigravity spilled into its home
4378
+ * (lib/antigravity/home.js antigravitySpilledOutputRead): the route gate lets it through, every other check stays.
4301
4379
  */
4302
- function antigravityGateCheck(live, call) {
4380
+ function antigravityGateCheck(live, call, { spilledOutput = false } = {}) {
4303
4381
  const name = acpToolName(call);
4304
4382
  const input = acpPolicyInput(call);
4305
4383
  const planned = planGate(live, 'antigravity', name, input);
@@ -4316,6 +4394,8 @@ export function createAssistantRuntime({
4316
4394
  const browserDenied = browserGate(live, name, input, { host: 'antigravity' });
4317
4395
  if (browserDenied) return { decision: 'deny', reason: browserDenied.reason };
4318
4396
  if (!live.gate || call.kind === 'think') return null;
4397
+ // The flag covers a plain read only (the brain sets it for nothing else; checked here too).
4398
+ if (spilledOutput === true && !call.mcp && (call.kind === 'read' || call.kind === 'search')) return null;
4319
4399
  const decision = decide(live, name);
4320
4400
  return decision.allow ? null : { decision: 'deny', reason: decision.reason };
4321
4401
  }
@@ -4332,7 +4412,7 @@ export function createAssistantRuntime({
4332
4412
  policyUrl: typeof ag.policyUrl === 'function' ? ag.policyUrl() : (ag.policyUrl || null),
4333
4413
  connect: ag.connect || undefined,
4334
4414
  userGemini: ag.userGemini || undefined,
4335
- policyCheck: (call) => antigravityGateCheck(live, call),
4415
+ policyCheck: (call, meta) => antigravityGateCheck(live, call, meta),
4336
4416
  // ACP counts tokens per session: what the session the record names had counted (a resume books only what follows).
4337
4417
  sessionUsageBase: saved && saved.sessionId && saved.sessionId === live.record.providerSessionId ? saved.usage || null : null,
4338
4418
  onAntigravitySession: (sessionId) => { if (sessionId && live.record.providerSessionId !== sessionId) { live.record.providerSessionId = sessionId; touch(live); } },
@@ -4469,6 +4549,8 @@ export function createAssistantRuntime({
4469
4549
  PreToolUse: [{
4470
4550
  hooks: [async (input) => {
4471
4551
  if (!live.gate || input?.agent_id) return {};
4552
+ // A Read of a tool result Claude Code saved for this session (a long recall or agent_list): never routed.
4553
+ if (claudeSpilledResultRead(input)) return {};
4472
4554
  const decision = decide(live, input?.tool_name);
4473
4555
  if (decision.allow) return {};
4474
4556
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: decision.reason } };
@@ -0,0 +1,53 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun — a brain's read of a tool output its own CLI saved to a file
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // A CLI that cuts a long tool output short in the model's context saves the whole output to a file of its own and
6
+ // tells the model to read it there. The route gate lets that read through before a turn is routed: the file holds
7
+ // the output of a tool the model already ran, and an unrouted turn runs only the always-allowed ones (recall,
8
+ // agent_list, agent_read …). Exactly the CLI's own file counts, never a link to another one.
9
+ //
10
+ // Claude Code <projects>/<project>/<session>/tool-results/<name>.txt|json, beside <session>.jsonl, the
11
+ // transcript its hook input names (claudeSpilledResultRead, the Claude brain's PreToolUse gate hook)
12
+ // Antigravity <home>/antigravity-cli/brain/<conversation>/.system_generated/steps/<n>/output.txt
13
+ // (lib/antigravity/home.js antigravitySpilledOutputRead)
14
+
15
+ import { lstatSync, realpathSync } from 'node:fs';
16
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
17
+
18
+ const CLAUDE_RESULT_NAME = '[A-Za-z0-9_][A-Za-z0-9_.-]{0,199}\\.(?:txt|json)';
19
+ const SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
20
+
21
+ /**
22
+ * Whether `file` lies under the CLI's own folder `anchor` at a path (relative to it) that `relRe` accepts, as a
23
+ * regular file with one name (no hard link) and with no symbolic link anywhere between `anchor` and it: its real
24
+ * path is that same relative path under the anchor's real path. Every folder level `relRe` names is checked that way,
25
+ * so put the anchor above them (a linked folder at the anchor itself would vouch for itself).
26
+ */
27
+ export function ownSpilledFile(file, anchor, relRe) {
28
+ if (typeof file !== 'string' || !file || typeof anchor !== 'string' || !anchor) return false;
29
+ const full = resolve(file);
30
+ const rel = relative(resolve(anchor), full);
31
+ if (!relRe.test(rel)) return false;
32
+ try {
33
+ if (realpathSync(full) !== join(realpathSync(anchor), rel)) return false;
34
+ const stat = lstatSync(full);
35
+ return stat.isFile() && stat.nlink === 1;
36
+ } catch { return false; }
37
+ }
38
+
39
+ /**
40
+ * A Claude Code PreToolUse hook input ({ tool_name, tool_input, transcript_path, session_id }) that only reads one
41
+ * of the session's own saved tool results: Read with an absolute file_path in the tool-results folder of the
42
+ * transcript the hook names.
43
+ */
44
+ export function claudeSpilledResultRead(input) {
45
+ if (String(input?.tool_name || '') !== 'Read') return false;
46
+ const file = input?.tool_input?.file_path;
47
+ const transcript = input?.transcript_path;
48
+ if (typeof file !== 'string' || !isAbsolute(file) || typeof transcript !== 'string' || !isAbsolute(transcript) || !transcript.endsWith('.jsonl')) return false;
49
+ const session = basename(transcript, '.jsonl');
50
+ if (!SESSION_ID_RE.test(session) || (input.session_id && String(input.session_id) !== session)) return false;
51
+ // Anchored at the transcript's folder: the session folder and tool-results must be real folders too.
52
+ return ownSpilledFile(file, dirname(transcript), new RegExp(`^${session}[\\\\/]tool-results[\\\\/]${CLAUDE_RESULT_NAME}$`));
53
+ }
@@ -151,6 +151,10 @@ export function createUserContextStore({
151
151
  return ensured;
152
152
  }
153
153
 
154
+ // The reads below say `+trashed_at IS NULL`: the plus keeps SQLite from choosing the index on `trashed_at` (it has
155
+ // no statistics, and that index names every live memory: 36,868 rows read whole to find 217, 30 ms on an idle
156
+ // machine and 1-3.8 s on a busy one, on the server's thread, 27 times in a day's stall log). With it the category's
157
+ // index is used: the same rows in under 2 ms.
154
158
  /** Every live, not superseded memory of the knowledge categories, parsed, newest first. Cached for 5 s. */
155
159
  function listKnowledge({ fresh = false } = {}) {
156
160
  if (!fresh && cache && Date.now() - cache.at < CACHE_MS) return cache.rows;
@@ -162,13 +166,13 @@ export function createUserContextStore({
162
166
  rows = db.prepare(`SELECT m.id, m.content, m.category, m.subcategory, m.project, m.importance, m.created_at, m.updated_at, m.related_memory_ids,
163
167
  md.kind, md.source_ref, (SELECT MAX(r.revision) FROM memory_revisions r WHERE r.memory_id = m.id) AS revision
164
168
  FROM memories m LEFT JOIN memory_metadata md ON md.memory_id = m.id
165
- WHERE m.trashed_at IS NULL AND m.category IN (${marks(names.length)})
169
+ WHERE +m.trashed_at IS NULL AND m.category IN (${marks(names.length)})
166
170
  AND NOT EXISTS (SELECT 1 FROM memory_relations s WHERE s.kind = 'supersedes' AND s.active = 1 AND s.to_id = m.id)
167
171
  ORDER BY m.updated_at DESC LIMIT ?`).all(...names, DIGEST.readLimit);
168
172
  } catch {
169
173
  // A store without the v2 tables: the memories alone.
170
174
  rows = db.prepare(`SELECT id, content, category, subcategory, project, importance, created_at, updated_at, related_memory_ids
171
- FROM memories WHERE trashed_at IS NULL AND category IN (${marks(names.length)}) ORDER BY updated_at DESC LIMIT ?`).all(...names, DIGEST.readLimit);
175
+ FROM memories WHERE +trashed_at IS NULL AND category IN (${marks(names.length)}) ORDER BY updated_at DESC LIMIT ?`).all(...names, DIGEST.readLimit);
172
176
  }
173
177
  } catch (error) { log('user-context:read-error', error?.message || String(error)); rows = []; }
174
178
  const parsed = rows.map((row) => parseKnowledge(row)).filter((item) => item.id && item.statement);
@@ -196,7 +200,7 @@ export function createUserContextStore({
196
200
  const names = categories();
197
201
  let vectors = [];
198
202
  try {
199
- vectors = getDb().prepare(`SELECT id, vector FROM memories WHERE trashed_at IS NULL AND category IN (${marks(names.length)}) ORDER BY updated_at DESC LIMIT ?`).all(...names, DIGEST.readLimit);
203
+ vectors = getDb().prepare(`SELECT id, vector FROM memories WHERE +trashed_at IS NULL AND category IN (${marks(names.length)}) ORDER BY updated_at DESC LIMIT ?`).all(...names, DIGEST.readLimit);
200
204
  } catch (error) { log('user-context:read-error', error?.message || String(error)); return []; }
201
205
  let query = null;
202
206
  try { query = await embed(String(text ?? '').slice(0, LEARN.messageClip)); } catch (error) { log('user-context:embed-error', error?.message || String(error)); return []; }