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,845 @@
|
|
|
1
|
+
// spawn_subagent + spawn_subagents — A2A delegation tools (Modus 1).
|
|
2
|
+
//
|
|
3
|
+
// Runs a sealed task in a fresh session of a target persona (defaults
|
|
4
|
+
// to a clone of the caller). Each spawn:
|
|
5
|
+
// - creates a sub-session with slug `sub-<parent>-<ms-ts>` (or
|
|
6
|
+
// `sub-self-<ms-ts>` for self-clones)
|
|
7
|
+
// - records spawn-meta on the session: { kind, parent_agent,
|
|
8
|
+
// parent_session, task_summary }
|
|
9
|
+
// - runs through the full somora pipeline (memory inject, tools,
|
|
10
|
+
// self-pointer with sub-context note, fallback engine)
|
|
11
|
+
// - returns the final assistant text + session slug for traceability
|
|
12
|
+
//
|
|
13
|
+
// Caps:
|
|
14
|
+
// - subagent_depth max 3 (configurable via SOMORA_MAX_SUBAGENT_DEPTH)
|
|
15
|
+
// - per-agent concurrent spawns: 4
|
|
16
|
+
// - global concurrent spawns: 16
|
|
17
|
+
//
|
|
18
|
+
// Memory + Dream: sub-sessions are normal sessions in the target
|
|
19
|
+
// persona's session-dir. Auto-inject runs per turn; the auto-dream
|
|
20
|
+
// worker picks them up like any other session.
|
|
21
|
+
|
|
22
|
+
import { z } from 'zod';
|
|
23
|
+
import { describeModelRefs, resolveAnyRef } from '../../config/types.ts';
|
|
24
|
+
import { loadPersona } from '../../persona/loader.ts';
|
|
25
|
+
import { completeTask, failTask, getTask, newTaskId, registerTask, type AsyncTaskEntry, markResultFetched, waitForTaskCompletion } from '../../server/async-tasks.ts';
|
|
26
|
+
import { registerWait } from '../../server/ask-wait-graph.ts';
|
|
27
|
+
import { logger } from '../../server/logger.ts';
|
|
28
|
+
import { classifyFetchError, loopbackFetch } from '../../server/loopback-fetch.ts';
|
|
29
|
+
import type { ChatTurnResolveDeps, ChatTurnResult } from '../../server/run-turn-types.ts';
|
|
30
|
+
import { startTurn } from '../../server/start-turn.ts';
|
|
31
|
+
import { createSession, sessionMetaStore } from '../../storage/sessions.ts';
|
|
32
|
+
import type { ToolDefinition } from '../types.ts';
|
|
33
|
+
import {
|
|
34
|
+
IMAGES_FIELD_DESCRIPTION,
|
|
35
|
+
MAX_IMAGES_PER_MESSAGE,
|
|
36
|
+
uploadLocalAttachments,
|
|
37
|
+
type AttachmentRef,
|
|
38
|
+
} from './images.ts';
|
|
39
|
+
import { longTaskMaxMs } from './long-task-timeouts.ts';
|
|
40
|
+
import { fetchResultViaHttp } from './status.ts';
|
|
41
|
+
|
|
42
|
+
const MAX_SUBAGENT_DEPTH = parseInt(process.env.SOMORA_MAX_SUBAGENT_DEPTH ?? '3', 10) || 3;
|
|
43
|
+
const MAX_CONCURRENT_PER_AGENT = 4;
|
|
44
|
+
const MAX_CONCURRENT_GLOBAL = 16;
|
|
45
|
+
|
|
46
|
+
// Process-wide concurrency tracker. Survives only as long as the
|
|
47
|
+
// somora process — sub-spawns across server restarts are fresh starts.
|
|
48
|
+
const activeByAgent = new Map<string, number>();
|
|
49
|
+
let activeGlobal = 0;
|
|
50
|
+
|
|
51
|
+
/** Try to reserve a spawn slot. Returns null on success, or an error
|
|
52
|
+
* message string on cap-rejection. Slot must be paired with
|
|
53
|
+
* releaseSpawnSlot() — release in a finally so a thrown background
|
|
54
|
+
* doesn't leak the counter. Same semantics for sync and async paths;
|
|
55
|
+
* the bug audit 2026-05-16 found the async path skipped accounting
|
|
56
|
+
* entirely, letting agents fan out way past the per-agent cap.
|
|
57
|
+
*
|
|
58
|
+
* Cap fairness (2026-07-28 feedback): spawns issued BY a sub
|
|
59
|
+
* (fromDepth ≥ 1) may fill the per-agent cap only up to cap-1 — the
|
|
60
|
+
* last slot is reserved for top-level spawns, so an orchestrator sub
|
|
61
|
+
* fanning out into children can never lock the main agent out of
|
|
62
|
+
* spawning (e.g. a replacement or corrective sub). */
|
|
63
|
+
export function reserveSpawnSlot(targetPersona: string, fromDepth = 0): string | null {
|
|
64
|
+
if (activeGlobal >= MAX_CONCURRENT_GLOBAL) {
|
|
65
|
+
return `spawn_subagent: global concurrent cap (${MAX_CONCURRENT_GLOBAL}) reached`;
|
|
66
|
+
}
|
|
67
|
+
const perAgent = activeByAgent.get(targetPersona) ?? 0;
|
|
68
|
+
const effectiveCap = fromDepth >= 1 ? MAX_CONCURRENT_PER_AGENT - 1 : MAX_CONCURRENT_PER_AGENT;
|
|
69
|
+
if (perAgent >= effectiveCap) {
|
|
70
|
+
return (
|
|
71
|
+
`spawn_subagent: per-agent concurrent cap for '${targetPersona}' ` +
|
|
72
|
+
`(${effectiveCap}${fromDepth >= 1 ? ` of ${MAX_CONCURRENT_PER_AGENT}; the last slot is reserved for top-level spawns` : ''}) reached`
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
activeByAgent.set(targetPersona, perAgent + 1);
|
|
76
|
+
activeGlobal++;
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function releaseSpawnSlot(targetPersona: string): void {
|
|
81
|
+
const cur = activeByAgent.get(targetPersona) ?? 0;
|
|
82
|
+
if (cur > 0) activeByAgent.set(targetPersona, cur - 1);
|
|
83
|
+
if (activeGlobal > 0) activeGlobal--;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
interface SpawnDeps {
|
|
87
|
+
chatTurnDeps: ChatTurnResolveDeps;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
let injectedDeps: SpawnDeps | null = null;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Server boot calls this once with the shared chatTurnDeps so the
|
|
94
|
+
* spawn tools can run the full chat pipeline without re-resolving
|
|
95
|
+
* server wiring on each call.
|
|
96
|
+
*/
|
|
97
|
+
export function configureSpawnTools(deps: SpawnDeps): void {
|
|
98
|
+
injectedDeps = deps;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const TaskSchema = z.object({
|
|
102
|
+
persona: z
|
|
103
|
+
.string()
|
|
104
|
+
.min(1)
|
|
105
|
+
.optional()
|
|
106
|
+
.describe('Target agent name. Omit to spawn a clone of the caller (<your-agent> → <your-agent>-clone).'),
|
|
107
|
+
model: z
|
|
108
|
+
.string()
|
|
109
|
+
.min(1)
|
|
110
|
+
.optional()
|
|
111
|
+
.describe(
|
|
112
|
+
'Model override — an alias or "provider/modelId" EXACTLY as configured in config.yaml; ' +
|
|
113
|
+
'invented names are rejected. Omit (recommended) to use the persona\'s default.',
|
|
114
|
+
),
|
|
115
|
+
task: z.string().min(1),
|
|
116
|
+
/**
|
|
117
|
+
* Optional per-spawn agent-loop override. Default global maxRounds=8
|
|
118
|
+
* is fine for sealed research subs; orchestrator subs that
|
|
119
|
+
* themselves spawn + poll can hit the cap fast — pass e.g.
|
|
120
|
+
* { maxRounds: 32 } for those.
|
|
121
|
+
*/
|
|
122
|
+
maxRounds: z
|
|
123
|
+
.number()
|
|
124
|
+
.int()
|
|
125
|
+
.min(1)
|
|
126
|
+
.max(100)
|
|
127
|
+
.optional()
|
|
128
|
+
.describe(
|
|
129
|
+
'Per-spawn override of agentLoop.maxRounds (the server config value; 8 if unset). Use higher (e.g. 32) for ' +
|
|
130
|
+
'orchestrator subs that spawn further sub-subs and poll their results.',
|
|
131
|
+
),
|
|
132
|
+
attention: z
|
|
133
|
+
.boolean()
|
|
134
|
+
.optional()
|
|
135
|
+
.describe(
|
|
136
|
+
'Async spawns only: when the sub finishes and you have not fetched its result, you get ' +
|
|
137
|
+
'an automatic [subagent attention] wake turn (default). Ignored when you started the sub while answering another agent or a voice call. Pass false to opt out for ' +
|
|
138
|
+
'subs whose results you will poll yourself or that need no follow-up.',
|
|
139
|
+
),
|
|
140
|
+
images: z
|
|
141
|
+
.array(z.string().min(1))
|
|
142
|
+
.max(MAX_IMAGES_PER_MESSAGE)
|
|
143
|
+
.optional()
|
|
144
|
+
.describe(IMAGES_FIELD_DESCRIPTION),
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
148
|
+
// spawn_subagent (single)
|
|
149
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
150
|
+
|
|
151
|
+
const SingleInput = TaskSchema.extend({
|
|
152
|
+
wait: z
|
|
153
|
+
.boolean()
|
|
154
|
+
.default(false)
|
|
155
|
+
.describe(
|
|
156
|
+
'When true: block this turn until the sub returns its final answer (good for "I need ' +
|
|
157
|
+
'the result NOW to compose my reply"). When false (default): fire-and-forget — returns ' +
|
|
158
|
+
'a task_id immediately, sub runs in the background. Check progress with subagent_status, ' +
|
|
159
|
+
'fetch the answer with subagent_result.',
|
|
160
|
+
),
|
|
161
|
+
}).strict();
|
|
162
|
+
|
|
163
|
+
export const spawnSubagent: ToolDefinition<z.infer<typeof SingleInput>> = {
|
|
164
|
+
name: 'spawn_subagent',
|
|
165
|
+
toolset: 'agents',
|
|
166
|
+
description:
|
|
167
|
+
'Spawn a sub-agent to handle a sealed task. The sub runs in a fresh session of the ' +
|
|
168
|
+
'target persona (defaults to a clone of you), goes through normal memory+tool+thinking ' +
|
|
169
|
+
'flow, and produces a final answer. ' +
|
|
170
|
+
'Default is fire-and-forget (wait:false): you get a task_id back immediately and your ' +
|
|
171
|
+
'turn ends — the user can keep chatting with you while the sub runs. When it finishes ' +
|
|
172
|
+
'you get a [subagent attention] wake turn automatically (opt out with attention:false); ' +
|
|
173
|
+
'use subagent_status / subagent_result to check earlier, subagent_cancel to abort a ' +
|
|
174
|
+
'running sub INCLUDING its child-spawns. ' +
|
|
175
|
+
'Set wait:true for synchronous "I need the result NOW to write my reply" delegations. ' +
|
|
176
|
+
'Either way, if the sub itself started work that finishes after its report (its own subs), ' +
|
|
177
|
+
'that outcome reaches you later on its own as a follow-up wake — you never have to poll for it. ' +
|
|
178
|
+
'Depth cap: 3 (a sub itself can spawn further subs up to that limit). ' +
|
|
179
|
+
'Per-agent concurrent cap: 4 — NOTE: subs spawned by your subs count against YOUR cap ' +
|
|
180
|
+
'too (child spawns may only fill 3 of the 4 slots; the last is reserved for you), and a ' +
|
|
181
|
+
'self-clone sub inherits your persona default model unless you pass model explicitly — ' +
|
|
182
|
+
'an expensive orchestrator spawning expensive children multiplies cost fast. ' +
|
|
183
|
+
'Cross-engine OK — <agent-a>-on-opus can spawn <agent-b>-on-gpt55. ' +
|
|
184
|
+
'Sub sessions stay visible in /sessions of the target persona with a "sub from X/Y" marker.',
|
|
185
|
+
inputSchema: SingleInput,
|
|
186
|
+
jsonSchema: {
|
|
187
|
+
type: 'object',
|
|
188
|
+
properties: {
|
|
189
|
+
persona: {
|
|
190
|
+
type: 'string',
|
|
191
|
+
description: 'Target agent name (e.g. "<agent-name>", "<other-agent>"). Omit for a clone of yourself.',
|
|
192
|
+
},
|
|
193
|
+
model: {
|
|
194
|
+
type: 'string',
|
|
195
|
+
description:
|
|
196
|
+
'Model override — an alias or "provider/modelId" EXACTLY as configured in config.yaml; ' +
|
|
197
|
+
'invented names are rejected. Omit (recommended) to use the persona\'s default.',
|
|
198
|
+
},
|
|
199
|
+
task: { type: 'string', description: 'The task / question for the sub. Will become its first user message.' },
|
|
200
|
+
maxRounds: {
|
|
201
|
+
type: 'integer',
|
|
202
|
+
minimum: 1,
|
|
203
|
+
maximum: 100,
|
|
204
|
+
description:
|
|
205
|
+
'Per-spawn override of agentLoop.maxRounds (the server config value; 8 if unset). Use higher (e.g. 32) for ' +
|
|
206
|
+
'orchestrator subs that spawn further sub-subs and poll their results.',
|
|
207
|
+
},
|
|
208
|
+
attention: {
|
|
209
|
+
type: 'boolean',
|
|
210
|
+
description:
|
|
211
|
+
'Async spawns only: automatic [subagent attention] wake turn when the sub finishes ' +
|
|
212
|
+
'unfetched (default true). Pass false to opt out. Ignored when you started the sub while ' +
|
|
213
|
+
'answering another agent or a voice call: they wait for the outcome and are told through ' +
|
|
214
|
+
'the follow-up, which needs that wake.',
|
|
215
|
+
},
|
|
216
|
+
images: {
|
|
217
|
+
type: 'array',
|
|
218
|
+
items: { type: 'string' },
|
|
219
|
+
maxItems: MAX_IMAGES_PER_MESSAGE,
|
|
220
|
+
description: IMAGES_FIELD_DESCRIPTION,
|
|
221
|
+
},
|
|
222
|
+
wait: {
|
|
223
|
+
type: 'boolean',
|
|
224
|
+
description:
|
|
225
|
+
'When true: block this turn until the sub returns its final answer. When false ' +
|
|
226
|
+
'(default): fire-and-forget — returns a task_id immediately, sub runs in the ' +
|
|
227
|
+
'background. Check progress with subagent_status, fetch the answer with subagent_result.',
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
required: ['task'],
|
|
231
|
+
additionalProperties: false,
|
|
232
|
+
},
|
|
233
|
+
// wait:false returns immediately (just registers + kicks off async),
|
|
234
|
+
// 30s is plenty. wait:true blocks for the full sub turn — sized off
|
|
235
|
+
// agentLoop.longTaskMaxTimeoutMs (default 30 min) so a sync spawn can
|
|
236
|
+
// legitimately wait for slow local models without artificial cutoff.
|
|
237
|
+
// The sub itself caps via its own agentLoop.maxRounds; this is just
|
|
238
|
+
// a runaway guard. Read at call time so config changes take effect
|
|
239
|
+
// without restart.
|
|
240
|
+
defaultTimeoutMs: 30_000,
|
|
241
|
+
timeoutFromInput: (input) => (input.wait ? longTaskMaxMs() : undefined),
|
|
242
|
+
// Static safety fence; actual cap is dynamic via timeoutFromInput.
|
|
243
|
+
maxTimeoutMs: 7_200_000,
|
|
244
|
+
async handler(input, ctx) {
|
|
245
|
+
const result = await runOneSpawn({
|
|
246
|
+
ctx,
|
|
247
|
+
wait: input.wait,
|
|
248
|
+
task: {
|
|
249
|
+
task: input.task,
|
|
250
|
+
...(input.persona ? { persona: input.persona } : {}),
|
|
251
|
+
...(input.model ? { model: input.model } : {}),
|
|
252
|
+
...(input.maxRounds ? { maxRounds: input.maxRounds } : {}),
|
|
253
|
+
...(input.attention !== undefined ? { attention: input.attention } : {}),
|
|
254
|
+
...(input.images && input.images.length > 0 ? { images: input.images } : {}),
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
return result;
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
262
|
+
// spawn_subagents (parallel batch)
|
|
263
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
264
|
+
|
|
265
|
+
const BatchInput = z
|
|
266
|
+
.object({
|
|
267
|
+
tasks: z
|
|
268
|
+
.array(TaskSchema)
|
|
269
|
+
.min(1)
|
|
270
|
+
.max(8)
|
|
271
|
+
.describe('Up to 8 tasks. Run in parallel; results returned together.'),
|
|
272
|
+
wait: z
|
|
273
|
+
.boolean()
|
|
274
|
+
.default(false)
|
|
275
|
+
.describe(
|
|
276
|
+
'Default false (fire-and-forget): each task gets its own task_id, all run in ' +
|
|
277
|
+
'parallel in the background and the tool returns at once — your turn goes on. true blocks until all ' +
|
|
278
|
+
'complete and returns results inline.',
|
|
279
|
+
),
|
|
280
|
+
})
|
|
281
|
+
.strict();
|
|
282
|
+
|
|
283
|
+
export const spawnSubagents: ToolDefinition<z.infer<typeof BatchInput>> = {
|
|
284
|
+
name: 'spawn_subagents',
|
|
285
|
+
toolset: 'agents',
|
|
286
|
+
description:
|
|
287
|
+
'Spawn multiple sub-agents in parallel. Each task is a {persona?, model?, task} record; ' +
|
|
288
|
+
'omitting persona = clone of you. Useful for fan-out queries: send the same task to ' +
|
|
289
|
+
'multiple personas to compare perspectives, or different focused tasks at once. ' +
|
|
290
|
+
'Returns one result per task in the same order. Same caps as spawn_subagent.',
|
|
291
|
+
inputSchema: BatchInput,
|
|
292
|
+
jsonSchema: {
|
|
293
|
+
type: 'object',
|
|
294
|
+
properties: {
|
|
295
|
+
tasks: {
|
|
296
|
+
type: 'array',
|
|
297
|
+
minItems: 1,
|
|
298
|
+
maxItems: 8,
|
|
299
|
+
items: {
|
|
300
|
+
type: 'object',
|
|
301
|
+
properties: {
|
|
302
|
+
persona: { type: 'string' },
|
|
303
|
+
model: {
|
|
304
|
+
type: 'string',
|
|
305
|
+
description:
|
|
306
|
+
'Model override — alias or "provider/modelId" exactly as configured; omit for the persona default.',
|
|
307
|
+
},
|
|
308
|
+
task: { type: 'string' },
|
|
309
|
+
maxRounds: {
|
|
310
|
+
type: 'integer',
|
|
311
|
+
minimum: 1,
|
|
312
|
+
maximum: 100,
|
|
313
|
+
description:
|
|
314
|
+
'Per-spawn override of agentLoop.maxRounds (the server config value; 8 if unset). Use higher (e.g. 32) ' +
|
|
315
|
+
'for orchestrator subs that spawn further sub-subs and poll their results.',
|
|
316
|
+
},
|
|
317
|
+
attention: {
|
|
318
|
+
type: 'boolean',
|
|
319
|
+
description:
|
|
320
|
+
'Async spawns only: automatic [subagent attention] wake turn when the sub ' +
|
|
321
|
+
'finishes unfetched (default true). Pass false to opt out.',
|
|
322
|
+
},
|
|
323
|
+
images: {
|
|
324
|
+
type: 'array',
|
|
325
|
+
items: { type: 'string' },
|
|
326
|
+
maxItems: MAX_IMAGES_PER_MESSAGE,
|
|
327
|
+
description: IMAGES_FIELD_DESCRIPTION,
|
|
328
|
+
},
|
|
329
|
+
},
|
|
330
|
+
required: ['task'],
|
|
331
|
+
additionalProperties: false,
|
|
332
|
+
},
|
|
333
|
+
},
|
|
334
|
+
wait: {
|
|
335
|
+
type: 'boolean',
|
|
336
|
+
description:
|
|
337
|
+
'Default false (fire-and-forget): each task gets its own task_id, all run in ' +
|
|
338
|
+
'parallel in the background and the tool returns at once — your turn goes on. true blocks until all ' +
|
|
339
|
+
'complete and returns results inline.',
|
|
340
|
+
},
|
|
341
|
+
},
|
|
342
|
+
required: ['tasks'],
|
|
343
|
+
additionalProperties: false,
|
|
344
|
+
},
|
|
345
|
+
// Same posture as spawn_subagent: wait:false is instant, wait:true
|
|
346
|
+
// blocks for all subs — sized off agentLoop.longTaskMaxTimeoutMs.
|
|
347
|
+
defaultTimeoutMs: 30_000,
|
|
348
|
+
timeoutFromInput: (input) => (input.wait ? longTaskMaxMs() : undefined),
|
|
349
|
+
maxTimeoutMs: 7_200_000,
|
|
350
|
+
async handler(input, ctx) {
|
|
351
|
+
const settled = await Promise.allSettled(
|
|
352
|
+
input.tasks.map((t) => runOneSpawn({ ctx, wait: input.wait, task: t })),
|
|
353
|
+
);
|
|
354
|
+
const results = settled.map((s, i) => {
|
|
355
|
+
if (s.status === 'fulfilled') return s.value;
|
|
356
|
+
const err = (s.reason as Error).message;
|
|
357
|
+
const t = input.tasks[i]!;
|
|
358
|
+
return {
|
|
359
|
+
ok: false as const,
|
|
360
|
+
persona: t.persona ?? ctx.agent,
|
|
361
|
+
error: err,
|
|
362
|
+
ms: 0,
|
|
363
|
+
};
|
|
364
|
+
});
|
|
365
|
+
return { count: results.length, results };
|
|
366
|
+
},
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
371
|
+
// shared spawn machinery
|
|
372
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
373
|
+
|
|
374
|
+
interface OneSpawnArgs {
|
|
375
|
+
ctx: import('../types.ts').ToolContext;
|
|
376
|
+
wait: boolean;
|
|
377
|
+
task: {
|
|
378
|
+
persona?: string;
|
|
379
|
+
model?: string;
|
|
380
|
+
task: string;
|
|
381
|
+
maxRounds?: number;
|
|
382
|
+
/** Attention-wake opt-out (async spawns). Default: wake. */
|
|
383
|
+
attention?: boolean;
|
|
384
|
+
/** Absolute paths of images the sub has to look at. */
|
|
385
|
+
images?: string[];
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
interface OneSpawnSyncResult {
|
|
390
|
+
ok: boolean;
|
|
391
|
+
wait: 'sync';
|
|
392
|
+
/** Since 2026-09-13 every spawn is a task; wait:true awaits it. */
|
|
393
|
+
task_id: string;
|
|
394
|
+
/** `pending` when the wait ran out before the sub finished — it keeps
|
|
395
|
+
* running, the parent is woken when it is done. */
|
|
396
|
+
state?: 'pending';
|
|
397
|
+
hint?: string;
|
|
398
|
+
persona: string;
|
|
399
|
+
agent_kind: 'self-clone' | 'named';
|
|
400
|
+
session_slug: string;
|
|
401
|
+
model: string;
|
|
402
|
+
result?: string;
|
|
403
|
+
/** Runtime verdict — see ChatTurnResult.outcome. */
|
|
404
|
+
outcome?: ChatTurnResult['outcome'];
|
|
405
|
+
outcome_reason?: string;
|
|
406
|
+
tool_calls?: number;
|
|
407
|
+
rounds?: number;
|
|
408
|
+
fallback?: ChatTurnResult['fallback'];
|
|
409
|
+
files_written?: string[];
|
|
410
|
+
media?: ChatTurnResult['media'];
|
|
411
|
+
error?: string;
|
|
412
|
+
ms: number;
|
|
413
|
+
thinkingActive: boolean;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
interface OneSpawnAsyncResult {
|
|
417
|
+
ok: true;
|
|
418
|
+
wait: 'async';
|
|
419
|
+
task_id: string;
|
|
420
|
+
persona: string;
|
|
421
|
+
agent_kind: 'self-clone' | 'named';
|
|
422
|
+
session_slug: string;
|
|
423
|
+
hint: string;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
type OneSpawnResult = OneSpawnSyncResult | OneSpawnAsyncResult;
|
|
427
|
+
|
|
428
|
+
async function runOneSpawn(args: OneSpawnArgs): Promise<OneSpawnResult> {
|
|
429
|
+
// injectedDeps absent is the normal MCP-child case (configureSpawnTools
|
|
430
|
+
// only runs in the main server). The handler dispatches to the HTTP
|
|
431
|
+
// fallback further down — this guard would have killed that path.
|
|
432
|
+
const { ctx, task } = args;
|
|
433
|
+
const parentDepth = ctx.subagentDepth ?? 0;
|
|
434
|
+
if (parentDepth >= MAX_SUBAGENT_DEPTH) {
|
|
435
|
+
throw new Error(
|
|
436
|
+
`spawn_subagent: recursion depth ${parentDepth} exceeds limit ${MAX_SUBAGENT_DEPTH}`,
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
const isSelfClone = !task.persona || task.persona === ctx.agent;
|
|
440
|
+
const targetPersona = task.persona ?? ctx.agent;
|
|
441
|
+
const personaCheck = await loadPersona(targetPersona);
|
|
442
|
+
if (!personaCheck) {
|
|
443
|
+
throw new Error(`spawn_subagent: persona '${targetPersona}' not found`);
|
|
444
|
+
}
|
|
445
|
+
// Validate a model override BEFORE creating the session + reserving a
|
|
446
|
+
// slot: an invented name ("myprovider/model-that-does-not-exist") otherwise fails
|
|
447
|
+
// deep inside the sub's first turn, leaving a dead session behind and
|
|
448
|
+
// an error that doesn't say what WOULD have worked (2026-08-24 report).
|
|
449
|
+
if (task.model && !resolveAnyRef(ctx.config, task.model)) {
|
|
450
|
+
throw new Error(
|
|
451
|
+
`spawn_subagent: model '${task.model}' is not configured — pass an alias or ` +
|
|
452
|
+
`provider/modelId exactly as listed in config.yaml, or omit \`model\` to use ` +
|
|
453
|
+
`${targetPersona}'s default (${personaCheck.model ?? 'unset'}). ` +
|
|
454
|
+
`Available: ${describeModelRefs(ctx.config)}`,
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
// Pictures for the brief. Uploaded BEFORE a slot is reserved and a
|
|
458
|
+
// session created: a wrong path is the caller's typo, and it should
|
|
459
|
+
// cost neither. The refs then travel every dispatch path below, the
|
|
460
|
+
// same ones the task text travels (2026-09-11: an orchestrator could
|
|
461
|
+
// only name a file, and a path is just text to a model that sees).
|
|
462
|
+
const briefAttachments: AttachmentRef[] =
|
|
463
|
+
task.images && task.images.length > 0
|
|
464
|
+
? await uploadLocalAttachments(task.images, spawnBase())
|
|
465
|
+
: [];
|
|
466
|
+
|
|
467
|
+
// Concurrency — slot must be held across the full lifetime of the
|
|
468
|
+
// sub-turn (sync + async both). reserveSpawnSlot also increments the
|
|
469
|
+
// counters atomically; the matching releaseSpawnSlot lives in the
|
|
470
|
+
// finally of each path (sync: line below; async: inside the
|
|
471
|
+
// background IIFE in spawnAsyncInProcess + the HTTP route).
|
|
472
|
+
const slotErr = reserveSpawnSlot(targetPersona, parentDepth);
|
|
473
|
+
if (slotErr) throw new Error(slotErr);
|
|
474
|
+
|
|
475
|
+
// Slug carries ms + random suffix so parallel spawns in the same
|
|
476
|
+
// millisecond don't collide (Math.random() collision in 4 lowercase
|
|
477
|
+
// alphanums is ~1/1.7M, paired with ms it's ~1/1.7B per same-ms
|
|
478
|
+
// pair). createSession also has its own collision-retry as a safety
|
|
479
|
+
// net. The slug stem `sub-self`/`sub-<parent>` stays grep-friendly
|
|
480
|
+
// for /sessions listings.
|
|
481
|
+
const ms = String(Date.now() % 1000).padStart(3, '0');
|
|
482
|
+
const rand = Math.random().toString(36).slice(2, 6).padEnd(4, '0');
|
|
483
|
+
const slug = isSelfClone
|
|
484
|
+
? `sub-self-${ms}-${rand}`
|
|
485
|
+
: `sub-${ctx.agent}-${ms}-${rand}`;
|
|
486
|
+
const sessionId = await createSession(targetPersona, slug);
|
|
487
|
+
// Attach the spawn meta block so /sessions can label this entry
|
|
488
|
+
// "sub from <parent>" without re-deriving from the slug.
|
|
489
|
+
const existingMeta = await sessionMetaStore.get(targetPersona, sessionId);
|
|
490
|
+
// A helper works where its parent works: the pinned project (and its
|
|
491
|
+
// folder) carries over. A builder helper runs unattended and builds —
|
|
492
|
+
// it has a sealed task, nobody to ask, no plan phase of its own.
|
|
493
|
+
const targetKind = personaCheck.kind;
|
|
494
|
+
const parentMeta = ctx.session ? ((await sessionMetaStore.get(ctx.agent, ctx.session)) as Record<string, unknown>) : {};
|
|
495
|
+
const inherited: Record<string, unknown> = {};
|
|
496
|
+
if (typeof parentMeta.workdir === 'string') inherited.workdir = parentMeta.workdir;
|
|
497
|
+
if (typeof parentMeta.projectSlug === 'string') {
|
|
498
|
+
inherited.projectSlug = parentMeta.projectSlug;
|
|
499
|
+
inherited.projectLinkedAt = new Date().toISOString();
|
|
500
|
+
}
|
|
501
|
+
if (targetKind === 'builder') {
|
|
502
|
+
inherited.builderMode = 'unattended';
|
|
503
|
+
inherited.builderPhase = 'build';
|
|
504
|
+
inherited.builderInitializedAt = Date.now();
|
|
505
|
+
if (typeof parentMeta.builderPlanPath === 'string') inherited.builderPlanPath = parentMeta.builderPlanPath;
|
|
506
|
+
}
|
|
507
|
+
await sessionMetaStore.set(targetPersona, sessionId, {
|
|
508
|
+
...existingMeta,
|
|
509
|
+
...inherited,
|
|
510
|
+
spawn: {
|
|
511
|
+
kind: isSelfClone ? 'self-sub' : 'sub',
|
|
512
|
+
parent_agent: ctx.agent,
|
|
513
|
+
parent_session: ctx.session ?? '?',
|
|
514
|
+
task_summary: task.task.slice(0, 200),
|
|
515
|
+
},
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
// ─── one path: the sub is a background task; wait:true awaits it ──
|
|
519
|
+
//
|
|
520
|
+
// Until 2026-09-13 wait:true was its own code path: no task id, no
|
|
521
|
+
// lock, no abort registration, and after the tool's 30-minute wait the
|
|
522
|
+
// child kept running with a result nobody could fetch (birdseye L8,
|
|
523
|
+
// L9, L16). Now every spawn registers a task and starts it in the
|
|
524
|
+
// background — in-process or through /spawn-async — and wait:true
|
|
525
|
+
// simply waits for that task's result. Same tool, same result shape;
|
|
526
|
+
// but the sub is stoppable, subagent_cancel reaches it, and a sub that
|
|
527
|
+
// outlives the wait wakes its parent when it finishes.
|
|
528
|
+
//
|
|
529
|
+
// The slot reserved above belongs to the background task from here on
|
|
530
|
+
// (in-process: the IIFE releases it; HTTP: the server owns its own and
|
|
531
|
+
// the child's local reservation is released at once).
|
|
532
|
+
let task_id: string;
|
|
533
|
+
try {
|
|
534
|
+
if (injectedDeps) {
|
|
535
|
+
task_id = await spawnAsyncInProcess({
|
|
536
|
+
targetPersona,
|
|
537
|
+
sessionId,
|
|
538
|
+
taskText: task.task,
|
|
539
|
+
parentAgent: ctx.agent,
|
|
540
|
+
parentSession: ctx.session ?? '?',
|
|
541
|
+
parentDepth,
|
|
542
|
+
modelOverride: task.model,
|
|
543
|
+
maxRoundsOverride: task.maxRounds,
|
|
544
|
+
attention: task.attention,
|
|
545
|
+
attachments: briefAttachments,
|
|
546
|
+
});
|
|
547
|
+
} else {
|
|
548
|
+
// MCP-child HTTP path: the SERVER process owns the task lifetime
|
|
549
|
+
// and releases ITS own slot when the task finishes. The slot we
|
|
550
|
+
// reserved lives in THIS per-turn child process and has no
|
|
551
|
+
// lifetime to track here — release it now, or it leaks for the
|
|
552
|
+
// rest of the child's life and caps the orchestrator at the
|
|
553
|
+
// per-agent/global limit forever within the turn (Juni-Audit
|
|
554
|
+
// 2026-06).
|
|
555
|
+
task_id = await spawnAsyncViaHttp({
|
|
556
|
+
targetAgent: targetPersona,
|
|
557
|
+
targetSession: sessionId,
|
|
558
|
+
taskText: task.task,
|
|
559
|
+
parentAgent: ctx.agent,
|
|
560
|
+
parentSession: ctx.session ?? '?',
|
|
561
|
+
parentDepth,
|
|
562
|
+
modelOverride: task.model,
|
|
563
|
+
maxRoundsOverride: task.maxRounds,
|
|
564
|
+
attention: task.attention,
|
|
565
|
+
attachments: briefAttachments,
|
|
566
|
+
});
|
|
567
|
+
releaseSpawnSlot(targetPersona);
|
|
568
|
+
}
|
|
569
|
+
} catch (err) {
|
|
570
|
+
// Slot release on synchronous setup failure — the background
|
|
571
|
+
// never actually started, so no IIFE finally will fire.
|
|
572
|
+
releaseSpawnSlot(targetPersona);
|
|
573
|
+
throw err;
|
|
574
|
+
}
|
|
575
|
+
logger.info({
|
|
576
|
+
msg: args.wait ? 'spawn_subagent.start_sync' : 'spawn_subagent.async_started',
|
|
577
|
+
task_id,
|
|
578
|
+
parent_agent: ctx.agent,
|
|
579
|
+
parent_session: ctx.session,
|
|
580
|
+
target: targetPersona,
|
|
581
|
+
session: sessionId,
|
|
582
|
+
depth: parentDepth + 1,
|
|
583
|
+
via: injectedDeps ? 'in-process' : 'http',
|
|
584
|
+
});
|
|
585
|
+
if (!args.wait) {
|
|
586
|
+
return {
|
|
587
|
+
ok: true,
|
|
588
|
+
wait: 'async',
|
|
589
|
+
task_id,
|
|
590
|
+
persona: targetPersona,
|
|
591
|
+
agent_kind: isSelfClone ? 'self-clone' : 'named',
|
|
592
|
+
session_slug: slug,
|
|
593
|
+
hint:
|
|
594
|
+
`Sub is running in the background. Check progress with subagent_status({ task_id: "${task_id}" }) ` +
|
|
595
|
+
`or fetch the answer with subagent_result({ task_id: "${task_id}" }).`,
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// ─── wait:true: block on the task ─────────────────────────────────
|
|
600
|
+
// The parent's turn BLOCKS on the sub — that wait must be visible in
|
|
601
|
+
// the A2A wait-graph, or a cycle routed through this spawn (parent
|
|
602
|
+
// waits sub, sub asks X, X asks parent) is undetectable and deadlocks
|
|
603
|
+
// silently (see src/server/ask-wait-graph.ts). In-process the edge is
|
|
604
|
+
// registered here; over HTTP, /spawn-result registers it from the
|
|
605
|
+
// waiter_* query. No cycle CHECK is needed: the sub-session is fresh.
|
|
606
|
+
const releaseWait =
|
|
607
|
+
injectedDeps && ctx.session
|
|
608
|
+
? registerWait(
|
|
609
|
+
{ agent: ctx.agent, session: ctx.session },
|
|
610
|
+
{ agent: targetPersona, session: sessionId },
|
|
611
|
+
)
|
|
612
|
+
: undefined;
|
|
613
|
+
// Answer before the engine's own race on this tool call (longTaskMax)
|
|
614
|
+
// would cut us off — a sub that needs longer keeps running and wakes
|
|
615
|
+
// the parent when it is done.
|
|
616
|
+
const budgetMs = Math.max(30_000, longTaskMaxMs() - 5_000);
|
|
617
|
+
const startedAt = Date.now();
|
|
618
|
+
try {
|
|
619
|
+
const entry = injectedDeps
|
|
620
|
+
? await waitForTaskCompletion(task_id, budgetMs)
|
|
621
|
+
: await fetchResultViaHttp(task_id, {
|
|
622
|
+
wait_until_done: true,
|
|
623
|
+
timeout_ms: budgetMs,
|
|
624
|
+
...(ctx.session ? { waiter_agent: ctx.agent, waiter_session: ctx.session } : {}),
|
|
625
|
+
});
|
|
626
|
+
const state = entry?.state;
|
|
627
|
+
if (!entry || state === 'running') {
|
|
628
|
+
logger.info({ msg: 'spawn_subagent.sync_timeout', task_id, target: targetPersona, session: sessionId, ms: Date.now() - startedAt });
|
|
629
|
+
return {
|
|
630
|
+
ok: false,
|
|
631
|
+
wait: 'sync',
|
|
632
|
+
state: 'pending',
|
|
633
|
+
task_id,
|
|
634
|
+
persona: targetPersona,
|
|
635
|
+
agent_kind: isSelfClone ? 'self-clone' : 'named',
|
|
636
|
+
session_slug: slug,
|
|
637
|
+
model: task.model ?? '',
|
|
638
|
+
hint:
|
|
639
|
+
`The sub is still working after ${Math.round(budgetMs / 60_000)} minutes. It keeps running; you are ` +
|
|
640
|
+
`woken when it finishes, or fetch it with subagent_result({ task_id: "${task_id}" }). Do not spawn it again.`,
|
|
641
|
+
ms: Date.now() - startedAt,
|
|
642
|
+
thinkingActive: false,
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
// The parent has the result in hand: no attention wake for it.
|
|
646
|
+
if (injectedDeps) markResultFetched(task_id);
|
|
647
|
+
const result: ChatTurnResult | undefined = entry.result;
|
|
648
|
+
const error = entry.error ?? result?.error;
|
|
649
|
+
logger.info({
|
|
650
|
+
msg: 'spawn_subagent.done',
|
|
651
|
+
task_id,
|
|
652
|
+
target: targetPersona,
|
|
653
|
+
session: sessionId,
|
|
654
|
+
state,
|
|
655
|
+
ms: Date.now() - startedAt,
|
|
656
|
+
bytes: result?.finalText.length ?? 0,
|
|
657
|
+
});
|
|
658
|
+
return {
|
|
659
|
+
ok: state === 'done' && !error,
|
|
660
|
+
wait: 'sync',
|
|
661
|
+
task_id,
|
|
662
|
+
persona: targetPersona,
|
|
663
|
+
agent_kind: isSelfClone ? 'self-clone' : 'named',
|
|
664
|
+
session_slug: slug,
|
|
665
|
+
model: result?.model ?? task.model ?? '',
|
|
666
|
+
...(result ? { result: result.finalText } : {}),
|
|
667
|
+
...(result?.outcome ? { outcome: result.outcome } : state === 'cancelled' ? { outcome: 'failed' as const } : {}),
|
|
668
|
+
...(result?.outcome_reason ? { outcome_reason: result.outcome_reason } : {}),
|
|
669
|
+
...(result ? { tool_calls: result.tool_calls } : {}),
|
|
670
|
+
...(result?.rounds !== undefined ? { rounds: result.rounds } : {}),
|
|
671
|
+
...(result?.fallback ? { fallback: result.fallback } : {}),
|
|
672
|
+
...(result?.files_written?.length ? { files_written: result.files_written } : {}),
|
|
673
|
+
...(result?.media?.length ? { media: result.media } : {}),
|
|
674
|
+
...(error ? { error } : {}),
|
|
675
|
+
ms: Date.now() - startedAt,
|
|
676
|
+
thinkingActive: result?.thinkingActive ?? false,
|
|
677
|
+
};
|
|
678
|
+
} finally {
|
|
679
|
+
releaseWait?.();
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/** startTurn without a pre-flight never skips; a null here is a bug. */
|
|
684
|
+
async function startSubTurn(args: Parameters<typeof startTurn>[0]): Promise<ChatTurnResult> {
|
|
685
|
+
const result = await startTurn(args);
|
|
686
|
+
if (!result) throw new Error('spawn_subagent: turn did not start');
|
|
687
|
+
return result;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* In-process async dispatch: register the task, kick off the turn
|
|
692
|
+
* as a background promise, return the task_id. completeTask /
|
|
693
|
+
* failTask write the result back into the shared task store.
|
|
694
|
+
*/
|
|
695
|
+
async function spawnAsyncInProcess(args: {
|
|
696
|
+
targetPersona: string;
|
|
697
|
+
sessionId: string;
|
|
698
|
+
taskText: string;
|
|
699
|
+
parentAgent: string;
|
|
700
|
+
parentSession: string;
|
|
701
|
+
parentDepth: number;
|
|
702
|
+
modelOverride?: string;
|
|
703
|
+
maxRoundsOverride?: number;
|
|
704
|
+
attention?: boolean;
|
|
705
|
+
attachments?: AttachmentRef[];
|
|
706
|
+
}): Promise<string> {
|
|
707
|
+
if (!injectedDeps) throw new Error('spawnAsyncInProcess called without injectedDeps');
|
|
708
|
+
const task_id = newTaskId();
|
|
709
|
+
registerTask({
|
|
710
|
+
task_id,
|
|
711
|
+
parent_agent: args.parentAgent,
|
|
712
|
+
parent_session: args.parentSession,
|
|
713
|
+
parent_depth: args.parentDepth,
|
|
714
|
+
target_agent: args.targetPersona,
|
|
715
|
+
target_session: args.sessionId,
|
|
716
|
+
started_at: Date.now(),
|
|
717
|
+
text: args.taskText,
|
|
718
|
+
...(args.attention !== undefined ? { attention: args.attention } : {}),
|
|
719
|
+
});
|
|
720
|
+
void (async () => {
|
|
721
|
+
// startTurn holds the per-session lock (two parallel async-spawns
|
|
722
|
+
// on the same session serialize) and registers the abort controller
|
|
723
|
+
// under the sub's (agent, session), so subagent_cancel and the Stop
|
|
724
|
+
// button cut the in-flight LLM call through the same signal.
|
|
725
|
+
try {
|
|
726
|
+
const result = await startSubTurn({
|
|
727
|
+
agent: args.targetPersona,
|
|
728
|
+
session: args.sessionId,
|
|
729
|
+
text: args.taskText,
|
|
730
|
+
turnId: task_id,
|
|
731
|
+
workId: task_id,
|
|
732
|
+
origin: {
|
|
733
|
+
kind: 'subagent',
|
|
734
|
+
depth: args.parentDepth + 1,
|
|
735
|
+
taskId: task_id,
|
|
736
|
+
...(args.parentSession !== '?' ? { parent: { agent: args.parentAgent, session: args.parentSession } } : {}),
|
|
737
|
+
},
|
|
738
|
+
...(args.attachments && args.attachments.length > 0
|
|
739
|
+
? { attachments: args.attachments }
|
|
740
|
+
: {}),
|
|
741
|
+
...(args.modelOverride ? { modelOverride: args.modelOverride } : {}),
|
|
742
|
+
...(args.maxRoundsOverride
|
|
743
|
+
? { agentLoopOverride: { maxRounds: args.maxRoundsOverride } }
|
|
744
|
+
: {}),
|
|
745
|
+
deps: injectedDeps!.chatTurnDeps,
|
|
746
|
+
});
|
|
747
|
+
// completeTask/failTask are no-ops when the task was already
|
|
748
|
+
// cancelled — the registry state stays 'cancelled'.
|
|
749
|
+
completeTask(task_id, result);
|
|
750
|
+
} catch (err) {
|
|
751
|
+
failTask(task_id, (err as Error).message);
|
|
752
|
+
} finally {
|
|
753
|
+
// Release the concurrency slot reserved by runOneSpawn — the
|
|
754
|
+
// background promise's lifetime IS the slot lifetime.
|
|
755
|
+
releaseSpawnSlot(args.targetPersona);
|
|
756
|
+
}
|
|
757
|
+
})();
|
|
758
|
+
return task_id;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* HTTP async dispatch: call /spawn-async on the localhost server. The
|
|
763
|
+
* server registers the task and runs it in its own process; we just
|
|
764
|
+
* return the task_id. status / result also go through HTTP later.
|
|
765
|
+
*/
|
|
766
|
+
async function spawnAsyncViaHttp(args: {
|
|
767
|
+
targetAgent: string;
|
|
768
|
+
targetSession: string;
|
|
769
|
+
taskText: string;
|
|
770
|
+
parentAgent: string;
|
|
771
|
+
parentSession: string;
|
|
772
|
+
parentDepth: number;
|
|
773
|
+
modelOverride?: string;
|
|
774
|
+
maxRoundsOverride?: number;
|
|
775
|
+
attention?: boolean;
|
|
776
|
+
attachments?: AttachmentRef[];
|
|
777
|
+
}): Promise<string> {
|
|
778
|
+
const host = process.env.SOMORA_HOST || '127.0.0.1';
|
|
779
|
+
const port = process.env.SOMORA_PORT || '18737';
|
|
780
|
+
// SOMORA_TLS=1 → server is HTTP/2-over-TLS; loopback must use
|
|
781
|
+
// https://<publicHost> (see spawnBase below).
|
|
782
|
+
const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
|
|
783
|
+
let res;
|
|
784
|
+
try {
|
|
785
|
+
res = await loopbackFetch(`${scheme}://${host}:${port}/spawn-async`, {
|
|
786
|
+
method: 'POST',
|
|
787
|
+
headers: { 'Content-Type': 'application/json' },
|
|
788
|
+
body: JSON.stringify({
|
|
789
|
+
agent: args.targetAgent,
|
|
790
|
+
session: args.targetSession,
|
|
791
|
+
text: args.taskText,
|
|
792
|
+
...(args.attachments && args.attachments.length > 0
|
|
793
|
+
? { attachments: args.attachments }
|
|
794
|
+
: {}),
|
|
795
|
+
// Deliberately NO from_agent: a spawn task brief is not an A2A
|
|
796
|
+
// message. Labeling it would render a peer-agent bubble + fire
|
|
797
|
+
// unread badges in the sub's session, and the sub's engine
|
|
798
|
+
// would frame the brief as inbound mail from the parent —
|
|
799
|
+
// while the in-process async path and BOTH sync paths deliver
|
|
800
|
+
// the same brief unlabeled. Parent attribution for the task
|
|
801
|
+
// registry travels via parent_agent below (Juni-Audit 2026-07,
|
|
802
|
+
// decision: briefs are neutral).
|
|
803
|
+
parent_agent: args.parentAgent,
|
|
804
|
+
parent_session: args.parentSession,
|
|
805
|
+
subagent_depth: args.parentDepth + 1,
|
|
806
|
+
...(args.modelOverride ? { model: args.modelOverride } : {}),
|
|
807
|
+
...(args.maxRoundsOverride ? { max_rounds: args.maxRoundsOverride } : {}),
|
|
808
|
+
...(args.attention !== undefined ? { attention: args.attention } : {}),
|
|
809
|
+
}),
|
|
810
|
+
});
|
|
811
|
+
} catch (err) {
|
|
812
|
+
const c = classifyFetchError(err);
|
|
813
|
+
throw new Error(
|
|
814
|
+
`spawn-async [${c.category}${c.code ? '/' + c.code : ''}]: ${c.message}` +
|
|
815
|
+
(c.hint ? ` — hint: ${c.hint}` : ''),
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
if (!res.ok) {
|
|
819
|
+
const body = await res.text().catch(() => '');
|
|
820
|
+
throw new Error(`spawn-async HTTP ${res.status}: ${body.slice(0, 300)}`);
|
|
821
|
+
}
|
|
822
|
+
const data = (await res.json()) as { task_id: string };
|
|
823
|
+
return data.task_id;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* MCP-child fallback: when spawn_subagent is invoked from inside a
|
|
828
|
+
* claude-cli or codex-cli MCP server (configureSpawnTools never ran
|
|
829
|
+
* here), reach back to the somora HTTP server on localhost. Same
|
|
830
|
+
* inputs, same eventual JSONL state — just routed through HTTP rather
|
|
831
|
+
* than a direct in-process call.
|
|
832
|
+
*
|
|
833
|
+
* Server host/port from SOMORA_HOST + SOMORA_PORT env (set by the
|
|
834
|
+
* parent server on launch). Falls back to 127.0.0.1:18737.
|
|
835
|
+
*/
|
|
836
|
+
/** Loopback base for this process — same rules the HTTP fallbacks use:
|
|
837
|
+
* SOMORA_HOST/PORT from the parent, https when the server runs TLS. */
|
|
838
|
+
function spawnBase(): string {
|
|
839
|
+
const host = process.env.SOMORA_HOST || '127.0.0.1';
|
|
840
|
+
const port = process.env.SOMORA_PORT || '18737';
|
|
841
|
+
const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
|
|
842
|
+
return `${scheme}://${host}:${port}`;
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
|