diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 4a07214fc7..5198248821 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,38 +1,38 @@ # Default reviewers -* @dalsoop +* @lidge-jun @Ingwannu # High-impact runtime behavior -/src/adapters/ @dalsoop -/src/providers/ @dalsoop -/src/codex/ @dalsoop -/src/server/ @dalsoop +/src/adapters/ @lidge-jun @Ingwannu +/src/providers/ @lidge-jun @Ingwannu +/src/codex/ @lidge-jun @Ingwannu +/src/server/ @lidge-jun @Ingwannu # Repository automation and release security -/.github/ @dalsoop -/.coderabbit.yaml @dalsoop -/.npmignore @dalsoop -/bunfig.toml @dalsoop -/scripts/release.ts @dalsoop -/scripts/release-notes.ts @dalsoop -/scripts/release-version-sources.ts @dalsoop -/scripts/prepare-package.ts @dalsoop -/package.json @dalsoop -/bun.lock @dalsoop +/.github/ @lidge-jun @Ingwannu +/.coderabbit.yaml @lidge-jun @Ingwannu +/.npmignore @lidge-jun @Ingwannu +/bunfig.toml @lidge-jun @Ingwannu +/scripts/release.ts @lidge-jun @Ingwannu +/scripts/release-notes.ts @lidge-jun @Ingwannu +/scripts/release-version-sources.ts @lidge-jun @Ingwannu +/scripts/prepare-package.ts @lidge-jun @Ingwannu +/package.json @lidge-jun @Ingwannu +/bun.lock @lidge-jun @Ingwannu # Authentication, credentials, and management API -/src/oauth/ @dalsoop -/src/codex/auth-context.ts @dalsoop -/src/server/auth-cors.ts @dalsoop -/src/server/management-api.ts @dalsoop -/src/lib/admin-secrets.ts @dalsoop -/src/lib/service-secrets.ts @dalsoop -/src/server/management-auth.ts @dalsoop +/src/oauth/ @lidge-jun @Ingwannu +/src/codex/auth-context.ts @lidge-jun @Ingwannu +/src/server/auth-cors.ts @lidge-jun @Ingwannu +/src/server/management-api.ts @lidge-jun @Ingwannu +/src/lib/admin-secrets.ts @lidge-jun @Ingwannu +/src/lib/service-secrets.ts @lidge-jun @Ingwannu +/src/server/management-auth.ts @lidge-jun @Ingwannu # Governance and security policy -/AGENTS.md @dalsoop -**/AGENTS.md @dalsoop -/MAINTAINERS.md @dalsoop -/SECURITY.md @dalsoop +/AGENTS.md @lidge-jun @Ingwannu +**/AGENTS.md @lidge-jun @Ingwannu +/MAINTAINERS.md @lidge-jun @Ingwannu +/SECURITY.md @lidge-jun @Ingwannu # Proxy core boundary — owner approval required. # These four files carry every user's request path, including users of no optional diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 07fd1d1cf6..7e4c10e160 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -4,7 +4,7 @@ contact_links: url: https://github.com/lidge-jun/opencodex/security/advisories/new about: Report undisclosed vulnerabilities privately to the maintainers. Do not open a public issue. - name: Security policy - url: https://github.com/lidge-jun/opencodex/blob/main/SECURITY.md + url: https://github.com/lidge-jun/opencodex/blob/dev/SECURITY.md about: Read the supported-version and reporting guidance before sharing security-sensitive details. - name: Contributing guide url: https://opencodex.me/contributing/ diff --git a/.github/actions/setup-project-bun/action.yml b/.github/actions/setup-project-bun/action.yml index 1ab22dd1dc..cf28f6f9d4 100644 --- a/.github/actions/setup-project-bun/action.yml +++ b/.github/actions/setup-project-bun/action.yml @@ -8,8 +8,8 @@ description: >- # (#6713 run 37631558263: Linux 1/4, macOS 2/2, Windows 9/9). It moved from 1.4.0 to # 1.4.3 for oven-sh/bun#44581: 1.4.0's Bun.spawnSync could lose a child's exit after # finalizers ran inside an earlier call and spin past its own timeout (#4956). -# Rejoin only after the upstream runner crash is fixed and a green lane=all -# dispatch proves the unified version; then delete testRunnerBun and this role input. +# Both roles now default to the package's 1.4.4 security transition, retaining role validation. +# Promotion requires a green full cross-platform lane=all run on the exact candidate head. inputs: role: description: Bun role to install (runtime or test-runner). diff --git a/.github/scripts/enforce-pr-target.test.cjs b/.github/scripts/enforce-pr-target.test.cjs index 8973f07a63..9756869eb9 100644 --- a/.github/scripts/enforce-pr-target.test.cjs +++ b/.github/scripts/enforce-pr-target.test.cjs @@ -94,7 +94,9 @@ describe("enforce-pr-target workflow", () => { it("writes exactly one consolidated comment via a single upsert helper", () => { assert.match(workflow, /GATE_MARKER,/); - assert.match(workflow, /comment\.body\?\.includes\(GATE_MARKER\)/); + // The gate comment is the bot comment that starts with GATE_MARKER; a + // marker echoed inside another comment does not classify it. + assert.match(workflow, /comments\.find\(isGateComment\)/); assert.match(workflow, /upsertGateComment/); assert.match(workflow, /buildGateCommentBody/); // No legacy two-comment write path remains. @@ -163,24 +165,23 @@ describe("enforce-pr-target workflow", () => { .split("- name: Checkout trusted PR-quality scripts")[1] .split(/\n {6}- name:/)[0]; assert.match(checkoutStep, /actions\/checkout@[0-9a-f]{40}/); - // The trusted ref comes from a fixed set of integration branches, never - // from the PR's own base commit: a stacked child's base is another open - // PR's head, and `base.sha` would let that unpromoted commit choose the - // code that runs with this job's write-capable token. + // The trusted ref is the single integration branch, never the PR's own + // base commit: a stacked child's base is another open PR's head, and + // `base.sha` would let that unpromoted commit choose the code that runs + // with this job's write-capable token. // // `status` has no pull_request payload and sources from the default branch - // that supplied the privileged workflow. A `main`-targeting PR sources - // from `main` so the workflow definition and the scripts match. Everything - // else resolves to `dev`. + // that supplied the privileged workflow. Every pull_request event resolves + // to `dev`, the only integration branch. // - // Exact equality, not fragment matching: separate checks for `status`, - // `main`, and `dev` would all pass with the operator grouping wrong or a - // surviving `base.sha` fallback. + // Exact equality, not fragment matching: separate checks for `status` and + // `dev` would both pass with the operator grouping wrong or a surviving + // `base.sha` fallback. const ref = checkoutStep.match(/^\s*ref:\s*(.+)$/m)?.[1]; assert.ok(ref, "trusted checkout must declare ref"); assert.equal( ref.replace(/\s+/g, " ").trim(), - "${{ github.event_name == 'status' && github.event.repository.default_branch || (github.event.pull_request.base.ref == 'main' && 'main' || 'dev') }}", + "${{ github.event_name == 'status' && github.event.repository.default_branch || 'dev' }}", ); assert.doesNotMatch(ref, /base\.sha|head\.(?:sha|ref)/); // Pinning the checkout ref only gates one step. A later `run:` or @@ -213,7 +214,7 @@ describe("enforce-pr-target workflow", () => { const checkouts = workflow.match(/uses:\s*actions\/checkout@[\s\S]*?(?=\n {6}- name:|$)/g) ?? []; for (const step of checkouts) { const stepRef = (step.match(/^\s*ref:\s*(.+)$/m)?.[1] ?? "").replace(/\s+/g, " ").trim(); - assert.equal(stepRef, "${{ github.event_name == 'status' && github.event.repository.default_branch || (github.event.pull_request.base.ref == 'main' && 'main' || 'dev') }}", "every checkout must use the trusted ref"); + assert.equal(stepRef, "${{ github.event_name == 'status' && github.event.repository.default_branch || 'dev' }}", "every checkout must use the trusted ref"); assert.doesNotMatch(step, /repository:/, "a checkout must not retarget its repository"); } // Checkout is not the only way to obtain PR-controlled code. A `run:` step diff --git a/.github/scripts/pr-hygiene.cjs b/.github/scripts/pr-hygiene.cjs index e0be6ae2c2..82586d4dea 100644 --- a/.github/scripts/pr-hygiene.cjs +++ b/.github/scripts/pr-hygiene.cjs @@ -292,6 +292,109 @@ const HYGIENE_GATE_LABELS = [ "attribution-approved", ]; +/** + * Exception approvals vouch for one revision of the change. Each counts only + * while the head the hygiene workflow last recorded is still the head being + * evaluated and nothing has rewritten the branch since. Sponsorship + * (`maintainer-sponsored`) is about which surfaces change, not about one + * revision, so it is not head-bound. + */ +const HEAD_BOUND_APPROVAL_LABELS = [ + "test-exception-approved", + "suppression-approved", + "generated-change-approved", + "dependency-change-approved", + "attribution-approved", +]; + +/** Issue events after which the head can point at an earlier commit again. */ +const HEAD_REWRITE_EVENTS = ["head_ref_force_pushed", "head_ref_restored"]; + +const APPROVAL_RECORD_TOKEN = "pr-hygiene-approvals"; +const APPROVAL_RECORD_LINE = /^$/; +const FULL_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/; + +function isRewriteCount(value) { + return Number.isSafeInteger(value) && value >= 0; +} + +/** + * Read the head binding the hygiene workflow wrote as the last line of its + * own section. The token must occur exactly once in `source` and sit on that + * last line, so echoed text (a changed path can contain newlines) can only + * make the record unreadable, never stand in for it. + * @returns {{ head: string, headRewrites: number | null } | null} + */ +function parseApprovalRecord(source) { + if (typeof source !== "string") return null; + if (source.split(APPROVAL_RECORD_TOKEN).length !== 2) return null; + const lines = source.split("\n").map((line) => line.trim()).filter(Boolean); + const match = lines.at(-1)?.match(APPROVAL_RECORD_LINE); + if (!match) return null; + let value; + try { + value = JSON.parse(match[1]); + } catch { + return null; + } + if (value === null || typeof value !== "object" || Array.isArray(value)) return null; + if (Object.keys(value).sort().join(",") !== "head,headRewrites") return null; + if (typeof value.head !== "string" || !FULL_SHA.test(value.head)) return null; + if (value.headRewrites !== null && !isRewriteCount(value.headRewrites)) return null; + return { head: value.head, headRewrites: value.headRewrites }; +} + +/** `headRewrites` is null when the history read failed: nothing is confirmed. */ +function formatApprovalRecord({ head, headRewrites }) { + const value = { head, headRewrites: isRewriteCount(headRewrites) ? headRewrites : null }; + return ""; +} + +function countHeadRewrites(events) { + return (events ?? []).filter((entry) => HEAD_REWRITE_EVENTS.includes(entry?.event)).length; +} + +function presentHeadBoundApprovals(labels) { + return HEAD_BOUND_APPROVAL_LABELS.filter((label) => labels.includes(label)); +} + +/** True when a current rewrite count could still confirm an approval. */ +function needsHeadRewriteCount({ labels = [], headSha, record = null, eventAction }) { + return ( + eventAction !== "synchronize" && + record !== null && + record.head === headSha && + isRewriteCount(record.headRewrites) && + presentHeadBoundApprovals(labels).length > 0 + ); +} + +/** + * Split the head-bound approvals on the pull request into the ones that still + * describe the evaluated head and the ones that do not. They are kept only + * when the last recorded evaluation saw this same head and the rewrite count, + * read before that evaluation's snapshot and again after this one's, has not + * changed. Without a rewrite, fast-forward pushes cannot bring the recorded + * head back, so the head has not moved since that evaluation, which removed + * every approval it could not confirm. A synchronize event, a missing record, + * or an unknown count confirms nothing. + * @returns {{ kept: string[], stale: string[] }} + */ +function reconcileHeadBoundApprovals({ + labels = [], + headSha, + record = null, + eventAction, + headRewriteCount = null, +}) { + const present = presentHeadBoundApprovals(labels); + const current = + needsHeadRewriteCount({ labels, headSha, record, eventAction }) && + isRewriteCount(headRewriteCount) && + headRewriteCount === record.headRewrites; + return current ? { kept: present, stale: [] } : { kept: [], stale: present }; +} + /** * Combine patch-hygiene and sponsored-surface failures into one list so the * hygiene workflow and the PR quality gate cannot disagree about Ready. @@ -340,6 +443,10 @@ module.exports = { addedLines, assessHygiene, collectDeterministicHygieneFailures, + countHeadRewrites, + formatApprovalRecord, + HEAD_BOUND_APPROVAL_LABELS, + HEAD_REWRITE_EVENTS, HYGIENE_FAILURE_HINTS, HYGIENE_GATE_LABELS, hasEmptyCatch, @@ -347,6 +454,9 @@ module.exports = { isBehaviorPath, isGeneratedPath, isTestPath, + needsHeadRewriteCount, + parseApprovalRecord, + reconcileHeadBoundApprovals, resultLines, resultLinesByHunk, }; diff --git a/.github/scripts/pr-hygiene.test.cjs b/.github/scripts/pr-hygiene.test.cjs index 3ab5a8b2ca..165d78566a 100644 --- a/.github/scripts/pr-hygiene.test.cjs +++ b/.github/scripts/pr-hygiene.test.cjs @@ -6,9 +6,15 @@ const { addedLines, assessHygiene, collectDeterministicHygieneFailures, + countHeadRewrites, + formatApprovalRecord, + HEAD_BOUND_APPROVAL_LABELS, HYGIENE_FAILURE_HINTS, HYGIENE_GATE_LABELS, hasEmptyCatch, + needsHeadRewriteCount, + parseApprovalRecord, + reconcileHeadBoundApprovals, resultLines, resultLinesByHunk, } = require("./pr-hygiene.cjs"); @@ -308,7 +314,7 @@ describe("pr-hygiene workflow trust boundary", () => { assert.ok(ref, "trusted checkout must declare ref"); assert.equal( ref.replace(/\s+/g, " ").trim(), - "${{ github.event.pull_request.base.ref == 'main' && 'main' || 'dev' }}", + "dev", ); // A stacked child PR's base is another open PR's head; neither a base nor // a head ref may select the code that runs with the write-capable token. @@ -349,7 +355,7 @@ describe("pr-hygiene workflow trust boundary", () => { const checkouts = workflow.match(/uses:\s*actions\/checkout@[\s\S]*?(?=\n {6}- name:|$)/g) ?? []; for (const step of checkouts) { const stepRef = (step.match(/^\s*ref:\s*(.+)$/m)?.[1] ?? "").replace(/\s+/g, " ").trim(); - assert.equal(stepRef, "${{ github.event.pull_request.base.ref == 'main' && 'main' || 'dev' }}", "every checkout must use the trusted ref"); + assert.equal(stepRef, "dev", "every checkout must use the trusted ref"); assert.doesNotMatch(step, /repository:/, "a checkout must not retarget its repository"); } // Checkout is not the only way to obtain PR-controlled code. A `run:` step @@ -391,3 +397,100 @@ describe("pr-hygiene workflow trust boundary", () => { ); }); }); + +describe("head-bound approvals", () => { + const HEAD = "c".repeat(40); + const OTHER = "d".repeat(40); + const record = (head, headRewrites) => + ""; + + it("covers exactly the exception approvals, not sponsorship", () => { + assert.deepEqual( + [...HEAD_BOUND_APPROVAL_LABELS].sort(), + HYGIENE_GATE_LABELS.filter( + (label) => label !== "intake: hygiene-blocked" && label !== "maintainer-sponsored", + ).sort(), + ); + }); + + it("round-trips a record, including an unknown rewrite count", () => { + const line = formatApprovalRecord({ head: HEAD, headRewrites: 2 }); + assert.equal(line, record(HEAD, 2)); + assert.deepEqual(parseApprovalRecord("status\n\n" + line), { head: HEAD, headRewrites: 2 }); + assert.deepEqual(parseApprovalRecord(formatApprovalRecord({ head: HEAD, headRewrites: undefined })), { + head: HEAD, + headRewrites: null, + }); + assert.deepEqual(parseApprovalRecord(record("e".repeat(64), 0)), { head: "e".repeat(64), headRewrites: 0 }); + }); + + it("rejects anything but one well-formed record on the last line", () => { + for (const source of [ + null, + "", + record(HEAD, 0) + "\nlater line", + record(HEAD, 0) + "\n" + record(HEAD, 0), + "mentions pr-hygiene-approvals elsewhere\n" + record(HEAD, 0), + "", + "", + "", + "", + record("abc", 0), + record(HEAD.toUpperCase(), 0), + record(HEAD, -1), + record(HEAD, 1.5), + record(HEAD, "1"), + ]) { + assert.equal(parseApprovalRecord(source), null, String(source)); + } + }); + + it("counts only head rewrite events", () => { + assert.equal( + countHeadRewrites([ + { event: "head_ref_force_pushed" }, + { event: "labeled" }, + { event: "head_ref_restored" }, + null, + ]), + 2, + ); + assert.equal(countHeadRewrites(undefined), 0); + }); + + it("keeps approvals only under an unchanged head and rewrite count", () => { + const labels = ["test-exception-approved", "maintainer-sponsored"]; + const base = { labels, headSha: HEAD, record: { head: HEAD, headRewrites: 1 }, eventAction: "edited" }; + const kept = { kept: ["test-exception-approved"], stale: [] }; + const stale = { kept: [], stale: ["test-exception-approved"] }; + assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: 1 }), kept); + assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: 2 }), stale); + assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: null }), stale); + assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: 1, eventAction: "synchronize" }), stale); + assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: 1, headSha: OTHER }), stale); + assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: 1, record: null }), stale); + assert.deepEqual( + reconcileHeadBoundApprovals({ ...base, headRewriteCount: 1, record: { head: HEAD, headRewrites: null } }), + stale, + ); + assert.deepEqual( + reconcileHeadBoundApprovals({ ...base, labels: ["maintainer-sponsored"], headRewriteCount: 1 }), + { kept: [], stale: [] }, + ); + }); + + it("asks for a rewrite count only when one could confirm an approval", () => { + const base = { + labels: ["suppression-approved"], + headSha: HEAD, + record: { head: HEAD, headRewrites: 0 }, + eventAction: "labeled", + }; + assert.equal(needsHeadRewriteCount(base), true); + assert.equal(needsHeadRewriteCount({ ...base, labels: [] }), false); + assert.equal(needsHeadRewriteCount({ ...base, eventAction: "synchronize" }), false); + assert.equal(needsHeadRewriteCount({ ...base, headSha: OTHER }), false); + assert.equal(needsHeadRewriteCount({ ...base, record: null }), false); + assert.equal(needsHeadRewriteCount({ ...base, record: { head: HEAD, headRewrites: null } }), false); + }); +}); diff --git a/.github/scripts/pr-quality-messages.cjs b/.github/scripts/pr-quality-messages.cjs index e9b642b574..c37625ea51 100644 --- a/.github/scripts/pr-quality-messages.cjs +++ b/.github/scripts/pr-quality-messages.cjs @@ -30,6 +30,18 @@ const HYGIENE_BLOCK_RE = new RegExp( `^[ \\t]*${HYGIENE_BLOCK_START}[ \\t]*\\n([\\s\\S]*?)\\n[ \\t]*${HYGIENE_BLOCK_END}[ \\t]*$`, "m" ); +/** + * Whole-line delimiter matchers, the same shape HYGIENE_BLOCK_RE anchors on. + * A block is only read when each delimiter occurs on exactly one line: a + * changed filename can contain newlines, so an echoed path can add delimiter + * lines, and an ambiguous block must never be cut at the first one. + */ +const HYGIENE_BLOCK_START_LINE_RE = new RegExp(`^[ \\t]*${HYGIENE_BLOCK_START}[ \\t]*$`, "gm"); +const HYGIENE_BLOCK_END_LINE_RE = new RegExp(`^[ \\t]*${HYGIENE_BLOCK_END}[ \\t]*$`, "gm"); + +function countDelimiterLines(text, pattern) { + return (text.match(pattern) ?? []).length; +} function inlineCode(value) { const text = String(value); @@ -41,6 +53,37 @@ function inlineCode(value) { return `${delimiter}${text}${delimiter}`; } +/** + * Render contributor-supplied text (a changed path) on one line: control + * characters, including newlines, become `\uXXXX` escapes. Without this an + * echoed path could add whole lines, such as delimiter or record lines, to a + * bot comment. + */ +function escapeControlCharacters(value) { + return String(value).replace( + /[\u0000-\u001f\u007f\u2028\u2029]/g, + character => "\\u" + character.charCodeAt(0).toString(16).padStart(4, "0") + ); +} + +/** The consolidated gate comment: written by the workflow bot, marker first. */ +function isGateComment(comment) { + return ( + comment?.user?.login === "github-actions[bot]" && + typeof comment.body === "string" && + comment.body.startsWith(GATE_MARKER) + ); +} + +/** The standalone hygiene comment posted before a gate comment exists. */ +function isStandaloneHygieneComment(comment) { + return ( + comment?.user?.login === "github-actions[bot]" && + typeof comment.body === "string" && + comment.body.startsWith(HYGIENE_MARKER) + ); +} + function readinessChecklistLines(readiness) { return REVIEW_READINESS_ITEMS.map( (item, index) => @@ -121,9 +164,17 @@ function buildGateCommentBody(state, opts) { * `null` when the comment has none. The gate rebuilds its body from scratch * every run, so without this round-trip a hygiene update from the separate * hygiene workflow would be silently dropped on the next gate write. + * An ambiguous block (a delimiter on more than one line) reads as `null`, so + * the gate drops it on rebuild instead of re-wrapping a truncated section. */ function extractHygieneSection(body) { if (typeof body !== "string") return null; + if ( + countDelimiterLines(body, HYGIENE_BLOCK_START_LINE_RE) !== 1 || + countDelimiterLines(body, HYGIENE_BLOCK_END_LINE_RE) !== 1 + ) { + return null; + } const match = body.match(HYGIENE_BLOCK_RE); if (!match) return null; return match[1] @@ -150,13 +201,40 @@ function withHygieneSection(body, hygieneLines) { ].join("\n"); if (HYGIENE_BLOCK_RE.test(base)) { - return base.replace(HYGIENE_BLOCK_RE, block); + // A callback, not a replacement string: echoed paths can contain $&, $1 + // and similar tokens that a template would expand into extra lines. + return base.replace(HYGIENE_BLOCK_RE, () => block); } // No existing block: append one at the end. return `${base.replace(/\s+$/, "")}\n\n## Hygiene\n\n${block}\n`; } +/** + * The text the hygiene workflow last wrote for this pull request: the hygiene + * block of the first bot comment that starts with GATE_MARKER, or the first + * bot comment that starts with HYGIENE_MARKER while that gate comment has no + * block yet (the gate never absorbs it). A marker elsewhere in a comment does + * not classify it. An ambiguous gate block yields `null`; later comments are + * never searched for a more convenient candidate. + */ +function authoritativeHygieneSection(comments) { + const list = comments ?? []; + const gate = list.find(isGateComment); + if (gate) { + const section = extractHygieneSection(gate.body); + if (section !== null) return section; + if ( + countDelimiterLines(gate.body, HYGIENE_BLOCK_START_LINE_RE) > 0 || + countDelimiterLines(gate.body, HYGIENE_BLOCK_END_LINE_RE) > 0 + ) { + return null; + } + } + const standalone = list.find(isStandaloneHygieneComment); + return standalone ? standalone.body : null; +} + function descriptionFailureLines(reason) { switch (reason) { case "empty": @@ -196,17 +274,7 @@ function buildFailureSections(failures, { pr, allowedBases, defaultBase }) { "", `This pull request currently targets ${inlineCode(pr.base.ref)}, but pull requests must target one of ${allowedBases.map(inlineCode).join(" or ")}.`, "", - `@${pr.user.login} Please retarget this PR to ${inlineCode(defaultBase)}. All contributions go to ${inlineCode(defaultBase)}; \`main\` receives only release promotions. See our [Contributing guide](https://lidge-jun.github.io/opencodex/contributing/) for details. Thanks! 🙏` - ); - } - - if (failures.some(failure => failure.code === "wrong_ancestry")) { - sections.push( - "⚠️ **Wrong branch ancestry**", - "", - `This pull request targets ${inlineCode(pr.base.ref)}, but its head appears to sit on the current ${inlineCode("main")} tip while being far behind ${inlineCode(pr.base.ref)}.`, - "", - `@${pr.user.login} Rebase onto the current ${inlineCode(pr.base.ref)} branch instead of opening from ${inlineCode("main")}. That keeps already-released commits out of the integration branch.` + `@${pr.user.login} Please retarget this PR to ${inlineCode(defaultBase)}. All contributions go to ${inlineCode(defaultBase)}. See our [Contributing guide](https://lidge-jun.github.io/opencodex/contributing/) for details. Thanks! 🙏` ); } @@ -244,9 +312,6 @@ function failureSummary(failures, { pr }) { if (failure.code === "wrong_base") { return `wrong base (${pr.base.ref})`; } - if (failure.code === "wrong_ancestry") { - return "wrong ancestry"; - } if (failure.code === "bad_description") { return `bad description (${failure.reason})`; } @@ -323,10 +388,14 @@ module.exports = { HYGIENE_BLOCK_START, HYGIENE_BLOCK_END, inlineCode, + escapeControlCharacters, + isGateComment, + isStandaloneHygieneComment, readinessChecklistLines, buildGateCommentBody, extractHygieneSection, withHygieneSection, + authoritativeHygieneSection, descriptionFailureLines, buildFailureSections, failureSummary, diff --git a/.github/scripts/pr-quality-messages.test.cjs b/.github/scripts/pr-quality-messages.test.cjs index c344ce1bc0..ad209ccc32 100644 --- a/.github/scripts/pr-quality-messages.test.cjs +++ b/.github/scripts/pr-quality-messages.test.cjs @@ -15,6 +15,10 @@ const { buildGateCommentBody, extractHygieneSection, withHygieneSection, + authoritativeHygieneSection, + escapeControlCharacters, + isGateComment, + isStandaloneHygieneComment, descriptionFailureLines, buildFailureSections, failureSummary, @@ -139,19 +143,17 @@ describe("buildFailureSections", () => { assert.match(sections, /@contributor Please retarget this PR to `dev`/); }); - it("builds ancestry, description, and screenshot sections", () => { + it("builds description and screenshot sections", () => { const sections = buildFailureSections( [ - { code: "wrong_ancestry" }, { code: "bad_description", reason: "empty" }, { code: "missing_ui_screenshot" } ], { pr: PR, allowedBases: ALLOWED_BASES, defaultBase: DEFAULT_BASE }, ).join("\n"); - assert.match(sections, /Wrong branch ancestry/); assert.match(sections, /Pull request description/); assert.match(sections, /UI screenshot required/); - assert.match(sections, /Rebase onto the current `main`/); + assert.doesNotMatch(sections, /Wrong branch ancestry/); }); }); @@ -161,14 +163,13 @@ describe("failureSummary", () => { failureSummary( [ { code: "wrong_base" }, - { code: "wrong_ancestry" }, { code: "bad_description", reason: "empty" }, { code: "missing_ui_screenshot" }, { code: "mystery" } ], { pr: PR }, ), - "wrong base (main); wrong ancestry; bad description (empty); missing UI screenshot; mystery", + "wrong base (main); bad description (empty); missing UI screenshot; mystery", ); }); }); @@ -421,3 +422,75 @@ describe("hygiene section round-trip", () => { assert.equal(afterGateSecond.split(HYGIENE_BLOCK_END).length - 1, 1); }); }); + +describe("authoritative hygiene section", () => { + const bot = { login: "github-actions[bot]" }; + const block = (lines) => + `${HYGIENE_BLOCK_START}\n${HYGIENE_MARKER}\n\n${lines.join("\n")}\n\n${HYGIENE_BLOCK_END}`; + + it("reads nothing from a block whose delimiters repeat on whole lines", () => { + const body = [GATE_MARKER, HYGIENE_BLOCK_START, "a", HYGIENE_BLOCK_END, "b", HYGIENE_BLOCK_END].join("\n"); + assert.equal(extractHygieneSection(body), null); + const twoStarts = [GATE_MARKER, HYGIENE_BLOCK_START, HYGIENE_BLOCK_START, "a", HYGIENE_BLOCK_END].join("\n"); + assert.equal(extractHygieneSection(twoStarts), null); + }); + + it("prefers the gate comment's block over a standalone hygiene comment", () => { + const comments = [ + { user: bot, body: `${HYGIENE_MARKER}\n\nstandalone` }, + { user: bot, body: `${GATE_MARKER}\n\n${block(["from gate"])}` }, + ]; + assert.equal(authoritativeHygieneSection(comments), "from gate"); + }); + + it("falls back to the standalone comment only while the gate comment has no block", () => { + const standalone = { user: bot, body: `${HYGIENE_MARKER}\n\nstandalone` }; + assert.equal(authoritativeHygieneSection([{ user: bot, body: GATE_MARKER }, standalone]), standalone.body); + assert.equal(authoritativeHygieneSection([standalone]), standalone.body); + const ambiguous = { user: bot, body: [GATE_MARKER, HYGIENE_BLOCK_START, "a", HYGIENE_BLOCK_END, HYGIENE_BLOCK_END].join("\n") }; + assert.equal(authoritativeHygieneSection([ambiguous, standalone]), null); + }); + + it("ignores comments not written by the workflow bot", () => { + const human = { user: { login: "contributor" }, body: `${GATE_MARKER}\n\n${block(["forged"])}` }; + assert.equal(authoritativeHygieneSection([human]), null); + assert.equal(authoritativeHygieneSection(undefined), null); + }); +}); + +describe("echoed text and comment classification", () => { + const bot = { login: "github-actions[bot]" }; + + it("escapes control characters so echoed text stays on one line", () => { + assert.equal(escapeControlCharacters("src/a.ts"), "src/a.ts"); + assert.equal(escapeControlCharacters("a\nb\r\tc\u2028"), "a\\u000ab\\u000d\\u0009c\\u2028"); + assert.ok(!escapeControlCharacters("x\n" + HYGIENE_BLOCK_END).includes("\n")); + }); + + it("classifies a comment only by the marker its body starts with", () => { + assert.equal(isGateComment({ user: bot, body: GATE_MARKER + "\n\nbody" }), true); + assert.equal(isGateComment({ user: bot, body: HYGIENE_MARKER + "\n- x " + GATE_MARKER }), false); + assert.equal(isGateComment({ user: { login: "someone" }, body: GATE_MARKER }), false); + assert.equal(isStandaloneHygieneComment({ user: bot, body: HYGIENE_MARKER + "\n\nok" }), true); + assert.equal(isStandaloneHygieneComment({ user: bot, body: GATE_MARKER + "\n" + HYGIENE_MARKER }), false); + }); + + it("does not read a standalone hygiene comment that echoes the gate marker as the gate block", () => { + const standalone = { + user: bot, + body: [HYGIENE_MARKER, "- x " + GATE_MARKER, HYGIENE_BLOCK_START, "echoed", HYGIENE_BLOCK_END].join("\n"), + }; + assert.equal(authoritativeHygieneSection([standalone]), standalone.body); + }); +}); + +describe("hygiene block replacement", () => { + it("writes replacement tokens in hygiene lines literally", () => { + const base = withHygieneSection(GATE_MARKER, ["first"]); + for (const token of ["$&", "$1", "$`", "$'", "$$"]) { + const updated = withHygieneSection(base, ["Paths: src/" + token + ".ts"]); + assert.ok(updated.includes("Paths: src/" + token + ".ts"), token); + assert.equal(extractHygieneSection(updated), "Paths: src/" + token + ".ts", token); + } + }); +}); diff --git a/.github/scripts/pr-quality.cjs b/.github/scripts/pr-quality.cjs index ddee9226bb..edc95afbd8 100644 --- a/.github/scripts/pr-quality.cjs +++ b/.github/scripts/pr-quality.cjs @@ -12,9 +12,6 @@ const { READINESS_LATEST_DEV_BEHIND_MAX } = require( path.join(__dirname, "pr-quality-state.cjs") ); -const ANCESTRY_BEHIND_THRESHOLD = 20; -/** Cap on ahead_by vs main so stale `dev` forks (many commits ahead of main) are not flagged. */ -const ANCESTRY_AHEAD_MAIN_MAX = 5; const MIN_SECTION_LEN = 40; const MIN_RICH_SECTIONS = 2; const UNSTRUCTURED_MIN_LEN = 120; @@ -106,20 +103,6 @@ const MARKDOWN_REFERENCE_DEF_RE = /^\s*\[([^\]]+)\]:\s*\S+/gm; /** Embedded HTML image with a renderable `src` (``). */ const HTML_IMAGE_RE = /]*\bsrc\s*=\s*(?:"[^"]+"|'[^']+'|[^\s>"']+)[^>]*>/i; -function isWrongAncestry({ - behindMain, - behindBase, - aheadMain = 0, - threshold = ANCESTRY_BEHIND_THRESHOLD, - aheadMainMax = ANCESTRY_AHEAD_MAIN_MAX, -}) { - return ( - behindMain === 0 && - behindBase >= threshold && - aheadMain <= aheadMainMax - ); -} - function authorHasPushPermission(permission) { return permission === "admin" || permission === "maintain" || permission === "write"; } @@ -528,12 +511,6 @@ function collectPrQualityFailures({ allowedBases, title = "", body, - behindMain, - behindBase, - aheadMain = 0, - authorPermission, - permissionLookupFailed = false, - ancestryLookupFailed = false, /** True when baseRef is another open PR's head (stacked child). */ stackedBase = false, /** Issue comments; a maintainer comment waives the GUI-screenshot gate. */ @@ -550,21 +527,6 @@ function collectPrQualityFailures({ const wrongBase = !allowedBases.includes(baseRef) && !stackedBase; if (wrongBase) { failures.push({ code: "wrong_base" }); - } else { - // Permission lookup fails closed (still evaluate ancestry). Compare API - // failures skip ancestry — zeros would falsely pass the #644 heuristic. - // Stacked children skip ancestry against the integration base; their parent - // PR is the temporary target. - const skipAncestry = - stackedBase || - ancestryLookupFailed || - (!permissionLookupFailed && authorHasPushPermission(authorPermission)); - if ( - !skipAncestry && - isWrongAncestry({ behindMain, behindBase, aheadMain }) - ) { - failures.push({ code: "wrong_ancestry" }); - } } const desc = assessPrDescription(body); @@ -587,12 +549,9 @@ function collectPrQualityFailures({ } module.exports = { - ANCESTRY_BEHIND_THRESHOLD, - ANCESTRY_AHEAD_MAIN_MAX, REVIEW_READINESS_ITEMS, REVIEW_READINESS_START, REVIEW_READINESS_END, - isWrongAncestry, authorHasPushPermission, assessPrDescription, guiPathsChanged, diff --git a/.github/scripts/pr-quality.test.cjs b/.github/scripts/pr-quality.test.cjs index 996e5b0867..b4287bfeb0 100644 --- a/.github/scripts/pr-quality.test.cjs +++ b/.github/scripts/pr-quality.test.cjs @@ -3,9 +3,7 @@ const { describe, it } = require("node:test"); const assert = require("node:assert/strict"); const { - ANCESTRY_BEHIND_THRESHOLD, REVIEW_READINESS_ITEMS, - isWrongAncestry, authorHasPushPermission, assessPrDescription, hasGuiCue, @@ -25,32 +23,6 @@ const { collectPrQualityFailures, } = require("./pr-quality.cjs"); -describe("isWrongAncestry", () => { - it("flags #644-shaped compares (0 behind main, far behind base, few ahead of main)", () => { - assert.equal( - isWrongAncestry({ behindMain: 0, behindBase: 44, aheadMain: 1 }), - true, - ); - }); - - it("uses threshold 20 by default", () => { - assert.equal(ANCESTRY_BEHIND_THRESHOLD, 20); - assert.equal(isWrongAncestry({ behindMain: 0, behindBase: 20, aheadMain: 1 }), true); - assert.equal(isWrongAncestry({ behindMain: 0, behindBase: 19, aheadMain: 1 }), false); - }); - - it("passes when head is behind main (not sitting on main tip)", () => { - assert.equal(isWrongAncestry({ behindMain: 1, behindBase: 44, aheadMain: 1 }), false); - }); - - it("passes stale dev-based branches that are many commits ahead of main", () => { - assert.equal( - isWrongAncestry({ behindMain: 0, behindBase: 44, aheadMain: 50 }), - false, - ); - }); -}); - describe("authorHasPushPermission", () => { it("accepts write/maintain/admin only", () => { assert.equal(authorHasPushPermission("admin"), true); @@ -680,12 +652,8 @@ describe("collectPrQualityFailures", () => { baseRef: "main", allowedBases: allowed, body: "## Summary\n" + "x".repeat(50) + "\n\n## Test plan\n" + "y".repeat(50), - behindMain: 0, - behindBase: 0, - authorPermission: "read", }); assert.ok(failures.some((f) => f.code === "wrong_base")); - assert.ok(!failures.some((f) => f.code === "wrong_ancestry")); }); it("reports wrong_base and bad_description together for main + empty body", () => { @@ -693,16 +661,16 @@ describe("collectPrQualityFailures", () => { baseRef: "main", allowedBases: allowed, body: "", - behindMain: 0, - behindBase: 0, - authorPermission: "read", }); assert.ok(failures.some((f) => f.code === "wrong_base")); assert.ok(failures.some((f) => f.code === "bad_description")); - assert.ok(!failures.some((f) => f.code === "wrong_ancestry")); }); - it("reports wrong_ancestry for contributor on #644-shaped compare", () => { + it("no longer fails a contributor for sitting on the deleted main tip", () => { + // The old `main...head` heuristic flagged a head that was level with + // `main` but far behind `dev`. `main` no longer exists, so there is no tip + // to compare against and no ancestry failure to raise. Being far behind + // `dev` is handled by the review-readiness latest-dev claim instead. const failures = collectPrQualityFailures({ baseRef: "dev", allowedBases: allowed, @@ -714,91 +682,17 @@ describe("collectPrQualityFailures", () => { "- Launch the tray app after setting CODEX_HOME", "- Confirm the listener and launcher use the same workspace root", ].join("\n"), - behindMain: 0, - behindBase: 44, - aheadMain: 1, - authorPermission: "read", }); - assert.deepEqual( - failures.map((f) => f.code), - ["wrong_ancestry"], - ); + assert.deepEqual(failures, []); }); - it("skips ancestry for push permission but still flags bad description", () => { + it("still flags a bad description for a contributor head", () => { const failures = collectPrQualityFailures({ baseRef: "dev", allowedBases: allowed, body: "", - behindMain: 0, - behindBase: 44, - aheadMain: 1, - authorPermission: "write", - }); - assert.ok(!failures.some((f) => f.code === "wrong_ancestry")); - assert.ok(failures.some((f) => f.code === "bad_description")); - }); - - it("applies ancestry when permission lookup failed (fail closed)", () => { - const failures = collectPrQualityFailures({ - baseRef: "dev", - allowedBases: allowed, - body: [ - "## Summary", - "This change updates the Windows tray launcher so it resolves CODEX_HOME through the shared helper instead of a hardcoded path.", - "", - "## Test plan", - "- Launch the tray app after setting CODEX_HOME", - "- Confirm the listener and launcher use the same workspace root", - ].join("\n"), - behindMain: 0, - behindBase: 44, - aheadMain: 1, - authorPermission: null, - permissionLookupFailed: true, - }); - assert.ok(failures.some((f) => f.code === "wrong_ancestry")); - }); - - it("does not flag stale dev-based branches that are far ahead of main", () => { - const failures = collectPrQualityFailures({ - baseRef: "dev", - allowedBases: allowed, - body: [ - "## Summary", - "This change updates the Windows tray launcher so it resolves CODEX_HOME through the shared helper instead of a hardcoded path.", - "", - "## Test plan", - "- Launch the tray app after setting CODEX_HOME", - "- Confirm the listener and launcher use the same workspace root", - ].join("\n"), - behindMain: 0, - behindBase: 44, - aheadMain: 50, - authorPermission: "read", - }); - assert.ok(!failures.some((f) => f.code === "wrong_ancestry")); - }); - - it("skips ancestry when compare lookup failed (cannot evaluate)", () => { - const failures = collectPrQualityFailures({ - baseRef: "dev", - allowedBases: allowed, - body: [ - "## Summary", - "This change updates the Windows tray launcher so it resolves CODEX_HOME through the shared helper instead of a hardcoded path.", - "", - "## Test plan", - "- Launch the tray app after setting CODEX_HOME", - "- Confirm the listener and launcher use the same workspace root", - ].join("\n"), - behindMain: 0, - behindBase: 0, - aheadMain: 0, - authorPermission: "read", - ancestryLookupFailed: true, }); - assert.ok(!failures.some((f) => f.code === "wrong_ancestry")); + assert.deepEqual(failures.map((f) => f.code), ["bad_description"]); }); it("skips wrong_base when stackedBase is set", () => { @@ -813,14 +707,9 @@ describe("collectPrQualityFailures", () => { "- Launch the tray app after setting CODEX_HOME", "- Confirm the listener and launcher use the same workspace root", ].join("\n"), - behindMain: 0, - behindBase: 44, - aheadMain: 1, - authorPermission: "read", stackedBase: true, }); assert.ok(!failures.some((f) => f.code === "wrong_base")); - assert.ok(!failures.some((f) => f.code === "wrong_ancestry")); }); it("still flags wrong_base for non-allow-list bases without stackedBase", () => { @@ -828,9 +717,6 @@ describe("collectPrQualityFailures", () => { baseRef: "main", allowedBases: allowed, body: "fix stuff", - behindMain: 0, - behindBase: 0, - authorPermission: "read", stackedBase: false, }); assert.ok(failures.some((f) => f.code === "wrong_base")); @@ -842,9 +728,6 @@ describe("collectPrQualityFailures", () => { allowedBases: allowed, title: "Fix dashboard spacing", body: richBody, - behindMain: 0, - behindBase: 0, - authorPermission: "read", changedFilePaths: ["gui/src/App.tsx"], }); assert.ok(failures.some((f) => f.code === "missing_ui_screenshot")); @@ -856,9 +739,6 @@ describe("collectPrQualityFailures", () => { allowedBases: allowed, title: "GUI: fix provider list spacing", body: richBody, - behindMain: 0, - behindBase: 0, - authorPermission: "read", changedFilePaths: ["scripts/foo.ts"], }); assert.ok(!failures.some((f) => f.code === "missing_ui_screenshot")); @@ -871,9 +751,6 @@ describe("collectPrQualityFailures", () => { allowedBases: allowed, title: "Large refactor", body: richBody, - behindMain: 0, - behindBase: 0, - authorPermission: "read", changedFilePaths: truncatedPaths, filesTruncated: true, }); @@ -888,9 +765,6 @@ describe("collectPrQualityFailures", () => { allowedBases: allowed, title: "Large refactor with gui tweak", body: richBody, - behindMain: 0, - behindBase: 0, - authorPermission: "read", changedFilePaths: truncatedPaths, filesTruncated: true, }); @@ -909,9 +783,6 @@ describe("collectPrQualityFailures", () => { "## Test plan", "- Ran bun test tests/ci-workflows/ci-workflows.test.ts", ].join("\n"), - behindMain: 0, - behindBase: 0, - authorPermission: "read", changedFilePaths: ["scripts/foo.ts"], }); assert.ok(!failures.some((f) => f.code === "missing_ui_screenshot")); @@ -929,9 +800,6 @@ describe("collectPrQualityFailures", () => { "## Test plan", "- Ran bun test tests/ci-workflows/ci-workflows.test.ts", ].join("\n"), - behindMain: 0, - behindBase: 0, - authorPermission: "read", changedFilePaths: ["gui/src/styles.css"], }); assert.ok(failures.some((f) => f.code === "missing_ui_screenshot")); @@ -949,9 +817,6 @@ describe("collectPrQualityFailures", () => { "## Test plan", "- Ran bun test tests/ci-workflows/ci-workflows.test.ts", ].join("\n"), - behindMain: 0, - behindBase: 0, - authorPermission: "read", changedFilePaths: ["gui/src/App.tsx"], guiOverrideComments: [ { author_association: "OWNER", body: "no gui changes here" }, @@ -972,9 +837,6 @@ describe("collectPrQualityFailures", () => { "## Test plan", "- Ran bun test tests/ci-workflows/ci-workflows.test.ts", ].join("\n"), - behindMain: 0, - behindBase: 0, - authorPermission: "read", changedFilePaths: ["gui/src/App.tsx"], guiOverrideComments: [ { author_association: "CONTRIBUTOR", body: "no gui changes here" }, @@ -997,9 +859,6 @@ describe("collectPrQualityFailures", () => { "## Test plan", "- Ran bun test tests/ci-workflows/ci-workflows.test.ts", ].join("\n"), - behindMain: 0, - behindBase: 0, - authorPermission: "read", changedFilePaths: ["gui/src/App.tsx"], }); assert.ok(!failures.some((f) => f.code === "missing_ui_screenshot")); @@ -1021,9 +880,6 @@ describe("collectPrQualityFailures", () => { "## Test plan", "- Ran bun test tests/ci-workflows/ci-workflows.test.ts", ].join("\n"), - behindMain: 0, - behindBase: 0, - authorPermission: "read", changedFilePaths: ["gui/src/App.tsx"], }); assert.ok(!failures.some((f) => f.code === "missing_ui_screenshot")); @@ -1045,9 +901,6 @@ describe("collectPrQualityFailures", () => { "## Test plan", "- Ran bun test tests/ci-workflows/ci-workflows.test.ts", ].join("\n"), - behindMain: 0, - behindBase: 0, - authorPermission: "read", changedFilePaths: ["gui/src/App.tsx"], }); assert.ok(failures.some((f) => f.code === "missing_ui_screenshot")); @@ -1071,9 +924,6 @@ describe("collectPrQualityFailures", () => { "- [ ] Docs or release notes were updated when needed.", "- [ ] Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.", ].join("\n"), - behindMain: 0, - behindBase: 0, - authorPermission: "read", }); assert.ok(!failures.some((f) => f.code === "missing_ui_screenshot")); }); diff --git a/.github/scripts/release-dispatch-guard.cjs b/.github/scripts/release-dispatch-guard.cjs index 507cd3e787..5350419523 100644 --- a/.github/scripts/release-dispatch-guard.cjs +++ b/.github/scripts/release-dispatch-guard.cjs @@ -1,44 +1,22 @@ "use strict"; -const ALLOWED_RELEASE_REFS = new Set([ - "refs/heads/main", - "refs/heads/preview", -]); +const ALLOWED_RELEASE_REFS = new Set(["refs/heads/dev"]); +const FULL_SHA = /^[0-9a-f]{40}$/; -function validateReleaseDispatch({ - eventName, - ref, - expectedSha, - actualSha, -}) { +function validateReleaseDispatch({ eventName, ref, sourceSha, workflowSha, expectedSha, actualSha }) { if (eventName !== "workflow_dispatch") { return `Release must be triggered by workflow_dispatch; got ${eventName || "(empty)"}.`; } - if (!ALLOWED_RELEASE_REFS.has(ref)) { - return `Release must run from main or preview; got ${ref || "(empty)"}.`; - } - - if (!expectedSha) { - return "expected-sha is required; refusing to publish without an audited commit."; - } - - if (!/^[0-9a-f]{40}$/.test(expectedSha)) { - return `expected-sha must be a full 40-character commit SHA; got ${expectedSha}.`; - } - - if (actualSha !== expectedSha) { - return ( - `branch moved after the release audit ` + - `(expected ${expectedSha}, got ${actualSha || "(empty)"}) — ` + - "refusing to publish an unaudited commit." - ); + return `Release must run from dev; got ${ref || "(empty)"}.`; } - + // Accept the old parameter names while callers migrate; the source is independently + // validated by release-evidence, not compared with the workflow revision. + const source = sourceSha ?? expectedSha ?? ""; + const workflow = workflowSha ?? actualSha ?? ""; + if (source && !FULL_SHA.test(source)) return "source-sha must be a full 40-character commit SHA."; + if (!FULL_SHA.test(workflow)) return "workflow SHA must be a full 40-character commit SHA."; return null; } -module.exports = { - ALLOWED_RELEASE_REFS, - validateReleaseDispatch, -}; +module.exports = { ALLOWED_RELEASE_REFS, validateReleaseDispatch }; diff --git a/.github/scripts/release-dispatch-guard.test.cjs b/.github/scripts/release-dispatch-guard.test.cjs index 7833ca0976..d1b1382b2f 100644 --- a/.github/scripts/release-dispatch-guard.test.cjs +++ b/.github/scripts/release-dispatch-guard.test.cjs @@ -4,63 +4,50 @@ const { describe, it } = require("node:test"); const assert = require("node:assert/strict"); const { validateReleaseDispatch } = require("./release-dispatch-guard.cjs"); -const SHA = "0123456789abcdef0123456789abcdef01234567"; -const OTHER_SHA = "89abcdef0123456789abcdef0123456789abcdef"; +const SOURCE_SHA = "0123456789abcdef0123456789abcdef01234567"; +const WORKFLOW_SHA = "89abcdef0123456789abcdef0123456789abcdef"; function validate(overrides = {}) { return validateReleaseDispatch({ eventName: "workflow_dispatch", - ref: "refs/heads/main", - expectedSha: SHA, - actualSha: SHA, + ref: "refs/heads/dev", + sourceSha: SOURCE_SHA, + workflowSha: WORKFLOW_SHA, ...overrides, }); } describe("release dispatch guard", () => { - it("accepts an exact audited SHA on main", () => { + it("accepts a source distinct from the trusted workflow revision", () => { + assert.notEqual(SOURCE_SHA, WORKFLOW_SHA); assert.equal(validate(), null); }); - it("accepts an exact audited SHA on preview", () => { - assert.equal( - validate({ ref: "refs/heads/preview" }), - null, - ); + it("allows an omitted source for subsequent evidence resolution", () => { + assert.equal(validate({ sourceSha: "" }), null); }); - it("rejects non-workflow_dispatch events", () => { - assert.match( - validate({ eventName: "push" }), - /must be triggered by workflow_dispatch/, - ); + it("rejects non-dispatch events", () => { + for (const eventName of ["push", "pull_request", "", undefined]) { + assert.match(validate({ eventName }), /must be triggered by workflow_dispatch/); + } }); - it("rejects release dispatches from unapproved refs", () => { - assert.match( - validate({ ref: "refs/heads/dev" }), - /must run from main or preview/, - ); + it("rejects every non-dev ref", () => { + for (const ref of ["refs/heads/main", "refs/heads/preview", "refs/heads/feature", "refs/tags/dev", "dev", "", undefined]) { + assert.match(validate({ ref }), /must run from dev/); + } }); - it("requires expected-sha", () => { - assert.match( - validate({ expectedSha: "" }), - /expected-sha is required/, - ); + it("rejects malformed nonempty source SHAs", () => { + for (const sourceSha of ["0123456", "A".repeat(40), "g".repeat(40), "a".repeat(41), ` ${SOURCE_SHA}`]) { + assert.match(validate({ sourceSha }), /source-sha must be a full 40-character commit SHA/); + } }); - it("requires a full 40-character commit SHA", () => { - assert.match( - validate({ expectedSha: "0123456" }), - /full 40-character commit SHA/, - ); - }); - - it("rejects when the selected ref moved after audit", () => { - assert.match( - validate({ actualSha: OTHER_SHA }), - /branch moved after the release audit/, - ); + it("requires a valid full workflow SHA even when source is omitted", () => { + for (const workflowSha of ["", undefined, "0123456", "A".repeat(40), "g".repeat(40), "a".repeat(41)]) { + assert.match(validate({ sourceSha: "", workflowSha }), /workflow SHA must be a full 40-character commit SHA/); + } }); }); diff --git a/.github/scripts/release-evidence-policy.json b/.github/scripts/release-evidence-policy.json new file mode 100644 index 0000000000..835a8e15a4 --- /dev/null +++ b/.github/scripts/release-evidence-policy.json @@ -0,0 +1,306 @@ +[ + { + "kind": "ci", + "version": 1, + "files": { + ".github/workflows/ci.yml": "b9c739e5d80e915d20bf776b1c698d92a0f01464", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "ce462107c70c4d1d33b1a88169bcaf07a2bc380a", + ".github/scripts/release-evidence.test.cjs": "a05e126ee2c17f00f1f4fb06c84eae2655aa1576", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405", + "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f", + "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29", + "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41", + "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } + }, + { + "kind": "ci", + "version": 1, + "files": { + ".github/workflows/ci.yml": "5cef76e77d391873e35012b3e9318c3d54e86da5", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd", + ".github/scripts/release-evidence.test.cjs": "4ecdd6ea059794e424372f6afc0eb850f32061f4", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405", + "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f", + "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29", + "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41", + "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } + }, + { + "kind": "service", + "version": 1, + "files": { + ".github/workflows/service-lifecycle.yml": "496319bee65c1030cf7905406b85fb9e716a22d5", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d" + } + }, + { + "kind": "ci", + "version": 1, + "files": { + ".github/workflows/ci.yml": "a53d40c6d971bba9a33c546f242c78b0f7695680", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd", + ".github/scripts/release-evidence.test.cjs": "4ecdd6ea059794e424372f6afc0eb850f32061f4", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405", + "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f", + "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29", + "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41", + "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } + }, + { + "kind": "ci", + "version": 1, + "files": { + ".github/workflows/ci.yml": "562e63d6bd140944d8c6ba808010913463c75826", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd", + ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405", + "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f", + "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29", + "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41", + "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } + }, + { + "kind": "ci", + "version": 1, + "files": { + ".github/workflows/ci.yml": "4d1d82f1d26d95d2448b1269dde1b7b14b73455e", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd", + ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405", + "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f", + "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29", + "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41", + "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } + }, + { + "kind": "ci", + "version": 1, + "files": { + ".github/workflows/ci.yml": "dc5496ad7e6a146a94fbe8dfeaa3b73461feafbc", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd", + ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405", + "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f", + "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29", + "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41", + "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } + }, + { + "kind": "service", + "version": 1, + "files": { + ".github/workflows/service-lifecycle.yml": "87249bf4d19ce47a6eafa59703fd8e52453cc924", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d" + } + }, + { + "kind": "ci", + "version": 1, + "files": { + ".github/workflows/ci.yml": "dc5496ad7e6a146a94fbe8dfeaa3b73461feafbc", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd", + ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405", + "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f", + "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29", + "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41", + "scripts/generate-ocx-skill-surface.ts": "155e866656ba2d71e8fd48adda857451caf16322", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } + }, + { + "kind": "ci", + "version": 1, + "files": { + ".github/workflows/ci.yml": "dc5496ad7e6a146a94fbe8dfeaa3b73461feafbc", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd", + ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405", + "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f", + "scripts/ci/test-durations.windows.tsv": "18c65823d855bb592cdd59bd102399bd9ead3967", + "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41", + "scripts/generate-ocx-skill-surface.ts": "155e866656ba2d71e8fd48adda857451caf16322", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } + }, + { + "kind": "ci", + "version": 1, + "files": { + ".github/workflows/ci.yml": "dc5496ad7e6a146a94fbe8dfeaa3b73461feafbc", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd", + ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405", + "scripts/ci/test-durations.tsv": "6ff82545debbd95286928a7a99abfdeb10020a7a", + "scripts/ci/test-durations.windows.tsv": "18c65823d855bb592cdd59bd102399bd9ead3967", + "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41", + "scripts/generate-ocx-skill-surface.ts": "155e866656ba2d71e8fd48adda857451caf16322", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } + } +] diff --git a/.github/scripts/release-evidence.cjs b/.github/scripts/release-evidence.cjs new file mode 100644 index 0000000000..c4cd8c762a --- /dev/null +++ b/.github/scripts/release-evidence.cjs @@ -0,0 +1,364 @@ +'use strict'; + +// Policy is loaded from the trusted release workflow revision, not the candidate. +// It pins the workflow, local setup action and enumerated CI job/test-selection +// helpers; it does not pin the candidate's whole source tree or every transitive +// test/build dependency. Those inputs, package scripts and repository writers are +// trusted through normal dev review. This is not a defence against a writer who +// can change trusted policy. Security review must assess that boundary separately. +// After reviewing an intentional policy-path change, update its Git blob ID in +// release-evidence-policy.json with `git hash-object --no-filters `, then +// run `node .github/scripts/release-evidence.cjs policy-check` and the evidence +// tests. Retain old approved entries if historical revisions must remain usable. +const APPROVED_POLICIES = require('./release-evidence-policy.json'); +const { execFileSync } = require('node:child_process'); +const { readFileSync } = require('node:fs'); +const { createHash } = require('node:crypto'); +const { resolve } = require('node:path'); +const REPOSITORY_ID = 1273824907; +const FULL_SHA = /^[0-9a-f]{40}$/; +const CI_JOBS = Object.freeze([ + 'changes', 'select windows runner', 'storage policy', 'api usage', 'gates', + ...Array.from({length: 5}, (_, i) => `test ${i + 1}/5`), + ...Array.from({length: 4}, (_, i) => `macos ${i + 1}/4`), + 'macos control', ...Array.from({length: 11}, (_, i) => `windows ${i + 1}/11`), + 'keyring ubuntu', 'keyring windows', 'keyring macos', 'docker smoke', + 'docs site build', 'structure gate', 'macos widget + bundle', 'desktop shell', + ...['ubuntu-latest', 'windows-latest', 'macos-latest'].flatMap(os => [ + `setup action ${os}`, `remote helper ${os}`, `npm-global ${os}`, + ]), 'ci', +]); + +function sha(value) { + if (typeof value !== 'string' || !FULL_SHA.test(value)) throw new Error('expected full lowercase commit SHA'); + return value; +} +function serviceJobs(sourceSha) { + sha(sourceSha); + return ['validate source', ...['linux-systemd', 'macos-launchd', 'windows-schtasks'].map(n => `${n} ${sourceSha}`)]; +} +function validateJobs(jobs, required) { + if (!Array.isArray(jobs)) throw new Error('invalid jobs response'); + const seen = new Set(); + for (const job of jobs) { + if (!job || typeof job.name !== 'string' || seen.has(job.name)) throw new Error('duplicate or malformed job'); + seen.add(job.name); + } + for (const name of required) { + const job = jobs.find(j => j.name === name); + if (!job || job.status !== 'completed' || job.conclusion !== 'success') throw new Error(`missing or unsuccessful job: ${name}`); + } + return true; +} +function apiClient(repository, token) { + if (repository !== 'lidge-jun/opencodex' || typeof token !== 'string' || !token) throw new Error('expected GH_TOKEN and GITHUB_REPOSITORY=lidge-jun/opencodex'); + const prefix = `https://api.github.com/repos/${repository}`; + return async path => { + if (path !== '' && (!path.startsWith('/') || path.startsWith('//'))) throw new Error('invalid API path'); + const response = await fetch(prefix + path, { + headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }, + redirect: 'error', + }); + if (!response.ok) throw new Error(`GitHub API request failed (${response.status})`); + return response.json(); + }; +} +async function pages(api, path, key, maxTotal = 1000) { + const collected = []; + let total; + for (let page = 1; ; page++) { + const data = await api(`${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`); + if (!data || !Number.isSafeInteger(data.total_count) || data.total_count < 0 || !Array.isArray(data[key]) || data[key].length > 100) throw new Error('invalid paginated response'); + if (total === undefined) total = data.total_count; + if (total !== data.total_count) throw new Error('pagination changed during lookup'); + if (total > maxTotal) throw new Error('pagination coverage exceeds the safe limit'); + if (data[key].length !== Math.min(100, total - collected.length)) throw new Error('incomplete pagination'); + collected.push(...data[key]); + if (collected.length === total) return collected; + if (!data[key].length || collected.length > total) throw new Error('incomplete pagination'); + } +} +async function treeEntry(api, commitSha, pathname) { + const commit = await api(`/git/commits/${sha(commitSha)}`); + let tree = commit?.tree?.sha; + if (!FULL_SHA.test(tree || '')) throw new Error('invalid commit tree'); + const parts = pathname.split('/'); + for (let i = 0; i < parts.length; i++) { + const data = await api(`/git/trees/${tree}`); + if (data.truncated || !Array.isArray(data.tree)) throw new Error('incomplete tree'); + const matches = data.tree.filter(entry => entry.path === parts[i]); + if (matches.length !== 1 || !FULL_SHA.test(matches[0].sha || '')) throw new Error('missing policy path'); + if (i === parts.length - 1) return matches[0]; + if (matches[0].type !== 'tree') throw new Error('invalid policy path'); + tree = matches[0].sha; + } + throw new Error('invalid policy path'); +} +async function assertPolicy(api, run, kind, policies) { + const candidates = policies.filter(p => p.kind === kind && p.version === 1 && p.files && typeof p.files === 'object'); + const workflowPath = `.github/workflows/${kind === 'ci' ? 'ci.yml' : 'service-lifecycle.yml'}`; + for (const policy of candidates) { + if (!Object.hasOwn(policy.files, workflowPath)) continue; + let matches = true; + for (const [path, expected] of Object.entries(policy.files)) { + let entry; + try { entry = await treeEntry(api, run.head_sha, path); } + catch (error) { + if (error.message === 'missing policy path') { matches = false; break; } + throw error; + } + if (!FULL_SHA.test(expected) || entry.type !== 'blob' || !['100644', '100755'].includes(entry.mode) || entry.sha !== expected) { matches = false; break; } + } + if (matches) return; + } + throw new Error(`unapproved ${kind} workflow or helper policy`); +} +const SERVICE_PATH = /^(?:src\/service\.ts|src\/service\/.+|desktop\/.+|src\/cli\.ts|src\/cli\/index\.ts|src\/lib\/bun-runtime\.ts|package\.json|bun\.lock|\.github\/workflows\/service-lifecycle\.yml|\.github\/workflows\/release\.yml)$/; +function serviceChangeRequired(paths) { + if (!Array.isArray(paths)) throw new Error('expected a list of changed paths'); + for (const path of paths) { + if (typeof path !== 'string' || !path || path.startsWith('/') || path.includes('\0') || path.split('/').some(part => !part || part === '.' || part === '..')) throw new Error('invalid changed path'); + } + return paths.some(path => SERVICE_PATH.test(path)); +} +function git(args) { + try { + return execFileSync('git', args, { encoding: 'buffer', maxBuffer: 100 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }); + } catch { + throw new Error('git could not verify the requested service range'); + } +} +function serviceRange(candidate, baseline) { + sha(candidate); + if (baseline !== '--initial') sha(baseline); + for (const commit of baseline === '--initial' ? [candidate] : [candidate, baseline]) { + if (git(['cat-file', '-t', commit]).toString('utf8').trim() !== 'commit') throw new Error('service range requires commit objects'); + } + const output = baseline === '--initial' + ? git(['ls-tree', '-r', '-z', '--name-only', '--full-tree', candidate]) + : (git(['merge-base', '--is-ancestor', baseline, candidate]), git(['diff', '--name-only', '-z', '--no-ext-diff', '--no-renames', baseline, candidate, '--'])); + let decoded; + try { decoded = new TextDecoder('utf-8', {fatal:true}).decode(output); } + catch { throw new Error('service range contains a non-UTF-8 path'); } + if (decoded && !decoded.endsWith('\0')) throw new Error('incomplete service range'); + return {required: serviceChangeRequired(decoded ? decoded.slice(0, -1).split('\0') : [])}; +} +function checkPolicyFiles(policies, root) { + const current = new Map(policies.map(policy => [policy.kind, policy])); + for (const kind of ['ci', 'service']) if (!current.has(kind)) throw new Error(`missing ${kind} evidence policy`); + for (const policy of current.values()) { + for (const [name, expected] of Object.entries(policy.files)) { + const bytes = readFileSync(resolve(root, name)); + const actual = createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex'); + if (actual !== expected) throw new Error(`policy fingerprint mismatch: ${name}`); + } + } + return true; +} +function validateRun(run, workflow, kind, sourceSha) { + if (!run || !Number.isSafeInteger(run.id) || run.id <= 0 || !Number.isSafeInteger(run.run_attempt) || run.run_attempt < 1 || + run.workflow_id !== workflow.id || run.repository?.id !== REPOSITORY_ID || run.head_repository?.id !== REPOSITORY_ID || + run.event !== 'workflow_dispatch' || run.head_branch !== 'dev' || run.status !== 'completed' || run.conclusion !== 'success') { + throw new Error('unqualified run metadata'); + } + sha(run.head_sha); + if (kind === 'ci' && (run.head_sha !== sourceSha || run.display_title !== `ocx-ci-v1 lane=all sha=${sourceSha}`)) throw new Error('CI lane or source mismatch'); +} +async function ancestor(api, base, head) { + sha(base); sha(head); + const data = await api(`/compare/${base}...${head}`); + if (!['ahead', 'behind', 'identical', 'diverged'].includes(data?.status)) throw new Error('invalid comparison'); + return data.status === 'ahead' || data.status === 'identical'; +} +// GitHub limits filtered workflow searches to 1,000 results. Discovery may +// inspect at most those 1,000; exact-SHA lists must fit completely in that cap. +// The compare bound and global request budget make failure explicit when a +// candidate is too old to prove newest within the available API budget. +const MAX_COMPARE_COMMITS = 200; +const MAX_API_REQUESTS = 800; +function createEvidence(rawApi, policies = APPROVED_POLICIES) { + let requestCount = 0; + const api = async path => { + if (++requestCount > MAX_API_REQUESTS) throw new Error('GitHub API request budget exceeded'); + return rawApi(path); + }; + const objects = new Map(); + const comparisons = new Map(); + async function policyApi(path) { + if (!/^\/git\/(?:commits|trees)\/[0-9a-f]{40}$/.test(path)) return api(path); + if (!objects.has(path)) objects.set(path, api(path).catch(error => { objects.delete(path); throw error; })); + return objects.get(path); + } + async function isAncestor(base, head) { + sha(base); sha(head); + if (base === head) return true; + const key = `${base}...${head}`; + if (!comparisons.has(key)) comparisons.set(key, ancestor(api, base, head)); + return comparisons.get(key); + } + async function workflow(kind) { + const filename = kind === 'ci' ? 'ci.yml' : 'service-lifecycle.yml'; + const [repo, wf] = await Promise.all([api(''), api(`/actions/workflows/${filename}`)]); + if (repo?.id !== REPOSITORY_ID || repo.full_name !== 'lidge-jun/opencodex' || wf?.path !== `.github/workflows/${filename}` || !Number.isSafeInteger(wf.id)) throw new Error('repository or workflow identity mismatch'); + return wf; + } + async function eligible(run, wf, kind, sourceSha) { + validateRun(run, wf, kind, sourceSha); + await assertPolicy(policyApi, run, kind, policies); + const jobs = await pages(api, `/actions/runs/${run.id}/attempts/${run.run_attempt}/jobs`, 'jobs'); + validateJobs(jobs, kind === 'ci' ? CI_JOBS : serviceJobs(sourceSha)); + } + async function qualifies(run, wf, kind, candidate, dev) { + try { + await eligible(run, wf, kind, candidate); + } catch (error) { + // API, pagination, resource limits and unknown errors are never evidence + // that a run is ineligible; stop instead of skipping them. + if (/^(unqualified run metadata|CI lane or source mismatch|unapproved .* workflow or helper policy|missing or unsuccessful job:|duplicate or malformed job|expected full lowercase commit SHA)/.test(error.message)) return false; + throw error; + } + return isAncestor(run.head_sha, dev); + } + function listPath(wf, head) { + const query = new URLSearchParams({event:'workflow_dispatch', branch:'dev', status:'success'}); + if (head) query.set('head_sha', sha(head)); + return `/actions/workflows/${wf.id}/runs?${query}`; + } + function signature(runs) { + const ids = new Set(); + return JSON.stringify(runs.map(run => { + if (!run || !Number.isSafeInteger(run.id) || run.id <= 0 || ids.has(run.id)) throw new Error('duplicate or malformed run'); + ids.add(run.id); + return [run.id,run.run_attempt,run.status,run.conclusion,run.head_sha,run.head_branch,run.event,run.workflow_id,run.repository?.id,run.head_repository?.id,run.display_title]; + })); + } + const snapshots = []; + async function exactRuns(wf, head) { + const path = listPath(wf, head); + const runs = await pages(api, path, 'workflow_runs'); + const stamp = signature(runs); + snapshots.push(async () => { + if (signature(await pages(api, path, 'workflow_runs')) !== stamp) throw new Error('run pagination changed during lookup'); + }); + return runs; + } + async function findEligible(runs, wf, kind, source, dev) { + for (const run of runs) { + const candidate = kind === 'ci' ? run.head_sha : source; + if (!FULL_SHA.test(candidate || '') || (kind === 'ci' && source && candidate !== source)) continue; + if (await qualifies(run, wf, kind, candidate, dev) && await isAncestor(candidate, dev)) return {sourceSha:candidate,ciRunId:run.id}; + } + return undefined; + } + async function discover(wf, dev) { + const path = listPath(wf); + const observed = []; + let total; + for (let page = 1; page <= 10; page++) { + const data = await api(`${path}&per_page=100&page=${page}`); + if (!data || !Number.isSafeInteger(data.total_count) || data.total_count < 0 || !Array.isArray(data.workflow_runs)) throw new Error('invalid paginated response'); + if (total === undefined) total = data.total_count; + if (total !== data.total_count) throw new Error('run pagination changed during lookup'); + const expected = Math.min(100, Math.max(0, total - observed.length)); + if (data.workflow_runs.length !== expected) throw new Error('incomplete run pagination'); + observed.push(...data.workflow_runs); + signature(observed); + const found = await findEligible(data.workflow_runs, wf, 'ci', undefined, dev); + if (found) { + const count = page, stamp = signature(observed), initialTotal = total; + snapshots.push(async () => { + const again = []; + for (let n = 1; n <= count; n++) { + const result = await api(`${path}&per_page=100&page=${n}`); + if (result?.total_count !== initialTotal || !Array.isArray(result.workflow_runs)) throw new Error('run pagination changed during lookup'); + again.push(...result.workflow_runs); + } + if (signature(again) !== stamp) throw new Error('run pagination changed during lookup'); + }); + return found; + } + if (observed.length === total) throw new Error('no qualifying ci evidence'); + } + throw new Error('run pagination coverage exceeds the safe limit'); + } + async function commitsSince(base, head) { + if (base === head) return []; + const collected = [], seen = new Set(); + let total; + for (let page = 1; ; page++) { + const data = await api(`/compare/${base}...${head}?per_page=100&page=${page}`); + if (data?.status !== 'ahead' || !Number.isSafeInteger(data.total_commits) || data.total_commits < 1 || !Array.isArray(data.commits)) throw new Error('invalid commit comparison'); + if (total === undefined) total = data.total_commits; + if (total !== data.total_commits) throw new Error('commit pagination changed during lookup'); + if (total > MAX_COMPARE_COMMITS) throw new Error('commit comparison coverage exceeds the safe limit'); + if (data.commits.length !== Math.min(100, total-collected.length)) throw new Error('incomplete commit pagination'); + for (const commit of data.commits) { + const value = sha(commit?.sha); + if (value === base || seen.has(value)) throw new Error('duplicate or malformed comparison commit'); + seen.add(value); collected.push(value); + } + if (collected.length === total) { + if (!seen.has(head)) throw new Error('incomplete commit comparison'); + return collected; + } + } + } + async function select(kind, sourceSha) { + if (!['ci','service'].includes(kind)) throw new Error('unknown evidence kind'); + if (sourceSha !== undefined) sha(sourceSha); + if (kind === 'service' && !sourceSha) throw new Error('service requires source SHA'); + if (!policies.some(policy => policy.kind === kind && policy.version === 1)) throw new Error(`no approved ${kind} evidence policy`); + const wf = await workflow(kind); + const dev = sha((await api('/commits/dev'))?.sha); + if (sourceSha && !await isAncestor(sourceSha, dev)) throw new Error('source is not a dev ancestor'); + let found; + if (sourceSha) { + // A service dispatch runs the workflow from dev and may test an older + // source; its head_sha is the workflow revision, not the tested source. + const runs = await exactRuns(wf, kind === 'ci' ? sourceSha : undefined); + found = await findEligible(runs, wf, kind, sourceSha, dev); + } else { + found = await discover(wf, dev); + const candidates = [found]; + for (const commit of await commitsSince(found.sourceSha, dev)) { + const runs = await exactRuns(wf, commit); + const candidate = await findEligible(runs, wf, 'ci', commit, dev); + if (candidate) candidates.push(candidate); + } + let newest; + for (const candidate of candidates) { + let includesAll = true; + for (const other of candidates) if (!await isAncestor(other.sourceSha, candidate.sourceSha)) { includesAll = false; break; } + if (includesAll) { + if (newest && newest.sourceSha !== candidate.sourceSha) throw new Error('ambiguous qualifying sources'); + newest = candidate; + } + } + if (!newest) throw new Error('ambiguous qualifying sources'); + found = newest; + } + if (!found) throw new Error(`no qualifying ${kind} evidence`); + for (const confirm of snapshots) await confirm(); + if (sha((await api('/commits/dev'))?.sha) !== dev) throw new Error('dev changed during evidence lookup'); + return found; + } + return { select }; +} +async function main(args) { + if (args[0] === 'service-range' && args.length === 3) { + process.stdout.write(`${JSON.stringify(serviceRange(args[1], args[2]))}\n`); + return; + } + if (args[0] === 'policy-check' && args.length === 1) { + checkPolicyFiles(APPROVED_POLICIES, resolve(__dirname, '../..')); + process.stdout.write('Evidence policy fingerprints match the working tree.\n'); + return; + } + if (!['resolve', 'check', 'service'].includes(args[0]) || args.length > 2 || (args[0] !== 'resolve' && args.length !== 2)) throw new Error('usage: release-evidence.cjs resolve [fullSha] | check | service | service-range | policy-check'); + if (args[1] !== undefined) sha(args[1]); + const evidence = createEvidence(apiClient(process.env.GITHUB_REPOSITORY, process.env.GH_TOKEN)); + const result = await evidence.select(args[0] === 'service' ? 'service' : 'ci', args[1]); + if (args[0] === 'resolve') process.stdout.write(`${JSON.stringify(result)}\n`); +} +if (require.main === module) main(process.argv.slice(2)).catch(error => { process.stderr.write(`release evidence: ${error.message}\n`); process.exitCode = 1; }); +module.exports = { CI_JOBS, serviceJobs, validateJobs, createEvidence, pages, validateRun, apiClient, serviceChangeRequired, serviceRange, checkPolicyFiles }; diff --git a/.github/scripts/release-evidence.test.cjs b/.github/scripts/release-evidence.test.cjs new file mode 100644 index 0000000000..de30ad3710 --- /dev/null +++ b/.github/scripts/release-evidence.test.cjs @@ -0,0 +1,372 @@ +'use strict'; +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const root = path.resolve(__dirname, '../..'); +const SHA = 'a'.repeat(40); + +test('full dispatch fixes path scopes and identifies its lane and SHA', () => { + const ci = fs.readFileSync(path.join(root, '.github/workflows/ci.yml'), 'utf8'); + assert.match(ci, /run-name:.*ocx-ci-v1.*github\.sha/); + for (const scope of ['gui', 'packaging', 'docs', 'structure', 'ci', 'desktop', 'native', 'setup_action', 'remote_helper']) { + assert.match(ci, new RegExp(`workflow_dispatch[^\\n]*lane[^\\n]*all[^\\n]*steps\\.filter\\.outputs\\.${scope}`)); + } +}); + +test('CI runs all release and Pages Node contract suites', () => { + const ci = fs.readFileSync(path.join(root, '.github/workflows/ci.yml'), 'utf8'); + const step = ci.split('\n').find(line => line.includes('node --test') && line.includes('release-evidence.test.cjs')); + assert.ok(step); + for (const suite of ['release-dispatch-guard.test.cjs','release-evidence.test.cjs','release-history.test.cjs','release-resume.test.cjs','deploy-docs.test.cjs']) assert.ok(step.includes(suite), suite); +}); + +test('service dispatch validates and binds the same full SHA in each job and checkout', () => { + const service = fs.readFileSync(path.join(root, '.github/workflows/service-lifecycle.yml'), 'utf8'); + assert.match(service, /source_sha:/); + assert.match(service, /\[0-9a-f\]\{40\}/); + for (const name of ['linux-systemd', 'macos-launchd', 'windows-schtasks']) { + assert.ok(service.includes('name: ' + name + ' ${{ github.event.inputs.source_sha')); + } + assert.equal((service.match(/ref: \$\{\{ github\.event_name == 'workflow_dispatch' && github\.event\.inputs\.source_sha \|\| github\.sha \}\}/g) || []).length, 3); +}); + +test('run attempt graph fails on missing, skipped and duplicate legs', () => { + const { validateJobs, CI_JOBS } = require('./release-evidence.cjs'); + const jobs = CI_JOBS.map(name => ({name, status:'completed', conclusion:'success'})); + assert.equal(validateJobs(jobs, CI_JOBS), true); + assert.throws(() => validateJobs(jobs.slice(1), CI_JOBS)); + assert.throws(() => validateJobs([...jobs, jobs[0]], CI_JOBS)); + assert.throws(() => validateJobs(jobs.map((j,i) => i ? j : {...j, conclusion:'skipped'}), CI_JOBS)); +}); + +test('service graph binds every leg to the exact tested SHA', () => { + const { validateJobs, serviceJobs } = require('./release-evidence.cjs'); + const names = serviceJobs(SHA); + const jobs = names.map(name => ({name, status:'completed', conclusion:'success'})); + assert.equal(validateJobs(jobs, names), true); + assert.throws(() => validateJobs(jobs, serviceJobs('b'.repeat(40)))); + assert.throws(() => serviceJobs('abc')); +}); + +test('authenticated client accepts repository root without allowing alternate hosts', async () => { + const { apiClient } = require('./release-evidence.cjs'); + const original = global.fetch; + const requests = []; + global.fetch = async (url, options) => { requests.push({url, options}); return {ok:true, json:async () => ({id:1273824907})}; }; + try { + const api = apiClient('lidge-jun/opencodex', 'token'); + assert.deepEqual(await api(''), {id:1273824907}); + assert.equal(requests[0].url, 'https://api.github.com/repos/lidge-jun/opencodex'); + await assert.rejects(api('//example.org'), /invalid API path/); + } finally { global.fetch = original; } +}); + +test('run identity rejects forged titles, wrong repository, branch, event and attempt', () => { + const { validateRun } = require('./release-evidence.cjs'); + const workflow = {id:42}; + const run = {id:7, workflow_id:42, repository:{id:1273824907}, head_repository:{id:1273824907}, event:'workflow_dispatch', head_branch:'dev', status:'completed', conclusion:'success', run_attempt:1, head_sha:SHA, display_title:`ocx-ci-v1 lane=all sha=${SHA}`}; + assert.doesNotThrow(() => validateRun(run, workflow, 'ci', SHA)); + for (const change of [{event:'push'}, {head_branch:'main'}, {conclusion:'failure'}, {run_attempt:0}, {repository:{id:2}}, {head_repository:{id:2}}, {display_title:`ocx-ci-v1 lane=release-gates sha=${SHA}`}, {display_title:`ocx-ci-v1 lane=windows-native-claim sha=${SHA}`}, {head_sha:'b'.repeat(40)}]) { + assert.throws(() => validateRun({...run, ...change}, workflow, 'ci', SHA)); + } +}); + +test('pagination reads all pages and refuses truncated or changing totals', async () => { + const { pages } = require('./release-evidence.cjs'); + const calls = []; + const api = async url => { calls.push(url); return url.endsWith('page=1') ? {total_count:101, jobs:Array.from({length:100}, (_,i) => i)} : {total_count:101, jobs:[100]}; }; + assert.equal((await pages(api, '/runs/1/jobs', 'jobs')).length, 101); + assert.equal(calls.length, 2); + await assert.rejects(pages(async () => ({total_count:2,jobs:[]}), '/runs/1/jobs', 'jobs'), /incomplete pagination/); + await assert.rejects(pages(async url => url.endsWith('page=1') ? {total_count:101,jobs:Array(100).fill(1)} : {total_count:102,jobs:[1,2]}, '/runs/1/jobs', 'jobs'), /pagination changed/); +}); + +test('selector authenticates policy and chooses the descendant, independent of run order', async () => { + const { createEvidence, CI_JOBS } = require('./release-evidence.cjs'); + const older = 'b'.repeat(40), newer = 'c'.repeat(40), tree = 'd'.repeat(40), blob = 'e'.repeat(40); + const mkRun = (id, head) => ({id, workflow_id:42, repository:{id:1273824907}, head_repository:{id:1273824907}, event:'workflow_dispatch', head_branch:'dev', status:'completed', conclusion:'success', run_attempt:2, head_sha:head, display_title:`ocx-ci-v1 lane=all sha=${head}`}); + const jobs = CI_JOBS.map(name => ({name, status:'completed', conclusion:'success'})); + const calls = []; + const api = async url => { + calls.push(url); + if (url === '') return {id:1273824907,full_name:'lidge-jun/opencodex'}; + if (url === '/actions/workflows/ci.yml') return {id:42,path:'.github/workflows/ci.yml'}; + if (url === '/commits/dev') return {sha:newer}; + if (url.startsWith('/compare/')) { const [base,head] = url.slice(9).split('...'); return {status:base === head ? 'identical' : base === older && head === newer ? 'ahead' : 'behind'}; } + if (url.startsWith('/actions/workflows/42/runs?')) return {total_count:2,workflow_runs:[mkRun(1,newer),mkRun(2,older)]}; + if (url.startsWith('/git/commits/')) return {tree:{sha:tree}}; + if (url === `/git/trees/${tree}`) return {truncated:false,tree:[{path:'.github',type:'tree',sha:tree},{path:'workflows',type:'tree',sha:tree},{path:'ci.yml',type:'blob',mode:'100644',sha:blob}]}; + if (/^\/actions\/runs\/[12]\/attempts\/2\/jobs\?/.test(url)) return {total_count:jobs.length,jobs}; + throw new Error(`unexpected API request ${url}`); + }; + const approved = [{kind:'ci',version:1,files:{'.github/workflows/ci.yml':blob}}]; + assert.deepEqual(await createEvidence(api, approved).select('ci'), {sourceSha:newer,ciRunId:1}); + assert.deepEqual(await createEvidence(api, approved).select('ci', older), {sourceSha:older,ciRunId:2}); + const historical = {kind:'ci',version:1,files:{'.github/workflows/absent.yml':blob,'.github/workflows/ci.yml':blob}}; + assert.deepEqual(await createEvidence(api, [historical, ...approved]).select('ci', older), {sourceSha:older,ciRunId:2}); + assert.ok(calls.some(url => url.includes('/attempts/2/jobs?'))); + await assert.rejects(createEvidence(api, [{kind:'ci',version:1,files:{'.github/workflows/ci.yml':'f'.repeat(40)}}]).select('ci'), /no qualifying/); + await assert.rejects(createEvidence(api, []).select('ci'), /no approved ci evidence policy/); +}); + +test('service uses setup action from the workflow revision rather than the historical candidate', () => { + const service = fs.readFileSync(path.join(root, '.github/workflows/service-lifecycle.yml'), 'utf8'); + assert.equal((service.match(/path: \.evidence-policy/g) || []).length, 3); + assert.equal((service.match(/ref: \$\{\{ github\.sha \}\}/g) || []).length, 3); + assert.equal((service.match(/uses: \.\/\.evidence-policy\/\.github\/actions\/setup-project-bun/g) || []).length, 3); +}); + +test('service evidence uses workflow revision policy and a complete current attempt for the candidate', async () => { + const { createEvidence, serviceJobs } = require('./release-evidence.cjs'); + const revision = 'b'.repeat(40), tree = 'c'.repeat(40), blob = 'd'.repeat(40); + const run = {id:9,workflow_id:43,repository:{id:1273824907},head_repository:{id:1273824907},event:'workflow_dispatch',head_branch:'dev',status:'completed',conclusion:'success',run_attempt:3,head_sha:revision}; + let jobs = serviceJobs(SHA).map(name => ({name,status:'completed',conclusion:'success'})); + const api = async url => { + if (url === '') return {id:1273824907,full_name:'lidge-jun/opencodex'}; + if (url === '/actions/workflows/service-lifecycle.yml') return {id:43,path:'.github/workflows/service-lifecycle.yml'}; + if (url === '/commits/dev') return {sha:revision}; + if (url.startsWith('/compare/')) return {status:'ahead'}; + if (url.startsWith('/actions/workflows/43/runs?')) return {total_count:1,workflow_runs:[run]}; + if (url === `/git/commits/${revision}`) return {tree:{sha:tree}}; + if (url === `/git/trees/${tree}`) return {truncated:false,tree:[{path:'.github',type:'tree',sha:tree},{path:'workflows',type:'tree',sha:tree},{path:'service-lifecycle.yml',type:'blob',mode:'100644',sha:blob}]}; + if (url.startsWith('/actions/runs/9/attempts/3/jobs?')) return {total_count:jobs.length,jobs}; + throw new Error(`unexpected API request ${url}`); + }; + const policy = [{kind:'service',version:1,files:{'.github/workflows/service-lifecycle.yml':blob}}]; + assert.deepEqual(await createEvidence(api, policy).select('service', SHA), {sourceSha:SHA,ciRunId:9}); + jobs = jobs.slice(1); + await assert.rejects(createEvidence(api, policy).select('service', SHA), /no qualifying/); + jobs = serviceJobs('e'.repeat(40)).map(name => ({name,status:'completed',conclusion:'success'})); + await assert.rejects(createEvidence(api, policy).select('service', SHA), /no qualifying/); +}); + +test('production policy pins the current workflows and job-selection helpers', () => { + const { execFileSync } = require('node:child_process'); + const policies = require('./release-evidence-policy.json'); + for (const kind of ['ci', 'service']) { + const policy = policies.filter(p => p.kind === kind && p.version === 1).at(-1); + assert.ok(policy); + const required = kind === 'ci' ? ['.github/workflows/ci.yml', '.github/actions/setup-project-bun/action.yml', 'scripts/ci/run-bun-test-batches.sh', 'scripts/ci/select-test-lane.sh', 'scripts/ci/windows-sensitive-diff.sh', 'scripts/test.ts', 'scripts/keyring-smoke.ts', 'desktop/scripts/verify-macos-runtime.sh', 'desktop/scripts/verify-linux-sidecar.sh', 'desktop/scripts/linux-packaged-e2e.ts'] : ['.github/workflows/service-lifecycle.yml', '.github/actions/setup-project-bun/action.yml']; + for (const name of required) assert.ok(policy.files[name], name); + for (const [name, digest] of Object.entries(policy.files)) { + assert.equal(execFileSync('git', ['hash-object', '--no-filters', name], {cwd:root,encoding:'utf8'}).trim(), digest, name); + } + } +}); + +test('service change detection handles initial trees, cumulative changes and deletions', () => { + const { serviceChangeRequired } = require('./release-evidence.cjs'); + assert.equal(serviceChangeRequired(['README.md', 'src/router.ts']), false); + for (const file of ['src/service.ts','src/service/daemon.ts','desktop/app/main.rs','src/cli.ts','src/cli/index.ts','src/lib/bun-runtime.ts','package.json','bun.lock','.github/workflows/service-lifecycle.yml','.github/workflows/release.yml']) { + assert.equal(serviceChangeRequired(['README.md',file]), true, file); + } + for (const file of ['src/service-other.ts','src/cli/index.ts.bak','nested/package.json']) assert.equal(serviceChangeRequired([file]), false, file); + assert.throws(() => serviceChangeRequired(null)); + assert.throws(() => serviceChangeRequired(['../src/service.ts'])); +}); + +test('service range accepts a reachable baseline or an explicit initial tree only', () => { + const { execFileSync } = require('node:child_process'); + const os = require('node:os'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ocx-service-evidence-')); + const git = (...args) => execFileSync('git', args, {cwd:dir,encoding:'utf8'}).trim(); + const script = path.join(root, '.github/scripts/release-evidence.cjs'); + const run = (...args) => JSON.parse(execFileSync(process.execPath, [script, 'service-range', ...args], {cwd:dir,encoding:'utf8',stdio:['ignore','pipe','pipe']})); + try { + git('init','-q'); git('config','user.email','fixture@localhost'); git('config','user.name','fixture'); + fs.mkdirSync(path.join(dir,'src/service'), {recursive:true}); + fs.writeFileSync(path.join(dir,'src/service/daemon.ts'),'one'); + git('add','.'); git('commit','-qm','initial'); const initial = git('rev-parse','HEAD'); + fs.writeFileSync(path.join(dir,'src/service/daemon.ts'),'two'); + git('add','.'); git('commit','-qm','service'); + fs.writeFileSync(path.join(dir,'README.md'),'other'); + git('add','.'); git('commit','-qm','later'); const later = git('rev-parse','HEAD'); + assert.deepEqual(run(initial,'--initial'), {required:true}); + assert.deepEqual(run(later,initial), {required:true}); + assert.deepEqual(run(later,later), {required:false}); + fs.unlinkSync(path.join(dir,'src/service/daemon.ts')); + git('add','-A'); git('commit','-qm','remove service'); const removed = git('rev-parse','HEAD'); + assert.deepEqual(run(removed,later), {required:true}); + assert.throws(() => run(initial,later)); + assert.throws(() => run(later)); + } finally { fs.rmSync(dir,{recursive:true,force:true}); } +}); + +test('policy approval check detects drift while retaining historical policies', () => { + const { checkPolicyFiles } = require('./release-evidence.cjs'); + const { createHash } = require('node:crypto'); + const os = require('node:os'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ocx-policy-check-')); + try { + const content = Buffer.from('reviewed'); + fs.writeFileSync(path.join(dir, 'file'),content); + const digest = createHash('sha1').update(`blob ${content.length}\0`).update(content).digest('hex'); + const policies = [{kind:'ci',files:{file:'f'.repeat(40)}}, {kind:'ci',files:{file:digest}}, {kind:'service',files:{file:digest}}]; + assert.equal(checkPolicyFiles(policies,dir), true); + fs.writeFileSync(path.join(dir,'file'),'changed'); + assert.throws(() => checkPolicyFiles(policies,dir), /fingerprint mismatch/); + assert.throws(() => checkPolicyFiles(policies.slice(0,2),dir), /missing service/); + } finally { fs.rmSync(dir,{recursive:true,force:true}); } +}); + +test('default production policy accepts its exact blobs and rejects a changed helper', async () => { + const { createEvidence, CI_JOBS } = require('./release-evidence.cjs'); + const policy = require('./release-evidence-policy.json').filter(p => p.kind === 'ci').at(-1); + const run = {id:88, workflow_id:42, repository:{id:1273824907},head_repository:{id:1273824907},event:'workflow_dispatch',head_branch:'dev',status:'completed',conclusion:'success',run_attempt:1,head_sha:SHA,display_title:`ocx-ci-v1 lane=all sha=${SHA}`}; + const jobs = CI_JOBS.map(name => ({name,status:'completed',conclusion:'success'})); + const trees = new Map(); + const directorySha = path => require('node:crypto').createHash('sha1').update(path).digest('hex'); + const treeFor = path => { const id = directorySha(path); if (!trees.has(id)) trees.set(id, []); return trees.get(id); }; + treeFor(''); + for (const [file, id] of Object.entries(policy.files)) { + const parts = file.split('/'); let current = ''; + for (const part of parts.slice(0,-1)) { + const next = current ? `${current}/${part}` : part; + if (!treeFor(current).some(e => e.path === part)) treeFor(current).push({path:part,type:'tree',mode:'040000',sha:directorySha(next)}); + treeFor(next); current = next; + } + treeFor(current).push({path:parts.at(-1),type:'blob',mode:'100644',sha:id}); + } + const api = async url => { + if (url === '') return {id:1273824907,full_name:'lidge-jun/opencodex'}; + if (url === '/actions/workflows/ci.yml') return {id:42,path:'.github/workflows/ci.yml'}; + if (url === '/commits/dev') return {sha:SHA}; + if (url.startsWith('/compare/')) return {status:'identical'}; + if (url.startsWith('/actions/workflows/42/runs?')) return {total_count:1,workflow_runs:[run]}; + if (url === `/git/commits/${SHA}`) return {tree:{sha:directorySha('')}}; + if (url.startsWith('/git/trees/')) return {truncated:false,tree:trees.get(url.slice('/git/trees/'.length))}; + if (url.startsWith('/actions/runs/88/attempts/1/jobs?')) return {total_count:jobs.length,jobs}; + throw new Error(`unexpected API request ${url}`); + }; + assert.deepEqual(await createEvidence(api).select('ci', SHA), {sourceSha:SHA,ciRunId:88}); + const script = treeFor('scripts/ci').find(e => e.path === 'run-bun-test-batches.sh'); + script.sha = 'f'.repeat(40); + await assert.rejects(createEvidence(api).select('ci', SHA), /no qualifying/); +}); + +function boundedFixture({ runs, order, race = false, raceState = false, devMoves = false, divergent = [], history = ['1','2','3'].map(x => x.repeat(40)) }) { + const { CI_JOBS } = require('./release-evidence.cjs'); + const tree = 'd'.repeat(40), blob = 'e'.repeat(40), calls = []; + let exactReads = 0; + const readsByHead = new Map(); + let devReads = 0; + const api = async url => { + calls.push(url); + if (url === '') return {id:1273824907,full_name:'lidge-jun/opencodex'}; + if (url === '/actions/workflows/ci.yml') return {id:42,path:'.github/workflows/ci.yml'}; + if (url === '/commits/dev') return {sha:devMoves && ++devReads > 1 ? 'f'.repeat(40) : history.at(-1)}; + if (url.startsWith('/compare/')) { + const parsed = new URL(url, 'https://fixture.invalid'); + const [base, head] = parsed.pathname.slice(9).split('...'); + const a=history.indexOf(base), b=history.indexOf(head); + const status = a===b ? 'identical' : divergent.includes(base) && divergent.includes(head) ? 'diverged' : a ({sha})) : []; + const page = Number(parsed.searchParams.get('page') || 1), size = Number(parsed.searchParams.get('per_page') || 100); + return {status,total_commits:commits.length,commits:commits.slice((page-1)*size,page*size)}; + } + if (url.startsWith('/actions/workflows/42/runs?')) { + const query = new URL(url, 'https://fixture.invalid').searchParams; + if (query.get('event') !== 'workflow_dispatch' || query.get('branch') !== 'dev') throw new Error('unfiltered 25000-run history'); + const head = query.get('head_sha'); + if (head) { exactReads++; readsByHead.set(head, (readsByHead.get(head) || 0) + 1); } + let selected = runs.map(r => raceState && head && readsByHead.get(head) > 1 && r.status === 'in_progress' ? {...r,status:'completed',conclusion:'success'} : r) + .filter(r => (!head || r.head_sha === head) && (!query.has('status') || r.conclusion === query.get('status'))); + if (order) selected = [...selected].sort((a,b) => order.indexOf(a.id)-order.indexOf(b.id)); + const page=Number(query.get('page') || 1), size=Number(query.get('per_page') || 100); + const total_count = selected.length + (race && head && exactReads > 1 ? 1 : 0); + return {total_count,workflow_runs:selected.slice((page-1)*size,page*size)}; + } + if (url.startsWith('/git/commits/')) return {tree:{sha:tree}}; + if (url === `/git/trees/${tree}`) return {truncated:false,tree:[{path:'.github',type:'tree',sha:tree},{path:'workflows',type:'tree',sha:tree},{path:'ci.yml',type:'blob',mode:'100644',sha:blob}]}; + if (/^\/actions\/runs\/\d+\/attempts\/1\/jobs\?/.test(url)) return {total_count:CI_JOBS.length,jobs:CI_JOBS.map(name => ({name,status:'completed',conclusion:'success'}))}; + throw new Error(`unexpected API request ${url}`); + }; + const makeRun = (id, source, conclusion='success') => ({id,workflow_id:42,repository:{id:1273824907},head_repository:{id:1273824907},event:'workflow_dispatch',head_branch:'dev',status:'completed',conclusion,run_attempt:1,head_sha:source,display_title:`ocx-ci-v1 lane=all sha=${source}`}); + return {api,calls,history,makeRun,policies:[{kind:'ci',version:1,files:{'.github/workflows/ci.yml':blob}}]}; +} + +test('exact SHA filters 25000 unrelated runs on the server', async () => { + const {createEvidence} = require('./release-evidence.cjs'); + const data = boundedFixture({runs:[]}); + const old = data.history[0]; + const run = data.makeRun(7,old); + const fixture = boundedFixture({runs:[run]}); + assert.deepEqual(await createEvidence(fixture.api,fixture.policies).select('ci',old), {sourceSha:old,ciRunId:7}); + assert.ok(fixture.calls.filter(x=>x.startsWith('/actions/workflows/42/runs?')).every(x=>new URL(x,'https://fixture.invalid').searchParams.get('head_sha')===old)); +}); + +test('newest selection proves ancestry independently of run completion ordering', async () => { + const {createEvidence} = require('./release-evidence.cjs'); + const seed = boundedFixture({runs:[]}), [older,,newer] = seed.history; + const fixture = boundedFixture({runs:[seed.makeRun(1,older),seed.makeRun(2,newer)],order:[1,2]}); + assert.deepEqual(await createEvidence(fixture.api,fixture.policies).select('ci'), {sourceSha:newer,ciRunId:2}); + assert.ok(fixture.calls.some(x=>x.startsWith('/compare/') && x.includes('per_page='))); +}); + +test('newer failed runs do not hide an older qualifying commit', async () => { + const {createEvidence} = require('./release-evidence.cjs'); + const seed = boundedFixture({runs:[]}), [older,,newer] = seed.history; + const fixture = boundedFixture({runs:[seed.makeRun(2,newer,'failure'),seed.makeRun(1,older)],order:[2,1]}); + assert.deepEqual(await createEvidence(fixture.api,fixture.policies).select('ci'), {sourceSha:older,ciRunId:1}); +}); + +test('more than 1000 failed newer runs do not exhaust the filtered search', async () => { + const {createEvidence} = require('./release-evidence.cjs'); + const seed=boundedFixture({runs:[]}), [older,,newer]=seed.history; + const failures=Array.from({length:1101},(_,i)=>seed.makeRun(i+2,newer,'failure')); + const fixture=boundedFixture({runs:[...failures,seed.makeRun(1,older)]}); + assert.deepEqual(await createEvidence(fixture.api,fixture.policies).select('ci'), {sourceSha:older,ciRunId:1}); +}); + +test('exact SHA pagination and concurrent list changes fail closed', async () => { + const {createEvidence} = require('./release-evidence.cjs'); + const seed = boundedFixture({runs:[]}), source=seed.history[0]; + const runs=Array.from({length:101},(_,i)=>seed.makeRun(i+1,source)); + const good=boundedFixture({runs}); + assert.equal((await createEvidence(good.api,good.policies).select('ci',source)).sourceSha,source); + assert.ok(good.calls.some(x=>x.includes('page=2'))); + const racing=boundedFixture({runs,race:true}); + await assert.rejects(createEvidence(racing.api,racing.policies).select('ci',source), /pagination|changed|incomplete/i); +}); + +test('newest selection detects dev movement and a newer run completing during lookup', async () => { + const {createEvidence} = require('./release-evidence.cjs'); + const seed=boundedFixture({runs:[]}), [older,,newer]=seed.history; + const progress={...seed.makeRun(2,newer),status:'in_progress',conclusion:null}; + const racing=boundedFixture({runs:[seed.makeRun(1,older),progress],raceState:true}); + await assert.rejects(createEvidence(racing.api,racing.policies).select('ci'), /changed/i); + const moved=boundedFixture({runs:[seed.makeRun(1,older)],devMoves:true}); + await assert.rejects(createEvidence(moved.api,moved.policies).select('ci'), /dev changed/i); +}); + +test('newest selection paginates the commit comparison and refuses excessive ancestry', async () => { + const {createEvidence} = require('./release-evidence.cjs'); + const history=Array.from({length:102},(_,i)=>(i+1).toString(16).padStart(40,'0')); + const seed=boundedFixture({runs:[],history}); + const fixture=boundedFixture({runs:[seed.makeRun(1,history[0])],history}); + assert.equal((await createEvidence(fixture.api,fixture.policies).select('ci')).sourceSha, history[0]); + assert.ok(fixture.calls.some(x=>x.startsWith('/compare/') && x.includes('page=2'))); + const longHistory=Array.from({length:202},(_,i)=>(i+1).toString(16).padStart(40,'0')); + const long=boundedFixture({runs:[seed.makeRun(1,longHistory[0])],history:longHistory}); + await assert.rejects(createEvidence(long.api,long.policies).select('ci'), /coverage exceeds/); +}); + +test('newest selection refuses incomparable green ancestors', async () => { + const {createEvidence} = require('./release-evidence.cjs'); + const history=['1','2','3','4'].map(x=>x.repeat(40)); + const seed=boundedFixture({runs:[],history}); + const fixture=boundedFixture({history,divergent:[history[1],history[2]],runs:[seed.makeRun(1,history[0]),seed.makeRun(2,history[1]),seed.makeRun(3,history[2])]}); + await assert.rejects(createEvidence(fixture.api,fixture.policies).select('ci'), /ambiguous/); +}); + +test('filtered searches fail closed beyond GitHub’s 1000-result coverage', async () => { + const {createEvidence} = require('./release-evidence.cjs'); + const seed=boundedFixture({runs:[]}), source=seed.history[0]; + const runs=Array.from({length:1001},(_,i)=>({...seed.makeRun(i+1,source),display_title:'old policy'})); + const discovery=boundedFixture({runs}); + await assert.rejects(createEvidence(discovery.api,discovery.policies).select('ci'), /coverage exceeds/); + assert.equal(discovery.calls.filter(x=>x.startsWith('/actions/workflows/42/runs?')).length,10); + const exact=boundedFixture({runs}); + await assert.rejects(createEvidence(exact.api,exact.policies).select('ci',source), /coverage exceeds/); +}); diff --git a/.github/scripts/release-history.cjs b/.github/scripts/release-history.cjs new file mode 100644 index 0000000000..e2de485339 --- /dev/null +++ b/.github/scripts/release-history.cjs @@ -0,0 +1,394 @@ +'use strict'; + +/* + * The collector reads npm, authenticated GitHub and local Git under the release + * lock. Callers MUST execute this file from the trusted workflow revision, with + * a complete git checkout and repeat the check immediately before publication. + * The API's fetchImpl injection is for trusted callers and tests only; + * the CLI pins both endpoints, package/repository identity and mapping policy. + * Decision primitives require complete, fresh evidence under the release + * lock. isAncestor must + * query complete Git history and throw on an unknown object. verifyReceipt and + * verifyProvenance must cryptographically authenticate their inputs, bind the + * supplied tuple, and return the literal boolean true. Neither JSON flags nor a + * candidate-created Actions artifact are authentication. Never invoke these + * functions with callbacks or evidence controlled by a dispatch input. + * + * reconcileHistory accepts registry versions {version,gitHead,publishedAt}, + * distTags, Git tag commits {version,sha}, GitHub releases {version,tag}, signed + * receipt envelopes {payload}, candidateSha/candidateVersion/channel, + * isAncestor and verifyReceipt. This primitive requires direct ancestry. + * resume:true requires the candidate to be the already-published floor and an + * authenticated receipt; it does not derive or approve a new version. + * Input arrays must cover the entire reconciled ledger, including partial npm + * publishes. A collector must separately detect pagination and snapshot races. + * + * verifyExactResume accepts tuple/receipt/registry/provenance/tag/release/historyFloor + * plus verifyReceipt, verifyProvenance and verifyHistory. verifyHistory must + * authenticate a fresh, complete, lock-protected reconciliation including all + * npm-only publications. Receipt payload binds the complete tuple and + * asset name-to-SHA256 map; registry.sha256 must be independently calculated + * from downloaded registry tarball bytes. Existing assets are hashed from bytes. + * A null tag/release means the authenticated GitHub lookup confirmed absence. + * Publication orchestration must not call npm publish after a successful resume. + */ +const { verify, createPublicKey } = require('node:crypto'); +const { spawnSync } = require('node:child_process'); +const { readFileSync } = require('node:fs'); +const { isDeepStrictEqual } = require('node:util'); +const SHA = /^[a-f0-9]{40}$/; +const DIGEST = /^[a-f0-9]{64}$/; +const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-preview\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?)?$/; +const PACKAGE = '@bitkyc08/opencodex'; +const REPO = 'lidge-jun/opencodex'; +const REPO_ID = 1273824907; +// One-time legacy transition. The collector verifies the tag and registry SHA, +// both ancestry relationships and actual version-only tree differences at run +// time. This code-backed policy still needs independent review before cutover. +const LEGACY_MAPPINGS = Object.freeze([ + {version:'2.99.0',legacySha:'667662903a6c139524506667d12656d9ad50fad0'}, + {version:'2.99.0-preview.20261108',legacySha:'68eee1eb804445ad86fe942b734060f323eb1517'}, +]); +const LEGACY_BASELINE = '0627a2c255bc239d5748119f1d0bc4457a1c03e3'; +const LEGACY_BASELINE_VERSION = '2.100.0'; +const VERSION_PATHS = Object.freeze(['package.json','desktop/src-tauri/tauri.conf.json','desktop/src-tauri/Cargo.toml','desktop/src-tauri/Cargo.lock']); + +function must(condition, message) { if (!condition) throw new Error(message); } +function version(v) { + const m = typeof v === 'string' && VERSION.exec(v); + must(m, 'invalid release version'); + const numbers = m.slice(1).map(x => x === undefined ? null : Number(x)); + must(numbers.every(x => x === null || Number.isSafeInteger(x)), 'invalid release version'); + return numbers; +} +function compareVersions(a, b) { + const x = version(a), y = version(b); + for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1; + if (x[3] === null || y[3] === null) return x[3] === y[3] ? 0 : x[3] === null ? 1 : -1; + for (let i = 3; i < 5; i++) { + if (x[i] !== y[i]) return x[i] === null ? -1 : y[i] === null ? 1 : x[i] < y[i] ? -1 : 1; + } + return 0; +} +function channelFor(v) { return version(v)[3] === null ? 'stable' : 'preview'; } +function validTuple(t) { + must(t && SHA.test(t.sourceSha || '') && SHA.test(t.workflowSha || '') && DIGEST.test(t.sha256 || '') && + Number.isSafeInteger(t.runId) && t.runId > 0 && Number.isSafeInteger(t.attempt) && t.attempt > 0 && + t.channel === channelFor(t.version), 'invalid receipt tuple'); + must(t.assets && typeof t.assets === 'object' && !Array.isArray(t.assets), 'invalid receipt assets'); + for (const [name, digest] of Object.entries(t.assets)) must(name && !/[\x00-\x1f/\\]/.test(name) && DIGEST.test(digest), 'invalid receipt asset'); +} +function sameTuple(a, b) { + validTuple(a); validTuple(b); + return ['sourceSha','workflowSha','version','channel','sha256','runId','attempt'].every(k => a[k] === b[k]) && + Object.keys(a.assets).length === Object.keys(b.assets).length && Object.entries(a.assets).every(([k,v]) => Object.hasOwn(b.assets,k) && b.assets[k] === v); +} +function assertReceipt(envelope, expected, verifyReceipt) { + must(envelope && typeof verifyReceipt === 'function' && verifyReceipt(envelope, expected) === true, 'receipt authentication failed'); + must(sameTuple(envelope.payload, expected), 'receipt tuple mismatch'); +} +function reconcileHistory(input) { + const {candidateSha, candidateVersion, channel, versions, distTags, tags, releases, receipts, isAncestor, verifyReceipt, resume = false} = input; + must(typeof resume === 'boolean', 'invalid resume mode'); + must(SHA.test(candidateSha || '') && channel === channelFor(candidateVersion), 'invalid candidate'); + must([versions,tags,releases,receipts].every(Array.isArray) && distTags && typeof distTags === 'object' && !Array.isArray(distTags) && typeof isAncestor === 'function', 'incomplete history'); + const byVersion = new Map(), byTag = new Map(), byRelease = new Map(), byReceipt = new Map(); + for (const r of versions) { + version(r?.version); must(!byVersion.has(r.version) && SHA.test(r.gitHead || ''), 'missing or duplicate registry source'); + const time = Date.parse(r.publishedAt); + must(typeof r.publishedAt === 'string' && Number.isFinite(time) && new Date(time).toISOString() === r.publishedAt, 'missing publication order'); + byVersion.set(r.version, {...r,time}); + } + for (const [name, v] of Object.entries(distTags)) { must(name && byVersion.has(v), 'unknown dist-tag version'); } + for (const t of tags) { version(t?.version); must(!byTag.has(t.version) && SHA.test(t.sha || '') && byVersion.has(t.version), 'unknown or duplicate tag'); byTag.set(t.version,t); } + for (const r of releases) { version(r?.version); must(!byRelease.has(r.version) && r.tag === `v${r.version}` && byTag.has(r.version), 'unknown or duplicate release'); byRelease.set(r.version,r); } + for (const envelope of receipts) { + const r = envelope?.payload; validTuple(r); + must(!byReceipt.has(r.version) && byVersion.has(r.version), 'unknown or duplicate receipt'); + assertReceipt(envelope, r, verifyReceipt); byReceipt.set(r.version, r); + } + const ordered = [...byVersion.values()].sort((a,b) => a.time-b.time); + for (let i = 0; i < ordered.length; i++) { + const r = ordered[i], tag = byTag.get(r.version), receipt = byReceipt.get(r.version); + if (i) must(ordered[i-1].time < r.time, 'ambiguous publication order'); + if (tag) must(tag.sha === r.gitHead, 'tag and registry source mismatch'); + if (receipt) must(receipt.sourceSha === r.gitHead && receipt.channel === channelFor(r.version), 'receipt and registry source mismatch'); + if (!tag || !byRelease.has(r.version)) must(receipt, 'npm-only publication requires authenticated receipt'); + } + for (let i = 1; i < ordered.length; i++) must(isAncestor(ordered[i-1].gitHead,ordered[i].gitHead) === true, 'publication lineage diverges'); + if (ordered.length) { + const floor = ordered.at(-1); + if (resume) { + must(candidateVersion === floor.version && candidateSha === floor.gitHead && byReceipt.has(floor.version), 'resume would roll back or lacks a receipt'); + } else { + must(ordered.every(r => compareVersions(candidateVersion, r.version) > 0), 'candidate version would regress or already exists'); + must(isAncestor(floor.gitHead,candidateSha) === true, 'candidate lineage would roll back or diverge'); + if (candidateSha === floor.gitHead) must(channel === 'stable' && channelFor(floor.version) === 'preview', 'same source only allowed for preview to stable'); + } + return {floor:{version:floor.version,sourceSha:floor.gitHead,publishedAt:floor.publishedAt}}; + } + must(!resume, 'resume requires published history'); + return {floor:null}; +} +function verifyExactResume({tuple, receipt, registry, provenance, tag, release, historyFloor, verifyReceipt, verifyProvenance, verifyHistory}) { + validTuple(tuple); assertReceipt(receipt, tuple, verifyReceipt); + must(registry && registry.version === tuple.version && registry.gitHead === tuple.sourceSha && registry.sha256 === tuple.sha256, 'registry identity or digest mismatch'); + must(typeof verifyProvenance === 'function' && verifyProvenance(provenance, tuple, registry) === true, 'provenance authentication failed'); + must(typeof verifyHistory === 'function' && verifyHistory(historyFloor) === true && historyFloor?.version === tuple.version && historyFloor.sourceSha === tuple.sourceSha, 'resume would roll back publication history'); + must(tag === null || (tag && tag.name === `v${tuple.version}` && tag.sha === tuple.sourceSha), 'existing tag mismatch'); + must(release === null || (release && tag && release.tag === tag.name && Array.isArray(release.assets)), 'existing release mismatch'); + const reuseAssets = [], seen = new Set(); + for (const asset of release?.assets || []) { + must(asset && typeof asset.name === 'string' && !seen.has(asset.name) && Object.hasOwn(tuple.assets,asset.name) && DIGEST.test(asset.sha256 || '') && tuple.assets[asset.name] === asset.sha256, 'unsafe existing asset'); + seen.add(asset.name); reuseAssets.push(asset.name); + } + return {publishNpm:false, reuseAssets:reuseAssets.sort()}; +} + +function createGit(repoPath) { + function run(args, allowNotAncestor = false, trim = true) { + const r = spawnSync('git', ['-C',repoPath,...args], {encoding:'utf8',maxBuffer:1024*1024,env:{...process.env,GIT_NO_REPLACE_OBJECTS:'1'},stdio:['ignore','pipe','pipe']}); + if (allowNotAncestor && r.status === 1) return false; + must(r.status === 0, `Git could not verify ${args[0]}; fetch complete dev and tag history`); + return trim ? r.stdout.trim() : r.stdout; + } + must(run(['rev-parse','--is-shallow-repository']) === 'false', 'Git history is shallow; fetch complete history'); + const known = new Set(), comparisons = new Map(); + function commit(sha) { + must(SHA.test(sha || ''), 'invalid Git source SHA'); + if (!known.has(sha)) { + try { run(['cat-file','-e',`${sha}^{commit}`]); } + catch { throw new Error(`Git source ${sha} is unavailable; fetch complete release and dev history and reconcile unknown sources`); } + known.add(sha); + } + } + function isAncestor(a,b) { + commit(a); commit(b); + const key = `${a}:${b}`; + if (!comparisons.has(key)) comparisons.set(key, run(['merge-base','--is-ancestor',a,b],true) !== false); + return comparisons.get(key); + } + function treeFile(sha,path) { + commit(sha); + const entry = run(['ls-tree',sha,'--',path]); + must(/^100644 blob [a-f0-9]{40}\t/.test(entry) && entry.endsWith(`\t${path}`), `legacy version file ${path} is missing or has an unsafe mode`); + const text = run(['show',`${sha}:${path}`],false,false); + must(!text.includes('\ufffd'), `legacy version file ${path} is not valid UTF-8`); + return text; + } + function changedPaths(a,b) { + commit(a); commit(b); + const output = run(['diff','--no-ext-diff','--no-renames','--name-status','-z',a,b,'--'],false,false); + const fields = output.split('\0'); + must(fields.pop() === '' && fields.length % 2 === 0, 'invalid legacy tree diff'); + const paths = []; + for (let i=0;i line.trim() === '[package]' ? i : -1).filter(i => i >= 0); + must(starts.length === 1, `ambiguous package version in ${path}`); + let end = starts[0] + 1; + while (end < lines.length && !/^\s*\[/.test(lines[end])) end++; + must(lines.slice(starts[0]+1,end).filter(line => /^\s*name\s*=\s*"opencodex-desktop"\s*$/.test(line)).length === 1, `invalid desktop package in ${path}`); + indexes = lines.map((line,i) => i > starts[0] && i < end && /^\s*version\s*=/.test(line) ? i : -1).filter(i => i >= 0); + } else { + indexes = []; + for (let i=0;i+2 0 && entries.length <= 10000, 'empty or oversized npm history requires reconciliation'); + const versions = entries.map(([v,metadata]) => { + version(v); + must(metadata?.name === PACKAGE && metadata.version === v, `npm ${v} has invalid package identity`); + const publishedAt = data.time[v], time = Date.parse(publishedAt); + must(typeof publishedAt === 'string' && Number.isFinite(time) && new Date(time).toISOString() === publishedAt, `npm ${v} has missing publication time`); + return {version:v,gitHead:metadata.gitHead ?? null,publishedAt,time}; + }).sort((a,b) => a.time-b.time); + for (let i=1;i r.version === value), `npm dist-tag ${key} names unknown version`); + if (tags.latest) must(channelFor(tags.latest) === 'stable', 'npm latest dist-tag is not stable'); + if (tags.preview) must(channelFor(tags.preview) === 'preview', 'npm preview dist-tag is not preview'); + return {versions,distTags:Object.fromEntries(Object.entries(tags).sort(([a],[b]) => a.localeCompare(b)))}; +} +function githubSnapshot(tags, releases) { + const tagMap = new Map(), releaseMap = new Map(); + for (const tag of tags) { + must(typeof tag?.name === 'string' && SHA.test(tag.commit?.sha || '') && !tagMap.has(tag.name), 'duplicate or malformed GitHub tag'); + tagMap.set(tag.name,tag.commit.sha); + } + for (const release of releases) { + must(typeof release?.tag_name === 'string' && typeof release.draft === 'boolean' && typeof release.prerelease === 'boolean' && !releaseMap.has(release.tag_name), 'duplicate or malformed GitHub release'); + releaseMap.set(release.tag_name,{draft:release.draft,prerelease:release.prerelease,published_at:release.published_at}); + } + return {tagMap,releaseMap}; +} +/** + * Read-only history gate. GH_TOKEN needs repository contents:read. Invoke from + * trusted workflow checkout with full Git history after acquiring the shared + * release lock: `node .github/scripts/release-history.cjs check + * `. Exit 0 returns JSON {floor,channels,devSha, + * versionsChecked}; any unverifiable evidence exits nonzero. Publications at + * or after the older channel head without a matching tag and published release + * stop for manual reconciliation; no receipt/provenance verifier is assumed. + * Older versions still participate in the global version and ordering checks. + * Re-run immediately before publication. This gate does not authorize + * npm publication or prove build, CI, package digest, provenance, or resume. + */ +async function collectPublicationHistory({candidateSha,candidateVersion,channel,repoPath = process.cwd(),token,fetchImpl = fetch}) { + must(typeof token === 'string' && token.length > 0 && typeof fetchImpl === 'function', 'GH_TOKEN is required for authenticated GitHub evidence'); + must(SHA.test(candidateSha || '') && channel === channelFor(candidateVersion), 'invalid candidate source, version or channel'); + const git = createGit(repoPath), base = `https://api.github.com/repos/${REPO}`; + const get = (path,allow404) => requestJson(fetchImpl,base+path,token,allow404); + const readNpm = async () => registrySnapshot(await requestJson(fetchImpl,'https://registry.npmjs.org/%40bitkyc08%2Fopencodex',token)); + const [repo,dev,npm,tags,releases] = await Promise.all([get(''),get('/commits/dev'),readNpm(),githubPages(fetchImpl,token,'tags'),githubPages(fetchImpl,token,'releases')]); + must(repo?.id === REPO_ID && repo.full_name === REPO, 'GitHub repository identity mismatch'); + must(SHA.test(dev?.sha || '') && git.isAncestor(candidateSha,dev.sha), 'candidate is not reachable from GitHub dev'); + const gh = githubSnapshot(tags,releases); + const channels = ['preview','stable'].map(c => npm.versions.filter(r => channelFor(r.version) === c).at(-1)).filter(Boolean).sort((a,b) => a.time-b.time); + const cutoff = channels[0].time; + for (const r of npm.versions.filter(r => r.time >= cutoff)) { + const tag = gh.tagMap.get(`v${r.version}`), release = gh.releaseMap.get(`v${r.version}`); + must(SHA.test(r.gitHead || ''), `npm ${r.version} has missing or invalid gitHead; reconcile publication source`); + must(tag, `npm-only publication ${r.version} (${r.gitHead}) has no GitHub tag; authenticated prior receipt and provenance required for reconciliation`); + must(tag === r.gitHead, `GitHub tag v${r.version} does not match npm gitHead`); + must(release && !release.draft && release.prerelease === (channelFor(r.version) === 'preview') && Number.isFinite(Date.parse(release.published_at)), `npm publication ${r.version} lacks a published matching GitHub release; authenticated receipt and provenance required`); + } + for (const r of npm.versions) { + must(compareVersions(candidateVersion,r.version) > 0, `candidate version ${candidateVersion} does not exceed published npm version ${r.version}`); + } + const selectedVersions = new Set(npm.versions.map(r => r.version)); + for (const [tag,release] of gh.releaseMap) { + if (release.draft) continue; + const published = Date.parse(release.published_at); + must(Number.isFinite(published), `GitHub release ${tag} has no publication time`); + if (published >= cutoff && tag.startsWith('v')) must(selectedVersions.has(tag.slice(1)), `GitHub release ${tag} has no matching npm version; reconcile partial publication`); + } + for (const r of channels) { + const legacy = LEGACY_MAPPINGS.find(m => m.version === r.version); + if (legacy) { + must(r.gitHead === legacy.legacySha && gh.tagMap.get(`v${r.version}`) === legacy.legacySha, `legacy ${r.version} registry or tag source does not match the fixed expected SHA`); + verifyLegacyTreeEvidence({repoPath,sourceSha:legacy.legacySha,baselineSha:LEGACY_BASELINE,sourceVersion:legacy.version,baselineVersion:LEGACY_BASELINE_VERSION,candidateSha,devSha:dev.sha}); + } else { + must(git.isAncestor(r.gitHead,candidateSha), `candidate lineage does not include ${r.version} source ${r.gitHead}`); + } + } + const newest = channels.at(-1); + if (candidateSha === newest.gitHead) must(channel === 'stable' && channelFor(newest.version) === 'preview', 'same source only allowed for preview to stable'); + const result = {floor:{version:newest.version,sourceSha:newest.gitHead,publishedAt:newest.publishedAt}}; + const [npmAgain,devAgain,tagsAgain,releasesAgain] = await Promise.all([readNpm(),get('/commits/dev'),githubPages(fetchImpl,token,'tags'),githubPages(fetchImpl,token,'releases')]); + const comparable = snapshot => JSON.stringify({tags:[...snapshot.tagMap].sort(),releases:[...snapshot.releaseMap].sort(([a],[b]) => a.localeCompare(b))}); + must(isDeepStrictEqual(npm,npmAgain) && devAgain?.sha === dev.sha && comparable(gh) === comparable(githubSnapshot(tagsAgain,releasesAgain)), 'publication evidence changed during collection; retry under the shared release lock'); + return {...result,channels:channels.map(({version,gitHead,publishedAt}) => ({version,sourceSha:gitHead,publishedAt})),devSha:dev.sha,versionsChecked:npm.versions.length}; +} + +// Ed25519 signatures authenticate raw bytes. The public key must come from a +// reviewed trusted policy, not an artifact, candidate checkout, or CLI input. +function verifyEd25519Receipt(bytes, signature, trustedPublicKey) { + try { + const key = createPublicKey(trustedPublicKey); + return key.asymmetricKeyType === 'ed25519' && Buffer.isBuffer(bytes) && Buffer.isBuffer(signature) && verify(null, bytes, key, signature); + } + catch { return false; } +} +// Signed JSON has shape {payload,expiresAt}; the verifier rejects a changed +// parsed payload and requires a separate authenticated run/attempt lookup. +function createReceiptVerifier({publicKey, now, verifyRun}) { + must(typeof now === 'function' && typeof verifyRun === 'function', 'receipt verification dependencies required'); + return (envelope, expected) => { + try { + if (!envelope || typeof envelope.signedBytes !== 'string' || typeof envelope.signature !== 'string') return false; + const bytes = Buffer.from(envelope.signedBytes, 'base64'); + const signature = Buffer.from(envelope.signature, 'base64'); + if (!bytes.length || bytes.length > 1024 * 1024 || bytes.toString('base64') !== envelope.signedBytes || signature.toString('base64') !== envelope.signature || + !verifyEd25519Receipt(bytes, signature, publicKey)) return false; + const signed = JSON.parse(bytes.toString('utf8')); + const expires = Date.parse(signed.expiresAt), current = now(); + if (!Number.isFinite(expires) || !Number.isFinite(current) || expires <= current || !isDeepStrictEqual(signed.payload, envelope.payload) || + !sameTuple(signed.payload, expected)) return false; + return verifyRun(signed.payload) === true; + } catch { return false; } + }; +} +// check must run from the trusted workflow revision under the release lock. +// GH_TOKEN is read from the environment; output contains no credentials. +async function main(args) { + const [command, first, second, third, ...extra] = args; + if (command === 'check') { + must(first && second && third && !extra.length, 'usage: release-history.cjs check '); + const result = await collectPublicationHistory({candidateSha:first,candidateVersion:second,channel:third,token:process.env.GH_TOKEN}); + process.stdout.write(`${JSON.stringify(result)}\n`); return; + } + must(command === 'verify-signature' && first && second && third && !extra.length, 'usage: release-history.cjs check | verify-signature '); + must(verifyEd25519Receipt(readFileSync(first), readFileSync(second), readFileSync(third)), 'receipt signature invalid'); + process.stdout.write('signature valid; publication evidence has not been checked\n'); +} +if (require.main === module) main(process.argv.slice(2)).catch(error => { process.stderr.write(`release history: ${error.message}\n`); process.exitCode = 1; }); +module.exports = {compareVersions, reconcileHistory, verifyExactResume, verifyEd25519Receipt, createReceiptVerifier, collectPublicationHistory, verifyLegacyTreeEvidence, LEGACY_MAPPINGS, LEGACY_BASELINE}; diff --git a/.github/scripts/release-history.test.cjs b/.github/scripts/release-history.test.cjs new file mode 100644 index 0000000000..0691262d23 --- /dev/null +++ b/.github/scripts/release-history.test.cjs @@ -0,0 +1,333 @@ +'use strict'; + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { generateKeyPairSync, sign } = require('node:crypto'); +const { mkdtempSync, rmSync, mkdirSync, writeFileSync } = require('node:fs'); +const { tmpdir } = require('node:os'); +const { join, resolve } = require('node:path'); +const { execFileSync } = require('node:child_process'); +const { reconcileHistory, verifyExactResume, createReceiptVerifier, collectPublicationHistory, verifyLegacyTreeEvidence } = require('./release-history.cjs'); + +const old = 'a'.repeat(40), newer = 'b'.repeat(40), other = 'c'.repeat(40), workflow = 'd'.repeat(40); +const digest = '1'.repeat(64), assetDigest = '2'.repeat(64); +const ancestry = (base, head) => base === head || (base === old && head === newer); +const record = (version, sourceSha, publishedAt) => ({version, gitHead: sourceSha, publishedAt}); +const receipt = (version, sourceSha, channel = 'stable') => ({version, sourceSha, workflowSha: workflow, channel, sha256: digest, runId: 123, attempt: 1, assets: {'app.zip': assetDigest}}); +const authenticated = x => x?.authenticated === true; +const attested = x => x?.verified === true; +const signed = payload => ({payload, authenticated: true}); +const snapshot = overrides => ({ + candidateSha: newer, candidateVersion: '1.0.2', channel: 'stable', + versions: [record('1.0.0', old, '2026-01-01T00:00:00.000Z')], + distTags: {latest: '1.0.0'}, tags: [{version: '1.0.0', sha: old}], + releases: [{version: '1.0.0', tag: 'v1.0.0'}], receipts: [], mappings: [], + isAncestor: ancestry, verifyReceipt: authenticated, ...overrides, +}); + +test('newer npm-only partial publication prevents source rollback', () => { + const r = receipt('1.0.1', newer); + const input = snapshot({candidateSha: old, versions: [record('1.0.0', old, '2026-01-01T00:00:00.000Z'), record('1.0.1', newer, '2026-01-02T00:00:00.000Z')], receipts: [signed(r)]}); + assert.throws(() => reconcileHistory(input), /lineage|rollback/); + assert.throws(() => reconcileHistory({...input, receipts: []}), /receipt/); + assert.throws(() => reconcileHistory({...input, receipts: [{payload:r, authenticated:false}]}), /receipt/); +}); + +test('pure history rejects divergent sources and arbitrary mappings cannot bypass ancestry', () => { + const input = snapshot({versions:[record('1.0.0', other, '2026-01-01T00:00:00.000Z')], tags:[{version:'1.0.0', sha:other}]}); + assert.throws(() => reconcileHistory(input), /lineage/); + assert.throws(() => reconcileHistory({...input, mappings:[{version:'1.0.0', legacySha:other, devSha:old}]}), /lineage/); +}); + +test('pure history rejects divergent channels', () => { + const input = snapshot({versions:[record('1.0.0',other,'2026-01-01T00:00:00.000Z'),record('1.0.1-preview.20260102.1',old,'2026-01-02T00:00:00.000Z')], + tags:[{version:'1.0.0',sha:other},{version:'1.0.1-preview.20260102.1',sha:old}], releases:[{version:'1.0.0',tag:'v1.0.0'},{version:'1.0.1-preview.20260102.1',tag:'v1.0.1-preview.20260102.1'}]}); + assert.throws(() => reconcileHistory(input), /lineage/); +}); + +test('stable may follow preview at the same source but rollback and ambiguity fail', () => { + const input = snapshot({candidateSha:old, candidateVersion:'1.0.1', versions:[record('1.0.1-preview.20260101.1',old,'2026-01-01T00:00:00.000Z')], tags:[{version:'1.0.1-preview.20260101.1',sha:old}], releases:[{version:'1.0.1-preview.20260101.1',tag:'v1.0.1-preview.20260101.1'}], distTags:{preview:'1.0.1-preview.20260101.1'}}); + assert.equal(reconcileHistory(input).floor.sourceSha, old); + assert.throws(() => reconcileHistory({...input, candidateVersion:'1.0.0'}), /version/); + assert.throws(() => reconcileHistory({...input, versions:[...input.versions, record('1.0.0',old,input.versions[0].publishedAt)]}), /order/); +}); + +function resumeInput() { + const tuple = receipt('1.0.1', newer); + return {tuple, receipt:signed(tuple), registry:{version:tuple.version, gitHead:newer, sha256:digest}, provenance:{verified:true}, tag:{name:'v1.0.1',sha:newer}, release:{tag:'v1.0.1',assets:[{name:'app.zip',sha256:assetDigest}]}, historyFloor:{version:tuple.version,sourceSha:newer}, verifyHistory:() => true, verifyReceipt:authenticated, verifyProvenance:attested}; +} +test('verified exact resume never requests republish or overwrites assets', () => { + assert.deepEqual(verifyExactResume(resumeInput()), {publishNpm:false, reuseAssets:['app.zip']}); +}); +test('resume rejects corrupt or forged receipts, registry and provenance mismatches, and asset replacement', () => { + const input = resumeInput(); + assert.throws(() => verifyExactResume({...input, receipt:{...input.receipt,authenticated:false}}), /receipt/); + assert.throws(() => verifyExactResume({...input, receipt:signed({...input.tuple, sha256:'3'.repeat(64)})}), /receipt/); + assert.throws(() => verifyExactResume({...input, registry:{...input.registry,gitHead:old}}), /registry/); + assert.throws(() => verifyExactResume({...input, provenance:{verified:false}}), /provenance/); + assert.throws(() => verifyExactResume({...input, historyFloor:{version:'1.0.2',sourceSha:other}}), /roll back/); + assert.throws(() => verifyExactResume({...input, verifyHistory:() => false}), /history/); + assert.throws(() => verifyExactResume({...input, tag:{name:'v1.0.1',sha:old}}), /tag/); + assert.throws(() => verifyExactResume({...input, release:{tag:'v1.0.1',assets:[{name:'app.zip',sha256:digest}]}}), /asset/); + assert.throws(() => verifyExactResume({...input, release:{tag:'v1.0.1',assets:[{name:'extra.zip',sha256:digest}]}}), /asset/); +}); + +test('real signed receipt binds bytes, tuple, expiry, and authenticated run attempt', () => { + const {privateKey, publicKey} = generateKeyPairSync('ed25519'); + const publicPem = publicKey.export({type:'spki',format:'pem'}); + const input = resumeInput(); + const bytes = Buffer.from(JSON.stringify({payload:input.tuple,expiresAt:'2026-01-02T00:00:00.000Z'})); + const envelope = {payload:input.tuple, signedBytes:bytes.toString('base64'), signature:sign(null,bytes,privateKey).toString('base64')}; + const makeVerifier = (now, verifyRun = t => t.runId === 123 && t.attempt === 1) => createReceiptVerifier({publicKey:publicPem, now:() => Date.parse(now), verifyRun}); + const verifyReceipt = makeVerifier('2026-01-01T00:00:00.000Z'); + assert.deepEqual(verifyExactResume({...input,receipt:envelope,verifyReceipt}), {publishNpm:false,reuseAssets:['app.zip']}); + assert.throws(() => verifyExactResume({...input,receipt:{...envelope,payload:{...input.tuple,attempt:2}},verifyReceipt}), /receipt/); + const forged = Buffer.from(bytes); forged[10] ^= 1; + assert.throws(() => verifyExactResume({...input,receipt:{...envelope,signedBytes:forged.toString('base64')},verifyReceipt}), /receipt/); + assert.throws(() => verifyExactResume({...input,receipt:envelope,verifyReceipt:makeVerifier('2026-01-02T00:00:00.000Z')}), /receipt/); + assert.throws(() => verifyExactResume({...input,receipt:envelope,verifyReceipt:makeVerifier('2026-01-01T00:00:00.000Z', () => false)}), /receipt/); + const history = snapshot({versions:[record('1.0.1',newer,'2026-01-01T00:00:00.000Z')], distTags:{latest:'1.0.1'}, tags:[], releases:[], receipts:[envelope], candidateSha:old, candidateVersion:'1.0.2', verifyReceipt}); + assert.throws(() => reconcileHistory(history), /lineage|rollback/); + assert.throws(() => reconcileHistory({...history,receipts:[{...envelope, signature:Buffer.alloc(64).toString('base64')}]}), /receipt/); + const resumed = reconcileHistory({...history,candidateSha:newer,candidateVersion:'1.0.1',distTags:{latest:'1.0.1'},resume:true}); + assert.equal(resumed.floor.sourceSha, newer); + assert.throws(() => reconcileHistory({...history,candidateSha:old,candidateVersion:'1.0.0',distTags:{latest:'1.0.1'},resume:true}), /roll back/); +}); + +test('history rejects missing sources, unknown tags, and missing registry evidence', () => { + const input = snapshot(); + assert.throws(() => reconcileHistory({...input, versions:[record('1.0.0','', '2026-01-01T00:00:00.000Z')]}), /source/); + assert.throws(() => reconcileHistory({...input, distTags:{latest:'1.0.5'}}), /dist-tag/); + assert.throws(() => reconcileHistory({...input, tags:[{version:'1.0.1',sha:old}]}), /tag/); + assert.throws(() => reconcileHistory({...input, releases:[{version:'1.0.0',tag:'v1.0.1'}]}), /release/); +}); + +function collectorFixture(t) { + const dir = mkdtempSync(join(tmpdir(), 'ocx-release-history-')); + t.after(() => rmSync(dir, {recursive:true, force:true})); + const git = (...args) => execFileSync('git', ['-C',dir,...args], {encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim(); + git('init','-q'); + const commit = name => { git('-c','user.name=Test','-c','user.email=test@localhost','commit','--allow-empty','-qm',name); return git('rev-parse','HEAD'); }; + const first = commit('preview'), second = commit('stable'), candidate = commit('candidate'); + const control = {devSha:candidate}; + const data = {name:'@bitkyc08/opencodex',versions:{},time:{},'dist-tags':{preview:'1.0.1-preview.20260101.1',latest:'1.0.1'}}; + const refs = new Map(); + function publish(v, sha, time, hasTag = true) { + data.versions[v] = {name:data.name,version:v,gitHead:sha}; data.time[v] = time; + if (hasTag) refs.set(v,sha); + } + publish('1.0.1-preview.20260101.1',first,'2026-01-01T00:00:00.000Z'); + publish('1.0.1',second,'2026-01-02T00:00:00.000Z'); + const fetchImpl = async (url, options) => { + const u = new URL(url); + assert.ok(options.signal); assert.equal(options.redirect,'error'); + if (u.hostname === 'registry.npmjs.org') return Response.json(data); + assert.equal(u.hostname,'api.github.com'); assert.equal(options.headers.Authorization,'Bearer test-token'); + const path = u.pathname.replace('/repos/lidge-jun/opencodex',''); + if (path === '') return Response.json({id:1273824907,full_name:'lidge-jun/opencodex'}); + if (path === '/commits/dev') return Response.json({sha:control.devSha}); + if (path === '/tags') return Response.json([...refs].map(([v,sha]) => ({name:`v${v}`,commit:{sha}}))); + if (path === '/releases') return Response.json([...refs].map(([v]) => ({tag_name:`v${v}`,draft:false,prerelease:v.includes('-preview.'),published_at:data.time[v]}))); + const m = /^\/git\/ref\/tags\/v(.+)$/.exec(path); + if (m) return refs.has(m[1]) ? Response.json({ref:`refs/tags/v${m[1]}`,object:{type:'commit',sha:refs.get(m[1])}}) : new Response('',{status:404}); + const r = /^\/releases\/tags\/v(.+)$/.exec(path); + if (r) return refs.has(r[1]) ? Response.json({tag_name:`v${r[1]}`,draft:false,prerelease:r[1].includes('-preview.'),published_at:'2026-01-01T00:00:00Z'}) : new Response('',{status:404}); + throw Error(`unexpected mock URL ${url}`); + }; + return {dir, git, commit, control, first, second, candidate, data, refs, publish, fetchImpl, args:{candidateSha:candidate,candidateVersion:'1.0.2',channel:'stable',repoPath:dir,token:'test-token',fetchImpl,mappings:[]}}; +} + +test('collector uses live-shaped npm and authenticated GitHub responses with real Git ancestry', async t => { + const f = collectorFixture(t); + const result = await collectPublicationHistory(f.args); + assert.deepEqual(result.floor,{version:'1.0.1',sourceSha:f.second,publishedAt:'2026-01-02T00:00:00.000Z'}); + assert.deepEqual(result.channels.map(x => x.version),['1.0.1-preview.20260101.1','1.0.1']); +}); + +test('collector refuses a newer npm-only source and missing source metadata', async t => { + const f = collectorFixture(t); + f.publish('1.0.2-preview.20260103.1',f.candidate,'2026-01-03T00:00:00.000Z',false); + await assert.rejects(collectPublicationHistory({...f.args,candidateSha:f.second,candidateVersion:'1.0.3'}), /npm-only|rollback|lineage/i); + await assert.rejects(collectPublicationHistory({...f.args,candidateVersion:'1.0.3'}), /npm-only.*receipt/i); + f.data.versions['1.0.2-preview.20260103.1'].gitHead = ''; + await assert.rejects(collectPublicationHistory({...f.args,candidateVersion:'1.0.3'}), /gitHead/); +}); + +test('collector refuses registry races and mismatched GitHub tag source', async t => { + const f = collectorFixture(t); + f.refs.set('1.0.1',f.first); + await assert.rejects(collectPublicationHistory(f.args), /tag.*gitHead/i); + f.refs.set('1.0.1',f.second); + let reads = 0; + const racingFetch = async (url, options) => { + if (new URL(url).hostname === 'registry.npmjs.org' && ++reads === 2) f.data['dist-tags'].next = '1.0.1'; + return f.fetchImpl(url,options); + }; + await assert.rejects(collectPublicationHistory({...f.args,fetchImpl:racingFetch}), /changed|race/i); +}); + +test('collector rejects arbitrary mappings for divergent nonlegacy channel histories', async t => { + const f = collectorFixture(t); + f.git('checkout','-q','--detach',f.first); + const divergent = f.commit('divergent preview'); + f.git('checkout','-q','--detach',f.candidate); + const preview = '1.0.1-preview.20260101.1'; + f.data.versions[preview].gitHead = divergent; f.refs.set(preview,divergent); + await assert.rejects(collectPublicationHistory({...f.args,mappings:[{version:preview,legacySha:divergent,devSha:f.candidate}]}), /lineage/); +}); + +test('collector rejects missing releases, ambiguous timestamps, and missing commit objects', async t => { + const f = collectorFixture(t); + const missingRelease = async (url, options) => { + const res = await f.fetchImpl(url,options); + if (new URL(url).pathname.endsWith('/releases')) { + const values = await res.json(); return Response.json(values.filter(v => v.tag_name !== 'v1.0.1')); + } + return res; + }; + await assert.rejects(collectPublicationHistory({...f.args,fetchImpl:missingRelease}), /matching GitHub release/); + f.data.time['1.0.1'] = f.data.time['1.0.1-preview.20260101.1']; + await assert.rejects(collectPublicationHistory(f.args), /ambiguous.*order/); + f.data.time['1.0.1'] = '2026-01-02T00:00:00.000Z'; + f.data.versions['1.0.1'].gitHead = 'f'.repeat(40); f.refs.set('1.0.1','f'.repeat(40)); + await assert.rejects(collectPublicationHistory(f.args), /Git source.*unavailable/); +}); + +test('collector accepts a strictly superseded historical tag mismatch', async t => { + const f = collectorFixture(t); + f.publish('1.0.0',f.first,'2025-12-30T00:00:00.000Z'); + f.refs.set('1.0.0',f.second); + assert.equal((await collectPublicationHistory(f.args)).floor.sourceSha,f.second); + f.refs.delete('1.0.0'); delete f.data.versions['1.0.0'].gitHead; + assert.equal((await collectPublicationHistory(f.args)).floor.sourceSha,f.second); +}); + +test('collector still enforces the version floor for superseded publications', async t => { + const f = collectorFixture(t); + f.publish('1.9.0',f.first,'2025-12-30T00:00:00.000Z'); + await assert.rejects(collectPublicationHistory(f.args), /candidate version.*1\.9\.0/); +}); + +test('collector rejects a mismatch at the older channel floor', async t => { + const f = collectorFixture(t); + f.refs.set('1.0.1-preview.20260101.1',f.second); + await assert.rejects(collectPublicationHistory(f.args), /tag.*gitHead/i); +}); + +test('collector rejects an npm-only publication newer than the older channel floor', async t => { + const f = collectorFixture(t); + f.publish('1.0.0',f.first,'2026-01-01T12:00:00.000Z',false); + await assert.rejects(collectPublicationHistory(f.args), /npm-only.*receipt/i); +}); + +test('collector refuses an arbitrary legacy mapping even with a future baseline', async t => { + const f = collectorFixture(t); + f.git('checkout','-q','--detach',f.first); + const divergent = f.commit('divergent preview'); + f.git('checkout','-q','--detach',f.candidate); + const future = f.commit('future baseline'); + const preview = '1.0.1-preview.20260101.1'; + f.data.versions[preview].gitHead = divergent; f.refs.set(preview,divergent); + const mappings = [{version:preview,legacySha:divergent,devSha:future},{version:'1.0.1',legacySha:f.second,devSha:future}]; + await assert.rejects(collectPublicationHistory({...f.args,mappings}), /lineage|baseline|ancestor/i); +}); + +test('collector accepts a candidate that merges both independently verified channel sources', async t => { + const f = collectorFixture(t); + f.git('checkout','-q','--detach',f.first); + const divergent = f.commit('divergent preview'); + f.git('checkout','-q','--detach',f.candidate); + f.git('-c','user.name=Test','-c','user.email=test@localhost','merge','--no-ff','-qm','merge preview',divergent); + const merged = f.git('rev-parse','HEAD'); + f.control.devSha = merged; + const preview = '1.0.1-preview.20260101.1'; + f.data.versions[preview].gitHead = divergent; f.refs.set(preview,divergent); + const result = await collectPublicationHistory({...f.args,candidateSha:merged}); + assert.equal(result.floor.sourceSha,f.second); +}); + +test('collector refuses unknown publication order even for old versions', async t => { + const f = collectorFixture(t); + f.publish('1.0.0',f.first,'2025-12-30T00:00:00.000Z'); + delete f.data.time['1.0.0']; + await assert.rejects(collectPublicationHistory(f.args), /publication time/); +}); + +test('collector reads all GitHub tag pages on both snapshots', async t => { + const f = collectorFixture(t); + let pageTwo = 0; + const paginatedFetch = async (url, options) => { + const u = new URL(url); + if (u.hostname === 'api.github.com' && u.pathname.endsWith('/tags')) { + const real = [...f.refs].map(([v,sha]) => ({name:`v${v}`,commit:{sha}})); + const filler = Array.from({length:99},(_,i) => ({name:`archive-${i}`,commit:{sha:f.first}})); + const combined = [...real,...filler]; + const page = Number(u.searchParams.get('page')); + if (page === 2) pageTwo++; + return Response.json(combined.slice((page-1)*100,page*100)); + } + return f.fetchImpl(url,options); + }; + await collectPublicationHistory({...f.args,fetchImpl:paginatedFetch}); + assert.equal(pageTwo,2); +}); + +test('collector permits preview to stable on the identical source', async t => { + const f = collectorFixture(t); + delete f.data.versions['1.0.1']; delete f.data.time['1.0.1']; delete f.data['dist-tags'].latest; f.refs.delete('1.0.1'); + const result = await collectPublicationHistory({...f.args,candidateSha:f.first,candidateVersion:'1.0.1'}); + assert.equal(result.floor.sourceSha,f.first); +}); + +test('collector rejects GitHub API failures and requires authentication', async t => { + const f = collectorFixture(t); + await assert.rejects(collectPublicationHistory({...f.args,token:''}), /GH_TOKEN/); + const fetchImpl = async (url, options) => new URL(url).pathname.endsWith('/tags') ? new Response('',{status:403}) : f.fetchImpl(url,options); + await assert.rejects(collectPublicationHistory({...f.args,fetchImpl}), /GitHub evidence request failed \(403\)/); +}); + +test('fixed stable and preview legacy trees differ from dev baseline only by verified version values', () => { + const baseline = '0627a2c255bc239d5748119f1d0bc4457a1c03e3'; + for (const [sourceSha,sourceVersion] of [['667662903a6c139524506667d12656d9ad50fad0','2.99.0'],['68eee1eb804445ad86fe942b734060f323eb1517','2.99.0-preview.20261108']]) { + assert.equal(verifyLegacyTreeEvidence({repoPath:resolve(__dirname,'../..'),sourceSha,baselineSha:baseline,sourceVersion,baselineVersion:'2.100.0',candidateSha:baseline,devSha:baseline}),true); + } +}); + +test('collector verifies both fixed legacy sources and refuses a forged legacy SHA', async t => { + const f = collectorFixture(t); + const baseline = '0627a2c255bc239d5748119f1d0bc4457a1c03e3'; + const stable = '667662903a6c139524506667d12656d9ad50fad0', preview = '68eee1eb804445ad86fe942b734060f323eb1517'; + f.data.versions = {}; f.data.time = {}; f.refs.clear(); f.control.devSha = baseline; + f.publish('2.99.0-preview.20261108',preview,'2026-01-01T00:00:00.000Z'); + f.publish('2.99.0',stable,'2026-01-02T00:00:00.000Z'); + f.data['dist-tags'] = {preview:'2.99.0-preview.20261108',latest:'2.99.0'}; + const args = {...f.args,repoPath:resolve(__dirname,'../..'),candidateSha:baseline,candidateVersion:'2.100.0'}; + assert.equal((await collectPublicationHistory(args)).floor.sourceSha,stable); + f.data.versions['2.99.0'].gitHead = baseline; f.refs.set('2.99.0',baseline); + await assert.rejects(collectPublicationHistory(args), /fixed expected SHA/); +}); + +test('legacy tree evidence rejects other changes, wrong version values, and an uncontained baseline', t => { + const dir = mkdtempSync(join(tmpdir(),'ocx-legacy-evidence-')); + t.after(() => rmSync(dir,{recursive:true,force:true})); + const git = (...args) => execFileSync('git',['-C',dir,...args],{encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim(); + git('init','-q'); mkdirSync(join(dir,'desktop/src-tauri'),{recursive:true}); + const write = (version,extra = '') => { + writeFileSync(join(dir,'package.json'),JSON.stringify({name:'fixture',version})+'\n'); + writeFileSync(join(dir,'desktop/src-tauri/tauri.conf.json'),JSON.stringify({version})+'\n'); + writeFileSync(join(dir,'desktop/src-tauri/Cargo.toml'),`[package]\nname = "opencodex-desktop"\nversion = "${version}"\n${extra}`); + writeFileSync(join(dir,'desktop/src-tauri/Cargo.lock'),`[[package]]\nname = "opencodex-desktop"\nversion = "${version}"\n`); + }; + const commit = msg => {git('add','.');git('-c','user.name=Test','-c','user.email=test@localhost','commit','-qm',msg);return git('rev-parse','HEAD');}; + write('1.0.0'); const sourceSha = commit('source'); + write('1.1.0'); const baselineSha = commit('baseline'); + const args = {repoPath:dir,sourceSha,baselineSha,sourceVersion:'1.0.0',baselineVersion:'1.1.0',candidateSha:baselineSha,devSha:baselineSha}; + assert.equal(verifyLegacyTreeEvidence(args),true); + assert.throws(() => verifyLegacyTreeEvidence({...args,sourceVersion:'1.0.1'}), /version/); + assert.throws(() => verifyLegacyTreeEvidence({...args,candidateSha:sourceSha}), /baseline.*candidate/i); + assert.throws(() => verifyLegacyTreeEvidence({...args,devSha:sourceSha}), /baseline.*dev/i); + write('1.1.0','description = "unexpected"\n'); const changedFile = commit('other content'); + assert.throws(() => verifyLegacyTreeEvidence({...args,baselineSha:changedFile,candidateSha:changedFile,devSha:changedFile}), /version|content/i); + writeFileSync(join(dir,'extra.txt'),'unexpected\n'); const extraPath = commit('extra path'); + assert.throws(() => verifyLegacyTreeEvidence({...args,baselineSha:extraPath,candidateSha:extraPath,devSha:extraPath}), /paths|diff/i); +}); diff --git a/.github/scripts/release-resume.cjs b/.github/scripts/release-resume.cjs new file mode 100755 index 0000000000..0106bdbf19 --- /dev/null +++ b/.github/scripts/release-resume.cjs @@ -0,0 +1,124 @@ +#!/usr/bin/env node +'use strict'; + +// The operator attests that this version was published from this source. +// Registry metadata and GitHub state are consistency checks, not provenance. +// Call from trusted workflow code with the release lock held; repeat immediately +// before release creation and asset attachment. This helper never publishes npm. +// Asset receipts must come from the trusted verify-release job in this workflow; +// this helper does not authenticate an arbitrary receipt file. +const { lstatSync, readFileSync } = require('node:fs'); +const { isDeepStrictEqual } = require('node:util'); +const { compareVersions } = require('./release-history.cjs'); +const REPO = 'lidge-jun/opencodex'; +const PACKAGE = '@bitkyc08/opencodex'; +const API = `https://api.github.com/repos/${REPO}`; +const REGISTRY = 'https://registry.npmjs.org/%40bitkyc08%2Fopencodex'; +const SHA = /^[a-f0-9]{40}$/, DIGEST = /^[a-f0-9]{64}$/; +const VERSION = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-preview\.\d{8}\.\d+)?$/; +function must(condition, message) { if (!condition) throw new Error(message); } +function timestamp(value) { + const time = Date.parse(value); + must(typeof value === 'string' && Number.isFinite(time) && new Date(time).toISOString() === value, 'invalid npm publication time'); + return time; +} +async function requestJson(fetchImpl,url,token,allow404 = false) { + const github = url.startsWith(API + '/'); + must(github || url === REGISTRY, 'unexpected evidence endpoint'); + let response; + try { + response = await fetchImpl(url,{headers:github ? {Authorization:`Bearer ${token}`,Accept:'application/vnd.github+json','X-GitHub-Api-Version':'2022-11-28'} : {Accept:'application/json'},redirect:'error',cache:'no-store',signal:AbortSignal.timeout(30000)}); + } catch { throw new Error('evidence request failed'); } + if (allow404 && response.status === 404) return null; + must(response.ok, `evidence request failed (${response.status})`); + const length = response.headers.get('content-length'); + must(!length || (/^\d+$/.test(length) && Number(length) <= 20*1024*1024), 'evidence too large'); + let size = 0; const chunks = []; + must(response.body, 'empty evidence response'); + for await (const chunk of response.body) { size += chunk.length; must(size <= 20*1024*1024, 'evidence too large'); chunks.push(chunk); } + try { return JSON.parse(Buffer.concat(chunks,size).toString('utf8')); } + catch { throw new Error('invalid JSON evidence'); } +} +async function pages(fetchImpl,token,path) { + const result=[]; + for (let page=1;page<=100;page++) { + const list=await requestJson(fetchImpl,`${API}/${path}?per_page=100&page=${page}`,token); + must(Array.isArray(list) && list.length<=100, 'invalid GitHub pagination'); + result.push(...list); + if (list.length<100) return result; + } + throw new Error('GitHub pagination limit exceeded'); +} +function registryCheck(data,version,sourceSha,now) { + must(data?.name===PACKAGE && data.versions && typeof data.versions==='object' && !Array.isArray(data.versions) && data.time && typeof data.time==='object' && data['dist-tags'] && typeof data['dist-tags']==='object' && !Array.isArray(data['dist-tags']), 'invalid npm history'); + const entries=Object.entries(data.versions); + must(entries.length>0 && entries.length<=10000 && Object.hasOwn(data.versions,version), 'npm version is missing'); + const published=timestamp(data.time[version]); must(published<=now,'future npm publication'); + for (const [v,metadata] of entries) { + must(metadata?.name===PACKAGE && metadata.version===v, 'invalid npm version identity'); + const time=timestamp(data.time[v]); + must(time<=now && (v===version || time0, 'empty verified asset receipt'); + for (const name of names) must(name && name!=='.' && name!=='..' && !/[\x00-\x1f\x7f/\\]/.test(name) && DIGEST.test(expected[name]), 'invalid verified asset receipt'); + for (const asset of assets) { + must(asset && typeof asset.name==='string' && !seen.has(asset.name) && Object.hasOwn(expected,asset.name) && asset.state==='uploaded' && asset.digest===`sha256:${expected[asset.name]}`, 'existing release asset mismatch'); + seen.add(asset.name); + } + const missing=names.filter(name=>!seen.has(name)).sort(); + must(!release || release.draft || missing.length===0, 'published release missing verified assets'); + return {reuseAssets:[...seen].sort(),missingAssets:missing}; +} +async function collectResumeDecision({version,sourceSha,channel,token,fetchImpl=fetch,now=Date.now,assetReceipt}) { + must(typeof version==='string' && VERSION.test(version) && SHA.test(sourceSha || '') && channel===(version.includes('-')?'preview':'stable'), 'explicit version, source and matching channel are required'); + must(typeof token==='string' && token.length>0 && typeof fetchImpl==='function', 'GH_TOKEN is required'); + const clock=now(); must(Number.isFinite(clock), 'invalid clock'); + const read=async()=> { + const [registry,tags,release]=await Promise.all([ + requestJson(fetchImpl,REGISTRY,token),pages(fetchImpl,token,'tags'), + requestJson(fetchImpl,`${API}/releases/tags/v${version}`,token,true), + ]); + registryCheck(registry,version,sourceSha,clock); + const tagExists=tagCheck(tags,version,sourceSha); + if (release!==null) must(Number.isSafeInteger(release.id) && release.id>0 && release.tag_name===`v${version}` && typeof release.draft==='boolean' && release.prerelease===(channel==='preview'), 'invalid GitHub release evidence'); + const assets=assetReceipt!==undefined && release ? await pages(fetchImpl,token,`releases/${release.id}/assets`) : []; + return {registry,tags,release,assets,tagExists}; + }; + const first=await read(), second=await read(); + must(isDeepStrictEqual(first,second), 'publication evidence changed while checking'); + const result={version,sourceSha,channel,publishNpm:false,tagExists:first.tagExists,releaseExists:first.release!==null,assetsChecked:assetReceipt!==undefined}; + if (assetReceipt!==undefined) Object.assign(result,checkAssets(assetReceipt,first.release,first.assets,version,sourceSha)); + return result; +} +async function main() { + const [command,version,sourceSha,channel,receiptPath,...extra]=process.argv.slice(2); + must((command==='check' && !receiptPath && !extra.length) || (command==='check-assets' && receiptPath && !extra.length), 'usage: release-resume.cjs check | check-assets '); + let assetReceipt; + if (command==='check-assets') { + const stat=lstatSync(receiptPath); must(stat.isFile() && !stat.isSymbolicLink() && stat.size<=1024*1024, 'invalid verified receipt file'); + assetReceipt=JSON.parse(readFileSync(receiptPath,'utf8')); + } + const result=await collectResumeDecision({version,sourceSha,channel,token:process.env.GH_TOKEN,assetReceipt}); + process.stdout.write(JSON.stringify(result)+'\n'); +} +if (require.main===module) main().catch(error=>{console.error(error.message);process.exitCode=1;}); +module.exports={collectResumeDecision}; diff --git a/.github/scripts/release-resume.test.cjs b/.github/scripts/release-resume.test.cjs new file mode 100644 index 0000000000..0ad20d2ff4 --- /dev/null +++ b/.github/scripts/release-resume.test.cjs @@ -0,0 +1,112 @@ +'use strict'; +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { mkdtempSync, writeFileSync, rmSync } = require('node:fs'); +const { tmpdir } = require('node:os'); +const { join } = require('node:path'); +const { spawnSync } = require('node:child_process'); +const { collectResumeDecision } = require('./release-resume.cjs'); +const packageName = '@bitkyc08/opencodex', sourceSha = 'a'.repeat(40), version = '2.100.1'; +const assetDigest = 'b'.repeat(64); +function fixture() { + const data = { + registry:{name:packageName,versions:{[version]:{name:packageName,version,gitHead:sourceSha}},time:{[version]:'2026-01-01T00:00:00.000Z'},'dist-tags':{latest:version}}, + tags:[{name:`v${version}`,commit:{sha:sourceSha}}], + release:null, + receipt:{version,sha:sourceSha,repo:'lidge-jun/opencodex',assets:{'ocx.zip':assetDigest}}, + }; + const fetchImpl = async (url,options) => { + assert.equal(options.method,undefined); + if (url === 'https://registry.npmjs.org/%40bitkyc08%2Fopencodex') { assert.equal(options.headers.Authorization,undefined); return Response.json(data.registry); } + assert.equal(options.headers.Authorization,'Bearer token'); + if (url.endsWith('/tags?per_page=100&page=1')) return Response.json(data.tags); + if (url.endsWith(`/releases/tags/v${version}`)) return data.release === null ? new Response('',{status:404}) : Response.json(data.release); + if (url.endsWith('/releases/99/assets?per_page=100&page=1')) return Response.json(data.release.assets); + throw Error(`unexpected URL ${url}`); + }; + return {data,args:{version,sourceSha,channel:'stable',token:'token',fetchImpl,now:()=>Date.parse('2026-01-02T00:00:00Z')}}; +} +test('explicit attested version and source produce a resume decision without npm publication', async () => { + const f=fixture(); + assert.deepEqual(await collectResumeDecision(f.args),{version,sourceSha,channel:'stable',publishNpm:false,tagExists:true,releaseExists:false,assetsChecked:false}); +}); +test('missing tag is allowed but wrong or unknown metadata is rejected', async () => { + const f=fixture(); f.data.tags=[]; + assert.equal((await collectResumeDecision(f.args)).tagExists,false); + for (const change of [ + f=>f.data.registry.versions[version].gitHead='c'.repeat(40), + f=>delete f.data.registry.versions[version], + f=>f.data.registry.versions[version].version='2.100.0', + f=>f.data.tags[0].commit.sha='c'.repeat(40), + f=>f.data.tags[0].commit.sha=null, + f=>delete f.data.registry.time[version], + f=>f.args.channel='preview', + f=>f.args.sourceSha='', + ]) { const x=fixture(); change(x); await assert.rejects(collectResumeDecision(x.args)); } +}); +test('newer npm publication or git tag blocks rollback', async () => { + for (const change of [ + f=>{f.data.registry.versions['2.100.2']={name:packageName,version:'2.100.2',gitHead:'c'.repeat(40)}; f.data.registry.time['2.100.2']='2026-01-01T01:00:00.000Z';}, + f=>{f.data.registry.versions['2.100.0']={name:packageName,version:'2.100.0',gitHead:'c'.repeat(40)}; f.data.registry.time['2.100.0']='2026-01-01T01:00:00.000Z';}, + f=>{f.data.tags.push({name:'v2.100.2',commit:{sha:sourceSha}});}, + ]) { const f=fixture(); change(f); await assert.rejects(collectResumeDecision(f.args),/floor|rollback/i); } +}); +test('existing release assets can only be reused against a matching verified receipt', async () => { + const f=fixture(); + f.data.release={id:99,tag_name:`v${version}`,draft:true,prerelease:false,assets:[{name:'ocx.zip',state:'uploaded',digest:`sha256:${assetDigest}`}]}; + const decision=await collectResumeDecision({...f.args,assetReceipt:f.data.receipt}); + assert.equal(decision.publishNpm,false); assert.deepEqual(decision.reuseAssets,['ocx.zip']); assert.deepEqual(decision.missingAssets,[]); + f.data.release.assets[0].digest='sha256:'+'c'.repeat(64); + await assert.rejects(collectResumeDecision({...f.args,assetReceipt:f.data.receipt}),/asset/i); + f.data.release.assets[0].digest=`sha256:${assetDigest}`; + await assert.rejects(collectResumeDecision({...f.args,assetReceipt:{...f.data.receipt,sha:'c'.repeat(40)}}),/receipt/i); +}); +test('draft may upload missing verified assets; published release cannot be missing them', async () => { + const f=fixture(); f.data.release={id:99,tag_name:`v${version}`,draft:true,prerelease:false,assets:[]}; + const result=await collectResumeDecision({...f.args,assetReceipt:f.data.receipt}); + assert.deepEqual(result.missingAssets,['ocx.zip']); + f.data.release.draft=false; + await assert.rejects(collectResumeDecision({...f.args,assetReceipt:f.data.receipt}),/missing/i); +}); +test('unknown and duplicate release assets and changing registry evidence are rejected', async () => { + const f=fixture(); + const asset={name:'ocx.zip',state:'uploaded',digest:`sha256:${assetDigest}`}; + f.data.release={id:99,tag_name:`v${version}`,draft:true,prerelease:false,assets:[asset,asset]}; + await assert.rejects(collectResumeDecision({...f.args,assetReceipt:f.data.receipt}),/asset/i); + f.data.release.assets=[{...asset,name:'unknown.zip'}]; + await assert.rejects(collectResumeDecision({...f.args,assetReceipt:f.data.receipt}),/asset/i); + const g=fixture(); let reads=0; const original=g.args.fetchImpl; + g.args.fetchImpl=async (...args)=>{ + if (args[0].startsWith('https://registry.npmjs.org/') && ++reads===2) g.data.registry['dist-tags'].preview=version; + return original(...args); + }; + await assert.rejects(collectResumeDecision(g.args),/changed/i); +}); +test('a newer tag on a later GitHub API page blocks resume', async () => { + const f=fixture(), original=f.args.fetchImpl; + f.args.fetchImpl=async (url,options)=>{ + if (url.endsWith('/tags?per_page=100&page=1')) return Response.json(Array.from({length:100},(_,i)=>({name:`old-${i}`,commit:{sha:sourceSha}}))); + if (url.endsWith('/tags?per_page=100&page=2')) return Response.json([{name:'v2.100.2',commit:{sha:sourceSha}}]); + return original(url,options); + }; + await assert.rejects(collectResumeDecision(f.args),/tag floor/); +}); +test('CLI consumes explicit version and source and prints the no-publish decision', () => { + const f=fixture(), dir=mkdtempSync(join(tmpdir(),'resume-cli-')); + try { + const fixturePath=join(dir,'fixture.json'), preload=join(dir,'preload.cjs'); + writeFileSync(fixturePath,JSON.stringify(f.data)); + writeFileSync(preload,`const d=require(${JSON.stringify(fixturePath)}); global.fetch=async (u,o)=>{if(o.method) throw Error('unexpected method'); if(u.startsWith('https://registry.npmjs.org/')) return Response.json(d.registry); if(u.includes('/tags?')) return Response.json(d.tags); if(u.includes('/releases/tags/')) return d.release ? Response.json(d.release) : new Response('',{status:404}); if(u.includes('/releases/99/assets?')) return Response.json(d.release.assets); throw Error('unexpected request');};`); + const run=spawnSync(process.execPath,['--require',preload,join(__dirname,'release-resume.cjs'),'check',version,sourceSha,'stable'],{encoding:'utf8',env:{...process.env,GH_TOKEN:'token'}}); + assert.equal(run.status,0,run.stderr); + assert.deepEqual(JSON.parse(run.stdout),{version,sourceSha,channel:'stable',publishNpm:false,tagExists:true,releaseExists:false,assetsChecked:false}); + f.data.release={id:99,tag_name:`v${version}`,draft:true,prerelease:false,assets:[{name:'ocx.zip',state:'uploaded',digest:`sha256:${assetDigest}`}]}; + writeFileSync(fixturePath,JSON.stringify(f.data)); + const receiptPath=join(dir,'receipt.json'); writeFileSync(receiptPath,JSON.stringify(f.data.receipt)); + const assets=spawnSync(process.execPath,['--require',preload,join(__dirname,'release-resume.cjs'),'check-assets',version,sourceSha,'stable',receiptPath],{encoding:'utf8',env:{...process.env,GH_TOKEN:'token'}}); + assert.equal(assets.status,0,assets.stderr); + assert.deepEqual(JSON.parse(assets.stdout).reuseAssets,['ocx.zip']); + const invalid=spawnSync(process.execPath,['--require',preload,join(__dirname,'release-resume.cjs'),'check',version,'','stable'],{encoding:'utf8',env:{...process.env,GH_TOKEN:'token'}}); + assert.equal(invalid.status,1); assert.equal(invalid.stdout,''); + } finally {rmSync(dir,{recursive:true,force:true});} +}); diff --git a/.github/workflows/catalog-async-contracts.yml b/.github/workflows/catalog-async-contracts.yml index eb6f033500..b35e4286cb 100644 --- a/.github/workflows/catalog-async-contracts.yml +++ b/.github/workflows/catalog-async-contracts.yml @@ -1,15 +1,6 @@ name: Catalog async contracts on: - push: - branches: [main, preview] - paths: - - src/** - - scripts/diagnostics/windows-version-control/** - - .github/actions/setup-project-bun/** - - .github/workflows/catalog-async-contracts.yml - - package.json - - bun.lock pull_request: paths: - src/** @@ -28,15 +19,30 @@ concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + validate-source: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Validate dispatch source + shell: bash + env: + EVENT_NAME: ${{ github.event_name }} + REF: ${{ github.ref }} + run: | + if [ "$EVENT_NAME" = workflow_dispatch ] && [ "$REF" != refs/heads/dev ]; then + echo '::error::manual catalog contracts must run from dev' + exit 1 + fi + contracts: + needs: validate-source name: Catalog async contracts (${{ matrix.os }}) runs-on: ${{ matrix.os }} timeout-minutes: 15 strategy: fail-fast: false matrix: - # Pull requests run the ubuntu leg only; macos and windows run on push - # to main/preview and on manual dispatch. + # Pull requests run the ubuntu leg only; macos and windows run on manual dispatch. os: ${{ fromJSON(github.event_name == 'pull_request' && '["ubuntu-latest"]' || '["ubuntu-latest","macos-latest","windows-latest"]') }} steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2df7ddab92..dc5496ad7e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,12 +1,13 @@ # ============================================================================ # CI POLICY (maintainer decision — do not change in a contributor PR) -# * Pull requests run ONLY the fast Ubuntu subset. +# * Pull requests run ONLY the fast Ubuntu subset (default: gates + `test changed`). # * Full cross-platform (macOS/Windows) CI runs ONLY via manual -# workflow_dispatch and on push to main/preview (release lines). -# * NEVER add a dev push trigger or pull_request runs for macOS/Windows jobs. +# workflow_dispatch on dev. +# * NEVER add a push trigger or pull_request runs for macOS/Windows jobs. # PRs that change this policy will be closed. See AGENTS.md "CI policy". # ============================================================================ name: Cross-platform CI +run-name: ocx-ci-v1 lane=${{ github.event.inputs.lane || 'all' }} sha=${{ github.sha }} on: # Always create the aggregate `ci` check for pull requests. Expensive jobs @@ -14,7 +15,7 @@ on: # docs-only PR receives explicit positive evidence instead of no check at all. pull_request: {} # No base-branch filter on purpose. GitHub matches `branches:` against the - # BASE ref, so `[main, dev]` silently excluded stacked child PRs — whose + # BASE ref, so even `[dev]` would silently exclude stacked child PRs — whose # base is another open PR's head branch, an intentional review workflow per # AGENTS.md that `enforce-target` already exempts from the wrong-base gate. # The #951-#955 stack merged with `enforce-target`, `label`, and @@ -24,79 +25,25 @@ on: # An allowlist cannot express "base is another PR's head" — stacked bases # carry contributor prefixes (`fix/`, `feat/`, `agent/`) as readily as # `codex/`, and contributor stacks need CI most. The `changes` job below is - # the real scope gate, using the same allowlist as the push trigger. Safe to - # widen here - # because this workflow is `pull_request` (not `pull_request_target`), + # the real scope gate for expensive jobs. Safe to + # widen here because this workflow is `pull_request` (not `pull_request_target`), # declares `contents: read`, and reads no secrets. # - # - # Pull requests run only the fast Ubuntu subset. Every macOS and Windows - # job (and the macOS/Windows legs of the keyring, npm-global, setup-action - # and remote-helper matrices) is skipped on `pull_request` and runs after - # merge instead, via workflow_dispatch, the main/preview `push:` below and - # the nightly schedule. - # - # `push:` is pinned to the release lines. dev is deliberately absent: - # cross-platform evidence for dev is run by hand via workflow_dispatch. - # main and preview MUST stay: release.yml requires a successful push-event - # Cross-platform CI run for the exact release SHA and states that a - # pull-request run does not qualify, so removing either branch breaks - # publication. - push: - branches: [main, preview] - paths: - - "Dockerfile" - - "compose.yaml" - - ".dockerignore" - - "docker/**" - - "src/**" - - "bin/**" - - "tests/**" - - "scripts/**" - - "app/**" - - "desktop/**" - - "gui/**" - - "assets/**" - - ".github/scripts/**" - - ".github/workflows/**" - - ".gitattributes" - - ".npmignore" - - "package.json" - - "bun.lock" - - "tsconfig.json" - - "README.md" - - "readme/**" - - "skills/**" - - ".github/ISSUE_TEMPLATE/**" - - "LICENSE" + # Pull requests run only the fast Ubuntu subset. Cross-platform jobs run + # after merge by a manual workflow_dispatch on dev. workflow_dispatch: inputs: lane: - description: "all (default), release-gates, or macos-control" + description: "all (default), release-gates, macos-control, or windows-native-claim" type: choice default: all - options: [all, release-gates, macos-control] - # Nightly safety net. The Windows shards run on a pull request only when the - # changes job judges it Windows-sensitive, so anything that slips past that - # filter must still be caught within a day: a scheduled run requests the full - # lane=all matrix (nine Windows shards and the macOS control included). - # - # GitHub runs schedules from the DEFAULT branch, which is main, so this - # trigger activates only once this file reaches main by promotion, and the - # workflow definition is main's. Every test checkout reads - # needs.changes.outputs.checkout_ref, which the changes job resolves to ONE - # dev commit on a schedule, so the run tests dev and every job tests the same - # SHA. Its check runs attach to main's head commit; release.yml accepts only a - # push-event run, so a scheduled run can never qualify a release. - schedule: - - cron: "17 18 * * *" + options: [all, release-gates, macos-control, windows-native-claim] permissions: contents: read -# Retrigger CI after dir-fsync / oauth deadline follow-ups (tip 34a1ac46). concurrency: - # `push` and `pull_request` want supersession: a newer head on the same ref + # Pull requests want supersession: a newer head on the same ref # makes the older one irrelevant, and cancelling it saves an hour of runners # for an answer nobody will read. # @@ -116,9 +63,8 @@ concurrency: # cancels nothing and nothing cancels it, including a second dispatch of the # same ref. # - # A scheduled run is keyed the same way. Keyed on the ref it would share - # refs/heads/main with a promotion push and, with cancel-in-progress, cancel - # the very run release.yml waits for. + # The schedule branch of this expression is retained for selector compatibility; + # this workflow no longer declares a schedule trigger. group: cross-platform-ci-${{ github.event_name == 'workflow_dispatch' && github.run_id || github.event_name == 'schedule' && github.run_id || github.ref }} cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' && github.event_name != 'schedule' }} @@ -147,12 +93,8 @@ jobs: # honest pull requests on GitHub-hosted runners and lets trusted branch runs # avoid the hosted-Windows Bun crashes. It is not the security boundary. # - # `push` on main/preview requires the push permission, and - # `workflow_dispatch` requires write access, so both carry a trusted author. - # A schedule runs main's workflow against a dev commit that already merged - # through review, the same trust as a push. - # A trusted author is not audited code: merging a contributor PR into `dev` - # fires `push`, and its dependencies and postinstall hooks then run here. + # `workflow_dispatch` requires write access, but a trusted author does not + # make candidate dependencies or postinstall hooks independently audited. select-windows-runner: name: select windows runner runs-on: ubuntu-latest @@ -161,6 +103,17 @@ jobs: runner: ${{ steps.pick.outputs.runner }} label: ${{ steps.pick.outputs.label }} steps: + # This job also runs when the diagnostic lane skips changes. + - name: Validate dispatch source + shell: bash + env: + EVENT_NAME: ${{ github.event_name }} + REF: ${{ github.ref }} + run: | + if [ "$EVENT_NAME" = workflow_dispatch ] && [ "$REF" != refs/heads/dev ]; then + echo '::error::manual cross-platform CI must run from dev' + exit 1 + fi - name: Pick runner id: pick env: @@ -191,7 +144,7 @@ jobs: echo 'label=windows-latest' >> "$GITHUB_OUTPUT" fi - # Which areas this push actually touches. + # Which areas the pull request actually touches. # # Deliberately a job-level filter rather than a wider workflow-level `paths:` # one. A workflow skipped by path filtering leaves its checks Pending forever, @@ -200,6 +153,7 @@ jobs: # in the `on:` block above. changes: name: changes + if: github.event_name != 'workflow_dispatch' || github.event.inputs.lane != 'windows-native-claim' runs-on: ubuntu-latest timeout-minutes: 5 # The workflow grants only `contents: read`, and specifying any permission @@ -216,24 +170,27 @@ jobs: # of silently making every expensive job skip. ci: ${{ steps.scope.outputs.ci }} desktop: ${{ steps.scope.outputs.desktop }} + fast: ${{ steps.lane.outputs.fast }} # true: `test changed` replaces the five shards native: ${{ steps.matrices.outputs.native }} # Matrix include lists for keyring-smoke and npm-global-smoke, built and # shape-checked by the same validation step as `native`. keyring_matrix: ${{ steps.matrices.outputs.keyring_matrix }} npm_global_matrix: ${{ steps.matrices.outputs.npm_global_matrix }} - # A scheduled run starts from main, so its path filter diffs main and would - # scope jobs by the wrong commit. The nightly safety net selects every scope - # instead, here and in the validation steps below, so it is the full matrix. - gui: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.gui }} - packaging: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.packaging }} - docs: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.docs }} - structure: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.structure }} + # A full manual dispatch selects every scope regardless of path filters. + gui: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.gui }} + packaging: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.packaging }} + docs: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.docs }} + structure: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.structure }} # Narrow scopes for two paths the ci filter leaves out on purpose. Both are re-emitted by the # validation step below, so a malformed filter output fails this job instead of silently # skipping the check it selects. setup_action: ${{ steps.narrow.outputs.setup_action }} remote_helper: ${{ steps.narrow.outputs.remote_helper }} - # Whether this pull request needs the nine Windows shards: the windows path + # Pull-request scope for the two smoke jobs that used to ride the whole ci filter. + # Manual dispatch runs both regardless; see the docker/keyring filters. + docker: ${{ steps.narrow.outputs.docker }} + keyring: ${{ steps.narrow.outputs.keyring }} + # Whether this pull request needs the Windows shards: the windows path # filter below OR an added src/tests line naming a Windows marker. Computed # by scripts/ci/windows-sensitive-diff.sh, which validates its input and # treats the diff as data. @@ -242,6 +199,16 @@ jobs: # except on a schedule, where it is the one dev SHA resolved below. checkout_ref: ${{ steps.nightly.outputs.checkout_ref }} steps: + - name: Validate dispatch source + shell: bash + env: + EVENT_NAME: ${{ github.event_name }} + REF: ${{ github.ref }} + run: | + if [ "$EVENT_NAME" = workflow_dispatch ] && [ "$REF" != refs/heads/dev ]; then + echo '::error::manual cross-platform CI must run from dev' + exit 1 + fi - name: Checkout uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: @@ -258,17 +225,18 @@ jobs: uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 with: # Without this the action compares against the repository's DEFAULT - # branch, which is `main`. A push to `dev` would then be diffed against - # `main`, so every area touched since the last promotion keeps reading - # as "changed" — the scoped jobs would run on nearly every dev push and - # the saving would silently not happen while CI stayed green. + # branch, which is `dev`. For a non-PR event that diff starts at + # `dev` itself, so every area touched since the branch point keeps + # reading as "changed" — the scoped jobs would run on nearly every + # such event and the saving would silently not happen while CI stayed + # green. # # On `pull_request` the action ignores this and uses the PR's own file - # list. On a branch push it means "compare against the previous commit - # on this branch", which is the intent. + # list. Otherwise `github.ref` keeps the diff scoped to this ref, which + # is the intent. base: ${{ github.ref }} filters: | - # Mirrors the push trigger's path allowlist. Pull requests always + # Pull requests always # start the workflow so the aggregate check exists, while these # paths decide whether the expensive test jobs need to run. ci: @@ -323,8 +291,7 @@ jobs: # assembled or launched: the shell itself, the standalone sidecar build # and its runtime locator, the native keyring staging, and the dependency # set. Ordinary src/** and gui/** changes no longer select it on a pull - # request; they are still covered on every promotion push to main and - # preview and by workflow_dispatch, which always request this job. + # request; a full manual dispatch requests this job after merge. # The workflow names itself so edits to this lane cannot skip their own E2E. desktop: - 'desktop/**' @@ -339,11 +306,11 @@ jobs: - '.github/workflows/ci.yml' # The docs site is built by nothing else on a pull request. `ci` above # deliberately omits `docs-site/**` -- a prose edit has no business - # starting the cross-platform suite -- and `deploy-docs.yml` triggers - # only on `push` to `main`. That left the Astro toolchain with no - # pull-request build gate at all, so a dependency bump under - # `docs-site/` could only be proven by an author's local run and would - # otherwise surface at promotion. + # starting the cross-platform suite -- and `deploy-docs.yml` is + # dispatch-only. That left the Astro toolchain with no pull-request + # build gate at all, so a dependency bump under `docs-site/` could + # only be proven by an author's local run and would otherwise surface + # at release time. # # `.github/workflows/ci.yml` is here so an edit to the job below # verifies itself. Without it this filter's own pull request would @@ -367,11 +334,8 @@ jobs: # `.github/workflows/ci.yml` is listed for the same reason `docs` # lists it: without it this filter's own pull request would skip the # job it adds. - # This list stays PULL-REQUEST scope only, like `docs` above: the - # push trigger's `paths:` is pinned to mirror `ci` exactly, and - # `dev`, `main` and `preview` are all protected to require a pull - # request, so every `structure/` change is read at the pull request - # before it can reach an integration line. + # This list keeps pull-request scope narrow; full manual dispatches + # also select the structure gate. structure: - 'structure/**' - '.github/workflows/ci.yml' @@ -388,7 +352,44 @@ jobs: # real only on macOS and Windows, so its job lints and tests the crate on all three. remote_helper: - 'native/remote-workspace-helper/**' - # Paths whose change selects the nine Windows suite shards on a pull + # docker-smoke and keyring-smoke on a pull request. Both used to run on every PR the + # ci filter matched, which is nearly all of them, while each proves something narrow: + # the image builds, starts and survives recreation with its volume; the OS keyring + # binding creates, reads and deletes a secret. A pull request now runs each only when + # its own inputs move. Manual dispatch requests both unconditionally. + # ci.yml is listed so an edit to either job verifies itself. The setup action is left to + # its own setup-action job, as the docs and structure filters leave it. + docker: + - 'Dockerfile' + - 'compose.yaml' + - '.dockerignore' + - 'docker/**' + - 'scripts/ci/docker-smoke.ts' + - 'scripts/generate-compatibility-version.ts' + - 'scripts/model-metadata.source.json' + # The image copies and runs src/, then builds the GUI with tsc and Vite. + # Include their inputs without selecting GUI tests or documentation alone. + - 'src/**' + - 'package.json' + - 'bun.lock' + - 'tsconfig.json' + - 'gui/package.json' + - 'gui/bun.lock' + - 'gui/src/**' + - 'gui/public/**' + - 'gui/index.html' + - 'gui/vite.config.ts' + - 'gui/tsconfig*.json' + - '.github/workflows/ci.yml' + # scripts/keyring-smoke.ts imports only src/lib/keyring-native.ts; the native binding + # itself arrives through package.json and bun.lock. + keyring: + - 'src/lib/keyring-native.ts' + - 'scripts/keyring-smoke.ts' + - 'package.json' + - 'bun.lock' + - '.github/workflows/ci.yml' + # Paths whose change selects the Windows suite shards on a pull # request. These carry the Windows service, update, shim, intercept, # ACL and process code, and the harness every Windows shard runs. # scripts/ci/windows-sensitive-diff.sh adds the content markers. @@ -439,8 +440,8 @@ jobs: id: scope shell: bash env: - CI_SCOPE: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.ci }} - DESKTOP_SCOPE: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.desktop }} + CI_SCOPE: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.ci }} + DESKTOP_SCOPE: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.desktop }} run: | set -euo pipefail case "$CI_SCOPE" in @@ -466,7 +467,7 @@ jobs: id: matrices shell: bash env: - NATIVE_SELECTED: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.native }} + NATIVE_SELECTED: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.native }} EVENT_NAME: ${{ github.event_name }} run: | set -euo pipefail @@ -530,11 +531,13 @@ jobs: id: narrow shell: bash env: - SETUP_ACTION: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.setup_action }} - REMOTE_HELPER: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.remote_helper }} + SETUP_ACTION: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.setup_action }} + REMOTE_HELPER: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.remote_helper }} + DOCKER_SCOPE: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.docker }} + KEYRING_SCOPE: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.keyring }} run: | set -euo pipefail - for pair in "setup_action=$SETUP_ACTION" "remote_helper=$REMOTE_HELPER"; do + for pair in "setup_action=$SETUP_ACTION" "remote_helper=$REMOTE_HELPER" "docker=$DOCKER_SCOPE" "keyring=$KEYRING_SCOPE"; do case "${pair#*=}" in true|false) printf '%s\n' "$pair" >> "$GITHUB_OUTPUT" @@ -546,6 +549,15 @@ jobs: esac done + - name: Choose the pull request test lane + id: lane + shell: bash + env: + EVENT_NAME: ${{ github.event_name }} + CI_SCOPE: ${{ steps.scope.outputs.ci }} + FULL_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'ci:full') }} + run: bash scripts/ci/select-test-lane.sh + - name: Decide whether the Windows shards run id: windows shell: bash @@ -554,9 +566,10 @@ jobs: PATH_SELECTED: ${{ steps.filter.outputs.windows }} run: bash scripts/ci/windows-sensitive-diff.sh - # A scheduled run starts from main's head. Resolve dev ONCE so the nine - # Windows shards, the macOS control and every other job test one commit, - # however long the queue between them. contents: read already covers it. + # A scheduled run starts from the default branch's head, which is `dev`. + # Resolve dev ONCE so the nine Windows shards, the macOS control and every + # other job test one commit, however long the queue between them. + # contents: read already covers it. - name: Resolve the commit a scheduled run tests id: nightly shell: bash @@ -578,13 +591,11 @@ jobs: printf 'Scheduled run: workflow from %s, testing dev at %s\n' "$GITHUB_SHA" "$sha" >> "$GITHUB_STEP_SUMMARY" printf 'scheduled run tests dev at %s (workflow %s)\n' "$sha" "$GITHUB_SHA" - # Bun roles (#6713): runtime 1.4.2 fixes #6684's Windows Bun.fetch streaming; - # the test runner skipped 1.4.2's multi-file --isolate preload segfault (#4821 - # reverted #4064; run 37631558263: Linux 1/4, macOS 2/2, Windows 9/9) and runs - # 1.4.3, whose oven-sh/bun#44581 stops Bun.spawnSync losing a child's exit (#4956). - # Rejoin after the upstream runner crash is fixed and a green lane=all dispatch - # proves the unified version, then delete testRunnerBun and the action's role input. - # The suite, split by file across four Linux runners. + # Bun runtime and test-runner roles both read their 1.4.4 defaults from package.json. + # Keep role validation after the historical isolate preload and spawnSync failures + # (#6713, #4956). Promotion requires a green full cross-platform lane=all run on + # the exact candidate head; focused local results do not replace that proof. + # The suite, split by file across five Linux runners. # # `scripts/ci/run-bun-test-batches.sh` assigns files to shards by the per-file # durations recorded in `scripts/ci/test-durations.tsv` (sorted round-robin when @@ -600,21 +611,27 @@ jobs: # the same coverage in fresh Bun processes. # # Only the suite lives here. Typecheck, lint, build, and the scans run once in - # `gates` rather than four times — they are fixed cost, and paying it per shard + # `gates` rather than five times — they are fixed cost, and paying it per shard # would eat what the sharding saves. + # The heavy Linux jobs (test shards, test-changed, gates) take the lidge self-hosted pool on + # trusted runs while the repository variable LIDGE_RUNNERS is on: pushes, manual runs, branches of + # this repository, and pull requests by owners, members or collaborators. Everything else, and every + # run while the variable is off, stays on ubuntu-latest, so the hosted runners keep carrying the light + # jobs. As with the Windows box above, this routing is operational; the fork-PR approval policy and + # the box's scaler, which only creates runners for trusted runs, are the security boundary. test: - name: test ${{ matrix.shard }}/4 + name: test ${{ matrix.shard }}/5 needs: changes - if: github.event_name != 'pull_request' || needs.changes.outputs.ci == 'true' - runs-on: ubuntu-latest - # A quarter of the suite. A shard that needs longer than this is wedged, not + if: github.event_name != 'pull_request' || (needs.changes.outputs.ci == 'true' && needs.changes.outputs.fast != 'true') + runs-on: ${{ vars.LIDGE_RUNNERS == 'on' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository || contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.pull_request.author_association)) && fromJSON('["self-hosted","linux","x64","lidge"]') || 'ubuntu-latest' }} + # A fifth of the suite. A shard that needs longer than this is wedged, not # slow — the old 30-minute ceiling was margin for the Windows leg, which no # longer runs here (see platform-windows). timeout-minutes: 15 strategy: fail-fast: false matrix: - shard: [1, 2, 3, 4] + shard: [1, 2, 3, 4, 5] steps: - name: Checkout uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 @@ -647,10 +664,7 @@ jobs: # gui/package.json. Without this the affected shards die on # `Cannot find module 'react/jsx-dev-runtime'` while the other shards pass. - name: Install dependencies - run: | - bun install --frozen-lockfile - cd gui - bun install --frozen-lockfile + run: bash scripts/ci/bun-install-frozen.sh . gui # Nor is the build. Tests that fetch the served dashboard read the session # bootstrap meta tags out of `gui/dist/index.html`, so without a build the @@ -665,9 +679,30 @@ jobs: - name: Test in fresh-process batches env: - TEST_SHARD: ${{ matrix.shard }}/4 + TEST_SHARD: ${{ matrix.shard }}/5 run: bash scripts/ci/run-bun-test-batches.sh "$TEST_SHARD" + # Fast lane: import-graph tests for the diff; the batched dev dispatch is the backstop. + test-changed: + name: test changed + needs: changes + if: github.event_name == 'pull_request' && needs.changes.outputs.fast == 'true' + runs-on: ${{ vars.LIDGE_RUNNERS == 'on' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository || contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.pull_request.author_association)) && fromJSON('["self-hosted","linux","x64","lidge"]') || 'ubuntu-latest' }} + timeout-minutes: 30 + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + persist-credentials: false + ref: ${{ needs.changes.outputs.checkout_ref }} + fetch-depth: 2 # merge commit + base tip, which the selection diffs against + - uses: ./.github/actions/setup-project-bun + with: + role: test-runner # See the Bun roles contract above test. + - name: Install dependencies and build the GUI the tests serve + run: bash scripts/ci/bun-install-frozen.sh . gui && cd gui && bun run build + - name: Test the files this pull request reaches + run: bash scripts/ci/run-changed-tests.sh + # Bun 1.3.14 has shown a Linux isolate/epoll race around the storage-policy # harness. Keep the entire six-file family in one fresh process so a runtime # failure is bounded to this job instead of poisoning a general test shard. @@ -690,10 +725,7 @@ jobs: role: test-runner # See the Bun roles contract above test. - name: Install dependencies - run: | - bun install --frozen-lockfile - cd gui - bun install --frozen-lockfile + run: bash scripts/ci/bun-install-frozen.sh . gui - name: Build GUI run: | @@ -732,10 +764,7 @@ jobs: role: test-runner # See the Bun roles contract above test. - name: Install dependencies - run: | - bun install --frozen-lockfile - cd gui - bun install --frozen-lockfile + run: bash scripts/ci/bun-install-frozen.sh . gui - name: Build GUI run: | @@ -752,7 +781,7 @@ jobs: name: gates needs: changes if: github.event_name != 'pull_request' || needs.changes.outputs.ci == 'true' - runs-on: ubuntu-latest + runs-on: ${{ vars.LIDGE_RUNNERS == 'on' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository || contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.pull_request.author_association)) && fromJSON('["self-hosted","linux","x64","lidge"]') || 'ubuntu-latest' }} timeout-minutes: 15 steps: - name: Checkout @@ -763,6 +792,8 @@ jobs: # residue. Matches the convention already used by the other workflows. persist-credentials: false ref: ${{ needs.changes.outputs.checkout_ref }} + # Release history tests verify old tag and dev-baseline trees. + fetch-depth: 0 - name: Setup project Bun uses: ./.github/actions/setup-project-bun @@ -770,10 +801,7 @@ jobs: role: test-runner # See the Bun roles contract above test. - name: Install dependencies - run: | - bun install --frozen-lockfile - cd gui - bun install --frozen-lockfile + run: bash scripts/ci/bun-install-frozen.sh . gui - name: GUI lint if: needs.changes.outputs.gui == 'true' @@ -799,6 +827,9 @@ jobs: - name: Check the generated ocx skill surface is current run: bun run skill:surface:check + - name: Test release evidence, history and docs deployment + run: node --test .github/scripts/release-dispatch-guard.test.cjs .github/scripts/release-evidence.test.cjs .github/scripts/release-history.test.cjs .github/scripts/release-resume.test.cjs .github/workflows/deploy-docs.test.cjs + - name: Check release helper syntax run: bun build scripts/release.ts --target=bun --outdir=.tmp/ci-release-script-check @@ -827,29 +858,28 @@ jobs: run: bun run src/cli/index.ts help platform-macos: - name: macos ${{ matrix.shard }}/3 + name: macos ${{ matrix.shard }}/4 needs: changes - # Never on pull requests: macOS legs run after merge, on push to - # main/preview, and on dispatch and the schedule. + # Never on pull requests: macOS legs run through manual dispatch. if: github.event_name != 'pull_request' runs-on: macos-latest - # Three shards. Unsharded, this job was the critical path on every green dev - # push (mean 14.9 min against a 4.7 min Linux maximum; devlog - # 260905_test_modularization_and_windows/003), so it was split in two. The - # suite then outgrew two halves: across seventeen dev dispatches from - # 2026-10-04 to 10-12 the slower half's test step went from 867s to 1155s, - # and run 38214884055 cancelled macos 2/2 at this cap with 68 files left - # while every test it had run was passing (#6978). Replaying the duration - # assignment against those runs' measured per-file times puts the slowest of - # three shards at 635-796s of tests, about 14 minutes with setup. The cap - # stays 20: the suite needs another shard, not a longer wait, and a wedged - # shard (#4956) is still cut off as early as before. The full-membership - # control runs the same bounded batches without sharding on explicit dispatch. + # Four shards. Three replaced two after run 38214884055 hit this cap with + # 68 files left and no failing tests (#6978). The suite outgrew three too: + # run 40727740334 took 13.1-16.4m, 40743681086 12.7-13.7m, and + # 40756291846 15.0-17.1m. In dev lane=all run 40766068492 (b16bc0978b), + # macos 1/3 (123090588998) reached batch 73/88 and macos 2/3 + # (123090589363) batch 93/93 before this cap cancelled them, with no failing + # tests. The cap stays 20: the suite needs another shard, not a longer wait, + # and a wedged shard (#4956) is still cut off as early as before. Four suite + # shards + control + widget/bundle request six macOS jobs for five runner + # slots: one queues, and each run pays one extra shard's setup overhead. + # The full-membership control runs the same bounded batches without sharding + # on explicit dispatch. timeout-minutes: 20 strategy: fail-fast: false matrix: - shard: [1, 2, 3] + shard: [1, 2, 3, 4] steps: - name: Checkout uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 @@ -895,7 +925,7 @@ jobs: - name: Test in fresh-process batches env: - TEST_SHARD: ${{ matrix.shard }}/3 + TEST_SHARD: ${{ matrix.shard }}/4 BUN_TEST_FILE_SCOPE: all BUN_TEST_BATCH_SIZE: '12' BUN_TEST_PARALLEL: '1' @@ -912,7 +942,6 @@ jobs: needs: changes # Diagnostic-only lanes stay off the ordinary release gates: list every lane # that should run this job, so a new lane defaults to skipping the diagnostic. - # The nightly schedule is the full lane=all matrix, so it runs this job too. if: >- github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all' || github.event.inputs.lane == 'macos-control') runs-on: macos-latest @@ -978,33 +1007,43 @@ jobs: - name: CLI help smoke run: bun run src/cli/index.ts help - # Windows runs on a Windows-sensitive pull request, on the nightly schedule, - # and on a lane=all (or default) dispatch. It is never part of the push run - # release.yml gates on. - # - # It left the PR lane first (16m23s against a 6-minute Linux critical path; - # the ceiling was raised twice rather than the gap closed — #711 vs #653, - # issue #717, then #827's 20-minute kill), then left the shipping boundary - # when the sharded promotion run surfaced ~207 Windows-only test failures - # that had been invisible while dev skipped the leg. Those are real defects, - # tracked as issue #1059, but they are pre-existing on every released - # version — gating the release on them blocks shipping fixes to the platforms - # that pass, for a platform that has never shipped green. - # - # The leg stays in the workflow, sharded and dispatchable, so the failure - # list can be burned down without losing the ability to measure progress. - # release.yml gates on a successful push-event run of this workflow, which - # now means Linux + macOS + the gates; Windows re-enters the gate when the - # tracked failures are fixed, not before. - # - # Dispatch-only proved too late. #6639, #6556, #6605 and #6606 each landed with - # green pull-request CI while breaking Windows, and the breakage surfaced days - # later on a manual dispatch. So a pull request whose changes job reports - # windows=true (a Windows path, or an added src/tests line naming a Windows - # marker; see scripts/ci/windows-sensitive-diff.sh) now runs the nine shards, - # and the daily schedule catches whatever that filter misses. + # A diagnostic run deliberately bypasses changes and the full CI graph. Its + # title identifies it as a partial run, never release evidence. + windows-native-claim: + name: windows native-main claim diagnostic + if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/dev' && github.event.inputs.lane == 'windows-native-claim' + runs-on: windows-latest + timeout-minutes: 30 + steps: + - name: Checkout workflow commit + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Setup project Bun + uses: ./.github/actions/setup-project-bun + with: + role: test-runner + - name: Install dependencies + run: bun install --frozen-lockfile + - name: Isolate homes + shell: pwsh + run: | + $root = Join-Path $env:RUNNER_TEMP "ocx-claim-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + $ocxHome = Join-Path $root 'opencodex' + $codexHome = Join-Path $root 'codex' + New-Item -ItemType Directory -Path $ocxHome, $codexHome -ErrorAction Stop | Out-Null + "OPENCODEX_HOME=$ocxHome" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + "CODEX_HOME=$codexHome" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + - name: Run native-main claim diagnostics + env: + OCX_TEST_WINDOWS_NATIVE_CLAIM_DIAGNOSTIC: '1' + run: bun test tests/codex-integration/main-quota-provenance.test.ts --timeout 60000 + + # Windows shards run only on a full manual dispatch. Pull requests retain + # fast Ubuntu checks, including when the Windows-sensitive filter is set. platform-windows: - name: windows ${{ matrix.shard }}/9 + name: windows ${{ matrix.shard }}/11 needs: [changes, select-windows-runner] if: >- github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all') @@ -1035,21 +1074,18 @@ jobs: # test deadline and all six shards, but left the whole batch and cleanup a # 30-minute bound. # - # Six shards then grew into the 30-minute ceiling too. Across seven lane=all - # dispatches the six shard totals were 114.3-133.2 minutes. The worst observed - # shard imbalance was 1.43x its dispatch's per-shard average. Eight shards leave - # no margin: 133.2 / 8 * 1.43 * 1.25 = 29.8 minutes after the already-observed - # 25% run-to-run slowdown. Nine gives 133.2 / 9 * 1.43 * 1.25 = 26.5 minutes. - # Keep the 30-minute bound and pay for three more concurrent runners plus their - # repeated checkout/install/build setup so test work, rather than the ceiling, - # shrinks. The per-batch timeout below is independent: it aborts a stuck Bun - # process but adds no delay to a healthy one, so calibrating it does not change - # this total-work projection. + # Nine shards also reached the ceiling: run 40756291846 cancelled 7/9 at batch + # 49/60; run 40743681086's successful shards took 22.1-29.5 minutes. Refreshing + # Windows weights from completed primary batches in both runs puts test work + # at 24.36/21.92/19.93 minutes with 9/10/11 shards. With the observed 2.4-minute + # maximum setup, eleven projects ~22.4 minutes; 25% test variance makes ~27.3. + # Pay for two extra setups (~3.3 runner-minutes at the older run's mean), keep + # the 30-minute job bound and all tests, and leave batch deadlines independent. timeout-minutes: 30 strategy: fail-fast: false matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8, 9] + shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] steps: - name: Show selected runner shell: bash @@ -1129,7 +1165,7 @@ jobs: # and service-manager guard before the lock boundary. shell: bash env: - TEST_SHARD: ${{ matrix.shard }}/9 + TEST_SHARD: ${{ matrix.shard }}/11 BUN_TEST_FILE_SCOPE: all BUN_TEST_BATCH_SIZE: "6" BUN_TEST_BATCH_TIMEOUT_SECONDS: "480" @@ -1145,7 +1181,7 @@ jobs: keyring-smoke: name: keyring ${{ matrix.name }} needs: changes - if: github.event_name != 'pull_request' || needs.changes.outputs.ci == 'true' + if: github.event_name != 'pull_request' || (needs.changes.outputs.ci == 'true' && needs.changes.outputs.keyring == 'true') runs-on: ${{ matrix.runner }} timeout-minutes: 8 strategy: @@ -1208,7 +1244,7 @@ jobs: docker-smoke: name: docker smoke needs: changes - if: github.event_name != 'pull_request' || needs.changes.outputs.ci == 'true' + if: github.event_name != 'pull_request' || (needs.changes.outputs.ci == 'true' && needs.changes.outputs.docker == 'true') runs-on: ubuntu-latest timeout-minutes: 20 steps: @@ -1225,7 +1261,7 @@ jobs: run: bun scripts/ci/docker-smoke.ts # Proves the Astro toolchain still builds the site, on the only event that can - # prove it before promotion. + # prove it before release. # # Linux only, and one leg. The site is static output from a Node/Bun toolchain # with no OS-specific behaviour to promise, so a Windows or macOS leg would buy @@ -1268,7 +1304,7 @@ jobs: # aggregate reported success while nothing had read the change (#5001). # # Running the gate directly here, rather than adding `structure/**` to `ci`, - # keeps a prose edit from starting nine Windows shards and two macOS shards for + # keeps a prose edit from starting the Windows shards and macOS shards for # a check that takes seconds. It runs whenever `structure/` changes, including # alongside a `src/` change where the suite covers it too; a duplicate of a # seconds-long check is not worth a condition that could be wrong. @@ -1498,7 +1534,7 @@ jobs: name: macos widget + bundle needs: [changes, gates] # Never on pull requests, like platform-macos: the widget extension and - # app bundle are rebuilt after merge, on push, dispatch and the schedule. + # app bundle are rebuilt through manual dispatch. if: github.event_name != 'pull_request' runs-on: macos-latest timeout-minutes: 30 @@ -1700,12 +1736,12 @@ jobs: ci: name: ci - if: always() + if: always() && (github.event_name != 'workflow_dispatch' || github.event.inputs.lane != 'windows-native-claim') # Every producer, including the ones that only feed other jobs. `needs` holds # direct dependencies only, so a failing `select-windows-runner` would # otherwise reach this gate as nothing at all while its dependents report # `skipped`, which is the shape the step below is written to catch. - needs: [changes, select-windows-runner, test, storage-policy, api-usage, gates, platform-macos, macos-control, platform-windows, keyring-smoke, docker-smoke, docs-site-build, structure-gate, privacy-gate, npm-global-smoke, widget, desktop-shell, setup-action, remote-helper] + needs: [changes, select-windows-runner, test, test-changed, storage-policy, api-usage, gates, platform-macos, macos-control, platform-windows, keyring-smoke, docker-smoke, docs-site-build, structure-gate, privacy-gate, npm-global-smoke, widget, desktop-shell, setup-action, remote-helper] runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -1721,11 +1757,14 @@ jobs: EVENT_NAME: ${{ github.event_name }} LANE: ${{ github.event.inputs.lane }} CHANGES_CI: ${{ needs.changes.outputs.ci }} + CHANGES_FAST: ${{ needs.changes.outputs.fast }} CHANGES_PACKAGING: ${{ needs.changes.outputs.packaging }} CHANGES_DOCS: ${{ needs.changes.outputs.docs }} CHANGES_STRUCTURE: ${{ needs.changes.outputs.structure }} CHANGES_SETUP_ACTION: ${{ needs.changes.outputs.setup_action }} CHANGES_REMOTE_HELPER: ${{ needs.changes.outputs.remote_helper }} + CHANGES_DOCKER: ${{ needs.changes.outputs.docker }} + CHANGES_KEYRING: ${{ needs.changes.outputs.keyring }} CHANGES_NATIVE: ${{ needs.changes.outputs.native }} CHANGES_DESKTOP: ${{ needs.changes.outputs.desktop }} CHANGES_WINDOWS: ${{ needs.changes.outputs.windows }} @@ -1749,6 +1788,12 @@ jobs: if [ "$EVENT_NAME" = "pull_request" ] && [ "$CHANGES_CI" != "true" ]; then scoped=not-requested fi + full_tests=$scoped # the fast lane swaps the shards for test changed; unset = full + changed_tests=not-requested + if [ "$EVENT_NAME" = "pull_request" ] && [ "$scoped" = requested ] && [ "${CHANGES_FAST:-false}" = "true" ]; then + full_tests=not-requested + changed_tests=requested + fi # platform-macos and widget never run on a pull request (macOS runs after merge). # desktop-shell (ubuntu) carries the ordinary scope gate AND the native or # package-E2E path filters. This mirrors those expressions exactly; where it @@ -1782,6 +1827,16 @@ jobs: if [ "$CHANGES_REMOTE_HELPER" = "true" ]; then remote_helper=requested fi + # docker-smoke and keyring-smoke follow the ci scope, narrowed on a pull request to + # their own filters. Mirrors their `if:` exactly, like desktop_shell above. + docker=$scoped + if [ "$EVENT_NAME" = "pull_request" ] && [ "$CHANGES_DOCKER" != "true" ]; then + docker=not-requested + fi + keyring=$scoped + if [ "$EVENT_NAME" = "pull_request" ] && [ "$CHANGES_KEYRING" != "true" ]; then + keyring=not-requested + fi # privacy-gate runs exactly where `gates` (scoped) does not, on every # pull request the ci filter declines. Deriving it from `scoped` keeps # the two scans complementary here as they are in the jobs' own @@ -1801,7 +1856,7 @@ jobs: if [ -z "$LANE" ] || [ "$LANE" = "all" ] || [ "$LANE" = "macos-control" ]; then dispatch=requested fi - # Only the default/all lane requests the nine Windows suite shards. + # Only the default/all lane requests the Windows suite shards. if [ -z "$LANE" ] || [ "$LANE" = "all" ]; then windows=requested fi @@ -1809,7 +1864,7 @@ jobs: # One line per job, mirroring that job's own `if:`. Adding a job to this workflow # without adding it here fails the gate by name rather than passing unnoticed. - GATED_JOBS="changes select-windows-runner test storage-policy api-usage gates" + GATED_JOBS="changes select-windows-runner test test-changed storage-policy api-usage gates" GATED_JOBS="$GATED_JOBS platform-macos keyring-smoke docker-smoke npm-global-smoke" GATED_JOBS="$GATED_JOBS macos-control platform-windows docs-site-build" GATED_JOBS="$GATED_JOBS structure-gate widget" @@ -1820,8 +1875,12 @@ jobs: expected_for() { case "$1" in changes|select-windows-runner) echo requested ;; - test|storage-policy|api-usage|gates|keyring-smoke|docker-smoke) + test) echo "$full_tests" ;; + test-changed) echo "$changed_tests" ;; + storage-policy|api-usage|gates) echo "$scoped" ;; + docker-smoke) echo "$docker" ;; + keyring-smoke) echo "$keyring" ;; platform-macos|widget) echo "$native" ;; desktop-shell) echo "$desktop_shell" ;; @@ -1869,10 +1928,10 @@ jobs: # started: five successes and one skipped leg roll up to `success`. No matrix here # carries a per-leg `if:`, so a leg can only be skipped when its whole job is, which # the expectation table above already catches. What that table cannot catch is a - # matrix that produced FEWER legs than the nine a dispatch is run to read, so count - # them by name. The nine Windows legs are the entire output of that dispatch. + # matrix that produced FEWER legs than the eleven a dispatch is run to read, so count + # them by name. The eleven Windows legs are the entire output of that dispatch. if [ "$windows" = requested ]; then - shards=9 + shards=11 # `filter=latest` (the default) is the latest execution of each job in the run, # which is what a human reading the run sees. Asking for one ATTEMPT instead would # fail every partial re-run: "Re-run failed jobs" puts only the repaired shard in diff --git a/.github/workflows/cleanup-closed-pr-branches.yml b/.github/workflows/cleanup-closed-pr-branches.yml index 4b0c1229a9..8cbca5076b 100644 --- a/.github/workflows/cleanup-closed-pr-branches.yml +++ b/.github/workflows/cleanup-closed-pr-branches.yml @@ -5,9 +5,8 @@ name: Clean branches from closed pull requests # merging leaves its head branch behind forever, which is how this repository # accumulated dozens of dead `codex/*` and `ingw/*` branches. # -# Scheduled workflows only run from the repository DEFAULT branch (currently -# `main`), not from `dev`. Landing this on `dev` alone does not start the -# cleanup until the change is also promoted to that default branch. +# Scheduled workflows only run from the repository DEFAULT branch, which is +# `dev`. A change lands on the live cleanup as soon as it is on `dev`. on: schedule: # Daily at 06:30 UTC (offset from the hour to reduce Action load spikes). diff --git a/.github/workflows/cleanup-orphaned-workflows.yml b/.github/workflows/cleanup-orphaned-workflows.yml index 6915a063ed..02d7005cd9 100644 --- a/.github/workflows/cleanup-orphaned-workflows.yml +++ b/.github/workflows/cleanup-orphaned-workflows.yml @@ -7,13 +7,6 @@ on: schedule: # Daily at 06:00 UTC. - cron: "0 6 * * *" - push: - branches: [main] - paths: - # The first promotion to main performs the initial backlog cleanup without - # exposing a branch-selectable manual trigger with actions:write. - - ".github/workflows/cleanup-orphaned-workflows.yml" - - "scripts/ci/cleanup-orphaned-workflows.mjs" permissions: actions: write # Required to delete orphaned workflow runs through the Actions API. @@ -35,9 +28,9 @@ jobs: persist-credentials: false - name: Setup Bun - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.2 + # The repository composite reads package.json dependencies.bun from the + # checkout above, so this job cannot drift from the runtime pin. + uses: ./.github/actions/setup-project-bun - name: Remove stale workflow histories env: diff --git a/.github/workflows/codex-queue-helpers.yml b/.github/workflows/codex-queue-helpers.yml index 62b5991b79..7145a1fa1a 100644 --- a/.github/workflows/codex-queue-helpers.yml +++ b/.github/workflows/codex-queue-helpers.yml @@ -7,14 +7,6 @@ on: - 'docs-site/astro.config.mjs' - 'docs-site/src/content/docs/guides/composer-usage-gate-fallback.md' - '.github/workflows/codex-queue-helpers.yml' - push: - branches: [main, preview] - paths: - - 'scripts/codex-queue.*' - - 'docs-site/astro.config.mjs' - - 'docs-site/src/content/docs/guides/composer-usage-gate-fallback.md' - - '.github/workflows/codex-queue-helpers.yml' - workflow_dispatch: permissions: diff --git a/.github/workflows/deploy-docs.test.cjs b/.github/workflows/deploy-docs.test.cjs new file mode 100644 index 0000000000..6343c63e1a --- /dev/null +++ b/.github/workflows/deploy-docs.test.cjs @@ -0,0 +1,64 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const workflow = fs.readFileSync(path.join(__dirname, 'deploy-docs.yml'), 'utf8'); +function scriptFor(step) { + const start = workflow.indexOf(` - name: ${step}\n`); + assert.notEqual(start, -1); + const rest = workflow.slice(start); + const match = rest.match(/\n run: \|\n((?: .*\n|\n)+)/); + assert.ok(match); + return match[1].replace(/^ /gm, ''); +} +const selection = scriptFor('Resolve published stable source'); +const guard = scriptFor('Require trusted dispatch'); +const sha = 'a'.repeat(40); +function run(script, overrides = {}) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ocx-pages-test-')); + try { + fs.writeFileSync(path.join(dir, 'gh'), '#!/bin/bash\nprintf "%s" "$MOCK_RELEASE"\n', { mode: 0o755 }); + fs.writeFileSync(path.join(dir, 'git'), '#!/bin/bash\nif [ "$MOCK_GIT_FAIL" = 1 ]; then exit 1; fi\nprintf "%s\\n" "$MOCK_SHA"\n', { mode: 0o755 }); + const output = path.join(dir, 'output'); + fs.writeFileSync(output, ''); + const env = { ...process.env, PATH: `${dir}:${process.env.PATH}`, GITHUB_OUTPUT: output, + GITHUB_STEP_SUMMARY: path.join(dir, 'summary'), GITHUB_REPOSITORY: 'owner/repo', + GITHUB_EVENT_NAME: 'workflow_dispatch', GITHUB_REF: 'refs/heads/dev', RELEASE_TAG: '', + MOCK_RELEASE: JSON.stringify({ tag_name: 'v2.3.4', draft: false, prerelease: false }), MOCK_SHA: sha, + ...overrides }; + const result = spawnSync('bash', ['-c', script], { env, encoding: 'utf8' }); + return { ...result, output: fs.readFileSync(output, 'utf8') }; + } finally { fs.rmSync(dir, { recursive: true, force: true }); } +} +test('only trusted dev dispatch reaches the build', () => { + assert.equal(run(guard).status, 0); + assert.notEqual(run(guard, { GITHUB_REF: 'refs/heads/pr-head' }).status, 0); + assert.notEqual(run(guard, { GITHUB_EVENT_NAME: 'push' }).status, 0); + assert.doesNotMatch(workflow, /^ push:/m); + assert.match(workflow, /ref: \$\{\{ steps\.source\.outputs\.sha \}\}/); + assert.match(workflow, /permissions:\n pages: write\n id-token: write/); +}); +test('latest and explicit published stable release select immutable commit', () => { + const latest = run(selection); + assert.equal(latest.status, 0, latest.stderr); + assert.equal(latest.output, `sha=${sha}\n`); + const explicit = run(selection, { RELEASE_TAG: 'v2.3.4', MOCK_RELEASE: JSON.stringify({ tagName: 'v2.3.4', isDraft: false, isPrerelease: false }) }); + assert.equal(explicit.status, 0, explicit.stderr); + assert.equal(explicit.output, `sha=${sha}\n`); +}); +test('refuses prereleases, drafts, mismatch, malformed tags and missing commits', () => { + for (const overrides of [ + { RELEASE_TAG: 'v2.3.4-preview.1' }, { RELEASE_TAG: '$(touch evil)' }, + { MOCK_RELEASE: JSON.stringify({ tag_name: 'v2.3.4', draft: true, prerelease: false }) }, + { MOCK_RELEASE: JSON.stringify({ tag_name: 'v2.3.4', draft: false, prerelease: true }) }, + { RELEASE_TAG: 'v2.3.4', MOCK_RELEASE: JSON.stringify({ tagName: 'v2.3.5', isDraft: false, isPrerelease: false }) }, + { MOCK_GIT_FAIL: '1' }, { MOCK_SHA: 'bad' }, { MOCK_RELEASE: '{}' }, + ]) { + const result = run(selection, overrides); + assert.notEqual(result.status, 0, JSON.stringify(overrides)); + assert.equal(result.output, ''); + } +}); diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index c46821034e..c726f02677 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -1,17 +1,14 @@ name: Deploy Docs to GitHub Pages on: - push: - branches: [main] - paths: - - "docs-site/**" - - ".github/workflows/deploy-docs.yml" workflow_dispatch: + inputs: + release-tag: + description: "Published stable release tag (empty selects the latest stable release)" + required: false + type: string -permissions: - contents: read - pages: write - id-token: write +permissions: {} concurrency: group: pages @@ -19,24 +16,74 @@ concurrency: jobs: build: - # Our independent repository does not publish the inherited site's configuration. - if: vars.OCX_ENABLE_DOCS_DEPLOY == '1' runs-on: ubuntu-latest timeout-minutes: 15 + permissions: + contents: read steps: - - name: Checkout + - name: Require trusted dispatch + run: | + test "$GITHUB_EVENT_NAME" = workflow_dispatch && test "$GITHUB_REF" = refs/heads/dev || { + echo '::error::Dispatch the trusted workflow from dev.'; exit 1; + } + - name: Checkout trusted workflow revision uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + ref: ${{ github.sha }} + fetch-depth: 0 + persist-credentials: false + - name: Resolve published stable source + id: source + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ inputs.release-tag }} + run: | + set -euo pipefail + if [ -n "$RELEASE_TAG" ]; then + [[ "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]] || { + echo '::error::Expected a stable release tag such as v1.2.3.'; exit 1; + } + release="$(gh release view "$RELEASE_TAG" --json tagName,isDraft,isPrerelease)" + else + release="$(gh api "repos/$GITHUB_REPOSITORY/releases/latest")" + fi + tag="$(RELEASE_JSON="$release" node - <<'NODE' + const r = JSON.parse(process.env.RELEASE_JSON); + const tag = r.tagName ?? r.tag_name; + const draft = r.isDraft ?? r.draft; + const prerelease = r.isPrerelease ?? r.prerelease; + if (draft !== false || prerelease !== false || typeof tag !== 'string' || + !/^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(tag) || + (process.env.RELEASE_TAG && tag !== process.env.RELEASE_TAG)) { + throw new Error('Release is not the requested published stable release'); + } + process.stdout.write(tag); + NODE + )" + sha="$(git rev-parse --verify "refs/tags/${tag}^{commit}")" + [[ "$sha" =~ ^[0-9a-f]{40}$ ]] || { echo '::error::Invalid release commit.'; exit 1; } + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "Building published release $tag at $sha" >> "$GITHUB_STEP_SUMMARY" + - name: Checkout published source + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + ref: ${{ steps.source.outputs.sha }} + persist-credentials: false - name: Build with Astro uses: withastro/action@e84f40bd8d2caa9e768ec82ad30dd81f0b280853 # v6.1.2 with: path: ./docs-site node-version: 22 - package-manager: bun@latest + # Must equal package.json dependencies.bun (asserted in ci-workflows.test.ts). + package-manager: bun@1.4.4 deploy: needs: build runs-on: ubuntu-latest timeout-minutes: 10 + permissions: + pages: write + id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} diff --git a/.github/workflows/dev-version-bump.yml b/.github/workflows/dev-version-bump.yml index 99a8946c3e..cd99285c43 100644 --- a/.github/workflows/dev-version-bump.yml +++ b/.github/workflows/dev-version-bump.yml @@ -19,8 +19,8 @@ name: Dev version bump # # A branch-selected dispatch executes that branch's workflow body with write permission. # The in-job guard therefore rejects accidental non-default-ref dispatches. It is an early -# warning, not a security boundary: a writer could remove it on their branch. Protected -# release branches and the required review on `dev` remain the enforcement boundaries. +# warning, not a security boundary: a writer could remove it on their branch. The protected +# `dev` branch and its required review remain the enforcement boundaries. on: workflow_dispatch: inputs: diff --git a/.github/workflows/enforce-issue-quality.yml b/.github/workflows/enforce-issue-quality.yml index a983da5d78..1531fb79f8 100644 --- a/.github/workflows/enforce-issue-quality.yml +++ b/.github/workflows/enforce-issue-quality.yml @@ -1,9 +1,8 @@ name: Enforce issue quality -# Issue events always load this workflow from the repository DEFAULT branch -# (currently `main`), not from `dev`. Landing here on `dev` alone does not -# change live issue-quality behavior until the change is also on that default -# branch. +# Issue events always load this workflow from the repository DEFAULT branch, +# which is `dev`. A change lands on the live issue-quality gate as soon as it is +# on `dev`. on: issues: types: diff --git a/.github/workflows/enforce-pr-target.yml b/.github/workflows/enforce-pr-target.yml index 35f6ea7b38..d2a9674595 100644 --- a/.github/workflows/enforce-pr-target.yml +++ b/.github/workflows/enforce-pr-target.yml @@ -44,7 +44,8 @@ jobs: github.event.label.name == 'test-exception-approved' || github.event.label.name == 'suppression-approved' || github.event.label.name == 'generated-change-approved' || - github.event.label.name == 'dependency-change-approved')) + github.event.label.name == 'dependency-change-approved' || + github.event.label.name == 'attribution-approved')) runs-on: ubuntu-latest permissions: contents: read @@ -190,19 +191,17 @@ jobs: # PR's head, so `base.sha` let an unpromoted commit choose which code # runs with this job's contents/pull-requests write token. # - # The branch is chosen, not fixed. `status` has no pull_request - # payload and runs the privileged workflow from the repository - # default branch, so it sources from that same promoted boundary. A - # `main`-targeting PR must take its scripts from `main`, or the gate - # runs a `main` workflow definition against `dev` scripts. Every - # other base, including a stacked child's, resolves to `dev`. - ref: ${{ github.event_name == 'status' && github.event.repository.default_branch || (github.event.pull_request.base.ref == 'main' && 'main' || 'dev') }} + # `status` has no pull_request payload and runs the privileged + # workflow from the repository default branch, so it sources from + # that same boundary. Every pull_request event, including a stacked + # child's, resolves to `dev`, the single integration branch. + ref: ${{ github.event_name == 'status' && github.event.repository.default_branch || 'dev' }} persist-credentials: false sparse-checkout: | .github/scripts MAINTAINERS.md - - name: Enforce PR target, ancestry, and description + - name: Enforce PR target and description uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 env: RESOLVED_PULL_NUMBER: ${{ needs.resolve-pr.outputs.pull-number }} @@ -229,7 +228,11 @@ jobs: ); const { collectDeterministicHygieneFailures, + countHeadRewrites, HYGIENE_FAILURE_HINTS, + needsHeadRewriteCount, + parseApprovalRecord, + reconcileHeadBoundApprovals, } = require( path.join(process.cwd(), ".github", "scripts", "pr-hygiene.cjs"), ); @@ -260,12 +263,13 @@ jobs: const { GATE_MARKER, READINESS_MARKER, - HYGIENE_MARKER, - HYGIENE_BLOCK_START, - HYGIENE_BLOCK_END, inlineCode, buildGateCommentBody, extractHygieneSection, + authoritativeHygieneSection, + withHygieneSection, + escapeControlCharacters, + isGateComment, buildFailureSections, failureSummary, buildStaleNotice, @@ -337,13 +341,10 @@ jobs: ); // One consolidated comment. The gate finds its own comment by the - // single GATE_MARKER; the legacy enforcer/readiness markers are - // matched only to migrate pre-consolidation PRs. - let gateComment = comments.find( - comment => - comment.user?.login === "github-actions[bot]" && - comment.body?.includes(GATE_MARKER) - ); + // single GATE_MARKER its body starts with (a marker echoed inside + // another bot comment does not count); the legacy enforcer/readiness + // markers are matched only to migrate pre-consolidation PRs. + let gateComment = comments.find(isGateComment); let gateCommentId = gateComment?.id ?? null; const storedGateState = parseGateState( gateComment?.body, @@ -437,13 +438,15 @@ jobs: async function upsertGateComment(state, opts) { let body = buildGateCommentBody(state, opts).join("\n"); // The hygiene workflow writes its status into this same comment. - // Preserve whatever it left so a gate rebuild does not drop it. + // Preserve whatever it left so a gate rebuild does not drop it; + // it carries the approval record the next runs read. Appended + // unconditionally (a rebuilt body may not end in whitespace) and + // never through a replacement template. const existingHygiene = extractHygieneSection(gateComment?.body); - if (existingHygiene && !body.includes("pr-hygiene-block")) { - body = body.replace( - /\s+$/, - `\n\n## Hygiene\n\n${HYGIENE_BLOCK_START}\n${HYGIENE_MARKER}\n\n${existingHygiene}\n\n${HYGIENE_BLOCK_END}` - ); + // Delimiter-aware: an echoed path that merely contains the marker + // text must not suppress the preservation. + if (existingHygiene && extractHygieneSection(body) === null) { + body = withHygieneSection(body, existingHygiene.split("\n")); } if (gateCommentId) { // Skip the write when the rebuilt body matches what is already @@ -678,9 +681,7 @@ jobs: gateState.pendingReattestation = null; } - let behindMain = 0; let behindBase = 0; - let aheadMain = 0; let ancestryLookupFailed = false; const baseAllowed = ALLOWED_BASES.includes(pr.base.ref); @@ -720,15 +721,10 @@ jobs: if (baseAllowed) { const headSha = pr.head.sha; try { - const { data: mainCompare } = - await github.rest.repos.compareCommitsWithBasehead({ - owner, - repo, - basehead: `main...${headSha}` - }); - behindMain = mainCompare.behind_by; - aheadMain = mainCompare.ahead_by; - + // `dev` is the only integration branch now. This single + // compare feeds the review-readiness latest-dev claim; there + // is no deleted `main` tip to compare against, so no + // wrong-ancestry verdict is derived here. const { data: baseCompare } = await github.rest.repos.compareCommitsWithBasehead({ owner, @@ -747,6 +743,10 @@ jobs: const changedFiles = []; const changedFilePaths = []; let filesTruncated = true; + // The head the changed-file list was verified against; null when the + // head moved during the snapshot. Head-bound approvals are judged + // against the same head the files belong to. + let changedFilesHeadSha = null; for (let attempt = 0; attempt < 2; attempt += 1) { const { data: fileSnapshot } = await github.rest.pulls.get({ owner, @@ -774,6 +774,8 @@ jobs: core.warning( "PR head moved during changed-file snapshot; treating file list as truncated." ); + } else { + changedFilesHeadSha = headShaForFiles; } changedFiles.length = 0; changedFiles.push(...listedFiles); @@ -794,12 +796,6 @@ jobs: allowedBases: ALLOWED_BASES, title: pr.title, body: pr.body, - behindMain, - behindBase, - aheadMain, - authorPermission, - permissionLookupFailed, - ancestryLookupFailed, stackedBase, // A maintainer issue comment ("not touching gui") waives the // GUI-screenshot gate; the comments are already fetched above. @@ -812,7 +808,37 @@ jobs: // the Hygiene comment section, but Ready / review-ready must not // clear while those checks fail. Re-assess here from the same // trusted scripts so the gate cannot race ahead of hygiene. - const labelNames = (pr.labels ?? []).map(label => label.name); + const liveLabelNames = (pr.labels ?? []).map(label => label.name); + // Head-bound exception approvals count only under the head binding + // the hygiene workflow recorded. This gate reads that record and + // never removes labels or writes it. + const approvalInput = { + labels: liveLabelNames, + // Files listed at another head than this run's PR snapshot + // confirm no approval. + headSha: + changedFilesHeadSha !== null && changedFilesHeadSha === pr.head?.sha + ? changedFilesHeadSha + : null, + record: parseApprovalRecord(authoritativeHygieneSection(comments)), + eventAction: context.payload.action, + }; + let headRewriteCount = null; + if (needsHeadRewriteCount(approvalInput)) { + try { + headRewriteCount = countHeadRewrites(await github.paginate( + github.rest.issues.listEvents, + { owner, repo, issue_number: pull_number, per_page: 100 } + )); + } catch (error) { + core.warning(`Could not read head rewrite history: ${error.message}`); + } + } + const { stale: staleApprovals } = reconcileHeadBoundApprovals({ + ...approvalInput, + headRewriteCount, + }); + const labelNames = liveLabelNames.filter(name => !staleApprovals.includes(name)); // Same inputs the hygiene workflow feeds the carry-attribution // assessor. Both gates must reach the same verdict or Ready can // clear while hygiene is still red. @@ -1222,11 +1248,6 @@ jobs: `Retarget this PR to ${inlineCode(DEFAULT_BASE)} — all contributions go to ${inlineCode(DEFAULT_BASE)}.` ); } - if (failures.some(failure => failure.code === "wrong_ancestry")) { - actions.push( - `Rebase onto the current ${inlineCode(DEFAULT_BASE)} branch instead of opening from ${inlineCode("main")}.` - ); - } if (failures.some(failure => failure.code === "bad_description")) { actions.push( "Add a real **Summary** and **Test plan** to the PR description." @@ -1241,7 +1262,7 @@ jobs: const hint = HYGIENE_FAILURE_HINTS[failure.code]; if (!hint) continue; const paths = failure.paths?.length - ? ` Paths: ${failure.paths.map(p => inlineCode(p)).join(", ")}.` + ? ` Paths: ${failure.paths.map(p => inlineCode(escapeControlCharacters(p))).join(", ")}.` : ""; actions.push(`Fix **${failure.code}** — ${hint}${paths}`); } @@ -1355,9 +1376,6 @@ jobs: if (failure.code === "wrong_base") { return `wrong target branch (${pr.base.ref}); retarget to ${inlineCode(DEFAULT_BASE)}.`; } - if (failure.code === "wrong_ancestry") { - return "wrong branch ancestry; rebase onto the latest dev."; - } if (failure.code === "bad_description") { return `PR description needs work (${failure.reason}).`; } diff --git a/.github/workflows/issue-quality-tests.yml b/.github/workflows/issue-quality-tests.yml index fd064ce101..3917fda15d 100644 --- a/.github/workflows/issue-quality-tests.yml +++ b/.github/workflows/issue-quality-tests.yml @@ -35,42 +35,6 @@ on: - ".github/workflows/issue-triage.yml" - ".github/workflows/issue-quality-tests.yml" - ".github/workflows/pr-hygiene.yml" - push: - # Release lines only; review is covered by the pull_request trigger above. - branches: [main, preview] - paths: - - ".github/ISSUE_TEMPLATE/**" - - ".github/scripts/issue-quality.cjs" - - ".github/scripts/issue-quality-core.cjs" - - ".github/scripts/issue-quality*.test.cjs" - - ".github/scripts/pr-quality.cjs" - - ".github/scripts/pr-quality.test.cjs" - - ".github/scripts/pr-quality-messages.cjs" - - ".github/scripts/pr-quality-messages.test.cjs" - - ".github/scripts/pr-quality-state.cjs" - - ".github/scripts/pr-readiness-reattest.cjs" - - ".github/scripts/pr-quality-state.test.cjs" - - ".github/scripts/pr-labeler.cjs" - - ".github/scripts/pr-labeler.test.cjs" - - ".github/scripts/enforce-pr-target.test.cjs" - - ".github/scripts/pr-hygiene.cjs" - - ".github/scripts/pr-hygiene.test.cjs" - - ".github/scripts/pr-sponsored-surface.cjs" - - ".github/scripts/pr-sponsored-surface.test.cjs" - - ".github/scripts/issue-translation.cjs" - - ".github/scripts/issue-translation.test.cjs" - - ".github/scripts/issue-triage*.cjs" - - ".github/scripts/copilot-workflows.test.cjs" - - ".github/scripts/install-copilot-cli.sh" - - ".github/scripts/run-copilot-inference*.cjs" - - ".github/scripts/parse-issue-translation-response.cjs" - - ".github/scripts/parse-issue-translation-response.test.cjs" - - ".github/workflows/enforce-issue-quality.yml" - - ".github/workflows/enforce-pr-target.yml" - - ".github/workflows/pr-labeler.yml" - - ".github/workflows/issue-triage.yml" - - ".github/workflows/issue-quality-tests.yml" - - ".github/workflows/pr-hygiene.yml" permissions: contents: read diff --git a/.github/workflows/k3s-image.yml b/.github/workflows/k3s-image.yml new file mode 100644 index 0000000000..fbfa11a3af --- /dev/null +++ b/.github/workflows/k3s-image.yml @@ -0,0 +1,74 @@ +name: k3s hub image + +# Builds the hub image that gujoai k3s-infra runs (live/pve-k3s-svc/opencodex) from main of +# dalsoop/opencodex and from the hub version tags (hub/-), and pushes it to GHCR. +# The image tag is -k3s-. One commit gets one +# image: when that tag already exists (main was built before the version tag on the same commit was +# pushed), the job reports the existing digest instead of building again. k3s-infra pins the image by +# the digest printed in the job summary. + +on: + push: + branches: [main] + tags: ["hub/*"] + workflow_dispatch: + +permissions: + contents: read + packages: write + +concurrency: + # Keyed on the commit, so a main push and a tag push of the same commit run one after the other. + group: k3s-image-${{ github.sha }} + cancel-in-progress: false + +jobs: + image: + if: github.repository == 'dalsoop/opencodex' + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + - uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 + - uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Tags + id: tags + run: | + version=$(jq -r .version package.json) + short=${GITHUB_SHA::12} + tag="ghcr.io/dalsoop/opencodex:${version}-k3s-${short}" + echo "tags=${tag}" >> "$GITHUB_OUTPUT" + if digest=$(docker buildx imagetools inspect "$tag" --format '{{json .Manifest}}' 2>/dev/null | jq -r .digest) && [ -n "$digest" ] && [ "$digest" != null ]; then + echo "existing=${digest}" >> "$GITHUB_OUTPUT" + echo "${tag} already exists (${digest}); not building again" + fi + - id: build + if: steps.tags.outputs.existing == '' + uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 + with: + context: . + platforms: linux/amd64 + push: true + provenance: false + tags: ${{ steps.tags.outputs.tags }} + labels: | + org.opencontainers.image.source=https://github.com/dalsoop/opencodex + org.opencontainers.image.revision=${{ github.sha }} + - name: Summary + env: + IMAGE: ${{ steps.tags.outputs.tags }} + DIGEST: ${{ steps.build.outputs.digest || steps.tags.outputs.existing }} + REF: ${{ github.ref }} + run: | + { + echo "ref: ${REF}" + echo "image: ${IMAGE}" + echo "digest: ${DIGEST}" + } >> "$GITHUB_STEP_SUMMARY" + echo "image ${IMAGE}@${DIGEST}" diff --git a/.github/workflows/personal-ci.yml b/.github/workflows/personal-ci.yml deleted file mode 100644 index d767b0cf14..0000000000 --- a/.github/workflows/personal-ci.yml +++ /dev/null @@ -1,56 +0,0 @@ -name: Personal repository CI - -on: - push: - branches: [main, personal/main-integration] - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: personal-ci-${{ github.ref }} - cancel-in-progress: true - -jobs: - verify: - if: github.repository == 'dalsoop/opencodex' - runs-on: ubuntu-latest - timeout-minutes: 45 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4] - steps: - - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 - with: - persist-credentials: false - fetch-tags: true - - uses: ./.github/actions/setup-project-bun - with: - role: test-runner - - run: bun install --frozen-lockfile - - run: bun run typecheck - - name: Typecheck personal installer - run: bun x tsc --ignoreConfig --noEmit --target esnext --module esnext --moduleResolution bundler --skipLibCheck --types bun scripts/personal-install.ts - - run: bun run structure:check - - run: bun run privacy:scan - - run: bun run build:gui - - name: Full suite in isolated batches - env: - TEST_SHARD: ${{ matrix.shard }}/4 - BUN_TEST_FILE_SCOPE: all - run: bash scripts/ci/run-bun-test-batches.sh "$TEST_SHARD" - docs: - if: github.repository == 'dalsoop/opencodex' - runs-on: ubuntu-latest - timeout-minutes: 15 - steps: - - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 - with: - persist-credentials: false - - uses: ./.github/actions/setup-project-bun - - run: bun install --frozen-lockfile - working-directory: docs-site - - run: bun run build - working-directory: docs-site diff --git a/.github/workflows/pr-hygiene.yml b/.github/workflows/pr-hygiene.yml index b60943b93a..73e7bb72bf 100644 --- a/.github/workflows/pr-hygiene.yml +++ b/.github/workflows/pr-hygiene.yml @@ -41,12 +41,11 @@ jobs: # PR's head, so `base.sha` let an unpromoted commit choose which code # runs with this job's issues/pull-requests write token. # - # The branch is chosen, not fixed: `pull_request_target` loads this - # workflow from the default branch, so a `main`-targeting PR must - # take its scripts from `main` too, or the gate runs a `main` - # workflow against `dev` scripts. Everything else, including stacked - # bases, resolves to `dev`, the single integration line. - ref: ${{ github.event.pull_request.base.ref == 'main' && 'main' || 'dev' }} + # `pull_request_target` loads this workflow from the default branch, + # and `dev` is the single integration line. A fixed `dev` keeps the + # scripts, workflow definition, and stacked children on one trusted + # revision. + ref: dev persist-credentials: false sparse-checkout: .github/scripts @@ -57,7 +56,12 @@ jobs: const path = require("node:path"); const { collectDeterministicHygieneFailures, + countHeadRewrites, + formatApprovalRecord, HYGIENE_FAILURE_HINTS, + needsHeadRewriteCount, + parseApprovalRecord, + reconcileHeadBoundApprovals, } = require( path.join(process.cwd(), ".github", "scripts", "pr-hygiene.cjs"), ); @@ -68,8 +72,11 @@ jobs: path.join(process.cwd(), ".github", "scripts", "pr-referenced-authors.cjs"), ); const { - GATE_MARKER, HYGIENE_MARKER, + authoritativeHygieneSection, + escapeControlCharacters, + isGateComment, + isStandaloneHygieneComment, withHygieneSection } = require( path.join(process.cwd(), ".github", "scripts", "pr-quality-messages.cjs"), @@ -104,33 +111,79 @@ jobs: } for (const name of Object.keys(labelDefinitions)) await ensureLabel(name); + // Counts head rewrites (force pushes, restored branches); null when + // the history cannot be read, which confirms no approval. + async function readHeadRewrites() { + try { + return countHeadRewrites( + await github.paginate(github.rest.issues.listEvents, { + owner, repo, issue_number: pull_number, per_page: 100, + }), + ); + } catch (error) { + core.warning(`Could not read head rewrite history: ${error.message}`); + return null; + } + } + // Read before the snapshot so the published record never counts a + // rewrite that happened after the head it names. + const headRewritesBefore = await readHeadRewrites(); const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number }); const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number, per_page: 100, }); + // The file list must belong to the head the approvals are judged + // against; if the head moved while listing, none is confirmed. + const { data: prAfterFiles } = await github.rest.pulls.get({ owner, repo, pull_number }); + const filesAtHead = prAfterFiles.head?.sha === pr.head.sha; const labels = new Set(pr.labels.map((label) => label.name)); + const comments = await github.paginate(github.rest.issues.listComments, { + owner, repo, issue_number: pull_number, per_page: 100, + }); // Exception approvals are head-specific: a new commit invalidates // them, so a contributor cannot obtain one narrow exception and - // then push unreviewed violations under the same label. - if (context.payload.action === "synchronize") { - for (const name of [ - "test-exception-approved", - "suppression-approved", - "generated-change-approved", - "dependency-change-approved", - "attribution-approved", - ]) { - if (labels.has(name)) { - await github.rest.issues.removeLabel({ - owner, repo, issue_number: pull_number, name, - }); - labels.delete(name); - } + // then push unreviewed violations under the same label. This is + // decided on every run from the head this workflow last recorded, + // not from the triggering action: a queued synchronize run can be + // replaced by a later event before it executes. + const approvalInput = { + labels: [...labels], + headSha: filesAtHead ? pr.head.sha : null, + record: parseApprovalRecord(authoritativeHygieneSection(comments)), + eventAction: context.payload.action, + }; + const headRewriteCount = needsHeadRewriteCount(approvalInput) + ? await readHeadRewrites() + : null; + const { stale: staleApprovals } = reconcileHeadBoundApprovals({ + ...approvalInput, + headRewriteCount, + }); + for (const name of staleApprovals) { + try { + await github.rest.issues.removeLabel({ + owner, repo, issue_number: pull_number, name, + }); + } catch (error) { + if (error.status !== 404) throw error; } + labels.delete(name); } + // Written last in the hygiene section on every outcome; the next + // run of this workflow and the PR gate both read it. + const approvalLines = [ + ...(staleApprovals.length === 0 + ? [] + : [ + "", + `ℹ️ Removed ${staleApprovals.map((name) => "\x60" + name + "\x60").join(", ")}: these approvals could not be confirmed for this head (\x60${pr.head.sha.slice(0, 7)}\x60). A maintainer can re-apply them after reviewing it.`, + ]), + "", + formatApprovalRecord({ head: pr.head.sha, headRewrites: headRewritesBefore }), + ]; // Sponsorship is head-independent: it is about which surfaces the // change touches, not about the state of a particular revision, so - // it is NOT cleared by the synchronize sweep above. + // it is not head-bound. // author_association is not enough: a read/triage collaborator can // be COLLABORATOR without write access. Match the PR quality gate. let authorPermission = null; @@ -188,17 +241,18 @@ jobs: } async function upsert(body) { - const comments = await github.paginate(github.rest.issues.listComments, { - owner, repo, issue_number: pull_number, per_page: 100, - }); // The single consolidated bot comment is the one the PR gate // owns (GATE_MARKER). Write the hygiene status into that same // comment so there is one editable message, not two. Fall back // to a standalone hygiene comment only when the gate has not - // posted yet (the next gate run absorbs it). - const gateComment = comments.find( - (comment) => comment.user?.login === "github-actions[bot]" && comment.body?.includes(GATE_MARKER), - ); + // posted yet; the next hygiene run writes into the gate comment. + // The comment list was read once above, before the approval + // check; both workflows share one concurrency group, so no gate + // write lands in between. + // Classified by the marker each body starts with, the same rule + // the approval-record reader uses: echoed paths can contain a + // marker string but never start the comment. + const gateComment = comments.find(isGateComment); if (gateComment) { // The hygiene block already carries the marker; strip the // standalone body's own marker line before merging. @@ -210,9 +264,7 @@ jobs: await github.rest.issues.updateComment({ owner, repo, comment_id: gateComment.id, body: merged }); return; } - const existingHygiene = comments.find( - (comment) => comment.user?.login === "github-actions[bot]" && comment.body?.includes(marker), - ); + const existingHygiene = comments.find(isStandaloneHygieneComment); if (existingHygiene) { await github.rest.issues.updateComment({ owner, repo, comment_id: existingHygiene.id, body }); } else { @@ -222,17 +274,17 @@ jobs: if (failures.length === 0) { await setBlocked(false); - await upsert(`${marker}\n\n✅ **Deterministic PR hygiene checks passed.**`); + await upsert([marker, "", "✅ **Deterministic PR hygiene checks passed.**", ...approvalLines].join("\n")); return; } const lines = failures.map((failure) => { const paths = failure.paths?.length - ? ` Paths: ${failure.paths.map((p) => `\`${p}\``).join(", ")}.` + ? ` Paths: ${failure.paths.map((p) => `\`${escapeControlCharacters(p)}\``).join(", ")}.` : ""; return `- **${failure.code}** — ${HYGIENE_FAILURE_HINTS[failure.code] ?? failure.code}${paths}`; }); await setBlocked(true); - await upsert([marker, "", "⚠️ **Deterministic hygiene checks failed.**", "", ...lines].join("\n")); + await upsert([marker, "", "⚠️ **Deterministic hygiene checks failed.**", "", ...lines, ...approvalLines].join("\n")); core.setFailed(`PR hygiene failed: ${failures.map((f) => f.code).join(", ")}`); diff --git a/.github/workflows/pr-labeler.yml b/.github/workflows/pr-labeler.yml index 309fd40b8f..f7c2b6fa63 100644 --- a/.github/workflows/pr-labeler.yml +++ b/.github/workflows/pr-labeler.yml @@ -1,9 +1,8 @@ name: PR Labeler # pull_request_target always loads this workflow from the repository DEFAULT -# branch (currently `main`), not from `dev`. Landing here on `dev` alone does -# not change live labeler behavior until the change is also on that default -# branch — same promotion model as enforce-issue-quality.yml. +# branch, which is `dev`. A change lands on the live labeler as soon as it is on +# `dev` — same model as enforce-issue-quality.yml. on: pull_request_target: # labeled/unlabeled let a human type-label change enqueue a fresher run in the diff --git a/.github/workflows/react-doctor.yml b/.github/workflows/react-doctor.yml index d8ac13ab36..2efa81541c 100644 --- a/.github/workflows/react-doctor.yml +++ b/.github/workflows/react-doctor.yml @@ -14,11 +14,15 @@ name: React Doctor on: # Scans the PR's changed files relative to the merge base of the target branch. + # The scan reads only gui/ (`directory: gui` below), so a pull request that + # changes nothing there has nothing to scan: it used to start a full-history + # checkout and an npm install on every PR for an empty changed-file list. No + # branch rule requires this check, so a PR it skips is not left waiting on it. pull_request: types: [opened, synchronize, reopened, ready_for_review] - # Scans `main` on every push to track the health-score trend. - push: - branches: ["main"] + paths: + - "gui/**" + - ".github/workflows/react-doctor.yml" permissions: contents: read @@ -27,8 +31,8 @@ permissions: # and the CLI exits 1 on ENOENT even for fork PRs. pull-requests: read -# Cancels any in-flight scan for the same PR (or branch, on push) the moment a -# new commit arrives, so only the latest run remains. +# Cancels any in-flight scan for the same PR the moment a new commit arrives, +# so only the latest run remains. concurrency: group: react-doctor-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 152d4a8ada..6cb29b6a76 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,15 +1,12 @@ name: Release -# Publish opencodex to npm — jawcode-style: triggered from the Actions tab with an explicit -# version, dist-tag, and a dry-run-first default. Bump package.json on main BEFORE dispatching -# (or use `bun run release `, which does the bump+commit+push+dispatch for you); the -# workflow verifies the version matches before publishing. +# Select a tested dev source with the workflow revision pinned independently from that source. on: workflow_dispatch: inputs: version: - description: "Version to publish — must equal package.json (e.g. 0.1.0)" - required: true + description: "Optional expected derived version; required original version when resuming" + required: false type: string tag: description: "npm dist-tag" @@ -25,13 +22,13 @@ on: type: boolean default: true resume-after-npm-publish: - description: "Operator attestation: a previous run of this workflow acknowledged npm publication for this exact commit; skip npm publish and complete the GitHub side" + description: "Attest npm publication was acknowledged for the exact supplied source and version; skip npm publish" required: false type: boolean default: false expected-sha: - description: "Immutable release commit this dispatch must publish (fail if the branch moved)" - required: true + description: "Optional exact full source SHA; it must have qualifying dev CI evidence" + required: false type: string permissions: {} @@ -45,39 +42,121 @@ jobs: runs-on: ubuntu-latest permissions: contents: read + actions: read + outputs: + source_sha: ${{ steps.source.outputs.source_sha }} + workflow_sha: ${{ steps.source.outputs.workflow_sha }} + version: ${{ steps.version.outputs.version }} steps: - - name: Checkout trusted dispatch guard + - name: Checkout trusted workflow revision uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: - ref: ${{ github.event.repository.default_branch }} + ref: ${{ github.sha }} persist-credentials: false - path: trusted-dispatch + fetch-depth: 0 - - name: Validate release dispatch + - name: Resolve eligible source + id: source env: - EXPECTED_SHA: ${{ inputs.expected-sha }} + GH_TOKEN: ${{ github.token }} + REQUESTED_SHA: ${{ inputs.expected-sha }} + REQUESTED_VERSION: ${{ inputs.version }} + RESUME: ${{ inputs.resume-after-npm-publish }} + DRY_RUN: ${{ inputs.dry-run }} run: | + set -euo pipefail + test "$GITHUB_EVENT_NAME" = workflow_dispatch && test "$GITHUB_REF" = refs/heads/dev || { + echo '::error::Release workflow must be dispatched from trusted dev.'; exit 1; + } node - <<'NODE' - const { validateReleaseDispatch } = require( - "./trusted-dispatch/.github/scripts/release-dispatch-guard.cjs", - ); - - const failure = validateReleaseDispatch({ - eventName: process.env.GITHUB_EVENT_NAME, - ref: process.env.GITHUB_REF, - expectedSha: process.env.EXPECTED_SHA, - actualSha: process.env.GITHUB_SHA, - }); - - if (failure) { - console.error(`::error::${failure}`); - process.exit(1); + const { validateReleaseDispatch } = require('./.github/scripts/release-dispatch-guard.cjs'); + const failure = validateReleaseDispatch({ eventName: process.env.GITHUB_EVENT_NAME, + ref: process.env.GITHUB_REF, sourceSha: process.env.REQUESTED_SHA, workflowSha: process.env.GITHUB_SHA }); + if (failure) throw new Error(failure); + NODE + if [ "$RESUME" = true ]; then + if [ -z "$REQUESTED_SHA" ] || [ -z "$REQUESTED_VERSION" ] || [ "$DRY_RUN" != false ]; then + echo '::error::Resume requires the original source SHA and version and cannot be a dry run.'; exit 1 + fi + fi + if [ -n "$REQUESTED_SHA" ]; then + result="$(node .github/scripts/release-evidence.cjs resolve "$REQUESTED_SHA")" + else + result="$(node .github/scripts/release-evidence.cjs resolve)" + fi + RESULT="$result" node - <<'NODE' + const fs = require('node:fs'); + const result = JSON.parse(process.env.RESULT); + if (!/^[0-9a-f]{40}$/.test(result.sourceSha) || !Number.isSafeInteger(result.ciRunId) || result.ciRunId <= 0 || + (process.env.REQUESTED_SHA && result.sourceSha !== process.env.REQUESTED_SHA)) { + throw new Error('Invalid source evidence'); } + fs.appendFileSync(process.env.GITHUB_OUTPUT, `source_sha=${result.sourceSha}\nworkflow_sha=${process.env.GITHUB_SHA}\n`); NODE + - name: Checkout selected source for version resolution + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + ref: ${{ steps.source.outputs.source_sha }} + path: candidate + persist-credentials: false + + - name: Setup project Bun + uses: ./.github/actions/setup-project-bun + + - name: Resolve release version + id: version + env: + CHANNEL: ${{ inputs.tag }} + EXPECTED_VERSION: ${{ inputs.version }} + RESUME: ${{ inputs.resume-after-npm-publish }} + run: | + set -euo pipefail + bun scripts/release-version-sources.ts check --root candidate + if [ "$RESUME" = true ]; then + # JavaScript template literals are evaluated by Bun, not the shell. + # shellcheck disable=SC2016 + bun -e ' + import { parseVersion } from "./scripts/version-line.ts"; + import { appendFileSync } from "node:fs"; + const value = process.env.EXPECTED_VERSION ?? "", channel = process.env.CHANNEL; + const parsed = parseVersion(value); + if (!/^\d+\.\d+\.\d+(?:-preview\.\d{8}(?:\.\d+)?)?$/.test(value) || !parsed || + !((channel === "latest" && parsed.prerelease === null) || + (channel === "preview" && parsed.prerelease?.[0] === "preview"))) throw Error("invalid original release version or channel"); + appendFileSync(process.env.GITHUB_OUTPUT, `version=${value}\n`); + ' + exit 0 + fi + npm view "$(node -p "require('./package.json').name")" versions --json > "$RUNNER_TEMP/release-npm-versions.json" + git tag --list 'v[0-9]*' > "$RUNNER_TEMP/release-tags.txt" + # JavaScript template literals are evaluated by Bun, not the shell. + # shellcheck disable=SC2016 + bun -e ' + import { devReleaseVersion, parseVersion } from "./scripts/version-line.ts"; + import { readFileSync, appendFileSync } from "node:fs"; + const versions = JSON.parse(readFileSync(`${process.env.RUNNER_TEMP}/release-npm-versions.json`, "utf8")); + if (!Array.isArray(versions) || versions.some(v => typeof v !== "string")) throw new Error("invalid npm versions"); + const tags = readFileSync(`${process.env.RUNNER_TEMP}/release-tags.txt`, "utf8").trim().split("\n").filter(Boolean).map(v => v.slice(1)); + const all = [...new Set([...versions, ...tags])]; + const stableTags = [], previewTags = []; + for (const version of all) { + const parsed = parseVersion(version); + if (!parsed) throw new Error(`invalid published version: ${version}`); + (parsed.prerelease === null ? stableTags : previewTags).push(version); + } + const channel = process.env.CHANNEL; + if (channel !== "latest" && channel !== "preview") throw new Error("invalid release channel"); + const base = JSON.parse(readFileSync("candidate/package.json", "utf8")).version; + const stamp = new Date().toISOString().slice(0, 10).replaceAll("-", ""); + const version = devReleaseVersion({ base, stableTags, previewTags, channel, stamp }); + if (process.env.EXPECTED_VERSION && process.env.EXPECTED_VERSION !== version) throw new Error("expected version differs from derived version"); + appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\n`); + ' + # Every publication precondition the dispatch can already decide, checked before any runner # starts packaging: channel and dist-tag, every version source, the tag, the GitHub release, - # npm, the global tag ordering and the dev pre-move (scripts/ci/release-preflight.sh). + # npm and the global tag ordering (scripts/ci/release-preflight.sh). # # Run 35783865160 packaged 2.62.0 for nineteen minutes and then failed the ordering gate in # `publish` on v2.63.0-preview.20260923. That tag already existed when the run's first job @@ -96,23 +175,37 @@ jobs: timeout-minutes: 5 permissions: contents: read + env: + SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }} + WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} steps: - name: Checkout uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: + ref: ${{ needs.validate-dispatch.outputs.workflow_sha }} persist-credentials: false + fetch-depth: 0 fetch-tags: true - name: Setup project Bun uses: ./.github/actions/setup-project-bun + - name: Stamp preflight version + run: | + set -euo pipefail + test -n "$SOURCE_SHA" && test -n "$WORKFLOW_SHA" && test -n "$RELEASE_VERSION" + test "$(git rev-parse HEAD)" = "$WORKFLOW_SHA" + bun scripts/release-version-sources.ts sync "$RELEASE_VERSION" + bun scripts/release-version-sources.ts check "$RELEASE_VERSION" + - name: Fetch the dev line run: git fetch --no-tags --depth=1 origin +refs/heads/dev:refs/remotes/origin/dev - name: Refuse a release that cannot publish env: GH_TOKEN: ${{ github.token }} - RELEASE_VERSION: ${{ inputs.version }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} NPM_DIST_TAG: ${{ inputs.tag }} DRY_RUN: ${{ inputs.dry-run }} RESUME: ${{ inputs.resume-after-npm-publish }} @@ -120,6 +213,7 @@ jobs: package-standalone: needs: [validate-dispatch, preflight] + if: ${{ github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/dev' }} strategy: fail-fast: false matrix: @@ -156,14 +250,35 @@ jobs: # actions: read lets the SignPath action read this job and download the unsigned artifact. actions: read contents: read + env: + SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }} + WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} steps: - name: Checkout uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: + ref: ${{ needs.validate-dispatch.outputs.source_sha }} + persist-credentials: false + + - name: Checkout trusted release policy + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + ref: ${{ needs.validate-dispatch.outputs.workflow_sha }} + path: trusted-release-policy persist-credentials: false - name: Setup project Bun - uses: ./.github/actions/setup-project-bun + uses: ./trusted-release-policy/.github/actions/setup-project-bun + + - name: Stamp and verify release version + shell: bash + run: | + set -euo pipefail + test -n "$SOURCE_SHA" && test -n "$WORKFLOW_SHA" && test -n "$RELEASE_VERSION" + test "$(git rev-parse HEAD)" = "$SOURCE_SHA" + bun trusted-release-policy/scripts/release-version-sources.ts sync "$RELEASE_VERSION" --root . + bun trusted-release-policy/scripts/release-version-sources.ts check "$RELEASE_VERSION" --root . # Windows Authenticode signing through SignPath Foundation (#7207). Decided before the build, so # a broken SignPath configuration fails in seconds instead of after the build. The rules @@ -201,7 +316,10 @@ jobs: OPENCODEX_HOME="$RUNNER_TEMP/ocx-home" "$binary" start --port 10177 >"$RUNNER_TEMP/ocx.log" 2>&1 & pid=$! trap 'kill "$pid" 2>/dev/null || true' EXIT - for _ in $(seq 1 30); do curl -fsS http://127.0.0.1:10177/healthz && break || sleep 1; done + for _ in $(seq 1 30); do + if curl -fsS http://127.0.0.1:10177/healthz; then break; fi + sleep 1 + done curl -fsS http://127.0.0.1:10177/healthz test "$(curl -sS -o /dev/null -w '%{http_code}' http://127.0.0.1:10177/)" = 200 @@ -276,12 +394,14 @@ jobs: - name: Archive standalone release shell: bash env: - RELEASE_VERSION: ${{ inputs.version }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} STANDALONE_TARGET: ${{ matrix.target }} run: | set -euo pipefail cd "dist/standalone/$STANDALONE_TARGET" if [[ "$RUNNER_OS" == "Windows" ]]; then + # Variables in this literal belong to PowerShell. + # shellcheck disable=SC2016 powershell -NoProfile -Command 'Compress-Archive -Path ocx.exe,gui,keyring -DestinationPath ("../../ocx-{0}-{1}.zip" -f $env:RELEASE_VERSION,$env:STANDALONE_TARGET) -Force' else tar -czf "../../ocx-${RELEASE_VERSION}-${STANDALONE_TARGET}.tar.gz" ocx gui keyring @@ -308,6 +428,7 @@ jobs: package-desktop: needs: [validate-dispatch, preflight] + if: ${{ github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/dev' }} strategy: fail-fast: false matrix: @@ -341,6 +462,9 @@ jobs: actions: read contents: read env: + SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }} + WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} # Whether this run holds the Developer ID material at all. A run without it still builds # locally useful bundles; a run with it must not silently downgrade any part of the app. DESKTOP_SIGNING_CONFIGURED: ${{ secrets.APPLE_CERTIFICATE != '' }} @@ -348,10 +472,27 @@ jobs: - name: Checkout uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: + ref: ${{ needs.validate-dispatch.outputs.source_sha }} + persist-credentials: false + + - name: Checkout trusted release policy + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + ref: ${{ needs.validate-dispatch.outputs.workflow_sha }} + path: trusted-release-policy persist-credentials: false - name: Setup project Bun - uses: ./.github/actions/setup-project-bun + uses: ./trusted-release-policy/.github/actions/setup-project-bun + + - name: Stamp and verify release version + shell: bash + run: | + set -euo pipefail + test -n "$SOURCE_SHA" && test -n "$WORKFLOW_SHA" && test -n "$RELEASE_VERSION" + test "$(git rev-parse HEAD)" = "$SOURCE_SHA" + bun trusted-release-policy/scripts/release-version-sources.ts sync "$RELEASE_VERSION" --root . + bun trusted-release-policy/scripts/release-version-sources.ts check "$RELEASE_VERSION" --root . # Windows Authenticode signing through SignPath Foundation (#7207). Decided before the build, so # a broken SignPath configuration fails in seconds instead of after the build. The rules @@ -379,8 +520,8 @@ jobs: - name: Verify every version source matches the release shell: bash env: - RELEASE_VERSION: ${{ inputs.version }} - run: bun scripts/release-version-sources.ts check "$RELEASE_VERSION" + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} + run: bun trusted-release-policy/scripts/release-version-sources.ts check "$RELEASE_VERSION" --root . - name: Install project dependencies run: bun install --frozen-lockfile --os=${{ matrix.dependency_os }} --cpu=${{ matrix.dependency_cpu }} @@ -548,7 +689,7 @@ jobs: if: runner.os == 'Windows' shell: bash env: - RELEASE_VERSION: ${{ inputs.version }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} run: bun desktop/scripts/windows-installer-config.ts "$RELEASE_VERSION" "$RUNNER_TEMP/opencodex-msi.json" - name: Preserve the compiled Linux sidecar @@ -706,7 +847,7 @@ jobs: - name: Rename release assets shell: bash env: - RELEASE_VERSION: ${{ inputs.version }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} DESKTOP_TARGET: ${{ matrix.target }} run: | args=( \ @@ -785,6 +926,227 @@ jobs: security delete-keychain "${OPENCODEX_SIGNING_KEYCHAIN}" fi + # Candidate code and npm lifecycle scripts run only in this read-only job. + package-npm: + needs: [validate-dispatch, preflight] + runs-on: ubuntu-latest + timeout-minutes: 25 + permissions: + contents: read + outputs: + artifact_id: ${{ steps.upload.outputs.artifact-id }} + env: + SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }} + WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} + steps: + - name: Checkout selected source + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + ref: ${{ needs.validate-dispatch.outputs.source_sha }} + persist-credentials: false + + - name: Checkout trusted release policy + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + ref: ${{ needs.validate-dispatch.outputs.workflow_sha }} + path: trusted-release-policy + persist-credentials: false + + - name: Setup project Bun + uses: ./trusted-release-policy/.github/actions/setup-project-bun + + - name: Stamp and verify release version + run: | + set -euo pipefail + test -n "$SOURCE_SHA" && test -n "$WORKFLOW_SHA" && test -n "$RELEASE_VERSION" + test "$(git rev-parse HEAD)" = "$SOURCE_SHA" + bun trusted-release-policy/scripts/release-version-sources.ts sync "$RELEASE_VERSION" --root . + bun trusted-release-policy/scripts/release-version-sources.ts check "$RELEASE_VERSION" --root . + + - name: Install dependencies + run: bun install --frozen-lockfile + + - name: Build npm package + run: | + set -euo pipefail + npm run prepublishOnly + npm run prepack + # All candidate lifecycle scripts have finished. Bind the packed manifest + # to the selected commit; npm pack below runs with scripts disabled. + node - <<'NODE' + const fs = require('node:fs'), { spawnSync } = require('node:child_process'); + const source = process.env.SOURCE_SHA; + if (!/^[0-9a-f]{40}$/.test(source || '')) throw Error('invalid source SHA'); + const git = spawnSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }); + if (git.status !== 0 || git.stdout.trim() !== source) throw Error('npm checkout source mismatch'); + const stat = fs.lstatSync('package.json'); + if (!stat.isFile() || stat.isSymbolicLink()) throw Error('invalid npm manifest'); + const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')); + if (pkg.version !== process.env.RELEASE_VERSION) throw Error('npm manifest version mismatch'); + pkg.gitHead = source; + fs.writeFileSync('package.json.release-tmp', JSON.stringify(pkg, null, 2) + '\n', { flag: 'wx' }); + fs.renameSync('package.json.release-tmp', 'package.json'); + NODE + mkdir -p "$RUNNER_TEMP/npm-pack" dist/npm + npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP/npm-pack" + shopt -s nullglob + packages=("$RUNNER_TEMP"/npm-pack/*.tgz) + test "${#packages[@]}" -eq 1 + cp -- "${packages[0]}" dist/npm/package.tgz + + - name: Upload npm package + id: upload + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: npm-package-unverified + path: dist/npm/package.tgz + if-no-files-found: error + retention-days: 7 + + # A fresh runner computes the receipt; candidate code cannot execute in this job. + verify-npm: + needs: [validate-dispatch, package-npm] + runs-on: ubuntu-latest + permissions: + contents: read + actions: read + outputs: + artifact_id: ${{ steps.upload.outputs.artifact-id }} + sha256: ${{ steps.receipt.outputs.sha256 }} + env: + SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }} + WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} + steps: + - name: Checkout trusted workflow revision + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + ref: ${{ needs.validate-dispatch.outputs.workflow_sha }} + persist-credentials: false + fetch-depth: 0 + + - name: Resolve trusted Bun version + id: bun-version + run: | + # JavaScript template literals are evaluated by Node, not the shell. + # shellcheck disable=SC2016 + node -e 'const v = require("./package.json").dependencies.bun; if (!/^\d+\.\d+\.\d+$/.test(v)) throw Error("invalid Bun pin"); require("node:fs").appendFileSync(process.env.GITHUB_OUTPUT, `version=${v}\n`);' + + - name: Setup trusted Bun + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: ${{ steps.bun-version.outputs.version }} + + - name: Download npm package by immutable artifact ID + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.package-npm.outputs.artifact_id }} + path: npm-artifact + + - name: Recheck source CI and service evidence + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + node .github/scripts/release-evidence.cjs check "$SOURCE_SHA" + baseline_tag="$(git tag --merged "$SOURCE_SHA" --list 'v[0-9]*' | bun -e ' + import { parseVersion, compareVersions } from "./scripts/version-line.ts"; + const tags = (await Bun.stdin.text()).trim().split("\n").filter(Boolean); + const versions = tags.map(tag => ({ tag, version: tag.slice(1) })); + if (versions.some(item => !parseVersion(item.version))) throw new Error("invalid release tag"); + const eligible = versions.filter(item => compareVersions(item.version, process.env.RELEASE_VERSION) < 0); + eligible.sort((a, b) => compareVersions(a.version, b.version)); + console.log(eligible.at(-1)?.tag ?? ""); + ')" + baseline=--initial + if [ -n "$baseline_tag" ]; then + draft="$(gh release view "$baseline_tag" --json isDraft --jq .isDraft)" + test "$draft" = false || { echo '::error::Service baseline is not a published release.'; exit 1; } + baseline="$(git rev-parse "refs/tags/${baseline_tag}^{commit}")" + fi + range="$(node .github/scripts/release-evidence.cjs service-range "$SOURCE_SHA" "$baseline")" + required="$(RANGE="$range" node -e 'const x = JSON.parse(process.env.RANGE); if (typeof x.required !== "boolean") throw Error("invalid service range"); process.stdout.write(String(x.required));')" + if [ "$required" = true ]; then + node .github/scripts/release-evidence.cjs service "$SOURCE_SHA" || { + echo "::error::Dispatch service-lifecycle.yml from dev for source ${SOURCE_SHA} and wait for all platforms."; exit 1; + } + fi + + - name: Require reconciled publication history + if: ${{ inputs.resume-after-npm-publish != true }} + env: + GH_TOKEN: ${{ github.token }} + NPM_DIST_TAG: ${{ inputs.tag }} + run: | + set -euo pipefail + if ! [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] || [ -z "$RELEASE_VERSION" ]; then + echo '::error::Invalid release identity for history reconciliation.'; exit 1 + fi + case "$NPM_DIST_TAG" in + latest) channel=stable ;; + preview) channel=preview ;; + *) echo '::error::Invalid release channel.'; exit 1 ;; + esac + node .github/scripts/release-history.cjs check "$SOURCE_SHA" "$RELEASE_VERSION" "$channel" + + - name: Verify resume registry identity + id: resume-identity + if: ${{ inputs.resume-after-npm-publish == true }} + run: | + set -euo pipefail + pkg_name="$(node -p "require('./package.json').name")" + registry_version="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" version --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000)" || { + echo '::error::Cannot read the exact npm version; resume refused.'; exit 1; + } + REGISTRY_VERSION="$registry_version" node - <<'NODE' + const value = JSON.parse(process.env.REGISTRY_VERSION); + if (typeof value !== 'string' || value !== process.env.RELEASE_VERSION) throw Error('npm version does not match original release'); + NODE + registry_head="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" gitHead --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000)" || { + echo '::error::Cannot read npm gitHead; resume refused.'; exit 1; + } + bun scripts/verify-release-resume.ts "$SOURCE_SHA" "$registry_head" + echo "resume_sha=$SOURCE_SHA" >> "$GITHUB_OUTPUT" + + - name: Create verified npm receipt + id: receipt + run: | + set -euo pipefail + node - <<'NODE' + const fs = require('node:fs'); + const crypto = require('node:crypto'); + const { spawnSync } = require('node:child_process'); + const archive = 'npm-artifact/package.tgz'; + const sha = /^[0-9a-f]{40}$/; + if (!sha.test(process.env.SOURCE_SHA) || !sha.test(process.env.WORKFLOW_SHA) || + !/^\d+$/.test(process.env.GITHUB_RUN_ID) || !/^\d+$/.test(process.env.GITHUB_RUN_ATTEMPT) || + !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(process.env.RELEASE_VERSION)) throw new Error('invalid receipt identity'); + const stat = fs.lstatSync(archive); + if (!stat.isFile() || stat.isSymbolicLink() || stat.size <= 0 || stat.size > 500 * 1024 * 1024) throw new Error('invalid npm tarball'); + const entries = spawnSync('tar', ['-tzf', archive], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }); + if (entries.status !== 0 || entries.stdout.split('\n').filter(p => p === 'package/package.json').length !== 1) throw new Error('invalid npm manifest entry'); + const manifest = spawnSync('tar', ['-xOzf', archive, 'package/package.json'], { encoding: 'utf8', maxBuffer: 1024 * 1024 }); + if (manifest.status !== 0) throw new Error('cannot read npm manifest'); + const pkg = JSON.parse(manifest.stdout), trusted = JSON.parse(fs.readFileSync('package.json', 'utf8')); + if (pkg.name !== trusted.name || pkg.version !== process.env.RELEASE_VERSION || pkg.gitHead !== process.env.SOURCE_SHA) throw new Error('npm package identity or gitHead mismatch'); + const digest = crypto.createHash('sha256').update(fs.readFileSync(archive)).digest('hex'); + const receipt = { sourceSha: process.env.SOURCE_SHA, workflowSha: process.env.WORKFLOW_SHA, + version: process.env.RELEASE_VERSION, runId: process.env.GITHUB_RUN_ID, + attempt: process.env.GITHUB_RUN_ATTEMPT, packageName: pkg.name, gitHead: pkg.gitHead, sha256: digest }; + fs.writeFileSync('npm-artifact/receipt.json', JSON.stringify(receipt) + '\n'); + fs.appendFileSync(process.env.GITHUB_OUTPUT, `sha256=${digest}\n`); + NODE + + - name: Upload verified npm package and receipt + id: upload + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: npm-package-verified + path: npm-artifact/ + if-no-files-found: error + retention-days: 7 + # Pre-publication verification. Everything that will be published is checked # here — expected platform set, every checksum, the updater signatures, and the # manifest parse-back — and publication consumes this result rather than @@ -797,11 +1159,15 @@ jobs: permissions: contents: read env: + SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }} + WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} UPDATER_SIGNING_CONFIGURED: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY != '' }} steps: - - name: Checkout + - name: Checkout trusted workflow revision uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: + ref: ${{ needs.validate-dispatch.outputs.workflow_sha }} persist-credentials: false - name: Setup project Bun @@ -823,23 +1189,49 @@ jobs: - name: Verify release assets env: - RELEASE_VERSION: ${{ inputs.version }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} run: | set -euo pipefail args=( --version "$RELEASE_VERSION" --dir dist/release --repo "$GITHUB_REPOSITORY" - --sha "$GITHUB_SHA" + --sha "$SOURCE_SHA" --receipt-out verification/receipt.json ) - # Signatures are verified whenever they exist; the manifest is only - # generated when this run holds the updater key, exactly as before. + # HEAD release policy requires updater signatures whenever the key is configured. if [ "$UPDATER_SIGNING_CONFIGURED" = "true" ]; then args+=(--manifest-out dist/release/latest.json --require-signatures) fi bun desktop/scripts/verify-release-assets.ts "${args[@]}" + - name: Bind verified asset digests + run: | + set -euo pipefail + node - <<'NODE' + const fs = require('node:fs'), crypto = require('node:crypto'), path = require('node:path'); + (async () => { + const receipt = JSON.parse(fs.readFileSync('verification/receipt.json', 'utf8')); + if (receipt.version !== process.env.RELEASE_VERSION || receipt.sha !== process.env.SOURCE_SHA || receipt.repo !== process.env.GITHUB_REPOSITORY) throw Error('asset verifier identity mismatch'); + const names = fs.readdirSync('dist/release').sort(); + if (!names.length) throw Error('empty verified release'); + const assets = {}; + for (const name of names) { + if (name === '.' || name === '..' || name.includes('/') || name.includes('\\')) throw Error('invalid asset name'); + const file = path.join('dist/release', name), stat = fs.lstatSync(file); + if (!stat.isFile() || stat.isSymbolicLink()) throw Error('asset is not a regular file'); + const hash = crypto.createHash('sha256'); + for await (const chunk of fs.createReadStream(file)) hash.update(chunk); + assets[name] = hash.digest('hex'); + } + receipt.workflowSha = process.env.WORKFLOW_SHA; + receipt.runId = process.env.GITHUB_RUN_ID; + receipt.attempt = process.env.GITHUB_RUN_ATTEMPT; + receipt.assets = assets; + fs.writeFileSync('verification/receipt.json', JSON.stringify(receipt) + '\n'); + })().catch(error => { console.error(error.message); process.exitCode = 1; }); + NODE + - name: Upload verified release bundle uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: @@ -858,15 +1250,20 @@ jobs: attach-release: runs-on: ubuntu-latest - needs: [publish, verify-release] + needs: [validate-dispatch, publish, verify-release] if: ${{ inputs.dry-run != true }} timeout-minutes: 10 permissions: contents: write + env: + SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }} + WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} steps: - name: Checkout uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: + ref: ${{ needs.validate-dispatch.outputs.workflow_sha }} persist-credentials: false - name: Setup project Bun @@ -888,30 +1285,90 @@ jobs: # run's version and commit, or nothing uploads. - name: Require the verification receipt for this commit env: - RELEASE_VERSION: ${{ inputs.version }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} run: | set -euo pipefail - receipt_version="$(bun -e 'console.log(JSON.parse(await Bun.file("verification/receipt.json").text()).version)')" - receipt_sha="$(bun -e 'console.log(JSON.parse(await Bun.file("verification/receipt.json").text()).sha)')" - test "$receipt_version" = "$RELEASE_VERSION" || { - echo "::error::verification receipt names version $receipt_version, not $RELEASE_VERSION" - exit 1 - } - test "$receipt_sha" = "$GITHUB_SHA" || { - echo "::error::verification receipt names commit $receipt_sha, not $GITHUB_SHA" - exit 1 - } + node - <<'NODE' + const fs = require('node:fs'), crypto = require('node:crypto'), path = require('node:path'); + (async () => { + const receipt = JSON.parse(fs.readFileSync('verification/receipt.json', 'utf8')); + if (receipt.version !== process.env.RELEASE_VERSION || receipt.sha !== process.env.SOURCE_SHA || + receipt.repo !== process.env.GITHUB_REPOSITORY || receipt.workflowSha !== process.env.WORKFLOW_SHA || + receipt.runId !== process.env.GITHUB_RUN_ID || !/^[1-9]\d*$/.test(receipt.attempt || '') || + !/^[1-9]\d*$/.test(process.env.GITHUB_RUN_ATTEMPT || '') || + BigInt(receipt.attempt) > BigInt(process.env.GITHUB_RUN_ATTEMPT) || + !receipt.assets || typeof receipt.assets !== 'object' || Array.isArray(receipt.assets)) throw Error('release receipt identity mismatch'); + const names = fs.readdirSync('dist/release').sort(), recorded = Object.keys(receipt.assets).sort(); + if (!names.length || JSON.stringify(names) !== JSON.stringify(recorded)) throw Error('release asset set mismatch'); + for (const name of names) { + if (name === '.' || name === '..' || /[\x00-\x1f\x7f/\\]/.test(name) || !/^[0-9a-f]{64}$/.test(receipt.assets[name])) throw Error('invalid asset receipt'); + const file = path.join('dist/release', name), stat = fs.lstatSync(file); + if (!stat.isFile() || stat.isSymbolicLink()) throw Error('asset is not a regular file'); + const hash = crypto.createHash('sha256'); + for await (const chunk of fs.createReadStream(file)) hash.update(chunk); + if (hash.digest('hex') !== receipt.assets[name]) throw Error(`asset sha256 mismatch: ${name}`); + } + })().catch(error => { console.error(error.message); process.exitCode = 1; }); + NODE + + - name: Check resume assets + if: ${{ inputs.resume-after-npm-publish == true }} + env: + GH_TOKEN: ${{ github.token }} + NPM_DIST_TAG: ${{ inputs.tag }} + run: | + set -euo pipefail + case "$NPM_DIST_TAG" in latest) channel=stable ;; preview) channel=preview ;; *) exit 1 ;; esac + decision="$(node .github/scripts/release-resume.cjs check-assets "$RELEASE_VERSION" "$SOURCE_SHA" "$channel" verification/receipt.json)" + DECISION="$decision" CHANNEL="$channel" node - <<'NODE' + const result = JSON.parse(process.env.DECISION); + if (result.version !== process.env.RELEASE_VERSION || result.sourceSha !== process.env.SOURCE_SHA || + result.channel !== process.env.CHANNEL || result.publishNpm !== false || result.assetsChecked !== true || + !Array.isArray(result.reuseAssets) || !Array.isArray(result.missingAssets)) throw Error('invalid resume asset decision'); + NODE - name: Attach to the release env: GH_TOKEN: ${{ github.token }} # Workflow inputs reach shell code through env, never by interpolation into # run: source. tests/ci-workflows.test.ts enforces this repo-wide. - RELEASE_VERSION: ${{ inputs.version }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} run: | set -euo pipefail release_tag="v${RELEASE_VERSION}" - gh release upload "$release_tag" dist/release/* --clobber + # The preceding receipt check binds this local set to verified bytes. + # Existing assets are reused only when GitHub reports their exact digest. + checker="$RUNNER_TEMP/check-release-assets.cjs" + cat > "$checker" <<'NODE' + const fs = require('node:fs'); + const release = JSON.parse(process.env.RELEASE_INFO); + const receipt = JSON.parse(fs.readFileSync('verification/receipt.json', 'utf8')); + if (typeof release.isDraft !== 'boolean' || !Array.isArray(release.assets) || + !receipt.assets || typeof receipt.assets !== 'object' || Array.isArray(receipt.assets)) throw Error('invalid release or receipt'); + const expected = receipt.assets, names = Object.keys(expected), seen = new Set(); + if (!names.length) throw Error('empty asset receipt'); + for (const name of names) { + if (!name || name === '.' || name === '..' || /[\x00-\x1f\x7f/\\]/.test(name) || !/^[0-9a-f]{64}$/.test(expected[name])) throw Error('invalid asset receipt'); + } + for (const asset of release.assets) { + if (!asset || typeof asset.name !== 'string' || seen.has(asset.name) || !Object.hasOwn(expected, asset.name) || + asset.state !== 'uploaded' || asset.digest !== `sha256:${expected[asset.name]}`) throw Error('existing asset is unexpected, unavailable or has a different digest'); + seen.add(asset.name); + } + const missing = names.filter(name => !seen.has(name)); + if ((!release.isDraft || process.env.CHECK_FINAL === 'true') && missing.length) throw Error('release is missing verified assets'); + if (missing.length) process.stdout.write(missing.join('\0') + '\0'); + NODE + release_info="$(gh release view "$release_tag" --json isDraft,assets)" + RELEASE_INFO="$release_info" CHECK_FINAL=false node "$checker" > "$RUNNER_TEMP/missing-release-assets" + missing=() + while IFS= read -r -d '' name; do missing+=("dist/release/$name"); done < "$RUNNER_TEMP/missing-release-assets" + if [ "${#missing[@]}" -gt 0 ]; then + gh release upload "$release_tag" "${missing[@]}" + fi + # Re-read the entire remote set before publishing the draft. + release_info="$(gh release view "$release_tag" --json isDraft,assets)" + RELEASE_INFO="$release_info" CHECK_FINAL=true node "$checker" > /dev/null # A published release is immutable: GitHub rejects every later asset upload # with HTTP 422, which is why v2.55.0 through v2.60.0 shipped with zero @@ -940,12 +1397,16 @@ jobs: # release is invisible to it and reads as not public, which is the question the row answers. release-outcomes: name: release outcomes - needs: [publish, attach-release] - if: ${{ always() && inputs.dry-run != true }} + needs: [validate-dispatch, publish, attach-release] + if: ${{ always() && needs.validate-dispatch.result == 'success' && inputs.dry-run != true }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: contents: read + env: + SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }} + WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} steps: - name: Checkout uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 @@ -955,7 +1416,7 @@ jobs: - name: Report release outcomes env: GH_TOKEN: ${{ github.token }} - RELEASE_VERSION: ${{ inputs.version }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} NPM_DIST_TAG: ${{ inputs.tag }} NPM_VERSION_STATE: ${{ needs.publish.outputs.npm_version }} NPM_DIST_TAG_STATE: ${{ needs.publish.outputs.npm_dist_tag }} @@ -964,9 +1425,11 @@ jobs: run: bash scripts/ci/release-outcome-report.sh publish: - needs: [validate-dispatch, verify-release] + needs: [validate-dispatch, verify-release, verify-npm] + if: ${{ inputs.dry-run != true }} runs-on: ubuntu-latest - timeout-minutes: 15 + # The two registry waits below can each take about 20 minutes (about 55 minutes worst case with read timeouts). + timeout-minutes: 75 outputs: npm_version: ${{ steps.registry-smoke.outputs.npm_version }} npm_dist_tag: ${{ steps.registry-smoke.outputs.npm_dist_tag }} @@ -975,318 +1438,267 @@ jobs: actions: read pull-requests: read id-token: write + env: + SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }} + WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} + # The ./ prefix is load-bearing: npm reads a bare "owner/repo..." spec as a GitHub shorthand + # and runs git ls-remote instead of publishing the file (run 42763073267). + NPM_TARBALL: ./npm-artifact/package.tgz + EXPECTED_DIGEST: ${{ needs.verify-npm.outputs.sha256 }} steps: - - name: Checkout + - name: Checkout trusted workflow revision uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 with: + ref: ${{ needs.validate-dispatch.outputs.workflow_sha }} fetch-depth: 0 - - name: Verify dispatched SHA - env: - EXPECTED_SHA: ${{ inputs.expected-sha }} + - name: Resolve trusted Bun version + id: bun-version run: | - if [ -z "$EXPECTED_SHA" ]; then - echo "::error::expected-sha is required; refusing to publish without an audited commit" - exit 1 - elif [ "$GITHUB_SHA" != "$EXPECTED_SHA" ]; then - echo "::error::branch moved after the release audit (expected ${EXPECTED_SHA}, got ${GITHUB_SHA}) — refusing to publish an unaudited commit" - exit 1 - fi + # JavaScript template literals are evaluated by Node, not the shell. + # shellcheck disable=SC2016 + node -e 'const v = require("./package.json").dependencies.bun; if (!/^\d+\.\d+\.\d+$/.test(v)) throw Error("invalid Bun pin"); require("node:fs").appendFileSync(process.env.GITHUB_OUTPUT, `version=${v}\n`);' - # opencodex is bun-native (the prepublishOnly audit, GUI build, and typecheck run under bun). - - name: Setup project Bun - uses: ./.github/actions/setup-project-bun + - name: Setup trusted Bun + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: ${{ steps.bun-version.outputs.version }} - # node + npm perform the actual publish. registry-url points npm at the public registry. - name: Setup Node uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 with: node-version: 24 - registry-url: "https://registry.npmjs.org" + registry-url: https://registry.npmjs.org - # Trusted Publishing (OIDC) needs npm >= 11.5.1. Node 24 runners already - # provide a compatible npm; avoid replacing the bundled npm because global - # npm self-updates can lose publish-time dependencies such as sigstore. - - name: Verify npm version - run: | - npm_version="$(npm --version)" - echo "npm=${npm_version}" - # shellcheck disable=SC2016 # the node script deliberately avoids shell expansion - node -e ' - const [major, minor] = process.argv[1].split(".").map(Number); - if (major < 11 || (major === 11 && minor < 5)) { - console.error(`npm ${process.argv[1]} is too old for trusted publishing; need >= 11.5.1`); - process.exit(1); - } - ' "$npm_version" + - name: Download verified npm package by immutable artifact ID + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.verify-npm.outputs.artifact_id }} + path: npm-artifact - - name: Install dependencies - run: bun install --frozen-lockfile + # Fetch the independently verified release receipt before publication, so + # an unavailable handoff cannot strand a newly published npm version. + - name: Download verified release receipt for publication + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: release-verification-receipt + path: verification - - name: Dependency audit (high severity) - run: bun run audit:high + - name: Verify immutable npm receipt + run: | + set -euo pipefail + node - <<'NODE' + const fs = require('node:fs'); + const crypto = require('node:crypto'); + const { spawnSync } = require('node:child_process'); + const archive = process.env.NPM_TARBALL; + const stat = fs.lstatSync(archive); + if (!stat.isFile() || stat.isSymbolicLink() || stat.size <= 0 || stat.size > 500 * 1024 * 1024) throw new Error('invalid npm tarball'); + const receipt = JSON.parse(fs.readFileSync('npm-artifact/receipt.json', 'utf8')); + const sha256 = crypto.createHash('sha256').update(fs.readFileSync(archive)).digest('hex'); + const expectedName = JSON.parse(fs.readFileSync('package.json', 'utf8')).name; + if (!/^[0-9a-f]{64}$/.test(process.env.EXPECTED_DIGEST) || sha256 !== process.env.EXPECTED_DIGEST || + receipt.sha256 !== sha256 || receipt.sourceSha !== process.env.SOURCE_SHA || receipt.workflowSha !== process.env.WORKFLOW_SHA || + receipt.version !== process.env.RELEASE_VERSION || receipt.runId !== process.env.GITHUB_RUN_ID || + !/^[1-9]\d*$/.test(receipt.attempt || '') || !/^[1-9]\d*$/.test(process.env.GITHUB_RUN_ATTEMPT || '') || + BigInt(receipt.attempt) > BigInt(process.env.GITHUB_RUN_ATTEMPT) || receipt.packageName !== expectedName || + receipt.gitHead !== process.env.SOURCE_SHA) throw new Error('npm receipt identity or digest mismatch'); + const entries = spawnSync('tar', ['-tzf', archive], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }); + if (entries.status !== 0 || entries.stdout.split('\n').filter(p => p === 'package/package.json').length !== 1) throw new Error('invalid npm manifest entry'); + const manifest = spawnSync('tar', ['-xOzf', archive, 'package/package.json'], { encoding: 'utf8', maxBuffer: 1024 * 1024 }); + if (manifest.status !== 0) throw new Error('cannot read npm manifest'); + const pkg = JSON.parse(manifest.stdout); + if (pkg.name !== expectedName || pkg.version !== process.env.RELEASE_VERSION || pkg.gitHead !== process.env.SOURCE_SHA || pkg.gitHead !== receipt.gitHead) throw new Error('npm package identity or gitHead mismatch'); + NODE - - name: Verify every version source matches the requested version + # Prepare and validate the receipt before the irreversible npm publication. + - name: Prepare publication receipt + if: ${{ inputs.resume-after-npm-publish != true }} env: - RELEASE_VERSION: ${{ inputs.version }} + NPM_DIST_TAG: ${{ inputs.tag }} run: | - # package.json plus the desktop sources (tauri.conf.json, Cargo.toml and the - # opencodex-desktop Cargo.lock entry). package-desktop already refused to build on a - # mismatch; this re-proves it on the commit that is about to publish. - bun scripts/release-version-sources.ts check "$RELEASE_VERSION" || { - echo "::error::a version source != requested (${RELEASE_VERSION}) — run scripts/release.ts, which moves all of them, on main first"; - exit 1; + set -euo pipefail + mkdir -p publication + node - <<'NODE' + const fs = require('node:fs'); + const receipt = JSON.parse(fs.readFileSync('verification/receipt.json', 'utf8')); + const sha = /^[0-9a-f]{40}$/, digest = /^[0-9a-f]{64}$/; + const runId = Number(process.env.GITHUB_RUN_ID), attempt = Number(process.env.GITHUB_RUN_ATTEMPT); + const version = process.env.RELEASE_VERSION, tag = process.env.NPM_DIST_TAG; + if (!sha.test(process.env.SOURCE_SHA || '') || !sha.test(process.env.WORKFLOW_SHA || '') || + !/^[1-9]\d*$/.test(process.env.GITHUB_RUN_ID || '') || !/^[1-9]\d*$/.test(process.env.GITHUB_RUN_ATTEMPT || '') || + !digest.test(process.env.EXPECTED_DIGEST || '') || !Number.isSafeInteger(runId) || runId <= 0 || + !Number.isSafeInteger(attempt) || attempt <= 0 || !/^\d+\.\d+\.\d+(?:-preview\.\d{8}\.\d+)?$/.test(version || '') || + !((tag === 'latest' && !version.includes('-')) || (tag === 'preview' && version.includes('-preview.')))) throw Error('invalid publication identity'); + if (receipt.sha !== process.env.SOURCE_SHA || receipt.workflowSha !== process.env.WORKFLOW_SHA || + receipt.version !== version || receipt.repo !== process.env.GITHUB_REPOSITORY || + receipt.runId !== process.env.GITHUB_RUN_ID || !/^[1-9]\d*$/.test(receipt.attempt || '') || + BigInt(receipt.attempt) > BigInt(process.env.GITHUB_RUN_ATTEMPT) || + !receipt.assets || typeof receipt.assets !== 'object' || Array.isArray(receipt.assets) || !Object.keys(receipt.assets).length) throw Error('release asset receipt mismatch'); + for (const [name, value] of Object.entries(receipt.assets)) { + if (!name || /[\x00-\x1f/\\]/.test(name) || !digest.test(value)) throw Error('invalid release asset receipt'); } + const publication = { sourceSha: process.env.SOURCE_SHA, workflowSha: process.env.WORKFLOW_SHA, + version, channel: tag === 'latest' ? 'stable' : 'preview', sha256: process.env.EXPECTED_DIGEST, + gitHead: process.env.SOURCE_SHA, runId, attempt, published: true, assets: receipt.assets }; + fs.writeFileSync('publication/pending.json', JSON.stringify(publication) + '\n', { flag: 'wx' }); + NODE - # The exact-SHA CI gate includes the hosted Linux, Windows, and macOS - # keyring smoke matrix. Do not duplicate its Linux bootstrap here. - - name: Require successful Cross-platform CI for this commit + - name: Recheck source CI and service evidence env: GH_TOKEN: ${{ github.token }} - RELEASE_VERSION: ${{ inputs.version }} - NPM_DIST_TAG: ${{ inputs.tag }} run: | set -euo pipefail - - case "$GITHUB_REF" in - refs/heads/main) - expected_tag="latest" - if [[ "$RELEASE_VERSION" == *-* ]]; then - echo "::error::main releases must use a stable semver version; got ${RELEASE_VERSION}" - exit 1 - fi - ;; - refs/heads/preview) - expected_tag="preview" - if [[ "$RELEASE_VERSION" != *-preview.* ]]; then - echo "::error::preview releases must use a preview prerelease version; got ${RELEASE_VERSION}" - exit 1 - fi - ;; - *) - echo "::error::Release must run from main or preview; got ${GITHUB_REF}" - exit 1 - ;; - esac - - if [ "$NPM_DIST_TAG" != "$expected_tag" ]; then - echo "::error::${GITHUB_REF#refs/heads/} releases must publish with npm dist-tag '${expected_tag}', got '${NPM_DIST_TAG}'" - exit 1 - fi - - ci_url="$( - gh run list \ - --workflow ci.yml \ - --branch "${GITHUB_REF#refs/heads/}" \ - --commit "$GITHUB_SHA" \ - --event push \ - --limit 10 \ - --json conclusion,url \ - --jq '[.[] | select(.conclusion == "success")][0].url // ""' - )" - - if [ -z "$ci_url" ]; then - # Deliberately narrower than "any successful ci.yml run for this SHA". - # The release branch's own push run is the one whose trigger set, - # runner selection, and job graph match what is being published — - # a green PR run for the same SHA ran against a merge ref with a - # different trigger context. Accepting it here would let a publish - # proceed while the promotion run was still pending, or had failed. - echo "::error::No successful Cross-platform CI run found for ${GITHUB_SHA} on ${GITHUB_REF#refs/heads/} (push event). A pull-request run does not qualify. Wait for the promotion run to pass before releasing." - gh run list --workflow ci.yml --commit "$GITHUB_SHA" --limit 10 || true - exit 1 - fi - - echo "Cross-platform CI passed for ${GITHUB_SHA}: ${ci_url}" - - # Service baseline (lineage-relative): merged tags only, so the - # changed-files gate compares against the last release actually - # reachable from this commit. The release-notes baseline below uses the - # full tag set instead, so a stable on another lineage can anchor the - # changelog range. - # - Preview: newest prior release of either channel (stable or preview). A - # preview→preview-only baseline skips a shipped stable and restates it. - # - Stable: newest prior stable only (matching preview carry adjusts the - # generate-notes range separately below). - previous_tag="$( - git tag --merged HEAD --list 'v[0-9]*' | - bun scripts/release-notes.ts previous-release-tag "$RELEASE_VERSION" - )" - if [ -n "$previous_tag" ]; then - changed_files="$(git diff --name-only "${previous_tag}..HEAD")" - else - changed_files="$(git diff-tree --no-commit-id --name-only -r "$GITHUB_SHA")" + node .github/scripts/release-evidence.cjs check "$SOURCE_SHA" + baseline_tag="$(git tag --merged "$SOURCE_SHA" --list 'v[0-9]*' | bun -e ' + import { parseVersion, compareVersions } from "./scripts/version-line.ts"; + const tags = (await Bun.stdin.text()).trim().split("\n").filter(Boolean); + const versions = tags.map(tag => ({ tag, version: tag.slice(1) })); + if (versions.some(item => !parseVersion(item.version))) throw new Error("invalid release tag"); + const eligible = versions.filter(item => compareVersions(item.version, process.env.RELEASE_VERSION) < 0); + eligible.sort((a, b) => compareVersions(a.version, b.version)); + console.log(eligible.at(-1)?.tag ?? ""); + ')" + baseline=--initial + if [ -n "$baseline_tag" ]; then + draft="$(gh release view "$baseline_tag" --json isDraft --jq .isDraft)" + test "$draft" = false || { echo '::error::Service baseline is not a published release.'; exit 1; } + baseline="$(git rev-parse "refs/tags/${baseline_tag}^{commit}")" fi - - # Keep in sync with the service-lifecycle.yml trigger paths. src/cli.ts is - # the pre-restructure compat stub that durable launchers still execute; the - # service implementation itself is the src/service/ directory, and the desktop - # shell packages and launches it. - if printf '%s\n' "$changed_files" | grep -Eq '^(src/service\.ts|src/service/.*|desktop/.*|src/cli\.ts|src/cli/index\.ts|src/lib/bun-runtime\.ts|package\.json|bun\.lock|\.github/workflows/service-lifecycle\.yml|\.github/workflows/release\.yml)$'; then - service_url="$( - gh run list \ - --workflow service-lifecycle.yml \ - --commit "$GITHUB_SHA" \ - --limit 10 \ - --json conclusion,headSha,url,workflowName \ - --jq '[.[] | select(.conclusion == "success")][0].url // ""' - )" - if [ -z "$service_url" ]; then - echo "::error::Service-related files changed since ${previous_tag:-initial commit}, but no successful Service lifecycle run was found for ${GITHUB_SHA}." - gh run list --workflow service-lifecycle.yml --commit "$GITHUB_SHA" --limit 10 || true - exit 1 - fi - echo "Service lifecycle passed for ${GITHUB_SHA}: ${service_url}" + range="$(node .github/scripts/release-evidence.cjs service-range "$SOURCE_SHA" "$baseline")" + required="$(RANGE="$range" node -e 'const x = JSON.parse(process.env.RANGE); if (typeof x.required !== "boolean") throw Error("invalid service range"); process.stdout.write(String(x.required));')" + if [ "$required" = true ]; then + node .github/scripts/release-evidence.cjs service "$SOURCE_SHA" || { + echo "::error::Dispatch service-lifecycle.yml from dev for source ${SOURCE_SHA} and wait for all platforms."; exit 1; + } fi - - name: Require dev to be ready for this release - env: - RELEASE_VERSION: ${{ inputs.version }} - run: | - set -euo pipefail - git fetch --force --tags origin +refs/heads/dev:refs/remotes/origin/dev - dev_version="$(git show origin/dev:package.json | bun -e 'console.log(JSON.parse(await Bun.stdin.text()).version)')" - bun scripts/version-line.ts assert-ahead "$dev_version" "$RELEASE_VERSION" - - # Tokenless publish via Trusted Publishing (OIDC) — NO NPM_TOKEN secret. npm auto-detects the - # OIDC environment (`id-token: write` above) and generates provenance automatically, so neither a - # token nor `--provenance` is needed. `npm publish` runs prepublishOnly first (typecheck + build - # the GUI into gui/dist), so even a dry-run fully verifies the build. - # PREREQUISITE: configure the Trusted Publisher for this repo + workflow on npmjs.com — possible - # only AFTER the package's first version exists (do the first publish locally, see the runbook). - - name: Preflight release metadata - id: metadata + - name: Refuse a release the current tag set already outranks env: - GH_TOKEN: ${{ github.token }} - RELEASE_VERSION: ${{ inputs.version }} - DRY_RUN: ${{ inputs.dry-run }} RESUME: ${{ inputs.resume-after-npm-publish }} run: | set -euo pipefail - - pkg_name="$(node -p "require('./package.json').name")" - release_tag="v${RELEASE_VERSION}" - dry_run="$DRY_RUN" - git fetch --force --tags origin - - existing_tag_sha="$(git rev-parse -q --verify "refs/tags/${release_tag}^{commit}" || true)" - if [ -n "$existing_tag_sha" ] && [ "$existing_tag_sha" != "$GITHUB_SHA" ]; then - echo "::error::${release_tag} already points at ${existing_tag_sha}, not ${GITHUB_SHA}" - exit 1 - fi - - if [ -n "$existing_tag_sha" ]; then - if [ "$RESUME" = "true" ]; then - echo "::notice::${release_tag} already exists at this commit; resuming" - elif [ "$dry_run" = "true" ]; then - echo "::notice::${release_tag} already exists at this commit; dry-run only" - else - echo "::error::${release_tag} already exists. Refusing to publish a version with pre-existing Git metadata." - exit 1 - fi + allow="" + existing_tag_sha="$(git rev-parse -q --verify "refs/tags/v${RELEASE_VERSION}^{commit}" || true)" + if [ -n "$existing_tag_sha" ] && [ "$existing_tag_sha" != "$SOURCE_SHA" ]; then + echo '::error::Existing release tag points at a different source.'; exit 1 fi + if [ "$RESUME" = true ] && [ -n "$existing_tag_sha" ]; then allow="--allow-existing-tag-at-head"; fi + git tag --list 'v*' | bun scripts/version-line.ts assert-releasable "$RELEASE_VERSION" ${allow:+"$allow"} - if gh release view "$release_tag" >/dev/null 2>&1; then - if [ "$RESUME" = "true" ]; then - echo "::notice::GitHub Release ${release_tag} already exists; resuming to complete the attachment" - elif [ "$dry_run" = "true" ]; then - echo "::notice::GitHub Release ${release_tag} already exists; dry-run only" - else - echo "::error::GitHub Release ${release_tag} already exists. Choose the next unused patch version." - exit 1 - fi - fi + - name: Build and validate release changelog + env: + GH_TOKEN: ${{ github.token }} + NPM_DIST_TAG: ${{ inputs.tag }} + run: | + set -euo pipefail + notes_file="$GITHUB_WORKSPACE/.release-notes.md" + bun scripts/build-release-changelog.ts --version "$RELEASE_VERSION" --dist-tag "$NPM_DIST_TAG" \ + --repository "$GITHUB_REPOSITORY" --target "$SOURCE_SHA" --out "$notes_file" + test -s "$notes_file" - if [ "$RESUME" = "true" ] && [ "$dry_run" = "true" ]; then - echo "::error::resume-after-npm-publish is a real-publication recovery path and cannot combine with dry-run" - exit 1 - fi - if npm view "${pkg_name}@${RELEASE_VERSION}" version >/dev/null 2>&1; then - if [ "$RESUME" = "true" ]; then - resume_git_head="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" gitHead --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000)" || { - echo "::error::Cannot verify the existing npm package source; resume refused" - exit 1 - } - bun scripts/verify-release-resume.ts "$GITHUB_SHA" "$resume_git_head" - echo "resume_sha=$GITHUB_SHA" >> "$GITHUB_OUTPUT" - echo "::notice::${pkg_name}@${RELEASE_VERSION} is acknowledged on npm; resuming after the recorded partial publication" - elif [ "$dry_run" = "true" ]; then - echo "::notice::${pkg_name}@${RELEASE_VERSION} already exists on npm; dry-run only" - else - echo "::error::${pkg_name}@${RELEASE_VERSION} already exists on npm. If a previous run acknowledged this publication and failed afterwards, re-dispatch with resume-after-npm-publish: true; otherwise choose the next unused patch version." - exit 1 - fi - elif [ "$RESUME" = "true" ]; then - echo "::error::resume-after-npm-publish is set, but ${pkg_name}@${RELEASE_VERSION} is not on npm — there is no acknowledged publication to resume from" + - name: Require publication hold to be enabled + env: + DRY_RUN: ${{ inputs.dry-run }} + PUBLISH_ENABLED: ${{ vars.OCX_DEV_RELEASE_PUBLISH_ENABLED }} + run: | + if [ "$DRY_RUN" != "true" ] && [ "$PUBLISH_ENABLED" != "true" ]; then + echo '::error::Publication is disabled; OCX_DEV_RELEASE_PUBLISH_ENABLED must equal true.' exit 1 fi - - name: Refuse a release the current tag set already outranks + - name: Require reconciled publication history + if: ${{ inputs.resume-after-npm-publish != true }} env: - RELEASE_VERSION: ${{ inputs.version }} - DRY_RUN: ${{ inputs.dry-run }} - RESUME: ${{ inputs.resume-after-npm-publish }} + GH_TOKEN: ${{ github.token }} + NPM_DIST_TAG: ${{ inputs.tag }} run: | set -euo pipefail - allow="" - existing_tag_sha="$(git rev-parse -q --verify "refs/tags/v${RELEASE_VERSION}^{commit}" || true)" - # Dry-run re-dispatches and the resume path both legitimately find the tag - # already at this commit; a moved tag is still refused above. - if { [ "$DRY_RUN" = "true" ] || [ "$RESUME" = "true" ]; } && [ -n "$existing_tag_sha" ] && [ "$existing_tag_sha" = "$GITHUB_SHA" ]; then - allow="--allow-existing-tag-at-head" + if ! [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] || [ -z "$RELEASE_VERSION" ]; then + echo '::error::Invalid release identity for history reconciliation.'; exit 1 fi - git tag --list 'v*' | bun scripts/version-line.ts assert-releasable "$RELEASE_VERSION" $allow + case "$NPM_DIST_TAG" in + latest) channel=stable ;; + preview) channel=preview ;; + *) echo '::error::Invalid release channel.'; exit 1 ;; + esac + node .github/scripts/release-history.cjs check "$SOURCE_SHA" "$RELEASE_VERSION" "$channel" - - name: Build and validate release changelog + - name: Verify resume registry identity + id: resume-identity + if: ${{ inputs.resume-after-npm-publish == true }} + run: | + set -euo pipefail + pkg_name="$(node -p "require('./package.json').name")" + registry_version="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" version --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000)" || { + echo '::error::Cannot read the exact npm version; resume refused.'; exit 1; + } + REGISTRY_VERSION="$registry_version" node - <<'NODE' + const value = JSON.parse(process.env.REGISTRY_VERSION); + if (typeof value !== 'string' || value !== process.env.RELEASE_VERSION) throw Error('npm version does not match original release'); + NODE + registry_head="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" gitHead --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000)" || { + echo '::error::Cannot read npm gitHead; resume refused.'; exit 1; + } + bun scripts/verify-release-resume.ts "$SOURCE_SHA" "$registry_head" + echo "resume_sha=$SOURCE_SHA" >> "$GITHUB_OUTPUT" + + - name: Check resume publication + id: resume-check + if: ${{ inputs.resume-after-npm-publish == true }} env: GH_TOKEN: ${{ github.token }} - RELEASE_VERSION: ${{ inputs.version }} NPM_DIST_TAG: ${{ inputs.tag }} run: | set -euo pipefail - notes_file="$GITHUB_WORKSPACE/.release-notes.md" - bun scripts/build-release-changelog.ts \ - --version "$RELEASE_VERSION" \ - --dist-tag "$NPM_DIST_TAG" \ - --repository "$GITHUB_REPOSITORY" \ - --target "$GITHUB_SHA" \ - --out "$notes_file" - test -s "$notes_file" || { - echo "::error::release changelog builder produced an empty notes file" - exit 1 - } + case "$NPM_DIST_TAG" in latest) channel=stable ;; preview) channel=preview ;; *) exit 1 ;; esac + decision="$(node .github/scripts/release-resume.cjs check "$RELEASE_VERSION" "$SOURCE_SHA" "$channel")" + DECISION="$decision" CHANNEL="$channel" node - <<'NODE' + const fs = require('node:fs'), result = JSON.parse(process.env.DECISION); + if (result.version !== process.env.RELEASE_VERSION || result.sourceSha !== process.env.SOURCE_SHA || + result.channel !== process.env.CHANNEL || result.publishNpm !== false || result.assetsChecked !== false) throw Error('invalid resume publication decision'); + fs.appendFileSync(process.env.GITHUB_OUTPUT, `resume_checked_sha=${result.sourceSha}\n`); + NODE - - name: Publish (or dry-run) + - name: Publish verified npm tarball id: publication env: - DRY_RUN: ${{ inputs.dry-run }} NPM_DIST_TAG: ${{ inputs.tag }} RESUME: ${{ inputs.resume-after-npm-publish }} - RELEASE_VERSION: ${{ inputs.version }} - VERIFIED_RESUME_SHA: ${{ steps.metadata.outputs.resume_sha }} + VERIFIED_RESUME_SHA: ${{ steps.resume-identity.outputs.resume_sha }} + VERIFIED_RESUME_DECISION: ${{ steps.resume-check.outputs.resume_checked_sha }} run: | set -euo pipefail - pkg_name="$(node -p "require('./package.json').name")" - if [ "$RESUME" = "true" ]; then - if [ -z "$VERIFIED_RESUME_SHA" ] || [ "$VERIFIED_RESUME_SHA" != "$GITHUB_SHA" ]; then - echo "::error::Resume has no matching registry source verification; publication remains unacknowledged" - exit 1 + if [ "$RESUME" = true ]; then + if [ -z "$VERIFIED_RESUME_SHA" ] || [ "$VERIFIED_RESUME_SHA" != "$SOURCE_SHA" ] || + [ -z "$VERIFIED_RESUME_DECISION" ] || [ "$VERIFIED_RESUME_DECISION" != "$SOURCE_SHA" ]; then + echo '::error::Resume has no matching registry verification; refusing publication acknowledgement.'; exit 1 fi - # npm publication was acknowledged by the earlier run and confirmed by the - # preflight above; completing the GitHub side must never republish. - echo "::notice::RESUME — npm publish skipped; publication already acknowledged" - echo "published=true" >> "$GITHUB_OUTPUT" - echo "Publication resumed for ${pkg_name}@${RELEASE_VERSION} at ${GITHUB_SHA} (npm publish skipped; acknowledged by the earlier run)." >> "$GITHUB_STEP_SUMMARY" - elif [ "$DRY_RUN" = "true" ]; then - echo "::notice::DRY RUN — building + packing, not publishing" - npm run prepublishOnly - npm pack --dry-run + echo "::notice::Resume verified; npm publish skipped." else - npm publish --tag "$NPM_DIST_TAG" --access public - echo "published=true" >> "$GITHUB_OUTPUT" - echo "Publication acknowledged for ${pkg_name}@${RELEASE_VERSION} at ${GITHUB_SHA}. If any later step in this run fails, re-dispatch with the same version and expected-sha plus resume-after-npm-publish: true — never republish this version." >> "$GITHUB_STEP_SUMMARY" + npm publish "$NPM_TARBALL" --ignore-scripts --tag "$NPM_DIST_TAG" --access public fi + echo "published=true" >> "$GITHUB_OUTPUT" + echo "Publication acknowledged for ${RELEASE_VERSION} at ${SOURCE_SHA}; do not republish this version." >> "$GITHUB_STEP_SUMMARY" + + # A same-run artifact is evidence to be authenticated, not provenance by itself. + - name: Record acknowledged publication + if: ${{ steps.publication.outputs.published == 'true' && inputs.resume-after-npm-publish != true }} + run: | + set -euo pipefail + test -s publication/pending.json && test ! -e publication/receipt.json + mv publication/pending.json publication/receipt.json + + - name: Upload publication receipt + if: ${{ steps.publication.outputs.published == 'true' && inputs.resume-after-npm-publish != true }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: release-publication-receipt + path: publication/receipt.json + if-no-files-found: error + retention-days: 7 # Publication is acknowledged before registry reads, which can lag or fail. # Recover only observation failures in this run; never retry npm publish. @@ -1294,7 +1706,7 @@ jobs: id: registry-smoke if: ${{ inputs.dry-run != true && steps.publication.outputs.published == 'true' }} env: - RELEASE_VERSION: ${{ inputs.version }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} NPM_DIST_TAG: ${{ inputs.tag }} PUBLISHED: ${{ steps.publication.outputs.published }} run: | @@ -1304,7 +1716,10 @@ jobs: exit 1 } pkg_name="$(node -p "require('./package.json').name")" - for attempt in $(seq 1 6); do + # npm can take 15+ minutes to serve a new version (2.100.1: ~15 min after publish), so the + # bounded wait is attempts x interval, about 20 minutes. Publication is never retried. + attempts="${REGISTRY_WAIT_ATTEMPTS:-40}"; interval="${REGISTRY_WAIT_SECONDS:-30}" + for attempt in $(seq 1 "$attempts"); do if VERSION=$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" version --fetch-retries=0 --fetch-timeout=8000 2>/dev/null); then if [ "$VERSION" != "$RELEASE_VERSION" ]; then echo "::error::Registry returned an unexpected version; refusing to create a release" @@ -1335,20 +1750,45 @@ jobs: echo "npm dist-tag ${NPM_DIST_TAG}: ${dist_tag_state}." >> "$GITHUB_STEP_SUMMARY" exit 0 fi - echo "::notice::Registry lookup not confirmed (attempt $attempt/6)" - if [ "$attempt" -lt 6 ]; then sleep 5; fi + echo "::notice::Registry lookup not confirmed (attempt $attempt/$attempts)" + if [ "$attempt" -lt "$attempts" ]; then sleep "$interval"; fi done + # Keep each outcome explicit for the recovery report. + # shellcheck disable=SC2129 echo "verification=pending" >> "$GITHUB_OUTPUT" echo "npm_version=unconfirmed" >> "$GITHUB_OUTPUT" echo "npm_dist_tag=unconfirmed" >> "$GITHUB_OUTPUT" echo "::warning::npm publish succeeded, but registry verification remains pending; continuing GitHub release creation without republishing" echo "Publication acknowledged for ${pkg_name}@${RELEASE_VERSION}; registry verification pending after bounded reads. Inspect the registry before announcing availability. Do not republish this version." >> "$GITHUB_STEP_SUMMARY" + - name: Verify published npm source + if: ${{ steps.publication.outputs.published == 'true' }} + run: | + set -euo pipefail + pkg_name="$(node -p "require('./package.json').name")" + attempts="${REGISTRY_WAIT_ATTEMPTS:-40}"; interval="${REGISTRY_WAIT_SECONDS:-30}" + for attempt in $(seq 1 "$attempts"); do + if head="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" gitHead --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000 2>/dev/null)"; then + if [ -n "$head" ] && [ "$head" != null ]; then + REGISTRY_HEAD="$head" node - <<'NODE' + const head = JSON.parse(process.env.REGISTRY_HEAD); + if (!/^[0-9a-f]{40}$/.test(process.env.SOURCE_SHA || '') || head !== process.env.SOURCE_SHA) { + throw Error('published npm gitHead does not match selected source'); + } + NODE + exit 0 + fi + fi + if [ "$attempt" -lt "$attempts" ]; then sleep "$interval"; fi + done + echo '::error::Published npm gitHead could not be verified; do not republish and reconcile manually.' + exit 1 + - name: Create GitHub release if: ${{ inputs.dry-run != true && steps.publication.outputs.published == 'true' }} env: GH_TOKEN: ${{ github.token }} - RELEASE_VERSION: ${{ inputs.version }} + RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }} RESUME: ${{ inputs.resume-after-npm-publish }} run: | set -euo pipefail @@ -1363,8 +1803,8 @@ jobs: git fetch --force --tags origin existing_tag_sha="$(git rev-parse -q --verify "refs/tags/${release_tag}^{commit}" || true)" - if [ -n "$existing_tag_sha" ] && [ "$existing_tag_sha" != "$GITHUB_SHA" ]; then - echo "::error::${release_tag} already points at ${existing_tag_sha}, not ${GITHUB_SHA}" + if [ -n "$existing_tag_sha" ] && [ "$existing_tag_sha" != "$SOURCE_SHA" ]; then + echo "::error::${release_tag} already points at ${existing_tag_sha}, not ${SOURCE_SHA}" exit 1 fi @@ -1374,7 +1814,7 @@ jobs: fi if [ -z "$existing_tag_sha" ]; then - git tag "$release_tag" "$GITHUB_SHA" + git tag "$release_tag" "$SOURCE_SHA" git push origin "refs/tags/${release_tag}" fi @@ -1393,6 +1833,6 @@ jobs: # Draft first. Publication freezes a release under GitHub's immutable # releases, so attach-release attaches the verified bundle to the draft # and publishes it afterwards. - gh release create "$release_tag" --draft --target "$GITHUB_SHA" --title "$release_tag" \ + gh release create "$release_tag" --draft --target "$SOURCE_SHA" --title "$release_tag" \ --notes-file "$notes_file" ${prerelease_flag:+$prerelease_flag} fi diff --git a/.github/workflows/service-lifecycle.yml b/.github/workflows/service-lifecycle.yml index ad86503340..87249bf4d1 100644 --- a/.github/workflows/service-lifecycle.yml +++ b/.github/workflows/service-lifecycle.yml @@ -2,7 +2,7 @@ name: Service lifecycle on: pull_request: - branches: [main, dev] + branches: [dev] paths: - "src/service.ts" # The service implementation is the src/service/ directory; src/service.ts is only @@ -23,45 +23,62 @@ on: # commit that touches only release.yml (e.g. the v2.40.0 permissions carry, #3263/#3264) # produced no run and the gate dead-ended until a manual dispatch. - ".github/workflows/release.yml" - push: - # Release lines only (no dev: cross-platform legs run on dev by manual - # workflow_dispatch). Pull requests run only the Linux leg. main and preview - # must stay: release.yml needs a successful push run for the exact release - # SHA, and scripts/release.ts only releases from main or preview. Without a - # branch filter every feature-branch push would re-run all three legs. - branches: [main, preview] - paths: - - "src/service.ts" - # Keep in sync with the release.yml service-gate regex (see above). - - "src/service/**" - - "desktop/**" - # Keep in sync with the release.yml service-gate regex (see above). - - "src/cli.ts" - - "src/cli/index.ts" - - "src/lib/bun-runtime.ts" - - "package.json" - - "bun.lock" - - ".github/workflows/service-lifecycle.yml" - # release.yml gates on THIS workflow having run for the release SHA. A release-branch - # commit that touches only release.yml (e.g. the v2.40.0 permissions carry, #3263/#3264) - # produced no run and the gate dead-ended until a manual dispatch. - - ".github/workflows/release.yml" workflow_dispatch: + inputs: + source_sha: + description: "Full dev ancestor SHA to test" + required: true + type: string permissions: contents: read concurrency: - group: service-lifecycle-${{ github.ref }} - cancel-in-progress: true + group: service-lifecycle-${{ github.event_name == 'workflow_dispatch' && github.run_id || github.ref }} + cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }} jobs: + validate-source: + name: validate source + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Validate dispatch source + shell: bash + env: + EVENT_NAME: ${{ github.event_name }} + REF: ${{ github.ref }} + SOURCE_SHA: ${{ github.event.inputs.source_sha }} + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + if [ "$EVENT_NAME" != workflow_dispatch ]; then exit 0; fi + if [ "$REF" != refs/heads/dev ] || ! [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]]; then + echo '::error::dispatch requires dev and a full lowercase source SHA' + exit 1 + fi + status="$(gh api "repos/${GITHUB_REPOSITORY}/compare/${SOURCE_SHA}...dev" --jq .status)" + if [ "$status" != ahead ] && [ "$status" != identical ]; then + echo '::error::source is not an ancestor of dev' + exit 1 + fi + linux-systemd: + name: linux-systemd ${{ github.event.inputs.source_sha }} + needs: validate-source runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 - - uses: ./.github/actions/setup-project-bun + with: + persist-credentials: false + ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_sha || github.sha }} + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + path: .evidence-policy + ref: ${{ github.sha }} + persist-credentials: false + - uses: ./.evidence-policy/.github/actions/setup-project-bun - run: bun install --frozen-lockfile @@ -177,13 +194,23 @@ jobs: fi macos-launchd: - # Pull requests run the Linux leg only; macOS runs on manual dispatch and main/preview push. + name: macos-launchd ${{ github.event.inputs.source_sha }} + needs: validate-source + # Pull requests run the Linux leg only; macOS runs on manual dispatch. if: github.event_name != 'pull_request' runs-on: macos-latest timeout-minutes: 10 steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 - - uses: ./.github/actions/setup-project-bun + with: + persist-credentials: false + ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_sha || github.sha }} + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + path: .evidence-policy + ref: ${{ github.sha }} + persist-credentials: false + - uses: ./.evidence-policy/.github/actions/setup-project-bun - run: bun install --frozen-lockfile @@ -257,13 +284,23 @@ jobs: fi windows-schtasks: - # Pull requests run the Linux leg only; Windows runs on manual dispatch and main/preview push. + name: windows-schtasks ${{ github.event.inputs.source_sha }} + needs: validate-source + # Pull requests run the Linux leg only; Windows runs on manual dispatch. if: github.event_name != 'pull_request' runs-on: windows-latest timeout-minutes: 10 steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 - - uses: ./.github/actions/setup-project-bun + with: + persist-credentials: false + ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_sha || github.sha }} + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + path: .evidence-policy + ref: ${{ github.sha }} + persist-credentials: false + - uses: ./.evidence-policy/.github/actions/setup-project-bun - run: bun install --frozen-lockfile diff --git a/.github/workflows/stale-needs-info.yml b/.github/workflows/stale-needs-info.yml index d33fb204a5..ca9838ff21 100644 --- a/.github/workflows/stale-needs-info.yml +++ b/.github/workflows/stale-needs-info.yml @@ -1,16 +1,14 @@ name: Close stale needs-info issues -# Scheduled workflows only run from the repository DEFAULT branch -# (currently `main`), not from `dev`. Landing here on `dev` alone does not -# change live issue-stale behavior until the change is also on that default -# branch. +# Scheduled workflows only run from the repository DEFAULT branch, which is +# `dev`. A change lands on the live schedule as soon as it is on `dev`. on: schedule: # Daily at 06:15 UTC (offset from the hour to reduce Action load spikes). - cron: "15 6 * * *" # No workflow_dispatch: a branch-selected manual run would execute that # branch's workflow body with issues:write / pull-requests:write, bypassing - # default-branch review. Schedule-only keeps the trusted revision on main. + # default-branch review. Schedule-only keeps the trusted revision on `dev`. permissions: issues: write diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 0000000000..6267919f0a --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,41 @@ +# gitleaks configuration for dalsoop/opencodex (read by .github/workflows/secret-detection.yml and the +# Macs' pre-commit secret check). The default rules stay on; nothing here disables a rule. +[extend] +useDefault = true + +[[allowlists]] +description = """ +Upstream lidge-jun/opencodex test fixtures (brought in with the v2.100.2 merge). Each listed file holds a made-up +provider key, token or canary that the upstream tests feed through redaction, error-body and request-log paths to +prove the value never reaches output. Reviewed 2026-11-12 (ocx-align T8): every hit is a test constant, not a +credential. Scoped to the generic-api-key rule and to exactly these files; every other rule still applies to them. +""" +targetRules = ["generic-api-key"] +paths = [ + '''^gui/tests/logs-failure-detail\.test\.ts$''', + '''^native/ocx-child/tests/relay_and_lifecycle\.rs$''', + '''^tests/fixtures/link/ocx-child-conformance\.json$''', + '''^tests/helpers/messages-proxy-refusal-case\.ts$''', + '''^tests/lib/client-error-body\.test\.ts$''', + '''^tests/lib/upstream-condition\.test\.ts$''', + '''^tests/providers/cc-switch-import\.test\.ts$''', + '''^tests/providers/command-code-plan-denial\.test\.ts$''', + '''^tests/responses/chat-error-body-normalization\.test\.ts$''', + '''^tests/responses/chat-error-collector-verdicts\.test\.ts$''', + '''^tests/responses/passthrough-headers\.test\.ts$''', + '''^tests/server/fallback-routes\.test\.ts$''', + '''^tests/server/local-control-socket\.test\.ts$''', + '''^tests/server/response-model-identity\.test\.ts$''', + '''^tests/server/safe-response-headers\.test\.ts$''', + '''^tests/server/server-chat-error-body-evidence\.test\.ts$''', + '''^tests/server/server-kiro-usage-log-e2e\.test\.ts$''', + '''^tests/server/server-live-cancel\.test\.ts$''', + '''^tests/server/server-native-final-log\.test\.ts$''', + '''^tests/server/server-ollama-inbound-errors\.test\.ts$''', + '''^tests/server/turn-state-handles\.test\.ts$''', + '''^tests/server/upstream-error-detail-boundaries\.test\.ts$''', + '''^tests/usage/mistral-budget-reset-identity\.test\.ts$''', + '''^tests/usage/provider-failure-detail\.test\.ts$''', + '''^tests/usage/request-log-error-detail\.test\.ts$''', + '''^tests/usage/request-log-identity-bounds\.test\.ts$''', +] diff --git a/AGENTS.md b/AGENTS.md index 26f50a0466..ea56c79a95 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,17 +2,6 @@ Guidance for AI agents (and humans) working on or reviewing this repository. -## Repository ownership and publishing target - -This is the independently maintained `dalsoop/opencodex` repository. Pushes, -issues, and pull requests belong in `dalsoop/opencodex` unless the user explicitly -requests a different destination for the current task. - -Do not open or update pull requests against `lidge-jun/opencodex`, or add it as -a Git remote, without an explicit request to contribute upstream. Historical -upstream links and the inherited maintainer instructions below do not authorize -publishing changes there. - ## What this project is opencodex (`ocx`) is a universal provider proxy for OpenAI Codex and Claude Code: @@ -124,10 +113,10 @@ different pointer, so every branch move and promotion dragged a diff. Reference *clones* are gitignored: they are third-party source carrying their own licenses and have no business in this repository's history. -Nothing in the build, typecheck, or test path reads from `devlog/`, so a -contributor who ignores it entirely still passes every gate. `privacy:scan` does -read it — that is deliberate, and it is what makes a public devlog safe rather -than merely visible. +Build and typecheck do not read `devlog/`. The test-layout membership oracle reads +`devlog/_fin/260905_test_modularization_and_windows/001_test_inventory.md`; sparse +checkouts running that test must materialize this tracked input. `privacy:scan` +also reads `devlog/` to keep public development notes safe to publish. Two mechanical guards in `tests/ci-workflows/repo-hygiene.test.ts` back this up: no `160000` gitlink may be tracked anywhere, and neither the vendored reference clones nor @@ -206,7 +195,7 @@ it binds you regardless of which mechanism is within reach. ```bash bun install -bun run typecheck # bun x tsc --noEmit (strict) +bun run typecheck # bun check --no-script --noEmit (strict) bun run test:changed # import-graph tests against the resolved `dev` merge base bun run test # full tests/ suite (default before review) bun run lint:gui # GUI eslint @@ -362,8 +351,8 @@ than nudged. they were deleted; `tests/ci-workflows/repo-hygiene.test.ts` now rejects those folders. When the PR resolves an issue, add `Closes #` to link it. GitHub auto-closes the linked issue only - when the PR merges into the default branch (`main`); PRs here target - `dev`, so close the issue manually once the change is on `dev`. + when the PR merges into the default branch, which is `dev`, so a linked issue + closes when its pull request merges. - **Landing another author's work:** reimplementing, superseding, carrying, or rebasing someone else's pull request requires a `Co-authored-by` trailer naming that author, in the description or in a branch commit so it survives @@ -378,18 +367,41 @@ than nudged. ## CI policy (maintainer decision — do not change) -- Pull requests run **only the fast Ubuntu subset**. +- Pull requests run **only the fast Ubuntu subset**. By default that is `gates` plus + `test changed` (import-graph tests for the diff); the four full Ubuntu shards run on a + pull request only with the `ci:full` label or a CI/harness/toolchain/dependency change. + Merged pull requests are verified in batches by a manual `dev` dispatch + (`MAINTAINERS.md`, "Batched merges"). Because `test changed` follows the module graph, + add `ci:full` for changes it cannot see (subprocesses, files read as data, generated output). - Full cross-platform (macOS/Windows) CI runs **only** via manual - `workflow_dispatch` and on push to `main`/`preview` (release lines). + `workflow_dispatch` on `dev`. A successful complete `lane=all` run establishes + evidence for its exact dev commit; a PR run or narrower manual lane does not. +- A manual `lane=all` dispatch is a **batch check on `dev`**, never a per-PR gate. + One run is about 32 jobs (11 Windows, at least 6 macOS, 15 Linux) and six runner-hours, and the + account has only five macOS slots (a macOS job can queue), so per-PR dispatches starve + every other check. On 2026-10-27, parallel agent lanes dispatched 48 of them in twelve hours (about 13,000 + runner-minutes). The queue passed 200 runs, and ordinary PR checks waited hours to start. + - Merge a pull request, including a Windows- or macOS-sensitive one, on its green PR + CI. After a batch of merges, run one `gh workflow run ci.yml --ref dev` as described + under "Batched merges". If it is red, stop merging and fix `dev` from that batch. + - Do not dispatch `lane=all` for a PR branch. Run it once for a batch on `dev`; + never re-dispatch merely because the head moved or rerun to green. Cancel your + own superseded dispatches with `gh run cancel`. + - Every description edit or label change starts three event-gate workflows. Batch those + edits, and keep the number of agents working pull requests in parallel small. - **Never** add a `dev` push trigger, or `pull_request` runs for macOS/Windows jobs, to any workflow. PRs that change this policy will be closed. ## Branch policy -- `dev` — the single integration branch and the target for every pull request. -- `main` — release branch. It only moves by maintainer-controlled promotion - from `dev` (releases, docs deploys). Do not open feature PRs against `main`. -- `preview` — prerelease train (`x.y.z-preview.*` versions). +- `dev` — the single development and integration branch, the repository default + branch, and the target for every ordinary pull request. Preview and stable + releases are built from eligible commits on this line, with versions stamped in + build checkouts. +- `main` and `preview` were deleted once the single-branch model was in place. + Their released history remains reachable through tags; they are not + integration, promotion, or review targets, and no workflow may trigger on or + check out either branch. Bun-native TypeScript on `dev` is the only runtime line. If native code returns, the expectation is an incremental module (for example Rust via N-API) @@ -404,9 +416,9 @@ Rebase pull requests are welcome. Bringing a stale branch onto the current head is ordinary maintenance — open it as a normal pull request and name the source commits in the description. -The **`enforce-target`** CI check rejects pull requests whose head -ancestry sits on the **`main`** tip while far behind **`dev`**, and rejects -empty, thin, or malformed descriptions. If changed paths include files under +The **`enforce-target`** CI check rejects pull requests whose base is not +**`dev`** (stacked children excepted), and rejects empty, thin, or malformed +descriptions. If changed paths include files under `gui/`, include a screenshot of the UI change in the description; the check re-runs on description edits until the screenshot is present. Drag the image into the description editor rather than committing it, or, when uploading from @@ -428,16 +440,15 @@ local-validation box is an author attestation only — fork contributors cannot repository CI; a maintainer has to — so the gate never disproves it; a new push still resets every box. A disproved claim unticks the matching box and keeps the PR a draft. -Authors with repository push permission skip the ancestry heuristic only. As with approval requirements in -[`MAINTAINERS.md`](./MAINTAINERS.md), the ancestry heuristic is a CI check -rather than a branch rule. The branches themselves are protected: `dev`, -`main`, and `preview` each require a pull request and block force-pushes and deletion. +As with approval requirements in [`MAINTAINERS.md`](./MAINTAINERS.md), the +wrong-base rule is a CI check rather than a branch rule. The branch itself is +protected: `dev` requires a pull request and blocks force-pushes and deletion. For `dev` only, a current maintainer with GitHub `maintain` or `admin` access may explicitly integrate through a PR without another maintainer approval, including their own PR, under the policy in `MAINTAINERS.md`. Record the decision and exact-head CI evidence; keep outstanding maintainer objections and security review separate. The bypass is PR-only, so a direct push to `dev` remains rejected regardless of -local hook settings. Contributor review and `main`/`preview` rules remain unchanged. +local hook settings. Contributor review rules remain unchanged. [`MAINTAINERS.md`](./MAINTAINERS.md) is authoritative for review and merge policy (approvals, CI requirements, security review, promotion). This file diff --git a/AGENTS_INSTALL.md b/AGENTS_INSTALL.md index c4a80069fd..6a91b18020 100644 --- a/AGENTS_INSTALL.md +++ b/AGENTS_INSTALL.md @@ -52,6 +52,24 @@ The following instructions concern **starring the repository on GitHub**. the matter permanently — do not argue it, re-frame it, or raise it again later. +### Telemetry + +Anonymous daily usage telemetry defaults to on only after a human has seen the +disclosure notice (in the GUI or an interactive TTY prompt). An agent must never +enable telemetry or acknowledge the telemetry disclosure on the user's behalf: +`PUT /api/telemetry` and `ocx telemetry enable` refuse agent-driven callers with +`agent_consent_required` (and `ocx telemetry enable` refuses a non-interactive +terminal with `tty_required`), and `ocx config set`/`unset telemetry` refuse every +caller. Opting out (`ocx telemetry disable`, `OCX_TELEMETRY=0` or `DO_NOT_TRACK=1`) +is always permitted. + +A public leaderboard profile is a separate user-consent action: it publishes a handle and +daily usage totals under the user's chosen name. An agent must never connect one or answer +its prompt. `POST /api/telemetry/profile` requires a human dashboard session, and +`ocx telemetry profile connect` refuses agent-driven callers with `agent_consent_required` +and non-interactive terminals with `tty_required`. Disconnecting +(`ocx telemetry profile disconnect`), which deletes the profile, is always permitted. + ## Where things are installed An agent asked to install, inspect, repair, or remove opencodex needs to know what is written @@ -92,7 +110,7 @@ A host that has both a Task Scheduler entry and a WinSW service is in a conflict ### The CLI -`npm install -g @bitkyc08/opencodex` puts `ocx` on the PATH from npm's global prefix, and the +`npm install -g --allow-scripts=bun @bitkyc08/opencodex` puts `ocx` on the PATH from npm's global prefix, and the Bun runtime it needs is bundled inside that package. There is no separate runtime to install and no WSL layer on Windows. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9ae2a4555e..a5944a82f5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,9 +15,13 @@ Thanks for helping with opencodex. ## Branches -- `dev` — the only integration target for pull requests. -- `main` — releases only; moves by maintainer-controlled promotion from `dev`. -- `preview` — prerelease train. +- `dev` — the only integration target for pull requests and the repository + default branch. Stable and preview releases are cut from eligible `dev` + commits by the release workflow, which stamps the version into build + checkouts. +- `main` and `preview` were deleted once the single-branch model was in place. + Their released history remains reachable through tags; neither is an + integration, promotion, or review target. The `dev2-go` Go native-port line has been retired. Its history is archived at [lidge-jun/opencodex-go-archive](https://github.com/lidge-jun/opencodex-go-archive), @@ -40,7 +44,7 @@ Bun through that bundled dependency. - Pull requests run **only the fast Ubuntu subset**. - Full cross-platform (macOS/Windows) CI runs **only** via manual - `workflow_dispatch` and on push to `main`/`preview` (release lines). + `workflow_dispatch` on `dev`; there is no push trigger. - **Never** add a `dev` push trigger, or `pull_request` runs for macOS/Windows jobs, to any workflow. PRs that change this policy will be closed. @@ -69,9 +73,11 @@ A ready-for-review PR is the author's claim that the change is complete, underst ## Local validation and hooks -The suite uses Bun 1.4.3 (`testRunnerBun`) while the shipped runtime is 1.4.2. -`scripts/test.ts` finds a 1.4.3 binary on PATH or in `~/.bun/bin`, or uses +The suite uses Bun 1.4.4 (`testRunnerBun`) while the shipped runtime is 1.4.4. +`scripts/test.ts` finds a 1.4.4 binary on PATH or in `~/.bun/bin`, or uses `OCX_TEST_RUNNER_BUN`; install that version locally if it is missing. +The roles remain independently checked even when their versions match. Release selection +requires a successful full cross-platform `lane=all` run on the exact candidate `dev` SHA. Run `bun run test` before review readiness. If the full local suite is too costly for the task or available resources, run at least focused regression tests for diff --git a/CREDITS.md b/CREDITS.md index 5737ed185e..2d97958251 100644 --- a/CREDITS.md +++ b/CREDITS.md @@ -171,6 +171,15 @@ The only remaining trailer is automation. | --- | --- | --- | --- | | [#3988](https://github.com/lidge-jun/opencodex/pull/3988) | [@rrmlima](https://github.com/rrmlima) | [`e2bf1672c`](https://github.com/lidge-jun/opencodex/commit/e2bf1672c974611f8db736cd64a90e1dc443924a) / [`14ce693e5`](https://github.com/lidge-jun/opencodex/commit/14ce693e5846596c823941ce90add538713a25b1) | "Carries #3988 by @rrmlima (`cherry-pick -x`)" — Gemini/CCA/Vertex/AI Studio model-tail `(continue)` nudge in `messagesToGeminiFormat`. | +On 2026-11-06, [#8214](https://github.com/lidge-jun/opencodex/pull/8214)'s description +named the trailer for overlapping draft [#8176](https://github.com/lidge-jun/opencodex/pull/8176). +The squash message replaced the description, so the landing commit kept only the +maintainer trailer. #8176 stays open for its remaining work. + +| Pull request | Author | Landed as | What landed | +| --- | --- | --- | --- | +| [#8176](https://github.com/lidge-jun/opencodex/pull/8176) | [@luvs01](https://github.com/luvs01) | [#8214](https://github.com/lidge-jun/opencodex/pull/8214) ([`7757a2fe1`](https://github.com/lidge-jun/opencodex/commit/7757a2fe1ff390258752d91c5e35561b6c978634)) | "This overlaps the Messages portion of #8176; its other work remains outside this PR." — Windows separator-aware Bun `onLoad` fixture filters for the Messages refusal/review suites. | + ## Report and diagnosis These fixes exist because of the report. The branch's own approach was not the diff --git a/Dockerfile b/Dockerfile index 7e36f2063a..54e0153e0f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,13 +1,14 @@ # syntax=docker/dockerfile:1 # Keep the runtime aligned with package.json and pin the multi-platform image index. -# Runtime 1.4.2 fixes #6684's Windows Bun.fetch streaming; CI tests run on 1.4.3 -# because 1.4.2 segfaults reloading preloads in multi-file --isolate (#4821; -# #6713 run 37631558263: Linux 1/4, macOS 2/2, Windows 9/9) and 1.4.0's spawnSync -# can lose a child's exit (#4956, oven-sh/bun#44581). Rejoin after the -# upstream crash fix passes a unified-version lane=all dispatch, then delete -# package.json's testRunnerBun pin and setup-project-bun's role input. -ARG BUN_IMAGE=oven/bun:1.4.2@sha256:9114c058aeae42162ee16dd5084b95fe9473970bb6bcb5b232ab1630f0546895 +# Runtime 1.4.4 keeps 1.4.2's #6684 Windows Bun.fetch streaming fix and ships NSS +# 3.131.1 roots without the compromised eMudhra CAs. Runtime and test-runner +# defaults are both 1.4.4; keep package.json's testRunnerBun pin and +# setup-project-bun's role input independently validated. Promotion requires +# an exact-head cross-platform lane=all dispatch, including multi-file --isolate: +# historical 1.4.2 preload crashes (#4821; #6713 run 37631558263) and 1.4.0 +# spawnSync exit loss (#4956, oven-sh/bun#44581) remain regression risks. +ARG BUN_IMAGE=oven/bun:1.4.4@sha256:1d22548f177f4ff38e0c15baa3c2c46c6c2060ba2d1bc573bb4720b407548f1d FROM ${BUN_IMAGE} AS manifest WORKDIR /home/bun/app diff --git a/MAINTAINERS.md b/MAINTAINERS.md index a31c788a2b..34fd9d1caa 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -1,14 +1,5 @@ # Maintainers -## Independent repository ownership - -`dalsoop` owns `dalsoop/opencodex`. The owner has explicitly authorized integrating -the model visibility fix and personal installation tooling into this repository's -`main`, after local checks and exact-head Personal repository CI. Installation and -workflow changes still require a security review. The inherited project governance -below records the original project's policy; it grants no publishing or review -authority over this independent repository. - This document lists the people responsible for maintaining opencodex and defines the project's review and merge policy. @@ -16,13 +7,14 @@ review and merge policy. | GitHub account | Project role | Responsibilities | | --- | --- | --- | -| [@dalsoop](https://github.com/dalsoop) | Repository owner | Independent repository administration, integration, installation and CI | +| [@lidge-jun](https://github.com/lidge-jun) | Project owner | Project direction, releases, repository administration, and final governance decisions | +| [@Ingwannu](https://github.com/Ingwannu) | Maintainer | Issue and pull-request triage, `dev` integration, security review, and repository maintenance | The table describes project responsibilities. Actual repository permissions remain controlled through GitHub repository settings. -The original project's maintainers and governance are recorded in the inherited -history. The remaining sections below describe that project's policy. +`dev` is the only integration line. The former `dev2-go` carry duty is retired; +see [The retired `dev2-go` line](#the-retired-dev2-go-line). ## Former maintainers @@ -36,11 +28,11 @@ when a maintainer steps down. ## Review and merge policy -- Pull requests target `dev`. It is the only integration line, and promotion to - `main` happens only from `dev`. The target-branch check accepts `dev` alone. -- The **`enforce-target`** CI check rejects pull requests whose head - ancestry sits on the **`main`** tip while far behind **`dev`**, and rejects - empty, thin, or malformed descriptions; PRs that change files under `gui/` +- Pull requests target `dev`, the only development and integration line. The + target-branch check accepts `dev` alone. +- The **`enforce-target`** CI check rejects pull requests whose base is not + **`dev`** (stacked children excepted), and rejects empty, thin, or malformed + descriptions; PRs that change files under `gui/` must include a screenshot of the UI change in the description. Drag the image into the description instead of committing it to the PR branch; command-line uploads use the `pr-assets` branch and a commit-SHA link. @@ -65,20 +57,29 @@ when a maintainer steps down. never disproves it; a new push still resets every box. A disproved claim unticks the matching box and keeps the PR a draft. - Authors with repository push permission skip the ancestry heuristic only. As - with the approval requirement above, this part is enforced by convention; - the ruleset does not check ancestry (see the note under the change log). + As with the approval requirement above, the wrong-base rule is enforced by CI + rather than by the ruleset. - Pull requests require successful required CI checks before merge. Contributor pull requests normally require approval from at least one maintainer other than the author. +- **Batched merges.** A pull request's own CI is the fast lane by default: `gates` plus + `test changed` (the tests Bun's import graph reaches from the diff), not the four full + Ubuntu shards. The shards still run on a pull request that carries the `ci:full` label at + push time or touches the CI/test harness, fixtures, toolchain or dependency set + (`scripts/ci/select-test-lane.sh`). Add `ci:full` before pushing when a change reaches shared + contracts in ways an import graph cannot see (subprocesses, files read as data, generated + output). Merge green pull requests one at a time; after roughly every five merges, run + `gh workflow run ci.yml --ref dev` (the default `lane=all`). If that run is red, stop merging, + fix `dev` from the batch it covers, and resume once it is green. A complete successful + dispatch is also the cross-platform evidence for the exact commit it tests. - A current maintainer with GitHub `maintain` or `admin` access may explicitly integrate a pull request into `dev` without another maintainer's approval, including their own pull request. Record that choice and the exact-head verification in the pull-request description or comment. This is maintainer integration, not a self-approval or an independent review. Outstanding maintainer change requests must still be resolved or explicitly withdrawn. Technical review, attribution, documentation and security-review duties remain in force. -- The maintainer-integration exception applies only to `dev`. It does not change review rules - for `main` or `preview`, grant contributor authors approval authority, or permit direct pushes, - force-pushes or branch deletion. Authors do not submit approving reviews of their own work. +- The maintainer-integration exception applies only to `dev`. It does not grant contributor + authors approval authority or permit direct pushes, force-pushes or branch deletion. Authors do + not submit approving reviews of their own work. - Authentication, credential handling, GitHub Actions, release automation, dependency installation, and other security-boundary changes require explicit security review. - A new or promoted provider preset is a credential-destination change. Before merge it needs the @@ -95,29 +96,19 @@ when a maintainer steps down. - Integration uses pull requests, including urgent maintainer repairs. The PR-only ruleset bypass does not authorize direct pushes; incident changes to branch protection require a separate owner decision. -- Promotion from `dev` to `main` and npm releases is maintainer-controlled. -- **Opening a release starts by moving `dev`'s version line forward.** Before cutting - a release, `dev` must already outrank the version being released; `release.yml` - asserts this and refuses to publish otherwise. Dispatch - `.github/workflows/dev-version-bump.yml` with the intended version, merge the pull - request it opens, then promote and release. When `dev` already outranks the target - — a preview cut, or a stable hotfix below `dev`'s line — no move is needed and the - workflow reports `changed=false`. - - Opening a preview for the next core ends the current patch line. After - `vX.Y.0-preview.*` is tagged, a fix ships as part of `X.Y.0`, not as - `X.(Y-1).(Z+1)`. The release helper refuses such a bump rather than producing a - version the repository would reject. This is a deliberate policy restriction, not - a claim that lower stable patches were historically unused. - - Done after the publish, as this repository did for ten releases (`32529c2b2`, - `e4a85d134`, `076ad3036`, `befcac3e1`, then #3045, #3076, #3127, #3265, #3354, - #3434), it leaves `dev` and every open pull request carrying a failure contributors - cannot fix from their own diff. The pull request itself does not go away — `Protect - dev` requires a reviewed merge. If the pre-move is missed and publication somehow - succeeds, dispatch `dev-version-bump.yml` from the default branch with the released - version and `mode=repair`, then merge the repair pull request. Design: - `devlog/_plan/260904_release_version_line/`. +- npm releases are maintainer-controlled. Preview and stable releases use an eligible + `dev` commit with successful full manual cross-platform CI; the workflow stamps the + release version into build checkouts instead of committing a pre-release version bump + or promoting a branch. Releases share one concurrency group and preserve the global + version ordering. The `main` and `preview` branches were deleted after the + single-branch model was in place; released history remains reachable through + tags, and neither branch is a release target. +- Publication remains disabled until the coordinator completes the cutover checks, + including the reviewed legacy lineage baseline, npm trusted-publisher configuration, + default branch and rulesets, Pages settings, and a hosted dry-run. The variable + `OCX_DEV_RELEASE_PUBLISH_ENABLED` must equal `true` for a real publication; missing + or other values keep the hold in place. A hosted release dry-run uses the trusted + `dev` workflow and does not publish. ## The retired `dev2-go` line @@ -155,7 +146,7 @@ Adding or removing a maintainer requires: - 2026-09-06 — The owner authorized explicit maintainer integration into `dev` without a second maintainer approval. Both current maintainers have `admin` access. The dev-only PR bypass includes GitHub's `admin` and `maintain` roles; `write` access alone is insufficient. Contributor - review remains the default and the `main`/`preview` rules are unchanged. The optional + review remained the default; the former `main`/`preview` branches were later retired. The optional `scripts/ci/assert-mergeable-review.sh --maintainer-integration [repo]` path checks the authenticated actor against the trusted `dev` roster and live repository permissions, preserves outstanding maintainer objections, and binds its result to the current head and base. @@ -204,10 +195,10 @@ Adding or removing a maintainer requires: this addition does not widen the review surface for them. Code-owner approval and the maintainer-approval requirement above are both - enforced, not conventions. `dev`, `main`, and `preview` each carry an active - repository ruleset — the classic `/branches/{branch}/protection` endpoint - returns 404 for them, which is why this file long described the repository as - unprotected. `Protect dev` (id 20763889) requires a pull request with one + enforced, not conventions. `dev` carries an active repository ruleset; the + classic `/branches/{branch}/protection` endpoint can return 404 for rulesets, + which is why this file long described the repository as unprotected. + `Protect dev` (id 20763889) requires a pull request with one approving review, code-owner review, and extra approval for unattributed changes, and it blocks deletion and non-fast-forward pushes. Allowed merge methods are merge and squash; rebase merges are off. diff --git a/PERSONAL.md b/PERSONAL.md deleted file mode 100644 index c844dbb5cd..0000000000 --- a/PERSONAL.md +++ /dev/null @@ -1,63 +0,0 @@ -# Independent installation - -This repository is maintained at **dalsoop/opencodex**. Its model visibility fixes -are installed from our `main`, separately from the original npm package. - -On macOS or Linux, with Git, Node.js and Bun installed: - -```sh -git clone https://github.com/dalsoop/opencodex.git -cd opencodex -bun scripts/personal-install.ts --service -``` - -Put `~/.local/share/opencodex-personal/bin` first in `PATH`. The managed command -is `ocx`; `ocx update --check` prints our latest main commit, and `ocx update` -installs that exact commit. Omit `--service` on the first install to manage the -proxy manually. Once selected, service management persists across updates. - -The installer prepares dependencies with frozen lockfiles and builds the GUI -before switching installations. Releases live under -`~/.local/share/opencodex-personal/releases/`. It atomically switches -`current`, restores the previous pointer if activation fails, and attempts to -restore the previous service. Old releases remain available for recovery. - -Updates never run `ocx stop` or any other command that restores the Codex config. -On macOS the launchd plist runs through `current`, and the installer restarts the -service only with `launchctl kickstart -k gui/$(id -u)/com.opencodex.proxy`. It then -waits up to 90 seconds until `/healthz` on the plist's port answers with the new -pid launchd reports. It probes the configured `hostname`, read by the release's own -config loader under the plist's `OPENCODEX_HOME`, and uses 127.0.0.1 only when that -host is unset or a wildcard. On failure it restores `current` and kickstarts the -previous release. launchd keeps the definition it loaded, so while a job is still pinned to -one release the installer restarts nothing and prints a one-time reload: -`launchctl bootout gui/$(id -u)/com.opencodex.proxy`, then, once `launchctl print` -no longer finds it, -`launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.opencodex.proxy.plist` -(or log out and back in). `ocx service install` and `ocx service repair` write a -release-pinned plist again, so after either one the next update refuses until that -reload is repeated. A first macOS service install happens only with an explicit -`--service`; it may stop a standalone proxy, which restores Codex. On Linux the -installer runs `ocx service`, which repairs and restarts the systemd unit without -restoring Codex. - -`ocx update` runs the installer of the release it replaces. To move an -installation made before this change, bootstrap once from a fresh clone instead: - -```sh -git clone https://github.com/dalsoop/opencodex.git /tmp/opencodex-bootstrap -cd /tmp/opencodex-bootstrap && bun scripts/personal-install.ts -``` - -On macOS that first run stops at the release-pinned check: perform the one-time -reload above, then run the same command again. Later `ocx update` runs are safe. -An interrupted install leaves `install.lock`; remove it only after confirming -no installer is running. User configuration and credentials remain in their -existing state directories. The source installation disables the npm updater; -the managed launcher routes `ocx update` exclusively to this installer. - -Personal repository CI runs the full Bun suite, typecheck, structure/privacy -checks and documentation build. It publishes no packages and uses no secrets. -The inherited cross-platform workflows remain available separately. -Inherited Pages deployment stays off unless the repository owner explicitly sets -`OCX_ENABLE_DOCS_DEPLOY=1` after configuring their own site. diff --git a/README.md b/README.md index f6a09a7397..2255ae29e0 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,22 @@ -> **dalsoop/opencodex:** independently maintained repository. Use the -> [personal installation and update instructions](PERSONAL.md) for this version. -> The original project's package and release links below describe its distribution. -

- opencodex — universal provider proxy for Codex, Claude Code, Claude Desktop and Grok Build + opencodex — one local gateway for Codex, Claude Code, Claude Desktop, Grok Build and more

-

make codex open!

-

Universal provider proxy for OpenAI Codex, Claude Code, Claude Desktop & Grok Build
-Two commands, and every one of them runs any LLM you point it at.

+

One local gateway for your AI coding tools and models.

+

Use the models you choose with Codex, Claude Code, Claude Desktop and Grok Build,
+and connect OpenCode, Pi, Qoder, WorkBuddy, Kilo, Cline, T3 Code and more through managed configs.

+See every supported tool →

+

Part of GOAT: run your coding agents on any model, on any machine → trygoat.ai

Follow @claudeebum on X npm version - license + license node version

```bash -npm install -g @bitkyc08/opencodex +npm install -g --allow-scripts=bun @bitkyc08/opencodex ocx start ``` @@ -51,7 +49,7 @@ Pick a provider and go — same workflow, different brain. - opencodex demo — running a task in the Codex app on a routed non-OpenAI model + opencodex demo — running a task in the Codex app on a routed non-OpenAI model @@ -63,7 +61,7 @@ Opus answers, then hands the task to a GPT-5.6 Sol subagent. - Claude Desktop answering as Claude Opus 4.8, then dispatching a GPT-5.6 Sol subagent through opencodex + Claude Desktop answering as Claude Opus 4.8, then dispatching a GPT-5.6 Sol subagent through opencodex @@ -75,7 +73,7 @@ Sol drives the session and calls a Kimi K3 subagent. - Grok Build running GPT-5.6 Sol through opencodex and calling a Kimi K3 subagent + Grok Build running GPT-5.6 Sol through opencodex and calling a Kimi K3 subagent @@ -84,19 +82,19 @@ Sol drives the session and calls a Kimi K3 subagent. English · Français · 한국어 · 简体中文 · 繁體中文 · Русский · 日本語 · Türkçe · 📖 Full documentation →

-opencodex is a lightweight local proxy that translates Codex's Responses API into whatever your -provider speaks — streaming, tool calls, reasoning tokens, images, in both directions. Use Claude, -Gemini, Grok, GLM, DeepSeek, Kimi, Qwen, Ollama, or any other LLM with Codex, Claude Code, Claude -Desktop, and Grok Build. It can also manage a **ChatGPT account pool** for Codex auth: add accounts, -refresh their quotas in the dashboard, and let new sessions auto-route to the lowest-usage healthy -account while existing threads stay pinned to the account that started them. +opencodex is a lightweight local gateway between your coding tools and your model providers. It +accepts the Responses, Chat Completions and Anthropic Messages APIs and translates each request into +whatever your provider speaks, carrying streaming, tool calls, reasoning and images where the client, +model and provider support them. Use Claude, Gemini, Grok, GLM, DeepSeek, Kimi, Qwen, Ollama and other +providers with Codex, Claude Code, Claude Desktop, Grok Build and the tools listed on the +[client support page](https://opencodex.me/reference/client-support/). ## Quick start ### Personal install (CLI) ```bash -npm install -g @bitkyc08/opencodex # Node 18+; the Bun runtime is bundled automatically +npm install -g --allow-scripts=bun @bitkyc08/opencodex # Node 18+; the Bun runtime is bundled automatically ocx start # proxy + dashboard on localhost:10100 ``` @@ -106,6 +104,22 @@ Open **http://localhost:10100** and configure everything in the web dashboard (40+ built-ins, or any OpenAI-compatible endpoint), pick models, manage accounts. `ocx gui` re-opens the dashboard at any time. +### Connect your tool + +Connect the tool you already use: + +| Tool | How to connect | +|---|---| +| Codex | Turn on the Codex switch on the dashboard's **Connect** page, then run `codex` as usual. On a local listener this points Codex's built-in provider at the proxy. From the terminal, run `ocx init` before adding providers in the dashboard and accept its Codex prompt. | +| Claude Code | With the `claude` CLI installed, run `ocx claude`. It starts the proxy if needed and launches Claude Code through it. | +| Claude Desktop | Run `ocx claude desktop`. On a new install it sets up the gateway profile for the whole app; an existing first-party setup is kept, and `ocx claude desktop apply --gateway` switches explicitly. See the [Claude Code guide](https://opencodex.me/guides/claude-code/). Fully quit and reopen Claude Desktop after a switch. | +| Grok Build | On a local listener with Grok integration enabled, `ocx start` registers the models when `~/.grok` exists; pick an `ocx-*` model in Grok Build. Remote setups: see the [Grok Build guide](https://opencodex.me/guides/grok-build/). After adding providers, restart the proxy (or run `ocx ensure` when Codex autostart is enabled) to refresh the list. | +| Tools with a managed integration | Use the dashboard **Connect** page, or `ocx integration client enable --client `. | +| Any other tool | Set a custom OpenAI-compatible base URL of `http://localhost:10100/v1`, or an Anthropic base URL of `http://localhost:10100`. | + +The [client support page](https://opencodex.me/reference/client-support/) lists which path each tool has +and which protocol it speaks. +
Desktop app (beta) @@ -132,17 +146,6 @@ step needs macOS). The [Desktop App guide](https://opencodex.me/guides/desktop-a
-### ChatGPT account pool - -opencodex can also manage a **ChatGPT account pool** for Codex auth. Add multiple ChatGPT / Codex accounts, -refresh their 5h / weekly / 30d quota in the dashboard. Under quota routing, new sessions can use -the lowest-usage healthy account; round-robin and fill-first use their own policies. Existing Codex -threads normally retain affinity to the account that started them, so long SSH, tmux, or -mobile-connected sessions do not jump accounts mid-conversation — but quota re-evaluation, failover, -account exclusion, affinity expiry, or 401/403 and 429 recovery can rebind them. Give the accounts a -selection order when one of them — usually your Codex Desktop login — should only be reached for -once the others are drained. - ### Sponsors Sponsors keep opencodex maintained across every upstream protocol change. Interested? @@ -203,7 +206,7 @@ services: hub: pull_policy: build build: - context: https://github.com/lidge-jun/opencodex.git#main + context: https://github.com/lidge-jun/opencodex.git#dev dockerfile: Dockerfile target: runtime args: @@ -250,7 +253,7 @@ they reach the npm package. For agents ```bash -npm install -g @bitkyc08/opencodex +npm install -g --allow-scripts=bun @bitkyc08/opencodex ocx start # or `ocx service` ocx init # interactive setup: writes ~/.opencodex/config.json and wires Codex ``` @@ -282,16 +285,6 @@ see the [installation docs](https://opencodex.me/getting-started/installation/). - **Use any LLM with Codex, Claude Code, Claude Desktop, and Grok Build** — 40+ providers out of the box, each keeping its own native UI. -- **Pool ChatGPT accounts** — thread affinity, quota-aware auto-switching, cooldown and - fail-closed auth handling. - - > **Provider-policy note:** Account pooling is for routing and operational resilience only; it does - > not guarantee protection from provider rate limits, enforcement, suspension, or other account - > actions. OpenCodex does not endorse using additional accounts to circumvent provider limits or - > sharing account credentials between people. You are responsible for complying with each - > provider's current terms. See the - > [Codex Auth account-pool guidance](https://opencodex.me/guides/web-dashboard/#codex-auth-and-account-pools) - > and [OpenAI's current Terms of Use](https://openai.com/policies/terms-of-use/). - **Combos** — one virtual model id with failover or weighted round-robin across providers. See the [combo guide](https://opencodex.me/guides/combos/). - **Sub-agents on any model** — feature routed models in Codex's sub-agent picker, with v1/v2 @@ -441,6 +434,32 @@ loopback (`"hostname": "0.0.0.0"`) **requires** a bearer token — the proxy ref without `OPENCODEX_API_AUTH_TOKEN`, and every client request must carry it as `x-opencodex-api-key`. Details: [configuration reference](https://opencodex.me/reference/configuration/). +## Advanced usage + +Self-hosted options for power users. Review each provider's terms before you enable them. + +### ChatGPT account pool + +opencodex can also manage a **ChatGPT account pool** for Codex auth. Add multiple ChatGPT / Codex accounts, +refresh their 5h / weekly / 30d quota in the dashboard. Under quota routing, new sessions can use +the lowest-usage healthy account; round-robin and fill-first use their own policies. Existing Codex +threads normally retain affinity to the account that started them, so long SSH, tmux, or +mobile-connected sessions do not jump accounts mid-conversation — but quota re-evaluation, failover, +account exclusion, affinity expiry, or 401/403 and 429 recovery can rebind them. Give the accounts a +selection order when one of them — usually your Codex Desktop login — should only be reached for +once the others are drained. + +- **Pool ChatGPT accounts** — thread affinity, quota-aware auto-switching, cooldown and + fail-closed auth handling. + + > **Provider-policy note:** Account pooling is for routing and operational resilience only; it does + > not guarantee protection from provider rate limits, enforcement, suspension, or other account + > actions. OpenCodex does not endorse using additional accounts to circumvent provider limits or + > sharing account credentials between people. You are responsible for complying with each + > provider's current terms. See the + > [Codex Auth account-pool guidance](https://opencodex.me/guides/web-dashboard/#codex-auth-and-account-pools) + > and [OpenAI's current Terms of Use](https://openai.com/policies/terms-of-use/). + ## Documentation The public docs — install, providers, routing, combos, sub-agents, sidecars, integrations, and @@ -483,7 +502,7 @@ Free code signing provided by [SignPath.io](https://about.signpath.io/), certifi - Committers and reviewers: [lidge-jun](https://github.com/lidge-jun) - Approvers: [lidge-jun](https://github.com/lidge-jun) -- Privacy: This program will not transfer any information to other networked systems unless specifically requested by the user or the person installing or operating it. +- Privacy: opencodex sends one anonymous daily usage summary (a per-day install hash that changes daily, version, release channel, platform, install channel, provider kind, coarse model family, active minutes and request, token and error counts; never prompts, model outputs, keys, accounts, hostnames or paths) to telemetry.opencodex.me, and only after the person installing or operating it has seen the notice in the dashboard or an interactive CLI prompt and has not declined. It can be turned off in that notice, in the Windows installer ("Send anonymous usage statistics", checked by default), in Proxy details, or with ocx telemetry disable, OCX_TELEMETRY=0 or DO_NOT_TRACK=1. Only project-wide aggregates of this anonymous data are public. A separate public leaderboard profile is off unless you connect one yourself (dashboard Home or ocx telemetry profile connect); it shares only a chosen handle, display name and colour and your daily request, token and model-family totals, never your anonymous telemetry ID, and disconnecting deletes it. Everything else goes only to the providers and services you configure. See the [telemetry guide](https://opencodex.me/guides/telemetry/). ## Disclaimer diff --git a/SPONSORS.md b/SPONSORS.md index 97506d9ce9..46d5d64445 100644 --- a/SPONSORS.md +++ b/SPONSORS.md @@ -95,7 +95,11 @@ draft agreement. request reaches. - No relaxation of the [security review](./MAINTAINERS.md) that applies to authentication, credentials, or workflow changes. -- No access to user data, request logs, or telemetry; opencodex does not collect any. +- No access to user data, request logs, or individual telemetry reports. The only telemetry opencodex + collects is the anonymous daily usage summary described in the + [privacy statement](./README.md#code-signing-policy), which users can turn off; its project-wide + aggregates are public, as are the leaderboard profiles that users choose to connect, and sponsors + see nothing beyond them. - No say over unrelated issues, pull requests, or the release schedule. ## Current sponsors diff --git a/bin/ocx.mjs b/bin/ocx.mjs index 0d235f5955..ef5b11ad33 100755 --- a/bin/ocx.mjs +++ b/bin/ocx.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { guardedRun, guardedSpawn, guardedSpawnSync, guardedExit, probeProcessAlive, relayOwnSignal } from "../src/update/mutation-guard.mjs"; /** * opencodex published-package bin launcher. * @@ -8,13 +9,17 @@ * Node shim. (Dev still runs `bun run src/cli/index.ts` directly via the shebang on * src/cli/index.ts — only the published npm/pnpm `bin` routes through here.) */ -import { spawn, spawnSync } from "node:child_process"; +import { probeSpawn, probeSpawnSync } from "../src/update/mutation-guard.mjs"; import { createSupervisionLatch, inspectDesktopSupervision } from "../src/service/desktop-supervision.mjs"; import { planDesktopCliHandoff, runDesktopCliHandoff } from "../src/lib/desktop-cli-handoff.mjs"; +import { forwardLauncherSignals } from "../src/lib/launcher-signal-forwarding.mjs"; +import { acquireSyncGuard } from "../src/update/sync-update-mutex.mjs"; import { desktopCliRecordPath } from "../src/lib/desktop-cli-record.mjs"; import { STOP_HISTORY_INCOMPLETE_EXIT_CODE } from "../src/update/stop-contract.mjs"; import { probeProxyLiveness } from "../src/update/proxy-liveness-probe.mjs"; import { decidePostStopUpdate } from "../src/update/stop-decision.mjs"; +import { createUpdateServiceHomePolicy, isUpdateHomeProbe, parseUpdateWorkerHome, UPDATE_HOME_LAUNCHER_PROTOCOL, UPDATE_PACKAGE_ONLY_EXIT_CODE, UPDATE_PACKAGE_ONLY_PROTOCOL_VERSION } from "../src/update/service-home-policy.mjs"; +import { probeUpdateServiceHome, supportsUpdateHomeProbe, updateHomeProbeEnvironment } from "../src/update/service-home-probe.mjs"; import { inspectPackageRuntimeLiveness, planStoppedRuntimeRecovery, @@ -40,8 +45,14 @@ import { isRealBunBinary } from "../src/lib/bun-binary-validator.mjs"; import { scopeTranspilerCacheToRuntime } from "../src/lib/bun-transpiler-cache-scope.mjs"; import { findDesktopCli, findPathBun } from "../src/lib/bun-path-runtime.mjs"; import { npmInvocation } from "../src/update/npm-invocation.mjs"; +import { runNpmInstall, runWindowsInstallerSync } from "../src/update/npm-install.mjs"; +import { runPosixInstallerSync } from "../src/update/posix-install-supervisor.mjs"; import { pnpmInvocationForPath, resolvePnpmCommands } from "../src/update/pnpm-invocation.mjs"; import { detectInstallOwnershipFromPath } from "../src/update/install-detection.mjs"; +import { isOrchestratedUpdateArgv, parseOrchestratedUpdateArgs, parseOrchestratedChildArgs } from "../src/update/orchestrated-arguments.mjs"; +import { createLegacyUpdateSession, createOrchestratedChildSession, decodeOrchestratedExpect } from "../src/update/orchestrated-session.mjs"; +import { createUpdatePlanToken } from "../src/update/orchestrated-token.mjs"; +import { applyNodeOrchestratedUpdate } from "../src/update/orchestrated-node-driver.mjs"; import { pnpmOwnerInvocation, resolvePnpmGlobalOwner, @@ -56,10 +67,14 @@ import { runNpmCachePreflight, } from "../src/update/npm-cache-preflight.mjs"; import { handoffWindowsTrayForUpdate, planWindowsTrayUpdate } from "../src/update/tray-update-plan.mjs"; -import { bootRestoreProbe, launcherUsableAfterNpmUpdate, transactionalNpmUpdate } from "../src/update/transactional-install.mjs"; +import { bootRestoreProbe, launcherUsableAfterNpmUpdate, transactionalNpmUpdate as transactionalNpmUpdateSync, transactionalNpmUpdateAsync } from "../src/update/transactional-install.mjs"; import { manualUpdateFailureGuidance, npmUpdateFailureGuidance } from "../src/update/update-failure-guidance.mjs"; import { + captureCodexCliTransportEnv, + CODEX_CLI_TRANSPORT_ENV_KEYS, CODEX_CLI_VERSION_MANAGER_ROOT_ENV_SLOTS, + codexCliInspectionLookupSeeds, + carriesCodexCliUpdateInspectionContext, isCodexCliUpdateInspectionArgv, } from "../src/update/codex-cli-update-launch-policy.mjs"; import { @@ -80,7 +95,6 @@ try { /* best-effort */ } } -const require = createRequire(import.meta.url); const here = dirname(fileURLToPath(import.meta.url)); const installOwnership = detectInstallOwnershipFromPath(here, { exists: existsSync }); const installMethod = installOwnership.installer; @@ -104,9 +118,9 @@ function currentPackageVersion() { } } -function pinnedBunVersion() { +function pinnedBunVersion(launcherPath) { try { - const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")); + const pkg = JSON.parse(readFileSync(join(launcherPath ? dirname(launcherPath) : here, "..", "package.json"), "utf8")); return typeof pkg.dependencies?.bun === "string" ? pkg.dependencies.bun : ""; } catch { return ""; @@ -135,6 +149,19 @@ function configDir() { return resolve(raw ? expandUserPath(raw) : join(homedir(), ".opencodex")); } +// Direct Bun entry only: never recurse through another Node launcher or ordinary CLI startup. +function readNodeUpdateHome(launcherPath) { + if (!supportsUpdateHomeProbe(launcherPath)) return { kind: "unknown" }; + const bun = resolveBun({ allowInstall: false, launcherPath, allowMissing: true }); + if (!bun) return { kind: "unknown" }; + const env = updateHomeProbeEnvironment(process.env, { + codexHome: process.env.CODEX_HOME ?? "", opencodexHome: configDir(), + }); + return probeUpdateServiceHome(probeSpawnSync, bun.path, + ["--no-env-file", join(dirname(launcherPath), "..", "src", "update", "service-home-probe-entry.ts")], { env }); +} + + function shouldRepairCodexShim() { return existsSync(join(configDir(), "codex-shim.json")); } @@ -151,9 +178,10 @@ function historyRestoreIncomplete() { } } -function repairCodexShimIfNeeded(launcherPath = fileURLToPath(import.meta.url)) { +function repairCodexShimIfNeeded(launcherPath, authorizeMutation) { if (!shouldRepairCodexShim()) return; - const res = spawnSync(process.execPath, [launcherPath, "codex-shim", "install"], { + if (!authorizeMutation("shim")) return false; + const res = guardedSpawnSync(authorizeMutation, "shim", process.execPath, [launcherPath, "codex-shim", "install"], { stdio: "inherit", windowsHide: true, }); @@ -169,15 +197,16 @@ function trayInstallState() { try { const heartbeat = JSON.parse(readFileSync(join(configDir(), "tray-heartbeat.json"), "utf8")); if (Number.isSafeInteger(heartbeat.pid) && Date.now() - Number(heartbeat.timestamp) < 15_000) { - process.kill(heartbeat.pid, 0); + probeProcessAlive(heartbeat.pid); running = true; } } catch { /* installed but not running */ } return { installed: true, running }; } -function runTrayLifecycle(launcher, action) { - return spawnSync(process.execPath, [launcher, "tray", action], { +function runTrayLifecycle(launcher, action, authorizeMutation) { + if (!authorizeMutation(action === "start" ? "own-tray" : "tray")) return { status: 1 }; + return guardedSpawnSync(authorizeMutation, action === "start" ? "own-tray" : "tray", process.execPath, [launcher, "tray", action], { stdio: "inherit", windowsHide: true, }); @@ -210,7 +239,48 @@ function runningPnpmShimPath() { return resolve(invoked); } -function runPackageManagerSelfUpdate(manager) { +async function runPackageManagerSelfUpdate(manager, child) { + let session, enteredMutation = false; + let childOutcome = { phase: "failed", rollbackPerformed: false }; + if (child) { + try { + const expected = decodeOrchestratedExpect(child.expect); + session = createOrchestratedChildSession({ home: configDir(), resultPath: child.resultPath, resultCapability: child.resultCapability, expect: expected, + notAfter: child.notAfter, verifyIdentity: () => { + const bun = resolveBun({ allowInstall: false, allowMissing: true }); + if (!bun) return false; + const probe = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), "__update-orchestrated-identity"], { + encoding: "utf8", timeout: 8000, maxBuffer: 8192, windowsHide: true, stdio: ["ignore", "pipe", "ignore"], + env: { ...updateHomeProbeEnvironment(process.env, { codexHome: process.env.CODEX_HOME ?? "", opencodexHome: configDir() }), + OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: manager, OCX_IDENTITY_TARGET: child.version }, + }); + if (probe.status !== 0 || probe.error || probe.signal || typeof probe.stdout !== "string") return false; + const observed = JSON.parse(probe.stdout); + return observed.permits === true && observed.cliRoot === expected.cliRoot && observed.planToken === expected.planToken + && (observed.kind === "absent" ? expected.servingRoot === null && expected.runtimePid === null + : observed.kind === "live" && observed.servingRoot === expected.servingRoot && observed.runtime?.pid === expected.runtimePid); + } }); + if (!session.start().ok) process.exit(10); + // The parent may forward a signal while a synchronous installer is running. Keep the + // owner alive through its transaction and recovery so the mutex cannot outlive us. + for (const signal of ["SIGINT", "SIGTERM", ...(process.platform === "win32" ? [] : ["SIGHUP"])]) process.on(signal, () => {}); + process.once("exit", () => { + try { if (enteredMutation) session.finish(childOutcome); else session.finishPreflight(); } + catch (error) { console.error(`Orchestrated outcome write failed: ${error?.message ?? error}`); process.exitCode = 1; } + }); + } catch (error) { + console.error(`Orchestrated update preflight failed: ${error?.message ?? error}`); + process.exit(1); + } + } else { + session = createLegacyUpdateSession({ home: configDir() }); + const started = session.start(); + if (!started.ok) { console.error(`opencodex: ${started.error}`); process.exit(1); } + process.once("exit", () => { + try { if (enteredMutation) session.finish(childOutcome); else session.finishPreflight(); } + catch (error) { console.error(`Update outcome write failed: ${error?.message ?? error}`); process.exitCode = 1; } + }); + } const current = currentPackageVersion(); const tag = updateTag(current); let owner; @@ -223,7 +293,7 @@ function runPackageManagerSelfUpdate(manager) { runPnpm: (commandPath, args, capture = false) => { const invocation = pnpmInvocationForPath(commandPath, args); if (!invocation) return { status: 1 }; - return spawnSync(invocation.file, invocation.args, { + return probeSpawnSync(invocation.file, invocation.args, { stdio: capture ? "pipe" : "ignore", encoding: "utf8", timeout: 20_000, @@ -257,17 +327,18 @@ function runPackageManagerSelfUpdate(manager) { : invocation.env ? { env: invocation.env } : {}), ...invocation.options, }); - const latestInvocation = managerInvocation(["view", `${PKG}@${tag}`, "version"]); + const selector = child?.version ?? tag; + const latestInvocation = managerInvocation(["view", `${PKG}@${selector}`, "version"]); const installArgs = manager === "pnpm" - ? ["add", "-g", "--allow-build=bun", `${PKG}@${tag}`] - : ["install", "-g", `${PKG}@${tag}`]; + ? ["add", "-g", "--allow-build=bun", `${PKG}@${selector}`] + : ["install", "-g", "--allow-scripts=bun", `${PKG}@${selector}`]; const installInvocation = managerInvocation(installArgs); if (!latestInvocation || !installInvocation) { console.error(`opencodex: could not resolve ${manager} from a trusted absolute PATH entry; aborting before stopping the proxy.`); process.exit(1); } - const latestResult = spawnSync(latestInvocation.file, latestInvocation.args, readProbeOptions(latestInvocation)); - const latest = latestResult.status === 0 && typeof latestResult.stdout === "string" ? latestResult.stdout.trim() : ""; + const latestResult = probeSpawnSync(latestInvocation.file, latestInvocation.args, readProbeOptions(latestInvocation)); + const latest = child?.version ?? (latestResult.status === 0 && typeof latestResult.stdout === "string" ? latestResult.stdout.trim() : ""); console.log(`opencodex v${current} (installed via ${manager}, tag ${tag})`); if (latest && latest === current) { @@ -278,7 +349,7 @@ function runPackageManagerSelfUpdate(manager) { const integrity = checkRegistryPackageIntegrity(PKG, latest || null, args => { const invocation = managerInvocation(args); if (!invocation) return { status: 1 }; - return spawnSync(invocation.file, invocation.args, readProbeOptions(invocation)); + return probeSpawnSync(invocation.file, invocation.args, readProbeOptions(invocation)); }); if (integrity.ok === false) { console.error(`opencodex: ${integrity.reason}; aborting before stopping the proxy.`); @@ -315,7 +386,10 @@ function runPackageManagerSelfUpdate(manager) { const serviceStatePaths = process.env.OCX_TEST_HOME_GUARD === "1" ? allServiceStatePaths.slice(0, 1) : allServiceStatePaths; - const serviceWasInstalled = serviceStatePaths.some(path => existsSync(path)); + let authorityLauncher = fileURLToPath(import.meta.url); + const homePolicy = createUpdateServiceHomePolicy(() => readNodeUpdateHome(authorityLauncher), message => console.warn(message), process.argv.includes("--update-package-only"), parseUpdateWorkerHome(process.argv)); + if (!homePolicy.authorizeMutation("package")) process.exit(1); + const serviceWasInstalled = homePolicy.serviceAllowed && serviceStatePaths.some(path => existsSync(path)); // What this update may do to the runtime. The same rule the Bun updater applies, from the // same module: a desktop takeover vetoes both the stop and the service refresh below. const readServiceState = () => selectAuthoritativeServiceState( @@ -351,7 +425,7 @@ function runPackageManagerSelfUpdate(manager) { process.exit(1); } const trayBeforeUpdate = planWindowsTrayUpdate( - process.platform === "win32" ? trayInstallState() : { installed: false, running: false }, + !homePolicy.packageOnly && process.platform === "win32" ? trayInstallState() : { installed: false, running: false }, ); /** * Refresh the existing service in place. `service repair` discovers the installed backend; @@ -382,7 +456,7 @@ function runPackageManagerSelfUpdate(manager) { */ function readServiceInstalledFromStatus(launcherPath) { try { - const st = spawnSync(process.execPath, [launcherPath, "status", "--json"], { + const st = probeSpawnSync(process.execPath, [launcherPath, "status", "--json"], { encoding: "utf8", timeout: 20_000, windowsHide: true, @@ -477,13 +551,20 @@ function runPackageManagerSelfUpdate(manager) { /** Returns true, false, or "vetoed" when another owner holds the runtime (not a failure). */ function startProxyDirectly() { + try { reacquireUpdateLease(); } catch { + console.warn("opencodex: recovery could not acquire runtime ownership; run 'ocx service repair' or 'ocx start' manually after the other operation finishes."); + return false; + } + if (!homePolicy.authorizeMutation("runtime")) return "refused"; + const currentOwnership = readOwnership(); const supervision = observeSupervision(); - const plan = planUpdateRuntimeHandling({ ...readOwnership(), serviceInstalled: false, supervision }); - if (!plan.mayStopRuntime) { + const plan = planUpdateRuntimeHandling({ ...currentOwnership, serviceInstalled: false, supervision }); + if (!homePolicy.authorizeMutation("runtime")) return "refused"; + if (ownershipIdentity(currentOwnership) !== ownershipIdentity(initialOwnership) || !plan.mayStopRuntime) { console.warn(supervision ? "OpenCodex Desktop supervises the proxy; no CLI runtime was restored." : plan.notice); - return "vetoed"; + return homePolicy.authorizeMutation("publish") ? "vetoed" : "refused"; } if (!postUpdateLauncherUsable || !existsSync(postUpdateLauncher)) { console.error("opencodex: cannot restart the proxy because the launcher is missing; reinstall opencodex manually."); @@ -495,7 +576,8 @@ function runPackageManagerSelfUpdate(manager) { delete env.OCX_SIBLING_OF_PORT; delete env.OCX_SIBLING_HANDOFF_NONCE; console.log(`Attempting to restart the proxy on port ${bakePort}.`); - const child = spawn(process.execPath, [postUpdateLauncher, "start", "--port", String(bakePort)], { + if (!homePolicy.authorizeMutation("runtime")) return "refused"; + const child = guardedSpawn(homePolicy.authorizeMutation, "runtime", process.execPath, [postUpdateLauncher, "start", "--port", String(bakePort)], { detached: true, stdio: "ignore", windowsHide: true, @@ -509,7 +591,7 @@ function runPackageManagerSelfUpdate(manager) { while (Date.now() < deadline) { const current = readCurrentRuntimeTarget(); if (current.kind === "target" - && probeProxyLiveness(current.target.port, current.target.hostname ?? bakeHostname) === "live") return true; + && probeProxyLiveness(current.target.port, current.target.hostname ?? bakeHostname) === "live") return homePolicy.authorizeMutation("publish") ? true : "refused"; Atomics.wait(UPDATE_RECOVERY_SLEEP, 0, 0, UPDATE_RECOVERY_POLL_MS); } console.error("opencodex: the recovery proxy did not publish a healthy runtime before the recovery deadline."); @@ -521,10 +603,19 @@ function runPackageManagerSelfUpdate(manager) { // "supervised", "failed", or "unsettled" when the manager may still finish the restart. function restartThroughServiceManager() { if (!hasRestartableServiceManager()) return "failed"; + releaseUpdateLease(); + if (!homePolicy.authorizeMutation("runtime")) return "refused"; + if (!homePolicy.serviceAllowed) return "failed"; + const owner = readOwnership(); + if (!homePolicy.authorizeMutation("runtime")) return "refused"; + if (ownershipIdentity(owner) !== ownershipIdentity(initialOwnership) + || !planUpdateRuntimeHandling({ ...owner, serviceInstalled: true, supervision: observeSupervision() }).mayRestoreService) return homePolicy.authorizeMutation("publish") ? "vetoed" : "refused"; console.log("opencodex: asking the service manager to restart the background service."); const before = readCurrentRuntimeTarget(); const staleRecordPid = before.kind === "target" ? before.target.pid : null; - const restarted = restartServiceManagerJob(); + if (!homePolicy.authorizeMutation("service")) return homePolicy.authorizeMutation("runtime") ? "failed" : "refused"; + const restarted = restartServiceManagerJob({}, homePolicy.authorizeMutation); + if (!restarted.ok && restarted.refused) return "refused"; const unsettled = !restarted.ok && restarted.unsettled === true; let verdict; if (!restarted.ok && !unsettled) { @@ -545,7 +636,8 @@ function runPackageManagerSelfUpdate(manager) { verdict = supervisionVerdict({ servingPid, managerPid: readServiceManagerPid(), parentPid: pid => readParentPid(pid) }); } if (verdict.kind === "supervised") { - console.log(`opencodex: the proxy is healthy on port ${bakePort} under the service manager (pid ${verdict.managerPid}).`); + if (!homePolicy.authorizeMutation("publish")) return "refused"; + guardedRun(homePolicy.authorizeMutation, "publish", console.log, [`opencodex: the proxy is healthy on port ${bakePort} under the service manager (pid ${verdict.managerPid}).`]); return "supervised"; } if (unsettled) { @@ -561,21 +653,34 @@ function runPackageManagerSelfUpdate(manager) { * manager may still finish its restart; callers exit non-zero for both. */ function refreshBackgroundServiceOrStartDirect() { + authorityLauncher = postUpdateLauncher; + if (!homePolicy.authorizeMutation("runtime")) return "refused"; + if (!homePolicy.serviceAllowed) return [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused"; + let homeRefused = false; const mayRefresh = () => { + if (!homePolicy.authorizeMutation("runtime")) { homeRefused = true; return false; } const supervision = observeSupervision(); const plan = planUpdateRuntimeHandling({ ...readOwnership(), serviceInstalled: true, supervision }); + if (!homePolicy.authorizeMutation("runtime")) { homeRefused = true; return false; } if (!plan.mayRestoreService) console.warn(supervision ? "OpenCodex Desktop supervises the proxy; CLI recovery was skipped. Use the app's updater (tray → Check for Updates)." : plan.notice); - return plan.mayRestoreService; + return plan.mayRestoreService && homePolicy.serviceAllowed; }; - if (!mayRefresh()) return; + if (!mayRefresh()) { + if (homeRefused) return "refused"; + if (!homePolicy.serviceAllowed) return [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused"; + return; + } const prevBake = process.env.OCX_BAKE_PORT; process.env.OCX_BAKE_PORT = String(bakePort); try { - let svc = spawnSync(process.execPath, serviceRefreshArgs(), { + if (!homePolicy.authorizeMutation("service")) return homePolicy.authorizeMutation("runtime") && [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused"; + let svc = guardedSpawnSync(homePolicy.authorizeMutation, "service", process.execPath, serviceRefreshArgs(), { stdio: "inherit", windowsHide: true, env: mutationChildEnvironment(), }); + if (!homePolicy.authorizeMutation("runtime")) return "refused"; + if (!homePolicy.serviceAllowed) return [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused"; // `serviceWasInstalled` is inferred from service-state.json alone, which can be // STALE — present while the registration is gone. Repair refuses that case by // design, and its thrown Error is indistinguishable from any other failure at @@ -585,18 +690,25 @@ function runPackageManagerSelfUpdate(manager) { // failure would resurrect the elevation prompt this change exists to avoid, and // could re-register a service the user just uninstalled. if (svc.status !== 0 && readServiceInstalledFromStatus(postUpdateLauncher) === false) { - if (!mayRefresh()) return; + if (!mayRefresh()) { + if (homeRefused) return "refused"; + if (!homePolicy.serviceAllowed) return [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused"; + return; + } console.log("No registered service found — installing it instead."); - svc = spawnSync(process.execPath, serviceInstallArgs(), { + const serviceInstallArgsForSpawn = serviceInstallArgs(); + if (!homePolicy.authorizeMutation("service")) return homePolicy.authorizeMutation("runtime") && [true, "vetoed"].includes(startProxyDirectly()) ? undefined : "refused"; + svc = guardedSpawnSync(homePolicy.authorizeMutation, "service", process.execPath, serviceInstallArgsForSpawn, { stdio: "inherit", windowsHide: true, env: mutationChildEnvironment(), }); + if (!homePolicy.authorizeMutation("runtime")) return "refused"; } let needDirectStart = svc.status !== 0; if (!needDirectStart) { // Exit 0 can still leave stale/missing assets that never bring the proxy // back — match the GUI/CLI fallthrough so /healthz is not left dead. try { - const st = spawnSync(process.execPath, [postUpdateLauncher, "status", "--json"], { + const st = probeSpawnSync(process.execPath, [postUpdateLauncher, "status", "--json"], { encoding: "utf8", timeout: 20_000, windowsHide: true, @@ -620,6 +732,7 @@ function runPackageManagerSelfUpdate(manager) { // just returned is indistinguishable from any other failure at this layer. const supervision = observeSupervision(); const nowOwned = planUpdateRuntimeHandling({ ...readOwnership(), serviceInstalled: true, supervision }); + if (!homePolicy.authorizeMutation("runtime")) return "refused"; if (!nowOwned.mayStopRuntime) { console.warn(supervision ? "OpenCodex Desktop supervises the proxy; CLI recovery was skipped. Use the app's updater (tray → Check for Updates)." @@ -627,9 +740,11 @@ function runPackageManagerSelfUpdate(manager) { return; } // #7043: the manager first. Only a proxy it owns counts as recovered. + if (!homePolicy.authorizeMutation("runtime")) return "refused"; const managed = restartThroughServiceManager(); - if (managed === "supervised") return; + if (managed === "supervised" || managed === "vetoed") return; if (managed === "unsettled") return "unsettled"; + if (managed === "refused") return "refused"; // Repair normally avoids elevation for a healthy registration, but a stale Windows // scheduler definition can require it. It can also fail — or exit 0 while leaving // a non-viable manager. Fall back to a direct detached proxy start so the @@ -643,6 +758,7 @@ function runPackageManagerSelfUpdate(manager) { const started = startProxyDirectly(); // An ownership veto is the correct outcome, not a degraded one. if (started === "vetoed") return; + if (started === "refused") return "refused"; if (started) console.warn(unsupervisedRuntimeWarning(bakePort)); return "unsupervised"; } @@ -652,7 +768,7 @@ function runPackageManagerSelfUpdate(manager) { } } - const updateLease = acquireOwnershipMutationLease(serviceStatePaths); + let updateLease = acquireOwnershipMutationLease(serviceStatePaths); delegatedOwnershipMutationToken = updateLease.token; let updateLeaseReleased = false; const releaseUpdateLease = () => { @@ -661,15 +777,22 @@ function runPackageManagerSelfUpdate(manager) { delegatedOwnershipMutationToken = null; updateLease.release(); }; + const reacquireUpdateLease = () => { + if (!updateLeaseReleased) return; + updateLease = acquireOwnershipMutationLease(serviceStatePaths); + updateLeaseReleased = false; + delegatedOwnershipMutationToken = updateLease.token; + }; let res; + let stopAttempted = false; let npmFailure = null; try { // Stop authority is decided under the same lease the child joins. A takeover between the // earlier preflight and this boundary therefore blocks stop before it is sent. const lockedOwnership = readOwnership(); const lockedPlan = planUpdateRuntimeHandling({ ...lockedOwnership, serviceInstalled: serviceWasInstalled, supervision: observeSupervision() }); - if (lockedOwnership.subjectToken !== initialOwnership.subjectToken || !lockedPlan.mayReplacePackage) { + if (!homePolicy.authorizeMutation("package") || lockedOwnership.subjectToken !== initialOwnership.subjectToken || !lockedPlan.mayReplacePackage) { releaseUpdateLease(); console.error(lockedPlan.notice ?? "opencodex: update stopped because runtime ownership changed before stop authorization; rerun from the beginning."); @@ -678,19 +801,29 @@ function runPackageManagerSelfUpdate(manager) { runtimePlan = lockedPlan; const stoppedOwnershipIdentity = ownershipIdentity(lockedOwnership); + if (session) { + const entered = await session.enterMutation(); + if (!entered.ok) { releaseUpdateLease(); process.exit(10); } + enteredMutation = true; + } + // Never replace package files under a live proxy — stop it first (full `ocx stop` // semantics: graceful drain, service stop, native Codex restore). Gate on the service // and the runtime-port record too: a service-managed or orphaned proxy can be live // while ocx.pid is stale/missing. - if (trayBeforeUpdate.stopBeforeReplacement) { + if (!homePolicy.packageOnly && trayBeforeUpdate.stopBeforeReplacement) { console.log("⏹ Handing off the Windows tray before updating..."); try { + if (!homePolicy.authorizeMutation("tray")) { releaseUpdateLease(); process.exit(1); } + let stopAttempted = false; handoffWindowsTrayForUpdate(trayBeforeUpdate, { stop: () => { - const stopped = runTrayLifecycle(launcher, "stop"); + if (!homePolicy.authorizeMutation("tray")) throw new Error("Automatic update tray handoff refused."); + stopAttempted = true; + const stopped = runTrayLifecycle(launcher, "stop", homePolicy.authorizeMutation); return { exitStatus: stopped.status, running: trayInstallState().running }; }, - start: () => runTrayLifecycle(launcher, "start"), + start: () => { if (stopAttempted && homePolicy.authorizeMutation("own-tray")) return runTrayLifecycle(launcher, "start", homePolicy.authorizeMutation); }, }); } catch { releaseUpdateLease(); @@ -700,9 +833,10 @@ function runPackageManagerSelfUpdate(manager) { } const hasRuntimeState = existsSync(join(configDir(), "ocx.pid")) || existsSync(join(configDir(), "runtime-port.json")); - let stopAttempted = false; function recoverStoppedRuntimeAfterFailure(reason) { + authorityLauncher = postUpdateLauncher; + if (!homePolicy.authorizeMutation("runtime")) return; const planRecovery = () => { const recoveryOwnership = readOwnership(); const liveness = currentPackageRuntimeLiveness(); @@ -726,6 +860,7 @@ function runPackageManagerSelfUpdate(manager) { // lease, and holding the lease through the repair's health wait keeps that proxy from // starting (#5760). Release it as the successful path does, then decide again. releaseUpdateLease(); + if (!homePolicy.authorizeMutation("runtime")) return; ({ liveness: recoveryLiveness, plan: recovery } = planRecovery()); } if (recovery.reason === "desktop-supervised") { @@ -755,7 +890,12 @@ function runPackageManagerSelfUpdate(manager) { // is the whole test here — the launcher cannot parse it, and `ocx stop` is what decides // whether the obligation is safe to finish. const hasPendingTeardown = hasPendingTeardownIn(readdirSync, configDir()); - const stopNeeded = serviceWasInstalled || hasRuntimeState || hasPendingTeardown; + if (homePolicy.packageOnly && hasPendingTeardown) { + releaseUpdateLease(); + console.error("opencodex: pending teardown requires manual recovery before package replacement; run 'ocx stop' from the owning installation."); + process.exit(1); + } + const stopNeeded = !homePolicy.packageOnly && (serviceWasInstalled || hasRuntimeState || hasPendingTeardown); if (stopNeeded && !runtimePlan.mayStopRuntime) { releaseUpdateLease(); console.error(runtimePlan.notice @@ -763,6 +903,7 @@ function runPackageManagerSelfUpdate(manager) { process.exit(1); } if (stopNeeded) { + if (!homePolicy.authorizeMutation("runtime")) { releaseUpdateLease(); process.exit(1); } const preStopPlan = planUpdateRuntimeHandling({ ...readOwnership(), serviceInstalled: serviceWasInstalled, supervision: observeSupervision(), }); @@ -771,9 +912,16 @@ function runPackageManagerSelfUpdate(manager) { releaseUpdateLease(); process.exit(1); } + if (!homePolicy.authorizeMutation("runtime")) { releaseUpdateLease(); process.exit(1); } + if (serviceWasInstalled && !homePolicy.serviceAllowed) { + console.warn("Service authority changed before proxy stop; check 'ocx service status' before retrying the update."); + releaseUpdateLease(); + process.exit(1); + } stopAttempted = true; console.log("⏹ Stopping the running proxy before updating..."); - const stopRes = spawnSync(process.execPath, [launcher, "stop"], { + if (!homePolicy.authorizeMutation(serviceWasInstalled ? "service" : "runtime")) { releaseUpdateLease(); process.exit(1); } + const stopRes = guardedSpawnSync(homePolicy.authorizeMutation, serviceWasInstalled ? "service" : "runtime", process.execPath, [launcher, "stop"], { stdio: "inherit", windowsHide: true, env: mutationChildEnvironment(), }); const stillHasRuntimeState = @@ -797,7 +945,7 @@ function runPackageManagerSelfUpdate(manager) { }); const historyOnlyStop = decision.reason === "history-only"; if (!decision.proceed) { - if (trayBeforeUpdate.restoreOnFailure) runTrayLifecycle(launcher, "start"); + if (trayBeforeUpdate.restoreOnFailure && homePolicy.authorizeMutation("own-tray")) runTrayLifecycle(launcher, "start", homePolicy.authorizeMutation); if (decision.reason === "teardown-outstanding") { console.error("opencodex: a shared teardown from an earlier stop is still outstanding and needs manual review; aborting the update."); console.error("opencodex: confirm no proxy is running, run 'ocx restore', then remove the pending-teardown file in the opencodex home."); @@ -829,12 +977,12 @@ function runPackageManagerSelfUpdate(manager) { const replacementOwnership = readOwnership(); const replacementPlan = planUpdateRuntimeHandling({ ...replacementOwnership, serviceInstalled: serviceWasInstalled, supervision: observeSupervision() }); const replacementLiveness = currentPackageRuntimeLiveness(); - if (replacementOwnership.subjectToken !== initialOwnership.subjectToken + if (!homePolicy.authorizeMutation("package") || replacementOwnership.subjectToken !== initialOwnership.subjectToken || !replacementPlan.mayReplacePackage || replacementLiveness !== "dead") { recoverStoppedRuntimeAfterFailure("replacement was refused"); releaseUpdateLease(); - if (trayBeforeUpdate.restoreOnFailure) runTrayLifecycle(launcher, "start"); + if (trayBeforeUpdate.restoreOnFailure && homePolicy.authorizeMutation("own-tray")) runTrayLifecycle(launcher, "start", homePolicy.authorizeMutation); console.error(replacementPlan.notice ?? "opencodex: update stopped because runtime ownership or liveness changed after the stop decision; rerun from the beginning."); process.exit(1); @@ -847,16 +995,50 @@ function runPackageManagerSelfUpdate(manager) { try { if (manager === "npm") { const packageDir = resolve(here, ".."); - const tx = transactionalNpmUpdate({ + const transactionalNpmUpdate = session ? transactionalNpmUpdateAsync : transactionalNpmUpdateSync; + if (!homePolicy.authorizeMutation("package")) throw new Error("Automatic package update refused."); + const tx = await transactionalNpmUpdate({ packageDir, pkgName: PKG, targetVersion: latest || undefined, tag, cachePath: npmCachePath, + mayReplacePackage: () => { + const ownership = readOwnership(); + const plan = planUpdateRuntimeHandling({ ...ownership, serviceInstalled: serviceWasInstalled, supervision: observeSupervision() }); + const liveness = currentPackageRuntimeLiveness(); + return homePolicy.authorizeMutation("package") && ownership.subjectToken === initialOwnership.subjectToken + && plan.mayReplacePackage && liveness === "dead"; + }, runNpm: (args) => { const invocation = npmInvocation(args); + if (!homePolicy.authorizeMutation("package")) return { status: 1 }; + if (process.platform === "win32") { + if (session) session.noteUntrackedInstaller(); + return runNpmInstall(invocation, { + authorizeMutation: homePolicy.authorizeMutation, + env: unprivilegedOwnershipMutationEnvironment(invocation?.options?.env ?? process.env), + }).then(result => { + if (session && result.processTreeExited === true && Number.isInteger(result.status)) session.confirmInstallerExit(); + else if (session) { session.retainInstallerFence(); return { ...result, processTreeExited: false }; } + return result; + }); + } if (!invocation) return { status: 1 }; - return spawnSync(invocation.file, invocation.args, { + if (!homePolicy.authorizeMutation("package")) return { status: 1 }; + if (session) { + try { + const result = runPosixInstallerSync({ file: invocation.file, args: invocation.args, + markerPath: join(configDir(), "update-orchestrated.json"), authorizeMutation: homePolicy.authorizeMutation, + env: unprivilegedOwnershipMutationEnvironment(invocation.options?.env ?? process.env) }); + if (!Number.isInteger(result.status) || result.signal || !result.groupExited || result.groupKilled !== false || result.processTreeExited === false) { + session.retainInstallerFence(); + return { ...result, processTreeExited: false }; + } + return { ...result, processTreeExited: true }; + } catch (error) { session.retainInstallerFence(); throw error; } + } + return guardedSpawnSync(homePolicy.authorizeMutation, "package", invocation.file, invocation.args, { ...invocation.options, stdio: "inherit", timeout: 180000, @@ -866,11 +1048,14 @@ function runPackageManagerSelfUpdate(manager) { }, log: (line) => console.log(line), }); + if (session) childOutcome = tx.ok ? { phase: "installed", activeRoot: packageDir } + : { phase: "failed", rollbackPerformed: tx.rolledBack === true, + ...(tx.processTreeExited === false ? { error: "installer-termination-unconfirmed", terminationConfirmed: false } : {}) }; postUpdateLauncherUsable = launcherUsableAfterNpmUpdate(tx); if (!tx.ok) npmFailure = tx; if (tx.ok) { res = { status: 0 }; - } else if (tx.phase === "stage" || tx.phase === "verify") { + } else if (tx.phase === "stage" || tx.phase === "verify" || tx.phase === "authorize") { // Live tree untouched: report and stop. Nothing to roll back. console.error(`opencodex: update aborted before touching the live install (${tx.phase}): ${tx.error}`); res = { status: 1 }; @@ -879,6 +1064,7 @@ function runPackageManagerSelfUpdate(manager) { res = { status: 1 }; } } else { + if (!homePolicy.authorizeMutation("package")) throw new Error("Automatic package update refused."); const update = runPnpmGlobalUpdate({ packageName: PKG, currentVersion: current, @@ -889,7 +1075,26 @@ function runPackageManagerSelfUpdate(manager) { runPnpm: (args, capture = false) => { const invocation = pnpmOwnerInvocation(owner, args); if (!invocation) return { status: 1 }; - return withPnpmCommandCwd(args, cwd => spawnSync(invocation.file, invocation.args, { + if (session && !capture) return withPnpmCommandCwd(args, cwd => { + const env = pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(invocation.env ?? process.env)); + if (process.platform === "win32") { + session.noteUntrackedInstaller(); + const result = runWindowsInstallerSync(invocation, { cwd, env, authorizeMutation: homePolicy.authorizeMutation }); + if (result.processTreeExited === true && Number.isInteger(result.status)) session.confirmInstallerExit(); + else { session.retainInstallerFence(); return { ...result, processTreeExited: false }; } + return result; + } + try { + const result = runPosixInstallerSync({ file: invocation.file, args: invocation.args, cwd, markerPath: join(configDir(), "update-orchestrated.json"), + authorizeMutation: homePolicy.authorizeMutation, env }); + if (!Number.isInteger(result.status) || result.signal || !result.groupExited || result.groupKilled !== false || result.processTreeExited === false) { + session.retainInstallerFence(); + return { ...result, processTreeExited: false }; + } + return { ...result, processTreeExited: true }; + } catch (error) { session.retainInstallerFence(); throw error; } + }); + return withPnpmCommandCwd(args, cwd => homePolicy.authorizeMutation("package") ? guardedSpawnSync(homePolicy.authorizeMutation, "package", invocation.file, invocation.args, { ...invocation.options, stdio: capture ? "pipe" : "inherit", encoding: "utf8", @@ -899,10 +1104,13 @@ function runPackageManagerSelfUpdate(manager) { // keep a cwd handle inside the package Windows is replacing. cwd, env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(invocation.env ?? process.env)), - })); + }) : { status: 1 }); }, log: line => console.log(line), }); + if (session) childOutcome = update.ok ? { phase: "installed", activeRoot: update.path } + : { phase: "failed", rollbackPerformed: update.rollbackPerformed === true, + ...(update.processTreeExited === false ? { error: "installer-termination-unconfirmed", terminationConfirmed: false } : {}) }; if (update.ok) { // pnpm switches the active global group and updates its shim. Continue recovery // through that fresh package tree, not the old group whose launcher is still @@ -928,39 +1136,72 @@ function runPackageManagerSelfUpdate(manager) { `Run 'ocx update' again or follow the manual recovery steps below.`); res = { status: 1 }; } - if (res.status !== 0) recoverStoppedRuntimeAfterFailure("update failed"); + if (res.status !== 0 && childOutcome.error !== "installer-termination-unconfirmed") recoverStoppedRuntimeAfterFailure("update failed"); } finally { // Expected aborts release before process.exit(); this covers every thrown or newly-added // path and keeps token restoration coupled to the lease itself. releaseUpdateLease(); } + if (childOutcome.error === "installer-termination-unconfirmed") process.exit(1); const postInstallPlan = planUpdateRuntimeHandling({ ...readOwnership(), serviceInstalled: serviceWasInstalled, supervision: observeSupervision() }); if (res.status === 0) { - console.log(`\nUpdated${latest ? ` to v${latest}` : ""}.`); + authorityLauncher = postUpdateLauncher; + if (homePolicy.packageOnly) { + if (!homePolicy.authorizeMutation("package-publish")) process.exit(1); + guardedRun(homePolicy.authorizeMutation, "package-publish", console.log, [`\nUpdated${latest ? ` to v${latest}` : ""}.`]); + homePolicy.check(homePolicy.initial); + console.log(`Restart the proxy: ${launcherStartHint(postUpdateLauncher, bakePort)}`); + if (!homePolicy.authorizeMutation("package-publish")) process.exit(1); + guardedExit(homePolicy.authorizeMutation, "package-publish", process.argv.includes("--update-worker-result") ? UPDATE_PACKAGE_ONLY_EXIT_CODE : 0); + } + const restoreOwnStoppedTray = () => { + if (trayBeforeUpdate.restoreOnFailure && postUpdateLauncherUsable && existsSync(postUpdateLauncher)) { + try { if (homePolicy.authorizeMutation("own-tray")) runTrayLifecycle(postUpdateLauncher, "start", homePolicy.authorizeMutation); } catch { /* preserve the authority refusal */ } + } + }; + if (!homePolicy.authorizeMutation("publish")) { + restoreOwnStoppedTray(); + process.exit(1); + } + guardedRun(homePolicy.authorizeMutation, "publish", console.log, [`\nUpdated${latest ? ` to v${latest}` : ""}.`]); if (!postInstallPlan.mayStopRuntime) console.warn("Runtime authority does not permit CLI recovery; no service was refreshed or proxy started."); - repairCodexShimIfNeeded(postUpdateLauncher); + if (!homePolicy.authorizeMutation("shim") || repairCodexShimIfNeeded(postUpdateLauncher, homePolicy.authorizeMutation) === false) { restoreOwnStoppedTray(); process.exit(1); } if (trayBeforeUpdate.refreshAfterReplacement) { - const tray = spawnSync(process.execPath, [postUpdateLauncher, ...trayBeforeUpdate.installArgs], { + if (!homePolicy.authorizeMutation("tray")) { + restoreOwnStoppedTray(); + process.exit(1); + } + const tray = guardedSpawnSync(homePolicy.authorizeMutation, "tray", process.execPath, [postUpdateLauncher, ...trayBeforeUpdate.installArgs], { stdio: "inherit", windowsHide: true, }); if (tray.status !== 0) { console.warn("opencodex: Windows tray refresh failed. Run: ocx tray install"); - if (trayBeforeUpdate.restoreOnFailure && postUpdateLauncherUsable) runTrayLifecycle(postUpdateLauncher, "start"); + if (trayBeforeUpdate.restoreOnFailure && postUpdateLauncherUsable && homePolicy.authorizeMutation("own-tray")) runTrayLifecycle(postUpdateLauncher, "start", homePolicy.authorizeMutation); } } // The stop above unloaded any managed service; refresh via the freshly-installed // launcher so the new files write the baked paths and the service restarts. if (postInstallPlan.mayRestoreService) { console.log("Refreshing the background service with the updated files..."); - const refreshed = refreshBackgroundServiceOrStartDirect(); - if (refreshed === "unsupervised" || refreshed === "unsettled") process.exit(1); + let refreshed; + try { refreshed = refreshBackgroundServiceOrStartDirect(); } + finally { releaseUpdateLease(); } + if (refreshed === "unsupervised" || refreshed === "unsettled" || refreshed === "refused") process.exit(1); } else if (postInstallPlan.mayStopRuntime) { - console.log(`Restart the proxy: ${launcherStartHint(postUpdateLauncher, bakePort)}`); + if (!homePolicy.authorizeMutation("runtime")) process.exit(1); + authorityLauncher = postUpdateLauncher; + if (stopAttempted) { + let started; + try { started = startProxyDirectly(); } + finally { releaseUpdateLease(); } + if (started !== true && started !== "vetoed") process.exit(1); + } else console.log(`Restart the proxy: ${launcherStartHint(postUpdateLauncher, bakePort)}`); } - process.exit(0); + if (!homePolicy.authorizeMutation("publish")) process.exit(1); + guardedExit(homePolicy.authorizeMutation, "publish", 0); } - if (trayBeforeUpdate.restoreOnFailure && postUpdateLauncherUsable) runTrayLifecycle(postUpdateLauncher, "start"); + if (trayBeforeUpdate.restoreOnFailure && postUpdateLauncherUsable && homePolicy.authorizeMutation("own-tray")) runTrayLifecycle(postUpdateLauncher, "start", homePolicy.authorizeMutation); if (npmFailure) { // Phase-specific next step (#5624): whether the previous version is still in place decides // between "retry" and "restore", and a bare reinstall must follow a stop (#5496). @@ -979,10 +1220,11 @@ function runPackageManagerSelfUpdate(manager) { process.exit(1); } -function bunBinDir() { +function bunBinDir(launcherPath) { // Resolve the `bun` dependency's directory without hardcoding the platform // package — the package manager's os/cpu/libc resolution already picked the right @oven/bun-*. - return dirname(require.resolve("bun/package.json")); + const resolver = createRequire(launcherPath || import.meta.url); + return dirname(resolver.resolve("bun/package.json")); } const BUN_OVERRIDE_ENV = "OPENCODEX_BUN_PATH"; @@ -1031,7 +1273,7 @@ function fail(msg) { process.exit(1); } -function resolveBun({ allowInstall = true } = {}) { +function resolveBun({ allowInstall = true, launcherPath, allowMissing = false } = {}) { // Keep direct package-launcher starts aligned with durable service/shim installs: // a valid explicit runtime must win even when the bundled dependency exists. const override = process.env[BUN_OVERRIDE_ENV]?.trim(); @@ -1045,7 +1287,7 @@ function resolveBun({ allowInstall = true } = {}) { let bunDir = null; try { - bunDir = bunBinDir(); + bunDir = bunBinDir(launcherPath); } catch { /* Missing dependency can still fall back to a validated PATH Bun. */ } let bin = bunDir ? findBunBinary(bunDir) : null; @@ -1055,7 +1297,7 @@ function resolveBun({ allowInstall = true } = {}) { // ~450-byte placeholder stub. Run the bun package's own installer once. const installJs = bunDir ? join(bunDir, "install.js") : null; if (allowInstall && installJs && existsSync(installJs)) { - const r = spawnSync(process.execPath, [installJs], { stdio: "inherit" }); + const r = probeSpawnSync(process.execPath, [installJs], { stdio: "inherit" }); if (r.status === 0) bin = findBunBinary(bunDir); } if (bin) return { path: bin, source: "bundled", version: bundledBunVersion(bunDir) }; @@ -1063,11 +1305,12 @@ function resolveBun({ allowInstall = true } = {}) { // Reached only when the bundled runtime is unusable. The two probes start the candidate Bun // cold, and on Windows a first run of a copied bun.exe is often held by an on-access scan for // well over a second, so the total budget is generous rather than interactive-tight. - const pathBun = findPathBun({ pinnedVersion: pinnedBunVersion(), deadlineMs: PATH_BUN_PROBE_BUDGET_MS }); + const pathBun = findPathBun({ pinnedVersion: pinnedBunVersion(launcherPath), deadlineMs: PATH_BUN_PROBE_BUDGET_MS }); if (pathBun) { console.error(`opencodex: using PATH Bun ${pathBun.version}.`); return { path: pathBun.path, source: "process", version: pathBun.version }; } + if (allowMissing) return null; fail(bunDir ? "Bun binary missing after install attempt." : "the `bun` dependency is not installed."); } @@ -1075,20 +1318,92 @@ function resolveBun({ allowInstall = true } = {}) { // intercepts `update` before the Bun CLI starts, so the help short-circuit must live // here too — otherwise --help runs the real self-update, stops the proxy, and drops // in-flight routed streams (issue #168). -const updateHelpRequested = process.argv[2] === "update" && +const updateHelpRequested = process.argv[2] === "update" && !isOrchestratedUpdateArgv(process.argv.slice(3)) && process.argv.slice(3).some(a => a === "--help" || a === "-h" || a === "help"); if (updateHelpRequested) { - console.log("Usage: ocx update [--tag latest|preview]\n\nUpdate opencodex. Preview installs stay on the preview tag unless overridden."); + console.log("Usage: ocx update [--tag latest|preview]\n ocx update --plan --json [--tag latest|preview | --version ]\n ocx update --yes --json [--tag latest|preview | --version ] [--expect-plan ] [--not-after ]\n\nPreview with --plan; apply with --yes. --expect-plan binds apply to the planToken; --not-after sets a Unix millisecond mutation deadline.\nOrchestrated exit codes: 0 verified or up-to-date; 10 refused; 11 failed with previous version verified; 12 unverified or still running; 64 invalid usage.\nPreview installs stay on the preview tag unless overridden."); process.exit(0); } +// This intercept precedes Desktop handoff, boot restore and install-capable Bun resolution. +// Capability only: no Bun lookup, home inspection, dotenv or ordinary bootstrap. +if (process.argv[2] === "__update-package-only-probe") { + if (process.argv.length !== 3) process.exit(2); + console.log(JSON.stringify({ schemaVersion: 1, packageOnlyProtocolVersion: UPDATE_PACKAGE_ONLY_PROTOCOL_VERSION })); + process.exit(0); +} +if (process.argv[2] === "__update-home-probe") { + if (!isUpdateHomeProbe(process.argv.slice(2))) process.exit(1); + console.log(JSON.stringify({ schemaVersion: 1, ...readNodeUpdateHome(fileURLToPath(import.meta.url)), launcherProtocolVersion: UPDATE_HOME_LAUNCHER_PROTOCOL })); + process.exit(0); +} +if (process.argv[2] === "__update-orchestrated-identity") { + if (process.argv.length !== 3) process.exit(1); + const bun = resolveBun({ allowInstall: false, allowMissing: true }); + if (!bun) process.exit(1); + const result = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), process.argv[2]], { + stdio: "inherit", timeout: 8000, windowsHide: true, env: { ...process.env, OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: "", OCX_IDENTITY_TARGET: "" }, + }); + process.exit(result.status ?? 1); +} + +const orchestratedUpdate = process.argv[2] === "update" && isOrchestratedUpdateArgv(process.argv.slice(3)); +const childArgs = orchestratedUpdate && process.env.OCX_UPDATE_ORCHESTRATED_CHILD === "1" + ? parseOrchestratedChildArgs(process.argv.slice(3), process.env) : null; +const orchestratedArgs = orchestratedUpdate && !childArgs?.ok ? parseOrchestratedUpdateArgs(process.argv.slice(3)) : null; +if (orchestratedArgs && !orchestratedArgs.ok) { + console.log(JSON.stringify({ error: "usage" })); + console.error("Usage: ocx update (--plan | --yes) --json [--tag latest|preview | --version ]"); + process.exit(64); +} +if (childArgs?.ok && isNodeModulesInstall() && !isBunGlobalInstall() && (installMethod === "npm" || installMethod === "pnpm")) { + await runPackageManagerSelfUpdate(installMethod, childArgs); +} +if (orchestratedArgs?.ok && orchestratedArgs.mode === "apply" && process.env.OCX_UPDATE_ORCHESTRATED_CHILD !== "1" + && isNodeModulesInstall() && !isBunGlobalInstall() && (installMethod === "npm" || installMethod === "pnpm")) { + const result = await applyNodeOrchestratedUpdate(orchestratedArgs, { + installer: installMethod, currentVersion: String(currentPackageVersion()), cliRoot: resolve(here, ".."), + home: configDir(), launcher: fileURLToPath(import.meta.url), resolveBun: () => resolveBun({ allowInstall: false, allowMissing: true }), + plan: (bun, version, tag) => probeSpawnSync(bun.path, ["--no-env-file", cliPath, "update", "--plan", "--json", + ...(version ? ["--version", version] : tag ? ["--tag", tag] : [])], { encoding: "utf8", maxBuffer: 65536, timeout: 60000, windowsHide: true, + stdio: ["ignore", "pipe", 2], env: process.env }), + identity: bun => { + const probe = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), "__update-orchestrated-identity"], { + encoding: "utf8", maxBuffer: 8192, timeout: 8000, windowsHide: true, stdio: ["ignore", "pipe", 2], + env: { ...updateHomeProbeEnvironment(process.env, { codexHome: process.env.CODEX_HOME ?? "", opencodexHome: configDir() }), + OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: "", OCX_IDENTITY_TARGET: "" }, + }); + if (probe.status !== 0 || probe.error || probe.signal) throw Error("identity unavailable"); + return JSON.parse(probe.stdout); + }, + pnpmCommands: resolvePnpmCommands(), runningShimPath: runningPnpmShimPath(), + runPnpm: (commandPath, args, capture = false) => { + const invocation = pnpmInvocationForPath(commandPath, args); + if (!invocation) return { status: 1 }; + return probeSpawnSync(invocation.file, invocation.args, { stdio: capture ? "pipe" : "ignore", encoding: "utf8", + timeout: 20000, windowsHide: true, cwd: PNPM_READ_CWD, + env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(process.env)), ...invocation.options }); + }, + spawn: probeSpawn, + }); + await new Promise(resolveOutput => process.stdout.write(`${JSON.stringify(result.result)}\n`, resolveOutput)); + process.exit(result.exitCode); +} +const passiveCapabilities = process.argv[2] === "capabilities"; const codexCliUpdateInspection = isCodexCliUpdateInspectionArgv(process.argv); +// Windows inspection currently refuses before candidate I/O, so a long-lived +// Windows server does not duplicate PATH into its inherited environment block. +const codexCliUpdateInspectionContext = codexCliUpdateInspection + || (process.platform !== "win32" && carriesCodexCliUpdateInspectionContext(process.argv)); if (codexCliUpdateInspection && typeof process.versions.bun === "string") { console.error("opencodex: codex-cli-update inspection must use the published Node launcher."); process.exit(1); } const { launchProof, launchContext, inheritedEnv } = createNodeLaunchContext(); +delete inheritedEnv.OCX_SYNC_MUTEX_HELD_BY; +// The parsed child capability was removed from process.env; only the Bun CLI handoff of this same child receives it. +if (childArgs?.ok) inheritedEnv.OCX_UPDATE_RESULT_CAPABILITY = childArgs.resultCapability; const desktopPlan = planDesktopCliHandoff({ selfPaths: [fileURLToPath(import.meta.url), process.execPath] }); if (desktopPlan.kind === "error") { if (desktopPlan.issue.startsWith("record-")) { @@ -1098,27 +1413,42 @@ if (desktopPlan.kind === "error") { } process.exit(1); } +let releaseSyncLease = () => {}; +let addSyncDelegate = () => {}; +if (process.argv[2] === "sync") { + const syncLease = acquireSyncGuard(configDir(), process.argv.slice(2)); + if (syncLease.kind === "refused") process.exit(syncLease.exit); + addSyncDelegate = pid => syncLease.addDelegate(pid); + inheritedEnv.OCX_SYNC_MUTEX_HELD_BY = String(process.pid); + let released = false; + releaseSyncLease = () => { + if (released) return; + try { syncLease.release(); released = true; } catch (error) { console.error(`opencodex: sync mutex release failed: ${error.message}`); } + }; + process.once("exit", releaseSyncLease); +} if (desktopPlan.kind === "handoff") { const result = await runDesktopCliHandoff(desktopPlan, { - argv: process.argv.slice(2), env: inheritedEnv, proof: launchProof, context: launchContext, + argv: process.argv.slice(2), env: inheritedEnv, proof: launchProof, context: launchContext, onSpawn: addSyncDelegate, }); if (result.kind === "error") { console.error(`opencodex: Desktop CLI handoff failed (${result.issue}). Repair the terminal command in OpenCodex Desktop, or run with OCX_NO_DESKTOP_HANDOFF=1.`); process.exit(127); } if (result.kind === "exit") { + releaseSyncLease(); if (result.signal) { - process.kill(process.pid, result.signal); + relayOwnSignal(result.signal); } else { process.exit(result.code); } // Signal delivery is asynchronous; never resume package repair or Bun lookup. await new Promise(() => {}); } - // Only confirmed target ENOENT reaches the ordinary package path below. + // A selected Desktop never falls back to the package after a launch failure. } -if (process.argv[2] === "update" && installMethod === "mise") { +if (!orchestratedUpdate && process.argv[2] === "update" && installMethod === "mise") { if (installOwnership.owner) { console.error( `opencodex: this installation is externally managed by mise; update it with: mise upgrade ${installOwnership.owner.tool}`, @@ -1131,15 +1461,15 @@ if (process.argv[2] === "update" && installMethod === "mise") { process.exit(1); } -if (process.argv[2] === "update" && isNodeModulesInstall() && !isBunGlobalInstall()) { - if (installMethod === "npm") runNpmSelfUpdate(); - if (installMethod === "pnpm") runPnpmSelfUpdate(); +if (!orchestratedUpdate && process.argv[2] === "update" && isNodeModulesInstall() && !isBunGlobalInstall()) { + if (installMethod === "npm") await runNpmSelfUpdate(); + if (installMethod === "pnpm") await runPnpmSelfUpdate(); } // #1849 boot probe: a prior update that lost power (or double-faulted) mid-swap leaves a // backup sibling and a broken live tree. Restore before anything tries to run from the // broken tree; reap stale backups once the live tree verifies healthy. -if (!codexCliUpdateInspection && installMethod === "npm" && isNodeModulesInstall() && !isBunGlobalInstall()) { +if (process.argv[2] !== "sync" && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection && installMethod === "npm" && isNodeModulesInstall() && !isBunGlobalInstall()) { try { const probe = bootRestoreProbe(resolve(here, "..")); if (probe.action === "restored") { @@ -1150,7 +1480,22 @@ if (!codexCliUpdateInspection && installMethod === "npm" && isNodeModulesInstall } catch { /* the probe must never block launch */ } } -const bunRuntime = resolveBun({ allowInstall: !codexCliUpdateInspection }); +const passiveSync = process.argv[2] === "sync"; +const bunRuntime = resolveBun({ allowInstall: !passiveSync && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection, allowMissing: orchestratedUpdate || passiveSync }); +if (!bunRuntime && passiveSync) fail("Bun is unavailable; install Bun before running sync."); +if (!bunRuntime && orchestratedArgs?.ok) { + const currentVersion = String(currentPackageVersion()), cliRoot = resolve(here, ".."); + if (orchestratedArgs.mode === "plan") { + const identity = { currentVersion, targetVersion: null, installer: installMethod, cliRoot, servingRoot: null, runtimeOwner: "unknown", runtime: null }; + console.log(JSON.stringify({ schema: "ocx.update.plan/1", currentVersion, targetVersion: null, installer: installMethod, + runtimeOwner: "unknown", servingPath: null, cliPath: cliRoot, canApply: false, reason: "plan-unavailable", restartRequired: false, + planToken: createUpdatePlanToken(identity), updateInFlight: true, mutationBoundMs: 900000 })); + process.exit(0); + } + console.log(JSON.stringify({ schema: "ocx.update.result/1", applied: false, fromVersion: currentVersion, toVersion: null, + installer: installMethod, restarted: false, healthy: false, rolledBack: false, error: "plan-unavailable" })); + process.exit(10); +} const bun = bunRuntime.path; // Run the Bun child asynchronously and FORWARD termination signals to it, then wait @@ -1192,26 +1537,56 @@ function createNodeLaunchContext() { : configuredCodexCliPath; const preBunPath = typeof process.env.PATH === "string" ? process.env.PATH : null; const preBunPathExt = typeof process.env.PATHEXT === "string" ? process.env.PATHEXT : null; + // HOME and NODE_PATH seed the candidate Node module lookup the update + // inspection models, so they are proof-bound here for the same reason as + // PATH: the live environment could have been rewritten after selection. They + // stay in the inherited environment regardless — the child may need them for + // its own work; only the snapshot copy is optional. + const preBunHome = typeof process.env.HOME === "string" ? process.env.HOME : null; + const preBunNodePath = typeof process.env.NODE_PATH === "string" ? process.env.NODE_PATH : null; const preBunCodexCliManagerRoots = Object.fromEntries( CODEX_CLI_VERSION_MANAGER_ROOT_ENV_SLOTS.flatMap(name => { const value = process.env[name]; return typeof value === "string" && value !== "" ? [[name, value]] : []; }), ); + // Proxy/CA settings are captured once, here, before Bun can add project dotenv + // values. They are part of the required selection snapshot, so they count + // against the context budget below before any optional lookup seed does. + const preBunTransportEnv = captureCodexCliTransportEnv(process.env); const launchProof = randomBytes(32).toString("base64url"); - const launchContext = JSON.stringify({ + const serializeContext = lookupSeeds => JSON.stringify({ version: 1, proof: launchProof, anthropicEnvSlots: preBunAnthropicSlots, - codexCliInspectionEnv: codexCliUpdateInspection ? { + codexCliInspectionEnv: codexCliUpdateInspectionContext ? { codexCliPath: preBunCodexCliPath, path: preBunPath, pathExt: preBunPathExt, + home: lookupSeeds.home, + nodePath: lookupSeeds.nodePath, managerRoots: preBunCodexCliManagerRoots, + transportEnv: preBunTransportEnv, + // The published Codex entrypoint selects its native backing by the arch of + // the Node that runs it; a Bun override or PATH fallback can run another + // arch under Rosetta, so this Node launcher's arch is the bound value. + arch: process.arch, configDir: configDir(), } : null, }); - // The inspection snapshot above already carries PATH, PATHEXT, and the manager-root slots as + let launchContext = serializeContext({ home: preBunHome, nodePath: preBunNodePath }); + // The lookup seeds are optional: a Windows inspection never models the global + // Node lookup, and an oversized NODE_PATH must not push the serialized + // context past the reader's limit — that would discard the whole selection + // snapshot, while dropped seeds merely leave the fallback lane unverifiable + // and fail only the content observation closed. + const lookupSeeds = codexCliInspectionLookupSeeds( + process.platform, preBunHome, preBunNodePath, launchContext.length, + ); + if (lookupSeeds.home !== preBunHome || lookupSeeds.nodePath !== preBunNodePath) { + launchContext = serializeContext(lookupSeeds); + } + // The inspection snapshot above already carries PATH, PATHEXT, manager roots and proxy/CA settings as // proof-bound values, and `inspectCodexCliInstall` reads them from that snapshot rather than // from the live environment. Inheriting them again would spend the 32,767-character Windows // environment block twice, so a large-but-valid shell environment could stop the Bun child @@ -1224,7 +1599,8 @@ function createNodeLaunchContext() { const inheritedEnv = { ...process.env }; if (codexCliUpdateInspection) { const snapshotted = new Set( - ["PATH", "PATHEXT", ...CODEX_CLI_VERSION_MANAGER_ROOT_ENV_SLOTS].map(name => name.toLowerCase()), + ["PATH", "PATHEXT", ...CODEX_CLI_VERSION_MANAGER_ROOT_ENV_SLOTS, + ...CODEX_CLI_TRANSPORT_ENV_KEYS].map(name => name.toLowerCase()), ); for (const name of Object.keys(inheritedEnv)) { if (snapshotted.has(name.toLowerCase())) delete inheritedEnv[name]; @@ -1233,7 +1609,9 @@ function createNodeLaunchContext() { return { launchProof, launchContext, inheritedEnv }; } -const child = spawn(bun, [cliPath, `${NODE_LAUNCH_PROOF_PREFIX}${launchProof}`, ...process.argv.slice(2).filter(arg => !arg.startsWith(NODE_LAUNCH_PROOF_PREFIX))], { +// Forwarders precede the spawn so no signal can kill this launcher by default action while the child runs. +const forwarding = forwardLauncherSignals(); +const child = probeSpawn(bun, [cliPath, `${NODE_LAUNCH_PROOF_PREFIX}${launchProof}`, ...process.argv.slice(2).filter(arg => !arg.startsWith(NODE_LAUNCH_PROOF_PREFIX))], { stdio: "inherit", // A headless Windows parent (Task Scheduler, dashboard restart, shortcut) has no // console to inherit. Without this flag Windows allocates a visible console for @@ -1247,35 +1625,30 @@ const child = spawn(bun, [cliPath, `${NODE_LAUNCH_PROOF_PREFIX}${launchProof}`, [BUN_RUNTIME_PATH_ENV]: bunRuntime.path, }, }); - -// Windows has no real POSIX signals (no SIGHUP); forwarding is best-effort there. -const FORWARDED = process.platform === "win32" ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP"]; -const handlers = FORWARDED.map(sig => { - const handler = () => { - try { - child.kill(sig); - } catch { - /* child already exited */ - } - }; - process.on(sig, handler); - return [sig, handler]; -}); -const clearHandlers = () => { - for (const [sig, handler] of handlers) process.removeListener(sig, handler); -}; +forwarding.attach(child); +let delegateError = false; +if (child.pid) { + try { addSyncDelegate(child.pid); } + catch (error) { + delegateError = true; + console.error(`opencodex: sync mutex delegate publication failed: ${error.message}`); + try { child.kill(); } catch (killError) { console.error(`opencodex: failed to stop sync child: ${killError.message}`); } + } +} child.on("error", err => { - clearHandlers(); + forwarding.clear(); console.error(`opencodex: failed to launch Bun runtime: ${err.message}`); process.exit(1); }); child.on("exit", (code, signal) => { - clearHandlers(); + forwarding.clear(); + releaseSyncLease(); + if (delegateError) process.exit(1); // Mirror the child's terminating signal/exit code so this launcher's status matches. if (signal) { - process.kill(process.pid, signal); + relayOwnSignal(signal); return; } process.exit(code ?? 1); diff --git a/bun.lock b/bun.lock index 063207baa8..cdfea17848 100644 --- a/bun.lock +++ b/bun.lock @@ -6,13 +6,13 @@ "name": "@bitkyc08/opencodex", "dependencies": { "@bufbuild/protobuf": "^2.14.0", - "@modelcontextprotocol/sdk": "^1.30.0", + "@modelcontextprotocol/sdk": "^1.32.1", "@napi-rs/keyring": "1.3.0", - "bun": "1.4.2", - "zod": "4.4.3", + "bun": "1.4.4", + "zod": "4.6.6", }, "devDependencies": { - "@types/bun": "1.4.0", + "@types/bun": "1.4.4", "typescript": "7.0.2", }, "optionalDependencies": { @@ -25,17 +25,18 @@ ], "overrides": { "@hono/node-server": "2.1.0", + "body-parser": "2.4.0", "fast-uri": "^3.1.7", - "hono": "4.13.8", - "ip-address": "^10.4.0", - "qs": "^6.16.0", + "hono": "4.13.13", + "ip-address": "^10.7.4", + "qs": "^6.16.1", }, "packages": { "@bufbuild/protobuf": ["@bufbuild/protobuf@2.14.0", "", {}, "sha512-C3UGsiCwSprE2NKIIFA3hCDlpXTMCAXRZuEVp88L1GY36Y41+rYL5fryE+nOFhp4p4JPQvdV8PQ4DWgHgeTE+w=="], "@hono/node-server": ["@hono/node-server@2.1.0", "", { "peerDependencies": { "hono": "^4" } }, "sha512-XovyyCCnBzW+zKu+z/zq8hwNs4KOR5rEMAOxo2f40Q5xoOI37IMm6MIg2COOUtUApo0i6850MTBKH2u4QLGIqg=="], - "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.31.0", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-UvTMgnNlnIBO/22ob2RcVGDlcvOslQs8T59+FTGdA0L27a39fdGF/EDETNtDVK4DZGpwomlsYpRdA8UXcVL/pw=="], + "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.1", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw=="], "@napi-rs/keyring": ["@napi-rs/keyring@1.3.0", "", { "optionalDependencies": { "@napi-rs/keyring-darwin-arm64": "1.3.0", "@napi-rs/keyring-darwin-x64": "1.3.0", "@napi-rs/keyring-freebsd-x64": "1.3.0", "@napi-rs/keyring-linux-arm-gnueabihf": "1.3.0", "@napi-rs/keyring-linux-arm64-gnu": "1.3.0", "@napi-rs/keyring-linux-arm64-musl": "1.3.0", "@napi-rs/keyring-linux-riscv64-gnu": "1.3.0", "@napi-rs/keyring-linux-x64-gnu": "1.3.0", "@napi-rs/keyring-linux-x64-musl": "1.3.0", "@napi-rs/keyring-win32-arm64-msvc": "1.3.0", "@napi-rs/keyring-win32-ia32-msvc": "1.3.0", "@napi-rs/keyring-win32-x64-msvc": "1.3.0" } }, "sha512-WrOw/bcXm0f9qHkumlT1QlArXSTWqaY9sunsDpOk+yCCorCKMxvWT/a3xko4EYHVdeZoh00yI2TydXn6eyICDA=="], @@ -63,31 +64,31 @@ "@napi-rs/keyring-win32-x64-msvc": ["@napi-rs/keyring-win32-x64-msvc@1.3.0", "", { "os": "win32", "cpu": "x64" }, "sha512-4DnCWXwDc0HRKwyRlG5y0VhKZW2tNRQfKKfyj6IX/KWfDNyq9hn4n+GL1auyDcOO/v8PwnhmYo2+rOOqCkvvOg=="], - "@oven/bun-darwin-aarch64": ["@oven/bun-darwin-aarch64@1.4.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-MXdZkP1featqxZ+/VTXWG1BVjM4OGBehVY2Q88EeUj/7L0UMeCGItmyPYTN+wxvlGJ6F66JEtzsw+GvQWewnag=="], + "@oven/bun-darwin-aarch64": ["@oven/bun-darwin-aarch64@1.4.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zW/hxwc8sJAILGwB5eTC4i48ouGXf0V4lrxmEOk3JIE6JkYVW1TZh1E2pIempqsezgW1sckTIIDudFON8bJ2Mw=="], - "@oven/bun-darwin-x64": ["@oven/bun-darwin-x64@1.4.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-gZTxZuLjkUhAWjTETu3tw0WhsEdNkJ64daj60ybhPf835a2yollV3yTkK9JozvzKPx4TRFzLSl8C+U525pxVbw=="], + "@oven/bun-darwin-x64": ["@oven/bun-darwin-x64@1.4.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-oKGcxLsvh4oHjAo28nPm8c/xN0o/OmGyj1IHYc94vprkWsW2hNg2keEZt5f40cI5Hvu4jDlSRTR0UNpv1UIAxw=="], - "@oven/bun-freebsd-aarch64": ["@oven/bun-freebsd-aarch64@1.4.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-SMNItMw1Z8QeeQVKnw8jA7xQNkeXdP+OPgin4Wi/QTx/B8RHHLnuZfqmFy7NtVeT2NF0kKYppW4WWd2CCYZjhQ=="], + "@oven/bun-freebsd-aarch64": ["@oven/bun-freebsd-aarch64@1.4.4", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-klvA9FlwLxZj3JYIOPQA4bbnHIC3uas8kBE4GaGGkeVgAQP/k8hAzYkOqkSaqHBDbxLrTyFEQArEAevJq6NJzg=="], - "@oven/bun-freebsd-x64": ["@oven/bun-freebsd-x64@1.4.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-THbPKXhO54N0DpFRKZNDZpQ7dpbX0bWASuARckAUS9wRtFIHsiY+uULXJvxJGo2YD1YewvXQ4G8Fj7XT5oBCiw=="], + "@oven/bun-freebsd-x64": ["@oven/bun-freebsd-x64@1.4.4", "", { "os": "freebsd", "cpu": "x64" }, "sha512-sF1xS/scbyN94P2d0eTiarO6JHxrIvhZNT9hnWjQXW5nwKRtfuP+UYnIMNyvW1BQPcZFP/cvfLBNUIe1ea4zPA=="], - "@oven/bun-linux-aarch64": ["@oven/bun-linux-aarch64@1.4.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-3BBP9ovJ2RGHFH6Ae1CAtxNtG1+YY6GD6rmYbsUosoAk9+OEl6zeDQ/k4fBkc6dYOJCtWnx8hUxzNzQATSmvYQ=="], + "@oven/bun-linux-aarch64": ["@oven/bun-linux-aarch64@1.4.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-ZTVtpf9zmHSBVPX1sBwe5agGb/rN34yPGg/Hby8e2Ax2uCUA2URZKlZH7qLntK7qaFJCMXh9v0GWNYN2zINz1w=="], - "@oven/bun-linux-aarch64-android": ["@oven/bun-linux-aarch64-android@1.4.2", "", { "os": "android", "cpu": "arm64" }, "sha512-3mZKO2rhsNgbAUtAHC1UKUlF2zTxFraDZT/Elv8wzyH0fJL9h+Iv3TgB9lO63w89PRn3eFe+NRA1bhVgikKNPQ=="], + "@oven/bun-linux-aarch64-android": ["@oven/bun-linux-aarch64-android@1.4.4", "", { "os": "android", "cpu": "arm64" }, "sha512-5lvn3at5vRC0GxvmiqEiV2/e23tnRi0q5pzR40yfDvDA3OW7PSkt4chF1nA9vnAJhro4/l+ol1FmNP6D3cf/oA=="], - "@oven/bun-linux-aarch64-musl": ["@oven/bun-linux-aarch64-musl@1.4.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-+Sm6y+lSiSFBOtXmnekp5Q6n1tUKlyv71FCPWBc61Cgb14T5eBs8SN/nh4MUCOKzONkI3O+as3MGUgikS4aCBQ=="], + "@oven/bun-linux-aarch64-musl": ["@oven/bun-linux-aarch64-musl@1.4.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-QFd0P+mHJxbZFbUla4MgiE5OwxysHaUIYxL2pPNkpWtaI7v4ShOpr8OhBmsuyB0xn5rv/ZJnPsj2y8+bB9+g/A=="], - "@oven/bun-linux-x64": ["@oven/bun-linux-x64@1.4.2", "", { "os": "linux", "cpu": "x64" }, "sha512-9/E/UXOTpSo3YsV5g+FhtTd/qTpiWoKuxS12cqtuYA1ssu9fRAoPQnipFgGyck3tWO63iUdxBiygq+kELFawng=="], + "@oven/bun-linux-x64": ["@oven/bun-linux-x64@1.4.4", "", { "os": "linux", "cpu": "x64" }, "sha512-CHbbkmHVM28T1GFq+6GL4Ao4ujwwYwj1CxFFwEFzLanPfNsId9AhbIP0Q4reWuWBkGimUkoQygrK7Rgjtj3vog=="], - "@oven/bun-linux-x64-android": ["@oven/bun-linux-x64-android@1.4.2", "", { "os": "android", "cpu": "x64" }, "sha512-6HC5tzcC79113n2IHCTJMWv+HsQImv4ZFEK2XpYLxY6HbT8tM4cUM2Zv1bHZBQsS3jv/zYBamDJ1UX7If0d5tw=="], + "@oven/bun-linux-x64-android": ["@oven/bun-linux-x64-android@1.4.4", "", { "os": "android", "cpu": "x64" }, "sha512-3dMicj9C1DhaIfDkwt/9GtpU0W+q+GazbG9OIlEyL3Q1BBEz2e6ZRz/JiO8D/ECC0caXAqvnpFudehcLlgIwWQ=="], - "@oven/bun-linux-x64-musl": ["@oven/bun-linux-x64-musl@1.4.2", "", { "os": "linux", "cpu": "x64" }, "sha512-vVTKUg1bnPhRP/Hp73jIVoFh2vPFNYEqYX0ERKfZBOQEEHitNAeukZzzuUDZS0SoDCIpuWUGSpd/CDMbjdR+Uw=="], + "@oven/bun-linux-x64-musl": ["@oven/bun-linux-x64-musl@1.4.4", "", { "os": "linux", "cpu": "x64" }, "sha512-lEEjNOJJrbGZu2NVcPI4uXdILcpspezWkA8R/Jr0RCGhM6zQd0Y7JBIIKNAmbX59EeWpeEz7Q78iLbpcAUypUA=="], - "@oven/bun-windows-aarch64": ["@oven/bun-windows-aarch64@1.4.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-8EJ1ST7339WJE3poPW5nBgVW/lWf9HBz4W27ZUNhburKmcBLOByPyE6DP9fHD8FQGm5c+ilUN2hX1mrW0jxq9Q=="], + "@oven/bun-windows-aarch64": ["@oven/bun-windows-aarch64@1.4.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-n0ep5ZRPCZY1+dqFJpnnRUZB1wy4GYU6At8RF+pyzySCLjkN9R4rFh2PtBHAgF/lg1vOl3/CeER3pDM+p40ATA=="], - "@oven/bun-windows-x64": ["@oven/bun-windows-x64@1.4.2", "", { "os": "win32", "cpu": "x64" }, "sha512-+bN6OuVld/9diT/RLSXSW7JE6CvNE3gL9XsAEjULi1nUsXd6DNO6GuA9jNdNb3r8PdJFnYHr5aypNV1Oj3Rd9g=="], + "@oven/bun-windows-x64": ["@oven/bun-windows-x64@1.4.4", "", { "os": "win32", "cpu": "x64" }, "sha512-a3LNctBVO8PjePsFZfwDleF2JXYf2BfQ1u/PLRnBDLnC2Riml+4+LgJpKj4xRGhB92KweGyQI5PXaTkP9qypMQ=="], - "@types/bun": ["@types/bun@1.4.0", "", { "dependencies": { "bun-types": "1.4.0" } }, "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ=="], + "@types/bun": ["@types/bun@1.4.4", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="], "@types/node": ["@types/node@26.0.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-fc3KiUoBt6kie0N9bIW3E47vZsuaMf0PM2AaUpLCLT0s/LvX1nxAim6Fc049cNxODPpGm6qRAuUOB86SkRuPQw=="], @@ -137,11 +138,11 @@ "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], - "body-parser": ["body-parser@2.3.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="], + "body-parser": ["body-parser@2.4.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ=="], - "bun": ["bun@1.4.2", "", { "optionalDependencies": { "@oven/bun-darwin-aarch64": "1.4.2", "@oven/bun-darwin-x64": "1.4.2", "@oven/bun-freebsd-aarch64": "1.4.2", "@oven/bun-freebsd-x64": "1.4.2", "@oven/bun-linux-aarch64": "1.4.2", "@oven/bun-linux-aarch64-android": "1.4.2", "@oven/bun-linux-aarch64-musl": "1.4.2", "@oven/bun-linux-x64": "1.4.2", "@oven/bun-linux-x64-android": "1.4.2", "@oven/bun-linux-x64-musl": "1.4.2", "@oven/bun-windows-aarch64": "1.4.2", "@oven/bun-windows-x64": "1.4.2" }, "os": [ "!aix", "!sunos", "!openbsd", ], "cpu": [ "x64", "arm64", ], "bin": { "bun": "bin/bun.exe", "bunx": "bin/bunx.exe" } }, "sha512-TrSXo6HJfIEaczpb3kjX82I2pL47vK1QUNmHRCUdz9IzaOwa9lzOXSWwu2l18YHE3sNfGRapVLd4nNm+22vVVA=="], + "bun": ["bun@1.4.4", "", { "optionalDependencies": { "@oven/bun-darwin-aarch64": "1.4.4", "@oven/bun-darwin-x64": "1.4.4", "@oven/bun-freebsd-aarch64": "1.4.4", "@oven/bun-freebsd-x64": "1.4.4", "@oven/bun-linux-aarch64": "1.4.4", "@oven/bun-linux-aarch64-android": "1.4.4", "@oven/bun-linux-aarch64-musl": "1.4.4", "@oven/bun-linux-x64": "1.4.4", "@oven/bun-linux-x64-android": "1.4.4", "@oven/bun-linux-x64-musl": "1.4.4", "@oven/bun-windows-aarch64": "1.4.4", "@oven/bun-windows-x64": "1.4.4" }, "os": [ "!aix", "!sunos", "!openbsd", ], "cpu": [ "x64", "arm64", ], "bin": { "bun": "bin/bun.exe", "bunx": "bin/bunx.exe" } }, "sha512-hj0ASdG6PNjLZGFAXktWb3Uaj/dcv/1wCsIttoEXADNIQBsGjTr+5uLKYbrDkuc7NT0Tkj4yPIqJI2jDxXdvVg=="], - "bun-types": ["bun-types@1.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q=="], + "bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="], "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], @@ -211,7 +212,7 @@ "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], - "hono": ["hono@4.13.8", "", {}, "sha512-/Gng7NfoykZl2pjukW5Z6+8Yxm3BPRf86GTbQnt0SbySkvax4fyL4H3HhY1cCpBGmiW9XDRFzRV+CXK2W8QudQ=="], + "hono": ["hono@4.13.13", "", {}, "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA=="], "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], @@ -219,7 +220,7 @@ "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], - "ip-address": ["ip-address@10.7.1", "", {}, "sha512-4OUAqU9Z1i3vCnS05hzGiFnEMDpQ+62pAD/MVQOp83fYyNC8GleCqaS0QikQBmcWCrKFiUs/B8ztRRiYOAXuCA=="], + "ip-address": ["ip-address@10.7.4", "", {}, "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg=="], "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="], @@ -265,7 +266,7 @@ "proxy-addr": ["proxy-addr@2.0.8", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="], - "qs": ["qs@6.16.0", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA=="], + "qs": ["qs@6.16.1", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg=="], "range-parser": ["range-parser@1.3.0", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="], @@ -315,11 +316,13 @@ "wreq-js": ["wreq-js@2.3.1", "", { "os": [ "linux", "win32", "darwin", ], "cpu": [ "x64", "arm64", ] }, "sha512-vaKasaKeskrDKEuuO5Q5uamEG9a6FrF5ZSicH7TCvYS4RxF7/gzaU/vYqwJzcs+uydyJPVWY1KCvfVCgp0tiGA=="], - "zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], + "zod": ["zod@4.6.6", "", {}, "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA=="], "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], - "body-parser/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "body-parser/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "body-parser/iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], "type-is/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], } diff --git a/bunfig.toml b/bunfig.toml index 1a6ced2c5d..7376005a5c 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -16,8 +16,10 @@ root = "tests" # # That qualifier is load-bearing. Bun resolves bunfig.toml from the CURRENT WORKING # DIRECTORY, so `cd /tmp && bun test /tests/x.test.ts` loads no preload at all: nothing -# is sandboxed, the guard stays disarmed, and every `getConfigDir()` in that process returns -# the developer's real `~/.opencodex`. On 2026-09-15 such a run deleted one. A test that needs -# a config directory pins its own OPENCODEX_HOME instead of trusting this line, and -# `tests/ci-workflows/test-home-guard.test.ts` enforces that for the destructive case. +# is sandboxed, and every `getConfigDir()` in that process returns the developer's real +# `~/.opencodex`. On 2026-09-15 such a run deleted one, and in #7407 another wrote auth.json. +# The write guard now arms itself from the test-file entry in that case (src/lib/test-home-guard.ts), +# so such writes throw instead of landing, but a test that needs a config directory still pins its +# own OPENCODEX_HOME instead of trusting this line, and `tests/ci-workflows/test-home-guard.test.ts` +# enforces that for the destructive case. preload = ["./tests/preload.ts"] diff --git a/desktop/scripts/generate-icons.ts b/desktop/scripts/generate-icons.ts index 6ce6a00c26..5a770c65cd 100644 --- a/desktop/scripts/generate-icons.ts +++ b/desktop/scripts/generate-icons.ts @@ -6,8 +6,8 @@ * was a separate artifact that could drift from the others and nothing could detect it. This makes * the sizes derived: one curve, rendered at each dimension the platforms ask for. * - * The SVG reproduces the raster it replaced to within antialiasing (430 of 262144 pixels at 512), - * measured rather than assumed — the geometry in that file was read off the original bitmap. + * The mark in that file is scripts/brand/opencodex-mark.svg verbatim, white on a dark plate; the + * menu bar source (tray/icon.svg) reuses its curves and its prompt mask. * * `--check` regenerates into a temporary directory and compares, so CI can fail on a hand-edited * PNG instead of letting the source and the shipped icons disagree quietly. @@ -71,7 +71,22 @@ const TRAY_OUTPUT = "tray/icon.png"; const TRAY_SIZE = 44; const traySource = join(iconsDir, "tray", "icon.svg"); const DOTTED_TRAY_OUTPUT = "tray/icon-update.png"; -const DOTTED_TRAY_SVG = ''; +/** Bottom-right badge, in the coordinates of tray/icon.svg's viewBox. */ +const DOTTED_TRAY_SVG = ''; + +/** + * The .icns is rendered from the same plate without its corner radius. Windows, Linux and the + * Store tiles draw the icon as it is, so they get the rounded plate; macOS applies its own + * rounded-rectangle mask and material, and a pre-rounded corner fights it. + */ +function fullBleedSource(target: string): string { + const base = readFileSync(source, "utf8"); + const square = base.replace(/(]*?) rx="\d+"/, "$1"); + if (square === base) throw new Error("icon.svg has no rounded backdrop to square off"); + const out = join(target, ".icon-full-bleed.svg"); + writeFileSync(out, square); + return out; +} function renderDottedTray(target: string): void { const dottedSvg = join(target, ".tray-update.svg"); @@ -104,7 +119,9 @@ function generateInto(target: string): { produced: string[]; icnsSkipped: boolea const iconset = join(target, "icon.iconset"); mkdirSync(iconset, { recursive: true }); - for (const entry of ICNS_ENTRIES) render(entry.size, join(iconset, entry.name)); + const square = fullBleedSource(target); + try { for (const entry of ICNS_ENTRIES) render(entry.size, join(iconset, entry.name), square); } + finally { rmSync(square, { force: true }); } const icns = spawnSync("iconutil", ["-c", "icns", iconset, "-o", join(target, "icon.icns")]); const icnsSkipped = icns.status !== 0; if (!icnsSkipped) produced.push("icon.icns"); diff --git a/desktop/scripts/telemetry-installer-dialog.ts b/desktop/scripts/telemetry-installer-dialog.ts new file mode 100644 index 0000000000..1e36eb0060 --- /dev/null +++ b/desktop/scripts/telemetry-installer-dialog.ts @@ -0,0 +1,188 @@ +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { + TELEMETRY_DISCLOSURE_HEADING, + TELEMETRY_DISCLOSURE_POINTS, + TELEMETRY_POLICY_URL, +} from "../../src/telemetry/disclosure"; + +/** + * Generates the WiX fragment that adds the telemetry choice to the Windows installer. + * + * SignPath Foundation's conditions say software that sends usage data must describe it in a privacy + * policy, display that policy during installation, and include an installation option to disable + * it. The fragment inserts a dialog between the welcome and install-directory pages of Tauri's + * WixUI_InstallDir sequence. It shows the same disclosure the CLI prompt prints, links the policy, + * and offers a "Send anonymous usage statistics" checkbox, checked by default (unchecked when the + * install already carries an opt-out). The choice and a stamp of when it was made go to HKLM, so a + * silent install run as SYSTEM covers every user, and an upgrade carries the previous choice forward. + * The desktop app (`installer_telemetry.rs`) persists an opt-out into each user's opencodex config + * once per stamp, before it starts or attaches to a proxy. + * + * Silent installs choose with the public property: `msiexec /i OpenCodex.msi /qn OCX_TELEMETRY_CHOICE=optout`. + * + * `bun desktop/scripts/telemetry-installer-dialog.ts --write` regenerates the committed file; + * `--check` fails when it is stale. + */ + +export const TELEMETRY_INSTALLER_FRAGMENT_PATH = "wix/telemetry-choice.wxs"; +export const TELEMETRY_INSTALLER_COMPONENT_GROUP = "OcxTelemetryInstallerChoice"; +export const TELEMETRY_INSTALLER_DIALOG = "OcxTelemetryDlg"; +export const TELEMETRY_INSTALLER_REGISTRY_KEY = "Software\\OpenCodex\\Telemetry"; +export const TELEMETRY_INSTALLER_REGISTRY_VALUE = "InstallerChoice"; +export const TELEMETRY_INSTALLER_STAMP_VALUE = "InstallerChoiceStamp"; +export const TELEMETRY_INSTALLER_STAMP_PROPERTY = "OCX_TELEMETRY_STAMP"; +export const TELEMETRY_INSTALLER_CHOICE_PROPERTY = "OCX_TELEMETRY_CHOICE"; +export const TELEMETRY_INSTALLER_CHECKBOX_PROPERTY = "OCX_TELEMETRY_SEND"; +export const TELEMETRY_INSTALLER_CHECKBOX_TEXT = "Send anonymous usage statistics"; +// Shown under the checkbox: "send" is never acted on, and a new opt-out applies to every account. +export const TELEMETRY_INSTALLER_KEEP_NOTE = + "Checked keeps each account's choice; unchecking turns it off for all."; +export const TELEMETRY_INSTALLER_SEND = "send"; +export const TELEMETRY_INSTALLER_OPT_OUT = "optout"; +// Fixed so upgrades keep one component identity for the HKLM values (new when the key path moved to HKLM). +const COMPONENT_GUID = "B3E1C7D2-58A4-4F0E-9C6B-7A2D41E95F08"; + +// Dialog units. WiX's standard dialogs are 370 x 270 with the button row below y = 234. +const TEXT_LEFT = 20; +const TEXT_WIDTH = 330; +const CHARS_PER_LINE = 72; +const LINE_HEIGHT = 10; +const POINTS_TOP = 50; +const POINT_GAP = 2; + +function xmlAttr(value: string): string { + // MSI formats control text, so brackets would be read as property references. + if (/[[\]{}]/.test(value)) throw new Error(`Installer text must not contain brackets or braces: ${value}`); + // The en-US MSI database uses code page 1252; keep to ASCII plus the bullet it also carries. + if (!/^[\x20-\x7E•]*$/.test(value)) throw new Error(`Installer text must stay within code page 1252: ${value}`); + return value + .replaceAll("&", "&") + .replaceAll('"', """) + .replaceAll("<", "<") + .replaceAll(">", ">"); +} + +function wrappedLines(text: string): number { + let lines = 1; + let width = 0; + for (const word of text.split(" ")) { + const next = width === 0 ? word.length : width + 1 + word.length; + if (next > CHARS_PER_LINE && width > 0) { + lines += 1; + width = word.length; + } else { + width = next; + } + } + return lines; +} + +export function renderTelemetryInstallerFragment(): string { + const controls: string[] = []; + let y = POINTS_TOP; + TELEMETRY_DISCLOSURE_POINTS.forEach((point, index) => { + const height = wrappedLines(point) * LINE_HEIGHT; + controls.push( + ` `, + ); + y += height + POINT_GAP; + }); + const linkY = y + 2; + const checkboxY = linkY + 14; + const noteY = checkboxY + 17; + if (noteY + LINE_HEIGHT > 232) { + throw new Error(`The telemetry disclosure no longer fits the installer dialog (it ends at ${noteY + LINE_HEIGHT}).`); + } + return ` + + + + + + + + + + + + + + + + + + + + + ${TELEMETRY_INSTALLER_CHOICE_PROPERTY} <> "" AND ${TELEMETRY_INSTALLER_CHOICE_PROPERTY} ~<> "${TELEMETRY_INSTALLER_SEND}" + + ${TELEMETRY_INSTALLER_CHOICE_PROPERTY} <> "" AND ${TELEMETRY_INSTALLER_STAMP_PROPERTY} = "" + ${TELEMETRY_INSTALLER_CHOICE_PROPERTY} = "" AND OCX_TELEMETRY_PREVIOUS_CHOICE <> "" + ${TELEMETRY_INSTALLER_STAMP_PROPERTY} = "" AND OCX_TELEMETRY_PREVIOUS_STAMP <> "" + + ${TELEMETRY_INSTALLER_STAMP_PROPERTY} <> "" + + ${TELEMETRY_INSTALLER_CHOICE_PROPERTY} = "" + + ${TELEMETRY_INSTALLER_CHOICE_PROPERTY} ~= "${TELEMETRY_INSTALLER_SEND}" + + + + + + + + + + + + + + +${controls.join("\n")} + + Read the full privacy policy]]> + + + + + 1 + + + ${TELEMETRY_INSTALLER_CHECKBOX_PROPERTY} = "1" + NOT (${TELEMETRY_INSTALLER_CHECKBOX_PROPERTY} = "1") + ${TELEMETRY_INSTALLER_CHOICE_PROPERTY} ~<> OCX_TELEMETRY_PREVIOUS_CHOICE + ${TELEMETRY_INSTALLER_CHOICE_PROPERTY} ~= OCX_TELEMETRY_PREVIOUS_CHOICE AND OCX_TELEMETRY_CARRIED_STAMP <> "" + 1 + + + 1 + + + + NOT Installed + NOT Installed + + + +`; +} + +if (import.meta.main) { + const target = join(import.meta.dir, "..", "src-tauri", TELEMETRY_INSTALLER_FRAGMENT_PATH); + const expected = renderTelemetryInstallerFragment(); + if (process.argv.includes("--write")) { + writeFileSync(target, expected, "utf8"); + } else { + let actual = ""; + try { actual = readFileSync(target, "utf8"); } catch { /* missing counts as stale */ } + if (actual !== expected) { + console.error(`${TELEMETRY_INSTALLER_FRAGMENT_PATH} is stale; run bun desktop/scripts/telemetry-installer-dialog.ts --write`); + process.exit(1); + } + } +} diff --git a/desktop/scripts/verify-release-assets.ts b/desktop/scripts/verify-release-assets.ts index 0c3175791b..d6845a470b 100644 --- a/desktop/scripts/verify-release-assets.ts +++ b/desktop/scripts/verify-release-assets.ts @@ -11,9 +11,10 @@ * version and commit before it uploads anything, so publication can only ever * consume the verified bundle. */ -import { createHash, createPublicKey, verify as ed25519Verify, type KeyObject } from "node:crypto"; +import { createHash, type KeyObject } from "node:crypto"; import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; +import { decodePublicKey, verifyLegacyMinisignBytes } from "../../src/update/minisign.mjs"; import { standaloneArchiveName, standaloneTargets as sharedStandaloneTargets, @@ -122,8 +123,6 @@ export function verifyChecksums(dir: string): number { return checksumFiles.length; } -const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex"); - export interface MinisignPublicKey { keyId: string; publicKey: KeyObject; @@ -146,31 +145,10 @@ function decodeBox(text: string, what: string): string { return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(payload); } -function boxLines(text: string): string[] { - // Accept minisign text with LF or CRLF and an optional terminal newline; - // signatures authenticate decoded bytes/comments, not transport line endings. - return text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n"); -} - /** minisign public key: base64 of algorithm ("Ed") || key id (8) || raw key (32). */ export function parseMinisignPublicKey(text: string): MinisignPublicKey { - const lines = boxLines(text); - if (lines.length !== 2 || !lines[0]!.startsWith("untrusted comment: ")) { - throw new Error("Malformed minisign public key box"); - } - const payload = decodeBase64(lines[1]!, "minisign public key", 42); - const algorithm = payload.subarray(0, 2).toString("utf8"); - if (algorithm !== "Ed") { - throw new Error(`Unsupported minisign public key algorithm: ${JSON.stringify(algorithm)}`); - } - return { - keyId: payload.subarray(2, 10).toString("hex"), - publicKey: createPublicKey({ - key: Buffer.concat([ED25519_SPKI_PREFIX, payload.subarray(10, 42)]), - format: "der", - type: "spki", - }), - }; + const { keyId, publicKey } = decodePublicKey(text); + return { keyId, publicKey }; } /** The updater public key pinned in the Tauri configuration. */ @@ -187,34 +165,10 @@ export function loadUpdaterPublicKey(tauriConfPath: string): MinisignPublicKey { export function verifyUpdaterSignature(filePath: string, key: MinisignPublicKey): void { const signaturePath = `${filePath}.sig`; if (!existsSync(signaturePath)) throw new Error(`Missing signature: ${signaturePath}`); - const lines = boxLines(decodeBox(readFileSync(signaturePath, "utf8"), "Tauri signature")); - const trustedPrefix = "trusted comment: "; - if (lines.length !== 4 || !lines[0]!.startsWith("untrusted comment: ") - || !lines[2]!.startsWith(trustedPrefix)) { - throw new Error(`Malformed signature box in ${signaturePath}`); - } - const payload = decodeBase64(lines[1]!, "signature packet", 74); - const globalSignature = decodeBase64(lines[3]!, "comment signature", 64); - const algorithm = payload.subarray(0, 2).toString("utf8"); - if (algorithm !== "ED") { - throw new Error(`Unsupported signature algorithm in ${signaturePath}: ${JSON.stringify(algorithm)}`); - } - const keyId = payload.subarray(2, 10).toString("hex"); - if (keyId !== key.keyId) { - throw new Error(`Signature ${signaturePath} was made by key ${keyId}, not the pinned updater key ${key.keyId}`); - } - const signature = payload.subarray(10, 74); - // ED is ordinary Ed25519 over the BLAKE2b-512 digest, not Ed25519ph. - const digest = createHash("blake2b512").update(readFileSync(filePath)).digest(); - if (!ed25519Verify(null, digest, key.publicKey, signature)) { - throw new Error(`Signature verification failed for ${filePath}`); - } - // minisign signs the raw signature + trimmed trusted comment, without its - // prefix or line terminator. The original filename may differ after collection. - const trustedComment = lines[2]!.slice(trustedPrefix.length).trim(); - const message = Buffer.concat([signature, Buffer.from(trustedComment, "utf8")]); - if (!ed25519Verify(null, message, key.publicKey, globalSignature)) { - throw new Error(`Comment signature verification failed for ${filePath}`); + try { + verifyLegacyMinisignBytes(readFileSync(filePath), readFileSync(signaturePath, "utf8"), key); + } catch (error) { + throw new Error(`${error instanceof Error ? error.message : String(error)}: ${filePath}`); } } diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index a462eaea16..8346f8d9bc 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "addr2line" -version = "0.25.1" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" +checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4" dependencies = [ "gimli", ] @@ -28,25 +28,19 @@ dependencies = [ [[package]] name = "alloc-no-stdlib" -version = "2.0.4" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" [[package]] name = "alloc-stdlib" -version = "0.2.4" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" dependencies = [ "alloc-no-stdlib", ] -[[package]] -name = "android-tzdata" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" - [[package]] name = "android_system_properties" version = "0.1.6" @@ -62,15 +56,6 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "async-broadcast" version = "0.7.2" @@ -158,13 +143,13 @@ dependencies = [ [[package]] name = "async-recursion" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -199,7 +184,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -250,14 +235,14 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "backtrace" -version = "0.3.76" +version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" +checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f" dependencies = [ "addr2line", "cfg-if", "libc", - "miniz_oxide 0.8.9", + "miniz_oxide 0.9.1", "object", "rustc-demangle", "windows-link 0.2.1", @@ -304,11 +289,11 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.9.4" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" dependencies = [ - "serde", + "serde_core", ] [[package]] @@ -344,9 +329,9 @@ dependencies = [ [[package]] name = "brotli" -version = "8.0.4" +version = "9.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -355,9 +340,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "5.0.3" +version = "6.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +checksum = "34c6783f42c21c952ad7112b354f0ba2f10760e9decea5b1b60523d6e270faaf" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -411,7 +396,7 @@ version = "0.18.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "cairo-sys-rs", "glib", "libc", @@ -432,11 +417,11 @@ dependencies = [ [[package]] name = "camino" -version = "1.1.12" +version = "1.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd0b03af37dad7a14518b7691d81acb0f8222604ad3d1b02f6b4bed5188c0cd5" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" dependencies = [ - "serde", + "serde_core", ] [[package]] @@ -459,24 +444,25 @@ dependencies = [ "semver", "serde", "serde_json", - "thiserror 2.0.20", + "thiserror 2.0.21", ] [[package]] name = "cargo_toml" -version = "0.22.3" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77" +checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9" dependencies = [ + "semver", "serde", - "toml 0.9.5", + "toml 1.1.8+spec-1.1.0", ] [[package]] name = "cc" -version = "1.4.7" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" dependencies = [ "find-msvc-tools", "shlex", @@ -490,13 +476,13 @@ checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" [[package]] name = "cfb" -version = "0.7.3" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f" +checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3" dependencies = [ - "byteorder", "fnv", "uuid", + "web-time", ] [[package]] @@ -534,22 +520,21 @@ dependencies = [ [[package]] name = "chrono" -version = "0.4.41" +version = "0.4.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ - "android-tzdata", "iana-time-zone", "num-traits", "serde", - "windows-link 0.1.3", + "windows-link 0.2.1", ] [[package]] name = "combine" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -574,6 +559,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -596,8 +591,8 @@ version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" dependencies = [ - "bitflags 2.9.4", - "core-foundation", + "bitflags 2.13.2", + "core-foundation 0.10.1", "core-graphics-types", "foreign-types", "libc", @@ -609,8 +604,8 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" dependencies = [ - "bitflags 2.9.4", - "core-foundation", + "bitflags 2.13.2", + "core-foundation 0.10.1", "libc", ] @@ -640,9 +635,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.2" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" dependencies = [ "cfg-if", ] @@ -674,9 +669,9 @@ dependencies = [ [[package]] name = "cssparser" -version = "0.36.0" +version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2" +checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" dependencies = [ "cssparser-macros", "dtoa-short", @@ -687,29 +682,19 @@ dependencies = [ [[package]] name = "cssparser-macros" -version = "0.6.1" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" +checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" dependencies = [ "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "ctor" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "352d39c2f7bef1d6ad73db6f5160efcaed66d94ef8c6c573a8410c00bf909a98" -dependencies = [ - "ctor-proc-macro", - "dtor", -] - -[[package]] -name = "ctor-proc-macro" -version = "0.0.7" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1" +checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" [[package]] name = "darling" @@ -731,7 +716,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -742,7 +727,7 @@ checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ "darling_core", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -758,9 +743,9 @@ dependencies = [ [[package]] name = "defmt" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" dependencies = [ "bitflags 1.3.2", "defmt-macros", @@ -768,45 +753,34 @@ dependencies = [ [[package]] name = "defmt-macros" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" dependencies = [ "defmt-parser", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "defmt-parser" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ - "thiserror 2.0.20", + "thiserror 2.0.21", ] [[package]] name = "deranged" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" dependencies = [ "serde_core", ] -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "derive_more" version = "2.1.1" @@ -850,9 +824,9 @@ dependencies = [ [[package]] name = "dirs" -version = "6.0.0" +version = "7.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" dependencies = [ "dirs-sys 0.5.0", ] @@ -886,7 +860,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "block2", "libc", "objc2", @@ -900,7 +874,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -928,9 +902,9 @@ dependencies = [ [[package]] name = "dom_query" -version = "0.27.0" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89" +checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc" dependencies = [ "bit-set", "cssparser", @@ -965,21 +939,6 @@ dependencies = [ "dtoa", ] -[[package]] -name = "dtor" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1057d6c64987086ff8ed0fd3fbf377a6b7d205cc7715868cd401705f715cbe4" -dependencies = [ - "dtor-proc-macro", -] - -[[package]] -name = "dtor-proc-macro" -version = "0.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5" - [[package]] name = "dunce" version = "1.0.5" @@ -994,16 +953,16 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" [[package]] name = "embed-resource" -version = "3.0.8" +version = "3.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63a1d0de4f2249aa0ff5884d7080814f446bb241a559af6c170a41e878ed2d45" +checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f" dependencies = [ "cc", "memchr", "rustc_version", - "toml 0.9.5", + "toml 1.1.8+spec-1.1.0", "vswhom", - "winreg 0.55.0", + "winreg 0.56.0", ] [[package]] @@ -1014,13 +973,12 @@ checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" [[package]] name = "encoding_rs" -version = "0.8.41" +version = "0.8.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5ef0006ac9ab233c38522f5ae99cae3625151de8f706cacee1cba4b8e2832a" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" dependencies = [ "cfg-if", "core_detect", - "multiversion", "multiversion_no_op", "rustversion", "scopeguard", @@ -1056,17 +1014,18 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "erased-serde" -version = "0.4.6" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e004d887f51fcb9fef17317a2f3525c887d8aa3f4f50fed920816a688284a5b7" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" dependencies = [ "serde", + "serde_core", "typeid", ] @@ -1137,9 +1096,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.13" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "flate2" @@ -1182,7 +1141,7 @@ checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -1253,7 +1212,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -1434,9 +1393,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.32.3" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" [[package]] name = "gio" @@ -1476,7 +1435,7 @@ version = "0.18.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "futures-channel", "futures-core", "futures-executor", @@ -1633,9 +1592,9 @@ dependencies = [ [[package]] name = "html5ever" -version = "0.38.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1054432bae2f14e0061e33d23402fbaa67a921d319d56adc6bcf887ddad1cbc2" +checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" dependencies = [ "log", "markup5ever", @@ -1682,13 +1641,12 @@ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "hyper" -version = "1.11.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", - "futures-channel", "futures-core", "http", "http-body", @@ -1702,9 +1660,9 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.9" +version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ "http", "hyper", @@ -1718,25 +1676,28 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.20" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "bytes", "futures-channel", "futures-util", "http", "http-body", + "httparse", "hyper", "ipnet", "libc", "percent-encoding", "pin-project-lite", "socket2 0.6.5", + "system-configuration", "tokio", "tower-service", "tracing", + "windows-registry", ] [[package]] @@ -1765,19 +1726,19 @@ dependencies = [ [[package]] name = "ico" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371" +checksum = "d75e94d66081e4d8dcd098bd8dc5254800fea14a26389b298410158d834de167" dependencies = [ "byteorder", - "png 0.17.16", + "png", ] [[package]] name = "icu_collections" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -1789,9 +1750,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -1802,9 +1763,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -1816,15 +1777,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ "displaydoc", "icu_collections", @@ -1837,15 +1798,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -1893,7 +1854,7 @@ dependencies = [ "byteorder-lite", "moxcms", "num-traits", - "png 0.18.1", + "png", ] [[package]] @@ -1921,9 +1882,9 @@ dependencies = [ [[package]] name = "infer" -version = "0.19.0" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7" +checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4" dependencies = [ "cfb", ] @@ -1984,9 +1945,9 @@ dependencies = [ [[package]] name = "jiff" -version = "0.2.37" +version = "0.2.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" dependencies = [ "defmt", "jiff-core", @@ -2011,9 +1972,9 @@ dependencies = [ [[package]] name = "jiff-static" -version = "0.2.37" +version = "0.2.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" dependencies = [ "jiff-core", "proc-macro2", @@ -2023,9 +1984,9 @@ dependencies = [ [[package]] name = "jiff-tzdb" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" [[package]] name = "jiff-tzdb-platform" @@ -2052,6 +2013,36 @@ dependencies = [ "windows-sys 0.45.0", ] +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link 0.2.1", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + [[package]] name = "jni-sys" version = "0.3.1" @@ -2082,9 +2073,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.105" +version = "0.3.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" dependencies = [ "cfg-if", "futures-util", @@ -2093,21 +2084,21 @@ dependencies = [ [[package]] name = "json-patch" -version = "3.0.1" +version = "4.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08" +checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" dependencies = [ "jsonptr", "serde", "serde_json", - "thiserror 1.0.69", + "thiserror 2.0.21", ] [[package]] name = "jsonptr" -version = "0.6.3" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70" +checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe" dependencies = [ "serde", "serde_json", @@ -2115,13 +2106,12 @@ dependencies = [ [[package]] name = "keyboard-types" -version = "0.7.0" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "serde", - "unicode-segmentation", ] [[package]] @@ -2150,9 +2140,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libdbus-sys" @@ -2175,9 +2165,9 @@ dependencies = [ [[package]] name = "libredox" -version = "0.1.24" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6480ccc157a1389bb2e4891b24751b0f798ba640d22386f23143fbcc89da195a" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ "libc", ] @@ -2217,9 +2207,9 @@ checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" [[package]] name = "markup5ever" -version = "0.38.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8983d30f2915feeaaab2d6babdd6bc7e9ed1a00b66b5e6d74df19aa9c0e91862" +checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" dependencies = [ "log", "tendril", @@ -2249,9 +2239,9 @@ checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" [[package]] name = "minisign-verify" -version = "0.2.5" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22f9645cb765ea72b8111f36c522475d2daa0d22c957a9826437e97534bc4e9e" +checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce" [[package]] name = "miniz_oxide" @@ -2275,9 +2265,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.3" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", @@ -2296,9 +2286,9 @@ dependencies = [ [[package]] name = "muda" -version = "0.19.3" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dd04e60bc0b07438a6771710ee1698f98f6ebbc7f89b61264af1563b8aeb878" +checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996" dependencies = [ "crossbeam-channel", "dpi", @@ -2309,33 +2299,12 @@ dependencies = [ "objc2-core-foundation", "objc2-foundation", "once_cell", - "png 0.18.1", + "png", "serde", - "thiserror 2.0.20", + "thiserror 2.0.21", "windows-sys 0.61.2", ] -[[package]] -name = "multiversion" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ca4bea16ffc3f443cf7d866912118196bfef4c6a1556ca00f9f9b00bb43f7c" -dependencies = [ - "multiversion-macros", -] - -[[package]] -name = "multiversion-macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d416831a7317ef4b08bee00b69cbbb9c8763da7959a7026244d6266869f9c83" -dependencies = [ - "proc-macro2", - "quote", - "rustversion", - "syn 3.0.6", -] - [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -2348,7 +2317,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "jni-sys 0.3.1", "log", "ndk-sys", @@ -2357,6 +2326,12 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + [[package]] name = "ndk-sys" version = "0.6.0+11769913" @@ -2372,6 +2347,18 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -2403,7 +2390,7 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" dependencies = [ - "proc-macro-crate 3.4.0", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 2.0.119", @@ -2411,9 +2398,9 @@ dependencies = [ [[package]] name = "objc2" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" dependencies = [ "objc2-encode", "objc2-exception-helper", @@ -2425,11 +2412,12 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "block2", "objc2", "objc2-core-foundation", "objc2-foundation", + "objc2-quartz-core", ] [[package]] @@ -2438,7 +2426,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "objc2", "objc2-foundation", ] @@ -2459,7 +2447,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "dispatch2", "objc2", ] @@ -2470,7 +2458,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "dispatch2", "objc2", "objc2-core-foundation", @@ -2503,7 +2491,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "objc2", "objc2-core-foundation", "objc2-core-graphics", @@ -2530,7 +2518,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "block2", "libc", "objc2", @@ -2543,7 +2531,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "objc2", "objc2-core-foundation", ] @@ -2554,7 +2542,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "objc2", "objc2-app-kit", "objc2-foundation", @@ -2566,7 +2554,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "objc2", "objc2-core-foundation", "objc2-foundation", @@ -2578,7 +2566,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "block2", "objc2", "objc2-cloud-kit", @@ -2609,7 +2597,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "block2", "objc2", "objc2-app-kit", @@ -2619,9 +2607,9 @@ dependencies = [ [[package]] name = "object" -version = "0.37.3" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" dependencies = [ "memchr", ] @@ -2634,9 +2622,9 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "open" -version = "5.4.4" +version = "5.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa576c76302b7b808eecc68061e67336c47833ef9d22caa74dda10fa9675eebc" +checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" dependencies = [ "dunce", "is-wsl", @@ -2645,7 +2633,7 @@ dependencies = [ [[package]] name = "opencodex-desktop" -version = "2.89.1-dalsoop.1" +version = "2.100.2" dependencies = [ "base64 0.22.1", "dbus", @@ -2668,6 +2656,12 @@ dependencies = [ "winreg 0.55.0", ] +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "option-ext" version = "0.2.0" @@ -2705,7 +2699,7 @@ dependencies = [ "objc2-osa-kit", "serde", "serde_json", - "thiserror 2.0.20", + "thiserror 2.0.21", ] [[package]] @@ -2846,37 +2840,24 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "plist" -version = "1.8.0" +version = "1.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "indexmap 2.14.2", "quick-xml", "serde", "time", ] -[[package]] -name = "png" -version = "0.17.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" -dependencies = [ - "bitflags 1.3.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - [[package]] name = "png" version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "crc32fast", "fdeflate", "flate2", @@ -2923,9 +2904,9 @@ dependencies = [ [[package]] name = "powerfmt" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" [[package]] name = "precomputed-hash" @@ -2955,11 +2936,11 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "3.4.0" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.23.4", + "toml_edit 0.25.17+spec-1.1.0", ] [[package]] @@ -3003,9 +2984,9 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" [[package]] name = "quick-xml" -version = "0.38.4" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" dependencies = [ "memchr", ] @@ -3024,7 +3005,7 @@ dependencies = [ "rustc-hash", "rustls", "socket2 0.6.5", - "thiserror 2.0.20", + "thiserror 2.0.21", "tokio", "tracing", "web-time", @@ -3032,9 +3013,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.18" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9746dbde176634f4f2f1faf2404e30a31b2bc1e9cafb5329c95d8177a18c9fc" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", "getrandom 0.4.3", @@ -3046,7 +3027,7 @@ dependencies = [ "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.20", + "thiserror 2.0.21", "tinyvec", "tracing", "web-time", @@ -3054,9 +3035,9 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", @@ -3089,9 +3070,9 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", "getrandom 0.4.3", @@ -3125,7 +3106,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", ] [[package]] @@ -3146,7 +3127,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" dependencies = [ "libredox", - "thiserror 2.0.20", + "thiserror 2.0.21", ] [[package]] @@ -3166,7 +3147,7 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -3207,7 +3188,6 @@ dependencies = [ "base64 0.22.1", "bytes", "futures-core", - "futures-util", "http", "http-body", "http-body-util", @@ -3227,14 +3207,12 @@ dependencies = [ "sync_wrapper", "tokio", "tokio-rustls", - "tokio-util", "tower", "tower-http", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", - "wasm-streams 0.4.2", "web-sys", "webpki-roots", ] @@ -3253,15 +3231,20 @@ dependencies = [ "http-body", "http-body-util", "hyper", + "hyper-rustls", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", "serde", "serde_json", "sync_wrapper", "tokio", + "tokio-rustls", "tokio-util", "tower", "tower-http", @@ -3269,7 +3252,7 @@ dependencies = [ "url", "wasm-bindgen", "wasm-bindgen-futures", - "wasm-streams 0.5.0", + "wasm-streams", "web-sys", ] @@ -3310,11 +3293,11 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys", @@ -3323,9 +3306,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "once_cell", "ring", @@ -3335,6 +3318,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pki-types" version = "1.15.1" @@ -3345,11 +3340,38 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni 0.22.4", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", @@ -3377,6 +3399,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "schemars" version = "0.8.22" @@ -3406,9 +3437,9 @@ dependencies = [ [[package]] name = "schemars" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ "dyn-clone", "ref-cast", @@ -3434,13 +3465,36 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "selectors" -version = "0.36.1" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5d9c0c92a92d33f08817311cf3f2c29a3538a8240e94a6a3c622ce652d7e00c" +checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "cssparser", "derive_more", "log", @@ -3455,11 +3509,12 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.26" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56e6fa9c48d24d85fb3de5ad847117517440f6beceb7798af16b4a87d616b8d0" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" dependencies = [ "serde", + "serde_core", ] [[package]] @@ -3474,12 +3529,13 @@ dependencies = [ [[package]] name = "serde-untagged" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34836a629bcbc6f1afdf0907a744870039b1e14c0561cb26094fa683b158eff3" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" dependencies = [ "erased-serde", "serde", + "serde_core", "typeid", ] @@ -3500,7 +3556,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -3535,7 +3591,7 @@ checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -3549,11 +3605,11 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.0.0" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40734c41988f7306bb04f0ecf60ec0f3f1caa34290e4e8ea471dcd3346483b83" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" dependencies = [ - "serde", + "serde_core", ] [[package]] @@ -3570,9 +3626,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.23.0" +version = "3.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "935177bb8c0cd8ca1a4e6d1a2ac8988bea69cab4f9d3a31311e012ad27868ea4" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" dependencies = [ "base64 0.23.1", "bs58", @@ -3582,7 +3638,7 @@ dependencies = [ "indexmap 2.14.2", "jiff", "schemars 0.9.0", - "schemars 1.2.2", + "schemars 1.2.3", "serde_core", "serde_json", "serde_with_macros", @@ -3591,14 +3647,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.23.0" +version = "3.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d607aa01a3cb0ad757d6fd216136910db3c97b102fe686585689615a02dbcdc" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" dependencies = [ "darling", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -3673,9 +3729,9 @@ dependencies = [ [[package]] name = "signal-hook" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a0c28ca5908dbdbcd52e6fdaa00358ab88637f8ab33e1f188dd510eb44b53d" +checksum = "b29ffa27d3d59a049bb328258de100f8012848d1b08d444e08bbc02ac468435e" dependencies = [ "libc", "signal-hook-registry", @@ -3697,6 +3753,16 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + [[package]] name = "simdutf8" version = "0.1.5" @@ -3705,9 +3771,9 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "siphasher" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" [[package]] name = "slab" @@ -3717,9 +3783,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.1" +version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" [[package]] name = "socket2" @@ -3795,6 +3861,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_vcruntime" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7" + [[package]] name = "string_cache" version = "0.9.0" @@ -3833,9 +3905,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "swift-rs" -version = "1.0.8" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e45c444e496845d3f2a351146bff59aae4975b2280238df1dfaa0c7d1846f38e" +checksum = "cefd87076fd385308ee4aff597256c902f1fbb4d031de1558efc12f8ffefadd9" dependencies = [ "base64 0.21.7", "serde", @@ -3865,9 +3937,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.6" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", @@ -3891,7 +3963,28 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", ] [[package]] @@ -3909,13 +4002,13 @@ dependencies = [ [[package]] name = "tao" -version = "0.35.3" +version = "0.37.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9" +checksum = "d5777b06fe6435126ae8d816eba269e050e1e10d302cf5461e9c49eccabc3548" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "block2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics", "crossbeam-channel", "dbus", @@ -3925,24 +4018,24 @@ dependencies = [ "gdkwayland-sys", "gdkx11-sys", "gtk", - "jni", + "jni 0.21.1", "libc", "log", "ndk", + "ndk-context", "ndk-sys", "objc2", "objc2-app-kit", "objc2-foundation", "objc2-ui-kit", - "once_cell", "parking_lot", "percent-encoding", "raw-window-handle", "tao-macros", "unicode-segmentation", "url", - "windows", - "windows-core 0.61.2", + "windows 0.62.2", + "windows-core 0.62.2", "windows-version", "x11-dl", ] @@ -3977,14 +4070,14 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" [[package]] name = "tauri" -version = "2.11.6" +version = "2.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fa5bacdb9bbad5954af3d1bd6cf6ae9192cab1b2e270f4a07f904610b9e85f4" +checksum = "5fb0244332cfb9cee7e2a568bf5da29a36ed8fdbd717f6f47a66b6b7b358c072" dependencies = [ "anyhow", "bytes", "cookie", - "dirs 6.0.0", + "dirs 7.0.0", "dunce", "embed_plist", "getrandom 0.3.4", @@ -3993,7 +4086,7 @@ dependencies = [ "heck 0.5.0", "http", "image", - "jni", + "jni 0.21.1", "libc", "log", "mime", @@ -4017,25 +4110,25 @@ dependencies = [ "tauri-runtime", "tauri-runtime-wry", "tauri-utils", - "thiserror 2.0.20", + "thiserror 2.0.21", "tokio", "tray-icon", "url", "webkit2gtk", "webview2-com", "window-vibrancy", - "windows", + "windows 0.62.2", ] [[package]] name = "tauri-build" -version = "2.6.3" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc9ce40b16101cb6ea63d3e221567affd1c3a9205f95d7bc574941a10636b632" +checksum = "adddb0e648752aaac5da9c3c3c6a68e1e87cab55e3b757b18a9441ef8c3ac614" dependencies = [ "anyhow", "cargo_toml", - "dirs 6.0.0", + "dirs 7.0.0", "glob", "heck 0.5.0", "json-patch", @@ -4043,6 +4136,8 @@ dependencies = [ "semver", "serde", "serde_json", + "static_vcruntime", + "strsim", "tauri-utils", "tauri-winres", "walkdir", @@ -4050,16 +4145,16 @@ dependencies = [ [[package]] name = "tauri-codegen" -version = "2.6.3" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08279169ff42f8fc45a1dbc9dcae888893ba95288142e5880c59b93a26d2cfc5" +checksum = "fb37631cf71dab5e8ab55e1bdd701e18a52653d90b78e71d0e5598b1e0a61316" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "brotli", "ico", "json-patch", "plist", - "png 0.17.16", + "png", "proc-macro2", "quote", "semver", @@ -4068,7 +4163,7 @@ dependencies = [ "sha2", "syn 2.0.119", "tauri-utils", - "thiserror 2.0.20", + "thiserror 2.0.21", "time", "url", "uuid", @@ -4077,9 +4172,9 @@ dependencies = [ [[package]] name = "tauri-macros" -version = "2.6.3" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8b394794f399a421811d06966343e7933fcae92d59f5180b9388d1174497a45" +checksum = "0cc38db58854c10fb5f91a887ed8bf82d3239bb92b5d8db86eda09e96d9963d1" dependencies = [ "heck 0.5.0", "proc-macro2", @@ -4091,9 +4186,9 @@ dependencies = [ [[package]] name = "tauri-plugin" -version = "2.6.3" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74be5dd4bed9afbd145e5716b5fa2ec28cbc29c34ffa61c258c9273d896c8020" +checksum = "67fb21a77e8f94e8beb3325e583102488659365af0a3948b7ea244c5b779c291" dependencies = [ "anyhow", "glob", @@ -4116,7 +4211,7 @@ dependencies = [ "serde_json", "tauri", "tauri-plugin", - "thiserror 2.0.20", + "thiserror 2.0.21", ] [[package]] @@ -4135,9 +4230,9 @@ dependencies = [ "serde_json", "tauri", "tauri-plugin", - "thiserror 2.0.20", + "thiserror 2.0.21", "url", - "windows", + "windows 0.61.3", "zbus", ] @@ -4168,7 +4263,7 @@ dependencies = [ "shared_child", "tauri", "tauri-plugin", - "thiserror 2.0.20", + "thiserror 2.0.21", "tokio", ] @@ -4181,7 +4276,7 @@ dependencies = [ "serde", "serde_json", "tauri", - "thiserror 2.0.20", + "thiserror 2.0.21", "tracing", "windows-sys 0.60.2", "zbus", @@ -4189,21 +4284,23 @@ dependencies = [ [[package]] name = "tauri-plugin-updater" -version = "2.9.0" +version = "2.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27cbc31740f4d507712550694749572ec0e43bdd66992db7599b89fbfd6b167b" +checksum = "d957abbcb3f9f6c76d22a3a0f012f30880640d0bccb5634d2b12a9937e4c872b" dependencies = [ - "base64 0.22.1", - "dirs 6.0.0", + "base64 0.23.1", + "dirs 7.0.0", "flate2", "futures-util", "http", "infer", + "libc", "log", "minisign-verify", "osakit", "percent-encoding", - "reqwest 0.12.24", + "reqwest 0.13.5", + "rustls", "semver", "serde", "serde_json", @@ -4211,25 +4308,25 @@ dependencies = [ "tauri", "tauri-plugin", "tempfile", - "thiserror 2.0.20", + "thiserror 2.0.21", "time", "tokio", "url", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "zip", ] [[package]] name = "tauri-runtime" -version = "2.11.3" +version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0b4bc95aed361b0019067d189a1174a603d460d0f6c72606512d59fc9c12ec8" +checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9" dependencies = [ "cookie", "dpi", "gtk", "http", - "jni", + "jni 0.21.1", "objc2", "objc2-ui-kit", "objc2-web-kit", @@ -4237,26 +4334,25 @@ dependencies = [ "serde", "serde_json", "tauri-utils", - "thiserror 2.0.20", + "thiserror 2.0.21", "url", "webkit2gtk", "webview2-com", - "windows", + "windows 0.62.2", ] [[package]] name = "tauri-runtime-wry" -version = "2.11.4" +version = "2.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f" +checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f" dependencies = [ "gtk", "http", - "jni", + "jni 0.21.1", "log", "objc2", "objc2-app-kit", - "once_cell", "percent-encoding", "raw-window-handle", "softbuffer", @@ -4266,15 +4362,15 @@ dependencies = [ "url", "webkit2gtk", "webview2-com", - "windows", + "windows 0.62.2", "wry", ] [[package]] name = "tauri-utils" -version = "2.9.3" +version = "2.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e176a18e67764923c4f1ce66f25ae4abe5f688384d5eb1a0fa6c77f3d90f887" +checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3" dependencies = [ "anyhow", "brotli", @@ -4300,8 +4396,8 @@ dependencies = [ "serde_json", "serde_with", "swift-rs", - "thiserror 2.0.20", - "toml 0.9.5", + "thiserror 2.0.21", + "toml 1.1.8+spec-1.1.0", "url", "urlpattern", "uuid", @@ -4310,13 +4406,13 @@ dependencies = [ [[package]] name = "tauri-winres" -version = "0.3.5" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1087b111fe2b005e42dbdc1990fc18593234238d47453b0c99b7de1c9ab2c1e0" +checksum = "c52bb6904475a6ca662f15ef787f18ade61d5740a1ee12c45d3b748efdb6f796" dependencies = [ "dunce", "embed-resource", - "toml 0.9.5", + "toml 1.1.8+spec-1.1.0", ] [[package]] @@ -4352,11 +4448,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.20" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.20", + "thiserror-impl 2.0.21", ] [[package]] @@ -4372,13 +4468,13 @@ dependencies = [ [[package]] name = "thiserror-impl" -version = "2.0.20" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -4413,9 +4509,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "zerovec", @@ -4444,9 +4540,9 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.26.5" +version = "0.26.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" dependencies = [ "rustls", "tokio", @@ -4479,17 +4575,17 @@ dependencies = [ [[package]] name = "toml" -version = "0.9.5" +version = "1.1.8+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75129e1dc5000bfbaa9fee9d1b21f974f9fbad9daec557a521ee6e080825f6e8" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" dependencies = [ "indexmap 2.14.2", - "serde", - "serde_spanned 1.0.0", - "toml_datetime 0.7.0", + "serde_core", + "serde_spanned 1.1.2", + "toml_datetime 1.1.2+spec-1.1.0", "toml_parser", "toml_writer", - "winnow 0.7.15", + "winnow 1.0.4", ] [[package]] @@ -4503,11 +4599,11 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.7.0" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bade1c3e902f58d73d3f294cd7f20391c1cb2fbcb643b73566bc773971df91e3" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" dependencies = [ - "serde", + "serde_core", ] [[package]] @@ -4536,30 +4632,30 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.23.4" +version = "0.25.17+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7211ff1b8f0d3adae1663b7da9ffe396eabe1ca25f0b0bee42b0da29a9ddce93" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" dependencies = [ "indexmap 2.14.2", - "toml_datetime 0.7.0", + "toml_datetime 1.1.2+spec-1.1.0", "toml_parser", - "winnow 0.7.15", + "winnow 1.0.4", ] [[package]] name = "toml_parser" -version = "1.1.3+spec-1.1.0" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ "winnow 1.0.4", ] [[package]] name = "toml_writer" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" [[package]] name = "tower" @@ -4582,7 +4678,7 @@ version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags 2.9.4", + "bitflags 2.13.2", "bytes", "futures-util", "http", @@ -4639,12 +4735,12 @@ dependencies = [ [[package]] name = "tray-icon" -version = "0.24.2" +version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "045979e3f037cd18ad1cb2a419dfda133c5c29c9f3453370079f2255d46c257e" +checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" dependencies = [ "crossbeam-channel", - "dirs 6.0.0", + "dirs 7.0.0", "libappindicator", "muda", "objc2", @@ -4653,9 +4749,9 @@ dependencies = [ "objc2-core-graphics", "objc2-foundation", "once_cell", - "png 0.18.1", + "png", "serde", - "thiserror 2.0.20", + "thiserror 2.0.21", "windows-sys 0.61.2", ] @@ -4665,6 +4761,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typeid" version = "1.0.3" @@ -4688,52 +4790,11 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "unic-char-property" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" -dependencies = [ - "unic-char-range", -] - -[[package]] -name = "unic-char-range" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" - -[[package]] -name = "unic-common" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" - -[[package]] -name = "unic-ucd-ident" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-version" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" -dependencies = [ - "unic-common", -] - [[package]] name = "unicode-ident" -version = "1.0.26" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-segmentation" @@ -4762,13 +4823,13 @@ dependencies = [ [[package]] name = "urlpattern" -version = "0.3.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d" +checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b" dependencies = [ + "icu_properties", "regex", "serde", - "unic-ucd-ident", "url", ] @@ -4834,9 +4895,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -4858,9 +4919,9 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.128" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" dependencies = [ "cfg-if", "once_cell", @@ -4871,19 +4932,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.78" +version = "0.4.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.128" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4891,39 +4953,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.128" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.128" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-streams" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" -dependencies = [ - "futures-util", - "js-sys", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - [[package]] name = "wasm-streams" version = "0.5.0" @@ -4939,9 +4988,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.105" +version = "0.3.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" dependencies = [ "js-sys", "wasm-bindgen", @@ -5013,27 +5062,34 @@ dependencies = [ "system-deps", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" dependencies = [ "rustls-pki-types", ] [[package]] name = "webview2-com" -version = "0.38.2" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a" +checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6" dependencies = [ "webview2-com-macros", "webview2-com-sys", - "windows", - "windows-core 0.61.2", - "windows-implement", - "windows-interface", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -5049,13 +5105,13 @@ dependencies = [ [[package]] name = "webview2-com-sys" -version = "0.38.2" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c" +checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb" dependencies = [ - "thiserror 2.0.20", - "windows", - "windows-core 0.61.2", + "thiserror 2.0.21", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -5091,16 +5147,17 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "window-vibrancy" -version = "0.6.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c" +checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580" dependencies = [ "objc2", "objc2-app-kit", "objc2-core-foundation", "objc2-foundation", + "objc2-quartz-core", "raw-window-handle", - "windows-sys 0.59.0", + "windows-sys 0.61.2", "windows-version", ] @@ -5110,11 +5167,23 @@ version = "0.61.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" dependencies = [ - "windows-collections", + "windows-collections 0.2.0", "windows-core 0.61.2", - "windows-future", + "windows-future 0.2.1", "windows-link 0.1.3", - "windows-numerics", + "windows-numerics 0.2.0", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", ] [[package]] @@ -5126,6 +5195,15 @@ dependencies = [ "windows-core 0.61.2", ] +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", +] + [[package]] name = "windows-core" version = "0.61.2" @@ -5160,7 +5238,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" dependencies = [ "windows-core 0.61.2", "windows-link 0.1.3", - "windows-threading", + "windows-threading 0.1.0", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -5207,6 +5296,27 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + [[package]] name = "windows-result" version = "0.3.4" @@ -5345,6 +5455,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-version" version = "0.1.7" @@ -5501,15 +5620,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "winnow" -version = "0.7.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" -dependencies = [ - "memchr", -] - [[package]] name = "winnow" version = "1.0.4" @@ -5538,6 +5648,16 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "winreg" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -5552,15 +5672,15 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "wry" -version = "0.55.1" +version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "186f9871daa55fd9c016578b810d149de58367113db7fb72b462d2323ce19514" +checksum = "759c50ddad0ef9913bb5496cb9d509a50433a3b78cb0238d61105526589cf0e9" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "block2", "cookie", "crossbeam-channel", - "dirs 6.0.0", + "dirs 7.0.0", "dom_query", "dpi", "dunce", @@ -5568,7 +5688,7 @@ dependencies = [ "gtk", "http", "javascriptcore-rs", - "jni", + "jni 0.21.1", "libc", "ndk", "objc2", @@ -5577,19 +5697,18 @@ dependencies = [ "objc2-foundation", "objc2-ui-kit", "objc2-web-kit", - "once_cell", "percent-encoding", "raw-window-handle", "sha2", "soup3", "tao-macros", - "thiserror 2.0.20", + "thiserror 2.0.21", "url", "webkit2gtk", "webkit2gtk-sys", "webview2-com", - "windows", - "windows-core 0.61.2", + "windows 0.62.2", + "windows-core 0.62.2", "windows-version", "x11-dl", ] @@ -5617,9 +5736,9 @@ dependencies = [ [[package]] name = "xattr" -version = "1.6.1" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08" dependencies = [ "libc", "rustix", @@ -5627,9 +5746,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -5638,13 +5757,13 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "synstructure", ] @@ -5689,10 +5808,10 @@ version = "5.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" dependencies = [ - "proc-macro-crate 3.4.0", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "zbus_names", "zvariant", "zvariant_utils", @@ -5700,9 +5819,9 @@ dependencies = [ [[package]] name = "zbus_names" -version = "4.3.4" +version = "4.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" dependencies = [ "serde", "winnow 1.0.4", @@ -5735,15 +5854,15 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "synstructure", ] [[package]] name = "zeroize" -version = "1.9.0" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" [[package]] name = "zerotrie" @@ -5758,9 +5877,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "yoke", "zerofrom", @@ -5769,25 +5888,28 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] name = "zip" -version = "4.6.1" +version = "9.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" +checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb" dependencies = [ - "arbitrary", "crc32fast", + "getrandom 0.4.3", "indexmap 2.14.2", "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", ] [[package]] @@ -5804,9 +5926,9 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" [[package]] name = "zvariant" -version = "5.15.0" +version = "5.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" dependencies = [ "endi", "enumflags2", @@ -5819,14 +5941,14 @@ dependencies = [ [[package]] name = "zvariant_derive" -version = "5.15.0" +version = "5.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" dependencies = [ - "proc-macro-crate 3.4.0", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "zvariant_utils", ] @@ -5839,6 +5961,6 @@ dependencies = [ "proc-macro2", "quote", "serde", - "syn 3.0.6", + "syn 3.0.9", "winnow 1.0.4", ] diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 7df992d284..02868cd01a 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,18 +1,18 @@ [package] name = "opencodex-desktop" -version = "2.89.1-dalsoop.1" +version = "2.100.2" description = "OpenCodex desktop shell" authors = ["OpenCodex contributors"] license = "MIT" edition = "2021" -rust-version = "1.88" +rust-version = "1.90" [lib] name = "opencodex_desktop_lib" crate-type = ["staticlib", "cdylib", "rlib"] [build-dependencies] -tauri-build = { version = "=2.6.3", features = [] } +tauri-build = { version = "=2.7.4", features = [] } [dependencies] base64 = "=0.22.1" @@ -22,14 +22,14 @@ serde = { version = "=1.0.229", features = ["derive"] } serde_json = "=1.0.151" sha2 = "=0.10.9" uuid = { version = "=1.18.1", features = ["v4"] } -tauri = { version = "=2.11.6", features = ["tray-icon", "image-png", "macos-private-api"] } -tauri-utils = "=2.9.3" +tauri = { version = "=2.12.5", features = ["tray-icon", "image-png", "macos-private-api"] } +tauri-utils = "=2.10.2" tauri-plugin-autostart = "=2.5.0" tauri-plugin-opener = "=2.5.3" tauri-plugin-process = "=2.3.0" tauri-plugin-shell = "=2.2.1" tauri-plugin-single-instance = "=2.4.0" -tauri-plugin-updater = "=2.9.0" +tauri-plugin-updater = "=2.14.1" tokio = { version = "=1.45.1", features = ["sync", "time"] } # Linux only, and already in this graph: `tao` enables its own `dbus` feature by default, so diff --git a/desktop/src-tauri/icons/128x128.png b/desktop/src-tauri/icons/128x128.png index 8827b1fdc2..50f397ea3e 100644 Binary files a/desktop/src-tauri/icons/128x128.png and b/desktop/src-tauri/icons/128x128.png differ diff --git a/desktop/src-tauri/icons/128x128@2x.png b/desktop/src-tauri/icons/128x128@2x.png index 21c507c776..4a7f9ebc7d 100644 Binary files a/desktop/src-tauri/icons/128x128@2x.png and b/desktop/src-tauri/icons/128x128@2x.png differ diff --git a/desktop/src-tauri/icons/32x32.png b/desktop/src-tauri/icons/32x32.png index 47a19b8131..e05de2d7d5 100644 Binary files a/desktop/src-tauri/icons/32x32.png and b/desktop/src-tauri/icons/32x32.png differ diff --git a/desktop/src-tauri/icons/64x64.png b/desktop/src-tauri/icons/64x64.png index 5f7a0713c8..14d673b07d 100644 Binary files a/desktop/src-tauri/icons/64x64.png and b/desktop/src-tauri/icons/64x64.png differ diff --git a/desktop/src-tauri/icons/Square107x107Logo.png b/desktop/src-tauri/icons/Square107x107Logo.png index 9436cf61e1..707d36aac2 100644 Binary files a/desktop/src-tauri/icons/Square107x107Logo.png and b/desktop/src-tauri/icons/Square107x107Logo.png differ diff --git a/desktop/src-tauri/icons/Square142x142Logo.png b/desktop/src-tauri/icons/Square142x142Logo.png index 80d163ad59..12d270f426 100644 Binary files a/desktop/src-tauri/icons/Square142x142Logo.png and b/desktop/src-tauri/icons/Square142x142Logo.png differ diff --git a/desktop/src-tauri/icons/Square150x150Logo.png b/desktop/src-tauri/icons/Square150x150Logo.png index 5148c874dc..76a91dedce 100644 Binary files a/desktop/src-tauri/icons/Square150x150Logo.png and b/desktop/src-tauri/icons/Square150x150Logo.png differ diff --git a/desktop/src-tauri/icons/Square284x284Logo.png b/desktop/src-tauri/icons/Square284x284Logo.png index d4ccde8b23..98d3aff54f 100644 Binary files a/desktop/src-tauri/icons/Square284x284Logo.png and b/desktop/src-tauri/icons/Square284x284Logo.png differ diff --git a/desktop/src-tauri/icons/Square30x30Logo.png b/desktop/src-tauri/icons/Square30x30Logo.png index acbbb84ceb..d8d9c8acfa 100644 Binary files a/desktop/src-tauri/icons/Square30x30Logo.png and b/desktop/src-tauri/icons/Square30x30Logo.png differ diff --git a/desktop/src-tauri/icons/Square310x310Logo.png b/desktop/src-tauri/icons/Square310x310Logo.png index 1b9c14d45a..f670fd3dfa 100644 Binary files a/desktop/src-tauri/icons/Square310x310Logo.png and b/desktop/src-tauri/icons/Square310x310Logo.png differ diff --git a/desktop/src-tauri/icons/Square44x44Logo.png b/desktop/src-tauri/icons/Square44x44Logo.png index 5ce2668bf2..bd6782da9b 100644 Binary files a/desktop/src-tauri/icons/Square44x44Logo.png and b/desktop/src-tauri/icons/Square44x44Logo.png differ diff --git a/desktop/src-tauri/icons/Square71x71Logo.png b/desktop/src-tauri/icons/Square71x71Logo.png index f9a361ad93..7e918f87dc 100644 Binary files a/desktop/src-tauri/icons/Square71x71Logo.png and b/desktop/src-tauri/icons/Square71x71Logo.png differ diff --git a/desktop/src-tauri/icons/Square89x89Logo.png b/desktop/src-tauri/icons/Square89x89Logo.png index eafa6f2087..5543513f1f 100644 Binary files a/desktop/src-tauri/icons/Square89x89Logo.png and b/desktop/src-tauri/icons/Square89x89Logo.png differ diff --git a/desktop/src-tauri/icons/StoreLogo.png b/desktop/src-tauri/icons/StoreLogo.png index 8621824587..1d7b42a098 100644 Binary files a/desktop/src-tauri/icons/StoreLogo.png and b/desktop/src-tauri/icons/StoreLogo.png differ diff --git a/desktop/src-tauri/icons/icon.icns b/desktop/src-tauri/icons/icon.icns index 12ddb09d39..84c56d5079 100644 Binary files a/desktop/src-tauri/icons/icon.icns and b/desktop/src-tauri/icons/icon.icns differ diff --git a/desktop/src-tauri/icons/icon.ico b/desktop/src-tauri/icons/icon.ico index 80ded4a940..f6e9f84cb9 100644 Binary files a/desktop/src-tauri/icons/icon.ico and b/desktop/src-tauri/icons/icon.ico differ diff --git a/desktop/src-tauri/icons/icon.png b/desktop/src-tauri/icons/icon.png index 5c8fa696c6..826793484c 100644 Binary files a/desktop/src-tauri/icons/icon.png and b/desktop/src-tauri/icons/icon.png differ diff --git a/desktop/src-tauri/icons/icon.svg b/desktop/src-tauri/icons/icon.svg index 7070d673ad..f7e4b76480 100644 --- a/desktop/src-tauri/icons/icon.svg +++ b/desktop/src-tauri/icons/icon.svg @@ -1,43 +1,37 @@ - - - - - + + + + + - - - - - - - - - - - + + + + + + + + + + + diff --git a/desktop/src-tauri/icons/tray/icon-update.png b/desktop/src-tauri/icons/tray/icon-update.png index 9cd0fc910e..5e9d17ebbc 100644 Binary files a/desktop/src-tauri/icons/tray/icon-update.png and b/desktop/src-tauri/icons/tray/icon-update.png differ diff --git a/desktop/src-tauri/icons/tray/icon.png b/desktop/src-tauri/icons/tray/icon.png index 1eec4cccaf..c895b398dc 100644 Binary files a/desktop/src-tauri/icons/tray/icon.png and b/desktop/src-tauri/icons/tray/icon.png differ diff --git a/desktop/src-tauri/icons/tray/icon.svg b/desktop/src-tauri/icons/tray/icon.svg index 1f917f1f01..879c8e7444 100644 --- a/desktop/src-tauri/icons/tray/icon.svg +++ b/desktop/src-tauri/icons/tray/icon.svg @@ -1,28 +1,28 @@ - + - - - - - + + + + + - - - + + + diff --git a/desktop/src-tauri/src/installer_telemetry.rs b/desktop/src-tauri/src/installer_telemetry.rs new file mode 100644 index 0000000000..8631adc98b --- /dev/null +++ b/desktop/src-tauri/src/installer_telemetry.rs @@ -0,0 +1,545 @@ +//! The Windows installer's "Send anonymous usage statistics" choice. +//! +//! SignPath Foundation's conditions require software that sends usage data to include an +//! installation option that disables it. The MSI page generated into +//! `desktop/src-tauri/wix/telemetry-choice.wxs` records the choice machine-wide under +//! `HKLM\Software\OpenCodex\Telemetry`: `InstallerChoice` (`send` or `optout`) and +//! `InstallerChoiceStamp` (when it was chosen). HKLM is what makes a silent install run as SYSTEM +//! (Intune, SCCM) or approved by another administrator reach the people who later use the app; an +//! upgrade carries the previous choice and stamp forward. The same two values under the user's own +//! `HKCU\Software\OpenCodex\Telemetry` are honoured too, as a per-user choice. +//! +//! Before the app resolves, attaches to or starts a proxy, this module carries an opt-out into the +//! current user's opencodex config by running the bundled `ocx telemetry disable`, which persists +//! `telemetry.decision = "declined"` (on a fresh install it is held as `pendingDecision` without +//! creating `config.json`). It then records the applied stamp in that user's HKCU, one value per +//! scope, so each opt-out applies once per user and a later dashboard choice is not overridden until +//! an install records a new opt-out. `send` is never acted on, and this module has no path that +//! enables telemetry, so no installer choice can turn a decline back on. +//! +//! When the decline could not be persisted, a sidecar this app starts runs with +//! `OCX_TELEMETRY=0`, and the save is retried in the background (`RETRY_DELAYS`) and again on the +//! next launch. A proxy this app only attaches to was started elsewhere with its own environment; +//! it follows the saved decline once a retry succeeds (it re-reads the config on every tick). If a +//! decline was saved but its stamp could not be recorded, the next launch saves it again, which can +//! override a dashboard enable made in between; that errs toward privacy. +//! +//! An MSI install does not put `ocx.exe` on PATH; the terminal command is installed by this app. +//! On a first install the app therefore runs before any proxy from that install can. After the app +//! has installed the terminal command, `ocx service install` can register a logon task that starts a +//! proxy without the app; an opt-out recorded by a later manual upgrade reaches that proxy's config +//! when the app next starts, and until then the service may still make its daily send. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; +use tauri::AppHandle; +use tauri_plugin_shell::ShellExt; +use tokio::time::{timeout_at, Instant}; + +// Read and written only on Windows; the names are pinned against the WiX fragment by a test. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub const REGISTRY_KEY: &str = r"Software\OpenCodex\Telemetry"; +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub const REGISTRY_VALUE: &str = "InstallerChoice"; +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub const STAMP_VALUE: &str = "InstallerChoiceStamp"; +/// Written by this app under HKCU: the stamp of the last machine-wide opt-out applied for this user. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub const APPLIED_STAMP_VALUE: &str = "AppliedInstallerStamp"; +/// Written by this app under HKCU: the stamp of the last per-user opt-out applied. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub const APPLIED_USER_STAMP_VALUE: &str = "AppliedUserInstallerStamp"; +// The installer's value for an opt-out, pinned against the WiX fragment by a test; the app treats any +// value other than `SEND` as an opt-out. +#[allow(dead_code)] +pub const OPT_OUT: &str = "optout"; +pub const SEND: &str = "send"; + +static SIDECAR_ENV_OPT_OUT: AtomicBool = AtomicBool::new(false); + +/// The opt-out step's own budget, so a slow first `ocx` start cannot use up the startup deadline. +const STEP_CAP: Duration = Duration::from_secs(10); +/// Background retries after a failed save, so an attached proxy does not keep its old setting. +pub const RETRY_DELAYS: [Duration; 4] = [ + Duration::from_secs(10), + Duration::from_secs(30), + Duration::from_secs(120), + Duration::from_secs(600), +]; +const RETRY_TIMEOUT: Duration = Duration::from_secs(30); + +/// Where an installer choice was recorded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Scope { + /// `HKLM`: every account on the computer. + Machine, + /// `HKCU`: this account only. Only the Windows registry reader records it. + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + User, +} + +impl Scope { + /// The HKCU value this app writes once an opt-out from this scope is applied. + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + pub fn applied_value(self) -> &'static str { + match self { + Scope::Machine => APPLIED_STAMP_VALUE, + Scope::User => APPLIED_USER_STAMP_VALUE, + } + } +} + +/// A choice the installer recorded. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InstallerChoice { + pub scope: Scope, + pub choice: String, + pub stamp: String, +} + +/// Registry access, injected so the decision logic is tested without Windows. +pub trait InstallerRegistry { + /// The choices the installer recorded, in any order. + fn choices(&self) -> Vec; + /// The stamp this app last applied for `scope` in this account. + fn applied_stamp(&self, scope: Scope) -> Option; + /// Record that the opt-out with `stamp` from `scope` is applied in this account. + fn mark_applied(&self, scope: Scope, stamp: &str) -> bool; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Outcome { + /// No opt-out is pending for this user: no choice, `send`, or one already applied. + NothingPending, + /// The decline is in the user's config and every pending stamp is recorded. + Applied, + /// The decline is in the config, but a stamp could not be recorded; the next launch re-applies it. + AppliedUnmarked, + /// The decline could not be persisted; a sidecar this app starts runs with `OCX_TELEMETRY=0`. + NotPersisted, +} + +/// Fail closed like the installer: any recorded value other than `send` (or nothing) is an opt-out. +fn is_opt_out(choice: &str) -> bool { + let choice = choice.trim(); + !choice.is_empty() && !choice.eq_ignore_ascii_case(SEND) +} + +/// The opt-outs this account has not applied yet, machine-wide first. `send` is never pending. +pub fn pending_opt_outs(registry: &R) -> Vec { + let mut pending: Vec = registry + .choices() + .into_iter() + .filter(|choice| is_opt_out(&choice.choice)) + .filter(|choice| { + registry + .applied_stamp(choice.scope) + .as_deref() + .map(str::trim) + != Some(choice.stamp.trim()) + }) + .collect(); + pending.sort_by_key(|choice| choice.scope != Scope::Machine); + pending +} + +/// `ocx telemetry disable` exits 0 only once the decline is persisted. +pub fn decline_persisted(exit_code: Option) -> bool { + exit_code == Some(0) +} + +/// Apply the pending opt-outs: one persisted decline covers all of them, and only then is each +/// stamp recorded. +pub fn settle( + registry: &R, + pending: &[InstallerChoice], + persist: impl FnOnce() -> bool, +) -> Outcome { + if pending.is_empty() { + return Outcome::NothingPending; + } + if !persist() { + return Outcome::NotPersisted; + } + let mut all_marked = true; + for choice in pending { + all_marked &= registry.mark_applied(choice.scope, choice.stamp.trim()); + } + if all_marked { + Outcome::Applied + } else { + Outcome::AppliedUnmarked + } +} + +/// Whether the sidecar this app starts must carry `OCX_TELEMETRY=0`. +pub fn sidecar_env_opt_out() -> bool { + SIDECAR_ENV_OPT_OUT.load(Ordering::SeqCst) +} + +/// Carry a pending installer opt-out into the current user's opencodex config. +pub async fn apply(app: &AppHandle, deadline: Instant) -> Outcome { + let registry = os::SystemRegistry; + let pending = pending_opt_outs(®istry); + let persisted = if pending.is_empty() { + false + } else { + disable(app, deadline.min(Instant::now() + STEP_CAP)).await + }; + let outcome = settle(®istry, &pending, || persisted); + match outcome { + Outcome::NotPersisted => { + SIDECAR_ENV_OPT_OUT.store(true, Ordering::SeqCst); + crate::logging::log_once( + "the installer's telemetry opt-out could not be saved", + "a proxy this app starts runs with OCX_TELEMETRY=0; saving is retried in the background", + ); + let app = app.clone(); + tauri::async_runtime::spawn(async move { retry(app, pending).await }); + } + Outcome::AppliedUnmarked => crate::logging::log_once( + "the installer's telemetry opt-out was saved but not recorded as applied", + "the next launch saves the decline again", + ), + Outcome::NothingPending | Outcome::Applied => {} + } + outcome +} + +async fn retry(app: AppHandle, pending: Vec) { + for delay in RETRY_DELAYS { + tokio::time::sleep(delay).await; + if disable(&app, Instant::now() + RETRY_TIMEOUT).await { + if settle(&os::SystemRegistry, &pending, || true) == Outcome::AppliedUnmarked { + crate::logging::log_once( + "the installer's telemetry opt-out was saved but not recorded as applied", + "the next launch saves the decline again", + ); + } + return; + } + } + crate::logging::log_once( + "the installer's telemetry opt-out could not be saved after retries", + "the next launch tries again; check that config.json is writable", + ); +} + +async fn disable(app: &AppHandle, deadline: Instant) -> bool { + let command = match app.shell().sidecar("ocx") { + Ok(command) => command.args(["telemetry", "disable", "--json"]), + Err(_) => return false, + }; + match timeout_at( + deadline, + crate::process_spawn::with_spawn_async(command.output()), + ) + .await + { + Ok(Ok(output)) => decline_persisted(output.status.code()), + _ => false, + } +} + +#[cfg(target_os = "windows")] +mod os { + use super::{InstallerChoice, InstallerRegistry, Scope}; + use winreg::enums::{ + HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, KEY_WOW64_64KEY, + }; + use winreg::RegKey; + + pub struct SystemRegistry; + + fn read(key: &RegKey, scope: Scope) -> Option { + let choice = key.get_value::(super::REGISTRY_VALUE).ok()?; + let stamp = key + .get_value::(super::STAMP_VALUE) + .unwrap_or_default(); + Some(InstallerChoice { + scope, + choice, + stamp, + }) + } + + impl InstallerRegistry for SystemRegistry { + fn choices(&self) -> Vec { + let mut choices = Vec::new(); + // The 64-bit view first, the 32-bit view second. + for view in [KEY_WOW64_64KEY, KEY_WOW64_32KEY] { + if let Some(choice) = RegKey::predef(HKEY_LOCAL_MACHINE) + .open_subkey_with_flags(super::REGISTRY_KEY, KEY_READ | view) + .ok() + .and_then(|key| read(&key, Scope::Machine)) + { + choices.push(choice); + break; + } + } + if let Some(choice) = RegKey::predef(HKEY_CURRENT_USER) + .open_subkey_with_flags(super::REGISTRY_KEY, KEY_READ) + .ok() + .and_then(|key| read(&key, Scope::User)) + { + choices.push(choice); + } + choices + } + + fn applied_stamp(&self, scope: Scope) -> Option { + RegKey::predef(HKEY_CURRENT_USER) + .open_subkey_with_flags(super::REGISTRY_KEY, KEY_READ) + .ok()? + .get_value::(scope.applied_value()) + .ok() + } + + fn mark_applied(&self, scope: Scope, stamp: &str) -> bool { + RegKey::predef(HKEY_CURRENT_USER) + .create_subkey(super::REGISTRY_KEY) + .and_then(|(key, _)| key.set_value(scope.applied_value(), &stamp.to_owned())) + .is_ok() + } + } +} + +#[cfg(not(target_os = "windows"))] +mod os { + use super::{InstallerChoice, InstallerRegistry, Scope}; + + /// Only the Windows installer records a choice. + pub struct SystemRegistry; + + impl InstallerRegistry for SystemRegistry { + fn choices(&self) -> Vec { + Vec::new() + } + + fn applied_stamp(&self, _scope: Scope) -> Option { + None + } + + fn mark_applied(&self, _scope: Scope, _stamp: &str) -> bool { + true + } + } +} + +#[cfg(test)] +mod tests { + use super::{ + decline_persisted, pending_opt_outs, settle, InstallerChoice, InstallerRegistry, Outcome, + Scope, + }; + use std::cell::{Cell, RefCell}; + use std::collections::HashMap; + + /// An in-memory registry: the installer's choices plus this account's applied stamps. + #[derive(Default)] + struct FakeRegistry { + choices: Vec, + applied: RefCell>, + refuse_marks: bool, + } + + impl FakeRegistry { + fn with(choices: &[(Scope, &str, &str)]) -> Self { + Self { + choices: choices + .iter() + .map(|(scope, choice, stamp)| InstallerChoice { + scope: *scope, + choice: (*choice).to_owned(), + stamp: (*stamp).to_owned(), + }) + .collect(), + ..Self::default() + } + } + + fn applied(&self, scope: Scope) -> Option { + self.applied.borrow().get(scope.applied_value()).cloned() + } + + fn set_applied(&self, scope: Scope, stamp: &str) { + self.applied + .borrow_mut() + .insert(scope.applied_value(), stamp.to_owned()); + } + } + + impl InstallerRegistry for FakeRegistry { + fn choices(&self) -> Vec { + self.choices.clone() + } + + fn applied_stamp(&self, scope: Scope) -> Option { + self.applied(scope) + } + + fn mark_applied(&self, scope: Scope, stamp: &str) -> bool { + if self.refuse_marks { + return false; + } + self.set_applied(scope, stamp); + true + } + } + + /// Run one launch: returns the outcome and whether a decline was persisted. + fn launch(registry: &FakeRegistry, persist_ok: bool) -> (Outcome, bool) { + let persisted = Cell::new(false); + let pending = pending_opt_outs(registry); + let outcome = settle(registry, &pending, || { + persisted.set(true); + persist_ok + }); + (outcome, persisted.get()) + } + + #[test] + fn a_machine_wide_opt_out_applies_once_per_account() { + let registry = FakeRegistry::with(&[(Scope::Machine, "optout", "11/8/2026 10:12:33")]); + assert_eq!(launch(®istry, true), (Outcome::Applied, true)); + assert_eq!( + registry.applied(Scope::Machine).as_deref(), + Some("11/8/2026 10:12:33") + ); + // The next launch finds the stamp applied and does nothing, so a later dashboard enable stays. + assert_eq!(launch(®istry, true), (Outcome::NothingPending, false)); + } + + #[test] + fn a_new_stamp_from_a_later_install_applies_again() { + let registry = FakeRegistry::with(&[(Scope::Machine, "optout", "s2")]); + registry.set_applied(Scope::Machine, "s1"); + assert_eq!(launch(®istry, true), (Outcome::Applied, true)); + assert_eq!(registry.applied(Scope::Machine).as_deref(), Some("s2")); + } + + #[test] + fn send_from_any_scope_never_acts_so_a_decline_is_never_flipped() { + for choices in [ + vec![(Scope::Machine, "send", "s1")], + vec![(Scope::User, "send", "s1")], + vec![(Scope::Machine, "send", "s1"), (Scope::User, "SEND", "s2")], + vec![(Scope::Machine, "", "s1"), (Scope::User, " Send ", "s2")], + ] { + let registry = FakeRegistry::with(&choices); + // Nothing runs: the bridge only ever runs `ocx telemetry disable`, and here not even that. + assert_eq!( + launch(®istry, true), + (Outcome::NothingPending, false), + "{choices:?}" + ); + assert_eq!(registry.applied(Scope::Machine), None); + assert_eq!(registry.applied(Scope::User), None); + } + } + + #[test] + fn an_unrecognized_value_counts_as_an_opt_out() { + for value in ["off", "0", "opt-out", "OptOut", " optout "] { + let registry = FakeRegistry::with(&[(Scope::User, value, "u1")]); + assert_eq!( + launch(®istry, true), + (Outcome::Applied, true), + "{value:?}" + ); + } + } + + #[test] + fn machine_and_per_user_opt_outs_are_both_honoured_machine_first() { + let registry = FakeRegistry::with(&[ + (Scope::User, "optout", "u1"), + (Scope::Machine, " OptOut ", "m1"), + ]); + let pending = pending_opt_outs(®istry); + assert_eq!( + pending + .iter() + .map(|choice| choice.scope) + .collect::>(), + vec![Scope::Machine, Scope::User] + ); + // One persisted decline covers both, and both stamps are recorded. + assert_eq!(launch(®istry, true), (Outcome::Applied, true)); + assert_eq!(registry.applied(Scope::Machine).as_deref(), Some("m1")); + assert_eq!(registry.applied(Scope::User).as_deref(), Some("u1")); + } + + #[test] + fn a_later_install_recording_send_leaves_an_applied_decline_alone() { + // An opt-out from an earlier install was applied for this account ... + let earlier = FakeRegistry::with(&[(Scope::Machine, "optout", "s1")]); + assert_eq!(launch(&earlier, true), (Outcome::Applied, true)); + // ... then an upgrade where someone checked the box records send with a new stamp. + let later = FakeRegistry::with(&[(Scope::Machine, "send", "s2")]); + later.set_applied(Scope::Machine, "s1"); + // Nothing runs, so the saved decline stays, and the applied stamp is not touched. + assert_eq!(launch(&later, true), (Outcome::NothingPending, false)); + assert_eq!(later.applied(Scope::Machine).as_deref(), Some("s1")); + } + + #[test] + fn a_per_user_opt_out_applies_when_the_machine_choice_is_send() { + let registry = FakeRegistry::with(&[ + (Scope::Machine, "send", "m1"), + (Scope::User, "optout", "u1"), + ]); + assert_eq!(launch(®istry, true), (Outcome::Applied, true)); + assert_eq!(registry.applied(Scope::Machine), None); + assert_eq!(registry.applied(Scope::User).as_deref(), Some("u1")); + } + + #[test] + fn an_applied_machine_stamp_does_not_hide_a_new_per_user_opt_out() { + let registry = FakeRegistry::with(&[ + (Scope::Machine, "optout", "m1"), + (Scope::User, "optout", "u1"), + ]); + registry.set_applied(Scope::Machine, "m1"); + let pending = pending_opt_outs(®istry); + assert_eq!( + pending + .iter() + .map(|choice| choice.scope) + .collect::>(), + vec![Scope::User] + ); + } + + #[test] + fn a_stamp_is_recorded_only_after_the_decline_persisted() { + let registry = FakeRegistry::with(&[(Scope::Machine, "optout", "m1")]); + assert_eq!(launch(®istry, false), (Outcome::NotPersisted, true)); + assert_eq!(registry.applied(Scope::Machine), None); + // The next launch tries again. + assert_eq!(launch(®istry, true), (Outcome::Applied, true)); + } + + #[test] + fn an_unrecorded_stamp_is_reported_and_retried_next_launch() { + let mut registry = FakeRegistry::with(&[(Scope::Machine, "optout", "m1")]); + registry.refuse_marks = true; + assert_eq!(launch(®istry, true), (Outcome::AppliedUnmarked, true)); + registry.refuse_marks = false; + assert_eq!(launch(®istry, true), (Outcome::Applied, true)); + } + + #[test] + fn no_choice_at_all_runs_nothing() { + let registry = FakeRegistry::default(); + assert_eq!(launch(®istry, true), (Outcome::NothingPending, false)); + } + + #[test] + fn only_a_clean_exit_counts_as_persisted() { + assert!(decline_persisted(Some(0))); + for code in [None, Some(1), Some(2), Some(-1)] { + assert!(!decline_persisted(code), "{code:?}"); + } + } +} diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index 255954ed76..2b17ef86d5 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -13,6 +13,7 @@ mod exit; mod first_run; mod formatting; mod identity; +mod installer_telemetry; mod logging; mod login_autostart; // The judgment is portable so Linux CI runs its fixture parity tests; only macOS reads launchd. @@ -48,11 +49,16 @@ mod tray_login; mod popup_portable_test; mod process_spawn; mod proxy; +mod recovery; +mod recovery_activity; +mod recovery_presence; mod resolve; mod runtime_stop; mod sidecar; mod startup; mod supervisor; +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +mod traffic_lights; mod tray; mod tray_availability; mod updater; @@ -402,14 +408,16 @@ pub fn run() { // zoom the window through `plugin:window` commands granted by // `capabilities/dashboard-titlebar.json`. Windows and Linux keep the native title // bar — the shell ships no min/max/close widgets of its own — while the sidebar-top - // layout applies unchanged. + // layout applies unchanged. The vertical inset depends on the macOS release, whose + // button metrics changed in 26 (`traffic_lights.rs`). #[cfg(target_os = "macos")] let builder = builder .title_bar_style(tauri::TitleBarStyle::Overlay) .hidden_title(true) .min_inner_size(360.0, 320.0) .traffic_light_position(tauri::Position::Logical(tauri::LogicalPosition::new( - 18.0, 22.0, + traffic_lights::X, + traffic_lights::y_for(traffic_lights::macos_major()), ))); let window = builder.build()?; window::configure(&window); @@ -419,6 +427,7 @@ pub fn run() { window::set_tray_policy(app.handle(), false); } + recovery::register(app.handle()); startup::begin(app.handle()); if !cfg!(debug_assertions) { diff --git a/desktop/src-tauri/src/native_tray_accounts.rs b/desktop/src-tauri/src/native_tray_accounts.rs index 54309ce674..8d2394bcf6 100644 --- a/desktop/src-tauri/src/native_tray_accounts.rs +++ b/desktop/src-tauri/src/native_tray_accounts.rs @@ -151,7 +151,7 @@ fn windows(quota: &Value, plan: &str) -> Vec { } pub fn provider(source: &Source, body: Option<&Value>, unavailable: bool) -> Value { - let parsed = body.and_then(parse_accounts); + let parsed = body.and_then(|body| parse_accounts(body, source.switch)); let malformed = body.is_some() && parsed.is_none(); let accounts = parsed.unwrap_or_default(); let mut row = json!({"id":source.name,"label":source.label, @@ -165,7 +165,7 @@ pub fn provider(source: &Source, body: Option<&Value>, unavailable: bool) -> Val row } -fn parse_accounts(body: &Value) -> Option> { +fn parse_accounts(body: &Value, kind: Option) -> Option> { let rows = body .get("accounts") .or_else(|| body.get("keys"))? @@ -175,9 +175,16 @@ fn parse_accounts(body: &Value) -> Option> { .find_map(|key| body[key].as_str()); rows.iter().enumerate().map(|(index,row)| { let id = row["id"].as_str()?; - let email = row["email"].as_str().map(mask_email); - let label = [row["alias"].as_str(),row["label"].as_str(),email.as_deref(),row["logLabel"].as_str(),Some(id)] - .into_iter().flatten().find(|v| !v.is_empty()).unwrap_or(id); + let oauth = kind == Some(AccountSwitchKind::OAuth); + let email = if oauth { None } else { row["email"].as_str().map(mask_email) }; + let label = if oauth { + [row["alias"].as_str(), row["maskedLabel"].as_str()] + .into_iter().flatten().map(str::trim).find(|v| !v.is_empty()) + .map(str::to_owned).unwrap_or_else(|| format!("Account {}", index + 1)) + } else { + [row["alias"].as_str(),row["label"].as_str(),email.as_deref(),row["logLabel"].as_str(),Some(id)] + .into_iter().flatten().find(|v| !v.is_empty()).unwrap_or(id).to_owned() + }; let unavailable = row["quotaUnavailable"].as_bool()==Some(true) || text(row,"quotaMode")=="unsupported" || !row["quota"].is_object(); let is_active = active.map_or(row["active"].as_bool()==Some(true),|selected|selected==id); @@ -230,6 +237,66 @@ fn exhausted(quota: &Value, plan: &str) -> bool { #[cfg(test)] mod tests { use super::*; + fn parse_accounts(body: &Value) -> Option> { + super::parse_accounts(body, None) + } + + fn oauth_accounts(body: Value) -> Vec { + let source = Source { + name: "example".into(), + label: "Example".into(), + path: None, + switch: Some(AccountSwitchKind::OAuth), + }; + provider(&source, Some(&body), false)["accounts"] + .as_array() + .unwrap() + .clone() + } + + #[test] + fn oauth_alias_is_trimmed_and_does_not_expose_legacy_email() { + let rows = oauth_accounts(json!({"accounts":[{"id":"private-id","alias":" Work ", + "maskedLabel":"m•••@e•••.com","email":"person@example.com"}]})); + assert_eq!(rows[0]["label"], "Work"); + assert!(rows[0]["email"].is_null()); + assert_eq!(rows[0]["accountId"], "private-id"); + assert_eq!(rows[0]["id"], "private-id:0"); + } + + #[test] + fn oauth_masked_label_follows_blank_alias() { + let rows = oauth_accounts(json!({"accounts":[{"id":"private-id","alias":" ", + "maskedLabel":" m•••@e•••.com ","label":"legacy","email":"person@example.com"}]})); + assert_eq!(rows[0]["label"], "m•••@e•••.com"); + assert!(rows[0]["email"].is_null()); + } + + #[test] + fn oauth_legacy_payload_uses_ordinal_instead_of_identifiers() { + let rows = oauth_accounts(json!({"accounts":[ + {"id":"private-id","email":"person@example.com","label":"legacy", "logLabel":"legacy-log"}, + {"id":"another-private-id","alias":" ","maskedLabel":" "}]})); + assert_eq!(rows[0]["label"], "Account 1"); + assert_eq!(rows[1]["label"], "Account 2"); + assert!(rows[0]["email"].is_null()); + assert!(rows[1]["email"].is_null()); + assert_eq!(rows[0]["accountId"], "private-id"); + assert_eq!(rows[1]["accountId"], "another-private-id"); + } + + #[test] + fn codex_and_api_key_labels_keep_the_existing_projection() { + let body = json!({"accounts":[{"id":"id","label":"Legacy label", + "maskedLabel":"ignored","email":"person@example.com"}]}); + for kind in [AccountSwitchKind::Codex, AccountSwitchKind::ApiKey] { + let rows = super::parse_accounts(&body, Some(kind)).unwrap(); + assert_eq!(rows[0]["label"], "Legacy label"); + assert_eq!(rows[0]["email"], "p•••@e•••.com"); + assert_eq!(rows[0]["accountId"], "id"); + } + } + #[test] fn source_routes_are_encoded_and_never_forward_credentials() { let rows = sources(&json!({"providers":{ diff --git a/desktop/src-tauri/src/provider_icons.rs b/desktop/src-tauri/src/provider_icons.rs index b3e971f890..515d9b9f64 100644 --- a/desktop/src-tauri/src/provider_icons.rs +++ b/desktop/src-tauri/src/provider_icons.rs @@ -38,6 +38,7 @@ const ALIASES: &[(&str, &str)] = &[ ("cursor", "cursor-color.svg"), ("deepseek", "deepseek-color.svg"), ("dsh-account", "deepseek-color.svg"), + ("workbuddy-ai", "workbuddy-color.svg"), ("devin", "devin.svg"), ("firepass", "firepass-color.svg"), ("fireworks", "fireworks-color.svg"), @@ -163,6 +164,7 @@ fn svg(file: &str) -> Option<&'static str> { "cursor-color.svg" => svg!("cursor-color.svg"), "deepinfra.svg" => svg!("deepinfra.svg"), "deepseek-color.svg" => svg!("deepseek-color.svg"), + "workbuddy-color.svg" => svg!("workbuddy-color.svg"), "devin.svg" => svg!("devin.svg"), "digitalocean.svg" => svg!("digitalocean.svg"), "featherless.svg" => svg!("featherless.svg"), diff --git a/desktop/src-tauri/src/recovery.rs b/desktop/src-tauri/src/recovery.rs new file mode 100644 index 0000000000..df60a6149e --- /dev/null +++ b/desktop/src-tauri/src/recovery.rs @@ -0,0 +1,92 @@ +//! Publish the shell's current intent independently of the supervised runtime's lifetime. +use crate::{ + exit::{ExitCoordinator, ExitPhase}, + recovery_activity::{Activity, Reservation}, + recovery_presence::{Presence, Snapshot}, +}; +use std::{ + path::Path, + sync::{Arc, Mutex}, +}; +use tauri::{AppHandle, Manager}; + +struct Recovery { + home: Arc>>, + activity: Arc, + _presence: Presence, +} + +/// Register before startup can resolve or spawn. A failure grants no consumer-side authority. +pub fn register(app: &AppHandle) { + let home = Arc::new(Mutex::new(None)); + let observed_home = Arc::clone(&home); + let activity = Arc::new(Activity::default()); + let observed_activity = Arc::clone(&activity); + let handle = app.clone(); + let snapshot = Arc::new(move || { + let state = handle + .try_state::() + .map(|exit| exit.supervision()); + Snapshot { + home: observed_home.lock().ok().and_then(|home| home.clone()), + wanted: observed_activity.recovering(state.is_some_and(|s| { + s.wanted + && !s.reason_set + && matches!(s.phase, ExitPhase::Idle | ExitPhase::Spawning) + })), + } + }); + match Presence::start(uuid::Uuid::new_v4().simple().to_string(), snapshot) { + Ok(presence) => { + app.manage(Recovery { + home, + activity, + _presence: presence, + }); + } + Err(_) => crate::logging::log_once( + "Desktop recovery evidence is unavailable", + "the native listener could not be registered", + ), + } +} + +fn update_activity(app: &AppHandle, update: impl FnOnce(&Activity)) { + if let Some(recovery) = app.try_state::() { + update(&recovery.activity); + } +} + +pub fn begin_run(app: &AppHandle, generation: u64, recovering: bool) { + update_activity(app, |activity| activity.begin_run(generation, recovering)); +} + +pub fn ready(app: &AppHandle, generation: u64, owned: bool) { + update_activity(app, |activity| activity.ready(generation, owned)); +} + +pub fn failed(app: &AppHandle, generation: u64) { + update_activity(app, |activity| activity.failed(generation)); +} + +pub fn defer_recovery(app: &AppHandle) { + update_activity(app, Activity::defer_recovery); +} + +pub fn finish_run(app: &AppHandle, generation: u64, ready: bool) { + update_activity(app, |activity| activity.finish_run(generation, ready)); +} + +pub fn reserve(app: &AppHandle) -> Option { + app.try_state::() + .and_then(|recovery| recovery.activity.reserve()) +} + +/// Only the bundled CLI's resolved home selects the scope; neither request bytes nor a locator do. +pub fn bind_home(app: &AppHandle, home: &Path) { + if let Some(recovery) = app.try_state::() { + if let Ok(mut current) = recovery.home.lock() { + *current = Some(home.to_path_buf()); + } + } +} diff --git a/desktop/src-tauri/src/recovery_activity.rs b/desktop/src-tauri/src/recovery_activity.rs new file mode 100644 index 0000000000..b3d078287b --- /dev/null +++ b/desktop/src-tauri/src/recovery_activity.rs @@ -0,0 +1,256 @@ +//! Recovery work is narrower than the person's general wish to have a runtime. +use std::sync::{Arc, Mutex}; + +#[derive(Clone, Copy, Default)] +enum Run { + #[default] + Idle, + Starting { + retry: bool, + }, + Failed { + retry: bool, + }, + Ready { + owned: bool, + }, + Supervised, +} + +#[derive(Default)] +struct Inner { + generation: u64, + run: Run, + reservations: usize, +} + +/// One view shared by accepted startup reports and the supervisor's actual work. +#[derive(Default)] +pub struct Activity { + inner: Mutex, +} + +impl Activity { + pub fn begin_run(&self, generation: u64, recovering: bool) { + if let Ok(mut inner) = self.inner.lock() { + if generation > inner.generation { + inner.generation = generation; + inner.run = Run::Starting { retry: recovering }; + } + } + } + + fn update_run(&self, generation: u64, update: impl FnOnce(&mut Run)) { + if let Ok(mut inner) = self.inner.lock() { + if inner.generation == generation { + update(&mut inner.run); + } + } + } + + /// Only an accepted Ready report supplies the binding's confirmed ownership. + pub fn ready(&self, generation: u64, owned: bool) { + self.update_run(generation, |run| { + if matches!(run, Run::Starting { .. }) { + *run = Run::Ready { owned }; + } + }); + } + + /// A terminal launch failure loses credit even while its async cleanup is running. + pub fn failed(&self, generation: u64) { + self.update_run(generation, |run| { + if let Run::Starting { retry } = *run { + *run = Run::Failed { retry }; + } + }); + } + + /// An owned child's exit during a run gives that run a real follow-up obligation. + pub fn defer_recovery(&self) { + if let Ok(mut inner) = self.inner.lock() { + match &mut inner.run { + Run::Starting { retry } | Run::Failed { retry } => *retry = true, + _ => {} + } + } + } + + /// Failed runs finish only after their follow-up has acquired any new reservation. + pub fn finish_run(&self, generation: u64, ready: bool) { + self.update_run(generation, |run| { + *run = if ready && matches!(run, Run::Ready { owned: true } | Run::Supervised) { + Run::Supervised + } else { + Run::Idle + }; + }); + } + + /// Keep the scheduled work alive across pending -> startup, including cancellation. + pub fn reserve(self: &Arc) -> Option { + let mut inner = self.inner.lock().ok()?; + inner.reservations = inner.reservations.checked_add(1)?; + Some(Reservation(Arc::clone(self))) + } + + /// The exit coordinator can revoke every kind of work without waiting for its cleanup. + pub fn recovering(&self, allowed: bool) -> bool { + allowed + && self.inner.lock().is_ok_and(|inner| { + inner.reservations > 0 + || matches!( + inner.run, + Run::Starting { .. } + | Run::Failed { retry: true } + | Run::Ready { owned: true } + | Run::Supervised + ) + }) + } +} + +/// Each task releases only its own reservation, including an early return or cancellation. +pub struct Reservation(Arc); + +impl Drop for Reservation { + fn drop(&mut self) { + if let Ok(mut inner) = self.0.inner.lock() { + inner.reservations -= 1; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_accepted_start_covers_the_resolved_home_before_spawn() { + let activity = Activity::default(); + assert!(!activity.recovering(true)); + activity.begin_run(1, false); + assert!(activity.recovering(true)); + } + + #[test] + fn a_terminal_launch_failure_stops_credit_before_cleanup_finishes() { + let activity = Activity::default(); + activity.begin_run(1, false); + assert!(activity.recovering(true)); + // Both an ordinary failure and the deadline guard publish this same transition. + activity.failed(1); + assert!(!activity.recovering(true)); + activity.finish_run(1, false); + assert!(!activity.recovering(true)); + } + + #[test] + fn guest_ready_does_not_claim_recovery_while_its_watchdog_waits() { + let activity = Arc::new(Activity::default()); + activity.begin_run(1, false); + activity.ready(1, false); + assert!(!activity.recovering(true)); + activity.finish_run(1, true); + assert!(!activity.recovering(true)); + // The guest watchdog may later schedule actual work. + let reservation = activity.reserve().unwrap(); + assert!(activity.recovering(true)); + drop(reservation); + assert!(!activity.recovering(true)); + } + + #[test] + fn confirmed_own_child_attachment_stays_supervised_after_ready() { + let activity = Arc::new(Activity::default()); + activity.begin_run(1, false); + activity.ready(1, true); + activity.finish_run(1, true); + assert!(activity.recovering(true)); + // Releasing the dead child's handle cannot erase this accepted Ready ownership. + let reservation = activity.reserve().unwrap(); + activity.begin_run(2, true); + drop(reservation); + assert!(activity.recovering(true)); + } + + #[test] + fn recovery_failure_transfers_credit_through_backoff_to_the_next_run() { + let activity = Arc::new(Activity::default()); + activity.begin_run(1, true); + activity.failed(1); + assert!(activity.recovering(true)); + let reservation = activity.reserve().unwrap(); + activity.finish_run(1, false); + assert!(activity.recovering(true)); + // The timer has cleared pending, but has not called begin_with yet. + assert!(activity.recovering(true)); + activity.begin_run(2, true); + drop(reservation); + assert!(activity.recovering(true)); + } + + #[test] + fn a_deferred_owned_exit_preserves_only_the_follow_up_obligation() { + let activity = Arc::new(Activity::default()); + activity.begin_run(1, false); + activity.defer_recovery(); + activity.failed(1); + assert!(activity.recovering(true)); + let reservation = activity.reserve().unwrap(); + activity.finish_run(1, false); + assert!(activity.recovering(true)); + drop(reservation); + assert!(!activity.recovering(true)); + } + + #[test] + fn a_held_or_cancelled_retry_without_scheduled_work_loses_credit() { + let activity = Activity::default(); + activity.begin_run(1, true); + activity.failed(1); + assert!(activity.recovering(true)); + activity.finish_run(1, false); + assert!(!activity.recovering(true)); + } + + #[test] + fn an_old_terminal_report_or_finalizer_cannot_clear_a_new_start() { + let activity = Activity::default(); + activity.begin_run(1, false); + activity.failed(1); + activity.begin_run(2, false); + activity.ready(1, false); + activity.failed(1); + activity.finish_run(1, false); + assert!(activity.recovering(true)); + activity.ready(2, false); + activity.begin_run(1, true); + assert!(!activity.recovering(true)); + } + + #[test] + fn cancelling_an_older_task_does_not_release_a_newer_reservation() { + let activity = Arc::new(Activity::default()); + let older = activity.reserve().unwrap(); + let newer = activity.reserve().unwrap(); + drop(older); + assert!(activity.recovering(true)); + drop(newer); + assert!(!activity.recovering(true)); + } + + #[test] + fn exit_revocation_overrides_startup_owned_and_reserved_work() { + let activity = Arc::new(Activity::default()); + activity.begin_run(1, false); + assert!(!activity.recovering(false)); + activity.ready(1, true); + activity.finish_run(1, true); + assert!(!activity.recovering(false)); + let _reservation = activity.reserve().unwrap(); + activity.begin_run(2, true); + activity.failed(2); + assert!(!activity.recovering(false)); + } +} diff --git a/desktop/src-tauri/src/recovery_presence.rs b/desktop/src-tauri/src/recovery_presence.rs new file mode 100644 index 0000000000..f4b668c9a4 --- /dev/null +++ b/desktop/src-tauri/src/recovery_presence.rs @@ -0,0 +1,429 @@ +//! Read-only, process-lifetime recovery evidence with no persistent discovery record. +//! Consumers must independently identify its executable and the accepted socket's owner. + +use std::{ + fs, + io::{self, Read, Write}, + net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream}, + path::PathBuf, + sync::{ + atomic::{AtomicBool, AtomicUsize, Ordering}, + Arc, + }, + thread, + time::{Duration, Instant}, +}; + +const DOMAIN: &str = "ocx-desktop-recovery-v1"; +const CONNECTION_BUDGET: Duration = Duration::from_secs(3); +const MAX_CONNECTIONS: usize = 4; +const ACCEPT_ERROR_BACKOFF: Duration = Duration::from_millis(50); + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Snapshot { + /// None until the bundled CLI has resolved this shell's configuration home. + pub home: Option, + /// Stop, Quit and update drain revoke this directly from the exit coordinator. + pub wanted: bool, +} + +pub struct Presence { + stopped: Arc, + address: SocketAddr, +} + +fn hex(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + bytes + .iter() + .flat_map(|b| { + [ + DIGITS[(b >> 4) as usize] as char, + DIGITS[(b & 15) as usize] as char, + ] + }) + .collect() +} + +fn token(text: &str, length: usize) -> bool { + text.len() == length + && text + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +fn answer(request: &str, instance: &str, pid: u32, snapshot: Snapshot) -> Option { + let nonce = request + .strip_prefix(&format!("{DOMAIN} "))? + .strip_suffix('\n')?; + if !token(nonce, 64) { + return None; + } + let home = snapshot + .home + .and_then(|path| fs::canonicalize(path).ok()) + .and_then(|path| path.to_str().map(str::to_owned)); + let (state, home) = match home { + Some(home) if home.len() <= 4096 => ( + if snapshot.wanted { + "recovering" + } else { + "stopped" + }, + hex(home.as_bytes()), + ), + _ => ("unknown", "-".to_owned()), + }; + Some(format!( + "{DOMAIN} {nonce} {instance} {pid} {state} {home}\n" + )) +} + +fn serve(mut stream: TcpStream, instance: &str, snapshot: &dyn Fn() -> Snapshot) -> io::Result<()> { + if !stream.peer_addr()?.ip().is_loopback() { + return Ok(()); + } + stream.set_write_timeout(Some(Duration::from_secs(1)))?; + let deadline = Instant::now() + CONNECTION_BUDGET; + // Two fresh challenges let the client bracket its OS observations without releasing the + // accepted socket. Nothing serves HTTP, mutates state or accepts a reusable credential. + for _ in 0..2 { + let mut request = Vec::new(); + loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Ok(()); + } + stream.set_read_timeout(Some(remaining))?; + let mut byte = [0_u8; 1]; + if stream.read(&mut byte)? == 0 { + return Ok(()); + } + request.push(byte[0]); + if request.len() > 128 { + return Ok(()); + } + if byte[0] == b'\n' { + break; + } + } + let Some(response) = std::str::from_utf8(&request) + .ok() + .and_then(|request| answer(request, instance, std::process::id(), snapshot())) + else { + return Ok(()); + }; + stream.write_all(response.as_bytes())?; + } + // Retain ownership of the exact accepted socket while the client takes its final snapshot. + let remaining = deadline.saturating_duration_since(Instant::now()); + if !remaining.is_zero() { + stream.set_read_timeout(Some(remaining))?; + let _ = stream.read(&mut [0_u8; 1]); + } + Ok(()) +} + +impl Presence { + pub fn start( + instance: String, + snapshot: Arc Snapshot + Send + Sync>, + ) -> io::Result { + Self::start_with_accept(instance, snapshot, TcpListener::accept) + } + + fn start_with_accept( + instance: String, + snapshot: Arc Snapshot + Send + Sync>, + mut accept: impl FnMut(&TcpListener) -> io::Result<(TcpStream, SocketAddr)> + Send + 'static, + ) -> io::Result { + if !token(&instance, 32) { + return Err(io::ErrorKind::InvalidInput.into()); + } + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?; + let address = listener.local_addr()?; + let stopped = Arc::new(AtomicBool::new(false)); + let stop = Arc::clone(&stopped); + let presence = Self { stopped, address }; + thread::Builder::new() + .name("desktop-recovery".into()) + .spawn(move || { + let active = Arc::new(AtomicUsize::new(0)); + while !stop.load(Ordering::Acquire) { + match accept(&listener) { + Ok((stream, _)) => { + if stop.load(Ordering::Acquire) { + break; + } + if active.load(Ordering::Acquire) >= MAX_CONNECTIONS { + continue; + } + active.fetch_add(1, Ordering::AcqRel); + let connection_active = Arc::clone(&active); + let snapshot = Arc::clone(&snapshot); + let instance = instance.clone(); + if thread::Builder::new() + .name("desktop-recovery-read".into()) + .spawn(move || { + let _ = serve(stream, &instance, snapshot.as_ref()); + connection_active.fetch_sub(1, Ordering::AcqRel); + }) + .is_err() + { + active.fetch_sub(1, Ordering::AcqRel); + } + } + Err(_) => { + // Retain the listener after transient aborts or resource exhaustion. + // Pace all errors, including interruptions, then recheck stop. + thread::sleep(ACCEPT_ERROR_BACKOFF); + } + } + } + })?; + Ok(presence) + } +} + +impl Drop for Presence { + fn drop(&mut self) { + self.stopped.store(true, Ordering::Release); + // Wake the blocking accept without an idle polling timer or an unbounded shutdown wait. + let _ = TcpStream::connect_timeout(&self.address, Duration::from_millis(50)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + io::{BufRead, BufReader}, + sync::{mpsc, Mutex}, + }; + + struct Finished(mpsc::Sender<()>); + + impl Drop for Finished { + fn drop(&mut self) { + let _ = self.0.send(()); + } + } + + fn unresolved_snapshot() -> Snapshot { + Snapshot { + home: None, + wanted: true, + } + } + + fn challenge(stream: &mut TcpStream) -> io::Result { + stream.set_read_timeout(Some(Duration::from_secs(1)))?; + stream.write_all(format!("{DOMAIN} {}\n", "b".repeat(64)).as_bytes())?; + let mut response = String::new(); + BufReader::new(stream).read_line(&mut response)?; + Ok(response) + } + + #[test] + fn accept_errors_retry_before_a_real_connection() { + for kind in [ + io::ErrorKind::ConnectionAborted, + io::ErrorKind::Other, + io::ErrorKind::Interrupted, + ] { + let (injected, observed) = mpsc::channel(); + let (finished, completion) = mpsc::channel(); + let finished = Finished(finished); + let mut first = true; + let presence = Presence::start_with_accept( + "a".repeat(32), + Arc::new(unresolved_snapshot), + move |listener| { + let _ = &finished; + if first { + first = false; + let _ = injected.send(()); + return Err(kind.into()); + } + listener.accept() + }, + ) + .unwrap(); + observed.recv_timeout(Duration::from_secs(1)).unwrap(); + // Only the error is injected; the next connection and response use the real socket. + let response = + TcpStream::connect(presence.address).and_then(|mut stream| challenge(&mut stream)); + drop(presence); + completion.recv_timeout(Duration::from_secs(1)).unwrap(); + let response = response.unwrap_or_else(|error| panic!("{kind:?}: {error}")); + assert!(response.starts_with(&format!("{DOMAIN} {} ", "b".repeat(64)))); + assert!(response.ends_with(" unknown -\n")); + } + } + + fn assert_persistent_accept_error_is_paced_and_stops(kind: io::ErrorKind) { + let (attempted, attempts) = mpsc::channel(); + let (finished, completion) = mpsc::channel(); + let finished = Finished(finished); + let mut count = 0; + let presence = + Presence::start_with_accept("a".repeat(32), Arc::new(unresolved_snapshot), move |_| { + let _ = &finished; + // Do not throttle the loop in the injected operation, even when it spins. + if count < 3 { + let _ = attempted.send(Instant::now()); + } + count += 1; + Err(kind.into()) + }) + .unwrap(); + let times: Result, _> = (0..3) + .map(|_| attempts.recv_timeout(Duration::from_secs(1))) + .collect(); + // Join the listener's lifetime signal before checking assertions, including a failed read. + drop(presence); + completion.recv_timeout(Duration::from_secs(1)).unwrap(); + let times = times.unwrap_or_else(|error| panic!("{kind:?}: {error}")); + for pair in times.windows(2) { + assert!( + pair[1].duration_since(pair[0]) >= ACCEPT_ERROR_BACKOFF, + "{kind:?} retried without an error backoff" + ); + } + } + + #[test] + fn persistent_aborted_accept_errors_are_paced_and_stop() { + assert_persistent_accept_error_is_paced_and_stops(io::ErrorKind::ConnectionAborted); + } + + #[test] + fn persistent_resource_accept_errors_are_paced_and_stop() { + assert_persistent_accept_error_is_paced_and_stops(io::ErrorKind::Other); + } + + #[test] + fn persistent_interrupted_accept_errors_are_paced_and_stop() { + assert_persistent_accept_error_is_paced_and_stops(io::ErrorKind::Interrupted); + } + + #[test] + fn a_fifth_reader_is_refused_while_four_challenged_readers_remain_open() { + let presence = Presence::start("a".repeat(32), Arc::new(unresolved_snapshot)).unwrap(); + let mut readers = Vec::new(); + let result = (|| -> io::Result { + for _ in 0..MAX_CONNECTIONS { + let mut stream = TcpStream::connect(presence.address)?; + let response = challenge(&mut stream)?; + assert!(response.ends_with(" unknown -\n")); + // A completed challenge proves each reader was admitted before trying the fifth. + readers.push(stream); + } + let mut extra = TcpStream::connect(presence.address)?; + extra.set_read_timeout(Some(Duration::from_secs(1)))?; + extra.read(&mut [0_u8; 1]) + })(); + drop(readers); + drop(presence); + assert_eq!(result.unwrap(), 0); + } + + #[test] + fn fresh_challenges_observe_stop_without_replacing_the_listener() { + let root = std::env::temp_dir().join(format!("ocx-recovery-wire-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + let home = root.join("home"); + fs::create_dir_all(&home).unwrap(); + let state = Arc::new(Mutex::new(Snapshot { + home: Some(home), + wanted: true, + })); + let observed = Arc::clone(&state); + let presence = Presence::start( + "a".repeat(32), + Arc::new(move || observed.lock().unwrap().clone()), + ) + .unwrap(); + let mut stream = TcpStream::connect(presence.address).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + for (nonce, wanted) in [('b', true), ('c', false)] { + state.lock().unwrap().wanted = wanted; + let nonce = nonce.to_string().repeat(64); + stream + .write_all(format!("{DOMAIN} {nonce}\n").as_bytes()) + .unwrap(); + let mut response = String::new(); + BufReader::new(&stream).read_line(&mut response).unwrap(); + assert!(response.starts_with(&format!( + "{DOMAIN} {nonce} {} {} ", + "a".repeat(32), + std::process::id() + ))); + assert!(response.contains(if wanted { " recovering " } else { " stopped " })); + } + drop(stream); + drop(presence); + assert_eq!(fs::read_dir(&root).unwrap().count(), 1); + let _ = fs::remove_dir_all(root); + } + + #[test] + fn idle_connections_release_every_slot_within_the_connection_budget() { + let presence = Presence::start( + "a".repeat(32), + Arc::new(|| Snapshot { + home: None, + wanted: true, + }), + ) + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(4); + let mut idle: Vec<_> = (0..MAX_CONNECTIONS) + .map(|_| TcpStream::connect(presence.address).unwrap()) + .collect(); + for stream in &mut idle { + let remaining = deadline.saturating_duration_since(Instant::now()); + assert!( + !remaining.is_zero(), + "idle connection exhausted the client budget" + ); + stream.set_read_timeout(Some(remaining)).unwrap(); + assert_eq!(stream.read(&mut [0_u8; 1]).unwrap(), 0); + } + assert!(Instant::now() < deadline); + // A fresh challenge is admitted after the entire idle cohort has expired. + let mut stream = TcpStream::connect(presence.address).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(1))) + .unwrap(); + let nonce = "b".repeat(64); + stream + .write_all(format!("{DOMAIN} {nonce}\n").as_bytes()) + .unwrap(); + let mut response = String::new(); + BufReader::new(&stream).read_line(&mut response).unwrap(); + assert!(response.starts_with(&format!("{DOMAIN} {nonce} "))); + assert!(response.ends_with(" unknown -\n")); + } + + #[test] + fn unresolved_home_and_invalid_requests_never_assert_recovery() { + let snapshot = Snapshot { + home: None, + wanted: true, + }; + let request = format!("{DOMAIN} {}\n", "a".repeat(64)); + assert!(answer(&request, &"b".repeat(32), 123, snapshot.clone()) + .unwrap() + .ends_with(" unknown -\n")); + for request in [ + "GET / HTTP/1.1\n", + "ocx-desktop-recovery-v1 short\n", + "ocx-desktop-recovery-v1 a\r\n", + ] { + assert!(answer(request, &"b".repeat(32), 123, snapshot.clone()).is_none()); + } + } +} diff --git a/desktop/src-tauri/src/sidecar.rs b/desktop/src-tauri/src/sidecar.rs index e601498fe0..f055f1e602 100644 --- a/desktop/src-tauri/src/sidecar.rs +++ b/desktop/src-tauri/src/sidecar.rs @@ -198,13 +198,17 @@ pub fn start( .map_err(|error| error.to_string())? .join("gui") .join("dist"); - let command = app + let mut command = app .shell() .sidecar("ocx") .map_err(|error| error.to_string())? .args(["start", "--port", &endpoint.port.to_string()]) .env("OPENCODEX_GUI_DIST", gui_dist) .env(SUPERVISED_ENV, "1"); + // The installer's opt-out could not be saved: keep this session from sending anything. + if crate::installer_telemetry::sidecar_env_opt_out() { + command = command.env("OCX_TELEMETRY", "0"); + } let (events, child) = crate::process_spawn::with_spawn(|| command.spawn()).map_err(|error| error.to_string())?; let watch = watch.for_child(child.pid()); diff --git a/desktop/src-tauri/src/startup.rs b/desktop/src-tauri/src/startup.rs index 8ceb94fbd4..d7a5e86b62 100644 --- a/desktop/src-tauri/src/startup.rs +++ b/desktop/src-tauri/src/startup.rs @@ -696,6 +696,7 @@ pub fn begin_with(app: &AppHandle, mode: Mode) -> bool { .store(mode == Mode::Recover, Ordering::Release); startup.restart(); let generation = startup.generation.fetch_add(1, Ordering::AcqRel) + 1; + crate::recovery::begin_run(app, generation, mode == Mode::Recover); let started = Instant::now(); startup.set_deadline(started + DEADLINE); let app = app.clone(); @@ -725,6 +726,7 @@ pub fn begin_with(app: &AppHandle, mode: Mode) -> bool { ), ); if let Expiry::Fired(progress) = &expiry { + crate::recovery::failed(&guard, generation); let _ = guard.emit(PHASE_EVENT, progress); } expiry @@ -769,7 +771,7 @@ pub fn begin_with(app: &AppHandle, mode: Mode) -> bool { (false, Some(held)) => crate::supervisor::RunOutcome::Held(held), (false, None) => crate::supervisor::RunOutcome::Failed, }; - crate::supervisor::run_finished(&app, mode, ended, detail.as_deref()); + crate::supervisor::run_finished(&app, generation, mode, ended, detail.as_deref()); }); true } @@ -784,6 +786,7 @@ fn settle(app: &AppHandle, started: Instant, generation: u64, reason: String) { }; startup.with_reporting(|| { if let Some(progress) = startup.settle(started, generation, reason) { + crate::recovery::failed(app, generation); let _ = app.emit(PHASE_EVENT, progress); } }); @@ -806,6 +809,9 @@ async fn run(app: &AppHandle, started: Instant) { ); report(app, started, Phase::Resolving, None); + // SignPath's installation-option condition: an opt-out chosen in the Windows installer is + // saved into the user's config before any proxy is resolved, attached to or started. + crate::installer_telemetry::apply(app, deadline).await; // D5: the shell no longer resolves the home, the port or liveness. It asks the bundled CLI, // which owns the tuned probe budgets that exist because a shell-side reimplementation answered // "nobody is listening" twice and started duplicate proxies. The call is inside the sequence, so @@ -833,6 +839,7 @@ async fn run(app: &AppHandle, started: Instant) { endpoint, home: answer.home(), }; + crate::recovery::bind_home(app, &target.home); let proxy = match ProxyClient::new(endpoint, Auth::new(answer.home())) { Ok(proxy) => proxy, Err(error) => { @@ -1810,6 +1817,17 @@ fn emit(app: &AppHandle, mut progress: Progress, failed_in: Option) -> bo if !startup.publish(&mut progress, failed_in) { return false; } + let generation = startup.generation.load(Ordering::Acquire); + if progress.phase == Phase::Ready.id() { + crate::recovery::ready( + app, + generation, + app.try_state::() + .is_some_and(|state| state.owns_runtime()), + ); + } else if progress.phase == Phase::Failed.id() { + crate::recovery::failed(app, generation); + } let _ = app.emit(PHASE_EVENT, progress); true }); diff --git a/desktop/src-tauri/src/supervisor.rs b/desktop/src-tauri/src/supervisor.rs index ffccc60b52..df62c72b51 100644 --- a/desktop/src-tauri/src/supervisor.rs +++ b/desktop/src-tauri/src/supervisor.rs @@ -383,7 +383,7 @@ fn on_exit(app: &AppHandle, pid: u32, exit: SidecarExit) { )); match verdict { Verdict::Ignore(_) => {} - Verdict::Defer => supervisor.state().owed = true, + Verdict::Defer => defer_recovery(app, &supervisor), Verdict::RespawnAfter(delay) => { // The child is gone: let go of its handle without signalling anything, so nothing // later reads it as a runtime this app still owns. @@ -396,6 +396,12 @@ fn on_exit(app: &AppHandle, pid: u32, exit: SidecarExit) { } } +fn defer_recovery(app: &AppHandle, supervisor: &Supervisor) { + let mut state = supervisor.state(); + state.owed = true; + crate::recovery::defer_recovery(app); +} + fn describe(verdict: Verdict, attempts: u32) -> String { match verdict { Verdict::Ignore(reason) => format!("left alone: {reason}"), @@ -413,19 +419,23 @@ fn schedule(app: &AppHandle, delay: Duration) { let Some(supervisor) = app.try_state::() else { return; }; - { + let reservation = { let mut state = supervisor.state(); if state.pending { return; } + // A duplicate scheduler must not see pending before its recovery credit exists. + let reservation = crate::recovery::reserve(app); state.pending = true; state.attempts = state.attempts.saturating_add(1); state.streak = 0; state.healthy_since = None; state.parked = None; - } + reservation + }; let app = app.clone(); tauri::async_runtime::spawn(async move { + let _reservation = reservation; sleep(delay).await; let Some(supervisor) = app.try_state::() else { return; @@ -439,10 +449,10 @@ fn schedule(app: &AppHandle, delay: Duration) { match decide(input(&app, false, false, attempts)) { Verdict::RespawnAfter(_) => { if !startup::begin_with(&app, Mode::Recover) { - supervisor.state().owed = true; + defer_recovery(&app, &supervisor); } } - Verdict::Defer => supervisor.state().owed = true, + Verdict::Defer => defer_recovery(&app, &supervisor), Verdict::Ignore(reason) => supervisor.note(&format!("recovery skipped: {reason}")), } }); @@ -452,8 +462,15 @@ fn schedule(app: &AppHandle, delay: Duration) { /// [`follow_up`] says: another attempt after the backoff, a parked watch when a listener this app /// cannot use holds the port, or nothing until the person retries. `detail` is the run's own last /// word, for the log. -pub fn run_finished(app: &AppHandle, mode: Mode, outcome: RunOutcome, detail: Option<&str>) { +pub fn run_finished( + app: &AppHandle, + generation: u64, + mode: Mode, + outcome: RunOutcome, + detail: Option<&str>, +) { let Some(supervisor) = app.try_state::() else { + crate::recovery::finish_run(app, generation, false); return; }; let ready = outcome == RunOutcome::Ready; @@ -468,6 +485,7 @@ pub fn run_finished(app: &AppHandle, mode: Mode, outcome: RunOutcome, detail: Op (owed, state.attempts) }; if ready { + crate::recovery::finish_run(app, generation, true); if mode == Mode::Recover { supervisor.note("recovery run ready"); } @@ -498,6 +516,7 @@ pub fn run_finished(app: &AppHandle, mode: Mode, outcome: RunOutcome, detail: Op } } } + crate::recovery::finish_run(app, generation, false); } /// The watchdog's one question: who answers the endpoint, if anything. diff --git a/desktop/src-tauri/src/traffic_lights.rs b/desktop/src-tauri/src/traffic_lights.rs new file mode 100644 index 0000000000..f578711606 --- /dev/null +++ b/desktop/src-tauri/src/traffic_lights.rs @@ -0,0 +1,126 @@ +//! Where the macOS traffic lights sit over the overlay title bar. +//! +//! The dashboard's sidebar strip (`gui/src/components/app-titlebar.css`) is a 40pt row with an +//! 80pt lead inset, and the native lights have to sit centered on that row. tao places them by +//! resizing the title-bar container to `close button height + y` and moving each button to +//! `x + i * spacing`; the button keeps its own offset inside the container. So the same `y` +//! lands differently when AppKit's button metrics change, and they did change in macOS 26: +//! +//! | design | close button | spacing | y=22 centers at | y centering on 20 | +//! |-----------------|--------------|---------|-----------------|-------------------| +//! | macOS 26 Tahoe | 14 x 14 | 23 | 20 | 22 | +//! | macOS 15 and up | 14 x 16 | 20 | 24 (4pt low) | 18 | +//! +//! Both rows were measured with an AppKit probe that replays tao 0.37.2's +//! `inset_traffic_lights` on an overlay window: once with the Tahoe design and once with the +//! pre-Tahoe design forced through `UIDesignRequiresCompatibility` (#8280). Horizontally both +//! designs start at x and end inside the strip's 80pt inset (Tahoe at 78pt, pre-Tahoe at 72pt), +//! so only `y` depends on the OS. + +/// Lead inset of the close button, in points. `--tl-inset` in app-titlebar.css is this plus +/// 52pt of lights and 10pt of air. +pub const X: f64 = 18.0; +/// macOS 26 (Tahoe) and later: 14pt-tall buttons centered on the 40pt row. +pub const Y_TAHOE: f64 = 22.0; +/// macOS 15 (Sequoia) and earlier: 16pt-tall buttons need 4pt less to land on the same line. +pub const Y_PRE_TAHOE: f64 = 18.0; +/// The first release with the taller title bar metrics. Apple went from 15 straight to 26. +const TAHOE_MAJOR: u32 = 26; + +/// The `y` for a given macOS major version. An unknown version keeps the Tahoe value, which is +/// what every build shipped before this distinction existed. +pub fn y_for(macos_major: Option) -> f64 { + match macos_major { + Some(major) if major < TAHOE_MAJOR => Y_PRE_TAHOE, + _ => Y_TAHOE, + } +} + +/// The major component of a product version such as `15.7.1` or `26.0`. +fn parse_major(version: &str) -> Option { + version.trim().split('.').next()?.parse().ok() +} + +/// The running macOS major version, from `kern.osproductversion`. Unlike the +/// `SystemVersion.plist` reads behind some version APIs, this sysctl is not redirected by +/// `SYSTEM_VERSION_COMPAT`, so it reports the real release. +#[cfg(target_os = "macos")] +pub fn macos_major() -> Option { + use std::ffi::{c_char, c_int, c_void, CStr}; + extern "C" { + fn sysctlbyname( + name: *const c_char, + oldp: *mut c_void, + oldlenp: *mut usize, + newp: *mut c_void, + newlen: usize, + ) -> c_int; + } + let mut buffer = [0u8; 32]; + let mut len = buffer.len(); + // SAFETY: the name is NUL-terminated, `buffer` is writable for `len` bytes, and no new + // value is set. + let status = unsafe { + sysctlbyname( + c"kern.osproductversion".as_ptr(), + buffer.as_mut_ptr().cast(), + &mut len, + std::ptr::null_mut(), + 0, + ) + }; + if status != 0 { + return None; + } + let version = CStr::from_bytes_until_nul(&buffer[..len.min(buffer.len())]).ok()?; + parse_major(version.to_str().ok()?) +} + +#[cfg(test)] +mod tests { + use super::{parse_major, y_for, X, Y_PRE_TAHOE, Y_TAHOE}; + + #[test] + fn product_versions_parse_to_their_major() { + assert_eq!(parse_major("26.6.2"), Some(26)); + assert_eq!(parse_major("15.7.1"), Some(15)); + assert_eq!(parse_major("14.0"), Some(14)); + assert_eq!(parse_major("10.16"), Some(10)); + assert_eq!(parse_major(" 13 "), Some(13)); + assert_eq!(parse_major(""), None); + assert_eq!(parse_major("abc"), None); + } + + #[test] + fn sequoia_and_earlier_lift_the_lights_onto_the_strip() { + for major in [10, 11, 12, 13, 14, 15] { + assert_eq!(y_for(Some(major)), Y_PRE_TAHOE, "macOS {major}"); + } + for major in [26, 27, 30] { + assert_eq!(y_for(Some(major)), Y_TAHOE, "macOS {major}"); + } + assert_eq!(y_for(None), Y_TAHOE); + } + + /// The measured geometry behind the constants: tao sets the container to + /// `button_height + y`, AppKit keeps the button's default offset from the container's bottom + /// edge, and the light should be centered on the 40pt strip row. + #[test] + fn both_designs_center_on_the_strip_row() { + // Center of the light, measured from the window's top edge. + let center = |height: f64, bottom: f64, y: f64| (height + y) - bottom - height / 2.0; + // Tahoe: a 14pt button whose default frame origin is (9, 9). + assert_eq!(center(14.0, 9.0, Y_TAHOE), 20.0); + // Pre-Tahoe: a 16pt button whose default frame origin is (7, 6). + assert_eq!(center(16.0, 6.0, Y_PRE_TAHOE), 20.0); + assert_eq!(center(16.0, 6.0, Y_TAHOE), 24.0); + assert_eq!(X, 18.0); + } + + #[cfg(target_os = "macos")] + #[test] + fn the_running_macos_reports_a_major_version() { + let major = super::macos_major().expect("kern.osproductversion"); + assert!(major >= 10, "{major}"); + } +} diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 6f350c6352..c7d1444e02 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "OpenCodex", - "version": "2.89.1-dalsoop.1", + "version": "2.100.2", "identifier": "com.opencodex.desktop", "build": { "frontendDist": "../ui", @@ -52,7 +52,13 @@ "type": "downloadBootstrapper" }, "wix": { - "language": "en-US" + "language": "en-US", + "fragmentPaths": [ + "wix/telemetry-choice.wxs" + ], + "componentGroupRefs": [ + "OcxTelemetryInstallerChoice" + ] } }, "linux": { diff --git a/desktop/src-tauri/update-trust-root.json b/desktop/src-tauri/update-trust-root.json new file mode 100644 index 0000000000..94bcccfa83 --- /dev/null +++ b/desktop/src-tauri/update-trust-root.json @@ -0,0 +1,38 @@ +{ + "schema": "ocx.update.root/1", + "revision": 1, + "expiresAt": "2028-11-07T00:00:00Z", + "rootKeys": [ + { + "keyId": "eae4c0180e8ca39a844b3c0e1ec28842261e85628d6dee77ceff5dd081853799", + "algorithm": "minisign-ed25519-blake2b512/1", + "publicKey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEFDNzZCMDg0NkVCRUJGODEKUldTQnY3NXVoTEIyckhRUXJMOXJRUDR0aHQ2L3pLVHVweXFSc1lzS24vWDNiSUJ5MXJIZmpyb2sK" + } + ], + "rootThreshold": 1, + "releaseKeys": [ + { + "keyId": "eae4c0180e8ca39a844b3c0e1ec28842261e85628d6dee77ceff5dd081853799", + "algorithm": "minisign-ed25519-blake2b512/1", + "publicKey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEFDNzZCMDg0NkVCRUJGODEKUldTQnY3NXVoTEIyckhRUXJMOXJRUDR0aHQ2L3pLVHVweXFSc1lzS24vWDNiSUJ5MXJIZmpyb2sK", + "channels": [ + "latest", + "preview", + "nightly" + ], + "roles": [ + "release", + "tree", + "desktop-artifact", + "standalone-artifact", + "guardian-artifact" + ] + } + ], + "releaseThreshold": 1, + "channels": [ + "latest", + "preview", + "nightly" + ] +} diff --git a/desktop/src-tauri/wix/telemetry-choice.wxs b/desktop/src-tauri/wix/telemetry-choice.wxs new file mode 100644 index 0000000000..56b36c19f4 --- /dev/null +++ b/desktop/src-tauri/wix/telemetry-choice.wxs @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + OCX_TELEMETRY_CHOICE <> "" AND OCX_TELEMETRY_CHOICE ~<> "send" + + OCX_TELEMETRY_CHOICE <> "" AND OCX_TELEMETRY_STAMP = "" + OCX_TELEMETRY_CHOICE = "" AND OCX_TELEMETRY_PREVIOUS_CHOICE <> "" + OCX_TELEMETRY_STAMP = "" AND OCX_TELEMETRY_PREVIOUS_STAMP <> "" + + OCX_TELEMETRY_STAMP <> "" + + OCX_TELEMETRY_CHOICE = "" + + OCX_TELEMETRY_CHOICE ~= "send" + + + + + + + + + + + + + + + + + + + + + <a href="https://opencodex.me/reference/code-signing/#privacy">Read the full privacy policy</a> + + + + + 1 + + + OCX_TELEMETRY_SEND = "1" + NOT (OCX_TELEMETRY_SEND = "1") + OCX_TELEMETRY_CHOICE ~<> OCX_TELEMETRY_PREVIOUS_CHOICE + OCX_TELEMETRY_CHOICE ~= OCX_TELEMETRY_PREVIOUS_CHOICE AND OCX_TELEMETRY_CARRIED_STAMP <> "" + 1 + + + 1 + + + + NOT Installed + NOT Installed + + + diff --git a/desktop/ui/cli.html b/desktop/ui/cli.html index 524c80fa02..7a81d87733 100644 --- a/desktop/ui/cli.html +++ b/desktop/ui/cli.html @@ -5,32 +5,116 @@ OpenCodex terminal command
-

Terminal command

- -

Reading command configuration…

-

-
    - -

    After enabling or repairing, open a new terminal. Existing shells and aliases can still select another command. Use type -a ocx on POSIX, or Get-Command ocx -All and where.exe ocx on Windows to check.

    -

    Remove the terminal command here before uninstalling Desktop. Removing it keeps your off choice for the next launch.

    -
    - - - +
    + +

    Terminal command

    +
    +
    + +

    Reading command configuration…

    +

    +
      + +
      + + + +
      +
      +

      After enabling or repairing, open a new terminal. Existing shells and aliases can still select another command. Use type -a ocx on POSIX, or Get-Command ocx -All and where.exe ocx on Windows to check.

      +

      Remove the terminal command here before uninstalling Desktop. Removing it keeps your off choice for the next launch.

      +
      diff --git a/desktop/ui/fonts/OFL.txt b/desktop/ui/fonts/OFL.txt new file mode 100644 index 0000000000..98835ac3f0 --- /dev/null +++ b/desktop/ui/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font) Geist-Italic[wght].ttf: Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/desktop/ui/fonts/geist-latin.woff2 b/desktop/ui/fonts/geist-latin.woff2 new file mode 100644 index 0000000000..991445d78a Binary files /dev/null and b/desktop/ui/fonts/geist-latin.woff2 differ diff --git a/desktop/ui/fonts/geist-mono-latin.woff2 b/desktop/ui/fonts/geist-mono-latin.woff2 new file mode 100644 index 0000000000..0750682c8d Binary files /dev/null and b/desktop/ui/fonts/geist-mono-latin.woff2 differ diff --git a/desktop/ui/index.html b/desktop/ui/index.html index 60eed6cf2d..81588dcb14 100644 --- a/desktop/ui/index.html +++ b/desktop/ui/index.html @@ -5,87 +5,120 @@ OpenCodex + + + + + + + + + + + + diff --git a/docs-site/public/grain.svg b/docs-site/public/grain.svg new file mode 100644 index 0000000000..9b7a1133c2 --- /dev/null +++ b/docs-site/public/grain.svg @@ -0,0 +1 @@ + diff --git a/docs-site/src/assets/logo-dark.svg b/docs-site/src/assets/logo-dark.svg new file mode 100644 index 0000000000..5b5acb9373 --- /dev/null +++ b/docs-site/src/assets/logo-dark.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/docs-site/src/assets/logo-light.svg b/docs-site/src/assets/logo-light.svg new file mode 100644 index 0000000000..0797892fe0 --- /dev/null +++ b/docs-site/src/assets/logo-light.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/docs-site/src/components/CloudCanvas.astro b/docs-site/src/components/CloudCanvas.astro new file mode 100644 index 0000000000..6abc9d8847 --- /dev/null +++ b/docs-site/src/components/CloudCanvas.astro @@ -0,0 +1,316 @@ +--- +// Animated WebGL2 cloud sky for the hero and closing panel. Renders into an +// absolutely positioned host that fills its nearest positioned ancestor. +// Without WebGL2 the host keeps its CSS sky colour, so the section still reads. +// Under reduced motion one still frame is drawn and re-drawn on theme change. +interface Props { + class?: string; + /** `sky` paints a full daylight sky; `overlay` draws only the clouds, + * dusk-lit and translucent, over whatever sits behind the canvas. */ + variant?: 'sky' | 'overlay'; +} +const { class: className, variant = 'sky' } = Astro.props; +--- + + + + diff --git a/docs-site/src/components/Header.astro b/docs-site/src/components/Header.astro index 1e6c9e2d58..7e86a7de5d 100644 --- a/docs-site/src/components/Header.astro +++ b/docs-site/src/components/Header.astro @@ -17,7 +17,34 @@ const base = import.meta.env.BASE_URL.replace(/\/?$/, '/'); const prefix = locale ? `${base}${locale}/` : base; type NavLink = { label: string; href: string }; -type NavGroup = { label: string; links: NavLink[] }; +type NavGroup = { label: string; links: NavLink[]; more?: NavLink }; + +// Dropdown rows: every entry gets an icon tile. +// Lucide outline paths (24x24, stroke), keyed by the link's slug. +const ICONS: Record = { + 'getting-started/installation/': 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3', + 'getting-started/quickstart/': 'M13 2 3 14h9l-1 8 10-12h-9l1-8Z', + 'getting-started/how-it-works/': 'M6 3v12M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM18 9a9 9 0 0 1-9 9', + 'getting-started/for-agents/': 'M12 8V4H8m8 0h-4M4 12a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2Zm11 3h.01M9 15h.01', + 'guides/providers/': 'M12 22v-5M9 8V2M15 8V2M6 8h12l-1 6a5 5 0 0 1-10 0Z', + 'guides/model-routing/': 'M6 19a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM18 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM9 16h5.5a3.5 3.5 0 0 0 0-7H15', + 'guides/combos/': 'm12 2 10 5-10 5L2 7Zm-10 10 10 5 10-5M2 17l10 5 10-5', + 'guides/codex-integration/': 'M16 18l6-6-6-6M8 6l-6 6 6 6', + 'guides/codex-app-models/': 'M3 5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Zm6-2v18M3 9h6', + 'guides/claude-code/': 'M4 17l6-6-6-6M12 19h8', + 'guides/sidecars/': 'M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm10 2-4.35-4.35', + 'guides/image-bridge/': 'M3 5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Zm6 6a2 2 0 1 0 0-4 2 2 0 0 0 0 4Zm12 4-3.09-3.09a2 2 0 0 0-2.82 0L6 21', + 'guides/video-bridge/': 'm16 13 5.22 3.48a.5.5 0 0 0 .78-.42V7.94a.5.5 0 0 0-.76-.43L16 10.5M4 6h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2Z', + 'guides/web-dashboard/': 'M3 3v16a2 2 0 0 0 2 2h16M7 16V9m5 7V5m5 11v-4', + 'guides/sub-agent-surface/': 'M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm13 10v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75', + 'reference/cli/': 'M4 17l6-6-6-6M12 19h8', + 'reference/configuration/': 'M20 7h-9M14 17H5M17 20a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM7 10a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z', + 'reference/adapters/': 'M12 22v-5M9 8V2M15 8V2M6 8h12l-1 6a5 5 0 0 1-10 0Z', + 'reference/architecture/': 'M3 3h7v7H3Zm11 0h7v7h-7Zm0 11h7v7h-7ZM3 14h7v7H3Z', + 'reference/proxy-formats/': 'M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5a2 2 0 0 0 2 2h1m8 0h1a2 2 0 0 0 2-2v-5a2 2 0 0 1 2-2 2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1', + 'reference/management-api/': 'M2 4h20v6H2Zm0 10h20v6H2ZM6 7h.01M6 17h.01', +}; +const iconFor = (href: string) => ICONS[href.slice(prefix.length)] ?? ICONS['guides/codex-integration/']; const fr = { 'Auto': 'Automatique', @@ -25,7 +52,7 @@ const fr = { 'Dark': 'Sombre', 'Theme': 'Thème', 'Click to use the next theme': 'Cliquez pour passer au thème suivant', - 'Getting Started': 'Démarrage', + 'Getting Started': 'Premiers pas', 'Installation': 'Installation', 'Quickstart': 'Démarrage rapide', 'How It Works': 'Fonctionnement', @@ -47,7 +74,9 @@ const fr = { 'Architecture': 'Architecture', 'Proxy API Formats': 'Formats de l’API proxy', 'Management API': 'API de gestion', + 'Dashboard': 'Tableau de bord', 'Contributing': 'Contribuer', + 'Explore guides': 'Explorer les guides', 'Main': 'Navigation principale', 'Select language': 'Choisir la langue', 'Menu': 'Menu', @@ -62,8 +91,8 @@ const starCount = await getStarCount(); const starLocale = locale ?? 'en'; const githubLabel = t('GitHub', 'GitHub', 'GitHub', 'GitHub', 'GitHub', 'GitHub', 'GitHub'); const starLabel = t( - 'GitHub, {count} stars', 'GitHub, 별 {count}개', 'GitHub,{count} 个星标', - 'GitHub, {count} звёзд', 'GitHub、{count} スター', 'GitHub,{count} 個星標', 'GitHub, {count} yıldız', + 'GitHub, {count} stars', 'GitHub, 스타 {count}개', 'GitHub,{count} 个星标', + 'GitHub, звёзд: {count}', 'GitHub、{count} スター', 'GitHub,{count} 個星標', 'GitHub, {count} yıldız', ); const githubAccessibleName = starCount === null ? githubLabel : starLabel.replace('{count}', starCount.toLocaleString(starLocale)); @@ -113,7 +142,7 @@ const groups: NavGroup[] = [ { label: t('Installation', '설치', '安装', 'Установка', 'インストール', '安裝', 'Kurulum'), href: `${prefix}getting-started/installation/` }, { label: t('Quickstart', '빠른 시작', '快速开始', 'Быстрый старт', 'クイックスタート', '快速入門', 'Hızlı Başlangıç'), href: `${prefix}getting-started/quickstart/` }, { label: t('How It Works', '동작 원리', '工作原理', 'Как это работает', '仕組み', '運作原理', 'Nasıl Çalışır'), href: `${prefix}getting-started/how-it-works/` }, - { label: t('Agent Quickstart', '에이전트 퀵스타트', 'Agent 快速上手', 'Быстрый старт для агентов', 'エージェント向けクイックスタート', 'Agent 快速上手', 'Ajanlar İçin Hızlı Başlangıç'), href: `${prefix}getting-started/for-agents/` }, + { label: t('Agent Quickstart', '에이전트용 빠른 시작', 'Agent 快速上手', 'Быстрый старт для агентов', 'エージェント向けクイックスタート', 'Agent 快速上手', 'Ajanlar İçin Hızlı Başlangıç'), href: `${prefix}getting-started/for-agents/` }, ], }, { @@ -145,17 +174,36 @@ const groups: NavGroup[] = [ }, ]; +const dashboard: NavLink = { + label: t('Dashboard', '대시보드', '仪表盘', 'Дашборд', 'ダッシュボード', '儀表板', 'Panel'), + href: `${prefix}dashboard/`, +}; + +// Eleven guides made the Guides panel read like a sitemap. The panel keeps +// the six people reach for first and ends in a row that jumps to the curated +// docs map on the landing page. That band is a selection of guide pages, not +// an index of them, and the docs sidebar is a subset too, so the row invites +// exploration instead of claiming it lists every guide. +const GUIDE_PICKS = ['providers', 'model-routing', 'codex-integration', 'claude-code', 'sidecars', 'web-dashboard']; +const guides = groups[1]; +guides.links = guides.links.filter((link) => GUIDE_PICKS.some((slug) => link.href.endsWith(`guides/${slug}/`))); +guides.more = { + label: t('Explore guides', '가이드 둘러보기', '浏览指南', 'Обзор руководств', 'ガイドを探る', '瀏覽指南', 'Kılavuzlara göz atın'), + href: `${prefix}#docs-map`, +}; + const contributing: NavLink = { - label: t('Contributing', '기여하기', '贡献', 'Участие в проекте', 'コントリビュート', '貢獻', 'Katkıda Bulunma'), + label: t('Contributing', '기여하기', '贡献指南', 'Участие в проекте', 'コントリビュート', '貢獻指南', 'Katkıda Bulunma'), href: `${prefix}contributing/`, }; --- -
      +
      -
      -

      {t('One proxy, the whole surface.', '프록시 하나로 전체 서피스를.', '一个代理,覆盖全部能力。', 'Один прокси — все возможности.', '1 つのプロキシでサーフェス全体を。', '一個代理,覆蓋全部能力。', 'Tek bir proxy, tüm yetenekler.')}

      +

      {t('One proxy, the whole surface.', '프록시 하나로 모든 기능을.', '一个代理,覆盖全部能力。', 'Один прокси — все возможности.', 'プロキシ 1 つで、すべてをカバー。', '一個代理,覆蓋全部能力。', 'Tek bir proxy, tüm yetenekler.')}

      -

      {t('Any provider', '모든 프로바이더', '任意 provider', 'Любой провайдер', '任意のプロバイダー', '任意供應商', 'Dilediğiniz sağlayıcı')}

      +

      {t('Any provider', '어떤 프로바이더든', '任意提供商', 'Любой провайдер', '任意のプロバイダー', '任意供應商', 'Dilediğiniz sağlayıcı')}

      - {t('Five adapters cover Anthropic Messages, Google Gemini, Azure, the OpenAI Responses passthrough, and every OpenAI-compatible Chat Completions endpoint — 40+ built-in providers.', '어댑터 다섯 개가 Anthropic Messages, Google Gemini, Azure, OpenAI Responses passthrough, 그리고 모든 OpenAI 호환 Chat Completions 엔드포인트를 커버합니다 — 내장 프로바이더 40+.', '五个适配器覆盖 Anthropic Messages、Google Gemini、Azure、OpenAI Responses passthrough,以及所有 OpenAI 兼容的 Chat Completions 端点 —— 内置 40+ provider。', 'Пять адаптеров покрывают Anthropic Messages, Google Gemini, Azure, OpenAI Responses passthrough и любую OpenAI-совместимую конечную точку Chat Completions — 40+ встроенных провайдеров.', '5 つのアダプターが Anthropic Messages、Google Gemini、Azure、OpenAI Responses passthrough、そしてすべての OpenAI 互換 Chat Completions エンドポイントをカバーします — 組み込みプロバイダー 40+。', '五個適配器覆蓋 Anthropic Messages、Google Gemini、Azure、OpenAI Responses passthrough,以及所有 OpenAI 相容的 Chat Completions 端點 —— 內建 40+ 供應商。', 'Beş adaptör; Anthropic Messages, Google Gemini, Azure, OpenAI Responses doğrudan geçişi ve tüm OpenAI uyumlu Chat Completions uç noktalarını kapsar — 40+ dahili sağlayıcı.')} + {t('Five adapters cover Anthropic Messages, Google Gemini, Azure, the OpenAI Responses passthrough, and every OpenAI-compatible Chat Completions endpoint — 40+ built-in providers.', '어댑터 5종이 Anthropic Messages, Google Gemini, Azure, OpenAI Responses 패스스루, 그리고 모든 OpenAI 호환 Chat Completions 엔드포인트를 지원합니다. 기본 내장 프로바이더만 40개가 넘습니다.', '五个适配器覆盖 Anthropic Messages、Google Gemini、Azure、OpenAI Responses passthrough,以及所有 OpenAI 兼容的 Chat Completions 端点 —— 内置 40+ 提供商。', 'Пять адаптеров покрывают Anthropic Messages, Google Gemini, Azure, OpenAI Responses passthrough и любую OpenAI-совместимую конечную точку Chat Completions — 40+ встроенных провайдеров.', '5 つのアダプターが Anthropic Messages、Google Gemini、Azure、OpenAI Responses passthrough、そしてすべての OpenAI 互換 Chat Completions エンドポイントをカバーします — 組み込みプロバイダー 40+。', '五個適配器覆蓋 Anthropic Messages、Google Gemini、Azure、OpenAI Responses passthrough,以及所有 OpenAI 相容的 Chat Completions 端點 —— 內建 40+ 供應商。', 'Beş adaptör; Anthropic Messages, Google Gemini, Azure, OpenAI Responses doğrudan geçişi ve tüm OpenAI uyumlu Chat Completions uç noktalarını kapsar — 40+ dahili sağlayıcı.')}

      {t('OAuth or API key', 'OAuth 또는 API 키', 'OAuth 或 API key', 'OAuth или API-ключ', 'OAuth または API キー', 'OAuth 或 API key', 'OAuth veya API anahtarı')}

      -

      {t('Log in with your xAI, Anthropic, or Kimi account — auto-refreshed — forward your ChatGPT login, or paste a key.', 'xAI, Anthropic, Kimi 계정으로 로그인(자동 갱신)하거나, ChatGPT 로그인을 포워딩하거나, 키를 붙여넣으세요.', '使用 xAI、Anthropic 或 Kimi 账号登录(自动刷新),转发 ChatGPT 登录,或粘贴 API key。', 'Войдите через аккаунт xAI, Anthropic или Kimi — с автообновлением, — пробросьте свой вход ChatGPT или просто вставьте ключ.', 'xAI、Anthropic、Kimi アカウントでログイン(自動更新)、ChatGPT ログインを転送、またはキーを貼り付け。', '使用 xAI、Anthropic 或 Kimi 帳號登入(自動重新整理),轉發 ChatGPT 登入,或貼上 API key。', 'xAI, Anthropic veya Kimi hesabınızla giriş yapın (otomatik yenilenir), ChatGPT oturumunuzu yönlendirin veya doğrudan bir API anahtarı yapıştırın.')}

      +

      {t('Log in with your xAI, Anthropic, or Kimi account — auto-refreshed — forward your ChatGPT login, or paste a key.', 'xAI, Anthropic, Kimi 계정으로 로그인하면 토큰이 자동으로 갱신됩니다. ChatGPT 로그인을 그대로 넘기거나 API 키를 붙여넣어도 됩니다.', '使用 xAI、Anthropic 或 Kimi 账号登录(自动刷新),转发 ChatGPT 登录,或粘贴 API key。', 'Войдите через аккаунт xAI, Anthropic или Kimi — с автообновлением, — пробросьте свой вход ChatGPT или просто вставьте ключ.', 'xAI、Anthropic、Kimi アカウントでログイン(自動更新)、ChatGPT ログインを転送、またはキーを貼り付け。', '使用 xAI、Anthropic 或 Kimi 帳號登入(自動重新整理),轉發 ChatGPT 登入,或貼上 API key。', 'xAI, Anthropic veya Kimi hesabınızla giriş yapın (otomatik yenilenir), ChatGPT oturumunuzu yönlendirin veya doğrudan bir API anahtarı yapıştırın.')}

      {t('ChatGPT account pool', 'ChatGPT 계정 풀', 'ChatGPT 账号池', 'Пул аккаунтов ChatGPT', 'ChatGPT アカウントプール', 'ChatGPT 帳號池', 'ChatGPT hesap havuzu')}

      -

      {t('Existing threads keep their account; new sessions auto-route to the lowest-usage healthy one after quota refresh.', '기존 thread는 계정을 유지하고, 새 세션은 할당량 갱신 후 사용량이 가장 낮은 정상 계정으로 자동 라우팅됩니다.', '已有 thread 保持原账号;新会话在刷新额度后自动路由到用量最低的健康账号。', 'Существующие треды сохраняют свой аккаунт; новые сессии после обновления квоты автоматически направляются на наименее загруженный работоспособный аккаунт.', '既存の thread はアカウントを維持し、新しいセッションは quota 更新後に使用量が最も低い健全なアカウントへ自動ルーティングされます。', '已有 thread 保持原帳號;新會話在重新整理額度後自動路由到用量最低的健康帳號。', 'Mevcut iş parçacıkları kendi hesaplarını korur; yeni oturumlar kota yenilenmesinden sonra en az kullanılan sağlıklı hesaba otomatik olarak yönlendirilir.')}

      +

      {t('Existing threads keep their account; new sessions auto-route to the lowest-usage healthy one after quota refresh.', '기존 스레드는 쓰던 계정을 그대로 유지하고, 새 세션은 할당량이 갱신되면 사용량이 가장 적은 정상 계정으로 자동 연결됩니다.', '已有 thread 保持原账号;新会话在刷新额度后自动路由到用量最低的健康账号。', 'Существующие треды сохраняют свой аккаунт; новые сессии после обновления квоты автоматически направляются на наименее загруженный работоспособный аккаунт.', '既存のスレッドはアカウントを維持し、新しいセッションはクォータ更新後に使用量が最も少ない正常なアカウントへ自動ルーティングされます。', '已有 thread 保持原帳號;新會話在重新整理額度後自動路由到用量最低的健康帳號。', 'Mevcut iş parçacıkları kendi hesaplarını korur; yeni oturumlar kota yenilenmesinden sonra en az kullanılan sağlıklı hesaba otomatik olarak yönlendirilir.')}

      -

      {t('Native in the model picker', '모델 선택기에 그대로', '原生出现在模型选择器', 'Нативно в селекторе моделей', 'モデルピッカーにネイティブ表示', '原生出現在模型選擇器', 'Model seçicide yerel olarak')}

      -

      {t('Routed models show up in Codex App with reasoning effort levels, next to the native ones.', '라우팅된 모델이 추론 강도 레벨과 함께 Codex App 선택기에 네이티브 모델과 나란히 표시됩니다.', '路由模型带推理强度等级出现在 Codex App 中,与原生模型并列。', 'Маршрутизированные модели появляются в Codex App с уровнями рассуждений — рядом с нативными.', 'ルーティングされたモデルは推論 effort レベルとともに Codex App のピッカーにネイティブモデルの隣に表示されます。', '路由模型帶推理強度等級出現在 Codex App 中,與原生模型並列。', 'Yönlendirilen modeller, yerel modellerin yanında akıl yürütme seviyeleriyle birlikte Codex App seçicisinde görüntülenir.')}

      - {t('Codex +

      {t('Native in the model picker', '모델 선택기에 기본 모델처럼', '原生显示在模型选择器中', 'Нативно в селекторе моделей', 'モデルピッカーにネイティブ表示', '原生顯示在模型選擇器中', 'Model seçicide yerel olarak')}

      +

      {t('Routed models show up in Codex App with reasoning effort levels, next to the native ones.', '라우팅된 모델도 추론 강도 옵션과 함께 Codex App 모델 선택기에 기본 모델과 나란히 표시됩니다.', '路由模型带推理强度等级出现在 Codex App 中,与原生模型并列。', 'Маршрутизированные модели появляются в Codex App с уровнями рассуждений — рядом с нативными.', 'ルーティングされたモデルも推論 effort レベル付きで、ネイティブモデルと並んで Codex App のピッカーに表示されます。', '路由模型帶推理強度等級出現在 Codex App 中,與原生模型並列。', 'Yönlendirilen modeller, yerel modellerin yanında akıl yürütme seviyeleriyle birlikte Codex App seçicisinde görüntülenir.')}

      + {t('Codex

      {t('Sub-agents', '서브에이전트', '子代理', 'Подагенты', 'サブエージェント', '子代理', 'Alt ajanlar')}

      -

      {t('Pin up to five routed or native models for Codex spawn_agent, and switch the v1 / base / v2 surface globally.', 'Codex spawn_agent용으로 라우팅·네이티브 모델을 최대 5개 고정하고, v1 / base / v2 서피스를 전역으로 전환합니다.', '为 Codex spawn_agent 固定最多五个路由或原生模型,并全局切换 v1 / base / v2 界面。', 'Закрепите до пяти маршрутизированных или нативных моделей для Codex spawn_agent и глобально переключайте интерфейс v1 / base / v2.', 'Codex spawn_agent 用にルーティング済み/ネイティブモデルを最大 5 つ固定し、v1 / base / v2 サーフェスをグローバルに切り替えます。', '為 Codex spawn_agent 固定最多五個路由或原生模型,並全域切換 v1 / base / v2 介面。', 'Codex spawn_agent için en fazla beş yönlendirilmiş veya yerel model sabitleyin ve v1 / base / v2 arayüzünü genel olarak değiştirin.')}

      +

      {t('Pin up to five routed or native models for Codex spawn_agent, and switch the v1 / base / v2 surface globally.', 'Codex spawn_agent에 쓸 라우팅 모델이나 기본 모델을 최대 5개까지 고정하고, v1 / base / v2 서피스를 한 번에 전환합니다.', '为 Codex spawn_agent 固定最多五个路由或原生模型,并全局切换 v1 / base / v2 界面。', 'Закрепите до пяти маршрутизированных или нативных моделей для Codex spawn_agent и глобально переключайте интерфейс v1 / base / v2.', 'Codex spawn_agent 用にルーティング済み/ネイティブモデルを最大 5 つ固定し、v1 / base / v2 サーフェスをグローバルに切り替えます。', '為 Codex spawn_agent 固定最多五個路由或原生模型,並全域切換 v1 / base / v2 介面。', 'Codex spawn_agent için en fazla beş yönlendirilmiş veya yerel model sabitleyin ve v1 / base / v2 arayüzünü genel olarak değiştirin.')}

      Claude Code

      -

      {t('ocx claude launches Claude Code against the same port — every routed model in the /model picker, auto-context up to 1M, roster sub-agents, and your claude.ai login stays active.', 'ocx claude가 같은 포트로 Claude Code를 띄웁니다 — 라우팅된 모든 모델이 /model 선택기에 뜨고, 최대 1M auto-context, 로스터 서브에이전트, claude.ai 로그인은 그대로 유지됩니다.', 'ocx claude 让 Claude Code 连接同一端口 —— 所有路由模型出现在 /model 选择器中,auto-context 最高 1M,roster 子代理,claude.ai 登录保持不变。', 'ocx claude запускает Claude Code на том же порту — все маршрутизированные модели в селекторе /model, auto-context до 1M, подагенты из ростера, а ваш вход в claude.ai остаётся активным.', 'ocx claude が同じポートで Claude Code を起動します — ルーティングされたすべてのモデルが /model ピッカーに表示され、最大 1M の auto-context、ロスターのサブエージェント、claude.ai ログインはそのまま維持されます。', 'ocx claude 讓 Claude Code 連線同一連接埠 —— 所有路由模型出現在 /model 選擇器中,auto-context 最高 1M,roster 子代理,claude.ai 登入保持不變。', 'ocx claude, Claude Code’u aynı port üzerinden başlatır — /model seçicisindeki tüm yönlendirilmiş modeller, 1M’a kadar otomatik bağlam, alt ajanlar ve claude.ai oturumunuz aktif kalır.')}

      +

      {t('ocx claude launches Claude Code against the same port — every routed model in the /model picker, auto-context up to 1M, roster sub-agents, and your claude.ai login stays active.', 'ocx claude로 같은 포트에서 Claude Code를 실행합니다. 라우팅된 모든 모델이 /model 선택기에 나타나고, 최대 1M 자동 컨텍스트와 로스터 서브에이전트를 쓸 수 있으며, claude.ai 로그인도 그대로 유지됩니다.', 'ocx claude 让 Claude Code 连接同一端口 —— 所有路由模型出现在 /model 选择器中,auto-context 最高 1M,roster 子代理,claude.ai 登录保持不变。', 'ocx claude запускает Claude Code на том же порту — все маршрутизированные модели в селекторе /model, auto-context до 1M, подагенты из ростера, а ваш вход в claude.ai остаётся активным.', 'ocx claude が同じポートで Claude Code を起動します — ルーティングされたすべてのモデルが /model ピッカーに表示され、最大 1M の auto-context、ロスターのサブエージェント、claude.ai ログインはそのまま維持されます。', 'ocx claude 讓 Claude Code 連線同一連接埠 —— 所有路由模型出現在 /model 選擇器中,auto-context 最高 1M,roster 子代理,claude.ai 登入保持不變。', 'ocx claude, Claude Code’u aynı port üzerinden başlatır — /model seçicisindeki tüm yönlendirilmiş modeller, 1M’a kadar otomatik bağlam, alt ajanlar ve claude.ai oturumunuz aktif kalır.')}

      {t('Claude

      {t('Search & vision sidecars', '검색 & 비전 사이드카', '搜索与视觉边车', 'Сайдкары поиска и зрения', '検索 & ビジョンサイドカー', '搜尋與視覺邊車', 'Arama & görme sidecar’ları')}

      -

      {t('Give non-OpenAI models real web search and image understanding through a gpt-5.6-luna sidecar.', 'gpt-5.6-luna 사이드카로 비 OpenAI 모델에 실제 웹 검색과 이미지 이해를 붙입니다.', '通过 gpt-5.6-luna 边车,让非 OpenAI 模型获得真实的网页搜索与图像理解能力。', 'Дайте моделям не от OpenAI настоящий веб-поиск и понимание изображений через сайдкар gpt-5.6-luna.', 'gpt-5.6-luna サイドカーで非 OpenAI モデルに本物のウェブ検索と画像理解を提供します。', '透過 gpt-5.6-luna 邊車,讓非 OpenAI 模型獲得真實的網頁搜尋與圖像理解能力。', 'gpt-5.6-luna sidecar’ı sayesinde OpenAI harici modellere gerçek web araması ve görsel anlama yeteneği kazandırın.')}

      +

      {t('Give non-OpenAI models real web search and image understanding through a gpt-5.6-luna sidecar.', 'gpt-5.6-luna 사이드카를 붙여 OpenAI 외 모델에서도 실제 웹 검색과 이미지 인식을 쓸 수 있습니다.', '通过 gpt-5.6-luna 边车,让非 OpenAI 模型获得真实的网页搜索与图像理解能力。', 'Дайте моделям не от OpenAI настоящий веб-поиск и понимание изображений через сайдкар gpt-5.6-luna.', 'gpt-5.6-luna サイドカーで非 OpenAI モデルに本格的なウェブ検索と画像理解を提供します。', '透過 gpt-5.6-luna 邊車,讓非 OpenAI 模型獲得真實的網頁搜尋與圖像理解能力。', 'gpt-5.6-luna sidecar’ı sayesinde OpenAI harici modellere gerçek web araması ve görsel anlama yeteneği kazandırın.')}

      -

      {t('Quickstart', '퀵스타트', '快速开始', 'Быстрый старт', 'クイックスタート', '快速入門', 'Hızlı Başlangıç')}

      -

      {t('ocx init writes a provider into your Codex config and shares one model catalog with Codex CLI, TUI, App, and SDK. ocx stop restores native Codex cleanly.', 'ocx init이 Codex 설정에 프로바이더를 기록하고 CLI, TUI, App, SDK가 같은 모델 카탈로그를 공유합니다. ocx stop이면 네이티브 Codex로 깔끔하게 복원됩니다.', 'ocx init 将 provider 写入 Codex 配置,CLI、TUI、App 与 SDK 共享同一模型目录。ocx stop 可干净地恢复原生 Codex。', 'ocx init записывает провайдера в конфигурацию Codex, а Codex CLI, TUI, App и SDK используют общий каталог моделей. ocx stop чисто восстанавливает нативный Codex.', 'ocx init が Codex 設定にプロバイダーを書き込み、CLI、TUI、App、SDK と同じモデルカタログを共有します。ocx stop でネイティブ Codex に綺麗に復元します。', 'ocx init 將供應商寫入 Codex 設定,CLI、TUI、App 與 SDK 共享同一模型目錄。ocx stop 可乾淨地恢復原生 Codex。', 'ocx init, Codex yapılandırmanıza bir sağlayıcı yazar; Codex CLI, TUI, App ve SDK aynı model kataloğunu paylaşır. ocx stop ile yerel Codex’e temiz bir şekilde geri dönebilirsiniz.')}

      +

      {t('Quickstart', '빠른 시작', '快速开始', 'Быстрый старт', 'クイックスタート', '快速入門', 'Hızlı Başlangıç')}

      +

      {t('ocx init writes a provider into your Codex config and shares one model catalog with Codex CLI, TUI, App, and SDK. ocx stop restores native Codex cleanly.', 'ocx init이 Codex 설정에 프로바이더를 추가하고, Codex CLI·TUI·App·SDK가 하나의 모델 카탈로그를 함께 씁니다. ocx stop을 실행하면 원래 Codex로 깔끔하게 돌아갑니다.', 'ocx init 将 provider 写入 Codex 配置,CLI、TUI、App 与 SDK 共享同一模型目录。ocx stop 可干净地恢复原生 Codex。', 'ocx init записывает провайдера в конфигурацию Codex, а Codex CLI, TUI, App и SDK используют общий каталог моделей. ocx stop чисто восстанавливает нативный Codex.', 'ocx init が Codex 設定にプロバイダーを書き込み、Codex CLI・TUI・App・SDK で 1 つのモデルカタログを共有します。ocx stop でネイティブの Codex にクリーンに戻せます。', 'ocx init 將供應商寫入 Codex 設定,CLI、TUI、App 與 SDK 共享同一模型目錄。ocx stop 可乾淨地恢復原生 Codex。', 'ocx init, Codex yapılandırmanıza bir sağlayıcı yazar; Codex CLI, TUI, App ve SDK aynı model kataloğunu paylaşır. ocx stop ile yerel Codex’e temiz bir şekilde geri dönebilirsiniz.')}

      zsh
      {quickstart.map((line) => ($ {line.cmd}  # {line.note}{'\n'}))}
      @@ -425,6 +443,11 @@ const docsMap = [
      -
      +

      {t('Explore the docs', '문서 살펴보기', '浏览文档', 'Изучите документацию', 'ドキュメントを探る', '瀏覽文件', 'Dokümantasyonu Keşfedin')}

      {docsMap.map((group) => ( @@ -453,8 +476,8 @@ const docsMap = [

      {t( 'opencodex is an independent community project, not affiliated with or endorsed by OpenAI, Anthropic, or any other provider. Some providers may restrict accounts that route traffic through third-party proxies — review each provider\u2019s Terms of Service before connecting.', - 'opencodex는 독립 커뮤니티 프로젝트이며 OpenAI, Anthropic 등 어떤 프로바이더와도 제휴하거나 보증받지 않습니다. 일부 프로바이더는 서드파티 프록시 경유 트래픽 계정을 제한할 수 있으니 연결 전 각 프로바이더의 이용약관을 확인하세요.', - 'opencodex 是独立的社区项目,与 OpenAI、Anthropic 或任何其他 provider 均无关联或背书。部分 provider 可能限制经第三方代理路由流量的账号 —— 连接前请查阅各 provider 的服务条款。', + 'opencodex는 독립 커뮤니티 프로젝트로, OpenAI, Anthropic 등 어떤 프로바이더와도 제휴 관계가 없고 보증을 받지 않습니다. 일부 프로바이더는 서드파티 프록시를 거친 트래픽이 있는 계정을 제한할 수 있으니, 연결하기 전에 각 프로바이더의 이용약관을 확인하세요.', + 'opencodex 是独立的社区项目,与 OpenAI、Anthropic 或任何其他提供商均无关联或背书。部分提供商可能限制经第三方代理路由流量的账号 —— 连接前请查阅各提供商的服务条款。', 'opencodex — независимый проект сообщества, никак не связанный с OpenAI, Anthropic или любым другим провайдером и не одобренный ими. Некоторые провайдеры могут ограничивать аккаунты, направляющие трафик через сторонние прокси, — перед подключением ознакомьтесь с условиями обслуживания каждого провайдера.', 'opencodex は独立したコミュニティプロジェクトであり、OpenAI、Anthropic などいかなるプロバイダーとも提携・推奨されるものではありません。一部のプロバイダーはサードパーティプロキシ経由のトラフィックを使用するアカウントを制限する可能性があります — 接続前に各プロバイダーの利用規約を確認してください。', 'opencodex 是獨立的社群專案,與 OpenAI、Anthropic 或任何其他供應商均無關聯或背書。部分供應商可能限制經第三方代理路由流量的帳號 —— 連線前請查閱各供應商的服務條款。', @@ -463,16 +486,289 @@ const docsMap = [

      + + diff --git a/docs-site/src/components/SiteJsonLd.astro b/docs-site/src/components/SiteJsonLd.astro index 18e2403d9b..d84049e2f1 100644 --- a/docs-site/src/components/SiteJsonLd.astro +++ b/docs-site/src/components/SiteJsonLd.astro @@ -22,14 +22,14 @@ const homeUrl = locale ? `${SITE_URL}/${locale}/` : `${SITE_URL}/`; const inLanguage = locale ? langs[locale] : 'en'; const descriptions = { - en: 'Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI, App, SDK, and Claude Code.', - fr: 'Proxy universel de fournisseurs pour OpenAI Codex et Claude Code — utilisez n’importe quel LLM avec Codex CLI, App, SDK et Claude Code.', - ko: 'OpenAI Codex & Claude Code를 위한 범용 프로바이더 프록시 — Codex CLI, App, SDK와 Claude Code에서 어떤 LLM이든 사용하세요.', - 'zh-CN': '面向 OpenAI Codex 与 Claude Code 的通用 provider 代理 —— 在 Codex CLI、App、SDK 和 Claude Code 中使用任意 LLM。', - 'zh-TW': '適用於 OpenAI Codex 與 Claude Code 的通用 provider 代理 —— 在 Codex CLI、App、SDK 和 Claude Code 中使用任意 LLM。', - ru: 'Универсальный прокси провайдеров для OpenAI Codex и Claude Code — используйте любую LLM с Codex CLI, App, SDK и Claude Code.', - ja: 'OpenAI Codex & Claude Code 向けの汎用プロバイダープロキシ — Codex CLI、App、SDK と Claude Code で任意の LLM を使えます。', - tr: 'OpenAI Codex ve Claude Code için evrensel sağlayıcı proxy’si — Codex CLI, App, SDK ve Claude Code ile dilediğiniz LLM’i kullanın.', + en: 'One local gateway for your AI coding tools and models: use the providers you choose with Codex, Claude Code, Claude Desktop and Grok Build, and connect more tools through managed configs.', + fr: 'Une passerelle locale unique pour vos outils de code IA et vos modèles : utilisez les fournisseurs de votre choix avec Codex, Claude Code, Claude Desktop et Grok Build, et connectez d’autres outils via des configurations gérées.', + ko: 'AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨이: Codex, Claude Code, Claude Desktop, Grok Build에서 원하는 프로바이더를 쓰고, 관리형 설정으로 더 많은 도구를 연결하세요.', + 'zh-CN': '一个本地网关,连接你的 AI 编程工具与模型:在 Codex、Claude Code、Claude Desktop 和 Grok Build 中使用你选择的提供商,并通过托管配置连接更多工具。', + 'zh-TW': '一個本機閘道,連接你的 AI 程式開發工具與模型:在 Codex、Claude Code、Claude Desktop 和 Grok Build 中使用你選擇的供應商,並透過代管設定連接更多工具。', + ru: 'Единый локальный шлюз для ваших ИИ-инструментов для кода и моделей: используйте выбранных провайдеров в Codex, Claude Code, Claude Desktop и Grok Build и подключайте другие инструменты через управляемые конфигурации.', + ja: 'AI コーディングツールとモデルをつなぐ 1 つのローカルゲートウェイ。Codex、Claude Code、Claude Desktop、Grok Build で好きなプロバイダーを使い、管理された設定でほかのツールも接続できます。', + tr: 'Yapay zekâ kodlama araçlarınız ve modelleriniz için tek bir yerel ağ geçidi: Codex, Claude Code, Claude Desktop ve Grok Build ile seçtiğiniz sağlayıcıları kullanın, diğer araçları yönetilen yapılandırmalarla bağlayın.', } as const; type GraphNode = Record; @@ -59,14 +59,15 @@ if (!locale) { name: 'opencodex', alternateName: 'ocx', description: - 'Local LLM proxy that lets OpenAI Codex (CLI, App, SDK) and Claude Code run on any model — Claude, Gemini, Grok, DeepSeek, Kimi, Qwen, Ollama, OpenRouter, and more — with streaming, tool calls, reasoning tokens, and images working in both directions.', + 'Local gateway that connects AI coding tools — OpenAI Codex (CLI, App, SDK), Claude Code, Claude Desktop, Grok Build and tools with managed configs — to the model providers you choose: Claude, Gemini, Grok, DeepSeek, Kimi, Qwen, Ollama, OpenRouter, and more, with streaming, tool calls, reasoning tokens, and images where the client, model and provider support them.', keywords: - 'codex, claude code, openai codex proxy, claude code proxy, llm proxy, ai gateway, anthropic, gemini, grok, deepseek, ollama, openrouter, responses api, codex cli', + 'codex, claude code, claude desktop, grok build, ai coding tools gateway, openai codex proxy, claude code proxy, llm proxy, ai gateway, anthropic, gemini, grok, deepseek, ollama, openrouter, responses api, codex cli', featureList: [ - 'Run Codex CLI/App/SDK on any LLM provider', - 'Run Claude Code on any LLM via the Anthropic Messages API', + 'Connect Codex CLI/App/SDK, Claude Code, Claude Desktop and Grok Build to the providers you choose', + 'Managed config integrations for OpenCode, Pi, Qoder, WorkBuddy, Kilo, Cline, T3 Code and more', + 'Accepts the Responses, Chat Completions and Anthropic Messages APIs', 'ChatGPT account pool with quota-aware routing', - 'Streaming, tool calls, reasoning tokens, and vision in both directions', + 'Streaming, tool calls, reasoning tokens, and vision where the client, model and provider support them', 'Web dashboard on localhost:10100', ], applicationCategory: 'DeveloperApplication', diff --git a/docs-site/src/components/TelemetryDashboard.astro b/docs-site/src/components/TelemetryDashboard.astro new file mode 100644 index 0000000000..f0f52ebb95 --- /dev/null +++ b/docs-site/src/components/TelemetryDashboard.astro @@ -0,0 +1,1521 @@ +--- +import { + getTelemetryDashboardCopy, + resolveTelemetryDashboardLocale, + TELEMETRY_DASHBOARD_STRINGS, + type TelemetryDashboardLocale, +} from "../data/telemetry-dashboard-i18n"; +import { + DEFAULT_TELEMETRY_RANGE, + GITHUB_RELEASES_URL, + GITHUB_REPO_SLUG, + NPM_DOWNLOADS_MONTHLY_URL, + NPM_DOWNLOADS_WEEKLY_URL, + NPM_DOWNLOADS_YEARLY_URL, + NPM_PACKAGE_NAME, + OUTCOME_COLORS, + TELEMETRY_GUIDE_PATH, + TELEMETRY_RANGES, + TELEMETRY_STATS_ENDPOINT, + TOKEN_MIX_COLORS, + TOKSCALE_REPO_URL, + getLocalizedWeekdayLabels, +} from "./telemetry-dashboard/index"; + +interface Props { + locale?: TelemetryDashboardLocale; +} + +const routeLocale = Astro.locals?.starlightRoute?.locale; +const locale = resolveTelemetryDashboardLocale(Astro.props.locale ?? routeLocale); +const copy = getTelemetryDashboardCopy(locale); + +const base = import.meta.env.BASE_URL.replace(/\/?$/, "/"); +const prefix = locale === "en" ? base : `${base}${locale}/`; + +const showGuideLink = + Object.keys(import.meta.glob("../content/docs/guides/telemetry.{md,mdx}")).length > 0; +const guideHref = `${prefix}${TELEMETRY_GUIDE_PATH}`; +const weekdayLabels = getLocalizedWeekdayLabels(locale); + +const rangeLabels: Record<(typeof TELEMETRY_RANGES)[number], string> = { + "7d": copy.range7d, + "30d": copy.range30d, + "90d": copy.range90d, + "365d": copy.range365d, +}; + +const kpiCards = [ + { id: "activeInstalls", label: copy.kpiActiveInstalls, initial: "0", title: "0 (0 install-days)" }, + { id: "newInstalls", label: copy.kpiNewInstalls, initial: "0", title: "0" }, + { id: "requests", label: copy.kpiRequests, initial: "0", title: "0" }, + { id: "tokens", label: copy.kpiTokens, initial: "0", title: "0" }, + { id: "activeHours", label: copy.kpiActiveHours, initial: "0h", title: "0h (0 min)" }, +] as const; + +const tokenBuckets = [ + { id: "input", label: copy.tokenInput, color: TOKEN_MIX_COLORS.input }, + { id: "cacheRead", label: copy.tokenCacheRead, color: TOKEN_MIX_COLORS.cacheRead }, + { id: "cacheWrite", label: copy.tokenCacheWrite, color: TOKEN_MIX_COLORS.cacheWrite }, + { id: "output", label: copy.tokenOutput, color: TOKEN_MIX_COLORS.output }, + { id: "reasoning", label: copy.tokenReasoning, color: TOKEN_MIX_COLORS.reasoning }, +] as const; + +const outcomeItems = [ + { id: "completed", label: copy.outcomeCompleted, color: OUTCOME_COLORS.completed }, + { id: "incomplete", label: copy.outcomeIncomplete, color: OUTCOME_COLORS.incomplete }, + { id: "aborted", label: copy.outcomeAborted, color: OUTCOME_COLORS.aborted }, + { id: "failed", label: copy.outcomeFailed, color: OUTCOME_COLORS.failed }, +] as const; + +const skeletonCells = Array.from({ length: 53 * 7 }, (_, idx) => idx); +--- + +
      + +
      +
      +
      +
      +

      {copy.title}

      + {copy.privacyBadge} + {copy.selfReportedLabel} +
      +

      {copy.subtitle}

      +
      + + {copy.updatedPrefix}: {copy.updatedPending} + + + GET /v1/stats + + + {copy.stateLoadingTitle} + {copy.stateLoadingBody} + +
      +
      + +
      +
      + {TELEMETRY_RANGES.map((range) => ( + + ))} +
      +
      +
      + +
      + + +
      + + + +
      + + +
      + {kpiCards.map((card) => ( +
      +
      {card.label}
      +
      + {card.initial} +
      +
      + ))} +
      +
      + + +
      +
      +
      +

      + {copy.tokenMixTitle} +

      +

      {copy.tokenMixSubtitle}

      +
      +
      + {copy.kpiTokens} + + 0 + +
      +
      +
      + + +
      + {tokenBuckets.map((bucket) => ( +
      +
      +
      +
      + 0 + 0.0% +
      +
      + ))} +
      +
      +
      + + +
      + +
      +
      +
      +

      + {copy.heatmapTitle} +

      +

      {copy.heatmapSubtitle}

      +
      +
      + + {copy.heatmapActiveDays.replace("{count}", "0")} + + +
      +
      + +
      +
      + +
      + +
      + {skeletonCells.map(() => ( +
      +
      +
      + + + +
      + + 365d UTC + +
      + {copy.heatmapLess} +
      + {([0, 1, 2, 3, 4] as const).map((grade) => ( +
      + {copy.heatmapMore} +
      +
      +

      + {copy.heatmapKeyboardHint} +

      +
      +
      + + +
      +
      +
      +

      + {copy.dailyChartTitle} +

      +

      {copy.dailyChartSubtitle}

      +
      +
      + + +
      +
      +
      + + + + + + + + + + + + + + + +
      {copy.dailyChartTitle}
      UTC{copy.colProvider}{copy.metricTokens}
      {copy.noDataInTable}
      +
      +
      +
      + + +
      +
      +
      +
      +

      + {copy.providersTitle} +

      +

      {copy.providersSubtitle}

      +
      +
      +
      + + + + + + + + + + + + + + +
      {copy.colProvider}{copy.colRequests}{copy.colTokens}{copy.colShare}
      {copy.noDataInTable}
      +
      +
      + +
      +
      +
      +

      + {copy.modelsTitle} +

      +

      {copy.modelsSubtitle}

      +
      +
      +
      + + + + + + + + + + + + + + +
      {copy.colModel}{copy.colRequests}{copy.colTokens}{copy.colShare}
      {copy.noDataInTable}
      +
      +
      +
      + + +
      +
      +
      +
      +

      + {copy.versionsTitle} +

      +

      {copy.versionsSubtitle}

      +
      +
      +
      + + + + + + + + + + + + + + +
      {copy.colVersion}{copy.colInstalls}{copy.colNewInstalls}{copy.colInstallShare}
      {copy.noDataInTable}
      +
      +
      + +
      +
      +
      +

      + {copy.platformsTitle} +

      +

      {copy.platformsSubtitle}

      +
      +
      +
      + + + + + + + + + + + + + +
      {copy.colPlatform}{copy.colInstalls}{copy.colInstallShare}
      {copy.noDataInTable}
      +
      +
      + +
      +
      +
      +

      + {copy.channelsTitle} +

      +

      {copy.channelsSubtitle}

      +
      +
      +
      + + + + + + + + + + + + + + +
      {copy.colChannel}{copy.colInstalls}{copy.colNewInstalls}{copy.colInstallShare}
      {copy.noDataInTable}
      +
      +
      +
      + + +
      +
      +
      +
      +

      + {copy.reliabilityTitle} +

      +

      {copy.reliabilitySubtitle}

      +
      +
      + {copy.completionRateLabel} + + 0.0% + +
      +
      + +
      + + +
      + {outcomeItems.map((item) => ( +
      +
      +
      +
      + 0 + 0.0% +
      +
      + ))} +
      + +

      {copy.topErrorsTitle}

      +
      + + + + + + + + + + + + + +
      {copy.colErrorCause}{copy.colErrorCount}{copy.colInstallShare}
      {copy.noErrorsRecorded}
      +
      +
      +
      + +
      +
      +
      +

      + {copy.downloadsTitle} +

      +

      {copy.downloadsSubtitle}

      +
      +
      + +
      +
      +
      +
      {copy.npmWeeklyLabel}
      +
      + — +
      + {NPM_PACKAGE_NAME} +
      +
      +
      {copy.npmMonthlyLabel}
      +
      + — +
      + {NPM_PACKAGE_NAME} +
      +
      +
      {copy.npmYearlyLabel}
      +
      + — +
      + {NPM_PACKAGE_NAME} +
      +
      +
      {copy.githubTotalLabel}
      +
      + — +
      + {GITHUB_REPO_SLUG} +
      +
      +
      + {copy.githubLatestLabel}{" "} + +
      +
      + — +
      + +
      +
      +
      +
      +
      + + + +
      + + + + diff --git a/docs-site/src/components/TelemetryLeaderboard.astro b/docs-site/src/components/TelemetryLeaderboard.astro new file mode 100644 index 0000000000..5285e1b8d7 --- /dev/null +++ b/docs-site/src/components/TelemetryLeaderboard.astro @@ -0,0 +1,188 @@ +--- +import { + TELEMETRY_LEADERBOARD_STRINGS, + resolveTelemetryLeaderboardLocale, + type TelemetryLeaderboardLocale, +} from "../data/telemetry-leaderboard-i18n"; +import { + TELEMETRY_LEADERBOARD_ENDPOINT, + TELEMETRY_PROFILE_BY_HANDLE_ENDPOINT, +} from "./telemetry-dashboard/leaderboard"; + +interface Props { + locale?: TelemetryLeaderboardLocale; +} + +const routeLocale = Astro.locals?.starlightRoute?.locale; +const locale = resolveTelemetryLeaderboardLocale(Astro.props.locale ?? routeLocale); +const copy = TELEMETRY_LEADERBOARD_STRINGS[locale]; +const periods = [ + { id: "day", label: copy.periodDay }, + { id: "week", label: copy.periodWeek }, + { id: "month", label: copy.periodMonth }, +] as const; +const metrics = [ + { id: "tokens", label: copy.metricTokens }, + { id: "requests", label: copy.metricRequests }, +] as const; +--- + +
      +
      +
      +
      +

      {copy.title}

      +

      {copy.subtitle}

      +
      +
      +
      + {periods.map(p => )} +
      +
      + {metrics.map(m => )} +
      +
      +
      + + + +
      + + + + + + + + + + +
      {copy.colRank}{copy.colProfile}{copy.colTokens}{copy.colRequests}
      +

      {copy.loading}

      + +
      + +
      +
      + +
      + + +
      + +
      +

      {copy.howToJoin}

      +
      +
      +
      + + + + + diff --git a/docs-site/src/components/telemetry-dashboard/client.ts b/docs-site/src/components/telemetry-dashboard/client.ts new file mode 100644 index 0000000000..b7a3835be8 --- /dev/null +++ b/docs-site/src/components/telemetry-dashboard/client.ts @@ -0,0 +1,707 @@ +import type * as Echarts from "echarts"; + +type EchartsModule = typeof import("echarts"); +let echartsLoad: Promise | null = null; +// Loaded on first chart render: keeps ECharts out of the initial page script and lets +// helpers in this module be imported where the docs-site dependencies are not installed. +function loadEcharts(): Promise { + return (echartsLoad ??= import("echarts")); +} +import type { TelemetryDashboardCopy } from "../../data/telemetry-dashboard-i18n"; +import { + DEFAULT_STATS_REQUEST_TIMEOUT_MS, + buildChannelRows, + buildDailyChartAccessibleTable, + buildDailyProviderChart, + buildHeatmapCalendar, + buildKpiStrip, + buildModelShareRows, + buildPlatformRows, + buildProviderShareRows, + buildReliabilitySummary, + buildStatsUrl, + buildTokenMix, + buildVersionRows, + classifyStatsResponse, + createEmptyStatsSnapshot, + createStatsRequestSequencer, + fetchGithubReleasesPages, + fetchJsonWithTimeout, + formatCompactNumber, + formatExactNumber, + formatGeneratedTimestamp, + formatHeatmapCellAriaLabel, + navigateHeatmapDate, + parseDownloadsPayload, + parseStatsRangeParam, + type DailyChartMetric, + type HeatmapCell, + type HeatmapNavigationKey, + type TelemetryStatsRange, + type TelemetryStatsV1, +} from "./index"; + +export function mountTelemetryDashboard( + root: HTMLElement | null = document.querySelector("[data-telemetry-dashboard]"), +): void { + if (!root) return; + + const locale = root.dataset.locale ?? "en"; + const statsEndpoint = + root.dataset.statsEndpoint ?? "https://telemetry.opencodex.me/v1/stats"; + const copy = JSON.parse(root.dataset.copy ?? "{}") as TelemetryDashboardCopy; + + let activeRange: TelemetryStatsRange = parseStatsRangeParam( + new URLSearchParams(window.location.search).get("range") ?? + root.dataset.defaultRange, + ); + let activeChartMetric: DailyChartMetric = "tokens"; + let latestStats: TelemetryStatsV1 | null = null; + let chartInstance: Echarts.ECharts | null = null; + let currentHeatmapCells: HeatmapCell[] = []; + let focusedHeatmapDate: string | null = null; + const statsSequencer = createStatsRequestSequencer(DEFAULT_STATS_REQUEST_TIMEOUT_MS); + + const setDashboardState = ( + state: "loading" | "ready" | "empty" | "error", + detail?: string, + ) => { + root.dataset.dashboardState = state; + for (const panel of root.querySelectorAll("[data-state-panel]")) { + panel.hidden = panel.dataset.statePanel !== state; + } + if (state === "error" && detail) { + const errBody = root.querySelector("[data-error-body]"); + if (errBody) { + errBody.textContent = `${copy.stateErrorBody} (${detail})`; + } + } + }; + + const syncRangePills = () => { + for (const btn of root.querySelectorAll("[data-range-pill]")) { + const isCurrent = btn.dataset.rangePill === activeRange; + btn.setAttribute("aria-pressed", isCurrent ? "true" : "false"); + } + }; + + const syncChartMetricPills = () => { + for (const btn of root.querySelectorAll("[data-chart-metric]")) { + const isCurrent = btn.dataset.chartMetric === activeChartMetric; + btn.setAttribute("aria-pressed", isCurrent ? "true" : "false"); + } + }; + + const renderDailyChart = () => { + const chartEl = root.querySelector("[data-daily-chart]"); + if (!chartEl) return; + const textColor = getComputedStyle(document.body).color; + const borderColor = + getComputedStyle(document.documentElement) + .getPropertyValue("--sl-color-gray-5") + .trim() || "rgba(128,128,128,0.25)"; + + const model = buildDailyProviderChart( + latestStats?.dailyByProvider, + latestStats?.daily, + activeChartMetric, + ); + const metricLabel = + activeChartMetric === "requests" ? copy.metricRequests : copy.metricTokens; + chartEl.setAttribute( + "aria-label", + `${copy.dailyChartTitle} (${metricLabel}): ${formatCompactNumber(model.total)}`, + ); + + const metricHeaderEl = root.querySelector( + "[data-daily-chart-metric-col]", + ); + if (metricHeaderEl) { + metricHeaderEl.textContent = metricLabel; + } + const chartTbody = root.querySelector( + "[data-daily-chart-tbody]", + ); + if (chartTbody) { + const srRows = buildDailyChartAccessibleTable(model, locale); + if (srRows.length === 0) { + chartTbody.replaceChildren(makeEmptyRow(3, copy.noDataInTable)); + } else { + chartTbody.replaceChildren( + ...srRows.map((row) => { + const tr = document.createElement("tr"); + const tdDay = document.createElement("td"); + tdDay.textContent = row.day; + const tdProv = document.createElement("td"); + tdProv.textContent = row.providerKind; + const tdVal = document.createElement("td"); + tdVal.textContent = `${row.valueExact} (${row.valueCompact})`; + tr.append(tdDay, tdProv, tdVal); + return tr; + }), + ); + } + } + + const applyChart = (echarts: EchartsModule) => { + if (!chartInstance) { + chartInstance = echarts.init(chartEl); + } + chartInstance.setOption( + { + textStyle: { color: textColor }, + tooltip: { + trigger: "axis", + axisPointer: { type: "shadow" }, + }, + legend: { + top: 0, + textStyle: { color: textColor, fontSize: 11 }, + }, + grid: { left: 52, right: 16, top: 34, bottom: 28 }, + xAxis: { + type: "category", + data: model.days, + axisLabel: { color: textColor, fontSize: 11 }, + axisLine: { lineStyle: { color: borderColor } }, + }, + yAxis: { + type: "value", + axisLabel: { + color: textColor, + fontSize: 11, + formatter: (val: number) => formatCompactNumber(val), + }, + splitLine: { lineStyle: { color: borderColor } }, + }, + series: model.series.map((s) => ({ + name: s.providerKind, + type: "bar", + stack: "daily", + itemStyle: { color: s.color }, + emphasis: { focus: "series" }, + data: s.values, + })), + }, + { notMerge: true }, + ); + }; + void loadEcharts().then(applyChart).catch(() => { + chartEl.dataset.chartUnavailable = "true"; + }); + }; + + const renderHeatmap = (stats: TelemetryStatsV1 | null) => { + const gridEl = root.querySelector("[data-heatmap-grid]"); + const monthsEl = root.querySelector("[data-heatmap-months]"); + const activeDaysEl = root.querySelector("[data-heatmap-active-days]"); + const peakEl = root.querySelector("[data-heatmap-peak]"); + const rangeLabelEl = root.querySelector("[data-heatmap-range-label]"); + const tooltipEl = root.querySelector("[data-heatmap-tooltip]"); + if (!gridEl || !monthsEl) return; + + const calendar = buildHeatmapCalendar(stats?.heatmap, locale); + currentHeatmapCells = calendar.cells; + + if (activeDaysEl) { + activeDaysEl.textContent = copy.heatmapActiveDays.replace( + "{count}", + formatExactNumber(calendar.activeDays, locale), + ); + } + if (peakEl) { + if (calendar.peakDay) { + peakEl.hidden = false; + peakEl.textContent = copy.heatmapPeakDay + .replace("{date}", calendar.peakDay.date) + .replace("{count}", formatExactNumber(calendar.peakDay.activeInstalls, locale)); + } else { + peakEl.hidden = true; + } + } + if (rangeLabelEl && calendar.startDate && calendar.endDate) { + rangeLabelEl.textContent = `${calendar.startDate} → ${calendar.endDate} (UTC)`; + } + + if (calendar.weekCount === 0) { + focusedHeatmapDate = null; + if (peakEl) { + peakEl.hidden = true; + peakEl.textContent = ""; + } + if (rangeLabelEl) { + rangeLabelEl.textContent = "365d UTC"; + } + gridEl.style.setProperty("--heatmap-weeks", "53"); + monthsEl.style.setProperty("--heatmap-weeks", "53"); + monthsEl.replaceChildren(); + const emptyButtons = Array.from({ length: 53 * 7 }, () => { + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "td-heatmap-cell"; + btn.dataset.grade = "0"; + btn.disabled = true; + btn.tabIndex = -1; + btn.setAttribute("aria-hidden", "true"); + return btn; + }); + gridEl.replaceChildren(...emptyButtons); + if (tooltipEl) { + tooltipEl.dataset.active = "false"; + tooltipEl.setAttribute("aria-hidden", "true"); + tooltipEl.textContent = "\u00a0"; + } + return; + } + + const weeks = String(calendar.weekCount); + gridEl.style.setProperty("--heatmap-weeks", weeks); + monthsEl.style.setProperty("--heatmap-weeks", weeks); + + monthsEl.replaceChildren( + ...calendar.monthMarkers.map((m) => { + const span = document.createElement("span"); + span.style.gridColumnStart = String(m.weekIndex + 1); + span.textContent = m.label; + return span; + }), + ); + + const selectableCells = calendar.cells.filter((c) => c.selectable); + focusedHeatmapDate = + selectableCells[selectableCells.length - 1]?.date ?? null; + + const showCellTooltip = (cell: HeatmapCell) => { + if (!tooltipEl || !cell.selectable) return; + tooltipEl.dataset.active = "true"; + tooltipEl.setAttribute("aria-hidden", "false"); + tooltipEl.textContent = `${cell.date} · ${formatExactNumber(cell.activeInstalls, locale)} ${copy.heatmapTooltipUnit}`; + }; + + const hideCellTooltip = () => { + if (!tooltipEl) return; + tooltipEl.dataset.active = "false"; + tooltipEl.setAttribute("aria-hidden", "true"); + }; + + const buttons = calendar.cells.map((cell) => { + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "td-heatmap-cell"; + btn.dataset.grade = String(cell.grade); + if (cell.selectable) { + btn.dataset.date = cell.date; + btn.tabIndex = cell.date === focusedHeatmapDate ? 0 : -1; + btn.setAttribute( + "aria-label", + formatHeatmapCellAriaLabel(cell, locale, copy.heatmapTooltipUnit), + ); + btn.setAttribute("aria-describedby", "td-heatmap-tooltip"); + btn.addEventListener("mouseenter", () => showCellTooltip(cell)); + btn.addEventListener("mouseleave", hideCellTooltip); + btn.addEventListener("focus", () => { + focusedHeatmapDate = cell.date; + showCellTooltip(cell); + }); + btn.addEventListener("blur", hideCellTooltip); + btn.addEventListener("keydown", (event: KeyboardEvent) => { + if (event.key === "Escape") { + event.preventDefault(); + hideCellTooltip(); + return; + } + if ( + ![ + "ArrowUp", + "ArrowDown", + "ArrowLeft", + "ArrowRight", + "Home", + "End", + ].includes(event.key) + ) { + return; + } + event.preventDefault(); + const nextDate = navigateHeatmapDate( + currentHeatmapCells, + cell.date, + event.key as HeatmapNavigationKey, + ); + if (!nextDate) return; + focusedHeatmapDate = nextDate; + for (const b of gridEl.querySelectorAll("button[data-date]")) { + const isTarget = b.dataset.date === nextDate; + b.tabIndex = isTarget ? 0 : -1; + if (isTarget) b.focus(); + } + }); + } else { + btn.disabled = true; + btn.tabIndex = -1; + btn.setAttribute("aria-hidden", "true"); + } + return btn; + }); + + gridEl.replaceChildren(...buttons); + }; + + const makeEmptyRow = (colSpan: number, message: string): HTMLTableRowElement => { + const tr = document.createElement("tr"); + tr.className = "td-empty-row"; + const td = document.createElement("td"); + td.colSpan = colSpan; + td.textContent = message; + tr.appendChild(td); + return tr; + }; + + const renderShareTable = ( + tbodyName: "providers" | "models", + rows: ReturnType, + ) => { + const tbody = root.querySelector( + `[data-tbody="${tbodyName}"]`, + ); + if (!tbody) return; + if (rows.length === 0) { + tbody.replaceChildren(makeEmptyRow(4, copy.noDataInTable)); + return; + } + tbody.replaceChildren( + ...rows.map((row) => { + const tr = document.createElement("tr"); + + const tdName = document.createElement("td"); + const identity = document.createElement("span"); + identity.className = "td-row-identity"; + const dot = document.createElement("span"); + dot.className = "td-row-dot"; + dot.style.backgroundColor = row.color; + dot.setAttribute("aria-hidden", "true"); + const label = document.createElement("span"); + label.textContent = row.label; + identity.append(dot, label); + tdName.appendChild(identity); + + const tdReq = document.createElement("td"); + tdReq.className = "td-num"; + tdReq.title = row.requestsExact; + tdReq.textContent = row.requestsCompact; + + const tdTok = document.createElement("td"); + tdTok.className = "td-num"; + tdTok.title = row.tokensExact; + tdTok.textContent = row.tokensCompact; + + const tdShare = document.createElement("td"); + tdShare.className = "td-num"; + tdShare.textContent = row.tokenShareLabel; + + tr.append(tdName, tdReq, tdTok, tdShare); + return tr; + }), + ); + }; + + const renderInstallTable = ( + tbodyName: "versions" | "platforms" | "channels", + rows: ReturnType, + includeNewInstalls: boolean, + ) => { + const tbody = root.querySelector( + `[data-tbody="${tbodyName}"]`, + ); + if (!tbody) return; + const cols = includeNewInstalls ? 4 : 3; + if (rows.length === 0) { + tbody.replaceChildren(makeEmptyRow(cols, copy.noDataInTable)); + return; + } + tbody.replaceChildren( + ...rows.map((row) => { + const tr = document.createElement("tr"); + const tdLabel = document.createElement("td"); + tdLabel.className = "td-mono"; + tdLabel.textContent = row.label; + + const tdInstalls = document.createElement("td"); + tdInstalls.className = "td-num"; + tdInstalls.title = row.installsExact; + tdInstalls.textContent = row.installsCompact; + + tr.append(tdLabel, tdInstalls); + + if (includeNewInstalls) { + const tdNew = document.createElement("td"); + tdNew.className = "td-num"; + tdNew.title = row.newInstallsExact ?? "0"; + tdNew.textContent = row.newInstallsCompact ?? "0"; + tr.appendChild(tdNew); + } + + const tdShare = document.createElement("td"); + tdShare.className = "td-num"; + tdShare.textContent = row.shareLabel; + tr.appendChild(tdShare); + return tr; + }), + ); + }; + + const applyStatsSnapshot = (stats: TelemetryStatsV1) => { + latestStats = stats; + + const updatedEl = root.querySelector("[data-updated-label]"); + const formattedTime = formatGeneratedTimestamp(stats.generatedAt, locale); + if (updatedEl && formattedTime) { + updatedEl.textContent = `${copy.updatedPrefix}: ${formattedTime}`; + } else if (updatedEl) { + updatedEl.textContent = `${copy.updatedPrefix}: ${copy.updatedPending}`; + } + + for (const kpi of buildKpiStrip(stats, locale)) { + const el = root.querySelector(`[data-kpi-value="${kpi.id}"]`); + if (el) { + el.textContent = kpi.compact; + el.title = kpi.exactTitle; + } + } + + const tokenMix = buildTokenMix(stats.totals.tokens, locale); + const totalMixEl = root.querySelector("[data-token-mix-total]"); + if (totalMixEl) { + totalMixEl.textContent = tokenMix.totalCompact; + totalMixEl.title = tokenMix.totalExactTitle; + } + for (const seg of tokenMix.segments) { + const barSeg = root.querySelector( + `[data-token-segment="${seg.id}"]`, + ); + if (barSeg) { + barSeg.style.flex = `${Math.max(seg.value, 0)} 1 0`; + barSeg.style.minWidth = seg.value > 0 ? "3px" : "0"; + barSeg.title = `${seg.id}: ${seg.exactTitle} (${seg.percentLabel})`; + } + const valEl = root.querySelector(`[data-token-value="${seg.id}"]`); + if (valEl) { + valEl.textContent = seg.compact; + valEl.title = seg.exactTitle; + } + const pctEl = root.querySelector(`[data-token-pct="${seg.id}"]`); + if (pctEl) { + pctEl.textContent = seg.percentLabel; + } + } + + renderHeatmap(stats); + renderDailyChart(); + + renderShareTable("providers", buildProviderShareRows(stats.providers, locale)); + renderShareTable("models", buildModelShareRows(stats.models, locale)); + + renderInstallTable("versions", buildVersionRows(stats.versions, locale), true); + renderInstallTable("platforms", buildPlatformRows(stats.platforms, locale), false); + renderInstallTable("channels", buildChannelRows(stats.channels, locale), true); + + const reliability = buildReliabilitySummary(stats.outcomes, stats.errors, locale); + const rateEl = root.querySelector("[data-completion-rate]"); + if (rateEl) { + rateEl.textContent = reliability.completedRatioLabel; + } + for (const out of reliability.outcomes) { + const segEl = root.querySelector( + `[data-outcome-segment="${out.key}"]`, + ); + if (segEl) { + segEl.style.flex = `${Math.max(out.count, 0)} 1 0`; + segEl.style.minWidth = out.count > 0 ? "3px" : "0"; + segEl.title = `${out.key}: ${out.exact} (${out.shareLabel})`; + } + const cntEl = root.querySelector( + `[data-outcome-count="${out.key}"]`, + ); + if (cntEl) { + cntEl.textContent = out.compact; + cntEl.title = out.exact; + } + const pctEl = root.querySelector( + `[data-outcome-pct="${out.key}"]`, + ); + if (pctEl) { + pctEl.textContent = out.shareLabel; + } + } + + const errorsTbody = root.querySelector( + '[data-tbody="errors"]', + ); + if (errorsTbody) { + if (reliability.errors.length === 0) { + errorsTbody.replaceChildren(makeEmptyRow(3, copy.noErrorsRecorded)); + } else { + errorsTbody.replaceChildren( + ...reliability.errors.map((err) => { + const tr = document.createElement("tr"); + const tdCause = document.createElement("td"); + tdCause.className = "td-mono"; + tdCause.textContent = err.cause; + + const tdCount = document.createElement("td"); + tdCount.className = "td-num"; + tdCount.title = err.exact; + tdCount.textContent = err.compact; + + const tdShare = document.createElement("td"); + tdShare.className = "td-num"; + tdShare.textContent = err.shareLabel; + + tr.append(tdCause, tdCount, tdShare); + return tr; + }), + ); + } + } + }; + + const loadTelemetryStats = async (range: TelemetryStatsRange) => { + activeRange = range; + syncRangePills(); + const ticket = statsSequencer.begin(range, DEFAULT_STATS_REQUEST_TIMEOUT_MS); + setDashboardState("loading"); + try { + const url = buildStatsUrl(range, statsEndpoint); + const response = await fetch(url, { + headers: { accept: "application/json" }, + signal: ticket.signal, + }); + if (!ticket.isCurrent()) return; + let body: unknown = null; + try { + body = await response.json(); + } catch { + body = null; + } + if (!ticket.isCurrent()) return; + const classified = classifyStatsResponse({ + ok: response.ok, + status: response.status, + body, + }); + if (classified.stats) { + applyStatsSnapshot(classified.stats); + } else { + applyStatsSnapshot(createEmptyStatsSnapshot(range)); + } + setDashboardState(classified.state, classified.detail); + } catch (error) { + if (!ticket.isCurrent()) return; + const isAbort = + error instanceof Error && error.name === "AbortError"; + const detailMessage = + ticket.didTimeout() || isAbort + ? "Request timed out" + : error instanceof Error + ? error.message + : String(error); + const classified = classifyStatsResponse({ + networkError: true, + errorMessage: detailMessage, + }); + applyStatsSnapshot(createEmptyStatsSnapshot(range)); + setDashboardState(classified.state, classified.detail); + } finally { + ticket.finish(); + } + }; + + const loadDownloads = async () => { + const [npmWeekly, npmMonthly, npmYearly, githubReleases] = await Promise.all([ + fetchJsonWithTimeout(root.dataset.npmWeeklyUrl, DEFAULT_STATS_REQUEST_TIMEOUT_MS), + fetchJsonWithTimeout(root.dataset.npmMonthlyUrl, DEFAULT_STATS_REQUEST_TIMEOUT_MS), + fetchJsonWithTimeout(root.dataset.npmYearlyUrl, DEFAULT_STATS_REQUEST_TIMEOUT_MS), + fetchGithubReleasesPages(root.dataset.githubReleasesUrl, DEFAULT_STATS_REQUEST_TIMEOUT_MS), + ]); + + const dl = parseDownloadsPayload({ + npmWeekly, + npmMonthly, + npmYearly, + githubReleases, + }); + + const setDlValue = (selector: string, value: number | null) => { + const el = root.querySelector(selector); + if (!el) return; + if (value === null) { + el.textContent = "—"; + el.title = copy.downloadsUnavailable; + } else { + el.textContent = formatCompactNumber(value); + el.title = formatExactNumber(value, locale); + } + }; + + setDlValue("[data-dl-npm-weekly]", dl.npmWeekly); + setDlValue("[data-dl-npm-monthly]", dl.npmMonthly); + setDlValue("[data-dl-npm-yearly]", dl.npmYearly); + const ghTotalEl = root.querySelector("[data-dl-gh-total]"); + if (ghTotalEl) { + if (dl.githubTotalDownloads === null) { + ghTotalEl.textContent = "—"; + ghTotalEl.title = copy.downloadsUnavailable; + delete ghTotalEl.dataset.partial; + } else if (dl.githubDownloadsPartial) { + const partialLabel = copy.downloadsPartial || "partial"; + ghTotalEl.textContent = `${formatCompactNumber(dl.githubTotalDownloads)} (${partialLabel})`; + ghTotalEl.title = `${formatExactNumber(dl.githubTotalDownloads, locale)} (${partialLabel})`; + ghTotalEl.dataset.partial = "true"; + } else { + ghTotalEl.textContent = formatCompactNumber(dl.githubTotalDownloads); + ghTotalEl.title = formatExactNumber(dl.githubTotalDownloads, locale); + ghTotalEl.dataset.partial = "false"; + } + } + setDlValue("[data-dl-gh-latest]", dl.githubLatestDownloads); + + const latestTagEl = root.querySelector("[data-dl-gh-latest-tag]"); + if (latestTagEl && dl.githubLatestTag) { + latestTagEl.textContent = `(${dl.githubLatestTag})`; + } + }; + + for (const btn of root.querySelectorAll("[data-range-pill]")) { + btn.addEventListener("click", () => { + const nextRange = parseStatsRangeParam(btn.dataset.rangePill); + const nextUrl = new URL(window.location.href); + nextUrl.searchParams.set("range", nextRange); + window.history.replaceState(null, "", nextUrl.toString()); + void loadTelemetryStats(nextRange); + }); + } + + for (const btn of root.querySelectorAll("[data-chart-metric]")) { + btn.addEventListener("click", () => { + activeChartMetric = + btn.dataset.chartMetric === "requests" ? "requests" : "tokens"; + syncChartMetricPills(); + renderDailyChart(); + }); + } + + const retryBtn = root.querySelector("[data-retry-btn]"); + retryBtn?.addEventListener("click", () => { + void loadTelemetryStats(activeRange); + }); + + window.addEventListener("resize", () => chartInstance?.resize()); + new MutationObserver(() => renderDailyChart()).observe(document.documentElement, { + attributes: true, + attributeFilter: ["data-theme"], + }); + + renderDailyChart(); + void loadTelemetryStats(activeRange); + void loadDownloads(); +} diff --git a/docs-site/src/components/telemetry-dashboard/constants.ts b/docs-site/src/components/telemetry-dashboard/constants.ts new file mode 100644 index 0000000000..50e330e936 --- /dev/null +++ b/docs-site/src/components/telemetry-dashboard/constants.ts @@ -0,0 +1,188 @@ +import type { + HeatmapGrade, + OutcomeClassId, + TelemetryStatsRange, + TokenBucketId, +} from "./types"; + +export const TELEMETRY_STATS_ENDPOINT = "https://telemetry.opencodex.me/v1/stats"; + +export const TELEMETRY_RANGES: readonly TelemetryStatsRange[] = Object.freeze([ + "7d", + "30d", + "90d", + "365d", +]); + +export const TELEMETRY_RANGE_DAYS: Readonly> = + Object.freeze({ + "7d": 7, + "30d": 30, + "90d": 90, + "365d": 365, + }); + +export const DEFAULT_TELEMETRY_RANGE: TelemetryStatsRange = "30d"; + +export const NPM_PACKAGE_NAME = "@bitkyc08/opencodex"; +export const GITHUB_REPO_SLUG = "lidge-jun/opencodex"; +export const GITHUB_RELEASES_PER_PAGE = 100; +export const GITHUB_RELEASES_MAX_PAGES = 10; + +export const NPM_DOWNLOADS_WEEKLY_URL = + "https://api.npmjs.org/downloads/point/last-week/@bitkyc08/opencodex"; +export const NPM_DOWNLOADS_MONTHLY_URL = + "https://api.npmjs.org/downloads/point/last-month/@bitkyc08/opencodex"; +export const NPM_DOWNLOADS_YEARLY_URL = + "https://api.npmjs.org/downloads/point/last-year/@bitkyc08/opencodex"; +export const GITHUB_RELEASES_URL = + `https://api.github.com/repos/${GITHUB_REPO_SLUG}/releases?per_page=${GITHUB_RELEASES_PER_PAGE}`; + +export const TOKSCALE_REPO_URL = "https://github.com/junhoyeo/tokscale"; + +/** + * Relative docs path for the telemetry privacy guide added by stack layer 5 + * (`docs-site/src/content/docs/guides/telemetry.md`). + */ +export const TELEMETRY_GUIDE_PATH = "guides/telemetry/"; + +/** + * Disjoint token mix palette adapted from junhoyeo/tokscale `TokenBreakdown.tsx` (MIT). + */ +export const TOKEN_MIX_COLORS: Readonly> = Object.freeze({ + input: "#56b4e9", + cacheRead: "#cc79a7", + cacheWrite: "#e69f00", + output: "#009e73", + reasoning: "#8b5cf6", +}); + +export const TOKEN_BUCKET_ORDER: readonly TokenBucketId[] = Object.freeze([ + "input", + "cacheRead", + "cacheWrite", + "output", + "reasoning", +]); + +export const OUTCOME_COLORS: Readonly> = Object.freeze({ + completed: "#10b981", + incomplete: "#f59e0b", + aborted: "#6b7280", + failed: "#ef4444", +}); + +/** + * 5-grade contribution heatmap ramps adapted from junhoyeo/tokscale `src/lib/themes.ts` (MIT). + */ +export const HEATMAP_GRADE_COLORS: Readonly<{ + light: readonly [string, string, string, string, string]; + dark: readonly [string, string, string, string, string]; +}> = Object.freeze({ + light: ["#eff2f5", "#79b8ff", "#388bfd", "#1f6feb", "#0d419d"], + dark: ["#191f2b", "#1d4ed8", "#2563eb", "#4b91ff", "#8cc0ff"], +}); + +export function getHeatmapGradeColor( + theme: "light" | "dark", + grade: HeatmapGrade, +): string { + const palette = theme === "light" ? HEATMAP_GRADE_COLORS.light : HEATMAP_GRADE_COLORS.dark; + return palette[grade] ?? palette[0]; +} + +const PROVIDER_COLOR_MAP: Readonly> = Object.freeze({ + openai: "#10a37f", + chatgpt: "#14b8a6", + anthropic: "#d97757", + "claude-subscription": "#e39980", + google: "#4285f4", + vertex: "#3b82f6", + xai: "#1da1f2", + deepseek: "#06b6d4", + moonshot: "#8b5cf6", + qwen: "#6366f1", + zai: "#0ea5e9", + minimax: "#ec4899", + mistral: "#f97316", + openrouter: "#a855f7", + groq: "#ef4444", + cerebras: "#eab308", + together: "#22c55e", + fireworks: "#f59e0b", + cursor: "#f59e0b", + kiro: "#14b8a6", + copilot: "#38bdf8", + devin: "#84cc16", + ollama: "#94a3b8", + lmstudio: "#64748b", + "local-other": "#78716c", + other: "#6b7280", +}); + +const MODEL_COLOR_MAP: Readonly> = Object.freeze({ + "gpt-6": "#059669", + "gpt-5": "#10b981", + "gpt-4": "#34d399", + "o-series": "#6366f1", + codex: "#f59e0b", + "claude-opus": "#da7756", + "claude-sonnet": "#e39980", + "claude-haiku": "#ecb8a6", + "gemini-3": "#2563eb", + "gemini-2": "#60a5fa", + grok: "#1da1f2", + deepseek: "#06b6d4", + qwen: "#1a73e8", + kimi: "#a855f7", + glm: "#0ea5e9", + minimax: "#ec4899", + mistral: "#f97316", + llama: "#84cc16", + other: "#6b7280", +}); + +const FALLBACK_SERIES_PALETTE = [ + "#3b82f6", + "#10b981", + "#d97757", + "#8b5cf6", + "#f59e0b", + "#06b6d4", + "#ec4899", + "#84cc16", +] as const; + +function hashColor(key: string): string { + let hash = 0; + for (let i = 0; i < key.length; i++) { + hash = (hash * 31 + key.charCodeAt(i)) | 0; + } + return FALLBACK_SERIES_PALETTE[Math.abs(hash) % FALLBACK_SERIES_PALETTE.length]!; +} + +export function getProviderColor(providerKind: string): string { + const normalized = providerKind.trim().toLowerCase(); + return PROVIDER_COLOR_MAP[normalized] ?? hashColor(normalized); +} + +/** + * Model family color resolver adapted from junhoyeo/tokscale `modelColors.ts` (MIT). + */ +export function getModelFamilyColor(modelFamily: string): string { + const normalized = modelFamily.trim().toLowerCase(); + if (MODEL_COLOR_MAP[normalized]) { + return MODEL_COLOR_MAP[normalized]!; + } + const tokens = normalized.split(/[^a-z0-9]+/); + for (const token of tokens) { + if (token === "opus") return MODEL_COLOR_MAP["claude-opus"]!; + if (token === "sonnet") return MODEL_COLOR_MAP["claude-sonnet"]!; + if (token === "haiku") return MODEL_COLOR_MAP["claude-haiku"]!; + if (token.startsWith("claude")) return MODEL_COLOR_MAP["claude-sonnet"]!; + if (token.startsWith("gpt")) return MODEL_COLOR_MAP["gpt-5"]!; + if (token.startsWith("gemini")) return MODEL_COLOR_MAP["gemini-3"]!; + if (MODEL_COLOR_MAP[token]) return MODEL_COLOR_MAP[token]!; + } + return hashColor(normalized); +} diff --git a/docs-site/src/components/telemetry-dashboard/format.ts b/docs-site/src/components/telemetry-dashboard/format.ts new file mode 100644 index 0000000000..a93cb04df5 --- /dev/null +++ b/docs-site/src/components/telemetry-dashboard/format.ts @@ -0,0 +1,294 @@ +import { + DEFAULT_TELEMETRY_RANGE, + TELEMETRY_RANGES, + TELEMETRY_RANGE_DAYS, + TELEMETRY_STATS_ENDPOINT, + TOKEN_BUCKET_ORDER, + TOKEN_MIX_COLORS, +} from "./constants"; +import type { + KpiCardItem, + TelemetryStatsRange, + TelemetryStatsV1, + TokenMixSegment, + TokenMixSummary, +} from "./types"; + +const MAX_SAFE = Number.MAX_SAFE_INTEGER; + +export function finiteNonNegativeInt(value: unknown): number { + const n = Number(value); + if (!Number.isFinite(n) || n <= 0) return 0; + if (n >= MAX_SAFE) return MAX_SAFE; + return Math.floor(n); +} + +export function safeAddInt(a: number, b: number): number { + return finiteNonNegativeInt(finiteNonNegativeInt(a) + finiteNonNegativeInt(b)); +} + +/** + * Compact K/M/B/T formatter adapted from junhoyeo/tokscale `formatTokenCount` (MIT). + * Promotes boundary values (>= 999.95 of a unit) to the next unit so `999,960` + * renders as `"1.0M"` instead of `"1000.0K"`. + */ +export function formatCompactNumber(value: number): string { + const count = finiteNonNegativeInt(value); + if (count >= 1_000_000_000_000) { + const val = (count / 1_000_000_000_000).toFixed(2).replace(/\.?0+$/, ""); + return `${val}T`; + } + if (count >= 1_000_000_000) { + const val = count / 1_000_000_000; + return val >= 999.95 ? `${(val / 1000).toFixed(1)}T` : `${val.toFixed(1)}B`; + } + if (count >= 1_000_000) { + const val = count / 1_000_000; + return val >= 999.95 ? `${(val / 1000).toFixed(1)}B` : `${val.toFixed(1)}M`; + } + if (count >= 1_000) { + const val = count / 1_000; + return val >= 999.95 ? `${(val / 1000).toFixed(1)}M` : `${val.toFixed(1)}K`; + } + return count.toLocaleString("en-US"); +} + +export function formatExactNumber(value: number, locale = "en-US"): string { + return finiteNonNegativeInt(value).toLocaleString(locale); +} + +export function computePercentage(part: number, total: number): number { + const safePart = finiteNonNegativeInt(part); + const safeTotal = finiteNonNegativeInt(total); + if (safeTotal <= 0 || safePart <= 0) return 0; + return Math.min(100, (safePart / safeTotal) * 100); +} + +export function formatPercent(part: number, total: number, digits = 1): string { + return `${computePercentage(part, total).toFixed(digits)}%`; +} + +export function formatActiveHours( + activeMinutes: number, + locale = "en-US", +): { hours: number; compact: string; exactTitle: string } { + const minutes = finiteNonNegativeInt(activeMinutes); + const hours = minutes / 60; + const exactMinutes = minutes.toLocaleString(locale); + if (minutes === 0) { + return { + hours: 0, + compact: "0h", + exactTitle: `0h (${exactMinutes} min)`, + }; + } + const roundedHours = Number(hours.toFixed(1)); + const exactHours = roundedHours.toLocaleString(locale, { + minimumFractionDigits: roundedHours % 1 === 0 ? 0 : 1, + maximumFractionDigits: 1, + }); + const compactBase = + hours >= 1_000 + ? formatCompactNumber(Math.round(hours)) + : hours >= 100 + ? String(Math.round(hours)) + : hours.toFixed(1).replace(/\.0$/, ""); + return { + hours: roundedHours, + compact: `${compactBase}h`, + exactTitle: `${exactHours}h (${exactMinutes} min)`, + }; +} + +export function sumDisjointTokens( + tokens: TelemetryStatsV1["totals"]["tokens"] | null | undefined, +): number { + if (!tokens) return 0; + return safeAddInt( + safeAddInt( + safeAddInt(tokens.input, tokens.cacheRead), + safeAddInt(tokens.cacheWrite, tokens.output), + ), + tokens.reasoning, + ); +} + +export function getStatsRangeDays( + range?: TelemetryStatsRange | string | null, +): number { + if (isTelemetryStatsRange(range)) { + return TELEMETRY_RANGE_DAYS[range]; + } + return TELEMETRY_RANGE_DAYS[DEFAULT_TELEMETRY_RANGE]; +} + +export function resolveAvgDailyActiveInstalls( + stats: Pick & + Partial>, +): number { + const explicit = stats.totals.avgDailyActiveInstalls; + if (typeof explicit === "number" && Number.isFinite(explicit) && explicit >= 0) { + return Math.round(Math.min(explicit, MAX_SAFE) * 10) / 10; + } + const installDays = finiteNonNegativeInt(stats.totals.activeInstalls); + const days = getStatsRangeDays(stats.range); + if (days <= 0 || installDays <= 0) return 0; + return Math.round((installDays / days) * 10) / 10; +} + +export function formatAvgDailyActiveInstalls( + avgDailyActiveInstalls: number, + installDays: number, + locale = "en-US", + installDaysLabel = "install-days", +): { avg: number; compact: string; exactTitle: string } { + const safeInstallDays = finiteNonNegativeInt(installDays); + const safeAvg = + typeof avgDailyActiveInstalls === "number" && + Number.isFinite(avgDailyActiveInstalls) && + avgDailyActiveInstalls > 0 + ? Math.round(Math.min(avgDailyActiveInstalls, MAX_SAFE) * 10) / 10 + : 0; + const exactInstallDays = safeInstallDays.toLocaleString(locale); + if (safeAvg === 0 && safeInstallDays === 0) { + return { + avg: 0, + compact: "0", + exactTitle: `0 (0 ${installDaysLabel})`, + }; + } + const exactAvg = safeAvg.toLocaleString(locale, { + minimumFractionDigits: safeAvg % 1 === 0 ? 0 : 1, + maximumFractionDigits: 1, + }); + const compact = + safeAvg >= 1_000 + ? formatCompactNumber(Math.round(safeAvg)) + : safeAvg.toFixed(1).replace(/\.0$/, ""); + return { + avg: safeAvg, + compact, + exactTitle: `${exactAvg} (${exactInstallDays} ${installDaysLabel})`, + }; +} + +export function buildKpiStrip( + stats: Pick & + Partial>, + locale = "en-US", + installDaysLabel = "install-days", +): KpiCardItem[] { + const installDays = finiteNonNegativeInt(stats.totals.activeInstalls); + const avgDaily = resolveAvgDailyActiveInstalls(stats); + const formattedAvg = formatAvgDailyActiveInstalls( + avgDaily, + installDays, + locale, + installDaysLabel, + ); + const newInstalls = finiteNonNegativeInt(stats.totals.newInstalls); + const requests = finiteNonNegativeInt(stats.totals.requests); + const totalTokens = sumDisjointTokens(stats.totals.tokens); + const activeHours = formatActiveHours(stats.totals.activeMinutes, locale); + + return [ + { + id: "activeInstalls", + rawValue: formattedAvg.avg, + compact: formattedAvg.compact, + exactTitle: formattedAvg.exactTitle, + }, + { + id: "newInstalls", + rawValue: newInstalls, + compact: formatCompactNumber(newInstalls), + exactTitle: formatExactNumber(newInstalls, locale), + }, + { + id: "requests", + rawValue: requests, + compact: formatCompactNumber(requests), + exactTitle: formatExactNumber(requests, locale), + }, + { + id: "tokens", + rawValue: totalTokens, + compact: formatCompactNumber(totalTokens), + exactTitle: formatExactNumber(totalTokens, locale), + }, + { + id: "activeHours", + rawValue: finiteNonNegativeInt(stats.totals.activeMinutes), + compact: activeHours.compact, + exactTitle: activeHours.exactTitle, + }, + ]; +} + +export function buildTokenMix( + tokens: TelemetryStatsV1["totals"]["tokens"] | null | undefined, + locale = "en-US", +): TokenMixSummary { + const totalTokens = sumDisjointTokens(tokens); + const segments: TokenMixSegment[] = TOKEN_BUCKET_ORDER.map((id) => { + const value = finiteNonNegativeInt(tokens?.[id]); + const percent = computePercentage(value, totalTokens); + return { + id, + value, + compact: formatCompactNumber(value), + exactTitle: formatExactNumber(value, locale), + percent, + percentLabel: `${percent.toFixed(1)}%`, + color: TOKEN_MIX_COLORS[id], + }; + }); + + return { + totalTokens, + totalCompact: formatCompactNumber(totalTokens), + totalExactTitle: formatExactNumber(totalTokens, locale), + segments, + }; +} + +export function isTelemetryStatsRange(value: unknown): value is TelemetryStatsRange { + return ( + typeof value === "string" && + (TELEMETRY_RANGES as readonly string[]).includes(value) + ); +} + +export function parseStatsRangeParam( + value: string | null | undefined, +): TelemetryStatsRange { + if (isTelemetryStatsRange(value)) return value; + return DEFAULT_TELEMETRY_RANGE; +} + +export function buildStatsUrl( + range: TelemetryStatsRange, + endpoint: string = TELEMETRY_STATS_ENDPOINT, +): string { + const url = new URL(endpoint); + url.searchParams.set("range", range); + return url.toString(); +} + +export function formatGeneratedTimestamp( + iso: string | null | undefined, + locale = "en-US", +): string | null { + if (!iso || typeof iso !== "string") return null; + const parsed = new Date(iso); + if (Number.isNaN(parsed.getTime())) return null; + return parsed.toLocaleString(locale, { + year: "numeric", + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + timeZone: "UTC", + timeZoneName: "short", + }); +} diff --git a/docs-site/src/components/telemetry-dashboard/heatmap.ts b/docs-site/src/components/telemetry-dashboard/heatmap.ts new file mode 100644 index 0000000000..7343c98ad9 --- /dev/null +++ b/docs-site/src/components/telemetry-dashboard/heatmap.ts @@ -0,0 +1,269 @@ +import { finiteNonNegativeInt, formatExactNumber, safeAddInt } from "./format"; +import type { + HeatmapCalendar, + HeatmapCell, + HeatmapGrade, + HeatmapMonthMarker, + TelemetryStatsV1, +} from "./types"; + +const DAY_MS = 86_400_000; +const DAY_KEY_RE = /^(\d{4})-(\d{2})-(\d{2})$/; +const SHORT_MONTHS = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", +] as const; + +export function formatLocalizedMonthShort( + monthIndex: number, + locale = "en-US", +): string { + const safeMonth = Math.max(0, Math.min(11, Math.floor(monthIndex))); + try { + const d = new Date(Date.UTC(2026, safeMonth, 15)); + return new Intl.DateTimeFormat(locale, { + month: "short", + timeZone: "UTC", + }).format(d); + } catch { + return SHORT_MONTHS[safeMonth] ?? "Jan"; + } +} + +export function getLocalizedWeekdayLabels(locale = "en-US"): { + mon: string; + wed: string; + fri: string; +} { + try { + const fmt = new Intl.DateTimeFormat(locale, { + weekday: "short", + timeZone: "UTC", + }); + // 2026-01-05 is Monday, 2026-01-07 is Wednesday, 2026-01-09 is Friday (UTC) + return { + mon: fmt.format(new Date(Date.UTC(2026, 0, 5))), + wed: fmt.format(new Date(Date.UTC(2026, 0, 7))), + fri: fmt.format(new Date(Date.UTC(2026, 0, 9))), + }; + } catch { + return { mon: "Mon", wed: "Wed", fri: "Fri" }; + } +} + +export function parseUtcDayMs(day: string): number | null { + const match = DAY_KEY_RE.exec(day); + if (!match) return null; + const year = Number(match[1]); + const month = Number(match[2]) - 1; + const date = Number(match[3]); + const ms = Date.UTC(year, month, date); + const check = new Date(ms); + if ( + check.getUTCFullYear() !== year || + check.getUTCMonth() !== month || + check.getUTCDate() !== date + ) { + return null; + } + return ms; +} + +export function formatUtcDayKey(ms: number): string { + return new Date(ms).toISOString().slice(0, 10); +} + +/** + * 5-grade intensity bucket adapted from junhoyeo/tokscale `getContributionIntensity` (MIT). + */ +export function computeHeatmapGrade( + activeInstalls: number, + maxActiveInstalls: number, +): HeatmapGrade { + const value = finiteNonNegativeInt(activeInstalls); + const max = finiteNonNegativeInt(maxActiveInstalls); + if (value <= 0 || max <= 0) return 0; + const ratio = value / max; + if (ratio >= 0.75) return 4; + if (ratio >= 0.5) return 3; + if (ratio >= 0.25) return 2; + return 1; +} + +export function buildHeatmapCalendar( + heatmap: TelemetryStatsV1["heatmap"] | null | undefined, + locale = "en-US", +): HeatmapCalendar { + const byDayMs = new Map(); + for (const row of heatmap ?? []) { + if (!row || typeof row.day !== "string") continue; + const ms = parseUtcDayMs(row.day); + if (ms === null) continue; + const count = finiteNonNegativeInt(row.activeInstalls); + const prev = byDayMs.get(ms); + byDayMs.set(ms, { + date: row.day, + activeInstalls: prev ? safeAddInt(prev.activeInstalls, count) : count, + }); + } + + const sortedMs = [...byDayMs.keys()].sort((a, b) => a - b); + if (sortedMs.length === 0) { + return { + cells: [], + weekCount: 0, + activeDays: 0, + totalActiveInstalls: 0, + maxActiveInstalls: 0, + peakDay: null, + startDate: null, + endDate: null, + monthMarkers: [], + }; + } + + const firstMs = sortedMs[0]!; + const lastMs = sortedMs[sortedMs.length - 1]!; + + let maxActiveInstalls = 0; + let activeDays = 0; + let totalActiveInstalls = 0; + let peakDay: { date: string; activeInstalls: number } | null = null; + + for (const ms of sortedMs) { + const entry = byDayMs.get(ms)!; + totalActiveInstalls = safeAddInt(totalActiveInstalls, entry.activeInstalls); + if (entry.activeInstalls > 0) { + activeDays += 1; + if (entry.activeInstalls > maxActiveInstalls) { + maxActiveInstalls = entry.activeInstalls; + } + if ( + !peakDay || + entry.activeInstalls > peakDay.activeInstalls || + (entry.activeInstalls === peakDay.activeInstalls && entry.date < peakDay.date) + ) { + peakDay = { date: entry.date, activeInstalls: entry.activeInstalls }; + } + } + } + + const calendarStartMs = firstMs - new Date(firstMs).getUTCDay() * DAY_MS; + const calendarEndMs = lastMs + (6 - new Date(lastMs).getUTCDay()) * DAY_MS; + const totalGridDays = Math.round((calendarEndMs - calendarStartMs) / DAY_MS) + 1; + const weekCount = Math.round(totalGridDays / 7); + + const cells: HeatmapCell[] = []; + for (let offset = 0; offset < totalGridDays; offset++) { + const ms = calendarStartMs + offset * DAY_MS; + const date = formatUtcDayKey(ms); + const inRange = ms >= firstMs && ms <= lastMs; + const selectable = inRange; + const activeInstalls = selectable ? (byDayMs.get(ms)?.activeInstalls ?? 0) : 0; + const grade = selectable + ? computeHeatmapGrade(activeInstalls, maxActiveInstalls) + : 0; + cells.push({ + date, + activeInstalls, + grade, + inRange, + selectable, + weekIndex: Math.floor(offset / 7), + dayOfWeek: offset % 7, + }); + } + + const monthMarkers: HeatmapMonthMarker[] = []; + const seenWeeks = new Set(); + let cursorMs = firstMs; + while (cursorMs <= lastMs) { + const d = new Date(cursorMs); + const monthIndex = d.getUTCMonth(); + const weekIndex = Math.floor((cursorMs - calendarStartMs) / (DAY_MS * 7)); + if (!seenWeeks.has(weekIndex)) { + const marker: HeatmapMonthMarker = { + label: formatLocalizedMonthShort(monthIndex, locale), + monthIndex, + weekIndex, + }; + const prev = monthMarkers[monthMarkers.length - 1]; + if (prev && weekIndex - prev.weekIndex < 3) { + if (prev.weekIndex === 0) { + monthMarkers[monthMarkers.length - 1] = marker; + } + } else { + monthMarkers.push(marker); + } + seenWeeks.add(weekIndex); + } + cursorMs = Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1); + } + + return { + cells, + weekCount, + activeDays, + totalActiveInstalls, + maxActiveInstalls, + peakDay, + startDate: formatUtcDayKey(firstMs), + endDate: formatUtcDayKey(lastMs), + monthMarkers, + }; +} + +export type HeatmapNavigationKey = + | "ArrowUp" + | "ArrowDown" + | "ArrowLeft" + | "ArrowRight" + | "Home" + | "End"; + +export function navigateHeatmapDate( + cells: readonly HeatmapCell[], + currentDate: string, + key: HeatmapNavigationKey, +): string | null { + const selectable = cells.filter((cell) => cell.selectable); + if (selectable.length === 0) return null; + if (key === "Home") return selectable[0]!.date; + if (key === "End") return selectable[selectable.length - 1]!.date; + + const idx = selectable.findIndex((cell) => cell.date === currentDate); + if (idx === -1) return selectable[selectable.length - 1]!.date; + + const delta = + key === "ArrowUp" + ? -1 + : key === "ArrowDown" + ? 1 + : key === "ArrowLeft" + ? -7 + : 7; + const nextIdx = Math.max(0, Math.min(selectable.length - 1, idx + delta)); + return selectable[nextIdx]!.date; +} + +export function formatHeatmapCellAriaLabel( + cell: Pick, + locale = "en-US", + unitLabel = "active installs", +): string { + const count = formatExactNumber(cell.activeInstalls, locale); + if (locale.toLowerCase().startsWith("en") && unitLabel === "active installs") { + return `${cell.date}: ${count} active installs (grade ${cell.grade})`; + } + return `${cell.date}: ${count} ${unitLabel} (${cell.grade}/4)`; +} diff --git a/docs-site/src/components/telemetry-dashboard/index.ts b/docs-site/src/components/telemetry-dashboard/index.ts new file mode 100644 index 0000000000..1b2e34dd38 --- /dev/null +++ b/docs-site/src/components/telemetry-dashboard/index.ts @@ -0,0 +1,6 @@ +export * from "./types"; +export * from "./constants"; +export * from "./format"; +export * from "./heatmap"; +export * from "./tables"; +export * from "./state"; diff --git a/docs-site/src/components/telemetry-dashboard/leaderboard.ts b/docs-site/src/components/telemetry-dashboard/leaderboard.ts new file mode 100644 index 0000000000..f1c62249f9 --- /dev/null +++ b/docs-site/src/components/telemetry-dashboard/leaderboard.ts @@ -0,0 +1,387 @@ +/** + * Client for the leaderboard section of opencodex.me/dashboard. Reads the collector's public profile + * endpoints and renders connected profiles only. Every user-supplied string (handle, display name) + * is written with `textContent`; a handle is validated before it is ever put into a request URL. + */ +import type { TelemetryLeaderboardCopy } from "../../data/telemetry-leaderboard-i18n"; + +export const TELEMETRY_LEADERBOARD_ENDPOINT = "https://telemetry.opencodex.me/v1/leaderboard"; +export const TELEMETRY_PROFILE_BY_HANDLE_ENDPOINT = "https://telemetry.opencodex.me/v1/profiles/by-handle/"; +/** Mirrors PROFILE_HANDLE_RE in src/telemetry/profile/contract.ts (asserted by a test). */ +export const LEADERBOARD_HANDLE_RE = /^[a-z0-9][a-z0-9-]{1,22}[a-z0-9]$/; +export const LEADERBOARD_PERIODS = ["day", "week", "month"] as const; +export const LEADERBOARD_METRICS = ["tokens", "requests"] as const; +export type LeaderboardPeriod = (typeof LEADERBOARD_PERIODS)[number]; +export type LeaderboardMetric = (typeof LEADERBOARD_METRICS)[number]; +export const LEADERBOARD_LIMIT = 50; +const FETCH_TIMEOUT_MS = 10_000; + +/** Mirrors PROFILE_AVATARS in src/telemetry/profile/contract.ts. */ +export const LEADERBOARD_AVATAR_COLORS: Readonly> = Object.freeze({ + slate: "#64748b", red: "#ef4444", orange: "#f97316", amber: "#f59e0b", lime: "#84cc16", green: "#22c55e", + teal: "#14b8a6", cyan: "#06b6d4", blue: "#3b82f6", indigo: "#6366f1", violet: "#8b5cf6", pink: "#ec4899", +}); + +export interface LeaderboardEntry { + rank: number; + handle: string; + displayName: string; + avatar: string; + tokens: number; + requests: number; +} + +export interface LeaderboardSnapshot { + period: LeaderboardPeriod; + metric: LeaderboardMetric; + total: number; + entries: LeaderboardEntry[]; +} + +export interface PublicProfilePeriod { rank: number | null; of: number; tokens: number; requests: number } +export interface PublicProfileView { + handle: string; + displayName: string; + avatar: string; + periods: Record; + families: Array<{ family: string; tokens: number; requests: number }>; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function count(value: unknown): number { + return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0; +} + +/** Normalize and validate a handle from user input or the ?profile= parameter. */ +export function normalizeLeaderboardHandle(raw: string | null | undefined): string | null { + const handle = (raw ?? "").trim().toLowerCase(); + if (!LEADERBOARD_HANDLE_RE.test(handle) || handle.includes("--") || /^[0-9-]+$/.test(handle)) return null; + return handle; +} + +export function parseLeaderboardPeriod(raw: string | null | undefined): LeaderboardPeriod { + return (LEADERBOARD_PERIODS as readonly string[]).includes(raw ?? "") ? raw as LeaderboardPeriod : "week"; +} + +export function parseLeaderboardMetric(raw: string | null | undefined): LeaderboardMetric { + return (LEADERBOARD_METRICS as readonly string[]).includes(raw ?? "") ? raw as LeaderboardMetric : "tokens"; +} + +export function buildLeaderboardUrl(endpoint: string, period: LeaderboardPeriod, metric: LeaderboardMetric): string { + const url = new URL(endpoint); + url.search = new URLSearchParams({ period, metric, limit: String(LEADERBOARD_LIMIT) }).toString(); + return url.toString(); +} + +/** Null for an invalid handle, so no request is ever built from one. */ +export function buildProfileUrl(endpoint: string, rawHandle: string, metric: LeaderboardMetric): string | null { + const handle = normalizeLeaderboardHandle(rawHandle); + if (!handle) return null; + const url = new URL(encodeURIComponent(handle), endpoint); + url.search = new URLSearchParams({ metric }).toString(); + return url.toString(); +} + +export function parseLeaderboard(value: unknown): LeaderboardSnapshot | null { + if (!isRecord(value) || !Array.isArray(value.entries)) return null; + const entries: LeaderboardEntry[] = []; + for (const raw of value.entries) { + if (!isRecord(raw) || typeof raw.handle !== "string" || typeof raw.displayName !== "string") continue; + if (!normalizeLeaderboardHandle(raw.handle)) continue; + entries.push({ + rank: count(raw.rank), + handle: raw.handle, + displayName: raw.displayName.slice(0, 64), + avatar: typeof raw.avatar === "string" ? raw.avatar : "slate", + tokens: count(raw.tokens), + requests: count(raw.requests), + }); + } + return { + period: parseLeaderboardPeriod(typeof value.period === "string" ? value.period : null), + metric: parseLeaderboardMetric(typeof value.metric === "string" ? value.metric : null), + total: count(value.total), + entries, + }; +} + +export function parsePublicProfile(value: unknown): PublicProfileView | null { + if (!isRecord(value) || !isRecord(value.profile) || !isRecord(value.periods)) return null; + const profile = value.profile; + if (typeof profile.handle !== "string" || !normalizeLeaderboardHandle(profile.handle) || typeof profile.displayName !== "string") return null; + const periods = {} as Record; + for (const period of LEADERBOARD_PERIODS) { + const entry = value.periods[period]; + if (!isRecord(entry)) return null; + periods[period] = { + rank: typeof entry.rank === "number" && entry.rank > 0 ? Math.floor(entry.rank) : null, + of: count(entry.of), + tokens: count(entry.tokens), + requests: count(entry.requests), + }; + } + const families = Array.isArray(value.families) + ? value.families.filter(isRecord).filter(row => typeof row.family === "string") + .map(row => ({ family: String(row.family), tokens: count(row.tokens), requests: count(row.requests) })) + : []; + return { + handle: profile.handle, + displayName: profile.displayName.slice(0, 64), + avatar: typeof profile.avatar === "string" ? profile.avatar : "slate", + periods, + families, + }; +} + +export function formatRankOf(copy: TelemetryLeaderboardCopy, rank: number | null, of: number, number: Intl.NumberFormat): string { + if (rank === null) return copy.profileNotRanked; + return copy.profileRankOf.replace("{rank}", number.format(rank)).replace("{of}", number.format(of)); +} + +export function avatarColor(avatar: string): string { + return LEADERBOARD_AVATAR_COLORS[avatar] ?? LEADERBOARD_AVATAR_COLORS.slate!; +} + +function initial(name: string): string { + return [...name.trim()][0]?.toUpperCase() ?? "?"; +} + +async function fetchJson(url: string, fetchImpl: typeof fetch): Promise<{ status: number; body: unknown }> { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); + try { + const response = await fetchImpl(url, { signal: controller.signal, headers: { accept: "application/json" } }); + const body: unknown = await response.json().catch(() => null); + return { status: response.status, body }; + } finally { + clearTimeout(timer); + } +} + +export interface MountLeaderboardOptions { + root?: ParentNode; + fetchImpl?: typeof fetch; + location?: { search: string }; + history?: { replaceState: (data: unknown, unused: string, url?: string) => void }; +} + +/** Wire up every `[data-telemetry-leaderboard]` root on the page. */ +export function mountTelemetryLeaderboard(options: MountLeaderboardOptions = {}): void { + const scope = options.root ?? document; + const fetchImpl = options.fetchImpl ?? fetch.bind(globalThis); + for (const root of Array.from(scope.querySelectorAll("[data-telemetry-leaderboard]"))) { + mountOne(root, fetchImpl, options); + } +} + +function mountOne(root: HTMLElement, fetchImpl: typeof fetch, options: MountLeaderboardOptions): void { + const pageHistory = options.history ?? (typeof history !== "undefined" ? history : undefined); + const copy = JSON.parse(root.dataset.copy ?? "{}") as TelemetryLeaderboardCopy; + const locale = root.dataset.locale ?? "en"; + const leaderboardEndpoint = root.dataset.leaderboardEndpoint ?? TELEMETRY_LEADERBOARD_ENDPOINT; + const profileEndpoint = root.dataset.profileEndpoint ?? TELEMETRY_PROFILE_BY_HANDLE_ENDPOINT; + const number = new Intl.NumberFormat(locale === "zh-cn" ? "zh-CN" : locale === "zh-tw" ? "zh-TW" : locale); + const compact = new Intl.NumberFormat(locale === "zh-cn" ? "zh-CN" : locale === "zh-tw" ? "zh-TW" : locale, { notation: "compact", maximumFractionDigits: 1 }); + const body = root.querySelector("[data-tl-rows]"); + const status = root.querySelector("[data-tl-status]"); + const retry = root.querySelector("[data-tl-retry]"); + const profilePanel = root.querySelector("[data-tl-profile]"); + const form = root.querySelector("[data-tl-find]"); + const input = root.querySelector("[data-tl-find-input]"); + const findError = root.querySelector("[data-tl-find-error]"); + const search = new URLSearchParams(options.location?.search ?? (typeof location !== "undefined" ? location.search : "")); + let period = parseLeaderboardPeriod(search.get("period")); + let metric = parseLeaderboardMetric(search.get("metric")); + let sequence = 0; + let profileSequence = 0; + + const setPressed = () => { + for (const button of Array.from(root.querySelectorAll("[data-tl-period]"))) { + button.setAttribute("aria-pressed", String(button.dataset.tlPeriod === period)); + } + for (const button of Array.from(root.querySelectorAll("[data-tl-metric]"))) { + button.setAttribute("aria-pressed", String(button.dataset.tlMetric === metric)); + } + }; + + const setStatus = (text: string, showRetry: boolean) => { + if (status) { + status.textContent = text; + status.hidden = text.length === 0; + } + if (retry) retry.hidden = !showRetry; + }; + + const renderRows = (snapshot: LeaderboardSnapshot) => { + if (!body) return; + body.replaceChildren(); + for (const entry of snapshot.entries) { + const row = document.createElement("tr"); + const rank = document.createElement("td"); + rank.className = "tl-rank"; + rank.textContent = number.format(entry.rank); + const who = document.createElement("td"); + const link = document.createElement("a"); + link.className = "tl-who"; + link.href = `?profile=${encodeURIComponent(entry.handle)}#leaderboard`; + link.addEventListener("click", event => { + event.preventDefault(); + void showProfile(entry.handle); + }); + const avatar = document.createElement("span"); + avatar.className = "tl-avatar"; + avatar.setAttribute("aria-hidden", "true"); + avatar.style.setProperty("background-color", avatarColor(entry.avatar)); + avatar.textContent = initial(entry.displayName); + const name = document.createElement("span"); + name.className = "tl-name"; + name.textContent = entry.displayName; + const handle = document.createElement("span"); + handle.className = "tl-handle"; + handle.textContent = `@${entry.handle}`; + link.append(avatar, name, handle); + who.append(link); + const tokens = document.createElement("td"); + tokens.className = "tl-num"; + tokens.textContent = compact.format(entry.tokens); + tokens.title = number.format(entry.tokens); + const requests = document.createElement("td"); + requests.className = "tl-num"; + requests.textContent = number.format(entry.requests); + row.append(rank, who, tokens, requests); + body.append(row); + } + }; + + const load = async () => { + const mine = ++sequence; + setPressed(); + setStatus(copy.loading, false); + try { + const { status: code, body: payload } = await fetchJson(buildLeaderboardUrl(leaderboardEndpoint, period, metric), fetchImpl); + if (mine !== sequence) return; + const snapshot = code === 200 ? parseLeaderboard(payload) : null; + if (!snapshot) { + body?.replaceChildren(); + setStatus(copy.error, true); + return; + } + renderRows(snapshot); + setStatus(snapshot.entries.length === 0 ? copy.empty : "", false); + } catch { + if (mine !== sequence) return; + body?.replaceChildren(); + setStatus(copy.error, true); + } + }; + + const renderProfile = (view: PublicProfileView | null) => { + if (!profilePanel) return; + profilePanel.replaceChildren(); + profilePanel.hidden = false; + if (!view) { + const missing = document.createElement("p"); + missing.textContent = copy.profileNotFound; + profilePanel.append(missing); + return; + } + const header = document.createElement("div"); + header.className = "tl-profile-header"; + const avatar = document.createElement("span"); + avatar.className = "tl-avatar tl-avatar-lg"; + avatar.setAttribute("aria-hidden", "true"); + avatar.style.setProperty("background-color", avatarColor(view.avatar)); + avatar.textContent = initial(view.displayName); + const titles = document.createElement("div"); + const name = document.createElement("h3"); + name.className = "tl-profile-name"; + name.textContent = view.displayName; + const handle = document.createElement("span"); + handle.className = "tl-handle"; + handle.textContent = `@${view.handle}`; + titles.append(name, handle); + const close = document.createElement("button"); + close.type = "button"; + close.className = "tl-close"; + close.textContent = copy.profileClose; + close.addEventListener("click", () => { + profilePanel.hidden = true; + profilePanel.replaceChildren(); + pageHistory?.replaceState(null, "", "#leaderboard"); + }); + header.append(avatar, titles, close); + const grid = document.createElement("div"); + grid.className = "tl-profile-periods"; + const labels: Record = { day: copy.periodDay, week: copy.periodWeek, month: copy.periodMonth }; + for (const p of LEADERBOARD_PERIODS) { + const cell = document.createElement("div"); + cell.className = "tl-profile-period"; + const label = document.createElement("span"); + label.className = "tl-label"; + label.textContent = labels[p]; + const rank = document.createElement("strong"); + rank.textContent = formatRankOf(copy, view.periods[p].rank, view.periods[p].of, number); + const totals = document.createElement("span"); + totals.className = "tl-label"; + totals.textContent = `${compact.format(view.periods[p].tokens)} ${copy.metricTokens} · ${number.format(view.periods[p].requests)} ${copy.metricRequests}`; + cell.append(label, rank, totals); + grid.append(cell); + } + profilePanel.append(header, grid); + if (view.families.length > 0) { + const families = document.createElement("p"); + families.className = "tl-label"; + families.textContent = `${copy.profileFamilies}: ${view.families.slice(0, 5).map(row => row.family).join(", ")}`; + profilePanel.append(families); + } + }; + + const showProfile = async (rawHandle: string) => { + const mine = ++profileSequence; + const url = buildProfileUrl(profileEndpoint, rawHandle, metric); + if (!url) { + if (findError) { + findError.textContent = copy.findInvalid; + findError.hidden = false; + } + return; + } + if (findError) findError.hidden = true; + try { + const { status: code, body: payload } = await fetchJson(url, fetchImpl); + // A later lookup started while this one was in flight: its answer wins. + if (mine !== profileSequence) return; + renderProfile(code === 200 ? parsePublicProfile(payload) : null); + const handle = normalizeLeaderboardHandle(rawHandle)!; + pageHistory?.replaceState(null, "", `?profile=${encodeURIComponent(handle)}#leaderboard`); + } catch { + if (mine === profileSequence) renderProfile(null); + } + }; + + for (const button of Array.from(root.querySelectorAll("[data-tl-period]"))) { + button.addEventListener("click", () => { + period = parseLeaderboardPeriod(button.dataset.tlPeriod); + void load(); + }); + } + for (const button of Array.from(root.querySelectorAll("[data-tl-metric]"))) { + button.addEventListener("click", () => { + metric = parseLeaderboardMetric(button.dataset.tlMetric); + void load(); + }); + } + retry?.addEventListener("click", () => { void load(); }); + form?.addEventListener("submit", event => { + event.preventDefault(); + void showProfile(input?.value ?? ""); + }); + + void load(); + const requested = search.get("profile"); + if (requested !== null) void showProfile(requested); +} + diff --git a/docs-site/src/components/telemetry-dashboard/state.ts b/docs-site/src/components/telemetry-dashboard/state.ts new file mode 100644 index 0000000000..7c4731780c --- /dev/null +++ b/docs-site/src/components/telemetry-dashboard/state.ts @@ -0,0 +1,476 @@ +import { + GITHUB_RELEASES_MAX_PAGES, + GITHUB_RELEASES_PER_PAGE, +} from "./constants"; +import { + finiteNonNegativeInt, + isTelemetryStatsRange, + safeAddInt, + sumDisjointTokens, +} from "./format"; +import type { + DashboardFetchState, + DownloadStats, + TelemetryStatsRange, + TelemetryStatsV1, +} from "./types"; + +export const DEFAULT_STATS_REQUEST_TIMEOUT_MS = 15_000; + +function isPlainObject(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +export function isValidTelemetryStatsV1(value: unknown): value is TelemetryStatsV1 { + if (!isPlainObject(value)) return false; + if (value.schemaVersion !== 1) return false; + if (typeof value.generatedAt !== "string") return false; + if (!isTelemetryStatsRange(value.range)) return false; + if (!isPlainObject(value.totals)) return false; + if (!isPlainObject(value.totals.tokens)) return false; + if ( + value.totals.avgDailyActiveInstalls !== undefined && + (typeof value.totals.avgDailyActiveInstalls !== "number" || + !Number.isFinite(value.totals.avgDailyActiveInstalls) || + value.totals.avgDailyActiveInstalls < 0) + ) { + return false; + } + if (!isPlainObject(value.outcomes)) return false; + if ( + !Array.isArray(value.daily) || + !Array.isArray(value.dailyByProvider) || + !Array.isArray(value.heatmap) || + !Array.isArray(value.providers) || + !Array.isArray(value.models) || + !Array.isArray(value.versions) || + !Array.isArray(value.platforms) || + !Array.isArray(value.channels) || + !Array.isArray(value.errors) + ) { + return false; + } + return true; +} + +export function isStatsSnapshotEmpty(stats: TelemetryStatsV1): boolean { + const totalTokens = sumDisjointTokens(stats.totals.tokens); + const heatmap = Array.isArray(stats.heatmap) ? stats.heatmap : []; + const hasHeatmapActivity = heatmap.some( + (d) => isPlainObject(d) && finiteNonNegativeInt(d.activeInstalls) > 0, + ); + return ( + finiteNonNegativeInt(stats.totals.activeInstalls) === 0 && + finiteNonNegativeInt(stats.totals.newInstalls) === 0 && + finiteNonNegativeInt(stats.totals.requests) === 0 && + totalTokens === 0 && + !hasHeatmapActivity + ); +} + +export function createEmptyStatsSnapshot( + range: TelemetryStatsRange = "30d", +): TelemetryStatsV1 { + return { + schemaVersion: 1, + generatedAt: "", + range, + totals: { + activeInstalls: 0, + avgDailyActiveInstalls: 0, + newInstalls: 0, + activeMinutes: 0, + requests: 0, + tokens: { + input: 0, + cacheRead: 0, + cacheWrite: 0, + output: 0, + reasoning: 0, + }, + }, + daily: [], + dailyByProvider: [], + heatmap: [], + providers: [], + models: [], + versions: [], + platforms: [], + channels: [], + outcomes: { + completed: 0, + failed: 0, + incomplete: 0, + aborted: 0, + }, + errors: [], + }; +} + +export interface StatsRequestTicket { + readonly requestId: number; + readonly range: TelemetryStatsRange; + readonly signal: AbortSignal; + isCurrent(): boolean; + didTimeout(): boolean; + finish(): void; +} + +export interface StatsRequestSequencer { + begin(range: TelemetryStatsRange, timeoutMs?: number): StatsRequestTicket; + abortActive(): void; + getCurrentRequestId(): number; +} + +export function createStatsRequestSequencer( + defaultTimeoutMs = DEFAULT_STATS_REQUEST_TIMEOUT_MS, +): StatsRequestSequencer { + let currentRequestId = 0; + let activeController: AbortController | null = null; + let activeTimer: ReturnType | null = null; + + const clearActiveTimer = () => { + if (activeTimer !== null) { + clearTimeout(activeTimer); + activeTimer = null; + } + }; + + const abortActive = () => { + clearActiveTimer(); + if (activeController) { + activeController.abort(); + activeController = null; + } + }; + + return { + begin(range: TelemetryStatsRange, timeoutMs = defaultTimeoutMs): StatsRequestTicket { + abortActive(); + currentRequestId += 1; + const myRequestId = currentRequestId; + const controller = new AbortController(); + activeController = controller; + let timedOut = false; + + if (timeoutMs > 0 && Number.isFinite(timeoutMs)) { + activeTimer = setTimeout(() => { + timedOut = true; + controller.abort(); + }, timeoutMs); + } + + return { + requestId: myRequestId, + range, + signal: controller.signal, + isCurrent: () => myRequestId === currentRequestId, + didTimeout: () => timedOut, + finish: () => { + if (myRequestId === currentRequestId) { + clearActiveTimer(); + if (activeController === controller) { + activeController = null; + } + } + }, + }; + }, + abortActive, + getCurrentRequestId: () => currentRequestId, + }; +} + +export async function fetchJsonWithTimeout( + url: string | undefined, + timeoutMs = DEFAULT_STATS_REQUEST_TIMEOUT_MS, + fetchImpl: typeof fetch = fetch, +): Promise { + if (!url) return null; + const controller = new AbortController(); + const timer = + timeoutMs > 0 && Number.isFinite(timeoutMs) + ? setTimeout(() => controller.abort(), timeoutMs) + : null; + try { + const res = await fetchImpl(url, { + headers: { accept: "application/json" }, + signal: controller.signal, + }); + if (!res.ok) return null; + return await res.json(); + } catch { + return null; + } finally { + if (timer !== null) clearTimeout(timer); + } +} + +export function parseGithubNextLink( + linkHeader: string | null | undefined, + currentUrl?: string, +): string | null { + if (!linkHeader || typeof linkHeader !== "string") return null; + for (const part of linkHeader.split(",")) { + const urlMatch = /<([^>]+)>/.exec(part); + if (!urlMatch?.[1]) continue; + const params = part.slice(urlMatch.index + urlMatch[0].length); + if (!/;\s*rel\s*=\s*(?:"next"|'next'|next\b)/i.test(params)) continue; + try { + const parsed = currentUrl + ? new URL(urlMatch[1].trim(), currentUrl) + : new URL(urlMatch[1].trim()); + if (parsed.protocol !== "https:" && parsed.protocol !== "http:") { + return null; + } + if (currentUrl) { + const base = new URL(currentUrl); + if (parsed.origin !== base.origin) return null; + } + return parsed.toString(); + } catch { + return null; + } + } + return null; +} + +export interface GithubReleasesFetchResult { + releases: unknown[] | null; + partial: boolean; + pagesFetched: number; +} + +export async function fetchGithubReleasesPages( + initialUrl: string | undefined, + timeoutMs = DEFAULT_STATS_REQUEST_TIMEOUT_MS, + fetchImpl: typeof fetch = fetch, + maxPages = GITHUB_RELEASES_MAX_PAGES, +): Promise { + if (!initialUrl) { + return { releases: null, partial: false, pagesFetched: 0 }; + } + const pageCap = Math.max(1, Math.floor(maxPages)); + let nextUrl: string | null = null; + try { + const normalized = new URL(initialUrl); + if (!normalized.searchParams.has("per_page")) { + normalized.searchParams.set("per_page", String(GITHUB_RELEASES_PER_PAGE)); + } + nextUrl = normalized.toString(); + } catch { + nextUrl = initialUrl; + } + + const allReleases: unknown[] = []; + let pagesFetched = 0; + + while (nextUrl && pagesFetched < pageCap) { + const controller = new AbortController(); + const timer = + timeoutMs > 0 && Number.isFinite(timeoutMs) + ? setTimeout(() => controller.abort(), timeoutMs) + : null; + let res: Response; + try { + res = await fetchImpl(nextUrl, { + headers: { accept: "application/json" }, + signal: controller.signal, + }); + } catch { + if (timer !== null) clearTimeout(timer); + return pagesFetched === 0 + ? { releases: null, partial: false, pagesFetched: 0 } + : { releases: allReleases, partial: true, pagesFetched }; + } + let pageBody: unknown; + try { + if (!res.ok) { + return pagesFetched === 0 + ? { releases: null, partial: false, pagesFetched: 0 } + : { releases: allReleases, partial: true, pagesFetched }; + } + pageBody = await res.json(); + } catch { + return pagesFetched === 0 + ? { releases: null, partial: false, pagesFetched: 0 } + : { releases: allReleases, partial: true, pagesFetched }; + } finally { + if (timer !== null) clearTimeout(timer); + } + + if (!Array.isArray(pageBody)) { + return pagesFetched === 0 + ? { releases: null, partial: false, pagesFetched: 0 } + : { releases: allReleases, partial: true, pagesFetched }; + } + + pagesFetched += 1; + allReleases.push(...pageBody); + + const linkHeader = res.headers?.get?.("link") ?? null; + const linkedNext = parseGithubNextLink(linkHeader, nextUrl); + if (!linkedNext) { + return { releases: allReleases, partial: false, pagesFetched }; + } + if (pagesFetched >= pageCap) { + return { releases: allReleases, partial: true, pagesFetched }; + } + nextUrl = linkedNext; + } + + return { + releases: pagesFetched > 0 ? allReleases : null, + partial: false, + pagesFetched, + }; +} + +export interface ClassifyStatsInput { + ok?: boolean; + status?: number; + body?: unknown; + networkError?: boolean; + errorMessage?: string; +} + +export interface ClassifiedStatsResult { + state: Exclude; + stats: TelemetryStatsV1 | null; + reason: + | "ok" + | "collector-not-deployed" + | "no-reports-yet" + | "http-error" + | "invalid-payload" + | "network-error"; + detail?: string; +} + +export function classifyStatsResponse( + input: ClassifyStatsInput, +): ClassifiedStatsResult { + if (input.networkError) { + return { + state: "error", + stats: null, + reason: "network-error", + detail: input.errorMessage ?? "Network request failed", + }; + } + + const status = input.status ?? (input.ok ? 200 : 500); + if (status === 404 || status === 502 || status === 503) { + return { + state: "empty", + stats: null, + reason: "collector-not-deployed", + detail: `HTTP ${status}`, + }; + } + + if (status < 200 || status >= 300 || input.ok === false) { + return { + state: "error", + stats: null, + reason: "http-error", + detail: input.errorMessage ?? `HTTP ${status}`, + }; + } + + if (!isValidTelemetryStatsV1(input.body)) { + return { + state: "error", + stats: null, + reason: "invalid-payload", + detail: "Malformed TelemetryStatsV1 payload", + }; + } + + if (isStatsSnapshotEmpty(input.body)) { + return { + state: "empty", + stats: input.body, + reason: "no-reports-yet", + }; + } + + return { + state: "ready", + stats: input.body, + reason: "ok", + }; +} + +function parseNpmDownloadsCount(payload: unknown): number | null { + if (!isPlainObject(payload)) return null; + const raw = payload.downloads; + if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) return null; + return Math.floor(raw); +} + +export function parseDownloadsPayload(input: { + npmWeekly?: unknown; + npmMonthly?: unknown; + npmYearly?: unknown; + githubReleases?: unknown; + githubDownloadsPartial?: boolean; +}): DownloadStats { + const npmWeekly = parseNpmDownloadsCount(input.npmWeekly); + const npmMonthly = parseNpmDownloadsCount(input.npmMonthly); + const npmYearly = parseNpmDownloadsCount(input.npmYearly); + + let githubTotalDownloads: number | null = null; + let githubDownloadsPartial = Boolean(input.githubDownloadsPartial); + let githubLatestTag: string | null = null; + let githubLatestDownloads: number | null = null; + let githubReleaseCount = 0; + + let releasesArray: unknown[] | null = null; + if (Array.isArray(input.githubReleases)) { + releasesArray = input.githubReleases; + } else if ( + isPlainObject(input.githubReleases) && + Array.isArray(input.githubReleases.releases) + ) { + releasesArray = input.githubReleases.releases; + if (typeof input.githubReleases.partial === "boolean") { + githubDownloadsPartial = input.githubReleases.partial; + } + } + + if (releasesArray) { + let total = 0; + for (const rel of releasesArray) { + if (!isPlainObject(rel) || rel.draft === true) continue; + githubReleaseCount += 1; + const assets = Array.isArray(rel.assets) ? rel.assets : []; + let releaseTotal = 0; + for (const asset of assets) { + if (!isPlainObject(asset)) continue; + const count = finiteNonNegativeInt(asset.download_count); + releaseTotal = safeAddInt(releaseTotal, count); + } + total = safeAddInt(total, releaseTotal); + // Previews count toward the totals, but "latest release" is the newest stable one. + if (githubLatestTag === null && rel.prerelease !== true && typeof rel.tag_name === "string" && rel.tag_name.trim()) { + githubLatestTag = rel.tag_name.trim(); + githubLatestDownloads = releaseTotal; + } + } + githubTotalDownloads = total; + } else { + githubDownloadsPartial = false; + } + + return { + npmWeekly, + npmMonthly, + npmYearly, + githubTotalDownloads, + githubDownloadsPartial, + githubLatestTag, + githubLatestDownloads, + githubReleaseCount, + }; +} diff --git a/docs-site/src/components/telemetry-dashboard/tables.ts b/docs-site/src/components/telemetry-dashboard/tables.ts new file mode 100644 index 0000000000..192932a9b6 --- /dev/null +++ b/docs-site/src/components/telemetry-dashboard/tables.ts @@ -0,0 +1,478 @@ +import { + OUTCOME_COLORS, + getModelFamilyColor, + getProviderColor, +} from "./constants"; +import { + computePercentage, + finiteNonNegativeInt, + formatCompactNumber, + formatExactNumber, + formatPercent, + safeAddInt, +} from "./format"; +import type { + DailyChartMetric, + DailyProviderSeries, + ErrorCauseRow, + InstallRow, + OutcomeClassId, + OutcomeRow, + ReliabilitySummary, + ShareRow, + StackedDailyChartModel, + TelemetryStatsV1, +} from "./types"; + +const DEFAULT_MAX_CHART_SERIES = 6; + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +function nonEmptyKey(value: unknown): string | null { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} + +function isOtherKey(key: string): boolean { + return key.trim().toLowerCase() === "other"; +} + +function normalizeKeyOrOther(key: string): string { + return isOtherKey(key) ? "other" : key; +} + +export function buildDailyProviderChart( + dailyByProvider: TelemetryStatsV1["dailyByProvider"] | null | undefined, + daily: TelemetryStatsV1["daily"] | null | undefined, + metric: DailyChartMetric = "tokens", + maxSeries = DEFAULT_MAX_CHART_SERIES, +): StackedDailyChartModel { + const daySet = new Set(); + for (const d of daily ?? []) { + if (d && typeof d.day === "string") daySet.add(d.day); + } + for (const row of dailyByProvider ?? []) { + if (row && typeof row.day === "string") daySet.add(row.day); + } + const days = [...daySet].sort(); + const dayIndexByKey = new Map(days.map((d, i) => [d, i])); + + const byProvider = new Map(); + for (const row of dailyByProvider ?? []) { + if (!row || typeof row.day !== "string" || typeof row.providerKind !== "string") { + continue; + } + const rawProvider = nonEmptyKey(row.providerKind); + if (!rawProvider) continue; + const providerKind = normalizeKeyOrOther(rawProvider); + const dayIdx = dayIndexByKey.get(row.day); + if (dayIdx === undefined) continue; + const rawVal = metric === "requests" ? row.requests : row.tokens; + const val = finiteNonNegativeInt(rawVal); + if (val <= 0) continue; + let entry = byProvider.get(providerKind); + if (!entry) { + entry = { total: 0, values: new Array(days.length).fill(0) }; + byProvider.set(providerKind, entry); + } + entry.values[dayIdx] = safeAddInt(entry.values[dayIdx] ?? 0, val); + entry.total = safeAddInt(entry.total, val); + } + + const explicitOther = byProvider.get("other"); + const ranked = [...byProvider.entries()] + .filter(([key]) => key !== "other") + .sort((a, b) => { + if (b[1].total !== a[1].total) return b[1].total - a[1].total; + return a[0].localeCompare(b[0]); + }); + + const limit = Math.max(1, Math.floor(maxSeries)); + const top = ranked.slice(0, limit); + const overflow = ranked.slice(limit); + + const series: DailyProviderSeries[] = top.map(([providerKind, data]) => ({ + providerKind, + color: getProviderColor(providerKind), + total: data.total, + values: data.values, + })); + + if (explicitOther || overflow.length > 0) { + const otherValues = new Array(days.length).fill(0); + let otherTotal = 0; + if (explicitOther) { + otherTotal = safeAddInt(otherTotal, explicitOther.total); + for (let i = 0; i < days.length; i++) { + otherValues[i] = safeAddInt(otherValues[i] ?? 0, explicitOther.values[i] ?? 0); + } + } + for (const [, data] of overflow) { + otherTotal = safeAddInt(otherTotal, data.total); + for (let i = 0; i < days.length; i++) { + otherValues[i] = safeAddInt(otherValues[i] ?? 0, data.values[i] ?? 0); + } + } + if (otherTotal > 0) { + series.push({ + providerKind: "other", + color: getProviderColor("other"), + total: otherTotal, + values: otherValues, + }); + } + } + + const total = series.reduce((acc, item) => safeAddInt(acc, item.total), 0); + return { days, metric, total, series }; +} + +export interface DailyChartAccessibleRow { + day: string; + providerKind: string; + value: number; + valueCompact: string; + valueExact: string; +} + +export function buildDailyChartAccessibleTable( + model: StackedDailyChartModel, + locale = "en-US", +): DailyChartAccessibleRow[] { + const rows: DailyChartAccessibleRow[] = []; + for (let dayIdx = 0; dayIdx < model.days.length; dayIdx++) { + const day = model.days[dayIdx]!; + for (const s of model.series) { + const val = finiteNonNegativeInt(s.values[dayIdx]); + if (val <= 0) continue; + rows.push({ + day, + providerKind: s.providerKind, + value: val, + valueCompact: formatCompactNumber(val), + valueExact: formatExactNumber(val, locale), + }); + } + } + return rows; +} + +export function buildProviderShareRows( + providers: TelemetryStatsV1["providers"] | null | undefined, + locale = "en-US", +): ShareRow[] { + const merged = new Map(); + for (const p of providers ?? []) { + if (!isRecord(p)) continue; + const rawKey = nonEmptyKey(p.providerKind); + if (!rawKey) continue; + const key = normalizeKeyOrOther(rawKey); + const requests = finiteNonNegativeInt(p.requests); + const tokens = finiteNonNegativeInt(p.tokens); + const prev = merged.get(key); + if (prev) { + prev.requests = safeAddInt(prev.requests, requests); + prev.tokens = safeAddInt(prev.tokens, tokens); + } else { + merged.set(key, { key, requests, tokens }); + } + } + const rows = [...merged.values()]; + rows.sort((a, b) => { + if (a.key === "other" && b.key !== "other") return 1; + if (b.key === "other" && a.key !== "other") return -1; + if (b.tokens !== a.tokens) return b.tokens - a.tokens; + if (b.requests !== a.requests) return b.requests - a.requests; + return a.key.localeCompare(b.key); + }); + const totalTokens = rows.reduce((acc, r) => safeAddInt(acc, r.tokens), 0); + const totalRequests = rows.reduce((acc, r) => safeAddInt(acc, r.requests), 0); + + return rows.map((r) => { + const tokenSharePercent = computePercentage(r.tokens, totalTokens); + const requestSharePercent = computePercentage(r.requests, totalRequests); + return { + key: r.key, + label: r.key, + color: getProviderColor(r.key), + requests: r.requests, + requestsCompact: formatCompactNumber(r.requests), + requestsExact: formatExactNumber(r.requests, locale), + requestSharePercent, + requestShareLabel: formatPercent(r.requests, totalRequests), + tokens: r.tokens, + tokensCompact: formatCompactNumber(r.tokens), + tokensExact: formatExactNumber(r.tokens, locale), + tokenSharePercent, + tokenShareLabel: formatPercent(r.tokens, totalTokens), + }; + }); +} + +export function buildModelShareRows( + models: TelemetryStatsV1["models"] | null | undefined, + locale = "en-US", +): ShareRow[] { + const merged = new Map(); + for (const m of models ?? []) { + if (!isRecord(m)) continue; + const rawKey = nonEmptyKey(m.modelFamily); + if (!rawKey) continue; + const key = normalizeKeyOrOther(rawKey); + const requests = finiteNonNegativeInt(m.requests); + const tokens = finiteNonNegativeInt(m.tokens); + const prev = merged.get(key); + if (prev) { + prev.requests = safeAddInt(prev.requests, requests); + prev.tokens = safeAddInt(prev.tokens, tokens); + } else { + merged.set(key, { key, requests, tokens }); + } + } + const rows = [...merged.values()]; + rows.sort((a, b) => { + if (a.key === "other" && b.key !== "other") return 1; + if (b.key === "other" && a.key !== "other") return -1; + if (b.tokens !== a.tokens) return b.tokens - a.tokens; + if (b.requests !== a.requests) return b.requests - a.requests; + return a.key.localeCompare(b.key); + }); + const totalTokens = rows.reduce((acc, r) => safeAddInt(acc, r.tokens), 0); + const totalRequests = rows.reduce((acc, r) => safeAddInt(acc, r.requests), 0); + + return rows.map((r) => { + const tokenSharePercent = computePercentage(r.tokens, totalTokens); + const requestSharePercent = computePercentage(r.requests, totalRequests); + return { + key: r.key, + label: r.key, + color: getModelFamilyColor(r.key), + requests: r.requests, + requestsCompact: formatCompactNumber(r.requests), + requestsExact: formatExactNumber(r.requests, locale), + requestSharePercent, + requestShareLabel: formatPercent(r.requests, totalRequests), + tokens: r.tokens, + tokensCompact: formatCompactNumber(r.tokens), + tokensExact: formatExactNumber(r.tokens, locale), + tokenSharePercent, + tokenShareLabel: formatPercent(r.tokens, totalTokens), + }; + }); +} + +export function buildVersionRows( + versions: TelemetryStatsV1["versions"] | null | undefined, + locale = "en-US", +): InstallRow[] { + const merged = new Map< + string, + { version: string; installs: number; newInstalls: number } + >(); + for (const v of versions ?? []) { + if (!isRecord(v)) continue; + const rawVersion = nonEmptyKey(v.version); + if (!rawVersion) continue; + const version = normalizeKeyOrOther(rawVersion); + const installs = finiteNonNegativeInt(v.installs); + const newInstalls = finiteNonNegativeInt(v.newInstalls); + const prev = merged.get(version); + if (prev) { + prev.installs = safeAddInt(prev.installs, installs); + prev.newInstalls = safeAddInt(prev.newInstalls, newInstalls); + } else { + merged.set(version, { version, installs, newInstalls }); + } + } + const rows = [...merged.values()]; + rows.sort((a, b) => { + if (a.version === "other" && b.version !== "other") return 1; + if (b.version === "other" && a.version !== "other") return -1; + if (b.installs !== a.installs) return b.installs - a.installs; + return b.version.localeCompare(a.version); + }); + const totalInstalls = rows.reduce((acc, r) => safeAddInt(acc, r.installs), 0); + return rows.map((r) => ({ + key: r.version, + label: r.version === "other" ? "other" : `v${r.version.replace(/^v/i, "")}`, + installs: r.installs, + installsCompact: formatCompactNumber(r.installs), + installsExact: formatExactNumber(r.installs, locale), + newInstalls: r.newInstalls, + newInstallsCompact: formatCompactNumber(r.newInstalls), + newInstallsExact: formatExactNumber(r.newInstalls, locale), + sharePercent: computePercentage(r.installs, totalInstalls), + shareLabel: formatPercent(r.installs, totalInstalls), + })); +} + +export function buildPlatformRows( + platforms: TelemetryStatsV1["platforms"] | null | undefined, + locale = "en-US", +): InstallRow[] { + const merged = new Map(); + for (const p of platforms ?? []) { + if (!isRecord(p)) continue; + const os = nonEmptyKey(p.os); + const arch = nonEmptyKey(p.arch); + if (!os) continue; + let key: string; + if (isOtherKey(os) && (!arch || isOtherKey(arch))) { + key = "other"; + } else if (!arch) { + continue; + } else { + key = `${os}/${arch}`; + } + const installs = finiteNonNegativeInt(p.installs); + const prev = merged.get(key); + if (prev) { + prev.installs = safeAddInt(prev.installs, installs); + } else { + merged.set(key, { key, installs }); + } + } + const rows = [...merged.values()]; + rows.sort((a, b) => { + if (a.key === "other" && b.key !== "other") return 1; + if (b.key === "other" && a.key !== "other") return -1; + if (b.installs !== a.installs) return b.installs - a.installs; + return a.key.localeCompare(b.key); + }); + const totalInstalls = rows.reduce((acc, r) => safeAddInt(acc, r.installs), 0); + return rows.map((r) => ({ + key: r.key, + label: r.key, + installs: r.installs, + installsCompact: formatCompactNumber(r.installs), + installsExact: formatExactNumber(r.installs, locale), + sharePercent: computePercentage(r.installs, totalInstalls), + shareLabel: formatPercent(r.installs, totalInstalls), + })); +} + +export function buildChannelRows( + channels: TelemetryStatsV1["channels"] | null | undefined, + locale = "en-US", +): InstallRow[] { + const merged = new Map< + string, + { channel: string; installs: number; newInstalls: number } + >(); + for (const c of channels ?? []) { + if (!isRecord(c)) continue; + const rawChannel = nonEmptyKey(c.installChannel); + if (!rawChannel) continue; + const channel = normalizeKeyOrOther(rawChannel); + const installs = finiteNonNegativeInt(c.installs); + const newInstalls = finiteNonNegativeInt(c.newInstalls); + const prev = merged.get(channel); + if (prev) { + prev.installs = safeAddInt(prev.installs, installs); + prev.newInstalls = safeAddInt(prev.newInstalls, newInstalls); + } else { + merged.set(channel, { channel, installs, newInstalls }); + } + } + const rows = [...merged.values()]; + rows.sort((a, b) => { + if (a.channel === "other" && b.channel !== "other") return 1; + if (b.channel === "other" && a.channel !== "other") return -1; + if (b.installs !== a.installs) return b.installs - a.installs; + return a.channel.localeCompare(b.channel); + }); + const totalInstalls = rows.reduce((acc, r) => safeAddInt(acc, r.installs), 0); + return rows.map((r) => ({ + key: r.channel, + label: r.channel, + installs: r.installs, + installsCompact: formatCompactNumber(r.installs), + installsExact: formatExactNumber(r.installs, locale), + newInstalls: r.newInstalls, + newInstallsCompact: formatCompactNumber(r.newInstalls), + newInstallsExact: formatExactNumber(r.newInstalls, locale), + sharePercent: computePercentage(r.installs, totalInstalls), + shareLabel: formatPercent(r.installs, totalInstalls), + })); +} + +const OUTCOME_KEYS: readonly OutcomeClassId[] = [ + "completed", + "incomplete", + "aborted", + "failed", +]; + +export function buildReliabilitySummary( + outcomes: TelemetryStatsV1["outcomes"] | null | undefined, + errors: TelemetryStatsV1["errors"] | null | undefined, + locale = "en-US", +): ReliabilitySummary { + const counts: Record = { + completed: finiteNonNegativeInt(outcomes?.completed), + incomplete: finiteNonNegativeInt(outcomes?.incomplete), + aborted: finiteNonNegativeInt(outcomes?.aborted), + failed: finiteNonNegativeInt(outcomes?.failed), + }; + const totalRequests = safeAddInt( + safeAddInt(counts.completed, counts.incomplete), + safeAddInt(counts.aborted, counts.failed), + ); + const completedRatioPercent = computePercentage(counts.completed, totalRequests); + const completedRatioLabel = formatPercent(counts.completed, totalRequests); + + const outcomeRows: OutcomeRow[] = OUTCOME_KEYS.map((key) => ({ + key, + count: counts[key], + compact: formatCompactNumber(counts[key]), + exact: formatExactNumber(counts[key], locale), + sharePercent: computePercentage(counts[key], totalRequests), + shareLabel: formatPercent(counts[key], totalRequests), + color: OUTCOME_COLORS[key], + })); + + const mergedErrors = new Map(); + for (const e of errors ?? []) { + if (!isRecord(e)) continue; + const rawCause = nonEmptyKey(e.cause); + if (!rawCause) continue; + const cause = normalizeKeyOrOther(rawCause); + const count = finiteNonNegativeInt(e.count); + if (count <= 0) continue; + const prev = mergedErrors.get(cause); + if (prev) { + prev.count = safeAddInt(prev.count, count); + } else { + mergedErrors.set(cause, { cause, count }); + } + } + const rawErrors = [...mergedErrors.values()]; + rawErrors.sort((a, b) => { + if (a.cause === "other" && b.cause !== "other") return 1; + if (b.cause === "other" && a.cause !== "other") return -1; + if (b.count !== a.count) return b.count - a.count; + return a.cause.localeCompare(b.cause); + }); + + const totalErrors = rawErrors.reduce((acc, e) => safeAddInt(acc, e.count), 0); + const errorRows: ErrorCauseRow[] = rawErrors.map((e) => ({ + cause: e.cause, + count: e.count, + compact: formatCompactNumber(e.count), + exact: formatExactNumber(e.count, locale), + sharePercent: computePercentage(e.count, totalErrors), + shareLabel: formatPercent(e.count, totalErrors), + })); + + return { + totalRequests, + completedRatioPercent, + completedRatioLabel, + outcomes: outcomeRows, + errors: errorRows, + totalErrors, + }; +} diff --git a/docs-site/src/components/telemetry-dashboard/types.ts b/docs-site/src/components/telemetry-dashboard/types.ts new file mode 100644 index 0000000000..76fc0dd448 --- /dev/null +++ b/docs-site/src/components/telemetry-dashboard/types.ts @@ -0,0 +1,236 @@ +export type TelemetryStatsRange = "7d" | "30d" | "90d" | "365d"; + +/** + * Public response contract of `GET https://telemetry.opencodex.me/v1/stats`. + * Kept in lockstep with `services/telemetry-collector/src/types.ts` and + * verified by `tests/ci-workflows/docs-telemetry-dashboard.test.ts`. + */ +export type TelemetryStatsV1 = { + schemaVersion: 1; + generatedAt: string; + range: TelemetryStatsRange; + totals: { + activeInstalls: number; + avgDailyActiveInstalls?: number; + newInstalls: number; + activeMinutes: number; + requests: number; + tokens: { + input: number; + cacheRead: number; + cacheWrite: number; + output: number; + reasoning: number; + }; + }; + daily: Array<{ + day: string; + activeInstalls: number; + newInstalls: number; + activeMinutes: number; + requests: number; + failed: number; + tokens: number; + }>; + dailyByProvider: Array<{ + day: string; + providerKind: string; + requests: number; + tokens: number; + }>; + heatmap: Array<{ + day: string; + activeInstalls: number; + }>; + providers: Array<{ + providerKind: string; + requests: number; + tokens: number; + }>; + models: Array<{ + modelFamily: string; + requests: number; + tokens: number; + }>; + versions: Array<{ + version: string; + installs: number; + newInstalls: number; + }>; + platforms: Array<{ + os: string; + arch: string; + installs: number; + }>; + channels: Array<{ + installChannel: string; + installs: number; + newInstalls: number; + }>; + outcomes: { + completed: number; + failed: number; + incomplete: number; + aborted: number; + }; + errors: Array<{ + cause: string; + count: number; + }>; +}; + +export type HeatmapGrade = 0 | 1 | 2 | 3 | 4; + +export type KpiMetricId = + | "activeInstalls" + | "newInstalls" + | "requests" + | "tokens" + | "activeHours"; + +export interface KpiCardItem { + id: KpiMetricId; + rawValue: number; + compact: string; + exactTitle: string; +} + +export type TokenBucketId = + | "input" + | "cacheRead" + | "cacheWrite" + | "output" + | "reasoning"; + +export interface TokenMixSegment { + id: TokenBucketId; + value: number; + compact: string; + exactTitle: string; + percent: number; + percentLabel: string; + color: string; +} + +export interface TokenMixSummary { + totalTokens: number; + totalCompact: string; + totalExactTitle: string; + segments: TokenMixSegment[]; +} + +export interface HeatmapCell { + date: string; + activeInstalls: number; + grade: HeatmapGrade; + inRange: boolean; + selectable: boolean; + weekIndex: number; + dayOfWeek: number; +} + +export interface HeatmapMonthMarker { + label: string; + monthIndex: number; + weekIndex: number; +} + +export interface HeatmapCalendar { + cells: HeatmapCell[]; + weekCount: number; + activeDays: number; + totalActiveInstalls: number; + maxActiveInstalls: number; + peakDay: { date: string; activeInstalls: number } | null; + startDate: string | null; + endDate: string | null; + monthMarkers: HeatmapMonthMarker[]; +} + +export type DailyChartMetric = "tokens" | "requests"; + +export interface DailyProviderSeries { + providerKind: string; + color: string; + total: number; + values: number[]; +} + +export interface StackedDailyChartModel { + days: string[]; + metric: DailyChartMetric; + total: number; + series: DailyProviderSeries[]; +} + +export interface ShareRow { + key: string; + label: string; + color: string; + requests: number; + requestsCompact: string; + requestsExact: string; + requestSharePercent: number; + requestShareLabel: string; + tokens: number; + tokensCompact: string; + tokensExact: string; + tokenSharePercent: number; + tokenShareLabel: string; +} + +export interface InstallRow { + key: string; + label: string; + installs: number; + installsCompact: string; + installsExact: string; + newInstalls?: number; + newInstallsCompact?: string; + newInstallsExact?: string; + sharePercent: number; + shareLabel: string; +} + +export type OutcomeClassId = "completed" | "failed" | "incomplete" | "aborted"; + +export interface OutcomeRow { + key: OutcomeClassId; + count: number; + compact: string; + exact: string; + sharePercent: number; + shareLabel: string; + color: string; +} + +export interface ErrorCauseRow { + cause: string; + count: number; + compact: string; + exact: string; + sharePercent: number; + shareLabel: string; +} + +export interface ReliabilitySummary { + totalRequests: number; + completedRatioPercent: number; + completedRatioLabel: string; + outcomes: OutcomeRow[]; + errors: ErrorCauseRow[]; + totalErrors: number; +} + +export interface DownloadStats { + npmWeekly: number | null; + npmMonthly: number | null; + npmYearly: number | null; + githubTotalDownloads: number | null; + githubDownloadsPartial: boolean; + githubLatestTag: string | null; + githubLatestDownloads: number | null; + githubReleaseCount: number; +} + +export type DashboardFetchState = "loading" | "ready" | "empty" | "error"; diff --git a/docs-site/src/content/docs/contributing.md b/docs-site/src/content/docs/contributing.md index bfa47f4d4e..282ec9c1e7 100644 --- a/docs-site/src/content/docs/contributing.md +++ b/docs-site/src/content/docs/contributing.md @@ -15,7 +15,7 @@ bun install bun run setup:hooks # retire the managed pre-push and post-merge hooks bun run dev:proxy # proxy API in dev mode bun run dev:gui # dashboard dev server (another terminal) -bun run typecheck # bun x tsc --noEmit +bun run typecheck # bun check --no-script --noEmit bun run test # full suite (default) ``` @@ -33,10 +33,11 @@ yourself — the dev server is unaffected because it rebuilds on demand. ## Build and test commands The root package is Bun-native TypeScript; there is no separate server compile step. Use the checked-in -scripts so local commands match CI: +scripts for local verification: ```bash -bun run typecheck # strict TypeScript check +bun run typecheck # strict Bun-native type check +bun run typecheck:tsc # reference check with the installed TypeScript compiler bun run test:changed # import-graph tests against the resolved dev merge base bun run test # full suite (default) bun test tests/routing/router.test.ts # focused test file @@ -45,9 +46,19 @@ bun run privacy:scan # credential/privacy scan used by CI bun run prepare:package # refresh package launchers/assets ``` -The suite uses Bun 1.4.3 (`package.json`'s `testRunnerBun`) while the shipped runtime is 1.4.2. -`scripts/test.ts` finds a 1.4.3 binary on PATH or in `~/.bun/bin`, or uses `OCX_TEST_RUNNER_BUN`. +`typecheck` uses Bun's native checker with the root `tsconfig.json`, preserving its `src/` scope +and strict compiler options without emitting files. `--no-script` keeps it on the type checker +if a `check` package script is added later. The installed Bun dependency supplies the checker; +`typecheck:tsc` retains the TypeScript compiler for comparisons and fallback. CI and release preflight +continue to invoke `tsc` directly, and the GUI retains its own TypeScript build check. +The `prepublishOnly` hook also uses `typecheck:tsc`, between the audit and GUI build steps; +an audit or compiler failure stops the remaining steps. + +The suite uses Bun 1.4.4 (`package.json`'s `testRunnerBun`) while the shipped runtime is 1.4.4. +`scripts/test.ts` finds a 1.4.4 binary on PATH or in `~/.bun/bin`, or uses `OCX_TEST_RUNNER_BUN`. Install that version locally if it is missing; the resolver never downloads it. +The roles remain independently checked even when their versions match. Release selection requires +a successful full cross-platform `lane=all` dispatch on the exact candidate SHA. Run `bun run test` by default. If a full run is disproportionately expensive for the task size, available machine resources, or concurrent worktrees, you must at least run focused regression tests @@ -83,9 +94,10 @@ cd docs-site && bun install && bun dev ## Docs publishing -The public docs publish to GitHub Pages at . The -`.github/workflows/deploy-docs.yml` workflow runs on `main` pushes that touch `docs-site/**` or the -workflow itself, builds `docs-site`, and deploys the generated site. Before pushing docs changes, +The public docs publish to GitHub Pages at . A maintainer manually +runs `.github/workflows/deploy-docs.yml` from `dev`; it builds the latest published stable release, +or a specified published stable tag, at its resolved commit. Deployment is separate from npm release. +Before pushing docs changes, run: ```bash @@ -98,14 +110,16 @@ bun run build GitHub Actions intentionally stay small: -- **Cross-platform CI** (`.github/workflows/ci.yml`) runs on pull requests and `main` pushes that - touch runtime, tests, package, script, TypeScript, or workflow files. Its Bun matrix covers Linux, - Windows, and macOS with install, typecheck, tests, privacy scan, a release-helper build smoke, GUI - build, and `ocx help`. A second three-OS lane proves npm global install works without a separately - installed Bun by using the package's bundled runtime. -- **Release** (`.github/workflows/release.yml`) is manual. It does not act as a second full CI - pipeline; before dry-run or publish it requires the exact release commit (`GITHUB_SHA`) to already - have a successful Cross-platform CI run. +- **Cross-platform CI** (`.github/workflows/ci.yml`) runs the scoped Linux checks on pull + requests; the full Linux, macOS and Windows matrix runs by manual dispatch from `dev` with + `lane=all`. A PR green is not full-platform release evidence. After a batch of merges, + maintainers run one full dispatch on `dev` rather than one per PR. +- **Release** (`.github/workflows/release.yml`) is a manual `dev` workflow that selects an exact + source with qualifying full-lane evidence, stamps the version in build checkouts, and checks + npm and GitHub release history before it publishes. Publication stays off until the maintainer + completes the cutover checks and enables it; an interrupted run is recovered by an + operator-attested resume that never republishes an npm version. See + [`MAINTAINERS.md`](https://github.com/lidge-jun/opencodex/blob/dev/MAINTAINERS.md) for the current procedure. - **Stale needs-info** (`.github/workflows/stale-needs-info.yml`) runs daily on the default branch. Open issues labeled `needs-info` with no activity for 14 days get a warning; after 7 more idle days they close as not planned. Any update clears the stale warning. To keep long-lived work open, @@ -120,33 +134,15 @@ GitHub Actions intentionally stay small: form already seeds `documentation`). Maintainers can re-apply area labels to all open issues with workflow_dispatch `backfill_open_areas` after the workflow is on the default branch. -Use the helper for releases: - - -Before running the helper, choose the intended release version and dispatch -`.github/workflows/dev-version-bump.yml` from the default branch with -`intended-version=` and `mode=pre-move`. Review and merge the PR it opens -into `dev`, then promote to `main` or `preview` and run the helper. If `dev` already -outranks the intended version, the workflow reports `changed=false` and no bump PR -is needed. Publishing still requires successful CI on the exact release commit. - -```bash -bun run release # commits/pushes the bump; publish workflow is dry-run by default -bun run release --bump minor # derive the next patch, minor, or major version from tags and npm channels -bun run release --publish # publish after the CI-gated dry run is understood -bun run release:watch # watch the newest Release workflow run -``` - -`--bump patch|minor|major` is an alternative to an explicit version. Once a preview tag opens a -higher version core, `--bump patch` refuses to continue the older stable patch line; ship that fix -in the open preview core instead. +The legacy version-bump and promotion procedure is not the new release path. Do not use it +as a substitute while the new publication gates remain unresolved. ## Branches -- `dev` — the only integration target. Open your pull request here. -- `main` — releases only. It moves by maintainer-controlled promotion from - `dev`; do not open feature pull requests against it. -- `preview` — the prerelease train. +- `dev` — the only integration target and the repository default branch. Open your pull + request here. +- `main` and `preview` were deleted once the single-branch model was in place. Their released + history remains reachable through tags; neither is an integration or promotion target. The `dev2-go` line that carried the Go native port has been retired, and the dual-track carry policy with it. Its history is published read-only at @@ -159,27 +155,29 @@ description. ## Pull requests -- Target **`dev`**. Do not open feature or fix pull requests against **`main`**. -- Branch from the current **`dev`** tip, not from **`main`**. The required **`enforce-target`** check rejects heads whose merge base sits on the **`main`** tip while the branch is far behind the pull request base (the failure mode seen in #644). +- Target **`dev`**. The required **`enforce-target`** check rejects any other base + except a stacked child targeting another open pull request's head. +- Branch from the current **`dev`** tip. A head that drifts too far behind `dev` + has its review-readiness latest-dev claim unticked rather than being rejected. - Write a real description: a **Summary** of what changed and why, plus a **Test plan** (or equivalent substance). Empty bodies, placeholder-only text, and descriptions that use escaped `\n` instead of real line breaks fail the check. - If the pull request changes files under `gui/`, include a screenshot of the UI change in the description; the `enforce-target` check re-runs on description edits until the screenshot is present. Drag the image into the description editor rather than committing it: an image on your branch rides the squash merge into `dev`. Maintainers uploading from the command line use the `pr-assets` branch and link by commit SHA. -- Workflow changes in this repository use **`pull_request_target`**. Updated enforcement logic applies only after the workflow is promoted to the repository default branch — the same operational caveat documented in #631. +- Workflow changes in this repository use **`pull_request_target`**. Updated enforcement logic applies only after the workflow reaches the repository default branch — the same operational caveat documented in #631. ## Project maintainers The current maintainers, their responsibilities, and the review and merge policy are documented in -[`MAINTAINERS.md`](https://github.com/lidge-jun/opencodex/blob/main/MAINTAINERS.md). GitHub review +[`MAINTAINERS.md`](https://github.com/lidge-jun/opencodex/blob/dev/MAINTAINERS.md). GitHub review ownership for the repository and security-sensitive paths is declared in `.github/CODEOWNERS`. Contributor pull requests normally need a maintainer's approval. A current maintainer with GitHub `maintain` or `admin` access may explicitly integrate a PR into `dev`, including their own, without a second maintainer approval. The decision and exact-head verification must be recorded; CI, security review and outstanding maintainer objections still apply. This exception -does not change `main`/`preview` review rules or allow direct pushes, force-pushes or deletion. +does not allow direct pushes, force-pushes or deletion. ## Conventions -- **ES Modules only** (`import`/`export`), TypeScript, `strict` mode. Keep `bun x tsc --noEmit` clean. +- **ES Modules only** (`import`/`export`), TypeScript, `strict` mode. Keep `bun run typecheck` clean. - **~500 lines per file max** — split by responsibility (the `web-search/` and `vision/` sidecars are good examples of small, focused modules behind a single `index.ts`). - **Handle async errors at boundaries** — sidecars never throw into the request path; they degrade to diff --git a/docs-site/src/content/docs/contributing/pr-quality.md b/docs-site/src/content/docs/contributing/pr-quality.md index bac390abde..2716c84122 100644 --- a/docs-site/src/content/docs/contributing/pr-quality.md +++ b/docs-site/src/content/docs/contributing/pr-quality.md @@ -90,14 +90,9 @@ tells you exactly what to change: lockfile changed without its manifest each need an explicit approval label. A comment-only change to a source file is not a behavior change and owes no test. -- **Cross-platform CI.** The suite runs sharded on Linux and in full on macOS for - every pull request. Windows runs at the shipping boundary — on promotion to - `main` or `preview` — so a slow or flaky Windows runner cannot decide when your - pull request turns green. - This runs for **every** pull request, whatever its base branch — including a - stacked child whose base is another open PR's head. The `paths:` filter, not - the base branch, decides whether the jobs run at all: a PR touching only docs - or `devlog/` queues nothing. +- **Cross-platform CI.** Pull requests run scoped Linux checks. Full Linux, macOS and Windows + coverage is a manual `lane=all` dispatch on `dev` after a batch of merges; a green PR is not + full-platform release evidence. Docs changes receive a scoped build gate. - **Type label.** The `label` check derives `bug` / `enhancement` / `documentation` / `chore` from your PR title. A title without a recognisable @@ -114,7 +109,7 @@ right; say why when it is wrong. It does not block a merge. `enforce-target` and `label` use trusted default-branch automation. The PR gate runs on `pull_request_target` and on CodeRabbit `status` events, both loaded from the repository default branch; the write-capable behavior therefore -changes only after the gate revision is promoted to `main`. The cross-platform +changes only after the gate revision reaches the repository default branch. The cross-platform CI workflow runs on `pull_request` and takes effect as soon as it is on the branch being targeted. diff --git a/docs-site/src/content/docs/dashboard.mdx b/docs-site/src/content/docs/dashboard.mdx new file mode 100644 index 0000000000..a72b6510f6 --- /dev/null +++ b/docs-site/src/content/docs/dashboard.mdx @@ -0,0 +1,15 @@ +--- +title: "Usage Dashboard" +description: "Project-wide anonymous usage statistics, contribution activity, provider and model breakdowns, and download metrics for opencodex." +template: splash +tableOfContents: false +editUrl: false +lastUpdated: false +--- + +import TelemetryDashboard from '../../components/TelemetryDashboard.astro'; +import TelemetryLeaderboard from '../../components/TelemetryLeaderboard.astro'; + + + + diff --git a/docs-site/src/content/docs/fr/contributing.md b/docs-site/src/content/docs/fr/contributing.md index 279b582c75..8a041cba0d 100644 --- a/docs-site/src/content/docs/fr/contributing.md +++ b/docs-site/src/content/docs/fr/contributing.md @@ -15,7 +15,7 @@ bun install bun run setup:hooks # retirer les anciens hooks gérés pre-push et post-merge bun run dev:proxy # proxy API in dev mode bun run dev:gui # dashboard dev server (another terminal) -bun run typecheck # bun x tsc --noEmit +bun run typecheck # bun check --no-script --noEmit bun run test # suite complète (par défaut) ``` @@ -60,33 +60,20 @@ Le site de documentation que vous lisez se trouve dans `docs-site/` (Astro + Sta cd docs-site && bun install && bun dev ``` -## Publication de la documentation +## CI / Release / Pages -La documentation publique est publiée sur GitHub Pages à l’adresse . Le workflow -`.github/workflows/deploy-docs.yml` s’exécute lors des push sur `main` qui modifient `docs-site/**` ou le -workflow lui-même. Il construit `docs-site` et déploie le site généré. Avant de pousser une modification, -exécutez : +Consultez la [version anglaise canonique](/contributing/) pour la publication, la CI, les versions et les branches. -```bash -cd docs-site -bun install --frozen-lockfile -bun run build -``` -## CI et versions +La branche `dev2-go`, qui portait l’ancien runtime natif Go, a été retirée, tout comme la politique à deux +lignes d’exécution. Son historique est publié en lecture seule sur +[lidge-jun/opencodex-go-archive](https://github.com/lidge-jun/opencodex-go-archive). +Le TypeScript natif pour Bun sur `dev` est désormais l’unique ligne d’exécution. + +Les pull requests de rebase sont les bienvenues. Rebaser une branche ancienne sur la tête actuelle constitue +une contribution normale ; indiquez les commits sources dans la description. -Les workflows GitHub Actions restent volontairement limités : -- **CI multiplateforme** (`.github/workflows/ci.yml`) s’exécute sur toutes les pull requests et sur les push vers - `dev`, `preview` et `main`. Un filtre interne limite les tâches coûteuses aux changements qui touchent le runtime, - les tests, les paquets, les scripts, TypeScript ou les workflows, tout en produisant un contrôle agrégé explicite - pour les PR documentaires. La suite principale est répartie sur Linux et exécutée intégralement sur macOS ; sa - voie Windows, actuellement non bloquante, ne s’exécute que sur lancement manuel avec `workflow_dispatch`. Des - tests ciblés du trousseau système et, lorsque le paquet change, de l’installation npm globale couvrent néanmoins - les trois systèmes. Cette dernière voie vérifie l’installation sans Bun préinstallé grâce au runtime fourni. -- **Version** (`.github/workflows/release.yml`) est un workflow manuel. Il ne remplace pas une seconde CI complète : - avant une simulation ou une publication, il exige qu’une CI multiplateforme ait déjà réussi pour le commit - exact de la version (`GITHUB_SHA`). - **Expiration des demandes d’informations** (`.github/workflows/stale-needs-info.yml`) s’exécute chaque jour sur la branche par défaut. Une issue ouverte portant `needs-info` sans activité depuis 14 jours reçoit un avertissement, puis est fermée après 7 jours supplémentaires d’inactivité. Toute mise à jour efface @@ -101,49 +88,11 @@ Les workflows GitHub Actions restent volontairement limités : `documentation`. Après promotion du workflow vers la branche par défaut, les responsables peuvent réappliquer les zones à toutes les issues ouvertes avec le workflow_dispatch `backfill_open_areas`. -Utilisez l'assistant pour les versions : - - -Avant d’exécuter le helper, choisissez la version prévue et lancez -`.github/workflows/dev-version-bump.yml` depuis la branche par défaut avec -`intended-version=` et `mode=pre-move`. Relisez et fusionnez la PR créée -vers `dev`, puis promouvez vers `main` ou `preview` avant de lancer le helper. -Si `dev` dépasse déjà la version prévue, le workflow renvoie `changed=false` et -aucune PR de version n’est nécessaire. La publication exige toujours une CI -réussie sur le commit exact de la release. - -```bash -bun run release # commits/pushes the bump; publish workflow is dry-run by default -bun run release --bump minor # calcule la prochaine version patch, minor ou major depuis les tags et canaux npm -bun run release --publish # publish after the CI-gated dry run is understood -bun run release:watch # watch the newest Release workflow run -``` - -`--bump patch|minor|major` remplace une version explicite. Dès qu’un tag de préversion ouvre un -core supérieur, `--bump patch` refuse de prolonger l’ancienne ligne stable ; publiez plutôt le -correctif dans le core de préversion ouvert. - -## Branches - -- `dev` — l’unique branche d’intégration. Ciblez-la avec votre pull request. -- `main` — réservée aux versions. Elle avance par promotion de `dev`, sous le contrôle des responsables ; - n’y ouvrez aucune pull request de fonctionnalité. -- `preview` — la branche des préversions. - -La branche `dev2-go`, qui portait l’ancien runtime natif Go, a été retirée, tout comme la politique à deux -lignes d’exécution. Son historique est publié en lecture seule sur -[lidge-jun/opencodex-go-archive](https://github.com/lidge-jun/opencodex-go-archive). -Le TypeScript natif pour Bun sur `dev` est désormais l’unique ligne d’exécution. - -Les pull requests de rebase sont les bienvenues. Rebaser une branche ancienne sur la tête actuelle constitue -une contribution normale ; indiquez les commits sources dans la description. - ## Demandes d'extraction -- Ciblez **`dev`**. N’ouvrez aucune pull request de fonctionnalité ou de correctif contre **`main`**. -- Partez de la tête actuelle de **`dev`**, pas de **`main`**. Le contrôle obligatoire **`enforce-target`** - rejette les branches dont la base de fusion se trouve sur la tête de **`main`** alors qu’elles sont très en - retard sur la branche cible, le mode d’échec observé dans #644. +- Ciblez **`dev`**, qui est aussi la branche par défaut du dépôt. **`main`** et **`preview`** ont été + supprimées une fois le modèle à branche unique en place. Le contrôle obligatoire **`enforce-target`** + rejette les pull requests dont la base n’est pas **`dev`** (les PR enfants empilées font exception). - Rédigez une vraie description : un **Résumé** de la modification et de sa raison, ainsi qu’un **Plan de test** ou un contenu équivalent. Les corps vides, les textes composés seulement d’espaces réservés et les descriptions contenant des `\n` échappés au lieu de véritables sauts de ligne échouent au contrôle. @@ -158,12 +107,12 @@ une contribution normale ; indiquez les commits sources dans la description. ## Responsables du projet Les responsables actuels, leurs attributions et les règles de revue et de fusion sont décrits dans -[`MAINTAINERS.md`](https://github.com/lidge-jun/opencodex/blob/main/MAINTAINERS.md). La propriété GitHub +[`MAINTAINERS.md`](https://github.com/lidge-jun/opencodex/blob/dev/MAINTAINERS.md). La propriété GitHub du dépôt et des chemins sensibles du point de vue de la sécurité est déclarée dans `.github/CODEOWNERS`. ## Conventions -- **Modules ES uniquement** (`import`/`export`), TypeScript, mode `strict`. Gardez `bun x tsc --noEmit` propre. +- **Modules ES uniquement** (`import`/`export`), TypeScript, mode `strict`. Gardez `bun run typecheck` propre. - **Environ 500 lignes au maximum par fichier** — répartissez le code par responsabilité. Les services auxiliaires `web-search/` et `vision/` sont bons exemples de petits modules ciblés derrière un seul `index.ts`). - **Gérer les erreurs asynchrones aux frontières** — les services auxiliaires ne propagent jamais d’exception dans le diff --git a/docs-site/src/content/docs/fr/contributing/pr-quality.md b/docs-site/src/content/docs/fr/contributing/pr-quality.md index 0711cb3b0e..d2c2047dfe 100644 --- a/docs-site/src/content/docs/fr/contributing/pr-quality.md +++ b/docs-site/src/content/docs/fr/contributing/pr-quality.md @@ -79,15 +79,7 @@ Trois contrôles déterministes précèdent la revue humaine. Chaque message d à un commentaire dans un fichier source ne change pas le comportement et n’exige aucun nouveau test de régression. La [politique de test locale](/fr/contributing/) reste applicable. -- **CI multiplateforme.** Pour les changements concernés, la suite est fragmentée sous Linux et exécutée - intégralement sous macOS pour chaque pull request. La voie Windows principale ne s’exécute actuellement que - sur lancement manuel avec `workflow_dispatch` ; elle ne bloque ni les PR ni les promotions. Des tests ciblés - du trousseau système et de l’installation npm globale peuvent toutefois inclure Windows. - - Le workflow est créé pour **toutes** les pull requests, quelle que soit leur branche de base, y compris une PR - enfant empilée dont la base est la tête d’une autre PR ouverte. Le filtre interne des changements, et non la - branche de base, décide quelles tâches coûteuses s’exécutent ; une PR limitée à la documentation reçoit tout - de même un contrôle agrégé explicite. +- **CI.** Consultez la [version anglaise canonique](/contributing/) pour la publication, la CI, les versions et les branches. - **Label de type.** Le contrôle `label` déduit `bug`, `enhancement`, `documentation` ou `chore` du titre de la PR. Si le titre ne possède aucun préfixe reconnu, par exemple `stack 3/5: …`, le contrôle examine les commits, @@ -102,8 +94,7 @@ un constat est erroné lorsqu’il l’est. CodeRabbit ne bloque pas une fusion. `enforce-target` et `label` utilisent une automatisation fiable chargée depuis la branche par défaut. Le contrôle de PR s’exécute sur les événements `pull_request_target` et `status` de CodeRabbit, tous deux chargés depuis la -branche par défaut du dépôt. Le comportement disposant de droits d’écriture ne change donc qu’après la promotion -de la révision du contrôle vers `main`. Le workflow de CI multiplateforme s’exécute sur `pull_request` et prend +branche par défaut du dépôt. Le comportement disposant de droits d’écriture ne change donc qu’après l’arrivée de la révision du contrôle sur la branche par défaut. Le workflow de CI multiplateforme s’exécute sur `pull_request` et prend effet dès qu’il se trouve sur la branche ciblée. ## Surfaces nécessitant un parrainage diff --git a/docs-site/src/content/docs/fr/getting-started/for-agents.md b/docs-site/src/content/docs/fr/getting-started/for-agents.md index 3e96290306..671d1d01e0 100644 --- a/docs-site/src/content/docs/fr/getting-started/for-agents.md +++ b/docs-site/src/content/docs/fr/getting-started/for-agents.md @@ -13,7 +13,7 @@ disponible pour une configuration interactive ; consultez le [tableau de bord w Installez le package publié et confirmez que `ocx` est sur `PATH` : ```bash -npm install -g @bitkyc08/opencodex +npm install -g --allow-scripts=bun @bitkyc08/opencodex ocx --version ``` diff --git a/docs-site/src/content/docs/fr/getting-started/installation.md b/docs-site/src/content/docs/fr/getting-started/installation.md index 65fb3d9113..456907e4e9 100644 --- a/docs-site/src/content/docs/fr/getting-started/installation.md +++ b/docs-site/src/content/docs/fr/getting-started/installation.md @@ -19,7 +19,7 @@ ChatGPT lorsqu’un modèle routé en a besoin. ## Installer ```bash -npm install -g @bitkyc08/opencodex +npm install -g --allow-scripts=bun @bitkyc08/opencodex ``` :::note[npm a-t-il bloqué le script postinstall de bun ?] @@ -52,7 +52,7 @@ les entrées du catalogue n’accordent aucun accès par elles-mêmes. N’utili tester des versions opencodex non encore publiées : ```bash -npm install -g @bitkyc08/opencodex@preview +npm install -g --allow-scripts=bun @bitkyc08/opencodex@preview ocx update --tag preview ``` diff --git a/docs-site/src/content/docs/fr/getting-started/quickstart.md b/docs-site/src/content/docs/fr/getting-started/quickstart.md index a3eb2f9fea..bf01104632 100644 --- a/docs-site/src/content/docs/fr/getting-started/quickstart.md +++ b/docs-site/src/content/docs/fr/getting-started/quickstart.md @@ -1,9 +1,9 @@ --- title: Démarrage rapide -description: Configurez votre premier fournisseur et acheminez OpenAI Codex via opencodex en trois commandes. +description: "Installez opencodex, ajoutez votre premier fournisseur et connectez votre outil de programmation : Codex, Claude Code, Claude Desktop, Grok Build ou un autre outil pris en charge." --- -Ce guide part d’une installation neuve et vous conduit jusqu’à l’exécution de Codex sur un modèle autre qu’OpenAI. +Ce guide vous mène d’une nouvelle installation à la première requête de votre outil de programmation. Les étapes 1 et 2 sont communes ; l’étape 3 propose une branche par outil. La [page des clients pris en charge](/fr/reference/client-support/) présente les outils et leurs connexions. ## 1. Exécutez l'assistant de configuration @@ -13,7 +13,7 @@ ocx init `ocx init` vous accompagne dans les étapes suivantes : -1. **Choix d’un fournisseur** — sélectionnez l’un des 104 préréglages intégrés au registre, ou `custom` pour saisir une +1. **Choix d’un fournisseur** — sélectionnez l’un des 107 préréglages intégrés au registre, ou `custom` pour saisir une URL de base et un adaptateur. 2. **Clé API** — collez une clé ou référencez une variable d’environnement telle que `${ANTHROPIC_API_KEY}`. 3. **Modèle par défaut** — pour les fournisseurs clés, locaux et personnalisés, acceptez le préréglage ou saisissez un identifiant de modèle. @@ -58,9 +58,13 @@ ocx status ocx gui # ouvre le tableau de bord sur le port actif ``` -## 3. Utiliser Codex +## 3. Connectez votre outil -Codex parle maintenant à opencodex de manière transparente : +Choisissez la branche correspondant à votre outil. Vous pouvez en connecter plusieurs : ils partagent les mêmes fournisseurs et modèles. + +### Codex + +Si vous avez accepté l’invite Codex à l’étape 1, Codex communique maintenant avec opencodex de manière transparente. Si vous avez refusé cette invite ou si la configuration s’est arrêtée parce qu’une configuration existait déjà, activez le commutateur Codex sur la page **Connect** du tableau de bord avant de lancer Codex ; [Intégration Codex](/fr/guides/codex-integration/) explique les modifications et leur restauration. ```bash codex "Refactor this function for readability" @@ -73,6 +77,42 @@ codex -m "anthropic/claude-opus-5" "Explain this stack trace" codex -m "ollama-cloud/glm-5.2" "Write a SQL migration" ``` +### Claude Code + +Avec le CLI `claude` installé : + +```bash +ocx claude +``` + +`ocx claude` démarre le proxy s’il ne fonctionne pas et lance Claude Code avec un environnement dirigé vers opencodex. Les arguments supplémentaires sont transmis. Consultez [Claude Code](/fr/guides/claude-code/) pour les valeurs par défaut des niveaux, les autres lanceurs et la désactivation. + +### Claude Desktop + +```bash +ocx claude desktop +``` + +Lors d’une nouvelle installation, cette commande configure le profil de passerelle pour toute l’application. Une installation utilisant déjà le mode first-party le conserve ; exécutez `ocx claude desktop apply --gateway` pour changer explicitement. Le mode first-party conserve claude.ai pour Desktop et ne route que son onglet Code ; consultez la section sur les modes Claude Desktop dans [Claude Code](/fr/guides/claude-code/). + +Quittez complètement puis rouvrez Claude Desktop après un changement de mode. + +### Grok Build + +Sur une écoute locale, si `~/.grok` existe, `ocx start` enregistre les modèles visibles dans `~/.grok/config.toml`. Choisissez un modèle `ocx-*` dans Grok Build. Les configurations distantes et le bloc géré sont décrits dans [Grok Build](/fr/guides/grok-build/). + +Après avoir ajouté des fournisseurs ou des modèles, lancez `ocx ensure` ou redémarrez le proxy pour que Grok Build les voie. + +### Autres outils + +Les outils avec intégration gérée (OpenCode, Pi, Qoder, WorkBuddy, Kilo, Cline, T3 Code et d’autres) se connectent depuis la page **Connect** du tableau de bord ou avec : + +```bash +ocx integration client enable --client +``` + +Les fichiers de configuration et les délais de prise d’effet sont décrits dans [Intégrations](/fr/guides/integrations/). Tout autre outil acceptant un point de terminaison personnalisé peut utiliser l’URL de base compatible OpenAI `http://localhost:10100/v1` ou l’URL de base Anthropic `http://localhost:10100`. + ## Choisissez des modèles de sous-agents (facultatif) Une nouvelle configuration propose cinq modèles natifs dans le sélecteur de sous-agents de Codex : `gpt-5.5`, diff --git a/docs-site/src/content/docs/fr/guides/claude-code.md b/docs-site/src/content/docs/fr/guides/claude-code.md index 0405b2807d..244e61e86e 100644 --- a/docs-site/src/content/docs/fr/guides/claude-code.md +++ b/docs-site/src/content/docs/fr/guides/claude-code.md @@ -15,8 +15,9 @@ ajouter un compte). Par défaut, chaque requête utilise uniquement le compte ** Un groupe de comptes Claude **expérimental et facultatif** (`anthropicAccountPool.enabled`) ajoute l'affinité de session et la sélection des nouvelles sessions basée sur l'usage entre ces comptes OAuth. Il ne contrôle **pas** le basculement sur 429 : dès que deux comptes utilisables sont enregistrés, une requête limitée bascule vers un autre compte que l'option soit activée ou non, et cela ne peut pas être désactivé. Pour les **nouvelles** sessions uniquement, `anthropicAccountPool.strategy` sélectionne un compte éligible : `quota` (par défaut) -choisit la plus faible utilisation connue dans la fenêtre configurée par `anthropicAccountPool.quotaWindow` -(`five-hour` par défaut, `weekly` ou `max-utilization`) lorsqu'elle dépasse `autoSwitchThreshold` ; `round-robin` +conserve le compte actif jusqu'à ce que son utilisation dans la fenêtre définie par +`anthropicAccountPool.quotaWindow` (`five-hour` par défaut, `weekly` ou `max-utilization`) atteigne +`autoSwitchThreshold` (80 par défaut), puis passe au compte le moins utilisé, en privilégiant les comptes encore sous leur propre seuil ; `round-robin` répartit les sessions uniformément (`stickyLimit`, `1` par défaut) ; `fill-first` utilise le compte actif jusqu'à un délai de récupération, une réauthentification ou le seuil, puis passe au suivant. Cette fonction est **désactivée par défaut** et reste expérimentale. @@ -34,8 +35,8 @@ consultez les conditions actuelles d'Anthropic. Comportement lorsque cette option est activée : - Un **429** en amont place le compte en temporisation selon `Retry-After` lorsqu'il est présent, ou selon un délai de repli, - efface ses affinités et peut faire basculer la requête vers un autre compte admissible, dans les limites prévues. -- L'affinité est **locale au processus** et disparaît au redémarrage du proxy. + et peut faire basculer la requête vers un autre compte admissible, dans les limites prévues. Seul un refus de quota partagé efface ses affinités ; une limitation temporaire les conserve. +- L'affinité survit au redémarrage dans le même répertoire de configuration et la même instance fournisseur (24 heures d'inactivité, 2 000 liaisons au maximum). Le fichier privé ne contient que des empreintes de session et d'identité de connexion, jamais de clé de session brute ni de jeton. Les anciens comptes sans identité persistante restent locaux au processus jusqu'à leur prochaine connexion. Le renouvellement du jeton conserve la liaison ; une nouvelle connexion, la suppression, la pause, une réauthentification requise ou une sélection manuelle pendant l'exécution l'invalident. Un détour temporaire dû à une limitation de débit conserve la liaison initiale. - Les erreurs de renouvellement du jeton conservent la règle `needsReauth`. Un 403 confirmé lié à un abonnement ou à la facturation du compte peut déclencher un basculement avant la sortie, avec une temporisation selon `Retry-After` ou de dix minutes. Un refus d’autorisation ordinaire reste terminal. Voir la [reprise des comptes](/guides/claude-code/). - Si chaque compte éligible est en temporisation, le proxy renvoie **429** (et non 401) avec `Retry-After` lorsqu'il est connu. @@ -64,7 +65,7 @@ ocx claude | `ANTHROPIC_DEFAULT_{OPUS,SONNET,FABLE}_MODEL` | `claudeCode.tierModels.*` ; lors d'un lancement par abonnement, si non défini, `claude-opus-5-5[1m]` / `claude-sonnet-5-5[1m]` / `claude-fable-5-1[1m]` natif | | `ANTHROPIC_DEFAULT_{OPUS,SONNET,FABLE,HAIKU}_MODEL_NAME` | Libellé `/model` d'un emplacement de niveau qu'OpenCodex règle sur un alias routé (par exemple `ocx-claude-native--gpt-6.1-sol` → `gpt-6.1-sol (native)`). La même paire est écrite dans l'environnement système launchd et dans le hook shell. L'identifiant du modèle reste l'alias. Un emplacement ou un libellé que vous définissez vous-même n'est pas modifié | | `CLAUDE_CODE_ALWAYS_ENABLE_EFFORT` | `1` lorsque `alwaysEnableEffort` est activé (conditionnel) | -| `ENABLE_TOOL_SEARCH` | `claudeCode.toolSearch` lorsqu'il est défini (conditionnel ; désactivé par défaut) | +| `ENABLE_TOOL_SEARCH` | `claudeCode.toolSearch` lorsqu'il est défini (conditionnel ; non injecté par défaut, la valeur par défaut de Claude Code s’applique) | | `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | Remplacement du contexte hérité lorsque `maxContextTokens` est défini (conditionnel) | Les variables que vous exportez vous-même gagnent toujours. Les arguments supplémentaires passent par : `ocx claude -p "hello"`. @@ -200,6 +201,8 @@ quittez complètement puis rouvrez Claude Desktop. Le mode picker fait partie de first-party : le [risque pour le compte du mode first-party](#first-party-sur-demande) s'applique donc aussi à ce mode. +Avant la première réponse du serveur amont, un téléversement picker sans progression pendant 60 secondes est fermé. Une expiration interrompt le téléversement sans réponse de succès ; en HTTP/2, seul le flux concerné est réinitialisé. Ce délai d’inactivité est suspendu lorsque le serveur amont exerce une contre-pression et supprimé dès la fin du téléversement ou la première réponse amont. Ce mécanisme de surveillance de l’inactivité n’ajoute aucune limite à la durée totale du téléversement ; les limites existantes de l’environnement d’exécution et du protocole restent applicables. Ce délai d’inactivité ne s’applique pas aux flux de réponse. + ### Utiliser les modèles opencodex depuis l'onglet Code de Desktop (associations first-party) En mode first-party, le sélecteur de modèles de l'onglet Code appartient à claude.ai : ses lignes @@ -488,9 +491,7 @@ Trois états de configuration : La valeur de compactage est réglable dans **Connexion → Claude**. **Avertissement :** une valeur supérieure à la fenêtre réelle d'un modèle rend ce modèle inutilisable : les tours échouent avant que le résumé puisse se déclencher. -La normalisation des erreurs de dépassement de contexte utilise uniquement les 65 536 premières unités de code UTF-16 du message du fournisseur. -Les diagnostics ou nombres de jetons situés après cette limite peuvent disparaître sans marqueur de troncature. -Consultez le [guide anglais](/guides/claude-code/#auto-context-big-context-models-without-the-200k-ceiling) pour les limites exactes et les conditions de reprise des nombres de jetons. +La normalisation des réponses d'erreur Messages utilise un texte fixe, sans conserver le texte du fournisseur ni les nombres de jetons. Un dépassement de contexte reconnu renvoie `prompt is too long: The request exceeds the model's context window.`. Dans un flux, un bloc dont le premier champ est l'événement error est conservé jusqu'à 1 Mio ; au-delà, une erreur fixe sans phrase de compaction est renvoyée. Consultez le [guide anglais](/guides/claude-code/#auto-context-big-context-models-without-the-200k-ceiling) pour la portée et les deux exceptions. Les modèles Anthropic natifs dont le contexte est inférieur à 1M ne sont jamais marqués automatiquement. Une fenêtre de compactage que vous exportez vous-même reste prioritaire pour le marquage des variables de lancement ; le proxy s'appuie sur votre valeur pour déterminer les modèles qui peuvent recevoir le marqueur sans risque. @@ -661,7 +662,7 @@ Le proxy traduit chaque requête Anthropic Messages API au format Codex Response | Assistant `tool_use` | `function_call` (`input` → JSON-stringifié `arguments`) | | Utilisateur `tool_result` | `function_call_output` (`is_error` → préfixe `[tool error]`) | | Relecture de `thinking` / `redacted_thinking` | Éléments `reasoning` avec enveloppes `ocxr1` bornées pour les signatures et les contenus masqués | -| Outils fonctionnels | `{type: "function"}` (`web_search*` → `{type: "web_search"}`) | +| Outils fonctionnels | `{type: "function"}` (`web_search*` → `{type: "web_search"}`) La recherche hébergée avec `allowed_domains`, `blocked_domains` ou `user_location` est omise sur les routes Responses/Chat traduites ; la forcer renvoie 400. Les définitions de fonctions `defer_loading` valides restent appelables comme fonctions ordinaires. Voir les [limites de traduction](/guides/claude-code/#search-restrictions-and-deferred-tools-on-translated-routes). | | `tool_choice` | `auto`→`auto`, `none`→`none`, `any`→`required`, fonction nommée→`{type:"function",name}`, hébergée WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | @@ -692,7 +693,7 @@ Sur l’adaptateur Anthropic prévu, les blocs signés non masqués (y compris t **Taxonomie des erreurs :** 400 `invalid_request_error`, 401 `authentication_error`, 402 `billing_error`, 403 `permission_error`, 404 `not_found_error`, 409 `conflict_error`, 413 `request_too_large`, 429 `rate_limit_error`, 504 `timeout_error`, 529 `overloaded_error`, -autre 5xx `api_error`. `Retry-After` est conservé. +autre 5xx `api_error`. `Retry-After` est envoyé en secondes entières (une date HTTP devient le nombre de secondes restantes), plafonné à huit jours. ## Mise en cache des prompts et utilisation des jetons @@ -700,9 +701,9 @@ autre 5xx `api_error`. `Retry-After` est conservé. et l'avant-dernier message utilisateur, ainsi que le champ `cache_control` automatique de premier niveau. Les tours stables atteignent généralement un taux d'accès au cache d'environ 99.9 %. -**Routage OpenAI/ChatGPT natif :** produit une valeur `prompt_cache_key` propre à la session, à partir de -`metadata.user_id` lorsqu'il est présent ou, à défaut, d'un hachage du contenu système, ainsi qu'un en-tête `session_id` -pour l'affinité du cache. La clé de cache inclut le modèle et l'intégralité des schémas d'outils. +**Routage OpenAI/ChatGPT natif :** produit une valeur `prompt_cache_key`, à partir de +`metadata.user_id` lorsqu'il s'agit d'une chaîne ou, à défaut, d'un hachage du contenu système, ainsi qu'un en-tête `session_id` +pour l'affinité du cache, cet en-tête provenant uniquement d'une identité de session et jamais de la clé de repli partagée. La clé de repli dérivée du contenu système (utilisée seulement si un contenu système est présent) inclut aussi le modèle et l'intégralité des schémas d'outils. **Calcul des jetons d'entrée :** Anthropic soustrait `cached_tokens` et `cache_write_tokens` de `input_tokens`, les exposant comme `cache_read_input_tokens` et `cache_creation_input_tokens`. diff --git a/docs-site/src/content/docs/fr/guides/codex-app-models.md b/docs-site/src/content/docs/fr/guides/codex-app-models.md index 0e69068a71..e6a653f337 100644 --- a/docs-site/src/content/docs/fr/guides/codex-app-models.md +++ b/docs-site/src/content/docs/fr/guides/codex-app-models.md @@ -3,6 +3,8 @@ title: Sélecteur de modèles de Codex App description: Comment les modèles opencodex apparaissent dans Codex App, Codex CLI et Codex TUI par l'intermédiaire du catalogue Codex partagé. --- +Par défaut : `false`. Avec `"omitDisabledNativeModels": true` dans `config.json`, puis `ocx sync`, les lignes natives désactivées sont omises du catalogue, du cache et de la découverte HTTP au format Codex. Le modèle d’héritage natif validé avant omission conserve les métadonnées des lignes routées. Les requêtes directes gardent leur routage habituel. Les descriptions de masquage ci-dessous concernent le comportement par défaut. + opencodex ne modifie pas Codex App. Il écrit la même configuration et le même catalogue de modèles Codex que ceux utilisés par Codex CLI et TUI. Le serveur d'application lit cet état partagé, mais certaines versions de Codex Desktop appliquent dans le moteur de rendu une seconde liste d'autorisation distante et peuvent @@ -138,11 +140,12 @@ approximation fondée sur un ancien modèle d'entrée. | Route | Identifiants du sélecteur et métadonnées du catalogue | | --- | --- | -| Connexion Codex (lignes qualifiées par compte désactivées) | Identifiants natifs non qualifiés comme `gpt-5.6-sol`, `gpt-5.6-terra` et `gpt-5.6-luna` ; Pool ou Direct est choisi avec `codexAccountMode`. Les lignes GPT-5.6 utilisent une fenêtre de catalogue de 372 000 jetons. | +| Connexion Codex (lignes qualifiées par compte désactivées) | Identifiants natifs non qualifiés comme `gpt-5.6-sol`, `gpt-5.6-terra` et `gpt-5.6-luna` ; Pool ou Direct est choisi avec `codexAccountMode`. Les lignes GPT-5.6 utilisent une fenêtre de catalogue de 372 000 jetons. `gpt-6.1-terra` : contexte par défaut 500,000 / étendu 872,000. | | Connexion Codex (lignes qualifiées par compte activées avec des sélecteurs admissibles) | Une ligne `/` par sélecteur admissible et modèle natif pris en charge ; chaque ligne utilise exclusivement le compte associé, et les lignes natives non qualifiées sont masquées dans le sélecteur. Les métadonnées natives et les fenêtres de contexte sont préservées. | | Connexion Codex (ligne Daybreak transférée explicitement) | `openai/gpt-daybreak-blue-latest` uniquement lorsque l'entrée `customModels` exacte est configurée sur le fournisseur canonique `openai`. Elle conserve l'identifiant Daybreak transmis et utilise l'instantané de capacités Sol épinglé (contexte de 372 000 jetons ; compactage automatique à 334 800 jetons). | -| OpenAI (clé API) | Exactement dix lignes avec espace de noms : `gpt-5.5`, `gpt-5.6`, Sol/Terra/Luna, les trois identifiants virtuels `*-pro` et les deux alias Daybreak (contexte de 1 050 000 jetons ; entrée maximale de 922 000 jetons pour les dix) | +| OpenAI (clé API) | Les modèles avec espace de noms comprennent `gpt-5.5`, `gpt-5.6`, Sol/Terra/Luna, les identifiants virtuels `*-pro` et les alias Daybreak (contexte de 1,050,000 ; entrée maximale de 922,000). `openai-apikey/gpt-6.1-terra` ajoute un contexte de 1,050,000 et une sortie maximale de 128,000. | | OpenRouter | `openrouter/openai/gpt-5.6-sol`, `openrouter/openai/gpt-5.6-terra`, `openrouter/openai/gpt-5.6-luna` (1 050 000) | +| OpenRouter | `openrouter/openai/gpt-6.1-terra` (1,050,000) | | Cursor | Le repli statique comprend `cursor/gpt-5.6-sol`, `cursor/gpt-5.6-terra` et `cursor/gpt-5.6-luna` (1 000 000), ainsi que des lignes ordinaires/rapides pour Grok 4.5, 4.6 et 4.7 (500 000) ; 4.6 et 4.7 ajoutent `xhigh`, et la découverte dynamique propre au compte détermine quelles lignes restent visibles. | | xAI | La découverte dynamique fait autorité. Le catalogue de secours comprend `xai/grok-4.6` et `xai/grok-4.7` et utilise `xai/grok-4.5` par défaut ; les trois ont une fenêtre de 500 000 jetons. Grok 4.6 et 4.7 proposent `low` / `medium` / `high` / `xhigh` (valeur amont par défaut : `high`), tandis que Grok 4.5 s’arrête à `high`. | diff --git a/docs-site/src/content/docs/fr/guides/codex-integration.md b/docs-site/src/content/docs/fr/guides/codex-integration.md index 8bdfd730b1..1ef8e55d72 100644 --- a/docs-site/src/content/docs/fr/guides/codex-integration.md +++ b/docs-site/src/content/docs/fr/guides/codex-integration.md @@ -134,6 +134,16 @@ configuration de référence et de repli. Sur l'interface de bouclage, ce fichie vous pouvez fusionner manuellement si l'injection automatique a été supprimée ; hors bouclage, il contient la forme avec fournisseur dédié. Le mode de fournisseur externe laisse ce profil intact. +Quand ce fichier est régénéré, les clés racine simples qu'OpenCodex ne gère pas sont conservées : un réglage +que vous ajoutez, comme `stream_idle_timeout_ms` ou `stream_max_retries`, survit à l'injection suivante. +Chaque affectation conservée est copiée telle quelle, y compris les valeurs sur plusieurs lignes et les entiers +64 bits, et placée avant la première table. Les clés à l'intérieur des tables et les clés racine pointées comme +`a.b = 1` ne sont pas conservées. En cas de conflit, OpenCodex l'emporte toujours : les clés racine qu'il gère +(`model_provider`, `model_catalog_json`, `openai_base_url`) sont réécrites pour le mode de routage actif, et +une clé racine portant le nom d'une table écrite par le profil, par exemple un `features = { ... }` en ligne +quand le profil écrit `[features]`, est supprimée. Si le fichier change pendant qu'une injection attend le +verrou d'écriture, l'injection s'arrête avec une erreur réessayable et laisse votre modification en place. + :::caution Les clés racine telles que `openai_base_url`, `model_provider` et `model_catalog_json` **doivent** précéder le premier en-tête `[table]`. L'injecteur garantit ce placement, supprime ses propres copies obsolètes ou en double diff --git a/docs-site/src/content/docs/fr/guides/codex-prompt.md b/docs-site/src/content/docs/fr/guides/codex-prompt.md index 33793afbcc..2641bb0c05 100644 --- a/docs-site/src/content/docs/fr/guides/codex-prompt.md +++ b/docs-site/src/content/docs/fr/guides/codex-prompt.md @@ -36,6 +36,12 @@ temporairement indisponible, ce qui n’est pas le cas. Cliquez sur le nom d’une couche pour afficher le texte qu’elle envoie. La boîte de dialogue le lit depuis `codex debug prompt-input` : il s’agit donc du contenu réel, et non d’une description. +Chaque appel de lecture dispose d’un délai fixe de 15 secondes, qui inclut la lecture des +métadonnées et l’attente d’une sonde partagée. L’expiration est vérifiée après la fin de la +lecture synchrone des métadonnées ; si le délai est épuisé, aucune nouvelle sonde ne démarre. +À l’expiration, la boîte de dialogue indique que le prompt n’a pas pu être lu, mais les +instructions de base lues localement sont tout de même renvoyées. + Il arrive qu’il n’y ait rien à afficher. La boîte de dialogue précise alors la raison : - **Le fichier existe, mais il est vide.** Votre fichier `~/.codex/AGENTS.md` ne contient aucun diff --git a/docs-site/src/content/docs/fr/guides/combos.md b/docs-site/src/content/docs/fr/guides/combos.md index 8a9398988f..43c8488cf4 100644 --- a/docs-site/src/content/docs/fr/guides/combos.md +++ b/docs-site/src/content/docs/fr/guides/combos.md @@ -140,6 +140,8 @@ chaque requête commence par Anthropic. Un échec d’Anthropic autorisant une n échec similaire d’OpenAI peut la faire basculer vers Google. Une erreur terminale interrompt immédiatement le traitement au lieu de essayer les cibles restantes. +Une réponse HTTP 400 d'un fournisseur peut toujours être spécifique à une cible. L'enveloppe opaque de fournisseur d'OpenRouter (`Provider returned error` avec un `code: 400` numérique, aucun `type`, et `metadata.raw: "ERROR"`) est traitée comme locale à la cible et permet au combo d'essayer la cible suivante sans placer la cible défaillante en période de refroidissement. Les 400 typés sans code, les erreurs connues de schéma `response_format` malformé et une enveloppe dont la racine énonce son propre code terminal restent terminales ; une racine qui énonce son propre signal de rebond (`model_not_found`, `insufficient_quota`, `usage_limit_exceeded`, `free_rate_limited`, `input_admission_refused` ou `unsupported_input_modality`) n'ajoute aucun nouveau verdict, et un code vide est traité comme une absence de code. Les incompatibilités de cibles reconnues décrites plus loin dans ce guide continuent d'avancer. + ### Round-robin : lots pondérés lisses `round-robin` utilise un round-robin pondéré en douceur. Un poids cible plus grand donne à cet objectif un plus grand @@ -200,8 +202,9 @@ Les échecs d’un combo se répartissent entre ceux qui entraînent un **bascul | --- | --- | | HTTP 401, 403, 404, 408, 429, ou n'importe quel 5xx | Refroidissez la cible et passez à la prochaine cible éligible. | | Erreur classée comme erreur d’authentification, d’abonnement, de quota, de limitation de débit, de surcharge ou de serveur en amont | Place la cible en période de refroidissement et bascule, même si le statut seul ne suffit pas. | -| Annulation client (499), `origin_rejected`, refus de cyber-politique, débordement de contexte ou autre demande invalide | Arrêtez et renvoyez l'erreur ; une autre cible ne rendrait pas la demande valide. | -| Rejet structuré de `user`, valeur non prise en charge pour `reasoning.effort`/`reasoning_effort`, rejet d'entrée d'image propre à un modèle (`param: input`), ou refus d'un média d'entrée que la route ne peut pas lire (`unsupported_input_modality`) | Bascule vers la cible admissible suivante avant le début de la sortie, sans délai de refroidissement ; voir Compatibilité des paramètres facultatifs ci-dessous. | +| Annulation client (499), `origin_rejected`, refus de cyber-politique ou autre demande invalide | Arrêtez et renvoyez l'erreur ; une autre cible ne rendrait pas la demande valide. | +| Dépassement de contexte confirmé avant la sortie, y compris HTTP 400 | Essaie la prochaine cible admissible non tentée sans refroidissement ; à épuisement, renvoie la première erreur de contexte HTTP 400 confirmée (un refus de contexte avec un autre statut fait aussi passer à la cible suivante, sans être conservé). | +| Rejet structuré de `user`, valeur non prise en charge pour `reasoning.effort`/`reasoning_effort`, rejet d'entrée d'image propre à un modèle (`param: input`), ou refus d'un média d'entrée que la route ne peut pas lire (`unsupported_input_modality`) | En cas de refus d'effort, tente le niveau publié immédiatement inférieur sur la même cible tant que le budget d'envoi le permet ; si aucun niveau ne fonctionne, bascule avant l'engagement de sortie sans refroidissement si le refus correspond à une enveloppe de compatibilité reconnue, sinon reste terminal. Les autres incompatibilités répertoriées basculent sans refroidissement ; voir Compatibilité des paramètres facultatifs ci-dessous. | | Premier appel d'outil d'un tour Responses exécuté par un adaptateur interne (`runTurn`) que la requête courante n'a pas déclaré, avant toute sortie et tout effet de bord non rejouable | Met la cible en refroidissement et bascule avec le même catalogue d'outils. Après une sortie visible ou un effet de bord non rejouable, le refus est définitif. Les requêtes Chat Completions et Anthropic Messages ne changent pas. | | Toute autre erreur non classifiée | Arrêtez et renvoyez l'erreur. | @@ -210,9 +213,15 @@ valeur `Retry-After` valide, opencodex l’utilise à la place ; les en-têtes d acceptées, et un délai explicite `Retry-After` est plafonné à 24 heures ; les autres temps de recharge restent plafonnés à 10 minutes. La requête actuelle ne réessaye jamais la même cible tentée. Les demandes ultérieures l'ignorent jusqu'à ce qu'il soit -le temps de recharge expire. S’il ne reste aucune cible éligible, le proxy renvoie HTTP 503 avec +le temps de recharge expire. Si aucune cible n’a été tentée et qu’aucune n’est éligible, le proxy renvoie HTTP 503 avec `error.code = "combo_unavailable"`. +Après un refus de contexte HTTP 400 confirmé, l’épuisement des cibles ou du budget d’envoi renvoie +le premier refus sous `context_length_exceeded`, avant toute erreur ultérieure réessayable, même de quota. +Cela inclut les cibles restantes incompatibles avec la relecture du raisonnement ou sans consentement +de dépense. L’annulation, un refus fatal ultérieur ou un refus explicite de la politique de repli reste +prioritaire ; aucune cible facturée sans consentement ne reçoit la requête. + :::note Le basculement est intentionnellement limité. Il facilite la disponibilité, l'authentification et l'authentification spécifiques à la cible. échecs de quota et de surcharge ; il ne cache pas les erreurs des appelants ni les refus de politique. @@ -366,11 +375,15 @@ message de validation. ### Pourquoi le basculement s'est-il arrêté après la première erreur ? -L’erreur était terminale plutôt que spécifique à la cible. Corriger une entrée invalide, réduire un contexte surdimensionné, +L’erreur était terminale plutôt que spécifique à la cible. Corriger une entrée invalide, gérer un refus de politique ou corriger l’origine de la demande rejetée. Les combos ne sautent pas dans ces cas-là. ## Compatibilité des paramètres facultatifs -Exception aux erreurs 400 terminales : un rejet structuré de `user`, une valeur non prise en charge pour `reasoning.effort`/`reasoning_effort`, un rejet d’entrée d’image propre à un modèle (`param: input`), ou le refus d’un média d’entrée que la route ne peut pas lire (`unsupported_input_modality`) peut faire passer le combo à la cible admissible suivante avant le début de la sortie, sans délai de refroidissement. Le refus de sécurité, l’annulation et une sortie déjà commencée restent non rejouables. +Exception aux erreurs 400 terminales : l'enveloppe opaque d'OpenRouter (`Provider returned error` avec `code: 400`, aucun `type` et `metadata.raw: "ERROR"`), ou un rejet structuré de `user`, une valeur non prise en charge pour `reasoning.effort`/`reasoning_effort`, un rejet d’entrée d’image propre à un modèle (`param: input`), ou le refus d’un média d’entrée que la route ne peut pas lire (`unsupported_input_modality`), ainsi qu'après l'enveloppe fournisseur exacte `{"code":"invalid-argument","error":"Invalid reasoning effort."}`. Lorsqu'une cible de combo refuse l'effort de raisonnement demandé, le combo réessaye d'abord cette cible au niveau d'effort publié immédiatement inférieur, un niveau par refus et dans la limite du budget d'envoi partagé ; cela s'applique à tout refus d'effort reconnu. Si aucun niveau inférieur ne réussit, un refus correspondant à l'une des formes ci-dessus passe à une autre cible sans refroidir la cible rejetée, en conservant le 400 initial de cette cible lorsqu'il ne reste plus d'envoi disponible pour le niveau suivant ; les autres refus d'effort restent terminaux. Une route qui refuse le média de la requête avec le code `unsupported_input_modality` avance de la même façon. Ce sont des incompatibilités pour cette requête, et non la preuve que la cible est défaillante. Les requêtes directes conservent leur réparation unique par rétrogradation d'effort. La récupération de compatibilité ne transforme pas silencieusement `none` en un effort différent et n'élargit pas le saut de combo à des requêtes invalides arbitraires. Le refus de sécurité, l’annulation et une sortie déjà commencée restent non rejouables. Une requête à cible unique renvoie toujours un rejet non résolu en amont. [Canonical compatibility details](/guides/combos/#request-local-target-compatibility). + +## Réservation d’une tentative de récupération + +Une tentative de récupération activée par `cooldownReprobe: { enabled: true }` appartient uniquement à la requête qui l’a réservée ; les autres requêtes restent soumises aux délais de refroidissement enregistrés. La réservation est conservée pendant l’attente et la sélection JEV. Une cible redevenue utilisable pendant l’attente peut être réessayée si son délai enregistré n’a pas changé. Un nouvel enregistrement annule la réservation de cette cible. Un succès ne supprime que le délai inchangé de la cible ayant répondu ; les cibles non essayées et les nouveaux échecs conservent leurs délais. La désactivation du fournisseur, les quotas, l’admissibilité de la requête et l’annulation restent vérifiés. Voir les [réglages et limites](/guides/combos/#retry-all-cooled-targets-opt-in). diff --git a/docs-site/src/content/docs/fr/guides/integrations.md b/docs-site/src/content/docs/fr/guides/integrations.md index a9121f6121..da6e5c90a7 100644 --- a/docs-site/src/content/docs/fr/guides/integrations.md +++ b/docs-site/src/content/docs/fr/guides/integrations.md @@ -6,6 +6,8 @@ description: Connectez opencodex à OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi Co L'onglet **Connexion** écrit le bloc fournisseur d'opencodex dans le fichier de configuration du client, puis peut le retirer. Dix-huit clients fonctionnent ainsi, chacun avec son propre commutateur : +Sous Windows, une surcharge exigeant un chemin absolu doit inclure une lettre de lecteur (`C:\Users\me\client`) ou un partage UNC (`\\server\share\client`). Les formes `\Users\me\client` et `/client/config`, dépendantes du lecteur courant, sont refusées. Les sélecteurs documentés comme acceptant `~` le développent depuis le répertoire personnel effectif ; Gentle Shell ne développe pas `~`. + | Client | Fichier de configuration | Format | Prise d'effet de la modification | Identifiant | |---|---|---|---|---| | OpenCode | `~/.config/opencode/opencode.json` | JSON | au prochain lancement direct | `OPENCODEX_OPENCODE_API_KEY` | @@ -24,7 +26,7 @@ puis peut le retirer. Dix-huit clients fonctionnent ainsi, chacun avec son propr | omo | `~/.omo/agent/models.json` | JSON | nouvelles sessions | espace réservé de bouclage | | Cline CLI | `~/.cline/data/settings/providers.json` + `models.json` | JSON | après arrêt et redémarrage | bouclage uniquement | | Kilo | premier fichier existant parmi `kilo.jsonc`, `kilo.json`, `opencode.jsonc`, `opencode.json` ou `config.json` sous `~/.config/kilo` (`XDG_CONFIG_HOME` déplace ce répertoire ; `kilo.jsonc` est créé si aucun n'existe) | JSONC | nouvelles sessions | `OPENCODEX_KILO_API_KEY` | -| Command Code | `~/.commandcode/providers.json` (sous Windows avec le répertoire personnel par défaut : utiliser `HOME ?? USERPROFILE` uniquement si la valeur n’est ni vide ni composée uniquement d’espaces et désigne un chemin absolu Windows, sinon `homedir()` ; un répertoire personnel fourni séparément est conservé ; ajouter `.commandcode\providers.json`) | JSON | au prochain lancement de Command Code | aucun — boucle locale sans clé (`apiKey: false`) | +| Command Code | `~/.commandcode/providers.json` (sous Windows avec le répertoire personnel par défaut : utiliser `HOME ?? USERPROFILE` uniquement si la valeur n’est ni vide ni composée uniquement d’espaces et désigne un chemin absolu Windows, sinon `homedir()` ; un répertoire personnel fourni séparément est conservé ; ajouter `.commandcode\providers.json`) | JSON | au prochain lancement de Command Code | aucun — boucle locale sans clé (`apiKey: false`) ; l’application de bureau exige sa propre connexion et opencodex n’écrit jamais `auth.json` | | Factory Droid | `~/.factory/settings.json` (`%USERPROFILE%\.factory\settings.json` sous Windows) | JSON | dès la détection du fichier | boucle locale sans clé | Les modèles GJC dotés d'une échelle d'effort de raisonnement prise en charge exportent `reasoning: true`, `thinking.levels` et `compat.supportsReasoningEffort`, afin que GJC propose le choix de l'effort. Les modèles Codex natifs reçoivent leur échelle standard même si le catalogue l'omet. Ces champs sont absents sans échelle connue ; `none` n'envoie pas d'effort et `ultra` devient `max` sur le réseau. Actualisez l'intégration pour mettre à jour ces options. @@ -148,11 +150,14 @@ synchronisation, même si le document géré ne change pas. Si le fichier change après votre examen, l'écriture est refusée car le plan est devenu obsolète. La boîte de dialogue remplace l'ancien plan par le nouveau et vous demande de confirmer à nouveau ; elle ne relance jamais -l'écriture automatiquement. Si l'aperçu est temporairement indisponible, rechargez normalement la page et -recommencez l'action. +l'écriture automatiquement. Si l'aperçu indique qu'aucun catalogue de modèles n'est encore chargé, la boîte de +dialogue reste ouverte et propose **Charger le catalogue et réessayer** : elle relit la liste des intégrations, +puis redemande le plan. Aside utilise le même flux d'aperçu et de confirmation pour un seul profil sélectionné à la fois. **Synchroniser -tous les profils** reste une action groupée distincte et n'est pas liée à un aperçu combiné unique. +tous les profils** reste une action groupée distincte et n'est pas liée à un aperçu combiné unique. Un plan décrit le fichier d'un seul profil : la carte +de la Vue d'ensemble d'une intégration Aside en conflit propose donc **Choisir un profil**, et le bloc se +remplace depuis la page de ce profil. ## À quoi s'attendre, en toute transparence @@ -328,3 +333,19 @@ ocx integration client enable --client kilo ## Factory Droid Factory Droid utilise `~/.factory/settings.json` (`%USERPROFILE%\.factory\settings.json` sous Windows). Activez explicitement l’intégration avec `ocx integration client enable --client droid`, puis choisissez un modèle personnalisé dans `/model`. Les entrées gérées n’utilisent pas de clé et fonctionnent uniquement en boucle locale. La désactivation supprime ces entrées ; l’annulation restaure les octets sauvegardés. Si l’ancien `config.json` contient des entrées OpenCodex ou si `settings.local.json` remplace `customModels`, résolvez ce conflit avant l’activation. Consultez la [documentation Factory BYOK](https://docs.factory.ai/model-independence/byok). + +## Hermes / Command Code: model names + +Hermes and Command Code support `--model-names alias|routed` (API: `modelNames`). +The default is `routed`, independent of `preferModelAliasIds`. A connection +stores its mode; later Apply without the option preserves it. Alias mode uses +only provider-qualified aliases that the router proves equivalent; missing, +unsafe or colliding aliases fall back to routed keys. Combos keep their keys. +Removed/renamed aliases migrate on the next successful managed refresh, with +foreign-edit refusal. Named Hermes profiles need explicit Apply. + +`ocx export --client hermes --model-names alias --json` previews a current +already loaded catalog without writing client files or managed state; a cold or +stale catalog returns unavailable. Explicit `--out` writes an export artifact. +See the [English integration guide](/guides/integrations/#opt-in-alias-model-names) +for the canonical workflow. diff --git a/docs-site/src/content/docs/fr/guides/model-ordering.md b/docs-site/src/content/docs/fr/guides/model-ordering.md index fab755afdf..95cdd75584 100644 --- a/docs-site/src/content/docs/fr/guides/model-ordering.md +++ b/docs-site/src/content/docs/fr/guides/model-ordering.md @@ -30,7 +30,7 @@ Sans ordre global du sélecteur, les priorités sans sélecteur pertinentes sont | `subagentModels[i]` | `i` (`0` à `4`) | La carte de classement présentée dans `src/codex/catalog/sync.ts` | | Autres modèles acheminés | `5` | Création d'une entrée routé dans `src/codex/catalog/sync.ts` | | Modèles routés non mis en avant et présents dans `modelPickerOrder` | `1000 + i` | Rang d’affichage du sélecteur dans `src/codex/catalog/sync.ts` | -| Slugs GPT natifs par défaut | `9` | Création d'entrées natives dans `src/codex/catalog/sync.ts` | +| Slugs GPT natifs par défaut | `sourcePriority` | Création d'entrées natives dans `src/codex/catalog/sync.ts` | | Modèles natifs non sélectionnés alors qu'une liste sélectionnée existe | Au moins `featured.length + 100` | Fusion du catalogue natif dans `src/codex/catalog/sync.ts` | La direction API limite `subagentModels` à cinq entrées avec `slice(0, 5)` en @@ -73,7 +73,7 @@ Sans sélecteur de compte éligible et sans liste de sélection non vide, l'ordr 3. Modèles natifs non sélectionnés, poussés sous le bloc sélectionné lors de la fusion du catalogue. Sans `subagentModels`, les modèles routés restent en priorité `5`, les entrées natives GPT utilisent leur -priorité (normalement `9` pour les entrées construites par opencodex), et le groupe routé reste provider/id +priorité (sourcePriority, avec `9` en dernier recours), et le groupe routé reste provider/id alphabétique. ## Exemple diff --git a/docs-site/src/content/docs/fr/guides/model-routing.md b/docs-site/src/content/docs/fr/guides/model-routing.md index 0b368488cb..273e2d1901 100644 --- a/docs-site/src/content/docs/fr/guides/model-routing.md +++ b/docs-site/src/content/docs/fr/guides/model-routing.md @@ -125,9 +125,3 @@ Le routage et la visibilité dans le catalogue sont deux mécanismes distincts : un fournisseur portant ce nom (par exemple `anthropic` ou `groq`) est effectivement configuré. Consultez [Configuration](/fr/reference/configuration/) pour connaître les champs de fournisseur lus par ces règles. - - - -## Valeurs par défaut de la découverte de modèles - -`modelDiscovery.newModelPolicy` vaut `"off"` par défaut, même si le champ est absent. À la première découverte réussie, seul le `defaultModel` configuré est visible ; sinon, activez les modèles nécessaires dans Models. Les sélections, interrupteurs, petites références existantes et catalogues statiques sont conservés. Un ancien catalogue en direct sans sélection comptant au moins 20 modèles et un modèle par défaut configuré est réduit une seule fois à ce dernier ; sans modèle par défaut, sa visibilité est conservée ; les choix manuels ultérieurs ne sont pas réinitialisés. Les nouveaux modèles restent masqués jusqu’à leur activation. Un `"on"` explicite autorise la publication automatique. Utilisez `ocx models new-policy off` (avec `--provider ` si nécessaire) et `ocx models new-arrivals --json`. diff --git a/docs-site/src/content/docs/fr/guides/ollama-clients.md b/docs-site/src/content/docs/fr/guides/ollama-clients.md new file mode 100644 index 0000000000..58c132f1f2 --- /dev/null +++ b/docs-site/src/content/docs/fr/guides/ollama-clients.md @@ -0,0 +1,71 @@ +--- +title: Clients compatibles Ollama +description: Dirigez les outils qui parlent l'API Ollama vers opencodex et utilisez les modèles de vos fournisseurs configurés. +--- + +opencodex répond à un sous-ensemble de l'API HTTP d'Ollama : un outil qui ne sait parler qu'à Ollama peut +ainsi utiliser les modèles déjà configurés dans opencodex. Les requêtes sont traduites vers le chemin Chat +Completions et envoyées au fournisseur choisi. opencodex ne télécharge, ne stocke et n'exécute aucun modèle sur +votre machine. + +## Connecter un client + +Utilisez l'adresse du proxy comme hôte Ollama. Pour une installation locale par défaut : + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +Lorsque le proxy exige une clé d'API (par exemple avec une liaison `0.0.0.0`), envoyez-la comme pour +`/v1/chat/completions`, par exemple `Authorization: Bearer `. Une clé limitée à certains modèles +ne voit et n'utilise que les modèles autorisés. Ces points de terminaison ne sont servis que par l'écouteur +principal ; l'écouteur loopback sans authentification, Remote Link et l'entrée de gestion du hub ne les exposent pas. + +## Points de terminaison + +| Point de terminaison | Comportement | +| --- | --- | +| `GET /api/version` | La version d'opencodex. | +| `GET /api/tags` | Les modèles des fournisseurs configurés, sous la forme `provider/model`. | +| `POST /api/show` | `{ "model": "provider/model" }` ne renvoie que des faits connus ; ni taille de fichier, ni empreinte, ni modèle de prompt, ni licence. | +| `POST /api/chat` | Conversation avec des messages `system`, `user`, `assistant` et `tool`. | +| `POST /api/generate` | Une seule invite, avec un `system` facultatif. | + +Tous les autres chemins `/api/*` restent dans l'API de gestion d'opencodex. + +## Champs de requête pris en charge + +- `model` : un nom renvoyé par `/api/tags`. +- `stream` : `true` par défaut (JSON délimité par des sauts de ligne). Indiquez `false` pour une seule réponse JSON. +- `images` : PNG, JPEG, GIF ou WebP en base64 sur les messages utilisateur (chat) ou sur la requête (generate). +- `tools` (chat uniquement) : outils de type fonction. Renvoyez le message assistant tel quel, y compris + l'`id` de chaque appel ; un résultat `tool` est associé par `tool_call_id` ou, à défaut, par `tool_name`. +- `options` : `temperature`, `top_p`, `num_predict` et `stop`. +- `format` : uniquement `"json"`. + +Chaque requête `/api/chat` accepte au maximum **1 024 appels d’outils au total** dans l’ensemble des messages +assistant, y compris ceux qui ont déjà un résultat. Au-delà, elle renvoie HTTP 400 avant d’atteindre +un fournisseur. Raccourcissez l’historique de la conversation et renvoyez-le, en conservant chaque +résultat d’outil avec l’appel correspondant dans le message assistant. + +Tout le reste est refusé avec un HTTP 400 au lieu d'être ignoré : `think`, `keep_alive`, `suffix`, `raw`, +`template`, `context`, les autres `options`, un `format` en schéma JSON et les URL d'images. Les points de +terminaison Ollama de gestion des modèles et d'embeddings ne sont pas fournis. + +Les combos, les politiques de routage, les alias `--fast` ou d'effort, et les fournisseurs qui transmettent les +identifiants de l'appelant ne peuvent pas être sélectionnés ici. Ces requêtes échouent avant tout envoi en amont. + +## Réponses + +Une réponse terminée porte `done: true` avec un `done_reason` valant `stop`, `tool_calls` ou `length`. +`prompt_eval_count` et `eval_count` apparaissent lorsque le fournisseur a signalé l'usage ; les champs de durée +ne sont pas renseignés. Un flux envoie exactement une ligne `done: true`, une fois la réponse amont entièrement terminée. + +Les erreurs utilisent la forme Ollama `{ "error": "message" }` et conservent le statut HTTP, y compris +`Retry-After` pour les limites de débit et les refus pour surcharge. Une réponse interrompue par un filtre de contenu +ou pour une raison inconnue est renvoyée comme erreur, jamais comme un arrêt normal. Si un flux échoue après avoir +commencé, sa dernière ligne est un objet `error` et aucune ligne `done: true` ne suit. + +Les requêtes apparaissent dans le journal des requêtes du tableau de bord comme le reste du trafic, et l'en-tête +de réponse `x-opencodex-request-id` désigne la ligne correspondante. diff --git a/docs-site/src/content/docs/fr/guides/providers.md b/docs-site/src/content/docs/fr/guides/providers.md index e3c4333104..dbc026ea5b 100644 --- a/docs-site/src/content/docs/fr/guides/providers.md +++ b/docs-site/src/content/docs/fr/guides/providers.md @@ -67,8 +67,9 @@ La relance d'une requête 429 avec la même clé, configurée par [`retryOn429`](/fr/reference/configuration/), s'applique uniquement aux fournisseurs à clé API (`authMode: "key"`). Les préréglages OAuth, de transfert et locaux sont exclus : leurs identifiants ne doivent jamais être réutilisés sur le même jeton, et les environnements locaux ne possèdent aucune clé distante à -préserver. Cette fonction est facultative : elle est désactivée lorsque l'option est absente ; la présence de -l'objet l'active, sauf si `enabled: false`. +préserver. Cette fonction est facultative, sauf pour les valeurs par défaut documentées propres à certaines destinations. Le Chat Mistral canonique utilise une politique de relance patiente (6 relances, intervalle de repli de 10 secondes), dans la limite de l’allocation d’envois existante pour l’ensemble de la requête. Les réglages explicites de `retryOn429`, y compris `enabled: false`, sont prioritaires. Le préréglage Mistral transmet aussi par défaut les clés de cache de prompt fournies ; `promptCacheKey: false` désactive cette transmission. L’affinité de cache augmente les chances de réutilisation, mais ne garantit pas un succès de cache et ne lève pas les limites de débit de jetons. + +Mistral utilise un seul fournisseur à clé API pour les clés Studio et Vibe. Les types de clés et les allocations des offres sont décrits dans la [documentation des clés API de Mistral](https://docs.mistral.ai/admin/identity-access/api-keys) ; le proxy ne déduit pas le niveau d’abonnement à partir de la clé. Pour tous les modèles, les échéances `Retry-After` explicites renvoyées en amont sont partagées entre les appels qui utilisent les mêmes identifiants et le même modèle. Un 429 sans délai de relance peut déclencher une attente de récupération prudente de 60 secondes lorsque des compteurs par minute valides indiquent une capacité épuisée, ou lorsque le coût mesuré de la requête refusée dépasse les jetons restants tout en tenant dans l’allocation complète annoncée. Il s’agit d’une politique de récupération locale, pas d’une prédiction exacte de la réinitialisation côté serveur. Le trafic sain ne prédit jamais le cache ni le coût de la requête suivante. Après l’attente, une seule sonde de récupération est envoyée ; si elle réussit, le trafic ordinaire reprend. Des indications absentes, mal formées, sans droit d’usage, mensuelles épuisées ou supérieures à l’allocation complète n’inventent ni réinitialisation ni compactage de l’historique. `requestPacing: { "enabled": false }` ou `retryOn429: { "respectRetryAfter": false }` désactive le cadencement partagé. Pour une relance avec la même clé, si le délai de relance de Mistral dépasse `retryOn429.maxIntervalMs`, le proxy renvoie le 429 et l’indication de relance au lieu de relancer trop tôt. Lorsque la sélection des clés en rotation est activée, les requêtes en attente revérifient le refroidissement des clés et acquièrent la capacité de cadencement d’une clé de remplacement, et un rejet de clé avant toute sortie peut être récupéré avec une clé saine dans la limite d’envois existante de la requête. Les fenêtres de contexte et les préférences de compactage par modèle restent indépendantes. ## 1. Connexion ChatGPT (transfert direct) @@ -179,8 +180,7 @@ Les fournisseurs OAuth dont les identifiants comportent un identifiant de compte peuvent conserver plusieurs connexions. La page **Fournisseurs** affiche ces comptes dans une liste déroulante, permet d'en ajouter un autre et de changer de compte actif sans déconnecter les autres. Une connexion ordinaire avec un identifiant Kimi qui ne contient aucune information d'identité remplace l'emplacement actif, tandis que l'action explicite **Ajouter un -compte** préserve cet emplacement et en active un nouveau, distinct. Les comptes Kiro sont indexés par ARN de -profil. `chatgpt` n'utilise toujours qu'un seul emplacement, car les comptes du pool Codex sont gérés dans un +compte** préserve cet emplacement et en active un nouveau, distinct. Les comptes Kiro utilisent l’ARN du profil avec l’adresse e-mail de l’utilisateur connecté lorsqu’elle est disponible ; plusieurs utilisateurs peuvent conserver des identifiants distincts pour un même profil d’organisation. `chatgpt` n'utilise toujours qu'un seul emplacement, car les comptes du pool Codex sont gérés dans un registre distinct. Les jetons restent dans `~/.opencodex/auth.json` ; `/api/oauth/accounts` ne renvoie que des métadonnées masquées. @@ -254,6 +254,8 @@ dans le pool de comptes, ce que fait aussi le pool de comptes Codex du tableau d ### Importation des identifiants Kiro +Dans le tableau de bord, choisissez **AWS IAM Identity Center**, puis indiquez l’URL du portail d’accès AWS et la région SSO de votre organisation. Autorisez le code d’appareil dans votre navigateur et choisissez le profil Kiro à enregistrer si plusieurs sont proposés. Aucun CLI ni accès SSH n’est nécessaire. Les instructions CLI ci-dessous concernent le choix **Kiro CLI**. + La connexion Kiro nécessite la CLI Kiro : sous Unix, installez-la avec `curl -fsSL https://cli.kiro.dev/install | bash` ; sous Windows PowerShell, utilisez `irm 'https://cli.kiro.dev/install.ps1' | iex`, puis connectez-vous avec `kiro-cli login`. En l'absence de session `kiro-cli`, `ocx login kiro` se rabat sur un jeton d'accès collé ou sur la variable @@ -308,7 +310,7 @@ existante n'est pas concernée. ## 3. Catalogue des clés API -opencodex fournit 104 préréglages intégrés : 84 à clé, 16 OAuth, trois locaux et un préréglage par défaut de +opencodex fournit 107 préréglages intégrés : 86 à clé, 17 OAuth, trois locaux et un préréglage par défaut de transfert ChatGPT. Dans le tableau de bord, le sélecteur **Ajouter un fournisseur** ouvre le tableau de bord du fournisseur à clé, valide la clé et l'enregistre ; la validation dépend du fournisseur. Parmi les entrées notables : @@ -358,13 +360,13 @@ promotionnels de Cline ne sont accessibles que dans l'IDE ou la CLI Cline, pas p | Novita AI | `https://api.novita.ai/openai/v1` | | Together | `https://api.together.xyz/v1` | | Fireworks | `https://api.fireworks.ai/inference/v1` | -| Moonshot (Kimi API) · Kimi (coding) | `https://api.moonshot.ai/v1` · `https://api.kimi.com/coding/v1` | +| Moonshot (Kimi API) · Kimi (coding) | `https://api.moonshot.ai/v1` · `https://api.kimi.com/coding/v1`. L’API `moonshot` utilise `kimi-k3.1-pro` par défaut ; les sélections `kimi-k2.5` enregistrées pour les adresses API officielles migrent vers ce modèle. | | Hugging Face | `https://router.huggingface.co/v1` | | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | | Z.AI (GLM Coding) | `https://api.z.ai/api/coding/paas/v4` | | Zhipu AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | | [BigModel Coding Plan — Responses (liste statique)](/guides/providers/#bigmodel-coding-plan-over-responses) | `https://open.bigmodel.cn/api/v1` | -| Qwen Cloud | Forfait à jetons (par défaut) : `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · Facturation à l'usage : `https://dashscope.aliyuncs.com/compatible-mode/v1` · ou personnalisé | +| Qwen Cloud | Forfait à jetons (par défaut) : `https://token-plan.maas.qwencloudapi.com/compatible-mode/v1` · Facturation à l'usage : `https://dashscope.aliyuncs.com/compatible-mode/v1` · ou personnalisé | | Tencent Cloud Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | | Volcengine Ark · Coding Plan · Agent Plan | `https://ark.cn-beijing.volces.com/api/v3` · `https://ark.cn-beijing.volces.com/api/coding/v3` · `https://ark.cn-beijing.volces.com/api/plan/v3` | @@ -384,12 +386,18 @@ par Sionic, `deepseek/deepseek-v4.1-flash-ultrafast` et `z-ai/glm-5.3-flash-ultr sont affichés en premier. Créez une clé dans le [tableau de bord OpenGateway](https://opengateway.ai/api-keys), puis lancez `ocx provider add opengateway` ou sélectionnez **OpenGateway** dans le tableau de bord. Les requêtes chat utilisent la clé Bearer configurée ; la liste publique ne valide pas cette clé. +Sur le protocole Responses, OpenGateway refuse les appels d’outils personnalisés natifs rejoués ; le préréglage convertit donc les outils personnalisés Codex, comme `exec` en mode code, en outils de fonction avant l’envoi. +Les tableaux de contenu des résultats d’outils sont envoyés sous forme de texte, et les images sont conservées après le groupe de résultats d’outils associé. Les parties de résultat non prises en charge, y compris les refus et les contenus opaques, sont rejetées explicitement par une erreur d’entrée client avant l’envoi. +Le niveau de détail d’image `original` est converti en `high`, que la passerelle accepte ; les octets de l’image restent inchangés. +La route Responses native vérifie aussi les complétions vides en texte seul avant de les présenter comme un succès. +Un budget de sortie épuisé produit `incomplete` avec `max_output_tokens` ; le proxy n’augmente pas le budget demandé. Une complétion vide qui peut être relancée sans risque et qui dispose encore de budget peut être retentée une seule fois, dans la limite d’envois existante. `emptyCompletionRetry: false` explicite ou `OCX_EMPTY_COMPLETION_RETRY=0` désactive cette nouvelle tentative. Le texte, les refus, l’activité d’outils et les événements de flux inconnus empêchent la relance et conservent le flux d’origine. Cette protection ne modifie ni les autres fournisseurs ni leurs valeurs par défaut de nouvelle tentative. +La relance exige `store: false` explicite, une entrée complète et uniquement des outils exécutés par le client ; un outil hébergé comme `web_search` empêche la relance automatique même si aucun événement d’outil n’a été observé. **OpenCode Zen** (`opencode-zen`) utilise `https://opencode.ai/zen/v1` avec une clé API obtenue sur [opencode.ai/auth](https://opencode.ai/auth). Les modèles gratuits peuvent subir une limite courte d’environ 15–20 requêtes/minute (mesure communautaire ; OpenCode ne publie pas de RPM). Si une réponse 429 de limitation omet `Retry-After`, opencodex ajoute des indications et un `Retry-After` synthétique ; les en-têtes valides en amont restent prioritaires. Les tentatives avec la même clé restent facultatives via [`retryOn429`](/fr/reference/configuration/). Sur les routes officielles `https://opencode.ai/zen/v1` et `https://opencode.ai/inference/v1` du fournisseur canonique `opencode-zen` avec authentification par clé API, Gemini utilise automatiquement l’API native Google en mode `googleMode: ai-studio` (par défaut). Les identifiants Zen sont conservés, y compris Flash sans suffixe `-tiered`. Claude utilise automatiquement Anthropic Messages, quel que soit `googleMode`. Au chargement des configurations enregistrées, seules les anciennes surcharges Chat/Responses admissibles de ces modèles natifs sont ignorées, ainsi que les préférences admissibles de l’outil hébergé `image_generation` propres à Responses. Les fournisseurs personnalisés, les routes sans authentification par clé et les autres préférences restent inchangés. -**La prise en charge de `opencode-free` a été supprimée** : tous les modèles renvoient désormais `403 permission_denied` à cause du contrôle du niveau gratuit en amont chez OpenCode ([#7255](https://github.com/lidge-jun/opencodex/issues/7255)). Le chargement d’une configuration existante désactive en mémoire les entrées concernées et leurs références de modèles, avertit une fois par processus et ne modifie pas le fichier. Si ce fournisseur était le défaut, la route OpenAI OAuth standard devient le défaut. Utilisez `opencode-go`, `opencode-zen` avec clé ou un autre fournisseur. [Conditions OpenCode Zen](https://opencode.ai/docs/zen/). +**La prise en charge de `opencode-free` a été supprimée** : tous les modèles renvoient désormais `403 permission_denied` à cause du contrôle du niveau gratuit en amont chez OpenCode ([#7255](https://github.com/lidge-jun/opencodex/issues/7255)). Le chargement d’une configuration existante désactive en mémoire les entrées concernées et leurs références de modèles, avertit une fois par processus et ne modifie pas le fichier lors du chargement. Le prochain enregistrement supprime ces entrées et références de config.json. Avant cet enregistrement, le fichier original est automatiquement conservé dans `config.json.pre-opencode-free-removal.bak`, à côté de config.json, ou sous un nom unique si ce nom est occupé. Une copie indépendante, identique octet par octet, est réutilisée uniquement si sa protection réservée au propriétaire peut être vérifiée ; sinon, une nouvelle copie protégée est créée à côté. Aucun fichier existant n’est écrasé. Des premiers chargements simultanés peuvent laisser plusieurs copies identiques et protégées ; l’avertissement indique ce chemin. Pour restaurer la configuration, recopiez ce fichier sur config.json, par exemple après une rétrogradation. Si la copie échoue, l’avertissement demande de copier config.json immédiatement. Si ce fournisseur était le défaut, la route OpenAI OAuth standard devient le défaut. Utilisez `opencode-go`, `opencode-zen` avec clé ou un autre fournisseur. [Conditions OpenCode Zen](https://opencode.ai/docs/zen/). Les lectures passives appliquent uniquement la désactivation en mémoire, sans copie ni avertissement. Les affectations et valeurs par défaut valides de Claude Desktop sont conservées. Les règles dont la liste de modèles sources autorisés devient vide sont désactivées, ainsi que la synchronisation native des sous-agents si son modèle d’injection est supprimé. Les sauvegardes suivantes ne rétablissent pas les références supprimées et préservent les modifications simultanées valides. @@ -617,6 +625,9 @@ maintenir leur visibilité même lorsque les catalogues en direct ne sont pas en | Connexion Codex (Pool ou Direct) | `gpt-5.6-*` | 372 000 | | OpenAI (clé API) | `openai-apikey/gpt-5.6-*` plus `*-pro` | 1 050 000 (entrée maximale de 922 000) | | OpenRouter | `openrouter/openai/gpt-5.6-sol`, `openrouter/openai/gpt-5.6-terra`, `openrouter/openai/gpt-5.6-luna` | 1 050 000 | +| Codex | `gpt-6.1-terra` | 500,000 / 872,000 | +| OpenAI API | `openai-apikey/gpt-6.1-terra` | 1,050,000 (128,000 max output) | +| OpenRouter | `openrouter/openai/gpt-6.1-terra` | 1,050,000 | | Cursor | `cursor/gpt-5.6-sol`, `cursor/gpt-5.6-terra`, `cursor/gpt-5.6-luna` | 1 000 000 | Les entrées natives GPT-5.6 conservent les niveaux de raisonnement fixés en amont — Luna propose par exemple @@ -637,7 +648,7 @@ reste une passerelle à clé ou jeton d'abonnement sur son point de terminaison **Cloudflare AI Gateway** exige que les identifiants de votre compte et de votre passerelle figurent dans l'URL. Copilot présente un catalogue qui utilise plusieurs protocoles : ces modèles (`gpt-5.3-codex`, `gpt-5.4`, -`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) rejettent +`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) rejettent `/chat/completions` pour le trafic d'agent. opencodex route donc ces modèles sur l'API Responses par défaut, tandis que tous les autres modèles Copilot restent sur Chat Completions. L'ordre de priorité est le suivant : verrouillage explicite du protocole → entrée [`modelAdapters`](/fr/reference/configuration/providers/) définie @@ -716,4 +727,4 @@ au fournisseur. Les fournisseurs qui disposent d'une sonde en direct sont OpenAI/Codex, Anthropic, xAI, Cursor, Kimi, Google Antigravity, OpenRouter, DeepSeek, ClinePass, Z.AI, MiniMax, Moonshot, Venice, Synthetic, DeepInfra, -Neuralwatt, Command Code, ainsi que tout fournisseur personnalisé reposant sur a6api. +Neuralwatt, Command Code, ainsi que tout fournisseur personnalisé reposant sur a6api ou Abliteration. diff --git a/docs-site/src/content/docs/fr/guides/remote-hub.md b/docs-site/src/content/docs/fr/guides/remote-hub.md index aab597faa7..1d3e22389e 100644 --- a/docs-site/src/content/docs/fr/guides/remote-hub.md +++ b/docs-site/src/content/docs/fr/guides/remote-hub.md @@ -158,7 +158,7 @@ services: hub: pull_policy: build build: - context: https://github.com/lidge-jun/opencodex.git#main + context: https://github.com/lidge-jun/opencodex.git#dev dockerfile: Dockerfile target: runtime args: diff --git a/docs-site/src/content/docs/fr/guides/remote-link.md b/docs-site/src/content/docs/fr/guides/remote-link.md index 9503b02ad3..2f5b2b964a 100644 --- a/docs-site/src/content/docs/fr/guides/remote-link.md +++ b/docs-site/src/content/docs/fr/guides/remote-link.md @@ -10,10 +10,10 @@ Une liaison entre machines connecte un ordinateur OpenCodex **Home** à un ordin - Home peut se connecter à Child avec une clé OpenSSH. - Pour une liaison initiée par Child, Child peut se connecter à Home avec une clé OpenSSH (la connexion par mot de passe n’est pas prise en charge). - OpenCodex 2.66.0 ou ultérieur est installé sur Child (et sur Home pour une liaison initiée par Child). -- Les deux ordinateurs utilisent macOS ou Linux. +- Les ordinateurs peuvent utiliser macOS, Linux ou Windows x64. Windows nécessite OpenSSH Server et Windows PowerShell, sans Git Bash ni curl. - Le tableau de bord qui ajoute un Child depuis Home est ouvert sur Home ou via une session Hub appairée. Transformer l’ordinateur actuel en Child exige une session de tableau de bord appairée par l’opérateur ; une session locale sans identifiant ne peut pas valider ce changement de routage. -SSH par mot de passe et Windows restent hors du flux actuel. Une liaison peut être lancée des deux côtés : depuis Home, comme décrit ci-dessous, ou depuis Child, comme décrit dans la section « Connecter cet ordinateur comme Child ». +SSH par mot de passe n'est pas pris en charge. Une liaison peut être lancée depuis Home ou Child. Windows utilise PowerShell via la même connexion OpenSSH vérifiée. ## Ajouter un Child depuis `#remote` @@ -55,7 +55,7 @@ Le rôle **Child** exige également qu’OpenCodex fonctionne en mode autonome s - **Connected** signifie que le tunnel SSH est prêt et que Child peut utiliser la liaison Home. - **Reconnecting** signifie que le tunnel est réessayé. Les requêtes peuvent temporairement renvoyer `503` avec `Retry-After`. Sur un Child connecté depuis son propre tableau de bord, une requête attend d’abord jusqu’à 15 secondes le retour du tunnel. -- **Failed** signifie que la liaison nécessite une intervention. Vérifiez l’authentification SSH, la clé d’hôte confirmée, la redirection ou le délai indiqué. Le côté qui ouvre le tunnel SSH réessaie de lui-même après une mise en veille, une panne ou un redémarrage (Home pour un Child qu’il a ajouté, le Child pour une liaison qu’il a rejointe depuis son propre tableau de bord) : environ une fois par minute après un délai dépassé ou une erreur de redirection, et toutes les cinq minutes après une erreur d’authentification. Une clé d’hôte modifiée n’est jamais réessayée. Pour réessayer tout de suite, choisissez **Retry** dans le tableau de bord du Home ou exécutez `ocx link reconnect --link-id ` sur le Home. Le tunnel de cette liaison redémarre sans redémarrer OpenCodex. +- **Failed** signifie que la liaison nécessite une intervention. Vérifiez l’authentification SSH, la clé d’hôte confirmée, la redirection ou le délai indiqué. Le côté qui ouvre le tunnel SSH réessaie de lui-même après une mise en veille, une panne ou un redémarrage (Home pour un Child qu’il a ajouté, le Child pour une liaison qu’il a rejointe depuis son propre tableau de bord) : une minute après un délai dépassé ou une erreur de redirection, puis avec une attente qui double après chaque nouvel échec, jusqu’à cinq minutes, et toutes les cinq minutes après une erreur d’authentification. Une clé d’hôte modifiée n’est jamais réessayée. Pour réessayer tout de suite, choisissez **Retry** dans le tableau de bord du Home ou exécutez `ocx link reconnect --link-id ` sur le Home. Le tunnel de cette liaison redémarre sans redémarrer OpenCodex. Une liaison en échec ne bascule pas silencieusement vers un fournisseur local. @@ -85,10 +85,13 @@ ocx link issue --alias --tunnel-port [--json] ocx link status [--json] ocx link revoke --link-id [--json] ocx link reconnect --link-id [--json] +ocx link check (--link-id | --all) [--no-wait] [--json] ``` Sans terminal interactif (TTY), `--expect-fingerprint` est obligatoire. Dans un terminal interactif, vous pouvez l’omettre si vous confirmez explicitement l’empreinte proposée. +Sur le Home, `ocx link check (--link-id | --all)` lit pour chaque enfant lancé par le Home sa version installée, son type d’installation et sa voie de mise à jour : il exécute `ocx update --plan` de l’enfant par SSH (60 secondes par enfant, trois à la fois), qui calcule un plan sans rien modifier. Un enfant antérieur à 2.97.0 renvoie `owner-action` (`legacy-ocx`) ; sa version vient d’un appel SSH en lecture seule de plus sur macOS et Linux, ou de la version qu’il a annoncée par le lien sous Windows. Les liens ouverts depuis l’enfant et les enfants `ocx-child` sont signalés sans SSH. `ocx link status --json` ajoute alors un bloc `child` à chaque ligne (versions, écart de version, fraîcheur du catalogue, activité, dernière opération). Détails et codes de sortie : [Child install, catalog and activity](/guides/remote-link/#child-install-catalog-and-activity) (en anglais). + ## Guides associés - [Déploiement Remote Hub](/fr/guides/remote-hub/) diff --git a/docs-site/src/content/docs/fr/guides/sub-agent-surface.md b/docs-site/src/content/docs/fr/guides/sub-agent-surface.md index a5b172a4e4..5941150a65 100644 --- a/docs-site/src/content/docs/fr/guides/sub-agent-surface.md +++ b/docs-site/src/content/docs/fr/guides/sub-agent-surface.md @@ -46,6 +46,42 @@ Pour une liste v2, l'éligibilité a trois états : une entrée estampillée `" sans champ `multi_agent_version` est admissible. Une valeur explicite `"v1"` est exclue, car elle indique que le modèle appartient à l’autre surface de collaboration. +## Modèles annoncés par `spawn_agent` + +Codex liste au plus cinq modèles dans la description de l'outil `spawn_agent`, et il les choisit lui-même : il trie les lignes du catalogue visibles dans le sélecteur par `priority` croissante et garde les cinq premières. La liste de la page **Subagents** (`subagentModels`) n'agit sur cette sélection qu'en donnant à ses modèles les priorités les plus basses, dans l'ordre de la liste (`0` à `4` sans sélecteurs de compte). Elle ne limite pas la sélection à ces modèles. + +Si vous mettez en avant un à quatre modèles, Codex complète les emplacements restants avec les lignes suivantes par priorité. Vous n'avez pas choisi ces lignes, et le tableau de bord n'indique pas lesquelles sont retenues. Elles dépendent du catalogue : + +| Catalogue | Lignes qui complètent les emplacements restants | +| --- | --- | +| Sans sélecteurs de compte Codex | Les autres lignes routées `provider/model`. Elles partagent toutes la priorité `5` et apparaissent donc par nom de fournisseur, puis par identifiant de modèle, dans l'ordre alphabétique. Les lignes GPT natives non mises en avant ont une priorité d'au moins `100` plus le nombre d'identifiants mis en avant ; elles viennent donc après. | +| Avec sélecteurs de compte Codex | Les lignes natives qualifiées par compte (`/`), placées juste après les lignes mises en avant. Les lignes routées non mises en avant passent à la priorité `1005` et viennent après elles. | + +Par exemple, sans sélecteurs de compte et avec cette liste : + +```json +{ "subagentModels": ["xai/grok-4.5", "anthropic/claude-sonnet-5"] } +``` + +| Emplacement | Modèle | Priorité | Raison | +| ---: | --- | ---: | --- | +| 1 | `xai/grok-4.5` | `0` | Première entrée de la liste | +| 2 | `anthropic/claude-sonnet-5` | `1` | Deuxième entrée de la liste | +| 3 | `deepseek/deepseek-v4-flash` | `5` | Première ligne routée restante dans l'ordre alphabétique | +| 4 | `google/gemini-3-pro` | `5` | Ligne routée suivante | +| 5 | `moonshot/kimi-k3` | `5` | Ligne routée suivante | +| 6+ | `zai/glm-5.2`, puis les lignes GPT natives | `5`, puis `102 + sourcePriority` | Hors des cinq | + +Avec une liste vide, opencodex ne fixe aucune priorité et les cinq suivent les priorités normales du catalogue. + +Les emplacements complétés sont des annonces ordinaires : l'agent principal peut choisir l'un de ces modèles. La liste n'est pas non plus une liste d'autorisation : Codex accepte un modèle du catalogue hors des cinq lorsque l'agent principal le nomme exactement. Pour contrôler ce que Codex annonce : + +- Mettez cinq modèles en avant. Une liste complète ne laisse aucun emplacement à compléter. +- Désactivez un modèle que vous ne voulez jamais voir proposé, ou retirez-le des `selectedModels` de son fournisseur. Un modèle désactivé ou non sélectionné quitte le sélecteur et ne peut pas compléter un emplacement. +- `modelPickerOrder` modifie les priorités que Codex utilise pour trier. Une liste uniquement routée déplace les lignes listées non mises en avant à `1000` et au-delà ; les lignes routées non listées complètent donc les emplacements en premier. Une liste qui contient un identifiant natif nu ordonne tout le sélecteur, lignes mises en avant comprises : les lignes listées passent en premier et occupent les emplacements annoncés avant toute ligne non listée. Voir [Model ordering](/guides/model-ordering/). + +En v2, Codex écarte les lignes épinglées `"disabled"` avant de prendre les cinq ; le reste fonctionne de la même façon. La liste des consignes v2 d'opencodex (`{{roster}}`) ne nomme que les modèles configurés présents parmi les cinq : les modèles de complément apparaissent dans la description de l'outil Codex, jamais dans les consignes d'opencodex. Codex lit le catalogue au démarrage d'une session ; une modification de la liste s'applique donc aux nouvelles sessions. + ## Modèle et efforts de délégation La **délégation de sous-agent** du tableau de bord contrôle trois paramètres associés : @@ -239,6 +275,10 @@ un décompte partiel positif avant de passer un dépassement de modèle ou d'eff Il peut être masqué par le sélecteur, en dehors de la limite d'affichage de cinq modèles, absent du catalogue ou épinglé à la v1. Une valeur de surface `"v2"`, `null` ou absente est admissible ; une valeur explicite `"v1"` ne l’est pas. +### Pourquoi `spawn_agent` liste-t-il des modèles que je n'ai pas mis en avant ? + +Codex remplit jusqu'à cinq emplacements annoncés à partir du catalogue, par priorité. Avec moins de cinq modèles mis en avant, les lignes suivantes occupent les emplacements restants ; voir la section « Modèles annoncés par `spawn_agent` » ci-dessus. + ### Les changements de mode affectent-ils les sessions en cours ? Non. Démarrez une nouvelle session Codex après avoir changé de mode. Si un hôte App de longue durée affiche toujours des informations obsolètes diff --git a/docs-site/src/content/docs/fr/guides/web-dashboard.md b/docs-site/src/content/docs/fr/guides/web-dashboard.md index 1777b9be85..c0133287a2 100644 --- a/docs-site/src/content/docs/fr/guides/web-dashboard.md +++ b/docs-site/src/content/docs/fr/guides/web-dashboard.md @@ -13,9 +13,11 @@ catalogue, les services auxiliaires, les réglages des sous-agents et le trafic ocx gui ``` -Cette commande ouvre `http://localhost:` dans votre navigateur — ou -`http://127.0.0.1:` lorsque l’ingress de gestion du hub est activé — et démarre d'abord automatiquement le -proxy si nécessaire. En développement, vous pouvez lancer séparément le serveur de développement de +Cette commande ouvre l’adresse du proxy actif dans votre navigateur : `http://127.0.0.1:` par défaut, +ou `http://[::1]:` pour une liaison à l’adresse de bouclage IPv6 littérale `::1`. Ces adresses conservent +l’origine configurée nécessaire à l’appairage local du navigateur. Lorsque l’ingress de gestion du hub est activé, +elle ouvre `http://127.0.0.1:`. Le proxy démarre d’abord automatiquement si nécessaire. +En développement, vous pouvez lancer séparément le serveur de développement de l'interface contre un proxy déjà actif : ```bash @@ -37,6 +39,12 @@ remplissage automatique. Le tableau de bord lui-même ne conserve le jeton qu'en dans `localStorage` ni dans `sessionStorage` ; son enregistrement dépend entièrement du navigateur ou du gestionnaire de mots de passe. +**Mémoriser cet appareil** est désactivé par défaut. Sur un tableau de bord HTTPS direct (ou en boucle locale), le serveur échange le jeton administrateur contre un cookie d’appareil HttpOnly, SameSite=Strict et une preuve distincte stockée dans le localStorage de ce site. Le cookie est Secure en HTTPS et limité à l’hôte. Ni le cookie ni la preuve ne sont le jeton administrateur, et aucun ne fonctionne seul. Les cookies sont partagés entre les ports d’un même nom d’hôte ; la preuve, limitée à l’origine, lie l’appareil mémorisé à l’origine de ce tableau de bord. Préférez tout de même un nom d’hôte dédié. Le jeton administrateur n’est jamais écrit dans localStorage ou sessionStorage. Si le stockage du navigateur est indisponible ou ne peut enregistrer la preuve, la mémorisation est signalée comme indisponible. Pour un tableau de bord autonome derrière un proxy inverse qui termine TLS, OpenCodex voit une requête HTTP simple et refuse donc la mémorisation pour cette adresse ; la fenêtre de connexion l’explique et désactive l’option, et la connexion sans mémorisation fonctionne toujours. Un écouteur de gestion Hub de confiance fait exception et peut toujours mémoriser les appareils. + +Le fichier privé dashboard-sessions.json conserve les empreintes du cookie, de la preuve, du jeton administrateur et de l’identité du navigateur, l’origine du serveur et une expiration fixe de 30 jours. La relance de l’application Safari reprend une session courte tant que cet appareil reste autorisé. Les sessions mémorisées ne peuvent pas approuver les actions de consentement : étoile GitHub, consommation de crédits de réinitialisation, modification des couches de prompt, connexion Meta Muse, changements de compatibilité du bureau ou validation des quotas. Utilisez une nouvelle session locale ou appairée pour ces actions. Les tableaux de bord relayés, inter-origines ou HTTP distant ne prennent pas en charge la mémorisation. L’expiration, un changement d’identité du navigateur ou la rotation du jeton suivie d’un redémarrage imposent une nouvelle connexion. + +Une action **Oublier cet appareil** réussie, dans la barre latérale ou les actions mobiles, ainsi que la déconnexion réussie, révoque immédiatement l’enregistrement et toutes ses sessions et supprime la preuve du navigateur. Un échec de déconnexion conserve la preuve pour réessayer. Le serveur synchronise le contenu avant de publier le changement ; la persistance de l’entrée de répertoire après un plantage est assurée au mieux. Les anciennes clés de jeton mémorisé sont supprimées sans lecture ni migration. Réservez cette option aux appareils de confiance ; elle ne rétablit pas l’AutoFill de Safari. + ## Barre de résumé des quotas Une ligne de résumé en haut de chaque page, sauf la page Sécurité au démarrage, indique @@ -47,6 +55,8 @@ force jamais d'actualisation en amont. - Chaque étiquette affiche la fenêtre signalée prioritaire : d'abord hebdomadaire, puis mensuelle, puis 5 heures, puis une fenêtre nommée par le fournisseur ou des crédits prépayés. +- Les crédits prépayés utilisés à 90 % ou plus deviennent prioritaires si la fenêtre habituelle + préférée n'est pas critique. Si elle est aussi critique, elle reste affichée en priorité. - Une étiquette passe en ambre à 70 % d'utilisation et en rouge à 90 %. - Survolez une étiquette ou donnez-lui le focus au clavier pour voir toutes les fenêtres signalées avec leur heure de réinitialisation et l'heure de la lecture. Sur un écran tactile, le premier @@ -71,6 +81,7 @@ force jamais d'actualisation en amont. | **Sécurité au démarrage** | Vérifiez si le routage Codex injecté résiste à un redémarrage, avec des états distincts pour le service et le lanceur intermédiaire, ainsi que les commandes de réparation exactes. | | **Zone de notification Windows** | Installez au niveau de l'utilisateur un contrôleur lancé à la connexion pour démarrer, arrêter ou redémarrer le proxy en un clic, ouvrir le tableau de bord et consulter l'état. Ce contrôleur n'est pas un service de redémarrage du proxy. | | **Démarrage automatique de Codex** | Autorisez un lanceur intermédiaire Codex déjà installé à exécuter `ocx ensure`. Ce commutateur n'installe ni lanceur ni service d'arrière-plan. | +| **Télémétrie** | Activez ou désactivez **Partager des statistiques d'utilisation anonymes** et consultez **Aperçu du JSON** dans **Détails du proxy** (`#proxy-telemetry`). Lors du premier lancement ou après une mise à jour sans décision enregistrée, la fenêtre de consentement n'enregistre un choix que lorsque vous cliquez sur **Continuer** (`PUT /api/telemetry`) ; la fermer n'enregistre rien. Voir [Télémétrie et confidentialité](/fr/guides/telemetry/). | | **Fournisseurs** | Ajoutez, modifiez, activez, désactivez ou supprimez des fournisseurs, définissez le fournisseur par défaut parmi ceux activés et gérez, lorsqu'ils sont pris en charge, les groupes de comptes OAuth et de clés API. Si le fournisseur par défaut actuel est supprimé, le premier fournisseur activé restant prend sa place ; s'il n'en reste aucun, la suppression est refusée et le fournisseur par défaut actuel est conservé. Les réglages d'un fournisseur peuvent désactiver la découverte dynamique pour les points de terminaison dont le catalogue `/models` est absent, lent ou trop volumineux. Pour les groupes OAuth Claude (Anthropic), chaque compte connecté affiche ses propres barres de limites sur 5 heures et une semaine — l'utilisation est propre à chaque identifiant. En cas d'échec d'une sonde, les dernières barres connues sont conservées et marquées indisponibles jusqu'à la prochaine actualisation réussie. | | **Ajouter un fournisseur** | Recherchez dans les préréglages du registre une connexion par compte, un service à clé API, un serveur local ou un point de terminaison personnalisé. | | **Authentification Codex** | Ajoutez des comptes ChatGPT/Codex au groupe, sélectionnez le compte de la prochaine session, actualisez les quotas sur 5 h, une semaine et 30 jours, activez ou désactivez le changement automatique selon les quotas, réglez son seuil de 1 à 100 % et configurez le basculement en cas de défaillance transitoire. | @@ -83,13 +94,23 @@ force jamais d'actualisation en amont. Les vues Utilisation, Tableau de bord, Fournisseurs, Catalogue des fournisseurs et Clés API signalent les enregistrements exclus, même sans résultat lisible. Les décomptes, les dates et les classements reposent uniquement sur les lignes lisibles. L’enregistrement de l’ordre des modèles par utilisation est refusé si l’historique est incomplet : choisissez un autre ordre ou réparez l’historique avant de réessayer. +### Utilisation par application + +La page Utilisation s’ouvre avec **Toutes les applications**, **Tous les appareils** et **30 jours** dans le périmètre d’accès actuel. Vous pouvez restreindre l’application, l’appareil ou la période pendant que la page reste ouverte ; la rouvrir rétablit ces valeurs par défaut. + +Avec toutes les applications sélectionnées, la section **Applications** apparaît après Modèles et Fournisseurs. Pour les appareils et la période choisis, elle indique la part du total des jetons, le nombre de jetons, le coût estimé au tarif catalogue de l’API, le nombre de requêtes et celui des requêtes dont l’utilisation a été mesurée, par application. Codex CLI, bureau et IDE sont regroupés sous Codex. Les anciens enregistrements sans attribution client sont **Non classés**, distincts de **Inconnu** et **Autre**. Sélectionner une seule application masque cette répartition. Un proxy qui ne fournit pas cette répartition l’affiche comme indisponible ; une répartition vide indique l’absence d’utilisation par application dans le rapport. + ### Filtrer les requêtes -Les filtres combinent interface, requêtes interceptées, fournisseur, modèle exact, statut, période, vitesse et identifiant de conversation dans le journal chargé. Les choix incluent les tentatives de repli ; les modèles ignorent la casse et les espaces externes, sans correspondance partielle. Un choix disparu revient à Tous. +Le détail d’une requête privilégie la cause d’échec amont enregistrée plutôt qu’un message générique d’erreur du proxy. Le nombre d’envois physiques est toujours affiché lorsqu’il est valide ; une comptabilité absente ou invalide affiche **Unavailable**, et non zéro. **Retries** compte les envois après le premier uniquement lorsqu’une seule tentative entièrement réglée et cohérente est enregistrée. Les tentatives multiples, les comptabilités non résolues ou incohérentes et les normalisations avec perte omettent les retries au lieu d’en inventer. Une cause persistante inconnue revient au titre fondé sur le statut, sans attribution brute. **Upstream reason** affiche une condition fournisseur classée (par exemple limite de débit atteinte, quota ou crédits épuisés, fenêtre de contexte dépassée, emplacement non pris en charge, vérification du compte requise ou modèle indisponible), et **Failure detail** affiche un texte rédigé par le proxy, comme un délai d’inactivité ou une limite d’octets ; les nouvelles lignes ne conservent pas le texte d’erreur propre au fournisseur. D’anciens fichiers `usage.jsonl` peuvent encore le contenir, mais le tableau de bord l’écarte à la lecture. + +Les journaux réunissent toutes les applications et affichent une pastille client contenant uniquement une icône sur chaque requête, à la place des onglets par application. Les clients reconnus utilisent leur logo SVG ; les clients inconnus ou autres utilisent une icône neutre en forme de point d’interrogation. Les noms des applications restent accessibles aux lecteurs d’écran, sans texte visible. L’absence d’attribution client n’implique ni Codex ni un échec de la requête. La pastille identifie l’application cliente indépendamment du fournisseur et du protocole ; ce n’est pas un filtre d’application. + +Les filtres combinent requêtes interceptées, fournisseur, modèle exact, statut, période, vitesse et identifiant de conversation dans le journal chargé. Les choix incluent les tentatives de repli ; les modèles ignorent la casse et les espaces externes, sans correspondance partielle. Un choix disparu revient à Tous. Les périodes de 15 minutes, une heure et un jour évoluent toutes les 30 secondes dans l’onglet Logs, même sans actualisation automatique. La vitesse mesure les jetons de sortie par seconde sur toute la durée : moins de 15, de 15 à moins de 50, ou au moins 50 ; les valeurs indisponibles sont exclues quand ce filtre est actif. Réussite : 2xx ; erreur : 4xx/5xx. -Le compteur compare les résultats au total chargé ; la réinitialisation restaure toutes les lignes. Aucun résultat diffère d’un journal vide. Flèches et Home/End pilotent le sélecteur d’interface. Aucun historique au-delà du journal chargé n’est interrogé. +Le compteur compare les résultats au total chargé ; la réinitialisation restaure toutes les lignes. Aucun résultat diffère d’un journal vide. Aucun historique au-delà du journal chargé n’est interrogé. ### Liens directs vers une section diff --git a/docs-site/src/content/docs/fr/index.mdx b/docs-site/src/content/docs/fr/index.mdx index f482f1fe67..52182d8745 100644 --- a/docs-site/src/content/docs/fr/index.mdx +++ b/docs-site/src/content/docs/fr/index.mdx @@ -1,12 +1,12 @@ --- -title: "opencodex — Exécutez Codex sur n’importe quel LLM" -description: Proxy universel de fournisseurs pour OpenAI Codex et Claude Code — utilisez n’importe quel LLM avec Codex CLI, App, SDK et Claude Code. +title: "opencodex — Une passerelle locale pour Codex, Claude Code et plus" +description: "Une passerelle locale unique pour vos outils de code IA et vos modèles : utilisez les fournisseurs de votre choix avec Codex, Claude Code, Claude Desktop et Grok Build, et connectez d’autres outils via des configurations gérées." template: splash head: # La marque d'abord, pas de suffixe « | opencodex » : Google compare le nom du site avec # le titre de la page d'accueil, donc le mot-symbole mène et n'est pas dupliqué. - tag: title - content: "opencodex — Exécutez Codex sur n’importe quel LLM" + content: "opencodex — Une passerelle locale pour Codex, Claude Code et plus" - tag: meta attrs: property: og:locale diff --git a/docs-site/src/content/docs/fr/reference/cli.md b/docs-site/src/content/docs/fr/reference/cli.md index 2563cdc0de..2f16c1c5fc 100644 --- a/docs-site/src/content/docs/fr/reference/cli.md +++ b/docs-site/src/content/docs/fr/reference/cli.md @@ -17,7 +17,7 @@ Exécutez `ocx help` (ou `ocx --help` / `ocx -h`) pour afficher l’aide génér Les commandes de gestion communiquent avec l’API de gestion du proxy actif. Elles s’appuient sur le port d’exécution enregistré et sur des contrôles d’identité, plutôt que sur un second chemin de configuration. Un proxy arrêté ou inaccessible est représenté par une réponse HTTP 503 et entraîne un code de sortie CLI non nul. Les commandes explicitement documentées comme des opérations de configuration hors ligne peuvent, quant à elles, valider et modifier le fichier de configuration sans proxy actif. -`check` ne consulte aucun registre et n’exécute pas Codex. Sur POSIX, `selectionAttested` peut être `true` si le résolveur choisit le même chemin canonique que le candidat d’environnement capturé par le lanceur publié. Un manifeste npm-global lié peut alors établir `managed: true` s’il prouve la propriété et, lorsqu’une version candidate est signalée, si elle correspond à celle du manifeste ; les candidats persistants restent non attestés. Windows diffère l’inspection sans lire les fichiers du candidat ni la configuration. Une exécution directe via Bun ou les sources n’a pas de preuve du lanceur. `plan` consulte le registre officiel avec une configuration, un cache et des journaux npm temporaires isolés, et refuse les sessions actives ou une observation incomplète des processus. Il n’installe rien et n’envoie aucun signal. Voir [les commandes et motifs de refus complets (en anglais)](/reference/cli/agents/#read-only-codex-cli-update-plan). +`check` ne consulte aucun registre et n’exécute pas Codex. Sur POSIX, `selectionAttested` peut être `true` si le résolveur choisit le même chemin canonique que le candidat d’environnement capturé par le lanceur publié. Un manifeste npm-global lié peut alors établir `managed: true` s’il prouve la propriété et, lorsqu’une version candidate est signalée, si elle correspond à celle du manifeste ; les candidats persistants restent non attestés. Windows x64 prend aussi en charge un `codex.cmd` npm standard absolu lié à la preuve, avec une chaîne d’outils Node/npm liée par les handles — locale au préfixe quand elle est présente, sinon la paire PATH capturée ancrée à l’architecture du lanceur — et une plateforme de support vérifiée dans le préfixe, en utilisant des handles maintenus qui refusent la réanalyse. Les autres dispositions Windows restent différées ou non gérées. Un résultat `managed` Windows ne décrit que la disposition d’installation observée : le Node/npm lié est la chaîne d’outils de métadonnées en lecture seule de l’outil de mise à jour, et non une garantie sur l’interpréteur qu’une invocation ultérieure de `codex.cmd` résoudra. Une exécution directe via Bun ou les sources n’a pas de preuve du lanceur. `plan` consulte le registre officiel avec une configuration, un cache et des journaux npm temporaires isolés, et refuse les sessions actives ou une observation incomplète des processus. Il n’installe rien et n’envoie aucun signal. Sur Windows x64, `apply` exige un préfixe npm borné doté d'une autorité d'écriture privée vérifiée et préserve les packages et shims non liés ; les dispositions observées non prises en charge renvoient `applicable: false` et `refusal: windows_apply_disabled` ; la sélection par PATH seul, les wrappers de démarrage automatique OpenCodex et les replis global/vendor restent différés. Voir [les commandes et motifs de refus complets (en anglais)](/reference/cli/agents/#read-only-codex-cli-update-plan). Pour observer une installation Windows x64, consultez [`attest`](/fr/reference/cli/agents/). Sans chemins explicites, la commande observe le candidat sélectionné identifié par l’instantané du lanceur lié à la preuve ; aucune autorité de mise à jour ni sélection du runtime n’est attestée. diff --git a/docs-site/src/content/docs/fr/reference/cli/agents.md b/docs-site/src/content/docs/fr/reference/cli/agents.md index 1337a76d0c..a55deef900 100644 --- a/docs-site/src/content/docs/fr/reference/cli/agents.md +++ b/docs-site/src/content/docs/fr/reference/cli/agents.md @@ -169,6 +169,39 @@ Les familles sont `opus`, `fable`, `sonnet` et `haiku` ; les nouveaux itinérai seulement quand cette famille est vide. Les anciens indicateurs d'application `--static`, `--hybrid` et `--discovery-only` restent soutenus. Utilisez `ocx claude config ...` pour les réglages Claude Code. +### `ocx codex [codex args...]` + +La clé est fournie uniquement si la configuration et ses espaces de noms sont protégés contre les modifications par d’autres principaux ; l’utilisateur courant et les autorités privilégiées du système sont de confiance. Les processus du même utilisateur sont de confiance : un acteur disposant de vos droits d’écriture peut déjà lire votre fichier de clé OpenCodex. Le remplacement de configuration par ce même utilisateur entre vérification et démarrage natif est hors de ce modèle de menace ; le lanceur ne fige pas la configuration lors du transfert. + +Sur une installation Windows normale, les droits ProgramData par défaut permettent à d’autres utilisateurs de créer des dossiers. Les identifiants automatiques sont donc retenus même si `ProgramData\OpenAI\Codex` est absent. Le dossier de configuration système de Codex sous ProgramData doit exister et être accessible en écriture uniquement à Administrators/SYSTEM ; ses dossiers ancêtres doivent empêcher leur remplacement par d’autres utilisateurs. Demandez à un administrateur de vérifier la politique des dossiers. opencodex ne modifie jamais lui-même les ACL et ne fournit aucune commande de préparation. + +Vous pouvez aussi fournir la clé vous-même, par exemple en exportant `OPENCODEX_API_AUTH_TOKEN` ; `ocx codex` conserve sa valeur. Les fichiers de configuration système existants empêchent toujours les identifiants automatiques et nécessitent un examen séparé. Chaque motif de refus produit une courte ligne stderr précise, sans valeur de clé, contenu ni chemin de fichier de clé. + +Placez `--` avant une invite d’un seul mot pour éviter la sélection d’une sous-commande Codex inconnue. + +L’espace de configuration machine doit empêcher un autre utilisateur de créer les fichiers système absents. Un espace Windows ProgramData/OpenAI/Codex non protégé bloque l’injection sans créer de répertoire. macOS accepte les ACL de refus seules et les autorisations en lecture seule. Toute autorisation d’écriture, ajout, suppression, modification d’attributs, de sécurité ou de propriétaire est refusée, même après un refus. Les tags inconnus et erreurs d’inspection entraînent un refus. + +Un nouveau jeton de service est chargé uniquement si argv respecte la liste ci-dessous, si aucune variable non vide de proxy HTTP(S)/ALL ou `CODEX_*`/`OPENAI_*`/`AZURE_OPENAI_*` ne surcharge l’environnement (`CODEX_HOME` canonique est permis), et si les espaces home/config/système passent les contrôles de propriété. La configuration doit contenir uniquement les clés auditées et le fournisseur loopback géré exact, sans autre consommateur de clé ni couche de configuration. Tout argument hors liste, dont `-c`/`--config`, `-p`/`--profile`, les options inconnues et `resume`/`fork`, retient le jeton avec un diagnostic sans valeurs ; les identifiants explicites et les arguments sont préservés. + +Le répertoire canonique et `config.toml` doivent appartenir à l’utilisateur courant. POSIX refuse les écritures group/other ; Windows vérifie le SID propriétaire et refuse les droits d’écriture DACL hors utilisateur courant, SYSTEM et Administrators. Les droits de remplacement des ancêtres sont vérifiés. macOS exige aussi l’absence de préférences Codex forcées. Ces contrôles n’isolent pas un processus malveillant du même utilisateur ou d’un administrateur. + +| Allowlist | Flags | +| --- | --- | +| Switches | `--no-daemon`, `--json`, `--ephemeral`, `--skip-git-repo-check`, `--no-alt-screen`, `--full-auto`, `--dangerously-bypass-approvals-and-sandbox`, `--search` | +| One value | `--model`/`-m`, `--sandbox`/`-s`, `--ask-for-approval`/`-a`, `--image`/`-i` | + + + +Le chargement automatique interprète `CODEX_HOME` comme un chemin littéral, y compris `~` et les espaces, le vérifie et transmet le même chemin absolu canonique au processus enfant. Un répertoire illisible empêche le chargement. Toute valeur non vide de `HTTP_PROXY`, `HTTPS_PROXY` ou `ALL_PROXY`, quelle que soit la casse, empêche aussi le chargement indépendamment de `NO_PROXY` ; les lancements refusés et les identifiants exportés par l’utilisateur restent inchangés. Avec un nouveau jeton, `NO_PROXY` et `no_proxy` du processus enfant incluent `127.0.0.1` et `::1` en conservant les exclusions existantes. Activer `features.respect_system_proxy` ou transmettre `--enable`/`--disable` empêche le chargement automatique. + +Le lanceur tente de démarrer le proxy puis transmet les arguments d’origine à Codex, sans réécrire sa configuration. Les routes natives et les passerelles tierces sautent le démarrage. Une route inconnue avertit puis tente le démarrage ; un échec avertit et continue. L’aide, la version et les commandes internes comme `login`, `doctor` et `help` sautent le démarrage et la lecture automatique du jeton. + +Un `OPENCODEX_API_AUTH_TOKEN` absent est lu dans le `service-api-token` de cette installation uniquement si toute la configuration de transport du provider sélectionné correspond au bloc géré pour son écouteur loopback ou sa connexion client locale enregistrée. Le nom et les commentaires ne suffisent pas. Destinations inconnues ou distantes, profile par défaut, configuration de projet, `OPENAI_BASE_URL` et options transmises `-c`/`--config`, `-p`/`--profile`, `-C`/`--cd`, `--remote` désactivent cette lecture. Les identifiants exportés et les arguments sont conservés ; les remplacements du fichier et les collisions avec les jetons d’administration sont refusés. + +Seul un wrapper autostart correspondant (`matched`) lance directement son Codex sous-jacent. Un état inconnu, y compris une exception d’inspection, exige un contournement vérifié ; les wrappers CMD Windows gérés doivent correspondre au modèle généré complet avant leur exécution avec `OCX_SHIM_BYPASS=1`. Les lanceurs npm ordinaires restent pris en charge. Un wrapper invérifiable ou obsolète entraîne le code de sortie 1 sans démarrer Codex ; actualisez-le avec `ocx codex-shim install`. Le lancement ne répare pas les shims ; le contrôle de contenu ne garantit ni la provenance du fichier Windows sous-jacent ni l’absence de remplacement concurrent. + +Aide du lanceur : `ocx help codex` ; aide de Codex : `ocx codex --help`. Le comportement ultérieur de `codex` seul est conservé. + ### `ocx opencode [opencode args...]` Vérifiez que le proxy est actif, puis lancez opencode avec les blocs `provider.opencodex` et `providers.opencodex` générés dans la couche d’exécution intégrée d’OpenCode (`OPENCODE_CONFIG_CONTENT`). La configuration intégrée existante est préservée et seules ces deux clés sont remplacées pour ce lancement. Les fichiers `opencode.json` globaux ou propres au projet peuvent être lus afin de signaler une substitution existante, mais les fichiers sur disque ne sont jamais modifiés. Les modèles routés apparaissent sous la forme `opencodex//`. Un lancement ultérieur de `opencode` sans intermédiaire se comporte exactement comme auparavant. @@ -287,7 +320,7 @@ ocx system settings --stream-mode eager-relay ocx system codex-cli-update check --json ``` -`check` ne consulte aucun registre et n’exécute pas Codex. Sur POSIX, `selectionAttested` peut être `true` si le résolveur choisit le même chemin canonique que le candidat d’environnement capturé par le lanceur publié. Un manifeste npm-global lié peut alors établir `managed: true` s’il prouve la propriété et, lorsqu’une version candidate est signalée, si elle correspond à celle du manifeste ; les candidats persistants restent non attestés. Windows diffère l’inspection sans lire les fichiers du candidat ni la configuration. Une exécution directe via Bun ou les sources n’a pas de preuve du lanceur. `plan` consulte le registre officiel avec une configuration, un cache et des journaux npm temporaires isolés, et refuse les sessions actives ou une observation incomplète des processus. Il n’installe rien et n’envoie aucun signal. Voir [les commandes et motifs de refus complets (en anglais)](/reference/cli/agents/#read-only-codex-cli-update-plan). +`check` ne consulte aucun registre et n’exécute pas Codex. Sur POSIX, `selectionAttested` peut être `true` si le résolveur choisit le même chemin canonique que le candidat d’environnement capturé par le lanceur publié. Un manifeste npm-global lié peut alors établir `managed: true` s’il prouve la propriété et, lorsqu’une version candidate est signalée, si elle correspond à celle du manifeste ; les candidats persistants restent non attestés. Windows x64 prend aussi en charge un `codex.cmd` npm standard absolu lié à la preuve, avec une chaîne d’outils Node/npm liée par les handles — locale au préfixe quand elle est présente, sinon la paire PATH capturée ancrée à l’architecture du lanceur — et une plateforme de support vérifiée dans le préfixe, en utilisant des handles maintenus qui refusent la réanalyse. Les autres dispositions Windows restent différées ou non gérées. Un résultat `managed` Windows ne décrit que la disposition d’installation observée : le Node/npm lié est la chaîne d’outils de métadonnées en lecture seule de l’outil de mise à jour, et non une garantie sur l’interpréteur qu’une invocation ultérieure de `codex.cmd` résoudra. Une exécution directe via Bun ou les sources n’a pas de preuve du lanceur. `plan` consulte le registre officiel avec une configuration, un cache et des journaux npm temporaires isolés, et refuse les sessions actives ou une observation incomplète des processus. Il n’installe rien et n’envoie aucun signal. Sur Windows x64, `apply` exige un préfixe npm borné doté d'une autorité d'écriture privée vérifiée et préserve les packages et shims non liés ; les dispositions observées non prises en charge renvoient `applicable: false` et `refusal: windows_apply_disabled` ; la sélection par PATH seul, les wrappers de démarrage automatique OpenCodex et les replis global/vendor restent différés. Voir [les commandes et motifs de refus complets (en anglais)](/reference/cli/agents/#read-only-codex-cli-update-plan). Sous Windows, une commande simple capturée comme `CODEX_CLI_PATH=codex`, un chemin distant ou un chemin de périphérique produit plutôt `candidate_path_unavailable`. Le candidat a été capturé, mais son chemin ne convient pas à cette inspection. @@ -322,3 +355,19 @@ This takes effect on the **next routed `ocx claude` launch**, injecting `CLAUDE_ Claude Code **2.1.257 or newer** is required for FORCE. Plugin and built-in agents (including Explore/Plan) and per-call model arguments are overridden. Forks and subagent skills with `model: inherit` keep the main conversation model. The main loop and Haiku/small-fast sidecars are unaffected. Existing roster files remain available. The dashboard warns about old or unknown CLI versions, unavailable targets, and either variable already present in `settings.json` → `env` (which overrides launch env). Detection is read-only and server-local: it cannot inspect another launch shell, another machine, or project-local settings. An unknown result is not proof of force support. + +## Hermes / Command Code: model names + +Hermes and Command Code support `--model-names alias|routed` (API: `modelNames`). +The default is `routed`, independent of `preferModelAliasIds`. A connection +stores its mode; later Apply without the option preserves it. Alias mode uses +only provider-qualified aliases that the router proves equivalent; missing, +unsafe or colliding aliases fall back to routed keys. Combos keep their keys. +Removed/renamed aliases migrate on the next successful managed refresh, with +foreign-edit refusal. Named Hermes profiles need explicit Apply. + +`ocx export --client hermes --model-names alias --json` previews a current +already loaded catalog without writing client files or managed state; a cold or +stale catalog returns unavailable. Explicit `--out` writes an export artifact. +See the [English integration guide](/guides/integrations/#opt-in-alias-model-names) +for the canonical workflow. diff --git a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md index 918e27f2e3..dce969c0e9 100644 --- a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md @@ -32,7 +32,13 @@ ocx start --socks5-off ### `ocx stop` -Arrête le proxy actif à partir de son PID, supprime le fichier de PID et rétablit le fonctionnement natif de Codex. Si un service d’arrière-plan géré est installé, `ocx stop` l’arrête d’abord afin qu’il ne puisse pas relancer le proxy. Le bouton **Stop** du tableau de bord Web exécute la même opération (`POST /api/stop`) sur tous les backends, sauf le Planificateur de tâches Windows : le wrapper peut y relancer le proxy après la fin de la tâche, donc le tableau de bord refuse avec `respawnable_service`, ne modifie rien et vous demande d'exécuter `ocx stop`. +Un Link Child non supervisé restaure Codex natif et Grok avant de libérer son listener lors d’un signal, en revérifiant la connexion à chaque écriture. Service/Desktop, sibling, transfert de redémarrage et reçu stop du parent préservent les intégrations. L’arrêt refuse le redémarrage avec `409 runtime_stopping`. Une terminaison forcée peut éviter le signal ; la restauration par `ocx stop` reste nécessaire. + +Arrête le proxy actif à partir de son PID, supprime le fichier de PID et rétablit le fonctionnement natif de Codex. Si un service d’arrière-plan géré est installé, `ocx stop` l’arrête d’abord afin qu’il ne puisse pas relancer le proxy. Le levier du proxy du tableau de bord Web, tiré jusqu’en bas dans la barre latérale, exécute la même opération (`POST /api/stop`) sur tous les backends, sauf le Planificateur de tâches Windows : le wrapper peut y relancer le proxy après la fin de la tâche, donc le tableau de bord refuse avec `respawnable_service`, ne modifie rien et vous demande d'exécuter `ocx stop`. + +Sur un client hub connecté, `ocx stop`, y compris via l’API, conserve le routage Codex, le catalogue et la configuration Grok appartenant à la connexion ; `ocx start` les dessert de nouveau. L’arrêt explicite d’un Remote Link Child rétablit au contraire, si la restauration partagée réussit, le routage natif de Codex, le catalogue et les métadonnées de reprise sauvegardées, et supprime la configuration Grok gérée. La connexion Home enregistrée reste conservée ; `ocx disconnect` la supprime. + +Pour réutiliser Home depuis Codex après cette restauration, lancez `ocx start` (ou `ocx service start` si un service est installé), puis `ocx sync --restart-codex`. Le démarrage seul ne réapplique pas le routage ; sync ne recrée pas le bloc Grok. Si l’appartenance de la connexion ne peut pas être confirmée avant l’arrêt du service, l’API d’arrêt renvoie HTTP 409 avec `sharedTeardown: "refused"` et laisse le proxy et le gestionnaire de service actifs. Attendez la fin de la connexion ou déconnexion en cours, puis réessayez. ### `ocx restart` @@ -74,6 +80,10 @@ Réparez l'historique d'une tâche compactée par un fournisseur routé avant de Arrête le service et le proxy, supprime le service et le shim Codex, rétablit le fonctionnement natif de Codex, puis supprime la configuration locale d’opencodex uniquement si toutes les étapes de restauration ont réussi. `remove` est un alias de `uninstall`. Le nettoyage de la configuration exige les métadonnées de propriété créées par une installation récente ; les répertoires anciens ou partagés sont conservés. +Lorsque `ocx uninstall` s’exécute en tant que root ou depuis une invite Windows élevée (administrateur), il vérifie d’abord qu’aucun autre compte ne peut modifier le répertoire de configuration, les répertoires qui le contiennent ni aucun répertoire qu’il contient, et qu’aucun lien du répertoire de configuration ne mène en dehors de celui-ci (sous Windows, qu’il ne contient aucun lien). Si l’une de ces vérifications échoue, la désinstallation s’arrête avant toute modification et en indique la raison. Lancez `ocx uninstall` avec le compte propriétaire du répertoire de configuration, sans `sudo` ni droits d’administrateur, ou réservez ces répertoires à ce compte et supprimez ces liens, puis relancez la commande. Sous Windows ARM64, où opencodex ne peut pas savoir si l’invite est élevée, la même vérification s’applique ; si elle ne peut pas aboutir, arrêtez opencodex et supprimez vous-même le répertoire de configuration. + +Une entrée enregistrée dont un répertoire parent dans le répertoire de configuration est un lien (lien symbolique ou jonction) est laissée en place et listée parmi les chemins restants, et l’exécution se termine par une désinstallation partielle. Remplacez ce lien par le répertoire réel ou supprimez-le, puis relancez `ocx uninstall` pour terminer. + ## État et santé ### `ocx status [--json]` @@ -141,7 +151,7 @@ Vérifie l’identité du proxy actif. La sortie destinée aux utilisateurs indi ### `ocx ready [--json] [--wait [--timeout ]]` -Vérifie l’état de préparation après synchronisation au moyen du point de terminaison non authentifié `GET /readyz`. Il renvoie `200` lorsque le service est prêt, ou `503` avec `Retry-After: 1` pour les états `pending` et terminal `failed`. Son identité HTTP expurgée est `{service, version, uptime, pid, port, status, protocol, minimumClientProtocol, managementUrl}`. `protocol` est la version courante du protocole distant du hub, `minimumClientProtocol` la plus ancienne version cliente compatible et `managementUrl` l’origine canonique de gestion visible par le navigateur. Les anciens proxys dépourvus de `/readyz` échouent de manière sûre avec l’état `unreachable` ; `/healthz` mesure la disponibilité du processus, et non son état de préparation. +Vérifie l’état de préparation après synchronisation au moyen du point de terminaison non authentifié `GET /readyz`. Il renvoie `200` lorsque le service est prêt, ou `503` avec `Retry-After: 1` pour les états `pending` et terminal `failed`. Son identité HTTP expurgée est `{service, version, uptime, pid, port, status, protocol, minimumClientProtocol, managementUrl, features}`. `protocol` est la version courante du protocole distant du hub, `minimumClientProtocol` la plus ancienne version cliente compatible et `managementUrl` l’origine canonique de gestion visible par le navigateur. Les anciens proxys dépourvus de `/readyz` échouent de manière sûre avec l’état `unreachable` ; `/healthz` mesure la disponibilité du processus, et non son état de préparation. Par défaut, la commande effectue une seule sonde. Avec `--wait`, elle interroge le service jusqu’à ce qu’il soit prêt ou jusqu’à l’expiration du délai, mais s’arrête immédiatement si elle observe l’état terminal `failed`. Le délai par défaut est de 45 secondes. `--timeout ` exige `--wait` et accepte un entier positif compris entre 1 et 300. La sortie JSON de la CLI est `{ready, status, pid, port}`, où `status` vaut `ready`, `pending`, `failed` ou `unreachable`. Les codes de sortie sont 0 si le service est prêt ; 1 s’il n’est pas prêt, reste en attente, échoue, dépasse le délai ou est inaccessible ; et 64 si les arguments sont invalides. @@ -153,7 +163,13 @@ La section **OAuth reliability** indique si le stockage des identifiants est acc ## Synchronisation du catalogue -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +Sur un Home Remote Link, après la validation et l’enregistrement d’un catalogue à jour, `ocx sync` synchronise aussi les Enfants liés admissibles. `--local-only` désactive cette propagation. `--json` produit un seul document `ocx.sync.fanout/1` contenant le résultat du Home et l’état de chaque Enfant ; un Enfant ignoré indique la raison. Le code de sortie non nul du Home est renvoyé sans modification. Si le Home réussit, un Enfant connecté ignoré pendant la propagation, en échec ou en délai dépassé, ou un registre de liens illisible, entraîne le code de sortie 6. Les exclusions intentionnelles, comme les liens initiés par le client et `--local-only`, conservent leur comportement ; les Enfants connectés ignorés reçoivent une indication `hint`. En mode texte, le registre illisible produit un message sans chemin. Le code 7 est réservé à une mise à jour en cours. Si la synchronisation du Home lève une erreur en mode JSON, stdout conserve un seul document et stderr fournit un diagnostic assaini. + +La propagation ne demande jamais le redémarrage de l’application Codex ni d’un app-server sur un Enfant. Pour cela, utilisez GOAT, exécutez `ocx sync --restart-codex` sur un Enfant `ocx` complet, ou relancez séparément Codex Desktop et les processus `app-server` sur un hôte léger `ocx-child`. La synchronisation épinglée de l’Enfant peut néanmoins redémarrer son propre runtime client OpenCodex après l’application de réglages Home modifiés. Si le Home interrompt son processus SSH local après un délai dépassé, une synchronisation distante déjà lancée peut continuer sur l’Enfant. + +> **Enfant Remote Link :** sur un enfant `ocx` complet, `ocx sync` applique aussi les réglages Codex du Home et redémarre le runtime client s'il a démarré avant cette application ; si ce redémarrage échoue, l'ancien runtime continue de servir et la commande quitte avec un code non nul. Sur un hôte léger `ocx-child`, `ocx-child sync` démarre `ocx-child serve` s'il est absent, le relance lorsque `runtimeStartedAt < lastApplyAt` et publie la parité au mieux hors mode `stale` (un échec de relance arrête l'ancien relais et quitte avec un code non nul sans redémarrer Codex Desktop ni `app-server`, qu'il faut relancer séparément). Les champs de `ocx status --json` (ou `ocx-child status --json`) sur l'enfant et `ocx link status --json` sur le Home sont décrits dans [Remote Link apply parity](/reference/cli/lifecycle/#remote-link-apply-parity) (en anglais). Sur le Home, `ocx link check (--link-id | --all)` lit la version installée et la voie de mise à jour de chaque enfant lancé par le Home via `ocx update --plan` par SSH (60 secondes par enfant, sans rien installer), et `ocx link status --json` ajoute un bloc `child` à chaque ligne ; voir [Child install, catalog and activity](/guides/remote-link/#child-install-catalog-and-activity) (en anglais). Un redémarrage explicitement demandé a également lieu après une modification de `config.toml` validée et enregistrée, même si les octets du catalogue et du cache restent identiques. Une opération sans changement de configuration, un refus, une validation préalable ou une écriture annulée ne le déclenche pas. Sans option de redémarrage, sync ne redémarre jamais Codex automatiquement. @@ -169,6 +185,8 @@ Si des processus Codex `app-server` de longue durée sont encore actifs, `ocx sy Lorsque la commande s’exécute depuis l’application Codex, le redémarrage est confié à un assistant détaché et cette session se termine avec l’application. +**Synchronisation épinglée.** `ocx sync --expect-link ` (enfant Remote Link) et `ocx sync --expect-hub-key ` (client hub) ne synchronisent que si cette machine est toujours connectée à ce lien ou avec cette clé. Sinon, rien n'est modifié, les fournisseurs locaux ne sont pas synchronisés, la commande quitte avec le code 5 et la dernière ligne de stderr est `{"phase":"child_link_mismatch"|"hub_client_mismatch","reason":...}`. Un drapeau mal formé ou répété quitte avec le code 2. Détails : [référence anglaise](/reference/cli/lifecycle/#sync-only-from-the-expected-home---expect-link-and---expect-hub-key). + ### `ocx sync-cache [--restart-codex] [--restart-app-server-only]` Invalide le cache local du sélecteur de modèles de Codex afin qu’il soit reconstruit à partir du catalogue opencodex actif. Le même avertissement concernant un `app-server` obsolète et les mêmes options de redémarrage que pour `ocx sync` s’appliquent. @@ -351,7 +369,7 @@ Lorsqu'une version plus récente du paquet est connue, la zone de notification a ### `ocx gui` -Ouvre le [tableau de bord Web](/fr/guides/web-dashboard/) à l’adresse `http://localhost:` — ou `http://127.0.0.1:` lorsque l’ingress de gestion du hub est activé — et démarre automatiquement le proxy s’il n’est pas actif. +Ouvre le [tableau de bord Web](/fr/guides/web-dashboard/) à l’adresse `http://127.0.0.1:` — ou `http://127.0.0.1:` lorsque l’ingress de gestion du hub est activé — et démarre automatiquement le proxy s’il n’est pas actif. ## Mise à jour diff --git a/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md b/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md index 89d1e6773f..2aeeaf1a3d 100644 --- a/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md @@ -25,6 +25,7 @@ Gestion des fournisseurs non interactive. Les entrées de registre sont classée | `quota` | `--refresh`, `--json` | Lire les rapports sur les quotas des fournisseurs. | | `presets` | `--json` | Répertoriez les préréglages du fournisseur de tableau de bord. | | `account-mode` | `pool`, `direct`, `--json` | Sélectionnez le routage de compte mutualisé ou direct Codex. | +| `import-cc-switch` | `--source `, `--provider `, `--apply`, `--restore`, `--allow-private-network`, `--json` | Prévisualiser, appliquer sélectivement ou restaurer des entrées de fournisseurs sans clé depuis une base SQLite (`cc-switch.db`) ou un fichier JSON CC-Switch. | Par défaut, `add`, `remove` et `set-default` modifient la configuration locale. Ajoutez `--live` pour modifier le proxy actif, et `--yes` pour une suppression en direct. `--sync --json` tente aussi la synchronisation après enregistrement ; en cas d’échec, la sauvegarde reste acquise, avec un code non nul et `needsSync: true`. `--live` et `--sync` sont incompatibles. Voir le [guide anglais](/reference/cli/providers-accounts/#snapshot-edit-and-apply-with-a-baseline) pour pacing et snapshot/apply. @@ -60,6 +61,27 @@ la frontière est à vous de la respecter. Deux raisons pour lesquelles c'est im Utilisez `--api-key` ou un identifiant OAuth pour tout ce qui est secret. ::: +### Import de fournisseurs CC-Switch sans clé + +```bash +ocx provider import-cc-switch --source ~/.cc-switch/cc-switch.db +ocx stop +ocx provider import-cc-switch --source ~/.cc-switch/cc-switch.db --provider my-provider --apply +# Démarrez le proxy dans un autre terminal (ou exécutez ocx ensure), puis ajoutez les clés : +ocx start +printf '%s\n' "$API_KEY" | ocx account add-key my-provider + +# Chemin d’annulation distinct (arrêtez d’abord le proxy ; supprime uniquement les entrées sans clé non modifiées) : +ocx stop +ocx provider import-cc-switch --restore +``` + +`ocx provider import-cc-switch` projette des valeurs **uniquement** depuis une liste blanche explicite de champs de métadonnées non secrets (identifiants de fournisseur, types d’application, URL de base, dialectes et modèles par défaut) à partir d’une base SQLite ou d’un fichier JSON CC-Switch ordinaire. Les octets de la source et de la configuration intégrée sont lus de manière transitoire pour analyser l’entrée, tandis que les champs secrets, noms libres et commentaires TOML sont ignorés au niveau des octets, ne sont jamais décodés en chaînes, écrits ni journalisés, et les tampons d’octets transitoires sont remis à zéro dans `finally`. Les règles strictes de chemin d’URL (`http(s)://host[:port]` sans chemin ou avec 1 à 4 segments d’API en minuscules `[a-z0-9._-]` tels que `/v1`, `/api/v1` ou `/compatible-mode/v1`) et les contrôles syntaxiques d’identifiant/modèle servent de défense en profondeur sans faire écho aux valeurs rejetées. Les fichiers sources sont ouverts une seule fois avec vérification de descripteur `O_NOFOLLOW | O_NONBLOCK` et désérialisés en lecture seule en mémoire pour SQLite sans fichier temporaire ; les fichiers SQLite ayant plusieurs liens physiques (`nlink > 1`) sont refusés afin d’empêcher le contournement des contrôles de fichiers annexes, et si un fichier voisin `-wal` ou `-journal` est non vide, l’import refuse et demande de fermer CC-Switch (ou de consolider la base) avant de réessayer. N’importez que depuis une source locale CC-Switch de confiance et vérifiez chaque ID, modèle et `baseUrl` affichés avant d’ajouter des identifiants : + +- **Aperçu (par défaut) :** exige `--source `, n’écrit rien et indique les entrées découvertes, éligibles, en conflit et invalides. +- **Application (`--apply`) :** exige `--source ` et un proxy arrêté (`ocx stop`), et est refusée sur un Remote Link Child. Répétez `--provider ` pour n’importer que certaines entrées, ou passez `--allow-private-network` pour autoriser les URL de bouclage ou de réseau privé. Même sans aperçu préalable, `--apply` affiche chaque ID de fournisseur, modèle par défaut et URL de destination avant d’écrire les entrées sans clé et le journal d’annulation `$OPENCODEX_HOME/cc-switch-provider-import-journal.json` (`stdout` en mode texte, `stderr` en mode `--json`) ; un second `--apply` est refusé tant qu’un journal actif existe. Vérifiez les entrées affichées, démarrez le proxy (`ocx start` dans un autre terminal ou `ocx ensure`), puis ajoutez les clés avec `printf '%s\n' "$API_KEY" | ocx account add-key ` (entrée standard redirigée) ou `ocx login `. +- **Restauration (`--restore`) :** chemin d’annulation distinct (et non la suite de l’ajout d’identifiants) qui exige un proxy arrêté (`ocx stop`), est refusé sur un Remote Link Child et n’accepte ni `--source`, ni `--provider`, ni `--allow-private-network`. Il inspecte `auth.json` en lecture seule au niveau des octets (échec fermé s’il est illisible ou mal formé) et ne supprime du journal actif que les fournisseurs qui correspondent encore à leur état importé sans clé et qui ne sont ni sélectionnés comme `defaultProvider` ni référencés par le routage, les combos, la politique de repli (fallback policy), les comptes OAuth ou les clés API. + ## Authentification ### `ocx login ` @@ -107,7 +129,7 @@ Répertoriez et changez de compte de fournisseur et de pools de clés API via le la surface est : ```text -Usage: ocx account ... +Usage: ocx account ... list [provider] Codex account pool, OAuth accounts and API keys (identifiers shown masked as the API returns them). history openai [--limit <1-200>] Recent routing decisions for one Codex pool account. @@ -121,6 +143,7 @@ pause Hold an account out of automatic selection. resume Return a paused account to automatic selection. pause-exhausted Pause every account whose quota is spent. clear-cooldown Drop a cooldown the proxy set after an upstream failure. +reset-affinity [--json] Confirm all session bindings are cleared, even with no accounts; selection and pause state stay unchanged. Run on the Home; a Remote Link Child names the Home and sends no request. strategy [] Stratégie du pool ; least-loaded est réservé à Kiro. sticky [<1-100>] Requests a bound thread keeps on one account; omit the value to read it. priority [first|earlier|normal|later|last|-100..100|reset] Selection order; omit the value to read it. @@ -138,7 +161,7 @@ A selection-order change applies from the next unbound request and never moves a Les sous-commandes nécessitent que le proxy soit en cours d'exécution et résolvent automatiquement son port d'exécution enregistré, sauf `import-orca` : l'aperçu est purement local, et `import-orca --apply` exige que le proxy soit arrêté. Les opérations réussies se terminent 0. Utilisation invalide, un fournisseur ou un identifiant inconnu, un -proxy, ou un échec API se termine 1. Les champs d'informations d'identification sont affichés exactement comme la gestion API +proxy inaccessible ou un échec API renvoient normalement le code 1. Pour `reset-affinity`, HTTP 404 renvoie 4 et HTTP 409 renvoie 5 ; les autres échecs API et les résultats non confirmés renvoient 1. Les champs d'informations d'identification sont affichés exactement comme la gestion API les renvoie (y compris son masquage) ; Les clés API brutes et les jetons OAuth ne sont jamais restitués. Affichage les commodités sont synthétisées côté client, comme dans le tableau de bord : `main` désigne la connexion Codex App du groupe de comptes `openai`, les comptes OAuth sans adresse e-mail apparaissent sous la forme `Account N`, @@ -164,6 +187,15 @@ et la colonne plan/label recouvre le plan, l'e-mail masqué, l'étiquette et la ### `ocx account list [provider] [--json] [--all]` +Les comptes ChatGPT enregistrés dans le pool restent consultables sur les hôtes sans répertoire +Codex natif, y compris dans le tableau de bord et lors de l'actualisation des comptes. Cette consultation +ne crée pas de répertoire Codex et ne déconnecte pas le compte principal natif. Désactiver l'intégration +du client Codex ne désactive pas l'observation du quota d'une connexion native existante. Un chemin +`CODEX_HOME` explicite invalide continue de produire une erreur de configuration. Un stockage +`OPENCODEX_HOME` non sûr produit une erreur même si le répertoire Codex natif est absent. La résolution +du chemin Codex par défaut renvoie également une erreur s'il désigne un fichier, un lien symbolique +dont la cible n'existe pas, ou si son répertoire parent ne peut pas être traversé. + Sans fournisseur, répertorie le groupe de comptes Codex, les comptes OAuth et les groupes de clés API configurés. Les fournisseurs vides sont ignorés à moins que `--all` soit présent. Avec un fournisseur, répertorie uniquement cette famille d’informations d’identification. La sortie destinée aux utilisateurs utilise `PROVIDER TYPE ID PLAN/LABEL PRIORITY STATUS` ; une ligne Codex sélectionnée manuellement porte la mention @@ -198,9 +230,8 @@ cet état et quitte toujours 0. `--json` renvoie : `auto` efface la sélection manuelle pour que le pool place à nouveau le travail selon sa propre stratégie — sauf si un compte Codex porte littéralement l'id `auto`, qui l'emporte par correspondance exacte d'id ; `ocx account clear ` rétablit toujours la sélection automatique. Un compte Codex peut être désigné par l'alias défini avec `ocx account alias` au lieu de son id ; cela vaut aussi pour `priority`, `pause`, `resume`, `clear-cooldown`, `remove` et `alias`. Pour les comptes Codex, `auto`, `main` et `__main__` sont réservés sans distinction de casse et ne peuvent pas être attribués comme alias. Les noms affichés des comptes OAuth et des clés API conservent leurs règles existantes. Sélectionne un compte Codex, un compte OAuth ou une clé API existant. Pour `openai`, `main` sélectionne la -connexion Codex App. Une sélection en mode Codex Pool efface l'affinité locale du processus et s'applique à la requête suivante, -dont un provenant d'une tâche visible existante ; le redémarrage du proxy ou l'expulsion par affinité peuvent également laisser une tâche -non lié, tandis que les demandes en cours conservent leur compte capturé. Cela contrôle uniquement le routage du pool ; +connexion Codex App. Une sélection en mode Codex Pool efface l'affinité et s'applique à la requête suivante, +y compris si elle provient d'une tâche visible existante. Les liaisons des requêtes avec un identifiant de session (y compris les tours habituels de Codex CLI et App et les sous-agents), ou des requêtes sans session ancrées sur leur parent immédiat, peuvent survivre à un redémarrage normal du proxy jusqu’à 24 heures d’inactivité, si l’enregistrement final de l’affinité à l’arrêt réussit. Les chaînes sans session plus profondes et les liaisons à la connexion principale de Codex App restent en mémoire uniquement et sont réattribuées après le redémarrage ; une expulsion, la suppression du compte, une reconnexion, un plantage ou une réinitialisation de l’affinité peuvent laisser une tâche non liée, tandis que les demandes en cours conservent leur compte capturé. Cela contrôle uniquement le routage du pool ; Le mode direct continue d’utiliser les informations d’identification principales de l’appelant. Commutation proactive basée sur l'utilisation, 401/403 réauthentification, 429/retry-after temps de recharge, exclusion et pré-sortie 429/402 échec la récupération peut sélectionner ultérieurement un autre compte Pool éligible. Ces chemins de récupération restent actifs lorsque @@ -411,18 +442,19 @@ déplacé car son AAD chiffré et l'identité du trousseau de clés du système ### `ocx models [subcommand]` · `ocx model ` -`ocx model` est un alias de `ocx models`. Sans sous-commande, répertoriez les modèles implantés statiquement dans -fournisseurs configurés. `--provider` filtre un fournisseur configuré et `--json` renvoie le modèle +`ocx model` est un alias de `ocx models`. Sans sous-commande, liste les ID enregistrés et connus du routeur, notamment les modèles du registre, les modèles personnalisés et le cache de découverte de ce processus CLI. Le cache d’un nouveau processus peut être vide : ce n’est pas le catalogue du proxy actif. Certains anciens fournisseurs à clé conservent les modèles du registre après un changement de destination. `--provider` filtre un fournisseur configuré et `--json` renvoie le modèle métadonnées. `live` lit le catalogue en cours d'exécution ; `add`, `edit`, `remove` et `list-custom` gèrent le manuel entrées de catalogue ; `enable`, `disable` et `provider` contrôlent la visibilité ; `selected` contrôle un liste d'autorisation des fournisseurs ; `context` contrôle les plafonds de contexte du fournisseur ; et `shadow` gère l'arrière-plan interception d'appel fantôme. +Le champ `reasoningEfforts` apparaît uniquement avec `--json`. La valeur `null` signifie que la liste est inconnue ou n’a pas été consultée, notamment si sa vérification nécessiterait d’ouvrir le trousseau du système. Le tableau vide `[]` indique une liste explicitement vide ou un effort de raisonnement désactivé pour le modèle, par exemple par `noReasoningModels`. Utilisez `ocx models live` pour consulter le catalogue du proxy actif. + `add` et `remove` enregistrent localement par défaut ; `--live` modifie le proxy actif. Sans proxy, un enregistrement local `--json` renvoie `sync.status: "not-attempted"`, `needsSync: true` et le code 0. Une synchronisation tentée mais échouée conserve la sauvegarde et renvoie un code non nul. `list-custom` reste local. `display-name` prend l’ID amont brut ; `order` prend les IDs publics du sélecteur. Voir les contraintes de permutation complète, de préfixe featured et de réinitialisation native dans le [guide anglais](/reference/cli/providers-accounts/#display-names-and-picker-identities). | Sous-commande | Drapeaux pris en charge | Actions | | --- | --- | --- | -| `list` (par défaut) | `--provider `, `--json` | Répertoriez les modèles prédéfinis dans les fournisseurs configurés. | +| `list` (par défaut) | `--provider `, `--json` | Liste les modèles locaux enregistrés et connus du routeur. | | `live` | `--provider `, `--json` | Lisez le catalogue en cours d'exécution, y compris les modèles découverts lors de l'exécution. Les lignes sont marquées `native`/`routed`, `custom` et `enabled`/`disabled`. | | `add ` | `--display-name `, `--context-window `, `--modalities `, `--live`, `--json` | Enregistre un modèle personnalisé localement, ou sur le proxy actif avec `--live`. | | `edit ` | `--model-id `, `--display-name `, `--context-window `, `--modalities `, `--json` | Modifiez un modèle personnalisé. `-` libère un champ ; `0` efface la fenêtre contextuelle. | diff --git a/docs-site/src/content/docs/fr/reference/client-support.md b/docs-site/src/content/docs/fr/reference/client-support.md new file mode 100644 index 0000000000..92087d244c --- /dev/null +++ b/docs-site/src/content/docs/fr/reference/client-support.md @@ -0,0 +1,60 @@ +--- +title: "Clients pris en charge" +description: "Les outils de code auxquels opencodex se connecte, la façon dont chacun est relié et le protocole qu’il utilise." +--- + + + + +opencodex est une passerelle locale unique pour vos outils de code IA et vos modèles. Il configure certains outils nativement ; pour les autres, il exporte ou gère un fichier de configuration qui dirige l’outil vers le proxy local. Cette page est générée à partir des registres du code et reflète donc exactement ce que fournit la version actuelle. + +## Niveaux de prise en charge + +- **implemented**: le client figure dans le registre. Pour les configurations exportées, le protocole indiqué est lu dans la configuration générée par opencodex, et la génération échoue s’il change. Un protocole marqué *revu* désigne un point de terminaison issu d’une revue plutôt que de la configuration elle-même (clients natifs, et clients qui déduisent un point de terminaison précis d’un réglage) ; le générateur vérifie que le code revu est toujours en place. Les lignes « Compatible OpenAI » n’affirment aucun point de terminaison. +- **test-covered**: implemented, et un cas de test choisi en revue qui exerce ce client est lié. Le générateur vérifie seulement que le test existe toujours et qu’il est actif ; lisez-le pour savoir ce qu’il vérifie. +- **Vérifié à l’exécution**: une observation datée : une personne a exécuté le produit et la version du client indiqués avec la version d’opencodex indiquée, pour le scénario décrit, à cette date, et a lié la preuve. Cela ne dit rien des autres versions ou produits. La preuve est revue lors de l’ajout du résultat ; le générateur ne la rejoue pas. Un tiret signifie qu’aucun résultat n’est enregistré. + +## Clients + +| Client | Natif | Export de configuration | Intégration de fichier gérée | Protocole entrant | Niveau | Vérifié à l’exécution | Remarques | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Codex (CLI, app, SDK) | Oui | — | — | Responses (revu) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/codex-integration/codex-inject-missing-config.test.ts)) | — | Configuré par opencodex lui-même ; aucun fichier de configuration exporté. [guide](/fr/guides/codex-integration/) | +| Claude Code | Oui | — | — | Anthropic Messages (revu) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/claude-integration/claude-cli.test.ts)) | — | Configuré par opencodex lui-même ; aucun fichier de configuration exporté. [guide](/fr/guides/claude-code/) | +| Claude Desktop | Oui | — | — | Anthropic Messages (revu) | implemented | — | Configuré par opencodex lui-même ; aucun fichier de configuration exporté. | +| Grok Build | Oui | — | — | Responses (revu) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/providers/xai/grok-config-inject.test.ts)) | — | Configuré par opencodex lui-même ; aucun fichier de configuration exporté. [guide](/fr/guides/grok-build/) | +| Qoder | — | JSON | Oui | Compatible OpenAI (point de terminaison choisi par le client) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/qoder-client.test.ts)) | — | Écoute locale uniquement. | +| Qoder CN | — | JSON | Oui | Compatible OpenAI (point de terminaison choisi par le client) | implemented | — | Écoute locale uniquement. | +| WorkBuddy | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/agent-clients.test.ts)) | — | Écoute locale uniquement. L’application exécute d’abord une vérification propre au client et peut refuser. | +| WorkBuddy AI | — | JSON | Oui | Chat Completions | implemented | — | Écoute locale uniquement. L’application exécute d’abord une vérification propre au client et peut refuser. | +| OpenCode | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | L’export prend aussi en charge une écoute distante (il ajoute l’en-tête de clé API). [guide](/fr/guides/opencode/) | +| Pi | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | Écoute locale uniquement. [guide](/fr/guides/pi/) | +| Oh My Pi (omp) | — | YAML | Oui | Chat Completions; Responses (modèles OpenAI natifs uniquement) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | Écoute locale uniquement. Ne modifie que son propre bloc YAML. | +| Hermes | — | YAML | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/hermes-catalog-refresh.test.ts)) | — | L’export prend aussi en charge une écoute distante (il ajoute l’en-tête de clé API). Ne modifie que son propre bloc YAML. | +| OpenClaw | — | JSON5 | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/gui/integrations-invariants.test.ts)) | — | L’export prend aussi en charge une écoute distante (il ajoute l’en-tête de clé API). | +| Kimi CLI | — | TOML | Oui | Compatible OpenAI (point de terminaison choisi par le client) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export-new-clients.test.ts)) | — | Écoute locale uniquement. | +| Gajae | — | YAML | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/client-export-modality-enum.test.ts)) | — | Écoute locale uniquement. | +| DSH | — | YAML | Oui | Responses | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | Écoute locale uniquement. Écrit dans le magasin de fournisseurs actuel du client. Ne modifie que son propre bloc YAML. Les écritures passent par un fichier de verrou placé à côté de la configuration. | +| MCode | — | YAML | Oui | Anthropic Messages | implemented | — | Écoute locale uniquement. Les écritures passent par un fichier de verrou placé à côté de la configuration. | +| ZCode | — | JSON | Oui | Responses (revu) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/integrations-current-store.test.ts)) | — | Écoute locale uniquement. Écrit dans le magasin de fournisseurs actuel du client. Le client choisit le point de terminaison à partir de ce réglage (vérifié en revue d’après le comportement documenté du client). | +| Command Code | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/command-code-client.test.ts)) | — | Écoute locale uniquement. Les écritures passent par un fichier de verrou placé à côté de la configuration. | +| Prime | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/prime-client.test.ts)) | — | Écoute locale uniquement. | +| Aside | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/aside-profiles-catalog-refresh.test.ts)) | — | Écoute locale uniquement. | +| Raycast | — | YAML | Oui | Chat Completions (revu) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/raycast-client.test.ts)) | — | Écoute locale uniquement. Le client choisit le point de terminaison à partir de ce réglage (vérifié en revue d’après le comportement documenté du client). | +| omo | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/omo-client.test.ts)) | — | Écoute locale uniquement. | +| Cline | — | JSON | Oui | Responses | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/cline-client.test.ts)) | — | Écoute locale uniquement. Les écritures passent par un fichier de verrou placé à côté de la configuration. | +| Kilo Code | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/client-export-reasoning-controls.test.ts)) | — | L’export prend aussi en charge une écoute distante (il ajoute l’en-tête de clé API). | +| Factory Droid | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/droid-client.test.ts)) | — | Écoute locale uniquement. [guide](/fr/guides/factory-droid/) | +| Gentle Shell | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Écoute locale uniquement. | +| T3 Code | — | JSON | Oui | Anthropic Messages | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Écoute locale uniquement. L’application exécute d’abord une vérification propre au client et peut refuser. | + +## Points de terminaison entrants + +Le proxy accepte ces protocoles. Un outil absent de la liste peut quand même se connecter s’il permet de définir un point de terminaison personnalisé pour l’un d’eux. + +- `POST /v1/responses`: Responses +- `POST /v1/chat/completions`: Chat Completions +- `POST /v1/messages`: Anthropic Messages + +## Tenir cette page à jour + +Cette page est générée par `scripts/generate-client-support-matrix.ts` à partir des registres d’export, d’intégration gérée et d’intégration native. Pour ajouter un client, ajoutez son entrée dans `scripts/client-support-matrix/metadata.ts` puis lancez `bun run docs:clients` ; `bun run docs:clients:check` échoue tant que la page validée est obsolète. diff --git a/docs-site/src/content/docs/fr/reference/configuration.md b/docs-site/src/content/docs/fr/reference/configuration.md index 36ed8b6a38..4b8aabe981 100644 --- a/docs-site/src/content/docs/fr/reference/configuration.md +++ b/docs-site/src/content/docs/fr/reference/configuration.md @@ -27,6 +27,12 @@ Si le fichier ne peut pas être analysé, opencodex le sauvegarde en tant que `config.json.invalid-`, affiche un avertissement dans la console et démarre avec les valeurs par défaut. Si le fichier est absent, la valeur par défaut d'une nouvelle installation est également utilisée : un fournisseur `openai` en mode transfert. +Les commandes locales `ocx config set`, `unset`, `import`, la commande hors ligne `ocx effort`, +les opérations add/remove sur les modèles personnalisés et add/remove/set-default sur les fournisseurs +refusent un fichier `config.json` existant invalide ou illisible sans en modifier les octets. +Exécutez `ocx config validate` et réparez le fichier avant de réessayer. Si une configuration existe déjà, +import exige également que le fichier cible soit lisible et valide. + ## Priorité et valeurs par défaut Les valeurs valides de `config.json` remplacent les valeurs par défaut intégrées. Les champs facultatifs absents utilisent les valeurs par défaut @@ -60,4 +66,6 @@ opencodex écrit les fichiers gérés `config.toml` et `opencodex-catalog.json` puis le renomme (`atomicWriteFile`). Cela évite les fichiers partiels lorsque plusieurs processus d'écriture, comme `ocx stop` et le gestionnaire d'arrêt du proxy, restaurent Codex simultanément. +Sous Windows, si `opencodex-catalog.json` porte l'attribut lecture seule et bloque le renommage, opencodex efface +l'attribut et réessaie une fois ; un échec persistant signale `Codex catalog is read-only: ` au lieu d'un `EPERM` brut. ::: diff --git a/docs-site/src/content/docs/fr/reference/configuration/advisor.md b/docs-site/src/content/docs/fr/reference/configuration/advisor.md index 9c48ca2b7f..de932d06d6 100644 --- a/docs-site/src/content/docs/fr/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/fr/reference/configuration/advisor.md @@ -77,12 +77,18 @@ Une consultation peut envoyer : Le fournisseur conseiller configuré peut différer de celui du worker. +Les consultations respectent à la fois la portée de modèles capturée de la clé d'API de l'appelant, son consentement aux combos payants et ses limites de repli par appareil, et les limites d'hôte de la propre clé d'admission d'Advisor : `OPENCODEX_API_AUTH_TOKEN` ou le fichier de jeton du service s'il est défini et accepté par ce proxy, sinon la première clé d'API configurée. L'ordre des clés ne compte que dans ce dernier cas : placez en premier une clé qui peut atteindre le modèle Advisor, sinon chaque consultation est indisponible. Lorsqu'un jeton d'environnement ou de service est défini, c'est lui qui contrôle la consultation. Ces règles s'appliquent aussi aux choix de combo, aux modèles de décision imbriqués et aux nouvelles tentatives. Une consultation qui ne peut pas les satisfaire renvoie au worker un avis d'indisponibilité. + +Par exemple, une clé `laptop` avec `allowMeteredComboTargets: false` ne peut pas dépenser sur des cibles de combo facturées via Advisor, et `fallback.devices.laptop.provider: false` bloque aussi les sauts de repli de fournisseur d'Advisor. Un appelant loopback sans clé a toujours besoin de l'option `allowMeteredTargets: true` du combo. Lorsque les deux clés définissent `allowMeteredComboTargets: true` et que le combo définit `allowMeteredTargets: true`, Advisor peut utiliser ses cibles facturées, y compris via l'écouteur loopback d'une liaison publique. Le serveur capture la politique de l'appelant lorsqu'il authentifie la requête, avant d'attendre de la capacité pour le corps ou de le lire ; des modifications ultérieures des clés ou du repli ne peuvent pas élargir cette consultation. Cela couvre aussi les assistants de vision routés, les requêtes compact et leurs modèles de décision, ainsi que chaque nouvelle tentative de candidat dans un tour WebSocket. Chaque nouveau tour WebSocket capture sa propre politique. + OpenCodex n'insère pas dans ce prompt de clés d'API de fournisseur, d'en-têtes Authorization, de jetons OAuth, de secrets de configuration réservés au backend, d'environnement de processus, ni de chaîne de pensée cachée. Il ne déchiffre pas et ne transmet pas un raisonnement privé chiffré du fournisseur. **Le contenu de la tâche n'est pas expurgé de secrets.** Une clé collée dans la tâche, un secret dans un fichier lu par les outils, ou un jeton imprimé par un outil ou un journal peut être envoyé. OpenCodex n'exécute pas de DLP général. ## Autorité Le conseil manuel est le résultat d'outil de l'appel `advisor` que le worker a lui-même émis. Ce résultat est un objet JSON. Le champ `advice` est le texte du modèle conseiller. Le champ `status` est écrit par le runtime. +Lors des tours de recherche web basés sur fetch, la boucle de recherche n'expose l'outil synthétique `advisor` et n'intercepte ses appels de consultation manuelle que si le `tool_choice` effectif l'autorise. Un choix `allowed_tools` limité à `web_search` exclut les consultations manuelles du conseiller. Activer la recherche hébergée n'élargit pas cette autorisation. + Le conseil automatique est un objet JSON cité dans un message consultatif de rôle user distinct. Seule l’instruction fixe du runtime reste dans le message developer ; le texte généré par le conseiller ne passe jamais dans developer/system. Cela fonctionne avec OpenAI Chat et Anthropic sans inventer un appel d’outil. Les guillemets empêchent la rupture structurelle et les champs falsifiés, pas toute injection en langage naturel. Un protocole dédié pourrait mieux distinguer le conseil d’une demande utilisateur. Chaque requête permet au plus trois consultations et quatre continuations du worker. À la limite, l’outil advisor est retiré ; un nouvel appel reçoit une dernière continuation avec un résultat de limite, puis un autre appel termine avec 502 advisor_continuation_limit sans nouvel envoi. La limite est partagée avec les reprises de complétion vide. La suppression ne lit pas les chaînes du conseiller. Le dédoublonnage automatique appartient au registre du serveur. Un message developer, même s'il recopie le texte de transport, ne supprime pas le preflight. diff --git a/docs-site/src/content/docs/fr/reference/configuration/agents.md b/docs-site/src/content/docs/fr/reference/configuration/agents.md index 495c22ffdb..6053240fb5 100644 --- a/docs-site/src/content/docs/fr/reference/configuration/agents.md +++ b/docs-site/src/content/docs/fr/reference/configuration/agents.md @@ -34,6 +34,8 @@ L’API de gestion expose `GET`/`PUT /api/v2`, `/api/injection-model`, `/api/eff La page Codex Auth permet également de modifier l’indicateur natif `default_mode_request_user_input` de Codex (`GET`/`PUT /api/codex-auth/features/default-mode-request-user-input`). Son activation ajoute `[features] default_mode_request_user_input = true` au fichier `$CODEX_HOME/config.toml` de Codex au moyen de la commande officielle `codex features enable|disable`. Cette modification préserve le format du fichier et est retirée lorsque l’option est désactivée. Codex peut ainsi suspendre une session en mode Default et vous poser des questions avec l’outil `request_user_input`. Cet indicateur est encore en développement en amont et ne s’applique qu’aux nouvelles sessions ; l’activation échoue explicitement si la version installée de Codex ne le reconnaît pas encore. +Pendant qu’une mise à jour de Codex CLI détient l’installation, cette commande renvoie HTTP 503 avec `codex_cli_selection_busy` et `retryable: true` avant toute exécution. Réessayez après la mise à jour ; les erreurs d’écriture de la configuration restent des réponses 502. + ## Liste des modèles et consignes La liste v2 effective comprend, parmi les modèles configurés, les cinq premiers qui sont visibles dans le sélecteur, classés par priorité, compatibles avec v2 et présents dans le catalogue injecté. Un modèle est admissible en v2 si son choix imposé en amont vaut explicitement `"v2"`, vaut `null` ou est absent. Un véritable choix `"v1"` l’exclut. Les entrées exclues restent dans la configuration afin de pouvoir redevenir admissibles ultérieurement. @@ -122,3 +124,10 @@ Un plafond ne peut que réduire l’effort. Le niveau retenu est le niveau annon Les plafonds configurés s’appliquent aussi aux tours Chat Completions natifs admissibles sans effort épinglé pour le modèle. La conversion vers la valeur du fournisseur intervient lorsqu’un épinglage est appliqué ou qu’un plafond modifie la valeur ; sinon, la valeur de l’appelant natif conserve sa forme d’origine. Pour une présentation destinée aux débutants des comportements v1, default et v2, consultez [Surfaces de sous-agents](/fr/guides/sub-agent-surface/). + +## Mise à jour de la CLI pendant la synchronisation v1 + +Si la synchronisation avec `multiAgentMode: "v1"` doit désactiver la substitution v2 globale +de Codex, une mise à jour de la CLI Codex en cours peut refuser temporairement cette +synchronisation. Réessayez après la mise à jour. Un répertoire Codex utilisant déjà v1 +peut toujours être synchronisé, car aucune commande native de fonctionnalité n'est nécessaire. diff --git a/docs-site/src/content/docs/fr/reference/configuration/providers.md b/docs-site/src/content/docs/fr/reference/configuration/providers.md index 241b15259e..7214b3e422 100644 --- a/docs-site/src/content/docs/fr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/fr/reference/configuration/providers.md @@ -6,12 +6,26 @@ description: Entrées du fournisseur, authentification, points de terminaison, c Un fournisseur indique à opencodex où se trouve un modèle, quel adaptateur de protocole il utilise et comment les requêtes sont authentifiées. +## Nombre d’images par requête Mistral + +La limite d’images de Mistral et le réglage `mistralMaxImages` sont décrits dans la [référence canonique en anglais](/reference/configuration/providers/#mistral-images-per-request). Pour les éléments `image_url` qui atteignent le limiteur, les références absentes, vides ou non textuelles sont remplacées par du texte dans la copie sortante sans consommer la limite. Lors de la traduction des requêtes Responses, le parseur omet les blocs `input_image` sans URL utilisable ni identifiant de fichier. Dans un bloc de message ou de sortie d’outil, un `file_id` non vide sans `image_url` non vide entraîne le refus de la requête par la protection des médias avant l’envoi à Mistral ; dans un `agent_message` rejoué, que la protection n’inspecte pas, le parseur émet à la place un marqueur textuel `[image: ]` envoyé comme texte ordinaire sans consommer la limite d’images. Le limiteur compte seulement les chaînes non vides dans `image_url` ou `image_url.url`, sans vérifier la syntaxe ni l’accessibilité des URL. Les autres destinations restent inchangées. + ## Contexte des fournisseurs personnalisés En l’absence de fenêtre déclarée ou configurée, OpenCodex utilise les métadonnées Azure, puis celles du modèle dans les tables embarquées du fabricant ou des agrégateurs, puis le Context cap activé, et enfin 128k. Le minimum des valeurs déclarées/configurées est conservé et le cap reste une limite. Les fournisseurs intégrés ne changent pas. L’ID exact est prioritaire ; les variantes de casse ou point/tiret doivent être non ambiguës. L’estimation affecte la compaction de Codex et les catalogues clients, dont Claude, mais ne prouve pas la capacité du relais pour le routage. Configurez modelContextWindows ou Context cap si le relais accepte moins. Aucun cap n’est activé automatiquement et aucune requête de test n’est envoyée au modèle. Les limites de l’API OpenAI ne sont pas celles de l’abonnement Codex. Cette estimation est désactivée par défaut : activez-la par fournisseur avec `inferContextWindow: true`. Sans ce réglage, une fenêtre absente utilise le Context cap activé, puis 128k. +## GPT-6.1 Terra + +[GPT-6.1 Terra](https://openai.com/index/introducing-gpt-6-1-terra/), sorti le 26 octobre 2026, succède à GPT-5.6 Terra. `gpt-6.1-terra` reste disponible aux côtés de `gpt-5.6-terra`, sans changement de modèle par défaut ni de liste de sous-agents. GitHub Copilot utilise Responses ; OpenRouter propose `openai/gpt-6.1-terra` avec un contexte de 1,050,000 tokens et des tarifs de $1.00 en entrée / $5.00 en sortie par million de tokens. + +Codex natif : contexte par défaut de 500,000 tokens, plafond étendu de 872,000, effort par défaut `low` et niveaux `low`, `medium`, `high`, `xhigh`, `max`, `ultra`. Le niveau natif `ultra` est envoyé sous la forme `max` sur le réseau. La ligne native propose uniquement Fast. + +[API OpenAI](https://developers.openai.com/api/docs/models/gpt-6.1-terra) : contexte de 1,050,000 tokens, sortie maximale de 128,000 ; entrée texte/image, sortie texte ; connaissances arrêtées au 2026-06-01. Efforts : `none`, `low`, `medium` (par défaut), `high`, `xhigh`, `max`. Points de terminaison : `v1/responses` et `v1/chat/completions` ; les appels d’outils nécessitent Responses. + +Par million de tokens : $1.00 en entrée, $0.05 en lecture du cache, $1.25 en écriture du cache (30 minutes), $5.00 en sortie. Au-delà de 272,000 tokens d’entrée, toute la requête est facturée à 2× pour l’entrée et le cache, et 1.5× pour la sortie : respectivement $2.00 / $0.10 / $2.50 / $7.50. Le mode Fast coûte 2×. + ## Sélection des modèles à l’inscription Une nouvelle connexion sans OAuth attend une liste de modèles fiable avant de les exposer. Si l’onglet Models contient au moins 20 lignes distinctes, tous les interrupteurs de modèles sont initialement OFF ; le fournisseur reste ACTIVE. Les connexions utilisant effectivement OAuth ou la connexion ChatGPT conservent leurs valeurs par défaut. @@ -34,6 +48,7 @@ Après une inscription ou une connexion OAuth dans l’interface, une boîte de | `providers` | `Record` | — | Mappage du nom du fournisseur avec la configuration du fournisseur. | | `openaiProviderTierVersion?` | `2` | défini par la migration | Marque la projection OpenAI prenant en compte les options uniques comme terminée. | | `disabledModels?` | `string[]` | — | Modèles masqués du catalogue de Codex et de `/v1/models`, mais non bloqués des appels proxy directs. Un identifiant acheminé est supprimé des listes. Un identifiant natif qualifié de compte masque uniquement cette ligne de sélecteur ; un identifiant GPT natif nu masque la ligne nue et chaque ligne de sélecteur de compte pour ce modèle. La page Modèles du tableau de bord expose uniquement les lignes natives routées et nues ; utilisez ce champ de configuration directement pour masquer une ligne qualifiée par le sélecteur. | +| `omitDisabledNativeModels?` | `boolean` | `false` | Par défaut : `false`. Avec `"omitDisabledNativeModels": true` dans `config.json`, puis `ocx sync`, les lignes natives désactivées sont omises du catalogue, du cache et de la découverte HTTP au format Codex. Le modèle d’héritage natif validé avant omission conserve les métadonnées des lignes routées. Les requêtes directes gardent leur routage habituel. | | `providerContextCaps?` | `Record` | `{}` | Limites de contexte actives par fournisseur. Les fenêtres ordinaires sont réduites ; les modèles natifs prenant en charge une fenêtre longue peuvent être étendus uniquement jusqu’à leur propre plafond pris en charge. | | `providerContextCapValues?` | `Record` | `{}` | Dernières limites sélectionnées par fournisseur, conservées après désactivation. Ces valeurs n’activent aucun plafond. Une valeur active est prioritaire sur une valeur mémorisée. | | `contextCapValue?` | `number` | `350000` | Valeur par défaut lors de la première activation. Les activations suivantes restaurent la sélection du fournisseur. Modifier la valeur globale avec `setAll: true` ne modifie que les plafonds actifs ; `setAll: true` sans valeur active tous les fournisseurs configurés à la valeur globale actuelle. | @@ -44,9 +59,9 @@ Après une inscription ou une connexion OAuth dans l’interface, une boîte de | `activeCodexAccountId?` | `string` | — | Compte de pool sélectionné manuellement pour la prochaine demande. La sélection efface l'affinité des threads ; les demandes en cours conservent les informations d’identification capturées. | | `codexAccountPriorities?` | `Record` | — | Ordre de sélection par compte pour le pool Codex : identifiant de compte → entier de `-100` à `100`, **les valeurs élevées sont prioritaires**, une valeur absente équivaut à `0`. Cette limite porte sur le classement, et non sur l'admissibilité : la sélection retient, parmi les comptes déjà admissibles, le niveau prioritaire le plus élevé qui dispose encore d'une marge de quota, puis `accountPoolStrategy` choisit un compte dans ce niveau. Un niveau est ignoré uniquement lorsque chacun de ses membres atteint son propre seuil effectif non nul (valeur spécifique au compte ou seuil global), est en temporisation, est temporairement évité, est suspendu ou doit être réauthentifié ; un quota inconnu ne suffit jamais à considérer un niveau comme épuisé. L'ordre ne rend jamais admissible un compte qui ne l'est pas et ne réaffecte jamais une tâche déjà liée à un compte. Le compte principal `__main__` participe selon les mêmes règles ; la connexion Codex Desktop peut ainsi être configurée pour être utilisée en dernier. Sans entrée, le pool se comporte exactement comme auparavant. Un mappage mal formé est ignoré avec un avertissement dans la console : l'ordre est désactivé et la configuration n'est pas réparée. Ce champ est géré par `ocx account priority` et la page Codex Auth. | | `activeCodexAccountPinned?` | `string` | — | Identifiant du compte du dernier opérateur sélectionné manuellement. Lorsqu'il est défini, un niveau `codexAccountPriorities` supérieur ne peut pas le préempter jusqu'à ce que la broche soit libérée par drainage, exclusion, suppression ou un failover/promotion explicite. Un mouvement circulaire ordinaire à l’intérieur du niveau plafonné ne le libère pas. L'écriture d'une entrée `codexAccountPriorities` libère également le pin, donc un pin créé avant qu'un ordre n'existe ne peut pas surpasser un ensemble par la suite. `GET /api/codex-auth/active` indique à la fois si le compte effectif est épinglé (`pinned`) et le compte portant le plafond (`pinnedAccountId`). | -| `autoSwitchThreshold?` | `number` | `80` | Seuil d'utilisation pour la commutation proactive. `quota` peut réévaluer les requêtes non liées lors de leur prochaine requête. Les tâches liées conservent leur compte au-delà du seuil par défaut (`pool.cacheAffinity`) jusqu'à ce que ce compte soit épuisé ou ne puisse plus servir, et ne basculent alors que vers un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez `pool.cacheAffinity: false` pour réévaluer aussi les tâches liées à ce seuil. `fill-first` ne l'utilise que comme seuil d'évacuation pour l'affectation des requêtes non liées ; la sélection `round-robin` normale ne l'utilise pas. Le score retient la plus élevée des fenêtres de quota connues sur 5 heures, une semaine ou 30 jours. `0` désactive uniquement la commutation proactive fondée sur l'utilisation, pas l'affectation des requêtes non liées ni la récupération après incident. | +| `autoSwitchThreshold?` | `number` | `80` | Seuil d'utilisation pour la commutation proactive. `quota` peut réévaluer les requêtes non liées lors de leur prochaine requête. Les tâches liées conservent leur compte au-delà du seuil par défaut (`pool.cacheAffinity`) jusqu'à ce que ce compte soit épuisé ou ne puisse plus servir, et ne basculent alors que vers un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez `pool.cacheAffinity: false` pour réévaluer aussi les tâches liées à ce seuil. `fill-first` ne l'utilise que comme seuil d'évacuation pour l'affectation des requêtes non liées ; `round-robin` ne l'utilise que pour les nouvelles affectations non liées : tant qu'un compte admissible reste sous son seuil effectif, il ignore ceux qui l'atteignent ou le dépassent, sans jamais déplacer une tâche liée pour cette raison. Le score retient la plus élevée des fenêtres de quota connues sur 5 heures, une semaine ou 30 jours. `0` désactive uniquement la commutation proactive fondée sur l'utilisation, pas l'affectation des requêtes non liées ni la récupération après incident. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | Seuils par compte remplaçant `autoSwitchThreshold` : identifiant → entier de `0` à `100`. Une entrée absente hérite du seuil global ; `0` désactive uniquement les déplacements fondés sur l’utilisation depuis ce compte. Le compte principal `__main__` est pris en charge. La carte du compte dans Codex Auth gère cette valeur. Activer la valeur spécifique au compte copie le seuil global actuel dans une valeur fixe. Cette valeur, y compris `0`, reste prioritaire après toute modification du seuil global. La désactiver envoie `threshold: null`, supprime l'entrée et rétablit l'héritage du seuil global actuel et de ses modifications futures. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Stratégie d'affectation des requêtes Codex nouvelles ou non liées. Une requête est non liée lorsqu'elle ne possède aucune affinité active, définie par l'identifiant de la tâche parente et la portée du quota ; une tâche existante visible peut perdre son lien après le redémarrage du proxy ou la réinitialisation de l'affinité. `quota` sélectionne le compte admissible le moins utilisé lorsqu'aucun compte actif n'existe, conserve un compte actif admissible sous `autoSwitchThreshold` et, une fois le seuil franchi, peut déplacer une requête non liée. Les tâches liées suivent `pool.cacheAffinity` (activé par défaut) : elles restent jusqu'à ce que le compte soit épuisé (utilisation connue à 100 %) ou ne puisse plus servir, et ne se relient alors qu'à un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez le drapeau à `false` pour relier de manière proactive une tâche liée à un compte admissible moins utilisé au seuil, toujours sous la même contrainte de destination. `round-robin` répartit équitablement les requêtes non liées ; `fill-first` continue de les attribuer au compte actif jusqu'à sa temporisation, son indisponibilité ou le seuil d'évacuation configuré. `reset-first`: Parmi les comptes sous le seuil, privilégier le prochain reset de 5 heures ou hebdomadaire. Les tâches liées suivent la politique d’affinité configurée. Les quotas de modèles indépendants suivent l’ordre de consommation. Les resets mensuels ne déterminent pas cet ordre. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Stratégie d'affectation des requêtes Codex nouvelles ou non liées. Une requête est non liée lorsqu'elle ne possède aucune affinité active, définie par l'identifiant de la tâche parente et la portée du quota . Les liaisons des requêtes avec un identifiant de session (y compris les tours habituels de Codex CLI et App et les sous-agents), ou des requêtes sans session ancrées sur leur parent immédiat, peuvent survivre à un redémarrage normal du proxy jusqu’à 24 heures d’inactivité, si l’enregistrement final de l’affinité à l’arrêt réussit. Les chaînes sans session plus profondes et les liaisons à la connexion principale de Codex App restent en mémoire uniquement et sont réattribuées après le redémarrage ; une expulsion, la suppression du compte, une reconnexion, un plantage ou une réinitialisation de l’affinité peuvent laisser une tâche non liée. `quota` sélectionne le compte admissible le moins utilisé lorsqu'aucun compte actif n'existe, conserve un compte actif admissible sous `autoSwitchThreshold` et, une fois le seuil franchi, peut déplacer une requête non liée. Les tâches liées suivent `pool.cacheAffinity` (activé par défaut) : elles restent jusqu'à ce que le compte soit épuisé (utilisation connue à 100 %) ou ne puisse plus servir, et ne se relient alors qu'à un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez le drapeau à `false` pour relier de manière proactive une tâche liée à un compte admissible moins utilisé au seuil, toujours sous la même contrainte de destination. `round-robin` répartit équitablement les requêtes non liées entre les comptes admissibles sous leur `autoSwitchThreshold` effectif, ou entre tous les comptes admissibles s'ils ont tous atteint ou dépassé leur seuil ; `fill-first` continue de les attribuer au compte actif jusqu'à sa temporisation, son indisponibilité ou le seuil d'évacuation configuré. `reset-first`: Parmi les comptes sous le seuil, privilégier le prochain reset de 5 heures ou hebdomadaire. Les tâches liées suivent la politique d’affinité configurée. Les quotas de modèles indépendants suivent l’ordre de consommation. Les resets mensuels ne déterminent pas cet ordre. | | `pool.cacheAffinity?` | `boolean` | `true` | Ordre d'affinité de cache pour les threads Codex liés, indépendant de `pool.kernel`. Activé par défaut ; omettre la clé ou la définir à `true` conserve la liaison, et une valeur autre que `false` est lue comme activée. Une liaison active prime sur la marge de quota : `quota` ne déplace pas le thread simplement parce que l'utilisation a franchi `autoSwitchThreshold`, car déplacer une conversation liée jette le cache d'invites isolé par compte. Le thread quitte encore le compte s'il ne peut plus servir — suspendu, inutilisable, exclu du plan, identifiants invalides, génération remplacée, TTL expiré, refus de quota 429/402, ou réellement épuisé (utilisation connue à 100 %) — et seulement vers un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Un compte dont l'utilisation est inconnue n'est jamais choisi comme destination d'une tâche liée. Si tous les comptes dépassent le seuil, la tâche liée reste, car aucune destination n'est meilleure. Définissez `false` pour rétablir la réaffectation au seuil, toujours sous la même contrainte de destination. L'affinité est un réordonnancement, pas un verrouillage. | | `accountPoolStickyLimit?` | `number` | `1` | Nombre d'affectations de tâches nouvelles ou non liées conservées sur une même sélection tournante avant de passer à la suivante ; le compteur avance lorsqu'une tâche est liée, et non après une réponse réussie en amont. Plage : 1–100. | | `upstreamFailoverThreshold?` | `number` | `3` | Nombre d'échecs transitoires consécutifs avant le basculement des futures nouvelles sessions. Réglez `0` pour désactiver ce mécanisme. Pour les requêtes Responses ordinaires et les envois compacts natifs, les échecs avérés d'accessibilité DNS/TCP avant connexion sont suivis au niveau du couple fournisseur-hôte : ils n'affectent jamais l'état ni la temporisation du compte, l'affinité de tâche ou de session, la sélection du compte actif ou le routage du pool, et ne sont jamais comptabilisés dans ce seuil. | @@ -54,6 +69,8 @@ Après une inscription ou une connexion OAuth dans l’interface, une boîte de | `codexPinnedTransientPolicy?` | `"hold" \| "detour-new-threads"` | `"hold"` | Quand un compte épinglé est dégradé, `hold` continue de l'utiliser et journalise un avertissement ; `detour-new-threads` ne déplace que les nouveaux fils. Un tour déjà envoyé n'est jamais renvoyé. | | `codexWsReuseAcrossTurns?` | `boolean` | `false` | Réutilisation optionnelle du WebSocket Codex entre les tours d'un même compte et fil. Désactivé par défaut. Activé, un socket occupé est attendu au plus 750 ms et jusqu'à deux sockets restent lors d'un changement de modèle ou de palier. | | `upstreamHostCircuitThreshold?` | `number` | `0` | Seuil facultatif du coupe-circuit pour les échecs DNS/TCP avérés avant connexion sur les requêtes Responses OpenAI natives en mode transfert et les envois compacts. `0` le désactive ; `1`–`20` ouvre, après ce nombre de requêtes logiques arrivées à leur terme, une temporisation de 30 secondes propre à l'origine du fournisseur. Tant que le circuit est ouvert, les requêtes reçoivent `503` avec `Retry-After` avant la sélection du compte ou l'envoi en amont ; après la temporisation, une requête est admise en état semi-ouvert. Les délais d'attente et les réponses HTTP ne sont jamais comptabilisés, et toute réponse HTTP ferme le circuit. Ce mécanisme s'applique uniquement au routage du pool Codex sans compte épinglé ; il reste inactif pour `codexAccountMode: "direct"` et les sélecteurs qualifiés par compte. | +| `maxInboundBodyBytes?` | `number` | `0` | Limite en octets de la taille décodée d'un corps JSON entrant par requête. Une valeur absente ou `0` conserve les 256 MiB par défaut ; la valeur configurée est bornée à 1–512 MiB. Redémarrage requis. Un dépassement produit un HTTP 413 local avec le code `inbound_body_too_large`. Une limite effective supérieure à 256 MiB active aussi le contrôle partagé `maxConcurrentInboundBodyBytes` ; relever la limite par requête ne relève pas à lui seul le budget partagé. Routes concernées et détails : [admission des corps entrants](/fr/reference/inbound-body-admission/). | +| `maxConcurrentInboundBodyBytes?` | `number` | `536870912` (512 MiB) | Budget partagé d'admission facultatif de premier niveau, en octets, actif uniquement si la valeur effective de `maxInboundBodyBytes` dépasse 256 MiB. Une valeur absente, `0` ou invalide utilise les 512 MiB par défaut, inchangés. Les entiers positifs valides sont bornés à 512 MiB–2 GiB (`536870912`–`2147483648`) lors de leur utilisation. Redémarrage requis ; tous les écouteurs d'un processus partagent un seul budget. Il s'agit d'un décompte d'admission, pas d'une préallocation mémoire, d'une limite RSS ou d'un dimensionnement automatique selon la RAM. Choisir 2 GiB exige une décision explicite de l'opérateur. Voir [l'admission des corps entrants](/fr/reference/inbound-body-admission/) pour l'exemple, les compromis de file et de cycle de vie des réponses, et la raison pour laquelle le budget par défaut ne permet qu'un seul envoi complet de 512 MiB avant l'analyse. | | `modelCacheTtlMs?` | `number` | `300000` | Fenêtre de fraîcheur pour le cache `/models` par fournisseur. | | `cacheRetention?` | `"none" \| "short" \| "long"` | Anthropic direct : `"long"` ; autres points de terminaison compatibles Anthropic : `"short"` | Politique Anthropic de mise en cache des invites : désactivée, éphémère pendant 5 minutes ou étendue à 1 heure. Sans valeur, les requêtes vers `api.anthropic.com` (clé API ou pools de comptes OAuth) utilisent un TTL d’une heure ; les passerelles et points de terminaison compatibles gardent 5 minutes. Une valeur explicite l’emporte toujours. | | `tokenGuardian?` | `OcxTokenGuardianConfig` | désactivé | Politique facultative d'actualisation proactive OAuth et de préchauffage des comptes Codex. | @@ -112,7 +129,8 @@ sauvegarde dont le contenu diffère, puis réécrit en identifiants sans préfix | `defaultModel?` | `string` | Modèle utilisé lorsque ce fournisseur est sélectionné sans modèle explicite. | | `models?` | `string[]` | Liste initiale ou de repli. Avec `liveModels: false`, une liste `models` non vide est suivie de `retainModels` ; si `models` est vide ou absent, la liste commence par `defaultModel` (si configuré), puis `retainModels`, en conservant la première occurrence de chaque identifiant. | | `liveModels?` | `boolean` | Récupère le catalogue actif au démarrage et lors de la synchronisation (true par défaut). Les fournisseurs personnalisés utilisent `${baseUrl}/models` ; les fournisseurs intégrés peuvent employer une URL de registre et un filtre. | -| `selectedModels?` | `string[]` | Liste autorisée après découverte. Non vide : seuls ces identifiants sont admis. Vide ou absent : aucune liste supplémentaire. La politique de découverte et `disabledModels` restent applicables. | +| `modelDiscovery?` | `{ skipInvalidRows?: boolean }` | Compatibilité de la découverte en direct pour une passerelle dont la liste `/models` contient des lignes mal formées. Par défaut, une seule ligne invalide fait rejeter toute la liste, et l'avertissement indique la première ligne invalide et le nombre de lignes invalides. Avec `skipInvalidRows: true`, les lignes qui ne sont pas des objets ou dont l'id est absent, non textuel, vide ou invalide sont ignorées, et un avertissement unique indique combien l'ont été, jamais leur contenu. Les limites de taille et de nombre de lignes comptent toutes les lignes reçues ; la déduplication, les filtres du fournisseur et le retrait du préfixe d'id s'appliquent aux lignes restantes. Si des lignes ont été ignorées et qu'il n'en reste aucune, la liste est toujours rejetée au lieu d'être traitée comme un catalogue vide. Une sauvegarde vers la même destination qui l'omet le conserve ; un changement de destination le supprime. Sans rapport avec le bloc `modelDiscovery` de premier niveau, qui stocke l'état de la politique des nouveaux modèles. | +| `selectedModels?` | `string[]` | Liste autorisée du catalogue après la découverte. Non vide expose uniquement ces identifiants ; vide ou omis expose tous les modèles découverts. | | `contextWindow?` | `number` | Repli contextuel à l’échelle du fournisseur lorsque les métadonnées en amont sont absentes ; sinon, un plafond qui conserve des métadonnées en direct plus petites. Le tableau de bord Modèles expose cela séparément de `providerContextCaps`. | | `modelContextWindows?` | `Record` | Valeurs de repli ou plafonds de contexte par modèle. Ils remplacent `contextWindow` : une fenêtre inconnue utilise la valeur configurée, tandis que des métadonnées actives plus faibles restent déterminantes. | | `inferContextWindow?` | `boolean` | Fournisseurs personnalisés uniquement, désactivé par défaut. `true` complète une fenêtre absente à partir des métadonnées embarquées du modèle ; c’est une estimation, pas la capacité vérifiée du relais. | @@ -133,7 +151,7 @@ sauvegarde dont le contenu diffère, puis réécrit en identifiants sans préfix | `modelReasoningEfforts?` | `Record` | Libellés propres à chaque modèle. Une liste vide masque le contrôle de l'effort. Comme pour `reasoningEfforts`, chaque échelle configurée avec l'adaptateur `google` déclare la capacité `thinkingLevel` ; les requêtes directes et Vertex sans image utilisent le chemin Gemini à plat, tandis que Cloud Code Assist l'envoie dans son enveloppe de requête. | | `modelSupportsReasoningSummaries?` | `Record` | Définissez un modèle sur `false` pour arrêter la publicité des résumés et supprimer les champs de livraison du résumé. | | `modelReasoningSummaryDelivery?` | `Record` | Énumération de livraison des réponses par modèle ; réécrit un champ de livraison existant. | -| `modelAdapters?` | `Record` | Remplacement du protocole `openai-chat` ou `openai-responses` par modèle pour les passerelles multiprotocoles. Les entrées explicites priment sur les valeurs par défaut du registre. Le préréglage OpenCode Go sélectionne Responses pour `gpt-5.6-luna` tout en laissant les modèles apparentés sur leurs protocoles documentés ; DeepSeek peut sélectionner Responses natif pour `deepseek-v4-flash` ; GitHub Copilot déclare des valeurs par défaut limitées à Responses pour ces modèles (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`), car ces modèles rejettent `/chat/completions` pour le trafic des agents. Les modèles sans valeur intégrée par défaut, comme `gpt-5.4-nano`, peuvent être activés ici. Les services en amont à protocole unique et le transfert canonique ChatGPT rejettent ces remplacements. | +| `modelAdapters?` | `Record` | Remplacement du protocole `openai-chat` ou `openai-responses` par modèle pour les passerelles multiprotocoles. Les entrées explicites priment sur les valeurs par défaut du registre. Le préréglage OpenCode Go sélectionne Responses pour `gpt-5.6-luna` tout en laissant les modèles apparentés sur leurs protocoles documentés ; DeepSeek peut sélectionner Responses natif pour `deepseek-v4-flash` ; GitHub Copilot déclare des valeurs par défaut limitées à Responses pour ces modèles (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`), car ces modèles rejettent `/chat/completions` pour le trafic des agents. Les modèles sans valeur intégrée par défaut, comme `gpt-5.4-nano`, peuvent être activés ici. Les services en amont à protocole unique et le transfert canonique ChatGPT rejettent ces remplacements. | | Activation Responses xAI (tableau de bord) | interrupteur | Pour `xai` uniquement, définit ou efface atomiquement les entrées `modelAdapters` de `grok-4.5` et `grok-4.6`. Une seule entrée apparaît comme un état mixte jusqu’à la prochaine écriture. Les autres remplacements et le comportement des tiers restent inchangés. Grok 4.7 utilise Responses par défaut sur OAuth via le registre et peut passer à Chat avec une entrée explicite `modelAdapters["grok-4.7"] = "openai-chat"`. | | `xaiResponsesXSearch?` | `boolean` | Désactivé par défaut. Sur une destination xAI Responses, ajoute la déclaration `x_search` hébergée par le fournisseur uniquement lorsqu’un outil `web_search` actif subsiste après la normalisation finale de la requête. Les déclarations existantes ne sont pas dupliquées, les sélecteurs `tool_choice`/`allowed_tools` de l’appelant ne sont jamais élargis, et cette option est distincte des options `search.xSearch` du service auxiliaire de recherche web. | | `modelPreferHostedTools?` | `Record` | Activation explicite par modèle exact pour les passerelles Responses hors transfert qui réservent un espace de noms aux outils hébergés. Seul `["image_generation"]` est actuellement accepté ; le modèle correspondant doit utiliser le protocole `openai-responses` et prendre en charge cet outil hébergé. Le proxy supprime les déclarations clientes `image_gen` en conflit et réécrit leurs sélecteurs afin de préserver le choix d'outil de l'appelant. Pour les modèles virtuels `-pro` de l'API OpenAI, l'identifiant public sélectionné est comparé en premier et l'identifiant résolu du modèle de base sur le protocole sert de repli. `modelAdapters` résout d'abord l'identifiant public, puis celui de base ; la seconde résolution détermine le protocole final. Les autres modèles conservent le comportement normal des alias. | @@ -148,14 +166,15 @@ sauvegarde dont le contenu diffère, puis réécrit en identifiants sans préfix | `noPenaltyModels?` | `string[]` | Modèles qui rejettent les pénalités presence/frequency. Le préréglage `xai` intégré y liste ses modèles de raisonnement (`grok-4.7`, `grok-4.6`, `grok-4.5`, `grok-4.3`, `grok-4.20-multi-agent-0309`, `grok-4.20-0309-reasoning`, `grok-build-0.1`), que xAI documente comme les refusant ; les identifiants sans raisonnement conservent les pénalités de l’appelant. | | `noStructuredOutputModels?` | `string[]` | ID de modèle exact dont le point final `openai-chat` rejette `response_format`. Seule une correspondance exacte du modèle demandé omet le champ ; la traduction à sortie structurée reste activée pour tous les autres modèles `openai-chat`. | | `noJsonSchemaModels?` | `string[]` | ID de modèle exact dont le point final `openai-chat` rejette un `response_format` `json_schema` mais accepte encore `json_object`. Une telle requête est rétrogradée vers `json_object` au lieu d’être supprimée, donc un appelant qui demande du JSON en reçoit toujours. `noStructuredOutputModels` l’emporte quand un modèle figure dans les deux listes. Les préréglages `opencode go` et `opencode zen` l’embarquent pour leurs routes DeepSeek. | -| `foldDeveloperRoleToSystem?` | `boolean` | Indique si une destination `openai-chat` accepte le rôle `developer`. `foldDeveloperRoleToSystem` non défini envoie `system`, `true` envoie `system` et `false` envoie `developer`. Non défini signifie que rien n'a été enregistré pour cette destination ; `true` enregistre un service en amont qui refuse le rôle ; `false` en enregistre un qui l'accepte. Dans tous les cas le message conserve sa position dans la conversation ; seul le rôle change. Une destination qui refuse le rôle répond `400 role 'developer' is not allowed` et le tour ne démarre pas, d'où l'état non enregistré replié par défaut. | +| `foldDeveloperRoleToSystem?` | `boolean` | Indique si une destination `openai-chat` accepte le rôle `developer`. `foldDeveloperRoleToSystem` non défini envoie `system`, `true` envoie `system` et `false` envoie `developer`. Non défini signifie que rien n'a été enregistré pour cette destination ; `true` enregistre un service en amont qui refuse le rôle ; `false` en enregistre un qui l'accepte. Si `singleLeadingSystemMessage` n'est pas activé, le message conserve sa position dans la conversation ; seul le rôle change. Une destination qui refuse le rôle répond `400 role 'developer' is not allowed` et le tour ne démarre pas, d'où l'état non enregistré replié par défaut. | | `parallelToolCalls?` | `boolean` | Contrôler les appels d’outils parallèles. Pour `openai-chat`, ils sont activés par défaut ; `false` envoie explicitement `parallel_tool_calls: false`. Les autres adaptateurs ne les annoncent que lorsque la valeur vaut explicitement `true`. | | `terminalContinuationGuard?` | `boolean` | Active, pour un fournisseur `openai-chat`, une relance interne bornée lorsqu’un tour exploitable annonce une action puis s’arrête proprement sans appel d’outil. La valeur par défaut est `false`, et une valeur explicite `false` équivaut à l’absence du champ. Les tentatives de combinaison et les tours de compactage routés sont exclus ; les autres adaptateurs ignorent cette option. | | `responsesItemIdRepair?` | `{ message?: string[]; reasoning?: string[]; repairMissingTerminalIds?: boolean; repairInvalidIds?: boolean }` | Réparation SSE en aval désactivée par défaut pour les identifiants d'espace réservé exacts, les identifiants de terminal manquants et (avec `repairInvalidIds`) les identifiants message/reasoning manquant du préfixe canonique `msg_`/`rs_`. Les identifiants d’appel de fonction ne sont jamais réécrits. Le DeepSeek intégré active les deux derniers par défaut. | | `responsesSnapshotRepair?` | `boolean` | Réparation côté client désactivée par défaut pour les instantanés du cycle de vie des réponses clairsemés dans SSE et JSON. Remplit les métadonnées d'état canonique, de sortie et d'outil manquantes tandis que l'inspection brute et la persistance restent inchangées. | -| `retryOn429?` | `{ enabled?: boolean; attempts?: number; intervalMs?: number; maxIntervalMs?: number; respectRetryAfter?: boolean }` | Fournisseurs à clé API uniquement (`authMode: "key"`). Nouvelle tentative facultative sur la même cible après un 429 : lorsque `retryOn429` est absent, la fonctionnalité est désactivée ; la présence d'un objet l'active, sauf avec `enabled: false`. Après un 429, le proxy attend selon `Retry-After` reçu en amont ou selon l'intervalle fixe, puis relit la requête à l'identique avec la même clé avant tout basculement de clé. Ce comportement couvre la boucle principale de récupération d'un tour textuel, le protocole de transfert Responses, le pont d'images et de vidéos, le service auxiliaire de recherche Web et les continuations du terminal. Seules les réponses HTTP 429 reçues avant le début de la diffusion peuvent être relues ; les transports `runTurn` personnalisés ne font pas partie de la boucle de nouvelle tentative HTTP. `attempts` compte les relectures avec la même clé après le premier 429, soit `attempts` + 1 envois au total, et constitue un budget commun à toute la requête, partagé entre la boucle principale de récupération, la continuation de la garde du terminal et les nouvelles tentatives du pont. L'épuisement de `attempts` arrête uniquement les relectures supplémentaires avec la même clé : le basculement normal de clé ou la gestion de l'erreur finale s'applique ensuite selon les cibles disponibles. Sur le protocole de transfert authentifié par clé, aucun basculement n'est possible ; le 429 final est donc renvoyé sans modification. Codex ne retente jamais lui-même une requête après un 429 : cette option constitue ainsi la seule protection pour les fournisseurs à clé unique. Valeurs par défaut : `enabled: true`, `attempts: 3`, `intervalMs: 5000`, `maxIntervalMs: 60000` (chaque attente est plafonnée à `maxIntervalMs`, lui-même plafonné à 600000), `respectRetryAfter: true`. | +| `promptCacheKey?` | `boolean` | Active pour tout le fournisseur `openai-chat` la transmission de `prompt_cache_key`. L’adaptateur transmet la clé reçue sans en inventer ; la traduction Claude Messages peut toutefois la dériver de `metadata.user_id`, ou d’un groupe modèle/système/outils sans métadonnées. Désactivé par défaut sauf dans un préréglage ; Mistral l’active selon son [contrat de cache](https://docs.mistral.ai/studio/conversations/advanced/prompt-caching). `false` explicite le désactive. N’activer que si l’amont documente ce champ, car une passerelle stricte peut répondre HTTP 400. | +| `retryOn429?` | `{ enabled?: boolean; attempts?: number; intervalMs?: number; maxIntervalMs?: number; respectRetryAfter?: boolean }` | Réservé aux fournisseurs à clé API (`authMode: "key"`). Facultatif : absent, désactivé, sauf pour OpenCode Go et Command Code sur leurs destinations canoniques et Mistral canonique avec `openai-chat` : 6 relances, intervalle de 10 s, plafond de 60 s. Un objet active la fonction ; `enabled: false` désactive aussi ces valeurs de repli. Après un HTTP 429 avant le flux, attend `Retry-After` ou l’intervalle fixe, puis renvoie la même requête avec la même clé avant le basculement. Couvre la récupération du tour texte, Responses passthrough, les ponts image/vidéo, le service web-search et les continuations terminales ; les transports `runTurn` personnalisés sont exclus. `attempts` compte les relances après le premier 429 (envois totaux = `attempts` + 1), dans un budget partagé à l’échelle de la requête. Son épuisement arrête les relances avec la même clé, puis laisse agir le basculement ou l’erreur finale ; le passthrough à clé n’a pas de basculement. Pour Mistral Chat canonique, un délai explicite supérieur à l’attente autorisée arrête la relance avec la même clé et conserve le `Retry-After` original ; une autre clé du pool peut encore servir. Les autres fournisseurs conservent le délai plafonné. Mistral partage les échéances par identifiant/modèle, sauf avec `requestPacing.enabled: false` ou `retryOn429.respectRetryAfter: false`. Un 429 sans échéance avec une pression validée sur le budget par minute déclenche une attente prudente de 60 s, puis une seule sonde ; son succès rétablit le trafic ordinaire. Le trafic sain ne prédit pas le coût suivant. La politique utilise les allocations annoncées, exclut les allocations mensuelles connues comme épuisées, ne prédit pas une réinitialisation exacte et ne déclenche pas de compactage. Codex ne relance pas lui-même les 429. Valeurs par défaut de l’objet : `enabled: true`, `attempts: 3`, `intervalMs: 5000`, `maxIntervalMs: 60000` (attente plafonnée ; valeur maximale 600000), `respectRetryAfter: true`. | | `transientRetryOn5xx?` | `{ enabled?: boolean; attempts?: number }` | Fournisseurs `openai-chat` et `openai-responses` authentifiés par clé uniquement. Les fournisseurs `authMode: "forward"` (le pool de comptes ChatGPT) ne lisent jamais cette option et conservent l'échelle par défaut. Nouvelle tentative facultative pour les états transitoires reçus en amont avant le début de la diffusion (500, 502, 503, 504, 520, 521, 522) : l'absence de l'option la désactive ; la présence d'un objet l'active, sauf avec `enabled: false`. Ce comportement couvre la requête Responses initiale, la continuation de la garde du terminal, le point de terminaison natif `/v1/chat/completions` et les réémissions liées à la récupération après un 429 ou à la récupération de compte. `attempts` représente le nombre TOTAL d'envois en amont autorisés pour une requête, premier envoi compris (de 1 à 10, valeur par défaut : 3). Il constitue un budget commun à la requête, partagé avec la récupération après une réinitialisation de connexion ; ainsi, `3` signifie qu'au plus trois requêtes réelles atteignent le fournisseur. Les attentes utilisent une temporisation exponentielle à base fixe de 400 ms, plafonnée à 5 s, et respectent `Retry-After`. Cette option est distincte de `retryOn429`, qui traite la limitation de débit ; les échecs en cours de diffusion ne sont jamais relus. Chaque cible Combo compte son premier envoi prépayé dans son propre total configuré : `attempts: 1` autorise un envoi, sans rembourser la réservation ni élargir le plafond partagé. Un refus local ou une annulation avant l'envoi libère la réservation inutilisée. | -| `retryOnReset?` | `{ enabled?: boolean; replacements?: number }` | Fournisseurs `openai-responses` natifs, `authMode: "forward"` compris, ainsi que les requêtes Responses traduites envoyées par la voie générique avant les en-têtes reçus en amont. Remplacement facultatif d'un envoi qui a échoué alors que l'appelant n'avait rien observé : l'absence de l'option la désactive ; la présence d'un objet l'active, sauf avec `enabled: false`. Couvre les deux étapes ambiguës — une connexion rompue avant tout en-tête de réponse, et un corps SSE rompu après l'en-tête alors qu'il ne portait que des événements de contrôle. Une WebSocket canonique ChatGPT en amont qui s'est fermée ou a échoué après l'envoi de sa trame de création, avant tout événement Responses, est couverte de la même façon ; son remplacement est envoyé en HTTP. Seule une requête autonome est remplacée : `store: false`, `input` complet, ni `previous_response_id`, ni `conversation`, ni `stream_id`, et uniquement des outils exécutés par le client. `replacements` est le nombre d'envois de remplacement qu'UNE requête logique peut effectuer, toutes étapes et tous enfants de combo confondus (de 1 à 2, valeur par défaut : 1). Ce n'est ni un nombre de tentatives par étape ni un budget d'envoi : un remplacement doit toujours tenir dans l'allocation d'envois dont l'étape disposait déjà. Une requête qui a déjà émis une sortie ou un appel d'outil n'est jamais remplacée, quelle que soit cette valeur. L'inférence de remplacement peut tout de même être facturée si l'origine avait déjà démarré la première, d'où la désactivation par défaut. La voie générique de traduction prend en charge le remplacement après une rupture avant les en-têtes pour les envois initiaux et reconstruits, avec la même autorisation et le même budget d’envois. Les transports gérés par les adaptateurs et les erreurs des flux traduits après les en-têtes reçus en amont sont exclus. | +| `retryOnReset?` | `{ enabled?: boolean; replacements?: number }` | Fournisseurs `openai-responses` natifs, `authMode: "forward"` compris, ainsi que les requêtes Responses traduites envoyées par la voie générique avant les en-têtes reçus en amont. Remplacement facultatif d'un envoi qui a échoué alors que l'appelant n'avait rien observé : l'absence de l'option la désactive ; la présence d'un objet l'active, sauf avec `enabled: false`. Couvre les deux étapes ambiguës — une connexion rompue avant tout en-tête de réponse, et un corps SSE rompu après l'en-tête alors qu'il ne portait que des événements de contrôle. Une WebSocket canonique ChatGPT en amont qui s'est fermée ou a échoué après l'envoi de sa trame de création, avant tout événement Responses, est couverte de la même façon ; son remplacement est envoyé en HTTP. Seule une requête autonome est remplacée : `store: false`, `input` complet, ni `previous_response_id`, ni `conversation`, ni `stream_id`, et uniquement des outils exécutés par le client. Un tour chaîné dont ce proxy a déjà développé le `previous_response_id` à partir de son propre état de rejeu est admissible, car cet identifiant est retiré avant l'envoi. Quand une réinitialisation n'est pas remplacée, le journal du service en indique la raison : `ambiguous-no-policy`, `ambiguous-request-not-replayable` ou `ambiguous-allowance-spent`. `replacements` est le nombre d'envois de remplacement qu'UNE requête logique peut effectuer, toutes étapes et tous enfants de combo confondus (de 1 à 2, valeur par défaut : 1). Ce n'est ni un nombre de tentatives par étape ni un budget d'envoi : un remplacement doit toujours tenir dans l'allocation d'envois dont l'étape disposait déjà. Une requête qui a déjà émis une sortie ou un appel d'outil n'est jamais remplacée, quelle que soit cette valeur. L'inférence de remplacement peut tout de même être facturée si l'origine avait déjà démarré la première, d'où la désactivation par défaut. La voie générique de traduction prend en charge le remplacement après une rupture avant les en-têtes pour les envois initiaux et reconstruits, avec la même autorisation et le même budget d’envois. Les transports gérés par les adaptateurs et les erreurs des flux traduits après les en-têtes reçus en amont sont exclus. | | `autoToolChoiceOnlyModels?` | `string[]` | Modèles dont `tool_choice` accepte uniquement `auto` ou `none` ; les choix forcés sont dévalorisés. | | `preserveReasoningContentModels?` | `string[]` | Modèles nécessitant un assistant préalable `reasoning_content` dans l'historique des discussions. Les enregistrements depuis le tableau de bord conservent la liste enregistrée, y compris `[]`. `PATCH /api/providers?name=` accepte un tableau ou `null` pour l'effacer. Une sauvegarde qui déplace le fournisseur vers un autre adaptateur, une autre URL de base ou un autre mode d'authentification ne la conserve pas (voir la section ci-dessous). | | `reasoningDetailsModels?` | `string[]` | Modèles dont le point de terminaison renvoie la réflexion sous forme de tableau structuré `reasoning_details` (MiniMax série M avec `reasoning_split`) ; les deltas de flux sont des instantanés cumulatifs comparés par préfixe, et la réflexion conservée est rejouée sous forme de tableau `reasoning_details` plutôt que de chaîne `reasoning_content`. | @@ -167,13 +186,16 @@ sauvegarde dont le contenu diffère, puis réécrit en identifiants sans préfix | `anthropicEofTolerance?` | `boolean` | Laissez une passerelle compatible Anthropic compléter un flux qui se termine avant `message_stop`, uniquement lorsque du texte visible ou une entrée complète d'outil d'objet JSON a été reçue. Désactivé par défaut. | | `googleMode?` | `"ai-studio" \| "vertex" \| "cloud-code-assist"` | Mode Google transport/auth. Par défaut `ai-studio`. | | `googleToolSchemaPolicy?` | `"compatible" \| "reject-lossy"` | Google uniquement. Une valeur absente ou `compatible` conserve le schéma compatible et la réparation 400 existante hors mode direct. `reject-lossy` refuse une perte initiale ou une comparaison bornée indéterminée avant l’envoi et bloque une réparation Vertex ou Cloud Code Assist qui ouvrirait des contraintes. AI Studio direct n’effectue jamais cette réparation. | -| `project?` | `string` | ID du projet Vertex ou Antigravity Cloud Code Assist. Lorsqu'il est défini, les clés API Vertex utilisent le point de terminaison du projet ; sinon elles utilisent le mode express, même si `GOOGLE_CLOUD_PROJECT` est défini. ADC se replie sur `GOOGLE_CLOUD_PROJECT` / `GCLOUD_PROJECT`. | +| `project?` | `string` | ID du projet Vertex ou Antigravity Cloud Code Assist. Lorsqu'il est défini, les clés API Vertex utilisent le point de terminaison du projet ; sinon elles utilisent le mode express, même si `GOOGLE_CLOUD_PROJECT` est défini. ADC se replie sur `GOOGLE_CLOUD_PROJECT` / `GCLOUD_PROJECT`. Avec `"auto"`, chaque clé API Vertex résout son propre projet (une résolution réussie est mise en cache par clé ; une clé dont la résolution échoue est de nouveau sondée lors d'une requête ultérieure), de sorte qu'un pool de clés peut couvrir plusieurs projets ; ADC refuse `"auto"`. | | `location?` | `string` | Région Vertex. Les points de terminaison de projet avec clé API utilisent `global` par défaut et ignorent `GOOGLE_CLOUD_LOCATION` ; ADC exige ce champ ou le repli `GOOGLE_CLOUD_LOCATION`. | | `mcpServers?` | `Record` | Cursor uniquement : serveurs MCP sur entrée-sortie standard ou HTTP diffusé en continu. | | `desktopExecutor?` | `DesktopExecutorConfig` | Cursor uniquement : commandes externes d'utilisation d'un ordinateur et d'enregistrement de l'écran. | | `unsafeAllowNativeLocalExec?` | `boolean` | Ancien booléen de Cursor, équivalent à `nativeLocalExec: "on"` uniquement lorsque le champ plus récent n'est pas défini. | | `nativeLocalExec?` | `"off" \| "codex-sandbox" \| "on"` | Politique d'exécution locale de Cursor. `off` est la valeur par défaut ; actuellement, `codex-sandbox` échoue de manière sûre comme `off`. | +LM Studio instruction compatibility: `singleLeadingSystemMessage: true` overrides chronological Chat instruction placement by merging text-only system/developer messages into one leading system message. The LM Studio preset enables it by default; set it to `false` to disable merging. + + La création et le remplacement d’un fournisseur (`POST /api/providers`) valident `responsesPath` et `chatCompletionsPath` avant de modifier la configuration en mémoire ou sur disque. `PATCH /api/providers?name=` fusionne le corps de la requête avec le fournisseur enregistré ; les mises à jour qui touchent des champs autres que `disabled` — à l’exception des mises à jour portant uniquement sur `requestPacing` — valident de la même manière les chemins du fournisseur fusionné avant l’enregistrement, et un chemin conservé invalide renvoie `400` sans modifier la configuration. Les mêmes règles de chemin s’appliquent au chargement d’un fichier de configuration. Les fournisseurs à clé API peuvent détenir une clé littérale ou une référence à une variable d'environnement. Les fournisseurs OAuth utilisent le @@ -182,17 +204,17 @@ configuré sous [`claudeCode.authMode`](/fr/reference/configuration/server/#clau ### Ce qu'une sauvegarde de fournisseur conserve -`POST /api/providers` avec le nom d'un fournisseur existant remplace la ligne enregistrée par une ligne construite à partir de la requête. Le formulaire d'ajout/modification du tableau de bord ne peut pas envoyer tous les champs ; la sauvegarde conserve donc certains champs enregistrés que la requête omet. Huit d'entre eux décrivent le comportement d'un amont précis : `preserveReasoningContentModels`, `requiresReasoningPlaceholderModels`, `foldDeveloperRoleToSystem`, `reasoningWireFormat`, `omitReasoningEffortWithToolsModels`, `retryOn429`, `transientRetryOn5xx`, `retryOnReset`. +`POST /api/providers` avec le nom d'un fournisseur existant remplace la ligne enregistrée par une ligne construite à partir de la requête. Le formulaire d'ajout/modification du tableau de bord ne peut pas envoyer tous les champs ; la sauvegarde conserve donc certains champs enregistrés que la requête omet. Treize d'entre eux décrivent le comportement d'un amont précis : `preserveReasoningContentModels`, `preserveResponsesReasoningContent`, `requiresReasoningPlaceholderModels`, `foldDeveloperRoleToSystem`, `singleLeadingSystemMessage`, `reasoningWireFormat`, `omitReasoningEffortWithToolsModels`, `promoteAdditionalTools`, `retryOn429`, `transientRetryOn5xx`, `retryOnReset`, `unsupportedHostedTools`, `unsupportedHostedToolsWithClientTools`. -| Sauvegarde | Les huit réglages | `apiKeyPool` enregistré | +| Sauvegarde | Les treize réglages | `apiKeyPool` enregistré | | --- | --- | --- | | Même destination, champ omis | Valeur enregistrée conservée, y compris un `[]` ou un `false` explicite | Conservé | | Nouvelle destination, champ omis | Non conservée ; les valeurs par défaut du registre pour la nouvelle destination peuvent s'appliquer | Non conservé | | Champ envoyé dans la requête | La valeur de la requête | La valeur de la requête | -La destination est l'adaptateur, l'URL de base (schéma et hôte comparés sans tenir compte de la casse, barres obliques finales ignorées) et, lorsque la requête en indique un, le mode d'authentification. Déplacer un fournisseur vers une autre destination abandonne les huit réglages, qui décrivent l'amont précédent, ainsi que le pool de clés, dont les clés ont été émises pour lui. Une sauvegarde ne fusionne jamais le reste de l'ancienne ligne dans la nouvelle. +La destination est l'adaptateur, l'URL de base (schéma et hôte comparés sans tenir compte de la casse, barres obliques finales ignorées) et, lorsque la requête en indique un, le mode d'authentification. Déplacer un fournisseur vers une autre destination abandonne les treize réglages, qui décrivent l'amont précédent, ainsi que le pool de clés, dont les clés ont été émises pour lui. Une sauvegarde ne fusionne jamais le reste de l'ancienne ligne dans la nouvelle. -`PATCH /api/providers?name=` ne modifie que les champs qu'il nomme et conserve tous les autres champs enregistrés, quelle que soit la destination. Il accepte les huit réglages ; `null` en efface un. Pour les deux listes de raisonnement, un tableau vide est enregistré comme refus explicite au lieu d'être supprimé. +`PATCH /api/providers?name=` ne modifie que les champs qu'il nomme et conserve tous les autres champs enregistrés, quelle que soit la destination. Il accepte les treize réglages ; `null` en efface un. Pour les deux listes de raisonnement, un tableau vide est enregistré comme refus explicite au lieu d'être supprimé. ## Sécurité des connexions sortantes de diagnostic des fournisseurs @@ -218,8 +240,7 @@ Utilisez **Codex Auth** dans le tableau de bord pour ajouter des comptes au grou métadonnées non secrètes ; les jetons d'accès et d'actualisation utilisent le magasin d'identifiants renforcé. Le routage du pool distingue l'affectation des requêtes nouvelles ou non liées, la commutation proactive fondée sur l'utilisation et la récupération après incident. Une tâche liée conserve normalement son affinité. Par défaut (`pool.cacheAffinity`), cette réaffectation attend que le compte lié soit épuisé ou ne puisse plus servir, et seulement vers un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez `pool.cacheAffinity: false` pour laisser `quota` la relier dès la requête suivante une fois le seuil franchi, toujours sous la même contrainte de destination. Un refus de quota 429/402, une pause, une invalidation des identifiants ou l'expiration du TTL libèrent encore la liaison immédiatement ; une série d'échecs transitoires (5xx et autres échecs hors quota) sert la requête sur un autre compte sans supprimer la liaison active. -Une requête non liée ne possède aucune liaison active à un compte ; il peut s'agir d'une tâche existante visible après le redémarrage -du proxy ou la réinitialisation de l'affinité. Un 429 ou un 402 reçu avant le début de la diffusion déclenche une nouvelle tentative unique sur un +Une requête non liée ne possède aucune liaison active à un compte . Les liaisons des requêtes avec un identifiant de session (y compris les tours habituels de Codex CLI et App et les sous-agents), ou des requêtes sans session ancrées sur leur parent immédiat, peuvent survivre à un redémarrage normal du proxy jusqu’à 24 heures d’inactivité, si l’enregistrement final de l’affinité à l’arrêt réussit. Les chaînes sans session plus profondes et les liaisons à la connexion principale de Codex App restent en mémoire uniquement et sont réattribuées après le redémarrage ; une expulsion, la suppression du compte, une reconnexion, un plantage ou une réinitialisation de l’affinité peuvent laisser une tâche non liée. Un 429 ou un 402 reçu avant le début de la diffusion déclenche une nouvelle tentative unique sur un autre compte admissible au sein de la même requête, même lorsque la commutation proactive fondée sur l'utilisation est désactivée. Les changements de compte préservent et relisent le contexte de la conversation, mais la réutilisation du cache d'invites du fournisseur entre plusieurs comptes n'est pas garantie et le cache peut devoir être réchauffé. @@ -238,7 +259,7 @@ et suspend uniquement ceux dont l'utilisation vient d'être confirmée à 100 % | Stratégie | Comportement | | --- | --- | | `quota` (par défaut) | S'il n'existe aucun compte actif, choisir le compte admissible le moins utilisé selon les fenêtres de 5 heures, d'une semaine et de 30 jours. Sinon, conserver un compte actif admissible sous `autoSwitchThreshold` ; une fois le seuil franchi, une requête non liée peut être déplacée vers un compte admissible moins utilisé. Les tâches liées conservent l'affinité de cache par défaut et restent jusqu'à ce que le compte soit épuisé (utilisation connue à 100 %) ou ne puisse plus servir (suspendu, inutilisable) ; un déplacement exige alors une véritable marge de quota et une utilisation strictement inférieure sur la destination. Définissez `pool.cacheAffinity: false` pour laisser la requête suivante d'une tâche liée bouger au seuil, toujours vers un compte admissible moins utilisé disposant d'une véritable marge de quota. `0` désactive cette réévaluation fondée sur l'utilisation, mais pas la récupération après incident. | -| `round-robin` | Répartit uniformément les requêtes non liées entre les comptes admissibles. La rotation repose sur un compteur et ignore les seuils, mais le filtre commun des niveaux de priorité évalue toujours la marge de chaque compte selon son seuil effectif (valeur spécifique au compte ou seuil global). `accountPoolStickyLimit` (1–100) compte les affectations effectuées avec une même sélection, et non les réponses réussies en amont. | +| `round-robin` | La rotation repose sur un compteur. Une nouvelle affectation ignore les comptes ayant atteint leur `autoSwitchThreshold` effectif (valeur du compte ou seuil global, évalué comme pour `quota`) tant qu'un compte admissible reste en dessous ; une utilisation inconnue ou un seuil de `0` compte comme inférieur. Si tous les comptes admissibles ont atteint leur seuil, la rotation les inclut tous. Une tâche liée conserve son compte au-delà du seuil et ne change que s'il ne peut plus servir (temporisation, refus de quota, basculement ou pause) ; l'enfant d'une conversation active commence sur le compte utilisé par son parent. Le filtre commun des niveaux de priorité évalue la marge de la même façon. Une sélection manuelle de l'opérateur prend le placement suivant dans chaque portée de quota, quelle que soit son utilisation ; une requête réussie sur ce compte dans cette portée consomme la sélection, puis les placements suivants y appliquent à nouveau le seuil. `accountPoolStickyLimit` (1–100) compte les affectations effectuées avec une même sélection, et non les réponses réussies en amont. | | `fill-first` | Attribue les requêtes non liées au compte actif jusqu'à sa temporisation, sa réauthentification ou le seuil d'évacuation effectif de ce compte (valeur spécifique au compte ou seuil global) ; une utilisation inconnue n'impose pas de changement. Les tâches liées et saines conservent leur affinité. | La rotation ne protège pas contre l’application des règles par les fournisseurs ; l'utilisation de plusieurs comptes peut enfreindre les conditions du fournisseur. @@ -252,9 +273,9 @@ rotation automatique peut déclencher des restrictions du fournisseur. | Clé | Type | Par défaut | Description | | --- | --- | --- | --- | | `anthropicAccountPool.enabled?` | `boolean` | `false` | Active l'affinité de session persistante et la sélection des nouvelles sessions basée sur l'usage. **Le basculement sur 429 n'est pas contrôlé ici** : il s'active dès que deux comptes utilisables sont enregistrés, comme pour tout autre fournisseur multi-identifiants, et ne peut pas être désactivé. | -| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | Pour les nouvelles sessions, lorsque le compte actif atteint ce seuil, choisir la plus faible utilisation connue et mise en cache dans la fenêtre configurée. `0` désactive la sélection selon le quota. | -| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | Stratégie des nouvelles sessions ; `quota` classe les comptes selon la fenêtre définie par `quotaWindow`, par défaut les barres sur 5 heures, et `fill-first` évalue son seuil d'évacuation dans cette même fenêtre. | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | Barre d'utilisation signalée par le fournisseur, mise en cache et utilisée pour la sélection selon l'utilisation. `five-hour` conserve le comportement actuel. `weekly` utilise la barre hebdomadaire et ignore les comptes dont la barre sur 5 heures est épuisée tant qu'un autre compte admissible reste disponible, mais y revient si aucun autre ne reste. `max-utilization` utilise la valeur connue la plus élevée et peut donc employer la barre sur 5 heures avant que la barre hebdomadaire soit disponible ; si aucune n'est connue, le compte suit l'ordre des utilisations inconnues. Les utilisations connues précèdent les inconnues, mais si tous les comptes admissibles sont inconnus, la sélection en renvoie tout de même un dans leur ordre admissible. Après le départage documenté par la plus faible utilisation sur 5 heures, une égalité exacte conserve cet ordre. Une session saine avec affinité n'est pas rééquilibrée de manière proactive. Pour l'affectation des nouvelles sessions et la reprise du routage après un remplacement admissible à la suite d'un 429, `quota` classe directement les candidats admissibles avec cette fenêtre ; `fill-first` avance dans un ordre stable selon le seuil et les règles d'épuisement de cette fenêtre ; `round-robin` l'ignore. Le délai de récupération, les limites de basculement et l'éligibilité de réauthentification restent des états locaux distincts. Les barres hebdomadaires ne sont connues qu'après leur interrogation dans la page Fournisseurs du tableau de bord. | +| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | Pour les nouvelles sessions, lorsque le compte actif atteint ce seuil, choisir le compte dont l'utilisation connue en cache est la plus faible dans la fenêtre configurée, en privilégiant les comptes encore sous leur propre seuil ; le compte choisi n'a pas lui-même à atteindre ce seuil. `0` désactive uniquement la commutation proactive selon l'utilisation ; la sélection d'une nouvelle session et la reprise après un 429 admissible consultent toujours `quotaWindow`. | +| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | Stratégie des nouvelles sessions. `quota` conserve le compte actif jusqu'à ce que son utilisation dans `quotaWindow` atteigne son `autoSwitchThreshold` effectif (80 par défaut) ou qu'il ne puisse plus servir, puis choisit le compte le moins utilisé en privilégiant ceux sous leur propre seuil ; une utilisation inconnue conserve le compte actif. `round-robin` alterne les nouvelles sessions sans consulter les seuils d'utilisation. `fill-first` évalue son seuil d'évacuation dans `quotaWindow`. | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | Barre d'utilisation signalée par le fournisseur, mise en cache et utilisée pour la sélection selon l'utilisation. `five-hour` conserve le comportement actuel. `weekly` utilise la barre hebdomadaire et ignore les comptes dont la barre sur 5 heures est épuisée tant qu'un autre compte admissible reste disponible, mais y revient si aucun autre ne reste. `max-utilization` utilise la valeur connue la plus élevée et peut donc employer la barre sur 5 heures avant que la barre hebdomadaire soit disponible ; si aucune n'est connue, le compte suit l'ordre des utilisations inconnues. Les utilisations connues précèdent les inconnues, mais si tous les comptes admissibles sont inconnus, la sélection en renvoie tout de même un dans leur ordre admissible. Après le départage documenté par la plus faible utilisation sur 5 heures, une égalité exacte conserve cet ordre. Une session saine avec affinité n'est pas rééquilibrée de manière proactive. Lorsque `quota` choisit un remplacement (nouvelle session dont le compte actif a atteint son seuil ou ne peut plus servir, ou reprise après un 429 admissible), il privilégie les candidats sous leur propre seuil et les classe avec cette fenêtre ; `fill-first` avance dans un ordre stable selon le seuil et les règles d'épuisement de cette fenêtre ; `round-robin` l'ignore. Le délai de récupération, les limites de basculement et l'éligibilité de réauthentification restent des états locaux distincts. Les barres hebdomadaires de chaque compte proviennent des sondages d'utilisation ou des en-têtes de réponse observés. | | `anthropicAccountPool.stickyLimit?` | `number` | `1` | Liaisons de nouvelle session réussies conservées sur une sélection à tour de rôle. Portée 1–100. | Seul un 429 confirmant le rejet d'un quota partagé de cinq heures ou hebdomadaire déclenche la temporisation et le basculement du compte. Une limitation temporaire suspend son admission en conservant l'affinité : au plus un bref nouvel essai sur le même compte et un détour vers un autre compte admissible par requête. Sans en-tête probant, un 429 permet un seul bref nouvel essai sur le même compte, sans refroidir le compte ni inventer Retry-After. Le comportement par défaut avec un seul compte reste identique. Un rejet propre à Fable laisse Sonnet admissible ; choix manuel et affinité vérifient aussi les quotas partagés et ceux de la famille demandée. Les observations passives de famille expirent après trente minutes ou à leur réinitialisation connue et sont revalidées par une seule requête à la fois. Les seuils restent des préférences souples avec le repli existant lorsque tous les candidats sont épuisés, sans plafond strict d'utilisation ou de facturation. L'affinité est locale au processus et de taille bornée. Les erreurs de renouvellement du jeton suivent les règles de réauthentification existantes. Un 403 confirmé lié à un abonnement ou à la facturation du compte permet un basculement avant la sortie, avec une temporisation selon `Retry-After` ou de dix minutes par défaut. Un refus d’autorisation ordinaire ne déclenche pas de basculement. Si tous les comptes admissibles sont en temporisation, les clients reçoivent un 429 accompagné de diff --git a/docs-site/src/content/docs/fr/reference/configuration/server.md b/docs-site/src/content/docs/fr/reference/configuration/server.md index 20e8336a1f..cc7ddafbca 100644 --- a/docs-site/src/content/docs/fr/reference/configuration/server.md +++ b/docs-site/src/content/docs/fr/reference/configuration/server.md @@ -15,7 +15,7 @@ exécute des fonctionnalités d'assistance autour des demandes du fournisseur. | `proxy?` | `string` | — | URL du proxy HTTP(S) ou SOCKS5 sortant (`socks5://host:port`) ou `${ENV_VAR}`. Les URL HTTP s’appliquent à `HTTP_PROXY` / `HTTPS_PROXY` si elles sont vides. Les URL SOCKS5 utilisent le tunnel SOCKS5 intégré et sont aussi exposées via `ALL_PROXY` (`ocx start --socks5`); `HTTP(S)_PROXY` héritées sont effacées dans ce processus. Le bouclage reste dans `NO_PROXY`. | | `emptyCompletionRetry?` | `boolean` | `false` | Active une nouvelle tentative Responses identique lorsqu’une réponse ne contient ni texte ni appel d’outil. Cette tentative peut être facturée. `OCX_EMPTY_COMPLETION_RETRY=0` la désactive sans modifier la configuration ; les combinaisons et les tours de compactage routés restent exclus. | | `stallTimeoutSec?` | `number` | `300` (public) / désactivé (local) | Secondes sans progression utile en amont (Responses et Chat natif) avant la coupure du flux. Sans réglage, un amont **local** (loopback, privé ou nom `.local`/`.lan`) est désactivé par défaut et un amont public vaut 300 s ; une valeur positive s'applique aux deux (minimum 1 s) ; `0` désactive partout le watchdog de silence. Pour Responses qui replie le SSE canonique ChatGPT en JSON non-streaming, un plafond total indépendant de 15 minutes subsiste même lorsque ce watchdog est désactivé. Les lectures de corps en attente de `/v1/responses/compact` partagent ce budget mais valent 300 s par défaut même pour un amont local ; une valeur explicite, y compris `0`, prime. | -| `connectTimeoutMs?` | `number` | `200000` | Délai maximal par tentative pour DNS/TCP/TLS et les en-têtes finaux ; il prend fin avant la génération du corps. | +| `connectTimeoutMs?` | `number` | `200000` (public) / désactivé (local) | Délai par tentative entre l'envoi de la requête et le premier en-tête de réponse de l'amont (DNS/TCP/TLS et attente des en-têtes) ; il prend fin avant la génération du corps et est indépendant de `stallTimeoutSec`, qui régit le flux du corps. Sans réglage, un amont **local** (loopback, privé ou nom `.local`/`.lan`) est désactivé par défaut et un amont public vaut 200 s ; une valeur positive s'applique aux deux ; `0` (ou toute valeur non positive) désactive partout ce délai d'en-tête. La désactivation permet à un modèle local de passer plusieurs minutes en prompt prefill sur une requête volumineuse sans que l'horloge du premier en-tête ne coupe une requête saine. | | `shutdownTimeoutMs?` | `number` | `5000` | Délai de vidange gracieux avant l’annulation des tours actifs. | | `websockets?` | `boolean` | `false` | Annonce et autorise la route WebSocket Responses destinée aux clients. La valeur false maintient les clients sur HTTP/SSE ; elle ne désactive pas une optimisation WebSocket canonique admissible vers ChatGPT en amont. | | `corsAllowOrigins?` | `string[]` | `[]` | Origines exactes supplémentaires autorisées par CORS. Les origines de bouclage sont toujours autorisées. Les origines d'extensions de navigateur basées sur l'autorité telles que `chrome-extension://` sont prises en charge ; `*` n'est pas un caractère générique. Firefox et Safari régénèrent l'extension UUID (par installation / par lancement de navigateur), mettez donc à jour l'entrée lorsque l'origine change. | @@ -31,6 +31,7 @@ exécute des fonctionnalités d'assistance autour des demandes du fournisseur. | `webSearchSidecar?` | `OcxWebSearchSidecarConfig` | activé lorsqu'il est utilisable | Options du service auxiliaire de recherche Web. | | `visionSidecar?` | `OcxVisionSidecarConfig` | activé lorsqu'il est utilisable | Options du service auxiliaire de description d'images. | | `images?` | `OcxImagesConfig` | sélection automatique OpenAI | Options de relais d'images autonomes pour Codex `image_gen`. | +| `telemetry?` | `OcxTelemetryConfig` | activé par défaut après information d'un humain | État du consentement à la télémétrie quotidienne anonyme (`decision`, `decidedAt`, `noticeShownAt`). Rien n'est envoyé tant qu'une personne n'a pas vu l'avis ou donné son accord. Remplacé par `OCX_TELEMETRY=0` ou `DO_NOT_TRACK=1`. Voir [Télémétrie (`telemetry`)](#télémétrie-telemetry) et [Télémétrie et confidentialité](/fr/guides/telemetry/). | Si une ancienne version de développement a modifié les métadonnées de l'historique de reprise avant que la prise en charge de la sauvegarde n'existe, exécutez `ocx recover-history --legacy-openai --yes` pour forcer la récupération du fournisseur natif. @@ -155,6 +156,35 @@ La commande `ssh -L` simple écoute sur votre interface de bouclage locale et co `0.0.0.0`. Liez explicitement avec `ssh -L 127.0.0.1:20100:localhost:10100` en cas de doute. ::: +## Télémétrie (`telemetry`) + +La télémétrie d'utilisation quotidienne anonyme n'est activée par défaut qu'après qu'une personne a vu l'avis d'information (dans la fenêtre du tableau de bord ou une invite de terminal interactif). Le bloc `telemetry` dans `config.json` enregistre cet état de consentement : + +```json +{ + "telemetry": { + "decision": "accepted", + "decidedAt": "2026-11-07T09:00:00.000Z", + "noticeShownAt": "2026-11-07T09:00:00.000Z" + } +} +``` + +| Champ | Type | Par défaut | Signification | +| --- | --- | --- | --- | +| `telemetry.decision?` | `"accepted" \| "declined"` | non défini (indécis) | Choix explicite de l'utilisateur. `"declined"` désactive la télémétrie et supprime `/telemetry-id.json` ; `"accepted"` active les rapports quotidiens. | +| `telemetry.decidedAt?` | `string` (ISO 8601) | non défini | Horodatage UTC de l'enregistrement de `decision`. Seuls les jours calendaires UTC complets strictement postérieurs au jour UTC de `decidedAt ?? noticeShownAt` (`day > formatUtcDay(decidedAt ?? noticeShownAt)`) sont envoyés ; le jour du consentement et les jours antérieurs ne sont jamais envoyés rétroactivement. | +| `telemetry.noticeShownAt?` | `string` (ISO 8601) | non défini | Horodatage UTC auquel un humain a vu l'avis dans le tableau de bord web ou un terminal interactif. Lorsque `decision` n'est pas défini, la télémétrie n'envoie de rapport que si `noticeShownAt` est défini (`default-on`) ; sans lui, le proxy reste en `awaiting-notice`. | + +Le point de terminaison du collecteur (`https://telemetry.opencodex.me/v1/events`) est une constante du code et ne peut pas être configuré dans `config.json`. + +Deux variables d'environnement remplacent `config.json` et désactivent immédiatement la télémétrie sans modifier `config.json` (observer l'une d'elles au démarrage ou lors d'un cycle enregistre aussi `ineligibleThroughDay` dans `/telemetry-state.json` et supprime `/telemetry-id.json`, de sorte que ces jours ne sont jamais envoyés ultérieurement) : + +- `OCX_TELEMETRY=0` (accepte aussi `false`, `off` ou `no`, insensible à la casse) +- `DO_NOT_TRACK=1` (accepte aussi `true` ou `yes`, insensible à la casse) + +`ocx config set telemetry` et `ocx config unset telemetry` sont refusés, et `ocx config import` ignore tout bloc `telemetry` importé pour tous les appelants en préservant l'état existant ; utilisez plutôt `ocx telemetry enable` (nécessite un terminal humain interactif avec invite de confirmation, sinon échoue avec `agent_consent_required` / `tty_required`), `ocx telemetry disable`, `ocx telemetry status [--json]` ou le commutateur **Détails du proxy** du tableau de bord. Voir [Télémétrie et confidentialité](/fr/guides/telemetry/) pour le schéma complet et la politique de conservation. + ## Nettoyage du stockage `storageCleanupPolicy` est désactivé par défaut. Lorsqu'il est activé, il s'exécute selon `startup`, `daily`, `weekly` @@ -322,3 +352,11 @@ Le retour à 2.80.0 ne garantit ni l’agrégation canonique ni le même solde d Les journaux de versions expérimentales non publiées contenant `pool-current` ou `poolContinuity` sont exclus du contrat C, même après compactage. Leurs soldes d’origine restent un historique inconnu jusqu’à l’expiration normale, sans conversion ni suppression immédiate. Un enregistrement complet mais invalide, y compris un `null` final, bloque l’admission sous plafond. Le compactage peut conserver les données valides dans un point de contrôle propre, mais le refus reste actif jusqu’au redémarrage avec ce journal propre. Une dernière ligne JSON incomplète suit les règles de récupération existantes. Voir les limites et codes d’erreur dans la [référence anglaise](/reference/configuration/server/#historical-pool-continuity). + +## Classification des délais des upstreams locaux + +Cette classification règle les délais, pas les autorisations réseau. Sans requête DNS, les destinations HTTP(S) locales sont : `localhost` exact (casse indifférente, point final admis), `0.0.0.0`, loopback IPv4 (127/8), plages privées RFC 1918 et link-local (169.254/16), loopback IPv6, link-local (fe80::/10), unique-local (fc00::/7), équivalents IPv4-mapped et noms `.local`/`.lan`. Les autres noms DNS gardent les délais publics même s'ils résolvent vers loopback. Les destinations invalides, les schémas non pris en charge et `localhost.example` restent publics. + +Désactiver le délai d'en-tête préserve l'annulation client et toute échéance globale englobante. Un `stallTimeoutSec` explicitement positif borne le silence du corps local ; sans délais locaux header/stall configurés, aucune borne automatique ne précède les en-têtes. Le JSON local de Chat/Messages natif utilise le budget stall ; le JSON public conserve `max(connectTimeoutMs ?? 200000, 5000)`. Le corps compact conserve 300 secondes par défaut, même en local. Les budgets image/recherche restent inchangés. + +Le bloc facultatif `opencodeClientExport` accepte `headerTimeoutMs`, `chunkTimeoutMs` et `timeoutMs` : millisecondes positives ou `false` pour désactiver. Les valeurs absentes préservent les défauts OpenCode ; les champs invalides sont omis. Ces réglages couvrent tout le provider, dans options V1 et settings V2. Voir [modèles locaux lents](/guides/opencode/#slow-local-models-prefill-timeouts). diff --git a/docs-site/src/content/docs/fr/reference/inbound-body-admission.md b/docs-site/src/content/docs/fr/reference/inbound-body-admission.md index 6ca406cd94..cc3cc9efd6 100644 --- a/docs-site/src/content/docs/fr/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/fr/reference/inbound-body-admission.md @@ -9,14 +9,67 @@ reste 256 MiB et les valeurs configurées restent comprises entre 1 MiB et 512 M proxy après avoir modifié la limite afin que l'écouteur et les lecteurs utilisent ensemble la valeur voulue. +Conserver l'ancien budget partagé par défaut de 512 MiB ne supprime pas les compromis +décrits ci-dessous concernant la file et la rétention pendant le cycle de vie des réponses. + +## Choisir explicitement le budget partagé + +`maxConcurrentInboundBodyBytes` est un réglage facultatif de **premier niveau** dans +`config.json`, exprimé en octets. Sa valeur par défaut reste **512 MiB (`536870912`)**, +comme auparavant. Une valeur absente, `0` ou invalide utilise cette valeur par défaut. +Un entier positif valide est borné à **512 MiB–2 GiB (`536870912`–`2147483648`)** lors +de son utilisation. Redémarrez le proxy après modification. Tous les écouteurs d'un même +processus partagent un seul budget, distinct de `appOwnedMemoryBudgetMb`. + +Pour choisir une limite de 512 MiB par requête et activer explicitement un budget partagé +de 2 GiB, ajoutez ces champs au premier niveau de votre `config.json`, puis redémarrez : + +```json +{ + "maxInboundBodyBytes": 536870912, + "maxConcurrentInboundBodyBytes": 2147483648 +} +``` + +Ce choix de l'opérateur augmente le pic potentiel de consommation mémoire. Le proxy ne +détecte pas automatiquement la RAM disponible et ne choisit pas le budget en fonction de celle-ci. + ## Augmenter la limite modifie la simultanéité -Quand la limite résolue dépasse 256 MiB, chaque requête HTTP concernée réserve toute sa marge -configurée dans un budget d'admission partagé de 512 MiB pour le processus entier. Au plus une -requête de ce type peut donc s'exécuter à la fois, même si plusieurs écouteurs partagent le -processus. Les petits corps réservent eux aussi toute la marge ; ni un petit Content-Length ni -la compression ne contournent l'admission. La réservation demeure jusqu'à la fin du flux de -réponse, son échec ou la fin de l'annulation, et pas seulement jusqu'à l'analyse du JSON entrant. +Quand la limite effective dépasse 256 MiB, chaque requête HTTP concernée doit réserver toute +sa marge par requête **avant toute lecture du corps**. Ces réservations partagent le budget +`maxConcurrentInboundBodyBytes` du processus, dont la valeur par défaut reste **512 MiB**. + +Avant la fin de l'analyse JSON avec contrôle de taille, ni un petit `Content-Length` ni un petit +corps compressé sur le réseau ne réduisent la réservation. L'admission ne considère pas ces +valeurs comme une preuve fiable de la taille décodée ou normalisée du JSON. + +Après une analyse JSON réussie dans les limites de taille, le lecteur réduit la réservation +au maximum des octets observés sur le réseau, des octets décodés et de la mesure existante du +JSON normalisé lorsqu'un traducteur fournit un budget pour cette mesure. La réservation ne +peut que diminuer et reste plafonnée à la marge initiale par requête ; une mesure du JSON +normalisé supérieure à cette marge ne l'augmente jamais. Les contrôles UTF-8 et de JSON +resérialisé sont conservés ; la longueur d'entrée ne remplace pas la taille potentiellement +plus grande du JSON normalisé. + +Avec le **budget partagé par défaut de 512 MiB** et une **limite de 512 MiB par requête**, +**un seul envoi non encore analysé** peut réserver toute sa marge. Même si l'analyse réduit +sa réservation à **un octet**, la capacité restante est inférieure à 512 MiB. La prochaine +marge complète doit donc attendre qu'assez de capacité soit libérée. La valeur par défaut +**ne résout pas** le problème initial de simultanéité avec une limite de 512 MiB par requête. + +Définir explicitement `maxConcurrentInboundBodyBytes` à `2147483648` choisit **2 GiB** et +permet jusqu'à **4 envois réservant chacun 512 MiB** avant l'analyse et les réductions après +mesure. Ce budget de 2 GiB ne fixe pas un plafond de 4 requêtes après l'analyse : par exemple, +**8 très petites requêtes peuvent diffuser leur réponse simultanément** lorsque les réservations +réduites laissent de la place aux admissions suivantes, sous réserve du budget partagé et +des autres limites. + +La réservation réduite reste détenue pendant le travail asynchrone et l'attente du fournisseur, +jusqu'à la fin du flux de réponse (EOF), une erreur ou la fin de l'annulation. L'analyse seule +ne la libère pas. Si le client se déconnecte, elle reste détenue jusqu'à la fin de l'annulation +côté producteur. Elle est libérée exactement une fois, même si erreur, abandon et annulation +se produisent en concurrence. Les points de terminaison POST concernés sont `/v1/responses`, `/v1/responses/compact`, `/v1/chat/completions`, `/v1/messages`, `/v1/messages/count_tokens`, @@ -26,33 +79,51 @@ existantes par corps. Les traductions directes internes et les appels combo ne r une deuxième marge HTTP. Les limites de gestion, d'audio, d'historique de contexte et de WebSocket restent inchangées. -Un réglage absent ou égal à zéro, ou une limite résolue inférieure ou égale à 256 MiB, -n'active pas ce contrôle supplémentaire de simultanéité. Les limites existantes sur le nombre -de requêtes et les autres ressources continuent de s'appliquer. +Ce contrôle supplémentaire ne s'applique que si la valeur effective de `maxInboundBodyBytes` +dépasse 256 MiB. Omettre ce réglage par requête ou le définir à `0` conserve sa valeur par +défaut de 256 MiB et laisse le contrôle inactif. Omettre ou mettre à zéro +`maxConcurrentInboundBodyBytes` choisit au contraire le budget partagé par défaut de 512 MiB, +sans désactiver un contrôle déjà actif. Les limites existantes sur le nombre de requêtes et +les autres ressources continuent de s'appliquer. ## Refus temporaire ou corps trop volumineux -Si aucune marge n'est temporairement disponible, le serveur renvoie HTTP **503**, -`Retry-After: 1` et le code d'erreur `server_busy`, avant l'analyse du protocole ou l'envoi au -fournisseur. Les clients Messages et de comptage de jetons reçoivent une erreur au format -Anthropic de type `overloaded_error` ; les clients compatibles OpenAI reçoivent -`server_error`. Réessayez après la fin de la requête en cours, en respectant l'en-tête de -nouvelle tentative et la temporisation du client. Augmenter encore la limite du corps ne -résout pas l'indisponibilité de la marge. +Si la marge complète est temporairement indisponible, la requête peut rejoindre une **file +FIFO de 32 requêtes en attente au maximum**, avec une **attente limitée à 120 secondes**. +Pendant l'attente, l'application ne lit pas les corps des requêtes. Une réduction après mesure ou une libération +finale permet d'admettre les requêtes dans l'ordre de la file. Une requête abandonnée pendant +l'attente est retirée de la file et son corps non lu est annulé sans être consommé. + +Une file pleine ou une attente expirée entraîne HTTP **503**, `Retry-After: 1` et le code +d'erreur `server_busy`, avant l'analyse du corps ou l'envoi au fournisseur. Les corps non lus +sont annulés lors du refus. Les clients Messages et de comptage de jetons reçoivent une erreur +au format Anthropic de type `overloaded_error` ; les clients compatibles OpenAI reçoivent +`server_error`. Les contrôles d'authentification et d'origine précèdent l'admission et la mise +en file. + +Respectez l'en-tête de nouvelle tentative et la temporisation du client. L'attente bornée et +les réservations mesurées réduisent les refus de capacité évitables, sans éliminer toutes les +réponses 503. Augmenter encore la limite par requête ne résout pas un épuisement durable de +la capacité. Un corps dépassant sa limite par requête suit toujours le traitement HTTP **413** existant. Une taille déclarée excessive emprunte cette voie plutôt que de devenir un refus pour serveur -occupé. Une déconnexion conserve le comportement d'annulation existant. Les contrôles -d'authentification et d'origine précèdent ce contrôle de simultanéité. +occupé. ## Ce que mesure le budget -512 MiB est la somme des marges admises par requête, **pas une garantie que la mémoire du -processus restera sous 512 MiB**. Le décodage, les chaînes, les graphes d'objets, les copies -de requêtes et les autres états de l'application consomment davantage de mémoire. Les mesures -existantes des octets UTF-8 et du JSON resérialisé sont conservées ; la longueur de l'entrée -en octets ne remplace pas la taille potentiellement plus grande du JSON normalisé. +Le budget configuré compte des unités d'admission : les marges complètes avant l'analyse, +puis les réservations mesurées. Il **ne préalloue ni 2 GiB ni le volume configuré** et +**ne borne ni la RSS du processus ni le tas des objets analysés**. Le décodage, les chaînes, +les graphes d'objets, les copies de requêtes et les autres états de l'application consomment +de la mémoire supplémentaire ; la consommation réelle peut donc dépasser le budget. + +Choisir 2 GiB au lieu du budget partagé par défaut de 512 MiB quadruple la réservation totale +possible. Avec une limite de 512 MiB par requête, ce choix explicite admet jusqu'à quatre envois +complets avant l'analyse au lieu d'un, ce qui augmente le pic potentiel de consommation mémoire. +Choisissez le budget selon la marge mémoire de votre déploiement. Une limite par requête +inférieure ou égale à 256 MiB laisse ce contrôle inactif, quel que soit le budget partagé. -Pour des petites requêtes parallèles, conservez si possible la limite par défaut. Augmentez-la -volontairement pour un parcours avec un historique volumineux, en acceptant la restriction de -simultanéité supplémentaire. +Conservez si possible la limite par requête par défaut. Augmentez-la volontairement si un +parcours avec un historique volumineux l'exige, en tenant compte du pic mémoire potentiellement +plus élevé et de l'attente bornée. diff --git a/docs-site/src/content/docs/fr/reference/management-api.md b/docs-site/src/content/docs/fr/reference/management-api.md index b41651ea12..e155797773 100644 --- a/docs-site/src/content/docs/fr/reference/management-api.md +++ b/docs-site/src/content/docs/fr/reference/management-api.md @@ -279,15 +279,19 @@ Tant qu’une liste initiale fiable n’est pas disponible, les requêtes PUT va | `GET /api/oauth/status` | Sonder le flux OAuth d'un fournisseur | 400 fournisseur inconnu | | `POST /api/oauth/logout` | Supprimer les informations d'identification du fournisseur sélectionné | 400 fournisseur inconnu ; `oauth_mutation_busy` | | `GET, DELETE /api/oauth/accounts` | Répertorier les comptes masqués ou supprimer un compte Les lignes Kiro ajoutent `autoSelectable` et un `skipReason` fermé en cas d’exclusion de la sélection automatique ; un compte actif unique peut encore servir. Le quota reste facultatif. | 400 invalide provider/id ; 404 compte manquant ; `oauth_mutation_busy` | -| `PUT /api/oauth/accounts/active` | Sélectionnez le compte OAuth actif | 400 invalide provider/account ; `oauth_mutation_busy` | +| `PUT /api/oauth/accounts/active` | Sélectionnez le compte OAuth actif | 400 invalide provider/account ; `oauth_mutation_busy`; 503 `affinity_reset_not_persisted` (Anthropic: `selectionCommitted: true`, `retryable: true`; sélection enregistrée ; renvoyer la même requête même si le compte est actif) | | `GET, PUT, PATCH /api/oauth/accounts/pool` | Lire ou mettre à jour la stratégie du pool OAuth Anthropic | 400 fournisseur non Anthropic ou stratégie invalide | | `POST /api/oauth/accounts/clear-cooldown` | Effacer le temps de recharge d'un compte OAuth | 400 invalide provider/account | | `PUT /api/oauth/accounts/alias` | Définir ou supprimer un alias de compte OAuth | 400 invalide provider/account/alias | -| `PUT /api/oauth/accounts/pause` | Suspendre/reprendre Anthropic ou un compte OAuth générique. Body `{ provider, accountId, paused }` ; la suspension du compte actif sélectionne un autre compte utilisable s’il existe. | 400 fournisseur non pris en charge ou body invalide ; 404 compte absent ; `oauth_mutation_busy` | +| `PUT /api/oauth/accounts/pause` | Suspendre/reprendre Anthropic ou un compte OAuth générique. Body `{ provider, accountId, paused }` ; la suspension du compte actif sélectionne un autre compte utilisable s’il existe. | 400 fournisseur non pris en charge ou body invalide ; 404 compte absent ; `oauth_mutation_busy`; 503 `affinity_reset_not_persisted` (Anthropic: `pauseCommitted: true`, `retryable: true`; état de suspension enregistré ; conserver le compte et cet état, ajouter `retryAffinityReset: true` et réessayer, même après un redémarrage du serveur) | | `GET, POST, DELETE /api/providers/keys` | Répertorier les clés de fournisseur masquées, en ajouter ou en activer une, ou en supprimer une | 400 saisie invalide ; 404 fournisseur ou clé manquante | | `PUT /api/providers/keys/active` | Sélectionnez la clé active d'un fournisseur | 400 saisie invalide ; 404 provider/key manquant | | `PUT /api/providers/keys/alias` | Définir ou supprimer un alias de clé de fournisseur | 400 saisie invalide ; 404 provider/key manquant | +| `PUT /api/providers/keys/pause` | Suspendre ou reprendre une clé API de fournisseur. Body `{ name, id, paused }` ; la suspension de la clé active sélectionne la clé utilisable suivante selon l'ordre circulaire. En cas de succès, renvoie le résultat `activeAccountId` (ou `null`) et `activeAccountChanged`. | 400 saisie invalide ; 404 provider/key manquant | | `GET, POST, PATCH, DELETE /api/keys` | Répertorier, créer, modifier ou supprimer les clés d'admission du plan de données | 400 corps ou identifiant invalide ; 404 clé manquante | +| `PUT /api/oauth/accounts/affinity-reset` | Confirmer le reset des associations de conversations du provider sans exiger de compte. Body `{ provider }` ; succès : `affinityResetConfirmed: true`. CLI: `ocx account reset-affinity anthropic --json` (`anthropic2` supported). | 400 invalid body/provider; 503 `affinity_reset_not_persisted`, `retryable: true` | + +Le tableau de bord conserve l’avertissement tant que la publication du reset n’est pas confirmée, même si le compte a disparu. Un échec de chargement, une suspension ou une réauthentification requise conserve la tentative avec un message. Une fois l’absence confirmée par la liste, Réessayer appelle `PUT /api/oauth/accounts/affinity-reset` avec `{ provider }` et attend `affinityResetConfirmed: true` avant d’effacer l’avertissement. Cette opération supprime toutes les associations, y compris celles créées depuis le premier échec, sans sélectionner ni réactiver de compte ; une liste vide est acceptée. Une suppression avec un reset en attente envoie `retryAffinityReset=true`. En cas d’échec de publication, elle renvoie 503 `affinity_reset_not_persisted`, `deletionCommitted: true` et `retryable: true`. Le compte est déjà supprimé : réessayez le reset seul, pas la suppression. Une suppression ordinaire conserve les associations des comptes restants. Ce nettoyage est limité aux instances Anthropic OAuth enregistrées et conserve les contrôles d’authentification et d’origine de gestion. Les réponses qui répertorient les identifiants sont délibérément masquées. Les jetons d'accès OAuth et les clés API complètes des fournisseurs ne sont pas renvoyés aux clients du tableau de bord. @@ -353,7 +357,7 @@ lui-même s'il souhaite ajouter une étoile au dépôt. | `POST /api/system/restart` | Amorcer un redémarrage du processus qui attend l'évacuation des requêtes, sans retirer l'injection du client | Renvoie 202 ; les appels répétés signalent l'évacuation déjà en cours | | `POST /api/stop` | Arrêter le service, restaurer Codex en mode natif, retirer l'injection Grok gérée et évacuer les requêtes du proxy | 409 conflit de propriété du service; 409 `respawnable_service` lorsqu'un wrapper du Planificateur de tâches Windows pourrait relancer le proxy et que l'appelant n'est pas `ocx stop` (rien n'est modifié) ; 409 lorsque le gestionnaire installé refuse de s'arrêter ; 409 `service_state_unknown` lorsque l'état du Planificateur de tâches ne peut pas être lu (rien n'est modifié ; réparez la requête puis réessayez) | | `GET /api/system/codex-app-server` | Indiquer si les serveurs d'application Codex en cours d'exécution sont antérieurs au catalogue de modèles actuel | — | -| `POST /api/system/codex-restart` | Actualiser le catalogue, puis redémarrer les serveurs d'application Codex. L'application Codex Desktop n'est quittée puis relancée entièrement si elle a démarré avant l'écriture du catalogue actuel, si cette requête change la liaison `model_catalog_json` (même si le processus est plus récent que le fichier du catalogue), ou si l'état de son sélecteur ne peut pas être déterminé, afin que le sélecteur de modèles se recharge ; une application en cours avec un sélecteur à jour reste ouverte avec `desktopApp.reason: "picker_current"`. Une application fermée renvoie `desktopApp.reason: "no_targets"` ; son `pickerState` peut être `not_running`, ou `stale` si cette requête a changé la liaison au catalogue. `desktopApp.pickerState` indique la lecture qui a décidé (`current`, `stale`, `unknown` ou `not_running`). Lorsque le proxy lui-même s'exécute dans l'application Codex, le redémarrage Desktop est refusé plutôt que transféré. | Renvoie 200 avec `code: partially_stopped` lorsqu'une cible ne s'arrête pas | +| `POST /api/system/codex-restart` | Actualiser le catalogue, puis redémarrer les serveurs d'application Codex. Une application Codex Desktop en cours reçoit une tentative de redémarrage afin que le sélecteur de modèles puisse se recharger ; les champs `desktopApp` de la réponse signalent un refus, des cibles survivantes ou un échec de relance. Un processus plus récent que le catalogue est tout de même signalé avec `desktopApp.pickerState: "unknown"`, car son heure de démarrage ne prouve pas quelle liaison `model_catalog_json` il a chargée ; une synchronisation antérieure peut avoir relié un catalogue déjà existant. Un processus qui n'est pas plus récent que le catalogue, ou dont cette requête a changé la liaison, est `stale`. Une application fermée renvoie `desktopApp.reason: "no_targets"` ; son `pickerState` peut être `not_running`, ou `stale` si cette requête a changé la liaison au catalogue. Lorsque le proxy lui-même s'exécute dans l'application Codex, le redémarrage Desktop est refusé plutôt que transféré. | Renvoie 200 avec `code: partially_stopped` lorsqu'une cible ne s'arrête pas | ### Délégation de l'authentification Codex diff --git a/docs-site/src/content/docs/fr/reference/proxy-formats.md b/docs-site/src/content/docs/fr/reference/proxy-formats.md index ae904510a0..ae3aa2e736 100644 --- a/docs-site/src/content/docs/fr/reference/proxy-formats.md +++ b/docs-site/src/content/docs/fr/reference/proxy-formats.md @@ -225,6 +225,15 @@ La sortie sans streaming a `object: "chat.completion"`. La sortie streaming util `data: [DONE]`. Les informations d'appel d'outil et d'utilisation sont traduites là où les événements source sont transportés. eux. +Les réponses d'erreur et les trames d'erreur en streaming de ce point de terminaison utilisent des +messages rédigés par le proxy. Le proxy classe l'échec du fournisseur dans une condition fixe, par +exemple limite de débit atteinte, quota ou crédits épuisés, fenêtre de contexte dépassée, modèle +indisponible, emplacement non pris en charge ou vérification du compte requise, et renvoie le message +fixe de cette condition. Les refus de politique, les refus de rejeu et les limites du proxy ont leurs +propres messages fixes. Le statut HTTP, `error.type`, `error.code` et `Retry-After` gardent leur +signification : les clients qui s'appuient sur des codes comme `context_length_exceeded`, +`insufficient_quota` ou `rate_limit_exceeded` se comportent comme avant. + Étant donné que le chemin d'exécution interne est basé sur les réponses, un adaptateur de fournisseur peut imposer un chemin d'exécution plus étroit. ensemble de fonctionnalités. Par exemple, une fonctionnalité de demande qui ne peut pas être représentée par l'adaptateur sélectionné est renvoyé comme une erreur au lieu de changer silencieusement sa signification. diff --git a/docs-site/src/content/docs/fr/troubleshooting/windows-memory.md b/docs-site/src/content/docs/fr/troubleshooting/windows-memory.md index cae4dce252..b0d3f4476d 100644 --- a/docs-site/src/content/docs/fr/troubleshooting/windows-memory.md +++ b/docs-site/src/content/docs/fr/troubleshooting/windows-memory.md @@ -44,4 +44,4 @@ Si vous essayez l’une de ces solutions avec une charge Windows réelle, veuill L’installation et la réparation du service Windows ainsi que l’installation et l’actualisation du shim Codex vérifient que l’exécutable sélectionné peut créer puis supprimer un répertoire dans la racine de configuration OpenCodex. Ce contrôle de politique d’écriture ne corrige pas la mémoire. Un échec refuse l’opération avant tout arrêt, téléchargement, préparation ou écriture de jeton ou de lanceur. La réparation automatique du shim est différée avec des instructions et le démarrage continue. Les shims sains ou désactivés ne sont pas testés. Aucun autre runtime n’est recherché. Une première installation du planificateur enregistre sa tâche et revendique la racine de configuration avant ce contrôle ; en cas de refus, cet enregistrement est annulé et la racine revendiquée est conservée pour une nouvelle tentative. -> Le runtime Bun sélectionné ne peut pas créer puis supprimer un répertoire de configuration. La politique d’application Windows peut interdire les écritures depuis cet emplacement. Avant de lancer `ocx`, définissez `OPENCODEX_BUN_PATH` vers un exécutable Bun de confiance autorisé par votre politique, ou réinstallez avec `npm install -g @bitkyc08/opencodex`, puis réessayez. Aucun autre runtime n’a été sélectionné. +> Le runtime Bun sélectionné ne peut pas créer puis supprimer un répertoire de configuration. La politique d’application Windows peut interdire les écritures depuis cet emplacement. Avant de lancer `ocx`, définissez `OPENCODEX_BUN_PATH` vers un exécutable Bun de confiance autorisé par votre politique, ou réinstallez avec `npm install -g --allow-scripts=bun @bitkyc08/opencodex`, puis réessayez. Aucun autre runtime n’a été sélectionné. diff --git a/docs-site/src/content/docs/getting-started/for-agents.md b/docs-site/src/content/docs/getting-started/for-agents.md index b02c39812a..9bba3f1bfc 100644 --- a/docs-site/src/content/docs/getting-started/for-agents.md +++ b/docs-site/src/content/docs/getting-started/for-agents.md @@ -13,7 +13,7 @@ available for interactive configuration; see [Web Dashboard](/guides/web-dashboa Install the published package and confirm that `ocx` is on `PATH`: ```bash -npm install -g @bitkyc08/opencodex +npm install -g --allow-scripts=bun @bitkyc08/opencodex ocx --version ``` diff --git a/docs-site/src/content/docs/getting-started/installation.md b/docs-site/src/content/docs/getting-started/installation.md index 87bf1e1411..a2660d4c12 100644 --- a/docs-site/src/content/docs/getting-started/installation.md +++ b/docs-site/src/content/docs/getting-started/installation.md @@ -13,6 +13,12 @@ A stable OpenCodex Desktop install configures `ocx` for new terminals when the a On macOS and Linux, a current npm/pnpm package launcher that still runs delegates eligible commands to the Desktop CLI when its record is enabled and passes ownership, permission and file-safety checks. Windows has no package-launcher handoff: new terminals select the Desktop `ocx.exe` through user `Path` order. A `record-unsafe` error means the record or its directory failed a safety check. Open OpenCodex Desktop to repair the terminal command, or use `OCX_NO_DESKTOP_HANDOFF=1` for a package invocation on macOS/Linux. Package update/removal and internal inspection keep their existing path. `OCX_NO_DESKTOP_HANDOFF=1` suppresses that package handoff for one invocation; it does not change a direct Desktop shim or PATH configuration. +With an enabled Desktop command record, eligible macOS/Linux package-launcher calls stop if +the selected Desktop executable is missing or cannot start; they do not silently run the +npm/pnpm implementation. This can briefly interrupt commands during app replacement. Repair +or disable the terminal command in Desktop, or explicitly use `OCX_NO_DESKTOP_HANDOFF=1` +for one package invocation. That bypass does not repair the Desktop record, shim or PATH. + ## Prerequisites | Requirement | Why | @@ -24,7 +30,7 @@ On macOS and Linux, a current npm/pnpm package launcher that still runs delegate ## Install ```bash -npm install -g @bitkyc08/opencodex +npm install -g --allow-scripts=bun @bitkyc08/opencodex ``` With pnpm 10.4 or later: @@ -38,8 +44,8 @@ Recent npm versions may block bun's postinstall script (`npm warn install-scripts ... blocked because they are not covered by allowScripts`), which leaves the bundled Bun runtime unprepared. After trying permitted bundled-runtime recovery, the launcher can use an executable Bun from an absolute PATH directory if its -stable version has the pinned major and a minor at least the pinned minor. With the current -1.4.2 dependency, that means 1.4.0 or newer within major 1. Bounded version-policy and identity +stable version has the pinned major and a version at least the pinned version. With the current +1.4.4 dependency, that means 1.4.4 or newer within major 1. Bounded version-policy and identity checks require `bun --version` to match `bun -e`'s `Bun.version`. On POSIX, the launcher checks the whole candidate path, including ancestor directories and components reached through symlinks. Each traversed directory and symlink, and the resolved executable, must be owned by @@ -64,6 +70,12 @@ npm install -g --allow-scripts=bun @bitkyc08/opencodex # if the original install used sudo, keep using sudo: sudo npm install -g --allow-scripts=bun @bitkyc08/opencodex ``` + +On Windows a running proxy keeps `node_modules\bun\bin` open, so a manual +`npm install -g` fails with `EBUSY`. `ocx update` stops the proxy and restarts the service itself; +for a manual reinstall, stop it first (`ocx stop`), install, then restart through the owning service +(`ocx service restart`) or `ocx start` when unmanaged. `ocx doctor` prints this sequence when it finds +a package install whose bundled runtime never unpacked. ::: Verify both command aliases are on your `PATH`: @@ -110,7 +122,7 @@ the catalog entries do not grant access by themselves. Use the preview channel o unreleased opencodex builds: ```bash -npm install -g @bitkyc08/opencodex@preview +npm install -g --allow-scripts=bun @bitkyc08/opencodex@preview ocx update --tag preview ``` diff --git a/docs-site/src/content/docs/getting-started/quickstart.md b/docs-site/src/content/docs/getting-started/quickstart.md index 28cd4d10f7..cfb968ec90 100644 --- a/docs-site/src/content/docs/getting-started/quickstart.md +++ b/docs-site/src/content/docs/getting-started/quickstart.md @@ -1,9 +1,11 @@ --- title: Quickstart -description: Configure your first provider and route OpenAI Codex through opencodex in three commands. +description: Install opencodex, add your first provider, and connect the coding tool you already use, whether that is Codex, Claude Code, Claude Desktop, Grok Build or another supported tool. --- -This guide takes you from a fresh install to running Codex against a non-OpenAI model. +This guide takes you from a fresh install to the first request from the coding tool you already +use. Steps 1 and 2 are the same for every tool; step 3 has one short branch per tool. The +[client support page](/reference/client-support/) lists every tool and how it connects. ## Standalone binary (no npm) @@ -18,7 +20,7 @@ ocx init `ocx init` walks you through: -1. **Pick a provider** — choose one of the 104 built-in registry presets or `custom` to type a base +1. **Pick a provider** — choose one of the 107 built-in registry presets or `custom` to type a base URL and adapter. 2. **API key** — paste a key, or reference an environment variable like `${ANTHROPIC_API_KEY}`. 3. **Default model** — for key, local, and custom providers, accept the preset or enter a model id. @@ -103,9 +105,17 @@ ocx status ocx gui # open the dashboard on the live port ``` -## 3. Use Codex +## 3. Connect your tool -Codex now talks to opencodex transparently: +Pick the branch for the tool you use. You can connect more than one; they share the same +providers and models. + +### Codex + +If you accepted the Codex prompt in step 1, Codex now talks to opencodex transparently. If you +declined it, or setup exited because a config already existed, turn on the Codex switch on the +dashboard's **Connect** page before running Codex. [Codex Integration](/guides/codex-integration/) +explains what it changes and how to restore. ```bash codex "Refactor this function for readability" @@ -118,6 +128,53 @@ codex -m "anthropic/claude-opus-5" "Explain this stack trace" codex -m "ollama-cloud/glm-5.2" "Write a SQL migration" ``` +### Claude Code + +With the `claude` CLI installed: + +```bash +ocx claude +``` + +`ocx claude` starts the proxy if it is not running and launches Claude Code with its environment +pointed at opencodex. Extra arguments pass through. See [Claude Code](/guides/claude-code/) for +tier defaults, other launchers and how to opt out. + +### Claude Desktop + +```bash +ocx claude desktop +``` + +On a new install this sets up the gateway profile for the whole app. An install that already uses +the first-party mode keeps it; run `ocx claude desktop apply --gateway` to switch explicitly. The +first-party mode, which keeps Desktop on claude.ai and routes only its Code tab, is described under +[Claude Desktop modes](/guides/claude-code/#claude-desktop-modes-gateway-default-and-first-party). + +Fully quit and reopen Claude Desktop after switching modes. + +### Grok Build + +On a local listener, `ocx start` registers the visible models in `~/.grok/config.toml` when +`~/.grok` exists. Pick an `ocx-*` model in Grok Build. Remote setups and the managed block are +covered in [Grok Build](/guides/grok-build/). + +After you add providers or models, run `ocx ensure` or restart the proxy so Grok Build sees them. + +### Other tools + +Tools with a managed integration (OpenCode, Pi, Qoder, WorkBuddy, Kilo, Cline, T3 Code and more) are +connected from the dashboard's **Connect** page or with: + +```bash +ocx integration client enable --client +``` + +Each tool's config file and when the change takes effect are listed in +[Integrations](/guides/integrations/). Any other tool that accepts a custom endpoint can use the +OpenAI-compatible base URL `http://localhost:10100/v1` or the Anthropic base URL +`http://localhost:10100`. + ## Choose sub-agent models (optional) A fresh config features five native models in Codex's sub-agent picker: `gpt-5.5`, @@ -154,6 +211,12 @@ It stops before publishing a new runtime or changing those settings. Retry start local connectivity recovers; an installed background service retries through its service manager. A timeout does not permanently turn the new process into a secondary instance. +`Proxy ownership is unverified; startup refused` means the local owner check was +inconclusive. OpenCodex preserves the PID record, recovery journal and shared client +settings. Retry after the owner responds or exits; a failed health probe alone does +not authorize crash recovery. A dead recorded process with no listener still recovers +automatically. + IPv6 does not need to be enabled on loopback. Startup checks whether each loopback address can be bound locally and skips an unavailable family. Timeouts on an available family still stop startup until ownership can be verified. diff --git a/docs-site/src/content/docs/guides/chatgpt-desktop.md b/docs-site/src/content/docs/guides/chatgpt-desktop.md index 458acdfbed..8f195bfa82 100644 --- a/docs-site/src/content/docs/guides/chatgpt-desktop.md +++ b/docs-site/src/content/docs/guides/chatgpt-desktop.md @@ -104,10 +104,11 @@ restart transaction. ## Failure behavior and known limits -When the platform is not macOS, the OpenCodex runtime is missing, or the filter -self-test fails, the launcher runs the original binary with untouched stdout. A -missing bundled app-server binary is the exception: there is nothing to fall back -to, so the launcher exits with an error (see below). +The launcher verifies the executable before every start, including Desktop respawns. +If stdout filtering is unavailable or its self-test fails, the verified executable +runs with untouched stdout. If executable verification fails or the OpenCodex +validator is unavailable, the launcher exits with an error without starting the +app-server. A missing bundled app-server binary also prevents startup (see below). A filter that passes the self-test and then dies mid-session closes the pipe. What the bundled app-server does after that has not been verified; it may get SIGPIPE or a write error and be respawned by Desktop through the same launcher. @@ -117,8 +118,9 @@ remaining stream to raw bytes. The experiment depends on the bundled binary path, the app honoring `CODEX_CLI_PATH`, and current RPC field shapes. Updates may change these. A moved -or removed OpenCodex installation fails the launcher preflight and runs the -original binary. Run `ocx chatgpt launch` again after relocating the installation. +or removed OpenCodex installation can leave the launcher unable to verify the +executable, so it refuses startup. Run `ocx chatgpt launch` again after relocating +the installation, or `ocx chatgpt restore` to remove the override. If an app update moves or removes the bundled app-server binary itself, the launcher cannot start it: it prints a message naming `ocx chatgpt launch` and `ocx chatgpt restore` on stderr and exits, and Desktop cannot start its diff --git a/docs-site/src/content/docs/guides/claude-code.md b/docs-site/src/content/docs/guides/claude-code.md index eb1b9b9d14..1e82c07d20 100644 --- a/docs-site/src/content/docs/guides/claude-code.md +++ b/docs-site/src/content/docs/guides/claude-code.md @@ -15,7 +15,7 @@ This output-order fix does not resolve Cognition's separate refusal of some gene text. It preserves system instructions and safety constraints. For an Anthropic route on stored OAuth or an Anthropic API key, native Fast is available on -`claude-opus-5-5`, `claude-opus-5`, and `claude-opus-4-8`: pick the model's `--fast` row (listed +`claude-fable-5-2`, `claude-opus-5-5`, `claude-opus-5`, and `claude-opus-4-8`: pick the model's `--fast` row (listed when Fast rows are enabled) or set `fastMode: true`. Claude Code's own `/fast` toggle is not translated on routed requests: the `speed` field it sends does not survive translation. The proxy sends Anthropic's Fast request and records the returned `usage.speed`; only confirmed Fast usage gets the 2x API-equivalent cost estimate. A recognized Fast-specific refusal @@ -26,6 +26,19 @@ research-preview access. See [Anthropic Fast configuration](/reference/configuration/providers/#anthropic-fast-anthropic-speed) for the exact model and recovery scope. +## Claude OAuth client-version errors + +If an Anthropic OAuth request returns `claude_code_version_too_old`, check which provider you use. +For Codex routed through the `anthropic` adapter, OpenCodex supplies its own Claude Code +compatibility profile. Updating a separately installed `claude` executable does not update that +profile; update OpenCodex and restart the proxy instead. For the `claude-cli` provider or Claude +Code used directly, update the CLI instead. First-party native Messages requests with an observed +Claude client identity retain that client's version, and configured header overrides take precedence. + +For example, the error reported for `claude-fable-5-2` required Claude Code 2.1.290 or newer; +the profile in this version of OpenCodex presents 2.1.321. A newer upstream requirement may need +a later OpenCodex profile. Updating the profile does not grant model access or change subscription limits. + ## Tier defaults for CLI and external launchers In the Claude Code tab, select an Opus, Sonnet, Haiku or Fable default and **Save**. @@ -64,10 +77,28 @@ actual model served. This is especially useful for external classifiers requesti ## Claude OAuth account pool (experimental) -Native Anthropic subscription passthrough retains the upstream `anthropic-ratelimit-*` -response headers on streaming, JSON and upstream-error responses, so compatible Claude Code -statusLine consumers can read the provider's quota observations. Missing observations are -not filled with invented values. This relay does not change account selection or retry behavior. +Native Anthropic subscription passthrough retains recognized, valid `anthropic-ratelimit-*` +observations with normalized values on streaming, JSON and upstream-error responses. +Unrecognized names and invalid values are omitted; missing observations are not filled in. +Tests check the forwarded-header contract used by Claude Code statusLine consumers, including +fractional utilization and reset times. Account selection and retry behavior are unchanged. + +Usage reads support Ultra (formerly Max 20x). Pro, Max 5x and Team retain their measured +five-hour and weekly meters whichever one is currently binding. An Ultra null five-hour limit +leaves that meter absent unless Anthropic marks a finite session meter active. Current `limits` +counters take precedence over legacy duplicates; shared usage can affect routing even when +inactive, while only active model-specific weekly limits affect that model family. An inactive +model-specific limit, such as Fable while the shared week is the binding limit, still appears on +the account's quota bars tagged "Not in effect now". A Fable bar also shows the share Anthropic +reports, for example "Up to 50% of your weekly limit". A plan whose usage has no Fable row shows +no Fable bar. +The dashboard shows Pro, Max 5x, or Ultra beside Claude account quotas, using subscription +metadata from the authenticated profile. Both `ultra` and `claude_max_20x` display as Ultra +(the existing `ultra` and `max_20x` tier aliases are retained). Unfamiliar validated tiers retain their original name without +failing the usage read. Claude account rows prefer your alias, then a masked email, and +fall back to a numbered label when no safe identity is available. The provider Overview shows the +same label as a separate current-account field when its account list is verified. Set +`privacy.maskEmails` to `false` to show the full email in these rows instead. You can log in multiple Claude accounts via the Providers dashboard (`ocx login anthropic` / add-account). By default every request uses the **active** account only. @@ -78,9 +109,9 @@ session affinity and usage-aware new-session selection across those OAuth accoun to another account whether the pool is on or off, and the toggle does not switch that off; pause an account to keep it out of failover. For **new** sessions, -`anthropicAccountPool.strategy` selects among eligible accounts: `quota` (default) picks the -lowest known usage in the window set by `quotaWindow` (`five-hour` by default, or `weekly` / -`max-utilization`) when above `autoSwitchThreshold`; `round-robin` spreads evenly +`anthropicAccountPool.strategy` selects among eligible accounts: `quota` (default) keeps the active account until its usage in the window set by `quotaWindow` +(`five-hour` by default, or `weekly` / `max-utilization`) reaches `autoSwitchThreshold` +(default 80), then moves to the least-used account, preferring accounts still under their own threshold; `round-robin` spreads evenly (`stickyLimit`, default `1`); `fill-first` drains the active account until cooldown, reauthentication, or threshold, then advances. It is **off by default** and experimental. @@ -109,7 +140,7 @@ Operational contract when enabled: not postpone usage probes or clear a failed usage probe's unavailable status. Measurements whose known reset time has passed are discarded as unknown, including retained model-specific windows. Values without a known reset are preserved; missing data is never reported as zero usage. -- Affinity is **process-local** (lost on proxy restart). +- Affinity survives proxy restart within the same config home and provider instance (24-hour idle lifetime, newest 2,000 bindings). The private snapshot stores session digests and login fences, never raw session keys or tokens. Legacy accounts without a persistent login identity remain process-local until their next login. Token refresh preserves affinity; replacement login, account removal, pause/reauthentication and explicit runtime account selection invalidate it. A transient throttle detour preserves the original binding even when its pause expires before the retry commits. - A complete, structured **403** account-entitlement or billing refusal can rotate before output. Recognized cases include no Claude Code access, an expired/inactive subscription, and an insufficient Anthropic credit balance. The refused account loses its affinities and @@ -144,6 +175,7 @@ thinking fallback. Adaptive thinking without an explicit effort stays blank. The request controls; they do not confirm what effort the upstream applied or change the wire body. An enabled Anthropic account pool prefers native Messages for eligible direct Anthropic routes +and eligible key-auth Anthropic-compatible or first-party Anthropic children of strict failover combos without a default effort when neither native rollout flag explicitly disables that path. In Providers → Anthropic → Account pooling → **How account selection works**, **Preserve native Claude requests** stores `anthropicAccountPool.nativeMessages` (default true). Turning it off selects the legacy bridge @@ -183,7 +215,7 @@ ocx claude | `ANTHROPIC_DEFAULT_{OPUS,SONNET,FABLE}_MODEL` | `claudeCode.tierModels.*`; on a subscription launch an unset slot gets the native `claude-opus-5-5[1m]` / `claude-sonnet-5-5[1m]` / `claude-fable-5-1[1m]`, so `--model opus`, `sonnet` and `fable` keep their 1M context | | `ANTHROPIC_DEFAULT_{OPUS,SONNET,FABLE,HAIKU}_MODEL_NAME` | The `/model` label for a tier slot that OpenCodex sets to a routed alias, such as `gpt-6.1-sol (native)` for `ocx-claude-native--gpt-6.1-sol`. Without it, Claude Code labels that row with the alias. The alias stays the selected model id. When system env is on, the launchd environment and the shell hook get the same slot and label pair. A slot or label you set yourself is left alone | | `CLAUDE_CODE_ALWAYS_ENABLE_EFFORT` | `1` when `alwaysEnableEffort` is on (conditional) | -| `ENABLE_TOOL_SEARCH` | `claudeCode.toolSearch` when set (conditional; off by default — see [MCP tool schemas fill the context](#troubleshooting)) | +| `ENABLE_TOOL_SEARCH` | `claudeCode.toolSearch` when set (conditional; not injected by default, so Claude Code's own default applies — see [MCP tool schemas fill the context](#troubleshooting)) | | `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | Legacy context override when `maxContextTokens` is set (conditional) | Variables you export yourself always win. Extra arguments pass through: `ocx claude -p "hello"`. @@ -254,6 +286,12 @@ Claude Desktop can use OpenCodex in one of two mutually exclusive modes. Pick it **Connect → Claude Desktop → Connection mode** in the dashboard or with `ocx claude desktop apply --first-party|--gateway`. +> Desktop library profiles and `_meta.json` must be regular files of at most +> 4 MiB. OpenCodex also refuses generated profile or metadata output above that +> limit before replacing files. Back up and reduce oversized configuration +> manually; a size refusal does not truncate the existing data. Connection-owned +> stores retain their existing tighter limits. + ### Gateway (default) New installs use **gateway** by default. Its third-party profile, described below, switches the @@ -280,6 +318,32 @@ backup and replacement; if it detects a concurrent edit, it refuses with `deskto Review the edit and reapply. If restoring the profile also fails after a metadata error, the reported reason includes both failures; reconcile the profile and metadata before retrying. +#### Choose which models Claude Desktop lists + +**Connect → Claude Desktop → Desktop model list** has a checkbox for each model. Search by name or +filter by provider, then use **Select all matching** or **Clear all matching** to change every match, +including rows behind **Show more**. Click +**Save & apply** to write the list to Desktop. Only Claude Desktop's list changes: provider model +settings, Claude Code, Codex and other clients keep every model. + +**Newly discovered models** sets what happens when a provider later adds a model. **List +automatically** adds it to Desktop. **Keep hidden until selected** leaves it out until you check it. +The selection is saved in `claudeCode.desktopModelVisibility` and survives catalog refreshes and +reapplies. Tier families under **Advanced** stay optional and do not affect which models are shown. +A hidden model keeps its Desktop id, so a conversation that is already using it keeps working. + +The card shows the selected, available and applied counts separately. A selected model that is no +longer available is counted on its own and is not written. If the selection leaves no available +models, the writer falls back to every available model, including normally hidden routes. Update +the selection and apply again to narrow it. Before you apply, the card previews the model IDs the +selected profile file will gain and lose. Its applied count reads that file; it does not verify +which models the Desktop process has loaded. The status bar shows **Saved — apply to update Desktop** +until the saved list reaches the profile. Restart Desktop to load profile changes. +Applying replaces the model list in OpenCodex's Desktop profile, +including a list edited there by hand. Discovery-only mode (`--discovery-only`) writes no list, so +it does not use this selection. The dashboard will not save a selection that hides every +available model. + ### First-party (opt-in) :::caution[Account risk] @@ -399,6 +463,8 @@ applies to it as well. Desktop and CLI catalog rewrites share bounded row and me if adding routed models would exceed a limit, OpenCodex returns the original Anthropic catalog unchanged rather than publishing a partial list. +Before the first upstream response, a picker upload that makes no progress for 60 seconds is closed. An expired upload fails without a success response; HTTP/2 resets only the affected stream. This idle timer pauses when the upstream applies backpressure and is removed when the upload completes or the upstream first responds. This idle guard adds no overall upload-duration limit; existing runtime and protocol limits remain in effect. Response streams are excluded from this timer. + ### Use opencodex models from the Desktop Code tab (first-party bindings) In first-party mode the Code tab's model picker belongs to claude.ai: its rows (Opus 5.5, @@ -576,6 +642,20 @@ The one change to the body is tool-call ids. A `tool_use.id` or `tool_result.too Disable with `claudeCode.nativePassthrough: false`; point elsewhere with `claudeCode.anthropicBaseUrl`. +**Rate limits on passthrough.** A passthrough request uses the credential the caller sent, so it is +subject to that login's limits. When the login answers 429, OpenCodex returns the 429 with its +rate-limit and `Retry-After` headers; it does not resend a request authenticated with your credential +through another provider or account. +Claude Code sends some requests on its small-fast model, such as WebSearch on `claude-haiku-5-5`, +so those can fail on a rate-limited login while routed main turns keep working. To move that traffic +to a managed provider, map the model id with `claudeCode.intercept.modelMap` (or +`ocx claude desktop bind`) for first-party Desktop and CLI traffic, or `claudeCode.modelMap` for every +entry point. A mapped id no longer resolves to itself, so the passthrough condition above is not met +and the request is routed like any other. In `ocx claude` sessions, `claudeCode.tierModels.haiku` can +instead make Claude Code request a routed model id for that slot; a plain `claude-*` id there still +passes through, and an `ANTHROPIC_DEFAULT_HAIKU_MODEL` you export yourself wins +([#7912](https://github.com/lidge-jun/opencodex/issues/7912)). + ## Claude Desktop on a connected remote hub When this machine is connected to a hub, `ocx claude desktop apply` (or `ocx claude desktop`) @@ -672,6 +752,10 @@ Models with a long context window (1M, or at least the 829,800-token default com Claude models on an Anthropic route need a genuine 1M) get an extra `…[1m]` picker row: selecting it makes Claude Code account a full 1M context for that model (auto-compaction stays on) — the proxy strips the marker before routing. +Fast-eligible native OpenAI models also get a `…--fast[1m]` row labelled `· Fast · 1M` +when they meet the same long-context rule. This combines the native Fast tier with Claude +Code's long-context accounting; it does not raise the upstream input limit. The row keeps +the native model's input ceiling and the existing auto-compaction policy. Selecting one persists it to Claude Code's `settings.json` `model` field; inbound requests resolve the alias back to the routed model. On older Claude Code versions the picker stays native — set slots via @@ -743,20 +827,18 @@ upstream input limit. A classified input-limit rejection reaches Claude Code as compacts the conversation and retries on its own; a non-streaming response uses HTTP 400 instead of a retryable 502. Providers on the native Messages lane get the same wording. -Overflow normalization uses only the first **65,536 UTF-16 code units** of the provider's error -message, including messages that already use Anthropic's wording. This is a string-length limit, -not a byte or token limit. Text beyond it is discarded without an ellipsis or truncation marker, -so diagnostic details and token counts near the end may be absent from the error Claude Code -receives. The added `prompt is too long:` prefix, followed by a space, can make the final message -longer than this retained portion. - -Within that portion, recognized Anthropic wording is kept; otherwise OpenCodex emits -`prompt is too long: tokens > maximum` only when it finds -`maximum context length is tokens` followed by `resulted in tokens` or -`you requested tokens`. It uses the first stated limit and the first matching request -count after it. If that pair is missing, reversed, or cut off, it prefixes the retained text with -`prompt is too long:` followed by a space, without inventing counts. A throughput limit that only mentions tokens -(for example "too many tokens per minute") keeps its text and is not treated as an overflow. +Messages error-response normalization uses fixed proxy-written wording. A recognized context +rejection uses `prompt is too long: The request exceeds the model's context window.` instead of +provider prose or token counts. Throughput errors keep a separate fixed rate-limit sentence. + +On native and caller-forward Messages streams, only blocks whose first non-comment field is +exactly `event:error` or `event: error` have their error data normalized. The full diagnostic within +the 1 MiB error hold determines recovery wording. Above that bound, the stream emits +`The provider stream reported an error.` without a compaction phrase (OVERSIZE-1M), preserving its +issued HTTP status. Separately, native non-stream folds of collected error events return 502 where +an untyped proxy-built error envelope previously returned 200 (FOLD-502). See the +[Messages format contract](/reference/proxy-formats/#post-v1messages-and-count_tokens) for field +ordering, rename replay and the scope of these two exceptions. If compaction itself still exceeds the limit, preserve the original history and try compacting a fork with fewer enabled tool or MCP schemas, if your client supports @@ -818,6 +900,11 @@ Proxy startup/ensure, `ocx claude`, and relevant dashboard saves sync your featu overwritten or pruned; your own agents are never touched. - Files are atomically synced per file (write + rename). - `enabled: false` or `injectAgents: false` prunes all verified-owned definitions. +- Turning Claude Code off with the dashboard's integration toggle also prunes them right away + (best effort), so a native `claude` session started afterwards stops seeing proxy-only agents. + A file that cannot be deleted stays, and while a sibling OpenCodex instance owns + `~/.claude/agents` nothing is touched; turning it off again retries and also removes + definitions an older version left behind. - Successful CLI first-party saves and persisted Desktop first-party setup also attempt best-effort roster sync, including repeated setup to repair missing definitions. Refused setup and rollback do not sync agents. Turning first-party off alone does not disable agent registration. @@ -960,9 +1047,9 @@ The proxy translates every Anthropic Messages API request into the Codex Respons | Assistant text | `output_text` | | Assistant `tool_use` | `function_call` (`input` → JSON-stringified `arguments`) | | User `tool_result` | `function_call_output` (`is_error` → `[tool error]` prefix) | -| `tool_reference` in a tool result | Text `Tool loaded: ` in the paired result; preserves loaded-tool names without adding declarations or enabling translated server-side deferral | +| `tool_reference` in a tool result | Text `Tool loaded: ` in the paired result by default. The [append-only opt-in](#preserve-cache-prefixes-when-client-tools-load) may place a currently declared deferred function at its successful client discovery result on an eligible final Responses route; a reference alone never grants a tool or enables server-side search | | `thinking` / `redacted_thinking` replay | `reasoning` items with bounded `ocxr1` envelopes for signatures and redacted payloads | -| Function tools | `{type: "function"}` (`web_search*` → `{type: "web_search"}`). On a route to `api.anthropic.com`, the typed `web_search_*` and `web_fetch_*` declarations are also sent to Anthropic as declared and run server-side, unless the web-search sidecar supplies `web_search` itself. A search or fetch with a matching call and complete input comes back to the client as its `server_tool_use` block and its `web_search_tool_result` or `web_fetch_tool_result`, verbatim. Orphan results are dropped without synthesizing a call, while the surrounding text is preserved. When the client sends a complete pair back in its history, the next `api.anthropic.com` request carries it in place only if the following block uniquely identifies its original turn. Repeated anchors, unmatched or duplicate call/result ids, malformed call input, or a result appearing before its call drop the exchange. Call input must be an object with a nonempty search query or fetch URL string; other destinations never see the exchange | +| Function tools | `{type: "function"}` (`web_search*` → `{type: "web_search"}`). On a route to `api.anthropic.com`, the typed `web_search_*` and `web_fetch_*` declarations are also sent to Anthropic as declared and run server-side, unless the web-search sidecar supplies `web_search` itself. A search or fetch with a matching call and complete input comes back to the client as its `server_tool_use` block and its `web_search_tool_result` or `web_fetch_tool_result`, verbatim. Orphan results are dropped without synthesizing a call, while the surrounding text is preserved. When the client sends a complete pair back in its history, the next `api.anthropic.com` request carries it in place only if the following block uniquely identifies its original turn. Repeated anchors, unmatched or duplicate call/result ids, malformed call input, or a result appearing before its call drop the exchange. Call input must be an object with a nonempty search query or fetch URL string; other destinations never see the exchange Hosted search with `allowed_domains`, `blocked_domains` or `user_location` is omitted on translated Responses/Chat routes; forcing omitted search returns 400. Valid `defer_loading` function definitions remain callable as ordinary functions. See [translation limits](#search-restrictions-and-deferred-tools-on-translated-routes). | | `tool_choice` | `auto`→`auto`, `none`→`none`, `any`→`required`, named function→`{type:"function",name}`, hosted WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | @@ -975,6 +1062,23 @@ Replay preserves non-hidden signed blocks (including empty thinking) and opaque role; `tool_result` without `tool_use_id`; `tool_use` without id/name; named `tool_choice` without name. +### Search restrictions and deferred tools on translated routes + +When a `web_search*` tool supplies `allowed_domains`, `blocked_domains` or `user_location`, +OpenCodex omits hosted search from the translated Responses/Chat catalog, including combo +fallbacks and search sidecars. Those destinations cannot uniformly preserve the constraints; +search is never silently widened. Duplicate search declarations cannot bypass this rule. +A forced hosted-search choice with no surviving declaration returns HTTP 400. +First-party Anthropic destinations still receive the original typed declarations through the +existing server-tool lane when translation proceeds; native passthrough preserves them directly. +Unrestricted translated search remains available under the existing sidecar and admission rules. + +Valid function definitions with `defer_loading: true` remain callable as ordinary functions on +translated combo routes. This eager-loading degradation does not itself cause compatibility +rejection. Enforce mode still rejects unsupported top-level deferral, schema-less deferred tools, +server-executed discovery and unsupported discovery history. Eligible direct Responses routes +can use the [append-only opt-in](#preserve-cache-prefixes-when-client-tools-load). + ### Unicode-property patterns in tool schemas A JSON Schema `pattern` written for JavaScript may use Unicode property escapes such as @@ -1027,7 +1131,7 @@ on the schema to reject a malformed argument. **Error taxonomy:** 400 `invalid_request_error`, 401 `authentication_error`, 402 `billing_error`, 403 `permission_error`, 404 `not_found_error`, 409 `conflict_error`, 413 `request_too_large`, 429 `rate_limit_error`, 504 `timeout_error`, 529 `overloaded_error`, -other 5xx `api_error`. `Retry-After` is preserved. +other 5xx `api_error`. `Retry-After` is sent as whole seconds (an HTTP date becomes the remaining seconds), capped at eight days. ## Prompt caching and token usage @@ -1035,9 +1139,16 @@ other 5xx `api_error`. `Retry-After` is preserved. and the penultimate user message, plus top-level automatic `cache_control`. Stable turns normally produce about a 99.9% cache hit rate. -**Native OpenAI/ChatGPT routing:** derives a session-scoped `prompt_cache_key` (from -`metadata.user_id` when present, falling back to a system-content hash) and `session_id` header -for cache affinity. The cache key includes model and full tool schemas. +**Native OpenAI/ChatGPT routing:** derives a `prompt_cache_key` for cache affinity, and a +`session_id` header only from a session identity, never from the shared fallback key. When +`metadata.user_id` is a string, the key is session-scoped. Remote Claude Code puts a JSON object in +that string and adds a per-turn attribution token (`tk`) to it; when the object has other keys, +`tk` is dropped before hashing, so every turn of one session keeps one cache key and one +conversation id. Any other string (not JSON, a JSON array, or a JSON object holding only `tk`) is +hashed unchanged, and the `user` field is still derived from the raw string. Without a string +`metadata.user_id`, and when system content is present, the key falls back to a hash of the +resolved model, system prompt and full tool schemas: a cohort key shared by requests with the same +values, not a session key. **Token math:** Anthropic output subtracts `cached_tokens` and `cache_write_tokens` from `input_tokens`, exposing them as `cache_read_input_tokens` and `cache_creation_input_tokens`. @@ -1084,12 +1195,27 @@ gateway (default) or first-party, with the running proxy port in first-party mod **Save & apply** switches modes; **Save** alone stores the gateway profile lanes for a later gateway apply and leaves the current mode as is. +A model whose route is no longer in the catalog stays in the profile and shows **Unavailable**, +because a provider that is only briefly offline reads the same way. **Remove unavailable (N)** above +the model list, or **Remove** in an unavailable row of the Advanced lanes, drops those assignments +and their aliases from the page. A family whose default was removed falls to its first available +model; when none is left, the family's other unavailable models are removed with it, because a +family's default must be available, and the row says so before you click. Nothing changes until **Save** (or **Save & apply** to rewrite Claude Desktop's list), and +nothing is ever removed automatically. + `GET /api/claude-code` returns effective defaults, config, context-window registry, effective env, available route ids, aliases, and port. `PUT /api/claude-code` is partial and preserves omitted fields; `null` resets context/blocklist/compact-window values. ## Troubleshooting +### Windows Desktop apply reports `client_lifecycle_lock_failed` + +Update OpenCodex if Desktop apply stalls while many old lock files are present. Lifecycle acquisition +now verifies an already-private runtime directory before repeating its permission changes. It still +refuses apply when required permission hardening fails. Keep the existing runtime lock files in place; +removing them while clients are running can break coordination between processes. + **Claude Code says "Did 0 searches"** — Current builds translate completed Responses `web_search_call` items into paired Anthropic `server_tool_use` and `web_search_tool_result` blocks, including `usage.server_tool_use.web_search_requests`. Update opencodex if an older build completed @@ -1119,24 +1245,43 @@ window may be below the fixed 829,800-token floor. on Claude model mentions. This is normal for native passthrough; on routed models, opencodex stubs it by default (`blockedSkills: ["claude-api"]`). -**MCP tool schemas fill the context on turn one** — Claude Code turns MCP tool deferral off -whenever `ANTHROPIC_BASE_URL` is not a first-party Anthropic host. The check is keyed on the -host, not the model, so it applies to every `ocx claude` session: with many connectors -configured, every tool schema is inlined before you type anything. Re-enable deferral with: +**MCP tool schemas fill the context on turn one** — Whether Claude Code defers MCP tools behind a +gateway depends on its version. From v2.1.304, tool search is on by default when +`ANTHROPIC_BASE_URL` points to a gateway, which includes every `ocx claude` session, so MCP tools +are deferred and loaded through `ToolSearch`. Earlier versions turn deferral off behind a gateway +and inline every tool schema before you type anything. On those versions, re-enable it with: ```json { "claudeCode": { "toolSearch": true } } ``` -This is off by default because it only pays off on **native Anthropic passthrough** routes. -Deferral is a server-side optimisation, not a smaller request: Claude Code still sends every -tool definition, and Anthropic's API is what keeps deferred schemas out of the model's context -and answers the `tool_search` server tool with `tool_reference` blocks. A translated (routed) -model never reaches that machinery — opencodex drops the `tool_search` tool and ignores -`defer_loading` — so the provider still receives every schema while Claude Code stops counting -them and therefore stops compacting. With `claudeCode.compatibility: "enforce"` the same -request is rejected with 400 instead. Turn it on when `ocx claude` is routed to an Anthropic -model; leave it off for third-party routes until translated deferral is supported. +`ocx claude` injects `ENABLE_TOOL_SEARCH` only when `claudeCode.toolSearch` is set to an enabling +value; with the setting unset, the client's own default applies. `toolSearch: false` injects nothing, +so it does not turn tool search off. On a translated Chat route (DeepSeek, GLM and +similar providers), each `ToolSearch` load changes the tool list and the system message, so the +next request re-reads most of the conversation instead of hitting the provider's prompt cache +([#7963](https://github.com/lidge-jun/opencodex/issues/7963)). To trade first-turn context for a +stable cache prefix there, export `ENABLE_TOOL_SEARCH=false` before running `ocx claude`; a value +you export yourself always wins. To keep tool search on and the prefix stable instead, opt a +verified direct Chat route into [`claudeCode.chatToolDispatchModels`](#chat-routes). + +**Native Anthropic passthrough** preserves Anthropic's server-side +tool search: the client still sends deferred definitions, and Anthropic keeps them out of the +model context until discovery. The default translated path does not implement that server tool; +it drops the typed search declaration and ordinarily sends function schemas eagerly, which can +make the client's context accounting undercount the provider's input. + +There is a separate, narrow exception for **client-executed `ToolSearch`** on a verified Responses +destination selected by [`claudeCode.appendOnlyToolLoadingModels`](#preserve-cache-prefixes-when-client-tools-load), +or on a verified Chat destination selected by [`claudeCode.chatToolDispatchModels`](#chat-routes). +For that final physical route, the opt-in keeps unused deferred definitions out of the initial +catalog and adds current definitions at successful structured discovery results. Client-side +search must already work and an eager `ToolSearch` function must be declared. The launcher +`toolSearch` setting can enable client discovery where the client supports it, but does not by +itself activate the opt-in or provide server-side search. Verify this client-and-gateway combination +before enabling it; leave it off on other third-party routes. Compatibility-enforcement admission +is unchanged and can still reject unsupported deferral requests. Neither setting guarantees +cache hits or full native-tool-search parity. Accepted values follow Claude Code's own parser: `true`, `"auto"`, `"auto:N"` (N at least 100) and `"force"`. A value you export yourself always wins over the injected one. @@ -1161,6 +1306,123 @@ reuse still requires stable session identity and upstream cache availability. Changes to earlier instructions or tools, and conversation compaction, can still affect cache hits; preserving reminder order alone does not guarantee reuse. +### Preserve cache prefixes when client tools load + +For a **direct Responses route verified to accept `additional_tools`**, an opt-in can preserve +client ToolSearch loading history instead of adding each discovered function to the initial +catalog: + +```json +{ + "claudeCode": { + "appendOnlyToolLoadingModels": ["my-gateway/gpt-example"] + } +} +``` + +Selectors match resolved `provider/model` names, not picker aliases. A single trailing wildcard +such as `my-gateway/gpt-*` selects a verified model family; a global `*` is not accepted. The +list defaults to off, with a maximum of 128 entries of 512 characters each. Only a request whose +final physical route is a direct Responses provider gets the outbound rewrite. The destination +is checked again when the adapter is bound after a late subagent fallback or replacement; selecting +the original route does not authorize a different fallback. The request's original catalog remains +available to other attempts. A combo or policy request keeps the original catalog even when +selected, because its fallbacks may not keep the chronological placement. + +OpenCode Go's Responses endpoint and the official xAI Responses hosts keep the +original complete tool catalog even when selected. These destinations flatten or reject +`additional_tools`, so they cannot preserve this chronological loading prefix. Keep this opt-in +off for any other gateway that promotes discoveries to top-level `tools`. + +The optimization needs a string `metadata.user_id` and an eager declared `ToolSearch` function. +Unused deferred definitions stay out of the initial catalog before discovery as well as after it; +a successful structured ToolSearch result adds their currently declared definitions at that position. +It never grants tools from reference text or restores revoked definitions. Tools used before +being discovered and explicitly forced undiscovered tools remain in the initial catalog. Schemas, strictness and call/result pairing are +preserved. Missing metadata, absent/empty configuration, and native Anthropic passthrough keep +existing behavior. Malformed configuration is rejected on write; load recovery disables only +this optional setting rather than discarding providers. + +This is not server-side deferred-tool-search support and does not change compatibility-enforcement +admission or turn on tool search in the client. It applies when the client already discovers tools. +It does not guarantee cache hits: schema changes, revocations, model switches, compaction and +upstream cache availability can still require a new prefix. + +A Responses provider that accepts `additional_tools` but silently drops it is not verified for this +opt-in: the loaded definition never reaches the model. DeepSeek's official Responses API behaved this +way when measured on 2026-10-31. Use the Chat-route opt-in below for DeepSeek instead. + +#### Chat routes + +A Chat Completions route has no equivalent of `additional_tools`. On a translated Chat route, each +client ToolSearch load changes the tool catalog and the tool-name list in the system message, so the +next request misses the provider's prompt cache for the whole conversation. You can turn tool search +off with `ENABLE_TOOL_SEARCH=false` (see [MCP tool schemas fill the context](#troubleshooting)), or +keep it on and use a separate opt-in that keeps both stable for **direct Chat routes verified with +the models you use**: + +```json +{ + "claudeCode": { + "chatToolDispatchModels": ["deepseek/deepseek-flash"] + } +} +``` + +Selectors, limits, the metadata and eager `ToolSearch` prerequisites, and the combo, policy and +late-fallback rules are the same as for `appendOnlyToolLoadingModels`, applied to a final physical +route that is a direct `openai-chat` provider. On a selected route: + +- From the first request, the catalog carries one extra function, `use_loaded_tool`, and leaves + unused deferred tools out. Loading a tool changes neither the catalog nor the system message. +- A discovered tool's name, description and parameter schema are appended as text to the ToolSearch + result that loaded it. The model calls the tool through `use_loaded_tool` with + `{"name": ..., "arguments": {...}}`, and earlier calls are replayed in that same shape. +- opencodex rewrites every well-formed `use_loaded_tool` call to the tool it names before Claude + Code sees it, so Claude Code receives real tool names. A declared tool runs exactly as if the model + had called it directly, and a name Claude Code does not know is reported as an unknown tool under + that name. A malformed wrapper call, or one with extra keys, reaches Claude Code unchanged and fails + as an unknown tool. + +Limitations: the definitions are text, so provider-side strict schema enforcement does not apply to +them and an invalid argument costs a turn; the instruction sits inside a tool result, which some +models may not follow, so verify each model before selecting it. A request that forces a hidden tool, +restricts the allowed tools, or has an ambiguous history is sent unchanged. If a model calls a +deferred tool that ToolSearch has not loaded, directly or through `use_loaded_tool`, that tool +returns to the catalog and the cached prefix is lost once. Absent, empty or unlisted configuration +sends exactly the same request bytes as before. This does not guarantee cache hits either. Claude +Code receives a wrapper call's arguments when the call completes; that is how every tool call on a +translated Chat route arrives, so the option changes nothing there. + +#### Claude models behind a gateway that also serves GPT + +`appendOnlyToolLoadingModels` cannot fix Claude models that are routed through a Responses +gateway. Such a gateway can lift `additional_tools` back into Claude's initial `tools` array, and +Claude caches tools before the system prompt, so the request that loads a tool still misses. For a +key-authenticated gateway that also serves Anthropic Messages, send Claude models natively and keep +the other models on Responses with `modelAdapters`: + +```json +{ + "protocols": { "rollout": { "managedMessagesNative": true } }, + "providers": { + "my-gateway": { + "adapter": "anthropic", + "modelAdapters": { "gpt-example": "openai-responses" } + } + } +} +``` + +List every non-Claude model the provider serves in `modelAdapters`; an unlisted one would be sent +as Messages. Native Messages keep Claude Code's deferred tool definitions and `tool_reference` +results in place, so loading a tool adds to the cached prefix rather than replacing it. +`claudeCode.stabilizePromptCache` does not apply on that path and is not needed there; it still +helps any Claude request that stays on the bridge. Combos, policies, pinned efforts, synthetic +rows, the web-search sidecar and vision preprocessing keep requests on the bridge, as listed under +[rollout switches](/guides/protocol-paths/#rollout-switches). Third-party compatible providers do +not receive caller `anthropic-beta` values, so the gateway must accept these requests without them. + ### Intercept token recovery The running authenticated proxy validates the current token for each new CONNECT request. diff --git a/docs-site/src/content/docs/guides/codex-app-models.md b/docs-site/src/content/docs/guides/codex-app-models.md index 70fc8ccf02..2f5805d7b4 100644 --- a/docs-site/src/content/docs/guides/codex-app-models.md +++ b/docs-site/src/content/docs/guides/codex-app-models.md @@ -135,7 +135,7 @@ for the command, disable-key semantics, and safety constraints. ### What this means for a disabled native model -Without a native alias configured, disabling a bare native GPT slug does not remove it from the +By default, without a native alias configured, disabling a bare native GPT slug does not remove it from the catalog. The row stays with `visibility: "hide"`, which `/v1/models` and the dashboard both honour — they stop listing the model — while Desktop, under the policy above, can keep showing it. So the model can still be picked in Desktop after you disabled it, and the surfaces disagree about whether @@ -147,9 +147,13 @@ runs on the model you disabled, or fails on whatever path that id resolves to. E outcome is not the one the toggle implies. The row is retained deliberately. It holds the real upstream metadata, so re-enabling the model -restores that metadata instead of a synthesized guess. When you need the row gone outright rather -than hidden, configure a `nativeAlias` combo: while one exists, disabled bare native rows are -omitted from the effective catalog entirely. +restores that metadata instead of a synthesized guess. To omit disabled native rows without a +native alias, set `"omitDisabledNativeModels": true` in `config.json` and run `ocx sync`. +The option defaults off. Sync, the generated cache, and Codex-shaped HTTP discovery omit the +disabled rows while retaining a separately validated native inheritance template, so routed +rows keep their input and tool metadata even when the only template row was disabled. +Direct requests to a disabled native id still route normally. A `nativeAlias` combo also keeps +its existing omission behavior independently of this flag. If Codex's `config.toml` pins a root `model` that this proxy does not expose — a disabled model among them — every new session starts on a model opencodex does not serve. `ocx doctor` reports @@ -221,11 +225,12 @@ metadata instead of an older-template approximation. | Route | Picker ids and catalog metadata | | --- | --- | -| Codex login (account-qualified rows disabled) | Bare native ids such as `gpt-5.6-sol`, `gpt-5.6-terra`, and `gpt-5.6-luna`; Pool or Direct is selected through `codexAccountMode`. GPT-5.6 rows use a 922,000-token catalog window. | +| Codex login (account-qualified rows disabled) | Bare native ids such as `gpt-5.6-sol`, `gpt-5.6-terra`, and `gpt-5.6-luna`; Pool or Direct is selected through `codexAccountMode`. GPT-5.6 rows use a 922,000-token catalog window. `gpt-6.1-terra`: 500,000 default / 872,000 long context. | | Codex login (account-qualified rows enabled with eligible selectors) | One `/` row per eligible selector and supported native model; each row uses only its mapped account, and bare native rows are hidden from the picker. Native metadata and context windows are preserved. | | Codex login (explicit Daybreak forward row) | `openai/gpt-daybreak-blue-latest` only when the exact `customModels` row is configured on the canonical `openai` provider. It keeps the Daybreak wire id and uses the pinned Sol capability snapshot (922,000 context; 829,800 automatic compaction). | -| OpenAI (API key) | Exactly ten namespaced rows: `gpt-5.5`, `gpt-5.6`, Sol/Terra/Luna, the three `*-pro` virtual ids, and the two Daybreak aliases (1,050,000 context; 922,000 max input for all ten) | +| OpenAI (API key) | Namespaced models include `gpt-5.5`, `gpt-5.6`, Sol/Terra/Luna, the `*-pro` virtual ids and the Daybreak aliases (1,050,000 context; 922,000 max input). `openai-apikey/gpt-6.1-terra` adds 1,050,000 context and 128,000 max output. | | OpenRouter | `openrouter/openai/gpt-5.6-sol`, `openrouter/openai/gpt-5.6-terra`, `openrouter/openai/gpt-5.6-luna` (922,000) | +| OpenRouter | `openrouter/openai/gpt-6.1-terra` (1,050,000) | | Cursor | Static fallback includes `cursor/gpt-5.6-sol`, `cursor/gpt-5.6-terra`, and `cursor/gpt-5.6-luna` (1,000,000), plus regular/Fast rows for Grok 4.5, 4.6, and 4.7 (500,000); 4.6 and 4.7 add `xhigh`, and live account discovery decides which rows remain visible. | | xAI | Live discovery is authoritative. The fallback catalog includes `xai/grok-4.6` and `xai/grok-4.7` and defaults to `xai/grok-4.5`; all three have 500,000-token windows. Grok 4.6 and 4.7 expose `low` / `medium` / `high` / `xhigh` (upstream default: `high`), while Grok 4.5 stops at `high`. | @@ -278,6 +283,12 @@ preserved, so Luna has `max` but no `ultra`. On the wire, routed adapters map or clamp unsupported tiers. For older native models whose real ladder stops at `xhigh`, `nativeEffortClamp` maps a direct `max` or an `ultra` selection to `xhigh` (for example, GPT-5.5). Sol, Terra, and Luna have a real `max` rung. +The ChatGPT backend itself accepts `none` through `max`, so a native ChatGPT request never forwards `ultra` as-is: +native models with a real `max` rung receive `max`, including Astra, GPT-6.1 Sol and GPT-6.1 Terra whose ladders +list `ultra`, while older models such as GPT-5.5 receive `xhigh` as above. This applies to +`/v1/responses` and `/v1/chat/completions` alike. The native clamp does not apply to routed model IDs: a routed +OpenAI Chat passthrough can copy a declared `reasoning_effort: "ultra"` to its provider unchanged, +while the ordinary translated adapter maps `ultra` to `max`. Catalog advertisement of the two top tiers is unconditional: `ocx sync` no longer removes `max` or `ultra` when the installed Codex binary is too old to offer them — Codex versions without those @@ -314,6 +325,45 @@ advertised where it cannot be honored. An `openai-chat` destination can authoriz eligible model with `chatServiceTier: true`, or authorize only exact models with `modelSupportsServiceTier`; Responses routes do not need that extra Chat wire authorization. +### Selecting Flex in Codex + +For a routed provider and model verified to accept `service_tier: "flex"`, explicitly +declare Flex support alongside the existing Fast wire. Merge these fields into the +**existing** `providers.nanogpt` entry (do not replace its URL or credentials): + +```json +{ + "modelSupportsServiceTier": { "openai/gpt-6-luna": true }, + "fastWire": { + "kind": "service-tier", + "canonicalToWire": { "priority": "priority", "flex": "flex" }, + "foreignCallerTiers": "verbatim" + } +} +``` + +With an eligible `openai-responses` route, the Luna row advertises Standard, +Fast and Flex in Codex's speed selector. For an `openai-chat` route, also set +`chatServiceTier: true` **only if** the upstream Chat Completions endpoint supports +caller-provided service tiers. The `fastWire` mapping is **provider-wide**: +other service-tier-eligible routed models in the same `providers.nanogpt` +entry can also advertise Flex when the catalog publishes them as ordinary routed +rows, even when they are not listed in `modelSupportsServiceTier`. That map is not +an allowlist excluding other eligible models. Combo-namespace and native-alias +rows are **not** published with Flex. Verify Flex support for **every** eligible +ordinary routed model; +if only Luna supports Flex, configure it in a separate provider entry with +no other Fast-eligible models. Do not infer Flex support from Fast alone. + +Keep OpenCodex's global Fast mode on **Auto** (`fastMode` unset), as forcing +Fast or Default overrides the caller's Flex choice. After `ocx sync`, refresh the +Codex model list. Select **Flex** from the speed selector, or use +`/model --speed=flex` in Codex CLI. This is a **selectable tier**, +not a per-model forced default: switching models does not force Flex automatically. +The tier is forwarded as `service_tier: "flex"` and can still be declined by +the upstream; availability, cost and latency depend on the provider. Neither +the menu nor a request alone proves which tier was billed. + ### Selecting Ultra Fast in Codex Desktop For a provider that supports `service_tier: "ultrafast"`, declare that wire mapping once. diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index c38a4685dd..58b68cd413 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -26,12 +26,39 @@ plus `openai-apikey/` for the configured API key. Pool includes main plus Direct uses only the caller/main bearer. The routes do not fall back to one another. Shipped v1 configs migrate to marker 2 and preserve `config.json.pre-openai-tiers-v2.bak` for manual restore. +When Pool selects an added account, OpenCodex replaces installation identifiers already present in +the request headers or client metadata with a stable identifier for that account and OpenCodex home. +Token refresh keeps the identifier; switching accounts changes it. Direct mode and the native main +account keep your original values. Missing installation metadata stays absent. OpenCodex does not +change Codex's own `installation_id` file when switching native profiles. If the local installation +secret cannot be read safely, the request returns a retryable 503 before reaching ChatGPT. +The same isolation covers authenticated live call sessions and subsequent realtime/sideband +WebSocket frames. Pool turn metadata above 32 KiB is refused before sending (503 for HTTP, +connection closure for WebSocket frames); Direct and native main values remain unchanged. + Within Pool mode, a request carrying a validated native Codex login can use that login when the selected stored account is cooling down and no eligible stored alternative or recovery probe is available. This also covers a new request blocked before sending, following the same caller validation used after an upstream rejection. Existing model-permission and main-account policy checks still apply. The fallback preserves the stored account's cooldown and does not persist the -caller credential as the Pool selection. An exact account binding remains bound to that account. +caller credential as the Pool selection. An exact account binding remains bound to that account. A manual Pool +pin is a preference, not an exact account binding: it can still use this fallback. Use an +account-qualified model when a request must remain on one account. Pausing the observed native +main blocks fallback for its matching caller credential; it does not identify or pause unrelated +caller-owned logins. + +Adding or reauthenticating a pool account rejects a duplicate of the native main login with +`Account is already configured as the native Codex main account.` The check compares ChatGPT +account ID, personal/workspace subscription bucket, and email; a missing email does not prove +a different identity. Different workspaces, distinct workspace members, and separate personal +and workspace subscriptions remain supported. A failed usage lookup does not discard the +subscription plan carried by the login token. + +Existing duplicates remain stored but cannot be selected as a second Pool account. The account +list exposes `selectionExcludedReason: "duplicate_main"` and an actionable `selectionExcludedAction`. Use native main explicitly, +or sign native Codex into a different account before reusing the stored entry. Detection follows +the latest owned native-login observation, including a later native relogin; passive account +listing and caller-owned requests do not open native credentials to refresh that observation. ## Config injection @@ -125,6 +152,17 @@ to restore the default upstream WebSocket selection. This setting does not chang client-facing `websockets` switch or the ChatGPT account used for the request. Native mid-turn steering and injection need upstream WebSocket and are unavailable while it is off. +**Reasoning usage metadata (2.90.0 and later).** For HTTP/SSE clients on the canonical +ChatGPT route, the upstream WebSocket relay preserves an actual `x-reasoning-included` +connection-response header when the Bun runtime exposes it, including on a reused connection. +This tells Codex that the server's reported usage already includes earlier reasoning. Metadata +sent before the first Responses event takes precedence; later metadata remains in the stream +but cannot change headers already committed. The relay does not invent this signal or alter +usage numbers. A missing upstream signal and Codex's own accounting lifecycle remain separate +issues, so this change alone does not establish that early compaction is fixed. Client-facing +WebSocket connections have already completed their upgrade before the upstream response and +cannot receive the signal retroactively as an upgrade header. + Local provider pacing can also hold a request before it is dispatched at all. So a slow first output has several possible contributors, and upstream queueing is only one of them. `ocx doctor` classifies configuration and measures none of these: compare actual transport, pacing, network, @@ -374,11 +412,25 @@ reference/fallback config. On loopback it contains the root keys you can merge m injection was removed; on non-loopback it contains the dedicated provider form. External-provider mode leaves this profile untouched. +Rebuilding that file keeps the plain root keys OpenCodex does not manage, so a setting you add such as +`stream_idle_timeout_ms` or `stream_max_retries` survives the next injection. Each kept assignment is +copied exactly as written, including values that span several lines and 64-bit integers, and is placed +above the first table. Keys inside tables and dotted root keys such as `a.b = 1` are not kept. +OpenCodex wins every collision: the root keys it owns (`model_provider`, `model_catalog_json`, +`openai_base_url`) are rewritten for the routing mode in use, and a root key named like a table the +profile writes, such as an inline `features = { ... }` when the profile writes `[features]`, is +dropped. If the file changes while an injection waits for the write lock, the injection stops with a +retryable error and leaves your edit in place. + :::caution Root keys such as `openai_base_url`, `model_provider`, and `model_catalog_json` **must** sit before the first `[table]` header. The injector guarantees that placement, removes its own stale/duplicate copies, and never overwrites a user-owned root `openai_base_url`; if one exists, sync updates the catalog but reports that routing was not injected. + +Sync and restore also leave a root `model_context_window` in place, since OpenCodex never writes +that key. Codex uses it instead of each model's catalog window, capped at that model's maximum +window, so delete it yourself if you want each model to report its own window. ::: ## Shared model catalog @@ -393,7 +445,15 @@ $CODEX_HOME/opencodex-catalog.json $CODEX_HOME/models_cache.json ``` -On macOS, opencodex checks the Codex app’s bundled CLI in `/Applications/ChatGPT.app` and then `~/Applications/ChatGPT.app` after explicit selections, shims, PATH, established installs, and the runnable bare `codex` fallback, requires the bundle’s XML `Info.plist` identity to be `com.openai.codex`, and never automatically replaces a runnable persisted selection with an app candidate. +On macOS, opencodex checks the Codex app’s bundled CLI in `/Applications/ChatGPT.app` and then `~/Applications/ChatGPT.app` after explicit selections, shims, PATH, established installs, and the runnable bare `codex` fallback, requires the bundle’s XML `Info.plist` identity to be `com.openai.codex`, and never automatically replaces a runnable persisted selection with an app candidate. When no Codex CLI is found at all, the catalog probe behind `ocx connect status` readiness also tries those bundled locations, so a Child whose only Codex is the app’s bundled CLI reports its reasoning levels instead of `unverified`; every execution still passes the checks below. + +Execution checks also recognize `Codex.app` and `ChatGPT.app` at any location, including relocated +bundles, explicit `CODEX_CLI_PATH` or configured runtime commands, and symlink aliases. A recognized +name triggers verification; it does not grant trust. Before each execution, the canonical bundle +and exact binary must pass strict signature verification with OpenAI's Team ID and the ownership, +permission and ancestor-directory policy. The binary must resolve inside the bundle's `Contents/` +(including `Codex.app/Contents/Resources/codex-aarch64-apple-darwin`); unresolved bundles or binaries +are refused. Arbitrary non-app CLIs and third-party app bundles keep their existing execution policy. On WSL, if `CODEX_HOME` is unset and the Linux `~/.codex` directory is absent or holds no Codex state (`config.toml`, `auth.json`, `sessions`, `history.jsonl`), opencodex also @@ -710,6 +770,12 @@ Codex. Native custom calls and converted function calls use the same completion patch previews are held while their executable form is unresolved. JavaScript that merely contains patch text and unrelated native custom payloads stay unchanged. +When a routed model double-wraps an executable freeform body, opencodex removes one extra +JSON object containing only an input string. This repair applies to local exec and apply_patch +bodies, leaves other tool grammars and ambiguous objects unchanged, and does not decode recursively. +A body holds its streamed preview only while it can still turn out to be such a wrapper; +JavaScript that merely starts with an object or block keeps streaming as it arrives. + A routed model can also mistakenly send a shell-argument object such as `{"cmd":"git status --short"}` to code-mode `exec`. For a verified code-mode catalog, opencodex converts an unambiguous shell object into `tools.exec_command(...)` JavaScript @@ -911,13 +977,41 @@ or remove it to disable capture. The file is owner-only (`0600`) in the hardened and rolls after 200 lines, retaining the newest 100. Each JSONL record contains the protocol, routed provider/model, cache-counter presence and -provenance, process-local equality tags for the account, prompt-cache key, and allowlisted session -headers, plus ordered fingerprints for instructions, tools, and message/input blocks. Prefix -sections retain at most 128 tags and identify only the first divergent section/index. The -diagnostic never stores prompt or message text, tool names, raw headers, raw cache/session/account -identifiers, or a durable tag derived from them. Its random HMAC key is created at process start, -separate from other debug keys, and is never persisted; tags therefore compare values only within -one proxy process. +provenance, and process-local equality tags for the account, prompt-cache key, session headers, +and ordered instruction/tool/message blocks. It never stores prompt or message text, tool names, +raw headers, or raw cache/session/account identifiers. The random HMAC key is separate from other +debug keys, created at process start and never persisted, so tags compare only within one process. + +- `session.inboundHeaders` and `outboundHeaders` record `session_id`, `session-id`, `thread-id`, + and `x-session-id` independently. Identical values have identical tags across these names and + directions. An unobserved side is omitted, distinct from observed absent headers. These headers + are diagnostic correlation inputs, not proof of account affinity. +- `accountAffinity` records a separately tagged key from the shared Codex conversation-identity + derivation for each observed header set. `derived-key-not-binding` means exactly that: a key + is not evidence that a binding was stored, selected, or reused. Reported route labels are separate. +- `prefix.comparison` compares the observed inbound and outbound projections. `continuation` + compares each side with the previous finalized request having the same complete nonempty inbound + session-header identity, authenticated caller scope, protocol, model, and config directory. The + caller scope comes from the authenticated admission captured before Chat/Messages bridging, not + from rewritten upstream headers. It is used only in private in-memory lookup keys, never serialized. + The same admitted key has the same scope across supported authentication headers; different keys + remain isolated. Without an authenticated admission identity (including unauthenticated loopback), + continuation comparisons are `uncomparable`; per-request inbound/outbound comparisons remain available. + Provider changes do not reset this + comparison; prompt-key and explicit account-label changes are reported separately. Outbound-only + session identifiers and prompt-cache keys never supply a missing correlation identity. +- Comparisons report `first`, `equal`, `append-only`, `different`, `truncated`, or `uncomparable`. + Only message-tail growth is append-only. Top-level instructions and system content precede tools; + input/message rows, including system/developer updates, stay in their original order. Missing + observations and unsupported shapes are uncomparable, never assumed equal to an empty prefix. +- Each section retains at most 128 tags. An unobserved common tail reports `truncated`, not equality + or an exact first divergence. At most 512 recent correlation histories are retained in memory; + an evicted history is `first` on its next observation. + +These are parsed-body observations at existing request hooks, not captured network bytes or proof +of upstream cache reuse. Concurrent requests compare in finalization order, not send order. The +switch changes diagnostics only, not affinity selection or cache behavior; the existing debug-mode +bridge requirement for otherwise eligible direct Chat/Messages lanes still applies. ### Catalog troubleshooting @@ -984,6 +1078,28 @@ has reached Codex the turn is never sent again. If every attempt is declined, Co the same error it would have received without the retries. Native compact requests move to another Pool account on a server error in the same way. +### Runtime agent instances (Codex 0.164+) + +Codex 0.164 can sign each request with a runtime agent assertion when +`features.runtime_agent_instances` is enabled (it is off by default). opencodex supports one of +its two modes: + +- `mode = "dual_header"` keeps the normal `Authorization: Bearer` credential and adds an + `x-openai-agent-assertion` header. opencodex treats the request exactly as before. The assertion + is forwarded only when the turn goes to ChatGPT Direct with your own credential. It is removed + when a Pool account, a stored main credential, a routed provider, or a sidecar serves the request, + because it belongs to the credential Codex sent. +- `mode = "assertion_only"` replaces the bearer with `Authorization: AgentAssertion `. + opencodex refuses these requests with HTTP 400 and error code `agent_assertion_unsupported`. + It never substitutes a Pool or provider credential for the assertion, and it never forwards or + logs the assertion. Use `dual_header`, or turn the feature off, when Codex runs through opencodex. + +### Launch with `ocx codex` + +The key is supplied only when the configuration and its namespaces are protected from other principals; the current user and privileged OS authorities are trusted. Same-user processes are trusted: an actor with your write access can already read your OpenCodex key file. Same-user configuration replacement between verification and native startup is outside this threat model; the launcher does not freeze configuration at handoff. + +On Windows, default ProgramData creation rights withhold the key even when `ProgramData\OpenAI\Codex` is absent. The system Codex configuration folder under ProgramData must exist and be writable only by Administrators/SYSTEM, with its ancestors protected against replacement by other users. Ask an administrator to review the directory policy. opencodex never changes ACLs itself and provides no provisioning command. Alternatively, supply your own key by exporting `OPENCODEX_API_AUTH_TOKEN`; `ocx codex` leaves it untouched. See [launcher requirements and diagnostics](/reference/cli/agents/#ocx-codex-codex-args). Other refusals also produce one short specific stderr line without key values, key-file contents or key-file paths. + ### Codex autostart shim Run `ocx codex-shim install` to install the optional launcher wrapper. It runs @@ -1230,6 +1346,8 @@ An allowed response with primary and secondary windows can omit the optional ter This recovery uses your included plan allowance and does not require enabling **Use credits**. Partial or invalid usage data retains the previous block until recovery is confirmed. +Stored accounts with **Use credits after limit** enabled renew their credit evidence on the existing background cycle once an included usage window is exhausted and the credit observation is at least three minutes old. In **Direct** mode this also covers stored accounts explicitly bound in `codexAccountNamespaces`, such as a sub-account selector. You can keep Direct mode and separate main/sub identities; this does not enable Pool routing or refresh unbound accounts. Paused and reauthentication-required accounts are skipped. Metadata reads do not validate pending accounts or send model requests. Failed reads retain backoff and requests still need fresh spendable credits; ordinary response usage headers do not renew the credit balance timestamp. + ### Cancelling main-account device reauthentication When cancelling main-account device reauthentication, a temporary DELETE or network failure, or a response with an unknown or nonterminal status, keeps the active flow and the cancellation-failure indication so cancellation can be retried. Status polling normally continues so a login that completes can still be detected. If a retryable cancellation failure overlaps a non-2xx GET status response while the flow is `pending` or `committing`, either response order preserves cancellation retry on that same flow, with its last server-provided device code, verification URL, and phase. The GET HTTP failure still stops polling, but cancellation can be retried without starting a second login POST. A terminal `failed` response releases the flow and displays the normalized failure reason; only `succeeded` reports login success. A confirmed `cancelled` response releases the flow so a new device login can be started. A definitive HTTP 404 response with code `unknown_flow` also releases the expired flow ID so a new device login can be started, but does not report a successful login or confirmed cancellation. Late POST, GET, or DELETE responses from an earlier flow cannot change the new flow or report login success for it. @@ -1240,6 +1358,23 @@ When an account leaves pool selection, the reason travels with the decision inst A main-account refresh that does not complete still answers `503` with `Retry-After`, because a retry may still succeed. The message now adds that a failure which persists means the main account needs reauthentication, rather than only asking for another attempt. +### Request-owned conversation affinity + +`codexPool.requestOwnedAffinity` is an optional boolean, defaulting to `false`. Set it to `true` +to keep a conversation carrying its own ChatGPT bearer on one eligible account within each quota +scope. Releases and model detours can still move it. The binding is process-local; restarting the +proxy or rotating the bearer starts a new binding. Session-less multi-generation subagent chains +may bind per thread. + +Affinity labels describe the binding when selection returns. `unbound` means no binding was stored; +`request_owned` means the caller-owned credential did not opt in, and `no_conversation` means no +conversation key was available. A later eligibility change can release a binding after selection. + +With or without the option, a request that carries its own bearer records which account served each +turn under a key scoped to that bearer. When a later turn is served by a different account, including +after you switch accounts manually, OpenCodex removes `previous_response_id` before sending and +rejects carried uploaded `file_id` references with HTTP 400, because the new account cannot read them. + ### Optional idle-window steering `codexPool.startIdleWindows` is an optional boolean and defaults to `false`. When enabled, a new diff --git a/docs-site/src/content/docs/guides/codex-prompt.md b/docs-site/src/content/docs/guides/codex-prompt.md index 75610d3a24..5ecd7f46cd 100644 --- a/docs-site/src/content/docs/guides/codex-prompt.md +++ b/docs-site/src/content/docs/guides/codex-prompt.md @@ -36,6 +36,12 @@ unavailable, which is not the case. Click a layer name to see the text it sends. The dialog reads it from `codex debug prompt-input`, so it is the real thing rather than a description. +The read has one fixed 15-second caller budget, including time spent +reading metadata and waiting on a shared probe. Synchronous metadata reads finish +before expiry can be checked; an exhausted budget then prevents a new probe. +If it expires, the dialog reports that the prompt +could not be read; locally available base instructions are still returned. + Sometimes there is nothing to show, and the dialog says which reason applies: - **The file exists but is empty.** Your `~/.codex/AGENTS.md` is zero bytes, so diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index 5f38d243f6..09273ba7d6 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -24,7 +24,7 @@ Mark a pay-per-use combo target with `"metered": true` when it follows subscript Request headers cannot grant consent. Model/provider scopes still apply. This covers initial selection, failover and recovery across combo strategies, compaction, Messages, Chat Completions and WebSocket requests, and a subagent model fallback naming a combo alias. A collapsed fallback tries a usable unmetered target before refusing. Unmarked targets retain existing behavior; metering is declared by the operator rather than detected automatically. -For example, a failover chain can target Anthropic OAuth, then Cursor, then `{ "provider": "anthropic-apikey", "model": "claude-opus-5-5", "metered": true }`. Without consent, exhaustion returns the last unmetered error, with one exception: an earlier 429 or 402 quota refusal takes precedence over a later 400, 401 or 403. If the subscription target returns 429 and Cursor then refuses with 401 or 403, the caller receives the subscription's 429, because the spent subscription explains the failure and Cursor's credential refusal does not. Dashboard saves retain omitted target metering and combo consent; explicitly setting either to false clears it. These consent fields are configured through the config file or API; the combo flag is also available through the CLI, while the dashboard does not expose it. +For example, a failover chain can target Anthropic OAuth, then Cursor, then `{ "provider": "anthropic-apikey", "model": "claude-opus-5-5", "metered": true }`. Without consent, exhaustion returns the last unmetered error, with exceptions for [confirmed context overflow](#context-window-refusals) and quota refusals: an earlier 429 or 402 quota refusal takes precedence over a later 400, 401 or 403. If the subscription target returns 429 and Cursor then refuses with 401 or 403, the caller receives the subscription's 429, because the spent subscription explains the failure and Cursor's credential refusal does not. Dashboard saves retain omitted target metering and combo consent; explicitly setting either to false clears it. These consent fields are configured through the config file or API; the combo flag is also available through the CLI, while the dashboard does not expose it. ## 60-second quickstart @@ -152,6 +152,13 @@ native routing and catalog identity on the next sync. ### Failover: ordered primary and backups +For Responses requests that require a tool, Meta Responses targets are skipped before sending +because Meta does not support mandatory `tool_choice`. An eligible later target receives the +original choice, subject to its existing adapter compatibility rules. This includes hosted choices +such as `web_search`, `tool_search`, `computer_use` and `image_gen`, and MCP choices with a +nonempty `server_label` and an omitted, null or nonempty name, including inside required allowed-tools lists. Chat translation preserves a forced `tool_search` as the synthetic function choice. If every target is incompatible for this reason, +the combo reports the constraint. Chat targets that cannot preserve a mandatory selector, including models configured for auto-only tool choice, are also skipped before sending. Registered OpenAI API virtual models use the actual wire model's adapter and tool-choice policy for this decision. Malformed or unknown choices retain the provider's ordinary error path. + `failover` selects the first eligible target in configuration order. A target is eligible when its provider exists, is enabled, is not cooling down, and can handle any special request constraint. Weights and `stickyLimit` do not affect this strategy. @@ -166,6 +173,22 @@ each request starts with Anthropic. A retryable Anthropic failure moves that req retryable OpenAI failure can move it to Google. A terminal error stops immediately instead of trying the remaining targets. +A provider's HTTP 400 response can still be target-specific. OpenRouter's opaque provider wrapper +(`Provider returned error` with numeric `code: 400`, no `type`, and `metadata.raw: "ERROR"`) is +treated as target-local and allows the combo to try the next target without cooling the failed one. +Typed uncoded 400s, known malformed `response_format` schema errors, and an envelope whose root +states its own terminal code remain terminal; a root that states a hop signal of its own +(`model_not_found`, `insufficient_quota`, `usage_limit_exceeded`, `free_rate_limited`, +`input_admission_refused` or `unsupported_input_modality`) adds no new verdict, and an empty +code is treated as no code. Recognized target incompatibilities described later in this guide +still advance. + +A streamed error event that carries no status of its own but an integral numeric `code` between +400 and 599 is judged with that code as its HTTP status, so it gets the same decision and cooldown +as the matching HTTP response. Before output starts, a generic streamed 400, 409, 413 or 422 therefore +stops the combo as it does over HTTP, a 401, 402 or 403 cools the provider, and a recognized context +overflow still advances. + ### Round-robin: smooth weighted batches `round-robin` uses smooth weighted round-robin. A larger target weight gives that target a larger @@ -251,6 +274,13 @@ without separately attributable bars remain unknown. Active-account summaries, m display reports, credits and API/Spark/USD meters are not quota evidence for this decision. The separate Anthropic · Pool 2 (`anthropic2`) account pool is not a source of this evidence, so its targets stay unknown. +Antigravity contributes Gem/Cla five-hour and weekly buckets only after a fresh authenticated probe +for its sole active, usable OAuth account, and only to the `google-antigravity` provider that signs in +with that account. A renamed provider row reads unknown and never reuses that account's quota. Quota +follows the resolved native `gemini-*` or `claude-*` model, not its display alias. Account, credential, project or destination +changes withdraw the old observation. A display-only refresh can retain matching family counters +only with their original timestamps; per-model and Argon rows never become decision evidence. + :::caution[Additional decision data] Opting in sends quota tiers, and available used percentage/window/reset delay, to your selected decision backend, including hosted TypeSafe. No account ids, tokens or credential fingerprints @@ -265,6 +295,61 @@ API `false` disables the switch. Omitted fields survive JEV updates, target repl rename, including saves through the existing editor. Switching away from JEV removes both quota settings. No new editor controls or background quota work are enabled. +### Session pin for JEV + +A JEV Combo decides a target for every request, so consecutive turns of one conversation can move +between providers, and each move starts with a cold provider prompt cache. `sessionPin` is an +opt-in setting per JEV Combo, off by default, that keeps a client session on the target JEV chose +for it while the session stays active: + +In the dashboard, open the JEV Combo editor's **Decision method** section and enable +**Keep a session on its decided target**, then set **Idle window (ms)** and save. The range is +60000–86400000 ms (1 minute–24 hours); newly enabled pins start at 60000 ms. Disable the checkbox +and save to turn pinning off. Invalid or empty enabled windows block saving; failed saves keep +your edits for retry. Older responses without this setting leave it omitted until you change it. + +```bash +ocx combo set jev-auto --session-pin 20m --json +``` + +```json +{ "strategy": "jev", "sessionPin": { "ttlMs": 1200000 } } +``` + +The first request of a session is decided normally. Once the target JEV applied for it completes a +response, later requests of the same session reuse that target and effort without another decision +call. `ttlMs` (1 minute to 24 hours) is an idle window: every completed turn on the pinned target, +tool-call continuations included, starts it again, and a session that stays quiet longer is decided +afresh. + +A session is identified by the client's own session headers (`thread-id`, `session_id` or +`session-id`, `x-codex-parent-thread-id`, or a promoted `x-session-id`) together with the API key +that admitted the request and the Combo. Requests without a session header are never pinned, +`prompt_cache_key` is never used as a session identity, and two API keys never share a pin. + +JEV decides again, and the new decision replaces the pin, when: + +- the pinned target is not offered for this request: disabled, removed from the Combo, cooling + down after a 429 or another failure, out of cached quota, metered, or otherwise ineligible; +- the pinned effort is no longer offered for that target; +- `decisionQuotaSignals` is on and the target's quota evidence reads nearly exhausted; +- any send of a pinned session fails (that request still fails over as usual); +- the configuration has changed since the pin was written. + +A cancelled request keeps the pin. A fail-open decision (timeout, missing key, invalid answer) +never creates one. Pins live in the proxy's memory, at most 512 sessions, and do not survive a +restart. + +Usage records mark a reused turn with `jevDecision.pinned: true` and `pinReason: "session"`. A +decision that replaced a released pin records why in `pinReason` (`expired`, `config_changed`, +`target_unavailable`, `effort_unavailable` or `quota_nearly_exhausted`). `ocx combo stats` +counts pinned requests apart from decisions; they still count toward successful requests, model +fallbacks and per-model tokens. + +A pin makes provider cache reuse possible; whether the provider actually serves cached tokens still +depends on the provider, the account and a stable prompt prefix. `--session-pin -` (API `null`) +turns it off, switching away from JEV removes it, and saves from the dashboard editor keep it. + ### Decision method `strategy: "jev"` asks a decision backend to choose the first eligible target and a compatible @@ -393,10 +478,21 @@ Combo's `decisionProvider`: - Self-hosted services receive each target/effort option as a plain description string (for example `Target openai/gpt-5.6-sol (provider openai, model gpt-5.6-sol) with low reasoning effort.`), because Ollama accepts only string or `null` option descriptions. TypeSafe keeps - receiving the structured option objects. -- OpenCodex offers 2–26 options to a System One-compatible row. Each target contributes one option - per offered reasoning effort; use per-target `reasoningEfforts` to trim them. Fewer than 2 or - more than 26 options fail open without a request. + receiving the structured option objects. When targeting Vercel AI Gateway (`ai-gateway.vercel.sh`), + route options include both `value` and detailed `description` fields. Other self-hosted endpoints, + including a custom `/decisions` path, keep the System One request format. +- OpenCodex offers 2–26 options to a System One-compatible row (`SELF_HOSTED_MIN_OPTIONS = 2`, `SELF_HOSTED_MAX_OPTIONS = 26`). + Each target contributes one option per offered reasoning effort; use per-target `reasoningEfforts` to trim them. + Fewer than 2 or more than 26 options fail open without a request. For Vercel AI Gateway, whose + [OpenAI-compatible Decisions reference](https://vercel.com/docs/ai-gateway/sdks-and-apis/openai-decisions) + supports 1..255 choices, the upper bound expands to 255 options (`DECISIONS_MAX_OPTIONS = 255`); OpenCodex + enforces the 2-choice minimum as local routing policy to select among candidate targets. +- Vercel AI Gateway endpoints (`https://ai-gateway.vercel.sh/v1`) automatically normalize to `/decisions`. + OpenCodex projects structured conversation context into a formatted plain-text `input` string + (`Task:`, `Signals:`, `Recent Assistant:`, `Recent Tool Call:`, and `Tool Output:`). Route answers are accepted + from object (`answers.route`) or choice-array formats, resolving from either `choice` or `value`. Probability + distributions are accepted as key-value maps or probability records; duplicate choice keys or invalid distributions + strictly fail open to the first eligible target. - A cold model load can take tens of seconds, and an aborted decision request makes Ollama abandon the load. Pre-warm the model and keep it resident (`OLLAMA_KEEP_ALIVE=-1`, or `keep_alive`), and raise `decisionTimeoutMs` (1000–120000 ms, default 4000) when the service is slower than four seconds. @@ -539,8 +635,9 @@ are ignored. Operator notes are evidence for the decision, not commands, and can target allowlist or reasoning-effort limits. Only put information there that may be disclosed to the selected decision backend. -Each logical model call is decided on its own; there is no per-conversation pin. Consecutive turns of -one session can therefore land on different targets, and every switch starts a cold provider prompt +By default, each logical model call is decided on its own. Unless you enable the opt-in +[session pin](#session-pin-for-jev), consecutive turns of one session can therefore land on +different targets, and every switch starts a cold provider prompt cache, so a mix of very different targets can cost more input tokens than it saves. Keep the allowlist to targets you are content to alternate between. Targets marked `lastResort` are withheld from JEV under `cooldownWaitPolicy: "before-last-resort"` while any normal target is offered, and @@ -570,10 +667,13 @@ target/effort, a coarse decision gate, latency, optional confidence/probability, Automated tests use mocked TypeSafe responses plus a no-key fail-open smoke; a live TypeSafe decision requires an operator-supplied key and is not run implicitly. -JEV's selected effort applies to the first Responses child and to native Chat children on the opt-in -`protocols.rollout.nativeChatCombos` path. It replaces caller effort and removes conflicting thinking -controls and caller `service_tier`; an explicit no-effort choice removes effort even when the Combo has -a forced default. Provider effort pins, caps and wire normalization still apply afterward. +With `jevEffortMode: "decide"` (the default), JEV's selected effort applies to the first Responses child +and to native Chat children on the opt-in `protocols.rollout.nativeChatCombos` path. It replaces caller +effort and removes conflicting thinking controls and caller `service_tier`; an explicit no-effort choice +removes effort even when the Combo has a forced default. With `"client"`, JEV keeps its selected target +but leaves effort resolution to ordinary Combo policy: the caller and the target ladder, plus +`defaultEffort`, so `defaultEffortMode: "force"` still overrides caller effort in client mode. Provider +effort pins, caps and wire normalization still apply afterward. Request and attempt logs show a differing applied effort as `high->xhigh` or `high->low`, retaining later adjustments such as `high->xhigh->medium`. An unchanged effort or a no-effort choice keeps the existing label. Later fallback targets use ordinary Combo policy from the original request, without another JEV call. @@ -590,15 +690,18 @@ rows show decision count, applied count, and average latency for `typesafe`, `sy ## What happens when a target fails Combo failures are divided into **hop** failures and **terminal** failures. +To make a combo fail with a clear `fallback_refused` error instead of hopping to another model or +provider, see [Fallback off](/guides/fallback-off/). | Result | Behavior | | --- | --- | | HTTP 401, 403, 404, 408, 429, or any 5xx | Cool the target and hop to the next eligible target. | | HTTP 410 with an explicit model end-of-life, retired, deprecated, sunset, decommissioned, or no-longer-available signal | Cool that target and hop. Unrelated 410 responses remain terminal. | | Classified authentication, subscription, quota, rate-limit, overload, or upstream-server error | Cool the target and hop, even when the status alone is not sufficient. | -| Client cancellation (499), `origin_rejected`, cyber-policy refusal, context overflow, or other invalid request | Stop and return the error; another target would not make the request valid. | +| Confirmed context-window overflow before output, including HTTP 400 | Try the next untried eligible target without cooling this target; another model may have a larger window. Exhaustion returns the first confirmed HTTP 400 context-length error; a context refusal sent with another status still advances but is not retained. | +| Client cancellation (499), `origin_rejected`, cyber-policy refusal, or other invalid request | Stop and return the error; another target would not make the request valid. | | Exact HTTP 400 saying a model is not supported when using Codex with a ChatGPT account | Try the next declared target before output commitment. The message must be the whole refusal in `detail`, `error.message`, or bare text; competing `detail` and `error` envelopes stay terminal. This does not quarantine the account or cool every model on the provider. | -| Structured HTTP 400 rejecting optional `user`, an unsupported reasoning effort, model-scoped image input, or input media the route cannot read (`unsupported_input_modality`) | Hop before output commitment without cooling; see request-local target compatibility below. | +| Structured HTTP 400 rejecting optional `user`, an unsupported reasoning effort, model-scoped image input, or input media the route cannot read (`unsupported_input_modality`) | For an effort refusal, try the next lower published rung on the same target while the send budget allows; if no rung works, hop before output commitment without cooling if the refusal matches a recognized compatibility shape, otherwise stay terminal. Other listed mismatches hop without cooling; see request-local target compatibility below. | | First tool call of a Responses turn run by an in-process adapter (`runTurn`) that the current request did not declare, before any output or replay-unsafe side effect | Cool the target and hop with the same tool catalog. After visible output or a replay-unsafe side effect the refusal is final. Chat Completions and Anthropic Messages requests are unchanged. | | Any other unclassified error | Stop and return the error. | @@ -609,8 +712,16 @@ the combo returns the last real upstream failure without sending to that target. When `cooldownMs` is unset, a hopped target uses an upstream fallback: 5 seconds for request-rate 429s with upstream code `1302` or `1305`, 10 minutes for a spent account usage window, and 60 seconds otherwise. A usage window is recognised by upstream code (`usage_limit_exceeded`, -`usage_limit_reached`, `1308`) or by the prose `usage limit reached`, independent of HTTP status — -the ChatGPT Codex backend reports a spent window as a 502 rather than the documented 429. Credential and +`usage_limit_reached`, `1308`) or by quota exhaustion phrasing (such as `usage limit reached`, +`token-plan ... quota has been exhausted`, or `weekly usage quota exceeded`) +outside 400 and 422 responses, independent of HTTP status — the ChatGPT Codex backend reports a spent +window as a 502 rather than the documented 429. A 400 or 422 response needs a structured code: a +validation error that merely quotes quota wording (e.g. `quota exhausted`) does not hop. Codes +inferred from that prose by the proxy's formatter do not count as upstream structured evidence. +Devin's explicit weekly/monthly/daily or usage-window exhaustion becomes 429 and uses the +10-minute target hold; per-minute/per-hour and MCP configuration `failed_precondition` trailers stay +400 and stop. Raw Devin trailer text is redacted. A spent +window cools only that target, so other accounts of the same provider stay eligible. Credential and billing failures that already black out the whole provider (`invalid_api_key`, `insufficient_quota`, `payment_required`, and the other provider-scoped codes) take the same 10-minute hold. When it is set, `cooldownMs` applies whenever no usable upstream `Retry-After` or Codex reset signal exists, including those @@ -678,13 +789,21 @@ cooldown expires; request-local compatibility rejections do not cool the target. immediate upstream directive, just like `Retry-After: 0`. Set `waitForCooldownMs` to allow a later request to wait for the earliest eligible target cooldown, up to that cap on each selection attempt, and then make one fresh selection. A request may therefore wait up to `hops × waitForCooldownMs` -across multiple failover hops. The default is `0`, which fails closed immediately with HTTP 503 when +across multiple failover hops. Before any target is attempted, the default `0` fails closed immediately with HTTP 503 when every eligible target is cooling; that `combo_unavailable` 503 carries a `Retry-After` header equal to the earliest remaining cooldown, rounded up to whole seconds with a minimum of 1. Waits are not jittered, so synchronized wake-ups are possible. An aborted request cancels this wait and returns the normal `client_cancelled` response; it does not dispatch a backup target after cancellation. A combo target -cooldown is process-local per-combo state and is separate from the account-level Codex quota cooldown -used by native account routing. +cooldown is per-combo state, separate from the account-level Codex quota cooldown used by native +account routing. It is saved with its absolute expiry to `combo-cooldowns.json` in the opencodex home, +so a restart keeps it until that expiry; proxies sharing one home never shorten each other's +cooldowns. Saving, renaming or deleting the combo clears its cooldowns. + +After a confirmed HTTP 400 context refusal, exhaustion returns the first such refusal as +`context_length_exceeded`, including when the remaining targets cannot replay reasoning or lack +metered-spend consent, or the send budget is exhausted. It takes precedence over later retryable +errors, including quota errors. Cancellation, later fatal refusals and explicit fallback-policy +refusals still stop immediately; no unconsented metered target is sent the request. :::note Failover is intentionally bounded. It helps with target-specific availability, authentication, @@ -698,21 +817,38 @@ classify the original HTTP 403 as a hop. For streaming requests, the upstream HTTP status is not the final decision. OpenCodex buffers a bounded pre-output prefix of the selected child's Responses SSE. If the stream reports a retryable `response.failed` terminal before any text, reasoning, tool call, or other output event, the child -is recorded as failed and the combo may try its next eligible target. A zero-output -`response.incomplete` follows the same path when its reason is missing or is `adapter_eof`, -`missing_terminal_event`, or `upstream_stall_timeout`. Explicit semantic reasons such as -`max_output_tokens` and `content_filter` remain terminal, as does an explicit null reason. -A reasonless final snapshot that already contains output items is also kept. Once any output event begins, -the target is committed: a later stream failure is returned to the client and is never replayed on -another provider, which prevents duplicate text and tool execution. If the pre-output buffer reaches -its safety cap without a terminal or output boundary, OpenCodex also commits the current target -instead of growing memory without a bound. +is recorded as failed and the combo may try its next eligible target. Run-turn combo targets buffer +their pre-output reasoning for up to one second instead: if a +zero-output `max_output_tokens` terminal arrives before any visible output and within the hold, the +turn advances to another eligible target without cooling the healthy candidate; once the reasoning +hold expires or visible output begins, the target commits and buffered reasoning is streamed +immediately to the client. A zero-output `response.incomplete` follows the same path when its reason +is missing or is `adapter_eof`, `missing_terminal_event`, `upstream_stall_timeout`, or an explicit +`max_output_tokens` limit before any output is emitted. The `max_output_tokens` exception requires +the turn to look finished: a snapshot that carries `end_turn: false`, or whose +`incomplete_details.retryable` is `false`, stays on its target. An Anthropic `pause_turn` is a paused +long-running turn the client is expected to continue; it reaches you as the same `incomplete` with +reason `max_output_tokens` it always has, and it also stays on its target instead of moving to the +next one. Other explicit semantic reasons such as `content_filter` remain terminal, as do post-output +`max_output_tokens` limits and an explicit null reason. +When every run-turn or SSE target ends with such a zero-output `max_output_tokens` limit, and no +confirmed context refusal was seen (that one still takes precedence), the client receives the last +attempt's HTTP 200 `incomplete` response (reason `max_output_tokens`) with that attempt's usage, +rather than a 502 failure. Non-streaming native JSON is the exception: that body is never inspected, +so its `incomplete` body, empty or not, is returned to you unchanged. A reasonless final snapshot +that already contains output items is also kept. The rate-limit and +response-metadata frames that a native Codex (ChatGPT account) target sends over its WebSocket are +not output, so an overload error that follows them with no output still moves to the next target. +Once any output event begins or the reasoning hold deadline is reached, the target is committed: a later stream failure is +returned to the client and is never replayed on another provider, which prevents duplicate text and tool +execution. If the pre-output buffer reaches its safety cap without a terminal or output boundary, +OpenCodex also commits the current target instead of growing memory without a bound. ## Request-local target compatibility When routing Claude Code to the canonical ChatGPT Codex backend, OpenCodex removes the unsupported top-level `user` metadata field without changing the session/cache key, input messages, tool schemas, or safety identifiers. Public Responses API and noncanonical forward gateways keep that field. -A combo can also advance after an intact HTTP 400 `invalid_request_error` that specifically rejects `user`, reports `unsupported_value` for `reasoning.effort`/`reasoning_effort`, or reports `param: input` with an exact model-scoped `does not support image inputs` rejection. A route that refuses the request's media with code `unsupported_input_modality`, such as image input sent to a CLI provider route without a verified multimodal contract, advances the same way. This is a mismatch for that request, not evidence that the target is unhealthy, so it records no cooldown. This compatibility recovery does not silently change `none` into a different effort or broaden this exception to arbitrary invalid requests. Policy refusals, cancellation and already-committed output remain non-replayable. A single-target request still returns an unresolved upstream rejection. +A combo can also advance after an intact HTTP 400 `invalid_request_error` that specifically rejects `user`, reports `unsupported_value` for `reasoning.effort`/`reasoning_effort`, or reports `param: input` with an exact model-scoped `does not support image inputs` rejection, and after the exact vendor envelope `{"code":"invalid-argument","error":"Invalid reasoning effort."}`. When a combo target refuses the requested reasoning effort, the combo first retries that target at the next lower published effort rung, one rung per refusal and within the shared send budget; this applies to any recognized effort refusal. If no lower rung succeeds, a refusal in one of the shapes above advances to another target without cooling the rejected one, keeping that target's original 400 when the next rung has no send left; other effort refusals stay terminal. A route that refuses the request's media with code `unsupported_input_modality`, such as image input sent to a CLI provider route without a verified multimodal contract, advances the same way. These are mismatches for this request, not evidence that the target is unhealthy. Direct requests retain their single effort-downgrade repair. Compatibility recovery does not silently change `none` into a different effort or broaden the combo hop to arbitrary invalid requests. Policy refusals, cancellation and already-committed output remain non-replayable. A single-target request still returns an unresolved upstream rejection. ## Tool calls stay on one target @@ -861,7 +997,8 @@ ocx combo remove --yes `set` also accepts `--strategy`, `--sticky`, `--effort`, `--alias`, `--native-alias`, `--allow-metered-targets on|off`, `--display-name`, `--description`, `--decision-provider`, `--decision-timeout`, and `--rename-from`. Use `-` as the value of `--effort`, `--alias`, `--display-name`, `--description`, `--decision-provider`, or `--decision-timeout` to -clear that field. The two decision flags apply only to `--strategy jev`. `--native-alias` requires a currently supported bare native +clear that field. The two decision flags apply only when the effective strategy is JEV: `--strategy jev`, or a stored JEV combo when `--strategy` is omitted. On an existing combo, `--targets` replaces only +the target list: without `--strategy` the stored strategy and its JEV settings stay as they are. `--native-alias` requires a currently supported bare native model alias and a non-empty display name. `create` and `update` are aliases for `set`; `delete` is an alias for `remove`; and the same subcommands are available under `ocx route combo`. @@ -922,6 +1059,7 @@ Combos are stored in the top-level `combos` object, keyed by combo id: | `defaultEffort` | No | `null` | `low`, `medium`, `high`, `xhigh`, `max`, or `ultra`; resolved against each target's advertised ladder. | | `defaultEffortMode` | No | `"fallback"` | `"fallback"` preserves explicit caller effort. `"force"` overrides valid caller effort, requires a valid non-null default, and can increase cost and latency. | | `reasoningEffortMode` | No | `"strict"` | `"strict"` intersects every known target ladder, so one target advertising no effort control empties the combo's picker. `"adaptive"` excludes those empty ladders from the published intersection. At dispatch, explicit empty or adaptive unknown ladders remove unsupported effort/thinking controls while preserving supported non-effort reasoning fields such as `reasoning.summary`; known non-empty targets keep existing effort resolution. | +| `jevEffortMode` | No | `"decide"` | JEV combos only. `"decide"` applies the decision effort and lets it override the caller. `"client"` keeps the decision target choice but leaves effort to the caller and the target ladder, so a provider that swaps its upstream model id per tier is not re-tiered by JEV. `defaultEffortMode: "force"` still overrides caller effort in client mode. Cache reuse still needs a stable caller effort, target and prompt prefix, and depends on the provider and account. | | `imageInput` | No | `"auto"` | `"auto"` or `"disabled"`. `"auto"` publishes image support only when every target supports images; `"disabled"` forces text-only (drops image from published modalities and rejects image-bearing requests before dispatch). | | `alias` | No | none | Optional trimmed public model id; use the alias rules above. An empty value is stored as no alias. | | `nativeAlias` | No | `false` | Explicitly permit a currently supported bare native `alias` to take routing and catalog precedence. Never inferred from the alias. | @@ -944,7 +1082,7 @@ Every target is currently ineligible: for example, its provider is disabled, it it has already been attempted for this request, or an encrypted v2 task excludes it. Check target provider state and recent upstream errors. When no target was attempted, the error message lists why each target was skipped, for example -`No available targets for combo: fast (openai/gpt-6: quota exhausted; anthropic/claude-opus-5-5: cooldown 42s)`. +`No available targets for combo (2 targets; target 1 (openai): quota exhausted; target 2 (anthropic): cooldown)`. The client error names targets by position and provider only; the service log records the target's position and provider when it fails or when the proxy waits out its cooldown. For cooldowns, follow an observed `Retry-After` value first; Codex reset headers also take precedence over `cooldownMs`. If neither upstream signal is usable, the configured `cooldownMs` applies, or the upstream fallback applies @@ -952,6 +1090,8 @@ when it is unset (5 seconds for request-rate codes `1302`/`1305`, 10 minutes for window or a credential/billing failure, otherwise 60 seconds). Explicit `Retry-After` delays are capped at 24 hours; the other cooldowns are capped at 10 minutes. +Validation errors (HTTP 400/422) that quote quota or free-tier cap text do not trigger fallback by that text alone. A structured `free_rate_limited` refusal still tries the next eligible target without cooling the healthy provider or target. + ### Why was my alias rejected? Check the alias grammar and reserved names first. A duplicate alias or invalid shape is rejected as @@ -959,7 +1099,46 @@ HTTP 400. A slashed alias whose first segment is a configured Codex account name as HTTP 409; choose a different alias namespace. The CLI and dashboard display the server's exact validation message. +### Context-window refusals + +Combo recovery reuses the bounded context-overflow detector used by Responses recovery. It reads the innermost provider message and recognizes explicit context-window/length overflow wording: a history, conversation, input, prompt, request, turn, or messages that have reached or passed a model's context limit; a prompt, input, request, or messages that are too long for the model's context window; a context window/length/limit that is full, exhausted, at its limit, or has been exceeded; and `context_length_exceeded`, `prompt is too long`, `input is too long for requested model`, and `Please reduce the length of the messages or completion`. The last three count only when the provider message starts with them (Anthropic's with its token counts), so a validation error that quotes one as a parameter value, or an SDK error string that wraps one, does not qualify. A negator that governs the overflow wording -- "does not exceed", "has not been exceeded", or "must not exceed" without a token count showing the limit was crossed -- keeps it out, while a negation in an earlier clause does not cancel a later overflow report. Capacity and availability prose about the service ("the context window is full, retry later", "shards exhausted", "KV cache for the context window is exhausted") describes back-pressure, not this turn's size, and keeps its cooldown. That wording is read in the clause that carries the verdict; a remedy that follows it ("Remove older messages before retrying", "enable prompt caching") does not turn an overflow into back-pressure. On a 5xx, "full", "exhausted" and "at its limit" never count as an overflow; they qualify only on a 4xx that speaks about the request. The detector can read the diagnostic from a string-valued JSON `error` field as well as a structured error message; a code beside an unrelated message, malformed JSON, a parameter validation error, or a generic instruction to shorten a parameter does not qualify. Already-committed output is never replayed. Fallback policy, spend consent and send budgets still apply; each physical attempt retains its own usage. When eligible targets or the send budget run out, the first confirmed HTTP 400 context refusal takes precedence over later retryable errors, including quota errors. A later fatal refusal still stops immediately. + ### Why did failover stop after the first error? -The error was terminal rather than target-specific. Fix invalid input, reduce an oversized context, +The error was terminal rather than target-specific. Fix invalid input, handle a policy refusal, or correct the rejected request origin. Combos do not hop for those cases. + +## Retry all-cooled targets (opt-in) + +Combo cooldown recovery is opt-in and disabled by default. To allow one new +failover pass when every otherwise eligible target has a saved combo cooldown: + +```sh +ocx combo set review --cooldown-reprobe on --cooldown-reprobe-interval 300000 +ocx combo set review --cooldown-reprobe off +``` + +The corresponding per-combo configuration is: + +```json +{ "cooldownReprobe": { "enabled": true, "intervalMs": 300000 } } +``` + +The default interval is five minutes; accepted values are integer milliseconds +from 1000 to 86400000. Setting the interval alone does not enable recovery. +Recovery is demand-driven: the first eligible request can reserve a pass immediately, +and later passes are separated by at least the configured interval. There is no timer +or background traffic. Each target can be attempted once in the request's existing +failover budget; failures record fresh cooldowns. Account quota checks, disabled +providers, request compatibility, metered-spend permissions and cancellation remain +enforced. Explicit provider Retry-After values may therefore be retried early only +when the operator enables this option. Preview/list operations never clear cooldowns. +The interval is tracked per combo in memory and resets on proxy restart or combo +selection-state reset. Existing cooldown-wait behavior is unchanged when disabled. + +A recovery pass belongs only to the request that reserved it; other requests still +observe the saved cooldowns. That reservation follows the request through cooldown +waits and JEV selection. A target that becomes usable again during a wait can still +be retried if its cooldown has not changed. A newer cooldown cancels that target's +reservation. Success clears only the unchanged cooldown of the target that answered; +untried targets and newer failures keep their cooldowns. diff --git a/docs-site/src/content/docs/guides/custom-gateway.md b/docs-site/src/content/docs/guides/custom-gateway.md new file mode 100644 index 0000000000..c50c6bbaf1 --- /dev/null +++ b/docs-site/src/content/docs/guides/custom-gateway.md @@ -0,0 +1,94 @@ +--- +title: Verify a custom remote gateway +description: Check a custom Chat Completions gateway from discovery through a bounded completion. +--- + +Before registering a gateway, obtain its authorized Chat Completions base URL, API key, and +supported model IDs from its operator. For example, `https://api.example.com/v1` is a placeholder, +not a working endpoint. Start the proxy if it is not already running, then choose **Custom** in the +dashboard, name it `my-gateway`, select `openai-chat`, and enter the authorized URL and key in the +form. Save it without putting the key in commands or shared examples. A saved provider is not yet +proof that discovery or inference works. + +On a [Remote Link](/guides/remote-link/) Child, providers come from the Home: the Child's dashboard +refuses provider changes and its requests are served by the Home's providers. Register and verify +the gateway on the Home instead. + +Check the boundaries separately, using the configured local port if it differs from the default: + +```sh +curl -fsS http://127.0.0.1:10100/healthz +ocx ready +ocx provider test my-gateway +ocx models live --provider my-gateway --json +``` + +Health and readiness describe the proxy; they do not prove the upstream can generate text. The +provider test without `--model` checks discovery, not inference. `applicable: false` can mean there +is no live discovery endpoint for a static catalog; it is not a successful inference test. A public +model list also need not validate the key. If discovery fails or no model appears, check the URL, +credentials, upstream access, and provider configuration before selecting a model. + +A gateway can serve completions without a model-list endpoint. If its operator supplies a supported +raw ID, configure `liveModels: false` and `models: ["vendor/model"]` on the existing provider, +preserving its other fields and replacing the example ID with the supplied value. See +[static model catalogs](/reference/configuration/providers/#static-model-allowlists). + +Before editing `config.json` directly, save your work and wait for active requests to finish; +stopping the proxy can interrupt them. Stop the proxy through its owner: quit OpenCodex Desktop +from its tray, run `ocx service stop` for a service install, or run `ocx stop` for an unsupervised +proxy. Confirm it is stopped, then edit and save the file without running other configuration +writers. Start it again through the same owner: reopen Desktop, run `ocx service start`, or run the +original `ocx start` command with its launch options, including `--port` if supplied. For a +foreground start, leave it running in its terminal and run `ocx sync` and the remaining checks from +another terminal. Then inspect the live catalog again. Alternatively, test the supplied raw ID directly +with the cost-confirmed completion command below; that test does not require a catalog row. + +In the live catalog inspect the actual `id`, `namespaced`, `disabled`, and +`initialSelectionPending` fields. Initial selection can leave models off or pending; see +[initial model selection](/reference/configuration/providers/#initial-model-selection). +Resolve pending initial selection before enabling a row. For visibility commands, combine the +provider name with the row's **raw `id`**, preserving any slashes inside that ID: + +```sh +ocx models enable 'my-gateway/' +``` + +For example, a raw `id` of `vendor/model` needs the selector `my-gateway/vendor/model`. +The client-facing `namespaced` slug may instead be `my-gateway/vendor-model`; substituting that +encoded slug can leave a raw disabled entry in place. Enabling one model does not disable others. +If only that model should be visible from this gateway, disable each other enabled gateway row +using its raw `id` in the same selector format, then inspect the list again: + +```sh +ocx models disable 'my-gateway/' +ocx models live --provider my-gateway --json +``` + +Check that the intended row has `disabled: false` and the other intended exclusions are disabled. +A bare native model ID can select a different route. Use exact values rather than display names or +guessed reasoning suffixes: a suffix may be a distinct upstream model ID, while reasoning effort +is a separate setting. See the [CLI reference](/reference/cli/providers-accounts/) for details. + +When needed, run `ocx sync` to update the client catalog, then confirm the model appears in the +Codex model picker. A running client can retain an older in-memory list. Preserve active work and, +if the picker remains stale, fully quit and reopen Codex. Alternatively, after explicit approval, +use [`ocx system codex-restart --yes`](/reference/cli/agents/): it can +interrupt the session and discard unsaved drafts, selections, or pending approval prompts. +Outside the direct config-file edit above, restarting a client or proxy is not the default recovery step. + +To verify one actual completion on a supported key-auth remote configuration, pass the **raw +upstream `id`** from the row or gateway operator unchanged, without adding the provider prefix: + +```sh +ocx provider test my-gateway --model '' +``` + +This sends one bounded request, consumes quota, and may incur charges. Confirm the default-No prompt +only after approving that cost; non-interactive or JSON use requires `--yes`. An +`applicable: false` completion result sends no completion and is not a pass, even if the command +exits zero. Before counting a successful test as a pass, check that the reported wire model +matches the intended upstream ID; an alias can resolve to a different model. In JSON output this +is `wireModel`. A successful text completion does not establish tool calling, structured output, +continuation behavior, or the model's actual identity; upstream-reported identity is metadata. For +later compatibility issues, reproduce the affected protocol separately with a sanitized fixture. diff --git a/docs-site/src/content/docs/guides/desktop-app.md b/docs-site/src/content/docs/guides/desktop-app.md index 73e9367061..3ef800fc2f 100644 --- a/docs-site/src/content/docs/guides/desktop-app.md +++ b/docs-site/src/content/docs/guides/desktop-app.md @@ -28,6 +28,37 @@ SignPath Foundation is rolling out ([Windows Code Signing](/reference/code-signi release carries the signature, Windows SmartScreen may warn about an unsigned installer; choose **More info → Run anyway** after confirming that you downloaded it from the release page. +One installer page describes the anonymous daily usage summary OpenCodex sends, links the +[privacy statement](/reference/code-signing/#privacy), and has a **Send anonymous usage +statistics** checkbox, checked by default. Clear it and the app saves the opt-out to your +opencodex config the first time it starts, before any proxy runs. The choice applies to every +account on the computer, once for each account, so it also works for a silent install run by an +administrator or a deployment tool (Intune, SCCM). For a silent install, pass +`OCX_TELEMETRY_CHOICE=optout`: + +```powershell +msiexec /i OpenCodex--windows-x64.msi /qn OCX_TELEMETRY_CHOICE=optout +``` + +The installer needs administrator rights and records the choice for the whole computer. +Only `send` keeps telemetry on; `optout`, in any letter case, and any other value (`off`, `0`) turn it off. +Each install that passes `OCX_TELEMETRY_CHOICE` records a new decision, so a deployment that reuses +the same command for every version applies the opt-out again after each upgrade, over any dashboard +choice made since. + +Leaving the box checked does not start sending by itself: the dashboard still shows its one-time +notice first, and a checked box never turns telemetry back on for an account that turned it off. +In-app updates, reduced-UI installs (`/qr`) and maintenance runs of the installed version skip this +page and keep the recorded choice. Running a newer installer by hand shows the page again, unchecked +if you opted out before. Continuing without changing the box keeps that earlier decision as it was, +so it is not applied again over a choice you made in the dashboard since; changing the box records a +new decision. + +If you installed the background service with `ocx service install`, it can start a proxy at logon +without the app. An opt-out recorded by a later installer reaches that service's config the next +time the app starts; until then the service may still send its daily summary. To stop it at once, +run `ocx telemetry disable`. + ### Linux Download `OpenCodex--linux-x86_64.AppImage` or @@ -105,7 +136,15 @@ when they verify that the app runs its bundled proxy, even without recorded owne CLI service repairs for that runtime. On macOS and Linux, turn on **Start at Login** in the OpenCodex menu instead of installing a background service. Startup safety credits the app only when its login registration is verified; if it cannot be verified, follow the Desktop guidance in status. -The Startup page then labels the Desktop row **Running · Start at Login not verified**. +In the dashboard's Getting started checklist, the last step under the app is +**Turn on Start at Login** and opens the Desktop card on the Startup page. It is marked +done only when Startup safety verifies the registration and the app runs the proxy. It +shows as to do when Start at Login is verified off, or on macOS when the app is confirmed +not to be running the proxy. Otherwise the step stays unmarked, which is the usual case on +Windows (the registration is not verified) and on Linux without a verified autostart +entry; check the item in the OpenCodex menu yourself. +The Startup page shows a quiet **Start at Login not verified** note when the app's +registration cannot be checked. A verified disabled registration is shown as action required. On macOS the menu's **Start at Login** item is checked only when Startup safety would verify the same registration. Otherwise the item is unchecked and its label says why: **disabled by macOS** opens System Settings → General → Login Items & Extensions, where @@ -116,18 +155,32 @@ is missing** means the login item names an app that no longer exists, so delete means the registration could not be read. While the app runs the proxy, the Startup page keeps the background service installer disabled; to use it instead, quit OpenCodex and run `ocx service install` in a terminal. The Codex launcher shim can still be installed there. -When a Codex launch finds no proxy, the shim waits for OpenCodex to restart it, opens -OpenCodex on macOS if it quit and its recorded ownership matches a valid **Start at Login** -registration, and otherwise reports an error instead of starting a second proxy. Automatic +When a Codex launch finds no proxy, the bundled CLI waits for independently verified Desktop +recovery, including when Desktop has no recorded ownership claim. A matching Desktop that has +stopped its proxy, or whose recovery cannot be verified, produces an error — except that on a +platform without live-image verification a recorded ownership claim with the app still running +keeps the existing bounded wait. A process name or +locator file alone does not block ordinary CLI startup. The shim opens OpenCodex on macOS if it +quit and its recorded ownership matches a valid **Start at Login** registration. Automatic reopening selects that registration's app bundle path and checks that its declared main executable matches the registered Desktop executable. If registration is missing, stale or inconsistent, open OpenCodex manually; another copy with the same bundle identifier is not selected as a fallback. If the shim reads "activation not confirmed", add `. ~/.opencodex/codex-shell-env.sh` to your shell startup file after other PATH setup. +Recovery verification covers the matching bundled CLI on macOS/Linux and the protected system +Debian installation. An old npm-created shim can pin a separate Bun/CLI installation and bypass +Desktop's terminal-command handoff. That entrypoint cannot verify a macOS or Windows Desktop, +including an official signed copy, or an arbitrary per-user Linux copy. Recreate the shim from +Desktop's Startup page or invoke its bundled CLI. Windows cannot yet establish the live image +identity required for this recovery proof; an identified running sibling earns no recovery credit +and, without a recorded Desktop claim, reports an error instead of starting a CLI proxy — even +when its on-disk signatures are valid. With a recorded claim and the app running, the CLI keeps +its existing bounded wait for Desktop's proxy. + The bundled CLI is `/Applications/OpenCodex.app/Contents/MacOS/ocx` on macOS and `/usr/bin/ocx` for the Linux deb package. Run that executable with `status` to check -the app's proxy. Windows also verifies live supervision, but **Start at Login** remains +the app's proxy. Windows verifies live supervision when the proxy child is already running, but **Start at Login** remains unverified there and Desktop receives no startup protection credit. While the CLI detects Desktop supervising the proxy, `ocx service install`, `repair`, @@ -160,7 +213,7 @@ On Linux, the pinned autostart backend writes the login entry to `~/.config/autostart/OpenCodex.desktop`, even when `$XDG_CONFIG_HOME` is set. Startup safety reads that entry and the desktop install-id under `~/.config`. When `$XDG_CONFIG_HOME` points elsewhere, the login session searches a different autostart -directory, so startup safety stays **At risk** instead of crediting the entry. +directory, so startup safety does not credit the entry as restart protection. The entry counts only while it is not marked `Hidden=true` or `X-GNOME-Autostart-enabled=false`, and has no `OnlyShowIn`, `NotShowIn`, or `TryExec` condition. Its `Exec` must be an unquoted absolute path to `opencodex-desktop`, without @@ -169,12 +222,15 @@ executable must still be named `opencodex-desktop`, with its bundled `ocx` besid Startup safety reads the full evidence chain twice and grants protection only when both reads agree. -AppImage installations remain **At risk**: the autostart backend registers the outer +AppImage installations do not receive verified Desktop protection: the autostart backend registers the outer AppImage path, while the live desktop process runs inside its mount. Startup safety cannot verify that relationship and does not credit AppImage protection. -A missing or stale check remains **At risk**. If the desktop app owns the proxy but -protection cannot be verified, reopen OpenCodex and check **Start at Login**. Service -and launcher installation or repair stays disabled while that ownership remains; +A missing or stale check does not earn restart-protection credit. If Desktop owns or +supervises the proxy, the page shows an informational note and asks you to check +**Start at Login** in the OpenCodex menu. Service installation or repair stays disabled +while that ownership remains. The launcher shim can still be installed when diagnostics are fresh; +its Install button is disabled while diagnostics are stale. On Linux without a tray, inspect +`~/.config/autostart/OpenCodex.desktop` and the conditions described above. The command `ocx restore` is still available to undo Codex routing. Normal desktop updates replace the bundled CLI with the fixed startup probe. No local @@ -209,9 +265,9 @@ shows the Child's dashboard. If the port is held by something the app cannot use bound to an address other than `127.0.0.1`, the app stops retrying and waits for that to change. A recovery that finishes while the update page is open leaves that page on screen. -The tray's **Stop proxy** and **Quit** keep the proxy stopped. The dashboard's own **Stop** button -does not stop a proxy the app runs, because the app would start it again: it says so and changes -nothing. What the app decided and why is +The tray's **Stop proxy** and **Quit** keep the proxy stopped. The dashboard's own stop (pulling the +proxy lever at the foot of the sidebar all the way down) does not stop a proxy the app runs, +because the app would start it again: it says so and changes nothing. What the app decided and why is recorded in `runtime-supervisor.log` in the app's log directory (`~/Library/Logs/com.opencodex.desktop` on macOS). @@ -280,7 +336,10 @@ Before uninstalling a supported Desktop installation, open **Terminal command** dashboard or tray and choose **Remove terminal command**. Desktop removes only its unchanged managed configuration. Modified blocks or files are preserved and reported; resolve those issues before deleting the app. Uninstalling the app directly does not guarantee cleanup -of shell files or the user `Path`. +of shell files or the user `Path`. On macOS/Linux, a stale enabled Desktop command record +also blocks eligible npm/pnpm launcher calls if the selected app executable is gone. Repair +or remove the terminal command before deleting the app. `OCX_NO_DESKTOP_HANDOFF=1` permits +one explicit package-launcher invocation; it does not repair the record, shim or PATH. On macOS, drag `OpenCodex.app` from Applications to the Trash. On Windows, remove OpenCodex from **Installed apps**. On Debian-based Linux systems, run: diff --git a/docs-site/src/content/docs/guides/fallback-off.md b/docs-site/src/content/docs/guides/fallback-off.md new file mode 100644 index 0000000000..424b158e01 --- /dev/null +++ b/docs-site/src/content/docs/guides/fallback-off.md @@ -0,0 +1,132 @@ +--- +title: "Fallback off" +description: Turn model and provider fallback off per scope, and see what happens on a Remote Link Child when its Home is unreachable. +--- + +OpenCodex can serve a request from a different model or provider when the one you chose fails: a +[combo](/guides/combos/) moves to its next target, a [routing profile](/guides/routing-profile-editor/) +tries its next candidate, a spawned subagent moves down its model fallback chain, and the main-account +hard lock can reroute to its configured fallback model. All of these stay on by default. + +Turn a kind of fallback **off** when you would rather get a clear error than an answer from somewhere +you did not pick. + +## What counts as a fallback + +A fallback is a hop to a **different model** or a **different provider**: + +| Kind | Example | Switch | +|---|---|---| +| Model fallback | `anthropic/claude-opus` fails, `anthropic/claude-sonnet` would answer | `model` | +| Provider fallback | `anthropic/claude-opus` fails, `openai/gpt-6-sol` would answer | `provider` | + +Rotation among the accounts or API keys of **one provider pool** for the same model is not a fallback. +It is how a pool absorbs a rate-limited account, and it keeps working whatever you set here. Retrying +the same target, and transport fallbacks that keep the same target, are not fallbacks either. + +When a main-account hard lock routes to a combo or profile, it refuses early only when every declared +destination is known to be policy-denied. Otherwise normal selection proceeds without filtering, and +its actual selected destination still follows these switches. Allowing provider fallback does not allow +a different model on the same provider when model fallback is off, even if another candidate is allowed. + +## Turn fallback off + +```bash +ocx fallback off # model and provider fallback, everywhere +ocx fallback off --kind provider # only cross-provider hops +ocx fallback off --route combo/coding # one combo, routing profile or model selector +ocx fallback off --provider anthropic # hops that leave one provider +ocx fallback on --route combo/coding # an exception under a global off +ocx fallback clear --route combo/coding # remove an override +ocx fallback status # current settings and the last fallback +``` + +The same switches are on the dashboard: the **Fallback** card at the bottom of the **Dashboard** holds the +global switches, the overrides and the last fallback taken or refused. + +### Precedence + +1. A **device** set to off always refuses (see [per device](#per-device-settings)). A device setting can + only refuse; turning it on never reopens a hop another scope refuses. +2. Otherwise the most specific setting wins: **route**, then **provider**, then **global**. +3. Nothing set means allowed, which is today's behavior. + +The settings live in `config.json` under `fallback`: + +```json +{ + "fallback": { + "provider": false, + "routes": { "combo/coding": { "provider": true } }, + "providers": { "anthropic": { "model": false } }, + "devices": { "lnk_0123456789abcdef": { "localFallback": false, "model": false } } + } +} +``` + +A malformed leaf is ignored, so policy resolution uses the next applicable scope, and `ocx config` +diagnostics name it. A whole-config write that contains one is refused instead. + +## The error you get + +A refused fallback answers with the **status of the failure that triggered it**, so a refused 429 is +still a 429 with its `Retry-After`, and with this body: + +```json +{ + "error": { + "type": "fallback_refused", + "code": "fallback_refused", + "message": "combo/coding: anthropic/claude-opus failed (rate_limited). Provider fallback to openai/gpt-6-sol is off for route combo/coding, so OpenCodex did not send the request there. To allow it: ocx fallback on --kind provider --route combo/coding", + "fallback": { "kind": "provider", "scope": "route", "scopeKey": "combo/coding", + "from": "anthropic/claude-opus", "to": "openai/gpt-6-sol", "trigger": "rate_limited" } + } +} +``` + +The response also carries `x-opencodex-fallback: refused`. When the first target is already known to be +unavailable, the refusal happens before anything is sent, and the fallback target is never contacted. +The status depends on why the first target was skipped: + +- A combo's first target cooling down, or with its quota spent: 429. +- A combo's first target disabled or not usable for the request: 503. +- A blocked main account: 429. +- An unavailable subagent model: 503. + +After a real upstream failure, the refusal keeps that failure's status. + +## Remote Link Children and Hub clients + +A Remote Link Child and a Hub client never serve requests from their own local providers. When the +Home is unreachable, a Child answers a retryable `503` (and a Hub client's dashboard relay a `502`) with: + +```json +{ "error": "link tunnel unavailable", "code": "home_unreachable", "message": "The Home is unreachable, and OpenCodex did not serve this request from this device's local providers. …" } +``` + +Nothing is sent to a local provider, and the link key and the request body never leave the device. + +### Per-device settings + +On the Home, each linked device has two switches, on **Remote Link** or with the CLI: + +```bash +ocx fallback local on --device mac-studio # permission for local fallback while the Home is down +ocx fallback off --device mac-studio # refuse model and provider fallback for this device's requests +``` + +`--device` takes a link alias or id from `ocx link status`, or a Hub data key id. + +**Local fallback** is a permission that GOAT reads: with it on, GOAT may move that device's work to the +device's own sign-ins while the Home is unreachable. OpenCodex itself still answers `home_unreachable` +and never serves the device locally. It is off unless you turn it on. + +## Status + +`ocx status --json` includes a `fallback` object (on a Child it is the Home's, read over the link), and +`GET /api/fallback` returns the same `ocx.fallback/1` document: the effective global switches, the +overrides, every device with its local fallback permission, and the last 20 fallbacks taken or refused +with time, route, from, to, trigger and the scope that decided. The list is kept in memory and resets +when the proxy restarts. It never contains request bodies, keys or account identities. + +A Home that supports this advertises `fallback-policy/1` in `GET /readyz` `features`. diff --git a/docs-site/src/content/docs/guides/integrations.md b/docs-site/src/content/docs/guides/integrations.md index 78e83640a6..5f72065642 100644 --- a/docs-site/src/content/docs/guides/integrations.md +++ b/docs-site/src/content/docs/guides/integrations.md @@ -1,10 +1,10 @@ --- title: Integrations -description: Connect opencodex to OpenCode, Pi, Gentle Shell, OMP, Hermes, OpenClaw, Kimi Code, gjc, DeepSeek Harness, MiniMax Code, ZCode, Prime Agent, Aside, Raycast, omo, Cline CLI, Kilo, Command Code and Factory Droid from the dashboard — one switch per client, with a backup taken before every write. +description: Connect opencodex to OpenCode, Pi, Gentle Shell, OMP, Hermes, OpenClaw, Kimi Code, gjc, DeepSeek Harness, MiniMax Code, ZCode, Prime Agent, Aside, Raycast, omo, Qoder, Cline CLI, Kilo, Command Code, Factory Droid and T3 Code from the dashboard — one switch per client, with a backup taken before every write. --- The **Connect** page writes opencodex's provider block into a client's own config -file, and removes it again. Twenty clients work this way, each with a switch: +file, and removes it again. Each client below has its own switch: | Client | Config file | Format | When the change takes effect | Credential | |---|---|---|---|---| @@ -24,10 +24,14 @@ file, and removes it again. Twenty clients work this way, each with a switch: | Raycast | `~/.config/raycast/ai/providers.yaml` | YAML | immediately on save — Raycast watches the file | none — loopback only | | omo (Pi / senpi) | `~/.omo/agent/models.json` | JSON | new sessions | loopback placeholder | | Qoder | `settings.json` in `$QODER_CONFIG_DIR`, default `~/.qoder` | JSON | new sessions | loopback placeholder | +| Qoder CN | `settings.json` in `$QODERCN_CONFIG_DIR`, default `~/.qoder-cn` | JSON | new sessions | loopback placeholder | +| WorkBuddy (CN) | `~/.workbuddy/models.json` | JSON | auto reload / new sessions | loopback placeholder | +| WorkBuddy AI | `~/.workbuddy-ai/models.json` | JSON | auto reload / new sessions | loopback placeholder | | Cline CLI | `~/.cline/data/settings/providers.json` and sibling `models.json` | JSON pair | after stopping and restarting Cline | loopback placeholder | | Kilo | first existing `kilo.jsonc`, `kilo.json`, `opencode.jsonc`, `opencode.json`, or `config.json` under `~/.config/kilo` | JSONC | new sessions | `OPENCODEX_KILO_API_KEY` | -| Command Code | `~/.commandcode/providers.json` (on Windows with the default home: use `HOME ?? USERPROFILE` only if nonblank and Windows-absolute, otherwise `homedir()`; a separately supplied home is preserved; append `.commandcode\providers.json`) | JSON | next launch of Command Code | none — keyless loopback (`apiKey: false`) | +| Command Code | `~/.commandcode/providers.json` (on Windows with the default home: use `HOME ?? USERPROFILE` only if nonblank and Windows-absolute, otherwise `homedir()`; a separately supplied home is preserved; append `.commandcode\providers.json`) | JSON | next launch of Command Code | none — keyless loopback (`apiKey: false`); the desktop app needs its own sign-in and opencodex never writes `auth.json` | | Factory Droid | `~/.factory/settings.json` (`%USERPROFILE%\.factory\settings.json` on Windows) | JSON | immediately via file watching | none — keyless loopback | +| T3 Code | `$T3CODE_HOME/userdata/settings.json` (default `~/.t3/userdata/settings.json`) | JSON | immediately — T3 Code watches the file | non-secret loopback marker | ## Gentle Shell @@ -65,6 +69,58 @@ This integration retains Pi’s loopback-only export policy and stores no real A [omo (Codex / LazyCodex) role models](#omo-codex--lazycodex-role-models). OpenCode-based omo (oh-my-opencode) keeps its own config under OpenCode; opencodex does not read or write it. +The managed Pi-based omo block uses the Chat dialect (`api: "openai-completions"`) by default. Chat +drops the previous step's reasoning across tool calls, which long omo tool loops notice. To have +enable and every refresh write the Responses dialect instead, set this config-file-only key in +your opencodex config: + +```json +{ "omoClientExport": { "api": "openai-responses" } } +``` + +Restart the proxy to load the edited config (`ocx service restart` for a service install, or `ocx stop`, then `ocx start`), then refresh the omo integration from **Connect → omo** in the dashboard. +Refreshing alone uses the running proxy's config and does not reload the config file. + +The setting applies only to omo; Pi, Gentle Shell and the other Pi-format clients keep +`openai-completions`. To return to Chat, remove the key, restart the proxy in the same way, then +refresh **Connect → omo**. An unknown value is ignored. +opencodex still owns only `providers.opencodex` in `~/.omo/agent/models.json`, so other providers +in that file are left as they are. + +### Qoder CN and WorkBuddy editions + +In **Connect**, enable **Qoder CN**, **WorkBuddy (CN)** or **WorkBuddy AI**, then choose +an OpenCodex model in the client's custom-model picker. The proxy must stay running. +The first enable saves a snapshot; disable removes only the generated contribution, +and Undo restores the snapshot. Existing models and unrelated settings remain intact. +These are separate connections from Global Qoder and from each other. + +The same operations are available through the CLI (replace `workbuddy` with +`workbuddy-ai` or `qoder-cn` for the other editions): + +```bash +ocx integration client enable --client workbuddy +ocx export --client workbuddy --json +ocx integration client disable --client workbuddy +``` + +Qoder CN honors `QODERCN_CONFIG_DIR`. Both WorkBuddy editions honor their native +`WORKBUDDY_CONFIG_DIR`, then `CODEBUDDY_CONFIG_DIR`; unset overrides keep the regional +roots in the table. Overrides must be absolute, `~`, or start with `~/` or `~\`. WorkBuddy's legacy +array configuration and its object-form `models` list are both supported. If an existing +`availableModels` restriction excludes OpenCodex models, remove that restriction in +WorkBuddy before enabling. Project-level settings can override user-level models. + +Connections require an unauthenticated loopback listener; no upstream credentials are +copied into these clients. WorkBuddy receives the full Chat Completions URL and the +capabilities declared by the OpenCodex catalog. Restart the client or start a new session +if its model picker has not reloaded yet. Configuration/lifecycle tests do not establish +end-to-end compatibility with every upstream model or every client release. + +Doubao Desktop and Devin currently have no verified arbitrary-provider configuration +contract in this integration. They have no enable switch; adding a local JSON file alone +would not make their model pickers consume it. + Qoder IDE / qodercli supports export and managed configuration through the Dashboard and CLI: ```bash @@ -74,15 +130,64 @@ ocx integration client disable --client qoder ``` Qoder uses `settings.json` in `QODER_CONFIG_DIR` when that variable is set, and -`~/.qoder/settings.json` otherwise; a relative `QODER_CONFIG_DIR` is refused. Enable merges `providers.opencodex` and -OpenCodex entries in `modelConfigs.customModels`, preserving other providers, custom models, -and settings. Disable removes the recorded OpenCodex entries; restore uses the existing +`~/.qoder/settings.json` otherwise; a relative `QODER_CONFIG_DIR` is refused. Enable merges only `providers.opencodex`, preserving other providers, custom models, +and settings. Models appear once in the provider catalog; duplicating them in +`modelConfigs.customModels` causes Qoder to reject the provider. Refreshing an older managed +integration removes its recorded duplicate rows; user-edited rows remain conflicts. Disable removes the recorded OpenCodex entries; restore uses the existing snapshot workflow. The provider's default model is the first model in the sorted export. -Custom models use their catalog context window, falling back to 128000 input tokens. +If `modelConfigs.customModels` already holds an `opencodex` row for an exported model that +OpenCodex did not write, enable, refresh, overwrite and disable report a conflict and leave the +file unchanged; remove or rename that row in Qoder's settings, then try again. Rows for other +providers or for models outside the export are left alone. +Provider models use their catalog `contextWindow`, falling back to 128000 input tokens. +Restart Qoder after refreshing an existing integration to reload the provider registry. The generated API key is a non-secret placeholder: Qoder integration requires loopback access and refuses an authenticated non-loopback bind. When the dedicated unauthenticated loopback listener is enabled, exports point Qoder at that listener. `ocx sync` and catalog changes refresh an already enabled Qoder integration like the other managed clients. +Model IDs containing `,` or `]` (for example `kimi/k3[1m]`) are exported like any other model. + +## T3 Code + +[T3 Code](https://github.com/pingdotgg/t3code) drives the Codex and Claude Code CLIs already +installed on the machine. Its Codex threads route through opencodex once the +[Codex integration](/guides/codex-integration/) is enabled, because T3 Code lists Codex models +through `codex app-server`, which reads `$CODEX_HOME/config.toml` like every Codex client. Routed +models then appear under Codex with no T3 Code switch, as long as T3 Code runs Codex with the same +Codex home opencodex manages (`CODEX_HOME`, default `~/.codex`). A T3 Code Codex instance pointed at +another home does not see the routed catalog. + +The **T3 Code** switch adds the Claude side. It needs the Messages API, which every Claude turn +uses: while Messages is off on the API page, enable and refresh are refused, and disable still +works. + +```bash +ocx export --client t3code --json +ocx integration client enable --client t3code +ocx integration client disable --client t3code +``` + +Enable writes one provider instance, `providerInstances.opencodex`, into T3 Code's server settings +and leaves every other instance and setting alone. It is a Claude instance named **opencodex** that +runs your own `claude` binary with `ANTHROPIC_BASE_URL` set to the proxy, the non-secret +`opencodex-proxy` marker as `ANTHROPIC_AUTH_TOKEN`, an explicitly empty `ANTHROPIC_API_KEY`, and +`CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1` so a `settings.json` env block in your Claude config cannot +re-point it. Each routed model is a custom model keyed by its opencodex selector +(`provider/model`), which T3 Code sends verbatim. A model with an effort ladder declares it, so T3 Code offers its effort control and can start a subagent on it at a chosen effort. It appears in T3 Code's model picker under +**opencodex**. T3 Code reloads the file on its own, so no restart is needed; catalog changes and +`ocx sync` refresh the instance. + +T3 Code keeps its data in `T3CODE_HOME` when set, otherwise `~/.t3`. Set the same variable on the +opencodex process if you relocate it; a relative value is refused. On Windows, use a fully qualified +drive path (`C:\shared\t3`) or UNC path (`\\server\share\t3`); paths without a drive, such as +`\shared\t3` or `/shared/t3`, are refused. `~` expands against the effective user home. +The marker is not a credential, so the integration needs loopback access and refuses an authenticated non-loopback bind unless the +unauthenticated loopback listener is enabled. + +Treat the instance as opencodex's. Marking one of its variables **Sensitive** in T3 Code, adding +a custom model to it, or toggling it off rewrites the block. The switch then shows a conflict +instead of overwriting your edit, and **Replace** restores the generated block. To use +different settings, add your own Claude instance in T3 Code beside it. Generated catalogs include only enabled models from each provider selection. This applies to both downloads and managed integrations, including Pi and Aside. The management model list still shows @@ -240,6 +345,12 @@ still reads as installed, while a config-path override moves only the file. If y are still on the older `.clawdbot` layout, that is found too: the modern directory wins when it exists, and the legacy one is used when it is the only one there. +On Windows, overrides requiring absolute paths must include a drive letter +(`C:\Users\me\client`) or a UNC share (`\\server\share\client`). Drive-less +rooted forms such as `\Users\me\client` or `/client/config` are refused because +they depend on the current drive. A selector documented to support `~` still expands +it against the effective home; Gentle Shell does not expand `~`. + These must be **absolute paths** or start with `~`. A relative one is refused rather than resolved, because it would mean whatever directory each process happened to start in — and that path is stored with the backup, so it has to name the same file @@ -299,7 +410,12 @@ parse, or one whose structure we cannot reason about, still refuses. ## Hermes session affinity The generated `providers.opencodex` block includes `session_affinity_header: session-id` for all -models. This names a header; Hermes supplies its dynamic conversation identifier. OpenCodex does +models. Retain this generated default unless you deliberately choose log-only correlation: +changing `session_affinity_header` from `session-id` to `x-hermes-conversation-id` replaces the +header sent by Hermes. Because OpenCodex treats `x-hermes-conversation-id` strictly as a request-log +correlation fallback and not as a native routing or turn-termination identity, switching to +`x-hermes-conversation-id` removes native session affinity and lane assignment while correlating +agent loops in request logs. This names a header; Hermes supplies its dynamic conversation identifier. OpenCodex does not write a shared static identifier or change `api_mode` to enable affinity. Use a Hermes version supporting [per-provider request options](https://hermes-agent.nousresearch.com/docs/user-guide/configuring-models#per-provider-request-options). @@ -318,6 +434,39 @@ exception to the conflict rule above: other edits, a different header name, or a matching ownership record still require conflict resolution. Unrelated YAML settings and comments remain untouched, and the existing snapshot and Restore workflow applies to the upgrade. +## Hermes profiles + +Hermes keeps a separate home for each bot profile. The default profile uses +`~/.hermes/config.yaml` (`%LOCALAPPDATA%\hermes\config.yaml` on Windows, or `$HERMES_HOME/config.yaml`), +and each named profile created with `hermes profile create ` uses +`/profiles//config.yaml`. See Hermes' +[profiles guide](https://hermes-agent.nousresearch.com/docs/user-guide/profiles). + +When named profiles exist, **Connect → Hermes** lists every profile with its own status. Select a +profile to apply, disable, replace, or restore OpenCodex for that profile alone; each profile keeps its +own backups and rollback history, and the other profiles stay unchanged. Every profile keeps its own +`model.default` and other providers: OpenCodex adds only `providers.opencodex`. With no named profiles, +the page works as before and changes the default profile. + +Catalog changes and `ocx sync` automatically refresh only the default profile resolved from the +running proxy's environment (including `HERMES_HOME`). Named profiles keep their previous catalog. +After changing the model selection, open **Connect → Hermes**, select each named profile showing +**Update needed**, and review and confirm **Apply**. The CLI has no named-profile selector. +With an unchanged catalog, refresh stays **Current** after edits to comments or settings outside +`providers.opencodex`; it changes neither the file nor the recorded baseline. When a catalog update +is pending, automatic refresh refuses any Hermes file changed since the last Apply, including those +unrelated edits. When the catalog shows **Update needed**, review and Apply +the pending catalog change to resume automatic updates. Apply with an unchanged catalog is a no-op +and does not accept a new file baseline. + +The management API selects a profile with `profile=` on `/api/client-integrations/hermes` and with +`client=hermes&profile=` on the preview, journal, and restore endpoints; +`GET /api/client-integrations/hermes/profiles` lists the profiles. A directory under `profiles/` counts +only when Hermes would list it: a valid name, a Hermes identity file such as `config.yaml` or `SOUL.md`, +and no deletion marker. A profile reached through a symbolic link or junction is not offered. If +`HERMES_HOME` later points at a different Hermes home, a profile with the same name there is refused +until you disconnect the original one, so OpenCodex never loses track of a file it changed. + ## Preview and confirm changes In the dashboard, Apply, Replace, Disable, and Restore begin with a preview. The dialog shows exactly which @@ -330,14 +479,20 @@ though the managed document does not change. If the file changes after you review it, the write is refused as stale. The dialog replaces the old plan with the updated one and asks you to confirm again; it never retries the write -automatically. If a preview is temporarily unavailable, reload the page normally and start the -action again. +automatically. When a preview reports that no model catalog is loaded yet, the dialog stays open and +offers **Load catalog and retry**: it reads the integration list again — the ordinary load that +retains the catalog, never a preview that gathers models — and then asks for the plan once more. -Aside uses the same preview and confirmation flow for one selected profile at a time. **Sync all -profiles** remains a separate bulk action and is not bound to one combined preview. +Aside uses the same preview and confirmation flow for one selected profile at a time, and a plan +describes exactly that profile's file. Because one plan cannot describe several independently +changing files, the Overview card for a conflicted Aside integration opens **Connect → Aside** with +**Choose profile** rather than a Replace action; replace the block on the profile's own page. **Sync +all profiles** remains a separate bulk action and is not bound to one combined preview. ## What to expect, honestly +If a generated managed path cannot be represented safely, that client reports an unsafe status and its preview refuses the operation. Attempts to apply, overwrite or disable return HTTP 409 without changing the configuration. Other clients remain available. + **Managed configuration files are limited to 4 MiB (4,194,304 UTF-8 bytes).** The shared integration reader refuses larger files as unsafe to read, and the writer refuses a merged configuration that exceeds the same limit with `write_failed`, leaving @@ -406,6 +561,38 @@ ocx integration client history --client hermes ocx integration client restore --op [--confirm-drift] ``` +### Opt-in alias model names + +Hermes and Command Code accept `--model-names alias|routed`. The default is +`routed`, independent of `preferModelAliasIds`. For example: + +```bash +ocx export --client hermes --model-names alias --json +ocx integration client preview --client hermes --operation apply --model-names alias --json +ocx integration client enable --client hermes --model-names alias +ocx integration client enable --client commandcode --model-names alias +``` + +Export is a preview: it uses an already loaded, current catalog and writes no +client configuration or integration state. If that catalog is unavailable, load +the model catalog separately and retry. `--out` explicitly writes an export +artifact; it does not connect the client. + +The connection stores the mode. Omitting the flag on later Apply (including the +dashboard) preserves it; explicit `--model-names routed` resets it. A qualified +alias such as `AC/AC-model-x` replaces `acme/vendor-model-x` only when the router +proves the same provider and model. Missing or unsafe aliases and collisions +fall back to the routed key. Combos retain their existing keys. + +After an alias rename or removal, run `ocx sync` or explicitly Apply the connection: +the next successful managed refresh replaces the old key with the newly validated +alias or routed fallback. Alias edits do not atomically update client files. +Refresh remains idempotent and refuses foreign edits. If an alias changes while +Apply or refresh waits, the write is refused; retry against the current catalog. +Each named Hermes profile +stores its own mode; automatic catalog refresh covers only the default profile, +so named profiles need explicit Apply. Other exporters retain routed names. + ### Preview and bind a terminal write The existing direct commands remain supported. To bind a write to a reviewed @@ -502,10 +689,12 @@ ocx mcode ``` Once connected, `ocx sync` and `POST /api/sync` refresh owned MCode, Pi, Aside, -Raycast, omo, OpenCode, and Kilo catalogs with the current model selection, context windows, and -reasoning-effort ladders. Proxy startup refreshes an owned Raycast catalog. Changes to +Raycast, omo, OpenCode, Kilo, and Hermes catalogs with the current model selection, context windows, and +reasoning-effort ladders. Background catalog changes also refresh the connected Hermes default profile unattended; +an edited Hermes file with a pending catalog update is refused and reported; a never-connected or disabled integration stays untouched. +Named profiles require [explicit Apply](#hermes-profiles). Proxy startup refreshes an owned Raycast catalog. Changes to model visibility, provider selection, or presets also refresh connected Pi, Aside, -Raycast, omo, OpenCode, and Kilo catalogs. +Raycast, omo, OpenCode, Kilo, and Hermes catalogs. Missing, foreign-edited, or unsafe blocks stay untouched, as do previously owned blocks you removed manually. An enabled Aside profile is an exception to the usual owned-only refresh: if its account @@ -746,7 +935,7 @@ every Codex agent role found in `$CODEX_HOME/agents/*.toml`, with the model each to. Codex runs a role on that pin no matter which model the parent asks for, so this is where a role's model is actually decided. LazyCodex counts as installed when the `omo@sisyphuslabs` Codex plugin is enabled in `$CODEX_HOME/config.toml` and an installed copy under -`$CODEX_HOME/plugins/cache/sisyphuslabs/omo/` carries its `lazycodex-install.json`. A `~/.omo` +`$CODEX_HOME/plugins/cache/sisyphuslabs/omo/` carries its plugin manifest or `lazycodex-install.json`. A `~/.omo` folder on its own does not count, because Pi-based omo creates it too. Without LazyCodex the section is hidden and the command line reports it as not installed. Pick a model and a reasoning effort on a row and press Save. A row whose role has no model pin can save an effort on its own; @@ -802,15 +991,43 @@ exists only while LazyCodex is detected. Without it the dashboard shows neither, Auto-assign proposes a model for every role at once. opencodex asks your default Codex model (the root `model` in Codex `config.toml`) one question: for each role, given its -description and the start of its instructions, which capability tier (fast, standard or frontier) -and how much reasoning (glance, measured, thorough or exhaustive) does it need? That model never -picks a model. opencodex then picks the cheapest model from your picker list that reaches the tier: +description and the start of its instructions, which capability tier (fast, standard or frontier), +how much reasoning (glance, measured, thorough or exhaustive) and which task domain (coding, agentic, +reasoning, writing, knowledge or general) does it need? That model never picks a model. opencodex +then picks the cheapest model from your picker list that reaches the tier: - Models listed under `codexRoleTiers` in the opencodex config (`{ "fast": [...], "standard": [...], "frontier": [...] }`) have that tier. +- When two or more of the other models have a published score in the role's domain, those models are + tiered by distinct score values, without requiring a price; equal scores share a tier, and unscored models are left out. Scores come from + [Artificial Analysis](https://artificialanalysis.ai) when you add your own API key + (below). Artificial Analysis no longer publishes a Coding or Agentic Index, so every domain is scored by + its Intelligence Index. The response's `capability` block names the source it used. - Other models with a known price are ranked by price and split evenly across the three tiers. With only one or two priced models, the dearest is frontier and the other, if any, is standard. -- Models with no price and no listed tier are never proposed. List them to include them. +- When tiering falls back to price, models with no price and no listed tier are not proposed. List them to include them. + +To use Artificial Analysis, create a free API key at [artificialanalysis.ai](https://artificialanalysis.ai/data-api/docs) +and set it as a literal, an `${ENV}` reference or a keychain reference: + +```json +{ + "codexRoleCapability": { + "artificialAnalysis": { "apiKey": "${ARTIFICIAL_ANALYSIS_API_KEY}" } + } +} +``` + +opencodex reads the free language model list (`/api/v2/language/models/free`) once per day, one request +per page, which stays inside the free tier's daily request limit. Its terms allow +using the data for your own decisions and forbid passing it on, so auto-assign keeps the scores +internal: the response carries the tier each model got and the attribution, without the scores. If the +key is absent or the read fails, auto-assign uses configured tiers and prices; `capability.error` reports +why and the source attribution fields are null. A retired `huggingFace` setting is ignored. + +Artificial Analysis refuses HTTP redirects, reads at most ten pages and 16 MiB in total, and gives each +request a 30-second timeout; a longer list counts as a failed read. Credentials are sent only to its +fixed API endpoint. Each proposal shows the model, the tier, the reasoning effort, a one-line reason, and what would move it up or down. A role the model could not size clearly is shown as not sized, with the reason, and @@ -826,6 +1043,13 @@ ocx agent roles suggest ocx agent roles suggest --model xai/grok-4.5 --apply ``` +The CLI's `--apply` accepts up to 50 changed roles in one history batch. A larger operation is +refused before any role update; preview it and apply individual choices with `ocx agent roles set`. +An interrupted operation reports confirmed writes and the unconfirmed request, and leaves earlier +writes applied. See the [CLI apply and recovery contract](/reference/cli/agents/) before retrying. + +Under the table, **Change history** lists the newest changes a save, an auto-assign apply or `ocx agent roles set` wrote, newest first, in whole batches and never more than 50, so an Apply all is listed with every role it wrote or not at all, with each role's model and effort before and after. One Apply all is one entry. **Restore** writes the earlier values back through the same save, so a restore is listed too. A save never removes a model pin, so a role that had none keeps its current model and gets only its effort back. The history lives in `integrations/codex-agent-roles.jsonl` under the opencodex config directory, which retains at most 256 KiB and 1000 rows by dropping its oldest whole batches. Compaction targets 128 KiB and preserves a Restore together with its complete source batch when they fit both limits, making room by dropping unrelated older batches; history can still expire as later writes arrive. The writer captures the bounded history before appending so a Restore does not evict its own source at the retention boundary; the omo card's Restore center above tracks only `~/.omo/agent/models.json`. Each change records the Codex home it was made in, and only the current home's changes are listed or restored, so after pointing `CODEX_HOME` elsewhere the list starts empty and a Restore from another home's history is refused. If the history file cannot be read, the section says so in place of the list, and the role table keeps working. + ## Kilo Kilo CLI, VS Code, and JetBrains share one global config. This integration writes @@ -839,6 +1063,9 @@ remove `provider.opencodex` from those files before enabling the integration. An candidate also blocks the write. Disable can still remove a block owned in the recorded file while another candidate conflicts or cannot be parsed; the other candidate is left untouched. +OpenCodex reads these candidate files as JSONC. A `//` line comment ends at a CR, LF, or CRLF +line ending, so a file saved with any of these line endings keeps the settings that follow a comment. + The owned fragment is only `provider.opencodex` (OpenCode V1 shape: `npm`, `options`, `models`). Kilo's published schema has no OpenCode V2 `providers` key, so that block is not emitted; Kilo instead receives the per-model reasoning choices as a variant map inside @@ -854,6 +1081,9 @@ sync`, `POST /api/sync`, and visibility, provider, or preset changes refresh an block under the same safe owned-only rules as every other client, and a new Kilo session loads the updated file. +When reading these candidate files, OpenCodex accepts a trailing comma after an array element or +object property. Write an empty array or object as `[]` or `{}`; `[,]` and `{,}` are refused as malformed. + ```bash ocx integration client enable --client kilo ocx export --client kilo --out ./kilo.jsonc @@ -876,6 +1106,16 @@ whichever one it was written into. form for an endpoint that needs no key. A raw string is refused by Command Code, and no service-token file is read, referenced, or exported by this integration. +**The desktop app needs its own sign-in.** Command Code Desktop never reads the +keyless provider form: before it shows a workspace it checks `~/.commandcode/auth.json` +(or `COMMAND_CODE_API_KEY`) and, finding neither, stops on its sign-in screen. Sign in +there once — or with `cmd login` — and the app stores its own credential. + +opencodex does not write that file. It belongs to Command Code and is shared with real +logins and every other provider's tokens, so enabling this integration only writes +`providers.json`; the placeholder is never written to `auth.json`, and Apply, overwrite, +catalog refresh, and Disable all leave the store byte-for-byte alone. + **Home resolution.** There is no `COMMANDCODE_HOME` override here. The published client resolves `HOME ?? USERPROFILE` and then appends `/.commandcode/providers.json`; it does not consult that variable. An override this integration honoured but the diff --git a/docs-site/src/content/docs/guides/lm-studio.md b/docs-site/src/content/docs/guides/lm-studio.md new file mode 100644 index 0000000000..33b4395229 --- /dev/null +++ b/docs-site/src/content/docs/guides/lm-studio.md @@ -0,0 +1,38 @@ +--- +title: LM Studio strict chat templates +description: Configure one leading system message for LM Studio Chat models. +--- + +The **LM Studio (local)** preset enables `singleLeadingSystemMessage: true` for +the `openai-chat` adapter. This combines text-only system/developer instructions +into one leading system message with blank lines between messages. It supports +custom model IDs, including quantization and checkpoint suffixes, without relying +on the model-name compatibility selector. + +For an existing renamed/custom LM Studio provider, add this boolean explicitly +in the provider editor. The stored value is independent of the provider name, +hostname, and port. A same-destination save preserves an omitted setting; a POST +that replaces the destination must resubmit it. PATCH accepts a boolean or `null` +to clear the override. Clearing it on the canonical LM Studio provider restores +the preset default. + +Set `singleLeadingSystemMessage: false` to disable merging for a template that +accepts chronological instruction messages. Other presets keep their defaults. +`foldDeveloperRoleToSystem` continues to control only the developer role; enabling +single-message compatibility takes precedence over that role choice and the +model-name-based late-instruction workaround. + +Hoisting later instructions changes their chronological scope and can invalidate +prompt-cache prefixes. Translated requests preserve IR instruction order: base +system prompts first, followed by timeline developer instructions. The Responses +parser already collects input system items into the base prompt, so their original +positions relative to developer items are not recovered. Direct Chat passthrough +preserves the original relative order of system/developer messages. Both paths +normalize the outbound copy and keep user messages and tool pairs in order. + +Non-text system/developer parts in direct Chat fail explicitly rather than being +silently discarded. Translated developer documents keep their file parts in a +user-compatible message at the existing timeline slot while their text joins the +leading system message. Developer image/audio messages keep their existing +user-compatible mapping. No LM Studio runtime is required to configure this flag; +the served model's template still determines which other wire features it accepts. diff --git a/docs-site/src/content/docs/guides/minimax.md b/docs-site/src/content/docs/guides/minimax.md index db01d782d7..121bf88c9c 100644 --- a/docs-site/src/content/docs/guides/minimax.md +++ b/docs-site/src/content/docs/guides/minimax.md @@ -13,7 +13,7 @@ the protocol boundary it actually exposes: ## MiniMax Code In the OpenCodex Models page, both MiniMax Coding Plan regions advertise image input for -`MiniMax-M3` and `MiniMax-M3.1-Flash-Preview`. A Combo's **Image / multimodal** switch is +`MiniMax-M3` and `MiniMax-M3.1-Flash`. A Combo's **Image / multimodal** switch is available only when every selected model supports image input. The switch controls image attachments; it does not enable video uploads. diff --git a/docs-site/src/content/docs/guides/model-ordering.md b/docs-site/src/content/docs/guides/model-ordering.md index b3ca477259..35e2b5a6dc 100644 --- a/docs-site/src/content/docs/guides/model-ordering.md +++ b/docs-site/src/content/docs/guides/model-ordering.md @@ -30,8 +30,18 @@ Without complete-picker ordering, the relevant no-selector priorities are: | `subagentModels[i]` | `i` (`0` through `4`) | The featured rank map in `src/codex/catalog/sync.ts` | | Other routed models | `5` | Routed entry creation in `src/codex/catalog/sync.ts` | | Non-featured routed models listed in `modelPickerOrder` | `1000 + i` | Display-only picker rank in `src/codex/catalog/sync.ts` | -| Native GPT slugs by default | `9` | Native entry creation in `src/codex/catalog/sync.ts` | -| Unselected native models while a featured list exists | At least `featured.length + 100` | Native catalog merge in `src/codex/catalog/sync.ts` | +| Native GPT slugs without a featured list | `sourcePriority` (fallback `9`) | Shared native source-priority resolver | +| Unselected native models while a featured list exists | `featured.length + 100 + sourcePriority` | Shared native source-priority resolver | + +Native source priority comes from the current discovered descriptor, then the pristine catalog +backup, then the same model's retained source value, then the upstream snapshot. Each candidate +must be an integer from `0` through `1000`; invalid values are skipped and the final fallback is +`9`. Published display priorities are never reused as source priorities. With four featured +models, native source priorities `3`, `8` and missing become `107`, `112` and `113` respectively. +This preserves native source order behind featured and ordinary routed rows, including after +repeated sync or featuring and later unfeaturing a native. The live Codex model list, published +catalog and models cache use the same priorities for the same inputs. Account-selector groups +retain their separate stride policy; complete-picker ordering remains the final override. The management API limits `subagentModels` to five entries with `slice(0, 5)` in `src/server/management/agent-settings-routes.ts`. This matches the Codex `spawn_agent` surface, which @@ -73,7 +83,7 @@ With no eligible account selectors and a non-empty featured list, the resulting 3. Unselected native models, pushed below the featured block during catalog merge. Without `subagentModels`, routed models remain at priority `5`, native GPT entries use their normal -priority (normally `9` for entries built by opencodex), and the routed group remains provider/id +source priority (fallback `9`), and the routed group remains provider/id alphabetical. ## Example @@ -101,7 +111,7 @@ The picker begins as follows: | 5 | `gpt-5.6-terra` | `4` | Fifth selection | | 6 | `anthropic/claude-fable-5` | `5` | First remaining routed id in provider/id alphabetical order | | 7 onward | Remaining routed models | `5` | Provider alphabetically, then model id alphabetically | -| After routed models | Remaining native models | `featured.length + 100` or higher | Unselected natives are moved below the featured block | +| After routed models | Remaining native models | `featured.length + 100 + sourcePriority` | Source order is preserved within the native band | The first five entries are the overrides advertised to `spawn_agent`; the rest continue in the normal picker order. With account selectors, the five-entry limit applies after bare native choices diff --git a/docs-site/src/content/docs/guides/model-routing.md b/docs-site/src/content/docs/guides/model-routing.md index 9c7e8bc573..772a078eb7 100644 --- a/docs-site/src/content/docs/guides/model-routing.md +++ b/docs-site/src/content/docs/guides/model-routing.md @@ -82,7 +82,18 @@ Routing and catalog visibility are separate controls: for that model. - A provider's non-empty `selectedModels` is another catalog allowlist. Live discovery and direct routing still work; only catalog and `/v1/models` emission are narrowed. -- `modelDiscovery.newModelPolicy` defaults to `"off"`, including when omitted in an existing configuration. On the first successful live discovery, only the configured `defaultModel` starts visible; without a matching default, enable the models you need in **Models**. Saved model selections, per-model switches and short existing baselines are preserved. An existing unselected live catalog with at least 20 models and a configured default is narrowed to that default once; existing baselines without a default retain their visibility; later manual changes are not reset. Static/manual catalogs are unchanged. Later arrivals remain hidden until enabled. Explicit `"on"` opts into automatic exposure. This policy applies before `/v1/models`, client exports and Codex catalog publication; failed discovery changes no choices. Use `ocx models new-policy off` (optionally `--provider `) and `ocx models new-arrivals --json`. +- Fresh installs set `modelDiscovery.newModelPolicy` to `"off"`. After the first successful live + fetch establishes a baseline, later arrivals are appended to `disabledModels` and carry a **NEW** + dashboard badge until enabled or acknowledged. Existing installs remain `"on"` until opted in. + The policy applies before publishing newly discovered models through `/v1/models`, the dashboard, + client configuration exports, or a Codex catalog sync (including service startup). + Enabling an arrival manually keeps it enabled on later refreshes and exports. + If the running provider configuration differs from disk, model lists still apply the policy + using a temporary projection; they leave the running configuration and saved choices untouched. + Use `ocx models new-policy off` globally, add `--provider ` for an override, and inspect + `ocx models new-arrivals [--json]`. Failed/degraded fetches never change the baseline. Providers + with a non-empty `selectedModels` (including preset mode) are already curated, so this policy is + deliberately inert for them. - `provider.disabled: true` removes that provider from catalog discovery. Explicit `provider/model` requests fail, and `defaultModel` / `models[]` scans skip it. - Routed catalog rows are cloned from the Codex-native template, so native-only delivery flags are diff --git a/docs-site/src/content/docs/guides/ollama-clients.md b/docs-site/src/content/docs/guides/ollama-clients.md new file mode 100644 index 0000000000..7e4f1534ca --- /dev/null +++ b/docs-site/src/content/docs/guides/ollama-clients.md @@ -0,0 +1,73 @@ +--- +title: Ollama-compatible clients +description: Point tools that speak the Ollama API at opencodex and use your configured provider models. +--- + +opencodex answers a subset of the Ollama HTTP API, so a tool that only knows how to talk to Ollama +can use the models you already configured in opencodex. Requests are translated onto the Chat +Completions path and sent to the selected provider. opencodex does not download, store or run +models on your machine. + +## Connect a client + +Use the proxy address as the Ollama host. For a default local install: + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +When the proxy requires an API key (for example on a `0.0.0.0` bind), send it the same way as for +`/v1/chat/completions`, for example `Authorization: Bearer `. A key with a model +scope only sees and uses the models it is allowed to. The endpoints are served on the main listener +only; the unauthenticated loopback listener, Remote Link and the hub management ingress do not +expose them. + +## Endpoints + +| Endpoint | Behavior | +| --- | --- | +| `GET /api/version` | The opencodex version. | +| `GET /api/tags` | Configured provider models as `provider/model` names. | +| `POST /api/show` | `{ "model": "provider/model" }` returns only known facts; no file size, digest, template or license. | +| `POST /api/chat` | Chat with `system`, `user`, `assistant` and `tool` messages. | +| `POST /api/generate` | Single prompt with optional `system`. | + +Every other `/api/*` path stays part of the opencodex management API. + +## Supported request fields + +- `model`: a name from `/api/tags`. +- `stream`: defaults to `true` (newline-delimited JSON). Set `false` for one JSON response. +- `images`: base64 PNG, JPEG, GIF or WebP on user messages (chat) or the request (generate). +- `tools` (chat only): function tools. Send the assistant message back unchanged, including each + call's `id`; a `tool` result is matched by `tool_call_id` or, failing that, by `tool_name`. +- `options`: `temperature`, `top_p`, `num_predict` and `stop`. +- `format`: `"json"` only. + +Each `/api/chat` request accepts at most **1,024 tool calls in total** across all assistant messages, +including calls that already have tool results. Above this limit, the request returns HTTP 400 +before reaching a provider. Shorten the conversation history and resend it, keeping each retained +tool result together with its corresponding assistant tool call. + +Anything else is rejected with HTTP 400 instead of being ignored. That includes `think`, +`keep_alive`, `suffix`, `raw`, `template`, `context`, other `options`, JSON-schema `format` and image +URLs. Ollama's model-management and embedding endpoints are not provided. + +Combos, routing policies, `--fast` or effort aliases, and providers that forward the caller's own +credentials cannot be selected here. Requests for them fail before anything is sent upstream. + +## Responses + +A finished reply carries `done: true` with `done_reason` set to `stop`, `tool_calls` or `length`. +`prompt_eval_count` and `eval_count` appear when the provider reported usage; duration fields are +not reported. A stream sends exactly one `done: true` line, after the upstream reply has fully +completed. + +Errors use the Ollama shape `{ "error": "message" }` and keep the HTTP status, including +`Retry-After` on rate limits and busy refusals. A reply stopped by a content filter or for an unknown +reason is returned as an error, never as a normal stop. If a stream fails after it started, its last +line is an `error` object and no `done: true` line follows. + +Requests appear in the dashboard request log like other traffic, and the response header +`x-opencodex-request-id` names the matching row. diff --git a/docs-site/src/content/docs/guides/opencode.md b/docs-site/src/content/docs/guides/opencode.md index cc61a911c5..0465f6b079 100644 --- a/docs-site/src/content/docs/guides/opencode.md +++ b/docs-site/src/content/docs/guides/opencode.md @@ -93,6 +93,8 @@ read global or project config to detect a provider override — under `provider. or `providers.opencodex` — while your existing providers, agents, keybinds, MCP entries, and relative `{file:…}` references keep resolving from their original files. +The JSONC reader accepts a single leading UTF-8 byte-order mark (BOM), as emitted by some Windows editors. BOM characters inside strings remain unchanged. + For this launch only, opencodex adds both generated blocks — `provider.opencodex` and `providers.opencodex` — through OpenCode's inline runtime layer. That layer merges after global/custom/project config and overrides only conflicting keys for the child process. @@ -201,6 +203,43 @@ CLI export, dashboard export, managed refresh and the launcher share the effecti The `opencodex` provider block is regenerated on every launch, so per-model tweaks made inside it will not survive. Keep custom entries under a provider key of your own instead. +## Slow local models (prefill timeouts) + +opencode waits a bounded time for the first response header from a provider (five minutes by +default in current V2), and a separate, longer bound between streamed chunks. Behind the +`opencodex` provider, a local model (LM Studio, vLLM, +Ollama, or any self-hosted endpoint) can spend longer than that in prompt *prefill* on a large +prompt — processing the prompt before it emits a single token. On a non-streaming turn the proxy +sends opencode nothing until the upstream completes, so opencode's own header wait fires first and +the turn fails with `Timed out waiting for response headers`, even though the model is still +working. + +Because the generated `opencodex` provider multiplexes every routed upstream under one block and +opencode's timeouts are provider-wide, raise or disable the wait for the whole provider with +`opencodeClientExport` in your opencodex config. It is omitted by default, so opencode keeps its +native waits (header and the longer chunk bound) unless you opt in: + +```json +{ + "opencodeClientExport": { + "headerTimeoutMs": false, + "chunkTimeoutMs": 1800000 + } +} +``` + +| Field | opencode setting | Meaning | +| --- | --- | --- | +| `headerTimeoutMs` | `settings.headerTimeout` | Wait for the proxy's first response header. A number of milliseconds, or `false` to disable. | +| `chunkTimeoutMs` | `settings.chunkTimeout` | Wait between streamed response chunks. A number of milliseconds, or `false` to disable. | +| `timeoutMs` | `settings.timeout` | Whole-request bound. A number of milliseconds, or `false`. opencode applies no default. | + +Each value is emitted verbatim into both the `provider.opencodex` (`options`) and +`providers.opencodex` (`settings`) blocks. Disabling `headerTimeout` removes opencode's safety net +against a genuinely hung proxy for every model routed through it, so prefer a large explicit value +(for example `1800000` for thirty minutes) unless you specifically want no bound. A malformed value +is dropped and opencode keeps its native default rather than failing to load. + ## Requirements opencode must be installed and on `PATH`: diff --git a/docs-site/src/content/docs/guides/pi.md b/docs-site/src/content/docs/guides/pi.md index 03b1886a8e..741b56d429 100644 --- a/docs-site/src/content/docs/guides/pi.md +++ b/docs-site/src/content/docs/guides/pi.md @@ -147,12 +147,14 @@ An explicit reasoning effort of `none` survives Chat conversion. Output limits a controls are preserved for generic API-key Responses targets; the canonical ChatGPT target still applies its own restrictions. This does not make all providers' controls equivalent. -**Audio and most file attachments need a native input wire that supports them.** A document -that carries its own base64 bytes in a user message is the exception: it survives translation -and reaches the Anthropic, OpenAI Chat and Google wires as a native document, file part and -inline data part. Everything else still returns an explicit error rather than succeeding -without the attachment — audio, a file-ID or remote reference the proxy cannot dereference, an -attachment in a tool output or a system message, and a document routed to a wire with no byte +Inline WAV/MP3 audio in a user message or tool result survives translation to OpenAI Chat as an +`input_audio` content part; tool-result audio is promoted into a follow-up user message after +the paired tool results because Chat tool messages are text-only. A document that carries its +own base64 bytes in a user message is also carried: it reaches the Anthropic, OpenAI Chat and +Google wires as a native document, file part and inline data part. Everything else still +returns an explicit error rather than succeeding without the attachment — remote or +unsupported audio, a file-ID or remote reference the proxy cannot dereference, an attachment +in a system message, a document in a tool result, and a document routed to a wire with no byte carrier. File-ID-only images have the same restriction because translated adapters cannot resolve those IDs. Convert the attachment to text first, or use a native wire and model that support it. Native Chat and raw Responses (including Azure) retain their existing behavior; diff --git a/docs-site/src/content/docs/guides/protocol-paths.md b/docs-site/src/content/docs/guides/protocol-paths.md index 9c79f5699a..ffe4788dbb 100644 --- a/docs-site/src/content/docs/guides/protocol-paths.md +++ b/docs-site/src/content/docs/guides/protocol-paths.md @@ -99,10 +99,10 @@ These switches stage the new paths. Each defaults to off except `antigravityDire | Switch | When on | | --- | --- | | `nativeChatCombos` | An eligible Chat candidate inside a combo is sent natively from its own copy of the client body; the other candidates keep the bridge. | -| `managedMessagesNative` | A Messages request whose route is a direct, key-authenticated Anthropic provider is sent as Messages instead of through the bridge. Routes that need bridge-only behaviour (a pinned effort, blocked-skill elision, the web-search sidecar, vision preprocessing, synthetic rows) stay on the bridge. | -| `managedMessagesNativeOAuth` | Native Messages for the unpooled `anthropic` OAuth provider on `api.anthropic.com`. Effective only together with `managedMessagesNative`; a pooled Anthropic OAuth account set stays on the bridge. | +| `managedMessagesNative` | Send eligible direct Anthropic routes and key-auth Anthropic-compatible or first-party Anthropic children of strict failover combos as Messages. Combo defaults/effort rewrites and bridge-only behaviour (pinned effort, blocked-skill elision, web-search sidecar, vision preprocessing, synthetic rows) retain the bridge. | +| `managedMessagesNativeOAuth` | Extend native Messages to configured Anthropic OAuth instances on `api.anthropic.com`, including stored account pools and eligible failover children. Effective only together with `managedMessagesNative`. | | `directEncoders` | For a non-Responses upstream, the answer to a Chat or Messages client is encoded directly from the adapter's events instead of through the internal Responses stream. The request side is unchanged. | -| `antigravityDirect` | **On by default**; set it to `false` to turn it off. A Chat or Messages request whose route is one Google Antigravity provider skips the internal Responses body in both directions: the conversation is decoded from the client body straight into what the Google adapter compiles from, and the answer is encoded directly as with `directEncoders`. The path reads `chat -> ir -> other` or `messages -> ir -> other`. Request settings (model, effort, limits, tool choice) still pass through the usual policies, so account rotation, effort rules and usage are unchanged. Combos, policies, a hosted web-search tool, images for a model marked text-only, a model the shadow-call intercept could rewrite, and text the proxy rewrites (a skills catalog, a generated-image link) stay on the bridge, and the log row names the reason. | +| `antigravityDirect` | **On by default**; set it to `false` to turn it off. A Chat or Messages request whose route is one Google Antigravity provider skips the internal Responses body in both directions: the conversation is decoded from the client body straight into what the Google adapter compiles from, and the answer is encoded directly as with `directEncoders`. The path reads `chat -> ir -> other` or `messages -> ir -> other`. Request settings (model, effort, limits, tool choice) still pass through the usual policies, so account rotation, effort rules and usage are unchanged. Combos, policies, a hosted web-search tool, images for a model marked text-only, a model the shadow-call intercept could rewrite, and text the proxy rewrites (a skills catalog, a generated-image link) stay on the bridge, and the log row names the reason. On a Chat request the decoded conversation counts toward the shared translation budget, so a request whose retained IR exceeds it is refused with HTTP 413 and `translation_buffer_limit` before anything goes upstream. | | `shadowPlan` | At the end of each Chat or Messages request, the plan a preview would have predicted is compared with the path the request took; a disagreement adds `planMismatch: true` to the log row's path record. No second request is sent. | Change them with the CLI or by editing `protocols` in `config.json` @@ -135,8 +135,14 @@ These paths still use the internal Responses bridge or are not covered: - Chat and Messages requests are still decoded into a Responses-shaped body before the IR, including on a translated path. The exception is a Chat or Messages request to a single Google Antigravity route, unless `antigravityDirect` is set to `false`. -- Routing-policy candidates, combos reached through an effort row, combo candidates while - `nativeChatCombos` is off, and Messages combos. +- Routing-policy candidates, combos reached through an effort row, and Chat combo candidates while + `nativeChatCombos` is off. Messages combos retain the bridge except eligible Anthropic key-auth compatible or first-party + children of strict failover combos without a default effort. Each eligible child starts from the + source Messages envelope, preserving system/messages/tools/cache breakpoints under the existing + native allowlist and credential rules. Without explicit operator retention, TTL-less combo + breakpoints stay TTL-less. Pre-output retryable errors may fall back; any content/tool block + commits the child and forbids replay. Every child enforces the caller's model/provider scope. + Preserved prefixes do not prove live cache hits. - Direct encoding (`directEncoders`) covers only a concrete, non-Responses route in streaming delivery. Combo and policy children, routed compaction, run-turn adapters (Cursor, Devin, coding-agent CLIs, CodeBuddy), and sidecar turns keep the bridge. @@ -153,8 +159,8 @@ These paths still use the internal Responses bridge or are not covered: their current behavior. Headers alone do not authorize requests or establish official support. The TypeScript Agent SDK's `sdk-ts` user-agent entrypoint is recognized with the same required identity headers, preserving its allowlisted native feature betas on first-party Anthropic requests. -- Native Chat over OAuth is not planned. Native Messages over Anthropic OAuth covers only an - unpooled account; a pooled account set stays on the bridge. +- Native Chat over OAuth is not planned. Native Messages over Anthropic OAuth includes pooled + accounts under the same native eligibility and credential-binding rules. - The managed native Messages path forwards a caller's `anthropic-beta` values only from a short allowlist and only to `api.anthropic.com`, drops top-level fields outside its allowlist without a feature effect, and does not apply diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index 6dc0dbdbac..4859df3100 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -13,6 +13,9 @@ These links preserve the preset's referral parameters. Sponsor information is sh the configured provider name, adapter and endpoint match the preset; it never changes routing, account selection or defaults. +While a provider login is in progress, its Accounts panel offers **Cancel** once sign-in +instructions appear. + ## OpenAI account modes | Provider id | Use | Credential/account rule | @@ -52,6 +55,8 @@ reset is expected to recover as `+N% pool capacity`. **Incomplete coverage** mea accounts could not safely contribute to the estimate, for example because their plan or quota is unknown, their reading is stale, or the account is paused or needs reauthentication. +Business Premium seats reported as `self_serve_business_prolite` count as five Standard-seat units in this estimate. This display weight does not select accounts or create a five-hour window when the upstream reports only weekly usage. The calibration follows the [official Business usage limits](https://help.openai.com/en/articles/12003714-chatgpt-business-models-and-limits), checked 2026-10-20; unknown plans continue to count at the baseline with the unknown-plan count disclosed. An enabled Anthropic OAuth account pool with two or more accounts gets the same kind of estimate, every routable account weighted equally: inactive accounts use their last measured reading (no extra usage requests), paused, reauthenticating or stale accounts count as incomplete coverage, and with the pool off or one account the row shows the active account's own reading as before. + A **partial window coverage** warning means some included accounts reported one quota window but not another. The overview keeps those windows separate and marks each affected window incomplete instead of treating the missing reading as usage for that window. @@ -60,14 +65,14 @@ This estimate is display-only. It does not change account selection, session aff switching, cooldowns, or any other routing decision. Use the [Codex Auth account pool](/guides/web-dashboard/#codex-auth-and-account-pools) for the individual account state and routing controls. -Shipped v1 configs migrate automatically to marker 2 and one option-aware row. The original config -is retained once at `~/.opencodex/config.json.pre-openai-tiers-v2.bak`; restore it with -`cp ~/.opencodex/config.json.pre-openai-tiers-v2.bak ~/.opencodex/config.json`. +Shipped v1 configs migrate automatically to marker 2 and one option-aware row. The original config is retained once at `~/.opencodex/config.json.pre-openai-tiers-v2.bak`; restore it with `cp ~/.opencodex/config.json.pre-openai-tiers-v2.bak ~/.opencodex/config.json`. + +[Claude OAuth client-version errors](/guides/claude-code/#claude-oauth-client-version-errors) ## Claude Opus 5.5 progress updates When the `anthropic` adapter sends Claude Opus 5.5 to `api.anthropic.com` (OAuth or API key), -OpenCodex requests Anthropic's [progress-update display mode](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates). +OpenCodex defaults to Anthropic's [progress-update display mode](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates). Progress updates and mid-turn acknowledgements appear as visible assistant commentary in Codex, even when thinking summaries are hidden. Reasoning summaries are omitted in this mode because Anthropic cannot distinguish progress updates from reasoning under `display: "summarized"`. @@ -75,6 +80,14 @@ The original signed thinking blocks are preserved for tool continuation; no sign or rewritten. Updates appear once their signed block completes. Other models and compatible third-party endpoints retain their existing thinking display behavior. +To request summarized thinking instead, explicitly send `reasoning.summary: "concise"` or +`"detailed"`. OpenCodex then sends `thinking: {type: "adaptive", display: "summarized"}` without +the updates beta and returns thinking text as reasoning instead of progress commentary. In this +mode, Anthropic's progress updates may be folded into the reasoning summary. The choice also +works when reasoning effort is omitted or `"none"`; it does not change the requested effort. +Omitting `reasoning.summary` or sending `"auto"` (the Codex default) or `"none"` keeps the updates default. Local summary hiding +still controls reasoning visibility and does not hide progress commentary in updates mode. + ## Anthropic image input The built-in Claude model seeds advertise text and image input for both `anthropic` (OAuth) and @@ -82,8 +95,11 @@ The built-in Claude model seeds advertise text and image input for both `anthrop Explicit per-model input-modality overrides remain authoritative; unknown models are not assumed image-capable. This applies across integrations wherever the client's configuration supports image capability metadata: OpenClaw exports a declared `input` array, and Kimi Code exports -`capabilities: ["image_in"]` only for image-capable models. OpenClaw omits `input` when no supported -modalities are declared; Kimi omits `capabilities` for unknown or text-only models. Clients without +`capabilities: ["image_in"]` only for image-capable models, adding `"thinking"` when the model +declares an effort ladder. Kimi Code also receives that ladder as `support_efforts` (limited to +`low`, `medium`, `high`, `xhigh` and `max`, in that order) and the declared default as +`default_effort` when it is in the ladder. OpenClaw omits `input` when no supported modalities are +declared; Kimi omits `capabilities` for models that declare neither image input nor an effort ladder. Clients without a supported capability field keep their existing configuration shape. After updating opencodex, regenerate or refresh the client configuration managed by opencodex to receive the updated metadata. @@ -107,6 +123,12 @@ identity for five minutes. Only the refused opaque payloads are suppressed when identified; newly issued thinking remains replayable. Plaintext history remains available; a failed or cancelled retry does not disable thinking replay on later requests. +## xAI Responses includes + +For xAI Responses requests, OpenCodex removes the unsupported `output.encrypted_content` entry +from `include`, including on the [US regional endpoint](https://docs.x.ai/developers/advanced-api-usage/regions). +Other include entries are preserved; an empty result omits the field. Other providers are unaffected. + ## Auth modes Provider configs accept three `authMode` values (`key` is the default). The built-in registry also @@ -121,8 +143,60 @@ labels local presets separately; those normally omit both `authMode` and `apiKey The [`retryOn429`](/reference/configuration/) same-key 429 replay applies only to API-key providers (`authMode: "key"`). OAuth, forward, and local presets are excluded — their credentials must never be replayed on the same token, and local runtimes have no remote key to -preserve. It is opt-in: when the option is absent the feature is off; object presence enables -it unless `enabled: false`. +preserve. It is opt-in except for documented destination-specific defaults. Canonical Mistral +Chat uses a patient retry policy (6 replays, 10-second fallback interval), within the +existing request-wide send allowance. Explicit `retryOn429` settings, including +`enabled: false`, take precedence. The Mistral preset also forwards supplied prompt-cache +keys by default; `promptCacheKey: false` disables forwarding. Cache affinity improves the +chance of reuse, but does not guarantee a cache hit or remove token-throughput limits. + +Mistral uses one API-key provider for both Studio and Vibe keys. Key types and plan allowances +are described in [Mistral's API-key documentation](https://docs.mistral.ai/admin/identity-access/api-keys); +the proxy does not infer a subscription tier from the key. At `https://api.mistral.ai/v1`, the dashboard +reads API and Vibe budgets from `/v1/billing/budget` and the plan from `/v1/billing/subscription`, +using the inference credential and egress. Measured windows show usage, total and recognized plan name. +Budgets are display-only: they do not rank keys, route or pause traffic, or enter the quota pool. +Missing, malformed or non-positive budgets, malformed currencies and out-of-range percentages are unknown; +unknown plan names are omitted. Fresh last-good readings survive 402, 408, 429, 5xx and transport failures, +but 401, 403 and other non-retryable client refusals suppress them. For every model, explicit upstream +`Retry-After` deadlines are shared between calls on the same credential and model. A 429 +without a retry time can activate a conservative 60-second recovery wait when valid minute +counters show exhausted capacity, or the refused query's measured cost exceeds the remaining +tokens while fitting the full advertised allowance. This is a local recovery policy, not an +exact server-reset prediction. Healthy traffic never predicts the next query's cache or cost. +After the wait, one recovery probe runs; success restores ordinary traffic. Missing, malformed, +zero-entitlement, exhausted-monthly, or above-full-allowance evidence does not invent a reset or compact history. +`requestPacing: { "enabled": false }` or `retryOn429: { "respectRetryAfter": false }` +disables shared pacing. If Mistral's +retry time exceeds `retryOn429.maxIntervalMs`, the proxy returns the 429 and retry hint rather +than replaying early. Context windows and per-model compaction preferences remain independent. + +Mistral accepts a different set of `reasoning_effort` values for each model and refuses the +rest with HTTP 400 (or 422 for `ultra`). The preset ships the accepted rungs as registry +`modelReasoningEfforts` rows. Client exports such as `ocx export --client opencode` offer only +these variants. The Codex catalog still adds its synthetic `ultra` rung, plus `max` where a +model's list omits it, and requests clamp those to the highest listed rung: + +| Model | Efforts | +|---|---| +| `zai-glm-5-3`, `zai-glm-5-3-flash` | `low`, `high`, `max` | +| `mistral-large-4`, `mistral-large-4-0` | `low`, `medium`, `high` | +| `deepseek-v4-1-flash-1017` | `low`, `high`, `xhigh`, `max` | + +The GLM and Large 4 rows follow [Mistral's reasoning guide](https://docs.mistral.ai/capabilities/reasoning). +Mistral documents no values for DeepSeek V4.1 Flash 1017, so its row is the set measured to +answer HTTP 200 in November 2026 and may change. A `modelReasoningEfforts` entry of your own +for a model replaces its row. + +On native Chat Completions, for a model with reasoning enabled, a caller's `ultra` is sent as `max`, or as the model's highest +declared rung below `max` (`high` on Large 4). This applies to every `openai-chat` provider +unless the model's declared ladder lists `ultra` itself. A `reasoningEffortMap` alias for `max` +applies to the folded value, and `__omit__` drops the effort field. On models with independent +thinking and effort controls, the effort still selects the thinking switch; legacy thinking-toggle +wires keep their existing discriminator mapping. Models with reasoning disabled (for +example `noReasoningModels`) drop `reasoning_effort` entirely. Other caller values are forwarded +as sent unless an effort pin or a qualifying effort cap rewrites them; rewritten values also go +through the provider's wire mapping. When round-robin key selection is enabled, queued requests recheck key cooldowns before sending and acquire pacing capacity for any replacement key. This applies to native Chat, Messages, Responses and compact. Waiting for replacement-key capacity does not consume the upstream response-header timeout. Per-key pacing and round-robin use guarded HTTP/SSE even when upstream WebSockets are enabled; WebSocket-only steering and injection require a route without those key policies. This does not change the saved active key. An established upstream turn keeps its credential; later sends are refused if that key cools. Pre-output key rejection can recover to a healthy key within the existing request limit. Direct Images and compact requests record genuine 401/429 cooldowns without replaying that paid POST. @@ -174,10 +248,22 @@ Two exceptions are worth knowing because you can hit them: | OrcaRouter | `ocx login orcarouter-oauth` — consent mints a user-owned, long-lived `sk-orca-…` key, and the request then carries a key | `orcarouter` — the same key pasted by hand | | Meta Muse | `ocx login meta-muse` can import a local Muse Code CLI key or start device login. Meta scopes that credential to its own CLI, so this is an unsupported use: how the calls settle is not observable from the API, and you should treat every call as billable against your account | `meta-model` is the supported path — every call is metered per token, and a Muse Code subscription does not work there | +When the Grok subscription catalog publishes selectable context windows, opencodex uses the +widest published rung: `[256000, 500000]` exposes 500k for Grok 4.5–4.7, including the 4.7 Fast +lane. Your configured model window and enabled Context cap still lower that value. If your plan +serves a shorter window, configure that limit; the catalog does not verify account entitlement. + Cursor, Kiro, Zed Hosted AI and Nous Portal are login-only and have no API-key equivalent. Google Antigravity is login-only too: `ocx login google-antigravity` signs in with your Google account over the Cloud Code Assist wire, and the `google` preset beside it is the AI Studio Gemini API — a different product reached with its own key, not a key mode for the same login. +If Antigravity login cannot discover a Cloud Code Assist project, the failure includes a sanitized +summary for `loadCodeAssist` and the last `onboardUser` response: HTTP status, response category, +completion/error presence and known project-field types. It distinguishes HTTP refusal, unusable +JSON, invalid roots, unfinished onboarding and completion with an error or without a project. +The summary omits upstream values, arbitrary key names and account/project identifiers. Login +still requires a discovered project and saves no account when discovery fails. + The Antigravity Accounts tab shows an observed membership tier as a badge beside the account label, using the upstream tier ID (for example `free-tier` or `gemini-pro`). No badge appears when the plan is unknown; it does not affect routing or quota. @@ -219,9 +305,25 @@ account's own model discovery, because Google enables models per account: some a Claude Sonnet 4.6 and Claude Opus 4.6 (Thinking), others only Claude Opus and Sonnet 5.5 (directly billed, non-trial Pro or Ultra plans), and Gemini 4 Argon only on Ultra and Enterprise. Both Claude generations map: 4.6 takes its effort as a thinking level, 5.5 as its `-low`, `-medium`, or -`-high` model. With several Antigravity accounts and `oauthAccountFailover.enabled`, a request -prefers an account whose discovery lists the requested model. Saved selections of models that left -the list keep routing as before. +`-high` model. + +Antigravity requests go only to accounts that may serve the requested model. OpenCodex remembers +each account's model list from that account's own discovery, in memory, for six hours. An account +whose list includes the model is preferred; an account with no current list (not yet discovered, +expired, or forgotten by a restart) is still used, because nothing proves it lacks the model. An +account whose current list omits the model is never sent the request, including on 429 and +authentication failover. If the selected account omits it and `oauthAccountFailover.enabled` is on, +the request moves to another account that is not paused or awaiting reauthentication. Otherwise +OpenCodex refuses the request locally with HTTP 403 `permission_denied` and sends nothing upstream: + +- `The selected Google Antigravity account does not list the model "" in its model discovery. Select an account that lists it, or enable oauthAccountFailover so OpenCodex can choose one.` + Another usable account may serve the model, but failover is off. +- `The selected Google Antigravity account does not list the model "" in its model discovery, and no account that may serve it could be used for this request. Retry the request.` + Failover is on and chose another account, but that account could not be used for this request. +- `No usable Google Antigravity account lists the model "" in its model discovery. Choose a model your accounts list, or add an account that has access to it.` + Every usable account's current list omits the model. + +A saved selection of a model that left the list follows the same rule. To check which mode a provider is actually using, open it on the Providers page: the **Connection** block's **Authentication** row reads `OAuth`, `API key`, `ChatGPT passthrough`, `Local`, or @@ -281,10 +383,10 @@ ocx logout | --- | --- | --- | --- | | `xai` | `openai-chat` | `https://cli-chat-proxy.grok.com/v1` | OAuth uses the separate Grok CLI subscription gateway. The API-key override uses `https://api.x.ai/v1` and may inject Priority Processing. Live-first Grok catalog; `grok-4.5` is the fallback default. | | `anthropic` | `anthropic` | `https://api.anthropic.com` | Claude models; live model list fetched from `/v1/models`. | -| `kimi` | `openai-chat` | `https://api.kimi.com/coding/v1` | Kimi Code Plan coding models. Defaults to the stable `kimi-for-coding` alias (currently K2.8 Preview): 1M-token context window, adjustable `low`/`high`/`max` thinking (default `max`), text + image input. Retired `kimi-k2.x` selections are migrated to the alias on upgrade. | +| `kimi` | `openai-chat` | `https://api.kimi.com/coding/v1` | Kimi Code Plan coding models. Defaults to the stable `kimi-for-coding` alias (currently K2.8 Preview): 1M-token context window, adjustable `low`/`high`/`max` thinking (default `max`), text + image input. `k3.1-pro` and `k3.1-pro-highspeed` (K3.1 Pro) are also listed: 1M-token context, thinking-only on the same ladder (default `max`). Retired `kimi-k2.x` selections are migrated to the alias on upgrade. | | `kimi-responses` | `openai-responses` | `https://api.kimi.com/coding/v1` | Same Kimi account login (reuses the `kimi` OAuth credential) over the OpenAI Responses wire. Same model roster and capabilities as `kimi`; thinking content stays encrypted server-side, tool calls and results stay visible. | | `nous` | `openai-chat` | `https://inference-api.nousresearch.com/v1` | Nous Research subscription gateway (same backend Hermes Agent uses). Device-grant login against `portal.nousresearch.com`; the access token is the per-request inference JWT. Mixed paid + `:free` model catalog (`tencent/hy3:free`, `stepfun/step-3.7-flash:free`, ...) discovered live from the signed-in account. Refresh tokens are single-use and rotated on every refresh. | -| `kiro` | `kiro` | `https://runtime.us-east-1.kiro.dev` | The dashboard Login and Add account buttons offer Builder ID, Google, GitHub device login, or Kiro CLI. Native device login adds an account without signing `kiro-cli` out. The Kiro CLI choice imports or starts a CLI session; its Add account workflow temporarily switches the CLI account and restores it on cancellation or failure. | +| `kiro` | `kiro` | `https://runtime.us-east-1.kiro.dev` | The dashboard Login and Add account buttons offer AWS IAM Identity Center, Builder ID, Google, GitHub device login, or Kiro CLI. Native device login adds an account without signing `kiro-cli` out. The Kiro CLI choice imports or starts a CLI session; its Add account workflow temporarily switches the CLI account and restores it on cancellation or failure. | | `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth over the Cloud Code Assist wire. Live discovery uses CCA's authenticated `v1internal:fetchAvailableModels` endpoint and publishes the agent models available to the signed-in account; the maintained catalog remains the fallback. | | `cursor` | `cursor` | `https://api2.cursor.sh` | Experimental PKCE login, live HTTP/2 transport with an opt-in HTTP/1.1 compatibility path, and account-filtered model discovery. | | `zed` | `zed` | `https://cloud.zed.dev` | Experimental Zed Hosted AI bridge. Uses Zed's native-app RSA callback, exchanges the account token for a short-lived hosted-inference token, and discovers the account's live roster. | @@ -340,6 +442,13 @@ revokes it, run `ocx login zed` again. For Zed-hosted OpenAI models, OpenCodex translates `developer` instructions to `system` messages and removes OpenAI-private fields and unsupported built-in tools such as `web_search`. Function and custom tools remain available through the delegate; a tool choice with no supported tools left becomes `none`. +Current-turn tool declarations carried in Codex's `additional_tools` input are promoted into the +supported tool catalog. Function calls and custom-tool input are relayed in order, including +interleaved calls, so a tool-using turn can continue after its introductory text. Incomplete calls +keep only received arguments and remain incomplete; cancellation releases buffered data. Conflicting +completed custom input, including later deltas, fails the turn with incomplete calls. Function arguments accept JSON whitespace differences outside strings, decoded string escapes, and compatible partial snapshots while preserving delivered bytes. Number literals must match exactly (`1` and `1.0` conflict); object-key order and duplicate members must match too. These conservative conflicts fail the turn. JSON nesting is limited to 65,536 containers; deeper input fails with a clear depth-limit message. Late fragments are validated incrementally. On upstream failure, received text and +reasoning remain visible and usage retains numeric counters only. The relay is covered by synthetic stream fixtures; live hosted-stream compatibility remains unverified. + For the canonical Kimi Coding Plan presets (`kimi` account login and `kimi-code` API key), opencodex forwards only a caller-supplied stable `prompt_cache_key` to the Chat Completions request (the Responses wire accepts the same field, but opencodex does not send it there today); @@ -353,15 +462,33 @@ to avoid its `assistant must not be empty` rejection. Nonempty text, whitespace, reasoning and tool calls/results are retained; stored client history is not rewritten. An empty message referenced by an `item_reference` in the same input is retained rather than leaving a dangling reference. -Kimi Coding usage prices for `k3`, `k3[1m]`, and `k3-256k` are **API-reference estimates** across -`kimi`, `kimi-code`, and `kimi-responses`, using the published default 5-minute cache-write rate. -They do not reproduce Code Plan billing or quota: K3's 1M variant consumes about twice the quota -of `k3-256k`. `kimi-for-coding` now points to K2.8 Preview, so its former K2.7 price is no longer +Kimi Coding usage prices for `k3`, `k3[1m]`, `k3-256k`, `k3.1-pro`, and `k3.1-pro-highspeed` are +**API-reference estimates** across `kimi`, `kimi-code`, and `kimi-responses`, using the published +default 5-minute cache-write rate (the `moonshot` API preset prices the same models as `kimi-k3`, +`kimi-k3.1-pro`, and `kimi-k3.1-pro-highspeed`). They do not reproduce Code Plan billing or quota: +K3's 1M variant consumes about twice the quota of `k3-256k`, and K3.1 Pro Highspeed about twice +that of `k3.1-pro`. `kimi-for-coding` now points to K2.8 Preview, so its former K2.7 price is no longer used; its estimate remains unavailable unless the operator supplies `modelCosts`. Unknown-price routing policies and cost caps that exclude unknown estimates can therefore exclude this alias. See [Kimi's model configuration](https://www.kimi.com/code/docs/en/kimi-code/models.html) and [API pricing](https://platform.kimi.ai/docs/pricing/chat). +The `moonshot` (Kimi API) preset lists `kimi-k3.1-pro` and `kimi-k3.1-pro-highspeed` next to +`kimi-k3` and the K2 ids. Both have a 1M-token context window and text + image input, and always +think: the picker offers `low` / `high` / `max` (default `max`), Codex `medium` is sent as `high` +and `xhigh` as `max`, and an explicit `none` leaves `reasoning_effort` out so the upstream default +applies. Fixed sampling parameters (`temperature`, `top_p`, penalties) are not sent. A saved +`moonshot` model list that is still the previous built-in list gains both ids at startup when it +points at the International or China endpoint; this roster refresh adds no models to an edited +list or a Custom URL. The retired-id migration below applies separately. +The preset defaults to the vendor-recommended `kimi-k3.1-pro`. `kimi-k2.5`, discontinued on +2026-08-31, is removed from the API seeds; saved selections on the official International or China +endpoint migrate to `kimi-k3.1-pro`, refreshing old built-in context and reasoning metadata while +preserving explicit overrides. Custom destinations keep their saved selections. `kimi-k2.6` and +`kimi-k2.7-code` (including highspeed) remain selectable for existing users: Moonshot closes the +K2 series to new accounts on 2026-10-31 and plans to retire it by the end of December 2026; see the +[Kimi API model list](https://platform.kimi.ai/docs/models.md) (checked 2026-10-28). + A custom `openai-chat` provider can opt in when its upstream documents support for `prompt_cache_key`: @@ -461,7 +588,7 @@ OAuth providers whose credentials include a stable account id or email can keep login. The Providers page shows those accounts in a dropdown, lets you add another, and switches the active account without logging the others out. A normal login with an identity-less Kimi credential replaces the active slot, while an explicit **Add account** preserves that slot and activates a new, -distinct one. Kiro accounts are keyed by profile ARN. `chatgpt` is always single-slot because Codex +distinct one. Kiro accounts use the profile ARN together with the signed-in user's email when available; different users can keep separate credentials for one organization profile. `chatgpt` is always single-slot because Codex pool accounts have a separate ledger. Tokens stay in `~/.opencodex/auth.json`; `/api/oauth/accounts` returns masked metadata only. @@ -478,6 +605,8 @@ cat accounts.json | ocx account import google-antigravity --format cockpit-tools Inline JSON and extra positional arguments are rejected. Keep exported files private and delete or store them securely after import. +Each record may carry an optional `project_id` for an account whose Cloud Code Assist project is not discovered automatically. It must be a Google Cloud project id (6–30 lowercase letters, digits or hyphens). OpenCodex uses it only when discovery finds no project, and only after a quota check with that account's own token succeeds for it; otherwise the record fails with `missing_project` and nothing is saved. A discovered project always takes precedence. + ### OAuth reliability opencodex coordinates token refresh and Codex pool routing so concurrent requests do not race the @@ -561,6 +690,8 @@ If Kiro ends with plain text instead of its private final-answer tool, one bound still runs, and only the resulting final answer is displayed. Progress accompanying a real tool call remains visible. A normal private final answer needs no completion retry. +When Kiro's safety filter stops a turn (`CONTENT_FILTERED`, for example the Claude `BIO` classifier), the request ends as a refusal that clients do not retry: Claude clients see `stop_reason: "refusal"` and Codex sees a failed response carrying Kiro's category and explanation. If the filter stops the bounded retry, no final answer is displayed; the progress held from the first attempt and any partial text from the retry are shown as commentary before the refusal. + When Kiro emits credit metering, request logs preserve the reported spend as `usage.providerCredits`, including in the persisted usage ledger. These are Kiro credits; token counts may still be estimated, and the credit value does not replace USD cost estimates. @@ -583,7 +714,19 @@ Other messages, statuses, and AWS SSO responses do not trigger this desktop-spec ### Kiro credential import -The dashboard offers native Builder ID, Google, and GitHub device login without Kiro CLI. +The dashboard offers native AWS IAM Identity Center, Builder ID, Google, and GitHub device login without Kiro CLI. + +For an organization account, choose **AWS IAM Identity Center**, enter your AWS access portal URL +(for example `https://example.awsapps.com/start`) and the region where your organization configured +IAM Identity Center. Open the verification link in your own browser, enter the displayed code, +and authorize the account. The hub completes the grant; no SSH session or browser callback to +the hub is required. If AWS lists several Kiro profiles, choose the profile to save. With one +profile the account is saved automatically. The SSO region and the selected profile's API region +are kept separately. Profile discovery checks AWS's US East and Frankfurt service regions. +The signed-in user's email is resolved from AWS for the selected profile before saving; users +sharing one organization profile keep separate account credentials. Cancellation or expiry before +the credential write saves no account. Native login adds a slot and keeps the existing selection. + The Kiro CLI choice and `ocx login kiro` import path use the CLI: on Unix, install it with `curl -fsSL https://cli.kiro.dev/install | bash`; on Windows PowerShell, use `irm 'https://cli.kiro.dev/install.ps1' | iex`; then sign in with `kiro-cli login`. Without a `kiro-cli` session, `ocx login kiro` falls @@ -620,9 +763,15 @@ an ambiguous token selection), when `KIROCLI_DB_PATH` / `KIRO_CLI_DB_FILE` redir from the live CLI store, or when an existing primary CLI database has no recognized token row. Repair or remove the unreadable database under the normal `kiro-cli` data path, unset those import selectors, then retry. Signing in from a machine with no existing `kiro-cli` session is unaffected. -The native dashboard choices are add-only and do not sign out `kiro-cli`. A device dialog shows the code and verification destination. Only recognized Kiro or Builder ID hosts are opened as links; an unexpected destination is shown as copyable text for review. Closing the dialog sends cancellation and leaves a bounded background status check to reconcile a commit already in progress. A stalled status response is retried; exhausting the flow deadline produces the neutral ended outcome rather than claiming success. Google and GitHub approval completes when Kiro reports `authorized` (or the legacy `approved` status) with valid tokens and a profile ARN. +The native dashboard choices are add-only and do not sign out `kiro-cli`. A device dialog shows the code and verification destination. Only recognized Kiro or regional AWS device-SSO hosts are opened as links; an unexpected destination is shown as copyable text for review. Closing the dialog sends cancellation and leaves a bounded background status check to reconcile a commit already in progress. A stalled status response is retried; exhausting the flow deadline produces the neutral ended outcome rather than claiming success. Google and GitHub approval completes when Kiro reports `authorized` (or the legacy `approved` status) with valid tokens and a profile ARN. The account list marks Kiro accounts excluded from automatic selection with a reason, when available. +### DeepSeek API + +The `deepseek` API-key provider includes `deepseek-flash`, its `deepseek-v4-flash` alias, and `deepseek-v4-pro`. DeepSeek [withdrew the Pro retirement plan](https://api-docs.deepseek.com/updates/) and continues serving it; opencodex retains Pro in the catalog with a 1,048,576-token context window, text-only input, and `low`/`high`/`max` reasoning effort. Responses requests use its native Responses endpoint; Chat Completions requests retain the Chat wire. Flash remains the default. Third-party providers have independent model availability. + +On upgrade, startup adds Pro to a saved model list only when it exactly matches the previous built-in DeepSeek seed and still uses the official endpoint and adapter. Customized lists, including empty lists, remain unchanged; live discovery need not be enabled for this repair. + ### DeepSeek Account (DSH) `dsh-account` is an experimental, import-first account provider designed to reuse the authenticated account credentials of an installed DeepSeek Harness (DSH) Desktop application. @@ -636,7 +785,7 @@ The account list marks Kiro accounts excluded from automatic selection with a re ## 3. API-key catalog -opencodex ships 104 built-in presets: 84 key-based, 16 OAuth, three local, and one default +opencodex ships 107 built-in presets: 86 key-based, 17 OAuth, three local, and one default ChatGPT-forward preset. The dashboard's **Add provider** picker opens a key provider's dashboard, validates the key, and stores it; validation is provider-specific. Notable entries: @@ -654,7 +803,7 @@ preserves those requested tiers; any backend-specific normalization remains Clin available in the Cline IDE/CLI, not through the API; `minimax/minimax-m2.5` is the documented API free-experimentation model. -**OrcaRouter** ([sponsor](https://github.com/lidge-jun/opencodex/blob/main/SPONSORS.md)) is an +**OrcaRouter** ([sponsor](https://github.com/lidge-jun/opencodex/blob/dev/SPONSORS.md)) is an OpenAI-compatible gateway at `https://api.orcarouter.ai/v1` with vendor-namespaced model ids (`openai/gpt-5.5`, `anthropic/claude-opus-4.8`, `deepseek/deepseek-v4-flash`, ...) and an adaptive router, `orcarouter/auto`, that grades each prompt and picks the model. Create a key in the @@ -718,7 +867,7 @@ region-pinned EU routes, is at [opper.ai/models](https://opper.ai/models). Opper | Z.AI (GLM Coding) | `https://api.z.ai` — Responses at `/api/v1/responses` by default; Chat Completions at `/api/coding/paas/v4/chat/completions` per model through `modelAdapters` | | Zhipu AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | | BigModel Coding Plan (Responses, static roster) | `https://open.bigmodel.cn/api/v1` | -| Qwen Cloud | Token plan (default): `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · Pay as you go: `https://dashscope.aliyuncs.com/compatible-mode/v1` · or Custom | +| Qwen Cloud | Token plan (default): `https://token-plan.maas.qwencloudapi.com/compatible-mode/v1` · Pay as you go: `https://dashscope.aliyuncs.com/compatible-mode/v1` · or Custom | | Tencent Cloud Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | | Volcengine Ark · Coding Plan · Agent Plan | `https://ark.cn-beijing.volces.com/api/v3` · `https://ark.cn-beijing.volces.com/api/coding/v3` · `https://ark.cn-beijing.volces.com/api/plan/v3` | @@ -728,11 +877,34 @@ region-pinned EU routes, is at [opper.ai/models](https://opper.ai/models). Opper | Opper | `https://api.opper.ai/v3/compat` | | TokenLab | `https://api.tokenlab.sh/v1` | | Modelflare | `https://modelflare.dev/v1` | +| AI Stupid Level | `https://aistupidlevel.info/v1` | +| cheapaimodel | `https://api.cheapaimodel.ai/v1` | | OpenGateway | `https://apis.opengateway.ai/v1` | | GitLab Duo | `https://cloud.gitlab.com/ai/v1/proxy/openai/v1` | | Cloudflare AI Gateway | `https://gateway.ai.cloudflare.com/v1/{account-id}/{gateway}/anthropic` | | …and more | opencode zen, Vercel AI Gateway, Venice, NanoGPT, Synthetic, Qianfan, Alibaba, Parallel, ZenMux, LiteLLM | +**Alibaba Token Plan** provides Beijing Personal Edition and International Team Edition +presets. Both regions offer both subscription tiers. The presets keep static chat-model +lists because upstream discovery also includes non-chat models. Existing selections and +explicit International endpoint overrides are preserved. + +Both presets include `deepseek-v4.1-flash-1017` with text/image input, text output, +1,000,000 context and `low`/`high`/`max` reasoning (default `high`). Its 393,216 output +budget follows the existing published-budget normalization, not a measured boundary; +the lab lists 384,000. Strict schemas reject and `json_object` is unverified for this +exact ID, so Chat requests omit `response_format`. This is best-effort text, not +guaranteed JSON. The bare model's verified JSON downgrade and existing Responses +pins are unchanged. Beijing also includes now-listed `deepseek-v4-pro-0813`; +International omits retired `deepseek-v3.2` and bare `deepseek-v4-flash` but retains +`deepseek-v4-flash-0731`. Both presets keep the hosts their official quick starts +document: Beijing `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1` and +International `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1`. +The Qwen Cloud preset uses the separate Token Plan host that Qwen Cloud documents above. +See the [1017 model card](https://www.qianwenai.com/models/deepseek-v4.1-flash-1017), +[Chat reference](https://docs.qwencloud.com/api-reference/chat/openai-chat) and +[Personal overview](https://help.aliyun.com/en/model-studio/token-plan-personal-overview). + **OpenGateway** is an OpenAI-compatible gateway operated by Sionic AI at `https://apis.opengateway.ai/v1`. Its public catalog contains about 80 active models (as verified on 2026-10-02); the preset automatically refreshes the live model list from @@ -743,8 +915,20 @@ Create a key in the [OpenGateway dashboard](https://opengateway.ai/api-keys), th use the configured Bearer key; the public model list does not validate that key. On the Responses wire OpenGateway rejects replayed native custom tool calls, so the preset lowers Codex custom tools such as code-mode `exec` to function tools before sending them. - -**TokenLab** ([sponsor](https://github.com/lidge-jun/opencodex/blob/main/SPONSORS.md)) is an +Tool-result content arrays are sent as text, with images preserved after the paired tool-result group. Unsupported result parts, including refusals and opaque content, are rejected explicitly with a client input error before sending. +Image detail `original` maps to `high`, which the gateway accepts; image bytes remain unchanged. +The native Responses route also checks text-only empty completions before exposing them as success. +Exhausted output budgets produce `incomplete` with `max_output_tokens`; the proxy does not increase +the requested budget. A replay-safe empty completion with budget remaining may retry once, within +the existing send limit. Explicit `emptyCompletionRetry: false` or `OCX_EMPTY_COMPLETION_RETRY=0` +disables that retry. Text, refusals, tool activity, and unknown stream events prevent replay and +retain the original stream, as does a response snapshot that already carries aggregate `output_text` +(an absent, `null` or empty `output_text` still allows the retry). +The protection does not change other providers or their retry defaults. +Replay requires explicit `store: false`, complete input, and client-executed tools only; a hosted +tool such as `web_search` prevents automatic replay even if no tool event was observed. + +**TokenLab** ([sponsor](https://github.com/lidge-jun/opencodex/blob/dev/SPONSORS.md)) is an OpenAI-compatible API gateway at [tokenlab.sh](https://tokenlab.sh/r/OPENCODEX), operated by TOKENLAB AI INC. Create a workspace [API key](https://tokenlab.sh/dashboard/api?tab=keys), then run @@ -760,7 +944,7 @@ Each model then uses the request format TokenLab declares for it | Models | Codex (Responses clients) | Chat clients | Claude Code (Anthropic clients) | | --- | --- | --- | --- | -| `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6-sol`, `gpt-6-luna`, `grok-4.7`, `deepseek-v4.1-flash`, `deepseek-v4-pro`, `kimi-k3`, `glm-5.3` | [Responses](https://tokenlab.sh/docs/en/api-reference/responses/create-response) | Chat Completions | Chat Completions | +| `gpt-6-astra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-sol`, `gpt-6-luna`, `grok-4.7`, `deepseek-v4.1-flash`, `deepseek-v4-pro`, `kimi-k3`, `glm-5.3` | [Responses](https://tokenlab.sh/docs/en/api-reference/responses/create-response) | Chat Completions | Chat Completions | | `claude-*` | [Messages](https://tokenlab.sh/docs/en/api-reference/messages/create-message) | Messages | Messages | | Every other model, including `gemini-3.8-flash` | Chat Completions | Chat Completions | Chat Completions | @@ -781,9 +965,11 @@ picker and marks it as a sponsor, and nothing else about routing or defaults cha **Modelflare** is an OpenAI-compatible relay at `https://modelflare.dev/v1`. Select **Modelflare** in `ocx init` or the dashboard's **Add provider** picker, or run `ocx provider add modelflare`, and give it your key directly or as the reference `${MODELFLARE_API_KEY}` so the key stays in your -environment. The preset uses Chat Completions and seeds four models that +environment. The preset uses Chat Completions. The following existing models were verified with chat, streaming and tool calls: `glm-5.3-flash` (the default), -`claude-sonnet-5-5`, `gpt-6.1-sol` and `deepseek-v4-flash`. You can add other Chat-compatible +`claude-sonnet-5-5`, `gpt-6.1-sol` and `deepseek-v4-flash`. +`gpt-6.1-terra` is a preemptive seed mirroring Sol; it has not been inference-verified here. +You can add other Chat-compatible Modelflare models as custom models. Image and video models use separate Modelflare endpoints and do not work through this Chat preset. An ordinary Modelflare key is bound to one routing group and can call only that group's models, so use a Smart key for the full seeded set, or pass @@ -791,6 +977,46 @@ can call only that group's models, so use a Smart key for the full seeded set, o `deepseek-v4.1-flash` is listed upstream but currently answers 503, so the preset leaves it out. Upstream latency varies from a few seconds to about 30 seconds, with occasional transient 503s. +**AI Stupid Level** is a Smart Router at `https://aistupidlevel.info/v1`, operated by S.C. Studio +Platforms S.R.L. Create a router key at [aistupidlevel.info/router/keys](https://aistupidlevel.info/router/keys) +and add your own OpenAI, Anthropic, Google, DeepSeek, Kimi or GLM keys to the same account. Then select +**AI Stupid Level** in `ocx init` or the dashboard's **Add provider** picker, or run +`ocx provider add aistupidlevel`, and give it the router key directly or as the reference +`${AISTUPIDLEVEL_API_KEY}`. The router calls each model with your own provider key, so the provider +bills you directly and AI Stupid Level adds no markup ([terms](https://aistupidlevel.info/terms#router)). +The preset uses Chat Completions for every client, Claude Code included, and discovers models from the +authenticated `GET /v1/models`. Its seeded models are the +[routing modes](https://aistupidlevel.info/router/docs#strategies): `auto-coding` (the default) sends +each request to the model with the best measured score on AI Stupid Level's coding benchmark, +`auto-tooling` and `auto-reasoning` do the same for tool use and reasoning, and `auto-value-coding` or +`auto-fastest-quality` pick the best-value or fastest model within 5 points of the best. A real model id +from the live list, such as `aistupidlevel/claude-opus-5-5`, pins one model, and the `X-AISM-Model` +response header names the model that answered. Routing modes declare a 262,144-token window and 64,000 +output tokens, which hold for any model the router picks. The router accepts text only, so for a +routing mode or pinned model at the preset destination the proxy hands images to the vision sidecar instead of sending them. Its Anthropic +Messages endpoint is a passthrough to Anthropic without routing, so the preset does not use it. + +**cheapaimodel** is a pay-per-token API gateway for open-weight models (DeepSeek, GLM, Kimi) and +Grok, operated by LINKOVA PTE. LTD. Create an [API key](https://console.cheapaimodel.ai/keys) on a +prepaid USD balance, then select **cheapaimodel** in `ocx init` or the dashboard's **Add provider** +picker, or run `ocx provider add cheapaimodel`, and give it the key directly or as the reference +`${CHEAPAIMODEL_API_KEY}`. The preset uses [Chat Completions](https://cheapaimodel.ai/docs/api/create-chat-completion) +for every client and discovers models from the authenticated +[`GET /v1/models`](https://cheapaimodel.ai/docs/api/list-models), which answers 401 without a valid +key. The seeded models are `deepseek-v4-1-flash` (the default), `glm-5.3`, `glm-5.3-flash`, `kimi-k3` +and `grok-4.7`; `glm-5.3` is text only, so images for it go to the vision sidecar. `kimi-k3` accepts +only its own sampling values, so the preset does not forward `temperature` or `top_p` to it. The +preset sends every request through Chat Completions, the one interface every catalog model supports; +it does not use the gateway's Responses or Anthropic Messages endpoints. cheapaimodel's +[terms](https://cheapaimodel.ai/terms) and [privacy policy](https://cheapaimodel.ai/privacy) apply to +requests sent to this service. + +The provider editor also accepts an optional `inputModalities` fallback: a nonempty array containing +`text`, `image`, `audio`, or `video`. Exact per-model declarations take precedence. Invalid values +are rejected on save; a malformed value in a hand-edited config loads as `["text"]` with a warning. +The preset's text-only fallback is applied at runtime, including when saved under another provider +name at the same URL and Chat adapter. It does not follow a custom URL or another adapter. + The MiniMax and MiniMax (CN) provider cards can also show Coding Plan quota when the configured key has an active plan. The dashboard reads the plan's 5-hour window and, when present, weekly window; these are display observations and do not change model routing. @@ -802,17 +1028,16 @@ attempt fails, while transient failures keep it. An unreadable or oversized body further attempts. Dollar credits show the included allowance only, excluding purchased credits, so an exhausted allowance stops routing to Ollama Cloud only when no purchased credit remains. -`MiniMax-M3.1-Flash-Preview` (1M context) is listed on both MiniMax presets. MiniMax serves it -only to Token Plan subscription keys and MiniMax Code for now, so a pay-as-you-go API key gets an -error for it. Thinking is always on: the effort picker offers `low` through `max` and defaults to -`max`, and there is no way to turn thinking off. MiniMax has not published a per-token price -for the preview; usage is drawn from your -[Token Plan quota](https://platform.minimax.io/docs/guides/pricing-token-plan), so OpenCodex -shows no estimated cost for it. MiniMax's `/models` endpoint does not list -the preview yet, so OpenCodex keeps it in the catalog from the preset. An install whose saved -MiniMax model list is still the previous default receives it on the next start; a list you edited -is left as it is; register the preview by hand with -`ocx models add minimax MiniMax-M3.1-Flash-Preview --context-window 1000000`. +`MiniMax-M3.1-Flash` (1M context, up to 524,288 output tokens) is the default model on both MiniMax +presets. MiniMax released it on 2026-10-19 and retired the `MiniMax-M3.1-Flash-Preview` id, so a +saved configuration that still names the preview is renamed to `MiniMax-M3.1-Flash` on the next +start. Thinking is always on: the effort picker offers `low` through `max` and defaults to `max`, +and there is no way to turn thinking off. MiniMax's `/models` endpoint does not list Flash, so +OpenCodex keeps it in the catalog from the preset. An install whose saved MiniMax model list is +still the previous default receives it on the next start; a list you edited is left as it is; +register it by hand with +`ocx models add minimax MiniMax-M3.1-Flash --context-window 1000000`. +The seed refresh applies only to official MiniMax endpoints; Custom URLs keep their model list. **OpenCode Go** routes `gemini-4-argon-contributor` through its Gemini API, including streaming and tool-result continuations. The existing `opencode-go` preset keeps its @@ -857,10 +1082,12 @@ when a stable upstream session is required. **MiMo tool-call echoes.** On OpenCode Go and other Chat Completions routes, a bare `` block is hidden when it duplicates one structured call to the same tool -with the same effective input. If the input differs or several calls could explain +with the same effective input. This includes MiMo wrappers such as +`` with matching closing IDs, including echoes appended to ordinary prose. +Code examples remain visible. If the input differs or several calls could explain the block, the markup remains visible. For `mimo-v2` and dotted MiMo V2 model IDs such as `mimo-v2.6-pro`, if the gateway instead sends exactly one empty `{}` call for a declared -freeform tool and puts its input in a standalone bare block, opencodex restores that +freeform tool and puts its input in a standalone bare or identified block, opencodex restores that input to the call and hides the block. Hyphenated IDs such as `mimo-v2-pro` and `mimo-v2-omni` are outside this recovery rule. Prose, quoted examples, ordinary functions, and ambiguous responses remain unchanged. This also handles @@ -870,7 +1097,7 @@ MiMo's malformed ` models. Coding Plan defaults to `ark-code-latest`, while Agent Plan defaults to > `deepseek-v4-flash`. +On the pay-as-you-go Ark route, Kimi K3.1 Pro (`kimi-k3-1-pro`, including dated versions) +replays tool-only assistant turns with an empty string. Its endpoint rejects the legacy +empty-text array with HTTP 400; other Ark models keep their existing continuation format. + > **Volcengine Plan usage restriction:** Volcengine documents Coding Plan and Agent Plan quota as > valid only inside supported AI coding tools, and warns that using a plan key for general API > calls may suspend the subscription or ban the account. Routing Codex or Claude Code through @@ -1033,6 +1271,10 @@ ladder, and `meta-model/muse-wonder-1.0` (Muse Wonder, preview) with `minimal` t Muse Wonder is Standard mode only on the Model API: it has no Contributor tier and costs $4 per 1M input and $20 per 1M output tokens. Muse Wonder Full is available only inside Muse Code subscriptions, so it is not seeded. +On startup, an untouched saved two-Spark model list gains Muse Wonder when `meta-model` uses +`https://api.meta.ai/v1` or has no saved endpoint override. Custom gateway destinations and +hand-edited model lists stay unchanged. Existing per-model context-window overrides and output +limits are preserved; Wonder's context window is filled only into an existing window map. Discovery stays off until an authenticated roster is verified, because Meta serves image and voice models on the same host. @@ -1076,7 +1318,14 @@ prove your Muse Code plan covers Muse Wonder. **Read this before enabling it.** Meta scopes that credential to the Muse Code CLI, so using it here is an *unsupported* path. Meta does not authorize subscription coverage outside its own client, how these calls settle is not observable from the API, and you -should treat every call as billable against your account. The key, imported or pasted, is copied into +should treat every call as billable against your account. Meta can also refuse the request +outright with HTTP 403 and *"This API key is billed to a Muse Code subscription. Muse Code +subscriptions cover requests from the Muse Code client only. Use it in Muse Code, or use a +pay-as-you-go API key for other clients."* OpenCodex reports that as a +plan restriction on a valid credential, not a rejected or expired one, because no re-login +can lift it: a Muse Code subscription key cannot serve any request outside the Muse Code +client, and a pay-as-you-go Meta API key with the `meta-model` provider is the supported +path. The key, imported or pasted, is copied into OpenCodex's auth store (`~/.opencodex/auth.json`, mode 0600) like every other OAuth credential. The dashboard shows a Terms-of-Service warning before the first login and before any reauthentication — the same treatment Anthropic and Google Antigravity get. @@ -1089,6 +1338,14 @@ request translation rather than passthrough reports none. An account that has no served a streaming turn simply shows no quota, which is not an error. Rate limits apply per team, not per key. +When the current Muse account's latest-started retained request explicitly reports subscription exhaustion +with a future reset time, the dashboard quota strip can show that observed limit even if +Meta omitted the normal usage frame. The Muse chip includes a reset countdown. This reads +local request-log evidence and never sends a model request. It does not classify an unnamed +window as five-hour or weekly, and a newer successful request or an elapsed reset removes +this fallback. The fallback selects by request start time across the server-bounded matching +log history, so an older request that finishes later cannot hide a newer success. + For a supported setup, use `meta-model` above with your own key. **Command Code quota.** The dashboard and `ocx account refresh` probe Command Code's @@ -1160,6 +1417,39 @@ Create a key in [Novita's key manager](https://novita.ai/settings/key-management > hosts and schemas and are not routed by this preset. > Live discovery for this preset is capped at a 1 MiB response and 256 raw model rows. +### WorkBuddy AI subscription + +`workbuddy-ai` connects your international WorkBuddy AI subscription as a model provider. +Choose **WorkBuddy AI** in Providers and log in, or run: + +```bash +ocx login workbuddy-ai +``` + +Complete the browser sign-in; OpenCodex polls for authorization for up to five minutes. +Tokens are stored in OpenCodex and refreshed on demand. Adding accounts uses the existing +OAuth account list; team identity stays attached to its own token. No WorkBuddy desktop +installation or credential-file import is required. + +Models and capabilities come from your account's live product catalog. Select a +`workbuddy-ai/` model after login; `workbuddy-ai/default-model` is the fallback +selector when discovery is unavailable. Streaming, tool calls and buffered responses use +WorkBuddy's Chat endpoint. The Overview and Accounts tabs show remaining credits, used/total credits, base and gift +balances, and the next expiring non-daily credits when available. Refresh reads the signed-in +account's billing summary; an unavailable read is not a zero balance. These credits are +informational and do not disable free models when paid credits run out. +When the reported total is positive, the header quota summary shows the unavailable percentage, +including frozen credits, rounded to the nearest whole percent. It gives no exhaustion warning: +free models may still work. An individual +credit expiry is not shown as a reset of the entire balance. + +This uses an unofficial subscription protocol based on +[Magpie's WorkBuddy plugin](https://github.com/magpie-community/plugins/tree/e7f65641df820dfd715c0d2241f99f2092e4efb1/packages/workbuddy). +Upstream client-channel or account restrictions are returned to the caller. OpenCodex does +not rewrite agent identity prompts to bypass them. Availability depends on your account, +region, model entitlement and WorkBuddy's current API. This is separate from the CodeBuddy +CLI API-key providers and does not connect the WorkBuddy desktop client to OpenCodex. + ### Official CodeBuddy Code CLI (Global & CN) OpenCodex provides official adapter support for Tencent Cloud's CodeBuddy Code CLI via the `codebuddy` (Global) and `codebuddy-cn` (China) presets. @@ -1225,10 +1515,13 @@ OpenCodex provides official adapter support for Qoder through the `qoder` (Globa - **Authentication:** Create a PAT in the account integrations page ([Global](https://qoder.com/account/integrations), [CN](https://qoder.cn/account/integrations)) and paste it as the provider's API key. The stored key reaches the CLI only as `QODER_PERSONAL_ACCESS_TOKEN` (Global) or `QODERCN_PERSONAL_ACCESS_TOKEN` (CN) in a scoped child environment. - **Region Isolation:** Each preset accepts only its canonical destination (`https://qoder.com` or `https://qoder.cn`) and resolves its own executable. Credentials, model cache, usage, and health are independent; neither region falls back to the other. An older custom provider named `qoder` with a different destination keeps its existing adapter and URL. -- **Model Discovery:** `qoder --list-models` is the authoritative entitlement roster for the current PAT. The cache is bound to an irreversible fingerprint of the token, so switching accounts never reuses another account's roster. If discovery fails, the provider degrades to a stale cache and then the documented static seed. +- **Windows executables:** Each preset launches its CLI's native executable (`qoder.exe` or `qodercli.exe` for Global, `qodercn.exe` or `qoderclicn.exe` for CN) when one is on PATH. Within one PATH folder the `.exe` wins over a same-name `.cmd`, and a later candidate name such as `qoderclicn.exe` anywhere on PATH wins over `qodercn.cmd`; an earlier PATH folder that holds only `qodercn.cmd` still shadows a later folder's `qodercn.exe`. Qoder turns pass empty `--tools` and `--setting-sources` values to keep the CLI's built-in tools and local settings out, and a dispatcher that forwards through PowerShell drops those empty values. When only such a dispatcher is found, the turn fails before the CLI starts with `cli_dispatcher_drops_empty_args`; add the folder holding the native executable to PATH (the official CN installer places it in `%USERPROFILE%\.qoder-cn\bin\qoderclicn`) and retry. A dispatcher that passes arguments straight through, such as an npm shim, keeps working. +- **Model Discovery:** `qoder --list-models` is the authoritative entitlement roster for the current PAT. The cache is bound to an irreversible fingerprint of the token, so switching accounts never reuses another account's roster. If discovery fails, the provider degrades to a stale cache and then the documented static seed. The CLI starts a full agent runtime first, so background catalog discovery allows each run up to 30 seconds, and concurrent callers of the same provider share one run per token. The dashboard connection test waits at most 8 seconds: past that it reports the provider as still discovering rather than failed, and when the run succeeds the catalog is re-synced without a proxy restart. Codex sessions that are already running keep their previous model list until they restart: restart Codex, or run `ocx system codex-restart --yes`, which restarts Codex app-servers (the CLI reference describes what it keeps and what it relaunches). - **Token usage:** Qoder CLI reports zero token counts unless its usage switch is on, so each preset turns it on in its scoped CLI child environment: `QODER_EXPOSE_TOKEN_USAGE=true` for Global and `QODERCN_EXPOSE_TOKEN_USAGE=true` for CN, which reads only its own prefix. - **Tool Ownership:** The CLI runs single-turn `stream-json` with `--tools ""`, `--strict-mcp-config`, setting sources disabled, and session persistence disabled, so Codex keeps exclusive tool ownership. Client-declared tools are exposed through an isolated request-scoped MCP server. -- **Image Input:** Qoder Global accepts image input through the Qoder CLI. OpenCodex forwards supported image inputs that reach the Global adapter to the CLI without maintaining a per-model vision capability allowlist there. Image compatibility and any model-specific preprocessing or routing are handled by Qoder. OpenCodex does not use the static discovery fallback roster to classify per-model vision capability. Qoder CN keeps its existing sidecar classification, and any residual raw-image request that reaches the CN adapter is rejected as `unsupported_input_modality`. OpenCodex serializes history before the current turn, but Qoder does not persist sessions, so prior images are replayed on later turns. In observed multi-turn image conversations, replayed images can become unreliably associated or effectively ordered relative to the historical text they originally accompanied. +- **Tool names:** Qoder Global and Qoder CN accept each selected tool's exact client name or its advertised MCP name. Repeating the same call ID and arguments under either spelling returns the tool call only once. Unknown or unselected names are rejected. If one selected tool's client name equals another selected tool's MCP name, the request fails with `tool_catalog_invalid` before the CLI starts. Select one of those tools or rename it to remove the ambiguity. Tool execution remains with the client. +- **Output guard:** If the CLI echoes OpenCodex tool-call/result replay envelopes into assistant text, the turn fails with `vendor_scaffold_detected` (502) instead of returning the envelope as a successful answer, and neither reasoning nor tool calls following the envelope are forwarded. Reasoning starts a fresh replay-text block, so earlier prose or code fences cannot hide an envelope in later text. If the CLI's turn already ended with its own error, that error is reported instead, still without the envelope. The proxy does not retry that failure automatically. Ordinary prose and closed fenced examples follow the shared envelope recognizer; an unverified overflowing fenced example is refused. Assistant text preserves Unicode characters split across CLI frames; unpaired surrogates are replaced with U+FFFD. +- **Image Input:** Global continues forwarding supported images through the shared projection without a per-model vision allowlist. CN retains its vision-sidecar defaults. Its raw-image route admits only one canonical base64 PNG of at most 1 MiB decoded, 8192 pixels per edge, and 16 million total pixels in a single user turn with `DeepSeek-Flash` or `Qwen3.8-Flash`. Use `qoderclicn 1.1.70`: [issue #7516](https://github.com/lidge-jun/opencodex/issues/7516) reports Windows 11 x64 live success for those models on both `--attachment` and inline `--input-format stream-json --output-format stream-json` stdin; OpenCodex uses only stdin. The adapter validates base64 length/padding, decoded PNG signature and basic IHDR fields before CLI discovery; it does not decompress pixels or validate every PNG chunk/CRC. These ceilings are OpenCodex resource policy, not verified vendor maxima: the reported live evidence covers a 96×96 PNG, whose RGBA raster is only 36 KiB. Larger inputs require separate verification. Other CLI versions have not been verified, and the adapter does not probe the installed version. CN refuses raw URL images, other image formats/models, multiple images, tool-result images and image-bearing history/multi-turn replay before starting the CLI with `unsupported_input_modality`; use the vision sidecar for those inputs. Injected CLI tests cover serialization and cancellation without claiming live upstream support. Qoder's supported projection keeps image blocks in conversation order and marks unsupported references as `[image omitted: unsupported reference]`. Global stateless replay can still associate historical images unreliably with their original text; CN does not enable that unverified replay surface. - **PAT recovery:** For both Qoder presets, a multi-key API-key pool can switch to another PAT on a supported authentication rejection or account-level quota exhaustion, but only before response content or an event that makes replay unsafe. Recovery requires Qoder-specific classification and respects credential-hop and send budgets; an HTTP 401/429 or quota message alone is not permission to replay. Single-key configurations do not rotate. Sharing the CLI runner does not enable this API-key recovery for CodeBuddy or self-authenticated Claude CLI. - **Quota:** No public quota API is used, so totals and reset times are unavailable. Codes 110 (account daily limit) and 118 (personal Credits exhaustion) report `insufficient_quota` and permit consideration of PAT recovery. Other supported quota codes also report `insufficient_quota` but do not authorize it. Numeric error codes take precedence: an unrecognized numeric code does not fall back to quota or authentication text. Without a numeric code, only the supported account-daily message beginning “You've reached your daily usage limit for Chat”, with no team/model/shared qualifier, grants quota recovery; generic credit-limit text does not. Only quota failures eligible for PAT recovery enter key cooldown handling. When such a failure has no reset time, the failed key uses the existing default cooldown; nonrecoverable quota classifications do not create a cooldown through this path, and no next-day reset is inferred. - **Operators:** Qoder Global is operated by BRIGHT ZENITH PRIVATE LIMITED under the [product service terms](https://qoder.com/product-service); Qoder CN by 通义云启(杭州)信息技术有限公司 with Alibaba Cloud. Verify `ocx provider test qoder` (or `qoder-cn`) after configuring. @@ -1253,8 +1546,9 @@ CLI headlessly (`claude -p`, `stream-json`) once per turn: - **Prerequisites:** `npm install -g @anthropic-ai/claude-code`, then sign in once with `claude` (or `claude setup-token`). The CLI uses the machine's own Claude Code sign-in (the macOS Keychain entry, or `~/.claude/.credentials.json` elsewhere). -- **No credential stored:** this row holds no API key, and OpenCodex never reads, copies or forwards - a Claude token. The CLI owns the login and bills the account itself. A CLI that is not signed in +- **No credential stored:** this row holds no API key. Quota preflight reads the CLI sign-in token + in memory and sends it only to Anthropic's usage endpoint. OpenCodex does not store that token or + inject it into CLI inference requests. The CLI owns the login and bills the account itself. A CLI that is not signed in fails the turn with a sign-in error naming the command, instead of a generic `401`. Classification follows the same fact: the preset is a keyless key row (`keyOptional`), so it needs no API key and no key field is offered for it. An API key saved on this row by other means is never @@ -1271,11 +1565,21 @@ CLI headlessly (`claude -p`, `stream-json`) once per turn: OpenCodex runs as, so every request routed through this row — from any client of the proxy — spends that one Claude account. There is no per-client account, no pooling and no multiplexing; giving several people their own Claude usage needs one proxy user per sign-in. -- **Input media:** the row publishes its models as text-only for v1. The CLI accepts an image frame - on its stream-json input, but no headless turn has been shown to hand those bytes to the model, so - an image sent straight to this provider is refused (`unsupported_input_modality`) instead of - being silently dropped and answered blind. With the - vision sidecar on the request path, images are captioned into text before they reach the row. +- **Subscription usage:** the Providers workspace shows the plan's 5-hour, weekly and model-scoped + windows from the last usage check OpenCodex recorded before a turn, for the account Claude Code is + signed in to now. Opening the page never probes or launches the CLI, and **Refresh all quotas** + re-reads the local sign-in and that recorded observation rather than Anthropic's endpoint. After a + sign-out or account switch the previous account's row disappears on **Refresh all quotas**, and + within a minute otherwise; a newly signed-in account shows nothing until its first Claude turn. +- **Input media:** the row advertises text and image input. The stable replay sends native image + blocks directly through the official CLI, following the labelled message they belong to. This + includes multiple attachments, retained historical images and images returned by client tools. Text and images retain their order within each message. + Unsupported image references fail explicitly, including Responses image `file_id` references in messages + and tool results; supply a supported image URL instead. Images in system or developer instructions are refused + before vision preprocessing or helper calls. Omitted history also omits its images. A vision + sidecar is not needed. An untouched v2.94.0 text-only roster is migrated; edited lists and explicit + per-model capability overrides remain authoritative. Live verification used Claude Code 2.1.312 + and Fable 5.1; other model/CLI combinations still depend on their upstream image support. - **Isolation:** every turn runs in a scoped child environment with no inherited `ANTHROPIC_*` variable (a `claude` already pointed at this proxy therefore cannot loop back into it), telemetry, feedback and the auto-updater disabled, and `--tools ""`, `--strict-mcp-config` plus @@ -1392,6 +1696,16 @@ under `provider.apiKeyPool`, makes it active, and mirrors it to `provider.apiKey adapters continue to read the same field as before. The same dropdown can switch or remove keys; the management API is `/api/providers/keys` and returns masked keys only. +Each configured key row in the dashboard provides dedicated Pause and Resume controls (along with +`ocx account pause` and `ocx account resume` in the CLI). A paused key is excluded from automatic +request routing, failover, and cooldown recovery (a media call the Responses xAI image/video bridge has +already planned keeps the key it was planned with). If another enabled row shares the same key reference, it remains usable. When the last enabled row for the active reference is paused, OpenCodex +automatically selects the next usable unpaused key in the pool in ring order. If all keys in the pool +are paused, requests that need that provider return HTTP 403 `permission_error` until a key is +resumed. The built-in Images route can still use another eligible upstream. Selecting a paused +key row resumes and activates it. Resume clears the pause while preserving a healthy active key; +the resumed key becomes active when no usable key is currently selected. + ### Switching accounts from the terminal Use `ocx account list`, `ocx account current`, and `ocx account use` to inspect or switch the same @@ -1427,6 +1741,9 @@ visible even while live catalogs lag: | Codex login (Pool or Direct) | `gpt-5.6-*` | 922,000 | | OpenAI (API key) | `openai-apikey/gpt-5.6-*` plus `*-pro` | 922,000 (922,000 max input) | | OpenRouter | `openrouter/openai/gpt-5.6-sol`, `openrouter/openai/gpt-5.6-terra`, `openrouter/openai/gpt-5.6-luna` | 922,000 | +| Codex | `gpt-6.1-terra` | 500,000 / 872,000 | +| OpenAI API | `openai-apikey/gpt-6.1-terra` | 1,050,000 (128,000 max output) | +| OpenRouter | `openrouter/openai/gpt-6.1-terra` | 1,050,000 | | Cursor | `cursor/gpt-5.6-sol`, `cursor/gpt-5.6-terra`, `cursor/gpt-5.6-luna` | 1,000,000 | The native GPT-5.6 entries preserve the pinned upstream reasoning ladders (for example, Luna has @@ -1473,7 +1790,7 @@ seconds per call, including pacing and body reads. These are OpenCodex safeguard GitHub limits; oversized catalogs, slow negotiation or a truncated intent excerpt can affect compatibility. For named selections, Copilot fronts a mixed-wire catalog: the following models (`gpt-5.3-codex`, `gpt-5.4`, -`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) reject +`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) reject `/chat/completions` for agent traffic, so opencodex routes those models over the Responses API by built-in default while every other Copilot model stays on chat completions. The precedence is: hard wire pin → your explicit @@ -1545,6 +1862,22 @@ dashboard or `custom` in `ocx init` and enter the base URL. See the [Configuration reference](/reference/configuration/) for every provider field (`headers`, `noReasoningModels`, `noVisionModels`, `models`, …). +For Claude models reached through the translated Chat adapter, opencodex flattens tool-schema root +`oneOf`, `anyOf`, and `allOf` into an object. This uses the actual upstream model id whose final +slash-separated segment starts with `claude-` (case-insensitive), not every model on the gateway. +Nested schemas retain their existing normalization. Root required fields are retained; `allOf` +branch required fields are merged, while `oneOf`/`anyOf` branch required fields are not promoted. +Local root-branch references are followed for at most 64 references across the schema; unresolved, +cyclic, external, over-budget references or referenced compositions leave the root composition intact +and may be rejected upstream. Inline nested compositions also stay intact when they contain unread +properties or references, or exceed 256 inspected entries per tool schema; constraint-only +nesting still flattens. Property schemas and literal values are not scanned by this guard. Nested +references are preserved. Flattening is lossy: branch constraints +disappear and later property definitions win, so tools must validate arguments. Existing Zen and +Azure schema compatibility rules remain in effect. + +See [Verify a custom remote gateway](/guides/custom-gateway/) for the setup and validation checklist. + ## Approval reviewer per provider Codex asks a second model to review approval requests, and takes that reviewer from @@ -1607,7 +1940,26 @@ provider-specific) is already consumed. Providers with a live probe: OpenAI/Codex, Anthropic, xAI, Cursor, Kimi, Google Antigravity, OpenCode Go, OpenRouter, DeepSeek, ClinePass, Z.AI, MiniMax, Moonshot, Venice, Synthetic, DeepInfra, Neuralwatt, Command Code, and any a6api-backed -custom provider. +or Abliteration custom provider. + +**Kimi Coding Plan quota.** Account login and API-key providers on the canonical +`https://api.kimi.com/coding/v1` endpoint read `/usages`. API-key providers on the regional +`https://api.kimi.ai/coding/v1` endpoint read `/usages` from that same origin; account login +stays on `api.kimi.com`. Plans that report +`usages.limit_month_total` (or `monthTotal`) show a monthly utilization bar, with +`limit_month_code` (or `monthCode`) as the fallback when total usage is unavailable. +The `used_ratio` / `usedRatio` fraction must be in `[0, 1]` before conversion to a consumed +percentage; invalid ratios are ignored. Empty or unusable `usages` containers do not hide +usable monthly data in another supported envelope. Any reported reset time is retained. +Existing 5-hour, weekly, and total subscription-credit +windows remain separate, and an absent monthly window is not shown as 0%. + +**Abliteration credits.** A provider of any name whose `baseUrl` is +`https://api.abliteration.ai` or `https://api.abliteration.ai/v1` reads +`GET https://api.abliteration.ai/v1/credits` with its active key as a Bearer token and does not +follow redirects. `total_credits` minus `total_usage` is the remaining USD balance, shown as a +credits bar of consumed spend. An account with no credits shows no bar. A rejected key clears the +row; `503 credit_balance_unavailable`, 408, and 429 keep the last reading. **OpenCode Go quota.** The canonical `opencode-go` preset reads `GET https://opencode.ai/zen/go/v1/usage` with the configured key as a Bearer token and diff --git a/docs-site/src/content/docs/guides/remote-hub.md b/docs-site/src/content/docs/guides/remote-hub.md index ab4e06cd75..e6d2014e39 100644 --- a/docs-site/src/content/docs/guides/remote-hub.md +++ b/docs-site/src/content/docs/guides/remote-hub.md @@ -482,6 +482,11 @@ above already sets it. A whole-array set replaces the array, so when the hub alr run the line `invite` prints — it carries the existing ones plus the new origin. `ocx config get corsAllowOrigins` shows what is there now. +`invite` picks the origin from the config file, but a running hub checks it against the config it +is running with: `hub.managementPublicOrigin` is applied only at start, and a `corsAllowOrigins` edit +may not reach the running hub until it restarts. After changing either, restart the hub before +inviting; `ocx config set` prints a reminder for both keys and for `hub.managementIngress`. + `ocx hub invite --json` emits `{ code, expiresAt, dataUrl, managementUrl, command }` with `expiresAt` as ISO 8601. The code is a secret: single-use, five-minute lifetime, rate-limited at the hub, and not to be persisted, logged, or pasted into an issue. `--clients codex,claude` picks which client configs @@ -523,6 +528,14 @@ healthy one. `ocx service start`, both still work and the error path names the first one as a fallback. Neither is the recommended route any more. +Either verb also recovers a job you booted out by hand. `launchctl bootout` returns before the +process exits, and while the old process drains `launchctl print` already reports the job absent — +so an immediate re-bootstrap can still fail with `Bootstrap failed: 5`. The recovery round waits +between a bounded number of attempts instead of retrying once, so +`launchctl bootout gui/$(id -u)/com.opencodex.proxy` followed by a single `ocx service restart` or +`ocx service repair` serves on the first call. A teardown that never finishes still reaches the +diagnostic error rather than hanging. + Linux and Windows never had this gap: `ocx service restart` there ends in `systemctl --user restart` and a stop-then-start of the scheduled task respectively, whichever verb asked. @@ -560,9 +573,9 @@ input checks. ## Docker Compose opencodex does not publish an official container image. The repository does maintain a source-build -[`Dockerfile`](https://github.com/lidge-jun/opencodex/blob/main/Dockerfile), -[`compose.yaml`](https://github.com/lidge-jun/opencodex/blob/main/compose.yaml), and a narrow -`.dockerignore`. The build pins the multi-platform Bun 1.4.2 image index by digest, runs the proxy as +[`Dockerfile`](https://github.com/lidge-jun/opencodex/blob/dev/Dockerfile), +[`compose.yaml`](https://github.com/lidge-jun/opencodex/blob/dev/compose.yaml), and a narrow +`.dockerignore`. The build pins the multi-platform Bun 1.4.4 image index by digest, runs the proxy as the non-root `bun` user, keeps the root filesystem read-only, drops Linux capabilities, and publishes only the data listener on the host's `127.0.0.1:10100` by default. The foreground process uses `OCX_SERVICE=1`, so stopping or recreating the container preserves routed Codex state instead @@ -651,7 +664,7 @@ services: hub: pull_policy: build build: - context: https://github.com/lidge-jun/opencodex.git#main + context: https://github.com/lidge-jun/opencodex.git#dev dockerfile: Dockerfile target: runtime args: @@ -760,6 +773,12 @@ For a service rollback, stop the branch service and repair the prior release aga loopback browser origin, so an origin-bound grant could never match. Nothing was minted. Run the `ocx config set corsAllowOrigins` line the error prints, with the joining machine's proxy port. See [Inviting another machine](#inviting-another-machine). +- **`ocx hub invite` says `Minting a pairing code failed (origin-refused)`:** the running hub refused + the browser origin the invite names. It admits only the `hub.managementPublicOrigin` and + `corsAllowOrigins` it is running with, which can predate a recent `ocx config set`. Restart the hub + (the error prints the restart command for this install) and invite again. `(rate-limited)` means + the hub is limiting new codes (eight a minute, and a cap on unused ones); wait for earlier codes to + be used or expire (five minutes), then invite again. `(rejected)` is any other refusal. - **`ocx hub invite` says the advertised data origin would be this machine's own loopback:** the bind is loopback-only or a wildcard and `hub.dataPublicOrigin` is unset, so there is no address to advertise and nothing guesses a tailnet or LAN one. Nothing was minted. Set diff --git a/docs-site/src/content/docs/guides/remote-link.md b/docs-site/src/content/docs/guides/remote-link.md index e3dbbf673e..9d168a889f 100644 --- a/docs-site/src/content/docs/guides/remote-link.md +++ b/docs-site/src/content/docs/guides/remote-link.md @@ -9,11 +9,11 @@ A machine link connects an OpenCodex **Home** computer to a **Child** computer o - The Home computer can log in to the Child with an OpenSSH key. - For a Child-initiated link, the Child can log in to Home with an OpenSSH key (password login is not supported). -- OpenCodex 2.66.0 or later is installed on the Child computer, and on Home for a Child-initiated link. -- Both computers run macOS or Linux. +- OpenCodex 2.66.0 or later on Home (and on the Child for a Child-initiated link or full Child install). When adding a Child from Home, a bare SSH host needs no pre-installed Node, Bun, or OpenCodex if Home has a verified `ocx-child` build for the Child's platform: Home can then plant that standalone binary over SSH during onboarding. The npm package and the desktop app do not include `ocx-child` builds; see [Ephemeral Child machines](#ephemeral-child-machines-ocx-child) for where Home looks for one. +- Both computers run macOS, Linux, or Windows x64. Windows requires OpenSSH Server and Windows PowerShell; Git Bash and curl are not required. - The dashboard that adds a Child from Home is opened on Home itself or through a paired Hub session. Turning the current computer into a Child requires an operator-paired dashboard session; a credentialless local dashboard session cannot commit that routing change. -Password SSH and Windows are outside the current flow. A link can be started from either side: from the Home, as described next, or from the Child, as described in [Connect this computer as a Child](#connect-this-computer-as-a-child). +Password SSH is not supported. Links can be started from Home or Child. Windows execution uses PowerShell over the same pinned OpenSSH connection. ## Add a Child from `#remote` @@ -21,12 +21,14 @@ Password SSH and Windows are outside the current flow. A link can be started fro 2. Choose **Home**, then **Continue**. The SSH host list opens. 3. Choose a host from the SSH candidates, or enter an SSH config alias. 4. Run the connection test and compare the offered host fingerprint with the fingerprint for the machine you intend to use. Comparing it helps detect a wrong host or a changed host key before SSH trusts the host. -5. Confirm the fingerprint, then connect the Child. +5. Confirm the fingerprint, then choose **Connect child** (or **Plant lightweight agent & connect** when connecting a bare SSH host that does not have OpenCodex installed yet). The dashboard does not ask you to enter a token. It probes the host first, and it cannot apply the link until you explicitly confirm the fingerprint. The Add Child sheet explains that the Child uses this Home's providers over SSH and lists the prerequisites above. Host aliases come from `~/.ssh/config` on the Home running OpenCodex, not necessarily the computer displaying the browser. If discovery succeeds with no hosts, add a `Host` entry like this, then choose **Rescan hosts**. You can also enter an existing alias manually; selecting or entering an alias enables **Test connection**. The sheet links to this guide. +Host discovery also follows top-level `Include` directives. Parentheses and braces in an included filename stay literal when combined with wildcards: for example, `Include conf.d/*(1).conf` finds `backup(1).conf`, and `Include conf.d/shard-{1..3}-*.conf` looks for filenames containing `{1..3}`. An `Include` inside a `Host` or `Match` block is conditional and is not used for discovery. + ```sshconfig Host devbox HostName devbox.example.com @@ -49,6 +51,12 @@ Connecting restarts OpenCodex on this computer. Codex turns that are already run The Child waits for its configured port while the old process releases it. If a CLI-managed restart still fails, run `ocx start` on the Child and check `~/.opencodex/restart-handoff.log`. In the desktop app, the app starts and supervises the replacement automatically. +An explicit `ocx stop` on a Remote Link Child stops its proxy and, when shared restoration succeeds, restores native Codex routing, its catalog and backed-up resume-history metadata and removes the managed Grok configuration. The saved Home connection is kept; use `ocx disconnect` to remove that connection. + +If a hub connection takes ownership while stopping, its routing and configuration are preserved. A connection still being created or disconnected can refuse restoration; let that operation finish, then retry `ocx stop`. The dashboard stop API returns HTTP 409 with `sharedTeardown: "refused"` when ownership cannot be confirmed and keeps the listener running. Signal cleanup also preserves configuration when ownership cannot be confirmed. + +To use Home from Codex again after restoration, start the Child with `ocx start` (or `ocx service start` for an installed service), then run `ocx sync --restart-codex`. Starting the runtime does not reapply a Child's Codex routing. Sync reapplies Codex settings when Codex is enabled for the saved connection, and the flag restarts Codex to load them; it does not recreate the Grok block. This is the explicit Link Child stop/start workflow; hub-client ownership and the separate restart, recycling, service-exit and sibling rules are unchanged. + If **Child** says to pair this machine first, open this computer's configured literal-loopback HTTP dashboard, for example `http://127.0.0.1:`. The local pairing form appears only when pairing is missing and the dashboard and API use the same loopback origin. Copy the form's `ocx gui pair --origin "http://127.0.0.1:"` command, run it in a terminal on this computer, and paste the one-use code into the form. Use the exact origin shown in the form; a provider API key or admin token is not a pairing code. Missing pairing is separate from a configured-port mismatch. On a Hub dashboard opened through a non-loopback address, the browser may have no loopback session or may have a shared session that cannot manage machine links. When Remote Link reports that session or permission problem, choose **Connect this dashboard to the hub** in the Remote Link page to open the one-time pairing form. Run the displayed command on the Hub and enter its code. The page validates the new session's Remote Link access before it closes the form. @@ -59,30 +67,44 @@ The **Child** role also requires a standalone OpenCodex runtime running on its c - **Connected** means the SSH tunnel is ready and the Child can use the Home link. - **Reconnecting** means the tunnel is being retried. Requests can temporarily return `503` with `Retry-After` while the retry is in progress. On a Child that connected from its own dashboard, a request first waits up to 15 seconds for the tunnel to come back. -- **Failed** means the link needs attention. Check SSH authentication, the confirmed host key, forwarding, or the timeout reason shown in the dashboard. The side that runs the SSH tunnel keeps retrying by itself, after sleep, an outage or a restart: Home for a Child it added, and the Child for a link it joined from its own dashboard. It retries about once a minute after a timeout or forwarding error, and every five minutes after an authentication error. A changed host key is never retried. To try again at once, select **Retry** in the Home's dashboard or run `ocx link reconnect --link-id ` on the Home. It restarts that link's tunnel without restarting OpenCodex. +- **Failed** means the link needs attention. Check SSH authentication, the confirmed host key, forwarding, or the timeout reason shown in the dashboard. The side that runs the SSH tunnel keeps retrying by itself, after sleep, an outage or a restart: Home for a Child it added, and the Child for a link it joined from its own dashboard. After a timeout or forwarding error the Home retries a Child it added every minute, so a laptop that slept reconnects within about a minute of waking; a Child that joined from its own dashboard retries after one minute and doubles the wait after each retry that fails again, up to five minutes. After an authentication error either side retries every five minutes. A changed host key is never retried. To try again at once, select **Retry** in the Home's dashboard or run `ocx link reconnect --link-id ` on the Home. It restarts that link's tunnel without restarting OpenCodex. A failed link does not silently switch to a local provider. The Child returns a retryable `503` without forwarding the link key or request when its tunnel is failed, stopped, or not supervised. It also keeps the key local when another process owns the tunnel port; free that port so the Child's SSH tunnel can bind it. +On a Child, `GET /healthz` only says that OpenCodex is running. `GET /readyz` (and `ocx ready`) also says whether the link can carry a request right now: while it cannot, it answers `503` with `Retry-After: 1`, `"status": "pending"` and a `link` object such as `{ "state": "unavailable", "reason": "home_unreachable" }`, and while it can, `200` with `"status": "ready"` and `{ "state": "available" }`. The reasons are `tunnel_connecting`, `tunnel_failed`, `tunnel_idle`, `tunnel_unavailable`, `sidecar_invalid`, `home_unreachable`, `home_unauthorized`, `link_auth_failed`, `link_credential_unavailable`, `link_unverified` and `client_state_changed`. A Child that joined from its own dashboard answers from its tunnel. A Child that its Home added has no tunnel of its own to look at, so it asks the Home through the tunnel with the same credential-free check every relayed request starts with; it repeats that check at most once every five seconds, and answers `link_unverified` when the Home has not replied within half a second. + +The reason `client_state_changed` means the running Child's saved connection is missing or now names another owner or link. Its machine and link status endpoints also return `503` with this reason. Stop or restart the Child and check its connection before re-linking; this readiness result does not itself disconnect the relay. + +`ocx connect status` on a Child prints the same verdict as a `Link tunnel:` line under the local Codex CLI line: `up`, `down ()` with one of the reasons above, or `unknown` when no Child runtime is running (`runtime_not_running`), its answer could not be read (`runtime_unreadable`), or the Home check had not settled after one retry (`link_unverified`). `--json` carries it as `linkTunnel`. `Connection: connected` keeps meaning that this machine is linked; a Child whose laptop slept shows `Connection: connected` with `Link tunnel: down (home_unreachable)` until the Home reconnects the tunnel. + +If `ocx connect status --json` reports `disconnected` but a leftover service token prevents a new link, inspect the situation on the Child. After confirming that preserving the existing token files is intended, run `ocx disconnect --orphaned-token --yes`. It refuses a connected or pending client and any live client runtime or unverified runtime state. It also refuses a Hub, a non-loopback bind, a configured or matching admission secret, and an installed or unverified service: these can use the token for admission. On a Hub, manage the credential through the Hub service; otherwise inspect the bind, API keys, token environment and `ocx service status`, and remove or migrate a service only if intended before retrying. It moves the token and any rotation backup into a private directory under the OpenCodex config directory, prints the location, and does not infer that either token belonged to the link. On Windows, recovery requires hard-link support to preserve file identity while closing handles; if it reports an incomplete backup, inspect the reported directory and original files before retrying. If recovery was interrupted and a retry refuses with `unsafe token file` because another hard link exists, check the `orphaned-token-*` folders for a leftover `.service-api-token.identity` (or `.service-api-token.prev.identity`) file. Remove it only if it is a hard link of the current token file (the same file, not just the same name); keep any other pin, because it may be the only copy of an older token. Then inspect any remaining hard links to the token file before retrying. Stop OpenCodex to restore: move the saved files back only when the original names are absent. The command does not revoke a Home key or restore missing client configuration. + +To confirm which Home is serving a Child, compare the `x-opencodex-served-by` header on the Child's `GET /v1/models` with the `instanceId` in the Home's `GET /healthz`. The Child passes the Home's header through unchanged, so the two match while the link works. The value is an opaque id, never a hostname; see [Home identity and the served-by header](/reference/management-api/#home-identity-and-the-served-by-header). + ## What a Child shows and manages A Child runs on the Home's providers, accounts and settings, so the Home is where you change them. - **Dashboard.** The Child's dashboard shows the Home's state read-only and says "Managed by Home over Remote Link". Dashboard and Providers read the Home through the link, and the usage strip in the header shows the Home's quota. The model list is not shown on a Child, because building it runs provider discovery on the Home; Codex on the Child already offers the Home's models. For the same reason, the delegation and sidecar model pickers on a Child list the native models and the Home's current choices, not the Home's full routed list. Saving a change there is refused with a message that names the Home; make the change in the Home's dashboard. The Child's browser never receives a Home credential. - **Codex settings.** `ocx sync` on the Child (and connecting it) applies the Codex settings OpenCodex manages on the Home: Fast mode, the multi-agent mode, the web search sidecar switch, and the native sub-agent defaults when the Home syncs them. `ocx sync` and `ocx status` list the values that came from the Home. The default reasoning effort and the effort levels shown in the Codex app's model picker are Codex app settings on each computer; OpenCodex does not manage them on any computer. + + When OpenCodex Desktop or a background service supervises the Child runtime, sync succeeds after applying settings and reports that the runtime restart is deferred. The settings take effect when that supervisor restarts the runtime: use **Quit** in the OpenCodex tray menu, then reopen OpenCodex, or run `ocx service restart` for a service. - **CLI.** Commands that only read, such as `ocx account list`, `ocx provider quota` and `ocx usage`, read the Home. They show what the Home has already observed: a read from a Child never makes the Home probe a provider, refresh a token or start a process, so quota and account details are as fresh as the Home's own activity keeps them. Reads that only exist to run provider discovery or a forced refresh, such as `ocx models live`, `ocx models preset show` and `ocx account list --quota`, are refused like changes. Commands that change configuration are refused with one message that names the Home and the link and says no request was sent. `ocx status` describes the Home and the link. `ocx provider list` and `ocx config get` still show this computer's own configuration, labelled as local and inactive while the computer is linked. `ocx config set`, `ocx config unset` and `ocx config import` still write locally, each with the same note, and `ocx provider add`, `remove` and `set-default` are refused because those providers are not used while linked. +An import that would replace or remove an active client connection is refused. Disconnect that client first, or import a file that preserves its connection record exactly. + These reads need an OpenCodex version with the Remote Link management relay on both the Home and the Child. An older Home answers with a message asking you to upgrade it. ## Remove a Child -Select **Disconnect** for the Child and confirm the alias. The Home stops the tunnel, revokes that Child's link key, and removes the saved link record. +Select **Disconnect** for the Child and confirm the alias. The Home stops the tunnel, revokes that Child's link key, and removes the saved link record. On a lightweight (`ocx-child`) Child, disconnecting restores `~/.codex` and stops the relay with zero background processes while keeping `~/.cache/opencodex/bin/ocx-child` cached by default for fast reconnects; check **Also delete the planted lightweight agent binary from the remote computer** (or pass `--purge` to `ocx link revoke`) to delete the planted binary as well. Home runs that purge through the planted binary at `~/.cache/opencodex/bin/ocx-child` (`%LOCALAPPDATA%\opencodex\bin\ocx-child.exe` on Windows), never through another `ocx-child` on `PATH`. If that file is missing, or the Child does not confirm that it deleted the binary, Disconnect reports an error and keeps the link so you can retry, disconnect without the purge option, or remove the file yourself. `--purge` applies only to a lightweight Child: Home refuses it for a full OpenCodex install, and for a link saved before Home recorded the Child type it checks the Child first. If the Home cannot reach the Child to run its disconnect command, choose **Remove here only**. This removes the local tunnel, key, and record. Then log in to the Child and run: ```bash -ocx disconnect +ocx disconnect # or ~/.cache/opencodex/bin/ocx-child detach on a lightweight Child ``` To disconnect a Child-initiated link, run `ocx disconnect` on the Child. It disconnects the client tunnel and revokes the link on Home over SSH. If Home revocation fails, it prints: `Home revoke failed; run ocx link revoke --link-id on the home.` @@ -95,6 +117,20 @@ When a step fails, the dashboard shows the reason and, when SSH reported one, a - **ocx was not found on the remote computer**: OpenCodex looks for `ocx` on the PATH of a non-interactive SSH session first, then in `~/.bun/bin`, `~/.local/bin`, `/opt/homebrew/bin` and `/usr/local/bin`. If it is installed elsewhere, add that directory to PATH in a file the remote shell reads for non-interactive sessions, such as `~/.zshenv` for zsh. - **OpenCodex on the remote computer is too old**: run `ocx update` on that computer. Remote Link needs 2.66.0 or later. - **The remote computer did not report an OpenCodex version**: `ocx --version` on that computer printed something else, for example the usage text of an unsupported Windows install. +- **Requests fail with `home_unreachable` while the Home is down**: a Child never serves requests from its own providers. When the tunnel is down before a request is forwarded, the Child answers a retryable 503 and sends nothing to the Home. If the tunnel drops after forwarding started, the answer is also `home_unreachable`, but the Home may already have received the request. A failed link relay authentication answers `link_relay_auth_failed` instead: upgrade the Home and Child or re-link. Whether GOAT may move that device's work to its own sign-ins is the per-device local fallback permission on the Home's **Remote Link** page, or `ocx fallback local on --device `; see [Fallback off](/guides/fallback-off/). +- **A Home link stays Failed with a forwarding error after the Home slept or changed networks**: run `ocx link status --json` on the Home. Its `tunnel` field shows the attempts since the link was last connected, `nextRetryAt`, and the last failure. A `lastFailure.cause` of `remote_forward_conflict` means the Child's SSH server still holds the tunnel port for the session that died with the Home's old connection, so every new tunnel is refused until it lets go. OpenCodex keeps retrying and connects on its own once the port is free; it never stops processes on the Child. The Child's SSH server notices a dead session only when it probes it. Without `ClientAliveInterval` in the Child's `sshd_config`, that can take as long as the operating system's TCP keepalive (two hours by default on macOS). Setting `ClientAliveInterval 15` and `ClientAliveCountMax 3` there makes it drop such a session within about a minute. + +### Retryable 503 diagnostics + +A relay-generated `503` includes a server-generated `x-opencodex-link-request-id`. Use it to correlate a failure with local evidence under the Child's OpenCodex configuration home: `link/diagnostics.jsonl` and one rotated backup, `link/diagnostics.jsonl.1`. Each file is capped at 256 KiB, with private permissions (directory 0700 and files 0600 on POSIX; private ACLs on Windows). Records contain only fixed event/outcome/state categories, generated correlation IDs, numeric timing/generation/attempt metadata and timestamps, never secrets, request bodies, headers, URLs, account identifiers or raw errors. Each event/outcome pair is limited to one record per second; the next record includes a count of suppressed events, so an absent record does not prove an absent failure. A backward wall-clock adjustment starts a new rate-limit window, including when the writer queue is full, and preserves the suppression count. An asynchronous writer keeps at most 56 pending records, counts overflow as suppression, and yields while Windows ACL work runs. Logging is best effort and cannot change whether a request is admitted. Graceful signal shutdown and standalone recycling wait up to one second for queued diagnostics before exiting; stalled storage, forced termination and power loss can still lose records. + +`owner_lookup` records refused ownership checks; routine successful checks are silent. `owner_lookup.elapsedMs` measures the owner lookup itself. For `auth_timeout`, `relay_retry` and `relay_failure` report the actual transport-attempt duration in `elapsedMs` (normally about five seconds). A `relay_recovered` event with outcome `recovered` is emitted only after a retry receives an upstream response with `upstream.ok` (HTTP 2xx); it does not prove the streamed body completed. Rate limiting makes request-ID correlation sampled evidence, not a guaranteed trace of every failed request. + +The Home writes the same kind of file under its own configuration home for the tunnels it runs. Each change of a Home-initiated tunnel's state is a `tunnel_transition` record with `previousState`, `state`, the cause as `outcome` (`auth`, `hostkey`, `forward`, `remote_forward_conflict`, `timeout`, `network`, `unknown`, `spawn_failed` or `listener_unavailable`; `connected`, `spawned` or `stopped` when nothing failed), the `attempt` count since the link was last connected, the link's `tunnelPort` and, when a retry is scheduled, `retryAfterMs`. A retry of a failed link that fails again is recorded too, so an outage leaves one record per attempt. The same rate limit applies, across all links. + +Before sending data, OpenCodex allows one shared preflight retry for either an owner-lookup deadline or a specifically identified five-second authentication deadline. The retry obtains fresh owner proof where required and a fresh physical socket, then authenticates that socket before sending the link credential or body. It does not reuse cached owner approval, bypass security checks, restart SSH or OpenCodex, or replay a dispatched request body. The two-second owner-lookup and five-second authentication deadlines are unchanged for each attempt; other failures do not qualify for this preflight retry. + +This can recover these transient deadline paths and helps diagnose future failures. It does not establish the historical cause of [#7297](https://github.com/lidge-jun/opencodex/issues/7297). ## Security @@ -110,8 +146,11 @@ ocx link issue --alias --tunnel-port [--json] ocx link status [--json] ocx link revoke --link-id [--json] ocx link reconnect --link-id [--json] +ocx link check (--link-id | --all) [--no-wait] [--json] ``` +`ocx link status` needs the local admin token on a listener that only this machine can reach. When the public listener is bound to a non-loopback address, for example a Hub on `0.0.0.0`, no TCP listener qualifies: the hub management listener is reached through Tailscale Serve, so it refuses the raw admin token for link routes. On macOS and Linux the proxy therefore also opens a private Unix socket, `/run/control-.sock`, in a directory only your user can enter, and `ocx link status` uses it automatically. The socket answers only `GET /api/link/status` and still requires the admin token. Windows and runtimes older than this change keep the TCP path, where the read returns `403` on such a Hub. + ## Related guides - [Remote Hub Deployment](/guides/remote-hub/) @@ -123,12 +162,42 @@ Update both the Home and Child when upgrading to connection-bound relay authenti Removing the final Home link drains pending authenticated relay requests before releasing its listener. Stopping the process still cancels active connections. This does not change which caller credentials are stripped or which routes can be relayed, and it does not replace SSH's host-key verification. +### Home and Child versions + +On the Home, `ocx link status --json` reports the Home's own `local` version, relay authentication version and features, and gives every link a `peer` block. Nothing is read over SSH: the Home learns about a Child from the relay authentication check the Child sends before each relayed request. From 2.91.0 that check also carries the Child's version and feature list. The Home keeps what it learned in memory, so after a Home restart a link reads `unknown` until its Child relays a request again. + +| Part of the link | First release | +|---|---| +| `relay-auth/2`, connection-bound relay authentication | 2.69.0 | +| `link-management-relay`, read-only Home management on the Child | 2.84.0 | +| `link-peer-report/1`, the Child reports its version and features | 2.91.0 | + +`peer.compatibility` is one of: + +- `compatible`: the relay authentication versions match, and the Home serves every feature the Child reports. A Child older than 2.91.0 reports no version; `peer.version` is then `null` and `peer.versionRange` gives the range its relay authentication implies, for example `{ "min": "2.69.0", "below": "2.91.0" }`. +- `degraded`: the Child reports a feature this Home does not serve. Upgrade the Home. +- `incompatible`: the Child asked for a relay authentication version this Home does not speak, so its relayed requests are refused. `peer.reasons` names the side to upgrade. +- `unknown`: the Child has not relayed a request since the Home started, or it sent a version or feature list the Home could not read, so its features cannot be checked. + +The version a Child reports is its own claim, bound to its link key. OpenCodex uses it for display and never for admission. Older `ocx` installations keep receiving the previous status document; only a 2.91.0 or newer CLI asks for these fields. + +### Child install, catalog and activity + +`ocx link status --json` on the Home also gives every link a `child` block. An older Home omits it, and an older CLI never asks for it. + +- `runningVersion` is the version the Child reported over the link. `installedVersion`, `installKind` and `update` (`route`, `reason`, `observedAt`) come from the last `ocx link check` and stay `null` until one ran. `versionSkew` compares the installed version, or the running one, with the Home's: `same`, `behind`, `ahead` or `unknown`. It is always `unknown` for an `ocx-child` Child. +- `catalog.state` is `current` when the catalog the Child last downloaded from the Home is the Home's current one, `behind` when the Home's catalog changed since, and `unknown` before the first download. The Home compares the catalog's content, not file times, so restoring an older catalog file also reads `behind`. A download proves only that the Child fetched the catalog, not that it applied it; the check `ocx link add` runs at enrollment counts as a download. +- `activity.idle` is `true` when no relayed model request has run on that link for 10 minutes. `inFlight` counts the requests running now. Token counting, catalog and readiness reads do not count, and a request from a Child older than connection-bound relay authentication counts against every link. +- `activeJob` names an operation running on that link, and `lastOperation` the last one that finished. `codex` is `null` for now. + +`ocx link check --link-id ` (repeatable) or `ocx link check --all` asks Children for their install facts. For each Home-initiated Child the Home runs the Child's `ocx update --plan` over the link's SSH connection, which computes an update plan and changes nothing; each call has a 60-second budget and three run at a time. A Child older than 2.97.0 does not have that command: the item reads `owner-action` with reason `legacy-ocx`, and the Home learns the version from one more read-only SSH call on macOS and Linux, or from the version the Child reported over the link on Windows. On an npm or pnpm Child without a recorded serving install, the command runs through the `ocx` launcher, so the launcher's usual startup bookkeeping runs first, as it does for every `ocx sync` the Home sends there. Links a Child started from its own dashboard and `ocx-child` Children are reported without SSH. The command waits for the job and prints it as JSON (`--no-wait` prints it at once); it exits 0 when every Child answered, 6 when a Child is busy, offline, too old or not checkable, 1 on a failure, 4 for an unknown link or a Home too old for this command, and 5 when another operation is running on that link. + ### Standalone pairing authorization The existing `ocx gui pair --origin ` command works while OpenCodex runs as a background service. Run it under the account that owns the service's private OpenCodex home, then enter the returned one-use code in the local dashboard. No server terminal, additional password, Windows Hello or hardware key is required. The CLI and server must use the same current version and configuration home; restart an older server after updating. Mixed-version Hub invitations also require updating the CLI and server together. Pairing refuses a symlinked configuration home or intent directory; use the actual protected directory as `OPENCODEX_HOME`. -Internally, the CLI creates a short-lived authorization commitment and attempts to remove it after use or failure. Reading runtime information alone does not authorize pairing, and the verifier is not stored on disk. This is a private-home write-access boundary, not biometric or human-presence authentication: a program with full access to that user's files is still trusted. Existing Hub invitation authorization is unchanged. If a pairing request fails, run a fresh command after resolving the reported problem. This does not add Windows SSH Remote Link support. +Internally, the CLI creates a short-lived authorization commitment and attempts to remove it after use or failure. Reading runtime information alone does not authorize pairing, and the verifier is not stored on disk. This is a private-home write-access boundary, not biometric or human-presence authentication: a program with full access to that user's files is still trusted. Existing Hub invitation authorization is unchanged. If a pairing request fails, run a fresh command after resolving the reported problem. SSH Remote Link on Windows uses the separate PowerShell execution path described above. If a process is interrupted during pairing, rerun the command to obtain a new authorization. Do not manually remove pairing state while the service or a pairing command is running. @@ -140,7 +209,30 @@ The check covers the intent folder and record. It does not protect against repla On the Home, run `ocx link probe child-a --json` to inspect the offered SSH fingerprint, key type and OpenCodex version. Verify the fingerprint through a trusted source. Then run `ocx link add child-a --expect-fingerprint SHA256:… --json`. The command probes again and refuses a mismatch before storing trust or issuing a key. Without the fingerprint flag, it requires an interactive terminal and an explicit `yes` after showing the fingerprint. It never prints the link key. -Home-initiated connections now restart the Child after saving its connection, including capable older Child installations. The Child must already serve standalone OpenCodex on its configured port, expose bound restart support, and have curl installed. Update or disconnect a Child that fails this preflight. Desktop and system OpenCodex installations take precedence over generic PATH shims; broken candidates are skipped. Windows Children remain unsupported. +Home-initiated connections now restart the Child after saving its connection, including capable older Child installations. The Child must already serve standalone OpenCodex on its configured port and expose bound restart support. POSIX Children need curl; Windows uses a bounded loopback HTTP request through .NET. Update or disconnect a Child that fails this preflight. On macOS and Linux Children, Home first runs the OpenCodex installation that most recently started serving the Child, including an npm install under a custom prefix, even when another installed copy is newer. An older desktop app or PATH copy no longer answers for it. If that installation is gone or cannot report its version, Desktop and system OpenCodex installations take precedence over generic PATH shims; broken candidates are skipped. Windows x64 Children use encoded PowerShell commands without consuming key stdin. The preflight reads `ocx config show --json` under the runner's 4 MiB capture limit, so a Child with a large saved configuration still accepts a link; output past that limit answers `child_preflight_output_limit` and names the command to trim. When a phase fails, `ocx link add` prints the phase together with the Child's own reason, for example an invalid saved configuration or the failing command's last error line. That reason is shortened and has OpenCodex keys and URL query strings removed. + +### Ephemeral Child machines (`ocx-child`) + +For disposable SSH devboxes, containers and lightweight cloud VMs where installing the full Bun OpenCodex runtime is unnecessary, Home can stream a SHA-256-verified standalone `ocx-child` binary (no Node or Bun required on the Child) over SSH `stdin` into `~/.cache/opencodex/bin/ocx-child` (`%LOCALAPPDATA%\opencodex\bin\ocx-child.exe` on Windows) when you choose **Plant lightweight agent & connect** in `#remote` or run `ocx link add --plant --expect-fingerprint SHA256:…` (an interactive `ocx link add ` asks once before planting). The Child downloads nothing, so it needs no outbound internet access, but a POSIX Child must have `sha256sum`, `shasum`, or `openssl`: the binary is checked against its SHA-256 before it is installed or run, and without one of those tools the plant is refused (`hash_tool_unavailable`). You can also pre-place `ocx-child` in `~/.local/bin/ocx-child`, `~/.cache/opencodex/bin/ocx-child`, or `PATH`. Before enrollment, Home probes every full `ocx` candidate first and falls back to `ocx-child` when no runnable full `ocx` is present; once `$OPENCODEX_HOME/child/state.json` exists, remote commands keep targeting `ocx-child` until it detaches. + +Home plants only a build it can verify, and it does not download or build one. The npm package and the desktop app ship no `ocx-child` builds, so on a packaged install the probe reports the bare host as not plantable (`plantable: false`, `plantUnavailableReason: "artifact_not_found"`) until you provide one. Home looks in these places, in order, for the Child's target (`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, or `windows-x64`): + +1. The directory named by `OPENCODEX_CHILD_BIN_DIR` on Home: `ocx-child-` (`ocx-child-windows-x64.exe` for Windows) or `/ocx-child`, plus plain `ocx-child` when the Child has the Home's own target. The file must be listed in a `SHA256SUMS` file in the same directory. +2. A `native-bin/` directory next to the OpenCodex sources or the running executable, with the same `SHA256SUMS` rule. No OpenCodex package provides this directory today. +3. In a source checkout only, `native/ocx-child/target/release/ocx-child` when the Child has the Home's own target. +4. `$OPENCODEX_HOME/cache/ocx-child//ocx-child-` with a `SHA256SUMS` file beside it. Nothing fills this cache automatically; copy builds there yourself. + +To prepare a build, run `cargo build --release --locked --manifest-path native/ocx-child/Cargo.toml` in a source checkout (cross-compiling for other targets), copy the result to one of those directories under the `ocx-child-` name, and write its `SHA256SUMS` line with `sha256sum ocx-child- >> SHA256SUMS` (or `shasum -a 256`). The files must not be symlinks or group- or world-writable. + +Unlike a full `ocx` Child, a clean detached `ocx-child` host needs no pre-running background daemon before `ocx link add`: Home checks target-port availability and `~/.codex/config.toml` ownership before committing (`409 child_port_busy` if port `10100` is held by another process, or `409 child_external_provider_conflict` if another model provider or custom base URL already owns `config.toml`, leaving Child files untouched and rolling back any newly planted binary), pipes the link credential over SSH stdin, starts `ocx-child serve`, and confirms an authenticated `/v1/catalog` relay. Connected rows in `#remote` display a **Lightweight** / **Full install** badge and a **Home settings synced** / **Sync needed** parity badge. Running `ocx link revoke --link-id ` keeps the cached binary for fast re-attach, whereas `ocx link revoke --link-id --purge` (or `ocx-child detach --purge` on the Child) also deletes the planted binary from the managed cache directory. + +Keep `OPENCODEX_HOME` and `CODEX_HOME` pointed at the same directories throughout the connection. If detach reports a restore or shutdown error, keep the Child's recovery files and resolve the error before retrying. + +### Windows computers + +A Windows x64 Child needs OpenSSH Server, Windows PowerShell and either standalone `ocx.exe` or lightweight `ocx-child.exe`. Home recognizes Windows during the probe, records it with the link, and runs every Child command through PowerShell over the same pinned SSH connection, whether the SSH default shell is cmd or PowerShell. The link key still travels only on standard input. Closing the SSH connection ends the selected remote Child command. If Windows PowerShell on the Child cannot load the helper that contains the selected executable in a kill-on-close Job, for example under Constrained Language Mode, the command is refused and nothing runs. If Home cannot tell which platform the Child runs, it stops before issuing a link key. + +Run `ocx link cleanup` on Home to inspect recorded Child platforms without changing them. Current Home releases disconnect Windows Children through PowerShell. If a remote disconnect fails, resolve the reported shell or installation error and retry; **Remove here only** remains an explicit recovery action that can leave the Child needing a local disconnect. Restart waits for running turns and may take several minutes. Success requires the restarted Child to serve the client role and relay a fresh complete catalog to this Home. SSH setup has a bounded allowance derived from measured latency; relay verification starts after restart with its own 15-second window. Errors name the failing phase. If an error reports residual Child configuration, run `ocx disconnect` and `ocx restart` on that Child before retrying. Home cleanup alone does not restore Child configuration. A CLI timeout reports an uncertain outcome; inspect Home `ocx link status` and Child `ocx connect status` first. diff --git a/docs-site/src/content/docs/guides/remote-workspace.md b/docs-site/src/content/docs/guides/remote-workspace.md index 1ebc0f725a..ade9bc5ed6 100644 --- a/docs-site/src/content/docs/guides/remote-workspace.md +++ b/docs-site/src/content/docs/guides/remote-workspace.md @@ -167,6 +167,8 @@ to another computer or folder silently. If the Executor disconnects, the session Prompt submission acknowledges acceptance immediately; the dashboard polls the session for progress and completion. If the acknowledgement is lost, the draft remains visible with an unknown-submission notice. Check session progress before sending it again; the dashboard never retries a prompt automatically. +If the Pi process exits or its extension fails while a turn is starting, the session reports the failure even if Pi has not acknowledged that turn yet. + **Stop** remains available while a prompt is running. It interrupts the Hub coding-agent turn, cancels an active Executor command, and prevents a late response from reopening the stopped session. diff --git a/docs-site/src/content/docs/guides/sidecars.md b/docs-site/src/content/docs/guides/sidecars.md index 1e353a4a48..0ff80e3627 100644 --- a/docs-site/src/content/docs/guides/sidecars.md +++ b/docs-site/src/content/docs/guides/sidecars.md @@ -18,6 +18,11 @@ closed. Explicit `xai` requires a usable stored Grok OAuth account and does not requires both ChatGPT login auth and an enabled `forward` provider. ::: +On file load, a retired OpenCode Free model target in global or `claudeCode` overrides of +`visionSidecar` or `webSearchSidecar` is removed and that sidecar is explicitly disabled, retaining +its other settings. Select a supported target before re-enabling it. Healthy targets and the defaults +for absent sidecar sections are unchanged. + ### Additional web-search backends (explicit-only) Three more web-search backends exist beyond the ChatGPT and Claude paths. Each is @@ -32,6 +37,12 @@ a missing credential produces no sidecar plan and the request takes the normal r ## Web-search sidecar +Anthropic search-model calls and their connection-reset retries also consume the logical request's +shared model-send and token allowances on routed Responses, including RunTurn adapters and the +passthrough search bridge. `maxSearchesPerTurn` does not grant extra model sends. If admission is +exhausted, that search returns an error result without contacting Anthropic. Helper admission does +not spend the routed model's final-recovery reserve. Standalone `/v1/alpha/search` keeps its existing behavior. + When Codex requests hosted `web_search` for a non-passthrough routed model, opencodex: 1. **Drops** the hosted `web_search` tool and exposes a synthetic `web_search(query)` function tool @@ -138,6 +149,19 @@ failures after response headers have started are delivered as `response.failed` ## Vision sidecar +Mistral's `zai-glm-5-3` is enrolled by the provider preset as text-only. With the +vision sidecar enabled and available, OpenCodex describes attached images and +sends their text descriptions to GLM. The Codex catalog advertises image +attachments for this route. After an update, run `ocx sync`, then fully quit and +relaunch the Codex desktop app or reload the VS Code window. Sync without a +restart flag does not restart an existing Codex app-server, which can retain +the old model list. Alternatively, use `ocx sync --restart-codex` to sync and +restart matching Codex processes and the desktop app. Finish active work first: +this restart ends live conversations. See the [sync and restart reference](/reference/cli/lifecycle/#ocx-sync---restart-codex---restart-app-server-only). +After relaunch, select `mistral/zai-glm-5-3` and verify that image attachments +are available. No model modality override is needed. Mistral documents native input in its +[GLM 5.3 reference](https://docs.mistral.ai/models/zai-glm-5-3). + Image routing is capability-aware. Before an image-bearing upstream send, opencodex resolves the selected model's effective input modalities from runtime provider evidence, explicit operator declarations, backend/registry metadata, and generated vendor metadata. A target positively known to be text-only goes through the Vision Sidecar first; the image is described **before** the main call and replaced inline with text. A target positively known to support images receives the image directly. Unknown custom models keep the existing compatibility behavior rather than being guessed text-only. For the canonical ChatGPT Codex route, opencodex uses the `openai-codex` metadata bundle rather than public OpenAI API metadata, so backend-specific modality differences are respected. The native Chat fast path uses the same gate and cannot bypass a known text-only verdict. Without an available sidecar plan, raw images are stripped before a proven text-only backend. @@ -265,3 +289,15 @@ Claude Code OAuth fingerprint precedent, but should be soak-tested with the intended account and workload. See the [Configuration reference](/reference/configuration/server/#sidecars) for every field. + +Search responses with malformed optional fields retain valid answer text and citations. Invalid error-message values use a generic failure message. A repeated full-text completion for the same output part replaces its previous snapshot instead of duplicating the answer; distinct output parts remain separate. + +A completion that omits a content index cannot merge parts with different known content indexes. If a final message has malformed or missing content, its unique item ID still preserves its output position when recovering streamed text. Conflicting positions and duplicate final item IDs do not provide that ordering evidence. + +The OpenAI search and vision sidecars accept CR, LF and CRLF line endings, including mixed endings and CRLF split across network chunks. They read a final completion or failure event even when the server closes the body without a trailing newline. The first terminal event or `[DONE]` ends collection; later frames are ignored even when they share its network chunk. An unfinished response or one stopped by a size limit still reports an error. + +When a search answer ends with a Sources list, an unmatched list item stays in the answer instead of being removed as a citation. A title followed by its URL is still consumed as one citation. Non-HTTP URI-like text inside inline code, such as `mode:fast`, stays in the answer; code-formatted HTTP(S) URLs are still citations. + +Final response citations supply the title for a URL already seen during streaming. When the final response cites the same URL more than once, the first valid title among those citations is used. If no final title is valid, a valid streamed title is retained. Streaming-only sources are kept within the existing source-count, URL, title and byte limits. + +Long search queries and answers are shortened without splitting a UTF-16 surrogate pair, so a single character such as 😀 is never cut in half by the result limits. A sequence of several characters, such as emoji joined with a zero-width joiner, can still be cut between its parts. diff --git a/docs-site/src/content/docs/guides/sub-agent-surface.md b/docs-site/src/content/docs/guides/sub-agent-surface.md index 67ec9f1a8a..eab0c0000b 100644 --- a/docs-site/src/content/docs/guides/sub-agent-surface.md +++ b/docs-site/src/content/docs/guides/sub-agent-surface.md @@ -79,6 +79,65 @@ For a v2 roster, eligibility has three states: an entry stamped `"v2"`, explicit with no `multi_agent_version` field is eligible. A genuine `"v1"` pin is excluded because it states that the model belongs to the other collaboration surface. +## Which models `spawn_agent` advertises + +Codex lists at most five models in the `spawn_agent` tool description, and it chooses them +itself: it sorts the picker-visible catalog rows by `priority`, lowest first, and takes the first +five. The roster on the **Subagents** page (`subagentModels`) shapes that list only by giving its +models the lowest priorities in roster order (`0` through `4` without account selectors). It +does not limit the list to the roster. + +When you feature one to four models, Codex fills the remaining slots with the next rows by +priority. You did not choose those rows, and the dashboard does not show which ones they are. They +depend on the catalog: + +| Catalog | Rows that fill the remaining slots | +| --- | --- | +| No Codex account selectors | Other routed `provider/model` rows. They all share priority `5`, so they appear by provider name and then model id, alphabetically. Unfeatured native GPT rows use `featured.length + 100 + sourcePriority`, preserving native source order behind those routed rows. | +| Codex account selectors | Account-qualified native rows (`/`), which directly follow the featured rows. Unfeatured routed rows move to priority `1005` and come after them. | + +For example, with no account selectors and this roster: + +```json +{ "subagentModels": ["xai/grok-4.5", "anthropic/claude-sonnet-5"] } +``` + +| Slot | Model | Priority | Why | +| ---: | --- | ---: | --- | +| 1 | `xai/grok-4.5` | `0` | First roster entry | +| 2 | `anthropic/claude-sonnet-5` | `1` | Second roster entry | +| 3 | `deepseek/deepseek-v4-flash` | `5` | First remaining routed row alphabetically | +| 4 | `google/gemini-3-pro` | `5` | Next routed row | +| 5 | `moonshot/kimi-k3` | `5` | Next routed row | +| 6+ | `zai/glm-5.2`, then native GPT rows | `5`, then `102 + sourcePriority` | Outside the five | + +The native source rank uses current discovery before the pristine backup, exact-model retained +source rank and upstream snapshot, with fallback `9`. Repeated sync and feature/unfeature preserve +that unbanded rank. The live list, published catalog and cache agree for equal inputs. See +[Model ordering](/guides/model-ordering/) for validation and picker-order overrides. + +With an empty roster, opencodex pins nothing and the five follow the catalog's normal +priorities. + +The filled slots are ordinary advertisements, so the main agent may pick one of those models. +The list is also not an allowlist: Codex accepts a catalog model outside the five when the main +agent names it exactly. To control what Codex advertises: + +- Feature five models. With a full roster, no slot is left to fill. +- Disable a model you never want offered, or leave it out of its provider's `selectedModels`. + A disabled or unselected model leaves the picker and cannot fill a slot. +- `modelPickerOrder` changes the priorities Codex sorts by. A routed-only list moves the listed + unfeatured rows to `1000` and up, so the unlisted routed rows fill the slots first. A list that + contains a bare native id orders the complete picker, featured rows included: listed rows come + first and take the advertised slots before any unlisted row. See + [Model ordering](/guides/model-ordering/). + +On v2, Codex skips rows pinned `"disabled"` before it takes the five; otherwise the window works +the same way. The opencodex v2 guidance roster (`{{roster}}`) names only configured roster models +inside the five, so filler models appear in Codex's tool description and never in opencodex +guidance. Codex reads the catalog when a session starts, so a roster change applies to new +sessions. + ## Delegation model and effort The dashboard's **Sub-agent delegation** controls three related settings: @@ -92,7 +151,8 @@ description of the work Codex usually hands off, sizes it with one call to your and proposes the cheapest sufficient model and an effort from the list the picker offers, with the reasoning and the signals that would move it up or down. Nothing changes until you choose **Use this**, which saves exactly like picking the model and effort by hand. Tiers come from -`codexRoleTiers` or price, as in [role auto-assign](/guides/integrations/#auto-assign). +`codexRoleTiers` or price, as in [role auto-assign](/guides/integrations/#auto-assign), without the +measured scores role auto-assign can read from configured sources. `multiAgentGuidanceEnabled` defaults to on and is the master switch for opencodex-authored guidance on both surfaces. Turning it off suppresses both the v2 designation block and v1 proactive text. @@ -137,9 +197,12 @@ opencodex no sign that v1 is available, so the guidance is not added there. The default-off `syncCodexSubagentDefaults` option is separate from guidance. When opencodex owns active Codex routing, sync or restart can write the selected values as marker-owned `[agents] default_subagent_model` and `default_subagent_reasoning_effort` entries in Codex TOML. -opencodex updates or removes only fields bearing its markers. If either target field is user-owned, -the pair is left unchanged rather than partially written; ambiguous TOML is rejected without a -write. External provider managers and user-owned root routing also remain authoritative. +opencodex updates or removes only fields bearing its markers. If you edit a managed value in place, +the next sync keeps your value, drops the marker, and treats the field as yours from then on. +Restore also keeps those edits when they recreate previously injected file contents. If +either target field is user-owned, the pair is left unchanged rather than partially written; +ambiguous TOML is rejected without a write. External provider managers and user-owned root +routing also remain authoritative. ## Fallback chains @@ -306,6 +369,12 @@ a positive partial count before passing a model or effort override. It may be picker-hidden, outside the five-model display limit, missing from the catalog, or pinned to v1. A `"v2"`, `null`, or absent surface value is eligible; a real `"v1"` pin is not. +### Why does `spawn_agent` list models I did not feature? + +Codex fills up to five advertised slots from the catalog by priority. With fewer than five +featured models, the next rows take the remaining slots; see +[Which models `spawn_agent` advertises](#which-models-spawn_agent-advertises). + ### Do mode changes affect running sessions? No. Start a new Codex session after changing the mode. If a long-running App host still shows stale diff --git a/docs-site/src/content/docs/guides/telemetry.md b/docs-site/src/content/docs/guides/telemetry.md new file mode 100644 index 0000000000..0b6d8c8564 --- /dev/null +++ b/docs-site/src/content/docs/guides/telemetry.md @@ -0,0 +1,397 @@ +--- +title: Telemetry and Privacy +description: Anonymous daily usage statistics, consent and agent boundaries, opt-out controls, payload preview, and collector retention. +--- + +opencodex includes anonymous, daily usage telemetry so maintainers and the community can see which +versions, platforms, install channels, provider kinds, and coarse model families are used in +practice and where request failures occur. Project-wide daily aggregates (active and new install +counts, a 365-day active-install heatmap, active minutes, request outcomes, five-bucket token +totals, daily and range provider-kind and model-family shares, top-50 version counts, OS/CPU +platform and install-channel counts, and error-cause counts) are served publicly by the +collector's read-only `GET /v1/stats` endpoint for the [public project dashboard](/dashboard/); per-day install +hashes (`installDayHash`) and rate-limit hashes (`ip_hash`) are never returned by `/v1/stats`. + +Telemetry is **on by default**, and **nothing is sent until a person has seen the notice**. + +## How consent and the default-on rule work + +A fresh install — or an existing install that updates into a release with telemetry and has no +saved decision — starts in the `awaiting-notice` state. While in `awaiting-notice`, the proxy +sends no telemetry. + +Sending becomes active only after a person has seen the disclosure or recorded a choice: + +1. **Web dashboard popup (`TelemetryConsentCard`)** — opens on a standalone or Home proxy on first + run or after an update when no decision is recorded and no environment opt-out is set (connected + Remote Link Child proxies defer telemetry management to their Home proxy). The **Share anonymous + daily usage statistics** checkbox is pre-checked. Clicking **Continue** saves `decision: "accepted"` + (or `"declined"` if unchecked), `decidedAt`, and `noticeShownAt` via `PUT /api/telemetry`. + Dismissing the dialog with Escape, the backdrop, or the close button — or merely loading the page + without clicking **Continue** — records **nothing** (`decision` and `noticeShownAt` stay unset, + and there is no notice-only endpoint). While undecided, the popup returns on the next app start + or dashboard load until you click **Continue** or record a choice in **Proxy details** or the CLI. +2. **Interactive terminal prompt** — `ocx start`, `ocx init`, and `ocx service install` first print + a disclosure block (what is sent, what is never sent, that project-wide aggregates are public at + `opencodex.me/dashboard`, how to inspect the exact payload with `ocx telemetry status --json`, + and how to turn telemetry off with `ocx telemetry disable`, `OCX_TELEMETRY=0`, `DO_NOT_TRACK=1`, + or the **Proxy details** toggle) and then ask `Share anonymous usage statistics? [Y/n]` once when + both stdin and stdout are interactive TTYs (`isatty`), `OCX_SERVICE` is unset, and `isAgentDriven()` + is false. Pressing Enter or `y` records `decision: "accepted"` (plus `decidedAt` and `noticeShownAt`); + `n` records `decision: "declined"`. +3. **Explicit enable** — turning on **Share anonymous usage statistics** in the dashboard under + **Proxy details** records `decision: "accepted"` right away (the panel already shows what is sent). + Running `ocx telemetry enable [--json]` in an interactive human terminal (where both stdin and + stdout are TTYs, not `OCX_SERVICE`, and not `isAgentDriven()`) prints the same disclosure block, + asks the `[Y/n]` confirmation prompt (default yes), and records `decision: "accepted"` when + confirmed. + +`resolveTelemetryStatus` (`src/telemetry/consent.ts`) evaluates effective state in this exact +precedence order: + +| Condition (first match wins) | Effective state | Status `reason` | +| --- | --- | --- | +| `OCX_TELEMETRY` is `0`, `false`, `off`, or `no` | Disabled | `env-ocx-telemetry` | +| `DO_NOT_TRACK` is `1`, `true`, or `yes` | Disabled | `env-do-not-track` | +| `telemetry.decision === "declined"` | Disabled | `declined` | +| `telemetry.decision === "accepted"` | Enabled | `accepted` | +| `telemetry.decision` unset and `telemetry.noticeShownAt` set | Enabled | `default-on` | +| `telemetry.decision` unset and `telemetry.noticeShownAt` unset | Disabled | `awaiting-notice` | + +## Agent-driven starts never enable telemetry + +An AI coding agent or automation harness must never answer the telemetry prompt or acknowledge the +disclosure on your behalf: + +- When `ocx start`, `ocx init`, or `ocx service install` runs under an agent or CI environment + (`CLAUDECODE`, `CODEX_THREAD_ID`, `CURSOR_TRACE_ID`, `CI`, and similar markers checked by + `isAgentDriven()`), in a non-TTY shell, or as a background service (`OCX_SERVICE=1`), opencodex + skips the prompt, prints a one-line notice at most once per version (tracked in + `/.telemetry-deferred`), and writes **neither** `noticeShownAt` nor `decision`. + The install stays in `awaiting-notice` and sends nothing until you use the dashboard or an + outside-agent terminal session yourself. +- `PUT /api/telemetry` requires a live human dashboard browser session (`hasHumanDashboardSession`). + Requests authenticated only with the management admin token or a remembered-device session are + refused with HTTP `403` (`code: "agent_consent_required"`). +- `ocx telemetry enable` requires an interactive human terminal (`isatty` on both stdin and stdout, + not `OCX_SERVICE`, and not `isAgentDriven()`). Otherwise it exits non-zero (`1`) with + `agent_consent_required` or `tty_required` and directs you to the dashboard. +- `ocx config set telemetry` and `ocx config unset telemetry` are refused for all callers, and + `ocx config import` ignores any imported `telemetry` block for every caller and preserves the + persisted `telemetry` configuration unchanged. +- Opting out with `ocx telemetry disable`, `OCX_TELEMETRY=0`, or `DO_NOT_TRACK=1` is always + permitted, including from scripts and agent sessions. + +As with GitHub starring, these checks guard the standard CLI and management API paths against +agent harnesses (`AGENT_ENV_VARS`) and admin-token callers; they are paired with the policy rule +that agents running as your local user must never edit `config.json` or mint a loopback session to +record consent on your behalf. + +## How to turn telemetry off + +You can disable telemetry at any time through any of these controls: + +1. **Windows installer** — the MSI has a page with this summary, a link to the + [privacy statement](/reference/code-signing/#privacy), and a **Send anonymous usage statistics** + checkbox, checked by default. Clear it, or pass `OCX_TELEMETRY_CHOICE=optout` to a silent + `msiexec /qn` install, and the desktop app saves `"decision": "declined"` the first time each + account on the computer starts it, before it resolves or starts any proxy (on a fresh install the + decline is held in `telemetry-state.json` until a `config.json` exists, so `ocx init` still runs + setup). The choice is recorded for the whole computer, so it also covers a silent install run by + an administrator or a deployment tool, and in-app updates keep it (only `send` keeps telemetry on; + `optout` in any letter case, or any other value, turns it off). Each opt-out applies once per + account: running a newer installer and continuing + without changing the box keeps the earlier decision as it was, so it is not applied again over a + choice you made in the dashboard since. If the save fails, a proxy the app starts runs with + `OCX_TELEMETRY=0`, and the app retries in the background and on the next launch. Leaving the box + checked does not start sending by itself, and never turns telemetry back on for an account that + turned it off; the popup below still appears first. A background service from + `ocx service install` can start a proxy at logon without the app, so an opt-out recorded by a + later installer reaches it the next time the app starts; run `ocx telemetry disable` to stop it + at once. +2. **GUI consent popup** — uncheck **Share anonymous daily usage statistics** and click + **Continue** when the first-run or post-update dialog appears. +3. **Proxy details toggle** — open the [Web Dashboard](/guides/web-dashboard/) Overview page, go to + the **Telemetry** section under **Proxy details** (`#proxy-telemetry`), and switch off **Share + anonymous usage statistics**. +4. **CLI command**: + + ```bash + ocx telemetry disable + ``` + + This writes `"decision": "declined"` to `config.json` and, once that decline is durably + persisted, deletes `/telemetry-id.json`. If `mutatePersistedConfig` returns + `unavailable` or throws during `ocx telemetry enable` or `ocx telemetry disable`, the CLI exits + non-zero with an actionable error, prints no success line, and does not delete + `telemetry-id.json` unless the decline persisted. +5. **`OCX_TELEMETRY=0`** — set `OCX_TELEMETRY=0` (or `false`, `off`, `no`, case-insensitive) in the + proxy environment. +6. **`DO_NOT_TRACK=1`** — set `DO_NOT_TRACK=1` (or `true`, `yes`, case-insensitive) in the proxy + environment. + +The two environment variables only reach a proxy that inherits them. A proxy run as a background +service (systemd, launchd or Task Scheduler, through `ocx service install`) does not see variables +exported in your interactive shell; set them in the service's own environment, or use one of the +persistent controls above. `ocx telemetry status` asks the running proxy, so it shows the state that +proxy actually uses. + +Both environment variables override `config.json` immediately without modifying the saved file. +Whenever `OCX_TELEMETRY` or `DO_NOT_TRACK` opt-out is observed — at proxy startup in +`src/server/background-lifecycle.ts` (even though the scheduler timer is not started) and on every +scheduler tick — opencodex also persists `ineligibleThroughDay` set to today's UTC day (`YYYY-MM-DD`) +and an `envOptOutActiveSince` marker in `/telemetry-state.json` via an atomic no-follow +write and deletes `/telemetry-id.json`. A proxy started with the variable reads it +once, so the marker covers every day that proxy keeps running. The opt-out period ends when that +proxy stops cleanly, or, if it crashed, at the first scheduler tick without the variable; either way +`ineligibleThroughDay` moves to that day. If you later remove the environment variable, no day the +opt-out covered is ever sent, including the day it ended, and a fresh install ID is minted on the next +eligible send. While either variable is set, the dashboard toggle is disabled and +names the active variable. + +## How to see the exact payload + +`GET /api/telemetry` and `ocx telemetry status [--json]` build `preview` for the **same completed UTC +day the scheduler would send next** (the oldest eligible unsent UTC day within the 7-day window, with +`previewEligible: true`). When no completed UTC day is currently eligible to be sent (for example +before consent is given, on the UTC day consent was recorded, while disabled, or when all eligible +days have already been sent), the snapshot previews the latest completed UTC day for inspection and +returns `previewEligible: false` so it never implies that day will be sent: + +- **CLI (human-readable + JSON preview)**: + + ```bash + ocx telemetry status + ``` + +- **CLI (machine-readable snapshot)**: + + ```bash + ocx telemetry status --json + ``` + + This queries `GET /api/telemetry` when the proxy is running and falls back to building the same + snapshot locally from `config.json` and `usage.jsonl` when the proxy is stopped. +- **Web dashboard** — click **Preview the JSON** inside the first-run/post-update consent dialog + or beside the **Share anonymous usage statistics** switch in **Proxy details** to view the + **What is sent** / **Never sent** summary and the exact JSON payload. + +Before the first report has been sent — or after telemetry is disabled and `telemetry-id.json` is +removed — no local install ID exists on disk, so `installDayHash` in the preview is shown as 64 +zeros (`0000000000000000000000000000000000000000000000000000000000000000`). + +## What is collected + +Each report covers one completed UTC calendar day (`YYYY-MM-DD`) and is validated by +`validateTelemetryPayloadV1` (`src/telemetry/contract.ts`) before leaving the proxy and again on the +collector. Unknown keys and strings outside the closed vocabularies below are rejected. + +Here is a real example payload produced by `buildTelemetryPayloadV1` (`src/telemetry/payload.ts`): + +```json +{ + "schemaVersion": 1, + "batchId": "c2bf1164-d009-4111-a8a6-902d55f727c7", + "day": "2026-11-06", + "installDayHash": "456b15e3a95d8665bbd9a40ac2cae49986aec3f03b78b6dd601df49abfc406d4", + "newInstall": false, + "env": { + "version": "2.99.0", + "releaseChannel": "latest", + "os": "darwin", + "arch": "arm64", + "installChannel": "npm-global" + }, + "activeMinutes": 312, + "requests": { + "completed": 840, + "failed": 12, + "incomplete": 3, + "aborted": 5 + }, + "models": [ + { + "providerKind": "anthropic", + "modelFamily": "claude-opus", + "requests": 400, + "inputTokens": 184200, + "cacheReadTokens": 6410000, + "cacheWriteTokens": 512000, + "outputTokens": 96400, + "reasoningTokens": 28100 + }, + { + "providerKind": "chatgpt", + "modelFamily": "gpt-6", + "requests": 460, + "inputTokens": 210500, + "cacheReadTokens": 5890000, + "cacheWriteTokens": 0, + "outputTokens": 112300, + "reasoningTokens": 44800 + } + ], + "errors": { + "rate-limit": 7, + "upstream-fault": 5 + } +} +``` + +| Field | Contents | +| --- | --- | +| `schemaVersion` | Fixed integer `1`. | +| `batchId` | Random UUID v4 generated when the payload is built. | +| `day` | Completed UTC calendar date (`YYYY-MM-DD`), within the last 7 completed UTC days. | +| `installDayHash` | `sha256(installId + ":" + day)` as 64 lowercase hex characters. Rotates every UTC day. | +| `newInstall` | `true` only on the first report ever sent for the current local `telemetry-id.json`; `false` afterward. | +| `env.version` | Version matching `^\d+\.\d+\.\d+(-preview\.\d{8}(\.\d+)?)?$` (for example `2.40.1`, `2.6.15-preview.20260701`, `2.6.15-preview.20260701.1`, or `2.7.9-preview.20260712.2`); any `+build` metadata is stripped by the client and rejected by `validateTelemetryPayloadV1`. | +| `env.releaseChannel` | `"latest"` or `"preview"`. | +| `env.os` | `"darwin"`, `"linux"`, `"win32"`, or `"other"`. | +| `env.arch` | `"x64"`, `"arm64"`, or `"other"`. | +| `env.installChannel` | `"npm-global"`, `"pnpm-global"`, `"bun-global"`, `"mise"`, `"standalone"`, `"desktop"`, `"docker"`, `"source"`, or `"unknown"`. | +| `activeMinutes` | Distinct UTC minutes (`0`–`1440`) during `day` in which at least one request was logged in `usage.jsonl`. | +| `requests` | Request counts by closed outcome class: `completed`, `failed`, `incomplete`, and `aborted`. | +| `models` | Up to 64 rows per day, grouped by unique `(providerKind, modelFamily)` pairs from the closed rosters below (if more than 64 pairs occur in a day, the top 63 rows by requests and total tokens are kept and the remaining rows are merged into `"other"` / `"other"`). Multi-attempt `combo` requests attribute each attempt to the underlying provider and model, so `models[].requests` can sum to more than top-level `requests`. Each row reports `requests` and five disjoint token counters — `inputTokens` (uncached input), `cacheReadTokens`, `cacheWriteTokens`, `outputTokens` (non-reasoning output), and `reasoningTokens` — whose sum equals the request's displayed total tokens (`usageDisplayTotalTokens`). | +| `errors` | Counts of non-completed requests keyed by the closed failure-cause roster (`transport-unsent`, `transport-ambiguous`, `upstream-declined`, `rate-limit`, `quota-exhausted`, `credential-rejected`, `policy-refusal`, `parameter-rejected`, `ciphertext-refusal`, `payload-too-large`, `payload-rejected`, `upstream-fault`, `empty-output`, `client-cancelled`, `local-refusal`). | + +Closed `providerKind` values (26): `openai`, `chatgpt`, `anthropic`, `claude-subscription`, `google`, `vertex`, `xai`, `deepseek`, `moonshot`, `qwen`, `zai`, `minimax`, `mistral`, `openrouter`, `groq`, `cerebras`, `together`, `fireworks`, `cursor`, `kiro`, `copilot`, `devin`, `ollama`, `lmstudio`, `local-other`, `other`. + +Closed `modelFamily` values (19): `gpt-6`, `gpt-5`, `gpt-4`, `o-series`, `codex`, `claude-opus`, `claude-sonnet`, `claude-haiku`, `gemini-3`, `gemini-2`, `grok`, `deepseek`, `qwen`, `kimi`, `glm`, `minimax`, `mistral`, `llama`, `other`. + +## What is never collected + +opencodex never includes any of the following in telemetry payloads: + +- Prompts, completions, reasoning traces, tool arguments, or any request or response bodies. +- API keys, OAuth access or refresh tokens, session cookies, or management/data-plane tokens. +- Account IDs, email addresses, organization identifiers, or billing/plan details. +- User-chosen provider names or keys, custom model IDs outside the closed `modelFamily` + buckets above (unknown models map to `"other"`), or custom `baseUrl` and proxy URLs. +- Hostnames, local or upstream IP addresses, MAC addresses, hardware serials, working directories, + or file paths. +- Raw or free-form upstream error messages or stack traces. +- Usage from the UTC calendar day on which consent or disclosure was recorded (`formatUtcDay(decidedAt ?? noticeShownAt)`) or any earlier UTC day — only completed UTC calendar days strictly after the consent/disclosure day (`day > formatUtcDay(decidedAt ?? noticeShownAt)`) are ever sent. +- Usage from any UTC calendar day covered by an `OCX_TELEMETRY=0` or `DO_NOT_TRACK=1` opt-out, including every day a proxy started with it kept running and the day the opt-out ended (`day <= ineligibleThroughDay`, and nothing at all while `envOptOutActiveSince` is set). + +## Public profile and rank (opt-in) + +Separately from the anonymous telemetry above, you can connect a **public profile** to appear on the +[leaderboard](/dashboard/#leaderboard) and see where your own usage ranks over the last day, week and month. It +is off unless you connect it yourself, and it never changes your anonymous telemetry choice; connecting +needs anonymous telemetry to be on, because the profile's totals come from the same local daily aggregate. + +- **Connect** from the *Public profile & rank* card on the dashboard Home, or with + `ocx telemetry profile connect --handle [--name ] [--avatar ]` in an + interactive terminal (the prompt defaults to no). You choose a handle (3–24 lowercase letters, digits or + hyphens), a display name and an avatar colour from a fixed palette. No e-mail address or account is asked + for. The collector returns a secret that the proxy stores in `/telemetry-profile.json` + (mode `0600`); it is never shown, printed or returned by the dashboard API, and the collector keeps only + its SHA-256 hash. Like the telemetry decision, connecting is refused for agents + (`agent_consent_required`), non-interactive terminals (`tty_required`) and remembered dashboard + sessions. +- **What is public**: the handle, display name and colour, your rank, and per day the request count, the + five token buckets and per-model-family request and token totals (the closed `modelFamily` list). + The collector's profile and leaderboard responses carry `x-robots-tag: noindex`; the + [dashboard](/dashboard/#leaderboard) page renders them in the browser and is itself a public page. +- **What is sent**: once per completed UTC day strictly after the day you connected, at most one day per + tick and no more than 7 days back, `POST /v1/profiles/me/days` with exactly those totals. Profile + submissions carry no install ID, install-day hash, batch ID, version, platform, install channel, provider + name or kind, error, prompt, output, key, account or path, and run on their own timer. Nothing is sent + while anonymous telemetry is off (`OCX_TELEMETRY=0`, `DO_NOT_TRACK=1`, declined or awaiting the notice); + the profile stays connected and resumes when telemetry is on again. +- **See it**: `ocx telemetry profile status` shows the profile, a summary of the next day it would send, and + your ranks; `ocx telemetry profile status --json` includes the exact payload as `preview`. The card shows the + profile and ranks. +- **Disconnect** at any time, from the card or with `ocx telemetry profile disconnect` (always allowed, + including for agents, with the proxy stopped and with telemetry off). It deletes the profile and every day + submitted for it on the collector. If the collector cannot be reached, the deletion stays pending, nothing + more is sent, and the proxy retries on every tick and on its next start. Disconnecting and connecting again + is also how to replace the secret. +- **Ranking**: for each period the collector ranks profiles with a positive total using standard + competition ranking (ties share a rank). Totals are self-reported and checked for consistency and daily + limits, each day is accepted once, and the first submission for a day wins. +- **Abuse controls**: reserved handles, display names of 1–32 letters, digits, spaces and `. _ ' -` that cannot + look like a web address, five profile + creations per network per hour, per-profile submission limits, profiles that never submit are removed after + 14 days, and maintainers can hide a profile from every public view. +- **Sign-in with GitHub** is not available yet: it needs a GitHub OAuth app that the maintainers have not + created. + +## Storage, retention, and collector source + +- **Local install ID and daily hash rotation** — when telemetry sends its first report, the proxy + creates `/telemetry-id.json` (mode `0600`) containing a random UUID v4. The raw + UUID never leaves your machine; each report sends only `sha256(installId + ":" + day)`. Because + the UTC date is hashed together with the UUID, an installation's hash changes every day and + cannot be linked across days on the server. Declining telemetry or running with `OCX_TELEMETRY=0` + or `DO_NOT_TRACK=1` deletes `telemetry-id.json` immediately, and re-enabling later generates a new + UUID. +- **Streaming single-day aggregation** — `src/telemetry/aggregate.ts` scans `usage.jsonl` through + `scanUsageLedgerCooperatively` and accumulates counters inside the `onEntry` callback for the + target UTC day only; it never retains ledger rows in memory. +- **Background schedule and no backfill** — an unref'd background timer (`src/telemetry/scheduler.ts`) + runs once after startup (30–60 s jitter) and every 6 hours thereafter (with jitter), completely off + the request path. Each tick carries an `AbortSignal` cancelled on shutdown (`stopProcessLoops`) or + when consent changes (`nudgeTelemetryScheduler`), re-reads `config.json` from disk, and sends at + most **one** completed UTC day per + tick (oldest unsent day first, within the last 7 completed UTC days) to + `https://telemetry.opencodex.me/v1/events` with a 10-second timeout. Only completed UTC calendar + days strictly after the consent/disclosure UTC day (`day > formatUtcDay(decidedAt ?? noticeShownAt)`) + and strictly after `ineligibleThroughDay` (`day > ineligibleThroughDay`) are ever sent. Immediately + before transmission, the scheduler re-reads persisted consent and environment variables and aborts + without sending if telemetry is no longer effective. If the collector returns HTTP `429` or `503`, + the client persists `retryAfterUntil` in `/telemetry-state.json` and skips ticks + until that time: it honors a `Retry-After` header when present and otherwise backs off about 15–20 + minutes. Sent day markers in + `telemetry-state.json` are pruned after 30 days. If the collector is not yet deployed or is + unreachable, the 10-second send attempt fails quietly in the background without affecting proxy + traffic or marking the day as sent. +- **One report per install per day** — the collector deduplicates on `(day, install_day_hash)` in a + single atomic conditional D1 batch across `daily_installs`, `daily_totals`, `daily_models`, and + `daily_errors`. Re-sending the same day for the same `installDayHash` is a no-op and never + double-counts. +- **Salted hourly hash for rate limiting (no raw IP addresses stored)** — the collector never + stores raw client IP addresses. For abuse rate limiting (**120 reports per hour** per key, sized + for shared NAT / CGNAT addresses and returning HTTP `429` with `Retry-After`), ingest hashes a + key derived only from Cloudflare's `cf-connecting-ip` (an IPv4 address as is, an IPv6 address + collapsed to its /64 prefix so one host cannot rotate past the limit; `x-forwarded-for` is + ignored) with a mandatory secret salt and the current UTC hour + (`sha256(RATE_LIMIT_SALT + "\0" + bucketHour + "\0" + key)`) in `rate_limits`, and an hourly + scheduled job (`15 * * * *`) deletes each bucket within about 2 hours 15 minutes of its hour. +- **Install-days, small-cohort protection, and unauthenticated self-reported figures** — because + `installDayHash` rotates every UTC day, `totals.activeInstalls` and the `installs` count in each + breakdown of `GET /v1/stats` measure **install-days** (the sum of daily reporting installs across + the selected range), while `totals.avgDailyActiveInstalls` reports `install-days / days in range` + rounded to 1 decimal place (shown on the dashboard as **Avg daily active installs** with + install-days in the tooltip). Small-cohort protection is applied per day, on distinct installs: + a breakdown row (`providers`, `models`, `versions`, `platforms`, `channels`, `errors`, and each + day of `dailyByProvider`) includes a day's value for a key only when at least **10 distinct + installs** reported that key on that day, before days are summed into the selected range. One + install therefore cannot reach the threshold alone by reporting on many days or through many + providers or model families (`daily_models`, `daily_errors`, `daily_provider_installs` and + `daily_family_installs` count each report once per key). Version, platform and channel rows below + the threshold fold into that day's `"other"`, published only if it reaches 10; provider, model + and error rows below it are dropped. `totals`, `daily`, and `heatmap` stay unfiltered, so a + suppressed value can still be approximated by subtraction from the published totals. In addition, + reports to + `POST /v1/events` are **unauthenticated** and can be forged within the per-key rate limit and + payload bounds. Forged reports can also lift a real install over the threshold: 9 forged reports + for a rare key on the same day as one real install make 10 distinct installs, and the sender can + subtract their own share to recover that install's figures for the key. The install stays + anonymous, and the rate limit raises the cost without preventing it. The public dashboard + therefore labels all figures + **"self-reported by opencodex installs"**. +- **Daily aggregate retention** — `daily_installs` rows (which hold only the per-day hash, version, + release channel, OS, CPU architecture, install channel, `new_install`, and `active_minutes`) are + pruned after 400 days; `daily_totals`, `daily_models`, and `daily_errors` hold only project-wide + daily counters with no per-install rows and are retained indefinitely. +- **Collector-first contract rollout and auditable source code** — the client implementation lives in + [`src/telemetry/`](https://github.com/lidge-jun/opencodex/tree/main/src/telemetry) and the + Cloudflare Worker + D1 collector lives in + [`services/telemetry-collector/`](https://github.com/lidge-jun/opencodex/tree/main/services/telemetry-collector). + Both import the closed rosters in `src/telemetry/contract.ts`, so any roster or wire-contract + addition follows a **collector-first** rollout (deployed to the collector before a client release + emits it). + For the `config.json` schema and environment variables, see + [Server and Runtime Configuration](/reference/configuration/server/#telemetry-telemetry). diff --git a/docs-site/src/content/docs/guides/web-dashboard.md b/docs-site/src/content/docs/guides/web-dashboard.md index 6cdb10f4d2..2344a57ac4 100644 --- a/docs-site/src/content/docs/guides/web-dashboard.md +++ b/docs-site/src/content/docs/guides/web-dashboard.md @@ -13,9 +13,11 @@ settings, and request traffic. ocx gui ``` -This opens `http://localhost:` in your browser — or `http://127.0.0.1:` when hub -management ingress is enabled — auto-starting the proxy first if needed. In -development you can run the GUI dev server separately against a running proxy: +This opens the running proxy's address in your browser: `http://127.0.0.1:` by default, +or `http://[::1]:` for a literal IPv6 loopback bind. These literal addresses preserve the +configured origin required for local browser pairing. With hub management ingress enabled, it opens +`http://127.0.0.1:`. The proxy starts automatically first if needed. In development +you can run the GUI dev server separately against a running proxy: ```bash ocx start @@ -35,6 +37,14 @@ password manager can offer to save and autofill it. The dashboard itself still k in memory and does not write it to `localStorage` or `sessionStorage`; whether it is saved is entirely the browser or password manager's decision. +**Remember this device** is off by default. On a direct HTTPS dashboard (or local loopback), it exchanges the admin token for a server-issued HttpOnly, SameSite=Strict device cookie plus a separate device proof stored in this site's localStorage. HTTPS cookies are Secure and host-only. Neither the cookie nor the proof is the admin token, and neither works alone. Cookies are shared across ports of the same hostname; the origin-scoped proof binds the remembered device to this dashboard origin. Still prefer a dedicated hostname. The admin token is never written to localStorage or sessionStorage. If browser storage is unavailable or cannot save the proof, Remember reports unavailable. On a standalone dashboard behind a TLS-terminating reverse proxy, OpenCodex sees a plain HTTP request, so it refuses Remember for that address; the sign-in dialog says so and turns the option off, and signing in without Remember still works. A trusted Hub management listener is the exception and can still remember devices. + +The private dashboard-sessions.json stores hashes of the cookie, proof, admin credential and browser identity, the server origin and a fixed 30-day expiry. Relaunching the Safari home-screen app resumes a short-lived GUI session while that device record is valid. Remembered sessions cannot approve consent actions: GitHub stars, reset-credit consumption, prompt-layer edits, Meta Muse sign-in, desktop compatibility changes or quota validation. Use a fresh local or paired session for those actions. Cross-origin/relayed dashboards and remote plaintext HTTP do not support Remember. Expiry, a browser identity change, or rotating the admin token and restarting the server requires sign-in again. + +Successful **Forget this device** in the sidebar or mobile action bar (and session logout) immediately revokes the record and all sessions resumed from it, and removes the browser proof. Failed logout keeps the proof so you can retry. The server syncs the record contents before publishing the change; directory-entry durability after a crash is best effort. Older remembered bearer-token keys are removed without being read or migrated. Use only on a device you trust. This does not make Safari offer password AutoFill. + +An already-issued session that is otherwise valid can still **Forget this device** after a browser User-Agent change; ordinary access and resumption continue to require the original browser identity. + ### Finding the admin token You only need this on a non-loopback bind. A local dashboard never asks, and if a local one @@ -69,6 +79,23 @@ missing credential — the proxy did not recognise the request as loopback. Open the address the proxy prints on startup (usually `http://127.0.0.1:`), and prefer that exact host and port over a LAN IP or an alias. +## Classic dashboard + +The dashboard was redesigned: its sidebar now groups pages into **Everyday**, **Set up** and +**Fine-tuning**, and it opens on a Home page. The previous design stays available as the +**classic dashboard** at `/classic/` on the same proxy, for example `http://127.0.0.1:10100/classic/`. + +- To switch, select the clock icon (**Classic dashboard**) beside the theme switch at the foot of + the sidebar. The classic sidebar has **New dashboard** at the top of its foot to come back. +- The choice is remembered per browser, so opening `/` later lands on the dashboard you picked. + The desktop app follows the same choice. The tray popover always uses the new design. +- The classic dashboard is a snapshot of the previous design. It talks to the same proxy and + changes the same settings, but pages and settings added after the redesign appear only in the + new dashboard. + +The sidebar rows described under [Dashboard layout](#dashboard-layout) are the classic +dashboard's. + ## Dashboard layout The sidebar has eight rows, in order: **Dashboard**, **Connect**, **Codex**, **Providers**, **Models**, **Subagents**, **Usage & Logs**, and **Remote Link**. **Connect** opens the page headed **Connect**, with its tab strip ordered **Codex**, **Claude**, **Claude Desktop**, **Grok Build**, then the remaining integrations. Claude has no sub-tabs; it shows the Claude Code settings directly. Claude Desktop is a separate Connect tab at `#claude/desktop`. Connect has no section switcher. **Subagents** opens Subagents and groups Subagents and Advisor (`#advisor`) with a pill-shaped section switcher. **Usage & Logs** opens Usage and groups Usage, Logs & Debug, and Storage with a pill-shaped section switcher. The last row, **Remote Link**, groups Remote Link (`#remote`) and Remote Workspace (`#remote-workspace`, when available) with the same switcher. **Codex** is the renamed **Codex Set** row; the preserved URLs include `#codex-set`, `#claude`, `#claude/code`, and `#claude/desktop`; the former `#claude/settings` bookmark opens Code. The former `#claude/account` bookmark redirects to `#providers?provider=anthropic&tab=accounts`. Startup (`#startup`) stays outside the sidebar. @@ -92,6 +119,8 @@ is visible) and never forces an upstream refresh. - Each chip shows the preferred reported window: weekly first, then monthly, then 5-hour, then a provider-named window or prepaid credits. +- Critical prepaid credits (90% or more used) take the headline when the preferred regular window + is not critical. If that window is also critical, it remains the headline. - A chip turns amber at 70% used and red at 90% used. - Hover or keyboard-focus a chip to see every reported window with its reset time and the time the reading was taken. The details stay open as the pointer moves from the chip into the popover, @@ -114,14 +143,15 @@ is visible) and never forces an upstream refresh. | **Native reasoning retention** | Independently opt into reasoning ciphertext forwarding on native model or account changes. Both default off; account retention is experimental. See [the configuration scope](/reference/configuration/server/#native-reasoning-retention). | | **Sub-agent delegation** | Choose a native or routed model and optional reasoning effort shared by OpenCodex delegation guidance and the separate native-default opt-in. This is not a proxy-side per-spawn router; see below. | | **Sidecars** | Choose the web-search model and effort plus the vision-description model. Changes apply on the next request. | -| **Maintenance** | Resync the Codex model catalog, inspect project-local config bypass warnings, check the latest or preview release, and run an update with optional proxy restart. In the desktop shell, its update entry opens the native app update page instead of running the package updater. | +| **Maintenance** | Resync the Codex model catalog, inspect project-local config bypass warnings, check the latest or preview release, and run an update with optional proxy restart. With restart on, Codex routing and its model catalog stay in place while the package is replaced, so a Codex app that loads them during the update still sees your routed models; the restarted proxy takes them over, and `ocx stop` restores native Codex if it never comes back. In the desktop shell, its update entry opens the native app update page instead of running the package updater. | | **Startup safety** | Show whether injected Codex routing survives a restart, with separate service and launcher-shim health plus exact repair commands. | | **Windows tray** | Install a per-user login tray for one-click proxy start, stop, restart, dashboard access, and status. The tray is a controller, not a proxy restart service. | | **Codex autostart** | Allow an already-installed Codex launcher shim to run `ocx ensure`. This toggle does not install a shim or background service. | -| **Providers** | Add, edit, set the default (enabled providers only), enable/disable, and remove providers; manage OAuth account pools and API-key pools where supported. Removing the current default switches to the first remaining enabled provider when one exists; otherwise deletion is refused and the current default is kept. Provider Settings can disable live model discovery for endpoints with missing, slow, or oversized `/models` catalogs. For Claude (Anthropic) OAuth pools, each logged-in account shows its own 5-hour and weekly rate-limit bars (usage is per credential); a failed probe keeps the last-known bars and marks them unavailable until the next successful refresh. The Provider Overview shown when no provider is selected carries a **Refresh all quotas** control that forces one server-side re-read of every configured provider; a provider whose upstream probe fails keeps its last-good row, so the status line reports that the check completed rather than claiming every value is fresh, and each row's own age stays the per-provider freshness signal. | +| **Telemetry** | Toggle **Share anonymous usage statistics** and inspect **Preview the JSON** under **Proxy details** (`#proxy-telemetry`). On first run or after an update while undecided, the consent popup saves a choice only when **Continue** is clicked (`PUT /api/telemetry`); dismissing it records nothing. See [Telemetry and Privacy](/guides/telemetry/). | +| **Providers** | Add, edit, set the default (enabled providers only), enable/disable, and remove providers; manage OAuth account pools and API-key pools where supported. Removing the current default switches to the first remaining enabled provider when one exists; otherwise deletion is refused and the current default is kept. Provider Settings can disable live model discovery for endpoints with missing, slow, or oversized `/models` catalogs. For Claude (Anthropic) OAuth pools, each logged-in account shows its own 5-hour and weekly rate-limit bars (usage is per credential); a failed probe keeps the last-known bars and marks them unavailable until the next successful refresh. Refreshing quota skips paused OAuth accounts and disabled API keys; skipped rows without a cached reading remain unavailable but do not affect the refresh result. Refreshing reports failure when an unpaused OAuth account or enabled API key that supports quota reads has an unavailable reading. The Provider Overview shown when no provider is selected carries a **Refresh all quotas** control that forces one server-side re-read of every configured provider; a provider whose upstream probe fails keeps its last-good row, so the status line reports that the check completed rather than claiming every value is fresh, and each row's own age stays the per-provider freshness signal. Unsaved Settings and JSON edits are kept in memory per logical dashboard server: switching servers parks the draft, saving writes only to the server where editing began, and a changed saved configuration asks you to keep your draft or use the saved values. Keeping a JSON draft merges only your changes into the latest config and names any field changed on both sides; Settings saves only the fields you changed. On a relay that predates target-bound saves, the dashboard checks the target immediately before sending but cannot verify it atomically, and says so once; update the proxy for the stronger guarantee. Closing or reloading the dashboard discards these drafts. | | **Add provider** | One search above the tabs reaches all four at once — Accounts, Free, Local, Paid. While a query is live the results are grouped by tab with a count each, and the selected tab stays put rather than jumping. Press ArrowDown in the search box to focus the first available result action, skipping disabled buttons; if no action is available, focus stays in the search box. Local runtimes (Ollama, vLLM, LM Studio, LiteLLM) have their own tab, and a long provider note clamps to two lines with the full text one click away. Claude Code CLI (subscription) sits under Paid with a Subscription CLI badge, and selecting it warns that it bills the signed-in Claude subscription through `claude -p` and never uses an API key (use `anthropic-apikey` for key billing). | | **Codex Auth** | Add ChatGPT/Codex pool accounts, select the next-session account, refresh 5h / weekly / 30d quotas, enable or disable quota auto-switch, set its 1–100% threshold, and configure transient-failure failover. | -| **Subagents** | Feature up to five bare native or namespaced routed models in the `spawn_agent` override list. | +| **Subagents** | Feature up to five bare native or namespaced routed models in the `spawn_agent` override list. The **Workflow limits for subagents** panel sets how many turns one task may run in parallel and how many model requests and distinct subagents it may use per 10-minute window. See [workflow limits](/reference/configuration/server/#workflow-limits). | | **Models** | Toggle native GPT and routed models, set provider allowlists and context caps, choose v1/base/v2, and configure the v2 thread limit. The page distinguishes a catalog saved on the hub, a catalog fetched by this client, and activation in a running client. A fetch timestamp does not prove it includes the latest hub save, and runtime activation is shown as unverified. Configured providers stay visible as zero-model groups when discovery is off or returns no rows. | | **Logs** | Auto-refresh recent requests with tokens, requested effort and (when available) effective outbound effort, resolved model, provider, status, request id, duration, and error details. The detail view includes the exact reasoning wire field when the adapter emits one. Filter by opaque conversation/session id (when the client sends one) to total tokens and estimated list-price cost for the currently loaded Logs ring. | | **Usage / Debug** | Inspect token-usage coverage and trends. The Usage page's Models table also breaks each model down into input tokens, output tokens, cache hits, cache writes, and cache hit rate; a dash means cache telemetry for that metric is unavailable. Or enable opt-in provider transport and usage-extraction diagnostics. | @@ -135,6 +165,10 @@ to save an incomplete snapshot; choose another order or repair the history befor ### Account selection +For a provider's OAuth accounts, finish the current sign-in or account removal before starting +the other operation. If the account list and sign-in status cannot be refreshed, the status remains +unverified and **Log out** is available to explicitly retry recovery. + Account selection is shared with request routing. Selecting an OAuth account takes effect on the next request even when a pool is enabled. A healthy selection is not replaced merely because another generic OAuth account has more unused quota. If the account returns 429, automatic @@ -142,8 +176,24 @@ failover can still select another usable account with the pool off. A committed selection updates the dashboard immediately; account changes do not wait for the quota refresh timer. Requests already sent upstream retain their original credentials. +### Usage by app + +Usage opens with **All apps**, **All devices**, and **30d** selected within +the current access scope. You can narrow the app, device, or time range while the page is +open; reopening it restores these defaults. + +With **All apps** selected, **Apps** appears after Models and Providers. It shows each app's +share of total tokens, token count, estimated API list-price cost, request count, and measured +request count for the selected devices and time range. Codex CLI, desktop, and IDE usage is +grouped under Codex. Historical records without client attribution appear as **Unclassified**, +separately from **Unknown** and **Other**. Selecting one app hides this breakdown. A proxy +that does not supply the breakdown shows it as unavailable; an empty breakdown means no app +usage in the report. + ### Filtering request logs +Request details prefer a recognized upstream failure cause over generic proxy-error copy. Physical sends are always shown when valid; missing or invalid accounting shows **Unavailable**, not zero. **Retries** counts sends after the first only when one fully settled, consistent attempt is recorded. Multi-attempt, unresolved, inconsistent, or lossy-normalized records omit retries instead of inventing them. Unknown persisted causes use the status-based headline without raw attribution. **Upstream reason** shows a classified provider condition (for example rate limited, quota or credits exhausted, context window exceeded, location not supported, account verification required, or model unavailable), and **Failure detail** shows text written by the proxy, such as a stall timeout or byte-cap limit. When the provider names a published error class or finish reason (for example Gemini or Vertex `INVALID_ARGUMENT`, or `MALFORMED_FUNCTION_CALL`), Failure detail also shows that token; new rows do not store the provider's own error text. Older `usage.jsonl` files may still contain it, but the dashboard drops it when reading them. + A proxy replay refusal keeps HTTP 429 and error code `upstream_reset_replay_refused`, but its request and attempt failure cause is `transport-ambiguous`, with resend permission `refused-ambiguous`: the upstream may already have processed the turn. A genuine provider @@ -152,7 +202,13 @@ its request and attempt failure cause is `transport-ambiguous`, with resend perm A Codex move to another account after HTTP 402 appears as **Account quota exhausted (402)** in the attempt's recovery details and counts as a quota recovery in exported metrics. -Logs filters combine surface, intercepted requests, provider, exact model, status, time, +Logs shows all apps together, with an icon-only client chip on each request instead of +app tabs. Recognized clients use their SVG logos; unknown or other clients use a neutral +question-mark icon. App names remain available to screen readers without visible text. +Missing client attribution does not imply Codex or a request failure. The chip identifies +the client app, independently of the provider and protocol, and is not an app filter. + +Logs filters combine intercepted requests, provider, exact model, status, time, speed, and conversation ID over the currently loaded request ring. Provider and model choices also include fallback attempts; model matching ignores case and surrounding spaces but does not match partial names. Choices that disappear from the ring reset to All. @@ -184,9 +240,8 @@ Historical logs are not rewritten and missing generation timestamps are not inve tok/s column and speed filter above are not affected. Active filters show the matching count out of the loaded total. Reset filters restores all -rows and returns keyboard focus to the All surface control; “No matching requests” -differs from an empty log ring. Use arrow keys or Home/End in -the surface selector. These controls do not query historical records beyond the loaded ring. +rows; “No matching requests” differs from an empty log ring. These controls do not query +historical records beyond the loaded ring. The language picker includes **Português** (Brazilian Portuguese, `pt-BR`). Portuguese browser languages select it automatically unless a supported language preference is already saved. @@ -289,6 +344,14 @@ they have been synchronized. See In **Connect → API Keys**, every row of the key table has its own delete button, which asks for confirmation in place. Clicking a key can show its full value with a **Copy** button only from an independently authorized session. +### Applying a Codex CLI update over HTTP + +The CLI-update HTTP API has no dashboard job UI. Its apply route requires a current explicitly paired browser session on trusted loopback ingress, matching Origin and CSRF headers, and `confirmed: true`. Automatic local sign-in, a remembered admin session, an admin token or Tailscale sign-in alone cannot authorize this action. + +For standalone local pairing, open the dashboard at its configured literal `http://127.0.0.1:` or `http://[::1]:` origin. Use the existing local pairing form in **Connect → API Keys** or Remote Link setup: run the displayed `ocx gui pair --origin ""` command locally, then redeem its one-time code in that form. Pairing does not apply an update; a subsequent confirmed API request is still required. A server configured with hostname `localhost`, a wildcard bind, or a connected-client role cannot issue this local pairing authority. Remote pairing does not remove the apply route's trusted-loopback requirement. + +Without an eligible HTTP pairing path, use `ocx system codex-cli-update plan` followed by `ocx system codex-cli-update apply --plan-id <32-hex> --yes` locally. This uses the same durable job owner without a GUI session. Pairing proves authority to write the protected configuration home, not human identity or protection from unrestricted same-user processes. + ### Reading an existing API key Showing a stored key's full value requires a dashboard session established by explicit pairing or @@ -451,6 +514,8 @@ The GUI is a thin client over the proxy's JSON management API. Useful endpoints | `GET` / `PUT /api/subagent-models` | Read or set the five featured `spawn_agent` override models. | | `POST /api/stop` | Stop the proxy/service, restore native Codex, and exit. Refused with `respawnable_service` on the Windows Task Scheduler backend, with `self_unload_service` when this proxy is itself the installed launchd/systemd job, and with `service_state_unknown` when the Task Scheduler state cannot be read; nothing is changed in any of those cases. A dashboard session is also refused, with `desktop_supervised`, while the OpenCodex desktop app runs the proxy. | +Stop rechecks connection ownership before restoring configuration. A new hub connection keeps its routing, catalog and Grok configuration. If ownership is still changing or cannot be confirmed, the API returns HTTP 409 with `sharedTeardown: "refused"` and keeps serving; finish the connection operation and retry. See the [Remote Link stop workflow](/guides/remote-link/). + :::tip Adding **Ollama Cloud** or another catalog provider from the dashboard copies its text-versus-vision classification into the saved provider config, so the [vision sidecar](/guides/sidecars/) @@ -475,10 +540,12 @@ Usage heatmap days have one Tab entry point. Use Up/Down for adjacent days and L shows **No changes** or **Unsaved changes**, with **Revert** to discard edits and **Save** to commit them. Both switches apply immediately; **Save** never changes them. When interception is stopped, the page shows why and offers **Start interception**, which starts it in place without restarting OpenCodex. The former Code, Settings, and Account sub-tabs are gone; everything the read-only Settings view showed except the intercept port number is on this page. -**Claude Desktop** is its own Connect tab at `#claude/desktop`. It contains the Desktop mode picker and model families. One status row shows whether Claude Desktop runs the profile and whether it is saved, with **Save** and **Save & apply** beside it. +**Claude Desktop** is its own Connect tab at `#claude/desktop`. It contains the Desktop mode picker, a per-model list of what Claude Desktop shows (see [Choose which models Claude Desktop lists](/guides/claude-code/#choose-which-models-claude-desktop-lists)), and model families under **Advanced**. One status row shows whether Claude Desktop runs the profile, with a separate chip for whether dashboard edits are saved, and **Save** and **Save & apply** beside it. Claude/Anthropic accounts are managed only on **Providers > Anthropic > Accounts**: login and the browser option, the account roster with switch, pause, remove, and reauthentication, the paste-code field, account pool settings, and quota. Claude no longer has an Account sub-tab. Provider-level controls such as the default provider, removal, and the enabled switch stay on Providers. +If an account change is still in progress, wait for it to finish before retrying logout. After an account removal, the dashboard rechecks the provider's login status; if it cannot verify the result, refresh the account list before retrying the removal. + The bookmarks `#claude` and `#claude/code` open this page, and the former `#claude/settings` redirects to `#claude/code`; `#claude/desktop` selects the separate Claude Desktop tab. The old `#claude/account` bookmark redirects to `#providers?provider=anthropic&tab=accounts`. Legacy `#integrations/claude` and `#integrations/claude/desktop` bookmarks still redirect to `#claude/code` and `#claude/desktop`, respectively. Arrow keys move between tabs; Home and End select the first and last tab. @@ -507,3 +574,23 @@ test for the same provider returns 409. Completed diagnostics and applicability results return 200, including a structured error when inference fails. Destination policy and provider egress settings apply; redirects, retries and failover are disabled. For the CLI workflow, see [Providers and accounts](/reference/cli/providers-accounts/). + +**Test all models** runs the same completion test for every configured, listed and +default model of the provider, one request at a time, after a single confirmation that +states the maximum number of requests; some models can be skipped before sending. The +single-model **Test model** control and **Test all models** share one guard per provider, so +each stays disabled while the other is confirming or running. **Stop** cancels the in-flight request and sends no +more. Each model is reported as passed, failed (the upstream answered with an error or +timed out) or not tested. The latter covers management API refusals such as a concurrent +test, admission refusals before sending (missing or changed credentials or a refused +destination), and upstream HTTP 401/403/429 authentication, access or quota refusals +returned in a structured result with HTTP 200. None of these categories becomes a disable target. An unsupported +effective adapter marks only that model as not tested and continues, because one provider +can use different wires for different models. Provider-wide applicability refusals, such as +OAuth authentication or unsupported transport settings, stop the run. When any model failed, **Disable failed models** asks a second +confirmation and then removes only those models from the model catalog and picker through the +same visibility setting as the **Models** page, where they can be re-enabled. Like any hidden +model, they stay callable by exact id. Models are never disabled +without that confirmation. Leaving the page or changing the provider connection withdraws +pending disable consent and aborts its request. A new batch waits until disable consent or +the visibility write has settled, so an older response cannot hide the newer batch's action. diff --git a/docs-site/src/content/docs/index.mdx b/docs-site/src/content/docs/index.mdx index 985cbde406..fcdddab345 100644 --- a/docs-site/src/content/docs/index.mdx +++ b/docs-site/src/content/docs/index.mdx @@ -1,12 +1,12 @@ --- -title: "opencodex — Run Codex on any LLM" -description: Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI, App, SDK, and Claude Code. +title: "opencodex — One local gateway for Codex, Claude Code and more" +description: "One local gateway for your AI coding tools and models: use the providers you choose with Codex, Claude Code, Claude Desktop and Grok Build, and connect more tools through managed configs." template: splash head: # Brand-first, no " | opencodex" suffix: Google matches the site name against # the home page title, so the wordmark leads and is not duplicated. - tag: title - content: "opencodex — Run Codex on any LLM" + content: "opencodex — One local gateway for Codex, Claude Code and more" - tag: meta attrs: property: og:locale diff --git a/docs-site/src/content/docs/ja/contributing.md b/docs-site/src/content/docs/ja/contributing.md index 9ad672176e..52f91416fa 100644 --- a/docs-site/src/content/docs/ja/contributing.md +++ b/docs-site/src/content/docs/ja/contributing.md @@ -12,7 +12,7 @@ bun install bun run setup:hooks # 旧管理対象 pre-push・post-merge の削除 bun run dev:proxy # 開発モードのプロキシ API bun run dev:gui # ダッシュボード dev サーバー(別ターミナル) -bun run typecheck # bun x tsc --noEmit +bun run typecheck # bun check --no-script --noEmit bun run test # 全テストスイート(既定) ``` @@ -57,59 +57,10 @@ CI だけに任せたり、ローカルテストを一律に省略したりす cd docs-site && bun install && bun dev ``` -## ドキュメントのデプロイ +## CI / Release / Pages -公開ドキュメントは GitHub Pages の に公開されます。 -`.github/workflows/deploy-docs.yml` は `main` push で `docs-site/**` またはワークフロー自体が変わると -実行されます。`docs-site` をビルドした後、生成されたサイトをデプロイします。ドキュメント変更を push する前に以下を -実行してください。 +公開、CI、リリース、ブランチについては[英語の正本](/contributing/)を参照してください。 -```bash -cd docs-site -bun install --frozen-lockfile -bun run build -``` - -## CI とリリース - -GitHub Actions は必要な作業のみを行います。 - -- **Cross-platform CI**(`.github/workflows/ci.yml`)はランタイム、テスト、パッケージ、スクリプト、 - TypeScript、ワークフローファイルが変更された pull request と `main` push で実行されます。Bun matrix は Linux、 - Windows、macOS で install、typecheck、tests、privacy scan、release helper build smoke、GUI build、 - `ocx help` を検査します。別途 3 OS レーンはバンドルランタイムを使い、Bun を別途インストールしなくても - npm global install が動作するか確認します。 -- **Release**(`.github/workflows/release.yml`)は手動で実行します。2 つ目の完全 CI パイプラインではなく、 - dry-run や publish 前に正確なリリースコミット(`GITHUB_SHA`)で Cross-platform CI が - 成功したか確認します。 - -リリースには helper を使ってください。 - - -helper の実行前にリリース予定のバージョンを決め、デフォルトブランチから -`.github/workflows/dev-version-bump.yml` を `intended-version=`、 -`mode=pre-move` で実行してください。生成された PR をレビューして `dev` にマージし、 -`main` または `preview` に昇格してから helper を実行します。`dev` がすでに予定の -バージョンより新しい場合は `changed=false` となり、バージョン更新 PR は不要です。 -公開には正確なリリースコミットの CI 成功が引き続き必要です。 - -```bash -bun run release # バージョン bump を commit/push、publish ワークフローはデフォルト dry-run -bun run release --bump minor # tag と npm channel から次の patch、minor、major バージョンを導出 -bun run release --publish # CI-gated dry-run を確認した後、実際の publish -bun run release:watch # 直近の Release ワークフロー run を監視 -``` - -明示的なバージョンの代わりに `--bump patch|minor|major` を指定できます。上位 core の preview tag が -作られた後は、`--bump patch` は古い stable patch ラインの継続を拒否します。その修正は開いている -preview core に含めてください。 - -## ブランチ - -- `dev` — 唯一の統合先。すべての PR をここに出します。 -- `main` — リリース専用。`dev` からメンテナーが昇格させるときだけ動きます。機能 PR を直接 - 出さないでください。 -- `preview` — プレリリーストレイン。 Go ネイティブポートを担っていた `dev2-go` は廃止し、2 本の統合ラインを維持する方針も 終了しました。履歴は @@ -122,7 +73,7 @@ Go ネイティブポートを担っていた `dev2-go` は廃止し、2 本の ## 規約 -- **ES Modules のみ**(`import`/`export`)、TypeScript、`strict` モード。`bun x tsc --noEmit` をクリーンに +- **ES Modules のみ**(`import`/`export`)、TypeScript、`strict` モード。`bun run typecheck` をクリーンに 保ってください。 - **ファイルあたり最大約 500 行** — 責任ごとに分割してください。単一の `index.ts` の後に小さく集中したモジュールを置いた `web-search/` と `vision/` サイドカーが良い例です。 diff --git a/docs-site/src/content/docs/ja/getting-started/for-agents.md b/docs-site/src/content/docs/ja/getting-started/for-agents.md index 9eb2aa2957..db3261538f 100644 --- a/docs-site/src/content/docs/ja/getting-started/for-agents.md +++ b/docs-site/src/content/docs/ja/getting-started/for-agents.md @@ -10,7 +10,7 @@ description: ユーザー同意の境界を越えずに、エージェント主 公開されたパッケージをインストールし、`ocx` が `PATH` 上にあることを確認します。 ```bash -npm install -g @bitkyc08/opencodex +npm install -g --allow-scripts=bun @bitkyc08/opencodex ocx --version ``` diff --git a/docs-site/src/content/docs/ja/getting-started/installation.md b/docs-site/src/content/docs/ja/getting-started/installation.md index 49b50f7d37..3ac4677d74 100644 --- a/docs-site/src/content/docs/ja/getting-started/installation.md +++ b/docs-site/src/content/docs/ja/getting-started/installation.md @@ -18,7 +18,7 @@ opencodex をインストールすると同じ実行ファイルを指す `ocx` ## インストール ```bash -npm install -g @bitkyc08/opencodex +npm install -g --allow-scripts=bun @bitkyc08/opencodex ``` :::note[npm が bun の postinstall をブロックした?] @@ -63,7 +63,7 @@ GPT-5.6 Sol/Terra/Luna カタログ情報がすでに含まれています。た ありません。まだ正式配布されていない opencodex ビルドを試す場合のみ preview チャネルを使ってください: ```bash -npm install -g @bitkyc08/opencodex@preview +npm install -g --allow-scripts=bun @bitkyc08/opencodex@preview ocx update --tag preview ``` diff --git a/docs-site/src/content/docs/ja/getting-started/quickstart.md b/docs-site/src/content/docs/ja/getting-started/quickstart.md index 2294fc1d54..cfd4f95bca 100644 --- a/docs-site/src/content/docs/ja/getting-started/quickstart.md +++ b/docs-site/src/content/docs/ja/getting-started/quickstart.md @@ -1,9 +1,9 @@ --- title: クイックスタート -description: 最初のプロバイダーを構成し、3 つのコマンドで OpenAI Codex を opencodex 経由でルーティングします。 +description: "opencodex をインストールして最初のプロバイダーを追加し、Codex、Claude Code、Claude Desktop、Grok Build など、普段使う対応コーディングツールを接続します。" --- -このガイドでは、新規インストールから非 OpenAI モデルに対して Codex を実行するまでを説明します。 +このガイドでは、新規インストールから普段使うコーディングツールで最初のリクエストを送るまでを説明します。手順 1 と 2 は全ツール共通で、手順 3 はツール別です。[クライアント対応ページ](/ja/reference/client-support/)に各ツールと接続方法を記載しています。 ## スタンドアロンバイナリ(npm 不要) @@ -18,7 +18,7 @@ ocx init `ocx init` では次の手順を説明します。 -1. **プロバイダーを選択してください** — 104 個の組み込みレジストリプリセットのいずれか、または `custom` を選択してベース URL とアダプターを入力します。 +1. **プロバイダーを選択してください** — 107 個の組み込みレジストリプリセットのいずれか、または `custom` を選択してベース URL とアダプターを入力します。 2. **API キー** — キーを貼り付けるか、`${ANTHROPIC_API_KEY}` のような環境変数を参照します。 3. **デフォルト モデル** — キー、ローカル、カスタム プロバイダーの場合は、プリセットを受け入れるか、モデル ID を入力します。 4. **プロキシ ポート** — デフォルトは `10100` です。 @@ -55,9 +55,13 @@ ocx status ocx gui # open the dashboard on the live port ``` -## 3.Codexを使用する +## 3. ツールを接続する -Codex は透過的に opencodex と通信するようになりました。 +使用するツールの手順を選んでください。複数のツールを接続でき、プロバイダーとモデルを共有します。 + +### Codex + +手順 1 で Codex の確認に同意した場合、Codex は透過的に opencodex と通信します。確認を拒否した場合、または既存の設定があるためにセットアップが終了した場合は、Codex を実行する前にダッシュボードの **Connect** ページにある Codex スイッチをオンにします。[Codex 統合](/ja/guides/codex-integration/)では変更内容と復元方法を説明しています。 ```bash codex "Refactor this function for readability" @@ -70,6 +74,42 @@ codex -m "anthropic/claude-opus-5" "Explain this stack trace" codex -m "ollama-cloud/glm-5.2" "Write a SQL migration" ``` +### Claude Code + +`claude` CLI をインストールした状態で実行します。 + +```bash +ocx claude +``` + +`ocx claude` はプロキシが停止中なら起動し、opencodex を指す環境で Claude Code を起動します。追加の引数はそのまま渡されます。階層のデフォルト、他のランチャー、無効化の方法は [Claude Code](/ja/guides/claude-code/)を参照してください。 + +### Claude Desktop + +```bash +ocx claude desktop +``` + +新規インストールではアプリ全体にゲートウェイプロファイルを設定します。すでに first-party モードを使用している場合はそのまま維持され、`ocx claude desktop apply --gateway` を実行すると明示的に切り替えられます。Desktop を claude.ai のままにして Code タブのみをルーティングする first-party モードは、[Claude Code](/ja/guides/claude-code/)の Claude Desktop モードの節を参照してください。 + +モードを切り替えた後は、Claude Desktop を完全に終了してから開き直してください。 + +### Grok Build + +ローカルリスナーでは、`~/.grok` が存在すると `ocx start` が表示対象のモデルを `~/.grok/config.toml` に登録します。Grok Build で `ocx-*` モデルを選択します。リモート設定と管理対象ブロックは [Grok Build](/ja/guides/grok-build/)を参照してください。 + +プロバイダーやモデルを追加した後は、`ocx ensure` を実行するかプロキシを再起動すると Grok Build に反映されます。 + +### その他のツール + +管理対象の統合があるツール(OpenCode、Pi、Qoder、WorkBuddy、Kilo、Cline、T3 Code など)は、ダッシュボードの **Connect** ページまたは次のコマンドで接続します。 + +```bash +ocx integration client enable --client +``` + +各ツールの設定ファイルと変更の反映時期は[統合](/ja/guides/integrations/)を参照してください。カスタムエンドポイントに対応するその他のツールでは、OpenAI 互換ベース URL `http://localhost:10100/v1` または Anthropic ベース URL `http://localhost:10100` を使えます。 + ## サブエージェント モデルの選択 (オプション) 新しい設定には、Codex のサブエージェント ピッカーの 5 つのネイティブ モデル、`gpt-5.5`、`gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-5.6-luna`、および `gpt-6-astra` が含まれています。 `ocx gui` を開いて、最大 5 つのネイティブ モデルまたはルーティング モデルを置換または並べ替えます。ダッシュボードでは、優先サブエージェント モデルと推論負荷を 1 つ設定することもできます。 v1/base/v2 を選択し、ガイダンス、ネイティブのデフォルト、およびフォールバックがいつ適用されるかを理解するには、[サブエージェントサーフェス](/guides/sub-agent-surface/) を参照してください。 diff --git a/docs-site/src/content/docs/ja/guides/claude-code.md b/docs-site/src/content/docs/ja/guides/claude-code.md index 8476e7eb93..5018932a5e 100644 --- a/docs-site/src/content/docs/ja/guides/claude-code.md +++ b/docs-site/src/content/docs/ja/guides/claude-code.md @@ -53,7 +53,7 @@ ocx claude | `ANTHROPIC_DEFAULT_{OPUS,SONNET,FABLE}_MODEL` | `claudeCode.tierModels.*`(サブスクリプション起動で未設定の場合はネイティブの `claude-opus-5-5[1m]` / `claude-sonnet-5-5[1m]` / `claude-fable-5-1[1m]`) | | `ANTHROPIC_DEFAULT_{OPUS,SONNET,FABLE,HAIKU}_MODEL_NAME` | OpenCodex がルーティングエイリアスを設定した Tier スロットの `/model` ラベル(例: `ocx-claude-native--gpt-6.1-sol` → `gpt-6.1-sol (native)`)。launchd のシステム環境とシェルフックにも同じ組で書き込みます。モデル ID はエイリアスのままです。自分で設定したスロットやラベルは変更しません | | `CLAUDE_CODE_ALWAYS_ENABLE_EFFORT` | `alwaysEnableEffort` がオンなら `1` (条件付き) | -| `ENABLE_TOOL_SEARCH` | `claudeCode.toolSearch` が設定されている場合 (条件付き、既定はオフ) | +| `ENABLE_TOOL_SEARCH` | `claudeCode.toolSearch` が設定されている場合 (条件付き、既定では注入せず Claude Code 自身の既定値に従う) | | `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | `maxContextTokens` が設定された場合の従来コンテキスト上書き値 (条件付き) | 直接 export した変数が常に優先します。追加引数はそのまま渡されます: `ocx claude -p "hello"`。 @@ -192,6 +192,8 @@ Picker プロファイルを選択した後は、Claude Desktop を完全に終 Picker モードは 1P の一部なので、[1P のアカウントリスク](#1pオプトイン)も同じように適用されます。 +上流サーバーの最初の応答前に、60 秒間転送が進まない Picker アップロードは終了します。タイムアウトしたアップロードに成功応答は返しません。HTTP/2 では対象のストリームだけをリセットします。上流のバックプレッシャーで転送が一時停止している間は、このタイマーも停止します。アップロード完了時または上流の最初の応答時にタイマーを解除します。このアイドル監視はアップロード全体の所要時間に追加の上限を設けません。既存のランタイムやプロトコルの制限は引き続き適用されます。応答ストリームはこのタイマーの対象外です。 + ### Code タブで opencodex モデルを使う(1P バインディング) 1P モードでは、Code タブのモデルピッカーは claude.ai が提供します。各行(Opus 5.5、Sonnet 5、 @@ -360,9 +362,7 @@ Claude Code は未知モデルのコンテキストを 200k トークンとし **接続 → Claude** で圧縮値を調整できます。**警告:** モデルの実際のコンテキストウィンドウより大きく上げると 要約を開始する前にチャットエラーが発生します。 -コンテキスト超過エラーの正規化では、プロバイダーのエラーメッセージの先頭 65,536 UTF-16 コード単位だけを使います。 -末尾の診断情報やトークン数は、省略を示す印なしで失われることがあります。 -詳しい制限とトークン数の扱いは[英語ガイド](/guides/claude-code/#auto-context-big-context-models-without-the-200k-ceiling)を参照してください。 +Messages のエラー応答の正規化では、プロバイダーの文章やトークン数ではなく固定文を使います。認識したコンテキスト超過は `prompt is too long: The request exceeds the model's context window.` として返します。最初のフィールドが error イベントのストリームブロックは 1 MiB まで保持し、超過時は圧縮を促さない固定エラーにします。対象範囲と二つの例外は[英語ガイド](/guides/claude-code/#auto-context-big-context-models-without-the-200k-ceiling)を参照してください。 1M 未満のネイティブ Anthropic モデルには自動で標識を付けません。自分で export した圧縮値は起動スロットの標識に優先し、プロキシは**ユーザーが指定した**値を基準にどのモデルに安全に標識を付けるか決定します。ディスカバリー行はその export を無視し、固定の下限を保ちます。 直接編集した設定値が不正な場合は 829,800 に戻ります。 @@ -535,7 +535,7 @@ Messages → Responses に変換されるリクエストでは、Claude Code の | Assistant `tool_use` | `function_call`(`input` → JSON 文字列に変換した `arguments`) | | ユーザー `tool_result` | `function_call_output`(`is_error` → `[tool error]` 接頭辞) | | `thinking` / `redacted_thinking` 再生 | シグネチャと秘匿ペイロードを境界付き `ocxr1` エンベロープに保持した `reasoning` 項目 | -| Function ツール | `{type: "function"}`(`web_search*` → `{type: "web_search"}`). `api.anthropic.com` への翻訳ルートでは、型付き `web_search_*` と `web_fetch_*` 宣言も Anthropic に送信され、サーバー側で実行されます。ただし Web 検索サイドカーが `web_search` を提供する場合はそちらが優先されます。検索と取得の結果は `server_tool_use` と対応する `web_search_tool_result` / `web_fetch_tool_result` としてクライアントに返されます | +| Function ツール | `{type: "function"}`(`web_search*` → `{type: "web_search"}`). `api.anthropic.com` への翻訳ルートでは、型付き `web_search_*` と `web_fetch_*` 宣言も Anthropic に送信され、サーバー側で実行されます。ただし Web 検索サイドカーが `web_search` を提供する場合はそちらが優先されます。検索と取得の結果は `server_tool_use` と対応する `web_search_tool_result` / `web_fetch_tool_result` としてクライアントに返されます `allowed_domains`、`blocked_domains`、`user_location` を指定したホスト検索は翻訳された Responses/Chat ルートから除外され、強制すると 400 を返します。有効な `defer_loading` 関数定義は通常の関数として呼び出せます。[翻訳の制限](/guides/claude-code/#search-restrictions-and-deferred-tools-on-translated-routes)を参照してください。 | | `tool_choice` | `auto`→`auto`、`none`→`none`、`any`→`required`、名前指定関数→`{type:"function",name}`、ホスト型 WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | @@ -566,7 +566,7 @@ role、`tool_use_id` のない `tool_result`、id/name のない `tool_use`、na **エラー分類:** 400 `invalid_request_error`、401 `authentication_error`、 402 `billing_error`、403 `permission_error`、404 `not_found_error`、409 `conflict_error`、 413 `request_too_large`、429 `rate_limit_error`、504 `timeout_error`、529 `overloaded_error`、 -それ以外の 5xx は `api_error` です。`Retry-After` はそのまま維持します。 +それ以外の 5xx は `api_error` です。`Retry-After` は整数の秒数で送信し(HTTP 日付は残り秒数に変換)、上限は 8 日です。 ## プロンプトキャッシュとトークン使用量 @@ -574,9 +574,9 @@ role、`tool_use_id` のない `tool_result`、id/name のない `tool_use`、na 分岐点と最上位自動 `cache_control` を管理します。安定した会話では通常キャッシュヒット率が約 99.9% です。 -**ネイティブ OpenAI/ChatGPT ルーティング:** セッションスコープ `prompt_cache_key`(`metadata.user_id` があれば -使用、なければシステム内容ハッシュ使用)とキャッシュ選好のための `session_id` ヘッダーを作ります。 -キャッシュキーにはモデルと全体ツールスキーマが含まれます。 +**ネイティブ OpenAI/ChatGPT ルーティング:** `prompt_cache_key`(`metadata.user_id` が文字列であれば +使用、なければシステム内容ハッシュ使用)と、セッション識別子がある場合のみキャッシュ選好のための `session_id` ヘッダーを作ります(共有フォールバックキーからは作りません)。 +システム内容ハッシュから作るフォールバックキー(システム内容がある場合のみ)には、モデルと全体ツールスキーマも含まれます。 **トークン計算:** Anthropic 出力は `input_tokens` から `cached_tokens` と `cache_write_tokens` を引き、 それぞれ `cache_read_input_tokens` と `cache_creation_input_tokens` として公開します。リクエストログはこれを再び diff --git a/docs-site/src/content/docs/ja/guides/codex-app-models.md b/docs-site/src/content/docs/ja/guides/codex-app-models.md index 63d62a2736..daa8fc7eab 100644 --- a/docs-site/src/content/docs/ja/guides/codex-app-models.md +++ b/docs-site/src/content/docs/ja/guides/codex-app-models.md @@ -3,6 +3,8 @@ title: Codex App モデル ピッカー description: opencodex モデルが、共有 Codex カタログを通じて Codex App、Codex CLI、Codex TUI にどのように表示されるか。 --- +既定値は `false` です。`config.json` に `"omitDisabledNativeModels": true` を設定して `ocx sync` を実行すると、無効な native 行を catalog、cache、Codex 形式の HTTP モデル一覧から除外します。除外前に検証した継承テンプレートを保持するため routed 行のメタデータは変わりません。直接リクエストのルーティングも変わりません。以下の hide の説明は既定の設定に適用されます。 + opencodex は Codex アプリにパッチを適用しません。Codex CLI/TUI と同じ Codex 設定とモデル カタログを書き込みます。app-server はその共有状態を読み取りますが、一部の Codex Desktop リリースは renderer 側で追加の remote allowlist を適用し、routed row を picker から除外する @@ -52,10 +54,11 @@ visibility = "list" |ルート |ピッカー ID とカタログのメタデータ | | --- | --- | -| Codex ログイン (account-qualified 行が無効) | `gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-5.6-luna` などの bare native id を表示し、`codexAccountMode` に従って Pool または Direct を使用します。GPT-5.6 行のカタログ ウィンドウは 922,000 トークンです。 | +| Codex ログイン (account-qualified 行が無効) | `gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-5.6-luna` などの bare native id を表示し、`codexAccountMode` に従って Pool または Direct を使用します。GPT-5.6 行のカタログ ウィンドウは 922,000 トークンです。 `gpt-6.1-terra`:既定 500,000 / 長文 872,000。 | | Codex ログイン (account-qualified 行が有効で、有効な selector あり) | 有効な selector とサポート対象 native model の各組み合わせに `/` 行を表示します。各行は対応付けられたアカウントだけを使用し、bare native 行はピッカーで非表示になります。Native metadata と context window は保持されます。 | -| OpenAI (API キー) |正確に 8 つの名前空間行: `gpt-5.5`、`gpt-5.6`、Sol/Terra/Luna、および 3 つの `*-pro` 仮想 ID (コンテキスト 922,000、8 つすべての最大入力 922,000) | +| OpenAI (API キー) | 名前空間付きモデルには `gpt-5.5`、`gpt-5.6`、Sol/Terra/Luna、`*-pro` 仮想 ID、Daybreak エイリアスが含まれます(コンテキスト 1,050,000、最大入力 922,000)。`openai-apikey/gpt-6.1-terra` はコンテキスト 1,050,000、最大出力 128,000 です。 | |オープンルーター | `openrouter/openai/gpt-5.6-sol`、`openrouter/openai/gpt-5.6-terra`、`openrouter/openai/gpt-5.6-luna` (922,000) | +| OpenRouter | `openrouter/openai/gpt-6.1-terra` (1,050,000) | | Cursor | 静的フォールバックには `cursor/gpt-5.6-sol`、`cursor/gpt-5.6-terra`、`cursor/gpt-5.6-luna` (1,000,000) と、Grok 4.5 / 4.6 / 4.7 の通常・Fast 行 (500,000) が含まれます。4.6 と 4.7 は `xhigh` も公開し、ライブアカウントの検出によって表示される行が決まります。 | | xAI | xAI のライブ検出が優先されます。フォールバックには `xai/grok-4.6` と `xai/grok-4.7` が含まれ、デフォルトは `xai/grok-4.5` です。3 モデルともコンテキストは 500,000 トークンです。Grok 4.6 と 4.7 は `low` / `medium` / `high` / `xhigh`(上流のデフォルトは `high`)を提供し、Grok 4.5 は `high` までです。 | diff --git a/docs-site/src/content/docs/ja/guides/codex-integration.md b/docs-site/src/content/docs/ja/guides/codex-integration.md index 908fdd1bbc..57d16985e0 100644 --- a/docs-site/src/content/docs/ja/guides/codex-integration.md +++ b/docs-site/src/content/docs/ja/guides/codex-integration.md @@ -94,6 +94,8 @@ env_key = "OPENCODEX_API_AUTH_TOKEN" OpenCodex がルーティングを所有している場合、どちらのモードも参照/フォールバック設定として `$CODEX_HOME/opencodex.config.toml` を書き込みます。ループバックでは、自動挿入が削除された場合に手動でマージできるルート キーが含まれています。非ループバックでは、専用のプロバイダー フォームが含まれます。外部プロバイダー モードでは、このプロファイルは変更されません。 +このファイルを再生成しても、OpenCodex が管理しない単純なルート キーは保持されます。そのため、`stream_idle_timeout_ms` や `stream_max_retries` のように追加した設定は次の挿入後も残ります。保持される代入は、複数行にわたる値や 64 ビット整数も含めて書かれたとおりにコピーされ、最初のテーブルより前に置かれます。テーブル内のキーと、`a.b = 1` のようなドット付きルート キーは保持されません。衝突した場合は常に OpenCodex が優先されます。OpenCodex が所有するルート キー(`model_provider`、`model_catalog_json`、`openai_base_url`)は使用中のルーティング モードに合わせて書き直され、プロファイルが書き込むテーブルと同じ名前のルート キー(プロファイルが `[features]` を書き込むときのインライン `features = { ... }` など)は削除されます。挿入が書き込みロックを待っている間にファイルが変更された場合、挿入は再試行可能なエラーで停止し、編集内容はそのまま残ります。 + :::caution `openai_base_url`、`model_provider`、`model_catalog_json` などのルート キーは、最初の `[table]` ヘッダーの前に**なければなりません**。インジェクターはその配置を保証し、それ自身の古い/重複したコピーを削除し、ユーザー所有のルート `openai_base_url` を決して上書きしません。存在する場合、sync はカタログを更新しますが、ルーティングが挿入されなかったことを報告します。 ::: diff --git a/docs-site/src/content/docs/ja/guides/codex-prompt.md b/docs-site/src/content/docs/ja/guides/codex-prompt.md index fa1639d47b..30fa39a918 100644 --- a/docs-site/src/content/docs/ja/guides/codex-prompt.md +++ b/docs-site/src/content/docs/ja/guides/codex-prompt.md @@ -36,6 +36,11 @@ Codex が実際には使用しない順序を示すことになります。 レイヤー名をクリックすると、送信されるテキストを確認できます。ダイアログは `codex debug prompt-input` から内容を読み取るため、説明ではなく実際の送信内容です。 +読み取りには、メタデータの読み取りと共有プローブの待機時間を含む、呼び出しごとに固定の +15 秒の制限があります。同期的なメタデータの読み取りが終わってから時間切れを確認し、 +制限に達していれば新しいプローブを開始しません。時間切れになると、ダイアログはプロンプトを +読み取れなかったと表示しますが、ローカルで読み取れた基本指示は引き続き返されます。 + 表示する内容がない場合もあり、ダイアログに該当する理由が表示されます。 - **ファイルは存在しますが空です。** `~/.codex/AGENTS.md` が 0 バイトのため、 diff --git a/docs-site/src/content/docs/ja/guides/combos.md b/docs-site/src/content/docs/ja/guides/combos.md index cb31f349e6..ecd110db6b 100644 --- a/docs-site/src/content/docs/ja/guides/combos.md +++ b/docs-site/src/content/docs/ja/guides/combos.md @@ -64,6 +64,8 @@ ocx combo show main ## 戦略を選択してください +必須の `tool_choice` を維持できないターゲットは送信前にスキップされ、すべて非対応の場合はその制約を示すエラーを返します。自動選択のみを許可する Chat モデルと、OpenAI 仮想モデルの実際の送信モデルのポリシーも判定対象です。直接の hosted/MCP 選択、`tool_search`、無効な選択値の扱いは[英語の基準説明](/guides/combos/#failover-ordered-primary-and-backups)を参照してください。 + ### フェイルオーバー: 順序付けされたプライマリとバックアップ `failover` は、構成順序で最初の適格なターゲットを選択します。ターゲットは、プロバイダーが存在し、有効になっていて、クールダウン中でなく、特別なリクエスト制約を処理できる場合に適格となります。重みと `stickyLimit` はこの戦略に影響しません。 @@ -76,6 +78,8 @@ ocx combo show main 各リクエストは Anthropic で始まります。再試行可能な Anthropic エラーが発生すると、そのリクエストは OpenAI に移動します。再試行可能な OpenAI が失敗すると、OpenAI が Google に移される可能性があります。端末エラーは、残りのターゲットを試行する代わりに、ただちに停止します。 +プロバイダーの HTTP 400 応答も、ターゲット固有である場合があります。OpenRouter の不透明なプロバイダーラッパー(数値の `code: 400`、`type` なし、`metadata.raw: "ERROR"` を持つ `Provider returned error`)はターゲットローカルとして扱われ、失敗したターゲットをクールダウンせずに combo が次のターゲットを試行できるようにします。型付きの未コード化 400、既知の不正な `response_format` スキーマエラー、およびルートが独自の終了コードを示すエンベロープは終了扱いのままです。ルートが独自のホップ信号(`model_not_found`、`insufficient_quota`、`usage_limit_exceeded`、`free_rate_limited`、`input_admission_refused` または `unsupported_input_modality`)を示しても新しい判定は追加されず、空のコードはコードなしとして扱われます。このガイドで後述する認識されたターゲット非互換性は引き続き進行します。 + ### ラウンドロビン: スムーズな加重バッチ `round-robin` はスムーズな加重ラウンドロビンを使用します。ターゲットの重みが大きいほど、すべてのシェアを 1 つの長いブロックとして送信することなく、時間の経過とともにそのターゲットに大きなシェアが与えられます。 `stickyLimit` は、次の重み付けされた選択の前に、選択されたターゲットに残る成功したリクエストの数を制御します。 @@ -124,15 +128,18 @@ ocx combo set balanced \ | HTTP 401、403、404、408、429、または任意の 5xx |ターゲットを冷却し、次の適格なターゲットに移動します。 | |モデルのサポート終了、retired、deprecated、sunset、decommissioned、または利用不可を明示する HTTP 410 |そのターゲットをクールダウンし、次へ進みます。無関係な 410 はターミナル エラーのままです。 | |機密認証、サブスクリプション、クォータ、レート制限、過負荷、またはアップストリーム サーバー エラー |ステータスだけでは物足りない場合でもターゲットを冷やしてホップさせましょう。 | -|クライアントのキャンセル (499)、`origin_rejected`、サイバー ポリシーの拒否、コンテキスト オーバーフロー、またはその他の無効なリクエスト |停止してエラーを返します。別のターゲットではリクエストは有効になりません。 | +|クライアントのキャンセル (499)、`origin_rejected`、サイバー ポリシーの拒否、またはその他の無効なリクエスト |停止してエラーを返します。別のターゲットではリクエストは有効になりません。 | +| 出力前に確認したコンテキスト超過(HTTP 400 を含む) | クールダウンせず次の未試行の適格な対象へ進み、使い切った場合は最初に確認した HTTP 400 のコンテキストエラーを返します(他のステータスのコンテキスト拒否も次へ進みますが、保持されません)。 | | ChatGPT アカウントで Codex を使う際に、そのモデルをサポートしないことを示す正確な HTTP 400 の拒否 | 出力を確定する前に、次の設定済みターゲットを試します。拒否文全体が `detail`、`error.message`、または本文そのものにある場合に限ります。`detail` と `error` が競合する応答は終了扱いです。この拒否だけでアカウントを再認証待ちにしたり、プロバイダーの全モデルをクールダウンしたりしません。 | -|`user` の明示的な拒否、`reasoning.effort`/`reasoning_effort` の非対応値、モデル固有の画像入力拒否(`param: input`)、またはルートが読み取れない入力メディアの拒否(`unsupported_input_modality`)を示す構造化 HTTP 400 |出力開始前に次の適格なターゲットへ進み、クールダウンを記録しません。任意パラメーターの互換性を参照してください。 | +|`user` の明示的な拒否、`reasoning.effort`/`reasoning_effort` の非対応値、モデル固有の画像入力拒否(`param: input`)、またはルートが読み取れない入力メディアの拒否(`unsupported_input_modality`)を示す構造化 HTTP 400 |推論エフォートの拒否の場合、送信バジェットが許す限り同じターゲットで次に低い公開ラングを試行します。どのラングも機能しない場合は、認識された互換性のある形式に一致すれば冷却せずに出力確定前に次のターゲットへ進み、それ以外は終了します。その他の記載された不一致はクールダウンなしで進みます。任意パラメーターの互換性を参照してください。 | |インプロセスアダプター(`runTurn`)が実行する Responses ターンで、現在のリクエストが宣言していない最初のツール呼び出し(出力やリプレイ不可の副作用より前) |ターゲットをクールダウンし、同じツールカタログで次へ進みます。可視出力やリプレイ不可の副作用の後は拒否が確定します。Chat Completions と Anthropic Messages のリクエストは変わりません。 | |その他の未分類のエラー |停止してエラーを返します。 | `cooldownMs` が未設定の場合、ホップされたターゲットはアップストリームのフォールバックを使用します。アップストリームコード `1302` または `1305` を伴うリクエストレート 429 では 5 秒、アカウントの利用枠を使い切った場合は 10 分、それ以外では 60 秒です。利用枠を使い切ったことは、アップストリームコード(`usage_limit_exceeded`、`usage_limit_reached`、`1308`)または `usage limit reached` という文言で判定され、HTTP ステータスには依存しません。ChatGPT Codex バックエンドは、使い切った枠をドキュメント化された 429 ではなく 502 として報告するためです。プロバイダー全体をすでに除外する認証情報・請求の失敗(`invalid_api_key`、`insufficient_quota`、`payment_required` など)も同じ 10 分間のクールダウンになります。設定されている場合、使用可能なアップストリームの `Retry-After` または Codex リセットシグナルが存在しないときは、これらのリクエストレート 429 を含め、`cooldownMs` が適用されます。数値の `Retry-After` 秒数と HTTP-date 値が受け入れられ、明示的な上流の `Retry-After` は最大 24 時間、リセット由来・設定済み・フォールバックのクールダウンは最大 10 分です。優先順位は強い順に、明示的な `Retry-After` → Codex リセットヘッダー(`x-codex-primary-reset-at`、`x-codex-secondary-reset-at`、または `x-codex-tertiary-reset-at`)→ コンボの `cooldownMs`(設定時)→ 使い切った利用枠または認証情報・請求の失敗に対する 10 分のクールダウン → アップストリームのレート制限コード `1302`/`1305` に対する 5 秒のリクエストレート フォールバック → 60 秒のデフォルトです。利用枠のクールダウンが先に判定されるため、リクエストレートコードと利用上限の文言の両方を伴う失敗は、5 秒ではなく 10 分のクールダウンになります。有効な即時指定 `Retry-After: 0` は、設定されたクールダウンで置き換えられず、即時のアップストリーム指示として維持されます。 -現在のリクエストは、同じ試行ターゲットを再試行しません。ただし例外が1つあります。`waitForCooldownMs` を設定した単一ターゲット コンボは、フェイルオーバー先の代替がないため、同じリクエスト内でそのターゲットのクールダウンが期限切れになれば、唯一のターゲットを再試行できます。リクエストローカルの互換性拒否は、引き続き再試行せずに返されます。後続のリクエストでは、クールダウンが期限切れになるまでそのターゲットをスキップします。すでに過去の時刻である `Retry-After` の HTTP-date も、`Retry-After: 0` と同様に即時のアップストリーム指示として維持されます。`waitForCooldownMs` を設定すると、後続のリクエストは、最も早く利用可能になるターゲットのクールダウンを、その選択試行ごとにこの上限まで待ってから、新たに 1 回選択できます。したがって、複数のフェイルオーバー ホップをまたぐリクエストは合計で `hops × waitForCooldownMs` まで待つ場合があります。デフォルトは `0` です。適格なターゲットがすべて冷却中の場合、HTTP 503 ですぐにフェイルクローズし、その `combo_unavailable` 503 には最も早く終了する残りのクールダウンと等しい `Retry-After` ヘッダーが含まれ、秒単位に切り上げられ、最小値は 1 秒です。待機にはジッターがないため、同期したウェイクアップが発生する可能性があります。中止されたリクエストはこの待機をキャンセルし、通常の `client_cancelled` 応答を返します。キャンセル後にバックアップ ターゲットをディスパッチすることはありません。コンボ ターゲットのクールダウンはプロセス ローカルなコンボごとの状態であり、ネイティブ アカウント ルーティングで使用されるアカウントレベルの Codex クォータ クールダウンとは別です。 +現在のリクエストは、同じ試行ターゲットを再試行しません。ただし例外が1つあります。`waitForCooldownMs` を設定した単一ターゲット コンボは、フェイルオーバー先の代替がないため、同じリクエスト内でそのターゲットのクールダウンが期限切れになれば、唯一のターゲットを再試行できます。リクエストローカルの互換性拒否は、引き続き再試行せずに返されます。後続のリクエストでは、クールダウンが期限切れになるまでそのターゲットをスキップします。すでに過去の時刻である `Retry-After` の HTTP-date も、`Retry-After: 0` と同様に即時のアップストリーム指示として維持されます。`waitForCooldownMs` を設定すると、後続のリクエストは、最も早く利用可能になるターゲットのクールダウンを、その選択試行ごとにこの上限まで待ってから、新たに 1 回選択できます。したがって、複数のフェイルオーバー ホップをまたぐリクエストは合計で `hops × waitForCooldownMs` まで待つ場合があります。デフォルトは `0` です。適格なターゲットがすべて冷却中の場合、HTTP 503 ですぐにフェイルクローズし、その `combo_unavailable` 503 には最も早く終了する残りのクールダウンと等しい `Retry-After` ヘッダーが含まれ、秒単位に切り上げられ、最小値は 1 秒です。待機にはジッターがないため、同期したウェイクアップが発生する可能性があります。中止されたリクエストはこの待機をキャンセルし、通常の `client_cancelled` 応答を返します。キャンセル後にバックアップ ターゲットをディスパッチすることはありません。コンボ ターゲットのクールダウンはコンボごとの状態であり、ネイティブ アカウント ルーティングで使用されるアカウントレベルの Codex クォータ クールダウンとは別です。絶対的な期限とともに opencodex ホームの `combo-cooldowns.json` に保存されるため、再起動後もその期限まで維持されます。同じホームを共有するプロキシ同士が互いのクールダウンを短縮することはありません。コンボを保存、名前変更、削除すると、そのクールダウンは消去されます。 + +上記の HTTP 503 は、まだ対象を試行していない場合に適用されます。確認済みの HTTP 400 コンテキスト拒否の後に適格な対象または送信予算を使い切った場合、最初の拒否を `context_length_exceeded` として返し、クォータを含む後続の再試行可能なエラーより優先します。残りの対象が推論を再生できない場合や従量課金への同意がない場合も同様です。キャンセル、後続の致命的な拒否、明示的なフォールバックポリシーの拒否は直ちに停止します。同意のない従量課金対象へは送信しません。 :::note フェイルオーバーは意図的に制限されています。これは、ターゲット固有の可用性、認証、クォータ、および過負荷の障害に役立ちます。呼び出し元のエラーやポリシーの拒否は隠蔽されません。 @@ -266,10 +273,14 @@ ocx combo remove --yes ### 最初のエラーの後にフェイルオーバーが停止したのはなぜですか? -このエラーはターゲット固有のものではなく、最終的なものでした。無効な入力を修正し、大きすぎるコンテキストを削減し、ポリシーの拒否を処理し、拒否されたリクエストの送信元を修正します。コンボはそのような場合には機能しません。 +このエラーはターゲット固有のものではなく、最終的なものでした。無効な入力を修正し、ポリシーの拒否を処理し、拒否されたリクエストの送信元を修正します。コンボはそのような場合には機能しません。 ## 任意パラメーターの互換性 -通常の 400 エラーは終了扱いですが、`user` の明示的な拒否、`reasoning.effort`/`reasoning_effort` の非対応値、モデル固有の画像入力拒否(`param: input`)、またはルートが読み取れない入力メディアの拒否(`unsupported_input_modality`)を示す構造化エラーでは、出力開始前に次の適格なターゲットへ進めます。この不一致ではクールダウンを記録しません。安全ポリシーによる拒否、キャンセル、出力開始後の再実行は禁止のままです。 +通常の 400 エラーは終了扱いですが、OpenRouter の不透明なプロバイダーラッパー(数値の `code: 400`、`type` なし、`metadata.raw: "ERROR"` を持つ `Provider returned error`)、または `user` の明示的な拒否、`reasoning.effort`/`reasoning_effort` の非対応値、モデル固有の画像入力拒否(`param: input`)、またはルートが読み取れない入力メディアの拒否(`unsupported_input_modality`)を示す構造化エラー、およびベンダーエンベロープ `{"code":"invalid-argument","error":"Invalid reasoning effort."}` では、出力確定前に次の適格なターゲットへ進めます。コンボターゲットが要求された推論エフォートを拒否した場合、コンボはまずそのターゲットで次に低い公開エフォートラングを、拒否ごとに1ラングずつ、共有送信バジェットの範囲内で再試行します。これは認識されたすべてのエフォート拒否に適用されます。より低いラングがいずれも成功しない場合、上記のいずれかの形式の拒否は拒否されたターゲットを冷却することなく別のターゲットへ進み、次のラングに送信枠が残っていない場合はそのターゲットの元の 400 を保持します。その他のエフォート拒否は終了扱いのままです。メディアを `unsupported_input_modality` で拒否するルートも同様に進みます。これらはこのリクエストに対する不一致であり、ターゲットが異常である証拠ではありません。直接リクエストは単一のエフォートダウングレード修復を保持します。互換性回復によって `none` が別のエフォートに暗黙に変更されたり、任意の無効なリクエストにコンボホップが拡大されたりすることはありません。安全ポリシーによる拒否、キャンセル、出力開始後の再実行は禁止のままです。単一ターゲットのリクエストは未解決の上流拒否を返します。 [Canonical compatibility details](/guides/combos/#request-local-target-compatibility). + +## クールダウン回復の予約 + +`cooldownReprobe: { enabled: true }` で有効にした回復試行は、予約したリクエストだけに属し、他のリクエストには保存済みのクールダウンが引き続き適用されます。予約はクールダウン待機と JEV 選択を経ても維持されます。待機中に再び利用可能になったターゲットは、クールダウンが変わっていなければ再試行できますが、新しいクールダウンの記録はそのターゲットの予約を無効にします。成功時は応答したターゲットの変更されていないクールダウンだけを解除し、未試行のターゲットや新しい失敗のクールダウンは残します。プロバイダーの無効化、クォータ、リクエストの適格性、キャンセルの確認は引き続き有効です。[設定と制限](/guides/combos/#retry-all-cooled-targets-opt-in)を参照してください。 diff --git a/docs-site/src/content/docs/ja/guides/desktop-app.md b/docs-site/src/content/docs/ja/guides/desktop-app.md index 4bac00e438..8a802d6743 100644 --- a/docs-site/src/content/docs/ja/guides/desktop-app.md +++ b/docs-site/src/content/docs/ja/guides/desktop-app.md @@ -46,6 +46,10 @@ sudo apt install ./OpenCodex--linux-amd64.deb macOS では、ダッシュボードを閉じてもアプリはメニューバーで動作し続けます。Dock または Finder から OpenCodex を再度開くと、プロキシを再起動せずにダッシュボードが再表示されます。 +Codex の起動でプロキシが見つからない場合、同梱 CLI は独立して検証された Desktop の復旧を待ちます。Desktop に記録された所有権クレームがない場合も同様です。一致する Desktop がプロキシを停止済みか復旧を検証できないときはエラーになりますが、実行イメージ検証のないプラットフォームでは、記録された所有権クレームがありアプリが実行中なら既存の制限付き待機を維持します。プロセス名や検出ファイルだけでは通常の CLI 起動を妨げません。shim は macOS でアプリが終了しており、記録された所有権が有効な **Start at Login** 登録と一致すれば OpenCodex を開きます。自動で開き直すときはその登録の app バンドルパスを選択し、宣言されたメイン実行ファイルが登録済み Desktop の実行ファイルと一致するか確認します。登録がない・古い・不整合の場合は OpenCodex を手動で開いてください。同じバンドル識別子を持つ別コピーは代替として選択されません。shim が "activation not confirmed" と表示する場合は、シェル起動ファイルの他の PATH 設定の後に `. ~/.opencodex/codex-shell-env.sh` を追加してください。 + +復旧検証の対象は、macOS/Linux の一致する同梱 CLI と保護されたシステム Debian インストールです。古い npm 製の shim は別の Bun/CLI インストールを固定し、Desktop のターミナルコマンド受け渡しを迂回する場合があります。そのエントリポイントでは、公式署名コピーを含む macOS/Windows の Desktop や任意のユーザー単位 Linux コピーを検証できません。Desktop の Startup ページで shim を作り直すか、同梱 CLI を実行してください。Windows はこの復旧証明に必要な実行イメージの同一性をまだ確立できません。識別された実行中の兄弟プロセスは復旧クレジットを得られず、記録された Desktop クレームがなければ CLI プロキシを起動する代わりにエラーを報告します(ディスク上の署名が有効でも同様です)。記録されたクレームがありアプリが実行中なら、CLI は Desktop のプロキシへの既存の制限付き待機を維持します。 + ## トレイでの使用量表示 macOS と Windows ではトレイアイコンをクリックするとコンパクトな使用量ウィンドウが開きます。トレイの **Show usage** 操作でも開けます。これはトレイのクリックイベントを転送しない Linux デスクトップでも使えます。Linux では、デスクトップ環境にトレイアイコンが表示されなくても起動時にダッシュボードが開きます。 diff --git a/docs-site/src/content/docs/ja/guides/integrations.md b/docs-site/src/content/docs/ja/guides/integrations.md index 1cecbcb394..adb148640d 100644 --- a/docs-site/src/content/docs/ja/guides/integrations.md +++ b/docs-site/src/content/docs/ja/guides/integrations.md @@ -3,7 +3,9 @@ title: クライアント統合 description: ダッシュボードから opencodex を OpenCode、Pi、OMP、Hermes、OpenClaw、Kimi Code、gjc、DeepSeek Harness、MiniMax Code、ZCode、Prime Agent、Aside、Raycast、omo、Cline CLI、Kilo、Command Code、Factory Droid に接続します。クライアントごとにスイッチがあり、書き込み前には必ずバックアップを取ります。 --- -**接続** タブは、各クライアントの設定ファイルに opencodex のプロバイダーブロックを書き込み、必要に応じて削除します。次の 18 クライアントは、それぞれのスイッチで管理できます。 +**接続** タブは、各クライアントの設定ファイルに opencodex のプロバイダーブロックを書き込み、必要に応じて削除します。以下のクライアントは、それぞれのスイッチで管理できます。 + +Windows で絶対パスが必要なオーバーライドには、ドライブ文字(`C:\Users\me\client`)または UNC 共有(`\\server\share\client`)が必要です。現在のドライブに依存する `\Users\me\client` と `/client/config` は拒否されます。`~` 対応と明記されたセレクターは有効なホームを基準に展開します。Gentle Shell は `~` を展開しません。 | クライアント | 設定ファイル | 形式 | 変更が反映される時点 | 認証情報 | |---|---|---|---|---| @@ -23,7 +25,7 @@ description: ダッシュボードから opencodex を OpenCode、Pi、OMP、Her | omo | `~/.omo/agent/models.json` | JSON | 新しいセッション | ループバック用プレースホルダー | | Cline CLI | `~/.cline/data/settings/providers.json` と同階層の `models.json` | JSON のペア | Cline の停止と再起動後 | ループバック用プレースホルダー | | Kilo | `~/.config/kilo` 内で最初に存在する `kilo.jsonc`、`kilo.json`、`opencode.jsonc`、`opencode.json`、`config.json`(`XDG_CONFIG_HOME` でディレクトリを変更可能。どれもなければ `kilo.jsonc` を作成) | JSONC | 新しいセッション | `OPENCODEX_KILO_API_KEY` | -| Command Code | `~/.commandcode/providers.json` (Windows の既定ホームを使用する場合: `HOME ?? USERPROFILE` が空文字列や空白のみではなく Windows の絶対パスの場合に限り使用し、それ以外は `homedir()`。別途指定されたホームは保持。その配下の `.commandcode\providers.json`) | JSON | Command Code の次回起動時 | なし — キー不要のループバック (`apiKey: false`) | +| Command Code | `~/.commandcode/providers.json` (Windows の既定ホームを使用する場合: `HOME ?? USERPROFILE` が空文字列や空白のみではなく Windows の絶対パスの場合に限り使用し、それ以外は `homedir()`。別途指定されたホームは保持。その配下の `.commandcode\providers.json`) | JSON | Command Code の次回起動時 | なし — キー不要のループバック (`apiKey: false`)。デスクトップアプリは独自のサインインが必要で、opencodex は `auth.json` を書き込みません | | Factory Droid | `~/.factory/settings.json` (`%USERPROFILE%\.factory\settings.json` Windows の場合) | JSON | ファイル変更を即時反映 | キー不要のループバック | 生成されるカタログには、各プロバイダーの選択で有効なモデルのみが含まれます。これはダウンロードと管理対象の統合の両方に適用され、Pi と Aside も対象です。管理画面のモデル一覧にはすべてのモデルが表示されるため、追加のモデルを有効にできます。 @@ -98,9 +100,9 @@ Apply、Replace、Disable、Restore はプレビューから始まります。 計画に変更がない場合、管理対象のクライアント文書は要求した状態にすでになっています。選択された Aside プロファイルでは、文書に変更がなくても、確定によって同期の設定が保存される場合があります。 -確認後にファイルが変更されると、古い計画として書き込みが拒否されます。ダイアログは更新された計画に置き換えて再確認を求め、自動再試行はしません。プレビューが一時的に使えない場合は、通常どおりページを再読み込みして操作をやり直してください。 +確認後にファイルが変更されると、古い計画として書き込みが拒否されます。ダイアログは更新された計画に置き換えて再確認を求め、自動再試行はしません。プレビューがモデルカタログ未読み込みを報告した場合、ダイアログは開いたままで **カタログを読み込んで再試行** を表示します。統合一覧を読み直してから計画を再度取得します。 -Aside も選択したプロファイル 1 件ずつ同じプレビューと確認の手順を使います。**Sync all profiles** は別の一括操作であり、1 つの統合プレビューには結び付きません。 +Aside も選択したプロファイル 1 件ずつ同じプレビューと確認の手順を使います。**Sync all profiles** は別の一括操作であり、1 つの統合プレビューには結び付きません。1 つの計画は 1 プロファイルのファイルだけを表すため、競合している Aside の概要カードには **プロファイルを選択** が表示され、ブロックの置き換えはそのプロファイルのページで行います。 ## 実際に起こること @@ -221,6 +223,16 @@ Undo は、もともと存在しなかったファイルも含め、**元の両 ダウンロードされる `cline-config-bundle.json` には、`providers.json` 用の `settings` と `models.json` 用の `catalog` という 2 つのネイティブ文書要素が含まれます。それ自体は Cline の設定ファイルではありません。ジャーナル付きのマージとロールバックには統合コマンドを使ってください。生成された統合はリモートの受け入れ認証に対応せず、認証不要のループバックアクセスが必要です。 +## omo (Pi ベース) の Responses 方言 + +管理対象の Pi ベース omo ブロックは、既定で Chat 方言 (`api: "openai-completions"`) を使います。Chat はツール呼び出しをまたいで前のステップの推論を落とすため、長い omo のツールループで影響が出ます。有効化とすべての更新で Responses 方言を書き込むには、opencodex の設定ファイルにだけ設定できる次のキーを追加します。 + +```json +{ "omoClientExport": { "api": "openai-responses" } } +``` + +編集した設定を読み込むためにプロキシを再起動し (サービスとしてインストールした場合は `ocx service restart`、それ以外は `ocx stop` の後に `ocx start`)、ダッシュボードの **Connect → omo** から omo 統合を更新してください。更新だけでは実行中のプロキシの設定を使い、設定ファイルは読み直しません。この設定は omo にだけ適用され、Pi、Gentle Shell などほかの Pi 形式のクライアントは `openai-completions` のままです。Chat に戻すには、キーを削除して同じ手順で再起動し、**Connect → omo** を更新します。不明な値は無視されます。opencodex が所有するのは引き続き `~/.omo/agent/models.json` の `providers.opencodex` だけで、ほかのプロバイダーはそのまま残ります。 + ## omo (Codex / LazyCodex) のロール別推論負荷 LazyCodex が検出されると、omo タブの **omo (Codex / LazyCodex)** セクションで、`$CODEX_HOME/agents/*.toml` にある各ロールのモデルと推論負荷を選んで **保存** できます。モデルが固定されていないロールの行では推論負荷だけを保存でき、そのロールは引き続きモデルを継承します。opencodex はそのロールファイルのルートにある `model` と `model_reasoning_effort` のキーだけを更新し、存在しない固定値はファイルの先頭付近に追加します。ロールの指示、ほかのコメントやキーはそのまま残ります。モデルだけを変えて保存すると `effort` を送らないため、両方のファイルの推論負荷は変わりません。段階を選ぶとロールファイルの `model_reasoning_effort` を追加または置き換え、LazyCodex がその段階に対応していれば `~/.omo/omo.jsonc` の `[codex].agents..reasoning` にも書き込みます(`ultra` はロールファイルにだけ残り、以前の `reasoning` は削除されます)。コマンドラインでは `ocx agent roles set --effort ` で同じ操作ができます。 @@ -233,6 +245,8 @@ LazyCodex が検出されると、omo タブの **omo (Codex / LazyCodex)** セ **自動割り当て** は、必要な能力と推論負荷を評価したロールのうち、選んだモデルの推論負荷の段階リストが空でないすべてのロールに推論負荷を提案します。**適用**、**すべて適用**、または `ocx agent roles suggest --apply` は、そのロールの `model_reasoning_effort` を追加または置き換えます。推論負荷は選んだモデル自身の段階から、最も低い段階、既定の段階、既定より 1 つ上の段階、最も高い段階のいずれかになります。段階リストが空なら推論負荷を提案せず(`proposedEffort: null`)、適用時は `effort` を送らないため既存の固定値はそのまま残ります。`null` の提案が固定値を消すことはありません。 +CLI の `ocx agent roles suggest --apply` は、1 つの履歴バッチで最大 **50 件の変更対象ロール**を適用します。設定が既に一致するロール、評価されていないロール、割当先のないロールは数えません。50 件を超える場合は、ロールの更新を一件も送信せず終了コード 5 で拒否します。`--apply` なしでプレビューし、個別の変更には `ocx agent roles set [--effort ]` を使ってください。途中で失敗した場合の確認済み・未確認の更新と再試行の注意点は、[CLI の適用と復旧の契約](/reference/cli/agents/)を参照してください。 + ## Kilo Kilo CLI、VS Code、JetBrains は同じグローバル設定を共有します。この統合は `~/.config/kilo` 内の `kilo.jsonc`、`kilo.json`、`opencode.jsonc`、`opencode.json`、`config.json` のうち最初に存在するファイルに `provider.opencodex` を書き込みます。`XDG_CONFIG_HOME` でこのディレクトリを変更できます。候補がなければ `kilo.jsonc` を作成します。プロジェクト設定には書き込みません。 @@ -276,3 +290,19 @@ GitHub Copilot デスクトップアプリでは、opencodex を OpenAI 互換 ## Factory Droid Factory Droid は `~/.factory/settings.json`(Windows では `%USERPROFILE%\.factory\settings.json`)を使用します。`ocx integration client enable --client droid` で明示的に有効化し、`/model` でカスタムモデルを選択します。管理対象の行はキーを使わず、ループバックでのみ動作します。無効化すると管理対象の行が削除され、Undo で保存済みのバイト列が復元されます。従来の `config.json` に OpenCodex の行がある場合や、`settings.local.json` が `customModels` を上書きする場合は、有効化する前に競合を解消してください。[Factory BYOK のドキュメント](https://docs.factory.ai/model-independence/byok)も参照してください。 + +## Hermes / Command Code: model names + +Hermes and Command Code support `--model-names alias|routed` (API: `modelNames`). +The default is `routed`, independent of `preferModelAliasIds`. A connection +stores its mode; later Apply without the option preserves it. Alias mode uses +only provider-qualified aliases that the router proves equivalent; missing, +unsafe or colliding aliases fall back to routed keys. Combos keep their keys. +Removed/renamed aliases migrate on the next successful managed refresh, with +foreign-edit refusal. Named Hermes profiles need explicit Apply. + +`ocx export --client hermes --model-names alias --json` previews a current +already loaded catalog without writing client files or managed state; a cold or +stale catalog returns unavailable. Explicit `--out` writes an export artifact. +See the [English integration guide](/guides/integrations/#opt-in-alias-model-names) +for the canonical workflow. diff --git a/docs-site/src/content/docs/ja/guides/model-ordering.md b/docs-site/src/content/docs/ja/guides/model-ordering.md index 74febb1e78..a00f1cd0c0 100644 --- a/docs-site/src/content/docs/ja/guides/model-ordering.md +++ b/docs-site/src/content/docs/ja/guides/model-ordering.md @@ -28,7 +28,7 @@ selector がない場合の priority は次のとおりです。 --- | ---: | --- | | `subagentModels[i]` | `i`(`0` から `4`) | `src/codex/catalog/sync.ts` の featured rank map | | その他のルーティングモデル | `5` | `src/codex/catalog/sync.ts` のルーティング項目生成 | -| デフォルトネイティブ GPT スラッグ | `9` | `src/codex/catalog/sync.ts` のネイティブ項目生成 | +| デフォルトネイティブ GPT スラッグ | `sourcePriority` | `src/codex/catalog/sync.ts` のネイティブ項目生成 | | featured リストがあるとき選択されていないネイティブモデル | 最小 `featured.length + 100` | `src/codex/catalog/sync.ts` のネイティブカタログマージ | 管理 API は `src/server/management/agent-settings-routes.ts` の `slice(0, 5)` で `subagentModels` を最大 @@ -69,7 +69,7 @@ Codex の priority ソートでもこの先頭順序は保存されます。 3. カタログマージ過程で featured ブロックの下に押し下げられた選択されていないネイティブモデル `subagentModels` がない場合、ルーティングモデルは priority `5` を維持し、ネイティブ GPT 項目は通常 priority -(opencodex が作った項目は通常 `9`)を使います。ルーティンググループ内部は引き続きプロバイダー/ID +(sourcePriority、情報がなければ `9`)を使います。ルーティンググループ内部は引き続きプロバイダー/ID アルファベット順です。 ## 例 diff --git a/docs-site/src/content/docs/ja/guides/model-routing.md b/docs-site/src/content/docs/ja/guides/model-routing.md index 1f3d2137c9..900185715a 100644 --- a/docs-site/src/content/docs/ja/guides/model-routing.md +++ b/docs-site/src/content/docs/ja/guides/model-routing.md @@ -83,7 +83,15 @@ model ID は変更しません。`openai-apikey/` は API key transport ブロックしません。 - プロバイダーの `selectedModels` が空でなければカタログ許可リストとして動作します。ライブモデル探索と 直接ルーティングはそのままに、カタログと `/v1/models` に公開するモデルだけ絞ります。 -- `modelDiscovery.newModelPolicy` の既定値は `"off"` です。既存の設定で省略した場合も同じです。最初の正常なライブ探索では、設定済みの `defaultModel` のみを表示します。一致する既定モデルがない場合は **Models** で必要なモデルを有効にしてください。保存済みの選択、個別スイッチ、短い既存の探索基準、静的カタログは保持します。未選択の既存ライブ一覧が20件以上で既定モデルが設定済みなら一度だけそのモデルに絞ります。既定モデルのない既存の探索基準は表示状態を保持し、その後の手動変更は初期化しません。新着モデルも手動で有効にするまで非表示です。明示的な `"on"` は自動公開を許可します。公開前に適用し、探索失敗時は選択を変更しません。`ocx models new-policy off` と `ocx models new-arrivals --json` を使用できます。 +- `modelDiscovery.newModelPolicy` が `"off"` の場合、最初の成功したライブ探索で基準を確立し、 + その後に追加されたモデルを `disabledModels` に入れます。これは `/v1/models`、ダッシュボード、 + クライアント設定のエクスポート、サービス起動時を含む Codex カタログ同期で公開する前に + 適用されます。手動で有効化したモデルは、その後の更新やエクスポートでも有効なままです。 + 新規インストールの既定値は `"off"`、既存のインストールは変更するまで `"on"` です。 + `ocx models new-policy off` で全体に適用し、`--provider ` で個別に上書きします。 + `ocx models new-arrivals [--json]` で追加モデルを確認できます。失敗または縮退した探索では + 基準は変わりません。`selectedModels` が空でないプロバイダーはすでに選別済みのため、 + このポリシーによる自動無効化は行いません。 - `provider.disabled: true` のプロバイダーはカタログ探索から除外されます。明示的 `provider/model` リクエストは 失敗し、`defaultModel` / `models[]` 検査でもスキップします。 - `providerContextCaps` はプロバイダーごとに Codex に表示するコンテキスト上限を指定します。 diff --git a/docs-site/src/content/docs/ja/guides/ollama-clients.md b/docs-site/src/content/docs/ja/guides/ollama-clients.md new file mode 100644 index 0000000000..fb6f55f26f --- /dev/null +++ b/docs-site/src/content/docs/ja/guides/ollama-clients.md @@ -0,0 +1,68 @@ +--- +title: Ollama 互換クライアント +description: Ollama API を話すツールを opencodex に向け、設定済みのプロバイダーモデルを使います。 +--- + +opencodex は Ollama HTTP API の一部に応答します。Ollama としか通信できないツールでも、opencodex に +設定済みのモデルを使えます。リクエストは Chat Completions 経路に変換され、選択したプロバイダーに送られます。 +opencodex はお使いのマシン上でモデルをダウンロード、保存、実行しません。 + +## クライアントの接続 + +プロキシのアドレスを Ollama ホストとして指定します。既定のローカルインストールでは次のとおりです。 + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +プロキシが API キーを要求する場合(たとえば `0.0.0.0` バインド)は、`/v1/chat/completions` と同じ方法で +送ります。例: `Authorization: Bearer `。モデル範囲付きのキーでは、許可されたモデルだけが表示・使用 +されます。これらのエンドポイントはメインリスナーでのみ提供され、認証なしのループバックリスナー、Remote Link、 +ハブ管理イングレスでは公開されません。 + +## エンドポイント + +| エンドポイント | 動作 | +| --- | --- | +| `GET /api/version` | opencodex のバージョン。 | +| `GET /api/tags` | 設定済みのプロバイダーモデルを `provider/model` 名で返します。 | +| `POST /api/show` | `{ "model": "provider/model" }` は既知の情報のみを返します。ファイルサイズ、ダイジェスト、テンプレート、ライセンスは含みません。 | +| `POST /api/chat` | `system`、`user`、`assistant`、`tool` メッセージによるチャット。 | +| `POST /api/generate` | 任意の `system` を伴う単一プロンプト。 | + +それ以外の `/api/*` パスはすべて opencodex 管理 API のままです。 + +## 対応するリクエストフィールド + +- `model`: `/api/tags` に含まれる名前。 +- `stream`: 既定値は `true`(改行区切り JSON)。JSON 応答を 1 つだけ受け取るには `false` にします。 +- `images`: ユーザーメッセージ(chat)またはリクエスト(generate)に付ける base64 の PNG、JPEG、GIF、WebP。 +- `tools`(chat のみ): 関数ツール。assistant メッセージは各呼び出しの `id` を含めてそのまま送り返します。 + `tool` の結果は `tool_call_id`、なければ `tool_name` で対応付けられます。 +- `options`: `temperature`、`top_p`、`num_predict`、`stop`。 +- `format`: `"json"` のみ。 + +各 `/api/chat` リクエストでは、すべての assistant メッセージを合わせて **ツール呼び出しは最大 1,024 件**です。 +結果がすでに返された呼び出しも含みます。上限を超えると、プロバイダーに送信される前に HTTP 400 が返されます。 +会話履歴を短くして再送してください。残すツール結果と、それに対応する assistant のツール呼び出しは必ず一緒に残します。 + +それ以外は無視されず、HTTP 400 で拒否されます。`think`、`keep_alive`、`suffix`、`raw`、`template`、 +`context`、その他の `options`、JSON スキーマ形式の `format`、画像 URL が該当します。Ollama のモデル管理および +埋め込みエンドポイントは提供されません。 + +コンボ、ルーティングポリシー、`--fast` や effort のエイリアス、呼び出し元自身の認証情報を転送するプロバイダーは +ここでは選択できません。これらのリクエストは、上流に何も送信される前に失敗します。 + +## レスポンス + +完了した応答には `done: true` と、`stop`、`tool_calls`、`length` のいずれかの `done_reason` が付きます。 +`prompt_eval_count` と `eval_count` はプロバイダーが使用量を報告した場合に現れ、所要時間のフィールドは報告されません。 +ストリームは、上流の応答が完全に終わった後に `done: true` の行をちょうど 1 回だけ送ります。 + +エラーは Ollama 形式の `{ "error": "message" }` を使い、HTTP ステータスを保ちます。レート制限と混雑による拒否では +`Retry-After` も含まれます。コンテンツフィルターや不明な理由で止まった応答は、通常の停止ではなくエラーとして返されます。 +ストリームが開始後に失敗した場合、最後の行は `error` オブジェクトになり、`done: true` の行は続きません。 + +リクエストは他のトラフィックと同様にダッシュボードのリクエストログに表示され、レスポンスヘッダー +`x-opencodex-request-id` が対応する行を示します。 diff --git a/docs-site/src/content/docs/ja/guides/providers.md b/docs-site/src/content/docs/ja/guides/providers.md index 6e06678477..1d68dbc3b9 100644 --- a/docs-site/src/content/docs/ja/guides/providers.md +++ b/docs-site/src/content/docs/ja/guides/providers.md @@ -57,7 +57,9 @@ Codex login を Pool モードで使うと、Providers の概要には任意の [`retryOn429`](/ja/reference/configuration/)(同一キーでの 429 リトライ)は API キー プロバイダー (`authMode: "key"`)のみに適用されます。OAuth・forward・ローカル プリセットは除外されます — 同じトークンを再送すべきではなく、ローカルランタイムには保存すべきリモートキーがありません。 -オプトインです: オプションが無ければ無効、オブジェクトがあれば `enabled: false` でない限り有効です。 +ドキュメントに記載された宛先固有のデフォルトを除き、オプトインです。正規の Mistral Chat は、既存のリクエスト全体の送信枠の範囲内で、粘り強いリトライポリシー(再送 6 回、フォールバック間隔 10 秒)を使います。`enabled: false` を含む明示的な `retryOn429` 設定が優先されます。Mistral プリセットは、渡されたプロンプトキャッシュキーもデフォルトで転送します。`promptCacheKey: false` で転送を無効にできます。キャッシュアフィニティは再利用の可能性を高めますが、キャッシュヒットを保証せず、トークンスループットの制限もなくしません。 + +Mistral は Studio キーと Vibe キーの両方に 1 つの API キー プロバイダーを使います。キーの種類とプランの許容量は [Mistral の API キーのドキュメント](https://docs.mistral.ai/admin/identity-access/api-keys)に記載されています。プロキシはキーからサブスクリプションのティアを推測しません。すべてのモデルで、上流が明示した `Retry-After` の期限は、同じ認証情報とモデルでの呼び出し間で共有されます。リトライ時刻のない 429 は、有効な分単位カウンターが容量の枯渇を示す場合、または拒否されたクエリの実測コストが残りトークンを超えつつ公表された全許容量には収まる場合に、控えめな 60 秒の回復待機を開始することがあります。これはローカルの回復ポリシーであり、サーバーのリセット時刻を正確に予測するものではありません。正常なトラフィックでは、次のクエリのキャッシュやコストを予測しません。待機後に回復プローブを 1 回だけ送り、成功すれば通常のトラフィックに戻ります。欠落、不正な形式、利用権ゼロ、月間枠の枯渇、全許容量超過といった根拠からは、リセットを作り出したり履歴をコンパクトしたりしません。`requestPacing: { "enabled": false }` または `retryOn429: { "respectRetryAfter": false }` で共有ペーシングを無効にします。同じキーでの再送について、Mistral のリトライ時刻が `retryOn429.maxIntervalMs` を超える場合、プロキシは早すぎる再送をせず、429 とリトライのヒントを返します。ラウンドロビンのキー選択が有効な場合、待機中のリクエストはキーのクールダウンを再確認して代替キーのペーシング容量を確保し、出力前のキー拒否はリクエストの既存の送信上限内で正常なキーに切り替えて回復できます。コンテキストウィンドウとモデルごとのコンパクション設定は独立したままです。 ## 1. ChatGPT ログイン(forward / パススルー) @@ -163,7 +165,7 @@ opt-in した上流がこのフィールドを拒否しても、opencodex はフ 認証情報に固定アカウント ID やメールがある OAuth プロバイダーはログインを複数保持できます。 Providers ページでアカウントを追加し、別アカウントをログアウトせずにアクティブアカウントだけを切り替えられます。 -アカウント識別情報がない Kimi 認証情報は通常のログインではアクティブスロットを差し替えますが、明示的な **アカウントを追加** では既存スロットを保持し、別の新しいスロットをアクティブにします。Kiro アカウントはプロファイル ARN をキーに保存されます。 +アカウント識別情報がない Kimi 認証情報は通常のログインではアクティブスロットを差し替えますが、明示的な **アカウントを追加** では既存スロットを保持し、別の新しいスロットをアクティブにします。Kiro アカウントはプロファイル ARN と、取得できる場合はサインインしたユーザーのメールアドレスを組み合わせて識別されます。同じ組織プロファイルを共有するユーザーも、それぞれ別の認証情報を保持できます。 `chatgpt` は Codex アカウントプールに別の保存場所があり、常に単一スロットのみ書き込みます。トークンは `~/.opencodex/auth.json` に保存され、 `/api/oauth/accounts` はマスク済みメタデータのみを返します。 @@ -182,6 +184,8 @@ cat accounts.json | ocx account import google-antigravity --format cockpit-tools ### Kiro 認証情報の取り込み +ダッシュボードでは **AWS IAM Identity Center** を選び、組織の AWS アクセスポータル URL と SSO リージョンを入力すると、CLI や SSH を使わずにアカウントを追加できます。ブラウザーでデバイスコードを承認し、複数の Kiro プロファイルがある場合は保存するものを選択します。以下の CLI 手順は **Kiro CLI** の選択肢に適用されます。 + Kiro のログインには Kiro CLI が必要です。Unix では `curl -fsSL https://cli.kiro.dev/install | bash`、Windows PowerShell では `irm 'https://cli.kiro.dev/install.ps1' | iex` でインストールしてから、先に `kiro-cli login` でサインインしてください。`kiro-cli` セッションがない場合、`ocx login kiro` は貼り付けたアクセストークンまたは `KIRO_ACCESS_TOKEN` 環境変数にフォールバックします。 通常の `ocx login kiro` 取り込みは CLI の SQLite データベースを読み取り専用で開き、データベース、WAL、SHM を変更しません。 @@ -206,7 +210,7 @@ Kiro のログインには Kiro CLI が必要です。Unix では `curl -fsSL ht ## 3. API キーカタログ -opencodex には組み込みプリセットが 104 個含まれています。キー方式 84、OAuth 16、ローカル 3、 +opencodex には組み込みプリセットが 107 個含まれています。キー方式 86、OAuth 17、ローカル 3、 デフォルト ChatGPT 転送プリセット 1 です。ダッシュボードの **Add provider** ピッカーはキー発行ページを開き、 入力したキーを検証した後保存します(検証はプロバイダー固有です)。主な項目は以下のとおりです: @@ -254,13 +258,13 @@ Cline IDE/CLI のみで API からは使えません。`minimax/minimax-m2.5` | Novita AI | `https://api.novita.ai/openai/v1` | | Together | `https://api.together.xyz/v1` | | Fireworks | `https://api.fireworks.ai/inference/v1` | -| Moonshot (Kimi API) · Kimi (coding) | `https://api.moonshot.ai/v1` · `https://api.kimi.com/coding/v1` | +| Moonshot (Kimi API) · Kimi (coding) | `https://api.moonshot.ai/v1` · `https://api.kimi.com/coding/v1`。`moonshot` API の既定モデルは `kimi-k3.1-pro` です。公式 API の保存済み `kimi-k2.5` 選択はこのモデルへ移行します。 | | Hugging Face | `https://router.huggingface.co/v1` | | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | | Z.AI (GLM Coding) | `https://api.z.ai/api/coding/paas/v4` | | Zhipu AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | | [BigModel Coding Plan — Responses (静的モデル一覧)](/guides/providers/#bigmodel-coding-plan-over-responses) | `https://open.bigmodel.cn/api/v1` | -| Qwen Cloud | トークンプラン(デフォルト): `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · 従量課金: `https://dashscope.aliyuncs.com/compatible-mode/v1` · またはカスタム | +| Qwen Cloud | トークンプラン(デフォルト): `https://token-plan.maas.qwencloudapi.com/compatible-mode/v1` · 従量課金: `https://dashscope.aliyuncs.com/compatible-mode/v1` · またはカスタム | | Tencent Cloud Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | | Volcengine Ark · Coding Plan · Agent Plan | `https://ark.cn-beijing.volces.com/api/v3` · `https://ark.cn-beijing.volces.com/api/coding/v3` · `https://ark.cn-beijing.volces.com/api/plan/v3` | @@ -280,12 +284,18 @@ Chat Completions モデル(および Responses 専用で Responses にルー [OpenGateway ダッシュボード](https://opengateway.ai/api-keys)でキーを作成し、 `ocx provider add opengateway` を実行するか、ダッシュボードで **OpenGateway** を選択してください。 Chat リクエストは設定済みの Bearer キーを使います。公開一覧はキーの有効性を検証しません。 +Responses では OpenGateway がネイティブのカスタムツール呼び出しの再送を拒否するため、プリセットはコードモードの `exec` など Codex のカスタムツールを送信前に関数ツールへ変換します。 +ツール結果のコンテンツ配列はテキストとして送り、画像は対応するツール結果グループの後に保持します。refusal や不透明なコンテンツなど、サポートされない結果パートは送信前に明示的なクライアント入力エラーとして拒否します。 +画像の詳細度 `original` はゲートウェイが受け付ける `high` に変換し、画像のバイトはそのまま保ちます。 +ネイティブ Responses ルートは、テキストのみの空の完了を成功として返す前に検査します。 +出力予算を使い切った場合は `max_output_tokens` を伴う `incomplete` になり、プロキシは要求された予算を増やしません。予算が残っていて安全に再送できる空の完了は、既存の送信上限の範囲内で 1 回だけ再試行することがあります。明示的な `emptyCompletionRetry: false` または `OCX_EMPTY_COMPLETION_RETRY=0` でこの再試行を無効にします。テキスト、refusal、ツールの動作、未知のストリームイベントがあると再送せず、元のストリームを保持します。この保護は他のプロバイダーやそのリトライのデフォルトを変更しません。 +再送には明示的な `store: false`、完全な入力、クライアント実行のツールのみが必要です。`web_search` などのホスト型ツールがあると、ツールイベントが観測されていなくても自動再送しません。 **OpenCode Zen**(`opencode-zen`)は [opencode.ai/auth](https://opencode.ai/auth) の API キーで `https://opencode.ai/zen/v1` を使用します。無料モデルは毎分約 15–20 リクエストの短時間レート制限に当たることがあります(コミュニティ計測。OpenCode は RPM を公表していません)。レート制限 429 に `Retry-After` がない場合、opencodex は案内と合成 `Retry-After` を追加し、有効な上流ヘッダーを優先します。同一キーの再試行は [`retryOn429`](/ja/reference/configuration/) で有効にします。 正規の `opencode-zen` プロバイダーで API キー認証と公式ルート `https://opencode.ai/zen/v1` または `https://opencode.ai/inference/v1` を使用すると、Gemini は既定の `googleMode: ai-studio` で Google ネイティブ API を自動的に使用します。Zen のモデル ID は、`-tiered` 接尾辞のない Flash ID もそのまま保持します。Claude は `googleMode` に関係なく Anthropic Messages を使用します。保存済み設定の読み込み時、これらのネイティブモデルの適格な旧 Chat/Responses オーバーライドと、適格な Responses 専用 `image_generation` ホストツール設定のみを無視します。カスタムプロバイダー、キー認証以外のルート、その他の設定は変更しません。 -**`opencode-free` のサポートは削除されました。** OpenCode の上流無料枠の制限により、すべてのモデルが `403 permission_denied` を返すためです([#7255](https://github.com/lidge-jun/opencodex/issues/7255))。既存設定の読み込み時は該当項目と依存するモデル参照をメモリ上で無効にし、プロセスごとに一度警告します。ファイルは変更しません。既定のプロバイダーだった場合、標準の OpenAI OAuth 経路を既定にします。`opencode-go`、API キー付きの `opencode-zen`、または別のプロバイダーを使用してください。[OpenCode Zen 規約](https://opencode.ai/docs/zen/)。 +**`opencode-free` のサポートは削除されました。** OpenCode の上流無料枠の制限により、すべてのモデルが `403 permission_denied` を返すためです([#7255](https://github.com/lidge-jun/opencodex/issues/7255))。既存設定の読み込み時は該当項目と依存するモデル参照をメモリ上で無効にし、プロセスごとに一度警告します。読み込み時にファイルは変更しません。次回の設定保存時に、これらの項目と参照は config.json から削除されます。保存前に元のファイルが隣の `config.json.pre-opencode-free-removal.bak` に自動保存されます。その名前が使用中なら一意の名前のコピーを作成します。バイトが同一の独立したコピーは、所有者のみがアクセスできることを検証できる場合に限り再利用し、それ以外は隣に保護された新しいコピーを作成します。既存ファイルは上書きしません。初回の読み込みが重なると、同一の保護されたコピーが複数残る場合があります。警告には復元用コピーのパスが表示されます。ダウングレード後などに、そのコピーを config.json に上書きして復元できます。コピーに失敗した場合は、すぐに config.json をコピーするよう警告されます。既定のプロバイダーだった場合、標準の OpenAI OAuth 経路を既定にします。`opencode-go`、API キー付きの `opencode-zen`、または別のプロバイダーを使用してください。[OpenCode Zen 規約](https://opencode.ai/docs/zen/)。 パッシブ読み取りではメモリ内の無効化のみを行い、コピーの作成や警告は行いません。 正常な Claude Desktop の割り当てと既定値は保持されます。ソースモデルの許可リストが空になるルールは無効になり、注入モデルが削除された場合はネイティブサブエージェント同期も無効になります。その後の設定保存では、削除済み参照を復元せず、正常な同時編集を保持します。 @@ -457,6 +467,9 @@ Sol/Terra/Luna をフォールバックリストに入れています。 | Codex ログイン(Pool または Direct) | `gpt-5.6-*` | 922,000 | | OpenAI (API キー) | `openai-apikey/gpt-5.6-*` と `*-pro` | 922,000 (max input 922,000) | | OpenRouter | `openrouter/openai/gpt-5.6-sol`、`openrouter/openai/gpt-5.6-terra`、`openrouter/openai/gpt-5.6-luna` | 922,000 | +| Codex | `gpt-6.1-terra` | 500,000 / 872,000 | +| OpenAI API | `openai-apikey/gpt-6.1-terra` | 1,050,000 (128,000 max output) | +| OpenRouter | `openrouter/openai/gpt-6.1-terra` | 1,050,000 | | Cursor | `cursor/gpt-5.6-sol`、`cursor/gpt-5.6-terra`、`cursor/gpt-5.6-luna` | 1,000,000 | ネイティブ GPT-5.6 項目は固定の上流推論段階に従います。例えば Luna には @@ -476,7 +489,7 @@ Amazon Bedrock ネイティブ API のような、これらの実装のいずれ Gateway** は URL にアカウント + ゲートウェイ ID を埋める必要があります。 Copilot は混在 wire カタログを提供します。モデル(`gpt-5.3-codex`、`gpt-5.4`、 -`gpt-5.4-mini`、`gpt-5.5`、`gpt-5.6-luna`、`gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)はエージェント +`gpt-5.4-mini`、`gpt-5.5`、`gpt-5.6-luna`、`gpt-5.6-sol`、`gpt-5.6-terra`、 `gpt-6.1-sol`、 `gpt-6.1-terra`、 `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)はエージェント 通信の `/chat/completions` を拒否するため、opencodex はこれらのモデルを組み込みデフォルトで Responses API 経由にルーティングし、他の Copilot モデルはすべて chat completions のままです。 優先順位は次のとおりです: ハード wire ピン → 明示的な diff --git a/docs-site/src/content/docs/ja/guides/remote-hub.md b/docs-site/src/content/docs/ja/guides/remote-hub.md index 2b89e9c36c..e73af96b02 100644 --- a/docs-site/src/content/docs/ja/guides/remote-hub.md +++ b/docs-site/src/content/docs/ja/guides/remote-hub.md @@ -159,7 +159,7 @@ services: hub: pull_policy: build build: - context: https://github.com/lidge-jun/opencodex.git#main + context: https://github.com/lidge-jun/opencodex.git#dev dockerfile: Dockerfile target: runtime args: diff --git a/docs-site/src/content/docs/ja/guides/remote-link.md b/docs-site/src/content/docs/ja/guides/remote-link.md index 4ae8b63419..72a8f2ab9b 100644 --- a/docs-site/src/content/docs/ja/guides/remote-link.md +++ b/docs-site/src/content/docs/ja/guides/remote-link.md @@ -10,10 +10,10 @@ description: SSH で OpenCodex の Home コンピューターと Child コンピ - Home から Child に OpenSSH キーでログインできること。 - Child から開始するリンクでは、Child から Home に OpenSSH キーでログインできる必要があります(パスワードログインには対応していません)。 - Child に OpenCodex 2.66.0 以降がインストールされていること(Child から開始するリンクでは Home にも)。 -- 両方のコンピューターが macOS または Linux であること。 +- 両方のコンピューターで macOS、Linux、Windows x64 を使用できます。Windows には OpenSSH Server と Windows PowerShell が必要です。Git Bash と curl は不要です。 - Home から Child を追加するダッシュボードは Home 上で開くか、ペアリング済みの Hub セッションを使用します。現在のコンピューターを Child にするには、オペレーターがペアリングしたダッシュボードセッションが必要です。認証情報なしのローカルセッションでは、このルーティング変更を確定できません。 -パスワード SSH と Windows は現在のフローに含まれません。リンクはどちら側からでも開始できます。次の手順のように Home から開始するか、後述の「このコンピューターを Child として接続する」のように Child から開始します。 +パスワード SSH はサポートされません。リンクは Home または Child から開始できます。Windows では検証済みの OpenSSH 接続経由で PowerShell を実行します。 ## `#remote` から Child を追加する @@ -55,7 +55,7 @@ Home のプロバイダーを使うコンピューターで次の操作を行い - **Connected** は SSH トンネルが準備でき、Child が Home のリンクを使える状態です。 - **Reconnecting** はトンネルを再試行している状態です。再試行中はリクエストが `Retry-After` 付きの `503` を一時的に返すことがあります。自分のダッシュボードから接続した Child では、リクエストはまずトンネルの復帰を最大 15 秒待ちます。 -- **Failed** は対応が必要な状態です。SSH 認証、確認済みのホストキー、転送、タイムアウトの理由を確認してください。SSH トンネルを張る側が、スリープ、障害、再起動の後も自動で再試行します。Home が追加した Child では Home が、自分のダッシュボードから接続した Child では Child が再試行します。タイムアウトや転送エラーの後は約 1 分ごと、認証エラーの後は 5 分ごとです。ホストキーが変わった場合は再試行しません。すぐに再接続するには、Home のダッシュボードで **Retry** を選ぶか、Home で `ocx link reconnect --link-id ` を実行します。OpenCodex を再起動せずに、そのリンクのトンネルだけを張り直します。 +- **Failed** は対応が必要な状態です。SSH 認証、確認済みのホストキー、転送、タイムアウトの理由を確認してください。SSH トンネルを張る側が、スリープ、障害、再起動の後も自動で再試行します。Home が追加した Child では Home が、自分のダッシュボードから接続した Child では Child が再試行します。タイムアウトや転送エラーの後は 1 分後に再試行し、失敗が続くたびに間隔を倍にして最大 5 分ごとになります。認証エラーの後は 5 分ごとです。ホストキーが変わった場合は再試行しません。すぐに再接続するには、Home のダッシュボードで **Retry** を選ぶか、Home で `ocx link reconnect --link-id ` を実行します。OpenCodex を再起動せずに、そのリンクのトンネルだけを張り直します。 リンクが失敗しても、ローカルプロバイダーへ自動的に切り替わることはありません。 @@ -85,10 +85,13 @@ ocx link issue --alias --tunnel-port [--json] ocx link status [--json] ocx link revoke --link-id [--json] ocx link reconnect --link-id [--json] +ocx link check (--link-id | --all) [--no-wait] [--json] ``` 対話型端末(TTY)でない場合、`--expect-fingerprint` は必須です。対話型端末では省略できますが、提示されたフィンガープリントを明示的に承認する必要があります。 +Home で `ocx link check (--link-id | --all)` を実行すると、Home から追加した各 Child のインストール済みバージョン、インストール種別、更新経路を読み取ります。リンクの SSH 経由で Child の `ocx update --plan` を実行し(Child ごとに 60 秒、同時に 3 台まで)、計画を計算するだけで何も変更しません。2.97.0 より古い Child は `owner-action`(`legacy-ocx`)となり、バージョンは macOS と Linux では読み取り専用の SSH 呼び出しをもう 1 回行って、Windows ではリンク経由で報告されたバージョンから取得します。Child 側から接続したリンクと `ocx-child` の Child は SSH なしで報告されます。`ocx link status --json` は各行に `child` ブロック(バージョン、バージョン差、カタログの鮮度、アクティビティ、直近の操作)を追加します。詳細と終了コードは [Child install, catalog and activity](/guides/remote-link/#child-install-catalog-and-activity)(英語)を参照してください。 + ## 関連ガイド - [Remote Hub のデプロイ](/ja/guides/remote-hub/) diff --git a/docs-site/src/content/docs/ja/guides/sub-agent-surface.md b/docs-site/src/content/docs/ja/guides/sub-agent-surface.md index c8d4e06b54..25a084a0fc 100644 --- a/docs-site/src/content/docs/ja/guides/sub-agent-surface.md +++ b/docs-site/src/content/docs/ja/guides/sub-agent-surface.md @@ -33,6 +33,42 @@ opencodex は、これを最終パスとしてライブ `/v1/models` カタロ v2 ロスターの場合、適格性には 3 つの状態があります。`"v2"` スタンプが付いているエントリー、明示的に `null` に設定されているエントリー、または `multi_agent_version` フィールドのないエントリーが適格です。純正の `"v1"` ピンは、モデルが他のコラボレーション サーフェスに属していると記載されているため、除外されます。 +## `spawn_agent` が提示するモデル + +Codex は `spawn_agent` ツールの説明に最大 5 つのモデルを列挙し、その選択は Codex 自身が行います。ピッカーに表示されるカタログ行を `priority` の昇順に並べ、先頭の 5 つを取ります。**Subagents** ページのロスター (`subagentModels`) がこのリストに影響するのは、ロスター順に最も低い priority (アカウントセレクターがない場合は `0`〜`4`) を割り当てることだけです。リストをロスターに限定するわけではありません。 + +モデルを 1〜4 個だけ指定すると、Codex は残りの枠を priority 順に次の行で埋めます。これらの行はユーザーが選んだものではなく、どのモデルが入ったかはダッシュボードにも表示されません。どの行が入るかはカタログによって決まります。 + +| カタログ | 残りの枠を埋める行 | +| --- | --- | +| Codex アカウントセレクターなし | その他のルーティング済み `provider/model` 行。すべて priority `5` を共有するため、プロバイダー名、次にモデル ID のアルファベット順に並びます。指定されていないネイティブ GPT 行の priority は `100` に指定した ID の数を足した値以上なので、その後に来ます。 | +| Codex アカウントセレクターあり | アカウント指定のネイティブ行 (`/`)。指定した行の直後に来ます。指定されていないルーティング済み行は priority `1005` に移り、その後に来ます。 | + +たとえば、アカウントセレクターがなく、ロスターが次のとおりの場合: + +```json +{ "subagentModels": ["xai/grok-4.5", "anthropic/claude-sonnet-5"] } +``` + +| 枠 | モデル | Priority | 理由 | +| ---: | --- | ---: | --- | +| 1 | `xai/grok-4.5` | `0` | ロスターの 1 番目 | +| 2 | `anthropic/claude-sonnet-5` | `1` | ロスターの 2 番目 | +| 3 | `deepseek/deepseek-v4-flash` | `5` | アルファベット順で最初の残りのルーティング済み行 | +| 4 | `google/gemini-3-pro` | `5` | 次のルーティング済み行 | +| 5 | `moonshot/kimi-k3` | `5` | 次のルーティング済み行 | +| 6+ | `zai/glm-5.2`、続いてネイティブ GPT 行 | `5`、続いて `102 + sourcePriority` | 5 つの枠外 | + +ロスターが空の場合、opencodex は何も固定せず、5 つの枠はカタログ本来の priority に従います。 + +埋められた枠も通常の提示と同じなので、メインエージェントがそのモデルを選ぶことがあります。また、このリストは許可リストではありません。メインエージェントが正確な名前を指定すれば、Codex は 5 つの枠外のカタログモデルも受け付けます。Codex が提示するリストを制御するには: + +- モデルを 5 つ指定します。ロスターが埋まっていれば、補充される枠は残りません。 +- 提示させたくないモデルは無効にするか、そのプロバイダーの `selectedModels` から外します。無効または未選択のモデルはピッカーから消えるため、枠を埋めることはありません。 +- `modelPickerOrder` は Codex が並べ替えに使う priority を変更します。ルーティング済み行だけのリストでは、列挙された未指定の行が `1000` 以上に移るため、列挙されていないルーティング済み行が先に枠を埋めます。ベアのネイティブ ID を含むリストは、指定した行も含めてピッカー全体を並べ替えます。列挙された行が先頭に来るため、列挙されていないどの行よりも先に提示枠を占めます。[Model ordering](/guides/model-ordering/) を参照してください。 + +v2 では、Codex は 5 つを取る前に `"disabled"` に固定された行を除外します。それ以外は同じ仕組みです。opencodex の v2 ガイダンスのロスター (`{{roster}}`) は、5 つの枠内にある設定済みのロスターモデルだけを挙げます。そのため、補充されたモデルは Codex のツール説明にだけ現れ、opencodex のガイダンスには現れません。Codex はセッション開始時にカタログを読むため、ロスターの変更は新しいセッションから反映されます。 + ## 委任モデルと推論負荷 ダッシュボードの **サブエージェント委任** は、次の 3 つの関連設定を制御します。 @@ -163,6 +199,10 @@ curl -X PUT http://localhost:10100/api/injection-model \ ピッカーで非表示になっているか、5 つのモデルの表示制限を超えているか、カタログから欠落しているか、v1 に固定されている可能性があります。 `"v2"`、`null`、または表面値が存在しない場合は対象となります。実際の `"v1"` ピンはそうではありません。 +### 指定していないモデルが `spawn_agent` に表示されるのはなぜですか? + +Codex は最大 5 つの提示枠を、カタログから priority 順に埋めます。指定したモデルが 5 つ未満の場合、残りの枠には次の行が入ります。上の「`spawn_agent` が提示するモデル」の節を参照してください。 + ### モードの変更は実行中のセッションに影響しますか? いいえ。モードを変更した後、新しい Codex セッションを開始します。長時間実行されているアプリ ホストで依然として古いカタログ状態が表示される場合は、`ocx sync` を実行して、その Codex サーフェスを再起動します。 diff --git a/docs-site/src/content/docs/ja/guides/web-dashboard.md b/docs-site/src/content/docs/ja/guides/web-dashboard.md index bc1e933f30..541d28d931 100644 --- a/docs-site/src/content/docs/ja/guides/web-dashboard.md +++ b/docs-site/src/content/docs/ja/guides/web-dashboard.md @@ -13,7 +13,7 @@ opencodex はプロキシが提供するローカルウェブダッシュボー ocx gui ``` -ブラウザで `http://localhost:` を開きます。ハブで管理イングレスが有効な場合は `http://127.0.0.1:<管理ポート>` を開きます。プロキシがオフなら先に自動で起動します。 +ブラウザで実行中のプロキシのアドレスを開きます。既定は `http://127.0.0.1:`、IPv6 ループバックの `::1` にバインドしている場合は `http://[::1]:` です。このリテラルアドレスにより、ローカルブラウザのペアリングに必要な設定済みオリジンが保たれます。ハブで管理イングレスが有効な場合は `http://127.0.0.1:<管理ポート>` を開きます。プロキシがオフなら先に自動で起動します。 開発中は実行中のプロキシと GUI 開発サーバーを別々に起動できます。 ```bash @@ -27,11 +27,18 @@ bun run dev:gui リモートダッシュボードでは標準のパスワードフォームが表示され、ブラウザのパスワードマネージャーで保存・自動入力できます。ダッシュボード自体はトークンをメモリ内だけに保持し、`localStorage` や `sessionStorage` には書き込みません。保存するかどうかはブラウザまたはパスワードマネージャーだけが決定します。 +**このデバイスを記憶する** は既定でオフです。直接アクセスする HTTPS ダッシュボード(またはローカルループバック)で、管理者トークンをサーバー発行の HttpOnly・SameSite=Strict デバイス Cookie と、このサイトの localStorage に保存する別のデバイス証明に交換します。HTTPS の Cookie は Secure でホスト限定です。Cookie も証明も管理者トークンではなく、どちらも単独では機能しません。同じホスト名のポート間では Cookie が共有されるため、オリジン単位の証明が記憶したデバイスをこのダッシュボードのオリジンに結び付けます。それでも専用ホスト名を推奨します。管理者トークンは localStorage や sessionStorage に保存しません。ブラウザーのストレージが使えない、または証明を保存できない場合、記憶機能は利用不可と表示されます。スタンドアロンのダッシュボードを TLS を終端するリバースプロキシ経由で使う場合、 OpenCodex には通常の HTTP リクエストとして見えるため、そのアドレスでは記憶を拒否します。サインイン画面がその旨を表示してオプションをオフにし、記憶なしのサインインは引き続き使えます。信頼された Hub の管理リスナーは例外で、引き続きデバイスを記憶できます。 + +非公開の dashboard-sessions.json は Cookie・証明・管理者認証情報・ブラウザー識別のハッシュ、サーバーのオリジンと固定30日間の有効期限を保存します。Safari ホーム画面アプリを再起動すると、有効なデバイス記録から短期セッションを再開します。記憶したセッションでは、GitHub スター、リセットクレジットの消費、プロンプト層の編集、Meta Muse サインイン、デスクトップ互換性の変更、クォータ検証などの同意操作を承認できません。これらには新しいローカルまたはペアリング済みセッションを使ってください。中継・別オリジン・リモートの平文 HTTP は記憶機能に対応しません。期限切れ、ブラウザー識別の変更、管理者トークン変更後のサーバー再起動では再ログインが必要です。 + +サイドバーやモバイル操作の **このデバイスを解除**、またはログアウトが成功すると、記録とすべての派生セッションが即座に失効し、ブラウザーの証明を削除します。ログアウトに失敗した場合は再試行のため証明を保持します。サーバーは変更公開前に記録の内容を同期しますが、クラッシュ時のディレクトリエントリの永続性はベストエフォートです。旧トークン保存キーは読み取りや移行をせず削除します。信頼できるデバイスのみで使用してください。Safari の自動入力を有効にするものではありません。 + ## クォータ概要バー 起動安全性ページを除くすべてのページ上部の 1 行の概要に、各プロバイダーの現在のクォータ使用率が表示されます。例: `OpenAI 31% | Claude 54% | xAI 12% | Google 8%`。プロバイダー画面と同じクォータレポート(`GET /api/provider-quotas`、タブが表示されている間は 60 秒ごと)を読み取り、上流への強制更新は行いません。 - 各チップには、報告されたウィンドウのうち優先されるものを表示します。週間、30 日、5 時間、プロバイダー固有のウィンドウ、前払いクレジットの順です。 +- 前払いクレジットの使用率が 90% 以上で、優先される通常のウィンドウが危険水準に達していない場合は、クレジットを表示します。通常のウィンドウも危険水準なら、そのウィンドウを優先します。 - 70% 使用でアンバー色、90% 使用で赤色になります。 - チップにカーソルを合わせるかキーボードでフォーカスすると、報告されたすべてのウィンドウとそのリセット時刻、読み取り時刻が表示されます。タッチ画面では最初のタップで表示されます。 - チップをクリック(タッチ画面では 2 回目のタップ)すると、プロバイダー画面でそのプロバイダーのアカウントタブが開き、アカウントや API キーを管理できます。 @@ -50,6 +57,7 @@ bun run dev:gui | **起動安全性** | 注入された Codex ルーティングが再起動後も機能するか、サービスと launcher shim の状態、正確な修復コマンドと共に表示します。 | | **Windows トレイ** | ユーザーのログイントレイを導入し、プロキシ開始・停止・再起動・ダッシュボード・状態をクリックで操作します。トレイは再起動サービスではありません。 | | **Codex 自動起動** | インストール済み Codex launcher shim に `ocx ensure` の実行を許可します。このトグルは shim やバックグラウンドサービスをインストールしません。 | +| **テレメトリ** | **プロキシ詳細**(`#proxy-telemetry`)で **匿名の利用統計を共有する** を切り替えたり、**JSONをプレビュー** を確認したりします。初回起動時や更新後の同意ポップアップは **続行** をクリックしたときのみ選択を保存し(`PUT /api/telemetry`)、閉じても何も記録しません。[テレメトリとプライバシー](/ja/guides/telemetry/)を参照してください。 | | **プロバイダー** | プロバイダーを追加、編集、既定に設定(有効なプロバイダーのみ)、有効化/無効化、削除し、対応する OAuth アカウントプールと API キープールを管理します。現在の既定を削除すると、残っている最初の有効なプロバイダーに切り替わります(存在する場合)。なければ削除は拒否され、現在の既定は保持されます。Claude(Anthropic)OAuth プールでは、ログイン済みの各アカウントに独自の 5 時間・週間レート制限バーが表示され(利用量は資格情報単位)、取得失敗時は直近の値を保持して一時利用不可と表示します。 | | **プロバイダー追加** | レジストリベースのプリセットからアカウントログイン、API キーサービス、ローカルサーバー、custom エンドポイントを検索します。 | | **Codex 認証** | ChatGPT/Codex プールアカウントを追加し、次回セッションアカウントを選び、5 時間 / 週間 / 30 日クォータを更新し、クォータ自動切り替えのオン/オフと 1~100% のしきい値、一時的失敗フェイルオーバーを設定します。 | @@ -62,13 +70,23 @@ bun run dev:gui 使用量、ダッシュボード、プロバイダー画面、プロバイダーカタログ、API キー画面は、読み取れる記録がなくても除外された使用履歴の警告を表示します。回数、日付、使用順位は読み取れる記録のみを反映します。履歴が不完全な場合はモデルの使用回数順の保存を拒否します。別の順序を選ぶか、履歴を修復してから再試行してください。 +### アプリ別の使用量 + +Usage は現在のアクセス範囲で、**すべてのアプリ**・**すべてのデバイス**・**30日**を初期選択します。ページを開いている間はアプリ、デバイス、期間を絞り込めますが、開き直すと初期値に戻ります。 + +すべてのアプリを選択すると、Models と Providers の後に **アプリ**の内訳が表示されます。選択したデバイスと期間について、アプリごとの総トークンに占める割合、トークン数、API 定価換算の推定費用、リクエスト数、使用量を測定できたリクエスト数を示します。Codex CLI・デスクトップ・IDE は Codex にまとめます。クライアント情報のない過去の記録は **未分類**とし、**不明**・**その他**と区別します。アプリを一つ選ぶと内訳は非表示になります。内訳を提供しないプロキシでは利用不可と表示し、空の内訳ではレポートにアプリ使用量がないと表示します。 + ### リクエストログの絞り込み -Logsではサーフェス、インターセプトされたリクエスト、プロバイダー、完全なモデル名、ステータス、時間、速度、会話IDを組み合わせて、読み込み済みログを絞り込みます。選択肢にはフォールバック試行も含まれます。モデル名は大文字小文字と前後の空白を無視しますが、部分一致ではありません。ログから消えた選択肢は全件に戻ります。 +リクエスト詳細では、一般的なプロキシエラーの文言よりも、記録されたアップストリームの失敗原因を優先して表示します。物理的なアップストリーム送信数は有効な場合に常に表示し、会計情報がない、または無効な場合は 0 ではなく **Unavailable** と表示します。**Retries** は、完全に精算され整合する単一の試行が記録されている場合に限り、最初の送信以降の追加送信回数として表示します。複数の試行、未解決・不整合な会計、または損失のある attempt 正規化では、再試行回数を推測せず非表示にします。未知の永続化された原因は、状態に基づく見出しに戻ります。**Upstream reason** には分類されたプロバイダーの状態(レート制限、クォータまたはクレジットの枯渇、コンテキストウィンドウ超過、未対応の地域、アカウント確認が必要、モデル利用不可など)を、**Failure detail** にはストールタイムアウトやバイト上限などプロキシが記述したテキストを表示します。新しい行にはプロバイダー自身のエラーテキストを保存しません。古い `usage.jsonl` ファイルには残っている場合がありますが、ダッシュボードは読み込み時にそれを破棄します。 + +Logs はアプリ別タブの代わりにすべてのアプリのリクエストをまとめ、各リクエストにアイコンのみのクライアントチップを表示します。認識されたクライアントには SVG ロゴを、不明またはその他のクライアントには中立的な疑問符アイコンを使用します。アプリ名は画面に文字として表示せず、スクリーンリーダーには引き続き提供します。クライアント情報がないことは、Codex やリクエスト失敗を意味しません。チップはプロバイダーやプロトコルとは別にクライアントアプリを示し、アプリフィルターではありません。 + +Logsではインターセプトされたリクエスト、プロバイダー、完全なモデル名、ステータス、時間、速度、会話IDを組み合わせて、読み込み済みログを絞り込みます。選択肢にはフォールバック試行も含まれます。モデル名は大文字小文字と前後の空白を無視しますが、部分一致ではありません。ログから消えた選択肢は全件に戻ります。 時間は直近15分・1時間・1日で、Logsタブでは自動更新をオフにしても30秒ごとに更新します。速度はリクエスト全体の時間あたりの毎秒出力トークン数で、15未満、15以上50未満、50以上です。速度フィルター中は測定不能な行を除外します。成功は2xx、エラーは4xx/5xxです。 -一致件数と読み込み総数を表示し、リセットで全行を復元します。一致なしと空ログを区別します。サーフェスは矢印キーとHome/Endで操作できます。読み込み範囲外の履歴は検索しません。 +一致件数と読み込み総数を表示し、リセットで全行を復元します。一致なしと空ログを区別します。読み込み範囲外の履歴は検索しません。 ### セクションへのリンク diff --git a/docs-site/src/content/docs/ja/index.mdx b/docs-site/src/content/docs/ja/index.mdx index 7c44164cea..03759a3dd0 100644 --- a/docs-site/src/content/docs/ja/index.mdx +++ b/docs-site/src/content/docs/ja/index.mdx @@ -1,10 +1,10 @@ --- -title: "opencodex — Codex を任意の LLM 上で" -description: OpenAI Codex & Claude Code 向けの汎用プロバイダープロキシ — Codex CLI、App、SDK と Claude Code で任意の LLM を使えます。 +title: "opencodex — Codex、Claude Code などをつなぐローカルゲートウェイ" +description: "AI コーディングツールとモデルをつなぐ 1 つのローカルゲートウェイ。Codex、Claude Code、Claude Desktop、Grok Build で好きなプロバイダーを使い、管理された設定でほかのツールも接続できます。" template: splash head: - tag: title - content: "opencodex — Codex を任意の LLM 上で" + content: "opencodex — Codex、Claude Code などをつなぐローカルゲートウェイ" - tag: meta attrs: property: og:locale diff --git a/docs-site/src/content/docs/ja/reference/adapters.md b/docs-site/src/content/docs/ja/reference/adapters.md index b817283250..08cd6d0548 100644 --- a/docs-site/src/content/docs/ja/reference/adapters.md +++ b/docs-site/src/content/docs/ja/reference/adapters.md @@ -111,7 +111,7 @@ HTTP リトライ ループの対象外です。 - メッセージを Anthropic content block(text、base64 image、`tool_use`、`thinking`)に変換します。 - **Extended thinking の計算:** Anthropic は `max_tokens > thinking.budget_tokens` を要求します。 アダプターは reasoning effort を budget にマッピングし(minimal 1024 … max 32000)、出力余裕を取った安全な `max_tokens` を計算します。thinking がオンのときは Anthropic が禁止する **`temperature`/`top_p` を削除**します。 -- **adaptive thinking の表示:** adaptive thinking モデル(Opus 4.7+、Sonnet 5、Fable)には `thinking.display: "summarized"` を送るため、長い思考は数分間の heartbeat ではなく reasoning delta として Chat と Responses のクライアントに届きます。reasoning の要約を隠すリクエスト(`reasoning.summary: "none"`)はプロバイダーの既定値を維持します。 +- **adaptive thinking の表示:** adaptive thinking モデル(Opus 4.7+、Sonnet 5、Fable)には `thinking.display: "summarized"` を送るため、長い思考は数分間の heartbeat ではなく reasoning delta として Chat と Responses のクライアントに届きます。reasoning の要約を隠すリクエスト(`reasoning.summary: "none"`)はプロバイダーの既定値を維持します。ただし、`api.anthropic.com` の Opus 5.5 は `display: "updates"` が既定で、`reasoning.summary` に `"concise"` または `"detailed"` を明示すると updates ベータなしで `"summarized"` を使用します。[Opus 5.5 の進捗更新](/guides/providers/#claude-opus-55-progress-updates)を参照してください。 - 常に `anthropic-version: 2023-06-01` を送ります。`content_block_delta`(`text_delta`、 `thinking_delta`、`input_json_delta`)をストリーミングします。 diff --git a/docs-site/src/content/docs/ja/reference/cli.md b/docs-site/src/content/docs/ja/reference/cli.md index c766a1cdfa..c43b436384 100644 --- a/docs-site/src/content/docs/ja/reference/cli.md +++ b/docs-site/src/content/docs/ja/reference/cli.md @@ -20,7 +20,7 @@ opencodex CLI は `ocx` です。最初のコマンド名でディスパッチ 管理コマンドは、2 番目の構成パスを維持するのではなく、記録されたランタイム ポートと ID チェックを使用して、稼働中のプロキシの管理 API をラウンドトリップします。停止したプロキシまたは到達不能なプロキシは HTTP 503 として表され、ゼロ以外の CLI 終了が生成されます。オフライン構成操作として明示的に文書化されているコマンドは、代わりに、稼働中のプロキシを使用せずに設定ファイルを検証および編集できます。 -`check` はレジストリへの問い合わせも Codex の実行も行いません。POSIX では、公開ランチャーが記録した環境候補とランタイムリゾルバーが選ぶ正規パスが一致すると `selectionAttested: true` になり、リンクされた npm-global パッケージのマニフェストで所有権を確認でき、候補バージョンが報告されている場合はそれがマニフェストのバージョンと一致するときに `managed: true` になります。永続化された候補は認証されません。Windows は候補や設定ファイルを読まずに検査を延期します。Bun やソースからの直接実行にはランチャーの証明がありません。`plan` は分離した一時 npm 設定・キャッシュ・ログで公式レジストリに問い合わせ、実行中のセッションや不完全なプロセス観測を拒否します。インストールやプロセスへのシグナル送信は行いません。[コマンドと拒否理由の詳細(英語)](/reference/cli/agents/#read-only-codex-cli-update-plan)を参照してください。 +`check` はレジストリへの問い合わせも Codex の実行も行いません。POSIX では、公開ランチャーが記録した環境候補とランタイムリゾルバーが選ぶ正規パスが一致すると `selectionAttested: true` になり、リンクされた npm-global パッケージのマニフェストで所有権を確認でき、候補バージョンが報告されている場合はそれがマニフェストのバージョンと一致するときに `managed: true` になります。永続化された候補は認証されません。Windows x64 は、証明にバインドされた絶対パスの標準 npm `codex.cmd` と保持ハンドルにバインドされた Node/npm ツールチェーン(存在する場合はプレフィックスローカル、存在しないことが確認された場合はランチャーアーキテクチャにアンカーされたキャプチャ済み PATH ペア)、検証済みのインプレフィックスプラットフォームバッキングもサポートし、リパースを拒否する保持ハンドルを使用します。他の Windows レイアウトは引き続き延期または非管理です。Windows の `managed` 結果は観測されたインストールレイアウトのみを分類し、バインドされた Node/npm はアップデーターの読み取り専用メタデータツールチェーンであって、後の `codex.cmd` 呼び出しがどのインタープリターを解決するかを保証するものではありません。Bun やソースからの直接実行にはランチャーの証明がありません。`plan` は分離した一時 npm 設定・キャッシュ・ログで公式レジストリに問い合わせ、実行中のセッションや不完全なプロセス観測を拒否します。インストールやプロセスへのシグナル送信は行いません。Windows x64 の apply には、検証済みのプライベート書き込み権限を持つ制限付き npm プレフィックスが必要で、無関係なパッケージ・shim を保持します。適用条件を満たさない観測レイアウトは `applicable: false` と `refusal: windows_apply_disabled` を返し、PATH のみの選択・OpenCodex 自動起動ラッパー・global/vendor フォールバックは引き続き延期されます。[コマンドと拒否理由の詳細(英語)](/reference/cli/agents/#read-only-codex-cli-update-plan)を参照してください。 Windows x64 インストールの観測は [`attest` コマンド](/ja/reference/cli/agents/)を参照してください。明示パスを省略すると、証明にバインドされたランチャースナップショットが特定した選択候補を観測します。更新権限やランタイム選択は証明しません。 diff --git a/docs-site/src/content/docs/ja/reference/cli/agents.md b/docs-site/src/content/docs/ja/reference/cli/agents.md index ebe43edfff..961c01c9bf 100644 --- a/docs-site/src/content/docs/ja/reference/cli/agents.md +++ b/docs-site/src/content/docs/ja/reference/cli/agents.md @@ -130,6 +130,39 @@ ocx claude desktop import [--apply] Validate and import JSON ファミリは `opus`、`fable`、`sonnet`、および `haiku` です。新しいルートは `opus` で始まります。 `none` は、そのファミリーが空の場合にのみ有効です。従来の適用フラグ `--static`、`--hybrid`、および `--discovery-only` は引き続きサポートされます。クロードコードの設定には`ocx claude config ...`を使用してください。 +### `ocx codex [codex args...]` + +キーは設定とその名前空間が他の主体による変更から保護されている場合にのみ渡します。現在の利用者と特権 OS 主体を信頼します。同じ利用者のプロセスは信頼対象です。その利用者の書き込み権限を持つ主体は、既にその利用者の OpenCodex キーファイルも読めます。検証からネイティブ起動までの同一利用者による設定置換はこの脅威モデルの対象外で、引き渡し時に設定を固定しません。 + +通常の Windows の既定 ProgramData 権限では他の利用者がディレクトリを作成できます。そのため `ProgramData\OpenAI\Codex` がなくても自動認証情報を保留します。ProgramData 配下のシステム Codex 設定フォルダーは存在し、Administrators/SYSTEM だけが書き込める必要があり、他の利用者による祖先ディレクトリの置換も防ぐ必要があります。管理者にディレクトリポリシーの確認を依頼してください。opencodex 自身は ACL を変更せず、準備用のコマンドも提供しません。 + +代わりに利用者が自分でキーを指定できます。例えば `OPENCODEX_API_AUTH_TOKEN` を環境変数としてエクスポートすると、`ocx codex` はその値を変更しません。既存のシステム設定ファイルがあれば引き続き自動認証情報を保留し、別途確認が必要です。各保留理由はキー値、キーファイルの内容やパスを含まない短い具体的な stderr 診断一行で示されます。 + +単語一つのプロンプトの前に `--` を置き、未知の Codex サブコマンド選択を防いでください。 + +設定ファイルがなくても、machine 設定パスに他の利用者が作成できない必要があります。Windows ProgramData/OpenAI/Codex の保護を確認できなければ注入を保留し、ディレクトリを作成しません。macOS は拒否のみの ACL と読み取り専用の許可を受け入れます。書き込み・追記・削除・属性・セキュリティ・所有者の変更を許可するエントリは、先行する拒否があっても拒否します。不明なタグや検査エラーも拒否します。 + +新しいサービストークンを読み込むのは、argv が下記の許可リスト内で、空でない HTTP(S)/ALL proxy や `CODEX_*`/`OPENAI_*`/`AZURE_OPENAI_*` 環境変数の上書きがなく(正規の `CODEX_HOME` は許可)、ホーム・設定・システムの名前空間が所有権検査を通過した場合だけです。設定は監査済みキーと正確な管理 loopback provider のみで、追加の資格情報利用先や設定層がない必要があります。`-c`/`--config`、`-p`/`--profile`、未知のフラグ、`resume`/`fork` など許可外の引数ではトークンを保留し、値を含まない診断を出します。明示した資格情報と元の引数は維持します。 + +正規ホームと `config.toml` は現在の利用者所有である必要があります。POSIX は group/other の書き込みを、Windows は現在の利用者・SYSTEM・Administrators 以外への DACL 書き込み許可を拒否し、所有者 SID を確認します。祖先パスの置換権限も確認し、macOS は強制 Codex 設定 preference がないことも要求します。同じ利用者や管理者の悪意あるプロセスを隔離するものではありません。 + +| Allowlist | Flags | +| --- | --- | +| Switches | `--no-daemon`, `--json`, `--ephemeral`, `--skip-git-repo-check`, `--no-alt-screen`, `--full-auto`, `--dangerously-bypass-approvals-and-sandbox`, `--search` | +| One value | `--model`/`-m`, `--sandbox`/`-s`, `--ask-for-approval`/`-a`, `--image`/`-i` | + + + +自動認証情報の読み込みでは `CODEX_HOME` の `~` と空白をリテラルなパスとして解釈して検証し、同じ正規絶対パスを子プロセスに渡します。ホームを読めない場合は読み込みません。大文字小文字を問わず、空でない `HTTP_PROXY`、`HTTPS_PROXY`、`ALL_PROXY` があれば `NO_PROXY` に関係なく自動読み込みを省略します。拒否した起動とユーザーがエクスポートした認証情報は変更しません。新しいトークンを渡す場合、既存の除外項目を保持し、子の `NO_PROXY` と `no_proxy` に `127.0.0.1` と `::1` を追加します。`features.respect_system_proxy` の有効化や `--enable`/`--disable` の転送では自動読み込みを省略します。 + +元の引数で Codex を起動する前にプロキシの起動を試みます。ルーティングは Codex 設定が所有し、ランチャーは書き換えません。ネイティブと外部ゲートウェイでは起動を省略します。不明なルートでは警告して起動を試み、失敗しても警告後に続行します。ヘルプ、バージョン、`login`、`doctor`、`help` などの内部コマンドは起動と自動トークン読み込みを省略します。 + +選択した provider の全転送設定が、このインストールのループバックリスナーまたは保存されたローカルクライアント接続向けの管理ブロックと一致する場合だけ、不足する `OPENCODEX_API_AUTH_TOKEN` をこのインストールの `service-api-token` から読みます。名前や注入コメントだけでは許可しません。不明・リモートの接続先、既定 profile、プロジェクト設定、`OPENAI_BASE_URL`、転送した `-c`/`--config`、`-p`/`--profile`、`-C`/`--cd`、`--remote` は自動読み込みを省略します。ユーザーがエクスポートした認証情報と引数を保持し、トークンファイルの上書きと管理トークンの衝突を拒否します。 + +一致を確認した(`matched`)autostart wrapper だけが背後の Codex を直接実行します。検査例外を含む不明な状態では検証済みのバイパスが必要で、管理対象の Windows CMD wrapper は生成テンプレート全体と一致した場合だけ `OCX_SHIM_BYPASS=1` で実行します。通常の npm ランチャーは利用できます。検証不能または古い wrapper は終了コード 1 で拒否し、Codex は開始しません。`ocx codex-shim install` で更新してください。この起動は shim を修復せず、内容検査は Windows backing ファイルの出所や並行したパス置換を保証しません。 + +ランチャーのヘルプは `ocx help codex`、Codex のヘルプは `ocx codex --help` です。後で通常の `codex` を起動する動作は変わりません。 + ### `ocx opencode [opencode args...]` プロキシが実行されていることを確認し、OpenCode のインライン ランタイム層 (`OPENCODE_CONFIG_CONTENT`) で生成された `provider.opencodex` および `providers.opencodex` ブロックを使用してオープンコードを起動します。既存のインライン設定は保持され、今回の起動ではこの 2 つのキーのみが置き換えられます。グローバルまたはプロジェクトの `opencode.json` ファイルは、既存の上書きについて警告するために読み取られることがありますが、ディスク上のファイルは変更されません。ルーティングされたモデルは `opencodex//` として表示されます。後でプレーン `opencode` を起動すると、以前とまったく同じように動作します。 @@ -218,7 +251,7 @@ ocx system settings --stream-mode eager-relay ocx system codex-cli-update check --json ``` -`check` はレジストリへの問い合わせも Codex の実行も行いません。POSIX では、公開ランチャーが記録した環境候補とランタイムリゾルバーが選ぶ正規パスが一致すると `selectionAttested: true` になり、リンクされた npm-global パッケージのマニフェストで所有権を確認でき、候補バージョンが報告されている場合はそれがマニフェストのバージョンと一致するときに `managed: true` になります。永続化された候補は認証されません。Windows は候補や設定ファイルを読まずに検査を延期します。Bun やソースからの直接実行にはランチャーの証明がありません。`plan` は分離した一時 npm 設定・キャッシュ・ログで公式レジストリに問い合わせ、実行中のセッションや不完全なプロセス観測を拒否します。インストールやプロセスへのシグナル送信は行いません。[コマンドと拒否理由の詳細(英語)](/reference/cli/agents/#read-only-codex-cli-update-plan)を参照してください。 +`check` はレジストリへの問い合わせも Codex の実行も行いません。POSIX では、公開ランチャーが記録した環境候補とランタイムリゾルバーが選ぶ正規パスが一致すると `selectionAttested: true` になり、リンクされた npm-global パッケージのマニフェストで所有権を確認でき、候補バージョンが報告されている場合はそれがマニフェストのバージョンと一致するときに `managed: true` になります。永続化された候補は認証されません。Windows x64 は、証明にバインドされた絶対パスの標準 npm `codex.cmd` と保持ハンドルにバインドされた Node/npm ツールチェーン(存在する場合はプレフィックスローカル、存在しないことが確認された場合はランチャーアーキテクチャにアンカーされたキャプチャ済み PATH ペア)、検証済みのインプレフィックスプラットフォームバッキングもサポートし、リパースを拒否する保持ハンドルを使用します。他の Windows レイアウトは引き続き延期または非管理です。Windows の `managed` 結果は観測されたインストールレイアウトのみを分類し、バインドされた Node/npm はアップデーターの読み取り専用メタデータツールチェーンであって、後の `codex.cmd` 呼び出しがどのインタープリターを解決するかを保証するものではありません。Bun やソースからの直接実行にはランチャーの証明がありません。`plan` は分離した一時 npm 設定・キャッシュ・ログで公式レジストリに問い合わせ、実行中のセッションや不完全なプロセス観測を拒否します。インストールやプロセスへのシグナル送信は行いません。Windows x64 の apply には、検証済みのプライベート書き込み権限を持つ制限付き npm プレフィックスが必要で、無関係なパッケージ・shim を保持します。適用条件を満たさない観測レイアウトは `applicable: false` と `refusal: windows_apply_disabled` を返し、PATH のみの選択・OpenCodex 自動起動ラッパー・global/vendor フォールバックは引き続き延期されます。[コマンドと拒否理由の詳細(英語)](/reference/cli/agents/#read-only-codex-cli-update-plan)を参照してください。 Windows で `CODEX_CLI_PATH=codex` のような単純なコマンド名、リモートパス、デバイスパスが候補としてキャプチャされた場合は、`candidate_path_unavailable` を報告します。候補は取得されていますが、そのパスはこの検査の対象になりません。 @@ -252,3 +285,19 @@ This takes effect on the **next routed `ocx claude` launch**, injecting `CLAUDE_ Claude Code **2.1.257 or newer** is required for FORCE. Plugin and built-in agents (including Explore/Plan) and per-call model arguments are overridden. Forks and subagent skills with `model: inherit` keep the main conversation model. The main loop and Haiku/small-fast sidecars are unaffected. Existing roster files remain available. The dashboard warns about old or unknown CLI versions, unavailable targets, and either variable already present in `settings.json` → `env` (which overrides launch env). Detection is read-only and server-local: it cannot inspect another launch shell, another machine, or project-local settings. An unknown result is not proof of force support. + +## Hermes / Command Code: model names + +Hermes and Command Code support `--model-names alias|routed` (API: `modelNames`). +The default is `routed`, independent of `preferModelAliasIds`. A connection +stores its mode; later Apply without the option preserves it. Alias mode uses +only provider-qualified aliases that the router proves equivalent; missing, +unsafe or colliding aliases fall back to routed keys. Combos keep their keys. +Removed/renamed aliases migrate on the next successful managed refresh, with +foreign-edit refusal. Named Hermes profiles need explicit Apply. + +`ocx export --client hermes --model-names alias --json` previews a current +already loaded catalog without writing client files or managed state; a cold or +stale catalog returns unavailable. Explicit `--out` writes an export artifact. +See the [English integration guide](/guides/integrations/#opt-in-alias-model-names) +for the canonical workflow. diff --git a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md index df2d6de16f..5cf94f691a 100644 --- a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md @@ -28,7 +28,19 @@ ocx start --socks5-off ### `ocx stop` -実行中のプロキシを (PID によって) 停止し、PID ファイルを削除して、ネイティブ Codex を復元します。マネージド バックグラウンド サービスがインストールされている場合、`ocx stop` はそれを最初に停止するため、プロキシを再起動できません。Web ダッシュボードの **停止** ボタンは同じ処理 (`POST /api/stop`) を実行しますが、Windows タスク スケジューラだけは例外です。タスク終了後もラッパーがプロキシを再起動しうるため、ダッシュボードは `respawnable_service` で拒否し、何も変更せずに `ocx stop` の実行を促します。 +監督プロセスのない Link Child は終了シグナル時、各書き込みで接続を再確認し、リスナーを閉じる前に Codex と管理対象 Grok を復元します。サービス・Desktop、sibling、再起動の引き継ぎ、親 stop 記録がある場合は設定を保持します。終了中の再起動は `409 runtime_stopping` です。強制終了はシグナル処理を省略する場合があり、親 `ocx stop` の復元も必要です。 + +実行中のプロキシを (PID によって) 停止し、PID ファイルを削除します。スタンドアロンの所有者ではネイティブ Codex を復元します。マネージド バックグラウンド サービスがインストールされている場合、`ocx stop` はそれを最初に停止するため、プロキシを再起動できません。Web ダッシュボードのサイドバーにあるプロキシ レバーを下まで引く停止操作は同じ処理 (`POST /api/stop`) を実行しますが、Windows タスク スケジューラだけは例外です。タスク終了後もラッパーがプロキシを再起動しうるため、ダッシュボードは `respawnable_service` で拒否し、何も変更せずに `ocx stop` の実行を促します。 + +接続済みの hub クライアントでは、`ocx stop`(成功した API 停止を含む)は接続が所有する Codex のルーティング、モデルカタログ、Grok 設定を保持します。`ocx start` はルーティングを再注入せず、その設定で再び処理します。Codex を自身のアカウントへ戻すには `ocx disconnect`、既にネイティブルーティングへ戻した後の再適用には `ocx sync --restart-codex` を使います。 + +Remote Link Child を明示的に停止すると、共有設定の復元が成功した場合、ネイティブ Codex のルーティング、カタログ、バックアップ済みの再開履歴メタデータを復元し、管理対象の Grok 設定を削除します。保存済みの Home 接続は保持され、`ocx disconnect` で削除できます。Codex から Home を再び使うには、`ocx start`(サービス導入済みなら `ocx service start`)の後に `ocx sync --restart-codex` を実行してください。起動だけではルーティングは再適用されず、sync は Grok ブロックを再作成しません。 + +サービス停止前に接続の所有権を確認できない場合、停止 API は HTTP 409 と `sharedTeardown: "refused"` を返し、プロキシとサービスマネージャーを稼働させたままにします。接続または切断の処理が完了してから再試行してください。 + +接続済みクライアントの停止では、保護されたローカルのランタイム記録とリスナーの証明を照合します。クライアント用リスナーと通常プロキシの両方にこの確認が必要で、通常プロキシでは設定の保持機能も認証付きの読み取りで確認します。古いランタイムや確認できないランタイムは、サービスやプロセスを停止する前に拒否されます。監視元からランタイムを更新・再起動して再試行してください。 + +既に停止済みのクライアントでは、サービス管理側が非アクティブで、既知のローカル接続先にランタイムが存在しないことを確認してから、通常の未実行結果を返します。 ### `ocx restart` @@ -69,6 +81,10 @@ ocx eject back すべての復元手順が成功した場合にのみ、サービスとプロキシを停止し、サービスと Codex シムを削除し、ネイティブ Codex を復元してから、opencodex ローカル設定を削除します。 `remove` は `uninstall` の別名です。設定のクリーンアップには、新規インストールによって作成された所有権メタデータが必要です。従来のディレクトリまたは共有ディレクトリはそのまま残ります。 +`ocx uninstall` を root または管理者として昇格した Windows プロンプトで実行すると、まず他のアカウントが設定ディレクトリ、その上位ディレクトリ、その中のどのディレクトリも変更できないこと、そして設定ディレクトリ内のリンクがその外を指していないこと (Windows ではリンクがまったくないこと) を確認します。どちらかを満たさない場合は、何も変更する前に停止し、理由を表示します。設定ディレクトリを所有するアカウントで `sudo` や管理者権限なしに `ocx uninstall` を実行するか、それらのディレクトリをそのアカウントだけに制限してそのようなリンクを削除してから、もう一度実行してください。昇格しているかどうかを判別できない Windows ARM64 でも同じ確認を行います。確認を完了できない場合は、opencodex を停止してから設定ディレクトリを手動で削除してください。 + +設定ディレクトリ内で親ディレクトリがリンク (シンボリックリンクまたはジャンクション) になっている記録済みの項目はそのまま残され、残ったパスとして表示され、実行は部分的なアンインストールとして終了します。そのリンクを実際のディレクトリに置き換えるか削除してから、`ocx uninstall` をもう一度実行すると完了します。 + ## ステータスと健康状態 ### `ocx status [--json]` @@ -137,7 +153,7 @@ ocx status --json 認証不要の `GET /readyz` エンドポイントで同期後の準備状態を確認します。準備完了時は `200`、 `pending` または終端状態の `failed` では `Retry-After: 1` とともに `503` を返します。HTTP の -サニタイズ済み識別フィールドは `{service, version, uptime, pid, port, status, protocol, minimumClientProtocol, managementUrl}` です。`protocol` は hub の現在の remote protocol、`minimumClientProtocol` は互換性のある最小 client protocol、`managementUrl` は browser から見える canonical management origin です。`/readyz` がない +サニタイズ済み識別フィールドは `{service, version, uptime, pid, port, status, protocol, minimumClientProtocol, managementUrl, features}` です。`protocol` は hub の現在の remote protocol、`minimumClientProtocol` は互換性のある最小 client protocol、`managementUrl` は browser から見える canonical management origin です。`/readyz` がない 旧プロキシは `unreachable` として fail-closed し、`/healthz` は readiness ではなく別の liveness 確認です。 デフォルトでは 1 回だけ probe します。`--wait` は準備完了または timeout まで polling しますが、 終端 `failed` を確認すると即座に終了します。デフォルト timeout は 45 秒で、`--timeout ` には @@ -154,7 +170,13 @@ ocx status --json ## カタログの同期 -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +Remote Link の Home では、最新のカタログが正常にコミットされた後、`ocx sync` は対象となるリンク済み Child にも同期を伝播します。`--local-only` はこの伝播を無効にします。`--json` は Home の結果と各 Child の状態を含む単一の `ocx.sync.fanout/1` 文書を出力し、スキップされた Child の理由も示します。Home 自体の終了コードが 0 以外の場合は、そのコードを変更せずに返します。Home が成功した場合、接続された Child の同期スキップ、失敗、タイムアウト、またはリンクストアの読み取り不能は終了コード 6 となります。クライアント主導リンクや `--local-only` などの意図的なスキップは従来どおりです。スキップされた接続済み Child には対処方法を示す `hint` が付きます。リンクストアを読み取れない場合、テキスト表示ではパスを含まないエラーを出します。コード 7 は更新処理中のために予約されています。JSON モードで Home の同期が例外を送出した場合も、stdout は単一の結果文書を保ち、stderr に無害化された診断を出力します。 + +伝播は Child の Codex アプリや app-server の再起動を要求しません。必要な場合は GOAT を使うか、フル `ocx` Child では `ocx sync --restart-codex` を実行してください(軽量 `ocx-child` Child では Codex デスクトップと `app-server` を別途再起動してください)。ただし、Child の固定先同期は、変更された Home 設定を適用した後、自身の OpenCodex クライアントランタイムを再起動することがあります。Home がタイムアウトしてローカルの SSH プロセスを停止しても、すでに開始されたリモート同期は Child 上で続くことがあります。 + +> **Remote Link Child:** フル `ocx` Child では `ocx sync` が Home の Codex 設定も適用し、クライアントランタイムがその適用より前に起動していた場合は再起動フラグなしでも再起動します。再起動に失敗しても以前のランタイムは動作し続け、コマンドは 0 以外で終了します。軽量 `ocx-child` ホストでは `ocx-child sync` が未起動時に `ocx-child serve` を起動し、`runtimeStartedAt < lastApplyAt` のときにローテーションして非 `stale` 同期時にベストエフォートで parity を報告します(ローテーション失敗時は旧リレー停止後に 0 以外で終了するため再実行で復旧し、Codex デスクトップや `app-server` の再起動は別途行ってください)。Child の `ocx status --json`(または `ocx-child status --json`)と Home の `ocx link status --json` の関連フィールドは [Remote Link apply parity](/reference/cli/lifecycle/#remote-link-apply-parity)(英語)を参照してください。 Home では `ocx link check (--link-id | --all)` が SSH 経由の `ocx update --plan`(Child ごとに 60 秒、インストールは変更しません)で Home から追加した各 Child のインストール済みバージョンと更新経路を読み取り、`ocx link status --json` は各行に `child` ブロックを追加します。詳しくは [Child install, catalog and activity](/guides/remote-link/#child-install-catalog-and-activity)(英語)を参照してください。 再起動フラグを明示した場合、カタログとキャッシュのバイト列が変わらなくても、`config.toml` の変更が正常にコミットされれば再起動します。設定だけを扱う操作が変更なし、拒否、事前検証、ロールバックとなった場合は再起動しません。再起動フラグがなければ、sync が Codex を自動的に再起動することはありません。 @@ -168,6 +190,8 @@ ocx status --json コマンドを Codex アプリ内から実行すると、再起動は切り離されたヘルパーに引き渡され、このセッションはアプリとともに終了します。 +**接続先を固定した同期。** `ocx sync --expect-link `(Remote Link Child)と `ocx sync --expect-hub-key `(hub クライアント)は、このマシンがまだそのリンク、またはそのキーで接続している場合にのみ同期します。そうでなければ何も変更せず、ローカルのプロバイダーも同期せず、終了コード 5 で終了し、stderr の最後の行は `{"phase":"child_link_mismatch"|"hub_client_mismatch","reason":...}` になります。不正な形式または重複したフラグは終了コード 2 で終了します。詳細は[英語版リファレンス](/reference/cli/lifecycle/#sync-only-from-the-expected-home---expect-link-and---expect-hub-key)を参照してください。 + ### `ocx sync-cache [--restart-codex] [--restart-app-server-only]` Codex のローカル モデル ピッカー キャッシュを無効にし、アクティブな opencodex カタログから再構築されるようにします。 `ocx sync` と同じ、古い `app-server` 警告とオプションの再起動フラグが適用されます。 @@ -301,7 +325,7 @@ Windows ステータス トレイ アイコンをインストールして制御 ### `ocx gui` -`http://localhost:` で [ウェブダッシュボード](/guides/web-dashboard/) を開き、プロキシが実行されていない場合は自動起動します。ハブで管理イングレスが有効な場合は `http://127.0.0.1:<管理ポート>` を開きます。 +`http://127.0.0.1:` で [ウェブダッシュボード](/guides/web-dashboard/) を開き、プロキシが実行されていない場合は自動起動します。ハブで管理イングレスが有効な場合は `http://127.0.0.1:<管理ポート>` を開きます。 ## 更新 diff --git a/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md b/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md index f920a33c45..5ba526d7f2 100644 --- a/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md @@ -24,6 +24,7 @@ description: プロバイダー構成、資格情報、クォータ、および | `quota` | `--refresh`、`--json` |プロバイダー クォータ レポートを読み取ります。 | | `presets` | `--json` |ダッシュボードプロバイダーのプリセットを一覧表示します。 | | `account-mode` | `pool`、`direct`、`--json` |プールされた Codex アカウント ルーティングまたは直接の Codex アカウント ルーティングを選択します。 | +| `import-cc-switch` | `--source `、`--provider `、`--apply`、`--restore`、`--allow-private-network`、`--json` | CC-Switch の SQLite(`cc-switch.db`)または JSON ファイルからキーなしのプロバイダー項目をプレビュー・選択適用・復元します。 | 既定の `add`、`remove`、`set-default` はローカル設定を変更します。稼働中のプロキシを変更するには `--live`、ライブ削除にはさらに `--yes` が必要です。`--sync --json` も保存後に同期を試み、失敗時は保存を保持して非ゼロ終了と `needsSync: true` を返します。`--live` と `--sync` は併用できません。pacing と snapshot/apply の手順は[英語版](/reference/cli/providers-accounts/#snapshot-edit-and-apply-with-a-baseline)を参照してください。 @@ -57,6 +58,27 @@ ocx models live --provider ark --json 秘密にあたる値は `--api-key` か OAuth ログインを使ってください。 ::: +### キーなしの CC-Switch プロバイダーインポート + +```bash +ocx provider import-cc-switch --source ~/.cc-switch/cc-switch.db +ocx stop +ocx provider import-cc-switch --source ~/.cc-switch/cc-switch.db --provider my-provider --apply +# 別のターミナルでプロキシを起動(または ocx ensure を実行)してからキーを登録: +ocx start +printf '%s\n' "$API_KEY" | ocx account add-key my-provider + +# ロールバック用の別経路(先にプロキシを停止;未編集のキーなし項目のみ削除): +ocx stop +ocx provider import-cc-switch --restore +``` + +`ocx provider import-cc-switch` は通常の CC-Switch SQLite データベースまたはレガシー JSON ファイルから、非秘密メタデータフィールドの明示的な許可リスト(プロバイダー ID、アプリ種別、ベース URL、アダプター、既定モデル)の値**のみ**を射影します。入力を走査するためソースと埋め込み設定のバイト列を一時的に読み取りますが、秘密フィールド・自由記述の表示名・TOML コメントはバイト単位でスキップされ、文字列へのデコード・書き込み・ログ出力は一切行われず、一時バイトバッファは `finally` でゼロ消去されます。ベース URL パスの厳格な規則(`http(s)://host[:port]` に空パスまたは `/v1`・`/api/v1`・`/compatible-mode/v1` などの小文字 `[a-z0-9._-]` による 1〜4 個の API パスセグメント)と識別子/モデルの構文検査は多層防御として機能し、不適合な値をエコーせずに拒否します。ソースファイルは `O_NOFOLLOW | O_NONBLOCK` の記述子検証付きで一度だけ開かれ、SQLite は一時ファイルを作らずメモリ上で読み取り専用展開されます。複数ハードリンク(`nlink > 1`)を持つ SQLite ファイルは別名パスによるサイドカー検査回避を防ぐため拒否され、隣接する `-wal` または `-journal` ファイルが空でない場合は CC-Switch を終了(またはデータベースをチェックポイント)して再試行するよう求めて拒否します。信頼できるローカルの CC-Switch ソースのみを使用し、出力されたすべての ID・モデル・`baseUrl` を確認してから資格情報を登録してください: + +- **プレビュー(既定):** `--source ` が必要で、何も書き込まず、検出・対象・競合・無効の件数を報告します。 +- **適用(`--apply`):** `--source ` とプロキシの停止(`ocx stop`)が必要で、Remote Link Child では拒否されます。`--provider ` を繰り返して対象を絞り込むか、ループバックやプライベートネットワークのベース URL には `--allow-private-network` を指定します。事前のプレビューなしでも、`--apply` はキーなしのプロバイダー項目とロールバックジャーナル `$OPENCODEX_HOME/cc-switch-provider-import-journal.json` を書き込む前にすべてのプロバイダー ID・既定モデル・接続先 URL を出力します(テキストモードでは `stdout`、`--json` モードでは `stderr`)。アクティブなジャーナルが存在する間、2 回目の `--apply` は拒否されます。出力内容を確認したらプロキシを起動(別ターミナルで `ocx start` または `ocx ensure`)し、`printf '%s\n' "$API_KEY" | ocx account add-key `(パイプ標準入力)または `ocx login ` で資格情報を追加します。 +- **復元(`--restore`):** 資格情報登録の続きではなく独立したロールバック経路であり、プロキシの停止(`ocx stop`)が必要で、Remote Link Child では拒否され、`--source`・`--provider`・`--allow-private-network` は受け付けません。`auth.json` をバイト単位で読み取り専用検査(読み取り不能または不正形式時はフェイルクローズ)し、インポート時のキーなし状態と一致したままで、かつ `defaultProvider` に選択されておらず、ルーティング・コンボ(combos)・フォールバックポリシー(fallback policy)・OAuth アカウント・API キーのいずれからも参照されていないプロバイダーのみをアクティブなジャーナルから削除します。 + ## 認証 ### `ocx login ` @@ -81,7 +103,7 @@ ocx login anthropic 実行中のプロキシを介してプロバイダー アカウントと API キー プールを一覧表示し、切り替えます。出荷されたヘルプ画面は次のとおりです。 ```text -Usage: ocx account ... +Usage: ocx account ... list [provider] Codex account pool, OAuth accounts and API keys (identifiers shown masked as the API returns them). history openai [--limit <1-200>] Recent routing decisions for one Codex pool account. @@ -95,6 +117,7 @@ pause Hold an account out of automatic selection. resume Return a paused account to automatic selection. pause-exhausted Pause every account whose quota is spent. clear-cooldown Drop a cooldown the proxy set after an upstream failure. +reset-affinity [--json] Confirm all session bindings are cleared, even with no accounts; selection and pause state stay unchanged. Run on the Home; a Remote Link Child names the Home and sends no request. strategy [] Pool placement strategy; omit the value to read it. sticky [<1-100>] Requests a bound thread keeps on one account; omit the value to read it. priority [first|earlier|normal|later|last|-100..100|reset] Selection order; omit the value to read it. @@ -109,7 +132,7 @@ main Manage the Codex App logi Codex pool selection applies to the next request after clearing existing affinity; in-flight requests keep their captured account. ``` -サブコマンドはプロキシが実行されている必要があり、記録されたランタイムポートを自動解決します。ただし `import-orca` は例外で、プレビューはローカルのみ、`import-orca --apply` はプロキシの停止が必要です。操作が成功した場合は 0 で終了します。無効な使用法、不明なプロバイダーまたはアカウント/キー ID、到達不能なプロキシ、または API エラーが発生した場合は 1 で終了します。資格情報フィールドは、管理 API が返したとおりに表示されます (マスキングを含む)。生の API キーと OAuth トークンは決して返されません。表示の利便性は、ダッシュボードと同様にクライアント側で合成されます。`main` は、`openai` アカウント プール内の Codex アプリ ログインの CLI エイリアスであり、電子メールのない OAuth アカウントは `Account N` として表示され、プラン/ラベル列はプラン、マスクされた電子メール、ラベル、およびマスクされたキーにわたってフォールバックされます。 +サブコマンドはプロキシが実行されている必要があり、記録されたランタイムポートを自動解決します。ただし `import-orca` は例外で、プレビューはローカルのみ、`import-orca --apply` はプロキシの停止が必要です。操作が成功した場合は 0 で終了します。無効な使用法、不明なプロバイダーまたはアカウント/キー ID、到達不能なプロキシ、または API エラーが発生した場合は通常 1 で終了します。ただし `reset-affinity` は HTTP 404 で終了コード 4、HTTP 409 で終了コード 5 を返し、その他の API エラーや未確認の結果では 1 を返します。資格情報フィールドは、管理 API が返したとおりに表示されます (マスキングを含む)。生の API キーと OAuth トークンは決して返されません。表示の利便性は、ダッシュボードと同様にクライアント側で合成されます。`main` は、`openai` アカウント プール内の Codex アプリ ログインの CLI エイリアスであり、電子メールのない OAuth アカウントは `Account N` として表示され、プラン/ラベル列はプラン、マスクされた電子メール、ラベル、およびマスクされたキーにわたってフォールバックされます。 `--json` アカウント行では、次の一般的な形状が使用されます (オプションのフィールドが使用できない場合は省略されます)。 @@ -131,6 +154,14 @@ Codex pool selection applies to the next request after clearing existing affinit ### `ocx account list [provider] [--json] [--all] [--quota [--refresh]]` +保存済みの ChatGPT プールアカウントは、ネイティブ Codex ホームがないホストでも、 +ダッシュボードやアカウント更新時を含めて一覧表示できます。一覧表示によって Codex ホームが +作成されたり、ネイティブのメインアカウントからサインアウトしたりすることはありません。 +Codex クライアント連携を無効にしても、既存のネイティブログインのクォータ観測は無効になりません。 +明示的に指定した `CODEX_HOME` のパスが無効な場合は、引き続き設定エラーを返します。 +`OPENCODEX_HOME` のストレージが安全でない場合は、ネイティブ Codex ホームがなくてもエラーを返します。 +既定の Codex ホームのパス解決では、ファイル、リンク先が存在しないシンボリックリンク、辿れない親ディレクトリもエラーになります。 + プロバイダーを使用しない場合、Codex プール、OAuth アカウント、および設定された API キー プールが一覧表示されます。 `--all` が存在しない限り、空のプロバイダーはスキップされます。プロバイダーを使用すると、その資格情報ファミリーのみがリストされます。人間の出力では `PROVIDER TYPE ID PLAN/LABEL PRIORITY STATUS` を使用します。手動で選択した Codex 行には `selected` というマークが付けられます。利用可能な Kiro アカウントが 2 つ以上保存されている場合、既定では 429 を受けると別のアカウントへ自動的に切り替え、既知の残り利用枠が最も多いアカウントを優先します。この切り替えはアカウントの存在によって有効になり、無効にはできません。`oauthAccountFailover.enabled: false` が断るのは 429 復旧ではなく、送信前にアカウントを選ぶ動作だけです。`ocx account login kiro` はアカウントを 1 件ずつプールへ追加します。結果が空であっても成功です。 `--json` は次を返します: ```text @@ -150,7 +181,7 @@ Codex pool selection applies to the next request after clearing existing affinit `auto` は手動の選択を解除し、プールが自身の戦略で再び配置するようにします — ただし id が `auto` の Codex アカウントが存在する場合は完全一致の id が優先され、`ocx account clear ` が常に自動選択を復元します。Codex アカウントは id の代わりに `ocx account alias` で付けたエイリアスでも指定でき、`priority`、`pause`、`resume`、`clear-cooldown`、`remove`、`alias` でも同様です。Codex アカウントでは `auto`、`main`、`__main__` は大文字・小文字を区別せず予約語として扱われるため、エイリアスとして設定できません。OAuth アカウントと API キーの表示名には従来のルールが適用されます。 既存の Codex アカウント、OAuth アカウント、または API key を選びます。`openai` で `main` は Codex App ログインを -選択します。Codex Pool の選択は process-local affinity を消去し、既存の表示タスクを含む次のリクエストから適用されます。プロキシ再起動や affinity eviction 後もタスクは未紐付けになり得ますが、処理中のリクエストは取得済みアカウントを維持します。この選択は Pool routing のみを制御し、Direct mode は caller-owned/native main credential を使い続けます。使用量ベースのプロアクティブ切り替え、401/403 再認証、429/retry-after cooldown、除外、出力前 429/402 の障害回復により、後で別の適格 Pool アカウントが選ばれる場合があります。これらの回復経路は使用量ベース切り替えが off でも有効です。アカウント変更後も OpenCodex は会話コンテキストを再生しますが、provider prompt cache は再ウォームアップが必要な場合があります。 +選択します。Codex Pool の選択は affinity を消去し、既存の表示タスクを含む次のリクエストから適用されます。セッションIDを持つリクエスト(通常の Codex CLI・App のターンやサブエージェントを含む)と、直近の親に紐付くセッションなしリクエストの紐付けは、シャットダウン時の最終的な affinity 保存が成功した場合、プロキシの正常な再起動後も最大24時間の非活動期間まで保持されることがあります。より深いセッションなしの連鎖と Codex App のメインログインへの紐付けはメモリ内にのみ残り、再起動後に再割り当てされます。eviction、アカウント削除、再ログイン、クラッシュ、affinity リセットではタスクが未紐付けになり得ますが、処理中のリクエストは取得済みアカウントを維持します。この選択は Pool routing のみを制御し、Direct mode は caller-owned/native main credential を使い続けます。使用量ベースのプロアクティブ切り替え、401/403 再認証、429/retry-after cooldown、除外、出力前 429/402 の障害回復により、後で別の適格 Pool アカウントが選ばれる場合があります。これらの回復経路は使用量ベース切り替えが off でも有効です。アカウント変更後も OpenCodex は会話コンテキストを再生しますが、provider prompt cache は再ウォームアップが必要な場合があります。 不明なプロバイダーや id は終了コード 1 です。`--json` は次を返します。 **401/403** では、そのアカウントへのプロセスローカルな affinity を解除し、再認証を要求します。 **429** では `Retry-After` を尊重してアカウントの cooldown を開始し、affinity を解除したうえで、 @@ -313,13 +344,15 @@ native-main トラフィックまたはジャーナル復旧を受け入れる ### `ocx models [subcommand]`・`ocx model ` -`ocx model` は `ocx models` の別名です。サブコマンドを使用しない場合、構成されたプロバイダーに静的にシードされたモデルを一覧表示します。 `--provider` は 1 つの構成済みプロバイダーをフィルターし、`--json` はモデル メタデータを返します。 `live` は実行中のカタログを読み取ります。 `add`、`edit`、`remove`、および `list-custom` は手動カタログ エントリを管理します。 `enable`、`disable`、および `provider` は可視性を制御します。 `selected` はプロバイダー許可リストを制御します。 `context` はプロバイダーのコンテキストの上限を制御します。 `shadow` はバックグラウンドのシャドウ コール インターセプトを管理します。 +`ocx model` は `ocx models` の別名です。サブコマンドを使用しない場合、保存済みモデルとルーターが認識するモデル ID を一覧表示します。レジストリのシード、カスタムモデル、この CLI プロセス自身の検出キャッシュが含まれます。新しい CLI プロセスのキャッシュは空の場合があり、実行中のプロキシのカタログとは異なります。従来のキー方式プリセットでは、接続先を変更してもレジストリのシードが残る場合があります。 `--provider` は 1 つの構成済みプロバイダーをフィルターし、`--json` はモデル メタデータを返します。 `live` は実行中のカタログを読み取ります。 `add`、`edit`、`remove`、および `list-custom` は手動カタログ エントリを管理します。 `enable`、`disable`、および `provider` は可視性を制御します。 `selected` はプロバイダー許可リストを制御します。 `context` はプロバイダーのコンテキストの上限を制御します。 `shadow` はバックグラウンドのシャドウ コール インターセプトを管理します。 + +`reasoningEfforts` は `--json` でのみ表示されます。`null` は一覧が不明または未照会であることを示し、OS のキーチェーンを開く必要がある場合も含みます。空配列 `[]` は明示的な空の一覧、または `noReasoningModels` などによってそのモデルの推論 effort が無効であることを示します。稼働中のプロキシのカタログは `ocx models live` で確認できます。 `add` と `remove` は既定でローカル保存し、`--live` で稼働中のプロキシを変更します。ローカル `--json` 保存時にプロキシがなければ `sync.status: "not-attempted"`、`needsSync: true`、終了コード 0 を返します。試行した同期が失敗しても保存は維持され、終了コードは非ゼロです。`list-custom` はローカル一覧です。`display-name` は raw upstream ID、`order` は picker の public ID を使います。完全な並べ替え、featured 接頭部、native 順序のリセット制約は[英語版](/reference/cli/providers-accounts/#display-names-and-picker-identities)を参照してください。 |サブコマンド |サポートされているフラグ |アクション | | --- | --- | --- | -| `list` (デフォルト) | `--provider `、`--json` |構成されたプロバイダーにシードされたモデルをリストします。 | +| `list` (デフォルト) | `--provider `、`--json` | 保存済みモデルとローカルでルーターが認識するモデルを一覧表示します。 | | `live` | `--provider `、`--json` |実行時に検出されたモデルを含む、実行中のカタログを読み取ります。行には、`native`/`routed`、`custom`、および `enabled`/`disabled` というフラグが付けられます。 | | `add ` | `--display-name `、`--context-window `、`--modalities `, `--live`, `--json` | カスタムモデルをローカルに、または `--live` で稼働中のプロキシに登録します。 | | `edit ` | `--model-id `、`--display-name `、`--context-window `、`--modalities `、`--json` |カスタムモデルを編集します。 `-` はフィールドをクリアします。 `0` はコンテキスト ウィンドウをクリアします。 | diff --git a/docs-site/src/content/docs/ja/reference/client-support.md b/docs-site/src/content/docs/ja/reference/client-support.md new file mode 100644 index 0000000000..bef13c39dd --- /dev/null +++ b/docs-site/src/content/docs/ja/reference/client-support.md @@ -0,0 +1,60 @@ +--- +title: "クライアント対応" +description: "opencodex が接続するコーディングツール、それぞれの接続方法、使用するプロトコル。" +--- + + + + +opencodex は、AI コーディングツールとモデルをつなぐ 1 つのローカルゲートウェイです。一部のツールはネイティブに設定し、それ以外はローカルプロキシを指す設定ファイルをエクスポートまたは管理します。このページはコードのレジストリから生成されるため、現在のリリースの内容と正確に一致します。 + +## サポートレベル + +- **implemented**: レジストリに登録されたクライアントです。エクスポートされる設定では、表のプロトコルは opencodex が生成する設定から読み取られ、変わると生成が失敗します。*レビュー済み*は、エンドポイントが設定そのものではなくレビューに基づくことを示します(ネイティブクライアントと、設定を特定のエンドポイントに変換するクライアント)。レビューしたコードが残っているかを生成時に確認します。「OpenAI 互換」の行は特定のエンドポイントを主張しません。 +- **test-covered**: implemented であり、レビューで選んだこのクライアントのテストケースへのリンクがあります。生成時に確認するのはテストが存在し無効化されていないことだけです。何を検証しているかはテストを読んでください。 +- **実行確認**: ある時点の観察記録です。表のクライアント製品・バージョンを表の opencodex バージョンで、記載のシナリオにより、その日付に人が実行し、証拠をリンクしました。ほかのバージョンや製品については何も示しません。証拠は結果の追加時にレビューされ、生成時に再実行はされません。ダッシュは記録がないことを示します。 + +## クライアント + +| クライアント | ネイティブ | 設定エクスポート | 管理ファイル連携 | 受信プロトコル | サポートレベル | 実行確認 | 備考 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Codex (CLI, app, SDK) | はい | — | — | Responses (レビュー済み) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/codex-integration/codex-inject-missing-config.test.ts)) | — | opencodex が直接設定します。エクスポートされる設定ファイルはありません。 [ガイド](/ja/guides/codex-integration/) | +| Claude Code | はい | — | — | Anthropic Messages (レビュー済み) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/claude-integration/claude-cli.test.ts)) | — | opencodex が直接設定します。エクスポートされる設定ファイルはありません。 [ガイド](/ja/guides/claude-code/) | +| Claude Desktop | はい | — | — | Anthropic Messages (レビュー済み) | implemented | — | opencodex が直接設定します。エクスポートされる設定ファイルはありません。 | +| Grok Build | はい | — | — | Responses (レビュー済み) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/providers/xai/grok-config-inject.test.ts)) | — | opencodex が直接設定します。エクスポートされる設定ファイルはありません。 [ガイド](/ja/guides/grok-build/) | +| Qoder | — | JSON | はい | OpenAI 互換(エンドポイントはクライアントが選択) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/qoder-client.test.ts)) | — | ローカルリスナーのみ。 | +| Qoder CN | — | JSON | はい | OpenAI 互換(エンドポイントはクライアントが選択) | implemented | — | ローカルリスナーのみ。 | +| WorkBuddy | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/agent-clients.test.ts)) | — | ローカルリスナーのみ。適用前にクライアント固有のチェックを実行し、拒否することがあります。 | +| WorkBuddy AI | — | JSON | はい | Chat Completions | implemented | — | ローカルリスナーのみ。適用前にクライアント固有のチェックを実行し、拒否することがあります。 | +| OpenCode | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | リモートリスナーにも対応します(API キーヘッダーを追加)。 [ガイド](/ja/guides/opencode/) | +| Pi | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | ローカルリスナーのみ。 [ガイド](/ja/guides/pi/) | +| Oh My Pi (omp) | — | YAML | はい | Chat Completions; Responses (ネイティブ OpenAI モデルのみ) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | ローカルリスナーのみ。自分の YAML ブロックだけを編集します。 | +| Hermes | — | YAML | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/hermes-catalog-refresh.test.ts)) | — | リモートリスナーにも対応します(API キーヘッダーを追加)。自分の YAML ブロックだけを編集します。 | +| OpenClaw | — | JSON5 | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/gui/integrations-invariants.test.ts)) | — | リモートリスナーにも対応します(API キーヘッダーを追加)。 | +| Kimi CLI | — | TOML | はい | OpenAI 互換(エンドポイントはクライアントが選択) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export-new-clients.test.ts)) | — | ローカルリスナーのみ。 | +| Gajae | — | YAML | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/client-export-modality-enum.test.ts)) | — | ローカルリスナーのみ。 | +| DSH | — | YAML | はい | Responses | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | ローカルリスナーのみ。クライアントの現在のプロバイダーストアに書き込みます。自分の YAML ブロックだけを編集します。設定ファイル横のロックファイルで書き込みを調整します。 | +| MCode | — | YAML | はい | Anthropic Messages | implemented | — | ローカルリスナーのみ。設定ファイル横のロックファイルで書き込みを調整します。 | +| ZCode | — | JSON | はい | Responses (レビュー済み) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/integrations-current-store.test.ts)) | — | ローカルリスナーのみ。クライアントの現在のプロバイダーストアに書き込みます。クライアントがこの設定からエンドポイントを選びます(クライアントの文書化された動作に基づきレビュー済み)。 | +| Command Code | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/command-code-client.test.ts)) | — | ローカルリスナーのみ。設定ファイル横のロックファイルで書き込みを調整します。 | +| Prime | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/prime-client.test.ts)) | — | ローカルリスナーのみ。 | +| Aside | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/aside-profiles-catalog-refresh.test.ts)) | — | ローカルリスナーのみ。 | +| Raycast | — | YAML | はい | Chat Completions (レビュー済み) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/raycast-client.test.ts)) | — | ローカルリスナーのみ。クライアントがこの設定からエンドポイントを選びます(クライアントの文書化された動作に基づきレビュー済み)。 | +| omo | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/omo-client.test.ts)) | — | ローカルリスナーのみ。 | +| Cline | — | JSON | はい | Responses | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/cline-client.test.ts)) | — | ローカルリスナーのみ。設定ファイル横のロックファイルで書き込みを調整します。 | +| Kilo Code | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/client-export-reasoning-controls.test.ts)) | — | リモートリスナーにも対応します(API キーヘッダーを追加)。 | +| Factory Droid | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/droid-client.test.ts)) | — | ローカルリスナーのみ。 [ガイド](/ja/guides/factory-droid/) | +| Gentle Shell | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | ローカルリスナーのみ。 | +| T3 Code | — | JSON | はい | Anthropic Messages | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | ローカルリスナーのみ。適用前にクライアント固有のチェックを実行し、拒否することがあります。 | + +## 受信エンドポイント + +プロキシは次のプロトコルを受け付けます。上の表にないツールでも、いずれかのカスタムエンドポイントを設定できれば接続できます。 + +- `POST /v1/responses`: Responses +- `POST /v1/chat/completions`: Chat Completions +- `POST /v1/messages`: Anthropic Messages + +## このページを最新に保つ + +このページは `scripts/generate-client-support-matrix.ts` がエクスポート・管理連携・ネイティブ連携のレジストリから生成します。クライアントを追加するには `scripts/client-support-matrix/metadata.ts` にエントリを追加し、`bun run docs:clients` を実行してください。コミット済みのページが古いと `bun run docs:clients:check` が失敗します。 diff --git a/docs-site/src/content/docs/ja/reference/configuration.md b/docs-site/src/content/docs/ja/reference/configuration.md index df2527ef86..7bd2589c16 100644 --- a/docs-site/src/content/docs/ja/reference/configuration.md +++ b/docs-site/src/content/docs/ja/reference/configuration.md @@ -19,6 +19,11 @@ opencodex は、永続的な設定を `$OPENCODEX_HOME/config.json` (通常は ` ファイルを解析できない場合、opencodex はファイルを `config.json.invalid-` としてバックアップし、コンソールに警告を表示し、デフォルトで起動します。欠落しているファイルでも、新規インストールのデフォルトである 1 つの `openai` フォワード プロバイダーが使用されます。 +ローカルの `ocx config set`、`unset`、`import`、オフラインの `ocx effort`、カスタムモデルの add/remove、 +プロバイダーの add/remove/set-default は、既存の `config.json` が無効または読み取り不能な場合、 +元のバイト列を変更せずに拒否します。`ocx config validate` を実行し、ファイルを修復してから再試行してください。 +既存の設定がある場合、import にも読み取り可能で有効な保存先ファイルが必要です。 + ## 優先順位とデフォルト `config.json` の有効な値は、組み込みのデフォルトをオーバーライドします。省略可能なフィールドが欠落している場合は、ドメイン ページに記載されているデフォルトが使用されます。 `OPENCODEX_HOME` は、デフォルトの構成ディレクトリよりも優先されます。 `apiKey: "${PROVIDER_API_KEY}"` などの環境参照を受け入れるフィールドは、リクエスト時にその変数を解決します。送信プロキシの場合、すでに設定されている `HTTP_PROXY` または `HTTPS_PROXY` が最上位の `proxy` フィールドよりも優先されます。 @@ -41,5 +46,5 @@ opencodex は、永続的な設定を `$OPENCODEX_HOME/config.json` (通常は ` API キーには `${ENV_VAR}` 参照を優先します。リテラルの `apiKey`、`apiKeyPool[].key`、および `apiKeys[].key` 値は秘密です。コミットしたり、ログに貼り付けたり、共有したりしないでください。 OAuth およびフォワード プロバイダー トークンは、`config.json` ではなく別の資格情報ストアに保存されます。アカウント ID と電子メールも非公開にしておく必要があります。サポートされている場合は、パブリック セレクター エイリアスを使用します。 :::note[アトミック書き込み] -opencodex は、一時ファイルを介して管理対象の `config.toml` および `opencodex-catalog.json` ファイルを書き込み、その後名前を変更します (`atomicWriteFile`)。これにより、`ocx stop` やプロキシ シャットダウン ハンドラーなどの同時ライターが Codex を同時に復元するときに、部分的なファイルが生成されるのを防ぎます。 +opencodex は、一時ファイルを介して管理対象の `config.toml` および `opencodex-catalog.json` ファイルを書き込み、その後名前を変更します (`atomicWriteFile`)。これにより、`ocx stop` やプロキシ シャットダウン ハンドラーなどの同時ライターが Codex を同時に復元するときに、部分的なファイルが生成されるのを防ぎます。Windows では、`opencodex-catalog.json` に読み取り専用属性が付いて名前変更が拒否された場合、opencodex が属性を解除して一度だけ再試行します。それでも失敗する場合は、生の `EPERM` ではなく `Codex catalog is read-only: ` を報告します。 ::: diff --git a/docs-site/src/content/docs/ja/reference/configuration/advisor.md b/docs-site/src/content/docs/ja/reference/configuration/advisor.md index d78a179f23..59b4614e1e 100644 --- a/docs-site/src/content/docs/ja/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/ja/reference/configuration/advisor.md @@ -60,12 +60,18 @@ description: manual、preflight、証拠に基づく adaptive ポリシーによ 設定されたアドバイザーのプロバイダーは、ワーカーのプロバイダーと異なる場合があります。 +相談は、呼び出し元の取得済み API キーのモデル範囲・有料 combo への同意・デバイス別 fallback 制限と、Advisor 自身の受付キーのホスト制限の両方に従います。受付キーは、設定されていれば `OPENCODEX_API_AUTH_TOKEN` またはこのプロキシが受け付けるサービストークンファイル、なければ最初に設定された API キーです。キーの順序が意味を持つのはこの最後の場合だけです。Advisor モデルに届くキーを先頭に置かないと、すべての相談が利用できません。環境トークンまたはサービストークンが設定されているときは、そのトークンが相談を決めます。これらの規則は combo の選択、入れ子の判定モデル、再試行にも適用されます。満たせない相談は worker に利用不可の通知を返します。 + +たとえば `allowMeteredComboTargets: false` の `laptop` キーは Advisor 経由で従量課金の combo ターゲットに費用を使えず、`fallback.devices.laptop.provider: false` は Advisor のプロバイダー fallback ホップも止めます。キーのない loopback 呼び出し元には、引き続き combo の `allowMeteredTargets: true` のオプトインが必要です。両方のキーが `allowMeteredComboTargets: true` を設定し、combo が `allowMeteredTargets: true` を設定していれば、公開バインドの loopback リスナー経由でも Advisor は従量課金ターゲットを使えます。サーバーは本文の容量待ちや本文の読み取りより前、リクエストを認証した時点で呼び出し元のポリシーを取得します。その後のキーや fallback の編集でその相談の範囲が広がることはありません。これはルーティングされた画像補助、compact リクエストとその判定モデル、WebSocket ターン内のすべての候補再試行にも適用されます。新しい WebSocket ターンはそれぞれ自分のポリシーを取得します。 + OpenCodex はプロバイダー API キー、Authorization ヘッダー、OAuth トークン、バックエンド専用の設定秘密、プロセス環境、隠された思考連鎖をそのプロンプトへ入れません。暗号化されたプロバイダー私有の推論を復号して転送することもしません。**タスク内容は一般には秘密除去されません。** タスクへ貼られた鍵、ツールが読んだファイル内の秘密、ツールやログが出力したトークンは送られることがあります。OpenCodex は汎用の DLP を実行しません。 ## 権威 手動の助言は、ワーカー自身が行った `advisor` 呼び出しに対するツール結果です。結果は JSON オブジェクトです。`advice` はアドバイザーモデルのテキストです。`status` はランタイムが書きます。 +fetch ベースの Web 検索ターンでは、実際に適用される `tool_choice` が合成 `advisor` ツールを許可する場合に限り、検索ループがそのツールを公開し、手動相談の呼び出しを処理します。`allowed_tools` を `web_search` だけに制限すると、アドバイザーへの手動相談は許可されません。ホスト型検索を有効にしても、このツールの許可範囲は広がりません。 + 自動助言の引用済み JSON は、別の user ロールの助言メッセージで渡します。developer メッセージには固定のランタイム指示だけを残し、アドバイザーの生成文は developer/system に入りません。OpenAI Chat と Anthropic の両方で、偽のツール呼び出しなしに送れます。引用は構造の破壊やフィールドの偽造を防ぎますが、自然言語によるプロンプトインジェクションを完全には防ぎません。専用プロトコルなら通常のユーザー入力と区別しやすくなります。1 リクエストにつき相談は最大 3 回、ワーカー継続は最大 4 回です。上限で advisor ツールを除去し、再呼び出しには上限結果付きの最終継続を 1 回だけ許可します。さらに呼ばれた場合は 502 advisor_continuation_limit で終了し、追加送信しません。空の完了の再試行も同じ上限を共有します。 抑制はアドバイザーの文字列を読みません。自動の重複排除はサーバー所有の台帳だけです。転送文を写した developer メッセージも preflight を抑制しません。 diff --git a/docs-site/src/content/docs/ja/reference/configuration/providers.md b/docs-site/src/content/docs/ja/reference/configuration/providers.md index 42e6f48ebc..0b2b908649 100644 --- a/docs-site/src/content/docs/ja/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ja/reference/configuration/providers.md @@ -5,12 +5,26 @@ description: プロバイダー エントリ、認証、エンドポイント、 プロバイダーは、opencodex に、モデルが存在する場所、モデルが通信するワイヤー アダプター、およびリクエストの認証方法を伝えます。 +## Mistral のリクエストごとの画像数 + +Mistral の画像数制限と `mistralMaxImages` の設定は[英語の正規リファレンス](/reference/configuration/providers/#mistral-images-per-request)を参照してください。リミッターに届いた `image_url` 要素の画像参照が欠落、空、または文字列でない場合、送信用コピー内でテキストに置き換えられ、画像数の上限を消費しません。変換される Responses リクエストでは、有効な URL もファイル ID もない `input_image` をパーサーが省略します。メッセージやツール出力のブロック内で、空でない `file_id` があり空でない `image_url` がない場合、メディアガードが Mistral への送信前にリクエストを拒否します。ガードが検査しない再生済みの `agent_message` 内では、パーサーが代わりに `[image: ]` テキストマーカーを出力し、通常のテキストとして送信され画像数の上限を消費しません。リミッターは `image_url` または `image_url.url` の空でない文字列のみを数え、URL の構文や到達可能性は検証しません。他の送信先の動作は変わりません。 + ## カスタムプロバイダーのコンテキスト モデルのウィンドウが未報告・未設定の場合、Azure メタデータ、モデル ID による同梱ベンダー/集約メタデータ、有効な Context cap、128k の順で補完します。報告値と設定値は小さい方を使い、Context cap は引き続き上限となります。組み込みプロバイダーは変更しません。完全一致を優先し、大文字小文字やドット/ハイフンの別表記は曖昧でない場合だけ認めます。推定は Codex の圧縮予算や Claude を含むクライアントのカタログに反映されますが、ルーティングの実測能力とは区別します。同名モデルでも中継サービスの容量は保証されません。必要に応じて modelContextWindows または Context cap を設定してください。自動的な cap の有効化やモデルへの試験リクエストは行いません。OpenAI API の値は Codex サブスクリプションの上限ではありません。 この推定は既定で無効です。プロバイダーごとに `inferContextWindow: true` で有効にします。未設定の場合、ウィンドウがないモデルは有効な Context cap、次に 128k を使います。 +## GPT-6.1 Terra + +[GPT-6.1 Terra](https://openai.com/index/introducing-gpt-6-1-terra/) は GPT-5.6 Terra の後継として 2026年10月26日に公開されました。`gpt-6.1-terra` は `gpt-5.6-terra` と並行して利用でき、既定モデルやサブエージェントのモデル一覧は変更しません。GitHub Copilot では Responses を使用します。OpenRouter の ID は `openai/gpt-6.1-terra` で、コンテキストは 1,050,000、100万トークンあたり入力 $1.00、出力 $5.00 です。 + +ネイティブ Codex:既定コンテキスト 500,000、長文コンテキスト上限 872,000、既定 effort は `low`。段階は `low`、`medium`、`high`、`xhigh`、`max`、`ultra` です。ネイティブの `ultra` は通信時に `max` として送信します。ネイティブ行の高速モードは Fast のみです。 + +[OpenAI API](https://developers.openai.com/api/docs/models/gpt-6.1-terra):コンテキスト 1,050,000、最大出力 128,000。入力はテキストと画像、出力はテキスト。知識カットオフは 2026-06-01 です。effort は `none`、`low`、`medium`(既定)、`high`、`xhigh`、`max`。エンドポイントは `v1/responses` と `v1/chat/completions` ですが、ツール呼び出しには Responses が必要です。 + +100万トークンあたり入力 $1.00、キャッシュ入力 $0.05、キャッシュ書き込み $1.25(30分)、出力 $5.00。入力が 272,000 トークンを超える場合、リクエスト全体の入力・キャッシュは 2×、出力は 1.5× となり、それぞれ $2.00 / $0.10 / $2.50 / $7.50 です。Fast モードは 2× です。 + ## 初回登録時のモデル選択 新しい非 OAuth 接続では、信頼できるモデル一覧の取得が完了するまでモデルの公開を保留します。Models タブの重複しないモデル行が20個以上なら、モデルのスイッチをすべて OFF にします。プロバイダー自体は ACTIVE のままです。実際の認証方式が OAuth または ChatGPT ログインなら既定値を維持します。 @@ -33,6 +47,7 @@ GUI で登録または OAuth ログインが完了すると、Models ページ | `providers` | `Record` | — |プロバイダー名からプロバイダー設定へのマップ。 | | `openaiProviderTierVersion?` | `2` |移行によって設定される |単一のオプション対応 OpenAI プロジェクションを完了としてマークします。 | | `disabledModels?` | `string[]` | — | Codex catalog と `/v1/models` から非表示にする model。直接の proxy 呼び出しはブロックしません。routed id は一覧から削除されます。account-qualified native id は該当する selector row だけを非表示にし、bare native GPT id は bare row とその model の全 account-selector row を非表示にします。Models ページに表示されるのは bare native 行と routed 行だけです。selector-qualified 行を 1 つだけ非表示にするには、この設定フィールドを直接編集してください。 | +| `omitDisabledNativeModels?` | `boolean` | `false` | 既定値は `false` です。`config.json` に `"omitDisabledNativeModels": true` を設定して `ocx sync` を実行すると、無効な native 行を catalog、cache、Codex 形式の HTTP モデル一覧から除外します。除外前に検証した継承テンプレートを保持するため routed 行のメタデータは変わりません。直接リクエストのルーティングも変わりません。 | | `providerContextCaps?` | `Record` | `{}` | プロバイダーごとの有効なコンテキスト上限。通常のウィンドウは縮小されます。長いウィンドウに対応したネイティブモデルは、そのモデルが対応する上限まで拡張できます。 | | `providerContextCapValues?` | `Record` | `{}` | プロバイダーごとに最後に選択した上限。無効にしても保持され、この値だけで上限が有効になることはありません。有効な値が保存済みの値より優先されます。 | | `contextCapValue?` | `number` | `350000` | 初回の有効化で使う既定値。再び有効にすると、そのプロバイダーの選択値を復元します。`setAll: true` とともにグローバル値を変更すると、有効な上限だけを更新します。値を指定せずに `setAll: true` を送ると、設定済みの全プロバイダーの上限を現在のグローバル値で有効にします。 | @@ -42,9 +57,9 @@ GUI で登録または OAuth ログインが完了すると、Models ページ | `codexAccountPickerEnabled?` | `boolean` | map が空なら off | 有効な `codexAccountNamespaces` mapping から account-qualified Codex picker row を生成するかを制御します。`true` は mapping された行の表示を許可します。空でない map で省略した場合は後方互換性のため有効として扱われ、map が空なら off です。`false` は mapping を削除せず、明示的な `/` routing も無効にせずに、生成行を非表示にして picker の bare native 行を復元します。 | | `activeCodexAccountId?` | `string` | — |次のリクエスト用に手動で選択されたプール アカウント。選択するとスレッドのアフィニティがクリアされます。実行中のリクエストでは、取得された資格情報が保持されます。 | | `codexAccountPriorities?` | `Record` | — | Codex pool のアカウント別選択順。アカウント ID → `-100` から `100` の整数で、**大きいほど先に使われ**、未設定は `0` です。これは eligibility ではなく順序の境界です。選択は適格なアカウントを、まだ quota に余裕がある最上位 tier に絞り込み、その tier の中を `accountPoolStrategy` が選びます。tier が飛ばされるのは、そのメンバー全員が自身の 0 以外の実効しきい値(アカウント別上書き、未設定ならグローバル値)以上、cooldown 中、soft-avoid、一時停止、または再認証待ちのときだけで、usage 不明が tier を drain させることはありません。順序付けが不適格なアカウントを選択可能にすることはなく、すでにアカウントが結び付いた thread を再 bind することもありません。メインの `__main__` も同じ条件で参加するため、Codex Desktop ログインを最後に使わせられます。エントリが 1 つもなければ挙動は従来どおりです。map が不正な場合は警告を出して順序付けを無効にします(config の修復処理は走りません)。`ocx account priority` と Codex Auth ページで管理します。 | -| `autoSwitchThreshold?` | `number` | `80` | 使用量ベースのプロアクティブ切り替えしきい値。`quota` は未紐付けタスクの次のリクエストを再評価できます。紐付け済みタスクは既定(`pool.cacheAffinity`)ではしきい値を超えても同じアカウントを維持し、アカウントが使い切られるか処理できなくなったときだけ離れ、その場合も実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`pool.cacheAffinity: false` にするとしきい値で紐付け済みタスクも再評価します。`fill-first` は未紐付け割り当ての使い切り基準としてのみ使用し、通常の `round-robin` 選択は使用しません。既知の 5 時間、週次、30 日 quota window の最大スコアを使います。`0` は使用量ベースの切り替えだけを無効にし、未紐付け割り当てや障害回復は無効にしません。 | +| `autoSwitchThreshold?` | `number` | `80` | 使用量ベースのプロアクティブ切り替えしきい値。`quota` は未紐付けタスクの次のリクエストを再評価できます。紐付け済みタスクは既定(`pool.cacheAffinity`)ではしきい値を超えても同じアカウントを維持し、アカウントが使い切られるか処理できなくなったときだけ離れ、その場合も実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`pool.cacheAffinity: false` にするとしきい値で紐付け済みタスクも再評価します。`fill-first` は未紐付け割り当ての使い切り基準としてのみ使用し、`round-robin` は新規/未紐付けの割り当て時にのみ使用し、しきい値未満の適格アカウントがある間は実効しきい値以上のアカウントを除外し、この理由で紐付け済みタスクを移動しません。既知の 5 時間、週次、30 日 quota window の最大スコアを使います。`0` は使用量ベースの切り替えだけを無効にし、未紐付け割り当てや障害回復は無効にしません。 | | `codexAccountAutoSwitchThresholds?` | `Record` | — | `autoSwitchThreshold` のアカウント別上書き(アカウント ID → `0`〜`100` の整数)。未設定はグローバル値を継承し、`0` はそのアカウントからの使用量ベース切り替えだけを無効にします。メインの `__main__` も指定できます。Codex Auth の各アカウントカードで管理します。 上書きを有効にすると、現在のグローバルしきい値が固定のアカウント別値としてコピーされます。`0` を含む上書き値は、その後グローバル値が変更されても優先されます。無効にすると `threshold: null` を送信してエントリを削除し、現在のグローバルしきい値と今後の変更を継承する状態に戻ります。 | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新規/未紐付け Codex リクエストの割り当て戦略。live な `(parent thread id, quota scope)` affinity がなければ未紐付けで、プロキシ再起動や affinity リセット後は既存の表示タスクも未紐付けになり得ます。`quota` はアクティブアカウントがなければ既知 usage 最小の適格アカウントを選び、適格なアクティブアカウントが `autoSwitchThreshold` 未満なら維持します。しきい値到達後は未紐付けリクエストを移せます。紐付け済みタスクは既定ではアカウントが使い切られるか(既知 usage 100%)処理できなくなるまで維持され、離れるときは実際に quota 余裕があり usage がより低いアカウントへだけ移ります。フラグをオフにすると、しきい値で紐付け済みタスクの次のリクエストも実際に quota 余裕があり usage がより低い適格アカウントへ移せます。`round-robin` は未紐付けリクエストを均等分散し、`fill-first` は cooldown、使用不可、または drain threshold までアクティブアカウントへ割り当てます。 `reset-first`: 使用率のしきい値未満から、次の5時間枠または週次枠のリセットが最も近いアカウントを選びます。紐付け済みタスクは設定されたアフィニティ方針に従います。独立したモデル枠は使用率順です。 月次リセットはこの順序に使用しません。 | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新規/未紐付け Codex リクエストの割り当て戦略。live な `(parent thread id, quota scope)` affinity がなければ未紐付けです。セッションIDを持つリクエスト(通常の Codex CLI・App のターンやサブエージェントを含む)と、直近の親に紐付くセッションなしリクエストの紐付けは、シャットダウン時の最終的な affinity 保存が成功した場合、プロキシの正常な再起動後も最大24時間の非活動期間まで保持されることがあります。より深いセッションなしの連鎖と Codex App のメインログインへの紐付けはメモリ内にのみ残り、再起動後に再割り当てされます。eviction、アカウント削除、再ログイン、クラッシュ、affinity リセットではタスクが未紐付けになり得ます。`quota` はアクティブアカウントがなければ既知 usage 最小の適格アカウントを選び、適格なアクティブアカウントが `autoSwitchThreshold` 未満なら維持します。しきい値到達後は未紐付けリクエストを移せます。紐付け済みタスクは既定ではアカウントが使い切られるか(既知 usage 100%)処理できなくなるまで維持され、離れるときは実際に quota 余裕があり usage がより低いアカウントへだけ移ります。フラグをオフにすると、しきい値で紐付け済みタスクの次のリクエストも実際に quota 余裕があり usage がより低い適格アカウントへ移せます。`round-robin` は実効 `autoSwitchThreshold` 未満の適格アカウントに未紐付けリクエストを均等分散し、全員がしきい値以上なら全適格アカウントに分散し、`fill-first` は cooldown、使用不可、または drain threshold までアクティブアカウントへ割り当てます。 `reset-first`: 使用率のしきい値未満から、次の5時間枠または週次枠のリセットが最も近いアカウントを選びます。紐付け済みタスクは設定されたアフィニティ方針に従います。独立したモデル枠は使用率順です。 月次リセットはこの順序に使用しません。 | | `pool.cacheAffinity?` | `boolean` | `true` | 紐付け済み Codex スレッド向けの cache-affinity 順序。`pool.kernel` とは独立で、既定はオンです。不正な値はオンとして読みます。live な紐付けが quota 余裕より優先され、`quota` は使用量が `autoSwitchThreshold` を超えたという理由だけではスレッドを移しません。一時停止、使用不可、または実際に使い切られたアカウント(既知 usage 100%)では離れますが、実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`false` にするとしきい値での再紐付けに戻ります。affinity は固定ではなく並べ替えです。 | | `accountPoolStickyLimit?` | `number` | `1` | 1 回の round-robin 選択で次へ進む前に保持する新規/未紐付けタスク割り当て数。カウンターは上流の成功後ではなくタスクの紐付け時に増えます。範囲 1–100。`accountPoolStrategy` が `round-robin` のときのみ。 | | `upstreamFailoverThreshold?` | `number` | `3` |今後の新しいセッションがフェイルオーバーする前に一時的なエラーが連続して発生する。 `0` を無効に設定します。通常のResponses送信とネイティブcompact送信では、実証済みの接続前DNS/TCP到達不能障害はprovider-host単位で記録され、アカウントの健全性、アカウントのクールダウン、スレッド/セッションの親和性、アクティブアカウントの選択、Poolルーティングには影響せず、この閾値にもカウントされません。 | @@ -52,6 +67,8 @@ GUI で登録または OAuth ログインが完了すると、Models ページ | `codexPinnedTransientPolicy?` | `"hold" \| "detour-new-threads"` | `"hold"` | 手動ピンが劣化したとき、`hold` は警告を出して使い続け、`detour-new-threads` は新しいスレッドだけを別アカウントへ置きます。送信済みのターンは再送しません。 | | `codexWsReuseAcrossTurns?` | `boolean` | `false` | 同一アカウントとスレッドで Codex WebSocket をターンをまたいで再利用します。既定はオフ。オンにすると忙しいソケットを最大750ms待ち、モデルやティアの変更では最大2本を残します。 | | `upstreamHostCircuitThreshold?` | `number` | `0` | ネイティブOpenAI forwardのResponses送信とcompact送信で、実証済みの接続前DNS/TCP障害に適用するオプトインのサーキットしきい値です。`0`で無効、`1`〜`20`ではその回数の終端論理リクエストが失敗するとprovider-originを30秒間遮断します。遮断中はアカウント選択やupstream送信の前に`Retry-After`付き`503`を返し、時間経過後はhalf-openリクエストを1件だけ許可します。タイムアウトとHTTP応答は数えず、HTTP応答が1件でもあれば回路を閉じます。 Codex Pool ルーティングでアカウントが固定されていない場合にのみ適用され、`codexAccountMode: "direct"` とアカウント修飾セレクターでは動作しません。 | +| `maxInboundBodyBytes?` | `number` | `0` | 受信する JSON 本文 1 件のデコード後のサイズを制限するバイト単位の設定です。省略または `0` でデフォルトの 256 MiB を維持し、設定値は 1〜512 MiB に制限されます。変更後は再起動が必要です。超過時はコード `inbound_body_too_large` のローカル HTTP 413 を返します。適用される上限が 256 MiB を超えると `maxConcurrentInboundBodyBytes` の共有ゲートも有効になり、リクエスト単位の上限だけを上げても共有予算は増えません。対象ルートと詳細は[受信リクエスト本文の受け入れ](/ja/reference/inbound-body-admission/)を参照してください。 | +| `maxConcurrentInboundBodyBytes?` | `number` | `536870912` (512 MiB) | バイト単位の任意のトップレベル共有受け入れ予算です。適用される `maxInboundBodyBytes` が 256 MiB を超える場合にのみ有効です。省略、`0`、無効な値は従来のデフォルト 512 MiB を使います。有効な正の整数は使用時に 512 MiB〜2 GiB (`536870912`〜`2147483648`) に制限されます。再起動が必要で、同一プロセス内のすべてのリスナーが 1 つの予算を共有します。受け入れの計上用であり、メモリの事前割り当て、RSS 上限、RAM に応じた自動調整ではありません。2 GiB には運用者の明示的な選択が必要です。設定例、キューとレスポンスのライフサイクルに伴う制約、デフォルトで解析前の完全な 512 MiB アップロードが 1 件だけになる理由は[受信リクエスト本文の受け入れ](/ja/reference/inbound-body-admission/)を参照してください。 | | `modelCacheTtlMs?` | `number` | `300000` |プロバイダーごとの `/models` キャッシュの鮮度ウィンドウ。 | | `cacheRetention?` | `"none" \| "short" \| "long"` | Anthropic ファーストパーティ: `"long"`、その他の Anthropic 互換エンドポイント: `"short"` | Anthropic プロンプト キャッシュ ポリシー: 無効、5 分間の一時的、または 1 時間の延長。未設定の場合、`api.anthropic.com`(API キーまたは OAuth アカウント プール)へのリクエストは 1 時間の TTL を使い、互換ゲートウェイやベンダーのエンドポイントは 5 分の TTL のままです。明示した値が常に優先されます。 | | `tokenGuardian?` | `OcxTokenGuardianConfig` |オフ |オプションのプロアクティブな OAuth 更新および Codex アカウントのウォームアップ ポリシー。 | @@ -104,8 +121,9 @@ account を削除しても mapping は保持され、同じ id を再追加す | `defaultModel?` | `string` |このプロバイダーが明示的なモデルなしで選択された場合に使用されるモデル。 | | `models?` | `string[]` | 初期/フォールバックモデル一覧。`liveModels: false` で `models` が空でなければ、その後に `retainModels` を追加します。`models` が空または省略されている場合は、設定済みの `defaultModel`、`retainModels` の順に初期一覧を作り、重複 ID は最初の出現だけを残します。 | | `liveModels?` | `boolean` |開始/同期時にライブ カタログをフェッチします (デフォルトは `true`)。カスタムプロバイダーは `${baseUrl}/models` を使用します。組み込みはレジストリ URL とフィルターを使用する場合があります。 | -| `selectedModels?` | `string[]` | 探索後の許可リスト。非空の場合は指定 ID のみを許可し、空または省略時は追加の許可リストを適用しません。探索ポリシーと `disabledModels` は引き続き適用されます。 | -| `modelDisplayNames?` | `Record` | このプロバイダーの正確なネイティブモデル ID をキーにした、永続的な表示専用ラベルです。大文字と小文字は区別されます。ラベルはプロバイダーカタログのメタデータより優先され、認証、アダプター、ルーティング、課金、上流リクエストには影響しません。マップは検出上限と同じ 2,000 件までです。 | +| `modelDiscovery?` | `{ skipInvalidRows?: boolean }` | `/models` の一覧に不正な行を含むゲートウェイ向けのライブ検出互換設定です。既定では不正な行が 1 つでもあると一覧全体を拒否し、警告に最初の不正な行と不正な行の数を示します。`skipInvalidRows: true` の場合、オブジェクトでない行や id が欠落・非文字列・空・その他不正な行をスキップし、スキップした数だけを一度警告します (行の内容は出しません)。サイズと行数の上限は受信したすべての行を数え、重複排除・プロバイダーフィルター・id プレフィックス除去は残った行に適用されます。行をスキップして 1 行も残らない場合は、空のカタログとして扱わず一覧を拒否します。同じ宛先への保存で省略すると保持され、別の宛先へ移すと破棄されます。トップレベルの `modelDiscovery` (新モデルポリシーの状態) とは別物です。 | +| `selectedModels?` | `string[]` |検出後のカタログ許可リスト。空でない場合は、それらの ID のみが公開されます。空または省略すると、検出されたすべてのモデルが公開されます。 | +| `modelDisplayNames?` | `Record` | このプロバイダーの正確なネイティブモデル ID をキーにした、永続的な表示専用ラベルです。大文字と小文字は区別されます。ラベルはプロバイダーカタログのメタデータより優先され、認証、アダプター、ルーティング、課金、上流リクエストには影響しません。例外として、直接の `provider/model` セレクターが既知の ID、エイリアス、`retainModels` のいずれにも一致しない場合(ライブ一覧がまだ取得されていない間など)、エンコード形が一致するキーをネイティブ ID として送信します。マップは検出上限と同じ 2,000 件までです。 | | `contextWindow?` | `number` | アップストリームのメタデータが無い場合に使うプロバイダー全体のコンテキスト値。メタデータがある場合は上限として働き、より小さいライブ値をそのまま残します。Models ダッシュボードでは `providerContextCaps` とは別に設定します。 | | `modelContextWindows?` | `Record` | モデルごとのコンテキスト値および上限。`contextWindow` より優先され、ウィンドウが不明なら設定値を使い、より小さいライブメタデータがあればそちらが優先されます。 | | `inferContextWindow?` | `boolean` | カスタムプロバイダーのみ、既定は無効。`true` で欠けたウィンドウを同梱モデルメタデータから補完します。推定値であり、中継の容量を検証したものではありません。 | @@ -126,7 +144,7 @@ account を削除しても mapping は保持され、同じ id を再追加す | `modelReasoningEfforts?` | `Record` |モデルごとのラベル。空のリストは努力制御を非表示にします。 | | `modelSupportsReasoningSummaries?` | `Record` |モデルを `false` に設定して、概要の広告を停止し、概要配信フィールドを削除します。 | | `modelReasoningSummaryDelivery?` | `Record` |モデルごとの応答配信列挙型。既存の配信フィールドを書き換えます。 | -| `modelAdapters?` | `Record` | 混合配線ゲートウェイのモデルごとの `openai-chat` または `openai-responses` 配線オーバーライド。明示的なエントリはレジストリのデフォルトを破ります。DeepSeek のプリセットは `deepseek-v4-flash` のネイティブ Responses を選択でき、GitHub Copilot は モデル (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) を Responses 専用デフォルトとして宣言します。これらのモデルはエージェント トラフィックで `/chat/completions` を拒否するためです。`gpt-5.4-nano` のようなビルトイン デフォルトのないモデルはここでオプトインできます。単線アップストリーム ピンと正規の ChatGPT 転送はオーバーライドを拒否します。 | +| `modelAdapters?` | `Record` | 混合配線ゲートウェイのモデルごとの `openai-chat` または `openai-responses` 配線オーバーライド。明示的なエントリはレジストリのデフォルトを破ります。DeepSeek のプリセットは `deepseek-v4-flash` のネイティブ Responses を選択でき、GitHub Copilot は モデル (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) を Responses 専用デフォルトとして宣言します。これらのモデルはエージェント トラフィックで `/chat/completions` を拒否するためです。`gpt-5.4-nano` のようなビルトイン デフォルトのないモデルはここでオプトインできます。単線アップストリーム ピンと正規の ChatGPT 転送はオーバーライドを拒否します。 | | xAI Responses オプトイン(ダッシュボード) | スイッチ | `xai` のみで、`grok-4.5` と `grok-4.6` の `modelAdapters` エントリを原子的に設定または削除します。片方だけの場合は、次のスイッチ操作で両方が正規化されるまで混合状態を表示します。他のオーバーライドと tier 動作は変わりません。 Grok 4.7 は OAuth でレジストリの既定値により Responses を使用し、明示的な `modelAdapters["grok-4.7"] = "openai-chat"` で Chat に切り替えられます。 | | `xaiResponsesXSearch?` | `boolean` | デフォルトでは無効です。xAI Responses の宛先では、最終的なリクエスト正規化後もライブの `web_search` ツールが残っている場合にのみ、プロバイダーがホストする `x_search` 宣言を追加します。既存の宣言は重複させず、呼び出し元の `tool_choice` / `allowed_tools` セレクターの範囲を拡張することもありません。また、これは `search.xSearch` オプションを持つウェブ検索サイドカーとは別です。 | | `modelPreferHostedTools?` | `Record` | hosted tool namespace を予約する非 forward Responses gateway 向けの完全一致モデル opt-in。現在は `["image_generation"]` のみを受け付けます。一致したモデルは `openai-responses` wire を使い、その hosted tool をサポートする必要があります。競合するクライアント `image_gen` 宣言を除去し、呼び出し元の tool choice を維持するため selector も書き換えます。OpenAI API の仮想 `-pro` モデルでは、まず選択した公開 ID に一致させ、解決後のベース wire-model ID をフォールバックとして使用します。`modelAdapters` は公開 ID、次にベース ID の順に解決し、後者の結果が最終 wire を決めます。未設定のモデルは通常の alias 動作を維持します。 | @@ -141,13 +159,14 @@ account を削除しても mapping は保持され、同じ id を再追加す | `noPenaltyModels?` | `string[]` |存在/周波数ペナルティを拒否するモデル。 組み込みの`xai`プリセットは、xAIがこれらを拒否すると文書化している推論モデル(`grok-4.7`, `grok-4.6`, `grok-4.5`, `grok-4.3`, `grok-4.20-multi-agent-0309`, `grok-4.20-0309-reasoning`, `grok-build-0.1`)をここに登録します。非推論モデルは呼び出し元のペナルティをそのまま受け取ります。 | | `noStructuredOutputModels?` | `string[]` | `openai-chat` エンドポイントが `response_format` を拒否する正確なモデル ID。要求モデルが項目と完全一致する場合だけフィールドを省略し、その他の `openai-chat` モデルでは structured-output 変換を維持します。 | | `noJsonSchemaModels?` | `string[]` | `openai-chat` エンドポイントが `json_schema` 形式は拒否しつつ `json_object` は受け入れる正確なモデル ID。この要求はフィールドを削除せず `json_object` に降格して送るため、JSON を求めた呼び出し側は散文ではなく JSON を受け取れます。両方の一覧に載るモデルでは `noStructuredOutputModels` が優先します。`opencode go` / `opencode zen` プリセットが DeepSeek 経路に既定で載せます。 | -| `foldDeveloperRoleToSystem?` | `boolean` | `openai-chat` の宛先が `developer` ロールを受け付けるかを記録します。`foldDeveloperRoleToSystem` が未設定なら `system`、`true` なら `system`、`false` なら `developer` として送ります。未設定はこの宛先について何も記録されていないことを意味し、`true` は上流がロールを拒否する記録、`false` は受け付ける記録です。いずれの場合もメッセージは会話内の位置を保ち、変わるのはロールだけです。ロールを拒否する宛先は `400 role 'developer' is not allowed` を返してターンが始まらないため、未記録の既定は畳む側にしてあります。 | +| `foldDeveloperRoleToSystem?` | `boolean` | `openai-chat` の宛先が `developer` ロールを受け付けるかを記録します。`foldDeveloperRoleToSystem` が未設定なら `system`、`true` なら `system`、`false` なら `developer` として送ります。未設定はこの宛先について何も記録されていないことを意味し、`true` は上流がロールを拒否する記録、`false` は受け付ける記録です。`singleLeadingSystemMessage` が有効でない場合、メッセージは会話内の位置を保ち、変わるのはロールだけです。ロールを拒否する宛先は `400 role 'developer' is not allowed` を返してターンが始まらないため、未記録の既定は畳む側にしてあります。 | | `parallelToolCalls?` | `boolean` |並列ツール呼び出しを切り替えます。 OpenAI Chat はデフォルトでオンになっています。非チャット アダプターは明示的な `true` でのみアドバタイズします。 | | `responsesItemIdRepair?` | `{ message?: string[]; reasoning?: string[]; repairMissingTerminalIds?: boolean; repairInvalidIds?: boolean }` |正確なプレースホルダー ID、欠落している端末 ID、および(`repairInvalidIds` で)正規の `msg_`/`rs_` 接頭辞を欠く message/reasoning ID に対するダウンストリーム SSE 修復はデフォルトで無効になっています。関数呼び出し ID は決して書き換えられません。組み込み DeepSeek は最後の 2 つをデフォルトで有効にします。 | | `responsesSnapshotRepair?` | `boolean` | デフォルトで無効のクライアント向け修復です。SSE と JSON の Responses ライフサイクルで欠落した status、output、ツールメタデータを補完し、raw 検査と永続化は変更しません。 | -| `retryOn429?` | `{ enabled?: boolean; attempts?: number; intervalMs?: number; maxIntervalMs?: number; respectRetryAfter?: boolean }` | API-key プロバイダーのみ(`authMode: "key"`)。オプトインの同一ターゲット 429 リトライ: `retryOn429` が無ければ無効で、オブジェクトがあれば `enabled: false` でない限り有効になります。429 時に待機(上流の `Retry-After` または固定間隔)してから、キー フェイルオーバーの前に同一キーで同一リクエストを再送します — メインのテキストターン回復ループ、Responses passthrough、画像/動画ブリッジ、web-search サイドカー、ターミナル継続要求をすべてカバーします。再送の対象はプリストリームの HTTP 429 応答のみで、カスタム `runTurn` トランスポートは HTTP リトライループの対象外です。`attempts` は最初の 429 以降の同一キー再送回数(合計送信数 = `attempts` + 1)で、メインの回復ループ・ターミナルガード継続・ブリッジ再試行で共有されるリクエスト単位の予算です。`attempts` を使い切っても同一キーでの再送が止まるだけで、通常のキー フェイルオーバーまたは最終エラー処理が利用可能なターゲットに応じて続きます — キー認証の passthrough ワイヤにはフェイルオーバーがないため、使い切った 429 はそのまま返ります。Codex 自体は 429 をリトライしないため、単一キーのプロバイダーでは唯一の防御です。デフォルト: `enabled: true`、`attempts: 3`、`intervalMs: 5000`、`maxIntervalMs: 60000`(1回の待機は `maxIntervalMs` で上限、その上限は 600000)、`respectRetryAfter: true`。 | +| `promptCacheKey?` | `boolean` | `openai-chat` のプロバイダー全体で `prompt_cache_key` の転送を有効にします。アダプターは受け取ったキーを転送し生成しませんが、Claude Messages 変換では `metadata.user_id`、またはメタデータがなければモデル・システム・ツールの組み合わせから導出します。プリセットが指定しない限り既定は無効です。Mistral は[プロンプトキャッシュ契約](https://docs.mistral.ai/studio/conversations/advanced/prompt-caching)に従い有効で、明示的な `false` で無効になります。上流が対応を明記する場合のみ有効にしてください。厳格なゲートウェイは未知のフィールドを HTTP 400 で拒否する場合があります。 | +| `retryOn429?` | `{ enabled?: boolean; attempts?: number; intervalMs?: number; maxIntervalMs?: number; respectRetryAfter?: boolean }` | API キーのプロバイダーのみ(`authMode: "key"`)。未設定なら無効ですが、正規の OpenCode Go と Command Code、および正規の Mistral の `openai-chat` は例外で、再送 6 回、間隔 10 秒、上限 60 秒のポリシーを使います。オブジェクトを指定すると有効になり、`enabled: false` はこの既定ポリシーも無効にします。ストリーム開始前の HTTP 429 で `Retry-After` または固定間隔を待ち、キーの切り替え前に同じキーで同じリクエストを再送します。テキストターンの回復、Responses passthrough、画像・動画ブリッジ、web-search サイドカー、ターミナル継続が対象で、独自の `runTurn` は対象外です。`attempts` は最初の 429 後の同一キー再送回数(総送信数 = `attempts` + 1)で、リクエスト全体で共有します。使い切ると同一キーの再送だけが止まり、通常のキー切り替えか最終エラー処理に進みます。キー認証の passthrough では切り替えがなく、そのまま 429 を返します。正規の Mistral Chat で明示的な上流の待機時間が許容上限を超えると、同一キー再送を止めて元の `Retry-After` を返しますが、別のプールキーが処理できる場合があります。他のプロバイダーでは待機時間を上限で切り詰めます。Mistral は認証情報とモデルごとに期限を共有します。`requestPacing.enabled: false` または `retryOn429.respectRetryAfter: false` で無効になります。再試行時刻のない 429 で分単位の予算不足が検証されると、控えめな 60 秒の回復待機後、プローブを 1 回実行し、成功すれば通常のトラフィックを再開します。正常なトラフィックから次のトークン消費は予測しません。公表された許容量を使い、既知の月間枠の枯渇は除外し、正確なリセット時刻を保証せず、履歴の圧縮も起動しません。Codex 自体は 429 を再試行しません。オブジェクトの既定値:`enabled: true`、`attempts: 3`、`intervalMs: 5000`、`maxIntervalMs: 60000`(待機の上限、設定の最大値は 600000)、`respectRetryAfter: true`。 | | `transientRetryOn5xx?` | `{ enabled?: boolean; attempts?: number }` | キー認証の `openai-chat` および `openai-responses` プロバイダーのみ。`authMode: "forward"` のプロバイダー(ChatGPT アカウントプール)はこのオプションを読まず、既定の再試行段数を維持します。ストリーム開始前に上流から返される一時的なステータス(500、502、503、504、520、521、522)に対するオプトインの再試行です。設定がなければ無効で、オブジェクトを指定すると `enabled: false` でない限り有効になります。最初の Responses リクエスト、ターミナルガード継続、ネイティブの `/v1/chat/completions`、および 429/アカウント回復時の再取得が対象です。`attempts` は最初の送信を含め、1 回のリクエストで許可される上流への送信総数です(1~10、デフォルトは 3)。接続リセット回復と共有するリクエスト単位の単一予算であるため、`3` を指定した場合、プロバイダーに到達する実リクエストは最大 3 回です。待機には 400 ms を基準とする固定式の指数バックオフを使用し、上限は 5 秒で、`Retry-After` に従います。レート制限を扱う `retryOn429` とは別の機能であり、ストリーム開始後の失敗は再送されません。 各 Combo ターゲットでは、事前予約した初回送信もそのターゲットの設定総数に含まれます。`attempts: 1` は 1 回だけ送信し、予約を返却して余裕を作ったり、共有上限を広げたりしません。送信前のローカル拒否やキャンセルでは未使用の予約を解放します。 | -| `retryOnReset?` | `{ enabled?: boolean; replacements?: number }` | ネイティブ `openai-responses` プロバイダー(`authMode: "forward"` を含む)と、上流ヘッダー受信前の汎用 Responses 変換経路に適用されます。呼び出し側が何も観測しないまま失敗した送信を、オプトインで置き換えます。設定がなければ無効で、オブジェクトを指定すると `enabled: false` でない限り有効になります。レスポンスヘッダーが届く前に接続が切れた場合と、ヘッダー後に SSE 本文が制御イベントだけを運んだまま切れた場合の両方が対象です。canonical ChatGPT upstream WebSocket で create フレームの送信後、Responses イベントが届く前にソケットが閉じたかエラーになった場合も同じく対象で、その置き換えは HTTP で送信します。置き換えるのは自己完結したリクエストだけで、`store: false`、完全な `input`、`previous_response_id` / `conversation` / `stream_id` がないこと、クライアントが実行するツールのみ、が条件です。`replacements` は、すべてのレッグとすべてのコンボ子リクエストを合わせて 1 つの論理リクエストが行える置き換え送信の回数です(1..2、デフォルトは 1)。レッグ単位の再試行回数でも送信予算でもないため、置き換え送信もそのレッグがすでに持つ送信許容量に収まる必要があります。すでに出力やツール呼び出しを送ったリクエストは、この値に関わらず置き換えません。元の送信がすでに開始されていた場合は置き換えた推論も課金される可能性があるため、既定では無効です。 汎用変換経路では、初回送信と再構築後の送信のどちらも、同じ許可と送信予算でヘッダー受信前の接続リセットを置き換えます。アダプター独自のトランスポートと、上流ヘッダー受信後の変換ストリーム障害は対象外です。 | +| `retryOnReset?` | `{ enabled?: boolean; replacements?: number }` | ネイティブ `openai-responses` プロバイダー(`authMode: "forward"` を含む)と、上流ヘッダー受信前の汎用 Responses 変換経路に適用されます。呼び出し側が何も観測しないまま失敗した送信を、オプトインで置き換えます。設定がなければ無効で、オブジェクトを指定すると `enabled: false` でない限り有効になります。レスポンスヘッダーが届く前に接続が切れた場合と、ヘッダー後に SSE 本文が制御イベントだけを運んだまま切れた場合の両方が対象です。canonical ChatGPT upstream WebSocket で create フレームの送信後、Responses イベントが届く前にソケットが閉じたかエラーになった場合も同じく対象で、その置き換えは HTTP で送信します。置き換えるのは自己完結したリクエストだけで、`store: false`、完全な `input`、`previous_response_id` / `conversation` / `stream_id` がないこと、クライアントが実行するツールのみ、が条件です。このプロキシが自身のリプレイ状態から展開済みの `previous_response_id` を持つ連鎖ターンは、送信前にその ID が取り除かれるため対象になります。リセットが置き換えられなかった場合は、その理由(`ambiguous-no-policy`、`ambiguous-request-not-replayable`、`ambiguous-allowance-spent`)がサービスログに記録されます。`replacements` は、すべてのレッグとすべてのコンボ子リクエストを合わせて 1 つの論理リクエストが行える置き換え送信の回数です(1..2、デフォルトは 1)。レッグ単位の再試行回数でも送信予算でもないため、置き換え送信もそのレッグがすでに持つ送信許容量に収まる必要があります。すでに出力やツール呼び出しを送ったリクエストは、この値に関わらず置き換えません。元の送信がすでに開始されていた場合は置き換えた推論も課金される可能性があるため、既定では無効です。 汎用変換経路では、初回送信と再構築後の送信のどちらも、同じ許可と送信予算でヘッダー受信前の接続リセットを置き換えます。アダプター独自のトランスポートと、上流ヘッダー受信後の変換ストリーム障害は対象外です。 | | `autoToolChoiceOnlyModels?` | `string[]` | `tool_choice` が `auto` または `none` のみを受け入れるモデル。強制的な選択は格下げされます。 | | `preserveReasoningContentModels?` | `string[]` |チャット履歴に以前のアシスタント `reasoning_content` が必要なモデル。ダッシュボードから保存しても、保存済みのリスト(`[]` を含む)は保持されます。`PATCH /api/providers?name=` は配列、または消去するための `null` を受け付けます。 アダプター、ベース URL、または認証モードを変えて別の宛先に移す保存では保持されません(下の節を参照)。 | | `reasoningDetailsModels?` | `string[]` | thinking を構造化された `reasoning_details` 配列で返すモデル(`reasoning_split` 使用の MiniMax M シリーズ)。ストリーム差分は累積スナップショットとして prefix-diff され、保持された reasoning は `reasoning_content` 文字列ではなく `reasoning_details` 配列としてリプレイされます。 | @@ -159,30 +178,33 @@ account を削除しても mapping は保持され、同じ id を再追加す | `anthropicEofTolerance?` | `boolean` | `message_stop` 前にストリームが終了しても、可視テキストまたは完全な JSON オブジェクトのツール入力が受信済みの場合に限り完了を許可します(Anthropic 互換ゲートウェイ向け)。デフォルトはオフ。 | | `googleMode?` | `"ai-studio" \| "vertex" \| "cloud-code-assist"` | Google トランスポート/認証モード。デフォルトは`ai-studio`です。 | | `googleToolSchemaPolicy?` | `"compatible" \| "reject-lossy"` | Google 専用です。省略時または `compatible` は互換スキーマと既存の非直接 400 修復を維持します。`reject-lossy` は初期損失または判定不能な上限付き比較を送信前に拒否し、制約を開く Vertex/Cloud Code Assist 修復を保留します。直接 AI Studio はこの修復を行いません。 | -| `project?` | `string` | Vertex または Antigravity Cloud Code Assist プロジェクト ID。Vertex の API キーは、これが設定されているとプロジェクトエンドポイントを使い、未設定なら `GOOGLE_CLOUD_PROJECT` があっても express モードを使います。ADC は `GOOGLE_CLOUD_PROJECT` / `GCLOUD_PROJECT` にフォールバックします。 | +| `project?` | `string` | Vertex または Antigravity Cloud Code Assist プロジェクト ID。Vertex の API キーは、これが設定されているとプロジェクトエンドポイントを使い、未設定なら `GOOGLE_CLOUD_PROJECT` があっても express モードを使います。ADC は `GOOGLE_CLOUD_PROJECT` / `GCLOUD_PROJECT` にフォールバックします。`"auto"` を指定すると、Vertex の各 API キーが自身のプロジェクトを解決します(解決に成功した結果はキーごとにキャッシュし、解決に失敗したキーは後続のリクエストで再度プローブします)。1 つのキープールで複数プロジェクトを扱えます。ADC は `"auto"` を拒否します。 | | `location?` | `string` | Vertex のロケーション。API キーのプロジェクトエンドポイントは既定で `global` を使い、`GOOGLE_CLOUD_LOCATION` を無視します。ADC にはこの値か `GOOGLE_CLOUD_LOCATION` フォールバックが必要です。 | | `mcpServers?` | `Record` |カーソルのみ: 標準入出力またはストリーミング可能な HTTP MCP サーバー。 | | `desktopExecutor?` | `DesktopExecutorConfig` |カーソルのみ: 外部コンピュータ使用および画面録画コマンド。 | | `unsafeAllowNativeLocalExec?` | `boolean` |カーソルのレガシー ブール値。新しいフィールドが設定されていない場合のみ、`nativeLocalExec: "on"` と同等です。 | | `nativeLocalExec?` | `"off" \| "codex-sandbox" \| "on"` |カーソルのローカル実行ポリシー。 `off` がデフォルトです。 `codex-sandbox` は現在、`off` と同様にフェールクローズされます。 | +LM Studio instruction compatibility: `singleLeadingSystemMessage: true` overrides chronological Chat instruction placement by merging text-only system/developer messages into one leading system message. The LM Studio preset enables it by default; set it to `false` to disable merging. + + プロバイダーの登録・置換(`POST /api/providers`)では、メモリやファイルの設定を変更する前に `responsesPath` と `chatCompletionsPath` を検証します。`PATCH /api/providers?name=` はリクエスト本文を保存済みのプロバイダーにマージします。`disabled` 以外のフィールドを変更する更新(`requestPacing` のみの更新を除く)では、保存前にマージ後のプロバイダーのパスを同じ方法で検証し、保持されているパスが無効な場合は `400` を返して設定を変更しません。設定ファイルの読み込みにも同じ経路の規則が適用されます。 API キープロバイダーは、リテラルキーまたは環境参照を保持する場合があります。 OAuth プロバイダーは、`ocx login` によって設定された資格情報ストアを使用します。サブスクリプションに基づくクロード コードの起動動作は、[`claudeCode.authMode`](/ja/reference/configuration/server/#claude-code-claudecode) で構成されます。 ### プロバイダーの保存で保持されるもの -既存のプロバイダー名で `POST /api/providers` を送ると、保存済みの行はリクエストから組み立てた行で置き換えられます。ダッシュボードの追加・編集フォームはすべてのフィールドを送れないため、リクエストが省略した保存済みフィールドの一部は保存時に引き継がれます。そのうち次の 8 つは、特定のアップストリームの挙動を記録するものです:`preserveReasoningContentModels`, `requiresReasoningPlaceholderModels`, `foldDeveloperRoleToSystem`, `reasoningWireFormat`, `omitReasoningEffortWithToolsModels`, `retryOn429`, `transientRetryOn5xx`, `retryOnReset`。 +既存のプロバイダー名で `POST /api/providers` を送ると、保存済みの行はリクエストから組み立てた行で置き換えられます。ダッシュボードの追加・編集フォームはすべてのフィールドを送れないため、リクエストが省略した保存済みフィールドの一部は保存時に引き継がれます。そのうち次の 13 個は、特定のアップストリームの挙動を記録するものです:`preserveReasoningContentModels`, `preserveResponsesReasoningContent`, `requiresReasoningPlaceholderModels`, `foldDeveloperRoleToSystem`, `singleLeadingSystemMessage`, `reasoningWireFormat`, `omitReasoningEffortWithToolsModels`, `promoteAdditionalTools`, `retryOn429`, `transientRetryOn5xx`, `retryOnReset`, `unsupportedHostedTools`, `unsupportedHostedToolsWithClientTools`。 -| 保存 | 8 つの設定 | 保存済みの `apiKeyPool` | +| 保存 | 13 個の設定 | 保存済みの `apiKeyPool` | | --- | --- | --- | | 同じ宛先、フィールド省略 | 保存済みの値を保持(明示的な `[]` や `false` を含む) | 保持 | | 新しい宛先、フィールド省略 | 保持しない。新しい宛先のレジストリ既定値が適用されることがあります | 保持しない | | リクエストでフィールドを送信 | リクエストの値 | リクエストの値 | -宛先とは、アダプター、ベース URL(スキームとホストは大文字小文字を区別せず、末尾のスラッシュは無視)、そしてリクエストが指定した場合は認証モードです。別の宛先へ移すと、以前のアップストリームを表す 8 つの設定と、そのために発行されたキーのプールは引き継がれません。保存時に古い行の残りを新しい行へマージすることはありません。 +宛先とは、アダプター、ベース URL(スキームとホストは大文字小文字を区別せず、末尾のスラッシュは無視)、そしてリクエストが指定した場合は認証モードです。別の宛先へ移すと、以前のアップストリームを表す 13 個の設定と、そのために発行されたキーのプールは引き継がれません。保存時に古い行の残りを新しい行へマージすることはありません。 -`PATCH /api/providers?name=` は指定したフィールドだけを変更し、宛先に関係なくほかの保存済みフィールドはすべて保持します。8 つの設定をすべて受け付け、`null` で消去します。2 つの推論リストでは、空の配列は削除されず明示的なオプトアウトとして保存されます。 +`PATCH /api/providers?name=` は指定したフィールドだけを変更し、宛先に関係なくほかの保存済みフィールドはすべて保持します。13 個の設定をすべて受け付け、`null` で消去します。2 つの推論リストでは、空の配列は削除されず明示的なオプトアウトとして保存されます。 ## プロバイダーによるアウトバウンドの安全性診断 @@ -203,8 +225,7 @@ pool アカウントの追加と quota 更新はダッシュボードの **Codex 使い切られるか処理できなくなるまで再紐付けを延期し、離れるときは実際に quota 余裕があり usage が より低いアカウントへだけ移ります。フラグをオフにすると、`quota` はしきい値超過後の次のリクエストで 再紐付けできます。 -pause、cooldown、再認証、障害処理も独立して routing を消去または変更できます。未紐付けリクエストには -プロキシ再起動や affinity リセット後の既存タスクも含まれます。出力前の **429/402** は使用量ベースの +pause、cooldown、再認証、障害処理も独立して routing を消去または変更できます。未紐付けリクエストには有効なアカウントの紐付けがありません。セッションIDを持つリクエスト(通常の Codex CLI・App のターンやサブエージェントを含む)と、直近の親に紐付くセッションなしリクエストの紐付けは、シャットダウン時の最終的な affinity 保存が成功した場合、プロキシの正常な再起動後も最大24時間の非活動期間まで保持されることがあります。より深いセッションなしの連鎖と Codex App のメインログインへの紐付けはメモリ内にのみ残り、再起動後に再割り当てされます。eviction、アカウント削除、再ログイン、クラッシュ、affinity リセットではタスクが未紐付けになり得ます。出力前の **429/402** は使用量ベースの 切り替えがオフでも同じリクエストで適格な代替アカウントへ 1 回再試行できます。アカウント変更後も会話 コンテキストは保持・再生されますが、アカウント間の provider prompt cache 再利用は保証されません。 一時停止したアカウントと quota metadata は表示されたままですが、自動切り替え、再試行/failover 選択、cooldown 復旧プローブ、手動有効化の対象外です。 @@ -216,8 +237,7 @@ pause、cooldown、再認証、障害処理も独立して routing を消去ま 別の適格な Pool アカウントへリクエストを切り替えることがあります。これらの障害回復は `autoSwitchThreshold: 0` でも有効であり、`0` が無効にするのは使用量に基づく予防的な切り替えだけです。 -**割り当てとプロアクティブ切り替え戦略:** `quota`(既定)はアクティブアカウントがない場合に最小 usage の適格アカウントを選び、適格なアクティブアカウントが `autoSwitchThreshold` 未満なら維持します。`autoSwitchThreshold` 超過後は未紐付けリクエストを移せます。既定では cache affinity が quota 余裕より優先され、紐付け済みタスクはアカウントが使い切られるか(既知 usage 100%)処理できなくなるまで維持され、離れるときは実際に quota 余裕があり usage がより低いアカウントへだけ移ります。usage が不明なアカウントは紐付け済みタスクの移動先にはならず、すべてのアカウントがしきい値を超えていればそのまま残ります。フラグをオフにすると紐付け済みタスクの次のリクエストもしきい値で再紐付けできますが、その場合も実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`round-robin` は -未紐付けリクエストを均等分散し、しきい値は通常の rotation を変えません。`accountPoolStickyLimit` +**割り当てとプロアクティブ切り替え戦略:** `quota`(既定)はアクティブアカウントがない場合に最小 usage の適格アカウントを選び、適格なアクティブアカウントが `autoSwitchThreshold` 未満なら維持します。`autoSwitchThreshold` 超過後は未紐付けリクエストを移せます。既定では cache affinity が quota 余裕より優先され、紐付け済みタスクはアカウントが使い切られるか(既知 usage 100%)処理できなくなるまで維持され、離れるときは実際に quota 余裕があり usage がより低いアカウントへだけ移ります。usage が不明なアカウントは紐付け済みタスクの移動先にはならず、すべてのアカウントがしきい値を超えていればそのまま残ります。フラグをオフにすると紐付け済みタスクの次のリクエストもしきい値で再紐付けできますが、その場合も実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`round-robin`:rotationはカウンター方式です。新規割り当てでは実効 `autoSwitchThreshold`(アカウント別上書きまたはグローバル既定値、`quota` と同じスコア)未満の適格アカウントがある間、しきい値以上のアカウントを除外します。使用量不明またはしきい値 `0` は未満として扱い、全適格アカウントがしきい値以上なら全員で順番に回します。紐付け済みタスクはしきい値を超えても維持し、処理不能(cooldown、quota 拒否、failover、pause)の場合のみ移動します。live な会話の子は親が使用中のアカウントから始まります。共通の優先度階層フィルターも同じ方法で余裕を評価します。オペレーターの手動選択は、使用量にかかわらず各 quota スコープの次の配置を取ります。そのスコープでそのアカウントへのリクエストが成功すると選択は消費され、以後の配置では再びしきい値が適用されます。`accountPoolStickyLimit` (既定 `1`、1–100)は成功応答ではなく割り当て/紐付け数を数えます。`fill-first` は未紐付けリクエストを cooldown、再認証、またはそのアカウントの実効 drain threshold(アカウント別上書き、未設定ならグローバル値)までアクティブアカウントへ割り当て、正常な紐付け済みタスクは affinity を維持します。これらの戦略は provider enforcement を回避しません。 @@ -229,9 +249,9 @@ affinity を維持します。これらの戦略は provider enforcement を回 |キー |タイプ |デフォルト |説明 | | --- | --- | --- | --- | | `anthropicAccountPool.enabled?` | `boolean` | `false` | スティッキー セッション アフィニティと使用量に基づく新規セッション選択を有効にします。**429 フェイルオーバーはここでは制御しません**: 使用可能なアカウントが 2 つ以上あれば他の複数資格情報プロバイダーと同様に有効になり、無効にはできません。 | -| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` |新しいセッションでは、アクティブなアカウントがこのしきい値に達すると、設定した期間で既知のキャッシュ使用量が最も低いアカウントを選択します。 `0` はクォータ選択を無効にします。 | -| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` |新しいセッション戦略。`quota` は `quotaWindow` で指定した期間(既定は 5 時間足)でアカウントを順位付けし、`fill-first` も同じ期間で使い切りのしきい値を判定します。 | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` |使用量ベースのアカウント選択で使う、プロバイダー報告のキャッシュ済み使用率です。`five-hour` は従来の動作を維持します。`weekly` は週次使用量を使い、他に対象アカウントが残る間だけ 5 時間使用量が上限に達したアカウントを除外し、残らない場合はそれらへフォールバックします。`max-utilization` は判明している値のうち最も高いものを使うため、週次使用量が未取得でも 5 時間使用量を利用できます。どちらも不明なら unknown の順位付けに従います。既知の使用量は unknown より先ですが、対象がすべて unknown でも対象順の先頭を選択します。記載した 5 時間使用量による同点判定後も完全に同点なら、対象順を維持します。正常な affinity セッションを先回りして再配置することはありません。新規セッションの割り当てと、対象となる 429 代替後のルーティング復旧では、`quota` はこの期間で対象候補を直接順位付けし、`fill-first` はこの期間のしきい値と上限到達ルールを使って安定順に進み、`round-robin` はこの設定を無視します。クールダウン、フェイルオーバー上限、再認証の適格性は別のローカル状態です。アカウント別の週次使用量は、ダッシュボードのプロバイダーページで取得した後にのみ利用できます。 | +| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | 新規セッションでは、アクティブアカウントがこのしきい値に達すると、設定した期間の既知のキャッシュ済み使用量が最小のアカウントを選びます(自身のしきい値未満のアカウントを優先します)。選択先自体がしきい値以上である必要はありません。`0` は使用量ベースの先行切り替えのみを無効にし、新規セッションの選択と対象となる 429 後の復旧では引き続き `quotaWindow` を参照します。 | +| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | 新規セッション戦略。`quota` は `quotaWindow` の使用量が実効 `autoSwitchThreshold`(既定 80)に達するか処理不能になるまでアクティブアカウントを維持し、その後は自身のしきい値未満のアカウントを優先して最小使用量へ移ります。使用量不明なら維持します。`round-robin` は使用量のしきい値を参照せず新規セッションをローテーションします。`fill-first` は `quotaWindow` で使い切りしきい値を判定します。 | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` |使用量ベースのアカウント選択で使う、プロバイダー報告のキャッシュ済み使用率です。`five-hour` は従来の動作を維持します。`weekly` は週次使用量を使い、他に対象アカウントが残る間だけ 5 時間使用量が上限に達したアカウントを除外し、残らない場合はそれらへフォールバックします。`max-utilization` は判明している値のうち最も高いものを使うため、週次使用量が未取得でも 5 時間使用量を利用できます。どちらも不明なら unknown の順位付けに従います。既知の使用量は unknown より先ですが、対象がすべて unknown でも対象順の先頭を選択します。記載した 5 時間使用量による同点判定後も完全に同点なら、対象順を維持します。正常な affinity セッションを先回りして再配置することはありません。`quota` が代替を選ぶとき(アクティブアカウントがしきい値に達したか処理不能な新規セッション、または対象となる 429 後の復旧)、自身のしきい値未満の候補を優先し、この期間で順位付けし、`fill-first` はこの期間のしきい値と上限到達ルールを使って安定順に進み、`round-robin` はこの設定を無視します。クールダウン、フェイルオーバー上限、再認証の適格性は別のローカル状態です。アカウント別の週次使用量は、使用量プローブまたは観測したレスポンスヘッダーから取得します。 | | `anthropicAccountPool.stickyLimit?` | `number` | `1` |成功した新しいセッションのバインドは 1 つのラウンドロビン選択で保持されます。範囲は 1 ~ 100。 | 共有の5時間・週次クォータが拒否された429だけがアカウントのクールダウンと切り替えを行います。一時的な速度制限はアフィニティを維持して送信受付だけを停止し、リクエストごとに短い同一アカウント再試行1回と別の対象アカウントへの切り替え1回までです。根拠ヘッダーのない429は同一アカウントで1回だけ再試行し、アカウントを冷却せず、Retry-Afterも生成しません。既定の単一アカウント動作は変わりません。Fable専用の拒否はSonnetを制限しません。手動選択とアフィニティもリクエストモデルの共有・ファミリークォータを確認します。パッシブなファミリー情報は30分または既知のリセットで期限切れとなり、1つの送信リクエストで再確認します。使用量しきい値はソフトな優先設定で、全候補消耗時のフォールバックを維持します。使用量・課金のハード上限ではありません。アフィニティはプロセスローカルであり、サイズ制限があります。トークン更新の失敗は既存の再認証ルールに従います。確認済みの契約・アカウント請求の 403 は出力前に別アカウントへ切り替え、`Retry-After` または既定の10分間のクールダウンを記録します。一般的な権限拒否では切り替えません。すべての対象となるアカウントが冷却されている場合、クライアントは、既知の場合、認証エラーではなく、`Retry-After` を含む 429 を受け取ります。 @@ -490,7 +510,9 @@ Vercel AI Gateway は、1 つのモデルを複数の基盤となる推論プロ 適用済みの上書きとまだ一致する場合にのみ、元のネイティブ名が復元されます。外部で変更された表示名にも既存のネイティブメタデータ正規化が適用されます。 例えば Astra (`gpt-6-astra`) では、固定されたネイティブ名と異なる名前は引き続きその固定名に置き換えられます。 表示名の上書きによってモデル ID、メタデータ(機能を含む)、順序、ルーティングされたコンボのエイリアス、アカウント修飾付きの行は変更されません。 -このローカルカタログの上書きは、HTTP のモデル一覧や仮想 `*-pro` 行の表示名には適用されません。 +`GET /api/models` もプレフィックスなしのネイティブ行に空でない上書き名を返すため、クライアントのエクスポートと `ocx opencode` はその名前を使います。 +OpenCode は `sol (native)` のように既存の接尾辞を保持します。`ocx opencode` を再起動するか、管理対象の連携を更新すると生成設定に反映されます。 +上書きがない場合の表示名、`/v1/models`、仮想 `*-pro` 行は変わりません。 プレビュー GPT-5.6 フォールバック エントリは同じメカニズムを使用します。 OpenAI API キー プリセットは、ベース ID と Pro ID にコンテキスト `1050000` と最大入力 `922000` をシードします。 OpenRouter は、コンテキスト `1050000` を持つ `openai/gpt-5.6-sol`、`openai/gpt-5.6-terra`、および `openai/gpt-5.6-luna` をシードします。ネイティブのプール/ダイレクトのウィンドウは[予約 OpenAI プロバイダーのポリシー](/reference/configuration/providers/#reserved-openai-providers)に従います。同期されたカタログは、`xhigh` を区別しつつ、`max` をアドバタイズします。 diff --git a/docs-site/src/content/docs/ja/reference/configuration/server.md b/docs-site/src/content/docs/ja/reference/configuration/server.md index f7f1665247..1a3028c97d 100644 --- a/docs-site/src/content/docs/ja/reference/configuration/server.md +++ b/docs-site/src/content/docs/ja/reference/configuration/server.md @@ -15,7 +15,7 @@ description: リスナー、リモート アクセス、アドミッション | `emptyCompletionRetry?` | `boolean` | `false` | テキストもツール呼び出しもない Responses ターンを、ターミナルイベント前にストリームが終了した場合も含め、同一リクエストで 1 回再試行するよう明示的に有効化します。再試行は課金対象になる場合があります。`OCX_EMPTY_COMPLETION_RETRY=0` で設定を変更せず無効化できます。combo と routed-compaction turn は対象外です。 | | `dropCodexSafetyBuffering?` | `boolean` | `false` | Codex Responses パススルーから Codex の safety-buffering ヒントを除去します。対象は `x-codex-safety-buffering-enabled` / `x-codex-safety-buffering-faster-model` 応答ヘッダー、`safety_buffering` 型の `response.metadata` SSE イベント、およびその他の SSE イベントにある `safety_buffering` フィールドです。Codex TUI はこれらを、既定の操作でセッションをより弱いモデルに切り替える「より高速なモデルで再試行」プロンプトとして表示します。その他の `x-codex-*` ヘッダーと SSE イベントの内容は、そのフィールドの除去を除いて変更せずに転送されます。既定ではオフです。 | | `stallTimeoutSec?` | `number` | `300`(public)/ 無効(local) | ストリームが遮断されるまでの、有効な上流進捗がない秒数(Responses とネイティブ Chat)。未設定では**ローカル**上流(loopback・プライベート・`.local`/`.lan` 名)は無効が既定、public 上流は 300 秒。正の値は両方に適用(最小 1 秒)、`0` で無通信 watchdog を全面無効化。canonical ChatGPT SSE を非ストリーミング JSON にまとめる Responses リクエストには、watchdog が無効でも独立した 15 分の全体上限が残る。`/v1/responses/compact` の保留ボディ読み取りもこの予算を共有するが、ローカル上流でも既定は 300 秒。明示値(`0` を含む)が優先される。 | -| `connectTimeoutMs?` | `number` | `200000` |試行ごとの DNS/TCP/TLS/最終ヘッダーの期限。本体が生成される前に終了します。 | +| `connectTimeoutMs?` | `number` | `200000`(public)/ 無効(local) | リクエスト送信から上流が最初の応答ヘッダーを返すまでの試行ごとの期限(DNS/TCP/TLS とヘッダー待ち)。本体生成の前に終了し、本体ストリームを制御する `stallTimeoutSec` とは無関係です。未設定では**ローカル**上流(loopback・プライベート・`.local`/`.lan` 名)は無効が既定、public 上流は 200 秒。正の値は両方に適用、`0`(または任意の非正値)でヘッダー期限を全面無効化します。無効にすることで、ローカルモデルが大きなプロンプトで数分の prompt prefill を行っても、最初のヘッダーのタイマーが健全なリクエストを切断しません。 | | `shutdownTimeoutMs?` | `number` | `5000` |アクティブなターンが中止される前の正常な排出期限。 | | `websockets?` | `boolean` | `false` | クライアント向け Responses WebSocket パスを広告して許可します。false の場合クライアントは HTTP/SSE を使いますが、対象となる canonical ChatGPT upstream WS 最適化は無効にしません。 | | `corsAllowOrigins?` | `string[]` | `[]` | 追加の正確な CORS origin。ループバック origin は常に許可します。`chrome-extension://` など authority ベースのブラウザー拡張 origin に対応し、`*` はワイルドカードではありません。Firefox と Safari は拡張 UUID を(インストール/ブラウザー起動ごとに)再生成するため、origin が変わったらエントリを更新してください。 | @@ -26,11 +26,13 @@ description: リスナー、リモート アクセス、アドミッション | `serviceHealthRecovery.enabled?` | `boolean` | `false` | バックグラウンドサービス向けのオプトイン復旧。小さな監視プロセスが `/healthz` を確認し、プロキシが生きたまま連続プローブに約 1 分間まったく応答しない場合に終了させ、サービスマネージャー(タスク スケジューラ、launchd、systemd、WinSW)に再起動させます。管理対象サービスの子プロセスでのみ起動し、停止したプロセスが保持していたリクエストは再送しません。1 時間あたり最大 3 回。再起動が必要です。自動復旧には数値のバインドアドレス(または既定の localhost/ワイルドカード マッピング)が必要です。DNS バインド名は監視されません。記録されたアドレスまたはポートが変更されると監視が停止します。 | | `codexAutoStart?` | `boolean` | `true` | Codex を起動する前に、Codex シムで `ocx ensure` を実行させます。 False を指定すると、操作が行われないことが保証されます。 | | `codexShimAutoRestore?` | `boolean` | `true` |完了した外部 Codex アップデートによってインストールされたシムが置き換えられた後、インストールされているシムを復元します。環境オプトアウト: `OPENCODEX_CODEX_SHIM_AUTO_RESTORE=0`。 | +| `nativeMainRefresh?` | `"codex" \| "opencodex"` | auto | `CODEX_HOME` 内のネイティブ メイン ChatGPT ログインを更新する主体を選択します。キーリングの応答はその照会だけに適用されます。トークンがなければその認証情報の準備は失敗しますが、次の照会が同じトークンを返しても利用できます。永続的な拒否状態は保持せず、準備済みのリクエストは完了できます。ファイルベースの動作は変わりません。自動選択を含む動作の詳細は[英語版 Server fields](/reference/configuration/server/#server-fields)を参照してください。 | | `syncResumeHistory?` | `boolean` | `true` | Codex App 履歴の互換性を元に戻すことができます。元のメタデータは `ocx stop` / `ocx restore` によってバックアップおよび復元されます。 | | `shadowCallIntercept?` | `{ enabled?: boolean; model?: string; sourceModels?: string[] }` |オフ |認識された Codex ヘルパー/シャドウ呼び出しを、リクエストに設定された推論エフォートを維持したまま選択したモデルにリダイレクトします。デフォルトのソースプレフィックスは `gpt-6-luna`, `gpt-5.6-luna` です。0.144.x 以前のクライアントでは `gpt-5.4-mini` が使われており、`sourceModels` で復元できます。 | | `webSearchSidecar?` | `OcxWebSearchSidecarConfig` |使用可能な場合はオン | Web 検索サイドカー オプション。 | | `visionSidecar?` | `OcxVisionSidecarConfig` |使用可能な場合はオン |画像説明サイドカー オプション。 | | `images?` | `OcxImagesConfig` | OpenAI の自動選択 | Codex `image_gen` のスタンドアロン イメージ リレー オプション。 | +| `telemetry?` | `OcxTelemetryConfig` | 人間への通知後に既定でオン | 匿名の1日ごとの利用統計テレメトリの同意状態(`decision`、`decidedAt`、`noticeShownAt`)。人が通知を見るか同意するまで何も送信されません。`OCX_TELEMETRY=0` または `DO_NOT_TRACK=1` で上書きされます。[テレメトリ (`telemetry`)](#テレメトリ-telemetry) と [テレメトリとプライバシー](/ja/guides/telemetry/) を参照してください。 | バックアップ サポートが存在する前に古い開発ビルドで再開履歴メタデータが変更された場合は、`ocx recover-history --legacy-openai --yes` を実行してネイティブ プロバイダーの回復を強制します。 このコマンドは、正当な専用プロバイダー履歴を含む、ユーザーメッセージを持つすべての `opencodex` 行を再ラベル付けします。実行前にライフサイクル リファレンスの全範囲に関する警告を確認してください。 @@ -93,6 +95,35 @@ ssh -L 20100:localhost:10100 -L 1455:localhost:1455 you@remote プレーン `ssh -L` はローカル ループバックでリッスンし、デフォルトの非認証バインドに対して安全です。 `ssh -g -L`、ブロードコンテナパブリッシング、または `0.0.0.0` でクライアント側を公開する転送モードを使用しないでください。不明な場合は、`ssh -L 127.0.0.1:20100:localhost:10100` と明示的にバインドします。 ::: +## テレメトリ (`telemetry`) + +匿名の1日ごとの利用統計テレメトリは、人が通知(GUI ポップアップまたは対話型ターミナルのプロンプト)を見た後にのみ既定でオンになります。`config.json` の `telemetry` ブロックはこの同意状態を記録します。 + +```json +{ + "telemetry": { + "decision": "accepted", + "decidedAt": "2026-11-07T09:00:00.000Z", + "noticeShownAt": "2026-11-07T09:00:00.000Z" + } +} +``` + +| フィールド | 型 | 既定値 | 説明 | +| --- | --- | --- | --- | +| `telemetry.decision?` | `"accepted" \| "declined"` | 未設定(未決定) | 明示的なユーザーの選択。`"declined"` はテレメトリを無効化し `/telemetry-id.json` を削除します。`"accepted"` は日次レポートを有効化します。 | +| `telemetry.decidedAt?` | `string` (ISO 8601) | 未設定 | `decision` が記録された UTC タイムスタンプ。`decidedAt ?? noticeShownAt` の UTC 日より後の完了済み UTC 暦日(`day > formatUtcDay(decidedAt ?? noticeShownAt)`)のみが送信され、同意当日およびそれ以前の日は送信されません。 | +| `telemetry.noticeShownAt?` | `string` (ISO 8601) | 未設定 | ウェブダッシュボードまたは対話型ターミナルで人間が開示通知を見た UTC タイムスタンプ。`decision` が未設定の場合、`noticeShownAt` が設定されているときのみ送信され(`default-on`)、未設定なら `awaiting-notice` のまま待機します。 | + +コレクターのエンドポイント(`https://telemetry.opencodex.me/v1/events`)はコード定数であり、`config.json` では変更できません。 + +2 つの環境変数が `config.json` より優先され、保存済み `config.json` を変更せずにテレメトリを即座に無効化します(起動時またはスケジューラのティックで検出されると `/telemetry-state.json` に当日の UTC 日を `ineligibleThroughDay` として記録し `/telemetry-id.json` を削除するため、後から変数を解除してもその期間の日次データは送信されず新しい ID が発行されます)。 + +- `OCX_TELEMETRY=0`(大文字・小文字を問わず `false`、`off`、`no` も可) +- `DO_NOT_TRACK=1`(大文字・小文字を問わず `true`、`yes` も可) + +`ocx config set telemetry` と `ocx config unset telemetry` は拒否され、`ocx config import` もすべての呼び出し元でインポートされた `telemetry` ブロックを無視して既存の状態を保持します。代わりに `ocx telemetry enable`(対話型ターミナルが必須で開示と確認を表示し、それ以外は `agent_consent_required` / `tty_required` で終了)、`ocx telemetry disable`、`ocx telemetry status [--json]`、またはダッシュボードの **プロキシ詳細** トグルを使用してください。ペイロードスキーマと保持ポリシーの詳細は [テレメトリとプライバシー](/ja/guides/telemetry/) を参照してください。 + ## ストレージのクリーンアップ `storageCleanupPolicy` はデフォルトでは無効になっています。有効にすると、アーカイブされたバイト数が `trigger.archivedBytesOver` を超えた後、`startup`、`daily`、`weekly`、または `manual` で実行されます。 `target.reduceToBytes` または `target.removeOldestPercent` のいずれかに向かって最も古いアーカイブが選択されます。 `mode` のデフォルトは `quarantine` です。 `permanent` は、明示的な破壊的な選択としてのみ使用してください。ポリシーは `lastRun` および `nextRun` を維持します。 [ストレージ] ページまたは `GET`/`PUT /api/storage/cleanup-policy` で設定します。 `POST /api/storage/cleanup-policy/run` を使用して手動実行をトリガーします。 @@ -245,3 +276,11 @@ CLI 内部の再試行・ツールターンは要求全体の送信回数上限 完全だが不正な記録(最終行の `null` も含む)は上限付きの受け入れを拒否します。圧縮は有効な残高を保持して続行し、 実行中の拒否はクリーンなジャーナルを再起動で読み直すまで残ります。途中で切れた最終 JSON 行は従来の復旧規則に従います。 詳しい境界とエラーは[英語の正本](/reference/configuration/server/#historical-pool-continuity)を参照してください。 + +## ローカル upstream のタイムアウト分類 + +この分類はタイムアウト方針であり、ネットワークアクセスの許可ではありません。DNS を参照せず HTTP(S) の宛先を分類します。正確な `localhost`(大文字小文字と末尾のドットを許容)、`0.0.0.0`、IPv4 loopback (127/8)、RFC 1918 private、link-local (169.254/16)、IPv6 loopback、link-local (fe80::/10)、unique-local (fc00::/7)、IPv4-mapped アドレス、`.local`/`.lan` 名がローカルです。他の DNS 名は loopback に解決されても公開向けの期限を維持します。不正な宛先、非対応スキーム、`localhost.example` も同様です。 + +ヘッダー期限を無効にしてもクライアントのキャンセルと上位の全体期限は維持されます。明示的な正の `stallTimeoutSec` はローカル本文の無応答を制限します。ローカルの header/stall が未設定なら、ヘッダー到着前の自動期限はありません。ネイティブ Chat/Messages のローカル JSON 読み取りは stall 予算を使用し、公開 JSON 読み取りは従来の `max(connectTimeoutMs ?? 200000, 5000)` を維持します。Compact 本文の既定 300 秒と画像・検索 sidecar の予算は変わりません。 + +任意の `opencodeClientExport` は `headerTimeoutMs`、`chunkTimeoutMs`、`timeoutMs` に正のミリ秒または無効化する `false` を指定できます。省略時は OpenCode の既定値を維持し、不正なフィールドは出力しません。V1 options と V2 settings の provider 全体に適用します。[遅いローカルモデル](/guides/opencode/#slow-local-models-prefill-timeouts)を参照してください。 diff --git a/docs-site/src/content/docs/ja/reference/inbound-body-admission.md b/docs-site/src/content/docs/ja/reference/inbound-body-admission.md index c458b118b0..f2ac83d554 100644 --- a/docs-site/src/content/docs/ja/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/ja/reference/inbound-body-admission.md @@ -5,22 +5,55 @@ description: リクエスト本文の上限引き上げが、同時 HTTP リク [プロバイダー設定リファレンス](/ja/reference/configuration/providers/)では、受信する JSON 本文 1 件のデコード後の最大サイズである `maxInboundBodyBytes` を説明しています。デフォルトは引き続き 256 MiB で、設定可能な値は 1 MiB から 512 MiB です。変更後はプロキシを再起動し、リスナーと読み取り処理の両方に意図した上限を適用してください。 +従来の共有予算のデフォルト 512 MiB を維持しても、以下に説明するキューやレスポンスのライフサイクル中の予約保持に伴う制約は残ります。 + +## 共有予算を明示的に選ぶ + +`maxConcurrentInboundBodyBytes` は、バイト単位で指定する `config.json` の任意の**トップレベル**設定です。デフォルトは従来と同じ **512 MiB (`536870912`)** です。省略、`0`、無効な値の場合はこのデフォルトを使います。有効な正の整数は、使用時に **512 MiB〜2 GiB (`536870912`〜`2147483648`)** の範囲に制限されます。設定後はプロキシを再起動してください。同一プロセス内のすべてのリスナーは 1 つの予算を共有し、`appOwnedMemoryBudgetMb` とは別に扱います。 + +リクエストごとの上限を 512 MiB にし、共有予算を明示的に 2 GiB にするには、既存の `config.json` のトップレベルに次のフィールドを追加し、再起動します。 + +```json +{ + "maxInboundBodyBytes": 536870912, + "maxConcurrentInboundBodyBytes": 2147483648 +} +``` + +これはメモリ使用量のピークが増える可能性を踏まえた運用者の選択です。プロキシは利用可能な RAM を自動検出せず、それに応じた予算も選びません。 + ## 上限を引き上げると同時実行数が変わる -解決された上限が 256 MiB を超える場合、対象の各 HTTP リクエストは、プロセス全体で共有する 512 MiB の受け入れ予算から、設定した許容量の全量を予約します。複数のリスナーが同じプロセスを共有する場合も、同時に実行できる対象リクエストは最大 1 件です。小さな本文でも許容量全体を予約し、小さい Content-Length や圧縮によって受け入れ制御を回避することはできません。予約は JSON の解析直後ではなく、レスポンスストリームが終了、失敗、またはキャンセル処理を完了するまで続きます。 +適用される上限が 256 MiB を超える場合、対象の各 HTTP リクエストは、**本文を読み取る前に**リクエストごとの許容量全体を予約する必要があります。予約はプロセス全体の `maxConcurrentInboundBodyBytes` 予算を共有し、デフォルトは引き続き **512 MiB** です。 + +サイズを制限した JSON 解析が完了するまでは、`Content-Length` や圧縮された転送本文が小さくても予約量を減らしません。これらの値を、デコード後や正規化後の JSON サイズの根拠として信頼することはありません。 + +サイズ制限内で JSON 解析に成功すると、読み取り処理は、実測した転送バイト数とデコード後のバイト数のうち大きい値まで予約量を減らします。変換処理が正規化 JSON の測定用予算を渡した場合は、既存の正規化 JSON の測定値も含めた最大値を使います。予約量は最初のリクエスト許容量を上限として減ることしかなく、正規化後の測定値がその上限を超えても増えません。既存の UTF-8 と JSON 再シリアル化の検査は維持され、入力バイト長を、より大きくなり得る正規化 JSON サイズの代わりには使用しません。 + +**デフォルトの共有予算 512 MiB** と**リクエストごとの上限 512 MiB** では、許容量全体を予約できる未解析のアップロードは **1 件だけ**です。解析後の予約が **1 バイト**まで減っても、残りの容量は 512 MiB 未満です。次の完全な許容量は、十分な容量が解放されるまで待つ必要があります。そのため、デフォルトではリクエストごとの上限が 512 MiB の場合の元の同時実行問題は**解決しません**。 + +`maxConcurrentInboundBodyBytes` に `2147483648` を明示すると **2 GiB** を選択し、解析と実測による予約削減の前に **512 MiB 全体を予約するアップロードを最大 4 件**受け入れられます。この 2 GiB 予算は、解析後の同時実行数を 4 件に固定しません。例えば、先に解析したリクエストの予約量が減って次の受け入れに余裕ができれば、共有予算と他の制限の範囲内で、**非常に小さいリクエスト 8 件が同時にレスポンスをストリーミング**できます。 + +減量後の予約は、非同期処理やプロバイダーの応答待ちの間も保持され、レスポンスストリームの EOF、エラー、またはキャンセル処理の完了時に解放されます。解析だけでは解放されません。クライアントが切断しても、生成側のキャンセル処理が完了するまで保持されます。エラー、中断、キャンセルが競合しても、解放は正確に 1 回だけ行われます。 対象となる POST エンドポイントは `/v1/responses`、`/v1/responses/compact`、`/v1/chat/completions`、`/v1/messages`、`/v1/messages/count_tokens`、`/v1/images/generations`、`/v1/images/edits`、`/v1/alpha/search` です。画像、検索、トークン計数には、従来の設定可能な本文ごとの上限も適用されます。内部の直接変換やコンボ呼び出しは、HTTP の許容量を二重に予約しません。管理、音声、コンテキスト履歴、WebSocket の制限は変わりません。 -設定を省略またはゼロにした場合、あるいは解決された上限が 256 MiB 以下の場合、この追加の同時実行ゲートは有効になりません。既存のリクエスト件数やその他のリソース制限は引き続き適用されます。 +この追加の同時実行ゲートは、適用される `maxInboundBodyBytes` が 256 MiB を超える場合にのみ有効です。このリクエスト単位の設定を省略するか `0` にすると、デフォルトの 256 MiB が使われ、ゲートは無効のままです。一方、`maxConcurrentInboundBodyBytes` を省略または `0` にすると共有予算のデフォルト 512 MiB が選ばれ、有効なゲートを無効にはしません。既存のリクエスト件数やその他のリソース制限は引き続き適用されます。 ## 一時的な拒否と大きすぎる本文の違い -許容量が一時的に使えない場合、プロトコル解析やプロバイダーへの送信前に、HTTP **503**、`Retry-After: 1`、エラーコード `server_busy` が返されます。Messages とトークン計数のクライアントには、型が `overloaded_error` の Anthropic 形式のエラーが返されます。OpenAI 互換クライアントには `server_error` が返されます。リトライヘッダーとクライアント側のバックオフに従い、現在のリクエストが完了してから再試行してください。本文の上限をさらに引き上げても、予算不足は解消しません。 +許容量全体を一時的に予約できない場合、リクエストは **最大 32 件の FIFO 待機キュー**に入り、**最大 120 秒**待機できます。待機中はアプリケーションがリクエスト本文を読み取りません。測定後の予約量削減や最終解放で空きができると、待機順に受け入れます。待機中に中断されたリクエストはキューから除去され、未読の本文は消費せずキャンセルされます。 -本文がリクエスト単位の上限を超えた場合は、従来どおり HTTP **413** になります。宣言されたサイズが上限超過なら、混雑による拒否には置き換わりません。切断時のキャンセル動作も従来どおりです。認証とオリジンの確認は、この同時実行ゲートより先に行われます。 +キューが満杯、または待機時間が満了すると、本文の解析やプロバイダーへの送信前に HTTP **503**、`Retry-After: 1`、エラーコード `server_busy` が返されます。拒否時には未読の本文がキャンセルされます。Messages とトークン計数のクライアントには、型が `overloaded_error` の Anthropic 形式のエラーが、OpenAI 互換クライアントには `server_error` が返されます。認証とオリジンの確認は、受け入れやキューへの追加より先に行われます。 + +再試行時は、リトライヘッダーとクライアント側のバックオフに従ってください。上限のある待機と実測に基づく予約量の削減は、回避可能な容量不足による拒否を減らしますが、すべての 503 をなくすものではありません。リクエスト単位の上限をさらに引き上げても、継続的な容量不足は解決しません。 + +本文がリクエスト単位の上限を超えた場合は、従来どおり HTTP **413** になります。宣言されたサイズが上限超過なら、混雑による拒否には置き換わりません。 ## 予算が測るもの -512 MiB は受け入れたリクエストごとの許容量の合計であり、**プロセスのメモリ使用量が 512 MiB 未満に収まる保証ではありません**。デコード、文字列、オブジェクトグラフ、リクエストのコピー、その他のアプリケーション状態には追加のメモリが必要です。既存の UTF-8 と JSON の再シリアル化による測定は維持されます。入力のバイト長を、より大きくなり得る正規化後の JSON サイズの代わりには使用しません。 +設定した予算は受け入れを計上するもので、解析前は許容量全体、解析後は実測に基づく予約量を合算します。**2 GiB や設定容量を事前に割り当てるものではなく**、**プロセス RSS や解析済みオブジェクトのヒープの上限でもありません**。デコード、文字列、オブジェクトグラフ、リクエストのコピー、その他のアプリケーション状態には追加のメモリが必要で、実際のメモリ使用量は予算を超えることがあります。 + +共有予算のデフォルト 512 MiB に代えて 2 GiB を選ぶと、予約できる合計量は 4 倍になります。リクエストごとの上限が 512 MiB なら、この明示的な選択により解析前の完全なアップロードを 1 件に代えて最大 4 件受け入れ、メモリ使用量のピークが増える可能性があります。運用環境のメモリの余裕に応じて予算を選んでください。リクエストごとの上限が 256 MiB 以下なら、共有予算の設定にかかわらず追加ゲートは無効です。 -小さなリクエストを並列実行する場合は、可能な限りデフォルトの上限を維持してください。長い履歴を扱うために引き上げる際は、追加の同時実行制限を理解したうえで設定してください。 +可能な限り、リクエスト単位のデフォルト上限を維持してください。長い履歴を扱うために引き上げる場合は、メモリ使用量のピークが大きくなる可能性と待機の上限を考慮してください。 diff --git a/docs-site/src/content/docs/ja/reference/management-api.md b/docs-site/src/content/docs/ja/reference/management-api.md index 86e5f8c183..d3e4013024 100644 --- a/docs-site/src/content/docs/ja/reference/management-api.md +++ b/docs-site/src/content/docs/ja/reference/management-api.md @@ -247,15 +247,19 @@ Aside プロファイルの変更はこの場合でも一つだけ保存しま | `GET /api/oauth/status` | 1 つのプロバイダーの OAuth フローをポーリングする | 400 不明なプロバイダー | | `POST /api/oauth/logout` |選択したプロバイダー資格情報を削除します | 400 不明なプロバイダー。 `oauth_mutation_busy` | | `GET, DELETE /api/oauth/accounts` | マスクされたアカウントを一覧表示するか、アカウントを 1 つ削除する Kiro の行には自動選択の `autoSelectable` と、除外時には閉じた集合の `skipReason` が含まれます。アクティブな単一アカウントは送信を続けられ、クォータ取得は任意です。 | 400 無効なプロバイダー/ID。 404 アカウントがありません。 `oauth_mutation_busy` | -| `PUT /api/oauth/accounts/active` |アクティブな OAuth アカウントを選択します | 400 無効なプロバイダー/アカウント。 `oauth_mutation_busy` | +| `PUT /api/oauth/accounts/active` |アクティブな OAuth アカウントを選択します | 400 無効なプロバイダー/アカウント。 `oauth_mutation_busy`; 503 `affinity_reset_not_persisted` (Anthropic: `selectionCommitted: true`, `retryable: true`; アカウント選択は保存済み。すでに有効でも同じリクエストを再送信) | | `GET, PUT, PATCH /api/oauth/accounts/pool` | Anthropic OAuth プール ポリシーの読み取りまたは更新 | 400 非 Anthropic プロバイダーまたは無効なポリシー | | `POST /api/oauth/accounts/clear-cooldown` | 1 つの OAuth アカウントのランタイム クールダウンをクリアする | 400 無効なプロバイダー/アカウント | | `PUT /api/oauth/accounts/alias` | OAuth アカウント エイリアスを設定またはクリアする | 400 無効なプロバイダー/アカウント/エイリアス | -| `PUT /api/oauth/accounts/pause` | Anthropic または汎用 OAuth アカウントを一時停止・再開。Body `{ provider, accountId, paused }`。アクティブなアカウントを停止すると、利用可能な別のアカウントがあれば切り替えます。 | 400 未対応のプロバイダーまたは無効な body;404 アカウントなし;`oauth_mutation_busy` | +| `PUT /api/oauth/accounts/pause` | Anthropic または汎用 OAuth アカウントを一時停止・再開。Body `{ provider, accountId, paused }`。アクティブなアカウントを停止すると、利用可能な別のアカウントがあれば切り替えます。 | 400 未対応のプロバイダーまたは無効な body;404 アカウントなし;`oauth_mutation_busy`; 503 `affinity_reset_not_persisted` (Anthropic: `pauseCommitted: true`, `retryable: true`; 一時停止状態は保存済み。同じアカウントと停止状態を維持し、`retryAffinityReset: true` を追加して再送信。サーバー再起動後もリセットを確認) | | `GET, POST, DELETE /api/providers/keys` |マスクされたプロバイダー キーを一覧表示し、1 つを追加/アクティブ化するか、1 つを削除します。 400 無効な入力。 404 プロバイダー/キーがありません | | `PUT /api/providers/keys/active` |プロバイダーのアクティブなキーを選択します | 400 無効な入力。 404 プロバイダー/キーがありません | | `PUT /api/providers/keys/alias` |プロバイダー キー エイリアスを設定またはクリアする | 400 無効な入力。 404 プロバイダー/キーがありません | +| `PUT /api/providers/keys/pause` | プロバイダー API キーを一時停止または再開します。Body `{ name, id, paused }`。アクティブなキーを一時停止すると、リング順で次の利用可能なキーを選択します。成功時は結果の `activeAccountId`(該当なしの場合は `null`)と `activeAccountChanged` を返します。 | 400 無効な入力。404 プロバイダー/キーがありません | | `GET, POST, PATCH, DELETE /api/keys` |データ プレーン アドミッション キーの一覧表示、作成、編集、または削除 | 400 無効な本文/ID。 404 キーがありません | +| `PUT /api/oauth/accounts/affinity-reset` | アカウントを必要とせず provider 全体の会話接続リセットの保存を確認します。Body `{ provider }`。成功時 `affinityResetConfirmed: true`. CLI: `ocx account reset-affinity anthropic --json` (`anthropic2` supported). | 400 invalid body/provider; 503 `affinity_reset_not_persisted`, `retryable: true` | + +ダッシュボードは、対象アカウントが消えてもリセットの保存が確認されるまで警告を保持します。一覧の読み込み失敗や、アクティブアカウントの一時停止・再認証時も通知と再試行を保持します。一覧で不在を確認した後の再試行は、`{ provider }` で `PUT /api/oauth/accounts/affinity-reset` を呼び、`affinityResetConfirmed: true` を受け取った場合のみ警告を消します。この操作は最初の失敗後に作られた接続を含む全接続を消しますが、アカウントの選択・再開は行わず、一覧が空でも実行できます。未確認のリセットがある状態での削除は `retryAffinityReset=true` を送り、保存失敗時は 503 `affinity_reset_not_persisted`、`deletionCommitted: true`、`retryable: true` を返します。アカウントは削除済みなので、削除ではなくリセット専用 API を再試行してください。通常の削除は残るアカウントの接続を保持します。対象は登録済み Anthropic OAuth インスタンスに限り、既存の管理認証とオリジン検査を維持します。 資格情報リストの応答は意図的にマスクされます。 OAuth アクセス トークンと完全なプロバイダー API キーはダッシュボード クライアントに返されません。 diff --git a/docs-site/src/content/docs/ja/reference/proxy-formats.md b/docs-site/src/content/docs/ja/reference/proxy-formats.md index 50ddb2fe2c..3b90fa2390 100644 --- a/docs-site/src/content/docs/ja/reference/proxy-formats.md +++ b/docs-site/src/content/docs/ja/reference/proxy-formats.md @@ -150,6 +150,8 @@ WebSocket が無効になっている場合、アップグレード試行では 非ストリーミング出力には `object: "chat.completion"` があります。ストリーミング出力では、`object: "chat.completion.chunk"` の SSE オブジェクト、選択デルタ、`finish_reason`、および `data: [DONE]` の端末選択を使用します。ツール呼び出しと使用情報は、ソース イベントが伝達する場所に変換されて戻されます。 +このエンドポイントのエラー応答とストリーミングのエラーフレームは、プロキシが作成したメッセージを使います。プロキシはプロバイダーの失敗を、レート制限、クォータまたはクレジットの枯渇、コンテキストウィンドウ超過、モデル利用不可、利用できない地域、アカウント確認が必要、などの固定の状態に分類し、その状態の固定メッセージを返します。ポリシーによる拒否、再送の拒否、プロキシの制限にはそれぞれ固定メッセージがあります。HTTP ステータス、`error.type`、`error.code`、`Retry-After` の意味は変わらないため、`context_length_exceeded`、`insufficient_quota`、`rate_limit_exceeded` などのコードで分岐するクライアントはこれまでどおり動作します。 + 内部実行パスは応答ベースであるため、プロバイダー アダプターはより狭い機能セットを課すことができます。たとえば、選択したアダプタで表現できないリクエスト機能は、その意味を黙って変更するのではなく、エラーとして返されます。 ## `POST /v1/messages` および `count_tokens` @@ -239,6 +241,8 @@ Connections > API keys に音声入力とリアルタイム音声の項目があ ## `POST /v1/responses/compact` +compact リクエストに不正な OpenCodex 管理の retained-compaction 入力(`ocx2:`)が含まれる場合、HTTP 400(`error.type: "invalid_request_error"`)を返します。検証のタイミングとアカウントへの影響は[英語の正規リファレンス](/reference/proxy-formats/#post-v1responsescompact)を参照してください。 + 圧縮により、長い応答会話を短縮する必要があるクライアントの置換履歴が返されます。 |ルートの種類 |行動 | diff --git a/docs-site/src/content/docs/ja/troubleshooting/windows-memory.md b/docs-site/src/content/docs/ja/troubleshooting/windows-memory.md index 774933a39f..3bdc80e3f6 100644 --- a/docs-site/src/content/docs/ja/troubleshooting/windows-memory.md +++ b/docs-site/src/content/docs/ja/troubleshooting/windows-memory.md @@ -50,4 +50,4 @@ Windows では、#32111 クラッシュを回避するために、opencodex は Windows のサービスのインストール・修復と Codex shim のインストール・更新は、選択した実行ファイルが OpenCodex 設定ルート内でディレクトリを作成・削除できるか確認します。これはメモリ修正ではなく書き込みポリシーの確認です。失敗するとサービス停止、ダウンロード、ステージング、トークンやランチャーの書き込み前に拒否します。shim の自動修復は案内付きで延期され、起動は続行します。正常または無効な shim は検査しません。別のランタイムを自動探索しません。 初回のスケジューラーインストールでは、この確認の前にタスクを登録し設定ルートを確保します。拒否された場合は新しい登録を取り消し、確保したルートは再試行用に残します。 -> 選択した Bun ランタイムが設定ディレクトリ内でディレクトリを作成・削除できませんでした。Windows のアプリケーションポリシーがこの実行ファイルの位置からの書き込みを拒否している可能性があります。`ocx` 起動前にポリシーが許可する信頼できる Bun のパスを `OPENCODEX_BUN_PATH` に設定するか、`npm install -g @bitkyc08/opencodex` で再インストールして再試行してください。別のランタイムは選択していません。 +> 選択した Bun ランタイムが設定ディレクトリ内でディレクトリを作成・削除できませんでした。Windows のアプリケーションポリシーがこの実行ファイルの位置からの書き込みを拒否している可能性があります。`ocx` 起動前にポリシーが許可する信頼できる Bun のパスを `OPENCODEX_BUN_PATH` に設定するか、`npm install -g --allow-scripts=bun @bitkyc08/opencodex` で再インストールして再試行してください。別のランタイムは選択していません。 diff --git a/docs-site/src/content/docs/ko/contributing.md b/docs-site/src/content/docs/ko/contributing.md index cb8ba43379..1eabaa87db 100644 --- a/docs-site/src/content/docs/ko/contributing.md +++ b/docs-site/src/content/docs/ko/contributing.md @@ -12,7 +12,7 @@ bun install bun run setup:hooks # 기존 관리형 pre-push·post-merge 제거 bun run dev:proxy # 개발 모드 프록시 API bun run dev:gui # 대시보드 dev 서버(다른 터미널) -bun run typecheck # bun x tsc --noEmit +bun run typecheck # bun check --no-script --noEmit bun run test # 전체 테스트 스위트 (기본) ``` @@ -57,59 +57,10 @@ subsystem의 기존 테스트 근처에 집중된 회귀 테스트를 추가하 cd docs-site && bun install && bun dev ``` -## 문서 배포 +## CI / Release / Pages -공개 문서는 GitHub Pages의 에 게시됩니다. -`.github/workflows/deploy-docs.yml`은 `main` push에서 `docs-site/**`나 워크플로 자체가 바뀌면 -실행됩니다. `docs-site`를 빌드한 뒤 생성된 사이트를 배포합니다. 문서 변경을 push하기 전에 다음을 -실행하세요. +문서 배포, CI, 릴리스 및 브랜치 정책은 [영어 원문](/contributing/)을 참고하세요. -```bash -cd docs-site -bun install --frozen-lockfile -bun run build -``` - -## CI와 릴리즈 - -GitHub Actions는 필요한 작업만 수행합니다. - -- **Cross-platform CI**(`.github/workflows/ci.yml`)는 런타임, 테스트, 패키지, 스크립트, - TypeScript, 워크플로 파일이 바뀐 pull request와 `main` push에서 실행됩니다. Bun matrix는 Linux, - Windows, macOS에서 install, typecheck, tests, privacy scan, release helper build smoke, GUI build, - `ocx help`를 검사합니다. 별도의 3개 OS lane은 번들 런타임을 사용해 Bun을 따로 설치하지 않아도 - npm global install이 동작하는지 확인합니다. -- **Release**(`.github/workflows/release.yml`)는 수동으로 실행합니다. 두 번째 전체 CI 파이프라인이 - 아니며, dry-run이나 publish 전에 정확한 릴리즈 커밋(`GITHUB_SHA`)에서 Cross-platform CI가 - 성공했는지 확인합니다. - -릴리즈에는 helper를 사용하세요. - - -helper 실행 전에 릴리즈할 버전을 정하고, 기본 브랜치에서 -`.github/workflows/dev-version-bump.yml`을 `intended-version=`, -`mode=pre-move`로 실행하세요. 생성된 PR을 검토해 `dev`에 머지한 뒤 -`main` 또는 `preview`로 승격하고 helper를 실행하세요. `dev` 버전이 이미 더 -높으면 워크플로가 `changed=false`를 반환하므로 버전 이동 PR은 필요 없습니다. -배포에는 정확한 릴리즈 커밋의 CI 통과가 여전히 필요합니다. - -```bash -bun run release # 버전 bump를 commit/push, publish workflow는 기본 dry-run -bun run release --bump minor # tag와 npm channel에서 다음 patch, minor, major 버전을 계산 -bun run release --publish # CI-gated dry-run을 확인한 뒤 실제 publish -bun run release:watch # 가장 최근 Release workflow run 감시 -``` - -명시적 버전 대신 `--bump patch|minor|major`를 사용할 수 있습니다. 더 높은 core의 preview tag가 -열린 뒤에는 `--bump patch`가 이전 stable patch 라인의 계속을 거부합니다. 해당 수정은 열린 preview -core에 포함해 릴리즈하세요. - -## 브랜치 - -- `dev` — 유일한 통합 대상. 모든 PR을 여기로 올립니다. -- `main` — 릴리즈 전용. `dev`에서 메인테이너가 승격시킬 때만 움직이며, 기능 PR을 직접 - 올리지 않습니다. -- `preview` — 프리릴리즈 트레인. Go 네이티브 포트를 담당했던 `dev2-go`는 정리했고, 두 라인을 동시에 유지하던 정책도 함께 끝났습니다. 히스토리는 @@ -121,7 +72,7 @@ Go 네이티브 포트를 담당했던 `dev2-go`는 정리했고, 두 라인을 ## 컨벤션 -- **ES Modules 전용**(`import`/`export`), TypeScript, `strict` 모드. `bun x tsc --noEmit`을 깨끗하게 +- **ES Modules 전용**(`import`/`export`), TypeScript, `strict` 모드. `bun run typecheck`을 깨끗하게 유지하세요. - **파일당 최대 약 500줄** — 책임별로 나누세요. 단일 `index.ts` 뒤에 작고 집중된 모듈을 둔 `web-search/`와 `vision/` 사이드카가 좋은 예입니다. diff --git a/docs-site/src/content/docs/ko/getting-started/for-agents.md b/docs-site/src/content/docs/ko/getting-started/for-agents.md index 4b6a07ded6..b79ffdd7f0 100644 --- a/docs-site/src/content/docs/ko/getting-started/for-agents.md +++ b/docs-site/src/content/docs/ko/getting-started/for-agents.md @@ -10,7 +10,7 @@ description: 사용자의 동의 경계를 넘지 않으면서 에이전트가 배포된 패키지를 설치하고 `ocx`가 `PATH`에 들어 있는지 확인합니다: ```bash -npm install -g @bitkyc08/opencodex +npm install -g --allow-scripts=bun @bitkyc08/opencodex ocx --version ``` diff --git a/docs-site/src/content/docs/ko/getting-started/installation.md b/docs-site/src/content/docs/ko/getting-started/installation.md index df36ad351a..909eb04922 100644 --- a/docs-site/src/content/docs/ko/getting-started/installation.md +++ b/docs-site/src/content/docs/ko/getting-started/installation.md @@ -18,7 +18,7 @@ opencodex를 설치하면 같은 실행 파일을 가리키는 `ocx`와 `opencod ## 설치 ```bash -npm install -g @bitkyc08/opencodex +npm install -g --allow-scripts=bun @bitkyc08/opencodex ``` :::note[npm이 bun postinstall을 차단했다면?] @@ -26,8 +26,8 @@ npm install -g @bitkyc08/opencodex install-scripts ... blocked because they are not covered by allowScripts`). 이 경우 번들 Bun 런타임이 준비되지 않을 수 있습니다. 런처는 허용된 번들 복구를 시도한 다음, 절대 경로 PATH 디렉터리의 실행 가능한 Bun을 검증합니다. 정식 버전의 -major가 패키지 pin과 같고 minor가 pin 이상이면 사용할 수 있습니다. 현재 의존성 -1.4.2에서는 1.4.0 이상, 2.0.0 미만입니다. 제한 시간 안에 버전 정책과 identity를 확인하며, +major가 패키지 pin과 같고 버전이 pin 이상이면 사용할 수 있습니다. 현재 의존성 +1.4.4에서는 1.4.4 이상, 2.0.0 미만입니다. 제한 시간 안에 버전 정책과 identity를 확인하며, `bun --version` 출력이 `bun -e`로 확인한 `Bun.version`과 같아야 합니다. POSIX에서는 런처가 상위 디렉터리와 심볼릭 링크를 따라 도달하는 구성 요소를 포함한 후보 경로 전체를 검사합니다. 검사하는 각 디렉터리와 심볼릭 링크, 최종 실행 파일은 root 또는 런처의 유효 사용자 소유여야 합니다. @@ -86,7 +86,7 @@ GPT-5.6 Sol/Terra/Luna 카탈로그 정보가 이미 들어 있습니다. 다만 아닙니다. 아직 정식 배포되지 않은 opencodex 빌드를 시험할 때만 preview 채널을 사용하세요: ```bash -npm install -g @bitkyc08/opencodex@preview +npm install -g --allow-scripts=bun @bitkyc08/opencodex@preview ocx update --tag preview ``` diff --git a/docs-site/src/content/docs/ko/getting-started/quickstart.md b/docs-site/src/content/docs/ko/getting-started/quickstart.md index 2c06b538f7..bceda554cf 100644 --- a/docs-site/src/content/docs/ko/getting-started/quickstart.md +++ b/docs-site/src/content/docs/ko/getting-started/quickstart.md @@ -1,9 +1,9 @@ --- title: 빠른 시작 -description: 첫 프로바이더를 설정하고 명령어 세 개로 OpenAI Codex를 opencodex로 라우팅합니다. +description: "opencodex를 설치하고 첫 프로바이더를 추가한 뒤 Codex, Claude Code, Claude Desktop, Grok Build 또는 다른 지원 코딩 도구를 연결합니다." --- -이 가이드는 새로 설치한 상태에서 OpenAI가 아닌 모델로 Codex를 실행하기까지의 과정을 안내합니다. +이 가이드는 새 설치부터 사용 중인 코딩 도구의 첫 요청까지 안내합니다. 1, 2단계는 모든 도구에 공통이며 3단계는 도구별로 나뉩니다. [클라이언트 지원 페이지](/ko/reference/client-support/)에서 도구와 연결 방법을 확인하세요. ## 독립 실행형 바이너리(npm 없음) @@ -18,7 +18,7 @@ ocx init `ocx init`은 다음 과정을 안내합니다: -1. **프로바이더 선택** — 내장 레지스트리 프리셋 104개 중 하나를 고르거나 `custom`을 선택해 base URL과 adapter를 직접 입력합니다. +1. **프로바이더 선택** — 내장 레지스트리 프리셋 107개 중 하나를 고르거나 `custom`을 선택해 base URL과 adapter를 직접 입력합니다. 2. **API 키** — 키를 붙여넣거나 `${ANTHROPIC_API_KEY}` 같은 환경 변수를 참조합니다. 3. **기본 모델** — 키, 로컬, custom 프로바이더에서는 프리셋을 그대로 쓰거나 모델 ID를 직접 입력합니다. 4. **프록시 포트** — 기본값은 `10100`입니다. @@ -53,9 +53,13 @@ ocx status ocx gui # open the dashboard on the live port ``` -## 3. Codex 사용 +## 3. 도구 연결 -이제 Codex는 opencodex와 투명하게 연결됩니다: +사용하는 도구에 해당하는 안내를 선택하세요. 여러 도구를 연결할 수 있으며 프로바이더와 모델은 공유됩니다. + +### Codex + +1단계에서 Codex 프롬프트를 수락했다면 이제 Codex가 opencodex와 투명하게 통신합니다. 프롬프트를 거절했거나 기존 설정이 있어 설정이 종료됐다면 Codex를 실행하기 전에 대시보드 **Connect** 페이지의 Codex 스위치를 켜세요. [Codex 통합](/ko/guides/codex-integration/)에서 변경 내용과 복원 방법을 설명합니다. ```bash codex "Refactor this function for readability" @@ -68,6 +72,42 @@ codex -m "anthropic/claude-opus-5" "Explain this stack trace" codex -m "ollama-cloud/glm-5.2" "Write a SQL migration" ``` +### Claude Code + +`claude` CLI가 설치된 상태에서: + +```bash +ocx claude +``` + +`ocx claude`는 프록시가 실행 중이 아니면 시작하고 opencodex를 가리키는 환경으로 Claude Code를 실행합니다. 추가 인수는 그대로 전달됩니다. 계층 기본값, 다른 실행기와 사용 중지 방법은 [Claude Code](/ko/guides/claude-code/)를 참조하세요. + +### Claude Desktop + +```bash +ocx claude desktop +``` + +새로 설치할 때는 앱 전체에 게이트웨이 프로필을 설정합니다. 이미 first-party 모드를 사용하는 설치는 해당 모드를 유지하며, `ocx claude desktop apply --gateway`를 실행해 명시적으로 전환할 수 있습니다. Desktop은 claude.ai를 유지하고 Code 탭만 라우팅하는 first-party 모드는 [Claude Code](/ko/guides/claude-code/)의 Claude Desktop 모드 항목을 참조하세요. + +모드를 전환한 뒤에는 Claude Desktop을 완전히 종료했다가 다시 여세요. + +### Grok Build + +로컬 리스너에서 `~/.grok`이 존재하면 `ocx start`가 표시되는 모델을 `~/.grok/config.toml`에 등록합니다. Grok Build에서 `ocx-*` 모델을 선택하세요. 원격 설정과 관리 블록은 [Grok Build](/ko/guides/grok-build/)를 참조하세요. + +프로바이더나 모델을 추가한 뒤에는 `ocx ensure`를 실행하거나 프록시를 재시작해야 Grok Build에 반영됩니다. + +### 다른 도구 + +관리형 통합이 있는 도구(OpenCode, Pi, Qoder, WorkBuddy, Kilo, Cline, T3 Code 등)는 대시보드의 **Connect** 페이지에서 연결하거나 다음을 사용하세요: + +```bash +ocx integration client enable --client +``` + +각 도구의 설정 파일과 적용 시점은 [통합](/ko/guides/integrations/)을 참조하세요. 사용자 지정 엔드포인트를 지원하는 다른 도구는 OpenAI 호환 기본 URL `http://localhost:10100/v1` 또는 Anthropic 기본 URL `http://localhost:10100`을 사용할 수 있습니다. + ## Sub-agent 모델 선택(선택 사항) 새 구성에는 Codex의 sub-agent 선택기에 네이티브 모델 다섯 개인 `gpt-5.5`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, `gpt-6-astra`가 표시됩니다. `ocx gui`를 열어 네이티브 또는 라우팅 모델을 최대 다섯 개까지 바꾸거나 순서를 다시 정할 수 있습니다. 대시보드에서는 선호하는 sub-agent 모델과 추론 강도도 설정할 수 있습니다. [Sub-agent Surface](/guides/sub-agent-surface/)에서 v1/base/v2를 고르고, guidance, 네이티브 기본값, fallback이 언제 적용되는지 확인합니다. diff --git a/docs-site/src/content/docs/ko/guides/claude-code.md b/docs-site/src/content/docs/ko/guides/claude-code.md index 14ebff76cb..4f0e6f4e2d 100644 --- a/docs-site/src/content/docs/ko/guides/claude-code.md +++ b/docs-site/src/content/docs/ko/guides/claude-code.md @@ -14,6 +14,19 @@ Messages API를 통해 사용하는 Devin 경로(SWE-2 포함)에서는 늦게 이 출력 순서 수정으로 Cognition이 생성된 일부 시스템 텍스트를 거부하는 별개의 문제가 해결되지는 않아요. 시스템 지시와 안전 제약은 그대로 유지해요. +## Claude OAuth 클라이언트 버전 오류 + +Anthropic OAuth 요청에서 `claude_code_version_too_old`가 반환되면 사용하는 프로바이더를 확인하세요. +Codex에서 `anthropic` 어댑터로 연결할 때는 OpenCodex 자체의 Claude Code 호환 프로필을 사용합니다. +별도로 설치한 `claude` 실행 파일을 업데이트해도 이 프로필은 바뀌지 않습니다. OpenCodex를 업데이트하고 +프록시를 재시작하세요. `claude-cli` 프로바이더나 Claude Code를 직접 사용한다면 해당 CLI를 업데이트하세요. +실제 Claude 클라이언트의 식별 정보를 전달받은 Anthropic 네이티브 Messages 요청은 그 클라이언트의 버전을 유지하며, +설정한 헤더가 있으면 그 값이 우선합니다. + +예를 들어 `claude-fable-5-2`에서 보고된 오류는 Claude Code 2.1.290 이상을 요구했습니다. +이 버전의 OpenCodex 프로필은 2.1.321을 사용합니다. 향후 상위 버전이 필요해지면 더 최신 OpenCodex +프로필이 필요할 수 있습니다. 프로필을 갱신해도 모델 이용 권한이나 구독 한도는 바뀌지 않습니다. + ## CLI와 외부 실행 앱의 티어 기본값 Claude Code 탭에서 Opus, Sonnet, Haiku, Fable 기본 모델을 선택한 뒤 **저장**하세요. @@ -56,7 +69,7 @@ ocx claude | `ANTHROPIC_DEFAULT_{OPUS,SONNET,FABLE}_MODEL` | `claudeCode.tierModels.*` (구독으로 실행할 때 설정하지 않으면 네이티브 `claude-opus-5-5[1m]` / `claude-sonnet-5-5[1m]` / `claude-fable-5-1[1m]`) | | `ANTHROPIC_DEFAULT_{OPUS,SONNET,FABLE,HAIKU}_MODEL_NAME` | OpenCodex가 라우팅 별칭으로 설정한 티어 슬롯의 `/model` 라벨(예: `ocx-claude-native--gpt-6.1-sol` → `gpt-6.1-sol (native)`). launchd 시스템 환경과 셸 훅에도 같은 짝으로 기록합니다. 모델 ID는 별칭 그대로입니다. 직접 설정한 슬롯이나 라벨은 건드리지 않습니다 | | `CLAUDE_CODE_ALWAYS_ENABLE_EFFORT` | `alwaysEnableEffort`가 켜져 있으면 `1` (조건부) | -| `ENABLE_TOOL_SEARCH` | `claudeCode.toolSearch`가 설정된 경우 (조건부, 기본값은 꺼짐) | +| `ENABLE_TOOL_SEARCH` | `claudeCode.toolSearch`가 설정된 경우 (조건부, 기본으로는 주입하지 않으며 Claude Code 자체 기본값을 따름) | | `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | `maxContextTokens`가 설정된 경우 기존 컨텍스트 재정의 값 (조건부) | 직접 내보낸 변수가 항상 우선해요. 추가 인자는 그대로 전달돼요: `ocx claude -p "hello"`. @@ -153,6 +166,8 @@ hook을 제거해요. Claude Desktop은 별도 profile을 사용하며 shell hoo `claudeCode.nativePassthrough: false`로 끌 수 있고, `claudeCode.anthropicBaseUrl`로 다른 주소를 지정할 수 있어요. +**패스스루의 레이트 리밋.** 패스스루 요청은 호출자가 보낸 자격 증명을 그대로 쓰므로 그 로그인의 한도를 따라요. 그 로그인이 429를 돌려주면 OpenCodex는 레이트 리밋 헤더와 `Retry-After`를 유지한 429를 돌려주고, 사용자 자격 증명으로 인증된 요청을 다른 프로바이더나 계정으로 다시 보내지 않아요. Claude Code는 `claude-haiku-5-5`에서 실행하는 WebSearch처럼 일부 요청을 small-fast 모델로 보내기 때문에, 라우팅된 메인 턴은 잘 되는데 이런 요청만 레이트 리밋에 걸린 로그인에서 실패할 수 있어요. 이 트래픽을 관리형 프로바이더로 옮기려면 모델 ID를 매핑하세요. 1P Desktop·CLI 트래픽은 `claudeCode.intercept.modelMap`(또는 `ocx claude desktop bind`), 모든 진입점은 `claudeCode.modelMap`을 쓰면 돼요. 매핑된 ID는 자기 자신으로 해석되지 않으므로 위 패스스루 조건을 만족하지 않고 다른 요청처럼 라우팅돼요. `ocx claude` 세션에서는 `claudeCode.tierModels.haiku`로 그 슬롯이 라우팅된 모델 ID를 요청하게 할 수도 있어요. 다만 여기에 일반 `claude-*` ID를 넣으면 여전히 패스스루되고, 직접 export한 `ANTHROPIC_DEFAULT_HAIKU_MODEL`이 우선해요([#7912](https://github.com/lidge-jun/opencodex/issues/7912)). + ## Claude Desktop 모드: 게이트웨이(기본값)와 1P 대시보드의 **연결 → Claude Desktop → 연결 모드** 또는 @@ -217,6 +232,8 @@ Picker 모드를 끄거나 Desktop을 완전히 다시 시작할 때까지 Deskt Picker 모드는 1P의 일부이므로 [1P 계정 위험](#1p직접-선택)도 그대로 적용돼요. +상위 서버의 첫 응답 전에는 60초 동안 전송이 진행되지 않는 Picker 업로드를 종료해요. 유휴 시간 만료는 성공 응답을 보내지 않고 업로드를 실패 처리하며, HTTP/2에서는 해당 스트림만 재설정해요. 상위 서버가 데이터를 받지 못해 전송을 일시 중지한 동안에는 이 타이머도 멈추고, 업로드가 끝나거나 첫 응답이 오면 해제해요. 이 유휴 타이머는 전체 업로드 시간에 추가 제한을 두지 않으며, 기존 런타임·프로토콜 제한은 그대로 적용돼요. 응답 스트림은 이 타이머의 적용 대상이 아니에요. + ### Code 탭에서 opencodex 모델 쓰기 (1P 바인딩) 1P 모드에서 Code 탭의 모델 선택기는 claude.ai가 채워요. Opus 5.5, Sonnet 5, Haiku 4.5와 @@ -395,9 +412,7 @@ Claude Code는 알 수 없는 모델의 컨텍스트를 200k 토큰으로 계산 **연결 → Claude**에서 압축 값을 조절할 수 있어요. **경고:** 모델의 실제 컨텍스트 창보다 크게 올리면 요약을 시작하기 전에 채팅 오류가 발생해요. -컨텍스트 초과 오류를 정규화할 때는 제공자 오류 메시지의 첫 65,536 UTF-16 코드 단위만 사용해요. -뒤쪽 진단 내용이나 토큰 수는 별도 잘림 표시 없이 빠질 수 있어요. -자세한 제한과 토큰 수 처리 조건은 [영문 가이드](/guides/claude-code/#auto-context-big-context-models-without-the-200k-ceiling)를 참고하세요. +Messages 오류 응답 정규화에서는 제공자 문구나 토큰 수 대신 고정 문구를 사용해요. 인식된 컨텍스트 초과는 `prompt is too long: The request exceeds the model's context window.`로 전달해요. 스트림의 첫 필드가 오류 이벤트인 블록에는 1 MiB 한도가 적용돼요. 한도를 넘으면 압축 문구 없는 고정 오류를 보내요. 자세한 범위와 두 예외는 [영문 가이드](/guides/claude-code/#auto-context-big-context-models-without-the-200k-ceiling)를 참고하세요. 1M 미만인 네이티브 Anthropic 모델에는 자동으로 표식을 붙이지 않아요. 직접 내보낸 압축 값은 실행 슬롯 표식에서 항상 우선하며, 프록시는 **사용자가 지정한** 값을 기준으로 어떤 모델에 안전하게 표식을 붙일지 결정해요. @@ -573,9 +588,9 @@ Messages → Responses로 변환되는 요청에서는 Claude Code의 `/effort` | Assistant 텍스트 | `output_text` | | Assistant `tool_use` | `function_call`(`input` → JSON 문자열로 변환한 `arguments`) | | 사용자 `tool_result` | `function_call_output`(`is_error` → `[tool error]` 접두사) | -| 도구 결과의 `tool_reference` | 짝지어진 결과에 `Tool loaded: ` 텍스트로 보존합니다. 도구 선언을 추가하거나 번역 경로의 서버 측 지연 로딩을 활성화하지는 않습니다. | +| 도구 결과의 `tool_reference` | 기본적으로 짝지어진 결과에 `Tool loaded: ` 텍스트를 보존합니다. [append-only 옵션](/guides/claude-code/#preserve-cache-prefixes-when-client-tools-load)을 켠 적격 최종 Responses 경로에서는 성공한 클라이언트 검색 결과 위치에 현재 선언된 지연 함수의 정의를 배치할 수 있습니다. 참조만으로 도구 권한이나 서버 측 검색 기능을 추가하지는 않습니다. | | `thinking` / `redacted_thinking` 재생 | 서명과 비공개 페이로드를 제한된 `ocxr1` 봉투에 담은 `reasoning` 항목 | -| Function 도구 | `{type: "function"}`(`web_search*` → `{type: "web_search"}`). `api.anthropic.com`으로 번역하여 보내는 경로에서는 타입이 지정된 `web_search_*`와 `web_fetch_*` 선언도 Anthropic에 전달되어 서버에서 실행됩니다. 웹 검색 사이드카가 `web_search`를 제공하면 사이드카가 우선합니다. 검색과 가져오기 결과는 `server_tool_use` 및 대응하는 `web_search_tool_result` / `web_fetch_tool_result` 블록으로 클라이언트에 반환됩니다 | +| Function 도구 | `{type: "function"}`(`web_search*` → `{type: "web_search"}`). `api.anthropic.com`으로 번역하여 보내는 경로에서는 타입이 지정된 `web_search_*`와 `web_fetch_*` 선언도 Anthropic에 전달되어 서버에서 실행됩니다. 웹 검색 사이드카가 `web_search`를 제공하면 사이드카가 우선합니다. 검색과 가져오기 결과는 `server_tool_use` 및 대응하는 `web_search_tool_result` / `web_fetch_tool_result` 블록으로 클라이언트에 반환됩니다 `allowed_domains`, `blocked_domains`, `user_location`이 있으면 번역된 Responses/Chat 경로에서 호스팅 검색을 제외하며, 제외된 검색을 강제하면 400을 반환합니다. 유효한 `defer_loading` 함수 정의는 일반 함수로 호출할 수 있습니다. [번역 제한](/guides/claude-code/#search-restrictions-and-deferred-tools-on-translated-routes)을 참고하세요. | | `tool_choice` | `auto`→`auto`, `none`→`none`, `any`→`required`, 이름 지정 함수→`{type:"function",name}`, 호스팅 WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | @@ -634,7 +649,7 @@ role, `tool_use_id` 없는 `tool_result`, id/name 없는 `tool_use`, name 없는 **오류 분류:** 400 `invalid_request_error`, 401 `authentication_error`, 402 `billing_error`, 403 `permission_error`, 404 `not_found_error`, 409 `conflict_error`, 413 `request_too_large`, 429 `rate_limit_error`, 504 `timeout_error`, 529 `overloaded_error`, -그 밖의 5xx는 `api_error`예요. `Retry-After`는 그대로 유지해요. +그 밖의 5xx는 `api_error`예요. `Retry-After`는 정수 초로 보내며(HTTP 날짜는 남은 초로 바꿔요) 최대 8일로 제한해요. ## 프롬프트 캐싱과 토큰 사용량 @@ -642,9 +657,9 @@ role, `tool_use_id` 없는 `tool_result`, id/name 없는 `tool_use`, name 없는 분기점과 최상위 자동 `cache_control`을 관리해요. 안정적인 대화에서는 보통 캐시 적중률이 약 99.9%예요. -**네이티브 OpenAI/ChatGPT 라우팅:** 세션 범위 `prompt_cache_key`(`metadata.user_id`가 있으면 -사용하고, 없으면 시스템 내용 해시 사용)와 캐시 선호도를 위한 `session_id` 헤더를 만들어요. -캐시 키에는 모델과 전체 도구 스키마가 들어가요. +**네이티브 OpenAI/ChatGPT 라우팅:** `prompt_cache_key`(`metadata.user_id`가 문자열이면 +사용하고, 없으면 시스템 내용 해시 사용)와, 세션 식별자가 있을 때만 캐시 선호도를 위한 `session_id` 헤더를 만들어요(공유 대체 키로는 만들지 않아요). +시스템 내용 해시로 만드는 대체 키(시스템 내용이 있을 때만 사용)에는 모델과 전체 도구 스키마도 들어가요. **토큰 계산:** Anthropic 출력은 `input_tokens`에서 `cached_tokens`와 `cache_write_tokens`를 빼고, 각각 `cache_read_input_tokens`와 `cache_creation_input_tokens`로 노출해요. 요청 로그는 이를 다시 @@ -719,6 +734,16 @@ Anthropic 백엔드를 명시하면 의도적으로 실패 후 중단해요. 언급하면 자동으로 불러와요. 네이티브 패스스루에서는 정상이며, 라우팅 모델에서는 opencodex가 기본적으로 스텁으로 바꿔요(`blockedSkills: ["claude-api"]`). +**첫 턴부터 MCP 도구 스키마가 컨텍스트를 채움** — 게이트웨이 뒤에서 Claude Code가 MCP 도구를 지연 로드하는지는 버전에 따라 다릅니다. v2.1.304부터는 `ANTHROPIC_BASE_URL`이 게이트웨이를 가리켜도(모든 `ocx claude` 세션 포함) 도구 검색이 기본으로 켜집니다. 그 이전 버전은 게이트웨이 뒤에서 지연 로드를 끄고 첫 턴에 모든 도구 스키마를 넣으므로 `claudeCode.toolSearch: true`로 다시 켤 수 있습니다. `ocx claude`는 이 설정이 켜는 값일 때만 `ENABLE_TOOL_SEARCH`를 주입하고, 설정이 없으면 클라이언트 자체 기본값을 따릅니다. `toolSearch: false`는 아무것도 주입하지 않으므로 도구 검색을 끄지 않습니다. 번역 Chat 경로(DeepSeek, GLM 등)에서는 `ToolSearch`로 도구를 불러올 때마다 도구 목록과 시스템 메시지가 바뀌어 다음 요청이 프롬프트 캐시를 대부분 놓칩니다([#7963](https://github.com/lidge-jun/opencodex/issues/7963)). 캐시를 우선하려면 `ocx claude` 실행 전에 `ENABLE_TOOL_SEARCH=false`를 export하세요. 직접 export한 값이 항상 우선합니다. 도구 검색을 켠 채로 prefix를 유지하려면 검증한 직접 Chat 경로를 `claudeCode.chatToolDispatchModels`로 선택하세요(아래 Chat 경로 설명 참고). 네이티브 Anthropic 경로는 서버 측 검색과 지연 도구 참조를 그대로 전달합니다. 기본 번역 경로는 같은 서버 기능을 제공하지 않으므로 모든 타사 경로에서 켜도 된다는 뜻은 아닙니다. + +예외적으로, 클라이언트가 직접 실행하는 eager `ToolSearch` 함수와 구조화된 검색 결과를 제공하고 최종 Responses 목적지가 `additional_tools`를 지원한다면 `claudeCode.appendOnlyToolLoadingModels`로 그 목적지를 명시하여 사용할 수 있습니다. 이 옵션은 사용하지 않은 지연 정의를 초기 카탈로그에서 제외하고 성공한 검색 위치에 현재 정의를 배치합니다. 런처의 `toolSearch` 설정만으로 이 동작이나 서버 측 검색이 활성화되지는 않습니다. 지원되는 클라이언트와 게이트웨이 조합에서만 켜고, 그 밖의 타사 경로에서는 꺼 두세요. 기존 compatibility-enforcement 검사는 그대로 적용되므로 지원하지 않는 요청을 거절할 수 있습니다. 캐시 적중이나 네이티브 검색과의 완전한 동등성은 보장하지 않습니다. [영문 설정 안내](/guides/claude-code/#preserve-cache-prefixes-when-client-tools-load)를 참고하세요. + +OpenCode Go의 Responses 엔드포인트와 공식 xAI Responses 호스트는 선택 목록에 있어도 원래 전체 도구 카탈로그를 유지합니다. 이 목적지들은 `additional_tools`를 초기 `tools`로 승격하거나 거절하므로 시간순 로딩 prefix를 보존할 수 없습니다. 검색 결과의 정의를 초기 `tools`로 승격하는 다른 게이트웨이에서도 이 옵션을 꺼 두세요. + +`additional_tools`를 받아들이지만 오류 없이 버리는 Responses 공급자도 이 옵션의 대상이 아닙니다. 불러온 정의가 모델에게 전달되지 않기 때문입니다. 2026-10-31 측정에서 DeepSeek 공식 Responses API가 이렇게 동작했습니다. DeepSeek에는 아래 Chat 경로 옵션을 사용하세요. + +Chat Completions 경로에는 `additional_tools`에 해당하는 수단이 없습니다. 변환된 Chat 경로에서는 ToolSearch로 도구를 불러올 때마다 도구 카탈로그와 시스템 메시지의 도구 이름 목록이 바뀌어, 다음 요청이 대화 전체에서 공급자 프롬프트 캐시를 놓칩니다. `ENABLE_TOOL_SEARCH=false`로 도구 검색을 끌 수도 있고, 도구 검색을 켠 채로 사용하는 모델로 검증한 직접 Chat 경로라면 `claudeCode.chatToolDispatchModels`(예: `["deepseek/deepseek-flash"]`)로 둘을 고정할 수 있습니다. 선택자 문법, 제한, 메타데이터와 eager `ToolSearch` 전제, combo·policy·늦은 대체 경로 규칙은 `appendOnlyToolLoadingModels`와 같고, 최종 물리 경로가 직접 `openai-chat` 공급자일 때만 적용됩니다. 선택된 경로에서는 첫 요청부터 카탈로그에 `use_loaded_tool` 함수 하나를 더하고 사용하지 않은 지연 도구는 뺍니다. 검색으로 찾은 도구의 이름, 설명, 매개변수 스키마는 그 도구를 불러온 ToolSearch 결과 뒤에 텍스트로 붙습니다. 모델은 `use_loaded_tool`로 그 도구를 호출하고, opencodex는 형식이 올바른 `use_loaded_tool` 호출을 모두 이름이 가리키는 도구 호출로 바꿔 Claude Code에 전달하므로 Claude Code는 항상 실제 도구 이름을 받습니다. 선언된 도구는 직접 호출한 것과 똑같이 실행되고, Claude Code가 모르는 이름은 그 이름 그대로 알 수 없는 도구로 보고됩니다. 형식이 맞지 않거나 다른 키가 섞인 호출은 그대로 전달되어 알 수 없는 도구로 실패합니다. 모델이 ToolSearch로 불러오지 않은 지연 도구를 직접 또는 `use_loaded_tool`로 호출하면 그 도구가 카탈로그로 돌아와 캐시 prefix를 한 번 잃습니다. 정의가 텍스트로 전달되므로 공급자 측 strict 스키마 검사는 적용되지 않습니다. 안내가 도구 결과 안에 있어 따르지 않는 모델이 있을 수 있으니 모델마다 검증한 뒤 켜세요. 옵션이 없거나 비어 있거나 목록에 없는 경로는 이전과 같은 요청 바이트를 보냅니다. 캐시 적중을 보장하지는 않습니다. Claude Code는 래퍼 호출의 인자를 호출이 끝난 뒤에 받는데, 변환된 Chat 경로의 모든 도구 호출이 이렇게 전달되므로 이 옵션으로 달라지는 점은 아닙니다. [영문 설정 안내](/guides/claude-code/#chat-routes)를 참고하세요. + **서브에이전트가 잘못된 모델로 디스패치됨** — 로스터 에이전트(`ocx-*`)는 Agent 도구의 `model` 인자가 아니라 `` 지시문을 사용해요. 지시문이 원하는 라우트와 일치하는지 확인하고, 모델 자리 표시자로 `"haiku"`를 전달하세요. diff --git a/docs-site/src/content/docs/ko/guides/codex-app-models.md b/docs-site/src/content/docs/ko/guides/codex-app-models.md index 899ffc1975..f06017e026 100644 --- a/docs-site/src/content/docs/ko/guides/codex-app-models.md +++ b/docs-site/src/content/docs/ko/guides/codex-app-models.md @@ -3,6 +3,8 @@ title: Codex App 모델 선택기 description: 공유 Codex 카탈로그를 통해 opencodex 모델이 Codex App, Codex CLI, Codex TUI에 표시되는 방식. --- +기본값은 `false`입니다. `config.json`에 `"omitDisabledNativeModels": true`를 설정하고 `ocx sync`를 실행하면 비활성화한 native 행을 catalog와 cache, Codex 형식의 HTTP 모델 목록에서 제외합니다. 제외 전 검증한 상속 템플릿을 보존하므로 routed 행의 메타데이터는 유지되며 직접 요청의 라우팅은 바뀌지 않습니다. 아래 hide 설명은 기본 설정에 해당합니다. + opencodex는 Codex App을 직접 고치지 않습니다. Codex CLI/TUI와 같은 Codex 설정과 모델 카탈로그를 씁니다. app-server는 이 공유 상태를 읽지만, 일부 Codex Desktop 릴리스는 renderer에서 추가 remote allowlist를 적용해 routed row를 picker에서 제거할 수 있습니다. 명시적 `nativeAlias: true` combo가 @@ -104,11 +106,12 @@ GPT-5.6에만 사용합니다. 오래된 템플릿으로 근사하지 않고 모 | 경로 | 선택기 id와 카탈로그 메타데이터 | | --- | --- | -| Codex 로그인(계정 한정 선택기 행 비활성) | `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna` 같은 bare native id를 표시하고 `codexAccountMode`에 따라 Pool 또는 Direct를 사용합니다. GPT-5.6 행의 카탈로그 창은 922,000토큰입니다. | +| Codex 로그인(계정 한정 선택기 행 비활성) | `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna` 같은 bare native id를 표시하고 `codexAccountMode`에 따라 Pool 또는 Direct를 사용합니다. GPT-5.6 행의 카탈로그 창은 922,000토큰입니다. `gpt-6.1-terra`: 기본 500,000 / 장문 872,000. | | Codex 로그인(계정 한정 선택기 행 활성, 유효한 selector 있음) | 유효한 selector와 지원되는 native model의 각 조합마다 `/` 행을 표시합니다. 각 행은 매핑된 계정만 사용하며 bare native 행은 선택기에서 숨깁니다. Native metadata와 context window는 보존됩니다. | | Codex 로그인(명시적 Daybreak forward 행) | canonical `openai` provider에 정확한 `customModels` 항목이 있을 때만 `openai/gpt-daybreak-blue-latest`를 표시합니다. Daybreak wire id를 유지하고 고정된 Sol capability snapshot(컨텍스트 922,000; 자동 압축점 922,000)을 사용합니다. | -| OpenAI(API key) | 정확히 열 개의 네임스페이스 행: `gpt-5.5`, `gpt-5.6`, Sol/Terra/Luna, 세 개의 `*-pro` 가상 id, 두 Daybreak 별칭 (모두 컨텍스트 922,000; 최대 입력 922,000) | +| OpenAI(API key) | 네임스페이스 모델에는 `gpt-5.5`, `gpt-5.6`, Sol/Terra/Luna, `*-pro` 가상 id, Daybreak 별칭이 포함됩니다(컨텍스트 1,050,000; 최대 입력 922,000). `openai-apikey/gpt-6.1-terra`는 컨텍스트 1,050,000, 최대 출력 128,000입니다. | | OpenRouter | `openrouter/openai/gpt-5.6-sol`, `openrouter/openai/gpt-5.6-terra`, `openrouter/openai/gpt-5.6-luna` (922,000) | +| OpenRouter | `openrouter/openai/gpt-6.1-terra` (1,050,000) | | Cursor | 정적 폴백에는 `cursor/gpt-5.6-sol`, `cursor/gpt-5.6-terra`, `cursor/gpt-5.6-luna` (1,000,000)와 Grok 4.5/4.6/4.7의 일반·Fast 항목(500,000)이 들어갑니다. 4.6과 4.7은 `xhigh`도 노출하며, 실시간 계정 탐색이 어떤 항목을 계속 보일지 정합니다. | | xAI | 실시간 탐색이 기준입니다. 폴백 카탈로그에는 `xai/grok-4.6`과 `xai/grok-4.7`이 포함되며 기본값은 `xai/grok-4.5`입니다. 세 모델 모두 컨텍스트 창은 500,000입니다. Grok 4.6과 4.7은 `low` / `medium` / `high` / `xhigh`(업스트림 기본값: `high`)를 제공하고, Grok 4.5는 `high`까지만 제공합니다. | @@ -172,6 +175,46 @@ fast_mode = true `service_tier`가 제거됩니다(레지스트리가 정식 OpenAI를 `true`, DeepSeek과 Volcengine Ark를 `false`로 분류). 미분류 커스텀 게이트웨이는 호출자가 준 값을 그대로 보존하고 주입도 받지 않습니다. 따라서 처리 불가능한 곳에 fast 옵션이 노출되지 않으며, 커스텀 게이트웨이는 `true`로 명시적으로 옵트인할 수 있습니다. +### Codex에서 Flex 선택 + +`service_tier: "flex"` 지원이 확인된 라우팅 프로바이더와 모델에 한해 Flex를 +명시적으로 선언할 수 있습니다. 아래 필드는 **기존** `providers.nanogpt` 설정에 +병합해야 하며 URL과 API 키를 덮어쓰면 안 됩니다. + +```json +{ + "modelSupportsServiceTier": { "openai/gpt-6-luna": true }, + "fastWire": { + "kind": "service-tier", + "canonicalToWire": { "priority": "priority", "flex": "flex" }, + "foreignCallerTiers": "verbatim" + } +} +``` + +적격한 `openai-responses` 라우트에서는 Luna의 Codex 속도 선택기에 Standard, +Fast, Flex가 나타납니다. `openai-chat` 라우트는 Chat Completions API가 +호출자의 서비스 등급을 지원하는 것이 확인된 경우에만 `chatServiceTier: true`도 +설정해야 합니다. `fastWire` 매핑은 **프로바이더 전체에 적용**되므로 같은 +`providers.nanogpt` 항목에서 서비스 등급 사용이 이미 허용된 다른 모델에도 +Flex 선택지가 표시될 수 있습니다. `modelSupportsServiceTier`에 Luna만 적어도 +이미 적격인 다른 모델을 제외하는 허용 목록이 되는 것은 아닙니다. 다만 Flex 선택지는 +카탈로그에 게시되는 **일반 라우팅 모델 행**에만 표시되며, Combo 네임스페이스와 +Native Alias 행에는 표시되지 않습니다. 따라서 해당 항목에서 서비스 등급 사용이 +허용된 **모든 일반 라우팅 모델**의 Flex 지원 여부를 확인하세요. +Luna만 Flex를 지원한다면 Fast 지원 모델이 다른 모델과 섞이지 않도록 +**별도 프로바이더 항목**으로 분리해야 합니다. Fast 지원만으로 Flex 지원을 +추정해서는 안 됩니다. + +OpenCodex의 전역 Fast 설정은 **Auto**(`fastMode` 생략)로 유지하세요. +Fast 또는 Default 강제 모드는 Flex 선택을 덮어씁니다. `ocx sync` 후 Codex의 +모델 목록을 갱신하고 속도 선택기에서 **Flex**를 선택하거나, Codex CLI에서 +`/model --speed=flex`를 사용하면 됩니다. 이는 **선택 가능한 등급**이지 +모델별 강제 기본값은 아닙니다. 다른 모델로 바꾸더라도 Flex 사용이 자동 강제되지는 +않습니다. 상위 API로 `service_tier: "flex"`를 전달하지만, 실제 처리 가능 여부, +요금과 지연 시간은 공급자에 따라 다릅니다. 메뉴나 요청 로그만으로 Flex 과금이 +확정되지는 않습니다. + ### Codex 데스크톱에서 Ultra Fast 선택 `service_tier: "ultrafast"`를 지원하는 프로바이더에는 전송 매핑을 한 번 설정하면 됩니다. diff --git a/docs-site/src/content/docs/ko/guides/codex-integration.md b/docs-site/src/content/docs/ko/guides/codex-integration.md index 33ab38aac9..e5adb56b10 100644 --- a/docs-site/src/content/docs/ko/guides/codex-integration.md +++ b/docs-site/src/content/docs/ko/guides/codex-integration.md @@ -13,6 +13,18 @@ Pool 모드에서는 선택된 저장 계정이 쿨다운 중이고 사용 가 권한과 main 계정 정책 검사는 유지됩니다. 이 fallback은 저장 계정의 쿨다운을 해제하거나 호출자 인증을 Pool 선택으로 저장하지 않습니다. 특정 계정에 정확히 고정된 요청은 그 계정에 계속 묶입니다. +수동 Pool pin은 우선순위 선호이므로 위 fallback을 허용합니다. 특정 계정만 사용해야 하면 +계정이 지정된 모델을 선택하세요. 관측된 native main을 일시 정지하면 일치하는 호출자 자격 증명의 +Pool fallback도 거부하지만, 별도 호출자 로그인을 main으로 간주하지는 않습니다. + +계정 ID·개인/워크스페이스 구독 구분·이메일이 native main과 중복되는 Pool 등록 및 재인증은 +거부됩니다. 이메일이 없으면 다른 구성원이라는 근거로 취급하지 않습니다. 서로 다른 워크스페이스, +이메일로 구분되는 구성원, 개인/워크스페이스 구독은 계속 사용할 수 있습니다. 사용량 조회 실패 시에도 +로그인 토큰의 구독 정보는 유지합니다. 기존 중복 계정은 삭제하지 않고 Pool 선택에서 제외하며 계정 +목록의 `selectionExcludedReason: "duplicate_main"`과 `selectionExcludedAction`으로 이유를 알립니다. native main을 사용하거나 +native Codex를 다른 계정으로 로그인하면 됩니다. 재로그인 감지는 권한을 확보한 다음 native 로그인 +관측에서 반영하며, 수동 목록 조회나 호출자 소유 요청은 이를 위해 native 자격 증명을 읽지 않습니다. + ## 설정 주입 `ocx init`, `ocx start`, `ocx sync`는 모두 인젝터를 호출합니다. 기본 loopback 바인드에서는 Codex의 빌트인 `openai` 프로바이더 id를 그대로 유지한 채, 그 프로바이더가 opencodex를 바라보게 합니다. @@ -184,6 +196,8 @@ env_key = "OPENCODEX_API_AUTH_TOKEN" OpenCodex가 라우팅을 소유할 때는 두 모드 모두 `$CODEX_HOME/opencodex.config.toml`을 참고용/폴백 설정으로 작성합니다. loopback에서는 자동 주입이 사라졌을 때 수동으로 합칠 수 있는 root key가 들어가고, non-loopback에서는 전용 provider 형식이 들어갑니다. 외부 provider 모드는 이 프로필을 건드리지 않습니다. +이 파일을 다시 만들 때 OpenCodex가 관리하지 않는 일반 root key는 그대로 남습니다. 그래서 `stream_idle_timeout_ms`나 `stream_max_retries`처럼 직접 추가한 설정은 다음 주입 뒤에도 유지됩니다. 남는 대입문은 여러 줄에 걸친 값과 64비트 정수까지 작성한 그대로 복사되고, 첫 번째 테이블보다 앞에 놓입니다. 테이블 안의 키와 `a.b = 1` 같은 점 표기 root key는 남지 않습니다. 충돌하면 항상 OpenCodex 쪽이 이깁니다. OpenCodex가 소유한 root key(`model_provider`, `model_catalog_json`, `openai_base_url`)는 현재 라우팅 모드에 맞게 다시 쓰이고, 프로필이 쓰는 테이블과 이름이 같은 root key(프로필이 `[features]`를 쓸 때의 인라인 `features = { ... }` 등)는 버려집니다. 주입이 쓰기 잠금을 기다리는 동안 파일이 바뀌면 주입은 재시도 가능한 오류로 멈추고 수정한 내용은 그대로 둡니다. + :::caution `openai_base_url`, `model_provider`, `model_catalog_json` 같은 root key는 첫 번째 `[table]` 헤더보다 **반드시** 앞에 있어야 합니다. 인젝터는 그 위치를 보장하고, 자신이 남긴 오래되었거나 중복된 복사본은 지웁니다. 사용자가 소유한 root `openai_base_url`은 덮어쓰지 않습니다. 그런 값이 있으면 sync는 카탈로그만 갱신하고 라우팅은 주입하지 않았다고 알립니다. ::: @@ -199,7 +213,15 @@ $CODEX_HOME/opencodex-catalog.json $CODEX_HOME/models_cache.json ``` -macOS에서는 명시적 선택, shim, PATH, 기존 설치 경로와 실행 가능한 기본 `codex` 후보 뒤에 `/Applications/ChatGPT.app`, `~/Applications/ChatGPT.app` 순서로 Codex 앱의 번들 CLI를 확인하며, 번들의 XML `Info.plist` 식별자가 `com.openai.codex`여야 하고 실행 가능한 저장된 선택을 앱 후보로 자동 교체하지 않습니다. +macOS에서는 명시적 선택, shim, PATH, 기존 설치 경로와 실행 가능한 기본 `codex` 후보 뒤에 `/Applications/ChatGPT.app`, `~/Applications/ChatGPT.app` 순서로 Codex 앱의 번들 CLI를 확인하며, 번들의 XML `Info.plist` 식별자가 `com.openai.codex`여야 하고 실행 가능한 저장된 선택을 앱 후보로 자동 교체하지 않습니다. Codex CLI가 전혀 발견되지 않으면 `ocx connect status` 준비 상태 뒤의 카탈로그 프로브도 해당 번들 위치를 시도하므로, 앱 번들 CLI만 있는 Child는 `unverified` 대신 지원 추론 수준을 보고합니다. 실행 시에는 아래 검사가 그대로 적용됩니다. + +실행 시에는 위치와 관계없이 `Codex.app`과 `ChatGPT.app`을 인식하며, 이동한 번들, 명시적 +`CODEX_CLI_PATH`·설정 런타임 명령, 심볼릭 링크 별칭에도 같은 검증을 적용합니다. 앱 이름은 검증 +대상만 결정하고 신뢰를 허용하지 않습니다. 매 실행 전에 정규화한 번들과 정확한 실행 파일의 +엄격한 서명 검증, OpenAI Team ID, 소유권·권한·상위 디렉터리 정책을 확인합니다. 실행 파일은 +번들의 `Contents/` 안에 있어야 하며(Codex.app의 `Contents/Resources/codex-aarch64-apple-darwin` +포함), 번들이나 실행 파일을 정규화할 수 없으면 실행을 거부합니다. 일반 CLI와 다른 회사 앱의 +번들은 기존 실행 정책을 유지합니다. WSL에서는 `CODEX_HOME`이 비어 있고 Linux `~/.codex` 디렉터리가 없거나 Codex 상태(`config.toml`, `auth.json`, `sessions`, `history.jsonl`)가 전혀 없을 때 `/mnt/c/Users/*/.codex/config.toml` 아래의 단일 Windows Codex Desktop home도 확인합니다. 후보가 정확히 하나면 그 디렉터리를 사용하므로 WSL app-server mode와 Windows Codex Desktop이 같은 config와 auth 파일을 공유합니다. 이 탐지를 덮으려면 `CODEX_HOME`을 명시하세요. @@ -207,6 +229,17 @@ Windows에서 Orca shell은 `CODEX_HOME`과 `ORCA_CODEX_HOME`을 Orca의 번들 전용 provider 모드의 `requires_openai_auth = true`는 Codex App/TUI의 계정 게이트 화면을 네이티브 Codex와 같은 조건으로 맞춥니다. opencodex는 `/v1/responses`도 WebSocket으로 제공합니다. 전용 provider는 `"websockets": true`일 때만 `supports_websockets = true`를 광고합니다. loopback에서는 Codex의 빌트인 provider가 먼저 WebSocket을 시도할 수 있으며, 비활성화된 proxy는 `426`을 반환해서 Codex가 HTTP/SSE로 fallback합니다. +**추론 사용량 표시 보존(2.90.0 이상).** 정식 ChatGPT 경로를 HTTP/SSE로 받는 +클라이언트에는, Bun 런타임이 제공하는 상류 WebSocket 연결 응답의 실제 +`x-reasoning-included` 헤더를 전달합니다. 같은 연결을 재사용하는 요청에서도 유지합니다. +이 표시는 서버가 보고한 사용량에 이전 추론량이 이미 포함됐음을 Codex에 알립니다. +첫 Responses 이벤트 전에 받은 메타데이터가 우선하며, 이후 메타데이터는 본문에 남지만 +이미 확정한 응답 헤더를 바꾸지는 못합니다. 없는 표시를 만들어 붙이거나 사용량 숫자를 +수정하지 않습니다. 상류가 표시를 보내지 않는 경우와 Codex 자체의 사용량 상태 관리는 +별도 문제이므로, 이 변경만으로 조기 압축 해결을 보장하지 않습니다. 클라이언트도 +WebSocket으로 연결하면 상류 응답 전에 연결 승인이 끝나므로, 그 승인 헤더에 표시를 +나중에 추가할 수는 없습니다. + 네이티브 ChatGPT forward 요청의 로컬 재생 상태가 만료되었거나 없으면 opencodex는 upstream 요청 전에 `previous_response_not_found`를 반환합니다. Codex WebSocket 클라이언트는 일반 스트림 재시도 한도 안에서 다시 연결하고, 완료된 도구 호출과 결과를 포함한 현재 보유 @@ -367,6 +400,8 @@ ChatGPT 계정을 추가하거나 재인증할 때 OpenCodex는 일반적으로 **Codex Set → Multi-auth**에서 **Codex Auth** 제목 줄의 **Codex 크레딧** 스위치를 켜면 메인 계정과 풀 계정의 최근 크레딧 잔액이 Week 바로 아래에 표시됩니다. 기본값은 꺼짐이며 `showCodexCredits`로 저장됩니다. 잔액은 로케일에 맞는 숫자로 표시하고, 응답에 따라 무제한 또는 초과 사용 한도 도달 안내를 표시합니다. 전체 크레딧 한도가 제공되지 않으므로 막대는 백분율이 아닌 사용 가능 상태를 나타냅니다. 스위치는 표시만 제어하며 새 로그인에는 해당 계정의 조회 결과가 필요합니다. +**Use credits after limit**을 허용한 저장 계정은 포함 사용량 한도가 소진되고 크레딧 관측이 3분 이상 지나면 기존 백그라운드 주기에서 잔액을 다시 조회합니다. **Direct** 모드에서도 `codexAccountNamespaces`로 명시적으로 연결한 서브 계정 등이 대상입니다. Direct와 메인/서브 계정 분리를 유지하며, Pool 라우팅을 켜거나 연결되지 않은 계정을 조회하지 않습니다. 일시 정지·재인증 필요 계정은 제외합니다. 메타데이터 조회는 검증 대기 계정을 검증하거나 모델 요청을 보내지 않습니다. 조회 실패 시 재시도 대기를 유지하며 요청에는 여전히 최신의 사용 가능한 크레딧 증거가 필요합니다. 일반 응답의 사용량 헤더는 크레딧 잔액 관측 시각을 갱신하지 않습니다. + 별도의 백그라운드 재검증은 기본적으로 꺼져 있습니다. Token Guardian, `openai`의 `proactive` 갱신 정책, `tokenGuardian.codexWarmupEnabled`가 필요하며 등록 검증 대기 계정은 제외합니다. ### 계정이 요청을 처리하지 못하게 된 이유 diff --git a/docs-site/src/content/docs/ko/guides/codex-prompt.md b/docs-site/src/content/docs/ko/guides/codex-prompt.md index 318468b05d..d01f82b5df 100644 --- a/docs-site/src/content/docs/ko/guides/codex-prompt.md +++ b/docs-site/src/content/docs/ko/guides/codex-prompt.md @@ -35,6 +35,11 @@ Codex가 실제로 쓰지 않는 순서를 보여 주게 됩니다. 레이어 이름을 클릭하면 전송되는 텍스트를 볼 수 있습니다. 대화 상자는 `codex debug prompt-input`에서 내용을 읽으므로 설명문이 아닌 실제 전송 내용입니다. +읽기에는 호출마다 고정된 15초 제한이 있으며, 메타데이터를 읽는 시간과 공유 프로브를 +기다리는 시간도 포함됩니다. 동기식 메타데이터 읽기가 끝난 뒤에 시간 초과를 확인하므로, +그때 제한에 도달했다면 새 프로브를 시작하지 않습니다. 시간이 초과되면 대화 상자는 +프롬프트를 읽지 못했다고 표시하지만, 로컬에서 읽은 기본 지침은 계속 반환됩니다. + 표시할 내용이 없을 때도 있으며, 대화 상자에 해당하는 이유가 나옵니다. - **파일은 있지만 비어 있습니다.** `~/.codex/AGENTS.md`가 0바이트라서 diff --git a/docs-site/src/content/docs/ko/guides/combos.md b/docs-site/src/content/docs/ko/guides/combos.md index e5d8c84451..e9a9e2c116 100644 --- a/docs-site/src/content/docs/ko/guides/combos.md +++ b/docs-site/src/content/docs/ko/guides/combos.md @@ -70,6 +70,8 @@ alias는 클라이언트가 요청하는 공개 이름만 바꿉니다. 콤보 ## 전략 선택 +필수 `tool_choice`를 보존할 수 없는 대상은 전송 전에 건너뛰며, 모든 대상이 호환되지 않으면 해당 제약을 오류로 반환합니다. 자동 선택만 허용하는 Chat 모델과 OpenAI 가상 모델의 실제 전송 모델 정책도 이 판단에 반영됩니다. 직접 hosted/MCP 선택, `tool_search`, 잘못된 선택값의 처리 범위는 [영문 기준 설명](/guides/combos/#failover-ordered-primary-and-backups)을 참고하세요. + ### 페일오버: 순서가 있는 기본값과 예비값 `failover`는 설정 순서에서 가장 먼저 적합한 대상을 선택합니다. 대상이 적합하려면 해당 공급자가 존재하고, 활성화되어 있고, 쿨다운 중이 아니며, 요청에 붙은 특수 조건을 처리할 수 있어야 합니다. 이 전략에서는 가중치와 `stickyLimit`이 영향을 주지 않습니다. @@ -82,6 +84,8 @@ alias는 클라이언트가 요청하는 공개 이름만 바꿉니다. 콤보 각 요청은 Anthropic에서 시작합니다. Anthropic에서 재시도 가능한 실패가 나면 그 요청은 OpenAI로 넘어갑니다. OpenAI에서도 재시도 가능한 실패가 나면 Google로 넘어갈 수 있습니다. 종결 오류가 나면 남은 대상은 더 시도하지 않고 즉시 멈춥니다. +제공자의 HTTP 400 응답도 대상별 오류일 수 있습니다. OpenRouter의 불투명 제공자 래퍼(숫자 `code: 400`, `type` 없음, `metadata.raw: "ERROR"`를 포함하는 `Provider returned error`)는 대상 로컬로 처리되어 실패한 대상을 쿨다운하지 않고 콤보가 다음 대상을 시도할 수 있도록 합니다. 타입이 지정된 비코드 400, 알려진 잘못된 형식의 `response_format` 스키마 오류, 그리고 루트가 자체 종결 코드를 명시하는 봉투는 계속 종결 오류로 유지됩니다. 루트가 자체 홉 신호(`model_not_found`, `insufficient_quota`, `usage_limit_exceeded`, `free_rate_limited`, `input_admission_refused` 또는 `unsupported_input_modality`)를 명시하더라도 새로운 판정이 추가되지 않으며, 빈 코드는 코드가 없는 것으로 처리됩니다. 이 가이드의 뒷부분에 설명된 인식된 대상 비호환성은 계속 진행됩니다. + ### 라운드 로빈: 부드러운 가중 배치 `round-robin`은 smooth weighted round-robin을 사용합니다. 대상 가중치가 클수록 시간에 따라 더 큰 비중을 가져가지만, 그 몫이 한꺼번에 긴 덩어리로 몰리지는 않습니다. `stickyLimit`은 선택된 대상에 몇 번의 성공 요청을 붙여 둘지 정합니다. @@ -130,9 +134,10 @@ ocx combo set balanced \ | HTTP 401, 403, 404, 408, 429, 또는 모든 5xx | 대상을 쿨다운으로 보내고 다음 적합한 대상으로 넘어갑니다. | | 모델 수명 종료, retired, deprecated, sunset, decommissioned, 또는 더 이상 사용할 수 없다는 신호가 명시된 HTTP 410 | 해당 대상만 쿨다운으로 보내고 다음 대상으로 넘어갑니다. 관련 없는 410은 종결 오류로 유지합니다. | | 인증, 구독, 쿼터, 속도 제한, 과부하, 또는 상위 서버 오류로 분류됨 | 상태 코드만으로는 충분하지 않더라도 대상을 쿨다운으로 보내고 넘어갑니다. | -| 클라이언트 취소(499), `origin_rejected`, cyber-policy refusal, context overflow, 또는 기타 invalid request | 멈추고 오류를 반환합니다. 다른 대상을 써도 요청이 유효해지지 않기 때문입니다. | +| 클라이언트 취소(499), `origin_rejected`, cyber-policy refusal, 또는 기타 invalid request | 멈추고 오류를 반환합니다. 다른 대상을 써도 요청이 유효해지지 않기 때문입니다. | +| 출력 전 확인된 컨텍스트 초과 오류(HTTP 400 포함) | 쿨다운 없이 다음 미시도 적격 대상을 시도합니다. 모두 실패하면 처음 확인된 HTTP 400 컨텍스트 오류를 반환합니다(다른 상태 코드의 컨텍스트 거부도 다음 대상으로 넘어가지만 보관되지 않습니다). | | ChatGPT 계정으로 Codex를 사용할 때 해당 모델을 지원하지 않는다는 정확한 HTTP 400 거부 | 출력이 시작되기 전에 다음 설정 대상으로 넘어갑니다. 거부 문장 전체가 `detail`, `error.message` 또는 일반 텍스트에 있어야 하며, `detail`과 `error`가 충돌하면 중단합니다. 이 사유만으로 계정을 재인증 상태로 바꾸거나 공급자의 모든 모델에 쿨다운을 걸지는 않습니다. | -| `user`를 명시적으로 거부하거나, `reasoning.effort`/`reasoning_effort`의 지원되지 않는 값, 모델별 이미지 입력 거부(`param: input`) 또는 경로가 읽을 수 없는 입력 미디어 거부(`unsupported_input_modality`)를 나타내는 구조화된 HTTP 400 | 출력 시작 전에 쿨다운 기록 없이 다음 적격 대상으로 넘어갑니다. 선택적 매개변수 호환성을 참조하세요. | +| `user`를 명시적으로 거부하거나, `reasoning.effort`/`reasoning_effort`의 지원되지 않는 값, 모델별 이미지 입력 거부(`param: input`) 또는 경로가 읽을 수 없는 입력 미디어 거부(`unsupported_input_modality`)를 나타내는 구조화된 HTTP 400 | 추론 노력 거부의 경우 전송 예산이 허용하는 동안 동일한 대상에서 다음으로 낮은 게시된 단계를 시도합니다. 작동하는 단계가 없으면 거부가 인지된 호환성 형태와 일치할 경우 출력 확정 전에 쿨다운 없이 다음 대상으로 넘어가며, 그렇지 않으면 종료됩니다. 기타 나열된 불일치는 쿨다운 없이 넘어갑니다. 선택적 매개변수 호환성을 참조하세요. | | 인프로세스 어댑터(`runTurn`)가 실행하는 Responses 턴에서 현재 요청이 선언하지 않은 첫 도구 호출(출력이나 재전송 불가 부작용 이전) | 대상을 쿨다운하고 같은 도구 카탈로그로 다음 대상으로 넘어갑니다. 출력이 보였거나 재전송 불가 부작용이 생긴 뒤에는 거부가 그대로 확정됩니다. Chat Completions와 Anthropic Messages 요청은 바뀌지 않습니다. | | 그 밖의 분류되지 않은 오류 | 멈추고 오류를 반환합니다. | @@ -142,7 +147,9 @@ ocx combo set balanced \ `cooldownMs`가 설정되지 않으면 홉된 대상은 업스트림 폴백을 사용합니다. 업스트림 코드 `1302` 또는 `1305`인 요청 속도 제한 429는 5초, 계정 사용량 창을 소진한 경우는 10분, 그 외에는 60초입니다. 사용량 창 소진은 업스트림 코드(`usage_limit_exceeded`, `usage_limit_reached`, `1308`)나 `usage limit reached` 문구로 인식하며 HTTP 상태와 무관합니다. ChatGPT Codex 백엔드가 소진된 창을 문서화된 429가 아니라 502로 보고하기 때문입니다. 공급자 전체를 이미 차단하는 자격 증명·결제 실패(`invalid_api_key`, `insufficient_quota`, `payment_required` 등)도 같은 10분 쿨다운을 받습니다. 설정하면 사용 가능한 업스트림 `Retry-After` 또는 Codex 재설정 신호가 없을 때, 해당 요청 속도 제한 429를 포함해 `cooldownMs`가 적용됩니다. 숫자로 된 `Retry-After` 초와 HTTP-date 값을 허용합니다. 명시적 서버 지연은 최대 24시간, 재설정 신호·설정값·폴백 쿨다운은 최대 10분으로 제한됩니다. 우선순위는 강한 순서대로 명시적 `Retry-After` → Codex 재설정 헤더(`x-codex-primary-reset-at`, `x-codex-secondary-reset-at`, 또는 `x-codex-tertiary-reset-at`) → 콤보의 `cooldownMs`(설정된 경우) → 소진된 사용량 창이나 자격 증명·결제 실패에 대한 10분 쿨다운 → 업스트림 속도 제한 코드 `1302`/`1305`의 5초 요청 속도 제한 폴백 → 60초 기본값입니다. 사용량 창을 먼저 확인하므로, 요청 속도 제한 코드와 사용 한도 문구를 함께 가진 실패는 5초가 아니라 10분 동안 쿨다운됩니다. 유효한 즉시 지시인 `Retry-After: 0`은 설정된 쿨다운으로 대체하지 않고 업스트림의 즉시 지시로 유지합니다. -현재 요청은 이미 시도한 대상을 다시 시도하지 않습니다. 단 한 가지 예외가 있습니다. `waitForCooldownMs`를 설정한 단일 대상 콤보는 대체할 다른 대상이 없으므로, 같은 요청 안에서 그 대상의 쿨다운이 끝나면 유일한 대상을 다시 시도할 수 있습니다. 요청 로컬 호환성 거부는 여전히 재시도 없이 반환됩니다. 이후 요청은 쿨다운이 끝날 때까지 해당 대상을 건너뜁니다. 이미 지난 시각을 가리키는 `Retry-After` HTTP-date도 `Retry-After: 0`과 마찬가지로 업스트림의 즉시 지시로 유지됩니다. `waitForCooldownMs`를 설정하면 이후 요청은 가장 먼저 적합해지는 대상의 쿨다운을 선택 시도마다 이 한도까지 기다린 뒤 새로 한 번 선택합니다. 따라서 여러 failover 홉을 거치는 요청은 총 `hops × waitForCooldownMs`까지 기다릴 수 있습니다. 기본값은 `0`입니다. 모든 적합한 대상이 쿨다운 중이고 대기 한도가 0이거나 가장 이른 만료 시각이 대기 한도를 넘으면 요청은 즉시 HTTP 503으로 종료됩니다. 이 `combo_unavailable` 503에는 가장 이른 잔여 쿨다운과 같은 `Retry-After` 헤더가 포함되며, 값은 올림해 정수 초로 표시되고 최소 1초입니다. 대기에 지터를 적용하지 않으므로 동시에 깨어날 수 있습니다. 요청이 중단되면 이 대기가 취소되고 정상 `client_cancelled` 응답이 반환됩니다. 취소 후 백업 대상을 디스패치하지 않습니다. 콤보 대상 쿨다운은 프로세스 로컬 콤보별 상태입니다. 네이티브 계정 라우팅에서 사용하는 계정 수준 Codex 쿼터 쿨다운과는 별개입니다. +현재 요청은 이미 시도한 대상을 다시 시도하지 않습니다. 단 한 가지 예외가 있습니다. `waitForCooldownMs`를 설정한 단일 대상 콤보는 대체할 다른 대상이 없으므로, 같은 요청 안에서 그 대상의 쿨다운이 끝나면 유일한 대상을 다시 시도할 수 있습니다. 요청 로컬 호환성 거부는 여전히 재시도 없이 반환됩니다. 이후 요청은 쿨다운이 끝날 때까지 해당 대상을 건너뜁니다. 이미 지난 시각을 가리키는 `Retry-After` HTTP-date도 `Retry-After: 0`과 마찬가지로 업스트림의 즉시 지시로 유지됩니다. `waitForCooldownMs`를 설정하면 이후 요청은 가장 먼저 적합해지는 대상의 쿨다운을 선택 시도마다 이 한도까지 기다린 뒤 새로 한 번 선택합니다. 따라서 여러 failover 홉을 거치는 요청은 총 `hops × waitForCooldownMs`까지 기다릴 수 있습니다. 기본값은 `0`입니다. 모든 적합한 대상이 쿨다운 중이고 대기 한도가 0이거나 가장 이른 만료 시각이 대기 한도를 넘으면 요청은 즉시 HTTP 503으로 종료됩니다. 이 `combo_unavailable` 503에는 가장 이른 잔여 쿨다운과 같은 `Retry-After` 헤더가 포함되며, 값은 올림해 정수 초로 표시되고 최소 1초입니다. 대기에 지터를 적용하지 않으므로 동시에 깨어날 수 있습니다. 요청이 중단되면 이 대기가 취소되고 정상 `client_cancelled` 응답이 반환됩니다. 취소 후 백업 대상을 디스패치하지 않습니다. 콤보 대상 쿨다운은 콤보별 상태이며, 네이티브 계정 라우팅에서 사용하는 계정 수준 Codex 쿼터 쿨다운과는 별개입니다. 절대 만료 시각과 함께 opencodex 홈의 `combo-cooldowns.json`에 저장되므로 재시작해도 그 시각까지 유지됩니다. 같은 홈을 쓰는 프록시끼리 서로의 쿨다운을 줄이지 않습니다. 콤보를 저장하거나 이름을 바꾸거나 삭제하면 해당 쿨다운이 지워집니다. + +위 HTTP 503 규칙은 아직 대상을 시도하지 않았을 때 적용됩니다. 확인된 HTTP 400 컨텍스트 거부 후 적격 대상이나 전송 예산을 소진하면 첫 거부를 `context_length_exceeded`로 반환하며, 쿼터 오류를 포함한 이후의 재시도 가능한 오류보다 우선합니다. 남은 대상이 추론을 재생할 수 없거나 과금 동의가 없는 경우도 같습니다. 취소, 이후의 치명적 거부, 명시적인 폴백 정책 거부는 즉시 중단합니다. 동의 없는 과금 대상으로 요청을 보내지 않습니다. :::note 페일오버는 의도적으로 범위를 제한합니다. 대상별 가용성, 인증, 쿼터, 과부하 실패에는 도움이 되지만, 호출자 오류나 정책 거부를 숨기지는 않습니다. @@ -280,12 +287,16 @@ opencodex 인스턴스에 기록했는지 확인하세요. ### 첫 번째 오류 뒤에 failover가 멈춘 이유는 무엇인가요? -대상별 오류가 아니라 종결 오류였기 때문입니다. 잘못된 입력을 수정하고, 너무 큰 context를 줄이고, +대상별 오류가 아니라 종결 오류였기 때문입니다. 잘못된 입력을 수정하고, 정책 거부를 처리하거나, 거부된 요청 origin을 바로잡으세요. combo는 이런 경우 다음 대상으로 넘어가지 않습니다. ## 선택적 매개변수 호환성 -일반적인 400 오류는 종료되지만, `user`를 명시적으로 거부하거나 `reasoning.effort`/`reasoning_effort`의 지원되지 않는 값, 모델별 이미지 입력 거부(`param: input`) 또는 경로가 읽을 수 없는 입력 미디어 거부(`unsupported_input_modality`)를 나타내는 구조화된 오류는 출력 시작 전에 다음 적격 대상으로 넘어갈 수 있습니다. 이 경우 쿨다운을 기록하지 않습니다. 보안 정책 거부, 취소 및 이미 시작된 출력은 재실행하지 않습니다. +일반적인 400 오류는 종료되지만, OpenRouter의 불투명 제공자 래퍼(숫자 `code: 400`, `type` 없음, `metadata.raw: "ERROR"`를 포함하는 `Provider returned error`) 또는 `user`를 명시적으로 거부하거나 `reasoning.effort`/`reasoning_effort`의 지원되지 않는 값, 모델별 이미지 입력 거부(`param: input`) 또는 경로가 읽을 수 없는 입력 미디어 거부(`unsupported_input_modality`)를 나타내는 구조화된 오류 및 정확한 벤더 엔벨로프 `{"code":"invalid-argument","error":"Invalid reasoning effort."}`의 경우 출력 확정 전에 다음 적격 대상으로 넘어갈 수 있습니다. 콤보 대상이 요청된 추론 노력을 거부하면, 콤보는 먼저 해당 대상에 대해 공유 전송 예산 내에서 거부당 한 단계씩 다음으로 낮은 게시된 노력 단계로 재시도합니다. 이는 인식된 모든 노력 거부에 적용됩니다. 더 낮은 단계가 모두 성공하지 못하면 위의 형태 중 하나에 해당하는 거부는 거부된 대상을 냉각하지 않고 다른 대상으로 넘어가며, 다음 단계에 남은 전송이 없을 때 해당 대상의 원래 400을 유지합니다. 기타 노력 거부는 종료 상태로 유지됩니다. `unsupported_input_modality` 코드로 요청의 미디어를 거부하는 경로도 동일하게 진행됩니다. 이는 이 요청에 대한 불일치일 뿐 대상이 비정상이라는 증거가 아닙니다. 직접 요청은 단일 노력 다운그레이드 복구를 유지합니다. 호환성 복구는 `none`을 다른 노력으로 자동으로 변경하거나 임의의 잘못된 요청으로 콤보 홉을 넓히지 않습니다. 보안 정책 거부, 취소 및 이미 시작된 출력은 재실행하지 않습니다. 단일 대상 요청은 여전히 해결되지 않은 업스트림 거부를 반환합니다. [Canonical compatibility details](/guides/combos/#request-local-target-compatibility). + +## 쿨다운 복구 예약 + +`cooldownReprobe: { enabled: true }`로 활성화한 복구 시도는 이를 예약한 요청에만 속하며, 다른 요청에는 저장된 쿨다운이 계속 적용됩니다. 예약은 쿨다운 대기와 JEV 선택을 거쳐 유지됩니다. 대기 중 다시 사용 가능해진 대상은 기존 쿨다운이 바뀌지 않았다면 재시도할 수 있지만, 새 쿨다운 기록은 그 대상의 예약을 무효화합니다. 성공하면 응답한 대상의 변경되지 않은 쿨다운만 해제하며, 시도하지 않은 대상과 새로운 실패의 쿨다운은 유지합니다. 공급자 비활성화, 할당량, 요청 적격성 및 취소 검사는 계속 적용됩니다. [설정과 제한](/guides/combos/#retry-all-cooled-targets-opt-in)을 참고하세요. diff --git a/docs-site/src/content/docs/ko/guides/custom-gateway.md b/docs-site/src/content/docs/ko/guides/custom-gateway.md new file mode 100644 index 0000000000..ab48e8d19d --- /dev/null +++ b/docs-site/src/content/docs/ko/guides/custom-gateway.md @@ -0,0 +1,88 @@ +--- +title: 사용자 지정 원격 게이트웨이 검증 +description: 모델 목록 조회부터 제한된 응답 생성까지 사용자 지정 게이트웨이를 확인합니다. +--- + +등록 전에 운영자로부터 사용이 허가된 Chat Completions 베이스 URL, API 키, 지원 모델 ID를 확보하세요. +예를 들어 `https://api.example.com/v1`은 실제 엔드포인트가 아닌 자리표시자입니다. 프록시가 꺼져 있다면 +시작한 다음 대시보드에서 **Custom**을 선택하고 이름을 `my-gateway`, 어댑터를 `openai-chat`으로 정한 뒤 +허가된 URL과 키를 입력하고 저장하세요. 키를 명령이나 공유 예시에 넣지 마세요. 저장 성공만으로 모델 목록 조회나 +추론 성공이 증명되지는 않습니다. + +[Remote Link](/ko/guides/remote-link/) Child에서는 provider를 Home에서 가져옵니다. Child 대시보드는 provider 변경을 +거부하고, 요청은 Home의 provider가 처리합니다. 게이트웨이 등록과 검증은 Home에서 하세요. + +각 단계를 따로 확인하세요. 기본 포트가 아니면 설정한 로컬 포트를 사용합니다. + +```sh +curl -fsS http://127.0.0.1:10100/healthz +ocx ready +ocx provider test my-gateway +ocx models live --provider my-gateway --json +``` + +Health와 readiness는 프록시 상태이며 업스트림의 텍스트 생성 성공을 뜻하지 않습니다. `--model` 없는 +provider test는 추론이 아닌 모델 목록 조회를 검사합니다. 정적 카탈로그에 실시간 모델 조회 엔드포인트가 없으면 +`applicable: false`가 나올 수 있으며 이는 추론 성공이 아닙니다. 공개 모델 목록의 성공도 키 유효성을 +증명하지 않을 수 있습니다. 모델 목록 조회가 실패하거나 모델이 없다면 선택 전에 URL, 자격 증명, 업스트림 접근 권한과 +프로바이더 설정을 확인하세요. + +게이트웨이는 모델 목록 엔드포인트가 없어도 응답을 생성할 수 있습니다. 운영자가 지원하는 원본 ID를 제공했다면 +기존 프로바이더의 다른 필드는 유지하고 `liveModels: false`, `models: ["vendor/model"]`을 설정하세요. +예시 ID는 제공받은 정확한 값으로 바꿉니다. [정적 모델 설정](/ko/reference/configuration/providers/)을 참고하세요. + +`config.json`을 직접 수정하기 전에 작업을 저장하고 진행 중인 요청이 끝날 때까지 기다리세요. 프록시를 중지하면 +진행 중인 요청이 중단될 수 있습니다. 관리 주체에 따라 Desktop 트레이에서 OpenCodex를 종료하거나, 서비스 설치는 +`ocx service stop`, 감독되지 않는 프록시는 `ocx stop`으로 중지하세요. 중지된 것을 확인한 뒤 다른 설정 쓰기 작업을 +실행하지 않는 상태에서 파일을 수정하고 저장합니다. 같은 관리 주체로 다시 시작하세요: Desktop을 다시 열거나, +`ocx service start`를 실행하거나, 기존 `ocx start` 명령과 실행 옵션을 사용합니다. 직접 지정한 `--port`도 +포함합니다. 포그라운드 시작 명령은 해당 터미널에서 계속 실행하고 다른 터미널에서 `ocx sync`와 나머지 검사를 +실행하세요. 그다음 live 카탈로그를 다시 확인합니다. 또는 아래 비용 확인을 거치는 응답 생성 명령에 +제공받은 원본 ID를 직접 사용할 수 있습니다. 이 테스트에는 카탈로그 행이 필요하지 않습니다. + +live 카탈로그에서 실제 `id`, `namespaced`, `disabled`, `initialSelectionPending`을 확인하세요. +초기 선택에 따라 모델이 꺼져 있거나 대기 상태일 수 있습니다. [초기 모델 선택](/ko/reference/configuration/providers/)을 +참고하세요. 행을 켜기 전에 초기 선택의 대기 상태를 해소합니다. 표시 관리 명령의 선택자는 프로바이더 이름과 행의 +**원본 `id`**를 조합하며, ID 내부의 슬래시를 그대로 유지합니다. + +```sh +ocx models enable 'my-gateway/<원본-업스트림-ID>' +``` + +예를 들어 원본 `id`가 `vendor/model`이면 선택자는 `my-gateway/vendor/model`입니다. +클라이언트용 `namespaced` 값은 `my-gateway/vendor-model`처럼 인코딩될 수 있습니다. 이를 대신 사용하면 +원본 ID로 저장된 비활성 항목이 해제되지 않을 수 있습니다. 모델 하나를 켜도 다른 모델은 꺼지지 않습니다. +이 게이트웨이에서 해당 모델만 표시하려면 같은 선택자 형식에 각 행의 원본 `id`를 넣어 다른 활성 모델을 끄고 +목록을 다시 확인하세요. + +```sh +ocx models disable 'my-gateway/<다른-원본-업스트림-ID>' +ocx models live --provider my-gateway --json +``` + +원하는 행은 `disabled: false`이고 제외하려는 다른 행은 비활성 상태인지 확인하세요. 접두사 없는 네이티브 모델 ID는 +다른 경로를 선택할 수 있습니다. 표시 이름이나 추측한 reasoning 접미사 대신 정확한 값을 쓰세요. 접미사는 별도 +업스트림 모델 ID일 수 있으며 reasoning 강도는 별도 설정입니다. 자세한 내용은 +[CLI 레퍼런스](/ko/reference/cli/providers-accounts/)를 참고하세요. + +필요하면 `ocx sync`로 클라이언트 카탈로그에 반영한 뒤 Codex 모델 선택기에 해당 모델이 나타나는지 확인하세요. +실행 중인 클라이언트는 이전 목록을 메모리에 유지할 수 있습니다. 진행 중인 작업을 보존하고 목록이 계속 오래된 상태라면 +Codex를 완전히 종료한 뒤 다시 여세요. 또는 명시적으로 승인한 뒤 +[`ocx system codex-restart --yes`](/ko/reference/cli/agents/)를 사용할 수 있습니다. +이 명령은 세션을 중단하고 저장하지 않은 초안, 선택 또는 대기 중인 승인 요청을 잃게 할 수 있습니다. +위의 설정 파일 직접 수정 외에는 클라이언트나 프록시 재시작이 기본 복구 단계가 아닙니다. + +지원되는 키 인증 원격 설정에서 실제 응답 생성 요청 하나를 검증하려면 행이나 게이트웨이 운영자로부터 얻은 +**업스트림 원본 `id`**를 프로바이더 접두사를 추가하지 않고 그대로 사용합니다. + +```sh +ocx provider test my-gateway --model '<원본-업스트림-ID>' +``` + +이 명령은 제한된 요청 하나를 보내며 쿼터를 사용하고 요금이 발생할 수 있습니다. 비용을 승인한 뒤에만 기본값이 +No인 확인 질문에 동의하세요. 비대화형 또는 JSON 사용에는 `--yes`가 필요합니다. 응답 생성 테스트의 +`applicable: false`는 요청을 보내지 않았다는 뜻이며 종료 코드가 0이어도 통과가 아닙니다. 성공한 테스트를 통과로 +판정하기 전에 보고된 wire 모델이 의도한 업스트림 ID와 일치하는지 확인하세요. 별칭이 다른 모델로 해석될 수 있습니다. +JSON 출력에서는 `wireModel`입니다. 텍스트 생성 성공 +한 번은 도구 호출, 구조화 출력, 연속 호출 또는 모델의 실제 정체를 증명하지 않습니다. 업스트림이 보고한 +모델명은 메타데이터입니다. 이후 호환성 문제는 비식별 fixture로 해당 프로토콜을 따로 재현하세요. diff --git a/docs-site/src/content/docs/ko/guides/desktop-app.md b/docs-site/src/content/docs/ko/guides/desktop-app.md index 37c38585ff..6da1eded1f 100644 --- a/docs-site/src/content/docs/ko/guides/desktop-app.md +++ b/docs-site/src/content/docs/ko/guides/desktop-app.md @@ -81,7 +81,8 @@ macOS, Linux, Windows에서 데스크톱 앱이 번들 프록시를 실행하는 설치하는 대신 OpenCodex 메뉴에서 **Start at Login**을 켜세요. 앱의 로그인 등록이 확인되어야 재시작 후 보호가 적용됩니다. 등록을 확인할 수 없으면 status에 표시되는 데스크톱 안내를 따르세요. 실행 관계 확인은 소유권을 생성하지 않습니다. -이때 시작 안전 페이지의 데스크톱 앱 행에는 **실행 중 · 로그인 시 시작 미확인**이 표시됩니다. +등록을 확인할 수 없으면 시작 안전 페이지에 **로그인 시 시작 미확인** 안내가 표시됩니다. +꺼진 상태가 확인되고 다른 보호가 없으면 조치가 필요하다고 표시합니다. macOS에서 메뉴의 **Start at Login** 항목은 시작 안전 페이지도 같은 등록을 확인할 때만 체크됩니다. 그렇지 않으면 체크가 해제된 채 이유가 라벨에 붙습니다. **disabled by macOS**는 시스템 설정 → 일반 → 로그인 항목 및 확장 프로그램을 열며, 거기서 OpenCodex가 로그인 시 @@ -91,18 +92,30 @@ macOS에서 메뉴의 **Start at Login** 항목은 시작 안전 페이지도 **status unknown**은 등록을 읽지 못했다는 뜻입니다. 앱이 프록시를 실행하는 동안 시작 안전 페이지는 백그라운드 서비스 설치를 막아 둡니다. 서비스를 대신 쓰려면 OpenCodex를 종료하고 터미널에서 `ocx service install`을 실행하세요. Codex 런처 shim은 이 페이지에서 설치할 수 있습니다. -Codex를 실행할 때 프록시가 없으면 shim은 OpenCodex가 프록시를 다시 띄우기를 기다립니다. macOS에서 -앱이 종료돼 있고 기록된 소유 정보가 유효한 **Start at Login** 등록과 일치하면 앱을 열고, 그 밖의 -경우에는 두 번째 프록시를 띄우지 않고 오류를 알립니다. 자동으로 다시 열 때는 그 등록에 기록된 앱 +Codex를 실행할 때 프록시가 없으면 번들 CLI는 독립적으로 확인된 Desktop의 복구를 기다립니다. +기록된 소유 정보가 없어도 적용됩니다. 확인된 Desktop이 프록시를 중지했거나 복구 상태를 검증할 수 +없으면 오류를 알립니다. 다만 플랫폼이 복구 검증 자체를 지원하지 않을 때는 기록된 소유 정보와 +실행 중인 앱이 기존의 한정된 대기를 그대로 허용합니다. 프로세스 이름이나 검색용 파일만으로는 일반 CLI 시작을 막지 않습니다. +macOS에서 앱이 종료돼 있고 기록된 소유 정보가 유효한 **Start at Login** 등록과 일치하면 앱을 엽니다. +자동으로 다시 열 때는 그 등록에 기록된 앱 번들 경로를 사용하고, 번들이 선언한 주 실행 파일이 등록된 Desktop 실행 파일과 같은지 확인합니다. 등록이 없거나 오래됐거나 서로 맞지 않으면 OpenCodex를 직접 여세요. 번들 식별자가 같은 다른 사본을 대신 고르지 않습니다. shim이 "활성화 미확인"으로 보이면 셸 시작 파일의 다른 PATH 설정 뒤에 `. ~/.opencodex/codex-shell-env.sh`를 추가하세요. +복구 검증은 macOS/Linux에서 같은 설치의 번들 CLI와 보호된 시스템 Debian 설치를 지원합니다. +예전에 npm으로 만든 shim은 별도 Bun/CLI 경로를 고정하여 Desktop의 터미널 명령 전달을 거치지 +않을 수 있습니다. 이 진입점에서는 공식 서명된 사본을 포함한 macOS/Windows Desktop이나 임의의 +사용자별 Linux 사본을 검증할 수 없습니다. Desktop의 Startup 페이지에서 shim을 다시 만들거나 +번들 CLI를 실행하세요. Windows에서는 복구 증명에 필요한 실제 실행 이미지의 동일성을 아직 확인할 +수 없어, 같은 설치의 앱이 실행 중이면 복구 점수를 인정하지 않고 기록된 소유 정보가 없으면 +디스크 파일의 서명이 유효하더라도 CLI 프록시를 띄우는 대신 오류를 알립니다. 기록된 소유 정보가 +있고 앱이 실행 중이면 CLI는 Desktop 프록시를 기다리는 기존의 한정된 대기를 유지합니다. + 번들 CLI 경로는 macOS에서 `/Applications/OpenCodex.app/Contents/MacOS/ocx`, Linux deb 패키지에서 `/usr/bin/ocx`입니다. 해당 실행 파일에 `status`를 붙여 -앱의 프록시 상태를 확인할 수 있습니다. Windows에서도 실행 중인 감독 관계를 확인하지만, +앱의 프록시 상태를 확인할 수 있습니다. Windows에서도 프록시 자식 프로세스가 실행 중이면 감독 관계를 확인하지만, **Start at Login**은 검증하지 않으며 Desktop에 시작 안전 보호를 인정하지 않습니다. CLI가 Desktop의 프록시 감독을 감지하면 `ocx service install`, `repair`, `start`, diff --git a/docs-site/src/content/docs/ko/guides/integrations.md b/docs-site/src/content/docs/ko/guides/integrations.md index c5a058d89b..5f0d192334 100644 --- a/docs-site/src/content/docs/ko/guides/integrations.md +++ b/docs-site/src/content/docs/ko/guides/integrations.md @@ -3,7 +3,9 @@ title: 연동 description: 대시보드에서 OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi Code, gjc, DeepSeek Harness, MiniMax Code, ZCode, Prime Agent, Aside, Raycast, omo, Cline CLI, Kilo, Command Code와 Factory Droid를 opencodex에 연결합니다. 클라이언트마다 스위치가 하나씩 있으며 기록 전마다 백업합니다. --- -**연결** 페이지는 클라이언트의 설정 파일에 opencodex 프로바이더 블록을 쓰고 다시 제거합니다. 다음 18개 클라이언트는 각각 스위치로 관리합니다. +**연결** 페이지는 클라이언트의 설정 파일에 opencodex 프로바이더 블록을 쓰고 다시 제거합니다. 다음 클라이언트는 각각 스위치로 관리합니다. + +Windows에서 절대 경로가 필요한 오버라이드는 드라이브 문자(`C:\Users\me\client`) 또는 UNC 공유(`\\server\share\client`)를 포함해야 합니다. 현재 드라이브에 의존하는 `\Users\me\client`와 `/client/config`는 거부됩니다. `~`를 지원한다고 명시된 선택자는 유효 홈을 기준으로 확장합니다. Gentle Shell은 `~`를 확장하지 않습니다. | 클라이언트 | 설정 파일 | 형식 | 변경 적용 시점 | 자격 증명 | |---|---|---|---|---| @@ -23,7 +25,7 @@ description: 대시보드에서 OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi Code, | omo | `~/.omo/agent/models.json` | JSON | 새 세션에서 | 루프백 자리표시자 | | Cline CLI | `~/.cline/data/settings/providers.json` 및 같은 위치의 `models.json` | JSON 파일 쌍 | Cline을 중지하고 다시 시작한 뒤 | 루프백 자리표시자 | | Kilo | `~/.config/kilo`에서 먼저 존재하는 `kilo.jsonc`, `kilo.json`, `opencode.jsonc`, `opencode.json`, `config.json` (`XDG_CONFIG_HOME`로 디렉터리 변경 가능, 모두 없으면 `kilo.jsonc` 생성) | JSONC | 새 세션에서 | `OPENCODEX_KILO_API_KEY` | -| Command Code | `~/.commandcode/providers.json` (Windows 기본 홈 사용 시: `HOME ?? USERPROFILE` 값이 비어 있거나 공백만으로 구성되지 않은 Windows 절대 경로일 때만 사용하고, 그 외에는 `homedir()` 사용. 별도로 전달된 홈은 유지. 해당 홈 아래의 `.commandcode\providers.json`) | JSON | 다음 Command Code 실행 시 | 없음 — 키 없는 루프백 (`apiKey: false`) | +| Command Code | `~/.commandcode/providers.json` (Windows 기본 홈 사용 시: `HOME ?? USERPROFILE` 값이 비어 있거나 공백만으로 구성되지 않은 Windows 절대 경로일 때만 사용하고, 그 외에는 `homedir()` 사용. 별도로 전달된 홈은 유지. 해당 홈 아래의 `.commandcode\providers.json`) | JSON | 다음 Command Code 실행 시 | 없음 — 키 없는 루프백 (`apiKey: false`). 데스크톱 앱은 자체 로그인이 필요하며 opencodex는 `auth.json`을 기록하지 않습니다 | | Factory Droid | `~/.factory/settings.json` (`%USERPROFILE%\.factory\settings.json` Windows에서) | JSON | 파일 변경 시 즉시 | 키 없는 루프백 | 생성된 카탈로그에는 각 프로바이더 선택에서 활성화된 모델만 들어갑니다. Pi와 Aside를 포함한 다운로드와 관리형 연동 모두에 적용됩니다. 관리 모델 목록에는 전체 모델이 계속 표시되어 추가 모델을 활성화할 수 있습니다. @@ -92,15 +94,21 @@ Disable은 opencodex가 소유한다고 기록한 항목만 제거합니다. 이 Hermes 세션 식별 설정에는 예외가 있습니다. 기존 관리 설정에 `session_affinity_header: session-id`만 추가했다면 **Apply**로 수용할 수 있습니다. 다른 관리 필드의 수정은 계속 충돌로 처리됩니다. 적용 전에는 백그라운드 모델 목록 갱신도 보류됩니다. 이 설정은 provider의 모든 모델에 적용되며 해당 기능을 지원하는 Hermes 버전이 필요합니다. 캐시 적중률은 보장하지 않습니다. [영문 업그레이드 안내](/guides/integrations/#hermes-session-affinity)를 참조하세요. +## Hermes 프로필의 모델 목록 갱신 + +모델 목록 변경과 `ocx sync`는 실행 중인 프록시의 환경(`HERMES_HOME` 포함)에서 정한 기본 프로필만 자동 갱신합니다. 이름이 있는 프로필은 이전 목록을 유지하므로 **Connect → Hermes**에서 **Update needed**인 프로필을 선택하고 **Apply** 미리 보기를 검토한 뒤 적용하세요. CLI에는 이름이 있는 프로필 선택자가 없습니다. + +모델 목록이 바뀌지 않았다면 주석이나 `providers.opencodex` 밖 설정을 수정해도 갱신은 **Current** 상태를 유지하며 파일과 기록된 기준선을 바꾸지 않습니다. 모델 목록 변경이 대기 중이면 자동 갱신은 마지막 적용 이후 달라진 Hermes 파일을 이런 수정까지 포함해 거부합니다. 모델 목록 변경으로 **Update needed**가 표시되면 해당 변경을 **Apply**하여 자동 갱신을 다시 허용할 수 있습니다. 목록이 같은 상태의 Apply는 아무것도 바꾸지 않으며 새 파일 기준선도 저장하지 않습니다. 비활성화했거나 연결한 적 없는 설정은 자동으로 연결하지 않습니다. [영문 프로필 안내](/guides/integrations/#hermes-profiles)를 참조하세요. + ## 변경 미리 보기와 확인 Apply, Replace, Disable, Restore는 미리 보기로 시작합니다. 대화 상자는 제한된 변경 경로와 각 값의 추가·갱신·삭제 여부를 포함해 어떤 관리 설정이 바뀔지 정확히 보여줍니다. 확인하기 전에 계획을 검토하세요. 계획에 변경이 없다면 관리 대상 클라이언트 문서가 이미 요청한 상태라는 뜻입니다. Aside 프로필을 선택했다면 관리 문서가 바뀌지 않아도 확인 시 그 프로필의 동기화 기본 설정을 저장할 수 있습니다. -검토 후 파일이 바뀌면 오래된 계획으로 판단해 쓰기를 거부합니다. 대화 상자가 갱신된 계획을 보여주고 다시 확인을 요청하며, 자동으로 쓰기를 재시도하지 않습니다. 미리 보기를 일시적으로 사용할 수 없다면 페이지를 일반적으로 새로고침하고 작업을 다시 시작하세요. +검토 후 파일이 바뀌면 오래된 계획으로 판단해 쓰기를 거부합니다. 대화 상자가 갱신된 계획을 보여주고 다시 확인을 요청하며, 자동으로 쓰기를 재시도하지 않습니다. 미리 보기가 모델 카탈로그가 아직 로드되지 않았다고 알리면 대화 상자는 열린 채로 **카탈로그 로드 후 다시 시도**를 제공합니다. 통합 목록을 다시 읽은 뒤 계획을 다시 요청합니다. -Aside는 선택한 프로필 하나에 같은 미리 보기와 확인 흐름을 사용합니다. **Sync all profiles**는 별도 일괄 작업이며 하나의 통합 미리 보기에 묶이지 않습니다. +Aside는 선택한 프로필 하나에 같은 미리 보기와 확인 흐름을 사용합니다. **Sync all profiles**는 별도 일괄 작업이며 하나의 통합 미리 보기에 묶이지 않습니다. 하나의 계획은 한 프로필의 파일만 설명하므로, 충돌 상태인 Aside 개요 카드는 **프로필 선택**을 제공하고 블록 교체는 해당 프로필 페이지에서 합니다. ## 실제로 예상해야 할 동작 @@ -225,6 +233,16 @@ Undo는 원래 없던 파일까지 포함해 **두 원본 바이트 문자열 다운로드되는 `cline-config-bundle.json`에는 두 네이티브 문서 구성 요소가 있습니다. `providers.json`용 `settings`와 `models.json`용 `catalog`입니다. 번들 자체가 Cline 설정 파일은 아닙니다. 저널을 남기는 병합과 롤백에는 연동 명령을 권장합니다. 생성된 연동은 원격 수용 연결을 지원하지 않으며 인증이 없는 루프백 접근이 필요합니다. +## omo (Pi 기반) Responses 방언 + +관리되는 Pi 기반 omo 블록은 기본으로 Chat 방언(`api: "openai-completions"`)을 씁니다. Chat은 도구 호출 사이에서 이전 단계의 추론을 버리므로 긴 omo 도구 루프에서 차이가 납니다. 연결과 모든 갱신에서 Responses 방언을 쓰게 하려면 opencodex 설정 파일에만 넣을 수 있는 다음 키를 추가하세요. + +```json +{ "omoClientExport": { "api": "openai-responses" } } +``` + +수정한 설정을 읽도록 프록시를 다시 시작한 뒤(서비스로 설치했다면 `ocx service restart`, 아니면 `ocx stop` 다음 `ocx start`), 대시보드의 **Connect → omo**에서 omo 통합을 갱신하세요. 갱신만 하면 실행 중인 프록시의 설정을 쓰므로 설정 파일을 다시 읽지 않습니다. 이 설정은 omo에만 적용되며 Pi, Gentle Shell 등 다른 Pi 형식 클라이언트는 `openai-completions`를 유지합니다. Chat으로 되돌리려면 키를 지우고 같은 방법으로 다시 시작한 뒤 **Connect → omo**를 갱신하세요. 알 수 없는 값은 무시됩니다. opencodex는 여전히 `~/.omo/agent/models.json`의 `providers.opencodex`만 관리하며 다른 프로바이더는 그대로 둡니다. + ## omo (Codex / LazyCodex) 역할별 추론 강도 LazyCodex가 감지되면 omo 탭의 **omo (Codex / LazyCodex)** 섹션에서 `$CODEX_HOME/agents/*.toml`에 있는 역할마다 모델과 추론 강도를 고른 뒤 **저장**을 누를 수 있습니다. 모델 고정이 없는 역할의 행은 강도만 저장할 수 있고, 그 역할은 계속 모델을 상속합니다. opencodex는 그 역할 파일의 루트 `model`과 `model_reasoning_effort` 키만 고치고, 없는 고정값은 파일 위쪽에 추가합니다. 역할의 지침, 다른 주석과 다른 키는 그대로 둡니다. 모델만 바꿔 저장하면 `effort`를 보내지 않으므로 두 파일의 추론 강도가 그대로 유지됩니다. 단계를 고르면 역할 파일의 `model_reasoning_effort`를 추가하거나 바꾸고, LazyCodex가 그 단계를 지원하면 `~/.omo/omo.jsonc`의 `[codex].agents..reasoning`에도 씁니다(`ultra`는 역할 파일에만 남고, 이전 `reasoning`은 제거합니다). 명령줄에서는 `ocx agent roles set --effort `로 같은 작업을 합니다. @@ -237,16 +255,22 @@ LazyCodex가 감지되면 omo 탭의 **omo (Codex / LazyCodex)** 섹션에서 `$ **자동 배정**은 필요한 능력과 추론 강도를 판정한 역할 가운데 선택된 모델의 강도 단계 목록이 비어 있지 않은 모든 역할에 추론 강도를 제안하며, **적용**, **모두 적용** 또는 `ocx agent roles suggest --apply`는 그 역할의 `model_reasoning_effort` 값을 추가하거나 바꿉니다. 강도는 선택된 모델 자체의 단계에서 정하며, 가장 낮은 단계, 기본 단계, 기본보다 한 단계 높은 단계, 가장 높은 단계 중 하나입니다. 단계 목록이 비어 있으면 강도를 제안하지 않고(`proposedEffort: null`), 적용할 때 `effort`를 보내지 않아 기존 강도 고정을 그대로 둡니다. `null` 제안은 고정값을 지우지 않습니다. +CLI의 `ocx agent roles suggest --apply`는 한 이력 묶음에 **변경할 역할을 최대 50개** 적용합니다. 이미 같은 값으로 설정됐거나 평가·배정되지 않은 역할은 세지 않습니다. 50개를 넘으면 역할 업데이트를 하나도 보내지 않고 종료 코드 5로 거부합니다. `--apply` 없이 미리 확인한 뒤, 개별 변경에는 `ocx agent roles set [--effort ]`을 사용하세요. 도중에 실패했을 때 확인된 쓰기와 미확인 요청을 구분하고 재시도하는 방법은 [CLI 적용·복구 규칙](/reference/cli/agents/)을 참고하세요. + ## Kilo Kilo CLI, VS Code, JetBrains는 전역 설정을 공유합니다. 이 연동은 `~/.config/kilo` 아래의 `kilo.jsonc`, `kilo.json`, `opencode.jsonc`, `opencode.json`, `config.json` 중 먼저 존재하는 파일에 `provider.opencodex`를 씁니다. `XDG_CONFIG_HOME`로 이 디렉터리를 옮길 수 있습니다. 후보 파일이 없으면 `kilo.jsonc`를 만듭니다. 프로젝트 설정은 수정하지 않습니다. Kilo는 이 전역 파일을 모두 병합합니다. 다른 후보 파일에도 `provider.opencodex`가 있으면 상태에 충돌 파일을 표시하고 적용과 교체를 거부합니다. 연동을 켜기 전에 해당 파일에서 `provider.opencodex`를 제거하세요. 이미 소유한 파일의 블록은 충돌 중에도 비활성화할 수 있습니다. 읽을 수 없거나 안전하지 않은 후보 파일도 쓰기를 막습니다. +OpenCodex는 이 후보 파일을 JSONC로 읽습니다. `//` 한 줄 주석은 CR, LF, CRLF 줄바꿈에서 끝나므로, 어떤 줄바꿈으로 저장한 파일이든 주석 뒤의 설정을 그대로 읽습니다. + 관리하는 부분은 OpenCode V1 형식의 `provider.opencodex`(`npm`, `options`, `models`)뿐입니다. OpenCode V2의 `providers` 키는 내보내지 않습니다. 대신 모델별 추론 선택지는 프로바이더 블록 안의 변형 맵으로, OpenCode 내보내기와 같은 유효 정규 메타데이터에서 기록됩니다. `$schema`, `model`, `enabled_providers`, MCP 등의 키는 사용자가 관리합니다. 적용한 뒤 Kilo에서 `opencodex/`을 선택하세요. 루프백에서는 `options.apiKey`로 `{env:OPENCODEX_KILO_API_KEY}`를 사용합니다. 루프백이 아닌 바인드에서는 인증을 `options.headers["x-opencodex-api-key"]`로 옮기며 실제 키를 저장하지 않습니다. 적용 시 전역 파일 전체를 보기 좋은 JSON으로 다시 쓰므로 다른 키의 주석과 후행 쉼표는 보존되지 않습니다. Kilo는 자동 카탈로그 갱신 대상입니다. `ocx sync`, `POST /api/sync`, 표시 여부·프로바이더·프리셋 변경은 다른 클라이언트와 같은 소유 블록만 갱신하는 안전한 규칙으로 소유한 Kilo 블록을 갱신하며, 새 Kilo 세션이 갱신된 파일을 읽습니다. +후보 파일을 읽을 때 배열 요소나 객체 속성 뒤의 후행 쉼표는 허용합니다. 빈 배열과 객체는 `[]`, `{}`로 작성하세요. `[,]`, `{,}`는 잘못된 형식으로 거부합니다. + ```bash ocx integration client enable --client kilo ocx export --client kilo --out ./kilo.jsonc @@ -304,3 +328,19 @@ GitHub Copilot 데스크톱 앱에서 opencodex를 OpenAI 호환 모델 프로 행과 기본값이 함께 제거되며, 되돌리기는 저장된 행과 기본값을 함께 복원합니다. Factory Droid는 `~/.factory/settings.json`(Windows에서는 `%USERPROFILE%\.factory\settings.json`)을 사용합니다. `ocx integration client enable --client droid`로 명시적으로 활성화한 다음 `/model`에서 사용자 지정 모델을 선택하세요. 관리되는 항목에는 키가 없으며 루프백에서만 동작합니다. 비활성화하면 관리되는 항목이 제거되고, Undo는 저장된 원본 바이트를 복원합니다. 기존 `config.json`에 OpenCodex 항목이 있거나 `settings.local.json`이 `customModels`를 덮어쓰면 활성화 전에 충돌을 해결하세요. [Factory BYOK 문서](https://docs.factory.ai/model-independence/byok)를 참고하세요. + +## Hermes / Command Code: model names + +Hermes and Command Code support `--model-names alias|routed` (API: `modelNames`). +The default is `routed`, independent of `preferModelAliasIds`. A connection +stores its mode; later Apply without the option preserves it. Alias mode uses +only provider-qualified aliases that the router proves equivalent; missing, +unsafe or colliding aliases fall back to routed keys. Combos keep their keys. +Removed/renamed aliases migrate on the next successful managed refresh, with +foreign-edit refusal. Named Hermes profiles need explicit Apply. + +`ocx export --client hermes --model-names alias --json` previews a current +already loaded catalog without writing client files or managed state; a cold or +stale catalog returns unavailable. Explicit `--out` writes an export artifact. +See the [English integration guide](/guides/integrations/#opt-in-alias-model-names) +for the canonical workflow. diff --git a/docs-site/src/content/docs/ko/guides/model-ordering.md b/docs-site/src/content/docs/ko/guides/model-ordering.md index e921bfdfbc..5aa24876b6 100644 --- a/docs-site/src/content/docs/ko/guides/model-ordering.md +++ b/docs-site/src/content/docs/ko/guides/model-ordering.md @@ -28,7 +28,7 @@ selector가 없을 때의 priority는 다음과 같습니다. | --- | ---: | --- | | `subagentModels[i]` | `i` (`0`부터 `4`) | `src/codex/catalog/sync.ts`의 featured rank map | | 그 밖의 라우팅 모델 | `5` | `src/codex/catalog/sync.ts`의 라우팅 항목 생성 | -| 기본 네이티브 GPT slug | `9` | `src/codex/catalog/sync.ts`의 네이티브 항목 생성 | +| 기본 네이티브 GPT slug | `sourcePriority` | `src/codex/catalog/sync.ts`의 네이티브 항목 생성 | | featured 목록이 있을 때 선택되지 않은 네이티브 모델 | 최소 `featured.length + 100` | `src/codex/catalog/sync.ts`의 네이티브 카탈로그 병합 | 관리 API는 `src/server/management/agent-settings-routes.ts`의 `slice(0, 5)`로 `subagentModels`를 최대 @@ -69,7 +69,7 @@ Codex의 priority 정렬에서도 이 선두 순서가 보존됩니다. 3. 카탈로그 병합 과정에서 featured 블록 아래로 밀린 선택되지 않은 네이티브 모델 `subagentModels`가 없으면 라우팅 모델은 priority `5`를 유지하고, 네이티브 GPT 항목은 정상 priority -(opencodex가 만든 항목은 보통 `9`)를 사용합니다. 라우팅 그룹 내부는 계속 프로바이더/id +(sourcePriority, 출처가 없으면 `9`)를 사용합니다. 라우팅 그룹 내부는 계속 프로바이더/id 알파벳순입니다. ## 예시 diff --git a/docs-site/src/content/docs/ko/guides/model-routing.md b/docs-site/src/content/docs/ko/guides/model-routing.md index 4b5f184e34..d20f8320c7 100644 --- a/docs-site/src/content/docs/ko/guides/model-routing.md +++ b/docs-site/src/content/docs/ko/guides/model-routing.md @@ -82,7 +82,15 @@ fallback하지 않습니다. 막지는 않습니다. - 프로바이더의 `selectedModels`가 비어 있지 않으면 카탈로그 허용 목록으로 동작합니다. 실시간 모델 탐색과 직접 라우팅은 그대로 두고, 카탈로그와 `/v1/models`에 내보낼 모델만 줄입니다. -- `modelDiscovery.newModelPolicy`의 기본값은 `"off"`이며, 기존 설정에서 생략한 경우에도 적용됩니다. 첫 실시간 탐색 성공 시 설정된 `defaultModel`만 표시합니다. 일치하는 기본 모델이 없으면 **모델**에서 필요한 모델을 직접 켜세요. 기존 선택 목록, 모델별 켜기/끄기 설정과 짧은 탐색 기준, 수동·정적 카탈로그는 보존합니다. 선택 설정이 없는 기존 실시간 카탈로그가 20개 이상이고 기본 모델이 설정되어 있으면 한 번만 기본 모델로 줄입니다. 기본 모델이 없는 기존 탐색 기준은 표시 상태를 보존하며, 이후 수동 변경은 다시 초기화하지 않습니다. 이후 발견된 모델도 직접 켜기 전까지 숨깁니다. 명시적 `"on"`은 자동 노출을 허용합니다. `/v1/models`, 클라이언트 내보내기, Codex 카탈로그 공개 전에 적용하며, 탐색 실패 시 선택을 바꾸지 않습니다. `ocx models new-policy off`에 `--provider `을 추가해 공급자별로 설정하고, `ocx models new-arrivals --json`으로 새 모델을 확인합니다. +- `modelDiscovery.newModelPolicy`가 `"off"`이면 첫 실시간 탐색 성공 시 기준을 만들고, + 이후 추가된 모델을 `disabledModels`에 넣습니다. 이 정책은 `/v1/models`, 대시보드, + 클라이언트 설정 내보내기, 서비스 시작을 포함한 Codex 카탈로그 동기화에서 새 모델을 공개하기 + 전에 적용됩니다. 수동으로 활성화한 모델은 이후 새로고침과 내보내기에서도 활성 상태를 유지합니다. + 새 설치의 기본값은 `"off"`이며, 기존 설치는 직접 바꾸기 전까지 `"on"`을 유지합니다. + `ocx models new-policy off`로 전역 정책을 설정하고, `--provider `으로 프로바이더별 + 정책을 지정합니다. `ocx models new-arrivals [--json]`으로 새 모델을 확인할 수 있습니다. + 실패하거나 제한된 탐색은 기준을 바꾸지 않습니다. `selectedModels`가 비어 있지 않은 + 프로바이더는 이미 선택 목록을 사용하므로 이 정책으로 모델을 자동 비활성화하지 않습니다. - `provider.disabled: true`인 프로바이더는 카탈로그 탐색에서 제외됩니다. 명시적 `provider/model` 요청은 실패하고, `defaultModel` / `models[]` 검사에서도 건너뜁니다. - `providerContextCaps`는 공급자별로 Codex에 표시할 컨텍스트 상한을 지정합니다. diff --git a/docs-site/src/content/docs/ko/guides/ollama-clients.md b/docs-site/src/content/docs/ko/guides/ollama-clients.md new file mode 100644 index 0000000000..26bb2eb6a2 --- /dev/null +++ b/docs-site/src/content/docs/ko/guides/ollama-clients.md @@ -0,0 +1,68 @@ +--- +title: Ollama 호환 클라이언트 +description: Ollama API를 사용하는 도구를 opencodex에 연결해 설정된 프로바이더 모델을 사용합니다. +--- + +opencodex는 Ollama HTTP API의 일부를 제공합니다. 따라서 Ollama와만 통신할 수 있는 도구도 opencodex에 +이미 설정한 모델을 사용할 수 있습니다. 요청은 Chat Completions 경로로 변환되어 선택한 프로바이더로 +전송됩니다. opencodex는 사용자의 컴퓨터에서 모델을 내려받거나 저장하거나 실행하지 않습니다. + +## 클라이언트 연결 + +프록시 주소를 Ollama 호스트로 사용합니다. 기본 로컬 설치에서는 다음과 같습니다. + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +프록시가 API 키를 요구하는 경우(예: `0.0.0.0` 바인드) `/v1/chat/completions`와 같은 방식으로 키를 +보냅니다. 예: `Authorization: Bearer `. 모델 범위가 지정된 키는 허용된 모델만 보고 사용할 수 +있습니다. 이 엔드포인트는 기본 리스너에서만 제공되며, 인증 없는 루프백 리스너, Remote Link, 허브 관리 +인그레스에서는 노출되지 않습니다. + +## 엔드포인트 + +| 엔드포인트 | 동작 | +| --- | --- | +| `GET /api/version` | opencodex 버전. | +| `GET /api/tags` | 설정된 프로바이더 모델을 `provider/model` 이름으로 나열합니다. | +| `POST /api/show` | `{ "model": "provider/model" }`은 알려진 정보만 반환합니다. 파일 크기, 다이제스트, 템플릿, 라이선스는 없습니다. | +| `POST /api/chat` | `system`, `user`, `assistant`, `tool` 메시지로 대화합니다. | +| `POST /api/generate` | 선택적 `system`이 있는 단일 프롬프트. | + +그 밖의 모든 `/api/*` 경로는 opencodex 관리 API로 남습니다. + +## 지원하는 요청 필드 + +- `model`: `/api/tags`에 있는 이름. +- `stream`: 기본값은 `true`(줄 단위 JSON)입니다. JSON 응답 하나를 받으려면 `false`로 설정합니다. +- `images`: 사용자 메시지(chat) 또는 요청(generate)에 넣는 base64 PNG, JPEG, GIF, WebP. +- `tools`(chat 전용): 함수 도구. assistant 메시지는 각 호출의 `id`를 포함해 그대로 다시 보냅니다. + `tool` 결과는 `tool_call_id`로, 없으면 `tool_name`으로 연결됩니다. +- `options`: `temperature`, `top_p`, `num_predict`, `stop`. +- `format`: `"json"`만 지원합니다. + +각 `/api/chat` 요청은 모든 assistant 메시지에 걸쳐 **도구 호출을 합계 1,024개까지** 허용합니다. +이미 결과가 있는 호출도 합계에 포함됩니다. 한도를 넘으면 프로바이더로 보내기 전에 HTTP 400을 반환합니다. +대화 이력을 줄인 뒤 다시 보내세요. 남겨 둔 도구 결과에는 해당 assistant 도구 호출도 함께 남겨야 합니다. + +그 밖의 항목은 무시되지 않고 HTTP 400으로 거부됩니다. `think`, `keep_alive`, `suffix`, `raw`, +`template`, `context`, 기타 `options`, JSON 스키마 `format`, 이미지 URL이 여기에 해당합니다. Ollama의 모델 +관리 및 임베딩 엔드포인트는 제공되지 않습니다. + +콤보, 라우팅 정책, `--fast` 또는 effort 별칭, 호출자 자신의 자격 증명을 전달하는 프로바이더는 여기서 +선택할 수 없습니다. 이러한 요청은 업스트림으로 아무것도 보내기 전에 실패합니다. + +## 응답 + +완료된 응답에는 `done: true`와 `stop`, `tool_calls`, `length` 중 하나인 `done_reason`이 있습니다. +`prompt_eval_count`와 `eval_count`는 프로바이더가 사용량을 보고한 경우에만 나타나며, 소요 시간 필드는 +보고되지 않습니다. 스트림은 업스트림 응답이 완전히 끝난 뒤 `done: true` 줄을 정확히 한 번 보냅니다. + +오류는 Ollama 형식 `{ "error": "message" }`을 사용하며 HTTP 상태를 유지합니다. 속도 제한과 혼잡 거부에는 +`Retry-After`도 포함됩니다. 콘텐츠 필터나 알 수 없는 이유로 중단된 응답은 일반적인 중지가 아니라 오류로 +반환됩니다. 스트림이 시작된 뒤 실패하면 마지막 줄은 `error` 객체이며 `done: true` 줄은 뒤따르지 않습니다. + +요청은 다른 트래픽과 마찬가지로 대시보드 요청 로그에 표시되며, 응답 헤더 +`x-opencodex-request-id`가 해당 행을 가리킵니다. diff --git a/docs-site/src/content/docs/ko/guides/opencode.md b/docs-site/src/content/docs/ko/guides/opencode.md index f1ea7cafbb..0d2f11cd11 100644 --- a/docs-site/src/content/docs/ko/guides/opencode.md +++ b/docs-site/src/content/docs/ko/guides/opencode.md @@ -34,6 +34,8 @@ opencodex/gpt-5.6-sol # native slugs stay unprefixed 확인할 수 있으며, 기존의 공급자, 에이전트, 키 바인딩, MCP 항목, 그리고 상대 경로 `{file:…}` 참조는 계속 원래 파일을 기준으로 해석됩니다. +JSONC를 읽을 때 일부 Windows 편집기가 파일 맨 앞에 붙이는 UTF-8 BOM 하나를 허용합니다. 문자열 안의 BOM 문자는 그대로 유지합니다. + 이번 실행에서만 opencodex는 생성된 `provider.opencodex`와 `providers.opencodex` 블록을 OpenCode의 인라인 런타임 레이어를 통해 추가합니다. 이 레이어는 전역/사용자 지정/프로젝트 구성 뒤에 병합되며, 자식 프로세스에서는 충돌하는 키만 덮어씁니다. diff --git a/docs-site/src/content/docs/ko/guides/providers.md b/docs-site/src/content/docs/ko/guides/providers.md index 2d52b2757f..e51b6e70f0 100644 --- a/docs-site/src/content/docs/ko/guides/providers.md +++ b/docs-site/src/content/docs/ko/guides/providers.md @@ -42,6 +42,8 @@ shipped v1 config는 marker 2의 단일 옵션 행으로 자동 이관됩니다. `~/.opencodex/config.json.pre-openai-tiers-v2.bak`에 한 번 보존되며 다음 명령으로 복원합니다: `cp ~/.opencodex/config.json.pre-openai-tiers-v2.bak ~/.opencodex/config.json`. +[Claude OAuth 클라이언트 버전 오류](/ko/guides/claude-code/#claude-oauth-클라이언트-버전-오류) + ## 인증 모드 프로바이더 설정에서 쓸 수 있는 `authMode`는 세 가지이며, 기본값은 `key`입니다. 빌트인 레지스트리는 @@ -55,8 +57,9 @@ shipped v1 config는 marker 2의 단일 옵션 행으로 자동 이관됩니다. [`retryOn429`](/ko/reference/configuration/)(동일 키 429 재시도)는 API 키 프로바이더 (`authMode: "key"`)에만 적용됩니다. OAuth·forward·로컬 프리셋은 제외됩니다 — 같은 토큰을 -재전송해서는 안 되며, 로컬 런타임에는 보존할 원격 키가 없습니다. 옵트인입니다: 옵션이 없으면 -꺼져 있고, 객체가 있으면 `enabled: false`가 아닌 한 활성화됩니다. +재전송해서는 안 되며, 로컬 런타임에는 보존할 원격 키가 없습니다. 문서화된 대상별 기본값을 제외하면 옵트인입니다. 정식 Mistral Chat은 기존 요청 단위 전송 한도 안에서 끈질긴 재시도 정책(재전송 6회, 대체 간격 10초)을 사용합니다. `enabled: false`를 포함한 명시적인 `retryOn429` 설정이 우선합니다. Mistral 프리셋은 전달받은 프롬프트 캐시 키도 기본으로 전달하며, `promptCacheKey: false`로 전달을 끌 수 있습니다. 캐시 친화성은 재사용 가능성을 높이지만 캐시 적중을 보장하거나 토큰 처리량 제한을 없애지는 않습니다. + +Mistral은 Studio 키와 Vibe 키 모두에 하나의 API 키 프로바이더를 사용합니다. 키 종류와 요금제 허용량은 [Mistral API 키 문서](https://docs.mistral.ai/admin/identity-access/api-keys)에 설명되어 있으며, 프록시는 키에서 구독 등급을 추론하지 않습니다. 모든 모델에서 업스트림이 명시한 `Retry-After` 기한은 같은 자격 증명과 모델의 호출 사이에서 공유됩니다. 재시도 시각이 없는 429는 유효한 분 단위 카운터가 용량 소진을 보여 주거나, 거절된 쿼리의 측정 비용이 남은 토큰을 넘지만 공시된 전체 허용량 안에 들어올 때 보수적인 60초 복구 대기를 시작할 수 있습니다. 이는 로컬 복구 정책이며 서버 재설정 시각을 정확히 예측하는 것이 아닙니다. 정상 트래픽에서는 다음 쿼리의 캐시나 비용을 예측하지 않습니다. 대기 후 복구 프로브를 한 번 보내고, 성공하면 일반 트래픽으로 돌아갑니다. 근거가 없거나, 형식이 잘못됐거나, 이용 권한이 0이거나, 월간 한도가 소진됐거나, 전체 허용량을 넘는 경우에는 재설정을 지어내거나 기록을 압축하지 않습니다. `requestPacing: { "enabled": false }` 또는 `retryOn429: { "respectRetryAfter": false }`로 공유 페이싱을 끕니다. 같은 키로 재전송할 때 Mistral의 재시도 시각이 `retryOn429.maxIntervalMs`를 넘으면 프록시는 일찍 재전송하지 않고 429와 재시도 힌트를 반환합니다. 라운드 로빈 키 선택이 켜져 있으면 대기 중인 요청은 키 쿨다운을 다시 확인하고 대체 키의 페이싱 용량을 확보하며, 출력 전의 키 거절은 요청의 기존 전송 한도 안에서 정상 키로 복구될 수 있습니다. 컨텍스트 창과 모델별 압축 설정은 서로 독립적으로 유지됩니다. ## 1. ChatGPT 로그인 (forward / 패스스루) @@ -167,7 +170,7 @@ deny-by-default 상태로 유지됩니다. 자격 증명에 고정된 계정 id나 이메일이 있는 OAuth 프로바이더는 로그인을 여러 개 보관할 수 있습니다. Providers 페이지에서 계정을 추가하고, 다른 계정을 로그아웃하지 않은 채 활성 계정만 바꿀 수 있습니다. -계정 식별 정보가 없는 Kimi 자격 증명은 일반 로그인에서는 활성 슬롯을 교체하지만, 명시적인 **계정 추가**에서는 기존 슬롯을 보존하고 별도의 새 슬롯을 활성화합니다. Kiro 계정은 프로필 ARN을 키로 저장됩니다. +계정 식별 정보가 없는 Kimi 자격 증명은 일반 로그인에서는 활성 슬롯을 교체하지만, 명시적인 **계정 추가**에서는 기존 슬롯을 보존하고 별도의 새 슬롯을 활성화합니다. Kiro 계정은 프로필 ARN과 로그인한 사용자의 이메일(제공되는 경우)을 함께 사용해 구분합니다. 같은 조직 프로필을 공유하는 사용자도 각자의 자격 증명을 별도로 유지할 수 있습니다. `chatgpt`는 Codex 계정 풀에 별도 저장소가 있어 항상 단일 슬롯만 씁니다. 토큰은 `~/.opencodex/auth.json`에 저장되고, `/api/oauth/accounts`는 마스킹된 메타데이터만 반환합니다. @@ -186,6 +189,8 @@ cat accounts.json | ocx account import google-antigravity --format cockpit-tools ### Kiro 자격 증명 가져오기 +대시보드에서 **AWS IAM Identity Center**를 선택하고 조직의 AWS 액세스 포털 URL과 SSO 리전을 입력하면 CLI나 SSH 없이 계정을 추가할 수 있습니다. 브라우저에서 기기 코드를 승인하고 Kiro 프로필이 여러 개면 저장할 프로필을 선택하세요. 아래 CLI 설명은 **Kiro CLI** 선택 항목에 해당합니다. + Kiro 로그인에는 Kiro CLI가 필요합니다. Unix에서는 `curl -fsSL https://cli.kiro.dev/install | bash`, Windows PowerShell에서는 `irm 'https://cli.kiro.dev/install.ps1' | iex`로 설치한 뒤 먼저 `kiro-cli login`으로 로그인하세요. `kiro-cli` 세션이 없으면 `ocx login kiro`는 붙여 넣은 액세스 토큰이나 `KIRO_ACCESS_TOKEN` 환경 변수로 폴백합니다. 일반 `ocx login kiro` 가져오기는 CLI SQLite 데이터베이스를 읽기 전용으로 열며 데이터베이스, WAL, SHM을 수정하지 않습니다. @@ -210,7 +215,7 @@ Kiro 로그인에는 Kiro CLI가 필요합니다. Unix에서는 `curl -fsSL http ## 3. API 키 카탈로그 -opencodex에는 빌트인 프리셋이 104개 들어 있습니다. 키 방식 84개, OAuth 16개, 로컬 3개, +opencodex에는 빌트인 프리셋이 107개 들어 있습니다. 키 방식 86개, OAuth 17개, 로컬 3개, 기본 ChatGPT 포워드 프리셋 1개입니다. 대시보드의 **Add provider** 선택기는 키 발급 페이지를 열고, 입력한 키를 검증한 뒤 저장합니다(검증은 프로바이더별로 다릅니다). 주요 항목은 다음과 같습니다: @@ -259,13 +264,13 @@ Cline IDE/CLI에서만 제공되며 API로는 사용할 수 없습니다. `minim | Novita AI | `https://api.novita.ai/openai/v1` | | Together | `https://api.together.xyz/v1` | | Fireworks | `https://api.fireworks.ai/inference/v1` | -| Moonshot (Kimi API) · Kimi (coding) | `https://api.moonshot.ai/v1` · `https://api.kimi.com/coding/v1` | +| Moonshot (Kimi API) · Kimi (coding) | `https://api.moonshot.ai/v1` · `https://api.kimi.com/coding/v1`. `moonshot` API 기본 모델은 `kimi-k3.1-pro`입니다. 공식 API 주소에 저장된 `kimi-k2.5` 선택은 이 모델로 마이그레이션됩니다. | | Hugging Face | `https://router.huggingface.co/v1` | | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | | Z.AI (GLM Coding) | `https://api.z.ai/api/coding/paas/v4` | | Zhipu AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | | [BigModel Coding Plan — Responses (정적 모델 목록)](/guides/providers/#bigmodel-coding-plan-over-responses) | `https://open.bigmodel.cn/api/v1` | -| Qwen Cloud | Token plan(기본): `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · 종량제: `https://dashscope.aliyuncs.com/compatible-mode/v1` · 또는 사용자 지정 | +| Qwen Cloud | Token plan(기본): `https://token-plan.maas.qwencloudapi.com/compatible-mode/v1` · 종량제: `https://dashscope.aliyuncs.com/compatible-mode/v1` · 또는 사용자 지정 | | Tencent Cloud Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | | Volcengine Ark · Coding Plan · Agent Plan | `https://ark.cn-beijing.volces.com/api/v3` · `https://ark.cn-beijing.volces.com/api/coding/v3` · `https://ark.cn-beijing.volces.com/api/plan/v3` | @@ -285,12 +290,23 @@ Chat Completions 모델(그리고 Responses 전용이라 Responses로 보내는 [OpenGateway 대시보드](https://opengateway.ai/api-keys)에서 키를 발급한 뒤 `ocx provider add opengateway`를 실행하거나 대시보드에서 **OpenGateway**를 선택하세요. Chat 요청은 설정한 Bearer 키를 사용하며 공개 모델 목록은 키의 유효성을 검증하지 않습니다. +OpenGateway는 Responses에서 네이티브 커스텀 도구 호출의 재전송을 거절하므로 프리셋은 코드 모드의 `exec` 등 Codex 커스텀 도구를 전송 전에 함수 도구로 변환합니다. +Responses 도구 결과 배열은 텍스트로 변환하고 이미지는 짝이 맞는 도구 결과 묶음 뒤의 메시지에 보존합니다. refusal이나 불투명한 내용 등 지원하지 않는 결과 part는 전송 전에 명시적인 클라이언트 입력 오류로 거절합니다. +이미지의 `original` 상세도는 게이트웨이가 지원하는 `high`로 바꾸며 이미지 바이트는 그대로 유지합니다. +네이티브 Responses 경로는 텍스트가 없는 완료 응답도 검사합니다. 출력 예산이 소진됐으면 +`incomplete / max_output_tokens`로 알리며 요청한 예산을 임의로 늘리지 않습니다. +예산이 남고 안전하게 재전송할 수 있는 빈 완료는 기존 호출 한도 안에서 한 번만 재시도합니다. +`emptyCompletionRetry: false` 또는 `OCX_EMPTY_COMPLETION_RETRY=0`이면 이 재시도를 끕니다. +텍스트·거절·도구 동작·알 수 없는 스트림 이벤트가 관측되면 재전송하지 않고 원본을 유지합니다. +다른 제공자의 동작과 재시도 기본값에는 적용하지 않습니다. +재전송은 명시적인 `store: false`, 완전한 입력, 클라이언트 실행 도구만 있는 요청에 한정합니다. +`web_search` 같은 서버 실행 도구가 선언돼 있으면 도구 이벤트가 없어도 자동 재전송하지 않습니다. **OpenCode Zen**(`opencode-zen`)은 [opencode.ai/auth](https://opencode.ai/auth)에서 발급한 API 키로 `https://opencode.ai/zen/v1`을 사용합니다. 무료 모델은 분당 약 15–20회 요청의 짧은 창 속도 제한에 걸릴 수 있습니다(커뮤니티 측정; OpenCode는 RPM을 공개하지 않음). 속도 제한 429에 `Retry-After`가 없으면 opencodex가 안내와 합성 `Retry-After`를 추가하며, 유효한 업스트림 헤더가 우선합니다. 동일 키 재시도는 [`retryOn429`](/ko/reference/configuration/)로 선택합니다. 정식 `opencode-zen` 제공자에서 API 키 인증과 공식 경로 `https://opencode.ai/zen/v1` 또는 `https://opencode.ai/inference/v1`을 사용하면 Gemini는 기본 `googleMode: ai-studio`에서 Google 네이티브 API를 자동으로 사용합니다. Zen 모델 ID는 `-tiered` 접미사가 없는 Flash ID도 그대로 유지합니다. Claude는 `googleMode`와 관계없이 Anthropic Messages를 사용합니다. 저장된 설정을 읽을 때 이 네이티브 모델의 조건에 맞는 기존 Chat/Responses 재정의와 조건에 맞는 Responses 전용 `image_generation` 호스팅 도구 선호 설정만 무시합니다. 사용자 지정 제공자, 키 인증이 아닌 경로, 그 밖의 선호 설정은 그대로 유지합니다. -**`opencode-free` 지원이 제거되었습니다.** OpenCode의 업스트림 무료 등급 제한으로 모든 모델이 `403 permission_denied`를 반환하기 때문입니다([#7255](https://github.com/lidge-jun/opencodex/issues/7255)). 기존 설정을 불러오면 해당 항목과 종속 모델 참조를 메모리에서 비활성화하고 프로세스당 한 번 경고하며 파일은 변경하지 않습니다. 기본 공급자였다면 표준 OpenAI OAuth 경로가 기본값이 됩니다. `opencode-go`, API 키를 사용하는 `opencode-zen` 또는 다른 공급자를 사용하세요. [OpenCode Zen 약관](https://opencode.ai/docs/zen/). +**`opencode-free` 지원이 제거되었습니다.** OpenCode의 업스트림 무료 등급 제한으로 모든 모델이 `403 permission_denied`를 반환하기 때문입니다([#7255](https://github.com/lidge-jun/opencodex/issues/7255)). 기존 설정을 불러오면 해당 항목과 종속 모델 참조를 메모리에서 비활성화하고 프로세스당 한 번 경고하며 불러올 때 파일은 변경하지 않습니다. 다음 설정 저장 시 해당 항목과 참조가 config.json에서 제거됩니다. 저장 전에 원본 파일을 같은 폴더의 `config.json.pre-opencode-free-removal.bak`에 자동 보관합니다. 해당 이름이 이미 사용 중이면 고유한 이름의 사본을 만듭니다. 바이트가 동일한 독립 사본은 소유자만 접근할 수 있음을 검증한 경우에만 재사용하고, 그렇지 않으면 그 옆에 보호된 새 사본을 만듭니다. 기존 파일은 덮어쓰지 않습니다. 첫 로드가 겹치면 동일하게 보호된 사본이 여러 개 남을 수 있습니다. 경고에 복구 사본 경로가 표시됩니다. 다운그레이드 후 복원하려면 이 사본을 config.json 위에 복사하세요. 자동 복사에 실패하면 config.json을 즉시 복사하라는 경고가 표시됩니다. 기본 공급자였다면 표준 OpenAI OAuth 경로가 기본값이 됩니다. `opencode-go`, API 키를 사용하는 `opencode-zen` 또는 다른 공급자를 사용하세요. [OpenCode Zen 약관](https://opencode.ai/docs/zen/). 수동적 읽기(passive read)에서는 메모리 내 비활성화만 적용하고 사본이나 경고를 만들지 않습니다. 정상 Claude Desktop 할당과 기본값은 유지됩니다. 소스 모델 허용 목록이 비게 되는 규칙은 비활성화되며, 주입 모델이 제거되면 네이티브 하위 에이전트 동기화도 비활성화됩니다. 이후 설정을 저장하면 제거된 참조는 다시 기록되지 않고 정상적인 동시 편집은 유지됩니다. @@ -459,6 +475,9 @@ Sol/Terra/Luna를 폴백 목록에 넣어 둡니다. | Codex 로그인(Pool 또는 Direct) | `gpt-5.6-*` | 922,000 | | OpenAI (API key) | `openai-apikey/gpt-5.6-*`와 `*-pro` | 922,000 (max input 922,000) | | OpenRouter | `openrouter/openai/gpt-5.6-sol`, `openrouter/openai/gpt-5.6-terra`, `openrouter/openai/gpt-5.6-luna` | 922,000 | +| Codex | `gpt-6.1-terra` | 500,000 / 872,000 | +| OpenAI API | `openai-apikey/gpt-6.1-terra` | 1,050,000 (128,000 max output) | +| OpenRouter | `openrouter/openai/gpt-6.1-terra` | 1,050,000 | | Cursor | `cursor/gpt-5.6-sol`, `cursor/gpt-5.6-terra`, `cursor/gpt-5.6-luna` | 1,000,000 | 네이티브 GPT-5.6 항목은 고정된 업스트림 reasoning 단계를 그대로 따릅니다. 예를 들어 Luna에는 @@ -479,7 +498,7 @@ Amazon Bedrock 네이티브 API처럼 이 구현 중 어느 것과도 맞지 않 Gateway**는 URL에 계정 + 게이트웨이 id를 채워야 합니다. Copilot은 혼합 wire 카탈로그를 제공합니다. 모델(`gpt-5.3-codex`, `gpt-5.4`, -`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)은 에이전트 +`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)은 에이전트 트래픽에 대해 `/chat/completions`를 거부하므로 opencodex는 이 모델들을 내장 기본값으로 Responses API를 통해 라우팅하고, 다른 Copilot 모델은 모두 chat completions를 유지합니다. 우선순위는 하드 wire 핀 → 명시적 [`modelAdapters`](/ko/reference/configuration/providers/) @@ -544,6 +563,7 @@ opencodex를 로컬 OpenAI 호환 서버로 향하게 하세요 — 보통은 (`headers`, `noReasoningModels`, `noVisionModels`, `models`, …)는 [설정 레퍼런스](/ko/reference/configuration/)를 참고하세요. +설정과 검증 단계는 [사용자 지정 원격 게이트웨이 검증](/ko/guides/custom-gateway/)을 참고하세요. ### Antigravity 쿼터 조회 실패 확인 diff --git a/docs-site/src/content/docs/ko/guides/remote-hub.md b/docs-site/src/content/docs/ko/guides/remote-hub.md index eaa3558e86..204cefb5ef 100644 --- a/docs-site/src/content/docs/ko/guides/remote-hub.md +++ b/docs-site/src/content/docs/ko/guides/remote-hub.md @@ -334,7 +334,7 @@ services: hub: pull_policy: build build: - context: https://github.com/lidge-jun/opencodex.git#main + context: https://github.com/lidge-jun/opencodex.git#dev dockerfile: Dockerfile target: runtime args: diff --git a/docs-site/src/content/docs/ko/guides/remote-link.md b/docs-site/src/content/docs/ko/guides/remote-link.md index ea3733f92e..43a1f35793 100644 --- a/docs-site/src/content/docs/ko/guides/remote-link.md +++ b/docs-site/src/content/docs/ko/guides/remote-link.md @@ -10,10 +10,10 @@ description: SSH로 OpenCodex Home 컴퓨터와 Child 컴퓨터를 연결합니 - Home 컴퓨터에서 OpenSSH 키 로그인으로 Child 컴퓨터에 접속할 수 있어야 합니다. - 자식이 시작하는 링크에서는 자식에서 OpenSSH 키 로그인으로 홈에 접속할 수 있어야 합니다(비밀번호 로그인은 지원하지 않음). - Child 컴퓨터에 OpenCodex 2.66.0 이상이 설치되어 있어야 합니다(자식이 시작하는 링크에서는 Home에도). -- 두 컴퓨터 모두 macOS 또는 Linux여야 합니다. +- 두 컴퓨터는 macOS, Linux 또는 Windows x64를 사용할 수 있습니다. Windows에는 OpenSSH Server와 Windows PowerShell이 필요하며 Git Bash와 curl은 필요하지 않습니다. - Home에서 Child를 추가하는 대시보드는 Home에서 직접 열거나 페어링된 Hub 세션을 사용해야 합니다. 현재 컴퓨터를 Child로 전환하려면 운영자가 페어링한 대시보드 세션이 필요하며, 자격 증명 없이 발급된 로컬 세션은 이 라우팅 변경을 확정할 수 없습니다. -비밀번호 SSH와 Windows는 현재 흐름에서 지원하지 않습니다. 링크는 어느 쪽에서든 시작할 수 있습니다. 아래 순서대로 Home에서 시작하거나, 이어지는 "이 컴퓨터를 Child로 연결하기" 절처럼 Child에서 시작합니다. +비밀번호 SSH는 지원하지 않습니다. Home 또는 Child에서 링크를 시작할 수 있습니다. Windows는 동일하게 고정된 OpenSSH 연결을 통해 PowerShell을 실행합니다. ## `#remote`에서 Child 추가하기 @@ -55,18 +55,18 @@ Home의 프로바이더를 사용할 컴퓨터에서 다음을 진행합니다. - **Connected**는 SSH 터널이 준비되어 Child가 Home 링크를 사용할 수 있다는 뜻입니다. - **Reconnecting**은 터널을 다시 연결하는 중이라는 뜻입니다. 재시도 중에는 요청이 일시적으로 `Retry-After`와 함께 `503`을 반환할 수 있습니다. 자기 대시보드에서 연결한 Child에서는 요청이 먼저 터널이 돌아오기를 최대 15초 기다립니다. -- **Failed**는 조치가 필요하다는 뜻입니다. SSH 인증, 확인한 호스트 키, 포워딩 또는 타임아웃 사유를 확인하세요. SSH 터널을 띄운 쪽이 절전, 장애, 재시작 뒤에도 스스로 다시 시도합니다. Home이 추가한 Child라면 Home이, 자기 대시보드에서 연결한 Child라면 Child가 시도합니다. 타임아웃이나 포워딩 오류 뒤에는 약 1분마다, 인증 오류 뒤에는 5분마다 시도합니다. 호스트 키가 바뀐 경우에는 다시 시도하지 않습니다. 바로 다시 연결하려면 Home 대시보드에서 **Retry**를 누르거나 Home에서 `ocx link reconnect --link-id `를 실행하세요. OpenCodex를 재시작하지 않고 그 링크의 터널만 다시 띄웁니다. +- **Failed**는 조치가 필요하다는 뜻입니다. SSH 인증, 확인한 호스트 키, 포워딩 또는 타임아웃 사유를 확인하세요. SSH 터널을 띄운 쪽이 절전, 장애, 재시작 뒤에도 스스로 다시 시도합니다. Home이 추가한 Child라면 Home이, 자기 대시보드에서 연결한 Child라면 Child가 시도합니다. 타임아웃이나 포워딩 오류 뒤에는 1분 뒤에 다시 시도하고, 다시 실패할 때마다 간격을 두 배로 늘려 최대 5분마다 시도합니다. 인증 오류 뒤에는 5분마다 시도합니다. 호스트 키가 바뀐 경우에는 다시 시도하지 않습니다. 바로 다시 연결하려면 Home 대시보드에서 **Retry**를 누르거나 Home에서 `ocx link reconnect --link-id `를 실행하세요. OpenCodex를 재시작하지 않고 그 링크의 터널만 다시 띄웁니다. 링크가 실패해도 로컬 프로바이더로 조용히 전환하지 않습니다. ## Child 제거하기 -Child의 **Disconnect**를 선택하고 alias를 확인합니다. Home은 터널을 중지하고 해당 Child의 링크 키를 폐기한 뒤 저장된 링크 기록을 삭제합니다. +Child의 **Disconnect**를 선택하고 alias를 확인합니다. Home은 터널을 중지하고 해당 Child의 링크 키를 폐기한 뒤 저장된 링크 기록을 삭제합니다. 경량 에이전트(`ocx-child`)로 연결된 Child는 기본적으로 빠른 재연결을 위해 `~/.cache/opencodex/bin/ocx-child` 파일을 남겨두며, 확인 대화상자에서 **심어둔 경량 에이전트 파일까지 원격 컴퓨터에서 함께 삭제**를 선택하거나 `ocx link revoke --link-id --purge`를 실행하면 에이전트 파일까지 함께 삭제합니다. Home은 이 삭제를 `PATH`에 있는 다른 `ocx-child`가 아니라 `~/.cache/opencodex/bin/ocx-child`(Windows에서는 `%LOCALAPPDATA%\opencodex\bin\ocx-child.exe`)에 심어둔 파일로 실행합니다. 그 파일이 없거나 Child가 파일을 삭제했다고 확인하지 않으면 Disconnect는 오류를 보고하고 링크를 그대로 남겨 두므로, 다시 시도하거나 삭제 옵션 없이 연결을 해제하거나 파일을 직접 지울 수 있습니다. `--purge`는 경량 Child에만 적용됩니다. 전체 OpenCodex 설치에서는 Home이 거부하고, Home이 Child 종류를 기록하기 전에 저장된 링크라면 먼저 Child를 확인합니다. Home에서 Child의 연결 해제 명령을 실행할 수 없으면 **Remove here only**를 선택합니다. 그러면 이 컴퓨터의 터널, 키, 기록만 삭제됩니다. 그 다음 Child에 로그인하여 실행합니다. ```bash -ocx disconnect +ocx disconnect # 경량 모듈 Child인 경우 ~/.cache/opencodex/bin/ocx-child detach ``` 자식 연결을 끊으려면 자식에서 `ocx disconnect`를 실행합니다. 이 명령은 클라이언트 터널을 끊고 SSH를 통해 홈에서 링크를 폐기합니다. 홈에서 폐기하지 못하면 다음 문구를 출력합니다: `Home revoke failed; run ocx link revoke --link-id on the home.` @@ -79,16 +79,19 @@ Child는 링크를 통해 Home 컴퓨터의 프로바이더와 프로바이더 ```text ocx link probe [--json] -ocx link add [--expect-fingerprint SHA256:…] [--json] +ocx link add [--plant] [--expect-fingerprint SHA256:…] [--json] ocx link port [--json] ocx link issue --alias --tunnel-port [--json] ocx link status [--json] -ocx link revoke --link-id [--json] +ocx link revoke --link-id [--purge] [--force --yes] [--json] ocx link reconnect --link-id [--json] +ocx link check (--link-id | --all) [--no-wait] [--json] ``` 비대화형 실행(TTY 없음)에서는 `--expect-fingerprint`가 필수입니다. 대화형 터미널에서는 옵션을 생략할 수 있지만, 제시된 지문을 명시적으로 확인해야 합니다. +Home에서 `ocx link check (--link-id | --all)`를 실행하면 Home이 추가한 각 Child의 설치 버전, 설치 종류, 업데이트 경로를 읽습니다. 링크의 SSH로 Child의 `ocx update --plan`을 실행하며(Child마다 60초, 동시에 세 대), 이 명령은 계획만 계산하고 아무것도 바꾸지 않습니다. 2.97.0보다 오래된 Child는 `owner-action`(`legacy-ocx`)으로 표시되고, 버전은 macOS와 Linux에서는 읽기 전용 SSH 호출을 한 번 더 해서, Windows에서는 링크로 보고된 버전에서 가져옵니다. Child 쪽에서 연결한 링크와 `ocx-child` Child는 SSH 없이 보고됩니다. `ocx link status --json`은 각 행에 `child` 블록(버전, 버전 차이, 카탈로그 최신 여부, 활동, 마지막 작업)을 추가합니다. 자세한 내용과 종료 코드는 [Child install, catalog and activity](/guides/remote-link/#child-install-catalog-and-activity)(영문)를 참고하세요. + ## 관련 가이드 - [Remote Hub 배포](/ko/guides/remote-hub/) @@ -99,7 +102,7 @@ ocx link reconnect --link-id [--json] OpenCodex가 백그라운드 서비스로 실행 중이어도 기존 `ocx gui pair --origin <로컬 주소>` 명령을 사용할 수 있습니다. 서비스의 개인 OpenCodex 폴더를 소유한 계정으로 명령을 실행하고, 반환된 일회용 코드를 로컬 대시보드에 입력하세요. 서버 터미널, 추가 비밀번호, Windows Hello 또는 하드웨어 보안키가 필요하지 않습니다. CLI와 서버는 같은 최신 버전과 설정 폴더를 사용해야 하며, 업데이트 뒤에는 이전 서버를 재시작하세요. Hub 초대도 CLI와 서버의 버전이 다르면 함께 업데이트해야 합니다. 설정 폴더나 일회용 승인 폴더가 심볼릭 링크이면 페어링을 거부하므로, `OPENCODEX_HOME`에는 보호된 실제 폴더 경로를 지정하세요. -CLI는 짧게 유효한 일회용 승인 정보를 만들고, 사용하거나 실패하면 정리를 시도합니다. 실행 정보를 읽는 것만으로는 승인받을 수 없고, 검증에 필요한 원래 비밀값은 파일에 저장하지 않습니다. 이 방식은 개인 폴더의 쓰기 권한을 확인하는 것으로, 생체 인증이나 사람의 직접 승인을 증명하지는 않습니다. 사용자 파일을 자유롭게 수정할 수 있는 프로그램은 여전히 신뢰 범위 안에 있습니다. 기존 Hub 초대의 권한 정책은 바뀌지 않습니다. 페어링 요청이 실패하면 안내된 문제를 해결한 뒤 새 명령을 실행하세요. Windows의 SSH Remote Link 지원을 추가하는 변경은 아닙니다. +CLI는 짧게 유효한 일회용 승인 정보를 만들고, 사용하거나 실패하면 정리를 시도합니다. 실행 정보를 읽는 것만으로는 승인받을 수 없고, 검증에 필요한 원래 비밀값은 파일에 저장하지 않습니다. 이 방식은 개인 폴더의 쓰기 권한을 확인하는 것으로, 생체 인증이나 사람의 직접 승인을 증명하지는 않습니다. 사용자 파일을 자유롭게 수정할 수 있는 프로그램은 여전히 신뢰 범위 안에 있습니다. 기존 Hub 초대의 권한 정책은 바뀌지 않습니다. 페어링 요청이 실패하면 안내된 문제를 해결한 뒤 새 명령을 실행하세요. Windows의 SSH Remote Link는 위에서 설명한 별도의 PowerShell 실행 경로를 사용합니다. 페어링 도중 프로세스가 중단되면 명령을 다시 실행해 새로운 승인을 받으세요. 서비스나 페어링 명령이 실행 중일 때는 페어링 상태 파일을 수동으로 제거하지 마세요. diff --git a/docs-site/src/content/docs/ko/guides/remote-workspace.md b/docs-site/src/content/docs/ko/guides/remote-workspace.md index 338234f4da..1dcdf4564a 100644 --- a/docs-site/src/content/docs/ko/guides/remote-workspace.md +++ b/docs-site/src/content/docs/ko/guides/remote-workspace.md @@ -93,6 +93,8 @@ ocx remote-workspace status 프롬프트를 보내면 수락 여부를 즉시 응답하고, 대시보드는 진행과 완료 상태를 폴링합니다. 수락 응답을 잃으면 초안은 제출 여부를 알 수 없다는 알림과 함께 남습니다. 다시 보내기 전에 세션 진행 상태를 확인하세요. 대시보드는 프롬프트를 자동 재시도하지 않습니다. +턴을 시작하는 동안 Pi 프로세스가 종료되거나 확장 기능에서 오류가 발생하면, Pi가 아직 해당 턴의 수락을 응답하지 않았더라도 세션에 실패가 표시됩니다. + 프롬프트 실행 중에도 **Stop**을 사용할 수 있습니다. Hub 코딩 에이전트의 현재 턴을 중단하고 활성 Executor 명령을 취소하며, 늦게 온 응답이 중지된 세션을 다시 열지 못하게 합니다. ## 여러 세션을 분할해서 보기 diff --git a/docs-site/src/content/docs/ko/guides/sidecars.md b/docs-site/src/content/docs/ko/guides/sidecars.md index 9716fc2793..f84514a74c 100644 --- a/docs-site/src/content/docs/ko/guides/sidecars.md +++ b/docs-site/src/content/docs/ko/guides/sidecars.md @@ -18,6 +18,12 @@ ChatGPT 로그인(`forward`) 프로바이더나 저장된 Anthropic OAuth 프로 ## 웹 검색 사이드카 +라우팅된 Responses 요청에서는 Anthropic 검색 모델 호출과 연결 재설정 후 재시도도 요청 전체의 +모델 전송·토큰 한도에 포함됩니다. RunTurn 어댑터와 패스스루 검색 브리지에도 적용되며, +`maxSearchesPerTurn`을 높여도 모델 전송 허용량이 추가되지는 않습니다. 한도가 소진되면 +Anthropic에 요청을 보내지 않고 해당 검색을 오류 결과로 반환합니다. 검색 보조 요청은 +원래 모델의 마지막 복구용 예산을 소모하지 않습니다. 독립 `/v1/alpha/search`는 기존 동작을 유지합니다. + Codex가 패스스루가 아닌 라우팅 모델에 호스팅 `web_search`를 요청하면 opencodex는 다음 순서로 처리합니다. @@ -158,3 +164,15 @@ OpenCodex가 `web_search` 가로채기를 멈추고 Codex 통합이 `~/.codex/co 파일을 직접 고치고 싶다면 이전처럼 `config.json`에서 `enabled`를 `false`로 두면 됩니다. Anthropic OAuth 검색과 이미지 설명은 기존 Claude Code OAuth fingerprint 선례를 따르지만, 실제 계정과 작업량으로 충분히 soak test하는 편이 좋습니다. 전체 필드는 [설정 레퍼런스](/ko/reference/configuration/server/#sidecars)를 참고하세요. + +검색 응답의 선택 필드 형식이 잘못되어도 유효한 답변과 출처는 유지합니다. 오류 메시지 값의 형식이 잘못되면 일반 실패 메시지를 표시합니다. 같은 출력 부분의 전체 텍스트 완료 이벤트가 반복되면 이전 스냅샷을 교체하여 답변 중복을 막습니다. 서로 다른 출력 부분은 별도로 유지합니다. + +완료 이벤트에서 콘텐츠 인덱스를 생략해도 이미 서로 다른 인덱스를 가진 부분을 합치지 않습니다. 최종 메시지의 콘텐츠가 잘못되었거나 누락되면, 고유한 항목 ID로 해당 출력 위치를 유지하며 스트리밍 텍스트를 복구합니다. 위치 정보가 충돌하거나 최종 항목 ID가 중복되면 이 정보로 순서를 추정하지 않습니다. + +OpenAI 검색·비전 사이드카는 CR, LF, CRLF 줄바꿈과 이들이 섞인 응답을 처리하며, CRLF가 여러 네트워크 청크로 나뉘어도 이벤트를 읽습니다. 서버가 마지막 줄바꿈 없이 응답 본문을 닫아도 마지막 완료 또는 실패 이벤트를 읽습니다. 첫 종료 이벤트 또는 `[DONE]`에서 수집을 끝내며, 같은 네트워크 청크에 있어도 뒤따르는 이벤트는 무시합니다. 완료되지 않았거나 크기 제한으로 중단된 응답은 계속 오류로 처리합니다. + +검색 답변의 Sources 목록에서 URL과 짝을 이루지 못한 글머리표는 출처로 삭제하지 않고 답변에 남깁니다. 제목 다음 줄에 해당 URL이 있으면 하나의 출처로 처리합니다. `mode:fast`처럼 인라인 코드 안의 비 HTTP URI 형태 텍스트는 답변에 남기며, 코드로 표시한 HTTP(S) URL은 출처로 처리합니다. + +스트리밍 중 이미 받은 URL이라도 최종 응답에 출처 제목이 있으면 그 제목을 사용합니다. 최종 응답이 같은 URL을 여러 번 인용하면 그중 처음으로 유효한 제목을 사용합니다. 유효한 최종 제목이 없으면 유효한 스트리밍 제목을 유지합니다. 스트리밍에만 있는 출처도 기존 출처 수·URL·제목·바이트 제한 안에서 보존합니다. + +긴 검색어와 답변은 UTF-16 서로게이트 쌍을 나누지 않는 위치에서 줄이므로, 결과 길이 제한 때문에 😀 같은 한 글자가 반으로 잘리지 않습니다. 다만 제로 폭 결합자(ZWJ)로 이어진 이모지처럼 여러 글자로 이루어진 조합은 중간에서 잘릴 수 있습니다. diff --git a/docs-site/src/content/docs/ko/guides/sub-agent-surface.md b/docs-site/src/content/docs/ko/guides/sub-agent-surface.md index c0273412ec..baece5604c 100644 --- a/docs-site/src/content/docs/ko/guides/sub-agent-surface.md +++ b/docs-site/src/content/docs/ko/guides/sub-agent-surface.md @@ -33,6 +33,42 @@ opencodex는 이 값을 Codex가 읽는 실시간 `/v1/models` 카탈로그와 v2 로스터의 경우 적합성은 세 가지 상태로 나뉩니다. `"v2"`로 표시된 항목, 명시적으로 `null`로 설정된 항목, 또는 `multi_agent_version` 필드가 없는 항목은 사용 가능합니다. 진짜 `"v1"` 핀은 해당 모델이 다른 협업 서피스에 속한다고 명시하므로 제외됩니다. +## `spawn_agent`가 광고하는 모델 + +Codex는 `spawn_agent` 도구 설명에 모델을 최대 5개까지 나열하며, 그 목록은 Codex가 직접 고릅니다. 선택기에 보이는 카탈로그 행을 `priority` 오름차순으로 정렬한 뒤 앞의 5개를 가져옵니다. **Subagents** 페이지의 로스터(`subagentModels`)는 로스터 순서대로 소속 모델에 가장 낮은 priority(계정 셀렉터가 없으면 `0`~`4`)를 주는 방식으로만 이 목록에 영향을 줍니다. 목록을 로스터로 제한하지는 않습니다. + +모델을 1~4개만 지정하면 Codex는 남은 칸을 priority 순으로 다음 행들로 채웁니다. 이 행들은 사용자가 고른 것이 아니며, 대시보드도 어떤 모델이 들어갔는지 보여 주지 않습니다. 어떤 행이 들어가는지는 카탈로그에 따라 다릅니다. + +| 카탈로그 | 남은 칸을 채우는 행 | +| --- | --- | +| Codex 계정 셀렉터 없음 | 나머지 라우팅 `provider/model` 행. 모두 priority `5`를 공유하므로 provider 이름, 그다음 모델 id의 알파벳 순서로 들어갑니다. 지정하지 않은 네이티브 GPT 행은 priority가 `100`에 지정한 id 수를 더한 값 이상이라 그 뒤에 옵니다. | +| Codex 계정 셀렉터 있음 | 계정 지정 네이티브 행(`/`). 지정한 행 바로 뒤에 옵니다. 지정하지 않은 라우팅 행은 priority `1005`로 옮겨져 그 뒤에 옵니다. | + +예를 들어 계정 셀렉터가 없고 로스터가 다음과 같으면: + +```json +{ "subagentModels": ["xai/grok-4.5", "anthropic/claude-sonnet-5"] } +``` + +| 칸 | 모델 | Priority | 이유 | +| ---: | --- | ---: | --- | +| 1 | `xai/grok-4.5` | `0` | 로스터 첫 번째 항목 | +| 2 | `anthropic/claude-sonnet-5` | `1` | 로스터 두 번째 항목 | +| 3 | `deepseek/deepseek-v4-flash` | `5` | 알파벳 순으로 첫 번째인 남은 라우팅 행 | +| 4 | `google/gemini-3-pro` | `5` | 다음 라우팅 행 | +| 5 | `moonshot/kimi-k3` | `5` | 다음 라우팅 행 | +| 6+ | `zai/glm-5.2`, 그다음 네이티브 GPT 행 | `5`, 그다음 `102 + sourcePriority` | 5개 밖 | + +로스터가 비어 있으면 opencodex는 아무것도 고정하지 않고, 5개는 카탈로그의 원래 priority를 따릅니다. + +채워진 칸도 일반 광고 항목이므로 메인 에이전트가 그 모델을 고를 수 있습니다. 이 목록은 허용 목록도 아닙니다. 메인 에이전트가 정확한 이름을 대면 Codex는 5개 밖의 카탈로그 모델도 받아들입니다. Codex가 광고하는 목록을 제어하려면: + +- 모델 5개를 지정하세요. 로스터가 가득 차면 채울 칸이 남지 않습니다. +- 절대 제안되지 않았으면 하는 모델은 비활성화하거나 해당 provider의 `selectedModels`에서 빼세요. 비활성화되었거나 선택되지 않은 모델은 선택기에서 빠지므로 칸을 채울 수 없습니다. +- `modelPickerOrder`는 Codex가 정렬에 쓰는 priority를 바꿉니다. 라우팅 행만 담은 목록은 나열된 미지정 행을 `1000` 이상으로 옮기므로, 나열되지 않은 라우팅 행이 먼저 칸을 채웁니다. bare 네이티브 id가 들어 있는 목록은 지정한 행까지 포함해 선택기 전체를 정렬합니다. 나열된 행이 앞에 오므로 나열되지 않은 어떤 행보다 먼저 광고 칸을 차지합니다. [Model ordering](/guides/model-ordering/)을 참고하세요. + +v2에서는 Codex가 5개를 고르기 전에 `"disabled"`로 고정된 행을 건너뜁니다. 그 밖에는 똑같이 동작합니다. opencodex v2 가이던스 로스터(`{{roster}}`)는 5개 안에 든, 설정된 로스터 모델만 나열합니다. 그래서 채워진 모델은 Codex 도구 설명에만 나타나고 opencodex 가이던스에는 나타나지 않습니다. Codex는 세션을 시작할 때 카탈로그를 읽으므로 로스터 변경은 새 세션부터 적용됩니다. + ## 위임 모델과 추론 강도 대시보드의 **서브에이전트 위임** 설정은 다음 세 가지 값을 제어합니다. @@ -161,6 +197,10 @@ curl -X PUT http://localhost:10100/api/injection-model \ 선택기에서 숨겨져 있거나, 다섯 모델 표시 한도를 넘었거나, 카탈로그에 없거나, v1에 고정되어 있을 수 있습니다. `v2`, `null`, 또는 값이 없는 서피스 값은 사용할 수 있지만, 실제 `"v1"` 핀은 사용할 수 없습니다. +### 지정하지 않은 모델이 왜 `spawn_agent` 목록에 보이나요? + +Codex는 광고하는 칸을 최대 5개까지 카탈로그에서 priority 순으로 채웁니다. 지정한 모델이 5개보다 적으면 다음 행들이 남은 칸을 차지합니다. 위의 "`spawn_agent`가 광고하는 모델" 절을 참고하세요. + ### 모드를 바꾸면 실행 중인 세션에도 반영되나요? 아닙니다. 모드를 바꾼 뒤에는 새 Codex 세션을 시작하세요. 오래 실행 중인 App 호스트에 오래된 카탈로그 상태가 남아 있으면 `ocx sync`를 실행한 뒤 해당 Codex 서피스를 다시 시작하세요. diff --git a/docs-site/src/content/docs/ko/guides/web-dashboard.md b/docs-site/src/content/docs/ko/guides/web-dashboard.md index d014bf6f19..05cf8b5402 100644 --- a/docs-site/src/content/docs/ko/guides/web-dashboard.md +++ b/docs-site/src/content/docs/ko/guides/web-dashboard.md @@ -13,7 +13,7 @@ opencodex는 프록시가 제공하는 로컬 웹 대시보드(`gui/` 아래의 ocx gui ``` -브라우저에서 `http://localhost:`를 엽니다. 허브에서 관리 리스너를 켜 두면 `http://127.0.0.1:<관리 포트>`를 엽니다. 프록시가 꺼져 있으면 먼저 자동으로 시작합니다. +브라우저에서 실행 중인 프록시의 주소를 엽니다. 기본값은 `http://127.0.0.1:`이고, IPv6 루프백 `::1`에 바인딩했다면 `http://[::1]:`입니다. 이 리터럴 주소는 로컬 브라우저 페어링에 필요한 설정된 origin을 유지합니다. 허브에서 관리 리스너를 켜 두면 `http://127.0.0.1:<관리 포트>`를 엽니다. 프록시가 꺼져 있으면 먼저 자동으로 시작합니다. 개발 중에는 실행 중인 프록시와 GUI 개발 서버를 따로 띄울 수 있습니다. ```bash @@ -27,11 +27,31 @@ bun run dev:gui 원격 대시보드는 표준 비밀번호 폼을 표시하므로 브라우저 비밀번호 관리자가 토큰 저장과 자동 완성을 제안할 수 있습니다. 대시보드 자체는 토큰을 메모리에만 보관하며 `localStorage`나 `sessionStorage`에 쓰지 않습니다. 저장 여부는 전적으로 브라우저 또는 비밀번호 관리자가 결정합니다. +**이 기기 기억하기**는 기본적으로 꺼져 있습니다. 직접 HTTPS 대시보드(또는 로컬 루프백)에서 관리자 토큰을 서버 발급 HttpOnly, SameSite=Strict 기기 쿠키와 이 사이트의 localStorage에 저장하는 별도의 기기 증명으로 교환합니다. HTTPS 쿠키는 Secure이며 해당 호스트에만 적용됩니다. 쿠키와 증명은 모두 관리자 토큰이 아니며, 어느 쪽도 단독으로 작동하지 않습니다. 같은 호스트명의 여러 포트는 쿠키를 공유하므로, 오리진별 저장소의 증명이 기억한 기기를 이 대시보드 오리진에 묶습니다. 그래도 전용 호스트명을 권장합니다. 관리자 토큰은 localStorage나 sessionStorage에 저장하지 않습니다. 브라우저 저장소를 사용할 수 없거나 증명 저장에 실패하면 기억하기는 사용 불가로 표시됩니다. 독립 실행형 대시보드가 TLS를 종료하는 리버스 프록시 뒤에 있으면 OpenCodex가 일반 HTTP 요청으로 보기 때문에 해당 주소에서는 기억하기를 거부합니다. 로그인 창이 이를 안내하고 옵션을 끄며, 기억하기 없이 로그인하는 것은 계속 가능합니다. 신뢰된 Hub 관리 리스너는 예외이며 계속 기기를 기억할 수 있습니다. + +비공개 dashboard-sessions.json에는 쿠키·증명·관리자 인증 정보·브라우저 식별 해시, 서버 오리진과 고정 30일 만료를 저장합니다. Safari 홈 화면 앱을 다시 열면 유효한 기기 기록으로 단기 세션을 재개합니다. 기억한 세션으로는 GitHub 스타, 리셋 크레딧 소비, 프롬프트 계층 편집, Meta Muse 로그인, 데스크톱 호환성 변경, 할당량 검증에 동의할 수 없습니다. 이 작업에는 새 로컬 세션이나 페어링한 세션을 사용하세요. 릴레이·다른 오리진·원격 평문 HTTP에서는 기억하기를 지원하지 않습니다. 만료, 브라우저 식별 변경, 관리자 토큰 교체 후 서버 재시작 시 다시 로그인해야 합니다. + +사이드바나 모바일 작업의 **이 기기 잊기** 또는 로그아웃이 성공하면 기기 기록과 모든 파생 세션을 즉시 철회하고 브라우저의 증명을 삭제합니다. 로그아웃 실패 시에는 재시도할 수 있도록 증명을 유지합니다. 서버는 변경을 게시하기 전에 기록 내용을 디스크에 동기화하지만, 충돌 후 디렉터리 항목의 내구성은 최선 노력 수준입니다. 이전 토큰 저장 키는 읽거나 마이그레이션하지 않고 삭제합니다. 신뢰하는 기기에서만 사용하세요. Safari 자동 완성을 복원하는 기능은 아닙니다. + +## 구버전(클래식) 대시보드 + +대시보드는 새로 디자인되었습니다. 사이드바는 이제 **매일**, **처음 설정**, **세부 설정**으로 페이지를 +묶고, 홈 화면에서 시작합니다. 이전 디자인은 같은 프록시의 `/classic/` 주소(예: +`http://127.0.0.1:10100/classic/`)에서 **구버전 대시보드**로 계속 쓸 수 있습니다. + +- 사이드바 아래쪽 테마 버튼 옆의 시계 아이콘(**구버전 UI**)을 누르면 바뀝니다. 구버전 사이드바 + 아래쪽 맨 위의 **새 UI로 전환**을 누르면 돌아옵니다. +- 고른 대시보드는 브라우저마다 기억되므로, 나중에 `/`를 열어도 고른 쪽으로 열립니다. 데스크톱 앱도 + 같은 선택을 따릅니다. 트레이 팝오버는 항상 새 디자인입니다. +- 구버전 대시보드는 이전 디자인을 그대로 보관한 것입니다. 같은 프록시와 통신하고 같은 설정을 + 바꾸지만, 리디자인 이후에 추가된 페이지와 설정은 새 대시보드에만 있습니다. + ## 사용량 요약 바 시작 안전성 페이지를 제외한 모든 페이지 상단의 한 줄 요약에 프로바이더별 현재 할당량 사용률이 표시됩니다. 예: `OpenAI 31% | Claude 54% | xAI 12% | Google 8%`. 프로바이더 작업 화면과 같은 할당량 보고(`GET /api/provider-quotas`)를 탭이 보이는 동안 60초마다 읽으며, 업스트림 강제 새로고침은 하지 않습니다. - 각 항목은 보고된 창 가운데 우선순위가 높은 창을 표시합니다. 주간, 월간, 5시간, 프로바이더 고유 창 또는 선불 크레딧 순서입니다. +- 선불 크레딧 사용률이 90% 이상이고 우선 일반 창이 위험 수준이 아니면 크레딧을 대표값으로 표시합니다. 일반 창도 위험 수준이면 그 창을 유지합니다. - 70% 이상 사용하면 주황색, 90% 이상이면 빨간색으로 표시됩니다. - 항목에 마우스를 올리거나 키보드로 포커스하면 보고된 모든 창의 사용률, 초기화 시각, 데이터 기준 시각이 나옵니다. 터치 화면에서는 첫 번째 탭에서 나옵니다. - 항목을 클릭하면(터치 화면에서는 두 번째 탭) 프로바이더 화면에서 해당 프로바이더의 계정 탭이 열리고, 거기서 계정이나 API 키를 관리합니다. @@ -50,6 +70,7 @@ bun run dev:gui | **시작 안전성** | 주입된 Codex 라우팅이 재부팅 후에도 유지되는지 서비스와 launcher shim 상태, 정확한 복구 명령과 함께 표시합니다. | | **Windows 트레이** | 로그인할 때 사용자 전용 트레이를 시작하고 프록시 시작·중지·재시작·대시보드·상태를 클릭으로 제어합니다. 트레이는 재시작 서비스가 아닙니다. | | **Codex 자동 시작** | 이미 설치된 Codex launcher shim이 `ocx ensure`를 실행하도록 허용합니다. 이 토글은 shim이나 백그라운드 서비스를 설치하지 않습니다. | +| **텔레메트리** | **Proxy details**(`#proxy-telemetry`)에서 **익명 사용 통계 공유**를 켜거나 끄고 **JSON 미리보기**를 확인합니다. 첫 실행이나 업데이트 후 동의 팝업은 **계속**을 클릭할 때만 선택을 저장하며(`PUT /api/telemetry`), 닫으면 아무것도 기록하지 않습니다. [텔레메트리 및 개인정보](/ko/guides/telemetry/)를 참고하세요. | | **Providers** | 프로바이더를 추가, 편집, 기본으로 설정(활성만), 활성화/비활성화, 제거하고, 지원되는 OAuth 계정 풀과 API key 풀을 관리합니다. 현재 기본 프로바이더를 제거하면 남아 있는 첫 번째 활성 프로바이더로 전환됩니다(있는 경우); 없으면 삭제가 거부되고 현재 기본이 유지됩니다. Claude(Anthropic) OAuth 풀에서는 로그인한 계정마다 자체 5시간·주간 한도 막대가 표시되며(사용량은 자격 증명 단위), 조회 실패 시 마지막 값을 유지하고 일시 불가 상태로 표시합니다. 프로바이더를 선택하지 않았을 때 보이는 Provider Overview에는 **전체 할당량 갱신** 버튼이 있어 설정된 모든 프로바이더를 서버에서 한 번에 다시 읽습니다. 조회에 실패한 프로바이더는 마지막 값을 유지하므로, 상태 문구는 모든 값이 새로 왔다고 말하지 않고 조회가 끝났다고만 알리며, 각 행의 확인 시각이 프로바이더별 신선도를 보여 줍니다. | | **Add provider** | 탭 위의 검색창 하나가 계정·무료·로컬·유료 네 탭을 한 번에 찾습니다. 검색 중에는 선택한 탭이 움직이지 않고, 결과를 탭별로 묶어 개수와 함께 보여 줍니다. 로컬 런타임(Ollama, vLLM, LM Studio, LiteLLM)은 별도 탭을 쓰며, 긴 설명은 두 줄로 줄고 클릭하면 전체가 열립니다. | | **Codex Auth** | ChatGPT/Codex 풀 계정을 추가하고, 다음 세션 계정을 선택하고, 5시간 / 주간 / 30일 할당량을 갱신하며, 할당량 자동 전환을 켜거나 끄고 1~100% 임계값과 일시적 실패 failover를 설정합니다. | @@ -62,9 +83,19 @@ bun run dev:gui Usage, Dashboard, 공급자 작업 화면·카탈로그, API 키 화면은 읽을 수 있는 기록이 없어도 일부 기록 제외 경고를 표시합니다. 횟수·날짜·사용 순위는 읽을 수 있는 기록만 반영합니다. 이력이 불완전하면 모델의 ‘많이 사용한 순서’ 저장을 거절합니다. 다른 순서를 선택하거나 이력을 복구한 뒤 다시 시도하세요. +### 앱별 사용량 + +Usage는 현재 접근 범위에서 **모든 앱**, **모든 기기**, 최근 30일을 기본으로 엽니다. 페이지가 열려 있는 동안 앱·기기·기간을 좁힐 수 있으며, 다시 열면 기본값으로 돌아갑니다. + +전체 앱을 선택하면 Models와 Providers 다음에 **앱** 내역이 표시됩니다. 선택한 기기와 기간에 대해 앱별 전체 토큰 비중, 토큰 수, API 정가 환산 추정 비용, 요청 수, 사용량이 측정된 요청 수를 보여 줍니다. Codex CLI·데스크톱·IDE는 Codex로 합산됩니다. 클라이언트 정보가 없는 과거 기록은 **미분류**로 표시하며 **알 수 없음**·**기타**와 구분합니다. 앱 하나를 선택하면 이 내역은 숨겨집니다. 프록시가 내역을 제공하지 않으면 사용 불가로, 빈 내역을 제공하면 보고서에 앱 사용량이 없는 것으로 표시합니다. + ### 요청 로그 필터 -Logs에서는 클라이언트 종류, 가로챈 요청, 공급자, 정확한 모델명, 상태, 시간, +요청 상세 화면은 일반 프록시 오류 문구 대신 기록된 업스트림 실패 원인을 우선 표시합니다. 물리적 업스트림 전송 수는 유효할 때 항상 표시하며, 회계 정보가 없거나 유효하지 않으면 0이 아니라 **Unavailable**로 표시합니다. **Retries**는 완전히 정산되고 일관된 단일 시도가 기록된 경우에만 첫 전송 이후 추가 전송 횟수로 표시합니다. 여러 시도, 미해결·불일치 회계 또는 손실 있는 attempt 정규화에서는 재시도 횟수를 만들어 내지 않고 숨깁니다. 알 수 없는 영속 원인은 상태 기반 제목으로 돌아갑니다. **Upstream reason**은 분류된 공급자 상태(속도 제한, 할당량 또는 크레딧 소진, 컨텍스트 창 초과, 지원되지 않는 위치, 계정 인증 필요, 모델 사용 불가 등)를, **Failure detail**은 정지 시간 초과나 바이트 상한처럼 프록시가 작성한 텍스트를 표시합니다. 새 행에는 공급자 자체의 오류 텍스트를 저장하지 않습니다. 이전 `usage.jsonl` 파일에는 남아 있을 수 있지만, 대시보드는 읽을 때 이를 버립니다. + +Logs는 앱별 탭 대신 모든 앱의 요청을 함께 표시하고 각 요청에 아이콘만 있는 클라이언트 칩을 붙입니다. 인식된 클라이언트는 SVG 로고를, 알 수 없거나 기타로 분류된 클라이언트는 중립적인 물음표 아이콘을 사용합니다. 앱 이름은 화면에 텍스트로 표시하지 않으며 스크린 리더에는 계속 제공됩니다. 클라이언트 정보가 없다고 Codex나 요청 실패로 간주하지 않습니다. 칩은 공급자·프로토콜과 별개로 클라이언트 앱을 나타내며 앱 필터가 아닙니다. + +Logs에서는 가로챈 요청, 공급자, 정확한 모델명, 상태, 시간, 속도, 대화 ID 조건을 함께 적용할 수 있습니다. 현재 불러온 로그만 필터링하며, 공급자·모델 선택지에는 폴백 시도도 포함됩니다. 모델명은 대소문자와 앞뒤 공백을 무시하지만 부분 이름은 일치하지 않습니다. 선택한 공급자나 모델이 불러온 로그에서 @@ -78,9 +109,9 @@ Logs에서는 클라이언트 종류, 가로챈 요청, 공급자, 정확한 모 없는 요청은 제외됩니다. 성공은 2xx, 오류는 4xx·5xx입니다. 필터를 적용하면 일치하는 건수와 불러온 전체 건수가 표시됩니다. 필터를 초기화하면 -불러온 모든 행이 다시 나타나고 키보드 포커스는 클라이언트 종류의 전체 선택으로 돌아갑니다. +불러온 모든 행이 다시 나타납니다. 조건에 맞는 요청이 없는 상태와 로그 자체가 빈 -상태는 구분해서 표시합니다. 클라이언트 종류는 방향키와 Home/End로 선택할 수 있습니다. +상태는 구분해서 표시합니다. 불러온 범위 밖의 과거 로그는 조회하지 않습니다. ### 섹션으로 바로 가기 diff --git a/docs-site/src/content/docs/ko/index.mdx b/docs-site/src/content/docs/ko/index.mdx index f1182e8c0d..471cafd707 100644 --- a/docs-site/src/content/docs/ko/index.mdx +++ b/docs-site/src/content/docs/ko/index.mdx @@ -1,10 +1,10 @@ --- -title: "opencodex — Codex를 어떤 LLM 위에서든" -description: OpenAI Codex & Claude Code를 위한 범용 프로바이더 프록시 — Codex CLI, App, SDK와 Claude Code에서 어떤 LLM이든 사용하세요. +title: "opencodex — Codex, Claude Code 등을 잇는 로컬 게이트웨이" +description: "AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨이: Codex, Claude Code, Claude Desktop, Grok Build에서 원하는 프로바이더를 쓰고, 관리형 설정으로 더 많은 도구를 연결하세요." template: splash head: - tag: title - content: "opencodex — Codex를 어떤 LLM 위에서든" + content: "opencodex — Codex, Claude Code 등을 잇는 로컬 게이트웨이" - tag: meta attrs: property: og:locale diff --git a/docs-site/src/content/docs/ko/reference/adapters.md b/docs-site/src/content/docs/ko/reference/adapters.md index 546a0dea6e..cd6ed21d0b 100644 --- a/docs-site/src/content/docs/ko/reference/adapters.md +++ b/docs-site/src/content/docs/ko/reference/adapters.md @@ -23,6 +23,13 @@ interface ProviderAdapter { 스트림으로 표현할 수 없는 전송 방식을 지원합니다. 이후 [`bridge.ts`](/ko/reference/architecture/#브리지)가 이벤트를 Responses SSE로 바꿉니다. +## 공통 도구 인자 보정 + +브리지는 도구 스키마에 따라 정수 필드의 정수형 실수와 문자열 전용 필드의 안전한 정수를 +보정합니다. 안전한 정수 범위를 벗어난 값, 오버플로 숫자, 보정하지 않는 정수가 아닌 소수는 원래 토큰을 정확히 유지하면서 +다른 안전한 필드는 계속 보정합니다. 중첩 배열과 중복 키의 unsafe 토큰도 모두 보존하므로, +타임아웃 보정이 관련 없는 식별자를 조용히 바꾸지 않습니다. + ## `openai-chat` **대상:** OpenAI **Chat Completions**(`POST {baseUrl}/chat/completions`)와 모든 호환 프로바이더 @@ -120,7 +127,7 @@ Ollama 공급자에 `adapter: "ollama-native"`로 설정할 수도 있습니다. 어댑터는 reasoning effort를 budget으로 매핑하고(minimal 1024 … max 32000), 출력 여유를 둔 안전한 `max_tokens`를 계산합니다. thinking이 켜지면 Anthropic에서 금지한 **`temperature`/`top_p`를 제거**합니다. -- **적응형 thinking 표시:** 적응형 thinking 모델(Opus 4.7+, Sonnet 5, Fable)에는 `thinking.display: "summarized"`를 보내므로, 긴 사고가 몇 분 동안의 heartbeat 대신 reasoning delta로 Chat과 Responses 클라이언트에 전달됩니다. reasoning 요약을 숨기는 요청(`reasoning.summary: "none"`)은 공급자 기본값을 그대로 씁니다. +- **적응형 thinking 표시:** 적응형 thinking 모델(Opus 4.7+, Sonnet 5, Fable)에는 `thinking.display: "summarized"`를 보내므로, 긴 사고가 몇 분 동안의 heartbeat 대신 reasoning delta로 Chat과 Responses 클라이언트에 전달됩니다. reasoning 요약을 숨기는 요청(`reasoning.summary: "none"`)은 공급자 기본값을 그대로 씁니다. 단, `api.anthropic.com`의 Opus 5.5는 `display: "updates"`가 기본이며, `reasoning.summary`를 `"concise"` 또는 `"detailed"`로 명시하면 updates 베타 없이 `"summarized"`를 사용합니다. [Opus 5.5 진행 업데이트](/guides/providers/#claude-opus-55-progress-updates)를 참고하세요. - 항상 `anthropic-version: 2023-06-01`을 보냅니다. `content_block_delta`(`text_delta`, `thinking_delta`, `input_json_delta`)를 스트리밍합니다. @@ -131,6 +138,17 @@ Ollama 공급자에 `adapter: "ollama-native"`로 설정할 수도 있습니다. 사용합니다. **인증:** `googleMode`에 따라 API 키, Vertex ADC, Google Antigravity OAuth 중 하나를 선택합니다. +대시보드의 Google Vertex AI 프리셋에서 프로젝트 ID와 리전을 선택적으로 입력할 수 있습니다. +API 키를 비우고 `GOOGLE_CLOUD_API_KEY`가 설정되지 않았다면 **프록시 호스트**의 ADC를 +사용합니다. ADC에는 프로젝트와 리전이 필요하며, 폼 또는 프록시 호스트의 +`GOOGLE_CLOUD_PROJECT` / `GCLOUD_PROJECT` 및 `GOOGLE_CLOUD_LOCATION`으로 설정합니다. +provider를 추가했다고 자격증명이나 권한의 유효성이 검증되는 것은 아닙니다. API 키에 +프로젝트를 지정하지 않으면 Vertex express 모드를 사용합니다. +대시보드 프리셋은 설정한 기본 모델로 시작하는 정적 목록을 사용하며, 연결 테스트는 Vertex +자격증명이나 권한을 검증하지 않습니다. +기존 Vertex 항목에서 `liveModels`를 생략하면 일반 검색 엔드포인트를 통한 기존 실시간 검색이 유지됩니다. +`liveModels: false`는 정적 목록을 사용하며 설정 화면에서 두 모드를 전환할 수 있습니다. + - 시스템 프롬프트 → `systemInstruction`; 메시지 → `contents[]`(assistant → `model`); 툴 → `functionDeclarations`. data URL 이미지 → `inline_data`. - Gemini가 tool-call id를 생략하면 합성합니다. Vertex와 Antigravity에서는 불투명한 @@ -147,6 +165,8 @@ Ollama 공급자에 `adapter: "ollama-native"`로 설정할 수도 있습니다. block을 보냅니다. - `application/vnd.amazon.eventstream`을 디코딩해 text/thinking/tool 이벤트를 복원하고, 잘린 툴 JSON을 감지합니다. 업스트림이 토큰 수를 반환하지 않아 사용량은 추정합니다. + 디코더는 종료 시 전송 계층 정리 완료를 기다리지 않고 취소를 시작하므로, 정리 작업이 + 멈춰도 읽기를 중단한 소비자가 디코더 종료를 계속 기다리지 않습니다. - `fetchResponse`에서 제한된 횟수만 재시도하고 오류를 분류/마스킹합니다. 비스트리밍 파서는 웹 검색 루프를 위해 같은 이벤트 스트림을 끝까지 소비합니다. ### 완료와 네이티브 stop reason diff --git a/docs-site/src/content/docs/ko/reference/architecture.md b/docs-site/src/content/docs/ko/reference/architecture.md index 59dc83a038..17941510af 100644 --- a/docs-site/src/content/docs/ko/reference/architecture.md +++ b/docs-site/src/content/docs/ko/reference/architecture.md @@ -75,6 +75,8 @@ HTTP 경계는 `server/index/serve-options.ts`가 맡고, Responses 데이터 없습니다. reasoning을 보존하는 모델과 다른 어댑터는 이전 thinking을 실제로 보내므로 계속 계산에 넣습니다. +문자 기반 토큰 추정은 기본 평면의 중국어·한국어뿐 아니라 𠀀 같은 보조 평면의 한자에도 기존 CJK 가중치를 적용합니다. 보조 평면 한자의 서로게이트 쌍은 이 묶음에 UTF-16 코드 유닛 두 개로 계산합니다. 여전히 근사치이며, 모델별 비율·컨텍스트 창 상한·프로바이더가 보고한 실제 사용량은 바꾸지 않습니다. + ## 파서 `responses/parser.ts`는 들어오는 요청을 `responses/schema.ts`(Zod)로 검증한 다음 diff --git a/docs-site/src/content/docs/ko/reference/cli.md b/docs-site/src/content/docs/ko/reference/cli.md index 3abe8fbd11..26c7c0ff0a 100644 --- a/docs-site/src/content/docs/ko/reference/cli.md +++ b/docs-site/src/content/docs/ko/reference/cli.md @@ -17,7 +17,9 @@ opencodex CLI는 `ocx`입니다. 첫 번째 명령 이름으로 분기하며, `s 관리 명령은 기록된 런타임 포트와 신원 검사를 사용해 살아 있는 프록시의 management API와 왕복 통신하며, 두 번째 설정 경로를 따로 두지 않습니다. 멈췄거나 닿을 수 없는 프록시는 HTTP 503으로 표시되며 CLI는 0이 아닌 종료 코드를 반환합니다. 명시적으로 오프라인 설정 작업으로 문서화된 명령은 라이브 프록시 없이 설정 파일을 검증하고 수정할 수 있습니다. -`check`는 레지스트리를 조회하거나 Codex를 실행하지 않습니다. POSIX에서는 배포 런처가 캡처한 환경 후보와 런타임 리졸버가 선택한 정규 경로가 같으면 `selectionAttested: true`가 될 수 있습니다. 연결된 npm-global 패키지 매니페스트가 소유권을 증명하고, 후보 버전이 보고된 경우 그 버전이 매니페스트 버전과 일치하면 `managed: true`가 될 수 있으며 저장된 후보는 인증되지 않습니다. Windows는 후보나 설정 파일을 읽지 않고 검사를 연기합니다. 직접 Bun/소스 실행은 런처 증거가 없어 후보를 신뢰하지 않습니다. `plan`은 격리된 임시 npm 설정·캐시·로그로 공식 레지스트리를 조회하고 활성 세션이나 불완전한 프로세스 관측을 거절합니다. 설치하거나 프로세스에 신호를 보내지 않습니다. [명령과 거절 사유의 전체 설명(영문)](/reference/cli/agents/#read-only-codex-cli-update-plan)을 참고하세요. +`check`는 레지스트리를 조회하거나 Codex를 실행하지 않습니다. POSIX에서는 배포 런처가 캡처한 환경 후보와 런타임 리졸버가 선택한 정규 경로가 같으면 `selectionAttested: true`가 될 수 있습니다. 연결된 npm-global 패키지 매니페스트가 소유권을 증명하고, 후보 버전이 보고된 경우 그 버전이 매니페스트 버전과 일치하면 `managed: true`가 될 수 있으며 저장된 후보는 인증되지 않습니다. Windows x64는 증명에 바인딩된 절대 표준 npm `codex.cmd`와 보유 핸들로 바인딩된 Node/npm 도구체인(있으면 프리픽스 로컬, 없다고 확인되면 런처 아키텍처에 고정된 캡처된 PATH 쌍), 검증된 인프리픽스 플랫폼 백킹도 지원하며 reparse를 거부하는 보유 핸들을 사용합니다. 다른 Windows 레이아웃은 계속 연기되거나 관리되지 않습니다. Windows의 `managed` 결과는 관측된 설치 레이아웃만 분류하며, 바인딩된 Node/npm은 업데이터의 읽기 전용 메타데이터 도구체인일 뿐 이후 `codex.cmd` 호출이 어떤 인터프리터를 해석할지를 보증하지 않습니다. 검증된 ACL 경로와 관찰 한도 안의 공유 prefix에서는 명시적 apply를 허용하고, 무관한 패키지·shim의 바이트와 신원 보존을 확인하며, prefix 관찰 한도는 4,096항목·총 512 MiB·파일당 384 MiB입니다. 지원하지 않는 경로와 ARM64는 거절합니다. 직접 Bun/소스 실행은 런처 증거가 없어 후보를 신뢰하지 않습니다. `plan`은 격리된 임시 npm 설정·캐시·로그로 공식 레지스트리를 조회하고 활성 세션이나 불완전한 프로세스 관측을 거절합니다. 설치하거나 프로세스에 신호를 보내지 않습니다. 적용 조건을 충족하지 않는 Windows 설치는 `applicable: false`와 `refusal: windows_apply_disabled`를 가진 결정적 읽기 전용 plan을 생성하며, PATH 전용 선택·OpenCodex 자동 시작 래퍼·global/vendor 폴백은 계속 연기됩니다. [명령과 거절 사유의 전체 설명(영문)](/reference/cli/agents/#read-only-codex-cli-update-plan)을 참고하세요. + +Windows plan은 npm 패키지 전체와 모듈 조회 경로의 쓰기 권한도 검증합니다. 선택된 Node는 동기 모듈 훅을 지원해야 하며, npm은 검증된 트리 밖의 의존성을 실행할 수 없습니다. Apply는 설치 프로세스 종료와 readback까지 선택 변경과 소유 세션 시작을 busy로 거절하고, 자식 수명이 불명확하면 이 배제를 유지합니다. Windows x64 설치 관측은 [`attest` 명령](/ko/reference/cli/agents/)을 참조하세요. 명시적 경로 없이 증명에 바인딩된 런처 스냅샷이 식별한 선택 후보를 관측하며, 업데이트 권한이나 런타임 선택을 증명하지 않습니다. diff --git a/docs-site/src/content/docs/ko/reference/cli/agents.md b/docs-site/src/content/docs/ko/reference/cli/agents.md index c8bb7e5373..102cff039a 100644 --- a/docs-site/src/content/docs/ko/reference/cli/agents.md +++ b/docs-site/src/content/docs/ko/reference/cli/agents.md @@ -162,6 +162,41 @@ ocx claude desktop import [--apply] Validate and import JSON family는 `opus`, `fable`, `sonnet`, `haiku`이며, 새 route는 `opus`에서 시작합니다. `none`은 해당 family가 비어 있을 때만 유효합니다. 레거시 apply 플래그인 `--static`, `--hybrid`, `--discovery-only`도 계속 지원합니다. Claude Code 설정은 `ocx claude config ...`를 사용하십시오. +### `ocx codex [codex args...]` + +키는 설정과 해당 경로가 다른 보안 주체의 변경으로부터 보호될 때만 전달합니다. 현재 사용자와 권한 있는 OS 주체는 신뢰합니다. 같은 사용자로 실행되는 프로세스는 신뢰 대상입니다. 사용자의 쓰기 권한을 가진 행위자는 사용자의 OpenCodex 키 파일도 이미 읽을 수 있습니다. 검증과 네이티브 시작 사이에 같은 사용자가 설정을 교체하는 시나리오는 이 위협 모델의 범위 밖이며, 런처는 인계 시 설정을 고정하지 않습니다. + +일반적인 Windows 설치의 기본 ProgramData 권한은 다른 사용자에게 디렉터리 생성 권한을 줍니다. 따라서 `ProgramData\OpenAI\Codex`가 없어도 자동 자격 증명을 보류합니다. ProgramData 아래의 시스템 Codex 설정 폴더는 존재해야 하고 Administrators/SYSTEM만 쓸 수 있어야 하며, 다른 사용자가 상위 디렉터리를 교체할 수 없어야 합니다. 관리자에게 디렉터리 정책 검토를 요청하세요. opencodex는 직접 ACL을 변경하지 않으며 프로비저닝 명령을 제공하지 않습니다. + +대신 사용자가 직접 키를 제공할 수 있습니다. 예를 들어 `OPENCODEX_API_AUTH_TOKEN` 환경 변수를 내보내면 `ocx codex`는 그 값을 그대로 유지합니다. 기존 시스템 설정 파일은 여전히 자동 자격 증명을 보류하며 별도 검토가 필요합니다. 각 보류 사유는 키 값, 키 파일 내용이나 경로 없이 짧고 구체적인 stderr 진단 한 줄로 표시됩니다. + +한 단어 프롬프트 앞에는 `--`를 넣어 알 수 없는 Codex 하위 명령 선택을 막으세요. + +설정 파일이 없어도 machine 설정 경로에 다른 사용자가 파일을 만들 수 없어야 합니다. Windows ProgramData/OpenAI/Codex 경로의 보호를 증명할 수 없으면 자동 토큰을 보류하며 디렉터리를 만들지 않습니다. macOS는 거부 전용 ACL과 읽기 전용 허용 항목을 수락합니다. 쓰기·추가·삭제·속성·보안·소유자 변경을 허용하는 항목은 앞에 거부 항목이 있어도 거부합니다. 알 수 없는 태그나 검사 오류도 거부합니다. + +새 서비스 토큰은 argv가 아래 허용 목록 안에 있고, 비어 있지 않은 HTTP(S)/ALL proxy 및 `CODEX_*`/`OPENAI_*`/`AZURE_OPENAI_*` 환경 재정의가 없으며(정규 `CODEX_HOME`은 허용), 홈·설정·시스템 경로가 소유권 검사를 통과할 때만 읽습니다. 설정에는 검증된 키와 정확한 관리 loopback provider만 있어야 하며 추가 자격 증명 소비자나 설정층이 없어야 합니다. `-c`/`--config`, `-p`/`--profile`, 알 수 없는 플래그, `resume`/`fork` 등 허용 목록 밖의 인자는 토큰을 보류하고 값 없는 진단을 출력합니다. 명시적인 사용자 자격 증명과 원래 인자는 유지합니다. + +정규 홈 디렉터리와 `config.toml`은 현재 사용자 소유여야 합니다. POSIX에서는 group/other 쓰기를, Windows에서는 현재 사용자·SYSTEM·Administrators 이외의 DACL 쓰기 권한을 거부하고 소유자 SID를 확인합니다. 상위 경로 교체 권한도 확인합니다. macOS에서는 강제 Codex 설정 preference가 없어야 합니다. 같은 사용자나 관리자의 악성 프로세스로부터 격리하는 기능은 아닙니다. + +| Allowlist | Flags | +| --- | --- | +| Switches | `--no-daemon`, `--json`, `--ephemeral`, `--skip-git-repo-check`, `--no-alt-screen`, `--full-auto`, `--dangerously-bypass-approvals-and-sandbox`, `--search` | +| One value | `--model`/`-m`, `--sandbox`/`-s`, `--ask-for-approval`/`-a`, `--image`/`-i` | + + + +자동 자격 증명 전달은 `CODEX_HOME`의 `~`와 공백을 리터럴 경로로 해석하고 검증한 뒤, 동일한 정규 절대 경로를 자식에게 전달합니다. 홈을 읽을 수 없으면 토큰을 읽지 않습니다. 대소문자와 관계없이 `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` 중 비어 있지 않은 값이 있으면 `NO_PROXY`와 무관하게 자동 로딩을 건너뜁니다. 거부된 실행과 사용자가 내보낸 자격 증명은 변경하지 않습니다. 새 토큰을 전달할 때 자식의 `NO_PROXY`와 `no_proxy`에 기존 우회 항목을 보존하면서 `127.0.0.1`과 `::1`을 추가합니다. `features.respect_system_proxy`를 켜거나 `--enable`/`--disable`을 전달하면 자동 로딩을 건너뜁니다. + +원래 인자로 Codex를 실행하기 전에 프록시 시작을 시도합니다. 라우팅은 Codex 설정이 소유하며 런처가 재작성하지 않습니다. 네이티브 및 다른 게이트웨이 경로에서는 시작을 생략합니다. 알 수 없는 라우팅은 경고 후 시작을 시도하며, 시작 실패 시에도 경고 후 실행합니다. 도움말·버전 및 `login`, `doctor`, `help` 같은 내부 명령은 시작과 자동 토큰 읽기를 생략합니다. + +선택한 provider의 전체 전송 설정이 이 설치의 로컬 리스너 또는 저장된 로컬 클라이언트 연결에 대해 생성한 관리 블록과 일치할 때만, 누락된 `OPENCODEX_API_AUTH_TOKEN`을 이 설치의 `service-api-token`에서 읽습니다. 이름이나 주입 주석만으로는 허용하지 않습니다. 알 수 없거나 원격인 목적지, 기본 profile, 프로젝트 설정, `OPENAI_BASE_URL`, 전달된 `-c`/`--config`, `-p`/`--profile`, `-C`/`--cd`, `--remote`는 자동 읽기를 생략합니다. 사용자가 export한 자격 증명과 인자는 보존하며, 토큰 파일 경로 재정의와 관리 토큰 충돌은 거부합니다. + +일치가 확인된(`matched`) autostart wrapper만 backing Codex를 직접 실행합니다. 검사 예외를 포함한 알 수 없는 상태는 검증된 bypass가 필요하며, 관리되는 Windows CMD wrapper는 현재 생성 템플릿 전체와 일치해야 `OCX_SHIM_BYPASS=1`로 실행합니다. 일반 npm 런처는 지원합니다. 검증할 수 없거나 오래된 wrapper는 종료 코드 1로 거부하며 Codex를 시작하지 않습니다. `ocx codex-shim install`로 갱신하세요. 이 실행은 shim을 수리하지 않으며, 내용 검사는 Windows backing 파일 출처나 동시 경로 교체를 보장하지 않습니다. + +macOS에서는 도움말과 버전을 포함한 매 실행 시, 선택한 실행 파일의 경로나 정규 경로가 `.app` 번들 내부에 있으면 검증합니다. 이름을 바꾼 번들과 번들 내부를 가리키는 심볼릭 링크도 번들 및 실행 파일의 안전한 소유권, 권한, OpenAI 서명을 요구합니다. 선택한 번들 구성원은 실행 파일, 중간 디렉터리 또는 번들 전체의 심볼릭 링크를 거쳐도 해당 번들의 정규 `Contents/` 내부에 있어야 합니다. 검증 실패 시 Codex를 시작하지 않고 종료 코드 1을 반환합니다. npm 설치를 포함한 일반 번들 외부 실행 파일의 동작은 유지됩니다. + +런처 도움말은 `ocx help codex`, Codex 도움말은 `ocx codex --help`입니다. 이후 plain `codex`의 동작은 기존과 같습니다. + ### `ocx opencode [opencode args...]` 프록시가 실행 중인지 확인한 뒤, OpenCode의 인라인 런타임 계층(`OPENCODE_CONFIG_CONTENT`)에 생성된 `provider.opencodex` 및 `providers.opencodex` 블록을 넣어 opencode를 실행합니다. 기존 인라인 config는 유지되고, 이번 실행에서는 이 두 키만 교체됩니다. 전역 또는 프로젝트 `opencode.json` 파일은 기존 override가 있는지 경고하기 위해 읽을 수 있지만, 디스크상의 파일은 절대 수정하지 않습니다. 라우팅된 model은 `opencodex//`로 나타납니다. 이후 plain `opencode`를 실행하면 이전과 정확히 같은 방식으로 동작합니다. @@ -256,7 +291,7 @@ ocx system settings --stream-mode eager-relay ocx system codex-cli-update check --json ``` -`check`는 레지스트리를 조회하거나 Codex를 실행하지 않습니다. POSIX에서는 배포 런처가 캡처한 환경 후보와 런타임 리졸버가 선택한 정규 경로가 같으면 `selectionAttested: true`가 될 수 있습니다. 연결된 npm-global 패키지 매니페스트가 소유권을 증명하고, 후보 버전이 보고된 경우 그 버전이 매니페스트 버전과 일치하면 `managed: true`가 될 수 있으며 저장된 후보는 인증되지 않습니다. Windows는 후보나 설정 파일을 읽지 않고 검사를 연기합니다. 직접 Bun/소스 실행은 런처 증거가 없어 후보를 신뢰하지 않습니다. `plan`은 격리된 임시 npm 설정·캐시·로그로 공식 레지스트리를 조회하고 활성 세션이나 불완전한 프로세스 관측을 거절합니다. 설치하거나 프로세스에 신호를 보내지 않습니다. [명령과 거절 사유의 전체 설명(영문)](/reference/cli/agents/#read-only-codex-cli-update-plan)을 참고하세요. +`check`는 레지스트리를 조회하거나 Codex를 실행하지 않습니다. POSIX에서는 배포 런처가 캡처한 환경 후보와 런타임 리졸버가 선택한 정규 경로가 같으면 `selectionAttested: true`가 될 수 있습니다. 연결된 npm-global 패키지 매니페스트가 소유권을 증명하고, 후보 버전이 보고된 경우 그 버전이 매니페스트 버전과 일치하면 `managed: true`가 될 수 있으며 저장된 후보는 인증되지 않습니다. Windows x64는 증명에 바인딩된 절대 표준 npm `codex.cmd`와 보유 핸들로 바인딩된 Node/npm 도구체인(있으면 프리픽스 로컬, 없다고 확인되면 런처 아키텍처에 고정된 캡처된 PATH 쌍), 검증된 인프리픽스 플랫폼 백킹도 지원하며 reparse를 거부하는 보유 핸들을 사용합니다. 다른 Windows 레이아웃은 계속 연기되거나 관리되지 않습니다. Windows의 `managed` 결과는 관측된 설치 레이아웃만 분류하며, 바인딩된 Node/npm은 업데이터의 읽기 전용 메타데이터 도구체인일 뿐 이후 `codex.cmd` 호출이 어떤 인터프리터를 해석할지를 보증하지 않습니다. 직접 Bun/소스 실행은 런처 증거가 없어 후보를 신뢰하지 않습니다. `plan`은 격리된 임시 npm 설정·캐시·로그로 공식 레지스트리를 조회하고 활성 세션이나 불완전한 프로세스 관측을 거절합니다. 설치하거나 프로세스에 신호를 보내지 않습니다. Windows x64 apply는 검증된 개인 쓰기 권한을 가진 제한된 npm prefix를 요구하고 무관한 패키지·shim을 보존하며, 적용 조건을 충족하지 않는 관측 레이아웃은 `applicable: false`와 `refusal: windows_apply_disabled`를 가진 결정적 읽기 전용 plan을 생성합니다. PATH 전용 선택·OpenCodex 자동 시작 래퍼·global/vendor 폴백은 계속 연기됩니다. [명령과 거절 사유의 전체 설명(영문)](/reference/cli/agents/#read-only-codex-cli-update-plan)을 참고하세요. Windows에서 `CODEX_CLI_PATH=codex` 같은 단순 명령 이름이나 원격 경로·장치 경로가 후보로 캡처되면 `candidate_path_unavailable`을 보고합니다. 후보는 캡처됐지만 해당 경로가 이 검사 대상에 적합하지 않은 경우입니다. @@ -306,3 +341,19 @@ This takes effect on the **next routed `ocx claude` launch**, injecting `CLAUDE_ Claude Code **2.1.257 or newer** is required for FORCE. Plugin and built-in agents (including Explore/Plan) and per-call model arguments are overridden. Forks and subagent skills with `model: inherit` keep the main conversation model. The main loop and Haiku/small-fast sidecars are unaffected. Existing roster files remain available. The dashboard warns about old or unknown CLI versions, unavailable targets, and either variable already present in `settings.json` → `env` (which overrides launch env). Detection is read-only and server-local: it cannot inspect another launch shell, another machine, or project-local settings. An unknown result is not proof of force support. + +## Hermes / Command Code: model names + +Hermes and Command Code support `--model-names alias|routed` (API: `modelNames`). +The default is `routed`, independent of `preferModelAliasIds`. A connection +stores its mode; later Apply without the option preserves it. Alias mode uses +only provider-qualified aliases that the router proves equivalent; missing, +unsafe or colliding aliases fall back to routed keys. Combos keep their keys. +Removed/renamed aliases migrate on the next successful managed refresh, with +foreign-edit refusal. Named Hermes profiles need explicit Apply. + +`ocx export --client hermes --model-names alias --json` previews a current +already loaded catalog without writing client files or managed state; a cold or +stale catalog returns unavailable. Explicit `--out` writes an export artifact. +See the [English integration guide](/guides/integrations/#opt-in-alias-model-names) +for the canonical workflow. diff --git a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md index 5c353e5bd8..9c29a2e8d4 100644 --- a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md @@ -44,9 +44,11 @@ ocx start --socks5-off ### `ocx stop` -실행 중인 프록시를 PID 기준으로 중지하고, PID 파일을 삭제한 뒤 기본 Codex를 복원합니다. 관리형 +감독 프로세스 없이 실행되는 Link Child는 종료 신호 처리 시 각 쓰기 직전에 연결을 재확인하고 리스너를 닫기 전에 Codex 기본 설정과 관리 Grok 설정을 복원합니다. 서비스·Desktop 감독, sibling, 재시작·재활용 인계, 부모 stop 영수증이 있으면 설정을 보존합니다. 종료 중 재시작 요청은 `409 runtime_stopping`입니다. 강제 종료는 신호 처리를 건너뛸 수 있어 부모 `ocx stop`의 복원도 필요합니다. + +실행 중인 프록시를 PID 기준으로 중지하고 PID 파일을 삭제합니다. 독립 실행 소유자라면 기본 Codex를 복원합니다. 관리형 백그라운드 서비스가 설치되어 있으면 `ocx stop`이 먼저 그 서비스를 중지하므로 프록시가 다시 -올라올 수 없습니다. 웹 대시보드의 **Stop** 버튼도 같은 동작(`POST /api/stop`)을 하지만, Windows 작업 스케줄러는 예외입니다. 작업이 끝나도 래퍼가 프록시를 다시 띄울 수 있어서, 대시보드는 `respawnable_service`로 거절하고 아무것도 바꾸지 않은 채 `ocx stop` 실행을 안내합니다. +올라올 수 없습니다. 웹 대시보드 사이드바의 프록시 레버를 끝까지 당기는 정지도 같은 동작(`POST /api/stop`)을 하지만, Windows 작업 스케줄러는 예외입니다. 작업이 끝나도 래퍼가 프록시를 다시 띄울 수 있어서, 대시보드는 `respawnable_service`로 거절하고 아무것도 바꾸지 않은 채 `ocx stop` 실행을 안내합니다. 프록시가 종료된 것만으로 Codex/Grok 공유 설정 복원까지 성공했다고 판단하지 않습니다. 종료 응답이 실패를 보고하거나, 읽을 수 없거나, 요청한 복원 처리 방식을 확인해 주지 않으면 기존 소유권·재시작 @@ -54,6 +56,16 @@ ocx start --socks5-off 넘어가지 않습니다. 영수증에 근거한 지연 복원도 최종 복원과 영수증 정리를 부모가 담당하며, 부모의 공유 설정 복원이 실패하면 종료 실패로 남기고 미완료 영수증을 보존합니다. +연결된 hub 클라이언트에서는 성공한 API 종료를 포함해 `ocx stop`이 연결 소유의 Codex 라우팅, 모델 카탈로그와 Grok 설정을 보존합니다. `ocx start`는 라우팅을 다시 주입하지 않고 보존한 설정으로 서비스를 재개합니다. Codex를 자체 계정으로 돌리려면 `ocx disconnect`를, 이미 기본 라우팅으로 복원했다면 다시 연결하려고 `ocx sync --restart-codex`를 실행하세요. + +Remote Link Child를 명시적으로 중지하면 공유 설정 복원에 성공한 경우 기본 Codex 라우팅, 카탈로그와 백업된 재개 이력 메타데이터를 복원하고 관리형 Grok 설정을 제거합니다. 저장된 Home 연결은 유지하며 `ocx disconnect`로 제거할 수 있습니다. Codex에서 Home을 다시 쓰려면 `ocx start`(서비스가 설치되어 있으면 `ocx service start`) 후 `ocx sync --restart-codex`를 실행하세요. 시작만으로 라우팅을 다시 적용하지 않으며, sync는 Grok 블록을 다시 만들지 않습니다. + +서비스 중지 전에 연결 소유권을 확인할 수 없으면 종료 API는 HTTP 409와 `sharedTeardown: "refused"`를 반환하고 프록시와 서비스 관리자를 실행 상태로 둡니다. 진행 중인 연결 또는 연결 해제가 끝난 뒤 다시 시도하세요. + +연결된 클라이언트를 중지할 때는 보호된 로컬 런타임 기록과 리스너의 신원 증명을 대조합니다. 클라이언트 리스너와 일반 프록시 모두 이 검증이 필요하며, 일반 프록시는 인증된 조회로 설정 보존 기능도 확인합니다. 오래되었거나 검증할 수 없는 런타임은 서비스나 프로세스를 중지하기 전에 거절합니다. 런타임을 관리하는 앱이나 서비스에서 업데이트·재시작한 뒤 다시 시도하세요. + +이미 중지된 클라이언트는 서비스 관리자가 비활성이고 알려진 로컬 주소에 런타임이 없음을 확인한 뒤 정상적인 미실행 결과를 반환합니다. + ### `ocx restart` 프록시가 실행 중이면 확인된 정확한 PID와 포트에 in-place 재시작을 요청하고, 정상 드레인을 @@ -115,6 +127,16 @@ dedicated-provider history도 포함됩니다. 상태를 백업하고 이 전체 별칭입니다. 설정 정리에는 새 설치로 만들어진 소유권 메타데이터가 필요하며, 오래된 디렉터리나 공유 디렉터리는 그대로 남깁니다. +`ocx uninstall`을 root 권한이나 관리자 권한으로 상승된 Windows 프롬프트에서 실행하면, 먼저 다른 계정이 +설정 디렉터리, 그 상위 디렉터리, 그 안의 어떤 디렉터리도 변경할 수 없는지, 그리고 설정 디렉터리 안의 링크가 그 밖을 +가리키지 않는지(Windows에서는 링크가 전혀 없는지) 확인합니다. 어느 하나라도 맞지 않으면 아무것도 바꾸기 전에 중단하고 이유를 알려 줍니다. 설정 디렉터리를 +소유한 계정으로 `sudo`나 관리자 권한 없이 `ocx uninstall`을 실행하거나, 해당 디렉터리를 그 계정만 쓸 수 있도록 +제한하고 그런 링크를 제거한 뒤 다시 실행하십시오. 권한 상승 여부를 확인할 수 없는 Windows ARM64에서도 같은 확인을 +적용하며, 확인을 마칠 수 없으면 opencodex를 중지한 뒤 설정 디렉터리를 직접 제거하십시오. + +설정 디렉터리 안에서 상위 디렉터리가 링크(심볼릭 링크 또는 정션)인 기록된 항목은 그대로 두고 남은 경로로 표시하며, +실행은 부분 제거로 끝납니다. 그 링크를 실제 디렉터리로 바꾸거나 제거한 뒤 `ocx uninstall`을 다시 실행하면 마무리됩니다. + ## 상태 및 헬스 ### `ocx status [--json]` @@ -209,7 +231,7 @@ ocx status --json 인증이 필요 없는 `GET /readyz` 엔드포인트로 동기화 후 준비 상태를 확인합니다. 준비되면 `200`, `pending` 또는 종단 상태인 `failed`이면 `Retry-After: 1`과 함께 `503`을 반환합니다. HTTP의 정제된 -식별 필드는 `{service, version, uptime, pid, port, status, protocol, minimumClientProtocol, managementUrl}`입니다. `protocol`은 허브의 현재 원격 프로토콜, `minimumClientProtocol`은 호환되는 최소 클라이언트 프로토콜, `managementUrl`은 브라우저에서 보이는 표준 관리 origin입니다. `/readyz`가 없는 이전 프록시는 +식별 필드는 `{service, version, uptime, pid, port, status, protocol, minimumClientProtocol, managementUrl, features}`입니다. `protocol`은 허브의 현재 원격 프로토콜, `minimumClientProtocol`은 호환되는 최소 클라이언트 프로토콜, `managementUrl`은 브라우저에서 보이는 표준 관리 origin입니다. `/readyz`가 없는 이전 프록시는 `unreachable`로 fail-closed하며, `/healthz`는 준비 상태가 아닌 별도의 liveness 확인입니다. 기본값은 한 번의 probe이며, `--wait`는 준비 또는 timeout까지 polling하지만 종단 `failed`를 확인하면 즉시 종료합니다. 기본 timeout은 45초이며, `--timeout `는 `--wait`와 함께 써야 하고 양의 정수인 1~300초 범위를 받습니다. CLI JSON은 @@ -236,7 +258,13 @@ single-flight/lock 파일을 만들 수 있는지, 건강하지 않은 OAuth 또 ## 카탈로그 동기화 -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +Remote Link Home에서는 최신 카탈로그가 성공적으로 커밋된 뒤 `ocx sync`가 조건을 충족하는 연결된 Child에도 동기화를 전파합니다. `--local-only`는 이 전파를 끕니다. `--json`은 Home 결과와 각 Child의 상태를 담은 단일 `ocx.sync.fanout/1` 문서를 출력하며, 건너뛴 연결된 Child에는 이유와 조치 방법(`hint`)을 표시합니다. Home 자체의 종료 코드가 0이 아니면 그 코드를 그대로 반환합니다. Home이 성공한 경우 연결된 Child의 동기화를 건너뛰거나 Child 실패, 시간 초과 또는 링크 저장소를 읽을 수 없는 경우 종료 코드 6을 반환합니다. 클라이언트 주도 링크와 `--local-only` 등 의도적으로 건너뛰는 경우는 기존 종료 동작을 유지합니다. 링크 저장소를 읽을 수 없으면 텍스트 모드에서 경로가 없는 오류를 출력합니다. 코드 7은 업데이트 진행 중을 위해 예약되어 있습니다. JSON 모드에서 Home 동기화가 예외를 던져도 stdout에는 결과 문서 하나만 출력하고 stderr에는 안전하게 변환된 진단을 출력합니다. + +전파는 Child의 Codex 앱이나 app-server 재시작을 요청하지 않습니다. 재시작이 필요하면 GOAT를 사용하거나, 전체 `ocx` Child에서는 `ocx sync --restart-codex`를 실행하고 경량 `ocx-child` 호스트에서는 Codex 데스크톱 앱과 `app-server`를 별도로 재시작하세요. 다만 Child의 고정 대상 동기화는 변경된 Home 설정을 적용한 뒤 자체 OpenCodex 클라이언트 런타임을 재시작할 수 있습니다. Home이 시간 초과로 로컬 SSH 프로세스를 중지하더라도 이미 시작된 원격 동기화는 Child에서 계속될 수 있습니다. + +> **Remote Link Child:** 전체 `ocx` Child에서는 `ocx sync`가 Home의 Codex 설정도 적용하며, 클라이언트 런타임이 그 적용보다 먼저 시작되었으면 재시작 플래그 없이도 재시작하고 실패하더라도 이전 런타임이 계속 서비스한 채 0이 아닌 코드로 끝납니다. 경량 `ocx-child` 호스트에서는 `ocx-child sync`가 릴레이가 없을 때 `ocx-child serve`를 시작하고 `runtimeStartedAt < lastApplyAt`이면 교체하며 `stale`이 아닌 동기화에서 최선을 다해 parity를 보고합니다(교체 실패 시 이전 릴레이가 멈춘 상태로 0이 아닌 코드로 끝나며, Codex 데스크톱 앱과 장기 실행 `app-server` 프로세스는 별도로 재시작해야 합니다). Child의 `ocx status --json`(또는 `ocx-child status --json`)과 Home의 `ocx link status --json` 필드는 [Remote Link apply parity](/reference/cli/lifecycle/#remote-link-apply-parity)(영문)를 참고하세요. Home에서는 `ocx link check (--link-id | --all)`가 SSH로 `ocx update --plan`을 실행해(Child마다 60초, 설치는 바꾸지 않음) Home이 추가한 각 Child의 설치 버전과 업데이트 경로를 읽고, `ocx link status --json`은 각 행에 `child` 블록을 추가합니다. 자세한 내용은 [Child install, catalog and activity](/guides/remote-link/#child-install-catalog-and-activity)(영문)를 참고하세요. 재시작 플래그를 명시하면 카탈로그와 캐시 바이트가 같아도 `config.toml` 변경이 성공적으로 커밋된 뒤 재시작합니다. 설정만 다루는 작업이 변경 없음, 거부, 사전 검증 또는 롤백으로 끝나면 재시작하지 않습니다. 재시작 플래그가 없으면 sync는 Codex를 자동으로 재시작하지 않습니다. @@ -262,6 +290,8 @@ app-server / code-mode-host 프로세스에만 `SIGTERM`을 보내고 데스크 명령을 Codex 앱 안에서 실행하면 재시작은 분리된 helper에 넘기고, 이 세션은 앱과 함께 종료됩니다. +**대상을 고정한 동기화.** `ocx sync --expect-link `(Remote Link Child)와 `ocx sync --expect-hub-key `(hub 클라이언트)는 이 머신이 여전히 그 링크나 그 키로 연결되어 있을 때만 동기화합니다. 그렇지 않으면 아무것도 바꾸지 않고 로컬 공급자도 동기화하지 않으며, 종료 코드 5로 끝나고 stderr 마지막 줄에 `{"phase":"child_link_mismatch"|"hub_client_mismatch","reason":...}`를 출력합니다. 형식이 잘못되었거나 반복된 플래그는 종료 코드 2로 끝납니다. 자세한 내용은 [영어 레퍼런스](/reference/cli/lifecycle/#sync-only-from-the-expected-home---expect-link-and---expect-hub-key)를 참고하세요. + ### `ocx sync-cache [--restart-codex] [--restart-app-server-only]` Codex의 로컬 모델 선택기 캐시를 무효화하여, 활성 opencodex 카탈로그에서 다시 빌드되게 합니다. @@ -433,7 +463,7 @@ Windows 상태 트레이 아이콘을 설치하고 제어합니다. Windows 로 ### `ocx gui` 프록시가 실행 중이 아니면 자동으로 시작하면서 [웹 대시보드](/guides/web-dashboard/)를 -`http://localhost:`에서 엽니다. 허브에서 관리 리스너를 켜 두면 `http://127.0.0.1:<관리 포트>`에서 엽니다. +`http://127.0.0.1:`에서 엽니다. 허브에서 관리 리스너를 켜 두면 `http://127.0.0.1:<관리 포트>`에서 엽니다. ## 업데이트 diff --git a/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md b/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md index a60a7f2168..baed5fbfe5 100644 --- a/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md @@ -24,6 +24,7 @@ description: 제공자 설정, 자격 증명, 할당량, 모델 카탈로그 명 | `quota` | `--refresh`, `--json` | 제공자 할당량 보고서를 읽습니다. | | `presets` | `--json` | 대시보드 제공자 프리셋을 나열합니다. | | `account-mode` | `pool`, `direct`, `--json` | Codex 계정 라우팅을 풀 기반으로 할지 직접 연결로 할지 선택합니다. | +| `import-cc-switch` | `--source `, `--provider `, `--apply`, `--restore`, `--allow-private-network`, `--json` | CC-Switch SQLite(`cc-switch.db`) 또는 레거시 JSON 파일에서 키 없는 프로바이더 항목을 미리보기·선택 적용·복원합니다. | 기본 `add`, `remove`, `set-default`는 로컬 설정을 바꿉니다. 실행 중인 프록시를 바꾸려면 `--live`를 지정하세요. 실시간 삭제에는 `--yes`도 필요합니다. `--sync --json`도 저장 후 동기화를 실제로 시도하며, 실패하면 저장은 유지한 채 0이 아닌 코드와 `needsSync: true`를 반환합니다. `--live`와 `--sync`는 함께 쓸 수 없습니다. pacing·snapshot/apply 절차는 [영문 명령 안내](/reference/cli/providers-accounts/#snapshot-edit-and-apply-with-a-baseline)를 참고하세요. @@ -57,6 +58,27 @@ ocx models live --provider ark --json 비밀에 해당하는 값은 `--api-key`나 OAuth 로그인을 쓰세요. ::: +### 키 없는 CC-Switch 프로바이더 가져오기 + +```bash +ocx provider import-cc-switch --source ~/.cc-switch/cc-switch.db +ocx stop +ocx provider import-cc-switch --source ~/.cc-switch/cc-switch.db --provider my-provider --apply +# 다른 터미널에서 프록시를 시작(또는 ocx ensure 실행)한 뒤 키를 등록: +ocx start +printf '%s\n' "$API_KEY" | ocx account add-key my-provider + +# 별도의 롤백 경로(먼저 프록시를 중지; 수정되지 않은 키 없는 항목만 제거): +ocx stop +ocx provider import-cc-switch --restore +``` + +`ocx provider import-cc-switch`는 일반 CC-Switch SQLite 데이터베이스나 레거시 JSON 파일에서 명시적으로 허용된 비비밀 메타데이터 필드(프로바이더 ID, 앱 유형, 기본 URL, 프로토콜 어댑터, 기본 모델)의 값**만** 투영합니다. 입력을 스캔하기 위해 소스와 내장 설정 바이트를 일시적으로 읽지만, 비밀 필드·자유 텍스트 표시 이름·TOML 주석은 바이트 수준에서 건너뛰어 문자열로 디코딩하거나 기록·로깅하지 않으며 임시 바이트 버퍼는 `finally`에서 0으로 지워집니다. 좁은 기본 URL 경로 규칙(`http(s)://host[:port]`와 빈 경로 또는 `/v1`, `/api/v1`, `/compatible-mode/v1` 같은 1~4개의 소문자 `[a-z0-9._-]` API 경로 세그먼트)과 식별자/모델 구문 검사는 심층 방어로 동작하며 부적합한 값을 에코하지 않고 거부합니다. 소스 파일은 `O_NOFOLLOW | O_NONBLOCK` 디스크립터 검증과 함께 한 번만 열리고 SQLite는 임시 파일 없이 메모리에서 읽기 전용으로 역직렬화됩니다. 여러 하드 링크(`nlink > 1`)를 가진 SQLite 파일은 별칭 경로를 통한 사이드카 검사 우회를 막기 위해 거부되며, 인접한 `-wal` 또는 `-journal` 파일이 비어 있지 않으면 CC-Switch를 종료(또는 데이터베이스 체크포인트)한 뒤 다시 시도하라고 안내하며 거부합니다. 신뢰할 수 있는 로컬 CC-Switch 소스만 사용하고, 출력된 모든 ID·모델·`baseUrl`을 확인한 뒤 자격 증명을 추가하세요: + +- **미리보기(기본값):** `--source `이 필요하며 아무것도 쓰지 않고 발견·적격·충돌·무효 항목 수를 보고합니다. +- **적용(`--apply`):** `--source `과 중지된 프록시(`ocx stop`)가 필요하며 Remote Link Child에서는 거부됩니다. 선택한 항목만 가져오려면 `--provider `를 반복하고, 루프백이나 사설 네트워크 기본 URL을 허용하려면 `--allow-private-network`를 지정하세요. 사전 미리보기 없이 실행하더라도 `--apply`는 키 없는 프로바이더 항목과 롤백 저널(`$OPENCODEX_HOME/cc-switch-provider-import-journal.json`)을 기록하기 전에 가져올 모든 프로바이더 ID·기본 모델·대상 URL을 먼저 출력합니다(텍스트 모드에서는 `stdout`, `--json` 모드에서는 `stderr`). 활성 저널이 있는 동안 두 번째 `--apply`는 거부됩니다. 출력된 항목을 확인한 뒤 프록시를 시작(다른 터미널에서 `ocx start` 또는 `ocx ensure`)하고 `printf '%s\n' "$API_KEY" | ocx account add-key `(파이프 표준 입력) 또는 `ocx login `로 자격 증명을 등록하세요. +- **복원(`--restore`):** 자격 증명 추가의 연속이 아닌 별도의 롤백 경로로, 중지된 프록시(`ocx stop`)가 필요하며 Remote Link Child에서는 거부되고 `--source`·`--provider`·`--allow-private-network`는 받지 않습니다. `auth.json`을 바이트 수준에서 읽기 전용으로 검사(읽을 수 없거나 형식이 잘못되면 안전하게 보류)하며, 가져온 키 없는 상태와 여전히 일치하고 `defaultProvider`로 선택되지 않았으며 라우팅·콤보(combos)·폴백 정책(fallback policy)·OAuth 계정·API 키 어디에서도 참조되지 않은 프로바이더만 활성 저널에서 제거합니다. + ## 인증 ### `ocx login ` @@ -191,7 +213,7 @@ Luna 메타데이터임을 표시해 사용합니다. 목록에 보인다는 사 실행 중인 프록시를 통해 제공자 계정과 API 키 풀을 나열하고 전환합니다. 제공되는 도움말 표면은 다음과 같습니다: ```text -Usage: ocx account ... +Usage: ocx account ... list [provider] Codex account pool, OAuth accounts and API keys (identifiers shown masked as the API returns them). history openai [--limit <1-200>] Recent routing decisions for one Codex pool account. @@ -205,6 +227,7 @@ pause Hold an account out of automatic selection. resume Return a paused account to automatic selection. pause-exhausted Pause every account whose quota is spent. clear-cooldown Drop a cooldown the proxy set after an upstream failure. +reset-affinity [--json] Confirm all session bindings are cleared, even with no accounts; selection and pause state stay unchanged. Run on the Home; a Remote Link Child names the Home and sends no request. strategy [] Pool placement strategy; omit the value to read it. sticky [<1-100>] Requests a bound thread keeps on one account; omit the value to read it. priority [first|earlier|normal|later|last|-100..100|reset] Selection order; omit the value to read it. @@ -219,7 +242,7 @@ main Manage the Codex App logi Codex pool selection applies to the next request after clearing existing affinity; in-flight requests keep their captured account. ``` -하위 명령은 프록시가 실행 중이어야 하며 기록된 런타임 포트를 자동으로 찾습니다. 다만 `import-orca`는 예외로, 미리보기는 로컬 전용이고 `import-orca --apply`는 프록시가 멈춰 있어야 합니다. 성공한 작업은 종료 코드 0으로 끝납니다. 잘못된 사용, 알 수 없는 제공자 또는 계정/키 id, 도달할 수 없는 프록시, API 실패는 종료 코드 1로 끝납니다. 자격 증명 필드는 관리 API가 반환한 그대로 표시됩니다(마스킹도 그대로 포함됩니다). 원시 API 키와 OAuth 토큰은 절대 반환하지 않습니다. 표시 편의 기능은 대시보드와 마찬가지로 클라이언트 쪽에서 합성합니다. `main`은 `openai` 계정 풀의 Codex App 로그인에 대한 CLI 별칭이고, 이메일이 없는 OAuth 계정은 `Account N`으로 표시되며, plan/label 열은 plan, 마스킹된 이메일, label, 마스킹된 키 순으로 대체합니다. +하위 명령은 프록시가 실행 중이어야 하며 기록된 런타임 포트를 자동으로 찾습니다. 다만 `import-orca`는 예외로, 미리보기는 로컬 전용이고 `import-orca --apply`는 프록시가 멈춰 있어야 합니다. 성공한 작업은 종료 코드 0으로 끝납니다. 잘못된 사용, 알 수 없는 제공자 또는 계정/키 id, 도달할 수 없는 프록시, API 실패는 기본적으로 종료 코드 1로 끝납니다. 단, `reset-affinity`는 HTTP 404에 종료 코드 4, HTTP 409에 종료 코드 5를 반환하며, 그 밖의 API 실패나 확인되지 않은 결과는 종료 코드 1을 반환합니다. 자격 증명 필드는 관리 API가 반환한 그대로 표시됩니다(마스킹도 그대로 포함됩니다). 원시 API 키와 OAuth 토큰은 절대 반환하지 않습니다. 표시 편의 기능은 대시보드와 마찬가지로 클라이언트 쪽에서 합성합니다. `main`은 `openai` 계정 풀의 Codex App 로그인에 대한 CLI 별칭이고, 이메일이 없는 OAuth 계정은 `Account N`으로 표시되며, plan/label 열은 plan, 마스킹된 이메일, label, 마스킹된 키 순으로 대체합니다. `--json` 계정 행은 다음 공통 형태를 사용합니다(사용할 수 없는 필드는 생략됩니다): @@ -241,12 +264,28 @@ Codex pool selection applies to the next request after clearing existing affinit ### `ocx account list [provider] [--json] [--all] [--quota [--refresh]]` +저장된 ChatGPT 풀 계정은 네이티브 Codex 홈이 없는 호스트에서도 대시보드와 계정 새로 고침을 +포함해 계속 나열할 수 있습니다. 목록 조회는 Codex 홈을 만들거나 네이티브 메인 계정에서 +로그아웃하지 않습니다. Codex 클라이언트 통합을 비활성화해도 기존 네이티브 로그인의 할당량 +관측은 비활성화되지 않습니다. 명시적으로 지정한 `CODEX_HOME` 경로가 유효하지 않으면 계속 +설정 오류를 반환합니다. `OPENCODEX_HOME` 저장소가 안전하지 않으면 네이티브 Codex 홈이 +없어도 오류를 반환합니다. +기본 Codex 홈의 경로를 확인할 때도 파일, 대상이 없는 심볼릭 링크, 탐색할 수 없는 상위 디렉터리는 오류를 발생시킵니다. + 제공자를 지정하지 않으면 Codex 풀, OAuth 계정, 설정된 API 키 풀을 나열합니다. `--all`이 없으면 비어 있는 제공자는 건너뜁니다. 제공자를 지정하면 해당 자격 증명 계열만 나열합니다. 사람이 보는 출력은 `PROVIDER TYPE ID PLAN/LABEL PRIORITY STATUS` 형식을 사용하며, 수동으로 선택한 Codex 행에는 `selected`가 표시됩니다. 사용 가능한 Kiro 계정이 두 개 이상 저장되어 있으면 기본적으로 429 응답 시 다른 계정으로 자동 전환하며, 알려진 잔여 할당량이 가장 많은 계정을 우선합니다. 이 전환은 계정 존재만으로 활성화되며 끌 수 없습니다. `oauthAccountFailover.enabled: false`는 429 복구가 아니라 요청을 보내기 전 계정을 고르는 동작만 거부합니다. `ocx account login kiro`는 계정을 한 번에 하나씩 풀에 추가합니다. 빈 결과도 성공입니다. `--json`은 다음을 반환합니다: ```text { accounts: AccountRow[], notes: string[] } ``` +Codex JSON 행에는 등록된 `id`와 같은 `slotId`, 그리고 `native-main` 또는 `pool`인 +`slotKind`가 포함됩니다. 프록시가 상위 계정과 사용자 식별값을 모두 확인하면 +`uai1_` 뒤에 소문자 16진수 64자리가 붙는 `upstreamAccountKey`도 제공합니다. +같은 `openai` 제공자에서 키가 같으면 한 상위 사용자의 슬롯이며, 각 슬롯과 한도 상태는 +그대로 유지해야 합니다. 키는 이 설치 환경에 한정되고 관리자 토큰이 바뀌면 달라질 수 +있습니다. 키가 없을 때는 가려진 이메일이나 한도가 비슷하다는 이유로 묶지 않습니다. +상위 계정 ID·사용자 식별값·인증 정보 원문은 목록에 포함되지 않습니다. + ### `ocx account current [--json]` 활성 계정이나 키를 보여줍니다. 수동 고정이 없는 Codex 풀은 우선순위를 고려한 자동 선택을 보고합니다. 가장 우선순위가 높은 적격 tier를 고르고, 그 tier 안에서 할당량 라우팅 기준으로 가장 적게 사용한 항목을 선택합니다. 활성 자격 증명이 없는 다른 계열은 그 상태를 보고하고도 종료 코드 0으로 끝납니다. `--json`은 다음을 반환합니다: @@ -260,7 +299,7 @@ Codex pool selection applies to the next request after clearing existing affinit `auto`는 수동 선택을 지워 풀이 다시 자체 전략으로 작업을 배치하게 합니다 — 단 id가 `auto`인 Codex 계정이 있으면 정확한 id 일치가 우선되며 `ocx account clear `는 항상 자동 선택을 복원합니다. Codex 계정은 id 대신 `ocx account alias`로 지정한 별칭으로도 가리킬 수 있으며, `priority`, `pause`, `resume`, `clear-cooldown`, `remove`, `alias`에서도 마찬가지입니다. Codex 계정에서 `auto`, `main`, `__main__`은 대소문자 구분 없이 예약어이므로 별칭으로 지정할 수 없습니다. OAuth 계정과 API 키의 표시 이름에는 기존 규칙이 그대로 적용됩니다. 기존 Codex 계정, OAuth 계정 또는 API key를 선택합니다. `openai`에서 `main`은 Codex App 로그인을 -선택합니다. Codex Pool 선택은 프로세스 로컬 affinity를 지우고 기존에 보이던 작업을 포함한 다음 요청부터 적용됩니다. 프록시 재시작이나 affinity eviction 뒤에도 작업이 바인딩 없는 상태가 될 수 있지만, 진행 중인 요청은 이미 확보한 계정을 유지합니다. 이 선택은 Pool 라우팅만 제어하며 Direct mode는 호출자 소유/native main credential을 계속 사용합니다. 사용량 기반 선제 전환, 401/403 재인증, 429/retry-after cooldown, 제외, 출력 전 429/402 실패 복구는 나중에 다른 적격 Pool 계정을 선택할 수 있습니다. 이러한 복구 경로는 사용량 기반 전환이 꺼져 있어도 동작합니다. 계정이 바뀌어도 OpenCodex는 대화 문맥을 재생하지만 프로바이더 측 prompt cache는 다시 예열해야 할 수 있습니다. +선택합니다. Codex Pool 선택은 affinity를 지우고 기존에 보이던 작업을 포함한 다음 요청부터 적용됩니다. 세션 ID가 있는 요청(일반적인 Codex CLI 및 App 턴과 서브에이전트 포함)이나 바로 위 부모에 연결된 세션 없는 요청의 바인딩은 종료 시 마지막 affinity 저장이 성공하면 프록시를 정상적으로 재시작해도 최대 24시간의 유휴 기간 동안 유지될 수 있습니다. 더 깊은 세션 없는 체인과 Codex App의 주 로그인에 대한 바인딩은 메모리에만 남으며 재시작 후 다시 배정됩니다. eviction, 계정 삭제, 재로그인, 충돌 또는 affinity 초기화로 작업이 바인딩 없는 상태가 될 수 있습니다. 진행 중인 요청은 이미 확보한 계정을 유지합니다. 이 선택은 Pool 라우팅만 제어하며 Direct mode는 호출자 소유/native main credential을 계속 사용합니다. 사용량 기반 선제 전환, 401/403 재인증, 429/retry-after cooldown, 제외, 출력 전 429/402 실패 복구는 나중에 다른 적격 Pool 계정을 선택할 수 있습니다. 이러한 복구 경로는 사용량 기반 전환이 꺼져 있어도 동작합니다. 계정이 바뀌어도 OpenCodex는 대화 문맥을 재생하지만 프로바이더 측 prompt cache는 다시 예열해야 할 수 있습니다. 알 수 없는 프로바이더나 id는 종료 코드 1입니다. `--json`은 다음을 반환합니다. **401/403**이 발생하면 해당 계정의 프로세스 로컬 affinity를 해제하고 재인증을 요구합니다. **429**에서는 `Retry-After`를 준수해 계정 cooldown을 시작하고 affinity를 해제한 뒤, @@ -431,13 +470,15 @@ native-main 트래픽이나 저널 복구를 허용하기 전에 수명 주기 ### `ocx models [subcommand]` · `ocx model ` -`ocx model`은 `ocx models`의 별칭입니다. 하위 명령이 없으면 설정된 제공자에 사전 등록된 모델을 나열합니다. `--provider`는 설정된 제공자 하나를 필터링하고 `--json`은 모델 메타데이터를 반환합니다. `live`는 실행 중인 카탈로그를 읽습니다. `add`, `edit`, `remove`, `list-custom`은 수동 카탈로그 항목을 관리합니다. `enable`, `disable`, `provider`는 가시성을 제어합니다. `selected`는 제공자 허용 목록을 제어합니다. `context`는 제공자 컨텍스트 한도를 제어합니다. `shadow`는 백그라운드 shadow-call 가로채기를 관리합니다. +`ocx model`은 `ocx models`의 별칭입니다. 하위 명령이 없으면 저장된 모델과 라우터가 아는 모델 ID를 나열합니다. 레지스트리 시드, 사용자 정의 모델, 현재 CLI 프로세스의 검색 캐시가 포함됩니다. 새 CLI 프로세스의 캐시는 비어 있을 수 있으며 실행 중인 프록시 카탈로그와 다릅니다. 일부 기존 키 방식 프리셋은 접속 주소를 바꾼 뒤에도 레지스트리 시드를 유지할 수 있습니다. `--provider`는 설정된 제공자 하나를 필터링하고 `--json`은 모델 메타데이터를 반환합니다. `live`는 실행 중인 카탈로그를 읽습니다. `add`, `edit`, `remove`, `list-custom`은 수동 카탈로그 항목을 관리합니다. `enable`, `disable`, `provider`는 가시성을 제어합니다. `selected`는 제공자 허용 목록을 제어합니다. `context`는 제공자 컨텍스트 한도를 제어합니다. `shadow`는 백그라운드 shadow-call 가로채기를 관리합니다. + +`reasoningEfforts` 목록은 `--json`에서만 표시됩니다. `null`은 목록을 알 수 없거나 조회하지 않았다는 뜻이며, 확인하려면 OS 키체인을 열어야 하는 경우도 포함합니다. 빈 배열 `[]`은 명시적으로 비어 있는 목록이거나 `noReasoningModels` 등으로 해당 모델의 reasoning effort가 비활성화됐다는 뜻입니다. 실행 중인 프록시의 카탈로그는 `ocx models live`로 확인합니다. `add`·`remove`는 기본적으로 로컬 저장이며 `--live`를 주면 실행 중인 프록시를 바꿉니다. 로컬 `--json` 저장은 프록시가 없으면 `sync.status: "not-attempted"`, `needsSync: true`, 종료 코드 0을 반환합니다. 실제 동기화 시도가 실패하면 저장은 유지하고 0이 아닌 코드로 끝납니다. `list-custom`은 로컬 목록입니다. 발견된 모델의 표시 이름은 raw upstream ID를 받는 `display-name`으로 바꾸고, picker 순서는 public ID를 받는 `order`로 바꿉니다. [영문 절차](/reference/cli/providers-accounts/#display-names-and-picker-identities)에서 전체 목록·featured 접두부·native 순서 초기화 제약을 확인하세요. | 하위 명령 | 지원 플래그 | 동작 | | --- | --- | --- | -| `list` (기본값) | `--provider `, `--json` | 설정된 제공자에 사전 등록된 모델을 나열합니다. | +| `list` (기본값) | `--provider `, `--json` | 로컬에 저장된 모델과 라우터가 아는 모델을 나열합니다. | | `live` | `--provider `, `--json` | 런타임에 발견된 모델을 포함해 실행 중인 카탈로그를 읽습니다. 행에는 `native`/`routed`, `custom`, `enabled`/`disabled` 표시가 붙습니다. | | `add ` | `--display-name `, `--context-window `, `--modalities `, `--live`, `--json` | 사용자 정의 모델을 로컬에 등록하거나 `--live`로 실행 중인 프록시에 등록합니다. | | `edit ` | `--model-id `, `--display-name `, `--context-window `, `--modalities `, `--json` | 사용자 지정 모델을 수정합니다. `-`는 필드를 지우고, `0`은 컨텍스트 창을 지웁니다. | diff --git a/docs-site/src/content/docs/ko/reference/client-support.md b/docs-site/src/content/docs/ko/reference/client-support.md new file mode 100644 index 0000000000..2e52ed4cd4 --- /dev/null +++ b/docs-site/src/content/docs/ko/reference/client-support.md @@ -0,0 +1,60 @@ +--- +title: "클라이언트 지원" +description: "opencodex가 연결하는 코딩 도구, 각 도구의 연결 방식, 사용하는 프로토콜." +--- + + + + +opencodex는 AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨이입니다. 일부 도구는 직접(네이티브로) 설정하고, 나머지는 로컬 프록시를 가리키는 설정 파일을 내보내거나 관리합니다. 이 페이지는 코드 레지스트리에서 생성되므로 현재 릴리스가 제공하는 내용과 정확히 일치합니다. + +## 지원 수준 + +- **implemented**: 레지스트리에 등록된 클라이언트입니다. 내보내는 설정의 경우 표의 프로토콜은 opencodex가 생성하는 설정에서 읽으며, 바뀌면 생성이 실패합니다. *검토됨* 표시는 설정 자체가 아니라 리뷰에서 나온 특정 엔드포인트를 뜻합니다(네이티브 클라이언트, 설정값을 특정 엔드포인트로 바꾸는 클라이언트). 생성기는 리뷰한 코드가 그대로 있는지 확인합니다. 'OpenAI 호환' 행은 엔드포인트를 단정하지 않습니다. +- **test-covered**: implemented이면서, 리뷰로 고른 이 클라이언트의 테스트 케이스가 링크되어 있습니다. 생성기는 테스트가 존재하고 비활성화되지 않았는지만 확인하므로, 무엇을 검증하는지는 테스트를 직접 읽어 보세요. +- **실행 검증**: 특정 시점의 관찰 기록입니다. 표에 적힌 클라이언트 제품·버전을 표에 적힌 opencodex 버전과 함께, 명시한 시나리오로, 그 날짜에 사람이 실행하고 증거를 링크했습니다. 다른 버전이나 제품에 대해서는 아무것도 보장하지 않습니다. 증거는 결과를 추가할 때 리뷰하며, 생성기가 다시 실행하지 않습니다. 대시(—)는 기록된 결과가 없다는 뜻입니다. + +## 클라이언트 + +| 클라이언트 | 네이티브 | 설정 내보내기 | 관리형 파일 연동 | 수신 프로토콜 | 지원 수준 | 실행 검증 | 참고 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Codex (CLI, app, SDK) | 예 | — | — | Responses (검토됨) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/codex-integration/codex-inject-missing-config.test.ts)) | — | opencodex가 직접 설정하며 내보내는 설정 파일은 없습니다. [가이드](/ko/guides/codex-integration/) | +| Claude Code | 예 | — | — | Anthropic Messages (검토됨) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/claude-integration/claude-cli.test.ts)) | — | opencodex가 직접 설정하며 내보내는 설정 파일은 없습니다. [가이드](/ko/guides/claude-code/) | +| Claude Desktop | 예 | — | — | Anthropic Messages (검토됨) | implemented | — | opencodex가 직접 설정하며 내보내는 설정 파일은 없습니다. | +| Grok Build | 예 | — | — | Responses (검토됨) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/providers/xai/grok-config-inject.test.ts)) | — | opencodex가 직접 설정하며 내보내는 설정 파일은 없습니다. [가이드](/ko/guides/grok-build/) | +| Qoder | — | JSON | 예 | OpenAI 호환(엔드포인트는 클라이언트가 선택) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/qoder-client.test.ts)) | — | 로컬 리스너 전용. | +| Qoder CN | — | JSON | 예 | OpenAI 호환(엔드포인트는 클라이언트가 선택) | implemented | — | 로컬 리스너 전용. | +| WorkBuddy | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/agent-clients.test.ts)) | — | 로컬 리스너 전용. 적용 전에 클라이언트별 검사를 실행하며 거부할 수 있습니다. | +| WorkBuddy AI | — | JSON | 예 | Chat Completions | implemented | — | 로컬 리스너 전용. 적용 전에 클라이언트별 검사를 실행하며 거부할 수 있습니다. | +| OpenCode | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | 원격 리스너도 지원합니다(API 키 헤더를 추가). [가이드](/ko/guides/opencode/) | +| Pi | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | 로컬 리스너 전용. [가이드](/ko/guides/pi/) | +| Oh My Pi (omp) | — | YAML | 예 | Chat Completions; Responses (네이티브 OpenAI 모델만) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | 로컬 리스너 전용. 자기 YAML 블록만 수정합니다. | +| Hermes | — | YAML | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/hermes-catalog-refresh.test.ts)) | — | 원격 리스너도 지원합니다(API 키 헤더를 추가). 자기 YAML 블록만 수정합니다. | +| OpenClaw | — | JSON5 | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/gui/integrations-invariants.test.ts)) | — | 원격 리스너도 지원합니다(API 키 헤더를 추가). | +| Kimi CLI | — | TOML | 예 | OpenAI 호환(엔드포인트는 클라이언트가 선택) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export-new-clients.test.ts)) | — | 로컬 리스너 전용. | +| Gajae | — | YAML | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/client-export-modality-enum.test.ts)) | — | 로컬 리스너 전용. | +| DSH | — | YAML | 예 | Responses | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | 로컬 리스너 전용. 클라이언트의 현재 provider 저장소에 씁니다. 자기 YAML 블록만 수정합니다. 설정 파일 옆 잠금 파일로 쓰기를 조율합니다. | +| MCode | — | YAML | 예 | Anthropic Messages | implemented | — | 로컬 리스너 전용. 설정 파일 옆 잠금 파일로 쓰기를 조율합니다. | +| ZCode | — | JSON | 예 | Responses (검토됨) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/integrations-current-store.test.ts)) | — | 로컬 리스너 전용. 클라이언트의 현재 provider 저장소에 씁니다. 클라이언트가 이 설정값으로 엔드포인트를 고릅니다(클라이언트 문서 동작 기준으로 리뷰함). | +| Command Code | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/command-code-client.test.ts)) | — | 로컬 리스너 전용. 설정 파일 옆 잠금 파일로 쓰기를 조율합니다. | +| Prime | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/prime-client.test.ts)) | — | 로컬 리스너 전용. | +| Aside | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/aside-profiles-catalog-refresh.test.ts)) | — | 로컬 리스너 전용. | +| Raycast | — | YAML | 예 | Chat Completions (검토됨) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/raycast-client.test.ts)) | — | 로컬 리스너 전용. 클라이언트가 이 설정값으로 엔드포인트를 고릅니다(클라이언트 문서 동작 기준으로 리뷰함). | +| omo | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/omo-client.test.ts)) | — | 로컬 리스너 전용. | +| Cline | — | JSON | 예 | Responses | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/cline-client.test.ts)) | — | 로컬 리스너 전용. 설정 파일 옆 잠금 파일로 쓰기를 조율합니다. | +| Kilo Code | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/client-export-reasoning-controls.test.ts)) | — | 원격 리스너도 지원합니다(API 키 헤더를 추가). | +| Factory Droid | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/droid-client.test.ts)) | — | 로컬 리스너 전용. [가이드](/ko/guides/factory-droid/) | +| Gentle Shell | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | 로컬 리스너 전용. | +| T3 Code | — | JSON | 예 | Anthropic Messages | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | 로컬 리스너 전용. 적용 전에 클라이언트별 검사를 실행하며 거부할 수 있습니다. | + +## 수신 엔드포인트 + +프록시는 아래 프로토콜을 받습니다. 위 목록에 없는 도구도 이 중 하나로 사용자 지정 엔드포인트를 설정할 수 있으면 연결할 수 있습니다. + +- `POST /v1/responses`: Responses +- `POST /v1/chat/completions`: Chat Completions +- `POST /v1/messages`: Anthropic Messages + +## 이 페이지 최신 상태 유지 + +이 페이지는 `scripts/generate-client-support-matrix.ts`가 내보내기·관리형 연동·네이티브 연동 레지스트리로부터 생성합니다. 클라이언트를 추가하려면 `scripts/client-support-matrix/metadata.ts`에 항목을 넣고 `bun run docs:clients`를 실행하세요. 커밋된 페이지가 오래되면 `bun run docs:clients:check`가 실패합니다. diff --git a/docs-site/src/content/docs/ko/reference/configuration.md b/docs-site/src/content/docs/ko/reference/configuration.md index 4f80b5136a..25cd618d29 100644 --- a/docs-site/src/content/docs/ko/reference/configuration.md +++ b/docs-site/src/content/docs/ko/reference/configuration.md @@ -27,6 +27,11 @@ opencodex는 지속 설정을 `$OPENCODEX_HOME/config.json`에 저장합니다. 남긴 뒤 기본값으로 시작합니다. 파일이 없어도 새로 설치한 경우의 기본값을 그대로 사용하며, 그것은 단일 `openai` forward 프로바이더입니다. +로컬 `ocx config set`, `unset`, `import`, 오프라인 `ocx effort`, 커스텀 모델 추가·삭제, +프로바이더 추가·삭제·기본값 변경은 기존 `config.json`이 유효하지 않거나 읽을 수 없으면 +원본 바이트를 바꾸지 않고 거부합니다. `ocx config validate`로 확인하고 파일을 고친 뒤 +다시 실행하세요. import도 기존 설정 파일이 있다면 읽을 수 있고 유효한 대상 파일을 요구합니다. + ## 우선순위와 기본값 `config.json`의 유효한 값은 내장 기본값보다 우선합니다. 선택 사항으로 비어 있는 필드는 각 도메인 페이지에 @@ -60,5 +65,7 @@ account id와 이메일도 공개하지 않는 편이 좋으니, 가능하면 opencodex는 관리형 `config.toml`과 `opencodex-catalog.json` 파일을 임시 파일로 쓴 뒤 rename하는 방식(`atomicWriteFile`)으로 저장합니다. 이렇게 하면 `ocx stop`과 프록시 종료 handler처럼 동시에 실행되는 writer가 Codex를 되돌릴 때도 -부분 파일이 생기지 않습니다. +부분 파일이 생기지 않습니다. Windows에서 `opencodex-catalog.json`에 읽기 전용 속성이 있어 +rename이 거부되면 opencodex가 속성을 해제하고 한 번만 재시도합니다. 그래도 실패하면 원시 `EPERM` 대신 +`Codex catalog is read-only: `를 보고합니다. ::: diff --git a/docs-site/src/content/docs/ko/reference/configuration/advisor.md b/docs-site/src/content/docs/ko/reference/configuration/advisor.md index 0e1b4d940f..dd7c22c811 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/ko/reference/configuration/advisor.md @@ -60,12 +60,18 @@ description: manual, preflight 및 증거 기반 adaptive 정책을 제공하는 설정된 어드바이저 프로바이더는 워커의 프로바이더와 다를 수 있습니다. +상담은 호출자에게서 캡처한 API 키의 모델 범위, 유료 combo 동의, 디바이스 fallback 제한과 Advisor 자체 승인 키의 호스트 제한을 모두 따릅니다. 승인 키는 설정된 경우 `OPENCODEX_API_AUTH_TOKEN` 또는 이 프록시가 받아들이는 서비스 토큰 파일이고, 그렇지 않으면 첫 번째로 구성된 API 키입니다. 키 순서는 이 마지막 경우에만 의미가 있습니다. Advisor 모델에 접근할 수 있는 키를 맨 앞에 두지 않으면 모든 상담을 사용할 수 없습니다. 환경 토큰이나 서비스 토큰이 설정되어 있으면 그 토큰이 상담을 결정합니다. 이 규칙은 combo 선택, 중첩 판정 모델, 재시도에도 적용됩니다. 규칙을 충족하지 못한 상담은 worker에게 사용 불가 안내를 반환합니다. + +예를 들어 `allowMeteredComboTargets: false`인 `laptop` 키는 Advisor를 통해 종량제 combo 대상에 비용을 쓸 수 없고, `fallback.devices.laptop.provider: false`는 Advisor의 프로바이더 fallback 홉도 막습니다. 키가 없는 loopback 호출자는 여전히 combo의 `allowMeteredTargets: true` 옵트인이 필요합니다. 두 키가 모두 `allowMeteredComboTargets: true`를 설정하고 combo가 `allowMeteredTargets: true`를 설정하면, 공개 바인드의 loopback 리스너를 거치더라도 Advisor가 종량제 대상을 사용할 수 있습니다. 서버는 본문 용량을 기다리거나 본문을 읽기 전, 요청을 인증할 때 호출자 정책을 캡처합니다. 이후 키나 fallback을 편집해도 그 상담의 범위는 넓어지지 않습니다. 라우팅된 비전 도우미, compact 요청과 그 판정 모델, WebSocket 턴 안의 모든 후보 재시도에도 똑같이 적용됩니다. 새 WebSocket 턴은 각자 자신의 정책을 캡처합니다. + OpenCodex는 프로바이더 API 키, Authorization 헤더, OAuth 토큰, 백엔드 전용 설정 비밀, 프로세스 환경, 숨겨진 사고 과정을 그 프롬프트에 넣지 않습니다. 암호화된 프로바이더 사유 추론을 복호해 전달하지도 않습니다. **작업 내용의 비밀은 일반적으로 제거되지 않습니다.** 작업에 붙여 넣은 키, 도구가 읽은 파일 속의 비밀, 도구나 로그가 출력한 토큰은 전송될 수 있습니다. OpenCodex는 범용 DLP를 실행하지 않습니다. ## 권한 수동 조언은 워커가 직접 호출한 `advisor`에 대한 도구 결과입니다. 결과는 JSON 객체입니다. `advice`는 어드바이저 모델의 텍스트입니다. `status`는 런타임이 씁니다. +fetch 기반 웹 검색 턴에서는 실제 적용되는 `tool_choice`가 합성 `advisor` 도구를 허용할 때만 해당 도구를 노출하고 수동 상담 호출을 가로챕니다. `allowed_tools`가 `web_search`로 제한되어 있으면 어드바이저 수동 상담은 허용되지 않습니다. 호스팅 검색을 활성화해도 이 도구 허용 범위가 넓어지지는 않습니다. + 자동 조언의 인용된 JSON은 별도의 user 역할 자문 메시지로 전달합니다. developer 메시지에는 고정된 런타임 지시만 남고, Advisor가 생성한 텍스트는 developer/system에 들어가지 않습니다. OpenAI Chat과 Anthropic 모두 가짜 도구 호출 없이 이를 지원합니다. JSON 인용은 구조 탈출과 필드 위조를 막지만 자연어 프롬프트 주입을 완전히 차단하지는 않습니다. 전용 프로토콜은 일반 사용자 입력과 조언을 더 명확히 구분할 수 있습니다. 요청당 상담은 최대 3회, 워커 이어가기는 최대 4회입니다. 상담 한도에 도달하면 advisor 도구를 제거하고 반복 호출에 한도 결과를 전달하는 마지막 이어가기를 한 번만 허용합니다. 다시 호출하면 추가 전송 없이 502 advisor_continuation_limit로 끝납니다. 빈 완료 재시도도 같은 한도를 공유합니다. 억제는 어드바이저 문자열을 읽지 않습니다. 자동 중복 제거는 서버가 소유한 원장뿐입니다. 전송 문장을 복사한 developer 메시지도 preflight를 억제하지 않습니다. diff --git a/docs-site/src/content/docs/ko/reference/configuration/providers.md b/docs-site/src/content/docs/ko/reference/configuration/providers.md index e3b823d0e9..156978ba6e 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ko/reference/configuration/providers.md @@ -5,12 +5,26 @@ description: 공급자 항목, 인증, 엔드포인트, 모델 카탈로그, 할 공급자는 opencodex에 모델의 위치, 사용하는 와이어 어댑터, 요청 인증 방식을 알려줍니다. +## Mistral 요청당 이미지 수 + +Mistral 요청의 이미지 수 제한과 `mistralMaxImages` 설정은 [영문 기준 문서](/reference/configuration/providers/#mistral-images-per-request)를 참조하세요. 제한기에 도달한 `image_url` 항목의 이미지 참조가 누락되거나 비어 있거나 문자열이 아니면 전송용 사본에서 텍스트로 대체되며 이미지 한도를 소비하지 않습니다. 번역되는 Responses 요청에서 사용 가능한 URL과 파일 ID가 모두 없는 `input_image`는 파서가 제외합니다. 메시지나 도구 출력 블록 안에서 비어 있지 않은 `file_id`만 있고 비어 있지 않은 `image_url`이 없으면 미디어 가드가 Mistral 전송 전에 요청을 거절합니다. 가드가 검사하지 않는 재생된 `agent_message` 내부에서는 파서가 대신 `[image: ]` 텍스트 마커를 내보내며 일반 텍스트로 전송되고 이미지 한도를 소비하지 않습니다. 제한기는 `image_url` 또는 `image_url.url`의 비어 있지 않은 문자열만 계산하고 URL 문법이나 접근 가능성은 검증하지 않습니다. 다른 대상의 동작은 바뀌지 않습니다. + ## 사용자 지정 공급자의 컨텍스트 모델 창이 보고되거나 설정되지 않으면 Azure 메타데이터, 모델 ID로 찾은 번들 공급업체/집계 메타데이터, 활성 Context cap, 128k 순서로 보완합니다. 보고된 값과 설정 값 중 작은 값을 유지하고 Context cap은 계속 상한으로 적용됩니다. 기본 공급자는 바뀌지 않습니다. 정확한 ID를 우선하며 대소문자 및 점/하이픈 변형은 충돌이 없을 때만 허용합니다. 추정값은 Codex 압축 예산과 Claude 등 클라이언트 카탈로그에 반영되지만 라우팅의 검증된 용량으로 취급하지 않습니다. 같은 모델 이름이 중계 서비스의 실제 용량을 보장하지 않으므로 modelContextWindows 또는 Context cap으로 실제 상한을 설정하세요. cap을 자동으로 켜거나 모델 시험 요청을 보내지 않습니다. OpenAI API 값은 Codex 구독의 제한이 아닙니다. 이 추정은 기본적으로 꺼져 있습니다. 공급자별로 `inferContextWindow: true`를 설정해야 켜집니다. 설정하지 않으면 창이 없는 모델은 활성 Context cap, 그다음 128k를 사용합니다. +## GPT-6.1 Terra + +[GPT-6.1 Terra](https://openai.com/index/introducing-gpt-6-1-terra/)는 GPT-5.6 Terra의 후속 모델로 2026년 10월 26일 출시되었습니다. `gpt-6.1-terra`는 `gpt-5.6-terra`와 함께 제공하며 기본 모델이나 하위 에이전트 모델 목록은 바꾸지 않습니다. GitHub Copilot에서는 Responses를 사용합니다. OpenRouter ID는 `openai/gpt-6.1-terra`이며 컨텍스트는 1,050,000, 100만 토큰당 입력 $1.00 / 출력 $5.00입니다. + +네이티브 Codex: 기본 컨텍스트 500,000, 장문 상한 872,000, 기본 effort `low`, 단계는 `low`, `medium`, `high`, `xhigh`, `max`, `ultra`입니다. 네이티브 `ultra`는 전송 시 `max`로 변환합니다. 네이티브 행의 고속 모드는 Fast만 제공합니다. + +[OpenAI API](https://developers.openai.com/api/docs/models/gpt-6.1-terra): 컨텍스트 1,050,000, 최대 출력 128,000, 텍스트·이미지 입력과 텍스트 출력, 지식 기준일 2026-06-01입니다. effort는 `none`, `low`, `medium`(기본), `high`, `xhigh`, `max`입니다. 엔드포인트는 `v1/responses`와 `v1/chat/completions`이며 도구 호출에는 Responses가 필요합니다. + +100만 토큰당 입력 $1.00, 캐시 입력 $0.05, 캐시 쓰기 $1.25(30분), 출력 $5.00입니다. 입력이 272,000 토큰을 초과하면 요청 전체에 입력·캐시 2×, 출력 1.5×를 적용하여 각각 $2.00 / $0.10 / $2.50 / $7.50입니다. Fast 모드는 2×입니다. + ## 처음 등록할 때의 모델 선택 신규 비-OAuth 연결은 신뢰할 수 있는 모델 목록을 확보할 때까지 모델 노출을 보류합니다. Models 탭의 중복 없는 모델 행이 20개 이상이면 모델 스위치를 모두 OFF로 설정합니다. 프로바이더는 활성 상태를 유지합니다. 실제 인증 방식이 OAuth나 ChatGPT 로그인인 연결은 기존 기본값을 유지합니다. @@ -33,6 +47,7 @@ GUI에서 등록이나 OAuth 로그인을 마치면 Models 페이지로 이동 | `providers` | `Record` | — | 공급자 이름을 공급자 설정에 매핑합니다. | | `openaiProviderTierVersion?` | `2` | 마이그레이션으로 설정됨 | 옵션을 인식하는 단일 OpenAI 투영이 완료되었음을 표시합니다. | | `disabledModels?` | `string[]` | — | Codex catalog와 `/v1/models`에서는 숨기지만 직접 proxy 호출은 차단하지 않습니다. routed id는 목록에서 제거됩니다. account-qualified native id는 해당 selector row만 숨기고, bare native GPT id는 bare row와 그 model의 모든 account-selector row를 숨깁니다. Models 페이지에는 bare native 행과 routed 행만 표시됩니다. selector-qualified 행 하나만 숨기려면 이 설정 필드에 직접 추가하세요. | +| `omitDisabledNativeModels?` | `boolean` | `false` | 기본값은 `false`입니다. `config.json`에 `"omitDisabledNativeModels": true`를 설정하고 `ocx sync`를 실행하면 비활성화한 native 행을 catalog와 cache, Codex 형식의 HTTP 모델 목록에서 제외합니다. 제외 전 검증한 상속 템플릿을 보존하므로 routed 행의 메타데이터는 유지되며 직접 요청의 라우팅은 바뀌지 않습니다. | | `providerContextCaps?` | `Record` | `{}` | 공급자별 활성 컨텍스트 상한입니다. 일반 윈도는 줄어들며, 장문 윈도를 지원하는 네이티브 모델은 해당 모델의 지원 상한까지만 확장할 수 있습니다. | | `providerContextCapValues?` | `Record` | `{}` | 공급자별로 마지막에 선택한 상한입니다. 꺼도 선택값이 남으며, 저장된 값만으로는 상한이 활성화되지 않습니다. 활성 값이 저장된 선택값보다 우선합니다. | | `contextCapValue?` | `number` | `350000` | 처음 켤 때 쓰는 기본값입니다. 다시 켜면 공급자별 선택값을 복원합니다. `setAll: true`와 함께 전역 값을 바꾸면 활성 상한만 갱신합니다. 값 없이 `setAll: true`를 보내면 설정된 모든 공급자의 상한을 현재 전역 값으로 켭니다. | @@ -42,9 +57,9 @@ GUI에서 등록이나 OAuth 로그인을 마치면 Models 페이지로 이동 | `codexAccountPickerEnabled?` | `boolean` | map이 비어 있으면 꺼짐 | 유효한 `codexAccountNamespaces` 매핑에서 account-qualified Codex 선택기 행을 생성할지 제어합니다. `true`는 매핑된 행의 표시를 허용합니다. 비어 있지 않은 map에서 생략하면 이전 버전과의 호환성을 위해 활성화된 것으로 취급되며, map이 비어 있으면 꺼집니다. `false`는 매핑을 삭제하거나 명시적 `/` 라우팅을 비활성화하지 않은 채 생성 행을 숨기고 선택기에 bare native 행을 복원합니다. | | `activeCodexAccountId?` | `string` | — | 다음 요청에 수동으로 선택한 Pool 계정입니다. 선택하면 thread 결속이 해제되며, 진행 중인 요청은 캡처한 자격 증명을 유지합니다. | | `codexAccountPriorities?` | `Record` | — | Codex pool의 계정별 선택 순서. 계정 ID → `-100`부터 `100`까지의 정수이며 **값이 클수록 먼저** 쓰이고, 항목이 없으면 `0`입니다. 이는 eligibility 경계가 아니라 순서 경계입니다. 선택은 이미 적격한 계정들을 quota 여유가 남은 최상위 tier로 좁히고, 그 tier 안에서 `accountPoolStrategy`가 계정을 고릅니다. tier를 건너뛰는 경우는 그 구성원 전부가 자신의 0이 아닌 유효 임계값(계정별 재정의 또는 전역 기본값) 이상, cooldown, soft-avoid, 일시 중지 또는 재인증 대기일 때뿐이며, usage를 알 수 없다고 해서 tier가 소진되지는 않습니다. 순서는 부적격 계정을 선택 가능하게 만들지 않고, 이미 계정에 묶인 thread를 다시 bind하지도 않습니다. 메인 `__main__` 계정도 동일한 조건으로 참여하므로 Codex Desktop 로그인을 마지막에 쓰도록 둘 수 있습니다. 항목이 하나도 없으면 동작은 이전과 같습니다. map이 잘못된 경우 경고를 출력하고 순서 지정을 끕니다(config 복구는 하지 않습니다). `ocx account priority`와 Codex Auth 페이지에서 관리합니다. | -| `autoSwitchThreshold?` | `number` | `80` | 사용량 기반 선제 전환 임계값입니다. `quota`는 바인딩 없는 작업의 다음 요청을 재평가할 수 있습니다. 바인딩된 작업은 기본값(`pool.cacheAffinity`)에서 이 임계값을 넘어도 계정을 유지하며, 해당 계정이 소진되었거나 더 이상 처리할 수 없을 때에만 떠나고, 그때도 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. `pool.cacheAffinity: false`로 두면 임계값에서 바인딩된 작업도 재평가합니다. `fill-first`는 바인딩 없는 작업 배정의 소진 기준으로만 사용하며, 기본 `round-robin` 선택은 이 값을 사용하지 않습니다. 알려진 5시간, 주간, 30일 quota window 중 가장 높은 점수를 씁니다. `0`은 사용량 기반 전환만 끄며 바인딩 없는 작업 배정이나 실패 복구는 끄지 않습니다. | +| `autoSwitchThreshold?` | `number` | `80` | 사용량 기반 선제 전환 임계값입니다. `quota`는 바인딩 없는 작업의 다음 요청을 재평가할 수 있습니다. 바인딩된 작업은 기본값(`pool.cacheAffinity`)에서 이 임계값을 넘어도 계정을 유지하며, 해당 계정이 소진되었거나 더 이상 처리할 수 없을 때에만 떠나고, 그때도 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. `pool.cacheAffinity: false`로 두면 임계값에서 바인딩된 작업도 재평가합니다. `fill-first`는 바인딩 없는 작업 배정의 소진 기준으로만 사용하며, `round-robin`은 새/바인딩 없는 작업 배정에만 사용하며 임계값 미만인 적격 계정이 남아 있는 동안 유효 임계값 이상인 계정을 건너뛰고 이 때문에 바인딩된 작업을 옮기지 않습니다. 알려진 5시간, 주간, 30일 quota window 중 가장 높은 점수를 씁니다. `0`은 사용량 기반 전환만 끄며 바인딩 없는 작업 배정이나 실패 복구는 끄지 않습니다. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | 계정별 `autoSwitchThreshold` 재정의입니다(계정 ID → `0`~`100` 정수). 항목이 없으면 전역 값을 상속하고, `0`은 해당 계정에서 시작하는 사용량 기반 전환만 끕니다. 메인 `__main__` 계정도 지원합니다. Codex Auth의 계정 카드에서 관리합니다. 재정의를 켜면 현재 전역 임계값을 고정된 계정별 값으로 복사합니다. `0`을 포함한 재정의 값은 이후 전역 값이 바뀌어도 우선합니다. 끄면 `threshold: null`을 보내 항목을 삭제하고 현재 전역 임계값과 향후 변경 사항을 상속하는 상태로 돌아갑니다. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 새 작업/바인딩 없는 Codex 요청의 계정 배정 전략입니다. `(parent thread id, quota scope)`의 live affinity가 없으면 바인딩 없는 요청이며, 프록시 재시작이나 affinity 초기화 뒤에는 기존에 보이던 작업도 바인딩이 없어질 수 있습니다. `quota`는 활성 계정이 없을 때 알려진 usage가 가장 낮은 적격 계정을 선택하고, 적격 활성 계정이 `autoSwitchThreshold` 미만이면 유지합니다. 임계값 도달 뒤에는 바인딩 없는 요청을 옮길 수 있습니다. 바인딩된 작업은 기본값에서 계정이 소진되었거나(알려진 usage 100%) 더 이상 처리할 수 없을 때까지 유지되며, 떠날 때는 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. 플래그를 끄면 임계값에서 바인딩된 작업의 다음 요청도 실제 quota 여유가 있고 usage가 더 낮은 적격 계정으로 옮길 수 있습니다. `round-robin`은 바인딩 없는 요청을 균등 분배하고, `fill-first`는 cooldown, 사용 불가 또는 drain threshold까지 활성 계정에 배정합니다. `reset-first`: 사용량 임계값 미만인 계정 중 다음 5시간·주간 초기화가 가장 가까운 계정을 고릅니다. 연결된 작업은 설정된 어피니티 정책을 따릅니다. 독립 모델 한도에는 사용량 순서를 적용합니다. 월간 초기화는 이 순서에 사용하지 않습니다. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 새 작업/바인딩 없는 Codex 요청의 계정 배정 전략입니다. `(parent thread id, quota scope)`의 live affinity가 없으면 바인딩 없는 요청입니다. 세션 ID가 있는 요청(일반적인 Codex CLI 및 App 턴과 서브에이전트 포함)이나 바로 위 부모에 연결된 세션 없는 요청의 바인딩은 종료 시 마지막 affinity 저장이 성공하면 프록시를 정상적으로 재시작해도 최대 24시간의 유휴 기간 동안 유지될 수 있습니다. 더 깊은 세션 없는 체인과 Codex App의 주 로그인에 대한 바인딩은 메모리에만 남으며 재시작 후 다시 배정됩니다. eviction, 계정 삭제, 재로그인, 충돌 또는 affinity 초기화로 작업이 바인딩 없는 상태가 될 수 있습니다. `quota`는 활성 계정이 없을 때 알려진 usage가 가장 낮은 적격 계정을 선택하고, 적격 활성 계정이 `autoSwitchThreshold` 미만이면 유지합니다. 임계값 도달 뒤에는 바인딩 없는 요청을 옮길 수 있습니다. 바인딩된 작업은 기본값에서 계정이 소진되었거나(알려진 usage 100%) 더 이상 처리할 수 없을 때까지 유지되며, 떠날 때는 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. 플래그를 끄면 임계값에서 바인딩된 작업의 다음 요청도 실제 quota 여유가 있고 usage가 더 낮은 적격 계정으로 옮길 수 있습니다. `round-robin`은 유효 `autoSwitchThreshold` 미만인 적격 계정에 바인딩 없는 요청을 균등 분배하고 모두 임계값 이상이면 모든 적격 계정에 분배하며, `fill-first`는 cooldown, 사용 불가 또는 drain threshold까지 활성 계정에 배정합니다. `reset-first`: 사용량 임계값 미만인 계정 중 다음 5시간·주간 초기화가 가장 가까운 계정을 고릅니다. 연결된 작업은 설정된 어피니티 정책을 따릅니다. 독립 모델 한도에는 사용량 순서를 적용합니다. 월간 초기화는 이 순서에 사용하지 않습니다. | | `pool.cacheAffinity?` | `boolean` | `true` | 바인딩된 Codex 스레드의 cache-affinity 순서입니다. `pool.kernel`과는 별개이며 기본값은 켜짐입니다. 잘못된 값은 켜진 것으로 읽습니다. live 바인딩이 quota 여유보다 우선하므로 `quota`는 사용량이 `autoSwitchThreshold`를 넘었다는 이유만으로 스레드를 옮기지 않습니다. 해당 계정이 일시 중지되었거나 사용할 수 없거나 실제로 소진된 경우(알려진 usage 100%)에는 떠나되, 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. `false`로 두면 임계값 재바인딩이 복원됩니다. affinity는 고정이 아니라 재정렬입니다. | | `accountPoolStickyLimit?` | `number` | `1` | 한 round-robin 선택이 다음으로 넘어가기 전에 유지하는 새 작업/바인딩 없는 작업 배정 수입니다. 카운터는 업스트림 성공 뒤가 아니라 작업을 바인딩할 때 증가합니다. 범위 1–100이며 `accountPoolStrategy`가 `round-robin`일 때만 적용됩니다. | | `upstreamFailoverThreshold?` | `number` | `3` | 연속된 일시적 실패가 이 횟수에 도달하면 이후 새 세션은 failover됩니다. `0`으로 두면 비활성화됩니다. 일반 Responses와 네이티브 compact 전송에서 입증된 연결 전 DNS/TCP 도달 불가 실패는 provider-host 범위로 기록되며 계정 상태, 계정 쿨다운, 스레드/세션 선호도, 활성 계정 선택 또는 Pool 라우팅에 영향을 주지 않고 이 임계값에도 집계되지 않습니다. | @@ -52,6 +67,8 @@ GUI에서 등록이나 OAuth 로그인을 마치면 Models 페이지로 이동 | `codexPinnedTransientPolicy?` | `"hold" \| "detour-new-threads"` | `"hold"` | 수동 핀이 저하되면 `hold`는 경고를 남기고 계속 사용하고, `detour-new-threads`는 새 스레드만 다른 계정에 둡니다. 이미 보낸 턴은 다시 보내지 않습니다. | | `codexWsReuseAcrossTurns?` | `boolean` | `false` | 같은 계정과 스레드의 Codex WebSocket을 턴 사이에 재사용합니다. 기본값은 꺼짐입니다. 켜면 바쁜 소켓을 최대 750ms 기다리고, 모델이나 티어가 바뀌어도 소켓을 최대 2개 유지합니다. | | `upstreamHostCircuitThreshold?` | `number` | `0` | 네이티브 OpenAI forward Responses와 compact 전송에서 입증된 연결 전 DNS/TCP 실패에 적용하는 선택적 회로 차단 임계값입니다. `0`은 비활성화하며, `1`~`20`은 이 횟수만큼 최종 논리 요청이 실패하면 provider-origin을 30초 동안 차단합니다. 차단 중에는 계정 선택이나 업스트림 전송 전에 `Retry-After`가 포함된 `503`을 반환하고, 시간이 지나면 반개방 요청 하나만 허용합니다. 타임아웃과 HTTP 응답은 집계하지 않으며, HTTP 응답이 하나라도 오면 회로를 닫습니다. Codex Pool 라우팅에서 계정이 고정되지 않은 경우에만 적용되며, `codexAccountMode: "direct"` 및 계정 한정 선택자에서는 동작하지 않습니다. | +| `maxInboundBodyBytes?` | `number` | `0` | 인바운드 JSON 본문 하나의 디코딩 후 크기를 제한하는 바이트 단위 설정입니다. 생략하거나 `0`이면 기본값 256 MiB를 유지하며, 설정값은 1~512 MiB로 제한됩니다. 변경 후 다시 시작해야 합니다. 초과 시 오류 코드가 `inbound_body_too_large`인 로컬 HTTP 413을 반환합니다. 적용된 한도가 256 MiB를 넘으면 `maxConcurrentInboundBodyBytes`의 공유 게이트도 적용되며, 요청별 한도만 높여도 공유 예산이 늘지는 않습니다. 적용 대상 경로와 자세한 내용은 [인바운드 본문 수용](/ko/reference/inbound-body-admission/)을 참고하세요. | +| `maxConcurrentInboundBodyBytes?` | `number` | `536870912` (512 MiB) | 바이트 단위의 선택적 최상위 공유 수용 예산입니다. 적용된 `maxInboundBodyBytes`가 256 MiB를 넘을 때만 사용합니다. 생략하거나 `0` 또는 잘못된 값이면 종전 기본값 512 MiB를 사용합니다. 유효한 양의 정수는 실제 사용할 때 512 MiB~2 GiB (`536870912`~`2147483648`)로 제한합니다. 변경 후 다시 시작해야 하며, 같은 프로세스의 모든 리스너가 예산 하나를 공유합니다. 수용량 계산용이며 메모리 사전 할당, RSS 상한 또는 RAM에 따른 자동 조정 기능이 아닙니다. 2 GiB는 운영자가 명시적으로 선택해야 합니다. 설정 예제, 대기열 및 응답 수명에 따른 제약, 기본값으로 파싱 전 512 MiB 전체 업로드를 1건만 수용하는 이유는 [인바운드 본문 수용](/ko/reference/inbound-body-admission/)을 참고하세요. | | `modelCacheTtlMs?` | `number` | `300000` | 공급자별 `/models` 캐시의 최신성 창입니다. | | `cacheRetention?` | `"none" \| "short" \| "long"` | Anthropic 퍼스트파티: `"long"`, 그 외 Anthropic 호환 엔드포인트: `"short"` | Anthropic 프롬프트 캐시 정책입니다. 비활성, 5분짜리 임시, 1시간짜리 확장 중 하나입니다. 설정하지 않으면 `api.anthropic.com`(API 키 또는 OAuth 계정 풀) 요청은 1시간 TTL을 쓰고, 호환 게이트웨이와 벤더 엔드포인트는 5분 TTL을 유지합니다. 명시한 값이 항상 우선합니다. | | `tokenGuardian?` | `OcxTokenGuardianConfig` | 꺼짐 | 선택적 선제 OAuth 갱신과 Codex 계정 워밍업 정책입니다. | @@ -104,8 +121,9 @@ managed map을 활성화하면 privacy-safe selector를 만들고, 이후 계정 | `defaultModel?` | `string` | 이 공급자를 선택할 때 모델을 따로 지정하지 않으면 사용하는 모델입니다. | | `models?` | `string[]` | 초기/폴백 모델 목록입니다. `liveModels: false`에서 `models`가 비어 있지 않으면 `models`, `retainModels` 순으로 구성합니다. `models`가 비어 있거나 생략되면 설정된 `defaultModel`, `retainModels` 순으로 구성하고, 중복 ID는 처음 나온 항목만 남깁니다. | | `liveModels?` | `boolean` | 시작 또는 동기화 시 라이브 카탈로그를 가져옵니다. 기본값은 `true`입니다. 사용자 지정 공급자는 `${baseUrl}/models`를 사용하고, 내장은 레지스트리 URL을 사용한 뒤 필터링할 수 있습니다. | -| `selectedModels?` | `string[]` | 발견 후 카탈로그 허용 목록입니다. 값이 있으면 그 id만 허용하며, 비어 있거나 생략하면 추가 허용 목록을 적용하지 않습니다. 탐색 정책과 `disabledModels`는 계속 적용됩니다. | -| `modelDisplayNames?` | `Record` | 이 공급자의 정확한 네이티브 모델 id를 키로 쓰는 영구 표시 전용 이름입니다. 키는 대소문자를 구분합니다. 이름은 공급자 카탈로그 메타데이터보다 우선하며 인증, 어댑터, 라우팅, 청구 또는 업스트림 요청을 바꾸지 않습니다. 맵은 발견 한도와 같은 최대 2,000개 항목을 가질 수 있습니다. | +| `modelDiscovery?` | `{ skipInvalidRows?: boolean }` | `/models` 목록에 잘못된 행이 섞여 있는 게이트웨이를 위한 라이브 검색 호환 설정입니다. 기본값에서는 잘못된 행이 하나라도 있으면 목록 전체를 거부하고, 경고에 첫 번째 잘못된 행과 잘못된 행 수를 표시합니다. `skipInvalidRows: true`이면 객체가 아니거나 id가 없거나 문자열이 아니거나 비어 있거나 그 밖에 유효하지 않은 행을 건너뛰고, 건너뛴 개수만 한 번 경고합니다(행 내용은 남기지 않습니다). 응답 크기와 행 수 제한은 받은 모든 행을 셉니다. 중복 제거, 프로바이더 필터, id 접두사 제거는 남은 행에 적용됩니다. 행을 건너뛰었는데 남은 행이 없으면 빈 카탈로그로 취급하지 않고 목록을 계속 거부합니다. 같은 대상으로 저장하면서 이 필드를 빼면 유지되고, 다른 대상으로 옮기면 삭제됩니다. 새 모델 정책 상태를 저장하는 최상위 `modelDiscovery`와는 다른 설정입니다. | +| `selectedModels?` | `string[]` | 발견 후 카탈로그 허용 목록입니다. 값이 비어 있지 않으면 그 id만 노출하고, 비어 있거나 생략하면 발견된 모델을 모두 노출합니다. | +| `modelDisplayNames?` | `Record` | 이 공급자의 정확한 네이티브 모델 id를 키로 쓰는 영구 표시 전용 이름입니다. 키는 대소문자를 구분합니다. 이름은 공급자 카탈로그 메타데이터보다 우선하며 인증, 어댑터, 라우팅, 청구 또는 업스트림 요청을 바꾸지 않습니다. 단, 직접 `provider/model` 선택자가 알려진 id, 별칭, `retainModels` 어디에도 맞지 않으면(예: 라이브 목록을 아직 받지 못한 동안) 인코딩 형태가 같은 키를 네이티브 id로 보냅니다. 맵은 발견 한도와 같은 최대 2,000개 항목을 가질 수 있습니다. | | `contextWindow?` | `number` | 업스트림 메타데이터가 없을 때 쓰이는 공급자 전반의 컨텍스트 값입니다. 메타데이터가 있으면 상한으로 동작해 더 작은 라이브 값을 그대로 둡니다. Models 대시보드에서 `providerContextCaps`와 별도로 설정합니다. | | `modelContextWindows?` | `Record` | 모델별 컨텍스트 값이자 상한입니다. `contextWindow`보다 우선하며, 창 크기를 알 수 없으면 설정값을 쓰고 더 작은 라이브 메타데이터가 있으면 그쪽을 따릅니다. | | `inferContextWindow?` | `boolean` | 사용자 지정 공급자 전용이며 기본값은 꺼짐입니다. `true`이면 빠진 창을 번들 모델 메타데이터로 채웁니다. 추정값이며 중계의 실제 용량을 검증하지 않습니다. | @@ -126,7 +144,7 @@ managed map을 활성화하면 privacy-safe selector를 만들고, 이후 계정 | `modelReasoningEfforts?` | `Record` | 모델별 레이블입니다. 빈 목록이면 effort 제어를 숨깁니다. | | `modelSupportsReasoningSummaries?` | `Record` | 모델을 `false`로 두면 summary 광고를 멈추고 summary 전달 필드를 제거합니다. | | `modelReasoningSummaryDelivery?` | `Record` | 모델별 Responses 전달 enum입니다. 기존 delivery 필드를 다시 씁니다. | -| `modelAdapters?` | `Record` | 혼합 와이어 게이트웨이를 위한 모델별 `openai-chat` 또는 `openai-responses` 와이어 재정의입니다. 명시적 항목이 레지스트리 기본값보다 우선합니다. DeepSeek 프리셋은 `deepseek-v4-flash`에 네이티브 Responses를 선택할 수 있고, GitHub Copilot은 모델(`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)을 Responses 전용 기본값으로 선언합니다. 이 모델들은 에이전트 트래픽에서 `/chat/completions`를 거부하기 때문입니다. `gpt-5.4-nano`처럼 기본값이 없는 모델은 여기서 직접 옵트인할 수 있습니다. 단일 와이어 상위 항목과 정식 ChatGPT forward는 재정의를 거부합니다. | +| `modelAdapters?` | `Record` | 혼합 와이어 게이트웨이를 위한 모델별 `openai-chat` 또는 `openai-responses` 와이어 재정의입니다. 명시적 항목이 레지스트리 기본값보다 우선합니다. DeepSeek 프리셋은 `deepseek-v4-flash`에 네이티브 Responses를 선택할 수 있고, GitHub Copilot은 모델(`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)을 Responses 전용 기본값으로 선언합니다. 이 모델들은 에이전트 트래픽에서 `/chat/completions`를 거부하기 때문입니다. `gpt-5.4-nano`처럼 기본값이 없는 모델은 여기서 직접 옵트인할 수 있습니다. 단일 와이어 상위 항목과 정식 ChatGPT forward는 재정의를 거부합니다. | | xAI Responses 옵트인(대시보드) | 스위치 | `xai`에서만 `grok-4.5`와 `grok-4.6`의 `modelAdapters` 항목을 원자적으로 설정하거나 지웁니다. 한 항목만 있으면 다음 스위치 쓰기가 둘을 정규화할 때까지 혼합 상태로 표시됩니다. 다른 재정의와 티어 동작은 바뀌지 않습니다. Grok 4.7은 OAuth에서 레지스트리 와이어 기본값으로 Responses를 사용하며, 명시적 `modelAdapters["grok-4.7"] = "openai-chat"` 항목으로 Chat으로 전환할 수 있습니다. | | `xaiResponsesXSearch?` | `boolean` | 기본적으로 비활성화됩니다. xAI Responses 대상에서는 최종 요청 정규화 후에도 실제 `web_search` 도구가 남아 있을 때만 공급자가 호스팅하는 `x_search` 선언을 추가합니다. 기존 선언은 중복하지 않고, 호출자의 `tool_choice`/`allowed_tools` 선택기 범위를 확장하지 않으며, 웹 검색 사이드카의 `search.xSearch` 옵션과는 별개입니다. | | `modelPreferHostedTools?` | `Record` | hosted tool namespace를 예약하는 non-forward Responses gateway용 정확한 모델 ID opt-in입니다. 현재 `["image_generation"]`만 허용하며, 일치하는 모델은 `openai-responses` wire를 사용하고 해당 hosted tool을 지원해야 합니다. 충돌하는 클라이언트 `image_gen` 선언을 제거하고 호출자의 tool choice를 유지하도록 selector도 다시 씁니다. OpenAI API 가상 `-pro` 모델은 선택한 공개 ID를 먼저 일치시키고, 해석된 기본 wire-model ID를 대체값으로 사용합니다. `modelAdapters`는 공개 ID를 먼저, 그 다음 기본 ID를 해석하며, 두 번째 결과가 최종 wire를 결정합니다. 설정하지 않은 모델은 일반 alias 동작을 유지합니다. | @@ -141,13 +159,14 @@ managed map을 활성화하면 privacy-safe selector를 만들고, 이후 계정 | `noPenaltyModels?` | `string[]` | presence/frequency penalty를 허용하지 않는 모델입니다. 기본 `xai` 프리셋은 xAI 문서가 이 값을 거부한다고 밝힌 추론 모델(`grok-4.7`, `grok-4.6`, `grok-4.5`, `grok-4.3`, `grok-4.20-multi-agent-0309`, `grok-4.20-0309-reasoning`, `grok-build-0.1`)을 여기에 넣습니다. 추론이 없는 모델은 호출자가 보낸 penalty를 그대로 받습니다. | | `noStructuredOutputModels?` | `string[]` | `openai-chat` 엔드포인트가 `response_format`을 거부하는 정확한 모델 ID입니다. 요청 모델이 항목과 정확히 일치할 때만 필드를 생략하며, 그 외 `openai-chat` 모델에서는 structured-output 변환을 유지합니다. | | `noJsonSchemaModels?` | `string[]` | `openai-chat` 엔드포인트가 `json_schema` 형식은 거부하지만 `json_object`는 받는 정확한 모델 ID입니다. 이런 요청은 필드를 지우는 대신 `json_object`로 낮춰 보내므로, JSON을 요청한 클라이언트가 산문 대신 JSON을 받습니다. 한 모델이 두 목록에 모두 있으면 `noStructuredOutputModels`가 우선합니다. `opencode go`, `opencode zen` 프리셋이 DeepSeek 경로에 기본으로 싣습니다. | -| `foldDeveloperRoleToSystem?` | `boolean` | `openai-chat` 목적지가 `developer` 역할을 받는지 기록합니다. `foldDeveloperRoleToSystem`이 없으면 `system`, `true`이면 `system`, `false`이면 `developer`로 보냅니다. 값이 없다는 것은 이 목적지에 대해 기록된 것이 없다는 뜻이고, `true`는 상위 서비스가 역할을 거부한다는 기록, `false`는 받아들인다는 기록입니다. 어느 경우에도 메시지는 대화 안의 원래 위치를 유지하며 역할만 바뀝니다. 역할을 거부하는 목적지는 `400 role 'developer' is not allowed`로 응답해 턴이 시작조차 못 하므로, 기록이 없는 상태의 기본값을 접는 쪽으로 둡니다. | +| `foldDeveloperRoleToSystem?` | `boolean` | `openai-chat` 목적지가 `developer` 역할을 받는지 기록합니다. `foldDeveloperRoleToSystem`이 없으면 `system`, `true`이면 `system`, `false`이면 `developer`로 보냅니다. 값이 없다는 것은 이 목적지에 대해 기록된 것이 없다는 뜻이고, `true`는 상위 서비스가 역할을 거부한다는 기록, `false`는 받아들인다는 기록입니다. `singleLeadingSystemMessage`가 활성화되지 않은 경우 메시지는 대화 안의 원래 위치를 유지하며 역할만 바뀝니다. 역할을 거부하는 목적지는 `400 role 'developer' is not allowed`로 응답해 턴이 시작조차 못 하므로, 기록이 없는 상태의 기본값을 접는 쪽으로 둡니다. | | `parallelToolCalls?` | `boolean` | 병렬 도구 호출을 켜거나 끕니다. OpenAI Chat은 기본으로 켜져 있고, 비-chat 어댑터는 명시적으로 `true`일 때만 이를 노출합니다. | | `responsesItemIdRepair?` | `{ message?: string[]; reasoning?: string[]; repairMissingTerminalIds?: boolean; repairInvalidIds?: boolean }` | 기본값이 꺼진 downstream SSE 복구입니다. 정확한 자리표시자 id, 누락된 종료 id, 그리고(`repairInvalidIds`) 정규 `msg_`/`rs_` 접두사가 없는 message/reasoning id를 복구합니다. function-call id는 다시 쓰지 않습니다. 내장 DeepSeek은 마지막 두 가지를 기본으로 켭니다. | | `responsesSnapshotRepair?` | `boolean` | 기본값이 꺼진 클라이언트용 복구입니다. SSE와 JSON의 Responses 수명 주기에서 누락된 status, output, 도구 메타데이터를 채우며 raw 검사와 영속화는 변경하지 않습니다. | -| `retryOn429?` | `{ enabled?: boolean; attempts?: number; intervalMs?: number; maxIntervalMs?: number; respectRetryAfter?: boolean }` | API-key 프로바이더 전용(`authMode: "key"`). 동일 대상 429 재시도: `retryOn429`가 없으면 기능이 꺼져 있고, 객체가 있으면 `enabled: false`가 아닌 한 활성화됩니다. 429 시 대기(업스트림 `Retry-After` 또는 고정 간격) 후 키 장애 조치 전에 동일 키로 동일 요청을 재전송합니다 — 일반 텍스트 턴 복구 루프, Responses passthrough, 이미지/비디오 브리지, web-search 사이드카, 터미널 연속 요청을 모두 포함합니다. 재전송 대상은 프리스트림 HTTP 429 응답뿐이며, 커스텀 `runTurn` 전송은 HTTP 재시도 루프에서 제외됩니다. `attempts`는 첫 429 이후의 동일 키 재전송 횟수(총 전송 = `attempts` + 1)이며, 메인 복구 루프·터미널 가드 연속 요청·브리지 재시도가 공유하는 요청 단위 예산입니다. `attempts`를 모두 소진해도 동일 키 재전송만 중단되며, 이후에는 일반 키 장애 조치 또는 최종 오류 처리가 사용 가능한 대상에 따라 진행됩니다 — 키 인증 passthrough 와이어에는 장애 조치가 없으므로 소진된 429가 그대로 반환됩니다. Codex 자체는 429를 재시도하지 않으므로 단일 키 프로바이더의 유일한 방어선입니다. 기본값: `enabled: true`, `attempts: 3`, `intervalMs: 5000`, `maxIntervalMs: 60000`(단일 대기는 `maxIntervalMs`로 상한, 그 자체는 600000으로 상한), `respectRetryAfter: true`. | +| `promptCacheKey?` | `boolean` | `openai-chat` 프로바이더 전체에서 `prompt_cache_key` 전달을 켭니다. 어댑터는 받은 키만 전달하지만 Claude Messages 변환은 `metadata.user_id` 또는 메타데이터가 없을 때 모델/시스템/도구 조합에서 키를 유도할 수 있습니다. 프리셋이 선언하지 않으면 기본적으로 꺼집니다. Mistral은 [프롬프트 캐시 계약](https://docs.mistral.ai/studio/conversations/advanced/prompt-caching)에 따라 켜며 명시적 `false`로 끕니다. 엄격한 게이트웨이는 알 수 없는 필드를 HTTP 400으로 거절할 수 있으므로 업스트림이 지원을 명시할 때만 켜세요. | +| `retryOn429?` | `{ enabled?: boolean; attempts?: number; intervalMs?: number; maxIntervalMs?: number; respectRetryAfter?: boolean }` | API 키 프로바이더 전용(`authMode: "key"`). 미설정 시 꺼지지만 정식 엔드포인트의 OpenCode Go와 Command Code, 정식 Mistral `openai-chat`은 예외로 재전송 6회, 간격 10초, 상한 60초 정책을 사용합니다. 객체를 지정하면 켜지며 `enabled: false`는 이 기본 정책도 끕니다. 스트림 시작 전 HTTP 429에서 `Retry-After` 또는 고정 간격을 기다린 후 키 장애 조치 전에 동일 키로 동일 요청을 재전송합니다. 텍스트 턴 복구, Responses passthrough, 이미지/비디오 브리지, web-search 사이드카, 터미널 연속 요청을 포함하며 커스텀 `runTurn`은 제외됩니다. `attempts`는 첫 429 이후 동일 키 재전송 횟수(총 전송 = `attempts` + 1)로 요청 전체에서 공유됩니다. 소진 시 동일 키 재전송만 중단되고 일반 키 장애 조치나 최종 오류 처리가 이어집니다. 키 인증 passthrough에는 장애 조치가 없어 원래 429를 반환합니다. 정식 Mistral Chat의 명시적 대기 시간이 허용 상한을 넘으면 동일 키 재전송을 중단하고 원래 `Retry-After`를 반환하지만 풀의 다른 키가 처리할 수 있습니다. 다른 프로바이더는 대기 시간을 상한으로 제한합니다. Mistral은 자격 증명/모델별 재시도 기한을 공유하며 `requestPacing.enabled: false` 또는 `retryOn429.respectRetryAfter: false`로 끕니다. 재시도 시각이 없는 429에서 분당 예산 부족이 검증되면 보수적인 60초 복구 대기 후 한 번 탐색하고, 성공하면 일반 트래픽으로 돌아갑니다. 정상 트래픽에서는 다음 토큰 비용을 예측하지 않습니다. 공시된 허용량을 사용하고 소진된 월간 허용량은 제외하며 정확한 초기화 시각을 보장하거나 기록 압축을 유발하지 않습니다. Codex 자체는 429를 재시도하지 않습니다. 객체 기본값: `enabled: true`, `attempts: 3`, `intervalMs: 5000`, `maxIntervalMs: 60000`(대기 상한, 설정 최대 600000), `respectRetryAfter: true`. | | `transientRetryOn5xx?` | `{ enabled?: boolean; attempts?: number }` | 키 인증 `openai-chat` 및 `openai-responses` 프로바이더 전용입니다. `authMode: "forward"` 프로바이더(ChatGPT 계정 풀)는 이 옵션을 읽지 않고 기본 재시도 단계를 유지합니다. 스트림 시작 전의 일시적인 업스트림 상태(500, 502, 503, 504, 520, 521, 522)를 선택적으로 재시도합니다. 이 옵션이 없으면 꺼져 있고, 객체가 있으면 `enabled: false`가 아닌 한 활성화됩니다. 최초 Responses 요청, 터미널 가드 연속 요청, 네이티브 `/v1/chat/completions`, 429/계정 복구 재조회를 포함합니다. `attempts`는 최초 전송을 포함하여 요청 하나에 허용되는 업스트림 전송의 총횟수(1..10, 기본값 3)입니다. 연결 재설정 복구와 요청 단위 예산 하나를 공유하므로 `3`이면 실제로 프로바이더에 도달하는 요청은 최대 세 번입니다. 대기에는 400ms로 고정된 지수 백오프를 사용하고 상한은 5초이며 `Retry-After`를 따릅니다. 속도 제한을 처리하는 `retryOn429`와는 별개이며, 스트림 도중의 실패는 절대 재전송하지 않습니다. 각 Combo 대상은 선예약한 첫 전송을 해당 대상의 설정 총횟수에 포함합니다. `attempts: 1`은 한 번만 전송하며, 예약을 환불해 여유를 만들거나 공유 상한을 늘리지 않습니다. 전송 전 로컬 거부나 취소는 미사용 예약을 해제합니다. | -| `retryOnReset?` | `{ enabled?: boolean; replacements?: number }` | 네이티브 `openai-responses` 프로바이더(`authMode: "forward"` 포함)와 업스트림 헤더 수신 전의 일반 Responses 변환 전송 경로에 적용됩니다. 호출자가 아무것도 관측하지 못한 채 실패한 전송을 선택적으로 대체합니다. 이 옵션이 없으면 꺼져 있고, 객체가 있으면 `enabled: false`가 아닌 한 활성화됩니다. 응답 헤더가 오기 전에 연결이 끊어진 경우와, 헤더 이후 SSE 본문이 제어 이벤트만 실은 채 끊어진 경우를 모두 다룹니다. canonical ChatGPT 업스트림 WebSocket에서 create 프레임을 보낸 뒤 Responses 이벤트가 오기 전에 소켓이 닫히거나 오류가 난 경우도 같은 방식으로 다루며, 이때 대체 전송은 HTTP로 보냅니다. 자체 완결된 요청만 대체합니다. `store: false`, 완전한 `input`, `previous_response_id`·`conversation`·`stream_id` 없음, 클라이언트가 실행하는 도구만 해당합니다. `replacements`는 모든 구간과 모든 콤보 자식을 합쳐 논리 요청 하나가 만들 수 있는 대체 전송 횟수입니다(1..2, 기본값 1). 구간별 재시도 횟수도 전송 예산도 아니므로, 대체 전송도 해당 구간이 이미 가진 전송 허용량 안에 들어가야 합니다. 이미 출력이나 도구 호출을 내보낸 요청은 이 값과 무관하게 대체하지 않습니다. 원본 전송이 이미 시작됐다면 대체한 추론도 과금될 수 있어서 기본값은 꺼짐입니다. 일반 변환 전송 경로에서는 최초 전송과 재구축한 전송 모두 같은 대체 권한과 전송 예산으로 헤더 수신 전 연결 리셋을 대체합니다. 어댑터가 자체 관리하는 전송 경로와 업스트림 헤더 수신 후 변환 스트림 장애는 제외됩니다. | +| `retryOnReset?` | `{ enabled?: boolean; replacements?: number }` | 네이티브 `openai-responses` 프로바이더(`authMode: "forward"` 포함)와 업스트림 헤더 수신 전의 일반 Responses 변환 전송 경로에 적용됩니다. 호출자가 아무것도 관측하지 못한 채 실패한 전송을 선택적으로 대체합니다. 이 옵션이 없으면 꺼져 있고, 객체가 있으면 `enabled: false`가 아닌 한 활성화됩니다. 응답 헤더가 오기 전에 연결이 끊어진 경우와, 헤더 이후 SSE 본문이 제어 이벤트만 실은 채 끊어진 경우를 모두 다룹니다. canonical ChatGPT 업스트림 WebSocket에서 create 프레임을 보낸 뒤 Responses 이벤트가 오기 전에 소켓이 닫히거나 오류가 난 경우도 같은 방식으로 다루며, 이때 대체 전송은 HTTP로 보냅니다. 자체 완결된 요청만 대체합니다. `store: false`, 완전한 `input`, `previous_response_id`·`conversation`·`stream_id` 없음, 클라이언트가 실행하는 도구만 해당합니다. 이 프록시가 자체 재생 상태로 이미 확장한 `previous_response_id`가 있는 연쇄 턴은 전송 전에 그 ID가 제거되므로 대상이 됩니다. 리셋이 대체되지 않으면 서비스 로그에 그 이유(`ambiguous-no-policy`, `ambiguous-request-not-replayable`, `ambiguous-allowance-spent`)가 기록됩니다. `replacements`는 모든 구간과 모든 콤보 자식을 합쳐 논리 요청 하나가 만들 수 있는 대체 전송 횟수입니다(1..2, 기본값 1). 구간별 재시도 횟수도 전송 예산도 아니므로, 대체 전송도 해당 구간이 이미 가진 전송 허용량 안에 들어가야 합니다. 이미 출력이나 도구 호출을 내보낸 요청은 이 값과 무관하게 대체하지 않습니다. 원본 전송이 이미 시작됐다면 대체한 추론도 과금될 수 있어서 기본값은 꺼짐입니다. 일반 변환 전송 경로에서는 최초 전송과 재구축한 전송 모두 같은 대체 권한과 전송 예산으로 헤더 수신 전 연결 리셋을 대체합니다. 어댑터가 자체 관리하는 전송 경로와 업스트림 헤더 수신 후 변환 스트림 장애는 제외됩니다. | | `autoToolChoiceOnlyModels?` | `string[]` | `tool_choice`가 `auto` 또는 `none`만 받는 모델입니다. 강제 선택은 낮은 수준으로 바뀝니다. | | `preserveReasoningContentModels?` | `string[]` | chat 기록에서 이전 assistant `reasoning_content`가 필요한 모델입니다. 대시보드에서 저장해도 저장된 목록(`[]` 포함)은 유지됩니다. `PATCH /api/providers?name=`는 배열 또는 지우기 위한 `null`을 받습니다. 어댑터, 기본 URL, 인증 모드를 바꿔 다른 목적지로 옮기는 저장에서는 유지되지 않습니다(아래 절 참고). | | `reasoningDetailsModels?` | `string[]` | thinking을 구조화된 `reasoning_details` 배열로 반환하는 모델(`reasoning_split` 사용 MiniMax M 시리즈). 스트림 델타는 누적 스냅샷이라 prefix-diff로 처리하고, 보존된 reasoning은 `reasoning_content` 문자열 대신 `reasoning_details` 배열로 리플레이합니다. | @@ -159,35 +178,40 @@ managed map을 활성화하면 privacy-safe selector를 만들고, 이후 계정 | `anthropicEofTolerance?` | `boolean` | `message_stop` 전에 스트림이 끝나도 표시 텍스트 또는 완전한 JSON 객체 툴 입력을 받은 경우에만 완료를 허용합니다(Anthropic 호환 게이트웨이용). 기본값은 꺼짐. | | `googleMode?` | `"ai-studio" \| "vertex" \| "cloud-code-assist"` | Google 전송/인증 모드입니다. 기본값은 `ai-studio`입니다. | | `googleToolSchemaPolicy?` | `"compatible" \| "reject-lossy"` | Google 전용입니다. 생략하거나 `compatible`이면 호환 스키마와 기존 비직접 400 복구를 유지합니다. `reject-lossy`는 초기 손실 또는 판정 불가능한 상한 비교를 전송 전에 거부하고 제약을 개방하는 Vertex 또는 Cloud Code Assist 복구를 보류합니다. 직접 AI Studio는 이 복구를 수행하지 않습니다. | -| `project?` | `string` | Vertex 또는 Antigravity Cloud Code Assist 프로젝트 id입니다. Vertex API 키는 이 값이 있으면 프로젝트 엔드포인트를 쓰고, 없으면 `GOOGLE_CLOUD_PROJECT`가 설정돼 있어도 express 모드를 씁니다. ADC는 `GOOGLE_CLOUD_PROJECT` / `GCLOUD_PROJECT`로 폴백합니다. | +| `project?` | `string` | Vertex 또는 Antigravity Cloud Code Assist 프로젝트 id입니다. Vertex API 키는 이 값이 있으면 프로젝트 엔드포인트를 쓰고, 없으면 `GOOGLE_CLOUD_PROJECT`가 설정돼 있어도 express 모드를 씁니다. ADC는 `GOOGLE_CLOUD_PROJECT` / `GCLOUD_PROJECT`로 폴백합니다.`"auto"`로 설정하면 각 Vertex API 키가 자신의 프로젝트를 확인합니다(확인에 성공한 결과는 키마다 캐시하고, 확인에 실패한 키는 이후 요청에서 다시 탐색합니다). 하나의 키 풀이 여러 프로젝트에 걸칠 수 있으며, ADC는 `"auto"`를 거부합니다. | | `location?` | `string` | Vertex 위치입니다. API 키 프로젝트 엔드포인트는 기본값이 `global`이고 `GOOGLE_CLOUD_LOCATION`을 무시합니다. ADC는 이 값이나 `GOOGLE_CLOUD_LOCATION` 폴백이 필요합니다. | | `mcpServers?` | `Record` | Cursor 전용입니다. stdio 또는 Streamable HTTP MCP 서버입니다. | | `desktopExecutor?` | `DesktopExecutorConfig` | Cursor 전용입니다. 외부 computer-use 및 record-screen 명령입니다. | | `unsafeAllowNativeLocalExec?` | `boolean` | Cursor 레거시 불리언입니다. 더 새로운 필드가 설정되지 않았을 때만 `nativeLocalExec: "on"`과 같습니다. | | `nativeLocalExec?` | `"off" \| "codex-sandbox" \| "on"` | Cursor 로컬 실행 정책입니다. 기본값은 `off`입니다. `codex-sandbox`는 현재 `off`처럼 실패를 닫습니다. | +LM Studio instruction compatibility: `singleLeadingSystemMessage: true` overrides chronological Chat instruction placement by merging text-only system/developer messages into one leading system message. The LM Studio preset enables it by default; set it to `false` to disable merging. + + 공급자 등록·교체(`POST /api/providers`)는 `responsesPath`와 `chatCompletionsPath`를 검증한 뒤 메모리와 파일의 설정을 변경합니다. `PATCH /api/providers?name=`는 요청 본문을 저장된 공급자에 병합합니다. `disabled` 외의 필드를 변경하는 업데이트(`requestPacing`만 변경하는 업데이트 제외)는 저장 전에 병합된 공급자의 경로를 같은 방식으로 검증하며, 유지된 경로가 유효하지 않으면 `400`을 반환하고 설정을 변경하지 않습니다. 설정 파일을 읽을 때도 같은 경로 규칙을 적용합니다. API 키 공급자는 리터럴 키나 환경 참조를 둘 수 있습니다. OAuth 공급자는 `ocx login`으로 채워지는 자격 증명 저장소를 사용합니다. 구독 기반 Claude Code 실행 동작은 [`claudeCode.authMode`](/ko/reference/configuration/server/#claude-code-claudecode)에서 설정합니다. ### 프로바이더 저장이 유지하는 것 -기존 프로바이더 이름으로 `POST /api/providers`를 보내면 저장된 행이 요청으로 만든 행으로 바뀝니다. 대시보드의 추가/편집 폼은 모든 필드를 보낼 수 없으므로, 요청이 빠뜨린 저장 필드 일부는 저장할 때 이어서 유지됩니다. 그중 여덟 가지는 특정 업스트림의 동작을 기록한 설정입니다: `preserveReasoningContentModels`, `requiresReasoningPlaceholderModels`, `foldDeveloperRoleToSystem`, `reasoningWireFormat`, `omitReasoningEffortWithToolsModels`, `retryOn429`, `transientRetryOn5xx`, `retryOnReset`. +기존 프로바이더 이름으로 `POST /api/providers`를 보내면 저장된 행이 요청으로 만든 행으로 바뀝니다. 대시보드의 추가/편집 폼은 모든 필드를 보낼 수 없으므로, 요청이 빠뜨린 저장 필드 일부는 저장할 때 이어서 유지됩니다. 그중 열세 가지는 특정 업스트림의 동작을 기록한 설정입니다: `preserveReasoningContentModels`, `preserveResponsesReasoningContent`, `requiresReasoningPlaceholderModels`, `foldDeveloperRoleToSystem`, `singleLeadingSystemMessage`, `reasoningWireFormat`, `omitReasoningEffortWithToolsModels`, `promoteAdditionalTools`, `retryOn429`, `transientRetryOn5xx`, `retryOnReset`, `unsupportedHostedTools`, `unsupportedHostedToolsWithClientTools`. -| 저장 | 여덟 가지 설정 | 저장된 `apiKeyPool` | +| 저장 | 열세 가지 설정 | 저장된 `apiKeyPool` | | --- | --- | --- | | 같은 목적지, 필드 생략 | 저장된 값 유지(명시적인 `[]`나 `false` 포함) | 유지 | | 새 목적지, 필드 생략 | 유지하지 않음. 새 목적지의 레지스트리 기본값이 적용될 수 있음 | 유지하지 않음 | | 요청에 필드를 보냄 | 요청의 값 | 요청의 값 | -목적지는 어댑터, 기본 URL(스킴과 호스트는 대소문자를 구분하지 않고, 끝의 슬래시는 무시), 그리고 요청이 지정한 경우 인증 모드입니다. 프로바이더를 다른 목적지로 옮기면 이전 업스트림을 설명하는 여덟 가지 설정과, 그 업스트림용으로 발급된 키 풀을 가져가지 않습니다. 저장은 이전 행의 나머지를 새 행에 병합하지 않습니다. +목적지는 어댑터, 기본 URL(스킴과 호스트는 대소문자를 구분하지 않고, 끝의 슬래시는 무시), 그리고 요청이 지정한 경우 인증 모드입니다. 프로바이더를 다른 목적지로 옮기면 이전 업스트림을 설명하는 열세 가지 설정과, 그 업스트림용으로 발급된 키 풀을 가져가지 않습니다. 저장은 이전 행의 나머지를 새 행에 병합하지 않습니다. -`PATCH /api/providers?name=`는 지정한 필드만 바꾸고, 목적지와 상관없이 나머지 저장 필드는 모두 유지합니다. 여덟 가지 설정을 모두 받고, `null`로 지웁니다. 두 추론 목록에서 빈 배열은 삭제되지 않고 명시적인 옵트아웃으로 저장됩니다. +`PATCH /api/providers?name=`는 지정한 필드만 바꾸고, 목적지와 상관없이 나머지 저장 필드는 모두 유지합니다. 열세 가지 설정을 모두 받고, `null`로 지웁니다. 두 추론 목록에서 빈 배열은 삭제되지 않고 명시적인 옵트아웃으로 저장됩니다. ## 공급자 진단용 외부 요청 안전성 대시보드 연결 테스트와 라이브 모델 발견은 범위가 제한된 GET 전용 전송을 사용합니다. 아웃바운드 프록시가 없으면 opencodex는 호스트 이름을 한 번만 확인하고, 검증된 주소로만 연결합니다. HTTPS는 원래 Host, SNI, 인증서 검증을 유지하며, 공급자 설정으로 인증서 검사를 끌 수는 없습니다. +직접 응답 다운로드는 로컬 처리가 다음 데이터를 받을 준비가 될 때까지 잠시 멈춥니다. gzip과 deflate 응답에도 적용됩니다. 이 대기 시간은 공급자의 무응답 시간으로 계산하지 않으며, 요청 전체의 제한 시간과 취소는 계속 적용됩니다. + 이 작업들은 [서버에 설정된 아웃바운드 fetch](/ko/reference/configuration/server/)를 사용합니다. `config.proxy`로 설정했거나 SOCKS5 `ALL_PROXY`에서 상속된 서버 SOCKS5 프록시는 대상이 `NO_PROXY`에 걸리지 않을 때 OpenCodex의 내장 터널을 사용합니다. `HTTP_PROXY`와 `HTTPS_PROXY`는 Bun의 네이티브 HTTP(S) 처리를 그대로 사용하지만, SOCKS가 아닌 `ALL_PROXY`는 네이티브 HTTP fetch 경로가 아닙니다. URL과 리터럴 주소 검사는 계속 실행되지만, 선택된 프록시가 최종 경로, DNS 응답, 피어를 고르므로 opencodex는 그 피어를 고정하거나 검증할 수 없습니다. 이는 명시적인 보안 한계입니다. 사설/로컬 목적지는 `allowPrivateNetwork: true`가 필요하며, 아웃바운드 프록시가 활성화된 경우에는 일치하는 `NO_PROXY` 항목도 필요합니다. loopback은 자동으로 추가됩니다. CIDR 항목은 해석하지 않으므로 각 LAN 호스트는 따로 적어야 합니다. matcher는 정확한 호스트, 도메인 접미사, 선택적 포트, 괄호로 감싼 IPv6, `*`를 지원합니다. 예를 들면 `192.168.1.50`은 따로 적어야 합니다. 메타데이터와 link-local 목적지는 계속 차단됩니다. 진단 요청은 리디렉션을 거부하고, 자격 증명이 제거된 대상만 보고합니다. 일반적인 공급자 요청의 리디렉션 검토는 이 진단 가드와 별도로 유지됩니다. @@ -202,8 +226,7 @@ pool 계정 추가와 quota 갱신은 대시보드의 **Codex Auth** 페이지 구분됩니다. 바인딩된 작업은 보통 affinity를 유지합니다. 기본값(`pool.cacheAffinity`)에서는 바인딩된 계정이 소진되었거나 더 이상 처리할 수 없을 때까지 재바인딩을 미루고, 떠날 때는 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. 플래그를 끄면 `quota`가 사용량 임계값을 넘은 뒤 다음 요청에서 재바인딩할 수 있습니다. 일시 중지, cooldown, 재인증, 실패 처리도 -독립적으로 라우팅을 지우거나 바꿀 수 있습니다. 바인딩 없는 요청은 live 계정 바인딩이 없는 요청이며, 프록시 재시작이나 -affinity 초기화 뒤의 기존 작업도 포함될 수 있습니다. 출력 전 **429/402**는 사용량 기반 선제 +독립적으로 라우팅을 지우거나 바꿀 수 있습니다. 바인딩 없는 요청에는 live 계정 바인딩이 없습니다. 세션 ID가 있는 요청(일반적인 Codex CLI 및 App 턴과 서브에이전트 포함)이나 바로 위 부모에 연결된 세션 없는 요청의 바인딩은 종료 시 마지막 affinity 저장이 성공하면 프록시를 정상적으로 재시작해도 최대 24시간의 유휴 기간 동안 유지될 수 있습니다. 더 깊은 세션 없는 체인과 Codex App의 주 로그인에 대한 바인딩은 메모리에만 남으며 재시작 후 다시 배정됩니다. eviction, 계정 삭제, 재로그인, 충돌 또는 affinity 초기화로 작업이 바인딩 없는 상태가 될 수 있습니다. 출력 전 **429/402**는 사용량 기반 선제 전환이 꺼져 있어도 같은 요청에서 적격 대체 계정으로 한 번 재시도할 수 있습니다. 계정이 바뀌어도 대화 문맥은 보존·재생되지만 계정 간 프로바이더 측 prompt cache 재사용은 보장되지 않아 다시 예열해야 할 수 있습니다. @@ -218,7 +241,7 @@ affinity 초기화 뒤의 기존 작업도 포함될 수 있습니다. 출력 **배정 및 선제 전환 전략:** `quota`(기본)는 활성 계정이 없을 때 최저 usage의 적격 계정을 선택하고, 적격 활성 계정이 `autoSwitchThreshold` 미만이면 유지합니다. 임계값 도달 뒤에는 바인딩 없는 요청을 옮길 수 있습니다. 기본값에서 cache affinity가 quota 여유보다 우선하며, 바인딩된 작업은 계정이 소진되었거나(알려진 usage 100%) 처리할 수 없을 때까지 유지되고, 떠날 때는 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. usage를 모르는 계정은 바인딩된 작업의 목적지가 되지 않으며, 모든 계정이 임계값 위이면 그대로 둡니다. 플래그를 끄면 바인딩된 작업의 다음 요청도 임계값에서 옮길 수 있지만, 그때도 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 갑니다. -`round-robin`은 바인딩 없는 요청을 균등 분배하며 임계값은 기본 순환에 영향을 주지 않습니다. +`round-robin`은 카운터 기반으로 순환합니다. 새 배정은 유효 `autoSwitchThreshold`(계정별 재정의 또는 전역 기본값, `quota`와 같은 점수) 미만인 적격 계정이 있으면 임계값 이상인 계정을 건너뜁니다. 사용량을 모르거나 임계값이 `0`이면 미만으로 취급하고 모든 적격 계정이 임계값 이상이면 모두 순환합니다. 바인딩된 작업은 임계값을 넘어도 계정을 유지하며 처리할 수 없는 경우(cooldown, quota 거부, failover, pause)에만 이동합니다. live 대화의 자식은 부모가 사용하는 계정에서 시작합니다. 공통 우선순위 계층 필터도 같은 방식으로 여유를 평가합니다. 운영자의 수동 선택은 사용량과 관계없이 각 quota 범위의 다음 배정을 가져가며, 해당 범위에서 그 계정의 요청이 성공하면 선택이 소진되어 이후 배정에는 다시 임계값이 적용됩니다. `accountPoolStickyLimit`(기본 `1`, 1–100)은 성공 응답이 아니라 배정/바인딩 횟수를 셉니다. `fill-first`는 바인딩 없는 요청을 cooldown, 재인증 또는 해당 계정의 유효 drain threshold(계정별 재정의 또는 전역 기본값)까지 활성 계정에 배정하고, 정상적인 바인딩 작업은 affinity를 유지합니다. 이 전략들은 provider enforcement를 우회하지 않으며 @@ -231,9 +254,9 @@ affinity 초기화 뒤의 기존 작업도 포함될 수 있습니다. 출력 | 키 | 타입 | 기본값 | 설명 | | --- | --- | --- | --- | | `anthropicAccountPool.enabled?` | `boolean` | `false` | sticky 세션 결속과 사용량 기반 새 세션 선택을 켭니다. **429 failover는 여기서 제어되지 않습니다**: 쓸 수 있는 계정이 둘 이상이면 다른 다중 자격 증명 제공자와 똑같이 자동으로 켜지며, 끌 수 없습니다. | -| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | 새 세션에서는 활성 계정이 이 임계값에 도달하면 설정된 창의 알려진 캐시 사용량이 가장 낮은 계정을 고릅니다. `0`이면 quota 선택을 끕니다. | -| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | 새 세션 전략입니다. `quota`는 `quotaWindow`로 지정한 창(기본값은 5시간 막대)으로 계정 순위를 매기고, `fill-first`도 같은 창에서 소진 임계값을 판정합니다. | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | 사용량 기반 계정 선택에 사용하는, 공급자가 보고한 캐시 사용률 막대입니다. `five-hour`는 기존 동작을 유지합니다. `weekly`는 주간 막대를 사용하며 다른 사용 가능한 계정이 남아 있을 때만 5시간 막대가 소진된 계정을 건너뛰고, 아무 계정도 남지 않으면 해당 계정으로 폴백합니다. `max-utilization`은 알려진 값 중 가장 높은 값을 사용하므로 주간 사용량을 알기 전에도 5시간 사용량을 쓸 수 있고, 둘 다 모르면 unknown 순서를 따릅니다. 알려진 사용량은 unknown보다 앞서지만, 사용 가능한 계정이 모두 unknown이어도 사용 가능한 순서의 계정을 선택합니다. 앞서 설명한 5시간 사용량 동점 판정 뒤에도 완전히 같으면 사용 가능한 순서를 유지합니다. 정상 affinity 세션을 선제적으로 재배치하지 않습니다. 새 세션 배정과 가능한 429 대체 이후 라우팅 복구에서 `quota`는 이 창으로 사용 가능한 후보의 순위를 직접 매기고, `fill-first`는 이 창의 임계값과 소진 규칙에 따라 안정 순서로 이동하며, `round-robin`은 이 설정을 무시합니다. 쿨다운, failover 한도, 재인증 가능 여부는 별도의 로컬 상태로 유지됩니다. 계정별 주간 막대는 대시보드의 프로바이더 페이지에서 조회한 뒤에만 알 수 있습니다. | +| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | 새 세션에서 활성 계정이 이 임계값에 도달하면 설정된 창의 알려진 캐시 사용량이 가장 낮은 계정을 선택하며, 자체 임계값 미만인 계정을 우선합니다. 선택된 계정 자체가 임계값 이상일 필요는 없습니다. `0`은 사용량 기반 선제 전환만 끄며 새 세션 선택과 적격 429 이후 복구는 여전히 `quotaWindow`를 참조합니다. | +| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | 새 세션 전략입니다. `quota`는 `quotaWindow` 사용량이 유효 `autoSwitchThreshold`(기본 80)에 도달하거나 처리할 수 없을 때까지 활성 계정을 유지한 뒤 자체 임계값 미만 계정을 우선하여 사용량이 가장 적은 계정으로 이동합니다. 사용량을 모르면 활성 계정을 유지합니다. `round-robin`은 사용량 임계값을 읽지 않고 새 세션을 순환합니다. `fill-first`는 `quotaWindow`에서 소진 임계값을 평가합니다. | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | 사용량 기반 계정 선택에 사용하는, 공급자가 보고한 캐시 사용률 막대입니다. `five-hour`는 기존 동작을 유지합니다. `weekly`는 주간 막대를 사용하며 다른 사용 가능한 계정이 남아 있을 때만 5시간 막대가 소진된 계정을 건너뛰고, 아무 계정도 남지 않으면 해당 계정으로 폴백합니다. `max-utilization`은 알려진 값 중 가장 높은 값을 사용하므로 주간 사용량을 알기 전에도 5시간 사용량을 쓸 수 있고, 둘 다 모르면 unknown 순서를 따릅니다. 알려진 사용량은 unknown보다 앞서지만, 사용 가능한 계정이 모두 unknown이어도 사용 가능한 순서의 계정을 선택합니다. 앞서 설명한 5시간 사용량 동점 판정 뒤에도 완전히 같으면 사용 가능한 순서를 유지합니다. 정상 affinity 세션을 선제적으로 재배치하지 않습니다. `quota`가 대체 계정을 고를 때(활성 계정이 임계값에 도달했거나 처리할 수 없는 새 세션 또는 적격 429 이후 복구) 자체 임계값 미만 후보를 우선하고 이 창으로 순위를 매기며, `fill-first`는 이 창의 임계값과 소진 규칙에 따라 안정 순서로 이동하며, `round-robin`은 이 설정을 무시합니다. 쿨다운, failover 한도, 재인증 가능 여부는 별도의 로컬 상태로 유지됩니다. 계정별 주간 막대는 사용량 프로브나 관측된 응답 헤더에서 얻습니다. | | `anthropicAccountPool.stickyLimit?` | `number` | `1` | 성공한 새 세션 결속이 한 번의 라운드로빈 선택에 유지되는 횟수입니다. 범위는 1–100입니다. | 공유 5시간/주간 할당량의 거부가 확인된 429만 계정 쿨다운과 전환을 유발합니다. 일시적인 속도 제한은 affinity를 유지하며 해당 계정의 전송만 잠시 중지합니다. 요청마다 짧은 동일 계정 재시도 한 번과 적격한 다른 계정 전환 한 번까지만 허용됩니다. 근거 헤더가 없는 429는 동일 계정에서 한 번만 짧게 재시도하며 계정 상태를 냉각하지 않고 Retry-After를 만들어 붙이지 않습니다. 기본 단일 계정 동작은 유지됩니다. Fable 전용 거부는 Sonnet을 제한하지 않습니다. 수동 선택과 affinity도 요청 모델의 공유/계열 할당량을 확인합니다. 수동 조회가 아닌 응답 헤더의 계열 근거는 30분 또는 알려진 리셋 시각에 만료되며 요청 하나로 재확인합니다. 사용량 임계값은 소프트 선호이고 모든 후보가 소진되면 기존 폴백을 유지합니다. 사용량 또는 결제 하드 캡이 아닙니다. 결속은 프로세스 로컬이며 크기가 제한됩니다. 토큰 갱신 실패는 기존 재인증 규칙을 따릅니다. 확인된 구독 또는 계정 결제 403은 출력 전에 다른 계정으로 전환하며 `Retry-After` 또는 기본 10분 동안 냉각합니다. 일반 권한 거부는 전환하지 않습니다. 적격한 계정이 모두 쿨다운 중이면, 클라이언트는 인증 오류가 아니라 알려진 경우 `Retry-After`가 포함된 429를 받습니다. @@ -393,6 +416,12 @@ Cursor 서버 주도 로컬 도구는 기본값으로 비활성화됩니다. Cod 필드는 최상위가 아니라 `providers.cursor`에 설정하십시오. 대시보드에서는 **Providers → Cursor → Edit JSON**을 사용해 저장한 뒤 다시 시작합니다. 레거시 `unsafeAllowNativeLocalExec: true`는 `nativeLocalExec`이 설정되지 않았을 때만 `nativeLocalExec: "on"`과 같습니다. MCP, 화면 녹화, computer use는 `mcpServers`와 `desktopExecutor`가 따로 제어합니다. +네이티브 `grep`이 허용된 디렉터리 검색에서는 `glob`으로 파일을 고릅니다. `*.ts`는 모든 하위 폴더의 +파일명에 적용되고, `src/**/*.ts`는 선택한 검색 폴더를 기준으로 한 상대 경로에 적용됩니다(`./`로 시작해도 됩니다). 모든 운영체제에서 +패턴의 경로 구분자는 `/`를 사용합니다. 문자 범위와 중괄호 선택 패턴을 지원하며, Bun 1.4.4에서는 +`**/!(*.test).ts` 같은 제외 패턴과 `part-{1..3}.ts` 같은 숫자 범위도 지원합니다. +필터는 검색 폴더를 바꾸거나 네이티브 실행을 활성화하지 않습니다. + 각 `mcpServers.`는 `command`(stdio) 또는 `url`(Streamable HTTP) 중 하나를 받습니다. stdio는 `args`, `env`, `cwd`도 받습니다. HTTP는 `headers`를 받습니다. 둘 다 `enabled`(기본값 true)와 `toolPrefix`를 지원합니다. `desktopExecutor`는 `computerUseCommand`, `recordScreenCommand`, `cwd`, `env`, `timeoutMs`(기본값 `30000`)를 받습니다. 명령은 `sh -c`를 거치며 stdin에서 JSON 요청 하나를 읽고, stdout에 JSON 결과 하나를 써야 합니다. :::caution[보안] @@ -495,7 +524,9 @@ Vercel AI Gateway는 하나의 모델을 여러 기반 추론 공급자에 걸 적용된 재정의와 여전히 일치할 때만 원래 네이티브 이름을 복원합니다. 외부에서 변경된 표시 이름도 기존 네이티브 메타데이터 정규화 규칙을 따릅니다. 예를 들어 Astra (`gpt-6-astra`)는 고정된 네이티브 이름과 다른 이름을 여전히 그 고정 이름으로 교체합니다. 표시 이름 재정의는 모델 ID, 기능을 포함한 메타데이터, 정렬 순서, 라우팅된 콤보 별칭 및 계정 선택자가 붙은 항목을 바꾸지 않습니다. -이 로컬 카탈로그 재정의는 HTTP 모델 목록이나 가상 `*-pro` 항목의 이름을 바꾸지 않습니다. +`GET /api/models`도 접두사 없는 네이티브 행에 비어 있지 않은 재정의 이름을 반환하므로 클라이언트 내보내기와 `ocx opencode`가 이 이름을 사용합니다. +OpenCode는 `sol (native)`처럼 기존 접미사를 유지합니다. `ocx opencode`를 다시 실행하거나 관리형 통합을 새로 고치면 생성된 설정에 반영됩니다. +재정의가 없을 때의 이름, `/v1/models`, 가상 `*-pro` 항목은 바뀌지 않습니다. 프리뷰 GPT-5.6 폴백 항목도 같은 메커니즘을 사용합니다. OpenAI API 키 프리셋은 base와 Pro id에 컨텍스트 `1050000`, 최대 입력 `922000`을 채웁니다. OpenRouter는 `openai/gpt-5.6-sol`, `openai/gpt-5.6-terra`, `openai/gpt-5.6-luna`에 컨텍스트 `1050000`을 채웁니다. 네이티브 Pool/Direct 창은 [예약된 OpenAI 공급자 정책](/reference/configuration/providers/#reserved-openai-providers)을 따릅니다. 동기화된 카탈로그는 `xhigh`를 구분한 채 `max`를 노출합니다. diff --git a/docs-site/src/content/docs/ko/reference/configuration/routing.md b/docs-site/src/content/docs/ko/reference/configuration/routing.md index d19dce2f09..fed5f09dbf 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/routing.md +++ b/docs-site/src/content/docs/ko/reference/configuration/routing.md @@ -121,6 +121,27 @@ CLI: `ocx route policy list`, `ocx route policy show `, `ocx route policy dr CLI: `ocx logs explain `, `ocx logs rebuild-index`, `ocx logs index-status`. +### 인덱스 검사와 복구 + +기존 기록 인덱스를 처음 열면 읽기 전용 워커에서 무결성을 검사합니다. +기록 조회는 이 초기 검사를 기다리며, 프록시의 요청 처리 스레드를 막지 않습니다. +동기식 라우팅 조회는 검사 중에 busy를 반환하므로 라우팅 프로필의 +`unknownEvidence.health` 정책이 적용됩니다. 작은 인덱스를 인라인으로 재구축한 경우에는 +성공 직후 사용할 수 있으며, 워커에서 재구축한 인덱스는 게시 전에 검사를 마칩니다. + +검사나 재구축에 성공한 뒤 최소 5분이 지나면 다음 조회가 백그라운드 무결성 검사 하나를 +시작합니다. 이미 검증된 인덱스는 검사 중에도 조회할 수 있습니다. 일반 갱신은 스키마, +원본 파일 식별자와 바이트 오프셋을 확인하지만 전체 동기식 검사를 반복하지 않으며, +조회가 없는 동안에는 타이머를 실행하지 않습니다. 데이터베이스 잠금이나 워커 실행 실패 +같은 일시적인 검사 오류는 인덱스를 삭제하지 않고, 30초가 지난 뒤의 조회에서 다시 시도합니다. +초기 검증을 마치지 못한 인덱스는 그동안 사용할 수 없습니다. + +손상이 탐지되면 `usage.jsonl`에서 자동으로 재구축하며, 영향을 받은 비동기 기록·분석 +조회는 복구 후 한 번 재시도합니다. 인덱스를 닫거나 재구축할 때에는 이전 검사 결과를 +폐기하고 검사 워커가 파일을 해제한 뒤 인덱스를 교체합니다. 검사와 복구는 원본 기록을 +다시 쓰지 않습니다. 초기 검사에는 인덱스 크기에 비례하는 시간이 걸리며, +이후 백그라운드 검사는 인덱스를 사용하는 동안에만 실행됩니다. + ## 마이그레이션 `routingProfiles`는 선택적 추가 설정입니다. 기존 설정 파일과 이전 `usage.jsonl` 행은 그대로 읽힙니다. 인덱스는 일회용이며 삭제 시 다음 쿼리에서 `usage.jsonl`로 자동 재구축됩니다. 자동 튜닝은 없습니다. diff --git a/docs-site/src/content/docs/ko/reference/configuration/server.md b/docs-site/src/content/docs/ko/reference/configuration/server.md index 145679df1e..5b71745b45 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/server.md +++ b/docs-site/src/content/docs/ko/reference/configuration/server.md @@ -15,7 +15,7 @@ description: 리스너, 원격 접근, admission 키, 타임아웃, 저장소, | `emptyCompletionRetry?` | `boolean` | `false` | 텍스트나 도구 호출이 없는 Responses 턴을, 터미널 이벤트 전에 스트림이 종료된 경우를 포함해 동일한 요청으로 한 번 재시도하도록 선택합니다. 재시도에는 비용이 발생할 수 있습니다. `OCX_EMPTY_COMPLETION_RETRY=0`은 설정을 바꾸지 않고 비활성화하며, combo 및 routed-compaction turn은 제외됩니다. | | `dropCodexSafetyBuffering?` | `boolean` | `false` | Canonical Codex Responses 응답의 선택적 safety-buffering 헤더 두 개와 SSE 힌트를 제거합니다. 공급자의 안전 정책이나 거절 응답은 바뀌지 않습니다. Native WS 메타데이터와 compact는 제외됩니다. | | `stallTimeoutSec?` | `number` | `300`(public) / 비활성(local) | 스트림이 끊기기까지 유효한 업스트림 진행이 없는 시간(초, Responses 및 네이티브 Chat). 미설정 시 **로컬** 업스트림(loopback, private, `.local`/`.lan` 이름)은 비활성이 기본이고 공개 업스트림은 300초. 양수 값은 둘 다에 적용(최소 1초), `0`은 무응답 watchdog을 전면 비활성화한다. canonical ChatGPT SSE를 비스트리밍 JSON으로 접는 Responses 요청에는 이 watchdog이 꺼져도 별도의 15분 전체 상한이 남는다. `/v1/responses/compact`의 보류 바디 읽기도 이 예산을 공유하지만 로컬 업스트림에서도 기본은 300초. 명시 값(`0` 포함)이 우선한다. | -| `connectTimeoutMs?` | `number` | `200000` | 시도별 DNS/TCP/TLS/최종 헤더 기한입니다. 본문 생성 전에 끝납니다. | +| `connectTimeoutMs?` | `number` | `200000`(public) / 비활성(local) | 요청 전송부터 업스트림이 첫 응답 헤더를 반환할 때까지의 시도별 기한(DNS/TCP/TLS 및 헤더 대기). 본문 생성 전에 끝나며, 본문 스트림을 제어하는 `stallTimeoutSec`와는 무관합니다. 미설정 시 **로컬** 업스트림(loopback, private, `.local`/`.lan` 이름)은 비활성이 기본이고 공개 업스트림은 200초. 양수 값은 둘 다에 적용, `0`(또는 임의의 비양수 값)은 헤더 기한을 전면 비활성화합니다. 비활성 덕분에 로컬 모델이 큰 프롬프트에서 수 분간 prompt prefill을 해도 첫 헤더 시계가 정상 요청을 끊지 않습니다. | | `shutdownTimeoutMs?` | `number` | `5000` | 진행 중인 turn을 중단하기 전에 허용하는 정상 종료 드레인 기한입니다. | | `websockets?` | `boolean` | `false` | 클라이언트용 Responses WebSocket 경로를 광고하고 허용합니다. `false`이면 클라이언트는 HTTP/SSE를 사용하며, 적격 canonical ChatGPT 업스트림 WS 최적화는 비활성화하지 않습니다. | | `corsAllowOrigins?` | `string[]` | `[]` | CORS에서 추가로 허용할 정확한 origin입니다. 루프백 origin은 항상 허용됩니다. `chrome-extension://` 같은 authority 기반 브라우저 확장 origin을 지원하며, `*`는 와일드카드가 아닙니다. Firefox와 Safari는 확장 UUID를 (설치/브라우저 실행 때마다) 새로 만드므로 origin이 바뀌면 항목을 갱신하세요. | @@ -26,11 +26,13 @@ description: 리스너, 원격 접근, admission 키, 타임아웃, 저장소, | `serviceHealthRecovery.enabled?` | `boolean` | `false` | 백그라운드 서비스용 선택적 복구입니다. 작은 감시 프로세스가 `/healthz`를 확인하고, 프록시가 살아 있지만 연속 프로브에 약 1분 동안 전혀 응답하지 않으면 종료해 서비스 관리자(작업 스케줄러, launchd, systemd, WinSW)가 다시 시작하게 합니다. 관리되는 서비스 자식 프로세스에서만 시작되며, 멈춘 프로세스가 처리 중이던 요청은 재전송하지 않습니다. 시간당 최대 3회. 재시작이 필요합니다. 자동 복구에는 숫자 바인드 주소(또는 기본 localhost/와일드카드 매핑)가 필요합니다. DNS 바인드 이름은 모니터링하지 않습니다. 기록된 주소 또는 포트가 변경되면 모니터링이 중지됩니다. | | `codexAutoStart?` | `boolean` | `true` | Codex shim이 Codex를 실행하기 전에 `ocx ensure`를 돌리도록 허용합니다. `false`이면 ensure는 아무 작업도 하지 않습니다. | | `codexShimAutoRestore?` | `boolean` | `true` | 완료된 외부 Codex 업데이트가 설치된 shim을 교체한 뒤 복원합니다. 환경 변수로 끌 수 있습니다: `OPENCODEX_CODEX_SHIM_AUTO_RESTORE=0`. | +| `nativeMainRefresh?` | `"codex" \| "opencodex"` | auto | `CODEX_HOME`의 네이티브 메인 ChatGPT 로그인을 갱신할 주체를 고릅니다. 키링 조회 결과는 해당 조회에만 적용됩니다. 토큰이 없으면 해당 자격 증명 준비는 실패하며, 다음 조회가 같은 토큰을 반환해도 사용할 수 있습니다. 영구 거부 상태는 저장하지 않으며 이미 준비된 요청은 완료할 수 있습니다. 파일 기반 동작은 유지됩니다. 자동 선택을 포함한 전체 동작은 [Server fields(영문)](/reference/configuration/server/#server-fields)를 참조하세요. | | `syncResumeHistory?` | `boolean` | `true` | 되돌릴 수 있는 Codex App history 호환성입니다. 원래 메타데이터는 `ocx stop` / `ocx restore`가 백업하고 복원합니다. | | `shadowCallIntercept?` | `{ enabled?: boolean; model?: string; sourceModels?: string[] }` | off | 인식된 Codex 보조/섀도 호출을 요청에 설정된 reasoning effort를 유지한 채 선택한 모델로 다시 보냅니다. 기본 source prefix는 `gpt-6-luna`, `gpt-5.6-luna`입니다. 0.144.x 이하의 이전 클라이언트는 `gpt-5.4-mini`를 사용했으며 `sourceModels`로 복원할 수 있습니다. | | `webSearchSidecar?` | `OcxWebSearchSidecarConfig` | on when usable | 웹 검색 사이드카 옵션입니다. | | `visionSidecar?` | `OcxVisionSidecarConfig` | on when usable | 이미지 설명 사이드카 옵션입니다. | | `images?` | `OcxImagesConfig` | automatic OpenAI selection | Codex `image_gen`용 독립형 Images 릴레이 옵션입니다. | +| `telemetry?` | `OcxTelemetryConfig` | 사용자 고지 후 기본 켜짐 | 익명 일일 사용 텔레메트리 동의 상태(`decision`, `decidedAt`, `noticeShownAt`)입니다. 사람이 고지를 보거나 동의하기 전에는 아무것도 전송하지 않습니다. `OCX_TELEMETRY=0` 또는 `DO_NOT_TRACK=1`로 재정의할 수 있습니다. [Telemetry (`telemetry`)](#telemetry-telemetry) 및 [텔레메트리 및 개인정보](/ko/guides/telemetry/)를 참고하세요. | 오래된 개발 빌드가 백업 지원이 생기기 전에 resume-history 메타데이터를 바꿨다면, native-provider 복구를 강제로 수행하려면 `ocx recover-history --legacy-openai --yes`를 실행합니다. 이 명령은 정상적인 dedicated-provider history를 포함해 사용자 메시지가 있는 모든 `opencodex` row를 재태깅합니다. 실행하기 전에 lifecycle reference의 전체 범위 경고를 확인하세요. @@ -141,6 +143,35 @@ ssh -L 20100:localhost:10100 -L 1455:localhost:1455 you@remote 일반 `ssh -L`은 로컬 루프백에서만 수신하므로 기본 비인증 바인드에는 안전합니다. `ssh -g -L`, 광범위한 컨테이너 퍼블리싱, 또는 클라이언트 쪽을 `0.0.0.0`에 노출하는 포워딩 모드는 사용하지 마십시오. 확신이 없으면 `ssh -L 127.0.0.1:20100:localhost:10100`처럼 명시적으로 바인드합니다. ::: +## Telemetry (`telemetry`) + +익명 일일 사용 텔레메트리는 사람이 고지 안내(GUI 팝업 또는 대화형 터미널 프롬프트)를 확인한 뒤에만 기본으로 켜집니다. `config.json`의 `telemetry` 블록은 이 동의 상태를 기록합니다. + +```json +{ + "telemetry": { + "decision": "accepted", + "decidedAt": "2026-11-07T09:00:00.000Z", + "noticeShownAt": "2026-11-07T09:00:00.000Z" + } +} +``` + +| 키 | 형식 | 기본값 | 설명 | +| --- | --- | --- | --- | +| `telemetry.decision?` | `"accepted" \| "declined"` | 미설정 (미결정) | 사용자의 명시적 선택입니다. `"declined"`는 텔레메트리를 끄고 `/telemetry-id.json`을 즉시 삭제하며, `"accepted"`는 일일 보고서를 활성화합니다. | +| `telemetry.decidedAt?` | `string` (ISO 8601) | 미설정 | `decision`이 기록된 UTC 시각입니다. `decidedAt ?? noticeShownAt`의 UTC 날짜보다 strictly 이후인 완료된 UTC 달력 날짜(`day > formatUtcDay(decidedAt ?? noticeShownAt)`)만 전송하며, 동의 당일과 이전 날짜는 절대 전송하지 않습니다. | +| `telemetry.noticeShownAt?` | `string` (ISO 8601) | 미설정 | 웹 대시보드나 대화형 터미널에서 사람이 고지를 확인한 UTC 시각입니다. `decision`이 미설정일 때는 `noticeShownAt`이 있어야만 전송되며(`default-on`), 없으면 `awaiting-notice` 상태로 유지됩니다. | + +수집 서버 엔드포인트(`https://telemetry.opencodex.me/v1/events`)는 코드 상수이며 `config.json`에서 변경할 수 없습니다. + +두 환경 변수는 저장된 `config.json`을 수정하지 않고 즉시 텔레메트리를 비활성화합니다(프록시 시작 시나 스케줄러 틱에서 감지되면 `/telemetry-state.json`에 오늘 UTC 날짜를 `ineligibleThroughDay`로 기록하고 `/telemetry-id.json`을 삭제하므로, 이후 환경 변수를 제거해도 해당 날짜는 전송되지 않으며 새 ID가 생성됩니다). + +- `OCX_TELEMETRY=0` (대소문자 구분 없이 `false`, `off`, `no`도 허용) +- `DO_NOT_TRACK=1` (대소문자 구분 없이 `true`, `yes`도 허용) + +`ocx config set telemetry`와 `ocx config unset telemetry`는 거부되며, `ocx config import`도 모든 호출자에 대해 가져온 `telemetry` 블록을 무시하고 기존 동의 상태를 그대로 유지합니다. 대신 `ocx telemetry enable`(대화형 터미널 필수, 고지문과 확인 프롬프트 표시 후 기록하며 아닐 경우 `agent_consent_required` / `tty_required`로 종료), `ocx telemetry disable`, `ocx telemetry status [--json]` 또는 대시보드 **Proxy details** 토글을 사용하세요. 전체 페이로드 스키마와 보관 정책은 [텔레메트리 및 개인정보](/ko/guides/telemetry/)를 참고하세요. + ## Storage cleanup `storageCleanupPolicy`는 기본적으로 비활성화되어 있습니다. 활성화하면 아카이브된 바이트가 `trigger.archivedBytesOver`를 넘은 뒤 `startup`, `daily`, `weekly`, 또는 `manual` 시점에 실행됩니다. 가장 오래된 아카이브를 골라 `target.reduceToBytes` 또는 `target.removeOldestPercent` 방향으로 줄입니다. `mode`의 기본값은 `quarantine`이며, `permanent`는 명시적인 파괴적 선택으로만 사용합니다. 이 정책은 `lastRun`과 `nextRun`을 저장합니다. Storage 페이지에서 또는 `GET`/`PUT /api/storage/cleanup-policy`로 설정할 수 있으며, 수동 실행은 `POST /api/storage/cleanup-policy/run`으로 트리거합니다. @@ -308,3 +339,11 @@ CLI 내부 재시도·도구 턴은 요청 전체 전송 횟수 한도에 따로 압축은 유효한 잔액을 보존하며 계속할 수 있습니다. 실행 중 거부 상태는 재시작 뒤 깨끗한 저널을 읽을 때까지 남습니다. 쓰다 끊긴 마지막 JSON 줄은 기존 복구 규칙을 따릅니다. 세부 조건과 오류 코드는 [영문 원문](/reference/configuration/server/#historical-pool-continuity)을 참조하세요. + +## 로컬 업스트림 타임아웃 분류 + +로컬 분류는 타임아웃 정책이며 네트워크 접근 권한을 부여하지 않습니다. DNS 조회 없이 HTTP(S) 목적지를 분류합니다. 정확한 `localhost`(대소문자 무관, 끝의 점 허용), `0.0.0.0`, IPv4 loopback(127/8), RFC 1918 private 및 link-local(169.254/16), IPv6 loopback·link-local(fe80::/10)·unique-local(fc00::/7), IPv4-mapped 주소, `.local`/`.lan` 이름이 로컬입니다. 다른 DNS 이름은 loopback으로 해석되더라도 공개 기본값을 유지합니다. 잘못된 목적지, 지원하지 않는 스킴, `localhost.example`도 공개 기본값을 유지합니다. + +헤더 제한을 꺼도 클라이언트 취소와 상위 전체 기한은 유지됩니다. 명시적인 양수 `stallTimeoutSec`는 로컬 바디 무응답을 제한합니다. 로컬 헤더·stall 설정이 모두 없으면 헤더 이전의 자동 제한은 없습니다. 네이티브 Chat/Messages 로컬 JSON 읽기는 stall 예산을 쓰며 공개 JSON 읽기는 기존 `max(connectTimeoutMs ?? 200000, 5000)`을 유지합니다. Compact 바디의 기본 300초와 이미지/검색 사이드카 예산도 유지됩니다. + +선택 설정 `opencodeClientExport`의 `headerTimeoutMs`, `chunkTimeoutMs`, `timeoutMs`는 양수 밀리초 또는 비활성화 값 `false`를 받습니다. 생략 시 OpenCode 기본값을 유지하고 잘못된 필드는 내보내지 않습니다. V1 options와 V2 settings의 provider 전체에 적용됩니다. [느린 로컬 모델](/guides/opencode/#slow-local-models-prefill-timeouts)을 참고하세요. diff --git a/docs-site/src/content/docs/ko/reference/inbound-body-admission.md b/docs-site/src/content/docs/ko/reference/inbound-body-admission.md index ec9d5f5f4a..45ccb681fd 100644 --- a/docs-site/src/content/docs/ko/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/ko/reference/inbound-body-admission.md @@ -5,22 +5,55 @@ description: 요청 본문 한도를 높였을 때 동시 HTTP 요청, 재시도 [프로바이더 설정 레퍼런스](/ko/reference/configuration/providers/)의 `maxInboundBodyBytes`는 인바운드 JSON 본문 하나의 디코딩 후 최대 크기를 설명합니다. 기본값은 계속 256 MiB이며, 설정 가능한 값은 1 MiB에서 512 MiB 사이입니다. 한도를 바꾼 뒤에는 리스너와 리더가 같은 한도를 사용하도록 프록시를 다시 시작하세요. +종전 공유 예산 기본값인 512 MiB를 유지해도 아래에서 설명하는 대기열과 응답 수명 동안의 예약 유지에 따른 제약은 남습니다. + +## 공유 예산을 명시적으로 선택하기 + +`maxConcurrentInboundBodyBytes`는 바이트 단위로 지정하는 `config.json`의 선택적 **최상위** 설정입니다. 기본값은 종전과 같은 **512 MiB (`536870912`)**입니다. 생략하거나 `0` 또는 잘못된 값을 지정하면 이 기본값을 사용합니다. 유효한 양의 정수는 실제 사용할 때 **512 MiB~2 GiB (`536870912`~`2147483648`)** 범위로 제한합니다. 설정을 바꾼 뒤에는 프록시를 다시 시작하세요. 같은 프로세스의 모든 리스너가 예산 하나를 공유하며, `appOwnedMemoryBudgetMb`와는 별개입니다. + +요청별 한도를 512 MiB로 정하고 공유 예산을 2 GiB로 명시적으로 늘리려면, 다음 필드를 기존 `config.json`의 최상위에 추가한 뒤 다시 시작하세요. + +```json +{ + "maxInboundBodyBytes": 536870912, + "maxConcurrentInboundBodyBytes": 2147483648 +} +``` + +이 설정은 순간 최대 메모리 사용량이 커질 수 있음을 고려한 운영자의 선택입니다. 프록시는 사용 가능한 RAM을 자동으로 감지하거나 그에 맞춰 예산을 정하지 않습니다. + ## 한도를 높이면 동시 처리량이 달라집니다 -적용된 한도가 256 MiB를 넘으면 해당 HTTP 요청마다 설정된 허용량 전체를 프로세스 전체가 공유하는 512 MiB 수용 예산에서 예약합니다. 따라서 여러 리스너가 한 프로세스를 공유하더라도 한 번에 요청 하나만 실행할 수 있습니다. 본문이 작아도 허용량 전체를 예약하며, 작은 Content-Length 값이나 압축으로 수용 검사를 우회할 수 없습니다. 예약은 요청 JSON 파싱 직후가 아니라 응답 스트림이 끝나거나 실패하거나 취소가 마무리될 때까지 유지됩니다. +적용된 한도가 256 MiB를 넘으면 해당 HTTP 요청은 **본문을 읽기 전에** 적용된 요청별 허용량 전체를 예약해야 합니다. 예약은 프로세스 전체의 `maxConcurrentInboundBodyBytes` 예산을 공유하며, 기본값은 계속 **512 MiB**입니다. + +크기를 제한하면서 JSON 파싱을 완료하기 전까지는 `Content-Length`가 작거나 압축된 전송 본문이 작아도 예약량을 줄이지 않습니다. 이 값들만으로 디코딩 후 크기나 정규화된 JSON 크기를 판단하지 않습니다. + +제한된 크기 안에서 JSON 파싱에 성공하면 리더는 실제 전송 바이트 수와 디코딩 후 바이트 수 중 큰 값으로 예약량을 줄입니다. 변환기가 정규화된 JSON 측정에 쓸 예산을 제공한 경우에는 기존 정규화 JSON 측정값까지 포함해 가장 큰 값을 사용합니다. 예약량은 처음 예약한 허용량 범위 안에서 줄어들기만 하며, 정규화 측정값이 그보다 커도 늘어나지 않습니다. 기존 UTF-8 및 JSON 재직렬화 검사는 유지되며, 입력 바이트 길이로 더 클 수 있는 정규화 JSON 크기를 대신하지 않습니다. + +**기본 공유 예산 512 MiB**와 **요청별 한도 512 MiB**를 사용하면, 아직 파싱하지 않은 업로드는 **1건만** 허용량 전체를 예약할 수 있습니다. 파싱 후 예약량이 **1바이트**까지 줄어도 남는 용량은 512 MiB보다 작습니다. 따라서 충분한 용량이 반환될 때까지 다음 요청은 512 MiB 전체를 예약할 수 없습니다. 기본값만으로는 요청별 한도가 512 MiB일 때의 원래 동시 처리 문제를 **해결하지 못합니다**. + +`maxConcurrentInboundBodyBytes`를 `2147483648`로 명시하면 **2 GiB**를 선택하며, 파싱 및 측정에 따른 예약량 축소 전에도 **512 MiB 전체를 예약하는 업로드를 최대 4건** 수용할 수 있습니다. 이 2 GiB 예산이 파싱 후까지 동시 요청 수를 4건으로 고정하지는 않습니다. 예를 들어 먼저 파싱된 요청의 예약량이 줄어 다음 요청을 수용할 여유가 생기면, 공유 예산과 다른 제한 안에서 **아주 작은 요청 8건도 동시에 응답을 스트리밍**할 수 있습니다. + +줄어든 예약량은 비동기 작업과 프로바이더 응답 대기 중에도 유지되며, 응답 스트림의 끝(EOF), 오류 또는 취소 완료 시점에 해제됩니다. 파싱만 끝났다고 해제하지 않습니다. 클라이언트 연결이 끊겨도 응답 생산자의 취소 처리가 끝날 때까지 유지합니다. 오류·요청 중단·취소가 겹치더라도 해제는 정확히 한 번만 일어납니다. 적용 대상 POST 엔드포인트는 `/v1/responses`, `/v1/responses/compact`, `/v1/chat/completions`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/images/generations`, `/v1/images/edits`, `/v1/alpha/search`입니다. 이미지, 검색, 토큰 계산에는 기존의 설정 가능한 본문별 한도가 계속 적용됩니다. 내부 직접 변환 호출과 콤보 호출은 HTTP 허용량을 두 번 예약하지 않습니다. 관리 API, 오디오, 컨텍스트 기록, WebSocket의 한도는 그대로입니다. -설정을 생략하거나 0으로 두거나 적용된 한도가 256 MiB 이하라면 이 추가 동시 처리 게이트는 켜지지 않습니다. 기존 요청 수 제한과 다른 자원 제한은 계속 적용됩니다. +이 추가 동시 처리 게이트는 적용된 `maxInboundBodyBytes`가 256 MiB를 넘을 때만 켜집니다. 이 요청별 설정을 생략하거나 `0`으로 두면 기본값인 256 MiB가 유지되어 게이트가 꺼져 있습니다. 반면 `maxConcurrentInboundBodyBytes`를 생략하거나 `0`으로 두면 공유 기본값인 512 MiB를 선택하며, 이미 켜진 게이트를 끄지는 않습니다. 기존 요청 수 제한과 다른 자원 제한은 계속 적용됩니다. ## 일시적인 거부와 크기 초과 본문의 차이 -허용량을 일시적으로 사용할 수 없으면 프로토콜 파싱이나 프로바이더 호출 전에 HTTP **503**, `Retry-After: 1`, 오류 코드 `server_busy`를 반환합니다. Messages 및 토큰 계산 클라이언트에는 유형이 `overloaded_error`인 Anthropic 형식 오류를, OpenAI 호환 클라이언트에는 `server_error`를 반환합니다. 재시도 헤더와 클라이언트의 백오프를 지키면서 현재 요청이 끝난 뒤 다시 시도하세요. 본문 한도를 더 높여도 허용량 부족은 해결되지 않습니다. +허용량 전체를 바로 예약할 수 없으면 **최대 32건의 요청이 FIFO 대기열**에서 **최대 120초** 기다릴 수 있습니다. 대기 중에는 애플리케이션이 요청 본문을 읽지 않습니다. 측정 후 예약량이 줄거나 요청이 끝나 예산이 반환되면 대기 순서대로 요청을 수용합니다. 대기 중 요청이 중단되면 대기열에서 제거하고, 읽지 않은 본문을 소비하지 않고 취소합니다. -요청별 한도보다 큰 본문은 기존 HTTP **413** 처리 경로를 따릅니다. 선언된 크기가 한도를 넘는 경우에도 일시적 거부가 아니라 그 경로를 사용합니다. 연결이 끊기면 기존 취소 동작을 유지합니다. 인증과 출처 검사는 이 동시 처리 게이트보다 먼저 실행됩니다. +대기열이 가득 찼거나 대기 시간이 만료되면 본문 파싱이나 프로바이더 호출 전에 HTTP **503**, `Retry-After: 1`, 오류 코드 `server_busy`를 반환하고, 읽지 않은 본문을 취소합니다. Messages 및 토큰 계산 클라이언트에는 유형이 `overloaded_error`인 Anthropic 형식 오류를, OpenAI 호환 클라이언트에는 `server_error`를 반환합니다. 인증과 출처 검사는 예약 및 대기열 진입보다 먼저 실행됩니다. + +재시도할 때는 재시도 헤더와 클라이언트의 백오프를 지키세요. 대기열과 파싱 후 예약량 조정은 불필요한 용량 부족 거부를 줄이지만 모든 503을 없애지는 않습니다. 요청별 본문 한도를 더 높여도 지속적인 용량 부족은 해결되지 않습니다. + +요청별 한도보다 큰 본문은 기존 HTTP **413** 처리 경로를 따릅니다. 선언된 크기가 한도를 넘는 경우에도 일시적 거부가 아니라 그 경로를 사용합니다. ## 예산이 측정하는 것 -512 MiB는 수용된 요청별 허용량의 합계이며, **프로세스 메모리가 512 MiB 아래로 유지된다는 보장은 아닙니다**. 디코딩, 문자열, 객체 그래프, 요청 사본, 기타 애플리케이션 상태에 추가 메모리가 듭니다. 기존 UTF-8 및 다시 직렬화한 JSON의 측정 방식은 유지됩니다. 입력 바이트 길이로 더 클 수 있는 정규화된 JSON 크기를 대신하지 않습니다. +설정된 예산은 요청을 수용하기 위한 계산 예산입니다. 파싱 전에는 허용량 전체를, 파싱 후에는 측정된 예약량을 합산합니다. **2 GiB나 설정된 용량을 미리 할당하지 않으며**, **프로세스 RSS나 파싱된 객체의 힙 크기 상한도 아닙니다**. 디코딩, 문자열, 객체 그래프, 요청 사본, 기타 애플리케이션 상태에 추가 메모리가 들어 실제 메모리 사용량은 예산을 넘을 수 있습니다. + +공유 기본값인 512 MiB 대신 2 GiB를 선택하면 예약 가능한 총량이 4배가 됩니다. 요청별 한도가 512 MiB일 때 이 명시적 선택으로 파싱 전 전체 업로드를 1건 대신 최대 4건 수용하므로, 순간 최대 메모리 사용량이 더 커질 수 있습니다. 배포 환경의 여유 메모리를 고려해 예산을 선택하세요. 요청별 한도가 256 MiB 이하라면 공유 예산 설정과 관계없이 이 추가 게이트가 꺼져 있습니다. -작은 요청을 병렬로 처리한다면 가능한 한 기본 한도를 유지하세요. 긴 기록이 필요한 워크플로에서는 추가 동시 처리 제한을 감수하고 한도를 높이세요. +가능한 한 요청별 기본 한도를 유지하세요. 긴 기록이 필요한 워크플로에서 한도를 높일 때는 커질 수 있는 순간 최대 메모리 사용량과 대기열의 한도도 함께 고려하세요. diff --git a/docs-site/src/content/docs/ko/reference/management-api.md b/docs-site/src/content/docs/ko/reference/management-api.md index ae9420f811..256415a052 100644 --- a/docs-site/src/content/docs/ko/reference/management-api.md +++ b/docs-site/src/content/docs/ko/reference/management-api.md @@ -255,16 +255,20 @@ Aside 프로필 변경은 이때도 한 가지를 저장합니다. 확인을 보 | `GET /api/oauth/status` | 하나의 provider OAuth 흐름을 조회합니다 | 400 알 수 없는 provider | | `POST /api/oauth/logout` | 선택된 provider 자격 증명을 제거합니다 | 400 알 수 없는 provider; `oauth_mutation_busy` | | `GET, DELETE /api/oauth/accounts` | 마스킹된 계정을 나열하거나 계정 하나를 제거합니다 Kiro 행에는 자동 선택 가능 여부인 `autoSelectable`과 제외 시 닫힌 집합의 `skipReason`이 포함됩니다. 활성 단일 계정은 여전히 요청을 보낼 수 있고 quota 조회는 선택 사항입니다. | 400 잘못된 provider/id; 404 계정 없음; `oauth_mutation_busy` | -| `PUT /api/oauth/accounts/active` | 활성 OAuth 계정을 선택합니다 | 400 잘못된 provider/account; `oauth_mutation_busy` | +| `PUT /api/oauth/accounts/active` | 활성 OAuth 계정을 선택합니다 | 400 잘못된 provider/account; `oauth_mutation_busy`; 503 `affinity_reset_not_persisted` (Anthropic: `selectionCommitted: true`, `retryable: true`; 계정 선택은 저장됨; 이미 활성 상태여도 동일 요청을 재전송) | | `GET, PUT, PATCH /api/pool/settings` | 모든 pool 종류(codex, anthropic, generic)의 policy를 읽거나 업데이트합니다. 세 종류 모두 같은 키로 응답하고, 해당 종류가 실제로 적용하는 필드는 `supported`에 나옵니다 | 400 알 수 없는 provider, 해당 종류가 지원하지 않는 필드, 잘못된 값 | | `GET, PUT, PATCH /api/oauth/accounts/pool` | Anthropic과 일반 OAuth provider의 기존 pool policy입니다. `/api/pool/settings`로 대체되었고 기존 클라이언트를 위해 유지합니다 | 400 codex 또는 API 키 provider, 잘못된 policy | | `POST /api/oauth/accounts/clear-cooldown` | OAuth 계정 하나의 런타임 cooldown을 지웁니다 | 400 잘못된 provider/account | | `PUT /api/oauth/accounts/alias` | OAuth 계정 alias를 설정하거나 지웁니다 | 400 잘못된 provider/account/alias | -| `PUT /api/oauth/accounts/pause` | Anthropic 또는 일반 OAuth 계정을 정지·재개합니다. Body `{ provider, accountId, paused }`. 활성 계정을 정지하면 사용 가능한 다른 계정이 있을 때 전환합니다. | 400 지원하지 않는 provider 또는 잘못된 body; 404 계정 없음; `oauth_mutation_busy` | +| `PUT /api/oauth/accounts/pause` | Anthropic 또는 일반 OAuth 계정을 정지·재개합니다. Body `{ provider, accountId, paused }`. 활성 계정을 정지하면 사용 가능한 다른 계정이 있을 때 전환합니다. | 400 지원하지 않는 provider 또는 잘못된 body; 404 계정 없음; `oauth_mutation_busy`; 503 `affinity_reset_not_persisted` (Anthropic: `pauseCommitted: true`, `retryable: true`; 일시정지 상태는 저장됨; 계정과 정지 상태를 유지하고 `retryAffinityReset: true`를 추가해 재시도하면 서버 재시작 후에도 초기화를 확인) | | `GET, POST, DELETE /api/providers/keys` | 마스킹된 provider key를 나열, 추가/활성화, 또는 제거합니다 | 400 잘못된 입력; 404 provider/key 없음 | | `PUT /api/providers/keys/active` | provider의 활성 key를 선택합니다 | 400 잘못된 입력; 404 provider/key 없음 | | `PUT /api/providers/keys/alias` | provider-key alias를 설정하거나 지웁니다 | 400 잘못된 입력; 404 provider/key 없음 | +| `PUT /api/providers/keys/pause` | provider API key 하나를 일시 중지하거나 재개합니다. Body `{ name, id, paused }`. 활성 key를 일시 중지하면 ring order에서 다음 사용 가능한 key를 선택합니다. 성공 응답에는 결과 `activeAccountId`(없으면 `null`)와 `activeAccountChanged`가 포함됩니다. | 400 잘못된 입력; 404 provider/key 없음 | | `GET, POST, PATCH, DELETE /api/keys` | 데이터 평면 admission key를 나열, 생성, 수정, 또는 삭제합니다 | 400 잘못된 본문/id; 404 key 없음 | +| `PUT /api/oauth/accounts/affinity-reset` | 계정 없이 provider 전체의 대화 연결 초기화 저장을 확인합니다. Body `{ provider }`; 성공 시 `affinityResetConfirmed: true`. CLI: `ocx account reset-affinity anthropic --json` (`anthropic2` supported). | 400 invalid body/provider; 503 `affinity_reset_not_persisted`, `retryable: true` | + +대시보드는 저장된 계정이 사라져도 초기화 저장이 확인되기 전에는 경고를 보존합니다. 목록 로드 실패나 활성 계정의 일시정지·재인증 상태에서도 안내와 재시도를 유지합니다. 로드된 목록에서 계정 부재가 확인되면 재시도는 `{ provider }`로 `PUT /api/oauth/accounts/affinity-reset`을 호출하고, `affinityResetConfirmed: true`를 받아야 경고를 지웁니다. 이 작업은 최초 실패 이후 생성된 연결까지 모두 지우지만 계정을 선택·재개하지 않으며 빈 목록에서도 가능합니다. 초기화가 남은 상태의 계정 삭제는 `retryAffinityReset=true`를 보내고, 게시 실패 시 503 `affinity_reset_not_persisted`, `deletionCommitted: true`, `retryable: true`를 반환합니다. 계정은 이미 삭제됐으므로 삭제 대신 초기화 전용 API를 재시도하세요. 일반 삭제는 남은 계정의 연결을 보존합니다. 초기화 전용 정리는 등록된 Anthropic OAuth 인스턴스만 지원하며 기존 관리 인증·출처 검사를 유지합니다. 자격 증명 목록 응답은 의도적으로 마스킹됩니다. OAuth access token과 완전한 provider API key는 대시보드 클라이언트에 반환되지 않습니다. diff --git a/docs-site/src/content/docs/ko/reference/proxy-formats.md b/docs-site/src/content/docs/ko/reference/proxy-formats.md index 03ae6b806c..77ed94107a 100644 --- a/docs-site/src/content/docs/ko/reference/proxy-formats.md +++ b/docs-site/src/content/docs/ko/reference/proxy-formats.md @@ -197,6 +197,13 @@ choice, 이미지, reasoning effort, 지원되는 response format을 변환한 SSE 객체, choice delta, `finish_reason`이 있는 종료 choice, `data: [DONE]`을 사용합니다. tool-call과 usage 정보는 원본 이벤트가 그것들을 담고 있을 때 다시 변환됩니다. +이 엔드포인트의 오류 응답과 스트리밍 오류 프레임은 프록시가 작성한 메시지를 사용합니다. 프록시는 +provider 실패를 속도 제한, 할당량 또는 크레딧 소진, 컨텍스트 창 초과, 모델 사용 불가, 지원되지 않는 위치, +계정 인증 필요 같은 고정된 상태로 분류하고 그 상태의 고정 메시지를 반환합니다. 정책 거부, 재전송 거부, +프록시 한도에는 각각 고정 메시지가 있습니다. HTTP 상태, `error.type`, `error.code`, `Retry-After`의 의미는 +그대로이므로 `context_length_exceeded`, `insufficient_quota`, `rate_limit_exceeded` 같은 코드로 분기하는 +클라이언트는 이전과 같이 동작합니다. + 내부 실행 경로가 Responses 기반이기 때문에 provider adapter는 더 좁은 기능 집합을 강제할 수 있습니다. 예를 들어 선택된 adapter로 표현할 수 없는 요청 기능은 의미를 바꾸지 않고 오류로 반환됩니다. @@ -294,12 +301,17 @@ call creation 이후 클라이언트는 다음의 지원되는 모든 inbound 프록시는 업스트림 join URL을 정규화한 뒤, 양방향 텍스트 및 바이너리 프레임을 투명하게 릴레이합니다. 업스트림 인증은 프록시가 소유한 상태로 유지되며, 클라이언트 프로토콜 헤더는 보존됩니다. +sideband 연결을 종료할 때 프록시는 업스트림의 정상 종료를 1초 동안 기다린 뒤, 응답하지 않는 +전송 연결을 강제로 닫습니다. 클라이언트 업그레이드가 실패한 경우에도 실제 업스트림 연결이 +닫힌 것을 확인한 후에만 해당 계정의 활성 통화 용량을 반환합니다. + call creation과 sideband join은 같은 OpenAI 계정으로 이루어져야 하며, 그렇지 않으면 업스트림이 join을 거부합니다(`404`). 두 요청 모두 Codex의 `session-id`와 `thread-id` 헤더를 실어 보냅니다. Pool 모드는 계정 선택을 그 쌍에 묶어 두므로(프로세스 로컬) 프록시에 도착한 join은 통화를 만든 계정을 그대로 쓰고, Direct 모드는 두 요청 모두 호출자의 현재 bearer를 전달합니다. 릴레이되는 클라이언트 헤더는 정확히 `openai-alpha`, `x-session-id`, `session-id`, `thread-id`, `originator`, `x-oai-attestation`, -`x-codex-turn-metadata`(`src/server/live.ts`의 `LIVE_CLIENT_PROTOCOL_HEADERS`)이며, 각 헤더는 +`x-codex-turn-metadata`, `voice-session-id`(실시간 `x-session-id`와 별개인 클라이언트 음성 세션 id) +(`src/server/live.ts`의 `LIVE_CLIENT_PROTOCOL_HEADERS`)이며, 각 헤더는 호출자가 보낸 경우에만 전달되고 프록시가 만들어 내지 않습니다. `Authorization`과 ChatGPT 계정 id는 ChatGPT 경로에서 프록시가 소유합니다(Pool은 저장된 계정으로 교체, Direct는 검증된 호출자 bearer를 전달). API 키 프로바이더는 자체 bearer를 씁니다. Codex가 join을 프록시로 보내는 것은 @@ -308,6 +320,8 @@ API 키 프로바이더는 자체 bearer를 씁니다. Codex가 join을 프록 ## `POST /v1/responses/compact` +compact 요청에 잘못된 OpenCodex 소유 retained-compaction 입력(`ocx2:`)이 있으면 HTTP 400(`error.type: "invalid_request_error"`)을 반환합니다. 검증 시점과 계정에 미치는 영향은 [영문 기준 문서](/reference/proxy-formats/#post-v1responsescompact)를 참조하세요. + Compaction은 긴 Responses 대화를 줄여야 하는 클라이언트를 위해 대체 히스토리를 반환합니다. | 경로 유형 | 동작 | diff --git a/docs-site/src/content/docs/ko/troubleshooting/windows-memory.md b/docs-site/src/content/docs/ko/troubleshooting/windows-memory.md index 1534ef83f4..2e0396dff3 100644 --- a/docs-site/src/content/docs/ko/troubleshooting/windows-memory.md +++ b/docs-site/src/content/docs/ko/troubleshooting/windows-memory.md @@ -44,4 +44,4 @@ Windows에서는 opencodex가 #32111 충돌을 피하기 위해 스트리밍 응 Windows 서비스 설치·복구와 Codex shim 설치·갱신은 선택한 실행 파일이 OpenCodex 설정 루트 안에 디렉터리를 만들고 제거할 수 있는지 검사합니다. 메모리 수정이 아닌 쓰기 정책 검사입니다. 실패하면 서비스 중지, 다운로드, 스테이징, 토큰·실행 파일 쓰기 전에 거부합니다. shim 자동 복구는 안내와 함께 지연되며 시작은 계속됩니다. 정상 상태 또는 비활성화된 shim은 검사하지 않습니다. 다른 런타임을 자동으로 찾지 않습니다. 처음 하는 스케줄러 설치는 이 검사 전에 작업을 등록하고 설정 루트를 확보합니다. 거부되면 새 등록은 되돌리고, 확보한 루트는 재시도를 위해 남겨 둡니다. -> 선택한 Bun 런타임이 OpenCodex 설정 디렉터리 안에 디렉터리를 만들고 제거하지 못했습니다. Windows 애플리케이션 정책이 이 실행 파일 위치의 쓰기를 차단할 수 있습니다. `ocx` 실행 전에 정책이 허용하는 신뢰할 수 있는 Bun 실행 파일로 `OPENCODEX_BUN_PATH`를 설정하거나, `npm install -g @bitkyc08/opencodex`로 다시 설치한 뒤 재시도하세요. 다른 런타임은 선택하지 않았습니다. +> 선택한 Bun 런타임이 OpenCodex 설정 디렉터리 안에 디렉터리를 만들고 제거하지 못했습니다. Windows 애플리케이션 정책이 이 실행 파일 위치의 쓰기를 차단할 수 있습니다. `ocx` 실행 전에 정책이 허용하는 신뢰할 수 있는 Bun 실행 파일로 `OPENCODEX_BUN_PATH`를 설정하거나, `npm install -g --allow-scripts=bun @bitkyc08/opencodex`로 다시 설치한 뒤 재시도하세요. 다른 런타임은 선택하지 않았습니다. diff --git a/docs-site/src/content/docs/reference/adapters.md b/docs-site/src/content/docs/reference/adapters.md index 435e83f1a9..14f420d27a 100644 --- a/docs-site/src/content/docs/reference/adapters.md +++ b/docs-site/src/content/docs/reference/adapters.md @@ -23,6 +23,13 @@ adapter own retries/timeouts, while `runTurn` supports transports that cannot be HTTP fetch followed by one response stream. [`bridge.ts`](/reference/architecture/#the-bridge) then turns the events into Responses SSE. +## Shared tool argument repair + +The bridge repairs integral floats in integer fields and safe bare integers in string-only +fields against the tool's schema. Unsafe integers, overflowing numbers and unrepaired non-integral +decimals retain their exact tokens while safe siblings are still repaired. Nested arrays and duplicate keys retain every +unsafe token, so repairing a timeout cannot silently change an unrelated identifier. + ## External task input on translated Responses routes Codex task coordination can deliver input as `function_call_output` with nonblank @@ -82,6 +89,18 @@ transport; it does not infer subscription attribution from the inbound protocol. Adjacent text blocks share inline-tag parsing; typed thinking resets it. Unsupported or malformed array blocks return an upstream error. Other hosts keep their existing behavior. This does not add Mistral signature replay. +- Canonical key-auth Mistral Chat (`https://api.mistral.ai/v1`) maps `max_completion_tokens` to + `max_tokens` while keeping an explicit non-null `max_tokens`, and drops `user`, `store`, `thinking`, + `include_reasoning`, `reasoning` and `top_k`. Its preset folds developer messages to system by + default; an explicit `foldDeveloperRoleToSystem: false` overrides this. Native Chat also follows + the configured model effort ladder: an unsupported `medium` becomes `low` for the bundled + DeepSeek/GLM ladders. Mistral Large 4 keeps its supported `medium` rung. +- On that canonical destination, native Chat responses normalize typed arrays in both SSE deltas + and JSON messages: text becomes string `content`, thinking becomes `reasoning_content`. + OpenAI-compatible clients receive strings rather than rendering array objects as `[object Object]`. +- Schema-validation 4xx errors retain a bounded list of recognized field names and error types in + Logs failure details. Upstream messages, submitted values and unknown location keys are omitted; + the client-facing error message policy is unchanged. - Suppresses bare `` text when it duplicates a structured call, and collapses two immediately adjacent identical blocks when exactly one structured call agrees with their function and input. A doubled `input` is reduced to one copy, joined either directly or by one newline, @@ -169,13 +188,49 @@ API, the adapter removes item-level `extra_content` from the outgoing HTTP reque create. Native `/responses/compact` applies the same projection. The original history keeps the Google thought signature for later Google turns. Other Responses gateways retain their extensions. +OpenAI-operated destinations receive replayed `url_citation` annotations with missing or invalid +titles and indices repaired. This applies to ordinary HTTP/WebSocket requests and native +`/responses/compact`. Custom gateways keep the original annotations even when +`supportsNativeCompactEndpoint: true` enables native compaction. Citation repair leaves the +client's stored history unchanged. + The adapter preserves the incoming client's `User-Agent` as a fallback in both auth modes because some Responses-compatible providers use the Codex client fingerprint for compatibility behavior. An explicitly configured provider `User-Agent` remains authoritative regardless of header casing; if the caller sends none, OpenCodex does not invent one. Additional caller metadata can be selected with `forwardClientHeaders`; provider `headers` win for this option, and credential or transport-owned names are refused. Canonical ChatGPT forward auth retains its separate fixed header allowlist. -Only `originator`, `x-client-request-id`, `x-codex-app-version`, and `user-agent` are supported by `forwardClientHeaders`; arbitrary names are rejected on load/write and ignored at runtime. +Only `originator`, `x-client-request-id`, `x-codex-app-version`, `user-agent`, +`x-codex-window-id`, and `x-codex-installation-id` are supported by `forwardClientHeaders`; +arbitrary names and wildcard prefixes are rejected on load/write and ignored at runtime. + +For a custom gateway that requires original Codex client metadata (for example, a sub2api +account with `codex_cli_only` enabled), select only the fields its operator requires. +If it requires the caller's window identifier, opt in on that provider: + +```json +{ + "forwardClientHeaders": [ + "originator", "user-agent", "x-codex-app-version", "x-client-request-id", + "x-codex-window-id" + ] +} +``` + +This preserves only values the client actually sends, including across native compact fallback. +WebSocket clients retain their original `User-Agent` and app-version metadata through the +handshake, with the same provider forwarding policy as HTTP clients. +Responses authentication preparation preserves that permitted metadata before the final +provider transport applies its header policy, for both HTTP and WebSocket turns. +Both identifier headers are off by default on custom providers and require separate selection. +Add `x-codex-installation-id` only when the trusted destination also requires it: an installation +identifier can correlate requests across sessions. Selecting a window identifier does not enable +the installation identifier. Removing a name stops this option copying it on subsequent requests; +it does not erase identifiers already received by the destination. Provider `headers` remain +authoritative, and this option does not filter identifiers already present in the request body. +Missing identifiers are never generated, and connection tests or model discovery do not acquire +a Codex identity through this option. These headers preserve caller metadata; they do not prove +that the caller is an official client or grant permission under a gateway's access policy. ### Native compaction on custom gateways @@ -224,6 +279,9 @@ WebSocket proxy settings fall back to HTTP/SSE. HTTP fetch-based Responses handl `config.proxy` or a SOCKS5 `ALL_PROXY` uses the built-in tunnel when `NO_PROXY` does not exempt the target. Scheme-specific HTTP(S) proxy variables retain their separate native handling; non-SOCKS `ALL_PROXY` is not a native HTTP fetch route. +Internal model decisions, compaction responses, combo failover, and native Responses delivery accept valid event-stream media +types regardless of casing or parameters, including `Text/Event-Stream; charset=UTF-8`. Other explicit +media types retain their original format even when a parameter mentions `text/event-stream`. Native delivery also identifies JSON by its exact media type; a JSON name inside a parameter does not select the JSON decoder. Its existing missing-header SSE fallback and plaintext V2 event validation still apply. Noncanonical Responses gateways receive Codex's client-executed `tool_search` declaration as a collision-safe public function tool. Matching request history and JSON/SSE function calls are @@ -244,6 +302,31 @@ blank strings and mixed encrypted/unknown parts are not partially converted. See [agent messages](/reference/configuration/providers/#routed-agent-messages) for the separate opt-in encrypted-task recovery behavior. +Meta Responses also receives Codex's current `additional_tools` declarations in the public +`tools` array. The catalog is captured before history normalization: replayed declarations +and historical tool-search discoveries cannot activate tools for the new turn. Current +namespace, custom-tool and long-name aliases retain the existing normalization and response +restoration. Current declarations keep their parameter schemas when search results repeat a tool. +Historical custom calls retain their existing function-call representation without granting +those old tools current authority. Nested function definitions become public declarations. +Malformed or unrepresentable namespace catalogs return HTTP 400 before inference, including +requests with string or omitted input, rather than being partially promoted. + +For Meta Responses at the exact `api.meta.ai` host, OpenCodex omits the unsupported +`output.encrypted_content` include requested by Codex Desktop. Meta otherwise rejects the +request before inference. `reasoning.encrypted_content` and other include entries remain +intact, so stateless reasoning replay is preserved. The same exact-entry normalization +applies to xAI and to Kimi Code at its exact HTTPS Responses endpoint +(`https://api.kimi.com/coding/v1/responses`); unrelated Responses destinations keep their original include list. + +These request-shape fixes do not change account entitlements. Meta limits Muse Code +subscription credentials to the Muse Code client; other clients require a separately +billed Meta API key. A subscription key can therefore return HTTP 403 through OpenCodex +even when the request shape is valid. OpenCodex answers that refusal in one sentence: it is a +plan restriction on a valid credential rather than a rejected or expired one, and the +supported path is the `meta-model` provider with a pay-as-you-go key, not a re-login. See +[Meta's subscription rules](https://dev.meta.ai/docs/muse-code/subscriptions). + For xAI Responses, `auto` or `none` tool selection is omitted when normalization leaves no tools in the request, including when cached-only search is removed. Valid forced function selections remain intact. Replayed custom tool calls with missing or invalid item ids receive stable ids @@ -323,6 +406,14 @@ MiMo model Command Code serves. **Auth:** `key` (`x-api-key` by default, or `Authorization: Bearer` with `apiKeyTransport: "bearer"`) or `oauth` (Bearer + `anthropic-beta`, for Claude Pro/Max). - Converts messages to Anthropic content blocks (text, base64 image, `tool_use`, `thinking`). +- Routed Codex compaction keeps the client tool catalog, system prompt and tool-selection + options to preserve their prompt-cache prefix. Summary requests disable search/media + sidecars; upstream-hosted tools retain their declarations with `tool_choice: none`, as does a + mandatory tool choice, while the advertised catalog stays the same. A request that advertises a + sidecar web-search tool (for example Exa) still changes its tool prefix on compaction. + A summary that attempts a tool call fails without publishing a function call or replacing + history. A successful summary returns exactly one compaction item. Image normalization + and the existing one-shot tighter-image retry after HTTP 413 remain unchanged. - Translated Anthropic Messages reasoning replay shares the request translation budget, including encoding/decoding copy overhead. Requests exceeding it return HTTP 413 with `translation_buffer_limit`; signatures and opaque reasoning data are never truncated to fit. @@ -334,7 +425,14 @@ MiMo model Command Code serves. - **Adaptive thinking display:** adaptive-thinking models (Opus 4.7+, Sonnet 5, Fable) are asked for `thinking.display: "summarized"`, so a long think reaches Chat and Responses clients as reasoning deltas instead of minutes of heartbeats. A request that hides the reasoning summary - (`reasoning.summary: "none"`) keeps the provider default. + (`reasoning.summary: "none"`) keeps the provider default. Native Opus 5.5 on `api.anthropic.com` + defaults to `display: "updates"`; explicit `reasoning.summary: "concise"` or `"detailed"` + selects `"summarized"` without the updates beta. See [Opus 5.5 progress updates](/guides/providers/#claude-opus-55-progress-updates). + The provider or exact-model `thinkingDisplay` setting overrides that default: + `summarized` forces `display: "summarized"`, `updates` keeps progress commentary, and + `omitted` drops the display field so a Chat client receives no reasoning deltas during the + think. An explicit request summary still wins. See + [provider configuration](/reference/configuration/providers/). - **Structured output:** Responses `text.format` and Chat Completions `response_format` requests with `type: "json_schema"` become Anthropic `output_config.format`. The format merges into an existing adaptive-thinking output configuration, preserving a compatible `output_config.effort`. @@ -371,6 +469,17 @@ MiMo model Command Code serves. `/v1beta/models/{model}:streamGenerateContent`; the other modes use their native Google endpoints. **Auth:** API key, Vertex ADC, or Google Antigravity OAuth, selected by `googleMode`. +For the Google Vertex AI dashboard preset, Project ID and Location are optional fields. With +an empty API key, the proxy uses ADC on the **proxy host**, unless `GOOGLE_CLOUD_API_KEY` is set; +that environment key takes precedence. ADC also needs a project and location, supplied in the +form or by `GOOGLE_CLOUD_PROJECT` / `GCLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` on the proxy +host. Adding the provider does not verify that credentials or permissions are usable. A key +without an explicit project uses Vertex express mode. +The dashboard preset uses a static catalog seeded by the configured default model; its connection +test does not verify Vertex credentials or permissions. +Existing Vertex rows without `liveModels` retain live discovery through the generic discovery endpoint. +Use `liveModels: false` for a static catalog; Settings can switch between the two modes. + - **Location denials are permission errors, not invalid requests.** Google rejects unsupported geographic or datacenter locations with HTTP 400 `FAILED_PRECONDITION: User location is not supported for the API use.` The proxy reports this as `… location not supported: …` and @@ -383,7 +492,13 @@ MiMo model Command Code serves. - Tool-call ids are synthesized when Gemini omits them. Vertex and Antigravity preserve and replay opaque `thoughtSignature` values so tool-result continuations retain Gemini reasoning continuity. The signature cache is snapshotted to the config directory, so continuations also survive proxy - restarts. + restarts. On Vertex and Antigravity, when upstream rejects a request with any HTTP 400, or with + `INVALID_ARGUMENT` or a signature error inside a 200 response, that conversation's in-memory + signature replay entry is cleared so the next turn does not replay it. A rejection whose text + names a signature also evicts the rejected signatures from the durable store; any other + rejection leaves durable entries in place. The rejected request itself is not retried. +- Antigravity's Gemini 4 Argon requests include the selected thinking tier when thought summaries + are enabled, allowing its thought summaries to appear in supported clients. - **Malformed response shapes fail closed.** A claimed candidate, its `content`, or its `content.parts` that is not the documented container terminates the turn with a `google response contained invalid …` error naming the structural reason and the offending @@ -459,11 +574,50 @@ MiMo model Command Code serves. solely because the client permits parallel calls. - Accepts Responses `text` controls that are not structured output — `text.verbosity` and `text.format: {"type":"text"}` — without forwarding them. Kiro has no wire field for either, so - they are ignored rather than rejected. Structured output (`text.format` of type `json_schema` - or `json_object`) is still refused: the Kiro wire cannot constrain the response shape, and a - caller expecting JSON would otherwise receive prose. + they are ignored rather than rejected. +- Emulates structured output (Responses `text.format` of type `json_schema` or `json_object`, and + Messages `output_config.format`). The Kiro wire cannot constrain the response shape, so the + adapter advertises a private output tool whose input schema is the requested schema and returns + that tool's input as the response text. A plain-text reply that is already the requested JSON is + accepted as is. Any other reply, including an empty one, gets one bounded retry when the model stopped cleanly (a reply cut by the output-token limit, a content filter or a full context window ends with that stop's own error instead), and if the retry also fails the request ends + with an `invalid_kiro_structured_output` error. Prose is not returned as the structured answer; + commentary preceding a real client tool call can still stream with that call. + Without `strict: true` the check covers JSON syntax, the root type and the root's required + properties. With `strict: true` the whole value is checked exactly against the schema, and a + strict schema outside this subset is refused before the request is sent: + - `type`, `properties`, `required`, `additionalProperties`, single-schema `items`, `enum`, + `const` and `anyOf`. A `const` or `enum` value that contains a number is refused: the proxy + receives the request already parsed, so a number such as `1.0000000000000001` arrives as `1` + and an exact match could accept a value the caller excluded. + - `$ref` only to `#/$defs/` or `#/definitions/` at the schema root, with `~0` and + `~1` as the only JSON Pointer escapes. References such + as `#`, `#/properties/...` or `#/default`, nested `$defs`, and reference cycles that never + reach a property or item are refused, and so is a `$ref` with an assertion keyword beside it + (drafts disagree on whether such siblings apply), a `$id` below the root, and `$anchor`. + - `minLength`, `maxLength`, `minItems` and `maxItems` as non-negative integers. + - `minimum`, `maximum`, `exclusiveMinimum` and `exclusiveMaximum` as safe integers or decimals + with at most 15 significant digits. The model's numbers are compared exactly as written. This is + a heuristic for the bound itself: a bound written with more digits than a double holds can still + arrive rounded, so a value within about one unit in the last place of the bound may be judged on + the wrong side. + - `multipleOf`, `pattern` and `patternProperties` are refused in strict mode. Without + `strict: true` they are accepted and left to the light checks above. + + Validation work is capped per answer (10,000 schema checks plus 16 per JSON value, 128 schema + levels deep), including `const`/`enum` comparisons and every pass over `required` lists, object + entries, long strings and long numbers. A strict format without a JSON object schema is refused, + and so is a `type` list that repeats a type. An answer that needs more counts as not + matching the format. A strict schema with more than 10,000 nodes, or more than 10,000 values in + its `const`/`enum` literals, is refused. Error messages name the failed check only, never a + property name or path from the answer or the schema. + A Messages `output_config.format` schema always gets the `strict: true` checks, even when it + has optional properties and is therefore forwarded to OpenAI-compatible destinations without + `strict`: Anthropic promises an answer that conforms to the schema. A Messages schema outside + this subset is refused before the request is sent. - Decodes `application/vnd.amazon.eventstream`, reconstructs text/thinking/tool events, detects truncated tool JSON, and estimates usage because the upstream does not return token counts. + Decoder teardown initiates cancellation without waiting for transport cleanup to settle, so a + stalled cleanup promise cannot hold the decoder open after the consumer stops reading. - Uses the configured `baseUrl` verbatim when it is custom. A canonical `runtime.{region}.kiro.dev` URL follows the imported credential's API region; only that canonical shape is eligible for one budgeted fallback to `q.{region}.amazonaws.com` after an endpoint, @@ -491,7 +645,9 @@ MiMo model Command Code serves. The plan's precise credit balance is retained with that identity-fenced quota reading. Separately, Kiro `meteringEvent` credit values are measured request spend: the last value within a physical response is used, and credits from separately billed sends are added. - Token usage remains estimated; credits are never inferred from tokens. + Token usage remains estimated; credits are never inferred from tokens. Requests with hosted + search or image tools retain the adapter's full prompt estimate in Usage and daily activity, + including replayed history, even when the model does not invoke those tools. - After an admitted request, reads that account's available models from the regional management service without delaying the request. Cached results add model IDs to the shipped catalog. Empty or unrecognised replies retain the shipped list and any last good account list. Model @@ -499,7 +655,8 @@ MiMo model Command Code serves. limits inform context windows, conservatively combined with shipped limits when evidence is partial. Accounts that have not served have no list evidence yet. - Participates in multi-account rotation. With two stored accounts, a request-rate refusal - cools the refused account briefly; an exact monthly-quota refusal on HTTP 400 or 429 + cools the refused account briefly; an exact `MONTHLY_REQUEST_COUNT` or + `OVERAGE_REQUEST_LIMIT_EXCEEDED` refusal on HTTP 400 or 429 excludes it until the observed reset or evidence expiry. A confirmed HTTP 403 suspension quarantines that account in process, while an ordinary 403 does not rotate. Reactive rotation remains available when `oauthAccountFailover.enabled` is false. Refusal-aware @@ -551,6 +708,8 @@ real client tool call keeps the turn open. A completion-tool answer is always em `final_answer`, even when it exactly repeats prior commentary, because phase correctness is more important than cosmetic de-duplication. Tool-free requests retain normal text completion behavior. +The continuation's instruction tells the model that its ordinary text has not reached the user, and asks it to call `codex_kiro_final_answer` with the complete final answer if the task is complete, submitting its previous reply unchanged when that reply already was the answer. A model that answered a trivial request in plain text therefore keeps its answer, instead of being told to continue a task it had already finished. + ### Reasoning effort The GPT-5.6 family uses `additionalModelRequestFields.reasoning.effort`; `claude-opus-5` @@ -624,7 +783,11 @@ compatibility pair: `agent.v1.AgentService/RunSSE` for server output and guard. Tool availability, execution policy, and approval/sandbox behavior are unchanged. In code mode — a freeform unified `exec` and no bare shell bridge — the redirect points inside `exec`, where shell, file, search, and fetch are nested `tools.(...)` helpers of the JavaScript cell, - and never recommends the top-level shell bridge code mode does not expose. A flat catalog that + and never recommends the top-level shell bridge code mode does not expose. Cursor can defer the + Codex tools, `exec` included, behind its own `GetDynamicTools`/`CallDynamicTool` pair, so + code-mode guidance tells the model to call `CallDynamicTool` with namespace + `opencodex-responses` and the listed tool name when a listed tool is missing from its top-level + list. A model can still try a Cursor-native tool first; that attempt is denied as before. A flat catalog that carries `shell_command`/`exec_command` or a non-freeform unified `exec` keeps the bridge wording; a catalog that carries neither — an orchestrator client exposing only its own Responses tools, for example — is redirected to the request's actual wire names, so the model is pointed at a @@ -670,7 +833,10 @@ configuration that names the old id is rewritten at startup. This supports continuity but does not guarantee an upstream cache hit or a particular saving. - Reasoning continuity carries provider signatures across turns. If Cognition refuses a signed Anthropic replay before visible output, Devin retries once with the signature withheld and the - thinking text preserved. + thinking text preserved. Responses clients keep live text/tool streaming: a late turn signature + receives its own output index after the owning item closes, avoiding duplicate text and + unfinished-tool errors in index-keyed clients. Replay pairs the trailer only with adjacent + assistant output; matching IDs are checked when present, while ID-stripping clients remain supported. - Live model discovery via `GetCascadeModelConfigs`; the static seed is filtered against the account's live roster so models not on the plan drop out instead of failing at request time. - Tool definitions are encoded in the request and tool-call events are decoded from the response @@ -771,6 +937,11 @@ appended to the id instead. **Targets:** **Azure OpenAI**. Wraps `openai-responses` (so also `passthrough: true`). **Auth:** `key` via the `api-key` header (not Bearer). +Azure requests omit the unsupported output.encrypted_content entry from include, +while retaining reasoning.encrypted_content and all other entries. This also applies +to openai-responses configurations targeting a resource under .openai.azure.com. +When no entries remain, include is omitted. + - Delegates request building to the Responses passthrough, validates that `baseUrl` contains no unresolved template placeholder, and replaces `Authorization` with `api-key`. The configured URL targets Azure's v1 Responses API directly, so the adapter does not append `api-version`. diff --git a/docs-site/src/content/docs/reference/architecture.md b/docs-site/src/content/docs/reference/architecture.md index 02885f50ef..8d636575e4 100644 --- a/docs-site/src/content/docs/reference/architecture.md +++ b/docs-site/src/content/docs/reference/architecture.md @@ -79,6 +79,8 @@ the estimate excludes it too; history that never reaches the provider therefore context-limit refusal. Models that preserve reasoning, and other adapters, send that thinking and still count it. +Character-based token estimates apply the existing denser CJK weight to supplementary Han characters such as 𠀀 as well as BMP Chinese and Korean text. A supplementary Han surrogate pair contributes two UTF-16 units to that bucket. These remain heuristics: model ratios, context-window caps and provider-reported usage are unchanged. + ## The parser `responses/parser.ts` validates the incoming request with `responses/schema.ts` (Zod), then builds an @@ -122,6 +124,13 @@ and disabled for a local one (`stallTimeoutSec`; `0` disables it everywhere); reaching it aborts the upstream and emits `response.incomplete` with reason `upstream_stall_timeout`, preventing a hung connection from blocking Codex indefinitely. +The adapter's response-body inactivity guard has a separate failure path. When an initial or +recovery, terminal-guard continuation, or empty-completion retry response body stalls during translated Responses streaming, the terminal event is +`response.failed` with code `upstream_stall_timeout` and a bounded-duration message. The request +log classifies that terminal as 504 and can record the duration as `body_stall`. HTTP headers +already sent for the stream cannot change. A buffered initial or continuation body stall returns +HTTP 504 with the same bounded-duration message, which can also produce the `body_stall` detail. + Tool calls are disambiguated into three Responses item types using the namespace map, the freeform set, and the tool-search set captured by the parser — so MCP namespaces, `apply_patch`-style freeform tools, and client-executed `tool_search` all round-trip. A `buildResponseJSON()` variant produces a diff --git a/docs-site/src/content/docs/reference/cli.md b/docs-site/src/content/docs/reference/cli.md index 22214a24ed..ae34dcac19 100644 --- a/docs-site/src/content/docs/reference/cli.md +++ b/docs-site/src/content/docs/reference/cli.md @@ -152,18 +152,35 @@ manifest can then establish `managed: true` when it proves ownership and, if a c The JSON report exposes `candidateAvailable`, `candidateVersion`, `candidateSource`, and `selectionAttested`. Inspecting the configured candidate requires a trusted published-launcher context; a direct Bun/source launch has no such proof, ignores ambient and persisted candidate state, and may report -`candidate_unavailable` on POSIX or `windows_inspection_deferred` on Windows. On Windows this first slice performs no candidate or configuration filesystem I/O: -only a proof-captured absolute environment candidate can receive lexical app-bundle or version-manager labels; -every other Windows candidate fails closed. The command does not install or repair software, execute +`candidate_unavailable` on POSIX or `windows_inspection_deferred` on Windows. Windows x64 also supports +a proof-captured absolute standard npm `codex.cmd` with a held-bound Node/npm toolchain — prefix-local +when present, otherwise the captured-PATH pair anchored to the launcher architecture — and a verified +in-prefix platform backing. It uses reparse-refusing held handles; other Windows layouts remain deferred +or unmanaged. A `managed` Windows result classifies the observed installation layout only: the bound Node/npm +is the updater's read-only metadata toolchain, never a claim about which interpreter a later `codex.cmd` +invocation resolves, while inspection and planning stay read-only; applicability and confirmed apply are decided separately. +The command does not install or repair software, execute Codex or npm, control a running process, or write configuration/cache state. `ocx system codex-cli-update plan --json` adds a read-only update decision for an attested POSIX npm-global installation. It resolves `latest` through the official npm registry, validates the exact version and SHA-512 integrity, and refuses active sessions or incomplete process observation. Registry queries use isolated temporary npm configuration, cache and logs with best-effort cleanup. -No software is installed and no process is signalled. Windows returns `windows_inspection_deferred`. +No software is installed and no process is signalled. Windows x64 apply requires a bounded npm +prefix with verified private write authority and preserves unrelated packages and shims; unsupported observed layouts return +`applicable: false` and `refusal: windows_apply_disabled`. +PATH-only selection and OpenCodex autostart wrappers remain deferred. +Windows planning also requires trusted write authority over npm's complete package tree and module +lookup directories. Apply keeps selection changes and owned session starts busy through installer +termination and readback; an unknown child lifetime keeps that exclusion in place. +The selected Node must support synchronous module hooks; npm cannot load dependencies outside its verified tree. See [planning details](/reference/cli/agents/#read-only-codex-cli-update-plan). +For a reviewed applicable npm-global plan, `ocx system codex-cli-update apply --plan-id --yes` +performs the exact update and returns a durable job. `ocx system codex-cli-update status --json` +reads its result; use a stable `--request-id` for a lost-response retry. See +[confirmation and job states](/reference/cli/agents/#confirmed-codex-cli-apply-and-job-status). + For Windows x64 installation observation, see [the `attest` command](/reference/cli/agents/#explicit-installation-observation-on-windows-x64). Without explicit paths it observes the selected candidate identified from the proof-bound launcher snapshot; it does not grant update authority or attest runtime selection. List or status is the default where unambiguous. Use `--json` only on leaves that support it, and @@ -264,6 +281,8 @@ local configuration and local Lab inspection do not require startup. `ocx status --json` includes `cliCommand`: configured Desktop intent, the expected executable, observed PATH candidates, `pathFirst`, `desktopFirstOnPath`, issue codes, and `shellResolution: "unobserved"`. The human status report prints one command-selection line. `ocx doctor` adds an “ocx command selection” section: invalid, unsafe (`record-unsafe`) or enabled-pending records and missing/unusable Desktop targets fail the check, while disabled cleanup-pending records, PATH ordering conflicts and incomplete scans warn. `OCX_NO_DESKTOP_HANDOFF=1` suppresses package-launcher handoff for one invocation; it leaves the Desktop shim and PATH configuration in place. These read-only observations do not execute candidates, resolve parent-shell aliases/functions, or identify the proxy’s runtime owner. On Windows, package-launcher handoff is disabled; user `Path` order selects the Desktop `ocx.exe`. Status and doctor still read the record and report the first PATH candidate. A possible cmd current-directory candidate is reported separately from PATH order. +`ocx status --json` also includes `install`: how this `ocx` was installed, using the same detector `ocx update` acts on. `install.method` is `bun`, `npm`, `pnpm`, `mise`, `source`, `standalone` (the compiled desktop binary) or `unknown` when detection failed. `install.evidence.basis` names what decided it (`package-layout`, `mise-backend-record`, `standalone-binary` or `unavailable`); a mise install adds the mise tool alias and backend, and a failure adds an `error` code. No path is added. + Output flags are per command. `doctor` rejects `--json` with exit 2; [`v2` (family reference)](/reference/cli/agents/) supports `--json` for local and `--live` targets. Even for JSON-capable management commands, API failures diff --git a/docs-site/src/content/docs/reference/cli/agents.md b/docs-site/src/content/docs/reference/cli/agents.md index c63aef492c..f3058e22e2 100644 --- a/docs-site/src/content/docs/reference/cli/agents.md +++ b/docs-site/src/content/docs/reference/cli/agents.md @@ -34,6 +34,23 @@ prints a proposed model and effort per role without writing anything. `--apply` through the same write as `set`, skipping and naming the roles whose model and effort already match. See [Auto-assign](/guides/integrations/#auto-assign). +One `--apply` accepts at most **50 changed roles**, so its recorded changes fit one complete +history batch and can be restored together in the dashboard's **Change history**. Already-set, +unsized and unassigned roles do not count toward this limit. If more than 50 roles would change, +the command exits 5 before sending any role update. Preview without `--apply`, then use +`ocx agent roles set [--effort ]` for individual changes. + +Updates run sequentially. If a request fails, earlier confirmed writes remain applied, later +roles are not attempted, and the command keeps the original nonzero error exit. The receipt names +confirmed writes, the role whose write was not confirmed, roles not attempted, and the server-issued +history batch when known. A lost response can follow a saved write, including the first write before +its batch id is received; inspect `ocx agent roles --json` and the dashboard history before retrying. +No automatic retry or rollback occurs. History remains subject to its existing availability and +retention limits; a batch id does not guarantee that every write was recorded or is still restorable. +With `--json`, an interrupted apply adds `complete: false`, `unconfirmedRole` and `unattemptedRoles` +beside the existing `applied`, `skipped` and `omoJsoncNotWritten` arrays. A preflight refusal instead +adds `refusal` with code `too_many_role_changes`, the limit and the proposed change count. + Human-readable suggestion output displays terminal control characters as visible escapes. Use `--json` when you need the original suggestion values without presentation escaping. @@ -257,20 +274,29 @@ unqualified bare OpenAI model id. Bare `gpt-5.6-*` native aliases use Codex Pool Account-qualified OpenAI routes remain distinct, while provider-qualified routes such as `openai-apikey/gpt-5.6-*` use their configured API key and never fall through to the native alias. Read the safety and visibility contract in the guide before enabling the compatibility pair. -With `--strategy jev` only, the decision method is chosen by one of two mutually exclusive flags. +Only when the effective strategy is JEV (`--strategy jev`, or a stored JEV Combo when `--strategy` is omitted), the decision method is chosen by one of two mutually exclusive flags. `--decision-provider ` names a configured `jev-decision` row (for example a self-hosted Ollama `tev1`) as a System One-compatible server. `--decision-model ` names an ordinary opencodex route (for example `ollama/qwen3:4b`) that answers the same choice as JSON; it cannot be -this combo or any JEV combo. Omitting both uses TypeSafe. `--decision-timeout ` sets the +this combo or any JEV combo. A new JEV Combo that omits both uses TypeSafe; an existing JEV Combo keeps +its stored decision method until one of the flags changes it. `--decision-timeout ` sets the decision deadline (1000–120000, default 4000); `-` clears any of the three. `ocx combo set --decision-quota-signals on|off|-` controls per-Combo advisory evidence. `--decision-quota-tiers '{"limited":80}'` sets partial threshold overrides; `-` clears them. -Both are JEV-only. Omitted policy survives `--targets-file` replacement, `--targets` with `--strategy jev`, and rename (`--targets` alone keeps the existing failover default). Off retains thresholds; +Both are JEV-only. Omitted policy survives `--targets-file` or `--targets` replacement and rename. Without +`--strategy`, replacing the targets of an existing Combo keeps its stored strategy, so a JEV Combo stays JEV with +its decision method, quota settings and session pin; a new Combo defaults to failover. If the kept JEV +policy rejects the new targets, the command fails, names that policy, and saves nothing. Off retains thresholds; switching away from JEV removes both settings. This adds quota data to the selected decision backend, not probes, new account selection or hard exclusions. See [quota defaults, freshness and privacy](/guides/combos/#advisory-quota-signals-for-jev). +`ocx combo set --session-pin ` (JEV only) keeps each client session on the target +JEV chose for it while the session stays active, so the provider prompt cache stays warm. The +duration is the idle window: `90s`, `20m`, `1h` or milliseconds, from 1 minute to 24 hours; `-` +turns it off. See [Session pin for JEV](/guides/combos/#session-pin-for-jev). + `ocx combo test [--combo ] [--decision-provider | --decision-model ] [--decision-timeout ]` sends one synthetic decision probe through a saved combo's method or an unsaved selection and reports the gate, backend, and latency; it may spend one decision call. @@ -309,6 +335,8 @@ explicit `lastResort: false`. `--image-input auto|disabled` and `--reasoning-effort-mode strict|adaptive` preserve omission, while explicit `auto` and `strict` override saved disabled/adaptive values. Reasoning-effort mode is separate from `--effort-mode fallback|force`, which governs the default effort. +`--jev-effort-mode decide|client` also preserves omission; `client` keeps JEV's target +choice and leaves effort to ordinary Combo policy, and explicit `decide` clears a saved `client`. `--allow-metered-targets on|off` grants or clears operator consent for marked combo targets on a loopback-only proxy; public and linked callers still need configured-key consent. `--native-alias on|off` preserves explicit false; the legacy bare flag means true. Turning it off may require the intended alias clear, `--native-alias off --alias -`, @@ -334,6 +362,25 @@ There is no monetary cost or comparative savings field in this report. See [Combos](/guides/combos/) for routing behavior and configuration guidance. +## Fallback off + +### `ocx fallback ...` + +```bash +ocx fallback status --json +ocx fallback off --kind provider +ocx fallback on --route combo/coding +ocx fallback clear --provider anthropic --kind model +ocx fallback local on --device mac-studio +``` + +`off`, `on` and `clear` take `--kind model|provider|all` (default `all`) and at most one scope: +`--provider `, `--route ` or `--device `; with none they set the global switch. +A device set to off always refuses; otherwise route beats provider beats global. `local` records whether a +device may use its own providers while the Home is unreachable, a permission GOAT reads; OpenCodex itself +still answers `home_unreachable` there. The commands talk to the live proxy; on a Remote Link Child, +`status` reads the Home and writes are refused. See [Fallback off](/guides/fallback-off/). + ## Routing profiles Existing profiles support inspection and evaluation through the live API: @@ -935,6 +982,43 @@ native-mode flags are rejected; failed runtime save has no local fallback. Apply is a separate existing Desktop action on its machine, so verify host/context before choosing it. Rendered models are not proof of native application. +### `ocx codex [codex args...]` + +The key is supplied only when the configuration and its namespaces are protected from other principals; the current user and privileged OS authorities are trusted. Same-user processes are trusted: an actor with your write access can already read your OpenCodex key file. Same-user configuration replacement between verification and native startup is outside this threat model; the launcher does not freeze configuration at handoff. + +On a normal Windows installation, default ProgramData permissions allow other users to create directories. Automatic credentials are therefore withheld even when `ProgramData\OpenAI\Codex` is absent. The system Codex configuration folder under ProgramData must exist and be writable only by Administrators/SYSTEM, and its ancestors must prevent replacement by other users. Ask an administrator to review the directory policy. opencodex never changes ACLs itself and provides no provisioning command. + +Alternatively, supply the key yourself, for example by exporting `OPENCODEX_API_AUTH_TOKEN`; `ocx codex` leaves it untouched. Existing system configuration files still withhold automatic credentials and require separate review. Each withholding reason produces one short, specific stderr diagnostic without key values, key-file contents or key-file paths. + +Use `--` before a single-word prompt so it cannot select an unknown Codex subcommand. + +Automatic credentials also require a fresh ownership proof from this installation's running listener. For a standalone proxy, the proof must come from the exact HTTP origin in the managed Codex provider configuration; a running proxy on a different port or loopback address does not authorize that destination. A direct client proves its own machine listener and keeps its saved server URL checks, because the server it dials is a different installation. For a direct client the proof shows that the answering listener belongs to this installation; it does not prove which kind of listener it is. Without a matching proof, the launcher withholds the automatic token and leaves routing unchanged. + +The machine configuration namespace must also prevent other users from creating missing system files. An unprotected Windows ProgramData/OpenAI/Codex namespace withholds automatic credentials; the launcher does not create it. macOS accepts deny-only and read-only allow ACLs, but refuses any allow entry granting write, append, delete, attribute/security changes or ownership changes, even after a deny entry. Unknown tags and inspection errors refuse. + +A fresh service token is loaded only when argv is within the allowlist below, the environment has no nonempty HTTP(S)/ALL proxy or `CODEX_*`/`OPENAI_*`/`AZURE_OPENAI_*` overrides (canonical `CODEX_HOME` is allowed), and the home/config/system namespaces pass ownership checks. The configuration must contain only audited keys and the exact managed loopback provider, with no additional credential consumers or configuration layers. Every unsupported argument, including `-c`/`--config`, `-p`/`--profile`, unknown flags and `resume`/`fork`, withholds the token with a value-free diagnostic; explicit user credentials and original arguments are preserved. + +The canonical home directory and `config.toml` must belong to the current user. POSIX denies group/other writes; Windows checks owner SID and rejects DACL write grants outside the current user, SYSTEM and Administrators. Ancestor replacement permissions are checked too. macOS additionally requires no forced Codex configuration preferences. These checks exclude other-user writers; they do not isolate a malicious process running as the same user or an administrator. + +| Allowlist | Flags | +| --- | --- | +| Switches | `--no-daemon`, `--json`, `--ephemeral`, `--skip-git-repo-check`, `--no-alt-screen`, `--full-auto`, `--dangerously-bypass-approvals-and-sandbox`, `--search` | +| One value | `--model`/`-m`, `--sandbox`/`-s`, `--ask-for-approval`/`-a`, `--image`/`-i` | + + + +Automatic credential delivery resolves `CODEX_HOME` as a literal path (including `~` and whitespace), verifies that home, and passes its canonical absolute path to the child. An unreadable home skips loading. Any nonempty `HTTP_PROXY`, `HTTPS_PROXY`, or `ALL_PROXY` variable, in any letter case, also skips loading regardless of `NO_PROXY`; denied launches and user-exported credentials remain unchanged. With a newly loaded token, both child `NO_PROXY` and `no_proxy` include `127.0.0.1` and `::1`, preserving existing bypass entries. Enabling `features.respect_system_proxy` or forwarding `--enable`/`--disable` skips automatic loading. + +Ensure the proxy is running, then launch Codex with the original arguments. Routing remains in Codex configuration; the launcher never rewrites it. Native and foreign routes skip startup. Unknown routing warns and attempts startup; a failed startup warns and continues. Help/version and internal commands such as `login`, `doctor`, and `help` skip startup and automatic token loading. + +A missing `OPENCODEX_API_AUTH_TOKEN` is read from this installation's `service-api-token` only when the selected provider's complete transport configuration matches the managed block for the configured loopback listener or persisted local client connection. Names and injection comments alone grant no credential access. Unknown or remote destinations, default profiles, project configuration, `OPENAI_BASE_URL`, and forwarded `-c`/`--config`, `-p`/`--profile`, `-C`/`--cd`, or `--remote` options skip automatic loading. User-exported credentials and arguments are preserved; token-file overrides cannot select a different credential, and management-token collisions are refused. + +Only a matched autostart wrapper launches its backing Codex directly. Unknown state, including an inspection exception, requires a verified bypass; Windows CMD managed wrappers must match the complete current generated template before the selected absolute command runs with `OCX_SHIM_BYPASS=1`. Ordinary npm launchers remain supported. Unverifiable or obsolete wrappers refuse with exit 1 and start no Codex; run `ocx codex-shim install` to refresh them. This launch does not repair shims. The content check does not establish Windows backing-file provenance or prevent concurrent pathname replacement. + +On macOS, every launch, including help/version, verifies the selected executable when its selected path or canonical location is inside any `.app` bundle. Renamed bundles and symlinks into bundles require the same safe ownership, permissions and OpenAI signatures for the bundle and executable. A selected bundle member must stay inside that bundle's canonical `Contents/`, including through executable, directory or whole-bundle symlinks. Failed verification exits 1 without starting Codex. Ordinary non-bundle executables, including npm installations, retain their behavior. + +Use `ocx help codex` for launcher help and `ocx codex --help` for Codex help. Launching plain `codex` later retains its existing behavior. + ### `ocx opencode [opencode args...]` Ensure the proxy is running, then launch opencode with the generated `provider.opencodex` and @@ -951,13 +1035,32 @@ Manage and apply the Grok Build model fence. ## Client config export +Hermes and Command Code export and integration apply/overwrite accept +`--model-names alias|routed` (JSON API field: `modelNames`). Omission on export +means `routed`; omission on a later integration Apply preserves its stored mode. +This is independent of `preferModelAliasIds`. Only a provider-qualified alias +that routes to the same provider/model is emitted; unsafe, missing or colliding +aliases fall back to routed names, and combos keep their existing keys. + +`ocx export --client hermes --model-names alias --json` previews an existing +current catalog without writing client files or managed state. A cold/stale +catalog returns unavailable; load the catalog separately and retry. Explicit +`--out` writes only the requested export artifact and retains its existing +exclusive-create/`--force` behavior. For managed writes, pass the same mode to +both `integration client preview --operation apply|overwrite` and `enable` when +confirming a plan. The field is unsupported on disable/restore and other clients. +An alias change during Apply or refresh can cause a conflict before any write; +retry against the current catalog. Removed/renamed aliases migrate at the next successful refresh, with foreign-edit +refusal. See [the integration guide](/guides/integrations/#opt-in-alias-model-names). + ### `ocx export --client ` Print a client config wired to the running proxy. The command serializes the `opencodex` provider block — base URL, model list, and the client's credential reference or loopback placeholder — in the selected client's native format. -The proxy must be running; the command resolves its live port, reads `/api/models`, and emits only +The proxy must be running; the command resolves its live port, uses the current +catalog (`/api/models` or the server-side client export), and emits only models Codex can currently see. OpenCode and Kilo exports preserve effective model limits, known capabilities, declared reasoning @@ -1000,7 +1103,7 @@ client applies its own defaults for those). | `raycast` | `~/.config/raycast/ai/providers.yaml` on macOS and Windows alike (Raycast does not honor `XDG_CONFIG_HOME`) | `raycast-providers.yaml` | none — loopback only, no `api_keys` entry is written | | `omo` | `~/.omo/agent/models.json` (`OMO_CODING_AGENT_DIR`, then `SENPI_CODING_AGENT_DIR`, then `PI_CODING_AGENT_DIR` win in that order when set; a relative value is refused) | `omo-models.json` | none — loopback placeholder | | `kilo` | first existing `kilo.jsonc`, `kilo.json`, `opencode.jsonc`, `opencode.json`, or `config.json` under `~/.config/kilo` (`XDG_CONFIG_HOME` relocates that directory); uses `kilo.jsonc` when none exists | `kilo.jsonc` | `OPENCODEX_KILO_API_KEY` | -| `commandcode` | `~/.commandcode/providers.json` (on Windows with the default home: use `HOME ?? USERPROFILE` only if nonblank and Windows-absolute, otherwise `homedir()`; a separately supplied home is preserved; append `.commandcode\providers.json`) | `providers.json` | loopback only; `apiKey: false`; no environment variable | +| `commandcode` | `~/.commandcode/providers.json` (on Windows with the default home: use `HOME ?? USERPROFILE` only if nonblank and Windows-absolute, otherwise `homedir()`; a separately supplied home is preserved; append `.commandcode\providers.json`) | `providers.json` | loopback only; `apiKey: false`; no environment variable; never writes `~/.commandcode/auth.json` — the desktop app requires its own sign-in | | `droid` | `~/.factory/settings.json` (`%USERPROFILE%\.factory\settings.json` on Windows) | `factory-settings.json` | loopback only; no environment variable | The managed DSH export requires DSH 0.1.0-rc.6 or newer and owns only @@ -1135,9 +1238,12 @@ resolver selects the same canonical environment candidate without executing it. can then establish `managed: true` when it proves ownership and, if a candidate version is reported, that version matches the manifest; persisted candidates remain unattested. The JSON report exposes `candidateAvailable`, `candidateVersion`, `candidateSource`, and `selectionAttested`. Inspecting the configured candidate requires a trusted published-launcher context; a direct Bun/source launch has no such proof, ignores ambient and persisted candidate state, and may report -`candidate_unavailable` on POSIX. On Windows this first slice performs no candidate or configuration filesystem I/O: -only a proof-captured absolute environment candidate can receive lexical app-bundle or version-manager labels; -every other Windows candidate fails closed. Because that slice never consults persisted state, a Windows run +`candidate_unavailable` on POSIX. On Windows x64, a proof-captured absolute standard npm `codex.cmd` +can be managed when held local handles bind its package, a prefix-local Node/npm pair or the captured +PATH metadata pair tied to the launcher architecture, and the first in-prefix platform backing. +This metadata pair does not attest the interpreter a later CMD invocation would select. +Plan paths and configured version-manager roots must use their canonical long DOS names; +aliases, unavailable roots and reparse points leave the installation unmanaged. Other Windows layouts remain deferred or unmanaged. Windows never consults persisted state, so a run with no captured environment candidate reports `windows_inspection_deferred` rather than `candidate_unavailable`: the command cannot observe whether a Codex CLI is installed, so it reports the deferral instead of asserting that no candidate exists. The command does not execute Codex or a package manager, repair a shim, @@ -1154,18 +1260,86 @@ ocx system codex-cli-update plan --channel latest --json ``` Run through the published Node launcher with the intended `CODEX_CLI_PATH` in the shell environment. -The plan requires an attested POSIX npm-global installation and a linked package manifest version. +The plan requires an attested npm-global installation and a linked package manifest version. +Windows supports only an explicit absolute standard npm `codex.cmd` with a held-bound Node/npm toolchain — +prefix-local when present, otherwise the captured-PATH pair anchored to the launcher architecture; +PATH-only selection, OpenCodex autostart wrappers and global/vendor fallback stay deferred. It queries the official npm registry for an exact version, SHA-512 integrity and same-origin tarball, using the launcher's captured PATH and isolated temporary npm configuration, cache and logs. Proxy settings and `NODE_EXTRA_CA_CERTS` remain supported; cleanup is best-effort. No Codex command runs. An applicable plan reports `applicable: true` and a deterministic `planId` binding platform, -installation-root digest, installed version, channel and target version/integrity. The plan is never +installation-root/content digests, installed version, channel and exact main/platform artifacts. The plan is never persisted. It refuses downgrades, already-current versions, active Codex sessions and incomplete -process observation. Windows returns `windows_inspection_deferred` before registry/process queries. +process observation. Supported Windows metadata queries use the observed Node/npm under matching +held handles. Windows x64 can be applicable only for a bounded npm prefix with verified +write authority; other observed prefixes retain `windows_apply_disabled`. Active/unknown sessions still refuse earlier. Unsupported +Windows layouts return `windows_inspection_deferred` before registry/process queries. A refusal exits 0: inspect `applicable` and `refusal`. The printed install argv is indicative; this -command installs nothing, changes no application state and never signals a session. No apply command -is exposed, and a plan ID is not installation authorization. +command installs nothing, changes no application state and never signals a session. +A plan ID alone is not installation authorization: apply requires separate explicit confirmation. + +#### Confirmed Codex CLI apply and job status + +```bash +ocx system codex-cli-update apply --plan-id <32-hex> --yes --request-id --json +ocx system codex-cli-update status --json +``` + +Apply supports the selected, managed, non-shim npm-global CLI on Linux/macOS and the restricted +Windows x64 npm layout. It revalidates the +approved plan under an installation lease, verifies the exact main/platform archives, installs them +offline with lifecycle scripts disabled, and checks installed files and the selected CLI's version. +Existing Codex sessions are never stopped; active or unknown process observations refuse the update. +Windows supports shared prefixes with verified ACLs and no reparse paths. Observation includes +unrelated packages and shims, capped at 4,096 entries, 512 MiB total and 384 MiB per file. Their +bytes and identities must be preserved. Larger or unsafe prefixes, ARM64, shim repair, native apps +and other installation managers remain unsupported. Unknown child lifetime or incomplete handle cleanup retains staging and +the installation lease; do not retry by deleting its lock. Readback includes auxiliary files, +new/absent backing roots and npm's hidden lockfile. `not_applied` means scoped installation state +was observed unchanged, not that npm performed no I/O anywhere. +Installation directories and staging require trusted POSIX ownership and permissions throughout their +ancestry. Unsafe installation paths report `installation_prefix_unsupported` or +`installation_paths_untrusted`; unsafe temporary roots report `staging_path_untrusted`. Use a private +temporary directory below trusted ancestors (root-owned sticky temporary roots are supported). +Owned session starts, desktop restarts and runtime/shim selection changes report busy while installation +and readback run. An unconfirmed installer or verification child keeps admission closed. Admission +recovers when the owned process group is proven gone, including a verification child that closes after +its reap deadline. Worker loss before commit also restores admission; worker close after commit alone +does not. Durable recovery records preserve this exclusion across proxy restarts. +On Windows, recovery checks the exact installer/verifier Job and original process creation identity; +all Job members must have exited. Access failures keep admission closed and never stop an installer. +Missing child identity, partial records or inaccessible liveness evidence require inspection. A complete terminal write left +before its publication rename can restore admission after restart when its exact owner and current +parent/group absence are verified. On Windows, a complete pending child identity can also restore +admission when it matches the armed owner and Job, the guardian's terminal proof is valid, and the +parent, exact child lifetime and every Job member are proven gone. Missing proof, incomplete or armed +pending writes still require inspection; guardian death alone cannot reopen admission. +Recovery does not change an +ambiguous job result, retry installation or reclaim an abandoned installation lease. +Without recovery history, a symlinked `OPENCODEX_HOME` (or home ancestor) permits these ordinary +operations. With history, admission reads the protected canonical home target; unsafe recovery +paths still report busy. This does not relax the updater's installation or config-path eligibility. +Shim repair, native apps and other installation managers remain unsupported. + +Apply exits 0 only for an `applied` job; `not_applied`, `refused`, `ambiguous` and pending duplicate jobs +exit 1, including with `--json`. Status reads the +same private job record without a running proxy or GUI token. Reuse the same optional request ID after +a lost response: the same key and plan return the original job; a changed plan with that key refuses. +The private ledger retains up to 64 jobs, including finished jobs, without automatic pruning. At that +limit, new request IDs are refused with `store_full`; existing matching retries still return their +original job. Capacity and operator recovery remain a separate follow-up that must preserve this +deduplication contract. A busy admission ledger reports `job_store_busy` (HTTP 503 with `Retry-After: 1`); +permanent admission failures have no retry-delay header. Missing or unreadable CLI +status returns `job_unavailable` and a nonzero exit. Completion persistence failures do not rerun the +installer or turn an uncertain job into a confirmed success. +An ambiguous result is never automatically retried or rolled back. After an owner restart, an unfinished +job reports unknown ownership instead of claiming the old process stopped. Inspect the job's outcome, +child/lease state and cleanup errors; command exit status alone does not establish an installation result. + +The management API provides authenticated plan/status reads and confirmed trusted-loopback GUI-session +apply admission. A published Node `ocx start` supplies the required inspection snapshot; direct Bun or +compiled sidecar startup does not provide that proof. The Dashboard update panel is a separate follow-up. #### Explicit installation observation on Windows x64 @@ -1178,7 +1352,7 @@ ocx system codex-cli-update attest --candidate --npm-prefix -o pid=,ppid=,args=` and + `lsof -nP -iTCP: -sTCP:LISTEN` provide process and listener clues. They do not by + themselves establish the home, supervisor, or complete visibility; use the appropriate OS + tools and permissions to verify those separately. +2. Only if those facts are verified and forced termination is acceptable, the owner can run + `ocx stop` from the owning installation and home. It tries a graceful stop first, but may + fall back to forced termination if that fails; it can also refuse, including when the blank + hostname prevents guarded ownership verification. Do not bypass a refusal. +3. Independently confirm the identified process has exited, no supervisor will restart it, + and the intended address and port are free. A successful stop or a status result alone is + not proof of all three. Once confirmed, run `ocx start` from the intended installation and + home with the intended bind and port settings; a successful start regenerates the record. + +If any check is incomplete, the stop fails or is refused, or forced termination is unacceptable, +stop and ask the owner or administrator to investigate. Do not edit the runtime record or kill +unrelated processes. Retry the update restart if needed after the new proxy is running. + Identical version strings and the `unknown` / `0.0.0` placeholders suppress the warning, as does an absent proxy version. Doctor does not report placeholders as a confirmed match. Different strings still produce a neutral warning when they cannot be strictly parsed as SemVer or differ @@ -279,6 +358,9 @@ only in build metadata; neither side is called older. Versions are not trimmed a is not normalized. JSON exposes the same advice in `versionSkew`, whose fields remain `cliVersion`, `proxyVersion`, `skewed`, and `warning`. +On a Remote Link Child and its Home, `--json` also reports `appliedCodexSettingsDigest`, +`lastApplyAt` and `runtimeStartedAt`; see [Remote Link apply parity](#remote-link-apply-parity). + Print a read-only diagnostic summary: proxy PID, `/healthz` reachability, dashboard URL, config path, default provider, Codex autostart setting, service state, shim state, and the redacted effective Codex home. Only the explicit, high-confidence Windows Orca runtime-home signature adds an actionable App-home @@ -394,12 +476,19 @@ not traffic missed between polls; injection seq cannot exclude restart/eviction Check post-sync readiness through the unauthenticated `GET /readyz` endpoint. It returns `200` when ready, or `503` with `Retry-After: 1` for `pending` and terminal `failed`. Its sanitized HTTP identity is `{service, version, uptime, pid, port, status}` plus the remote-hub protocol fields -`{protocol, minimumClientProtocol, managementUrl}`. `protocol` is the hub protocol this proxy +`{protocol, minimumClientProtocol, managementUrl, features}`. `protocol` is the hub protocol this proxy speaks and `minimumClientProtocol` the oldest client it still accepts, so a client can refuse an incompatible pairing before sending anything else. `managementUrl` is the origin a client should use for the management plane: the configured `hub.managementPublicOrigin` when `runtimeRole` is `hub`, and otherwise the origin the request itself arrived on. A readiness request with no -HTTP(S) origin is rejected rather than answered with a guess. Old proxies without `/readyz` fail +HTTP(S) origin is rejected rather than answered with a guess. +`features` lists the peer features this build serves, so a peer can check a capability without +comparing versions: `relay-auth/` names the Remote Link relay authentication version, +`link-management-relay` the read-only Remote Link management relay, `link-peer-report/` that +a Remote Link Home reports each Child's version and compatibility in `ocx link status`, `quota-pool/1` the +`GET /api/quota-pool` management read, and `served-by-header` the `x-opencodex-served-by` response +header. A feature this build does not serve is absent. The list holds fixed names only, never +account or configuration data. Old proxies without `/readyz` fail closed as `unreachable`; `/healthz` is separate liveness, not readiness. The command performs one probe by default; `--wait` polls until ready or timeout, but exits immediately when it observes the terminal `failed` state. The default timeout is 45 seconds; `--timeout ` requires `--wait` and accepts positive integer seconds from 1–300. @@ -408,6 +497,12 @@ The CLI's own `--json` output is deliberately narrower than the HTTP body: it em `unreachable`. Exit codes are 0 for ready; 1 for not-ready, pending, failed, timeout, or unreachable; and 64 for invalid arguments. +On a Remote Link Child, readiness also covers the link. While the link cannot carry a request, +`/readyz` answers `503` with `status: "pending"` and `link: {state: "unavailable", reason}`, so +`ocx ready --wait` keeps waiting until the link is back; a working link adds +`link: {state: "available"}` to the `200` answer. `/healthz` on a Child keeps meaning only that the +process runs. The reasons are listed in [Remote Link](/guides/remote-link/#link-status). + ### `ocx resolve [--json]` Resolve the runtime facts a shell needs without re-implementing them: the config home, the @@ -455,9 +550,12 @@ of deleting anything. Run read-only environment and connectivity diagnostics: state paths and filesystem type, WSL dual installs, proxy environment/config, ChatGPT reachability, Codex plugin and project-config warnings, -and pending history migration. The Codex app-home targeting section also detects the narrow Windows -Orca runtime-home mismatch and explains service migration when applicable. Paths shown by this -diagnostic redact the OS username. Doctor prints repair hints but does not apply them. +and pending history migration. The **Native main refresh** section reads admission status from the +running proxy's authenticated, read-only native-main admission endpoint, so a separately launched `ocx doctor` +reports the service's `foreign-ownership` or other fence reason; if the proxy cannot be queried it +reports admission as unavailable. The Codex app-home targeting section also detects the narrow +Windows Orca runtime-home mismatch and explains service migration when applicable. Paths shown by +this diagnostic redact the OS username. Doctor prints repair hints but does not apply them. Project-config diagnostics ignore provider examples inside TOML multiline strings, including `developer_instructions`. Real provider and profile settings after the closing delimiter are still @@ -491,10 +589,35 @@ See [v2 outcomes](/reference/cli/agents/#explicit-v2-target-and-outcome) and for target, scope and spending boundaries. A reset-grant status read can contact upstream status but never consumes or resumes a grant. -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +On a Remote Link Home, a successfully committed current catalog is also synced to eligible linked +Children. `--local-only` disables this fan-out. `--json` prints one `ocx.sync.fanout/1` result with +the Home outcome and each Child's state. A connected Child skipped during fan-out includes its reason +and an actionable `hint` in JSON and human output. Update OpenCodex on an older Child to at least +2.93.0 using the installer that owns the selected `ocx`. For a Desktop install on headless Windows, +use **Check for Updates** in the signed-in Desktop tray. A link +mismatch may require re-linking the Child, while an updating Child can be retried after the update. +The Home's own nonzero exit code is returned unchanged. When the Home exits 0, a connected Child +skipped during fan-out, a failed or timed-out Child, or an unreadable link store produces exit 6. +Intentional skips such as client-initiated links and `--local-only` keep their existing exit behavior. +An unreadable link store produces a path-free error in human output. Exit 7 is reserved +for an update in flight. +If the Home sync throws in JSON mode, stdout still contains one result document and stderr gives a +sanitized failure message. + +Fan-out never requests a Codex app or app-server restart on a Child. Use GOAT, run +`ocx sync --restart-codex` on a full `ocx` Child, or restart the Codex desktop app and long-lived `app-server` processes separately on a lightweight `ocx-child` Child if a Codex restart is needed. The Child's pinned sync may +still restart its own OpenCodex client runtime after applying changed Home settings. If the Home +times out and stops its local SSH process, a remote sync already running may continue on the Child. + +If an update is in flight or the shared update/sync mutex cannot be determined, sync changes nothing, reports `update-in-flight`, and exits 7. If another sync holds the mutex, it reports `sync-in-progress` and exits 1; a Home counts that Child as failed and exits 6 when its own sync succeeded. With `--json`, either refusal prints one result document with the Home skipped and the refusal reason in `fanout.reason`. An explicitly requested restart also runs after a successful committed `config.toml` change, even if the catalog and cache bytes are unchanged. A configuration-only no-op, refusal, preflight, or rolled-back write does not trigger it. Without a restart flag, sync never automatically restarts Codex. +On a Remote Link Child, `ocx sync` also applies the Home's Codex settings and, when the client runtime +started before that apply, restarts it; see [Remote Link apply parity](#remote-link-apply-parity). + Fetch the live model list from every configured provider and re-inject the merged catalog into Codex. Run it after adding a provider or to refresh available models. @@ -522,6 +645,46 @@ and a stale picker is not. When the command runs from inside the Codex app, the restart is handed off to a detached helper and this session ends with the app. +#### Sync only from the expected Home: `--expect-link` and `--expect-hub-key` + +```bash +ocx sync --expect-link [--restart-codex] +ocx sync --expect-hub-key [--restart-codex] +``` + +A script that reads `ocx connect status --json` and then runs `ocx sync` cannot tell whether the +machine was disconnected or relinked to another Home in between; a plain `ocx sync` would then +sync the local providers or the other Home's catalog. Passing the identity you read closes that +gap. `--expect-link` takes the `link.linkId` of a Remote Link Child and `--expect-hub-key` the +`apiKeyId` of a hub client. The check runs under the same lock that chooses the sync path, and +every later write is bound to the connection that passed it. + +When the identity holds, the command is exactly the connected sync above. Otherwise it changes +nothing (not even the automatic Codex shim repair other commands run first), never syncs the local +providers, exits **5**, and prints a human line followed by one JSON line as the last line on stderr: + +```json +{"phase":"child_link_mismatch","reason":"other_link"} +``` + +`phase` is `child_link_mismatch` for `--expect-link` and `hub_client_mismatch` for +`--expect-hub-key`. + +| `reason` | Machine state | +| --- | --- | +| `disconnected` | Not connected to any Home or hub | +| `invalid_state` | The client configuration or a connect marker cannot be read | +| `disconnect_pending` | A disconnect has started and not finished | +| `pending_operation` | A key rotation, a connect, or another sync is in progress (including one that holds the locks this check needs) | +| `hub_client` | `--expect-link` on a hub client | +| `link_client` | `--expect-hub-key` on a Remote Link Child | +| `other_link` / `other_key` | Connected, but to a different link or with a different key | + +A missing or malformed value, a repeated flag, or both flags together exit 2 before any state is +read. A connection that changes after the check, while the catalog is being fetched, still fails +as a plain connected sync does (exit 1, nothing written). Versions without these flags ignore +them, so check `ocx --version` first. + ### `ocx sync-cache [--restart-codex] [--restart-app-server-only]` Invalidate Codex's local model picker cache so it is rebuilt from the active opencodex catalog. The @@ -663,10 +826,15 @@ Launchd restarts the proxy after a crash or failed restart handoff, but leaves i the service deliberately exits cleanly because the desktop app owns the runtime. Run `ocx service repair` once to apply this behavior to a service installed by an older version. -Definitions installed before this change still carry the old versioned paths and cannot migrate -themselves — once the old executable is deleted, no opencodex code runs to fix it. Run -`ocx service repair` once after upgrading. Linux service starts then follow the launcher; macOS -repair writes the new package paths into the launchd definition. +Definitions installed before this change do not have the resolved `CODEX_HOME` and `OPENCODEX_HOME` +pinned for service restarts. After upgrading, run `ocx service repair` once so the generated shell +reasserts both homes after login-profile initialization and Task Scheduler keeps absolute home paths +rather than expanding the task's runtime profile variables. Repair also refreshes old versioned paths; +if the old executable was already deleted, reinstall opencodex before repairing. Linux service +starts then follow the launcher; macOS repair writes the new package and home paths into the launchd +definition. +On macOS, install and repair refuse a home or proxy environment value that contains a control +character an XML plist cannot hold (for example U+0001); the error names the variable to fix. An already-running proxy is not replaced by an external upgrade: when the installed CLI is newer than the running proxy, run `ocx service restart` so the new build serves. On macOS, `repair` is not enough there: the definition did not change, and a repair that changes nothing reloads nothing. @@ -681,7 +849,7 @@ If the proxy is newer instead, check the CLI installation and `PATH` as describe | `restart` | The same refresh and a guaranteed restart on every platform. On macOS an unchanged, already-loaded job is kickstarted in place. Not an alias of `repair`. | | `start` | Start an installed service. | | `stop` | Stop the service and restore native Codex. | -| `status` | Report service and proxy diagnostics plus log paths. | +| `status` | Report service and proxy diagnostics plus log paths. `--json` prints the passive document described below. | | `uninstall` | Remove the service and restore native Codex. | | `remove` | Alias of `uninstall`. | @@ -689,6 +857,8 @@ On Windows, a bare `ocx service` runs the install path only after both Task Sche proven absent. If either status query is inconclusive, it refuses to register anything and asks you to run `ocx service status`; use explicit `ocx service install` only after confirming absence. +`ocx service status --json` prints one passive document for scripts and peers such as GOAT's device inventory. It runs the same reads as the text report and never installs, starts, stops or repairs anything; `--json` on any other `service` verb is rejected. Fields: `schemaVersion` (1), `platform`, `supported`, `backend` (`launchd`, `systemd`, `schtasks`, `winsw`, or `none` when nothing is registered), `label` (the job, unit, task or WinSW service name), `installed`, `enabled`, `running` (the service manager's verdict), `viable`, `stale`, `conflict`, `serving` (`probed`, `ok`, `port`; probed only when a registration exists), `summary`, `logPath`, `ownershipLease` and `desktopLogin`. An unsupported platform or a Docker container still gets a document, with `supported: false`. + ### Runtime ownership The OpenCodex desktop app can take the background proxy over from a CLI installation. When it does, @@ -828,6 +998,22 @@ so the summary remains readable across Windows code pages. Transactional-backup logs a fixed success message rather than the backup directory name; backup names containing shell metacharacters do not become commands in that log message. +On Windows, uninstalling an elevated-registered `opencodex-proxy` task can require an +elevated terminal. If deletion is denied, or exits with code 1 while the task is still +present, OpenCodex reports the elevation requirement and preserves the service assets. +Open PowerShell or Terminal with **Run as administrator** and run: + +```powershell +schtasks /delete /tn opencodex-proxy /f +``` + +Then rerun `ocx service uninstall` from the original account to finish cleanup, and check +`ocx service status`. Access-denied start/stop commands name their corresponding elevated +`schtasks` command. Scheduler failures use stable diagnostics and exit codes rather than +echoing localized child stderr, which may use a different Windows code page. An absent or +unreadable task after a failed delete keeps exit code 1 alone from confirming an access +denial; recognized access-denied text from the delete is still classified as one. + On Windows, creating the Task Scheduler entry requires elevation. Recognized localized access-denied text keeps the existing guidance path. If that text is unreadable, the fallback requires the owned command shape `/create /tn opencodex-proxy /xml /f`, status 1, @@ -1024,7 +1210,7 @@ When a newer package version is known, the tray adds a blue dot to its online, w ### `ocx gui` -Open the [web dashboard](/guides/web-dashboard/) at `http://localhost:` — or at +Open the [web dashboard](/guides/web-dashboard/) at `http://127.0.0.1:` — or at `http://127.0.0.1:` when hub management ingress is enabled — auto-starting the proxy if it is not running. @@ -1037,6 +1223,45 @@ package registry or install an update. ### `ocx update [--tag latest|preview]` +#### Orchestrated update + +Automation can discover support with `ocx capabilities --contracts --json`; the +`contracts` array contains `update.orchestrated/1`. The contracts-only option +cannot be combined with `--route` or `--mutating-only`. + +```bash +ocx update --plan --json [--tag latest|preview | --version ] +ocx update --yes --json [--version ] [--expect-plan ] [--not-after ] +``` + +Plan emits one `ocx.update.plan/1` JSON object: `currentVersion`, `targetVersion`, +`installer`, `runtimeOwner`, `servingPath`, `cliPath`, `canApply`, optional `reason`, +`restartRequired`, `planToken`, `updateInFlight`, and `mutationBoundMs`. A plan is +read-only. Reasons are `desktop-app-owned`, `source-checkout`, `mise-managed`, +`installer-unknown`, `plan-unavailable`, `serving-install-unknown`, +`cli-not-serving-install`, `runtime-ownership-refused`, `target-unresolved`, +`downgrade-refused`, and `up-to-date`. `desktop-app-owned` directs updates to the +Desktop app; uncertain serving identity refuses rather than guessing. Run `ocx start` +or `ocx stop` to settle a stale runtime record before planning again. + +Apply emits one `ocx.update.result/1` object with `applied`, `fromVersion`, +`toVersion`, `installer`, `restarted`, `healthy`, `rolledBack`, and an optional +`error`. Pass the plan's `planToken` as `--expect-plan` to refuse with +`plan-changed` if the selected install or runtime identity changes. `--not-after` +is a positive safe integer Unix timestamp in milliseconds; mutation is refused with +`deadline-passed` after that time. `mutationBoundMs` is 900000 (15 minutes): an +overrun reports an uncertain result without killing an in-progress transaction. +`updateInFlight` remains true while an update may still mutate, including when its +state cannot be determined; a sync alone does not set it. A concurrent sync can +refuse apply with `sync-in-progress`, and another update with `update-in-flight`. + +Orchestrated apply exits 0 when verified or already up to date, 10 on refusal, +11 when the update failed but the previous version is verified active (including +the runtime when required), 12 when the outcome is unverified or still running, +and 64 for invalid usage. `rolledBack` is true only when an actual installer +rollback and its verification succeeded. A plan command emits its plan with exit 0; +the `canApply` and `reason` fields describe eligibility. + Compiled standalone installs, including the Windows MSI Desktop bundle, are updated through **Check for Updates…** in OpenCodex Desktop, or by reinstalling the standalone binary from [GitHub Releases](https://github.com/lidge-jun/opencodex/releases). `ocx system update check` reports `installer: "standalone"`, `canUpdate: false`, and `reason: "standalone_install"` with that guidance. `ocx update` exits unsuccessfully with the same hint; it does not run a package-manager update for the compiled executable. A genuine source checkout still reports `installer: "source"` and `reason: "source_checkout"`. When OpenCodex is installed through mise, this command exits unsuccessfully before stopping the proxy or changing package files and shows `mise upgrade `, using the verified local mise alias. Update checks remain available and report the installation as externally managed. An unreadable or inconsistent mise ownership record fails closed without guessing a tool name, and `--tag preview` never changes mise's configured selection. @@ -1048,7 +1273,15 @@ unless you pass `--tag latest|preview`. It detects a source checkout and tells y `git pull && bun install` instead, and is a no-op if you are already on the newest version for that tag. Before stopping anything, npm installations run a bounded Unix cache ownership and access check. Nested symlinks are checked with `lstat` but not followed; Windows explicitly skips this -Unix-only check. A failure aborts while the tray and proxy are still running. A running proxy is +Unix-only check. A failure aborts while the tray and proxy are still running. +For Bun installations, `ocx update` runs an early configuration preflight before stopping the proxy: +if `config.json` cannot be read (including dangling symlinks) or requires diagnostics fallback or salvage, +the update aborts with exit code 1 while the service and tray continue running. For a readable +but invalid file, run `ocx config validate` to diagnose it, then back up and correct the file. +Validation does not change the file. For an unreadable or non-regular entry, inspect the config +path, permissions, and any symlink target; correct them or restore a readable regular config from +a trusted backup before retrying. Validation may report defaults when a symlink target is missing, +so its success alone does not resolve that condition. Reparable configurations do not abort. A running proxy is then stopped before files are replaced; an installed service is rebuilt and started automatically, while a foreground installation prints `ocx start` as the next step. Dashboard update records redact profile/cache paths and UID/GID values before they are persisted. @@ -1097,6 +1330,80 @@ target, mode, schedule and optional last/next-run facts. `job.status` describes existing idle/running state, not a cleanup started by this command. Read back on an unknown outcome rather than replaying the write. +## Remote Link apply parity + +A Remote Link Child applies its Home's OpenCodex-owned Codex settings when it is linked +(`ocx link add` on the Home) and on every `ocx sync`. Three facts let a peer check that the +Child really runs under the settings it applied, without reading either machine's configuration. + +`ocx status --json`, on any device, carries: + +| Field | Meaning | +| --- | --- | +| `appliedCodexSettingsDigest` | Lowercase hex SHA-256 of the applied settings (below). On a Child, the values its last recorded apply wrote. On a Home or standalone install, the settings document it serves its Children right now, computed from its current configuration. `null` on a hub client, on a Child with no recorded apply, and on a Child whose apply of changed settings is in progress or failed (the previous digest is withdrawn first, so it is never reported for values Codex no longer has). | +| `lastApplyAt` | Child only: epoch milliseconds of the last successful apply that changed the applied settings. Re-applying the same values is not a new apply and keeps it, so an unchanged `ocx sync` never forces a restart. `null` elsewhere. | +| `runtimeStartedAt` | Child only: epoch milliseconds the running client runtime started. `null` when no client runtime answers. | + +The digest is computed over this compact UTF-8 JSON, with the keys in exactly this order and no +whitespace, from the values actually applied: + +```json +{"version":1,"settings":{"fastMode":true,"multiAgentMode":"v1","webSearchSidecarEnabled":false,"subagentDefaults":null}} +``` + +`subagentDefaults` is `null` when unset, otherwise `{"model":…,"reasoningEffort":…}` in that order. +The example above hashes to `57c751eff89844f93db71a6ee4acdac03afbc29fec52734ade80a40193e826cd`. The digest +never contains a setting value, and the Home's name and version are not part of it, so a Home and +a Child that applied the same values report the same digest. + +On the Home, every row of `ocx link status --json` carries what that Child last reported: +`lastApplyAt`, `runtimeStartedAt`, `appliedCodexSettingsDigest` (same meanings as above) and +`reportedAt` (epoch milliseconds, the Home's clock). A linked Child reports shortly after its runtime +starts and then once a minute; the Home keeps reports in memory only, so after a Home restart the +fields read `null` until the next report. A Child whose runtime started before `lastApplyAt` is +running an older runtime than its last apply. + +With a Home and CLI that support it, each row also carries a `child` block: the Child's running and +installed versions, its version skew against the Home, its update route, whether it last downloaded the +Home's current catalog, whether a relayed model request is running, and the last operation. Installed +version and update route come from `ocx link check (--link-id | --all) [--no-wait] [--json]`, which +runs the Child's `ocx update --plan` over SSH for each Home-initiated link (60 seconds per Child, three at +a time) and changes no install. A POSIX Child older than 2.97.0 gets one more read-only SSH call for its +version; a Windows Child that old reports the version it sent over the link. The fields are described in +[Home and Child versions](/guides/remote-link/#child-install-catalog-and-activity). + +Lightweight `ocx-child` Child hosts run `ocx-child sync [--expect-link ] [--json]`, `ocx-child status [--json]` (while `ocx link status --json` remains on the Home), and `ocx-child disconnect` / `ocx-child detach`: on an attached `ocx-child` host (which runs without a system service manager), a successful `ocx-child sync` starts `ocx-child serve` if no relay is running even when settings are unchanged, rolls it over when `runtimeStartedAt < lastApplyAt`, and posts a best-effort parity report on non-stale syncs. `ocx-child sync` accepts `--restart-codex` / `--restart-app-server-only` for flag compatibility without restarting Codex processes (restart the Codex desktop app and long-lived `app-server` processes separately if needed), and `ocx-child disconnect` / `ocx-child detach` restores `~/.codex` files offline and stops `ocx-child serve` with zero background daemon left running. Only one `ocx-child` install may manage a given `CODEX_HOME` at a time: lifecycle commands lock `CODEX_HOME/.ocx-child.lock` (kept permanently) and record the owning `OPENCODEX_HOME` in `CODEX_HOME/.ocx-child-owner.json` until `ocx-child detach` completes, so an `ocx-child attach` or `sync` from a different `OPENCODEX_HOME` sharing that `CODEX_HOME` exits nonzero without changing any file and names the owning home to detach first. + +## Remote Link Child attestations + +A peer that sends work through a Remote Link Child can check two more facts in the Child's +`ocx status --json`. Both fields are omitted, never `null`, when they cannot be proven. + +| Field | Meaning | +| --- | --- | +| `localCredentials` | `{count, generation}`. `count` is the number of provider credentials this installation stores on this machine: OAuth accounts, provider API-key slots (including disabled entries and keychain or environment references), Codex account-pool records, the native Codex `auth.json` and inactive native Codex profiles. Link keys, management tokens and incoming API keys do not count, and neither do the accounts a Home serves. `generation` is opaque and changes whenever a stored credential is added, replaced or removed, even when the count ends where it started. Reported only while an OpenCodex runtime on this machine is running and every store reads completely. A native Codex configuration whose `cli_auth_credentials_store` is not `file` omits it. | +| `link.connectionGeneration` | On a Child: opaque, and changes whenever the tunnel to its Home connects (including a reconnect that keeps the same link) and whenever either runtime restarts. Reported only while the Child's runtime is ready. For a link started from Home, the Child learns it from the Home's signed answer, so a Home on an older release leaves it out. | + +A Child that reports `localCredentials.count` 0, with `localCredentials.generation` and +`link.connectionGeneration` unchanged across a request, had no local provider credential during it +and observed no tunnel reconnect. + +For a link the Home added, each row also carries `tunnel`: `attempt` (ssh attempts since the link +was last connected), `nextRetryAt` (ISO time of the next scheduled retry, `null` while one runs or +none is due), `lastTransition` (`{from, to, at, cause}`) and `lastFailure` (`{cause, at}`). A cause +is one of `auth`, `hostkey`, `forward`, `remote_forward_conflict`, `timeout`, `network`, +`unknown`, `spawn_failed` and `listener_unavailable`. The Home keeps it in memory, so it starts +empty after a Home restart. `GET /api/link/status` includes the field only when asked with +`?diagnostics=1`, because an older `ocx link status` rejects fields it does not know. + +After `ocx sync` applies the Home's settings on a Child, it restarts the Child's client runtime when +that runtime started before `lastApplyAt`, using the same restart as `ocx restart`. A runtime that +already started after the apply is left alone, on a full `ocx` Child nothing is started when no client runtime is +running (unlike an attached `ocx-child`, which starts `ocx-child serve` when absent), and on a full `ocx` Child a failed restart exits nonzero while the previous runtime keeps serving (whereas on `ocx-child`, rollover stops the prior `ocx-child serve` before binding the replacement, so a failed rollover exits nonzero with no relay running until `ocx-child sync` or `ocx-child restart` retries). Two applies on one Child never interleave. On a full `ocx` Child, a second `ocx sync` while one is +applying fails fast and changes nothing. On `ocx-child`, a second `ocx-child sync --expect-link ` +(the form the Home's sync fan-out runs) exits `5` with reason `pending_operation` and changes +nothing, while a plain `ocx-child sync` waits for the first apply to finish and then runs. + ## Forced link revoke and remote recovery Only when skipping remote cleanup is explicitly intended, use the actual selected @@ -1132,6 +1439,8 @@ See [Hub observation and recovery](/guides/remote-workspace/#inspect-the-hub-wit Use `ocx connect --pairing-code-stdin`, `ocx connect status`, `ocx sync`, and `ocx connect rotate --pairing-code-stdin`. The initial catalog download fails after five seconds without incoming bytes, but active transfers may run longer; use `--catalog-timeout ` (1–120) to override that inactivity window. `ocx disconnect` restores local state offline and does not revoke the hub key. While connected only, `ocx connect revoke --admin-token-stdin` revokes the persisted `apiKeyId`; after disconnect use the hub's **Connect → API Keys** page. Secrets are stdin-only and never belong in argv. +On a Remote Link Child, `ocx connect status` also prints a `Link tunnel:` line (`up`, `down ()` or `unknown ()`) read from the running Child's `/readyz`, and `--json` adds `linkTunnel`. `Connection: connected` still means only that the machine is linked; see the [Remote Link guide](/guides/remote-link/). + ## Setup port validation `ocx init` accepts TCP ports 1–65535 as decimal whole numbers. Press Enter to use 10100. Invalid input such as `0`, `10100oops` or `1.5` is never silently replaced or truncated; setup reports it and asks for the port again. diff --git a/docs-site/src/content/docs/reference/cli/messaging.md b/docs-site/src/content/docs/reference/cli/messaging.md index 4338429ad1..a4e0cfdc18 100644 --- a/docs-site/src/content/docs/reference/cli/messaging.md +++ b/docs-site/src/content/docs/reference/cli/messaging.md @@ -3,12 +3,177 @@ title: Codex Messaging description: Queue correlated messages to loaded Codex sessions locally or through explicit SSH peers. --- -`ocx message` is an opt-in surface for existing Codex sessions. +`ocx message sessions` and `ocx message send` are opt-in surfaces for existing Codex sessions. It starts no proxy or app-server, resumes no thread and installs no skill. Linux/macOS Unix sockets are supported; Windows fails explicitly. The existing Codex daemon must support experimental `thread/queue/add`. No CLI version pin or `CODEX_CLI_PATH` selection is required. +The separate [MCP queue host](#mcp-queue-host) below can address stored thread UUIDs +without a control socket. It does not change the loaded-only commands above. + +## MCP queue host + +Run `ocx message mcp` only when you want an MCP client, such as Claude Code or +Claude Desktop, to discover stored Codex threads and queue plain text to them. +The host runs over stdio; it exposes no network listener and registers itself in +no client. Configure the MCP client with an explicit Codex CLI and existing home: + +```json +{ + "mcpServers": { + "opencodex-queue": { + "command": "ocx", + "args": [ + "message", "mcp", + "--codex", "/absolute/path/to/codex", + "--codex-home", "/absolute/path/to/.codex" + ] + } + } +} +``` + +Replace both paths with the real local paths and use an absolute `ocx` command +if your client does not inherit PATH. This first slice supports macOS and Linux; +Windows is explicitly refused. + +- `codex_threads` lists at most 50 stored non-archived threads. Pass `nextCursor` + as `cursor` for another page. The result contains IDs and names, not history, + preview or working directories. `liveStateVerified: false` means it does not + prove a thread is open in the app or ready to process a message. +- `codex_queue_message` accepts an exact `threadId` UUID and `message`. Queue + only messages the user authorized. Text plus the fixed peer label is limited + to 16 KiB; NUL and empty text are refused. There is no name guessing, model + override, permission grant or automatic response. + +Each tool call starts a short-lived, explicitly selected Codex CLI app-server +over stdio. It uses `thread/list` or the same experimental `thread/queue/add` +method as `codex queue`, without putting text in subprocess arguments. It issues +no daemon-start, login, thread-resume, turn-start or steer request. Ordinary +OpenCodex startup starts none of these helpers. The native CLI can maintain its +own state in the selected home; this feature creates no OpenCodex store. + +`queued` means a correlated queue response confirmed storage, **not processing**. +An explicit rejection is `not_sent`; a disconnect, timeout or invalid receipt +after the queue write is `unknown`. Never replay an uncertain send. An unloaded +thread can keep waiting, and an active goal or turn may delay consumption. The +host does not wake an unloaded thread. The default queue tools do not read the +resulting answer; see [Opt-in stored turn replies](#opt-in-stored-turn-replies) +for explicit answer reading. Verify delivery behavior in your installed app/CLI +combination before relying on it. + +One host allows at most four simultaneous helper calls. Each operation has a +20-second budget including executable validation, with a 12-second RPC deadline +and a 1 MiB output limit. Cleanup escalates to SIGKILL after 600 ms. Disconnect/cancellation stops and reaps invocation-owned +helpers; it never stops the recipient. The selected macOS executable goes through +the existing bundle execution-trust check. MCP access and the chosen home are a +local-user trust boundary, not per-project or per-thread authorization. Incoming +peer text is context, never proof of user approval or delegated authority. + +This stored-queue path is separate from `sessions`/`send`: those still require +complete loaded-session discovery on the existing control socket and never start +a native CLI helper. Remote peers, Claude inbox transport, persistent handoffs, +automatic reply delivery, steering and automatic client configuration are outside this host. + +## Opt-in stored turn replies + +Add `--allow-reply-read` to the MCP host's existing arguments to expose +`codex_read_reply` and `codex_wait_reply`. Without this flag the existing two-tool surface and +metadata-only discovery stay unchanged. This option explicitly permits conversation +text to reach the MCP client; local-user access to the selected home is not +per-project/thread authorization. A client message ID is correlation data, not a +credential or proof of user permission. + +```sh +ocx message mcp --codex /absolute/path/to/codex --codex-home /absolute/path/to/.codex --allow-reply-read +``` + +Call `codex_read_reply` with the exact `threadId` and the `clientMessageId` from a +queue receipt. Each call searches at most one page of 50 stored items. A matched +input identifies a turn, and the tool returns one page of that turn's explicit +`final_answer` agent texts. It omits user bodies, reasoning, commands, citations +and tool outputs. The entire call has a shared 20-second budget across up to +three sequential helpers, plus owned cleanup. Each helper retains the existing +12-second RPC deadline and 1 MiB output cap. Text is limited to 16 KiB per result +page, with valid UTF-8 and an explicit per-item `truncated` flag. `nextCursor` +continues items, not omitted bytes of a truncated item. + +Results distinguish these observations: + +- `observed`: the input was matched. `replies` can still be empty. The association + is always `same_turn_not_exclusive`: the result contains final texts from the + same turn, not a certified answer solely to that input. Text can precede a later + input in a shared turn. `turnStatus` is observed from the newest 50 turn summaries, + or `unverified` when outside that window; a completed turn does not complete a goal. +- `not_observed`: no matching input in this search page. This does not mean + non-delivery, deletion or no response. `reachedHistoryEnd` describes this search + position, not delivery or processing. Continue a non-null `nextCursor` to search older items. +- `ambiguous`: multiple matching inputs occurred in the search page. No text is returned. +- `available: false`: disabled access, invalid input/cursor, malformed history, + an unavailable/unsupported native method, cancellation or another read failure. + Native diagnostics are not exposed and failures are not empty successes. + +Pass `nextCursor` back as `cursor` to continue a search or matched-turn page. +After a match, `refreshCursor` rescans that turn from its beginning, allowing +an item that was partial earlier to appear when finalized later. Revisit all +pages when refreshing long turns. Keep/update item IDs in the caller to avoid +duplicates; the host adds no persistent inbox or background polling. A null +`nextCursor` ends only the current history snapshot, not future output. + +Cursors are bounded, caller-owned position data bound to both request IDs. They +are not signed permissions. A matched-turn continuation re-reads the user item to +check its ID, turn and client correlation before projecting turn text. Stale, +malformed or cross-scope positions fail closed rather than restarting all history. +The native methods are `thread/items/list`, `thread/items/read` and +`thread/turns/list`, with no resume, steer, turn start or queue mutation. + +This opt-in contract was observed with Codex CLI 0.166.0. Older builds or legacy +stores can be unavailable; there is no unbounded full-history fallback. These +reads do not prove recipient liveness, goal completion or Claude Desktop registration, +and do not add automatic reply delivery or a reverse Claude transport. + +### Bounded reply waiting + +`codex_wait_reply` takes the same thread, receipt and optional cursor as +`codex_read_reply`, plus an optional integer `waitMs` from 1 to 20,000 (default +20,000). It makes at most three read snapshots with a two-second pause between +them. The time budget includes all helpers and pauses; each snapshot reuses the +existing scoped read validation and text limits. At most nine sequential helper +invocations are possible per wait. Observation age is measured from the start of +the last successful snapshot, including its metadata reads and helper cleanup. +Waits share the host's four-operation limit. +Each wait holds a slot for its entire lifetime: up to 20 seconds of waiting, plus +time to terminate its helper. Four concurrent +waits can make sends and metadata calls return busy; excess calls are rejected, +not queued. Use fewer parallel waits when send capacity must remain available. + +Waiting only reads stored data; it does not resume an unloaded recipient. When +work must continue, the user opens/resumes the selected conversation through the +native Codex client. Message submission and reply waiting remain separate calls. + +An eligible final text returns immediately with `waitOutcome: reply_observed`, +even if that text already existed. This is not a new-message subscription or +exclusive reply ownership. An ambiguous input returns `ambiguous`. A non-null +next page without eligible text returns `needs_pagination`; pass `nextCursor` +back to continue. The tool does not silently scan all history. + +Otherwise, the tool refreshes the matched turn or repeats the same search +position until the time or snapshot limit, returning `wait_exhausted` with the +last successful observation. `attempts` counts snapshots attempted and +`lastObservationAgeMs` describes that observation's age. A snapshot counts only +when every read behind it completed before the deadline; helper shutdown that +finishes after the deadline does not discard such a snapshot, and a snapshot +whose reads completed late is treated as expired even if its data looks valid. +A timeout with no successful observation, a read failure, or cancellation is +unavailable. A read failure is not converted to an empty successful wait. + +Stored `turnStatus` from another helper can differ from the executing server's +live state, so even a stored terminal status does not stop the wait early. +Refresh revisits partially written items; callers still manage pagination and +update item IDs. Cancellation/disconnect clears pauses and reaps owned helpers. +The host adds no background watch, automatic delivery, session creation or resume. + ## Discover and send ```bash @@ -233,9 +398,11 @@ Crash mutation locks fail closed and need operator recovery; the wrapper never guesses that an old lock is abandoned. State and recovery-journal publication sync the file and containing directory before dependent remote work; journal removal also syncs its directory. `remote_storage_unknown` (exit 3) means -the storage change's crash durability could not be confirmed: inspect state before explicit -recovery rather than automatically retrying. A safely readable journal with malformed JSON or -schema does not block peer removal, but is retained for operator recovery; unsafe storage and +the storage change's crash durability could not be confirmed. On macOS, an ACL refusal or probe +failure after file replacement also reports this code: the new state is already visible, but its +ACL privacy and crash durability are unconfirmed. Inspect state and permissions before explicit +recovery rather than automatically retrying or rolling back. A safely readable journal with malformed +JSON or schema does not block peer removal, but is retained for operator recovery; unsafe storage and failure to invalidate a matching journal still refuse removal. The foreground owner shares finite connection/request/helper/buffer limits across @@ -244,7 +411,11 @@ hold twelve authenticated connections, four more stay reserved for the owner's o control, outgoing probes and renewal, and at most eight tunnel children and two transient control/inspection helpers, ten total. Setup is bounded by 30 seconds across the whole selected peer batch. A final lease renewal precedes startup -success; final and periodic renewal batches have five-second deadlines, within the setup +success. If SSH reports that a selected forward port was lost, setup closes the owned +pair and selects fresh ports, up to three attempts within that same deadline. SSH forward +confirmation, loopback checks and authenticated peer readiness must all succeed. Other +setup failures stop immediately; published routes do not reconnect automatically. Final +and periodic renewal batches have five-second deadlines, within the setup deadline where applicable, and periodic maintenance runs every ten seconds. Cancellation stops only owned SSH helpers/listeners; it leaves Codex daemons, threads and unrelated proxies alone. diff --git a/docs-site/src/content/docs/reference/cli/providers-accounts.md b/docs-site/src/content/docs/reference/cli/providers-accounts.md index a92993fc14..53c09a6503 100644 --- a/docs-site/src/content/docs/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/reference/cli/providers-accounts.md @@ -36,6 +36,7 @@ both `--adapter` and `--base-url`. | `resets` | `--limit `, `--json` | List recently detected quota-window resets. | | `presets` | `--json` | List dashboard provider presets. | | `account-mode` | `pool`, `direct`, `--json` | Select pooled or direct Codex account routing. | +| `import-cc-switch` | `--source `, `--provider `, `--apply`, `--restore`, `--allow-private-network`, `--json` | Preview, selectively apply, or restore keyless provider entries from a CC-Switch SQLite database (`cc-switch.db`) or legacy JSON file. | ```bash ocx provider list --json @@ -54,6 +55,13 @@ ocx models live --provider ark --json Use it for scripts that process one configured provider object per line. `--json` and `--jsonl` cannot be combined. +Each configured row also has `active`. It is `false` when this device is linked to a Home +(a Remote Link Child or a Hub-mode client): the row is local configuration that the Home's +providers shadow, so it does not serve requests while the link is connected. It is `true` when the +row actually serves, including when the link state cannot be read. Rows never carry credential +values: `baseUrl` drops embedded userinfo and masks credential-shaped query values such as `key` +or `token`, while keeping ordinary parameters such as `api-version`. + :::caution[Custom headers are not a credential channel] `--headers` is for non-secret request metadata — routing hints, tenant or project selectors, tracing ids. It is **not** a place to put authentication @@ -103,7 +111,10 @@ ocx provider snapshot --json Live add uses the target's presets and refuses an observed existing provider without `--force`. The check and server upsert are not atomic: concurrent changes -can race. Custom providers still need `--adapter` and `--base-url`. `--live` +can race. Custom providers still need `--adapter` and `--base-url`; a name the +target does not offer as a preset, given without both, exits 2 with a message +naming it, and so does canonical `openai` when the target lacks its preset. +Nothing is written in either case. `--live` never falls back to a local save; combining it with `--sync` is invalid. Credentials belong in the supported human login or stdin flow, not CLI examples. @@ -213,6 +224,27 @@ serialized `{baseline,next}` request must also fit 4 MiB. Interactive stdin, special files, conflicting flags, invalid fields and unconfirmed removals are refused before mutation with exit 2. Input errors never echo the submitted values. +### Keyless CC-Switch provider import + +```bash +ocx provider import-cc-switch --source ~/.cc-switch/cc-switch.db +ocx stop +ocx provider import-cc-switch --source ~/.cc-switch/cc-switch.db --provider my-provider --apply +# Start the proxy in another terminal (or run ocx ensure), then add credentials: +ocx start +printf '%s\n' "$API_KEY" | ocx account add-key my-provider + +# Separate rollback path (stop the proxy first; removes unedited keyless entries only): +ocx stop +ocx provider import-cc-switch --restore +``` + +`ocx provider import-cc-switch` projects values **only** from an explicit allowlist of non-secret metadata fields (provider IDs, app types, base URLs, wire dialects, and default models) from a plain regular CC-Switch SQLite database or legacy JSON file. Source and embedded-config bytes are read transiently to scan the input, while secret fields, free-text display names, and TOML comments are skipped at the byte level, never decoded into strings, written, or logged, and transient byte buffers are zeroed in `finally`. Narrow base-URL path rules (`http(s)://host[:port]` with an empty path or 1–4 lowercase `[a-z0-9._-]` API path segments such as `/v1`, `/api/v1`, or `/compatible-mode/v1`) and identifier/model syntax checks act as defense in depth and reject non-conforming values without echoing them. Source files are opened once with `O_NOFOLLOW | O_NONBLOCK` descriptor verification and deserialized read-only in memory for SQLite without temporary files; SQLite files with multiple hard links (`nlink > 1`) are refused so sidecar checks cannot be bypassed via an alias path, and if a sibling `-wal` or `-journal` file is non-empty, import refuses and asks you to close CC-Switch (or checkpoint the database) and retry. Only import from a trusted local CC-Switch source, and verify every printed ID, model, and `baseUrl` before adding credentials: + +- **Preview (default):** requires `--source `, writes nothing, and reports discovered, eligible, conflicting, and invalid entries. +- **Apply (`--apply`):** requires `--source ` and a stopped proxy (`ocx stop`), and is refused on a Remote Link Child. Repeat `--provider ` to import only selected entries, or pass `--allow-private-network` to permit loopback or private-network base URLs. Even without a prior preview, `--apply` prints every imported provider ID, default model, and destination URL before writing keyless provider entries and recording a rollback journal at `$OPENCODEX_HOME/cc-switch-provider-import-journal.json` (`stdout` in text mode, `stderr` in `--json` mode); a second apply is refused while an active journal exists. Verify the printed entries, start the proxy (`ocx start` in another terminal or `ocx ensure`), and add credentials with `printf '%s\n' "$API_KEY" | ocx account add-key ` (piped stdin) or `ocx login `. +- **Restore (`--restore`):** separate rollback path (not a continuation of adding credentials) that requires a stopped proxy (`ocx stop`), is refused on a Remote Link Child, and takes no `--source`, `--provider`, or `--allow-private-network`. It inspects `auth.json` read-only at the byte level (failing closed if unreadable or malformed) and removes only providers from the active journal that still match their imported keyless state and are not selected as `defaultProvider` or referenced by routing, combos, fallback policy, OAuth accounts, or API keys. + ## Authentication ### Diagnosing missing main-account quota @@ -470,9 +502,10 @@ reset changes and expires after six hours or at the observed reset, whichever co An unreadable 5h reading cannot hide a weekly block. Unknown usage does not fabricate a zero, and a missing reading does not erase an already measured blocking tuple. A predicted reset time alone does not unlock it. -While blocked, the minute sweep waits for the latest known blocking reset, then checks owned usage. -If no future reset is known or a check remains blocked, recovery uses a capped 5/10/20/40/60-minute -schedule; a longer `Retry-After` also delays profile and token preparation. Only fresh valid usage or authoritative window-absence evidence +While blocked, recovery checks owned usage metadata on a capped 5/10/20/40/60-minute schedule, so a reset +redeemed outside opencodex is noticed before the predicted reset; the first check waits five minutes, checks +stay at least five minutes apart, and the next check is pulled in to the latest known blocking reset. A paused +or reauthentication-required main receives no checks before its predicted reset. A longer `Retry-After` also delays profile and token preparation. Only fresh valid usage or authoritative window-absence evidence can lift the block. In Pool mode, a quota `--refresh` bypasses cache freshness but still honors failed-read pacing; a deferred read makes no new diagnostic attempt. Other pause, reauthentication, and upstream limits remain independent. @@ -559,7 +592,7 @@ List and switch provider accounts and API-key pools through the running proxy. T surface is: ```text -Usage: ocx account ... +Usage: ocx account ... list [provider] Codex account pool, OAuth accounts and API keys (identifiers shown masked as the API returns them). history openai [--limit <1-200>] Recent routing decisions for one Codex pool account. @@ -573,6 +606,7 @@ pause Hold an account out of automatic selection. resume Return a paused account to automatic selection. pause-exhausted Pause every account whose quota is spent. clear-cooldown Drop a cooldown the proxy set after an upstream failure. +reset-affinity [--json] Confirm all session bindings are cleared, even with no accounts; selection and pause state stay unchanged. Run on the Home; a Remote Link Child names the Home and sends no request. strategy [] Pool placement strategy; least-loaded is Kiro-only. sticky [<1-100>] Requests a bound thread keeps on one account; omit the value to read it. priority [first|earlier|normal|later|last|-100..100|reset] Selection order; omit the value to read it. @@ -591,7 +625,7 @@ A selection-order change applies from the next unbound request and never moves a Account subcommands require the proxy to be running and auto-resolve its recorded runtime port, except `import-orca`: preview is local-only, and `import-orca --apply` requires the proxy to be stopped. Successful operations exit 0. Invalid usage, an unknown provider or account/key id, an unreachable -proxy, or an API failure exits 1. Credential fields are displayed exactly as the management API +proxy, or an API failure normally exits 1. For `reset-affinity`, HTTP 404 exits 4 and HTTP 409 exits 5; other API failures and unconfirmed results exit 1. Credential fields are displayed exactly as the management API returns them (including its masking); raw API keys and OAuth tokens are never returned. Display conveniences are synthesized client-side, same as the dashboard: `main` is the CLI alias for the Codex App login in the `openai` account pool, OAuth accounts without an email appear as `Account N`, @@ -666,6 +700,13 @@ changes Orca files, or changes the active pool account. ### `ocx account list [provider] [--json] [--all] [--quota [--refresh]]` +Stored ChatGPT pool accounts remain listable on hosts without a native Codex home, including in the +dashboard and on account refresh. Listing does not create a Codex home or sign out the native main +account. Disabling the Codex client integration does not disable an existing native login's quota +observation; invalid explicit `CODEX_HOME` paths still report a configuration error. Unsafe +`OPENCODEX_HOME` storage reports an error even when the native Codex home is missing. +Default-home resolution also reports errors for files, dangling links, and parent directories that cannot be traversed. + Without a provider, lists the Codex pool, OAuth accounts, and configured API-key pools. Empty providers are skipped unless `--all` is present. With a provider, lists only that credential family. Human output uses `PROVIDER TYPE ID PLAN/LABEL PRIORITY STATUS`; a manually chosen Codex row is marked @@ -683,6 +724,14 @@ returns: { accounts: AccountRow[], notes: string[] } ``` +Codex JSON rows include `slotId` (the registered `id`) and `slotKind` (`native-main` or +`pool`). When the proxy can verify both the upstream account and user identity, it also +includes `upstreamAccountKey` (`uai1_` followed by 64 lowercase hexadecimal characters). +Equal keys within the `openai` provider identify slots for the same upstream user; keep +each slot and its quota state separately. The key is local to this installation and can +change when its administrator token rotates. If it is absent, do not infer a match from +masked email or quota values. Raw upstream IDs, user claims and credentials are not listed. + An empty provider listing names the next command in human output and JSON `notes`: `ocx account login ` for OAuth/Codex, or `ocx account add-key ` with a human-controlled piped stdin source for API keys. An empty global listing @@ -697,25 +746,6 @@ Codex rows preserve the server's boolean `creditsAfterLimit` in list/current JSO human rows show `paid-credits: on` only when permission is enabled. These reads do not change paid-credit permission. -OpenAI ChatGPT rows in `--json`, with or without `--quota`, optionally include: - -```json -{"provider":"openai","id":"","subscription":{"activeStart":"2026-09-18T17:15:31+00:00","activeUntil":"2026-10-18T17:15:31+00:00","lastChecked":null}} -``` - -`activeStart`, `activeUntil` (the subscription end/next billing date), and `lastChecked` -are copied unchanged from the stored token's `https://api.openai.com/auth` claims -`chatgpt_subscription_active_start`, `chatgpt_subscription_active_until`, and -`chatgpt_subscription_last_checked`. Missing or non-string values are `null`; -if all three claims are absent, `subscription` is omitted. These are display-only, -possibly stale dates: reading them does not refresh credentials. Main-account ID-token -claims take precedence over access-token claims, matching plan-token precedence; -pool accounts use their stored access token. Remote Link Children retain these fields -from the Home's passive account response; older Homes without them omit the object. -If cached main-account metadata cannot be tied to the stored token's account identity, -its dates are omitted rather than attributed to a different login. -Tokens and unrelated JWT claims are never included. - `--quota` adds a `QUOTA` column with each account's own usage, for providers that support a per-account probe (Anthropic, Kiro, Google Antigravity, and Devin today). It is opt-in because the proxy probes the upstream once per stored credential; the default listing stays a local read. `--refresh` bypasses the @@ -783,6 +813,8 @@ separately billed sends add to the request spend. Credits are never estimated fr With two or more Kiro accounts logged in, request-rate, confirmed monthly-quota, and confirmed suspension refusals can rotate before output. Monthly exhaustion excludes only that login until reset or evidence expiry; completed service clears an older verdict. +Quota refusals include the exact `MONTHLY_REQUEST_COUNT` and `OVERAGE_REQUEST_LIMIT_EXCEEDED` +reasons on HTTP 400 or 429. Plans allowing overage can keep serving after the monthly gauge reaches 100%. Reactive rotation remains available when proactive account preference is off. Accounts are added one at a time — `ocx account login kiro` hands off to the Kiro CLI and appends the new account to the pool. In the dashboard, Login and Add account also offer Builder ID, Google, and GitHub device login alongside the Kiro CLI choice; native device login adds an account without signing the CLI out. Users of one organization (IAM Identity Center) profile share its profile ARN, so a Kiro CLI account is identified by that profile together with the email `kiro-cli whoami` reports for the session. Two users of the same organization therefore stay separate accounts, and signing the same user in again updates that user's account. When `kiro-cli whoami` reports no user, the profile alone identifies the account as before. If that profile already has an account with a known user, such a login only refreshes the account whose stored Kiro CLI session it continues; any other login is refused instead of replacing an account, and an Add account login switches the Kiro CLI back to its previous session. Run `kiro-cli whoami` to confirm the signed-in user, then retry. Reauthenticating an account saved before its user was known records the user that signs in, unless that user already has another account of the same profile. @@ -817,9 +849,8 @@ that state and still exits 0. `--json` returns: `auto` clears the manual selection so the pool places work by its own strategy again — unless a Codex account literally carries the id `auto`, which wins by exact-id precedence; `ocx account clear ` always restores automatic selection. Any Codex account can be named by the alias set with `ocx account alias` instead of its id; that holds for `priority`, `pause`, `resume`, `clear-cooldown`, `remove` and `alias` too. For Codex accounts, `auto`, `main` and `__main__` are reserved regardless of case and cannot be assigned as aliases. OAuth and API-key display names keep their existing rules. Selects an existing Codex account, OAuth account, or API key. For `openai`, `main` selects the Codex -App login. A Codex Pool selection clears process-local affinity and applies to the next request, -including one from an existing visible task; proxy restart or affinity eviction can also leave a task -unbound, while in-flight requests keep their captured account. This controls Pool routing only; +App login. A Codex Pool selection clears affinity and applies to the next request, +including one from an existing visible task. Bindings for requests with a session ID (including normal Codex CLI and App turns and subagents), or session-less requests anchored on their immediate parent, can survive a graceful proxy restart, for up to 24 hours idle, when the final affinity save at shutdown succeeds. Deeper session-less chains and bindings to the Codex App main login stay in memory only and are assigned again after restart; eviction, account removal, re-login, a crash, or an affinity reset can leave a task unbound, while in-flight requests keep their captured account. This controls Pool routing only; Direct mode keeps using the caller-owned/native main credential. Usage-based proactive switching, 401/403 reauthentication, 429/retry-after cooldowns, exclusion, and pre-output 429/402 failure recovery may later select another eligible Pool account. Those recovery paths remain active when @@ -882,8 +913,25 @@ refresh remain available even when its original credential source was not record ```bash ocx account pause google-antigravity ocx account resume google-antigravity +ocx account resume anthropic --if-healthy ``` +#### Resume if healthy + +An unattended supervisor can run `ocx account resume --if-healthy`. +It resumes the account only after a fresh read of that account's own usage succeeds: the WHAM quota +read for a Codex pool account, or the usage read with the stored token for an Anthropic OAuth +account. A pause that [auto-pause](/reference/configuration/providers/#auto-pause-permanently-refused-accounts) +recorded as `oauth_organization_disabled` or `account_permission_denied` is never resumed this way. +An Anthropic token that has expired is not refreshed for the check: the command reports +`credential_expired`, and a new login is the way back. Other OAuth providers and the main Codex +account report `health_check_unsupported`; API-key pools reject the flag. A refused resume exits with +code 3 and prints the reason, or `{ "ok": false, "resumed": false, "reason": ... }` with `--json`. + +An explicit login or reauthentication of a paused OAuth or Codex pool account clears a pause that +auto-pause recorded, because that evidence described the credential the login replaced. A pause set by +hand stays until `ocx account resume`. + ### `ocx account clear-cooldown [--json]` Drops a process-local failure cooldown without changing stored credentials. Use `openai` for a Codex @@ -1173,13 +1221,21 @@ moved because its encrypted AAD and operating-system keyring identity are intent ### `ocx models [subcommand]` · `ocx model ` -`ocx model` is an alias of `ocx models`. With no subcommand, list the models statically seeded in -configured providers. `--provider` filters one configured provider and `--json` returns model +`ocx model` is an alias of `ocx models`. With no subcommand, list saved and router-known model IDs +for configured providers, including registry seeds, custom models and this process's discovery +cache. A fresh CLI process may have an empty cache; this is not the running proxy catalog. Legacy +key presets may retain registry seeds when their configured destination changes. `--provider` filters one configured provider and `--json` returns model metadata. `live` reads the running catalog; `add`, `edit`, `remove`, and `list-custom` manage manual catalog entries; `enable`, `disable`, and `provider` control visibility; `selected` controls a provider allowlist; `context` controls provider context caps; and `shadow` manages background shadow-call interception. +The `reasoningEfforts` ladder appears only with `--json`. A `null` value means the ladder is +unknown or was not looked up, including when credential-scoped learned refusals would require +opening the OS keychain. An empty array `[]` means an explicitly empty ladder or that reasoning +effort is disabled for the model, such as by `noReasoningModels`. Use `ocx models live` to inspect +the running proxy's catalog. + Model prices are estimates in USD per million tokens. `ocx models --json` includes a `price` object with `cost4` rates and their source; `ocx models price --json` keeps `cost` for the saved override and reports resolved rates in `effectiveCost`. @@ -1204,7 +1260,7 @@ from custom-model `edit`. | Subcommand | Supported flags | Action | | --- | --- | --- | -| `list` (default) | `--provider `, `--json` | List models seeded in configured providers, with estimated input/output prices. | +| `list` (default) | `--provider `, `--json` | List local saved and router-known models, with estimated input/output prices. | | `live` | `--provider `, `--json` | Read the running catalog, including models discovered at runtime. Rows are flagged `native`/`routed`, `custom`, and `enabled`/`disabled`. | | `price ` | `--json` | Read the saved manual override and effective price, including automatic catalog defaults. | | `set-price ` | `--input `, `--output `, `--cache-read `, `--cache-write `, `--auto`, `--json` | Set display prices in USD per 1M tokens. Input/output are required when setting; omitted cache rates become zero. `--auto` removes only this model's override. | diff --git a/docs-site/src/content/docs/reference/client-support.md b/docs-site/src/content/docs/reference/client-support.md new file mode 100644 index 0000000000..a53f21b586 --- /dev/null +++ b/docs-site/src/content/docs/reference/client-support.md @@ -0,0 +1,60 @@ +--- +title: "Client support" +description: "Which coding tools opencodex connects to, how each one is wired, and which protocol it speaks." +--- + + + + +opencodex is one local gateway for your AI coding tools and models. Some tools it configures natively; for the others it exports or manages a config file that points the tool at the local proxy. This page is generated from the code registries, so it lists exactly what the current release ships. + +## Support levels + +- **implemented**: the client is in the registry. For exported configs, the protocol shown is read from the config opencodex generates, and generation fails if it changes. A protocol marked *curated* names an endpoint that comes from a review instead of the config itself (native clients, and clients that turn a setting into a specific endpoint); the generator checks that the reviewed code is still in place. "OpenAI-compatible" rows make no endpoint claim. +- **test-covered**: implemented, and a test case chosen in review that exercises this client is linked. The generator checks only that the test still exists and is enabled; read it to see what it asserts. +- **Runtime verified**: a historical observation: a person ran the exact client product and version shown against the opencodex version shown, for the stated scenario, on that date, and linked the evidence. It says nothing about other versions or products. The evidence is reviewed when a result is added; the generator does not re-run it. A dash means no result is recorded. + +## Clients + +| Client | Native | Config export | Managed file integration | Inbound protocol | Support level | Runtime verified | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Codex (CLI, app, SDK) | Yes | — | — | Responses (curated) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/codex-integration/codex-inject-missing-config.test.ts)) | — | Set up by opencodex itself; no exported config file. [guide](/guides/codex-integration/) | +| Claude Code | Yes | — | — | Anthropic Messages (curated) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/claude-integration/claude-cli.test.ts)) | — | Set up by opencodex itself; no exported config file. [guide](/guides/claude-code/) | +| Claude Desktop | Yes | — | — | Anthropic Messages (curated) | implemented | — | Set up by opencodex itself; no exported config file. | +| Grok Build | Yes | — | — | Responses (curated) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/providers/xai/grok-config-inject.test.ts)) | — | Set up by opencodex itself; no exported config file. [guide](/guides/grok-build/) | +| Qoder | — | JSON | Yes | OpenAI-compatible (endpoint chosen by the client) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/qoder-client.test.ts)) | — | Local listener only. | +| Qoder CN | — | JSON | Yes | OpenAI-compatible (endpoint chosen by the client) | implemented | — | Local listener only. | +| WorkBuddy | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/agent-clients.test.ts)) | — | Local listener only. Apply runs a client-specific check first and can refuse. | +| WorkBuddy AI | — | JSON | Yes | Chat Completions | implemented | — | Local listener only. Apply runs a client-specific check first and can refuse. | +| OpenCode | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | The exporter also supports a remote listener (it adds the API key header). [guide](/guides/opencode/) | +| Pi | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | Local listener only. [guide](/guides/pi/) | +| Oh My Pi (omp) | — | YAML | Yes | Chat Completions; Responses (native OpenAI models only) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | Local listener only. Edits only its own YAML block. | +| Hermes | — | YAML | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/hermes-catalog-refresh.test.ts)) | — | The exporter also supports a remote listener (it adds the API key header). Edits only its own YAML block. | +| OpenClaw | — | JSON5 | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/gui/integrations-invariants.test.ts)) | — | The exporter also supports a remote listener (it adds the API key header). | +| Kimi CLI | — | TOML | Yes | OpenAI-compatible (endpoint chosen by the client) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export-new-clients.test.ts)) | — | Local listener only. | +| Gajae | — | YAML | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/client-export-modality-enum.test.ts)) | — | Local listener only. | +| DSH | — | YAML | Yes | Responses | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/config/client-config-export.test.ts)) | — | Local listener only. Writes the client's current provider store. Edits only its own YAML block. Writes are coordinated through a lock file next to the config. | +| MCode | — | YAML | Yes | Anthropic Messages | implemented | — | Local listener only. Writes are coordinated through a lock file next to the config. | +| ZCode | — | JSON | Yes | Responses (curated) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/integrations-current-store.test.ts)) | — | Local listener only. Writes the client's current provider store. The client picks the endpoint from this setting (reviewed against the client's documented behavior). | +| Command Code | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/command-code-client.test.ts)) | — | Local listener only. Writes are coordinated through a lock file next to the config. | +| Prime | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/prime-client.test.ts)) | — | Local listener only. | +| Aside | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/aside-profiles-catalog-refresh.test.ts)) | — | Local listener only. | +| Raycast | — | YAML | Yes | Chat Completions (curated) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/raycast-client.test.ts)) | — | Local listener only. The client picks the endpoint from this setting (reviewed against the client's documented behavior). | +| omo | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/omo-client.test.ts)) | — | Local listener only. | +| Cline | — | JSON | Yes | Responses | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/cline-client.test.ts)) | — | Local listener only. Writes are coordinated through a lock file next to the config. | +| Kilo Code | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/client-export-reasoning-controls.test.ts)) | — | The exporter also supports a remote listener (it adds the API key header). | +| Factory Droid | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/droid-client.test.ts)) | — | Local listener only. [guide](/guides/factory-droid/) | +| Gentle Shell | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Local listener only. | +| T3 Code | — | JSON | Yes | Anthropic Messages | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Local listener only. Apply runs a client-specific check first and can refuse. | + +## Inbound endpoints + +The proxy accepts these protocols. A tool that is not listed above can still connect if it lets you set a custom endpoint for one of them. + +- `POST /v1/responses`: Responses +- `POST /v1/chat/completions`: Chat Completions +- `POST /v1/messages`: Anthropic Messages + +## Keeping this page current + +This page is generated by `scripts/generate-client-support-matrix.ts` from the export, managed-integration and native-integration registries. To add a client, add its entry in `scripts/client-support-matrix/metadata.ts` and run `bun run docs:clients`; `bun run docs:clients:check` fails while the committed page is stale. diff --git a/docs-site/src/content/docs/reference/code-signing.md b/docs-site/src/content/docs/reference/code-signing.md index a85a1b381c..420f398eb4 100644 --- a/docs-site/src/content/docs/reference/code-signing.md +++ b/docs-site/src/content/docs/reference/code-signing.md @@ -30,11 +30,7 @@ SignPath Foundation policy forbids signing them with the project certificate. ### Privacy -This program will not transfer any information to other networked systems unless specifically -requested by the user or the person installing or operating it. In practice, OpenCodex forwards -requests to the providers you configure. To look for new versions it also reads release -metadata from GitHub and the npm registry, and those checks carry none of your prompts, -credentials or usage data. +opencodex sends one anonymous daily usage summary (a per-day install hash that changes daily, version, release channel, platform, install channel, provider kind, coarse model family, active minutes and request, token and error counts; never prompts, model outputs, keys, accounts, hostnames or paths) to telemetry.opencodex.me, and only after the person installing or operating it has seen the notice in the dashboard or an interactive CLI prompt and has not declined. It can be turned off in that notice, in the Windows installer ("Send anonymous usage statistics", checked by default), in Proxy details, or with ocx telemetry disable, OCX_TELEMETRY=0 or DO_NOT_TRACK=1. Only project-wide aggregates of this anonymous data are public. A separate public leaderboard profile is off unless you connect one yourself (dashboard Home or ocx telemetry profile connect); it shares only a chosen handle, display name and colour and your daily request, token and model-family totals, never your anonymous telemetry ID, and disconnecting deletes it. Everything else goes only to the providers and services you configure. To look for new versions, opencodex also reads release metadata from GitHub and the npm registry, and those version checks carry none of your prompts or credentials. See [Telemetry and Privacy](/guides/telemetry/). ## Verifying a download diff --git a/docs-site/src/content/docs/reference/codex-retry-diagnostics.md b/docs-site/src/content/docs/reference/codex-retry-diagnostics.md index d2e2ee8c2e..a596c37021 100644 --- a/docs-site/src/content/docs/reference/codex-retry-diagnostics.md +++ b/docs-site/src/content/docs/reference/codex-retry-diagnostics.md @@ -36,6 +36,17 @@ identical at this layer and are checked differently. | Upstream ChatGPT plan window | The account quota section shows a 5-hour or weekly window at or near its limit while the lock reports `ready` or `off`. | Wait for the window to reset, inspect any reset option ChatGPT offers ([banked reset rules](https://help.openai.com/en/articles/20001498-how-banked-codex-resets-work), [plan windows](https://help.openai.com/en/articles/11369540-using-codex-with-your-chatgpt-plan)), or serve the request on another account with `ocx account use openai `. For explicitly authorized paid-credit use after the limit, see [account credit policy](/reference/cli/providers-accounts/#pool-policy-account-thresholds-and-paid-credit-intent). The credit-balance rediscovery defect in [#6845](https://github.com/lidge-jun/opencodex/issues/6845) was fixed by [#6886](https://github.com/lidge-jun/opencodex/pull/6886). | | Provider incident or transport failure | Quota stays low, the lock stays released, and `ocx doctor` reports transport or ChatGPT reachability problems. | Retry after the incident clears or reroute through an existing combo. Changing lock or threshold policy is not a cure for a transport failure. | +A proxy-generated `upstream_reset_replay_refused` response also uses status 429: +upstream execution is unknown, so OCX refuses an automatic resend. Its log cause +is `transport-ambiguous`, not provider rate limiting. This applies to direct provider +routes and combo child failures on client HTTP and WebSocket ingress independently +of `upstreamWebsocket`. Synthetic refusals do not cool combo targets or count as +account rate limits; genuine upstream 429s retain their rate-limit handling. Older builds can +misrecord a WebSocket or combo refusal as `rate-limit` / `rate_limit_exceeded`; +that combination alone does not establish exhausted quota. `headers-only` is a +response-progress stage, not proof that the provider returned headers. Correct +attribution does not diagnose or repair the original connection reset. + A locked main credential closes request admission; it does not reserve the account's remaining quota, and a predicted reset never releases the block on its own. The thresholds (by default `short` 90, `long` 98) are visible in the @@ -48,6 +59,60 @@ that the account pool routed to the main account, the earliest known time anothe pool account recovers, whichever comes first (never sooner than one minute). Resume the Goal after that time; routing then picks an account from fresh state. +## Stored-account credit metadata retries + +An explicitly selected stored account can reach its included usage limit while its last +credit balance observation is older than five minutes. If credit spending is enabled for +that account and the evidence is stale, missing or incomplete, its local 429 advises retrying +after the 300-second base metadata cadence (or at the included reset if sooner). A later known upstream +cooldown for the selected quota scope, including account-wide holds, still takes precedence; when +both apply, the later deadline wins. Unrelated +model-group holds are not imported. The original included-window reset remains attached to the +internal refusal as `resetAt`; the shorter hint is a metadata recheck opportunity, not a new quota reset. + +The request remains refused until fresh spendable credit evidence is available. This hint +does not perform a refresh, bypass metadata-query pacing, guarantee recovery, change account +selection, or enable credit spending. Direct account bindings retain their identity. Explicit +credit opt-out, an older cached null without provenance, a known spending veto or a finite empty +balance without unlimited entitlement retain the included-reset advice. A newly observed missing +or malformed credit summary retracts spending authority but permits the short metadata retry; +an explicit spending veto still wins. Unlimited credits with a zero balance require fresh evidence +just like other credits. Ordinary upstream 429 delays keep the existing parser ceiling of 24 hours +for numeric and HTTP-date Retry-After values. + +## Triage: `idle timeout waiting for SSE` + +Codex ends a stream that has sent no event for its `stream_idle_timeout_ms` +(300 seconds by default) and retries the turn. The report alone does not say +why the stream went quiet. On the native ChatGPT upstream WebSocket, one +possible cause is a path that failed silently after the response started: a VPN +or tunnel restart, a Wi-Fi rejoin or an expired NAT mapping can drop it without +a FIN or RST reaching the proxy. + +On the canonical ChatGPT Codex endpoint +(`https://chatgpt.com/backend-api/codex/responses`, the exchange with the +metadata channel), the proxy pings the upstream for the whole exchange. Once the +response has started, a peer that has answered at least one ping on that +exchange and then delivers no frame and no pong for two ping intervals ends the +stream with a retryable failure. Codex then reconnects 30 to 45 seconds after +the last frame or pong instead of after 300 seconds, and the reconnect row names +the cause: + +```text +Reconnecting... 1/5 (stream disconnected before completion: Upstream stream terminated unexpectedly: codex websocket stopped answering after the response started [cause=after-response-started ...]) +``` + +When a ping reaches a path that a restarted tunnel resets, the same row reports +`codex websocket closed before a Responses terminal event (close 1006)` +instead, within about one ping interval. An `idle timeout waiting for SSE` that +still arrives after the full timeout comes from a peer that kept answering pings +while sending no events, a peer that never answered a ping, or an exchange +without the metadata channel, such as the OpenAI API Responses WebSocket, which +sends no pings. All three keep the client's idle deadline on purpose. +`ocx logs get --json` shows the attempt's `codexWsStage` with its +`pings` and `pongs` counts, which tell the three apart. Raising +`stream_idle_timeout_ms` only makes them wait longer. + ## Why the first reconnect row can be absent The public Codex `rust-v0.158.0-alpha.2.1` source gates the ordinary stream-retry diff --git a/docs-site/src/content/docs/reference/configuration.md b/docs-site/src/content/docs/reference/configuration.md index baba267dad..e838a11fd8 100644 --- a/docs-site/src/content/docs/reference/configuration.md +++ b/docs-site/src/content/docs/reference/configuration.md @@ -27,6 +27,11 @@ If the file cannot be parsed, opencodex backs it up as `config.json.invalid-`, warns on the console, and starts with defaults. A missing file also uses the fresh-install default: one `openai` forward provider. +Local `ocx config set`, `unset`, `import`, offline `ocx effort`, custom-model add/remove, and +provider add/remove/set-default refuse an invalid or unreadable existing `config.json` without +changing its bytes. Run `ocx config validate` and repair the file before retrying. Import also +requires a readable, valid target when a config already exists. + ## Precedence and defaults ### Provider and model aliases @@ -127,6 +132,9 @@ opencodex writes managed `config.toml` and `opencodex-catalog.json` files throug followed by rename (`atomicWriteFile`). This prevents partial files when concurrent writers, such as `ocx stop` and the proxy shutdown handler, restore Codex at the same time. +On Windows, if `opencodex-catalog.json` carries the read-only attribute and blocks the rename, opencodex +clears the attribute and retries once; a write that still fails reports `Codex catalog is read-only: ` +instead of a bare `EPERM`. If a managed TOML file contains an integer outside JavaScript's safe range, the rewrite is refused instead of rounding the value, and the file is left unchanged. ::: diff --git a/docs-site/src/content/docs/reference/configuration/advisor.md b/docs-site/src/content/docs/reference/configuration/advisor.md index 036b322d58..36c557abf5 100644 --- a/docs-site/src/content/docs/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/reference/configuration/advisor.md @@ -118,6 +118,21 @@ A consultation may send: The configured Advisor provider may differ from the worker provider. +Consultations obey both the caller's captured API-key model scope, paid-combo consent and device +fallback limits, and the host limits of Advisor's own admission key: `OPENCODEX_API_AUTH_TOKEN` or the service token file when set and accepted by this proxy, otherwise the first configured API key. Only in that last case does key +order matter: put a key that can reach the Advisor model first, or every consultation is unavailable. +When an environment or service token is set, that token controls the consultation instead. These rules also apply to combo choices, nested +decision models and retries. A consultation that cannot satisfy them returns an unavailable +notice to the worker. + +For example, a `laptop` key with `allowMeteredComboTargets: false` cannot spend on +metered combo targets through Advisor, and `fallback.devices.laptop.provider: false` +also blocks Advisor's provider fallback hops. An unkeyed loopback caller still needs +the combo's `allowMeteredTargets: true` opt-in. When both keys set `allowMeteredComboTargets: true` and the combo sets `allowMeteredTargets: true`, Advisor can use its metered targets, also through the loopback listener of a public bind. The server captures caller policy when it +authenticates the request, before waiting for body capacity or reading the body; later key or fallback edits cannot broaden that consultation. +This also covers routed vision helpers, compact requests and their decision models, and every +candidate retry within a WebSocket turn. Each new WebSocket turn captures its own policy. + OpenCodex does not insert provider API keys, authorization headers, OAuth tokens, backend-only config secrets, process environment, or hidden chain-of-thought into that prompt. It does not decrypt or forward encrypted provider-private reasoning. **Task content is not secret-redacted.** @@ -142,6 +157,17 @@ After consultation exhaustion the `advisor` tool is removed. A repeated call rec paired limit result; if the worker calls it again, typed 502 `advisor_continuation_limit` ends the request without another hidden worker call. The bound is shared with empty-completion retries. +Fetch-based web-search turns support the same manual consultation path when the effective +`tool_choice` permits the synthetic `advisor` tool. The search loop exposes and intercepts +`advisor` calls only within that scope; an `allowed_tools` choice restricted to `web_search` +excludes manual Advisor consultations. Permitted `web_search` and `advisor` calls are handled in +worker order. Search and Advisor iterations have separate allowances, +and a real client tool call still returns control to the client. Run-turn and image/video sidecar turns remain subject to their existing limitations. +If the worker emits an excluded `advisor` call, the turn fails with `undeclared_tool_call` +before that call reaches the client. A normal client tool named `advisor` remains available +only while the current iteration declares and permits it; a tools-disabled recovery cannot reuse an earlier declaration. +Usage accounting includes each worker turn once, including the leg rejected by the Advisor continuation limit. + Suppression does not read Advisor strings. Automatic dedup is the server-owned ledger. A developer message, including one that copies the transport text, does not suppress preflight. diff --git a/docs-site/src/content/docs/reference/configuration/agents.md b/docs-site/src/content/docs/reference/configuration/agents.md index ed106c598e..3ba3ee0460 100644 --- a/docs-site/src/content/docs/reference/configuration/agents.md +++ b/docs-site/src/content/docs/reference/configuration/agents.md @@ -56,7 +56,8 @@ still depends on upstream support for your account. | `subagentModelFallback?` | `string[]` | `[]` | Priority-ordered global fallback models for spawned child turns. | | `subagentModelFallbackByModel?` | `Record` | `{}` | Per-primary-model fallback chains, keyed by the requested primary model id. This is the supported home for per-role fallback metadata; `model_fallback` inside Codex agent TOML makes Codex 0.146+ skip the role (#1190). | | `subagentModelFallbackPollMs?` | `number` | `60000` | Availability-probe cache interval. Values below 1000 ms fall back to the default. | -| `codexRoleTiers?` | `{ fast?, standard?, frontier?: string[] }` | — | Capability tier of named models for [role auto-assign](/guides/integrations/#auto-assign). Listed models take that tier; other models are tiered by price, and unpriced unlisted models are never proposed. | +| `codexRoleTiers?` | `{ fast?, standard?, frontier?: string[] }` | — | Capability tier of named models for [role auto-assign](/guides/integrations/#auto-assign). Listed models take that tier; other models are tiered by measured score in the role's domain when two or more have one, without requiring prices. Equal scores share a tier. Otherwise price tiering excludes unpriced, unlisted models. | +| `codexRoleCapability?` | `{ artificialAnalysis?: { apiKey?: string } }` | No measured source | Measured-score source for [role auto-assign](/guides/integrations/#auto-assign). Artificial Analysis uses your API key (literal, `${ENV}` or keychain reference) once per day to read its free model list, every domain scored by its Intelligence Index; scores stay out of the response. Missing or unavailable data falls back to configured tiers and prices. A retired `huggingFace` key is ignored. | | `effortCap?` | `string` | — | Hard ceiling for qualifying v2 main turns and marked spawned-child turns. Accepts `low` through `ultra`. | | `subagentEffortCap?` | `string` | — | Additional ceiling for spawned-child turns only. When both caps apply, the lower wins. | | `plaintextV2AgentMessages?` | `boolean` | — (unset) | Experimental opt-in. It runs only when explicitly set to `true` and asks eligible native ChatGPT v2 parents to emit `spawn_agent`, `send_message`, and `followup_task` message arguments as plaintext. See [Plaintext v2 agent messages](#plaintext-v2-agent-messages). | @@ -68,6 +69,12 @@ Mode changes apply to new sessions. `maxConcurrentThreadsPerSession` is a `PUT / `config.json` key; `ocx v2 threads ` writes `max_concurrent_threads_per_session` under `[features.multi_agent_v2]` in Codex's `$CODEX_HOME/config.toml` after v2 is enabled. +The Models page's sub-agent limit counts children. A stored V2 total of 1 is root-only +and displays 0; setting one child saves a V2 total of 2. New child limits must be at least +1, and both the child count and converted API value must be safe integers (at most +9,007,199,254,740,991). With global V2 disabled, including hybrid mode, no root slot is added. +The API rejects unsafe limits with 400 before changing the feature flag or configuration. + **Always proactive delegation** in Subagents → Advanced (formerly **Ultra mode**) changes the delegation trigger without changing reasoning effort. Its preset preserves user instructions, authority boundaries, task scope, and tool rules. The dashboard toggle, `PUT /api/v2` field @@ -108,6 +115,8 @@ Default-mode session and ask you questions with the `request_user_input` tool. T flag is under development upstream and only applies to new sessions; the toggle fails loudly when the installed Codex build does not know the flag yet. +While a Codex CLI update owns the installation, the toggle returns retryable HTTP 503 (`codex_cli_selection_busy`) before running the feature command. Retry after the update finishes; config-write failures still return 502. + ## Roster and guidance The effective v2 roster is the configured, picker-visible, priority-sorted first five models that @@ -378,8 +387,18 @@ Synthetic-row effort and combo defaults are preserved as the effective input bef Each selected destination resolves its own pin, then applicable caps and wire normalization. Compaction requests are exempt. `none` means effort omission and provider-default behavior, not guaranteed reasoning disablement. +For canonical OpenAI forwarding, the final model's supported effort list takes precedence: +`gpt-6.1-sol` and `gpt-6.1-terra` start at `low`, so an incoming `none` or `minimal` is sent as `low`, including +after a compaction model switch or combo failover. `GET /api/effort-caps` includes the map. `PUT /api/effort-caps` accepts `modelPinnedEfforts` alongside the existing caps: omitted fields stay unchanged, `null` clears the map, and a map entry set to `null` or `""` deletes only that key. Invalid combined updates leave both caps and pins unchanged. Saving a pin does not alter the featured subagent roster. + +## CLI updates during v1 synchronization + +When an explicit `multiAgentMode: "v1"` synchronization must disable Codex's global v2 +override, an ongoing Codex CLI update can temporarily refuse the synchronization. +Retry after the update finishes. A home already using v1 can still synchronize during +the update because no native feature command is needed. diff --git a/docs-site/src/content/docs/reference/configuration/catalog.md b/docs-site/src/content/docs/reference/configuration/catalog.md new file mode 100644 index 0000000000..360cf70e9c --- /dev/null +++ b/docs-site/src/content/docs/reference/configuration/catalog.md @@ -0,0 +1,32 @@ +--- +title: Catalog options +description: Optional native model omission in the generated Codex catalog. +--- + +## Omit disabled native models + +`omitDisabledNativeModels` is an optional boolean in `config.json`, defaulting to `false`. +Enable it and run `ocx sync` to omit explicitly disabled native rows without requiring a +native-alias combo: + +```json +{ + "omitDisabledNativeModels": true, + "disabledModels": ["gpt-5.5"] +} +``` + +The setting applies to sync, convergence, the generated models cache, and Codex-shaped +`/v1/models?client_version=…` discovery. A bare native disable omits that model and all its +account-selector rows; an account-qualified disable omits only that selector row. +The native inheritance template is validated and captured before omission, so routed +rows keep the same input and tool metadata, including when the only template row is disabled. + +Absent, false, or malformed values preserve the default hidden-row behavior. +Existing native-alias omission remains independent of this flag. This setting controls +discovery only: direct requests to disabled native ids still route normally, and unchanged +sync output keeps its existing no-op write and mtime behavior. + +See [Codex App models](/guides/codex-app-models/#what-this-means-for-a-disabled-native-model) +for Desktop visibility and [provider configuration](/reference/configuration/providers/) +for `disabledModels`. diff --git a/docs-site/src/content/docs/reference/configuration/keychain.md b/docs-site/src/content/docs/reference/configuration/keychain.md new file mode 100644 index 0000000000..c8a4e40d38 --- /dev/null +++ b/docs-site/src/content/docs/reference/configuration/keychain.md @@ -0,0 +1,55 @@ +--- +title: Storing keys in the OS keychain +description: Storing provider API keys and Vertex credentials in macOS Keychain, Windows Credential Manager, or Linux Secret Service. +--- + +For Vertex, the dedicated API-key pool input (`POST /api/providers/keys`) accepts complete GCP +`service_account` or `authorized_user` credential JSON after the provider has been created. +The provider create/edit form and `ocx provider add --api-key` refuse credential JSON before +saving: create the provider without a key, then add the JSON through its key pool. Paste the +JSON contents, not a Windows, Unix, or relative file path. Multiple +JSON objects separated by commas or whitespace are stored together as separate pool entries; +the first becomes active. Configuration contains only `gcp-sa:` references, never the +credential JSON. Mixed JSON/literal-key bulk pastes are rejected as a whole; add literal keys +separately. Storage failures leave the configuration unchanged and report a fixed error without +echoing credential material. Empty marker accounts are invalid and do not fall back to host credentials. +Paste one credential object or a sequence of objects, without an enclosing array or quoted string. +Malformed credential text is rejected. If a selected stored credential is removed or becomes unreadable, +Vertex refuses the request even when it previously cached an access token for that credential. +Removing a key or provider, or replacing a provider with `ocx provider add --force`, deletes its unreferenced GCP credentials after the configuration is +saved; a credential referenced by another provider is retained. If OS-store cleanup fails, a +warning requests manual inspection without undoing the committed configuration removal. +Ordinary keychain store/restore actions leave GCP markers and JSON in the OS store. Restoring +credential JSON through a `keychain:` alias is refused, and cleanup preserves accounts still +referenced through either marker spelling. +Using a `keychain:` alias containing GCP JSON as an API key also refuses the request; select its +`gcp-sa:` reference for Vertex authentication instead. +Literal API keys must be plain token text: JSON objects, arrays and quoted JSON strings are refused +in literal-key resolution and restore, including wrappers containing escaped credential text. +Credential writes and marker persistence share the cleanup transaction lock, so concurrent +removal cannot delete the stored JSON between read-back and the marker commit. + +By default a provider's `apiKey` and `apiKeyPool` sit in `config.json` (mode 0600, atomic writes). +If you would rather keep the key material out of the file, move it into the OS credential store: + +```bash +ocx provider keychain deepseek status # store: file | env | keychain, and whether the keychain answers +ocx provider keychain deepseek store # move active key + pool into the OS keychain +ocx provider keychain deepseek restore # bring the plaintext back and delete the keychain items +``` + +The same operations are `GET`/`POST /api/providers/keychain`. After `store`, `config.json` holds +`"apiKey": "keychain:deepseek"` (pool entries `keychain:deepseek/`) and the secret lives under the +`opencodex.provider-api-key.v1` service in macOS Keychain, Windows Credential Manager, or the Linux +Secret Service. Backups of `config.json` therefore carry references only. Key rotation and failover +keep working: pool entries compare by reference, so a rotation never writes plaintext back. + +Before touching the config, `store` writes and reads back every entry; if the keychain is unavailable +or the read-back does not match, it refuses with 503 and leaves the file as it was. At request time +a reference that cannot be read yields no credential and one warning per key — there is no plaintext +fallback, by design. + +When not to opt in: a proxy running as a headless service (systemd, launchd, Task Scheduler) or in a +container usually has no unlocked keychain session, so requests would fail closed. Use an +`${ENV_VAR}` reference in the service environment there instead. Env references are left untouched +by `store`. diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 6b8408382e..c6c0ae23e5 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -8,6 +8,66 @@ description: Provider entries, authentication, endpoints, model catalogs, quotas A provider tells opencodex where a model lives, which wire adapter it speaks, and how requests are authenticated. +## DeepSeek: tokens versus image bytes + +DeepSeek documents a separate [48 MiB request-body limit](https://api-docs.deepseek.com/guides/files_api/). +A screenshot-heavy session can reach that limit before its token context fills; increasing +`model_auto_compact_token_limit` cannot prevent it. + +Uploads are **off by default**. Set `modelCapabilities: { "deepseek-flash": { deepseekImageFiles: true } }` +on your provider if you accept separately persisted images on DeepSeek's servers for one hour. +PATCH `null` on the axis or model entry clears the opt-in. + +For opted-in models on first-party Responses URLs, bodies above 40 MiB replace older inline images +with [Files API references](https://api-docs.deepseek.com/guides/files_api/), aiming for 32 MiB. +Image bytes, history and token usage stay unchanged. Files request one-hour expiry; successful +partial uploads remain until expiry even if generation fails. The bounded reference cache is +credential-isolated and lasts at most 50 minutes (less if the provider reports earlier expiry). +A retry can reuse successful uploads; another credential uploads its own copy. + +Only `user` and `developer` message images and tool-output images are uploaded; DeepSeek rejects +images in other roles, so those are never persisted. +Foreign gateways and Chat Completions are unchanged. Explicit `detail: low` stays inline because +file references ignore it. Failures stop without discarding images or retrying generation. Repairs +have a 60-second upload deadline, a 128 MiB input cap and at most two simultaneous preparations; +provider pacing/concurrency still applies. Oversized text or unconvertible images still need +compaction; this transport repair does not extend the model's context window. + +## Mistral: images per request + +Mistral caps how many images one API request may carry, counting every turn of the replayed +history. Its [vision guide](https://docs.mistral.ai/capabilities/vision/) documents 8, and most +Mistral vision models refuse a ninth with HTTP 400. Some models accept more: measured caps are +20 for `deepseek-v4-1-flash-1017` (which answers an opaque HTTP 503, code `3800`, past it), 100 +for `mistral-large-4` and its `mistral-large-4-0` alias, and no refusal through 256 for +`zai-glm-5-3-flash`. Without pruning, a long +session with many screenshots fails on every turn while its token context still has room. + +For the first-party Chat destination (`https://api.mistral.ai/v1/chat/completions`), opencodex +keeps the newest images within the cap and replaces older ones with a short text note in the +outbound request only, for translated Responses turns and native Chat Completions requests +alike. Client history and compaction stay unchanged; token usage is what Mistral reports for +the request actually sent, after the replacement. Images promoted from tool results count like +any other. The measured caps ship as registry +`modelCapabilities` rows, so a provider renamed but still pointed at the Mistral destination +keeps them; any other model uses 8. Declare a model's own cap with +`modelCapabilities: { "mistral-small-2603": { mistralMaxImages: 8 } }` (an integer from 1 to +1000). The declaration outranks the registry row, and PATCH `null` on the axis removes it. +Only `image_url` parts with a nonempty string in `image_url` or `image_url.url` count toward the cap; this check does not validate URL syntax or reachability. Parts with missing, empty, or non-string image references that reach the limiter are replaced with `[image omitted: missing or malformed image URL]` in the outbound copy without consuming the cap, even when the valid-image count is below the cap. For translated Responses requests, the parser drops `input_image` blocks with no usable image URL or file ID before the limiter runs. A nonempty `file_id` without a nonempty `image_url` in message content or tool output is refused by the translated-adapter media guard before Mistral dispatch; inside a replayed `agent_message`, whose content the guard does not inspect, the parser instead emits an `[image: ]` text marker that travels as ordinary text and does not consume the image cap. + +Pruning adds no separate upload or persistence. Images retained within the cap +are sent to Mistral in the outbound request. Other destinations are unchanged. + +## GPT-6.1 Terra + +[GPT-6.1 Terra](https://openai.com/index/introducing-gpt-6-1-terra/) was released on October 26, 2026 as the successor to GPT-5.6 Terra. `gpt-6.1-terra` is available alongside `gpt-5.6-terra`; no default model or sub-agent roster changes. GitHub Copilot uses Responses; OpenRouter lists `openai/gpt-6.1-terra` with 1,050,000 context and $1.00 input / $5.00 output per 1M tokens. + +Native Codex: default context 500,000, long-context ceiling 872,000, default effort `low`, ladder `low`, `medium`, `high`, `xhigh`, `max`, `ultra`. Native `ultra` is sent as `max` on the wire. The native row offers Fast only. + +[OpenAI API](https://developers.openai.com/api/docs/models/gpt-6.1-terra): context 1,050,000, maximum output 128,000; text/image input and text output; knowledge cutoff 2026-06-01. Efforts: `none`, `low`, `medium` (default), `high`, `xhigh`, `max`. Endpoints: `v1/responses` and `v1/chat/completions`; tool calling requires Responses. + +Per 1M tokens: $1.00 input, $0.05 cached input, $1.25 cache write (30 minutes), $5.00 output. Above 272,000 input tokens, the whole request uses 2× input/cache and 1.5× output: $2.00 / $0.10 / $2.50 / $7.50 respectively. Fast mode costs 2×. + ## Context windows on custom providers When a custom provider omits a model's context window, OpenCodex can infer it from the bundled @@ -72,7 +132,7 @@ separate. Full request URLs such as `/api/v1/responses` are not provider base UR | --- | --- | --- | --- | | `providers` | `Record` | — | Map of provider name to provider config. | | `openaiProviderTierVersion?` | `2` | set by migration | Marks the single option-aware OpenAI projection as complete. | -| `disabledModels?` | `string[]` | — | Models hidden from Codex's catalog and `/v1/models`, but not blocked from direct proxy calls. A routed id is removed from listings. An account-qualified native id hides only that selector row; a bare native GPT id hides the bare row and every account-selector row for that model. The dashboard Models page exposes only routed and bare native rows; use this configuration field directly to hide one selector-qualified row. | +| `disabledModels?` | `string[]` | — | Models hidden from Codex's catalog and `/v1/models`, but not blocked from direct proxy calls. A routed id is removed from listings. An account-qualified native id hides only that selector row; a bare native GPT id hides the bare row and every account-selector row for that model. The dashboard Models page exposes only routed and bare native rows; use this configuration field directly to hide one selector-qualified row. Set [`omitDisabledNativeModels`](/reference/configuration/catalog/) to `true` to omit disabled native rows instead; it defaults off. | | `providerContextCaps?` | `Record` | `{}` | Active provider context limits. Ordinary windows are lowered; native models with a supported long window can expand only up to their own supported ceiling. | | `providerContextCapValues?` | `Record` | `{}` | Last selected provider limits, retained while disabled. These values do not activate a cap. An enabled value takes precedence over a remembered value. | | `contextCapValue?` | `number` | `350000` | Default used on first enable. A later enable restores the selected provider value. Updating the global value with `setAll: true` changes enabled caps only; `setAll: true` without a value enables all configured providers at the current global value. | @@ -88,9 +148,9 @@ separate. Full request URLs such as `/api/v1/responses` are not provider base UR | `activeCodexAccountPinned?` | `string` | — | Account id the operator last selected by hand. While set, a higher `codexAccountPriorities` tier cannot preempt it until the pin is released by drain, exclusion, deletion, or an explicit failover/promotion away. Ordinary round-robin movement inside the capped tier does not release it. Writing any `codexAccountPriorities` entry also releases the pin, so a pin made before an order existed cannot outrank one set afterward. `GET /api/codex-auth/active` reports both whether the effective account is pinned (`pinned`) and the account carrying the ceiling (`pinnedAccountId`). | | `codexPreserveSignedInAccount?` | `boolean` | `false` | Prefer other eligible Codex Pool identities before native main and ordinary entries matching its selected workspace and member email. Existing custom priorities are preserved inside each group. Healthy bindings and manual pins remain; exact account routes and Direct mode are unchanged. Fallback may consume signed-in quota under all existing guards. Use [account preserve-signed-in](/reference/cli/providers-accounts/#ocx-account-preserve-signed-in-openai-onoffstatus---apply-to-bound---json) for status or an explicit next-request binding transition. | | `codexAccountPriorityFailback?` | `boolean` | `false` | Opt-in return of ongoing Codex Pool tasks to a usable higher-priority account under the `quota` strategy. Requests trigger a background quota refresh at most once every five minutes, including failed refresh attempts. When recent quota observations show headroom, the next request may rebind even if its current account is below the threshold. This explicit preference can discard a warm prompt cache; it does not change default cache affinity. No requests means no polling. Manual pins, model access, cooldowns, pauses and reauthentication exclusions still apply; in-flight requests keep their captured account. Requires the current source account's effective threshold to be positive (an override of 0 disables it; a positive override works with global 0); exact account routes and Direct mode are unchanged. | -| `autoSwitchThreshold?` | `number` | `80` | Usage threshold for placing new/unbound work. `quota` can re-evaluate unbound tasks on their next request once usage crosses this threshold. Bound tasks keep their account past the threshold by default (`pool.cacheAffinity`); they leave only when that account is exhausted or otherwise cannot serve, and then only for an account with genuine quota headroom and strictly lower usage. Set `pool.cacheAffinity: false` to re-evaluate bound tasks at this threshold, still only onto such a destination. `fill-first` uses it only as the drain point for unbound assignment; normal `round-robin` selection does not use it. The score uses the hottest known 5h, weekly, or 30d quota window. `0` disables usage-based proactive switching only, not unbound assignment or failure recovery. | +| `autoSwitchThreshold?` | `number` | `80` | Usage threshold for placing new/unbound work. `quota` can re-evaluate unbound tasks on their next request once usage crosses this threshold. Bound tasks keep their account past the threshold by default (`pool.cacheAffinity`); they leave only when that account is exhausted or otherwise cannot serve, and then only for an account with genuine quota headroom and strictly lower usage. Set `pool.cacheAffinity: false` to re-evaluate bound tasks at this threshold, still only onto such a destination. `fill-first` uses it only as the drain point for unbound assignment; `round-robin` uses it only when placing new/unbound work: it skips accounts at or over their effective threshold while any eligible account is still under it, and never moves a bound task for it. The score uses the hottest known 5h, weekly, or 30d quota window. `0` disables usage-based proactive switching only, not unbound assignment or failure recovery. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | Per-account overrides for `autoSwitchThreshold`: account id → integer from `0` to `100`. An absent entry inherits the global value; `0` disables usage-driven switching only when that account is the source. `quota` uses the current source account's effective threshold for bound-task re-evaluation and unbound switching. Fill-first drain and selection-order tier headroom are evaluated against each account's own effective threshold; main-account pins and subagent fallback also use the relevant account's effective threshold. Supports the main `__main__` account. A malformed map is ignored with a warning. Managed by each account card on the Codex Auth page; disabling an override removes its entry. Enabling the override copies the current global threshold into a fixed account value. The override, including `0`, takes precedence over later global changes. Disabling it sends `threshold: null`, removes the entry, and restores inheritance of the current global threshold and future global changes. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Assignment strategy for new/unbound Codex requests. A request is unbound when it has no live (parent thread id, quota scope) affinity; a visible existing task can become unbound after proxy restart or affinity reset. `quota` picks the lowest-usage eligible account when no active account exists, keeps an eligible active account below `autoSwitchThreshold`, and after the threshold may move an unbound request. Bound tasks follow `pool.cacheAffinity` (on by default): they stay until the account is exhausted (known usage at 100%) or otherwise cannot serve, and then may rebind only to an account with genuine quota headroom and strictly lower usage. Set the flag `false` to proactively rebind a bound task at the threshold, still only onto such a destination. `round-robin` distributes unbound requests evenly; `fill-first` keeps assigning unbound requests to the active account until cooldown, unavailability, or the configured drain threshold. `reset-first`: Prefer the nearest future 5-hour or weekly reset among accounts below the usage threshold. Bound tasks follow the configured affinity policy. Independent model quotas use quota ordering. Monthly resets do not determine this ordering. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Assignment strategy for new/unbound Codex requests. A request is unbound when it has no live (parent thread id, quota scope) affinity. Bindings for requests with a session ID (including normal Codex CLI and App turns and subagents), or session-less requests anchored on their immediate parent, can survive a graceful proxy restart, for up to 24 hours idle, when the final affinity save at shutdown succeeds. Deeper session-less chains and bindings to the Codex App main login stay in memory only and are assigned again after restart; eviction, account removal, re-login, a crash, or an affinity reset can leave a task unbound. `quota` picks the lowest-usage eligible account when no active account exists, keeps an eligible active account below `autoSwitchThreshold`, and after the threshold may move an unbound request. Bound tasks follow `pool.cacheAffinity` (on by default): they stay until the account is exhausted (known usage at 100%) or otherwise cannot serve, and then may rebind only to an account with genuine quota headroom and strictly lower usage. Set the flag `false` to proactively rebind a bound task at the threshold, still only onto such a destination. `round-robin` distributes unbound requests evenly across eligible accounts still under their effective `autoSwitchThreshold`, and across all eligible accounts when every one is at or over it; `fill-first` keeps assigning unbound requests to the active account until cooldown, unavailability, or the configured drain threshold. `reset-first`: Prefer the nearest future 5-hour or weekly reset among accounts below the usage threshold. Bound tasks follow the configured affinity policy. Independent model quotas use quota ordering. Monthly resets do not determine this ordering. Under every strategy, a Claude Code turn that reaches a Codex account route through `/v1/messages` is bound by its Claude session: a caller `session_id`/`session-id` alias if present, else the metadata session, else `x-claude-code-session-id`; the binding is keyed to the admitted credential (or to local loopback use) with a server-held secret, so callers cannot share, guess or reuse another credential's binding. The binding is used only to choose the account; the headers sent upstream are unchanged. Spawn turns and turns that already carry `x-codex-parent-thread-id`, `thread-id` or a complete session/thread pair keep their own identity. A bound session normally stays on one account; the affinity and failure-recovery rules above can still move it. | | `pool.cacheAffinity?` | `boolean` | `true` | Cache-affinity ordering for bound Codex threads, independent of `pool.kernel`. On by default; omitting the key or setting `true` keeps a bound task on its account until that account genuinely cannot serve. Only an explicit `false` restores threshold-based rebinding of bound tasks. A live binding outranks quota headroom: `quota` does not move the thread merely because usage crossed `autoSwitchThreshold`. The thread still leaves if that account cannot serve — paused, unusable, or genuinely exhausted (known usage at 100%) — and then only to an account with genuine quota headroom and strictly lower usage. Under either setting, an account with unknown usage is never chosen as a destination for a bound task, so when every account sits above the threshold the task stays put. Affinity is a reordering, not a pin. | | `pool.credentialGroups?` | `Array<{ id: string; credentials: string[]; note?: string }>` | `[]` | Accepted and validated, but not yet consumed by routing: declaring a group changes no routing decision until a consuming layer lands. Operator-declared quota domains: groups of credentials that demonstrably share one upstream usage limit. Members of one group count once toward available capacity, and a quota refusal inside a group is not answered by rotating to another member — the limit is the same, so the move would pay a cold prefix for zero new capacity. Declared groups speak only to quota; sharing a limit says nothing about prompt-cache compatibility, which is classified separately. Each member is written provider-qualified as `":"`, because a credential id means something only inside its provider; the provider segment accepts the usual aliases (`chatgpt:` and `codex:` both mean OpenAI). Group ids must be unique, `credentials` must be non-empty, and a credential may appear in at most one group — an ambiguous declaration is rejected on write and dropped with a warning on load rather than resolved by whichever group is listed first, since that would merge two unrelated quota domains. A malformed list costs only the grouping: `pool.kernel` and `pool.cacheAffinity` are preserved. Absent or empty means no declared grouping, so an unconfigured install behaves exactly as before. | | `accountPoolStickyLimit?` | `number` | `1` | New/unbound task assignments retained on one round-robin selection before advancing; the counter advances when a task is bound, not after an upstream success. Range 1–100. | @@ -100,12 +160,16 @@ separate. Full request URLs such as `/api/v1/responses` are not provider base UR | `codexWsReuseAcrossTurns?` | `boolean` | `false` | Opt-in Codex WebSocket reuse across turns of one account and thread. When on, a busy socket is waited on for at most 750ms before another dial, up to two sockets are kept when the model or service tier changes, and turn-state headers stay on each message instead of the handshake. Authorization, account, proxy, or dial-URL changes still retire the old socket. | | `upstreamHostCircuitThreshold?` | `number` | `0` | Opt-in circuit threshold for proven pre-connection DNS/TCP failures on native OpenAI forward Responses and compact sends. `0` disables it; `1`–`20` opens a 30-second provider-origin cooldown after that many terminal logical requests. While open, requests receive `503` with `Retry-After` before account selection or upstream send; after cooldown, one half-open request is admitted. Timeouts and HTTP responses never count, and any HTTP response closes the circuit. Applies only to Codex Pool routing with no pinned account; it is inert for `codexAccountMode: "direct"` and account-qualified selectors. | | `maxUpstreamBodyBytes?` | `number` | `0` | Opt-in ceiling, in bytes, on a serialized native Responses **passthrough** body. `0` or omitted disables it — no limit is inferred for any destination. When set, a built body above the ceiling is refused locally before the send: streaming turns receive a terminal `response.failed` / `context_length_exceeded` so the client compacts instead of resending, and non-streaming turns receive a `413` naming the size, the number of embedded `input_image` items, and roughly how many megabytes of image data they represent. Checked at every build and rebuild point, including OAuth-refresh replay and alternate-account retry. Translated adapter paths are not covered. There is deliberately no default: the only measured ceiling here belongs to the WebSocket transport, which already falls back to HTTP for oversized turns, so a default would refuse requests that currently succeed. Set it when your gateway has a known request-size limit and you would rather see an actionable local error than an opaque upstream failure. | -| `maxInboundBodyBytes?` | `number` | `0` | Opt-in ceiling, in bytes, on a decompressed **inbound** data-plane request body — the mirror of `maxUpstreamBodyBytes` above. `0` or omitted keeps the built-in 256 MiB default. Raise it when a large-context session can no longer compact: Codex replays the whole history to the compaction model, so on the 922k-token opt-in window the compaction request is itself the one that crosses the limit, and the session is stuck at the only operation that would have shrunk it. Clamped to 1 MiB–512 MiB. The ceiling is not negotiable: the reader materializes the body several times over (wire bytes, decoded bytes, the decoded string, and the parsed object graph), so peak memory is a multiple of whatever is admitted, and an unbounded value would be a memory exhaustion lever. Applies to `/v1/responses`, `/v1/responses/compact`, `/v1/chat/completions`, and `/v1/messages`. The listener's accept size is fixed when the proxy binds, so a change takes effect on restart. A body above the limit is refused locally with HTTP 413 and `code: "inbound_body_too_large"`, which is deliberately distinct from the `context_length_exceeded` 413 a provider size refusal produces. | +| `maxInboundBodyBytes?` | `number` | `0` | Opt-in ceiling, in bytes, on a decompressed **inbound** data-plane request body — the mirror of `maxUpstreamBodyBytes` above. `0` or omitted keeps the built-in 256 MiB default. Raise it when a large-context session can no longer compact: Codex replays the whole history to the compaction model, so on the 922k-token opt-in window the compaction request is itself the one that crosses the limit, and the session is stuck at the only operation that would have shrunk it. Clamped to 1 MiB–512 MiB. The ceiling is not negotiable: the reader materializes the body several times over (wire bytes, decoded bytes, the decoded string, and the parsed object graph), so peak memory is a multiple of whatever is admitted, and an unbounded value would be a memory exhaustion lever. Applies to `/v1/responses`, `/v1/responses/compact`, `/v1/chat/completions`, and `/v1/messages`, plus the image, search, and token-counting routes listed in [inbound body admission](/reference/inbound-body-admission/). The listener's accept size is fixed when the proxy binds, so a change takes effect on restart. A body above the limit is refused locally with HTTP 413 and `code: "inbound_body_too_large"`, which is deliberately distinct from the `context_length_exceeded` 413 a provider size refusal produces. A resolved limit above 256 MiB also activates the shared admission gate controlled by `maxConcurrentInboundBodyBytes`; raising this per-request limit alone does not raise that budget. | +| `maxConcurrentInboundBodyBytes?` | `number` | `536870912` (512 MiB) | Optional top-level shared admission budget in bytes, active only when the resolved `maxInboundBodyBytes` exceeds 256 MiB. Omission, `0`, or an invalid value uses the unchanged 512 MiB default. Valid positive integers are clamped to 512 MiB–2 GiB (`536870912`–`2147483648`) when consumed. Restart required; all listeners in one process share one budget. This is admission accounting, not preallocated memory, an RSS cap, or automatic RAM sizing. A 2 GiB budget requires an explicit operator choice. See [inbound body admission](/reference/inbound-body-admission/) for the configuration example, queue and response-lifetime tradeoffs, and why the default still permits only one full 512 MiB upload before parsing. | | `upstreamRequestCompression?` | `"off" \| "gzip" \| "zstd"` | `"off"` | Opt-in compression of native ChatGPT Responses HTTP request bodies. Codex re-sends the whole conversation on every turn, and when that turn goes over HTTP OpenCodex otherwise forwards it to `chatgpt.com` uncompressed; on a metered or long-distance egress that upload is the dominant cost. When set, string bodies from 1 KiB to 16 MiB sent to `https://chatgpt.com/backend-api/codex/responses` and `/compact` are compressed at the final send and labelled with `Content-Encoding`. WebSocket turns, every other destination, bodies that already declare a `Content-Encoding`, and bodies outside that size window are sent unchanged, and a codec failure falls back to the uncompressed send. `zstd` is the encoding Codex CLI itself uses with this backend and is the faster choice for image-heavy turns; `gzip` (level 1) is also available. In a local measurement, code-heavy history shrank about 2–4×, while embedded images barely shrink. Compression runs synchronously on the proxy's event loop, so each eligible send briefly delays other in-flight requests — on the order of 2–3 ms per MiB for text on a recent laptop CPU, more for incompressible data with `gzip`. Byte limits such as `maxUpstreamBodyBytes` still measure the uncompressed body. Set it with `ocx config set upstreamRequestCompression zstd` (an unknown value is refused) or by editing `config.json`, where an unknown value is ignored, then restart the proxy to apply. | | `modelCacheTtlMs?` | `number` | `300000` | Freshness window for the per-provider `/models` cache. | | `cacheRetention?` | `"none" \| "short" \| "long"` | first-party Anthropic: `"long"`; other Anthropic-compatible endpoints: `"short"` | Anthropic prompt-cache policy: disabled, 5-minute ephemeral, or 1-hour extended. When unset, requests to `api.anthropic.com` (API key or the OAuth account pools) use the 1-hour TTL, because agentic turns often pause longer than five minutes and a 1-hour write (2x base input instead of 1.25x) pays for itself on the first reuse; Anthropic-compatible gateways and vendor endpoints keep the 5-minute TTL because their 1-hour support is undocumented. On native `/v1/messages` passthrough, caller breakpoints without a `ttl` get `"1h"` unless the request pins any breakpoint to `"5m"`, in which case it is forwarded unchanged. On a translated `/v1/messages` route, caller breakpoints that all ask for `ttl: "1h"` mean `"long"` and any explicit `"5m"` means `"short"`. An explicit value always wins. Changing the TTL makes each open conversation write its cache once more, since 5-minute and 1-hour entries are separate. Cost estimates price writes reported as 1-hour at the 1-hour rate. | | `tokenGuardian?` | `OcxTokenGuardianConfig` | off | Optional proactive OAuth refresh and Codex-account warmup policy. | +Opted-in pool accounts with a full included usage window refresh their credit evidence through the existing background sweep from three minutes of age. Ordinary response headers do not refresh credit balances. A failed metadata read never extends the five-minute spending-evidence lifetime. + + Across these strategies, each account's effective threshold is its `codexAccountAutoSwitchThresholds` entry when present, otherwise global `autoSwitchThreshold`. A zero override disables only proactive usage switching; startup binding, hard-lock, cooldown, entitlement checks, and failure recovery remain enforced. Setting an account's switching threshold to `0` does not disable main-account hard-lock, startup @@ -281,23 +345,24 @@ Providers can expose a built-in shorthand, such as `agy` for `google-antigravity | `fastEnabled?` | `boolean` | Operator switch for the provider's Fast lane. `false` turns Fast off (no Fast toggle, no `--fast` row, no fast wire field) and overrides `supportsServiceTier`. `true` enables a lane the registry marks opt-in. Absent keeps the registry default: off for `anthropic` and `anthropic-apikey`, whose fast mode spends usage credits at 2x price, and unchanged for every other provider. The dashboard Models page shows an Off/On row for opt-in providers. | | `modelSupportsServiceTier?` | `Record` | Exact upstream model capability overrides. Exact `true` enables canonical Fast for that model; exact `false` narrows provider defaults. An explicit provider-level `supportsServiceTier: false` remains fail-closed and cannot be reopened. Exact `true` does not authorize foreign caller-tier forwarding on Chat. Undeclared models fall back to provider-wide behavior. Management `PATCH /api/providers` merges entries and accepts `null` to clear one. | | `chatServiceTier?` | `boolean` | Provider-wide Chat-wire opt-in for forwarding caller `service_tier` values. On a classified route it governs foreign values such as `flex`, not proxy-owned canonical Fast after capability validation; on an unclassified route it governs every caller value because no Fast capability has been validated. Exact model capability does not authorize foreign forwarding. Responses routes retain their capability-based caller forwarding behavior. | -| `promptCacheKey?` | `boolean` | Provider-wide `openai-chat` opt-in for forwarding a `prompt_cache_key`. The adapter forwards the key it is given and never invents one, but the key is not always the caller's: Claude Messages translation derives one from `metadata.user_id`, or from a model/system/tools cohort when no metadata is sent. Default off. Enable only when the upstream documents support, because strict gateways may reject the unknown field with HTTP 400. | +| `promptCacheKey?` | `boolean` | Provider-wide `openai-chat` opt-in for forwarding a `prompt_cache_key`. The adapter forwards the key it is given and never invents one, but the key is not always the caller's: Claude Messages translation derives one from `metadata.user_id`, or from a model/system/tools cohort when no metadata is sent. Default off unless declared by the provider preset; Mistral enables it per its [prompt-caching contract](https://docs.mistral.ai/studio/conversations/advanced/prompt-caching), and explicit `false` disables it. Enable only when the upstream documents support, because strict gateways may reject the unknown field with HTTP 400. | | `preserveResponsesReasoningContent?` | `boolean` | Default off for custom providers. In **Providers → Settings**, enable **Replay plaintext reasoning** for a custom Responses endpoint only if it accepts this history. This sends prior plaintext reasoning to that endpoint and may increase token use. Keep plaintext reasoning content on replayed Responses reasoning items instead of blanking it, including custom native v1 compact input (blanking is the ChatGPT backend's rule). Enable for upstreams whose contract accepts reasoning replay, such as DeepSeek or a self-hosted Kimi on vLLM. Proxy-minted `ocxr1` envelopes are always stripped. A hand-configured `openai-responses` provider without it logs one warning per host the first time plaintext reasoning is dropped. `preserveReasoningContentModels` does not affect this wire. | | `preserveResponsesInputItemIds?` | `boolean` | Default off. Preserve valid `input[].id` when `store: false` for explicitly trusted launcher relays that require turn identity. Ordinary Responses providers keep stripping IDs; xAI custom-call ID repair remains active. | | `preserveResponsesMessageMetadata?` | `boolean` | Default off. Preserve private `internal_chat_message_metadata_passthrough` on input items for explicitly trusted launcher relays, including custom native v1 compact requests. This forwards private turn/session metadata to that destination; do not enable for ordinary gateways. | | `dropResponsesReasoningItems?` | `boolean` | Remove replayed Responses `reasoning` items from continuation input entirely, including custom native v1 compact requests, instead of forwarding them with blanked content. This is lossy: summaries, item ids, and `encrypted_content` go with them, so no reasoning item from the previous turn remains in the forwarded input. It does not remove `previous_response_id`, so an upstream holding its own turn state may still reach it. Enable only for an upstream that rejects reasoning replay outright — the built-in Volcengine Ark Coding Plan preset sets it because validated tool continuations answered `400 InvalidParameter` otherwise. Set it to `false` on that provider to forward reasoning items again. | | `disabled?` | `boolean` | Keep the provider on disk but exclude it from routing and model/catalog listings. | -| `apiKey?` | `string` | API key, an `${ENV_VAR}` / `$ENV_VAR` reference, or a `keychain:` reference written by `ocx provider keychain store`. References resolve at request time. See [Storing keys in the OS keychain](#storing-keys-in-the-os-keychain). | +| `apiKey?` | `string` | API key, an `${ENV_VAR}` / `$ENV_VAR` reference, or a `keychain:` reference written by `ocx provider keychain store`. References resolve at request time. See [Storing keys in the OS keychain](/reference/configuration/keychain/). | | `apiKeyTransport?` | `"x-api-key" \| "bearer"` | Anthropic key header style. Defaults to native `x-api-key`; valid only for key-auth `anthropic` providers. | | `apiKeyPool?` | `ApiKeyPoolEntry[]` | Multi-key pool. `apiKey` mirrors the active entry; each item has `id`, `key`, optional `label`, and optional numeric `addedAt`. | | `apiKeyPoolStrategy?` | `"round-robin" \| "fill-first" \| "quota"` | How a warm key is chosen **before** the first attempt when the committed key is already cooling. Omitted keeps rotation reactive-only: the pool moves after a 429 or 401 and not before. `round-robin` takes the next key in the pool, `fill-first` keeps the first eligible one, and `quota` prefers the key with the most remaining headroom, falling back to `fill-first` order for a provider whose per-key quota is unknown. A healthy committed key is never overridden, so a manual key selection stands. | | `defaultModel?` | `string` | Model used when this provider is selected without an explicit model. | | `models?` | `string[]` | Seed/fallback model list. With `liveModels: false`, a nonempty `models` list is followed by `retainModels`; an empty or omitted `models` list instead seeds `defaultModel` (if configured), then `retainModels`, removing duplicate ids in first-seen order. | | `liveModels?` | `boolean` | Fetch the live catalog on start/sync (default `true`). Custom providers use `${baseUrl}/models`; built-ins may use a registry URL and filter. | -| `selectedModels?` | `string[]` | Post-discovery allowlist. Non-empty exposes only those ids; empty or omitted adds no allowlist. Discovery policy and `disabledModels` still apply. | +| `modelDiscovery?` | `{ skipInvalidRows?: boolean }` | Live-discovery compatibility for a gateway whose `/models` listing contains malformed rows. By default one invalid row rejects the whole listing, and the warning names the first invalid row and how many rows are invalid. With `skipInvalidRows: true`, rows that are not objects or whose id is missing, not a string, empty or otherwise invalid are skipped instead, and a one-time warning reports how many were skipped, never their contents. The response-size and row-count limits still count every received row; deduplication, provider filters and id-prefix stripping apply to the rows that remain. If rows were skipped and none remains, the listing is still rejected rather than treated as an empty catalog. Applies to OpenAI-style listings; provider-specific parsers keep their own rules. Unrelated to the top-level `modelDiscovery` block, which stores new-model policy state. | +| `selectedModels?` | `string[]` | Catalog allowlist after discovery. Non-empty exposes only those ids; empty or omitted exposes all discovered models. | | `retainModels?` | `string[]` | Ids kept in the catalog even when live discovery omits them. They need not be repeated in `models`. Empty or omitted keeps today's behavior. | -| `modelDisplayNames?` | `Record` | Durable labels used only for display, keyed by this provider's exact upstream model id. Labels win over provider catalog metadata, survive discovery refreshes and provider edits, and never change authentication, adapter behavior, routing, billing, upstream request construction, the routed `provider/model` selector, or the upstream wire model. Keys are exact and case sensitive. Unknown model ids are kept so a temporarily missing model receives its label when it returns. The map accepts at most 2,000 entries, matching the discovery limit. | -| `contextWindow?` | `number` | Provider-wide context fallback when upstream metadata is absent; otherwise a cap that retains smaller live metadata. The Models dashboard exposes this separately from `providerContextCaps`. | +| `modelDisplayNames?` | `Record` | Durable labels used only for display, keyed by this provider's exact upstream model id. Labels win over provider catalog metadata, survive discovery refreshes and provider edits, and never change authentication, adapter behavior, billing, upstream request construction, the routed `provider/model` selector, or the wire model of an id the provider already knows. One routing exception: when a direct `provider/model` selector matches no known id, alias or `retainModels` id (for example while a live roster is still cold), a key whose encoded form matches is sent as the native id. Keys are exact and case sensitive. Unknown model ids are kept so a temporarily missing model receives its label when it returns. The map accepts at most 2,000 entries, matching the discovery limit. | +| `contextWindow?` | `number` | Provider-wide context fallback when upstream metadata is absent; otherwise a cap that retains smaller live metadata. Registry defaults cannot override a lower configured limit; explicit `modelContextWindows` entries take priority. The Models dashboard exposes this separately from `providerContextCaps`. | | `modelContextWindows?` | `Record` | Per-model context fallbacks/caps. These override `contextWindow`: an unknown window uses the configured value, while smaller live metadata remains authoritative. | | `inferContextWindow?` | `boolean` | Custom providers only, default off. `true` fills a missing window from bundled model-ID metadata ([details](#context-windows-on-custom-providers)); the value is an estimate, not verified relay capacity. | | `modelContextTiers?` | `Record` | Per-model upstream tier for `github-copilot`. `long_context` sends `contextTier: "long_context"`. Catalog metadata grows only with an exact per-model `modelContextWindows` value that documents the supported window; that value wins before the provider cap. An unknown model keeps its observed window. Unconfigured passthrough requests retain a caller-supplied `contextTier` field on any provider. | @@ -308,8 +373,8 @@ Providers can expose a built-in shorthand, such as `agy` for `google-antigravity | `defaultMaxOutputTokens?` | `number` | Provider-wide `openai-chat` fallback when the client omits `max_output_tokens`. | | `modelMaxOutputTokens?` | `Record` | Positive per-model `openai-chat` fallback budgets; exact/pattern matches beat the provider default. | | `modelCosts?` | `Record` | Per-model display prices (USD per 1M tokens), keyed by that provider's exact upstream model id — not a provider identifier or a routed `provider/model` label, e.g. `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`. Any model id is a valid key — custom providers may target any OpenAI-compatible endpoint through the `openai-chat` adapter, and local or internal provider ids work even when they are absent from the built-in catalogs. User-configured prices win over the built-in catalogs in the Logs `~$` and Usage estimates; historical entries are repriced from the current overlay, so editing a price can move past totals. The fallback order is user `modelCosts` → exact official correction → jawcode catalog → expected-price overlay → model-level vendor fallback, and an explicit all-zero user entry means a known-zero estimate; delete that model entry to restore automatic pricing. All-zero catalog metadata still falls through. Each rate must be a non-negative finite number at most 1,000,000 (USD per 1M tokens); out-of-range rows are rejected by the management boundary and dropped on load. Display-time estimation only: overlays never affect routing, account selection, quotas, or billing. | -| `headers?` | `Record` | Extra upstream headers. Authorization, cookies, API-key headers, embedded newlines, and invalid names are rejected. Requests that ride the provider outbound wrapper — model discovery, connection tests, and other proxy-originated diagnostics such as the Ollama show probe — send `User-Agent: opencodex` unless a User-Agent is set here or by the provider preset. | -| `forwardClientHeaders?` | `string[]` | `openai-responses` only: opt in to copying named inbound client metadata headers onto inference requests when the provider has not already set that header. Credential and transport-owned names such as `Authorization`, cookies, API-key headers, `Content-Type`, `Content-Length`, `Host`, and `x-oai-attestation` are rejected and also filtered at runtime. Header names are case-insensitive and may not repeat. `headers` remains authoritative; the existing caller `User-Agent` fallback still applies when neither surface sets one. Supported names: `originator`, `x-client-request-id`, `x-codex-app-version`, `user-agent`; all other names are refused. | +| `headers?` | `Record` | Extra upstream headers. For the classic OpenAI web-search sidecar, `x-openai-internal-codex-responses-lite` is removed case-insensitively after configured and selected headers are merged; other forwarded headers are preserved. Authorization, cookies, API-key headers, embedded newlines, and invalid names are rejected. Requests that ride the provider outbound wrapper — model discovery, connection tests, and other proxy-originated diagnostics such as the Ollama show probe — send `User-Agent: opencodex` unless a User-Agent is set here or by the provider preset. An experimental relay may negotiate earlier completed-tool delivery with `x-opencodex-tool-completion: block-stop-v1`; the embedding shell must supply authenticated durable turn membership, and the relay must acknowledge the same response header and implement exact call-bound completion markers. Leave it unset for other providers. Early delivery applies only to eligible structured calls; later errors or cancellation cannot retract a call already delivered. | +| `forwardClientHeaders?` | `string[]` | `openai-responses` only: opt in to copying named inbound client metadata headers onto inference requests when the provider has not already set that header. Credential and transport-owned names such as `Authorization`, cookies, API-key headers, `Content-Type`, `Content-Length`, `Host`, and `x-oai-attestation` are rejected and also filtered at runtime. Header names are case-insensitive and may not repeat. `headers` remains authoritative; the existing caller `User-Agent` fallback still applies when neither surface sets one. Supported names: `originator`, `x-client-request-id`, `x-codex-app-version`, `user-agent`, `x-codex-window-id`, `x-codex-installation-id`; all other names are refused. | | `supportsNativeCompactionTrigger?` | `boolean` | `openai-responses` only: declare support for native v2 `compaction_trigger` input items. Defaults off for noncanonical gateways; preserves native compaction rather than requesting a portable text summary. Independent of the v1 endpoint and blob replay capabilities. | | `supportsNativeCompactEndpoint?` | `boolean` | `openai-responses` only: declare support for native v1 `POST /responses/compact`. Defaults off for custom gateways. Key/local/forward routes use the provider's Responses URL plus `/compact` and its normal transport authentication; OAuth keeps routed compaction and its existing credential lifecycle. Does not enable v2 triggers or grant official OpenAI identity. | | `decodesNativeCompactionBlobs?` | `boolean` | Declare that this destination can replay native, non-`ocx1:` compaction blobs. Independent of either generation capability; a known serving-provider mismatch still degrades foreign ciphertext. Enable only after testing compact and a subsequent turn on the same backend. | @@ -326,15 +391,19 @@ Providers can expose a built-in shorthand, such as `agy` for `google-antigravity | `modelSuppressSyntheticMax?` | `Record` | Catalog-only per-model switch. `true` prevents OpenCodex from adding a missing synthetic `max` rung while retaining a provider-declared `max` and continuing to add `ultra` to reasoning-capable ladders. A preserved row that already contains `max` keeps it until healthy discovery rebuilds that row, because the catalog does not persist whether an older `max` was synthetic. If a configured default names a suppressed missing `max`, the catalog falls back to the highest real rung below it. Codex uses the same ladder membership for the picker and explicit `spawn_agent` effort validation, so an explicit `max` spawn can fail client-side before proxy clamping; `ultra` remains the supported harness path. | | `modelSupportsReasoningSummaries?` | `Record` | Set a model to `false` to stop advertising summaries and strip summary-delivery fields. | | `modelReasoningSummaryDelivery?` | `Record` | Per-model Responses delivery enum; rewrites an existing delivery field. | -| `modelAdapters?` | `Record` | Per-model `openai-chat` or `openai-responses` wire override for mixed-wire gateways. Explicit entries beat registry defaults. The OpenCode Go preset selects Responses for `gpt-5.6-luna` while leaving sibling models on their documented wires; DeepSeek can select native Responses for `deepseek-v4-flash`; Alibaba Token Plan (Beijing) pins `qwen3.8-flash`, `qwen3.7-plus`, and `glm-5.3` to its native Responses API for Responses inbound only (live-verified on that gateway, including plaintext reasoning replay; Chat and Anthropic inbound stay on Chat, and the rest of the family can be opted in here); and GitHub Copilot declares Responses-only defaults for the following models (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) because those models reject `/chat/completions` for agent traffic. Models without a built-in default (for example `gpt-5.4-nano`) can be opted in here. Single-wire upstream pins and canonical ChatGPT forward reject overrides. | +| `thinkingDisplay?` | `"auto" \| "summarized" \| "updates" \| "omitted"` | Anthropic adaptive `thinking.display` policy for this provider. Unset and `auto` keep the built-in selection: native Claude Opus 5.5 on `api.anthropic.com` sends `updates` (progress commentary), and other adaptive models send `summarized`. `summarized` forces reasoning summaries for both. `updates` is honored only where the adapter already sent it — native Opus 5.5 — and is treated as `auto` for every other model. `omitted` sends adaptive thinking without a display field, matching hidden thinking; the stream then carries signature-only thinking blocks, so a Chat client sees only stream heartbeats during a long think. An explicit request `reasoning.summary` of `concise` or `detailed` still forces `summarized`. The dashboard provider editor and `PATCH /api/providers` accept `null` to clear it. `ocx config set providers..thinkingDisplay summarized` writes it directly. | +| `modelThinkingDisplay?` | `Record` | Per-model override of `thinkingDisplay`, keyed by the exact upstream model id (for example `claude-opus-5-5`). An entry always wins over the provider-wide value, including an explicit `auto` that returns one model to the built-in behavior; a model with no entry uses the provider value. The same value rules apply, including `updates` degrading to `auto` on models that never received that display. `PATCH /api/providers` merges entries and accepts `null` for one entry or the whole map to clear it. | +| `modelAdapters?` | `Record` | Per-model `openai-chat` or `openai-responses` wire override for mixed-wire gateways. Explicit entries beat registry defaults. The OpenCode Go preset selects Responses for `gpt-5.6-luna` while leaving sibling models on their documented wires; DeepSeek can select native Responses for `deepseek-v4-flash`; Alibaba Token Plan (Beijing) pins `qwen3.8-flash`, `qwen3.7-plus`, and `glm-5.3` to its native Responses API for Responses inbound only (live-verified on that gateway, including plaintext reasoning replay; Chat and Anthropic inbound stay on Chat, and the rest of the family can be opted in here); and GitHub Copilot declares Responses-only defaults for the following models (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) because those models reject `/chat/completions` for agent traffic. Models without a built-in default (for example `gpt-5.4-nano`) can be opted in here. Single-wire upstream pins and canonical ChatGPT forward reject overrides. | | xAI Chat Completions (dashboard / CLI) | switch | Grok 4.5/4.6 OAuth Responses requests default to Responses. Existing Chat overrides are migrated once on upgrade; later Chat choices are preserved. Turn on to select Chat for both models, off to select Responses. CLI: `ocx provider edit xai --xai-chat on` or `--xai-chat off` (running proxy required). Mixed means only one model currently uses Chat. Other overrides and tier policy stay unchanged. API-key and translated Chat/Anthropic defaults are unchanged. Grok 4.7 defaults to Responses on OAuth through its registry wire default and can use Chat through an explicit `modelAdapters["grok-4.7"] = "openai-chat"` override. | | `xaiResponsesXSearch?` | `boolean` | Disabled by default. On an xAI Responses destination, append the provider-hosted `x_search` declaration only when a live `web_search` tool survives final request normalization. Existing declarations are not duplicated, caller `tool_choice`/`allowed_tools` selectors are never widened, and this is separate from the web-search sidecar's `search.xSearch` options. | | `modelPreferHostedTools?` | `Record` | Exact-model opt-in for non-forward Responses gateways that reserve a hosted-tool namespace. Currently accepts only `["image_generation"]`; a matching model must use the `openai-responses` wire and support that hosted tool. It removes colliding client `image_gen` declarations and rewrites their selectors to preserve caller tool choice. For OpenAI API virtual `-pro` models, the selected public ID is matched first and the resolved base wire-model ID is a fallback. `modelAdapters` resolves the public ID first, then the base ID; the second resolution determines the final wire. Other models retain normal alias behavior. | | `annotateEmptyToolOutputs?` | `boolean` | Replace a present-but-empty tool result with a short marker before it reaches the model, so a blank result is not read as a missing one. Applies to blank strings and text-only part arrays; image, file, and encrypted parts are never touched. Defaults to `true` for DeepSeek from the built-in registry and is otherwise unset. Set `false` to opt a provider out — an explicit `false` is preserved across later edits that omit the field. `PATCH /api/providers?name=` accepts `true`, `false`, or `null` to clear the override and return to registry-default behavior. | +| `promoteAdditionalTools?` | `boolean` | Whether to promote Codex Desktop's `additional_tools` input items into top-level `tools` and strip the wrapper from `input`. Enabled automatically for OpenCode Go and xAI (`api.x.ai` and `cli-chat-proxy.grok.com`) unless `authMode` is `"forward"`, where promotion needs an explicit `true`; other OpenAI-strict third-party gateways that return HTTP 422 for unknown item types in `input` can opt in here. `PATCH /api/providers?name=` accepts a boolean or `null` to clear it. | | `unsupportedHostedTools?` | `string[]` | Hosted tool declarations this Responses destination rejects, so they are stripped from `tools`, from client-loaded `additional_tools`, and from `tool_choice` instead of being forwarded and rejected upstream. Use it for an OpenAI-compatible gateway with a narrower capability set — one that accepts plain Responses requests and `function` tools but returns HTTP 400 for hosted `web_search` — so a text-only prompt is not failed by a capability it never needed. Accepts only hosted tool type names (`web_search`, `web_search_preview`, `file_search`, `computer_use_preview`, `computer_use`, `code_interpreter`, `image_generation`, `image_gen`, `mcp`, `tool_search`, `local_shell`, `x_search`); an unrecognized name is rejected rather than silently ignored. Spelling variants of one capability are aliased, so `["web_search"]` also denies `web_search_preview`. A provider cannot both deny a hosted tool here and prefer it in `modelPreferHostedTools`. Xiaomi MiMo Responses destinations (`xiaomimimo.com` and its subdomains, including `api.xiaomimimo.com` and `token-plan-cn.xiaomimimo.com`) automatically strip `web_search` and `web_search_preview` while preserving function tools; no declaration is needed for these hosts. This is independent of `supportsResponsesCustomTools`; set both for a gateway that also rejects native custom tools. `PATCH /api/providers?name=` accepts an array or `null` to clear it. | +| `unsupportedHostedToolsWithClientTools?` | `string[]` | Hosted tool declarations this Responses destination rejects only when the same request also declares client tools: a `function` or `custom` tool, or a `namespace` with members, in `tools`, in client-loaded `additional_tools`, or in a `tool_search_output` result. Such a request has the named hosted declarations stripped from `tools`, `additional_tools`, and `tool_choice` exactly as `unsupportedHostedTools` would strip them, so a forced selector for a removed tool becomes `"none"`. A request that declares only hosted tools keeps them. Use it for a gateway that serves hosted `web_search` alone and function calling alone but returns HTTP 400 for both together, such as a Gemini-backed Responses gateway that answers `Please enable tool_config.include_server_side_tool_invocations to use Built-in tools with Function calling.`. Accepts the same hosted tool type names and spelling aliases as `unsupportedHostedTools`; an unrecognized name is rejected. `unsupportedHostedTools` stays authoritative: a tool listed there is always stripped. As with that list, a provider cannot also prefer a tool named here in `modelPreferHostedTools`. Unset or `[]` changes nothing. `PATCH /api/providers?name=` accepts an array or `null` to clear it. | | `reasoningEffortMap?` | `Record` | Provider-wide wire aliases for reasoning labels. Map a label to `"__omit__"` to drop the reasoning field from the upstream request entirely: `reasoning_effort` on an OpenAI-compatible wire, and Ollama's native `think` field on the Ollama native adapter (#2356). | | `modelReasoningEffortMap?` | `Record>` | Per-model wire aliases for reasoning labels. Map a label to `"__omit__"` to drop the reasoning field from the upstream request entirely. | -| `reasoningWireFormat?` | `"gateway-object"` | For OpenAI-compatible gateways that accept `reasoning: { enabled, effort }` instead of `reasoning_effort`. The ClinePass preset sets this automatically. A provider save that keeps the destination keeps it; see [What a provider save keeps](#what-a-provider-save-keeps). `PATCH` accepts `"gateway-object"` or `null` to clear it. | +| `reasoningWireFormat?` | `"gateway-object"` | For OpenAI-compatible gateways that accept `reasoning: { enabled, effort }` instead of `reasoning_effort`. For custom Responses destinations, this also explicitly permits the OCX `reasoning.enabled` extension; other Responses destinations strip that internal field. Model thinking capability alone does not opt into this wire format. The ClinePass preset sets this automatically. A provider save that keeps the destination keeps it; see [What a provider save keeps](#what-a-provider-save-keeps). `PATCH` accepts `"gateway-object"` or `null` to clear it. | | `noReasoningModels?` | `string[]` | Models that reject reasoning/thinking parameters. | | `noTemperatureModels?` | `string[]` | Models that reject caller-specified `temperature`. | | `noTopPModels?` | `string[]` | Models that reject caller-specified `top_p`. | @@ -342,22 +411,23 @@ Providers can expose a built-in shorthand, such as `agy` for `google-antigravity | `noPenaltyModels?` | `string[]` | Models that reject presence/frequency penalties. The built-in `xai` preset lists its reasoning models (`grok-4.7`, `grok-4.6`, `grok-4.5`, `grok-4.3`, `grok-4.20-multi-agent-0309`, `grok-4.20-0309-reasoning`, `grok-build-0.1`), which xAI documents as rejecting them; non-reasoning ids keep caller penalties. | | `noStructuredOutputModels?` | `string[]` | Exact model IDs whose `openai-chat` endpoint rejects `response_format`. Only an exact requested-model match omits the field; structured-output translation stays enabled for every other `openai-chat` model. | | `noJsonSchemaModels?` | `string[]` | Exact model IDs whose `openai-chat` endpoint rejects a `json_schema` `response_format` but still accepts `json_object`. Such a request is downgraded to `json_object` instead of being dropped, so a caller asking for JSON still gets JSON. `noStructuredOutputModels` wins when a model is on both lists. The `opencode go` and `opencode zen` presets ship this for their DeepSeek routes. | -| `foldDeveloperRoleToSystem?` | `boolean` | Whether an `openai-chat` destination accepts the `developer` role. `foldDeveloperRoleToSystem` unset sends `system`, `true` sends `system`, and `false` sends `developer`. Unset means nothing has been recorded about this destination; `true` records an upstream that rejects the role; `false` records one that accepts it. The message keeps its position in the conversation in every case — only the role changes. A destination that rejects the role answers `400 role 'developer' is not allowed` and the turn never starts, which is why the unrecorded state is the folded one. A provider save that keeps the destination keeps it; see [What a provider save keeps](#what-a-provider-save-keeps). `PATCH` accepts a boolean or `null` to clear it. | +| `foldDeveloperRoleToSystem?` | `boolean` | Whether an `openai-chat` destination accepts the `developer` role. `foldDeveloperRoleToSystem` unset sends `system`, `true` sends `system`, and `false` sends `developer`. Unset means nothing has been recorded about this destination; `true` records an upstream that rejects the role; `false` records one that accepts it. Unless [single-leading-system compatibility](/guides/lm-studio/) is enabled, the message keeps its position in the conversation in every case — only the role changes. A destination that rejects the role answers `400 role 'developer' is not allowed` and the turn never starts, which is why the unrecorded state is the folded one. A provider save that keeps the destination keeps it; see [What a provider save keeps](#what-a-provider-save-keeps). `PATCH` accepts a boolean or `null` to clear it. | | `omitReasoningEffortWithToolsModels?` | `string[]` | Exact `openai-chat` model IDs that accept a reasoning-effort field on an ordinary turn but reject it once function tools are present. The model keeps its advertised effort ladder; OpenCodex omits the wire field for tool-bearing requests only and the upstream default applies. Narrower than `noReasoningModels`, which strips reasoning from every request and costs the model its picker entirely. A provider save that keeps the destination keeps it; see [What a provider save keeps](#what-a-provider-save-keeps). | | `parallelToolCalls?` | `boolean` | Toggle parallel tool calls. OpenAI Chat defaults on; non-chat adapters advertise only on explicit `true`. | | `terminalContinuationGuard?` | `boolean` | Opt in an `openai-chat` provider to one bounded internal re-ask when an actionable turn announces work, then cleanly stops without a tool call. Defaults to `false`; explicit `false` behaves like omission. Combo attempts and routed compaction turns are excluded, and non-`openai-chat` adapters ignore this option. | | `responsesItemIdRepair?` | `{ message?: string[]; reasoning?: string[]; repairMissingTerminalIds?: boolean; repairInvalidIds?: boolean }` | Disabled-by-default downstream SSE repair for exact placeholder ids, missing terminal ids, and (with `repairInvalidIds`) message/reasoning ids missing the canonical `msg_`/`rs_` prefix. Function-call ids are never rewritten. Built-in DeepSeek enables the last two by default. | | `responsesSnapshotRepair?` | `boolean` | Disabled-by-default client-facing repair for sparse Responses lifecycle snapshots in SSE and JSON. Fills missing canonical status, output, and tool metadata while raw inspection and persistence remain unchanged. | +| `messagePhaseInference?` | `boolean` | Off by default. For Responses passthrough streams, infer missing message phases at completion: a subsequent protocol event yields `commentary`; a terminal event or `[DONE]` yields `final_answer`. Explicit commentary/final_answer phases are preserved (null or unknown values are inferred like missing ones), keepalives do not decide phase, and completed/incomplete snapshots reuse per-item decisions when their phase is absent. Live text keeps streaming while message completion waits for classification. Retained state uses the request's translator budget. Also applies to JSON reconstructed from upstream SSE; ordinary upstream JSON is unchanged. | | `webSearchBridge?` | `{ enabled?: boolean; backend?: "ollama" \| "openai" \| "anthropic" \| "xai" \| "gemini" \| "exa"; maxSearches?: number; timeoutMs?: number; endpoint?: string }` | Key-auth `openai-responses` passthrough providers only. Off by default. Codex always declares the hosted `web_search` tool, and the passthrough relays it on the assumption the destination executes it. A gateway that does not run hosted search answers with a `function_call` named `web_search` that nothing runs, and the undeclared-tool guard ends the turn. With `enabled: true` and an explicit `backend` OpenCodex intercepts that call, runs the search itself, feeds the result back to the same upstream, and shows Codex a hosted `web_search_call` cell. Never armed for `authMode: "forward"` (ChatGPT already searches) or for a provider that executes hosted search upstream. `backend` is required; there is no implicit default and a missing credential for the named backend leaves the bridge disarmed rather than falling through to another paid search. `ollama` reuses this provider's own API key on `POST /api/web_search`, so the origin must be `https://ollama.com` unless the operator names `endpoint` explicitly. `openai` / `anthropic` / `xai` / `gemini` / `exa` reuse the matching sidecar executor and that executor's own credential (`webSearchSidecar.exaApiKey` for Exa). The search model comes from `webSearchSidecar.model` only when `webSearchSidecar.backend` resolves to the same backend this bridge names; otherwise the bridge runs that backend's own default, because a model chosen for one vendor is rejected by another. An unset `webSearchSidecar.backend` resolves to `openai`, so an unset-backend model reaches an `openai` bridge and no other. There is no per-provider bridge model override. Streaming turns only. A turn that mixes `web_search` with another client tool call still fails closed rather than dropping the client's call. Assistant text such as XML-like `` prose is not executed. Defaults: `maxSearches: 3` (1..10), `timeoutMs: 60000` (1000..600000). | -| `retryOn429?` | `{ enabled?: boolean; attempts?: number; intervalMs?: number; maxIntervalMs?: number; respectRetryAfter?: boolean }` | API-key providers only (`authMode: "key"`). Opt-in same-target 429 retry: when `retryOn429` is absent the feature is off, except that key-auth OpenCode Go and Command Code (canonical endpoints) fall back to a patient policy (6 replays, 10 s interval, 60 s cap); object presence enables it unless `enabled: false`, which also turns that fallback off. On 429 the proxy waits (upstream `Retry-After` or the fixed interval) and replays the identical request on the same key before any key failover — across the main text-turn recovery loop, the Responses passthrough wire, the image/video bridge, the web-search sidecar, and terminal continuations. Only pre-stream HTTP 429 responses are eligible for replay; custom `runTurn` transports are outside the HTTP retry loop. `attempts` counts same-key replays after the first 429 (total sends = `attempts` + 1) and is one request-wide budget shared by the main recovery loop, the terminal-guard continuation, and bridge retries. Exhausting `attempts` only stops further same-key replays: normal key failover or final-error handling then applies per the available targets — on the key-auth passthrough wire there is no failover, so the exhausted 429 surfaces as-is. Codex itself never retries 429, so this is the only defense for single-key providers. Defaults: `enabled: true`, `attempts: 3`, `intervalMs: 5000`, `maxIntervalMs: 60000` (any single wait is capped at `maxIntervalMs`, itself capped at 600000), `respectRetryAfter: true`. | +| `retryOn429?` | `{ enabled?: boolean; attempts?: number; intervalMs?: number; maxIntervalMs?: number; respectRetryAfter?: boolean }` | API-key providers only (`authMode: "key"`). Opt-in same-target 429 retry: when `retryOn429` is absent the feature is off, except that key-auth OpenCode Go and Command Code (canonical endpoints) fall back to a patient policy (6 replays, 10 s interval, 60 s cap), and canonical Mistral `openai-chat` falls back to 6 replays with a 10 s interval and 60 s cap; object presence enables it unless `enabled: false`, which also turns that fallback off. On 429 the proxy waits (upstream `Retry-After` or the fixed interval) and replays the identical request on the same key before any key failover — across the main text-turn recovery loop, the Responses passthrough wire, the image/video bridge, the web-search sidecar, and terminal continuations. Only pre-stream HTTP 429 responses are eligible for replay; custom `runTurn` transports are outside the HTTP retry loop. `attempts` counts same-key replays after the first 429 (total sends = `attempts` + 1) and is one request-wide budget shared by the main recovery loop, the terminal-guard continuation, and bridge retries. Exhausting `attempts` only stops further same-key replays: normal key failover or final-error handling then applies per the available targets — on the key-auth passthrough wire there is no failover, so the exhausted 429 surfaces as-is. For canonical Mistral Chat, an explicit upstream delay above the allowed wait stops same-key replay (another pooled key may still serve) and returns the original `Retry-After`; other providers retain the capped-delay behavior. Mistral shares retry deadlines per credential/model unless `requestPacing.enabled: false` or `retryOn429.respectRetryAfter: false`. A 429 with validated minute-budget pressure and no retry time activates a conservative 60 s recovery wait, followed by one probe; success restores ordinary traffic. Healthy traffic never predicts the next token charge. This policy uses advertised allowances, excludes known exhausted monthly allowances, does not claim an exact reset time, and never triggers compaction. Codex itself never retries 429, so this is the only defense for single-key providers. Defaults: `enabled: true`, `attempts: 3`, `intervalMs: 5000`, `maxIntervalMs: 60000` (any single wait is capped at `maxIntervalMs`, itself capped at 600000), `respectRetryAfter: true`. | | `transientRetryOn5xx?` | `{ enabled?: boolean; attempts?: number }` | Key-auth `openai-chat` and `openai-responses` providers only. `authMode: "forward"` providers (the ChatGPT account pool) never read this option and keep the default ladder. Opt-in retry for pre-stream transient upstream statuses (500, 502, 503, 504, 520, 521, 522): absent means off, object presence enables it unless `enabled: false`. Covers the initial Responses request, the Responses passthrough lane and each of its recovery legs (OAuth-401 replay, same-target 429 replay, validated rebuild), the terminal-guard continuation, and native `/v1/chat/completions`. `attempts` is the TOTAL number of upstream sends allowed for one request including the first (1..10, default 3) — it is one budget shared with connection-reset recovery, so `3` means at most three real requests reach the provider. On the Responses passthrough lane the configured value is additionally intersected with the request-wide send allowance, so a value below that allowance narrows the ladder exactly while a value above it does not raise the bound. Each Combo target includes its prepaid first send in that target's configured total; `attempts: 1` sends once, without refunding the reservation or widening the shared Combo ceiling. A local refusal or cancellation before dispatch releases an unsent booking. Waits use a fixed 400 ms exponential backoff capped at 5 s and honor `Retry-After`. Separate from `retryOn429`, which handles rate limiting; mid-stream failures are never replayed. | -| `retryOnReset?` | `{ enabled?: boolean; replacements?: number }` | Native `openai-responses` providers, including `authMode: "forward"`, plus generic translated Responses dispatch before upstream headers. Opt-in replacement of a send that failed while the caller had observed nothing: absent means off, object presence enables it unless `enabled: false`. Covers both ambiguous stages — a connection that died before any response header, and an SSE body that died after the header while carrying only control events. A canonical ChatGPT upstream WebSocket that closed or errored after its create frame left, before any Responses event, is covered the same way, and its replacement is sent over HTTP. Only a self-contained request is ever replaced: `store: false`, complete `input`, no `previous_response_id`, `conversation` or `stream_id`, and only client-executed tools. `replacements` is the number of replacement sends ONE logical request may make across every leg and every combo child (1..2, default 1) — not a per-leg retry count and not a send budget, so a replacement still has to fit inside the send allowance the leg already had. A request that already emitted output or a tool call is never replaced, whatever this is set to. The replacement inference may still be billed if the origin had already started the first one, which is why this is off by default. Generic translated dispatch supports pre-header reset replacement for initial and rebuilt sends under the same grant and send budget. Adapter-owned transports and translated stream failures after upstream headers are excluded. | +| `retryOnReset?` | `{ enabled?: boolean; replacements?: number }` | Native `openai-responses` providers, including `authMode: "forward"`, plus generic translated Responses dispatch before upstream headers. Opt-in replacement of a send that failed while the caller had observed nothing: absent means off, object presence enables it unless `enabled: false`. Covers both ambiguous stages — a connection that died before any response header, and an SSE body that died after the header while carrying only control events. A canonical ChatGPT upstream WebSocket that closed or errored after its create frame left, before any Responses event, is covered the same way, and its replacement is sent over HTTP. Only a self-contained request is ever replaced: `store: false`, complete `input`, no `previous_response_id`, `conversation` or `stream_id`, and only client-executed tools. A chained turn whose `previous_response_id` this proxy already expanded from its own replay state qualifies, because that id is removed before the send. When a reset is not replaced, the service log records why: `ambiguous-no-policy`, `ambiguous-request-not-replayable` or `ambiguous-allowance-spent`. `replacements` is the number of replacement sends ONE logical request may make across every leg and every combo child (1..2, default 1) — not a per-leg retry count and not a send budget, so a replacement still has to fit inside the send allowance the leg already had. A request that already emitted output or a tool call is never replaced, whatever this is set to. The replacement inference may still be billed if the origin had already started the first one, which is why this is off by default. Generic translated dispatch supports pre-header reset replacement for initial and rebuilt sends under the same grant and send budget. Adapter-owned transports and translated stream failures after upstream headers are excluded. | | `autoToolChoiceOnlyModels?` | `string[]` | Models whose `tool_choice` accepts only `auto` or `none`; forced choices are downgraded. | -| `preserveReasoningContentModels?` | `string[]` | Models requiring prior assistant `reasoning_content` in chat history. A provider save that keeps the destination keeps the stored list, including `[]`; see [What a provider save keeps](#what-a-provider-save-keeps). `PATCH /api/providers?name=` accepts an array or `null` to clear it. | +| `preserveReasoningContentModels?` | `string[]` | Models requiring prior assistant `reasoning_content` in chat history. Translated Chat requests to `api.mistral.ai` instead reconstruct native thinking chunks before assistant text; supplied thinking replays by default for all hosted families, and an explicit list (including `[]`) overrides enrollment. No placeholder thinking or signatures are invented. Native Chat passthrough is unchanged. A provider save that keeps the destination keeps the stored list, including `[]`; see [What a provider save keeps](#what-a-provider-save-keeps). `PATCH /api/providers?name=` accepts an array or `null` to clear it. | | `inlineThinkTagModels?` | `string[]` | Opt-in recovery for `openai-chat` gateways without a server-side reasoning parser. A leading `` / `` / `` block (optionally after whitespace) activates splitting in streamed and buffered replies. All answer whitespace is preserved. Subsequent tags are delimiters anywhere, including same-line interleaving and code fences; this mode does not interpret Markdown. Ordinary text or a code fence before the first tag keeps the whole reply untouched. Off by default; prefer structured upstream reasoning or `reasoningSplitModels` where supported. | | `reasoningDetailsModels?` | `string[]` | Models whose endpoint returns thinking as a structured `reasoning_details` array (MiniMax M-series with `reasoning_split`); stream deltas are cumulative snapshots that are prefix-diffed, and preserved reasoning replays as a `reasoning_details` array instead of a `reasoning_content` string. | | `requiresReasoningPlaceholderModels?` | `string[]` | Models whose upstream rejects a tool_call continuation missing `reasoning_content` (DeepSeek thinking mode); a minimal placeholder is injected when the replay cache misses. Defaults to `preserveReasoningContentModels`; set `[]` to opt out. A provider save that keeps the destination keeps the stored list, including `[]`; see [What a provider save keeps](#what-a-provider-save-keeps). `PATCH /api/providers?name=` accepts an array or `null` to clear it. | -| `showThinkingSummary?` | `boolean` | Display provider-authored summaries when a Responses client omits `reasoning.summary`. Explicit wire `"none"` wins; a client that serializes its preference as omission cannot be distinguished. Raw reasoning remains content and is never relabeled as a summary. The `google-antigravity` preset defaults to `true`; explicit `false` disables that default. CCA Gemini requests also opt into `generationConfig.thinkingConfig.includeThoughts` when display is enabled; image, Claude and gpt-oss requests do not. This does not change client configuration or global catalog summary defaults. | +| `showThinkingSummary?` | `boolean` | Display provider-authored summaries when a Responses client omits `reasoning.summary`. Explicit wire `"none"` wins; a client that serializes its preference as omission cannot be distinguished. Raw reasoning remains content and is never relabeled as a summary. The `google-antigravity` preset defaults to `true`; explicit `false` disables that default. Eligible CCA, Vertex and direct Gemini requests also opt into `generationConfig.thinkingConfig.includeThoughts` when display is enabled; image, Claude, gpt-oss and unladdered Vertex requests do not. This does not change client configuration or global catalog summary defaults. | | `hideRawReasoning?` | `boolean` | Keep a routed provider's raw chain of thought off the client-facing content channel (openai-chat `reasoning_content`, kiro tags, `response.reasoning_text.*`) while provider-authored summaries still stream on the summary channel. Explicit wire `reasoning.summary: "none"` keeps hiding both. This controls what a client displays; it does not keep the text from the client. A Responses bridge route still sends it inside the `ocxr1` replay envelope in the reasoning item's `encrypted_content`, which is base64 JSON rather than encryption, so the client can echo it back on the next turn. The direct Chat and Messages encoders have no envelope on their wire, so those clients receive no copy and replay comes from the server-side reasoning replay cache. `preserveReasoningContentModels` replay and DeepSeek-style continuations are unaffected either way. Off by default; a native passthrough route relays the upstream's own frames and ignores this option. A save of the same provider name keeps an omitted value even after a destination move; `PATCH` accepts a boolean or `null` to clear it. | | `thinkingToggleModels?` | `string[]` | Chat models using `thinking.enabled` rather than an effort ladder. | | `thinkingBudgetModels?` | `string[]` | Chat models using integer `thinking_budget`; effort maps to a budget fraction. | @@ -367,10 +437,11 @@ Providers can expose a built-in shorthand, such as `agy` for `google-antigravity | `googleMode?` | `"ai-studio" \| "vertex" \| "cloud-code-assist"` | Google transport/auth mode. Default `ai-studio`. | | `googleToolSchemaPolicy?` | `"compatible" \| "reject-lossy"` | Google only. Omitted/`compatible` preserves the compatible tool schema and existing non-direct 400 repair. `reject-lossy` rejects initial schema loss or an indeterminate bounded comparison before dispatch and withholds a Vertex or Cloud Code Assist repair that would open constraints. Direct AI Studio never performs that repair. | | `directGeminiWireRenames?` | `boolean` | Google only. Applies in AI Studio mode, including custom Google-compatible URLs. Omitted or `true` keeps the `-tiered` wire rename for Gemini Flash ids (`gemini-3.7-flash` -> `gemini-3.7-flash-tiered`); `false` sends the requested bare ids to the wire unchanged. Vertex and canonical keyed OpenCode Zen routes preserve the requested model ID regardless of this setting; Cloud Code Assist routing is unchanged. Set `false` when the configured upstream still serves the bare ids. | -| `project?` | `string` | Vertex or Antigravity Cloud Code Assist project id. Vertex API keys use this project endpoint when set; without it they use express mode, even if `GOOGLE_CLOUD_PROJECT` is set. ADC falls back to `GOOGLE_CLOUD_PROJECT` / `GCLOUD_PROJECT`. | +| `project?` | `string` | Vertex or Antigravity Cloud Code Assist project id. Vertex API keys use this project endpoint when set; without it they use express mode, even if `GOOGLE_CLOUD_PROJECT` is set. ADC falls back to `GOOGLE_CLOUD_PROJECT` / `GCLOUD_PROJECT`. `"auto"` makes each Vertex API key resolve its own project (a successful lookup is cached per key; a key whose lookup fails is probed again on a later request), so one key pool can span projects; ADC rejects `"auto"`. | | — | — | Antigravity account quota probes (`retrieveUserQuota` and `retrieveUserQuotaSummary`) always go to Google's own Cloud Code host through the pinned outbound transport, regardless of a configured `baseUrl`; the account bearer is never sent to an operator-configured endpoint and a redirect aborts the probe. Only the model-list fallback still honors `baseUrl`. | -| — | — | If Antigravity quota summary returns 403 for a valid OAuth account, OpenCodex retries that endpoint once with the legacy `antigravity/1.0` User-Agent and the same token and project. A 401 is not retried. Inference and model discovery retain the IDE User-Agent. | +| — | — | Antigravity quota summary is requested with the Antigravity CLI User-Agent, the only client family for which Google includes the Gemini 4 Argon quota group. If it returns 403 for a valid OAuth account, OpenCodex retries that endpoint once with the legacy `antigravity/1.0` User-Agent and the same token and project. A 401 is not retried. Non-Argon inference and the model-list quota fallback keep the IDE User-Agent. | | — | — | Antigravity quota shows Gemini 4 Argon as separate `Argon` / `Argon (Weekly)` windows next to Gem and Cla. They are display-only: account ranking, quota exhaustion, reset ordering and reset notifications keep using the Gemini and Claude windows, and Argon requests are still judged by the Gemini window. | +| — | — | Refreshing Antigravity discovery unions usable accounts' enabled models and retains each account's own roster for six hours. With account failover active, a CCA 404 tries another eligible account only when its complete original error is at most 4 KiB and contains a model ResourceInfo whose resourceName exactly matches `models/`. Message-only errors, other resources and oversized, incomplete or erroring bodies keep the original HTTP status without a model denial or rotation. A confirmed denial lasts up to 24 hours, until positive discovery started after that request or credential replacement; older discovery cannot clear it or replace a newer positive roster. Exhaustion names the model and distinguishes unavailable accounts from credential, admission, or send-budget failure. No paid/trial classification is inferred. | | `location?` | `string` | Vertex location. API-key project endpoints default to `global` and ignore `GOOGLE_CLOUD_LOCATION`; ADC requires this field or the `GOOGLE_CLOUD_LOCATION` fallback. Gemini 4 Argon supports `global`, `us`, and `eu`. | | `mcpServers?` | `Record` | Cursor only: stdio or Streamable HTTP MCP servers. | | `desktopExecutor?` | `DesktopExecutorConfig` | Cursor only: external computer-use and record-screen commands. | @@ -446,23 +517,21 @@ and `modelContextWindows` for that exact id when needed. Unknown ids are not gue ### What a provider save keeps -`POST /api/providers` with the name of an existing provider replaces the stored row with one built from the request. The dashboard's add/edit form cannot send every field, so the save keeps some stored fields the request omits. Eight of them record how one upstream behaves: `preserveReasoningContentModels`, `requiresReasoningPlaceholderModels`, `foldDeveloperRoleToSystem`, `reasoningWireFormat`, `omitReasoningEffortWithToolsModels`, `retryOn429`, `transientRetryOn5xx` and `retryOnReset`. +`POST /api/providers` with the name of an existing provider replaces the stored row with one built from the request. The dashboard's add/edit form cannot send every field, so the save keeps some stored fields the request omits. Thirteen of them record how one upstream behaves: `preserveReasoningContentModels`, `preserveResponsesReasoningContent`, `requiresReasoningPlaceholderModels`, `foldDeveloperRoleToSystem`, `singleLeadingSystemMessage`, `reasoningWireFormat`, `omitReasoningEffortWithToolsModels`, `promoteAdditionalTools`, `retryOn429`, `transientRetryOn5xx`, `retryOnReset`, `unsupportedHostedTools` and `unsupportedHostedToolsWithClientTools`. -| Save | The eight settings | Stored `apiKeyPool` | +| Save | The thirteen settings | Stored `apiKeyPool` | | --- | --- | --- | | Same destination, field omitted | Stored value kept, including an explicit `[]` or `false` | Kept | | New destination, field omitted | Not kept; registry defaults for the new destination may apply | Not kept | | Field sent in the request | The request's value | The request's value | -The destination is the adapter, the base URL (scheme and host compared without regard to case, trailing slashes ignored) and, when the request names one, the auth mode. Moving a provider to another destination drops the eight settings because they describe the previous upstream, and drops the key pool because its keys were issued for it. A save never merges the rest of the old row into the new one. +The destination is the adapter, the base URL (scheme and host compared without regard to case, trailing slashes ignored) and, when the request names one, the auth mode. Moving a provider to another destination drops the thirteen settings because they describe the previous upstream, and drops the key pool because its keys were issued for it. A save never merges the rest of the old row into the new one. The provider-level `modelDiscovery` block follows the same destination rule: a same-destination save that omits it keeps it, and a move drops it. `hideRawReasoning` is an operator display policy, so a save of the same provider name keeps its stored value whenever the request omits it, including after a destination move. A value sent in the request wins, including `false`. -The optional `inferContextWindow` setting also survives same-name saves that omit it, including -destination moves. Its read, update, and clear behavior is described under -[Context windows on custom providers](#context-windows-on-custom-providers). +The optional `inferContextWindow` setting also survives same-name saves that omit it, including destination moves. Its read, update, and clear behavior is described under [Context windows on custom providers](#context-windows-on-custom-providers). -`PATCH /api/providers?name=` changes only the fields it names and keeps every other stored field, whatever the destination. It accepts all eight settings; `null` clears one. It also accepts a boolean `hideRawReasoning` or `null` to clear it. For the two reasoning lists an empty array is stored as an explicit opt-out rather than removed. +`PATCH /api/providers?name=` changes only the fields it names and keeps every other stored field, whatever the destination. It accepts all thirteen settings; `null` clears one. It also accepts `modelDiscovery`, where `null` or `{}` clears it. It also accepts a boolean `hideRawReasoning` or `null` to clear it. For the two reasoning lists an empty array is stored as an explicit opt-out rather than removed. With `webSearchBridge` enabled, a search continuation stays bound to the API-key selection that served the first request. Changing the selected key, its reference or resolved value, authentication @@ -669,8 +738,11 @@ restores the original native name only when the row's display name still matches override. A newer external display name is preserved subject to existing native metadata normalization; for example, Astra (`gpt-6-astra`) still replaces a non-pinned name with its pinned native name. The label overlay leaves model IDs, metadata (including capabilities), ordering, -routed combo aliases, and account-qualified rows unchanged. This local catalog override does -not relabel the HTTP model listings or virtual `*-pro` rows. +routed combo aliases, and account-qualified rows unchanged. `GET /api/models` also exposes these +labels for bare native rows, so client exports and the `ocx opencode` launcher use them. +OpenCode keeps its existing suffix, for example `sol (native)`. Relaunch `ocx opencode` or +refresh the managed integration to update its generated configuration. Without an override, +existing export labels stay unchanged. `/v1/models` and virtual `*-pro` rows are unchanged. The effective label order is operator `modelDisplayNames`, then provider catalog metadata, then the normal `provider/model` fallback. The routed selector remains `xai/grok-4.6`, while the upstream @@ -697,6 +769,8 @@ it does not restore the old name. Requests have a 60-second deadline covering th follow-up list refresh. A timeout does not undo a write: use **Retry** to check the current name before making another change. +Claude Code's `/model` picker (Anthropic-flavor `GET /v1/models`) shows a routed row with an exact label as `