typeclaw 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +4 -0
  2. package/auth.schema.json +109 -0
  3. package/package.json +2 -2
  4. package/secrets.schema.json +109 -0
  5. package/src/agent/attention-escalation.ts +4 -3
  6. package/src/agent/auth.ts +2 -2
  7. package/src/agent/index.ts +25 -2
  8. package/src/agent/restart/index.ts +17 -8
  9. package/src/agent/session-origin.ts +15 -2
  10. package/src/agent/subagents.ts +29 -1
  11. package/src/agent/system-prompt.ts +18 -5
  12. package/src/agent/tools/restart.ts +0 -3
  13. package/src/agent/tools/spawn-subagent.ts +7 -0
  14. package/src/bundled-plugins/memory/README.md +12 -1
  15. package/src/bundled-plugins/memory/index.ts +63 -8
  16. package/src/bundled-plugins/memory/memory-logger.ts +14 -10
  17. package/src/bundled-plugins/operator/operator.ts +1 -0
  18. package/src/channels/adapters/kakaotalk.ts +1 -1
  19. package/src/channels/adapters/webex-bot-classify.ts +20 -14
  20. package/src/channels/adapters/webex-bot-reference.ts +8 -6
  21. package/src/channels/adapters/webex-bot.ts +106 -39
  22. package/src/channels/adapters/webex-channel-resolver.ts +29 -0
  23. package/src/channels/adapters/webex-classify.ts +104 -0
  24. package/src/channels/adapters/webex-format.ts +53 -0
  25. package/src/channels/adapters/webex-id-ref.ts +32 -0
  26. package/src/channels/adapters/webex-reference.ts +49 -0
  27. package/src/channels/adapters/webex.ts +493 -0
  28. package/src/channels/manager.ts +63 -7
  29. package/src/channels/persistence.ts +67 -5
  30. package/src/channels/router.ts +8 -0
  31. package/src/channels/schema.ts +2 -0
  32. package/src/cli/channel.ts +118 -7
  33. package/src/cli/init.ts +70 -1
  34. package/src/cli/model.ts +143 -3
  35. package/src/config/channels-mutation.ts +2 -1
  36. package/src/config/config.ts +94 -31
  37. package/src/config/index.ts +3 -0
  38. package/src/config/models-mutation.ts +105 -15
  39. package/src/config/providers-mutation.ts +4 -4
  40. package/src/config/providers.ts +6 -14
  41. package/src/container/shared.ts +21 -0
  42. package/src/container/start.ts +25 -7
  43. package/src/doctor/channel-checks.ts +43 -0
  44. package/src/hostd/daemon.ts +7 -5
  45. package/src/hostd/index.ts +1 -11
  46. package/src/hostd/paths.ts +0 -16
  47. package/src/hostd/protocol.ts +2 -2
  48. package/src/init/checkpoint.ts +1 -1
  49. package/src/init/index.ts +60 -3
  50. package/src/init/run-owner-claim.ts +1 -0
  51. package/src/init/webex-auth.ts +68 -0
  52. package/src/inspect/label.ts +13 -2
  53. package/src/inspect/render.ts +5 -3
  54. package/src/permissions/resolve.ts +38 -1
  55. package/src/role-claim/match-rule.ts +5 -1
  56. package/src/run/index.ts +4 -1
  57. package/src/secrets/codex-auth-json.ts +52 -17
  58. package/src/secrets/encryption.ts +5 -1
  59. package/src/secrets/export-codex-auth-file.ts +26 -3
  60. package/src/secrets/schema.ts +35 -0
  61. package/src/secrets/webex-store.ts +113 -0
  62. package/src/skills/typeclaw-config/SKILL.md +18 -16
  63. package/typeclaw.schema.json +326 -0
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)
@@ -11,6 +11,7 @@ export const CHANNEL_KINDS = [
11
11
  'slack-bot',
12
12
  'discord-bot',
13
13
  'telegram-bot',
14
+ 'webex',
14
15
  'webex-bot',
15
16
  'line',
16
17
  'kakaotalk',
@@ -186,7 +187,7 @@ function buildDetail(kind: ChannelKind, channelConfig: unknown, secretsBlock: un
186
187
  const repos = isObjectRecord(channelConfig) && Array.isArray(channelConfig.repos) ? channelConfig.repos.length : 0
187
188
  return { detail: `${repos} repo${repos === 1 ? '' : 's'}` }
188
189
  }
189
- if (kind === 'line' || kind === 'kakaotalk') {
190
+ if (kind === 'line' || kind === 'kakaotalk' || kind === 'webex') {
190
191
  if (!isObjectRecord(secretsBlock)) return {}
191
192
  const accounts = isObjectRecord(secretsBlock.accounts) ? Object.keys(secretsBlock.accounts).length : 0
192
193
  const current = typeof secretsBlock.currentAccount === 'string' ? secretsBlock.currentAccount : undefined
@@ -636,30 +636,75 @@ function asModelRef(value: string): ModelRef {
636
636
  // level. `migrateLegacyConfigShape` rewrites that to `models: { default: ... }`
637
637
  // on first load (and writes the result back to disk + commits via
638
638
  // `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)))
639
+ // Mirrors pi-coding-agent's `ThinkingLevel`. Kept as a local enum (rather than
640
+ // importing the SDK type) so the schema owns the canonical value list and zod
641
+ // can validate `typeclaw.json` without a runtime SDK dependency.
642
+ export const thinkingLevelSchema = z.enum(['off', 'minimal', 'low', 'medium', 'high', 'xhigh'])
643
+ export type ThinkingLevel = z.infer<typeof thinkingLevelSchema>
644
+
645
+ // Reject exact duplicates in a chain — retrying the same ref after the same
646
+ // class of failure is almost certainly a config typo, and silently deduping
647
+ // would mask user intent. Different models from the same provider (e.g.
648
+ // `["openai/gpt-5.4-nano", "openai/gpt-5.4-mini"]`) are still valid because
649
+ // they hit distinct upstream endpoints.
650
+ const noDuplicateChainRefs = (arr: readonly string[]): boolean => new Set(arr).size === arr.length
651
+ const chainRefinementMessage = { message: 'models chain must not contain duplicate refs' }
652
+ const modelChainInputSchema = z.array(singleModelRef).min(1).refine(noDuplicateChainRefs, chainRefinementMessage)
653
+
654
+ // A profile value is one of three shapes, all normalised to `ProfileEntry`:
655
+ // "openai/gpt-5.4-nano" single ref
656
+ // ["refA", "refB"] fallback chain
657
+ // { models: "refA" | ["refA","refB"], thinkingLevel? } rich object
658
+ // The rich object couples a per-profile `thinkingLevel` to the model(s); the
659
+ // `models` key mirrors the top-level map name and reads naturally for both a
660
+ // single ref and a chain. `model` is accepted as single-ref sugar but exactly
661
+ // one of `model`/`models` may be present. Legacy string/array forms keep
662
+ // parsing untouched (they normalise to `{ refs, thinkingLevel: undefined }`),
663
+ // so no migration is needed.
664
+ const richProfileSchema = z
665
+ .object({
666
+ model: singleModelRef.optional(),
667
+ models: z.union([singleModelRef, modelChainInputSchema]).optional(),
668
+ thinkingLevel: thinkingLevelSchema.optional(),
669
+ })
670
+ .strict()
671
+ .superRefine((value, ctx) => {
672
+ if (value.model === undefined && value.models === undefined) {
673
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'profile must specify `model` or `models`' })
674
+ }
675
+ if (value.model !== undefined && value.models !== undefined) {
676
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'profile must specify only one of `model` or `models`' })
677
+ }
678
+ })
679
+
680
+ const profileEntrySchema = z
681
+ .union([singleModelRef, modelChainInputSchema, richProfileSchema])
682
+ .transform((value): ProfileEntry => {
683
+ if (typeof value === 'string' || Array.isArray(value)) {
684
+ const refs = (Array.isArray(value) ? value : [value]).map((ref) => asModelRef(ref))
685
+ return { refs }
686
+ }
687
+ const refsInput = value.models ?? value.model!
688
+ const refs = (Array.isArray(refsInput) ? refsInput : [refsInput]).map((ref) => asModelRef(ref))
689
+ return value.thinkingLevel === undefined ? { refs } : { refs, thinkingLevel: value.thinkingLevel }
690
+ })
691
+
655
692
  export const modelsSchema = z
656
- .record(z.string().min(1), modelRefOrChainSchema)
693
+ .record(z.string().min(1), profileEntrySchema)
657
694
  .refine((m) => 'default' in m, { message: 'models.default is required' })
658
695
 
696
+ // A model profile after normalisation: its fallback chain (always non-empty)
697
+ // plus an optional reasoning effort. `thinkingLevel` resolution is layered at
698
+ // session creation: profile's own → `default` profile's → SDK default.
699
+ export type ProfileEntry = {
700
+ refs: ModelRef[]
701
+ thinkingLevel?: ThinkingLevel
702
+ }
703
+
659
704
  // Zod's `z.record(..., refine)` doesn't refine the inferred type. The
660
705
  // `default` key is schema-enforced, so we narrow it here to spare every
661
706
  // consumer the `T | undefined` assertion noise.
662
- export type Models = Record<string, ModelRef[]> & { default: ModelRef[] }
707
+ export type Models = Record<string, ProfileEntry> & { default: ProfileEntry }
663
708
 
664
709
  export const configSchema = z
665
710
  .object({
@@ -668,9 +713,11 @@ export const configSchema = z
668
713
  // `default(() => ...)` ensures every parsed config has at least
669
714
  // `models.default`. Direct `.default({ default: ... })` would short-circuit
670
715
  // 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>,
716
+ // shaped to match the post-transform output (a `ProfileEntry`), not the
717
+ // user-facing input shape.
718
+ models: modelsSchema.default(() => ({
719
+ default: { refs: [asModelRef(DEFAULT_MODEL_REF)] },
720
+ })) as unknown as z.ZodType<Models>,
674
721
  customModels: customModelsSchema,
675
722
  // Defaults to `[]` so the field can be omitted from `typeclaw.json` (no
676
723
  // host paths exposed) without failing the whole config load. `typeclaw
@@ -754,27 +801,43 @@ function resolveCustomModelCost(cost: CustomModelMeta['cost']): Model<KnownApi>[
754
801
  }
755
802
 
756
803
  // 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`.
804
+ // chain and per-profile thinking level. Unknown profiles fall back to
805
+ // `default` so callers can pass through arbitrary subagent-declared or
806
+ // user-overridden strings without crashing. `refs` is non-empty (the schema
807
+ // guarantees `default` exists and every value is at least one ref). `ref` is
808
+ // the head of the chain — the model the session is created with first.
809
+ // Callers that don't implement fallback can keep reading `ref`; fallback-aware
810
+ // callers iterate `refs`. `thinkingLevel` is the profile's own override (may be
811
+ // undefined, meaning inherit the `default` profile's level — see session
812
+ // creation).
763
813
  export type ResolvedProfile = {
764
814
  ref: ModelRef
765
815
  refs: ModelRef[]
816
+ thinkingLevel?: ThinkingLevel
766
817
  profile: string
767
818
  fellBackToDefault: boolean
768
819
  }
769
820
 
770
821
  export function resolveProfile(models: Models, name: string | undefined): ResolvedProfile {
771
822
  const requested = name ?? 'default'
772
- const refs = models[requested]
773
- if (refs !== undefined) {
774
- return { ref: refs[0]!, refs, profile: requested, fellBackToDefault: false }
823
+ const entry = models[requested]
824
+ if (entry !== undefined) {
825
+ return {
826
+ ref: entry.refs[0]!,
827
+ refs: entry.refs,
828
+ thinkingLevel: entry.thinkingLevel,
829
+ profile: requested,
830
+ fellBackToDefault: false,
831
+ }
775
832
  }
776
833
  const fallback = models.default
777
- return { ref: fallback[0]!, refs: fallback, profile: 'default', fellBackToDefault: true }
834
+ return {
835
+ ref: fallback.refs[0]!,
836
+ refs: fallback.refs,
837
+ thinkingLevel: fallback.thinkingLevel,
838
+ profile: 'default',
839
+ fellBackToDefault: true,
840
+ }
778
841
  }
779
842
 
780
843
  // 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