@skaile/workspaces 4.18.0 → 4.19.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/CHANGELOG.md +6 -0
- package/dist/{asset-feeds-KWWDOLAS.js → asset-feeds-VXK6SHWK.js} +4 -4
- package/dist/{asset-feeds-KWWDOLAS.js.map → asset-feeds-VXK6SHWK.js.map} +1 -1
- package/dist/asset-manager/index.js +1 -1
- package/dist/bridge/codex-app-server.js +2 -1
- package/dist/bridge/drivers/claude-sdk.js +20 -5
- package/dist/bridge/drivers/claude-sdk.js.map +1 -1
- package/dist/bridge/drivers/codex.js +4 -3
- package/dist/bridge/drivers/codex.js.map +1 -1
- package/dist/bridge/drivers/continue.js +4 -3
- package/dist/bridge/drivers/continue.js.map +1 -1
- package/dist/bridge/drivers/echo.js +1 -1
- package/dist/bridge/drivers/gemini.js +6 -5
- package/dist/bridge/drivers/goose.js +4 -3
- package/dist/bridge/drivers/goose.js.map +1 -1
- package/dist/bridge/drivers/omp.js +5 -3
- package/dist/bridge/drivers/omp.js.map +1 -1
- package/dist/bridge/drivers/opencode.js +4 -3
- package/dist/bridge/drivers/opencode.js.map +1 -1
- package/dist/bridge/drivers/qwen.js +6 -5
- package/dist/bridge/drivers/qwen.js.map +1 -1
- package/dist/bridge/index.js +5 -4
- package/dist/bridge/src/agent-exec.d.ts +6 -0
- package/dist/bridge/src/agent-exec.d.ts.map +1 -1
- package/dist/bridge/src/agent-transcript.d.ts +18 -0
- package/dist/bridge/src/agent-transcript.d.ts.map +1 -0
- package/dist/bridge/src/codex-app-server.d.ts.map +1 -1
- package/dist/bridge/src/drivers/_subprocess-cli.d.ts.map +1 -1
- package/dist/bridge/src/drivers/claude-sdk.d.ts +2 -0
- package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
- package/dist/bridge/src/drivers/omp.d.ts.map +1 -1
- package/dist/bridge/src/drivers/scrub-transcript.d.ts +29 -0
- package/dist/bridge/src/drivers/scrub-transcript.d.ts.map +1 -1
- package/dist/bridge/src/index.d.ts +2 -0
- package/dist/bridge/src/index.d.ts.map +1 -1
- package/dist/{chunk-4BOSWZIB.js → chunk-25BOOOSM.js} +3 -3
- package/dist/{chunk-4BOSWZIB.js.map → chunk-25BOOOSM.js.map} +1 -1
- package/dist/{chunk-O4NAFJLZ.js → chunk-66MJRB6K.js} +2 -2
- package/dist/{chunk-O4NAFJLZ.js.map → chunk-66MJRB6K.js.map} +1 -1
- package/dist/{chunk-S3ZR5G45.js → chunk-66WUZ3XL.js} +5 -5
- package/dist/{chunk-S3ZR5G45.js.map → chunk-66WUZ3XL.js.map} +1 -1
- package/dist/{chunk-3W7AOGPY.js → chunk-6S5KL76M.js} +225 -46
- package/dist/chunk-6S5KL76M.js.map +1 -0
- package/dist/{chunk-F5UGKSCI.js → chunk-6V3DMJPL.js} +3 -3
- package/dist/{chunk-F5UGKSCI.js.map → chunk-6V3DMJPL.js.map} +1 -1
- package/dist/{chunk-UI4ICUTH.js → chunk-EBYSCP6J.js} +4 -4
- package/dist/{chunk-UI4ICUTH.js.map → chunk-EBYSCP6J.js.map} +1 -1
- package/dist/{chunk-HRHV52XT.js → chunk-EEODEEKX.js} +3 -3
- package/dist/{chunk-HRHV52XT.js.map → chunk-EEODEEKX.js.map} +1 -1
- package/dist/{chunk-ZHHIIIZU.js → chunk-EPSCLN5W.js} +3 -3
- package/dist/{chunk-ZHHIIIZU.js.map → chunk-EPSCLN5W.js.map} +1 -1
- package/dist/{chunk-BDCABUDR.js → chunk-J3K5O6XA.js} +3 -3
- package/dist/{chunk-BDCABUDR.js.map → chunk-J3K5O6XA.js.map} +1 -1
- package/dist/{chunk-4F2L7WPU.js → chunk-K4O6L3WH.js} +5 -3
- package/dist/chunk-K4O6L3WH.js.map +1 -0
- package/dist/{chunk-R6DXYDPU.js → chunk-P6S5K7AI.js} +3 -3
- package/dist/{chunk-R6DXYDPU.js.map → chunk-P6S5K7AI.js.map} +1 -1
- package/dist/{chunk-C5SMPTNV.js → chunk-RGB45PIL.js} +2 -2
- package/dist/{chunk-C5SMPTNV.js.map → chunk-RGB45PIL.js.map} +1 -1
- package/dist/{chunk-XFYURHVP.js → chunk-RYIWFV67.js} +2 -2
- package/dist/{chunk-XFYURHVP.js.map → chunk-RYIWFV67.js.map} +1 -1
- package/dist/{chunk-XV6SM6LT.js → chunk-S4R3WNRF.js} +3 -3
- package/dist/{chunk-XV6SM6LT.js.map → chunk-S4R3WNRF.js.map} +1 -1
- package/dist/{chunk-4ZWAXIHA.js → chunk-T6QGP5HN.js} +6 -6
- package/dist/{chunk-4ZWAXIHA.js.map → chunk-T6QGP5HN.js.map} +1 -1
- package/dist/{chunk-QTC7I2KF.js → chunk-VXY6LSQ3.js} +6 -6
- package/dist/{chunk-QTC7I2KF.js.map → chunk-VXY6LSQ3.js.map} +1 -1
- package/dist/{chunk-CFBKN3BP.js → chunk-W2SDSDR7.js} +23 -13
- package/dist/chunk-W2SDSDR7.js.map +1 -0
- package/dist/{chunk-MYGLPCMR.js → chunk-XAKGLR4Y.js} +6 -6
- package/dist/{chunk-MYGLPCMR.js.map → chunk-XAKGLR4Y.js.map} +1 -1
- package/dist/chunk-YROR332M.js +25 -0
- package/dist/chunk-YROR332M.js.map +1 -0
- package/dist/{chunk-FQ45HI34.js → chunk-YUH46KA7.js} +6 -4
- package/dist/chunk-YUH46KA7.js.map +1 -0
- package/dist/cli/index.js +33 -32
- package/dist/cli/index.js.map +1 -1
- package/dist/connectors/index.js +6 -5
- package/dist/{ensure-sources-ZURLP3YP.js → ensure-sources-WYXFJWUO.js} +4 -4
- package/dist/{ensure-sources-ZURLP3YP.js.map → ensure-sources-WYXFJWUO.js.map} +1 -1
- package/dist/factory-assets/connectors/box.js +6 -5
- package/dist/factory-assets/connectors/deploy.js +6 -5
- package/dist/factory-assets/connectors/devserver.js +6 -5
- package/dist/factory-assets/connectors/flow/adapter.js +6 -5
- package/dist/factory-assets/connectors/flow/run-flow.js +7 -6
- package/dist/factory-assets/connectors/flow.js +6 -5
- package/dist/factory-assets/connectors/git.js +6 -5
- package/dist/factory-assets/connectors/gmail.js +6 -5
- package/dist/factory-assets/connectors/googledrive.js +6 -5
- package/dist/factory-assets/connectors/local.js +6 -5
- package/dist/factory-assets/connectors/mattermost.js +6 -5
- package/dist/factory-assets/connectors/memory.js +6 -5
- package/dist/factory-assets/connectors/minio.js +6 -5
- package/dist/factory-assets/connectors/postgres.js +6 -5
- package/dist/factory-assets/connectors/s3.js +6 -5
- package/dist/factory-assets/connectors/sharepoint.js +6 -5
- package/dist/factory-assets/connectors/sqlite.js +6 -5
- package/dist/factory-assets/connectors/static-server.js +6 -5
- package/dist/factory-assets/connectors/tunnel.js +6 -5
- package/dist/factory-assets/connectors/webdav.js +6 -5
- package/dist/factory-assets/connectors/xstate-store.js +6 -5
- package/dist/factory-assets/connectors/xstate.js +6 -5
- package/dist/{helpers-5KGGPDGO.js → helpers-TANA2HQT.js} +4 -4
- package/dist/{helpers-5KGGPDGO.js.map → helpers-TANA2HQT.js.map} +1 -1
- package/dist/{library-publish-ZQXODG4U.js → library-publish-JQNTMKZG.js} +6 -6
- package/dist/{library-publish-ZQXODG4U.js.map → library-publish-JQNTMKZG.js.map} +1 -1
- package/dist/{open-library-FWUMCU7A.js → open-library-NKZ4HJJ6.js} +5 -5
- package/dist/{open-library-FWUMCU7A.js.map → open-library-NKZ4HJJ6.js.map} +1 -1
- package/dist/{project-UCWVE4YV.js → project-AEAM2ZEW.js} +5 -5
- package/dist/{project-UCWVE4YV.js.map → project-AEAM2ZEW.js.map} +1 -1
- package/dist/runner/index.js +9 -8
- package/dist/runner/src/serve-credentials.d.ts +2 -1
- package/dist/runner/src/serve-credentials.d.ts.map +1 -1
- package/dist/runner/src/serve.d.ts.map +1 -1
- package/dist/sdk/asset-manager.js +1 -1
- package/dist/sdk/bridge.js +5 -4
- package/dist/sdk/index.js +9 -8
- package/dist/sdk/index.js.map +1 -1
- package/dist/sdk/runner.js +9 -8
- package/dist/{setup-ACVYCGYQ.js → setup-Q7ACRV72.js} +10 -9
- package/dist/setup-Q7ACRV72.js.map +1 -0
- package/dist/{source-55ORZZU7.js → source-QXQ3NO46.js} +6 -6
- package/dist/{source-55ORZZU7.js.map → source-QXQ3NO46.js.map} +1 -1
- package/dist/{source-manifest-publish-2GMXNX6M.js → source-manifest-publish-UKWCZA2M.js} +7 -7
- package/dist/{source-manifest-publish-2GMXNX6M.js.map → source-manifest-publish-UKWCZA2M.js.map} +1 -1
- package/dist/tui/index.js +9 -8
- package/dist/tui/index.js.map +1 -1
- package/dist/workspace-plugin/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3W7AOGPY.js.map +0 -1
- package/dist/chunk-4F2L7WPU.js.map +0 -1
- package/dist/chunk-CFBKN3BP.js.map +0 -1
- package/dist/chunk-FQ45HI34.js.map +0 -1
- package/dist/setup-ACVYCGYQ.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../bridge/src/cloud.ts","../bridge/src/agent-exec.ts","../bridge/src/drivers/scrub-transcript.ts","../bridge/src/drivers/resume-probe.ts"],"names":["join"],"mappings":";;;;;;;;;AAuCA,IAAM,iBAAA,GAAoB,CAAC,mBAAA,EAAqB,sBAAA,EAAwB,oBAAoB,CAAA;AAQrF,IAAM,0BAAA,GAA6B;AAQ1C,IAAM,iBAAA,GAA0C;AAAA,EAC9C,mBAAA,EAAqB,IAAA;AAAA,EACrB,aAAA,EAAe,IAAA;AAAA,EACf,WAAA,EAAa;AACf,CAAA;AAcO,SAAS,mBAAmB,KAAA,EAA4C;AAC7E,EAAA,MAAM,UAAW,KAAA,CAA6B,OAAA;AAC9C,EAAA,MAAM,SAAA,GAAY,eAAe,KAAK,CAAA;AACtC,EAAA,IAAI,OAAA,KAAY,yBAAA,IAA6B,SAAA,KAAc,SAAA,EAAW,OAAO,SAAA;AAC7E,EAAA,IAAI,OAAA,KAAY,eAAA,IAAmB,SAAA,KAAc,QAAA,EAAU,OAAO,Q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,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-3W7AOGPY.js","sourcesContent":["/**\n * AI endpoint transport for the `claude-sdk` driver — the Claude Agent SDK's\n * child-process environment.\n *\n * {@link buildClaudeEndpointEnv} takes an **AI provider registry entry** and\n * is what the driver calls, on every transport. It is plan §2.3's\n * `buildEndpointEnv` for the claude-sdk row (named for the driver because the\n * vars it emits — `CLAUDE_CODE_USE_*`, `ANTHROPIC_*` — are the Claude Agent\n * SDK's own contract, not a portable one).\n *\n * A registry entry says what the deleted `cloud` axis said — Amazon Bedrock,\n * Google Vertex AI, Azure AI Foundry, a generic gateway — with `surface` +\n * `transport` + `base_url` + `credential`, and says it for the direct\n * endpoint too, which the `cloud` axis could not address at all.\n *\n * Cross-repo contract: env key names and semantics here are load-bearing —\n * the platform resolves credential bundles against the same key set.\n */\n\nimport {\n type AIProviderEntry,\n type AIProviderLlmEntry,\n entryTransport,\n normalizeAnthropicBaseUrl,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\n\n/**\n * Env vars scrubbed from the inherited environment before an endpoint env is\n * assembled. Ambient first-party credentials or a stale `CLAUDE_CODE_USE_*`\n * flag must never leak into a session whose entry points elsewhere (the\n * ambient carriers are restored explicitly when the entry has none of its\n * own).\n *\n * Deliberately NOT exhaustive: ambient transport-specific vars (AWS_*,\n * GOOGLE_*, ANTHROPIC_VERTEX_PROJECT_ID, ANTHROPIC_FOUNDRY_*) survive so a\n * standalone CLI inherits its own signing chain; the SDK ignores vars whose\n * transport flag is unset.\n */\nconst SCRUBBED_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_BASE_URL\"];\n\n/**\n * The Anthropic first-party endpoint. An entry that resolves to exactly this\n * host needs no `ANTHROPIC_BASE_URL`: the SDK already points there, and an\n * explicit value would make every default session look like a third-party\n * redirect to Claude Code's own telemetry and auth heuristics.\n */\nexport const ANTHROPIC_DEFAULT_BASE_URL = \"https://api.anthropic.com\";\n\n/**\n * Headers the SDK owns and an entry must not restate through\n * `ANTHROPIC_CUSTOM_HEADERS`: the protocol version it was built against, and\n * the two credential carriers (which are `credential.ref`'s job — a literal\n * secret in `headers` is a validation error anyway).\n */\nconst SDK_OWNED_HEADERS: Record<string, true> = {\n \"anthropic-version\": true,\n authorization: true,\n \"x-api-key\": true,\n};\n\n/**\n * Which of the Claude Agent SDK's four native transports an entry addresses.\n *\n * The SDK has no `transport` field: it switches on a `CLAUDE_CODE_USE_*` flag.\n * Bedrock and Vertex are their own wire surfaces, so they are recognized by\n * `surface` as well as by `transport` — a legacy-derived entry that had no\n * region (and therefore no `params`, and therefore no `transport`) is still a\n * Bedrock session, exactly as it was before the registry existed.\n */\nexport type ClaudeEndpointMode = \"anthropic\" | \"bedrock\" | \"vertex\" | \"foundry\";\n\n/** Classify a registry entry into its {@link ClaudeEndpointMode}. */\nexport function claudeEndpointMode(entry: AIProviderEntry): ClaudeEndpointMode {\n const surface = (entry as AIProviderLlmEntry).surface;\n const transport = entryTransport(entry);\n if (surface === \"bedrock-converse-stream\" || transport === \"bedrock\") return \"bedrock\";\n if (surface === \"google-vertex\" || transport === \"vertex\") return \"vertex\";\n if (transport === \"foundry\") return \"foundry\";\n return \"anthropic\";\n}\n\n/** Arguments for {@link buildClaudeEndpointEnv}. */\nexport interface ClaudeEndpointEnvInput {\n /** The selected registry entry — the whole endpoint definition. */\n entry: AIProviderEntry;\n /**\n * The entry's credential, already resolved from its `credential.ref`\n * (`resolveEntryCredential`). Absent for `kind: none`, for an ambient\n * `sigv4` / `google_adc` / `azure_entra` chain, for `oauth` (whose blob the\n * runner writes to the Claude credentials file, never to the env), and for a\n * reference that did not resolve.\n */\n credential?: string;\n /**\n * The driver's base environment — `process.env` with `undefined` dropped.\n * The endpoint vars are layered **on top** of it, never instead of it, so\n * `PATH`, `HOME` and `SKAILE_SESSION_ID` reach the child.\n */\n baseEnv: Record<string, string>;\n /** `AgentConfig.env` plus any credential material the session carried. */\n configEnv?: Record<string, string>;\n}\n\n/**\n * Assemble the Claude Agent SDK child env for one registry entry (plan §2.3).\n *\n * Pure (no external state read, no input mutated). Starts from `baseEnv`\n * merged with `configEnv`, scrubs the inherited Anthropic credential/routing\n * vars and every `CLAUDE_CODE_USE_*` flag, then writes exactly what the entry\n * describes: at most one transport flag, the endpoint, and the credential in\n * the carrier its `kind` names.\n *\n * Credential kinds (§1.4): `api_key_header` → `ANTHROPIC_API_KEY` (the SDK\n * sends it as `x-api-key`); `bearer` → `ANTHROPIC_AUTH_TOKEN` (sent as\n * `Authorization: Bearer`); `sigv4` / `google_adc` / `azure_entra` emit\n * nothing and let the AWS/Google/Azure chain sign — which is why the scrub\n * deliberately spares ambient `AWS_*` / `GOOGLE_*` values; `oauth` and `none`\n * emit nothing, and the pre-scrub ambient carriers are restored so an OAuth or\n * shell-configured session keeps the auth it had.\n *\n * Never returns `undefined` or empty values; absent settings are omitted.\n */\nexport function buildClaudeEndpointEnv(args: ClaudeEndpointEnvInput): Record<string, string> {\n const { entry, credential, baseEnv, configEnv } = args;\n const env: Record<string, string> = { ...baseEnv, ...(configEnv ?? {}) };\n\n // Captured before the scrub — an entry with no credential material of its\n // own falls back to these, the way the gateway branch always has.\n const ambient = { authToken: env.ANTHROPIC_AUTH_TOKEN, apiKey: env.ANTHROPIC_API_KEY };\n\n for (const key of Object.keys(env)) {\n if (SCRUBBED_ENV_KEYS.includes(key) || key.startsWith(\"CLAUDE_CODE_USE_\")) {\n delete env[key];\n }\n }\n\n const set = (key: string, value: string | undefined) => {\n // Falsy check is deliberate: an empty-string credential/setting is never\n // valid env — dropping it beats shipping a key the SDK treats as set.\n if (value) env[key] = value;\n };\n\n const kind = entry.credential?.kind ?? \"none\";\n const params = (entry as AIProviderLlmEntry).params as Record<string, string> | undefined;\n\n // Static headers ride as ANTHROPIC_CUSTOM_HEADERS (`Name: Value` per line),\n // the only channel the SDK offers. An entry with none leaves an ambient\n // value alone.\n const headers = Object.entries(entry.headers ?? {}).filter(\n ([name]) => !SDK_OWNED_HEADERS[name.toLowerCase()],\n );\n if (headers.length > 0) {\n env.ANTHROPIC_CUSTOM_HEADERS = headers.map(([name, value]) => `${name}: ${value}`).join(\"\\n\");\n }\n\n switch (claudeEndpointMode(entry)) {\n case \"bedrock\": {\n env.CLAUDE_CODE_USE_BEDROCK = \"1\";\n // The AWS credential bundle itself is `configEnv` material (AWS_*), and\n // ambient AWS_* survived the scrub, so a standalone CLI keeps its own.\n set(\"AWS_REGION\", params?.region);\n break;\n }\n case \"vertex\": {\n env.CLAUDE_CODE_USE_VERTEX = \"1\";\n // GOOGLE_APPLICATION_CREDENTIALS is a path the runner materialized; it\n // arrives through `configEnv` or ambient, never from `credential`.\n set(\"ANTHROPIC_VERTEX_PROJECT_ID\", params?.project);\n set(\"CLOUD_ML_REGION\", params?.location);\n break;\n }\n case \"foundry\": {\n env.CLAUDE_CODE_USE_FOUNDRY = \"1\";\n // §1.3: an explicit `base_url` wins over the resource-derived endpoint,\n // and the SDK has a separate var for each form.\n if (entry.base_url) set(\"ANTHROPIC_FOUNDRY_BASE_URL\", entry.base_url);\n else set(\"ANTHROPIC_FOUNDRY_RESOURCE\", params?.resource);\n set(\"ANTHROPIC_FOUNDRY_API_KEY\", credential);\n break;\n }\n case \"anthropic\": {\n const baseUrl = normalizeAnthropicBaseUrl(resolveEntryBaseUrl(entry));\n if (baseUrl && baseUrl.toLowerCase() !== ANTHROPIC_DEFAULT_BASE_URL) {\n env.ANTHROPIC_BASE_URL = baseUrl;\n }\n if (kind === \"bearer\") set(\"ANTHROPIC_AUTH_TOKEN\", credential);\n else if (kind === \"api_key_header\") set(\"ANTHROPIC_API_KEY\", credential);\n if (!credential) {\n // `oauth` / `none` / an unresolved ref: the ambient carriers are the\n // only auth this session has, and the scrub just removed them.\n if (ambient.authToken) env.ANTHROPIC_AUTH_TOKEN = ambient.authToken;\n else set(\"ANTHROPIC_API_KEY\", ambient.apiKey);\n }\n break;\n }\n }\n\n return env;\n}\n","import { isAbsolute } from \"node:path\";\n\n/**\n * Names the shim that starts agent processes as a separate uid.\n *\n * In the Skaile agent image the runner cannot switch uid itself (it runs with\n * no-new-privs and no `CAP_SETUID`). When the container entrypoint has started\n * the root launcher (`skaile-agent-launchd`), it exports this variable with the\n * absolute path of the runner-side shim (`skaile-agent-exec`). A driver then\n * spawns `<shim> -- <command> <args...>` instead of `<command>`: the shim\n * passes its stdio, cwd, argv and env to the launcher, which runs the command\n * as the agent uid, forwards signals and reports the exit status, so the\n * returned child behaves like a direct one.\n *\n * Unset (every other environment, and the image until the entrypoint wires\n * it): drivers spawn directly, unchanged.\n */\nexport const AGENT_EXEC_ENV = \"SKAILE_AGENT_EXEC\";\n\n/**\n * The shim path from `env`, or `null` when the uid split is off.\n *\n * Throws on a relative path rather than spawning the agent unsplit: only the\n * entrypoint sets this, so a bad value is a broken image, and silently running\n * the agent as the runner's uid would hide exactly what the variable promises.\n */\nexport function resolveAgentExec(\n env: Record<string, string | undefined> = process.env,\n): string | null {\n const value = env[AGENT_EXEC_ENV]?.trim();\n if (!value) return null;\n if (!isAbsolute(value)) {\n throw new Error(\n `${AGENT_EXEC_ENV} must be an absolute path to the agent launch shim, got \"${value}\"`,\n );\n }\n return value;\n}\n\n/**\n * The command line to spawn: `command args` itself, or routed through the\n * shim when one is configured. The `--` stops the shim reading the agent's\n * own arguments as options.\n */\nexport function wrapAgentCommand(\n command: string,\n args: readonly string[],\n shim: string | null,\n): { command: string; args: string[] } {\n if (!shim) return { command, args: [...args] };\n return { command: shim, args: [\"--\", command, ...args] };\n}\n","/**\n * Poisoned-transcript repair for the Claude Agent SDK driver.\n *\n * The Anthropic Messages API can permanently reject a conversation once its\n * persisted history contains a malformed content block. Because the bad block\n * lives in the SDK's on-disk JSONL transcript, every replayed turn fails with\n * the same `400 invalid_request_error` and the session is bricked with no\n * in-band recovery.\n *\n * This module repairs the transcript in place, covering three known poison\n * classes:\n *\n * 1. **Image `media_type` mismatch / omission.** An image block whose declared\n * `media_type` does not match — or is missing for — the actual bytes:\n * `... The image was specified using the image/png media type, but the\n * image appears to be a image/jpeg image`. Produced by the Claude Code\n * `Read` tool's format fallback (anthropics/claude-code#55338, #30124,\n * #33179). Repaired by sniffing the base64 magic bytes and correcting\n * `media_type`.\n * 2. **Oversized image.** An image whose decoded payload exceeds the API's\n * 5 MB per-image limit (anthropics/claude-code#34566). Replaced with a\n * text stub — the byte budget cannot be recovered any other way.\n * 3. **`cache_control` on an empty text block.** A text block carrying a\n * `cache_control` marker with empty/whitespace `text`\n * (anthropics/claude-code#59626). The `cache_control` field is stripped.\n *\n * Genuinely unidentifiable image blocks are also replaced with a text stub.\n *\n * Recovering by content scan (rather than parsing the API's `messages.N`\n * index) is deliberate: the index addresses the assembled API request, not a\n * JSONL line, and reproducing the SDK's message-assembly is fragile. A full\n * scan is index-free and repairs every poisoned block in one pass.\n *\n * **Async and line-streaming since #454.** A Claude Code transcript is routinely\n * multi-megabyte (base64 images inline in `tool_result` blocks), and this runs on\n * a failed turn *and before every resume* — inside the single-threaded `skaile\n * serve` loop. The previous `readFileSync` + `writeFileSync` + `renameSync` held\n * the loop for the whole file and materialised it twice over as one string. Both\n * passes now stream line by line off a `createReadStream`, so the loop is yielded\n * between lines and peak memory is one JSONL line rather than the whole file, and\n * every I/O phase is deadline-bounded.\n *\n * Streaming was chosen over a worker thread: the work is I/O-bound rather than\n * CPU-bound (per-line `JSON.parse` on a yielded loop is not what stalls a turn),\n * and a worker would add a structured-clone of the same multi-MB payload plus a\n * thread lifecycle to a path that must never block a turn.\n *\n * @module\n */\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { readdir, rename, stat, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { fsDeadlineMs, tryWithFsDeadline, withFsDeadline } from \"@skaile/workspaces/core\";\n\n/**\n * Minimal logger shape accepted by {@link scrubPoisonedTranscript}. Compatible\n * with the bridge `Logger`, but narrowed so the helper stays unit-testable\n * without a real logger instance.\n *\n * @category Transcript repair\n */\nexport interface ScrubLogger {\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n}\n\n/**\n * Options for {@link scrubPoisonedTranscript}.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptOptions {\n /**\n * Claude Code config directory — the parent of `projects/`. Resolve from\n * `CLAUDE_CONFIG_DIR`, falling back to `~/.claude`.\n */\n configDir: string;\n /** SDK session id whose transcript JSONL should be repaired. */\n sessionId: string;\n /** Optional logger for diagnostics. */\n log?: ScrubLogger;\n}\n\n/**\n * Outcome of a {@link scrubPoisonedTranscript} pass.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptResult {\n /** The located JSONL transcript path, or `null` when not found. */\n filePath: string | null;\n /** Image blocks whose `media_type` was corrected (or filled in) to match the bytes. */\n corrected: number;\n /**\n * Image blocks replaced with a text stub — either unidentifiable bytes or a\n * payload over the API's 5 MB per-image limit.\n */\n stubbed: number;\n /** Empty text blocks from which a rejected `cache_control` marker was stripped. */\n cacheStripped: number;\n /**\n * `true` when the transcript was located, contained at least one poisoned\n * block, and was rewritten. `false` means nothing needed repair (or the\n * file was not found) — the caller should not retry the resume.\n */\n changed: boolean;\n}\n\n/** Text inserted in place of an image block whose format cannot be identified. */\nconst STUB_TEXT = \"[image removed: unprocessable image data]\";\n\n/** Text inserted in place of an image block that exceeds the API size limit. */\nconst STUB_TEXT_OVERSIZED = \"[image removed: image too large]\";\n\n/**\n * The Anthropic Messages API rejects any single image whose decoded payload\n * exceeds 5 MB. An image at or under this is left alone; a larger one is\n * stubbed (its byte budget cannot be recovered).\n */\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Identify an image's media type from the leading bytes of its base64 payload.\n *\n * Recognises the four formats the Anthropic API accepts. Returns `null` when\n * the magic bytes match no known format — the caller treats that as a\n * genuinely corrupt block and stubs it.\n *\n * @param base64 - Base64-encoded image data (only the prefix is inspected).\n * @returns An `image/*` media type, or `null` when unrecognised.\n * @category Transcript repair\n */\nexport function sniffImageMediaType(base64: string): string | null {\n let buf: Buffer;\n try {\n // 32 base64 chars decode to 24 bytes — enough for the WebP check at 12.\n buf = Buffer.from(base64.slice(0, 32), \"base64\");\n } catch {\n return null;\n }\n if (buf.length < 4) {\n return null;\n }\n // JPEG — SOI marker `FF D8`. Third byte varies (and may be corrupt), so a\n // two-byte check is intentional: it still matches malformed JPEGs, which is\n // exactly the poison case the API flags as \"appears to be image/jpeg\".\n if (buf[0] === 0xff && buf[1] === 0xd8) {\n return \"image/jpeg\";\n }\n // PNG — `89 50 4E 47`.\n if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {\n return \"image/png\";\n }\n // GIF — `47 49 46 38` (\"GIF8\").\n if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) {\n return \"image/gif\";\n }\n // WebP — `RIFF` at 0..3 and `WEBP` at 8..11.\n if (\n buf.length >= 12 &&\n buf[0] === 0x52 &&\n buf[1] === 0x49 &&\n buf[2] === 0x46 &&\n buf[3] === 0x46 &&\n buf[8] === 0x57 &&\n buf[9] === 0x45 &&\n buf[10] === 0x42 &&\n buf[11] === 0x50\n ) {\n return \"image/webp\";\n }\n return null;\n}\n\n/** A base64 image source on a content block (shape is SDK-defined). */\ninterface Base64ImageSource {\n type?: string;\n media_type?: string;\n data?: string;\n}\n\n/** Loosely-typed content block from a transcript message. */\ninterface ContentBlockLike {\n type?: string;\n source?: Base64ImageSource;\n content?: unknown;\n [k: string]: unknown;\n}\n\n/** Mutable counters threaded through one scrub pass. */\ninterface ScrubCounters {\n corrected: number;\n stubbed: number;\n cacheStripped: number;\n}\n\n/** Total repairs recorded in a counter set — used to detect per-line changes. */\nfunction totalChanges(c: ScrubCounters): number {\n return c.corrected + c.stubbed + c.cacheStripped;\n}\n\n/**\n * Repair a single content block. Returns the (possibly replaced) block.\n *\n * - A `tool_result` block recurses into its `content` array.\n * - A text block carrying a `cache_control` marker whose `text` is empty or\n * whitespace has the marker stripped (the API rejects `cache_control` on\n * empty text blocks).\n * - An image block whose decoded payload exceeds the API's 5 MB limit is\n * replaced with a text stub.\n * - An image block whose bytes match no known format is replaced with a text\n * stub (an image cannot simply be dropped — a `tool_result` must keep at\n * least one content entry, and a bare `image` block is replaced 1:1).\n * - An image block whose declared `media_type` mismatches (or is missing for)\n * the sniffed type is corrected in place.\n * - Every other block is returned untouched.\n */\nfunction scrubBlock(block: ContentBlockLike, counters: ScrubCounters): ContentBlockLike {\n if (block.type === \"tool_result\" && Array.isArray(block.content)) {\n return {\n ...block,\n content: (block.content as ContentBlockLike[]).map((inner) => scrubBlock(inner, counters)),\n };\n }\n\n // A `cache_control` marker on a text block whose text is empty or whitespace\n // is rejected by the API (\"cache_control cannot be set for empty text\n // blocks\"). Strip the marker — the empty block itself is harmless.\n if (block.type === \"text\" && block.cache_control != null) {\n const text = typeof block.text === \"string\" ? block.text : \"\";\n if (text.trim() === \"\") {\n counters.cacheStripped++;\n const clone = { ...block };\n delete clone.cache_control;\n return clone;\n }\n }\n\n if (\n block.type === \"image\" &&\n block.source?.type === \"base64\" &&\n typeof block.source.data === \"string\"\n ) {\n const data = block.source.data;\n // The API rejects any image whose decoded payload exceeds 5 MB. The byte\n // budget cannot be salvaged, so the whole block becomes a text stub.\n // base64 encodes 3 bytes per 4 chars, so decoded length ≈ len * 3 / 4.\n if (Math.floor((data.length * 3) / 4) > MAX_IMAGE_BYTES) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT_OVERSIZED };\n }\n const sniffed = sniffImageMediaType(data);\n if (sniffed === null) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT };\n }\n if (sniffed !== block.source.media_type) {\n counters.corrected++;\n return { ...block, source: { ...block.source, media_type: sniffed } };\n }\n }\n\n return block;\n}\n\n/**\n * Locate the JSONL transcript for `sessionId` under `<configDir>/projects/`.\n *\n * Claude Code encodes the project directory into the `projects/` subfolder\n * name; rather than reproduce that encoding, this scans every subfolder for\n * `<sessionId>.jsonl` (the session id is a UUID — globally unique).\n *\n * Async and deadline-bounded since #454. The `existsSync(projectsDir)` probe is\n * gone: `readdir` already fails on a missing directory, so the probe was a\n * second stat on the same path for no information.\n *\n * `timeoutMs` defaults to {@link fsDeadlineMs} so callers that only need the\n * path (the resume probe) can omit it.\n *\n * @category Transcript repair\n */\nexport async function locateTranscriptPath(\n configDir: string,\n sessionId: string,\n timeoutMs: number = fsDeadlineMs(),\n): Promise<string | null> {\n const projectsDir = join(configDir, \"projects\");\n const entries = await tryWithFsDeadline(\n `readdir ${projectsDir}`,\n () => readdir(projectsDir),\n null,\n timeoutMs,\n );\n if (!entries) return null;\n for (const entry of entries) {\n const candidate = join(projectsDir, entry, `${sessionId}.jsonl`);\n const found = await tryWithFsDeadline(\n `stat ${candidate}`,\n async () => (await stat(candidate)).isFile(),\n false,\n timeoutMs,\n );\n if (found) return candidate;\n }\n return null;\n}\n\n/**\n * Yield a file's contents line by line, reproducing `readFileSync(...).split(\"\\n\")`\n * exactly — including the final (possibly empty) segment, so a trailing newline\n * survives a rewrite byte for byte.\n *\n * Splits on `\\n` alone, so a line out of a CRLF transcript arrives with its\n * `\\r` still attached. That carrier byte is part of the line here, and\n * {@link repairLine} re-attaches it to a line it rewrites — the file keeps the\n * terminator style it arrived with. Deliberately not `node:readline`:\n * `crlfDelay` strips the `\\r` outright (rewriting a CRLF transcript to LF) and\n * the interface swallows the trailing-newline distinction, either of which\n * would make the \"clean transcript is left byte-for-byte untouched\" guarantee\n * false. Only one line is held in memory at a time, so a multi-MB transcript\n * never materialises as a single string.\n */\nasync function* streamLines(filePath: string): AsyncGenerator<string> {\n const stream = createReadStream(filePath, { encoding: \"utf8\" });\n let pending = \"\";\n try {\n for await (const chunk of stream) {\n pending += chunk as string;\n let idx = pending.indexOf(\"\\n\");\n while (idx !== -1) {\n yield pending.slice(0, idx);\n pending = pending.slice(idx + 1);\n idx = pending.indexOf(\"\\n\");\n }\n }\n yield pending;\n } finally {\n stream.destroy();\n }\n}\n\n/**\n * Repair one JSONL line, returning the (possibly rewritten) line and mutating\n * `counters`. A non-JSON, blank, or content-less line is returned untouched.\n *\n * The reader splits on `\\n` only, so a line from a CRLF transcript still carries\n * its trailing `\\r`. An untouched line is returned verbatim and keeps it; a\n * rewritten one is rebuilt by `JSON.stringify`, which would drop it — leaving a\n * repaired CRLF transcript with mixed line endings. So the terminator is split\n * off before the parse and re-appended to the rewritten line.\n */\nfunction repairLine(line: string, counters: ScrubCounters): string {\n if (line.trim() === \"\") return line;\n const eol = line.endsWith(\"\\r\") ? \"\\r\" : \"\";\n const body = eol === \"\" ? line : line.slice(0, -1);\n let entry: { message?: { content?: unknown } };\n try {\n entry = JSON.parse(body);\n } catch {\n return line; // Not JSON — leave untouched.\n }\n const content = entry.message?.content;\n if (!Array.isArray(content)) return line;\n const before = totalChanges(counters);\n const scrubbed = (content as ContentBlockLike[]).map((block) => scrubBlock(block, counters));\n if (totalChanges(counters) === before) return line; // Nothing changed on this line.\n return `${JSON.stringify({ ...entry, message: { ...entry.message, content: scrubbed } })}${eol}`;\n}\n\n/**\n * Scan a Claude Code SDK transcript for image content blocks whose declared\n * `media_type` does not match the actual bytes, repair them, and atomically\n * rewrite the file.\n *\n * Safe to call after a turn has failed: the SDK query is dead at that point,\n * and the next resume re-reads the transcript from disk.\n *\n * **Async since #454.** Two streaming passes rather than one whole-file read:\n * pass 1 counts repairs without writing anything, and pass 2 runs only when\n * pass 1 found something. The common case — the preventive scrub of a clean\n * transcript before every resume — is therefore one streaming read and zero\n * writes, and a clean transcript is still left byte-for-byte untouched.\n *\n * @param opts - Config directory, session id, and an optional logger.\n * @returns A {@link ScrubTranscriptResult}. When `changed` is `true` the\n * caller may retry the resume with the same session id.\n * @category Transcript repair\n */\nexport async function scrubPoisonedTranscript(\n opts: ScrubTranscriptOptions,\n): Promise<ScrubTranscriptResult> {\n const { configDir, sessionId, log } = opts;\n const timeoutMs = fsDeadlineMs();\n const result: ScrubTranscriptResult = {\n filePath: null,\n corrected: 0,\n stubbed: 0,\n cacheStripped: 0,\n changed: false,\n };\n\n const filePath = await locateTranscriptPath(configDir, sessionId, timeoutMs);\n if (!filePath) {\n log?.warn(\"scrub-transcript: no transcript found\", { configDir, sessionId });\n return result;\n }\n result.filePath = filePath;\n\n // ── Pass 1: detect. Streams the transcript, counting repairs, writing nothing.\n const counters: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n try {\n await withFsDeadline(\n `scan transcript ${filePath}`,\n async () => {\n for await (const line of streamLines(filePath)) repairLine(line, counters);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to read transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n return result;\n }\n\n result.corrected = counters.corrected;\n result.stubbed = counters.stubbed;\n result.cacheStripped = counters.cacheStripped;\n\n if (totalChanges(counters) === 0) {\n return result;\n }\n\n // ── Pass 2: rewrite. Atomic: stream a sibling temp file, then rename over the\n // original. Line separators are re-emitted exactly as pass 1 split them, so a\n // trailing newline and any blank lines survive verbatim.\n const tmpPath = `${filePath}.scrub-tmp`;\n try {\n await withFsDeadline(\n `rewrite transcript ${filePath}`,\n async () => {\n const discard: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n await pipeline(\n (async function* () {\n let first = true;\n for await (const line of streamLines(filePath)) {\n yield first ? repairLine(line, discard) : `\\n${repairLine(line, discard)}`;\n first = false;\n }\n })(),\n createWriteStream(tmpPath, { encoding: \"utf8\" }),\n );\n await rename(tmpPath, filePath);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to rewrite transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n // Never leave a half-written sibling behind — the next scrub would rewrite\n // it anyway, but a stray `.scrub-tmp` in the SDK's projects dir is noise.\n await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), undefined, timeoutMs);\n return result;\n }\n\n result.changed = true;\n log?.info(\"scrub-transcript: repaired poisoned transcript\", {\n filePath,\n corrected: result.corrected,\n stubbed: result.stubbed,\n cacheStripped: result.cacheStripped,\n });\n return result;\n}\n","/**\n * Pre-first-turn resume probe for the Claude Agent SDK driver.\n *\n * A tier-1 native resume only hands its session id to the SDK inside the first\n * real turn, so the `jsonl_lost` outcome (\"No conversation found\") is invisible\n * until a turn is consumed. The runner shares the container filesystem with the\n * SDK, so a cheap `stat` of the on-disk JSONL transcript is an authoritative,\n * side-effect-free signal of whether the resume will find its history — no\n * probe query, no spurious model turn.\n *\n * @module\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { withFsDeadline } from \"@skaile/workspaces/core\";\nimport { locateTranscriptPath } from \"./scrub-transcript.js\";\n\n/**\n * Overall wall-clock budget for the probe. Deliberately a small fraction of the\n * platform's `session_init_ack` timeout (`DEFAULT_INIT_ACK_TIMEOUT_MS`, 15s):\n * the probe runs synchronously on the pre-ack path, so a wedged\n * `CLAUDE_CONFIG_DIR` mount must never push the ack past its deadline.\n */\nconst RESUME_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Outcome of {@link probeResumeTranscript}: whether the SDK transcript for a\n * requested tier-1 resume exists on disk.\n *\n * @category Resume probe\n */\nexport type ResumeProbeOutcome = \"transcript_found\" | \"jsonl_lost\";\n\n/**\n * Resolve the Claude Code config directory — the parent of `projects/` — from\n * an explicit env map, the process environment, or the `~/.claude` default.\n *\n * The runner's probe and the claude-sdk driver share this one resolver, so they\n * agree as long as they see the same `CLAUDE_CONFIG_DIR`. Today they do:\n * `CLAUDE_CONFIG_DIR` is container-scoped and neither side threads a per-session\n * override through `config.env`, so both fall through to `process.env`. If a\n * future change ever set the driver's `config.env.CLAUDE_CONFIG_DIR` to a\n * divergent path, the reactive `resume_failed { jsonl_lost }` turn remains the\n * safety net.\n *\n * @category Resume probe\n */\nexport function resolveClaudeConfigDir(env?: Record<string, string | undefined>): string {\n return env?.CLAUDE_CONFIG_DIR || process.env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n}\n\n/**\n * Probe whether the SDK JSONL transcript for `sessionId` exists on disk.\n *\n * Non-null locator result → `transcript_found`; null → `jsonl_lost`;\n * `undefined` → outcome unknown (the probe exceeded its budget or errored). The\n * caller leaves the ack field ABSENT on `undefined` so the reactive\n * `resume_failed { jsonl_lost }` turn stays the safety net — a timed-out probe\n * must never masquerade as a genuine `jsonl_lost` and force a needless downgrade.\n *\n * `opts.timeoutMs` overrides {@link RESUME_PROBE_TIMEOUT_MS}; `opts.locate`\n * overrides the transcript locator (used by tests / alternate stores).\n *\n * @category Resume probe\n */\nexport async function probeResumeTranscript(\n sessionId: string,\n opts?: {\n env?: Record<string, string | undefined>;\n timeoutMs?: number;\n locate?: (configDir: string, sessionId: string) => Promise<string | null>;\n },\n): Promise<ResumeProbeOutcome | undefined> {\n const configDir = resolveClaudeConfigDir(opts?.env);\n const timeoutMs = opts?.timeoutMs ?? RESUME_PROBE_TIMEOUT_MS;\n const locate = opts?.locate ?? locateTranscriptPath;\n try {\n // Bound the whole probe on wall-clock and THROW on expiry: the inner per-op\n // deadline swallows a timeout into a null path (a false `jsonl_lost`), so a\n // wedged mount must yield \"unknown\" here rather than a spurious downgrade.\n const filePath = await withFsDeadline(\n `resume-probe ${sessionId}`,\n () => locate(configDir, sessionId),\n timeoutMs,\n );\n return filePath ? \"transcript_found\" : \"jsonl_lost\";\n } catch {\n return undefined;\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../bridge/src/codex-app-server.ts"],"names":[],"mappings":";;;;AAqCO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,YACW,IAAA,EACT;AACA,IAAA,KAAA,CAAM,CAAA,iBAAA,EAAoB,IAAI,CAAA,CAAE,CAAA;AAFvB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGT,IAA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A,EAAU;AAClB,QAAA,IAAI;AACF,UAAA,IAAA,CAAK,KAAA,CAAM,EAAE,EAAA,EAAI,KAAA,EAAO,EAAE,MAAM,CAAA,KAAA,EAAQ,OAAA,EAAS,6BAAA,EAA8B,EAAG,CAAA;AAAA,QACpF,CAAA,CAAA,MAAQ;AACN,UAAA,IAAA,CAAK,KAAK,UAAU,CAAA;AAAA,QACtB;AAAA,MACF;AAAA,IACF,CAAA,SAAE;AACA,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,UAAA,CAAW,KAAA,EAAM;AACjB,MAAA,IAAA,CAAK,SAAA,CAAU,OAAO,EAAE,CAAA;AAAA,IAC1B;AAAA,EACF;AACF","file":"chunk-4F2L7WPU.js","sourcesContent":["import { CodexNativeStateUnavailable } from \"./codex/native-state.js\";\nimport { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\n// Narrow module, not the `core` barrel: the barrel's chunks carry `import.meta`,\n// which breaks consumers that transpile this entry to CommonJS.\nimport { processGroupAlive } from \"../../core/src/process-alive.js\";\nimport type { NativeRequests, NativeServerRequests } from \"./codex/native-protocol.generated.js\";\n\n/** The retained native request types, exposed only through this client surface. */\nexport type CodexRequestMethod = keyof NativeRequests;\n/** Native callback handlers receive cancellation when their process is disposed. */\nexport type CodexServerRequestHandlers = {\n [M in keyof NativeServerRequests]?: (\n params: NativeServerRequests[M][\"params\"],\n signal: AbortSignal,\n ) => Promise<NativeServerRequests[M][\"result\"]>;\n};\n/** Explicit process inputs keep managed callers from inheriting ambient credentials. */\nexport interface CodexAppServerOptions {\n command: string;\n args: string[];\n cwd: string;\n env: Record<string, string>;\n clientInfo: NativeRequests[\"initialize\"][\"params\"][\"clientInfo\"];\n requestTimeoutMs?: number;\n serverRequestTimeoutMs?: number;\n maxPendingRequests?: number;\n maxFrameBytes?: number;\n /** Isolate and reap the native process group on POSIX. */\n processGroup?: boolean;\n onServerRequest?: CodexServerRequestHandlers;\n /** Final synchronous lifecycle veto before a callback reply; cannot grant a missing handler. */\n canReplyToServerRequest?: (method: string, params: unknown) => boolean;\n onNotification?: (method: string, params: unknown) => void;\n /** Exactly once on terminal failure or disposal, even with no RPC pending. */\n onClose?: (error: CodexAppServerError) => void;\n}\n/** Safe error codes never contain stderr, native errors, RPC payloads or credentials. */\nexport class CodexAppServerError extends Error {\n constructor(\n readonly code: \"closed\" | \"process\" | \"protocol\" | \"timeout\" | \"rejected\" | \"capacity\",\n ) {\n super(`Codex App Server ${code}`);\n this.name = \"CodexAppServerError\";\n }\n}\ntype Pending = {\n resolve: (value: unknown) => void;\n reject: (error: CodexAppServerError | CodexNativeStateUnavailable) => void;\n timer: ReturnType<typeof setTimeout>;\n resumeThreadId?: string;\n};\nconst record = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\nconst validId = (value: unknown): value is string | number =>\n typeof value === \"string\" || (typeof value === \"number\" && Number.isSafeInteger(value));\nfunction bound(value: number | undefined, fallback: number, maximum: number): number {\n const result = value ?? fallback;\n if (!Number.isSafeInteger(result) || result <= 0 || result > maximum)\n throw new CodexAppServerError(\"protocol\");\n return result;\n}\n\n/** One initialized stdio process with correlated, bounded requests and terminal disposal. */\nexport class CodexAppServerClient {\n private readonly pending = new Map<number, Pending>();\n private readonly callbacks = new Map<string | number, AbortController>();\n private readonly timeout: number;\n private readonly callbackTimeout: number;\n private readonly capacity: number;\n private readonly frameLimit: number;\n private readonly child: ChildProcessWithoutNullStreams;\n private readonly closed: Promise<void>;\n private terminal = false;\n private childClosed = false;\n private nextId = 1;\n private buffer = \"\";\n\n private constructor(private readonly options: CodexAppServerOptions) {\n this.timeout = bound(options.requestTimeoutMs, 15_000, 300_000);\n this.callbackTimeout = bound(options.serverRequestTimeoutMs, 30_000, 300_000);\n this.capacity = bound(options.maxPendingRequests, 64, 1024);\n this.frameLimit = bound(options.maxFrameBytes, 1024 * 1024, 16 * 1024 * 1024);\n this.child = spawn(options.command, options.args, {\n cwd: options.cwd,\n env: options.env,\n stdio: \"pipe\",\n detached: options.processGroup === true && process.platform !== \"win32\",\n });\n this.closed = new Promise((resolve) =>\n this.child.once(\"close\", () => {\n this.childClosed = true;\n resolve();\n }),\n );\n this.child.stdout.setEncoding(\"utf8\");\n this.child.stdout.on(\"data\", (chunk: string) => this.receive(chunk));\n // Drain without retaining raw diagnostic output: native stderr can contain secrets.\n this.child.stderr.resume();\n this.child.on(\"error\", () => this.fail(\"process\"));\n this.child.stdin.on(\"error\", () => this.fail(\"process\"));\n this.child.stdout.on(\"error\", () => this.fail(\"process\"));\n this.child.stderr.on(\"error\", () => this.fail(\"process\"));\n this.child.once(\"exit\", () => this.fail(\"process\"));\n }\n\n /** Spawn and finish the native initialize/initialized handshake before returning. */\n static async connect(\n options: CodexAppServerOptions,\n signal?: AbortSignal,\n ): Promise<CodexAppServerClient> {\n let client: CodexAppServerClient | undefined;\n const abort = () => client?.fail(\"closed\");\n try {\n if (signal?.aborted) throw new CodexAppServerError(\"closed\");\n client = new CodexAppServerClient(options);\n signal?.addEventListener(\"abort\", abort, { once: true });\n await client.request(\"initialize\", {\n clientInfo: options.clientInfo,\n capabilities: { experimentalApi: true },\n });\n client.write({ method: \"initialized\" });\n return client;\n } catch (error) {\n await client?.dispose();\n throw error instanceof CodexAppServerError ? error : new CodexAppServerError(\"process\");\n } finally {\n signal?.removeEventListener(\"abort\", abort);\n }\n }\n\n /** Timeout closes this generation, so late replies can never satisfy a later request. */\n request<M extends CodexRequestMethod>(\n method: M,\n params: NativeRequests[M][\"params\"],\n ): Promise<NativeRequests[M][\"result\"]> {\n if (this.terminal) return Promise.reject(new CodexAppServerError(\"closed\"));\n if (this.pending.size >= this.capacity)\n return Promise.reject(new CodexAppServerError(\"capacity\"));\n const id = this.nextId++;\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => this.fail(\"timeout\"), this.timeout);\n this.pending.set(id, {\n resolve: resolve as (value: unknown) => void,\n reject,\n timer,\n ...(method === \"thread/resume\" &&\n params !== null &&\n \"threadId\" in params &&\n typeof params.threadId === \"string\"\n ? { resumeThreadId: params.threadId }\n : {}),\n });\n try {\n this.write({ id, method, params });\n } catch {\n this.fail(\"protocol\");\n }\n });\n }\n\n /** Reject pending work immediately and wait a bounded interval for process shutdown. */\n async dispose(): Promise<void> {\n this.fail(\"closed\");\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n this.closed,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, 1000);\n }),\n ]);\n clearTimeout(timer);\n }\n\n /** Positive exit proof for callers that may replace a failed native generation. */\n get terminationConfirmed(): boolean {\n if (!this.childClosed) return false;\n if (!this.options.processGroup || process.platform === \"win32\" || !this.child.pid) return true;\n // A group left holding only unreaped zombies runs nothing; a bare kill(-pid, 0) says otherwise.\n return !processGroupAlive(this.child.pid);\n }\n\n private fail(code: CodexAppServerError[\"code\"]): void {\n if (this.terminal) return;\n this.terminal = true;\n this.buffer = \"\";\n for (const request of this.pending.values()) {\n clearTimeout(request.timer);\n request.reject(new CodexAppServerError(code));\n }\n this.pending.clear();\n for (const controller of this.callbacks.values()) controller.abort();\n this.callbacks.clear();\n if (this.options.processGroup && process.platform !== \"win32\" && this.child.pid) {\n try {\n process.kill(-this.child.pid, \"SIGKILL\");\n } catch {\n this.child.kill(\"SIGKILL\");\n }\n } else this.child.kill(\"SIGKILL\");\n try {\n this.options.onClose?.(new CodexAppServerError(code));\n } catch {\n // Observer failures cannot interrupt transport cleanup.\n }\n }\n\n private write(frame: unknown): void {\n if (this.terminal) throw new CodexAppServerError(\"closed\");\n const line = `${JSON.stringify(frame)}\\n`;\n if (Buffer.byteLength(line) > this.frameLimit) throw new CodexAppServerError(\"protocol\");\n this.child.stdin.write(line);\n }\n\n private receive(chunk: string): void {\n if (this.terminal) return;\n this.buffer += chunk;\n try {\n for (;;) {\n const end = this.buffer.indexOf(\"\\n\");\n if (end < 0) break;\n const line = this.buffer.slice(0, end);\n this.buffer = this.buffer.slice(end + 1);\n if (Buffer.byteLength(line) > this.frameLimit) throw new CodexAppServerError(\"protocol\");\n if (!line.trim()) continue;\n const frame: unknown = JSON.parse(line);\n if (!record(frame)) throw new CodexAppServerError(\"protocol\");\n if (typeof frame.method === \"string\") {\n if (\"id\" in frame) {\n if (!validId(frame.id)) throw new CodexAppServerError(\"protocol\");\n void this.handleServerRequest(frame.id, frame.method, frame.params);\n } else this.options.onNotification?.(frame.method, frame.params);\n } else {\n if (\n typeof frame.id !== \"number\" ||\n !Number.isSafeInteger(frame.id) ||\n \"error\" in frame === \"result\" in frame\n )\n throw new CodexAppServerError(\"protocol\");\n const request = this.pending.get(frame.id);\n if (!request) throw new CodexAppServerError(\"protocol\");\n clearTimeout(request.timer);\n this.pending.delete(frame.id);\n if (\"error\" in frame) {\n // Pinned 0.153.4 thread_store_resume_read_error maps only missing rollout\n // to this exact invalid-request message. Never retain raw native errors.\n const missing =\n request.resumeThreadId &&\n record(frame.error) &&\n frame.error.code === -32600 &&\n frame.error.message === `no rollout found for thread id ${request.resumeThreadId}`;\n request.reject(\n missing ? new CodexNativeStateUnavailable() : new CodexAppServerError(\"rejected\"),\n );\n } else request.resolve(frame.result);\n }\n if (this.terminal) return;\n }\n if (Buffer.byteLength(this.buffer) > this.frameLimit)\n throw new CodexAppServerError(\"protocol\");\n } catch {\n this.fail(\"protocol\");\n }\n }\n\n private async handleServerRequest(\n id: string | number,\n method: string,\n params: unknown,\n ): Promise<void> {\n if (this.callbacks.has(id) || this.callbacks.size >= this.capacity)\n return this.fail(\"protocol\");\n const controller = new AbortController();\n this.callbacks.set(id, controller);\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const handler = Object.hasOwn(this.options.onServerRequest ?? {}, method)\n ? this.options.onServerRequest?.[method as keyof NativeServerRequests]\n : undefined;\n if (!handler) throw new CodexAppServerError(\"rejected\");\n const result = await Promise.race([\n Promise.resolve().then(() => {\n if (this.terminal || controller.signal.aborted) throw new CodexAppServerError(\"closed\");\n return (handler as (params: unknown, signal: AbortSignal) => Promise<unknown>)(\n params,\n controller.signal,\n );\n }),\n new Promise<never>((_, reject) => {\n controller.signal.addEventListener(\n \"abort\",\n () => reject(new CodexAppServerError(\"closed\")),\n { once: true },\n );\n timer = setTimeout(() => {\n controller.abort();\n reject(new CodexAppServerError(\"timeout\"));\n }, this.callbackTimeout);\n }),\n ]);\n const current = this.options.canReplyToServerRequest?.(method, params) ?? true;\n if (\n !current ||\n this.terminal ||\n controller.signal.aborted ||\n this.callbacks.get(id) !== controller\n )\n throw new CodexAppServerError(\"closed\");\n this.write({ id, result });\n } catch {\n if (!this.terminal) {\n try {\n this.write({ id, error: { code: -32603, message: \"Codex client request failed\" } });\n } catch {\n this.fail(\"protocol\");\n }\n }\n } finally {\n clearTimeout(timer);\n controller.abort();\n this.callbacks.delete(id);\n }\n }\n}\n"]}
|