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.
Files changed (213) hide show
  1. package/package.json +6 -3
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/attention-escalation.ts +8 -5
  4. package/src/agent/auth-reloadable.ts +2 -3
  5. package/src/agent/auth.ts +59 -79
  6. package/src/agent/compaction.ts +2 -2
  7. package/src/agent/index.ts +173 -85
  8. package/src/agent/live-sessions.ts +2 -2
  9. package/src/agent/live-subagents.ts +1 -0
  10. package/src/agent/llm-replay-sanitizer.ts +1 -1
  11. package/src/agent/model-overrides.ts +1 -1
  12. package/src/agent/multimodal/look-at.ts +3 -3
  13. package/src/agent/multimodal/read-redirect.ts +1 -1
  14. package/src/agent/plugin-tools.ts +76 -39
  15. package/src/agent/prompt-cache-key.ts +42 -0
  16. package/src/agent/provider-error.ts +179 -10
  17. package/src/agent/reload-tool.ts +1 -1
  18. package/src/agent/restart-handoff/index.ts +7 -14
  19. package/src/agent/reviewer-activity.ts +68 -0
  20. package/src/agent/session-origin.ts +33 -0
  21. package/src/agent/subagents.ts +14 -2
  22. package/src/agent/system-prompt.ts +68 -202
  23. package/src/agent/todo/continuation-policy.ts +12 -4
  24. package/src/agent/tool-error-remediation.ts +1 -1
  25. package/src/agent/tool-file-safety.ts +113 -14
  26. package/src/agent/tool-not-found-nudge.ts +1 -1
  27. package/src/agent/tool-result-budget.ts +2 -2
  28. package/src/agent/tools/channel-disengage.ts +2 -2
  29. package/src/agent/tools/channel-edit.ts +2 -2
  30. package/src/agent/tools/channel-fetch-attachment.ts +2 -2
  31. package/src/agent/tools/channel-history-render.ts +2 -1
  32. package/src/agent/tools/channel-history.ts +2 -2
  33. package/src/agent/tools/channel-react.ts +2 -2
  34. package/src/agent/tools/channel-read.ts +2 -2
  35. package/src/agent/tools/channel-reply.ts +25 -7
  36. package/src/agent/tools/channel-send.ts +51 -9
  37. package/src/agent/tools/curl-impersonate.ts +11 -2
  38. package/src/agent/tools/grant-role.ts +2 -2
  39. package/src/agent/tools/post-github-review.ts +79 -17
  40. package/src/agent/tools/restart.ts +2 -2
  41. package/src/agent/tools/skip-response.ts +4 -4
  42. package/src/agent/tools/spawn-subagent.ts +165 -14
  43. package/src/agent/tools/stream-snapshot.ts +2 -2
  44. package/src/agent/tools/subagent-cancel.ts +2 -2
  45. package/src/agent/tools/subagent-output.ts +10 -2
  46. package/src/agent/tools/todo/index.ts +2 -2
  47. package/src/agent/tools/webfetch/tool.ts +2 -2
  48. package/src/agent/tools/websearch.ts +2 -2
  49. package/src/bundled-plugins/backup/README.md +10 -9
  50. package/src/bundled-plugins/backup/runner.ts +140 -58
  51. package/src/bundled-plugins/backup/subagents.ts +58 -26
  52. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  53. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  54. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  55. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  56. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  57. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  58. package/src/bundled-plugins/operator/operator.ts +15 -4
  59. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  60. package/src/bundled-plugins/security/index.ts +50 -2
  61. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  62. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/discord-bot.ts +122 -67
  64. package/src/channels/adapters/discord-reactions.ts +18 -0
  65. package/src/channels/adapters/discord.ts +114 -8
  66. package/src/channels/adapters/github/inbound.ts +103 -8
  67. package/src/channels/adapters/github/index.ts +251 -19
  68. package/src/channels/adapters/github/last-alive.ts +27 -0
  69. package/src/channels/adapters/github/outbound.ts +54 -18
  70. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  71. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  72. package/src/channels/adapters/github/reactions.ts +100 -0
  73. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  74. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  75. package/src/channels/adapters/github/recovery.ts +106 -0
  76. package/src/channels/adapters/github/review-check.ts +510 -0
  77. package/src/channels/adapters/github/review-submitter.ts +34 -2
  78. package/src/channels/adapters/instagram.ts +32 -14
  79. package/src/channels/adapters/kakaotalk.ts +22 -7
  80. package/src/channels/adapters/line.ts +18 -3
  81. package/src/channels/adapters/outbound-account.ts +20 -0
  82. package/src/channels/adapters/own-reactions.ts +66 -0
  83. package/src/channels/adapters/recovery-correlation.ts +214 -0
  84. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  85. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  86. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  87. package/src/channels/adapters/slack-bot.ts +125 -57
  88. package/src/channels/adapters/slack-classify.ts +25 -4
  89. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  90. package/src/channels/adapters/slack-reactions.ts +18 -0
  91. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  92. package/src/channels/adapters/slack.ts +48 -3
  93. package/src/channels/adapters/teams.ts +14 -4
  94. package/src/channels/adapters/telegram-bot.ts +56 -10
  95. package/src/channels/adapters/webex-bot.ts +12 -2
  96. package/src/channels/adapters/webex.ts +12 -2
  97. package/src/channels/background-handoff.ts +434 -0
  98. package/src/channels/background-obligations.ts +893 -0
  99. package/src/channels/continuity-types.ts +271 -0
  100. package/src/channels/github-review-check.ts +598 -0
  101. package/src/channels/github-review-turn-ledger.ts +102 -28
  102. package/src/channels/github-review-verdict-coordinator.ts +96 -13
  103. package/src/channels/github-token-bridge.ts +11 -5
  104. package/src/channels/inbound-journal.ts +1738 -0
  105. package/src/channels/index.ts +6 -1
  106. package/src/channels/manager.ts +17 -7
  107. package/src/channels/recovery-dispatcher.ts +264 -0
  108. package/src/channels/recovery-notice.ts +94 -0
  109. package/src/channels/recovery-outbox.ts +459 -0
  110. package/src/channels/router.ts +2582 -633
  111. package/src/channels/schema.ts +8 -1
  112. package/src/channels/subagent-completion-bridge.ts +17 -14
  113. package/src/channels/types.ts +121 -16
  114. package/src/channels/waiting-reactions.ts +664 -0
  115. package/src/cli/compose.ts +7 -4
  116. package/src/cli/hostd.ts +49 -3
  117. package/src/cli/inspect.ts +11 -14
  118. package/src/cli/model.ts +7 -5
  119. package/src/cli/oauth-callbacks.ts +38 -23
  120. package/src/coding-agent/broker-body.ts +38 -0
  121. package/src/coding-agent/broker.ts +290 -0
  122. package/src/coding-agent/claude.ts +95 -0
  123. package/src/coding-agent/codex.ts +104 -0
  124. package/src/coding-agent/index.ts +506 -0
  125. package/src/coding-agent/omo-state.ts +69 -0
  126. package/src/coding-agent/omo-stream.ts +98 -0
  127. package/src/coding-agent/omo.ts +192 -0
  128. package/src/coding-agent/runner.ts +263 -0
  129. package/src/coding-agent/tool.ts +62 -0
  130. package/src/coding-agent/worktree.ts +355 -0
  131. package/src/compose/restart.ts +10 -3
  132. package/src/compose/start.ts +20 -3
  133. package/src/config/config.ts +70 -26
  134. package/src/config/providers.ts +278 -50
  135. package/src/container/exit-reason.ts +44 -0
  136. package/src/container/index.ts +5 -0
  137. package/src/container/log-archive.ts +51 -13
  138. package/src/container/memory-limit.ts +1 -1
  139. package/src/container/memory-oversubscription.ts +36 -6
  140. package/src/container/oom-events.ts +86 -0
  141. package/src/container/restart.ts +2 -0
  142. package/src/container/shared.ts +8 -1
  143. package/src/container/start.ts +25 -13
  144. package/src/container/stop.ts +6 -2
  145. package/src/container/tool-oom-priority.ts +32 -0
  146. package/src/cron/consumer.ts +10 -4
  147. package/src/cron/reloadable.ts +23 -2
  148. package/src/doctor/checks.ts +14 -2
  149. package/src/hostd/daemon.ts +20 -10
  150. package/src/hostd/spawn.ts +106 -5
  151. package/src/hostd/version.ts +20 -0
  152. package/src/hostd/watchdog.ts +241 -0
  153. package/src/init/dockerfile.ts +57 -592
  154. package/src/init/index.ts +6 -7
  155. package/src/init/oauth-login.ts +57 -17
  156. package/src/inspect/transcript-view.ts +6 -3
  157. package/src/mcp/client.ts +3 -1
  158. package/src/operations/classify-tool-outcome.ts +45 -1
  159. package/src/operations/incidents.ts +10 -5
  160. package/src/plugin/core-tool-names.ts +1 -1
  161. package/src/plugin/define.ts +1 -0
  162. package/src/plugin/index.ts +1 -0
  163. package/src/plugin/types.ts +6 -1
  164. package/src/run/background-handoff-boot.ts +86 -0
  165. package/src/run/channel-session-factory.ts +5 -4
  166. package/src/run/index.ts +93 -93
  167. package/src/run/resource-sample.ts +19 -0
  168. package/src/sandbox/build.ts +4 -0
  169. package/src/sandbox/coding-agent.ts +214 -0
  170. package/src/sandbox/policy.ts +1 -0
  171. package/src/sandbox/runtime-private.ts +4 -1
  172. package/src/secrets/coding-agent-auth.ts +97 -0
  173. package/src/secrets/index.ts +0 -16
  174. package/src/secrets/refresh-provider-oauth.ts +30 -76
  175. package/src/secrets/schema.ts +3 -4
  176. package/src/secrets/storage.ts +133 -234
  177. package/src/server/command-runner.ts +6 -2
  178. package/src/server/index.ts +102 -41
  179. package/src/sessions/index.ts +1 -1
  180. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  181. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  182. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  183. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  184. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  185. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  186. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  187. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  188. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  189. package/src/skills/typeclaw-config/SKILL.md +24 -24
  190. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  191. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  192. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  193. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  194. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  195. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  196. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  197. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  198. package/src/skills/typeclaw-plugins/SKILL.md +20 -20
  199. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  200. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  201. package/src/tui/index.ts +5 -3
  202. package/src/tui/theme.ts +1 -1
  203. package/typeclaw.schema.json +44 -2
  204. package/src/agent/adaptive-thinking-compat.ts +0 -79
  205. package/src/secrets/claude-credentials-json.ts +0 -129
  206. package/src/secrets/codex-auth-json.ts +0 -102
  207. package/src/secrets/export-claude-credentials-file.ts +0 -270
  208. package/src/secrets/export-codex-auth-file.ts +0 -250
  209. package/src/secrets/oauth-xai.ts +0 -348
  210. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  211. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  212. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  213. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -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
- }
@@ -1,250 +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, resolve } from 'node:path'
13
-
14
- import { decodeCodexAccessTokenExpiryMs, emitCodexAuthJson, isDecodableJwt } from './codex-auth-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
-
21
- export type ExportCodexAuthFileResult =
22
- | { action: 'skipped'; reason: SkipReason }
23
- | { action: 'wrote'; path: string }
24
- | { action: 'failed'; reason: string }
25
-
26
- export type SkipReason =
27
- | 'codex-cli-disabled'
28
- | 'no-openai-codex-credential'
29
- | 'credential-not-oauth'
30
- | 'on-disk-is-fresher'
31
-
32
- export type ExportCodexAuthFileOptions = {
33
- codexCliEnabled: boolean
34
- providers: Providers
35
- homeDir?: string
36
- now?: () => number
37
- log?: (message: string) => void
38
- }
39
-
40
- // Writes typeclaw's openai-codex OAuth credential to $HOME/.codex/auth.json
41
- // when it's safe to do so. Container HOME is /home/agent and ephemeral; this
42
- // boot-time export reconstructs the CLI file from secrets.json after provider
43
- // OAuth refresh has had a chance to update the canonical credential.
44
- //
45
- // Three guards, cheapest first. The first two return without ever touching
46
- // the filesystem, which keeps the 90% case (users who don't enable Codex
47
- // CLI) at zero overhead on every container start.
48
- export function exportCodexAuthFileIfApplicable(options: ExportCodexAuthFileOptions): ExportCodexAuthFileResult {
49
- if (!options.codexCliEnabled) return { action: 'skipped', reason: 'codex-cli-disabled' }
50
-
51
- const credential = options.providers['openai-codex']
52
- if (credential === undefined) return { action: 'skipped', reason: 'no-openai-codex-credential' }
53
- if (credential.type !== 'oauth') return { action: 'skipped', reason: 'credential-not-oauth' }
54
-
55
- const targetPath = join(options.homeDir ?? homedir(), '.codex', 'auth.json')
56
-
57
- try {
58
- if (!shouldOverwrite(targetPath, credential, options.now ?? Date.now)) {
59
- return { action: 'skipped', reason: 'on-disk-is-fresher' }
60
- }
61
- const contents = emitCodexAuthJson(credential)
62
- writeAtomic(targetPath, contents)
63
- return { action: 'wrote', path: targetPath }
64
- } catch (err) {
65
- const reason = err instanceof Error ? err.message : String(err)
66
- options.log?.(`exportCodexAuthFile: ${reason}`)
67
- return { action: 'failed', reason }
68
- }
69
- }
70
-
71
- // Newer-wins: skip the write unless typeclaw's stored credential is
72
- // strictly fresher than the on-disk JWT. Codex CLI rotates tokens
73
- // in-place (it rewrites auth.json with a refreshed access_token whose
74
- // JWT exp is later), so on a restart the file may legitimately be ahead
75
- // of secrets.json. We must not clobber that.
76
- //
77
- // Ties skip: when expiries match, there's nothing to gain from a write,
78
- // and avoiding the I/O keeps the steady state at zero churn after the
79
- // first boot. The only writes we ever do are first-write (B1), recovery
80
- // (B6), or refresh-from-typeclaw-side (B3).
81
- //
82
- // On any error reading or parsing the on-disk file (missing, corrupt JSON,
83
- // missing JWT, undecodable exp), we return true. That's the "we have a
84
- // valid credential, the file is unusable, replace it" fallback case (B1
85
- // and B6 in the design doc).
86
- //
87
- // A file missing a usable `id_token` is unusable too, regardless of how
88
- // fresh its access token is: codex rejects the whole auth.json with
89
- // `missing field id_token` before any model call. This guard runs BEFORE
90
- // the newer-wins expiry compare so a pre-fix TypeClaw-emitted file (valid,
91
- // possibly fresher access token, but no id_token) is always rewritten —
92
- // the path that self-heals already-broken agents on restart.
93
- function shouldOverwrite(
94
- targetPath: string,
95
- credential: ProviderCredential & { expires?: unknown; access?: unknown },
96
- now: () => number,
97
- ): boolean {
98
- let raw: string
99
- try {
100
- raw = readFileSync(targetPath, 'utf8')
101
- } catch {
102
- return true
103
- }
104
-
105
- let parsed: unknown
106
- try {
107
- parsed = JSON.parse(raw)
108
- } catch {
109
- return true
110
- }
111
-
112
- if (!onDiskHasUsableIdToken(parsed)) return true
113
-
114
- const onDiskAccess = readOnDiskAccessToken(parsed)
115
- if (onDiskAccess === null) return true
116
-
117
- const onDiskExpiry = decodeCodexAccessTokenExpiryMs(onDiskAccess)
118
- if (onDiskExpiry === null) return true
119
-
120
- const credentialExpiry = readCredentialExpiry(credential, now)
121
- return credentialExpiry > onDiskExpiry
122
- }
123
-
124
- function readOnDiskAccessToken(parsed: unknown): string | null {
125
- return readOnDiskToken(parsed, 'access_token')
126
- }
127
-
128
- // codex parses `tokens.id_token` as a JWT, so a value that is absent, empty,
129
- // or not a decodable JWT is unusable — codex rejects the whole auth.json on
130
- // load. Validate decodability (not just presence) so a file with a non-empty
131
- // but malformed id_token, even alongside a fresh access token, is treated as
132
- // stale and rewritten rather than preserved by the newer-wins compare.
133
- function onDiskHasUsableIdToken(parsed: unknown): boolean {
134
- const idToken = readOnDiskToken(parsed, 'id_token')
135
- return idToken !== null && isDecodableJwt(idToken)
136
- }
137
-
138
- function readOnDiskToken(parsed: unknown, field: 'access_token' | 'id_token'): string | null {
139
- if (typeof parsed !== 'object' || parsed === null) return null
140
- const tokens = (parsed as Record<string, unknown>)['tokens']
141
- if (typeof tokens !== 'object' || tokens === null) return null
142
- const value = (tokens as Record<string, unknown>)[field]
143
- return typeof value === 'string' && value.length > 0 ? value : null
144
- }
145
-
146
- // Resolution order for the credential's expiry:
147
- // 1. The `expires` field pi-ai writes (absolute ms epoch).
148
- // 2. The JWT `exp` claim decoded from `access`.
149
- // 3. Now — guarantees we still write on first boot when the credential
150
- // lacks both, rather than silently skipping forever.
151
- function readCredentialExpiry(credential: { expires?: unknown; access?: unknown }, now: () => number): number {
152
- if (typeof credential.expires === 'number' && Number.isFinite(credential.expires)) {
153
- return credential.expires
154
- }
155
- if (typeof credential.access === 'string') {
156
- const fromJwt = decodeCodexAccessTokenExpiryMs(credential.access)
157
- if (fromJwt !== null) return fromJwt
158
- }
159
- return now()
160
- }
161
-
162
- // Atomic temp-then-rename, mirroring src/secrets/storage.ts's
163
- // writeEnvelopeAtomic. The directory is created with 0700 and the file
164
- // with 0600 because $HOME/.codex/auth.json holds a long-lived refresh
165
- // token — leaking it via lax permissions defeats the whole point of
166
- // running typeclaw on a multi-user host. The 0600 chmod after rename is
167
- // belt-and-suspenders: writeFileSync's `mode` is applied at create time,
168
- // but umask can mask it down on some filesystems.
169
- //
170
- // Symlink preservation is still a safety property even though TypeClaw no
171
- // longer plants one here. An operator or external tool may preconfigure
172
- // $HOME/.codex/auth.json as a symlink; POSIX rename(2) replaces that directory
173
- // entry instead of following it. Resolve the target and rename there so the
174
- // caller's symlink survives. The temp file MUST live alongside the real target
175
- // because renameSync across filesystems fails with EXDEV.
176
- function writeAtomic(targetPath: string, contents: string): void {
177
- const realTarget = resolveSymlinkTarget(targetPath)
178
- const dir = dirname(realTarget)
179
- mkdirSync(dir, { recursive: true, mode: DIR_MODE })
180
- const tmp = `${realTarget}.${process.pid}.${Date.now()}.tmp`
181
- writeFileSync(tmp, contents, { encoding: 'utf8', mode: FILE_MODE })
182
- try {
183
- renameSync(tmp, realTarget)
184
- } catch (err) {
185
- try {
186
- unlinkSync(tmp)
187
- } catch {
188
- // best-effort cleanup of the temp file when rename fails
189
- }
190
- throw err
191
- }
192
- // statSync + chmodSync rather than unconditional chmod so a 0644 file
193
- // installed by something else stays visible in tests (we WANT to overwrite
194
- // permissions when we own the file).
195
- try {
196
- statSync(realTarget)
197
- chmodSync(realTarget, FILE_MODE)
198
- } catch {
199
- // ignore — file vanished between rename and chmod is benign
200
- }
201
- }
202
-
203
- // Returns the absolute path renameSync should target. When `path` is a symlink,
204
- // returns the resolved absolute target so we write through the link instead of
205
- // replacing it. Otherwise returns the path unchanged.
206
- //
207
- // readlinkSync throws EINVAL when the path exists but isn't a symlink,
208
- // and ENOENT when nothing is there. Either case → write to the original
209
- // path; the parent-dir mkdir + atomic rename handle the rest. We don't
210
- // distinguish errno because both have the same fallback.
211
- function resolveSymlinkTarget(path: string): string {
212
- let link: string
213
- try {
214
- link = readlinkSync(path)
215
- } catch {
216
- return path
217
- }
218
- return isAbsolute(link) ? link : resolve(dirname(path), link)
219
- }
220
-
221
- export type ExportCodexAuthFileForAgentOptions = {
222
- agentDir: string
223
- codexCliEnabled: boolean
224
- homeDir?: string
225
- log?: (message: string) => void
226
- }
227
-
228
- // Boot-time convenience wrapper for src/run/index.ts. Mirrors
229
- // hydrateChannelEnvFromSecrets's contract: takes agentDir, never throws,
230
- // returns a result the caller can ignore. Secrets-file read failures are
231
- // caught and surfaced as a 'failed' result so the agent boot is not blocked
232
- // by a missing or malformed secrets.json — same non-fatal policy hydrate
233
- // uses on the channels slice.
234
- export function exportCodexAuthFileForAgent(options: ExportCodexAuthFileForAgentOptions): ExportCodexAuthFileResult {
235
- if (!options.codexCliEnabled) return { action: 'skipped', reason: 'codex-cli-disabled' }
236
- let providers: Providers
237
- try {
238
- providers = new SecretsBackend(join(options.agentDir, 'secrets.json')).tryReadProvidersSync()
239
- } catch (err) {
240
- const reason = err instanceof Error ? err.message : String(err)
241
- options.log?.(`exportCodexAuthFile: ${reason}`)
242
- return { action: 'failed', reason }
243
- }
244
- return exportCodexAuthFileIfApplicable({
245
- codexCliEnabled: options.codexCliEnabled,
246
- providers,
247
- ...(options.homeDir !== undefined ? { homeDir: options.homeDir } : {}),
248
- ...(options.log !== undefined ? { log: options.log } : {}),
249
- })
250
- }