typeclaw 0.42.1 → 0.43.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.
Files changed (42) hide show
  1. package/auth.schema.json +16 -0
  2. package/package.json +2 -2
  3. package/secrets.schema.json +16 -0
  4. package/src/agent/index.ts +9 -2
  5. package/src/agent/live-subagents.ts +4 -4
  6. package/src/agent/plugin-tools.ts +8 -2
  7. package/src/agent/session-origin.ts +6 -3
  8. package/src/agent/system-prompt.ts +41 -3
  9. package/src/agent/tools/channel-react.ts +5 -4
  10. package/src/agent/tools/spawn-subagent.ts +80 -24
  11. package/src/bundled-plugins/planner/planner.ts +1 -1
  12. package/src/bundled-plugins/researcher/researcher.ts +2 -2
  13. package/src/bundled-plugins/reviewer/reviewer.ts +1 -1
  14. package/src/channels/adapters/discord-bot-thread-room.ts +73 -0
  15. package/src/channels/adapters/discord-bot.ts +85 -4
  16. package/src/channels/adapters/discord.ts +15 -2
  17. package/src/channels/adapters/slack-bot-classify.ts +1 -0
  18. package/src/channels/adapters/slack-classify.ts +1 -0
  19. package/src/channels/engagement.ts +33 -0
  20. package/src/channels/manager.ts +9 -1
  21. package/src/channels/router.ts +500 -91
  22. package/src/channels/schema.ts +24 -0
  23. package/src/channels/types.ts +18 -5
  24. package/src/cli/channel.ts +40 -13
  25. package/src/cli/command-meta.ts +2 -0
  26. package/src/cli/index.ts +1 -0
  27. package/src/cli/mcp.ts +233 -0
  28. package/src/hostd/daemon.ts +28 -9
  29. package/src/hostd/protocol.ts +12 -9
  30. package/src/mcp/client.ts +15 -5
  31. package/src/mcp/index.ts +12 -0
  32. package/src/mcp/manager.ts +9 -4
  33. package/src/mcp/oauth.ts +212 -0
  34. package/src/run/index.ts +15 -2
  35. package/src/sandbox/hidden-paths.ts +59 -0
  36. package/src/sandbox/index.ts +1 -1
  37. package/src/secrets/index.ts +1 -1
  38. package/src/secrets/schema.ts +13 -0
  39. package/src/secrets/secrets-provider.ts +2 -2
  40. package/src/secrets/storage.ts +108 -1
  41. package/src/skills/typeclaw-channel-github/SKILL.md +2 -2
  42. package/src/skills/typeclaw-troubleshooting/SKILL.md +1 -1
package/auth.schema.json CHANGED
@@ -777,6 +777,22 @@
777
777
  }
778
778
  },
779
779
  "additionalProperties": {}
780
+ },
781
+ "mcp": {
782
+ "default": {},
783
+ "type": "object",
784
+ "propertyNames": {
785
+ "type": "string"
786
+ },
787
+ "additionalProperties": {
788
+ "type": "object",
789
+ "properties": {
790
+ "client": {},
791
+ "tokens": {},
792
+ "discovery": {}
793
+ },
794
+ "additionalProperties": {}
795
+ }
780
796
  }
781
797
  },
782
798
  "required": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.42.1",
3
+ "version": "0.43.1",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -50,7 +50,7 @@
50
50
  "@mariozechner/pi-tui": "^0.73.1",
51
51
  "@modelcontextprotocol/sdk": "^1.29.0",
52
52
  "@mozilla/readability": "^0.6.0",
53
- "agent-messenger": "^2.28.0",
53
+ "agent-messenger": "^2.29.0",
54
54
  "cheerio": "^1.2.0",
55
55
  "citty": "^0.2.2",
56
56
  "cron-parser": "^5.5.0",
@@ -777,6 +777,22 @@
777
777
  }
778
778
  },
779
779
  "additionalProperties": {}
780
+ },
781
+ "mcp": {
782
+ "default": {},
783
+ "type": "object",
784
+ "propertyNames": {
785
+ "type": "string"
786
+ },
787
+ "additionalProperties": {
788
+ "type": "object",
789
+ "properties": {
790
+ "client": {},
791
+ "tokens": {},
792
+ "discovery": {}
793
+ },
794
+ "additionalProperties": {}
795
+ }
780
796
  }
781
797
  },
782
798
  "required": [
@@ -66,6 +66,8 @@ import {
66
66
  buildSlimSystemPrompt,
67
67
  DEFAULT_SUBAGENT_ROSTER,
68
68
  renderRuntimeBlock,
69
+ renderRuntimeNondisclosureRule,
70
+ stripRuntimeIdentityProse,
69
71
  } from './system-prompt'
70
72
  import { attachToolNotFoundNudge } from './tool-not-found-nudge'
71
73
  import { createBudgetState, type ToolResultBudget, wrapToolDefinitionWithBudget } from './tool-result-budget'
@@ -914,10 +916,12 @@ export async function createOverrideResourceLoader(
914
916
  permissions?: PermissionService,
915
917
  runtimeVersion?: string,
916
918
  ): Promise<DefaultResourceLoader> {
917
- const withRuntime =
918
- getConfig().branding && runtimeVersion !== undefined
919
+ const branding = getConfig().branding
920
+ const withRuntime = branding
921
+ ? runtimeVersion !== undefined
919
922
  ? `${systemPrompt}\n\n${renderRuntimeBlock(runtimeVersion)}`
920
923
  : systemPrompt
924
+ : `${stripRuntimeIdentityProse(systemPrompt)}\n\n${renderRuntimeNondisclosureRule()}`
921
925
  const finalPrompt = withOrigin(withRuntime, origin, permissions)
922
926
  const loader = new DefaultResourceLoader({
923
927
  cwd: process.cwd(),
@@ -1051,6 +1055,9 @@ export function composeSystemPrompt(parts: SystemPromptComposition): string {
1051
1055
  if (branding && parts.runtimeVersion !== undefined) {
1052
1056
  prompt = `${prompt}\n\n${renderRuntimeBlock(parts.runtimeVersion)}`
1053
1057
  }
1058
+ if (!branding) {
1059
+ prompt = `${prompt}\n\n${renderRuntimeNondisclosureRule()}`
1060
+ }
1054
1061
  if (parts.origin !== undefined) {
1055
1062
  prompt = `${prompt}\n\n${renderSessionOrigin(parts.origin, Date.now(), parts.roleContext)}`
1056
1063
  }
@@ -23,10 +23,10 @@ export type LiveSubagent = {
23
23
  // subagent_output/subagent_cancel. Absent when no permission service was
24
24
  // active at spawn, in which case the cap fails closed.
25
25
  spawnedByRole?: string
26
- // True when spawned with run_in_background. Only background spawns deliver
27
- // their result out-of-band (via the subagent.completed broadcast and the
28
- // parent's drain); synchronous spawns return their result inline as the tool
29
- // result, so the drain MUST NOT re-prompt for them. See runSubagentDrain.
26
+ // True when the spawn resolved to background mode. Only background spawns
27
+ // deliver their result out-of-band (via the subagent.completed broadcast and
28
+ // the parent's drain); foreground spawns return their result inline as the
29
+ // tool result, so the drain MUST NOT re-prompt for them. See runSubagentDrain.
30
30
  background?: boolean
31
31
  startedAt: number
32
32
  status: SubagentStatus
@@ -40,6 +40,7 @@ import {
40
40
  commandNeedsRealProc,
41
41
  DEFAULT_SANDBOX_ENV,
42
42
  ensureBwrapAvailable,
43
+ ensureHiddenMaskTargets,
43
44
  ensureSessionTmpDir,
44
45
  getProcBindSafetyVerdict,
45
46
  isPackageInstallCommand,
@@ -526,6 +527,11 @@ async function applyBashSandbox(
526
527
  const sandboxEnvOverlay = buildRoleScopedConfigEnv(agentDir, dirs, envOverlay)
527
528
 
528
529
  await ensureBwrapAvailable()
530
+ // bwrap's --ro-bind-data/--tmpfs mask ops abort when the target does not exist
531
+ // on the (read-only, virtiofs/OrbStack) agent-folder bind. Materialize the mask
532
+ // targets on the real host FS first; the full {dirs, files} still feeds
533
+ // subtractMasked below so a masked path is never re-exposed by a later RW bind.
534
+ const maskTargets = await ensureHiddenMaskTargets({ dirs, files })
529
535
  // Per-session /tmp: bind this session's scratch dir over the default
530
536
  // --tmpfs /tmp so writes survive across the role's sandboxed bash calls AND
531
537
  // match what the write/edit wrapper redirected a /tmp path to. The bind is
@@ -613,8 +619,8 @@ async function applyBashSandbox(
613
619
  { type: 'bind', source: sessionTmp, dest: '/tmp' },
614
620
  ],
615
621
  ...(packageInstall !== undefined
616
- ? { writableRoot: { dir: packageInstall.root }, masks: { dirs, files }, protected: packageInstall.protected }
617
- : { masks: { dirs, files }, writable, protected: protectedZones }),
622
+ ? { writableRoot: { dir: packageInstall.root }, masks: maskTargets, protected: packageInstall.protected }
623
+ : { masks: maskTargets, writable, protected: protectedZones }),
618
624
  symlinks,
619
625
  network: 'inherit',
620
626
  cwd: agentDir,
@@ -429,8 +429,11 @@ function renderChannelOrigin(
429
429
  '**React like a teammate would.** `channel_react({ emoji })` adds only a',
430
430
  'reaction: `+1` approve, `rocket` shipping/exciting, `tada` celebrate,',
431
431
  '`heart` appreciate, `laugh` funny, `eyes` looking. Use it when it adds',
432
- 'real signal, not every turn. It does NOT satisfy the reply obligation;',
433
- 'substantive answers still go through `channel_reply`.',
432
+ 'real signal, not every turn. The reaction is applied ONLY if you also',
433
+ 'reply to this message this turn; if you stay silent or `skip_response`,',
434
+ 'it is dropped — so never react to a message you are only observing and',
435
+ 'not answering. It does NOT satisfy the reply obligation; substantive',
436
+ 'answers still go through `channel_reply`.',
434
437
  )
435
438
  }
436
439
 
@@ -492,7 +495,7 @@ function renderChannelOrigin(
492
495
  ]),
493
496
  '',
494
497
  '**Backgrounded work does not end the obligation.** If you spawn a',
495
- 'subagent with `run_in_background: true` to answer the current inbound,',
498
+ 'subagent in the background to answer the current inbound,',
496
499
  'you promised a reply you have not delivered. Do not skip: the system will',
497
500
  'not surface the result. When the subagent-completion `<system-reminder>` arrives,',
498
501
  'call `subagent_output` and send the result via `channel_reply`.',
@@ -121,13 +121,15 @@ Commits to your agent folder (your own state):
121
121
 
122
122
  Delegate focused work with \`spawn_subagent\`, \`subagent_output\`, and \`subagent_cancel\`. Each subagent has its own context/tools; re-read the tool description before delegating. Briefly: ${subagentRoster}.
123
123
 
124
+ Spawns run in the BACKGROUND by default: the tool returns a task_id immediately and a \`<system-reminder>\` arrives when the subagent completes — do NOT poll \`subagent_output\`. Pass \`run_in_foreground: true\` for a quick call whose result you need inline this turn. Deep-profile subagents (deep investigation, review, planning) always run in the background from here — requesting foreground for one is overridden, and the tool result tells you so.
125
+
124
126
  Pick one of three modes:
125
127
 
126
- **Mode A — Research fan-out.** Broad search: spawn 2-5 \`explorer\`/\`scout\` workers in parallel with \`run_in_background: true\`, end your response, then collect each completion once via \`subagent_output\`. Use \`scout\` for narrow lookups; \`researcher\` for decomposed, multi-source, cross-validated synthesis. When the user *explicitly* says "research"/"investigate" (or equivalent), you MUST spawn \`researcher\` — answering from training memory or a single inline \`web_search\` does not satisfy the request, even if you think you know the answer. (Fanning out \`scout\`/\`explorer\` underneath is fine, but it does not replace \`researcher\`.)
128
+ **Mode A — Research fan-out.** Broad search: spawn 2-5 \`explorer\`/\`scout\` workers in parallel (background by default), end your response, then collect each completion once via \`subagent_output\`. Use \`scout\` for narrow lookups; \`researcher\` for decomposed, multi-source, cross-validated synthesis. When the user *explicitly* says "research"/"investigate" (or equivalent), you MUST spawn \`researcher\` — answering from training memory or a single inline \`web_search\` does not satisfy the request, even if you think you know the answer. (Fanning out \`scout\`/\`explorer\` underneath is fine, but it does not replace \`researcher\`.)
127
129
 
128
- **Mode B — Delegate-and-converse.** For >~30s side-effectful/noisy work (installs, builds, \`docker\`, scrapes, long tests, multi-host loops, fetch-and-synthesize chains), spawn one background subagent and stay responsive: \`operator\` for side effects, \`scout\` quick lookup, \`researcher\` deep investigation, \`planner\` risk-aware sequencing. Keep single fast calls inline. For hard execution work that needs stronger reasoning than the default tier — gnarly bugs, non-obvious refactors, failures that resisted a quick fix — pass \`profile: "deep"\` to run that one spawn on a stronger model; leave it off for routine work. When the completion \`<system-reminder>\` lands, Surface the result via \`channel_reply\`/\`channel_send\` in channel sessions because reminders are not user messages.
130
+ **Mode B — Delegate-and-converse.** For >~30s side-effectful/noisy work (installs, builds, \`docker\`, scrapes, long tests, multi-host loops, fetch-and-synthesize chains), spawn one subagent (background) and stay responsive: \`operator\` for side effects, \`scout\` quick lookup, \`researcher\` deep investigation, \`planner\` risk-aware sequencing. For a quick lookup whose answer you need inline, pass \`run_in_foreground: true\`. For hard execution work that needs stronger reasoning than the default tier — gnarly bugs, non-obvious refactors, failures that resisted a quick fix — pass \`profile: "deep"\` to run that one spawn on a stronger model; leave it off for routine work. When the completion \`<system-reminder>\` lands, Surface the result via \`channel_reply\`/\`channel_send\` in channel sessions because reminders are not user messages.
129
131
 
130
- **Mode C — Troubleshooting.** After ~3 non-converging attempts at the same failure, stop and hand the loop to \`operator\` with \`run_in_background: true\` (and \`profile: "deep"\` when the failure is genuinely hard), symptom, attempts, and success condition. Read \`typeclaw-troubleshooting\` before spawning.
132
+ **Mode C — Troubleshooting.** After ~3 non-converging attempts at the same failure, stop and hand the loop to \`operator\` (background; add \`profile: "deep"\` when the failure is genuinely hard), symptom, attempts, and success condition. Read \`typeclaw-troubleshooting\` before spawning.
131
133
 
132
134
  **Status queries.** If the user asks "status?" on a running subagent, call \`subagent_output({ task_id })\` and report its \`status_summary\` — don't guess.
133
135
 
@@ -182,6 +184,42 @@ export function renderRuntimeBlock(version: string): string {
182
184
  TypeClaw runtime version: ${version}.`
183
185
  }
184
186
 
187
+ // Appended to the system prompt ONLY when `config.branding` is false. Branding
188
+ // off rephrases the opening and drops the version block, but the literal
189
+ // "typeclaw" still reaches the model through functional tokens it can't lose
190
+ // without breaking: bundled skill names (`typeclaw-render-pdf` etc.), the
191
+ // operator CLI (`typeclaw logs -f`), and `typeclaw.json`. Aliasing every one
192
+ // would break skill/tool resolution, so instead of hiding the tokens we tell
193
+ // the model not to surface them as its identity. English-authored on purpose:
194
+ // this is an instruction TO the model (applied in any reply language), not
195
+ // user-text pattern matching, so AGENTS.md's multi-language matching rule does
196
+ // not apply.
197
+ export function renderRuntimeNondisclosureRule(): string {
198
+ return `## Runtime disclosure
199
+
200
+ The operator set \`branding: false\`. Never reveal, name, or hint at the runtime,
201
+ platform, framework, or vendor hosting you — in any language. You are the agent
202
+ defined by IDENTITY.md and SOUL.md; if asked what you run on, who built you, or
203
+ your stack/model/provider, decline briefly and stay in character.
204
+
205
+ Internal tokens you use for real work (skill names, the operator CLI, config
206
+ filenames) are implementation details, not your identity — use them, but never
207
+ surface them as the answer to "what are you running on?"`
208
+ }
209
+
210
+ // Bundled subagent prompts (scout/operator/reviewer/planner/researcher/explorer)
211
+ // open with hardcoded identity prose — "running inside TypeClaw" and, in the
212
+ // planner, "TypeClaw ships a `reviewer`". The nondisclosure rule tells the model
213
+ // not to volunteer the runtime, but that prose STATES it outright, so a
214
+ // branding-off subagent still reads its own name in the first sentence. This
215
+ // strips exactly those two identity phrases (not functional `typeclaw.json`-style
216
+ // tokens) from an override prompt when branding is off, so the rule is not
217
+ // fighting the prose. Kept as exact-literal replacements rather than a broad
218
+ // /typeclaw/i regex precisely so functional tokens survive untouched.
219
+ export function stripRuntimeIdentityProse(prompt: string): string {
220
+ return prompt.replaceAll(' running inside TypeClaw', '').replaceAll('TypeClaw ships a', 'The runtime ships a')
221
+ }
222
+
185
223
  // Wall-clock anchor injected into the **user turn**, not the system prompt.
186
224
  //
187
225
  // Why per-turn instead of session-creation: long-lived channel sessions can
@@ -41,8 +41,9 @@ export function createChannelReactTool({
41
41
  'Pick the reaction a thoughtful teammate would leave: :+1: to agree or approve, :rocket: for something ' +
42
42
  'shipping or exciting, :tada: to celebrate, :heart: to show appreciation, :eyes: to signal "I am looking at this", ' +
43
43
  ':laugh: for something funny. Use it when a reaction adds genuine social signal — not on every message. ' +
44
- 'A reaction does NOT replace `channel_reply`: when the message needs a substantive answer, still send one. ' +
45
- 'If a reaction alone is the whole response, call `skip_response` afterward so the turn ends cleanly. ' +
44
+ 'The reaction is only applied if you ALSO reply to this message in the same turn (via `channel_reply`/' +
45
+ '`channel_send`); if you stay silent or `skip_response`, the reaction is dropped. So do not use a reaction ' +
46
+ 'as a standalone response to a message you are only observing — react to the messages you actually answer. ' +
46
47
  'Pass the bare emoji name, no colons.',
47
48
  parameters: Type.Object({
48
49
  emoji: Type.String({
@@ -66,7 +67,7 @@ export function createChannelReactTool({
66
67
  const reactionRef = getReactionRef()
67
68
  if (reactionRef === undefined) return deny('this conversation has no message to react to')
68
69
 
69
- const result = await router.react({
70
+ const result = await router.queueReactionAfterReply({
70
71
  adapter: origin.adapter,
71
72
  workspace: origin.workspace,
72
73
  chat: origin.chat,
@@ -82,7 +83,7 @@ export function createChannelReactTool({
82
83
  content: [
83
84
  {
84
85
  type: 'text' as const,
85
- text: `${TOOL_RESULT_PREFIX}reacted with :${params.emoji}: on ${origin.adapter}:${origin.workspace}/${origin.chat}`,
86
+ text: `${TOOL_RESULT_PREFIX}will react with :${params.emoji}: on ${origin.adapter}:${origin.workspace}/${origin.chat} if you reply this turn`,
86
87
  },
87
88
  ],
88
89
  details,
@@ -78,14 +78,16 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
78
78
  description: '3-5 word label for this spawn, used for logs and the status_summary. Optional.',
79
79
  }),
80
80
  ),
81
- run_in_background: Type.Optional(
81
+ run_in_foreground: Type.Optional(
82
82
  Type.Boolean({
83
83
  description:
84
- 'When true, the spawn returns immediately with a task_id; the subagent runs in the background and a system-reminder is delivered when it completes. ' +
85
- 'When false (default), the spawn blocks until the subagent finishes and returns its final message synchronously. ' +
86
- 'For PARALLEL fan-out, do NOT use background mode: emit several spawn_subagent calls (sync, the default) in a SINGLE turn — they execute concurrently and all their results return together before your next turn. ' +
87
- 'Reserve background mode for a long-running task you want to keep the conversation moving alongside (Mode B). ' +
88
- 'NOTE: background mode from subagents is only available when that subagent is explicitly enabled to drain child results; otherwise use sync spawns batched in one turn instead.',
84
+ 'Request a FOREGROUND (synchronous) spawn: the tool blocks until the subagent finishes and returns its final message inline. ' +
85
+ 'When omitted (the default) from a top-level session, the spawn runs in the BACKGROUND — it returns a task_id immediately and a system-reminder arrives when it completes; do NOT poll subagent_output. ' +
86
+ 'The runtime may override your request and always states which mode it used and why in the tool result: ' +
87
+ 'a deep-profile subagent spawned from a top-level session is forced to the background (a foreground run would freeze this session while it works), ' +
88
+ 'and a background spawn requested from a subagent session that cannot drain child results is degraded to foreground so the result still reaches you. ' +
89
+ 'From a subagent session the default is foreground — which is what you need to fold a delegated result into your own output; ' +
90
+ 'for PARALLEL fan-out, emit several foreground spawns in a SINGLE turn and their results return together.',
89
91
  }),
90
92
  ),
91
93
  profile: Type.Optional(
@@ -115,17 +117,19 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
115
117
  `subagent.spawn denied: maximum delegation depth (${MAX_SUBAGENT_DEPTH}) reached; a subagent at this depth cannot spawn further subagents`,
116
118
  )
117
119
  }
118
- if (origin?.kind === 'subagent' && params.run_in_background === true && allowBackgroundFromSubagent !== true) {
119
- return errorResult(
120
- 'subagent.spawn denied: background spawning is not available from a subagent session because the result cannot be delivered after this turn ends. ' +
121
- 'Retry with run_in_background=false (or omit it) — the synchronous spawn blocks until the child finishes and returns its result into your context, ' +
122
- 'which is what you need to fold the result into your output.',
123
- )
124
- }
120
+ const subagentName = params.subagent_type
121
+ const { background, overrideNote } = resolveSpawnMode({
122
+ foreground: params.run_in_foreground,
123
+ fromSubagent: origin?.kind === 'subagent',
124
+ // Deep-profile spawns run for minutes; forcing them background from a
125
+ // top-level session keeps a foreground run from freezing the message
126
+ // loop. Per-spawn override wins over the declared profile.
127
+ isDeepProfile: (params.profile ?? subagent.profile) === 'deep',
128
+ canBackgroundFromSubagent: allowBackgroundFromSubagent === true,
129
+ subagentName,
130
+ })
125
131
 
126
132
  const taskId = generateTaskId()
127
- const subagentName = params.subagent_type
128
- const background = params.run_in_background === true
129
133
  const payload: Record<string, unknown> = { requestId: taskId, prompt: params.prompt }
130
134
  if (params.description !== undefined) payload.description = params.description
131
135
  if (params.profile !== undefined) payload.profile = params.profile
@@ -200,11 +204,12 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
200
204
  taskId,
201
205
  sessionId: resolvedHandle.sessionId,
202
206
  }
207
+ const baseText = `Spawned ${subagentName} in background. task_id=${taskId}. You will receive a system-reminder when it completes. Use subagent_output to check progress or fetch results.`
203
208
  return {
204
209
  content: [
205
210
  {
206
211
  type: 'text' as const,
207
- text: `Spawned ${subagentName} in background. task_id=${taskId}. You will receive a system-reminder when it completes. Use subagent_output to check progress or fetch results.`,
212
+ text: overrideNote !== undefined ? `${overrideNote}\n\n${baseText}` : baseText,
208
213
  },
209
214
  ],
210
215
  details,
@@ -223,11 +228,12 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
223
228
  result.finalMessage !== undefined
224
229
  ? ` It produced output before failing; recover it below instead of redoing the work:\n\n${result.finalMessage}`
225
230
  : ''
231
+ const failureText = `${subagentName} failed after ${durationMs}ms: ${result.error}.${recovered}`
226
232
  return {
227
233
  content: [
228
234
  {
229
235
  type: 'text' as const,
230
- text: `${subagentName} failed after ${durationMs}ms: ${result.error}.${recovered}`,
236
+ text: overrideNote !== undefined ? `${overrideNote}\n\n${failureText}` : failureText,
231
237
  },
232
238
  ],
233
239
  details,
@@ -242,14 +248,15 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
242
248
  durationMs,
243
249
  ...(result.finalMessage !== undefined ? { finalMessage: result.finalMessage } : {}),
244
250
  }
251
+ const syncText =
252
+ result.finalMessage !== undefined
253
+ ? result.finalMessage
254
+ : `${subagentName} completed in ${durationMs}ms with no final message.`
245
255
  return {
246
256
  content: [
247
257
  {
248
258
  type: 'text' as const,
249
- text:
250
- result.finalMessage !== undefined
251
- ? result.finalMessage
252
- : `${subagentName} completed in ${durationMs}ms with no final message.`,
259
+ text: overrideNote !== undefined ? `${overrideNote}\n\n${syncText}` : syncText,
253
260
  },
254
261
  ],
255
262
  details,
@@ -265,9 +272,9 @@ export function spawnSubagentDescription(registry: SubagentRegistry): string {
265
272
  `Spawn a subagent to do focused work on your behalf. Use this when a task is heavy enough to deserve a fresh context window (research fan-out) ` +
266
273
  `or long-running enough that you want to keep the conversation moving while it runs (delegate-and-converse). ` +
267
274
  `Available subagents: ${available}. ` +
268
- `When run_in_background=true (preferred for long-running work), the tool returns a task_id immediately and the subagent runs concurrently — ` +
269
- `you will receive a system-reminder when it completes; do NOT poll subagent_output. ` +
270
- `When run_in_background=false (default), the tool blocks and returns the subagent's final message synchronously. ` +
275
+ `The default mode depends on the caller's origin: a top-level session defaults to background (the tool returns a task_id immediately and a system-reminder arrives when the subagent completes — do NOT poll subagent_output), while a subagent session defaults to foreground so the result folds into your own output. ` +
276
+ `Pass run_in_foreground=true to force a blocking inline result, or run_in_foreground=false to request background. ` +
277
+ `The runtime may override the mode and states which it used and why in the tool result (a deep-profile subagent is forced to the background from a top-level session; a background request from a subagent that cannot drain child results degrades to foreground). ` +
271
278
  `The delegation chain is depth-limited: a subagent you spawn may itself delegate once more, but no deeper — ` +
272
279
  `keep your delegation tree shallow.`
273
280
  )
@@ -360,3 +367,52 @@ function errorResult(message: string): ToolReturn {
360
367
  details,
361
368
  }
362
369
  }
370
+
371
+ export type SpawnModeResolution = {
372
+ background: boolean
373
+ overrideNote: string | undefined
374
+ }
375
+
376
+ // Resolve foreground vs background for a spawn, with the runtime free to
377
+ // override the caller's request and report why. Two axes decide it: whether the
378
+ // caller is a top-level session (its turn services the live message loop) or a
379
+ // subagent (its turn does not), and whether the child runs on the deep profile.
380
+ // `foreground` is the tri-state tool param: undefined means the caller did not
381
+ // choose, so the origin default applies.
382
+ //
383
+ // - Top-level default is background: a long child must not block the loop.
384
+ // Deep-profile children are forced background even when foreground is asked.
385
+ // - Subagent default is foreground: the sync result folds into the caller's own
386
+ // output (e.g. planner -> reviewer). A subagent can still opt into background
387
+ // with foreground=false, but only when the runtime can drain child
388
+ // completions; otherwise that request degrades to foreground so the result is
389
+ // not lost.
390
+ export function resolveSpawnMode(input: {
391
+ foreground: boolean | undefined
392
+ fromSubagent: boolean
393
+ isDeepProfile: boolean
394
+ canBackgroundFromSubagent: boolean
395
+ subagentName: string
396
+ }): SpawnModeResolution {
397
+ const { foreground, fromSubagent, isDeepProfile, canBackgroundFromSubagent, subagentName } = input
398
+
399
+ if (fromSubagent) {
400
+ const wantsBackground = foreground === false
401
+ if (wantsBackground && !canBackgroundFromSubagent) {
402
+ return {
403
+ background: false,
404
+ overrideNote: `\`${subagentName}\` was spawned in the FOREGROUND: a subagent session cannot drain background children after its turn ends, so a foreground run is the only way its result reaches you.`,
405
+ }
406
+ }
407
+ return { background: wantsBackground, overrideNote: undefined }
408
+ }
409
+
410
+ if (isDeepProfile && foreground === true) {
411
+ return {
412
+ background: true,
413
+ overrideNote: `\`${subagentName}\` was spawned in the BACKGROUND despite the foreground request: it runs on the deep profile (minutes of work), and a foreground run would freeze this session until it finished. A completion reminder will arrive when it is done.`,
414
+ }
415
+ }
416
+
417
+ return { background: foreground !== true, overrideNote: undefined }
418
+ }
@@ -80,7 +80,7 @@ PREFER the two purpose-built research workers for any quick search or gathering
80
80
  - \`scout\` — web research. Spawn it for ANYTHING that lives on the public internet: prices, schedules, opening hours, standard timelines, prevailing practice, vendor docs, prior art, "what are the options for X". It returns a focused, citation-backed answer. This is your default for the research-resolvable facts a plan rests on.
81
81
  - \`explorer\` — local filesystem search. Spawn it to understand the existing code, config, sessions, memory, or git history on this agent — "what does this module do", "where is X configured", "summarize the shape of this system" — before planning a change to it.
82
82
 
83
- Lean on these liberally. A quick \`scout\` for real prices or a quick \`explorer\` for the actual shape of a module turns an assumption-laden plan into a grounded one, and it costs you almost nothing because the heavy reading happens in their context, not yours. When a plan depends on multiple independent facts, **fan out in parallel**: either emit all the independent \`spawn_subagent\` calls (sync, the default) in a SINGLE turn so they run concurrently and return together, or spawn them with \`run_in_background=true\` and fold each result in as its \`<system-reminder>\` arrives (your session stays alive until every child reports back). Either way, fold the distilled results into your single planning pass; do NOT spawn one, wait, then spawn the next unless the second genuinely depends on the first — that serializes what should be parallel.
83
+ Lean on these liberally. A quick \`scout\` for real prices or a quick \`explorer\` for the actual shape of a module turns an assumption-laden plan into a grounded one, and it costs you almost nothing because the heavy reading happens in their context, not yours. When a plan depends on multiple independent facts, **fan out in parallel**: either emit all the independent \`spawn_subagent\` calls (foreground, the default from your session) in a SINGLE turn so they run concurrently and return together, or spawn them with \`run_in_foreground=false\` and fold each result in as its \`<system-reminder>\` arrives (your session stays alive until every child reports back). Either way, fold the distilled results into your single planning pass; do NOT spawn one, wait, then spawn the next unless the second genuinely depends on the first — that serializes what should be parallel.
84
84
 
85
85
  - Spawn these workers for context-heavy GATHERING, not for forming the plan. The decomposition, the sequencing, and the verdict are YOURS — never delegate the judgment.
86
86
  - Each delegated task must be self-contained: the worker does not see this conversation or the goal. Put everything it needs in the prompt.
@@ -70,8 +70,8 @@ You run on a deliberately expensive model. Every search result page and every fe
70
70
  **Delegate first; fetch yourself only as a last resort.** Before you reach for \`web_search\`, \`web_fetch\`, \`read\`, or \`grep\`, ask: "could \`scout\` or \`explorer\` get this for me and hand back just the distilled answer?" If yes — which is almost always — spawn the worker with \`spawn_subagent\`.
71
71
 
72
72
  **Fan out in parallel.** For a gathering round, emit several \`scout\`/\`explorer\` \`spawn_subagent\` calls together in a SINGLE turn so they run concurrently rather than one-at-a-time. You have two equivalent ways to do this, both of which deliver every worker's findings back to you:
73
- - **Synchronous batch (simplest):** emit the calls with \`run_in_background=false\` (the default) in one assistant message. They execute concurrently and all results return together before your next turn, where you fold them into one synthesis pass.
74
- - **Background:** emit them with \`run_in_background=true\`; each returns a task_id immediately and you receive a \`<system-reminder>\` as each completes, then fetch the result with \`subagent_output\`. Use this when you want to start synthesizing on early results while slower workers finish. Your session stays alive until every background child you spawned has reported back, so no result is lost.
73
+ - **Synchronous batch (simplest, the default):** emit the calls in one assistant message with no mode flag. From your subagent session they run in the FOREGROUND by default — they execute concurrently and all results return together before your next turn, where you fold them into one synthesis pass.
74
+ - **Background:** emit them with \`run_in_foreground=false\`; each returns a task_id immediately and you receive a \`<system-reminder>\` as each completes, then fetch the result with \`subagent_output\`. Use this when you want to start synthesizing on early results while slower workers finish. Your session stays alive until every background child you spawned has reported back, so no result is lost.
75
75
 
76
76
  Either way, do NOT spawn one, wait for it, then spawn the next unless the second task genuinely depends on the first's result — that serializes what should be parallel.
77
77
 
@@ -92,7 +92,7 @@ This is not a last resort — it is your DEFAULT for any non-trivial target, and
92
92
  - Spawn read-only/research workers (\`scout\`, \`explorer\`) for context-heavy gathering, not for forming the verdict. The findings and the \`<review>\` block are YOURS — never delegate the judgment.
93
93
  - Each delegated task must be self-contained: the worker does not see this conversation or the target. Put everything it needs in the prompt.
94
94
  - The chain is depth-limited: a worker you spawn cannot spawn again. Keep delegation one level deep.
95
- - \`subagent_output\`/\`subagent_cancel\` reach only the tasks YOU spawned. To gather in parallel, either emit all the independent \`spawn_subagent\` calls (sync, the default) in a SINGLE turn so they run concurrently and return together, or spawn them with \`run_in_background=true\` and fold each result in as its \`<system-reminder>\` arrives (your session stays alive until every child reports back). Either way, fold the results into your single review pass before you finish.
95
+ - \`subagent_output\`/\`subagent_cancel\` reach only the tasks YOU spawned. To gather in parallel, either emit all the independent \`spawn_subagent\` calls (foreground, the default from your session) in a SINGLE turn so they run concurrently and return together, or spawn them with \`run_in_foreground=false\` and fold each result in as its \`<system-reminder>\` arrives (your session stays alive until every child reports back). Either way, fold the results into your single review pass before you finish.
96
96
 
97
97
  ## Tools
98
98
 
@@ -0,0 +1,73 @@
1
+ import type { InboundMessage } from '@/channels/types'
2
+
3
+ const DISCORD_API_BASE = 'https://discord.com/api/v10'
4
+ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000
5
+
6
+ // Discord channel `type` values that are threads (public, private, announcement
7
+ // threads). A Discord thread is its OWN channel — a thread message arrives with
8
+ // `chat = <thread-channel-id>` and `thread = null`, unlike Slack where the
9
+ // thread ts rides `thread`. So the only way to know an inbound is in a thread
10
+ // room is to look up the channel's type; the gateway MESSAGE_CREATE event
11
+ // carries no thread/parent signal.
12
+ const DISCORD_THREAD_CHANNEL_TYPES: ReadonlySet<number> = new Set([10, 11, 12])
13
+
14
+ export type DiscordChannelMeta = { type?: number; parent_id?: string }
15
+
16
+ // The lookup has THREE outcomes, and the failure case must not be conflated
17
+ // with a confirmed non-thread channel:
18
+ // - a channel object → we know the type (thread or not)
19
+ // - 'unknown' → the fetch failed (network / non-OK / rate limit); we cannot
20
+ // tell, so downstream must fail closed rather than assume "normal channel".
21
+ type ChannelMetaLookup = DiscordChannelMeta | 'unknown'
22
+
23
+ export type DiscordThreadRoomResolverOptions = {
24
+ token: string
25
+ fetchImpl?: typeof fetch
26
+ now?: () => number
27
+ ttlMs?: number
28
+ }
29
+
30
+ // Maps a lookup outcome to the room signal. A confirmed thread carries its
31
+ // parent for membership scoping; a confirmed non-thread returns undefined (the
32
+ // solo fallback may apply). An 'unknown' fetch failure returns a bare thread
33
+ // room WITHOUT parentChat: it fails the engagement gate closed (so the bot
34
+ // won't butt into a possibly-thread it can't classify) while still resolving
35
+ // membership against the thread's own channel — the same conservative posture
36
+ // as a private thread whose parent we can't read.
37
+ export function discordThreadRoom(meta: ChannelMetaLookup): InboundMessage['room'] {
38
+ if (meta === 'unknown') return { kind: 'thread' }
39
+ if (meta.type === undefined || !DISCORD_THREAD_CHANNEL_TYPES.has(meta.type)) return undefined
40
+ return meta.parent_id !== undefined ? { kind: 'thread', parentChat: meta.parent_id } : { kind: 'thread' }
41
+ }
42
+
43
+ export function createDiscordThreadRoomResolver(
44
+ options: DiscordThreadRoomResolverOptions,
45
+ ): (channelId: string) => Promise<InboundMessage['room']> {
46
+ const fetchImpl = options.fetchImpl ?? fetch
47
+ const now = options.now ?? Date.now
48
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
49
+ const cache = new Map<string, { value: DiscordChannelMeta; expiresAt: number }>()
50
+
51
+ return async (channelId: string): Promise<InboundMessage['room']> => {
52
+ const cached = cache.get(channelId)
53
+ if (cached !== undefined && cached.expiresAt > now()) return discordThreadRoom(cached.value)
54
+ // Only CONFIRMED metadata is cached. A failed lookup ('unknown') is not
55
+ // cached, so the next message on this channel retries rather than pinning
56
+ // the fail-closed state for the whole TTL.
57
+ const meta = await fetchChannelMeta(channelId)
58
+ if (meta !== 'unknown') cache.set(channelId, { value: meta, expiresAt: now() + ttlMs })
59
+ return discordThreadRoom(meta)
60
+ }
61
+
62
+ async function fetchChannelMeta(channelId: string): Promise<ChannelMetaLookup> {
63
+ try {
64
+ const response = await fetchImpl(`${DISCORD_API_BASE}/channels/${encodeURIComponent(channelId)}`, {
65
+ headers: { Authorization: `Bot ${options.token}` },
66
+ })
67
+ if (!response.ok) return 'unknown'
68
+ return (await response.json()) as DiscordChannelMeta
69
+ } catch {
70
+ return 'unknown'
71
+ }
72
+ }
73
+ }