typeclaw 0.48.13 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/package.json +5 -5
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/index.ts +144 -72
  4. package/src/agent/live-sessions.ts +2 -2
  5. package/src/agent/live-subagents.ts +1 -0
  6. package/src/agent/plugin-tools.ts +53 -11
  7. package/src/agent/prompt-cache-key.ts +42 -0
  8. package/src/agent/provider-error.ts +179 -10
  9. package/src/agent/restart-handoff/index.ts +7 -14
  10. package/src/agent/reviewer-activity.ts +68 -0
  11. package/src/agent/session-origin.ts +33 -0
  12. package/src/agent/subagents.ts +13 -1
  13. package/src/agent/system-prompt.ts +68 -202
  14. package/src/agent/todo/continuation-policy.ts +12 -4
  15. package/src/agent/tool-file-safety.ts +113 -14
  16. package/src/agent/tool-not-found-nudge.ts +1 -1
  17. package/src/agent/tools/channel-history-render.ts +2 -1
  18. package/src/agent/tools/channel-reply.ts +23 -5
  19. package/src/agent/tools/channel-send.ts +49 -7
  20. package/src/agent/tools/curl-impersonate.ts +11 -2
  21. package/src/agent/tools/post-github-review.ts +77 -15
  22. package/src/agent/tools/skip-response.ts +2 -2
  23. package/src/agent/tools/spawn-subagent.ts +163 -12
  24. package/src/agent/tools/subagent-output.ts +8 -0
  25. package/src/bundled-plugins/backup/README.md +10 -9
  26. package/src/bundled-plugins/backup/runner.ts +140 -58
  27. package/src/bundled-plugins/backup/subagents.ts +58 -26
  28. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  29. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  30. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  31. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  32. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  33. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  34. package/src/bundled-plugins/operator/operator.ts +15 -4
  35. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  36. package/src/bundled-plugins/security/index.ts +50 -2
  37. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  38. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  39. package/src/channels/adapters/discord-bot.ts +122 -67
  40. package/src/channels/adapters/discord-reactions.ts +18 -0
  41. package/src/channels/adapters/discord.ts +114 -8
  42. package/src/channels/adapters/github/inbound.ts +103 -8
  43. package/src/channels/adapters/github/index.ts +251 -19
  44. package/src/channels/adapters/github/last-alive.ts +27 -0
  45. package/src/channels/adapters/github/outbound.ts +54 -18
  46. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  47. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  48. package/src/channels/adapters/github/reactions.ts +100 -0
  49. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  50. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  51. package/src/channels/adapters/github/recovery.ts +106 -0
  52. package/src/channels/adapters/github/review-check.ts +510 -0
  53. package/src/channels/adapters/github/review-submitter.ts +34 -2
  54. package/src/channels/adapters/instagram.ts +32 -14
  55. package/src/channels/adapters/kakaotalk.ts +22 -7
  56. package/src/channels/adapters/line.ts +18 -3
  57. package/src/channels/adapters/outbound-account.ts +20 -0
  58. package/src/channels/adapters/own-reactions.ts +66 -0
  59. package/src/channels/adapters/recovery-correlation.ts +214 -0
  60. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  61. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  62. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/slack-bot.ts +125 -57
  64. package/src/channels/adapters/slack-classify.ts +25 -4
  65. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  66. package/src/channels/adapters/slack-reactions.ts +18 -0
  67. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  68. package/src/channels/adapters/slack.ts +48 -3
  69. package/src/channels/adapters/teams.ts +14 -4
  70. package/src/channels/adapters/telegram-bot.ts +56 -10
  71. package/src/channels/adapters/webex-bot.ts +12 -2
  72. package/src/channels/adapters/webex.ts +12 -2
  73. package/src/channels/background-handoff.ts +434 -0
  74. package/src/channels/background-obligations.ts +893 -0
  75. package/src/channels/continuity-types.ts +271 -0
  76. package/src/channels/github-review-check.ts +598 -0
  77. package/src/channels/github-review-turn-ledger.ts +102 -28
  78. package/src/channels/github-review-verdict-coordinator.ts +72 -12
  79. package/src/channels/github-token-bridge.ts +11 -5
  80. package/src/channels/inbound-journal.ts +1738 -0
  81. package/src/channels/index.ts +6 -1
  82. package/src/channels/manager.ts +17 -7
  83. package/src/channels/recovery-dispatcher.ts +264 -0
  84. package/src/channels/recovery-notice.ts +94 -0
  85. package/src/channels/recovery-outbox.ts +459 -0
  86. package/src/channels/router.ts +2539 -615
  87. package/src/channels/schema.ts +8 -1
  88. package/src/channels/subagent-completion-bridge.ts +17 -14
  89. package/src/channels/types.ts +121 -16
  90. package/src/channels/waiting-reactions.ts +664 -0
  91. package/src/cli/compose.ts +7 -4
  92. package/src/cli/hostd.ts +49 -3
  93. package/src/cli/inspect.ts +11 -14
  94. package/src/coding-agent/broker-body.ts +38 -0
  95. package/src/coding-agent/broker.ts +290 -0
  96. package/src/coding-agent/claude.ts +95 -0
  97. package/src/coding-agent/codex.ts +104 -0
  98. package/src/coding-agent/index.ts +506 -0
  99. package/src/coding-agent/omo-state.ts +69 -0
  100. package/src/coding-agent/omo-stream.ts +98 -0
  101. package/src/coding-agent/omo.ts +192 -0
  102. package/src/coding-agent/runner.ts +263 -0
  103. package/src/coding-agent/tool.ts +62 -0
  104. package/src/coding-agent/worktree.ts +355 -0
  105. package/src/compose/restart.ts +10 -3
  106. package/src/compose/start.ts +20 -3
  107. package/src/config/config.ts +10 -3
  108. package/src/config/providers.ts +12 -9
  109. package/src/container/exit-reason.ts +44 -0
  110. package/src/container/index.ts +5 -0
  111. package/src/container/log-archive.ts +51 -13
  112. package/src/container/memory-limit.ts +1 -1
  113. package/src/container/memory-oversubscription.ts +36 -6
  114. package/src/container/oom-events.ts +86 -0
  115. package/src/container/restart.ts +2 -0
  116. package/src/container/shared.ts +8 -1
  117. package/src/container/start.ts +25 -13
  118. package/src/container/stop.ts +6 -2
  119. package/src/container/tool-oom-priority.ts +32 -0
  120. package/src/cron/consumer.ts +10 -4
  121. package/src/cron/reloadable.ts +23 -2
  122. package/src/doctor/checks.ts +14 -2
  123. package/src/hostd/daemon.ts +20 -10
  124. package/src/hostd/spawn.ts +106 -5
  125. package/src/hostd/version.ts +20 -0
  126. package/src/hostd/watchdog.ts +241 -0
  127. package/src/init/dockerfile.ts +57 -592
  128. package/src/init/index.ts +2 -3
  129. package/src/mcp/client.ts +3 -1
  130. package/src/operations/classify-tool-outcome.ts +45 -1
  131. package/src/operations/incidents.ts +10 -5
  132. package/src/plugin/core-tool-names.ts +1 -1
  133. package/src/plugin/define.ts +1 -0
  134. package/src/plugin/index.ts +1 -0
  135. package/src/plugin/types.ts +6 -1
  136. package/src/run/background-handoff-boot.ts +86 -0
  137. package/src/run/index.ts +83 -83
  138. package/src/run/resource-sample.ts +19 -0
  139. package/src/sandbox/build.ts +4 -0
  140. package/src/sandbox/coding-agent.ts +214 -0
  141. package/src/sandbox/policy.ts +1 -0
  142. package/src/sandbox/runtime-private.ts +4 -1
  143. package/src/secrets/coding-agent-auth.ts +97 -0
  144. package/src/secrets/index.ts +0 -16
  145. package/src/server/command-runner.ts +6 -2
  146. package/src/server/index.ts +101 -40
  147. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  148. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  149. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  150. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  151. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  152. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  153. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  154. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  155. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  156. package/src/skills/typeclaw-config/SKILL.md +21 -21
  157. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  158. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  159. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  160. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  161. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  162. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  163. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  164. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  165. package/src/skills/typeclaw-plugins/SKILL.md +15 -15
  166. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  167. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  168. package/typeclaw.schema.json +12 -1
  169. package/src/secrets/claude-credentials-json.ts +0 -129
  170. package/src/secrets/codex-auth-json.ts +0 -102
  171. package/src/secrets/export-claude-credentials-file.ts +0 -270
  172. package/src/secrets/export-codex-auth-file.ts +0 -250
  173. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  174. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  175. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  176. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -20,7 +20,7 @@ import { formatComposeStats } from './compose-stats'
20
20
  import { formatComposeStatus } from './compose-status'
21
21
  import { formatComposeUsage, formatComposeUsageJson } from './compose-usage'
22
22
  import { preflightDocker, printDockerGuidance } from './docker-preflight'
23
- import { c, errorLine, spinner } from './ui'
23
+ import { c, errorLine, log, spinner } from './ui'
24
24
  import { parseSince, parseUntil } from './usage-args'
25
25
 
26
26
  // Compose fans a docker command out across every agent folder. A down daemon
@@ -54,7 +54,7 @@ const startSub = defineCommand({
54
54
  await requireDockerOrExit()
55
55
  const board = makeBoard('Starting agents')
56
56
  const s = spinner()
57
- const { agents, results } = await composeStart({
57
+ const { agents, results, memoryWarning } = await composeStart({
58
58
  rootCwd: process.cwd(),
59
59
  preferredHostPort: Number(args.port),
60
60
  forceBuild: args.build,
@@ -73,6 +73,7 @@ const startSub = defineCommand({
73
73
  }
74
74
  const failed = results.reduce((n, r) => (r.ok ? n : n + 1), 0)
75
75
  board.finish(s, results, 'started', failed)
76
+ if (memoryWarning !== null) log.warn(memoryWarning.join('\n'))
76
77
  if (failed > 0) process.exit(1)
77
78
  },
78
79
  })
@@ -121,7 +122,7 @@ const restartSub = defineCommand({
121
122
  await requireDockerOrExit()
122
123
  const board = makeBoard('Restarting agents')
123
124
  const s = spinner()
124
- const { agents, results } = await composeRestart({
125
+ const { agents, results, memoryWarning } = await composeRestart({
125
126
  rootCwd: process.cwd(),
126
127
  preferredHostPort: Number(args.port),
127
128
  forceBuild: args.build,
@@ -142,6 +143,7 @@ const restartSub = defineCommand({
142
143
  }
143
144
  const failed = results.reduce((n, r) => (r.ok ? n : n + 1), 0)
144
145
  board.finish(s, results, 'restarted', failed)
146
+ if (memoryWarning !== null) log.warn(memoryWarning.join('\n'))
145
147
  if (failed > 0) process.exit(1)
146
148
  },
147
149
  })
@@ -381,7 +383,8 @@ function formatRestartDone<T extends { start: { hostPort: number } }>(result: Ag
381
383
  // line so compose start/restart don't silently drop what `typeclaw start` prints.
382
384
  function appendWarnings(head: string, warnings: string[] | undefined): string {
383
385
  if (warnings === undefined || warnings.length === 0) return head
384
- return [head, ...warnings.map((w) => ` ${c.yellow('⚠')} ${w}`)].join('\n')
386
+ // Continuation lines of a multi-line warning stay under its first line.
387
+ return [head, ...warnings.map((w) => ` ${c.yellow('⚠')} ${w.replaceAll('\n', '\n ')}`)].join('\n')
385
388
  }
386
389
 
387
390
  function emitComposeDoctor(report: ComposeDoctorReport, opts: { verbose: boolean; json: boolean }): void {
package/src/cli/hostd.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  type RestartOptions,
9
9
  type RestartResult,
10
10
  } from '@/container'
11
+ import { isDaemonReachable } from '@/hostd/client'
11
12
  import {
12
13
  applyCredentialRotation,
13
14
  type CredentialRotationApplyResult,
@@ -19,7 +20,8 @@ import { createKakaoRenewalManager } from '@/hostd/kakao-renewal-manager'
19
20
  import { createPortbrokerManager } from '@/hostd/portbroker-manager'
20
21
  import type { SupervisorLogEvent, SupervisorRestart } from '@/hostd/supervisor'
21
22
  import { createTeamsRenewalManager } from '@/hostd/teams-renewal-manager'
22
- import { computeSourceVersion, resolveSrcRoot, UNVERSIONED_SENTINEL } from '@/hostd/version'
23
+ import { computeSourceVersion, hostBunVersionWarning, resolveSrcRoot, UNVERSIONED_SENTINEL } from '@/hostd/version'
24
+ import { runWatchdog, spawnProcessWorker, watchForOrphaning } from '@/hostd/watchdog'
23
25
  import { createWebexRenewalManager } from '@/hostd/webex-renewal-manager'
24
26
  import { validateRestartDeps, type RestartDepsPreflightResult } from '@/init/restart-deps-preflight'
25
27
  import { requestReloadWithFallback } from '@/reload'
@@ -30,8 +32,29 @@ export const hostdCommand = defineCommand({
30
32
  description: 'internal: host-side typeclaw daemon (do not invoke directly)',
31
33
  hidden: true,
32
34
  },
33
- async run() {
35
+ args: {
36
+ worker: { type: 'boolean', description: 'internal: run the daemon itself under the watchdog' },
37
+ 'watchdog-pid': { type: 'string', description: 'internal: pid of the supervising watchdog parent' },
38
+ },
39
+ async run({ args }) {
34
40
  const cliEntry = process.argv[1] ?? ''
41
+ if (!args.worker) {
42
+ await runHostdWatchdog(cliEntry)
43
+ return
44
+ }
45
+ let shutdown: (() => void) | null = null
46
+ const watchdogPid = Number(args['watchdog-pid'])
47
+ if (Number.isSafeInteger(watchdogPid) && watchdogPid > 0) {
48
+ watchForOrphaning({
49
+ watchdogPid,
50
+ onOrphaned: () => {
51
+ writeLogLine(`[hostd] watchdog parent ${watchdogPid} is gone; exiting`)
52
+ if (shutdown) shutdown()
53
+ else process.exit(1)
54
+ },
55
+ })
56
+ }
57
+
35
58
  const srcRoot = resolveSrcRoot(cliEntry)
36
59
  const version = srcRoot === null ? UNVERSIONED_SENTINEL : await computeSourceVersion({ srcRoot })
37
60
 
@@ -97,7 +120,7 @@ export const hostdCommand = defineCommand({
97
120
  restart: hostdRestart,
98
121
  })
99
122
 
100
- const shutdown = (): void => {
123
+ shutdown = (): void => {
101
124
  void daemon
102
125
  .stop()
103
126
  .then(() => portbroker.drain())
@@ -113,6 +136,27 @@ export const hostdCommand = defineCommand({
113
136
  },
114
137
  })
115
138
 
139
+ const WATCHDOG_PROBE_TIMEOUT_MS = 2_000
140
+
141
+ async function runHostdWatchdog(cliEntry: string): Promise<void> {
142
+ const log = (message: string): void => writeLogLine(`[hostd-watchdog] ${message}`)
143
+ const bunWarning = hostBunVersionWarning(process.versions.bun)
144
+ if (bunWarning) log(`WARNING: ${bunWarning}`)
145
+
146
+ const watchdog = runWatchdog({
147
+ spawnWorker: () =>
148
+ spawnProcessWorker([process.execPath, cliEntry, '_hostd', '--worker', '--watchdog-pid', String(process.pid)]),
149
+ probe: () => isDaemonReachable(WATCHDOG_PROBE_TIMEOUT_MS),
150
+ onLog: log,
151
+ })
152
+ const shutdown = (): void => {
153
+ void watchdog.stop().then(() => process.exit(0))
154
+ }
155
+ process.on('SIGTERM', shutdown)
156
+ process.on('SIGINT', shutdown)
157
+ process.exit(await watchdog.done)
158
+ }
159
+
116
160
  export type HostdRestartDeps = {
117
161
  validateConfig: (cwd: string) => ValidateConfigResult
118
162
  loadConfigSync: (cwd: string) => Config
@@ -239,6 +283,8 @@ function formatLog(event: DaemonLogEvent | SupervisorLogEvent): string {
239
283
  return `[hostd] deregistered ${event.containerName} (${event.reason})`
240
284
  case 'registration-skipped':
241
285
  return `[hostd] skipped persisted registration ${event.containerName}: ${event.reason}`
286
+ case 'container-exited':
287
+ return `[hostd] ${event.containerName}: ${event.reason}`
242
288
  case 'restart-scheduled':
243
289
  return `[hostd] restart scheduled for ${event.containerName}${event.build ? ' (with rebuild)' : ''}`
244
290
  case 'restart-completed':
@@ -122,6 +122,17 @@ export async function runInspectViewer(opts: RunInspectViewerOptions): Promise<n
122
122
  sinceMs = Date.now() - d.ms
123
123
  }
124
124
 
125
+ const interactive = Boolean(process.stdin.isTTY)
126
+ // Reject picker-only invocations before probing Docker: no container state
127
+ // can make a non-interactive terminal capable of driving the picker.
128
+ if (!interactive && opts.sessionArg === undefined) {
129
+ process.stderr.write(`${errorLine('typeclaw inspect needs an interactive terminal to pick a session.')}\n`)
130
+ process.stderr.write(
131
+ 'Pass an explicit session id (`typeclaw inspect <id>`) or use `--json <id>` for a scriptable stream.\n',
132
+ )
133
+ return 2
134
+ }
135
+
125
136
  const containerRunning = (await requireContainerRunning({ cwd })).ok
126
137
  if (!containerRunning) {
127
138
  process.stderr.write(`${c.yellow('⚠')} container not running; showing read-only history and logs only\n`)
@@ -149,20 +160,6 @@ export async function runInspectViewer(opts: RunInspectViewerOptions): Promise<n
149
160
  preselectKey = 'logs'
150
161
  }
151
162
 
152
- const interactive = Boolean(process.stdin.isTTY)
153
-
154
- // Without a TTY, clack's picker keypress loop busy-spins kevent64 at 100% CPU
155
- // forever instead of resolving (e.g. `typeclaw inspect | head`, a daemon
156
- // spawn). A resolved session arg auto-opens without the picker, so only the
157
- // picker-mandatory case is refused — mirroring --json's explicit-id rule.
158
- if (!interactive && preselectKey === undefined) {
159
- process.stderr.write(`${errorLine('typeclaw inspect needs an interactive terminal to pick a session.')}\n`)
160
- process.stderr.write(
161
- 'Pass an explicit session id (`typeclaw inspect <id>`) or use `--json <id>` for a scriptable stream.\n',
162
- )
163
- return 2
164
- }
165
-
166
163
  const liveHint = interactive ? escHintLine(color) : undefined
167
164
  const inspectUrl = containerRunning ? await resolveInspectUrl(cwd) : undefined
168
165
  const liveSource = inspectUrl !== undefined ? buildLiveSource(inspectUrl) : undefined
@@ -0,0 +1,38 @@
1
+ import type { IncomingMessage } from 'node:http'
2
+ import { promisify } from 'node:util'
3
+ import { constants, zstdDecompress } from 'node:zlib'
4
+
5
+ const MAX_BODY = 32 * 1024 * 1024
6
+ const decompress = promisify(zstdDecompress)
7
+
8
+ export async function readCodingBody(
9
+ request: IncomingMessage,
10
+ signal: AbortSignal,
11
+ ): Promise<{ body: Buffer } | { status: number; code: string }> {
12
+ const chunks: Buffer[] = []
13
+ let size = 0
14
+ for await (const chunk of request) {
15
+ signal.throwIfAborted()
16
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
17
+ size += bytes.length
18
+ if (size > MAX_BODY) return { status: 413, code: 'request_too_large' }
19
+ chunks.push(bytes)
20
+ }
21
+ const compressed = Buffer.concat(chunks)
22
+ if (!request.headers['content-encoding']) return { body: compressed }
23
+ try {
24
+ // Both the output allocation and decoder window are bounded. Checking only
25
+ // compressed bytes would allow a tiny expansion bomb to exhaust the runtime.
26
+ const body = await decompress(compressed, {
27
+ maxOutputLength: MAX_BODY,
28
+ params: { [constants.ZSTD_d_windowLogMax]: 25 },
29
+ })
30
+ signal.throwIfAborted()
31
+ return { body }
32
+ } catch (error) {
33
+ if (signal.aborted) throw error
34
+ return error instanceof Error && 'code' in error && error.code === 'ERR_BUFFER_TOO_LARGE'
35
+ ? { status: 413, code: 'request_too_large' }
36
+ : { status: 400, code: 'invalid_compression' }
37
+ }
38
+ }
@@ -0,0 +1,290 @@
1
+ import { randomBytes, timingSafeEqual } from 'node:crypto'
2
+ import { once } from 'node:events'
3
+ import { createServer, request as httpRequest, type IncomingMessage, type ServerResponse } from 'node:http'
4
+ import { request as httpsRequest } from 'node:https'
5
+
6
+ import type { CodingAgentAuth, CodingAgentAuthResolver, CodingAgentProvider } from '@/secrets/coding-agent-auth'
7
+
8
+ import { readCodingBody } from './broker-body'
9
+
10
+ const MAX_STREAMS = 4
11
+ const ANTHROPIC_ROUTES = new Set(['/v1/messages', '/v1/messages/count_tokens'])
12
+ const ANTHROPIC_HEADERS = ['anthropic-version', 'anthropic-beta', 'user-agent', 'x-app'] as const
13
+ const CODEX_HEADERS = ['user-agent', 'originator', 'version', 'session_id', 'x-codex-turn-metadata'] as const
14
+ const OMO_CODEX_HEADERS = [
15
+ ...CODEX_HEADERS,
16
+ 'openai-beta',
17
+ 'session-id',
18
+ 'thread-id',
19
+ 'x-client-request-id',
20
+ 'x-codex-routing-hint',
21
+ ] as const
22
+ const REJECTED_HEADERS = [
23
+ 'proxy-authorization',
24
+ 'forwarded',
25
+ 'x-forwarded-host',
26
+ 'x-forwarded-for',
27
+ 'anthropic-organization-id',
28
+ 'anthropic-workspace-id',
29
+ 'x-organization-id',
30
+ 'x-workspace-id',
31
+ 'chatgpt-account-id',
32
+ 'openai-organization',
33
+ 'openai-project',
34
+ ] as const
35
+
36
+ export class SecretScrubber {
37
+ private pending = ''
38
+ constructor(private readonly secrets: readonly string[]) {}
39
+
40
+ push(text: string, final = false): string {
41
+ this.pending += text
42
+ const secrets = this.secrets.filter(Boolean)
43
+ const keep = Math.max(1, ...secrets.map((s) => s.length)) - 1
44
+ let index = 0
45
+ let output = ''
46
+ while (index < this.pending.length && (final || index < this.pending.length - keep)) {
47
+ const secret = secrets.find((value) => this.pending.startsWith(value, index))
48
+ if (secret) {
49
+ output += '[redacted]'
50
+ index += secret.length
51
+ } else {
52
+ output += this.pending[index]
53
+ index++
54
+ }
55
+ }
56
+ this.pending = this.pending.slice(index)
57
+ return output
58
+ }
59
+ }
60
+
61
+ export type CodingBroker = {
62
+ readonly baseUrl: string
63
+ readonly capability: string
64
+ close(): Promise<void>
65
+ }
66
+
67
+ export async function startCodingBroker(
68
+ options: {
69
+ provider?: CodingAgentProvider
70
+ engine?: 'claude' | 'codex' | 'omo'
71
+ auth: CodingAgentAuthResolver
72
+ allowedModels: readonly string[]
73
+ deadline: number
74
+ signal?: AbortSignal
75
+ },
76
+ // Dependency injection for wire-level tests only. No config/tool operand can select a destination.
77
+ testDependencies?: { upstream: URL },
78
+ ): Promise<CodingBroker> {
79
+ const provider = options.provider ?? 'anthropic'
80
+ const omo = options.engine === 'omo'
81
+ const oauthShape =
82
+ omo &&
83
+ provider === 'anthropic' &&
84
+ (await options.auth.resolve(options.signal, undefined, provider)).type === 'oauth'
85
+ // Senpi 2026.10.10 selects OAuth body/tool shaping by this prefix. It is
86
+ // still a fresh local capability, never an upstream OAuth credential.
87
+ const capability = `${oauthShape ? 'sk-ant-oat01-' : ''}${randomBytes(32).toString('hex')}`
88
+ const controller = new AbortController()
89
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal
90
+ const upstream =
91
+ testDependencies?.upstream ??
92
+ new URL(provider === 'anthropic' ? 'https://api.anthropic.com' : 'https://chatgpt.com')
93
+ let active = 0
94
+ let closed = false
95
+ const server = createServer({ maxHeaderSize: 16 * 1024 }, (req, res) => {
96
+ void handle(req, res).catch(() => {
97
+ if (!res.headersSent) reject(res, 502, 'upstream_unavailable')
98
+ else res.destroy()
99
+ })
100
+ })
101
+ server.maxHeadersCount = 64
102
+ server.on('connect', (_req, socket) => socket.end('HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\n\r\n'))
103
+ server.on('upgrade', (_req, socket) => socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n'))
104
+ const listening = once(server, 'listening')
105
+ server.listen(0, '127.0.0.1')
106
+ await listening
107
+ const address = server.address()
108
+ if (!address || typeof address === 'string') throw new Error('Coding broker could not bind loopback.')
109
+ const baseUrl = `http://127.0.0.1:${address.port}`
110
+ let closing: Promise<void> | undefined
111
+ const close = (): Promise<void> => {
112
+ if (closing) return closing
113
+ closed = true
114
+ controller.abort()
115
+ clearTimeout(timer)
116
+ options.signal?.removeEventListener('abort', onAbort)
117
+ closing = new Promise<void>((resolve) => {
118
+ server.close(() => resolve())
119
+ server.closeAllConnections()
120
+ })
121
+ return closing
122
+ }
123
+ const onAbort = () => {
124
+ void close()
125
+ }
126
+ const timer = setTimeout(onAbort, Math.max(1, options.deadline - Date.now()))
127
+ options.signal?.addEventListener('abort', onAbort, { once: true })
128
+ if (signal.aborted) await close()
129
+ return { baseUrl, capability, close }
130
+
131
+ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
132
+ if (closed || signal.aborted || Date.now() >= options.deadline) return reject(res, 401, 'capability_expired')
133
+ const provided = req.headers.authorization
134
+ const expected = `Bearer ${capability}`
135
+ if (
136
+ typeof provided !== 'string' ||
137
+ provided.length !== expected.length ||
138
+ !timingSafeEqual(Buffer.from(provided), Buffer.from(expected))
139
+ )
140
+ return reject(res, 401, 'invalid_capability')
141
+ // Inspect the raw origin-form target; WHATWG URL would normalize traversal away.
142
+ const target = req.url ?? ''
143
+ const [route, query, extra] = target.split('?')
144
+ if (
145
+ req.method !== 'POST' ||
146
+ !route ||
147
+ !(provider === 'anthropic'
148
+ ? ANTHROPIC_ROUTES.has(route)
149
+ : route === (omo ? '/v1/codex/responses' : '/v1/responses')) ||
150
+ extra !== undefined ||
151
+ (query !== undefined && (provider !== 'anthropic' || query !== 'beta=true')) ||
152
+ req.rawHeaders.length > 128
153
+ ) {
154
+ return reject(res, 400, 'unsupported_request')
155
+ }
156
+ if (
157
+ req.headers.upgrade ||
158
+ (req.headers['content-encoding'] !== undefined &&
159
+ !(omo && provider === 'openai-codex' && req.headers['content-encoding'] === 'zstd')) ||
160
+ REJECTED_HEADERS.some((name) => req.headers[name] !== undefined) ||
161
+ req.headers.host !== new URL(baseUrl).host ||
162
+ !req.headers['content-type']?.startsWith('application/json')
163
+ )
164
+ return reject(res, 400, 'unsupported_headers')
165
+ if (active >= MAX_STREAMS) return reject(res, 429, 'concurrency_limit')
166
+ active++
167
+ const disconnected = new AbortController()
168
+ const requestSignal = AbortSignal.any([signal, disconnected.signal])
169
+ res.on('close', () => disconnected.abort())
170
+ try {
171
+ const read = await readCodingBody(req, requestSignal)
172
+ if ('code' in read) return reject(res, read.status, read.code)
173
+ const body = read.body
174
+ let value: unknown
175
+ try {
176
+ value = JSON.parse(body.toString('utf8'))
177
+ } catch {
178
+ return reject(res, 400, 'invalid_json')
179
+ }
180
+ if (!isObject(value) || typeof value.model !== 'string' || !options.allowedModels.includes(value.model)) {
181
+ return reject(res, 400, 'unsupported_model')
182
+ }
183
+ if (['url', 'base_url', 'baseURL', 'endpoint', 'upstream', 'destination'].some((key) => key in value)) {
184
+ return reject(res, 400, 'unsupported_destination')
185
+ }
186
+ let auth = await options.auth.resolve(requestSignal, undefined, provider)
187
+ const secrets = new Set(auth.secrets)
188
+ let response = await forward(auth)
189
+ if (response.statusCode === 401) {
190
+ response.destroy()
191
+ auth = await options.auth.resolve(requestSignal, auth, provider)
192
+ auth.secrets.forEach((secret) => secrets.add(secret))
193
+ response = await forward(auth)
194
+ }
195
+ const status = response.statusCode ?? 502
196
+ const allSecrets = [...secrets, capability]
197
+ const scrub = (text: string) => new SecretScrubber(allSecrets).push(text, true)
198
+ for (const [key, value] of Object.entries(response.headers)) {
199
+ if (typeof value !== 'string') continue
200
+ // Provider-prefixed rate-limit names are untrusted text too.
201
+ if (allSecrets.some((secret) => secret.length > 0 && key.includes(secret.toLowerCase()))) continue
202
+ if (key === 'request-id' || key === 'x-request-id') res.setHeader(key, scrub(value).slice(0, 200))
203
+ if (
204
+ (key === 'retry-after' || key.startsWith('anthropic-ratelimit-') || key.startsWith('x-ratelimit-')) &&
205
+ /^[0-9T:Z.+-]{1,64}$/.test(value)
206
+ ) {
207
+ res.setHeader(key, scrub(value))
208
+ }
209
+ }
210
+ if (status >= 300) {
211
+ response.destroy()
212
+ return reject(
213
+ res,
214
+ status === 429 ? 429 : status === 401 || status === 403 ? 401 : 502,
215
+ status === 429
216
+ ? 'rate_limit'
217
+ : status === 401 || status === 403
218
+ ? 'authentication_required'
219
+ : 'upstream_unavailable',
220
+ )
221
+ }
222
+ // The ChatGPT Codex backend streams SSE with no Content-Type header at all.
223
+ const contentType = response.headers['content-type'] ?? (provider === 'openai-codex' ? 'text/event-stream' : '')
224
+ if (!/^(application\/json|text\/event-stream)(;|$)/i.test(contentType)) {
225
+ response.destroy()
226
+ return reject(res, 502, 'unsupported_response')
227
+ }
228
+ res.statusCode = status
229
+ res.setHeader('content-type', contentType.split(';')[0] ?? 'application/json')
230
+ const scrubber = new SecretScrubber(allSecrets)
231
+ const decoder = new TextDecoder()
232
+ for await (const chunk of response) {
233
+ requestSignal.throwIfAborted()
234
+ const text = scrubber.push(decoder.decode(chunk, { stream: true }))
235
+ if (text && !res.write(text)) await once(res, 'drain', { signal: requestSignal })
236
+ }
237
+ res.end(scrubber.push(decoder.decode(), true))
238
+
239
+ function forward(credential: CodingAgentAuth): Promise<IncomingMessage> {
240
+ if ((credential.provider ?? 'anthropic') !== provider)
241
+ throw new Error('Inference credential provider mismatch.')
242
+ const headers: Record<string, string> = {
243
+ 'content-type': 'application/json',
244
+ ...(provider === 'anthropic' ? { 'anthropic-version': '2023-06-01' } : { accept: 'text/event-stream' }),
245
+ }
246
+ for (const key of provider === 'anthropic' ? ANTHROPIC_HEADERS : omo ? OMO_CODEX_HEADERS : CODEX_HEADERS) {
247
+ const value = req.headers[key]
248
+ if (typeof value === 'string') headers[key] = value
249
+ }
250
+ if (credential.provider === 'openai-codex') {
251
+ headers.authorization = `Bearer ${credential.token}`
252
+ headers['ChatGPT-Account-Id'] = credential.accountId
253
+ } else if (credential.type === 'oauth') {
254
+ headers.authorization = `Bearer ${credential.token}`
255
+ headers['anthropic-beta'] = [
256
+ ...new Set([
257
+ ...(headers['anthropic-beta'] ?? '').split(',').filter(Boolean),
258
+ 'claude-code-20250219',
259
+ 'oauth-2025-04-20',
260
+ ]),
261
+ ].join(',')
262
+ headers['x-app'] = 'cli'
263
+ } else headers['x-api-key'] = credential.token
264
+ // node:https does not honor ambient HTTP_PROXY/CA/URL overrides. Never follow Location.
265
+ return new Promise((resolve, rejectRequest) => {
266
+ const request = (upstream.protocol === 'https:' ? httpsRequest : httpRequest)(
267
+ new URL(provider === 'anthropic' ? target : '/backend-api/codex/responses', upstream),
268
+ { method: 'POST', headers, signal: requestSignal, rejectUnauthorized: true },
269
+ resolve,
270
+ )
271
+ request.on('error', () => rejectRequest(new Error('Inference transport failed.')))
272
+ // Forward the inspected JSON, never compressed bytes or an encoding
273
+ // header from the untrusted client.
274
+ request.end(JSON.stringify(value))
275
+ })
276
+ }
277
+ } finally {
278
+ active--
279
+ }
280
+ }
281
+ }
282
+
283
+ function reject(res: ServerResponse, status: number, code: string): void {
284
+ res.writeHead(status, { 'content-type': 'application/json', connection: 'close' })
285
+ res.end(JSON.stringify({ type: 'error', error: { type: code, message: code } }))
286
+ }
287
+
288
+ function isObject(value: unknown): value is Record<string, unknown> {
289
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
290
+ }
@@ -0,0 +1,95 @@
1
+ import { z } from 'zod'
2
+
3
+ export const CLAUDE_CODE_VERSION = '2.1.299'
4
+ // Explicit compatibility set, not an open-ended provider allowlist.
5
+ export const CLAUDE_AUXILIARY_MODELS = ['claude-haiku-4-5-20251001', 'claude-sonnet-4-6', 'claude-opus-4-7'] as const
6
+ export type CodingMode = 'code' | 'plan'
7
+
8
+ export function claudeArguments(options: {
9
+ model: string
10
+ mode: CodingMode
11
+ sessionId: string
12
+ resume: boolean
13
+ }): string[] {
14
+ return [
15
+ 'claude',
16
+ '-p',
17
+ '--output-format',
18
+ 'stream-json',
19
+ '--verbose',
20
+ '--model',
21
+ options.model,
22
+ '--permission-mode',
23
+ options.mode === 'plan' ? 'plan' : 'dontAsk',
24
+ '--allowedTools',
25
+ 'Read,Edit,Write,Bash,Agent,Glob,Grep',
26
+ '--settings',
27
+ JSON.stringify({ sandbox: { enabled: false } }),
28
+ options.resume ? '--resume' : '--session-id',
29
+ options.sessionId,
30
+ ]
31
+ }
32
+
33
+ export function claudeEnvironment(configDir: string, baseUrl: string, capability: string): Record<string, string> {
34
+ return {
35
+ CLAUDE_CONFIG_DIR: configDir,
36
+ ANTHROPIC_BASE_URL: baseUrl,
37
+ ANTHROPIC_AUTH_TOKEN: capability,
38
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
39
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: CLAUDE_AUXILIARY_MODELS[0],
40
+ ANTHROPIC_DEFAULT_SONNET_MODEL: CLAUDE_AUXILIARY_MODELS[1],
41
+ ANTHROPIC_DEFAULT_OPUS_MODEL: CLAUDE_AUXILIARY_MODELS[2],
42
+ }
43
+ }
44
+
45
+ const eventSchema = z
46
+ .object({
47
+ type: z.string(),
48
+ session_id: z.string().uuid().optional(),
49
+ subtype: z.string().optional(),
50
+ is_error: z.boolean().optional(),
51
+ result: z.string().optional(),
52
+ permission_denials: z.array(z.unknown()).optional(),
53
+ })
54
+ .passthrough()
55
+
56
+ export class ClaudeStreamParser {
57
+ sessionId: string | undefined
58
+ finalMessage = ''
59
+ terminal = false
60
+ failed = false
61
+ permissionDenied = false
62
+ malformed = false
63
+ private pending = ''
64
+
65
+ push(text: string): void {
66
+ this.pending += text
67
+ if (this.pending.length > 4 * 1024 * 1024) throw new Error('Claude event exceeds the 4 MiB event limit.')
68
+ let newline: number
69
+ while ((newline = this.pending.indexOf('\n')) !== -1) {
70
+ const line = this.pending.slice(0, newline)
71
+ this.pending = this.pending.slice(newline + 1)
72
+ this.line(line)
73
+ }
74
+ }
75
+
76
+ finish(): void {
77
+ if (this.pending.trim()) this.line(this.pending)
78
+ this.pending = ''
79
+ }
80
+
81
+ private line(line: string): void {
82
+ if (!line.trim()) return
83
+ try {
84
+ const event = eventSchema.parse(JSON.parse(line))
85
+ if (event.session_id) this.sessionId = event.session_id
86
+ if (event.type !== 'result') return
87
+ this.terminal = true
88
+ this.failed = event.is_error === true || event.subtype !== 'success'
89
+ this.permissionDenied = (event.permission_denials?.length ?? 0) > 0
90
+ this.finalMessage = event.result ?? ''
91
+ } catch {
92
+ this.malformed = true
93
+ }
94
+ }
95
+ }