typeclaw 0.39.3 → 0.39.5

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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/agent/attention-escalation.ts +11 -1
  3. package/src/agent/index.ts +10 -14
  4. package/src/agent/model-fallback.ts +13 -4
  5. package/src/agent/provider-error.ts +36 -1
  6. package/src/agent/subagents.ts +34 -3
  7. package/src/agent/throttle-circuit.ts +50 -0
  8. package/src/agent/tools/channel-reply.ts +48 -3
  9. package/src/agent/tools/ddg.ts +40 -5
  10. package/src/agent/tools/keyed-semaphore.ts +114 -0
  11. package/src/agent/tools/search-retry.ts +82 -0
  12. package/src/agent/turn-runner.ts +162 -0
  13. package/src/bundled-plugins/explorer/explorer.ts +5 -0
  14. package/src/bundled-plugins/memory/README.md +14 -14
  15. package/src/bundled-plugins/memory/append-tool.ts +98 -8
  16. package/src/bundled-plugins/memory/dreaming.ts +1 -1
  17. package/src/bundled-plugins/memory/fragment-parser.ts +10 -3
  18. package/src/bundled-plugins/memory/load-memory.ts +28 -2
  19. package/src/bundled-plugins/memory/memory-logger.ts +21 -5
  20. package/src/bundled-plugins/memory/search-tool.ts +50 -7
  21. package/src/bundled-plugins/memory/stream-events.ts +23 -0
  22. package/src/bundled-plugins/memory/vector/hybrid.ts +9 -2
  23. package/src/bundled-plugins/reviewer/reviewer.ts +3 -1
  24. package/src/bundled-plugins/scout/scout.ts +5 -0
  25. package/src/bundled-plugins/security/index.ts +24 -1
  26. package/src/bundled-plugins/security/policies/cron-promotion.ts +94 -62
  27. package/src/bundled-plugins/security/policies/plugin-addition.ts +2 -4
  28. package/src/bundled-plugins/security/policies/role-promotion.ts +2 -4
  29. package/src/channels/adapters/github/permission-guidance.ts +18 -0
  30. package/src/channels/adapters/webex-bot.ts +26 -25
  31. package/src/channels/adapters/webex-prefetch-limiter.ts +120 -0
  32. package/src/channels/adapters/webex.ts +27 -30
  33. package/src/channels/manager.ts +64 -57
  34. package/src/channels/router.ts +134 -4
  35. package/src/channels/types.ts +8 -1
  36. package/src/cli/builtins.ts +6 -32
  37. package/src/cli/channel.ts +7 -11
  38. package/src/cli/command-meta.ts +93 -0
  39. package/src/cli/help.ts +24 -0
  40. package/src/cli/index.ts +34 -10
  41. package/src/cli/init.ts +2 -2
  42. package/src/cli/plugin-commands-dispatch.ts +7 -1
  43. package/src/config/config.ts +27 -1
  44. package/src/container/start.ts +22 -2
  45. package/src/hostd/daemon.ts +55 -26
  46. package/src/hostd/spawn.ts +53 -19
  47. package/src/permissions/permissions.ts +12 -0
  48. package/src/run/codex-fetch-observer.ts +11 -6
  49. package/src/secrets/oauth-xai.ts +2 -2
  50. package/src/server/index.ts +27 -2
  51. package/src/skills/typeclaw-channel-github/SKILL.md +59 -13
  52. package/src/skills/typeclaw-channels/SKILL.md +1 -1
  53. package/src/skills/typeclaw-config/SKILL.md +1 -0
  54. package/src/skills/typeclaw-cron/SKILL.md +9 -4
  55. package/src/skills/typeclaw-permissions/SKILL.md +18 -6
@@ -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'
@@ -4,6 +4,7 @@ import { cancel, confirm, intro, isCancel, log, note, password, select, spinner,
4
4
  import { defineCommand } from 'citty'
5
5
  import QRCode from 'qrcode'
6
6
 
7
+ import { githubRequiredPermissionsNote } from '@/channels/adapters/github/permission-guidance'
7
8
  import { config } from '@/config'
8
9
  import {
9
10
  listChannels,
@@ -1039,8 +1040,7 @@ async function promptGithubCredentials(cwd: string): Promise<{
1039
1040
  note(
1040
1041
  [
1041
1042
  'Choose PAT auth for a quick setup, or GitHub App auth for expiring installation tokens.',
1042
- 'Required permissions: Issues read/write, Pull requests read/write, Discussions read/write (if used),',
1043
- 'Metadata read, and Webhooks read/write (TypeClaw will create and manage the repository webhooks for you).',
1043
+ githubRequiredPermissionsNote(true),
1044
1044
  ].join('\n'),
1045
1045
  'Get GitHub credentials',
1046
1046
  )
@@ -1196,19 +1196,16 @@ async function promptGithubAuthUpdate(currentType: 'pat' | 'app'): Promise<Githu
1196
1196
  if (nextType === 'pat') {
1197
1197
  if (action === 'rotate') {
1198
1198
  note(
1199
- [
1200
- 'Rotate at https://github.com/settings/personal-access-tokens.',
1201
- 'Required permissions: Issues read/write, Pull requests read/write, Discussions read/write (if used),',
1202
- 'Metadata read, and Webhooks read/write.',
1203
- ].join('\n'),
1199
+ ['Rotate at https://github.com/settings/personal-access-tokens.', githubRequiredPermissionsNote(false)].join(
1200
+ '\n',
1201
+ ),
1204
1202
  'Rotate the GitHub PAT',
1205
1203
  )
1206
1204
  } else {
1207
1205
  note(
1208
1206
  [
1209
1207
  'Create a fine-grained PAT at https://github.com/settings/personal-access-tokens.',
1210
- 'Required permissions: Issues read/write, Pull requests read/write, Discussions read/write (if used),',
1211
- 'Metadata read, and Webhooks read/write.',
1208
+ githubRequiredPermissionsNote(false),
1212
1209
  ].join('\n'),
1213
1210
  'Switch to GitHub PAT auth',
1214
1211
  )
@@ -1236,8 +1233,7 @@ async function promptGithubAuthUpdate(currentType: 'pat' | 'app'): Promise<Githu
1236
1233
  note(
1237
1234
  [
1238
1235
  'Create a GitHub App at https://github.com/settings/apps/new and install it on your repositories.',
1239
- 'Required permissions: Issues read/write, Pull requests read/write, Discussions read/write (if used),',
1240
- 'Metadata read, and Webhooks read/write.',
1236
+ githubRequiredPermissionsNote(false),
1241
1237
  'Then collect the App ID, generate a private key (.pem), and grab the Installation ID from the URL',
1242
1238
  'of the installation page (https://github.com/settings/installations/<installation-id>).',
1243
1239
  ].join('\n'),
@@ -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
+ }
package/src/cli/index.ts CHANGED
@@ -75,6 +75,17 @@ function runHostStartupMigrationsOnce(commandName: string | undefined): void {
75
75
  }
76
76
  }
77
77
 
78
+ // Plugin commands are discovered from the agent folder; outside one, discovery
79
+ // yields nothing and no section prints. Shared by the --help and no-command
80
+ // paths so both keep showing plugin commands above the builtin usage table.
81
+ async function printPluginCommandsSection(): Promise<void> {
82
+ const { renderPluginCommandsSection } = await import('./plugin-command-help')
83
+ const { discoverCommands } = await import('./plugin-commands')
84
+ const discovery = await discoverCommands({ cwd: process.cwd() })
85
+ const section = renderPluginCommandsSection(discovery.commands)
86
+ if (section !== null) process.stdout.write(`${section}\n\n`)
87
+ }
88
+
78
89
  async function runWithPluginDispatch(): Promise<void> {
79
90
  const argv = process.argv.slice(2)
80
91
  const first = argv[0]
@@ -91,17 +102,30 @@ async function runWithPluginDispatch(): Promise<void> {
91
102
  await maybeNotifyUpdate(first)
92
103
  }
93
104
 
105
+ // Top-level help and the no-command case are hand-rendered from the static
106
+ // command-meta table (see ./help) instead of `runMain(main)`. Routing them
107
+ // through citty would resolve every lazy `subCommands` thunk just to read the
108
+ // descriptions for the usage table, importing all 25 command modules (and
109
+ // their config/docker/agent-messenger graphs) — which made a bare `typeclaw`
110
+ // slower than running a real subcommand. Per-command help (`typeclaw x --help`)
111
+ // still goes through citty below, importing only that one command.
94
112
  if (first === '--help' || first === '-h') {
95
- // citty calls process.exit() after rendering help, so anything we print
96
- // AFTER `runMain(main)` is never reached. Print the plugin commands
97
- // section first; citty's own help follows and the user reads top-down.
98
- const { renderPluginCommandsSection } = await import('./plugin-command-help')
99
- const { discoverCommands } = await import('./plugin-commands')
100
- const discovery = await discoverCommands({ cwd: process.cwd() })
101
- const section = renderPluginCommandsSection(discovery.commands)
102
- if (section !== null) process.stdout.write(`${section}\n\n`)
103
- await runMain(main)
104
- return
113
+ await printPluginCommandsSection()
114
+ const { renderTopLevelUsage } = await import('./help')
115
+ process.stdout.write(`${await renderTopLevelUsage()}\n\n`)
116
+ process.exit(0)
117
+ }
118
+
119
+ if (first === undefined) {
120
+ // No plugin discovery here: bare `typeclaw` must stay a pure
121
+ // E_NO_COMMAND report and never load plugin/config code (discoverCommands
122
+ // can rewrite typeclaw.json via loadConfigSync). Plugin commands surface
123
+ // only on explicit top-level help and plugin-command dispatch. Mirror
124
+ // citty's E_NO_COMMAND: usage to stdout, the message to stderr, exit 1.
125
+ const { renderTopLevelUsage } = await import('./help')
126
+ process.stdout.write(`${await renderTopLevelUsage()}\n\n`)
127
+ process.stderr.write('No command specified.\n')
128
+ process.exit(1)
105
129
  }
106
130
 
107
131
  if (
package/src/cli/init.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  } from '@clack/prompts'
16
16
  import { defineCommand } from 'citty'
17
17
 
18
+ import { githubRequiredPermissionsNote } from '@/channels/adapters/github/permission-guidance'
18
19
  import {
19
20
  KNOWN_PROVIDER_VENDORS,
20
21
  KNOWN_PROVIDERS,
@@ -1666,8 +1667,7 @@ async function runGithubFlow(cwd: string): Promise<StepResult<CollectedInputs['c
1666
1667
  note(
1667
1668
  [
1668
1669
  'Choose PAT auth for a quick setup, or GitHub App auth for expiring installation tokens.',
1669
- 'Required permissions: Issues read/write, Pull requests read/write, Discussions read/write (if used),',
1670
- 'Metadata read, and Webhooks read/write (TypeClaw will create and manage the repository webhooks for you).',
1670
+ githubRequiredPermissionsNote(true),
1671
1671
  ].join('\n'),
1672
1672
  'Get GitHub credentials',
1673
1673
  )
@@ -1,4 +1,4 @@
1
- import { proxyContainerCommand } from './container-command-client'
1
+ import { proxyContainerCommand, type ContainerProxyOptions } from './container-command-client'
2
2
  import { parseArgs, runHostCommand } from './host-command-runner'
3
3
  import { renderCommandHelp } from './plugin-command-help'
4
4
  import { discoverCommands } from './plugin-commands'
@@ -16,6 +16,11 @@ export type DispatchOptions = {
16
16
  stdout?: WritableStream<Uint8Array>
17
17
  stderr?: WritableStream<Uint8Array>
18
18
  signal?: AbortSignal
19
+ // Test seam: override container-URL resolution so unit tests exercise the
20
+ // container dispatch path without spawning a real `docker inspect` (slow and
21
+ // flaky on Windows CI). Unset in production: proxyContainerCommand falls back
22
+ // to the live docker probe.
23
+ resolveContainerUrl?: ContainerProxyOptions['resolveUrl']
19
24
  }
20
25
 
21
26
  export async function dispatchPluginCommand(opts: DispatchOptions): Promise<PluginCommandDispatchOutcome> {
@@ -62,6 +67,7 @@ export async function dispatchPluginCommand(opts: DispatchOptions): Promise<Plug
62
67
  stdout,
63
68
  stderr,
64
69
  abortSignal: signal,
70
+ resolveUrl: opts.resolveContainerUrl,
65
71
  })
66
72
  if (!containerResult.ok) {
67
73
  return { kind: 'error', exitCode: containerResult.exitCode, message: containerResult.message }
@@ -707,13 +707,39 @@ const profileEntrySchema = z
707
707
  return value.thinkingLevel === undefined ? { refs } : { refs, thinkingLevel: value.thinkingLevel }
708
708
  })
709
709
 
710
+ // Built-in per-profile `thinkingLevel` defaults, materialized at parse time so
711
+ // resolved config / `typeclaw model list` / prompt dumps show the effective level
712
+ // and users can override per profile. Materialized here (not as a runtime
713
+ // constant) the `deep: 'high'` default rides on the `deep` entry itself, so it
714
+ // still beats a lowered `models.default.thinkingLevel` (resolution reads the
715
+ // profile's own level first). `default` and `vision` carry none — they fall
716
+ // through to the model/SDK default. `high` over `xhigh`: `xhigh` ~doubles latency
717
+ // and spend for no agentic-quality gain.
718
+ const PROFILE_THINKING_LEVEL_DEFAULTS = {
719
+ fast: 'low',
720
+ deep: 'high',
721
+ } satisfies Partial<Record<string, ThinkingLevel>>
722
+
710
723
  export const modelsSchema = z
711
724
  .record(z.string().min(1), profileEntrySchema)
712
725
  .refine((m) => 'default' in m, { message: 'models.default is required' })
726
+ // Fill only when unset, so an explicit level (including `off`) always wins.
727
+ .transform((models): Models => {
728
+ let next: Record<string, ProfileEntry> | undefined
729
+ for (const [profile, thinkingLevel] of Object.entries(PROFILE_THINKING_LEVEL_DEFAULTS)) {
730
+ const entry = models[profile]
731
+ if (entry !== undefined && entry.thinkingLevel === undefined) {
732
+ next ??= { ...models }
733
+ next[profile] = { ...entry, thinkingLevel }
734
+ }
735
+ }
736
+ return (next ?? models) as Models
737
+ })
713
738
 
714
739
  // A model profile after normalisation: its fallback chain (always non-empty)
715
740
  // plus an optional reasoning effort. `thinkingLevel` resolution is layered at
716
- // session creation: profile's own → `default` profile's → SDK default.
741
+ // session creation: profile's own (incl. built-in per-profile defaults
742
+ // materialized above) → `default` profile's → SDK default.
717
743
  export type ProfileEntry = {
718
744
  refs: ModelRef[]
719
745
  thinkingLevel?: ThinkingLevel