OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat(scans): support hosted Standard scan execution (#1559)
mluck-openaic9b75c68aac3
diff --git a/plugins/codex-security/scripts/finalize_scan_contract.py b/plugins/codex-security/scripts/finalize_scan_contract.pyindex ae22843c0..f32249e2d 100644--- a/plugins/codex-security/scripts/finalize_scan_contract.py+++ b/plugins/codex-security/scripts/finalize_scan_contract.py@@ -415,7 +415,9 @@ def _require_str(payload: dict[str, Any], key: str, context: str) -> str:return value-def _require_safe_relative_path(value: str, context: str, *, allow_dot: bool = False) -> str:+def _require_safe_relative_path(value: object, context: str, *, allow_dot: bool = False) -> str:+ if not isinstance(value, str) or not value:+ raise ContractError(f"{context}: expected a safe repository-relative POSIX path")try:value.encode("utf-8")except UnicodeEncodeError as exc:@@ -423,8 +425,7 @@ def _require_safe_relative_path(value: str, context: str, *, allow_dot: bool = Fpath = PurePosixPath(value)normalized = path.as_posix()if (- not value.strip()- or (normalized == "." and not allow_dot)+ (normalized == "." and not allow_dot)or (len(value) >= 2 and value[0].isalpha() and value[1] == ":")or "\\" in valueor "\0" in value@@ -438,7 +439,7 @@ def _require_safe_relative_path(value: str, context: str, *, allow_dot: bool = Fdef _require_portable_relative_path(value: str, context: str, *, allow_dot: bool = False) -> str:normalized = _require_safe_relative_path(value, context, allow_dot=allow_dot)- if any(_windows_unsafe_path_component(part) for part in value.split("/")):+ if not value.strip() or any(_windows_unsafe_path_component(part) for part in value.split("/")):raise ContractError(f"{context}: expected a safe scan-relative POSIX path")return normalized@@ -961,7 +962,7 @@ def _stable_id(prefix: str, *parts: str) -> str:def _validate_location(location: dict[str, Any], context: str) -> None:- _require_safe_relative_path(_require_str(location, "path", context), f"{context}.path")+ _require_safe_relative_path(location.get("path"), f"{context}.path")start = location.get("startLine")end = location.get("endLine", start)if not isinstance(start, int) or start < 1:@@ -1593,7 +1594,7 @@ def _validate_finding(finding: dict[str, Any], context: str) -> None:_require_str(evidence, "code", evidence_context)if evidence_key == "codeEvidence":_require_safe_relative_path(- _require_str(evidence, "path", evidence_context),+ evidence.get("path"),f"{evidence_context}.path",)diff --git a/plugins/codex-security/scripts/report_projection.py b/plugins/codex-security/scripts/report_projection.pyindex 8fb0c4f3f..15485408b 100644--- a/plugins/codex-security/scripts/report_projection.py+++ b/plugins/codex-security/scripts/report_projection.py@@ -4,6 +4,7 @@from __future__ import annotationsimport argparse+import jsonimport refrom collections import Counterfrom typing import Any@@ -44,6 +45,20 @@ def _strings(value: Any) -> list[str]:return [text for item in value if (text := _text(item, ""))]+def _path_label(value: str) -> str:+ if "," in value or value != " ".join(value.split()) or any(ord(c) < 32 for c in value):+ return json.dumps(value)+ return value+++def _path_text(value: str) -> str:+ label = _path_label(value)+ if label != value:+ marker = _code_fence(label, minimum=1)+ return f"{marker}{label}{marker}"+ return re.sub(r"([\\`*_\[\]<>])", r"\\\1", value)++def _cell(value: Any) -> str:return _text(value, "none").replace("|", "\\|").replace("\n", "<br>")@@ -386,7 +401,7 @@ def _root_cause_code_evidence(def _code_evidence_location(item: dict[str, Any]) -> str:location = item.get("location")if isinstance(location, str):- return location+ return " ".join(location.split())if isinstance(location, dict):item = locationpath = item.get("path")@@ -394,6 +409,7 @@ def _code_evidence_location(item: dict[str, Any]) -> str:end = item.get("endLine", start)if not isinstance(path, str) or not path:return ""+ path = _path_label(path)if not isinstance(start, int):return pathreturn f"{path}:{start}" if end == start else f"{path}:{start}-{end}"@@ -408,7 +424,7 @@ def _code_evidence_lines(evidence: list[dict[str, Any]]) -> list[str]:lines: list[str] = []for index, item in enumerate(evidence):label = _text(item.get("label"), f"Code evidence {index + 1}")- location = " ".join(_code_evidence_location(item).split())+ location = _code_evidence_location(item)explanation = _text(item.get("explanation"), "")language = item.get("language") if isinstance(item.get("language"), str) else ""language = language if re.fullmatch(r"[A-Za-z0-9_+.-]*", language) else ""@@ -437,7 +453,7 @@ def _locations(finding: dict[str, Any]) -> str:start = location["startLine"]end = location.get("endLine", start)suffix = f":{start}" if end == start else f":{start}-{end}"- rendered.append(f"{location['path']}{suffix}")+ rendered.append(f"{_path_text(location['path'])}{suffix}")return ", ".join(rendered)@@ -541,7 +557,7 @@ def _finding_header(number: int, finding: dict[str, Any]) -> list[str]:f"| Confidence rationale | {_cell(finding['confidence']['rationale'])} |",f"| Category | {_cell(finding['taxonomy']['category'])} |",f"| CWE | {_cell(cwes)} |",- f"| Affected lines | {_cell(_locations(finding))} |",+ "| Affected lines | " + _locations(finding).replace("|", "\\|") + " |",]@@ -615,9 +631,9 @@ def _finding_section(number: int, finding: dict[str, Any]) -> list[str]:validation_code_evidence = _section_code_evidence(finding, validation)dataflow_code_evidence = _section_code_evidence(finding, attack_path, *dataflow_sections)reachability_code_evidence = _section_code_evidence(finding, reachability)- dataflow_summary = _text(- dataflow.get("summary"),- f"The canonical finding records the affected path at {_locations(finding)}, but no expanded source-to-sink narrative was recorded.",+ dataflow_summary = _text(dataflow.get("summary"), "") or (+ f"The canonical finding records the affected path at {_locations(finding)}, "+ "but no expanded source-to-sink narrative was recorded.")reachability_summary = _text(reachability.get("summary"), "") or _text(attack_path.get("summary"),@@ -769,8 +785,12 @@ def build_report_markdown(deep_presentation = uses_deep_presentation(coverage, findings)deep_finding_groups = _deep_finding_groups(findings, writeup_paths) if deep_presentation else []hardening_portfolio_path = _hardening_portfolio_path(scan)- include_paths = _strings(coverage.get("includePaths", scope.get("includePaths", [])))- exclude_paths = _strings(coverage.get("excludePaths", scope.get("excludePaths", [])))+ include_paths = [+ _path_text(path) for path in coverage.get("includePaths", scope.get("includePaths", []))+ ]+ exclude_paths = [+ _path_text(path) for path in coverage.get("excludePaths", scope.get("excludePaths", []))+ ]limitations = _strings(scope.get("limitations"))explicit_exclusions = coverage.get("explicitExclusions", [])lines = [diff --git a/plugins/codex-security/tests/test_finalize_scan_contract.py b/plugins/codex-security/tests/test_finalize_scan_contract.pyindex 063da2933..5eee19329 100644--- a/plugins/codex-security/tests/test_finalize_scan_contract.py+++ b/plugins/codex-security/tests/test_finalize_scan_contract.py@@ -82,7 +82,7 @@ class FinalizeScanContractTest(ScanFixtureTestCase):@skipIf(os.name == "nt", "POSIX source filenames")def test_sarif_hashes_source_names_that_are_not_portable_artifact_names(self) -> None:source_root = self.scan_dir / "source"- for name in ("aux.c", "con.py", "src/a:b.c", "what?.md"):+ for name in ("aux.c", "con.py", "src/a:b.c", "what?.md", " ", "\u00a0"):with self.subTest(name=name):source = source_root / namesource.parent.mkdir(parents=True, exist_ok=True)@@ -2318,6 +2318,43 @@ The extraction root is not enforced.self.read_json("scan-manifest.json")["scan"]["scope"]["includePaths"], ["."])+ def test_preserves_literal_whitespace_repository_paths(self) -> None:+ for path in (" ", " ", "\u00a0"):+ with self.subTest(path=path):+ self.manifest["scan"]["scope"]["includePaths"] = [path]+ self.coverage["includePaths"] = [path]+ self.coverage["deferred"] = [+ {"id": "review", "reason": "Review is incomplete.", "paths": [path]}+ ]+ self.findings["findings"][0]["locations"] = [{"path": path, "startLine": 1}]+ self.findings["findings"][0]["codeEvidence"] = [+ {+ "id": "source",+ "label": "Source",+ "path": path,+ "startLine": 1,+ "code": "source()",+ "explanation": "Repository-relative evidence.",+ }+ ]+ self.write_scan()+ manifest, findings, coverage = FINALIZER.finalize_scan(self.scan_dir)+ self.assertEqual(manifest["scan"]["scope"]["includePaths"], [path])+ self.assertEqual(coverage["includePaths"], [path])+ self.assertEqual(coverage["deferred"][0]["paths"], [path])+ self.assertEqual(findings["findings"][0]["locations"][0]["path"], path)+ self.assertEqual(findings["findings"][0]["codeEvidence"][0]["path"], path)+ if path.isascii():+ self.assertIn(+ f'- Included paths: `"{path}"`',+ (self.scan_dir / "report.md").read_text(encoding="utf-8"),+ )++ def test_rejects_whitespace_only_artifact_paths(self) -> None:+ for path in (" ", " ", "\u00a0"):+ with self.subTest(path=path), self.assertRaises(FINALIZER.ContractError):+ FINALIZER._require_portable_relative_path(path, "artifact")+def test_rejects_missing_coverage_receipt(self) -> None:self.coverage["surfaces"][0]["receiptRefs"] = ["artifacts/02_discovery/work_ledger.jsonl"]self.write_scan()diff --git a/plugins/codex-security/tests/test_report_projection.py b/plugins/codex-security/tests/test_report_projection.pyindex 75333791e..6749ff6ee 100644--- a/plugins/codex-security/tests/test_report_projection.py+++ b/plugins/codex-security/tests/test_report_projection.py@@ -678,7 +678,7 @@ def test_projection_escapes_markdown_link_syntax_in_finding_title() -> None:assert "[Parser ](https://example.com) [boundary](" not in markdown-def test_projection_normalizes_target_and_scope_paths() -> None:+def test_projection_normalizes_target_and_quotes_scope_control_characters() -> None:manifest, findings, coverage = canonical_documents()manifest["scan"]["target"]["displayName"] = "repo\n## Injected target heading"manifest["scan"]["scope"]["includePaths"] = ["src\n## Injected path heading"]@@ -689,7 +689,46 @@ def test_projection_normalizes_target_and_scope_paths() -> None:assert "\n## Injected target heading" not in markdownassert "\n## Injected path heading" not in markdownassert "# Security Review: repo ## Injected target heading" in markdown- assert "- Included paths: src ## Injected path heading" in markdown+ assert '- Included paths: `"src\\n## Injected path heading"`' in markdown+++ ("path", "marker"),+ [+ (" ", "`"),+ (" ", "`"),+ (" service ", "`"),+ ("a,b.ts", "`"),+ ("a b", "`"),+ (" a`b ", "``"),+ ("a``b,c", "```"),+ ],+)+def test_projection_preserves_ambiguous_literal_paths(path: str, marker: str) -> None:+ manifest, findings, coverage = canonical_documents()+ coverage["includePaths"] = [path]+ coverage["excludePaths"] = [path]+ findings["findings"][0]["locations"] = [{"path": path, "startLine": 1}]+ findings["findings"][0]["codeEvidence"] = [+ {"id": "source", "label": "Source", "path": path, "startLine": 1, "code": "source()"}+ ]+ findings["findings"][0]["rootCause"] = {"evidenceRefs": ["source"]}++ markdown = PROJECTION.build_report_markdown(manifest, findings, coverage)++ assert f'- Included paths: {marker}"{path}"{marker}' in markdown+ assert f'- Excluded paths: {marker}"{path}"{marker}' in markdown+ assert f'| Affected lines | {marker}"{path}"{marker}:1 |' in markdown+ assert f'{marker}"{path}":1{marker}' in markdown+++def test_projection_distinguishes_repeated_spaces_from_ordinary_path_spacing() -> None:+ manifest, findings, coverage = canonical_documents()+ coverage["includePaths"] = ["a b", "a b", " ", " "]++ markdown = PROJECTION.build_report_markdown(manifest, findings, coverage)++ assert '- Included paths: `"a b"`, a b, `" "`, `" "`' in markdowndef test_projection_includes_exact_target_identity() -> None:diff --git a/sdk/typescript/TESTING.md b/sdk/typescript/TESTING.mdindex 92ca056f5..ba5051ef8 100644--- a/sdk/typescript/TESTING.md+++ b/sdk/typescript/TESTING.md@@ -34,6 +34,11 @@ For CI's full archive inspection, pass the exact `.tgz` path printed byThese checks include native Node contracts for SDK completion, cancellation,close cleanup, and CLI terminal sanitization. They use the installed package,controlled model output, and the real workbench without live model credentials.+The installed-package checks also verify hosted SDK exports, input validation,+and the `scan --host` protocol without preparing a repository or requiring Git.+The hosted-scan tests cover real repository scans, scope, artifact seals, and+executor receipts. To rerun just the installed-package check, use+`node scripts/smoke-hosted-package.mjs /absolute/path/to/node_modules/@openai/codex-security`.Tests run in random order by default. To replay a failure, pass the seed fromBun's summary to `pnpm run test --seed 12345`.diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex 8827c9147..084fd2dcd 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -1776,3 +1776,7 @@ capabilities, no-new-privileges, and seccomp policy. Hosts that permit nested usnamespaces do not need it. The legacy Landlock fallback is unsupported.See the [Docker guide](https://github.com/openai/codex-security/blob/main/docker/README.md)for deployment and source-build instructions.++### Hosted Standard scan++`codex-security scan --host` runs one versioned JSON-RPC invocation with an explicit host executor. Use it alone; it never performs local inference. See [the hosted scan protocol](hosted-scans.md) for input, filesystem, artifact, usage, and cancellation requirements.diff --git a/sdk/typescript/docs/hosted-scans.md b/sdk/typescript/docs/hosted-scans.mdnew file mode 100644index 000000000..88d02b382--- /dev/null+++ b/sdk/typescript/docs/hosted-scans.md@@ -0,0 +1,242 @@+# Hosted Standard scans (protocol v2)++`codex-security scan --host` runs one scan using newline-delimited JSON-RPC on+stdin/stdout. Use the flag alone. It performs no login, update check, local+inference, or model fallback. Ordinary local scans keep their existing behavior.++## Public executor API++Use the standalone `runHostedScan(input, { executor, signal, onEvent })`+function to run one hosted Standard scan. `CodexSecurity.run()` retains its local+scan behavior; it does not accept a hosted executor. The CLI command is a thin+JSON-RPC adapter around the same standalone function.++The CLI owns scan registration, plugin lifecycle, target checks, finalization,+report generation and sealed artifact validation. The host owns authorization,+frozen checkout, execution, durable run state, replay, reconciliation, usage,+billing and cleanup. It collects authoritative usage before cleanup and persists+accepted output independently from inference. Findings ingestion and+deduplication consume that accepted output separately. CLI workbench state+remains scan-domain state; there is no hosted-attempt replay store.++```ts+import { runHostedScan, type ScanExecutor } from "@openai/codex-security";++const executor: ScanExecutor = {+ async run(request, { signal, onEvent }) {+ // Persist the request identity before dispatch. Mount the matching plugin,+ // checkout, scan state and output directory in the remote executor.+ return await host.executeOnce(request, { signal, onEvent });+ },+};+const result = await runHostedScan(+ {+ version: 2,+ repository: "/workspace/repository",+ revision: "0123456789012345678901234567890123456789",+ scope: { paths: ["services/api", "services/web"] },+ outputDirectory: "/scan/output",+ stateDirectory: "/scan/state",+ model: "gpt-5.6-sol",+ reasoningEffort: "high",+ identity: {+ runId: "run-1",+ attemptId: "attempt-1",+ buildId: "runtime-build",+ },+ },+ {+ executor,+ onEvent(event) {+ console.error(event);+ },+ },+);++// These host methods are application code, outside the CLI.+await host.persistReceipt(result);+if (result.status === "completed") {+ // Check the frozen identity/scope and artifact paths, hashes, sizes and seals.+ await host.verifyAndAcceptArtifacts(result);+} else if (result.status === "acceptance_unknown") {+ // Look up the existing attempt/session; do not call runHostedScan again.+ await host.reconcileExecution(result.identity, result.execution);+}+// Failed and canceled receipts remain recorded but are not accepted+// completed scans. Persistence retries reuse this receipt without more inference.+```++The function creates and closes its scan client internally, reusing the ordinary+Standard scan lifecycle. Omit `scope` for the entire repository, or pass literal+repository-relative folders/files. Model settings come from the frozen input;+local profiles and other local scan options are not accepted.++`ScanExecutor.run` receives an AbortSignal and an optional `onEvent` observer for+`{type: "progress", progress}` or `{type: "activity", activity}` events. Progress+uses the existing `ScanProgress` type; activity uses `ScanActivity`. Observer+failures cannot stop execution. Aborting waits for the executor to settle; the+host must cancel remote work and return its recorded outcome.++Preparation errors throw before execution. Execution and finalization return a+`HostedScanResult` receipt with status `completed`, `failed`,+`canceled`, or `acceptance_unknown`. The receipt retains the executor's outcome, session+identity, usage, message and structured error even if artifact finalization+fails. Only validated artifacts receive hashes and sizes. Repeated invocations+are separate scans; the host decides whether a new invocation is allowed.++Temporary runtime cleanup failures preserve the terminal receipt, including+its execution outcome, session identity, usage, and validated artifacts. They+are reported separately through `onEvent` as a failed message activity with+ID `runtime.cleanup` (a `scan.progress` notification over JSON-RPC). A cleanup+failure does not change the scan status or require another execution attempt.++## Wire contract++Send `{"jsonrpc":"2.0","id":"run","method":"run","params":...}` with the+parameters below. IDs are strings or safe integers from -9007199254740991 through+9007199254740991; send larger numeric identifiers as strings.++```json+{+ "version": 2,+ "repository": "/workspace/repository",+ "revision": "0123456789012345678901234567890123456789",+ "scope": { "paths": ["services/api", "services/web"] },+ "outputDirectory": "/scan/output",+ "stateDirectory": "/scan/state",+ "model": "gpt-5.6-sol",+ "reasoningEffort": "high",+ "identity": {+ "runId": "example-run",+ "attemptId": "example-attempt",+ "buildId": "exact-runtime-build"+ }+}+```++Omit `scope` to scan the entire repository, matching the local CLI default.+`{"paths":["."]}` also means the repository. An explicit empty list is invalid;+root cannot be mixed with narrower paths. Each entry is one literal filename or+directory: `app/[slug]/page.tsx` and `reports/a,b.ts` are not patterns or lists.+Significant whitespace is preserved; `" service "` and `" "` do not select+`"service"` or the repository. An explicit empty string is invalid. Paths use the+ordinary CLI target resolver's filename semantics, with repository-relative+paths required here. They are normalized, deduplicated and sorted without+changing filename characters. Preparation also checks the existing output+contract: scope paths must be valid UTF-8 and cannot contain control characters,+backslashes, or start with a drive prefix such as `C:`. Incompatible filenames+fail before executor dispatch, including on POSIX where those files may exist.+Every selected path must exist and remain inside+the repository at the frozen revision before any execution request. Missing paths fail the whole+request; the CLI never skips them or broadens the scope. Canonical path aliases+are rejected with an actionable correction. Diff, Deep, resume, mock, local+workflow and post-scan execution are unsupported in this hosted Standard API.++The CLI verifies HEAD before path existence, registers the scan with its bundled+workbench, and sends one `execution.run` request. Its JSON-RPC ID equals the+required `params.requestId`. Params contain `version: 2`, normalized+`repository`, `revision`, `scope`, `identity`, registered `scanId`, `prompt`,+`model`, `reasoningEffort`, and `runtime`:++- `pluginRoot` and `pluginVersion`: the matching bundled plugin.+- `stateDirectory` and `outputDirectory`: writable paths outside the repository.+- `environment`: explicit runtime paths and interpreter settings, never host+ inference credentials.++The CLI and executor must share these filesystem paths or explicitly transfer+the same state. This includes:++- The frozen checkout and matching `pluginRoot` tree, including its executable+ helpers, skills, and MCP server.+- The whole `stateDirectory`, including the registered workbench database,+ journals, and scan inputs; a live database file alone is not a consistent copy.+- `outputDirectory`, where the executor records its draft and the CLI later+ writes the validated manifest, findings, coverage, and report.+- The temporary files named by `CODEX_SECURITY_CONFIG_PATH` and, for path scans,+ `CODEX_SECURITY_TARGET_PATHS_FILE` in `runtime.environment`. These are required+ by preflight and scope binding, even though they can live outside the state+ and output directories. The supplied interpreter paths must also resolve.++Keep these paths available throughout the invocation. The CLI removes its+temporary config/scope files when the invocation closes; caller-owned state+and output directories remain available. If remote work may outlive an+`acceptance_unknown` return, the host must preserve the files that work still+needs before returning that outcome. Use shared mounts or a coordinated transfer+that preserves the supplied path bindings, not independent copies of mutable+workbench state.++Run the plugin stdio server from+`pluginRoot/scripts/launch_codex_security_mcp --stdio` with the supplied+environment. The executor needs the target files, plugin skills and registered+artifacts, and must expose `record_codex_security_scan_draft`. CLI workbench+finalization follows the turn. Merely returning model text is insufficient.+Separately provisioned executors must receive the exact frozen runtime/plugin+build and preserve state; do not interpret plugin schemas as strict Structured+Outputs schemas.++The execution response `result` has:++- Required `requestId` matching the execution request, and `status`:+ `completed`, `failed`, `canceled`, or `acceptance_unknown`.+- `sessionId`, required for completed execution and optional for other outcomes.+- Optional `finalResponse`, `message`, and structured `error` with numeric `code`,+ string `message` and optional `data`.+- Optional opaque host `usage`. Absence means unknown, never zero. The host collects+ it for diagnostics; these observations do not replace authoritative accounting.++A transport failure or mismatched receipt is not proof of non-acceptance. The+CLI stops without resubmitting and leaves reconciliation to the host. The terminal+result retains `execution` even when scanning fails or is canceled. The runtime's+`hostProtocolVersion` identifies this protocol as version 2.+A package-exported example is available at+`@openai/codex-security/schemas/hosted-scan-v2.fixture.json`. Its `response` is+the executor's reply; `terminal` is the separate final scan receipt. The example+hashes and sizes are illustrative and do not validate any real files.++| Final scan status | Host handling |+| ---------------------- | ------------------------------------------------------------------------------------------------ |+| `completed` | Verify artifact receipts and seals before accepting output. |+| `failed` or `canceled` | Retain identity, diagnostics and any execution/usage receipt. |+| `acceptance_unknown` | Reconcile the existing remote attempt and collect usage before cleanup; do not resubmit blindly. |++Reconciliation uses the host's durable attempt/session identifiers and provider+status. Preserve state and output for inspection, and cancel or join remote work+before releasing resources it still uses. The hosted API has no replay store,+resume, or finalize-only operation: calling `runHostedScan` again registers a new+scan. A provider reporting execution completion does not substitute for a+validated, sealed scan receipt.++## Progress, cancellation and artifacts++The host sends `execution.progress` notifications with `{requestId, event}`.+The CLI forwards valid progress/activity through `scan.progress` notifications+with `{id: <original run RPC id>, event}`. Invalid optional event payloads are+ignored; mismatched request IDs are rejected. Stdout contains JSON-RPC only.++Send `{"jsonrpc":"2.0","method":"cancel","params":{"id":"run"}}` with the+original run request ID. The CLI aborts its executor signal, emits+`execution.cancel` with `{requestId}`, and waits for the host's outcome/usage+before returning a canceled result. The host must continue reading notifications+while executing. SIGINT/SIGTERM, output errors/closure, and cancellation with+blocked output terminate the transport even while a write callback is stuck.+Input EOF before the terminal response fails the run; EOF while that response is+flushing waits for the write callback. A selected successful result is not a+successful delivery. Hosts own deadlines and independently cancel remote work+and reconcile known execution identities after transport failure.++Preparation failures include typed `error.data.reason` for missing, escaping,+aliased or syntactically invalid paths and revision mismatch. Other failures+must not be presented as missing paths.++The terminal run result includes `version: 2`, `status`, frozen+identity/revision/normalized scope, output directory, scan ID when registered,+plugin version when known, `provenance` (CLI/plugin/build identity), optional `execution`,+and `artifacts`. Each artifact is `{path, sha256, bytes}` over its exact bytes.+Receipts cover canonical outputs, sealed supplemental files, and preserved+source files bound by the manifest. Coverage limitations remain diagnostics in+completed scans; required-output failures return `failed`, and unvalidated files+never receive artifact receipts. `acceptance_unknown`, failed+and canceled results are not accepted completed scans.++The host verifies receipt paths, hashes, sizes, scope, revision and seals before+accepting output.diff --git a/sdk/typescript/package.json b/sdk/typescript/package.jsonindex 738ccd66c..022cf7d67 100644--- a/sdk/typescript/package.json+++ b/sdk/typescript/package.json@@ -28,7 +28,8 @@"import": "./dist/index.js","default": "./dist/index.js"},- "./schemas/project-config.schema.json": "./schemas/project-config.schema.json"+ "./schemas/project-config.schema.json": "./schemas/project-config.schema.json",+ "./schemas/hosted-scan-v2.fixture.json": "./schemas/hosted-scan-v2.fixture.json"},"bin": {"codex-security": "./bin/codex-security.mjs",@@ -43,7 +44,8 @@"README.md","docs/cli.md","docs/findings-service.md",- "docs/dedupe-records.md"+ "docs/dedupe-records.md",+ "docs/hosted-scans.md"],"publishConfig": {"access": "public",diff --git a/sdk/typescript/schemas/hosted-scan-v2.fixture.json b/sdk/typescript/schemas/hosted-scan-v2.fixture.jsonnew file mode 100644index 000000000..9bf196867--- /dev/null+++ b/sdk/typescript/schemas/hosted-scan-v2.fixture.json@@ -0,0 +1,145 @@+{+ "run": {+ "jsonrpc": "2.0",+ "id": "run",+ "method": "run",+ "params": {+ "version": 2,+ "repository": "/workspace/repository",+ "revision": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "scope": {+ "paths": ["service-a", "service-b"]+ },+ "outputDirectory": "/scan/output",+ "stateDirectory": "/scan/state",+ "model": "fixture-model",+ "reasoningEffort": "medium",+ "identity": {+ "runId": "run-1",+ "attemptId": "attempt-1",+ "buildId": "fixture-build"+ }+ }+ },+ "execution": {+ "jsonrpc": "2.0",+ "id": "request-1",+ "method": "execution.run",+ "params": {+ "version": 2,+ "repository": "/workspace/repository",+ "revision": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "scope": {+ "paths": ["service-a", "service-b"]+ },+ "identity": {+ "runId": "run-1",+ "attemptId": "attempt-1",+ "buildId": "fixture-build"+ },+ "model": "fixture-model",+ "reasoningEffort": "medium",+ "requestId": "request-1",+ "scanId": "scan-1",+ "prompt": "Scan the selected paths.",+ "runtime": {+ "pluginRoot": "/opt/runtime/cli/_bundled_plugin",+ "pluginVersion": "0.1.95",+ "stateDirectory": "/scan/state",+ "outputDirectory": "/scan/output",+ "environment": {+ "CODEX_SECURITY_STATE_DIR": "/scan/state",+ "CODEX_SECURITY_CONFIG_PATH": "/scan/tmp/config-preflight.toml",+ "CODEX_SECURITY_TARGET_PATHS_FILE": "/scan/tmp/target-paths.json"+ }+ }+ }+ },+ "progress": {+ "jsonrpc": "2.0",+ "method": "execution.progress",+ "params": {+ "requestId": "request-1",+ "event": {+ "type": "progress",+ "progress": {+ "phase": "discovery",+ "filesCompleted": 1,+ "filesTotal": 2+ }+ }+ }+ },+ "response": {+ "jsonrpc": "2.0",+ "id": "request-1",+ "result": {+ "requestId": "request-1",+ "status": "completed",+ "sessionId": "session-1",+ "usage": {+ "input_tokens": 12,+ "output_tokens": 6,+ "cached_input_tokens": 0+ }+ }+ },+ "terminal": {+ "jsonrpc": "2.0",+ "id": "run",+ "result": {+ "version": 2,+ "repository": "/workspace/repository",+ "revision": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "scope": {+ "paths": ["service-a", "service-b"]+ },+ "identity": {+ "runId": "run-1",+ "attemptId": "attempt-1",+ "buildId": "fixture-build"+ },+ "outputDirectory": "/scan/output",+ "status": "completed",+ "scanId": "scan-1",+ "pluginVersion": "0.1.95",+ "provenance": {+ "cliVersion": "0.2.0",+ "pluginVersion": "0.1.95",+ "buildId": "fixture-build"+ },+ "execution": {+ "requestId": "request-1",+ "status": "completed",+ "sessionId": "session-1",+ "usage": {+ "input_tokens": 12,+ "output_tokens": 6,+ "cached_input_tokens": 0+ }+ },+ "artifacts": [+ {+ "path": "scan-manifest.json",+ "sha256": "1111111111111111111111111111111111111111111111111111111111111111",+ "bytes": 1024+ },+ {+ "path": "findings.json",+ "sha256": "2222222222222222222222222222222222222222222222222222222222222222",+ "bytes": 256+ },+ {+ "path": "coverage.json",+ "sha256": "3333333333333333333333333333333333333333333333333333333333333333",+ "bytes": 512+ },+ {+ "path": "report.md",+ "sha256": "4444444444444444444444444444444444444444444444444444444444444444",+ "bytes": 768+ }+ ]+ }+ }+}diff --git a/sdk/typescript/scripts/build-host-bundle.mjs b/sdk/typescript/scripts/build-host-bundle.mjsnew file mode 100644index 000000000..610ce2bf0--- /dev/null+++ b/sdk/typescript/scripts/build-host-bundle.mjs@@ -0,0 +1,124 @@+// Development bundle: the exact locally built CLI, plugin, Linux dependencies,+// and Node executable. Nothing is published or installed in the scan checkout.+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import {+ cp,+ mkdir,+ mkdtemp,+ readFile,+ readdir,+ rm,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { bundledPluginFiles } from "./build-plugin.mjs";++const packageRoot = resolve(import.meta.dirname, "..");+const output = process.argv[2];+if (!output)+ throw new Error(+ "Usage: node scripts/build-host-bundle.mjs /absolute/output.tar.gz",+ );+if (+ process.platform !== "linux" ||+ process.arch !== "x64" ||+ !process.report.getReport().header.glibcVersionRuntime+)+ throw new Error("Build the hosted bundle on Linux x64 with glibc.");+const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");+const run = (command, args, cwd = packageRoot) =>+ execFileSync(command, args, { cwd, stdio: "inherit" });+const staging = await mkdtemp(join(tmpdir(), "codex-security-host-bundle-"));+try {+ run("pnpm", ["pack", "--pack-destination", staging]);+ const archive = (await readdir(staging)).find((name) =>+ name.endsWith(".tgz"),+ );+ if (!archive) throw new Error("Package build did not create an archive.");+ const bundle = join(staging, "bundle");+ await mkdir(join(bundle, "bin"), { recursive: true });+ await mkdir(join(bundle, "cli"));+ run("tar", [+ "-xzf",+ join(staging, archive),+ "--strip-components=1",+ "-C",+ join(bundle, "cli"),+ ]);+ for (const name of ["pnpm-lock.yaml", "pnpm-workspace.yaml"])+ await cp(join(packageRoot, name), join(bundle, "cli", name));+ run(+ "pnpm",+ [+ "install",+ "--prod",+ "--frozen-lockfile",+ "--ignore-scripts",+ "--store-dir",+ process.env["PNPM_STORE_DIR"] ??+ join(tmpdir(), "codex-security-pnpm-store"),+ ],+ join(bundle, "cli"),+ );+ await cp(process.execPath, join(bundle, "bin", "node"));+ const pluginRoot = join(bundle, "cli", "_bundled_plugin");+ const pluginHash = createHash("sha256");+ for (const path of await bundledPluginFiles(pluginRoot))+ pluginHash.update(+ `${path}\0${sha(await readFile(join(pluginRoot, path)))}\n`,+ );+ const pluginSha256 = pluginHash.digest("hex");+ const packageSha256 = sha(await readFile(join(staging, archive)));+ const nodeSha256 = sha(await readFile(process.execPath));+ const pkg = JSON.parse(+ await readFile(join(bundle, "cli", "package.json"), "utf8"),+ );+ const plugin = JSON.parse(+ await readFile(join(pluginRoot, ".codex-plugin", "plugin.json"), "utf8"),+ );+ const identity = {+ version: 1,+ hostProtocolVersion: 2,+ buildId: sha(`${packageSha256}\0${nodeSha256}\0${pluginSha256}`),+ sourceRevision: execFileSync("git", ["rev-parse", "HEAD"], {+ cwd: packageRoot,+ encoding: "utf8",+ }).trim(),+ cliVersion: pkg.version,+ pluginVersion: plugin.version,+ nodeVersion: process.version.slice(1),+ platform: "linux-x64",+ pluginSha256,+ };+ await writeFile(+ join(bundle, "runtime.json"),+ `${JSON.stringify(identity, null, 2)}\n`,+ );+ await mkdir(dirname(resolve(output)), { recursive: true });+ run("tar", [+ "--hard-dereference",+ "-czf",+ resolve(output),+ "-C",+ bundle,+ "bin",+ "cli",+ "runtime.json",+ ]);+ const digest = sha(await readFile(resolve(output)));+ await writeFile(+ `${resolve(output)}.sha256`,+ `${digest} ${resolve(output)}\n`,+ );+ await writeFile(+ `${resolve(output)}.json`,+ `${JSON.stringify(identity, null, 2)}\n`,+ );+ console.log(+ JSON.stringify({ bundle: resolve(output), sha256: digest, ...identity }),+ );+} finally {+ await rm(staging, { recursive: true, force: true });+}diff --git a/sdk/typescript/scripts/build-plugin.mjs b/sdk/typescript/scripts/build-plugin.mjsindex 10b9331d4..d426e06ba 100644--- a/sdk/typescript/scripts/build-plugin.mjs+++ b/sdk/typescript/scripts/build-plugin.mjs@@ -31,7 +31,7 @@ function validatePath(path) {}}-async function destinationFiles(root, prefix = "") {+export async function bundledPluginFiles(root, prefix = "") {const entries = await readdir(join(root, prefix), {withFileTypes: true,});@@ -39,7 +39,7 @@ async function destinationFiles(root, prefix = "") {for (const entry of entries) {const path = prefix === "" ? entry.name : `${prefix}/${entry.name}`;if (entry.isDirectory()) {- files.push(...(await destinationFiles(root, path)));+ files.push(...(await bundledPluginFiles(root, path)));} else if (entry.isFile()) {files.push(path);} else {@@ -114,7 +114,9 @@ export async function buildBundledPlugin({await chmod(output, mode);}- if (!isDeepStrictEqual(await destinationFiles(staged), [...files].sort())) {+ if (+ !isDeepStrictEqual(await bundledPluginFiles(staged), [...files].sort())+ ) {throw new Error("Bundled plugin generated files outside its contract.");}try {diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjsindex d0a28a973..808c2a0df 100644--- a/sdk/typescript/scripts/check-package.mjs+++ b/sdk/typescript/scripts/check-package.mjs@@ -102,6 +102,8 @@ function validatePackagePaths(entries) {"package/docs/cli.md","package/docs/findings-service.md","package/docs/dedupe-records.md",+ "package/docs/hosted-scans.md",+ "package/schemas/hosted-scan-v2.fixture.json","package/LICENSE","package/bin/codex-security.mjs","package/dist/index.js",diff --git a/sdk/typescript/scripts/fixtures/package-consumer.ts b/sdk/typescript/scripts/fixtures/package-consumer.tsindex c674612af..985170fc7 100644--- a/sdk/typescript/scripts/fixtures/package-consumer.ts+++ b/sdk/typescript/scripts/fixtures/package-consumer.ts@@ -6,6 +6,11 @@ import {classifyScanDirectorySeverity,deduplicateScan,deduplicateRecords,+ runHostedScan,+ type HostedScanInput,+ type HostedScanOptions,+ type HostedScanResult,+ type ScanExecutor,type DeduplicateRecordsInput,type DeduplicateRecordsResult,type DeduplicationReviewRequest,@@ -301,3 +306,24 @@ export async function suggestFindingOwners(identifiers: report.results.map(({ owner }) => ownerIdentifier(owner)),};}++export async function hostedScan(+ input: HostedScanInput,+ executor: ScanExecutor,+ signal: AbortSignal,+): Promise<HostedScanResult> {+ const options: HostedScanOptions = {+ executor,+ signal,+ onEvent(event) {+ event.type satisfies "progress" | "activity";+ },+ };+ return await runHostedScan(input, options);+}++const localOptions: ScanOptions = {+ // @ts-expect-error Hosted execution uses the standalone runHostedScan API.+ hosted: {},+};+void localOptions;diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex a268379b2..c6877b358 100644--- a/sdk/typescript/scripts/package-dist-files.mjs+++ b/sdk/typescript/scripts/package-dist-files.mjs@@ -1,5 +1,9 @@const distModules = ["api",+ "scan-executor",+ "host-protocol",+ "hosted-scan",+ "hosted-scan-protocol","artifact-export","auth","bulk-scan-discovery",diff --git a/sdk/typescript/scripts/smoke-hosted-package.mjs b/sdk/typescript/scripts/smoke-hosted-package.mjsnew file mode 100644index 000000000..e528ae72c--- /dev/null+++ b/sdk/typescript/scripts/smoke-hosted-package.mjs@@ -0,0 +1,46 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { readFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { join, resolve } from "node:path";+import { pathToFileURL } from "node:url";++const packageRoot = resolve(process.argv[2] ?? ".");+const publicSdk = await import(+ pathToFileURL(join(packageRoot, "dist/index.js")).href+);+assert.equal(typeof publicSdk.runHostedScan, "function");+const fixture = JSON.parse(+ await readFile(+ createRequire(join(packageRoot, "package.json")).resolve(+ "@openai/codex-security/schemas/hosted-scan-v2.fixture.json",+ ),+ "utf8",+ ),+);+const input = publicSdk.HostedScanInputSchema.parse(fixture.run.params);+assert.equal(input.version, 2);+await assert.rejects(+ publicSdk.runHostedScan(+ { ...input, scope: { paths: [] } },+ { executor: { run: () => assert.fail("Invalid input must not execute") } },+ ),+ { name: "ZodError" },+);++// Check the packaged entrypoint and protocol without repository preparation.+// Real scans and executor receipts are covered by hosted-scan.test.ts.+const result = spawnSync(+ process.execPath,+ [join(packageRoot, "bin/codex-security.mjs"), "scan", "--host"],+ { input: "invalid JSON\n", encoding: "utf8", windowsHide: true },+);+assert.equal(result.error, undefined);+assert.equal(result.status, 2, result.stderr);+const response = JSON.parse(result.stdout);+assert.equal(response.jsonrpc, "2.0");+assert.equal(response.id, null);+assert.equal(response.error.code, -32700);+console.log(+ "Validated hosted SDK exports, input validation, and CLI protocol.",+);diff --git a/sdk/typescript/scripts/smoke-package.mjs b/sdk/typescript/scripts/smoke-package.mjsindex e46060acf..b6bfe53bb 100644--- a/sdk/typescript/scripts/smoke-package.mjs+++ b/sdk/typescript/scripts/smoke-package.mjs@@ -800,6 +800,11 @@ try {],{ cwd: consumer },);+ run(+ process.execPath,+ [join(packageRoot, "scripts", "smoke-hosted-package.mjs"), installedRoot],+ { cwd: consumer },+ );const selectedPlugin = join(consumer, "compatibility-selected-plugin");await cp(join(installedRoot, "_bundled_plugin"), selectedPlugin, {recursive: true,@@ -840,7 +845,7 @@ try {);console.log(- `Validated installed ${packageManifest.name}@${packageManifest.version}: public import, NodeNext types, CLI, SDK lifecycle, credential locking, ${expectedPluginFiles.length} bundled plugin files, MCP initialization, bundled Codex version, and a nested worker without global codex.`,+ `Validated installed ${packageManifest.name}@${packageManifest.version}: public import, NodeNext types, CLI, SDK lifecycle, credential locking, hosted scans, ${expectedPluginFiles.length} bundled plugin files, MCP initialization, bundled Codex version, and a nested worker without global codex.`,);} finally {await rm(consumer, {diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 8c4cbab58..eeaddaceb 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -2,6 +2,13 @@import { workbenchArgs } from "./workbench-arguments.js";import { isSafeNonNegativeInteger as safeInteger } from "./value.js";+import {+ ScanExecutionError,+ ScanExecutionResultSchema,+ type ScanExecutor,+ type ScanExecutionEvent,+ type ScanExecutionRequest,+} from "./scan-executor.js";import {chmod,lstat,@@ -501,6 +508,7 @@ function patchOutcomeFromResponse(}}export type ScanAuthentication =+ | { method: "host"; verified: false }| { method: "command"; verified: false }| {method: "api_key";@@ -599,6 +607,15 @@ interface CodexSecurityRuntimeOptions {}interface ClientDependencies {+ /** Explicit hosted execution; never falls back to createCodex. */+ hostedScan?: {+ executor: ScanExecutor;+ context: Pick<+ ScanExecutionRequest,+ "repository" | "revision" | "scope" | "identity"+ >;+ onEvent(event: ScanExecutionEvent): void;+ };createCodex(options: CodexOptions & { nativeProfile?: string },): CodexClientLike | Promise<CodexClientLike>;@@ -675,6 +692,11 @@ export class CodexSecurity {repository: string,options: ScanOptions = {},): Promise<ScanResult> {+ // Reject the removed experimental option rather than starting local inference.+ if ("hosted" in options)+ throw new CodexSecurityError(+ "Use runHostedScan with an executor for hosted execution.",+ );return await this.#trackOperation(() =>options.workflowId === undefined? this.#run(repository, { ...options })@@ -1702,6 +1724,16 @@ export class CodexSecurity {...(knowledgeBase?.protectedRoots ?? []),]) {git = await inspectTrustedExecutable("git", git.environment, root);+ if (this.#dependencies.hostedScan !== undefined) {+ // Match the hosted MCP launchers' PATH-based tool lookups.+ for (const command of process.platform === "win32"+ ? ["node"]+ : ["dirname", "node"]) {+ git.environment = (+ await inspectTrustedExecutable(command, git.environment, root)+ ).environment;+ }+ }}checkOpen();const scanOutputRoot =@@ -2722,6 +2754,7 @@ export class CodexSecurity {)(`Could not run post-scan instructions: ${errorMessage(error)}`);}}+ if (this.#dependencies.hostedScan !== undefined) return result;try {const runWorkbench = (args: readonly string[], input?: string) =>workbench(workbenchOptions, args, input);@@ -2946,7 +2979,11 @@ export class CodexSecurity {}}if (this.#closed) this.#requireOpen();- if (signal.aborted && !(failure instanceof ScanInterruptedError)) {+ if (+ signal.aborted &&+ !(failure instanceof ScanInterruptedError) &&+ !(failure instanceof ScanExecutionError)+ ) {throwIfAborted(signal, scanDir);}throw failure;@@ -3179,6 +3216,90 @@ export class CodexSecurity {environment: ProcessEnvironment;codexOptions: CodexOptions & { nativeProfile?: string };}> {+ const hosted = this.#dependencies.hostedScan;+ if (hosted !== undefined) {+ const environment = {+ ...definedEnvironment(+ environmentWithGit(session.runtime.environment, git),+ ),+ ...runtimePaths,+ };+ const model = scanModelConfiguration(session.effectiveConfig);+ return {+ environment,+ // Hosted Standard scans do not launch a local Codex process.+ codexOptions: {},+ codex: {+ startThread: () => {+ let id: string | null = null;+ return {+ get id() {+ return id;+ },+ async runStreamed(prompt, { signal }) {+ const request = {+ version: 2 as const,+ requestId: randomUUID(),+ ...hosted.context,+ scanId: runtimePaths["CODEX_SECURITY_SCAN_ID"]!,+ prompt,+ ...model,+ runtime: {+ pluginRoot: session.runtime.plugin.pluginRoot,+ pluginVersion: session.runtime.plugin.version,+ stateDirectory: runtimePaths["CODEX_SECURITY_STATE_DIR"]!,+ outputDirectory: runtimePaths["CODEX_SECURITY_SCAN_DIR"]!,+ environment,+ },+ };+ // A transport failure is terminal; only the host can reconcile+ // whether remote execution was accepted.+ let result;+ try {+ result = ScanExecutionResultSchema.parse(+ await hosted.executor.run(request, {+ signal: signal ?? new AbortController().signal,+ onEvent: hosted.onEvent,+ }),+ );+ } catch (error) {+ // Transport failure does not prove non-acceptance. Never resubmit.+ throw new ScanExecutionError({+ requestId: request.requestId,+ status: "acceptance_unknown",+ message: errorMessage(error),+ });+ }+ if (result.requestId !== request.requestId)+ throw new ScanExecutionError({+ ...result,+ requestId: request.requestId,+ status: "acceptance_unknown",+ message:+ "Execution response does not match the active request.",+ });+ if (result.status !== "completed")+ throw new ScanExecutionError(result);+ id = result.sessionId!;+ return {+ events: (async function* () {+ yield { type: "thread.started", thread_id: id };+ yield {+ type: "item.completed",+ item: {+ type: "agent_message",+ text: result.finalResponse ?? "",+ },+ };+ yield { type: "turn.completed", usage: result.usage };+ })(),+ };+ },+ };+ },+ },+ };+ }const {runtime,runtimeHome,@@ -3310,6 +3431,59 @@ export class CodexSecurity {temporaryRoot?: string,deepScan = false,): Promise<PreparedSession> {+ if (this.#dependencies.hostedScan !== undefined) {+ // Hosted scans use only the explicitly selected bundle and configuration.+ // No local auth, Codex subprocess, provider profile, or ambient config.+ const environment = this.#dependencies.environment;+ const pluginRoot = await bundledPluginRoot();+ const metadata = await pluginMetadata(pluginRoot);+ const effectiveConfig = {+ // The executor supplies its actual tools and capacity. Local Codex+ // defaults must not masquerade as hosted runtime capabilities.+ approval_policy: "never",+ ...this.config.codexOverrides,+ };+ const preflightConfig = scanPreflightCodexConfig(effectiveConfig);+ const runtimeHome = await createIsolatedHome(temporaryRoot, (path) =>+ requireOutputOutsideRepositories(protectedRoots, path, "runtime"),+ );+ const configPath = join(runtimeHome, "config-preflight.toml");+ const runtime: PreparedRuntime = {+ codexHome: runtimeHome,+ bootstrapWorkspace: runtimeHome,+ configPath,+ credentialsAvailable: false,+ environment: definedEnvironment(environment),+ plugin: {+ ...metadata,+ pluginRoot,+ installedRoot: pluginRoot,+ marketplaceRoot: pluginRoot,+ marketplaceName: "codex-security-sdk",+ },+ };+ this.#runtime = runtime;+ await writeCodexConfig(configPath, preflightConfig);+ const python = await resolvePluginPython({+ environment,+ protectedRoot,+ signal,+ });+ return {+ runtime,+ runtimeHome,+ effectiveConfig,+ preflightConfig,+ sessionConfig: preflightConfig,+ modelProvider: "host",+ externalProvider: null,+ apiKey: null,+ scanEnvironment: environment,+ authentication: { method: "host", verified: false },+ approvalPolicy: "never",+ python,+ };+ }let releaseCredentialHome: (() => Promise<void>) | null = null;const checkOpen = (): void => {this.#requireOpen();diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex afc13c8a4..9ddee0712 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -99,6 +99,7 @@ import { DEFAULT_DEDUPE_CONCURRENCY } from "./deduplication/deduplication.js";import { savedScanWorkbench } from "./saved-scan-bootstrap.js";import { deduplicateScanInternal } from "./deduplication/scan.js";import { runRecordsProtocol } from "./deduplication/records-protocol.js";+import { runHostedScanProtocol } from "./hosted-scan-protocol.js";import {classifyScanSeverityInternal,classifyScanDirectorySeverityInternal,@@ -1717,15 +1718,18 @@ export async function main(dependencies: CliDependencies = DEFAULT_DEPENDENCIES,): Promise<number> {if (- argv[0] === "dedupe" &&- argv.includes("--records") &&+ ((argv[0] === "dedupe" && argv.includes("--records")) ||+ (argv[0] === "scan" &&+ argv.some((arg) => arg === "--host" || arg.startsWith("--host=")))) &&!argv.includes("--help") &&!argv.includes("-h") &&!argv.includes("--schema")) {- if (argv.length !== 2) {+ if (argv.length !== 2 || (argv[0] === "scan" && argv[1] !== "--host")) {errorOutput.write(- "codex-security: --records must be used alone with dedupe.\n",+ argv[0] === "scan"+ ? "codex-security: --host must be used alone with scan.\n"+ : "codex-security: --records must be used alone with dedupe.\n",);return 2;}@@ -1733,11 +1737,9 @@ export async function main(const removeSignals = listenForAbort(dependencies, controller);let exitCode: number;try {- const code = await runRecordsProtocol(- dependencies.recordsInput ?? process.stdin,- output,- controller.signal,- );+ const code = await (+ argv[0] === "scan" ? runHostedScanProtocol : runRecordsProtocol+ )(dependencies.recordsInput ?? process.stdin, output, controller.signal);exitCode =controller.signal.reason === "SIGINT"? 130@@ -3526,6 +3528,12 @@ export async function main(options: z.object({config: PROJECT_CONFIG_OPTION,+ host: z+ .boolean()+ .default(false)+ .describe(+ "Run one hosted Standard scan over JSON-RPC stdin/stdout; use alone.",+ ),workflowId: optionValue("--workflow-id").optional().describe(@@ -3656,6 +3664,8 @@ export async function main(),output: scanOutputSchema("SCAN_FAILED"),async run({ args, error: incurError, format, options }) {+ if (options.host)+ throw new CodexSecurityError("Use scan --host alone.");if (format === "md") {errorOutput.write("codex-security: Markdown output is not supported for scan results.\n",diff --git a/sdk/typescript/src/contract.ts b/sdk/typescript/src/contract.tsindex c8c6b9744..1927fa553 100644--- a/sdk/typescript/src/contract.ts+++ b/sdk/typescript/src/contract.ts@@ -677,7 +677,7 @@ async function verifyScanRoot(function safeRelativePath(value: string, context: string): string {const parts = value.split("/");if (- value.trim().length === 0 ||+ value.length === 0 ||Buffer.from(value, "utf8").toString("utf8") !== value ||value === "." ||value.startsWith("/") ||@@ -705,7 +705,10 @@ function safeRelativePath(value: string, context: string): string {function portableRelativePath(value: string, context: string): string {const normalized = safeRelativePath(value, context);- if (value.split("/").some(isWindowsUnsafePathComponent)) {+ if (+ value.trim().length === 0 ||+ value.split("/").some(isWindowsUnsafePathComponent)+ ) {throw new ContractValidationError(`${context}: expected a safe scan-relative POSIX path.`,);@@ -713,7 +716,7 @@ function portableRelativePath(value: string, context: string): string {return normalized;}-function safeScopePath(value: string): string {+export function safeScopePath(value: string): string {return value === "."? value: safeRelativePath(value, "manifest scope include path");diff --git a/sdk/typescript/src/deduplication/records-protocol.ts b/sdk/typescript/src/deduplication/records-protocol.tsindex a0c6c11e7..746beefa3 100644--- a/sdk/typescript/src/deduplication/records-protocol.ts+++ b/sdk/typescript/src/deduplication/records-protocol.ts@@ -1,181 +1,26 @@-import { createInterface } from "node:readline";-import { type Readable, Writable } from "node:stream";-import { z } from "incur";+import type { Readable } from "node:stream";+import { runHostProtocol } from "../host-protocol.js";import { deduplicateRecords, type DeduplicateRecordsInput } from "./records.js";-const rpcId = z.union([z.string(), z.number().int()]);-const envelope = z.strictObject({ jsonrpc: z.literal("2.0") });-const request = envelope.extend({- id: rpcId,- method: z.literal("run"),- params: z.unknown(),-});-const cancellation = envelope.extend({- method: z.literal("cancel"),- params: z.strictObject({ id: rpcId }),-});-const response = z.union([- envelope.extend({ id: rpcId, result: z.unknown() }),- envelope.extend({- id: rpcId,- error: z.strictObject({- code: z.number().int(),- message: z.string(),- data: z.unknown().optional(),- }),- }),-]);-type Output = Pick<NodeJS.WriteStream, "write"> & {- on?(event: "error", listener: (error: Error) => void): unknown;- off?(event: "error", listener: (error: Error) => void): unknown;-};--/** One bidirectional run. Stdout contains JSON-RPC envelopes only. */export async function runRecordsProtocol(input: Readable,- output: Output,+ output: Parameters<typeof runHostProtocol>[1],signal?: AbortSignal,): Promise<number> {- const controller = new AbortController();- let runId: string | number | undefined;- let finished = false;- let pending:- | { id: string; resolve(value: unknown): void; reject(error: Error): void }- | undefined;- const { promise: completion, resolve: complete } =- Promise.withResolvers<number>();- const lines = createInterface({+ return await runHostProtocol(input,- crlfDelay: Infinity,- terminal: false,- });- const send = async (message: object) => {- const line = `${JSON.stringify(message)}\n`;- if (output instanceof Writable) {- await new Promise<void>((resolve, reject) =>- output.write(line, (error) => (error ? reject(error) : resolve())),- );- } else {- output.write(line);- }- };- const fail = (code: number, message: string, canWrite = true) => {- if (finished) return;- // Stop scheduling before notifying the host; a disconnect cannot become uniqueness.- finished = true;- controller.abort(new Error(message));- pending?.reject(new Error(message));- pending = undefined;- const flushed = canWrite- ? send({ jsonrpc: "2.0", id: runId ?? null, error: { code, message } })- : Promise.resolve();- void flushed.catch(() => undefined).then(() => complete(2));- };- const disconnected = () =>- fail(-32000, "Host disconnected before the run completed.");- const inputError = (error: Error) => fail(-32000, error.message);- const outputError = (error: Error) => fail(-32000, error.message, false);- const canceled = () => {- if (finished) {- // A terminal response may be blocked on a host that stopped reading.- if (output instanceof Writable) output.destroy();- complete(2);- } else {- fail(-32800, "Deduplication canceled.");- }- };- input.on("error", inputError);- input.on("close", disconnected);- if (output instanceof Writable) output.on("close", disconnected);- lines.on("close", disconnected);- lines.on("error", inputError);- output.on?.("error", outputError);- signal?.addEventListener("abort", canceled, { once: true });- lines.on("line", (line) => {- let message: unknown;- try {- message = JSON.parse(line);- } catch {- fail(-32700, "Invalid JSON.");- return;- }- const cancel = cancellation.safeParse(message);- if (cancel.success) {- if (runId === undefined || cancel.data.params.id !== runId)- fail(-32600, "Cancellation does not match the active run.");- else canceled();- return;- }- if (finished) return;- const run = request.safeParse(message);- if (run.success) {- if (runId !== undefined) {- fail(-32600, "Only one run request is allowed.");- return;- }- runId = run.data.id;- void deduplicateRecords(run.data.params as DeduplicateRecordsInput, {- signal: controller.signal,- reviewRunner: {- run(review) {- if (finished) return Promise.reject(controller.signal.reason);- return new Promise((resolve, reject) => {- pending = { id: review.requestId, resolve, reject };- void send({- jsonrpc: "2.0",- id: review.requestId,- method: "review.run",- params: review,- }).catch(outputError);- });+ output,+ {+ label: "Deduplication",+ requestMethod: "review.run",+ run: (params, execute, signal) =>+ deduplicateRecords(params as DeduplicateRecordsInput, {+ signal,+ reviewRunner: {+ run: (request) => execute(request.requestId, request),},- },- }).then(- async (result) => {- if (finished) return;- finished = true;- try {- await send({ jsonrpc: "2.0", id: runId, result });- complete(result.status === "completed" ? 0 : 1);- } catch {- complete(2);- }- },- (error: unknown) => {- fail(- -32602,- error instanceof Error ? error.message : "Invalid run parameters.",- );- },- );- return;- }- const reply = response.safeParse(message);- if (!reply.success || !pending || reply.data.id !== pending.id) {- fail(-32600, "Malformed, unexpected, or mismatched review response.");- return;- }- const review = pending;- pending = undefined;- if ("error" in reply.data)- review.reject(new Error(reply.data.error.message));- else review.resolve(reply.data.result);- });- if (signal?.aborted) canceled();- if (input.readableEnded || input.destroyed) disconnected();- try {- return await completion;- } finally {- lines.removeAllListeners("line");- lines.removeListener("close", disconnected);- lines.removeListener("error", inputError);- lines.close();- input.pause();- input.removeListener("error", inputError);- input.removeListener("close", disconnected);- if (output instanceof Writable)- output.removeListener("close", disconnected);- output.off?.("error", outputError);- signal?.removeEventListener("abort", canceled);- }+ }),+ },+ signal,+ );}diff --git a/sdk/typescript/src/host-protocol.ts b/sdk/typescript/src/host-protocol.tsnew file mode 100644index 000000000..5ec577574--- /dev/null+++ b/sdk/typescript/src/host-protocol.ts@@ -0,0 +1,313 @@+import { createInterface } from "node:readline";+import { type Readable, Writable } from "node:stream";+import { z } from "incur";++const rpcId = z.union([z.string(), z.number().int()]);+const envelope = z.strictObject({ jsonrpc: z.literal("2.0") });+const request = envelope.extend({+ id: rpcId,+ method: z.literal("run"),+ params: z.unknown(),+});+const cancellation = envelope.extend({+ method: z.literal("cancel"),+ params: z.strictObject({ id: rpcId }),+});+const progress = envelope.extend({+ method: z.literal("execution.progress"),+ params: z.strictObject({ requestId: z.string(), event: z.unknown() }),+});+const response = z.union([+ envelope.extend({ id: rpcId, result: z.unknown() }),+ envelope.extend({+ id: rpcId,+ error: z.strictObject({+ code: z.number().int(),+ message: z.string(),+ data: z.unknown().optional(),+ }),+ }),+]);+type Output = Pick<NodeJS.WriteStream, "write"> & {+ on?(event: "error", listener: (error: Error) => void): unknown;+ off?(event: "error", listener: (error: Error) => void): unknown;+};+type Execute = (+ id: string,+ request: unknown,+ onProgress?: (event: unknown) => void,+) => Promise<unknown>;++/** One bidirectional run, shared with dedupe. This transport never replays. */+export async function runHostProtocol(+ input: Readable,+ output: Output,+ operation: {+ label: string;+ requestMethod: string;+ /** Scan cancellation must retain the host's eventual receipt and usage. */+ awaitCancellationReceipt?: boolean;+ errorData?: (error: unknown) => object | undefined;+ run(+ params: unknown,+ execute: Execute,+ signal: AbortSignal,+ onProgress: (event: unknown) => void,+ ): Promise<{ status: string }>;+ },+ signal?: AbortSignal,+): Promise<number> {+ const controller = new AbortController();+ let runId: string | number | undefined;+ let terminalCode: number | undefined;+ let completed = false;+ let pending:+ | {+ id: string;+ resolve(value: unknown): void;+ reject(error: Error): void;+ onProgress?: (event: unknown) => void;+ }+ | undefined;+ const { promise: completion, resolve: resolveCompletion } =+ Promise.withResolvers<number>();+ const complete = (code: number) => {+ if (completed) return;+ completed = true;+ resolveCompletion(code);+ };+ const stopOutput = (code: number) => {+ if (completed) return;+ complete(code);+ if (output instanceof Writable) {+ // Native stdout can emit close repeatedly when destroy() is called from+ // its close listener. Detach before destroying, even before cleanup runs.+ output.off("close", outputClosed);+ output.destroy();+ }+ };+ const lines = createInterface({+ input,+ crlfDelay: Infinity,+ terminal: false,+ });+ const send = async (message: object, onFlushed?: () => void) => {+ const line = `${JSON.stringify(message)}\n`;+ if (output instanceof Writable) {+ if (output.destroyed) throw new Error("Host output is closed.");+ await new Promise<void>((resolve, reject) => {+ let settled = false;+ const settle = (error?: Error | null) => {+ if (settled) return;+ settled = true;+ output.off("close", closed);+ // Node can emit error/close before the rejected Promise is observed.+ // Record the failed write now, so the selected result cannot win.+ if (error) outputError(error);+ else onFlushed?.();+ error ? reject(error) : resolve();+ };+ const closed = () =>+ settle(new Error("Host output closed during write."));+ output.once("close", closed);+ output.write(line, settle);+ });+ } else {+ output.write(line);+ onFlushed?.();+ }+ };+ const fail = (+ code: number,+ message: string,+ canWrite = true,+ data?: object,+ ) => {+ if (completed) return;+ if (terminalCode !== undefined) {+ if (!canWrite) stopOutput(2);+ return;+ }+ terminalCode = 2;+ controller.abort(new Error(message));+ pending?.reject(new Error(message));+ pending = undefined;+ // A peer that stopped reading cannot receive an error. Unblock both the+ // request write and completion instead of waiting for a write callback.+ if (+ !canWrite ||+ (output instanceof Writable &&+ (output.writableLength > 0 || output.writableNeedDrain))+ ) {+ stopOutput(2);+ return;+ }+ void send({+ jsonrpc: "2.0",+ id: runId ?? null,+ error: { code, message, ...(data === undefined ? {} : { data }) },+ })+ .catch(() => undefined)+ .then(() => complete(2));+ };+ const disconnected = () => {+ // Stdin EOF does not close stdout. If a terminal response is already being+ // written, its callback decides whether delivery succeeded.+ if (terminalCode === undefined)+ fail(-32000, "Host disconnected before the run completed.");+ };+ const inputError = (error: Error) => fail(-32000, error.message);+ const outputError = (error: Error) => fail(-32000, error.message, false);+ const outputClosed = () => outputError(new Error("Host output is closed."));+ const interrupted = () => {+ if (terminalCode !== undefined) stopOutput(2);+ else fail(-32800, `${operation.label} canceled.`);+ };+ const canceled = () => {+ if (+ !operation.awaitCancellationReceipt ||+ terminalCode !== undefined ||+ (output instanceof Writable &&+ (output.writableLength > 0 || output.writableNeedDrain))+ ) {+ interrupted();+ return;+ }+ if (controller.signal.aborted) return;+ controller.abort(new Error(`${operation.label} canceled.`));+ if (pending)+ void send({+ jsonrpc: "2.0",+ method: "execution.cancel",+ params: { requestId: pending.id },+ }).catch(outputError);+ };+ input.on("error", inputError);+ input.on("close", disconnected);+ if (output instanceof Writable) output.on("close", outputClosed);+ lines.on("close", disconnected);+ lines.on("error", inputError);+ output.on?.("error", outputError);+ signal?.addEventListener("abort", interrupted, { once: true });+ lines.on("line", (line) => {+ let message: unknown;+ try {+ message = JSON.parse(line);+ } catch {+ fail(-32700, "Invalid JSON.");+ return;+ }+ const cancel = cancellation.safeParse(message);+ if (cancel.success) {+ if (runId === undefined || cancel.data.params.id !== runId)+ fail(-32600, "Cancellation does not match the active run.");+ else canceled();+ return;+ }+ if (terminalCode !== undefined) return;+ const run = request.safeParse(message);+ if (run.success) {+ if (runId !== undefined) {+ fail(-32600, "Only one run request is allowed.");+ return;+ }+ runId = run.data.id;+ void operation+ .run(+ run.data.params,+ (id, params, onProgress) => {+ if (terminalCode !== undefined || controller.signal.aborted)+ return Promise.reject(controller.signal.reason);+ if (pending)+ return Promise.reject(new Error("Execution is already pending."));+ return new Promise((resolve, reject) => {+ pending = { id, resolve, reject, onProgress };+ void send({+ jsonrpc: "2.0",+ id,+ method: operation.requestMethod,+ params,+ }).catch(outputError);+ });+ },+ controller.signal,+ (event) => {+ if (terminalCode === undefined)+ void send({+ jsonrpc: "2.0",+ method: "scan.progress",+ params: { id: runId, event },+ }).catch(outputError);+ },+ )+ .then(+ async (result) => {+ if (terminalCode !== undefined) return;+ const code = result.status === "completed" ? 0 : 1;+ terminalCode = code;+ try {+ await send({ jsonrpc: "2.0", id: runId, result }, () =>+ complete(code),+ );+ } catch {+ complete(2);+ }+ },+ (error: unknown) =>+ fail(+ -32602,+ error instanceof Error+ ? error.message+ : "Invalid run parameters.",+ true,+ operation.errorData?.(error),+ ),+ );+ return;+ }+ const event = progress.safeParse(message);+ if (+ event.success &&+ operation.awaitCancellationReceipt &&+ pending &&+ event.data.params.requestId === pending.id+ ) {+ // Optional progress must never interrupt execution, including bad events+ // or host observer exceptions. Correlation still rejects stale messages.+ try {+ pending.onProgress?.(event.data.params.event);+ } catch {}+ return;+ }+ const reply = response.safeParse(message);+ if (!reply.success || !pending || reply.data.id !== pending.id) {+ fail(+ -32600,+ `Malformed, unexpected, or mismatched ${operation.requestMethod === "review.run" ? "review" : "execution"} response.`,+ );+ return;+ }+ const execution = pending;+ pending = undefined;+ if ("error" in reply.data)+ execution.reject(new Error(reply.data.error.message));+ else execution.resolve(reply.data.result);+ });+ if (signal?.aborted) interrupted();+ if (input.readableEnded || input.destroyed) disconnected();+ try {+ return await completion;+ } finally {+ lines.removeAllListeners("line");+ lines.removeListener("close", disconnected);+ lines.removeListener("error", inputError);+ lines.close();+ input.pause();+ input.removeListener("error", inputError);+ input.removeListener("close", disconnected);+ if (output instanceof Writable)+ output.removeListener("close", outputClosed);+ output.off?.("error", outputError);+ signal?.removeEventListener("abort", interrupted);+ }+}diff --git a/sdk/typescript/src/hosted-scan-protocol.ts b/sdk/typescript/src/hosted-scan-protocol.tsnew file mode 100644index 000000000..1e33361a2--- /dev/null+++ b/sdk/typescript/src/hosted-scan-protocol.ts@@ -0,0 +1,46 @@+import type { Readable } from "node:stream";+import { runHostProtocol } from "./host-protocol.js";+import {+ type HostedScanInput,+ HostedScanPreparationError,+ runHostedScan,+} from "./hosted-scan.js";+import {+ ScanExecutionEventSchema,+ ScanExecutionResultSchema,+} from "./scan-executor.js";++export async function runHostedScanProtocol(+ input: Readable,+ output: Parameters<typeof runHostProtocol>[1],+ signal?: AbortSignal,+): Promise<number> {+ return await runHostProtocol(+ input,+ output,+ {+ label: "Scan",+ requestMethod: "execution.run",+ awaitCancellationReceipt: true,+ errorData: (error) =>+ error instanceof HostedScanPreparationError+ ? { reason: error.reason }+ : undefined,+ run: async (params, execute, signal, onEvent) =>+ await runHostedScan(params as HostedScanInput, {+ signal,+ onEvent,+ executor: {+ run: async (request, options) =>+ ScanExecutionResultSchema.parse(+ await execute(request.requestId, request, (event) => {+ const parsed = ScanExecutionEventSchema.safeParse(event);+ if (parsed.success) options.onEvent?.(parsed.data);+ }),+ ),+ },+ }),+ },+ signal,+ );+}diff --git a/sdk/typescript/src/hosted-scan.ts b/sdk/typescript/src/hosted-scan.tsnew file mode 100644index 000000000..e14966a53--- /dev/null+++ b/sdk/typescript/src/hosted-scan.ts@@ -0,0 +1,335 @@+import { createHash } from "node:crypto";+import { isDeepStrictEqual } from "node:util";+import { readScanFile, safeScopePath } from "./contract.js";+import { isRecord } from "./record.js";+import { VERSION } from "./version.js";+import {+ ScanExecutionError,+ type ScanExecutor,+ type ScanExecutionResult,+ type ScanExecutionEvent,+ type ScanExecutionRequest,+} from "./scan-executor.js";+export type { ScanExecutor, ScanExecutionRequest } from "./scan-executor.js";+import { realpath } from "node:fs/promises";+import { isAbsolute, relative, resolve, sep } from "node:path";+import { z } from "zod";+import { CodexSecurity } from "./api.js";+import { ScanInterruptedError, errorMessage } from "./errors.js";+import { normalizeRepository, repositoryRevision } from "./targets.js";+import { isWithin } from "./trusted-executable.js";++/** Hosted v2 mirrors repository/paths targets; only Standard scans are supported. */+export const HostedScanInputSchema = z.strictObject({+ version: z.literal(2),+ repository: z.string().min(1),+ revision: z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),+ scope: z+ .strictObject({ paths: z.array(z.string().min(1)).min(1) })+ .optional(),+ outputDirectory: z.string().min(1),+ stateDirectory: z.string().min(1),+ model: z.string().min(1),+ reasoningEffort: z.enum(["low", "medium", "high", "xhigh"]),+ identity: z.strictObject({+ runId: z.string().min(1),+ attemptId: z.string().min(1),+ buildId: z.string().min(1),+ }),+});++export type HostedScanInput = z.infer<typeof HostedScanInputSchema>;+export class HostedScanPreparationError extends Error {+ constructor(+ readonly reason:+ | "scope_syntax"+ | "scope_missing"+ | "scope_outside_repository"+ | "scope_alias"+ | "revision_mismatch",+ message: string,+ ) {+ super(message);+ this.name = "HostedScanPreparationError";+ }+}++export function normalizeHostedScope(path: string): string {+ const parts = path.split(process.platform === "win32" ? /[/\\]/ : "/");+ if (+ path.length === 0 ||+ path.includes("\0") ||+ isAbsolute(path) ||+ (process.platform === "win32" && /^[a-z]:/i.test(path)) ||+ parts.includes("..")+ ) {+ throw new HostedScanPreparationError(+ "scope_syntax",+ "Use non-empty repository-relative folders or files without parent traversal or NUL characters.",+ );+ }+ const normalized = parts+ .filter((part) => part !== "" && part !== ".")+ .join("/");+ try {+ return safeScopePath(normalized || ".");+ } catch {+ throw new HostedScanPreparationError(+ "scope_syntax",+ `${JSON.stringify(path)} cannot be used as scan scope: the output contract requires UTF-8 repository-relative paths without drive prefixes, backslashes, or control characters.`,+ );+ }+}++function comparePaths(left: string, right: string): number {+ return Buffer.compare(Buffer.from(left), Buffer.from(right));+}++export function normalizeHostedPaths(+ paths: readonly string[] = ["."],+): string[] {+ if (paths.length === 0)+ throw new HostedScanPreparationError(+ "scope_syntax",+ "An explicit path scope must not be empty. Omit scope to scan the repository.",+ );+ const normalized = [...new Set(paths.map(normalizeHostedScope))].sort(+ comparePaths,+ );+ if (normalized.length > 1 && normalized.includes("."))+ throw new HostedScanPreparationError(+ "scope_syntax",+ "Repository scope cannot be mixed with narrower paths.",+ );+ return normalized;+}++/** Validate every path at the frozen commit before registering a scan/executing. */+async function prepareHostedScan(input: HostedScanInput, signal?: AbortSignal) {+ const scope = { paths: normalizeHostedPaths(input.scope?.paths) };+ const repository = await normalizeRepository(input.repository);+ if ((await repositoryRevision(repository, signal)) !== input.revision)+ throw new HostedScanPreparationError(+ "revision_mismatch",+ "Checkout does not match the frozen revision.",+ );+ for (const path of scope.paths) {+ const selected = resolve(repository, path);+ let target: string;+ try {+ target = await realpath(selected);+ } catch (error) {+ if (+ !(error instanceof Error) ||+ !("code" in error) ||+ error.code !== "ENOENT"+ )+ throw error;+ throw new HostedScanPreparationError(+ "scope_missing",+ `${path} does not exist at the selected revision. Update the paths and start a new scan.`,+ );+ }+ if (!isWithin(repository, target))+ throw new HostedScanPreparationError(+ "scope_outside_repository",+ `${path} resolves outside the repository.`,+ );+ if (target !== selected) {+ const canonical =+ relative(repository, target).split(sep).join("/") || ".";+ throw new HostedScanPreparationError(+ "scope_alias",+ `${path} resolves to ${canonical}. Use the canonical repository path and start a new scan.`,+ );+ }+ }+ return {+ repository,+ revision: input.revision,+ scope,+ identity: input.identity,+ };+}++function hostedScanEnvironment(stateDirectory: string): Record<string, string> {+ const environment: Record<string, string> = {+ PATH: process.env["PATH"] ?? "",+ CODEX_SECURITY_STATE_DIR: resolve(stateDirectory),+ };+ for (const key of [+ "SYSTEMROOT",+ "WINDIR",+ "PATHEXT",+ "TMPDIR",+ "TEMP",+ "TMP",+ ])+ if (process.env[key] !== undefined) environment[key] = process.env[key]!;+ return environment;+}++export interface HostedScanOptions {+ executor: ScanExecutor;+ signal?: AbortSignal;+ onEvent?: (event: ScanExecutionEvent) => void;+}++/** One invocation, with only scan-domain state. The host decides retry/reconciliation. */+export async function runHostedScan(+ value: HostedScanInput,+ options: HostedScanOptions,+) {+ const input = HostedScanInputSchema.parse(value);+ const context = await prepareHostedScan(input, options.signal);+ let execution: ScanExecutionResult | undefined;+ let request: ScanExecutionRequest | undefined;+ let scanId: string | undefined;+ const onEvent = (event: ScanExecutionEvent): void => {+ void Promise.resolve()+ .then(() => options.onEvent?.(event))+ .catch(() => {});+ };+ const client = new CodexSecurity(+ {+ codexOverrides: {+ model: input.model,+ model_reasoning_effort: input.reasoningEffort,+ },+ },+ {+ environment: hostedScanEnvironment(input.stateDirectory),+ hostedScan: {+ context,+ executor: {+ async run(value, runOptions) {+ request = value;+ execution = await options.executor.run(value, runOptions);+ return execution;+ },+ },+ onEvent,+ },+ createCodex() {+ throw new Error("Local inference is unavailable in hosted mode.");+ },+ },+ { surface: "sdk" },+ );+ let outputDirectory = resolve(input.outputDirectory);+ const base = () => ({+ version: 2 as const,+ ...context,+ outputDirectory,+ ...(scanId === undefined ? {} : { scanId }),+ ...(request === undefined+ ? {}+ : {+ pluginVersion: request.runtime.pluginVersion,+ }),+ provenance: {+ cliVersion: VERSION,+ buildId: input.identity.buildId,+ ...(request === undefined+ ? {}+ : { pluginVersion: request.runtime.pluginVersion }),+ },+ ...(execution === undefined ? {} : { execution }),+ });+ try {+ const result = await client.run(context.repository, {+ target:+ context.scope.paths[0] === "."+ ? "repository"+ : context.scope.paths.map((path) => `./${path}`),+ mode: "standard",+ outputDir: outputDirectory,+ signal: options.signal,+ onOutputDirReady(path) {+ outputDirectory = path;+ },+ onScanRegistered(scan) {+ scanId = scan.scanId;+ outputDirectory = scan.scanDir;+ },+ onProgress(progress) {+ onEvent({ type: "progress", progress });+ },+ onActivity(activity) {+ onEvent({ type: "activity", activity });+ },+ });+ if (+ result.manifest.scan.target.revision !== context.revision ||+ (await repositoryRevision(context.repository, options.signal)) !==+ context.revision+ )+ throw new Error(+ "Checkout changed from the frozen revision during execution.",+ );+ if (+ !isDeepStrictEqual(+ [...result.manifest.scan.scope.includePaths].sort(comparePaths),+ context.scope.paths,+ ) ||+ result.manifest.scan.scope.excludePaths.length !== 0+ )+ throw new Error("Completed artifacts do not match the requested scope.");+ const sources = result.manifest.scan["preservedSources"];+ const names = new Set([+ "scan-manifest.json",+ "findings.json",+ "coverage.json",+ "report.md",+ ...result.manifest.scan.artifacts.map((artifact) => artifact.path),+ ...(isRecord(sources) ? Object.keys(sources) : []),+ ]);+ const artifacts = await Promise.all(+ [...names].sort().map(async (path) => {+ const contents = await readScanFile(outputDirectory, path, path);+ return {+ path,+ sha256: createHash("sha256").update(contents).digest("hex"),+ bytes: Buffer.byteLength(contents),+ };+ }),+ );+ return {+ ...base(),+ status: "completed" as const,+ artifacts,+ };+ } catch (error) {+ if (error instanceof ScanExecutionError) execution = error.result;+ return {+ ...base(),+ status:+ execution?.status === "acceptance_unknown"+ ? ("acceptance_unknown" as const)+ : options.signal?.aborted ||+ execution?.status === "canceled" ||+ error instanceof ScanInterruptedError+ ? ("canceled" as const)+ : ("failed" as const),+ error: errorMessage(error),+ artifacts: [],+ };+ } finally {+ try {+ await client.close();+ } catch (error) {+ onEvent({+ type: "activity",+ activity: {+ id: "runtime.cleanup",+ kind: "message",+ status: "failed",+ description: `Hosted scan cleanup failed: ${errorMessage(error)}`,+ paths: [],+ },+ });+ }+ }+}++export type HostedScanResult = Awaited<ReturnType<typeof runHostedScan>>;diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex 253402aee..81fcc5200 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -4,6 +4,22 @@ export type {ArtifactExportResult,} from "./artifact-export.js";export { CodexSecurity, createSecurity } from "./api.js";+export {+ runHostedScan,+ HostedScanInputSchema,+ HostedScanPreparationError,+} from "./hosted-scan.js";+export type {+ HostedScanInput,+ HostedScanOptions,+ HostedScanResult,+} from "./hosted-scan.js";+export type {+ ScanExecutor,+ ScanExecutionRequest,+ ScanExecutionResult,+ ScanExecutionEvent,+} from "./scan-executor.js";export { loadProjectConfig, resolveProjectConfig } from "./project-config.js";export type {ResolvedProjectConfig,diff --git a/sdk/typescript/src/scan-executor.ts b/sdk/typescript/src/scan-executor.tsnew file mode 100644index 000000000..e9b25aa36--- /dev/null+++ b/sdk/typescript/src/scan-executor.ts@@ -0,0 +1,109 @@+import { z } from "zod";+import { CodexSecurityError } from "./errors.js";+import type { ScanActivity } from "./scan-activity.js";+import type { ScanProgress } from "./worker-progress.js";++/** One Standard scan. The host owns execution, persistence and reconciliation. */+export interface ScanExecutionRequest {+ version: 2;+ requestId: string;+ scanId: string;+ repository: string;+ revision: string;+ scope: { paths: string[] };+ identity: { runId: string; attemptId: string; buildId: string };+ prompt: string;+ model: string;+ reasoningEffort: string;+ runtime: {+ pluginRoot: string;+ pluginVersion: string;+ stateDirectory: string;+ outputDirectory: string;+ /** Runtime context only. Credentials belong to the host executor. */+ environment: Record<string, string>;+ };+}++export const ScanExecutionResultSchema = z+ .strictObject({+ requestId: z.string().min(1),+ status: z.enum(["completed", "failed", "canceled", "acceptance_unknown"]),+ sessionId: z.string().min(1).optional(),+ finalResponse: z.string().optional(),+ /** Host usage is opaque; absence means unknown, not zero. */+ usage: z.unknown().optional(),+ message: z.string().optional(),+ error: z+ .strictObject({+ code: z.number().int(),+ message: z.string(),+ data: z.unknown().optional(),+ })+ .optional(),+ })+ .refine(+ (value) => value.status !== "completed" || value.sessionId !== undefined,+ {+ message: "Completed execution requires a sessionId.",+ },+ );+export type ScanExecutionResult = z.infer<typeof ScanExecutionResultSchema>;+export type ScanExecutionEvent =+ | { type: "progress"; progress: ScanProgress }+ | { type: "activity"; activity: ScanActivity };++export const ScanExecutionEventSchema = z.discriminatedUnion("type", [+ z.strictObject({+ type: z.literal("progress"),+ progress: z.strictObject({+ phase: z.enum([+ "preflight",+ "threat_model",+ "discovery",+ "validation",+ "attack_path",+ "reporting",+ ]),+ filesCompleted: z.number().int().nonnegative(),+ filesTotal: z.number().int().nonnegative(),+ }),+ }),+ z.strictObject({+ type: z.literal("activity"),+ activity: z.strictObject({+ id: z.string(),+ kind: z.enum(["command", "tool", "reasoning", "message"]),+ status: z.enum(["running", "completed", "failed"]),+ description: z.string(),+ paths: z.array(z.string()),+ worker: z.number().int().optional(),+ }),+ }),+]);++export interface ScanExecutor {+ /** Submit once. On abort, settle with the host's recorded outcome and usage. */+ run(+ request: ScanExecutionRequest,+ options: {+ signal: AbortSignal;+ onEvent?: (event: ScanExecutionEvent) => void;+ },+ ): Promise<ScanExecutionResult>;+}++/** Carries the exact execution outcome even when finalization cannot complete. */+export class ScanExecutionError extends CodexSecurityError {+ constructor(+ public readonly result: ScanExecutionResult,+ message?: string,+ ) {+ super(+ message ??+ result.message ??+ result.error?.message ??+ `Hosted execution ${result.status}.`,+ );+ }+}diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 2ba1cdc92..41399e3b5 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -4185,7 +4185,25 @@ describe("CodexSecurity orchestration", () => {{},{ parent: "thread-1" },);- await observed.promise;+ // The fake stream has no executor transport to keep the+ // event loop alive while the tracker polls its new worker.+ const timeout = setTimeout(+ () =>+ observed.reject(+ new Error(+ "Timed out waiting for worker observation.",+ ),+ ),+ Number(+ process.env["CODEX_SECURITY_TEST_TIMEOUT_MS"] ??+ "30000",+ ),+ );+ try {+ await observed.promise;+ } finally {+ clearTimeout(timeout);+ }}}}@@ -4209,6 +4227,7 @@ describe("CodexSecurity orchestration", () => {expect(workers).toEqual([{ kind: "observed", worker: 1 }]);expect(errors).toEqual(failure === "none" ? [] : ["onWorkerEvent"]);} finally {+ observed.resolve();await client.close();}},diff --git a/sdk/typescript/tests-ts/contract.test.ts b/sdk/typescript/tests-ts/contract.test.tsindex 5b712ab1e..3c7592224 100644--- a/sdk/typescript/tests-ts/contract.test.ts+++ b/sdk/typescript/tests-ts/contract.test.ts@@ -789,6 +789,8 @@ describe("canonical scan contract", () => {"artifacts/report.json.","artifacts/report.json ","artifacts/CON.txt",+ " ",+ "\u00a0",]) {const scanDir = await copyExample();const path = join(scanDir, "scan-manifest.json");@@ -858,6 +860,31 @@ describe("canonical scan contract", () => {).resolves.toBeDefined();});+ test.each([" ", " ", "\u00a0"])(+ "preserves literal whitespace repository path %j in the contract",+ async (path) => {+ const scanDir = await copyExample();+ const manifestPath = join(scanDir, "scan-manifest.json");+ const findingsPath = join(scanDir, "findings.json");+ const coveragePath = join(scanDir, "coverage.json");+ const manifest = await readJson(manifestPath);+ const findings = await readJson(findingsPath);+ const coverage = await readJson(coveragePath);+ manifest["scan"]["scope"]["includePaths"] = [path];+ coverage["includePaths"] = [path];+ findings["findings"][0]["locations"][0]["path"] = path;+ await writeJson(manifestPath, manifest);+ await writeJson(findingsPath, findings);+ await writeJson(coveragePath, coverage);+ await reseal(scanDir);++ const contract = await loadContract(scanDir, { pluginRoot: PLUGIN_ROOT });+ expect(contract.manifest.scan.scope.includePaths).toEqual([path]);+ expect(contract.coverage.includePaths).toEqual([path]);+ expect(contract.findings.findings[0]!.locations[0]!.path).toBe(path);+ },+ );+test.each([-1, 0])("agrees with Python on a finding end-line offset of %i",async (offset) => {diff --git a/sdk/typescript/tests-ts/fixtures/host-protocol-node.ts b/sdk/typescript/tests-ts/fixtures/host-protocol-node.tsnew file mode 100644index 000000000..5de0035f7--- /dev/null+++ b/sdk/typescript/tests-ts/fixtures/host-protocol-node.ts@@ -0,0 +1,59 @@+import { Writable } from "node:stream";+import { main } from "../../src/cli.js";+import { runHostProtocol } from "../../src/host-protocol.js";++const scenario = process.argv[2];+if (scenario === "cli") {+ await main(process.argv.slice(3));+} else {+ const output =+ scenario === "failed-terminal"+ ? new Writable({+ write(_chunk, _encoding, callback) {+ const fail = () =>+ callback(new Error("Synthetic terminal write failure"));+ if (process.argv[4] === "async") queueMicrotask(fail);+ else fail();+ },+ })+ : scenario === "close-after-flush"+ ? new Writable({+ write(_chunk, _encoding, callback) {+ this.end();+ callback();+ },+ })+ : scenario === "eof-before-flush"+ ? new Writable({+ write(_chunk, _encoding, callback) {+ process.stderr.write("writing\n");+ process.stdin.once("end", () => {+ queueMicrotask(() => callback());+ });+ },+ })+ : process.stdout;+ // Windows stdout pipes write synchronously. Hold a native queued write+ // without blocking the event loop that must receive cancellation.+ if (scenario === "queued-execution") output.cork();+ const code = await runHostProtocol(process.stdin, output, {+ label: "Scan",+ requestMethod: "execution.run",+ awaitCancellationReceipt: true,+ async run(_params, execute) {+ if (scenario === "queued-execution") {+ const execution = execute("request-1", {+ payload: "synthetic request",+ });+ process.stderr.write(+ JSON.stringify({ queued: output.writableLength > 0 }) + "\n",+ );+ await execution;+ }+ return { status: process.argv[3] ?? "completed" };+ },+ });+ process.stderr.write(JSON.stringify({ code }) + "\n");+ // Match the CLI: native stdout can remain open after destroy().+ process.exit(code);+}diff --git a/sdk/typescript/tests-ts/host-protocol-node.test.ts b/sdk/typescript/tests-ts/host-protocol-node.test.tsnew file mode 100644index 000000000..4dc4b8b2d--- /dev/null+++ b/sdk/typescript/tests-ts/host-protocol-node.test.ts@@ -0,0 +1,143 @@+import { afterAll, beforeAll, expect, test } from "bun:test";+import { spawn } from "node:child_process";+import { once } from "node:events";+import { mkdtemp, rm } from "node:fs/promises";+import { join } from "node:path";+import { createInterface } from "node:readline";+import { pathToFileURL } from "node:url";+import { nodeCommand } from "./support/shell.js";++let directory: string;+let fixture: string;+const node = nodeCommand().command;++beforeAll(async () => {+ // Resolve external dependencies from the SDK, as the installed CLI does.+ directory = await mkdtemp(join(import.meta.dirname, "..", ".host-pipes-"));+ const built = await Bun.build({+ entrypoints: [+ join(import.meta.dirname, "fixtures", "host-protocol-node.ts"),+ ],+ outdir: directory,+ target: "node",+ packages: "external",+ });+ expect(built.success).toBe(true);+ fixture = built.outputs[0]!.path;+});++afterAll(async () => {+ if (directory) await rm(directory, { recursive: true, force: true });+});++function launch(...args: string[]) {+ const child = spawn(+ node,+ [+ "--input-type=module",+ "--eval",+ `await import(${JSON.stringify(pathToFileURL(fixture).href)})`,+ "synthetic-launcher",+ ...args,+ ],+ {+ stdio: ["pipe", "pipe", "pipe"],+ windowsHide: true,+ timeout: 10_000,+ killSignal: "SIGKILL",+ },+ );+ const exited = once(child, "exit");+ const messages = createInterface({ input: child.stderr });+ const lines = messages[Symbol.asyncIterator]();+ child.stdin.on("error", () => {});+ return {+ child,+ exited,+ lines,+ send(value: unknown) {+ child.stdin.write(JSON.stringify(value) + "\n");+ },+ async [Symbol.asyncDispose]() {+ child.kill("SIGKILL");+ child.stdin.destroy();+ child.stdout.destroy();+ messages.close();+ child.stderr.destroy();+ await exited;+ },+ };+}++const run = { jsonrpc: "2.0", id: "run-1", method: "run", params: {} };++test.each([+ ["completed", "sync"],+ ["completed", "async"],+ ["incomplete", "sync"],+ ["incomplete", "async"],+] as const)(+ "Node terminal write failure overrides a %s result (%s callback)",+ async (status, callback) => {+ await using host = launch("failed-terminal", status, callback);+ host.send(run);+ expect(await host.exited).toEqual([2, null]);+ },+);++test("Node input EOF waits for the selected terminal response to flush", async () => {+ await using host = launch("eof-before-flush");+ host.send(run);+ expect(await host.lines.next()).toEqual({ value: "writing", done: false });+ host.child.stdin.end();+ expect(await host.lines.next()).toEqual({+ value: '{"code":0}',+ done: false,+ });+ expect(await host.exited).toEqual([0, null]);+});++test("Node output close after a successful terminal flush preserves success", async () => {+ await using host = launch("close-after-flush");+ host.send(run);+ expect(await host.exited).toEqual([0, null]);+});++test.each(["cancel", "disconnect"])(+ "Node queued stdout execution write terminates on %s without recursive teardown",+ async (action) => {+ await using host = launch("queued-execution");+ host.send(run);+ expect(await host.lines.next()).toEqual({+ value: '{"queued":true}',+ done: false,+ });+ if (action === "cancel")+ host.send({+ jsonrpc: "2.0",+ method: "cancel",+ params: { id: "run-1" },+ });+ else host.child.stdin.end();+ expect(await host.exited).toEqual([2, null]);+ },+);++test.each([+ [+ "dedupe",+ "--records",+ { version: 1, observations: [], candidateRelationships: [] },+ ],+ ["scan", "--host", {}],+] as const)(+ "Node CLI %s %s exits with a transport failure when its reader closes",+ async (command, flag, params) => {+ await using host = launch("cli", command, flag);+ const closed = once(host.child.stdout, "close");+ host.child.stdout.destroy();+ await closed;+ host.send({ ...run, params });+ expect(await host.exited).toEqual([2, null]);+ },+);diff --git a/sdk/typescript/tests-ts/hosted-scan.test.ts b/sdk/typescript/tests-ts/hosted-scan.test.tsnew file mode 100644index 000000000..2a687e477--- /dev/null+++ b/sdk/typescript/tests-ts/hosted-scan.test.ts@@ -0,0 +1,1113 @@+import { execFileSync, spawn } from "node:child_process";+import { createInterface } from "node:readline";+import { createHash } from "node:crypto";+import { PassThrough, Writable } from "node:stream";+import { readFile, realpath, stat, symlink } from "node:fs/promises";+import { tmpdir } from "node:os";+import { delimiter, dirname, isAbsolute, join } from "node:path";+import { afterEach, expect, mock, spyOn, test } from "bun:test";+import {+ normalizeHostedScope,+ normalizeHostedPaths,+ HostedScanInputSchema,+ type HostedScanInput,+ type ScanExecutionRequest,+} from "../src/hosted-scan.js";+import { runHostedScanProtocol } from "../src/hosted-scan-protocol.js";+import { runHostProtocol } from "../src/host-protocol.js";+import { CodexSecurity, runHostedScan } from "../src/index.js";+import * as config from "../src/config.js";+import * as hostedScan from "../src/hosted-scan.js";+import {+ ScanExecutionResultSchema,+ type ScanExecutionEvent,+ type ScanExecutionResult,+ type ScanExecutor,+} from "../src/scan-executor.js";+import { main } from "../src/cli.js";+import { capture, dependencies } from "./cli-fixtures.js";+import { normalizeTarget } from "../src/targets.js";+import { runWorkbench } from "../src/runtime.js";+import { pythonExecutable } from "./support/python.js";+import { git } from "./git-fixture.js";+import { PLUGIN_ROOT } from "./plugin-root.js";+import {+ createApiTestFixtures,+ removeTemporaryDirectory,+} from "./support/temporary-directories.js";+import { parseJsonLines, readJson, writeJson } from "./support/json.js";+import { rejecting } from "./support/errors.js";+import { writeSource } from "./support/shell.js";++const { cleanup, temporaryDirectory } = createApiTestFixtures("hosted-scan-");+afterEach(cleanup);++async function fixture(+ additionalFiles: readonly string[] = [],+): Promise<HostedScanInput> {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ for (const name of [+ "service-a/index.ts",+ "service-b/index.ts",+ "service-c/index.ts",+ ...additionalFiles,+ ])+ writeSource(repository, name, "export const value = 1;\n");+ git(repository, "init", "-q");+ git(repository, "add", ".");+ git(repository, "commit", "-qm", "fixture");+ return {+ version: 2,+ repository,+ revision: git(repository, "rev-parse", "HEAD"),+ scope: { paths: ["service-a"] },+ outputDirectory: join(root, "run", "attempt", "output"),+ stateDirectory: join(root, "run", "attempt", "state"),+ model: "gpt-5.6-sol",+ reasoningEffort: "high",+ identity: {+ runId: "run-1",+ attemptId: "attempt-1",+ buildId: "fixture-build",+ },+ };+}++async function writeDraft(request: ScanExecutionRequest) {+ const directory = request.runtime.outputDirectory;+ const documents = {+ "scan-manifest.json": {+ scan: {+ target: { kind: "git_revision" },+ scope: {+ summary: "Synthetic scope fixture",+ runtimeStatus: "not_run",+ limitations: [],+ },+ },+ },+ "findings.json": { findings: [] },+ "coverage.json": {+ inventoryStrategy:+ request.scope.paths[0] === "." ? "repository" : "scoped_path",+ surfaces: [+ {+ id: "fixture",+ label: "Synthetic scope fixture",+ disposition: "no_issue_found",+ receiptRefs: [],+ notes: "Synthetic test only.",+ },+ ],+ explicitExclusions: [],+ deferred: [],+ },+ };+ for (const [name, document] of Object.entries(documents))+ await writeJson(join(directory, name), document);+}++function receipt(+ request: Pick<ScanExecutionRequest, "requestId">,+ overrides: Partial<ScanExecutionResult> = {},+): ScanExecutionResult {+ return {+ requestId: request.requestId,+ status: "completed",+ sessionId: "host-session",+ ...overrides,+ };+}++function draftExecutor(+ afterDraft?: (+ ...args: Parameters<ScanExecutor["run"]>+ ) => void | Promise<void>,+) {+ return {+ run: mock<ScanExecutor["run"]>(async (request, options) => {+ await writeDraft(request);+ await afterDraft?.(request, options);+ return receipt(request);+ }),+ };+}++function noExecution() {+ return { run: mock(rejecting("must not execute")) };+}++const cleanupFailureMessage = "Synthetic hosted cleanup failed";++function failHostedCleanup() {+ const close = CodexSecurity.prototype.close;+ return spyOn(CodexSecurity.prototype, "close").mockImplementation(+ async function (this: CodexSecurity) {+ await close.call(this);+ throw new Error(cleanupFailureMessage);+ },+ );+}++function send(stream: Pick<Writable, "write">, message: object) {+ stream.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");+}++async function protocolError(params: unknown) {+ const input = new PassThrough();+ const output = capture();+ const completed = runHostedScanProtocol(input, output.stream);+ send(input, { id: "run", method: "run", params });+ expect(await completed).toBe(2);+ const messages = parseJsonLines(output.text());+ expect(messages).toHaveLength(1);+ input.destroy();+ return messages[0].error;+}++function blockedOutput() {+ const writing = Promise.withResolvers<void>();+ let release!: () => void;+ const write = mock((_chunk, _encoding, callback) => {+ release = callback;+ writing.resolve();+ });+ return {+ output: new Writable({ write }),+ write,+ writing: writing.promise,+ release: () => release(),+ };+}++test.each([+ "/tmp",+ "",+ "nul\0path",+ "C:part.ts",+ "tab\tname.ts",+ "line\nname.ts",+ "invalid\ud800.ts",+ "../src",+ "src/../other",+ ...(process.platform === "win32" ? ["C:/src", "C:src", "a\\..\\b"] : []),+])("rejects unsupported scope %p", (path) =>+ expect(() => normalizeHostedScope(path)).toThrow(),+);++for (const path of ["C:part.ts", "tab\tname.ts", "line\nname.ts"]) {+ test.skipIf(process.platform === "win32")(+ `rejects tracked contract-incompatible scope ${JSON.stringify(path)} before execution`,+ async () => {+ const input = await fixture([path]);+ input.scope = { paths: [path] };+ const executor = noExecution();+ await expect(runHostedScan(input, { executor })).rejects.toMatchObject({+ reason: "scope_syntax",+ });+ expect(executor.run).not.toHaveBeenCalled();+ },+ );+}++const sealedScopes: {+ name: string;+ paths: string[];+ normalized?: string[];+ files?: string[];+ reported?: string[];+}[] = [+ { name: "repository", paths: ["."], reported: ["repository"] },+ { name: "directory", paths: ["service-a"] },+ { name: "file", paths: ["service-a/index.ts"] },+ {+ name: "multiple normalized paths",+ paths: ["./service-b/", "service-a", "service-a/"],+ normalized: ["service-a", "service-b"],+ },+ {+ name: "bracketed routes, commas and a literal tilde",+ paths: ["app/[slug]/page.tsx", "reports/a,b.ts", "~"],+ files: ["app/[slug]/page.tsx", "reports/a,b.ts", "~"],+ reported: [String.raw`app/\[slug\]/page.tsx`, '`"reports/a,b.ts"`', "~"],+ },+ ...(process.platform === "win32"+ ? []+ : [+ {+ name: "significant spaces and POSIX filename characters",+ paths: [" ", " service ", "literal/*?.ts", "service space"],+ files: [+ " /index.ts",+ " service /index.ts",+ "service/index.ts",+ "literal/*?.ts",+ "service space/index.ts",+ "service space/index.ts",+ ],+ reported: [+ '`" "`',+ '`" service "`',+ String.raw`literal/\*?.ts`,+ '`"service space"`',+ ],+ },+ ]),+];++test.each(sealedScopes)(+ "hosted $name scope is retained in sealed artifacts and hashes",+ async ({ paths, normalized = paths, files, reported = normalized }) => {+ const input = await fixture(files);+ input.scope = { paths };+ if (files) {+ const ordinary = await normalizeTarget(+ input.repository,+ paths.map((path) => `./${path}`),+ );+ expect(ordinary.paths).toEqual(normalized);+ }+ const executor = draftExecutor((request) => {+ expect(request.scope.paths).toEqual(normalized);+ expect(request.identity).toEqual(input.identity);+ expect(request).toMatchObject({+ model: input.model,+ reasoningEffort: input.reasoningEffort,+ });+ for (const key of ["OPENAI_API_KEY", "CODEX_API_KEY"])+ expect(request.runtime.environment).not.toHaveProperty(key);+ const preflight = JSON.parse(+ execFileSync(+ request.runtime.environment["PYTHON"]!,+ [+ join(request.runtime.pluginRoot, "scripts/config_preflight.py"),+ "--profile",+ "security_scan",+ "--cwd",+ request.runtime.outputDirectory,+ "--runtime-check",+ "delegation_available=true",+ "--config",+ request.runtime.environment["CODEX_SECURITY_CONFIG_PATH"]!,+ ],+ { encoding: "utf8", env: request.runtime.environment },+ ),+ );+ expect(preflight.status).toBe("ready");+ });+ const result = await runHostedScan(input, { executor });+ expect(result.status, JSON.stringify(result)).toBe("completed");+ expect(executor.run).toHaveBeenCalledTimes(1);+ expect(result.scope.paths).toEqual(normalized);+ const manifest = await readJson<any>(+ join(result.outputDirectory, "scan-manifest.json"),+ );+ const coverage = await readJson<any>(+ join(result.outputDirectory, "coverage.json"),+ );+ expect(manifest.scan.scope.includePaths).toEqual(normalized);+ expect(manifest.scan.target.revision).toBe(input.revision);+ expect(manifest.scan.sealedAt).toBeTruthy();+ expect(coverage).toMatchObject({+ includePaths: normalized,+ mode: normalized[0] === "." ? "repository" : "scoped_path",+ });+ const report = await readFile(+ join(result.outputDirectory, "report.md"),+ "utf8",+ );+ for (const path of reported) expect(report).toContain(path);+ if (normalized.length > 1) expect(report).not.toContain("service-c");+ for (const artifact of result.artifacts) {+ const data = await readFile(join(result.outputDirectory, artifact.path));+ expect(artifact.sha256).toBe(+ createHash("sha256").update(data).digest("hex"),+ );+ expect(artifact.bytes).toBe(data.byteLength);+ }+ const artifactPaths = result.artifacts.map((artifact) => artifact.path);+ for (const path of Object.keys(manifest.scan.preservedSources ?? {}))+ expect(artifactPaths).toContain(path);+ for (const artifact of manifest.scan.artifacts)+ expect(artifactPaths).toContain(artifact.path);+ },+);++test("hosted execution preserves inspected runtime tool paths", async () => {+ const input = await fixture(["tools/placeholder.ts"]);+ const repositoryTools = await realpath(join(input.repository, "tools"));+ const linkedTools = join(await temporaryDirectory(), "linked-tools");+ const trustedTools = await realpath(dirname(process.execPath));+ await symlink(+ repositoryTools,+ linkedTools,+ process.platform === "win32" ? "junction" : "dir",+ );+ const executableAliases: string[] = [];+ for (const name of process.platform === "win32"+ ? ["node.exe"]+ : ["dirname", "node"]) {+ const directory = await temporaryDirectory();+ await symlink(+ join(repositoryTools, "placeholder.ts"),+ join(directory, name),+ "file",+ );+ executableAliases.push(await realpath(directory));+ }+ const previousPath = process.env["PATH"];+ const executor = draftExecutor();+ try {+ process.env["PATH"] = [+ repositoryTools,+ linkedTools,+ ...executableAliases,+ trustedTools,+ previousPath ?? "",+ ].join(delimiter);+ const result = await runHostedScan(input, { executor });+ expect(result.status).toBe("completed");+ expect(executor.run).toHaveBeenCalledTimes(1);+ const environment = executor.run.mock.calls[0]![0].runtime.environment;+ const paths = environment["PATH"]!.split(delimiter);+ expect(paths).not.toContain(repositoryTools);+ expect(paths).not.toContain(linkedTools);+ for (const directory of executableAliases)+ expect(paths).not.toContain(directory);+ expect(paths).toContain(trustedTools);+ expect(isAbsolute(environment["CODEX_SECURITY_GIT"] ?? "")).toBe(true);+ expect(isAbsolute(environment["PYTHON"] ?? "")).toBe(true);+ } finally {+ if (previousPath === undefined) delete process.env["PATH"];+ else process.env["PATH"] = previousPath;+ }+});++test.skipIf(process.platform === "win32")(+ "missing whitespace paths never fall back to a trimmed sibling or repository",+ async () => {+ const input = await fixture();+ const executor = noExecution();+ for (const path of [" ", " service-a "]) {+ await expect(+ runHostedScan({ ...input, scope: { paths: [path] } }, { executor }),+ ).rejects.toMatchObject({ reason: "scope_missing" });+ }+ expect(executor.run).not.toHaveBeenCalled();+ },+);++test("preparation verifies revision and rejects missing or escaping paths before execution", async () => {+ const input = await fixture();+ const executor = noExecution();+ await expect(+ runHostedScan(+ { ...input, revision: "0".repeat(40), scope: { paths: ["missing"] } },+ { executor },+ ),+ ).rejects.toThrow("frozen revision");+ await expect(+ runHostedScan({ ...input, scope: { paths: ["missing"] } }, { executor }),+ ).rejects.toThrow("does not exist");+ await symlink(+ tmpdir(),+ join(input.repository, "escape"),+ process.platform === "win32" ? "junction" : "dir",+ );+ await expect(+ runHostedScan({ ...input, scope: { paths: ["escape"] } }, { executor }),+ ).rejects.toThrow("outside the repository");+ expect(executor.run).not.toHaveBeenCalled();+});++test("remote uncertainty is terminal with no local fallback or resubmission", async () => {+ const executor = { run: mock(rejecting("Remote acceptance unknown")) };+ const result = await runHostedScan(await fixture(), { executor });+ expect(executor.run).toHaveBeenCalledTimes(1);+ expect(result.status).toBe("acceptance_unknown");+ expect(result).toHaveProperty("error", "Remote acceptance unknown");+});++test("hosted aliases require a canonical path before inference, including aliases to root", async () => {+ const input = await fixture();+ const executor = noExecution();+ for (const [name, target] of [+ ["alias", join(input.repository, "service-a")],+ ["root-alias", input.repository],+ ] as const) {+ await symlink(+ target,+ join(input.repository, name),+ process.platform === "win32" ? "junction" : "dir",+ );+ await expect(+ runHostedScan({ ...input, scope: { paths: [name] } }, { executor }),+ ).rejects.toMatchObject({ reason: "scope_alias" });+ }+ expect(executor.run).not.toHaveBeenCalled();+});++test.each(["missing", "invalid"] as const)(+ "a completed model turn with %s artifacts fails the scan",+ async (artifacts) => {+ const usage = { input_tokens: 123, output_tokens: 7 };+ const result = await runHostedScan(await fixture(), {+ executor: {+ async run(request) {+ if (artifacts === "invalid") {+ await writeDraft(request);+ writeSource(+ request.runtime.outputDirectory,+ "findings.json",+ "{invalid JSON",+ );+ }+ return receipt(request, { usage });+ },+ },+ });+ expect(result.status).toBe("failed");+ expect(result.artifacts).toEqual([]);+ expect(result.execution).toMatchObject({+ status: "completed",+ sessionId: "host-session",+ usage,+ });+ },+);++test("sealed coverage with follow-up diagnostics remains completed", async () => {+ const result = await runHostedScan(await fixture(), {+ executor: draftExecutor(async (request) => {+ const file = join(request.runtime.outputDirectory, "coverage.json");+ const coverage = await readJson<any>(file);+ coverage.surfaces[0].disposition = "needs_follow_up";+ await writeJson(file, coverage);+ }),+ });+ expect(result.status).toBe("completed");+ expect(result.artifacts.map((artifact) => artifact.path)).toContain(+ "coverage.json",+ );+ const coverage = await readJson<any>(+ join(result.outputDirectory, "coverage.json"),+ );+ expect(coverage.surfaces[0].disposition).toBe("needs_follow_up");+});++test("a changed checkout cannot produce accepted completed output", async () => {+ const input = await fixture();+ const result = await runHostedScan(input, {+ executor: draftExecutor(() => {+ git(input.repository, "commit", "--allow-empty", "-qm", "changed");+ }),+ });+ expect(result.status).toBe("failed");+ expect(result.artifacts).toEqual([]);+});++test("malformed run input returns one protocol error", async () => {+ expect((await protocolError({ version: 2 })).code).toBe(-32602);+});++test.each([+ { path: "missing", reason: "scope_missing" },+ { path: "C:part.ts", reason: "scope_syntax" },+ { path: "tab\tname.ts", reason: "scope_syntax" },+ { path: "line\nname.ts", reason: "scope_syntax" },+])(+ "scope %p has a typed preparation error and never asks for execution",+ async ({ path, reason }) => {+ const params = await fixture();+ params.scope!.paths = [path];+ expect((await protocolError(params)).data).toEqual({ reason });+ },+);++test.each([+ { args: ["scan", "--host=true"] },+ { args: ["scan", "--host", "--path", "service-a"] },+ { args: ["scan", ".", "--host"] },+])("host mode rejects unsupported combinations %p", async ({ args }) => {+ const stdout = capture();+ const stderr = capture();+ expect(await main(args, stdout.stream, stderr.stream, dependencies())).toBe(+ 2,+ );+ expect(stdout.text()).toBe("");+ expect(stderr.text()).toContain("--host must be used alone");+});++test.each([false, true])(+ "CLI pipes retain progress and execution receipts, including cancellation (%p)",+ async (cancel) => {+ const input = await fixture();+ const child = spawn(+ process.execPath,+ [join(import.meta.dirname, "../src/cli.ts"), "scan", "--host"],+ {+ env: {+ PATH: process.env["PATH"],+ TMPDIR: process.env["TMPDIR"],+ SYSTEMROOT: process.env["SYSTEMROOT"],+ },+ stdio: ["pipe", "pipe", "pipe"],+ },+ );+ const closed = new Promise<number | null>((resolve, reject) => {+ child.on("exit", resolve);+ child.on("error", reject);+ });+ let stderr = "";+ child.stderr.on("data", (chunk) => {+ stderr += chunk.toString();+ });+ const messages: any[] = [];+ const usage = { input_tokens: 88 };+ let requestId: string | undefined;+ try {+ send(child.stdin, { id: "run", method: "run", params: input });+ for await (const line of createInterface({ input: child.stdout })) {+ const message = JSON.parse(line);+ messages.push(message);+ if (message.method === "execution.run") {+ requestId = message.params.requestId;+ for (const event of [progressEvent, { invalid: true }])+ send(child.stdin, {+ method: "execution.progress",+ params: { requestId, event },+ });+ if (cancel) {+ send(child.stdin, { method: "cancel", params: { id: "run" } });+ } else {+ await writeDraft(message.params);+ send(child.stdin, {+ id: message.id,+ result: receipt(message.params, {+ sessionId: "fake-host",+ usage,+ }),+ });+ }+ } else if (message.method === "execution.cancel") {+ expect(message.params.requestId).toBe(requestId);+ send(child.stdin, {+ id: requestId,+ result: receipt(message.params, {+ status: "canceled",+ sessionId: "fake-host",+ usage,+ }),+ });+ }+ }+ expect(await closed, stderr).toBe(cancel ? 1 : 0);+ expect(+ messages.filter((message) => message.method === "execution.run"),+ ).toHaveLength(1);+ expect(messages).toContainEqual({+ jsonrpc: "2.0",+ method: "scan.progress",+ params: { id: "run", event: progressEvent },+ });+ expect(messages.at(-1)).toMatchObject({+ id: "run",+ result: {+ status: cancel ? "canceled" : "completed",+ execution: { sessionId: "fake-host", usage },+ },+ });+ } finally {+ child.kill();+ }+ },+);++const progressEvent: ScanExecutionEvent = {+ type: "progress",+ progress: { phase: "discovery", filesCompleted: 1, filesTotal: 2 },+};+const activityEvent: ScanExecutionEvent = {+ type: "activity",+ activity: {+ id: "activity-1",+ kind: "tool",+ status: "running",+ description: "Reading selected files",+ paths: ["service-a/index.ts"],+ },+};++test("empty or root-mixed explicit scopes fail instead of broadening", () => {+ expect(() => normalizeHostedPaths([])).toThrow();+ expect(() => normalizeHostedPaths(["service-a", "."])).toThrow();+ expect(() => normalizeHostedPaths(["service-a", "./"])).toThrow();+ expect(normalizeHostedPaths()).toEqual(["."]);+ expect(normalizeHostedPaths(["\u{10000}", "\uE000"])).toEqual([+ "\uE000",+ "\u{10000}",+ ]);+});++test("one missing or escaping path rejects the entire multi-path request before dispatch", async () => {+ const input = await fixture();+ const executor = noExecution();+ for (const paths of [+ [],+ ["service-a", "missing"],+ ["service-a", "../escape"],+ ]) {+ await expect(+ runHostedScan({ ...input, scope: { paths } }, { executor }),+ ).rejects.toThrow();+ }+ expect(executor.run).not.toHaveBeenCalled();+});++test("standalone SDK forwards progress, isolates observer errors and defaults to full scan", async () => {+ const input = await fixture();+ delete input.scope;+ const events: string[] = [];+ const result = await runHostedScan(input, {+ executor: draftExecutor((request, options) => {+ expect(request.scope.paths).toEqual(["."]);+ options.onEvent?.(progressEvent);+ options.onEvent?.(activityEvent);+ }),+ onEvent(event) {+ events.push(event.type);+ if (event.type === "progress")+ throw new Error("Optional progress failed");+ },+ });+ expect(result.status, JSON.stringify(result)).toBe("completed");+ expect(result.scope.paths).toEqual(["."]);+ expect(events).toContain("progress");+ expect(events).toContain("activity");+});++test.each([+ ["failed", undefined],+ ["failed", "remote-session"],+ ["canceled", "remote-session"],+ ["acceptance_unknown", "remote-session"],+] as const)(+ "standalone SDK retains %s host identity %p and usage in its terminal receipt",+ async (status, sessionId) => {+ const input = await fixture();+ const usage = {+ authoritative_snapshot: { input_tokens: 123, output_tokens: 7 },+ };+ let execution: ScanExecutionResult | undefined;+ const terminal = await runHostedScan(input, {+ executor: {+ async run(request) {+ execution = receipt(request, {+ status,+ sessionId,+ usage,+ error: {+ code: -32010,+ message: "Recorded remote outcome",+ data: { remoteTurnId: "turn-1" },+ },+ });+ return execution;+ },+ },+ });+ expect(terminal.status).toBe(status);+ expect(terminal.execution).toEqual(execution);+ expect(terminal.artifacts).toEqual([]);+ },+);++test("failed hosted config preparation removes its temporary runtime home", async () => {+ const input = await fixture();+ const executor = noExecution();+ let runtimeHome: string | undefined;+ const writeConfig = spyOn(config, "writeCodexConfig").mockImplementation(+ async (path) => {+ runtimeHome = dirname(path);+ throw new Error("Synthetic hosted config preparation failed");+ },+ );+ try {+ const result = await runHostedScan(input, { executor });+ expect(result).toMatchObject({+ status: "failed",+ error: "Synthetic hosted config preparation failed",+ });+ expect(executor.run).not.toHaveBeenCalled();+ expect(runtimeHome).toBeDefined();+ await expect(stat(runtimeHome!)).rejects.toMatchObject({ code: "ENOENT" });+ } finally {+ writeConfig.mockRestore();+ if (runtimeHome !== undefined) await removeTemporaryDirectory(runtimeHome);+ }+});++test.each(["completed", "acceptance_unknown"] as const)(+ "SDK cleanup failure preserves the %s receipt even when its observer throws",+ async (status) => {+ const input = await fixture();+ const events: ScanExecutionEvent[] = [];+ let execution: ScanExecutionResult | undefined;+ const executor = {+ run: mock<ScanExecutor["run"]>(async (request) => {+ if (status === "completed") await writeDraft(request);+ execution = receipt(request, {+ status,+ sessionId: "known-host-session",+ usage: { input_tokens: 123, output_tokens: 7 },+ ...(status === "acceptance_unknown"+ ? {+ error: {+ code: -32010,+ message: "Recorded remote uncertainty",+ data: { remoteTurnId: "turn-1" },+ },+ }+ : {}),+ });+ return execution;+ }),+ };+ const close = failHostedCleanup();+ try {+ const terminal = await runHostedScan(input, {+ executor,+ onEvent(event) {+ events.push(event);+ if (+ event.type === "activity" &&+ event.activity.id === "runtime.cleanup"+ )+ throw new Error("Optional cleanup observer failed");+ },+ });+ expect(terminal.status).toBe(status);+ expect(terminal.execution).toEqual(execution);+ expect(terminal.identity).toEqual(input.identity);+ expect(terminal.scanId).toBe(executor.run.mock.calls[0]![0].scanId);+ expect(executor.run).toHaveBeenCalledTimes(1);+ expect(close).toHaveBeenCalledTimes(1);+ expect(events).toContainEqual({+ type: "activity",+ activity: {+ id: "runtime.cleanup",+ kind: "message",+ status: "failed",+ description: expect.stringContaining(cleanupFailureMessage),+ paths: [],+ },+ });+ if (status === "completed") {+ expect(terminal.artifacts.map((artifact) => artifact.path)).toContain(+ "scan-manifest.json",+ );+ const manifest = await readJson<any>(+ join(terminal.outputDirectory, "scan-manifest.json"),+ );+ expect(manifest.scan.sealedAt).toBeTruthy();+ } else {+ expect(terminal).toHaveProperty("error", execution?.error?.message);+ expect(terminal.artifacts).toEqual([]);+ }+ } finally {+ close.mockRestore();+ }+ },+);++test("wire cleanup failure retains an uncertain terminal result and reports cleanup separately", async () => {+ const params = await fixture();+ const input = new PassThrough();+ const output = new PassThrough();+ const lines = createInterface({ input: output });+ const messages: any[] = [];+ let execution: ScanExecutionResult | undefined;+ const close = failHostedCleanup();+ try {+ const finished = runHostedScanProtocol(input, output);+ send(input, { id: "run", method: "run", params });+ for await (const line of lines) {+ const message = JSON.parse(line);+ messages.push(message);+ if (message.method === "execution.run") {+ execution = receipt(message.params, {+ status: "acceptance_unknown",+ sessionId: "known-host-session",+ usage: { input_tokens: 42 },+ error: {+ code: -32010,+ message: "Recorded remote uncertainty",+ data: { remoteTurnId: "turn-1" },+ },+ });+ send(input, { id: message.id, result: execution });+ } else if (message.id === "run") {+ break;+ }+ }+ expect(await finished).toBe(1);+ expect(close).toHaveBeenCalledTimes(1);+ expect(+ messages.filter((message) => message.method === "execution.run"),+ ).toHaveLength(1);+ expect(messages.filter((message) => message.id === "run")).toHaveLength(1);+ expect(messages.at(-1)).toMatchObject({+ id: "run",+ result: { status: "acceptance_unknown", execution },+ });+ expect(messages.at(-1).result.execution).toEqual(execution);+ expect(messages.filter((message) => "error" in message)).toEqual([]);+ expect(messages).toContainEqual({+ jsonrpc: "2.0",+ method: "scan.progress",+ params: {+ id: "run",+ event: {+ type: "activity",+ activity: {+ id: "runtime.cleanup",+ kind: "message",+ status: "failed",+ description: expect.stringContaining(cleanupFailureMessage),+ paths: [],+ },+ },+ },+ });+ } finally {+ close.mockRestore();+ lines.close();+ input.destroy();+ output.destroy();+ }+});++test("cancellation after registration retains scan identity before executor dispatch", async () => {+ const input = await fixture();+ const controller = new AbortController();+ const executor = noExecution();+ const result = await runHostedScan(input, {+ signal: controller.signal,+ onEvent(event) {+ if (+ event.type === "progress" &&+ event.progress.phase === "preflight" &&+ event.progress.filesTotal > 0+ )+ controller.abort();+ },+ executor,+ });+ expect(result.status).toBe("canceled");+ expect(executor.run).not.toHaveBeenCalled();+ expect(result.scanId).toBeString();+ expect(result.execution).toBeUndefined();+ const history = await runWorkbench(+ {+ python: pythonExecutable()!,+ pluginRoot: PLUGIN_ROOT,+ environment: {+ PATH: process.env["PATH"],+ SYSTEMROOT: process.env["SYSTEMROOT"],+ CODEX_SECURITY_STATE_DIR: input.stateDirectory,+ },+ },+ ["list-scans", "--repository", input.repository],+ );+ expect(history["scans"]).toMatchObject([+ {+ scanId: result.scanId,+ scanDir: result.outputDirectory,+ progress: { status: "failed" },+ },+ ]);+});++test("SDK cancellation waits for the executor receipt without losing known session/usage", async () => {+ const input = await fixture();+ const controller = new AbortController();+ const result = await runHostedScan(input, {+ signal: controller.signal,+ executor: {+ async run(request, options) {+ controller.abort();+ expect(options.signal.aborted).toBe(true);+ await Promise.resolve();+ return receipt(request, {+ status: "canceled",+ sessionId: "canceled-session",+ usage: { input_tokens: 42 },+ });+ },+ },+ });+ expect(result.status).toBe("canceled");+ expect(result.execution).toMatchObject({+ status: "canceled",+ sessionId: "canceled-session",+ usage: { input_tokens: 42 },+ });+});++test("mismatched execution receipts are never accepted or retried", async () => {+ const input = await fixture();+ const executor = {+ run: mock(async () =>+ receipt(+ { requestId: "other-request" },+ {+ sessionId: "known-session",+ usage: { input_tokens: 9 },+ },+ ),+ ),+ };+ const result = await runHostedScan(input, { executor });+ expect(executor.run).toHaveBeenCalledTimes(1);+ expect(result.status).toBe("acceptance_unknown");+ expect(result.execution?.sessionId).toBe("known-session");+ expect(result.artifacts).toEqual([]);+});++test("same Cloud attempt does not create CLI cross-invocation replay decisions", async () => {+ const input = await fixture();+ const requests: string[] = [];+ const executor = {+ async run(request: ScanExecutionRequest): Promise<ScanExecutionResult> {+ requests.push(request.requestId);+ return receipt(request, {+ status: "acceptance_unknown",+ sessionId: "host-owned-session",+ });+ },+ };+ for (const suffix of ["first", "second"]) {+ const result = await runHostedScan(+ { ...input, outputDirectory: join(input.outputDirectory, suffix) },+ { executor },+ );+ expect(result.status).toBe("acceptance_unknown");+ }+ expect(requests).toHaveLength(2);+ expect(requests[0]).not.toBe(requests[1]);+});++test.each(["cancel", "disconnect", "signal"])(+ "blocked execution request terminates on %s",+ async (action) => {+ const params = await fixture();+ const input = new PassThrough();+ const controller = new AbortController();+ const { output, writing, release } = blockedOutput();+ const run = spyOn(hostedScan, "runHostedScan");+ try {+ const finished = runHostedScanProtocol(input, output, controller.signal);+ send(input, { id: "run", method: "run", params });+ await writing;+ if (action === "cancel")+ send(input, { method: "cancel", params: { id: "run" } });+ else if (action === "signal") controller.abort();+ else input.end();+ expect(await finished).toBe(2);+ expect(output.destroyed).toBe(true);+ expect(run).toHaveBeenCalledTimes(1);+ } finally {+ release();+ input.destroy();+ output.destroy();+ // Transport cancellation can finish before the scan closes its client.+ await Promise.allSettled(run.mock.results.map(({ value }) => value));+ run.mockRestore();+ }+ },+);++test.each(["result", "error"])(+ "output closure interrupts a blocked terminal %s without a second response",+ async (terminal) => {+ const input = new PassThrough();+ const { output, writing, release, write } = blockedOutput();+ const finished = runHostProtocol(input, output, {+ label: "Scan",+ requestMethod: "execution.run",+ async run() {+ if (terminal === "error") throw new Error("Invalid run parameters");+ return { status: "completed" };+ },+ });+ send(input, { id: "run", method: "run", params: {} });+ await writing;+ input.end();+ output.destroy();+ try {+ expect(await finished).toBe(2);+ expect(output.destroyed).toBe(true);+ expect(write).toHaveBeenCalledTimes(1);+ } finally {+ release();+ input.destroy();+ output.destroy();+ }+ },+);++test("the exported contract fixture matches v2 and rejects explicit empty scope", async () => {+ const fixture = await readJson<any>(+ join(import.meta.dirname, "../schemas/hosted-scan-v2.fixture.json"),+ );+ expect(HostedScanInputSchema.parse(fixture.run.params).scope).toEqual({+ paths: ["service-a", "service-b"],+ });+ expect(+ HostedScanInputSchema.safeParse({+ ...fixture.run.params,+ scope: { paths: [] },+ }).success,+ ).toBe(false);+ expect(+ HostedScanInputSchema.safeParse({ ...fixture.run.params, scope: undefined })+ .success,+ ).toBe(true);+ expect(fixture.terminal.id).toBe(fixture.run.id);+ expect(fixture.terminal.result).toMatchObject({+ version: 2,+ status: "completed",+ identity: fixture.run.params.identity,+ scope: fixture.run.params.scope,+ scanId: fixture.execution.params.scanId,+ execution: ScanExecutionResultSchema.parse(fixture.response.result),+ });+});++test("standalone SDK rejects local scan options and configuration before dispatch", async () => {+ const input = await fixture();+ const executor = noExecution();+ for (const extra of [+ { mode: "deep" },+ { config: { codexOverrides: { profile: "local" } } },+ ])+ await expect(+ runHostedScan({ ...input, ...extra }, { executor }),+ ).rejects.toThrow("Unrecognized key");+ expect(executor.run).not.toHaveBeenCalled();+});++test("ordinary SDK rejects the removed hosted option instead of using local inference", async () => {+ const client = new CodexSecurity();+ try {+ await expect(+ client.run("unused-repository", {+ // @ts-expect-error Legacy JavaScript callers must fail before local inference.+ hosted: {},+ }),+ ).rejects.toThrow("Use runHostedScan with an executor");+ } finally {+ await client.close();+ }+});diff --git a/sdk/typescript/tests-ts/package-tar-listing.test.ts b/sdk/typescript/tests-ts/package-tar-listing.test.tsindex 79f1ef9aa..1a0eab4ce 100644--- a/sdk/typescript/tests-ts/package-tar-listing.test.ts+++ b/sdk/typescript/tests-ts/package-tar-listing.test.ts@@ -81,6 +81,8 @@ function packageTar({"package/docs/cli.md","package/docs/findings-service.md","package/docs/dedupe-records.md",+ "package/docs/hosted-scans.md",+ "package/schemas/hosted-scan-v2.fixture.json","package/schemas/project-config.schema.json","package/LICENSE",...executablePaths,diff --git a/sdk/typescript/tests-ts/runtime-plugin-reuse.test.ts b/sdk/typescript/tests-ts/runtime-plugin-reuse.test.tsindex 5c30b446a..f0912f79b 100644--- a/sdk/typescript/tests-ts/runtime-plugin-reuse.test.ts+++ b/sdk/typescript/tests-ts/runtime-plugin-reuse.test.ts@@ -3,8 +3,10 @@ import { once } from "node:events";import * as fsPromises from "node:fs/promises";import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";import { dirname, join } from "node:path";+import { createInterface } from "node:readline";import { expect, spyOn, test } from "bun:test";import { bootstrapPlugin } from "../src/runtime.js";+import { nodeCommand } from "./support/shell.js";import { temporaryDirectory } from "./support/temporary-directories.js";test.each(["unchanged", "missing", "truncated"] as const)(@@ -74,29 +76,30 @@ async function checkWorkerReuse();const expectedManifest = await readFile(manifest, "utf8");const worker = spawn(- process.execPath,+ nodeCommand().command,["--eval",- `process.once("message", () => {+ `process.stdin.once("end", () => {try {- process.send(require("node:fs").readFileSync("scripts/helper.txt", "utf8"));+ process.stdout.write(JSON.stringify(require("node:fs").readFileSync("scripts/helper.txt", "utf8")) + "\\n");} catch (error) {- process.send({ error: String(error) });- } finally {- process.disconnect();+ process.stdout.write(JSON.stringify({ error: String(error) }) + "\\n");}});- process.send("ready");`,+ process.stdin.resume();+ process.stdout.write("ready\\n");`,],{cwd: first.installedRoot,- stdio: ["ignore", "ignore", "ignore", "ipc"],+ stdio: ["pipe", "pipe", "ignore"],+ windowsHide: true,},);const exited = once(worker, "exit");+ const output = createInterface({ input: worker.stdout });+ const messages = output[Symbol.asyncIterator]();try {- const [ready] = await Promise.race([once(worker, "message"), exited]);- expect(ready).toBe("ready");+ expect(await messages.next()).toEqual({ value: "ready", done: false });if (metadata === "missing") await rm(manifest);else if (metadata === "truncated") await writeFile(manifest, "{");const originalWrite = fsPromises.writeFile;@@ -153,10 +156,10 @@ async function checkWorkerReuse(write?.mockRestore();rename?.mockRestore();}- const response = once(worker, "message");- worker.send("read");- const [content] = await Promise.race([response, exited]);- expect(content).toBe(helper);+ worker.stdin.end();+ const response = await messages.next();+ expect(response.done).toBe(false);+ expect(JSON.parse(response.value!)).toBe(helper);expect(installs).toBe(1);if (failReplacement && !concurrent) {if (metadata === "missing") {@@ -179,6 +182,7 @@ async function checkWorkerReuse(await bootstrapPlugin(home, selected, options);expect(installs).toBe(1);} finally {+ output.close();if (worker.exitCode === null && worker.signalCode === null) worker.kill();await exited;}