typeclaw 0.42.0 → 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.
Files changed (89) hide show
  1. package/auth.schema.json +16 -0
  2. package/package.json +3 -3
  3. package/secrets.schema.json +16 -0
  4. package/src/agent/adaptive-thinking-compat.ts +79 -0
  5. package/src/agent/index.ts +79 -101
  6. package/src/agent/live-subagents.ts +4 -4
  7. package/src/agent/plugin-tools.ts +85 -132
  8. package/src/agent/provider-error.ts +37 -0
  9. package/src/agent/reload-tool.ts +1 -1
  10. package/src/agent/session-origin.ts +6 -3
  11. package/src/agent/subagents.ts +2 -2
  12. package/src/agent/system-prompt.ts +24 -8
  13. package/src/agent/tool-result-budget.ts +1 -1
  14. package/src/agent/tools/channel-react.ts +5 -4
  15. package/src/agent/tools/spawn-subagent.ts +80 -24
  16. package/src/agent/tools/stream-snapshot.ts +8 -3
  17. package/src/bundled-plugins/agent-browser/index.ts +18 -8
  18. package/src/bundled-plugins/memory/README.md +4 -1
  19. package/src/bundled-plugins/memory/belief-sentence.ts +50 -0
  20. package/src/bundled-plugins/memory/dreaming.ts +13 -6
  21. package/src/bundled-plugins/memory/load-memory.ts +22 -2
  22. package/src/bundled-plugins/memory/memory-logger.ts +1 -1
  23. package/src/bundled-plugins/planner/planner.ts +1 -1
  24. package/src/bundled-plugins/researcher/researcher.ts +2 -2
  25. package/src/bundled-plugins/reviewer/reviewer.ts +1 -1
  26. package/src/capabilities/control-plane.ts +24 -0
  27. package/src/capabilities/index.ts +2 -0
  28. package/src/capabilities/runtime.ts +30 -0
  29. package/src/channels/adapters/discord-bot-thread-room.ts +73 -0
  30. package/src/channels/adapters/discord-bot.ts +9 -1
  31. package/src/channels/adapters/slack-bot-classify.ts +1 -0
  32. package/src/channels/adapters/slack-classify.ts +1 -0
  33. package/src/channels/engagement.ts +33 -0
  34. package/src/channels/manager.ts +41 -47
  35. package/src/channels/router.ts +150 -21
  36. package/src/channels/types.ts +10 -0
  37. package/src/cli/channel.ts +49 -12
  38. package/src/cli/command-meta.ts +2 -0
  39. package/src/cli/hostd.ts +4 -3
  40. package/src/cli/index.ts +1 -0
  41. package/src/cli/logs.ts +2 -2
  42. package/src/cli/mcp.ts +233 -0
  43. package/src/cli/restart.ts +5 -3
  44. package/src/cli/shell.ts +2 -2
  45. package/src/cli/start.ts +2 -2
  46. package/src/cli/status.ts +2 -2
  47. package/src/cli/stop.ts +2 -2
  48. package/src/compose/restart.ts +4 -3
  49. package/src/compose/start.ts +2 -2
  50. package/src/compose/stop.ts +2 -2
  51. package/src/config/config.ts +10 -1
  52. package/src/config/providers.ts +61 -9
  53. package/src/container/controller.ts +104 -0
  54. package/src/container/index.ts +9 -0
  55. package/src/hostd/daemon.ts +28 -9
  56. package/src/hostd/protocol.ts +12 -9
  57. package/src/init/index.ts +1 -1
  58. package/src/init/instagram-auth.ts +189 -34
  59. package/src/inspect/logs-item.ts +2 -2
  60. package/src/mcp/client.ts +16 -6
  61. package/src/mcp/index.ts +12 -0
  62. package/src/mcp/manager.ts +9 -4
  63. package/src/mcp/oauth.ts +212 -0
  64. package/src/run/index.ts +36 -11
  65. package/src/run/{codex-fetch-observer.ts → llm-fetch-observer.ts} +182 -82
  66. package/src/sandbox/availability.ts +2 -2
  67. package/src/sandbox/build.ts +1 -1
  68. package/src/sandbox/hidden-paths.ts +59 -0
  69. package/src/sandbox/index.ts +1 -1
  70. package/src/sandbox/policy.ts +2 -2
  71. package/src/secrets/discord-store.ts +4 -13
  72. package/src/secrets/index.ts +1 -1
  73. package/src/secrets/instagram-store.ts +4 -13
  74. package/src/secrets/kakao-store.ts +4 -13
  75. package/src/secrets/line-store.ts +4 -13
  76. package/src/secrets/schema.ts +13 -0
  77. package/src/secrets/secrets-provider.ts +86 -0
  78. package/src/secrets/slack-store.ts +4 -13
  79. package/src/secrets/storage.ts +108 -1
  80. package/src/secrets/webex-store.ts +4 -13
  81. package/src/server/index.ts +2 -2
  82. package/src/skills/typeclaw-channel-github/SKILL.md +2 -2
  83. package/src/skills/typeclaw-channel-instagram/SKILL.md +1 -1
  84. package/src/skills/typeclaw-config/SKILL.md +5 -3
  85. package/src/skills/typeclaw-plugins/SKILL.md +1 -1
  86. package/src/skills/typeclaw-troubleshooting/SKILL.md +1 -1
  87. package/src/stream/broker.ts +4 -3
  88. package/src/stream/types.ts +1 -0
  89. package/typeclaw.schema.json +14 -0
@@ -1,20 +1,19 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks'
2
2
  import { join } from 'node:path'
3
3
 
4
- import type { AgentTool } from '@mariozechner/pi-agent-core'
5
4
  import {
6
- createBashTool as piCreateBashTool,
5
+ createBashToolDefinition as piCreateBashToolDefinition,
6
+ createEditToolDefinition as piCreateEditToolDefinition,
7
+ createFindToolDefinition as piCreateFindToolDefinition,
8
+ createGrepToolDefinition as piCreateGrepToolDefinition,
9
+ createLsToolDefinition as piCreateLsToolDefinition,
10
+ createReadToolDefinition as piCreateReadToolDefinition,
11
+ createWriteToolDefinition as piCreateWriteToolDefinition,
7
12
  defineTool as piDefineTool,
8
- editTool as piEditTool,
9
- findTool as piFindTool,
10
- grepTool as piGrepTool,
11
- lsTool as piLsTool,
12
- readTool as piReadTool,
13
- writeTool as piWriteTool,
14
13
  } from '@mariozechner/pi-coding-agent'
15
14
  import type { BashSpawnContext, ToolDefinition } from '@mariozechner/pi-coding-agent'
16
- import type { Static, TSchema } from '@sinclair/typebox'
17
- import { Type } from '@sinclair/typebox'
15
+ import type { Static, TSchema } from 'typebox'
16
+ import { Type } from 'typebox'
18
17
  import { z } from 'zod'
19
18
 
20
19
  import {
@@ -41,6 +40,7 @@ import {
41
40
  commandNeedsRealProc,
42
41
  DEFAULT_SANDBOX_ENV,
43
42
  ensureBwrapAvailable,
43
+ ensureHiddenMaskTargets,
44
44
  ensureSessionTmpDir,
45
45
  getProcBindSafetyVerdict,
46
46
  isPackageInstallCommand,
@@ -102,8 +102,6 @@ function bashSpawnHookWithOverlay(context: BashSpawnContext): BashSpawnContext {
102
102
  return { ...context, env: { ...context.env, ...overlay } }
103
103
  }
104
104
 
105
- const piBashTool = piCreateBashTool(process.cwd(), { spawnHook: bashSpawnHookWithOverlay })
106
-
107
105
  const ACKNOWLEDGE_GUARDS_SCHEMA = Type.Optional(
108
106
  Type.Object(
109
107
  {
@@ -115,31 +113,50 @@ const ACKNOWLEDGE_GUARDS_SCHEMA = Type.Optional(
115
113
  ),
116
114
  )
117
115
 
118
- // pi-coding-agent 0.67.3 contract (load-bearing for hook coverage):
119
- // - `createAgentSession({ tools: AgentTool[] })` is ONLY a name filter for
120
- // `initialActiveToolNames`. It does NOT swap builtin implementations.
121
- // - `customTools: ToolDefinition[]` entries override builtins by name in
122
- // `_refreshToolRegistry` (the registry merge writes customTools last).
116
+ // pi-coding-agent 0.73 contract (load-bearing for hook coverage):
117
+ // - `createAgentSession({ tools: string[] })` is a name allowlist: only the
118
+ // listed names stay active, and that allowlist gates BOTH builtins and
119
+ // custom tools (see `allowedToolNames` in pi's `_refreshToolRegistry`).
120
+ // - `noTools: "builtin"` drops pi's read/bash/edit/write from the INITIAL
121
+ // active set; pi still registers its base builtins, so a same-named entry
122
+ // in `customTools` is what overrides the implementation (registry
123
+ // last-write-wins). Passing an explicit `tools:` allowlist plus shipping all
124
+ // seven wrapped builtins is what makes the wrapped versions the only
125
+ // callable ones.
123
126
  //
124
- // Consequence: to put a `tool.before` hook around pi's builtin read/bash/edit/
125
- // write, TypeClaw must wrap them as `ToolDefinition`s and pass them via
126
- // `customTools` — not via `tools`. `wrapAgentToolAsCustomToolDefinition`
127
- // produces those wrapped definitions; `setupSession` in `src/agent/index.ts`
128
- // appends them whenever the session has any `tool.before` / `tool.after`
129
- // hooks registered. Subagent narrowing still comes from `tools:` (the
130
- // name-filter path); the wrapped customTools just replace the implementation
131
- // underneath so subagent and channel sessions share the same hook coverage.
132
- type PiAgentToolName = 'read' | 'bash' | 'edit' | 'write' | 'grep' | 'find' | 'ls'
127
+ // Consequence: every builtin enters as a `ToolDefinition` (pi now exposes
128
+ // `create*ToolDefinition` factories), TypeClaw wraps each one with its hook +
129
+ // guard + sandbox pipeline, and the call site routes them through `customTools`
130
+ // while narrowing via `tools:` names. There is no longer an `AgentTool` vs
131
+ // `ToolDefinition` split.
132
+ type PiBuiltinToolName = 'read' | 'bash' | 'edit' | 'write' | 'grep' | 'find' | 'ls'
133
133
  type TypeclawToolName = 'web_search' | 'web_fetch'
134
134
 
135
- const PI_AGENT_TOOL_MAP: Record<PiAgentToolName, AgentTool<any, any>> = {
136
- read: piReadTool,
137
- bash: piBashTool,
138
- edit: piEditTool,
139
- write: piWriteTool,
140
- grep: piGrepTool,
141
- find: piFindTool,
142
- ls: piLsTool,
135
+ const PI_BUILTIN_TOOL_NAMES: readonly PiBuiltinToolName[] = ['read', 'bash', 'edit', 'write', 'grep', 'find', 'ls']
136
+
137
+ // pi builtins resolve relative paths (and, for trusted/owner bash, the spawn
138
+ // cwd) against the cwd baked in at factory time, so the definitions are built
139
+ // per session from the session's agentDir rather than the module-load
140
+ // process.cwd() — otherwise a session whose agentDir differs from the import-
141
+ // time cwd would read/write in the wrong tree. bash keeps the spawnHook that
142
+ // threads the internal env overlay to the (non-sandboxed) spawn.
143
+ function createPiBuiltinToolDefinition(name: PiBuiltinToolName, cwd: string): ToolDefinition<any, any, any> {
144
+ switch (name) {
145
+ case 'read':
146
+ return piCreateReadToolDefinition(cwd)
147
+ case 'bash':
148
+ return piCreateBashToolDefinition(cwd, { spawnHook: bashSpawnHookWithOverlay })
149
+ case 'edit':
150
+ return piCreateEditToolDefinition(cwd)
151
+ case 'write':
152
+ return piCreateWriteToolDefinition(cwd)
153
+ case 'grep':
154
+ return piCreateGrepToolDefinition(cwd)
155
+ case 'find':
156
+ return piCreateFindToolDefinition(cwd)
157
+ case 'ls':
158
+ return piCreateLsToolDefinition(cwd)
159
+ }
143
160
  }
144
161
 
145
162
  const TYPECLAW_TOOL_DEFINITION_MAP: Record<TypeclawToolName, ToolDefinition<any, any, any>> = {
@@ -147,33 +164,25 @@ const TYPECLAW_TOOL_DEFINITION_MAP: Record<TypeclawToolName, ToolDefinition<any,
147
164
  web_fetch: webFetchTool,
148
165
  }
149
166
 
150
- function isPiAgentToolName(name: string): name is PiAgentToolName {
151
- return name in PI_AGENT_TOOL_MAP
167
+ function isPiBuiltinToolName(name: string): name is PiBuiltinToolName {
168
+ return (PI_BUILTIN_TOOL_NAMES as readonly string[]).includes(name)
152
169
  }
153
170
 
154
- function isTypeclawToolName(name: string): name is TypeclawToolName {
155
- return name in TYPECLAW_TOOL_DEFINITION_MAP
171
+ export function isPiCodingBuiltinName(name: string): boolean {
172
+ return isPiBuiltinToolName(name)
156
173
  }
157
174
 
158
- export type ResolvedBuiltinTools = {
159
- agentTools: AgentTool<any, any>[]
160
- toolDefinitions: ToolDefinition<any, any, any>[]
175
+ function isTypeclawToolName(name: string): name is TypeclawToolName {
176
+ return name in TYPECLAW_TOOL_DEFINITION_MAP
161
177
  }
162
178
 
163
- export function resolveBuiltinToolRefs(refs: BuiltinToolRef[]): ResolvedBuiltinTools {
164
- const agentTools: AgentTool<any, any>[] = []
165
- const toolDefinitions: ToolDefinition<any, any, any>[] = []
166
- for (const ref of refs) {
179
+ export function resolveBuiltinToolRefs(refs: BuiltinToolRef[], cwd: string): ToolDefinition<any, any, any>[] {
180
+ return refs.map((ref) => {
167
181
  const name = ref.__builtinTool
168
- if (isPiAgentToolName(name)) {
169
- agentTools.push(PI_AGENT_TOOL_MAP[name])
170
- } else if (isTypeclawToolName(name)) {
171
- toolDefinitions.push(TYPECLAW_TOOL_DEFINITION_MAP[name])
172
- } else {
173
- throw new Error(`unknown built-in tool ref: ${name}`)
174
- }
175
- }
176
- return { agentTools, toolDefinitions }
182
+ if (isPiBuiltinToolName(name)) return createPiBuiltinToolDefinition(name, cwd)
183
+ if (isTypeclawToolName(name)) return TYPECLAW_TOOL_DEFINITION_MAP[name]
184
+ throw new Error(`unknown built-in tool ref: ${name}`)
185
+ })
177
186
  }
178
187
 
179
188
  export type WrapToolOptions = {
@@ -363,81 +372,20 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
363
372
  })
364
373
  }
365
374
 
366
- export function wrapSystemAgentTool<TParams extends TSchema, TDetails = unknown>(
367
- tool: AgentTool<TParams, TDetails>,
368
- opts: WrapSystemToolOptions,
369
- ): AgentTool<TParams, TDetails> {
370
- return {
371
- ...tool,
372
- parameters: withGuardAcknowledgements(tool.name, tool.parameters),
373
- async execute(toolCallId, params, signal, onUpdate) {
374
- const mutableArgs = params as Record<string, unknown>
375
- const liveOrigin = opts.getOrigin?.()
376
- const blockResult = await opts.hooks.runToolBefore({
377
- tool: tool.name,
378
- sessionId: opts.sessionId,
379
- callId: toolCallId,
380
- args: mutableArgs,
381
- ...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
382
- })
383
- if (blockResult !== undefined) {
384
- throw new Error(`blocked: ${blockResult.reason}`)
385
- }
386
- const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs)
387
- if (loopGate.blockNow) {
388
- fireLoopAbort(opts.getAbort, 'loop_guard:block')
389
- throw new Error(loopGate.message)
390
- }
391
- const guardResult = await runFinalWriteGuards({
392
- tool: tool.name,
393
- args: mutableArgs,
394
- agentDir: opts.agentDir,
395
- })
396
- if (guardResult !== undefined) {
397
- throw new Error(`blocked: ${guardResult.reason}`)
398
- }
399
- const readGuardResult = runFinalReadGuards({ tool: tool.name, args: mutableArgs })
400
- if (readGuardResult !== undefined) {
401
- throw new Error(`blocked: ${readGuardResult.reason}`)
402
- }
403
- stripGuardAcknowledgements(mutableArgs)
404
-
405
- const result = await tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate)
406
- const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
407
- if ('deferredBlock' in resolved) {
408
- fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
409
- throw new Error(resolved.deferredBlock)
410
- }
411
- const hookResult = resolved.result
412
- await opts.hooks.runToolAfter({
413
- tool: tool.name,
414
- sessionId: opts.sessionId,
415
- callId: toolCallId,
416
- result: hookResult,
417
- })
418
- return {
419
- content: hookResult.content as ContentPart[],
420
- details: hookResult.details as TDetails,
421
- }
422
- },
423
- }
424
- }
425
-
426
- // Wraps a pi-coding-agent AgentTool into a ToolDefinition so it can ride in
427
- // `customTools` and override pi's same-named builtin (see top-of-file contract
428
- // block). The hook + guard pipeline matches `wrapSystemAgentTool`; only the
429
- // input/output shape differs.
430
- export function wrapAgentToolAsCustomToolDefinition<TParams extends TSchema, TDetails = unknown>(
431
- tool: AgentTool<TParams, TDetails>,
375
+ // Wraps a pi builtin `ToolDefinition` (read/bash/edit/write/grep/find/ls) with
376
+ // TypeClaw's full pipeline — hooks, loop guard, write/read guards, per-subagent
377
+ // bash policy, bwrap sandbox, /tmp redirect, and the internal bash env overlay —
378
+ // then ships it through `customTools`. `noTools: "builtin"` at the call site
379
+ // disables pi's own unwrapped copies, so this wrapped definition is the ONLY
380
+ // registered implementation of each builtin name.
381
+ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = unknown, TState = any>(
382
+ tool: ToolDefinition<TParams, TDetails, TState>,
432
383
  opts: WrapSystemToolOptions,
433
- ): ToolDefinition<TParams, TDetails> {
384
+ ): ToolDefinition<TParams, TDetails, TState> {
434
385
  return piDefineTool({
435
- name: tool.name,
436
- label: tool.label,
437
- description: tool.description,
386
+ ...tool,
438
387
  parameters: withGuardAcknowledgements(tool.name, tool.parameters),
439
- prepareArguments: tool.prepareArguments,
440
- async execute(toolCallId, params, signal, onUpdate) {
388
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
441
389
  const mutableArgs = params as Record<string, unknown>
442
390
  const liveOrigin = opts.getOrigin?.()
443
391
  // Defense-in-depth: strip any pre-existing internal env-overlay key
@@ -499,7 +447,7 @@ export function wrapAgentToolAsCustomToolDefinition<TParams extends TSchema, TDe
499
447
  let rawResult: ToolResult
500
448
  try {
501
449
  rawResult = await bashEnvStore.run(bashEnvOverlay, () =>
502
- tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate),
450
+ tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate, ctx),
503
451
  )
504
452
  } catch (error) {
505
453
  // A throwing tool (pi's bash rejects on non-zero exit) must still run
@@ -549,12 +497,12 @@ async function runToolAfterSafely(
549
497
  }
550
498
  }
551
499
 
552
- export function defaultBuiltinPiAgentTools(): AgentTool<any, any>[] {
553
- return [piReadTool, piBashTool, piEditTool, piWriteTool, piGrepTool, piFindTool, piLsTool]
500
+ export function defaultBuiltinPiToolDefinitions(cwd: string): ToolDefinition<any, any, any>[] {
501
+ return PI_BUILTIN_TOOL_NAMES.map((name) => createPiBuiltinToolDefinition(name, cwd))
554
502
  }
555
503
 
556
504
  export function buildBuiltinPiToolOverrides(opts: WrapSystemToolOptions): ToolDefinition<any, any>[] {
557
- return defaultBuiltinPiAgentTools().map((tool) => wrapAgentToolAsCustomToolDefinition(tool, opts))
505
+ return defaultBuiltinPiToolDefinitions(opts.agentDir).map((tool) => wrapBuiltinToolDefinition(tool, opts))
558
506
  }
559
507
 
560
508
  // Rewrites mutableArgs.command in place so the bash builtin runs inside bwrap
@@ -579,6 +527,11 @@ async function applyBashSandbox(
579
527
  const sandboxEnvOverlay = buildRoleScopedConfigEnv(agentDir, dirs, envOverlay)
580
528
 
581
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 })
582
535
  // Per-session /tmp: bind this session's scratch dir over the default
583
536
  // --tmpfs /tmp so writes survive across the role's sandboxed bash calls AND
584
537
  // match what the write/edit wrapper redirected a /tmp path to. The bind is
@@ -666,8 +619,8 @@ async function applyBashSandbox(
666
619
  { type: 'bind', source: sessionTmp, dest: '/tmp' },
667
620
  ],
668
621
  ...(packageInstall !== undefined
669
- ? { writableRoot: { dir: packageInstall.root }, masks: { dirs, files }, protected: packageInstall.protected }
670
- : { masks: { dirs, files }, writable, protected: protectedZones }),
622
+ ? { writableRoot: { dir: packageInstall.root }, masks: maskTargets, protected: packageInstall.protected }
623
+ : { masks: maskTargets, writable, protected: protectedZones }),
671
624
  symlinks,
672
625
  network: 'inherit',
673
626
  cwd: agentDir,
@@ -26,6 +26,13 @@ export type DetectedProviderError = {
26
26
 
27
27
  const GENERIC_SAFE_NOTICE = 'The upstream LLM provider failed. Operators can check `typeclaw logs` for details.'
28
28
 
29
+ // The fetch observer (`llm-fetch-observer`) aborts a stalled provider stream
30
+ // with a message ending in this marker (TTFB / idle / overall deadline). Such a
31
+ // stall is a hard throw, not a `stopReason: 'error'` soft error, so it never
32
+ // reaches `detectProviderError`; the marker lets the hard-throw path recognize
33
+ // and surface it. The literal is the system's own token — English by design.
34
+ const OBSERVER_TIMEOUT = /\(typeclaw observer timeout\)/i
35
+
29
36
  // Each entry pairs a narrow matcher against the raw provider text with the
30
37
  // canonical, leak-free sentence shown in channels. Matchers are intentionally
31
38
  // specific: a miss falls through to GENERIC_SAFE_NOTICE rather than echoing raw
@@ -60,6 +67,10 @@ const SAFE_CLASSES: ReadonlyArray<{ match: RegExp; safe: string }> = [
60
67
  match: /\b(billing|quota|insufficient.*(credit|fund|balance)|payment|account is not active)\b/i,
61
68
  safe: 'The upstream LLM provider rejected the request for a billing/quota reason. Operators can check `typeclaw logs` for details.',
62
69
  },
70
+ {
71
+ match: OBSERVER_TIMEOUT,
72
+ safe: 'The upstream LLM provider stopped responding and the request timed out. Try again shortly.',
73
+ },
63
74
  ]
64
75
 
65
76
  function toSafeMessage(raw: string): string {
@@ -90,6 +101,17 @@ export function isThrottleOrOverload(raw: string): boolean {
90
101
  return THROTTLE_OR_OVERLOAD.test(raw)
91
102
  }
92
103
 
104
+ // Failover predicate for turn-drivers' `shouldFailover`: rotate to the next model
105
+ // ref on a transient capacity signal (throttle/overload) OR an observer stall
106
+ // timeout. A stall — the provider accepted the stream but stopped sending bytes —
107
+ // is as transient as an overload and another ref may well succeed, so it must
108
+ // fail OVER before the caller surfaces a failure notice. Account-wide faults
109
+ // (billing/quota/auth) still return false via `isThrottleOrOverload` — a
110
+ // different ref shares the same account problem.
111
+ export function isFailoverWorthy(raw: string): boolean {
112
+ return isThrottleOrOverload(raw) || OBSERVER_TIMEOUT.test(raw)
113
+ }
114
+
93
115
  export function detectProviderError(message: unknown): DetectedProviderError | null {
94
116
  if (typeof message !== 'object' || message === null) return null
95
117
  const m = message as { role?: unknown; stopReason?: unknown; errorMessage?: unknown }
@@ -102,6 +124,21 @@ export function detectProviderError(message: unknown): DetectedProviderError | n
102
124
  return { message: text, safeMessage: toSafeMessage(text) }
103
125
  }
104
126
 
127
+ // Classifies a HARD-thrown error (an exception out of `session.prompt()`, after
128
+ // model fallback is exhausted) into a user-facing notice — the throw counterpart
129
+ // to `detectProviderError`'s soft-error path. Returns `null` for errors that are
130
+ // NOT an operator-actionable provider failure (internal bugs, network blips),
131
+ // so the caller stays silent-with-log rather than spamming channels. The three
132
+ // recognized classes are: failover-worthy throttle/overload, account-wide faults
133
+ // (billing/quota/auth) that must surface, and observer stall timeouts.
134
+ export function detectHardProviderError(err: unknown): DetectedProviderError | null {
135
+ const message = err instanceof Error ? err.message : String(err)
136
+ const isProviderFailure =
137
+ isThrottleOrOverload(message) || NON_FAILOVER_FAULT.test(message) || OBSERVER_TIMEOUT.test(message)
138
+ if (!isProviderFailure) return null
139
+ return { message, safeMessage: toSafeMessage(message) }
140
+ }
141
+
105
142
  export type ProviderErrorListener = (error: DetectedProviderError) => void
106
143
  export type Unsubscribe = () => void
107
144
 
@@ -1,5 +1,5 @@
1
1
  import { defineTool } from '@mariozechner/pi-coding-agent'
2
- import { Type } from '@sinclair/typebox'
2
+ import { Type } from 'typebox'
3
3
 
4
4
  import type { ReloadRegistry, ReloadResult } from '@/reload'
5
5
 
@@ -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`.',
@@ -10,7 +10,7 @@ import { applyTurnThinkingLevel } from './attention-escalation'
10
10
  import { type AgentSession, createSession, type PluginSessionWiring } from './index'
11
11
  import { resolveFallbackChain } from './model-fallback'
12
12
  import { applyModelRuntimeOverrides } from './model-overrides'
13
- import { isThrottleOrOverload, subscribeProviderErrors } from './provider-error'
13
+ import { isFailoverWorthy, subscribeProviderErrors } from './provider-error'
14
14
  import type { SubagentBashPolicy } from './reviewer-bash-policy'
15
15
  import type { SessionOrigin } from './session-origin'
16
16
  import {
@@ -349,7 +349,7 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
349
349
  text: turnText,
350
350
  skipProviderErrorSubscription: true,
351
351
  detectSoftErrorFromLeaf: true,
352
- shouldFailover: (err) => isThrottleOrOverload(err.message),
352
+ shouldFailover: (err) => isFailoverWorthy(err.message),
353
353
  setModelForRef: async (ref) => {
354
354
  await session.setModel(applyModelRuntimeOverrides(resolveModel(ref), ref))
355
355
  activeModelRef = ref
@@ -11,10 +11,15 @@ const PACKAGE_JSON_INSTALL_RULE =
11
11
  // by the no-registry path (back-compat callers, the debug dumper); production
12
12
  // full-mode sessions pass the real registry-rendered roster via
13
13
  // `composeSystemPrompt`'s `subagentRoster` field.
14
- export function buildDefaultSystemPrompt(subagentRoster: string): string {
15
- return `You are a general-purpose AI agent running inside TypeClaw.
14
+ export function buildDefaultSystemPrompt(subagentRoster: string, branding = true): string {
15
+ const opening = branding
16
+ ? `You are a general-purpose AI agent running inside TypeClaw.
16
17
 
17
- TypeClaw is domain-agnostic: \`IDENTITY.md\` defines your role, \`SOUL.md\` your voice, and \`AGENTS.md\` your operating manual. This prompt describes only the runtime.
18
+ TypeClaw is domain-agnostic: \`IDENTITY.md\` defines your role, \`SOUL.md\` your voice, and \`AGENTS.md\` your operating manual. This prompt describes only the runtime.`
19
+ : `You are a general-purpose AI agent.
20
+
21
+ Your runtime is domain-agnostic: \`IDENTITY.md\` defines your role, \`SOUL.md\` your voice, and \`AGENTS.md\` your operating manual. This prompt describes only the runtime.`
22
+ return `${opening}
18
23
 
19
24
  ## Your agent folder
20
25
 
@@ -93,7 +98,7 @@ Use tmux only for work that belongs in your session. Delegate self-contained lon
93
98
 
94
99
  ## Version control
95
100
 
96
- Your agent folder is a git repository, but **it is your own private backup repo — not a software project you develop.** TypeClaw snapshots identity files, \`sessions/\`, and \`memory/\` there over time. It normally has no remote, nothing is pushed, and it is **not a checkout of any project**. Commits here save your state, not a codebase contribution.
101
+ Your agent folder is a git repository, but **it is your own private backup repo — not a software project you develop.** ${branding ? 'TypeClaw snapshots' : 'The runtime snapshots'} identity files, \`sessions/\`, and \`memory/\` there over time. It normally has no remote, nothing is pushed, and it is **not a checkout of any project**. Commits here save your state, not a codebase contribution.
97
102
 
98
103
  For project work (bug, feature, PR), clone the project repo into \`/tmp/<repo>\`, work there, and open the PR from that clone with \`gh\`. Never \`git init\`, add a remote, or push your agent folder as the project. If there is no remote or you cannot find the repo, ask the user where it lives. Your agent folder is where you live; the clone is where you work.
99
104
 
@@ -116,13 +121,15 @@ Commits to your agent folder (your own state):
116
121
 
117
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}.
118
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
+
119
126
  Pick one of three modes:
120
127
 
121
- **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\`.)
122
129
 
123
- **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.
124
131
 
125
- **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.
126
133
 
127
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.
128
135
 
@@ -262,7 +269,9 @@ export function renderTurnRoleAnchor(role: string): string | undefined {
262
269
  // The full DEFAULT_SYSTEM_PROMPT remains the right choice for TUI + channel
263
270
  // sessions because there IS a human reading the output, the agent IS expected
264
271
  // to maintain its agent folder over time, and conversational register matters.
265
- export const SLIM_SYSTEM_PROMPT = `You are an AI agent running inside TypeClaw.
272
+ export function buildSlimSystemPrompt(branding = true): string {
273
+ const opening = branding ? 'You are an AI agent running inside TypeClaw.' : 'You are an AI agent.'
274
+ return `${opening}
266
275
 
267
276
  Never echo secrets from \`secrets.json\` or \`.env\`, or any credential you see in the environment. Never include them in tool calls, logs, or commit messages.
268
277
 
@@ -277,3 +286,10 @@ Your free-write zone is \`workspace/\`. Do not create files at the root of the a
277
286
  The agent folder is a private backup repo with no remote, not a project checkout. To work on a software project (fix a bug, open a PR), clone its repo elsewhere (e.g. \`/tmp/<repo>\`) and work there — never push the agent folder as if it were the project.
278
287
 
279
288
  See the session-origin block below for what kind of session this is and what's expected of you.`
289
+ }
290
+
291
+ // Back-compat constant: the slim prompt with branding on. Retained because
292
+ // tests assert `prompt.startsWith(SLIM_SYSTEM_PROMPT)` on the default path;
293
+ // production slim composition substitutes the branding flag via
294
+ // `buildSlimSystemPrompt`.
295
+ export const SLIM_SYSTEM_PROMPT = buildSlimSystemPrompt()
@@ -1,6 +1,6 @@
1
1
  import type { AgentTool } from '@mariozechner/pi-agent-core'
2
2
  import type { ToolDefinition } from '@mariozechner/pi-coding-agent'
3
- import type { TSchema } from '@sinclair/typebox'
3
+ import type { TSchema } from 'typebox'
4
4
 
5
5
  // Subagents that read large files (memory-logger and dreaming each read parent
6
6
  // session transcripts that can run hundreds of KB) are vulnerable to a class
@@ -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,