typeclaw 0.42.1 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/auth.schema.json +16 -0
- package/package.json +1 -1
- package/secrets.schema.json +16 -0
- package/src/agent/live-subagents.ts +4 -4
- package/src/agent/plugin-tools.ts +8 -2
- package/src/agent/session-origin.ts +6 -3
- package/src/agent/system-prompt.ts +5 -3
- package/src/agent/tools/channel-react.ts +5 -4
- package/src/agent/tools/spawn-subagent.ts +80 -24
- package/src/bundled-plugins/planner/planner.ts +1 -1
- package/src/bundled-plugins/researcher/researcher.ts +2 -2
- package/src/bundled-plugins/reviewer/reviewer.ts +1 -1
- package/src/channels/adapters/discord-bot-thread-room.ts +73 -0
- package/src/channels/adapters/discord-bot.ts +9 -1
- package/src/channels/adapters/slack-bot-classify.ts +1 -0
- package/src/channels/adapters/slack-classify.ts +1 -0
- package/src/channels/engagement.ts +33 -0
- package/src/channels/router.ts +139 -19
- package/src/channels/types.ts +10 -0
- package/src/cli/command-meta.ts +2 -0
- package/src/cli/index.ts +1 -0
- package/src/cli/mcp.ts +233 -0
- package/src/hostd/daemon.ts +28 -9
- package/src/hostd/protocol.ts +12 -9
- package/src/mcp/client.ts +15 -5
- package/src/mcp/index.ts +12 -0
- package/src/mcp/manager.ts +9 -4
- package/src/mcp/oauth.ts +212 -0
- package/src/run/index.ts +15 -2
- package/src/sandbox/hidden-paths.ts +59 -0
- package/src/sandbox/index.ts +1 -1
- package/src/secrets/index.ts +1 -1
- package/src/secrets/schema.ts +13 -0
- package/src/secrets/secrets-provider.ts +2 -2
- package/src/secrets/storage.ts +108 -1
- package/src/skills/typeclaw-channel-github/SKILL.md +2 -2
- 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
package/secrets.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": [
|
|
@@ -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
|
|
27
|
-
// their result out-of-band (via the subagent.completed broadcast and
|
|
28
|
-
// parent's drain);
|
|
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:
|
|
617
|
-
: { masks:
|
|
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.
|
|
433
|
-
'
|
|
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
|
|
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
|
|
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
|
|
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\`
|
|
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
|
|
|
@@ -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
|
-
'
|
|
45
|
-
'
|
|
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.
|
|
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}
|
|
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
|
-
|
|
81
|
+
run_in_foreground: Type.Optional(
|
|
82
82
|
Type.Boolean({
|
|
83
83
|
description:
|
|
84
|
-
'
|
|
85
|
-
'When
|
|
86
|
-
'
|
|
87
|
-
'
|
|
88
|
-
'
|
|
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
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
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:
|
|
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: `${
|
|
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
|
-
`
|
|
269
|
-
`
|
|
270
|
-
`
|
|
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 (
|
|
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
|
|
74
|
-
- **Background:** emit them with \`
|
|
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 (
|
|
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
|
+
}
|
|
@@ -55,6 +55,7 @@ import {
|
|
|
55
55
|
registerCommands,
|
|
56
56
|
type DiscordCommandDeclaration,
|
|
57
57
|
} from './discord-bot-slash-commands'
|
|
58
|
+
import { createDiscordThreadRoomResolver } from './discord-bot-thread-room'
|
|
58
59
|
import { addDiscordMentionHints, type DiscordMentionUser } from './mention-hints'
|
|
59
60
|
|
|
60
61
|
// One declared slash command per logical agent gesture. /stop maps to the
|
|
@@ -954,6 +955,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
|
|
|
954
955
|
let stopWaiters: Array<() => void> = []
|
|
955
956
|
|
|
956
957
|
const channelResolver = createDiscordChannelResolver({ token: options.token })
|
|
958
|
+
const threadRoomResolver = createDiscordThreadRoomResolver({ token: options.token, fetchImpl })
|
|
957
959
|
|
|
958
960
|
// Discord mentions by snowflake id (`<@id>`/`<@!id>`), so no username form.
|
|
959
961
|
const selfIdentityResolver: ChannelSelfIdentityResolver = () => (botUserId !== null ? { id: botUserId } : null)
|
|
@@ -1061,10 +1063,16 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
|
|
|
1061
1063
|
}
|
|
1062
1064
|
},
|
|
1063
1065
|
})
|
|
1064
|
-
|
|
1066
|
+
// Discord threads are their own channels (`chat = thread id`, `thread`
|
|
1067
|
+
// stays null), so the engagement gate cannot see "this is a thread" from
|
|
1068
|
+
// the payload alone. Resolve the channel's type/parent and stamp the
|
|
1069
|
+
// structural `room` signal for guild inbounds; DMs are never thread rooms.
|
|
1070
|
+
const room = event.guild_id !== undefined ? await threadRoomResolver(event.channel_id) : undefined
|
|
1071
|
+
const basePayload =
|
|
1065
1072
|
referenceResult.referenceContext === undefined
|
|
1066
1073
|
? { ...verdict.payload, text: hintedText }
|
|
1067
1074
|
: { ...verdict.payload, text: hintedText, referenceContext: referenceResult.referenceContext }
|
|
1075
|
+
const payload = room !== undefined ? { ...basePayload, room } : basePayload
|
|
1068
1076
|
|
|
1069
1077
|
const routedTag = await formatChannelTag(payload.workspace, payload.chat)
|
|
1070
1078
|
logger.info(
|
|
@@ -143,6 +143,7 @@ export function classifyInbound(
|
|
|
143
143
|
workspace,
|
|
144
144
|
chat: event.channel,
|
|
145
145
|
thread,
|
|
146
|
+
...(thread !== null ? { room: { kind: 'thread' as const } } : {}),
|
|
146
147
|
...(typingThread !== undefined ? { typingThread } : {}),
|
|
147
148
|
text,
|
|
148
149
|
...(attachments.length > 0 ? { attachments } : {}),
|
|
@@ -49,6 +49,7 @@ export function classifyInbound(
|
|
|
49
49
|
workspace,
|
|
50
50
|
chat: event.channel,
|
|
51
51
|
thread,
|
|
52
|
+
...(thread !== null ? { room: { kind: 'thread' as const } } : {}),
|
|
52
53
|
text: rawText,
|
|
53
54
|
externalMessageId: event.ts,
|
|
54
55
|
reactionRef: encodeSlackReactionRef({ channel: event.channel, ts: event.ts }),
|
|
@@ -216,11 +216,44 @@ export function decideEngagement(input: EngagementInput): EngagementDecision {
|
|
|
216
216
|
// fallback fix.
|
|
217
217
|
if (targetsSomeoneElse(message, participants, botInThread)) return 'observe'
|
|
218
218
|
|
|
219
|
+
// Thread solo-fallback fail-closed gate. A thread is a SEPARATE live session
|
|
220
|
+
// from its parent channel (the participant/membership key carries the thread
|
|
221
|
+
// suffix — see `channelKeyId`), so a freshly-opened thread starts with one
|
|
222
|
+
// known speaker and a cold membership cache. That collapses `effectiveHumans`
|
|
223
|
+
// to ≤1 and would trip the solo-human fallback below, making the bot butt
|
|
224
|
+
// into a thread it was never part of in a busy multi-human channel. Membership
|
|
225
|
+
// is a room property, not a thread property, so a thread may ride the fallback
|
|
226
|
+
// ONLY on a fresh, complete membership read that itself proves ≤1 human; null
|
|
227
|
+
// / truncated / stale reads fail closed to `observe`. Exemptions: DMs (solo by
|
|
228
|
+
// construction) and threads the bot ALREADY participates in (`botInThread` —
|
|
229
|
+
// an established conversation, not an un-addressed intrusion; this is the same
|
|
230
|
+
// escape hatch the `replyToOtherMessageId` suppressor uses). Non-thread solo
|
|
231
|
+
// channels keep the legacy answer-everything fallback untouched.
|
|
232
|
+
//
|
|
233
|
+
// `isThreadRoom` reads the structural `room` signal FIRST so this fires for
|
|
234
|
+
// Discord threads too (their `thread` is null — the thread id lives in
|
|
235
|
+
// `chat`), falling back to `thread !== null` for Slack-shaped inbounds.
|
|
236
|
+
if (isThreadRoom(message) && !botInThread && !isFreshCompleteSoloRoom(input.membership, now)) {
|
|
237
|
+
return 'observe'
|
|
238
|
+
}
|
|
239
|
+
|
|
219
240
|
if (effectiveHumans <= 1 && !message.authorIsBot) return 'engage'
|
|
220
241
|
|
|
221
242
|
return 'observe'
|
|
222
243
|
}
|
|
223
244
|
|
|
245
|
+
function isThreadRoom(message: InboundMessage): boolean {
|
|
246
|
+
if (message.isDm) return false
|
|
247
|
+
return message.room?.kind === 'thread' || message.thread !== null
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function isFreshCompleteSoloRoom(membership: MembershipCount | null, now: number): boolean {
|
|
251
|
+
if (membership === null) return false
|
|
252
|
+
if (membership.truncated) return false
|
|
253
|
+
if (now - membership.fetchedAt >= MEMBERSHIP_FRESHNESS_MS) return false
|
|
254
|
+
return membership.humans <= 1
|
|
255
|
+
}
|
|
256
|
+
|
|
224
257
|
// Structural "this message is addressed to someone other than us" test. Pure
|
|
225
258
|
// over adapter-classified booleans + observed peer names — no semantic text
|
|
226
259
|
// interpretation, so it is safe for the content-blind engagement gate. Shared
|