synabun 2.4.1 → 2.4.2
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 +30 -0
- package/README.md +1 -1
- package/browser-extension/content.js +56 -14
- package/browser-extension/engine.js +158 -8
- package/browser-extension/manifest.json +3 -1
- package/browser-extension/protocol.js +91 -6
- package/browser-extension/service-worker.js +13 -5
- package/browser-extension/tokens.css +1 -1
- package/docs/browser-extension-bridge.md +24 -4
- package/lib/data-home-files.js +4 -2
- package/lib/first-launch-protection.js +8 -2
- package/lib/update-snapshot.js +11 -4
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +25 -2
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +62 -17
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-bench.d.ts +22 -22
- package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
- package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-maintenance.js +34 -45
- package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
- package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
- package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-copy.js +467 -0
- package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.js +60 -0
- package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-retrieval.js +188 -40
- package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
- package/mcp-server/dist/services/memory-schema.d.ts +58 -2
- package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-schema.js +190 -13
- package/mcp-server/dist/services/memory-schema.js.map +1 -1
- package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
- package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-sessions.js +56 -20
- package/mcp-server/dist/services/memory-sessions.js.map +1 -1
- package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-verification.js +8 -5
- package/mcp-server/dist/services/memory-verification.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +5 -0
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +19 -2
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.js +145 -0
- package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
- package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
- package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
- package/mcp-server/dist/services/sqlite-write.js +94 -0
- package/mcp-server/dist/services/sqlite-write.js.map +1 -0
- package/mcp-server/dist/services/sqlite.d.ts +39 -0
- package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
- package/mcp-server/dist/services/sqlite.js +249 -8
- package/mcp-server/dist/services/sqlite.js.map +1 -1
- package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
- package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
- package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe-config.js +32 -10
- package/mcp-server/dist/services/typesafe-config.js.map +1 -1
- package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe.js +9 -7
- package/mcp-server/dist/services/typesafe.js.map +1 -1
- package/mcp-server/dist/services/vector-cache.d.ts +32 -0
- package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
- package/mcp-server/dist/services/vector-cache.js +161 -8
- package/mcp-server/dist/services/vector-cache.js.map +1 -1
- package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
- package/mcp-server/dist/tools/agents.d.ts +11 -7
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +27 -9
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +10 -3
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
- package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
- package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
- package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
- package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-interact.js +6 -1
- package/mcp-server/dist/tools/browser-interact.js.map +1 -1
- package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
- package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
- package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +20 -2
- package/mcp-server/src/index.ts +59 -17
- package/mcp-server/src/services/memory-maintenance.ts +31 -28
- package/mcp-server/src/services/memory-migration-copy.ts +419 -0
- package/mcp-server/src/services/memory-migration-worker.ts +55 -0
- package/mcp-server/src/services/memory-retrieval.ts +173 -32
- package/mcp-server/src/services/memory-schema.ts +194 -12
- package/mcp-server/src/services/memory-sessions.ts +54 -21
- package/mcp-server/src/services/memory-verification.ts +7 -4
- package/mcp-server/src/services/neural-interface.ts +22 -2
- package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
- package/mcp-server/src/services/retrieval-reader.ts +131 -0
- package/mcp-server/src/services/sqlite-write.ts +60 -0
- package/mcp-server/src/services/sqlite.ts +246 -8
- package/mcp-server/src/services/typesafe-config.ts +25 -6
- package/mcp-server/src/services/typesafe.ts +9 -7
- package/mcp-server/src/services/vector-cache.ts +154 -9
- package/mcp-server/src/tools/agents.ts +26 -9
- package/mcp-server/src/tools/browser-advanced.ts +10 -3
- package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
- package/mcp-server/src/tools/browser-interact.ts +5 -1
- package/neural-interface/i18n/en.json +263 -1
- package/neural-interface/i18n/pt-BR.json +264 -2
- package/neural-interface/lib/agents/split.js +32 -4
- package/neural-interface/lib/assistant-api.js +19 -8
- package/neural-interface/lib/assistant-brains/claude.js +2 -0
- package/neural-interface/lib/assistant-catalog.js +2 -2
- package/neural-interface/lib/assistant-config.js +0 -7
- package/neural-interface/lib/assistant-dispatch.js +257 -95
- package/neural-interface/lib/assistant-persona.js +16 -4
- package/neural-interface/lib/assistant-pricing.js +65 -14
- package/neural-interface/lib/assistant-router.js +131 -47
- package/neural-interface/lib/assistant-run-wait.js +45 -28
- package/neural-interface/lib/assistant-runtime.js +39 -33
- package/neural-interface/lib/backup-contents.js +158 -0
- package/neural-interface/lib/backup-crypto-io.js +330 -0
- package/neural-interface/lib/backup-crypto-worker.js +130 -0
- package/neural-interface/lib/backup-crypto.js +525 -0
- package/neural-interface/lib/backup-download.js +268 -0
- package/neural-interface/lib/backup-encryption.js +318 -0
- package/neural-interface/lib/backup-groups.js +287 -0
- package/neural-interface/lib/backup-restore-session.js +176 -0
- package/neural-interface/lib/backup-restore-stage.js +60 -0
- package/neural-interface/lib/backup-service.js +788 -233
- package/neural-interface/lib/backup-zip-reader.js +30 -18
- package/neural-interface/lib/backup-zip-writer.js +34 -10
- package/neural-interface/lib/browser-extension-adapter.js +89 -13
- package/neural-interface/lib/browser-extension-bridge.js +18 -7
- package/neural-interface/lib/claude-agent-bridge.js +1 -0
- package/neural-interface/lib/claude-session-cleanup.js +5 -1
- package/neural-interface/lib/cli-update-planner.js +105 -6
- package/neural-interface/lib/client-diagnostics.js +42 -0
- package/neural-interface/lib/confined-fs.js +7 -2
- package/neural-interface/lib/coordination/README.md +8 -2
- package/neural-interface/lib/coordination/contract.js +161 -0
- package/neural-interface/lib/coordination/database.js +999 -0
- package/neural-interface/lib/coordination/operations.js +436 -0
- package/neural-interface/lib/coordination/service.js +68 -537
- package/neural-interface/lib/coordination/storage-worker.js +101 -0
- package/neural-interface/lib/coordination/store.js +219 -1111
- package/neural-interface/lib/db.js +70 -32
- package/neural-interface/lib/health-count.js +37 -0
- package/neural-interface/lib/loop-stall.js +139 -0
- package/neural-interface/lib/maritaca/client.js +2 -2
- package/neural-interface/lib/maritaca/models.js +12 -17
- package/neural-interface/lib/maritaca/opencode.js +4 -2
- package/neural-interface/lib/memory-api.js +9 -1
- package/neural-interface/lib/memory-session-capture.js +42 -10
- package/neural-interface/lib/memory-store-gate.js +313 -0
- package/neural-interface/lib/memory-store-migrate.js +65 -0
- package/neural-interface/lib/memory-timers.js +7 -7
- package/neural-interface/lib/native-loop-providers.js +13 -16
- package/neural-interface/lib/native-loop-runtime.js +28 -7
- package/neural-interface/lib/opencode-build-preflight.js +18 -1
- package/neural-interface/lib/opencode-native-boundary.js +69 -8
- package/neural-interface/lib/opencode-provider-view.js +14 -3
- package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
- package/neural-interface/lib/opencode2-client.js +2 -1
- package/neural-interface/lib/recall-impact.js +122 -0
- package/neural-interface/lib/scratch-evidence.js +420 -0
- package/neural-interface/lib/scratch-process-guard.js +139 -0
- package/neural-interface/lib/scratch-references.js +279 -0
- package/neural-interface/lib/scratch-retention-core.js +385 -0
- package/neural-interface/lib/scratch-retention-worker.js +37 -0
- package/neural-interface/lib/scratch-retention.js +151 -0
- package/neural-interface/lib/session-cache-builder.js +31 -43
- package/neural-interface/lib/session-cache-worker.js +157 -0
- package/neural-interface/lib/session-indexer.js +28 -21
- package/neural-interface/lib/session-search-index.js +85 -0
- package/neural-interface/lib/skills/creation.js +1 -1
- package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
- package/neural-interface/lib/style-guide/store.js +43 -3
- package/neural-interface/lib/system-restore.js +50 -0
- package/neural-interface/lib/teams/api.js +15 -6
- package/neural-interface/lib/teams/claims.js +67 -31
- package/neural-interface/lib/teams/index.js +7 -7
- package/neural-interface/lib/teams/integration.js +40 -40
- package/neural-interface/lib/teams/landing.js +6 -6
- package/neural-interface/lib/teams/recovery.js +24 -23
- package/neural-interface/lib/teams/scheduler.js +194 -95
- package/neural-interface/lib/teams/state.js +14 -14
- package/neural-interface/lib/teams/worktrees.js +27 -27
- package/neural-interface/lib/whatsapp/bridge.js +2 -1
- package/neural-interface/lib/worker-confinement.js +47 -2
- package/neural-interface/lib/worker-mcp-channel.js +2 -0
- package/neural-interface/lib/worker-resume.js +5 -0
- package/neural-interface/lib/worker-stop.js +86 -0
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/index.html +233 -24
- package/neural-interface/public/onboarding.html +259 -34
- package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
- package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
- package/neural-interface/public/shared/agy/agy-options.js +11 -0
- package/neural-interface/public/shared/agy/agy-panel.js +29 -10
- package/neural-interface/public/shared/agy/agy-styles.js +14 -12
- package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
- package/neural-interface/public/shared/api.js +1 -1
- package/neural-interface/public/shared/assistant/asst-api.js +3 -3
- package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
- package/neural-interface/public/shared/assistant/asst-control.js +2 -0
- package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
- package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
- package/neural-interface/public/shared/assistant/asst-render.js +105 -38
- package/neural-interface/public/shared/assistant/asst-route.js +100 -21
- package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
- package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
- package/neural-interface/public/shared/assistant/asst-state.js +11 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
- package/neural-interface/public/shared/assistant/route-identity.js +2 -1
- package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
- package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
- package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
- package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
- package/neural-interface/public/shared/client-diagnostics.js +94 -0
- package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
- package/neural-interface/public/shared/cp/cp-styles.js +1 -1
- package/neural-interface/public/shared/effort-i18n.js +118 -0
- package/neural-interface/public/shared/html-shell.js +4 -52
- package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
- package/neural-interface/public/shared/memory-store-wait.js +52 -0
- package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
- package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
- package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
- package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
- package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
- package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
- package/neural-interface/public/shared/output-format.js +294 -0
- package/neural-interface/public/shared/provider-icons.js +6 -0
- package/neural-interface/public/shared/schedules-view.js +2 -1
- package/neural-interface/public/shared/server-presence.js +77 -0
- package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
- package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
- package/neural-interface/public/shared/settings/settings-ia.js +1 -1
- package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
- package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
- package/neural-interface/public/shared/studio-attention.js +6 -0
- package/neural-interface/public/shared/styles.css +341 -437
- package/neural-interface/public/shared/transcript-rows.js +28 -3
- package/neural-interface/public/shared/tray-auto-close.js +18 -5
- package/neural-interface/public/shared/ui-agents.js +1 -2
- package/neural-interface/public/shared/ui-automation-studio.js +168 -108
- package/neural-interface/public/shared/ui-claude-panel.js +42 -65
- package/neural-interface/public/shared/ui-loading.js +124 -17
- package/neural-interface/public/shared/ui-native-loop-router.js +10 -0
- package/neural-interface/public/shared/ui-navbar.js +2 -1
- package/neural-interface/public/shared/ui-output.js +533 -0
- package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
- package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
- package/neural-interface/public/shared/ui-sessions.js +2 -2
- package/neural-interface/public/shared/ui-settings-entry.js +18 -0
- package/neural-interface/public/shared/ui-settings.js +224 -65
- package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
- package/neural-interface/public/shared/ui-tooltip.js +16 -0
- package/neural-interface/public/shared/ui-tutorial.js +5 -6
- package/neural-interface/public/shared/ui-worker-end.js +27 -8
- package/neural-interface/public/shared/worker-end.js +9 -4
- package/neural-interface/public/variant/2d/main.js +5 -0
- package/neural-interface/public/variant/3d/app.js +10 -0
- package/neural-interface/public/variant/3d/main.js +5 -1
- package/neural-interface/scripts/scratch-retention.mjs +20 -0
- package/neural-interface/server.js +477 -139
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/scripts/restore-data-home-from-backup.mjs +175 -8
- package/setup.js +18 -4
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
import { getDb } from './sqlite.js';
|
|
19
|
+
import { withMemoryWrite, writeNowOrSoon } from './sqlite-write.js';
|
|
19
20
|
import { autoHealGate, readTargetBench, DEFAULT_BROWSER_ASSIST, BROWSER_TARGET_DEFAULTS, type BrowserAssistConfig } from './browser-assist-gate.js';
|
|
20
21
|
export type { BrowserAssistConfig, BrowserTargetBench } from './browser-assist-gate.js';
|
|
21
22
|
// desktop-assist-gate.ts is a leaf as well (node builtins, the browser gate and the pure risk modules): no cycle back into this file.
|
|
@@ -548,10 +549,7 @@ export function logSessionFromRef(ref: unknown): string | null {
|
|
|
548
549
|
return cleanSessionId(compaction ? compaction[1] : ref);
|
|
549
550
|
}
|
|
550
551
|
|
|
551
|
-
|
|
552
|
-
export function writeTypeSafeLog(row: TypeSafeLogRow): number | null {
|
|
553
|
-
try {
|
|
554
|
-
const d = getDb();
|
|
552
|
+
function insertTypeSafeLog(d: ReturnType<typeof getDb>, row: TypeSafeLogRow): number {
|
|
555
553
|
const result = d.prepare(`INSERT INTO typesafe_log(created_at,surface,origin,entity_id,model,question_count,state_preview,answers,latency_ms,input_tokens,output_tokens,cached,error,session_id,project,surfaces)
|
|
556
554
|
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(
|
|
557
555
|
row.created_at ?? new Date().toISOString(), row.surface, row.origin, row.entity_id, row.model, row.question_count,
|
|
@@ -562,23 +560,44 @@ export function writeTypeSafeLog(row: TypeSafeLogRow): number | null {
|
|
|
562
560
|
);
|
|
563
561
|
if (++insertsSincePrune >= PRUNE_EVERY) { insertsSincePrune = 0; pruneTypeSafeLog(); }
|
|
564
562
|
return Number(result.lastInsertRowid);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Append one row and return its id. Never throws: the log is diagnostics, not the judgment. Null when the row could
|
|
567
|
+
* not be written now: another connection held the writer, and the row is written in the background instead of this
|
|
568
|
+
* call sleeping in SQLite's busy handler on the event loop (writeNowOrSoon).
|
|
569
|
+
*/
|
|
570
|
+
export function writeTypeSafeLog(row: TypeSafeLogRow): number | null {
|
|
571
|
+
try {
|
|
572
|
+
const d = getDb();
|
|
573
|
+
return writeNowOrSoon(d, () => insertTypeSafeLog(d, row)) ?? null;
|
|
565
574
|
} catch { return null; /* diagnostics must never fail the caller */ }
|
|
566
575
|
}
|
|
567
576
|
|
|
577
|
+
/** writeTypeSafeLog() for async callers (judge()): waits for the writer without blocking the event loop, then gives the id. */
|
|
578
|
+
export async function writeTypeSafeLogAsync(row: TypeSafeLogRow): Promise<number | null> {
|
|
579
|
+
try {
|
|
580
|
+
const d = getDb();
|
|
581
|
+
if (d.isTransaction) return insertTypeSafeLog(d, row);
|
|
582
|
+
return await withMemoryWrite(d, () => insertTypeSafeLog(d, row));
|
|
583
|
+
} catch { return null; }
|
|
584
|
+
}
|
|
585
|
+
|
|
568
586
|
/** Record what the caller did with a judgment. Bounded; never throws. */
|
|
569
587
|
export function annotateTypeSafeLog(id: number | null | undefined, outcome: unknown): void {
|
|
570
588
|
if (!id) return;
|
|
571
589
|
try {
|
|
572
590
|
let text = JSON.stringify(outcome);
|
|
573
591
|
if (text.length > OUTCOME_MAX_CHARS) text = JSON.stringify({ truncated: true, chars: text.length });
|
|
574
|
-
|
|
592
|
+
const d = getDb();
|
|
593
|
+
writeNowOrSoon(d, () => d.prepare('UPDATE typesafe_log SET outcome=? WHERE id=?').run(text, id));
|
|
575
594
|
} catch { /* diagnostics */ }
|
|
576
595
|
}
|
|
577
596
|
|
|
578
597
|
/** Point rows logged under a provisional entity id at the one that was finally stored. */
|
|
579
598
|
export function relinkTypeSafeLog(fromEntity: string, toEntity: string): void {
|
|
580
599
|
if (!fromEntity || !toEntity || fromEntity === toEntity) return;
|
|
581
|
-
try { getDb().prepare('UPDATE typesafe_log SET entity_id=? WHERE entity_id=?').run(toEntity, fromEntity); } catch { /* diagnostics */ }
|
|
600
|
+
try { const d = getDb(); writeNowOrSoon(d, () => d.prepare('UPDATE typesafe_log SET entity_id=? WHERE entity_id=?').run(toEntity, fromEntity)); } catch { /* diagnostics */ }
|
|
582
601
|
}
|
|
583
602
|
|
|
584
603
|
/** Keep only the newest `keep` rows. Returns the number deleted. */
|
|
@@ -31,7 +31,7 @@ import { existsSync, readFileSync } from 'node:fs';
|
|
|
31
31
|
import { getEnvPath } from '../config.js';
|
|
32
32
|
import { callerMemoryContext } from './identity.js';
|
|
33
33
|
import {
|
|
34
|
-
typesafeConfig, surfaceConfig,
|
|
34
|
+
typesafeConfig, surfaceConfig, writeTypeSafeLogAsync, statePreview, cleanSessionId,
|
|
35
35
|
DEFAULT_BASE_URL, DEFAULT_MODEL, type JudgeOrigin,
|
|
36
36
|
} from './typesafe-config.js';
|
|
37
37
|
|
|
@@ -295,8 +295,10 @@ export async function judge(
|
|
|
295
295
|
const sessionId = cleanSessionId(options.sessionId === undefined ? caller.session : options.sessionId);
|
|
296
296
|
const project = (options.project === undefined ? caller.project : options.project) || null;
|
|
297
297
|
const riders = options.riders?.filter(r => r && r !== surface) ?? [];
|
|
298
|
-
|
|
299
|
-
|
|
298
|
+
// Awaited, so onLogged still runs before the judgment returns; the row waits for SQLite's writer without
|
|
299
|
+
// blocking the event loop (a capture in the session-cache worker can hold it for a while).
|
|
300
|
+
const log = async (fields: { answers?: Answers | null; latencyMs: number; inputTokens: number; outputTokens: number; cached: boolean; error: string | null; model?: string | null }) => {
|
|
301
|
+
const id = await writeTypeSafeLogAsync({
|
|
300
302
|
surface, origin, entity_id: options.entityId ?? null, model: fields.model ?? model,
|
|
301
303
|
question_count: questionCount, state_preview: preview, answers: fields.answers ?? null,
|
|
302
304
|
latency_ms: fields.latencyMs, input_tokens: fields.inputTokens, output_tokens: fields.outputTokens,
|
|
@@ -312,7 +314,7 @@ export async function judge(
|
|
|
312
314
|
if (cached) {
|
|
313
315
|
typesafeMetrics.cached++; metrics.cached++;
|
|
314
316
|
options.onUsage?.({ inputTokens: 0, outputTokens: 0, latencyMs: 0, cached: true });
|
|
315
|
-
log({ answers: cached, latencyMs: 0, inputTokens: 0, outputTokens: 0, cached: true, error: null });
|
|
317
|
+
await log({ answers: cached, latencyMs: 0, inputTokens: 0, outputTokens: 0, cached: true, error: null });
|
|
316
318
|
return cached;
|
|
317
319
|
}
|
|
318
320
|
}
|
|
@@ -321,11 +323,11 @@ export async function judge(
|
|
|
321
323
|
const timeoutMs = options.timeoutMs ?? settings.timeoutMs ?? cfg.defaultTimeoutMs;
|
|
322
324
|
const started = Date.now();
|
|
323
325
|
typesafeMetrics.calls++; metrics.calls++;
|
|
324
|
-
const fail = (message: string) => {
|
|
326
|
+
const fail = async (message: string) => {
|
|
325
327
|
typesafeMetrics.failures++; metrics.failures++;
|
|
326
328
|
typesafeMetrics.lastError = message;
|
|
327
329
|
typesafeMetrics.lastErrorAt = new Date().toISOString();
|
|
328
|
-
log({ latencyMs: Date.now() - started, inputTokens: 0, outputTokens: 0, cached: false, error: message });
|
|
330
|
+
await log({ latencyMs: Date.now() - started, inputTokens: 0, outputTokens: 0, cached: false, error: message });
|
|
329
331
|
return null;
|
|
330
332
|
};
|
|
331
333
|
try {
|
|
@@ -366,7 +368,7 @@ export async function judge(
|
|
|
366
368
|
}
|
|
367
369
|
const answeredBy = typeof body.model === 'string' ? body.model : null;
|
|
368
370
|
options.onUsage?.({ inputTokens, outputTokens, latencyMs, cached: false, model: answeredBy });
|
|
369
|
-
log({ answers: body.answers, latencyMs, inputTokens, outputTokens, cached: false, error: null, model: answeredBy ?? model });
|
|
371
|
+
await log({ answers: body.answers, latencyMs, inputTokens, outputTokens, cached: false, error: null, model: answeredBy ?? model });
|
|
370
372
|
return body.answers;
|
|
371
373
|
} catch (error) {
|
|
372
374
|
return fail((error as Error).name === 'TimeoutError' ? 'timeout' : (error as Error).message);
|
|
@@ -43,6 +43,7 @@ export class VectorCache {
|
|
|
43
43
|
|
|
44
44
|
/** Drop everything; next query reloads from the database. */
|
|
45
45
|
invalidate(): void {
|
|
46
|
+
this.version++;
|
|
46
47
|
this.loaded = false;
|
|
47
48
|
this.ids = [];
|
|
48
49
|
this.rowIndexById.clear();
|
|
@@ -87,6 +88,7 @@ export class VectorCache {
|
|
|
87
88
|
}
|
|
88
89
|
|
|
89
90
|
private reload(): void {
|
|
91
|
+
this.version++;
|
|
90
92
|
this.reloadCount++;
|
|
91
93
|
// Read the watermark BEFORE the rows. A concurrent commit will then be
|
|
92
94
|
// replayed on the next call instead of accidentally marked as observed.
|
|
@@ -182,6 +184,7 @@ export class VectorCache {
|
|
|
182
184
|
if (!this.loaded) return;
|
|
183
185
|
const idx = this.rowIndexById.get(id);
|
|
184
186
|
if (idx === undefined) return;
|
|
187
|
+
this.version++;
|
|
185
188
|
|
|
186
189
|
const last = this.count - 1;
|
|
187
190
|
if (idx !== last) {
|
|
@@ -203,17 +206,66 @@ export class VectorCache {
|
|
|
203
206
|
*/
|
|
204
207
|
topK(query: number[] | Float32Array, k: number, threshold: number, allowedIds?: Set<string>): TopKResult[] {
|
|
205
208
|
this.ensureFresh();
|
|
206
|
-
|
|
209
|
+
const scan = this.startScan(query, k, allowedIds, threshold);
|
|
210
|
+
if (!scan) return [];
|
|
211
|
+
this.scanRows(scan, 0, scan.total);
|
|
212
|
+
return this.finishScan(scan);
|
|
213
|
+
}
|
|
207
214
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
215
|
+
/**
|
|
216
|
+
* topK() in slices of ~8 ms that yield to the event loop (149k session
|
|
217
|
+
* chunks: ~60 ms of scoring in one piece). Brings the cache up to date first,
|
|
218
|
+
* as ready() does. A cache changed during a yield is scanned again from the
|
|
219
|
+
* start; after three such restarts the last scan runs without yielding.
|
|
220
|
+
*/
|
|
221
|
+
async topKAsync(query: number[] | Float32Array, k: number, threshold: number, allowedIds?: Set<string>): Promise<TopKResult[]> {
|
|
222
|
+
await this.ready();
|
|
223
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
224
|
+
this.ensureFresh();
|
|
225
|
+
const scan = this.startScan(query, k, allowedIds, threshold);
|
|
226
|
+
if (!scan) return [];
|
|
227
|
+
const version = this.version;
|
|
228
|
+
let from = 0;
|
|
229
|
+
let slice = performance.now();
|
|
230
|
+
while (from < scan.total) {
|
|
231
|
+
const to = Math.min(scan.total, from + 2048);
|
|
232
|
+
this.scanRows(scan, from, to);
|
|
233
|
+
from = to;
|
|
234
|
+
if (from < scan.total && performance.now() - slice >= 8) {
|
|
235
|
+
await new Promise<void>(done => setImmediate(done));
|
|
236
|
+
if (this.version !== version) break;
|
|
237
|
+
slice = performance.now();
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (from >= scan.total) return this.finishScan(scan);
|
|
241
|
+
}
|
|
242
|
+
return this.topK(query, k, threshold, allowedIds);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Bumped by every change to the rows, their order or the matrix. */
|
|
246
|
+
private version = 0;
|
|
213
247
|
|
|
248
|
+
private startScan(query: number[] | Float32Array, k: number, allowedIds: Set<string> | undefined, threshold: number) {
|
|
249
|
+
if (this.count === 0 || this.dim === 0) return null;
|
|
250
|
+
const q = query instanceof Float32Array ? query : new Float32Array(query);
|
|
251
|
+
if (q.length !== this.dim || !q.every(Number.isFinite) || k < 1) return null;
|
|
214
252
|
const selected = allowedIds && allowedIds.size < this.count / 2
|
|
215
253
|
? [...allowedIds].map(id=>this.rowIndexById.get(id)).filter((r): r is number=>r !== undefined) : undefined;
|
|
216
|
-
|
|
254
|
+
return { q, k, threshold, allowedIds, selected, total: selected?.length ?? this.count, hits: [] as TopKResult[] };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private finishScan(scan: { hits: TopKResult[]; k: number }): TopKResult[] {
|
|
258
|
+
const { hits, k } = scan;
|
|
259
|
+
hits.sort((a, b) => b.score - a.score);
|
|
260
|
+
return hits.length > k ? hits.slice(0, k) : hits;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
private scanRows(scan: NonNullable<ReturnType<VectorCache['startScan']>>, from: number, to: number): void {
|
|
264
|
+
const { q, k, allowedIds, selected, hits } = scan;
|
|
265
|
+
const threshold = scan.threshold;
|
|
266
|
+
const dim = this.dim;
|
|
267
|
+
const m = this.matrix;
|
|
268
|
+
for (let index = from; index < to; index++) {
|
|
217
269
|
const r = selected ? selected[index] : index;
|
|
218
270
|
if (allowedIds && !allowedIds.has(this.ids[r])) continue;
|
|
219
271
|
const base = r * dim;
|
|
@@ -243,9 +295,102 @@ export class VectorCache {
|
|
|
243
295
|
}
|
|
244
296
|
}
|
|
245
297
|
}
|
|
298
|
+
}
|
|
246
299
|
|
|
247
|
-
|
|
248
|
-
|
|
300
|
+
/**
|
|
301
|
+
* Bring a journalled cache up to date without a synchronous full load, for
|
|
302
|
+
* async callers (recall). A cold cache, or one opened on another connection,
|
|
303
|
+
* is built in slices; a journal backlog of any size replays in slices. The
|
|
304
|
+
* topK() that follows in the same turn then has (almost) nothing to replay.
|
|
305
|
+
* A synchronous reload of 149k session chunks blocked the Neural Interface's
|
|
306
|
+
* event loop for 0.5-1.8 s per recall (docs/startup-freeze-and-agents-audit.md).
|
|
307
|
+
*/
|
|
308
|
+
async ready(): Promise<void> {
|
|
309
|
+
if (!this.entity) return;
|
|
310
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
311
|
+
const db = this.getDb();
|
|
312
|
+
if (!this.loaded || this.connection !== db) { await this.warm(); continue; }
|
|
313
|
+
if (await this.replay(db)) return;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Replay the journal after lastSequence in pages, yielding every ~8 ms. false: the cache changed under it. */
|
|
318
|
+
private async replay(db: DatabaseSync): Promise<boolean> {
|
|
319
|
+
const page = db.prepare('SELECT seq,id FROM memory_changes WHERE entity=? AND seq>? ORDER BY seq LIMIT 512');
|
|
320
|
+
const generation = this.ids;
|
|
321
|
+
let slice = performance.now();
|
|
322
|
+
for (;;) {
|
|
323
|
+
const rows = page.all(this.entity!, this.lastSequence) as Array<{ seq: number; id: string }>;
|
|
324
|
+
if (!rows.length) return true;
|
|
325
|
+
for (const id of new Set(rows.map(r => r.id))) {
|
|
326
|
+
this.remove(id);
|
|
327
|
+
this.setFromDb(id);
|
|
328
|
+
if (performance.now() - slice >= 8) {
|
|
329
|
+
await new Promise<void>(done => setImmediate(done));
|
|
330
|
+
if (generation !== this.ids || !this.loaded || db !== this.getDb()) return false;
|
|
331
|
+
slice = performance.now();
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
if (generation !== this.ids || !this.loaded) return false;
|
|
335
|
+
// A synchronous topK() may have replayed further meanwhile: never move back.
|
|
336
|
+
this.lastSequence = Math.max(this.lastSequence, Number(rows[rows.length - 1].seq));
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
private warming: Promise<void> | null = null;
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Page the journalled table by rowid and read each eligible vector by its
|
|
344
|
+
* indexed id. No cursor or WAL read transaction crosses a yield. Changes to
|
|
345
|
+
* earlier pages replay from the starting watermark before the first search.
|
|
346
|
+
* Concurrent callers share one build.
|
|
347
|
+
*/
|
|
348
|
+
warm(): Promise<void> {
|
|
349
|
+
if (!this.warming) this.warming = this.warmOnce().finally(() => { this.warming = null; });
|
|
350
|
+
return this.warming;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private async warmOnce(): Promise<void> {
|
|
354
|
+
const db = this.getDb();
|
|
355
|
+
if (!this.entity || (this.loaded && this.connection === db)) return;
|
|
356
|
+
const generation = this.ids;
|
|
357
|
+
const watermark = db.prepare('SELECT COALESCE(MAX(seq),0) AS seq FROM memory_changes WHERE entity=?').get(this.entity);
|
|
358
|
+
const table = '"' + this.entity.replaceAll('"', '""') + '"';
|
|
359
|
+
const first = db.prepare(`SELECT rowid,id FROM ${table} ORDER BY rowid LIMIT 64`);
|
|
360
|
+
const next = db.prepare(`SELECT rowid,id FROM ${table} WHERE rowid>? ORDER BY rowid LIMIT 64`);
|
|
361
|
+
first.setReadBigInts(true);
|
|
362
|
+
next.setReadBigInts(true);
|
|
363
|
+
const byId = db.prepare(this.getVectorSql);
|
|
364
|
+
const staged = new VectorCache(this.getDb, this.loadSql, this.getVectorSql);
|
|
365
|
+
staged.loaded = true;
|
|
366
|
+
staged.capacity = 64;
|
|
367
|
+
let slice = performance.now();
|
|
368
|
+
let rows = first.all();
|
|
369
|
+
while (rows.length) {
|
|
370
|
+
for (const row of rows) {
|
|
371
|
+
const vector = byId.get(row.id)?.vector as Uint8Array | undefined;
|
|
372
|
+
if (vector?.byteLength && !(vector.byteLength % 4) && (!staged.dim || vector.byteLength === staged.dim * 4)) {
|
|
373
|
+
staged.set(String(row.id), new Float32Array(vector.buffer, vector.byteOffset, vector.byteLength / 4));
|
|
374
|
+
}
|
|
375
|
+
if (performance.now() - slice >= 8) {
|
|
376
|
+
await new Promise<void>(done => setImmediate(done));
|
|
377
|
+
if (generation !== this.ids || db !== this.getDb()) return;
|
|
378
|
+
slice = performance.now();
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
rows = next.all(rows[rows.length - 1].rowid);
|
|
382
|
+
}
|
|
383
|
+
this.connection = db;
|
|
384
|
+
this.lastSequence = Number(watermark?.seq ?? 0);
|
|
385
|
+
this.ids = staged.ids;
|
|
386
|
+
this.rowIndexById = staged.rowIndexById;
|
|
387
|
+
this.matrix = staged.matrix;
|
|
388
|
+
this.capacity = staged.capacity;
|
|
389
|
+
this.count = staged.count;
|
|
390
|
+
this.dim = staged.dim;
|
|
391
|
+
this.loaded = true;
|
|
392
|
+
this.version++;
|
|
393
|
+
this.reloadCount++;
|
|
249
394
|
}
|
|
250
395
|
|
|
251
396
|
size(): number {
|
|
@@ -38,6 +38,9 @@ export const RUN_EVENT_KINDS = [
|
|
|
38
38
|
'run.completed', 'run.budget', 'run.notice', 'run.message', 'run.progress',
|
|
39
39
|
] as const;
|
|
40
40
|
|
|
41
|
+
/** One title limit for agent_route planned_split.slices and agent_team slices[].title (= TEAM_LIMITS.title in neural-interface/lib/teams/schema.js). */
|
|
42
|
+
export const SLICE_TITLE_MAX = 80;
|
|
43
|
+
|
|
41
44
|
const runIdField = (purpose: string) => z.string().min(1).max(200).describe(purpose);
|
|
42
45
|
const optionalId = (purpose: string) => z.string().min(1).max(200).optional().describe(purpose);
|
|
43
46
|
|
|
@@ -61,9 +64,10 @@ export const agentRouteSchema = {
|
|
|
61
64
|
),
|
|
62
65
|
planned_split: z.object({
|
|
63
66
|
workers: z.number().int().min(1).max(6),
|
|
64
|
-
slices: z.array(z.string().min(1).max(
|
|
67
|
+
slices: z.array(z.string().min(1).max(SLICE_TITLE_MAX).describe(`Slice title, at most ${SLICE_TITLE_MAX} characters: agent_team start must give exactly these titles.`)).min(1).max(6),
|
|
65
68
|
reason: z.string().min(1).max(400).optional(),
|
|
66
69
|
}).optional().describe('At Pair/Team/Swarm, plan code/complex/research/review before routing. Give the target 2/4/6 workers and distinct slice titles; fewer requires a reason why it cannot sensibly split further. One approval covers the whole plan.'),
|
|
70
|
+
needs_host: z.boolean().optional().describe('Set true when this task requires host access unavailable to workers, such as writing outside the workspace. Computer use alone does not require it. The worker-only classes design, image_gen, and video_gen refuse needs_host:true.'),
|
|
67
71
|
needs_vision: z.boolean().optional().describe('true when the task needs to see images or the screen (always true for computer).'),
|
|
68
72
|
proposals: z.array(z.object({
|
|
69
73
|
kind: z.enum(['direct', 'dispatch']).describe('"direct" = do it here on your own model (or another model of your own provider); "dispatch" = hand it to a worker.'),
|
|
@@ -269,7 +273,7 @@ export const agentCatalogDescription =
|
|
|
269
273
|
'Discover what you can route to: providers (claude-code, codex, opencode, antigravity) with models (tier, price per 1M tokens, vision, context, efforts), plus `chat` (chat-only providers such as maritaca: a side panel the user talks to, prices in BRL, never a dispatch target), accounts with subscription usage remaining (or usage unknown; API keys are n/a), registered projects (cwd candidates), SynaBun tool groups and each host\'s effect, rails/limits, active runs, and `agents`: the SynaBun agents the owner approved, which a dispatch names with agent_ref (ref, name, description, provider/model, task classes, scope global or project, revision; provider and search filter them too). Without arguments it returns a compact routing view (OpenCode sampled); pass provider and/or search to list more models. Call it when the routing sheet in your instructions lacks a model, or after a MODEL_UNKNOWN rejection. Returns JSON.';
|
|
270
274
|
|
|
271
275
|
export const agentRouteDescription =
|
|
272
|
-
'The runtime taskId owns one card: retries return it even with different wording or proposals. Only a genuinely separate subtask uses its own stable task_key. Plan the whole task before routing it once. At Pair/Team/Swarm, code/complex/research/review target 2/4/6 workers: pass planned_split with that many distinct titles or fewer with a reason. All four require cwd; a non-git project falls back to one worker with a reason. The card shows this split and one approval covers all workers. Follow next: agent_team plan → start for all splits. Research/review pass task_class and empty owned_paths: separate worktrees, no integration or landing; wait and synthesize. Never route individual slices. Other classes and Solo stay single. Route an actionable task BEFORE starting it (you are the planner). Give task_class, a one-line summary, your honest confidence (0-1) and 1-3 proposals (direct = here on your model; dispatch = a worker provider/model). proposals.account_id accepts an account id or "auto" (most subscription usage left); limited pinned/default accounts fall back within the provider. The returned target.account includes usage and corrections explain the choice. The server applies the session\'s route mode (always ask / ask when unsure / never ask): it approves at once, or shows the user a route card and waits briefly. A planned split uses workers; on a single-task route card the user can pick here or a worker: follow the returned target.kind and next, never your proposal. Follow the returned status and next: approved+dispatch → follow next with the approved route_id; approved+direct → do it yourself (a route the user kept here is never dispatched: agent_dispatch refuses it with ROUTE_IS_DIRECT); continuation → end your turn (SynaBun continues on the chosen model); pending → end your turn, the choice arrives as a [SynaBun Mailbox] route_decided event; declined → do not start (reason no_capable_model: no model can make the image or video, or see for design; tell the user which Model routes row needs one); clarifying → end your turn, the user has not answered your agent_clarify questions yet (independent:true for a task that does not depend on them). image_gen / video_gen always route to a worker whose model generates the medium, design to a worker whose model can see. With a session budget, a provider whose share is used up cannot take the task: SynaBun first divides the unspent budget again, then moves the task to the next capable provider with money left (your next proposal, the same tier on another provider, then a free model) and says so in corrections (reason budget_share, "budget: codex share used up -> claude-code/sonnet"); the saved routes yield to this. When no provider can pay it declines with reason budget_exhausted and names the dry providers (dry). The result carries budget: each provider\'s share, spent and left. Routed workers inherit the approved agent for their task class; agent_ref "none" opts out. A proposal may name an agent (agent_ref, with cwd for a project\'s own): it is a dispatch on what the agent runs on, unless the proposal names its own. Never use it for conversation or bookkeeping. Returns JSON.';
|
|
276
|
+
'The runtime taskId owns one card: retries return it even with different wording or proposals. Only a genuinely separate subtask uses its own stable task_key. Plan the whole task before routing it once. At Pair/Team/Swarm, code/complex/research/review target 2/4/6 workers: pass planned_split with that many distinct titles or fewer with a reason. All four require cwd; a non-git project falls back to one worker with a reason. The card shows this split and one approval covers all workers. Follow next: agent_team plan → start for all splits. Research/review pass task_class and empty owned_paths: separate worktrees, no integration or landing; wait and synthesize. Never route individual slices. Other classes and Solo stay single. For work that requires access outside the worker sandbox, set needs_host:true. Only Here is available. The worker-only classes design, image_gen, and video_gen refuse needs_host:true with ROUTE_INVALID. Route an actionable task BEFORE starting it (you are the planner). Give task_class, a one-line summary, your honest confidence (0-1) and 1-3 proposals (direct = here on your model; dispatch = a worker provider/model). proposals.account_id accepts an account id or "auto" (most subscription usage left); limited pinned/default accounts fall back within the provider. The returned target.account includes usage and corrections explain the choice. The server applies the session\'s route mode (always ask / ask when unsure / never ask): it approves at once, or shows the user a route card and waits briefly. A planned split uses workers; on a single-task route card the user can pick here or a worker: follow the returned target.kind and next, never your proposal. Follow the returned status and next: approved+dispatch → follow next with the approved route_id; approved+direct → do it yourself (a route the user kept here is never dispatched: agent_dispatch refuses it with ROUTE_IS_DIRECT); continuation → end your turn (SynaBun continues on the chosen model); pending → end your turn, the choice arrives as a [SynaBun Mailbox] route_decided event; declined → do not start (reason no_capable_model: no model can make the image or video, or see for design; tell the user which Model routes row needs one); clarifying → end your turn, the user has not answered your agent_clarify questions yet (independent:true for a task that does not depend on them). image_gen / video_gen always route to a worker whose model generates the medium, design to a worker whose model can see. With a session budget, a provider whose share is used up cannot take the task: SynaBun first divides the unspent budget again, then moves the task to the next capable provider with money left (your next proposal, the same tier on another provider, then a free model) and says so in corrections (reason budget_share, "budget: codex share used up -> claude-code/sonnet"); the saved routes yield to this. When no provider can pay it declines with reason budget_exhausted and names the dry providers (dry). A host-only route on an unpriced provider declines with reason budget_unpriced (BUDGET_UNPRICED). The result carries budget: each provider\'s share, spent and left. Routed workers inherit the approved agent for their task class; agent_ref "none" opts out. A proposal may name an agent (agent_ref, with cwd for a project\'s own): it is a dispatch on what the agent runs on, unless the proposal names its own. Never use it for conversation or bookkeeping. Returns JSON.';
|
|
273
277
|
|
|
274
278
|
export const agentClarifyDescription =
|
|
275
279
|
'Ask the user 1-3 targeted questions BEFORE routing a new request that is materially ambiguous: two plausible readings with different results, an unclear target (project, feature, files, audience), destructive or irreversible scope, spend, or memories that conflict with it. Not for clear requests, details a sensible default covers, anything the request, memory or the project answers, or the model (agent_route asks that). Each question gets 2-4 options (recommended first; the user can always type their own); add constraints (what the request fixes) and assumptions (what you will assume for the rest). The card waits briefly. Follow the returned status and next: answered → route, then agent_dispatch with the brief_id (SynaBun adds the user\'s original words, their answers, the constraints and assumptions to the worker\'s context); declined → proceed on your assumptions; pending → end your turn, the answers arrive as a [SynaBun Mailbox] clarify_answered event or as the user\'s next message, and dependent routes and dispatches wait until then. Returns JSON.';
|
|
@@ -304,13 +308,13 @@ export const agentUsageDescription =
|
|
|
304
308
|
// ════ agents-p4 BEGIN: agent_team ════
|
|
305
309
|
// One task given to several workers (neural-interface/lib/teams/scheduler.js). The same role gate as every agent_*
|
|
306
310
|
// tool; the Neural Interface enforces the session's Agent density, the plan's rules and the landing rule.
|
|
307
|
-
export const AGENT_TEAM_ACTIONS = ['plan', 'start', 'status', 'integrate', 'land', 'cleanup', 'discard', 'list'] as const;
|
|
311
|
+
export const AGENT_TEAM_ACTIONS = ['plan', 'start', 'status', 'assign', 'set_test_command', 'integrate', 'land', 'cleanup', 'discard', 'list'] as const;
|
|
308
312
|
/** The most slices any Agent density allows (Swarm). */
|
|
309
313
|
export const AGENT_TEAM_MAX_SLICES = 6;
|
|
310
314
|
|
|
311
315
|
const teamSliceSchema = z.object({
|
|
312
316
|
id: z.string().min(1).max(40).describe('Short lower-case name of the slice, e.g. "api" ("integration" is reserved).'),
|
|
313
|
-
title: z.string().min(1).max(
|
|
317
|
+
title: z.string().min(1).max(SLICE_TITLE_MAX).describe(`What this part is, in a few words; exactly the approved route's planned_split title (an older route's longer title: its first ${SLICE_TITLE_MAX} characters).`),
|
|
314
318
|
task: z.string().min(1).max(16000).describe('Self-contained instructions for this slice\'s worker: goal, constraints, acceptance. It sees only its own slice, plus which files the other slices own.'),
|
|
315
319
|
owned_paths: z.array(z.string().min(1).max(300)).max(64).optional().describe('The files this slice may write, as patterns relative to the project ("src/api/**", "docs/guide.md"). No file may be owned by two slices. Research/review omit this or pass [] (read-only).'),
|
|
316
320
|
depends_on: z.array(z.string().min(1).max(40)).max(5).optional().describe('Slices that must be joined before this one starts (it then starts from their finished work).'),
|
|
@@ -320,16 +324,16 @@ const teamSliceSchema = z.object({
|
|
|
320
324
|
|
|
321
325
|
export const agentTeamSchema = {
|
|
322
326
|
action: z.enum(AGENT_TEAM_ACTIONS).describe(
|
|
323
|
-
'plan: check a plan (density, overlapping files, dependency cycles) and return it normalized; creates nothing. start: create the worktrees and dispatch the workers. status: slices, runs, claims, the integration branch, the last events. integrate: try again after a needs_attention. land: the integration branch into the user\'s branch. cleanup: after successful land and the user\'s yes, delete finished team worktrees/branches. discard: give the team up. list: this session\'s teams.'
|
|
327
|
+
'plan: check a plan (density, overlapping files, dependency cycles) and return it normalized; creates nothing. start: create the worktrees and dispatch the workers. status: slices, runs, claims, the integration branch, the last events. assign: give unowned paths to a slice. set_test_command: correct the test command before the first join attempt. integrate: try again after a needs_attention. land: the integration branch into the user\'s branch. cleanup: after successful land and the user\'s yes, delete finished team worktrees/branches. discard: give the team up. list: this session\'s teams.'
|
|
324
328
|
),
|
|
325
329
|
assistant_session_id: optionalId('Your ASSISTANT_SESSION_ID (plan, start, list).'),
|
|
326
|
-
team_id: z.string().min(1).max(40).optional().describe('status
|
|
330
|
+
team_id: z.string().min(1).max(40).optional().describe('Required for status, assign, set_test_command, integrate, land, cleanup and discard. For start, use the team_id from plan or let the server generate one.'),
|
|
327
331
|
title: z.string().min(1).max(80).optional().describe('plan / start: the team\'s task in a few words.'),
|
|
328
332
|
project_path: z.string().min(1).max(1024).optional().describe('plan / start: absolute path of the project (a git repository with at least one commit; pick from agent_catalog projects).'),
|
|
329
333
|
base_commit: z.string().min(40).max(64).optional().describe('start: the full commit id the plan action pinned (omitted: the project\'s current commit).'),
|
|
330
334
|
fewer_reason: z.string().min(1).max(400).optional().describe('Required when slices are fewer than density. Must match planned_split.reason on the approved route.'),
|
|
331
335
|
slices: z.array(teamSliceSchema).min(1).max(AGENT_TEAM_MAX_SLICES).optional().describe('plan / start: the parts of the task, one worker each. At most what the session\'s Agent density allows (Pair 2, Team 4, Swarm 6; Solo: no team).'),
|
|
332
|
-
test_command: z.string().min(1).max(600).optional().describe('start: what proves the joined work, run on the integration branch after every join (e.g. "npm test"). Without one nothing is tested and you cannot land.'),
|
|
336
|
+
test_command: z.string().min(1).max(600).optional().describe('start / set_test_command: what proves the joined work, run on the integration branch after every join (e.g. "npm test"). The first join attempt locks this command. Without one nothing is tested and you cannot land.'),
|
|
333
337
|
route_id: optionalId('start: the route_id agent_route returned with status "approved" for this task. One route covers every slice.'),
|
|
334
338
|
task_class: z.enum(TASK_CLASSES).optional().describe('plan/start: code (default), complex, research or review. Research/review have read-only worktrees, no integration branch, tests or landing; the approved route must match.'),
|
|
335
339
|
provider: z.enum(PROVIDERS).optional().describe('start: the worker runtime, when there is no route_id and a slice names no agent_ref.'),
|
|
@@ -342,7 +346,8 @@ export const agentTeamSchema = {
|
|
|
342
346
|
context: z.string().max(8000).optional().describe('start: background every worker of the team gets (decisions already taken, conventions).'),
|
|
343
347
|
tags: z.array(z.string().min(1).max(40)).max(6).optional().describe('start: tags for the runs.'),
|
|
344
348
|
brief_id: optionalId('start: the brief_id of a clarification, so every worker gets the user\'s own words and answers.'),
|
|
345
|
-
slice_id: z.string().min(1).max(40).optional().describe('integrate: only this slice (omitted: every slice that is not joined).'),
|
|
349
|
+
slice_id: z.string().min(1).max(40).optional().describe('assign: the slice receiving the paths. integrate: retry only this slice (omitted: every slice that is not joined).'),
|
|
350
|
+
paths: z.array(z.string().min(1).max(300)).min(1).max(64).optional().describe('assign: unowned project-relative paths or patterns to add to this slice, using the plan’s ownership rules.'),
|
|
346
351
|
target_branch: z.string().min(1).max(200).optional().describe('land: the branch that receives the work (default: the branch checked out in the project).'),
|
|
347
352
|
mode: z.enum(['ff', 'merge']).optional().describe('land: "ff" (default) moves the branch forward to the integration branch; "merge" makes a merge commit.'),
|
|
348
353
|
user_confirmed: z.boolean().optional().describe('cleanup: true only after the user says yes to deleting the landed team worktrees and branches; otherwise refused locally.'),
|
|
@@ -352,6 +357,7 @@ export const agentTeamSchema = {
|
|
|
352
357
|
export const agentTeamDescription =
|
|
353
358
|
'Code/complex/research/review: plan the task first, then target the session density (Pair 2, Team 4, Swarm 6). Fewer slices require fewer_reason matching the approved route. agent_route planned_split must match the project, count and titles. One approved route covers all slices, including replacements; never route a slice. Research/review use task_class and empty owned_paths: every worker gets its own worktree from one pinned commit, removed when it ends. Changes or commits are kept and reported. No integration branch, test_command or landing; wait and synthesize their results. Give ONE task to several workers at once, each in its own git worktree and branch (never the user\'s checkout or branch). Code/complex tasks need file-disjoint parts; research/review need distinct read-only scopes, within the user\'s Agent density (Solo 1: no team; Pair 2; Team 4; Swarm 6): SynaBun refuses a team at Solo (TEAM_DENSITY_SOLO) and a plan with more slices than the level allows (TEAM_TOO_MANY_SLICES), with overlapping files or a dependency cycle. ' +
|
|
354
359
|
'Flow: agent_route the task once → action "plan" (returns the normalized plan with its team_id and base_commit, the density check and any errors; creates nothing) → action "start" with that plan and the approved route_id (returns workflow_id) → agent_wait on the workflow_id → a team_ready mailbox event → action "status" → action "land", or ask the user. ' +
|
|
360
|
+
'For a request_change on an unowned path, use "assign" with team_id, slice_id and paths. The worker receives the new scope. Use "set_test_command" to correct the verification command before the first join attempt. ' +
|
|
355
361
|
'SynaBun commits each finished slice\'s own files, joins them on synabun/<team>/integration in dependency order and runs test_command on that exact commit; a conflict or failed tests go back to the slice\'s worker with the report (twice), then a needs_attention event reaches you: read "status", help with agent_send, then "integrate", or "discard". ' +
|
|
356
362
|
'Landing rule: land yourself only when you judge the work ready, the integration tests passed, the user\'s branch has not moved and no file with local changes is touched; land returns SynaBun\'s refusal report unchanged (TESTS_NOT_PASSED, NOT_FAST_FORWARD, OWNER_BRANCH_MOVED, DIRTY_FILES_AFFECTED, TEAM_NOT_READY…). On a refusal do not retry or work around it: ask the user. ' +
|
|
357
363
|
'Cleanup: successful land returns cleanup (worktrees, branches). When the task is fully finished, suggest deleting them with a synabun-followups confirm card. Only after the user says yes call cleanup with team_id and user_confirmed:true. The server requires a landed team, every run ended done, every branch merged into the target and every worktree clean. Refusals CLEANUP_NOT_CONFIRMED, TEAM_NOT_LANDED, TEAM_RUNS_ACTIVE, BRANCH_NOT_MERGED, BRANCH_MOVED (a branch moved after the check), WORKTREE_DIRTY remove nothing: keep them and tell the user which check failed. Never delete team worktrees or branches with git directly. Returns JSON.';
|
|
@@ -406,6 +412,7 @@ export function handleAgentRoute(args: AgentRouteArgs): Promise<ToolResult> {
|
|
|
406
412
|
task_key: args.task_key,
|
|
407
413
|
summary: args.summary,
|
|
408
414
|
confidence: args.confidence,
|
|
415
|
+
needs_host: args.needs_host,
|
|
409
416
|
needs_vision: args.needs_vision,
|
|
410
417
|
planned_split: args.planned_split,
|
|
411
418
|
proposals: args.proposals,
|
|
@@ -686,6 +693,12 @@ export function handleAgentTeam(args: AgentTeamArgs): Promise<ToolResult> {
|
|
|
686
693
|
}
|
|
687
694
|
case 'status':
|
|
688
695
|
return needTeam() ?? json(await ni.assistantTeamStatus(args.team_id as string));
|
|
696
|
+
case 'assign':
|
|
697
|
+
if (!args.team_id || !args.slice_id || !args.paths?.length) return invalid('assign needs team_id, slice_id and paths.');
|
|
698
|
+
return json(await ni.assistantTeamAssign(args.team_id, args.slice_id, args.paths));
|
|
699
|
+
case 'set_test_command':
|
|
700
|
+
if (!args.team_id || !args.test_command?.trim()) return invalid('set_test_command needs team_id and test_command.');
|
|
701
|
+
return json(await ni.assistantTeamSetTestCommand(args.team_id, args.test_command));
|
|
689
702
|
case 'integrate':
|
|
690
703
|
return needTeam() ?? json(await ni.assistantTeamIntegrate(args.team_id as string, { sliceId: args.slice_id }));
|
|
691
704
|
case 'land':
|
|
@@ -712,7 +725,11 @@ export function registerAgentTools(server: McpServer) {
|
|
|
712
725
|
return [
|
|
713
726
|
server.tool('agent_catalog', agentCatalogDescription, agentCatalogSchema, (args) => handleAgentCatalog(args)),
|
|
714
727
|
server.tool('agent_list', agentListDescription, agentListSchema, (args) => handleAgentList(args)),
|
|
715
|
-
|
|
728
|
+
// Claude resumes conversations with their deferred tools. Keep this first-step tool in the
|
|
729
|
+
// current prompt so routing uses the schema advertised by the live MCP connection.
|
|
730
|
+
server.registerTool('agent_route', {
|
|
731
|
+
description: agentRouteDescription, inputSchema: agentRouteSchema, _meta: { 'anthropic/alwaysLoad': true },
|
|
732
|
+
}, (args) => handleAgentRoute(args)),
|
|
716
733
|
server.tool('agent_clarify', agentClarifyDescription, agentClarifySchema, (args) => handleAgentClarify(args)),
|
|
717
734
|
// Preserve unknown input until the handler can reject retired fields from cached client schemas.
|
|
718
735
|
// Neither retired spelling is advertised or accepted as a working dispatch field.
|
|
@@ -2,6 +2,7 @@ import { z } from 'zod/v3';
|
|
|
2
2
|
import * as ni from '../services/neural-interface.js';
|
|
3
3
|
import { text } from './response.js';
|
|
4
4
|
import { useAnswer } from './morelogin.js';
|
|
5
|
+
import { extensionSetupMessage } from './browser-extension-setup.js';
|
|
5
6
|
|
|
6
7
|
const tabIdField = z.string().optional().describe('Target a specific tab within the session. Auto-resolved from environment if omitted.');
|
|
7
8
|
|
|
@@ -15,7 +16,7 @@ export const browserEvaluateSchema = {
|
|
|
15
16
|
};
|
|
16
17
|
|
|
17
18
|
export const browserEvaluateDescription =
|
|
18
|
-
'Execute JavaScript in the browser page context and return the result. Useful for reading DOM state, extracting data, or performing actions not covered by other tools.';
|
|
19
|
+
'Execute JavaScript in the browser page context and return the result. Useful for reading DOM state, extracting data, or performing actions not covered by other tools. Write one expression; wrap statements in a function, (() => { …; return value; })(), which works in every SynaBun browser (the owner\'s everyday browser takes nothing else).';
|
|
19
20
|
|
|
20
21
|
export async function handleBrowserEvaluate(args: { script?: string; expression?: string; sessionId?: string; tabId?: string }) {
|
|
21
22
|
const code = args.script || args.expression;
|
|
@@ -25,7 +26,8 @@ export async function handleBrowserEvaluate(args: { script?: string; expression?
|
|
|
25
26
|
if ('error' in resolved) return text(resolved.error);
|
|
26
27
|
|
|
27
28
|
const result = await ni.evaluate(resolved.sessionId, code, resolved.tabId);
|
|
28
|
-
|
|
29
|
+
// The owner's everyday browser needs a one-time setup before it runs page JavaScript: say that, not a bare code.
|
|
30
|
+
if (result.error) return text(`Evaluate failed: ${extensionSetupMessage(result) || result.error}`);
|
|
29
31
|
|
|
30
32
|
let msg: string;
|
|
31
33
|
try {
|
|
@@ -35,6 +37,11 @@ export async function handleBrowserEvaluate(args: { script?: string; expression?
|
|
|
35
37
|
} catch {
|
|
36
38
|
msg = String(result.result ?? 'undefined');
|
|
37
39
|
}
|
|
40
|
+
// The extension backend cuts a result longer than its cap: what came back is the beginning of its JSON text.
|
|
41
|
+
if (result.truncated === true) {
|
|
42
|
+
const whole = typeof result.valueLength === 'number' ? ` of ${result.valueLength}` : '';
|
|
43
|
+
msg += `\n[truncated: the first ${msg.length}${whole} characters of the result's JSON text. Return less, or read it in parts.]`;
|
|
44
|
+
}
|
|
38
45
|
|
|
39
46
|
return text(msg);
|
|
40
47
|
}
|
|
@@ -72,7 +79,7 @@ export async function handleBrowserWait(args: {
|
|
|
72
79
|
loadState: args.loadState,
|
|
73
80
|
timeout: args.timeout,
|
|
74
81
|
}, resolved.tabId);
|
|
75
|
-
if (result.error) return text(`Wait failed: ${result.error}`);
|
|
82
|
+
if (result.error) return text(`Wait failed: ${extensionSetupMessage(result) || result.error}`);
|
|
76
83
|
|
|
77
84
|
if (args.loadState) {
|
|
78
85
|
if (ni.isBrowserCompactMode()) return text(`Page reached "${args.loadState}"`);
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// What an agent is told when the owner's everyday browser (the SynaBun Browser Bridge extension) cannot run page
|
|
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
|
+
// page or of the call: the answer says what the owner does and what the agent can use meanwhile, so nobody retries,
|
|
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.
|
|
6
|
+
|
|
7
|
+
const EXTENSIONS_PAGE = 'chrome://extensions (edge://extensions in Edge)';
|
|
8
|
+
const NAME = '"SynaBun Browser Bridge"';
|
|
9
|
+
const ALLOW = `choose Details on ${NAME} and turn on "Allow User Scripts" (Chrome or Edge 138 and later; on an older version turn on Developer mode at the top of that page instead), then press Reload on the extension`;
|
|
10
|
+
const MEANWHILE_READ = 'Until then read the page with browser_snapshot or browser_content.';
|
|
11
|
+
|
|
12
|
+
const SETUP: Record<string, string> = {
|
|
13
|
+
USER_SCRIPTS_DISABLED:
|
|
14
|
+
`Running page JavaScript is switched off for the SynaBun extension in the owner's browser, so nothing was run. This is a one-time owner setup: tell the user to open ${EXTENSIONS_PAGE}, ${ALLOW}. ${MEANWHILE_READ}`,
|
|
15
|
+
USER_SCRIPTS_UNSUPPORTED:
|
|
16
|
+
`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
|
+
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.`,
|
|
19
|
+
NETWORK_IDLE_UNAVAILABLE:
|
|
20
|
+
`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
|
+
};
|
|
22
|
+
|
|
23
|
+
/** The owner-setup message for a refused browser call, or null when the refusal is not one of the setup codes. */
|
|
24
|
+
export function extensionSetupMessage(result: Record<string, unknown> | null | undefined): string | null {
|
|
25
|
+
const code = typeof result?.code === 'string' ? result.code : '';
|
|
26
|
+
return Object.prototype.hasOwnProperty.call(SETUP, code) ? SETUP[code] : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The setup codes, for tests. */
|
|
30
|
+
export const EXTENSION_SETUP_CODES = Object.freeze(Object.keys(SETUP));
|
|
@@ -358,5 +358,9 @@ export async function handleBrowserUpload(args: { ref?: string; selector?: strin
|
|
|
358
358
|
const result = await ni.upload(resolved.sessionId, args.selector, args.filePaths, args.nthMatch, resolved.tabId, args.ref, args.textHint, asked);
|
|
359
359
|
if (result.error) return text(`Upload failed: ${result.error}${(await describeFailure(result, { action: 'upload', selector: args.selector, textHint: args.textHint, asked })).text}`);
|
|
360
360
|
|
|
361
|
-
|
|
361
|
+
const target = describeTarget(args.ref, args.selector) + locationSuffix(result);
|
|
362
|
+
const files = result.files as Array<{ name: string; type: string; size: number }> | undefined;
|
|
363
|
+
if (!files?.length) return text(`File selection completed via ${target}. Page file details are unavailable. Check the page before retrying.`);
|
|
364
|
+
const details = files.map(file => `- ${JSON.stringify(file.name)} (${file.type || 'unspecified MIME type'}, ${file.size} bytes)`);
|
|
365
|
+
return text(`File input ${target} reported ${files.length} file(s)\n${details.join('\n')}`);
|
|
362
366
|
}
|