synabun 2.4.2 → 2.4.3

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 (103) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +23 -3
  4. package/lib/release-npm-ci.mjs +23 -1
  5. package/mcp-server/dist/services/neural-interface.js +1 -1
  6. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  7. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
  8. package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
  9. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
  10. package/mcp-server/package-lock.json +5 -5
  11. package/mcp-server/package.json +1 -1
  12. package/mcp-server/src/services/neural-interface.ts +1 -1
  13. package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
  14. package/neural-interface/i18n/en.json +50 -1
  15. package/neural-interface/i18n/pt-BR.json +57 -8
  16. package/neural-interface/lib/assistant-api.js +33 -0
  17. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  18. package/neural-interface/lib/assistant-dispatch.js +26 -2
  19. package/neural-interface/lib/assistant-envelope.js +40 -0
  20. package/neural-interface/lib/assistant-runtime.js +95 -10
  21. package/neural-interface/lib/browser-extension-adapter.js +1 -3
  22. package/neural-interface/lib/browser-extension-archive.js +149 -0
  23. package/neural-interface/lib/browser-extension-bridge.js +7 -4
  24. package/neural-interface/lib/browser-extension-folder.js +596 -76
  25. package/neural-interface/lib/browser-extension-package.js +200 -0
  26. package/neural-interface/lib/browser-extension-pin.js +84 -0
  27. package/neural-interface/lib/browser-extension-pin.json +33 -0
  28. package/neural-interface/lib/browser-extension-setup.js +105 -18
  29. package/neural-interface/lib/cli-install.js +23 -3
  30. package/neural-interface/lib/cli-update-planner.js +67 -4
  31. package/neural-interface/lib/native-loop-providers.js +10 -1
  32. package/neural-interface/lib/native-loop-runtime.js +20 -2
  33. package/neural-interface/lib/opencode-shell-read.js +107 -0
  34. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  35. package/neural-interface/lib/opencode-turn-release.js +173 -0
  36. package/neural-interface/lib/opencode-v2-client.js +4 -1
  37. package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
  38. package/neural-interface/lib/opencode2-client.js +341 -6
  39. package/neural-interface/lib/opencode2-translate.js +161 -4
  40. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  41. package/neural-interface/lib/whatsapp/bridge.js +52 -6
  42. package/neural-interface/package-lock.json +5 -5
  43. package/neural-interface/package.json +1 -1
  44. package/neural-interface/public/extension-setup.html +5 -2
  45. package/neural-interface/public/shared/agy/agy-panel.js +38 -10
  46. package/neural-interface/public/shared/assistant/asst-api.js +25 -0
  47. package/neural-interface/public/shared/assistant/asst-panel.js +69 -1
  48. package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
  49. package/neural-interface/public/shared/assistant/asst-render.js +138 -6
  50. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  51. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  52. package/neural-interface/public/shared/assistant/asst-styles.js +1 -0
  53. package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
  54. package/neural-interface/public/shared/extension-setup/es-page.js +10 -4
  55. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  56. package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
  57. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  58. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  59. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
  60. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  61. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
  62. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
  63. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
  64. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  65. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +346 -0
  66. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  67. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  68. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
  69. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  70. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  71. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  72. package/neural-interface/public/shared/settings/settings-browser-extension.js +54 -12
  73. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  74. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  75. package/neural-interface/public/shared/tray-auto-close.js +36 -6
  76. package/neural-interface/public/shared/ui-claude-panel.js +20 -0
  77. package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
  78. package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
  79. package/neural-interface/server.js +249 -35
  80. package/npm-shrinkwrap.json +5 -5
  81. package/package.json +1 -2
  82. package/browser-extension/content.js +0 -231
  83. package/browser-extension/engine.js +0 -658
  84. package/browser-extension/icons/icon-128.png +0 -0
  85. package/browser-extension/icons/icon-16.png +0 -0
  86. package/browser-extension/icons/icon-32.png +0 -0
  87. package/browser-extension/icons/icon-48.png +0 -0
  88. package/browser-extension/icons/status-off-16.png +0 -0
  89. package/browser-extension/icons/status-off-32.png +0 -0
  90. package/browser-extension/icons/status-off-48.png +0 -0
  91. package/browser-extension/icons/status-on-16.png +0 -0
  92. package/browser-extension/icons/status-on-32.png +0 -0
  93. package/browser-extension/icons/status-on-48.png +0 -0
  94. package/browser-extension/manifest.json +0 -58
  95. package/browser-extension/popup-strings.js +0 -250
  96. package/browser-extension/popup-view.js +0 -151
  97. package/browser-extension/popup.css +0 -166
  98. package/browser-extension/popup.html +0 -108
  99. package/browser-extension/popup.js +0 -359
  100. package/browser-extension/service-worker.js +0 -283
  101. package/browser-extension/setup-content.js +0 -36
  102. package/browser-extension/tokens.css +0 -326
  103. /package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"browser-extension-setup.js","sourceRoot":"","sources":["../../src/tools/browser-extension-setup.ts"],"names":[],"mappings":"AAAA,iHAAiH;AACjH,oHAAoH;AACpH,oHAAoH;AACpH,oGAAoG;AACpG,gGAAgG;AAEhG,MAAM,eAAe,GAAG,iDAAiD,CAAC;AAC1E,MAAM,IAAI,GAAG,0BAA0B,CAAC;AACxC,MAAM,KAAK,GAAG,qBAAqB,IAAI,kLAAkL,CAAC;AAC1N,MAAM,cAAc,GAAG,oEAAoE,CAAC;AAE5F,MAAM,KAAK,GAA2B;IACpC,qBAAqB,EACnB,uKAAuK,eAAe,KAAK,KAAK,KAAK,cAAc,EAAE;IACvN,wBAAwB,EACtB,gLAAgL,eAAe,KAAK,KAAK,KAAK,cAAc,EAAE;IAChO,yBAAyB,EACvB,+IAA+I,eAAe,wBAAwB,IAAI,gCAAgC,KAAK,6HAA6H;IAC9V,wBAAwB,EACtB,0LAA0L,eAAe,wBAAwB,IAAI,yEAAyE;CACjT,CAAC;AAEF,kHAAkH;AAClH,MAAM,UAAU,qBAAqB,CAAC,MAAkD;IACtF,MAAM,IAAI,GAAG,OAAO,MAAM,EAAE,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;IACjE,OAAO,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAChF,CAAC;AAED,kCAAkC;AAClC,MAAM,CAAC,MAAM,qBAAqB,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"browser-extension-setup.js","sourceRoot":"","sources":["../../src/tools/browser-extension-setup.ts"],"names":[],"mappings":"AAAA,iHAAiH;AACjH,oHAAoH;AACpH,oHAAoH;AACpH,oGAAoG;AACpG,sHAAsH;AACtH,oDAAoD;AACpD,EAAE;AACF,qHAAqH;AACrH,oHAAoH;AACpH,+GAA+G;AAC/G,kGAAkG;AAElG,MAAM,eAAe,GAAG,iDAAiD,CAAC;AAC1E,MAAM,IAAI,GAAG,0BAA0B,CAAC;AACxC,MAAM,KAAK,GAAG,qBAAqB,IAAI,kLAAkL,CAAC;AAC1N,MAAM,cAAc,GAAG,oEAAoE,CAAC;AAE5F,MAAM,KAAK,GAA2B;IACpC,qBAAqB,EACnB,uKAAuK,eAAe,KAAK,KAAK,KAAK,cAAc,EAAE;IACvN,wBAAwB,EACtB,gLAAgL,eAAe,KAAK,KAAK,KAAK,cAAc,EAAE;IAChO,yBAAyB,EACvB,+IAA+I,eAAe,wBAAwB,IAAI,gCAAgC,KAAK,4RAA4R;IAC7f,wBAAwB,EACtB,0LAA0L,eAAe,wBAAwB,IAAI,yEAAyE;CACjT,CAAC;AAEF,kHAAkH;AAClH,MAAM,UAAU,qBAAqB,CAAC,MAAkD;IACtF,MAAM,IAAI,GAAG,OAAO,MAAM,EAAE,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;IACjE,OAAO,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAChF,CAAC;AAED,kCAAkC;AAClC,MAAM,CAAC,MAAM,qBAAqB,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC"}
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "claude-memory-mcp",
3
- "version": "2.4.2",
3
+ "version": "2.4.3",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "claude-memory-mcp",
9
- "version": "2.4.2",
9
+ "version": "2.4.3",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@huggingface/transformers": "^3.0.0",
@@ -2353,9 +2353,9 @@
2353
2353
  }
2354
2354
  },
2355
2355
  "node_modules/body-parser": {
2356
- "version": "1.20.8",
2357
- "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.8.tgz",
2358
- "integrity": "sha512-JNcyFQ64OiijEkPzUBTCe+hyPXUD/3LEldGQ6iF5LR1w00mx9o7xtDWHXBY2iItjdCFGoilOLNQbH943ut7pHA==",
2356
+ "version": "1.20.9",
2357
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz",
2358
+ "integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==",
2359
2359
  "license": "MIT",
2360
2360
  "dependencies": {
2361
2361
  "bytes": "~3.1.2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-memory-mcp",
3
- "version": "2.4.2",
3
+ "version": "2.4.3",
4
4
  "private": true,
5
5
  "description": "Private MCP server runtime bundled with SynaBun for persistent memory and agent tooling",
6
6
  "license": "Apache-2.0",
@@ -26,7 +26,7 @@ const BASE_URL = process.env.NEURAL_INTERFACE_URL
26
26
  const DEFAULT_TIMEOUT = 10_000;
27
27
  const LONG_TIMEOUT = 30_000;
28
28
  // A page script. In the owner's everyday browser (the extension backend) one may run 30 s, and the Neural Interface
29
- // waits 35 s for the extension's answer (browser-extension/protocol.js: EVALUATE_TIMEOUT plus LONG_MARGIN); a shorter
29
+ // waits 35 s for the extension's answer (the extension contract, neural-interface/lib/browser-extension-protocol.js: EVALUATE_TIMEOUT plus LONG_MARGIN); a shorter
30
30
  // wait here would give up on a script that is still running and answers. The Playwright backends answer within their
31
31
  // own 10 s deadline, so for them this only bounds how long a lost answer is waited for.
32
32
  export const EVALUATE_TIMEOUT = 40_000;
@@ -2,7 +2,13 @@
2
2
  // JavaScript or watch the network yet. Each of these is a one-time owner setup in the browser, not a failure of the
3
3
  // page or of the call: the answer says what the owner does and what the agent can use meanwhile, so nobody retries,
4
4
  // reaches for another browser or reports the tool as broken. The codes are the extension contract's
5
- // (browser-extension/protocol.js ERROR_TEXT); a result with any other code is not one of these.
5
+ // (neural-interface/lib/browser-extension-protocol.js ERROR_TEXT, the app's own copy of the extension's protocol.js);
6
+ // a result with any other code is not one of these.
7
+ //
8
+ // The extension itself is not part of the app: the owner's "Connect your browser" downloads the version this SynaBun
9
+ // release pins from synabun.ai and verifies it, and a newer pin is fetched in the background after start. A browser
10
+ // that runs an older extension is told to Reload it once that folder is up to date, which SynaBun's Settings →
11
+ // Browser says. An agent never tells the owner to fetch or load the extension from anywhere else.
6
12
 
7
13
  const EXTENSIONS_PAGE = 'chrome://extensions (edge://extensions in Edge)';
8
14
  const NAME = '"SynaBun Browser Bridge"';
@@ -15,7 +21,7 @@ const SETUP: Record<string, string> = {
15
21
  USER_SCRIPTS_UNSUPPORTED:
16
22
  `The owner's browser cannot run page JavaScript for an extension (that needs Chrome or Edge 135 or later), so nothing was run. Tell the user to update the browser, then open ${EXTENSIONS_PAGE}, ${ALLOW}. ${MEANWHILE_READ}`,
17
23
  EXTENSION_RELOAD_REQUIRED:
18
- `The owner's browser still runs an older SynaBun Browser Bridge than this needs (1.4.0 or later), so nothing was done. Tell the user to open ${EXTENSIONS_PAGE} and press Reload on ${NAME}; for browser_evaluate, then ${ALLOW} once more. Until then read the page with browser_snapshot or browser_content, and wait with a selector or a fixed timeout.`,
24
+ `The owner's browser still runs an older SynaBun Browser Bridge than this needs (1.4.0 or later), so nothing was done. Tell the user to open ${EXTENSIONS_PAGE} and press Reload on ${NAME}; for browser_evaluate, then ${ALLOW} once more. If Reload changes nothing, SynaBun has not finished downloading this version's extension from synabun.ai: its Settings → Browser says so and offers Try again. Until then read the page with browser_snapshot or browser_content, and wait with a selector or a fixed timeout.`,
19
25
  NETWORK_IDLE_UNAVAILABLE:
20
26
  `The SynaBun extension cannot watch this browser's network requests yet (its webRequest permission is not in effect), so it cannot tell when the network is idle. Tell the user to open ${EXTENSIONS_PAGE} and press Reload on ${NAME}. Until then wait with loadState "load", a selector or a fixed timeout.`,
21
27
  };
@@ -1,4 +1,11 @@
1
1
  {
2
+ "shellStop": {
3
+ "failed": "Stop could not end {commands} ({reason}). It is still running, so this turn goes on. Press Stop again.",
4
+ "failedAgain": "Stop could not end {commands} again ({reason}). It is still running. Press Stop again, or Stop anyway to end this turn here.",
5
+ "anyway": "Stop anyway",
6
+ "abandoned": "Turn stopped. {commands} may still be running on this machine: SynaBun keeps trying to end it in the background.",
7
+ "unknownReason": "no reason given"
8
+ },
2
9
  "workerQuestion": {
3
10
  "deliveryFailed": "Could not deliver your answer. Try again.",
4
11
  "resolved": "Resolved"
@@ -10518,6 +10525,26 @@
10518
10525
  "error": "Error: {text}"
10519
10526
  },
10520
10527
  "rack": {
10528
+ "shell": {
10529
+ "running": "running",
10530
+ "runningNow": "Running",
10531
+ "background": "in the background",
10532
+ "stopped": "stopped",
10533
+ "timedOut": "timed out",
10534
+ "exit": "exit {code}",
10535
+ "loadFull": "Load full output",
10536
+ "loading": "Loading…",
10537
+ "jump": "Jump to latest",
10538
+ "copy": "Copy output",
10539
+ "copied": "Copied",
10540
+ "label": "Command output",
10541
+ "noOutputYet": "No output yet",
10542
+ "noOutput": "No output",
10543
+ "reading": "Reading the output…",
10544
+ "gone": "OpenCode no longer keeps the output of this command.",
10545
+ "partial": "Showing the last {shown} of {size}.",
10546
+ "capped": "Showing the last {shown} of {size}: the whole output is too long to show here."
10547
+ },
10521
10548
  "kind": {
10522
10549
  "think": "Thinking",
10523
10550
  "shell": "Terminal",
@@ -14650,12 +14677,13 @@
14650
14677
  "noControlled": "No tabs under agent control. Start a task in SynaBun. Its agent and tabs will appear here.",
14651
14678
  "takeBack": "Take back",
14652
14679
  "setupTitle": "Connect your browser",
14653
- "setupHelp": "Opens your default browser and the extension folder. You’ll finish three short install steps in the browser.",
14680
+ "setupHelp": "Downloads the extension from synabun.ai the first time, then opens your default browser and the extension folder. You’ll finish three short install steps in the browser.",
14654
14681
  "setupConnect": "Connect your browser",
14655
14682
  "setupReconnect": "Run setup again",
14656
14683
  "setupReinstall": "Reinstall",
14657
14684
  "setupCancel": "Cancel setup",
14658
14685
  "reloadNeeded": "The extension in your browser is older than SynaBun's copy: open your browser's extensions page and press Reload on SynaBun Browser Bridge.",
14686
+ "reloadRepaired": "SynaBun replaced the files in the extension folder with its verified copy. Your browser keeps running the old files until you reload the extension: open chrome://extensions (edge://extensions in Edge), find SynaBun Browser Bridge and press its Reload button. Then confirm below.",
14659
14687
  "setup": {
14660
14688
  "documentTitle": "Connect your browser — SynaBun",
14661
14689
  "title": "Connect your browser",
@@ -14680,6 +14708,7 @@
14680
14708
  "openedIn": "The setup page opened in {browser}. Continue there.",
14681
14709
  "restart": "Restart setup",
14682
14710
  "reloadNeeded": "The extension in {browser} is older than SynaBun's copy: press Reload on SynaBun Browser Bridge in the extensions page.",
14711
+ "reloadRepaired": "SynaBun replaced the files in the extension folder with its verified copy. {browser} may still run the old files: press Reload on SynaBun Browser Bridge in the extensions page, then confirm it in SynaBun Settings → Browser.",
14683
14712
  "liveIdle": "No setup is running. Press \"Connect your browser\" in SynaBun Settings → Browser.",
14684
14713
  "liveWaiting": "Keep this page open. We’ll detect SynaBun as soon as it’s installed.",
14685
14714
  "liveFound": "Extension found. Pairing automatically…",
@@ -14697,16 +14726,21 @@
14697
14726
  "error": "Something went wrong. Start again from SynaBun Settings → Browser.",
14698
14727
  "errorSETUP_EXPIRED": "This setup ran out of time. Start again.",
14699
14728
  "errorEXTENSION_FOLDER_FAILED": "SynaBun could not prepare the extension folder.",
14729
+ "errorEXTENSION_FOLDER_UNSAFE": "SynaBun didn’t use the extension folder in its data folder: it’s a link, belongs to another user, or others can write to it (on Linux, a group that is not your own private group counts as others). Nothing was changed. Fix or remove the browser-extension folder, then try again.",
14700
14730
  "errorOPEN_FAILED": "SynaBun could not open this page in the browser by itself. The steps below still work.",
14701
14731
  "errorSETUP_NOT_ACTIVE": "No setup is running. Start again from SynaBun Settings → Browser.",
14702
14732
  "errorSETUP_TICKETS_USED": "This setup used up its pairing attempts. Start again, or pair with a code in Settings.",
14703
14733
  "errorPAGE_SECRET_REQUIRED": "Reload this page.",
14704
14734
  "errorPEER_UNAVAILABLE": "SynaBun could not identify this browser. Reload this page.",
14735
+ "errorEXTENSION_DOWNLOAD_OFFLINE": "SynaBun couldn’t reach synabun.ai to download the extension. Check your internet connection, then try again.",
14736
+ "errorEXTENSION_DOWNLOAD_UNAVAILABLE": "synabun.ai doesn’t have the extension this SynaBun version needs right now. Try again later, or update SynaBun.",
14737
+ "errorEXTENSION_VERIFY_FAILED": "The download wasn’t the file this SynaBun version expects, so nothing was installed. Try again. If it keeps happening, update SynaBun.",
14705
14738
  "settings_waiting_for_extension": "Setup is open in {browser}. Finish the three install steps there. This card updates automatically when pairing completes.",
14706
14739
  "settings_pairing": "Pairing automatically… The extension is installed. Establishing its connection to SynaBun—no code to enter.",
14707
14740
  "settings_connected": "Connected.",
14708
14741
  "settings_unsupported": "{browser} can’t run the extension. Open the setup in another installed browser:",
14709
14742
  "settings_error": "The setup stopped ({code}). Start again.",
14743
+ "settings_downloading": "Downloading the extension from synabun.ai… {percent}%",
14710
14744
  "eyebrow": "{browser} · three steps, then automatic pairing",
14711
14745
  "stepOpenTitle": "Open the extensions page",
14712
14746
  "stepDeveloperTitle": "Turn on Developer mode",
@@ -14733,6 +14767,14 @@
14733
14767
  "needHelp": "Something isn’t working",
14734
14768
  "helpText": "No extension detected? Check that you selected the browser-extension folder containing manifest.json, and that SynaBun is enabled in this browser profile.",
14735
14769
  "policyText": "An organization policy may prevent Developer mode or Load unpacked. Ask your browser administrator for help, or choose an allowed browser.",
14770
+ "movedText": "Extension gone after a SynaBun update? Earlier versions loaded it from inside SynaBun’s install folder, which no longer contains it. Load the folder shown in step 3 instead: it is the same extension, and it pairs again by itself.",
14771
+ "downloadingTitle": "Downloading the extension…",
14772
+ "liveDownloading": "Downloading the SynaBun extension from synabun.ai…",
14773
+ "downloadingHelp": "SynaBun checks the download against this release before it installs anything. The setup guide opens when it’s ready.",
14774
+ "downloadProgress": "{received} of {total} KB",
14775
+ "downloadErrorTitle": "We couldn’t get the extension",
14776
+ "retryDownload": "Try again",
14777
+ "updateNeeded": "SynaBun is updating the extension folder for this version. When this note changes, press Reload on SynaBun Browser Bridge in the extensions page.",
14736
14778
  "copyFailed": "Couldn’t copy. Select the address and copy it manually."
14737
14779
  },
14738
14780
  "card": {
@@ -14746,6 +14788,7 @@
14746
14788
  "settingsTitle": "Your everyday browser",
14747
14789
  "openGuide": "Open setup guide",
14748
14790
  "setupDefault": "Full control is the default. Agents can use sites where you’re already signed in.",
14791
+ "reloadConfirm": "I reloaded the extension",
14749
14792
  "advanced": "Files and limits",
14750
14793
  "details": "Connection details",
14751
14794
  "untitledTab": "Untitled tab",
@@ -14762,6 +14805,12 @@
14762
14805
  "unpairedHelp": "Connect this browser to SynaBun on your computer.",
14763
14806
  "launching": "Opening your browser…",
14764
14807
  "launchingHelp": "Preparing your setup guide and extension folder.",
14808
+ "downloading": "Downloading the extension…",
14809
+ "downloadingHelp": "From synabun.ai. SynaBun verifies it before anything is installed.",
14810
+ "updating": "Updating the extension folder for this SynaBun version…",
14811
+ "updateFailed": "SynaBun couldn’t download this version’s extension, so the folder still holds the previous one. Your browser keeps working with it.",
14812
+ "folderPending": "Created when you press Connect your browser",
14813
+ "movedHelp": "Extension missing from your browser after an update? Earlier SynaBun versions loaded it from inside the app’s install folder, which no longer contains it. Run the setup below and load the folder it shows.",
14765
14814
  "setupRunningTitle": "Setup is open in {browser}",
14766
14815
  "setupRunningHelp": "Finish the three install steps there. This card updates automatically when pairing completes.",
14767
14816
  "pairing": "Pairing automatically…",
@@ -1,4 +1,11 @@
1
1
  {
2
+ "shellStop": {
3
+ "failed": "Parar não conseguiu encerrar {commands} ({reason}). O comando continua em execução, então este turno continua. Pressione Parar de novo.",
4
+ "failedAgain": "Parar não conseguiu encerrar {commands} de novo ({reason}). O comando continua em execução. Pressione Parar de novo, ou Parar assim mesmo para encerrar este turno aqui.",
5
+ "anyway": "Parar assim mesmo",
6
+ "abandoned": "Turno parado. {commands} pode continuar em execução nesta máquina: o SynaBun continua tentando encerrá-lo em segundo plano.",
7
+ "unknownReason": "sem motivo informado"
8
+ },
2
9
  "workerQuestion": {
3
10
  "deliveryFailed": "Não foi possível enviar sua resposta. Tente novamente.",
4
11
  "resolved": "Resolvido"
@@ -1463,7 +1470,7 @@
1463
1470
  "help": "Armazenamento, busca e backups"
1464
1471
  },
1465
1472
  "ai_decisions": {
1466
- "label": "Jev",
1473
+ "label": "Decisões de IA",
1467
1474
  "help": "Avaliações inteligentes e custo"
1468
1475
  },
1469
1476
  "projects": {
@@ -1521,7 +1528,7 @@
1521
1528
  "purpose": "Veja onde suas memórias ficam, escolha como o SynaBun as encontra e mantenha uma cópia que você possa restaurar."
1522
1529
  },
1523
1530
  "ai_decisions": {
1524
- "title": "Jev",
1531
+ "title": "Decisões de IA",
1525
1532
  "purpose": "Controle onde as avaliações inteligentes ajudam, o que podem usar e quanto custam."
1526
1533
  },
1527
1534
  "projects": {
@@ -5037,11 +5044,11 @@
5037
5044
  "omitted": "Outros {n} não couberam e só aparecem quando forem relevantes.",
5038
5045
  "learn": {
5039
5046
  "killSwitch": "Sem aprender no momento: as avaliações inteligentes estão desativadas neste servidor (SYNABUN_TYPESAFE=off). O que já se sabe continua sendo usado.",
5040
- "masterOff": "Sem aprender no momento: o {page} está desativado. O que já se sabe continua sendo usado.",
5041
- "noKey": "Sem aprender no momento: o {page} está sem chave de API. O que já se sabe continua sendo usado.",
5042
- "surfaceOff": "Sem aprender no momento: “User learning” está desativado no {page}. O que já se sabe continua sendo usado.",
5043
- "waiting": "Sem aprender por um instante: o {page} precisou esperar antes do próximo pedido. O que já se sabe continua sendo usado.",
5044
- "unavailable": "Sem aprender no momento: o {page} não está disponível. O que já se sabe continua sendo usado."
5047
+ "masterOff": "Sem aprender no momento: as avaliações estão desativadas em {page}. O que já se sabe continua sendo usado.",
5048
+ "noKey": "Sem aprender no momento: falta a chave de API em {page}. O que já se sabe continua sendo usado.",
5049
+ "surfaceOff": "Sem aprender no momento: “User learning” está desativado em {page}. O que já se sabe continua sendo usado.",
5050
+ "waiting": "Sem aprender por um instante: o serviço de {page} precisou esperar antes do próximo pedido. O que já se sabe continua sendo usado.",
5051
+ "unavailable": "Sem aprender no momento: o serviço de {page} não está disponível. O que já se sabe continua sendo usado."
5045
5052
  },
5046
5053
  "openPage": "Abrir {page}",
5047
5054
  "writer": {
@@ -10464,6 +10471,26 @@
10464
10471
  "error": "Erro: {text}"
10465
10472
  },
10466
10473
  "rack": {
10474
+ "shell": {
10475
+ "running": "em execução",
10476
+ "runningNow": "Em execução",
10477
+ "background": "em segundo plano",
10478
+ "stopped": "interrompido",
10479
+ "timedOut": "tempo esgotado",
10480
+ "exit": "saída {code}",
10481
+ "loadFull": "Carregar saída completa",
10482
+ "loading": "Carregando…",
10483
+ "jump": "Ir para o fim",
10484
+ "copy": "Copiar saída",
10485
+ "copied": "Copiado",
10486
+ "label": "Saída do comando",
10487
+ "noOutputYet": "Ainda sem saída",
10488
+ "noOutput": "Sem saída",
10489
+ "reading": "Lendo a saída…",
10490
+ "gone": "O OpenCode não guarda mais a saída deste comando.",
10491
+ "partial": "Mostrando os últimos {shown} de {size}.",
10492
+ "capped": "Mostrando os últimos {shown} de {size}: a saída completa é longa demais para mostrar aqui."
10493
+ },
10467
10494
  "kind": {
10468
10495
  "think": "Pensando",
10469
10496
  "shell": "Terminal de comandos",
@@ -14650,12 +14677,13 @@
14650
14677
  "noControlled": "Nenhuma aba sob controle de agentes. Inicie uma tarefa no SynaBun. O agente e suas abas aparecerão aqui.",
14651
14678
  "takeBack": "Retomar",
14652
14679
  "setupTitle": "Conectar seu navegador",
14653
- "setupHelp": "Abre seu navegador padrão e a pasta da extensão. Você conclui três etapas de instalação no navegador.",
14680
+ "setupHelp": "Baixa a extensão de synabun.ai na primeira vez e depois abre seu navegador padrão e a pasta da extensão. Você conclui três etapas de instalação no navegador.",
14654
14681
  "setupConnect": "Conectar seu navegador",
14655
14682
  "setupReconnect": "Configurar novamente",
14656
14683
  "setupReinstall": "Reinstalar",
14657
14684
  "setupCancel": "Cancelar configuração",
14658
14685
  "reloadNeeded": "A extensão no seu navegador é mais antiga que a cópia do SynaBun: abra a página de extensões do navegador e clique em Recarregar no SynaBun Browser Bridge.",
14686
+ "reloadRepaired": "O SynaBun substituiu os arquivos da pasta da extensão pela cópia verificada. Seu navegador continua executando os arquivos antigos até você recarregar a extensão: abra chrome://extensions (edge://extensions no Edge), encontre o SynaBun Browser Bridge e clique no botão Recarregar. Depois, confirme abaixo.",
14659
14687
  "setup": {
14660
14688
  "documentTitle": "Conectar seu navegador — SynaBun",
14661
14689
  "title": "Conectar seu navegador",
@@ -14680,6 +14708,7 @@
14680
14708
  "openedIn": "A página de configuração abriu no {browser}. Continue lá.",
14681
14709
  "restart": "Reiniciar configuração",
14682
14710
  "reloadNeeded": "A extensão no {browser} é mais antiga que a cópia do SynaBun: clique em Recarregar no SynaBun Browser Bridge na página de extensões.",
14711
+ "reloadRepaired": "O SynaBun substituiu os arquivos da pasta da extensão pela cópia verificada. O {browser} ainda pode executar os arquivos antigos: clique em Recarregar no SynaBun Browser Bridge na página de extensões e depois confirme em Configurações → Navegador do SynaBun.",
14683
14712
  "liveIdle": "Nenhuma configuração em andamento. Clique em \"Conectar seu navegador\" em Configurações → Navegador do SynaBun.",
14684
14713
  "liveWaiting": "Mantenha esta página aberta. Detectaremos o SynaBun assim que for instalado.",
14685
14714
  "liveFound": "Extensão encontrada. Pareando automaticamente…",
@@ -14697,16 +14726,21 @@
14697
14726
  "error": "Algo deu errado. Comece de novo em Configurações → Navegador do SynaBun.",
14698
14727
  "errorSETUP_EXPIRED": "O tempo desta configuração acabou. Comece de novo.",
14699
14728
  "errorEXTENSION_FOLDER_FAILED": "O SynaBun não conseguiu preparar a pasta da extensão.",
14729
+ "errorEXTENSION_FOLDER_UNSAFE": "O SynaBun não usou a pasta da extensão na pasta de dados: ela é um link, pertence a outro usuário ou outras pessoas podem alterá-la (no Linux, um grupo que não seja o seu grupo pessoal conta como outras pessoas). Nada foi mudado. Corrija ou remova a pasta browser-extension e tente novamente.",
14700
14730
  "errorOPEN_FAILED": "O SynaBun não conseguiu abrir esta página no navegador sozinho. Os passos abaixo continuam valendo.",
14701
14731
  "errorSETUP_NOT_ACTIVE": "Nenhuma configuração em andamento. Comece de novo em Configurações → Navegador do SynaBun.",
14702
14732
  "errorSETUP_TICKETS_USED": "Esta configuração esgotou as tentativas de pareamento. Comece de novo ou pareie com um código nas Configurações.",
14703
14733
  "errorPAGE_SECRET_REQUIRED": "Recarregue esta página.",
14704
14734
  "errorPEER_UNAVAILABLE": "O SynaBun não conseguiu identificar este navegador. Recarregue esta página.",
14735
+ "errorEXTENSION_DOWNLOAD_OFFLINE": "O SynaBun não conseguiu acessar synabun.ai para baixar a extensão. Verifique sua conexão com a internet e tente novamente.",
14736
+ "errorEXTENSION_DOWNLOAD_UNAVAILABLE": "O synabun.ai não tem agora a extensão de que esta versão do SynaBun precisa. Tente mais tarde ou atualize o SynaBun.",
14737
+ "errorEXTENSION_VERIFY_FAILED": "O download não era o arquivo que esta versão do SynaBun espera, então nada foi instalado. Tente novamente. Se continuar, atualize o SynaBun.",
14705
14738
  "settings_waiting_for_extension": "Configuração aberta no {browser}. Conclua as três etapas de instalação lá. Este cartão será atualizado automaticamente após o pareamento.",
14706
14739
  "settings_pairing": "Pareando automaticamente… A extensão está instalada. Conectando ao SynaBun, sem precisar digitar um código.",
14707
14740
  "settings_connected": "Conectado.",
14708
14741
  "settings_unsupported": "{browser} não executa a extensão. Abra a configuração em outro navegador instalado:",
14709
14742
  "settings_error": "A configuração parou ({code}). Comece de novo.",
14743
+ "settings_downloading": "Baixando a extensão de synabun.ai… {percent}%",
14710
14744
  "eyebrow": "{browser} · três etapas e pareamento automático",
14711
14745
  "stepOpenTitle": "Abra a página de extensões",
14712
14746
  "stepDeveloperTitle": "Ative o Modo do desenvolvedor",
@@ -14733,6 +14767,14 @@
14733
14767
  "needHelp": "Algo não está funcionando",
14734
14768
  "helpText": "Extensão não detectada? Verifique se selecionou a pasta browser-extension que contém manifest.json e se o SynaBun está ativado neste perfil.",
14735
14769
  "policyText": "Uma política da organização pode impedir o Modo do desenvolvedor ou Carregar sem compactação. Peça ajuda ao administrador ou escolha um navegador permitido.",
14770
+ "movedText": "A extensão sumiu depois de atualizar o SynaBun? Versões anteriores a carregavam de dentro da pasta de instalação do SynaBun, que não a contém mais. Carregue a pasta mostrada na etapa 3: é a mesma extensão, e ela pareia de novo sozinha.",
14771
+ "downloadingTitle": "Baixando a extensão…",
14772
+ "liveDownloading": "Baixando a extensão do SynaBun de synabun.ai…",
14773
+ "downloadingHelp": "O SynaBun confere o download com esta versão antes de instalar qualquer coisa. O guia de configuração abre quando estiver pronto.",
14774
+ "downloadProgress": "{received} de {total} KB",
14775
+ "downloadErrorTitle": "Não foi possível obter a extensão",
14776
+ "retryDownload": "Tentar novamente",
14777
+ "updateNeeded": "O SynaBun está atualizando a pasta da extensão para esta versão. Quando este aviso mudar, clique em Recarregar no SynaBun Browser Bridge na página de extensões.",
14736
14778
  "copyFailed": "Não foi possível copiar. Selecione o endereço e copie manualmente."
14737
14779
  },
14738
14780
  "card": {
@@ -14746,6 +14788,7 @@
14746
14788
  "settingsTitle": "Seu navegador do dia a dia",
14747
14789
  "openGuide": "Abrir guia de configuração",
14748
14790
  "setupDefault": "O controle total é o padrão. Os agentes podem usar sites em que você já está conectado.",
14791
+ "reloadConfirm": "Já recarreguei a extensão",
14749
14792
  "advanced": "Arquivos e limites",
14750
14793
  "details": "Detalhes da conexão",
14751
14794
  "untitledTab": "Aba sem título",
@@ -14762,6 +14805,12 @@
14762
14805
  "unpairedHelp": "Conecte este navegador ao SynaBun no seu computador.",
14763
14806
  "launching": "Abrindo seu navegador…",
14764
14807
  "launchingHelp": "Preparando o guia de configuração e a pasta da extensão.",
14808
+ "downloading": "Baixando a extensão…",
14809
+ "downloadingHelp": "De synabun.ai. O SynaBun a verifica antes de instalar qualquer coisa.",
14810
+ "updating": "Atualizando a pasta da extensão para esta versão do SynaBun…",
14811
+ "updateFailed": "O SynaBun não conseguiu baixar a extensão desta versão, então a pasta continua com a anterior. Seu navegador segue funcionando com ela.",
14812
+ "folderPending": "Criada quando você clicar em Conectar seu navegador",
14813
+ "movedHelp": "A extensão sumiu do navegador depois de uma atualização? Versões anteriores do SynaBun a carregavam de dentro da pasta de instalação do app, que não a contém mais. Execute a configuração abaixo e carregue a pasta que ela mostrar.",
14765
14814
  "setupRunningTitle": "Configuração aberta no {browser}",
14766
14815
  "setupRunningHelp": "Conclua as três etapas de instalação lá. Este cartão será atualizado automaticamente após o pareamento.",
14767
14816
  "pairing": "Pareando automaticamente…",
@@ -1169,6 +1169,39 @@ export function createAssistantApi({
1169
1169
  res.json({ ok: true, usage: runtime.usageView?.(id, task) ?? usage?.taskView(id, task) ?? null, budget: sessionBudgetView(id) });
1170
1170
  } catch (error) { sendError(res, error); }
1171
1171
  });
1172
+ // The shell commands of a session's OpenCode brain (which tool call each belongs to, whether it runs, how it
1173
+ // ended) and a page of what one printed: what the panel's terminal blocks show. The owner's page alone reads
1174
+ // them (this boot's page secret, no agent header): what a command printed is display data, so no brain and no
1175
+ // worker gets it here, and with it nothing of it reaches a model's context. The session in the path is the one
1176
+ // whose own brain is asked, and that brain reads only a command it ran itself (runtime.shellOutput).
1177
+ function shellReader(req, res) {
1178
+ const agent = ['x-synabun-terminal', 'x-synabun-assistant', 'x-synabun-role', 'x-synabun-brain-token', 'x-synabun-desktop-grant'].some((name) => req.get(name));
1179
+ if (agent || isGuestRequest(req) || callerContext(req).kind !== 'ui') { uiOnly(req, res, 'A command\'s output is shown in the user\'s own Assistant panel only.'); return false; }
1180
+ // The automation browser verifies as the owner while the owner's setting lets it act as owner; it still never
1181
+ // reads what a command printed (review S4): a page an agent drives would hand it to that agent's model.
1182
+ let fromAutomationBrowser = false;
1183
+ try { fromAutomationBrowser = typeof pageSession?.isAutomationBrowser === 'function' && pageSession.isAutomationBrowser(req) === true; } catch { fromAutomationBrowser = true; }
1184
+ if (fromAutomationBrowser) { res.status(403).json({ ok: false, code: 'WORKER_BROWSER', error: 'A command\'s output is shown in the owner\'s own browser or the app, never in SynaBun\'s automation browser.' }); return false; }
1185
+ return true;
1186
+ }
1187
+ router.get('/sessions/:id/shells', noStore, (req, res) => {
1188
+ if (!requireRuntime(res) || !shellReader(req, res)) return;
1189
+ const shells = typeof runtime.shellList === 'function' ? runtime.shellList(req.params.id) : null;
1190
+ if (!shells) return res.status(404).json({ ok: false, code: 'SESSION_NOT_FOUND', error: `Unknown assistant session ${req.params.id}` });
1191
+ res.json({ ok: true, shells });
1192
+ });
1193
+ router.get('/sessions/:id/shells/:shellId/output', noStore, async (req, res) => {
1194
+ if (!requireRuntime(res) || !shellReader(req, res)) return;
1195
+ if (typeof runtime.shellOutput !== 'function') return res.status(404).json({ ok: false, code: 'SHELL_OUTPUT_GONE', error: 'The output of that command is no longer available.' });
1196
+ const shellId = String(req.params.shellId || '');
1197
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(shellId)) return res.status(400).json({ ok: false, code: 'SHELL_ID_INVALID', error: 'That is not a command of this conversation.' });
1198
+ const number = (value) => (typeof value === 'string' && /^\d{1,15}$/.test(value) ? Number(value) : undefined);
1199
+ try {
1200
+ const page = await runtime.shellOutput(req.params.id, { shellId, cursor: number(req.query.cursor), tail: number(req.query.tail), limit: number(req.query.limit) });
1201
+ if (!page || page.ok === false) return res.status(Number(page?.status) >= 400 ? Number(page.status) : 502).json({ ok: false, code: page?.code || 'SHELL_OUTPUT_FAILED', error: page?.error || 'The output could not be read.' });
1202
+ res.json({ ok: true, ...page.data });
1203
+ } catch (error) { sendError(res, error); }
1204
+ });
1172
1205
  router.get('/sessions/:id', (req, res) => {
1173
1206
  if (!requireRuntime(res)) return;
1174
1207
  const session = runtime.getSession(req.params.id, { transcript: req.query.transcript !== '0', limit: clampInt(req.query.limit, 1, 2000, 400) });
@@ -13,9 +13,10 @@ import { dirname, resolve } from 'node:path';
13
13
  import { fileURLToPath, pathToFileURL } from 'node:url';
14
14
  import { normalizeOpenCodeModel } from '../native-loop-providers.js';
15
15
  import { agentOf, mcpServersOf, opencodeConfigFilePath, readOpencodeConfigDocument, setAgent, setMcpServer, withPlugin, withoutPlugin } from '../opencode-config.js';
16
- import { createOpenCodeEnvelopeTranslator, opencodeControlResponse } from '../assistant-envelope.js';
16
+ import { createOpenCodeEnvelopeTranslator, opencodeControlResponse, opencodeShellView } from '../assistant-envelope.js';
17
17
  import { opencodePlanPermission, opencodeReadOnlyPermission, planDenyMessage, readOnlyDenyMessage } from '../assistant-plan-permissions.js';
18
18
  import { planModeInstructions } from '../assistant-persona.js';
19
+ import { readShellOutputPage, SHELL_OUTPUT_GONE_TEXT } from '../opencode-shell-read.js';
19
20
  import { waitForSynabunTools, synabunConfigured, synabunToolsTimeoutText, OPENCODE_MCP_READY_TIMEOUT_MS, OPENCODE_MCP_SETTLE_MS, OPENCODE_MCP_LIST_GRACE_MS } from '../opencode-mcp-ready.js';
20
21
  export { synabunMcpState } from '../opencode-mcp-ready.js';
21
22
 
@@ -154,6 +155,9 @@ export function patchOpenCodeAssistantConfig(xdgRoot, { persona = '', role = 'as
154
155
  }
155
156
 
156
157
 
158
+ /** How many shell commands of its tool calls a brain remembers (a command still running is never forgotten for a newer one). */
159
+ export const OPENCODE_BRAIN_SHELLS_MAX = 200;
160
+
157
161
  /** The assistant's OpenCode approval mode: 'auto' (auto-accept) or 'default'. */
158
162
  export function opencodeApprovalMode(mode) {
159
163
  return mode === 'auto' || mode === 'acceptEdits' || mode === 'bypassPermissions' ? 'auto' : 'default';
@@ -208,12 +212,18 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
208
212
  let startPromise = null;
209
213
  let synabunExpected = false;
210
214
  let stops = 0;
215
+ // After a "Stop anyway" (a command may still run): what OpenCode does for that command's end (a start the client
216
+ // interrupts, its error) is no turn of the runtime's, and reaches nobody until the next turn of the user's.
217
+ let muted = false;
211
218
  let waitingAbort = null;
212
219
  let interruptPrompt = null;
213
220
  let exited = false;
214
221
  const serveExitMessage = 'The isolated OpenCode server stopped during this turn. Send the message again to resume.';
215
222
  const serveExitError = () => Object.assign(new Error(serveExitMessage), { code: 'OPENCODE_SERVE_EXITED' });
216
223
  const serveExited = () => exited || entry?.proc?.exitCode != null || entry?.proc?.signalCode != null;
224
+ const stopMayFail = () => {
225
+ try { return !!(client && sessionId && client.getClient?.()?.stopNeedsKill?.(sessionId) === true); } catch { return false; }
226
+ };
217
227
  function onServeExit() {
218
228
  if (disposed) return;
219
229
  exited = true;
@@ -248,8 +258,31 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
248
258
  if (typeof plan === 'boolean') planMode = plan;
249
259
  }
250
260
 
261
+ // The shell commands of this brain's tool calls, as its event stream told them (shellId → the panel's view of
262
+ // it, assistant-envelope.js opencodeShellView): what a panel is sent when it attaches, and the only commands
263
+ // whose output this brain reads for it. Display data: nothing of it goes to the model, the transcript or a meter.
264
+ const shells = new Map();
265
+ function noteShell(shell) {
266
+ if (!shell?.id) return;
267
+ shells.delete(shell.id);
268
+ shells.set(shell.id, shell);
269
+ if (shells.size <= OPENCODE_BRAIN_SHELLS_MAX) return;
270
+ for (const [id, known] of shells) {
271
+ if (shells.size <= OPENCODE_BRAIN_SHELLS_MAX) break;
272
+ if (known.status !== 'running') shells.delete(id);
273
+ }
274
+ }
275
+
251
276
  const emit = (packet) => {
252
277
  if (disposed) return;
278
+ if (packet.type === 'assistant:shell') { noteShell(packet.shell); sink.send(packet); return; }
279
+ if (muted) {
280
+ // What OpenCode does for an abandoned command's end is no turn of anyone's: its model output goes nowhere. A
281
+ // permission request or a question of it would wait where nobody sees it, so it is refused at once, and every
282
+ // panel of the session says so (review 29cd51fe, finding 3).
283
+ if (packet.type === 'control_request' && client) refuseMuted(packet);
284
+ return;
285
+ }
253
286
  const decision = packet.type === 'control_request' && client ? opencodeAutoDecision(packet, { approvalMode: remoteReadOnly ? 'default' : approvalMode, planMode: planning(), readOnly: remoteReadOnly }) : null;
254
287
  if (decision) {
255
288
  const body = opencodeControlResponse(packet, { behavior: decision });
@@ -268,6 +301,18 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
268
301
  };
269
302
  sink.send({ type: 'engine', engine: 'opencode', brain: 'opencode' });
270
303
 
304
+ /** A request asked after a "Stop anyway", before the user's next turn: refused, never left pending, and said. */
305
+ function refuseMuted(packet) {
306
+ const body = opencodeControlResponse(packet, { behavior: 'deny' });
307
+ const tool = packet.request?.tool_name || (body.kind === 'question' ? 'a question' : 'a permission');
308
+ sink.send({ type: 'stderr', text: `Declined ${tool}: OpenCode asked it after Stop anyway, while no turn of yours was running. Send a message to go on.` });
309
+ if (!body.requestID) return;
310
+ const call = body.kind === 'question'
311
+ ? client.question.reject({ requestID: body.requestID, directory: cwd })
312
+ : client.permission.reply({ requestID: body.requestID, reply: 'reject', directory: cwd, message: 'The user stopped this turn.' });
313
+ Promise.resolve(call).catch((error) => { if (!serveExited()) sink.send({ type: 'error', message: `OpenCode decline failed: ${error?.message || error}` }); });
314
+ }
315
+
271
316
  function bindTranslator() {
272
317
  translator = createOpenCodeEnvelopeTranslator({
273
318
  sessionId, emit, brain: { cwd, model: brain.model || null }, planTurn: () => turnPlanned,
@@ -279,6 +324,21 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
279
324
  unsubscribe = source?.onEvent?.((envelope) => {
280
325
  if (!disposed && !serveExited()) translator.handle(envelope?.eventType || '', envelope?.event || {});
281
326
  }) || null;
327
+ recallShells();
328
+ }
329
+
330
+ // A brain that comes back to a serve already running (a resumed conversation) learns the commands that serve
331
+ // still knows for its session; what the stream says from now on is newer, so a command already noted stays.
332
+ async function recallShells() {
333
+ const asked = sessionId;
334
+ if (!asked || typeof client?.extra?.shell?.list !== 'function') return;
335
+ let listed = null;
336
+ try { listed = await client.extra.shell.list({ sessionID: asked }); } catch { return; }
337
+ if (disposed || asked !== sessionId) return;
338
+ for (const item of Array.isArray(listed?.data) ? listed.data : []) {
339
+ const shell = opencodeShellView(item);
340
+ if (shell?.callID && !shells.has(shell.id)) emit({ type: 'assistant:shell', shell });
341
+ }
282
342
  }
283
343
 
284
344
  /** The serve's MCP servers as an `mcp_status` event (the runtime reads whether SynaBun, and so agent_route, is reachable). */
@@ -331,12 +391,14 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
331
391
  needsRestart: serveExited,
332
392
  start,
333
393
  async sendUserTurn({ text, images = [], model = null, effort = null, permissionMode: mode = null, planMode: plan = null } = {}) {
394
+ muted = false;
334
395
  const stop = stops;
335
396
  await start();
336
397
  if (disposed || stops !== stop) return false;
337
398
  if (serveExited()) throw serveExitError();
338
399
  applyModes(mode, plan);
339
400
  turnActive = true;
401
+ translator?.noteTurnStart?.();
340
402
  // The runtime passes the effective model/effort on every turn (the record
341
403
  // may have changed since this brain started; routed turns override it).
342
404
  const parts = [{ type: 'text', text }, ...opencodeImageParts(images)];
@@ -390,12 +452,31 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
390
452
  throw serveExited() ? serveExitError() : error;
391
453
  } finally { interruptPrompt = null; }
392
454
  },
393
- async abort() {
394
- stops += 1;
395
- waitingAbort?.abort();
396
- if (serveExited()) return;
397
- try { if (client && sessionId) await client.session.abort({ sessionID: sessionId, directory: cwd }); } catch {}
455
+ /** Could a Stop fail now (a command in the background to end, lib/opencode2-client.js stopNeedsKill)? */
456
+ stopMayFail: () => stopMayFail(),
457
+ /**
458
+ * Stop the turn. A Stop that has a command to end tears nothing down before OpenCode confirmed its end: when it
459
+ * could not (lib/opencode2-client.js abortSession, review B3) the turn goes on, held for the command, and the
460
+ * error (code SHELL_STOP_FAILED, `shells`) says which and why. `force` ("Stop anyway"): the turn ends whatever
461
+ * the command does; → `{ abandoned }`, the commands that may still run.
462
+ */
463
+ async abort({ force = false } = {}) {
464
+ const mayFail = !force && stopMayFail();
465
+ if (!mayFail) { stops += 1; waitingAbort?.abort(); }
466
+ if (serveExited()) return { abandoned: [] };
467
+ let answer = null;
468
+ try { if (client && sessionId) answer = await client.session.abort({ sessionID: sessionId, directory: cwd, ...(force ? { force: true } : {}) }); } catch (error) {
469
+ if (error?.cause?.name === 'ShellStopFailed' && !serveExited()) {
470
+ error.code = 'SHELL_STOP_FAILED';
471
+ error.shells = Array.isArray(error.data?.shells) ? error.data.shells : [];
472
+ throw error;
473
+ }
474
+ }
475
+ if (mayFail) { stops += 1; waitingAbort?.abort(); }
476
+ const abandoned = Array.isArray(answer?.data?.abandoned) ? answer.data.abandoned : [];
398
477
  if (!serveExited()) emit({ type: 'aborted' });
478
+ if (force) muted = true;
479
+ return { abandoned };
399
480
  },
400
481
  async setPermissionMode(mode, { planMode: plan = null } = {}) { applyModes(mode, plan); sink.send({ type: 'mode_changed', mode: approvalMode, planMode }); },
401
482
  respondControl(requestId, response) {
@@ -413,9 +494,31 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
413
494
  async compact() {
414
495
  await start();
415
496
  turnPlanned = false;
497
+ // A compact is the user's own request: what it says is theirs again, even right after a Stop anyway.
498
+ muted = false;
416
499
  await client.session.compact({ sessionID: sessionId, directory: cwd });
417
500
  },
418
501
  async mcpStatus() { await reportMcpStatus(); },
502
+ /** The shell commands of this brain's tool calls, oldest first (what a panel that attaches is shown). */
503
+ shells: () => [...shells.values()],
504
+ /**
505
+ * A page of what one of those commands printed (stdout and stderr as written, in order), for the panel that
506
+ * shows it: from the byte `cursor`, or the last `tail` bytes. Only a command this brain ran is read, on its
507
+ * own serve. → { status, data: { output, cursor, size, from } } or { ok: false, status, error }. Never throws.
508
+ */
509
+ async shellOutput({ shellId, cursor, tail, limit } = {}) {
510
+ const id = typeof shellId === 'string' ? shellId : '';
511
+ if (!id || !shells.has(id)) return { ok: false, status: 404, error: 'That command is not one of this conversation.' };
512
+ const api = client?.extra?.shell;
513
+ if (disposed || serveExited() || typeof api?.output !== 'function') return { ok: false, status: 404, error: SHELL_OUTPUT_GONE_TEXT };
514
+ try {
515
+ return await readShellOutputPage(api, { shellID: id, directory: cwd, cursor, tail, limit });
516
+ } catch (error) {
517
+ const status = Number(error?.status);
518
+ // OpenCode keeps a finished command's output for a while only (404); any other failure may pass.
519
+ return { ok: false, status: status >= 400 && status < 600 ? status : 502, error: status === 404 ? SHELL_OUTPUT_GONE_TEXT : (error?.message || 'The output could not be read.') };
520
+ }
521
+ },
419
522
  async reconcileUsage(meter) {
420
523
  if (!client || !sessionId || !meter || serveExited()) return false;
421
524
  let failed = false;
@@ -441,7 +544,18 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
441
544
  return !failed;
442
545
  },
443
546
  // The session resumed is the conversation now: the usage meter's root follows it.
444
- async resume(id) { if (!id) return; sessionId = id; deps.onOpenCodeRoot?.(id); if (client) bindTranslator(); },
547
+ async resume(id) {
548
+ if (!id) return;
549
+ // Another provider conversation (/resume): the commands of the one before are not this one's, neither to
550
+ // list nor to read (review S3). The panels hear the new list; the commands its serve knows follow.
551
+ if (id !== sessionId && shells.size) {
552
+ shells.clear();
553
+ if (!disposed) sink.send({ type: 'assistant:shells' });
554
+ }
555
+ sessionId = id;
556
+ deps.onOpenCodeRoot?.(id);
557
+ if (client) bindTranslator();
558
+ },
445
559
  async listSessions() { await start(); const rows = await client.session.list({ directory: cwd }).catch(() => null); return Array.isArray(rows?.data) ? rows.data : []; },
446
560
  isBusy() { return turnActive || pendingControls.size > 0; },
447
561
  identity() { return { providerSessionId: sessionId, providerThreadId: null, accountId: null, model: brain.model || null, effort: null, cwd, costUsd, busy: turnActive, termId }; },