typeclaw 0.48.12 → 0.49.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.
- package/package.json +6 -3
- package/scripts/dump-system-prompt.ts +52 -110
- 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 +173 -85
- package/src/agent/live-sessions.ts +2 -2
- package/src/agent/live-subagents.ts +1 -0
- 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 +76 -39
- package/src/agent/prompt-cache-key.ts +42 -0
- package/src/agent/provider-error.ts +179 -10
- package/src/agent/reload-tool.ts +1 -1
- package/src/agent/restart-handoff/index.ts +7 -14
- package/src/agent/reviewer-activity.ts +68 -0
- package/src/agent/session-origin.ts +33 -0
- package/src/agent/subagents.ts +14 -2
- package/src/agent/system-prompt.ts +68 -202
- package/src/agent/todo/continuation-policy.ts +12 -4
- package/src/agent/tool-error-remediation.ts +1 -1
- package/src/agent/tool-file-safety.ts +113 -14
- package/src/agent/tool-not-found-nudge.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-render.ts +2 -1
- 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 +25 -7
- package/src/agent/tools/channel-send.ts +51 -9
- package/src/agent/tools/curl-impersonate.ts +11 -2
- package/src/agent/tools/grant-role.ts +2 -2
- package/src/agent/tools/post-github-review.ts +79 -17
- package/src/agent/tools/restart.ts +2 -2
- package/src/agent/tools/skip-response.ts +4 -4
- package/src/agent/tools/spawn-subagent.ts +165 -14
- 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 +10 -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/backup/README.md +10 -9
- package/src/bundled-plugins/backup/runner.ts +140 -58
- package/src/bundled-plugins/backup/subagents.ts +58 -26
- package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
- package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
- package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
- package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
- package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
- package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
- package/src/bundled-plugins/operator/operator.ts +15 -4
- package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
- package/src/bundled-plugins/security/index.ts +50 -2
- package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
- package/src/channels/adapters/discord-bot-reactions.ts +18 -0
- package/src/channels/adapters/discord-bot.ts +122 -67
- package/src/channels/adapters/discord-reactions.ts +18 -0
- package/src/channels/adapters/discord.ts +114 -8
- package/src/channels/adapters/github/inbound.ts +103 -8
- package/src/channels/adapters/github/index.ts +251 -19
- package/src/channels/adapters/github/last-alive.ts +27 -0
- package/src/channels/adapters/github/outbound.ts +54 -18
- package/src/channels/adapters/github/pending-review-store.ts +141 -0
- package/src/channels/adapters/github/permission-guidance.ts +1 -0
- package/src/channels/adapters/github/reactions.ts +100 -0
- package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
- package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
- package/src/channels/adapters/github/recovery.ts +106 -0
- package/src/channels/adapters/github/review-check.ts +510 -0
- package/src/channels/adapters/github/review-submitter.ts +34 -2
- package/src/channels/adapters/instagram.ts +32 -14
- package/src/channels/adapters/kakaotalk.ts +22 -7
- package/src/channels/adapters/line.ts +18 -3
- package/src/channels/adapters/outbound-account.ts +20 -0
- package/src/channels/adapters/own-reactions.ts +66 -0
- package/src/channels/adapters/recovery-correlation.ts +214 -0
- package/src/channels/adapters/slack-bot-classify.ts +18 -11
- package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
- package/src/channels/adapters/slack-bot-reactions.ts +18 -0
- package/src/channels/adapters/slack-bot.ts +125 -57
- package/src/channels/adapters/slack-classify.ts +25 -4
- package/src/channels/adapters/slack-inbound-revision.ts +96 -0
- package/src/channels/adapters/slack-reactions.ts +18 -0
- package/src/channels/adapters/slack-thread-ts.ts +6 -0
- package/src/channels/adapters/slack.ts +48 -3
- package/src/channels/adapters/teams.ts +14 -4
- package/src/channels/adapters/telegram-bot.ts +56 -10
- package/src/channels/adapters/webex-bot.ts +12 -2
- package/src/channels/adapters/webex.ts +12 -2
- package/src/channels/background-handoff.ts +434 -0
- package/src/channels/background-obligations.ts +893 -0
- package/src/channels/continuity-types.ts +271 -0
- package/src/channels/github-review-check.ts +598 -0
- package/src/channels/github-review-turn-ledger.ts +102 -28
- package/src/channels/github-review-verdict-coordinator.ts +96 -13
- package/src/channels/github-token-bridge.ts +11 -5
- package/src/channels/inbound-journal.ts +1738 -0
- package/src/channels/index.ts +6 -1
- package/src/channels/manager.ts +17 -7
- package/src/channels/recovery-dispatcher.ts +264 -0
- package/src/channels/recovery-notice.ts +94 -0
- package/src/channels/recovery-outbox.ts +459 -0
- package/src/channels/router.ts +2582 -633
- package/src/channels/schema.ts +8 -1
- package/src/channels/subagent-completion-bridge.ts +17 -14
- package/src/channels/types.ts +121 -16
- package/src/channels/waiting-reactions.ts +664 -0
- package/src/cli/compose.ts +7 -4
- package/src/cli/hostd.ts +49 -3
- package/src/cli/inspect.ts +11 -14
- package/src/cli/model.ts +7 -5
- package/src/cli/oauth-callbacks.ts +38 -23
- package/src/coding-agent/broker-body.ts +38 -0
- package/src/coding-agent/broker.ts +290 -0
- package/src/coding-agent/claude.ts +95 -0
- package/src/coding-agent/codex.ts +104 -0
- package/src/coding-agent/index.ts +506 -0
- package/src/coding-agent/omo-state.ts +69 -0
- package/src/coding-agent/omo-stream.ts +98 -0
- package/src/coding-agent/omo.ts +192 -0
- package/src/coding-agent/runner.ts +263 -0
- package/src/coding-agent/tool.ts +62 -0
- package/src/coding-agent/worktree.ts +355 -0
- package/src/compose/restart.ts +10 -3
- package/src/compose/start.ts +20 -3
- package/src/config/config.ts +70 -26
- package/src/config/providers.ts +278 -50
- package/src/container/exit-reason.ts +44 -0
- package/src/container/index.ts +5 -0
- package/src/container/log-archive.ts +51 -13
- package/src/container/memory-limit.ts +1 -1
- package/src/container/memory-oversubscription.ts +36 -6
- package/src/container/oom-events.ts +86 -0
- package/src/container/restart.ts +2 -0
- package/src/container/shared.ts +8 -1
- package/src/container/start.ts +25 -13
- package/src/container/stop.ts +6 -2
- package/src/container/tool-oom-priority.ts +32 -0
- package/src/cron/consumer.ts +10 -4
- package/src/cron/reloadable.ts +23 -2
- package/src/doctor/checks.ts +14 -2
- package/src/hostd/daemon.ts +20 -10
- package/src/hostd/spawn.ts +106 -5
- package/src/hostd/version.ts +20 -0
- package/src/hostd/watchdog.ts +241 -0
- package/src/init/dockerfile.ts +57 -592
- package/src/init/index.ts +6 -7
- package/src/init/oauth-login.ts +57 -17
- package/src/inspect/transcript-view.ts +6 -3
- package/src/mcp/client.ts +3 -1
- package/src/operations/classify-tool-outcome.ts +45 -1
- package/src/operations/incidents.ts +10 -5
- package/src/plugin/core-tool-names.ts +1 -1
- package/src/plugin/define.ts +1 -0
- package/src/plugin/index.ts +1 -0
- package/src/plugin/types.ts +6 -1
- package/src/run/background-handoff-boot.ts +86 -0
- package/src/run/channel-session-factory.ts +5 -4
- package/src/run/index.ts +93 -93
- package/src/run/resource-sample.ts +19 -0
- package/src/sandbox/build.ts +4 -0
- package/src/sandbox/coding-agent.ts +214 -0
- package/src/sandbox/policy.ts +1 -0
- package/src/sandbox/runtime-private.ts +4 -1
- package/src/secrets/coding-agent-auth.ts +97 -0
- package/src/secrets/index.ts +0 -16
- 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/command-runner.ts +6 -2
- package/src/server/index.ts +102 -41
- package/src/sessions/index.ts +1 -1
- package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
- package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
- package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
- package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
- package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
- package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
- package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
- package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
- package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
- package/src/skills/typeclaw-config/SKILL.md +24 -24
- package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
- package/src/skills/typeclaw-cron/SKILL.md +1 -1
- package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
- package/src/skills/typeclaw-memory/SKILL.md +3 -3
- package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
- package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
- package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
- package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
- package/src/skills/typeclaw-plugins/SKILL.md +20 -20
- package/src/skills/typeclaw-skills/SKILL.md +19 -2
- package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
- package/src/tui/index.ts +5 -3
- package/src/tui/theme.ts +1 -1
- package/typeclaw.schema.json +44 -2
- package/src/agent/adaptive-thinking-compat.ts +0 -79
- package/src/secrets/claude-credentials-json.ts +0 -129
- package/src/secrets/codex-auth-json.ts +0 -102
- package/src/secrets/export-claude-credentials-file.ts +0 -270
- package/src/secrets/export-codex-auth-file.ts +0 -250
- package/src/secrets/oauth-xai.ts +0 -348
- package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
- package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
- package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
- package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
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
|
-
}
|
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
# Stop hook — schema and gotchas
|
|
2
|
-
|
|
3
|
-
Deep dive for the `Stop` lifecycle hook that powers the done-signal. Read it when the basic hook in `SKILL.md` isn't enough — when the transcript looks stale, the sentinel is malformed, or you need to extract intermediate tool calls from the JSONL.
|
|
4
|
-
|
|
5
|
-
## What fires when
|
|
6
|
-
|
|
7
|
-
Claude Code supports several lifecycle hooks. The two relevant to delegation are:
|
|
8
|
-
|
|
9
|
-
- **`Stop`** — fires every time the _main_ agent finishes responding. This is per-turn, not per-session. A 5-turn conversation fires `Stop` five times. The "task is done" signal is just "the latest Stop, where claude's message looks like a result not a question" — that's the multi-turn decision loop in `SKILL.md`.
|
|
10
|
-
- **`SubagentStop`** — fires when a _sub-agent_ (Task tool, plan-mode sub-agents, etc.) finishes. Sub-agents are claude spawning claude. You don't typically need to handle this — the parent's `Stop` fires after its sub-agents are done. Configure it only if you want progress signals during a sub-agent-heavy turn.
|
|
11
|
-
|
|
12
|
-
Other hooks that exist (`PreToolUse`, `PostToolUse`, `Notification`, `SessionStart`, `SessionEnd`, `PreCompact`, etc.) are out of scope for this skill — they're useful for progress logging, command auditing, or session bookkeeping, but they're not the done-signal.
|
|
13
|
-
|
|
14
|
-
## Stop event JSON schema
|
|
15
|
-
|
|
16
|
-
The hook command receives a single JSON object on stdin. Fields observed in current Claude Code (subject to upstream churn — the docs page is at `https://docs.anthropic.com/en/docs/claude-code/hooks`):
|
|
17
|
-
|
|
18
|
-
```jsonc
|
|
19
|
-
{
|
|
20
|
-
"session_id": "abc123…", // The Claude Code session UUID
|
|
21
|
-
"transcript_path": "/root/.claude/projects/-tmp-cc-foo/abc123.jsonl",
|
|
22
|
-
"cwd": "/tmp/cc-foo", // Should match your worktree path
|
|
23
|
-
"permission_mode": "default", // or "plan", "bypassPermissions", etc.
|
|
24
|
-
"hook_event_name": "Stop", // Literal "Stop" for this event
|
|
25
|
-
"stop_hook_active": false, // True only while the hook itself runs
|
|
26
|
-
"last_assistant_message": "…", // The text of claude's just-finished turn
|
|
27
|
-
}
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
Fields you actually use:
|
|
31
|
-
|
|
32
|
-
- **`last_assistant_message`** — your primary capture for the multi-turn decision loop. Read this from `sentinel.json`, classify (question / permission / result / spurious), act.
|
|
33
|
-
- **`transcript_path`** — points at the JSONL with the full conversation. Useful when `last_assistant_message` isn't enough.
|
|
34
|
-
- **`cwd`** — sanity check. If this isn't `/tmp/cc-<id>`, something is wrong with your tmux spawn (likely missing `-c`).
|
|
35
|
-
- **`session_id`** — useful for logging or if you want to correlate with the JSONL filename.
|
|
36
|
-
|
|
37
|
-
Fields you ignore:
|
|
38
|
-
|
|
39
|
-
- `permission_mode`, `stop_hook_active` — for hook-internal coordination, not delegation logic.
|
|
40
|
-
|
|
41
|
-
### SubagentStop deltas
|
|
42
|
-
|
|
43
|
-
If you ever configure a `SubagentStop` hook, expect these additional fields:
|
|
44
|
-
|
|
45
|
-
```jsonc
|
|
46
|
-
{
|
|
47
|
-
"agent_id": "def456…",
|
|
48
|
-
"agent_transcript_path": "/root/.claude/projects/-tmp-cc-foo/abc123/subagents/agent-def456.jsonl",
|
|
49
|
-
}
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
The schema is otherwise the same. `agent_transcript_path` is a separate JSONL per sub-agent.
|
|
53
|
-
|
|
54
|
-
## The transcript JSONL
|
|
55
|
-
|
|
56
|
-
`transcript_path` points at a JSONL file with one JSON object per line. Anthropic does not publish a formal schema — community tools (claudeoo, maury, serac) have reverse-engineered it. What you'll see:
|
|
57
|
-
|
|
58
|
-
- **`{ "type": "user", "message": { … } }`** — what you sent claude (or what the upstream parent sent, for sub-agents).
|
|
59
|
-
- **`{ "type": "assistant", "message": { "content": [ … ] } }`** — claude's response. `content` is an array of `{ "type": "text", "text": "…" }` and `{ "type": "tool_use", … }` objects.
|
|
60
|
-
- **`{ "type": "tool_use", "name": "Read", "input": { … } }`** — tool calls claude made.
|
|
61
|
-
- **`{ "type": "tool_result", "tool_use_id": "…", "content": "…" }`** — tool results.
|
|
62
|
-
- **`{ "type": "system", "subtype": "…" }`** — system events: `compact_boundary`, `turn_duration`, `stop_hook_summary`, etc.
|
|
63
|
-
- **`{ "type": "attachment", … }`** — file uploads or contextual attachments.
|
|
64
|
-
|
|
65
|
-
To extract claude's final text answer when `last_assistant_message` isn't enough:
|
|
66
|
-
|
|
67
|
-
```sh
|
|
68
|
-
# Read every assistant-text content line from the JSONL
|
|
69
|
-
jq -r 'select(.type == "assistant") | .message.content[] | select(.type == "text") | .text' "$transcript_path"
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
Filter further by timestamp or message-id if you only want the last turn.
|
|
73
|
-
|
|
74
|
-
## Documented race conditions
|
|
75
|
-
|
|
76
|
-
Three known races, all from upstream Claude Code issues. The skill body's design avoids them by preferring the sentinel over the JSONL; this is the reasoning if you have to debug:
|
|
77
|
-
|
|
78
|
-
1. **Stale transcript on Stop (#15813).** The `Stop` hook can fire before the last assistant message is flushed to the JSONL. If you read `transcript_path` immediately on hook fire, the last message may not be there yet. **Mitigation:** use `last_assistant_message` from the hook's stdin JSON as the primary capture; treat the JSONL as the backup, with a 1–2 second wait if it looks stale.
|
|
79
|
-
2. **Missing transcript file (#20612, #30217).** Some users report `transcript_path` pointing at a file that doesn't exist, especially in multi-session or concurrent-worktree setups. **Mitigation:** capture `last_assistant_message` on every Stop and accumulate it yourself if you need the full history. Falling back to `tmux capture-pane -S -` is the last-resort path.
|
|
80
|
-
3. **Inaccurate final token counts (#27361).** The JSONL has historically missed the final `message_stop` SSE event, causing `output_tokens` to be a mid-stream snapshot (sometimes undercounted by ~2x). **Mitigation:** don't rely on JSONL token counts for cost calculations; the Anthropic Console workspace usage is the authoritative source.
|
|
81
|
-
|
|
82
|
-
## Permission prompts vs Stop
|
|
83
|
-
|
|
84
|
-
A subtle point that confuses the multi-turn decision loop: **permission prompts do not fire `Stop`**. When claude is waiting for a "Allow this command?" yes/no, the turn isn't over — the model is waiting for the _user_ (you) to type y/n into the TUI, not waiting for a new prompt. So:
|
|
85
|
-
|
|
86
|
-
- **Permission prompt appears** → no `Stop`, no `.done`, you keep polling.
|
|
87
|
-
- **You answer the prompt** (via `tmux send-keys "y" Enter`) → claude continues working, eventually finishes its turn → `Stop` fires.
|
|
88
|
-
|
|
89
|
-
This is why the multi-turn loop's classification is "ends with question mark / contains 'Do you want me to'" — it's looking for _content-level_ questions claude wrote as part of its response, not permission-tool prompts. Permission prompts don't reach `last_assistant_message`; they only appear in the pane.
|
|
90
|
-
|
|
91
|
-
If you need to detect permission prompts (to auto-answer them), `capture-pane` is the only signal. Look for the literal yes/no UI affordance at the bottom of the pane. This is risky to automate — you're answering on the user's behalf for an operation you can't see the full safety implications of. Default behavior in this skill: pause polling for the sentinel, look at the pane after the budget elapses without a `.done`, and if there's a permission prompt sitting there, surface to the user rather than auto-answering.
|
|
92
|
-
|
|
93
|
-
## Things you must not do with the Stop hook
|
|
94
|
-
|
|
95
|
-
- **Do not write a per-worktree `.claude/settings.json` from operator code.** The hook is pre-baked into the image at build time (see `src/init/dockerfile.ts`, constants `TYPECLAW_CC_STOP_HOOK_PATH` and `TYPECLAW_CC_GLOBAL_SETTINGS`) precisely so the operator subagent never has to construct the JSON itself. Past delegations failed by inventing wrong shapes like `{"hooks": {"onStop": "./script.sh"}}` (wrong key — Claude Code's event name is literal `Stop`, no `on` prefix), `{"hooks": {"Stop": "./script.sh"}}` (right key, wrong value type — must be an array of matcher objects, not a string), and `{"hooks": {"Stop": [{"command": "./script.sh"}]}}` (missing the `matcher` and the inner `hooks` array — the schema is two levels of nesting, not one). All three slips silently fail: Claude Code ignores unknown keys, so the hook is never registered, `.done` is never created, and the polling loop times out at its wall-clock budget. If you ever find yourself wanting to write a per-worktree settings file, **stop** — either the global hook isn't installed (verify with the `jq` check in `SKILL.md`'s "The Stop hook" section) or you're trying to customize behavior the skill's flow doesn't anticipate. In the former case, bail to the user; in the latter, the right answer is a code change to `src/init/dockerfile.ts`, not a runtime JSON write.
|
|
96
|
-
- **Do not edit the in-Dockerfile hook config in a way that bypasses `JSON.stringify` + the regression test.** `TYPECLAW_CC_GLOBAL_SETTINGS` in `src/init/dockerfile.ts` is constructed via `JSON.stringify` so any structural drift fails `dockerfile.test.ts`'s `JSON.parse` regression test, not the docker build or (worse) the first failed delegation. Hand-writing the JSON as a string literal would let a typo land in production. The accepted shape is exactly `{"hooks": {"Stop": [{"matcher": "*", "hooks": [{"type": "command", "command": "..."}]}]}}`.
|
|
97
|
-
- **Do not set `matcher` to anything other than `"*"`.** The matcher filters by hook tool name; for `Stop`, there's no tool — `"*"` is the canonical "fire on every Stop". Other values may silently never match.
|
|
98
|
-
- **Do not put long-running commands in the hook.** The hook runs synchronously on the Claude Code main loop; a slow hook blocks the user's next prompt. Write the payload + touch a flag + exit. Anything heavier belongs in your polling loop, not the hook.
|
|
99
|
-
- **Do not skip the temp-file rename pattern.** Writing `sentinel.json` directly with `>` lets readers see partial JSON if they poll mid-write. Always `cat > sentinel.json.tmp && mv sentinel.json.tmp sentinel.json`.
|
|
100
|
-
- **Do not delete `transcript_path` from inside the hook.** The path is shared with `SessionEnd` and other lifecycle events; deleting it breaks downstream hooks.
|
|
101
|
-
- **Do not log the full hook payload to a place you don't control.** It contains `last_assistant_message`, which can contain anything claude said — including code, secrets the user pasted, or private context. Sentinel is fine (it's in `/tmp/`); piping to a shared log is not.
|