typeclaw 0.48.11 → 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 (94) hide show
  1. package/package.json +7 -4
  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 +42 -16
  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/bundled-plugins/github-cli-auth/gh-command.ts +7 -1
  36. package/src/bundled-plugins/github-cli-auth/index.ts +1 -1
  37. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -1
  38. package/src/bundled-plugins/memory/dreaming.ts +21 -6
  39. package/src/channels/adapters/kakaotalk-channel-resolver.ts +86 -16
  40. package/src/channels/adapters/kakaotalk.ts +7 -8
  41. package/src/channels/adapters/teams-classify.ts +21 -0
  42. package/src/channels/adapters/teams-edit.ts +2 -1
  43. package/src/channels/adapters/teams-format.ts +16 -0
  44. package/src/channels/adapters/teams.ts +12 -5
  45. package/src/channels/github-review-verdict-coordinator.ts +26 -3
  46. package/src/channels/router.ts +50 -25
  47. package/src/cli/compose.ts +3 -3
  48. package/src/cli/docker-preflight.ts +8 -4
  49. package/src/cli/model.ts +7 -5
  50. package/src/cli/oauth-callbacks.ts +38 -23
  51. package/src/cli/restart.ts +89 -23
  52. package/src/cli/start.ts +68 -16
  53. package/src/cli/status.ts +38 -6
  54. package/src/cli/stop.ts +5 -2
  55. package/src/compose/stop.ts +5 -4
  56. package/src/config/config.ts +62 -25
  57. package/src/config/providers.ts +272 -47
  58. package/src/container/build-cache.ts +807 -0
  59. package/src/container/compose-project.ts +4 -0
  60. package/src/container/docker-app.ts +74 -0
  61. package/src/container/log-archive.ts +33 -5
  62. package/src/container/memory-limit.ts +80 -0
  63. package/src/container/memory-oversubscription.ts +125 -0
  64. package/src/container/restart.ts +6 -1
  65. package/src/container/shared.ts +43 -16
  66. package/src/container/start.ts +280 -53
  67. package/src/container/stop.ts +19 -13
  68. package/src/container/verify-running.ts +12 -0
  69. package/src/cron/scheduler.ts +12 -4
  70. package/src/doctor/bounded-exec.ts +14 -0
  71. package/src/doctor/checks.ts +40 -15
  72. package/src/doctor/index.ts +14 -2
  73. package/src/doctor/plugin-bridge.ts +15 -3
  74. package/src/hostd/paths.ts +4 -0
  75. package/src/init/index.ts +4 -4
  76. package/src/init/oauth-login.ts +57 -17
  77. package/src/inspect/transcript-view.ts +6 -3
  78. package/src/run/channel-session-factory.ts +5 -4
  79. package/src/run/index.ts +27 -11
  80. package/src/run/resource-sample.ts +171 -0
  81. package/src/sandbox/index.ts +8 -1
  82. package/src/sandbox/session-tmp.ts +26 -1
  83. package/src/secrets/refresh-provider-oauth.ts +30 -76
  84. package/src/secrets/schema.ts +3 -4
  85. package/src/secrets/storage.ts +133 -234
  86. package/src/server/index.ts +1 -1
  87. package/src/sessions/index.ts +1 -1
  88. package/src/skills/typeclaw-config/SKILL.md +4 -4
  89. package/src/skills/typeclaw-plugins/SKILL.md +5 -5
  90. package/src/tui/index.ts +5 -3
  91. package/src/tui/theme.ts +1 -1
  92. package/typeclaw.schema.json +32 -1
  93. package/src/agent/adaptive-thinking-compat.ts +0 -79
  94. package/src/secrets/oauth-xai.ts +0 -348
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.48.11",
3
+ "version": "0.48.13",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -45,12 +45,14 @@
45
45
  "dependencies": {
46
46
  "@clack/core": "^1.2.0",
47
47
  "@clack/prompts": "^1.2.0",
48
+ "@earendil-works/pi-agent-core": "^0.87.1",
49
+ "@earendil-works/pi-ai": "^0.87.1",
50
+ "@earendil-works/pi-coding-agent": "^0.87.1",
51
+ "@earendil-works/pi-tui": "^0.87.1",
48
52
  "@huggingface/transformers": "4.2.0",
49
- "@mariozechner/pi-coding-agent": "^0.73.1",
50
- "@mariozechner/pi-tui": "^0.73.1",
51
53
  "@modelcontextprotocol/sdk": "^1.29.0",
52
54
  "@mozilla/readability": "^0.6.0",
53
- "agent-messenger": "^2.35.0",
55
+ "agent-messenger": "^2.37.2",
54
56
  "cheerio": "^1.2.0",
55
57
  "citty": "^0.2.2",
56
58
  "cron-parser": "^5.5.0",
@@ -60,6 +62,7 @@
60
62
  "qrcode": "^1.5.4",
61
63
  "tough-cookie": "^6.0.2",
62
64
  "turndown": "^7.2.4",
65
+ "typebox": "1.3.27",
63
66
  "zod": "^4.3.6"
64
67
  },
65
68
  "devDependencies": {
@@ -1,4 +1,4 @@
1
- import type { ThinkingLevel } from '@mariozechner/pi-agent-core'
1
+ import type { ThinkingLevel } from '@earendil-works/pi-agent-core'
2
2
 
3
3
  function normalize(text: string): string {
4
4
  return text
@@ -710,9 +710,11 @@ export function detectAttentionEscalation(text: string, prior?: QuestionSignal |
710
710
  return MORPHEME_PATTERNS.some((pattern) => pattern.test(normalized))
711
711
  }
712
712
 
713
- // `xhigh` is the strongest level. It's OpenAI-family-only, but `setThinkingLevel`
714
- // clamps it per-model (down to `high` on non-OpenAI), so it's safe to pass
715
- // unconditionally and gives OpenAI models maximum effort on escalation turns.
713
+ // Escalation targets `xhigh`. `setThinkingLevel` clamps it per model (down to
714
+ // `high` where unsupported), so it's safe to pass unconditionally. `max` ranks
715
+ // above `xhigh` (pi-ai models.js level order) on the models that offer it
716
+ // (GPT-6, Claude Opus 5.5), so a session already at `max` keeps it: an
717
+ // escalation turn must never get less effort than an ordinary one.
716
718
  const ESCALATED_LEVEL: ThinkingLevel = 'xhigh'
717
719
 
718
720
  // `allowEscalation: false` pins the turn to `sessionDefault`. Subagent turns set
@@ -729,7 +731,8 @@ export function resolveTurnThinkingLevel(
729
731
  options?: TurnThinkingOptions,
730
732
  ): ThinkingLevel | undefined {
731
733
  if (options?.allowEscalation === false) return sessionDefault
732
- return detectAttentionEscalation(text, prior) ? ESCALATED_LEVEL : sessionDefault
734
+ if (sessionDefault === 'max' || !detectAttentionEscalation(text, prior)) return sessionDefault
735
+ return ESCALATED_LEVEL
733
736
  }
734
737
 
735
738
  type ThinkingLevelSettable = {
@@ -3,9 +3,8 @@ import type { Reloadable, ReloadResult } from '@/reload'
3
3
  import { invalidateProviderAuthCache } from './auth'
4
4
 
5
5
  export type CreateProviderAuthReloadableOptions = {
6
- // Fired after the auth cache is cleared. The run stage wires this to channel
7
- // session teardown so live sessions — which captured an AuthStorage at
8
- // creation — are recreated with freshly-resolved credentials.
6
+ // Fired after the runtime cache is cleared. The run stage tears down live
7
+ // sessions so replacements capture freshly resolved credentials.
9
8
  onProviderAuthChanged?: () => void | Promise<void>
10
9
  }
11
10
 
package/src/agent/auth.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { join } from 'node:path'
2
2
 
3
- import { AuthStorage, ModelRegistry } from '@mariozechner/pi-coding-agent'
3
+ import { ModelRuntime } from '@earendil-works/pi-coding-agent'
4
4
 
5
- import { getConfig } from '@/config'
5
+ import { getConfig, resolveModel } from '@/config'
6
6
  import {
7
7
  KNOWN_PROVIDERS,
8
8
  providerForModelRef,
@@ -12,10 +12,8 @@ import {
12
12
  } from '@/config/providers'
13
13
  import { createSecretsStoreForAgent } from '@/secrets'
14
14
 
15
- type Auth = {
16
- authStorage: AuthStorage
17
- modelRegistry: ModelRegistry
18
- }
15
+ export type ProviderAuth = { modelRuntime: ModelRuntime }
16
+ type RuntimeProviderConfig = Parameters<ModelRuntime['registerProvider']>[1]
19
17
 
20
18
  const TEST_DUMMY_API_KEY = 'test_dummy_key'
21
19
 
@@ -23,89 +21,81 @@ function secretsJsonPath(): string {
23
21
  return join(process.cwd(), 'secrets.json')
24
22
  }
25
23
 
26
- // Per-provider cache. Sessions that use a profile mapped to provider X share
27
- // a single AuthStorage + ModelRegistry for that provider; first use of a new
28
- // provider lazily resolves its credentials. This replaces the singleton
29
- // `getAuth()` from before multi-model — the singleton couldn't represent
30
- // "auth for `default` is OpenAI, auth for `vision` is Fireworks" without
31
- // constructing both at boot.
32
- const cached = new Map<KnownProviderId, Auth>()
24
+ // Cache the in-flight Promise: concurrent sessions for a provider share one
25
+ // runtime and one credential store instead of racing OAuth refresh/setup.
26
+ const cached = new Map<KnownProviderId, Promise<ProviderAuth>>()
33
27
 
34
- export function getAuthFor(providerId: KnownProviderId): Auth {
28
+ export function getAuthFor(providerId: KnownProviderId): Promise<ProviderAuth> {
35
29
  const existing = cached.get(providerId)
36
30
  if (existing) return existing
31
+ const created: Promise<ProviderAuth> = createProviderAuth(providerId).catch((error) => {
32
+ // Evict only this attempt: after a reload, a newer creation may own the key.
33
+ if (cached.get(providerId) === created) cached.delete(providerId)
34
+ throw error
35
+ })
36
+ cached.set(providerId, created)
37
+ return created
38
+ }
37
39
 
40
+ async function createProviderAuth(providerId: KnownProviderId): Promise<ProviderAuth> {
38
41
  const provider = KNOWN_PROVIDERS[providerId]
39
-
40
- if (process.env.NODE_ENV === 'test' && !hasAnyCredentialInEnv(provider.apiKeyEnv)) {
41
- const authStorage = AuthStorage.inMemory()
42
- if (supportsApiKey(provider)) {
43
- authStorage.setRuntimeApiKey(provider.id, TEST_DUMMY_API_KEY)
44
- }
45
- const modelRegistry = ModelRegistry.create(authStorage)
46
- const auth = { authStorage, modelRegistry }
47
- cached.set(providerId, auth)
48
- return auth
42
+ const credentials = createSecretsStoreForAgent(secretsJsonPath())
43
+ const modelRuntime = await ModelRuntime.create({
44
+ credentials,
45
+ modelsPath: null,
46
+ refreshOnCreate: false,
47
+ })
48
+
49
+ // A session can switch to any configured fallback model. Register every
50
+ // curated provider, including built-ins: extension models replace the
51
+ // provider catalog, and composeModelProvider dispatches each passed model
52
+ // by its own api/baseUrl when its transport differs from the built-in.
53
+ for (const knownProvider of Object.values(KNOWN_PROVIDERS)) {
54
+ modelRuntime.registerProvider(knownProvider.id, toRuntimeProviderConfig(knownProvider))
49
55
  }
50
56
 
51
- const authStorage = createSecretsStoreForAgent(secretsJsonPath())
52
-
53
- // Env-wins for api-key providers: when the canonical env var is set, layer
54
- // that value in via setRuntimeApiKey so AuthStorage's hasAuth resolves
55
- // true without persisting anything to secrets.json. This is the explicit
56
- // reversal of the pre-v2 auto-migrate-to-file behaviour.
57
- //
58
- // setRuntimeApiKey is in-memory only (it writes to runtimeOverrides, never
59
- // through withLock), so the file remains untouched even when the env var
60
- // is set. OAuth credentials in the file still take precedence on read
61
- // because AuthStorage's hasAuth checks runtimeOverrides first only for
62
- // api-key-shaped credentials — OAuth on disk wins on its own.
63
- if (supportsApiKey(provider) && provider.apiKeyEnv) {
64
- const envKey = process.env[provider.apiKeyEnv]
65
- if (envKey !== undefined && envKey !== '') {
66
- const existingCred = authStorage.get(provider.id)
67
- if (existingCred === undefined || existingCred.type === 'api_key') {
68
- authStorage.setRuntimeApiKey(provider.id, envKey)
69
- }
57
+ const oauthProviders = new Set(
58
+ (await credentials.list())
59
+ .filter((credential) => credential.type === 'oauth')
60
+ .map((credential) => credential.providerId),
61
+ )
62
+ for (const knownProvider of Object.values(KNOWN_PROVIDERS)) {
63
+ if (!supportsApiKey(knownProvider) || !knownProvider.apiKeyEnv) continue
64
+ const envKey = process.env[knownProvider.apiKeyEnv]
65
+ // Runtime keys are memory-only. A persisted OAuth credential wins for
66
+ // dual-auth providers and env values never leak into the v2 envelope.
67
+ if (envKey && !oauthProviders.has(knownProvider.id)) {
68
+ await modelRuntime.setRuntimeApiKey(knownProvider.id, envKey)
70
69
  }
71
70
  }
72
71
 
73
- if (!authStorage.hasAuth(provider.id)) {
72
+ if (process.env.NODE_ENV === 'test' && !hasAnyCredentialInEnv(provider.apiKeyEnv)) {
73
+ if (supportsApiKey(provider)) await modelRuntime.setRuntimeApiKey(provider.id, TEST_DUMMY_API_KEY)
74
+ return { modelRuntime }
75
+ }
76
+ // checkAuth deliberately does not refresh OAuth. Boot must only reject a
77
+ // missing credential; a transient refresh failure belongs to the request
78
+ // path where pi can retry it on the next turn.
79
+ if (!(await modelRuntime.checkAuth(provider.id))) {
74
80
  console.error(missingCredentialMessage(providerId))
75
81
  process.exit(1)
76
82
  }
77
-
78
- const modelRegistry = ModelRegistry.create(authStorage)
79
- const auth = { authStorage, modelRegistry }
80
- cached.set(providerId, auth)
81
- return auth
83
+ return { modelRuntime }
82
84
  }
83
85
 
84
- // Back-compat shim for callers that still want the `default` profile's auth
85
- // (the main session path). Equivalent to `getAuthFor(provider-of-default)`.
86
- // Uses the head of the fallback chain; auth for the rest of the chain is
87
- // resolved lazily when fallback actually fires.
88
- export function getAuth(): Auth {
89
- const defaultRef = getConfig().models.default.refs[0]!
90
- return getAuthFor(providerForModelRef(defaultRef))
86
+ function toRuntimeProviderConfig(provider: (typeof KNOWN_PROVIDERS)[KnownProviderId]): RuntimeProviderConfig {
87
+ return {
88
+ name: provider.name,
89
+ baseUrl: provider.baseUrl,
90
+ api: Object.values(provider.models)[0]?.api,
91
+ models: Object.values(provider.models) as RuntimeProviderConfig['models'],
92
+ }
91
93
  }
92
94
 
93
- // Clears the per-provider cache so the next getAuthFor() re-resolves from
94
- // secrets.json (bind-mounted live) and re-layers process.env. Wired into
95
- // `typeclaw reload` via the providers reloadable so a rotated secrets.json
96
- // key takes effect without a container restart. Resolution stays lazy, so a
97
- // half-written secrets.json can't turn reload into getAuthFor's process-kill;
98
- // the missing-credential exit only fires on next actual use. Does NOT mutate
99
- // live AgentSessions that already captured an AuthStorage — the run stage
100
- // tears those down so the next session is built with fresh auth.
101
95
  export function invalidateProviderAuthCache(): void {
102
96
  cached.clear()
103
97
  }
104
98
 
105
- export function resetAuthForTesting(): void {
106
- cached.clear()
107
- }
108
-
109
99
  function hasAnyCredentialInEnv(apiKeyEnv: string | null): boolean {
110
100
  return apiKeyEnv !== null && process.env[apiKeyEnv] !== undefined && process.env[apiKeyEnv] !== ''
111
101
  }
@@ -114,18 +104,8 @@ function missingCredentialMessage(providerId: KnownProviderId): string {
114
104
  const provider = KNOWN_PROVIDERS[providerId]
115
105
  const defaultRef = getConfig().models.default.refs[0]!
116
106
  const defaultProviderId = providerForModelRef(defaultRef)
117
- // For the `default` profile, name the model in the error message (matches
118
- // pre-multi-model behavior). For any other profile, the user is mixing
119
- // providers across profiles and the error must name the failing provider
120
- // without claiming it's tied to the `default` model.
121
107
  const isDefault = defaultProviderId === providerId
122
- const ref = isDefault ? defaultRef : null
123
- const modelName =
124
- ref !== null
125
- ? ((provider.models as Record<string, { name: string }>)[ref.slice(ref.indexOf('/') + 1)]?.name ??
126
- ref.slice(ref.indexOf('/') + 1))
127
- : null
128
-
108
+ const modelName = isDefault ? resolveModel(defaultRef).name : null
129
109
  const oauthOnly = supportsOAuth(provider) && !supportsApiKey(provider)
130
110
  const apiKeyOnly = supportsApiKey(provider) && !supportsOAuth(provider)
131
111
 
@@ -1,5 +1,5 @@
1
- import type { KnownApi, Model } from '@mariozechner/pi-ai'
2
- import { SettingsManager } from '@mariozechner/pi-coding-agent'
1
+ import type { KnownApi, Model } from '@earendil-works/pi-ai'
2
+ import { SettingsManager } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  // Compaction trigger expressed as a fraction of the model's context window.
5
5
  // pi-coding-agent auto-compaction fires when `contextTokens > contextWindow -
@@ -7,8 +7,8 @@ import {
7
7
  DefaultResourceLoader,
8
8
  defineTool as definePiTool,
9
9
  SessionManager,
10
- } from '@mariozechner/pi-coding-agent'
11
- import type { AgentSession, ToolDefinition } from '@mariozechner/pi-coding-agent'
10
+ } from '@earendil-works/pi-coding-agent'
11
+ import type { AgentSession, ToolDefinition } from '@earendil-works/pi-coding-agent'
12
12
 
13
13
  import type { ChannelRouter } from '@/channels/router'
14
14
  import type { ReactionRef } from '@/channels/types'
@@ -36,10 +36,9 @@ import type {
36
36
  import { createHookBus, materializeSkills } from '@/plugin'
37
37
  import { CORE_SYSTEM_TOOL_NAMES } from '@/plugin/core-tool-names'
38
38
  import type { ReloadRegistry } from '@/reload'
39
- import { resolveHiddenPaths } from '@/sandbox'
39
+ import { enterSubagentTmpScope, resolveHiddenPaths } from '@/sandbox'
40
40
  import type { Stream } from '@/stream'
41
41
 
42
- import { applyAdaptiveThinkingCompat } from './adaptive-thinking-compat'
43
42
  import { getAuthFor } from './auth'
44
43
  import { createCompactionSettingsManager } from './compaction'
45
44
  import { renderGitNudge } from './git-nudge'
@@ -103,6 +102,13 @@ export { renderTurnRoleAnchor, renderTurnTimeAnchor } from './system-prompt'
103
102
 
104
103
  type AgentSessionTools = NonNullable<Parameters<typeof createAgentSession>[0]>['tools']
105
104
 
105
+ // Pi AI 0.73.1 capped an unset output budget at 32K
106
+ // (pi-ai dist/providers/simple-options.js:4). Pi 0.87.1 instead defaults to
107
+ // the full model maximum before context clamping (dist/api/simple-options.js:17),
108
+ // so preserve the former safe default at the session boundary. Explicit budgets
109
+ // remain untouched for compaction and channel-specific output caps.
110
+ export const DEFAULT_MAX_OUTPUT_TOKENS = 32_000
111
+
106
112
  export type PluginSessionWiring = {
107
113
  registry: PluginRegistry
108
114
  hooks: HookBus
@@ -276,7 +282,10 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
276
282
  // `refOverride` lets the model-fallback helper pin a specific entry from
277
283
  // the chain when it recreates a session after the previous ref failed.
278
284
  const activeRef: ModelRef = options.refOverride ?? resolved.ref
279
- const { authStorage, modelRegistry } = getAuthFor(providerForModelRef(activeRef))
285
+ // Provider auth owns both credentials and model resolution in Pi 0.87.
286
+ // Passing its ModelRuntime keeps every session request and compaction on the
287
+ // same configured provider runtime (sdk.d.ts:15-16; CHANGELOG 0.80.0).
288
+ const { modelRuntime } = await getAuthFor(providerForModelRef(activeRef))
280
289
  const sessionManager = options.sessionManager ?? SessionManager.inMemory()
281
290
 
282
291
  const materializedSkills =
@@ -353,7 +362,8 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
353
362
  : undefined
354
363
  const sessionBudgetState = sessionBudget ? createBudgetState() : undefined
355
364
 
356
- // The session's tool-name allowlist (pi 0.73 `tools:` is names, not tools).
365
+ // The session's tool-name allowlist is authoritative: with an explicit list,
366
+ // pi activates only listed builtins and custom tools (sdk.d.ts:35-47).
357
367
  // A subagent narrows to its declared refs; a non-subagent caller passes its
358
368
  // own explicit list (e.g. look-at's `[]`); everyone else leaves it undefined
359
369
  // so pi's default builtins apply. Implementations arrive via `customTools`;
@@ -514,16 +524,29 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
514
524
  const thinkingLevel = resolveSessionThinkingLevel(getConfig().models, resolved, activeRef)
515
525
  const { session } = await createAgentSession({
516
526
  model,
527
+ modelRuntime,
517
528
  sessionManager,
518
529
  settingsManager: createCompactionSettingsManager(model),
519
- authStorage,
520
- modelRegistry,
521
530
  resourceLoader,
522
531
  noTools: 'builtin',
523
532
  tools: intendedActiveToolNames,
524
533
  customTools,
525
534
  ...(thinkingLevel ? { thinkingLevel } : {}),
526
535
  })
536
+
537
+ // Wrapping also means `agent.streamFunction !== streamSimple`, which puts pi's
538
+ // summarization auth on its lenient branch (agent-session.js:214-232): a
539
+ // failed compaction auth surfaces from the request rather than as pi's
540
+ // "Authentication failed … /login" message. Channel sessions already wrap
541
+ // this function, so every origin now behaves the same way.
542
+ const innerStreamFunction = session.agent.streamFunction
543
+ session.agent.streamFunction = async (requestModel, context, streamOptions) => {
544
+ const maxTokens =
545
+ streamOptions?.maxTokens ??
546
+ (requestModel.maxTokens > 0 ? Math.min(requestModel.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS) : undefined)
547
+ return await innerStreamFunction(requestModel, context, { ...streamOptions, maxTokens })
548
+ }
549
+
527
550
  // typeclaw owns retry/fallback in its turn drivers, so the SDK's own
528
551
  // same-model auto-retry must be OFF. Leaving it on races typeclaw's
529
552
  // soft-error capture: the SDK can silently recover a `stopReason:'error'` turn
@@ -531,7 +554,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
531
554
  // failed (and burning an unnecessary failover). Disabling it makes a soft error
532
555
  // a deterministic, typeclaw-owned signal. Compaction/context-overflow recovery
533
556
  // is independent (gated on compaction settings), so this does not disable those.
534
- ;(session as { setAutoRetryEnabled?: (enabled: boolean) => void }).setAutoRetryEnabled?.(false)
557
+ session.setAutoRetryEnabled(false)
535
558
  const getAbortReason = () => abortHolder.reason
536
559
  const sessionWithAbortReason = Object.assign(session, { getAbortReason })
537
560
  const unsubLoopGuardTurn = attachLoopGuardTurnTracking(session.agent, () => {
@@ -553,13 +576,6 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
553
576
  }
554
577
  }
555
578
 
556
- // Same seam, one hook later: layer the adaptive-thinking rewrite over pi's
557
- // onPayload so Sonnet 5 / Fable 5 never receive the budget-based `thinking`
558
- // payload the pinned pi-ai 0.73.x emits for them (a hard 400 — see
559
- // adaptive-thinking-compat.ts). Covers every provider call path through the
560
- // agent, including model switches mid-session.
561
- applyAdaptiveThinkingCompat(session.agent)
562
-
563
579
  abortHolder.abort = (reason?: string) => {
564
580
  if (reason !== undefined) abortHolder.reason = reason
565
581
  if (session.agent.signal?.aborted !== true) session.agent.abort()
@@ -569,7 +585,17 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
569
585
 
570
586
  const unsubToolNudge = attachToolNotFoundNudge(session, intendedActiveToolNames)
571
587
 
588
+ // Registered only once creation can no longer fail, so a rejected creation
589
+ // leaves no scope entry behind; tools resolve the scope lazily at call time.
590
+ const releaseSubagentTmp =
591
+ options.origin?.kind === 'subagent' && options.origin.parentSessionId !== '<unknown>'
592
+ ? enterSubagentTmpScope(
593
+ options.plugins?.sessionId ?? sessionManager.getSessionId(),
594
+ options.origin.parentSessionId,
595
+ )
596
+ : undefined
572
597
  const dispose = async () => {
598
+ releaseSubagentTmp?.()
573
599
  unsubLoopGuardTurn()
574
600
  unsubRestart?.()
575
601
  unsubToolNudge()
@@ -33,7 +33,7 @@
33
33
  // This is a read-only projection: it never mutates the persisted JSONL, so an
34
34
  // already-poisoned session becomes usable without destructive migration.
35
35
 
36
- import type { Message } from '@mariozechner/pi-ai'
36
+ import type { Message } from '@earendil-works/pi-ai'
37
37
 
38
38
  export type ReplaySanitizerStats = {
39
39
  droppedOrphans: number
@@ -1,4 +1,4 @@
1
- import type { Api, Model } from '@mariozechner/pi-ai'
1
+ import type { Api, Model } from '@earendil-works/pi-ai'
2
2
 
3
3
  import { providerForModelRef, type KnownModelRef, type KnownProviderId, type ModelRef } from '@/config/providers'
4
4
 
@@ -1,8 +1,8 @@
1
1
  import { join } from 'node:path'
2
2
 
3
- import { Type } from '@mariozechner/pi-ai'
4
- import type { ImageContent } from '@mariozechner/pi-ai'
5
- import { defineTool } from '@mariozechner/pi-coding-agent'
3
+ import { Type } from '@earendil-works/pi-ai'
4
+ import type { ImageContent } from '@earendil-works/pi-ai'
5
+ import { defineTool } from '@earendil-works/pi-coding-agent'
6
6
 
7
7
  import { createSessionWithDispose, type SessionOrigin } from '@/agent'
8
8
  import { readResponseBodyBounded } from '@/agent/network/response-body'
@@ -5,7 +5,7 @@ import { GUARD_IMAGE_READ_REDIRECT } from '@/bundled-plugins/guard/keys'
5
5
 
6
6
  export { GUARD_IMAGE_READ_REDIRECT } from '@/bundled-plugins/guard/keys'
7
7
 
8
- // Mirrors the IMAGE_MIME_TYPES set in @mariozechner/pi-coding-agent
8
+ // Mirrors the IMAGE_MIME_TYPES set in @earendil-works/pi-coding-agent
9
9
  // (dist/utils/mime.ts). Keeping the trigger surface aligned with the upstream
10
10
  // read tool's image-attachment behavior means we redirect on exactly the
11
11
  // extensions that would otherwise inject `{ type: 'image' }` content parts
@@ -11,8 +11,8 @@ import {
11
11
  createReadToolDefinition as piCreateReadToolDefinition,
12
12
  createWriteToolDefinition as piCreateWriteToolDefinition,
13
13
  defineTool as piDefineTool,
14
- } from '@mariozechner/pi-coding-agent'
15
- import type { BashSpawnContext, ToolDefinition } from '@mariozechner/pi-coding-agent'
14
+ } from '@earendil-works/pi-coding-agent'
15
+ import type { BashSpawnContext, ToolDefinition } from '@earendil-works/pi-coding-agent'
16
16
  import type { Static, TSchema } from 'typebox'
17
17
  import { Type } from 'typebox'
18
18
  import { z } from 'zod'
@@ -182,22 +182,16 @@ export function sanitizeBashSpawnEnvironment(
182
182
  return env
183
183
  }
184
184
 
185
- // pi-coding-agent 0.73 contract (load-bearing for hook coverage):
185
+ // pi-coding-agent 0.87 contract (load-bearing for hook coverage):
186
186
  // - `createAgentSession({ tools: string[] })` is a name allowlist: only the
187
- // listed names stay active, and that allowlist gates BOTH builtins and
188
- // custom tools (see `allowedToolNames` in pi's `_refreshToolRegistry`).
189
- // - `noTools: "builtin"` drops pi's read/bash/edit/write from the INITIAL
190
- // active set; pi still registers its base builtins, so a same-named entry
191
- // in `customTools` is what overrides the implementation (registry
192
- // last-write-wins). Passing an explicit `tools:` allowlist plus shipping all
193
- // seven wrapped builtins is what makes the wrapped versions the only
194
- // callable ones.
187
+ // listed builtin and custom tool names are active (sdk.d.ts:35-47).
188
+ // - `noTools: "builtin"` disables Pi's default read/bash/edit/write tools but
189
+ // leaves custom tools eligible for that allowlist (sdk.d.ts:27-47).
195
190
  //
196
- // Consequence: every builtin enters as a `ToolDefinition` (pi now exposes
197
- // `create*ToolDefinition` factories), TypeClaw wraps each one with its hook +
198
- // guard + sandbox pipeline, and the call site routes them through `customTools`
199
- // while narrowing via `tools:` names. There is no longer an `AgentTool` vs
200
- // `ToolDefinition` split.
191
+ // Consequence: every builtin enters as a `ToolDefinition`, TypeClaw wraps each
192
+ // one with its hook + guard + sandbox pipeline, and the call site routes them
193
+ // through `customTools` while narrowing via `tools:` names. A named custom
194
+ // definition replaces the built-in implementation in the active registry.
201
195
  type TypeclawToolName = 'web_search' | 'web_fetch'
202
196
 
203
197
  // pi builtins resolve relative paths (and, for trusted/owner bash, the spawn
@@ -211,7 +205,13 @@ function createPiBuiltinToolDefinition(name: PiBuiltinToolName, cwd: string): To
211
205
  case 'read':
212
206
  return piCreateReadToolDefinition(cwd)
213
207
  case 'bash':
214
- return piCreateBashToolDefinition(cwd, { spawnHook: bashSpawnHookWithOverlay })
208
+ return piCreateBashToolDefinition(cwd, {
209
+ // Pi 0.87 assumes a non-empty ExtensionContext when session metadata is
210
+ // enabled (tools/bash.js:122-143). TypeClaw owns the bash environment
211
+ // boundary, so disable Pi metadata rather than bypassing the spawn hook.
212
+ exposeSessionEnvironment: false,
213
+ spawnHook: bashSpawnHookWithOverlay,
214
+ })
215
215
  case 'edit':
216
216
  return piCreateEditToolDefinition(cwd)
217
217
  case 'write':
@@ -326,20 +326,15 @@ export type WrapSystemToolOptions = {
326
326
  }
327
327
 
328
328
  // Zod 4 emits a top-level `"$schema": "https://json-schema.org/draft/2020-12/schema"`
329
- // pointer on every converted schema. Ajv v8 (used by pi-ai's runtime tool-argument
330
- // validator and by ModelRegistry's models.json validator) is configured for
331
- // Draft 7 and rejects unknown `$schema` URIs with:
332
- //
333
- // no schema with key or ref "https://json-schema.org/draft/2020-12/schema"
334
- //
335
- // That error is raised before the tool's execute is even invoked, so the model
336
- // sees the failure as a tool-call result and reacts by retrying or falling back
337
- // to other tools. In the memory-logger / dreaming subagents this meant the
338
- // `find_entry` tool was permanently broken: the subagent kept falling back to
339
- // `read(offset=1, limit=2000)` and chunked through entire multi-hundred-KB
340
- // transcripts on every channel turn. Stripping `$schema` is the minimal,
341
- // converter-version-independent fix; it leaves the actual JSON-schema body
342
- // untouched and lets Ajv use its default draft.
329
+ // pointer on every converted schema. It was first stripped because pi-ai's former
330
+ // Ajv (draft 7) validator rejected that URI before execute ran, which left the
331
+ // memory-logger and dreaming subagents without `find_entry` and made them read
332
+ // whole transcripts on every channel turn. pi 0.87 validates with TypeBox
333
+ // instead, but these parameter schemas are still forwarded verbatim to provider
334
+ // APIs, and pi strips JSON-Schema meta declarations itself only for Google
335
+ // (`sanitizeForOpenApi` in pi-ai dist/api/google-shared.js). Stripping the
336
+ // pointer keeps every provider's tool payload identical to earlier releases; it
337
+ // removes no constraint, since the schema body is untouched.
343
338
  export function zodToToolParameters(schema: z.ZodType<unknown>): TSchema {
344
339
  const json = z.toJSONSchema(schema, { io: 'input', reused: 'inline' }) as Record<string, unknown>
345
340
  delete json.$schema
@@ -1,4 +1,4 @@
1
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { defineTool } from '@earendil-works/pi-coding-agent'
2
2
  import { Type } from 'typebox'
3
3
 
4
4
  import type { ReloadRegistry, ReloadResult } from '@/reload'
@@ -1,4 +1,4 @@
1
- import type { ToolDefinition } from '@mariozechner/pi-coding-agent'
1
+ import type { ToolDefinition } from '@earendil-works/pi-coding-agent'
2
2
  import type { z } from 'zod'
3
3
 
4
4
  import { getConfig, resolveModel } from '@/config'
@@ -19,7 +19,7 @@ type RemediationRule = {
19
19
  }
20
20
 
21
21
  // First matching rule wins; keep the most specific patterns first. Upstream
22
- // sources: node_modules/@mariozechner/pi-coding-agent/dist/core/tools/{edit,read,ls,grep}.js
22
+ // sources: node_modules/@earendil-works/pi-coding-agent/dist/core/tools/{edit,read,ls,grep}.js
23
23
  const RULES: readonly RemediationRule[] = [
24
24
  {
25
25
  tools: ['edit'],
@@ -1,5 +1,5 @@
1
- import type { AgentTool } from '@mariozechner/pi-agent-core'
2
- import type { ToolDefinition } from '@mariozechner/pi-coding-agent'
1
+ import type { AgentTool } from '@earendil-works/pi-agent-core'
2
+ import type { ToolDefinition } from '@earendil-works/pi-coding-agent'
3
3
  import type { TSchema } from 'typebox'
4
4
 
5
5
  // Subagents that read large files (memory-logger and dreaming each read parent
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import type { ChannelRouter } from '@/channels/router'
5
5
  import type { AdapterId } from '@/channels/schema'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import {
5
5
  containsKimiToolDelimiter,
@@ -1,7 +1,7 @@
1
1
  import { join, sep } from 'node:path'
2
2
 
3
- import { Type } from '@mariozechner/pi-ai'
4
- import { defineTool } from '@mariozechner/pi-coding-agent'
3
+ import { Type } from '@earendil-works/pi-ai'
4
+ import { defineTool } from '@earendil-works/pi-coding-agent'
5
5
 
6
6
  import type { SessionOrigin } from '@/agent/session-origin'
7
7
  import { TOOL_INPUT_MAX_BYTES, writeFileAnchored } from '@/agent/tool-file-safety'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import type { ChannelRouter } from '@/channels/router'
5
5
  import type { AdapterId } from '@/channels/schema'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import type { ChannelRouter } from '@/channels/router'
5
5
  import type { AdapterId } from '@/channels/schema'
@@ -1,5 +1,5 @@
1
- import { Type } from '@mariozechner/pi-ai'
2
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { Type } from '@earendil-works/pi-ai'
2
+ import { defineTool } from '@earendil-works/pi-coding-agent'
3
3
 
4
4
  import type { ChannelRouter } from '@/channels/router'
5
5
  import { ADAPTER_IDS, type AdapterId } from '@/channels/schema'