typeclaw 0.39.3 → 0.39.4

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/package.json +1 -1
  2. package/src/agent/index.ts +10 -14
  3. package/src/agent/model-fallback.ts +13 -4
  4. package/src/agent/provider-error.ts +36 -1
  5. package/src/agent/subagents.ts +29 -2
  6. package/src/agent/throttle-circuit.ts +50 -0
  7. package/src/agent/turn-runner.ts +162 -0
  8. package/src/bundled-plugins/memory/README.md +12 -12
  9. package/src/bundled-plugins/memory/append-tool.ts +58 -6
  10. package/src/bundled-plugins/memory/dreaming.ts +1 -1
  11. package/src/bundled-plugins/memory/fragment-parser.ts +10 -3
  12. package/src/bundled-plugins/memory/load-memory.ts +28 -2
  13. package/src/bundled-plugins/memory/memory-logger.ts +14 -2
  14. package/src/bundled-plugins/memory/search-tool.ts +50 -7
  15. package/src/bundled-plugins/memory/stream-events.ts +23 -0
  16. package/src/bundled-plugins/memory/vector/hybrid.ts +9 -2
  17. package/src/bundled-plugins/security/index.ts +24 -1
  18. package/src/bundled-plugins/security/policies/cron-promotion.ts +94 -62
  19. package/src/bundled-plugins/security/policies/plugin-addition.ts +2 -4
  20. package/src/bundled-plugins/security/policies/role-promotion.ts +2 -4
  21. package/src/channels/adapters/webex-bot.ts +26 -25
  22. package/src/channels/adapters/webex-prefetch-limiter.ts +120 -0
  23. package/src/channels/adapters/webex.ts +27 -30
  24. package/src/channels/manager.ts +64 -57
  25. package/src/channels/router.ts +134 -4
  26. package/src/channels/types.ts +8 -1
  27. package/src/cli/builtins.ts +6 -32
  28. package/src/cli/command-meta.ts +93 -0
  29. package/src/cli/help.ts +24 -0
  30. package/src/cli/index.ts +34 -10
  31. package/src/config/config.ts +27 -1
  32. package/src/container/start.ts +22 -2
  33. package/src/hostd/daemon.ts +55 -26
  34. package/src/hostd/spawn.ts +53 -19
  35. package/src/permissions/permissions.ts +12 -0
  36. package/src/run/codex-fetch-observer.ts +11 -6
  37. package/src/secrets/oauth-xai.ts +2 -2
  38. package/src/server/index.ts +27 -2
  39. package/src/skills/typeclaw-channels/SKILL.md +1 -1
  40. package/src/skills/typeclaw-config/SKILL.md +1 -0
  41. package/src/skills/typeclaw-cron/SKILL.md +9 -4
  42. package/src/skills/typeclaw-permissions/SKILL.md +18 -6
@@ -261,48 +261,58 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
261
261
  })
262
262
  }
263
263
  if (name === 'line') {
264
+ const credentialsStore = createContainerLineCredentialStore(options.agentDir, env)
265
+ if (credentialsStore === null) return null
264
266
  return createLine({
265
267
  router,
266
268
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
267
269
  logger,
268
270
  selfAliasesRef: () => router.getSelfAliases(),
269
- credentialsStore: createContainerLineCredentialStore(options.agentDir, env),
271
+ credentialsStore,
270
272
  })
271
273
  }
272
274
  if (name === 'kakaotalk') {
275
+ const credentialsStore = createContainerKakaoCredentialStore(options.agentDir, env)
276
+ if (credentialsStore === null) return null
273
277
  return createKakaotalk({
274
278
  router,
275
279
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
276
280
  logger,
277
281
  selfAliasesRef: () => router.getSelfAliases(),
278
- credentialsStore: createContainerKakaoCredentialStore(options.agentDir, env),
282
+ credentialsStore,
279
283
  })
280
284
  }
281
285
  if (name === 'slack') {
286
+ const credentialsStore = createContainerSlackCredentialStore(options.agentDir, env)
287
+ if (credentialsStore === null) return null
282
288
  return createSlackUser({
283
289
  router,
284
290
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
285
291
  logger,
286
292
  selfAliasesRef: () => router.getSelfAliases(),
287
- credentialsStore: createContainerSlackCredentialStore(options.agentDir, env),
293
+ credentialsStore,
288
294
  })
289
295
  }
290
296
  if (name === 'discord') {
297
+ const credentialsStore = createContainerDiscordCredentialStore(options.agentDir, env)
298
+ if (credentialsStore === null) return null
291
299
  return createDiscordUser({
292
300
  router,
293
301
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
294
302
  logger,
295
303
  selfAliasesRef: () => router.getSelfAliases(),
296
- credentialsStore: createContainerDiscordCredentialStore(options.agentDir, env),
304
+ credentialsStore,
297
305
  })
298
306
  }
299
307
  if (name === 'webex') {
308
+ const credentialsStore = createContainerWebexCredentialStore(options.agentDir, env)
309
+ if (credentialsStore === null) return null
300
310
  return createWebex({
301
311
  router,
302
312
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
303
313
  logger,
304
314
  selfAliasesRef: () => router.getSelfAliases(),
305
- credentialsStore: createContainerWebexCredentialStore(options.agentDir, env),
315
+ credentialsStore,
306
316
  })
307
317
  }
308
318
  if (name === 'github') {
@@ -538,22 +548,33 @@ const TOKEN_ENV: Record<
538
548
  'webex-bot': ['WEBEX_BOT_TOKEN'],
539
549
  }
540
550
 
541
- function createContainerDiscordCredentialStore(
542
- agentDir: string,
543
- env: NodeJS.ProcessEnv,
544
- ): SecretsDiscordCredentialStore {
551
+ // Personal-account adapters (line/kakaotalk/slack/discord/webex) need the hostd
552
+ // triple the host CLI injects at `docker run` time, gated on a successful daemon
553
+ // registration (src/container/start.ts). If the daemon wasn't reachable at
554
+ // launch (e.g. a lost first-boot spawn race) the triple is absent; null lets
555
+ // buildAdapter skip the adapter instead of throwing and crashing the whole
556
+ // channel manager. startAdapter's signature pre-check only reads secrets.json,
557
+ // so this is the only place the missing triple is caught.
558
+ type HostdContainerCredentials = { hostdUrl: string; restartToken: string; containerName: string }
559
+
560
+ function resolveHostdContainerCredentials(env: NodeJS.ProcessEnv): HostdContainerCredentials | null {
545
561
  const hostdUrl = env.TYPECLAW_HOSTD_URL
546
562
  const restartToken = env.TYPECLAW_HOSTD_TOKEN
547
563
  const containerName = env.TYPECLAW_CONTAINER_NAME
548
- if (!hostdUrl || !restartToken || !containerName) {
549
- throw new Error('Discord credentials require TYPECLAW_HOSTD_URL, TYPECLAW_HOSTD_TOKEN, and TYPECLAW_CONTAINER_NAME')
550
- }
564
+ if (!hostdUrl || !restartToken || !containerName) return null
565
+ return { hostdUrl, restartToken, containerName }
566
+ }
567
+
568
+ function createContainerDiscordCredentialStore(
569
+ agentDir: string,
570
+ env: NodeJS.ProcessEnv,
571
+ ): SecretsDiscordCredentialStore | null {
572
+ const creds = resolveHostdContainerCredentials(env)
573
+ if (creds === null) return null
551
574
  return new SecretsDiscordCredentialStore({
552
575
  mode: 'container',
553
576
  secretsPath: join(agentDir, 'secrets.json'),
554
- hostdUrl,
555
- restartToken,
556
- containerName,
577
+ ...creds,
557
578
  })
558
579
  }
559
580
 
@@ -571,19 +592,16 @@ function buildDiscordSignature(agentDir: string): { signature: string; missing:
571
592
  }
572
593
  }
573
594
 
574
- function createContainerSlackCredentialStore(agentDir: string, env: NodeJS.ProcessEnv): SecretsSlackCredentialStore {
575
- const hostdUrl = env.TYPECLAW_HOSTD_URL
576
- const restartToken = env.TYPECLAW_HOSTD_TOKEN
577
- const containerName = env.TYPECLAW_CONTAINER_NAME
578
- if (!hostdUrl || !restartToken || !containerName) {
579
- throw new Error('Slack credentials require TYPECLAW_HOSTD_URL, TYPECLAW_HOSTD_TOKEN, and TYPECLAW_CONTAINER_NAME')
580
- }
595
+ function createContainerSlackCredentialStore(
596
+ agentDir: string,
597
+ env: NodeJS.ProcessEnv,
598
+ ): SecretsSlackCredentialStore | null {
599
+ const creds = resolveHostdContainerCredentials(env)
600
+ if (creds === null) return null
581
601
  return new SecretsSlackCredentialStore({
582
602
  mode: 'container',
583
603
  secretsPath: join(agentDir, 'secrets.json'),
584
- hostdUrl,
585
- restartToken,
586
- containerName,
604
+ ...creds,
587
605
  })
588
606
  }
589
607
 
@@ -601,19 +619,16 @@ function buildSlackSignature(agentDir: string): { signature: string; missing: st
601
619
  }
602
620
  }
603
621
 
604
- function createContainerWebexCredentialStore(agentDir: string, env: NodeJS.ProcessEnv): SecretsWebexCredentialStore {
605
- const hostdUrl = env.TYPECLAW_HOSTD_URL
606
- const restartToken = env.TYPECLAW_HOSTD_TOKEN
607
- const containerName = env.TYPECLAW_CONTAINER_NAME
608
- if (!hostdUrl || !restartToken || !containerName) {
609
- throw new Error('Webex credentials require TYPECLAW_HOSTD_URL, TYPECLAW_HOSTD_TOKEN, and TYPECLAW_CONTAINER_NAME')
610
- }
622
+ function createContainerWebexCredentialStore(
623
+ agentDir: string,
624
+ env: NodeJS.ProcessEnv,
625
+ ): SecretsWebexCredentialStore | null {
626
+ const creds = resolveHostdContainerCredentials(env)
627
+ if (creds === null) return null
611
628
  return new SecretsWebexCredentialStore({
612
629
  mode: 'container',
613
630
  secretsPath: join(agentDir, 'secrets.json'),
614
- hostdUrl,
615
- restartToken,
616
- containerName,
631
+ ...creds,
617
632
  })
618
633
  }
619
634
 
@@ -631,21 +646,16 @@ function buildWebexSignature(agentDir: string): { signature: string; missing: st
631
646
  }
632
647
  }
633
648
 
634
- function createContainerKakaoCredentialStore(agentDir: string, env: NodeJS.ProcessEnv): SecretsKakaoCredentialStore {
635
- const hostdUrl = env.TYPECLAW_HOSTD_URL
636
- const restartToken = env.TYPECLAW_HOSTD_TOKEN
637
- const containerName = env.TYPECLAW_CONTAINER_NAME
638
- if (!hostdUrl || !restartToken || !containerName) {
639
- throw new Error(
640
- 'KakaoTalk credentials require TYPECLAW_HOSTD_URL, TYPECLAW_HOSTD_TOKEN, and TYPECLAW_CONTAINER_NAME',
641
- )
642
- }
649
+ function createContainerKakaoCredentialStore(
650
+ agentDir: string,
651
+ env: NodeJS.ProcessEnv,
652
+ ): SecretsKakaoCredentialStore | null {
653
+ const creds = resolveHostdContainerCredentials(env)
654
+ if (creds === null) return null
643
655
  return new SecretsKakaoCredentialStore({
644
656
  mode: 'container',
645
657
  secretsPath: join(agentDir, 'secrets.json'),
646
- hostdUrl,
647
- restartToken,
648
- containerName,
658
+ ...creds,
649
659
  })
650
660
  }
651
661
 
@@ -663,19 +673,16 @@ function buildKakaotalkSignature(agentDir: string): { signature: string; missing
663
673
  }
664
674
  }
665
675
 
666
- function createContainerLineCredentialStore(agentDir: string, env: NodeJS.ProcessEnv): SecretsLineCredentialStore {
667
- const hostdUrl = env.TYPECLAW_HOSTD_URL
668
- const restartToken = env.TYPECLAW_HOSTD_TOKEN
669
- const containerName = env.TYPECLAW_CONTAINER_NAME
670
- if (!hostdUrl || !restartToken || !containerName) {
671
- throw new Error('LINE credentials require TYPECLAW_HOSTD_URL, TYPECLAW_HOSTD_TOKEN, and TYPECLAW_CONTAINER_NAME')
672
- }
676
+ function createContainerLineCredentialStore(
677
+ agentDir: string,
678
+ env: NodeJS.ProcessEnv,
679
+ ): SecretsLineCredentialStore | null {
680
+ const creds = resolveHostdContainerCredentials(env)
681
+ if (creds === null) return null
673
682
  return new SecretsLineCredentialStore({
674
683
  mode: 'container',
675
684
  secretsPath: join(agentDir, 'secrets.json'),
676
- hostdUrl,
677
- restartToken,
678
- containerName,
685
+ ...creds,
679
686
  })
680
687
  }
681
688
 
@@ -2,12 +2,14 @@ import { statSync } from 'node:fs'
2
2
  import { basename } from 'node:path'
3
3
 
4
4
  import type { AssistantMessage } from '@mariozechner/pi-ai'
5
- import { SessionManager } from '@mariozechner/pi-coding-agent'
5
+ import { type SessionEntry, SessionManager } from '@mariozechner/pi-coding-agent'
6
6
 
7
7
  import { createSession, renderTurnRoleAnchor, renderTurnTimeAnchor, type AgentSession } from '@/agent'
8
8
  import { applyTurnThinkingLevel, getQuestionSignal, type QuestionSignal } from '@/agent/attention-escalation'
9
+ import { resolveFallbackChain } from '@/agent/model-fallback'
10
+ import { applyModelRuntimeOverrides } from '@/agent/model-overrides'
9
11
  import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
10
- import { subscribeProviderErrors } from '@/agent/provider-error'
12
+ import { isThrottleOrOverload, subscribeProviderErrors } from '@/agent/provider-error'
11
13
  import type { RestartHandoff } from '@/agent/restart-handoff'
12
14
  import type { ChannelParticipant, SessionOrigin } from '@/agent/session-origin'
13
15
  import { renderSubagentCompletionReminder } from '@/agent/subagent-completion-reminder'
@@ -19,7 +21,9 @@ import {
19
21
  runIdleContinuation,
20
22
  } from '@/agent/todo/continuation-wiring'
21
23
  import { SUBAGENT_OUTPUT_TOOL_NAME } from '@/agent/tools/subagent-output'
24
+ import { promptPersistentTurnWithFallback } from '@/agent/turn-runner'
22
25
  import { type Command, type CommandPermission, type CommandResult, createCommandRegistry } from '@/commands'
26
+ import { getConfig, resolveModel } from '@/config'
23
27
  import { CORE_PERMISSIONS, type PermissionService } from '@/permissions'
24
28
  import type { HookBus } from '@/plugin'
25
29
  import { extractClaimCode } from '@/role-claim'
@@ -315,6 +319,32 @@ export const COLD_START_REPLY_NUDGE = [
315
319
  '',
316
320
  '---',
317
321
  ].join('\n')
322
+ // Reminder-only nudge for the empty-stop-after-tool-work retry. Distinct from
323
+ // both EMPTY_TURN_RETRY_NUDGE (which misdiagnoses a clean `stop` as output-budget
324
+ // exhaustion and, per its own docstring, makes the model RE-RUN its tools and
325
+ // strand again) and STRANDED_TOOLUSE_CONTINUATION_NUDGE (which assumes a `continue:
326
+ // true` status reply already landed). Here NO send landed, the model gathered real
327
+ // tool results, then the final completion came back as a bare empty `stop` — the
328
+ // Fireworks/gpt empty-completion degeneration. The recovery is to READ the results
329
+ // already in this branch, summarize, and reply — NOT to re-investigate. The
330
+ // trailing NO_REPLY escape is what makes the rare research-then-decline false
331
+ // positive self-correct on the first retry instead of forcing the fallback.
332
+ export const EMPTY_STOP_AFTER_TOOL_WORK_NUDGE = [
333
+ '---',
334
+ '**[SYSTEM MESSAGE — not from a human]**',
335
+ '',
336
+ 'Your previous turn gathered information with your tools, then ended without',
337
+ 'sending any reply — the final completion came back empty. This is an automated',
338
+ 'signal from the channel router, not a message from anyone in the chat. **Do not',
339
+ 'acknowledge or reply to this notice itself.**',
340
+ '',
341
+ 'Do NOT re-run your tools. The results you already gathered are still in this',
342
+ 'conversation above — read them, summarize what you found, and send your reply',
343
+ 'now via your channel reply tool. Only call more tools if a specific fact is',
344
+ 'genuinely still missing. If you truly have nothing to say, reply with `NO_REPLY`.',
345
+ '',
346
+ '---',
347
+ ].join('\n')
318
348
  // At most one continuation nudge per logical turn. Stricter than the empty-turn
319
349
  // retry budget (2) because the turn ALREADY delivered a user-facing reply — this
320
350
  // is a one-shot correction offer, not recovery from no output.
@@ -619,6 +649,7 @@ type LiveSession = {
619
649
  key: ChannelKey
620
650
  keyId: string
621
651
  session: ChannelAgentSession
652
+ activeModelRef: ReturnType<typeof resolveFallbackChain>[number]
622
653
  // The session's creation-time thinking level, captured once. A later escalated
623
654
  // turn moves `session.thinkingLevel` to `high`, so the live getter can't be the
624
655
  // reset target — this preserves the real default across the session's lifetime.
@@ -791,6 +822,14 @@ type LiveSession = {
791
822
  // increments it before injecting EMPTY_TURN_RETRY_NUDGE and reads it to decide
792
823
  // retry-vs-fallback. See the candidate===null branch.
793
824
  emptyTurnRetries: number
825
+ // Latches once a bare-empty `stop` has been classified as empty-stop-after-tool-work
826
+ // this logical turn. The recovery nudge tells the model NOT to re-run its tools, so
827
+ // a compliant retry is expected to land another bare-empty `stop` with NO new tool
828
+ // call — `attemptMadeToolCall` would then be false and the turn would silently bail
829
+ // with budget unspent. Once armed, the cause persists for the turn so later bare-empty
830
+ // stops keep spending the shared retry budget toward the visible fallback. Reset
831
+ // alongside `emptyTurnRetries` on a real user batch only (anti-reloop discipline).
832
+ emptyStopAfterToolWorkArmed: boolean
794
833
  // Count of continuation nudges spent on the CURRENT logical turn, bounded by
795
834
  // MAX_WILLINGNESS_NUDGES. Reset alongside `emptyTurnRetries` only when a real
796
835
  // user batch starts (batch.length > 0), NOT on the reminder-only iteration the
@@ -1294,6 +1333,7 @@ const GRANT_ALL_PERMISSIONS: PermissionService = {
1294
1333
  has: () => true,
1295
1334
  resolveRole: () => 'owner',
1296
1335
  compareRoleSeverity: () => 1,
1336
+ permissionsForRole: () => [CORE_PERMISSIONS.channelRespond],
1297
1337
  describe: () => ({ role: 'owner', permissions: [CORE_PERMISSIONS.channelRespond] }),
1298
1338
  replaceRoles: () => {},
1299
1339
  }
@@ -1795,6 +1835,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1795
1835
  key,
1796
1836
  keyId,
1797
1837
  session: created.session,
1838
+ activeModelRef: resolveFallbackChain(getConfig().models, undefined)[0]!,
1798
1839
  turnThinkingDefault: created.session.thinkingLevel,
1799
1840
  lastQuestionSignal: null,
1800
1841
  pendingUserTurnSignal: null,
@@ -1849,6 +1890,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1849
1890
  inFlightToolSends: new Map(),
1850
1891
  policyDeniedToolSendsThisTurn: new Map(),
1851
1892
  emptyTurnRetries: 0,
1893
+ emptyStopAfterToolWorkArmed: false,
1852
1894
  willingnessNudges: 0,
1853
1895
  lastTerminalReplyAbort: null,
1854
1896
  abortReasonThisTurn: null,
@@ -1999,10 +2041,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1999
2041
  chat: live.key.chat,
2000
2042
  thread: live.key.thread,
2001
2043
  limit: requested,
2044
+ prefetch: true,
2002
2045
  })
2003
2046
 
2004
2047
  if (!result.ok) {
2005
- logger.warn(`[channels] ${live.keyId}: prefetch skipped (history fetch failed: ${result.error})`)
2048
+ // An adapter that declined a best-effort read to avoid hammering a
2049
+ // rate-limited resource is expected optional-context loss, not a failure —
2050
+ // log it at info so it does not masquerade as an auth/network warning.
2051
+ if (result.skipReason === 'rate-limited') {
2052
+ logger.info(`[channels] ${live.keyId}: prefetch skipped (rate limited: ${result.error})`)
2053
+ } else {
2054
+ logger.warn(`[channels] ${live.keyId}: prefetch skipped (history fetch failed: ${result.error})`)
2055
+ }
2006
2056
  return
2007
2057
  }
2008
2058
 
@@ -2504,6 +2554,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2504
2554
  // iterations the retry itself queues do not refill the budget and loop
2505
2555
  // forever (and the raised cap stays scoped to the turn that set it).
2506
2556
  live.emptyTurnRetries = 0
2557
+ live.emptyStopAfterToolWorkArmed = false
2507
2558
  live.willingnessNudges = 0
2508
2559
  live.abortReasonThisTurn = null
2509
2560
  live.nextPromptMaxTokens = undefined
@@ -2575,7 +2626,26 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2575
2626
  applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault, live.lastQuestionSignal)
2576
2627
  live.promptInFlight = true
2577
2628
  try {
2578
- await live.session.prompt(promptText)
2629
+ const result = await promptPersistentTurnWithFallback({
2630
+ refs: resolveFallbackChain(getConfig().models, undefined),
2631
+ currentModelRef: live.activeModelRef,
2632
+ session: live.session,
2633
+ text: promptText,
2634
+ shouldFailover: (err) => isThrottleOrOverload(err.message),
2635
+ setModelForRef: async (ref) => {
2636
+ await live.session.setModel(applyModelRuntimeOverrides(resolveModel(ref), ref))
2637
+ live.activeModelRef = ref
2638
+ },
2639
+ beforeAttempt: () => {
2640
+ applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault, live.lastQuestionSignal)
2641
+ },
2642
+ onAttemptFailed: (attempt) => {
2643
+ logger.warn(
2644
+ `[channels] ${live.keyId}: ${attempt.outcome} failure on ${attempt.ref}: ${attempt.errorMessage ?? 'unknown'}; falling back`,
2645
+ )
2646
+ },
2647
+ })
2648
+ if (result.success) live.activeModelRef = result.refUsed
2579
2649
  await validateChannelTurn(live, successfulSendsBeforePrompt)
2580
2650
  live.consecutiveAborts = 0
2581
2651
  // Resolve the pending logical-turn signal on a binary rule: ONLY a
@@ -3985,6 +4055,42 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3985
4055
  await postEmptyTurnFallback('cold_start_solo_bare_empty_retries_exhausted')
3986
4056
  return
3987
4057
  }
4058
+ // Deliberately AFTER the cold-start guard (that path has its own nudge). A
4059
+ // bare-empty stop that followed real tool work — but landed no send — is the
4060
+ // no-send sibling of the willingness-ack / stranded-toolUse degenerations
4061
+ // above: the model gathered results then emitted an empty completion instead
4062
+ // of the answer. Retry telling it to summarize what it already has; on
4063
+ // exhaustion post the visible fallback rather than stranding the asker on
4064
+ // silence. The cause LATCHES for the logical turn (`emptyStopAfterToolWorkArmed`):
4065
+ // the nudge tells the model not to re-run tools, so a compliant retry lands
4066
+ // another bare-empty stop with NO new tool call — requiring fresh tool work on
4067
+ // every attempt would silently drop exactly that shape with budget unspent.
4068
+ // Once armed, subsequent bare-empty stops keep spending the shared retry budget
4069
+ // toward the fallback. An explicit non-empty NO_REPLY still escapes to silence
4070
+ // (its `trim()` is non-empty, so the first condition fails and it falls through
4071
+ // to no_reply below); a bare-empty stop with no tool work AND never-armed stays
4072
+ // silent too.
4073
+ if (
4074
+ assistantText.trim() === '' &&
4075
+ source === 'leaf' &&
4076
+ (live.emptyStopAfterToolWorkArmed || attemptMadeToolCall(live.session)) &&
4077
+ live.currentTurnAuthorId !== null &&
4078
+ live.successfulChannelSends === successfulSendsBeforePrompt &&
4079
+ live.promptQueue.length === 0
4080
+ ) {
4081
+ live.emptyStopAfterToolWorkArmed = true
4082
+ if (live.emptyTurnRetries < MAX_EMPTY_TURN_RETRIES) {
4083
+ live.emptyTurnRetries++
4084
+ logger.warn(
4085
+ `[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
4086
+ `cause=empty_stop_after_tool_work`,
4087
+ )
4088
+ live.pendingSystemReminders.push(EMPTY_STOP_AFTER_TOOL_WORK_NUDGE)
4089
+ return
4090
+ }
4091
+ await postEmptyTurnFallback('empty_stop_after_tool_work_retries_exhausted')
4092
+ return
4093
+ }
3988
4094
  const leakedReasoning = !isNoReplySignal(assistantText)
3989
4095
  logger.info(`[channels] ${live.keyId} no_reply${leakedReasoning ? ' (with_leaked_reasoning)' : ''}`)
3990
4096
  return
@@ -5571,6 +5677,30 @@ function hasToolCall(message: AssistantMessage): boolean {
5571
5677
  return message.content.some((block) => block.type === 'toolCall')
5572
5678
  }
5573
5679
 
5680
+ // True when any assistant message in the CURRENT prompt-attempt carries a
5681
+ // toolCall block. "This attempt" is bounded by walking the parentId chain back
5682
+ // to the first user message — which INCLUDES an injected retry nudge, since
5683
+ // that lands as a user-side entry — so each retry is scored on its own tool
5684
+ // work, not the original turn's. validateChannelTurn uses this to tell a
5685
+ // bare-empty `stop` that followed real tool work (Fireworks/gpt empty-completion
5686
+ // degeneration → retry) apart from a bare-empty `stop` that produced nothing
5687
+ // from nothing (deliberate silence → honor it). The `source === 'leaf'` +
5688
+ // `stopReason: 'stop'` invariant at the call site guarantees any tool called
5689
+ // this attempt already returned a toolResult; otherwise the leaf would be
5690
+ // `toolUse`, not `stop`. Depth-bounded like the other branch walks so a
5691
+ // malformed session can't loop.
5692
+ function attemptMadeToolCall(session: AgentSession): boolean {
5693
+ let cursor: SessionEntry | undefined = session.sessionManager.getLeafEntry()
5694
+ for (let depth = 0; depth < 32 && cursor; depth++) {
5695
+ if (cursor.type === 'message') {
5696
+ if (cursor.message.role === 'user') return false
5697
+ if (cursor.message.role === 'assistant' && hasToolCall(cursor.message)) return true
5698
+ }
5699
+ cursor = cursor.parentId ? session.sessionManager.getEntry(cursor.parentId) : undefined
5700
+ }
5701
+ return false
5702
+ }
5703
+
5574
5704
  // Lenient on purpose: distilled / smaller models routinely drift off the
5575
5705
  // documented `NO_REPLY` form. We additionally accept `(NO_REPLY)` (Claude-style
5576
5706
  // hedging) and empty visible text (e.g. Kimi-distilled models that emit only a
@@ -339,11 +339,18 @@ export type FetchHistoryArgs = {
339
339
  thread: string | null
340
340
  limit: number
341
341
  cursor?: string
342
+ // Set by best-effort callers (cold-start prefetch, membership fallback) to opt
343
+ // into adapter-side rate-limit backpressure. Explicit reads (channel_history)
344
+ // leave it unset so they always attempt the fetch under the router's timeout.
345
+ prefetch?: boolean
342
346
  }
343
347
 
344
348
  export type FetchHistoryResult =
345
349
  | { ok: true; messages: ChannelHistoryMessage[]; nextCursor?: string }
346
- | { ok: false; error: string }
350
+ // `skipReason: 'rate-limited'` marks an expected, optional-context skip (the
351
+ // adapter declined a best-effort read to avoid hammering a rate-limited
352
+ // resource) so callers can log it at info instead of warn.
353
+ | { ok: false; error: string; skipReason?: 'rate-limited' }
347
354
 
348
355
  // Registered per-adapter on the ChannelRouter alongside outbound/typing
349
356
  // callbacks. Adapters that cannot fetch history (e.g. webhook-only future
@@ -1,33 +1,7 @@
1
- // Single source of truth for the top-level `typeclaw` subcommands that the
2
- // CLI dispatches via citty. Plugin commands MUST NOT shadow these names.
1
+ // Stable, dependency-free re-export of the top-level `typeclaw` subcommand names
2
+ // that the CLI dispatches via citty. Plugin commands MUST NOT shadow these names.
3
3
  // `src/cli/index.ts` consumes this for argv interception; `src/plugin/registry.ts`
4
- // consumes it to reject plugin commands that collide.
5
- export const BUILTIN_COMMAND_NAMES = [
6
- 'init',
7
- 'run',
8
- 'tui',
9
- 'start',
10
- 'stop',
11
- 'restart',
12
- 'status',
13
- 'reload',
14
- 'logs',
15
- 'inspect',
16
- 'dreams',
17
- 'shell',
18
- 'compose',
19
- 'channel',
20
- 'cron',
21
- 'tunnel',
22
- 'role',
23
- 'provider',
24
- 'model',
25
- 'mount',
26
- 'doctor',
27
- 'usage',
28
- 'update',
29
- '_hostd',
30
- '_update-check',
31
- ] as const
32
-
33
- export type BuiltinCommandName = (typeof BUILTIN_COMMAND_NAMES)[number]
4
+ // consumes it to reject plugin commands that collide. The names (and their help
5
+ // descriptions) are defined in `./command-meta`.
6
+ export { BUILTIN_COMMAND_NAMES } from './command-meta'
7
+ export type { BuiltinCommandName } from './command-meta'
@@ -0,0 +1,93 @@
1
+ // MUST stay free of command-module imports. `src/cli/index.ts` hand-renders the
2
+ // top-level help table from this data so a bare `typeclaw`/`--help` does not make
3
+ // citty resolve all 25 lazy `subCommands` thunks (each pulling the full
4
+ // config/docker/agent-messenger graph) just to read their descriptions — the
5
+ // resolve-all-for-help path was why a bare invocation was slower than a real
6
+ // subcommand. Each command module keeps its own literal `meta.description` (what
7
+ // citty prints for `typeclaw <cmd> --help`); the descriptions here are a separate
8
+ // copy, and `command-meta.test.ts` asserts the two stay byte-identical so the
9
+ // top-level table and per-command help cannot drift.
10
+
11
+ export type BuiltinCommandName =
12
+ | 'init'
13
+ | 'run'
14
+ | 'tui'
15
+ | 'start'
16
+ | 'stop'
17
+ | 'restart'
18
+ | 'status'
19
+ | 'reload'
20
+ | 'logs'
21
+ | 'inspect'
22
+ | 'dreams'
23
+ | 'shell'
24
+ | 'compose'
25
+ | 'channel'
26
+ | 'cron'
27
+ | 'tunnel'
28
+ | 'role'
29
+ | 'provider'
30
+ | 'model'
31
+ | 'mount'
32
+ | 'doctor'
33
+ | 'usage'
34
+ | 'update'
35
+ | '_hostd'
36
+ | '_update-check'
37
+
38
+ export type BuiltinCommandMeta = {
39
+ name: BuiltinCommandName
40
+ description: string
41
+ hidden?: boolean
42
+ }
43
+
44
+ export const BUILTIN_COMMANDS: readonly BuiltinCommandMeta[] = [
45
+ { name: 'init', description: 'initialize a new typeclaw agent in the current directory' },
46
+ { name: 'run', description: 'run the agent in the foreground (container stage)' },
47
+ { name: 'tui', description: 'open the live agent session in the read+write viewer (host stage)' },
48
+ { name: 'start', description: 'launch the agent container in the background (host stage)' },
49
+ { name: 'stop', description: 'stop the agent container (host stage)' },
50
+ { name: 'restart', description: 'stop and relaunch the agent container (host stage)' },
51
+ { name: 'status', description: 'show the agent container and host daemon status (host stage)' },
52
+ { name: 'reload', description: "reload the running agent's reloadable subsystems (cron, ...)" },
53
+ { name: 'logs', description: 'show the agent container logs (host stage)' },
54
+ {
55
+ name: 'inspect',
56
+ description: 'session viewer: pick a session, the live TUI, or container logs to observe (host stage)',
57
+ },
58
+ {
59
+ name: 'dreams',
60
+ description: "browse the dreaming subagent's memory-consolidation journal from git history (host stage)",
61
+ },
62
+ { name: 'shell', description: 'open an interactive shell in the agent container (host stage)' },
63
+ { name: 'compose', description: 'orchestrate every typeclaw agent in immediate subdirectories of cwd' },
64
+ { name: 'channel', description: 'manage channel adapters wired into the agent' },
65
+ {
66
+ name: 'cron',
67
+ description: 'inspect cron jobs registered in the running agent (user-authored + plugin-contributed)',
68
+ },
69
+ { name: 'tunnel', description: 'manage public tunnels for channels and manual upstreams' },
70
+ { name: 'role', description: 'manage role memberships on this agent' },
71
+ { name: 'provider', description: 'manage LLM provider credentials in secrets.json' },
72
+ { name: 'model', description: 'manage model profiles in typeclaw.json (models.default, models.fast, …)' },
73
+ { name: 'mount', description: 'manage host files and directories mounted into the agent container' },
74
+ { name: 'doctor', description: 'diagnose the host, agent folder, and plugins; surface remediation steps' },
75
+ { name: 'usage', description: 'report LLM token usage and cost for this agent folder' },
76
+ { name: 'update', description: 'update the installed typeclaw CLI (auto-detects global vs local)' },
77
+ { name: '_hostd', description: 'internal: host-side typeclaw daemon (do not invoke directly)', hidden: true },
78
+ {
79
+ name: '_update-check',
80
+ description: 'internal: refresh the typeclaw version cache (do not invoke directly)',
81
+ hidden: true,
82
+ },
83
+ ]
84
+
85
+ export const BUILTIN_COMMAND_NAMES: readonly BuiltinCommandName[] = BUILTIN_COMMANDS.map((c) => c.name)
86
+
87
+ const DESCRIPTION_BY_NAME: ReadonlyMap<string, string> = new Map(BUILTIN_COMMANDS.map((c) => [c.name, c.description]))
88
+
89
+ export function getBuiltinCommandDescription(name: BuiltinCommandName): string {
90
+ const description = DESCRIPTION_BY_NAME.get(name)
91
+ if (description === undefined) throw new Error(`unknown builtin command: ${name}`)
92
+ return description
93
+ }
@@ -0,0 +1,24 @@
1
+ import { type CommandDef, renderUsage } from 'citty'
2
+
3
+ import { CLI_VERSION } from '../init/cli-version'
4
+ import { BUILTIN_COMMANDS } from './command-meta'
5
+
6
+ // Reuses citty's own renderUsage for byte-identical output, but feeds it static
7
+ // `{ meta }` subcommands instead of the lazy import-thunks the real `main` uses.
8
+ // renderUsage only reads each subcommand's `meta` (name/description/hidden), so
9
+ // these stand-ins render the same table WITHOUT importing the 25 command modules
10
+ // — the resolve-all-for-help path was the startup-cost regression this fixes.
11
+ function buildHelpCommand(): CommandDef {
12
+ const subCommands: Record<string, CommandDef> = {}
13
+ for (const { name, description, hidden } of BUILTIN_COMMANDS) {
14
+ subCommands[name] = { meta: { name, description, ...(hidden === true ? { hidden: true } : {}) } }
15
+ }
16
+ return {
17
+ meta: { name: 'typeclaw', version: CLI_VERSION, description: 'TypeClaw agent runtime' },
18
+ subCommands,
19
+ }
20
+ }
21
+
22
+ export async function renderTopLevelUsage(): Promise<string> {
23
+ return renderUsage(buildHelpCommand())
24
+ }