synabun 2.4.2 → 2.4.4
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.
- package/CHANGELOG.md +39 -0
- package/README.md +1 -1
- package/docs/browser-extension-bridge.md +83 -34
- package/lib/release-npm-ci.mjs +23 -1
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +8 -1
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/services/identity.d.ts +2 -0
- package/mcp-server/dist/services/identity.d.ts.map +1 -1
- package/mcp-server/dist/services/identity.js +4 -0
- package/mcp-server/dist/services/identity.js.map +1 -1
- package/mcp-server/dist/services/memory-client.d.ts +5 -0
- package/mcp-server/dist/services/memory-client.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-client.js +21 -2
- package/mcp-server/dist/services/memory-client.js.map +1 -1
- package/mcp-server/dist/services/memory-writer.d.ts +3 -0
- package/mcp-server/dist/services/memory-writer.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-writer.js +7 -1
- package/mcp-server/dist/services/memory-writer.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +11 -1
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +68 -18
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/services/typesafe-config.d.ts +38 -2
- package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe-config.js +260 -8
- package/mcp-server/dist/services/typesafe-config.js.map +1 -1
- package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
- package/mcp-server/dist/tools/agents.d.ts +3 -1
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +11 -6
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
- package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
- package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
- package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-observe.js +113 -27
- package/mcp-server/dist/tools/browser-observe.js.map +1 -1
- package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
- package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
- package/mcp-server/dist/tools/browser-readers.js +17 -0
- package/mcp-server/dist/tools/browser-readers.js.map +1 -0
- package/mcp-server/dist/tools/remember.d.ts.map +1 -1
- package/mcp-server/dist/tools/remember.js +6 -2
- package/mcp-server/dist/tools/remember.js.map +1 -1
- package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
- package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
- package/mcp-server/dist/tools/youtube/analytics.js +25 -20
- package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
- package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
- package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
- package/mcp-server/dist/tools/youtube/helpers.js +7 -3
- package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
- package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
- package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
- package/mcp-server/dist/tools/youtube/navigate.js +5 -3
- package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
- package/mcp-server/dist/tools/youtube/playlist.js +2 -2
- package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
- package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
- package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
- package/mcp-server/dist/tools/youtube/readers.js +15 -0
- package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
- package/mcp-server/package-lock.json +5 -5
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +8 -1
- package/mcp-server/src/services/identity.ts +5 -0
- package/mcp-server/src/services/memory-client.ts +32 -12
- package/mcp-server/src/services/memory-writer.ts +5 -2
- package/mcp-server/src/services/neural-interface.ts +66 -19
- package/mcp-server/src/services/typesafe-config.ts +268 -7
- package/mcp-server/src/tools/agents.ts +12 -6
- package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
- package/mcp-server/src/tools/browser-observe.ts +117 -28
- package/mcp-server/src/tools/browser-readers.ts +19 -0
- package/mcp-server/src/tools/remember.ts +6 -1
- package/mcp-server/src/tools/youtube/analytics.ts +26 -28
- package/mcp-server/src/tools/youtube/helpers.ts +8 -2
- package/mcp-server/src/tools/youtube/navigate.ts +6 -7
- package/mcp-server/src/tools/youtube/playlist.ts +2 -2
- package/mcp-server/src/tools/youtube/readers.ts +15 -0
- package/neural-interface/i18n/en.json +189 -1
- package/neural-interface/i18n/pt-BR.json +196 -8
- package/neural-interface/lib/assistant-api.js +123 -0
- package/neural-interface/lib/assistant-brains/claude.js +10 -0
- package/neural-interface/lib/assistant-brains/opencode.js +121 -7
- package/neural-interface/lib/assistant-dispatch.js +302 -44
- package/neural-interface/lib/assistant-envelope.js +40 -0
- package/neural-interface/lib/assistant-memory.js +3 -1
- package/neural-interface/lib/assistant-persona.js +6 -0
- package/neural-interface/lib/assistant-router.js +18 -8
- package/neural-interface/lib/assistant-runtime.js +182 -11
- package/neural-interface/lib/assistant-task-prompt.js +15 -2
- package/neural-interface/lib/browser-connection-state.js +20 -0
- package/neural-interface/lib/browser-extension-adapter.js +221 -17
- package/neural-interface/lib/browser-extension-archive.js +149 -0
- package/neural-interface/lib/browser-extension-bridge.js +46 -10
- package/neural-interface/lib/browser-extension-folder.js +635 -76
- package/neural-interface/lib/browser-extension-package.js +201 -0
- package/neural-interface/lib/browser-extension-pin.js +84 -0
- package/neural-interface/lib/browser-extension-pin.json +35 -0
- package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +111 -13
- package/neural-interface/lib/browser-extension-setup.js +108 -19
- package/neural-interface/lib/browser-extension-update.js +104 -0
- package/neural-interface/lib/browser-extraction.js +38 -14
- package/neural-interface/lib/claude-bg-tasks.js +183 -0
- package/neural-interface/lib/claude-history.js +12 -1
- package/neural-interface/lib/cli-install.js +23 -3
- package/neural-interface/lib/cli-update-planner.js +67 -4
- package/neural-interface/lib/confined-fs.js +25 -0
- package/neural-interface/lib/coordination/operations.js +2 -0
- package/neural-interface/lib/db.js +39 -16
- package/neural-interface/lib/editor-completion-opencode.js +2 -2
- package/neural-interface/lib/git-bash/manager.js +28 -3
- package/neural-interface/lib/git-status-runner.js +31 -3
- package/neural-interface/lib/loop-inventory.js +162 -0
- package/neural-interface/lib/loop-stall.js +74 -4
- package/neural-interface/lib/memory-session-capture.js +157 -66
- package/neural-interface/lib/native-loop-providers.js +82 -13
- package/neural-interface/lib/native-loop-runtime.js +23 -2
- package/neural-interface/lib/opencode-protocol.js +4 -2
- package/neural-interface/lib/opencode-shell-read.js +107 -0
- package/neural-interface/lib/opencode-stop-failures.js +40 -0
- package/neural-interface/lib/opencode-turn-release.js +173 -0
- package/neural-interface/lib/opencode-v2-client.js +4 -1
- package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
- package/neural-interface/lib/opencode2-client.js +341 -6
- package/neural-interface/lib/opencode2-translate.js +161 -4
- package/neural-interface/lib/peer-identity.js +62 -16
- package/neural-interface/lib/session-cache-builder.js +66 -18
- package/neural-interface/lib/session-capture-gate.js +42 -0
- package/neural-interface/lib/session-indexer.js +28 -20
- package/neural-interface/lib/teams/scheduler.js +3 -2
- package/neural-interface/lib/terminal-token-redaction.js +83 -0
- package/neural-interface/lib/ui-blob-api.js +14 -5
- package/neural-interface/lib/ui-blob-store.js +302 -39
- package/neural-interface/lib/whatsapp/bridge.js +52 -6
- package/neural-interface/package-lock.json +5 -5
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/extension-setup.html +6 -2
- package/neural-interface/public/shared/agy/agy-panel.js +38 -10
- package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
- package/neural-interface/public/shared/assistant/asst-api.js +67 -0
- package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
- package/neural-interface/public/shared/assistant/asst-panel.js +354 -11
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
- package/neural-interface/public/shared/assistant/asst-render.js +343 -10
- package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
- package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
- package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
- package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
- package/neural-interface/public/shared/assistant/asst-state.js +241 -2
- package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +21 -0
- package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
- package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
- package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
- package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
- package/neural-interface/public/shared/browser-extension-updates.js +88 -0
- package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
- package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
- package/neural-interface/public/shared/extension-setup/es-page.js +25 -12
- package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
- package/neural-interface/public/shared/extension-update-view.js +34 -0
- package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
- package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
- package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
- package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +350 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
- package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
- package/neural-interface/public/shared/settings/settings-browser-extension.js +61 -13
- package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
- package/neural-interface/public/shared/shell-stop-view.js +83 -0
- package/neural-interface/public/shared/styles.css +4 -0
- package/neural-interface/public/shared/tour/tour-actor.js +14 -3
- package/neural-interface/public/shared/tray-auto-close.js +36 -6
- package/neural-interface/public/shared/ui-claude-panel.js +130 -1
- package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
- package/neural-interface/public/shared/ui-notifications.js +23 -4
- package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
- package/neural-interface/public/shared/ui-settings-entry.js +6 -0
- package/neural-interface/public/shared/ui-tray-columns.js +9 -2
- package/neural-interface/public/shared/worker-end.js +18 -0
- package/neural-interface/scripts/patch-node-pty.mjs +151 -0
- package/neural-interface/scripts/rebuild-pty.js +10 -0
- package/neural-interface/server.js +725 -308
- package/npm-shrinkwrap.json +5 -5
- package/package.json +1 -2
- package/browser-extension/content.js +0 -231
- package/browser-extension/engine.js +0 -658
- package/browser-extension/icons/icon-128.png +0 -0
- package/browser-extension/icons/icon-16.png +0 -0
- package/browser-extension/icons/icon-32.png +0 -0
- package/browser-extension/icons/icon-48.png +0 -0
- package/browser-extension/icons/status-off-16.png +0 -0
- package/browser-extension/icons/status-off-32.png +0 -0
- package/browser-extension/icons/status-off-48.png +0 -0
- package/browser-extension/icons/status-on-16.png +0 -0
- package/browser-extension/icons/status-on-32.png +0 -0
- package/browser-extension/icons/status-on-48.png +0 -0
- package/browser-extension/manifest.json +0 -58
- package/browser-extension/popup-strings.js +0 -250
- package/browser-extension/popup-view.js +0 -151
- package/browser-extension/popup.css +0 -166
- package/browser-extension/popup.html +0 -108
- package/browser-extension/popup.js +0 -359
- package/browser-extension/service-worker.js +0 -283
- package/browser-extension/setup-content.js +0 -36
- package/browser-extension/tokens.css +0 -326
|
@@ -4,6 +4,13 @@
|
|
|
4
4
|
// shows the folder in Finder, Explorer or the file manager. The owner does the three steps no app may do for them
|
|
5
5
|
// (the extensions page, Developer mode, Load unpacked); the extension then pairs by itself with a one-time token.
|
|
6
6
|
//
|
|
7
|
+
// The folder's files are the one package this release pins, downloaded from synabun.ai and verified
|
|
8
|
+
// (lib/browser-extension-package.js). A folder that is already there is used as it is, in the same request as before.
|
|
9
|
+
// One that is not there yet, or is older than the pin, is fetched first: the setup is then `downloading` (with the
|
|
10
|
+
// bytes so far), and the browser and the folder are opened only once the verified files are in place. A download that
|
|
11
|
+
// fails ends the setup with its code (offline, unavailable, verification failed) and Start again tries once more;
|
|
12
|
+
// nothing is ever installed that did not verify.
|
|
13
|
+
//
|
|
7
14
|
// Every route that reaches this is the owner's (server.js mounts them behind the same guard as pairing and the mode:
|
|
8
15
|
// ownerRouteGuard, this boot's page secret, no automation caller). Nothing here starts a program by itself: `exec` is
|
|
9
16
|
// injected (server.js: execFile, no shell, detached) and gets a plan from lib/browser-default.js.
|
|
@@ -13,29 +20,60 @@
|
|
|
13
20
|
// bridge accepts it once, in its pairing handshake, and forgets it (lib/browser-extension-bridge.js
|
|
14
21
|
// beginSetupPairing). It is never logged, never in a status and never in a URL.
|
|
15
22
|
import { launchPlan, revealPlan, SUPPORTED_BROWSER_IDS } from './browser-default.js';
|
|
16
|
-
import { SETUP_PAGE_PATH } from './browser-extension-folder.js';
|
|
23
|
+
import { compareVersions, SETUP_PAGE_PATH } from './browser-extension-folder.js';
|
|
17
24
|
import { randomBytes } from 'node:crypto';
|
|
18
25
|
|
|
19
|
-
export const SETUP_STATES = Object.freeze(['idle', 'waiting-for-extension', 'pairing', 'connected', 'unsupported', 'error']);
|
|
26
|
+
export const SETUP_STATES = Object.freeze(['idle', 'downloading', 'waiting-for-extension', 'pairing', 'connected', 'unsupported', 'error']);
|
|
27
|
+
/** The codes a download of the extension package can end a setup with (lib/browser-extension-package.js). */
|
|
28
|
+
export const DOWNLOAD_ERRORS = Object.freeze(['EXTENSION_DOWNLOAD_OFFLINE', 'EXTENSION_DOWNLOAD_UNAVAILABLE', 'EXTENSION_VERIFY_FAILED']);
|
|
20
29
|
export const SETUP_WINDOW_MS = 15 * 60 * 1000;
|
|
21
30
|
export const TICKET_MS = 2 * 60 * 1000;
|
|
22
31
|
export const MAX_TICKETS = 5;
|
|
23
32
|
const fail = (code, message = code) => { throw Object.assign(new Error(message), { code }); };
|
|
24
33
|
|
|
34
|
+
/**
|
|
35
|
+
* Whether the browser should be told to reload the extension: it is connected, the folder holds what this release
|
|
36
|
+
* wants (the pinned version, or a newer one a later release left there) and the browser runs something else. While
|
|
37
|
+
* the folder itself is older than the pin a Reload changes nothing: that is `updateNeeded`, which SynaBun settles by
|
|
38
|
+
* downloading the pinned package. `reloadPending`: the folder's marker asks for a Reload until the setup page saw the
|
|
39
|
+
* extension running again; `reloadReason` says why. 'version': a verified upgrade awaits the new peer. 'port': the setup port changed while the version stayed, and the
|
|
40
|
+
* browser still runs the old manifest (asked only while the extension is connected). 'repair': files that were not
|
|
41
|
+
* the pinned extension were replaced, and the browser may still run them at the same version, connected or not (the
|
|
42
|
+
* changed code may not connect at all): asked until the owner confirms the Reload in Settings, and said in its own
|
|
43
|
+
* words (`reloadRepaired`).
|
|
44
|
+
*/
|
|
45
|
+
export function extensionVersions({ connected, extensionVersion, folderVersion, pinnedVersion, reloadPending = false, reloadReason = null }) {
|
|
46
|
+
const current = !!folderVersion && (!pinnedVersion || compareVersions(folderVersion, pinnedVersion) >= 0);
|
|
47
|
+
const repaired = current && reloadPending === true && reloadReason === 'repair';
|
|
48
|
+
const reloadNeeded = repaired || (current && reloadPending === true && reloadReason === 'version') || !!(connected && current && (extensionVersion !== folderVersion || reloadPending === true));
|
|
49
|
+
return {
|
|
50
|
+
reloadNeeded,
|
|
51
|
+
updateNeeded: !!(folderVersion && pinnedVersion && compareVersions(folderVersion, pinnedVersion) < 0),
|
|
52
|
+
...(repaired ? { reloadRepaired: true } : {}),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
25
56
|
/**
|
|
26
57
|
* `bridge` (createExtensionBridge), `detect()` → { browser, installedBrowsers } (browser-default.js detectBrowsers with
|
|
27
|
-
* the system's runners), `prepare()` → { folder, version, changed }
|
|
28
|
-
*
|
|
29
|
-
* `
|
|
58
|
+
* the system's runners), `prepare({ signal })` → { folder, version, changed } once the folder is ready to load
|
|
59
|
+
* (browser-extension-package.js ensure: it may download), `exec(cmd, args)` starts a program (never a shell),
|
|
60
|
+
* `appOrigin()` is this server's own origin on loopback (http://127.0.0.1:<port>), `platform` the OS,
|
|
61
|
+
* `folderVersion()` the version the folder holds, `packageStatus()` → { pinnedVersion, needs, phase, received, total,
|
|
62
|
+
* code, reloadPending } (browser-extension-package.js status; `needs` says that `prepare` will download),
|
|
63
|
+
* `confirmReload()` the setup page saw the extension's content script on this port (browser-extension-package.js; it
|
|
64
|
+
* never clears a repair's Reload).
|
|
30
65
|
*/
|
|
31
66
|
export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin, platform = process.platform, now = Date.now,
|
|
32
|
-
windowMs = SETUP_WINDOW_MS, ticketMs = TICKET_MS, maxTickets = MAX_TICKETS, folderVersion = () => null } = {}) {
|
|
67
|
+
windowMs = SETUP_WINDOW_MS, ticketMs = TICKET_MS, maxTickets = MAX_TICKETS, folderVersion = () => null, packageStatus = () => ({}), confirmReload = () => false, updateStatus } = {}) {
|
|
33
68
|
let setup = null;
|
|
69
|
+
// The latest start, from its first step: a cancel or a later start ends it before it prepares or opens anything.
|
|
70
|
+
let attempt = null;
|
|
34
71
|
const pageUrl = () => `${appOrigin()}${SETUP_PAGE_PATH}`;
|
|
35
72
|
const describe = browser => browser ? { id: browser.id, name: browser.name, supported: browser.supported === true, extensionsUrl: browser.extensionsUrl || null } : null;
|
|
36
73
|
function state() {
|
|
37
74
|
if (!setup) return 'idle';
|
|
38
75
|
if (setup.error) return 'error';
|
|
76
|
+
if (setup.preparing) return 'downloading';
|
|
39
77
|
const bridgeStatus = bridge.status();
|
|
40
78
|
// Paired by this setup: a pairing made after it began (its token, or the typed code as a fallback). Connected once
|
|
41
79
|
// the extension's first inventory arrived; "Pairing…" from the token's handshake until then.
|
|
@@ -59,16 +97,22 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
|
|
|
59
97
|
}
|
|
60
98
|
function view() {
|
|
61
99
|
const current = state(), bridgeStatus = bridge.status();
|
|
62
|
-
const
|
|
100
|
+
const pkg = packageStatus() || {};
|
|
101
|
+
const version = Object.hasOwn(pkg, 'folderVersion') ? pkg.folderVersion : folderVersion();
|
|
102
|
+
const pinnedVersion = typeof pkg.pinnedVersion === 'string' ? pkg.pinnedVersion : null;
|
|
63
103
|
return {
|
|
64
104
|
state: current,
|
|
105
|
+
...(updateStatus ? { update: updateStatus(bridgeStatus, pkg) } : {}),
|
|
65
106
|
...(setup ? { setupId: setup.id, browser: describe(setup.browser), defaultBrowser: describe(setup.defaultBrowser), installedBrowsers: setup.installed.map(describe),
|
|
66
107
|
folder: setup.folder, extensionsUrl: setup.browser?.extensionsUrl || null, opened: setup.opened, revealed: setup.revealed, expiresAt: setup.until } : {}),
|
|
67
108
|
...(setup?.error ? { code: setup.error.code } : {}),
|
|
68
109
|
connected: bridgeStatus.connected, paired: bridgeStatus.paired, bridgePort: bridgeStatus.port,
|
|
69
|
-
extensionVersion: bridgeStatus.extensionVersion || null, folderVersion: version,
|
|
70
|
-
// The
|
|
71
|
-
|
|
110
|
+
extensionVersion: bridgeStatus.extensionVersion || null, folderVersion: version, pinnedVersion,
|
|
111
|
+
// The bytes so far while the pinned package is on its way (the setup's own download, or an update's).
|
|
112
|
+
...(pkg.phase === 'downloading' ? { download: { received: Number(pkg.received) || 0, total: Number(pkg.total) || 0 } } : {}),
|
|
113
|
+
// The browser runs another copy than the folder holds (or an extension from before versions were reported);
|
|
114
|
+
// or the folder itself is older than this release's extension, which a download settles, never a Reload.
|
|
115
|
+
...extensionVersions({ connected: bridgeStatus.connected, extensionVersion: bridgeStatus.extensionVersion, folderVersion: version, pinnedVersion, reloadPending: pkg.reloadPending === true, reloadReason: pkg.reloadReason ?? null }),
|
|
72
116
|
};
|
|
73
117
|
}
|
|
74
118
|
return {
|
|
@@ -79,9 +123,16 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
|
|
|
79
123
|
*/
|
|
80
124
|
async start({ browserId } = {}) {
|
|
81
125
|
if (browserId !== undefined && browserId !== null && !SUPPORTED_BROWSER_IDS.includes(browserId)) fail('INVALID_MESSAGE');
|
|
82
|
-
if (setup) bridge.endSetupPairing();
|
|
126
|
+
if (setup) { bridge.endSetupPairing(); setup.stop?.abort(); }
|
|
127
|
+
// This start is the current one before its first wait: a cancel during the browser detection, or a later start
|
|
128
|
+
// whose detection ends first, leaves this one nothing to do when its own detection ends.
|
|
129
|
+
attempt?.stop.abort();
|
|
130
|
+
const own = { stop: new AbortController() };
|
|
131
|
+
attempt = own;
|
|
132
|
+
const superseded = () => attempt !== own || own.stop.signal.aborted;
|
|
83
133
|
let detected;
|
|
84
134
|
try { detected = await detect(); } catch { detected = { browser: null, installedBrowsers: [] }; }
|
|
135
|
+
if (superseded()) return view();
|
|
85
136
|
const installed = Array.isArray(detected?.installedBrowsers) ? detected.installedBrowsers.filter(b => b?.supported) : [];
|
|
86
137
|
const defaultBrowser = detected?.browser || { id: 'unknown', name: 'Unknown browser', supported: false, extensionsUrl: null };
|
|
87
138
|
let browser = defaultBrowser;
|
|
@@ -91,16 +142,47 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
|
|
|
91
142
|
}
|
|
92
143
|
setup = { id: randomBytes(12).toString('hex'), startedAt: now(), until: now() + windowMs, browser, defaultBrowser, installed,
|
|
93
144
|
folder: null, opened: false, revealed: false, tickets: 0, pairedBefore: bridge.status().pairedAt || 0, error: null };
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
145
|
+
const mine = setup;
|
|
146
|
+
mine.stop = own.stop;
|
|
147
|
+
// A browser that cannot run the extension gets no download: the page offers the installed ones, and choosing one
|
|
148
|
+
// starts the setup again.
|
|
149
|
+
if (!browser.supported && (packageStatus() || {}).needs) return view();
|
|
150
|
+
// Once the folder is ready: the page in the browser, the folder in the file manager (never for a start that was
|
|
151
|
+
// cancelled or replaced meanwhile).
|
|
152
|
+
const present = async () => {
|
|
153
|
+
if (!browser.supported || setup !== mine || superseded()) return;
|
|
154
|
+
mine.opened = await open(browser);
|
|
155
|
+
if (setup !== mine) return;
|
|
156
|
+
mine.revealed = (await reveal()).ok === true;
|
|
157
|
+
if (!mine.opened) mine.error = { code: 'OPEN_FAILED' };
|
|
158
|
+
};
|
|
159
|
+
// Started in this step, so the answer below already carries a download's progress.
|
|
160
|
+
let preparing;
|
|
161
|
+
try { preparing = Promise.resolve(prepare({ signal: mine.stop.signal })); } catch (error) { preparing = Promise.reject(error); }
|
|
162
|
+
const ready = preparing.then(
|
|
163
|
+
prepared => { mine.folder = prepared.folder; },
|
|
164
|
+
error => { mine.error = { code: DOWNLOAD_ERRORS.includes(error?.code) || error?.code === 'EXTENSION_FOLDER_UNSAFE' ? error.code : 'EXTENSION_FOLDER_FAILED' }; });
|
|
165
|
+
// A folder that needs no download answers in this request, as it always did. A download runs on: the setup is
|
|
166
|
+
// `downloading` until its files are verified and in place, and this request returns at once so its progress shows.
|
|
167
|
+
const needed = packageStatus() || {};
|
|
168
|
+
if (needed.needs || needed.phase === 'downloading') {
|
|
169
|
+
mine.preparing = true;
|
|
170
|
+
mine.settled = ready.then(async () => { mine.preparing = false; if (setup === mine && !mine.error) await present(); }).catch(() => { mine.preparing = false; });
|
|
171
|
+
return view();
|
|
100
172
|
}
|
|
173
|
+
await ready;
|
|
174
|
+
if (setup !== mine || mine.error) return view();
|
|
175
|
+
await present();
|
|
101
176
|
return view();
|
|
102
177
|
},
|
|
103
|
-
status: view,
|
|
178
|
+
status: view, state,
|
|
179
|
+
/**
|
|
180
|
+
* The setup page saw the extension's content script on this server's port (POST …/setup/seen): the browser runs
|
|
181
|
+
* the folder's manifest for this port, so the Reload a port change asked for is done. A repair's Reload is not: the
|
|
182
|
+
* copy the browser still runs answers the page just the same, so only the owner's confirmation in Settings clears it
|
|
183
|
+
* (POST …/reload/confirm, browser-extension-package.js confirmRepairReload).
|
|
184
|
+
*/
|
|
185
|
+
seen() { confirmReload(); return view(); },
|
|
104
186
|
/**
|
|
105
187
|
* The one-time token for the setup page (POST …/setup/ticket): only while the setup waits for the extension.
|
|
106
188
|
* Returns { token, bridgePort, expiresAt }.
|
|
@@ -111,11 +193,14 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
|
|
|
111
193
|
if (current !== 'waiting-for-extension') fail(current === 'error' ? setup.error?.code || 'SETUP_NOT_ACTIVE' : 'SETUP_NOT_WAITING');
|
|
112
194
|
if (setup.tickets >= maxTickets) fail('SETUP_TICKETS_USED');
|
|
113
195
|
setup.tickets++;
|
|
196
|
+
// A ticket clears no pending Reload: the page sends `seen` for that (it does before it asks for a ticket).
|
|
114
197
|
const until = Math.min(setup.until, now() + ticketMs);
|
|
115
198
|
const made = await bridge.beginSetupPairing({ until });
|
|
116
199
|
return { token: made.token, bridgePort: made.port, expiresAt: made.expiresAt };
|
|
117
200
|
},
|
|
118
|
-
cancel() { if (setup) bridge.endSetupPairing(); setup = null; return view(); },
|
|
201
|
+
cancel() { attempt?.stop.abort(); attempt = null; if (setup) { bridge.endSetupPairing(); setup.stop?.abort(); } setup = null; return view(); },
|
|
202
|
+
/** Resolves when a download this setup waits for has ended, either way (tests). */
|
|
203
|
+
settled: () => setup?.settled || Promise.resolve(),
|
|
119
204
|
reveal,
|
|
120
205
|
/** Opens the setup page again (in the setup's browser). */
|
|
121
206
|
async reopen() { if (!setup?.browser?.supported) fail('SETUP_NOT_ACTIVE'); setup.opened = await open(setup.browser); return view(); },
|
|
@@ -130,6 +215,10 @@ export const SETUP_ERROR_TEXT = Object.freeze({
|
|
|
130
215
|
SETUP_EXPIRED: 'This setup ran out of time (15 minutes). Start "Connect your browser" again.',
|
|
131
216
|
BROWSER_NOT_INSTALLED: 'That browser was not found on this computer.',
|
|
132
217
|
EXTENSION_FOLDER_FAILED: 'SynaBun could not prepare the extension folder in its data folder.',
|
|
218
|
+
EXTENSION_FOLDER_UNSAFE: 'SynaBun did not use the extension folder in its data folder (browser-extension): it is 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 that folder, then start "Connect your browser" again.',
|
|
219
|
+
EXTENSION_DOWNLOAD_OFFLINE: 'SynaBun could not reach synabun.ai to download the extension. Check the internet connection, then start "Connect your browser" again.',
|
|
220
|
+
EXTENSION_DOWNLOAD_UNAVAILABLE: 'synabun.ai did not have the extension this SynaBun version needs. Try again later, or update SynaBun.',
|
|
221
|
+
EXTENSION_VERIFY_FAILED: 'The downloaded extension was not the file this SynaBun version expects, so it was not installed. Try again; if it keeps failing, update SynaBun.',
|
|
133
222
|
OPEN_FAILED: 'SynaBun could not open the setup page in the browser. Open it yourself from Settings → Browser.',
|
|
134
223
|
REVEAL_FAILED: 'SynaBun could not show the folder. Copy its path from the setup page.',
|
|
135
224
|
INVALID_MESSAGE: 'Invalid setup request.',
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Update progress for the owner. The durable install marker survives a restart. An attempt lives only in
|
|
2
|
+
// the process that sent the command. An acknowledgement is never proof that the new copy is running.
|
|
3
|
+
import { compareVersions } from './browser-extension-folder.js';
|
|
4
|
+
import { SELF_RELOAD_SINCE } from './browser-extension-protocol.js';
|
|
5
|
+
import { extensionVersions } from './browser-extension-setup.js';
|
|
6
|
+
|
|
7
|
+
export const RECONNECT_WAIT_MS = 45_000;
|
|
8
|
+
export function createExtensionUpdate({ bridge, pkg, runsActive, now = Date.now }) {
|
|
9
|
+
let attempt = null, observed = null;
|
|
10
|
+
|
|
11
|
+
function status(peer = bridge.status(), disk = pkg.status()) {
|
|
12
|
+
const { connected, extensionVersion: runningVersion } = peer;
|
|
13
|
+
const { folderVersion, pinnedVersion } = disk;
|
|
14
|
+
const targetVersion = disk.needs === 'update' ? pinnedVersion : folderVersion || pinnedVersion;
|
|
15
|
+
if (attempt?.target !== targetVersion) attempt = null;
|
|
16
|
+
if (observed?.target !== targetVersion) observed = null;
|
|
17
|
+
// Explicit repair confirmation (or the setup page's port check) also clears the prompt while offline.
|
|
18
|
+
if (attempt && attempt.reason !== 'version' && !disk.reloadPending) attempt = null;
|
|
19
|
+
if (!connected && observed?.reason && observed.reason !== 'version' && !disk.reloadPending) observed = null;
|
|
20
|
+
const flags = extensionVersions({ ...disk, connected, extensionVersion: runningVersion });
|
|
21
|
+
const reason = disk.reloadReason || 'version';
|
|
22
|
+
const view = { phase: 'idle', runningVersion, folderVersion, pinnedVersion, targetVersion, reason,
|
|
23
|
+
fromVersion: runningVersion || observed?.from || disk.fromVersion || (disk.needs === 'update' ? folderVersion : null),
|
|
24
|
+
canReload: false, runsActive: runsActive(), claimedTabs: peer.tabs.filter(tab => tab.owner).length };
|
|
25
|
+
if (disk.needs === 'update' || flags.updateNeeded || (disk.needs === 'unsafe' && (peer.paired || folderVersion))) {
|
|
26
|
+
observed = { target: targetVersion, from: runningVersion || disk.fromVersion || folderVersion };
|
|
27
|
+
attempt = null;
|
|
28
|
+
if (disk.phase === 'failed') return { ...view, phase: 'failed', recovery: 'download', code: disk.code };
|
|
29
|
+
const percent = disk.total > 0 ? Math.min(100, Math.max(0, Math.floor(100 * disk.received / disk.total))) : 0;
|
|
30
|
+
return { ...view, phase: 'downloading', pending: disk.phase === 'idle', percent };
|
|
31
|
+
}
|
|
32
|
+
if (disk.needs || !folderVersion) return view; // a first install belongs to setup
|
|
33
|
+
if (flags.reloadNeeded && (observed?.reason !== reason || observed.done)) {
|
|
34
|
+
observed = { target: targetVersion, reason, from: runningVersion || disk.fromVersion };
|
|
35
|
+
}
|
|
36
|
+
if (attempt && !attempt.code && now() >= attempt.until) attempt.code = 'RELOAD_TIMEOUT';
|
|
37
|
+
if (attempt?.code) return { ...view, phase: 'failed', recovery: 'guided', code: attempt.code };
|
|
38
|
+
if (attempt) return { ...view, phase: 'reloading' };
|
|
39
|
+
if (flags.reloadNeeded || (observed && peer.paired && !connected && !observed.done)) {
|
|
40
|
+
return { ...view, phase: 'ready', confirmBusy: !!observed?.confirmBusy, canReload: connected && !observed?.verify && compareVersions(runningVersion, SELF_RELOAD_SINCE) >= 0 };
|
|
41
|
+
}
|
|
42
|
+
if (observed && connected && runningVersion === targetVersion) {
|
|
43
|
+
observed.done = true;
|
|
44
|
+
return { ...view, phase: 'done' };
|
|
45
|
+
}
|
|
46
|
+
return view;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Called once for the first authenticated inventory on each socket, even with no owner page open.
|
|
50
|
+
function connected(version) {
|
|
51
|
+
const disk = pkg.status();
|
|
52
|
+
if (disk.needs || version !== disk.folderVersion) {
|
|
53
|
+
if (attempt) attempt.code = 'RELOAD_OLD_VERSION';
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (disk.reloadReason === 'version' && pkg.confirmVersion(version)) {
|
|
57
|
+
observed = { target: version, from: disk.fromVersion, done: true };
|
|
58
|
+
} else if (attempt) {
|
|
59
|
+
// A same-version repair still needs the owner's confirmation. A port change needs setup/seen.
|
|
60
|
+
observed = { target: version, from: attempt.from, reason: attempt.reason, verify: !!disk.reloadPending, done: !disk.reloadPending };
|
|
61
|
+
}
|
|
62
|
+
attempt = null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function reload({ targetVersion, allowBusy = false }) {
|
|
66
|
+
const view = status();
|
|
67
|
+
const refuse = code => ({ ok: false, code, update: view });
|
|
68
|
+
if (!targetVersion || targetVersion !== view.targetVersion) return refuse('UPDATE_CHANGED');
|
|
69
|
+
if (view.phase === 'reloading' || view.phase === 'done') return { ok: true, update: view };
|
|
70
|
+
if (!view.canReload) return refuse('EXTENSION_RELOAD_REQUIRED');
|
|
71
|
+
if (!allowBusy && (view.claimedTabs || view.runsActive)) return refuse('RELOAD_BUSY');
|
|
72
|
+
const own = { target: targetVersion, reason: view.reason, from: view.runningVersion, until: now() + RECONNECT_WAIT_MS };
|
|
73
|
+
attempt = own;
|
|
74
|
+
const failed = code => {
|
|
75
|
+
if (attempt !== own) return;
|
|
76
|
+
// The old worker can close its socket just after the ack was queued. Only the new hello settles that case.
|
|
77
|
+
if (code === 'NOT_CONNECTED' || code === 'EXTENSION_NOT_CONNECTED') return;
|
|
78
|
+
if (code === 'RELOAD_BUSY') { observed.confirmBusy = true; attempt = null; return; }
|
|
79
|
+
own.code = 'RELOAD_FAILED';
|
|
80
|
+
};
|
|
81
|
+
bridge.publishUpdate?.();
|
|
82
|
+
bridge.request('selfReload', null, 'owner', { allowBusy }).then(result => {
|
|
83
|
+
if (!result.ok) failed(result.code);
|
|
84
|
+
}, error => failed(error?.code));
|
|
85
|
+
return { ok: true, update: { ...view, phase: 'reloading', canReload: false } };
|
|
86
|
+
}
|
|
87
|
+
return { status, connected, reload };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Mounted behind the bridge's owner/page-secret middleware. Even a browser granted general automation owner
|
|
91
|
+
// access cannot send this command. A read or a request missing the explicit click's target has no effect.
|
|
92
|
+
export function ownerReloadHandler({ update, isAutomationBrowser }) {
|
|
93
|
+
return (req, res) => {
|
|
94
|
+
const headers = req.headers;
|
|
95
|
+
if (isAutomationBrowser(req) || !/^https?:\/\//i.test(headers.origin || '') || headers['x-synabun-ui'] !== '1'
|
|
96
|
+
|| (headers['sec-fetch-site'] !== undefined && headers['sec-fetch-site'] !== 'same-origin')) {
|
|
97
|
+
return res.status(403).json({ ok: false, code: 'OWNER_ROUTE' });
|
|
98
|
+
}
|
|
99
|
+
const { targetVersion, allowBusy } = req.body || {};
|
|
100
|
+
if (typeof targetVersion !== 'string' || typeof allowBusy !== 'boolean') return res.status(400).json({ ok: false, code: 'INVALID_MESSAGE' });
|
|
101
|
+
const result = update.reload({ targetVersion, allowBusy });
|
|
102
|
+
return res.status(result.ok ? 200 : 409).json(result);
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -44,7 +44,7 @@ export function budgetExtractionItems(items, { fields, maxItems = 50, maxChars }
|
|
|
44
44
|
// `script-src` has no 'unsafe-eval', refused the second poll of every scrolled
|
|
45
45
|
// extraction with an EvalError ("the tweet extractor doesn't work on X").
|
|
46
46
|
|
|
47
|
-
const BUSY_SELECTOR = '[aria-busy="true"], [role="progressbar"]';
|
|
47
|
+
export const BUSY_SELECTOR = '[aria-busy="true"], [role="progressbar"]';
|
|
48
48
|
|
|
49
49
|
/** An extractor or a scroll target is one JavaScript expression (statements go in an IIFE). */
|
|
50
50
|
function expressionSource(source, what) {
|
|
@@ -232,21 +232,45 @@ export async function runBrowserExtraction(page, script, opts = {}, runtime = {}
|
|
|
232
232
|
};
|
|
233
233
|
}
|
|
234
234
|
|
|
235
|
+
/**
|
|
236
|
+
* The main content of a page (or of one element) as HTML, for the Markdown reader. A page function: Playwright sends
|
|
237
|
+
* its source to the page (readBrowserContentHtml), and the browser extension ships the same source as one of its fixed
|
|
238
|
+
* readers ('page.html', generated by scripts/extension/build-browser-readers.mjs). It clones before cleaning, drops
|
|
239
|
+
* navigation, chrome and scripts, resolves link and image addresses, and prefers <main>, <article> or [role=main].
|
|
240
|
+
* `dense` (the extension's reader only; Playwright never passes it, so its output is as before): on a page with none
|
|
241
|
+
* of those, the block that holds most of the page's paragraph text, when one block holds at least 60 % of it.
|
|
242
|
+
*/
|
|
243
|
+
export function contentHtmlOf(element, scoped, dense) {
|
|
244
|
+
const clone = element.cloneNode(true);
|
|
245
|
+
const noise = scoped
|
|
246
|
+
? 'script,style,noscript,iframe'
|
|
247
|
+
: 'nav,header,footer,aside,[role="navigation"],[role="banner"],[role="contentinfo"],[role="complementary"],.sidebar,.nav,.footer,.header,.advertisement,.ad,.ads,[class*="cookie"],[class*="popup"],[class*="modal"],[class*="overlay"],script,style,noscript,iframe';
|
|
248
|
+
clone.querySelectorAll(noise).forEach(node => node.remove());
|
|
249
|
+
clone.querySelectorAll('a[href],img[src]').forEach(node => {
|
|
250
|
+
const attr = node.tagName === 'A' ? 'href' : 'src';
|
|
251
|
+
try { node.setAttribute(attr, new URL(node.getAttribute(attr), document.baseURI).href); } catch { /* Keep unresolvable links verbatim. */ }
|
|
252
|
+
});
|
|
253
|
+
let main = scoped ? clone : (clone.querySelector('main') || clone.querySelector('article') || clone.querySelector('[role="main"]') || clone);
|
|
254
|
+
if (dense === true && !scoped && main === clone) {
|
|
255
|
+
const prose = node => { let n = 0; for (const p of node.querySelectorAll('p')) n += (p.textContent || '').trim().length; return n; };
|
|
256
|
+
const total = prose(clone);
|
|
257
|
+
if (total >= 500) {
|
|
258
|
+
let best = null, bestDensity = 0;
|
|
259
|
+
for (const block of clone.querySelectorAll('div,section')) {
|
|
260
|
+
const inside = prose(block);
|
|
261
|
+
if (inside < total * 0.6) continue;
|
|
262
|
+
const density = inside / Math.max(1, (block.textContent || '').length);
|
|
263
|
+
if (density >= bestDensity) { best = block; bestDensity = density; }
|
|
264
|
+
}
|
|
265
|
+
if (best) main = best;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return scoped ? main.outerHTML : main.innerHTML;
|
|
269
|
+
}
|
|
270
|
+
|
|
235
271
|
/** Scoped HTML reader: clone before cleaning, and retain link source URLs. */
|
|
236
272
|
export async function readBrowserContentHtml(page, selector) {
|
|
237
273
|
const target = page.locator(selector || 'body');
|
|
238
274
|
if (selector && await target.count() !== 1) throw new Error('Content selector must match exactly one element.');
|
|
239
|
-
return target.evaluate(
|
|
240
|
-
const clone = element.cloneNode(true);
|
|
241
|
-
const noise = scoped
|
|
242
|
-
? 'script,style,noscript,iframe'
|
|
243
|
-
: 'nav,header,footer,aside,[role="navigation"],[role="banner"],[role="contentinfo"],[role="complementary"],.sidebar,.nav,.footer,.header,.advertisement,.ad,.ads,[class*="cookie"],[class*="popup"],[class*="modal"],[class*="overlay"],script,style,noscript,iframe';
|
|
244
|
-
clone.querySelectorAll(noise).forEach(node => node.remove());
|
|
245
|
-
clone.querySelectorAll('a[href],img[src]').forEach(node => {
|
|
246
|
-
const attr = node.tagName === 'A' ? 'href' : 'src';
|
|
247
|
-
try { node.setAttribute(attr, new URL(node.getAttribute(attr), document.baseURI).href); } catch { /* Keep unresolvable links verbatim. */ }
|
|
248
|
-
});
|
|
249
|
-
const main = scoped ? clone : (clone.querySelector('main') || clone.querySelector('article') || clone.querySelector('[role="main"]') || clone);
|
|
250
|
-
return scoped ? main.outerHTML : main.innerHTML;
|
|
251
|
-
}, !!selector);
|
|
275
|
+
return target.evaluate(contentHtmlOf, !!selector);
|
|
252
276
|
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
2
|
+
// Claude Code background tasks, from the session's own transcript
|
|
3
|
+
//
|
|
4
|
+
// The Background tasks view of a panel that runs Claude Code (the Claude Code
|
|
5
|
+
// side panel, the Assistant) asks two things here:
|
|
6
|
+
// list(found) the session's background shells and watches, rebuilt from its transcript with the
|
|
7
|
+
// same registry and adapter the page folds live messages with
|
|
8
|
+
// (public/shared/bg-tasks/), so a reload or a server restart starts from what the
|
|
9
|
+
// session recorded, never from page memory;
|
|
10
|
+
// output(found, q) a page of what one of them printed.
|
|
11
|
+
// `found` is a transcript the caller located and confined (lib/path-confine.js findSessionTranscript).
|
|
12
|
+
//
|
|
13
|
+
// An output file is read only when the session itself reported it for that task (the result text of its tool
|
|
14
|
+
// call, or its task-notification), and only where Claude Code writes them: `claude-<uid>/<project>/<session>/tasks/`
|
|
15
|
+
// under the temporary folder, or `<config dir>/projects/<project>/<session>/tool-results|tasks/`. The request
|
|
16
|
+
// names a task id, never a path; the real path (every link resolved) must be inside one of those folders, its
|
|
17
|
+
// session folder must be the session's, and the file is opened without following a link (lib/confined-fs.js).
|
|
18
|
+
// What is read is scrubbed of SynaBun's run secrets with what lies on both sides of the page
|
|
19
|
+
// (lib/opencode-shell-read.js readSafeShellOutputPage), exactly as the OpenCode panel's shell output is. It goes
|
|
20
|
+
// to the owner's page only: never into a model's context, a transcript or a meter.
|
|
21
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
import { statSync, realpathSync } from 'node:fs';
|
|
24
|
+
import { tmpdir } from 'node:os';
|
|
25
|
+
import { basename, dirname, join } from 'node:path';
|
|
26
|
+
import { readConfinedRange } from './confined-fs.js';
|
|
27
|
+
import { isInside, PathConfineError } from './path-confine.js';
|
|
28
|
+
import { readSafeShellOutputPage, SHELL_OUTPUT_PAGE_BYTES } from './opencode-shell-read.js';
|
|
29
|
+
import { applyBgFact, createBgRegistry, isBgRunning, serializeBgRegistry } from '../public/shared/bg-tasks/bg-tasks-model.js';
|
|
30
|
+
import { claudeFactsFromTranscriptLine } from '../public/shared/bg-tasks/bg-tasks-claude.js';
|
|
31
|
+
|
|
32
|
+
/** The most of a transcript read in one step while it is folded. */
|
|
33
|
+
const TRANSCRIPT_CHUNK = 4 * 1024 * 1024;
|
|
34
|
+
/** How many transcripts keep their folded registry. */
|
|
35
|
+
const CACHE_SIZE = 12;
|
|
36
|
+
// Only lines that can carry a fact are parsed (a transcript reaches tens of MB).
|
|
37
|
+
const MARKERS = ['"Bash"', '"Monitor"', '"TaskStop"', '"KillShell"', '"KillBash"', 'backgroundTaskId', '"taskId"', 'queue-operation'];
|
|
38
|
+
|
|
39
|
+
const TASK_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
40
|
+
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
41
|
+
|
|
42
|
+
const realOrNull = (p) => { try { return realpathSync(p); } catch { return null; } };
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The folders Claude Code writes task output under, for this user: `<tmp>/claude-<uid>` for every temporary
|
|
46
|
+
* folder it may use (`CLAUDE_CODE_TMPDIR`, `/tmp`, the OS one) and `<configDir>/projects`.
|
|
47
|
+
*/
|
|
48
|
+
export function claudeOutputRoots({ configDirs = [], env = process.env, uid = typeof process.getuid === 'function' ? process.getuid() : null, platform = process.platform, tmp = tmpdir() } = {}) {
|
|
49
|
+
const temps = [env?.CLAUDE_CODE_TMPDIR, platform === 'win32' ? null : '/tmp', tmp].filter(Boolean);
|
|
50
|
+
const names = uid == null ? ['claude'] : [`claude-${uid}`];
|
|
51
|
+
const roots = [];
|
|
52
|
+
for (const t of temps) for (const n of names) roots.push(join(t, n));
|
|
53
|
+
for (const c of configDirs) if (c) roots.push(join(c, 'projects'));
|
|
54
|
+
return [...new Set(roots)];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Whether `file` is an output file of task `taskId` of session `sessionId` under one of `roots`, every link
|
|
59
|
+
* resolved. → `{ root, real }` (the real root and the real file) or null.
|
|
60
|
+
*/
|
|
61
|
+
export function confineTaskOutput(file, { sessionId, taskId, roots = [] } = {}) {
|
|
62
|
+
if (typeof file !== 'string' || !file || !TASK_ID.test(String(taskId || '')) || !SESSION_ID.test(String(sessionId || ''))) return null;
|
|
63
|
+
// The name the session reported must already be the task's: `<taskId>.output` (or `<taskId>.<ext>` in tool-results).
|
|
64
|
+
const name = basename(file);
|
|
65
|
+
if (!(name === `${taskId}.output` || name.startsWith(`${taskId}.`))) return null;
|
|
66
|
+
const real = realOrNull(file);
|
|
67
|
+
if (!real) return null;
|
|
68
|
+
// The real file still is the task's, directly in the session's tasks or tool-results folder.
|
|
69
|
+
if (basename(real) !== name) return null;
|
|
70
|
+
const folder = basename(dirname(real));
|
|
71
|
+
if (folder !== 'tasks' && folder !== 'tool-results') return null;
|
|
72
|
+
if (basename(dirname(dirname(real))) !== sessionId) return null;
|
|
73
|
+
for (const root of roots) {
|
|
74
|
+
const realRoot = realOrNull(root);
|
|
75
|
+
if (realRoot && isInside(realRoot, real)) return { root: realRoot, real };
|
|
76
|
+
}
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A raw page of a file, cut at UTF-8 character boundaries: `{ status, data: { output, cursor, size } }`. */
|
|
81
|
+
export function readFilePage(root, real, { cursor = 0, limit = SHELL_OUTPUT_PAGE_BYTES } = {}) {
|
|
82
|
+
let from = Math.max(0, Math.floor(Number(cursor) || 0));
|
|
83
|
+
const want = Math.max(1, Math.min(SHELL_OUTPUT_PAGE_BYTES, Math.floor(Number(limit) || SHELL_OUTPUT_PAGE_BYTES)));
|
|
84
|
+
let { bytes, size } = readConfinedRange(root, real, { start: from, length: want });
|
|
85
|
+
// A page that starts inside a character starts at the next one.
|
|
86
|
+
let skip = 0;
|
|
87
|
+
while (skip < bytes.length && skip < 3 && (bytes[skip] & 0xc0) === 0x80) skip += 1;
|
|
88
|
+
if (skip) { bytes = bytes.subarray(skip); from += skip; }
|
|
89
|
+
// A page that ends inside a character ends before it (the next page starts there).
|
|
90
|
+
// (Never down to nothing at the end of the file: a file that really ends inside a character is read as it is,
|
|
91
|
+
// or the reader would ask for the same byte forever.)
|
|
92
|
+
let end = bytes.length;
|
|
93
|
+
let i = end - 1;
|
|
94
|
+
let back = 0;
|
|
95
|
+
while (i >= 0 && back < 3 && (bytes[i] & 0xc0) === 0x80) { i -= 1; back += 1; }
|
|
96
|
+
if (i >= 0) {
|
|
97
|
+
const lead = bytes[i];
|
|
98
|
+
const need = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 1;
|
|
99
|
+
if (need > 1 && end - i < need && !(i === 0 && from + bytes.length >= size)) end = i;
|
|
100
|
+
}
|
|
101
|
+
const output = bytes.subarray(0, end).toString('utf8');
|
|
102
|
+
return { status: 200, data: { output, cursor: from + end, size } };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* createClaudeBgTasks({ roots }) — `roots(found)` → the folders output may be read from for that transcript
|
|
107
|
+
* (claudeOutputRoots with the account's config dir).
|
|
108
|
+
*/
|
|
109
|
+
export function createClaudeBgTasks({ roots = () => claudeOutputRoots(), cacheSize = CACHE_SIZE } = {}) {
|
|
110
|
+
const cache = new Map(); // realPath → { ino, offset, rest, reg }
|
|
111
|
+
|
|
112
|
+
function fold(entry, text) {
|
|
113
|
+
const lines = (entry.rest + text).split('\n');
|
|
114
|
+
entry.rest = lines.pop() || '';
|
|
115
|
+
for (const line of lines) {
|
|
116
|
+
if (!line || !MARKERS.some(m => line.includes(m))) continue;
|
|
117
|
+
let obj;
|
|
118
|
+
try { obj = JSON.parse(line); } catch { continue; }
|
|
119
|
+
for (const fact of claudeFactsFromTranscriptLine(obj)) applyBgFact(entry.reg, fact);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The registry of a transcript, folded from where the last read stopped (a file that grew is read on). */
|
|
124
|
+
function registryFor(found) {
|
|
125
|
+
if (!found?.realPath || !found?.realFolder) throw new PathConfineError(404, 'Transcript not found.');
|
|
126
|
+
let st;
|
|
127
|
+
try { st = statSync(found.realPath); } catch { throw new PathConfineError(404, 'Transcript not found.'); }
|
|
128
|
+
let entry = cache.get(found.realPath);
|
|
129
|
+
if (!entry || entry.ino !== st.ino || st.size < entry.offset) {
|
|
130
|
+
entry = { ino: st.ino, offset: 0, rest: '', reg: createBgRegistry() };
|
|
131
|
+
}
|
|
132
|
+
cache.delete(found.realPath);
|
|
133
|
+
cache.set(found.realPath, entry);
|
|
134
|
+
while (cache.size > cacheSize) cache.delete(cache.keys().next().value);
|
|
135
|
+
while (entry.offset < st.size) {
|
|
136
|
+
const { bytes } = readConfinedRange(found.realFolder, found.realPath, { start: entry.offset, length: Math.min(TRANSCRIPT_CHUNK, st.size - entry.offset) });
|
|
137
|
+
if (!bytes.length) break;
|
|
138
|
+
// Whole lines only: a line cut by the chunk (or still being written) waits in `rest`.
|
|
139
|
+
entry.offset += bytes.length;
|
|
140
|
+
fold(entry, bytes.toString('utf8'));
|
|
141
|
+
}
|
|
142
|
+
return entry.reg;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
registryFor,
|
|
147
|
+
/** → { tasks } (serializeBgRegistry). */
|
|
148
|
+
list(found) {
|
|
149
|
+
return serializeBgRegistry(registryFor(found));
|
|
150
|
+
},
|
|
151
|
+
/**
|
|
152
|
+
* A page of one task's output: `{ status, data: { output, cursor, size, from } }`, or `{ ok: false, status, code, error }`.
|
|
153
|
+
* `sessionId` is the transcript's session; `running` says the task may still write (from the caller's live view).
|
|
154
|
+
*/
|
|
155
|
+
async output(found, { sessionId, taskId, cursor, tail, limit, running = null } = {}) {
|
|
156
|
+
if (!TASK_ID.test(String(taskId || ''))) return { ok: false, status: 400, code: 'TASK_ID_INVALID', error: 'That is not a background task of this conversation.' };
|
|
157
|
+
const reg = registryFor(found);
|
|
158
|
+
const task = reg.tasks.get(taskId);
|
|
159
|
+
if (!task) return { ok: false, status: 404, code: 'TASK_UNKNOWN', error: 'That is not a background task of this conversation.' };
|
|
160
|
+
if (!task.outputFile) return { ok: false, status: 404, code: 'OUTPUT_NOT_REPORTED', error: 'The session has not said where this task writes yet.' };
|
|
161
|
+
const place = confineTaskOutput(task.outputFile, { sessionId, taskId, roots: roots(found) });
|
|
162
|
+
if (!place) {
|
|
163
|
+
// Gone (the temporary folder was cleaned), or a path that is not one of Claude Code's own output files.
|
|
164
|
+
let exists = false;
|
|
165
|
+
try { statSync(task.outputFile); exists = true; } catch { exists = false; }
|
|
166
|
+
return exists
|
|
167
|
+
? { ok: false, status: 403, code: 'OUTPUT_NOT_ALLOWED', error: 'That file is not where Claude Code keeps this session\'s task output.' }
|
|
168
|
+
: { ok: false, status: 404, code: 'OUTPUT_GONE', error: 'The output file of that task is no longer there.' };
|
|
169
|
+
}
|
|
170
|
+
const read = (q) => {
|
|
171
|
+
try { return readFilePage(place.root, place.real, q); }
|
|
172
|
+
catch (err) { return { ok: false, status: Number(err?.status) || 500, error: err?.message || 'The output could not be read.' }; }
|
|
173
|
+
};
|
|
174
|
+
const stillRunning = typeof running === 'boolean' ? running : isBgRunning(task);
|
|
175
|
+
const page = await readSafeShellOutputPage(read, { cursor, tail, limit, running: stillRunning });
|
|
176
|
+
if (!page || page.ok === false || !(Number(page.status) < 400)) {
|
|
177
|
+
return { ok: false, status: Number(page?.status) >= 400 ? Number(page.status) : 502, code: 'OUTPUT_FAILED', error: page?.error || 'The output could not be read.' };
|
|
178
|
+
}
|
|
179
|
+
return { status: 200, data: page.data };
|
|
180
|
+
},
|
|
181
|
+
forget(realPath) { cache.delete(realPath); },
|
|
182
|
+
};
|
|
183
|
+
}
|
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
// - `isMeta` user lines are injected by the CLI, not typed by the user;
|
|
12
12
|
// - every line carries a `uuid`.
|
|
13
13
|
|
|
14
|
+
import { parseTaskNotifications } from '../public/shared/bg-tasks/bg-tasks-model.js';
|
|
15
|
+
|
|
14
16
|
const MAX_TEXT = 64_000;
|
|
15
17
|
const MAX_RESULT_TEXT = 32_000;
|
|
16
18
|
const MAX_STRING = 20_000; // one string inside a structured result
|
|
@@ -192,7 +194,16 @@ export function historyRowsFromEntry(obj) {
|
|
|
192
194
|
if (obj.type === 'attachment' && obj.attachment?.type === 'queued_command') {
|
|
193
195
|
const a = obj.attachment;
|
|
194
196
|
const kind = a.origin?.kind || (a.commandMode && a.commandMode !== 'prompt' ? a.commandMode : '');
|
|
195
|
-
if (kind && kind !== 'human')
|
|
197
|
+
if (kind && kind !== 'human') {
|
|
198
|
+
const row = { role: 'system', subtype: 'origin', origin: a.origin && typeof a.origin === 'object' ? a.origin : { kind } };
|
|
199
|
+
// A background task's report, read into its fields (the panel draws a card linked to the task, never the markup).
|
|
200
|
+
const notifications = kind === 'task-notification' && typeof a.prompt === 'string' ? parseTaskNotifications(a.prompt).slice(0, 10) : [];
|
|
201
|
+
if (notifications.length) {
|
|
202
|
+
row.notifications = notifications;
|
|
203
|
+
if (obj.timestamp || a.timestamp) row.timestamp = obj.timestamp || a.timestamp;
|
|
204
|
+
}
|
|
205
|
+
out.rows.push(row);
|
|
206
|
+
}
|
|
196
207
|
else if (typeof a.prompt === 'string' && a.prompt.trim()) out.rows.push({ role: 'user', text: a.prompt.slice(0, MAX_TEXT), queued: true });
|
|
197
208
|
return out;
|
|
198
209
|
}
|