@nordhavnhq/runner 0.0.0-stage → 0.95.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/bin/cliclick +0 -0
- package/dist/brand.d.ts +5 -0
- package/dist/brand.js +18 -0
- package/dist/cli/agent.d.ts +9 -0
- package/dist/cli/agent.js +80 -0
- package/dist/cli/folder.d.ts +2 -0
- package/dist/cli/folder.js +103 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +67 -0
- package/dist/cli/lifecycle.d.ts +3 -0
- package/dist/cli/lifecycle.js +149 -0
- package/dist/cli/link.d.ts +42 -0
- package/dist/cli/link.js +314 -0
- package/dist/cli/logs.d.ts +2 -0
- package/dist/cli/logs.js +147 -0
- package/dist/cli/prompts.d.ts +7 -0
- package/dist/cli/prompts.js +13 -0
- package/dist/cli/ps.d.ts +2 -0
- package/dist/cli/ps.js +81 -0
- package/dist/cli/relay.d.ts +4 -0
- package/dist/cli/relay.js +29 -0
- package/dist/cli/update.d.ts +6 -0
- package/dist/cli/update.js +131 -0
- package/dist/config.d.ts +166 -0
- package/dist/config.js +383 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +145 -0
- package/dist/legacy-env.d.ts +4 -0
- package/dist/legacy-env.js +32 -0
- package/dist/paths.d.ts +37 -0
- package/dist/paths.js +92 -0
- package/dist/runtime/daemon.d.ts +57 -0
- package/dist/runtime/daemon.js +159 -0
- package/dist/runtime/dev-start.d.ts +31 -0
- package/dist/runtime/dev-start.js +110 -0
- package/dist/runtime/file-claims.d.ts +58 -0
- package/dist/runtime/file-claims.js +174 -0
- package/dist/runtime/fs-browse.d.ts +18 -0
- package/dist/runtime/fs-browse.js +104 -0
- package/dist/runtime/fs-checkout.d.ts +154 -0
- package/dist/runtime/fs-checkout.js +1049 -0
- package/dist/runtime/fs-git-index.d.ts +22 -0
- package/dist/runtime/fs-git-index.js +133 -0
- package/dist/runtime/fs-git.d.ts +16 -0
- package/dist/runtime/fs-git.js +424 -0
- package/dist/runtime/git-relay.d.ts +46 -0
- package/dist/runtime/git-relay.js +259 -0
- package/dist/runtime/git-unpushed.d.ts +36 -0
- package/dist/runtime/git-unpushed.js +93 -0
- package/dist/runtime/node-version.d.ts +12 -0
- package/dist/runtime/node-version.js +39 -0
- package/dist/runtime/preview-tunnel.d.ts +16 -0
- package/dist/runtime/preview-tunnel.js +135 -0
- package/dist/runtime/processes.d.ts +61 -0
- package/dist/runtime/processes.js +408 -0
- package/dist/runtime/project-node-download.d.ts +17 -0
- package/dist/runtime/project-node-download.js +137 -0
- package/dist/runtime/project-node.d.ts +65 -0
- package/dist/runtime/project-node.js +223 -0
- package/dist/runtime/reap-scratch.d.ts +22 -0
- package/dist/runtime/reap-scratch.js +112 -0
- package/dist/runtime/spill-tool-output.d.ts +14 -0
- package/dist/runtime/spill-tool-output.js +84 -0
- package/dist/runtime/up.d.ts +6 -0
- package/dist/runtime/up.js +1325 -0
- package/dist/tools/_coerce.d.ts +2 -0
- package/dist/tools/_coerce.js +26 -0
- package/dist/tools/_commit-scope.d.ts +14 -0
- package/dist/tools/_commit-scope.js +70 -0
- package/dist/tools/_jail.d.ts +68 -0
- package/dist/tools/_jail.js +209 -0
- package/dist/tools/_output.d.ts +24 -0
- package/dist/tools/_output.js +48 -0
- package/dist/tools/_ripgrep.d.ts +46 -0
- package/dist/tools/_ripgrep.js +148 -0
- package/dist/tools/_run-worktree.d.ts +10 -0
- package/dist/tools/_run-worktree.js +27 -0
- package/dist/tools/_shell-words.d.ts +15 -0
- package/dist/tools/_shell-words.js +43 -0
- package/dist/tools/_sonar/astro.d.ts +6 -0
- package/dist/tools/_sonar/astro.js +45 -0
- package/dist/tools/_sonar/blade.d.ts +3 -0
- package/dist/tools/_sonar/blade.js +53 -0
- package/dist/tools/_sonar/build.d.ts +44 -0
- package/dist/tools/_sonar/build.js +147 -0
- package/dist/tools/_sonar/changed.d.ts +21 -0
- package/dist/tools/_sonar/changed.js +230 -0
- package/dist/tools/_sonar/diagnose/delta.d.ts +27 -0
- package/dist/tools/_sonar/diagnose/delta.js +64 -0
- package/dist/tools/_sonar/diagnose/detect.d.ts +39 -0
- package/dist/tools/_sonar/diagnose/detect.js +117 -0
- package/dist/tools/_sonar/diagnose/index.d.ts +13 -0
- package/dist/tools/_sonar/diagnose/index.js +217 -0
- package/dist/tools/_sonar/diagnose/lint-worker.d.ts +1 -0
- package/dist/tools/_sonar/diagnose/lint-worker.js +48 -0
- package/dist/tools/_sonar/diagnose/pool.d.ts +22 -0
- package/dist/tools/_sonar/diagnose/pool.js +149 -0
- package/dist/tools/_sonar/diagnose/rules.d.ts +23 -0
- package/dist/tools/_sonar/diagnose/rules.js +131 -0
- package/dist/tools/_sonar/diagnose/types-worker.d.ts +1 -0
- package/dist/tools/_sonar/diagnose/types-worker.js +183 -0
- package/dist/tools/_sonar/files.d.ts +14 -0
- package/dist/tools/_sonar/files.js +121 -0
- package/dist/tools/_sonar/graph.d.ts +34 -0
- package/dist/tools/_sonar/graph.js +164 -0
- package/dist/tools/_sonar/hints.d.ts +116 -0
- package/dist/tools/_sonar/hints.js +545 -0
- package/dist/tools/_sonar/imports.d.ts +38 -0
- package/dist/tools/_sonar/imports.js +275 -0
- package/dist/tools/_sonar/index.d.ts +79 -0
- package/dist/tools/_sonar/index.js +462 -0
- package/dist/tools/_sonar/keys.d.ts +5 -0
- package/dist/tools/_sonar/keys.js +248 -0
- package/dist/tools/_sonar/laravel-routes.d.ts +15 -0
- package/dist/tools/_sonar/laravel-routes.js +263 -0
- package/dist/tools/_sonar/laravel.d.ts +64 -0
- package/dist/tools/_sonar/laravel.js +326 -0
- package/dist/tools/_sonar/location.d.ts +33 -0
- package/dist/tools/_sonar/location.js +137 -0
- package/dist/tools/_sonar/map.d.ts +43 -0
- package/dist/tools/_sonar/map.js +212 -0
- package/dist/tools/_sonar/parse.d.ts +3 -0
- package/dist/tools/_sonar/parse.js +76 -0
- package/dist/tools/_sonar/prewarm.d.ts +9 -0
- package/dist/tools/_sonar/prewarm.js +96 -0
- package/dist/tools/_sonar/prisma.d.ts +9 -0
- package/dist/tools/_sonar/prisma.js +51 -0
- package/dist/tools/_sonar/refs.d.ts +7 -0
- package/dist/tools/_sonar/refs.js +273 -0
- package/dist/tools/_sonar/render.d.ts +66 -0
- package/dist/tools/_sonar/render.js +498 -0
- package/dist/tools/_sonar/resolve.d.ts +63 -0
- package/dist/tools/_sonar/resolve.js +402 -0
- package/dist/tools/_sonar/roots.d.ts +4 -0
- package/dist/tools/_sonar/roots.js +42 -0
- package/dist/tools/_sonar/routes.d.ts +5 -0
- package/dist/tools/_sonar/routes.js +247 -0
- package/dist/tools/_sonar/serve.d.ts +12 -0
- package/dist/tools/_sonar/serve.js +104 -0
- package/dist/tools/_sonar/suggest.d.ts +23 -0
- package/dist/tools/_sonar/suggest.js +114 -0
- package/dist/tools/_sonar/tests.d.ts +21 -0
- package/dist/tools/_sonar/tests.js +134 -0
- package/dist/tools/_sonar/tsconfig.d.ts +34 -0
- package/dist/tools/_sonar/tsconfig.js +188 -0
- package/dist/tools/_sonar/types.d.ts +81 -0
- package/dist/tools/_sonar/types.js +6 -0
- package/dist/tools/_symbols.d.ts +27 -0
- package/dist/tools/_symbols.js +461 -0
- package/dist/tools/_test-report.d.ts +47 -0
- package/dist/tools/_test-report.js +203 -0
- package/dist/tools/_touched.d.ts +44 -0
- package/dist/tools/_touched.js +195 -0
- package/dist/tools/_upload.d.ts +26 -0
- package/dist/tools/_upload.js +132 -0
- package/dist/tools/_worktree-setup.d.ts +29 -0
- package/dist/tools/_worktree-setup.js +204 -0
- package/dist/tools/browser.d.ts +2 -0
- package/dist/tools/browser.js +8 -0
- package/dist/tools/commit-guard.d.ts +44 -0
- package/dist/tools/commit-guard.js +165 -0
- package/dist/tools/computer.d.ts +13 -0
- package/dist/tools/computer.js +952 -0
- package/dist/tools/console.d.ts +44 -0
- package/dist/tools/console.js +739 -0
- package/dist/tools/database.d.ts +28 -0
- package/dist/tools/database.js +152 -0
- package/dist/tools/filesystem.d.ts +36 -0
- package/dist/tools/filesystem.js +506 -0
- package/dist/tools/git-tag.d.ts +10 -0
- package/dist/tools/git-tag.js +164 -0
- package/dist/tools/git.d.ts +52 -0
- package/dist/tools/git.js +1272 -0
- package/dist/tools/http.d.ts +12 -0
- package/dist/tools/http.js +119 -0
- package/dist/tools/image.d.ts +8 -0
- package/dist/tools/image.js +551 -0
- package/dist/tools/index.d.ts +13 -0
- package/dist/tools/index.js +58 -0
- package/dist/tools/outline.d.ts +20 -0
- package/dist/tools/outline.js +98 -0
- package/dist/tools/search.d.ts +17 -0
- package/dist/tools/search.js +391 -0
- package/dist/tools/sonar.d.ts +17 -0
- package/dist/tools/sonar.js +231 -0
- package/dist/tools/testing.d.ts +36 -0
- package/dist/tools/testing.js +273 -0
- package/dist/tools/upload.d.ts +8 -0
- package/dist/tools/upload.js +106 -0
- package/dist/tools/webcam.d.ts +28 -0
- package/dist/tools/webcam.js +967 -0
- package/dist/update/install-kind.d.ts +35 -0
- package/dist/update/install-kind.js +109 -0
- package/dist/update/install.d.ts +32 -0
- package/dist/update/install.js +187 -0
- package/dist/update/manifest.d.ts +18 -0
- package/dist/update/manifest.js +73 -0
- package/dist/update/peers.d.ts +18 -0
- package/dist/update/peers.js +43 -0
- package/dist/update/policy.d.ts +20 -0
- package/dist/update/policy.js +49 -0
- package/dist/update/supervisor.d.ts +25 -0
- package/dist/update/supervisor.js +83 -0
- package/dist/update/updater.d.ts +44 -0
- package/dist/update/updater.js +116 -0
- package/dist/utils/format.d.ts +50 -0
- package/dist/utils/format.js +190 -0
- package/dist/version.d.ts +17 -0
- package/dist/version.js +63 -0
- package/dist/version.json +5 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/act-tools.d.ts +15 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/act-tools.js +541 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/cast-hub.d.ts +25 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/cast-hub.js +137 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/guard.d.ts +21 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/guard.js +104 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/host-protocol.d.ts +47 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/host-protocol.js +41 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/host.d.ts +18 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/host.js +15 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/index.d.ts +13 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/index.js +28 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/live-input.d.ts +74 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/live-input.js +93 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/live-open.d.ts +4 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/live-open.js +57 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/live.d.ts +148 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/live.js +179 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/local-live.d.ts +31 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/local-live.js +262 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/marks.d.ts +36 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/marks.js +173 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/page-events.d.ts +27 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/page-events.js +82 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/page-tools.d.ts +13 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/page-tools.js +526 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/params.d.ts +12 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/params.js +32 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/pick.d.ts +24 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/pick.js +76 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/session.d.ts +225 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/session.js +507 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/shots.d.ts +11 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/shots.js +103 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/show.d.ts +10 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/show.js +190 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/target.d.ts +37 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/target.js +82 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/tour.d.ts +19 -0
- package/node_modules/@nordhavnhq/runner-browser/dist/tour.js +178 -0
- package/node_modules/@nordhavnhq/runner-browser/package.json +18 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/config.d.ts +96 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/config.js +25 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/connection.d.ts +276 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/connection.js +507 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/constants.d.ts +48 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/constants.js +95 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/batch.d.ts +94 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/batch.js +219 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/calls.d.ts +136 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/calls.js +214 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/fs.d.ts +735 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/fs.js +40 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/loop.d.ts +362 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/loop.js +703 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/own-files.d.ts +105 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/own-files.js +202 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/phases.d.ts +204 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/phases.js +497 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/pins.d.ts +45 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/pins.js +176 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/processes.d.ts +74 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/processes.js +72 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/release-tag.d.ts +59 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/release-tag.js +117 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/replay.d.ts +62 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/replay.js +84 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/tool-names.d.ts +27 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/tool-names.js +80 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/version.d.ts +22 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/version.js +22 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/wire.d.ts +595 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/contract/wire.js +85 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/index.d.ts +43 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/index.js +50 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/inference.d.ts +135 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/inference.js +945 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/mcp.d.ts +67 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/mcp.js +47 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/platform.d.ts +21 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/platform.js +25 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/auto-load.d.ts +39 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/auto-load.js +67 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/background-commands.d.ts +61 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/background-commands.js +58 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/chat-run-ends.d.ts +23 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/chat-run-ends.js +42 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/duration.d.ts +6 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/duration.js +12 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/events.d.ts +150 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/events.js +36 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/extract-json.d.ts +14 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/extract-json.js +49 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-chat.d.ts +109 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-chat.js +894 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-task.d.ts +73 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-task.js +765 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/loop.d.ts +246 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/loop.js +621 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/messages.d.ts +88 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/messages.js +188 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/pending-steers.d.ts +15 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/pending-steers.js +10 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/phased-loop.d.ts +16 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/phased-loop.js +97 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/project-instructions.d.ts +22 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/project-instructions.js +47 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/run-tools.d.ts +26 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/run-tools.js +48 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/scratch-prompt.d.ts +8 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/scratch-prompt.js +19 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/side-question.d.ts +76 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/side-question.js +155 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/task-validation.d.ts +43 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/task-validation.js +37 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/unload-toolset.d.ts +49 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/unload-toolset.js +104 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/write-scope.d.ts +16 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/write-scope.js +6 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/tools/delegate.d.ts +86 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/tools/delegate.js +141 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/tools/index.d.ts +179 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/tools/index.js +35 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/tools/mcp.d.ts +21 -0
- package/node_modules/@nordhavnhq/runner-runtime/dist/tools/mcp.js +179 -0
- package/node_modules/@nordhavnhq/runner-runtime/package.json +18 -0
- package/package.json +33 -4
- package/README.md +0 -3
|
@@ -0,0 +1,894 @@
|
|
|
1
|
+
import { streamInference } from '../inference.js';
|
|
2
|
+
import { sendWsChatStream, sendWsChatDone, sendWsChatNarration, sendWsChatError, sendWsChatSteerApplied, sendWsToolUse, } from '../connection.js';
|
|
3
|
+
import { steerBody, steerIds } from './pending-steers.js';
|
|
4
|
+
import { markChatTurnDone, recordChatReply, recordChatRequest } from './side-question.js';
|
|
5
|
+
import { buildAgentHistoryMessages, buildUserMessage, userMessageText } from './messages.js';
|
|
6
|
+
import { buildScratchPromptNote } from './scratch-prompt.js';
|
|
7
|
+
import { buildProjectInstructionsNote } from './project-instructions.js';
|
|
8
|
+
import { writeScopeContext } from './write-scope.js';
|
|
9
|
+
import { executeMcpTool } from '../tools/mcp.js';
|
|
10
|
+
import { autoLoadToolDef, appendAutoLoadInstructions } from './auto-load.js';
|
|
11
|
+
import { applyUnloadToolset } from './unload-toolset.js';
|
|
12
|
+
import { postStudioLog } from '../mcp.js';
|
|
13
|
+
import { emitEvent } from './events.js';
|
|
14
|
+
import { createChatRunEnds, endsWithin, SUPERSEDED_RUN_WAIT_MS } from './chat-run-ends.js';
|
|
15
|
+
import { dispatchScratchKey } from '../contract/calls.js';
|
|
16
|
+
import { MAX_LOOP_MS, MAX_TOOL_ROUNDS } from '../constants.js';
|
|
17
|
+
import { TOOL_RESULT_MAX_CHARS } from '../contract/loop.js';
|
|
18
|
+
import { buildUnknownToolError } from '../contract/tool-names.js';
|
|
19
|
+
import { runAgenticLoop, } from './loop.js';
|
|
20
|
+
/**
|
|
21
|
+
* The one-to-one half of the cutoff notice: the next thing the person types
|
|
22
|
+
* goes to this same agent, so "reply continue" is an instruction that works.
|
|
23
|
+
*/
|
|
24
|
+
const CONTINUE_HINT = 'Reply "continue" and I\'ll pick up where I left off.';
|
|
25
|
+
/**
|
|
26
|
+
* The room half. In a meeting "continue" is wrong twice over: the transcript is
|
|
27
|
+
* shared, and who speaks next is a server-side routing call, so a human typing
|
|
28
|
+
* "continue" is routed like any other turn and can land on the chair or on a
|
|
29
|
+
* colleague. The agent that was cut off has no claim on the next turn.
|
|
30
|
+
*
|
|
31
|
+
* So the room is pointed at the thing that survives the floor moving on: a task.
|
|
32
|
+
* What exactly was left unfinished is not knowable from here - the breaker fires
|
|
33
|
+
* mid-tool-call and the loop has no model of the work - but the narration this
|
|
34
|
+
* notice is appended to IS the agent's own account of where it got to, which is
|
|
35
|
+
* why the notice never replaces a reply, only follows it.
|
|
36
|
+
*/
|
|
37
|
+
const MEETING_CUTOFF_HANDOVER = 'Whatever I was in the middle of is unfinished. This is a room, so there is nothing to reply "continue" to: the next turn is routed and may not come back to me. If the rest still needs doing, put it in a task with `studio_create_task` and say here that you did.';
|
|
38
|
+
/** A code session's reply suggestion on its own last line (the studio's shared/utils/reply-suggestion.ts). */
|
|
39
|
+
const REPLY_SUGGESTION_LINE = /(?:^|\n)[ \t]*<reply-suggestion>([^\n]*)<\/reply-suggestion>\s*$/i;
|
|
40
|
+
const REPLY_SUGGESTION_ANY_TAG = /<\/?reply-suggestion\b/i;
|
|
41
|
+
const REPLY_SUGGESTION_MAX_LENGTH = 200;
|
|
42
|
+
/**
|
|
43
|
+
* The cutoff notice under the reply, but above a reply-suggestion tag that ends
|
|
44
|
+
* it: the studio only takes that tag off the last line, so a notice under it
|
|
45
|
+
* would leave the raw tag on screen. A reply that is only the tag gets the
|
|
46
|
+
* notice above it too. Mirrors the studio's `appendAboveReplySuggestion` and
|
|
47
|
+
* its rules for a valid tag (not empty, at most 200 characters, no tag inside;
|
|
48
|
+
* not its code-fence check); change both together.
|
|
49
|
+
*/
|
|
50
|
+
export function appendCutoffNotice(reply, notice) {
|
|
51
|
+
const tag = REPLY_SUGGESTION_LINE.exec(reply);
|
|
52
|
+
const suggestion = tag?.[1].trim() ?? '';
|
|
53
|
+
if (!tag || !suggestion || suggestion.length > REPLY_SUGGESTION_MAX_LENGTH || REPLY_SUGGESTION_ANY_TAG.test(suggestion)) {
|
|
54
|
+
return `${reply}\n\n${notice}`;
|
|
55
|
+
}
|
|
56
|
+
const words = reply.slice(0, tag.index).replace(/\s+$/, '');
|
|
57
|
+
const above = words.trim() ? `${words}\n\n${notice}` : notice;
|
|
58
|
+
return `${above}\n${tag[0].trim()}`;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Actionable "you were cut off" notice for a turn stopped by a breaker
|
|
62
|
+
* (round/time/cost cap). Returns null when the turn ended normally, so the
|
|
63
|
+
* caller appends it ONLY to a genuine mid-work cutoff. A breaker fires while the
|
|
64
|
+
* agent is still calling tools, so its last narration (if any) is mid-work and
|
|
65
|
+
* must not read as a finished reply - hence the notice is appended even when a
|
|
66
|
+
* reply exists, not just when it is empty.
|
|
67
|
+
*
|
|
68
|
+
* The reason half is shared; only the "what now" half depends on where the turn
|
|
69
|
+
* was spoken, which the studio states on the frame as `inMeeting`. BOTH halves
|
|
70
|
+
* are byte-identical to the studio's own `cutoffNotice` in
|
|
71
|
+
* server/utils/internal-runtime/run-chat.ts, so an external agent and an
|
|
72
|
+
* internal one say the same thing after the same cutoff. Change one side and
|
|
73
|
+
* change the other in the same change.
|
|
74
|
+
*
|
|
75
|
+
* `inMeeting` is a required parameter rather than a defaulted one: an older
|
|
76
|
+
* studio omits the frame field, and turning that absence into `false` is the
|
|
77
|
+
* caller's job, done once where the frame is read, not silently here.
|
|
78
|
+
*/
|
|
79
|
+
export function cutoffNotice(stopReason, rounds, inMeeting) {
|
|
80
|
+
let reason;
|
|
81
|
+
switch (stopReason) {
|
|
82
|
+
case 'max-rounds':
|
|
83
|
+
reason = `I hit my limit of ${rounds} tool steps on this turn while still working.`;
|
|
84
|
+
break;
|
|
85
|
+
case 'max-loop-ms':
|
|
86
|
+
reason = 'I ran out of time on this turn while still working.';
|
|
87
|
+
break;
|
|
88
|
+
case 'max-cost':
|
|
89
|
+
reason = 'I reached this turn\'s cost limit while still working.';
|
|
90
|
+
break;
|
|
91
|
+
case 'loop':
|
|
92
|
+
reason = 'I was going in circles on this turn, so I stopped.';
|
|
93
|
+
break;
|
|
94
|
+
default:
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
return `${reason} ${inMeeting ? MEETING_CUTOFF_HANDOVER : CONTINUE_HINT}`;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Where in the budget each notice comes due.
|
|
101
|
+
*
|
|
102
|
+
* The second one is NOT at the very end on purpose. What it asks for - create a
|
|
103
|
+
* task for the rest - costs at least one more inference round plus a tool call,
|
|
104
|
+
* and a round that does not fit is a round the breaker cuts off: the room then
|
|
105
|
+
* gets `cutoffNotice` telling IT to make the task, which is the hand-over we
|
|
106
|
+
* just asked the agent to do, only now nobody did it. At 0.7 of a five-minute
|
|
107
|
+
* budget there is a minute and a half left, which is a round; at 0.8 there was
|
|
108
|
+
* one minute, which often is not.
|
|
109
|
+
*/
|
|
110
|
+
const HALF_TIME_RATIO = 0.5;
|
|
111
|
+
const WRAP_UP_RATIO = 0.7;
|
|
112
|
+
/** Marker keys for `alreadySent` - they identify the notice, not the ratio. */
|
|
113
|
+
const HALF_TIME_NOTICE = 1;
|
|
114
|
+
const WRAP_UP_NOTICE = 2;
|
|
115
|
+
/**
|
|
116
|
+
* How much time is left, in words.
|
|
117
|
+
*
|
|
118
|
+
* Floored rather than rounded, and never zero: `Math.round` printed "about 0
|
|
119
|
+
* minute(s) left" for everything under thirty seconds, which reads as "your time
|
|
120
|
+
* is gone" at the exact moment the agent still has a round to land the turn in.
|
|
121
|
+
* Flooring also never overstates the time, so "about 2 minutes" is a promise the
|
|
122
|
+
* clock can keep.
|
|
123
|
+
*/
|
|
124
|
+
function timeLeftPhrase(leftMs) {
|
|
125
|
+
if (leftMs < 60_000)
|
|
126
|
+
return 'less than a minute';
|
|
127
|
+
const minutes = Math.floor(leftMs / 60_000);
|
|
128
|
+
return `about ${minutes} minute${minutes === 1 ? '' : 's'}`;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* How much of the turn is gone, told to the agent while it can still act on it.
|
|
132
|
+
*
|
|
133
|
+
* A turn has a wall-clock budget (`maxLoopMs`, five minutes for chat) and the
|
|
134
|
+
* agent has no way to see it. So it decides whether to write a whole document
|
|
135
|
+
* inline without knowing whether there is time, discovers the answer when
|
|
136
|
+
* `cutoffNotice` cuts it off mid-work, and in a meeting the room has been
|
|
137
|
+
* waiting the entire time. Giving it the clock is what lets it make that call
|
|
138
|
+
* itself instead of running into it.
|
|
139
|
+
*
|
|
140
|
+
* Two notices, not one per round: a running commentary costs context on every
|
|
141
|
+
* later round and invites the model to narrate the time instead of using it.
|
|
142
|
+
* The first is informational, the second is what to DO about it, because by then
|
|
143
|
+
* the useful action is to stop and hand the rest to a task.
|
|
144
|
+
*
|
|
145
|
+
* Returns null when nothing is due. Never persisted and never broadcast: this
|
|
146
|
+
* rides in the loop's in-memory message array and dies with the turn.
|
|
147
|
+
*
|
|
148
|
+
* Byte-identical to the studio's `budgetNotice` in
|
|
149
|
+
* server/utils/internal-runtime/run-chat.ts, thresholds included, so an internal
|
|
150
|
+
* agent and an external one are told the same thing at the same moment. Change
|
|
151
|
+
* one side and change the other in the same change.
|
|
152
|
+
*/
|
|
153
|
+
export function budgetNotice(elapsedMs, maxLoopMs, alreadySent) {
|
|
154
|
+
const ratio = elapsedMs / maxLoopMs;
|
|
155
|
+
const left = timeLeftPhrase(Math.max(0, maxLoopMs - elapsedMs));
|
|
156
|
+
if (ratio >= WRAP_UP_RATIO && !alreadySent.has(WRAP_UP_NOTICE)) {
|
|
157
|
+
alreadySent.add(WRAP_UP_NOTICE);
|
|
158
|
+
alreadySent.add(HALF_TIME_NOTICE);
|
|
159
|
+
// The task first, the words after: if the breaker fires between the two,
|
|
160
|
+
// the thing that survives the turn exists and the room still gets a
|
|
161
|
+
// cutoff notice. The other order loses the task and keeps the sentence.
|
|
162
|
+
return `You have used most of your time for this turn (${left} left) and the room is waiting on you. Land this turn now: if the work is not finished, create a task for the rest first, then say in one line what you have and what you started. Do not begin anything new here.`;
|
|
163
|
+
}
|
|
164
|
+
if (ratio >= HALF_TIME_RATIO && !alreadySent.has(HALF_TIME_NOTICE)) {
|
|
165
|
+
alreadySent.add(HALF_TIME_NOTICE);
|
|
166
|
+
return `About half your time for this turn is gone (${left} left). Everyone in the room is waiting while you work, so if what is left is bigger than the time you have, make it a task rather than doing it here.`;
|
|
167
|
+
}
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Shown when a turn produced no reply and no breaker fired - a reasoning-only
|
|
172
|
+
* close the loop's force-synthesis could not salvage. Distinct from a cutoff:
|
|
173
|
+
* here the model chose to end, it just authored nothing.
|
|
174
|
+
*/
|
|
175
|
+
const GENERIC_EMPTY_REPLY = 'I finished this turn without a message to send. If you were expecting a response, let me know and I will continue.';
|
|
176
|
+
/**
|
|
177
|
+
* Chat runs another one took over: a newer dispatch of the same conversation,
|
|
178
|
+
* or a reconnect the studio did not keep them through (`keptRuns`). They stop
|
|
179
|
+
* without a word: the studio settled or restarted their turn already, and a
|
|
180
|
+
* `chat:done` from them would land on the run that replaced them.
|
|
181
|
+
*/
|
|
182
|
+
const supersededChatRuns = new WeakSet();
|
|
183
|
+
/** Stop a chat run another one took over (see `supersededChatRuns`). */
|
|
184
|
+
export function supersedeChatRun(controller) {
|
|
185
|
+
supersededChatRuns.add(controller);
|
|
186
|
+
controller.abort();
|
|
187
|
+
}
|
|
188
|
+
export function createHandleChat(deps) {
|
|
189
|
+
const { agent, agentName, config, agentHome, resolveProject, resolveWorkspaceFolders, resolveScratch, findProjectInstructions, spillToolOutput, resolveWriteScope, activeChatAborts, pendingChatSteers, toolProvider, debug } = deps;
|
|
190
|
+
const chatRunEnds = createChatRunEnds();
|
|
191
|
+
return async function handleChat(socket, msg) {
|
|
192
|
+
const abortController = new AbortController();
|
|
193
|
+
// One run per conversation: a dispatch for a conversation that still has a
|
|
194
|
+
// run here replaces it (the studio restarted the turn), so the old one
|
|
195
|
+
// stops instead of writing on next to it, and this one starts only once
|
|
196
|
+
// it has (`chatRunEnds`, awaited at the top of the try below).
|
|
197
|
+
const previous = activeChatAborts.get(msg.conversationId);
|
|
198
|
+
if (previous)
|
|
199
|
+
supersedeChatRun(previous);
|
|
200
|
+
activeChatAborts.set(msg.conversationId, abortController);
|
|
201
|
+
const run = chatRunEnds.begin(msg.conversationId);
|
|
202
|
+
const lastUserMsg = [...msg.history].reverse().find(h => h.role === 'user')?.content ?? '';
|
|
203
|
+
emitEvent({
|
|
204
|
+
kind: 'dispatch.received',
|
|
205
|
+
channel: 'chat',
|
|
206
|
+
agentSlug: agent.slug,
|
|
207
|
+
conversationId: msg.conversationId,
|
|
208
|
+
userName: msg.userName,
|
|
209
|
+
messageCount: msg.history.length,
|
|
210
|
+
preview: lastUserMsg ? lastUserMsg.slice(0, 60) : undefined,
|
|
211
|
+
});
|
|
212
|
+
if (debug) {
|
|
213
|
+
postStudioLog(config.studioUrl, agent.token, {
|
|
214
|
+
level: 'debug',
|
|
215
|
+
type: 'chat.dispatch',
|
|
216
|
+
message: `Chat dispatch received - ${msg.history.length} message(s) from ${msg.userName ?? 'unknown'}`,
|
|
217
|
+
data: { history: msg.history },
|
|
218
|
+
conversationUid: msg.conversationId,
|
|
219
|
+
userUuid: msg.userUuid,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
const startedAt = Date.now();
|
|
223
|
+
// The last aside actually sent to the studio this turn, or ''. Only set in a
|
|
224
|
+
// room; see the `onAssistantNarration` hook for why it is tracked here.
|
|
225
|
+
let lastNarrated = '';
|
|
226
|
+
// Outside a room: a steer was read and its answer is not said yet, and the
|
|
227
|
+
// last line sent as such an answer (or a reply kept before a steer), which
|
|
228
|
+
// the studio therefore already has as a message.
|
|
229
|
+
let answerSteer = false;
|
|
230
|
+
let lastSteerReply = '';
|
|
231
|
+
let finalReply;
|
|
232
|
+
let finalModel;
|
|
233
|
+
let totalInputTokens;
|
|
234
|
+
let totalOutputTokens;
|
|
235
|
+
let totalCostMicros;
|
|
236
|
+
try {
|
|
237
|
+
// 0. The run this one replaces, when one still runs: it was aborted
|
|
238
|
+
// above, wait for its loop and its tool in flight to stop before this
|
|
239
|
+
// one touches the conversation or the checkout.
|
|
240
|
+
if (run.previous && !(await endsWithin(run.previous, SUPERSEDED_RUN_WAIT_MS))) {
|
|
241
|
+
emitEvent({
|
|
242
|
+
kind: 'note',
|
|
243
|
+
level: 'warn',
|
|
244
|
+
channel: 'chat',
|
|
245
|
+
agentSlug: agent.slug,
|
|
246
|
+
conversationId: msg.conversationId,
|
|
247
|
+
message: `replaced run still busy after ${SUPERSEDED_RUN_WAIT_MS / 1000}s - starting anyway`,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
// Cancelled or replaced in turn while it waited: nothing to run.
|
|
251
|
+
if (abortController.signal.aborted) {
|
|
252
|
+
emitEvent({ kind: 'dispatch.cancelled', channel: 'chat', agentSlug: agent.slug, conversationId: msg.conversationId });
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
// 1. Tool registry - mutable across rounds within this dispatch.
|
|
256
|
+
// Seeded from the studio's dispatch (bootstrap + anything previously
|
|
257
|
+
// loaded in this conversation). The model expands it mid-loop by
|
|
258
|
+
// calling `studio_load_toolset`, which streams new defs back through
|
|
259
|
+
// `ctx.loadTools` (defined below) and into this map. The agentic
|
|
260
|
+
// loop re-reads it at the top of every round, so new tools become
|
|
261
|
+
// callable on the next inference call.
|
|
262
|
+
//
|
|
263
|
+
// Owner-only consent gating is already applied at dispatch time;
|
|
264
|
+
// tools with a non-null `mcpPath` are called via HTTP against the
|
|
265
|
+
// studio MCP API; the rest run locally inside the runner.
|
|
266
|
+
const registry = new Map();
|
|
267
|
+
for (const def of msg.agentConfig?.toolDefs ?? [])
|
|
268
|
+
registry.set(def.name, def);
|
|
269
|
+
const toolGroups = msg.agentConfig?.toolGroups ?? [];
|
|
270
|
+
const groupForToolName = new Map();
|
|
271
|
+
for (const g of toolGroups) {
|
|
272
|
+
for (const t of g.tools ?? [])
|
|
273
|
+
groupForToolName.set(t.name, g);
|
|
274
|
+
}
|
|
275
|
+
// 2. System prompt - fully assembled by the studio and shipped in the
|
|
276
|
+
// dispatch frame. The runner does no prompt assembly. The agentic
|
|
277
|
+
// loop owns its own tool-definitions builder (re-reads `registry`
|
|
278
|
+
// at the top of every round).
|
|
279
|
+
// We only append the concrete scratch path (the studio can't know
|
|
280
|
+
// this machine's local paths). Scratch is keyed by conversation id so
|
|
281
|
+
// every turn of the same chat shares one throwaway dir.
|
|
282
|
+
const scratchRoot = resolveScratch(dispatchScratchKey({ kind: 'chat', conversationUid: msg.conversationId }) ?? msg.conversationId);
|
|
283
|
+
const projectRoot = resolveProject(msg.project?.folder);
|
|
284
|
+
// The project's unmuted workspace folders: extra jail roots beside it.
|
|
285
|
+
const workspaceRoots = projectRoot !== agentHome && resolveWorkspaceFolders
|
|
286
|
+
? resolveWorkspaceFolders(msg.project?.workspaceFolders, projectRoot)
|
|
287
|
+
: [];
|
|
288
|
+
const writeScope = msg.project?.scope && projectRoot !== agentHome && resolveWriteScope
|
|
289
|
+
? resolveWriteScope(projectRoot, msg.project.scope)
|
|
290
|
+
: null;
|
|
291
|
+
const systemPrompt = `${msg.systemPrompt}${buildScratchPromptNote(scratchRoot)}${buildProjectInstructionsNote(findProjectInstructions, projectRoot, agentHome)}`;
|
|
292
|
+
const historyMessages = [];
|
|
293
|
+
msg.history.forEach((h, i) => {
|
|
294
|
+
const hasText = !!h.content && h.content.trim().length > 0;
|
|
295
|
+
const hasTools = h.role !== 'user' && (h.toolCalls?.length ?? 0) > 0;
|
|
296
|
+
const hasFiles = h.role === 'user' && (h.attachments?.length ?? 0) > 0;
|
|
297
|
+
// Drop empty/whitespace-only entries (e.g. multiple-choice answers
|
|
298
|
+
// persisted with content="" and the real payload in metadataJson) -
|
|
299
|
+
// AI SDK v6 + Anthropic reject empty text content blocks. An agent
|
|
300
|
+
// entry that ran tools but never narrated is NOT empty: its tool calls
|
|
301
|
+
// still need replaying. Neither is a person's message that is only a
|
|
302
|
+
// file or a photo: the file is the message.
|
|
303
|
+
if (!hasText && !hasTools && !hasFiles)
|
|
304
|
+
return;
|
|
305
|
+
if (h.role === 'user') {
|
|
306
|
+
historyMessages.push(buildUserMessage({ text: userMessageText(h.content, h.userName), attachments: h.attachments }));
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
historyMessages.push(...buildAgentHistoryMessages(h, `h${i}`));
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
// 3. Limits + tool-execution context.
|
|
313
|
+
const maxRounds = msg.agentConfig?.maxToolRounds ?? MAX_TOOL_ROUNDS;
|
|
314
|
+
const maxLoopMs = msg.agentConfig?.maxLoopMs ?? MAX_LOOP_MS;
|
|
315
|
+
// Where this turn is being spoken. Only the studio can know it, so it
|
|
316
|
+
// states it on the frame; an older studio omits the field and that absence
|
|
317
|
+
// is read as the one-to-one case it has always been. Read ONCE here and
|
|
318
|
+
// used by both notices: `budgetNotice` mid-turn and `cutoffNotice` at the
|
|
319
|
+
// end. Do not re-derive it anywhere else, and never sniff the system
|
|
320
|
+
// prompt for the meeting block - that is a hidden contract a prompt edit
|
|
321
|
+
// would break in silence.
|
|
322
|
+
const inMeeting = msg.inMeeting ?? false;
|
|
323
|
+
const truncateChars = msg.agentConfig?.toolResultTruncateChars ?? TOOL_RESULT_MAX_CHARS;
|
|
324
|
+
// Studio ships `maxCostPerTurn` in dollars (Float on `Agent`); the loop
|
|
325
|
+
// counts cost in micros. Convert once at the boundary. Undefined means
|
|
326
|
+
// "no cap" - the studio is expected to ship a default (currently $10).
|
|
327
|
+
const maxCostMicros = msg.agentConfig?.maxCostPerTurn !== undefined
|
|
328
|
+
? Math.round(msg.agentConfig.maxCostPerTurn * 1_000_000)
|
|
329
|
+
: undefined;
|
|
330
|
+
const attachments = [];
|
|
331
|
+
// Per-call sink for inline image bytes (capture tools with `keep:false`).
|
|
332
|
+
// Drained inside `executeTool` and threaded into the agentic loop via
|
|
333
|
+
// `ToolOutcome.images`, which `buildToolResultMessage` embeds as a v6
|
|
334
|
+
// `content` output so the model sees the bytes without an extra round.
|
|
335
|
+
const pendingToolImages = [];
|
|
336
|
+
const ctx = {
|
|
337
|
+
agentSlug: agent.slug,
|
|
338
|
+
agentName: agentName?.(),
|
|
339
|
+
organisationSlug: agent.organisationSlug,
|
|
340
|
+
// Relative tool paths resolve against the project THIS chat is about -
|
|
341
|
+
// the dispatch carries the project, and the agent is cross-project, so
|
|
342
|
+
// this can differ per conversation. Falls back to the agent's home when
|
|
343
|
+
// that project isn't available on this machine.
|
|
344
|
+
projectRoot,
|
|
345
|
+
...(workspaceRoots.length ? { workspaceRoots } : {}),
|
|
346
|
+
agentHome,
|
|
347
|
+
scratchRoot,
|
|
348
|
+
...writeScopeContext(writeScope),
|
|
349
|
+
projectSlug: msg.project?.slug,
|
|
350
|
+
conversationId: msg.conversationId,
|
|
351
|
+
// Carry the queue UID so MCP tool calls resolve the invocation project
|
|
352
|
+
// (mcp.ts injects it): without it, project-scoped secret lookups in a
|
|
353
|
+
// project-linked chat silently lose the project tier and only org-wide
|
|
354
|
+
// secrets resolve. The task handler threads its own queueUid the same way.
|
|
355
|
+
queueUid: msg.queueUid,
|
|
356
|
+
// A chat turn has somebody reading it, so confirm-first tools may run.
|
|
357
|
+
userPresent: true,
|
|
358
|
+
// Their git relay, when they connected one: commits in their name,
|
|
359
|
+
// pushes through their machine.
|
|
360
|
+
gitRelay: msg.gitRelay,
|
|
361
|
+
// The files of the checkout this chat changed itself and has not
|
|
362
|
+
// committed: `runner_git_status` names them `yours`. Only in a checkout.
|
|
363
|
+
...(msg.project && projectRoot !== agentHome ? { ownFiles: new Set(msg.project.ownFiles ?? []), touchedFiles: new WeakMap() } : {}),
|
|
364
|
+
signal: abortController.signal,
|
|
365
|
+
delegateTimeoutMs: msg.agentConfig?.delegateTimeoutMs,
|
|
366
|
+
runDeadlineAt: Date.now() + maxLoopMs,
|
|
367
|
+
studioUrl: config.studioUrl,
|
|
368
|
+
agentToken: agent.token,
|
|
369
|
+
socket,
|
|
370
|
+
attachments,
|
|
371
|
+
pendingToolImages,
|
|
372
|
+
loadTools: (defs) => {
|
|
373
|
+
for (const def of defs)
|
|
374
|
+
registry.set(def.name, def);
|
|
375
|
+
},
|
|
376
|
+
hasTool: (name) => registry.has(name),
|
|
377
|
+
};
|
|
378
|
+
// 4. Inference adapter - wires the loop to the streaming studio proxy
|
|
379
|
+
// (or direct-to-provider when `msg.inference` carries a runtime
|
|
380
|
+
// hint). Streaming text and thoughts go straight to the studio
|
|
381
|
+
// via `chat:stream` frames so the UI shows live typing.
|
|
382
|
+
// Every call is also recorded as the base a side question (`/btw`)
|
|
383
|
+
// is answered on (side-question.ts), with what the model answered.
|
|
384
|
+
const callInference = async (req, signal) => {
|
|
385
|
+
recordChatRequest(agent.slug, msg.conversationId, {
|
|
386
|
+
messages: req.messages,
|
|
387
|
+
tools: req.tools,
|
|
388
|
+
...(msg.queueUid ? { queueUid: msg.queueUid } : {}),
|
|
389
|
+
...(msg.inference ? { inference: msg.inference } : {}),
|
|
390
|
+
});
|
|
391
|
+
const result = await streamInference({
|
|
392
|
+
studioUrl: config.studioUrl,
|
|
393
|
+
connectionToken: agent.token,
|
|
394
|
+
messages: req.messages,
|
|
395
|
+
tools: req.tools,
|
|
396
|
+
...(req.toolChoice ? { toolChoice: req.toolChoice } : {}),
|
|
397
|
+
signal,
|
|
398
|
+
agentSlug: agent.slug,
|
|
399
|
+
conversationId: msg.conversationId,
|
|
400
|
+
// Without it the studio books no per-call usage on the turn's
|
|
401
|
+
// queue row: no model calls, no cache reads, no live meter.
|
|
402
|
+
queueUid: msg.queueUid,
|
|
403
|
+
inference: msg.inference,
|
|
404
|
+
}, (delta) => sendWsChatStream(socket, msg.conversationId, delta), (delta) => sendWsChatStream(socket, msg.conversationId, delta, true));
|
|
405
|
+
recordChatReply(agent.slug, msg.conversationId, result);
|
|
406
|
+
return result;
|
|
407
|
+
};
|
|
408
|
+
// Rolling-summary transport. Bound to the agent's configured compaction
|
|
409
|
+
// model when set, so a fold runs on a cheap/fast model instead of the
|
|
410
|
+
// agent's reasoning model. Undefined when not configured -> the loop
|
|
411
|
+
// reuses `callInference`. No stream callbacks: the summary is internal
|
|
412
|
+
// bookkeeping, not something the user should see typed into the chat.
|
|
413
|
+
//
|
|
414
|
+
// The `inference` hint is deliberately NOT forwarded here: it switches the
|
|
415
|
+
// runner to direct-mode against the AGENT's provider/baseUrl, which would
|
|
416
|
+
// silently ignore `modelOverride` and bill the expensive model anyway. The
|
|
417
|
+
// compaction call always goes through the studio proxy, which is what
|
|
418
|
+
// resolves the compaction provider.
|
|
419
|
+
const compactionOverride = msg.agentConfig?.compactionModelOverride;
|
|
420
|
+
const callSummaryInference = compactionOverride
|
|
421
|
+
? (req, signal) => streamInference({
|
|
422
|
+
studioUrl: config.studioUrl,
|
|
423
|
+
connectionToken: agent.token,
|
|
424
|
+
messages: req.messages,
|
|
425
|
+
tools: req.tools,
|
|
426
|
+
...(req.toolChoice ? { toolChoice: req.toolChoice } : {}),
|
|
427
|
+
signal,
|
|
428
|
+
agentSlug: agent.slug,
|
|
429
|
+
conversationId: msg.conversationId,
|
|
430
|
+
queueUid: msg.queueUid,
|
|
431
|
+
modelOverride: compactionOverride,
|
|
432
|
+
})
|
|
433
|
+
: undefined;
|
|
434
|
+
// 5. Tool-execution adapter - owns local-vs-MCP routing, WS
|
|
435
|
+
// `chat:tool-use` framing, and per-tool stdout logging.
|
|
436
|
+
const executeTool = async (call, toolDef) => {
|
|
437
|
+
// `studio_unload_toolset` carries `mcpPath: null` and is not a local
|
|
438
|
+
// tool: it only mutates this dispatch's registry, which the provider
|
|
439
|
+
// cannot see. Routed BEFORE the auto-load and unknown-tool branches
|
|
440
|
+
// below, which would otherwise reject it for having no path at all.
|
|
441
|
+
// Mirrors the studio-side interception in internal-runtime/adapters.ts.
|
|
442
|
+
if (toolDef && call.name === 'studio_unload_toolset') {
|
|
443
|
+
const unloadStart = Date.now();
|
|
444
|
+
sendWsToolUse(socket, msg.conversationId, call.name, 'running', call.arguments);
|
|
445
|
+
emitEvent({
|
|
446
|
+
kind: 'tool.start',
|
|
447
|
+
agentSlug: agent.slug,
|
|
448
|
+
tool: call.name,
|
|
449
|
+
conversationId: msg.conversationId,
|
|
450
|
+
argsBytes: JSON.stringify(call.arguments ?? {}).length,
|
|
451
|
+
});
|
|
452
|
+
const { result, isError } = applyUnloadToolset(call.arguments, registry, groupForToolName);
|
|
453
|
+
const durationMs = Date.now() - unloadStart;
|
|
454
|
+
sendWsToolUse(socket, msg.conversationId, call.name, isError ? 'error' : 'done', call.arguments, result, durationMs);
|
|
455
|
+
emitEvent({
|
|
456
|
+
kind: 'tool.end',
|
|
457
|
+
agentSlug: agent.slug,
|
|
458
|
+
tool: call.name,
|
|
459
|
+
conversationId: msg.conversationId,
|
|
460
|
+
durMs: durationMs,
|
|
461
|
+
error: isError ? result.slice(0, 200) : undefined,
|
|
462
|
+
});
|
|
463
|
+
return { result, isError, durationMs };
|
|
464
|
+
}
|
|
465
|
+
// First-use auto-load: a real, granted tool the model called before
|
|
466
|
+
// its schema landed in this dispatch's registry. Pull it in-band and
|
|
467
|
+
// run the call this same step instead of bouncing with "load and
|
|
468
|
+
// retry". Mirrors the studio-side path in internal-runtime/adapters.ts.
|
|
469
|
+
let resolvedDef = toolDef;
|
|
470
|
+
let autoLoaded = false;
|
|
471
|
+
if (!resolvedDef && groupForToolName.has(call.name)) {
|
|
472
|
+
resolvedDef = await autoLoadToolDef(call.name, registry, ctx);
|
|
473
|
+
autoLoaded = resolvedDef !== undefined;
|
|
474
|
+
}
|
|
475
|
+
// Unknown tool - the model invoked a name not in the registry and
|
|
476
|
+
// auto-load couldn't resolve it. Surface a helpful "load the toolset"
|
|
477
|
+
// hint and short-circuit.
|
|
478
|
+
if (!resolvedDef || (!resolvedDef.mcpPath && !toolProvider.isLocalTool(call.name))) {
|
|
479
|
+
const errMsg = buildUnknownToolError(call.name, groupForToolName);
|
|
480
|
+
sendWsToolUse(socket, msg.conversationId, call.name, 'error', call.arguments, errMsg, 0);
|
|
481
|
+
return { result: errMsg, isError: true, durationMs: 0 };
|
|
482
|
+
}
|
|
483
|
+
sendWsToolUse(socket, msg.conversationId, call.name, 'running', call.arguments);
|
|
484
|
+
emitEvent({
|
|
485
|
+
kind: 'tool.start',
|
|
486
|
+
agentSlug: agent.slug,
|
|
487
|
+
tool: call.name,
|
|
488
|
+
conversationId: msg.conversationId,
|
|
489
|
+
argsBytes: JSON.stringify(call.arguments ?? {}).length,
|
|
490
|
+
});
|
|
491
|
+
const toolStart = Date.now();
|
|
492
|
+
let result;
|
|
493
|
+
let isError;
|
|
494
|
+
// Reset before exec so only this call's pushes are captured. Only
|
|
495
|
+
// local capture tools push (keep:false mode); MCP tools never do.
|
|
496
|
+
pendingToolImages.length = 0;
|
|
497
|
+
try {
|
|
498
|
+
if (resolvedDef.mcpPath) {
|
|
499
|
+
result = await executeMcpTool(resolvedDef, call.arguments, ctx);
|
|
500
|
+
}
|
|
501
|
+
else {
|
|
502
|
+
result = await toolProvider.executeLocalTool(call.name, call.arguments, ctx);
|
|
503
|
+
}
|
|
504
|
+
isError = result.startsWith('Error:');
|
|
505
|
+
}
|
|
506
|
+
catch (err) {
|
|
507
|
+
result = `Error: ${err.message}`;
|
|
508
|
+
isError = true;
|
|
509
|
+
}
|
|
510
|
+
// Rich first-use fallback: the call errored on a tool we just
|
|
511
|
+
// auto-loaded, so the model formed its args blind. Append the tool's
|
|
512
|
+
// full instructions so the next round can correct instead of guessing.
|
|
513
|
+
if (autoLoaded && isError) {
|
|
514
|
+
result = await appendAutoLoadInstructions(call.name, result, ctx);
|
|
515
|
+
}
|
|
516
|
+
const durationMs = Date.now() - toolStart;
|
|
517
|
+
sendWsToolUse(socket, msg.conversationId, call.name, isError ? 'error' : 'done', call.arguments, result, durationMs, ctx.touchedFiles?.get(call.arguments));
|
|
518
|
+
emitEvent({
|
|
519
|
+
kind: 'tool.end',
|
|
520
|
+
agentSlug: agent.slug,
|
|
521
|
+
tool: call.name,
|
|
522
|
+
conversationId: msg.conversationId,
|
|
523
|
+
durMs: durationMs,
|
|
524
|
+
error: isError ? result.slice(0, 200) : undefined,
|
|
525
|
+
});
|
|
526
|
+
const inlineImages = pendingToolImages.splice(0);
|
|
527
|
+
return inlineImages.length > 0
|
|
528
|
+
? { result, isError, durationMs, images: inlineImages }
|
|
529
|
+
: { result, isError, durationMs };
|
|
530
|
+
};
|
|
531
|
+
// 6. Loop hooks.
|
|
532
|
+
// - `onEmptyToolCalls` catches the round-after-a-tool where the model
|
|
533
|
+
// returns no tool calls AND no text (it emitted only reasoning, or
|
|
534
|
+
// the studio stream closed with no content chunk). Left alone the
|
|
535
|
+
// loop would end with an empty reply and the runner would report a
|
|
536
|
+
// successful-but-blank chat turn, which reads as "the agent just
|
|
537
|
+
// went idle". We nudge it once to actually respond; if it comes back
|
|
538
|
+
// empty a second time we let the loop end and the fallback below
|
|
539
|
+
// surfaces a message instead of a void. A non-empty reply is passed
|
|
540
|
+
// through untouched (return undefined -> loop ends normally).
|
|
541
|
+
// - Debug-only `onInferenceInput/Output` mirror the verbose logs.
|
|
542
|
+
// Drain any `chat:steer` messages the studio pushed since the last round
|
|
543
|
+
// and frame them as a clear instruction. A BARE user message (just the
|
|
544
|
+
// steer text) lands as noise right after the agent's tool results and the
|
|
545
|
+
// model frequently replies with nothing -> empty turn -> fallback. Framing
|
|
546
|
+
// it as "the user just sent this, address it and reply" reliably elicits a
|
|
547
|
+
// real reply. Returns null when nothing is queued.
|
|
548
|
+
const drainSteerInstruction = () => {
|
|
549
|
+
const steers = pendingChatSteers.get(msg.conversationId);
|
|
550
|
+
if (!steers || steers.length === 0)
|
|
551
|
+
return null;
|
|
552
|
+
pendingChatSteers.delete(msg.conversationId);
|
|
553
|
+
const body = steerBody(steers);
|
|
554
|
+
// The lines waiting above the input (an id) move into the transcript
|
|
555
|
+
// here, where they were read.
|
|
556
|
+
sendWsChatSteerApplied(socket, msg.conversationId, steerIds(steers));
|
|
557
|
+
answerSteer = true;
|
|
558
|
+
emitEvent({ kind: 'note', level: 'info', channel: 'chat', agentSlug: agent.slug, conversationId: msg.conversationId, message: `applied ${steers.length} steer(s)` });
|
|
559
|
+
return `The user sent a new message while you were still replying:\n\n${body}\n\nTake it into account and reply to the user now.`;
|
|
560
|
+
};
|
|
561
|
+
let emptyReplyNudged = false;
|
|
562
|
+
// Which budget notices this turn has already spent. One Set per turn, so
|
|
563
|
+
// each notice fires at most once however many rounds the turn runs for.
|
|
564
|
+
const budgetNoticesSent = new Set();
|
|
565
|
+
const hooks = {
|
|
566
|
+
// - `onRoundStart` drains steers queued during a TOOL round and injects
|
|
567
|
+
// them before the next inference, so a message typed while the agent
|
|
568
|
+
// is working is picked up at its next step (like Claude). The
|
|
569
|
+
// plain-reply case is handled in `onEmptyToolCalls` below - a steer
|
|
570
|
+
// that lands during the final no-tool round would otherwise be dropped
|
|
571
|
+
// because the loop breaks before the next `onRoundStart`.
|
|
572
|
+
// A steer and a budget notice can both come due on the same round.
|
|
573
|
+
// Both go, joined: dropping either one loses something the agent
|
|
574
|
+
// needs, and the steer is a person talking. The clock is the SAME one
|
|
575
|
+
// the `max-loop-ms` breaker reads (`startedAt`, handed to the loop as
|
|
576
|
+
// `startedAtMs` below), or the agent would be told it has time left on
|
|
577
|
+
// a budget already spent. Only a room gets the clock: an ordinary chat
|
|
578
|
+
// has one person in it who can see a reply is taking a while.
|
|
579
|
+
onRoundStart: () => {
|
|
580
|
+
const parts = [
|
|
581
|
+
drainSteerInstruction(),
|
|
582
|
+
inMeeting ? budgetNotice(Date.now() - startedAt, maxLoopMs, budgetNoticesSent) : null,
|
|
583
|
+
].filter((p) => !!p);
|
|
584
|
+
return parts.length > 0 ? { injectUserMessage: parts.join('\n\n') } : undefined;
|
|
585
|
+
},
|
|
586
|
+
// - `hasPendingSteer` lets the loop cut a tool round short once a
|
|
587
|
+
// steer is queued, so it lands after one tool instead of all of them.
|
|
588
|
+
hasPendingSteer: () => (pendingChatSteers.get(msg.conversationId)?.length ?? 0) > 0,
|
|
589
|
+
onEmptyToolCalls: (round, reply) => {
|
|
590
|
+
// A steer that arrived during THIS round (which produced a plain reply,
|
|
591
|
+
// so `onRoundStart` won't run again) must be consumed here or it's lost.
|
|
592
|
+
// Commit the agent's reply, then run another round to address the steer.
|
|
593
|
+
// That reply answered what came before the steer and the next round's
|
|
594
|
+
// replaces it: sent as a message first, so it stands above the steer
|
|
595
|
+
// it did not see (the ack goes out in the drain, after it).
|
|
596
|
+
const kept = reply.trim();
|
|
597
|
+
if (!inMeeting && kept && (pendingChatSteers.get(msg.conversationId)?.length ?? 0) > 0) {
|
|
598
|
+
lastSteerReply = kept;
|
|
599
|
+
sendWsChatNarration(socket, msg.conversationId, kept, round, true);
|
|
600
|
+
}
|
|
601
|
+
const instruction = drainSteerInstruction();
|
|
602
|
+
if (instruction)
|
|
603
|
+
return { continueWithUserMessage: instruction };
|
|
604
|
+
if (reply.trim())
|
|
605
|
+
return;
|
|
606
|
+
if (emptyReplyNudged)
|
|
607
|
+
return;
|
|
608
|
+
emptyReplyNudged = true;
|
|
609
|
+
emitEvent({
|
|
610
|
+
kind: 'note',
|
|
611
|
+
level: 'info',
|
|
612
|
+
channel: 'chat',
|
|
613
|
+
agentSlug: agent.slug,
|
|
614
|
+
conversationId: msg.conversationId,
|
|
615
|
+
message: `empty round ${round} (no reply, no tool call) - nudging once`,
|
|
616
|
+
});
|
|
617
|
+
return {
|
|
618
|
+
continueWithUserMessage: 'Your last turn produced no message and no tool call. If the task is complete, reply to the user with a short summary of what you did. If it is not complete, continue working.',
|
|
619
|
+
};
|
|
620
|
+
},
|
|
621
|
+
};
|
|
622
|
+
// What the agent says to the room while it works, kept.
|
|
623
|
+
//
|
|
624
|
+
// A room clears the live bubble on the round's first `chat:tool-use` (it
|
|
625
|
+
// has to, or the sentence before the call glues onto the one after it) and
|
|
626
|
+
// the tool then runs for seconds. Without this the words are on screen
|
|
627
|
+
// only until the agent reaches for its next tool, and after a reload the
|
|
628
|
+
// whole working stretch is a gap with an answer at the end of it.
|
|
629
|
+
//
|
|
630
|
+
// Fire-and-forget, and that is deliberate: `wsSend` queues synchronously,
|
|
631
|
+
// so the frame is on the wire before the tool call that clears the bubble
|
|
632
|
+
// without making the loop wait on a socket round-trip. The studio's own
|
|
633
|
+
// narrator awaits its insert instead, because there the write IS the send.
|
|
634
|
+
//
|
|
635
|
+
// Only where the studio keeps them (a room, a code session: the frame's
|
|
636
|
+
// `keepsAsides`). `lastNarrated` is what the studio has therefore already
|
|
637
|
+
// been told, which is what the salvage check at the end of the turn needs
|
|
638
|
+
// - not `loopResult`'s own `lastNarration`, which counts asides this never
|
|
639
|
+
// shipped.
|
|
640
|
+
if (inMeeting || msg.keepsAsides) {
|
|
641
|
+
hooks.onAssistantNarration = (round, narration) => {
|
|
642
|
+
const text = narration.trim();
|
|
643
|
+
if (!text)
|
|
644
|
+
return;
|
|
645
|
+
lastNarrated = text;
|
|
646
|
+
sendWsChatNarration(socket, msg.conversationId, text, round);
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
else {
|
|
650
|
+
// Outside a room only the answer to a steer is kept: "how far are
|
|
651
|
+
// we?" is usually answered in the sentence before the next tool call,
|
|
652
|
+
// which otherwise lives only in the bubble that call clears.
|
|
653
|
+
hooks.onAssistantNarration = (round, narration) => {
|
|
654
|
+
const text = narration.trim();
|
|
655
|
+
if (!answerSteer || !text)
|
|
656
|
+
return;
|
|
657
|
+
answerSteer = false;
|
|
658
|
+
lastSteerReply = text;
|
|
659
|
+
sendWsChatNarration(socket, msg.conversationId, text, round, true);
|
|
660
|
+
};
|
|
661
|
+
}
|
|
662
|
+
if (debug) {
|
|
663
|
+
hooks.onInferenceInput = (round, messages, tools) => {
|
|
664
|
+
postStudioLog(config.studioUrl, agent.token, {
|
|
665
|
+
level: 'debug',
|
|
666
|
+
type: 'chat.inference.input',
|
|
667
|
+
message: `Inference input - round ${round}, ${messages.length} message(s), ${tools.length} tool(s)`,
|
|
668
|
+
data: { round, messages, tools },
|
|
669
|
+
conversationUid: msg.conversationId,
|
|
670
|
+
userUuid: msg.userUuid,
|
|
671
|
+
});
|
|
672
|
+
};
|
|
673
|
+
hooks.onInferenceOutput = (round, result) => {
|
|
674
|
+
postStudioLog(config.studioUrl, agent.token, {
|
|
675
|
+
level: 'debug',
|
|
676
|
+
type: 'chat.inference.output',
|
|
677
|
+
message: `Inference output - round ${round}${result.toolCalls.length ? `, ${result.toolCalls.length} tool call(s)` : ''}`,
|
|
678
|
+
data: {
|
|
679
|
+
round,
|
|
680
|
+
message: result.message,
|
|
681
|
+
toolCalls: result.toolCalls,
|
|
682
|
+
usage: result.usage,
|
|
683
|
+
model: result.model,
|
|
684
|
+
},
|
|
685
|
+
conversationUid: msg.conversationId,
|
|
686
|
+
userUuid: msg.userUuid,
|
|
687
|
+
});
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
// 7. Run the agentic loop. `startedAtMs` is set to the chat handler's
|
|
691
|
+
// own start so wall-clock time counts against `maxLoopMs` - and it is
|
|
692
|
+
// the same `startedAt` the budget notices above measure against, so
|
|
693
|
+
// what the agent is told and what the breaker enforces cannot drift.
|
|
694
|
+
const loopResult = await runAgenticLoop({
|
|
695
|
+
systemPrompt,
|
|
696
|
+
initialMessages: historyMessages,
|
|
697
|
+
registry,
|
|
698
|
+
callInference,
|
|
699
|
+
...(callSummaryInference ? { callSummaryInference } : {}),
|
|
700
|
+
executeTool,
|
|
701
|
+
...(spillToolOutput ? { spillToolOutput: (callId, toolName, text) => spillToolOutput(scratchRoot, callId, toolName, text) } : {}),
|
|
702
|
+
limits: {
|
|
703
|
+
maxRounds,
|
|
704
|
+
maxLoopMs,
|
|
705
|
+
toolResultTruncateChars: truncateChars,
|
|
706
|
+
maxCostMicros,
|
|
707
|
+
contextWindowTokens: msg.agentConfig?.contextWindowTokens,
|
|
708
|
+
// Meetings only: a room is held for as long as the turn runs, and the
|
|
709
|
+
// between-rounds check cannot interrupt a generation already in
|
|
710
|
+
// flight. In an ordinary chat nobody is blocked, so cutting a call
|
|
711
|
+
// there would discard work to buy nothing.
|
|
712
|
+
abortInferenceAtBudget: inMeeting,
|
|
713
|
+
},
|
|
714
|
+
signal: abortController.signal,
|
|
715
|
+
startedAtMs: startedAt,
|
|
716
|
+
// The todo list is on screen beside the chat: keep it current.
|
|
717
|
+
nudgeTodos: true,
|
|
718
|
+
hooks,
|
|
719
|
+
});
|
|
720
|
+
markChatTurnDone(agent.slug, msg.conversationId);
|
|
721
|
+
totalInputTokens = loopResult.totalUsage.inputTokens;
|
|
722
|
+
totalOutputTokens = loopResult.totalUsage.outputTokens;
|
|
723
|
+
totalCostMicros = loopResult.totalUsage.costMicros;
|
|
724
|
+
// A turn that ended on a question has said what it had to say with it
|
|
725
|
+
// (the card is its message): never post the loop's reply on that stop.
|
|
726
|
+
finalReply = loopResult.stopReason === 'awaiting-user' ? '' : loopResult.finalReply;
|
|
727
|
+
finalModel = loopResult.finalModel;
|
|
728
|
+
// A cancelled turn is NOT a failure mode to paper over: the user stopped it
|
|
729
|
+
// on purpose and the studio already finalises it (`chat:cancel` fails the
|
|
730
|
+
// queue entry and frees the slot). Ship only what the agent had actually
|
|
731
|
+
// authored before the stop (the loop salvages its last narration), and stay
|
|
732
|
+
// silent when it authored nothing - mirrors the abort branch of the catch
|
|
733
|
+
// below, which never sends `chat:done` either. Injecting a canned reply here
|
|
734
|
+
// made every stop-during-a-tool-call land as "I finished this turn without a
|
|
735
|
+
// message to send", since `cutoffNotice` has no text for a user abort.
|
|
736
|
+
const aborted = loopResult.stopReason === 'aborted';
|
|
737
|
+
// The turn ended on a question (studio_ask in a chat). The studio already wrote
|
|
738
|
+
// it into the chat as this agent's message, so there is nothing to add -
|
|
739
|
+
// but `chat:done` still goes out, empty, because that is what completes
|
|
740
|
+
// the queue entry and lets the agent go idle. Mirrors `resolveChatReply`.
|
|
741
|
+
const askedUser = loopResult.stopReason === 'awaiting-user';
|
|
742
|
+
// Two failure modes to make legible instead of shipping a blank or
|
|
743
|
+
// misleading turn:
|
|
744
|
+
// - empty reply: the model closed with no text/tool call (reasoning only,
|
|
745
|
+
// or a stream with no content chunk) that the loop could not salvage.
|
|
746
|
+
// - breaker cutoff: a round/time/cost cap stopped the turn while the agent
|
|
747
|
+
// was still calling tools. Any narration on that last round is mid-work,
|
|
748
|
+
// so append the cutoff notice even when a reply exists - otherwise it
|
|
749
|
+
// reads as a finished answer and hides the cutoff.
|
|
750
|
+
// Mirrors the studio side in run-chat.ts and the task handler in handle-task.ts.
|
|
751
|
+
//
|
|
752
|
+
// What that notice ASKS for depends on where the turn was spoken, which
|
|
753
|
+
// only the studio knows: in a one-to-one chat the next message comes back
|
|
754
|
+
// to this agent, so "reply continue" works; in a meeting the next turn is
|
|
755
|
+
// routed and may never reach it. `inMeeting` was resolved once, up with the
|
|
756
|
+
// limits, and the mid-turn budget notices read the same value.
|
|
757
|
+
const notice = aborted
|
|
758
|
+
? null
|
|
759
|
+
: cutoffNotice(loopResult.stopReason, loopResult.rounds, inMeeting);
|
|
760
|
+
// A room adds one case to the two above: when the model authored nothing
|
|
761
|
+
// at the end, the loop salvages its last narration into `finalReply` - and
|
|
762
|
+
// in a room that line was sent as `chat:narration` the moment it was said,
|
|
763
|
+
// so it is already a row everyone has been looking at for minutes.
|
|
764
|
+
// Shipping it again as the reply prints the same sentence twice, one
|
|
765
|
+
// bubble apart. Only what is genuinely NEW is persisted (a cutoff notice,
|
|
766
|
+
// or nothing at all), and the words are handed over separately as
|
|
767
|
+
// `spokenContent` so the room still routes its follow-up on what was said
|
|
768
|
+
// rather than on a notice. Mirrors `resolveChatReply`'s `alreadyInRoom` on
|
|
769
|
+
// the studio side.
|
|
770
|
+
//
|
|
771
|
+
// An abort is left to the branch below: the studio finalises a cancelled
|
|
772
|
+
// turn itself and the runner sends no `chat:done` at all, so there is
|
|
773
|
+
// nothing here to deduplicate.
|
|
774
|
+
// Outside a room the same goes for the answer to a steer, sent as its own
|
|
775
|
+
// message the moment it was said.
|
|
776
|
+
const said = finalReply.trim();
|
|
777
|
+
const alreadySent = !!said && (said === lastNarrated || said === lastSteerReply);
|
|
778
|
+
const alreadyInRoom = !aborted && alreadySent;
|
|
779
|
+
const spokenContent = alreadyInRoom
|
|
780
|
+
? [finalReply, notice].filter((t) => !!t && !!t.trim()).join('\n\n')
|
|
781
|
+
: undefined;
|
|
782
|
+
if (alreadyInRoom) {
|
|
783
|
+
emitEvent({
|
|
784
|
+
kind: 'note',
|
|
785
|
+
level: 'info',
|
|
786
|
+
channel: 'chat',
|
|
787
|
+
agentSlug: agent.slug,
|
|
788
|
+
conversationId: msg.conversationId,
|
|
789
|
+
message: `turn ended on an aside already in the room${notice ? ' - persisting the cutoff notice only' : ' - nothing left to persist'}`,
|
|
790
|
+
});
|
|
791
|
+
finalReply = notice ?? '';
|
|
792
|
+
}
|
|
793
|
+
else if (askedUser) {
|
|
794
|
+
emitEvent({
|
|
795
|
+
kind: 'note',
|
|
796
|
+
level: 'info',
|
|
797
|
+
channel: 'chat',
|
|
798
|
+
agentSlug: agent.slug,
|
|
799
|
+
conversationId: msg.conversationId,
|
|
800
|
+
message: 'turn ended on a question to the user - idle until they answer',
|
|
801
|
+
});
|
|
802
|
+
finalReply = '';
|
|
803
|
+
}
|
|
804
|
+
else if (aborted) {
|
|
805
|
+
emitEvent({
|
|
806
|
+
kind: 'note',
|
|
807
|
+
level: 'info',
|
|
808
|
+
channel: 'chat',
|
|
809
|
+
agentSlug: agent.slug,
|
|
810
|
+
conversationId: msg.conversationId,
|
|
811
|
+
message: `turn cancelled after ${loopResult.rounds} round(s) - ${said && !alreadySent ? 'shipping salvaged narration' : 'no new authored text, staying silent'}`,
|
|
812
|
+
});
|
|
813
|
+
// The salvaged line is an aside the studio already stored (a room, a
|
|
814
|
+
// code session) or the answer to a steer it already has: shipping it
|
|
815
|
+
// again wrote the same line twice, one row apart.
|
|
816
|
+
if (alreadySent)
|
|
817
|
+
finalReply = '';
|
|
818
|
+
}
|
|
819
|
+
else if (!finalReply.trim()) {
|
|
820
|
+
emitEvent({
|
|
821
|
+
kind: 'note',
|
|
822
|
+
level: 'warn',
|
|
823
|
+
channel: 'chat',
|
|
824
|
+
agentSlug: agent.slug,
|
|
825
|
+
conversationId: msg.conversationId,
|
|
826
|
+
message: `agent ended its turn with no reply (stopReason: ${loopResult.stopReason}, rounds: ${loopResult.rounds}) - using fallback message`,
|
|
827
|
+
});
|
|
828
|
+
finalReply = notice ?? GENERIC_EMPTY_REPLY;
|
|
829
|
+
}
|
|
830
|
+
else if (notice) {
|
|
831
|
+
emitEvent({
|
|
832
|
+
kind: 'note',
|
|
833
|
+
level: 'warn',
|
|
834
|
+
channel: 'chat',
|
|
835
|
+
agentSlug: agent.slug,
|
|
836
|
+
conversationId: msg.conversationId,
|
|
837
|
+
message: `agent turn cut off mid-work (stopReason: ${loopResult.stopReason}, rounds: ${loopResult.rounds}) - appending cutoff notice`,
|
|
838
|
+
});
|
|
839
|
+
finalReply = appendCutoffNotice(finalReply, notice);
|
|
840
|
+
}
|
|
841
|
+
// Blank when the turn was cancelled before the agent wrote anything, and
|
|
842
|
+
// when a room's turn ended on an aside that is already a row with no
|
|
843
|
+
// cutoff notice to add. The second one must still be SENT: the studio
|
|
844
|
+
// completes the queue entry and hands the floor back on this frame, and an
|
|
845
|
+
// empty `content` is a shape it already accepts (a turn of pure tool
|
|
846
|
+
// calls), and so is a turn that ended on a question. Only the cancel stays
|
|
847
|
+
// silent - the studio finalises that itself.
|
|
848
|
+
if ((finalReply.trim() || alreadyInRoom || askedUser) && !supersededChatRuns.has(abortController)) {
|
|
849
|
+
sendWsChatDone(socket, msg.conversationId, finalReply, {
|
|
850
|
+
inputTokens: totalInputTokens,
|
|
851
|
+
outputTokens: totalOutputTokens,
|
|
852
|
+
costMicros: totalCostMicros,
|
|
853
|
+
// Last round's input size = real context occupancy for the meter.
|
|
854
|
+
contextTokens: loopResult.totalUsage.contextTokens,
|
|
855
|
+
model: finalModel,
|
|
856
|
+
}, attachments.length > 0 ? attachments : undefined, loopResult.finalThoughts ?? undefined, spokenContent);
|
|
857
|
+
}
|
|
858
|
+
emitEvent(aborted
|
|
859
|
+
? { kind: 'dispatch.cancelled', channel: 'chat', agentSlug: agent.slug, conversationId: msg.conversationId }
|
|
860
|
+
: {
|
|
861
|
+
kind: 'dispatch.finished',
|
|
862
|
+
channel: 'chat',
|
|
863
|
+
agentSlug: agent.slug,
|
|
864
|
+
conversationId: msg.conversationId,
|
|
865
|
+
durMs: Date.now() - startedAt,
|
|
866
|
+
inputTokens: totalInputTokens,
|
|
867
|
+
outputTokens: totalOutputTokens,
|
|
868
|
+
costMicros: totalCostMicros,
|
|
869
|
+
model: finalModel,
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
catch (err) {
|
|
873
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
874
|
+
if (abortController.signal.aborted) {
|
|
875
|
+
emitEvent({ kind: 'dispatch.cancelled', channel: 'chat', agentSlug: agent.slug, conversationId: msg.conversationId });
|
|
876
|
+
}
|
|
877
|
+
else {
|
|
878
|
+
emitEvent({ kind: 'dispatch.failed', channel: 'chat', agentSlug: agent.slug, conversationId: msg.conversationId, error: message });
|
|
879
|
+
sendWsChatError(socket, msg.conversationId, message);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
finally {
|
|
883
|
+
run.end();
|
|
884
|
+
// Only while this turn is still the conversation's: a newer one owns the
|
|
885
|
+
// key now, its abort and its steers.
|
|
886
|
+
if (activeChatAborts.get(msg.conversationId) === abortController) {
|
|
887
|
+
activeChatAborts.delete(msg.conversationId);
|
|
888
|
+
// Drop any steer that landed after the final round so it can't leak into
|
|
889
|
+
// the next turn of this same conversation (the key is reused across turns).
|
|
890
|
+
pendingChatSteers.delete(msg.conversationId);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
};
|
|
894
|
+
}
|