typeclaw 0.48.12 → 0.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -3
- package/scripts/dump-system-prompt.ts +52 -110
- package/src/agent/attention-escalation.ts +8 -5
- package/src/agent/auth-reloadable.ts +2 -3
- package/src/agent/auth.ts +59 -79
- package/src/agent/compaction.ts +2 -2
- package/src/agent/index.ts +173 -85
- package/src/agent/live-sessions.ts +2 -2
- package/src/agent/live-subagents.ts +1 -0
- package/src/agent/llm-replay-sanitizer.ts +1 -1
- package/src/agent/model-overrides.ts +1 -1
- package/src/agent/multimodal/look-at.ts +3 -3
- package/src/agent/multimodal/read-redirect.ts +1 -1
- package/src/agent/plugin-tools.ts +76 -39
- package/src/agent/prompt-cache-key.ts +42 -0
- package/src/agent/provider-error.ts +179 -10
- package/src/agent/reload-tool.ts +1 -1
- package/src/agent/restart-handoff/index.ts +7 -14
- package/src/agent/reviewer-activity.ts +68 -0
- package/src/agent/session-origin.ts +33 -0
- package/src/agent/subagents.ts +14 -2
- package/src/agent/system-prompt.ts +68 -202
- package/src/agent/todo/continuation-policy.ts +12 -4
- package/src/agent/tool-error-remediation.ts +1 -1
- package/src/agent/tool-file-safety.ts +113 -14
- package/src/agent/tool-not-found-nudge.ts +1 -1
- package/src/agent/tool-result-budget.ts +2 -2
- package/src/agent/tools/channel-disengage.ts +2 -2
- package/src/agent/tools/channel-edit.ts +2 -2
- package/src/agent/tools/channel-fetch-attachment.ts +2 -2
- package/src/agent/tools/channel-history-render.ts +2 -1
- package/src/agent/tools/channel-history.ts +2 -2
- package/src/agent/tools/channel-react.ts +2 -2
- package/src/agent/tools/channel-read.ts +2 -2
- package/src/agent/tools/channel-reply.ts +25 -7
- package/src/agent/tools/channel-send.ts +51 -9
- package/src/agent/tools/curl-impersonate.ts +11 -2
- package/src/agent/tools/grant-role.ts +2 -2
- package/src/agent/tools/post-github-review.ts +79 -17
- package/src/agent/tools/restart.ts +2 -2
- package/src/agent/tools/skip-response.ts +4 -4
- package/src/agent/tools/spawn-subagent.ts +165 -14
- package/src/agent/tools/stream-snapshot.ts +2 -2
- package/src/agent/tools/subagent-cancel.ts +2 -2
- package/src/agent/tools/subagent-output.ts +10 -2
- package/src/agent/tools/todo/index.ts +2 -2
- package/src/agent/tools/webfetch/tool.ts +2 -2
- package/src/agent/tools/websearch.ts +2 -2
- package/src/bundled-plugins/backup/README.md +10 -9
- package/src/bundled-plugins/backup/runner.ts +140 -58
- package/src/bundled-plugins/backup/subagents.ts +58 -26
- package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
- package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
- package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
- package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
- package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
- package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
- package/src/bundled-plugins/operator/operator.ts +15 -4
- package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
- package/src/bundled-plugins/security/index.ts +50 -2
- package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
- package/src/channels/adapters/discord-bot-reactions.ts +18 -0
- package/src/channels/adapters/discord-bot.ts +122 -67
- package/src/channels/adapters/discord-reactions.ts +18 -0
- package/src/channels/adapters/discord.ts +114 -8
- package/src/channels/adapters/github/inbound.ts +103 -8
- package/src/channels/adapters/github/index.ts +251 -19
- package/src/channels/adapters/github/last-alive.ts +27 -0
- package/src/channels/adapters/github/outbound.ts +54 -18
- package/src/channels/adapters/github/pending-review-store.ts +141 -0
- package/src/channels/adapters/github/permission-guidance.ts +1 -0
- package/src/channels/adapters/github/reactions.ts +100 -0
- package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
- package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
- package/src/channels/adapters/github/recovery.ts +106 -0
- package/src/channels/adapters/github/review-check.ts +510 -0
- package/src/channels/adapters/github/review-submitter.ts +34 -2
- package/src/channels/adapters/instagram.ts +32 -14
- package/src/channels/adapters/kakaotalk.ts +22 -7
- package/src/channels/adapters/line.ts +18 -3
- package/src/channels/adapters/outbound-account.ts +20 -0
- package/src/channels/adapters/own-reactions.ts +66 -0
- package/src/channels/adapters/recovery-correlation.ts +214 -0
- package/src/channels/adapters/slack-bot-classify.ts +18 -11
- package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
- package/src/channels/adapters/slack-bot-reactions.ts +18 -0
- package/src/channels/adapters/slack-bot.ts +125 -57
- package/src/channels/adapters/slack-classify.ts +25 -4
- package/src/channels/adapters/slack-inbound-revision.ts +96 -0
- package/src/channels/adapters/slack-reactions.ts +18 -0
- package/src/channels/adapters/slack-thread-ts.ts +6 -0
- package/src/channels/adapters/slack.ts +48 -3
- package/src/channels/adapters/teams.ts +14 -4
- package/src/channels/adapters/telegram-bot.ts +56 -10
- package/src/channels/adapters/webex-bot.ts +12 -2
- package/src/channels/adapters/webex.ts +12 -2
- package/src/channels/background-handoff.ts +434 -0
- package/src/channels/background-obligations.ts +893 -0
- package/src/channels/continuity-types.ts +271 -0
- package/src/channels/github-review-check.ts +598 -0
- package/src/channels/github-review-turn-ledger.ts +102 -28
- package/src/channels/github-review-verdict-coordinator.ts +96 -13
- package/src/channels/github-token-bridge.ts +11 -5
- package/src/channels/inbound-journal.ts +1738 -0
- package/src/channels/index.ts +6 -1
- package/src/channels/manager.ts +17 -7
- package/src/channels/recovery-dispatcher.ts +264 -0
- package/src/channels/recovery-notice.ts +94 -0
- package/src/channels/recovery-outbox.ts +459 -0
- package/src/channels/router.ts +2582 -633
- package/src/channels/schema.ts +8 -1
- package/src/channels/subagent-completion-bridge.ts +17 -14
- package/src/channels/types.ts +121 -16
- package/src/channels/waiting-reactions.ts +664 -0
- package/src/cli/compose.ts +7 -4
- package/src/cli/hostd.ts +49 -3
- package/src/cli/inspect.ts +11 -14
- package/src/cli/model.ts +7 -5
- package/src/cli/oauth-callbacks.ts +38 -23
- package/src/coding-agent/broker-body.ts +38 -0
- package/src/coding-agent/broker.ts +290 -0
- package/src/coding-agent/claude.ts +95 -0
- package/src/coding-agent/codex.ts +104 -0
- package/src/coding-agent/index.ts +506 -0
- package/src/coding-agent/omo-state.ts +69 -0
- package/src/coding-agent/omo-stream.ts +98 -0
- package/src/coding-agent/omo.ts +192 -0
- package/src/coding-agent/runner.ts +263 -0
- package/src/coding-agent/tool.ts +62 -0
- package/src/coding-agent/worktree.ts +355 -0
- package/src/compose/restart.ts +10 -3
- package/src/compose/start.ts +20 -3
- package/src/config/config.ts +70 -26
- package/src/config/providers.ts +278 -50
- package/src/container/exit-reason.ts +44 -0
- package/src/container/index.ts +5 -0
- package/src/container/log-archive.ts +51 -13
- package/src/container/memory-limit.ts +1 -1
- package/src/container/memory-oversubscription.ts +36 -6
- package/src/container/oom-events.ts +86 -0
- package/src/container/restart.ts +2 -0
- package/src/container/shared.ts +8 -1
- package/src/container/start.ts +25 -13
- package/src/container/stop.ts +6 -2
- package/src/container/tool-oom-priority.ts +32 -0
- package/src/cron/consumer.ts +10 -4
- package/src/cron/reloadable.ts +23 -2
- package/src/doctor/checks.ts +14 -2
- package/src/hostd/daemon.ts +20 -10
- package/src/hostd/spawn.ts +106 -5
- package/src/hostd/version.ts +20 -0
- package/src/hostd/watchdog.ts +241 -0
- package/src/init/dockerfile.ts +57 -592
- package/src/init/index.ts +6 -7
- package/src/init/oauth-login.ts +57 -17
- package/src/inspect/transcript-view.ts +6 -3
- package/src/mcp/client.ts +3 -1
- package/src/operations/classify-tool-outcome.ts +45 -1
- package/src/operations/incidents.ts +10 -5
- package/src/plugin/core-tool-names.ts +1 -1
- package/src/plugin/define.ts +1 -0
- package/src/plugin/index.ts +1 -0
- package/src/plugin/types.ts +6 -1
- package/src/run/background-handoff-boot.ts +86 -0
- package/src/run/channel-session-factory.ts +5 -4
- package/src/run/index.ts +93 -93
- package/src/run/resource-sample.ts +19 -0
- package/src/sandbox/build.ts +4 -0
- package/src/sandbox/coding-agent.ts +214 -0
- package/src/sandbox/policy.ts +1 -0
- package/src/sandbox/runtime-private.ts +4 -1
- package/src/secrets/coding-agent-auth.ts +97 -0
- package/src/secrets/index.ts +0 -16
- package/src/secrets/refresh-provider-oauth.ts +30 -76
- package/src/secrets/schema.ts +3 -4
- package/src/secrets/storage.ts +133 -234
- package/src/server/command-runner.ts +6 -2
- package/src/server/index.ts +102 -41
- package/src/sessions/index.ts +1 -1
- package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
- package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
- package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
- package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
- package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
- package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
- package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
- package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
- package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
- package/src/skills/typeclaw-config/SKILL.md +24 -24
- package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
- package/src/skills/typeclaw-cron/SKILL.md +1 -1
- package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
- package/src/skills/typeclaw-memory/SKILL.md +3 -3
- package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
- package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
- package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
- package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
- package/src/skills/typeclaw-plugins/SKILL.md +20 -20
- package/src/skills/typeclaw-skills/SKILL.md +19 -2
- package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
- package/src/tui/index.ts +5 -3
- package/src/tui/theme.ts +1 -1
- package/typeclaw.schema.json +44 -2
- package/src/agent/adaptive-thinking-compat.ts +0 -79
- package/src/secrets/claude-credentials-json.ts +0 -129
- package/src/secrets/codex-auth-json.ts +0 -102
- package/src/secrets/export-claude-credentials-file.ts +0 -270
- package/src/secrets/export-codex-auth-file.ts +0 -250
- package/src/secrets/oauth-xai.ts +0 -348
- package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
- package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
- package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
- package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
package/src/cli/compose.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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':
|
package/src/cli/inspect.ts
CHANGED
|
@@ -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
|
package/src/cli/model.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { join } from 'node:path'
|
|
|
4
4
|
import { autocomplete, cancel, intro, isCancel, log, select } from '@clack/prompts'
|
|
5
5
|
import { defineCommand } from 'citty'
|
|
6
6
|
|
|
7
|
-
import type
|
|
7
|
+
import { type CustomModelMeta, type ThinkingLevel, thinkingLevelSchema } from '@/config'
|
|
8
8
|
import {
|
|
9
9
|
addProfile,
|
|
10
10
|
listModelProfiles,
|
|
@@ -59,7 +59,7 @@ const setSub = defineCommand({
|
|
|
59
59
|
thinking: {
|
|
60
60
|
type: 'string',
|
|
61
61
|
description:
|
|
62
|
-
"reasoning effort for THIS profile (off|minimal|low|medium|high|xhigh|default); the `default` profile's level is the de-facto global default",
|
|
62
|
+
"reasoning effort for THIS profile (off|minimal|low|medium|high|xhigh|max|default); the `default` profile's level is the de-facto global default",
|
|
63
63
|
required: false,
|
|
64
64
|
},
|
|
65
65
|
},
|
|
@@ -117,7 +117,7 @@ const thinkingSub = defineCommand({
|
|
|
117
117
|
level: {
|
|
118
118
|
type: 'positional',
|
|
119
119
|
description:
|
|
120
|
-
'reasoning effort (off|minimal|low|medium|high|xhigh); or "default" to clear and defer to the SDK default',
|
|
120
|
+
'reasoning effort (off|minimal|low|medium|high|xhigh|max); or "default" to clear and defer to the SDK default',
|
|
121
121
|
required: false,
|
|
122
122
|
},
|
|
123
123
|
},
|
|
@@ -318,7 +318,9 @@ async function pickProfileName(): Promise<string> {
|
|
|
318
318
|
return choice
|
|
319
319
|
}
|
|
320
320
|
|
|
321
|
-
|
|
321
|
+
// The config schema is the single source of truth, so `--thinking` and the
|
|
322
|
+
// picker accept exactly the levels typeclaw.json accepts (including `max`).
|
|
323
|
+
const THINKING_LEVELS: readonly ThinkingLevel[] = thinkingLevelSchema.options
|
|
322
324
|
const KEEP_THINKING_SENTINEL = '__keep__'
|
|
323
325
|
|
|
324
326
|
export type ParsedThinkingArg = { ok: true; level: ThinkingLevel | undefined } | { ok: false; reason: string }
|
|
@@ -326,7 +328,7 @@ export type ParsedThinkingArg = { ok: true; level: ThinkingLevel | undefined } |
|
|
|
326
328
|
export function parseThinkingArg(raw: string): ParsedThinkingArg {
|
|
327
329
|
const value = raw.trim().toLowerCase()
|
|
328
330
|
if (value === 'default' || value === 'unset' || value === 'none') return { ok: true, level: undefined }
|
|
329
|
-
if ((THINKING_LEVELS as string[]).includes(value)) return { ok: true, level: value as ThinkingLevel }
|
|
331
|
+
if ((THINKING_LEVELS as readonly string[]).includes(value)) return { ok: true, level: value as ThinkingLevel }
|
|
330
332
|
return {
|
|
331
333
|
ok: false,
|
|
332
334
|
reason: `Invalid --thinking "${raw}". Use one of: ${THINKING_LEVELS.join(', ')}, or "default" to clear.`,
|
|
@@ -1,29 +1,23 @@
|
|
|
1
|
-
import { isCancel, log, note, text } from '@clack/prompts'
|
|
1
|
+
import { isCancel, log, note, password, select, text } from '@clack/prompts'
|
|
2
2
|
|
|
3
3
|
import type { OAuthCallbacks } from '@/init/oauth-login'
|
|
4
4
|
|
|
5
5
|
// Shared between `typeclaw init` (src/cli/init.ts) and `typeclaw provider
|
|
6
6
|
// add/set` (src/cli/provider.ts). Both call into the same OAuth runner, so
|
|
7
7
|
// they need to render the same UX: a note() box with the URL + cross-device
|
|
8
|
-
// guidance, a
|
|
9
|
-
//
|
|
10
|
-
// different host than the CLI. See
|
|
11
|
-
// on each callback and why
|
|
8
|
+
// guidance, a select() prompt for provider-defined choices, a text() prompt
|
|
9
|
+
// for the post-callback manual fallback, and a concurrent onManualCodeInput
|
|
10
|
+
// prompt for users whose browser is on a different host than the CLI. See
|
|
11
|
+
// src/init/oauth-login.ts for the contract on each callback and why
|
|
12
|
+
// onManualCodeInput is required for cross-device.
|
|
12
13
|
//
|
|
13
|
-
// Returns `{ callbacks, dispose }` rather than bare callbacks because
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
// the user sees "Logged in to {Provider}" immediately followed by the stale
|
|
21
|
-
// "paste the redirect URL here" prompt that's now meaningless. Each call
|
|
22
|
-
// site (init/provider) MUST call `dispose()` in a finally after the OAuth
|
|
23
|
-
// runner returns so the orphaned prompt aborts cleanly; clack honors the
|
|
24
|
-
// signal by resolving the prompt with cancel state, the cancel branch
|
|
25
|
-
// throws inside our callback, and pi-ai's outer `.catch()` swallows it
|
|
26
|
-
// (since it stops awaiting the manual promise on the winning-browser path).
|
|
14
|
+
// Returns `{ callbacks, dispose }` rather than bare callbacks because pi-ai
|
|
15
|
+
// races `onManualCodeInput()` against the local callback server. Pi 0.87 aborts
|
|
16
|
+
// the losing manual prompt through its prompt signal (pi-ai
|
|
17
|
+
// dist/auth/oauth/anthropic.js:216-221,266); dispose remains a fallback for
|
|
18
|
+
// callers that end OAuth before pi reaches that race. Each call site
|
|
19
|
+
// (init/provider) MUST call `dispose()` in a finally after the OAuth runner
|
|
20
|
+
// returns so any still-live clack prompt is cancelled cleanly.
|
|
27
21
|
export type OAuthCallbackHandle = {
|
|
28
22
|
callbacks: OAuthCallbacks
|
|
29
23
|
dispose: () => void
|
|
@@ -32,6 +26,8 @@ export type OAuthCallbackHandle = {
|
|
|
32
26
|
export function buildOAuthCallbacks(providerName: string): OAuthCallbackHandle {
|
|
33
27
|
const controller = new AbortController()
|
|
34
28
|
const { signal } = controller
|
|
29
|
+
const promptSignal = (upstream?: AbortSignal): AbortSignal =>
|
|
30
|
+
upstream === undefined ? signal : AbortSignal.any([signal, upstream])
|
|
35
31
|
return {
|
|
36
32
|
dispose: () => controller.abort(),
|
|
37
33
|
callbacks: {
|
|
@@ -56,21 +52,40 @@ export function buildOAuthCallbacks(providerName: string): OAuthCallbackHandle {
|
|
|
56
52
|
onProgress: (message) => {
|
|
57
53
|
log.info(message)
|
|
58
54
|
},
|
|
59
|
-
onPrompt: async (message, placeholder) => {
|
|
55
|
+
onPrompt: async (message, placeholder, upstreamSignal) => {
|
|
60
56
|
const value = await text({
|
|
61
57
|
message,
|
|
62
|
-
signal,
|
|
58
|
+
signal: promptSignal(upstreamSignal),
|
|
63
59
|
...(placeholder !== undefined ? { placeholder } : {}),
|
|
64
60
|
})
|
|
65
61
|
if (isCancel(value)) return null
|
|
66
62
|
return value
|
|
67
63
|
},
|
|
68
|
-
|
|
64
|
+
// clack's password() has no placeholder option (PasswordOptions).
|
|
65
|
+
onSecret: async (message, _placeholder, upstreamSignal) => {
|
|
66
|
+
const value = await password({ message, signal: promptSignal(upstreamSignal) })
|
|
67
|
+
if (isCancel(value)) return null
|
|
68
|
+
return value
|
|
69
|
+
},
|
|
70
|
+
onSelect: async (message, options, upstreamSignal) => {
|
|
71
|
+
const value = await select({
|
|
72
|
+
message,
|
|
73
|
+
options: options.map((option) => ({
|
|
74
|
+
value: option.id,
|
|
75
|
+
label: option.label,
|
|
76
|
+
hint: option.description,
|
|
77
|
+
})),
|
|
78
|
+
signal: promptSignal(upstreamSignal),
|
|
79
|
+
})
|
|
80
|
+
if (isCancel(value)) return null
|
|
81
|
+
return value
|
|
82
|
+
},
|
|
83
|
+
onManualCodeInput: async (upstreamSignal) => {
|
|
69
84
|
const value = await text({
|
|
70
85
|
message:
|
|
71
86
|
'After signing in, paste the code shown on the page (some providers offer a copy button), or the full redirect address from the top of the browser:',
|
|
72
87
|
placeholder: 'code, or http://localhost:1455/auth/callback?code=...&state=...',
|
|
73
|
-
signal,
|
|
88
|
+
signal: promptSignal(upstreamSignal),
|
|
74
89
|
})
|
|
75
90
|
if (isCancel(value)) throw new Error('Login cancelled by user')
|
|
76
91
|
return value
|
|
@@ -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
|
+
}
|