Compare commits

..

3 Commits

Author SHA1 Message Date
Michael Bolin
8ae9f99d41 feat: exclude v1 from the JSON schema 2026-02-20 17:13:36 -08:00
Michael Bolin
b480a0eeae ignore v1 in JSON schema codegen 2026-02-20 17:11:27 -08:00
Michael Bolin
4e38c6a73b fix: explicitly list name collisions in JSON schema generation 2026-02-20 17:11:27 -08:00
560 changed files with 8916 additions and 62815 deletions

View File

@@ -1,185 +0,0 @@
---
name: babysit-pr
description: Babysit a GitHub pull request after creation by continuously polling CI checks/workflow runs, new review comments, and mergeability state until the PR is ready to merge (or merged/closed). Diagnose failures, retry likely flaky failures up to 3 times, auto-fix/push branch-related issues when appropriate, and stop only when user help is required (for example CI infrastructure issues, exhausted flaky retries, or ambiguous/blocking situations). Use when the user asks Codex to monitor a PR, watch CI, handle review comments, or keep an eye on failures and feedback on an open PR.
---
# PR Babysitter
## Objective
Babysit a PR persistently until one of these terminal outcomes occurs:
- The PR is merged or closed.
- CI is successful, there are no unaddressed review comments surfaced by the watcher, required review approval is not blocking merge, and there are no potential merge conflicts (PR is mergeable / not reporting conflict risk).
- A situation requires user help (for example CI infrastructure issues, repeated flaky failures after retry budget is exhausted, permission problems, or ambiguity that cannot be resolved safely).
Do not stop merely because a single snapshot returns `idle` while checks are still pending.
## Inputs
Accept any of the following:
- No PR argument: infer the PR from the current branch (`--pr auto`)
- PR number
- PR URL
## Core Workflow
1. When the user asks to "monitor"/"watch"/"babysit" a PR, start with the watcher's continuous mode (`--watch`) unless you are intentionally doing a one-shot diagnostic snapshot.
2. Run the watcher script to snapshot PR/CI/review state (or consume each streamed snapshot from `--watch`).
3. Inspect the `actions` list in the JSON response.
4. If `diagnose_ci_failure` is present, inspect failed run logs and classify the failure.
5. If the failure is likely caused by the current branch, patch code locally, commit, and push.
6. If `process_review_comment` is present, inspect surfaced review items and decide whether to address them.
7. If a review item is actionable and correct, patch code locally, commit, and push.
8. If the failure is likely flaky/unrelated and `retry_failed_checks` is present, rerun failed jobs with `--retry-failed-now`.
9. If both actionable review feedback and `retry_failed_checks` are present, prioritize review feedback first; a new commit will retrigger CI, so avoid rerunning flaky checks on the old SHA unless you intentionally defer the review change.
10. On every loop, verify mergeability / merge-conflict status (for example via `gh pr view`) in addition to CI and review state.
11. After any push or rerun action, immediately return to step 1 and continue polling on the updated SHA/state.
12. If you had been using `--watch` before pausing to patch/commit/push, relaunch `--watch` yourself in the same turn immediately after the push (do not wait for the user to re-invoke the skill).
13. Repeat polling until the PR is green + review-clean + mergeable, `stop_pr_closed` appears, or a user-help-required blocker is reached.
14. Maintain terminal/session ownership: while babysitting is active, keep consuming watcher output in the same turn; do not leave a detached `--watch` process running and then end the turn as if monitoring were complete.
## Commands
### One-shot snapshot
```bash
python3 .codex/skills/babysit-pr/scripts/gh_pr_watch.py --pr auto --once
```
### Continuous watch (JSONL)
```bash
python3 .codex/skills/babysit-pr/scripts/gh_pr_watch.py --pr auto --watch
```
### Trigger flaky retry cycle (only when watcher indicates)
```bash
python3 .codex/skills/babysit-pr/scripts/gh_pr_watch.py --pr auto --retry-failed-now
```
### Explicit PR target
```bash
python3 .codex/skills/babysit-pr/scripts/gh_pr_watch.py --pr <number-or-url> --once
```
## CI Failure Classification
Use `gh` commands to inspect failed runs before deciding to rerun.
- `gh run view <run-id> --json jobs,name,workflowName,conclusion,status,url,headSha`
- `gh run view <run-id> --log-failed`
Prefer treating failures as branch-related when logs point to changed code (compile/test/lint/typecheck/snapshots/static analysis in touched areas).
Prefer treating failures as flaky/unrelated when logs show transient infra/external issues (timeouts, runner provisioning failures, registry/network outages, GitHub Actions infra errors).
If classification is ambiguous, perform one manual diagnosis attempt before choosing rerun.
Read `.codex/skills/babysit-pr/references/heuristics.md` for a concise checklist.
## Review Comment Handling
The watcher surfaces review items from:
- PR issue comments
- Inline review comments
- Review submissions (COMMENT / APPROVED / CHANGES_REQUESTED)
It intentionally surfaces Codex reviewer bot feedback (for example comments/reviews from `chatgpt-codex-connector[bot]`) in addition to human reviewer feedback. Most unrelated bot noise should still be ignored.
For safety, the watcher only auto-surfaces trusted human review authors (for example repo OWNER/MEMBER/COLLABORATOR, plus the authenticated operator) and approved review bots such as Codex.
On a fresh watcher state file, existing pending review feedback may be surfaced immediately (not only comments that arrive after monitoring starts). This is intentional so already-open review comments are not missed.
When you agree with a comment and it is actionable:
1. Patch code locally.
2. Commit with `codex: address PR review feedback (#<n>)`.
3. Push to the PR head branch.
4. Resume watching on the new SHA immediately (do not stop after reporting the push).
5. If monitoring was running in `--watch` mode, restart `--watch` immediately after the push in the same turn; do not wait for the user to ask again.
If you disagree or the comment is non-actionable/already addressed, record it as handled by continuing the watcher loop (the script de-duplicates surfaced items via state after surfacing them).
If a code review comment/thread is already marked as resolved in GitHub, treat it as non-actionable and safely ignore it unless new unresolved follow-up feedback appears.
## Git Safety Rules
- Work only on the PR head branch.
- Avoid destructive git commands.
- Do not switch branches unless necessary to recover context.
- Before editing, check for unrelated uncommitted changes. If present, stop and ask the user.
- After each successful fix, commit and `git push`, then re-run the watcher.
- If you interrupted a live `--watch` session to make the fix, restart `--watch` immediately after the push in the same turn.
- Do not run multiple concurrent `--watch` processes for the same PR/state file; keep one watcher session active and reuse it until it stops or you intentionally restart it.
- A push is not a terminal outcome; continue the monitoring loop unless a strict stop condition is met.
Commit message defaults:
- `codex: fix CI failure on PR #<n>`
- `codex: address PR review feedback (#<n>)`
## Monitoring Loop Pattern
Use this loop in a live Codex session:
1. Run `--once`.
2. Read `actions`.
3. First check whether the PR is now merged or otherwise closed; if so, report that terminal state and stop polling immediately.
4. Check CI summary, new review items, and mergeability/conflict status.
5. Diagnose CI failures and classify branch-related vs flaky/unrelated.
6. Process actionable review comments before flaky reruns when both are present; if a review fix requires a commit, push it and skip rerunning failed checks on the old SHA.
7. Retry failed checks only when `retry_failed_checks` is present and you are not about to replace the current SHA with a review/CI fix commit.
8. If you pushed a commit or triggered a rerun, report the action briefly and continue polling (do not stop).
9. After a review-fix push, proactively restart continuous monitoring (`--watch`) in the same turn unless a strict stop condition has already been reached.
10. If everything is passing, mergeable, not blocked on required review approval, and there are no unaddressed review items, report success and stop.
11. If blocked on a user-help-required issue (infra outage, exhausted flaky retries, unclear reviewer request, permissions), report the blocker and stop.
12. Otherwise sleep according to the polling cadence below and repeat.
When the user explicitly asks to monitor/watch/babysit a PR, prefer `--watch` so polling continues autonomously in one command. Use repeated `--once` snapshots only for debugging, local testing, or when the user explicitly asks for a one-shot check.
Do not stop to ask the user whether to continue polling; continue autonomously until a strict stop condition is met or the user explicitly interrupts.
Do not hand control back to the user after a review-fix push just because a new SHA was created; restarting the watcher and re-entering the poll loop is part of the same babysitting task.
If a `--watch` process is still running and no strict stop condition has been reached, the babysitting task is still in progress; keep streaming/consuming watcher output instead of ending the turn.
## Polling Cadence
Use adaptive polling and continue monitoring even after CI turns green:
- While CI is not green (pending/running/queued or failing): poll every 1 minute.
- After CI turns green: start at every 1 minute, then back off exponentially when there is no change (for example 1m, 2m, 4m, 8m, 16m, 32m), capping at every 1 hour.
- Reset the green-state polling interval back to 1 minute whenever anything changes (new commit/SHA, check status changes, new review comments, mergeability changes, review decision changes).
- If CI stops being green again (new commit, rerun, or regression): return to 1-minute polling.
- If any poll shows the PR is merged or otherwise closed: stop polling immediately and report the terminal state.
## Stop Conditions (Strict)
Stop only when one of the following is true:
- PR merged or closed (stop as soon as a poll/snapshot confirms this).
- PR is ready to merge: CI succeeded, no surfaced unaddressed review comments, not blocked on required review approval, and no merge conflict risk.
- User intervention is required and Codex cannot safely proceed alone.
Keep polling when:
- `actions` contains only `idle` but checks are still pending.
- CI is still running/queued.
- Review state is quiet but CI is not terminal.
- CI is green but mergeability is unknown/pending.
- CI is green and mergeable, but the PR is still open and you are waiting for possible new review comments or merge-conflict changes per the green-state cadence.
- The PR is green but blocked on review approval (`REVIEW_REQUIRED` / similar); continue polling on the green-state cadence and surface any new review comments without asking for confirmation to keep watching.
## Output Expectations
Provide concise progress updates while monitoring and a final summary that includes:
- During long unchanged monitoring periods, avoid emitting a full update on every poll; summarize only status changes plus occasional heartbeat updates.
- Treat push confirmations, intermediate CI snapshots, and review-action updates as progress updates only; do not emit the final summary or end the babysitting session unless a strict stop condition is met.
- A user request to "monitor" is not satisfied by a couple of sample polls; remain in the loop until a strict stop condition or an explicit user interruption.
- A review-fix commit + push is not a completion event; immediately resume live monitoring (`--watch`) in the same turn and continue reporting progress updates.
- When CI first transitions to all green for the current SHA, emit a one-time celebratory progress update (do not repeat it on every green poll). Preferred style: `🚀 CI is all green! 33/33 passed. Still on watch for review approval.`
- Do not send the final summary while a watcher terminal is still running unless the watcher has emitted/confirmed a strict stop condition; otherwise continue with progress updates.
- Final PR SHA
- CI status summary
- Mergeability / conflict status
- Fixes pushed
- Flaky retry cycles used
- Remaining unresolved failures or review comments
## References
- Heuristics and decision tree: `.codex/skills/babysit-pr/references/heuristics.md`
- GitHub CLI/API details used by the watcher: `.codex/skills/babysit-pr/references/github-api-notes.md`

View File

@@ -1,4 +0,0 @@
interface:
display_name: "PR Babysitter"
short_description: "Watch PR CI, reviews, and merge conflicts"
default_prompt: "Babysit the current PR: monitor CI, reviewer comments, and merge-conflict status (prefer the watchers --watch mode for live monitoring); fix valid issues, push updates, and rerun flaky failures up to 3 times. Keep exactly one watcher session active for the PR (do not leave duplicate --watch terminals running). If you pause monitoring to patch review/CI feedback, restart --watch yourself immediately after the push in the same turn. If a watcher is still running and no strict stop condition has been reached, the task is still in progress: keep consuming watcher output and sending progress updates instead of ending the turn. Continue polling autonomously after any push/rerun until a strict terminal stop condition is reached or the user interrupts."

View File

@@ -1,72 +0,0 @@
# GitHub CLI / API Notes For `babysit-pr`
## Primary commands used
### PR metadata
- `gh pr view --json number,url,state,mergedAt,closedAt,headRefName,headRefOid,headRepository,headRepositoryOwner`
Used to resolve PR number, URL, branch, head SHA, and closed/merged state.
### PR checks summary
- `gh pr checks --json name,state,bucket,link,workflow,event,startedAt,completedAt`
Used to compute pending/failed/passed counts and whether the current CI round is terminal.
### Workflow runs for head SHA
- `gh api repos/{owner}/{repo}/actions/runs -X GET -f head_sha=<sha> -f per_page=100`
Used to discover failed workflow runs and rerunnable run IDs.
### Failed log inspection
- `gh run view <run-id> --json jobs,name,workflowName,conclusion,status,url,headSha`
- `gh run view <run-id> --log-failed`
Used by Codex to classify branch-related vs flaky/unrelated failures.
### Retry failed jobs only
- `gh run rerun <run-id> --failed`
Reruns only failed jobs (and dependencies) for a workflow run.
## Review-related endpoints
- Issue comments on PR:
- `gh api repos/{owner}/{repo}/issues/<pr_number>/comments?per_page=100`
- Inline PR review comments:
- `gh api repos/{owner}/{repo}/pulls/<pr_number>/comments?per_page=100`
- Review submissions:
- `gh api repos/{owner}/{repo}/pulls/<pr_number>/reviews?per_page=100`
## JSON fields consumed by the watcher
### `gh pr view`
- `number`
- `url`
- `state`
- `mergedAt`
- `closedAt`
- `headRefName`
- `headRefOid`
### `gh pr checks`
- `bucket` (`pass`, `fail`, `pending`, `skipping`)
- `state`
- `name`
- `workflow`
- `link`
### Actions runs API (`workflow_runs[]`)
- `id`
- `name`
- `status`
- `conclusion`
- `html_url`
- `head_sha`

View File

@@ -1,58 +0,0 @@
# CI / Review Heuristics
## CI classification checklist
Treat as **branch-related** when logs clearly indicate a regression caused by the PR branch:
- Compile/typecheck/lint failures in files or modules touched by the branch
- Deterministic unit/integration test failures in changed areas
- Snapshot output changes caused by UI/text changes in the branch
- Static analysis violations introduced by the latest push
- Build script/config changes in the PR causing a deterministic failure
Treat as **likely flaky or unrelated** when evidence points to transient or external issues:
- DNS/network/registry timeout errors while fetching dependencies
- Runner image provisioning or startup failures
- GitHub Actions infrastructure/service outages
- Cloud/service rate limits or transient API outages
- Non-deterministic failures in unrelated integration tests with known flake patterns
If uncertain, inspect failed logs once before choosing rerun.
## Decision tree (fix vs rerun vs stop)
1. If PR is merged/closed: stop.
2. If there are failed checks:
- Diagnose first.
- If branch-related: fix locally, commit, push.
- If likely flaky/unrelated and all checks for the current SHA are terminal: rerun failed jobs.
- If checks are still pending: wait.
3. If flaky reruns for the same SHA reach the configured limit (default 3): stop and report persistent failure.
4. Independently, process any new human review comments.
## Review comment agreement criteria
Address the comment when:
- The comment is technically correct.
- The change is actionable in the current branch.
- The requested change does not conflict with the users intent or recent guidance.
- The change can be made safely without unrelated refactors.
Do not auto-fix when:
- The comment is ambiguous and needs clarification.
- The request conflicts with explicit user instructions.
- The proposed change requires product/design decisions the user has not made.
- The codebase is in a dirty/unrelated state that makes safe editing uncertain.
## Stop-and-ask conditions
Stop and ask the user instead of continuing automatically when:
- The local worktree has unrelated uncommitted changes.
- `gh` auth/permissions fail.
- The PR branch cannot be pushed.
- CI failures persist after the flaky retry budget.
- Reviewer feedback requires a product decision or cross-team coordination.

View File

@@ -1,805 +0,0 @@
#!/usr/bin/env python3
"""Watch GitHub PR CI and review activity for Codex PR babysitting workflows."""
import argparse
import json
import os
import re
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from urllib.parse import urlparse
FAILED_RUN_CONCLUSIONS = {
"failure",
"timed_out",
"cancelled",
"action_required",
"startup_failure",
"stale",
}
PENDING_CHECK_STATES = {
"QUEUED",
"IN_PROGRESS",
"PENDING",
"WAITING",
"REQUESTED",
}
REVIEW_BOT_LOGIN_KEYWORDS = {
"codex",
}
TRUSTED_AUTHOR_ASSOCIATIONS = {
"OWNER",
"MEMBER",
"COLLABORATOR",
}
MERGE_BLOCKING_REVIEW_DECISIONS = {
"REVIEW_REQUIRED",
"CHANGES_REQUESTED",
}
MERGE_CONFLICT_OR_BLOCKING_STATES = {
"BLOCKED",
"DIRTY",
"DRAFT",
"UNKNOWN",
}
GREEN_STATE_MAX_POLL_SECONDS = 60 * 60
class GhCommandError(RuntimeError):
pass
def parse_args():
parser = argparse.ArgumentParser(
description=(
"Normalize PR/CI/review state for Codex PR babysitting and optionally "
"trigger flaky reruns."
)
)
parser.add_argument("--pr", default="auto", help="auto, PR number, or PR URL")
parser.add_argument("--repo", help="Optional OWNER/REPO override")
parser.add_argument("--poll-seconds", type=int, default=30, help="Watch poll interval")
parser.add_argument(
"--max-flaky-retries",
type=int,
default=3,
help="Max rerun cycles per head SHA before stop recommendation",
)
parser.add_argument("--state-file", help="Path to state JSON file")
parser.add_argument("--once", action="store_true", help="Emit one snapshot and exit")
parser.add_argument("--watch", action="store_true", help="Continuously emit JSONL snapshots")
parser.add_argument(
"--retry-failed-now",
action="store_true",
help="Rerun failed jobs for current failed workflow runs when policy allows",
)
parser.add_argument(
"--json",
action="store_true",
help="Emit machine-readable output (default behavior for --once and --retry-failed-now)",
)
args = parser.parse_args()
if args.poll_seconds <= 0:
parser.error("--poll-seconds must be > 0")
if args.max_flaky_retries < 0:
parser.error("--max-flaky-retries must be >= 0")
if args.watch and args.retry_failed_now:
parser.error("--watch cannot be combined with --retry-failed-now")
if not args.once and not args.watch and not args.retry_failed_now:
args.once = True
return args
def _format_gh_error(cmd, err):
stdout = (err.stdout or "").strip()
stderr = (err.stderr or "").strip()
parts = [f"GitHub CLI command failed: {' '.join(cmd)}"]
if stdout:
parts.append(f"stdout: {stdout}")
if stderr:
parts.append(f"stderr: {stderr}")
return "\n".join(parts)
def gh_text(args, repo=None):
cmd = ["gh"]
# `gh api` does not accept `-R/--repo` on all gh versions. The watcher's
# API calls use explicit endpoints (e.g. repos/{owner}/{repo}/...), so the
# repo flag is unnecessary there.
if repo and (not args or args[0] != "api"):
cmd.extend(["-R", repo])
cmd.extend(args)
try:
proc = subprocess.run(cmd, check=True, capture_output=True, text=True)
except FileNotFoundError as err:
raise GhCommandError("`gh` command not found") from err
except subprocess.CalledProcessError as err:
raise GhCommandError(_format_gh_error(cmd, err)) from err
return proc.stdout
def gh_json(args, repo=None):
raw = gh_text(args, repo=repo).strip()
if not raw:
return None
try:
return json.loads(raw)
except json.JSONDecodeError as err:
raise GhCommandError(f"Failed to parse JSON from gh output for {' '.join(args)}") from err
def parse_pr_spec(pr_spec):
if pr_spec == "auto":
return {"mode": "auto", "value": None}
if re.fullmatch(r"\d+", pr_spec):
return {"mode": "number", "value": pr_spec}
parsed = urlparse(pr_spec)
if parsed.scheme and parsed.netloc and "/pull/" in parsed.path:
return {"mode": "url", "value": pr_spec}
raise ValueError("--pr must be 'auto', a PR number, or a PR URL")
def pr_view_fields():
return (
"number,url,state,mergedAt,closedAt,headRefName,headRefOid,"
"headRepository,headRepositoryOwner,mergeable,mergeStateStatus,reviewDecision"
)
def checks_fields():
return "name,state,bucket,link,workflow,event,startedAt,completedAt"
def resolve_pr(pr_spec, repo_override=None):
parsed = parse_pr_spec(pr_spec)
cmd = ["pr", "view"]
if parsed["value"] is not None:
cmd.append(parsed["value"])
cmd.extend(["--json", pr_view_fields()])
data = gh_json(cmd, repo=repo_override)
if not isinstance(data, dict):
raise GhCommandError("Unexpected PR payload from `gh pr view`")
pr_url = str(data.get("url") or "")
repo = (
repo_override
or extract_repo_from_pr_url(pr_url)
or extract_repo_from_pr_view(data)
)
if not repo:
raise GhCommandError("Unable to determine OWNER/REPO for the PR")
state = str(data.get("state") or "")
merged = bool(data.get("mergedAt"))
closed = bool(data.get("closedAt")) or state.upper() == "CLOSED"
return {
"number": int(data["number"]),
"url": pr_url,
"repo": repo,
"head_sha": str(data.get("headRefOid") or ""),
"head_branch": str(data.get("headRefName") or ""),
"state": state,
"merged": merged,
"closed": closed,
"mergeable": str(data.get("mergeable") or ""),
"merge_state_status": str(data.get("mergeStateStatus") or ""),
"review_decision": str(data.get("reviewDecision") or ""),
}
def extract_repo_from_pr_view(data):
head_repo = data.get("headRepository")
head_owner = data.get("headRepositoryOwner")
owner = None
name = None
if isinstance(head_owner, dict):
owner = head_owner.get("login") or head_owner.get("name")
elif isinstance(head_owner, str):
owner = head_owner
if isinstance(head_repo, dict):
name = head_repo.get("name")
repo_owner = head_repo.get("owner")
if not owner and isinstance(repo_owner, dict):
owner = repo_owner.get("login") or repo_owner.get("name")
elif isinstance(head_repo, str):
name = head_repo
if owner and name:
return f"{owner}/{name}"
return None
def extract_repo_from_pr_url(pr_url):
parsed = urlparse(pr_url)
parts = [p for p in parsed.path.split("/") if p]
if len(parts) >= 4 and parts[2] == "pull":
return f"{parts[0]}/{parts[1]}"
return None
def load_state(path):
if path.exists():
try:
data = json.loads(path.read_text())
except json.JSONDecodeError as err:
raise RuntimeError(f"State file is not valid JSON: {path}") from err
if not isinstance(data, dict):
raise RuntimeError(f"State file must contain an object: {path}")
return data, False
return {
"pr": {},
"started_at": None,
"last_seen_head_sha": None,
"retries_by_sha": {},
"seen_issue_comment_ids": [],
"seen_review_comment_ids": [],
"seen_review_ids": [],
"last_snapshot_at": None,
}, True
def save_state(path, state):
path.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps(state, indent=2, sort_keys=True) + "\n"
fd, tmp_name = tempfile.mkstemp(prefix=f"{path.name}.", suffix=".tmp", dir=path.parent)
tmp_path = Path(tmp_name)
try:
with os.fdopen(fd, "w", encoding="utf-8") as tmp_file:
tmp_file.write(payload)
os.replace(tmp_path, path)
except Exception:
try:
tmp_path.unlink(missing_ok=True)
except OSError:
pass
raise
def default_state_file_for(pr):
repo_slug = pr["repo"].replace("/", "-")
return Path(f"/tmp/codex-babysit-pr-{repo_slug}-pr{pr['number']}.json")
def get_pr_checks(pr_spec, repo):
parsed = parse_pr_spec(pr_spec)
cmd = ["pr", "checks"]
if parsed["value"] is not None:
cmd.append(parsed["value"])
cmd.extend(["--json", checks_fields()])
data = gh_json(cmd, repo=repo)
if data is None:
return []
if not isinstance(data, list):
raise GhCommandError("Unexpected payload from `gh pr checks`")
return data
def is_pending_check(check):
bucket = str(check.get("bucket") or "").lower()
state = str(check.get("state") or "").upper()
return bucket == "pending" or state in PENDING_CHECK_STATES
def summarize_checks(checks):
pending_count = 0
failed_count = 0
passed_count = 0
for check in checks:
bucket = str(check.get("bucket") or "").lower()
if is_pending_check(check):
pending_count += 1
if bucket == "fail":
failed_count += 1
if bucket == "pass":
passed_count += 1
return {
"pending_count": pending_count,
"failed_count": failed_count,
"passed_count": passed_count,
"all_terminal": pending_count == 0,
}
def get_workflow_runs_for_sha(repo, head_sha):
endpoint = f"repos/{repo}/actions/runs"
data = gh_json(
["api", endpoint, "-X", "GET", "-f", f"head_sha={head_sha}", "-f", "per_page=100"],
repo=repo,
)
if not isinstance(data, dict):
raise GhCommandError("Unexpected payload from actions runs API")
runs = data.get("workflow_runs") or []
if not isinstance(runs, list):
raise GhCommandError("Expected `workflow_runs` to be a list")
return runs
def failed_runs_from_workflow_runs(runs, head_sha):
failed_runs = []
for run in runs:
if not isinstance(run, dict):
continue
if str(run.get("head_sha") or "") != head_sha:
continue
conclusion = str(run.get("conclusion") or "")
if conclusion not in FAILED_RUN_CONCLUSIONS:
continue
failed_runs.append(
{
"run_id": run.get("id"),
"workflow_name": run.get("name") or run.get("display_title") or "",
"status": str(run.get("status") or ""),
"conclusion": conclusion,
"html_url": str(run.get("html_url") or ""),
}
)
failed_runs.sort(key=lambda item: (str(item.get("workflow_name") or ""), str(item.get("run_id") or "")))
return failed_runs
def get_authenticated_login():
data = gh_json(["api", "user"])
if not isinstance(data, dict) or not data.get("login"):
raise GhCommandError("Unable to determine authenticated GitHub login from `gh api user`")
return str(data["login"])
def comment_endpoints(repo, pr_number):
return {
"issue_comment": f"repos/{repo}/issues/{pr_number}/comments",
"review_comment": f"repos/{repo}/pulls/{pr_number}/comments",
"review": f"repos/{repo}/pulls/{pr_number}/reviews",
}
def gh_api_list_paginated(endpoint, repo=None, per_page=100):
items = []
page = 1
while True:
sep = "&" if "?" in endpoint else "?"
page_endpoint = f"{endpoint}{sep}per_page={per_page}&page={page}"
payload = gh_json(["api", page_endpoint], repo=repo)
if payload is None:
break
if not isinstance(payload, list):
raise GhCommandError(f"Unexpected paginated payload from gh api {endpoint}")
items.extend(payload)
if len(payload) < per_page:
break
page += 1
return items
def normalize_issue_comments(items):
out = []
for item in items:
if not isinstance(item, dict):
continue
out.append(
{
"kind": "issue_comment",
"id": str(item.get("id") or ""),
"author": extract_login(item.get("user")),
"author_association": str(item.get("author_association") or ""),
"created_at": str(item.get("created_at") or ""),
"body": str(item.get("body") or ""),
"path": None,
"line": None,
"url": str(item.get("html_url") or ""),
}
)
return out
def normalize_review_comments(items):
out = []
for item in items:
if not isinstance(item, dict):
continue
line = item.get("line")
if line is None:
line = item.get("original_line")
out.append(
{
"kind": "review_comment",
"id": str(item.get("id") or ""),
"author": extract_login(item.get("user")),
"author_association": str(item.get("author_association") or ""),
"created_at": str(item.get("created_at") or ""),
"body": str(item.get("body") or ""),
"path": item.get("path"),
"line": line,
"url": str(item.get("html_url") or ""),
}
)
return out
def normalize_reviews(items):
out = []
for item in items:
if not isinstance(item, dict):
continue
out.append(
{
"kind": "review",
"id": str(item.get("id") or ""),
"author": extract_login(item.get("user")),
"author_association": str(item.get("author_association") or ""),
"created_at": str(item.get("submitted_at") or item.get("created_at") or ""),
"body": str(item.get("body") or ""),
"path": None,
"line": None,
"url": str(item.get("html_url") or ""),
}
)
return out
def extract_login(user_obj):
if isinstance(user_obj, dict):
return str(user_obj.get("login") or "")
return ""
def is_bot_login(login):
return bool(login) and login.endswith("[bot]")
def is_actionable_review_bot_login(login):
if not is_bot_login(login):
return False
lower_login = login.lower()
return any(keyword in lower_login for keyword in REVIEW_BOT_LOGIN_KEYWORDS)
def is_trusted_human_review_author(item, authenticated_login):
author = str(item.get("author") or "")
if not author:
return False
if authenticated_login and author == authenticated_login:
return True
association = str(item.get("author_association") or "").upper()
return association in TRUSTED_AUTHOR_ASSOCIATIONS
def fetch_new_review_items(pr, state, fresh_state, authenticated_login=None):
repo = pr["repo"]
pr_number = pr["number"]
endpoints = comment_endpoints(repo, pr_number)
issue_payload = gh_api_list_paginated(endpoints["issue_comment"], repo=repo)
review_comment_payload = gh_api_list_paginated(endpoints["review_comment"], repo=repo)
review_payload = gh_api_list_paginated(endpoints["review"], repo=repo)
issue_items = normalize_issue_comments(issue_payload)
review_comment_items = normalize_review_comments(review_comment_payload)
review_items = normalize_reviews(review_payload)
all_items = issue_items + review_comment_items + review_items
seen_issue = {str(x) for x in state.get("seen_issue_comment_ids") or []}
seen_review_comment = {str(x) for x in state.get("seen_review_comment_ids") or []}
seen_review = {str(x) for x in state.get("seen_review_ids") or []}
# On a brand-new state file, surface existing review activity instead of
# silently treating it as seen. This avoids missing already-pending review
# feedback when monitoring starts after comments were posted.
new_items = []
for item in all_items:
item_id = item.get("id")
if not item_id:
continue
author = item.get("author") or ""
if not author:
continue
if is_bot_login(author):
if not is_actionable_review_bot_login(author):
continue
elif not is_trusted_human_review_author(item, authenticated_login):
continue
kind = item["kind"]
if kind == "issue_comment" and item_id in seen_issue:
continue
if kind == "review_comment" and item_id in seen_review_comment:
continue
if kind == "review" and item_id in seen_review:
continue
new_items.append(item)
if kind == "issue_comment":
seen_issue.add(item_id)
elif kind == "review_comment":
seen_review_comment.add(item_id)
elif kind == "review":
seen_review.add(item_id)
new_items.sort(key=lambda item: (item.get("created_at") or "", item.get("kind") or "", item.get("id") or ""))
state["seen_issue_comment_ids"] = sorted(seen_issue)
state["seen_review_comment_ids"] = sorted(seen_review_comment)
state["seen_review_ids"] = sorted(seen_review)
return new_items
def current_retry_count(state, head_sha):
retries = state.get("retries_by_sha") or {}
value = retries.get(head_sha, 0)
try:
return int(value)
except (TypeError, ValueError):
return 0
def set_retry_count(state, head_sha, count):
retries = state.get("retries_by_sha")
if not isinstance(retries, dict):
retries = {}
retries[head_sha] = int(count)
state["retries_by_sha"] = retries
def unique_actions(actions):
out = []
seen = set()
for action in actions:
if action not in seen:
out.append(action)
seen.add(action)
return out
def is_pr_ready_to_merge(pr, checks_summary, new_review_items):
if pr["closed"] or pr["merged"]:
return False
if not checks_summary["all_terminal"]:
return False
if checks_summary["failed_count"] > 0 or checks_summary["pending_count"] > 0:
return False
if new_review_items:
return False
if str(pr.get("mergeable") or "") != "MERGEABLE":
return False
if str(pr.get("merge_state_status") or "") in MERGE_CONFLICT_OR_BLOCKING_STATES:
return False
if str(pr.get("review_decision") or "") in MERGE_BLOCKING_REVIEW_DECISIONS:
return False
return True
def recommend_actions(pr, checks_summary, failed_runs, new_review_items, retries_used, max_retries):
actions = []
if pr["closed"] or pr["merged"]:
if new_review_items:
actions.append("process_review_comment")
actions.append("stop_pr_closed")
return unique_actions(actions)
if is_pr_ready_to_merge(pr, checks_summary, new_review_items):
actions.append("stop_ready_to_merge")
return unique_actions(actions)
if new_review_items:
actions.append("process_review_comment")
has_failed_pr_checks = checks_summary["failed_count"] > 0
if has_failed_pr_checks:
if checks_summary["all_terminal"] and retries_used >= max_retries:
actions.append("stop_exhausted_retries")
else:
actions.append("diagnose_ci_failure")
if checks_summary["all_terminal"] and failed_runs and retries_used < max_retries:
actions.append("retry_failed_checks")
if not actions:
actions.append("idle")
return unique_actions(actions)
def collect_snapshot(args):
pr = resolve_pr(args.pr, repo_override=args.repo)
state_path = Path(args.state_file) if args.state_file else default_state_file_for(pr)
state, fresh_state = load_state(state_path)
if not state.get("started_at"):
state["started_at"] = int(time.time())
# `gh pr checks -R <repo>` requires an explicit PR/branch/url argument.
# After resolving `--pr auto`, reuse the concrete PR number.
checks = get_pr_checks(str(pr["number"]), repo=pr["repo"])
checks_summary = summarize_checks(checks)
workflow_runs = get_workflow_runs_for_sha(pr["repo"], pr["head_sha"])
failed_runs = failed_runs_from_workflow_runs(workflow_runs, pr["head_sha"])
authenticated_login = get_authenticated_login()
new_review_items = fetch_new_review_items(
pr,
state,
fresh_state=fresh_state,
authenticated_login=authenticated_login,
)
retries_used = current_retry_count(state, pr["head_sha"])
actions = recommend_actions(
pr,
checks_summary,
failed_runs,
new_review_items,
retries_used,
args.max_flaky_retries,
)
state["pr"] = {"repo": pr["repo"], "number": pr["number"]}
state["last_seen_head_sha"] = pr["head_sha"]
state["last_snapshot_at"] = int(time.time())
save_state(state_path, state)
snapshot = {
"pr": pr,
"checks": checks_summary,
"failed_runs": failed_runs,
"new_review_items": new_review_items,
"actions": actions,
"retry_state": {
"current_sha_retries_used": retries_used,
"max_flaky_retries": args.max_flaky_retries,
},
}
return snapshot, state_path
def retry_failed_now(args):
snapshot, state_path = collect_snapshot(args)
pr = snapshot["pr"]
checks_summary = snapshot["checks"]
failed_runs = snapshot["failed_runs"]
retries_used = snapshot["retry_state"]["current_sha_retries_used"]
max_retries = snapshot["retry_state"]["max_flaky_retries"]
result = {
"snapshot": snapshot,
"state_file": str(state_path),
"rerun_attempted": False,
"rerun_count": 0,
"rerun_run_ids": [],
"reason": None,
}
if pr["closed"] or pr["merged"]:
result["reason"] = "pr_closed"
return result
if checks_summary["failed_count"] <= 0:
result["reason"] = "no_failed_pr_checks"
return result
if not failed_runs:
result["reason"] = "no_failed_runs"
return result
if not checks_summary["all_terminal"]:
result["reason"] = "checks_still_pending"
return result
if retries_used >= max_retries:
result["reason"] = "retry_budget_exhausted"
return result
for run in failed_runs:
run_id = run.get("run_id")
if run_id in (None, ""):
continue
gh_text(["run", "rerun", str(run_id), "--failed"], repo=pr["repo"])
result["rerun_run_ids"].append(run_id)
if result["rerun_run_ids"]:
state, _ = load_state(state_path)
new_count = current_retry_count(state, pr["head_sha"]) + 1
set_retry_count(state, pr["head_sha"], new_count)
state["last_snapshot_at"] = int(time.time())
save_state(state_path, state)
result["rerun_attempted"] = True
result["rerun_count"] = len(result["rerun_run_ids"])
result["reason"] = "rerun_triggered"
else:
result["reason"] = "failed_runs_missing_ids"
return result
def print_json(obj):
sys.stdout.write(json.dumps(obj, sort_keys=True) + "\n")
sys.stdout.flush()
def print_event(event, payload):
print_json({"event": event, "payload": payload})
def is_ci_green(snapshot):
checks = snapshot.get("checks") or {}
return (
bool(checks.get("all_terminal"))
and int(checks.get("failed_count") or 0) == 0
and int(checks.get("pending_count") or 0) == 0
)
def snapshot_change_key(snapshot):
pr = snapshot.get("pr") or {}
checks = snapshot.get("checks") or {}
review_items = snapshot.get("new_review_items") or []
return (
str(pr.get("head_sha") or ""),
str(pr.get("state") or ""),
str(pr.get("mergeable") or ""),
str(pr.get("merge_state_status") or ""),
str(pr.get("review_decision") or ""),
int(checks.get("passed_count") or 0),
int(checks.get("failed_count") or 0),
int(checks.get("pending_count") or 0),
tuple(
(str(item.get("kind") or ""), str(item.get("id") or ""))
for item in review_items
if isinstance(item, dict)
),
tuple(snapshot.get("actions") or []),
)
def run_watch(args):
poll_seconds = args.poll_seconds
last_change_key = None
while True:
snapshot, state_path = collect_snapshot(args)
print_event(
"snapshot",
{
"snapshot": snapshot,
"state_file": str(state_path),
"next_poll_seconds": poll_seconds,
},
)
actions = set(snapshot.get("actions") or [])
if (
"stop_pr_closed" in actions
or "stop_exhausted_retries" in actions
or "stop_ready_to_merge" in actions
):
print_event("stop", {"actions": snapshot.get("actions"), "pr": snapshot.get("pr")})
return 0
current_change_key = snapshot_change_key(snapshot)
changed = current_change_key != last_change_key
green = is_ci_green(snapshot)
if not green:
poll_seconds = args.poll_seconds
elif changed or last_change_key is None:
poll_seconds = args.poll_seconds
else:
poll_seconds = min(poll_seconds * 2, GREEN_STATE_MAX_POLL_SECONDS)
last_change_key = current_change_key
time.sleep(poll_seconds)
def main():
args = parse_args()
try:
if args.retry_failed_now:
print_json(retry_failed_now(args))
return 0
if args.watch:
return run_watch(args)
snapshot, state_path = collect_snapshot(args)
snapshot["state_file"] = str(state_path)
print_json(snapshot)
return 0
except (GhCommandError, RuntimeError, ValueError) as err:
sys.stderr.write(f"gh_pr_watch.py error: {err}\n")
return 1
except KeyboardInterrupt:
sys.stderr.write("gh_pr_watch.py interrupted\n")
return 130
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -47,11 +47,6 @@ jobs:
steps:
- uses: actions/checkout@v6
- name: Set up Node.js for js_repl tests
uses: actions/setup-node@v6
with:
node-version-file: codex-rs/node-version.txt
# Some integration tests rely on DotSlash being installed.
# See https://github.com/openai/codex/pull/7617.
- name: Install DotSlash
@@ -112,45 +107,6 @@ jobs:
BUILDBUDDY_API_KEY: ${{ secrets.BUILDBUDDY_API_KEY }}
shell: bash
run: |
set -o pipefail
bazel_console_log="$(mktemp)"
print_failed_bazel_test_logs() {
local console_log="$1"
local testlogs_dir
testlogs_dir="$(bazel $BAZEL_STARTUP_ARGS info bazel-testlogs 2>/dev/null || echo bazel-testlogs)"
local failed_targets=()
while IFS= read -r target; do
failed_targets+=("$target")
done < <(
grep -E '^FAIL: //' "$console_log" \
| sed -E 's#^FAIL: (//[^ ]+).*#\1#' \
| sort -u
)
if [[ ${#failed_targets[@]} -eq 0 ]]; then
echo "No failed Bazel test targets were found in console output."
return
fi
for target in "${failed_targets[@]}"; do
local rel_path="${target#//}"
rel_path="${rel_path/:/\/}"
local test_log="${testlogs_dir}/${rel_path}/test.log"
echo "::group::Bazel test log tail for ${target}"
if [[ -f "$test_log" ]]; then
tail -n 200 "$test_log"
else
echo "Missing test log: $test_log"
fi
echo "::endgroup::"
done
}
bazel_args=(
test
//...
@@ -161,28 +117,12 @@ jobs:
--build_metadata=VISIBILITY=PUBLIC
)
if [[ "${RUNNER_OS:-}" != "Windows" ]]; then
# Bazel test sandboxes on macOS may resolve an older Homebrew `node`
# before the `actions/setup-node` runtime on PATH.
node_bin="$(which node)"
bazel_args+=("--test_env=CODEX_JS_REPL_NODE_PATH=${node_bin}")
fi
if [[ -n "${BUILDBUDDY_API_KEY:-}" ]]; then
echo "BuildBuddy API key is available; using remote Bazel configuration."
# Work around Bazel 9 remote repo contents cache / overlay materialization failures
# seen in CI (for example "is not a symlink" or permission errors while
# materializing external repos such as rules_perl). We still use BuildBuddy for
# remote execution/cache; this only disables the startup-level repo contents cache.
set +e
bazel $BAZEL_STARTUP_ARGS \
--noexperimental_remote_repo_contents_cache \
--bazelrc=.github/workflows/ci.bazelrc \
"${bazel_args[@]}" \
"--remote_header=x-buildbuddy-api-key=$BUILDBUDDY_API_KEY" \
2>&1 | tee "$bazel_console_log"
bazel_status=${PIPESTATUS[0]}
set -e
"--remote_header=x-buildbuddy-api-key=$BUILDBUDDY_API_KEY"
else
echo "BuildBuddy API key is not available; using local Bazel configuration."
# Keep fork/community PRs on Bazel but disable remote services that are
@@ -201,18 +141,9 @@ jobs:
# clear remote cache/execution endpoints configured in .bazelrc.
# https://bazel.build/reference/command-line-reference#common_options-flag--remote_cache
# https://bazel.build/reference/command-line-reference#common_options-flag--remote_executor
set +e
bazel $BAZEL_STARTUP_ARGS \
--noexperimental_remote_repo_contents_cache \
"${bazel_args[@]}" \
--remote_cache= \
--remote_executor= \
2>&1 | tee "$bazel_console_log"
bazel_status=${PIPESTATUS[0]}
set -e
fi
if [[ ${bazel_status:-0} -ne 0 ]]; then
print_failed_bazel_test_logs "$bazel_console_log"
exit "$bazel_status"
--remote_executor=
fi

View File

@@ -499,10 +499,6 @@ jobs:
steps:
- uses: actions/checkout@v6
- name: Set up Node.js for js_repl tests
uses: actions/setup-node@v6
with:
node-version-file: codex-rs/node-version.txt
- name: Install Linux build dependencies
if: ${{ runner.os == 'Linux' }}
shell: bash

View File

@@ -178,12 +178,6 @@ jobs:
shell: bash
run: |
set -euo pipefail
# Avoid problematic aws-lc jitter entropy code path on musl builders.
echo "AWS_LC_SYS_NO_JITTER_ENTROPY=1" >> "$GITHUB_ENV"
target_no_jitter="AWS_LC_SYS_NO_JITTER_ENTROPY_${{ matrix.target }}"
target_no_jitter="${target_no_jitter//-/_}"
echo "${target_no_jitter}=1" >> "$GITHUB_ENV"
# Clear global Rust flags so host/proc-macro builds don't pull in UBSan.
echo "RUSTFLAGS=" >> "$GITHUB_ENV"
echo "CARGO_ENCODED_RUSTFLAGS=" >> "$GITHUB_ENV"

View File

@@ -67,6 +67,128 @@ jobs:
echo "npm_tag=${npm_tag}" >> "$GITHUB_OUTPUT"
echo "should_publish=${should_publish}" >> "$GITHUB_OUTPUT"
rust-binaries:
name: Build Rust - ${{ matrix.target }}
needs: metadata
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
env:
CARGO_PROFILE_RELEASE_LTO: ${{ contains(needs.metadata.outputs.version, '-alpha') && 'thin' || 'fat' }}
defaults:
run:
working-directory: codex-rs
strategy:
fail-fast: false
matrix:
include:
- runner: macos-15-xlarge
target: aarch64-apple-darwin
- runner: macos-15-xlarge
target: x86_64-apple-darwin
- runner: ubuntu-24.04
target: x86_64-unknown-linux-musl
install_musl: true
- runner: ubuntu-24.04-arm
target: aarch64-unknown-linux-musl
install_musl: true
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Install UBSan runtime (musl)
if: ${{ matrix.install_musl }}
shell: bash
run: |
set -euo pipefail
if command -v apt-get >/dev/null 2>&1; then
sudo apt-get update -y
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y libubsan1
fi
- uses: dtolnay/rust-toolchain@1.93.0
with:
targets: ${{ matrix.target }}
- if: ${{ matrix.install_musl }}
name: Install Zig
uses: mlugg/setup-zig@v2
with:
version: 0.14.0
- if: ${{ matrix.install_musl }}
name: Install musl build dependencies
env:
TARGET: ${{ matrix.target }}
run: bash "${GITHUB_WORKSPACE}/.github/scripts/install-musl-build-tools.sh"
- if: ${{ matrix.install_musl }}
name: Configure rustc UBSan wrapper (musl host)
shell: bash
run: |
set -euo pipefail
ubsan=""
if command -v ldconfig >/dev/null 2>&1; then
ubsan="$(ldconfig -p | grep -m1 'libubsan\.so\.1' | sed -E 's/.*=> (.*)$/\1/')"
fi
wrapper_root="${RUNNER_TEMP:-/tmp}"
wrapper="${wrapper_root}/rustc-ubsan-wrapper"
cat > "${wrapper}" <<EOF
#!/usr/bin/env bash
set -euo pipefail
if [[ -n "${ubsan}" ]]; then
export LD_PRELOAD="${ubsan}\${LD_PRELOAD:+:\${LD_PRELOAD}}"
fi
exec "\$1" "\${@:2}"
EOF
chmod +x "${wrapper}"
echo "RUSTC_WRAPPER=${wrapper}" >> "$GITHUB_ENV"
echo "RUSTC_WORKSPACE_WRAPPER=" >> "$GITHUB_ENV"
- if: ${{ matrix.install_musl }}
name: Clear sanitizer flags (musl)
shell: bash
run: |
set -euo pipefail
# Clear global Rust flags so host/proc-macro builds don't pull in UBSan.
echo "RUSTFLAGS=" >> "$GITHUB_ENV"
echo "CARGO_ENCODED_RUSTFLAGS=" >> "$GITHUB_ENV"
echo "RUSTDOCFLAGS=" >> "$GITHUB_ENV"
# Override any runner-level Cargo config rustflags as well.
echo "CARGO_BUILD_RUSTFLAGS=" >> "$GITHUB_ENV"
echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV"
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV"
echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV"
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV"
sanitize_flags() {
local input="$1"
input="${input//-fsanitize=undefined/}"
input="${input//-fno-sanitize-recover=undefined/}"
input="${input//-fno-sanitize-trap=undefined/}"
echo "$input"
}
cflags="$(sanitize_flags "${CFLAGS-}")"
cxxflags="$(sanitize_flags "${CXXFLAGS-}")"
echo "CFLAGS=${cflags}" >> "$GITHUB_ENV"
echo "CXXFLAGS=${cxxflags}" >> "$GITHUB_ENV"
- name: Build exec server binaries
run: cargo build --release --target ${{ matrix.target }} --bin codex-exec-mcp-server --bin codex-execve-wrapper
- name: Stage exec server binaries
run: |
dest="${GITHUB_WORKSPACE}/artifacts/vendor/${{ matrix.target }}"
mkdir -p "$dest"
cp "target/${{ matrix.target }}/release/codex-exec-mcp-server" "$dest/"
cp "target/${{ matrix.target }}/release/codex-execve-wrapper" "$dest/"
- uses: actions/upload-artifact@v6
with:
name: shell-tool-mcp-rust-${{ matrix.target }}
path: artifacts/**
if-no-files-found: error
bash-linux:
name: Build Bash (Linux) - ${{ matrix.variant }} - ${{ matrix.target }}
needs: metadata
@@ -415,6 +537,7 @@ jobs:
name: Package npm module
needs:
- metadata
- rust-binaries
- bash-linux
- bash-darwin
- zsh-linux
@@ -456,6 +579,7 @@ jobs:
mkdir -p "$staging" "$staging/vendor"
cp shell-tool-mcp/README.md "$staging/"
cp shell-tool-mcp/package.json "$staging/"
cp -R shell-tool-mcp/bin "$staging/"
found_vendor="false"
shopt -s nullglob
@@ -489,6 +613,8 @@ jobs:
set -euo pipefail
staging="${{ steps.staging.outputs.dir }}"
chmod +x \
"$staging"/vendor/*/codex-exec-mcp-server \
"$staging"/vendor/*/codex-execve-wrapper \
"$staging"/vendor/*/bash/*/bash \
"$staging"/vendor/*/zsh/*/zsh

View File

@@ -24,7 +24,7 @@ In the codex-rs folder where the rust code lives:
Run `just fmt` (in `codex-rs` directory) automatically after you have finished making Rust code changes; do not ask for approval to run it. Additionally, run the tests:
1. Run the test for the specific project that was changed. For example, if changes were made in `codex-rs/tui`, run `cargo test -p codex-tui`.
2. Once those pass, if any changes were made in common, core, or protocol, run the complete test suite with `cargo test` (or `just test` if `cargo-nextest` is installed). Avoid `--all-features` for routine local runs because it expands the build matrix and can significantly increase `target/` disk usage; use it only when you specifically need full feature coverage. project-specific or individual tests can be run without asking the user, but do ask the user before running the complete test suite.
2. Once those pass, if any changes were made in common, core, or protocol, run the complete test suite with `cargo test --all-features`. project-specific or individual tests can be run without asking the user, but do ask the user before running the complete test suite.
Before finalizing a large change to `codex-rs`, run `just fix -p <project>` (in `codex-rs` directory) to fix any linter issues in the code. Prefer scoping with `-p` to avoid slow workspacewide Clippy builds; only run `just fix` without `-p` if you changed shared crates. Do not re-run tests after running `fix` or `fmt`.

View File

@@ -1,11 +1,4 @@
load("@apple_support//xcode:xcode_config.bzl", "xcode_config")
load("@rules_cc//cc:defs.bzl", "cc_shared_library")
cc_shared_library(
name = "clang",
deps = ["@llvm-project//clang:libclang"],
visibility = ["//visibility:public"],
)
xcode_config(name = "disable_xcode")

View File

@@ -1,7 +1,5 @@
module(name = "codex")
bazel_dep(name = "platforms", version = "1.0.0")
bazel_dep(name = "toolchains_llvm_bootstrapped", version = "0.5.6")
bazel_dep(name = "toolchains_llvm_bootstrapped", version = "0.5.3")
single_version_override(
module_name = "toolchains_llvm_bootstrapped",
patch_strip = 1,
@@ -10,8 +8,6 @@ single_version_override(
],
)
register_toolchains("@toolchains_llvm_bootstrapped//toolchain:all")
osx = use_extension("@toolchains_llvm_bootstrapped//extensions:osx.bzl", "osx")
osx.framework(name = "ApplicationServices")
osx.framework(name = "AppKit")
@@ -20,12 +16,8 @@ osx.framework(name = "CoreFoundation")
osx.framework(name = "CoreGraphics")
osx.framework(name = "CoreServices")
osx.framework(name = "CoreText")
osx.framework(name = "AudioToolbox")
osx.framework(name = "CFNetwork")
osx.framework(name = "FontServices")
osx.framework(name = "AudioUnit")
osx.framework(name = "CoreAudio")
osx.framework(name = "CoreAudioTypes")
osx.framework(name = "Foundation")
osx.framework(name = "ImageIO")
osx.framework(name = "IOKit")
@@ -33,7 +25,10 @@ osx.framework(name = "Kernel")
osx.framework(name = "OSLog")
osx.framework(name = "Security")
osx.framework(name = "SystemConfiguration")
use_repo(osx, "macosx15.4.sdk")
register_toolchains(
"@toolchains_llvm_bootstrapped//toolchain:all",
)
# Needed to disable xcode...
bazel_dep(name = "apple_support", version = "2.1.0")
@@ -44,9 +39,9 @@ bazel_dep(name = "rules_rs", version = "0.0.23")
# Special toolchains branch
archive_override(
module_name = "rules_rs",
integrity = "sha256-O34UF4H7b1Qacu3vlu2Od4ILGVApzg5j1zl952SFL3w=",
strip_prefix = "rules_rs-097123c2aa72672e371e69e7035869f5a45c7b2b",
url = "https://github.com/dzbarsky/rules_rs/archive/097123c2aa72672e371e69e7035869f5a45c7b2b.tar.gz",
integrity = "sha256-YbDRjZos4UmfIPY98znK1BgBWRQ1/ui3CtL6RqxE30I=",
strip_prefix = "rules_rs-6cf3d940fdc48baf3ebd6c37daf8e0be8fc73ecb",
url = "https://github.com/dzbarsky/rules_rs/archive/6cf3d940fdc48baf3ebd6c37daf8e0be8fc73ecb.tar.gz",
)
rules_rust = use_extension("@rules_rs//rs/experimental:rules_rust.bzl", "rules_rust")
@@ -139,9 +134,6 @@ crate.annotation(
"OPENSSL_NO_VENDOR": "1",
"OPENSSL_STATIC": "1",
},
crate_features = [
"dep:openssl-src",
],
crate = "openssl-sys",
data = ["@openssl//:gen_dir"],
)
@@ -153,28 +145,6 @@ crate.annotation(
workspace_cargo_toml = "rust/runfiles/Cargo.toml",
)
llvm = use_extension("@toolchains_llvm_bootstrapped//extensions:llvm.bzl", "llvm")
use_repo(llvm, "llvm-project")
crate.annotation(
# Provide the hermetic SDK path so the build script doesn't try to invoke an unhermetic `xcrun --show-sdk-path`.
build_script_data = [
"@macosx15.4.sdk//sysroot",
],
build_script_env = {
"BINDGEN_EXTRA_CLANG_ARGS": "-isystem $(location @toolchains_llvm_bootstrapped//:builtin_headers)",
"COREAUDIO_SDK_PATH": "$(location @macosx15.4.sdk//sysroot)",
"LIBCLANG_PATH": "$(location @codex//:clang)",
},
build_script_tools = [
"@codex//:clang",
"@toolchains_llvm_bootstrapped//:builtin_headers",
],
crate = "coreaudio-sys",
)
inject_repo(crate, "codex", "toolchains_llvm_bootstrapped", "macosx15.4.sdk")
# Fix readme inclusions
crate.annotation(
crate = "windows-link",
@@ -205,17 +175,6 @@ crate.annotation(
gen_build_script = "off",
deps = [":windows_import_lib"],
)
bazel_dep(name = "alsa_lib", version = "1.2.9.bcr.4")
crate.annotation(
crate = "alsa-sys",
gen_build_script = "off",
deps = ["@alsa_lib"],
)
inject_repo(crate, "alsa_lib")
use_repo(crate, "crates")
rbe_platform_repository = use_repo_rule("//:rbe.bzl", "rbe_platform_repository")

291
MODULE.bazel.lock generated

File diff suppressed because one or more lines are too long

1285
codex-rs/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -17,12 +17,11 @@ members = [
"cli",
"config",
"shell-command",
"shell-escalation",
"skills",
"core",
"hooks",
"secrets",
"exec",
"exec-server",
"execpolicy",
"execpolicy-legacy",
"keyring-store",
@@ -54,6 +53,7 @@ members = [
"utils/cli",
"utils/elapsed",
"utils/sandbox-summary",
"utils/sanitizer",
"utils/sleep-inhibitor",
"utils/approval-presets",
"utils/oss",
@@ -113,8 +113,6 @@ codex-responses-api-proxy = { path = "responses-api-proxy" }
codex-rmcp-client = { path = "rmcp-client" }
codex-secrets = { path = "secrets" }
codex-shell-command = { path = "shell-command" }
codex-shell-escalation = { path = "shell-escalation" }
codex-skills = { path = "skills" }
codex-state = { path = "state" }
codex-stdio-to-uds = { path = "stdio-to-uds" }
codex-tui = { path = "tui" }
@@ -133,10 +131,12 @@ codex-utils-pty = { path = "utils/pty" }
codex-utils-readiness = { path = "utils/readiness" }
codex-utils-rustls-provider = { path = "utils/rustls-provider" }
codex-utils-sandbox-summary = { path = "utils/sandbox-summary" }
codex-utils-sanitizer = { path = "utils/sanitizer" }
codex-utils-sleep-inhibitor = { path = "utils/sleep-inhibitor" }
codex-utils-string = { path = "utils/string" }
codex-windows-sandbox = { path = "windows-sandbox-rs" }
core_test_support = { path = "core/tests/common" }
exec_server_test_support = { path = "exec-server/tests/common" }
mcp_test_support = { path = "mcp-server/tests/common" }
# External
@@ -160,7 +160,6 @@ clap = "4"
clap_complete = "4"
color-eyre = "0.6.3"
crossbeam-channel = "0.5.15"
csv = "1.3.1"
crossterm = "0.28.1"
ctor = "0.6.3"
derive_more = "2"
@@ -182,13 +181,14 @@ ignore = "0.4.23"
image = { version = "^0.25.9", default-features = false }
include_dir = "0.7.4"
indexmap = "2.12.0"
indoc = "2.0"
insta = "1.46.3"
inventory = "0.3.19"
itertools = "0.14.0"
keyring = { version = "3.6", default-features = false }
landlock = "0.4.4"
lazy_static = "1"
libc = "0.2.182"
libc = "0.2.177"
log = "0.4"
lru = "0.16.3"
maplit = "1.0.2"
@@ -204,7 +204,7 @@ opentelemetry-otlp = "0.31.0"
opentelemetry-semantic-conventions = "0.31.0"
opentelemetry_sdk = "0.31.0"
os_info = "3.12.0"
owo-colors = "4.3.0"
owo-colors = "4.2.0"
path-absolutize = "3.1.1"
pathdiff = "0.2"
portable-pty = "0.9.0"
@@ -276,7 +276,7 @@ tracing-subscriber = "0.3.22"
tracing-test = "0.2.5"
tree-sitter = "0.25.10"
tree-sitter-bash = "0.25"
syntect = "5"
tree-sitter-highlight = "0.25.10"
ts-rs = "11"
tungstenite = { version = "0.27.0", features = ["deflate", "proxy"] }
uds_windows = "1.1.0"

View File

@@ -1,114 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"FileChange": {
"oneOf": [
{
"properties": {
"content": {
"type": "string"
},
"type": {
"enum": [
"add"
],
"title": "AddFileChangeType",
"type": "string"
}
},
"required": [
"content",
"type"
],
"title": "AddFileChange",
"type": "object"
},
{
"properties": {
"content": {
"type": "string"
},
"type": {
"enum": [
"delete"
],
"title": "DeleteFileChangeType",
"type": "string"
}
},
"required": [
"content",
"type"
],
"title": "DeleteFileChange",
"type": "object"
},
{
"properties": {
"move_path": {
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"update"
],
"title": "UpdateFileChangeType",
"type": "string"
},
"unified_diff": {
"type": "string"
}
},
"required": [
"type",
"unified_diff"
],
"title": "UpdateFileChange",
"type": "object"
}
]
},
"ThreadId": {
"type": "string"
}
},
"properties": {
"callId": {
"description": "Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].",
"type": "string"
},
"conversationId": {
"$ref": "#/definitions/ThreadId"
},
"fileChanges": {
"additionalProperties": {
"$ref": "#/definitions/FileChange"
},
"type": "object"
},
"grantRoot": {
"description": "When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).",
"type": [
"string",
"null"
]
},
"reason": {
"description": "Optional explanatory reason (e.g. request for extra write access).",
"type": [
"string",
"null"
]
}
},
"required": [
"callId",
"conversationId",
"fileChanges"
],
"title": "ApplyPatchApprovalParams",
"type": "object"
}

View File

@@ -1,117 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"NetworkPolicyAmendment": {
"properties": {
"action": {
"$ref": "#/definitions/NetworkPolicyRuleAction"
},
"host": {
"type": "string"
}
},
"required": [
"action",
"host"
],
"type": "object"
},
"NetworkPolicyRuleAction": {
"enum": [
"allow",
"deny"
],
"type": "string"
},
"ReviewDecision": {
"description": "User's decision in response to an ExecApprovalRequest.",
"oneOf": [
{
"description": "User has approved this command and the agent should execute it.",
"enum": [
"approved"
],
"type": "string"
},
{
"additionalProperties": false,
"description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.",
"properties": {
"approved_execpolicy_amendment": {
"properties": {
"proposed_execpolicy_amendment": {
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"proposed_execpolicy_amendment"
],
"type": "object"
}
},
"required": [
"approved_execpolicy_amendment"
],
"title": "ApprovedExecpolicyAmendmentReviewDecision",
"type": "object"
},
{
"description": "User has approved this command and wants to automatically approve any future identical instances (`command` and `cwd` match exactly) for the remainder of the session.",
"enum": [
"approved_for_session"
],
"type": "string"
},
{
"additionalProperties": false,
"description": "User chose to persist a network policy rule (allow/deny) for future requests to the same host.",
"properties": {
"network_policy_amendment": {
"properties": {
"network_policy_amendment": {
"$ref": "#/definitions/NetworkPolicyAmendment"
}
},
"required": [
"network_policy_amendment"
],
"type": "object"
}
},
"required": [
"network_policy_amendment"
],
"title": "NetworkPolicyAmendmentReviewDecision",
"type": "object"
},
{
"description": "User has denied this command and the agent should not execute it, but it should continue the session and try something else.",
"enum": [
"denied"
],
"type": "string"
},
{
"description": "User has denied this command and the agent should not do anything until the user's next command.",
"enum": [
"abort"
],
"type": "string"
}
]
}
},
"properties": {
"decision": {
"$ref": "#/definitions/ReviewDecision"
}
},
"required": [
"decision"
],
"title": "ApplyPatchApprovalResponse",
"type": "object"
}

View File

@@ -1,33 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"ChatgptAuthTokensRefreshReason": {
"oneOf": [
{
"description": "Codex attempted a backend request and received `401 Unauthorized`.",
"enum": [
"unauthorized"
],
"type": "string"
}
]
}
},
"properties": {
"previousAccountId": {
"description": "Workspace/account identifier that Codex was previously using.\n\nClients that manage multiple accounts/workspaces can use this as a hint to refresh the token for the correct workspace.\n\nThis may be `null` when the prior auth state did not include a workspace identifier (`chatgpt_account_id`).",
"type": [
"string",
"null"
]
},
"reason": {
"$ref": "#/definitions/ChatgptAuthTokensRefreshReason"
}
},
"required": [
"reason"
],
"title": "ChatgptAuthTokensRefreshParams",
"type": "object"
}

View File

@@ -1,23 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"accessToken": {
"type": "string"
},
"chatgptAccountId": {
"type": "string"
},
"chatgptPlanType": {
"type": [
"string",
"null"
]
}
},
"required": [
"accessToken",
"chatgptAccountId"
],
"title": "ChatgptAuthTokensRefreshResponse",
"type": "object"
}

View File

@@ -1,22 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"oneOf": [
{
"properties": {
"method": {
"enum": [
"initialized"
],
"title": "InitializedNotificationMethod",
"type": "string"
}
},
"required": [
"method"
],
"title": "InitializedNotification",
"type": "object"
}
],
"title": "ClientNotification"
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,330 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"AdditionalFileSystemPermissions": {
"properties": {
"read": {
"items": {
"type": "string"
},
"type": [
"array",
"null"
]
},
"write": {
"items": {
"type": "string"
},
"type": [
"array",
"null"
]
}
},
"type": "object"
},
"AdditionalMacOsPermissions": {
"properties": {
"accessibility": {
"type": [
"boolean",
"null"
]
},
"automations": {
"anyOf": [
{
"$ref": "#/definitions/MacOsAutomationValue"
},
{
"type": "null"
}
]
},
"calendar": {
"type": [
"boolean",
"null"
]
},
"preferences": {
"anyOf": [
{
"$ref": "#/definitions/MacOsPreferencesValue"
},
{
"type": "null"
}
]
}
},
"type": "object"
},
"AdditionalPermissionProfile": {
"properties": {
"fileSystem": {
"anyOf": [
{
"$ref": "#/definitions/AdditionalFileSystemPermissions"
},
{
"type": "null"
}
]
},
"macos": {
"anyOf": [
{
"$ref": "#/definitions/AdditionalMacOsPermissions"
},
{
"type": "null"
}
]
},
"network": {
"type": [
"boolean",
"null"
]
}
},
"type": "object"
},
"CommandAction": {
"oneOf": [
{
"properties": {
"command": {
"type": "string"
},
"name": {
"type": "string"
},
"path": {
"type": "string"
},
"type": {
"enum": [
"read"
],
"title": "ReadCommandActionType",
"type": "string"
}
},
"required": [
"command",
"name",
"path",
"type"
],
"title": "ReadCommandAction",
"type": "object"
},
{
"properties": {
"command": {
"type": "string"
},
"path": {
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"listFiles"
],
"title": "ListFilesCommandActionType",
"type": "string"
}
},
"required": [
"command",
"type"
],
"title": "ListFilesCommandAction",
"type": "object"
},
{
"properties": {
"command": {
"type": "string"
},
"path": {
"type": [
"string",
"null"
]
},
"query": {
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"search"
],
"title": "SearchCommandActionType",
"type": "string"
}
},
"required": [
"command",
"type"
],
"title": "SearchCommandAction",
"type": "object"
},
{
"properties": {
"command": {
"type": "string"
},
"type": {
"enum": [
"unknown"
],
"title": "UnknownCommandActionType",
"type": "string"
}
},
"required": [
"command",
"type"
],
"title": "UnknownCommandAction",
"type": "object"
}
]
},
"MacOsAutomationValue": {
"anyOf": [
{
"type": "boolean"
},
{
"items": {
"type": "string"
},
"type": "array"
}
]
},
"MacOsPreferencesValue": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "string"
}
]
},
"NetworkApprovalContext": {
"properties": {
"host": {
"type": "string"
},
"protocol": {
"$ref": "#/definitions/NetworkApprovalProtocol"
}
},
"required": [
"host",
"protocol"
],
"type": "object"
},
"NetworkApprovalProtocol": {
"enum": [
"http",
"https",
"socks5Tcp",
"socks5Udp"
],
"type": "string"
}
},
"properties": {
"approvalId": {
"description": "Unique identifier for this specific approval callback.\n\nFor regular shell/unified_exec approvals, this is null.\n\nFor zsh-exec-bridge subcommand approvals, multiple callbacks can belong to one parent `itemId`, so `approvalId` is a distinct opaque callback id (a UUID) used to disambiguate routing.",
"type": [
"string",
"null"
]
},
"command": {
"description": "The command to be executed.",
"type": [
"string",
"null"
]
},
"commandActions": {
"description": "Best-effort parsed command actions for friendly display.",
"items": {
"$ref": "#/definitions/CommandAction"
},
"type": [
"array",
"null"
]
},
"cwd": {
"description": "The command's working directory.",
"type": [
"string",
"null"
]
},
"itemId": {
"type": "string"
},
"networkApprovalContext": {
"anyOf": [
{
"$ref": "#/definitions/NetworkApprovalContext"
},
{
"type": "null"
}
],
"description": "Optional context for managed-network approval prompts."
},
"proposedExecpolicyAmendment": {
"description": "Optional proposed execpolicy amendment to allow similar commands without prompting.",
"items": {
"type": "string"
},
"type": [
"array",
"null"
]
},
"reason": {
"description": "Optional explanatory reason (e.g. request for network access).",
"type": [
"string",
"null"
]
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"itemId",
"threadId",
"turnId"
],
"title": "CommandExecutionRequestApprovalParams",
"type": "object"
}

View File

@@ -1,72 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"CommandExecutionApprovalDecision": {
"oneOf": [
{
"description": "User approved the command.",
"enum": [
"accept"
],
"type": "string"
},
{
"description": "User approved the command and future identical commands should run without prompting.",
"enum": [
"acceptForSession"
],
"type": "string"
},
{
"additionalProperties": false,
"description": "User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.",
"properties": {
"acceptWithExecpolicyAmendment": {
"properties": {
"execpolicy_amendment": {
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"execpolicy_amendment"
],
"type": "object"
}
},
"required": [
"acceptWithExecpolicyAmendment"
],
"title": "AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision",
"type": "object"
},
{
"description": "User denied the command. The agent will continue the turn.",
"enum": [
"decline"
],
"type": "string"
},
{
"description": "User denied the command. The turn will also be immediately interrupted.",
"enum": [
"cancel"
],
"type": "string"
}
]
}
},
"properties": {
"decision": {
"$ref": "#/definitions/CommandExecutionApprovalDecision"
}
},
"required": [
"decision"
],
"title": "CommandExecutionRequestApprovalResponse",
"type": "object"
}

View File

@@ -1,27 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"arguments": true,
"callId": {
"type": "string"
},
"threadId": {
"type": "string"
},
"tool": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"arguments",
"callId",
"threadId",
"tool",
"turnId"
],
"title": "DynamicToolCallParams",
"type": "object"
}

View File

@@ -1,66 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"DynamicToolCallOutputContentItem": {
"oneOf": [
{
"properties": {
"text": {
"type": "string"
},
"type": {
"enum": [
"inputText"
],
"title": "InputTextDynamicToolCallOutputContentItemType",
"type": "string"
}
},
"required": [
"text",
"type"
],
"title": "InputTextDynamicToolCallOutputContentItem",
"type": "object"
},
{
"properties": {
"imageUrl": {
"type": "string"
},
"type": {
"enum": [
"inputImage"
],
"title": "InputImageDynamicToolCallOutputContentItemType",
"type": "string"
}
},
"required": [
"imageUrl",
"type"
],
"title": "InputImageDynamicToolCallOutputContentItem",
"type": "object"
}
]
}
},
"properties": {
"contentItems": {
"items": {
"$ref": "#/definitions/DynamicToolCallOutputContentItem"
},
"type": "array"
},
"success": {
"type": "boolean"
}
},
"required": [
"contentItems",
"success"
],
"title": "DynamicToolCallResponse",
"type": "object"
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,165 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"ParsedCommand": {
"oneOf": [
{
"properties": {
"cmd": {
"type": "string"
},
"name": {
"type": "string"
},
"path": {
"description": "(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.",
"type": "string"
},
"type": {
"enum": [
"read"
],
"title": "ReadParsedCommandType",
"type": "string"
}
},
"required": [
"cmd",
"name",
"path",
"type"
],
"title": "ReadParsedCommand",
"type": "object"
},
{
"properties": {
"cmd": {
"type": "string"
},
"path": {
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"list_files"
],
"title": "ListFilesParsedCommandType",
"type": "string"
}
},
"required": [
"cmd",
"type"
],
"title": "ListFilesParsedCommand",
"type": "object"
},
{
"properties": {
"cmd": {
"type": "string"
},
"path": {
"type": [
"string",
"null"
]
},
"query": {
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"search"
],
"title": "SearchParsedCommandType",
"type": "string"
}
},
"required": [
"cmd",
"type"
],
"title": "SearchParsedCommand",
"type": "object"
},
{
"properties": {
"cmd": {
"type": "string"
},
"type": {
"enum": [
"unknown"
],
"title": "UnknownParsedCommandType",
"type": "string"
}
},
"required": [
"cmd",
"type"
],
"title": "UnknownParsedCommand",
"type": "object"
}
]
},
"ThreadId": {
"type": "string"
}
},
"properties": {
"approvalId": {
"description": "Identifier for this specific approval callback.",
"type": [
"string",
"null"
]
},
"callId": {
"description": "Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].",
"type": "string"
},
"command": {
"items": {
"type": "string"
},
"type": "array"
},
"conversationId": {
"$ref": "#/definitions/ThreadId"
},
"cwd": {
"type": "string"
},
"parsedCmd": {
"items": {
"$ref": "#/definitions/ParsedCommand"
},
"type": "array"
},
"reason": {
"type": [
"string",
"null"
]
}
},
"required": [
"callId",
"command",
"conversationId",
"cwd",
"parsedCmd"
],
"title": "ExecCommandApprovalParams",
"type": "object"
}

View File

@@ -1,117 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"NetworkPolicyAmendment": {
"properties": {
"action": {
"$ref": "#/definitions/NetworkPolicyRuleAction"
},
"host": {
"type": "string"
}
},
"required": [
"action",
"host"
],
"type": "object"
},
"NetworkPolicyRuleAction": {
"enum": [
"allow",
"deny"
],
"type": "string"
},
"ReviewDecision": {
"description": "User's decision in response to an ExecApprovalRequest.",
"oneOf": [
{
"description": "User has approved this command and the agent should execute it.",
"enum": [
"approved"
],
"type": "string"
},
{
"additionalProperties": false,
"description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.",
"properties": {
"approved_execpolicy_amendment": {
"properties": {
"proposed_execpolicy_amendment": {
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"proposed_execpolicy_amendment"
],
"type": "object"
}
},
"required": [
"approved_execpolicy_amendment"
],
"title": "ApprovedExecpolicyAmendmentReviewDecision",
"type": "object"
},
{
"description": "User has approved this command and wants to automatically approve any future identical instances (`command` and `cwd` match exactly) for the remainder of the session.",
"enum": [
"approved_for_session"
],
"type": "string"
},
{
"additionalProperties": false,
"description": "User chose to persist a network policy rule (allow/deny) for future requests to the same host.",
"properties": {
"network_policy_amendment": {
"properties": {
"network_policy_amendment": {
"$ref": "#/definitions/NetworkPolicyAmendment"
}
},
"required": [
"network_policy_amendment"
],
"type": "object"
}
},
"required": [
"network_policy_amendment"
],
"title": "NetworkPolicyAmendmentReviewDecision",
"type": "object"
},
{
"description": "User has denied this command and the agent should not execute it, but it should continue the session and try something else.",
"enum": [
"denied"
],
"type": "string"
},
{
"description": "User has denied this command and the agent should not do anything until the user's next command.",
"enum": [
"abort"
],
"type": "string"
}
]
}
},
"properties": {
"decision": {
"$ref": "#/definitions/ReviewDecision"
}
},
"required": [
"decision"
],
"title": "ExecCommandApprovalResponse",
"type": "object"
}

View File

@@ -1,35 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"grantRoot": {
"description": "[UNSTABLE] When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).",
"type": [
"string",
"null"
]
},
"itemId": {
"type": "string"
},
"reason": {
"description": "Optional explanatory reason (e.g. request for extra write access).",
"type": [
"string",
"null"
]
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"itemId",
"threadId",
"turnId"
],
"title": "FileChangeRequestApprovalParams",
"type": "object"
}

View File

@@ -1,47 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"FileChangeApprovalDecision": {
"oneOf": [
{
"description": "User approved the file changes.",
"enum": [
"accept"
],
"type": "string"
},
{
"description": "User approved the file changes and future changes to the same files should run without prompting.",
"enum": [
"acceptForSession"
],
"type": "string"
},
{
"description": "User denied the file changes. The agent will continue the turn.",
"enum": [
"decline"
],
"type": "string"
},
{
"description": "User denied the file changes. The turn will also be immediately interrupted.",
"enum": [
"cancel"
],
"type": "string"
}
]
}
},
"properties": {
"decision": {
"$ref": "#/definitions/FileChangeApprovalDecision"
}
},
"required": [
"decision"
],
"title": "FileChangeRequestApprovalResponse",
"type": "object"
}

View File

@@ -1,26 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"cancellationToken": {
"type": [
"string",
"null"
]
},
"query": {
"type": "string"
},
"roots": {
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"query",
"roots"
],
"title": "FuzzyFileSearchParams",
"type": "object"
}

View File

@@ -1,55 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"FuzzyFileSearchResult": {
"description": "Superset of [`codex_file_search::FileMatch`]",
"properties": {
"file_name": {
"type": "string"
},
"indices": {
"items": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"type": [
"array",
"null"
]
},
"path": {
"type": "string"
},
"root": {
"type": "string"
},
"score": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
}
},
"required": [
"file_name",
"path",
"root",
"score"
],
"type": "object"
}
},
"properties": {
"files": {
"items": {
"$ref": "#/definitions/FuzzyFileSearchResult"
},
"type": "array"
}
},
"required": [
"files"
],
"title": "FuzzyFileSearchResponse",
"type": "object"
}

View File

@@ -1,13 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"sessionId": {
"type": "string"
}
},
"required": [
"sessionId"
],
"title": "FuzzyFileSearchSessionCompletedNotification",
"type": "object"
}

View File

@@ -1,63 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"FuzzyFileSearchResult": {
"description": "Superset of [`codex_file_search::FileMatch`]",
"properties": {
"file_name": {
"type": "string"
},
"indices": {
"items": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
},
"type": [
"array",
"null"
]
},
"path": {
"type": "string"
},
"root": {
"type": "string"
},
"score": {
"format": "uint32",
"minimum": 0.0,
"type": "integer"
}
},
"required": [
"file_name",
"path",
"root",
"score"
],
"type": "object"
}
},
"properties": {
"files": {
"items": {
"$ref": "#/definitions/FuzzyFileSearchResult"
},
"type": "array"
},
"query": {
"type": "string"
},
"sessionId": {
"type": "string"
}
},
"required": [
"files",
"query",
"sessionId"
],
"title": "FuzzyFileSearchSessionUpdatedNotification",
"type": "object"
}

View File

@@ -1,48 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"JSONRPCErrorError": {
"properties": {
"code": {
"format": "int64",
"type": "integer"
},
"data": true,
"message": {
"type": "string"
}
},
"required": [
"code",
"message"
],
"type": "object"
},
"RequestId": {
"anyOf": [
{
"type": "string"
},
{
"format": "int64",
"type": "integer"
}
]
}
},
"description": "A response to a request that indicates an error occurred.",
"properties": {
"error": {
"$ref": "#/definitions/JSONRPCErrorError"
},
"id": {
"$ref": "#/definitions/RequestId"
}
},
"required": [
"error",
"id"
],
"title": "JSONRPCError",
"type": "object"
}

View File

@@ -1,19 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"code": {
"format": "int64",
"type": "integer"
},
"data": true,
"message": {
"type": "string"
}
},
"required": [
"code",
"message"
],
"title": "JSONRPCErrorError",
"type": "object"
}

View File

@@ -1,109 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"anyOf": [
{
"$ref": "#/definitions/JSONRPCRequest"
},
{
"$ref": "#/definitions/JSONRPCNotification"
},
{
"$ref": "#/definitions/JSONRPCResponse"
},
{
"$ref": "#/definitions/JSONRPCError"
}
],
"definitions": {
"JSONRPCError": {
"description": "A response to a request that indicates an error occurred.",
"properties": {
"error": {
"$ref": "#/definitions/JSONRPCErrorError"
},
"id": {
"$ref": "#/definitions/RequestId"
}
},
"required": [
"error",
"id"
],
"type": "object"
},
"JSONRPCErrorError": {
"properties": {
"code": {
"format": "int64",
"type": "integer"
},
"data": true,
"message": {
"type": "string"
}
},
"required": [
"code",
"message"
],
"type": "object"
},
"JSONRPCNotification": {
"description": "A notification which does not expect a response.",
"properties": {
"method": {
"type": "string"
},
"params": true
},
"required": [
"method"
],
"type": "object"
},
"JSONRPCRequest": {
"description": "A request that expects a response.",
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"type": "string"
},
"params": true
},
"required": [
"id",
"method"
],
"type": "object"
},
"JSONRPCResponse": {
"description": "A successful (non-error) response to a request.",
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"result": true
},
"required": [
"id",
"result"
],
"type": "object"
},
"RequestId": {
"anyOf": [
{
"type": "string"
},
{
"format": "int64",
"type": "integer"
}
]
}
},
"description": "Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.",
"title": "JSONRPCMessage"
}

View File

@@ -1,15 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "A notification which does not expect a response.",
"properties": {
"method": {
"type": "string"
},
"params": true
},
"required": [
"method"
],
"title": "JSONRPCNotification",
"type": "object"
}

View File

@@ -1,32 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"RequestId": {
"anyOf": [
{
"type": "string"
},
{
"format": "int64",
"type": "integer"
}
]
}
},
"description": "A request that expects a response.",
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"type": "string"
},
"params": true
},
"required": [
"id",
"method"
],
"title": "JSONRPCRequest",
"type": "object"
}

View File

@@ -1,29 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"RequestId": {
"anyOf": [
{
"type": "string"
},
{
"format": "int64",
"type": "integer"
}
]
}
},
"description": "A successful (non-error) response to a request.",
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"result": true
},
"required": [
"id",
"result"
],
"title": "JSONRPCResponse",
"type": "object"
}

View File

@@ -1,13 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"anyOf": [
{
"type": "string"
},
{
"format": "int64",
"type": "integer"
}
],
"title": "RequestId"
}

View File

@@ -1,994 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"AdditionalFileSystemPermissions": {
"properties": {
"read": {
"items": {
"type": "string"
},
"type": [
"array",
"null"
]
},
"write": {
"items": {
"type": "string"
},
"type": [
"array",
"null"
]
}
},
"type": "object"
},
"AdditionalMacOsPermissions": {
"properties": {
"accessibility": {
"type": [
"boolean",
"null"
]
},
"automations": {
"anyOf": [
{
"$ref": "#/definitions/MacOsAutomationValue"
},
{
"type": "null"
}
]
},
"calendar": {
"type": [
"boolean",
"null"
]
},
"preferences": {
"anyOf": [
{
"$ref": "#/definitions/MacOsPreferencesValue"
},
{
"type": "null"
}
]
}
},
"type": "object"
},
"AdditionalPermissionProfile": {
"properties": {
"fileSystem": {
"anyOf": [
{
"$ref": "#/definitions/AdditionalFileSystemPermissions"
},
{
"type": "null"
}
]
},
"macos": {
"anyOf": [
{
"$ref": "#/definitions/AdditionalMacOsPermissions"
},
{
"type": "null"
}
]
},
"network": {
"type": [
"boolean",
"null"
]
}
},
"type": "object"
},
"ApplyPatchApprovalParams": {
"properties": {
"callId": {
"description": "Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].",
"type": "string"
},
"conversationId": {
"$ref": "#/definitions/ThreadId"
},
"fileChanges": {
"additionalProperties": {
"$ref": "#/definitions/FileChange"
},
"type": "object"
},
"grantRoot": {
"description": "When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).",
"type": [
"string",
"null"
]
},
"reason": {
"description": "Optional explanatory reason (e.g. request for extra write access).",
"type": [
"string",
"null"
]
}
},
"required": [
"callId",
"conversationId",
"fileChanges"
],
"type": "object"
},
"ChatgptAuthTokensRefreshParams": {
"properties": {
"previousAccountId": {
"description": "Workspace/account identifier that Codex was previously using.\n\nClients that manage multiple accounts/workspaces can use this as a hint to refresh the token for the correct workspace.\n\nThis may be `null` when the prior auth state did not include a workspace identifier (`chatgpt_account_id`).",
"type": [
"string",
"null"
]
},
"reason": {
"$ref": "#/definitions/ChatgptAuthTokensRefreshReason"
}
},
"required": [
"reason"
],
"type": "object"
},
"ChatgptAuthTokensRefreshReason": {
"oneOf": [
{
"description": "Codex attempted a backend request and received `401 Unauthorized`.",
"enum": [
"unauthorized"
],
"type": "string"
}
]
},
"CommandAction": {
"oneOf": [
{
"properties": {
"command": {
"type": "string"
},
"name": {
"type": "string"
},
"path": {
"type": "string"
},
"type": {
"enum": [
"read"
],
"title": "ReadCommandActionType",
"type": "string"
}
},
"required": [
"command",
"name",
"path",
"type"
],
"title": "ReadCommandAction",
"type": "object"
},
{
"properties": {
"command": {
"type": "string"
},
"path": {
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"listFiles"
],
"title": "ListFilesCommandActionType",
"type": "string"
}
},
"required": [
"command",
"type"
],
"title": "ListFilesCommandAction",
"type": "object"
},
{
"properties": {
"command": {
"type": "string"
},
"path": {
"type": [
"string",
"null"
]
},
"query": {
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"search"
],
"title": "SearchCommandActionType",
"type": "string"
}
},
"required": [
"command",
"type"
],
"title": "SearchCommandAction",
"type": "object"
},
{
"properties": {
"command": {
"type": "string"
},
"type": {
"enum": [
"unknown"
],
"title": "UnknownCommandActionType",
"type": "string"
}
},
"required": [
"command",
"type"
],
"title": "UnknownCommandAction",
"type": "object"
}
]
},
"CommandExecutionRequestApprovalParams": {
"properties": {
"approvalId": {
"description": "Unique identifier for this specific approval callback.\n\nFor regular shell/unified_exec approvals, this is null.\n\nFor zsh-exec-bridge subcommand approvals, multiple callbacks can belong to one parent `itemId`, so `approvalId` is a distinct opaque callback id (a UUID) used to disambiguate routing.",
"type": [
"string",
"null"
]
},
"command": {
"description": "The command to be executed.",
"type": [
"string",
"null"
]
},
"commandActions": {
"description": "Best-effort parsed command actions for friendly display.",
"items": {
"$ref": "#/definitions/CommandAction"
},
"type": [
"array",
"null"
]
},
"cwd": {
"description": "The command's working directory.",
"type": [
"string",
"null"
]
},
"itemId": {
"type": "string"
},
"networkApprovalContext": {
"anyOf": [
{
"$ref": "#/definitions/NetworkApprovalContext"
},
{
"type": "null"
}
],
"description": "Optional context for managed-network approval prompts."
},
"proposedExecpolicyAmendment": {
"description": "Optional proposed execpolicy amendment to allow similar commands without prompting.",
"items": {
"type": "string"
},
"type": [
"array",
"null"
]
},
"reason": {
"description": "Optional explanatory reason (e.g. request for network access).",
"type": [
"string",
"null"
]
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"itemId",
"threadId",
"turnId"
],
"type": "object"
},
"DynamicToolCallParams": {
"properties": {
"arguments": true,
"callId": {
"type": "string"
},
"threadId": {
"type": "string"
},
"tool": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"arguments",
"callId",
"threadId",
"tool",
"turnId"
],
"type": "object"
},
"ExecCommandApprovalParams": {
"properties": {
"approvalId": {
"description": "Identifier for this specific approval callback.",
"type": [
"string",
"null"
]
},
"callId": {
"description": "Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].",
"type": "string"
},
"command": {
"items": {
"type": "string"
},
"type": "array"
},
"conversationId": {
"$ref": "#/definitions/ThreadId"
},
"cwd": {
"type": "string"
},
"parsedCmd": {
"items": {
"$ref": "#/definitions/ParsedCommand"
},
"type": "array"
},
"reason": {
"type": [
"string",
"null"
]
}
},
"required": [
"callId",
"command",
"conversationId",
"cwd",
"parsedCmd"
],
"type": "object"
},
"FileChange": {
"oneOf": [
{
"properties": {
"content": {
"type": "string"
},
"type": {
"enum": [
"add"
],
"title": "AddFileChangeType",
"type": "string"
}
},
"required": [
"content",
"type"
],
"title": "AddFileChange",
"type": "object"
},
{
"properties": {
"content": {
"type": "string"
},
"type": {
"enum": [
"delete"
],
"title": "DeleteFileChangeType",
"type": "string"
}
},
"required": [
"content",
"type"
],
"title": "DeleteFileChange",
"type": "object"
},
{
"properties": {
"move_path": {
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"update"
],
"title": "UpdateFileChangeType",
"type": "string"
},
"unified_diff": {
"type": "string"
}
},
"required": [
"type",
"unified_diff"
],
"title": "UpdateFileChange",
"type": "object"
}
]
},
"FileChangeRequestApprovalParams": {
"properties": {
"grantRoot": {
"description": "[UNSTABLE] When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).",
"type": [
"string",
"null"
]
},
"itemId": {
"type": "string"
},
"reason": {
"description": "Optional explanatory reason (e.g. request for extra write access).",
"type": [
"string",
"null"
]
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"itemId",
"threadId",
"turnId"
],
"type": "object"
},
"MacOsAutomationValue": {
"anyOf": [
{
"type": "boolean"
},
{
"items": {
"type": "string"
},
"type": "array"
}
]
},
"MacOsPreferencesValue": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "string"
}
]
},
"NetworkApprovalContext": {
"properties": {
"host": {
"type": "string"
},
"protocol": {
"$ref": "#/definitions/NetworkApprovalProtocol"
}
},
"required": [
"host",
"protocol"
],
"type": "object"
},
"NetworkApprovalProtocol": {
"enum": [
"http",
"https",
"socks5Tcp",
"socks5Udp"
],
"type": "string"
},
"ParsedCommand": {
"oneOf": [
{
"properties": {
"cmd": {
"type": "string"
},
"name": {
"type": "string"
},
"path": {
"description": "(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.",
"type": "string"
},
"type": {
"enum": [
"read"
],
"title": "ReadParsedCommandType",
"type": "string"
}
},
"required": [
"cmd",
"name",
"path",
"type"
],
"title": "ReadParsedCommand",
"type": "object"
},
{
"properties": {
"cmd": {
"type": "string"
},
"path": {
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"list_files"
],
"title": "ListFilesParsedCommandType",
"type": "string"
}
},
"required": [
"cmd",
"type"
],
"title": "ListFilesParsedCommand",
"type": "object"
},
{
"properties": {
"cmd": {
"type": "string"
},
"path": {
"type": [
"string",
"null"
]
},
"query": {
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"search"
],
"title": "SearchParsedCommandType",
"type": "string"
}
},
"required": [
"cmd",
"type"
],
"title": "SearchParsedCommand",
"type": "object"
},
{
"properties": {
"cmd": {
"type": "string"
},
"type": {
"enum": [
"unknown"
],
"title": "UnknownParsedCommandType",
"type": "string"
}
},
"required": [
"cmd",
"type"
],
"title": "UnknownParsedCommand",
"type": "object"
}
]
},
"RequestId": {
"anyOf": [
{
"type": "string"
},
{
"format": "int64",
"type": "integer"
}
]
},
"SkillRequestApprovalParams": {
"properties": {
"itemId": {
"type": "string"
},
"skillName": {
"type": "string"
}
},
"required": [
"itemId",
"skillName"
],
"type": "object"
},
"ThreadId": {
"type": "string"
},
"ToolRequestUserInputOption": {
"description": "EXPERIMENTAL. Defines a single selectable option for request_user_input.",
"properties": {
"description": {
"type": "string"
},
"label": {
"type": "string"
}
},
"required": [
"description",
"label"
],
"type": "object"
},
"ToolRequestUserInputParams": {
"description": "EXPERIMENTAL. Params sent with a request_user_input event.",
"properties": {
"itemId": {
"type": "string"
},
"questions": {
"items": {
"$ref": "#/definitions/ToolRequestUserInputQuestion"
},
"type": "array"
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"itemId",
"questions",
"threadId",
"turnId"
],
"type": "object"
},
"ToolRequestUserInputQuestion": {
"description": "EXPERIMENTAL. Represents one request_user_input question and its required options.",
"properties": {
"header": {
"type": "string"
},
"id": {
"type": "string"
},
"isOther": {
"default": false,
"type": "boolean"
},
"isSecret": {
"default": false,
"type": "boolean"
},
"options": {
"items": {
"$ref": "#/definitions/ToolRequestUserInputOption"
},
"type": [
"array",
"null"
]
},
"question": {
"type": "string"
}
},
"required": [
"header",
"id",
"question"
],
"type": "object"
}
},
"description": "Request initiated from the server and sent to the client.",
"oneOf": [
{
"description": "NEW APIs Sent when approval is requested for a specific command execution. This request is used for Turns started via turn/start.",
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"item/commandExecution/requestApproval"
],
"title": "Item/commandExecution/requestApprovalRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/CommandExecutionRequestApprovalParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Item/commandExecution/requestApprovalRequest",
"type": "object"
},
{
"description": "Sent when approval is requested for a specific file change. This request is used for Turns started via turn/start.",
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"item/fileChange/requestApproval"
],
"title": "Item/fileChange/requestApprovalRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/FileChangeRequestApprovalParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Item/fileChange/requestApprovalRequest",
"type": "object"
},
{
"description": "EXPERIMENTAL - Request input from the user for a tool call.",
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"item/tool/requestUserInput"
],
"title": "Item/tool/requestUserInputRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/ToolRequestUserInputParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Item/tool/requestUserInputRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"skill/requestApproval"
],
"title": "Skill/requestApprovalRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/SkillRequestApprovalParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Skill/requestApprovalRequest",
"type": "object"
},
{
"description": "Execute a dynamic tool call on the client.",
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"item/tool/call"
],
"title": "Item/tool/callRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/DynamicToolCallParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Item/tool/callRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"account/chatgptAuthTokens/refresh"
],
"title": "Account/chatgptAuthTokens/refreshRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/ChatgptAuthTokensRefreshParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Account/chatgptAuthTokens/refreshRequest",
"type": "object"
},
{
"description": "DEPRECATED APIs below Request to approve a patch. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).",
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"applyPatchApproval"
],
"title": "ApplyPatchApprovalRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/ApplyPatchApprovalParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "ApplyPatchApprovalRequest",
"type": "object"
},
{
"description": "Request to exec a command. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).",
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"execCommandApproval"
],
"title": "ExecCommandApprovalRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/ExecCommandApprovalParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "ExecCommandApprovalRequest",
"type": "object"
}
],
"title": "ServerRequest"
}

View File

@@ -1,17 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"itemId": {
"type": "string"
},
"skillName": {
"type": "string"
}
},
"required": [
"itemId",
"skillName"
],
"title": "SkillRequestApprovalParams",
"type": "object"
}

View File

@@ -1,22 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"SkillApprovalDecision": {
"enum": [
"approve",
"decline"
],
"type": "string"
}
},
"properties": {
"decision": {
"$ref": "#/definitions/SkillApprovalDecision"
}
},
"required": [
"decision"
],
"title": "SkillRequestApprovalResponse",
"type": "object"
}

View File

@@ -1,84 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"ToolRequestUserInputOption": {
"description": "EXPERIMENTAL. Defines a single selectable option for request_user_input.",
"properties": {
"description": {
"type": "string"
},
"label": {
"type": "string"
}
},
"required": [
"description",
"label"
],
"type": "object"
},
"ToolRequestUserInputQuestion": {
"description": "EXPERIMENTAL. Represents one request_user_input question and its required options.",
"properties": {
"header": {
"type": "string"
},
"id": {
"type": "string"
},
"isOther": {
"default": false,
"type": "boolean"
},
"isSecret": {
"default": false,
"type": "boolean"
},
"options": {
"items": {
"$ref": "#/definitions/ToolRequestUserInputOption"
},
"type": [
"array",
"null"
]
},
"question": {
"type": "string"
}
},
"required": [
"header",
"id",
"question"
],
"type": "object"
}
},
"description": "EXPERIMENTAL. Params sent with a request_user_input event.",
"properties": {
"itemId": {
"type": "string"
},
"questions": {
"items": {
"$ref": "#/definitions/ToolRequestUserInputQuestion"
},
"type": "array"
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"itemId",
"questions",
"threadId",
"turnId"
],
"title": "ToolRequestUserInputParams",
"type": "object"
}

View File

@@ -1,34 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"ToolRequestUserInputAnswer": {
"description": "EXPERIMENTAL. Captures a user's answer to a request_user_input question.",
"properties": {
"answers": {
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"answers"
],
"type": "object"
}
},
"description": "EXPERIMENTAL. Response payload mapping question ids to answers.",
"properties": {
"answers": {
"additionalProperties": {
"$ref": "#/definitions/ToolRequestUserInputAnswer"
},
"type": "object"
}
},
"required": [
"answers"
],
"title": "ToolRequestUserInputResponse",
"type": "object"
}

View File

@@ -1,67 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"ClientInfo": {
"properties": {
"name": {
"type": "string"
},
"title": {
"type": [
"string",
"null"
]
},
"version": {
"type": "string"
}
},
"required": [
"name",
"version"
],
"type": "object"
},
"InitializeCapabilities": {
"description": "Client-declared capabilities negotiated during initialize.",
"properties": {
"experimentalApi": {
"default": false,
"description": "Opt into receiving experimental API methods and fields.",
"type": "boolean"
},
"optOutNotificationMethods": {
"description": "Exact notification method names that should be suppressed for this connection (for example `codex/event/session_configured`).",
"items": {
"type": "string"
},
"type": [
"array",
"null"
]
}
},
"type": "object"
}
},
"properties": {
"capabilities": {
"anyOf": [
{
"$ref": "#/definitions/InitializeCapabilities"
},
{
"type": "null"
}
]
},
"clientInfo": {
"$ref": "#/definitions/ClientInfo"
}
},
"required": [
"clientInfo"
],
"title": "InitializeParams",
"type": "object"
}

View File

@@ -1,13 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"userAgent": {
"type": "string"
}
},
"required": [
"userAgent"
],
"title": "InitializeResponse",
"type": "object"
}

View File

@@ -237,23 +237,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"PatchApplyStatus": {
"enum": [

View File

@@ -237,23 +237,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"PatchApplyStatus": {
"enum": [

View File

@@ -351,23 +351,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"PatchApplyStatus": {
"enum": [

View File

@@ -420,23 +420,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"NetworkAccess": {
"enum": [
@@ -848,13 +836,6 @@
"description": "Model provider used for this thread (for example, 'openai').",
"type": "string"
},
"name": {
"description": "Optional user-facing thread title.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [

View File

@@ -374,23 +374,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"PatchApplyStatus": {
"enum": [
@@ -621,13 +609,6 @@
"description": "Model provider used for this thread (for example, 'openai').",
"type": "string"
},
"name": {
"description": "Optional user-facing thread title.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [

View File

@@ -374,23 +374,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"PatchApplyStatus": {
"enum": [
@@ -621,13 +609,6 @@
"description": "Model provider used for this thread (for example, 'openai').",
"type": "string"
},
"name": {
"description": "Optional user-facing thread title.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [

View File

@@ -420,23 +420,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"NetworkAccess": {
"enum": [
@@ -848,13 +836,6 @@
"description": "Model provider used for this thread (for example, 'openai').",
"type": "string"
},
"name": {
"description": "Optional user-facing thread title.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [

View File

@@ -374,23 +374,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"PatchApplyStatus": {
"enum": [
@@ -621,13 +609,6 @@
"description": "Model provider used for this thread (for example, 'openai').",
"type": "string"
},
"name": {
"description": "Optional user-facing thread title.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [

View File

@@ -420,23 +420,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"NetworkAccess": {
"enum": [
@@ -848,13 +836,6 @@
"description": "Model provider used for this thread (for example, 'openai').",
"type": "string"
},
"name": {
"description": "Optional user-facing thread title.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [

View File

@@ -374,23 +374,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"PatchApplyStatus": {
"enum": [
@@ -621,13 +609,6 @@
"description": "Model provider used for this thread (for example, 'openai').",
"type": "string"
},
"name": {
"description": "Optional user-facing thread title.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [

View File

@@ -374,23 +374,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"PatchApplyStatus": {
"enum": [
@@ -621,13 +609,6 @@
"description": "Model provider used for this thread (for example, 'openai').",
"type": "string"
},
"name": {
"description": "Optional user-facing thread title.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [

View File

@@ -351,23 +351,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"PatchApplyStatus": {
"enum": [

View File

@@ -351,23 +351,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"PatchApplyStatus": {
"enum": [

View File

@@ -351,23 +351,11 @@
"type": "string"
},
"MessagePhase": {
"description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.",
"oneOf": [
{
"description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
"enum": [
"commentary"
],
"type": "string"
},
{
"description": "The assistant's terminal answer text for the current turn.",
"enum": [
"final_answer"
],
"type": "string"
}
]
"enum": [
"commentary",
"finalAnswer"
],
"type": "string"
},
"PatchApplyStatus": {
"enum": [

View File

@@ -6,8 +6,8 @@ import type { ThreadId } from "./ThreadId";
export type ApplyPatchApprovalParams = { conversationId: ThreadId,
/**
* Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent]
* and [codex_protocol::protocol::PatchApplyEndEvent].
* Use to correlate this with [codex_core::protocol::PatchApplyBeginEvent]
* and [codex_core::protocol::PatchApplyEndEvent].
*/
callId: string, fileChanges: { [key in string]?: FileChange },
/**

View File

@@ -47,16 +47,12 @@ import type { PatchApplyBeginEvent } from "./PatchApplyBeginEvent";
import type { PatchApplyEndEvent } from "./PatchApplyEndEvent";
import type { PlanDeltaEvent } from "./PlanDeltaEvent";
import type { RawResponseItemEvent } from "./RawResponseItemEvent";
import type { RealtimeConversationClosedEvent } from "./RealtimeConversationClosedEvent";
import type { RealtimeConversationRealtimeEvent } from "./RealtimeConversationRealtimeEvent";
import type { RealtimeConversationStartedEvent } from "./RealtimeConversationStartedEvent";
import type { ReasoningContentDeltaEvent } from "./ReasoningContentDeltaEvent";
import type { ReasoningRawContentDeltaEvent } from "./ReasoningRawContentDeltaEvent";
import type { RemoteSkillDownloadedEvent } from "./RemoteSkillDownloadedEvent";
import type { RequestUserInputEvent } from "./RequestUserInputEvent";
import type { ReviewRequest } from "./ReviewRequest";
import type { SessionConfiguredEvent } from "./SessionConfiguredEvent";
import type { SkillRequestApprovalEvent } from "./SkillRequestApprovalEvent";
import type { StreamErrorEvent } from "./StreamErrorEvent";
import type { TerminalInteractionEvent } from "./TerminalInteractionEvent";
import type { ThreadNameUpdatedEvent } from "./ThreadNameUpdatedEvent";
@@ -79,4 +75,4 @@ import type { WebSearchEndEvent } from "./WebSearchEndEvent";
* Response event from the agent
* NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen.
*/
export type EventMsg = { "type": "error" } & ErrorEvent | { "type": "warning" } & WarningEvent | { "type": "realtime_conversation_started" } & RealtimeConversationStartedEvent | { "type": "realtime_conversation_realtime" } & RealtimeConversationRealtimeEvent | { "type": "realtime_conversation_closed" } & RealtimeConversationClosedEvent | { "type": "model_reroute" } & ModelRerouteEvent | { "type": "context_compacted" } & ContextCompactedEvent | { "type": "thread_rolled_back" } & ThreadRolledBackEvent | { "type": "task_started" } & TurnStartedEvent | { "type": "task_complete" } & TurnCompleteEvent | { "type": "token_count" } & TokenCountEvent | { "type": "agent_message" } & AgentMessageEvent | { "type": "user_message" } & UserMessageEvent | { "type": "agent_message_delta" } & AgentMessageDeltaEvent | { "type": "agent_reasoning" } & AgentReasoningEvent | { "type": "agent_reasoning_delta" } & AgentReasoningDeltaEvent | { "type": "agent_reasoning_raw_content" } & AgentReasoningRawContentEvent | { "type": "agent_reasoning_raw_content_delta" } & AgentReasoningRawContentDeltaEvent | { "type": "agent_reasoning_section_break" } & AgentReasoningSectionBreakEvent | { "type": "session_configured" } & SessionConfiguredEvent | { "type": "thread_name_updated" } & ThreadNameUpdatedEvent | { "type": "mcp_startup_update" } & McpStartupUpdateEvent | { "type": "mcp_startup_complete" } & McpStartupCompleteEvent | { "type": "mcp_tool_call_begin" } & McpToolCallBeginEvent | { "type": "mcp_tool_call_end" } & McpToolCallEndEvent | { "type": "web_search_begin" } & WebSearchBeginEvent | { "type": "web_search_end" } & WebSearchEndEvent | { "type": "exec_command_begin" } & ExecCommandBeginEvent | { "type": "exec_command_output_delta" } & ExecCommandOutputDeltaEvent | { "type": "terminal_interaction" } & TerminalInteractionEvent | { "type": "exec_command_end" } & ExecCommandEndEvent | { "type": "view_image_tool_call" } & ViewImageToolCallEvent | { "type": "exec_approval_request" } & ExecApprovalRequestEvent | { "type": "request_user_input" } & RequestUserInputEvent | { "type": "dynamic_tool_call_request" } & DynamicToolCallRequest | { "type": "skill_request_approval" } & SkillRequestApprovalEvent | { "type": "elicitation_request" } & ElicitationRequestEvent | { "type": "apply_patch_approval_request" } & ApplyPatchApprovalRequestEvent | { "type": "deprecation_notice" } & DeprecationNoticeEvent | { "type": "background_event" } & BackgroundEventEvent | { "type": "undo_started" } & UndoStartedEvent | { "type": "undo_completed" } & UndoCompletedEvent | { "type": "stream_error" } & StreamErrorEvent | { "type": "patch_apply_begin" } & PatchApplyBeginEvent | { "type": "patch_apply_end" } & PatchApplyEndEvent | { "type": "turn_diff" } & TurnDiffEvent | { "type": "get_history_entry_response" } & GetHistoryEntryResponseEvent | { "type": "mcp_list_tools_response" } & McpListToolsResponseEvent | { "type": "list_custom_prompts_response" } & ListCustomPromptsResponseEvent | { "type": "list_skills_response" } & ListSkillsResponseEvent | { "type": "list_remote_skills_response" } & ListRemoteSkillsResponseEvent | { "type": "remote_skill_downloaded" } & RemoteSkillDownloadedEvent | { "type": "skills_update_available" } | { "type": "plan_update" } & UpdatePlanArgs | { "type": "turn_aborted" } & TurnAbortedEvent | { "type": "shutdown_complete" } | { "type": "entered_review_mode" } & ReviewRequest | { "type": "exited_review_mode" } & ExitedReviewModeEvent | { "type": "raw_response_item" } & RawResponseItemEvent | { "type": "item_started" } & ItemStartedEvent | { "type": "item_completed" } & ItemCompletedEvent | { "type": "agent_message_content_delta" } & AgentMessageContentDeltaEvent | { "type": "plan_delta" } & PlanDeltaEvent | { "type": "reasoning_content_delta" } & ReasoningContentDeltaEvent | { "type": "reasoning_raw_content_delta" } & ReasoningRawContentDeltaEvent | { "type": "collab_agent_spawn_begin" } & CollabAgentSpawnBeginEvent | { "type": "collab_agent_spawn_end" } & CollabAgentSpawnEndEvent | { "type": "collab_agent_interaction_begin" } & CollabAgentInteractionBeginEvent | { "type": "collab_agent_interaction_end" } & CollabAgentInteractionEndEvent | { "type": "collab_waiting_begin" } & CollabWaitingBeginEvent | { "type": "collab_waiting_end" } & CollabWaitingEndEvent | { "type": "collab_close_begin" } & CollabCloseBeginEvent | { "type": "collab_close_end" } & CollabCloseEndEvent | { "type": "collab_resume_begin" } & CollabResumeBeginEvent | { "type": "collab_resume_end" } & CollabResumeEndEvent;
export type EventMsg = { "type": "error" } & ErrorEvent | { "type": "warning" } & WarningEvent | { "type": "model_reroute" } & ModelRerouteEvent | { "type": "context_compacted" } & ContextCompactedEvent | { "type": "thread_rolled_back" } & ThreadRolledBackEvent | { "type": "task_started" } & TurnStartedEvent | { "type": "task_complete" } & TurnCompleteEvent | { "type": "token_count" } & TokenCountEvent | { "type": "agent_message" } & AgentMessageEvent | { "type": "user_message" } & UserMessageEvent | { "type": "agent_message_delta" } & AgentMessageDeltaEvent | { "type": "agent_reasoning" } & AgentReasoningEvent | { "type": "agent_reasoning_delta" } & AgentReasoningDeltaEvent | { "type": "agent_reasoning_raw_content" } & AgentReasoningRawContentEvent | { "type": "agent_reasoning_raw_content_delta" } & AgentReasoningRawContentDeltaEvent | { "type": "agent_reasoning_section_break" } & AgentReasoningSectionBreakEvent | { "type": "session_configured" } & SessionConfiguredEvent | { "type": "thread_name_updated" } & ThreadNameUpdatedEvent | { "type": "mcp_startup_update" } & McpStartupUpdateEvent | { "type": "mcp_startup_complete" } & McpStartupCompleteEvent | { "type": "mcp_tool_call_begin" } & McpToolCallBeginEvent | { "type": "mcp_tool_call_end" } & McpToolCallEndEvent | { "type": "web_search_begin" } & WebSearchBeginEvent | { "type": "web_search_end" } & WebSearchEndEvent | { "type": "exec_command_begin" } & ExecCommandBeginEvent | { "type": "exec_command_output_delta" } & ExecCommandOutputDeltaEvent | { "type": "terminal_interaction" } & TerminalInteractionEvent | { "type": "exec_command_end" } & ExecCommandEndEvent | { "type": "view_image_tool_call" } & ViewImageToolCallEvent | { "type": "exec_approval_request" } & ExecApprovalRequestEvent | { "type": "request_user_input" } & RequestUserInputEvent | { "type": "dynamic_tool_call_request" } & DynamicToolCallRequest | { "type": "elicitation_request" } & ElicitationRequestEvent | { "type": "apply_patch_approval_request" } & ApplyPatchApprovalRequestEvent | { "type": "deprecation_notice" } & DeprecationNoticeEvent | { "type": "background_event" } & BackgroundEventEvent | { "type": "undo_started" } & UndoStartedEvent | { "type": "undo_completed" } & UndoCompletedEvent | { "type": "stream_error" } & StreamErrorEvent | { "type": "patch_apply_begin" } & PatchApplyBeginEvent | { "type": "patch_apply_end" } & PatchApplyEndEvent | { "type": "turn_diff" } & TurnDiffEvent | { "type": "get_history_entry_response" } & GetHistoryEntryResponseEvent | { "type": "mcp_list_tools_response" } & McpListToolsResponseEvent | { "type": "list_custom_prompts_response" } & ListCustomPromptsResponseEvent | { "type": "list_skills_response" } & ListSkillsResponseEvent | { "type": "list_remote_skills_response" } & ListRemoteSkillsResponseEvent | { "type": "remote_skill_downloaded" } & RemoteSkillDownloadedEvent | { "type": "skills_update_available" } | { "type": "plan_update" } & UpdatePlanArgs | { "type": "turn_aborted" } & TurnAbortedEvent | { "type": "shutdown_complete" } | { "type": "entered_review_mode" } & ReviewRequest | { "type": "exited_review_mode" } & ExitedReviewModeEvent | { "type": "raw_response_item" } & RawResponseItemEvent | { "type": "item_started" } & ItemStartedEvent | { "type": "item_completed" } & ItemCompletedEvent | { "type": "agent_message_content_delta" } & AgentMessageContentDeltaEvent | { "type": "plan_delta" } & PlanDeltaEvent | { "type": "reasoning_content_delta" } & ReasoningContentDeltaEvent | { "type": "reasoning_raw_content_delta" } & ReasoningRawContentDeltaEvent | { "type": "collab_agent_spawn_begin" } & CollabAgentSpawnBeginEvent | { "type": "collab_agent_spawn_end" } & CollabAgentSpawnEndEvent | { "type": "collab_agent_interaction_begin" } & CollabAgentInteractionBeginEvent | { "type": "collab_agent_interaction_end" } & CollabAgentInteractionEndEvent | { "type": "collab_waiting_begin" } & CollabWaitingBeginEvent | { "type": "collab_waiting_end" } & CollabWaitingEndEvent | { "type": "collab_close_begin" } & CollabCloseBeginEvent | { "type": "collab_close_end" } & CollabCloseEndEvent | { "type": "collab_resume_begin" } & CollabResumeBeginEvent | { "type": "collab_resume_end" } & CollabResumeEndEvent;

View File

@@ -3,9 +3,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ExecPolicyAmendment } from "./ExecPolicyAmendment";
import type { NetworkApprovalContext } from "./NetworkApprovalContext";
import type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment";
import type { ParsedCommand } from "./ParsedCommand";
import type { PermissionProfile } from "./PermissionProfile";
export type ExecApprovalRequestEvent = {
/**
@@ -43,12 +41,4 @@ network_approval_context?: NetworkApprovalContext,
/**
* Proposed execpolicy amendment that can be applied to allow future runs.
*/
proposed_execpolicy_amendment?: ExecPolicyAmendment,
/**
* Proposed network policy amendments (for example allow/deny this host in future).
*/
proposed_network_policy_amendments?: Array<NetworkPolicyAmendment>,
/**
* Optional additional filesystem permissions requested for this command.
*/
additional_permissions?: PermissionProfile, parsed_cmd: Array<ParsedCommand>, };
proposed_execpolicy_amendment?: ExecPolicyAmendment, parsed_cmd: Array<ParsedCommand>, };

View File

@@ -6,8 +6,8 @@ import type { ThreadId } from "./ThreadId";
export type ExecCommandApprovalParams = { conversationId: ThreadId,
/**
* Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent]
* and [codex_protocol::protocol::ExecCommandEndEvent].
* Use to correlate this with [codex_core::protocol::ExecCommandBeginEvent]
* and [codex_core::protocol::ExecCommandEndEvent].
*/
callId: string,
/**

View File

@@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type FileSystemPermissions = { read: Array<string> | null, write: Array<string> | null, };

View File

@@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type MacOsAutomationValue = boolean | Array<string>;

View File

@@ -1,7 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { MacOsAutomationValue } from "./MacOsAutomationValue";
import type { MacOsPreferencesValue } from "./MacOsPreferencesValue";
export type MacOsPermissions = { preferences: MacOsPreferencesValue | null, automations: MacOsAutomationValue | null, accessibility: boolean | null, calendar: boolean | null, };

View File

@@ -1,6 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { NetworkPolicyRuleAction } from "./NetworkPolicyRuleAction";
export type NetworkPolicyAmendment = { host: string, action: NetworkPolicyRuleAction, };

View File

@@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type NetworkPolicyRuleAction = "allow" | "deny";

View File

@@ -1,7 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { FileSystemPermissions } from "./FileSystemPermissions";
import type { MacOsPermissions } from "./MacOsPermissions";
export type PermissionProfile = { network: boolean | null, file_system: FileSystemPermissions | null, macos: MacOsPermissions | null, };

View File

@@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type RealtimeAudioFrame = { data: string, sample_rate: number, num_channels: number, samples_per_channel: number | null, };

View File

@@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type RealtimeConversationClosedEvent = { reason: string | null, };

View File

@@ -1,6 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { RealtimeEvent } from "./RealtimeEvent";
export type RealtimeConversationRealtimeEvent = { payload: RealtimeEvent, };

View File

@@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type RealtimeConversationStartedEvent = { session_id: string | null, };

View File

@@ -1,7 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { RealtimeAudioFrame } from "./RealtimeAudioFrame";
import type { JsonValue } from "./serde_json/JsonValue";
export type RealtimeEvent = { "SessionCreated": { session_id: string, } } | { "SessionUpdated": { backend_prompt: string | null, } } | { "AudioOut": RealtimeAudioFrame } | { "ConversationItemAdded": JsonValue } | { "Error": string };

View File

@@ -2,9 +2,8 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ExecPolicyAmendment } from "./ExecPolicyAmendment";
import type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment";
/**
* User's decision in response to an ExecApprovalRequest.
*/
export type ReviewDecision = "approved" | { "approved_execpolicy_amendment": { proposed_execpolicy_amendment: ExecPolicyAmendment, } } | "approved_for_session" | { "network_policy_amendment": { network_policy_amendment: NetworkPolicyAmendment, } } | "denied" | "abort";
export type ReviewDecision = "approved" | { "approved_execpolicy_amendment": { proposed_execpolicy_amendment: ExecPolicyAmendment, } } | "approved_for_session" | "denied" | "abort";

View File

@@ -8,10 +8,9 @@ import type { ChatgptAuthTokensRefreshParams } from "./v2/ChatgptAuthTokensRefre
import type { CommandExecutionRequestApprovalParams } from "./v2/CommandExecutionRequestApprovalParams";
import type { DynamicToolCallParams } from "./v2/DynamicToolCallParams";
import type { FileChangeRequestApprovalParams } from "./v2/FileChangeRequestApprovalParams";
import type { SkillRequestApprovalParams } from "./v2/SkillRequestApprovalParams";
import type { ToolRequestUserInputParams } from "./v2/ToolRequestUserInputParams";
/**
* Request initiated from the server and sent to the client.
*/
export type ServerRequest = { "method": "item/commandExecution/requestApproval", id: RequestId, params: CommandExecutionRequestApprovalParams, } | { "method": "item/fileChange/requestApproval", id: RequestId, params: FileChangeRequestApprovalParams, } | { "method": "item/tool/requestUserInput", id: RequestId, params: ToolRequestUserInputParams, } | { "method": "skill/requestApproval", id: RequestId, params: SkillRequestApprovalParams, } | { "method": "item/tool/call", id: RequestId, params: DynamicToolCallParams, } | { "method": "account/chatgptAuthTokens/refresh", id: RequestId, params: ChatgptAuthTokensRefreshParams, } | { "method": "applyPatchApproval", id: RequestId, params: ApplyPatchApprovalParams, } | { "method": "execCommandApproval", id: RequestId, params: ExecCommandApprovalParams, };
export type ServerRequest = { "method": "item/commandExecution/requestApproval", id: RequestId, params: CommandExecutionRequestApprovalParams, } | { "method": "item/fileChange/requestApproval", id: RequestId, params: FileChangeRequestApprovalParams, } | { "method": "item/tool/requestUserInput", id: RequestId, params: ToolRequestUserInputParams, } | { "method": "item/tool/call", id: RequestId, params: DynamicToolCallParams, } | { "method": "account/chatgptAuthTokens/refresh", id: RequestId, params: ChatgptAuthTokensRefreshParams, } | { "method": "applyPatchApproval", id: RequestId, params: ApplyPatchApprovalParams, } | { "method": "execCommandApproval", id: RequestId, params: ExecCommandApprovalParams, };

View File

@@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type SkillRequestApprovalEvent = { item_id: string, skill_name: string, };

View File

@@ -71,7 +71,6 @@ export type { ExecOutputStream } from "./ExecOutputStream";
export type { ExecPolicyAmendment } from "./ExecPolicyAmendment";
export type { ExitedReviewModeEvent } from "./ExitedReviewModeEvent";
export type { FileChange } from "./FileChange";
export type { FileSystemPermissions } from "./FileSystemPermissions";
export type { ForcedLoginMethod } from "./ForcedLoginMethod";
export type { ForkConversationParams } from "./ForkConversationParams";
export type { ForkConversationResponse } from "./ForkConversationResponse";
@@ -117,9 +116,6 @@ export type { LoginApiKeyResponse } from "./LoginApiKeyResponse";
export type { LoginChatGptCompleteNotification } from "./LoginChatGptCompleteNotification";
export type { LoginChatGptResponse } from "./LoginChatGptResponse";
export type { LogoutChatGptResponse } from "./LogoutChatGptResponse";
export type { MacOsAutomationValue } from "./MacOsAutomationValue";
export type { MacOsPermissions } from "./MacOsPermissions";
export type { MacOsPreferencesValue } from "./MacOsPreferencesValue";
export type { McpAuthStatus } from "./McpAuthStatus";
export type { McpInvocation } from "./McpInvocation";
export type { McpListToolsResponseEvent } from "./McpListToolsResponseEvent";
@@ -136,15 +132,12 @@ export type { ModelRerouteReason } from "./ModelRerouteReason";
export type { NetworkAccess } from "./NetworkAccess";
export type { NetworkApprovalContext } from "./NetworkApprovalContext";
export type { NetworkApprovalProtocol } from "./NetworkApprovalProtocol";
export type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment";
export type { NetworkPolicyRuleAction } from "./NetworkPolicyRuleAction";
export type { NewConversationParams } from "./NewConversationParams";
export type { NewConversationResponse } from "./NewConversationResponse";
export type { ParsedCommand } from "./ParsedCommand";
export type { PatchApplyBeginEvent } from "./PatchApplyBeginEvent";
export type { PatchApplyEndEvent } from "./PatchApplyEndEvent";
export type { PatchApplyStatus } from "./PatchApplyStatus";
export type { PermissionProfile } from "./PermissionProfile";
export type { Personality } from "./Personality";
export type { PlanDeltaEvent } from "./PlanDeltaEvent";
export type { PlanItem } from "./PlanItem";
@@ -155,11 +148,6 @@ export type { RateLimitSnapshot } from "./RateLimitSnapshot";
export type { RateLimitWindow } from "./RateLimitWindow";
export type { RawResponseItemEvent } from "./RawResponseItemEvent";
export type { ReadOnlyAccess } from "./ReadOnlyAccess";
export type { RealtimeAudioFrame } from "./RealtimeAudioFrame";
export type { RealtimeConversationClosedEvent } from "./RealtimeConversationClosedEvent";
export type { RealtimeConversationRealtimeEvent } from "./RealtimeConversationRealtimeEvent";
export type { RealtimeConversationStartedEvent } from "./RealtimeConversationStartedEvent";
export type { RealtimeEvent } from "./RealtimeEvent";
export type { ReasoningContentDeltaEvent } from "./ReasoningContentDeltaEvent";
export type { ReasoningEffort } from "./ReasoningEffort";
export type { ReasoningItem } from "./ReasoningItem";
@@ -208,7 +196,6 @@ export type { SkillDependencies } from "./SkillDependencies";
export type { SkillErrorInfo } from "./SkillErrorInfo";
export type { SkillInterface } from "./SkillInterface";
export type { SkillMetadata } from "./SkillMetadata";
export type { SkillRequestApprovalEvent } from "./SkillRequestApprovalEvent";
export type { SkillScope } from "./SkillScope";
export type { SkillToolDependency } from "./SkillToolDependency";
export type { SkillsListEntry } from "./SkillsListEntry";

View File

@@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type AdditionalFileSystemPermissions = { read: Array<string> | null, write: Array<string> | null, };

View File

@@ -1,7 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { MacOsAutomationValue } from "../MacOsAutomationValue";
import type { MacOsPreferencesValue } from "../MacOsPreferencesValue";
export type AdditionalMacOsPermissions = { preferences: MacOsPreferencesValue | null, automations: MacOsAutomationValue | null, accessibility: boolean | null, calendar: boolean | null, };

View File

@@ -1,7 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { AdditionalFileSystemPermissions } from "./AdditionalFileSystemPermissions";
import type { AdditionalMacOsPermissions } from "./AdditionalMacOsPermissions";
export type AdditionalPermissionProfile = { network: boolean | null, fileSystem: AdditionalFileSystemPermissions | null, macos: AdditionalMacOsPermissions | null, };

View File

@@ -1,7 +1,6 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { AdditionalPermissionProfile } from "./AdditionalPermissionProfile";
import type { CommandAction } from "./CommandAction";
import type { ExecPolicyAmendment } from "./ExecPolicyAmendment";
import type { NetworkApprovalContext } from "./NetworkApprovalContext";
@@ -37,10 +36,6 @@ cwd?: string | null,
* Best-effort parsed command actions for friendly display.
*/
commandActions?: Array<CommandAction> | null,
/**
* Optional additional permissions requested for this command.
*/
additionalPermissions?: AdditionalPermissionProfile | null,
/**
* Optional proposed execpolicy amendment to allow similar commands without prompting.
*/

View File

@@ -2,4 +2,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type MacOsPreferencesValue = boolean | string;
export type MessagePhase = "commentary" | "finalAnswer";

View File

@@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type SkillApprovalDecision = "approve" | "decline";

View File

@@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type SkillRequestApprovalParams = { itemId: string, skillName: string, };

View File

@@ -1,6 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { SkillApprovalDecision } from "./SkillApprovalDecision";
export type SkillRequestApprovalResponse = { decision: SkillApprovalDecision, };

View File

@@ -55,10 +55,6 @@ agentRole: string | null,
* Optional Git metadata captured when the thread was created.
*/
gitInfo: GitInfo | null,
/**
* Optional user-facing thread title.
*/
name: string | null,
/**
* Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read`
* (when `includeTurns` is true) responses.

View File

@@ -1,7 +1,6 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { MessagePhase } from "../MessagePhase";
import type { JsonValue } from "../serde_json/JsonValue";
import type { CollabAgentState } from "./CollabAgentState";
import type { CollabAgentTool } from "./CollabAgentTool";
@@ -12,6 +11,7 @@ import type { FileUpdateChange } from "./FileUpdateChange";
import type { McpToolCallError } from "./McpToolCallError";
import type { McpToolCallResult } from "./McpToolCallResult";
import type { McpToolCallStatus } from "./McpToolCallStatus";
import type { MessagePhase } from "./MessagePhase";
import type { PatchApplyStatus } from "./PatchApplyStatus";
import type { UserInput } from "./UserInput";
import type { WebSearchAction } from "./WebSearchAction";

View File

@@ -4,9 +4,6 @@ export type { Account } from "./Account";
export type { AccountLoginCompletedNotification } from "./AccountLoginCompletedNotification";
export type { AccountRateLimitsUpdatedNotification } from "./AccountRateLimitsUpdatedNotification";
export type { AccountUpdatedNotification } from "./AccountUpdatedNotification";
export type { AdditionalFileSystemPermissions } from "./AdditionalFileSystemPermissions";
export type { AdditionalMacOsPermissions } from "./AdditionalMacOsPermissions";
export type { AdditionalPermissionProfile } from "./AdditionalPermissionProfile";
export type { AgentMessageDeltaNotification } from "./AgentMessageDeltaNotification";
export type { AnalyticsConfig } from "./AnalyticsConfig";
export type { AppBranding } from "./AppBranding";
@@ -98,6 +95,7 @@ export type { McpToolCallProgressNotification } from "./McpToolCallProgressNotif
export type { McpToolCallResult } from "./McpToolCallResult";
export type { McpToolCallStatus } from "./McpToolCallStatus";
export type { MergeStrategy } from "./MergeStrategy";
export type { MessagePhase } from "./MessagePhase";
export type { Model } from "./Model";
export type { ModelListParams } from "./ModelListParams";
export type { ModelListResponse } from "./ModelListResponse";
@@ -131,13 +129,10 @@ export type { SandboxMode } from "./SandboxMode";
export type { SandboxPolicy } from "./SandboxPolicy";
export type { SandboxWorkspaceWrite } from "./SandboxWorkspaceWrite";
export type { SessionSource } from "./SessionSource";
export type { SkillApprovalDecision } from "./SkillApprovalDecision";
export type { SkillDependencies } from "./SkillDependencies";
export type { SkillErrorInfo } from "./SkillErrorInfo";
export type { SkillInterface } from "./SkillInterface";
export type { SkillMetadata } from "./SkillMetadata";
export type { SkillRequestApprovalParams } from "./SkillRequestApprovalParams";
export type { SkillRequestApprovalResponse } from "./SkillRequestApprovalResponse";
export type { SkillScope } from "./SkillScope";
export type { SkillToolDependency } from "./SkillToolDependency";
export type { SkillsConfigWriteParams } from "./SkillsConfigWriteParams";

View File

@@ -32,41 +32,15 @@ use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::sync::LazyLock;
use ts_rs::TS;
const HEADER: &str = "// GENERATED CODE! DO NOT MODIFY BY HAND!\n\n";
const IGNORED_DEFINITIONS: &[&str] = &["Option<()>"];
const JSON_V1_ALLOWLIST: &[&str] = &["InitializeParams", "InitializeResponse"];
const V1_CLIENT_REQUEST_METHODS: &[&str] = &[
"newConversation",
"getConversationSummary",
"listConversations",
"resumeConversation",
"forkConversation",
"archiveConversation",
"sendUserMessage",
"sendUserTurn",
"interruptConversation",
"addConversationListener",
"removeConversationListener",
"gitDiffToRemote",
"loginApiKey",
"loginChatGpt",
"cancelLoginChatGpt",
"logoutChatGpt",
"getAuthStatus",
"getUserSavedConfig",
"setDefaultModel",
"getUserAgent",
"userInfo",
"execOneOffCommand",
];
const EXCLUDED_SERVER_NOTIFICATION_METHODS_FOR_JSON: &[&str] = &[
"authStatusChange",
"loginChatGptComplete",
"sessionConfigured",
"rawResponseItem/completed",
];
static VARIANT_TITLE_COLLISION_OVERRIDES: LazyLock<HashMap<&'static str, &'static str>> =
LazyLock::new(HashMap::new);
static NUMBERED_DEFINITION_COLLISION_OVERRIDES: LazyLock<HashMap<&'static str, &'static str>> =
LazyLock::new(HashMap::new);
#[derive(Clone)]
pub struct GeneratedSchema {
@@ -212,8 +186,7 @@ pub fn generate_json_with_experimental(out_dir: &Path, experimental_api: bool) -
schemas.extend(export_server_response_schemas(out_dir)?);
schemas.extend(export_client_notification_schemas(out_dir)?);
schemas.extend(export_server_notification_schemas(out_dir)?);
schemas
.retain(|schema| !schema.in_v1_dir || JSON_V1_ALLOWLIST.contains(&schema.logical_name()));
schemas.retain(|schema| schema.namespace() == Some("v2"));
let mut bundle = build_schema_bundle(schemas)?;
if !experimental_api {
@@ -982,16 +955,10 @@ where
{
let file_stem = name.trim();
let (raw_namespace, logical_name) = split_namespace(file_stem);
let include_in_json_codegen =
raw_namespace != Some("v1") || JSON_V1_ALLOWLIST.contains(&logical_name);
let include_in_json_codegen = raw_namespace == Some("v2");
let schema = schema_for!(T);
let mut schema_value = serde_json::to_value(schema)?;
if include_in_json_codegen {
if file_stem == "ClientRequest" {
strip_v1_client_request_variants_from_json_schema(&mut schema_value);
} else if file_stem == "ServerNotification" {
strip_v1_server_notification_variants_from_json_schema(&mut schema_value);
}
enforce_numbered_definition_collision_overrides(file_stem, &mut schema_value);
annotate_schema(&mut schema_value, Some(file_stem));
}
@@ -1025,162 +992,96 @@ where
fn enforce_numbered_definition_collision_overrides(schema_name: &str, schema: &mut Value) {
for defs_key in ["definitions", "$defs"] {
let Some(defs) = schema.get(defs_key).and_then(Value::as_object) else {
let renames = {
let Some(defs) = schema.get(defs_key).and_then(Value::as_object) else {
continue;
};
collect_numbered_definition_collision_renames(schema_name, defs_key, defs)
};
if renames.is_empty() {
continue;
};
detect_numbered_definition_collisions(schema_name, defs_key, defs);
}
}
fn strip_v1_client_request_variants_from_json_schema(schema: &mut Value) {
let v1_methods: HashSet<&str> = V1_CLIENT_REQUEST_METHODS.iter().copied().collect();
strip_method_variants_from_json_schema(schema, &v1_methods);
}
fn strip_v1_server_notification_variants_from_json_schema(schema: &mut Value) {
let methods: HashSet<&str> = EXCLUDED_SERVER_NOTIFICATION_METHODS_FOR_JSON
.iter()
.copied()
.collect();
strip_method_variants_from_json_schema(schema, &methods);
}
fn strip_method_variants_from_json_schema(schema: &mut Value, methods_to_remove: &HashSet<&str>) {
{
let Some(root) = schema.as_object_mut() else {
return;
};
let Some(Value::Array(variants)) = root.get_mut("oneOf") else {
return;
};
variants.retain(|variant| !is_method_variant_in_set(variant, methods_to_remove));
}
let reachable = reachable_local_definitions(schema, "definitions");
let Some(root) = schema.as_object_mut() else {
return;
};
if let Some(definitions) = root.get_mut("definitions").and_then(Value::as_object_mut) {
definitions.retain(|name, _| reachable.contains(name));
}
}
fn is_method_variant_in_set(value: &Value, methods: &HashSet<&str>) -> bool {
let Value::Object(map) = value else {
return false;
};
let Some(properties) = map.get("properties").and_then(Value::as_object) else {
return false;
};
let Some(method_schema) = properties.get("method") else {
return false;
};
let Some(method) = string_literal(method_schema) else {
return false;
};
methods.contains(method)
}
fn reachable_local_definitions(schema: &Value, defs_key: &str) -> HashSet<String> {
let Some(definitions) = schema.get(defs_key).and_then(Value::as_object) else {
return HashSet::new();
};
let mut queue: Vec<String> = Vec::new();
let mut reachable: HashSet<String> = HashSet::new();
collect_local_definition_refs_excluding_maps(schema, defs_key, &mut queue, &mut reachable);
while let Some(name) = queue.pop() {
if let Some(def_schema) = definitions.get(&name) {
collect_local_definition_refs(def_schema, defs_key, &mut queue, &mut reachable);
}
}
reachable
}
fn collect_local_definition_refs_excluding_maps(
value: &Value,
defs_key: &str,
queue: &mut Vec<String>,
reachable: &mut HashSet<String>,
) {
match value {
Value::Object(map) => {
for (key, child) in map {
if key == defs_key || key == "$defs" || key == "definitions" {
continue;
}
collect_local_definition_refs_excluding_maps(child, defs_key, queue, reachable);
#[expect(clippy::expect_used)]
let defs = schema
.get_mut(defs_key)
.and_then(Value::as_object_mut)
.expect("definition map should still be present");
for (old_name, new_name, collision_key) in &renames {
if old_name == new_name {
continue;
}
assert!(
!defs.contains_key(new_name),
"Numbered definition collision override produced duplicate definition {new_name} for {collision_key}",
);
let schema_value = defs.remove(old_name).unwrap_or_else(|| {
panic!("Missing generated numbered definition {old_name} for {collision_key}")
});
defs.insert(new_name.clone(), schema_value);
}
for (old_name, new_name, _) in renames {
if old_name != new_name {
rewrite_named_local_ref(schema, defs_key, &old_name, &new_name);
}
}
Value::Array(items) => {
for child in items {
collect_local_definition_refs_excluding_maps(child, defs_key, queue, reachable);
}
}
_ => {}
}
collect_local_definition_ref_here(value, defs_key, queue, reachable);
}
fn collect_local_definition_refs(
value: &Value,
defs_key: &str,
queue: &mut Vec<String>,
reachable: &mut HashSet<String>,
) {
collect_local_definition_ref_here(value, defs_key, queue, reachable);
match value {
Value::Object(map) => {
for child in map.values() {
collect_local_definition_refs(child, defs_key, queue, reachable);
}
}
Value::Array(items) => {
for child in items {
collect_local_definition_refs(child, defs_key, queue, reachable);
}
}
_ => {}
}
}
fn collect_local_definition_ref_here(
value: &Value,
defs_key: &str,
queue: &mut Vec<String>,
reachable: &mut HashSet<String>,
) {
let Some(reference) = value
.as_object()
.and_then(|obj| obj.get("$ref"))
.and_then(Value::as_str)
else {
return;
};
let Some(name) = reference.strip_prefix(&format!("#/{defs_key}/")) else {
return;
};
let name = name.split('/').next().unwrap_or(name);
if reachable.insert(name.to_string()) {
queue.push(name.to_string());
}
}
fn detect_numbered_definition_collisions(
fn collect_numbered_definition_collision_renames(
schema_name: &str,
defs_key: &str,
defs: &Map<String, Value>,
) {
) -> Vec<(String, String, String)> {
let mut renames = Vec::new();
for generated_name in defs.keys() {
let base_name = generated_name.trim_end_matches(|c: char| c.is_ascii_digit());
if base_name == generated_name || !defs.contains_key(base_name) {
continue;
}
panic!(
"Numbered definition naming collision detected: schema={schema_name}|container={defs_key}|generated={generated_name}|base={base_name}"
let collision_key = format!(
"schema={schema_name}|container={defs_key}|generated={generated_name}|base={base_name}"
);
let replacement = NUMBERED_DEFINITION_COLLISION_OVERRIDES
.get(collision_key.as_str())
.map(|value| (*value).to_string())
.unwrap_or_else(|| {
panic!("Missing numbered definition collision override for {collision_key}")
});
renames.push((generated_name.clone(), replacement, collision_key));
}
renames
}
fn rewrite_named_local_ref(value: &mut Value, defs_key: &str, old_name: &str, new_name: &str) {
let direct = format!("#/{defs_key}/{old_name}");
let prefixed = format!("{direct}/");
let replacement = format!("#/{defs_key}/{new_name}");
let replacement_prefixed = format!("{replacement}/");
match value {
Value::Object(obj) => {
if let Some(Value::String(reference)) = obj.get_mut("$ref") {
if reference == &direct {
*reference = replacement;
} else if let Some(rest) = reference.strip_prefix(&prefixed) {
*reference = format!("{replacement_prefixed}{rest}");
}
}
for child in obj.values_mut() {
rewrite_named_local_ref(child, defs_key, old_name, new_name);
}
}
Value::Array(items) => {
for child in items {
rewrite_named_local_ref(child, defs_key, old_name, new_name);
}
}
_ => {}
}
}
@@ -1288,11 +1189,7 @@ fn variant_definition_name(base: &str, variant: &Value) -> Option<String> {
if props.len() == 1
&& let Some(key) = props.keys().next()
{
let pascal = props
.get(key)
.and_then(string_literal)
.map(to_pascal_case)
.unwrap_or_else(|| to_pascal_case(key));
let pascal = to_pascal_case(key);
return Some(format!("{pascal}{base}"));
}
}
@@ -1405,11 +1302,20 @@ fn annotate_variant_list(variants: &mut [Value], base: Option<&str>) {
&& let Some(base_name) = base
&& let Some(name) = variant_definition_name(base_name, variant)
{
let candidate = name.clone();
let mut candidate = name.clone();
if seen.contains(&candidate) {
let collision_key = variant_title_collision_key(base_name, &name, variant);
panic!(
"Variant title naming collision detected: {collision_key} (generated name: {name})"
candidate = VARIANT_TITLE_COLLISION_OVERRIDES
.get(collision_key.as_str())
.map(|value| (*value).to_string())
.unwrap_or_else(|| {
panic!(
"Missing variant title collision override for {collision_key} (generated name: {name})"
)
});
assert!(
!seen.contains(&candidate),
"Variant title collision override produced duplicate title {candidate} for {collision_key}",
);
}
if let Some(obj) = variant.as_object_mut() {
@@ -1947,15 +1853,6 @@ mod tests {
let thread_start_ts =
fs::read_to_string(output_dir.join("v2").join("ThreadStartParams.ts"))?;
assert_eq!(thread_start_ts.contains("mockExperimentalField"), true);
let command_execution_request_approval_ts = fs::read_to_string(
output_dir
.join("v2")
.join("CommandExecutionRequestApprovalParams.ts"),
)?;
assert_eq!(
command_execution_request_approval_ts.contains("additionalPermissions"),
true
);
Ok(())
}
@@ -2092,12 +1989,6 @@ export type Config = { stableField: Keep, unstableField: string | null } & ({ [k
let thread_start_json =
fs::read_to_string(output_dir.join("v2").join("ThreadStartParams.json"))?;
assert_eq!(thread_start_json.contains("mockExperimentalField"), false);
let command_execution_request_approval_json =
fs::read_to_string(output_dir.join("CommandExecutionRequestApprovalParams.json"))?;
assert_eq!(
command_execution_request_approval_json.contains("additionalPermissions"),
false
);
let client_request_json = fs::read_to_string(output_dir.join("ClientRequest.json"))?;
assert_eq!(
@@ -2108,7 +1999,6 @@ export type Config = { stableField: Keep, unstableField: string | null } & ({ [k
let bundle_json =
fs::read_to_string(output_dir.join("codex_app_server_protocol.schemas.json"))?;
assert_eq!(bundle_json.contains("mockExperimentalField"), false);
assert_eq!(bundle_json.contains("additionalPermissions"), false);
assert_eq!(bundle_json.contains("MockExperimentalMethodParams"), false);
assert_eq!(
bundle_json.contains("MockExperimentalMethodResponse"),

View File

@@ -671,11 +671,6 @@ server_request_definitions! {
response: v2::ToolRequestUserInputResponse,
},
SkillRequestApproval => "skill/requestApproval" {
params: v2::SkillRequestApprovalParams,
response: v2::SkillRequestApprovalResponse,
},
/// Execute a dynamic tool call on the client.
DynamicToolCall => "item/tool/call" {
params: v2::DynamicToolCallParams,
@@ -1371,33 +1366,4 @@ mod tests {
let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request);
assert_eq!(reason, Some("mock/experimentalMethod"));
}
#[test]
fn command_execution_request_approval_additional_permissions_is_marked_experimental() {
let params = v2::CommandExecutionRequestApprovalParams {
thread_id: "thr_123".to_string(),
turn_id: "turn_123".to_string(),
item_id: "call_123".to_string(),
approval_id: None,
reason: None,
network_approval_context: None,
command: Some("cat file".to_string()),
cwd: None,
command_actions: None,
additional_permissions: Some(v2::AdditionalPermissionProfile {
network: None,
file_system: Some(v2::AdditionalFileSystemPermissions {
read: Some(vec![std::path::PathBuf::from("/tmp/allowed")]),
write: None,
}),
macos: None,
}),
proposed_execpolicy_amendment: None,
};
let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&params);
assert_eq!(
reason,
Some("item/commandExecution/requestApproval.additionalPermissions")
);
}
}

View File

@@ -16,7 +16,7 @@ use crate::protocol::v2::TurnError;
use crate::protocol::v2::TurnStatus;
use crate::protocol::v2::UserInput;
use crate::protocol::v2::WebSearchAction;
use codex_protocol::models::MessagePhase;
use codex_protocol::models::MessagePhase as CoreMessagePhase;
use codex_protocol::protocol::AgentReasoningEvent;
use codex_protocol::protocol::AgentReasoningRawContentEvent;
use codex_protocol::protocol::AgentStatus;
@@ -190,15 +190,17 @@ impl ThreadHistoryBuilder {
self.current_turn = Some(turn);
}
fn handle_agent_message(&mut self, text: String, phase: Option<MessagePhase>) {
fn handle_agent_message(&mut self, text: String, phase: Option<CoreMessagePhase>) {
if text.is_empty() {
return;
}
let id = self.next_item_id();
self.ensure_turn()
.items
.push(ThreadItem::AgentMessage { id, text, phase });
self.ensure_turn().items.push(ThreadItem::AgentMessage {
id,
text,
phase: phase.map(Into::into),
});
}
fn handle_agent_reasoning(&mut self, payload: &AgentReasoningEvent) {
@@ -1194,7 +1196,7 @@ mod tests {
ThreadItem::AgentMessage {
id: "item-1".into(),
text: "Final reply".into(),
phase: Some(MessagePhase::FinalAnswer),
phase: Some(crate::protocol::v2::MessagePhase::FinalAnswer),
}
);
}

View File

@@ -234,8 +234,8 @@ pub struct GitDiffToRemoteResponse {
#[serde(rename_all = "camelCase")]
pub struct ApplyPatchApprovalParams {
pub conversation_id: ThreadId,
/// Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent]
/// and [codex_protocol::protocol::PatchApplyEndEvent].
/// Use to correlate this with [codex_core::protocol::PatchApplyBeginEvent]
/// and [codex_core::protocol::PatchApplyEndEvent].
pub call_id: String,
pub file_changes: HashMap<PathBuf, FileChange>,
/// Optional explanatory reason (e.g. request for extra write access).
@@ -255,8 +255,8 @@ pub struct ApplyPatchApprovalResponse {
#[serde(rename_all = "camelCase")]
pub struct ExecCommandApprovalParams {
pub conversation_id: ThreadId,
/// Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent]
/// and [codex_protocol::protocol::ExecCommandEndEvent].
/// Use to correlate this with [codex_core::protocol::ExecCommandBeginEvent]
/// and [codex_core::protocol::ExecCommandEndEvent].
pub call_id: String,
/// Identifier for this specific approval callback.
pub approval_id: Option<String>,

View File

@@ -20,12 +20,7 @@ use codex_protocol::items::TurnItem as CoreTurnItem;
use codex_protocol::mcp::Resource as McpResource;
use codex_protocol::mcp::ResourceTemplate as McpResourceTemplate;
use codex_protocol::mcp::Tool as McpTool;
use codex_protocol::models::FileSystemPermissions as CoreFileSystemPermissions;
use codex_protocol::models::MacOsAutomationValue as CoreMacOsAutomationValue;
use codex_protocol::models::MacOsPermissions as CoreMacOsPermissions;
use codex_protocol::models::MacOsPreferencesValue as CoreMacOsPreferencesValue;
use codex_protocol::models::MessagePhase;
use codex_protocol::models::PermissionProfile as CorePermissionProfile;
use codex_protocol::models::MessagePhase as CoreMessagePhase;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::InputModality;
use codex_protocol::openai_models::ReasoningEffort;
@@ -718,63 +713,6 @@ impl From<CoreNetworkApprovalContext> for NetworkApprovalContext {
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AdditionalFileSystemPermissions {
pub read: Option<Vec<PathBuf>>,
pub write: Option<Vec<PathBuf>>,
}
impl From<CoreFileSystemPermissions> for AdditionalFileSystemPermissions {
fn from(value: CoreFileSystemPermissions) -> Self {
Self {
read: value.read,
write: value.write,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AdditionalMacOsPermissions {
pub preferences: Option<CoreMacOsPreferencesValue>,
pub automations: Option<CoreMacOsAutomationValue>,
pub accessibility: Option<bool>,
pub calendar: Option<bool>,
}
impl From<CoreMacOsPermissions> for AdditionalMacOsPermissions {
fn from(value: CoreMacOsPermissions) -> Self {
Self {
preferences: value.preferences,
automations: value.automations,
accessibility: value.accessibility,
calendar: value.calendar,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AdditionalPermissionProfile {
pub network: Option<bool>,
pub file_system: Option<AdditionalFileSystemPermissions>,
pub macos: Option<AdditionalMacOsPermissions>,
}
impl From<CorePermissionProfile> for AdditionalPermissionProfile {
fn from(value: CorePermissionProfile) -> Self {
Self {
network: value.network,
file_system: value.file_system.map(AdditionalFileSystemPermissions::from),
macos: value.macos.map(AdditionalMacOsPermissions::from),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
@@ -2339,8 +2277,6 @@ pub struct Thread {
pub agent_role: Option<String>,
/// Optional Git metadata captured when the thread was created.
pub git_info: Option<GitInfo>,
/// Optional user-facing thread title.
pub name: Option<String>,
/// Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read`
/// (when `includeTurns` is true) responses.
/// For all other responses and notifications returning a Thread,
@@ -2728,6 +2664,24 @@ impl From<CoreUserInput> for UserInput {
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum MessagePhase {
Commentary,
FinalAnswer,
}
impl From<CoreMessagePhase> for MessagePhase {
fn from(value: CoreMessagePhase) -> Self {
match value {
CoreMessagePhase::Commentary => Self::Commentary,
CoreMessagePhase::FinalAnswer => Self::FinalAnswer,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type")]
@@ -2917,7 +2871,7 @@ impl From<CoreTurnItem> for ThreadItem {
ThreadItem::AgentMessage {
id: agent.id,
text,
phase: agent.phase,
phase: agent.phase.map(Into::into),
}
}
CoreTurnItem::Plan(plan) => ThreadItem::Plan {
@@ -3421,7 +3375,7 @@ pub struct ContextCompactedNotification {
pub turn_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, ExperimentalApi)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CommandExecutionRequestApprovalParams {
@@ -3458,26 +3412,12 @@ pub struct CommandExecutionRequestApprovalParams {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub command_actions: Option<Vec<CommandAction>>,
/// Optional additional permissions requested for this command.
#[experimental("item/commandExecution/requestApproval.additionalPermissions")]
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub additional_permissions: Option<AdditionalPermissionProfile>,
/// Optional proposed execpolicy amendment to allow similar commands without prompting.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
}
impl CommandExecutionRequestApprovalParams {
pub fn strip_experimental_fields(&mut self) {
// TODO: Avoid hardcoding individual experimental fields here.
// We need a generic outbound compatibility design for stripping or
// otherwise handling experimental server->client payloads.
self.additional_permissions = None;
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
@@ -3507,29 +3447,6 @@ pub struct FileChangeRequestApprovalResponse {
pub decision: FileChangeApprovalDecision,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillRequestApprovalParams {
pub item_id: String,
pub skill_name: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum SkillApprovalDecision {
Approve,
Decline,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillRequestApprovalResponse {
pub decision: SkillApprovalDecision,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
@@ -3773,6 +3690,7 @@ mod tests {
use codex_protocol::items::TurnItem;
use codex_protocol::items::UserMessageItem;
use codex_protocol::items::WebSearchItem;
use codex_protocol::models::MessagePhase as CoreMessagePhase;
use codex_protocol::models::WebSearchAction as CoreWebSearchAction;
use codex_protocol::protocol::NetworkAccess as CoreNetworkAccess;
use codex_protocol::protocol::ReadOnlyAccess as CoreReadOnlyAccess;
@@ -3982,7 +3900,7 @@ mod tests {
content: vec![AgentMessageContent::Text {
text: "final".to_string(),
}],
phase: Some(MessagePhase::FinalAnswer),
phase: Some(CoreMessagePhase::FinalAnswer),
});
assert_eq!(

View File

@@ -2,7 +2,6 @@ use std::collections::VecDeque;
use std::ffi::OsString;
use std::fs;
use std::fs::OpenOptions;
use std::io;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Write;
@@ -33,7 +32,6 @@ use codex_app_server_protocol::CommandExecutionRequestApprovalParams;
use codex_app_server_protocol::CommandExecutionRequestApprovalResponse;
use codex_app_server_protocol::CommandExecutionStatus;
use codex_app_server_protocol::DynamicToolSpec;
use codex_app_server_protocol::ExecPolicyAmendment;
use codex_app_server_protocol::FileChangeApprovalDecision;
use codex_app_server_protocol::FileChangeRequestApprovalParams;
use codex_app_server_protocol::FileChangeRequestApprovalResponse;
@@ -59,9 +57,6 @@ use codex_app_server_protocol::SendUserMessageParams;
use codex_app_server_protocol::SendUserMessageResponse;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ServerRequest;
use codex_app_server_protocol::SkillApprovalDecision;
use codex_app_server_protocol::SkillRequestApprovalParams;
use codex_app_server_protocol::SkillRequestApprovalResponse;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadListParams;
use codex_app_server_protocol::ThreadListResponse;
@@ -148,28 +143,10 @@ struct Cli {
#[arg(long, value_name = "json-or-@file", global = true)]
dynamic_tools: Option<String>,
/// Attach a skill input item to V2 turn/start requests.
///
/// Must be paired with --skill-path.
#[arg(long, value_name = "skill-name", global = true)]
skill_name: Option<String>,
/// Path to the SKILL.md file for --skill-name.
///
/// Must be paired with --skill-name.
#[arg(long, value_name = "path-to-skill-md", global = true)]
skill_path: Option<PathBuf>,
#[command(subcommand)]
command: CliCommand,
}
#[derive(Clone, Debug)]
struct SkillSelection {
name: String,
path: PathBuf,
}
#[derive(Subcommand)]
enum CliCommand {
/// Start `codex app-server` on a websocket endpoint in the background.
@@ -191,9 +168,6 @@ enum CliCommand {
},
/// Send a user message through the app-server V2 thread/turn APIs.
SendMessageV2 {
/// Opt into experimental app-server methods and fields.
#[arg(long)]
experimental_api: bool,
/// User message to send to Codex.
user_message: String,
},
@@ -267,40 +241,25 @@ pub fn run() -> Result<()> {
url,
config_overrides,
dynamic_tools,
skill_name,
skill_path,
command,
} = Cli::parse();
let dynamic_tools = parse_dynamic_tools_arg(&dynamic_tools)?;
let skill_selection = parse_skill_selection(skill_name, skill_path)?;
match command {
CliCommand::Serve { listen, kill } => {
ensure_dynamic_tools_unused(&dynamic_tools, "serve")?;
ensure_skill_unused(&skill_selection, "serve")?;
let codex_bin = codex_bin.unwrap_or_else(|| PathBuf::from("codex"));
serve(&codex_bin, &config_overrides, &listen, kill)
}
CliCommand::SendMessage { user_message } => {
ensure_dynamic_tools_unused(&dynamic_tools, "send-message")?;
ensure_skill_unused(&skill_selection, "send-message")?;
let endpoint = resolve_endpoint(codex_bin, url)?;
send_message(&endpoint, &config_overrides, user_message)
}
CliCommand::SendMessageV2 {
experimental_api,
user_message,
} => {
CliCommand::SendMessageV2 { user_message } => {
let endpoint = resolve_endpoint(codex_bin, url)?;
send_message_v2_endpoint(
&endpoint,
&config_overrides,
user_message,
experimental_api,
&dynamic_tools,
skill_selection.as_ref(),
)
send_message_v2_endpoint(&endpoint, &config_overrides, user_message, &dynamic_tools)
}
CliCommand::ResumeMessageV2 {
thread_id,
@@ -313,43 +272,24 @@ pub fn run() -> Result<()> {
thread_id,
user_message,
&dynamic_tools,
skill_selection.as_ref(),
)
}
CliCommand::ThreadResume { thread_id } => {
ensure_dynamic_tools_unused(&dynamic_tools, "thread-resume")?;
ensure_skill_unused(&skill_selection, "thread-resume")?;
let endpoint = resolve_endpoint(codex_bin, url)?;
thread_resume_follow(&endpoint, &config_overrides, thread_id)
}
CliCommand::TriggerCmdApproval { user_message } => {
let endpoint = resolve_endpoint(codex_bin, url)?;
trigger_cmd_approval(
&endpoint,
&config_overrides,
user_message,
&dynamic_tools,
skill_selection.as_ref(),
)
trigger_cmd_approval(&endpoint, &config_overrides, user_message, &dynamic_tools)
}
CliCommand::TriggerPatchApproval { user_message } => {
let endpoint = resolve_endpoint(codex_bin, url)?;
trigger_patch_approval(
&endpoint,
&config_overrides,
user_message,
&dynamic_tools,
skill_selection.as_ref(),
)
trigger_patch_approval(&endpoint, &config_overrides, user_message, &dynamic_tools)
}
CliCommand::NoTriggerCmdApproval => {
let endpoint = resolve_endpoint(codex_bin, url)?;
no_trigger_cmd_approval(
&endpoint,
&config_overrides,
&dynamic_tools,
skill_selection.as_ref(),
)
no_trigger_cmd_approval(&endpoint, &config_overrides, &dynamic_tools)
}
CliCommand::SendFollowUpV2 {
first_message,
@@ -362,7 +302,6 @@ pub fn run() -> Result<()> {
first_message,
follow_up_message,
&dynamic_tools,
skill_selection.as_ref(),
)
}
CliCommand::TriggerZshForkMultiCmdApproval {
@@ -382,25 +321,21 @@ pub fn run() -> Result<()> {
}
CliCommand::TestLogin => {
ensure_dynamic_tools_unused(&dynamic_tools, "test-login")?;
ensure_skill_unused(&skill_selection, "test-login")?;
let endpoint = resolve_endpoint(codex_bin, url)?;
test_login(&endpoint, &config_overrides)
}
CliCommand::GetAccountRateLimits => {
ensure_dynamic_tools_unused(&dynamic_tools, "get-account-rate-limits")?;
ensure_skill_unused(&skill_selection, "get-account-rate-limits")?;
let endpoint = resolve_endpoint(codex_bin, url)?;
get_account_rate_limits(&endpoint, &config_overrides)
}
CliCommand::ModelList => {
ensure_dynamic_tools_unused(&dynamic_tools, "model-list")?;
ensure_skill_unused(&skill_selection, "model-list")?;
let endpoint = resolve_endpoint(codex_bin, url)?;
model_list(&endpoint, &config_overrides)
}
CliCommand::ThreadList { limit } => {
ensure_dynamic_tools_unused(&dynamic_tools, "thread-list")?;
ensure_skill_unused(&skill_selection, "thread-list")?;
let endpoint = resolve_endpoint(codex_bin, url)?;
thread_list(&endpoint, &config_overrides, limit)
}
@@ -570,37 +505,22 @@ pub fn send_message_v2(
dynamic_tools: &Option<Vec<DynamicToolSpec>>,
) -> Result<()> {
let endpoint = Endpoint::SpawnCodex(codex_bin.to_path_buf());
send_message_v2_endpoint(
&endpoint,
config_overrides,
user_message,
true,
dynamic_tools,
None,
)
send_message_v2_endpoint(&endpoint, config_overrides, user_message, dynamic_tools)
}
fn send_message_v2_endpoint(
endpoint: &Endpoint,
config_overrides: &[String],
user_message: String,
experimental_api: bool,
dynamic_tools: &Option<Vec<DynamicToolSpec>>,
skill_selection: Option<&SkillSelection>,
) -> Result<()> {
if dynamic_tools.is_some() && !experimental_api {
bail!("--dynamic-tools requires --experimental-api for send-message-v2");
}
send_message_v2_with_policies(
endpoint,
config_overrides,
user_message,
experimental_api,
None,
None,
dynamic_tools,
skill_selection,
)
}
@@ -705,7 +625,6 @@ fn resume_message_v2(
thread_id: String,
user_message: String,
dynamic_tools: &Option<Vec<DynamicToolSpec>>,
skill_selection: Option<&SkillSelection>,
) -> Result<()> {
ensure_dynamic_tools_unused(dynamic_tools, "resume-message-v2")?;
@@ -722,7 +641,10 @@ fn resume_message_v2(
let turn_response = client.turn_start(TurnStartParams {
thread_id: resume_response.thread.id.clone(),
input: build_v2_input(user_message, skill_selection),
input: vec![V2UserInput::Text {
text: user_message,
text_elements: Vec::new(),
}],
..Default::default()
})?;
println!("< turn/start response: {turn_response:?}");
@@ -757,7 +679,6 @@ fn trigger_cmd_approval(
config_overrides: &[String],
user_message: Option<String>,
dynamic_tools: &Option<Vec<DynamicToolSpec>>,
skill_selection: Option<&SkillSelection>,
) -> Result<()> {
let default_prompt =
"Run `touch /tmp/should-trigger-approval` so I can confirm the file exists.";
@@ -766,13 +687,11 @@ fn trigger_cmd_approval(
endpoint,
config_overrides,
message,
true,
Some(AskForApproval::OnRequest),
Some(SandboxPolicy::ReadOnly {
access: ReadOnlyAccess::FullAccess,
}),
dynamic_tools,
skill_selection,
)
}
@@ -781,7 +700,6 @@ fn trigger_patch_approval(
config_overrides: &[String],
user_message: Option<String>,
dynamic_tools: &Option<Vec<DynamicToolSpec>>,
skill_selection: Option<&SkillSelection>,
) -> Result<()> {
let default_prompt =
"Create a file named APPROVAL_DEMO.txt containing a short hello message using apply_patch.";
@@ -790,13 +708,11 @@ fn trigger_patch_approval(
endpoint,
config_overrides,
message,
true,
Some(AskForApproval::OnRequest),
Some(SandboxPolicy::ReadOnly {
access: ReadOnlyAccess::FullAccess,
}),
dynamic_tools,
skill_selection,
)
}
@@ -804,18 +720,15 @@ fn no_trigger_cmd_approval(
endpoint: &Endpoint,
config_overrides: &[String],
dynamic_tools: &Option<Vec<DynamicToolSpec>>,
skill_selection: Option<&SkillSelection>,
) -> Result<()> {
let prompt = "Run `touch should_not_trigger_approval.txt`";
send_message_v2_with_policies(
endpoint,
config_overrides,
prompt.to_string(),
true,
None,
None,
dynamic_tools,
skill_selection,
)
}
@@ -823,15 +736,13 @@ fn send_message_v2_with_policies(
endpoint: &Endpoint,
config_overrides: &[String],
user_message: String,
experimental_api: bool,
approval_policy: Option<AskForApproval>,
sandbox_policy: Option<SandboxPolicy>,
dynamic_tools: &Option<Vec<DynamicToolSpec>>,
skill_selection: Option<&SkillSelection>,
) -> Result<()> {
let mut client = CodexClient::connect(endpoint, config_overrides)?;
let initialize = client.initialize_with_experimental_api(experimental_api)?;
let initialize = client.initialize()?;
println!("< initialize response: {initialize:?}");
let thread_response = client.thread_start(ThreadStartParams {
@@ -841,7 +752,11 @@ fn send_message_v2_with_policies(
println!("< thread/start response: {thread_response:?}");
let mut turn_params = TurnStartParams {
thread_id: thread_response.thread.id.clone(),
input: build_v2_input(user_message, skill_selection),
input: vec![V2UserInput::Text {
text: user_message,
// Test client sends plain text without UI element ranges.
text_elements: Vec::new(),
}],
..Default::default()
};
turn_params.approval_policy = approval_policy;
@@ -861,7 +776,6 @@ fn send_follow_up_v2(
first_message: String,
follow_up_message: String,
dynamic_tools: &Option<Vec<DynamicToolSpec>>,
skill_selection: Option<&SkillSelection>,
) -> Result<()> {
let mut client = CodexClient::connect(endpoint, config_overrides)?;
@@ -876,7 +790,11 @@ fn send_follow_up_v2(
let first_turn_params = TurnStartParams {
thread_id: thread_response.thread.id.clone(),
input: build_v2_input(first_message, skill_selection),
input: vec![V2UserInput::Text {
text: first_message,
// Test client sends plain text without UI element ranges.
text_elements: Vec::new(),
}],
..Default::default()
};
let first_turn_response = client.turn_start(first_turn_params)?;
@@ -885,7 +803,11 @@ fn send_follow_up_v2(
let follow_up_params = TurnStartParams {
thread_id: thread_response.thread.id.clone(),
input: build_v2_input(follow_up_message, skill_selection),
input: vec![V2UserInput::Text {
text: follow_up_message,
// Test client sends plain text without UI element ranges.
text_elements: Vec::new(),
}],
..Default::default()
};
let follow_up_response = client.turn_start(follow_up_params)?;
@@ -981,51 +903,6 @@ fn ensure_dynamic_tools_unused(
Ok(())
}
fn ensure_skill_unused(skill_selection: &Option<SkillSelection>, command: &str) -> Result<()> {
if skill_selection.is_some() {
bail!(
"skill input is only supported for v2 turn/start commands; remove --skill-name/--skill-path for {command}"
);
}
Ok(())
}
fn parse_skill_selection(
skill_name: Option<String>,
skill_path: Option<PathBuf>,
) -> Result<Option<SkillSelection>> {
match (skill_name, skill_path) {
(None, None) => Ok(None),
(Some(name), Some(path)) => {
let path = fs::canonicalize(&path)
.with_context(|| format!("canonicalize --skill-path {}", path.display()))?;
Ok(Some(SkillSelection { name, path }))
}
(Some(_), None) => bail!("--skill-name requires --skill-path"),
(None, Some(_)) => bail!("--skill-path requires --skill-name"),
}
}
fn build_v2_input(
user_message: String,
skill_selection: Option<&SkillSelection>,
) -> Vec<V2UserInput> {
let mut input = vec![V2UserInput::Text {
text: user_message,
// Test client sends plain text without UI element ranges.
text_elements: Vec::new(),
}];
if let Some(skill_selection) = skill_selection {
input.push(V2UserInput::Skill {
name: skill_selection.name.clone(),
path: skill_selection.path.clone(),
});
}
input
}
fn parse_dynamic_tools_arg(dynamic_tools: &Option<String>) -> Result<Option<Vec<DynamicToolSpec>>> {
let Some(raw_arg) = dynamic_tools.as_deref() else {
return Ok(None);
@@ -1072,7 +949,6 @@ struct CodexClient {
#[derive(Debug, Clone, Copy)]
enum CommandApprovalBehavior {
Prompt,
AlwaysAccept,
AbortOn(usize),
}
@@ -1123,7 +999,7 @@ impl CodexClient {
stdout: BufReader::new(stdout),
},
pending_notifications: VecDeque::new(),
command_approval_behavior: CommandApprovalBehavior::Prompt,
command_approval_behavior: CommandApprovalBehavior::AlwaysAccept,
command_approval_count: 0,
command_approval_item_ids: Vec::new(),
command_execution_statuses: Vec::new(),
@@ -1144,7 +1020,7 @@ impl CodexClient {
socket: Box::new(socket),
},
pending_notifications: VecDeque::new(),
command_approval_behavior: CommandApprovalBehavior::Prompt,
command_approval_behavior: CommandApprovalBehavior::AlwaysAccept,
command_approval_count: 0,
command_approval_item_ids: Vec::new(),
command_execution_statuses: Vec::new(),
@@ -1153,13 +1029,6 @@ impl CodexClient {
}
fn initialize(&mut self) -> Result<InitializeResponse> {
self.initialize_with_experimental_api(true)
}
fn initialize_with_experimental_api(
&mut self,
experimental_api: bool,
) -> Result<InitializeResponse> {
let request_id = self.request_id();
let request = ClientRequest::Initialize {
request_id: request_id.clone(),
@@ -1170,7 +1039,7 @@ impl CodexClient {
version: env!("CARGO_PKG_VERSION").to_string(),
},
capabilities: Some(InitializeCapabilities {
experimental_api,
experimental_api: true,
opt_out_notification_methods: Some(
NOTIFICATIONS_TO_OPT_OUT
.iter()
@@ -1603,9 +1472,6 @@ impl CodexClient {
ServerRequest::FileChangeRequestApproval { request_id, params } => {
self.approve_file_change_request(request_id, params)?;
}
ServerRequest::SkillRequestApproval { request_id, params } => {
self.approve_skill_request(request_id, params)?;
}
other => {
bail!("received unsupported server request: {other:?}");
}
@@ -1629,7 +1495,6 @@ impl CodexClient {
command,
cwd,
command_actions,
additional_permissions,
proposed_execpolicy_amendment,
} = params;
@@ -1656,48 +1521,28 @@ impl CodexClient {
{
println!("< command actions: {command_actions:?}");
}
if let Some(additional_permissions) = additional_permissions.as_ref() {
println!("< additional permissions: {additional_permissions:?}");
}
if let Some(execpolicy_amendment) = proposed_execpolicy_amendment.as_ref() {
println!("< proposed execpolicy amendment: {execpolicy_amendment:?}");
}
let decision = match self.command_approval_behavior {
CommandApprovalBehavior::Prompt => {
self.command_approval_decision(proposed_execpolicy_amendment)?
}
CommandApprovalBehavior::AlwaysAccept => CommandExecutionApprovalDecision::Accept,
CommandApprovalBehavior::AbortOn(index) if self.command_approval_count == index => {
CommandExecutionApprovalDecision::Cancel
}
CommandApprovalBehavior::AbortOn(_) => CommandExecutionApprovalDecision::Accept,
};
let response = CommandExecutionRequestApprovalResponse { decision };
let response = CommandExecutionRequestApprovalResponse {
decision: decision.clone(),
};
self.send_server_request_response(request_id, &response)?;
println!(
"< commandExecution decision for approval #{} on item {item_id}: {:?}",
self.command_approval_count, response.decision
self.command_approval_count, decision
);
Ok(())
}
fn approve_skill_request(
&mut self,
request_id: RequestId,
params: SkillRequestApprovalParams,
) -> Result<()> {
println!(
"\n< skill approval requested for item {}, skill {}",
params.item_id, params.skill_name
);
let response = SkillRequestApprovalResponse {
decision: SkillApprovalDecision::Approve,
};
self.send_server_request_response(request_id, &response)?;
Ok(())
}
fn approve_file_change_request(
&mut self,
request_id: RequestId,
@@ -1721,39 +1566,14 @@ impl CodexClient {
println!("< grant root: {}", grant_root.display());
}
let decision = self.file_change_approval_decision()?;
let response = FileChangeRequestApprovalResponse { decision };
let response = FileChangeRequestApprovalResponse {
decision: FileChangeApprovalDecision::Accept,
};
self.send_server_request_response(request_id, &response)?;
println!(
"< responded to fileChange request for item {item_id}: {:?}",
response.decision
);
println!("< approved fileChange request for item {item_id}");
Ok(())
}
fn command_approval_decision(
&self,
proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
) -> Result<CommandExecutionApprovalDecision> {
if let Some(execpolicy_amendment) = proposed_execpolicy_amendment {
return prompt_for_command_approval_with_amendment(execpolicy_amendment);
}
if prompt_for_yes_no("Approve command execution request? [y/n] ")? {
Ok(CommandExecutionApprovalDecision::Accept)
} else {
Ok(CommandExecutionApprovalDecision::Decline)
}
}
fn file_change_approval_decision(&self) -> Result<FileChangeApprovalDecision> {
if prompt_for_yes_no("Approve file-change request? [y/n] ")? {
Ok(FileChangeApprovalDecision::Accept)
} else {
Ok(FileChangeApprovalDecision::Decline)
}
}
fn send_server_request_response<T>(&mut self, request_id: RequestId, response: &T) -> Result<()>
where
T: Serialize,
@@ -1828,59 +1648,6 @@ fn print_multiline_with_prefix(prefix: &str, payload: &str) {
}
}
fn prompt_for_yes_no(prompt: &str) -> Result<bool> {
loop {
print!("{prompt}");
io::stdout()
.flush()
.context("failed to flush approval prompt")?;
let mut line = String::new();
io::stdin()
.read_line(&mut line)
.context("failed to read approval input")?;
let input = line.trim().to_ascii_lowercase();
if matches!(input.as_str(), "y" | "yes") {
return Ok(true);
}
if matches!(input.as_str(), "n" | "no") {
return Ok(false);
}
println!("please answer y or n");
}
}
fn prompt_for_command_approval_with_amendment(
execpolicy_amendment: ExecPolicyAmendment,
) -> Result<CommandExecutionApprovalDecision> {
loop {
print!("Approve command execution request? [y/n/a] (a=always allow) ");
io::stdout()
.flush()
.context("failed to flush approval prompt")?;
let mut line = String::new();
io::stdin()
.read_line(&mut line)
.context("failed to read approval input")?;
let input = line.trim().to_ascii_lowercase();
if matches!(input.as_str(), "y" | "yes") {
return Ok(CommandExecutionApprovalDecision::Accept);
}
if matches!(input.as_str(), "n" | "no") {
return Ok(CommandExecutionApprovalDecision::Decline);
}
if matches!(input.as_str(), "a" | "always" | "always allow") {
return Ok(
CommandExecutionApprovalDecision::AcceptWithExecpolicyAmendment {
execpolicy_amendment: execpolicy_amendment.clone(),
},
);
}
println!("please answer y, n, or a");
}
}
impl Drop for CodexClient {
fn drop(&mut self) {
let ClientTransport::Stdio { child, stdin, .. } = &mut self.transport else {

Some files were not shown because too many files have changed in this diff Show More