typeclaw 0.48.13 → 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 +5 -5
- package/scripts/dump-system-prompt.ts +52 -110
- package/src/agent/index.ts +144 -72
- package/src/agent/live-sessions.ts +2 -2
- package/src/agent/live-subagents.ts +1 -0
- package/src/agent/plugin-tools.ts +53 -11
- package/src/agent/prompt-cache-key.ts +42 -0
- package/src/agent/provider-error.ts +179 -10
- 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 +13 -1
- package/src/agent/system-prompt.ts +68 -202
- package/src/agent/todo/continuation-policy.ts +12 -4
- package/src/agent/tool-file-safety.ts +113 -14
- package/src/agent/tool-not-found-nudge.ts +1 -1
- package/src/agent/tools/channel-history-render.ts +2 -1
- package/src/agent/tools/channel-reply.ts +23 -5
- package/src/agent/tools/channel-send.ts +49 -7
- package/src/agent/tools/curl-impersonate.ts +11 -2
- package/src/agent/tools/post-github-review.ts +77 -15
- package/src/agent/tools/skip-response.ts +2 -2
- package/src/agent/tools/spawn-subagent.ts +163 -12
- package/src/agent/tools/subagent-output.ts +8 -0
- 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 +72 -12
- 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 +2539 -615
- 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/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 +10 -3
- package/src/config/providers.ts +12 -9
- 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 +2 -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/index.ts +83 -83
- 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/server/command-runner.ts +6 -2
- package/src/server/index.ts +101 -40
- 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 +21 -21
- 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 +15 -15
- package/src/skills/typeclaw-skills/SKILL.md +19 -2
- package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
- package/typeclaw.schema.json +12 -1
- 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/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/typeclaw.schema.json
CHANGED
|
@@ -1074,7 +1074,8 @@
|
|
|
1074
1074
|
"review": {
|
|
1075
1075
|
"default": {
|
|
1076
1076
|
"on": "review_requested",
|
|
1077
|
-
"approve": true
|
|
1077
|
+
"approve": true,
|
|
1078
|
+
"check": true
|
|
1078
1079
|
},
|
|
1079
1080
|
"type": "object",
|
|
1080
1081
|
"properties": {
|
|
@@ -1090,6 +1091,10 @@
|
|
|
1090
1091
|
"approve": {
|
|
1091
1092
|
"default": true,
|
|
1092
1093
|
"type": "boolean"
|
|
1094
|
+
},
|
|
1095
|
+
"check": {
|
|
1096
|
+
"default": true,
|
|
1097
|
+
"type": "boolean"
|
|
1093
1098
|
}
|
|
1094
1099
|
}
|
|
1095
1100
|
}
|
|
@@ -2658,6 +2663,7 @@
|
|
|
2658
2663
|
"xvfb": true,
|
|
2659
2664
|
"claudeCode": false,
|
|
2660
2665
|
"codexCli": false,
|
|
2666
|
+
"omoCli": false,
|
|
2661
2667
|
"append": []
|
|
2662
2668
|
}
|
|
2663
2669
|
},
|
|
@@ -2674,6 +2680,7 @@
|
|
|
2674
2680
|
"xvfb": true,
|
|
2675
2681
|
"claudeCode": false,
|
|
2676
2682
|
"codexCli": false,
|
|
2683
|
+
"omoCli": false,
|
|
2677
2684
|
"append": []
|
|
2678
2685
|
},
|
|
2679
2686
|
"type": "object",
|
|
@@ -2746,6 +2753,10 @@
|
|
|
2746
2753
|
"default": false,
|
|
2747
2754
|
"type": "boolean"
|
|
2748
2755
|
},
|
|
2756
|
+
"omoCli": {
|
|
2757
|
+
"default": false,
|
|
2758
|
+
"type": "boolean"
|
|
2759
|
+
},
|
|
2749
2760
|
"append": {
|
|
2750
2761
|
"default": [],
|
|
2751
2762
|
"type": "array",
|
|
@@ -1,129 +0,0 @@
|
|
|
1
|
-
import type { ProviderCredential } from './schema'
|
|
2
|
-
|
|
3
|
-
// Emit the on-disk shape Claude Code consumes at ~/.claude/.credentials.json
|
|
4
|
-
// (Linux/Windows; macOS keeps this same JSON inside the Keychain entry
|
|
5
|
-
// "Claude Code-credentials"). The single required top-level key is
|
|
6
|
-
// `claudeAiOauth`. Field names use camelCase, not snake_case — diverging
|
|
7
|
-
// from Codex CLI's `tokens.access_token` shape but matching every
|
|
8
|
-
// third-party Claude Code integration we surveyed (ATLAS_OS, OmniRoute,
|
|
9
|
-
// jcode, paperclip, opencode-claude-auth).
|
|
10
|
-
//
|
|
11
|
-
// `expiresAt` is MILLISECONDS since epoch, not seconds and not ISO. The
|
|
12
|
-
// CLI carries no top-level expiry field outside `claudeAiOauth` — token
|
|
13
|
-
// expiry is recorded both as `expiresAt` here and embedded in the JWT
|
|
14
|
-
// `exp` claim of `accessToken`. The runtime exporter (export-claude-
|
|
15
|
-
// credentials-file.ts) uses the JWT exp for its newer-wins compare,
|
|
16
|
-
// mirroring the Codex CLI exporter's approach, because `expiresAt` is
|
|
17
|
-
// the field Claude Code itself rewrites on in-place refresh.
|
|
18
|
-
//
|
|
19
|
-
// `mcpOAuth` (MCP server OAuth state) may coexist alongside
|
|
20
|
-
// `claudeAiOauth` in the same file. This emitter accepts an optional
|
|
21
|
-
// `preserveMcpOAuth` block so callers that read-merge-write the file
|
|
22
|
-
// don't drop unrelated state. Codex CLI's file is fully owned by the
|
|
23
|
-
// OAuth credential and has no equivalent; this is the one extra
|
|
24
|
-
// complication versus emitCodexAuthJson.
|
|
25
|
-
export type ClaudeAiOauthBlock = {
|
|
26
|
-
accessToken: string
|
|
27
|
-
refreshToken: string
|
|
28
|
-
expiresAt: number
|
|
29
|
-
scopes?: string[]
|
|
30
|
-
subscriptionType?: string
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export type EmitClaudeCredentialsJsonOptions = {
|
|
34
|
-
preserveMcpOAuth?: unknown
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function emitClaudeCredentialsJson(
|
|
38
|
-
credential: ProviderCredential,
|
|
39
|
-
options: EmitClaudeCredentialsJsonOptions = {},
|
|
40
|
-
): string {
|
|
41
|
-
if (credential.type !== 'oauth') {
|
|
42
|
-
throw new Error('emitClaudeCredentialsJson only accepts oauth-typed credentials')
|
|
43
|
-
}
|
|
44
|
-
const fields = credential as ProviderCredential & {
|
|
45
|
-
access?: unknown
|
|
46
|
-
refresh?: unknown
|
|
47
|
-
expires?: unknown
|
|
48
|
-
scopes?: unknown
|
|
49
|
-
subscriptionType?: unknown
|
|
50
|
-
}
|
|
51
|
-
const access = fields.access
|
|
52
|
-
const refresh = fields.refresh
|
|
53
|
-
if (typeof access !== 'string' || access.length === 0) {
|
|
54
|
-
throw new Error('credential is missing a non-empty `access` field')
|
|
55
|
-
}
|
|
56
|
-
if (typeof refresh !== 'string' || refresh.length === 0) {
|
|
57
|
-
throw new Error('credential is missing a non-empty `refresh` field')
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Resolution order for `expiresAt`:
|
|
61
|
-
// 1. `expires` on the credential (pi-ai writes absolute ms epoch here).
|
|
62
|
-
// 2. JWT `exp` claim decoded from `access`.
|
|
63
|
-
// 3. 0 — Claude Code treats a missing/zero expiry as "expired" and
|
|
64
|
-
// triggers an immediate refresh on next use, which is the safe
|
|
65
|
-
// fallback when neither source is available.
|
|
66
|
-
const expiresAt = readExpiryMs(fields, access)
|
|
67
|
-
|
|
68
|
-
const claudeAiOauth: ClaudeAiOauthBlock = {
|
|
69
|
-
accessToken: access,
|
|
70
|
-
refreshToken: refresh,
|
|
71
|
-
expiresAt,
|
|
72
|
-
}
|
|
73
|
-
if (Array.isArray(fields.scopes) && fields.scopes.every((s): s is string => typeof s === 'string')) {
|
|
74
|
-
claudeAiOauth.scopes = fields.scopes
|
|
75
|
-
}
|
|
76
|
-
if (typeof fields.subscriptionType === 'string' && fields.subscriptionType.length > 0) {
|
|
77
|
-
claudeAiOauth.subscriptionType = fields.subscriptionType
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// Read-merge-write: preserve any existing `mcpOAuth` block the caller
|
|
81
|
-
// supplied. The emitter doesn't read disk itself (that's the exporter's
|
|
82
|
-
// job); the caller passes whatever it found at the existing file path.
|
|
83
|
-
const out: Record<string, unknown> = { claudeAiOauth }
|
|
84
|
-
if (options.preserveMcpOAuth !== undefined) {
|
|
85
|
-
out['mcpOAuth'] = options.preserveMcpOAuth
|
|
86
|
-
}
|
|
87
|
-
return `${JSON.stringify(out, null, 2)}\n`
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
// Extracts the JWT `exp` claim (seconds since epoch) and converts to ms.
|
|
91
|
-
// Used by the runtime exporter's newer-wins compare and by emit's
|
|
92
|
-
// `expiresAt` fallback. Returns null on any decode failure; the caller
|
|
93
|
-
// treats that as "unknown freshness". Logic mirrors
|
|
94
|
-
// decodeCodexAccessTokenExpiryMs verbatim — Claude Code OAuth access
|
|
95
|
-
// tokens are standard JWTs with the same base64url-encoded payload
|
|
96
|
-
// shape Codex uses.
|
|
97
|
-
export function decodeClaudeAccessTokenExpiryMs(accessToken: string): number | null {
|
|
98
|
-
const parts = accessToken.split('.')
|
|
99
|
-
if (parts.length !== 3) return null
|
|
100
|
-
const middle = parts[1] ?? ''
|
|
101
|
-
if (middle === '') return null
|
|
102
|
-
const normalized = middle.replace(/-/g, '+').replace(/_/g, '/')
|
|
103
|
-
const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)
|
|
104
|
-
let payload: Record<string, unknown>
|
|
105
|
-
try {
|
|
106
|
-
const decoded = typeof atob === 'function' ? atob(padded) : Buffer.from(padded, 'base64').toString('utf8')
|
|
107
|
-
const parsed: unknown = JSON.parse(decoded)
|
|
108
|
-
if (!isPlainObject(parsed)) return null
|
|
109
|
-
payload = parsed
|
|
110
|
-
} catch {
|
|
111
|
-
return null
|
|
112
|
-
}
|
|
113
|
-
const exp = payload['exp']
|
|
114
|
-
if (typeof exp !== 'number' || !Number.isFinite(exp)) return null
|
|
115
|
-
return Math.floor(exp * 1000)
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
function readExpiryMs(fields: { expires?: unknown }, accessToken: string): number {
|
|
119
|
-
if (typeof fields.expires === 'number' && Number.isFinite(fields.expires)) {
|
|
120
|
-
return fields.expires
|
|
121
|
-
}
|
|
122
|
-
const fromJwt = decodeClaudeAccessTokenExpiryMs(accessToken)
|
|
123
|
-
if (fromJwt !== null) return fromJwt
|
|
124
|
-
return 0
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
128
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
129
|
-
}
|
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
import type { ProviderCredential } from './schema'
|
|
2
|
-
|
|
3
|
-
// Emit the on-disk shape Codex CLI consumes at ~/.codex/auth.json: a `tokens`
|
|
4
|
-
// object with id_token, access_token, refresh_token, and optional account_id.
|
|
5
|
-
// No top-level `expires` — codex re-derives expiry from the JWT `exp` claim.
|
|
6
|
-
//
|
|
7
|
-
// id_token is load-bearing: codex's deserializer (token_data.rs) declares
|
|
8
|
-
// `id_token: IdTokenInfo` with no Option/#[serde(default)], so omitting it
|
|
9
|
-
// fails the whole auth.json load with `missing field id_token` before any
|
|
10
|
-
// model call. codex parses it via `parse_chatgpt_jwt_claims`, which accepts
|
|
11
|
-
// any decodable 3-part JWT and treats every claim as optional.
|
|
12
|
-
//
|
|
13
|
-
// We prefer a real captured id_token (`idToken`/`id_token` on the credential,
|
|
14
|
-
// e.g. from a future pi-ai that persists it) and fall back to `access`. The
|
|
15
|
-
// fallback is sound because this flow's access token is itself a ChatGPT-claims
|
|
16
|
-
// JWT (carries `https://api.openai.com/auth`), so codex reads the same
|
|
17
|
-
// plan/account fields from it — self-healing agents whose stored credential
|
|
18
|
-
// predates id_token capture, without a re-login.
|
|
19
|
-
export function emitCodexAuthJson(credential: ProviderCredential): string {
|
|
20
|
-
if (credential.type !== 'oauth') {
|
|
21
|
-
throw new Error('emitCodexAuthJson only accepts oauth-typed credentials')
|
|
22
|
-
}
|
|
23
|
-
const fields = credential as ProviderCredential & {
|
|
24
|
-
access?: unknown
|
|
25
|
-
refresh?: unknown
|
|
26
|
-
accountId?: unknown
|
|
27
|
-
idToken?: unknown
|
|
28
|
-
id_token?: unknown
|
|
29
|
-
}
|
|
30
|
-
const access = fields.access
|
|
31
|
-
const refresh = fields.refresh
|
|
32
|
-
if (typeof access !== 'string' || access.length === 0) {
|
|
33
|
-
throw new Error('credential is missing a non-empty `access` field')
|
|
34
|
-
}
|
|
35
|
-
if (typeof refresh !== 'string' || refresh.length === 0) {
|
|
36
|
-
throw new Error('credential is missing a non-empty `refresh` field')
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const capturedIdToken = firstNonEmptyString(fields.idToken, fields.id_token)
|
|
40
|
-
const idToken = capturedIdToken ?? access
|
|
41
|
-
|
|
42
|
-
const tokens: Record<string, string> = {
|
|
43
|
-
id_token: idToken,
|
|
44
|
-
access_token: access,
|
|
45
|
-
refresh_token: refresh,
|
|
46
|
-
}
|
|
47
|
-
if (typeof fields.accountId === 'string' && fields.accountId.length > 0) {
|
|
48
|
-
tokens['account_id'] = fields.accountId
|
|
49
|
-
}
|
|
50
|
-
return `${JSON.stringify({ tokens }, null, 2)}\n`
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function firstNonEmptyString(...values: unknown[]): string | null {
|
|
54
|
-
for (const value of values) {
|
|
55
|
-
if (typeof value === 'string' && value.length > 0) return value
|
|
56
|
-
}
|
|
57
|
-
return null
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Extracts the JWT `exp` claim (seconds since epoch) and converts to ms.
|
|
61
|
-
// Used by the runtime exporter's newer-wins compare: ~/.codex/auth.json
|
|
62
|
-
// carries no top-level expiry, but the JWT inside `tokens.access_token`
|
|
63
|
-
// does. Returns null on any decode failure; the caller treats that as
|
|
64
|
-
// "unknown freshness" and falls back to overwriting from typeclaw's copy.
|
|
65
|
-
export function decodeCodexAccessTokenExpiryMs(accessToken: string): number | null {
|
|
66
|
-
const payload = decodeJwtPayload(accessToken)
|
|
67
|
-
if (payload === null) return null
|
|
68
|
-
const exp = payload['exp']
|
|
69
|
-
if (typeof exp !== 'number' || !Number.isFinite(exp)) return null
|
|
70
|
-
return Math.floor(exp * 1000)
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// True when the string decodes the way codex's `decode_jwt_payload` requires:
|
|
74
|
-
// three non-empty dot-separated parts with a base64url payload that is a JSON
|
|
75
|
-
// object. codex runs exactly this on `tokens.id_token` (via
|
|
76
|
-
// `parse_chatgpt_jwt_claims`) and rejects the whole auth.json if it fails, so
|
|
77
|
-
// the exporter uses this to decide whether an on-disk id_token is usable —
|
|
78
|
-
// not just non-empty.
|
|
79
|
-
export function isDecodableJwt(token: string): boolean {
|
|
80
|
-
return decodeJwtPayload(token) !== null
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function decodeJwtPayload(jwt: string): Record<string, unknown> | null {
|
|
84
|
-
const parts = jwt.split('.')
|
|
85
|
-
if (parts.length !== 3) return null
|
|
86
|
-
const middle = parts[1] ?? ''
|
|
87
|
-
if (middle === '') return null
|
|
88
|
-
// base64url → base64, then pad to a multiple of 4 (atob is strict).
|
|
89
|
-
const normalized = middle.replace(/-/g, '+').replace(/_/g, '/')
|
|
90
|
-
const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)
|
|
91
|
-
try {
|
|
92
|
-
const decoded = typeof atob === 'function' ? atob(padded) : Buffer.from(padded, 'base64').toString('utf8')
|
|
93
|
-
const parsed: unknown = JSON.parse(decoded)
|
|
94
|
-
return isPlainObject(parsed) ? parsed : null
|
|
95
|
-
} catch {
|
|
96
|
-
return null
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
101
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
102
|
-
}
|
|
@@ -1,270 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
chmodSync,
|
|
3
|
-
mkdirSync,
|
|
4
|
-
readFileSync,
|
|
5
|
-
readlinkSync,
|
|
6
|
-
renameSync,
|
|
7
|
-
statSync,
|
|
8
|
-
unlinkSync,
|
|
9
|
-
writeFileSync,
|
|
10
|
-
} from 'node:fs'
|
|
11
|
-
import { homedir } from 'node:os'
|
|
12
|
-
import { dirname, isAbsolute, join, posix, resolve } from 'node:path'
|
|
13
|
-
|
|
14
|
-
import { decodeClaudeAccessTokenExpiryMs, emitClaudeCredentialsJson } from './claude-credentials-json'
|
|
15
|
-
import type { ProviderCredential, Providers } from './schema'
|
|
16
|
-
import { SecretsBackend } from './storage'
|
|
17
|
-
|
|
18
|
-
const FILE_MODE = 0o600
|
|
19
|
-
const DIR_MODE = 0o700
|
|
20
|
-
export const CLAUDE_CREDENTIALS_FILE_NAME = '.credentials.json'
|
|
21
|
-
export const CLAUDE_DEFAULT_CONFIG_DIR_NAME = '.claude'
|
|
22
|
-
export const CLAUDE_CREDENTIALS_RELATIVE_PATH = posix.join(CLAUDE_DEFAULT_CONFIG_DIR_NAME, CLAUDE_CREDENTIALS_FILE_NAME)
|
|
23
|
-
|
|
24
|
-
export type ExportClaudeCredentialsFileResult =
|
|
25
|
-
| { action: 'skipped'; reason: SkipReason }
|
|
26
|
-
| { action: 'wrote'; path: string }
|
|
27
|
-
| { action: 'failed'; reason: string }
|
|
28
|
-
|
|
29
|
-
export type SkipReason =
|
|
30
|
-
| 'claude-code-disabled'
|
|
31
|
-
| 'no-anthropic-credential'
|
|
32
|
-
| 'credential-not-oauth'
|
|
33
|
-
| 'on-disk-is-fresher'
|
|
34
|
-
|
|
35
|
-
export type ExportClaudeCredentialsFileOptions = {
|
|
36
|
-
claudeCodeEnabled: boolean
|
|
37
|
-
providers: Providers
|
|
38
|
-
homeDir?: string
|
|
39
|
-
configDir?: string
|
|
40
|
-
now?: () => number
|
|
41
|
-
log?: (message: string) => void
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// Writes typeclaw's anthropic OAuth credential to
|
|
45
|
-
// $CLAUDE_CONFIG_DIR/.credentials.json (or $HOME/.claude/.credentials.json
|
|
46
|
-
// by default) when it's safe to do so. Container HOME is /home/agent and
|
|
47
|
-
// ephemeral; this boot-time export reconstructs the CLI file from secrets.json
|
|
48
|
-
// after provider OAuth refresh has updated the canonical credential.
|
|
49
|
-
//
|
|
50
|
-
// Three guards, cheapest first. The first two return without ever touching
|
|
51
|
-
// the filesystem, which keeps the 90% case (users who don't enable
|
|
52
|
-
// Claude Code) at zero overhead on every container start.
|
|
53
|
-
export function exportClaudeCredentialsFileIfApplicable(
|
|
54
|
-
options: ExportClaudeCredentialsFileOptions,
|
|
55
|
-
): ExportClaudeCredentialsFileResult {
|
|
56
|
-
if (!options.claudeCodeEnabled) return { action: 'skipped', reason: 'claude-code-disabled' }
|
|
57
|
-
|
|
58
|
-
const credential = options.providers['anthropic']
|
|
59
|
-
if (credential === undefined) return { action: 'skipped', reason: 'no-anthropic-credential' }
|
|
60
|
-
if (credential.type !== 'oauth') return { action: 'skipped', reason: 'credential-not-oauth' }
|
|
61
|
-
|
|
62
|
-
const targetPath = resolveClaudeCredentialsPath({
|
|
63
|
-
...(options.homeDir !== undefined ? { homeDir: options.homeDir } : {}),
|
|
64
|
-
...(options.configDir !== undefined ? { configDir: options.configDir } : {}),
|
|
65
|
-
})
|
|
66
|
-
|
|
67
|
-
try {
|
|
68
|
-
const existing = readExisting(targetPath)
|
|
69
|
-
if (!shouldOverwrite(existing, credential, options.now ?? Date.now)) {
|
|
70
|
-
return { action: 'skipped', reason: 'on-disk-is-fresher' }
|
|
71
|
-
}
|
|
72
|
-
const mcpOAuthOpt = existing?.mcpOAuth !== undefined ? { preserveMcpOAuth: existing.mcpOAuth } : {}
|
|
73
|
-
const contents = emitClaudeCredentialsJson(credential, mcpOAuthOpt)
|
|
74
|
-
writeAtomic(targetPath, contents)
|
|
75
|
-
return { action: 'wrote', path: targetPath }
|
|
76
|
-
} catch (err) {
|
|
77
|
-
const reason = err instanceof Error ? err.message : String(err)
|
|
78
|
-
options.log?.(`exportClaudeCredentialsFile: ${reason}`)
|
|
79
|
-
return { action: 'failed', reason }
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
type ExistingFile = {
|
|
84
|
-
onDiskAccessToken: string | null
|
|
85
|
-
onDiskExpiresAt: number | null
|
|
86
|
-
mcpOAuth: unknown
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// Read once, parse once. Returns null when the file is missing OR
|
|
90
|
-
// unparseable. Returning null short-circuits both branches of the
|
|
91
|
-
// overwrite decision (the no-disk-file recovery path) AND drops any
|
|
92
|
-
// non-recoverable mcpOAuth state — but if the file is unparseable
|
|
93
|
-
// there's nothing to recover anyway. When parsing succeeds, we hand
|
|
94
|
-
// back the access token (for the newer-wins compare) and the raw
|
|
95
|
-
// mcpOAuth block (for read-merge-write preservation).
|
|
96
|
-
function readExisting(targetPath: string): ExistingFile | null {
|
|
97
|
-
let raw: string
|
|
98
|
-
try {
|
|
99
|
-
raw = readFileSync(targetPath, 'utf8')
|
|
100
|
-
} catch {
|
|
101
|
-
return null
|
|
102
|
-
}
|
|
103
|
-
let parsed: unknown
|
|
104
|
-
try {
|
|
105
|
-
parsed = JSON.parse(raw)
|
|
106
|
-
} catch {
|
|
107
|
-
return null
|
|
108
|
-
}
|
|
109
|
-
if (typeof parsed !== 'object' || parsed === null) return null
|
|
110
|
-
const obj = parsed as Record<string, unknown>
|
|
111
|
-
const claudeBlock = obj['claudeAiOauth']
|
|
112
|
-
let onDiskAccessToken: string | null = null
|
|
113
|
-
let onDiskExpiresAt: number | null = null
|
|
114
|
-
if (typeof claudeBlock === 'object' && claudeBlock !== null) {
|
|
115
|
-
const claudeObj = claudeBlock as Record<string, unknown>
|
|
116
|
-
const access = claudeObj['accessToken']
|
|
117
|
-
if (typeof access === 'string' && access.length > 0) onDiskAccessToken = access
|
|
118
|
-
const expiresAt = claudeObj['expiresAt']
|
|
119
|
-
if (typeof expiresAt === 'number' && Number.isFinite(expiresAt) && expiresAt > 0) {
|
|
120
|
-
onDiskExpiresAt = expiresAt
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
return { onDiskAccessToken, onDiskExpiresAt, mcpOAuth: obj['mcpOAuth'] }
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// Newer-wins: skip the write unless typeclaw's stored credential is
|
|
127
|
-
// strictly fresher than the on-disk expiry. Claude Code rotates tokens
|
|
128
|
-
// in-place (issue #53063 in anthropics/claude-code confirms it rewrites
|
|
129
|
-
// .credentials.json with a fresher accessToken/refreshToken/expiresAt
|
|
130
|
-
// on every successful refresh), so on a restart the file may legitimately
|
|
131
|
-
// be ahead of secrets.json. We must not clobber that.
|
|
132
|
-
//
|
|
133
|
-
// Ties skip: when expiries match there's nothing to gain from a write,
|
|
134
|
-
// and avoiding the I/O keeps the steady state at zero churn.
|
|
135
|
-
//
|
|
136
|
-
// existing === null OR existing.onDiskAccessToken === null OR expiry
|
|
137
|
-
// undecodable from both expiresAt and JWT → return true. That's the "we
|
|
138
|
-
// have a valid credential, the file is unusable, replace it" recovery case.
|
|
139
|
-
function shouldOverwrite(
|
|
140
|
-
existing: ExistingFile | null,
|
|
141
|
-
credential: ProviderCredential & { expires?: unknown; access?: unknown },
|
|
142
|
-
now: () => number,
|
|
143
|
-
): boolean {
|
|
144
|
-
if (existing === null) return true
|
|
145
|
-
if (existing.onDiskAccessToken === null) return true
|
|
146
|
-
const onDiskExpiry = readOnDiskExpiry(existing)
|
|
147
|
-
if (onDiskExpiry === null) return true
|
|
148
|
-
const credentialExpiry = readCredentialExpiry(credential, now)
|
|
149
|
-
return credentialExpiry > onDiskExpiry
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function readOnDiskExpiry(existing: ExistingFile): number | null {
|
|
153
|
-
if (existing.onDiskExpiresAt !== null) return existing.onDiskExpiresAt
|
|
154
|
-
if (existing.onDiskAccessToken === null) return null
|
|
155
|
-
return decodeClaudeAccessTokenExpiryMs(existing.onDiskAccessToken)
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
// Resolution order for the credential's expiry:
|
|
159
|
-
// 1. The `expires` field pi-ai writes (absolute ms epoch).
|
|
160
|
-
// 2. The JWT `exp` claim decoded from `access`.
|
|
161
|
-
// 3. Now — guarantees we still write on first boot when the credential
|
|
162
|
-
// lacks both, rather than silently skipping forever.
|
|
163
|
-
function readCredentialExpiry(credential: { expires?: unknown; access?: unknown }, now: () => number): number {
|
|
164
|
-
if (typeof credential.expires === 'number' && Number.isFinite(credential.expires)) {
|
|
165
|
-
return credential.expires
|
|
166
|
-
}
|
|
167
|
-
if (typeof credential.access === 'string') {
|
|
168
|
-
const fromJwt = decodeClaudeAccessTokenExpiryMs(credential.access)
|
|
169
|
-
if (fromJwt !== null) return fromJwt
|
|
170
|
-
}
|
|
171
|
-
return now()
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
export function resolveClaudeCredentialsPath(options: { homeDir?: string; configDir?: string } = {}): string {
|
|
175
|
-
const configDir = resolveClaudeConfigDir(options.configDir)
|
|
176
|
-
if (configDir !== null) return join(configDir, CLAUDE_CREDENTIALS_FILE_NAME)
|
|
177
|
-
return join(options.homeDir ?? homedir(), CLAUDE_CREDENTIALS_RELATIVE_PATH)
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
function resolveClaudeConfigDir(configDir: string | undefined): string | null {
|
|
181
|
-
const raw = configDir ?? process.env['CLAUDE_CONFIG_DIR']
|
|
182
|
-
const trimmed = raw?.trim()
|
|
183
|
-
return trimmed === undefined || trimmed.length === 0 ? null : trimmed
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
// Atomic temp-then-rename, mirroring export-codex-auth-file.ts's
|
|
187
|
-
// writeAtomic. The directory is created with 0700 and the file with 0600
|
|
188
|
-
// because the credential carries a long-lived refresh token — leaking it
|
|
189
|
-
// via lax permissions defeats the whole point. The 0600 chmod after
|
|
190
|
-
// rename is belt-and-suspenders: writeFileSync's `mode` is applied at
|
|
191
|
-
// create time, but umask can mask it down on some filesystems.
|
|
192
|
-
//
|
|
193
|
-
// Symlink preservation remains a safety property even though TypeClaw no longer
|
|
194
|
-
// plants one here. An operator or external tool may preconfigure the credentials
|
|
195
|
-
// path as a symlink; POSIX rename(2) replaces that directory entry instead of
|
|
196
|
-
// following it. Resolve the target and rename there so the caller's symlink
|
|
197
|
-
// survives. The temp file MUST live alongside the real target because
|
|
198
|
-
// renameSync across filesystems fails with EXDEV.
|
|
199
|
-
function writeAtomic(targetPath: string, contents: string): void {
|
|
200
|
-
const realTarget = resolveSymlinkTarget(targetPath)
|
|
201
|
-
const dir = dirname(realTarget)
|
|
202
|
-
mkdirSync(dir, { recursive: true, mode: DIR_MODE })
|
|
203
|
-
const tmp = `${realTarget}.${process.pid}.${Date.now()}.tmp`
|
|
204
|
-
writeFileSync(tmp, contents, { encoding: 'utf8', mode: FILE_MODE })
|
|
205
|
-
try {
|
|
206
|
-
renameSync(tmp, realTarget)
|
|
207
|
-
} catch (err) {
|
|
208
|
-
try {
|
|
209
|
-
unlinkSync(tmp)
|
|
210
|
-
} catch {
|
|
211
|
-
// best-effort cleanup of the temp file when rename fails
|
|
212
|
-
}
|
|
213
|
-
throw err
|
|
214
|
-
}
|
|
215
|
-
try {
|
|
216
|
-
statSync(realTarget)
|
|
217
|
-
chmodSync(realTarget, FILE_MODE)
|
|
218
|
-
} catch {
|
|
219
|
-
// ignore — file vanished between rename and chmod is benign
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
// Returns the absolute path renameSync should target. When `path` is a symlink,
|
|
224
|
-
// returns the resolved absolute target so we write through the link instead of
|
|
225
|
-
// replacing it. Otherwise returns the path unchanged. readlinkSync throws EINVAL
|
|
226
|
-
// when the path exists but isn't a symlink and ENOENT when nothing is there —
|
|
227
|
-
// both cases fall through to the original path.
|
|
228
|
-
function resolveSymlinkTarget(path: string): string {
|
|
229
|
-
let link: string
|
|
230
|
-
try {
|
|
231
|
-
link = readlinkSync(path)
|
|
232
|
-
} catch {
|
|
233
|
-
return path
|
|
234
|
-
}
|
|
235
|
-
return isAbsolute(link) ? link : resolve(dirname(path), link)
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
export type ExportClaudeCredentialsFileForAgentOptions = {
|
|
239
|
-
agentDir: string
|
|
240
|
-
claudeCodeEnabled: boolean
|
|
241
|
-
homeDir?: string
|
|
242
|
-
configDir?: string
|
|
243
|
-
log?: (message: string) => void
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
// Boot-time convenience wrapper for src/run/index.ts. Mirrors
|
|
247
|
-
// exportCodexAuthFileForAgent: takes agentDir, never throws, returns a
|
|
248
|
-
// result the caller can ignore. Secrets-file read failures are caught
|
|
249
|
-
// and surfaced as 'failed' so the agent boot is never blocked by a
|
|
250
|
-
// missing or malformed secrets.json.
|
|
251
|
-
export function exportClaudeCredentialsFileForAgent(
|
|
252
|
-
options: ExportClaudeCredentialsFileForAgentOptions,
|
|
253
|
-
): ExportClaudeCredentialsFileResult {
|
|
254
|
-
if (!options.claudeCodeEnabled) return { action: 'skipped', reason: 'claude-code-disabled' }
|
|
255
|
-
let providers: Providers
|
|
256
|
-
try {
|
|
257
|
-
providers = new SecretsBackend(join(options.agentDir, 'secrets.json')).tryReadProvidersSync()
|
|
258
|
-
} catch (err) {
|
|
259
|
-
const reason = err instanceof Error ? err.message : String(err)
|
|
260
|
-
options.log?.(`exportClaudeCredentialsFile: ${reason}`)
|
|
261
|
-
return { action: 'failed', reason }
|
|
262
|
-
}
|
|
263
|
-
return exportClaudeCredentialsFileIfApplicable({
|
|
264
|
-
claudeCodeEnabled: options.claudeCodeEnabled,
|
|
265
|
-
providers,
|
|
266
|
-
...(options.homeDir !== undefined ? { homeDir: options.homeDir } : {}),
|
|
267
|
-
...(options.configDir !== undefined ? { configDir: options.configDir } : {}),
|
|
268
|
-
...(options.log !== undefined ? { log: options.log } : {}),
|
|
269
|
-
})
|
|
270
|
-
}
|