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.
- package/package.json +7 -4
- package/src/agent/attention-escalation.ts +8 -5
- package/src/agent/auth-reloadable.ts +2 -3
- package/src/agent/auth.ts +59 -79
- package/src/agent/compaction.ts +2 -2
- package/src/agent/index.ts +42 -16
- package/src/agent/llm-replay-sanitizer.ts +1 -1
- package/src/agent/model-overrides.ts +1 -1
- package/src/agent/multimodal/look-at.ts +3 -3
- package/src/agent/multimodal/read-redirect.ts +1 -1
- package/src/agent/plugin-tools.ts +26 -31
- package/src/agent/reload-tool.ts +1 -1
- package/src/agent/subagents.ts +1 -1
- package/src/agent/tool-error-remediation.ts +1 -1
- package/src/agent/tool-result-budget.ts +2 -2
- package/src/agent/tools/channel-disengage.ts +2 -2
- package/src/agent/tools/channel-edit.ts +2 -2
- package/src/agent/tools/channel-fetch-attachment.ts +2 -2
- package/src/agent/tools/channel-history.ts +2 -2
- package/src/agent/tools/channel-react.ts +2 -2
- package/src/agent/tools/channel-read.ts +2 -2
- package/src/agent/tools/channel-reply.ts +2 -2
- package/src/agent/tools/channel-send.ts +2 -2
- package/src/agent/tools/grant-role.ts +2 -2
- package/src/agent/tools/post-github-review.ts +2 -2
- package/src/agent/tools/restart.ts +2 -2
- package/src/agent/tools/skip-response.ts +2 -2
- package/src/agent/tools/spawn-subagent.ts +2 -2
- package/src/agent/tools/stream-snapshot.ts +2 -2
- package/src/agent/tools/subagent-cancel.ts +2 -2
- package/src/agent/tools/subagent-output.ts +2 -2
- package/src/agent/tools/todo/index.ts +2 -2
- package/src/agent/tools/webfetch/tool.ts +2 -2
- package/src/agent/tools/websearch.ts +2 -2
- package/src/bundled-plugins/github-cli-auth/gh-command.ts +7 -1
- package/src/bundled-plugins/github-cli-auth/index.ts +1 -1
- package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -1
- package/src/bundled-plugins/memory/dreaming.ts +21 -6
- package/src/channels/adapters/kakaotalk-channel-resolver.ts +86 -16
- package/src/channels/adapters/kakaotalk.ts +7 -8
- package/src/channels/adapters/teams-classify.ts +21 -0
- package/src/channels/adapters/teams-edit.ts +2 -1
- package/src/channels/adapters/teams-format.ts +16 -0
- package/src/channels/adapters/teams.ts +12 -5
- package/src/channels/github-review-verdict-coordinator.ts +26 -3
- package/src/channels/router.ts +50 -25
- package/src/cli/compose.ts +3 -3
- package/src/cli/docker-preflight.ts +8 -4
- package/src/cli/model.ts +7 -5
- package/src/cli/oauth-callbacks.ts +38 -23
- package/src/cli/restart.ts +89 -23
- package/src/cli/start.ts +68 -16
- package/src/cli/status.ts +38 -6
- package/src/cli/stop.ts +5 -2
- package/src/compose/stop.ts +5 -4
- package/src/config/config.ts +62 -25
- package/src/config/providers.ts +272 -47
- package/src/container/build-cache.ts +807 -0
- package/src/container/compose-project.ts +4 -0
- package/src/container/docker-app.ts +74 -0
- package/src/container/log-archive.ts +33 -5
- package/src/container/memory-limit.ts +80 -0
- package/src/container/memory-oversubscription.ts +125 -0
- package/src/container/restart.ts +6 -1
- package/src/container/shared.ts +43 -16
- package/src/container/start.ts +280 -53
- package/src/container/stop.ts +19 -13
- package/src/container/verify-running.ts +12 -0
- package/src/cron/scheduler.ts +12 -4
- package/src/doctor/bounded-exec.ts +14 -0
- package/src/doctor/checks.ts +40 -15
- package/src/doctor/index.ts +14 -2
- package/src/doctor/plugin-bridge.ts +15 -3
- package/src/hostd/paths.ts +4 -0
- package/src/init/index.ts +4 -4
- package/src/init/oauth-login.ts +57 -17
- package/src/inspect/transcript-view.ts +6 -3
- package/src/run/channel-session-factory.ts +5 -4
- package/src/run/index.ts +27 -11
- package/src/run/resource-sample.ts +171 -0
- package/src/sandbox/index.ts +8 -1
- package/src/sandbox/session-tmp.ts +26 -1
- package/src/secrets/refresh-provider-oauth.ts +30 -76
- package/src/secrets/schema.ts +3 -4
- package/src/secrets/storage.ts +133 -234
- package/src/server/index.ts +1 -1
- package/src/sessions/index.ts +1 -1
- package/src/skills/typeclaw-config/SKILL.md +4 -4
- package/src/skills/typeclaw-plugins/SKILL.md +5 -5
- package/src/tui/index.ts +5 -3
- package/src/tui/theme.ts +1 -1
- package/typeclaw.schema.json +32 -1
- package/src/agent/adaptive-thinking-compat.ts +0 -79
- package/src/secrets/oauth-xai.ts +0 -348
package/typeclaw.schema.json
CHANGED
|
@@ -28,14 +28,19 @@
|
|
|
28
28
|
"openai/gpt-5.4-mini",
|
|
29
29
|
"openai/gpt-5.4",
|
|
30
30
|
"openai/gpt-5.5",
|
|
31
|
+
"openai/gpt-6-sol",
|
|
32
|
+
"openai/gpt-6-luna",
|
|
31
33
|
"openai-codex/gpt-5.4-mini",
|
|
32
34
|
"openai-codex/gpt-5.4",
|
|
33
35
|
"openai-codex/gpt-5.5",
|
|
36
|
+
"openai-codex/gpt-6-sol",
|
|
37
|
+
"openai-codex/gpt-6-luna",
|
|
34
38
|
"anthropic/claude-haiku-4-5",
|
|
35
39
|
"anthropic/claude-sonnet-4-6",
|
|
36
40
|
"anthropic/claude-sonnet-5",
|
|
37
41
|
"anthropic/claude-opus-4-7",
|
|
38
42
|
"anthropic/claude-opus-4-8",
|
|
43
|
+
"anthropic/claude-opus-5-5",
|
|
39
44
|
"anthropic/claude-fable-5",
|
|
40
45
|
"fireworks/accounts/fireworks/routers/kimi-k2p6-turbo",
|
|
41
46
|
"zai/glm-4.5-air",
|
|
@@ -47,6 +52,7 @@
|
|
|
47
52
|
"zai-coding/glm-5-turbo",
|
|
48
53
|
"zai-coding/glm-5.1",
|
|
49
54
|
"xai/grok-4.3",
|
|
55
|
+
"xai/grok-4.7",
|
|
50
56
|
"xai/grok-4.20-0309-reasoning",
|
|
51
57
|
"xai/grok-4.20-0309-non-reasoning",
|
|
52
58
|
"xai/grok-build-0.1",
|
|
@@ -86,14 +92,19 @@
|
|
|
86
92
|
"openai/gpt-5.4-mini",
|
|
87
93
|
"openai/gpt-5.4",
|
|
88
94
|
"openai/gpt-5.5",
|
|
95
|
+
"openai/gpt-6-sol",
|
|
96
|
+
"openai/gpt-6-luna",
|
|
89
97
|
"openai-codex/gpt-5.4-mini",
|
|
90
98
|
"openai-codex/gpt-5.4",
|
|
91
99
|
"openai-codex/gpt-5.5",
|
|
100
|
+
"openai-codex/gpt-6-sol",
|
|
101
|
+
"openai-codex/gpt-6-luna",
|
|
92
102
|
"anthropic/claude-haiku-4-5",
|
|
93
103
|
"anthropic/claude-sonnet-4-6",
|
|
94
104
|
"anthropic/claude-sonnet-5",
|
|
95
105
|
"anthropic/claude-opus-4-7",
|
|
96
106
|
"anthropic/claude-opus-4-8",
|
|
107
|
+
"anthropic/claude-opus-5-5",
|
|
97
108
|
"anthropic/claude-fable-5",
|
|
98
109
|
"fireworks/accounts/fireworks/routers/kimi-k2p6-turbo",
|
|
99
110
|
"zai/glm-4.5-air",
|
|
@@ -105,6 +116,7 @@
|
|
|
105
116
|
"zai-coding/glm-5-turbo",
|
|
106
117
|
"zai-coding/glm-5.1",
|
|
107
118
|
"xai/grok-4.3",
|
|
119
|
+
"xai/grok-4.7",
|
|
108
120
|
"xai/grok-4.20-0309-reasoning",
|
|
109
121
|
"xai/grok-4.20-0309-non-reasoning",
|
|
110
122
|
"xai/grok-build-0.1",
|
|
@@ -145,14 +157,19 @@
|
|
|
145
157
|
"openai/gpt-5.4-mini",
|
|
146
158
|
"openai/gpt-5.4",
|
|
147
159
|
"openai/gpt-5.5",
|
|
160
|
+
"openai/gpt-6-sol",
|
|
161
|
+
"openai/gpt-6-luna",
|
|
148
162
|
"openai-codex/gpt-5.4-mini",
|
|
149
163
|
"openai-codex/gpt-5.4",
|
|
150
164
|
"openai-codex/gpt-5.5",
|
|
165
|
+
"openai-codex/gpt-6-sol",
|
|
166
|
+
"openai-codex/gpt-6-luna",
|
|
151
167
|
"anthropic/claude-haiku-4-5",
|
|
152
168
|
"anthropic/claude-sonnet-4-6",
|
|
153
169
|
"anthropic/claude-sonnet-5",
|
|
154
170
|
"anthropic/claude-opus-4-7",
|
|
155
171
|
"anthropic/claude-opus-4-8",
|
|
172
|
+
"anthropic/claude-opus-5-5",
|
|
156
173
|
"anthropic/claude-fable-5",
|
|
157
174
|
"fireworks/accounts/fireworks/routers/kimi-k2p6-turbo",
|
|
158
175
|
"zai/glm-4.5-air",
|
|
@@ -164,6 +181,7 @@
|
|
|
164
181
|
"zai-coding/glm-5-turbo",
|
|
165
182
|
"zai-coding/glm-5.1",
|
|
166
183
|
"xai/grok-4.3",
|
|
184
|
+
"xai/grok-4.7",
|
|
167
185
|
"xai/grok-4.20-0309-reasoning",
|
|
168
186
|
"xai/grok-4.20-0309-non-reasoning",
|
|
169
187
|
"xai/grok-build-0.1",
|
|
@@ -202,14 +220,19 @@
|
|
|
202
220
|
"openai/gpt-5.4-mini",
|
|
203
221
|
"openai/gpt-5.4",
|
|
204
222
|
"openai/gpt-5.5",
|
|
223
|
+
"openai/gpt-6-sol",
|
|
224
|
+
"openai/gpt-6-luna",
|
|
205
225
|
"openai-codex/gpt-5.4-mini",
|
|
206
226
|
"openai-codex/gpt-5.4",
|
|
207
227
|
"openai-codex/gpt-5.5",
|
|
228
|
+
"openai-codex/gpt-6-sol",
|
|
229
|
+
"openai-codex/gpt-6-luna",
|
|
208
230
|
"anthropic/claude-haiku-4-5",
|
|
209
231
|
"anthropic/claude-sonnet-4-6",
|
|
210
232
|
"anthropic/claude-sonnet-5",
|
|
211
233
|
"anthropic/claude-opus-4-7",
|
|
212
234
|
"anthropic/claude-opus-4-8",
|
|
235
|
+
"anthropic/claude-opus-5-5",
|
|
213
236
|
"anthropic/claude-fable-5",
|
|
214
237
|
"fireworks/accounts/fireworks/routers/kimi-k2p6-turbo",
|
|
215
238
|
"zai/glm-4.5-air",
|
|
@@ -221,6 +244,7 @@
|
|
|
221
244
|
"zai-coding/glm-5-turbo",
|
|
222
245
|
"zai-coding/glm-5.1",
|
|
223
246
|
"xai/grok-4.3",
|
|
247
|
+
"xai/grok-4.7",
|
|
224
248
|
"xai/grok-4.20-0309-reasoning",
|
|
225
249
|
"xai/grok-4.20-0309-non-reasoning",
|
|
226
250
|
"xai/grok-build-0.1",
|
|
@@ -260,14 +284,19 @@
|
|
|
260
284
|
"openai/gpt-5.4-mini",
|
|
261
285
|
"openai/gpt-5.4",
|
|
262
286
|
"openai/gpt-5.5",
|
|
287
|
+
"openai/gpt-6-sol",
|
|
288
|
+
"openai/gpt-6-luna",
|
|
263
289
|
"openai-codex/gpt-5.4-mini",
|
|
264
290
|
"openai-codex/gpt-5.4",
|
|
265
291
|
"openai-codex/gpt-5.5",
|
|
292
|
+
"openai-codex/gpt-6-sol",
|
|
293
|
+
"openai-codex/gpt-6-luna",
|
|
266
294
|
"anthropic/claude-haiku-4-5",
|
|
267
295
|
"anthropic/claude-sonnet-4-6",
|
|
268
296
|
"anthropic/claude-sonnet-5",
|
|
269
297
|
"anthropic/claude-opus-4-7",
|
|
270
298
|
"anthropic/claude-opus-4-8",
|
|
299
|
+
"anthropic/claude-opus-5-5",
|
|
271
300
|
"anthropic/claude-fable-5",
|
|
272
301
|
"fireworks/accounts/fireworks/routers/kimi-k2p6-turbo",
|
|
273
302
|
"zai/glm-4.5-air",
|
|
@@ -279,6 +308,7 @@
|
|
|
279
308
|
"zai-coding/glm-5-turbo",
|
|
280
309
|
"zai-coding/glm-5.1",
|
|
281
310
|
"xai/grok-4.3",
|
|
311
|
+
"xai/grok-4.7",
|
|
282
312
|
"xai/grok-4.20-0309-reasoning",
|
|
283
313
|
"xai/grok-4.20-0309-non-reasoning",
|
|
284
314
|
"xai/grok-build-0.1",
|
|
@@ -317,7 +347,8 @@
|
|
|
317
347
|
"low",
|
|
318
348
|
"medium",
|
|
319
349
|
"high",
|
|
320
|
-
"xhigh"
|
|
350
|
+
"xhigh",
|
|
351
|
+
"max"
|
|
321
352
|
]
|
|
322
353
|
}
|
|
323
354
|
},
|
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
// Compatibility shim for adaptive-thinking-only Anthropic models on the
|
|
2
|
-
// pinned pi stack (@mariozechner/* 0.73.x).
|
|
3
|
-
//
|
|
4
|
-
// The problem: Sonnet 5 and Fable 5 accept ONLY adaptive thinking. Manual
|
|
5
|
-
// extended thinking (`thinking: {type: "enabled"}` with `budget_tokens`)
|
|
6
|
-
// returns a 400. But pi-ai's `supportsAdaptiveThinking()` matches only
|
|
7
|
-
// 4.6-generation ids (`opus-4-6`, `sonnet-4-6`), so for any OTHER Anthropic
|
|
8
|
-
// model registered with `reasoning: true` it falls back to the budget-based
|
|
9
|
-
// path — and thinking is on by default (pi-coding-agent's
|
|
10
|
-
// DEFAULT_THINKING_LEVEL is "medium", and `defaultThinkingLevelForRef`
|
|
11
|
-
// deliberately defers to it). Net effect without this shim: a session on
|
|
12
|
-
// Sonnet 5 / Fable 5 400s on its first request. Still true on 0.73.1: pi-ai
|
|
13
|
-
// 0.73.1 does not force adaptive thinking for these ids, so bumping the
|
|
14
|
-
// @mariozechner/* stack to 0.73 (PR #1123) did not obviate this shim.
|
|
15
|
-
//
|
|
16
|
-
// The fix: pi-ai calls `options.onPayload(params, model)` right before the
|
|
17
|
-
// HTTP request and adopts a non-undefined return value as the request params
|
|
18
|
-
// (see `streamAnthropic` in pi-ai's providers/anthropic.ts). We hook that seam
|
|
19
|
-
// via `Agent.onPayload` — a public field, same seam `src/agent/index.ts`
|
|
20
|
-
// already uses for `convertToLlm` (the replay sanitizer) — and rewrite
|
|
21
|
-
// `thinking: {type: "enabled", ...}` to `thinking: {type: "adaptive"}` for
|
|
22
|
-
// exactly the adaptive-only model ids. Everything else passes through
|
|
23
|
-
// byte-identical.
|
|
24
|
-
//
|
|
25
|
-
// Not covered (deliberately): pi-ai also sends the
|
|
26
|
-
// `interleaved-thinking-2025-05-14` beta header for non-4.6 models. That
|
|
27
|
-
// header is set at SDK-client construction, before `onPayload` runs, so this
|
|
28
|
-
// shim can't remove it — it is redundant-but-harmless on adaptive models (the
|
|
29
|
-
// API ignores it), unlike the budget `thinking` payload which hard-fails.
|
|
30
|
-
//
|
|
31
|
-
// TODO(pi-migration): DELETE THIS FILE when typeclaw migrates off the
|
|
32
|
-
// @mariozechner/pi-* 0.73.x line to @earendil-works/pi-* >= 0.80 (the same
|
|
33
|
-
// maintainers' scope rename; @mariozechner ends at 0.73.1, @earendil-works
|
|
34
|
-
// starts at 0.74.0). As of @earendil-works/pi-ai 0.80.3 the sonnet-5 / fable-5
|
|
35
|
-
// model records carry `compat: { forceAdaptiveThinking: true }`, and the
|
|
36
|
-
// Anthropic transport reads that flag to emit `thinking: {type: "adaptive"}`
|
|
37
|
-
// itself (AnthropicMessagesCompat.forceAdaptiveThinking) — so on that stack the
|
|
38
|
-
// rewrite here becomes redundant and both this file and its `onPayload` wiring
|
|
39
|
-
// in `src/agent/index.ts` should be removed.
|
|
40
|
-
|
|
41
|
-
import type { Api, Model } from '@mariozechner/pi-ai'
|
|
42
|
-
|
|
43
|
-
type OnPayload = (payload: unknown, model: Model<Api>) => unknown | undefined | Promise<unknown | undefined>
|
|
44
|
-
|
|
45
|
-
type OnPayloadHost = { onPayload?: OnPayload }
|
|
46
|
-
|
|
47
|
-
// Mirrors pi-ai's own id matching style (`String.includes`, date-suffix
|
|
48
|
-
// tolerant). Scoped to the Anthropic Messages API so a same-named id on a
|
|
49
|
-
// different transport (e.g. a Bedrock alias) is never touched.
|
|
50
|
-
export function isAdaptiveOnlyAnthropicModel(model: Pick<Model<Api>, 'api' | 'id'>): boolean {
|
|
51
|
-
if (model.api !== 'anthropic-messages') return false
|
|
52
|
-
return model.id.includes('sonnet-5') || model.id.includes('fable-5')
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// Pure rewrite: budget-based `thinking` -> `{type: "adaptive"}` for
|
|
56
|
-
// adaptive-only models. Returns the ORIGINAL payload object (not a clone)
|
|
57
|
-
// whenever no rewrite applies, so "untouched" is reference-checkable in tests.
|
|
58
|
-
export function rewriteThinkingForAdaptiveOnlyModels(payload: unknown, model: Pick<Model<Api>, 'api' | 'id'>): unknown {
|
|
59
|
-
if (!isAdaptiveOnlyAnthropicModel(model)) return payload
|
|
60
|
-
if (payload === null || typeof payload !== 'object') return payload
|
|
61
|
-
if (!('thinking' in payload)) return payload
|
|
62
|
-
const thinking = payload.thinking
|
|
63
|
-
if (thinking === null || typeof thinking !== 'object') return payload
|
|
64
|
-
if (!('type' in thinking) || thinking.type !== 'enabled') return payload
|
|
65
|
-
return { ...payload, thinking: { type: 'adaptive' } }
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// Layers the rewrite over an agent's existing `onPayload` (pi-coding-agent
|
|
69
|
-
// installs one that dispatches extension `before_provider_request` handlers).
|
|
70
|
-
// Honors pi's contract that an `undefined` return means "keep the original
|
|
71
|
-
// payload": the inner hook's undefined falls back to the incoming payload
|
|
72
|
-
// before the rewrite runs, so the rewrite always sees the effective params.
|
|
73
|
-
export function applyAdaptiveThinkingCompat(agent: OnPayloadHost): void {
|
|
74
|
-
const inner = agent.onPayload
|
|
75
|
-
agent.onPayload = async (payload, model) => {
|
|
76
|
-
const effective = inner === undefined ? payload : ((await inner(payload, model)) ?? payload)
|
|
77
|
-
return rewriteThinkingForAdaptiveOnlyModels(effective, model)
|
|
78
|
-
}
|
|
79
|
-
}
|
package/src/secrets/oauth-xai.ts
DELETED
|
@@ -1,348 +0,0 @@
|
|
|
1
|
-
import { createServer, type Server } from 'node:http'
|
|
2
|
-
|
|
3
|
-
import { getOAuthProvider, registerOAuthProvider } from '@mariozechner/pi-ai/oauth'
|
|
4
|
-
import type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from '@mariozechner/pi-ai/oauth'
|
|
5
|
-
|
|
6
|
-
// xAI (Grok) OAuth 2.0. xAI runs a standard OIDC authorization server at
|
|
7
|
-
// auth.x.ai that supports BOTH authorization-code + PKCE (loopback callback)
|
|
8
|
-
// and the device-authorization grant. We implement the auth-code path with a
|
|
9
|
-
// localhost callback server (same UX as pi-ai's anthropic provider) plus a
|
|
10
|
-
// manual-paste fallback for cross-device/SSH flows.
|
|
11
|
-
//
|
|
12
|
-
// There is no public developer console to register a third-party OAuth client,
|
|
13
|
-
// so — like every OSS Grok integration (Grok CLI, opencode, hermes-agent,
|
|
14
|
-
// pi-xai-oauth) — we reuse the Grok CLI's public client id. The `plan=generic`
|
|
15
|
-
// query param is load-bearing: loopback OAuth against this client id is
|
|
16
|
-
// rejected without it. `referrer` is attribution only.
|
|
17
|
-
//
|
|
18
|
-
// Endpoints below are the live values from
|
|
19
|
-
// https://auth.x.ai/.well-known/openid-configuration. The token endpoint speaks
|
|
20
|
-
// application/x-www-form-urlencoded (OAuth2 default) — NOT JSON like Anthropic.
|
|
21
|
-
export const XAI_OAUTH_PROVIDER_ID = 'xai'
|
|
22
|
-
|
|
23
|
-
const CLIENT_ID = 'b1a00492-073a-47ea-816f-4c329264a828'
|
|
24
|
-
const AUTHORIZE_URL = 'https://auth.x.ai/oauth2/authorize'
|
|
25
|
-
const TOKEN_URL = 'https://auth.x.ai/oauth2/token'
|
|
26
|
-
const CALLBACK_HOST = '127.0.0.1'
|
|
27
|
-
const CALLBACK_PORT = 56121
|
|
28
|
-
const CALLBACK_PATH = '/callback'
|
|
29
|
-
const REDIRECT_URI = `http://${CALLBACK_HOST}:${CALLBACK_PORT}${CALLBACK_PATH}`
|
|
30
|
-
const SCOPES = 'openid profile email offline_access grok-cli:access api:access'
|
|
31
|
-
const REFERRER = 'typeclaw'
|
|
32
|
-
// Refresh slightly early so an in-flight request never races expiry.
|
|
33
|
-
const EXPIRY_SKEW_MS = 5 * 60 * 1000
|
|
34
|
-
const REQUEST_TIMEOUT_MS = 30_000
|
|
35
|
-
|
|
36
|
-
type XaiTokenResponse = {
|
|
37
|
-
access_token?: string
|
|
38
|
-
refresh_token?: string
|
|
39
|
-
expires_in?: number
|
|
40
|
-
token_type?: string
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function base64UrlEncode(bytes: Uint8Array): string {
|
|
44
|
-
let binary = ''
|
|
45
|
-
for (const byte of bytes) binary += String.fromCharCode(byte)
|
|
46
|
-
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
// PKCE (RFC 7636, S256). pi-ai keeps its `generatePKCE` helper out of the
|
|
50
|
-
// public `/oauth` barrel, so we generate the verifier/challenge with Web Crypto
|
|
51
|
-
// directly — available in both Node and Bun.
|
|
52
|
-
async function generatePkce(): Promise<{ verifier: string; challenge: string }> {
|
|
53
|
-
const verifier = base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)))
|
|
54
|
-
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))
|
|
55
|
-
return { verifier, challenge: base64UrlEncode(new Uint8Array(digest)) }
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function parseAuthorizationInput(input: string): { code?: string; state?: string } {
|
|
59
|
-
const value = input.trim()
|
|
60
|
-
if (!value) return {}
|
|
61
|
-
try {
|
|
62
|
-
const url = new URL(value)
|
|
63
|
-
return {
|
|
64
|
-
code: url.searchParams.get('code') ?? undefined,
|
|
65
|
-
state: url.searchParams.get('state') ?? undefined,
|
|
66
|
-
}
|
|
67
|
-
} catch {
|
|
68
|
-
// Not a full URL — fall through to query-string / bare-code handling.
|
|
69
|
-
}
|
|
70
|
-
if (value.includes('code=')) {
|
|
71
|
-
const params = new URLSearchParams(value)
|
|
72
|
-
return {
|
|
73
|
-
code: params.get('code') ?? undefined,
|
|
74
|
-
state: params.get('state') ?? undefined,
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
return { code: value }
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
type CallbackServer = {
|
|
81
|
-
server: Server
|
|
82
|
-
cancelWait: () => void
|
|
83
|
-
waitForCode: () => Promise<{ code: string; state: string | null } | null>
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
function successHtml(): string {
|
|
87
|
-
return '<!doctype html><html><body style="font-family:sans-serif;padding:2rem"><h2>xAI authentication complete.</h2><p>You can close this window and return to the terminal.</p></body></html>'
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
// The OAuth `error` query param is provider-supplied and reflected into the
|
|
91
|
-
// callback page, so escape it to keep a crafted callback URL
|
|
92
|
-
// (`?error=<script>…`) from injecting markup into the local page.
|
|
93
|
-
function escapeHtml(value: string): string {
|
|
94
|
-
return value
|
|
95
|
-
.replaceAll('&', '&')
|
|
96
|
-
.replaceAll('<', '<')
|
|
97
|
-
.replaceAll('>', '>')
|
|
98
|
-
.replaceAll('"', '"')
|
|
99
|
-
.replaceAll("'", ''')
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export function errorHtml(message: string): string {
|
|
103
|
-
return `<!doctype html><html><body style="font-family:sans-serif;padding:2rem"><h2>xAI authentication failed.</h2><p>${escapeHtml(message)}</p></body></html>`
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// Resolves to `null` when the fixed loopback port can't be bound (EADDRINUSE,
|
|
107
|
-
// sandbox bind restriction). The caller then falls back to manual-paste mode
|
|
108
|
-
// rather than failing the whole login — the browser callback is a convenience,
|
|
109
|
-
// not a hard requirement, since the user can always paste the redirect URL.
|
|
110
|
-
function startCallbackServer(expectedState: string): Promise<CallbackServer | null> {
|
|
111
|
-
return new Promise((resolve) => {
|
|
112
|
-
let settle: ((value: { code: string; state: string | null } | null) => void) | undefined
|
|
113
|
-
const waitForCodePromise = new Promise<{ code: string; state: string | null } | null>((resolveWait) => {
|
|
114
|
-
let settled = false
|
|
115
|
-
settle = (value) => {
|
|
116
|
-
if (settled) return
|
|
117
|
-
settled = true
|
|
118
|
-
resolveWait(value)
|
|
119
|
-
}
|
|
120
|
-
})
|
|
121
|
-
|
|
122
|
-
const server = createServer((req, res) => {
|
|
123
|
-
try {
|
|
124
|
-
const url = new URL(req.url || '', `http://${CALLBACK_HOST}`)
|
|
125
|
-
if (url.pathname !== CALLBACK_PATH) {
|
|
126
|
-
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' })
|
|
127
|
-
res.end(errorHtml('Callback route not found.'))
|
|
128
|
-
return
|
|
129
|
-
}
|
|
130
|
-
const code = url.searchParams.get('code')
|
|
131
|
-
const state = url.searchParams.get('state')
|
|
132
|
-
const error = url.searchParams.get('error')
|
|
133
|
-
if (error) {
|
|
134
|
-
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' })
|
|
135
|
-
res.end(errorHtml(`Error: ${error}`))
|
|
136
|
-
return
|
|
137
|
-
}
|
|
138
|
-
if (!code) {
|
|
139
|
-
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' })
|
|
140
|
-
res.end(errorHtml('Missing code parameter.'))
|
|
141
|
-
return
|
|
142
|
-
}
|
|
143
|
-
if (state !== expectedState) {
|
|
144
|
-
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' })
|
|
145
|
-
res.end(errorHtml('State mismatch.'))
|
|
146
|
-
return
|
|
147
|
-
}
|
|
148
|
-
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
|
|
149
|
-
res.end(successHtml())
|
|
150
|
-
settle?.({ code, state })
|
|
151
|
-
} catch {
|
|
152
|
-
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' })
|
|
153
|
-
res.end('Internal error')
|
|
154
|
-
}
|
|
155
|
-
})
|
|
156
|
-
|
|
157
|
-
server.on('error', () => {
|
|
158
|
-
server.close()
|
|
159
|
-
resolve(null)
|
|
160
|
-
})
|
|
161
|
-
server.listen(CALLBACK_PORT, CALLBACK_HOST, () => {
|
|
162
|
-
resolve({
|
|
163
|
-
server,
|
|
164
|
-
cancelWait: () => settle?.(null),
|
|
165
|
-
waitForCode: () => waitForCodePromise,
|
|
166
|
-
})
|
|
167
|
-
})
|
|
168
|
-
})
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
export type FetchFn = (input: string, init: RequestInit) => Promise<Response>
|
|
172
|
-
|
|
173
|
-
async function postForm(url: string, body: Record<string, string>, fetchImpl: FetchFn): Promise<XaiTokenResponse> {
|
|
174
|
-
const response = await fetchImpl(url, {
|
|
175
|
-
method: 'POST',
|
|
176
|
-
headers: {
|
|
177
|
-
'Content-Type': 'application/x-www-form-urlencoded',
|
|
178
|
-
Accept: 'application/json',
|
|
179
|
-
},
|
|
180
|
-
body: new URLSearchParams(body).toString(),
|
|
181
|
-
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
182
|
-
})
|
|
183
|
-
const text = await response.text()
|
|
184
|
-
if (!response.ok) {
|
|
185
|
-
throw new Error(`xAI OAuth request failed. status=${response.status}; url=${url}; body=${text}`)
|
|
186
|
-
}
|
|
187
|
-
try {
|
|
188
|
-
return JSON.parse(text) as XaiTokenResponse
|
|
189
|
-
} catch {
|
|
190
|
-
throw new Error(`xAI OAuth returned invalid JSON. url=${url}; body=${text}`)
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
function toCredentials(token: XaiTokenResponse): OAuthCredentials {
|
|
195
|
-
if (!token.access_token || !token.refresh_token || token.expires_in === undefined) {
|
|
196
|
-
throw new Error('xAI OAuth response missing access_token, refresh_token, or expires_in')
|
|
197
|
-
}
|
|
198
|
-
return {
|
|
199
|
-
access: token.access_token,
|
|
200
|
-
refresh: token.refresh_token,
|
|
201
|
-
expires: Date.now() + token.expires_in * 1000 - EXPIRY_SKEW_MS,
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
async function exchangeAuthorizationCode(
|
|
206
|
-
code: string,
|
|
207
|
-
verifier: string,
|
|
208
|
-
fetchImpl: FetchFn,
|
|
209
|
-
): Promise<OAuthCredentials> {
|
|
210
|
-
const token = await postForm(
|
|
211
|
-
TOKEN_URL,
|
|
212
|
-
{
|
|
213
|
-
grant_type: 'authorization_code',
|
|
214
|
-
client_id: CLIENT_ID,
|
|
215
|
-
code,
|
|
216
|
-
redirect_uri: REDIRECT_URI,
|
|
217
|
-
code_verifier: verifier,
|
|
218
|
-
},
|
|
219
|
-
fetchImpl,
|
|
220
|
-
)
|
|
221
|
-
return toCredentials(token)
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
type StartCallbackServerFn = (expectedState: string) => Promise<CallbackServer | null>
|
|
225
|
-
|
|
226
|
-
export async function loginXai(
|
|
227
|
-
callbacks: OAuthLoginCallbacks,
|
|
228
|
-
fetchImpl: FetchFn = fetch,
|
|
229
|
-
startServer: StartCallbackServerFn = startCallbackServer,
|
|
230
|
-
): Promise<OAuthCredentials> {
|
|
231
|
-
const { verifier, challenge } = await generatePkce()
|
|
232
|
-
const server = await startServer(verifier)
|
|
233
|
-
let code: string | undefined
|
|
234
|
-
try {
|
|
235
|
-
const authParams = new URLSearchParams({
|
|
236
|
-
client_id: CLIENT_ID,
|
|
237
|
-
response_type: 'code',
|
|
238
|
-
redirect_uri: REDIRECT_URI,
|
|
239
|
-
scope: SCOPES,
|
|
240
|
-
code_challenge: challenge,
|
|
241
|
-
code_challenge_method: 'S256',
|
|
242
|
-
state: verifier,
|
|
243
|
-
plan: 'generic',
|
|
244
|
-
referrer: REFERRER,
|
|
245
|
-
})
|
|
246
|
-
callbacks.onAuth({
|
|
247
|
-
url: `${AUTHORIZE_URL}?${authParams.toString()}`,
|
|
248
|
-
instructions:
|
|
249
|
-
'Complete login in your browser. Grok shows a code to copy on the "could not establish connection" page — paste that code here. If the browser is on another machine, paste the code (or the final redirect URL) here.',
|
|
250
|
-
})
|
|
251
|
-
|
|
252
|
-
if (server && callbacks.onManualCodeInput) {
|
|
253
|
-
// Race the local callback server against a manual paste: whichever lands
|
|
254
|
-
// a code first wins (cross-device/SSH logins can't reach the loopback).
|
|
255
|
-
let manualInput: string | undefined
|
|
256
|
-
let manualError: Error | undefined
|
|
257
|
-
const manualPromise = callbacks
|
|
258
|
-
.onManualCodeInput()
|
|
259
|
-
.then((input) => {
|
|
260
|
-
manualInput = input
|
|
261
|
-
server.cancelWait()
|
|
262
|
-
})
|
|
263
|
-
.catch((err) => {
|
|
264
|
-
manualError = err instanceof Error ? err : new Error(String(err))
|
|
265
|
-
server.cancelWait()
|
|
266
|
-
})
|
|
267
|
-
|
|
268
|
-
const result = await server.waitForCode()
|
|
269
|
-
if (manualError) throw manualError
|
|
270
|
-
if (result?.code) {
|
|
271
|
-
code = result.code
|
|
272
|
-
} else if (manualInput) {
|
|
273
|
-
code = parseManualCode(manualInput, verifier)
|
|
274
|
-
}
|
|
275
|
-
if (!code) {
|
|
276
|
-
await manualPromise
|
|
277
|
-
if (manualError) throw manualError
|
|
278
|
-
if (manualInput) {
|
|
279
|
-
code = parseManualCode(manualInput, verifier)
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
} else if (server) {
|
|
283
|
-
const result = await server.waitForCode()
|
|
284
|
-
if (result?.code) code = result.code
|
|
285
|
-
} else if (callbacks.onManualCodeInput) {
|
|
286
|
-
// No callback server bound — manual paste is the only path to a code.
|
|
287
|
-
code = parseManualCode(await callbacks.onManualCodeInput(), verifier)
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
if (!code) {
|
|
291
|
-
const input = await callbacks.onPrompt({
|
|
292
|
-
message: 'Paste the authorization code or full redirect URL:',
|
|
293
|
-
placeholder: REDIRECT_URI,
|
|
294
|
-
})
|
|
295
|
-
code = parseManualCode(input, verifier)
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
if (!code) throw new Error('Missing authorization code')
|
|
299
|
-
|
|
300
|
-
callbacks.onProgress?.('Exchanging authorization code for tokens...')
|
|
301
|
-
return await exchangeAuthorizationCode(code, verifier, fetchImpl)
|
|
302
|
-
} finally {
|
|
303
|
-
server?.server.close()
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
function parseManualCode(input: string, verifier: string): string | undefined {
|
|
308
|
-
const parsed = parseAuthorizationInput(input)
|
|
309
|
-
if (parsed.state && parsed.state !== verifier) throw new Error('OAuth state mismatch')
|
|
310
|
-
return parsed.code
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
export async function refreshXaiToken(refreshToken: string, fetchImpl: FetchFn = fetch): Promise<OAuthCredentials> {
|
|
314
|
-
const token = await postForm(
|
|
315
|
-
TOKEN_URL,
|
|
316
|
-
{
|
|
317
|
-
grant_type: 'refresh_token',
|
|
318
|
-
client_id: CLIENT_ID,
|
|
319
|
-
refresh_token: refreshToken,
|
|
320
|
-
},
|
|
321
|
-
fetchImpl,
|
|
322
|
-
)
|
|
323
|
-
// Some OAuth servers omit a rotated refresh token on refresh; keep the prior
|
|
324
|
-
// one so the credential stays usable across the next cycle.
|
|
325
|
-
return toCredentials({ ...token, refresh_token: token.refresh_token ?? refreshToken })
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
export const xaiOAuthProvider: OAuthProviderInterface = {
|
|
329
|
-
id: XAI_OAUTH_PROVIDER_ID,
|
|
330
|
-
name: 'xAI (Grok)',
|
|
331
|
-
usesCallbackServer: true,
|
|
332
|
-
login: loginXai,
|
|
333
|
-
refreshToken: (credentials) => refreshXaiToken(credentials.refresh),
|
|
334
|
-
getApiKey: (credentials) => credentials.access,
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
let registered = false
|
|
338
|
-
|
|
339
|
-
// pi-ai ships no built-in xAI OAuth provider, so we register ours. Idempotent
|
|
340
|
-
// and called from `createSecretsStoreForAgent` — the single chokepoint both the
|
|
341
|
-
// init-time login path and the container-runtime auth/refresh path go through —
|
|
342
|
-
// so the provider is always present before `AuthStorage.login()` /
|
|
343
|
-
// `getApiKey()` look it up via `getOAuthProvider('xai')`.
|
|
344
|
-
export function registerXaiOAuthProvider(): void {
|
|
345
|
-
if (registered && getOAuthProvider(XAI_OAUTH_PROVIDER_ID)) return
|
|
346
|
-
registerOAuthProvider(xaiOAuthProvider)
|
|
347
|
-
registered = true
|
|
348
|
-
}
|