somora 2026.930.1
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/LICENSE +21 -0
- package/README.md +364 -0
- package/bin/node-version.d.mts +3 -0
- package/bin/node-version.mjs +45 -0
- package/bin/somora.mjs +77 -0
- package/config.example.yaml +896 -0
- package/docs/agents.md +677 -0
- package/docs/api.md +3194 -0
- package/docs/browser.md +317 -0
- package/docs/builder.md +331 -0
- package/docs/cache-strategy.md +373 -0
- package/docs/compaction.md +253 -0
- package/docs/display.md +154 -0
- package/docs/dream-phases.md +891 -0
- package/docs/files.md +387 -0
- package/docs/imagegen.md +366 -0
- package/docs/images/somora-hero.png +0 -0
- package/docs/images/somora-mobile-2026-05-23.png +0 -0
- package/docs/images/somora-tui-2026-05-23.png +0 -0
- package/docs/images/somora-web-2026-05-23.png +0 -0
- package/docs/index.md +178 -0
- package/docs/lsp.md +93 -0
- package/docs/mcp.md +332 -0
- package/docs/memory.md +407 -0
- package/docs/mobile.md +310 -0
- package/docs/models.md +379 -0
- package/docs/projects.md +425 -0
- package/docs/realtime-voice.md +293 -0
- package/docs/resources.md +230 -0
- package/docs/sampling.md +128 -0
- package/docs/security.md +189 -0
- package/docs/sentinel.md +295 -0
- package/docs/setup.md +1217 -0
- package/docs/skills.md +501 -0
- package/docs/team.md +189 -0
- package/docs/thinking.md +463 -0
- package/docs/tmux.md +399 -0
- package/docs/tools.md +117 -0
- package/docs/videogen.md +191 -0
- package/docs/voice.md +288 -0
- package/docs/web.md +893 -0
- package/docs/wiki.md +583 -0
- package/npm-shrinkwrap.json +5670 -0
- package/package.json +116 -0
- package/src/attachments/store.ts +196 -0
- package/src/browser/change-stream.ts +31 -0
- package/src/browser/display.ts +108 -0
- package/src/browser/policy.ts +121 -0
- package/src/browser/screencast.ts +374 -0
- package/src/browser/service.ts +1337 -0
- package/src/browser/session.ts +15 -0
- package/src/browser/snapshot.ts +40 -0
- package/src/cli/auth.ts +117 -0
- package/src/cli/codex.ts +41 -0
- package/src/cli/lsp.ts +71 -0
- package/src/cli/resolvers/clawhub.ts +400 -0
- package/src/cli/setup.ts +835 -0
- package/src/cli/skill.ts +619 -0
- package/src/cli/somora.ts +548 -0
- package/src/cli/systemd-unit.ts +72 -0
- package/src/cli/team.ts +148 -0
- package/src/cli/tui/activity-stream.ts +121 -0
- package/src/cli/tui/api.ts +479 -0
- package/src/cli/tui/app.tsx +1169 -0
- package/src/cli/tui/autocomplete.tsx +55 -0
- package/src/cli/tui/commands.ts +913 -0
- package/src/cli/tui/dream-glyphs.ts +22 -0
- package/src/cli/tui/footer.tsx +15 -0
- package/src/cli/tui/format.ts +28 -0
- package/src/cli/tui/header.tsx +279 -0
- package/src/cli/tui/index.tsx +120 -0
- package/src/cli/tui/markdown.tsx +63 -0
- package/src/cli/tui/sampling.ts +162 -0
- package/src/cli/tui/separator.tsx +13 -0
- package/src/cli/tui/state.ts +42 -0
- package/src/cli/tui/stream.ts +330 -0
- package/src/cli/tui/thinking-text.ts +54 -0
- package/src/cli/tui/turn-views.tsx +499 -0
- package/src/cli/tui/types.ts +410 -0
- package/src/cli/tui/work-queue.ts +161 -0
- package/src/cli/update-args.ts +55 -0
- package/src/cli/wiki.ts +406 -0
- package/src/compaction/index.ts +28 -0
- package/src/compaction/midturn.ts +210 -0
- package/src/compaction/policy.ts +154 -0
- package/src/compaction/summarize.ts +691 -0
- package/src/compaction/template.ts +90 -0
- package/src/compaction/types.ts +148 -0
- package/src/config/loader.ts +276 -0
- package/src/config/reload.ts +43 -0
- package/src/config/types.ts +2292 -0
- package/src/dream/deep-actions.ts +324 -0
- package/src/dream/deep-dispatcher.ts +237 -0
- package/src/dream/deep-llm.ts +388 -0
- package/src/dream/deep-prompts.ts +106 -0
- package/src/dream/deep-runner.ts +757 -0
- package/src/dream/deep-skip-cache.ts +199 -0
- package/src/dream/deep-worker.ts +229 -0
- package/src/dream/json-salvage.ts +34 -0
- package/src/dream/judge.ts +188 -0
- package/src/dream/loop-state.ts +286 -0
- package/src/dream/lucid-actions.ts +303 -0
- package/src/dream/lucid-batches.ts +94 -0
- package/src/dream/lucid-prompt.ts +82 -0
- package/src/dream/lucid-runner.ts +744 -0
- package/src/dream/lucid-storage.ts +277 -0
- package/src/dream/lucid-structure.ts +102 -0
- package/src/dream/lucid-types.ts +137 -0
- package/src/dream/lucid-worker.ts +224 -0
- package/src/dream/rem-dedup.ts +502 -0
- package/src/dream/rem-extract.ts +782 -0
- package/src/dream/rem-reset-run.ts +67 -0
- package/src/dream/rem-runner.ts +696 -0
- package/src/dream/rem-worker.ts +527 -0
- package/src/dream/review-window.ts +71 -0
- package/src/dream/scheduler-state.ts +129 -0
- package/src/dream/storage.ts +497 -0
- package/src/dream/types.ts +133 -0
- package/src/dream/wiki-context.ts +133 -0
- package/src/engine/a2a.ts +33 -0
- package/src/engine/availability.ts +63 -0
- package/src/engine/claude-cli.ts +969 -0
- package/src/engine/codex-app-server-client.ts +294 -0
- package/src/engine/codex-bin.ts +49 -0
- package/src/engine/codex-cli.ts +1014 -0
- package/src/engine/codex-dynamic-tools.ts +239 -0
- package/src/engine/codex-home.ts +63 -0
- package/src/engine/codex-thread-config.ts +74 -0
- package/src/engine/context-budget.ts +257 -0
- package/src/engine/engine-meta-labels.ts +211 -0
- package/src/engine/grok-cli.ts +941 -0
- package/src/engine/inline-think.ts +59 -0
- package/src/engine/model-availability.ts +105 -0
- package/src/engine/openai-compatible.ts +2464 -0
- package/src/engine/reasoning-retry.ts +83 -0
- package/src/engine/registry.ts +13 -0
- package/src/engine/replay.ts +195 -0
- package/src/engine/sampling.ts +90 -0
- package/src/engine/thinking-params.ts +264 -0
- package/src/engine/types.ts +269 -0
- package/src/engine/user-tag.ts +24 -0
- package/src/imagegen/aspect.ts +128 -0
- package/src/imagegen/generate.ts +642 -0
- package/src/imagegen/references.ts +75 -0
- package/src/imagegen/types.ts +154 -0
- package/src/lsp/client.ts +183 -0
- package/src/lsp/fake-server.helper.mjs +42 -0
- package/src/lsp/format.ts +29 -0
- package/src/lsp/index.ts +21 -0
- package/src/lsp/manager.ts +238 -0
- package/src/lsp/registry.ts +151 -0
- package/src/mcp/config.ts +117 -0
- package/src/mcp/hub/audit.ts +55 -0
- package/src/mcp/hub/bridge.ts +115 -0
- package/src/mcp/hub/catalog.ts +69 -0
- package/src/mcp/hub/credentials.ts +406 -0
- package/src/mcp/hub/env-expand.ts +14 -0
- package/src/mcp/hub/manager.ts +770 -0
- package/src/mcp/hub/normalize.ts +213 -0
- package/src/mcp/server.ts +368 -0
- package/src/mcp/tool-schema.ts +20 -0
- package/src/media/capabilities.ts +392 -0
- package/src/media/records.ts +175 -0
- package/src/media/store.ts +217 -0
- package/src/media/types.ts +69 -0
- package/src/memory/chunking.ts +168 -0
- package/src/memory/embeddings.ts +262 -0
- package/src/memory/index.ts +15 -0
- package/src/memory/inject.ts +197 -0
- package/src/memory/manager.ts +996 -0
- package/src/memory/registry.ts +176 -0
- package/src/memory/rescan.ts +101 -0
- package/src/memory/retrieval.ts +586 -0
- package/src/memory/shared-index.ts +372 -0
- package/src/memory/slug.ts +39 -0
- package/src/memory/storage.ts +385 -0
- package/src/memory/watcher.ts +134 -0
- package/src/multimodal/blocks.ts +101 -0
- package/src/multimodal/dimensions.ts +214 -0
- package/src/multimodal/load.ts +86 -0
- package/src/multimodal/mime.ts +135 -0
- package/src/multimodal/pdf-render.ts +80 -0
- package/src/multimodal/user-content.ts +266 -0
- package/src/persona/files.ts +144 -0
- package/src/persona/loader.ts +598 -0
- package/src/persona/skill-gating-store.ts +59 -0
- package/src/persona/tool-gating-store.ts +113 -0
- package/src/projects/focus.ts +186 -0
- package/src/projects/prompt-block.ts +106 -0
- package/src/projects/scheme.ts +107 -0
- package/src/projects/store.ts +144 -0
- package/src/projects/types.ts +73 -0
- package/src/sentinel/dispatcher.ts +97 -0
- package/src/sentinel/schedule.ts +271 -0
- package/src/sentinel/scheduler.ts +840 -0
- package/src/sentinel/store.ts +259 -0
- package/src/sentinel/types.ts +221 -0
- package/src/server/activity-stream.ts +160 -0
- package/src/server/ask-calls.ts +137 -0
- package/src/server/ask-wait-graph.ts +171 -0
- package/src/server/async-tasks.ts +199 -0
- package/src/server/builder-busy.ts +86 -0
- package/src/server/builder-prompt.ts +204 -0
- package/src/server/builder-questions.ts +117 -0
- package/src/server/builder-session.ts +249 -0
- package/src/server/chat-aborts.ts +83 -0
- package/src/server/claude-config-dir.ts +71 -0
- package/src/server/claude-credential-sync.ts +454 -0
- package/src/server/env-file.ts +100 -0
- package/src/server/env.ts +115 -0
- package/src/server/heal-session.ts +151 -0
- package/src/server/history-page.ts +46 -0
- package/src/server/index.ts +7244 -0
- package/src/server/lockfile.ts +89 -0
- package/src/server/logger.ts +67 -0
- package/src/server/logs.ts +187 -0
- package/src/server/loopback-fetch.ts +130 -0
- package/src/server/openai-client.ts +89 -0
- package/src/server/prompt-assembly.ts +334 -0
- package/src/server/restart-reconcile.ts +139 -0
- package/src/server/run-turn-fallback.ts +275 -0
- package/src/server/run-turn-types.ts +91 -0
- package/src/server/run-turn.ts +1474 -0
- package/src/server/sanitize-assistant-text.ts +112 -0
- package/src/server/session-export.ts +220 -0
- package/src/server/session-queue.ts +376 -0
- package/src/server/session-workdir.ts +49 -0
- package/src/server/sse-h2-safe.ts +61 -0
- package/src/server/sse-liveness.ts +162 -0
- package/src/server/sse-serializer.ts +161 -0
- package/src/server/start-turn.ts +249 -0
- package/src/server/steer-inbox.ts +107 -0
- package/src/server/tls-keeper.ts +153 -0
- package/src/server/tool-format.ts +167 -0
- package/src/server/turn-framing.ts +52 -0
- package/src/server/turn-origin-kind.ts +74 -0
- package/src/server/turn-origin.ts +40 -0
- package/src/server/work-ledger.ts +975 -0
- package/src/server/workspace.ts +114 -0
- package/src/setup/config-edit.ts +201 -0
- package/src/setup/presets.ts +71 -0
- package/src/setup/prompt.ts +163 -0
- package/src/setup/tailscale.ts +44 -0
- package/src/skills/bin-checks.ts +227 -0
- package/src/skills/bootstrap.ts +347 -0
- package/src/skills/env-scope.ts +175 -0
- package/src/skills/gating.ts +71 -0
- package/src/skills/lint.ts +202 -0
- package/src/skills/load.ts +368 -0
- package/src/skills/path-helpers.ts +102 -0
- package/src/skills/registry.ts +178 -0
- package/src/ssh/exec.ts +142 -0
- package/src/ssh/index.ts +12 -0
- package/src/ssh/known-hosts.ts +109 -0
- package/src/ssh/pool.ts +307 -0
- package/src/storage/sessions.ts +602 -0
- package/src/team/render.ts +149 -0
- package/src/team/resolve.ts +122 -0
- package/src/team/store.ts +124 -0
- package/src/team/types.ts +111 -0
- package/src/team/write.ts +95 -0
- package/src/testing/isolated-home.mts +46 -0
- package/src/tmux/attention-watcher.ts +272 -0
- package/src/tmux/attention.ts +336 -0
- package/src/tmux/list.ts +91 -0
- package/src/tmux/origin-store.ts +102 -0
- package/src/tmux/tui-markers.ts +267 -0
- package/src/tools/agents/ask-cancel.ts +94 -0
- package/src/tools/agents/ask-result.ts +235 -0
- package/src/tools/agents/ask.ts +704 -0
- package/src/tools/agents/builder-dispatch.ts +217 -0
- package/src/tools/agents/images.ts +104 -0
- package/src/tools/agents/index.ts +42 -0
- package/src/tools/agents/long-task-timeouts.ts +39 -0
- package/src/tools/agents/session-list.ts +136 -0
- package/src/tools/agents/session-model.ts +106 -0
- package/src/tools/agents/spawn.ts +845 -0
- package/src/tools/agents/status.ts +589 -0
- package/src/tools/browser/index.ts +6 -0
- package/src/tools/browser/ops.ts +145 -0
- package/src/tools/browser/tools.ts +184 -0
- package/src/tools/builder/short-descriptions.ts +80 -0
- package/src/tools/builder/tools.ts +222 -0
- package/src/tools/docs/index.ts +1 -0
- package/src/tools/docs/tools.ts +228 -0
- package/src/tools/dream/index.ts +11 -0
- package/src/tools/dream/tools.ts +1002 -0
- package/src/tools/exec/allowlist.ts +233 -0
- package/src/tools/exec/background-detach.helper.mts +27 -0
- package/src/tools/exec/blacklist.ts +336 -0
- package/src/tools/exec/concurrency.ts +150 -0
- package/src/tools/exec/fit-output.ts +82 -0
- package/src/tools/exec/index.ts +7 -0
- package/src/tools/exec/internal-env.ts +89 -0
- package/src/tools/exec/job-store.ts +403 -0
- package/src/tools/exec/local.ts +649 -0
- package/src/tools/exec/remote.ts +399 -0
- package/src/tools/exec/tools.ts +934 -0
- package/src/tools/file/analyze.ts +378 -0
- package/src/tools/file/index.ts +2 -0
- package/src/tools/file/local.ts +707 -0
- package/src/tools/file/lsp-hook.ts +72 -0
- package/src/tools/file/persona-guard.ts +61 -0
- package/src/tools/file/policy.ts +292 -0
- package/src/tools/file/read-format.ts +129 -0
- package/src/tools/file/remote.ts +680 -0
- package/src/tools/file/replace.ts +507 -0
- package/src/tools/file/search-window.ts +224 -0
- package/src/tools/file/tools.ts +658 -0
- package/src/tools/file/write-scope.ts +182 -0
- package/src/tools/gating.ts +106 -0
- package/src/tools/image/budget.ts +82 -0
- package/src/tools/image/index.ts +7 -0
- package/src/tools/image/tools.ts +601 -0
- package/src/tools/index.ts +99 -0
- package/src/tools/memory/index.ts +12 -0
- package/src/tools/memory/tools.ts +399 -0
- package/src/tools/projects/index.ts +1 -0
- package/src/tools/projects/tools.ts +643 -0
- package/src/tools/registry.ts +427 -0
- package/src/tools/resources/index.ts +8 -0
- package/src/tools/resources/tools.ts +176 -0
- package/src/tools/resources/visibility.ts +60 -0
- package/src/tools/sentinel/index.ts +1 -0
- package/src/tools/sentinel/tools.ts +592 -0
- package/src/tools/skill/index.ts +4 -0
- package/src/tools/skill/tools.ts +285 -0
- package/src/tools/time/index.ts +5 -0
- package/src/tools/time/tools.ts +123 -0
- package/src/tools/tmux/index.ts +1 -0
- package/src/tools/tmux/local.ts +277 -0
- package/src/tools/tmux/remote.ts +168 -0
- package/src/tools/tmux/tools.ts +1064 -0
- package/src/tools/tool-output.ts +97 -0
- package/src/tools/types.ts +227 -0
- package/src/tools/video/index.ts +1 -0
- package/src/tools/video/tools.ts +425 -0
- package/src/tools/web/fetch.ts +337 -0
- package/src/tools/web/index.ts +4 -0
- package/src/tools/web/tools.ts +186 -0
- package/src/tools/wiki/index.ts +1 -0
- package/src/tools/wiki/tools.ts +445 -0
- package/src/tts/cache-gc.ts +128 -0
- package/src/tts/prepare-for-tts.ts +114 -0
- package/src/tts/service.ts +332 -0
- package/src/types/events.ts +695 -0
- package/src/types/turn-origin.ts +53 -0
- package/src/version.ts +21 -0
- package/src/videogen/dialects.ts +222 -0
- package/src/videogen/generate.ts +484 -0
- package/src/videogen/jobs.ts +178 -0
- package/src/videogen/runner.ts +125 -0
- package/src/videogen/wake.ts +119 -0
- package/src/voice/realtime/call.ts +948 -0
- package/src/voice/realtime/consult.ts +293 -0
- package/src/voice/realtime/fake-provider.ts +134 -0
- package/src/voice/realtime/manager.ts +384 -0
- package/src/voice/realtime/openai-provider.ts +471 -0
- package/src/voice/realtime/persona.ts +227 -0
- package/src/voice/realtime/session-match.ts +116 -0
- package/src/voice/realtime/types.ts +182 -0
- package/src/wiki/conflict.ts +113 -0
- package/src/wiki/explorer.ts +578 -0
- package/src/wiki/index-builder.ts +172 -0
- package/src/wiki/language.ts +134 -0
- package/src/wiki/log-builder.ts +150 -0
- package/src/wiki/map.ts +258 -0
- package/src/wiki/migration/analyze.ts +304 -0
- package/src/wiki/migration/execute.ts +689 -0
- package/src/wiki/migration/refine.ts +402 -0
- package/src/wiki/migration/store.ts +100 -0
- package/src/wiki/move-page.ts +57 -0
- package/src/wiki/structure-file.ts +192 -0
- package/src/wiki/taxonomy.ts +140 -0
- package/src/wiki/templates.ts +163 -0
- package/src/wiki/types.ts +133 -0
- package/templates/skills/README.md +24 -0
- package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
- package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
- package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
- package/templates/skills/_templates/default/SKILL.md +25 -0
- package/templates/skills/builder-handover/SKILL.md +96 -0
- package/templates/skills/builder-handover/assets/ORDER.md +12 -0
- package/templates/skills/skill-author/SKILL.md +110 -0
- package/tsconfig.json +22 -0
- package/web/dist/assets/index-BaVv6pB2.js +631 -0
- package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
- package/web/dist/assets/index-V3FV3Z25.css +32 -0
- package/web/dist/favicon.svg +8 -0
- package/web/dist/index.html +20 -0
- package/web/package.json +36 -0
- package/web/tsconfig.json +25 -0
- package/web-mobile/dist/apple-touch-icon.png +0 -0
- package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
- package/web-mobile/dist/favicon.svg +8 -0
- package/web-mobile/dist/icon-192.png +0 -0
- package/web-mobile/dist/icon-512.png +0 -0
- package/web-mobile/dist/index.html +27 -0
- package/web-mobile/dist/manifest.webmanifest +32 -0
- package/web-mobile/dist/service-worker.js +90 -0
- package/web-mobile/package.json +28 -0
- package/web-mobile/tsconfig.json +25 -0
|
@@ -0,0 +1,975 @@
|
|
|
1
|
+
// The work ledger — one book for everything an agent has been asked to
|
|
2
|
+
// do that is not the person typing right now.
|
|
3
|
+
//
|
|
4
|
+
// Until 2026-09-13 four places knew a part of that: the ask-call
|
|
5
|
+
// registry (agent_ask), the async-task registry (sub-agents, and
|
|
6
|
+
// sentinel fires dressed up as sub-agents), the video job files, and
|
|
7
|
+
// nothing at all for a voice consult. Each had its own states, its own
|
|
8
|
+
// wake timer with its own grace and its own suppression rule, and none
|
|
9
|
+
// of them carried the text — so "what is this agent still going to do"
|
|
10
|
+
// could be counted but never shown (private/turn-triggers-birdseye.md
|
|
11
|
+
// §5, private/turn-dispatch-phase2-design.md).
|
|
12
|
+
//
|
|
13
|
+
// This module is the single answer. ask-calls.ts and async-tasks.ts
|
|
14
|
+
// keep their exported functions and shapes as VIEWS over it, so every
|
|
15
|
+
// tool, route and test that reads them keeps working unchanged.
|
|
16
|
+
//
|
|
17
|
+
// Since 2026-09-13 (private/turn-dispatch-followup-design.md) the book
|
|
18
|
+
// also remembers during WHICH item a piece of work was started, so an
|
|
19
|
+
// answer that arrives after the turn that promised it has ended still
|
|
20
|
+
// reaches the one who asked: the follow-up (see maybeFollowUp below).
|
|
21
|
+
//
|
|
22
|
+
// In memory only, like the registries it replaces. Finished items are
|
|
23
|
+
// pruned after 24 h; the book holds at most 1000 entries and drops the
|
|
24
|
+
// oldest finished ones first. Running and waiting items are never
|
|
25
|
+
// dropped.
|
|
26
|
+
|
|
27
|
+
import type { TurnOrigin } from '../types/turn-origin.ts';
|
|
28
|
+
import { triggerChatAbort } from './chat-aborts.ts';
|
|
29
|
+
import { logger } from './logger.ts';
|
|
30
|
+
import type { ChatTurnResult } from './run-turn-types.ts';
|
|
31
|
+
import { dequeueSessionWork, getSessionLockStatus } from './session-queue.ts';
|
|
32
|
+
|
|
33
|
+
export type WorkState = 'queued' | 'running' | 'done' | 'failed' | 'cancelled' | 'dequeued';
|
|
34
|
+
|
|
35
|
+
export type WorkRequester =
|
|
36
|
+
/** Another agent's session started this (agent_ask, spawn). */
|
|
37
|
+
| { agent: string; session: string }
|
|
38
|
+
/** A person, through a client. */
|
|
39
|
+
| { human: true }
|
|
40
|
+
/** The voice self of a realtime call (consult). */
|
|
41
|
+
| { voiceCall: string };
|
|
42
|
+
|
|
43
|
+
export interface WorkItem {
|
|
44
|
+
/** agent_ask: call_id · sub/sentinel: task_id · human: turnId · voice: consultId · video: job id */
|
|
45
|
+
id: string;
|
|
46
|
+
origin: TurnOrigin;
|
|
47
|
+
target: { agent: string; session: string };
|
|
48
|
+
requester?: WorkRequester;
|
|
49
|
+
state: WorkState;
|
|
50
|
+
/** First 160 characters of the text, newlines collapsed — the only
|
|
51
|
+
* trace of the prompt this book keeps. */
|
|
52
|
+
preview: string;
|
|
53
|
+
/** Full text and attachments, kept ONLY while the item waits, so a
|
|
54
|
+
* taken-back human turn can hand them back (DELETE /chat/queue). */
|
|
55
|
+
text?: string;
|
|
56
|
+
attachments?: Array<{ hash: string; name: string; mime: string; size: number }>;
|
|
57
|
+
enqueuedAt: number;
|
|
58
|
+
startedAt?: number;
|
|
59
|
+
finishedAt?: number;
|
|
60
|
+
turnId?: string;
|
|
61
|
+
result?: ChatTurnResult;
|
|
62
|
+
error?: string;
|
|
63
|
+
/** The requester is still on the line (inline wait). A wake is only
|
|
64
|
+
* for a requester that has hung up. */
|
|
65
|
+
waiting: boolean;
|
|
66
|
+
/** The requester read the result — no wake needed. */
|
|
67
|
+
resultFetched: boolean;
|
|
68
|
+
wake: 'auto' | 'never';
|
|
69
|
+
/** Nesting depth of the requester (a sub-orchestrator keeps it across
|
|
70
|
+
* the wake). */
|
|
71
|
+
parentDepth?: number;
|
|
72
|
+
/** Text a finisher hands over for the wake, when the default per-kind
|
|
73
|
+
* template does not know the item's domain (video). */
|
|
74
|
+
wakeText?: string;
|
|
75
|
+
/** Its frame — what to do about it — beside the text (turn-framing.ts). */
|
|
76
|
+
wakePrefix?: string;
|
|
77
|
+
/** Media to attach to the wake turn (a finished video). */
|
|
78
|
+
wakeMediaIds?: string[];
|
|
79
|
+
/** The item whose turn was running in the requester's session when
|
|
80
|
+
* this one was opened — the work this one belongs to. A sub lisa
|
|
81
|
+
* spawns while answering naxon's call is `startedDuring` that call;
|
|
82
|
+
* a sub she spawns in the wake turn about that sub is `startedDuring`
|
|
83
|
+
* the wake item (chainRootOf follows it back to the call). */
|
|
84
|
+
startedDuring?: string;
|
|
85
|
+
/** When the requester last read the result (markFetched). A follow-up
|
|
86
|
+
* scheduled before that read is dropped. */
|
|
87
|
+
lastFetchedAt?: number;
|
|
88
|
+
/** Follow-ups sent for this item so far (ids of the turns that carried them). */
|
|
89
|
+
followUpsSent?: number;
|
|
90
|
+
/** Who cancelled it: a person (the queue popover, /queue in the TUI)
|
|
91
|
+
* wakes the requester like a take-back does — it did not do it
|
|
92
|
+
* itself; the requesting agent (subagent_cancel) knows; a child
|
|
93
|
+
* taken down with its parent (`cascade`) has no one left to tell. */
|
|
94
|
+
cancelledBy?: 'human' | 'agent' | 'cascade';
|
|
95
|
+
/** The requester took a RUNNING call back (withdrawWork): the target
|
|
96
|
+
* was asked to stop through its steer inbox, the result — whatever
|
|
97
|
+
* the target still delivers — wakes no one. */
|
|
98
|
+
withdrawnBy?: string;
|
|
99
|
+
withdrawnAt?: number;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export type WorkItemView = Omit<WorkItem, 'text' | 'attachments' | 'result'>;
|
|
103
|
+
|
|
104
|
+
const MAX_ITEMS = 1000;
|
|
105
|
+
const TERMINAL_TTL_MS = 24 * 60 * 60 * 1000;
|
|
106
|
+
const items = new Map<string, WorkItem>();
|
|
107
|
+
|
|
108
|
+
export const REMOVED_BY_USER = 'removed from the queue by the user before it started';
|
|
109
|
+
|
|
110
|
+
export function previewOf(text: string): string {
|
|
111
|
+
return text.replace(/\s+/g, ' ').trim().slice(0, 160);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function prune(): void {
|
|
115
|
+
const now = Date.now();
|
|
116
|
+
for (const [id, it] of items) {
|
|
117
|
+
if (it.finishedAt !== undefined && now - it.finishedAt > TERMINAL_TTL_MS) items.delete(id);
|
|
118
|
+
}
|
|
119
|
+
if (items.size <= MAX_ITEMS) return;
|
|
120
|
+
const finished = [...items.values()]
|
|
121
|
+
.filter((it) => it.finishedAt !== undefined)
|
|
122
|
+
.sort((a, b) => a.finishedAt! - b.finishedAt!);
|
|
123
|
+
for (const it of finished) {
|
|
124
|
+
if (items.size <= MAX_ITEMS) break;
|
|
125
|
+
items.delete(it.id);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface OpenWorkInput {
|
|
130
|
+
id: string;
|
|
131
|
+
origin: TurnOrigin;
|
|
132
|
+
target: { agent: string; session: string };
|
|
133
|
+
requester?: WorkRequester;
|
|
134
|
+
text: string;
|
|
135
|
+
attachments?: WorkItem['attachments'];
|
|
136
|
+
/** Default true: the requester waits inline for the result. */
|
|
137
|
+
waiting?: boolean;
|
|
138
|
+
/** Default 'auto' — a finished item wakes its requester. */
|
|
139
|
+
wake?: 'auto' | 'never';
|
|
140
|
+
parentDepth?: number;
|
|
141
|
+
/** Already running (no queue wait ahead) — sentinel and spawn used to
|
|
142
|
+
* register their tasks as running from the start. */
|
|
143
|
+
running?: boolean;
|
|
144
|
+
/** Explicit `startedDuring`; by default the active item of the
|
|
145
|
+
* requester's session (tests pass it, the server lets it default). */
|
|
146
|
+
startedDuring?: string;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function openWork(input: OpenWorkInput): WorkItem {
|
|
150
|
+
prune();
|
|
151
|
+
const it: WorkItem = {
|
|
152
|
+
id: input.id,
|
|
153
|
+
origin: input.origin,
|
|
154
|
+
target: input.target,
|
|
155
|
+
...(input.requester ? { requester: input.requester } : {}),
|
|
156
|
+
state: input.running ? 'running' : 'queued',
|
|
157
|
+
preview: previewOf(input.text),
|
|
158
|
+
text: input.text,
|
|
159
|
+
...(input.attachments && input.attachments.length > 0 ? { attachments: input.attachments } : {}),
|
|
160
|
+
enqueuedAt: Date.now(),
|
|
161
|
+
...(input.running ? { startedAt: Date.now() } : {}),
|
|
162
|
+
waiting: input.waiting ?? true,
|
|
163
|
+
resultFetched: false,
|
|
164
|
+
wake: input.wake ?? 'auto',
|
|
165
|
+
...(input.parentDepth !== undefined ? { parentDepth: input.parentDepth } : {}),
|
|
166
|
+
};
|
|
167
|
+
const during = input.startedDuring ?? activeItemOf(input.requester);
|
|
168
|
+
if (during && during !== it.id) it.startedDuring = during;
|
|
169
|
+
// attention:false says "do not wake ME". When the sub was started
|
|
170
|
+
// while answering someone else — a call, another agent — that someone
|
|
171
|
+
// is told through the follow-up, and the follow-up needs the wake
|
|
172
|
+
// turn. hans opted out twice on 2026-09-13 and the caller never heard
|
|
173
|
+
// the result; the flag does not count then.
|
|
174
|
+
if (it.wake === 'never' && it.origin.kind === 'subagent') {
|
|
175
|
+
const root = chainRootOf(it);
|
|
176
|
+
if (root && root.requester && !('human' in root.requester)) {
|
|
177
|
+
it.wake = 'auto';
|
|
178
|
+
logger.info({ msg: 'work.attention_overridden', id: it.id, root: root.id, root_kind: root.origin.kind, reason: 'someone is waiting for the outcome' });
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
items.set(it.id, it);
|
|
182
|
+
return it;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The item running in the requester's session right now — the one
|
|
186
|
+
* whose turn is calling the tool that opens this item. */
|
|
187
|
+
function activeItemOf(requester: WorkRequester | undefined): string | undefined {
|
|
188
|
+
if (!requester || !('agent' in requester) || !requester.session || requester.session === '?') return undefined;
|
|
189
|
+
const st = getSessionLockStatus(requester.agent, requester.session);
|
|
190
|
+
return st.activeWorkId;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** The lock was granted; the turn runs. The waiting-only text is dropped. */
|
|
194
|
+
export function markRunning(id: string, turnId?: string): void {
|
|
195
|
+
const it = items.get(id);
|
|
196
|
+
if (!it || it.state !== 'queued') return;
|
|
197
|
+
it.state = 'running';
|
|
198
|
+
it.startedAt = Date.now();
|
|
199
|
+
if (turnId) it.turnId = turnId;
|
|
200
|
+
delete it.text;
|
|
201
|
+
delete it.attachments;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export interface FinishOptions {
|
|
205
|
+
wakeText?: string;
|
|
206
|
+
wakePrefix?: string;
|
|
207
|
+
wakeMediaIds?: string[];
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** The turn ended. Terminal states are final: a cancelled or dequeued
|
|
211
|
+
* item whose promise settles later keeps its state. */
|
|
212
|
+
export function finishWork(id: string, result: ChatTurnResult, opts: FinishOptions = {}): WorkItem | undefined {
|
|
213
|
+
const it = items.get(id);
|
|
214
|
+
if (!it) return undefined;
|
|
215
|
+
if (it.state !== 'queued' && it.state !== 'running') return it;
|
|
216
|
+
it.state = result.error ? 'failed' : 'done';
|
|
217
|
+
it.result = result;
|
|
218
|
+
if (result.error) it.error = result.error;
|
|
219
|
+
it.finishedAt = Date.now();
|
|
220
|
+
if (opts.wakeText) it.wakeText = opts.wakeText;
|
|
221
|
+
if (opts.wakePrefix) it.wakePrefix = opts.wakePrefix;
|
|
222
|
+
if (opts.wakeMediaIds && opts.wakeMediaIds.length > 0) it.wakeMediaIds = opts.wakeMediaIds;
|
|
223
|
+
delete it.text;
|
|
224
|
+
delete it.attachments;
|
|
225
|
+
settle(it);
|
|
226
|
+
if (it.origin.kind === 'wake') maybeFollowUp(it);
|
|
227
|
+
return it;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function failWork(id: string, error: string, opts: FinishOptions = {}): WorkItem | undefined {
|
|
231
|
+
const it = items.get(id);
|
|
232
|
+
if (!it) return undefined;
|
|
233
|
+
if (it.state !== 'queued' && it.state !== 'running') return it;
|
|
234
|
+
it.state = 'failed';
|
|
235
|
+
it.error = error;
|
|
236
|
+
it.finishedAt = Date.now();
|
|
237
|
+
if (opts.wakeText) it.wakeText = opts.wakeText;
|
|
238
|
+
if (opts.wakePrefix) it.wakePrefix = opts.wakePrefix;
|
|
239
|
+
delete it.text;
|
|
240
|
+
delete it.attachments;
|
|
241
|
+
settle(it);
|
|
242
|
+
if (it.origin.kind === 'wake') maybeFollowUp(it);
|
|
243
|
+
return it;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export const WAKE_WITHDRAWN = 'withdrawn: the requester read the result before the wake turn started';
|
|
247
|
+
|
|
248
|
+
export function markFetched(id: string): void {
|
|
249
|
+
const it = items.get(id);
|
|
250
|
+
if (!it) return;
|
|
251
|
+
it.resultFetched = true;
|
|
252
|
+
it.lastFetchedAt = Date.now();
|
|
253
|
+
const t = pendingWakes.get(id);
|
|
254
|
+
if (t) {
|
|
255
|
+
clearTimeout(t);
|
|
256
|
+
pendingWakes.delete(id);
|
|
257
|
+
}
|
|
258
|
+
withdrawQueuedWake(id);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* The grace lost its race: the wake was dispatched 0.6 s before the
|
|
263
|
+
* requester fetched the result, waited behind its running turn, and
|
|
264
|
+
* then told it what it already knew — twice in Rene's hand test
|
|
265
|
+
* (naxon's [agent answer], lisa's second [subagent attention],
|
|
266
|
+
* 2026-09-13). A wake that has not started yet is taken out of the
|
|
267
|
+
* queue when the result is read; one already running is left alone.
|
|
268
|
+
*/
|
|
269
|
+
function withdrawQueuedWake(ref: string): void {
|
|
270
|
+
const w = items.get(`wake-${ref}`);
|
|
271
|
+
if (!w || w.state !== 'queued') return;
|
|
272
|
+
const outcome = dequeueSessionWork(w.target.agent, w.target.session, w.id);
|
|
273
|
+
if (outcome.status !== 'removed') return;
|
|
274
|
+
w.state = 'dequeued';
|
|
275
|
+
w.error = WAKE_WITHDRAWN;
|
|
276
|
+
w.finishedAt = Date.now();
|
|
277
|
+
delete w.text;
|
|
278
|
+
logger.info({ msg: 'work.wake_withdrawn', wake: w.id, ref, target_agent: w.target.agent, target_session: w.target.session });
|
|
279
|
+
for (const l of finishListeners) l(w);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export function setWaiting(id: string, waiting: boolean): void {
|
|
283
|
+
const it = items.get(id);
|
|
284
|
+
if (it) it.waiting = waiting;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export function getWork(id: string): WorkItem | undefined {
|
|
288
|
+
return items.get(id);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export interface WorkFilter {
|
|
292
|
+
target?: { agent: string; session?: string };
|
|
293
|
+
requester?: { agent: string; session?: string };
|
|
294
|
+
states?: WorkState[];
|
|
295
|
+
kinds?: Array<TurnOrigin['kind']>;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export function listWork(filter: WorkFilter = {}): WorkItem[] {
|
|
299
|
+
const out: WorkItem[] = [];
|
|
300
|
+
for (const it of items.values()) {
|
|
301
|
+
if (filter.target) {
|
|
302
|
+
if (it.target.agent !== filter.target.agent) continue;
|
|
303
|
+
if (filter.target.session !== undefined && it.target.session !== filter.target.session) continue;
|
|
304
|
+
}
|
|
305
|
+
if (filter.requester) {
|
|
306
|
+
const r = it.requester;
|
|
307
|
+
if (!r || !('agent' in r) || r.agent !== filter.requester.agent) continue;
|
|
308
|
+
if (filter.requester.session !== undefined && r.session !== filter.requester.session) continue;
|
|
309
|
+
}
|
|
310
|
+
if (filter.states && !filter.states.includes(it.state)) continue;
|
|
311
|
+
if (filter.kinds && !filter.kinds.includes(it.origin.kind)) continue;
|
|
312
|
+
out.push(it);
|
|
313
|
+
}
|
|
314
|
+
return out.sort((a, b) => a.enqueuedAt - b.enqueuedAt);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Poll until the item leaves queued/running or `timeoutMs` passes
|
|
318
|
+
* (200 ms cadence — the caller blocks server-side instead of burning
|
|
319
|
+
* agent-loop rounds). */
|
|
320
|
+
export async function waitForWork(id: string, timeoutMs: number): Promise<WorkItem | null> {
|
|
321
|
+
const start = Date.now();
|
|
322
|
+
while (Date.now() - start < timeoutMs) {
|
|
323
|
+
const it = items.get(id);
|
|
324
|
+
if (!it) return null;
|
|
325
|
+
if (it.state !== 'queued' && it.state !== 'running') return it;
|
|
326
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
327
|
+
}
|
|
328
|
+
return items.get(id) ?? null;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// ── cancel (running) ──────────────────────────────────────────────────
|
|
332
|
+
|
|
333
|
+
export interface CancelOutcome {
|
|
334
|
+
cancelled: string[];
|
|
335
|
+
skipped: Array<{ id: string; state: WorkState }>;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Items started FROM an item's target session — the sub-agents (and
|
|
339
|
+
* asks) a sub-orchestrator itself started. */
|
|
340
|
+
export function childrenOf(target: { agent: string; session: string }): WorkItem[] {
|
|
341
|
+
return listWork({ requester: target });
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Cancel a running item AND its descendants. Marks the registry state
|
|
346
|
+
* FIRST (so the settling promise cannot overwrite it), then triggers the
|
|
347
|
+
* chat-abort signal for the target session — the same signal the Stop
|
|
348
|
+
* button uses. Breadth-first over the requester tree. Disk artifacts
|
|
349
|
+
* stay untouched.
|
|
350
|
+
*/
|
|
351
|
+
export function cancelWork(id: string, reason: string, by: 'human' | 'agent' = 'agent'): CancelOutcome | null {
|
|
352
|
+
const root = items.get(id);
|
|
353
|
+
if (!root) return null;
|
|
354
|
+
const outcome: CancelOutcome = { cancelled: [], skipped: [] };
|
|
355
|
+
const queue: WorkItem[] = [root];
|
|
356
|
+
const seen = new Set<string>();
|
|
357
|
+
while (queue.length > 0) {
|
|
358
|
+
const it = queue.shift()!;
|
|
359
|
+
if (seen.has(it.id)) continue;
|
|
360
|
+
seen.add(it.id);
|
|
361
|
+
queue.push(...childrenOf(it.target));
|
|
362
|
+
if (it.state !== 'running' && it.state !== 'queued') {
|
|
363
|
+
outcome.skipped.push({ id: it.id, state: it.state });
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
it.state = 'cancelled';
|
|
367
|
+
it.error = reason;
|
|
368
|
+
it.finishedAt = Date.now();
|
|
369
|
+
it.cancelledBy = it.id === root.id ? by : 'cascade';
|
|
370
|
+
delete it.text;
|
|
371
|
+
delete it.attachments;
|
|
372
|
+
// Ask the session queue, not the item: an item still waiting for the
|
|
373
|
+
// lock is spliced out and the session's abort signal is NOT touched
|
|
374
|
+
// — the turn running there belongs to someone else (scratch smoke
|
|
375
|
+
// 2026-09-13: cancelling a waiting sub stopped the occupant's turn).
|
|
376
|
+
// An item the queue does not hold (running, or never queued through
|
|
377
|
+
// the lock at all) gets the abort.
|
|
378
|
+
const dq = dequeueSessionWork(it.target.agent, it.target.session, it.id);
|
|
379
|
+
const wasQueued = dq.status === 'removed';
|
|
380
|
+
const abortDelivered = wasQueued ? false : triggerChatAbort(it.target.agent, it.target.session).aborted;
|
|
381
|
+
for (const l of finishListeners) l(it);
|
|
382
|
+
logger.info({
|
|
383
|
+
msg: 'work.cancelled',
|
|
384
|
+
id: it.id,
|
|
385
|
+
kind: it.origin.kind,
|
|
386
|
+
target_agent: it.target.agent,
|
|
387
|
+
target_session: it.target.session,
|
|
388
|
+
abort_delivered: abortDelivered,
|
|
389
|
+
was_queued: wasQueued,
|
|
390
|
+
reason,
|
|
391
|
+
by: it.cancelledBy,
|
|
392
|
+
});
|
|
393
|
+
outcome.cancelled.push(it.id);
|
|
394
|
+
// Stopped by a person from the requester's own queue popover (Rene,
|
|
395
|
+
// 2026-09-13, hand test 10: lisa never learnt her sub was stopped):
|
|
396
|
+
// the requester hears it like a take-back. Its own cancel, or a
|
|
397
|
+
// child taken down with its parent, wakes no one.
|
|
398
|
+
if (it.cancelledBy === 'human') scheduleWake(it);
|
|
399
|
+
}
|
|
400
|
+
return outcome;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// ── withdraw (running) ────────────────────────────────────────────────
|
|
404
|
+
|
|
405
|
+
export type WithdrawWorkOutcome =
|
|
406
|
+
| { status: 'withdrawn'; item: WorkItem }
|
|
407
|
+
| { status: 'forbidden'; item: WorkItem }
|
|
408
|
+
| { status: 'not_running'; item: WorkItem }
|
|
409
|
+
| { status: 'unknown' };
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* The soft take-back of a call that already runs (Rene, 2026-09-24:
|
|
413
|
+
* "bei 2 den weichen Weg"): only the requester may do it, only for a
|
|
414
|
+
* running item. The item stays running — the target's turn goes on
|
|
415
|
+
* until it stops by itself — but its outcome wakes no one, and the
|
|
416
|
+
* caller (the route) drops a stop message into the target's steer
|
|
417
|
+
* inbox. A hard stop of another agent's turn stays with the person.
|
|
418
|
+
* agent_ask_cancel could only take back a QUEUED call, and a free
|
|
419
|
+
* target starts a call within milliseconds, so the take-back never
|
|
420
|
+
* fit the case it was for: "I delegated, the user changed course"
|
|
421
|
+
* (hans, 2026-09-24).
|
|
422
|
+
*/
|
|
423
|
+
export function withdrawWork(id: string, by: { agent: string }): WithdrawWorkOutcome {
|
|
424
|
+
const it = items.get(id);
|
|
425
|
+
if (!it) return { status: 'unknown' };
|
|
426
|
+
const r = it.requester;
|
|
427
|
+
if (!r || !('agent' in r) || r.agent !== by.agent) return { status: 'forbidden', item: it };
|
|
428
|
+
if (it.state !== 'running') return { status: 'not_running', item: it };
|
|
429
|
+
it.wake = 'never';
|
|
430
|
+
it.withdrawnBy = by.agent;
|
|
431
|
+
it.withdrawnAt = Date.now();
|
|
432
|
+
logger.info({
|
|
433
|
+
msg: 'work.withdrawn',
|
|
434
|
+
id: it.id,
|
|
435
|
+
kind: it.origin.kind,
|
|
436
|
+
target_agent: it.target.agent,
|
|
437
|
+
target_session: it.target.session,
|
|
438
|
+
by: by.agent,
|
|
439
|
+
ranMs: it.startedAt ? Date.now() - it.startedAt : undefined,
|
|
440
|
+
});
|
|
441
|
+
return { status: 'withdrawn', item: it };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// ── dequeue (waiting) ─────────────────────────────────────────────────
|
|
445
|
+
|
|
446
|
+
export type DequeueBy = 'human' | { agent: string };
|
|
447
|
+
|
|
448
|
+
export type DequeueWorkOutcome =
|
|
449
|
+
| { status: 'removed'; item: WorkItem }
|
|
450
|
+
| { status: 'running'; item: WorkItem }
|
|
451
|
+
| { status: 'forbidden'; item: WorkItem }
|
|
452
|
+
| { status: 'unknown' };
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Take a waiting item back before it starts. A person may remove any
|
|
456
|
+
* item; an agent only what it asked for itself (Rene, 2026-09-13). The
|
|
457
|
+
* waiter's acquire() rejects with DequeuedError, so the caller that
|
|
458
|
+
* queued it never runs the turn; the item reads `dequeued` with the
|
|
459
|
+
* reason, and whoever asks for the result reads failed + reason.
|
|
460
|
+
*/
|
|
461
|
+
export function dequeueWork(id: string, by: DequeueBy): DequeueWorkOutcome {
|
|
462
|
+
const it = items.get(id);
|
|
463
|
+
if (!it) return { status: 'unknown' };
|
|
464
|
+
if (it.state === 'running') return { status: 'running', item: it };
|
|
465
|
+
if (it.state !== 'queued') return { status: 'unknown' };
|
|
466
|
+
if (by !== 'human') {
|
|
467
|
+
const r = it.requester;
|
|
468
|
+
if (!r || !('agent' in r) || r.agent !== by.agent) return { status: 'forbidden', item: it };
|
|
469
|
+
}
|
|
470
|
+
const outcome = dequeueSessionWork(it.target.agent, it.target.session, it.id);
|
|
471
|
+
if (outcome.status === 'running') return { status: 'running', item: it };
|
|
472
|
+
it.state = 'dequeued';
|
|
473
|
+
it.error = REMOVED_BY_USER;
|
|
474
|
+
it.finishedAt = Date.now();
|
|
475
|
+
logger.info({
|
|
476
|
+
msg: 'work.dequeued',
|
|
477
|
+
id: it.id,
|
|
478
|
+
kind: it.origin.kind,
|
|
479
|
+
target_agent: it.target.agent,
|
|
480
|
+
target_session: it.target.session,
|
|
481
|
+
by: by === 'human' ? 'human' : by.agent,
|
|
482
|
+
waitedMs: Date.now() - it.enqueuedAt,
|
|
483
|
+
});
|
|
484
|
+
// The text stays on the item until the caller has read it back
|
|
485
|
+
// (DELETE /chat/queue returns it), then the item is a record only.
|
|
486
|
+
for (const l of finishListeners) l(it);
|
|
487
|
+
// A requester that hung up learns about it the same way it would
|
|
488
|
+
// have learnt about the answer (Rene, 2026-09-13: naxon only found
|
|
489
|
+
// out that lisa's queue had been cleared when he went looking).
|
|
490
|
+
scheduleWake(it);
|
|
491
|
+
return { status: 'removed', item: it };
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// ── wake ─────────────────────────────────────────────────────────────
|
|
495
|
+
|
|
496
|
+
export interface WakeDispatch {
|
|
497
|
+
agent: string;
|
|
498
|
+
session: string;
|
|
499
|
+
/** The record line: what happened. */
|
|
500
|
+
text: string;
|
|
501
|
+
/** What to do about it — beside the text (turn-framing.ts). */
|
|
502
|
+
prefix: string;
|
|
503
|
+
about: 'a2a' | 'subagent' | 'job';
|
|
504
|
+
ref: string;
|
|
505
|
+
depth: number;
|
|
506
|
+
mediaIds?: string[];
|
|
507
|
+
/** Item id for the wake turn; default `wake-<ref>`. A follow-up wake
|
|
508
|
+
* about the same ref needs its own. */
|
|
509
|
+
id?: string;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** A follow-up for an agent that asked: a message from the target back
|
|
513
|
+
* to the requester, framed as the late result of that call. */
|
|
514
|
+
export interface FollowUpMessage {
|
|
515
|
+
from: { agent: string; session: string };
|
|
516
|
+
to: { agent: string; session: string };
|
|
517
|
+
callId: string;
|
|
518
|
+
text: string;
|
|
519
|
+
prefix: string;
|
|
520
|
+
/** Item id for the message turn. */
|
|
521
|
+
id: string;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export interface WorkWakeDeps {
|
|
525
|
+
/** Grace before the wake — a requester that fetches right away needs none. */
|
|
526
|
+
graceMs: number;
|
|
527
|
+
dispatchWakeTurn: (args: WakeDispatch) => Promise<void>;
|
|
528
|
+
/** Main server only: how a follow-up reaches an agent that asked
|
|
529
|
+
* (private/turn-dispatch-followup-design.md §2). Absent → no A2A
|
|
530
|
+
* follow-ups (tests, MCP child). */
|
|
531
|
+
dispatchFollowUpMessage?: (args: FollowUpMessage) => Promise<void>;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
let wakeDeps: WorkWakeDeps | null = null;
|
|
535
|
+
const pendingWakes = new Map<string, ReturnType<typeof setTimeout>>();
|
|
536
|
+
|
|
537
|
+
export function configureWorkWake(deps: WorkWakeDeps): void {
|
|
538
|
+
wakeDeps = deps;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** Items whose wake timer is still pending, for a requester session. */
|
|
542
|
+
export function pendingWakesFor(requester: { agent: string; session: string }): WorkItem[] {
|
|
543
|
+
const out: WorkItem[] = [];
|
|
544
|
+
for (const id of pendingWakes.keys()) {
|
|
545
|
+
const it = items.get(id);
|
|
546
|
+
if (!it || !it.requester || !('agent' in it.requester)) continue;
|
|
547
|
+
if (it.requester.agent === requester.agent && it.requester.session === requester.session) out.push(it);
|
|
548
|
+
}
|
|
549
|
+
return out;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
type FinishListener = (item: WorkItem) => void;
|
|
553
|
+
const finishListeners: FinishListener[] = [];
|
|
554
|
+
|
|
555
|
+
/** Hear every terminal transition: done, failed, dequeued, cancelled.
|
|
556
|
+
* The realtime voice manager listens for its consults; the server
|
|
557
|
+
* publishes queue changes to the clients. */
|
|
558
|
+
export function onWorkFinished(listener: FinishListener): () => void {
|
|
559
|
+
finishListeners.push(listener);
|
|
560
|
+
return () => {
|
|
561
|
+
const i = finishListeners.indexOf(listener);
|
|
562
|
+
if (i >= 0) finishListeners.splice(i, 1);
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function settle(it: WorkItem): void {
|
|
567
|
+
for (const l of finishListeners) l(it);
|
|
568
|
+
scheduleWake(it);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
export function aboutOf(origin: TurnOrigin): WakeDispatch['about'] | null {
|
|
572
|
+
switch (origin.kind) {
|
|
573
|
+
case 'agent':
|
|
574
|
+
return 'a2a';
|
|
575
|
+
case 'subagent':
|
|
576
|
+
return 'subagent';
|
|
577
|
+
case 'wake':
|
|
578
|
+
return origin.about === 'job' ? 'job' : null;
|
|
579
|
+
default:
|
|
580
|
+
return null;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function head(it: WorkItem, n: number): string {
|
|
585
|
+
return (it.result?.finalText ?? it.error ?? '').replace(/\s+/g, ' ').slice(0, n);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Rene's hand test, 2026-09-13: the follow-up reached naxon on time and
|
|
590
|
+
* carried lisa's wake-turn answer — "leaving it, as ordered". Lisa did
|
|
591
|
+
* not know her answer was going anywhere. The wake turn's frame now
|
|
592
|
+
* says where it goes, so the model writes it for the receiver.
|
|
593
|
+
*/
|
|
594
|
+
export function forwardingNoteFor(it: WorkItem): string | undefined {
|
|
595
|
+
const root = chainRootOf(it);
|
|
596
|
+
// A quick sub finishes while the root is still answering: the wake is
|
|
597
|
+
// dispatched then and waits behind the root, so the note has to be
|
|
598
|
+
// written while the root still runs (scratch N1, 2026-09-13). Only a
|
|
599
|
+
// root that already ended without `done` gets none — no follow-up
|
|
600
|
+
// will come.
|
|
601
|
+
if (!root || (root.state !== 'done' && root.state !== 'running' && root.state !== 'queued')) return undefined;
|
|
602
|
+
const r = root.requester;
|
|
603
|
+
if (!r || 'human' in r) return undefined;
|
|
604
|
+
const when = 'once all the work you started for it has finished';
|
|
605
|
+
if ('voiceCall' in r) {
|
|
606
|
+
return `What you answer in this turn is read out to the caller as the follow-up to their earlier question ${when} — write it as that answer, with the results.`;
|
|
607
|
+
}
|
|
608
|
+
if (root.origin.kind === 'agent') {
|
|
609
|
+
return (
|
|
610
|
+
`What you answer in this turn is forwarded to agent ${r.agent} as the follow-up to the question they sent ` +
|
|
611
|
+
`(call_id "${root.id}") ${when} — write it as the answer to that question, with the results, not as a note to yourself.`
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
return (
|
|
615
|
+
`What you answer in this turn is forwarded to your parent (${r.agent}, session ${r.session}) as the follow-up to ` +
|
|
616
|
+
`task '${root.id}' ${when} — write it as the report, with the results.`
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* The wake per finished kind: the record line (what happened) and the
|
|
622
|
+
* frame beside it (what to do). Beside it, when the wake belongs to
|
|
623
|
+
* work someone else asked for, where the answer of this turn goes
|
|
624
|
+
* (forwardingNoteFor). The wording is the one each wake had
|
|
625
|
+
* before the ledger (ask-calls.ts, async-tasks.ts, 2026-09-12/07),
|
|
626
|
+
* split in two since 2026-09-13 (turn-framing.ts).
|
|
627
|
+
*/
|
|
628
|
+
export function wakeTextFor(it: WorkItem): { text: string; prefix: string } {
|
|
629
|
+
const base = wakeTextBase(it);
|
|
630
|
+
const note = forwardingNoteFor(it);
|
|
631
|
+
return note ? { text: base.text, prefix: base.prefix ? `${base.prefix}\n\n${note}` : note } : base;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function wakeTextBase(it: WorkItem): { text: string; prefix: string } {
|
|
635
|
+
if (it.wakeText) return { text: it.wakeText, prefix: it.wakePrefix ?? '' };
|
|
636
|
+
if (it.state === 'cancelled') {
|
|
637
|
+
return it.origin.kind === 'agent'
|
|
638
|
+
? {
|
|
639
|
+
text:
|
|
640
|
+
`[agent answer] The question you sent to ${it.target.agent} (session '${it.target.session}') was stopped ` +
|
|
641
|
+
`by the user before it was answered (call_id "${it.id}").`,
|
|
642
|
+
prefix: 'Ask again only if the user still wants it; otherwise tell your human in one line.',
|
|
643
|
+
}
|
|
644
|
+
: {
|
|
645
|
+
text:
|
|
646
|
+
`[subagent attention] Task '${it.id}' (sub-agent '${it.target.agent}', session '${it.target.session}') was ` +
|
|
647
|
+
`stopped by the user before it finished — there is no result${it.error ? ` (${it.error})` : ''}.`,
|
|
648
|
+
prefix: 'Spawn it again only if the user still wants it; otherwise tell your human in one line.',
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
if (it.state === 'dequeued') {
|
|
652
|
+
return it.origin.kind === 'agent'
|
|
653
|
+
? {
|
|
654
|
+
text:
|
|
655
|
+
`[agent answer] The question you sent to ${it.target.agent} (session '${it.target.session}') was removed ` +
|
|
656
|
+
`from the queue by the user before ${it.target.agent} saw it — it will not be answered (call_id "${it.id}").`,
|
|
657
|
+
prefix: 'Ask again only if the user still wants it; otherwise tell your human in one line.',
|
|
658
|
+
}
|
|
659
|
+
: {
|
|
660
|
+
text:
|
|
661
|
+
`[subagent attention] Task '${it.id}' (sub-agent '${it.target.agent}', session '${it.target.session}') was ` +
|
|
662
|
+
`removed from the queue by the user before it started — there is no result.`,
|
|
663
|
+
prefix: 'Spawn it again only if the user still wants it; otherwise tell your human in one line.',
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
if (it.origin.kind === 'agent') {
|
|
667
|
+
const h = head(it, 200);
|
|
668
|
+
return {
|
|
669
|
+
text:
|
|
670
|
+
`[agent answer] ${it.target.agent} has answered the question you sent to session ` +
|
|
671
|
+
`'${it.target.session}' — you had stopped waiting for it.` +
|
|
672
|
+
(h ? ` It begins: "${h}"` : ''),
|
|
673
|
+
prefix:
|
|
674
|
+
`Read the whole answer with agent_ask_result({ call_id: "${it.id}" }), then do what ` +
|
|
675
|
+
'depended on it. If nothing does, tell your human in one line what came back.',
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
const h = head(it, 160);
|
|
679
|
+
const media = it.result?.media ?? [];
|
|
680
|
+
const mediaLine = media.length > 0 ? ` Generated media (${media.length}): ${media.map((m) => m.path).join(', ')}.` : '';
|
|
681
|
+
const files = it.result?.files_written ?? [];
|
|
682
|
+
const filesLine = files.length > 0 ? ` Files written (${files.length}): ${files.join(', ')}.` : '';
|
|
683
|
+
const outcome = it.result?.outcome;
|
|
684
|
+
const outcomeLine = outcome
|
|
685
|
+
? ` Outcome: ${outcome}${it.result?.outcome_reason ? ` (${it.result.outcome_reason})` : ''}, ` +
|
|
686
|
+
`${it.result?.tool_calls ?? 0} tool calls` +
|
|
687
|
+
(it.result?.rounds !== undefined ? `, ${it.result.rounds} rounds` : '') +
|
|
688
|
+
'.'
|
|
689
|
+
: '';
|
|
690
|
+
return {
|
|
691
|
+
text:
|
|
692
|
+
`[subagent attention] Task '${it.id}' (sub-agent '${it.target.agent}', session ` +
|
|
693
|
+
`'${it.target.session}') finished with state '${it.state}'.` +
|
|
694
|
+
outcomeLine +
|
|
695
|
+
(h ? ` First line: "${h}"` : '') +
|
|
696
|
+
filesLine +
|
|
697
|
+
mediaLine,
|
|
698
|
+
prefix:
|
|
699
|
+
`Fetch the full answer with subagent_result({ task_id: "${it.id}" }), then continue ` +
|
|
700
|
+
'whatever depended on it (validate, report to the user, or chain the next step). If nothing ' +
|
|
701
|
+
'depends on it, a short acknowledgement to the user is enough.',
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
type FollowUpListener = (root: WorkItem, followUp: { text: string; failed?: string }) => void;
|
|
706
|
+
const followUpListeners: FollowUpListener[] = [];
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* A wake turn about an agent's answer is running on `here` — whose
|
|
710
|
+
* answer was it? That is who a reply from this turn belongs to.
|
|
711
|
+
*
|
|
712
|
+
* An agent asks `<other>/<project-session>` with wait:false, is woken
|
|
713
|
+
* with the answer, and writes back without naming a session. The wake
|
|
714
|
+
* turn carries no from_agent, so the reply-back default had nothing to
|
|
715
|
+
* go on and the message landed in `<other>/main` — a conversation that
|
|
716
|
+
* knew nothing about the project (report 2026-09-14; with wait:false
|
|
717
|
+
* and wakes this became the COMMON way into main). Only wakes about an
|
|
718
|
+
* A2A call: a sub-agent's session is a sealed room, not a place to
|
|
719
|
+
* write back to.
|
|
720
|
+
*/
|
|
721
|
+
export function wakeReplyTargetFor(here: { agent: string; session: string }): { agent: string; session: string } | null {
|
|
722
|
+
for (const it of items.values()) {
|
|
723
|
+
if (it.state !== 'running' || it.origin.kind !== 'wake' || it.origin.about !== 'a2a') continue;
|
|
724
|
+
if (it.target.agent !== here.agent || it.target.session !== here.session) continue;
|
|
725
|
+
const about = items.get(it.origin.ref);
|
|
726
|
+
if (about && about.origin.kind === 'agent') return { ...about.target };
|
|
727
|
+
}
|
|
728
|
+
return null;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** Hear every follow-up whose root was asked by a voice call: the
|
|
732
|
+
* realtime manager reads it out. Agent and sub-agent follow-ups go
|
|
733
|
+
* through the wake deps instead. */
|
|
734
|
+
export function onWorkFollowUp(listener: FollowUpListener): () => void {
|
|
735
|
+
followUpListeners.push(listener);
|
|
736
|
+
return () => {
|
|
737
|
+
const i = followUpListeners.indexOf(listener);
|
|
738
|
+
if (i >= 0) followUpListeners.splice(i, 1);
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* The item a piece of work ultimately belongs to: follow `startedDuring`
|
|
744
|
+
* back, treating a wake turn about Z as part of Z's chain. Undefined
|
|
745
|
+
* for an item nobody started from inside another item's turn.
|
|
746
|
+
*/
|
|
747
|
+
export function chainRootOf(it: WorkItem): WorkItem | undefined {
|
|
748
|
+
const seen = new Set<string>();
|
|
749
|
+
let cur: WorkItem | undefined = it;
|
|
750
|
+
while (cur && !seen.has(cur.id)) {
|
|
751
|
+
seen.add(cur.id);
|
|
752
|
+
if (cur.origin.kind === 'wake') {
|
|
753
|
+
cur = items.get(cur.origin.ref);
|
|
754
|
+
continue;
|
|
755
|
+
}
|
|
756
|
+
if (!cur.startedDuring) return undefined;
|
|
757
|
+
const parent = items.get(cur.startedDuring);
|
|
758
|
+
if (!parent) return undefined;
|
|
759
|
+
if (parent.origin.kind === 'wake') {
|
|
760
|
+
cur = parent;
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
return parent;
|
|
764
|
+
}
|
|
765
|
+
return undefined;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/** Is `it` anywhere below `rootId` — a child, a grandchild through a
|
|
769
|
+
* sub's own chain, a wake turn about any of them? */
|
|
770
|
+
export function inTreeOf(it: WorkItem, rootId: string): boolean {
|
|
771
|
+
const seen = new Set<string>();
|
|
772
|
+
let cur = chainRootOf(it);
|
|
773
|
+
while (cur && !seen.has(cur.id)) {
|
|
774
|
+
if (cur.id === rootId) return true;
|
|
775
|
+
seen.add(cur.id);
|
|
776
|
+
cur = chainRootOf(cur);
|
|
777
|
+
}
|
|
778
|
+
return false;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/** Everything still open below a root: queued or running items at any
|
|
782
|
+
* depth (a grandchild counts — naxon should hear once, after the whole
|
|
783
|
+
* tree, not once per level), and finished ones whose wake is still in
|
|
784
|
+
* its grace. */
|
|
785
|
+
export function openChainMembers(rootId: string): WorkItem[] {
|
|
786
|
+
const out: WorkItem[] = [];
|
|
787
|
+
for (const c of items.values()) {
|
|
788
|
+
if (c.id === rootId) continue;
|
|
789
|
+
const open = c.state === 'queued' || c.state === 'running' || pendingWakes.has(c.id);
|
|
790
|
+
if (!open) continue;
|
|
791
|
+
if (inTreeOf(c, rootId)) out.push(c);
|
|
792
|
+
}
|
|
793
|
+
return out;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** The final texts of the target's own wake turns for a root's work,
|
|
797
|
+
* oldest first, empty and repeated ones dropped. */
|
|
798
|
+
export function wakeAnswersFor(root: WorkItem): string[] {
|
|
799
|
+
const since = root.finishedAt ?? 0;
|
|
800
|
+
const turns = [...items.values()]
|
|
801
|
+
.filter(
|
|
802
|
+
(w) =>
|
|
803
|
+
w.origin.kind === 'wake' &&
|
|
804
|
+
w.state === 'done' &&
|
|
805
|
+
(w.finishedAt ?? 0) >= since &&
|
|
806
|
+
w.target.agent === root.target.agent &&
|
|
807
|
+
w.target.session === root.target.session &&
|
|
808
|
+
inTreeOf(w, root.id),
|
|
809
|
+
)
|
|
810
|
+
.sort((a, b) => (a.finishedAt ?? 0) - (b.finishedAt ?? 0));
|
|
811
|
+
const out: string[] = [];
|
|
812
|
+
for (const w of turns) {
|
|
813
|
+
const t = (w.result?.finalText ?? '').trim();
|
|
814
|
+
if (t && !out.includes(t)) out.push(t);
|
|
815
|
+
}
|
|
816
|
+
return out;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
export const FOLLOW_UP_PREFIX_A2A = (callId: string): string =>
|
|
820
|
+
`[Follow-up on the question you sent earlier (call_id "${callId}"): the work it started has finished. ` +
|
|
821
|
+
'Below is its result — treat it as the answer to that question. Continue whatever depended on it; ' +
|
|
822
|
+
'if nothing does, tell your human in one line.]';
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* A wake turn about a chain member ended (design §1). When the chain's
|
|
826
|
+
* root is a finished item someone asked for and nothing in the chain is
|
|
827
|
+
* still open, the requester hears about it exactly once: an agent as a
|
|
828
|
+
* message from the target (dispatchFollowUpMessage), a parent as one
|
|
829
|
+
* more [subagent attention] wake, a voice call through its listener.
|
|
830
|
+
*/
|
|
831
|
+
function maybeFollowUp(wake: WorkItem): void {
|
|
832
|
+
if (wake.origin.kind !== 'wake') return;
|
|
833
|
+
const deps = wakeDeps;
|
|
834
|
+
const child = items.get(wake.origin.ref);
|
|
835
|
+
const root = child ? chainRootOf(child) : undefined;
|
|
836
|
+
const skip = (reason: string): void => {
|
|
837
|
+
logger.info({ msg: 'work.follow_up_skipped', wake: wake.id, root: root?.id ?? null, reason });
|
|
838
|
+
};
|
|
839
|
+
if (!deps) return;
|
|
840
|
+
if (!child || !root) return; // nothing above this wake — the normal case for a person's session
|
|
841
|
+
if (root.state !== 'done') return skip('root_not_done');
|
|
842
|
+
const r = root.requester;
|
|
843
|
+
if (!r || 'human' in r) return skip('no_requester');
|
|
844
|
+
if (wake.state === 'failed' && wake.error === 'stopped by the user') return skip('stopped_by_user');
|
|
845
|
+
const open = openChainMembers(root.id);
|
|
846
|
+
if (open.length > 0) return skip(`open_children:${open.length}`);
|
|
847
|
+
// The model reported on its own: an A2A message from the target's
|
|
848
|
+
// session to the requester, opened after the root finished.
|
|
849
|
+
if ('agent' in r) {
|
|
850
|
+
const self = [...items.values()].some(
|
|
851
|
+
(c) =>
|
|
852
|
+
c.origin.kind === 'agent' &&
|
|
853
|
+
c.requester !== undefined &&
|
|
854
|
+
'agent' in c.requester &&
|
|
855
|
+
c.requester.agent === root.target.agent &&
|
|
856
|
+
c.requester.session === root.target.session &&
|
|
857
|
+
c.target.agent === r.agent &&
|
|
858
|
+
c.target.session === r.session &&
|
|
859
|
+
c.enqueuedAt >= (root.finishedAt ?? 0),
|
|
860
|
+
);
|
|
861
|
+
if (self) return skip('self_reported');
|
|
862
|
+
}
|
|
863
|
+
// What the target wrote about this work: the answers of ALL its wake
|
|
864
|
+
// turns in the tree since the root finished, in order — not only the
|
|
865
|
+
// last one. In Rene's hand test the three points stood in the first
|
|
866
|
+
// wake turn and the last one said "duplicate"; the asker got the
|
|
867
|
+
// duplicate.
|
|
868
|
+
const body = wakeAnswersFor(root).join('\n\n');
|
|
869
|
+
const failed = wake.state === 'failed' ? (wake.error ?? 'unknown error') : undefined;
|
|
870
|
+
if (!body && !failed) return skip('empty');
|
|
871
|
+
const scheduledAt = Date.now();
|
|
872
|
+
const n = (root.followUpsSent ?? 0) + 1;
|
|
873
|
+
root.followUpsSent = n;
|
|
874
|
+
const timer = setTimeout(() => {
|
|
875
|
+
const fresh = items.get(root.id);
|
|
876
|
+
if (!fresh) return;
|
|
877
|
+
if ((fresh.lastFetchedAt ?? 0) >= scheduledAt) return skip('fetched_meanwhile');
|
|
878
|
+
logger.info({ msg: 'work.follow_up', root: root.id, wake: wake.id, kind: root.origin.kind, n, ...(failed ? { failed } : {}) });
|
|
879
|
+
const text = failed
|
|
880
|
+
? body
|
|
881
|
+
? `${body}\n\n(The last turn reporting on this work failed: ${failed})`
|
|
882
|
+
: `The work started for this finished, but the turn reporting it failed: ${failed}`
|
|
883
|
+
: body;
|
|
884
|
+
if (fresh.result) fresh.result = { ...fresh.result, follow_ups: [...(fresh.result.follow_ups ?? []), text] };
|
|
885
|
+
if ('voiceCall' in r) {
|
|
886
|
+
for (const l of followUpListeners) l(fresh, { text, ...(failed ? { failed } : {}) });
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
if (root.origin.kind === 'agent') {
|
|
890
|
+
if (!deps.dispatchFollowUpMessage) return skip('no_message_dispatcher');
|
|
891
|
+
void deps
|
|
892
|
+
.dispatchFollowUpMessage({
|
|
893
|
+
from: root.target,
|
|
894
|
+
to: { agent: r.agent, session: r.session },
|
|
895
|
+
callId: root.id,
|
|
896
|
+
text,
|
|
897
|
+
prefix: FOLLOW_UP_PREFIX_A2A(root.id),
|
|
898
|
+
id: `followup-${root.id}-${n}`,
|
|
899
|
+
})
|
|
900
|
+
.catch((err: unknown) => logger.warn({ msg: 'work.follow_up_failed', root: root.id, err: (err as Error).message }));
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
const about = aboutOf(root.origin);
|
|
904
|
+
if (!about) return skip('no_wake_kind');
|
|
905
|
+
const head = text.replace(/\s+/g, ' ').slice(0, 160);
|
|
906
|
+
void deps
|
|
907
|
+
.dispatchWakeTurn({
|
|
908
|
+
agent: r.agent,
|
|
909
|
+
session: r.session,
|
|
910
|
+
text:
|
|
911
|
+
`[subagent attention] Task '${root.id}' (sub-agent '${root.target.agent}', session '${root.target.session}') ` +
|
|
912
|
+
`has a follow-up: the work it started has finished. It begins: "${head}"`,
|
|
913
|
+
prefix:
|
|
914
|
+
`Fetch it with subagent_result({ task_id: "${root.id}" }) — the follow-up is in its follow_ups field — ` +
|
|
915
|
+
'then continue whatever depended on it. If nothing does, a short acknowledgement to the user is enough.' +
|
|
916
|
+
(forwardingNoteFor(fresh) ? `\n\n${forwardingNoteFor(fresh)}` : ''),
|
|
917
|
+
about,
|
|
918
|
+
ref: root.id,
|
|
919
|
+
depth: fresh.parentDepth ?? 0,
|
|
920
|
+
id: `wake-${root.id}-fu${n}`,
|
|
921
|
+
})
|
|
922
|
+
.catch((err: unknown) => logger.warn({ msg: 'work.follow_up_failed', root: root.id, err: (err as Error).message }));
|
|
923
|
+
}, deps.graceMs);
|
|
924
|
+
timer.unref?.();
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
/**
|
|
928
|
+
* One wake for every kind (design §1.4). Fires after `graceMs` and only
|
|
929
|
+
* when: deps are wired (main server only), wake is 'auto', the state is
|
|
930
|
+
* done or failed (cancelled/dequeued: whoever did it knows), the
|
|
931
|
+
* requester hung up (not waiting inline), the requester is an agent
|
|
932
|
+
* session that exists, and nobody fetched the result meanwhile.
|
|
933
|
+
*/
|
|
934
|
+
function scheduleWake(it: WorkItem): void {
|
|
935
|
+
const deps = wakeDeps;
|
|
936
|
+
if (!deps) return;
|
|
937
|
+
if (it.wake !== 'auto') return;
|
|
938
|
+
if (it.state !== 'done' && it.state !== 'failed' && it.state !== 'dequeued' && !(it.state === 'cancelled' && it.cancelledBy === 'human')) return;
|
|
939
|
+
if (it.waiting) return;
|
|
940
|
+
const r = it.requester;
|
|
941
|
+
if (!r || !('agent' in r) || !r.session || r.session === '?') return;
|
|
942
|
+
const about = aboutOf(it.origin);
|
|
943
|
+
if (!about) return;
|
|
944
|
+
const timer = setTimeout(() => {
|
|
945
|
+
pendingWakes.delete(it.id);
|
|
946
|
+
const fresh = items.get(it.id);
|
|
947
|
+
if (!fresh || fresh.resultFetched) return;
|
|
948
|
+
logger.info({ msg: 'work.wake', id: it.id, about, requester_agent: r.agent, requester_session: r.session, state: fresh.state });
|
|
949
|
+
const wake = wakeTextFor(fresh);
|
|
950
|
+
void deps
|
|
951
|
+
.dispatchWakeTurn({
|
|
952
|
+
agent: r.agent,
|
|
953
|
+
session: r.session,
|
|
954
|
+
text: wake.text,
|
|
955
|
+
prefix: wake.prefix,
|
|
956
|
+
about,
|
|
957
|
+
ref: it.id,
|
|
958
|
+
depth: fresh.parentDepth ?? 0,
|
|
959
|
+
...(fresh.wakeMediaIds ? { mediaIds: fresh.wakeMediaIds } : {}),
|
|
960
|
+
})
|
|
961
|
+
.catch((err: unknown) => {
|
|
962
|
+
logger.warn({ msg: 'work.wake_failed', id: it.id, err: (err as Error).message });
|
|
963
|
+
});
|
|
964
|
+
}, deps.graceMs);
|
|
965
|
+
timer.unref?.();
|
|
966
|
+
pendingWakes.set(it.id, timer);
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
/** Test seam. */
|
|
970
|
+
export function _resetWorkLedger(): void {
|
|
971
|
+
followUpListeners.length = 0;
|
|
972
|
+
items.clear();
|
|
973
|
+
for (const t of pendingWakes.values()) clearTimeout(t);
|
|
974
|
+
pendingWakes.clear();
|
|
975
|
+
}
|