mixdog 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -23
- package/package.json +33 -27
- package/scripts/_test-folder-dialog.mjs +30 -0
- package/scripts/agent-parallel-smoke.mjs +388 -0
- package/scripts/agent-tag-reuse-smoke.mjs +183 -0
- package/scripts/background-task-meta-smoke.mjs +38 -0
- package/scripts/boot-smoke.mjs +52 -9
- package/scripts/build-runtime-linux.sh +348 -0
- package/scripts/build-runtime-macos.sh +217 -0
- package/scripts/build-runtime-windows.ps1 +242 -0
- package/scripts/compact-active-turn-test.mjs +68 -0
- package/scripts/compact-smoke.mjs +859 -129
- package/scripts/compact-trigger-migration-smoke.mjs +187 -0
- package/scripts/fix-brief-fn.mjs +35 -0
- package/scripts/fix-format-tool-surface.mjs +24 -0
- package/scripts/fix-tool-exec-visible.mjs +42 -0
- package/scripts/generate-runtime-manifest.mjs +166 -0
- package/scripts/hook-bus-test.mjs +330 -0
- package/scripts/lead-workflow-smoke.mjs +33 -39
- package/scripts/live-worker-smoke.mjs +43 -37
- package/scripts/llm-trace-summary.mjs +315 -0
- package/scripts/memory-meta-concurrency-test.mjs +20 -0
- package/scripts/output-style-smoke.mjs +56 -15
- package/scripts/parent-abort-link-test.mjs +44 -0
- package/scripts/patch-agent-brief.mjs +48 -0
- package/scripts/patch-app.mjs +21 -0
- package/scripts/patch-app2.mjs +18 -0
- package/scripts/patch-dist-brief.mjs +96 -0
- package/scripts/patch-tool-exec.mjs +70 -0
- package/scripts/pretool-ask-runtime-test.mjs +54 -0
- package/scripts/provider-toolcall-test.mjs +376 -0
- package/scripts/reactive-compact-persist-smoke.mjs +124 -0
- package/scripts/sanitize-tool-pairs-test.mjs +260 -0
- package/scripts/session-context-bench.mjs +344 -0
- package/scripts/session-ingest-smoke.mjs +177 -0
- package/scripts/set-effort-config-test.mjs +41 -0
- package/scripts/smoke-runtime-negative.ps1 +106 -0
- package/scripts/smoke-runtime-negative.sh +97 -0
- package/scripts/smoke.mjs +25 -0
- package/scripts/tool-result-hook-test.mjs +48 -0
- package/scripts/tool-smoke.mjs +1223 -95
- package/scripts/toolcall-args-test.mjs +150 -0
- package/scripts/tui-background-failure-smoke.mjs +73 -0
- package/scripts/usage-metrics-epoch-smoke.mjs +114 -0
- package/src/agents/debugger/AGENT.md +8 -0
- package/src/agents/explore/AGENT.md +4 -0
- package/src/agents/heavy-worker/AGENT.md +9 -3
- package/src/agents/maintainer/AGENT.md +4 -0
- package/src/agents/reviewer/AGENT.md +8 -0
- package/src/agents/scheduler-task/AGENT.md +12 -0
- package/src/agents/scheduler-task/agent.json +6 -0
- package/src/agents/webhook-handler/AGENT.md +12 -0
- package/src/agents/webhook-handler/agent.json +6 -0
- package/src/agents/worker/AGENT.md +9 -3
- package/src/app.mjs +77 -3
- package/src/defaults/hidden-roles.json +17 -12
- package/src/headless-role.mjs +117 -0
- package/src/help.mjs +30 -0
- package/src/hooks/lib/permission-evaluator.cjs +11 -475
- package/src/lib/keychain-cjs.cjs +9 -1
- package/src/lib/mixdog-debug.cjs +0 -7
- package/src/lib/rules-builder.cjs +240 -96
- package/src/lib/text-utils.cjs +1 -1
- package/src/mixdog-session-runtime.mjs +2325 -450
- package/src/output-styles/default.md +12 -28
- package/src/output-styles/extreme-simple.md +9 -6
- package/src/output-styles/simple.md +22 -9
- package/src/repl.mjs +118 -59
- package/src/rules/agent/00-common.md +15 -0
- package/src/rules/{bridge → agent}/20-skip-protocol.md +1 -2
- package/src/rules/agent/30-explorer.md +22 -0
- package/src/rules/{bridge → agent}/40-cycle1-agent.md +7 -0
- package/src/rules/{bridge → agent}/41-cycle2-agent.md +7 -0
- package/src/rules/{bridge → agent}/42-cycle3-agent.md +7 -0
- package/src/rules/lead/01-general.md +9 -5
- package/src/rules/lead/04-workflow.md +51 -12
- package/src/rules/lead/lead-tool.md +6 -0
- package/src/rules/shared/01-tool.md +12 -1
- package/src/runtime/agent/orchestrator/activity-bus.mjs +7 -18
- package/src/runtime/agent/orchestrator/agent-owner.mjs +11 -0
- package/src/runtime/agent/orchestrator/{smart-bridge/bridge-llm.mjs → agent-runtime/agent-dispatch.mjs} +138 -111
- package/src/runtime/agent/orchestrator/agent-runtime/agent-progress-watchdog.mjs +94 -0
- package/src/runtime/agent/orchestrator/{smart-bridge → agent-runtime}/cache-strategy.mjs +32 -23
- package/src/runtime/agent/orchestrator/{smart-bridge → agent-runtime}/session-builder.mjs +33 -27
- package/src/runtime/agent/orchestrator/{bridge-trace.mjs → agent-trace.mjs} +132 -81
- package/src/runtime/agent/orchestrator/cache-mtime.mjs +0 -21
- package/src/runtime/agent/orchestrator/config.mjs +174 -55
- package/src/runtime/agent/orchestrator/context/collect.mjs +195 -487
- package/src/runtime/agent/orchestrator/dispatch-persist.mjs +1 -1
- package/src/runtime/agent/orchestrator/internal-roles.mjs +77 -29
- package/src/runtime/agent/orchestrator/internal-tools.mjs +5 -6
- package/src/runtime/agent/orchestrator/mcp/client.mjs +15 -9
- package/src/runtime/agent/orchestrator/providers/anthropic-betas.mjs +7 -1
- package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +377 -243
- package/src/runtime/agent/orchestrator/providers/anthropic.mjs +146 -93
- package/src/runtime/agent/orchestrator/providers/api-usage.mjs +236 -4
- package/src/runtime/agent/orchestrator/providers/custom-tool-wire.mjs +49 -0
- package/src/runtime/agent/orchestrator/providers/gemini.mjs +58 -13
- package/src/runtime/agent/orchestrator/providers/grok-oauth.mjs +67 -149
- package/src/runtime/agent/orchestrator/providers/media-normalization.mjs +132 -2
- package/src/runtime/agent/orchestrator/providers/model-catalog.mjs +4 -1
- package/src/runtime/agent/orchestrator/providers/oauth-credential-probes.mjs +45 -0
- package/src/runtime/agent/orchestrator/providers/oauth-usage.mjs +61 -116
- package/src/runtime/agent/orchestrator/providers/openai-compat-presets.mjs +25 -0
- package/src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs +79 -255
- package/src/runtime/agent/orchestrator/providers/openai-compat.mjs +221 -70
- package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +477 -147
- package/src/runtime/agent/orchestrator/providers/openai-oauth.mjs +343 -496
- package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +6 -6
- package/src/runtime/agent/orchestrator/providers/registry.mjs +88 -51
- package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +31 -11
- package/src/runtime/agent/orchestrator/providers/statusline-route-meta.mjs +41 -8
- package/src/runtime/agent/orchestrator/session/cache/post-edit-marks.mjs +4 -4
- package/src/runtime/agent/orchestrator/session/cache/read-cache.mjs +1 -1
- package/src/runtime/agent/orchestrator/session/compact.mjs +1173 -267
- package/src/runtime/agent/orchestrator/session/context-utils.mjs +199 -36
- package/src/runtime/agent/orchestrator/session/loop.mjs +851 -674
- package/src/runtime/agent/orchestrator/session/manager.mjs +1593 -466
- package/src/runtime/agent/orchestrator/session/manager.reactive-persist.test.mjs +107 -0
- package/src/runtime/agent/orchestrator/session/store.mjs +291 -46
- package/src/runtime/agent/orchestrator/session/tool-result-offload.mjs +2 -2
- package/src/runtime/agent/orchestrator/stall-policy.mjs +31 -16
- package/src/runtime/agent/orchestrator/tool-loop-guard.mjs +3 -219
- package/src/runtime/agent/orchestrator/tools/bash-session.mjs +34 -7
- package/src/runtime/agent/orchestrator/tools/builtin/advisory-lock.mjs +1 -1
- package/src/runtime/agent/orchestrator/tools/builtin/arg-guard.mjs +19 -0
- package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +9 -9
- package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +60 -37
- package/src/runtime/agent/orchestrator/tools/builtin/cache-layers.mjs +21 -2
- package/src/runtime/agent/orchestrator/tools/builtin/device-paths.mjs +1 -1
- package/src/runtime/agent/orchestrator/tools/builtin/diagnostics-tool.mjs +0 -7
- package/src/runtime/agent/orchestrator/tools/builtin/glob-walk.mjs +1 -3
- package/src/runtime/agent/orchestrator/tools/builtin/list-tool.mjs +36 -12
- package/src/runtime/agent/orchestrator/tools/builtin/read-args.mjs +2 -0
- package/src/runtime/agent/orchestrator/tools/builtin/read-constants.mjs +2 -2
- package/src/runtime/agent/orchestrator/tools/builtin/read-formatting.mjs +5 -12
- package/src/runtime/agent/orchestrator/tools/builtin/read-image-resize.mjs +1 -1
- package/src/runtime/agent/orchestrator/tools/builtin/read-single-tool.mjs +4 -36
- package/src/runtime/agent/orchestrator/tools/builtin/read-tool.mjs +2 -40
- package/src/runtime/agent/orchestrator/tools/builtin/rg-runner.mjs +148 -27
- package/src/runtime/agent/orchestrator/tools/builtin/search-builders.mjs +2 -2
- package/src/runtime/agent/orchestrator/tools/builtin/search-tool.mjs +43 -75
- package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +90 -20
- package/src/runtime/agent/orchestrator/tools/builtin/snapshot-store.mjs +1 -1
- package/src/runtime/agent/orchestrator/tools/builtin.mjs +59 -5
- package/src/runtime/agent/orchestrator/tools/code-graph-state.mjs +86 -0
- package/src/runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs +11 -11
- package/src/runtime/agent/orchestrator/tools/code-graph.mjs +4106 -4019
- package/src/runtime/agent/orchestrator/tools/patch-tool-defs.mjs +33 -4
- package/src/runtime/agent/orchestrator/tools/patch.mjs +90 -6
- package/src/runtime/agent/orchestrator/tools/progress-message.mjs +6 -4
- package/src/runtime/agent/orchestrator/tools/result-compression.mjs +4 -4
- package/src/runtime/agent/orchestrator/tools/shell-command.mjs +8 -1
- package/src/runtime/agent/orchestrator/tools/shell-snapshot.mjs +4 -4
- package/src/runtime/channels/index.mjs +152 -24
- package/src/runtime/channels/lib/scheduler.mjs +18 -14
- package/src/runtime/channels/lib/session-discovery.mjs +3 -2
- package/src/runtime/channels/lib/tool-format.mjs +0 -2
- package/src/runtime/channels/lib/transcript-discovery.mjs +3 -2
- package/src/runtime/channels/lib/webhook.mjs +1 -1
- package/src/runtime/channels/tool-defs.mjs +29 -29
- package/src/runtime/memory/index.mjs +635 -107
- package/src/runtime/memory/lib/agent-ipc.mjs +29 -12
- package/src/runtime/memory/lib/core-memory-store.mjs +2 -2
- package/src/runtime/memory/lib/embedding-model-config.mjs +55 -0
- package/src/runtime/memory/lib/embedding-provider.mjs +31 -4
- package/src/runtime/memory/lib/embedding-worker.mjs +19 -10
- package/src/runtime/memory/lib/memory-cycle1.mjs +38 -17
- package/src/runtime/memory/lib/memory-cycle2.mjs +6 -7
- package/src/runtime/memory/lib/memory-cycle3.mjs +4 -4
- package/src/runtime/memory/lib/memory-ops-policy.mjs +2 -1
- package/src/runtime/memory/lib/memory-session-merge.mjs +38 -0
- package/src/runtime/memory/lib/memory.mjs +88 -9
- package/src/runtime/memory/lib/model-profile.mjs +1 -1
- package/src/runtime/memory/lib/pg/adapter.mjs +15 -1
- package/src/runtime/memory/lib/pg/supervisor.mjs +12 -0
- package/src/runtime/memory/lib/runtime-fetcher.mjs +37 -3
- package/src/runtime/memory/lib/session-ingest.mjs +194 -0
- package/src/runtime/memory/lib/trace-store.mjs +96 -51
- package/src/runtime/memory/tool-defs.mjs +46 -37
- package/src/runtime/search/index.mjs +102 -466
- package/src/runtime/search/lib/web-tools.mjs +45 -25
- package/src/runtime/search/tool-defs.mjs +16 -23
- package/src/runtime/shared/abort-controller.mjs +1 -1
- package/src/runtime/shared/atomic-file.mjs +4 -3
- package/src/runtime/shared/background-tasks.mjs +122 -11
- package/src/runtime/shared/child-spawn-gate.mjs +145 -0
- package/src/runtime/shared/config.mjs +7 -4
- package/src/runtime/shared/err-text.mjs +131 -4
- package/src/runtime/shared/llm/cost.mjs +2 -2
- package/src/runtime/shared/llm/http-agent.mjs +23 -7
- package/src/runtime/shared/llm/index.mjs +34 -11
- package/src/runtime/shared/llm/usage-log.mjs +4 -4
- package/src/runtime/shared/markdown-frontmatter.mjs +56 -0
- package/src/runtime/shared/singleton-owner.mjs +104 -0
- package/src/runtime/shared/tool-execution-contract.mjs +199 -20
- package/src/runtime/shared/tool-execution-contract.test.mjs +183 -0
- package/src/runtime/shared/tool-surface.mjs +624 -98
- package/src/runtime/shared/user-data-guard.mjs +0 -2
- package/src/standalone/agent-task-status.mjs +203 -0
- package/src/standalone/agent-task-status.test.mjs +76 -0
- package/src/standalone/agent-tool.mjs +1913 -0
- package/src/standalone/channel-worker.mjs +370 -14
- package/src/standalone/explore-tool.mjs +165 -70
- package/src/standalone/folder-dialog.mjs +314 -0
- package/src/standalone/hook-bus.mjs +898 -22
- package/src/standalone/memory-runtime-proxy.mjs +320 -0
- package/src/standalone/projects.mjs +226 -0
- package/src/standalone/provider-admin.mjs +41 -24
- package/src/standalone/seeds.mjs +2 -69
- package/src/standalone/usage-dashboard.mjs +96 -8
- package/src/tui/App.jsx +4798 -2153
- package/src/tui/components/AnsiText.jsx +39 -28
- package/src/tui/components/ContextPanel.jsx +87 -29
- package/src/tui/components/Markdown.jsx +43 -77
- package/src/tui/components/MarkdownTable.jsx +9 -184
- package/src/tui/components/Message.jsx +28 -11
- package/src/tui/components/Picker.jsx +95 -56
- package/src/tui/components/PromptInput.jsx +367 -239
- package/src/tui/components/QueuedCommands.jsx +1 -1
- package/src/tui/components/SlashCommandPalette.jsx +27 -21
- package/src/tui/components/Spinner.jsx +67 -38
- package/src/tui/components/StatusLine.jsx +606 -38
- package/src/tui/components/TextEntryPanel.jsx +128 -9
- package/src/tui/components/ToolExecution.jsx +617 -368
- package/src/tui/components/TurnDone.jsx +3 -3
- package/src/tui/components/UsagePanel.jsx +3 -5
- package/src/tui/components/tool-output-format.mjs +365 -0
- package/src/tui/components/tool-output-format.test.mjs +220 -0
- package/src/tui/dist/index.mjs +8915 -2418
- package/src/tui/engine-runtime-notification.test.mjs +115 -0
- package/src/tui/engine-tool-result-text.test.mjs +75 -0
- package/src/tui/engine.mjs +1455 -279
- package/src/tui/figures.mjs +21 -40
- package/src/tui/index.jsx +75 -31
- package/src/tui/input-editing.mjs +25 -0
- package/src/tui/markdown/format-token.mjs +511 -68
- package/src/tui/markdown/format-token.test.mjs +216 -0
- package/src/tui/markdown/render-ansi.mjs +94 -0
- package/src/tui/markdown/render-ansi.test.mjs +108 -0
- package/src/tui/markdown/stream-fence.mjs +34 -0
- package/src/tui/markdown/stream-fence.test.mjs +26 -0
- package/src/tui/markdown/table-layout.mjs +250 -0
- package/src/tui/paste-attachments.mjs +0 -7
- package/src/tui/spinner-verbs.mjs +1 -2
- package/src/tui/statusline-ansi-bridge.mjs +172 -0
- package/src/tui/statusline-ansi-bridge.test.mjs +159 -0
- package/src/tui/theme.mjs +746 -24
- package/src/tui/time-format.mjs +1 -1
- package/src/tui/transcript-tool-failures.mjs +67 -0
- package/src/tui/transcript-tool-failures.test.mjs +111 -0
- package/src/ui/ansi.mjs +1 -2
- package/src/ui/markdown.mjs +85 -26
- package/src/ui/markdown.test.mjs +70 -0
- package/src/ui/model-display.mjs +121 -0
- package/src/ui/session-stats.mjs +44 -0
- package/src/ui/statusline-context-label.test.mjs +15 -0
- package/src/ui/statusline.mjs +386 -178
- package/src/ui/tool-card.mjs +3 -16
- package/src/vendor/statusline/bin/statusline-lib.mjs +8 -4
- package/src/vendor/statusline/bin/statusline-route.mjs +169 -37
- package/src/vendor/statusline/bin/statusline-route.test.mjs +80 -0
- package/src/vendor/statusline/scripts/lib/gateway-settings.mjs +3 -3
- package/src/vendor/statusline/src/gateway/claude-current.mjs +1 -1
- package/src/vendor/statusline/src/gateway/route-meta.mjs +44 -6
- package/src/vendor/statusline/src/gateway/session-routes.mjs +1 -1
- package/src/workflows/default/WORKFLOW.md +12 -5
- package/src/workflows/default/workflow.json +0 -1
- package/src/workflows/solo/WORKFLOW.md +15 -0
- package/src/workflows/solo/workflow.json +7 -0
- package/vendor/ink/build/output.js +6 -1
- package/src/agents/scheduler-task.md +0 -3
- package/src/agents/web-researcher/AGENT.md +0 -3
- package/src/agents/web-researcher/agent.json +0 -6
- package/src/agents/webhook-handler.md +0 -3
- package/src/rules/bridge/00-common.md +0 -5
- package/src/rules/bridge/30-explorer.md +0 -4
- package/src/rules/lead/00-tool-lead.md +0 -5
- package/src/rules/shared/00-language.md +0 -3
- package/src/runtime/agent/orchestrator/tools/builtin/native-edit-runner.mjs +0 -110
- package/src/runtime/agent/orchestrator/tools/mutation-content-cache.mjs +0 -67
- package/src/runtime/memory/lib/bridge-trace-queries.mjs +0 -120
- package/src/runtime/shared/llm/pid-cleanup.mjs +0 -27
- package/src/standalone/bridge-tool.mjs +0 -1414
- package/src/tui/runtime/shared/process-shutdown.mjs +0 -1
|
@@ -1,1414 +0,0 @@
|
|
|
1
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
-
import { isAbsolute, resolve } from 'node:path';
|
|
3
|
-
import {
|
|
4
|
-
TOOL_ASYNC_EXECUTION_CONTRACT,
|
|
5
|
-
cancelBackgroundTask,
|
|
6
|
-
cleanupBackgroundTasks,
|
|
7
|
-
executionModeSchemaDescription,
|
|
8
|
-
getBackgroundTask,
|
|
9
|
-
listBackgroundTasks,
|
|
10
|
-
resolveExecutionMode,
|
|
11
|
-
startBackgroundTask,
|
|
12
|
-
taskIdFromArgs,
|
|
13
|
-
} from '../runtime/shared/background-tasks.mjs';
|
|
14
|
-
import { presentErrorText } from '../runtime/shared/err-text.mjs';
|
|
15
|
-
import { updateJsonAtomicSync } from '../runtime/shared/atomic-file.mjs';
|
|
16
|
-
import { prepareBridgeSession } from '../runtime/agent/orchestrator/smart-bridge/session-builder.mjs';
|
|
17
|
-
import { clearGatewaySessionRoute, writeGatewaySessionRoute } from '../vendor/statusline/src/gateway/session-routes.mjs';
|
|
18
|
-
|
|
19
|
-
const ROLE_PERMISSION_ALIASES = new Map([
|
|
20
|
-
['readonly', 'read'],
|
|
21
|
-
['read-only', 'read'],
|
|
22
|
-
['read', 'read'],
|
|
23
|
-
['full', 'full'],
|
|
24
|
-
]);
|
|
25
|
-
|
|
26
|
-
const PRESET_ALIASES = new Map([
|
|
27
|
-
['opus-xhigh', { base: 'opus-high', effort: 'xhigh', id: 'opus-xhigh', name: 'OPUS XHIGH' }],
|
|
28
|
-
]);
|
|
29
|
-
|
|
30
|
-
const DEFAULT_AGENT_PRESETS = Object.freeze({
|
|
31
|
-
explore: 'sonnet-high',
|
|
32
|
-
'web-researcher': 'sonnet-high',
|
|
33
|
-
maintainer: 'haiku',
|
|
34
|
-
worker: 'sonnet-high',
|
|
35
|
-
'heavy-worker': 'opus-high',
|
|
36
|
-
reviewer: 'opus-xhigh',
|
|
37
|
-
debugger: 'opus-xhigh',
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
export const BRIDGE_TOOL = {
|
|
41
|
-
name: 'bridge',
|
|
42
|
-
title: 'Bridge Agent',
|
|
43
|
-
annotations: {
|
|
44
|
-
title: 'Bridge Agent',
|
|
45
|
-
readOnlyHint: false,
|
|
46
|
-
destructiveHint: true,
|
|
47
|
-
idempotentHint: false,
|
|
48
|
-
openWorldHint: true,
|
|
49
|
-
bridgeHidden: true,
|
|
50
|
-
},
|
|
51
|
-
description: 'Delegate scoped work to workflow agents. Prefer async by default: spawn independent agents in parallel with distinct tags, then keep doing Lead-side work that does not need their result. After async spawn, do not call status/read, do not interfere, and do not poll; wait for the completion notification only when the next step depends on that result. status/read are manual recovery or explicit user-requested controls only. Use sync only when the next step must block.',
|
|
52
|
-
inputSchema: {
|
|
53
|
-
type: 'object',
|
|
54
|
-
properties: {
|
|
55
|
-
type: { type: 'string', enum: ['spawn', 'send', 'list', 'close', 'cancel', 'status', 'read', 'cleanup'], description: 'Action. Default spawn; send follows up to an existing tag/session. status/read are manual recovery controls, not normal polling.' },
|
|
56
|
-
mode: { type: 'string', enum: ['async', 'sync'], description: `${executionModeSchemaDescription('async')} Prefer async for model handoffs; use sync only for an explicit blocking handoff.` },
|
|
57
|
-
task_id: { type: 'string', description: 'Manual status/read/cancel recovery task id; not needed for normal async completion.' },
|
|
58
|
-
agent: { type: 'string', description: 'Workflow agent id to run.' },
|
|
59
|
-
tag: { type: 'string', description: 'Stable agent handle; distinct tag per parallel agent.' },
|
|
60
|
-
sessionId: { type: 'string', description: 'Raw sess_ id.' },
|
|
61
|
-
prompt: { type: 'string', description: 'Scoped task brief: anchors, constraints, done condition.' },
|
|
62
|
-
message: { type: 'string', description: 'Follow-up for send, or spawn brief.' },
|
|
63
|
-
file: { type: 'string', description: 'Prompt file.' },
|
|
64
|
-
cwd: { type: 'string', description: 'Working directory.' },
|
|
65
|
-
context: { type: 'string', description: 'Extra agent context.' },
|
|
66
|
-
firstResponseTimeoutMs: { type: 'number', minimum: 0, description: 'Abort only when the agent produces no first stream/tool activity within this many ms. Default 120s. 0 disables this watchdog.' },
|
|
67
|
-
idleTimeoutMs: { type: 'number', minimum: 0, description: 'Stale watchdog after first stream/tool activity. Default 30m. 0 disables stale abort.' },
|
|
68
|
-
},
|
|
69
|
-
additionalProperties: true,
|
|
70
|
-
},
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
const FINISHED_JOB_TTL_MS = 30 * 60_000;
|
|
74
|
-
const MAX_JOBS = 200;
|
|
75
|
-
const TERMINAL_REAP_MS = 60 * 60_000;
|
|
76
|
-
const WORKER_INDEX_FILE = 'bridge-workers.json';
|
|
77
|
-
function envTimeoutMs(name, fallback) {
|
|
78
|
-
const raw = process.env[name];
|
|
79
|
-
if (raw === undefined || raw === '') return fallback;
|
|
80
|
-
const n = Number(raw);
|
|
81
|
-
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
const DEFAULT_FIRST_RESPONSE_TIMEOUT_MS = envTimeoutMs('MIXDOG_BRIDGE_FIRST_RESPONSE_TIMEOUT_MS', 120_000);
|
|
85
|
-
const DEFAULT_STALE_TIMEOUT_MS = envTimeoutMs('MIXDOG_BRIDGE_STALE_TIMEOUT_MS', 30 * 60_000);
|
|
86
|
-
const ACTIVE_STAGES = new Set(['connecting', 'requesting', 'streaming', 'tool_running', 'running', 'cancelling']);
|
|
87
|
-
|
|
88
|
-
function clean(value) {
|
|
89
|
-
return String(value ?? '').trim();
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function normalizeAgentName(value) {
|
|
93
|
-
const id = clean(value).toLowerCase().replace(/[\s_]+/g, '-');
|
|
94
|
-
if (id === 'explorer') return 'explore';
|
|
95
|
-
if (id === 'maint' || id === 'maintenance' || id === 'memory') return 'maintainer';
|
|
96
|
-
if (id === 'heavy' || id === 'heavyworker') return 'heavy-worker';
|
|
97
|
-
if (id === 'review') return 'reviewer';
|
|
98
|
-
if (id === 'debug') return 'debugger';
|
|
99
|
-
return id;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export function resolveBridgeExecutionMode(args = {}, context = {}, defaultMode = 'async') {
|
|
103
|
-
const fallback = context.invocationSource !== 'user-command' ? 'async' : defaultMode;
|
|
104
|
-
return resolveExecutionMode(args, fallback);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
function normalizePermission(value) {
|
|
108
|
-
const key = clean(value).toLowerCase();
|
|
109
|
-
return ROLE_PERMISSION_ALIASES.get(key) || (key ? key : undefined);
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
function positiveInt(value) {
|
|
113
|
-
const n = Number(value);
|
|
114
|
-
return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
function terminalPidForContext(context = {}) {
|
|
118
|
-
return positiveInt(context?.clientHostPid);
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
function bridgeScope(args = {}, context = {}) {
|
|
122
|
-
const scope = clean(args.scope || args.terminal || args.term).toLowerCase();
|
|
123
|
-
if (args.allTerminals === true || scope === 'all' || scope === 'global') return {};
|
|
124
|
-
return context || {};
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
function sessionMatchesContext(session, context = {}) {
|
|
128
|
-
const wantedPid = terminalPidForContext(context);
|
|
129
|
-
if (!wantedPid) return true;
|
|
130
|
-
const sessionPid = positiveInt(session?.clientHostPid);
|
|
131
|
-
return !!sessionPid && sessionPid === wantedPid;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
function rowMatchesContext(row, context = {}) {
|
|
135
|
-
const wantedPid = terminalPidForContext(context);
|
|
136
|
-
if (!wantedPid) return true;
|
|
137
|
-
const rowPid = positiveInt(row?.clientHostPid);
|
|
138
|
-
return !!rowPid && rowPid === wantedPid;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
function nonNegativeInt(value) {
|
|
142
|
-
if (value === undefined || value === null || value === '') return null;
|
|
143
|
-
const n = Number(value);
|
|
144
|
-
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : null;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
function resolveWatchdogMs(value, fallback) {
|
|
148
|
-
const explicit = nonNegativeInt(value);
|
|
149
|
-
if (explicit !== null) return explicit;
|
|
150
|
-
return nonNegativeInt(fallback) ?? 0;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
function presetKey(preset) {
|
|
154
|
-
return clean(preset?.id || preset?.name);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
function bridgeRouteForStatusline(preset = {}) {
|
|
158
|
-
const provider = clean(preset.provider);
|
|
159
|
-
const model = clean(preset.model);
|
|
160
|
-
if (!provider || !model) return null;
|
|
161
|
-
const out = {
|
|
162
|
-
mode: 'fixed',
|
|
163
|
-
defaultProvider: provider,
|
|
164
|
-
defaultModel: model,
|
|
165
|
-
};
|
|
166
|
-
const id = clean(preset.id);
|
|
167
|
-
const name = clean(preset.name);
|
|
168
|
-
const modelDisplay = clean(preset.modelDisplay || preset.display || preset.displayName);
|
|
169
|
-
const effort = clean(preset.effort);
|
|
170
|
-
if (id) out.presetId = id;
|
|
171
|
-
if (name) out.presetName = name;
|
|
172
|
-
if (modelDisplay) out.modelDisplay = modelDisplay;
|
|
173
|
-
if (effort) {
|
|
174
|
-
out.effort = effort;
|
|
175
|
-
out.displayEffort = effort;
|
|
176
|
-
}
|
|
177
|
-
if (preset.fast === true || preset.fast === false) out.fast = preset.fast;
|
|
178
|
-
return out;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
function writeBridgeStatuslineRoute(sessionId, preset) {
|
|
182
|
-
const route = bridgeRouteForStatusline(preset);
|
|
183
|
-
if (!sessionId || !route) return false;
|
|
184
|
-
try { return writeGatewaySessionRoute(sessionId, route); } catch { return false; }
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
function clearBridgeStatuslineRoute(sessionId) {
|
|
188
|
-
if (!sessionId) return false;
|
|
189
|
-
try { return clearGatewaySessionRoute(sessionId); } catch { return false; }
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
function findPreset(config, key) {
|
|
193
|
-
const wanted = clean(key).toLowerCase();
|
|
194
|
-
if (!wanted) return null;
|
|
195
|
-
const presets = Array.isArray(config?.presets) ? config.presets : [];
|
|
196
|
-
return presets.find((p) => {
|
|
197
|
-
return clean(p?.id).toLowerCase() === wanted || clean(p?.name).toLowerCase() === wanted;
|
|
198
|
-
}) || null;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
function synthesizePreset(config, key) {
|
|
202
|
-
const alias = PRESET_ALIASES.get(clean(key).toLowerCase());
|
|
203
|
-
if (!alias) return null;
|
|
204
|
-
const base = findPreset(config, alias.base);
|
|
205
|
-
if (!base) return null;
|
|
206
|
-
return {
|
|
207
|
-
...base,
|
|
208
|
-
id: alias.id,
|
|
209
|
-
name: alias.name,
|
|
210
|
-
effort: alias.effort,
|
|
211
|
-
};
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
function normalizeAgentRoute(routeLike) {
|
|
215
|
-
const provider = clean(routeLike?.provider);
|
|
216
|
-
const model = clean(routeLike?.model);
|
|
217
|
-
if (!provider || !model) return null;
|
|
218
|
-
return {
|
|
219
|
-
provider,
|
|
220
|
-
model,
|
|
221
|
-
effort: clean(routeLike?.effort) || undefined,
|
|
222
|
-
fast: routeLike?.fast === true,
|
|
223
|
-
};
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
function agentPresetName(role) {
|
|
227
|
-
return `AGENT ${String(role || '').toUpperCase()}`;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
function readRoles(dataDir) {
|
|
231
|
-
const file = resolve(dataDir, 'user-workflow.json');
|
|
232
|
-
if (!existsSync(file)) return new Map();
|
|
233
|
-
const raw = JSON.parse(readFileSync(file, 'utf8'));
|
|
234
|
-
const roles = new Map();
|
|
235
|
-
for (const role of raw?.roles || []) {
|
|
236
|
-
if (!role?.name || !role?.preset) continue;
|
|
237
|
-
roles.set(String(role.name), {
|
|
238
|
-
name: String(role.name),
|
|
239
|
-
preset: String(role.preset),
|
|
240
|
-
permission: normalizePermission(role.permission) || 'full',
|
|
241
|
-
desc_path: typeof role.desc_path === 'string' ? role.desc_path : null,
|
|
242
|
-
maxLoopIterations: positiveInt(role.maxLoopIterations),
|
|
243
|
-
idleTimeoutMs: nonNegativeInt(role.idleTimeoutMs),
|
|
244
|
-
firstResponseTimeoutMs: nonNegativeInt(role.firstResponseTimeoutMs),
|
|
245
|
-
});
|
|
246
|
-
}
|
|
247
|
-
return roles;
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
async function resolvePrompt(args, cwd) {
|
|
251
|
-
const prompt = clean(args.prompt || args.message);
|
|
252
|
-
const file = clean(args.file);
|
|
253
|
-
if (prompt && file) throw new Error('bridge: provide only one of prompt/message or file');
|
|
254
|
-
if (prompt) return prompt;
|
|
255
|
-
if (file) {
|
|
256
|
-
const target = isAbsolute(file) ? file : resolve(cwd || process.cwd(), file);
|
|
257
|
-
return readFileSync(target, 'utf8');
|
|
258
|
-
}
|
|
259
|
-
throw new Error('bridge: prompt/message/file is required');
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
function withCwdHeader(prompt, cwd) {
|
|
263
|
-
if (!cwd) return prompt;
|
|
264
|
-
if (String(prompt).startsWith('[effective-cwd]')) return prompt;
|
|
265
|
-
return `[effective-cwd] ${cwd}\n\n${prompt}`;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
function oneLine(value, max = 180) {
|
|
269
|
-
const text = String(value ?? '').replace(/\s+/g, ' ').trim();
|
|
270
|
-
return text.length > max ? `${text.slice(0, max)}...` : text;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
function compactIso(value) {
|
|
274
|
-
const text = clean(value);
|
|
275
|
-
if (!text) return '';
|
|
276
|
-
return text.replace('T', ' ').replace(/\.\d+Z$/, 'Z');
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
function stripFinalAnswerWrapper(value) {
|
|
280
|
-
const text = String(value ?? '').trim();
|
|
281
|
-
const match = /^<final-answer\b[^>]*>([\s\S]*?)<\/final-answer>\s*$/i.exec(text);
|
|
282
|
-
return match ? match[1].trim() : text;
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
function renderResult(value) {
|
|
286
|
-
if (typeof value === 'string') return value;
|
|
287
|
-
if (value && typeof value === 'object') {
|
|
288
|
-
const lines = [];
|
|
289
|
-
|
|
290
|
-
if (Array.isArray(value.workers) || Array.isArray(value.jobs)) {
|
|
291
|
-
lines.push(`bridge mode: ${value.bridgeMode || 'async'}`);
|
|
292
|
-
const workers = Array.isArray(value.workers) ? value.workers : [];
|
|
293
|
-
lines.push(`agents: ${workers.length}`);
|
|
294
|
-
for (const worker of workers) {
|
|
295
|
-
const stale = Number.isFinite(worker.staleSeconds) ? ` stale=${worker.staleSeconds}s` : '';
|
|
296
|
-
const tokens = worker.windowTokens ? ` ctx=${worker.windowTokens}${worker.windowCap ? `/${worker.windowCap}` : ''}` : '';
|
|
297
|
-
const terminal = worker.clientHostPid ? ` term=${worker.clientHostPid}` : '';
|
|
298
|
-
lines.push(`- ${worker.tag} ${worker.role || 'agent'} ${worker.status || 'idle'}/${worker.stage || 'idle'} ${worker.provider}/${worker.model}${terminal}${stale}${tokens}`);
|
|
299
|
-
}
|
|
300
|
-
const jobs = Array.isArray(value.jobs) ? value.jobs : [];
|
|
301
|
-
lines.push(`tasks: ${jobs.length}`);
|
|
302
|
-
for (const job of jobs) {
|
|
303
|
-
const target = job.tag || job.sessionId || '-';
|
|
304
|
-
const terminal = job.clientHostPid ? ` term=${job.clientHostPid}` : '';
|
|
305
|
-
lines.push(`- ${job.task_id} ${job.type} ${job.status} target=${target}${terminal}${job.error ? ` error=${presentErrorText(job.error, { surface: 'bridge' })}` : ''}`);
|
|
306
|
-
}
|
|
307
|
-
if (workers.length === 0 && jobs.length === 0) lines.push('(no bridge agents or tasks)');
|
|
308
|
-
return lines.join('\n');
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
if (value.task_id) {
|
|
312
|
-
lines.push(`bridge task: ${value.task_id}`);
|
|
313
|
-
lines.push(`status: ${value.status}${value.mode ? ` (${value.mode})` : ''}`);
|
|
314
|
-
if (value.type) lines.push(`type: ${value.type}`);
|
|
315
|
-
if (value.tag || value.sessionId) lines.push(`target: ${value.tag || '-'} ${value.sessionId || ''}`.trim());
|
|
316
|
-
if (value.role) lines.push(`agent: ${value.role}`);
|
|
317
|
-
if (value.provider && value.model) lines.push(`model: ${value.provider}/${value.model}`);
|
|
318
|
-
if (value.effort) lines.push(`effort: ${value.effort}`);
|
|
319
|
-
if (value.fast === true || value.fast === false) lines.push(`fast: ${value.fast ? 'on' : 'off'}`);
|
|
320
|
-
if (value.maxLoopIterations || value.idleTimeoutMs || value.firstResponseTimeoutMs) {
|
|
321
|
-
const limitParts = [];
|
|
322
|
-
if (value.maxLoopIterations) limitParts.push(`loop=${value.maxLoopIterations}`);
|
|
323
|
-
if (value.firstResponseTimeoutMs) limitParts.push(`first=${Math.round(value.firstResponseTimeoutMs / 1000)}s`);
|
|
324
|
-
if (value.idleTimeoutMs) limitParts.push(`stale=${Math.round(value.idleTimeoutMs / 1000)}s`);
|
|
325
|
-
lines.push(`limits: ${limitParts.join(' ')}`);
|
|
326
|
-
}
|
|
327
|
-
if (value.stage || value.workerStatus) lines.push(`agent: ${value.workerStatus || 'unknown'}/${value.stage || 'unknown'}`);
|
|
328
|
-
if (value.startedAt) lines.push(`started: ${compactIso(value.startedAt)}`);
|
|
329
|
-
if (value.finishedAt) lines.push(`finished: ${compactIso(value.finishedAt)}`);
|
|
330
|
-
if (value.error) lines.push(`error: ${presentErrorText(value.error, { surface: 'bridge' })}`);
|
|
331
|
-
if (value.status === 'running') lines.push('notification: completion will be delivered to the owner session; use read/status only for manual recovery.');
|
|
332
|
-
if (value.result !== undefined) {
|
|
333
|
-
const result = value.result;
|
|
334
|
-
const content = typeof result === 'string' ? result : result?.content;
|
|
335
|
-
if (content) lines.push('', stripFinalAnswerWrapper(content));
|
|
336
|
-
else lines.push('', JSON.stringify(result, null, 2));
|
|
337
|
-
}
|
|
338
|
-
return lines.join('\n');
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
if (value.queued) {
|
|
342
|
-
return [
|
|
343
|
-
'bridge message queued',
|
|
344
|
-
`target: ${value.tag || '-'} ${value.sessionId || ''}`.trim(),
|
|
345
|
-
value.role ? `agent: ${value.role}` : null,
|
|
346
|
-
`queueDepth: ${value.queueDepth ?? 1}`,
|
|
347
|
-
].filter(Boolean).join('\n');
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
if (value.closed !== undefined) {
|
|
351
|
-
return [
|
|
352
|
-
`bridge close: ${value.closed ? 'ok' : 'not closed'}`,
|
|
353
|
-
value.tag ? `tag: ${value.tag}` : null,
|
|
354
|
-
value.sessionId ? `sessionId: ${value.sessionId}` : null,
|
|
355
|
-
value.task_id ? `task_id: ${value.task_id}` : null,
|
|
356
|
-
value.forgotten ? 'forgotten: true' : null,
|
|
357
|
-
].filter(Boolean).join('\n');
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
if (value.content !== undefined) {
|
|
361
|
-
const header = [
|
|
362
|
-
value.respawned ? 'bridge respawned' : 'bridge result',
|
|
363
|
-
value.tag ? `tag=${value.tag}` : null,
|
|
364
|
-
value.role ? `agent=${value.role}` : null,
|
|
365
|
-
value.provider && value.model ? `${value.provider}/${value.model}` : null,
|
|
366
|
-
].filter(Boolean).join(' ');
|
|
367
|
-
return `${header}\n${stripFinalAnswerWrapper(value.content)}`;
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
return JSON.stringify(value, null, 2);
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
export function createStandaloneBridge({ cfgMod, reg, mgr, dataDir, cwd: defaultCwd, defaultMode: initialMode }) {
|
|
374
|
-
const tags = new Map();
|
|
375
|
-
const tagRoles = new Map();
|
|
376
|
-
const tagCwds = new Map();
|
|
377
|
-
const jobs = new Map();
|
|
378
|
-
const reapTimers = new Map();
|
|
379
|
-
let tagSeq = 0;
|
|
380
|
-
let jobSeq = 0;
|
|
381
|
-
// Inline normalization here (normalizeMode is defined below — avoid
|
|
382
|
-
// use-before-def). When nothing is injected, the Lead defaults to async.
|
|
383
|
-
let defaultMode = (String(initialMode ?? 'async').toLowerCase() === 'async') ? 'async' : 'sync';
|
|
384
|
-
|
|
385
|
-
function normalizeMode(value) {
|
|
386
|
-
const mode = clean(value).toLowerCase();
|
|
387
|
-
return mode === 'async' ? 'async' : 'sync';
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
function modeFor(args = {}, context = {}) {
|
|
391
|
-
return resolveBridgeExecutionMode(args, context, defaultMode);
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
function nextJobId(type) {
|
|
395
|
-
jobSeq += 1;
|
|
396
|
-
return `job_${Date.now()}_${jobSeq}_${clean(type) || 'bridge'}`;
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
function workerIndexPath() {
|
|
400
|
-
return dataDir ? resolve(dataDir, WORKER_INDEX_FILE) : null;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
function workerRowKey(row = {}) {
|
|
404
|
-
return clean(row.sessionId) || clean(row.tag);
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
function workerRowTime(row = {}) {
|
|
408
|
-
return Date.parse(row.updatedAt || row.finishedAt || row.lastUsedAt || row.createdAt || '') || 0;
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
function isTerminalWorkerStatus(status) {
|
|
412
|
-
return /^(idle|closed|completed|failed|error|cancelled|canceled|killed|timeout)$/i.test(clean(status));
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
function keepWorkerRow(row = {}) {
|
|
416
|
-
if (!clean(row.tag) || !clean(row.sessionId)) return false;
|
|
417
|
-
const t = workerRowTime(row);
|
|
418
|
-
if (!t) return true;
|
|
419
|
-
if (!isTerminalWorkerStatus(row.status || row.stage)) return true;
|
|
420
|
-
return Date.now() - t < TERMINAL_REAP_MS;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
function normalizeWorkerRows(value) {
|
|
424
|
-
const source = Array.isArray(value?.workers)
|
|
425
|
-
? value.workers
|
|
426
|
-
: (value?.workers && typeof value.workers === 'object'
|
|
427
|
-
? Object.values(value.workers)
|
|
428
|
-
: (Array.isArray(value) ? value : []));
|
|
429
|
-
return source
|
|
430
|
-
.filter((row) => row && typeof row === 'object')
|
|
431
|
-
.map((row) => ({
|
|
432
|
-
tag: clean(row.tag),
|
|
433
|
-
sessionId: clean(row.sessionId),
|
|
434
|
-
role: clean(row.role) || null,
|
|
435
|
-
provider: clean(row.provider) || null,
|
|
436
|
-
model: clean(row.model) || null,
|
|
437
|
-
preset: clean(row.preset) || null,
|
|
438
|
-
effort: clean(row.effort) || null,
|
|
439
|
-
fast: row.fast === true ? true : (row.fast === false ? false : null),
|
|
440
|
-
status: clean(row.status) || 'idle',
|
|
441
|
-
stage: clean(row.stage) || clean(row.status) || 'idle',
|
|
442
|
-
createdAt: clean(row.createdAt) || null,
|
|
443
|
-
updatedAt: clean(row.updatedAt) || null,
|
|
444
|
-
lastUsedAt: clean(row.lastUsedAt) || null,
|
|
445
|
-
finishedAt: clean(row.finishedAt) || null,
|
|
446
|
-
clientHostPid: positiveInt(row.clientHostPid),
|
|
447
|
-
cwd: clean(row.cwd) || null,
|
|
448
|
-
task_id: clean(row.task_id || row.taskId) || null,
|
|
449
|
-
error: clean(row.error) || null,
|
|
450
|
-
permission: clean(row.permission) || null,
|
|
451
|
-
toolPermission: clean(row.toolPermission) || null,
|
|
452
|
-
messages: positiveInt(row.messages) || 0,
|
|
453
|
-
tools: positiveInt(row.tools) || 0,
|
|
454
|
-
}))
|
|
455
|
-
.filter(keepWorkerRow);
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
function readWorkerRows(context = {}) {
|
|
459
|
-
const file = workerIndexPath();
|
|
460
|
-
if (!file || !existsSync(file)) return [];
|
|
461
|
-
try {
|
|
462
|
-
const rows = normalizeWorkerRows(JSON.parse(readFileSync(file, 'utf8')));
|
|
463
|
-
return rows.filter((row) => rowMatchesContext(row, context));
|
|
464
|
-
} catch {
|
|
465
|
-
return [];
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
function writeWorkerRows(mutator) {
|
|
470
|
-
const file = workerIndexPath();
|
|
471
|
-
if (!file || typeof mutator !== 'function') return null;
|
|
472
|
-
try {
|
|
473
|
-
return updateJsonAtomicSync(file, (cur) => {
|
|
474
|
-
const byKey = new Map();
|
|
475
|
-
for (const row of normalizeWorkerRows(cur)) {
|
|
476
|
-
const key = workerRowKey(row);
|
|
477
|
-
if (key) byKey.set(key, row);
|
|
478
|
-
}
|
|
479
|
-
mutator(byKey);
|
|
480
|
-
const workers = {};
|
|
481
|
-
for (const row of [...byKey.values()].filter(keepWorkerRow)) {
|
|
482
|
-
const key = workerRowKey(row);
|
|
483
|
-
if (key) workers[key] = row;
|
|
484
|
-
}
|
|
485
|
-
return { version: 1, updatedAt: new Date().toISOString(), workers };
|
|
486
|
-
}, { lock: true });
|
|
487
|
-
} catch {
|
|
488
|
-
return null;
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
function workerRowFromSession(session, fallbackTag = '', extra = {}) {
|
|
493
|
-
const tag = clean(session?.bridgeTag) || clean(fallbackTag) || clean(extra.tag);
|
|
494
|
-
const sessionId = clean(session?.id || extra.sessionId);
|
|
495
|
-
if (!tag || !sessionId) return null;
|
|
496
|
-
const runtime = mgr.getSessionRuntime?.(sessionId);
|
|
497
|
-
const status = clean(extra.status) || (session?.closed === true ? 'closed' : clean(session?.status) || 'idle');
|
|
498
|
-
const stage = clean(extra.stage) || clean(runtime?.stage) || status;
|
|
499
|
-
const nowIso = new Date().toISOString();
|
|
500
|
-
return {
|
|
501
|
-
tag,
|
|
502
|
-
sessionId,
|
|
503
|
-
role: clean(extra.role) || clean(session?.role) || null,
|
|
504
|
-
provider: clean(extra.provider) || clean(session?.provider) || null,
|
|
505
|
-
model: clean(extra.model) || clean(session?.model) || null,
|
|
506
|
-
preset: clean(extra.preset) || clean(session?.presetName) || null,
|
|
507
|
-
effort: clean(extra.effort) || clean(session?.effort) || null,
|
|
508
|
-
fast: extra.fast === true || extra.fast === false ? extra.fast : (session?.fast === true ? true : null),
|
|
509
|
-
status,
|
|
510
|
-
stage,
|
|
511
|
-
createdAt: clean(session?.createdAt) || clean(extra.createdAt) || nowIso,
|
|
512
|
-
updatedAt: clean(extra.updatedAt) || nowIso,
|
|
513
|
-
lastUsedAt: clean(session?.lastUsedAt) || null,
|
|
514
|
-
finishedAt: clean(extra.finishedAt) || null,
|
|
515
|
-
clientHostPid: positiveInt(extra.clientHostPid) || positiveInt(session?.clientHostPid),
|
|
516
|
-
cwd: clean(session?.cwd) || clean(extra.cwd) || null,
|
|
517
|
-
task_id: clean(extra.task_id || extra.taskId) || null,
|
|
518
|
-
error: clean(extra.error) || null,
|
|
519
|
-
permission: clean(session?.permission) || null,
|
|
520
|
-
toolPermission: clean(session?.toolPermission) || null,
|
|
521
|
-
messages: Array.isArray(session?.messages) ? session.messages.length : 0,
|
|
522
|
-
tools: Array.isArray(session?.tools) ? session.tools.length : 0,
|
|
523
|
-
};
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
function workerRowToSession(row = {}) {
|
|
527
|
-
return {
|
|
528
|
-
id: row.sessionId,
|
|
529
|
-
bridgeTag: row.tag,
|
|
530
|
-
role: row.role || null,
|
|
531
|
-
provider: row.provider || null,
|
|
532
|
-
model: row.model || null,
|
|
533
|
-
presetName: row.preset || null,
|
|
534
|
-
effort: row.effort || null,
|
|
535
|
-
fast: row.fast === true,
|
|
536
|
-
status: row.status || 'idle',
|
|
537
|
-
stage: row.stage || row.status || 'idle',
|
|
538
|
-
createdAt: row.createdAt || null,
|
|
539
|
-
updatedAt: row.updatedAt || null,
|
|
540
|
-
lastUsedAt: row.lastUsedAt || null,
|
|
541
|
-
clientHostPid: row.clientHostPid || null,
|
|
542
|
-
cwd: row.cwd || null,
|
|
543
|
-
permission: row.permission || null,
|
|
544
|
-
toolPermission: row.toolPermission || null,
|
|
545
|
-
messageCount: Math.max(0, Number(row.messages || 0)),
|
|
546
|
-
toolCount: Math.max(0, Number(row.tools || 0)),
|
|
547
|
-
};
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
function upsertWorkerRow(row) {
|
|
551
|
-
const normalized = normalizeWorkerRows({ workers: [row] })[0];
|
|
552
|
-
if (!normalized) return false;
|
|
553
|
-
tags.set(normalized.tag, normalized.sessionId);
|
|
554
|
-
if (normalized.role) tagRoles.set(normalized.tag, normalized.role);
|
|
555
|
-
if (normalized.cwd) tagCwds.set(normalized.tag, normalized.cwd);
|
|
556
|
-
writeWorkerRows((byKey) => {
|
|
557
|
-
const key = workerRowKey(normalized);
|
|
558
|
-
const prev = byKey.get(key) || {};
|
|
559
|
-
const merged = { ...prev, ...normalized };
|
|
560
|
-
for (const field of ['role', 'provider', 'model', 'preset', 'effort', 'fast', 'clientHostPid', 'cwd', 'task_id', 'permission', 'toolPermission']) {
|
|
561
|
-
if ((merged[field] === null || merged[field] === '') && prev[field] != null && prev[field] !== '') {
|
|
562
|
-
merged[field] = prev[field];
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
byKey.set(key, {
|
|
566
|
-
...merged,
|
|
567
|
-
createdAt: normalized.createdAt || prev.createdAt || new Date().toISOString(),
|
|
568
|
-
updatedAt: normalized.updatedAt || new Date().toISOString(),
|
|
569
|
-
});
|
|
570
|
-
});
|
|
571
|
-
return true;
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
function upsertWorkerSession(session, fallbackTag = '', extra = {}) {
|
|
575
|
-
return upsertWorkerRow(workerRowFromSession(session, fallbackTag, extra));
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
function removeWorkerRow({ tag = '', sessionId = '' } = {}) {
|
|
579
|
-
const targetTag = clean(tag);
|
|
580
|
-
const targetSessionId = clean(sessionId);
|
|
581
|
-
writeWorkerRows((byKey) => {
|
|
582
|
-
for (const [key, row] of [...byKey.entries()]) {
|
|
583
|
-
if ((targetSessionId && row.sessionId === targetSessionId) || (targetTag && row.tag === targetTag)) {
|
|
584
|
-
byKey.delete(key);
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
});
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
function refreshTagsFromIndex(context = {}) {
|
|
591
|
-
const rows = readWorkerRows(context);
|
|
592
|
-
for (const row of rows) {
|
|
593
|
-
if (!row.tag || !row.sessionId) continue;
|
|
594
|
-
tags.set(row.tag, row.sessionId);
|
|
595
|
-
if (row.role) tagRoles.set(row.tag, row.role);
|
|
596
|
-
if (row.cwd) tagCwds.set(row.tag, row.cwd);
|
|
597
|
-
}
|
|
598
|
-
return rows;
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
function wantsSessionScan(args = {}) {
|
|
602
|
-
return args.recover === true || args.scanSessions === true || args.scan_sessions === true;
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
function resolveTag(target, context = {}, options = {}) {
|
|
606
|
-
const scanSessions = options.scanSessions === true;
|
|
607
|
-
refreshTagsFromSessions({ scanSessions, context });
|
|
608
|
-
const value = clean(target);
|
|
609
|
-
if (!value) return null;
|
|
610
|
-
if (value.startsWith('sess_')) {
|
|
611
|
-
const session = getLiveSession(value);
|
|
612
|
-
if (session && sessionMatchesContext(session, context)) return value;
|
|
613
|
-
const row = readWorkerRows(context).find((item) => item.sessionId === value);
|
|
614
|
-
return row ? value : null;
|
|
615
|
-
}
|
|
616
|
-
const matches = bridgeSessionEntries({ scanSessions, context })
|
|
617
|
-
.filter((entry) => entry.tag === value);
|
|
618
|
-
if (matches.length === 1) return matches[0].session.id;
|
|
619
|
-
if (matches.length > 1) {
|
|
620
|
-
throw new Error(`bridge: tag "${value}" is ambiguous across terminals; use sessionId`);
|
|
621
|
-
}
|
|
622
|
-
const sessionId = tags.get(value) || null;
|
|
623
|
-
const session = getLiveSession(sessionId);
|
|
624
|
-
return session && sessionMatchesContext(session, context) ? sessionId : null;
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
function getLiveSession(sessionId) {
|
|
628
|
-
if (!sessionId) return null;
|
|
629
|
-
const session = mgr.getSession(sessionId);
|
|
630
|
-
return session && session.closed !== true ? session : null;
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
function tagForSession(sessionId) {
|
|
634
|
-
const session = getLiveSession(sessionId);
|
|
635
|
-
const persistedTag = clean(session?.bridgeTag);
|
|
636
|
-
if (persistedTag) return persistedTag;
|
|
637
|
-
for (const [tag, sid] of tags.entries()) {
|
|
638
|
-
if (sid === sessionId) return tag;
|
|
639
|
-
}
|
|
640
|
-
return null;
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
function bridgeSessionEntries({ scanSessions = false, context = {} } = {}) {
|
|
644
|
-
const rows = [];
|
|
645
|
-
const seen = new Set();
|
|
646
|
-
const add = (session, fallbackTag = '') => {
|
|
647
|
-
const tag = clean(session?.bridgeTag) || clean(fallbackTag);
|
|
648
|
-
if (!tag || !session?.id || session.closed === true) return;
|
|
649
|
-
if (!sessionMatchesContext(session, context)) return;
|
|
650
|
-
if (seen.has(session.id)) return;
|
|
651
|
-
seen.add(session.id);
|
|
652
|
-
rows.push({ tag, session });
|
|
653
|
-
};
|
|
654
|
-
const addIndexRow = (row) => {
|
|
655
|
-
const tag = clean(row?.tag);
|
|
656
|
-
const sessionId = clean(row?.sessionId);
|
|
657
|
-
if (!tag || !sessionId || !rowMatchesContext(row, context)) return;
|
|
658
|
-
if (seen.has(sessionId)) return;
|
|
659
|
-
seen.add(sessionId);
|
|
660
|
-
rows.push({ tag, session: workerRowToSession(row), indexRow: row });
|
|
661
|
-
};
|
|
662
|
-
for (const row of readWorkerRows(context)) addIndexRow(row);
|
|
663
|
-
if (scanSessions) {
|
|
664
|
-
for (const session of mgr.listSessions({ includeClosed: false }) || []) {
|
|
665
|
-
add(session, session?.bridgeTag);
|
|
666
|
-
if (clean(session?.bridgeTag)) upsertWorkerSession(session, session.bridgeTag);
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
for (const [tag, sessionId] of tags.entries()) {
|
|
670
|
-
add(getLiveSession(sessionId), tag);
|
|
671
|
-
}
|
|
672
|
-
return rows;
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
function nextTag(role, context = {}) {
|
|
676
|
-
refreshTagsFromSessions({ context });
|
|
677
|
-
let tag;
|
|
678
|
-
do {
|
|
679
|
-
tag = `${clean(role) || 'agent'}${++tagSeq}`;
|
|
680
|
-
} while (resolveTag(tag, context));
|
|
681
|
-
return tag;
|
|
682
|
-
}
|
|
683
|
-
|
|
684
|
-
function refreshTagsFromSessions({ scanSessions = false, context = {} } = {}) {
|
|
685
|
-
const indexedRows = refreshTagsFromIndex(context);
|
|
686
|
-
const indexedKeys = new Set(indexedRows.map((row) => `${row.tag}\0${row.sessionId}`));
|
|
687
|
-
for (const [tag, sessionId] of [...tags.entries()]) {
|
|
688
|
-
if (indexedKeys.has(`${tag}\0${sessionId}`)) continue;
|
|
689
|
-
const session = getLiveSession(sessionId);
|
|
690
|
-
if (!session || session.closed) tags.delete(tag);
|
|
691
|
-
}
|
|
692
|
-
if (!scanSessions) return;
|
|
693
|
-
for (const session of mgr.listSessions({ includeClosed: false }) || []) {
|
|
694
|
-
const tag = clean(session?.bridgeTag);
|
|
695
|
-
if (!tag || tags.has(tag)) continue;
|
|
696
|
-
if (!sessionMatchesContext(session, context)) continue;
|
|
697
|
-
tags.set(tag, session.id);
|
|
698
|
-
if (session.role) tagRoles.set(tag, session.role);
|
|
699
|
-
if (session.cwd) tagCwds.set(tag, session.cwd);
|
|
700
|
-
upsertWorkerSession(session, tag);
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
function bindTag(tag, session, extra = {}) {
|
|
705
|
-
if (!tag || !session?.id) return;
|
|
706
|
-
tags.set(tag, session.id);
|
|
707
|
-
if (session.role) tagRoles.set(tag, session.role);
|
|
708
|
-
if (session.cwd) tagCwds.set(tag, session.cwd);
|
|
709
|
-
upsertWorkerSession(session, tag, extra);
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
function forgetTag(tag) {
|
|
713
|
-
if (!tag) return;
|
|
714
|
-
const sessionId = tags.get(tag) || '';
|
|
715
|
-
tags.delete(tag);
|
|
716
|
-
tagRoles.delete(tag);
|
|
717
|
-
tagCwds.delete(tag);
|
|
718
|
-
removeWorkerRow({ tag, sessionId });
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
function cancelReap(sessionId) {
|
|
722
|
-
const handle = reapTimers.get(sessionId);
|
|
723
|
-
if (!handle) return false;
|
|
724
|
-
clearTimeout(handle);
|
|
725
|
-
reapTimers.delete(sessionId);
|
|
726
|
-
return true;
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
function scheduleReap(sessionId) {
|
|
730
|
-
if (!sessionId) return;
|
|
731
|
-
cancelReap(sessionId);
|
|
732
|
-
const handle = setTimeout(() => {
|
|
733
|
-
reapTimers.delete(sessionId);
|
|
734
|
-
try { mgr.hideSessionFromList?.(sessionId); } catch {}
|
|
735
|
-
const tag = tagForSession(sessionId);
|
|
736
|
-
if (tag) forgetTag(tag);
|
|
737
|
-
removeWorkerRow({ tag, sessionId });
|
|
738
|
-
clearBridgeStatuslineRoute(sessionId);
|
|
739
|
-
try { mgr.closeSession(sessionId, 'terminal-reap'); } catch {}
|
|
740
|
-
}, TERMINAL_REAP_MS);
|
|
741
|
-
handle.unref?.();
|
|
742
|
-
reapTimers.set(sessionId, handle);
|
|
743
|
-
}
|
|
744
|
-
|
|
745
|
-
function isSessionBusy(sessionId) {
|
|
746
|
-
const runtime = mgr.getSessionRuntime?.(sessionId);
|
|
747
|
-
if (runtime?.controller?.signal && !runtime.controller.signal.aborted) return true;
|
|
748
|
-
if (runtime?.stage) return ACTIVE_STAGES.has(runtime.stage);
|
|
749
|
-
const session = getLiveSession(sessionId);
|
|
750
|
-
return ACTIVE_STAGES.has(session?.status || '');
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
function pruneJobs({ force = false } = {}) {
|
|
754
|
-
const now = Date.now();
|
|
755
|
-
for (const [jobId, job] of [...jobs.entries()]) {
|
|
756
|
-
if (job.status === 'running' && !force) continue;
|
|
757
|
-
const finishedAt = job.finishedAt ? Date.parse(job.finishedAt) : 0;
|
|
758
|
-
if (force || (finishedAt > 0 && now - finishedAt > FINISHED_JOB_TTL_MS)) {
|
|
759
|
-
jobs.delete(jobId);
|
|
760
|
-
}
|
|
761
|
-
}
|
|
762
|
-
if (jobs.size <= MAX_JOBS) return;
|
|
763
|
-
const removable = [...jobs.values()]
|
|
764
|
-
.filter((job) => job.status !== 'running')
|
|
765
|
-
.sort((a, b) => Date.parse(a.finishedAt || a.startedAt || 0) - Date.parse(b.finishedAt || b.startedAt || 0));
|
|
766
|
-
while (jobs.size > MAX_JOBS && removable.length > 0) {
|
|
767
|
-
const job = removable.shift();
|
|
768
|
-
jobs.delete(job.jobId);
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
async function ensureProvider(config, provider) {
|
|
773
|
-
const providers = { ...(config.providers || {}) };
|
|
774
|
-
providers[provider] = { ...(providers[provider] || {}), enabled: true };
|
|
775
|
-
await reg.initProviders(providers);
|
|
776
|
-
}
|
|
777
|
-
|
|
778
|
-
function resolvePreset(config, args, roleCfg) {
|
|
779
|
-
if (args.provider && args.model) {
|
|
780
|
-
return {
|
|
781
|
-
presetName: args.preset || '__direct__',
|
|
782
|
-
preset: {
|
|
783
|
-
id: '__direct__',
|
|
784
|
-
name: '__DIRECT__',
|
|
785
|
-
type: 'bridge',
|
|
786
|
-
provider: clean(args.provider),
|
|
787
|
-
model: clean(args.model),
|
|
788
|
-
effort: clean(args.effort) || undefined,
|
|
789
|
-
fast: args.fast === true,
|
|
790
|
-
tools: 'full',
|
|
791
|
-
},
|
|
792
|
-
};
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
const agentName = normalizeAgentName(args.agent || args.role);
|
|
796
|
-
const agentRoute = !clean(args.preset)
|
|
797
|
-
? (normalizeAgentRoute(config?.agents?.[agentName])
|
|
798
|
-
|| (agentName === 'maintainer' ? normalizeAgentRoute(config?.agents?.maintenance) : null))
|
|
799
|
-
: null;
|
|
800
|
-
if (agentRoute) {
|
|
801
|
-
return {
|
|
802
|
-
presetName: agentPresetName(agentName),
|
|
803
|
-
preset: {
|
|
804
|
-
id: `agent-${agentName}`,
|
|
805
|
-
name: agentPresetName(agentName),
|
|
806
|
-
type: 'bridge',
|
|
807
|
-
provider: agentRoute.provider,
|
|
808
|
-
model: agentRoute.model,
|
|
809
|
-
effort: agentRoute.effort,
|
|
810
|
-
fast: agentRoute.fast === true,
|
|
811
|
-
tools: 'full',
|
|
812
|
-
},
|
|
813
|
-
};
|
|
814
|
-
}
|
|
815
|
-
|
|
816
|
-
const presetName = clean(args.preset) || roleCfg?.preset || DEFAULT_AGENT_PRESETS[agentName];
|
|
817
|
-
if (!presetName) throw new Error(`bridge: agent "${agentName}" has no model assignment`);
|
|
818
|
-
const preset = findPreset(config, presetName) || synthesizePreset(config, presetName);
|
|
819
|
-
if (!preset) throw new Error(`bridge: preset "${presetName}" not found`);
|
|
820
|
-
return { presetName, preset };
|
|
821
|
-
}
|
|
822
|
-
|
|
823
|
-
function list({ scanSessions = false, context = {} } = {}) {
|
|
824
|
-
refreshTagsFromSessions({ scanSessions, context });
|
|
825
|
-
const now = Date.now();
|
|
826
|
-
const rows = [];
|
|
827
|
-
for (const { tag, session } of bridgeSessionEntries({ scanSessions, context })) {
|
|
828
|
-
const sessionId = session.id;
|
|
829
|
-
const runtime = mgr.getSessionRuntime?.(sessionId);
|
|
830
|
-
const status = session.closed === true ? 'closed' : (session.status || 'idle');
|
|
831
|
-
const stage = session.stage || (status === 'idle' || status === 'error' || status === 'closed'
|
|
832
|
-
? status
|
|
833
|
-
: (runtime?.stage || status));
|
|
834
|
-
rows.push({
|
|
835
|
-
tag,
|
|
836
|
-
sessionId,
|
|
837
|
-
role: session.role || null,
|
|
838
|
-
provider: session.provider,
|
|
839
|
-
model: session.model,
|
|
840
|
-
preset: session.presetName || null,
|
|
841
|
-
effort: session.effort || null,
|
|
842
|
-
fast: session.fast === true,
|
|
843
|
-
status,
|
|
844
|
-
stage,
|
|
845
|
-
createdAt: session.createdAt || null,
|
|
846
|
-
updatedAt: session.updatedAt || null,
|
|
847
|
-
lastUsedAt: session.lastUsedAt || null,
|
|
848
|
-
clientHostPid: session.clientHostPid || null,
|
|
849
|
-
lastStreamDeltaAt: runtime?.lastStreamDeltaAt ? new Date(runtime.lastStreamDeltaAt).toISOString() : null,
|
|
850
|
-
staleSeconds: runtime?.lastStreamDeltaAt ? Math.floor((now - runtime.lastStreamDeltaAt) / 1000) : null,
|
|
851
|
-
windowTokens: Number(session.lastContextTokens ?? session.lastInputTokens) || 0,
|
|
852
|
-
windowCap: Number(session.contextWindow) || null,
|
|
853
|
-
permission: session.permission || null,
|
|
854
|
-
toolPermission: session.toolPermission || null,
|
|
855
|
-
messages: Array.isArray(session.messages) ? session.messages.length : Math.max(0, Number(session.messageCount || 0)),
|
|
856
|
-
tools: Array.isArray(session.tools) ? session.tools.length : Math.max(0, Number(session.toolCount || 0)),
|
|
857
|
-
});
|
|
858
|
-
}
|
|
859
|
-
return rows;
|
|
860
|
-
}
|
|
861
|
-
|
|
862
|
-
function jobWorkerSnapshot(sessionId) {
|
|
863
|
-
if (!sessionId) return null;
|
|
864
|
-
const session = mgr.getSession(sessionId);
|
|
865
|
-
if (!session) return null;
|
|
866
|
-
const runtime = mgr.getSessionRuntime?.(sessionId);
|
|
867
|
-
const status = session.closed === true ? 'closed' : (session.status || 'idle');
|
|
868
|
-
return {
|
|
869
|
-
workerStatus: status,
|
|
870
|
-
stage: runtime?.stage || status,
|
|
871
|
-
clientHostPid: session.clientHostPid || null,
|
|
872
|
-
lastStreamDeltaAt: runtime?.lastStreamDeltaAt ? new Date(runtime.lastStreamDeltaAt).toISOString() : null,
|
|
873
|
-
};
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
function listJobs(context = {}) {
|
|
877
|
-
const wantedPid = terminalPidForContext(context);
|
|
878
|
-
const rows = listBackgroundTasks({ surface: 'bridge', context }).map((task) => ({
|
|
879
|
-
task_id: task.task_id,
|
|
880
|
-
type: task.operation,
|
|
881
|
-
status: task.status,
|
|
882
|
-
tag: task.tag || null,
|
|
883
|
-
sessionId: task.sessionId || null,
|
|
884
|
-
role: task.role || null,
|
|
885
|
-
preset: task.preset || null,
|
|
886
|
-
provider: task.provider || null,
|
|
887
|
-
model: task.model || null,
|
|
888
|
-
effort: task.effort || null,
|
|
889
|
-
fast: task.fast === true || task.fast === false ? task.fast : null,
|
|
890
|
-
maxLoopIterations: task.maxLoopIterations || null,
|
|
891
|
-
idleTimeoutMs: task.idleTimeoutMs || null,
|
|
892
|
-
firstResponseTimeoutMs: task.firstResponseTimeoutMs || null,
|
|
893
|
-
startedAt: task.startedAt,
|
|
894
|
-
finishedAt: task.finishedAt || null,
|
|
895
|
-
error: task.error || null,
|
|
896
|
-
...jobWorkerSnapshot(task.sessionId),
|
|
897
|
-
}));
|
|
898
|
-
return wantedPid ? rows.filter((row) => positiveInt(row.clientHostPid) === wantedPid) : rows;
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
function getJob(args, context = {}) {
|
|
902
|
-
const taskId = taskIdFromArgs(args);
|
|
903
|
-
if (!taskId) throw new Error('bridge read/status: task_id is required');
|
|
904
|
-
const task = getBackgroundTask(taskId, { surface: 'bridge', context });
|
|
905
|
-
if (!task) throw new Error(`bridge read/status: task "${taskId}" not found`);
|
|
906
|
-
return task;
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
function renderJob(job, includeResult = false) {
|
|
910
|
-
const meta = job.meta || {};
|
|
911
|
-
return {
|
|
912
|
-
task_id: job.taskId,
|
|
913
|
-
type: job.operation,
|
|
914
|
-
status: job.status,
|
|
915
|
-
tag: meta.tag || null,
|
|
916
|
-
sessionId: meta.sessionId || null,
|
|
917
|
-
role: meta.role || null,
|
|
918
|
-
preset: meta.preset || null,
|
|
919
|
-
provider: meta.provider || null,
|
|
920
|
-
model: meta.model || null,
|
|
921
|
-
effort: meta.effort || null,
|
|
922
|
-
fast: meta.fast === true || meta.fast === false ? meta.fast : null,
|
|
923
|
-
maxLoopIterations: meta.maxLoopIterations || null,
|
|
924
|
-
idleTimeoutMs: meta.idleTimeoutMs || null,
|
|
925
|
-
firstResponseTimeoutMs: meta.firstResponseTimeoutMs || null,
|
|
926
|
-
startedAt: job.startedAt,
|
|
927
|
-
finishedAt: job.finishedAt || null,
|
|
928
|
-
error: job.error || null,
|
|
929
|
-
...jobWorkerSnapshot(meta.sessionId),
|
|
930
|
-
...(includeResult && job.result !== undefined ? { result: job.result } : {}),
|
|
931
|
-
};
|
|
932
|
-
}
|
|
933
|
-
|
|
934
|
-
function preparedSpawnMeta(prepared, extras = {}) {
|
|
935
|
-
return {
|
|
936
|
-
...(extras || {}),
|
|
937
|
-
tag: prepared.tag,
|
|
938
|
-
sessionId: prepared.session.id,
|
|
939
|
-
role: prepared.role,
|
|
940
|
-
preset: presetKey(prepared.preset) || prepared.presetName,
|
|
941
|
-
provider: prepared.preset.provider,
|
|
942
|
-
model: prepared.preset.model,
|
|
943
|
-
effort: prepared.preset.effort || null,
|
|
944
|
-
fast: prepared.preset.fast === true,
|
|
945
|
-
maxLoopIterations: prepared.maxLoopIterations || null,
|
|
946
|
-
idleTimeoutMs: prepared.idleTimeoutMs || null,
|
|
947
|
-
firstResponseTimeoutMs: prepared.firstResponseTimeoutMs || null,
|
|
948
|
-
};
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
function pendingSpawnMeta(args = {}, extras = {}) {
|
|
952
|
-
const role = normalizeAgentName(args.agent || args.role);
|
|
953
|
-
return {
|
|
954
|
-
...(extras || {}),
|
|
955
|
-
tag: clean(args.tag) || null,
|
|
956
|
-
sessionId: null,
|
|
957
|
-
role: role || null,
|
|
958
|
-
preset: clean(args.preset) || null,
|
|
959
|
-
provider: clean(args.provider) || null,
|
|
960
|
-
model: clean(args.model) || null,
|
|
961
|
-
effort: clean(args.effort) || null,
|
|
962
|
-
fast: args.fast === true ? true : null,
|
|
963
|
-
};
|
|
964
|
-
}
|
|
965
|
-
|
|
966
|
-
function mergeJobMeta(job, meta = {}) {
|
|
967
|
-
if (!job || !meta || typeof meta !== 'object') return;
|
|
968
|
-
const next = { ...(job.meta || {}), ...meta };
|
|
969
|
-
job.meta = next;
|
|
970
|
-
if (job.input && typeof job.input === 'object') {
|
|
971
|
-
job.input = {
|
|
972
|
-
...job.input,
|
|
973
|
-
tag: next.tag || job.input.tag || null,
|
|
974
|
-
sessionId: next.sessionId || job.input.sessionId || null,
|
|
975
|
-
role: next.role || job.input.role || null,
|
|
976
|
-
};
|
|
977
|
-
}
|
|
978
|
-
job.label = next.tag || next.sessionId || job.label;
|
|
979
|
-
}
|
|
980
|
-
|
|
981
|
-
function closePreparedSpawn(prepared, reason = 'bridge-task-cancel') {
|
|
982
|
-
if (!prepared?.session?.id) return;
|
|
983
|
-
try { mgr.closeSession(prepared.session.id, reason); } catch {}
|
|
984
|
-
try { clearBridgeStatuslineRoute(prepared.session.id); } catch {}
|
|
985
|
-
if (prepared.tag) forgetTag(prepared.tag);
|
|
986
|
-
removeWorkerRow({ tag: prepared.tag, sessionId: prepared.session.id });
|
|
987
|
-
}
|
|
988
|
-
|
|
989
|
-
function startJob(type, meta, run, notifyContext = null) {
|
|
990
|
-
const clientHostPid = terminalPidForContext(notifyContext);
|
|
991
|
-
const jobMeta = {
|
|
992
|
-
...(meta || {}),
|
|
993
|
-
...(clientHostPid ? { clientHostPid } : {}),
|
|
994
|
-
};
|
|
995
|
-
let task;
|
|
996
|
-
task = startBackgroundTask({
|
|
997
|
-
surface: 'bridge',
|
|
998
|
-
operation: type,
|
|
999
|
-
label: jobMeta?.tag || jobMeta?.sessionId || type,
|
|
1000
|
-
input: { type, tag: jobMeta?.tag || null, sessionId: jobMeta?.sessionId || null, role: jobMeta?.role || null },
|
|
1001
|
-
context: notifyContext,
|
|
1002
|
-
meta: jobMeta,
|
|
1003
|
-
resultType: 'bridge_task_result',
|
|
1004
|
-
renderResult: (result) => renderResult(result),
|
|
1005
|
-
cancel: () => {
|
|
1006
|
-
const currentMeta = task?.meta || jobMeta;
|
|
1007
|
-
if (currentMeta?.sessionId) {
|
|
1008
|
-
try { mgr.closeSession(currentMeta.sessionId, 'bridge-task-cancel'); } catch {}
|
|
1009
|
-
}
|
|
1010
|
-
},
|
|
1011
|
-
run: async () => {
|
|
1012
|
-
// Yield one macrotask before doing bridge work. startBackgroundTask uses
|
|
1013
|
-
// a Promise microtask, which otherwise begins CPU-heavy spawn prep
|
|
1014
|
-
// before the TUI receives/render the "running" result.
|
|
1015
|
-
await new Promise((resolve) => setImmediate(resolve));
|
|
1016
|
-
if (task?.status === 'cancelled') return null;
|
|
1017
|
-
return await run(task);
|
|
1018
|
-
},
|
|
1019
|
-
});
|
|
1020
|
-
return task;
|
|
1021
|
-
}
|
|
1022
|
-
|
|
1023
|
-
function startDeferredSpawnJob(args, callerCwd, context, notifyContext, extras = {}) {
|
|
1024
|
-
return startJob('spawn', pendingSpawnMeta(args, extras), async (job) => {
|
|
1025
|
-
const prepared = await prepareSpawn(args, callerCwd, context);
|
|
1026
|
-
mergeJobMeta(job, preparedSpawnMeta(prepared, extras));
|
|
1027
|
-
upsertWorkerSession(prepared.session, prepared.tag, {
|
|
1028
|
-
...preparedSpawnMeta(prepared, extras),
|
|
1029
|
-
status: 'running',
|
|
1030
|
-
stage: 'running',
|
|
1031
|
-
task_id: job.taskId,
|
|
1032
|
-
startedAt: job.startedAt,
|
|
1033
|
-
});
|
|
1034
|
-
if (job?.status === 'cancelled') {
|
|
1035
|
-
closePreparedSpawn(prepared);
|
|
1036
|
-
return null;
|
|
1037
|
-
}
|
|
1038
|
-
return await runSpawn(prepared);
|
|
1039
|
-
}, notifyContext);
|
|
1040
|
-
}
|
|
1041
|
-
|
|
1042
|
-
function startProgressIdleWatchdog(sessionId, idleTimeoutMs, firstResponseTimeoutMs = DEFAULT_FIRST_RESPONSE_TIMEOUT_MS) {
|
|
1043
|
-
const staleMs = resolveWatchdogMs(idleTimeoutMs, DEFAULT_STALE_TIMEOUT_MS);
|
|
1044
|
-
const firstMs = resolveWatchdogMs(firstResponseTimeoutMs, DEFAULT_FIRST_RESPONSE_TIMEOUT_MS);
|
|
1045
|
-
if (!sessionId || (!staleMs && !firstMs)) return null;
|
|
1046
|
-
if (typeof mgr.getSessionProgressSnapshot !== 'function' && typeof mgr.getSessionLastProgressAt !== 'function') return null;
|
|
1047
|
-
if (typeof mgr.linkParentSignalToSession !== 'function') return null;
|
|
1048
|
-
const controller = new AbortController();
|
|
1049
|
-
try { mgr.linkParentSignalToSession(sessionId, controller.signal); } catch { return null; }
|
|
1050
|
-
const timer = setInterval(() => {
|
|
1051
|
-
const now = Date.now();
|
|
1052
|
-
const snapshot = typeof mgr.getSessionProgressSnapshot === 'function'
|
|
1053
|
-
? mgr.getSessionProgressSnapshot(sessionId)
|
|
1054
|
-
: null;
|
|
1055
|
-
if (snapshot) {
|
|
1056
|
-
if (snapshot.waitingForFirstActivity) {
|
|
1057
|
-
const startedAt = snapshot.modelRequestStartedAt || snapshot.askStartedAt;
|
|
1058
|
-
if (firstMs && startedAt && now - startedAt > firstMs) {
|
|
1059
|
-
try { controller.abort(new Error(`bridge first response stale (${firstMs}ms)`)); } catch {}
|
|
1060
|
-
}
|
|
1061
|
-
return;
|
|
1062
|
-
}
|
|
1063
|
-
const last = snapshot.lastProgressAt || snapshot.firstActivityAt;
|
|
1064
|
-
if (staleMs && last && now - last > staleMs) {
|
|
1065
|
-
try { controller.abort(new Error(`bridge task stale (${staleMs}ms without stream/tool progress)`)); } catch {}
|
|
1066
|
-
}
|
|
1067
|
-
return;
|
|
1068
|
-
}
|
|
1069
|
-
const last = mgr.getSessionLastProgressAt(sessionId);
|
|
1070
|
-
if (staleMs && last && now - last > staleMs) {
|
|
1071
|
-
try { controller.abort(new Error(`bridge task stale (${staleMs}ms without progress)`)); } catch {}
|
|
1072
|
-
}
|
|
1073
|
-
}, 1000);
|
|
1074
|
-
timer.unref?.();
|
|
1075
|
-
return {
|
|
1076
|
-
stop: () => {
|
|
1077
|
-
try { clearInterval(timer); } catch {}
|
|
1078
|
-
},
|
|
1079
|
-
};
|
|
1080
|
-
}
|
|
1081
|
-
|
|
1082
|
-
async function prepareSpawn(args, callerCwd = null, context = {}) {
|
|
1083
|
-
refreshTagsFromSessions({ context });
|
|
1084
|
-
const config = cfgMod.loadConfig();
|
|
1085
|
-
const roles = readRoles(dataDir);
|
|
1086
|
-
const role = normalizeAgentName(args.agent || args.role);
|
|
1087
|
-
if (!role) throw new Error('bridge spawn: agent is required');
|
|
1088
|
-
const roleCfg = roles.get(role);
|
|
1089
|
-
const { presetName, preset } = resolvePreset(config, args, roleCfg);
|
|
1090
|
-
await ensureProvider(config, preset.provider);
|
|
1091
|
-
|
|
1092
|
-
const tag = clean(args.tag) || nextTag(role, context);
|
|
1093
|
-
if (resolveTag(tag, context, { scanSessions: wantsSessionScan(args) })) throw new Error(`bridge spawn: tag "${tag}" already exists`);
|
|
1094
|
-
const baseCwd = resolve(callerCwd || defaultCwd || process.cwd());
|
|
1095
|
-
const workerCwd = clean(args.cwd) ? resolve(baseCwd, args.cwd) : baseCwd;
|
|
1096
|
-
const prompt = withCwdHeader(await resolvePrompt(args, workerCwd), workerCwd);
|
|
1097
|
-
const runtimeSpec = cfgMod.resolveRuntimeSpec(preset, { lane: 'bridge', agentId: tag });
|
|
1098
|
-
const maxLoopIterations = positiveInt(args.maxLoopIterations) || roleCfg?.maxLoopIterations || null;
|
|
1099
|
-
const idleTimeoutMs = resolveWatchdogMs(args.idleTimeoutMs, roleCfg?.idleTimeoutMs ?? DEFAULT_STALE_TIMEOUT_MS);
|
|
1100
|
-
const firstResponseTimeoutMs = resolveWatchdogMs(args.firstResponseTimeoutMs, roleCfg?.firstResponseTimeoutMs ?? DEFAULT_FIRST_RESPONSE_TIMEOUT_MS);
|
|
1101
|
-
const { session, effectiveCwd } = prepareBridgeSession({
|
|
1102
|
-
role,
|
|
1103
|
-
presetName,
|
|
1104
|
-
preset,
|
|
1105
|
-
runtimeSpec,
|
|
1106
|
-
owner: 'bridge',
|
|
1107
|
-
cwd: workerCwd,
|
|
1108
|
-
sourceType: 'cli',
|
|
1109
|
-
sourceName: role,
|
|
1110
|
-
clientHostPid: terminalPidForContext(context) || null,
|
|
1111
|
-
bridgeTag: tag,
|
|
1112
|
-
taskType: clean(args.taskType) || clean(args.typeHint) || undefined,
|
|
1113
|
-
maxLoopIterations: maxLoopIterations || undefined,
|
|
1114
|
-
permission: normalizePermission(roleCfg?.permission) || 'full',
|
|
1115
|
-
cacheKeyOverride: args.cacheKey || undefined,
|
|
1116
|
-
});
|
|
1117
|
-
// Lead sessions write a gateway-session route when created; bridge agents
|
|
1118
|
-
// are built through prepareBridgeSession(), so mirror that registration here
|
|
1119
|
-
// or the vendored L1/L2 statusline cannot resolve the agent route/model.
|
|
1120
|
-
writeBridgeStatuslineRoute(session.id, preset);
|
|
1121
|
-
bindTag(tag, session, {
|
|
1122
|
-
role,
|
|
1123
|
-
preset: presetKey(preset) || presetName,
|
|
1124
|
-
provider: preset.provider,
|
|
1125
|
-
model: preset.model,
|
|
1126
|
-
effort: preset.effort || null,
|
|
1127
|
-
fast: preset.fast === true,
|
|
1128
|
-
status: 'idle',
|
|
1129
|
-
stage: 'idle',
|
|
1130
|
-
});
|
|
1131
|
-
cancelReap(session.id);
|
|
1132
|
-
return { args, tag, session, role, preset, presetName, workerCwd: effectiveCwd || workerCwd, prompt, maxLoopIterations, idleTimeoutMs, firstResponseTimeoutMs };
|
|
1133
|
-
}
|
|
1134
|
-
|
|
1135
|
-
async function runSpawn(prepared) {
|
|
1136
|
-
const { args, tag, session, role, preset, presetName, workerCwd, prompt, idleTimeoutMs, firstResponseTimeoutMs } = prepared;
|
|
1137
|
-
const watchdog = startProgressIdleWatchdog(session.id, idleTimeoutMs, firstResponseTimeoutMs);
|
|
1138
|
-
let finalStatus = 'idle';
|
|
1139
|
-
upsertWorkerSession(session, tag, {
|
|
1140
|
-
role,
|
|
1141
|
-
preset: presetKey(preset) || presetName,
|
|
1142
|
-
provider: preset.provider,
|
|
1143
|
-
model: preset.model,
|
|
1144
|
-
effort: preset.effort || null,
|
|
1145
|
-
fast: preset.fast === true,
|
|
1146
|
-
status: 'running',
|
|
1147
|
-
stage: 'running',
|
|
1148
|
-
});
|
|
1149
|
-
try {
|
|
1150
|
-
const result = await mgr.askSession(session.id, prompt, args.context || null, null, workerCwd);
|
|
1151
|
-
const content = result?.content || '';
|
|
1152
|
-
return {
|
|
1153
|
-
tag,
|
|
1154
|
-
sessionId: session.id,
|
|
1155
|
-
role,
|
|
1156
|
-
preset: presetKey(preset) || presetName,
|
|
1157
|
-
provider: preset.provider,
|
|
1158
|
-
model: preset.model,
|
|
1159
|
-
effort: preset.effort || null,
|
|
1160
|
-
fast: preset.fast === true,
|
|
1161
|
-
content,
|
|
1162
|
-
};
|
|
1163
|
-
} catch (error) {
|
|
1164
|
-
finalStatus = 'error';
|
|
1165
|
-
throw error;
|
|
1166
|
-
} finally {
|
|
1167
|
-
watchdog?.stop?.();
|
|
1168
|
-
upsertWorkerSession(session, tag, {
|
|
1169
|
-
role,
|
|
1170
|
-
preset: presetKey(preset) || presetName,
|
|
1171
|
-
provider: preset.provider,
|
|
1172
|
-
model: preset.model,
|
|
1173
|
-
effort: preset.effort || null,
|
|
1174
|
-
fast: preset.fast === true,
|
|
1175
|
-
status: finalStatus,
|
|
1176
|
-
stage: finalStatus,
|
|
1177
|
-
finishedAt: new Date().toISOString(),
|
|
1178
|
-
});
|
|
1179
|
-
scheduleReap(session.id);
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
async function spawn(args) {
|
|
1184
|
-
return await runSpawn(await prepareSpawn(args));
|
|
1185
|
-
}
|
|
1186
|
-
|
|
1187
|
-
async function prepareSend(args, context = {}) {
|
|
1188
|
-
refreshTagsFromSessions({ scanSessions: wantsSessionScan(args), context });
|
|
1189
|
-
const target = clean(args.tag || args.sessionId);
|
|
1190
|
-
if (!target) throw new Error('bridge send: tag or sessionId is required');
|
|
1191
|
-
const sessionId = resolveTag(target, context, { scanSessions: wantsSessionScan(args) });
|
|
1192
|
-
if (!sessionId) throw new Error(`bridge send: target "${target}" not found`);
|
|
1193
|
-
const session = mgr.getSession(sessionId);
|
|
1194
|
-
if (!session || session.closed) throw new Error(`bridge send: session "${sessionId}" is closed`);
|
|
1195
|
-
cancelReap(sessionId);
|
|
1196
|
-
const prompt = await resolvePrompt(args, session.cwd || defaultCwd);
|
|
1197
|
-
return { args, session, sessionId, prompt };
|
|
1198
|
-
}
|
|
1199
|
-
|
|
1200
|
-
async function runSend(prepared) {
|
|
1201
|
-
const { args, session, sessionId, prompt } = prepared;
|
|
1202
|
-
const watchdog = startProgressIdleWatchdog(
|
|
1203
|
-
sessionId,
|
|
1204
|
-
resolveWatchdogMs(args.idleTimeoutMs, DEFAULT_STALE_TIMEOUT_MS),
|
|
1205
|
-
resolveWatchdogMs(args.firstResponseTimeoutMs, DEFAULT_FIRST_RESPONSE_TIMEOUT_MS),
|
|
1206
|
-
);
|
|
1207
|
-
const tag = tagForSession(sessionId);
|
|
1208
|
-
let finalStatus = 'idle';
|
|
1209
|
-
upsertWorkerSession(session, tag, { status: 'running', stage: 'running' });
|
|
1210
|
-
try {
|
|
1211
|
-
const result = await mgr.askSession(sessionId, prompt, args.context || null, null, session.cwd || defaultCwd);
|
|
1212
|
-
return {
|
|
1213
|
-
tag,
|
|
1214
|
-
sessionId,
|
|
1215
|
-
role: session.role || null,
|
|
1216
|
-
provider: session.provider,
|
|
1217
|
-
model: session.model,
|
|
1218
|
-
content: result?.content || '',
|
|
1219
|
-
};
|
|
1220
|
-
} catch (error) {
|
|
1221
|
-
finalStatus = 'error';
|
|
1222
|
-
throw error;
|
|
1223
|
-
} finally {
|
|
1224
|
-
watchdog?.stop?.();
|
|
1225
|
-
upsertWorkerSession(session, tag, {
|
|
1226
|
-
status: finalStatus,
|
|
1227
|
-
stage: finalStatus,
|
|
1228
|
-
finishedAt: new Date().toISOString(),
|
|
1229
|
-
});
|
|
1230
|
-
scheduleReap(sessionId);
|
|
1231
|
-
}
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
|
-
async function send(args) {
|
|
1235
|
-
return await runSend(await prepareSend(args));
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
function close(args, context = {}) {
|
|
1239
|
-
const scopedContext = bridgeScope(args, context);
|
|
1240
|
-
refreshTagsFromSessions({ scanSessions: wantsSessionScan(args), context: scopedContext });
|
|
1241
|
-
const taskId = taskIdFromArgs(args);
|
|
1242
|
-
const task = taskId ? getBackgroundTask(taskId, { surface: 'bridge', context }) : null;
|
|
1243
|
-
const taskMeta = task?.meta || {};
|
|
1244
|
-
const target = clean(args.tag || args.sessionId || taskMeta.sessionId);
|
|
1245
|
-
if (!target) {
|
|
1246
|
-
if (task?.taskId) {
|
|
1247
|
-
cancelBackgroundTask(task.taskId, 'cancelled by bridge close');
|
|
1248
|
-
return { closed: true, tag: taskMeta.tag || null, sessionId: null, task_id: task.taskId };
|
|
1249
|
-
}
|
|
1250
|
-
throw new Error('bridge close: tag or sessionId is required');
|
|
1251
|
-
}
|
|
1252
|
-
const sessionId = resolveTag(target, scopedContext, { scanSessions: wantsSessionScan(args) });
|
|
1253
|
-
if (!sessionId) {
|
|
1254
|
-
if (!target.startsWith('sess_') && tagRoles.has(target)) {
|
|
1255
|
-
forgetTag(target);
|
|
1256
|
-
if (task?.taskId) cancelBackgroundTask(task.taskId, 'cancelled by bridge close');
|
|
1257
|
-
return { closed: true, forgotten: true, tag: target, sessionId: null, task_id: task?.taskId || null };
|
|
1258
|
-
}
|
|
1259
|
-
throw new Error(`bridge close: target "${target}" not found`);
|
|
1260
|
-
}
|
|
1261
|
-
cancelReap(sessionId);
|
|
1262
|
-
const tag = tagForSession(sessionId);
|
|
1263
|
-
if (tag) forgetTag(tag);
|
|
1264
|
-
removeWorkerRow({ tag, sessionId });
|
|
1265
|
-
clearBridgeStatuslineRoute(sessionId);
|
|
1266
|
-
const ok = mgr.closeSession(sessionId, 'cli-bridge-close');
|
|
1267
|
-
if (task?.taskId) cancelBackgroundTask(task.taskId, 'cancelled by bridge close');
|
|
1268
|
-
return { closed: ok, tag, sessionId, task_id: task?.taskId || null };
|
|
1269
|
-
}
|
|
1270
|
-
|
|
1271
|
-
function cleanup(args = {}, context = {}) {
|
|
1272
|
-
const scopedContext = bridgeScope(args, context);
|
|
1273
|
-
const beforeTags = tags.size;
|
|
1274
|
-
refreshTagsFromSessions({ scanSessions: wantsSessionScan(args), context: scopedContext });
|
|
1275
|
-
const cleaned = cleanupBackgroundTasks({ surface: 'bridge', context: scopedContext, force: args.force === true });
|
|
1276
|
-
return {
|
|
1277
|
-
jobsRemoved: cleaned.removed,
|
|
1278
|
-
tagsRemoved: beforeTags - tags.size,
|
|
1279
|
-
jobs: listJobs(scopedContext).length,
|
|
1280
|
-
workers: list({ scanSessions: wantsSessionScan(args), context: scopedContext }).length,
|
|
1281
|
-
};
|
|
1282
|
-
}
|
|
1283
|
-
|
|
1284
|
-
function closeAll(reason = 'cli-bridge-close-all') {
|
|
1285
|
-
refreshTagsFromSessions({ scanSessions: false });
|
|
1286
|
-
const closed = [];
|
|
1287
|
-
const failed = [];
|
|
1288
|
-
for (const { tag, session } of bridgeSessionEntries({ scanSessions: false, context: {} })) {
|
|
1289
|
-
try {
|
|
1290
|
-
closed.push(close({ sessionId: session.id }));
|
|
1291
|
-
} catch (err) {
|
|
1292
|
-
failed.push({ tag, error: presentErrorText(err, { surface: 'bridge' }) });
|
|
1293
|
-
}
|
|
1294
|
-
}
|
|
1295
|
-
for (const task of listBackgroundTasks({ surface: 'bridge' })) {
|
|
1296
|
-
if (task?.status !== 'running') continue;
|
|
1297
|
-
cancelBackgroundTask(task.task_id, reason);
|
|
1298
|
-
closed.push({ closed: true, tag: task.tag || null, sessionId: task.sessionId || null, task_id: task.task_id });
|
|
1299
|
-
}
|
|
1300
|
-
for (const timer of reapTimers.values()) clearTimeout(timer);
|
|
1301
|
-
reapTimers.clear();
|
|
1302
|
-
writeWorkerRows((byKey) => byKey.clear());
|
|
1303
|
-
return { closed, failed };
|
|
1304
|
-
}
|
|
1305
|
-
|
|
1306
|
-
function coldRespawnArgs(args = {}, context = {}) {
|
|
1307
|
-
const target = clean(args.tag || args.sessionId);
|
|
1308
|
-
if (!target || target.startsWith('sess_') || resolveTag(target, context)) return null;
|
|
1309
|
-
const recoveredRole = clean(args.agent || args.role) || tagRoles.get(target);
|
|
1310
|
-
if (!recoveredRole) return null;
|
|
1311
|
-
return {
|
|
1312
|
-
...args,
|
|
1313
|
-
type: 'spawn',
|
|
1314
|
-
tag: target,
|
|
1315
|
-
agent: recoveredRole,
|
|
1316
|
-
role: recoveredRole,
|
|
1317
|
-
prompt: args.prompt ?? args.message,
|
|
1318
|
-
cwd: args.cwd ?? tagCwds.get(target) ?? undefined,
|
|
1319
|
-
respawned: true,
|
|
1320
|
-
};
|
|
1321
|
-
}
|
|
1322
|
-
|
|
1323
|
-
async function execute(args = {}, context = {}) {
|
|
1324
|
-
try {
|
|
1325
|
-
const type = clean(args.type) || 'spawn';
|
|
1326
|
-
const callerCwd = clean(context.cwd || context.callerCwd);
|
|
1327
|
-
const scopedContext = bridgeScope(args, context);
|
|
1328
|
-
const notifyContext = context;
|
|
1329
|
-
if (type === 'list') return renderResult({ bridgeMode: defaultMode, workers: list({ scanSessions: wantsSessionScan(args), context: scopedContext }), jobs: listJobs(scopedContext) });
|
|
1330
|
-
if (type === 'status') return renderResult(renderJob(getJob(args, scopedContext), false));
|
|
1331
|
-
if (type === 'read') return renderResult(renderJob(getJob(args, scopedContext), true));
|
|
1332
|
-
if (type === 'cleanup') return renderResult(cleanup(args, scopedContext));
|
|
1333
|
-
if (type === 'cancel') return renderResult(close(args, scopedContext));
|
|
1334
|
-
if (type === 'close') return renderResult(close(args, scopedContext));
|
|
1335
|
-
if (type === 'send') {
|
|
1336
|
-
const respawnArgs = coldRespawnArgs(args, scopedContext);
|
|
1337
|
-
if (respawnArgs) {
|
|
1338
|
-
if (modeFor(args, context) === 'async') {
|
|
1339
|
-
const job = startDeferredSpawnJob(respawnArgs, callerCwd, context, notifyContext, { respawned: true });
|
|
1340
|
-
return renderResult({ mode: 'async', respawned: true, ...renderJob(job, false) });
|
|
1341
|
-
}
|
|
1342
|
-
const prepared = await prepareSpawn(respawnArgs, callerCwd, context);
|
|
1343
|
-
return renderResult({ respawned: true, ...(await runSpawn(prepared)) });
|
|
1344
|
-
}
|
|
1345
|
-
const prepared = await prepareSend(args, scopedContext);
|
|
1346
|
-
if (isSessionBusy(prepared.sessionId) && typeof mgr.enqueuePendingMessage === 'function') {
|
|
1347
|
-
const queueDepth = mgr.enqueuePendingMessage(prepared.sessionId, prepared.prompt);
|
|
1348
|
-
return renderResult({
|
|
1349
|
-
queued: true,
|
|
1350
|
-
tag: tagForSession(prepared.sessionId),
|
|
1351
|
-
sessionId: prepared.sessionId,
|
|
1352
|
-
role: prepared.session.role || null,
|
|
1353
|
-
queueDepth,
|
|
1354
|
-
});
|
|
1355
|
-
}
|
|
1356
|
-
if (modeFor(args, context) === 'async') {
|
|
1357
|
-
const job = startJob('send', {
|
|
1358
|
-
tag: tagForSession(prepared.sessionId),
|
|
1359
|
-
sessionId: prepared.sessionId,
|
|
1360
|
-
role: prepared.session.role || null,
|
|
1361
|
-
provider: prepared.session.provider || null,
|
|
1362
|
-
model: prepared.session.model || null,
|
|
1363
|
-
preset: prepared.session.presetName || null,
|
|
1364
|
-
effort: prepared.session.effort || null,
|
|
1365
|
-
fast: prepared.session.fast === true,
|
|
1366
|
-
}, () => runSend(prepared), notifyContext);
|
|
1367
|
-
return renderResult({ mode: 'async', ...renderJob(job, false) });
|
|
1368
|
-
}
|
|
1369
|
-
return renderResult(await runSend(prepared));
|
|
1370
|
-
}
|
|
1371
|
-
if (type === 'spawn') {
|
|
1372
|
-
if (modeFor(args, context) === 'async') {
|
|
1373
|
-
const job = startDeferredSpawnJob(args, callerCwd, context, notifyContext);
|
|
1374
|
-
return renderResult({ mode: 'async', ...renderJob(job, false) });
|
|
1375
|
-
}
|
|
1376
|
-
const prepared = await prepareSpawn(args, callerCwd, context);
|
|
1377
|
-
return renderResult(await runSpawn(prepared));
|
|
1378
|
-
}
|
|
1379
|
-
throw new Error(`bridge: unknown type "${type}"`);
|
|
1380
|
-
} catch (err) {
|
|
1381
|
-
return `Error: ${presentErrorText(err, { surface: 'bridge' })}`;
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
|
|
1385
|
-
return {
|
|
1386
|
-
tools: [BRIDGE_TOOL],
|
|
1387
|
-
execute,
|
|
1388
|
-
getStatus: (context = {}) => {
|
|
1389
|
-
const scopedContext = bridgeScope({}, context);
|
|
1390
|
-
const pid = terminalPidForContext(scopedContext);
|
|
1391
|
-
return {
|
|
1392
|
-
bridgeMode: defaultMode,
|
|
1393
|
-
workers: list({ scanSessions: false, context: scopedContext }),
|
|
1394
|
-
jobs: listJobs(scopedContext),
|
|
1395
|
-
scope: pid ? { clientHostPid: pid } : { allTerminals: true },
|
|
1396
|
-
};
|
|
1397
|
-
},
|
|
1398
|
-
recoverWorkers: (context = {}) => {
|
|
1399
|
-
const scopedContext = bridgeScope({ recover: true }, context);
|
|
1400
|
-
refreshTagsFromSessions({ scanSessions: true, context: scopedContext });
|
|
1401
|
-
return list({ scanSessions: false, context: scopedContext });
|
|
1402
|
-
},
|
|
1403
|
-
getDefaultMode: () => defaultMode,
|
|
1404
|
-
setDefaultMode: (mode) => {
|
|
1405
|
-
defaultMode = normalizeMode(mode);
|
|
1406
|
-
return defaultMode;
|
|
1407
|
-
},
|
|
1408
|
-
toggleDefaultMode: () => {
|
|
1409
|
-
defaultMode = defaultMode === 'sync' ? 'async' : 'sync';
|
|
1410
|
-
return defaultMode;
|
|
1411
|
-
},
|
|
1412
|
-
closeAll,
|
|
1413
|
-
};
|
|
1414
|
-
}
|