typeclaw 0.38.1 → 0.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +5 -0
  2. package/package.json +2 -2
  3. package/src/agent/attention-escalation.ts +158 -7
  4. package/src/agent/auth.ts +2 -2
  5. package/src/agent/git-nudge.ts +7 -7
  6. package/src/agent/index.ts +25 -2
  7. package/src/agent/restart/index.ts +17 -8
  8. package/src/agent/session-origin.ts +21 -0
  9. package/src/agent/subagents.ts +29 -1
  10. package/src/agent/system-prompt.ts +18 -5
  11. package/src/agent/tools/restart.ts +0 -3
  12. package/src/agent/tools/spawn-subagent.ts +7 -0
  13. package/src/bundled-plugins/backup/index.ts +5 -2
  14. package/src/bundled-plugins/backup/runner.ts +55 -23
  15. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +7 -8
  16. package/src/bundled-plugins/memory/dreaming.ts +37 -24
  17. package/src/bundled-plugins/memory/index.ts +24 -6
  18. package/src/bundled-plugins/memory/memory-logger.ts +14 -10
  19. package/src/bundled-plugins/operator/operator.ts +1 -0
  20. package/src/channels/adapters/kakaotalk-membership.ts +67 -0
  21. package/src/channels/adapters/kakaotalk.ts +8 -0
  22. package/src/channels/adapters/line-token.ts +55 -0
  23. package/src/channels/adapters/line.ts +74 -0
  24. package/src/channels/adapters/webex-bot-classify.ts +14 -1
  25. package/src/channels/adapters/webex-bot.ts +24 -1
  26. package/src/channels/adapters/webex-classify.ts +16 -1
  27. package/src/channels/adapters/webex.ts +27 -1
  28. package/src/channels/router.ts +55 -2
  29. package/src/cli/hostd.ts +40 -0
  30. package/src/cli/model.ts +143 -3
  31. package/src/config/config.ts +101 -36
  32. package/src/config/index.ts +3 -0
  33. package/src/config/models-mutation.ts +105 -15
  34. package/src/config/providers-mutation.ts +4 -4
  35. package/src/config/providers.ts +6 -14
  36. package/src/container/shared.ts +136 -14
  37. package/src/container/shell.ts +12 -2
  38. package/src/container/start.ts +25 -7
  39. package/src/doctor/commit.ts +10 -10
  40. package/src/dreams/git.ts +20 -7
  41. package/src/dreams/index.ts +22 -7
  42. package/src/git/reconcile-ignored.ts +56 -27
  43. package/src/git/resolve-agent-git.ts +12 -0
  44. package/src/git/system-commit.ts +16 -10
  45. package/src/hostd/daemon.ts +16 -0
  46. package/src/hostd/index.ts +1 -11
  47. package/src/hostd/paths.ts +0 -16
  48. package/src/hostd/webex-renewal-manager.ts +216 -0
  49. package/src/init/dockerfile.ts +13 -4
  50. package/src/init/gitignore.ts +4 -2
  51. package/src/run/index.ts +4 -1
  52. package/src/secrets/schema.ts +1 -0
  53. package/src/secrets/webex-renewal.ts +215 -0
  54. package/src/server/index.ts +25 -3
  55. package/src/skills/typeclaw-config/SKILL.md +18 -16
  56. package/typeclaw.schema.json +172 -1
package/src/cli/model.ts CHANGED
@@ -1,13 +1,17 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
1
4
  import { autocomplete, cancel, intro, isCancel, log, select } from '@clack/prompts'
2
5
  import { defineCommand } from 'citty'
3
6
 
4
- import type { CustomModelMeta } from '@/config'
7
+ import type { CustomModelMeta, ThinkingLevel } from '@/config'
5
8
  import {
6
9
  addProfile,
7
10
  listModelProfiles,
8
11
  listRegisteredModelRefs,
9
12
  removeProfile,
10
13
  setProfile,
14
+ setProfileThinkingLevel,
11
15
  } from '@/config/models-mutation'
12
16
  import {
13
17
  isKnownModelRef,
@@ -51,6 +55,12 @@ const setSub = defineCommand({
51
55
  description: 'write even when the target provider has no credentials configured',
52
56
  required: false,
53
57
  },
58
+ thinking: {
59
+ type: 'string',
60
+ description:
61
+ "reasoning effort for THIS profile (off|minimal|low|medium|high|xhigh|default); the `default` profile's level is the de-facto global default",
62
+ required: false,
63
+ },
54
64
  },
55
65
  async run({ args }) {
56
66
  const cwd = ensureAgentDir()
@@ -59,14 +69,34 @@ const setSub = defineCommand({
59
69
 
60
70
  intro(`Setting model profile: ${profile} → ${picked.ref}`)
61
71
 
72
+ // Gather every interactive/flag input BEFORE any write, so cancelling a
73
+ // later prompt (e.g. the thinking-level select) aborts the whole command
74
+ // without having already mutated typeclaw.json. Non-interactive (`--thinking`)
75
+ // resolves the level from the flag; an interactive run (no flag, no explicit
76
+ // ref) offers the prompt; explicit-ref scripted calls leave the level alone.
77
+ const interactive = args.ref === undefined && args.thinking === undefined
78
+ let thinking: { level: ThinkingLevel | undefined } | undefined
79
+ if (args.thinking !== undefined) {
80
+ const parsed = parseThinkingArg(args.thinking)
81
+ if (!parsed.ok) {
82
+ console.error(errorLine(parsed.reason))
83
+ process.exit(1)
84
+ }
85
+ thinking = { level: parsed.level }
86
+ } else if (interactive) {
87
+ thinking = await pickProfileThinkingLevel(cwd, profile)
88
+ }
89
+
62
90
  const result = setProfile(cwd, profile, picked.ref, {
63
91
  force: args.force === true,
64
92
  ...(picked.meta !== undefined ? { meta: picked.meta } : {}),
93
+ ...(thinking !== undefined ? { thinkingLevel: thinking.level } : {}),
65
94
  })
66
95
  if (!result.ok) {
67
96
  console.error(errorLine(result.reason))
68
97
  process.exit(1)
69
98
  }
99
+
70
100
  done({
71
101
  title: c.green(`Profile "${profile}" set.`),
72
102
  details: `${profile} → ${picked.ref}`,
@@ -75,6 +105,50 @@ const setSub = defineCommand({
75
105
  },
76
106
  })
77
107
 
108
+ const thinkingSub = defineCommand({
109
+ meta: {
110
+ name: 'thinking',
111
+ description: "set the default profile's reasoning effort (the de-facto global default for new sessions)",
112
+ },
113
+ args: {
114
+ level: {
115
+ type: 'positional',
116
+ description:
117
+ 'reasoning effort (off|minimal|low|medium|high|xhigh); or "default" to clear and defer to the SDK default',
118
+ required: false,
119
+ },
120
+ },
121
+ async run({ args }) {
122
+ const cwd = ensureAgentDir()
123
+ let level: ThinkingLevel | undefined
124
+ if (args.level !== undefined) {
125
+ const parsed = parseThinkingArg(args.level)
126
+ if (!parsed.ok) {
127
+ console.error(errorLine(parsed.reason))
128
+ process.exit(1)
129
+ }
130
+ level = parsed.level
131
+ } else {
132
+ const picked = await pickProfileThinkingLevel(cwd, 'default')
133
+ if (picked === undefined) return
134
+ level = picked.level
135
+ }
136
+ const result = setProfileThinkingLevel(cwd, 'default', level)
137
+ if (!result.ok) {
138
+ console.error(errorLine(result.reason))
139
+ process.exit(1)
140
+ }
141
+ done({
142
+ title: c.green(
143
+ level === undefined
144
+ ? "default profile's thinkingLevel cleared."
145
+ : `default profile's thinkingLevel set to "${level}".`,
146
+ ),
147
+ hints: [{ label: 'If the agent is running:', command: 'typeclaw reload' }],
148
+ })
149
+ },
150
+ })
151
+
78
152
  const addSub = defineCommand({
79
153
  meta: {
80
154
  name: 'add',
@@ -174,13 +248,21 @@ const listSub = defineCommand({
174
248
  const refDisplay = (e: (typeof entries)[number]): string =>
175
249
  e.refs.length > 1 ? `${e.ref} ${c.dim(`(+${e.refs.length - 1} fallback)`)}` : e.ref
176
250
  const refWidth = Math.max(3, ...entries.map((e) => e.ref.length + (e.refs.length > 1 ? 14 : 0)))
251
+ // An explicit per-profile level shows as-is; a profile without one inherits
252
+ // the default profile's level (or the SDK default for `default` itself).
253
+ const thinkingDisplay = (e: (typeof entries)[number]): string =>
254
+ e.thinkingLevel !== undefined ? e.thinkingLevel : c.dim(e.isDefault ? 'sdk-default' : 'inherit')
255
+ const thinkingWidth = Math.max(
256
+ 5,
257
+ ...entries.map((e) => (e.thinkingLevel ?? (e.isDefault ? 'sdk-default' : 'inherit')).length),
258
+ )
177
259
 
178
- const header = `${'PROFILE'.padEnd(profileWidth)} ${'REF'.padEnd(refWidth)} PROVIDER STATUS`
260
+ const header = `${'PROFILE'.padEnd(profileWidth)} ${'REF'.padEnd(refWidth)} ${'THINK'.padEnd(thinkingWidth)} PROVIDER STATUS`
179
261
  console.log(c.dim(header))
180
262
  for (const e of entries) {
181
263
  const star = e.isDefault ? c.cyan('*') : ' '
182
264
  const status = e.credentialStatus === 'available' ? c.green('ok') : c.yellow('missing-credentials')
183
- const line = `${star}${e.profile.padEnd(profileWidth - 1)} ${refDisplay(e).padEnd(refWidth)} ${e.providerId.padEnd(12)} ${status}`
265
+ const line = `${star}${e.profile.padEnd(profileWidth - 1)} ${refDisplay(e).padEnd(refWidth)} ${thinkingDisplay(e).padEnd(thinkingWidth)} ${e.providerId.padEnd(12)} ${status}`
184
266
  console.log(line)
185
267
  if (e.refs.length > 1) {
186
268
  for (let i = 1; i < e.refs.length; i++) {
@@ -202,6 +284,7 @@ export const modelCommand = defineCommand({
202
284
  add: addSub,
203
285
  remove: removeSub,
204
286
  list: listSub,
287
+ thinking: thinkingSub,
205
288
  },
206
289
  })
207
290
 
@@ -232,6 +315,63 @@ async function pickProfileName(): Promise<string> {
232
315
  return choice
233
316
  }
234
317
 
318
+ const THINKING_LEVELS: ThinkingLevel[] = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh']
319
+ const KEEP_THINKING_SENTINEL = '__keep__'
320
+
321
+ export type ParsedThinkingArg = { ok: true; level: ThinkingLevel | undefined } | { ok: false; reason: string }
322
+
323
+ export function parseThinkingArg(raw: string): ParsedThinkingArg {
324
+ const value = raw.trim().toLowerCase()
325
+ if (value === 'default' || value === 'unset' || value === 'none') return { ok: true, level: undefined }
326
+ if ((THINKING_LEVELS as string[]).includes(value)) return { ok: true, level: value as ThinkingLevel }
327
+ return {
328
+ ok: false,
329
+ reason: `Invalid --thinking "${raw}". Use one of: ${THINKING_LEVELS.join(', ')}, or "default" to clear.`,
330
+ }
331
+ }
332
+
333
+ async function pickProfileThinkingLevel(
334
+ cwd: string,
335
+ profile: string,
336
+ ): Promise<{ level: ThinkingLevel | undefined } | undefined> {
337
+ const current = readProfileThinkingLevel(cwd, profile)
338
+ const clearedHint = profile === 'default' ? 'defer to the SDK default' : "inherit the default profile's level"
339
+ const choice = await select<string>({
340
+ message: `Reasoning effort for profile "${profile}"`,
341
+ options: [
342
+ { value: KEEP_THINKING_SENTINEL, label: 'keep current', hint: current ?? clearedHint },
343
+ ...THINKING_LEVELS.map((level) => ({ value: level, label: level })),
344
+ { value: 'default', label: 'clear', hint: clearedHint },
345
+ ],
346
+ initialValue: KEEP_THINKING_SENTINEL,
347
+ })
348
+ if (isCancel(choice)) {
349
+ cancel('Aborted.')
350
+ process.exit(0)
351
+ }
352
+ if (choice === KEEP_THINKING_SENTINEL) return undefined
353
+ if (choice === 'default') return { level: undefined }
354
+ return { level: choice as ThinkingLevel }
355
+ }
356
+
357
+ // Reads a profile's own thinkingLevel straight from disk (rich-object form
358
+ // only — a bare string/array profile has no level). Used to seed the
359
+ // interactive picker's "keep current" hint.
360
+ function readProfileThinkingLevel(cwd: string, profile: string): ThinkingLevel | undefined {
361
+ try {
362
+ const parsed = JSON.parse(readFileSync(join(cwd, 'typeclaw.json'), 'utf8')) as {
363
+ models?: Record<string, unknown>
364
+ }
365
+ const entry = parsed.models?.[profile]
366
+ if (typeof entry === 'object' && entry !== null && !Array.isArray(entry)) {
367
+ return (entry as { thinkingLevel?: ThinkingLevel }).thinkingLevel
368
+ }
369
+ return undefined
370
+ } catch {
371
+ return undefined
372
+ }
373
+ }
374
+
235
375
  async function pickModelRef(cwd: string): Promise<PickedModelRef> {
236
376
  while (true) {
237
377
  const refs = listRegisteredModelRefs(cwd)
@@ -481,15 +481,17 @@ export type SandboxConfig = z.infer<typeof sandboxSchema>
481
481
 
482
482
  // Host-stage `typeclaw compose` knobs. `exclude: true` skips this agent during
483
483
  // compose discovery (same effect as parking it under an `_`-prefixed dir, but
484
- // without renaming the folder). The container never reads this block — it's a
485
- // pure compose CLI hint, so omitting it keeps the agent in every compose
486
- // operation. Namespaced under `compose` so future compose-only settings have a
487
- // home without crowding the top level.
484
+ // without renaming the folder). `monorepo` is a host-stage scaffolding hint.
485
+ // The container never reads this block — it's a pure compose CLI hint, so
486
+ // omitting it keeps the agent in every compose operation. Namespaced under
487
+ // `compose` so future compose-only settings have a home without crowding the
488
+ // top level.
488
489
  export const composeSchema = z
489
490
  .object({
490
491
  exclude: z.boolean().default(false),
492
+ monorepo: z.boolean().default(false),
491
493
  })
492
- .default({ exclude: false })
494
+ .default({ exclude: false, monorepo: false })
493
495
 
494
496
  export type ComposeConfig = z.infer<typeof composeSchema>
495
497
 
@@ -636,30 +638,75 @@ function asModelRef(value: string): ModelRef {
636
638
  // level. `migrateLegacyConfigShape` rewrites that to `models: { default: ... }`
637
639
  // on first load (and writes the result back to disk + commits via
638
640
  // `persistMigratedConfig`), so every downstream consumer sees the new shape.
639
- const modelRefOrChainSchema = z
640
- .union([
641
- singleModelRef,
642
- z
643
- .array(singleModelRef)
644
- .min(1)
645
- // Reject exact duplicates in a chain — retrying the same ref after the
646
- // same class of failure is almost certainly a config typo, and silently
647
- // deduping would mask user intent. Different models from the same
648
- // provider (e.g. `["openai/gpt-5.4-nano", "openai/gpt-5.4-mini"]`) are
649
- // still valid because they hit distinct upstream endpoints.
650
- .refine((arr) => new Set(arr).size === arr.length, {
651
- message: 'models chain must not contain duplicate refs',
652
- }),
653
- ])
654
- .transform((value) => (Array.isArray(value) ? value : [value]).map((ref) => asModelRef(ref)))
641
+ // Mirrors pi-coding-agent's `ThinkingLevel`. Kept as a local enum (rather than
642
+ // importing the SDK type) so the schema owns the canonical value list and zod
643
+ // can validate `typeclaw.json` without a runtime SDK dependency.
644
+ export const thinkingLevelSchema = z.enum(['off', 'minimal', 'low', 'medium', 'high', 'xhigh'])
645
+ export type ThinkingLevel = z.infer<typeof thinkingLevelSchema>
646
+
647
+ // Reject exact duplicates in a chain — retrying the same ref after the same
648
+ // class of failure is almost certainly a config typo, and silently deduping
649
+ // would mask user intent. Different models from the same provider (e.g.
650
+ // `["openai/gpt-5.4-nano", "openai/gpt-5.4-mini"]`) are still valid because
651
+ // they hit distinct upstream endpoints.
652
+ const noDuplicateChainRefs = (arr: readonly string[]): boolean => new Set(arr).size === arr.length
653
+ const chainRefinementMessage = { message: 'models chain must not contain duplicate refs' }
654
+ const modelChainInputSchema = z.array(singleModelRef).min(1).refine(noDuplicateChainRefs, chainRefinementMessage)
655
+
656
+ // A profile value is one of three shapes, all normalised to `ProfileEntry`:
657
+ // "openai/gpt-5.4-nano" single ref
658
+ // ["refA", "refB"] fallback chain
659
+ // { models: "refA" | ["refA","refB"], thinkingLevel? } rich object
660
+ // The rich object couples a per-profile `thinkingLevel` to the model(s); the
661
+ // `models` key mirrors the top-level map name and reads naturally for both a
662
+ // single ref and a chain. `model` is accepted as single-ref sugar but exactly
663
+ // one of `model`/`models` may be present. Legacy string/array forms keep
664
+ // parsing untouched (they normalise to `{ refs, thinkingLevel: undefined }`),
665
+ // so no migration is needed.
666
+ const richProfileSchema = z
667
+ .object({
668
+ model: singleModelRef.optional(),
669
+ models: z.union([singleModelRef, modelChainInputSchema]).optional(),
670
+ thinkingLevel: thinkingLevelSchema.optional(),
671
+ })
672
+ .strict()
673
+ .superRefine((value, ctx) => {
674
+ if (value.model === undefined && value.models === undefined) {
675
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'profile must specify `model` or `models`' })
676
+ }
677
+ if (value.model !== undefined && value.models !== undefined) {
678
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'profile must specify only one of `model` or `models`' })
679
+ }
680
+ })
681
+
682
+ const profileEntrySchema = z
683
+ .union([singleModelRef, modelChainInputSchema, richProfileSchema])
684
+ .transform((value): ProfileEntry => {
685
+ if (typeof value === 'string' || Array.isArray(value)) {
686
+ const refs = (Array.isArray(value) ? value : [value]).map((ref) => asModelRef(ref))
687
+ return { refs }
688
+ }
689
+ const refsInput = value.models ?? value.model!
690
+ const refs = (Array.isArray(refsInput) ? refsInput : [refsInput]).map((ref) => asModelRef(ref))
691
+ return value.thinkingLevel === undefined ? { refs } : { refs, thinkingLevel: value.thinkingLevel }
692
+ })
693
+
655
694
  export const modelsSchema = z
656
- .record(z.string().min(1), modelRefOrChainSchema)
695
+ .record(z.string().min(1), profileEntrySchema)
657
696
  .refine((m) => 'default' in m, { message: 'models.default is required' })
658
697
 
698
+ // A model profile after normalisation: its fallback chain (always non-empty)
699
+ // plus an optional reasoning effort. `thinkingLevel` resolution is layered at
700
+ // session creation: profile's own → `default` profile's → SDK default.
701
+ export type ProfileEntry = {
702
+ refs: ModelRef[]
703
+ thinkingLevel?: ThinkingLevel
704
+ }
705
+
659
706
  // Zod's `z.record(..., refine)` doesn't refine the inferred type. The
660
707
  // `default` key is schema-enforced, so we narrow it here to spare every
661
708
  // consumer the `T | undefined` assertion noise.
662
- export type Models = Record<string, ModelRef[]> & { default: ModelRef[] }
709
+ export type Models = Record<string, ProfileEntry> & { default: ProfileEntry }
663
710
 
664
711
  export const configSchema = z
665
712
  .object({
@@ -668,9 +715,11 @@ export const configSchema = z
668
715
  // `default(() => ...)` ensures every parsed config has at least
669
716
  // `models.default`. Direct `.default({ default: ... })` would short-circuit
670
717
  // the refinement, so we lean on the lazy thunk form. The default value is
671
- // shaped to match the post-transform output (always `ModelRef[]`),
672
- // not the user-facing input shape.
673
- models: modelsSchema.default(() => ({ default: [asModelRef(DEFAULT_MODEL_REF)] })) as unknown as z.ZodType<Models>,
718
+ // shaped to match the post-transform output (a `ProfileEntry`), not the
719
+ // user-facing input shape.
720
+ models: modelsSchema.default(() => ({
721
+ default: { refs: [asModelRef(DEFAULT_MODEL_REF)] },
722
+ })) as unknown as z.ZodType<Models>,
674
723
  customModels: customModelsSchema,
675
724
  // Defaults to `[]` so the field can be omitted from `typeclaw.json` (no
676
725
  // host paths exposed) without failing the whole config load. `typeclaw
@@ -754,27 +803,43 @@ function resolveCustomModelCost(cost: CustomModelMeta['cost']): Model<KnownApi>[
754
803
  }
755
804
 
756
805
  // Resolves a profile name (e.g. `fast`, `deep`, `vision`) to its fallback
757
- // chain. Unknown profiles fall back to `default` so callers can pass through
758
- // arbitrary subagent-declared or user-overridden strings without crashing.
759
- // `refs` is non-empty (the schema guarantees `default` exists and every value
760
- // is at least one ref). `ref` is the head of the chain — the model the
761
- // session is created with first. Callers that don't implement fallback can
762
- // keep reading `ref`; fallback-aware callers iterate `refs`.
806
+ // chain and per-profile thinking level. Unknown profiles fall back to
807
+ // `default` so callers can pass through arbitrary subagent-declared or
808
+ // user-overridden strings without crashing. `refs` is non-empty (the schema
809
+ // guarantees `default` exists and every value is at least one ref). `ref` is
810
+ // the head of the chain — the model the session is created with first.
811
+ // Callers that don't implement fallback can keep reading `ref`; fallback-aware
812
+ // callers iterate `refs`. `thinkingLevel` is the profile's own override (may be
813
+ // undefined, meaning inherit the `default` profile's level — see session
814
+ // creation).
763
815
  export type ResolvedProfile = {
764
816
  ref: ModelRef
765
817
  refs: ModelRef[]
818
+ thinkingLevel?: ThinkingLevel
766
819
  profile: string
767
820
  fellBackToDefault: boolean
768
821
  }
769
822
 
770
823
  export function resolveProfile(models: Models, name: string | undefined): ResolvedProfile {
771
824
  const requested = name ?? 'default'
772
- const refs = models[requested]
773
- if (refs !== undefined) {
774
- return { ref: refs[0]!, refs, profile: requested, fellBackToDefault: false }
825
+ const entry = models[requested]
826
+ if (entry !== undefined) {
827
+ return {
828
+ ref: entry.refs[0]!,
829
+ refs: entry.refs,
830
+ thinkingLevel: entry.thinkingLevel,
831
+ profile: requested,
832
+ fellBackToDefault: false,
833
+ }
775
834
  }
776
835
  const fallback = models.default
777
- return { ref: fallback[0]!, refs: fallback, profile: 'default', fellBackToDefault: true }
836
+ return {
837
+ ref: fallback.refs[0]!,
838
+ refs: fallback.refs,
839
+ thinkingLevel: fallback.thinkingLevel,
840
+ profile: 'default',
841
+ fellBackToDefault: true,
842
+ }
778
843
  }
779
844
 
780
845
  // Resolves a mount's `path` field to an absolute host path, mirroring shell
@@ -14,6 +14,7 @@ export {
14
14
  gitignoreSchema,
15
15
  GWS_MULTI_ACCOUNT_PLUGIN_PACKAGE,
16
16
  GWS_MULTI_ACCOUNT_PLUGIN_VERSION,
17
+ thinkingLevelSchema,
17
18
  loadConfigSync,
18
19
  loadConfigSyncOrDefaults,
19
20
  loadPluginConfigsSync,
@@ -44,7 +45,9 @@ export {
44
45
  type ParseConfigJsonOptions,
45
46
  type ParseConfigJsonResult,
46
47
  type PortForward,
48
+ type ProfileEntry,
47
49
  type ResolvedProfile,
50
+ type ThinkingLevel,
48
51
  type ValidateConfigResult,
49
52
  } from './config'
50
53
  export { type KnownModelRef, type KnownProviderId, type ModelRef } from './providers'
@@ -3,7 +3,13 @@ import { join } from 'node:path'
3
3
 
4
4
  import { commitSystemFileSync } from '@/git/system-commit'
5
5
 
6
- import { configSchema, loadConfigSyncOrDefaults, validateConfig, type CustomModelMeta } from './config'
6
+ import {
7
+ configSchema,
8
+ loadConfigSyncOrDefaults,
9
+ validateConfig,
10
+ type CustomModelMeta,
11
+ type ThinkingLevel,
12
+ } from './config'
7
13
  import {
8
14
  KNOWN_PROVIDERS,
9
15
  isKnownModelRef,
@@ -25,6 +31,9 @@ export type ModelProfileEntry = {
25
31
  // dereference `refs[0]`. The chain itself is exposed as `refs`.
26
32
  ref: ModelRef
27
33
  refs: ModelRef[]
34
+ // The profile's own reasoning-effort override, or undefined when it inherits
35
+ // the `default` profile's level (which is itself the de-facto global default).
36
+ thinkingLevel?: ThinkingLevel
28
37
  providerId: KnownProviderId
29
38
  // Credential status for every provider referenced by the chain. The chain's
30
39
  // overall status is `available` only when every entry resolves; otherwise
@@ -47,14 +56,15 @@ export type ModelMutationResult = { ok: true } | { ok: false; reason: string }
47
56
  export function listModelProfiles(cwd: string, env: NodeJS.ProcessEnv = process.env): ModelProfileEntry[] {
48
57
  const models = loadConfigSyncOrDefaults(cwd).models
49
58
  const out: ModelProfileEntry[] = []
50
- for (const [profile, refs] of Object.entries(models)) {
51
- const headRef = refs[0]!
59
+ for (const [profile, entry] of Object.entries(models)) {
60
+ const headRef = entry.refs[0]!
52
61
  const providerId = providerForModelRef(headRef)
53
- const missingProviders = uniqueProviders(refs).filter((p) => !hasUsableCredential(cwd, p, env))
62
+ const missingProviders = uniqueProviders(entry.refs).filter((p) => !hasUsableCredential(cwd, p, env))
54
63
  out.push({
55
64
  profile,
56
65
  ref: headRef,
57
- refs,
66
+ refs: entry.refs,
67
+ ...(entry.thinkingLevel !== undefined ? { thinkingLevel: entry.thinkingLevel } : {}),
58
68
  providerId,
59
69
  missingProviders,
60
70
  isDefault: profile === 'default',
@@ -117,6 +127,12 @@ export type SetProfileOptions = {
117
127
  force?: boolean
118
128
  env?: NodeJS.ProcessEnv
119
129
  meta?: CustomModelMeta
130
+ // Present key = write this reasoning effort alongside the ref (an explicit
131
+ // `undefined` clears any existing level). Omit the key entirely to leave an
132
+ // existing per-profile level untouched. `setProfile` distinguishes the two
133
+ // via `Object.hasOwn`, so `{ thinkingLevel: undefined }` is a clear, not a
134
+ // no-op.
135
+ thinkingLevel?: ThinkingLevel
120
136
  }
121
137
 
122
138
  export function setProfile(
@@ -146,7 +162,13 @@ export function setProfile(
146
162
  const existingBefore = readModelsRaw(cwd)
147
163
  const verb = existingBefore !== null && trimmed in existingBefore ? 'set' : 'add'
148
164
  const customModel = !isKnownModelRef(ref) && options.meta !== undefined ? { ref, meta: options.meta } : undefined
149
- return writeProfile(cwd, trimmed, ref, `model: ${verb} ${trimmed} → ${ref}`, customModel)
165
+ // An explicit `thinkingLevel` key (even `undefined`) overrides the existing
166
+ // level; an omitted key preserves it. Pass the override as a single-element
167
+ // tuple so `writeProfile` can tell "clear to undefined" from "don't touch".
168
+ const thinkingOverride: [ThinkingLevel | undefined] | undefined = Object.hasOwn(options, 'thinkingLevel')
169
+ ? [options.thinkingLevel]
170
+ : undefined
171
+ return writeProfile(cwd, trimmed, ref, `model: ${verb} ${trimmed} → ${ref}`, customModel, thinkingOverride)
150
172
  }
151
173
 
152
174
  // `add` is just `set` with a uniqueness guard; users who want "update" should
@@ -192,15 +214,61 @@ export function removeProfile(cwd: string, profile: string): ModelMutationResult
192
214
  return writeModels(cwd, next, `model: remove ${profile}`)
193
215
  }
194
216
 
217
+ // Sets (or clears) a profile's reasoning effort without touching its refs.
218
+ // `undefined` collapses the profile back to its bare string/array ref form.
219
+ // The `default` profile's level is the de-facto global default, so
220
+ // `setProfileThinkingLevel(cwd, 'default', level)` is the "global" knob.
221
+ // Rejects a profile that doesn't exist yet — the user must set its model first.
222
+ export function setProfileThinkingLevel(
223
+ cwd: string,
224
+ profile: string,
225
+ level: ThinkingLevel | undefined,
226
+ ): ModelMutationResult {
227
+ const trimmed = profile.trim()
228
+ if (trimmed.length === 0) {
229
+ return { ok: false, reason: 'Profile name cannot be empty.' }
230
+ }
231
+ const existing = readModelsRaw(cwd)
232
+ if (existing === null) {
233
+ return { ok: false, reason: `${CONFIG_FILE} not found at ${cwd}. Run \`typeclaw init\` first.` }
234
+ }
235
+ const current = existing[trimmed]
236
+ if (current === undefined) {
237
+ return {
238
+ ok: false,
239
+ reason: `Profile "${trimmed}" not found. Run \`typeclaw model set ${trimmed} <ref>\` to create it first.`,
240
+ }
241
+ }
242
+ const refs = rawProfileRefs(current)
243
+ if (refs === undefined) {
244
+ return { ok: false, reason: `Profile "${trimmed}" has no model to attach a thinking level to.` }
245
+ }
246
+ const next: RawModels = { ...existing, [trimmed]: withRawProfileThinkingLevel(refs, level) }
247
+ const message =
248
+ level === undefined
249
+ ? `model: clear thinkingLevel for ${trimmed}`
250
+ : `model: set thinkingLevel ${level} for ${trimmed}`
251
+ return writeModels(cwd, next, message)
252
+ }
253
+
195
254
  function writeProfile(
196
255
  cwd: string,
197
256
  profile: string,
198
257
  ref: ModelRef,
199
258
  message: string,
200
259
  customModel?: { ref: ModelRef; meta: CustomModelMeta },
260
+ // `[level]` overrides (a wrapped `undefined` clears); `undefined` preserves
261
+ // the existing level. The tuple is what lets an explicit clear win over a
262
+ // pre-existing level instead of being swallowed by `??`.
263
+ thinkingOverride?: [ThinkingLevel | undefined],
201
264
  ): ModelMutationResult {
202
265
  const existing = readModelsRaw(cwd)
203
- const next: Record<string, string | string[]> = existing === null ? { default: ref } : { ...existing, [profile]: ref }
266
+ // Setting refs keeps a bare ref bare; it only becomes a rich object once a
267
+ // thinkingLevel is present. An override replaces the level (including a clear
268
+ // to undefined); otherwise the existing per-profile level is preserved.
269
+ const level = thinkingOverride !== undefined ? thinkingOverride[0] : rawProfileThinkingLevel(existing?.[profile])
270
+ const value = withRawProfileThinkingLevel(ref, level)
271
+ const next: RawModels = existing === null ? { default: value } : { ...existing, [profile]: value }
204
272
  if (existing === null && profile !== 'default') {
205
273
  next.default = ref
206
274
  }
@@ -209,7 +277,7 @@ function writeProfile(
209
277
 
210
278
  function writeModels(
211
279
  cwd: string,
212
- models: Record<string, string | string[]>,
280
+ models: RawModels,
213
281
  commitMessage: string,
214
282
  customModel?: { ref: ModelRef; meta: CustomModelMeta },
215
283
  ): ModelMutationResult {
@@ -262,15 +330,37 @@ function isObjectRecord(value: unknown): value is Record<string, unknown> {
262
330
  return typeof value === 'object' && value !== null && !Array.isArray(value)
263
331
  }
264
332
 
265
- // Returns the raw `models` block from disk in its on-disk shape: each value
266
- // is `string | string[]` (the user-facing schema). Writers preserve whichever
267
- // shape was already present for profiles they don't touch — converting a
268
- // hand-authored fallback chain back to a single string would silently drop
269
- // the fallback.
270
- function readModelsRaw(cwd: string): Record<string, string | string[]> | null {
333
+ // The on-disk shape of a single `models.<profile>` value: a bare ref string, a
334
+ // fallback-chain array, or a rich object carrying a per-profile thinkingLevel.
335
+ // Mutators read-modify-write this shape so they preserve whichever form the
336
+ // user hand-authored (and the sibling field they aren't touching).
337
+ type RawProfileValue = string | string[] | { model?: string; models?: string | string[]; thinkingLevel?: ThinkingLevel }
338
+ type RawModels = Record<string, RawProfileValue>
339
+
340
+ function rawProfileRefs(value: RawProfileValue | undefined): string | string[] | undefined {
341
+ if (value === undefined) return undefined
342
+ if (typeof value === 'string' || Array.isArray(value)) return value
343
+ return value.models ?? value.model
344
+ }
345
+
346
+ function rawProfileThinkingLevel(value: RawProfileValue | undefined): ThinkingLevel | undefined {
347
+ return value !== undefined && typeof value === 'object' && !Array.isArray(value) ? value.thinkingLevel : undefined
348
+ }
349
+
350
+ // Re-attaches a thinkingLevel to a ref/chain, collapsing back to the bare
351
+ // string/array form when there's no level so configs stay minimal.
352
+ function withRawProfileThinkingLevel(refs: string | string[], level: ThinkingLevel | undefined): RawProfileValue {
353
+ return level === undefined ? refs : { models: refs, thinkingLevel: level }
354
+ }
355
+
356
+ // Returns the raw `models` block from disk in its on-disk shape. Writers
357
+ // preserve whichever shape was already present for profiles they don't touch —
358
+ // converting a hand-authored fallback chain back to a single string, or
359
+ // dropping a per-profile thinkingLevel, would silently lose user intent.
360
+ function readModelsRaw(cwd: string): RawModels | null {
271
361
  try {
272
362
  const raw = readFileSync(join(cwd, CONFIG_FILE), 'utf8')
273
- const parsed = JSON.parse(raw) as { models?: Record<string, string | string[]> }
363
+ const parsed = JSON.parse(raw) as { models?: RawModels }
274
364
  return parsed.models ?? null
275
365
  } catch (error) {
276
366
  if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
@@ -136,8 +136,8 @@ export function findModelsReferencingProvider(cwd: string, providerId: string):
136
136
  const models = readModelsOrNull(cwd)
137
137
  if (models === null) return []
138
138
  const out: string[] = []
139
- for (const [profile, refs] of Object.entries(models)) {
140
- if (refs.some((r) => refTargetsProvider(r, providerId))) out.push(profile)
139
+ for (const [profile, entry] of Object.entries(models)) {
140
+ if (entry.refs.some((r) => refTargetsProvider(r, providerId))) out.push(profile)
141
141
  }
142
142
  return out
143
143
  }
@@ -212,8 +212,8 @@ function readEnvKey(env: NodeJS.ProcessEnv, key: string): string | undefined {
212
212
  function buildProviderReferenceMap(models: Models | null): Map<string, string[]> {
213
213
  const out = new Map<string, string[]>()
214
214
  if (models === null) return out
215
- for (const [profile, refs] of Object.entries(models)) {
216
- for (const ref of refs) {
215
+ for (const [profile, entry] of Object.entries(models)) {
216
+ for (const ref of entry.refs) {
217
217
  const providerId = safeProviderForRef(ref)
218
218
  if (providerId === null) continue
219
219
  const existing = out.get(providerId) ?? []
@@ -1,3 +1,4 @@
1
+ import type { ThinkingLevel } from '@mariozechner/pi-agent-core'
1
2
  import type { KnownApi, Model } from '@mariozechner/pi-ai'
2
3
 
3
4
  // Authentication mechanism a provider supports. `api-key` reads a static key
@@ -979,24 +980,15 @@ function knownProviderForModelRef(ref: string): KnownProviderId | null {
979
980
  return null
980
981
  }
981
982
 
982
- // Per-provider default for pi-coding-agent's `thinkingLevel` knob. Returning
983
- // `undefined` defers to the SDK default (`medium`); returning a level pins it
984
- // to that value at session-creation time.
985
- //
986
- // OpenAI-family providers (`openai`, `openai-codex`) pin to `low`: GPT-5.x at
987
- // `medium` pads reasoning tokens on routine tool-driven turns (code edits,
988
- // channel replies, cron prompts) with no observable quality delta on this
989
- // codebase's workloads. Applies to every session that resolves to a GPT model
990
- // regardless of profile, so the saving is uniform.
991
- //
992
- // Anthropic, GLM, and Kimi don't share the padding behavior, so they keep the
993
- // SDK default.
994
983
  export function isOpenAiFamilyRef(ref: KnownModelRef | ModelRef | string): boolean {
995
984
  return vendorForProviderId(providerForModelRef(ref)) === 'openai'
996
985
  }
997
986
 
998
- export function defaultThinkingLevelForRef(ref: KnownModelRef | ModelRef | string): 'low' | undefined {
999
- if (isOpenAiFamilyRef(ref)) return 'low'
987
+ // Returning `undefined` defers to pi-coding-agent's SDK default (`medium`);
988
+ // returning a level pins it at session-creation time. No family is pinned: the
989
+ // prior OpenAI `low` pin was dropped so GPT-5.x reasons at SDK strength like
990
+ // every other vendor.
991
+ export function defaultThinkingLevelForRef(_ref: KnownModelRef | ModelRef | string): ThinkingLevel | undefined {
1000
992
  return undefined
1001
993
  }
1002
994