typeclaw 0.45.1 → 0.46.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 (142) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -1
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +44 -30
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/multimodal/index.ts +1 -1
  7. package/src/agent/multimodal/look-at.ts +78 -44
  8. package/src/agent/multimodal/looker.ts +151 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +198 -0
  11. package/src/agent/plugin-tools.ts +379 -157
  12. package/src/agent/provider-error.ts +52 -1
  13. package/src/agent/restart/index.ts +61 -40
  14. package/src/agent/restart-handoff/index.ts +73 -4
  15. package/src/agent/reviewer-bash-policy.ts +42 -1
  16. package/src/agent/session-origin.ts +2 -0
  17. package/src/agent/subagent-drain.ts +117 -7
  18. package/src/agent/subagents.ts +49 -16
  19. package/src/agent/throttle-circuit.ts +25 -5
  20. package/src/agent/tool-error-remediation.ts +72 -0
  21. package/src/agent/tool-file-safety.ts +1050 -0
  22. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  23. package/src/agent/tools/ddg.ts +16 -2
  24. package/src/agent/tools/post-github-review.ts +199 -0
  25. package/src/agent/tools/spawn-subagent.ts +21 -18
  26. package/src/agent/tools/webfetch/fetch.ts +143 -183
  27. package/src/agent/tools/webfetch/tool.ts +2 -3
  28. package/src/agent/tools/websearch.ts +23 -2
  29. package/src/agent/tools-without-local-file-operands.ts +27 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/index.ts +2 -1
  32. package/src/bundled-plugins/backup/runner.ts +2 -1
  33. package/src/bundled-plugins/doc-render/render.ts +93 -12
  34. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  35. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  36. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  37. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  38. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  39. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  40. package/src/bundled-plugins/memory/README.md +23 -11
  41. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  42. package/src/bundled-plugins/memory/citations.ts +22 -9
  43. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  44. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  45. package/src/bundled-plugins/memory/index.ts +0 -4
  46. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  47. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  48. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  49. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  50. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  51. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  52. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  53. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  54. package/src/bundled-plugins/reviewer/index.ts +2 -2
  55. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  56. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  57. package/src/bundled-plugins/scout/scout.ts +8 -0
  58. package/src/bundled-plugins/security/index.ts +4 -4
  59. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  60. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  61. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  62. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  63. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  64. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  65. package/src/channels/adapters/discord-bot.ts +66 -6
  66. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  67. package/src/channels/adapters/discord-id.ts +4 -0
  68. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  69. package/src/channels/adapters/discord.ts +57 -7
  70. package/src/channels/adapters/github/auth-app.ts +41 -12
  71. package/src/channels/adapters/github/index.ts +23 -11
  72. package/src/channels/adapters/github/review-submitter.ts +302 -0
  73. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  74. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  75. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  76. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  77. package/src/channels/adapters/slack-bot.ts +19 -8
  78. package/src/channels/adapters/slack-classify.ts +21 -2
  79. package/src/channels/adapters/slack.ts +59 -7
  80. package/src/channels/adapters/telegram-bot.ts +18 -5
  81. package/src/channels/adapters/webex-bot.ts +8 -3
  82. package/src/channels/adapters/webex.ts +8 -3
  83. package/src/channels/fetch-attachment.ts +43 -0
  84. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  85. package/src/channels/github-token-bridge.ts +10 -3
  86. package/src/channels/manager.ts +9 -0
  87. package/src/channels/router.ts +248 -6
  88. package/src/channels/types.ts +28 -1
  89. package/src/cli/channel.ts +1 -1
  90. package/src/cli/init.ts +1 -1
  91. package/src/cli/model.ts +57 -7
  92. package/src/compose/stop.ts +17 -5
  93. package/src/config/config.ts +6 -6
  94. package/src/config/models-mutation.ts +13 -1
  95. package/src/config/providers.ts +176 -0
  96. package/src/container/start.ts +49 -10
  97. package/src/doctor/checks.ts +3 -1
  98. package/src/doctor/commit.ts +2 -1
  99. package/src/doctor/file-ownership.ts +52 -0
  100. package/src/dreams/git.ts +2 -1
  101. package/src/git/hookless.ts +5 -0
  102. package/src/git/reconcile-ignored.ts +18 -5
  103. package/src/git/secret-history.ts +371 -0
  104. package/src/git/system-commit.ts +12 -6
  105. package/src/init/dockerfile.ts +86 -5
  106. package/src/init/index.ts +17 -5
  107. package/src/init/models-dev.ts +4 -0
  108. package/src/init/validate-api-key.ts +2 -0
  109. package/src/mcp/tools.ts +16 -3
  110. package/src/permissions/builtins.ts +3 -1
  111. package/src/plugin/context.ts +2 -0
  112. package/src/plugin/index.ts +1 -0
  113. package/src/plugin/manager.ts +4 -0
  114. package/src/plugin/types.ts +21 -0
  115. package/src/run/index.ts +40 -0
  116. package/src/run/llm-fetch-observer.ts +41 -4
  117. package/src/sandbox/build.ts +37 -15
  118. package/src/sandbox/canonical-secrets.ts +18 -0
  119. package/src/sandbox/env-exposure.ts +80 -0
  120. package/src/sandbox/errors.ts +13 -6
  121. package/src/sandbox/hidden-paths.ts +102 -44
  122. package/src/sandbox/index.ts +22 -4
  123. package/src/sandbox/package-install.ts +3 -27
  124. package/src/sandbox/policy.ts +11 -25
  125. package/src/sandbox/privileged-runtime.ts +255 -0
  126. package/src/sandbox/session-tmp.ts +8 -2
  127. package/src/sandbox/writable-zones.ts +204 -140
  128. package/src/secrets/index.ts +8 -0
  129. package/src/secrets/refresh-provider-oauth.ts +128 -0
  130. package/src/server/command-runner.ts +48 -4
  131. package/src/server/index.ts +4 -0
  132. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  133. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  134. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  135. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  136. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  137. package/src/skills/typeclaw-config/SKILL.md +5 -5
  138. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  139. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  140. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  141. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  142. package/typeclaw.schema.json +20 -0
@@ -1,170 +1,29 @@
1
- # Auth flow — interactive
1
+ # Auth flow — operator-owned (Claude Code)
2
2
 
3
- Deep dive for the auth paths. Read it when `SKILL.md`'s "First-time auth (interactive)" section sends you here, or when an auth attempt fails and you need to understand what went wrong.
3
+ Claude Code authentication is outside the model-driven tool boundary. **Authenticated Claude Code delegation is unavailable from model-driven TypeClaw tools.** The agent must not read, print, parse, copy, write, verify, or probe any credential value or credential file.
4
4
 
5
- The two paths are intentionally symmetric: in both, the user produces one string on their side, pastes it to you, you validate it, you do read-modify-write on `.env`, you offer a restart. Only the credential differs.
5
+ ## No readiness bypass
6
6
 
7
- ## Path 0 — auto-export from typeclaw's anthropic OAuth credential
7
+ Do not check environment variables or profile-file existence as a way to enable delegation. TypeClaw masks canonical credential files and directories from model-driven bash, strips reusable credential environments, and unconditionally blocks non-bash tools from opening them. Provider authentication available to trusted runtime code is not delegated to a model-driven Claude child.
8
8
 
9
- If the user has already configured an `anthropic` OAuth credential in typeclaw (via `typeclaw provider add anthropic` or the init wizard) AND `docker.file.claudeCode: true`, the agent boot in `src/run/index.ts` auto-emits the credential to `~/.claude/.credentials.json` before `claude` ever runs. The destination matches Claude Code's documented Linux/Windows credential path; macOS uses the Keychain entry `"Claude Code-credentials"` with the same JSON shape, which typeclaw does not target (typeclaw runs Claude Code inside a Linux container).
9
+ ## When authentication is missing
10
10
 
11
- The on-disk shape:
11
+ Stop the delegation and tell the operator:
12
12
 
13
- ```json
14
- {
15
- "claudeAiOauth": {
16
- "accessToken": "sk-ant-oat01-...",
17
- "refreshToken": "sk-ant-ort01-...",
18
- "expiresAt": 1730000000000,
19
- "scopes": ["user:inference", "user:profile", "user:sessions:claude_code", "user:mcp_servers"],
20
- "subscriptionType": "max"
21
- }
22
- }
23
- ```
13
+ > Authenticated Claude Code delegation is unavailable from model-driven TypeClaw tools. Authenticate and run Claude Code directly as the host-side operator. Do not send an API key or OAuth token in chat.
24
14
 
25
- Field names are camelCase and `expiresAt` is **milliseconds** since epoch (not seconds, not ISO).
15
+ The operator may manage Claude Code authentication directly on the host. The model must not broker that path, request `claude setup-token` output, or transfer a credential into the container.
26
16
 
27
- ### Newer-wins on every boot
17
+ If Claude Code presents an auth prompt that requires entering or inspecting a credential, exit the delegated session. Do not run `claude setup-token` in the container or paste a key/token through tmux.
28
18
 
29
- The exporter compares typeclaw's stored `expires` against the JWT `exp` claim embedded in the on-disk `accessToken`. Strictly fresher wins; ties skip. Claude Code rotates tokens in place by rewriting `.credentials.json` on every successful refresh (anthropics/claude-code#53063), so on a restart the on-disk file may legitimately be ahead of `secrets.json` and must not be clobbered. The persistent-`$HOME` symlink the entrypoint shim installs (`~/.claude/.credentials.json` → `/agent/.typeclaw/home/.claude/.credentials.json`) is what makes the in-place refresh survive `stop`+`start`.
19
+ ## Runtime separation
30
20
 
31
- If `.credentials.json` already carries an `mcpOAuth` block (MCP server OAuth state), the exporter preserves it on overwrite. Only the `claudeAiOauth` block is rewritten.
21
+ Trusted runtime provisioning does not authorize a model-driven child. Any exported persistent profile remains masked, and the sandbox intentionally does not mount it or preserve Anthropic credential variables. Restarting cannot change this policy boundary.
32
22
 
33
- ### When Path 0 does NOT fire
23
+ ## Hard prohibitions
34
24
 
35
- - `docker.file.claudeCode: false` — the install layer is off, no point exporting.
36
- - `secrets.json#providers.anthropic` is absent — nothing to export.
37
- - The stored credential is api-key shape — Claude Code reads API keys from `ANTHROPIC_API_KEY` env, not from `.credentials.json`. Fall back to Path A.
38
- - The on-disk JWT `exp` is already fresher — Claude Code refreshed in-place, skip.
39
-
40
- In each of those cases the agent boots without touching the file and Path A or Path B applies. The exporter is failure-tolerant: any error (read, write, fs guard) is logged via `console.warn` and the boot continues — Claude Code will then surface the missing credential on first invocation, which is the existing fallback.
41
-
42
- ## Path A — API key (recap)
43
-
44
- The API key path lives entirely in `SKILL.md` because there's nothing to elaborate. Summary:
45
-
46
- 1. Prompt user for `sk-ant-…`.
47
- 2. Validate `/^sk-ant-[A-Za-z0-9_-]{20,}$/`.
48
- 3. Read `.env`, merge `ANTHROPIC_API_KEY=<value>` into the parsed map, reconstruct full content, write with `acknowledgeGuards: { nonWorkspaceWrite: true }`.
49
- 4. Verify.
50
- 5. Ask before restart.
51
-
52
- When to recommend it: the user has an **Anthropic Console** workspace (API billing, no Claude subscription). They get their key from `console.anthropic.com`. Cost is metered per-token against the Console workspace.
53
-
54
- ## Path B — OAuth long-lived token, generated on the user's machine
55
-
56
- This is the path for users with a Claude **Pro / Max / Team / Enterprise** subscription. Inference cost is bounded by the subscription's monthly Agent SDK credit pool, not per-token.
57
-
58
- The token is generated by `claude setup-token`, which is Anthropic's own one-time setup command. From the [official docs](https://code.claude.com/docs/en/authentication):
59
-
60
- > For CI pipelines, scripts, or other environments where interactive browser login isn't available, generate a one-year OAuth token with `claude setup-token`. The command walks you through OAuth authorization and prints a token to the terminal. It does not save the token anywhere; copy it and set it as the `CLAUDE_CODE_OAUTH_TOKEN` environment variable wherever you want to authenticate.
61
-
62
- A typeclaw container is precisely that environment ("CI pipelines, scripts, or other environments where interactive browser login isn't available"). The user runs `setup-token` on their own machine — where they already have `claude` installed and `/login`-ed — copies the printed token, and pastes it to you.
63
-
64
- ### Why on the user's machine, not in the container
65
-
66
- This was originally implemented as an in-container tmux dance: agent spawns `claude setup-token` in a tmux pane, scrapes the URL with `capture-pane`, surfaces it to the user, brokers the auth code back, regex-extracts the token from the pane. It worked, barely. It cost ~150 lines of pane-capture mechanics, ANSI stripping, URL-or-code parsing, retry logic, and timing assumptions that broke on every Claude Code version bump.
67
-
68
- The user-machine flow is strictly better:
69
-
70
- 1. **Zero in-container surface area.** No tmux session, no pane capture, no version-locked regex matching the prompt wording, no 30-second polling budget, no race between OAuth-code single-use and your retry loop.
71
- 2. **The user already has `claude` installed locally.** They had to, to have a subscription worth using `setup-token` against. The marginal install cost is zero.
72
- 3. **The browser is already on the user's machine.** No matter where the container lives — laptop, remote VM, shared workstation, cloud sandbox — the user's browser is where the user is. `setup-token` on the user's machine has a working `localhost:1455` callback by definition; no cross-device dance needed.
73
- 4. **Failure modes are easier to debug.** When `setup-token` fails on the user's machine, the user sees the error directly. When it failed in the container, you had to surface a stripped-ANSI capture-pane snapshot and hope the user could decipher it.
74
- 5. **The token has no network dependency from inside the container.** Once it's in `.env`, `claude` reads it from the environment on startup — no token-refresh round-trips, no `api.anthropic.com` reachability requirement at auth time (only at inference time, which the agent needs anyway).
75
-
76
- There is no remaining case where running `setup-token` inside the container is preferable. The only thing the container needs is the resulting token string.
77
-
78
- ### Step-by-step
79
-
80
- 1. **Confirm prerequisites with the user, in one message:**
81
-
82
- > To set up OAuth auth, you'll generate a long-lived token on your own machine. Two prerequisites:
83
- >
84
- > 1. Do you have the `claude` CLI installed locally? If not: install from `claude.com/code`, then `claude login` with your Claude Pro / Max / Team / Enterprise account.
85
- > 2. Do you have a paid Claude subscription? (`setup-token` requires Pro, Max, Team, or Enterprise — it doesn't work on free accounts.)
86
- >
87
- > Once both are true, reply "ready" and I'll send the next step.
88
-
89
- This single confirmation up-front is the difference between a one-paste flow and a multi-turn debugging session when the user discovers mid-flow that their CLI isn't installed.
90
-
91
- 2. **When the user confirms, send the generation instructions:**
92
-
93
- > Great. On your machine, run:
94
- >
95
- > ```sh
96
- > claude setup-token
97
- > ```
98
- >
99
- > It opens a browser, you authorize with your Claude account, and then prints **one long token** on the terminal. It looks something like:
100
- >
101
- > ```
102
- > sk-ant-oat01-<long random string>
103
- > ```
104
- >
105
- > Copy the whole token (just the token, not any surrounding text) and paste it back to me. The token is valid for one year and authenticates against your Claude subscription — treat it like a password.
106
-
107
- 3. **Wait for the user's reply.** Expected shapes:
108
- - **A bare token string.** Typically starts with `sk-ant-oat01-` but Anthropic has changed the prefix before and may again — do not hardcode the prefix.
109
- - **The full line including `CLAUDE_CODE_OAUTH_TOKEN=`** if they pasted the `export` line they wrote themselves. Strip the `CLAUDE_CODE_OAUTH_TOKEN=` prefix (and any leading `export `) before validating.
110
- - **An error message** if `setup-token` failed on their side. See the failure-mode list below.
111
- - **"cancel"** or equivalent. Drop the flow cleanly.
112
-
113
- 4. **Parse and validate**, in order:
114
- 1. Trim leading/trailing whitespace.
115
- 2. If the string starts with `export ` (with the space), drop the `export ` prefix.
116
- 3. If the string starts with `CLAUDE_CODE_OAUTH_TOKEN=`, drop that prefix. Also strip surrounding single or double quotes that the user's shell prompt may have included.
117
- 4. Validate the remainder: `/^[A-Za-z0-9_-]{30,}$/`. Tokens are opaque alphanumeric blobs with `_` and `-` only (current observed prefix is `sk-ant-oat01-` but Anthropic has changed prefixes before — validate by shape, not prefix). If the token format ever grows to include `.`, `/`, or other characters, this regex will reject valid tokens; widen the character class then, not preemptively.
118
- 5. If validation fails, ask once more: "That doesn't look like a `claude setup-token` token — it should be one long string with no spaces or newlines. Paste just the token. Or say 'cancel' to switch to API-key auth instead."
119
- 6. If the second attempt also fails, drop OAuth and recommend the API-key path.
120
-
121
- 5. **Confirm receipt without echoing the token.** Reply something like "Got it, validating and writing to `.env`." Never include the token in your reply, in a log line, in a sentinel, in a commit message, or anywhere else.
122
-
123
- 6. **Read `.env`** (existing content, may not exist).
124
-
125
- 7. **Parse into a key→value map.** Be tolerant of comments (`#`-prefixed lines), blank lines, and quoted values. Preserve order and comments when reconstructing.
126
-
127
- 8. **Merge `CLAUDE_CODE_OAUTH_TOKEN=<value>`.** Add if absent, replace if present. Do not quote — Docker's `--env-file` parser is brittle around quotes, and the token has no whitespace by validation.
128
-
129
- 9. **Write back with `acknowledgeGuards: { nonWorkspaceWrite: true }`.** `.env` is in the `nonWorkspaceWrite` guard's deny set; the ack flag is required on every write to it, not just the first.
130
-
131
- 10. **Verify by re-reading `.env`** and confirming the new line is there exactly once and the value matches what you wrote.
132
-
133
- 11. **Ask before restart**, same prompt as the API-key path:
134
-
135
- > Auth is on disk. The container needs to restart to load it (TUI will briefly disconnect). May I restart now, or do you have other changes to make first?
136
-
137
- 12. On yes → call the `restart` tool. On no → tell them to run `typeclaw restart` themselves when ready.
138
-
139
- 13. **Done.** There is no auth scratch directory, no tmux session to tear down, no worktree. The OAuth path has the same on-disk footprint as the API-key path: one new line in `.env`.
140
-
141
- ## Failure modes on the user's side
142
-
143
- These all surface as the user's reply being an error message instead of a token. Recognize them, do not validate them as tokens, and respond with the matching guidance.
144
-
145
- - **"command not found: claude"** — they don't have the CLI installed locally. Point them at `claude.com/code` and ask them to `claude login` after installing.
146
- - **"Not logged in"** / `setup-token` immediately asking them to log in — they have the CLI but no active subscription session. Have them run `claude login` first, then re-try `claude setup-token`.
147
- - **"This account doesn't have access to a paid Claude subscription"** — they're on a free account. `setup-token` requires Pro / Max / Team / Enterprise. They either upgrade or use the API-key path.
148
- - **"Token request failed"** / generic network error during `setup-token` — their local machine couldn't reach `claude.ai` or `api.anthropic.com`. Check VPN, firewall, corporate proxy. Re-try in a moment.
149
- - **Browser opened but no token appeared in terminal** — they authorized in the wrong account, or they closed the tab before the callback completed. Have them run `setup-token` again and wait for the terminal to finish.
150
- - **They report success but pasted a string that fails validation** — most likely they pasted the surrounding output (the `export` line, a banner, instructions) rather than just the token. Re-ask, emphasize "just the token, no surrounding text".
151
-
152
- ## Failure modes after you've written the token
153
-
154
- - **`typeclaw restart` fails or the container won't come up** — the credential is on disk, the restart is the problem. Don't re-prompt for auth; surface the restart failure and tell the user to run `typeclaw restart` from their host shell to see the underlying error.
155
- - **`claude` invocations after restart still say "Invalid API key" / "Unauthorized"** — token validation passed locally but the credential is rejected upstream. Three likely causes:
156
- 1. **Token from a different account than expected.** The user has multiple Claude accounts on their local machine and `setup-token` used the wrong one. Have them check `claude login` and re-run `setup-token` from the right account.
157
- 2. **`ANTHROPIC_API_KEY` is also set in `.env` and takes precedence.** Per the [auth precedence rules](https://code.claude.com/docs/en/authentication#authentication-precedence), `ANTHROPIC_API_KEY` outranks `CLAUDE_CODE_OAUTH_TOKEN`. Check `.env`; remove the stale `ANTHROPIC_API_KEY` line if the user wants OAuth.
158
- 3. **Token expired or revoked.** Tokens are one-year-lived; revocation happens if the user `/logout`s from the subscription that issued the token. Have them re-run `setup-token`.
159
-
160
- ## Things you must not do during auth
161
-
162
- - **Do not run `claude setup-token` inside the container.** Use the user-machine flow above. The in-container tmux dance that this skill used to recommend has been removed; it was strictly worse than asking the user to run one command on their machine.
163
- - **Do not log, echo, paste-back, or otherwise transcribe the user's token.** Not in a confirmation message, not in a sentinel, not in a commit. A one-year credential leak is significantly worse than a momentary "did you mean this?" reflection — there's no good reason for the token to leave the `.env` write path.
164
- - **Do not write the token to `.env` until you've validated its format.** A malformed token quietly turns into a broken auth that surfaces only on the next claude invocation, long after the user has moved on.
165
- - **Do not retry validation more than once.** If the first paste fails the regex, ask once with clearer guidance ("just the token, no surrounding text"). If the second also fails, the user is in a state that text instructions won't resolve — drop the OAuth path and recommend API-key auth.
166
- - **Do not advise the user to `typeclaw shell` and run `claude setup-token` inside the container as a "fallback"**. It does not work — the container has no browser. If `setup-token` is failing on the user's machine, the right fix is on their machine (check `claude login`, check network), not switching the dance to the container.
167
- - **Do not assume the token format prefix.** Anthropic has changed the prefix on long-lived tokens before (the docs use generic placeholders like `your-token`). Validate by shape (length + character class), not by prefix.
168
- - **Do not write to `.env` without `acknowledgeGuards: { nonWorkspaceWrite: true }`.** Same guard contract as every other `.env` write.
169
- - **Do not patch-edit `.env`.** Read-modify-write the whole file. A fragile `oldText` match could corrupt unrelated lines.
170
- - **Do not branch on local-vs-remote container topology.** The user-machine flow is the same whether the container is on the user's laptop or on a remote host — the user runs `setup-token` on whatever local machine they're at, the token works in either container.
25
+ - Never ask for or accept an API key, OAuth token, access token, or credential-file contents in chat.
26
+ - Never use `read`, `write`, `edit`, `look_at`, channel attachment tools, or shell commands to access `.env`, `secrets.json`, `auth.json`, `~/.claude/.credentials.json`, or their persistent backing directories.
27
+ - Never put credentials in prompts, tmux keystrokes, command arguments, sentinels, transcripts, logs, commits, or scratch files.
28
+ - Never treat a guard acknowledgement as authorization to handle credentials. Canonical credentials are blocked independently of plugin guard hooks.
29
+ - If a credential is offered, tell the user not to send it and redirect them to host-side setup.
@@ -5,17 +5,19 @@ description: Use this skill whenever you decide to delegate substantial coding o
5
5
 
6
6
  # typeclaw-codex-cli
7
7
 
8
+ > **Current security boundary:** authenticated Codex CLI delegation is unavailable from model-driven TypeClaw tools. The bash sandbox never receives OpenAI keys, OAuth tokens, or Codex credential profiles, regardless of role. Do not start the tmux/worktree delegation flow for work that requires authentication. A direct operator may authenticate and run Codex themselves from the host side, outside the model tool boundary. The mechanics below are retained for unauthenticated diagnostics and for a future explicitly brokered runtime, not as a credential workaround.
9
+
8
10
  You can delegate work to Codex CLI, OpenAI's official coding agent. The agent runs as an interactive TUI: it plans, edits files, runs tools, asks for approval — the full loop. You drive it through tmux because your own process has no TTY, you isolate it in a dedicated `git worktree` so its experiments never touch the live agent checkout, and you detect "turn done" through a `Stop` hook that writes a sentinel file (not by parsing the TUI buffer).
9
11
 
10
12
  This skill is for the case where Codex CLI is the right tool: hard architecture work, multi-file refactors, deep code analysis, a second-opinion read on something you wrote (especially when you already used Claude Code and want OpenAI's view, or vice versa). It is **not** for trivial edits — the round-trip cost (worktree setup + process spawn + auth check + TUI init + at least one full Codex turn) is 15–45 seconds and several thousand tokens of someone else's context window. Do trivial edits yourself.
11
13
 
12
- The shape of this skill is intentionally a mirror of `typeclaw-claude-code`: the worktree model, the tmux driving, the `.session-id` discovery, the multi-turn loop, the cleanup discipline are all byte-for-byte equivalent because Codex CLI's hook system ships the same event names (`SessionStart`, `Stop`), the same JSON payload shape (`session_id`, `transcript_path`, `cwd`, `hook_event_name` on stdin), and the same per-session filenames work. What differs is the install path (`@openai/codex` npm package, not curl-bash), the config file location (`~/.codex/hooks.json`, not `~/.claude/settings.json`), the onboarding dialog set (Auth + TrustDirectory, no theme picker), the auth mechanism (`OPENAI_API_KEY` or `codex login`, not Anthropic-specific OAuth), and the project-instruction file (`AGENTS.md`, not `CLAUDE.md`). The runbook is the same; the credentials and the pre-prompt modals differ.
14
+ The shape of this skill is intentionally a mirror of `typeclaw-claude-code`: the worktree model, tmux driving, session discovery, multi-turn loop, and cleanup discipline are equivalent. Codex's direct-operator host authentication differs from Claude's, but neither credential path is available to model-driven TypeClaw tools.
13
15
 
14
16
  ## Run the delegation inside `operator`, not inline
15
17
 
16
18
  Once you've decided Codex CLI is the right tool, spawn the bundled `operator` subagent to do the actual driving — don't run the worktree setup, the tmux session, the polling loop, the multi-turn decision loop, and the cleanup inline in your own context. The whole loop typically takes several minutes and produces large amounts of intermediate output (TUI buffer captures, Stop sentinels per turn, JSONL transcript references); running it inline blocks the user from talking to you and burns through your context window before you ever get to the synthesis step. `operator` is write-capable and runs the same loop, then returns a clean final report (what codex produced, what `git diff main..cx-<id>` shows, what you should review). You ship the worktree, the prompt, and the safety constraints to operator; operator ships you back the diff and the summary.
17
19
 
18
- Exception: a quick sanity ping (`codex --version` to check the binary exists, `env | grep OPENAI` to check auth). Those are single fast bash calls — do them inline. The "spawn through operator" rule applies to anything that runs `codex` itself as an interactive TUI.
20
+ Exception: a quick unauthenticated sanity ping (`codex --version` to check the binary exists). Do it inline. Do not probe authentication state. The "spawn through operator" rule applies to anything that runs `codex` itself as an interactive TUI.
19
21
 
20
22
  ## When to delegate to Codex CLI
21
23
 
@@ -32,46 +34,15 @@ Do **not** use Codex CLI for:
32
34
  - Anything where the user is watching your tool calls and wants to see each step — Codex's intermediate output is captured but not streamed back to the user.
33
35
  - Tasks that depend on context you haven't extracted yet. Codex won't have repo-wide context either; you have to brief it explicitly (it will read `AGENTS.md` from the worktree root, but anything outside that file you must put in the prompt).
34
36
 
35
- ## First-time auth (interactive)
36
-
37
- If `codex` is installed but no credential is set up, you have to broker the auth flow yourself. The user is talking to you through the TUI (or a channel); you walk them through one of two paths.
38
-
39
- **Decision rule, top to bottom:**
40
-
41
- 0. **typeclaw may have already done it for you.** If the agent was initialized with the `openai-codex` provider (the user pasted/ran OAuth into typeclaw itself), typeclaw writes `~/.codex/auth.json` automatically on every container start — provided `docker.file.codexCli: true` is set. Check `test -f ~/.codex/auth.json && jq -e '.tokens.access_token' ~/.codex/auth.json >/dev/null`; if both succeed, skip auth and go straight to delegation. The file is refreshed on every start via the newer-wins compare in `src/secrets/export-codex-auth-file.ts`, so a stale credential gets replaced without user intervention as long as the typeclaw-side credential is fresher.
42
- 1. **Already authenticated some other way?** Check both env (`env | grep -E '^(OPENAI_API_KEY|CODEX_API_KEY)='`) and on-disk (`test -f ~/.codex/auth.json`). If either resolves, skip auth entirely.
43
- 2. **User has an OpenAI API account** (api.openai.com billing, no ChatGPT Plus/Pro subscription) → API key path.
44
- 3. **User has a ChatGPT Plus / Pro / Team / Enterprise subscription and wants to use their subscription credits** → OAuth path via `codex login`.
45
- 4. **User is unsure** → ask which kind of OpenAI account they have. Both paths are equally low-friction. Pick by account shape, not by flow complexity.
46
-
47
- Both paths converge on the same final steps: read `.env`, merge one new `KEY=value` line or a copied `~/.codex/auth.json`, write back with the `nonWorkspaceWrite` guard ack, verify, and prompt the user to restart the container. Only the credential medium differs.
48
-
49
- ### API key path
50
-
51
- 1. Ask the user: "Paste your OpenAI API key (starts with `sk-`) — or say 'cancel' to use the OAuth flow instead."
52
- 2. **Validate** the pasted value before writing: `/^sk-[A-Za-z0-9_-]{20,}$/`. If it doesn't match, refuse and ask again — neither the guard nor the restart tool catches a malformed token.
53
- 3. **Read** the existing `.env` first (if any). Parse it into a key→value map so you don't clobber unrelated entries.
54
- 4. **Reconstruct** the full `.env` content with `OPENAI_API_KEY=<value>` added or replaced. (Codex also honors `CODEX_API_KEY` but that variant only takes effect for `codex exec`, not the interactive TUI we drive here — use `OPENAI_API_KEY`.)
55
- 5. **Write** with `acknowledgeGuards: { nonWorkspaceWrite: true }`. `.env` is in the `nonWorkspaceWrite` guard's deny set; the call fails without the ack flag.
56
- 6. **Verify** by re-reading the file.
57
- 7. **Ask the user**: "Auth is on disk. The container needs to restart to load it (TUI will briefly disconnect). May I restart now, or do you have other changes to make first?"
58
- 8. On yes → call the `restart` tool. On no → tell them to run `typeclaw restart` themselves when ready.
59
-
60
- ### OAuth path
37
+ ## Authentication boundary
61
38
 
62
- Unlike Claude Code's `claude setup-token` flow, Codex CLI's OAuth (via `codex login`) writes a credential **file** (`~/.codex/auth.json`) on the user's machine rather than printing a long-lived token to stdout. The user logs in locally, copies that file, and you place it into the container's `~/.codex/auth.json` via a write call.
39
+ Authentication is an **operator-owned host action**. Model-driven tools cannot read or write `.env`, `secrets.json`, `auth.json`, `~/.codex/auth.json`, or the persistent credential directories, and must never ask a user to paste a key, token, or credential-file contents into chat.
63
40
 
64
- Why this works: `~/.codex/auth.json` is the canonical credential location for the Codex CLI. From the official auth docs: "Credentials are persisted to `~/.codex/auth.json` by default." A typeclaw container, like any CI/headless environment, can simply receive that file from the user's already-authenticated machine. The container has no browser and cannot complete the `localhost:1455` OAuth callback on its own.
41
+ Even when TypeClaw's trusted runtime has provider credentials, model-driven bash does not inherit them and cannot open the exported profile. There is no readiness check that turns authenticated delegation on.
65
42
 
66
- 1. Confirm with the user: "Do you have the `codex` CLI installed on your local machine and are you signed in to it with your ChatGPT subscription? If not, install with `npm install -g @openai/codex`, then `codex login` and complete the browser authorization."
67
- 2. Once they confirm, instruct them: "On your machine, the file at `~/.codex/auth.json` now contains your credential. Paste its contents back to me — it's a small JSON object with an `OPENAI_API_KEY` field, OR a `tokens` object with `access_token` / `refresh_token` / `id_token`. Either shape is valid. Treat it like a password (the `access_token` if present is short-lived but the `refresh_token` is long-lived)."
68
- 3. When they paste, **validate** before writing: it must `JSON.parse` cleanly into an object with at least one of `{ OPENAI_API_KEY, tokens }`. If neither field is present, refuse and ask again — the user may have pasted only a fragment.
69
- 4. **Write to `~/.codex/auth.json` inside the container**, not `.env`. Create `~/.codex/` first if missing. Use `acknowledgeGuards: { nonWorkspaceWrite: true }` (the `~/.codex/` dir is outside `workspace/`). `~/.codex/auth.json` is symlinked by typeclaw's entrypoint shim to a host-side persistent path, so this write survives container restarts and codex's in-place token refreshes "just work" — see `references/auth-flow.md` "Persistence across container restarts" for the full mechanism.
70
- 5. **Verify** by re-reading the file and re-parsing.
71
- 6. **Ask before restart** (same prompt as the API key path).
72
- 7. On yes → call the `restart` tool. On no → `typeclaw restart` themselves when ready.
43
+ Stop and tell the operator that they must authenticate and invoke Codex CLI directly from the **host side**. Do not promise that `typeclaw restart`, a role grant, a guard acknowledgement, or an existing provider login will make authenticated model-driven delegation available. Any direct Codex login must be completed entirely by the operator; do not request the resulting artifact.
73
44
 
74
- The full validation rules, the failure modes on the user's side (their `codex` CLI is signed out, their subscription is expired, their `auth.json` is missing or malformed), and the rationale for not doing the OAuth dance in-container are in `references/auth-flow.md`.
45
+ The auth picker is also operator-owned. If it appears in the delegated TUI, abort the session and report that host-side authentication is required. Never navigate the picker or transmit a credential through tmux, a prompt, a tool argument, or a file writable by the model. See `references/auth-flow.md`.
75
46
 
76
47
  ### Cost-cap warning
77
48
 
@@ -83,8 +54,8 @@ Before you spawn `codex` for any real work:
83
54
 
84
55
  - **`docker.file.codexCli: true`** in `typeclaw.json`. Verify with `which codex`; if missing, the toggle isn't on. Tell the user to enable it and `typeclaw start --build`.
85
56
  - **`docker.file.tmux: true`** (default `true`, but check). Verify with `which tmux`.
86
- - **Auth set up** — see above. Verify with `env | grep -E '^(OPENAI_API_KEY|CODEX_API_KEY)='` OR `test -f ~/.codex/auth.json`.
87
- - **No onboarding seed needed.** Unlike Claude Code's `~/.claude.json` + `hasCompletedOnboarding: true` shim, Codex CLI has NO theme picker, NO telemetry consent dialog, NO terms-of-service prompt — verified directly against the upstream `codex-rs/tui/src/onboarding/onboarding_screen.rs` state machine. Codex's onboarding has exactly two interactive steps after the brief Welcome animation: an **Auth picker** (skipped automatically when `OPENAI_API_KEY` is in env or `~/.codex/auth.json` exists) and a **TrustDirectory** prompt (fires once per new cwd). The "Driving the session" section below clears both as a loop. If neither auth medium is present, the Auth picker fires and the delegation cannot proceed without runtime intervention — bail to the user.
57
+ - **No authenticated model-driven path.** If the task requires an OpenAI/Codex account, stop and hand execution to the direct host-side operator. Do not probe env vars or credential files.
58
+ - **Auth picker means stop.** Model-driven tools receive no Codex credential medium. If the picker appears, abort and hand execution to the direct host-side operator. The workspace-trust prompt is separate and may be handled only for an otherwise unauthenticated diagnostic.
88
59
  - **Agent folder is a git repo.** Verify with `git -C /agent rev-parse --is-inside-work-tree`. The worktree model below requires it. Codex CLI **additionally** requires a git repo by default (use `--skip-git-repo-check` to override, but we don't — the worktree is a git checkout by construction).
89
60
  - **No uncommitted changes that you care about.** `git -C /agent status --porcelain` should be clean, or you should be willing to set the working tree aside before delegating. The worktree is a separate checkout, so codex can't see your uncommitted changes — meaning codex operates on the last committed state. If the user wants codex to work with in-progress edits, commit them first (even on a WIP branch).
90
61
 
@@ -197,10 +168,10 @@ The minimum protocol — translate to your actual tool calls:
197
168
  1. Create the worktree.
198
169
  2. `tmux new-session -d -s cx-<id> -c /tmp/cx-<id> codex`. Do not pass any `--session-id` flag (the hook payload UUID is the source of truth).
199
170
  3. Wait ~3 seconds for the TUI to initialize.
200
- 4. **Clear startup dialogs (BEFORE sending the task prompt).** Codex's onboarding has at most three runtime prompts: the Auth picker (suppressed when `OPENAI_API_KEY` is in env OR `~/.codex/auth.json` exists), the TrustDirectory prompt (fires once per new cwd, so EVERY fresh `/tmp/cx-<id>/` triggers it), and the hook trust prompt (fires once per `~/.codex/hooks.json` change). Run this as a **loop**, not a one-shot: clearing one dialog can immediately reveal the next, and you must keep polling until codex's actual input prompt is visible (it renders a bottom-of-pane composer with a `▌` or similar prompt indicator).
171
+ 4. **Clear startup dialogs (BEFORE sending the task prompt).** The Auth picker is a hard stop; do not navigate it. TrustDirectory and hook-trust prompts may appear for unauthenticated diagnostics. Run detection as a loop so an auth picker revealed after another dialog still aborts the session.
201
172
 
202
173
  The three known modals, with the exact keystrokes for each:
203
- - **Auth picker** — "Sign in to Codex" with options to pick ChatGPT OAuth, Device code, or API key. If this fires despite `OPENAI_API_KEY` being set, the env var isn't being read — abort with `Ctrl-c` (or `/exit`) and surface to the user. Do NOT attempt to navigate the picker on the user's behalf.
174
+ - **Auth picker** — "Sign in to Codex" with OAuth, device-code, or API-key options. Abort with `Ctrl-c` (or `/exit`) and tell the direct operator to authenticate and run Codex host-side. Do not navigate it.
204
175
 
205
176
  - **TrustDirectory** — "Do you trust the files in this directory?" Options are `[Yes, trust] [No, exit]` with focus on **Yes** by default. Resolution: bare `tmux send-keys -t cx-<id> Enter`. Always verify the pane text matches the trust dialog before pressing Enter.
206
177
 
@@ -289,7 +260,7 @@ A re-statement, because this is where the skill is most often misused:
289
260
  - **Trivial edits**: the round-trip cost dominates. Do it yourself.
290
261
  - **Tasks needing live user visibility**: codex's tool calls don't stream back through TypeClaw. The user sees a long pause, not progress. Use your own tools.
291
262
  - **Tasks where you don't have the context to brief codex**: spend tokens narrowing the problem first. A vague delegation produces a vague result.
292
- - **Anything secret beyond `OPENAI_API_KEY` / `~/.codex/auth.json`**: codex only sees the prompt you send it and the files in its worktree. Don't try to pass secrets through the prompt — they'll land in codex's transcript and in your sentinel.
263
+ - **Any secret, including OpenAI/Codex credentials**: never pass it through the prompt or worktree. It would land in Codex's transcript and sentinels.
293
264
 
294
265
  ## Things you must not do
295
266
 
@@ -302,12 +273,11 @@ A re-statement, because this is where the skill is most often misused:
302
273
  - **Do not merge codex's branch into main without reviewing the diff.** The `git diff main..cx-<id>` is your review surface. Skipping the diff and merging blindly means you don't actually know what shipped.
303
274
  - **Do not commit `/tmp/cx-<id>/` artifacts back to the agent folder.** The sentinel, the hook script, the captured pane content are scratch — they live in `/tmp/`, they die with `worktree remove`.
304
275
  - **Do not paste Codex's output verbatim into a commit message or a user reply.** Summarize and attribute. You're accountable for the work you ship.
305
- - **Do not put `OPENAI_API_KEY` or `~/.codex/auth.json` contents in `typeclaw.json`, in a prompt, or in any committed file.** API keys live in `.env`; OAuth credentials live in `~/.codex/auth.json` (a non-committed file under `$HOME`). Period.
276
+ - **Do not put `OPENAI_API_KEY` or `~/.codex/auth.json` contents in `typeclaw.json`, a prompt, a worktree, or any model-accessible file.** Credential provisioning is direct-operator host work; the model does not edit `.env` or copy `auth.json`.
306
277
  - **Do not poll the JSONL transcript directly as the done-signal.** The JSONL has documented race conditions (the file can be stale when `Stop` fires). The sentinel is the reliable signal; the JSONL is for content, not lifecycle.
307
- - **Do not write to `.env` or `~/.codex/auth.json` without `acknowledgeGuards: { nonWorkspaceWrite: true }`.** Both are in the `nonWorkspaceWrite` guard's deny set; the ack is required on every write, not just the first one.
308
- - **Do not edit `.env` or `~/.codex/auth.json` with the `edit` tool's patch semantics.** Use read-modify-write: read the whole file, reconstruct the new content, write the whole file. A fragile `oldText` match could corrupt unrelated lines.
309
- - **Do not run `codex login` inside the container.** It's an OAuth flow that wants a browser. The container has no display, no browser, and is often on a different machine from the user anyway. Always have the user run `codex login` on their own machine and paste the resulting `~/.codex/auth.json` back to you; never spawn it in tmux on this side.
310
- - **Do not echo, log, or transcribe the pasted credential back to the user, into a sentinel, into a commit message, or into any message you send.** The `refresh_token` inside `~/.codex/auth.json` is a long-lived credential. Confirm receipt with "got it, validating" — never with the token itself.
278
+ - **Do not read, write, edit, parse, or verify `.env`, `secrets.json`, `auth.json`, `~/.codex/auth.json`, or any credential value.** These are outside the model-driven tool boundary; guard acknowledgements do not make credential handling acceptable.
279
+ - **Do not run `codex login` inside the container, and do not ask the user to paste its resulting credential file.** Authentication remains entirely on the operator's host side.
280
+ - **Do not ask for, receive, echo, log, or transcribe credentials.** If a user offers one, tell them not to send it and direct them to host-side setup.
311
281
  - **Do not navigate Codex's Auth picker on the user's behalf.** If the picker fires (because no env var and no `auth.json` is present), the user owes you an auth step and the delegation cannot proceed. Bail and surface to the user; do not try to pick "API key" then paste anything into the in-TUI prompt.
312
282
  - **Do not invent answers to Codex's clarifying questions.** If you can't derive the answer from the original task brief, surface the question to the user. Wrong answers compound across multi-turn delegations.
313
283
  - **Do not exceed 8 turns per delegation.** Abort, capture what you have, surface. Long delegations almost always mean the task wasn't shaped right.
@@ -316,7 +286,7 @@ A re-statement, because this is where the skill is most often misused:
316
286
 
317
287
  ## Cross-references
318
288
 
319
- - **`references/auth-flow.md`** — both auth paths in detail: the API-key recap, the OAuth user-machine flow (what to tell the user, what their `~/.codex/auth.json` looks like, validation rules), and the failure-mode catalogue (expired subscription, wrong account, malformed paste).
289
+ - **`references/auth-flow.md`** — the authentication boundary: authenticated delegation is unavailable to model-driven tools, and direct host-side setup and execution belong to the operator.
320
290
  - **`references/tmux-driving.md`** — full polling implementation, ANSI handling, session-died recovery, the `capture-pane` fallback details, the alternate-screen vs `--no-alt-screen` decision, the worktree-is-not-scratch distinction.
321
291
  - **`references/stop-hook.md`** — complete `Stop` event JSON schema for Codex CLI, transcript JSONL schema notes, documented race conditions to handle.
322
292
  - **`typeclaw-config`** — the `docker.file.codexCli` toggle that gates the install.
@@ -1,166 +1,29 @@
1
- # Auth flow — interactive (Codex CLI)
1
+ # Auth flow — operator-owned (Codex CLI)
2
2
 
3
- Deep dive for the auth paths. Read it when `SKILL.md`'s "First-time auth (interactive)" section sends you here, or when an auth attempt fails and you need to understand what went wrong.
3
+ Codex authentication is outside the model-driven tool boundary. **Authenticated Codex delegation is unavailable from model-driven TypeClaw tools.** The agent must not read, print, parse, copy, write, verify, or probe any credential value or credential file.
4
4
 
5
- The two paths are intentionally symmetric: in both, the user produces one artifact on their side, pastes it to you, you validate it, you do read-modify-write on `.env` (or write `~/.codex/auth.json`), you offer a restart. Only the credential medium differs.
5
+ ## No readiness bypass
6
6
 
7
- ## Path 0 — typeclaw-managed OAuth (auto-export, no user action)
7
+ Do not check environment variables or profile-file existence as a way to enable delegation. TypeClaw masks canonical credential files and directories from model-driven bash, strips reusable credential environments, and unconditionally blocks non-bash tools from opening them. Provider authentication available to trusted runtime code is not delegated to a model-driven Codex child.
8
8
 
9
- Before walking the user through either interactive path, check whether typeclaw has already provisioned `~/.codex/auth.json` from its own secrets store. This is the canonical state for users who configured `openai-codex` as their typeclaw model backend during `typeclaw init`:
9
+ ## When authentication is missing
10
10
 
11
- - `typeclaw init` ran the OAuth flow against pi-ai and wrote the credential to `secrets.json#providers.openai-codex` (shape: `{ type: 'oauth', access, refresh, expires, accountId }`).
12
- - `docker.file.codexCli: true` is set in `typeclaw.json`, so the Codex CLI is installed in the container.
13
- - On every `typeclaw start` / `typeclaw restart`, `src/run/index.ts`'s boot sequence calls `exportCodexAuthFileForAgent`, which:
14
- - Returns early (zero filesystem touches) if `codexCli` is off or no `openai-codex` credential exists.
15
- - Otherwise emits the modern `~/.codex/auth.json` shape (`{ tokens: { access_token, refresh_token, account_id? } }`) — no top-level `expires`, because Codex CLI re-derives expiry from the JWT on every load.
16
- - Compares the JWT `exp` claim in the on-disk access token against typeclaw's stored expiry. If the on-disk token is the same or newer (Codex CLI rotated it in-place since the last typeclaw write), the file is left alone — no clobber. If typeclaw's copy is strictly fresher (the user re-pasted OAuth), the file is replaced atomically.
11
+ Stop the delegation and tell the operator:
17
12
 
18
- Detection check before launching the interactive flow:
13
+ > Authenticated Codex CLI delegation is unavailable from model-driven TypeClaw tools. Authenticate and run Codex directly as the host-side operator. Do not send a key, token, or `auth.json` contents in chat.
19
14
 
20
- ```sh
21
- test -f ~/.codex/auth.json \
22
- && jq -e '.tokens.access_token' ~/.codex/auth.json >/dev/null
23
- ```
15
+ The operator may manage Codex CLI authentication directly on the host. The model must not broker that path, request the resulting artifact, or transfer it into the container.
24
16
 
25
- If both succeed, the credential is ready; skip Paths A and B and proceed to delegation. If only the first succeeds but the second fails (file exists but no `tokens.access_token`), the file is either an API-key shape (legacy) or corrupt — the runtime exporter's next-start pass will overwrite it from `secrets.json` if typeclaw has a valid OAuth credential, but for the current delegation you can either re-run `typeclaw restart` to force the resync, or fall back to interactive Path A / Path B.
17
+ If the Codex auth picker appears, exit the delegated session. Do not navigate the picker, run `codex login` in the container, paste a key through tmux, or ask the user to paste `~/.codex/auth.json`.
26
18
 
27
- If the user has `docker.file.codexCli: true` but typeclaw was initialized with a non-`openai-codex` model backend (e.g. `anthropic`, `openai`, `fireworks`), Path 0 won't fire — the auto-export's gate-2 returns because `secrets.json#providers.openai-codex` is absent. The user's manually-pasted `~/.codex/auth.json` (if any) is never touched in that case. Fall through to Path A or Path B.
19
+ ## Runtime separation
28
20
 
29
- ## Path A — API key (`OPENAI_API_KEY`)
21
+ Trusted runtime provisioning does not authorize a model-driven child. Any exported persistent profile remains masked, and the sandbox intentionally does not mount it or preserve OpenAI/Codex credential variables. Restarting cannot change this policy boundary.
30
22
 
31
- The API key path is direct. Summary:
23
+ ## Hard prohibitions
32
24
 
33
- 1. Prompt user for `sk-…`.
34
- 2. Validate `/^sk-[A-Za-z0-9_-]{20,}$/`.
35
- 3. Read `.env`, merge `OPENAI_API_KEY=<value>` into the parsed map, reconstruct full content, write with `acknowledgeGuards: { nonWorkspaceWrite: true }`.
36
- 4. Verify.
37
- 5. Ask before restart.
38
-
39
- When to recommend it: the user has an **OpenAI API account** (api.openai.com billing, no ChatGPT subscription) or specifically wants per-token billing. They get their key from `platform.openai.com/api-keys`. Cost is metered per-token against the API workspace.
40
-
41
- ### `OPENAI_API_KEY` vs `CODEX_API_KEY`
42
-
43
- Both env vars are recognized by the CLI, but they behave differently:
44
-
45
- - `OPENAI_API_KEY` — Used by both the interactive TUI and `codex exec`. This is the right variable for our flow (we drive the TUI).
46
- - `CODEX_API_KEY` — **Only honored by `codex exec`**. Setting it for the TUI silently does nothing; the TUI will still fire the Auth picker. Empirically confirmed in upstream docs. Use `OPENAI_API_KEY`.
47
-
48
- ### Auth precedence on the Codex side
49
-
50
- When multiple credentials coexist, Codex CLI resolves in this order (highest first):
51
-
52
- 1. `~/.codex/auth.json` if present — this OVERRIDES env vars for the interactive TUI.
53
- 2. `OPENAI_API_KEY` from env.
54
- 3. (Picker fires.)
55
-
56
- The first-match-wins rule is the OPPOSITE of how some Anthropic flows resolve (where env wins over file). If the user previously logged in with `codex login` and the `auth.json` still exists, setting `OPENAI_API_KEY` in `.env` will appear to do nothing because Codex preferentially loads `auth.json`. Mitigation: ask the user to remove `~/.codex/auth.json` if they want the env path to take effect.
57
-
58
- ## Path B — OAuth (`codex login` → `~/.codex/auth.json` file copy)
59
-
60
- This is the path for users with a ChatGPT **Plus / Pro / Team / Enterprise** subscription. Inference cost draws against the subscription's monthly Codex credit pool, not per-token billing.
61
-
62
- Unlike Anthropic's `claude setup-token` (which prints a long-lived token to stdout), Codex's `codex login` writes a credential **file** at `~/.codex/auth.json` on the user's machine. The user copies that file's contents back to you, and you write it to `~/.codex/auth.json` inside the container.
63
-
64
- ### Why on the user's machine, not in the container
65
-
66
- The OAuth flow uses a `localhost:1455` callback server, which means the browser and the local CLI process need to be on the same machine. A typeclaw container has no browser, no display, and (for remote-host deployments) is on a different machine from the user's browser anyway. The user's local machine already has `codex` installed for them to be a subscriber in the first place — they're the right place to run the one-off `codex login` command.
67
-
68
- There's also a `codex login --device-auth` flag for headless / cross-machine cases, but the resulting credential still lands at `~/.codex/auth.json` on the machine that ran the command, so the user-to-container copy step is the same either way.
69
-
70
- ### Step-by-step
71
-
72
- 1. **Confirm prerequisites with the user, in one message:**
73
-
74
- > To set up OAuth auth, you'll generate a credential file on your own machine. Two prerequisites:
75
- >
76
- > 1. Do you have the `codex` CLI installed locally? If not: `npm install -g @openai/codex`.
77
- > 2. Do you have a paid ChatGPT subscription? (Codex via OAuth requires Plus, Pro, Team, or Enterprise.)
78
- >
79
- > Once both are true, reply "ready" and I'll send the next step.
80
-
81
- This single confirmation up-front is the difference between a one-paste flow and a multi-turn debugging session when the user discovers mid-flow that their CLI isn't installed.
82
-
83
- 2. **When the user confirms, send the generation instructions:**
84
-
85
- > Great. On your machine, run:
86
- >
87
- > ```sh
88
- > codex login
89
- > ```
90
- >
91
- > It opens a browser, you authorize with your ChatGPT account, and the terminal confirms "Signed in." Now run:
92
- >
93
- > ```sh
94
- > cat ~/.codex/auth.json
95
- > ```
96
- >
97
- > Copy the entire JSON output — it's a small object with either an `OPENAI_API_KEY` field, OR a `tokens` object containing `access_token` / `refresh_token` / `id_token`, OR both. Paste it back to me. Treat it like a password — the `refresh_token` if present is long-lived.
98
-
99
- 3. **Wait for the user's reply.** Expected shapes:
100
- - **A JSON object string** starting with `{`. The expected shape.
101
- - **An error message** if `codex login` failed on their side. See the failure-mode list below.
102
- - **"cancel"** or equivalent. Drop the flow cleanly.
103
-
104
- 4. **Parse and validate**, in order:
105
- 1. Trim leading/trailing whitespace.
106
- 2. `JSON.parse(value)` — if it throws, refuse: "That doesn't look like valid JSON. Make sure you pasted the entire `cat` output including the surrounding `{` and `}`."
107
- 3. The parsed object must be a non-null plain object with at least one of: an `OPENAI_API_KEY` string field, OR a `tokens` object with at least one of `access_token`/`refresh_token`. If neither path is present, refuse and ask again.
108
- 4. If validation fails twice, drop OAuth and recommend the API-key path.
109
-
110
- 5. **Confirm receipt without echoing the credential.** Reply something like "Got it, validating and writing to `~/.codex/auth.json`." Never include any token field in your reply, in a log line, in a sentinel, in a commit message, or anywhere else.
111
-
112
- 6. **Ensure the directory exists.** Create `~/.codex/` if missing (`mkdir -p ~/.codex`). The Dockerfile layer creates it for the hooks config but won't fail if it already exists.
113
-
114
- 7. **Write `~/.codex/auth.json`** with the JSON-stringified canonical form (re-emit via `JSON.stringify(parsed, null, 2)` so you don't preserve weird whitespace from the paste). Use `acknowledgeGuards: { nonWorkspaceWrite: true }`.
115
-
116
- 8. **Verify** by re-reading the file and re-parsing.
117
-
118
- 9. **Ask before restart**, same prompt as the API-key path.
119
-
120
- 10. On yes → call the `restart` tool. On no → `typeclaw restart` themselves when ready.
121
-
122
- 11. **Done.** There is no auth scratch directory, no tmux session to tear down, no worktree. The OAuth path has the same on-disk footprint as the API-key path: one credential file under `$HOME`.
123
-
124
- ### Persistence across container restarts
125
-
126
- `~/.codex/auth.json` inside the container is a symlink — installed by `typeclaw`'s entrypoint shim on every boot — pointing at `/agent/.typeclaw/home/.codex/auth.json`, which lives in the bind-mounted agent folder on the host. Two consequences:
127
-
128
- 1. **You only paste auth.json once.** After the first successful write, `typeclaw restart` (or `typeclaw stop && typeclaw start`) preserves the credential without any further user action. Re-pasting is only needed when the refresh token itself is revoked (the user `/logout`s from their ChatGPT account, or the token expires after ~one year of inactivity).
129
- 2. **Codex's in-place refresh "just works."** When codex rotates tokens (it rewrites `auth.json` with a refreshed access token plus the updated refresh-token state), the write goes through the symlink and lands on the persistent host-side path. On the next container start the symlink resolves back to the same file, so refreshes compound across runs the same way they do on a persistent CI runner — this is the pattern OpenAI's own [Codex CI/CD auth guide](https://developers.openai.com/codex/auth/ci-cd-auth) prescribes.
130
-
131
- You do not need to do anything to enable this — the symlink is unconditional and idempotent, installed before the agent process ever starts. The persistent directory is gitignored (`.typeclaw/home/` in the generated `.gitignore`) so the credential never enters version control even though it sits inside the agent folder.
132
-
133
- If the user asks "won't I lose auth.json on restart?" the answer is "no — it's symlinked to a host-side path; only `workspace/` and the container's regular `$HOME` are ephemeral."
134
-
135
- ## Failure modes on the user's side
136
-
137
- These all surface as the user's reply being an error message instead of a JSON object. Recognize them, do not validate them as credentials, and respond with the matching guidance.
138
-
139
- - **"command not found: codex"** — they don't have the CLI installed locally. Point them at `npm install -g @openai/codex`.
140
- - **"You don't have access to a paid ChatGPT plan"** — they're on a free account. `codex login` (via ChatGPT OAuth) requires Plus / Pro / Team / Enterprise. They either upgrade or use the API-key path.
141
- - **"Browser didn't open"** — they're on a headless local environment. Recommend `codex login --device-auth` for the device-code flow, which prints a URL+code they can complete on any device.
142
- - **`~/.codex/auth.json` doesn't exist after login** — login failed silently. Have them re-run `codex login` and watch for error output.
143
- - **They report success but pasted a string that fails JSON.parse** — most likely they pasted just one field or shell prompt cruft. Re-ask: "Paste the full contents of `~/.codex/auth.json` starting with `{` and ending with `}`."
144
-
145
- ## Failure modes after you've written the credential
146
-
147
- - **`typeclaw restart` fails or the container won't come up** — the credential is on disk, the restart is the problem. Don't re-prompt for auth; surface the restart failure and tell the user to run `typeclaw restart` from their host shell to see the underlying error.
148
- - **`codex` invocations after restart still hit the Auth picker** — the credential file is being rejected. Three likely causes:
149
- 1. **JSON parse error inside Codex.** The file is on disk but malformed in a way `JSON.parse` accepted but Codex's schema validator rejects. `cat ~/.codex/auth.json | jq .` to inspect; surface to the user.
150
- 2. **`OPENAI_API_KEY` env var conflict.** Per the precedence rules above, `auth.json` overrides `OPENAI_API_KEY` — but if both are present and `auth.json` is malformed, Codex MAY fall back to the env var, which could be wrong/stale. Check `.env` for a stale `OPENAI_API_KEY` line and remove if the user is committing to OAuth.
151
- 3. **Token expired or revoked.** Tokens have a finite lifetime; revocation happens if the user signed out from `chatgpt.com` or revoked the Codex CLI integration. Have them re-run `codex login` and re-paste.
152
-
153
- ## Things you must not do during auth
154
-
155
- - **Do not run `codex login` inside the container.** Use the user-machine flow above. The in-container OAuth dance doesn't work — the container has no browser, and even with `--device-auth` the resulting credential file would land inside the container's `$HOME`, defeating the user-paste pattern that lets the typeclaw operator broker the credential without seeing it.
156
- - **Do not log, echo, paste-back, or otherwise transcribe the user's credential.** Not in a confirmation message, not in a sentinel, not in a commit. The `refresh_token` is long-lived; a leak is significantly worse than a momentary "did you mean this?" reflection.
157
- - **Do not write the credential to `~/.codex/auth.json` until you've validated its format.** A malformed credential quietly turns into a broken auth that surfaces only on the next codex invocation, long after the user has moved on.
158
- - **Do not retry validation more than once.** If the first paste fails JSON.parse, ask once with clearer guidance ("paste the full output of `cat ~/.codex/auth.json` starting with `{`"). If the second also fails, drop the OAuth path and recommend API-key auth.
159
- - **Do not advise the user to `typeclaw shell` and run `codex login` inside the container as a "fallback".** It does not work — the container has no browser. Use the user-machine flow.
160
- - **Do not assume the `auth.json` schema.** OpenAI may change the shape — today's keys are `OPENAI_API_KEY` and `tokens.{access_token, refresh_token, id_token}`, but future versions may add or rename fields. Validate by presence of at least ONE known key, not by exhaustive shape match.
161
- - **Do not write to `~/.codex/auth.json` without `acknowledgeGuards: { nonWorkspaceWrite: true }`.** Same guard contract as `.env` writes.
162
- - **Do not patch-edit `~/.codex/auth.json`.** Read-modify-write the whole file (or just write the new contents wholesale — there's nothing to preserve from a stale `auth.json` on a fresh delegation). Note that `~/.codex/auth.json` is a symlink into `/agent/.typeclaw/home/.codex/auth.json` — your write follows the link automatically and lands at the persistent host-side path, which is exactly what you want.
163
- - **Do not move, delete, or replace the `~/.codex/auth.json` symlink with a real file.** The entrypoint shim re-establishes it on every container start, so any in-container `mv`/`cp`/`rm -f && touch` against the link is at best wasted work and at worst loses the credential on the next restart. Write THROUGH the symlink instead.
164
- - **Do not write directly to `/agent/.typeclaw/home/`.** That path is a system-owned directory managed by the entrypoint shim. Use the `$HOME`-side path (`~/.codex/auth.json`) and let the symlink do its job. The persistent root may move or be renamed across typeclaw versions; the `$HOME` path is the stable contract.
165
- - **Do not store `OPENAI_API_KEY` in `~/.codex/auth.json`'s `OPENAI_API_KEY` field as a workaround for env-var precedence.** If the user wants the API-key path, the canonical location is `.env`. Mixing the two creates ambiguity for the next person debugging an auth failure.
166
- - **Do not branch on local-vs-remote container topology.** The user-machine flow is the same whether the container is on the user's laptop or on a remote host — the user runs `codex login` on whatever local machine they're at, the credential works in either container.
25
+ - Never ask for or accept an API key, access token, refresh token, ID token, or credential-file contents in chat.
26
+ - Never use `read`, `write`, `edit`, `look_at`, channel attachment tools, or shell commands to access `.env`, `secrets.json`, `auth.json`, `~/.codex/auth.json`, or their persistent backing directories.
27
+ - Never put credentials in prompts, tmux keystrokes, command arguments, sentinels, transcripts, logs, commits, or scratch files.
28
+ - Never treat a guard acknowledgement as authorization to handle credentials. Canonical credentials are blocked independently of plugin guard hooks.
29
+ - If a credential is offered, tell the user not to send it and redirect them to host-side setup.