typeclaw 0.48.12 → 0.48.13

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 (57) hide show
  1. package/package.json +6 -3
  2. package/src/agent/attention-escalation.ts +8 -5
  3. package/src/agent/auth-reloadable.ts +2 -3
  4. package/src/agent/auth.ts +59 -79
  5. package/src/agent/compaction.ts +2 -2
  6. package/src/agent/index.ts +31 -15
  7. package/src/agent/llm-replay-sanitizer.ts +1 -1
  8. package/src/agent/model-overrides.ts +1 -1
  9. package/src/agent/multimodal/look-at.ts +3 -3
  10. package/src/agent/multimodal/read-redirect.ts +1 -1
  11. package/src/agent/plugin-tools.ts +26 -31
  12. package/src/agent/reload-tool.ts +1 -1
  13. package/src/agent/subagents.ts +1 -1
  14. package/src/agent/tool-error-remediation.ts +1 -1
  15. package/src/agent/tool-result-budget.ts +2 -2
  16. package/src/agent/tools/channel-disengage.ts +2 -2
  17. package/src/agent/tools/channel-edit.ts +2 -2
  18. package/src/agent/tools/channel-fetch-attachment.ts +2 -2
  19. package/src/agent/tools/channel-history.ts +2 -2
  20. package/src/agent/tools/channel-react.ts +2 -2
  21. package/src/agent/tools/channel-read.ts +2 -2
  22. package/src/agent/tools/channel-reply.ts +2 -2
  23. package/src/agent/tools/channel-send.ts +2 -2
  24. package/src/agent/tools/grant-role.ts +2 -2
  25. package/src/agent/tools/post-github-review.ts +2 -2
  26. package/src/agent/tools/restart.ts +2 -2
  27. package/src/agent/tools/skip-response.ts +2 -2
  28. package/src/agent/tools/spawn-subagent.ts +2 -2
  29. package/src/agent/tools/stream-snapshot.ts +2 -2
  30. package/src/agent/tools/subagent-cancel.ts +2 -2
  31. package/src/agent/tools/subagent-output.ts +2 -2
  32. package/src/agent/tools/todo/index.ts +2 -2
  33. package/src/agent/tools/webfetch/tool.ts +2 -2
  34. package/src/agent/tools/websearch.ts +2 -2
  35. package/src/channels/github-review-verdict-coordinator.ts +26 -3
  36. package/src/channels/router.ts +50 -25
  37. package/src/cli/model.ts +7 -5
  38. package/src/cli/oauth-callbacks.ts +38 -23
  39. package/src/config/config.ts +62 -25
  40. package/src/config/providers.ts +272 -47
  41. package/src/init/index.ts +4 -4
  42. package/src/init/oauth-login.ts +57 -17
  43. package/src/inspect/transcript-view.ts +6 -3
  44. package/src/run/channel-session-factory.ts +5 -4
  45. package/src/run/index.ts +11 -11
  46. package/src/secrets/refresh-provider-oauth.ts +30 -76
  47. package/src/secrets/schema.ts +3 -4
  48. package/src/secrets/storage.ts +133 -234
  49. package/src/server/index.ts +1 -1
  50. package/src/sessions/index.ts +1 -1
  51. package/src/skills/typeclaw-config/SKILL.md +4 -4
  52. package/src/skills/typeclaw-plugins/SKILL.md +5 -5
  53. package/src/tui/index.ts +5 -3
  54. package/src/tui/theme.ts +1 -1
  55. package/typeclaw.schema.json +32 -1
  56. package/src/agent/adaptive-thinking-compat.ts +0 -79
  57. package/src/secrets/oauth-xai.ts +0 -348
package/src/run/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { join } from 'node:path'
2
2
 
3
- import { SessionManager } from '@mariozechner/pi-coding-agent'
3
+ import { SessionManager } from '@earendil-works/pi-coding-agent'
4
4
 
5
5
  import { createSession, createSessionWithDispose } from '@/agent'
6
6
  import { createProviderAuthReloadable } from '@/agent/auth-reloadable'
@@ -410,15 +410,15 @@ async function startAgentRuntime(
410
410
  //
411
411
  // MUST be awaited, and MUST run before the credential-file exporters below
412
412
  // and the first session-producing consumer (subagentConsumer.start /
413
- // cronConsumer.start / channelManager.start / the websocket server). The SDK
414
- // refresh holds SecretsBackend's async file lock across its network request;
415
- // getAuthFor()'s synchronous lock read gives up after ~200ms and
416
- // process.exit(1)s on ELOCKED. Fire-and-forget here would let a slow refresh
417
- // still own the lock when an exporter or consumer reads secrets — worse than
418
- // the lazy path. Awaiting behind this barrier guarantees no synchronous auth
419
- // reader exists while the refresh owns the lock. Never throws (the wrapper
420
- // swallows and logs), so a probe failure can't block boot; a refresh that
421
- // hangs on a wedged network hangs the first turn today anyway.
413
+ // cronConsumer.start / channelManager.start / the websocket server). The
414
+ // refresh holds SecretsBackend's file lock across its network request
415
+ // (`CredentialStore.modify`), while the synchronous readers the exporters and
416
+ // channel hydration use give up after ~200ms and throw ELOCKED.
417
+ // Fire-and-forget here would let a slow refresh still own the lock when an
418
+ // exporter or consumer reads secrets — worse than the lazy path. Awaiting
419
+ // behind this barrier guarantees no synchronous reader races the refresh.
420
+ // Never throws (the wrapper swallows and logs), so a probe failure can't block
421
+ // boot; a refresh that hangs on a wedged network hangs the first turn anyway.
422
422
  await refreshProviderOAuth({
423
423
  agentDir: cwd,
424
424
  log: (message) => console.warn(message),
@@ -898,7 +898,7 @@ async function startAgentRuntime(
898
898
  // session teardown observes it. secrets.json provider credentials are not
899
899
  // part of the typeclaw.json config diff, so a rotated key takes effect on
900
900
  // `typeclaw reload` only via this dedicated scope. Live sessions captured
901
- // their AuthStorage at creation, so teardown recreates them with fresh auth.
901
+ // their ModelRuntime at creation, so teardown recreates them with fresh auth.
902
902
  reloadRegistry.register(
903
903
  createProviderAuthReloadable({
904
904
  onProviderAuthChanged: () => channelManager.router.tearDownAllLive(),
@@ -1,6 +1,7 @@
1
1
  import { join } from 'node:path'
2
2
 
3
- import type { AuthStorage } from '@mariozechner/pi-coding-agent'
3
+ import type { CredentialStore } from '@earendil-works/pi-ai'
4
+ import { ModelRuntime } from '@earendil-works/pi-coding-agent'
4
5
 
5
6
  import { createSecretsStoreForAgent } from './storage'
6
7
 
@@ -15,9 +16,8 @@ export type ProviderRefreshOutcome = 'valid-or-refreshed' | 'refresh-failed'
15
16
  export type ProviderRefreshEntry = {
16
17
  providerId: string
17
18
  outcome: ProviderRefreshOutcome
18
- // Populated only for `refresh-failed`, drained from AuthStorage's internal
19
- // error log so operators see WHY the refresh failed (network, 400 from the
20
- // token endpoint, revoked refresh token, unknown OAuth provider).
19
+ // ModelRuntime returns the refresh rejection directly. This field is the
20
+ // operator-visible reason; there is no process-global error queue.
21
21
  error?: string
22
22
  }
23
23
 
@@ -26,103 +26,57 @@ export type RefreshProviderOAuthResult = {
26
26
  }
27
27
 
28
28
  export type RefreshProviderOAuthOptions = {
29
- authStorage: AuthStorage
29
+ modelRuntime: ModelRuntime
30
+ credentials: CredentialStore
30
31
  log?: (message: string) => void
31
32
  }
32
33
 
33
- // Proactively resolves every stored OAuth provider credential once, forcing the
34
- // SDK's lazy refresh-and-persist path to run at boot instead of on the first
35
- // user-facing turn.
36
- //
37
- // WHY THIS EXISTS. `AuthStorage.getApiKey()` is the SDK's only refresh trigger,
38
- // and it is lazy: it fires on the first LLM call for a provider. A container
39
- // that restarts with an already-expired access token therefore doesn't refresh
40
- // until a real turn runs — and if that refresh then fails (a wedged network
41
- // stack, a rotated refresh token), the failure surfaces as a generic
42
- // provider-error notice posted into a live channel/PR thread. Channel-adapter
43
- // OAuth already has host-side renewal crons (Kakao/Webex/Teams); provider OAuth
44
- // had nothing. This closes that gap by paying the refresh cost at boot, where a
45
- // failure is logged for the operator rather than shown to end users.
46
- //
47
- // Reuses the SDK path verbatim rather than re-implementing token refresh: a
48
- // single `getApiKey()` call per provider runs the exact locked
49
- // refresh-then-persist-to-secrets.json flow the runtime uses on every turn, so
50
- // a boot-refreshed token is written back through the same atomic writer and no
51
- // second refresh implementation can drift from it. `includeFallback: false`
52
- // keeps an unrelated env var from masking an OAuth refresh failure as success.
53
- //
54
- // Never throws: a boot-time credential probe must not block the agent from
55
- // starting. Each provider is isolated — one provider's failure doesn't stop the
56
- // others from being probed — and every failure is returned for the caller to
57
- // log.
34
+ // Container-stage boot probe: ModelRuntime owns signal-aware OAuth refresh and
35
+ // runs it inside CredentialStore.modify, so this shares the exact live-request
36
+ // lock/persist path without reimplementing provider token exchange.
58
37
  export async function refreshProviderOAuthCredentials(
59
38
  options: RefreshProviderOAuthOptions,
60
39
  ): Promise<RefreshProviderOAuthResult> {
61
- const { authStorage } = options
62
40
  const entries: ProviderRefreshEntry[] = []
41
+ const credentials = await options.credentials.list()
63
42
 
64
- const oauthProviderIds = Object.entries(authStorage.getAll())
65
- .filter(([, cred]) => cred.type === 'oauth')
66
- .map(([providerId]) => providerId)
67
-
68
- for (const providerId of oauthProviderIds) {
69
- // getApiKey drives the locked refresh-and-persist internally. A non-empty
70
- // return means the provider can serve a turn now (token was valid, or was
71
- // expired and got refreshed + written back). `undefined` means the refresh
72
- // truly failed — the SDK deliberately does NOT fall back to the stale token.
73
- const apiKey = await resolveApiKeySafely(authStorage, providerId)
74
- // Always drain so one provider's recorded error can't leak into the next
75
- // provider's outcome. drainErrors clears the buffer as it reads.
76
- const drained = authStorage.drainErrors()
77
-
78
- if (apiKey !== undefined && apiKey !== '') {
79
- entries.push({ providerId, outcome: 'valid-or-refreshed' })
80
- continue
43
+ for (const credential of credentials) {
44
+ if (credential.type !== 'oauth') continue
45
+ try {
46
+ const auth = await options.modelRuntime.getAuth(credential.providerId)
47
+ if (!auth?.auth.apiKey) throw new Error('refresh returned no API key')
48
+ entries.push({ providerId: credential.providerId, outcome: 'valid-or-refreshed' })
49
+ } catch (error) {
50
+ const reason = error instanceof Error ? error.message : String(error)
51
+ options.log?.(`refreshProviderOAuth: ${credential.providerId} refresh failed: ${reason}`)
52
+ entries.push({ providerId: credential.providerId, outcome: 'refresh-failed', error: reason })
81
53
  }
82
-
83
- const error = drained.length > 0 ? drained.map((e) => e.message).join('; ') : 'refresh returned no API key'
84
- options.log?.(`refreshProviderOAuth: ${providerId} refresh failed: ${error}`)
85
- entries.push({ providerId, outcome: 'refresh-failed', error })
86
54
  }
87
-
88
55
  return { entries }
89
56
  }
90
57
 
91
- // getApiKey already swallows refresh errors into drainErrors and returns
92
- // undefined, but guard the call itself so an unexpected throw (e.g. a corrupt
93
- // credential shape the SDK doesn't expect) degrades to a failed entry instead
94
- // of aborting the whole boot-time sweep.
95
- async function resolveApiKeySafely(authStorage: AuthStorage, providerId: string): Promise<string | undefined> {
96
- try {
97
- return await authStorage.getApiKey(providerId, { includeFallback: false })
98
- } catch {
99
- return undefined
100
- }
101
- }
102
-
103
58
  export type RefreshProviderOAuthForAgentOptions = {
104
59
  agentDir: string
105
60
  log?: (message: string) => void
106
61
  }
107
62
 
108
- // Boot-time convenience wrapper for src/run/index.ts, mirroring
109
- // exportCodexAuthFileForAgent's contract: takes agentDir, never throws, returns
110
- // a result the caller can log or ignore. Builds the same AuthStorage the run
111
- // stage uses per provider (createSecretsStoreForAgent) so the refresh writes
112
- // back through the bind-mounted secrets.json exactly as a live turn would.
63
+ // Container-stage convenience wrapper. Host CLI never calls this path; it
64
+ // reads the bind-mounted v2 envelope and asks ModelRuntime to refresh before
65
+ // the first user turn.
113
66
  export async function refreshProviderOAuthForAgent(
114
67
  options: RefreshProviderOAuthForAgentOptions,
115
68
  ): Promise<RefreshProviderOAuthResult> {
116
- let authStorage: AuthStorage
117
69
  try {
118
- authStorage = createSecretsStoreForAgent(join(options.agentDir, 'secrets.json'))
70
+ const credentials = createSecretsStoreForAgent(join(options.agentDir, 'secrets.json'))
71
+ const modelRuntime = await ModelRuntime.create({ credentials, modelsPath: null, refreshOnCreate: false })
72
+ return await refreshProviderOAuthCredentials({
73
+ credentials,
74
+ modelRuntime,
75
+ ...(options.log !== undefined ? { log: options.log } : {}),
76
+ })
119
77
  } catch (err) {
120
78
  const reason = err instanceof Error ? err.message : String(err)
121
79
  options.log?.(`refreshProviderOAuth: ${reason}`)
122
80
  return { entries: [] }
123
81
  }
124
- return refreshProviderOAuthCredentials({
125
- authStorage,
126
- ...(options.log !== undefined ? { log: options.log } : {}),
127
- })
128
82
  }
@@ -3,10 +3,9 @@ import { z } from 'zod'
3
3
  import { secretFieldSchema } from './resolve'
4
4
 
5
5
  // providers.<id> for api-key credentials: the `key` field is a Secret (string
6
- // shorthand or `{ value?, env? }` object). resolveSecret turns this into a
7
- // flat string at read time so AuthStorage (which expects `key: string`)
8
- // stays happy. OAuth credentials carry stateful refresh/access tokens that
9
- // are not env-injectable, so they pass through unchanged via catchall.
6
+ // shorthand or `{ value?, env? }` object). CredentialStore resolves this at
7
+ // request time; OAuth credentials carry stateful refresh/access tokens and
8
+ // are never env-injectable.
10
9
  const apiKeyProviderSchema = z.object({
11
10
  type: z.literal('api_key'),
12
11
  key: secretFieldSchema,