diff --git a/docs/client-session-ids.md b/docs/client-session-ids.md new file mode 100644 index 000000000..78600c900 --- /dev/null +++ b/docs/client-session-ids.md @@ -0,0 +1,152 @@ +# Client session identity: who carries a session id, how subagents behave, what to stamp + +> **Supersedes** the per-client *session-id* conclusions in `docs/identity-channels.md` §2 +> (the 2026-11-07 #5825 map: "content-hash fallback IS the optimum — closed", "NO wire identity +> signal", "needs one measurement run"). That doc's **message-id HARVEST** wiring (§1 seam, +> §3 trust boundaries, §4 change checklist) remains operative — only its per-client *session* +> rows are outdated. +> +> Date: 2026-11-22. Method: source-first (cloned repos, unpacked npm bundles, installed +> binaries), binary-second. Full per-client file:line evidence: `research/batch-open-1.md`, +> `batch-subagent.md`, `batch-closed-1.md`, `batch-nosignal.md`, `batch-unverified.md` +> (scratch), and `group2-get-id.md` / `group3-share-alt.md` (both complete, source-verified). + +## 1. The model (owner ruling 2026-11-22) + +Two separate things, kept apart on purpose: + +- **Identity (the session id)** = what the *client* stamps. bili trusts it **verbatim** — no + content-guessing forks. This is the server-side gate `trustStampedId` + (`src/rollout.ts`), **on by default** (GA, #7439). The four content-forecasting `|sub:` forks in + `src/session-resolve.ts` (derived-aux / persona-by-content / two derived-task) ride the stamped + id verbatim; the ONE survivor is the #5095 claude-code lane-token tail + (`|sub:t:`), which is *client-declared*, not guessed. +- **Purpose (which side-task: compaction / title / subagent / memory)** = **server-derived** from + each client's own signals (`x-grok-turn-idx`, `x-zcode-query-source`, `x-compaction`, `task_id`, + `agent-id`, …). The `x-bili-plugin-purpose` header is a **bonus** for the few clients that *can* + stamp it per-request (dsh/pi/opencode in-process; codex via config `http_headers`). + +> **Why purpose stays server-side:** nearly every client extension point is **static** +> (session/provider/process-scoped) — none has a per-request header hook. So a static stamp can at +> best declare the `"conversation"` sentinel, which bili normalizes back to *absent* +> (`src/server/handle.ts:1320`). Per-task purpose needs a per-request hook (rare) or server-side +> derivation (the norm). + +## 2. Global constraint (affects every verdict) + +`x-bili-plugin-purpose` is honored **only together with** the `x-bili-plugin` agent marker +(`src/plugin.ts:236-241` `pluginPurposeHeader()`). Without the marker, the purpose header is +ignored. This is intentional: honoring purpose on an un-announced client would let it opt its +traffic out of classification. + +## 3. 第一类 — have a stable session id + +### (a) subagents have DISTINCT ids → adopted / directly wired + +| client | session id | subagent model | in bili today? | to finish | +|---|---|---|---|---| +| **opencode** | `x-opencode-session-id` (= own `session.id`; parent as `x-opencode-parent-session-id`) | distinct per agent/fork | IN ROSTER `src/session-id.ts:99` | none — recognized; `trustStampedId` covers it | +| **codex** | `thread-id` (+`x-codex-turn-metadata` `thread_source`) | distinct (each spawned thread its own `thread-id`) | **HANDLED** `codexTurnIdentity()` `src/session-id.ts:473`; server keys it directly | none (modern ≥0.147); older builds fall to instructions fingerprint | +| **goose** | `agent-session-id` (= sqlite `sessions.id`) | distinct (`summon` spawns a new session) | IN ROSTER | none | +| **CodeBuddy** | `X-Conversation-ID` (persisted conv id, restart-stable) | distinct (`setupSubAgentSession`, own scope) | IN ROSTER | none | +| **zcode** | `x-session-id` (`subagent_agent_` prefix stripped pre-wire) | subagent distinct; **memory worker shares** parent id → already split server-side to `\|aux:zcode-memory:` | IN ROSTER + `zcodeMemoryConversation()` `src/session-id.ts:110` | none | +| **jcode** | body `prompt_cache_key` (**Responses wire only**) | n/a (single wire id) | **PROMOTED** `preferPromptCacheKeyIdentity()` `src/session-id.ts:409` | none on Responses; anthropic/openrouter wires have no id → still content-fallback there | +| **dsh / pi** | in-process plugin mints canonical ids | distinct | WIRED (in-process) | none — **full** (also the reference for purpose stamping) | +| **zed** | body `thread_id` (cloud `POST /completions`; OpenAI-subscribed path sends `session-id`+`thread-id` headers) | distinct (own thread id + `parent_thread_id`) | **NOT READ** — but `bili zed` cert-MITM already intercepts zed traffic (`src/cli.ts:96`) | **new wire** (scoped, `research/zed-scope.md`): zed's `/completions` is a non-standard envelope bili does not decode today (protocol=null → verbatim passthrough, **no** session at all). Needs an envelope classifier + `zed-wire.ts` unwrap/rewrap codec + provider→protocol dispatch; ~550-900 ln, one focused PR. Bonus: the OpenAI-subscribed path already sends `session-id`+`thread-id` headers (~10-ln roster add, independent). | + +### (b) subagents SHARE the parent session id → 第三类 (below) + +`mcode`, `qoder`, `claude-code`, `copilot`, `kiro` (plus `grok` aux / `omp` forks — see 第三类 notes). + +## 4. 第二类 — no session id (source re-verify; must at least land one) + +The #5825 map closed these as "content-hash fallback IS the optimum — closed". Source verification +**overturns that**: every one can land a stable per-session id, and **three of four need zero client +code change** (see `research/group2-get-id.md`, verified 2026-11-22 against current HEAD). + +| client | id source (verified) | minimal mechanism | per-session? | code change? | conf | +|---|---|---|---|---|---| +| **gemini-cli** | **user-mintable**: `--session ` + `createSessionId()` (`session.ts:9`) | env `GEMINI_CLI_CUSTOM_HEADERS` = the 3 bili headers, value aligned to `--session $S` | **yes** — the client's *own* id (persisted, `--resume $S`) | **none** | high | +| **crush** | internal `uuid.New()` per session (`session.go:107`) | `extra_headers: {"x-bili-plugin-conversation":"$BILI_SESSION_ID"}` + wrapper `BILI_SESSION_ID=$(uuidgen)` — **header values now shell-expand** (`config.go:114-120`) | yes (TUI + `crush run`); no for the shared `crush server` daemon | **none** (daemon needs a hook) | high | +| **aider** | **no id anywhere** (only a machine analytics uuid; `models.py:985`) | `--model-settings-file` with `extra_params.extra_headers`; wrapper mints a uuid per launch | yes (no resume → per-launch = per-session) | **none** | high | +| **kimi** | internal id exists but `--session` is resume-only; nothing on the wire (`catalog-service.ts:420`) | env `KIMI_CODE_CUSTOM_HEADERS` static (per process) | **process-scoped only** (concurrent sessions collide) | none per-process; ~10-20 ln upstream for true per-session | high | + +**Ranking (least effort first):** gemini-cli (env flag + the client's own id) → crush (env var + static config) → aider (wrapper-minted uuid) → kimi (weakest: per-process stamp only; true per-session needs an upstream `PreModelRequest` hook). + +All four wrappers send `x-bili-plugin` + `x-bili-plugin-conversation` (+ `x-bili-plugin-purpose`) together — the marker gate bili requires (`conversationHeaderSource`, `src/session-id.ts`). + +## 5. 第三类 — have id, but subagents SHARE it (listed separately; source re-verify the alternate signal) + +Source-verified per client (`research/group3-share-alt.md`, 2026-11-22). The "they share the +parent id, so they merge" premise holds for only **two** of the five — the other three have a +distinct id or a clean per-task signal: + +| client | what source actually shows | on wire? | subagent-reliable? | bili consumes? | minimal change | conf | +|---|---|---|---|---|---|---| +| **mcode** 0.7.9 | **premise wrong** — a subagent rides a *fresh child* `X-Mavis-Session-Id` (minted per spawn) | header | yes (structural) | yes (roster :99) | **none — drop the shared-id premise** | high | +| **copilot** 1.0.114 | `X-Agent-Task-Id` / `X-Parent-Agent-Id` on the model wire (runtime.node) | header | yes (subagent ⇒ parent-id present) | no | roster: insert `x-agent-task-id` before `x-session-id` | med-high | +| **claude-code** 2.1.330 | new `x-claude-code-request-class` (main/subagent/workflow/compaction/auxiliary/side_reply), **off** under a 3rd-party base URL unless `CLAUDE_CODE_GATEWAY_HINT_HEADERS=1` | header | yes once env on; absent by default | no | launcher sets env=1; session-id.ts read+validate; handle.ts split `subagent\|…`→`\|sub:`/`\|aux:`; keep #5095 token as fallback | high (default-off empirical) | +| **qoder** 1.1.95 | body `metadata.task_id`/`business_type`/`sub_task` (agent_summary/webfetch_summary/hook_prompt) — **side tasks only**; plain Task subagents carry nothing but a fresh `X-Request-Set-Id` | body | no for plain subagents; yes-ish for side tasks | no (only `x-session-id`) | handle.ts qoder clause: sidecar `webfetch_summary\|hook_prompt\|agent_summary` as `\|aux:` (zcode pattern :109); plain subagents unfixable on the wire | high | +| **kiro** 3.5.0 | body `metadata` `kiro:agent_continuation_id` / `root_conversation_id` / `agent_mode` (RE'd `cfd()`) | body | unknown (conditional emission, unverified on 3.5.0) | no (kiro.ts:71-78 reads conversation_id only) | extend kiro.ts lineage reader + `\|sub:kiro` **after one live `bili kiro` capture** | med / low-med | + +**Takeaway:** mcode → no work. copilot + claude-code → clean header additions (claude's needs +bili's launcher to set one env var — zero client patch). qoder → side tasks separable, plain +subagents not. kiro → one live capture before touching it. + +Notes: +- **grok** — side-tasks (btw/compaction/title) share the main id but are **already** classified by + the *absence* of `x-grok-turn-idx` (`src/server/handle.ts:1380` `grokAuxSidecar`). No new work + needed; listed here for completeness, not a blocker. +- **omp** — `Task` subagents get their *own* `prompt_cache_key` (distinct), but forks/`//tan` + deliberately **inherit** the parent key (cache-mirroring). Server-side: distinguish the inherited + case via the body key + a turn heuristic. + +## 6. Fix worklist (by effort, source-verified 2026-11-22) + +**A. bili-side only (no client change):** +1. **no work** — opencode / codex / goose / CodeBuddy / zcode / dsh **and mcode** (already distinct + on the wire; just turn on `trustStampedId`). +2. **add a header to the roster** — copilot (`x-agent-task-id` before `x-session-id`, + `src/session-id.ts:99`). +3. **launcher env + roster header + split** — claude-code: launcher sets + `CLAUDE_CODE_GATEWAY_HINT_HEADERS=1`; the split reads `x-claude-code-request-class` + and acts only on `subagent` (force the `|sub:` agent split) and `main` (suppress it); + `workflow`/`compaction`/`auxiliary`/`side_reply` are validated but fall through to the + legacy system-prefix heuristic (keep #5095 token as fallback for non-bili-launched processes). +4. **consume body lineage** — qoder side-tasks (`metadata.task_id`/`business_type` → `|aux:`, + zcode pattern), kiro (`kiro:root_conversation_id` after a live capture). +5. **server-side heuristic (no client fix exists)** — grok (turn-idx absence), omp (fork key mirror). + +**B. client must stamp an id (第二类 + zed):** +6. **zero client code change** — gemini-cli (env + `--session `), crush (env `$VAR` header), + aider (wrapper-minted uuid via `--model-settings-file`). +7. **per-process stamp** (fine single-session) — kimi. +8. **new wire** — zed (envelope classifier + `zed-wire.ts` codec + dispatch; ~550-900 ln, one PR; scope report `research/zed-scope.md`). Bonus: OpenAI-subscribed zed sends `session-id`+`thread-id` headers (~10-ln roster add). + +## 7. Rollout: GA-on (owner ruling 2026-11-22), residual risk accepted + +`trustStampedId` is **on by default, no gradual rollout** — the stamped-id model is proven in +production (the #6880 dsh terminal state + the long-running client-session-id roster). The one +residual risk is a client whose subagent rides the *parent's* session id: with content-forking +retired, such subagent traffic merges into the parent. Per the 第三类 verification that applies to +only **qoder plain Task subagents** and **kiro** (unverified); the rest are handled: +- copilot + claude-code: bili consumes their per-task header (`x-agent-task-id`, + `x-claude-code-request-class`), so their subagents key themselves apart. +- mcode / opencode / codex / goose / CodeBuddy / zcode / dsh / zed: subagent id is distinct on the + wire — no merge. +- qoder plain Task subagents + kiro: accepted as a merge (owner ruling); kiro also awaits one live + capture. Escape hatch stays available: `BILI_ROLLOUT_TRUST_STAMPED_ID=0` forces the legacy + `|sub:` ladder for a debug session. + +## 8. Status + +- 第一类 (have id): 7/8 already wired into bili; **zed** = bounded new work (`bili zed` MITM + intercepts the traffic; read body `thread_id` as the session key). +- 第二类 (no id): **DONE** (`research/group2-get-id.md`) — all 4 land a per-session id; gemini-cli / + crush / aider need **zero** client code change; kimi is per-process only. +- 第三类 (share id): **DONE** (`research/group3-share-alt.md`) — mcode premise wrong (child ids + distinct); copilot + claude-code have clean per-task headers; qoder side-tasks only; kiro needs + one live `bili kiro` capture. +- zed: scoped as a **new wire** (~550-900 ln, one PR) — `research/zed-scope.md`. The `bili zed` MITM + already intercepts the traffic; the gap is that bili does not decode zed's envelope (protocol=null), + so a classifier + codec + dispatch are needed, not a simple body read. diff --git a/docs/identity-channels.md b/docs/identity-channels.md index 87033547a..085715907 100644 --- a/docs/identity-channels.md +++ b/docs/identity-channels.md @@ -1,5 +1,13 @@ # Identity-channel wiring (#5825) +> **⚠️ SUPERSEDED — per-client *session-id* conclusions (2026-11-22).** The §2 rows for +> **crush / gemini-cli / hermes / aider / jcode / kimi** ("closed", "content-hash fallback IS the +> optimum") and **qoder / copilot** ("needs one measurement run") were re-verified against current +> source and are now outdated — see **`docs/client-session-ids.md`** for the current 18-client +> session-identity map (what carries a session id, how subagents behave, what to stamp). This page's +> **message-id HARVEST** machinery (§1 seam, §3 trust boundaries, §4 change checklist) is *not* +> superseded and remains operative. + One page for the cross-client "stable conversation + message id" wiring: who carries identity into bili, where it is consumed, and what every new lane must do. The design law (owner ruling 2026-11-07): **every client lane wires INTO diff --git a/reference/architecture.md b/reference/architecture.md index 392261e4e..2467eb631 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -193,6 +193,7 @@ billion-context/ │ ├── error-dump.ts # Rejected-body dump (diagnostics.dump4xx / BILI_DUMP_4XX) │ ├── ws-bridge.ts # Generic WebSocket bridge shell │ ├── responses-ws.ts # Codex/OpenCode Responses-over-WebSocket codec (#1844) +│ ├── zed-wire.ts # Zed cloud wire: {thread_id, provider_request} envelope codec + thread_id identity │ ├── kiro.ts # Kiro CLI: model-gateway hosts, built-in developer/system→user roles, kiro:conversation_id identity │ ├── launcher.ts # `bili ` launcher (auto-proxies both schemes) │ ├── client-config.ts # Read-only discovery of each client's own upstream config diff --git a/src/client-config.ts b/src/client-config.ts index 5fce9ce87..c93527544 100644 --- a/src/client-config.ts +++ b/src/client-config.ts @@ -1291,6 +1291,8 @@ export function readCrushConfig(env: NodeJS.ProcessEnv = process.env): CrushConf * (readZedConfig); exotic relays ride --mitm-domain. Loopback providers * (ollama, lmstudio) never appear here — they stay direct via NO_PROXY. */ export const ZED_DEFAULT_MODEL_HOSTS = [ + "cloud.zed.dev", + "llm-staging.zed.dev", "api.anthropic.com", "api.openai.com", "generativelanguage.googleapis.com", diff --git a/src/launcher.ts b/src/launcher.ts index 16ac40336..5e4218f69 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -1106,7 +1106,13 @@ const ENV_CLIENTS: Record = { * child's own egress now comes from the aux-proxy handoff in the spawn path * instead. The loopback exclusion that keeps the /bili/ leg direct when the * child DOES carry a proxy lives in mergeLoopbackNoProxy (#3446). */ - claude: { caKeys: [], proxy: false, httpProxyOnRouteHttp: false, baseUrlKeys: ["ANTHROPIC_BASE_URL"], ownBaseUrlKeys: ["ANTHROPIC_VERTEX_BASE_URL"] }, + claude: { caKeys: [], proxy: false, httpProxyOnRouteHttp: false, baseUrlKeys: ["ANTHROPIC_BASE_URL"], ownBaseUrlKeys: ["ANTHROPIC_VERTEX_BASE_URL"], + /** #7439: let claude-code send its per-task class header + * (`x-claude-code-request-class`) to bili — it is gated OFF under a + * 3rd-party base URL (i.e. bili) unless this env is set. The reader is + * claudeRequestClassOf / the additive override in + * claudeSubagentAgentId (src/session-id.ts). */ + extras: [["CLAUDE_CODE_GATEWAY_HINT_HEADERS", "1"]] }, codebuddy: { caKeys: ["NODE_EXTRA_CA_CERTS"], proxy: true, httpProxyOnRouteHttp: false, baseUrlKeys: ["CODEBUDDY_BASE_URL"] }, /** #653: qoder's model endpoint scheme is hardcoded https (no base-URL * override env), so the launcher can only route it via cert MITM: its diff --git a/src/persist.ts b/src/persist.ts index a00987682..35111d880 100644 --- a/src/persist.ts +++ b/src/persist.ts @@ -207,6 +207,7 @@ interface PersistedSession { emergencyShrinkEstimate?: number; lastInputTokensOrigin?: string; overflowArmTokens?: number; + preflightRuns?: number; overflowArmCompletionReserve?: number; overflowArmMismatchWarned?: boolean; // #3450 follow-up: provider-lifetime completion proof + its scope. @@ -4426,6 +4427,8 @@ function buildSession(parsed: PersistedSession): Session { emergencyShrinkEstimate: typeof stats.emergencyShrinkEstimate === "number" && Number.isFinite(stats.emergencyShrinkEstimate) && stats.emergencyShrinkEstimate > 0 ? stats.emergencyShrinkEstimate : undefined, // #1110: one-shot overflow arm — legacy files lack it; absent = no arm. overflowArmTokens: typeof stats.overflowArmTokens === "number" && Number.isFinite(stats.overflowArmTokens) && stats.overflowArmTokens > 0 ? stats.overflowArmTokens : undefined, + // One-shot preflight fold gate — legacy files lack it; absent = fresh. + preflightRuns: typeof stats.preflightRuns === "number" && Number.isFinite(stats.preflightRuns) && stats.preflightRuns >= 0 ? stats.preflightRuns : undefined, // #3450: proven completion reservation + one-time warn flag — legacy files lack both. overflowArmCompletionReserve: typeof stats.overflowArmCompletionReserve === "number" && Number.isFinite(stats.overflowArmCompletionReserve) && stats.overflowArmCompletionReserve > 0 ? stats.overflowArmCompletionReserve : undefined, overflowArmMismatchWarned: stats.overflowArmMismatchWarned === true ? true : undefined, diff --git a/src/rollout.ts b/src/rollout.ts index 4a98dd4cd..91f0b1318 100644 --- a/src/rollout.ts +++ b/src/rollout.ts @@ -170,6 +170,14 @@ export const ROLLOUT_FEATURES: Record = { // now with `rollout.features.passDshExtensions: true` / // `BILI_ROLLOUT_PASS_DSH_EXTENSIONS=1`. passDshExtensions: { percent: 0 }, + // #7439 — stamped session-id identity: the server trusts the client's stamped + // session id + purpose and stops content-guessing subagent forks (the |sub:… + // ladder in session-resolve.ts). GA — ON by default (owner ruling 2026-11-22): + // the stamped id is battle-tested across the dsh/claude/codex lanes. The #5095 + // client-declared subagent lane-token tail is NOT gated (it is the declared + // "tail" path, not a guess). Force OFF only to debug the legacy ladder, with + // BILI_ROLLOUT_TRUST_STAMPED_ID=0 or `rollout.features.trustStampedId: false`. + trustStampedId: { percent: 100 }, }; export const BP_MAX = 10_000; diff --git a/src/server.ts b/src/server.ts index c111e6905..e69b9b44e 100644 --- a/src/server.ts +++ b/src/server.ts @@ -114,6 +114,7 @@ import { isStrictReasoningEcho, modelIdOf, normalizeStrictEchoReasoning, normali export { isStrictReasoningEcho, normalizeStrictEchoReasoning, normalizeStrictEchoResponsesInput }; import { sanitizeResponsesInputIds, dropWhitespaceResponsesMessages, normalizeResponsesMessageItems } from "./loop/adapter-responses.js"; import type { CommandcodeEnvelopeMeta } from "./commandcode-wire.js"; +import type { ZedEnvelopeMeta } from "./zed-wire.js"; import { CODEX_COMPACT_HEALTH_RATIO, codexCompactMode, codexHealthBarApplies, hasCompactionTrigger, stripBiliCompactionItems, replaceBiliCompactionItems, codexCompactGate, codexCompactGatePre, buildTriggerForgeBody, mergeForgedSummaries } from "./codex-compact.js"; import { emitPreflightError } from "./stream-error.js"; import { agentProviderRecipes } from "./agent-providers.js"; @@ -2162,6 +2163,13 @@ export type Prepared = { * via wireTransform) using this meta. Presence also gates the JSONL * response codecs and disables #371 fake-completion retry. */ commandcode?: { meta: CommandcodeEnvelopeMeta }; + /** zed cloud wire: the request came as a cloud.zed.dev /completions + * envelope — the pipeline ran on the UNWRAPPED provider wire body; + * forward() rewraps it into the envelope at the final boundary (and every + * compress-loop re-send via wireTransform) using this meta. Presence also + * forces the NDJSON response to raw byte-passthrough and disables #371 + * fake-completion retry (no in-stream loop on this lane). */ + zed?: { meta: ZedEnvelopeMeta }; /** #2740: set when a Claude Code auto-mode classifier one-shot was answered * locally (BILI_AUTO_MODE_FORGE, default on). forward() serves `body` * without contacting upstream — zero egress, zero billing for the lane. */ @@ -2269,6 +2277,11 @@ export const headroomEffectiveLogged = new Set(); * session overflow arm's judging wall is session-scoped evidence, unlike the * config-derived [headroom] value, so the dedup key carries the session id. */ export const armJudgingWallLogged = new Set(); +/** One-shot preflight fold gate — per-session "blocked trigger" log dedupe + * (managed sessions re-trigger every turn once growth outruns the fold). + * Process-lifetime like armJudgingWallLogged; never cleared. Not exported: + * used only inside preflightCompressIfNeeded (unused-exports gate #1440 P6). */ +const preflightGateBlockedLogged = new Set(); // #1840: best-known OUTPUT ceiling for the request's model, resolved through // the SAME source chain (and rank order) the output-headroom fallback uses @@ -4201,6 +4214,32 @@ export async function preflightCompressIfNeeded( } } if (limit <= 0 || !model || !triggerFires) return prepared; + // One-shot fold gate: proxy-driven preflight folding gets exactly ONE + // effective attempt per session lifecycle. Once the session has been + // compressed by bili (a committed fold) or its fold attempt was aborted + // by a client disconnect, the trigger forwards as-is. (Fork children of a + // managed session inherit the committed count — src/plugin.ts + // fork-session — so they are born managed and never spend their own shot; + // their growth is covered by #1195 + the model-side compress tool.) Why: a slow + // self-summarizer + a client stream watchdog (~300s) turn repeated + // triggers into a never-shrinking abort loop (2026-11-22 incident: + // nine preflight runs of the same ~77K payload, each a 3.5-4 min + // self-summary, each aborted at exactly +300.0s, payload identical on + // every retry). Fast summary failures (429/400/empty) do NOT spend the + // shot — the #726/#4079 contract keeps re-running the walk on + // transient summary outages. After the shot is spent, overflow recovery + // stays with #1195 in-request refold and the egress fuse, and + // steady-state growth is the model's job via the compress tool + // (nudge path) — not another proxy-side multi-minute summary. + const compressionCommitted = (session.state.stats?.compressionCount ?? 0) > 0; + const preflightSpent = (session.stats.preflightRuns ?? 0) > 0; + if (compressionCommitted || preflightSpent) { + if (!preflightGateBlockedLogged.has(session.id)) { + preflightGateBlockedLogged.add(session.id); + log("warn", `[${session.id}] preflight trigger fired but the session's one-shot fold is already spent (${compressionCommitted ? `session compression-managed (${session.state.stats?.compressionCount} committed fold(s))` : "an earlier fold attempt was aborted by a client disconnect"}) — forwarding as-is; overflow recovery stays with #1195 in-request refold and the egress fuse`); + } + return prepared; + } // #3846: an earlier local 413 for THIS origin+model at an equal or wider // window is independent evidence the payload cannot fit here — the // forward-once escapes below must not re-bet the estimator guess. Fitting @@ -4654,6 +4693,16 @@ export async function preflightCompressIfNeeded( const f = result.failure; // 重建过程也会让出执行权;所有转发许可都必须在此重新检查取消。 if (clientAbort.signal.aborted || f?.kind === "aborted") { + // One-shot fold gate: a client-disconnected abort is the livelock + // shape (2026-11-22 log-32: nine 3.5-4 min self-summaries of the + // same payload, each cut at exactly +300.0s, payload never + // shrinking). The aborted attempt spent the session's one preflight + // shot: the next trigger forwards as-is (overflow recovery stays + // with #1195 in-request refold). A FAST failure (summary 429/400/ + // empty) does NOT spend the shot — the #726/#4079 retry contract + // must keep re-running the walk on transient summary outages. + session.stats.preflightRuns = (session.stats.preflightRuns ?? 0) + 1; + markDirty(session); const detail = f?.kind === "aborted" ? f.detail : "the client disconnected during preflight compression"; log("warn", `[${session.id}] preflight aborted (${detail}); not forwarding`); return { failFast: true, status: 0, message: detail, retryable: false, respond: false }; diff --git a/src/server/handle.ts b/src/server/handle.ts index 3a6250509..a97d06ff6 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -35,7 +35,7 @@ import { enterSessionContext, log as loggerLog } from "../logger.js"; import { codexCompactGatePre, codexCompactMode, hasCompactionTrigger, isCodexHost, replaceBiliCompactionItems } from "../codex-compact.js"; import { emitPreflightError } from "../stream-error.js"; import { agentProviderRecipes } from "../agent-providers.js"; -import { affinityToken, anthropicFirstUserFrag, claudeAnthropicPersonaOrderApplies, conversationHeaderSource, claudeSubagentAgentId, claudeSubagentSplit, claudeSubagentLaneTokenOf, clientConversationHeader, codexTurnIdentity, dshPersonaFingerprintApplies, instructionsFingerprintApplies, openaiSystemTextForPersona, preferPromptCacheKeyIdentity, zcodeMemoryConversation } from "../session-id.js"; +import { affinityToken, anthropicFirstUserFrag, claudeAnthropicPersonaOrderApplies, conversationHeaderSource, claudeSubagentAgentId, claudeSubagentSplit, claudeSubagentLaneTokenOf, clientConversationHeader, codexTurnIdentity, dshPersonaFingerprintApplies, instructionsFingerprintApplies, openaiSystemTextForPersona, preferPromptCacheKeyIdentity, preferZedThreadIdIdentity, qoderSideTaskConversation, zcodeMemoryConversation } from "../session-id.js"; import { preferKiroConversationIdentity } from "../kiro.js"; import { personaConversationOrder, type SessionOrderResolution } from "../session-resolve.js"; @@ -64,6 +64,7 @@ import { BILI_PASSTHROUGH_HEADER, BILI_PLUGIN_BYPASS_HEADER, isLoopbackAddress, import { checkTunnelDestination, tunnelAllowlistFromEnv } from "../tunnel-guard.js"; import { resolveCompatDropFields } from "../compat-drop.js"; import { unwrapCommandcodeBody, type CommandcodeEnvelopeMeta } from "../commandcode-wire.js"; +import { ZED_PROVIDER_PROTOCOL, ZED_PROVIDERS, unwrapZedEnvelope, type ZedEnvelopeMeta, type ZedProvider } from "../zed-wire.js"; import { DecompressedTooLargeError, decodeRequestBody, IngestBodyTooLargeError } from "../content-encoding.js"; import { matchModelEndpoint } from "../model-endpoints.js"; import { autoModeForgeEnabled, dshAuthoredCompactionEnabled, imageRescaleEnabled, limitsDecodedBytes as knobLimitsDecodedBytes, limitsIngestBytes as knobLimitsIngestBytes, noInjectTool as knobNoInjectTool, pluginBypassOverride, rawDumpDir as knobRawDumpDir } from "../knobs.js"; @@ -401,9 +402,10 @@ async function handleRequest( let providerDestUrl: string; let protocol: WireProtocol | null; /** #1295: wire family of a declared custom endpoint (currently only - * "commandcode"). Undefined for built-in families; drives the envelope + * "commandcode"); plus the zed cloud envelope wire (POST /completions, + * body-classified). Undefined for built-in families; drives the envelope * unwrap/rewrap + JSONL codec selection further down the pipeline. */ - let wireFamily: "commandcode" | null = null; + let wireFamily: "commandcode" | "zed" | null = null; /** Gemini's model, resolved from the request path (its body never carries * one). Undefined for every other protocol. */ let googleModel: string | undefined; @@ -505,15 +507,58 @@ async function handleRequest( protocol = declared.wire; } } else { - protocol = urlPath.endsWith("/chat/completions") || urlPath.endsWith("/llm_raw_chat") - ? "openai" - : urlPath.endsWith("/v1/messages") || urlPath.endsWith("/messages") - ? "anthropic" - : urlPath.endsWith("/responses") || responsesCompact - ? "responses" - : googlePathKind(urlPath) !== null - ? "google" - : null; + // zed cloud wire: cloud.zed.dev POSTs the provider request nested in a + // `{thread_id, prompt_id, provider, model, provider_request}` envelope + // to /completions. The ENVELOPE is the classifier (commandcode + // precedent) — but it must be PROBED BEFORE the suffix chain claims + // the path, because urlPath.endsWith("/completions") lands "/completions" + // on "anthropic". The probe is classification ONLY on the raw + // pre-decode bytes; the strict codec re-validates after the decode + // below and anything it rejects relays verbatim. The marker header + // lets the prepare* layers suppress the model-side compress surface + // (the response is NDJSON byte-passthrough — an in-stream acp loop is + // structurally unreachable, #3177 reasoning). + // The probe keys off the DESTINATION path: /bili/ tunnel URLs keep + // req.url wrapper-shaped, so urlPath is the embedded path only via + // route.rewrittenUrl. + let zedPath = urlPath; + if (route?.rewrittenUrl !== undefined) { + try { + zedPath = new URL(route.rewrittenUrl).pathname; + } catch { + zedPath = ""; + } + } + let zedProtocol: WireProtocol | null = null; + if ((zedPath === "/completions" || (route?.rewrittenUrl !== undefined && urlPath === "/completions")) && zedPath !== "/completions/compact") { + let probe: Record | undefined; + try { + const raw: unknown = JSON.parse(bodyBuffer.toString("utf8")); + if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) { + const r = raw as Record; + if (typeof r.provider === "string" && (ZED_PROVIDERS as readonly string[]).includes(r.provider) + && r.provider_request !== null && typeof r.provider_request === "object" && !Array.isArray(r.provider_request)) { + probe = r; + } + } + } catch { + probe = undefined; + } + if (probe !== undefined) { + wireFamily = "zed"; + zedProtocol = ZED_PROVIDER_PROTOCOL[probe.provider as ZedProvider]; + req.headers["x-bili-zed-lane"] = "1"; + } + } + protocol = zedProtocol ?? (zedPath.endsWith("/chat/completions") || zedPath.endsWith("/llm_raw_chat") + ? "openai" + : zedPath.endsWith("/v1/messages") || zedPath.endsWith("/messages") + ? "anthropic" + : zedPath.endsWith("/responses") || responsesCompact + ? "responses" + : googlePathKind(zedPath) !== null + ? "google" + : null); } // Gemini carries the model in the PATH, not the body — resolve it here so // the window/config block below and every later model-keyed decision see @@ -812,6 +857,38 @@ async function handleRequest( parsed = unwrapped.body; ccMeta = unwrapped.meta; } + // zed cloud envelope: unwrap the `{thread_id, prompt_id, provider, model, + // provider_request}` wrapper so everything below — #1284 disambiguation, + // model/window resolution, session binding, kernel prepare — sees the + // standard provider wire. rewrapZedEnvelope restores the envelope at the + // final forward boundary. Strict fidelity (#1284 precedent): a body the + // classifier promised but the codec cannot convert relays verbatim with a + // one-time loud warning — never a partial conversion. + let zedMeta: ZedEnvelopeMeta | undefined; + let zedThreadId: string | undefined; + if (wireFamily === "zed" && protocol !== null) { + const unwrapped = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) + ? unwrapZedEnvelope(parsed as Record) + : undefined; + if (!unwrapped) { + const relayKey = `zed:${upstreamOrigin}${urlPath}`; + if (!nonConversationRelayWarned.has(relayKey)) { + nonConversationRelayWarned.add(relayKey); + if (nonConversationRelayWarned.size > NON_CONVERSATION_RELAY_WARN_CAP) { + nonConversationRelayWarned.delete(nonConversationRelayWarned.values().next().value as string); + } + log("warn", `[zed] /completions envelope body is not a convertible zed cloud request — relaying verbatim to ${maskUrlsInText(upstreamOrigin)} — ${req.method ?? "?"} ${maskUrlForLog(req.url ?? "")}`); + } + await forward(req, res, opts, bodyBuffer, null, core, config, log, route, instanceId, undefined); + return; + } + parsed = unwrapped.innerBody; + zedMeta = unwrapped.meta; + zedThreadId = unwrapped.threadId; + // The google arm's inner body carries no model (Gemini's is path-based); + // the ENVELOPE's `model` is the only source on this wire. + if (protocol === "google" && googleModel === undefined) googleModel = zedMeta.model; + } // #2824: one cheap raw-text pass decides whether the incoming-image index // (#1995/#2607) can find anything — a provably image-free body skips BOTH // index builds (each one re-converts the full history wire→core). The @@ -1209,16 +1286,19 @@ async function handleRequest( : []; const claudeSub = protocol === "anthropic" ? claudeSubagentAgentId(req.headers, systemTextsForSplit) : undefined; const responsesIdentity = protocol === "responses" - ? (codexTurn - ? { value: codexTurn.value, source: "header" as const, clientProvided: true } - : preferKiroConversationIdentity( - preferPromptCacheKeyIdentity( - conversationIdentityResponses(parsed as ResponsesRequestBody, convHeader), - parsed as ResponsesRequestBody, - ), - parsed, - req.headers, - )) + ? preferZedThreadIdIdentity( + codexTurn + ? { value: codexTurn.value, source: "header" as const, clientProvided: true } + : preferKiroConversationIdentity( + preferPromptCacheKeyIdentity( + conversationIdentityResponses(parsed as ResponsesRequestBody, convHeader), + parsed as ResponsesRequestBody, + ), + parsed, + req.headers, + ), + zedThreadId, + ) : undefined; // OpenAI chat mirrors the responses pck promotion: clients that replay // full history statelessly (omp chat-completions via a relay) send NO @@ -1232,11 +1312,14 @@ async function handleRequest( ? conversationSignalOpenai(parsed as OpenAIRequestBody, convHeader) : ""; const openaiIdentity = protocol === "openai" - ? preferPromptCacheKeyIdentity( - convHeader - ? { value: openaiSignal, source: "header" as const, clientProvided: true } - : { value: openaiSignal, source: "content-fingerprint" as const, clientProvided: false }, - parsed as { prompt_cache_key?: unknown }, + ? preferZedThreadIdIdentity( + preferPromptCacheKeyIdentity( + convHeader + ? { value: openaiSignal, source: "header" as const, clientProvided: true } + : { value: openaiSignal, source: "content-fingerprint" as const, clientProvided: false }, + parsed as { prompt_cache_key?: unknown }, + ), + zedThreadId, ) : undefined; // Anthropic mirrors the openai pck promotion (#268): the omp plugin @@ -1248,11 +1331,14 @@ async function handleRequest( ? conversationSignalAnthropic(parsed as AnthropicRequestBody, convHeader) : ""; const anthropicIdentity = protocol === "anthropic" - ? preferPromptCacheKeyIdentity( - convHeader - ? { value: anthropicSignal, source: "header" as const, clientProvided: true } - : { value: anthropicSignal, source: "content-fingerprint" as const, clientProvided: false }, - parsed as { prompt_cache_key?: unknown }, + ? preferZedThreadIdIdentity( + preferPromptCacheKeyIdentity( + convHeader + ? { value: anthropicSignal, source: "header" as const, clientProvided: true } + : { value: anthropicSignal, source: "content-fingerprint" as const, clientProvided: false }, + parsed as { prompt_cache_key?: unknown }, + ), + zedThreadId, ) : undefined; // Gemini native wire: no conversation-header convention, and no @@ -1268,11 +1354,14 @@ async function handleRequest( // Without this, every Antigravity window shares the anonymous branch and // collides on the constant FNV-1a sessionId / empty-prefix affinity. const googleIdentity = protocol === "google" - ? { - value: v1ConvId ?? googleSignal, - source: v1ConvId || convHeader ? ("header" as const) : ("content-fingerprint" as const), - clientProvided: !!v1ConvId || !!convHeader, - } + ? preferZedThreadIdIdentity( + { + value: v1ConvId ?? googleSignal, + source: v1ConvId || convHeader ? ("header" as const) : ("content-fingerprint" as const), + clientProvided: !!v1ConvId || !!convHeader, + }, + zedThreadId, + ) : undefined; // #2156: a request that will ride the #388 side passthrough further // down must NEVER participate in persona namespace resolution. @@ -1529,7 +1618,20 @@ async function handleRequest( const zcodeMemory = zcodeParentIdentity?.clientProvided ? zcodeMemoryConversation(zcodeParentIdentity.value, req.headers) : undefined; - const conversation = zcodeMemory !== undefined ? zcodeMemory : protocol === "google" + // #7439 worklist — Qoder side tasks (agent/webfetch/hook summary) reuse + // the parent x-session-id and are tagged only in body + // metadata.business_type; give each its own |aux: lane (zcode-memory + // pattern) so they don't merge into the parent conversation. Responses + // wire only; plain Task subagents carry no wire marker. + const qoderSideTask = protocol === "responses" + ? qoderSideTaskConversation( + (responsesIdentity?.value + ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader)) ?? "", + parsed, + ) + : undefined; + const auxSidecar = zcodeMemory ?? qoderSideTask; + const conversation = auxSidecar !== undefined ? auxSidecar : protocol === "google" // #2730: the google lane is persona-aware too — dsh stamps its one // conversation id on every wire including gemini (`x-bili-plugin: dsh` // is wire-agnostic, dsh-native.ts; MODEL_API_SUFFIX routes google @@ -3367,6 +3469,7 @@ async function handleRequest( const runPrepare = async (): Promise => { const p = await runPrepareInner(); if (ccMeta !== undefined) p.commandcode = { meta: ccMeta }; + if (wireFamily === "zed" && zedMeta !== undefined) p.zed = { meta: zedMeta }; return p; }; // #332: codex's native remote-compaction request (trigger form) diff --git a/src/server/headers.ts b/src/server/headers.ts index c10477f89..db7479aac 100644 --- a/src/server/headers.ts +++ b/src/server/headers.ts @@ -48,6 +48,12 @@ export const UPSTREAM_HOP_HEADERS = new Set([ // host↔bili bookkeeping like the pf-* handshake above; the real upstream // must never see it. "x-bili-msg-ids", + // zed cloud lane marker: stamped by the /completions envelope classifier in + // handle() so the prepare* layers can tell the zed wire apart (its response + // is NDJSON byte-passthrough, so the model-side compress surface is off). + // Pure bili-internal bookkeeping like the pf-* handshake above; the real + // upstream must never see it. + "x-bili-zed-lane", "te", "trailer", "upgrade", diff --git a/src/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index 715ff6851..31fcaeaa0 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -85,7 +85,12 @@ export async function prepareAnthropic( const incomingMsgSeqs = (parsed as Record)[MSG_SEQS_BODY_FIELD]; delete (parsed as Record)[MSG_SEQS_BODY_FIELD]; ++session.stats.requests; - const injectTools = opts.compress.injectTool && !pluginMode; + // zed cloud wire: the response is NDJSON byte-passthrough, so an in-stream + // acp loop is structurally unreachable (same reasoning as DSH #3177) — the + // model-side compress surface (tools + standing prompt + nudge) is off. + const zedLane = req.headers["x-bili-zed-lane"] !== undefined; + const modelSurfaceOn = opts.compress.injectTool && !zedLane; + const injectTools = modelSurfaceOn && !pluginMode; // #3417: lane decisions (profile + per-wire observation) own the // surface gates; the dsh* alias stays for the remaining reads in this // file (Step 3 of #3417 renames the consumers). @@ -94,7 +99,7 @@ export async function prepareAnthropic( pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, - shouldInject: opts.compress.injectTool, + shouldInject: modelSurfaceOn, pluginHeaderPresent: pluginAgentHeader(req.headers) !== undefined, }); // #3222: #651's reasoning-drop plan, computed on the INBOUND history before @@ -338,14 +343,14 @@ export async function prepareAnthropic( // (applyAbsorbView hides regardless of enablement). const absorbBlock = effectiveAbsorbBlock(pluginMode, config, opts.compress.absorb); const absorbTools = absorbToolsFor(absorbBlock?.toolName ?? ABSORB_TOOL_NAME); - const absorbActive = absorbBlock?.enabled === true && opts.compress.injectTool; + const absorbActive = absorbBlock?.enabled === true && modelSurfaceOn; // #5765: block-lifecycle tools — one switch, off by default. const blockOps = blockOpsTools(); - const blockOpsActive = effectiveBlockOpsEnabled(pluginMode, config, opts.compress.blockOps) && opts.compress.injectTool; + const blockOpsActive = effectiveBlockOpsEnabled(pluginMode, config, opts.compress.blockOps) && modelSurfaceOn; // acp_rule has no processTurn side effect (no markers/instructions are // ever injected into messages), so unlike absorb it needs no loop- // config stripping — only tool availability matters. - const rulesActive = rulesEnabled(config) && opts.compress.injectTool; + const rulesActive = rulesEnabled(config) && modelSurfaceOn; // [#1097] the kernel ccr-store node ID-references oversized tool results // BEFORE absorb (ID-reference wins over distill); armed policy is // stamped per-request — strip `ccr` from the loop config when disarmed diff --git a/src/server/prepare-google.ts b/src/server/prepare-google.ts index 9906efb98..f25b48273 100644 --- a/src/server/prepare-google.ts +++ b/src/server/prepare-google.ts @@ -123,7 +123,11 @@ export async function prepareGoogle( // Title-generation requests (tiny budget) get no compress tooling — same // heuristic and same prefix-cache rationale as prepareOpenai. const isTitleGen = maxTokens <= 200; - const shouldInject = opts.compress.injectTool && !isTitleGen; + // zed cloud wire: the response is NDJSON byte-passthrough, so an in-stream + // acp loop is structurally unreachable (same reasoning as DSH #3177) — the + // model-side compress surface (tools + standing prompt + nudge) is off. + const zedLane = req.headers["x-bili-zed-lane"] !== undefined; + const shouldInject = opts.compress.injectTool && !isTitleGen && !zedLane; const injectTools = shouldInject && !pluginMode; // #3417: surface gating lives in lane-decisions (observed reachability // overrides the dsh default, #3401); alias kept for the remaining reads. diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index 034d6e916..d6ab3f81e 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -208,7 +208,11 @@ export async function prepareOpenai( // system prompt bytes (compress prompt added/removed) — which breaks the // provider prefix cache for every subsequent turn. const isTitleGen = maxTokens <= 200; - const shouldInject = opts.compress.injectTool && !isTitleGen; + // zed cloud wire: the response is NDJSON byte-passthrough, so an in-stream + // acp loop is structurally unreachable (same reasoning as DSH #3177) — the + // model-side compress surface (tools + standing prompt + nudge) is off. + const zedLane = req.headers["x-bili-zed-lane"] !== undefined; + const shouldInject = opts.compress.injectTool && !isTitleGen && !zedLane; const injectTools = shouldInject && !pluginMode; // #3177: DSH registers bili's ACP tools host-scope (invisible to the preset // agent — 0/3939 request headers carry them), so model-driven compression is diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index 2075c7861..88b14e856 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -159,7 +159,11 @@ export async function prepareResponses( const markerCounts = stripRawStage(parsed, "responses"); logRawStripCounts(markerCounts, log, sessionId); - const shouldInject = opts.compress.injectTool; + // zed cloud wire: the response is NDJSON byte-passthrough, so an in-stream + // acp loop is structurally unreachable (same reasoning as DSH #3177) — the + // model-side compress surface (tools + standing prompt + nudge) is off. + const zedLane = req.headers["x-bili-zed-lane"] !== undefined; + const shouldInject = opts.compress.injectTool && !zedLane; const injectTools = shouldInject && !pluginMode; // #3417: surface gating lives in lane-decisions (observed reachability // overrides the dsh default, #3401). diff --git a/src/server/relay.ts b/src/server/relay.ts index 9a298757a..d08e39470 100644 --- a/src/server/relay.ts +++ b/src/server/relay.ts @@ -17,6 +17,7 @@ import { credentialFingerprint, generationParamFp, lastForwardedBody, noteClient import { warnCacheCollapse } from "../cache-warn.js"; import { stampOutbound } from "../chain-checkpoint.js"; import { rewrapCommandcodeBody } from "../commandcode-wire.js"; +import { rewrapZedEnvelope } from "../zed-wire.js"; import { applyCompatDropFields, dropCompatFieldsJson, resolveCompatDropFields } from "../compat-drop.js"; import { applyCompatRoles, applyCompatRolesJson, detectRoleRejection, detectSystemPlacementError, hasOffHeadSystem, resolveCompatRoles, type CompatRoles } from "../compat-roles.js"; import { builtinCompatRoles, builtinRoleRestorePoints, withRestoredRoles } from "../kiro.js"; @@ -718,6 +719,12 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare wireBody = JSON.stringify(rewrapCommandcodeBody(JSON.parse(wireBody) as Record, prepared.commandcode.meta)); } catch { /* malformed flat body — pass through unchanged */ } } + // zed cloud wire: same final-boundary rewrap for the /completions envelope. + if (prepared?.zed && typeof wireBody === "string") { + try { + wireBody = JSON.stringify(rewrapZedEnvelope(JSON.parse(wireBody) as Record, prepared.zed.meta)); + } catch { /* malformed inner body — pass through unchanged */ } + } // #1421/#1683: outbound chain checkpoint — when egress stamping is enabled // (chainEgressStamp, DEFAULT OFF), every request THIS instance actually // processed leaves with a request-level stamp, so a downstream bili applies @@ -778,7 +785,8 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare // retry that dropped it would present flat OpenAI where the client's wire // expects the CLI envelope. const ccMetaForResend = prepared?.commandcode?.meta; - const wireTransform = compatProtocol || (steerCfg !== null && steerCfg.enabled) || compatDropPaths.length > 0 || v1Active || ccMetaForResend !== undefined + const zedMetaForResend = prepared?.zed?.meta; + const wireTransform = compatProtocol || (steerCfg !== null && steerCfg.enabled) || compatDropPaths.length > 0 || v1Active || ccMetaForResend !== undefined || zedMetaForResend !== undefined ? (b: Record): Record => { let out = b; if (compatProtocol && compatRoles) applyCompatRolesJson(out, compatProtocol, compatRoles); @@ -787,6 +795,7 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare // #3129: re-nest the rebuilt inner request into the CloudCode envelope. out = v1Active ? wrapV1Internal(out, v1Meta) : out; if (ccMetaForResend !== undefined) out = rewrapCommandcodeBody(out, ccMetaForResend); + if (zedMetaForResend !== undefined) out = rewrapZedEnvelope(out, zedMetaForResend); return out; } : undefined; @@ -2474,7 +2483,7 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare try { // #1295: commandcode streams terminate with their own finish event — // no fake-completion shape exists to buffer-and-retry (#371 off). - if (prepared !== null && prepared.stream && !prepared.commandcode && !prepared.sidePassthrough && maxFakeCompletionRetries() > 0) { + if (prepared !== null && prepared.stream && !prepared.commandcode && !prepared.zed && !prepared.sidePassthrough && maxFakeCompletionRetries() > 0) { // #1900: retry from wireBody — the exact bytes this request's main // attempt shipped (post wireTransform and any same-request re-send), // never the raw client body: upstream may have rejected those raw @@ -2534,7 +2543,13 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare opencodeLogId: upstream.headers.get("x-opencode-log-id") ?? undefined, cfRay: upstream.headers.get("cf-ray") ?? undefined, }; - if (prepared && prepared.resetAfterSuccess) { + if (prepared && prepared.zed) { + // zed cloud wire: NDJSON response — raw byte passthrough, no + // parsing, no usage accounting (request side is the only side bili + // rewrites on this lane; an in-stream loop is structurally + // unreachable, #3177 reasoning). + await pipeThrough(responseBody, res); + } else if (prepared && prepared.resetAfterSuccess) { const [toClient, toObserve] = responseBody.tee(); const observed = observeResponsesTerminalState(toObserve, prepared.stream); const tagLog = (msg: string) => log("info", `[${prepared.session.id}] ${msg}`); diff --git a/src/session-id.ts b/src/session-id.ts index e0b220ee9..d5ed10894 100644 --- a/src/session-id.ts +++ b/src/session-id.ts @@ -6,7 +6,7 @@ import type { PromptCacheRouting } from "./config.js"; export type ConversationIdentity = { value: string; - source: "header" | "body-session" | "metadata-session" | "previous-response" | "prompt-cache-key" | "content-fingerprint" | "generated"; + source: "header" | "body-session" | "metadata-session" | "previous-response" | "prompt-cache-key" | "zed-thread-id" | "content-fingerprint" | "generated"; clientProvided: boolean; }; @@ -95,8 +95,12 @@ export function conversationHeaderSource(headers: Record; + const bt = m.business_type; + if (typeof bt !== "string" || !QODER_SIDE_TASK_TYPES.has(bt)) return undefined; + // Two side tasks of the SAME business_type under one parent are distinct + // logical conversations. Disambiguate with the per-task id from the body + // (same pattern as zcodeMemoryConversation's x-query-id) so GA-on (which + // retires the in-lane content-guessed split) does not merge them; fall back + // to the type-only lane when the id is absent or malformed. + const taskId = m.task_id; + if (typeof taskId === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(taskId)) { + return `${parent}|aux:qoder-${bt}:${taskId}`; + } + return `${parent}|aux:qoder-${bt}`; +} + /** #1106/#1102: whether the Responses-wire instructions fingerprint should * participate in the compression-session key at all. Inverted allowlist: the * fingerprint is OFF by default and applies ONLY to signals with a verified @@ -431,6 +462,26 @@ export function preferPromptCacheKeyIdentity( return { ...identity, value: pck, source: "prompt-cache-key", clientProvided: true }; } +/** + * zed cloud wire thread_id promotion (#zed-cloud): cloud.zed.dev carries the + * conversation id ONLY in the request envelope (`{thread_id, prompt_id, + * provider, model, provider_request}`) — the inner provider body has none and + * zed sends no roster conversation header. `thread_id` is zed's stable + * per-thread uuid (the agent thread id), so it is exactly the missing signal + * the content-fingerprint fallback stands in for. It only replaces the + * fingerprint — real conversation headers and body session_ids stay stronger, + * so this can never override an identity the client stated more explicitly. + */ +export function preferZedThreadIdIdentity( + identity: T | undefined, + threadId: unknown, +): T | undefined { + if (!identity || identity.source !== "content-fingerprint") return identity; + const tid = typeof threadId === "string" ? threadId.trim() : ""; + if (tid.length === 0) return identity; + return { ...identity, value: tid, source: "zed-thread-id", clientProvided: true }; +} + /** * Codex turn-metadata partitioning (#316 / PR-A). * @@ -545,6 +596,21 @@ export function codexTurnIdentity(headers: Record): string | undefined { + const raw = headers["x-claude-code-request-class"]; + const v = typeof raw === "string" ? raw.trim() : ""; + return v !== "" && (CLAUDE_REQUEST_CLASSES as readonly string[]).includes(v) ? v : undefined; +} + export function claudeSubagentAgentId( headers: Record, systemBlocks: string[], @@ -557,6 +623,15 @@ export function claudeSubagentAgentId( const agentId = typeof agent === "string" && agent.trim().length > 0 ? agent.trim() : undefined; const parentId = typeof parent === "string" && parent.trim().length > 0 ? parent.trim() : undefined; if (agentId === undefined && parentId === undefined) return undefined; + // #7439: an explicit client-side task label (x-claude-code-request-class, + // gated on CLAUDE_CODE_GATEWAY_HINT_HEADERS) overrides the system-prefix + // heuristic. Strictly additive: "subagent" forces the split even when the + // system text looks main-like; "main" suppresses it; an absent label keeps + // the legacy path below byte-for-byte. The unique id is still + // agentId ?? parentId (no lane-token threading). + const reqClass = claudeRequestClassOf(headers); + if (reqClass === "subagent") return agentId ?? parentId; + if (reqClass === "main") return undefined; const isMain = systemBlocks.some((block) => { const t = block.trimStart(); return MAIN_SYSTEM_PREFIXES.some((p) => t.startsWith(p)); diff --git a/src/session-resolve.ts b/src/session-resolve.ts index e68d9a676..6476622b0 100644 --- a/src/session-resolve.ts +++ b/src/session-resolve.ts @@ -87,6 +87,7 @@ import { log as loggerLog } from "./logger.js"; // src/order-persist.ts — each side calls the other only inside function // bodies, never at module evaluation; see the note on its import). import { scheduleOrderPersist } from "./order-persist.js"; +import { featureEnabled } from "./rollout.js"; const TAIL_WINDOW = 8; @@ -342,6 +343,10 @@ export function resolveSessionOrder(rawId: string, history: unknown, personaTag? // empty system/instructions verbatim (non-anchoring) — this branch is // library defense for direct callers: the corpus census lane.) if (!mainShaped(kinds) && tag === "") { + if (featureEnabled("trustStampedId")) { + record(rawId, turns, tagHash, model); + return { key: rawId, action: "claim", reason: "trust-stamped-id: shallow side request rides the verbatim id (no |sub:aux fork)" }; + } return { key: `${rawId}|sub:aux`, action: "derived-aux", reason: "shallow history with no assistant turns" }; } record(rawId, turns, tagHash, model); @@ -499,6 +504,10 @@ export function resolveSessionOrder(rawId: string, history: unknown, personaTag? // headless-subagent call site passes one) widens the key into a // three-segment form so distinct same-type runs never share a // compression session; empty degrades to the two-segment key. + if (featureEnabled("trustStampedId")) { + record(rawId, turns, effectiveTagHash, effectiveModel); + return { key: rawId, action: "reanchor", reason: "trust-stamped-id: persona change rides the verbatim id (no |sub: fork)" }; + } const laneKey = disc !== "" ? `${rawId}|sub:${fp16(tag)}:${fp16(disc)}` : `${rawId}|sub:${fp16(tag)}`; record(laneKey, turns, tagHash, model); return { key: laneKey, action: "derived-persona", reason: "persona text changed without continuing history — persona lane" }; @@ -544,6 +553,10 @@ export function resolveSessionOrder(rawId: string, history: unknown, personaTag? // subagents under one main id) on distinct compression sessions. const taskRescue = tryMsgIdRescue("diverged-order"); if (taskRescue !== null) return taskRescue; + if (featureEnabled("trustStampedId")) { + record(rawId, turns, effectiveTagHash, effectiveModel); + return { key: rawId, action: "reanchor", reason: "trust-stamped-id: diverged order rides the verbatim id (no |sub:task fork)" }; + } return { key: `${rawId}|sub:task:${skel8(kinds)}`, action: "derived-task", reason: "no order+fragment alignment with the recorded skeleton" }; } // Shorter than recorded: either head truncation (dsh native compaction @@ -564,6 +577,10 @@ export function resolveSessionOrder(rawId: string, history: unknown, personaTag? } const shortRescue = tryMsgIdRescue("shorter-divergent"); if (shortRescue !== null) return shortRescue; + if (featureEnabled("trustStampedId")) { + record(rawId, turns, effectiveTagHash, effectiveModel); + return { key: rawId, action: "reanchor", reason: "trust-stamped-id: shorter divergent tail rides the verbatim id (no |sub:task fork)" }; + } return { key: `${rawId}|sub:task:${skel8(kinds)}`, action: "derived-task", diff --git a/src/session.ts b/src/session.ts index 2c8064415..336fae768 100644 --- a/src/session.ts +++ b/src/session.ts @@ -459,6 +459,21 @@ export type Session = { * usage report (one-shot, per the #554 contract) and on compression * reset. Absent on legacy session files → treated as no arm. */ overflowArmTokens?: number; + /** One-shot preflight fold gate — 1 when the session's preflight + * fold attempt was ABORTED by a client disconnect (the livelock + * shape: a 3.5-4 min self-summary cut at the client's ~300s stream + * watchdog, payload never shrinking — 2026-11-22 log-32 incident: + * nine runs, each aborted at exactly +300.0s). The preflight + * trigger (server.ts preflightCompressIfNeeded) forwards as-is once + * this is set or the session carries committed compression + * (state.stats.compressionCount). A fast summary failure (429/400/ + * empty) does NOT set it — the #726/#4079 retry contract keeps + * re-running the walk on transient outages. Overflow recovery after + * the shot is spent lives in #1195 in-request refold + the egress + * fuse; steady growth is the model's job via the compress tool + * (nudge path). Persisted; cleared on compression reset. + * Absent on legacy session files → treated as fresh. */ + preflightRuns?: number; /** #3450: completion-channel reservation PROVEN by an upstream-stated * overflow ("N in the completion" billed against the same wall) — * preflight folds against window − reserve because the foldable @@ -1811,6 +1826,10 @@ export function resetSessionCompression(session: Session): void { // longer bounds this session; drop it so the guard falls back to the // declared window instead of clamping to a stale ceiling. delete session.stats.overflowArmTokens; + // One-shot fold gate: the rebuilt conversation is a fresh lifecycle — + // it gets its own first preflight attempt (matches the reset semantics + // of the arm and baseline it rides alongside). + delete session.stats.preflightRuns; // #3450: same boundary — the proven completion reservation described the // pre-compaction payload lineage, and the rebuilt conversation re-arms the // one-time mismatch warning. diff --git a/src/zed-wire.ts b/src/zed-wire.ts new file mode 100644 index 000000000..6be917639 --- /dev/null +++ b/src/zed-wire.ts @@ -0,0 +1,81 @@ +// Codec for the zed cloud wire family: cloud.zed.dev wraps a standard provider +// request in an envelope ({thread_id, prompt_id, provider, model, +// provider_request}). unwrap turns one into the inner provider wire body so +// the standard pipeline (kernel, preflight, window resolution, session +// binding) runs unchanged; rewrap restores the envelope at the final forward +// boundary AFTER pipeline mutations have applied to the inner body. +// +// Strict fidelity (#1284 precedent): ANY shape this codec cannot convert is +// rejected (undefined) and the caller relays the original bytes verbatim — +// never a partial conversion. + +export const ZED_PROVIDERS = ["anthropic", "open_ai", "google", "x_ai"] as const; + +export type ZedProvider = (typeof ZED_PROVIDERS)[number]; + +export const ZED_PROVIDER_PROTOCOL: Record = { + anthropic: "anthropic", + open_ai: "responses", + google: "google", + x_ai: "openai", +}; + +export interface ZedEnvelopeMeta { + /** Every original top-level envelope key except `provider_request`, verbatim. */ + rest: Record; + provider: ZedProvider; + threadId?: string; + promptId?: string; + model?: string; +} + +interface UnwrappedZedEnvelope { + innerBody: Record; + provider: ZedProvider; + threadId?: string; + promptId?: string; + meta: ZedEnvelopeMeta; +} + +const isObj = (v: unknown): v is Record => v !== null && typeof v === "object" && !Array.isArray(v); + +function zedInnerShapeOk(provider: ZedProvider, inner: Record): boolean { + switch (provider) { + case "anthropic": + case "x_ai": + return Array.isArray(inner.messages) && inner.messages.length > 0; + case "open_ai": + return Array.isArray(inner.input); + case "google": + return Array.isArray(inner.contents); + } +} + +export function unwrapZedEnvelope(parsed: Record): UnwrappedZedEnvelope | undefined { + const provider = parsed.provider; + if (typeof provider !== "string" || !(ZED_PROVIDERS as readonly string[]).includes(provider)) return undefined; + const inner = parsed.provider_request; + if (!isObj(inner)) return undefined; + if (!zedInnerShapeOk(provider as ZedProvider, inner)) return undefined; + const rest: Record = {}; + for (const [k, v] of Object.entries(parsed)) { + if (k !== "provider_request") rest[k] = v; + } + const threadId = typeof rest.thread_id === "string" && rest.thread_id.length > 0 ? (rest.thread_id as string) : undefined; + const promptId = typeof rest.prompt_id === "string" && rest.prompt_id.length > 0 ? (rest.prompt_id as string) : undefined; + const model = typeof rest.model === "string" ? (rest.model as string) : undefined; + const meta: ZedEnvelopeMeta = { rest, provider: provider as ZedProvider, threadId, promptId, model }; + return { innerBody: inner, provider: provider as ZedProvider, threadId, promptId, meta }; +} + +export function rewrapZedEnvelope(innerBody: Record, meta: ZedEnvelopeMeta): Record { + // Every envelope field passes through VERBATIM from meta.rest (thread_id / + // prompt_id / provider / model are never pipeline-mutated); only `model` is + // refreshed when the pipeline rewrote the inner body's model, and + // `provider_request` carries the transformed inner body. + const out: Record = { ...meta.rest }; + const innerModel = typeof innerBody.model === "string" ? innerBody.model : undefined; + if (innerModel !== undefined) out.model = innerModel; + out.provider_request = innerBody; + return out; +} diff --git a/tests/claude-subagent-split.test.ts b/tests/claude-subagent-split.test.ts index bf4e9f1e4..577364fb0 100644 --- a/tests/claude-subagent-split.test.ts +++ b/tests/claude-subagent-split.test.ts @@ -6,7 +6,7 @@ import { defaultConfig } from "acp-kernel"; import { startServer } from "../src/server.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _resetSessionsForTest, peekSession } from "../src/session.ts"; -import { claudeSubagentAgentId, claudeSubagentSplit } from "../src/session-id.ts"; +import { claudeSubagentAgentId, claudeSubagentSplit, claudeRequestClassOf } from "../src/session-id.ts"; import type { ProxyOptions } from "../src/config.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; @@ -138,6 +138,39 @@ test("claudeSubagentAgentId: two-signal discrimination (headers + main system pr assert.equal(claudeSubagentAgentId(subagentHeaders, [" You are Claude Code..."]), undefined, "main prefix matched after leading whitespace"); }); +test("claudeRequestClassOf: validates the per-task label against the known set", () => { + for (const v of ["main", "subagent", "workflow", "compaction", "auxiliary", "side_reply"]) { + assert.equal(claudeRequestClassOf({ "x-claude-code-request-class": v }), v, `accepts ${v}`); + } + assert.equal(claudeRequestClassOf({ "x-claude-code-request-class": "bogus" }), undefined, "unknown value is treated as absent"); + assert.equal(claudeRequestClassOf({}), undefined, "absent header is undefined"); + assert.equal(claudeRequestClassOf({ "x-claude-code-request-class": ["subagent"] }), undefined, "array-valued (repeated) header is ambiguous → absent"); +}); + +test("#7439 request-class override: subagent label beats a main-like system; main label beats an agent-id", () => { + // A subagent whose system text STARTS with a main prefix would normally be + // classified as main (no split) by the system-prefix heuristic. An explicit + // request-class=subagent label now forces the split. + const mainLikeSystem = ["You are Claude Code, Anthropic's official CLI..."]; + const subWithMainLikeSystem = { "x-claude-code-agent-id": SUB_AGENT, "x-claude-code-request-class": "subagent" }; + assert.equal(claudeSubagentAgentId(subWithMainLikeSystem, mainLikeSystem), SUB_AGENT, "request-class=subagent forces the split even with a main-like system block"); + // ...but WITHOUT the label the same request stays unsplit (legacy heuristic) — proves the change is additive. + assert.equal(claudeSubagentAgentId({ "x-claude-code-agent-id": SUB_AGENT }, mainLikeSystem), undefined, "no label → legacy heuristic (main-like system) is unchanged"); + // A main turn that (oddly) carries an agent-id + request-class=main must NOT split. + assert.equal( + claudeSubagentAgentId({ "x-claude-code-agent-id": SUB_AGENT, "x-claude-code-request-class": "main" }, mainLikeSystem), + undefined, + "request-class=main suppresses the split", + ); + // A side task (compaction) is neither "main" nor "subagent", so it falls + // through to the legacy header/system path (unchanged). + assert.equal( + claudeSubagentAgentId({ "x-claude-code-agent-id": SUB_AGENT, "x-claude-code-request-class": "compaction" }, GENERAL_PURPOSE_SUB_SYSTEM), + SUB_AGENT, + "compaction (not main/sub) falls through to the legacy header/system path", + ); +}); + test("claudeSubagentSplit: stable namespace, main untouched", () => { assert.equal(claudeSubagentSplit(SESSION, subagentHeaders, GENERAL_PURPOSE_SUB_SYSTEM), SUB_SESSION); assert.equal(claudeSubagentSplit(SESSION, subagentHeaders, GENERAL_PURPOSE_SUB_SYSTEM), SUB_SESSION, "same agent id reuses the split id across turns"); diff --git a/tests/dsh-persona-continuity.test.ts b/tests/dsh-persona-continuity.test.ts index 48efe5c4e..93ecc0267 100644 --- a/tests/dsh-persona-continuity.test.ts +++ b/tests/dsh-persona-continuity.test.ts @@ -24,6 +24,11 @@ import test from "node:test"; import assert from "node:assert/strict"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy +// |sub: fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + import http from "node:http"; import { once } from "node:events"; import { createHash } from "node:crypto"; diff --git a/tests/issue2601-model-drift-absorption.test.ts b/tests/issue2601-model-drift-absorption.test.ts index b0fe613e0..10e084687 100644 --- a/tests/issue2601-model-drift-absorption.test.ts +++ b/tests/issue2601-model-drift-absorption.test.ts @@ -23,6 +23,11 @@ // WITHOUT parsing the system line-diff). import test from "node:test"; import assert from "node:assert/strict"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy +// |sub: fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + import path from "node:path"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; diff --git a/tests/issue2601-persona-fork-lineage.test.ts b/tests/issue2601-persona-fork-lineage.test.ts index ccf71bd8d..83be3f619 100644 --- a/tests/issue2601-persona-fork-lineage.test.ts +++ b/tests/issue2601-persona-fork-lineage.test.ts @@ -26,6 +26,11 @@ // through the normalized chain second chance. import test, { after } from "node:test"; import assert from "node:assert/strict"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy +// |sub: fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + import http from "node:http"; import { once } from "node:events"; import path from "node:path"; diff --git a/tests/issue2944-neutral-skeleton.test.ts b/tests/issue2944-neutral-skeleton.test.ts index 0c99581eb..3bd830150 100644 --- a/tests/issue2944-neutral-skeleton.test.ts +++ b/tests/issue2944-neutral-skeleton.test.ts @@ -46,6 +46,10 @@ process.env.XDG_DATA_HOME = join(XDG, "data"); process.env.XDG_STATE_HOME = join(XDG, "state"); process.env.BILI_PERSIST = "0"; process.env.NODE_ENV = "test"; +// Pin the legacy |sub: ladder: trustStampedId is now GA-on by default +// (#7439), but this suite characterizes the OLD resolver forks — force the +// feature OFF so it keeps asserting the pre-retirement behavior. +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; const { prefixAffinity } = await import("../src/prefix-affinity.ts"); // retired-module pin: persona-anchor — intentional dual-run 瞄点 (this suite diff --git a/tests/issue2948-aux-lane-lineage-guard.test.ts b/tests/issue2948-aux-lane-lineage-guard.test.ts index d9aaa97a8..bb27a96c3 100644 --- a/tests/issue2948-aux-lane-lineage-guard.test.ts +++ b/tests/issue2948-aux-lane-lineage-guard.test.ts @@ -16,6 +16,10 @@ // B. a REAL ref-holding fork is STILL followed even when a ref-less aux // lane is fresher than it (filter-then-pick; #2601 preserved). import test, { after } from "node:test"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy |sub: +// fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; import assert from "node:assert/strict"; import http from "node:http"; import { once } from "node:events"; diff --git a/tests/issue3397-persona-restart-stability.test.ts b/tests/issue3397-persona-restart-stability.test.ts index 747dd09f0..d15bc89cd 100644 --- a/tests/issue3397-persona-restart-stability.test.ts +++ b/tests/issue3397-persona-restart-stability.test.ts @@ -22,6 +22,11 @@ // through the proxy, mirroring the #2601 lineage rig. import test, { after } from "node:test"; import assert from "node:assert/strict"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy +// |sub: fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + import http from "node:http"; import { once } from "node:events"; import path from "node:path"; diff --git a/tests/issue4352-claude-anthropic-subagent-split.test.ts b/tests/issue4352-claude-anthropic-subagent-split.test.ts index bd8c6f682..42d9e0db0 100644 --- a/tests/issue4352-claude-anthropic-subagent-split.test.ts +++ b/tests/issue4352-claude-anthropic-subagent-split.test.ts @@ -1,5 +1,10 @@ import test from "node:test"; import assert from "node:assert/strict"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy +// |sub: fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + import http from "node:http"; import { once } from "node:events"; import { createHash, randomUUID } from "node:crypto"; diff --git a/tests/issue4778-dsh-goal-subfork.test.ts b/tests/issue4778-dsh-goal-subfork.test.ts index 524e795da..d2377c4eb 100644 --- a/tests/issue4778-dsh-goal-subfork.test.ts +++ b/tests/issue4778-dsh-goal-subfork.test.ts @@ -19,6 +19,11 @@ import test from "node:test"; import assert from "node:assert/strict"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy +// |sub: fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + import http from "node:http"; import { once } from "node:events"; import { createHash } from "node:crypto"; diff --git a/tests/issue5095-subagent-lane-token.test.ts b/tests/issue5095-subagent-lane-token.test.ts index e3b61fbc1..32a149faa 100644 --- a/tests/issue5095-subagent-lane-token.test.ts +++ b/tests/issue5095-subagent-lane-token.test.ts @@ -1,5 +1,10 @@ import test from "node:test"; import assert from "node:assert/strict"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy +// |sub: fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + import http from "node:http"; import { once } from "node:events"; import { createHash, randomUUID } from "node:crypto"; diff --git a/tests/issue5686-tagchanged-shorter-tail-reanchor.test.ts b/tests/issue5686-tagchanged-shorter-tail-reanchor.test.ts index 1503bc4c7..d30780fd3 100644 --- a/tests/issue5686-tagchanged-shorter-tail-reanchor.test.ts +++ b/tests/issue5686-tagchanged-shorter-tail-reanchor.test.ts @@ -26,6 +26,11 @@ import test from "node:test"; import assert from "node:assert/strict"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy +// |sub: fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + import { createHash } from "node:crypto"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; diff --git a/tests/issue5719-msgid-lane-identity.test.ts b/tests/issue5719-msgid-lane-identity.test.ts index a67f971be..c63e3637d 100644 --- a/tests/issue5719-msgid-lane-identity.test.ts +++ b/tests/issue5719-msgid-lane-identity.test.ts @@ -39,6 +39,11 @@ import test from "node:test"; import assert from "node:assert/strict"; +// Pin the legacy |sub: ladder: trustStampedId is GA-on by default (#7439); this +// suite characterizes the OLD msgid-lane guard-rail forks (T2/T3/T4) — force the +// feature OFF to keep asserting the pre-retirement behavior (issue2944 idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + const { resolveSessionOrder, diff --git a/tests/issue5719-self-checkpoint-reanchor.test.ts b/tests/issue5719-self-checkpoint-reanchor.test.ts index 18b2295bf..be9465e17 100644 --- a/tests/issue5719-self-checkpoint-reanchor.test.ts +++ b/tests/issue5719-self-checkpoint-reanchor.test.ts @@ -21,6 +21,11 @@ import test from "node:test"; import assert from "node:assert/strict"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy +// |sub: fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + import { createHash } from "node:crypto"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; diff --git a/tests/persona-fork-active-parent-guard.test.ts b/tests/persona-fork-active-parent-guard.test.ts index 0c1cf45af..7d47b123c 100644 --- a/tests/persona-fork-active-parent-guard.test.ts +++ b/tests/persona-fork-active-parent-guard.test.ts @@ -20,6 +20,10 @@ // (`fork.lastSeen > parent.lastSeen`, the pre-fix rule, which also matches a // STILL-ACTIVE parent whose parallel fork happens to be fresher). import test, { after } from "node:test"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy |sub: +// fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; import assert from "node:assert/strict"; import http from "node:http"; import { once } from "node:events"; diff --git a/tests/preflight-client-abort.test.ts b/tests/preflight-client-abort.test.ts index 759641fb9..4f25485bc 100644 --- a/tests/preflight-client-abort.test.ts +++ b/tests/preflight-client-abort.test.ts @@ -160,6 +160,10 @@ for (const pluginMode of [false, true]) { assert.equal(result.retryable, false); assert.ok(f.session.state.blocks.length > 0); assert.equal(mainCalls(), 0); + // #7545 one-shot gate: the client-disconnect abort spent the + // session's one preflight fold — the livelock-shape linkage + // (abort → flag) that the gate's e2e cases simulate. + assert.equal(f.session.stats.preflightRuns, 1, "the aborted attempt spent the one-shot preflight fold"); } finally { client.destroy(); const closed = once(downstream, "close"); diff --git a/tests/preflight-max-output-tokens.test.ts b/tests/preflight-max-output-tokens.test.ts index e377b93fa..54a94730c 100644 --- a/tests/preflight-max-output-tokens.test.ts +++ b/tests/preflight-max-output-tokens.test.ts @@ -220,17 +220,18 @@ test("e2e #663 (order A, stream-first): learn both rejections, summary recovers, assert.ok(learned && typeof learned === "object", "max_output_tokens rejection learned on the session"); assert.equal(learned?.[learnKey(upstreamUrl, "gpt-6-astra")], true, "learning scoped to upstream URL + model"); - // Second request (grown over-window again): every summary call is - // first-shot compatible — stream, no max_output_tokens. + // Second request (grown over-window again): under the one-shot fold + // gate the session is compression-managed after request 1's folds, + // so preflight no longer re-folds it — the payload is forwarded + // as-is with ZERO summary calls (overflow recovery stays with the + // #1195 in-request refold). The first-shot compatibility property is + // already proven by request 1's post-rejection summaries above. const callsBefore = calls.length; const r2 = await driveResponsesPreflight(proxyPort, upstreamPort, "s663-resp-a", "gpt-6-astra", longResponsesInput(24)); assert.equal(r2.status, 200, `second request must succeed, got ${r2.status}`); const newSummaries = calls.slice(callsBefore).filter((c) => c.summary); - assert.ok(newSummaries.length >= 1, "second request triggered preflight summaries"); - assert.ok( - newSummaries.every((c) => c.stream && c.maxOutputTokens === undefined), - `second-request summaries must be first-shot compatible, got ${JSON.stringify(newSummaries)}`, - ); + assert.equal(newSummaries.length, 0, "one-shot gate: the managed session's second request is forwarded as-is, no re-fold"); + assert.ok(calls.slice(callsBefore).some((c) => !c.summary), "the second request was forwarded upstream"); } finally { proxy.close(); proxy.closeIdleConnections?.(); @@ -378,17 +379,18 @@ test("e2e #663 (model scoping): rejection learned for model A keeps model B's 32 `every model A retry must drop the cap, got ${JSON.stringify(astraSummaries)}`, ); - // Same session, different model: preflight must fire again (grown - // over-window) and model B's summary keeps the cap. + // Same session, different model: the session is compression-managed + // after model A's folds, so the one-shot gate forwards the second + // request as-is — no summary call for model B either (model-B cap + // retention on summary calls is covered by the metadata scoping + // below: model B's key was never learned, so a future first-shot + // session for B would carry the cap). const callsBefore = calls.length; const r2 = await driveResponsesPreflight(proxyPort, upstreamPort, "s663-resp-d", "gpt-6-standard", longResponsesInput(24)); assert.equal(r2.status, 200, `second request (model B) must succeed, got ${r2.status}`); const standardSummaries = calls.slice(callsBefore).filter((c) => c.summary); - assert.ok(standardSummaries.length >= 1, "second request triggered preflight summaries"); - assert.ok( - standardSummaries.every((c) => c.model === "gpt-6-standard" && typeof c.maxOutputTokens === "number" && c.maxOutputTokens <= 32768), - `model B summaries must keep the output cap (<= 32768; #987 may clamp it), got ${JSON.stringify(standardSummaries)}`, - ); + assert.equal(standardSummaries.length, 0, "one-shot gate: the managed session's second request is forwarded as-is, no re-fold for model B either"); + assert.ok(calls.slice(callsBefore).some((c) => !c.summary), "the second request was forwarded upstream"); const sess = listSessions().find((s) => s.id.includes("s663-resp-d")); const learned = sess?.metadata?.preflightNoMaxOutputTokens as Record | undefined; diff --git a/tests/preflight-one-shot-gate.test.ts b/tests/preflight-one-shot-gate.test.ts new file mode 100644 index 000000000..72c5b1d8d --- /dev/null +++ b/tests/preflight-one-shot-gate.test.ts @@ -0,0 +1,264 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import { type ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { getSession, resetSessionCompression } from "../src/session.ts"; +import { normalizeUpstreamOrigin } from "../src/util.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; + +// One-shot preflight fold gate (2026-11-22 log-32 incident): proxy-driven +// preflight folding gets exactly ONE attempt per session lifecycle. After +// bili has compressed the session (committed fold) or a fold attempt started, +// the trigger forwards as-is — overflow recovery stays with #1195 in-request +// refold and the egress fuse, steady growth is the model's compress tool. +// Gate Test Discipline: every "blocked" case below is paired with the +// POSITIVE case A, which proves the identical payload shape DOES trigger and +// fold on a fresh session — so a blocked result can never be a vacuous +// non-trigger. + +function okSse(inputTokens: number): string { + return ( + `event: message_start\ndata: ${JSON.stringify({ type: "message_start", message: { id: "m1", role: "assistant", usage: { input_tokens: inputTokens } } })}\n\n` + + `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ok" } })}\n\n` + + `event: message_delta\ndata: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 3 } })}\n\n` + + `event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n` + ); +} + +// ~12k tokens of message text against a 10k window — the SAME shape the #330 +// test folds (two large recent messages, soft zone relaxed under overflow). +function overWindowPayload(): Array<{ role: string; content: string }> { + return [ + { role: "user", content: "start the task" }, + { role: "assistant", content: "A".repeat(24_000) }, + { role: "user", content: "B".repeat(24_000) }, + ]; +} + +type Call = { stream: boolean; body: string }; + +function makeUpstreamOk(calls?: Call[]): http.Server { + return http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + let parsed: { stream?: boolean } = {}; + try { parsed = JSON.parse(raw); } catch { /* keep {} */ } + calls?.push({ stream: !!parsed.stream, body: raw }); + if (parsed.stream) { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(okSse(1_000)); + } else { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ content: [{ type: "text", text: "SUMMARY: the large recent messages were deterministic filler; their raw content is no longer needed." }] })); + } + }); + }); +} + +function seedEvidence(sessionId: string, upstreamPort: number): void { + const s = getSession(sessionId); + s.stats.lastInputTokens = 1_000; + s.stats.lastInputTokensSource = "usage"; + s.stats.lastInputTokensOrigin = normalizeUpstreamOrigin(`http://127.0.0.1:${upstreamPort}`); +} + +function startProxy(upstreamPort: number, models: Record): Promise { + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + return startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models } }, + modelContextLimit: 400_000, + kernelConfig: defaultConfig(400_000), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + passthroughSource: null, + autoUpdate: false, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); +} + +async function post( + proxyPort: number, + upstreamPort: number, + sessionId: string, + messages: Array<{ role: string; content: string }>, +): Promise<{ status: number; body: string }> { + const r = await fetch(`http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1/messages`, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": sessionId }, + body: JSON.stringify({ model: "claude-small", max_tokens: 1_024, stream: true, messages }), + }); + const body = await r.text(); + return { status: r.status, body }; +} + +async function startPair(): Promise<{ proxy: http.Server; upstream: http.Server; proxyPort: number; upstreamPort: number; calls: Call[]; close: () => Promise }> { + const calls: Call[] = []; + const upstream = makeUpstreamOk(calls); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + const proxy = await startProxy(upstreamPort, { "claude-small": { context: 10_000 } }); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + return { + proxy, upstream, proxyPort, upstreamPort, calls, + close: async () => { + proxy.close(); proxy.closeIdleConnections?.(); + upstream.close(); upstream.closeIdleConnections?.(); + await Promise.allSettled([once(proxy, "close"), once(upstream, "close")]); + }, + }; +} + +// A (POSITIVE): a fresh session's first over-window payload triggers preflight, +// spends the summary call, folds, forwards the folded payload — and marks the +// session as spent (preflightRuns=1, committed fold). +test("one-shot gate: fresh session's first over-window payload still folds", async () => { + const env = await startPair(); + try { + const r = await post(env.proxyPort, env.upstreamPort, "oneshot-fresh", overWindowPayload()); + assert.equal(r.status, 200, r.body.slice(0, 300)); + assert.ok(env.calls.filter((c) => !c.stream).length >= 1, "preflight made the summarization call (the trigger fired)"); + assert.equal(env.calls.filter((c) => c.stream).length, 1, "the folded payload was forwarded upstream"); + const forwarded = env.calls.find((c) => c.stream)?.body ?? ""; + assert.ok(!forwarded.includes("A".repeat(100)), "the folded big message did NOT ride the forwarded payload"); + const s = getSession("oneshot-fresh"); + assert.ok(s.state.blocks.length >= 1, "the fold committed a block"); + assert.ok((s.state.stats?.compressionCount ?? 0) > 0, "the commit spends the session's one-shot fold (compression-managed)"); + } finally { + await env.close(); + } +}); + +// B (NEGATIVE): a session bili has already compressed (committed fold — the +// "managed session" the directive targets) must NOT get another proxy-side +// fold: the identical over-window payload is forwarded as-is, zero summary +// calls. The FIRST post in this test doubles as the positive proof that the +// exact shape triggers and folds on a fresh session (same as case A). +test("one-shot gate: compression-managed session (committed fold) → forwarded as-is, no fold", async () => { + const env = await startPair(); + try { + // Shot one: the fresh session's first over-window payload folds. + const r1 = await post(env.proxyPort, env.upstreamPort, "oneshot-managed", overWindowPayload()); + assert.equal(r1.status, 200, r1.body.slice(0, 300)); + assert.ok(env.calls.filter((c) => !c.stream).length >= 1, "shot one: preflight made the summarization call"); + const s = getSession("oneshot-managed"); + assert.ok((s.state.stats?.compressionCount ?? 0) > 0, "shot one committed (test precondition: the session is now compression-managed)"); + + // Shot two: the SAME over-window payload again — the gate must block + // the fold: forwarded as-is, no second summarization call. + const summaryCallsAfterShot1 = env.calls.filter((c) => !c.stream).length; + const r2 = await post(env.proxyPort, env.upstreamPort, "oneshot-managed", overWindowPayload()); + assert.equal(r2.status, 200, "the over-window payload is forwarded as-is, not withheld (r.status=" + r2.status + " " + r2.body.slice(0, 300) + ")"); + assert.equal(env.calls.filter((c) => !c.stream).length, summaryCallsAfterShot1, "NO new summarization call: the one-shot gate blocked the second fold"); + assert.equal(env.calls.filter((c) => c.stream).length, 2, "the second request was forwarded upstream (as-is, not withheld or re-folded)"); + const before = s.state.blocks.length; + assert.equal(getSession("oneshot-managed").state.blocks.length, before, "no new block was committed on the second request"); + } finally { + await env.close(); + } +}); + +// B2 (NEGATIVE, the discriminating one for the managed branch): case B's second +// request never reaches the gate — after shot 1's fold the reconciled payload +// FITS the window, so the triggerFires early return fires first. This variant +// regrows the session over-window with NEW large content, so the trigger +// genuinely fires and only the gate blocks the fold: without the gate this +// case re-folds (a new summarization call); with the gate it forwards as-is. +test("one-shot gate: managed session regrows over-window on new content → trigger fires, still no fold", async () => { + const env = await startPair(); + try { + // Shot one commits a fold (the session is now compression-managed). + const r1 = await post(env.proxyPort, env.upstreamPort, "oneshot-managed-grow", overWindowPayload()); + assert.equal(r1.status, 200, r1.body.slice(0, 300)); + const s = getSession("oneshot-managed-grow"); + assert.ok((s.state.stats?.compressionCount ?? 0) > 0, "shot one committed (precondition: the session is compression-managed)"); + + // Shot two: the SAME conversation plus NEW large content — the outbound + // is over-window again, so the trigger fires (not the fits early + // return). The gate must block the fold. + const summaryCallsBefore = env.calls.filter((c) => !c.stream).length; + const r2 = await post(env.proxyPort, env.upstreamPort, "oneshot-managed-grow", [ + { role: "user", content: "start the task" }, + { role: "user", content: "A".repeat(24000) }, + { role: "user", content: "A".repeat(24000) }, + { role: "user", content: "C".repeat(60000) }, + ]); + assert.equal(r2.status, 200, "the regrown over-window payload is forwarded as-is, not withheld (r.status=" + r2.status + " " + r2.body.slice(0, 300) + ")"); + assert.equal(env.calls.filter((c) => !c.stream).length, summaryCallsBefore, "NO new summarization call: the gate blocked the regrown trigger (this case re-folds without the gate)"); + assert.ok(env.calls.some((c) => c.stream && c.body.includes("C".repeat(100))), "the UNFOLDED new content rode the forward"); + assert.equal(getSession("oneshot-managed-grow").state.blocks.length, s.state.blocks.length, "no new block was committed on the second request"); + } finally { + await env.close(); + } +}); + +// C (NEGATIVE): the log-32 livelock shape — an ABORTED first attempt (flag set, +// nothing committed) must not re-start the multi-minute summary on the retry: +// the identical over-window payload is forwarded as-is, zero summary calls. +test("one-shot gate: spent flag (aborted first attempt, no commit) → retry forwarded as-is", async () => { + const env = await startPair(); + try { + const r0 = await post(env.proxyPort, env.upstreamPort, "oneshot-aborted", [{ role: "user", content: "hi" }]); + assert.equal(r0.status, 200, r0.body.slice(0, 300)); + seedEvidence("oneshot-aborted", env.upstreamPort); + const s = getSession("oneshot-aborted"); + // Simulate the 300s-aborted attempt: the flag was spent when the fold + // path began, but the summary never returned so no block committed. + s.stats.preflightRuns = 1; + assert.equal(s.state.blocks.length, 0, "nothing committed (test precondition)"); + + const summaryCallsBefore = env.calls.filter((c) => !c.stream).length; + const r = await post(env.proxyPort, env.upstreamPort, "oneshot-aborted", overWindowPayload()); + assert.equal(r.status, 200, "the retry is forwarded as-is, not re-folded (r.status=" + r.status + " " + r.body.slice(0, 300) + ")"); + assert.equal(env.calls.filter((c) => !c.stream).length, summaryCallsBefore, "the livelock is killed: no second summarization call"); + assert.ok(env.calls.find((c) => c.stream && c.body.includes("A".repeat(100))) !== undefined, "the UNFOLDED payload rode the forward"); + } finally { + await env.close(); + } +}); + +// D (POSITIVE): compression reset re-arms the gate — a rebuilt conversation is +// a fresh lifecycle and gets its own first attempt. +test("one-shot gate: compression reset re-arms the one-shot fold", async () => { + const env = await startPair(); + try { + const r0 = await post(env.proxyPort, env.upstreamPort, "oneshot-reset", [{ role: "user", content: "hi" }]); + assert.equal(r0.status, 200, r0.body.slice(0, 300)); + seedEvidence("oneshot-reset", env.upstreamPort); + const s = getSession("oneshot-reset"); + s.stats.preflightRuns = 1; + resetSessionCompression(s); + assert.equal(s.stats.preflightRuns, undefined, "the reset cleared the one-shot flag"); + + const r = await post(env.proxyPort, env.upstreamPort, "oneshot-reset", overWindowPayload()); + assert.equal(r.status, 200, r.body.slice(0, 300)); + assert.ok(env.calls.filter((c) => !c.stream).length >= 1, "after reset the fresh lifecycle folds again"); + assert.ok(getSession("oneshot-reset").state.blocks.length >= 1, "the re-armed attempt committed a block"); + } finally { + await env.close(); + } +}); diff --git a/tests/qoder-side-task.test.ts b/tests/qoder-side-task.test.ts new file mode 100644 index 000000000..ffb645499 --- /dev/null +++ b/tests/qoder-side-task.test.ts @@ -0,0 +1,64 @@ +// #7439 worklist — Qoder side-task sidecar (src/session-id.ts qoderSideTaskConversation). +// Qoder's side tasks (agent summary / webfetch summary / hook prompt) reuse the +// parent x-session-id and carry their task type only in the Responses body +// metadata.business_type. The server gives each its own `|aux:qoder-` lane +// (the zcode-memory pattern) so a side task does not merge into the parent +// conversation. Plain Task subagents carry no wire marker and are unfixable here. +// +// Hermetic roots mirror tests/trust-stamped-id.test.ts: a directly-invoked single +// file does NOT get tests/preload-test-env.mjs, and session-id.ts pulls in the +// prefix-affinity / store modules which touch XDG paths at load. +import assert from "node:assert"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const XDG = fs.mkdtempSync(path.join(os.tmpdir(), "bili-qoder-")); +process.env.XDG_DATA_HOME = path.join(XDG, "data"); +process.env.XDG_STATE_HOME = path.join(XDG, "state"); +process.env.XDG_CACHE_HOME = path.join(XDG, "cache"); +process.env.XDG_CONFIG_HOME = path.join(XDG, "config"); +process.env.BILI_PERSIST = "0"; +process.env.NODE_ENV = "test"; + +const { qoderSideTaskConversation } = await import("../src/session-id.ts"); + +test("qoder side task keys its own |aux: lane off body metadata.business_type", () => { + assert.equal(qoderSideTaskConversation("q", { metadata: { business_type: "agent_summary" } }), "q|aux:qoder-agent_summary"); + assert.equal(qoderSideTaskConversation("q", { metadata: { business_type: "webfetch_summary" } }), "q|aux:qoder-webfetch_summary"); + assert.equal(qoderSideTaskConversation("q", { metadata: { business_type: "hook_prompt" } }), "q|aux:qoder-hook_prompt"); +}); + +test("qoder side task of the SAME business_type disambiguates by body metadata.task_id", () => { + // Two same-type side tasks under one parent are distinct conversations; with + // GA-on (which retires the in-lane content-guessed split) the per-task id + // keeps them apart (zcode x-query-id pattern). Without it they'd merge + + // cross-bleed compression state. + assert.equal( + qoderSideTaskConversation("q", { metadata: { business_type: "agent_summary", task_id: "t-1" } }), + "q|aux:qoder-agent_summary:t-1", + ); + assert.equal( + qoderSideTaskConversation("q", { metadata: { business_type: "agent_summary", task_id: "t-2" } }), + "q|aux:qoder-agent_summary:t-2", + ); + assert.notEqual( + qoderSideTaskConversation("q", { metadata: { business_type: "agent_summary", task_id: "t-1" } }), + qoderSideTaskConversation("q", { metadata: { business_type: "agent_summary", task_id: "t-2" } }), + ); + // Malformed task_id (path-traversal charset) is ignored → type-only lane. + assert.equal( + qoderSideTaskConversation("q", { metadata: { business_type: "agent_summary", task_id: "../evil" } }), + "q|aux:qoder-agent_summary", + ); +}); + +test("non-qoder type / missing marker / non-object body → no sidecar", () => { + assert.equal(qoderSideTaskConversation("q", { metadata: { business_type: "main" } }), undefined); + assert.equal(qoderSideTaskConversation("q", { metadata: {} }), undefined); + assert.equal(qoderSideTaskConversation("q", { metadata: { business_type: 123 } }), undefined); + assert.equal(qoderSideTaskConversation("q", { input: "hi" }), undefined); + assert.equal(qoderSideTaskConversation("q", null), undefined); + assert.equal(qoderSideTaskConversation("q", undefined), undefined); +}); diff --git a/tests/responses-instructions-drift.test.ts b/tests/responses-instructions-drift.test.ts index dd8328424..7f148a8b7 100644 --- a/tests/responses-instructions-drift.test.ts +++ b/tests/responses-instructions-drift.test.ts @@ -26,6 +26,16 @@ process.env.XDG_CACHE_HOME = path.join(xdgRoot, "cache"); process.env.XDG_DATA_HOME = path.join(xdgRoot, "data"); process.env.XDG_CONFIG_HOME = path.join(xdgRoot, "config"); +// #7525: the trust-stamped-id GA (rollout percent 100) retires the content-guessed +// |sub: instructions-fingerprint split this suite exists to cover (#150: a +// codex root thread reusing a task id across personas still splits by +// instructions fingerprint; the #2250 migrate-carry rides the same |sub: +// lineage). Pin this file to the legacy (off) path so that split+migrate +// coverage stays tested on the escape-hatch path — the same pin the other 16 +// fork-lineage suites carry for the GA. The GA-on path (trust the stamped id, +// no content-guessed split) is covered by tests/trust-stamped-id.test.ts. +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + const { startServer } = await import("../src/server.ts"); const { SessionStore, _setStoreForTest } = await import("../src/persist.ts"); const { _setForTest: setRegistryForTest } = await import("../src/registry.ts"); diff --git a/tests/session-continuity-proof.test.ts b/tests/session-continuity-proof.test.ts index 31c74b7cf..ac57b43a2 100644 --- a/tests/session-continuity-proof.test.ts +++ b/tests/session-continuity-proof.test.ts @@ -51,6 +51,12 @@ import { createHash } from "node:crypto"; const testRoot = mkdtempSync(path.join(tmpdir(), "bc-continuity-proof-")); for (const key of ["XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) process.env[key] = testRoot; process.env.NODE_ENV = "test"; +// #7439 trustStampedId is GA-on by default, which retires the content- +// forecasting |sub: forks this proof's "scenario A control" asserts +// (uncorroborated persona drift must fork). Pin the flag OFF so the proof +// keeps exercising the legacy fork path (still reachable via the escape +// hatch), exactly like tests/issue2944-neutral-skeleton.test.ts does. +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; test.after(() => rmSync(testRoot, { recursive: true, force: true })); const { defaultConfig } = await import("acp-kernel"); diff --git a/tests/side-lane-invariants.test.ts b/tests/side-lane-invariants.test.ts index d851bec4e..4ab4a1238 100644 --- a/tests/side-lane-invariants.test.ts +++ b/tests/side-lane-invariants.test.ts @@ -1,4 +1,9 @@ import assert from "node:assert/strict"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy +// |sub: fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; + import http from "node:http"; import { once } from "node:events"; import test from "node:test"; diff --git a/tests/subagent-namespace.test.ts b/tests/subagent-namespace.test.ts index 7a6f24f61..6a6d6be0f 100644 --- a/tests/subagent-namespace.test.ts +++ b/tests/subagent-namespace.test.ts @@ -1,5 +1,9 @@ import { test } from "node:test"; import assert from "node:assert/strict"; +// trustStampedId is GA-on by default (#7439). This suite pins the legacy |sub: +// fork behavior — force the feature OFF so it keeps asserting the +// pre-retirement path (issue2944-neutral-skeleton idiom). +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "0"; import http from "node:http"; import { once } from "node:events"; import { defaultConfig } from "acp-kernel"; diff --git a/tests/trust-stamped-id.test.ts b/tests/trust-stamped-id.test.ts new file mode 100644 index 000000000..cf8be62b3 --- /dev/null +++ b/tests/trust-stamped-id.test.ts @@ -0,0 +1,90 @@ +// #7439/#6884 trust-stamped-id (server-side, gated). +// +// With the flag ON, the persona-order resolver's |sub: CONTENT-forecasting +// (derived-aux / derived-task / persona-lane-by-content) is retired for +// id-bearing traffic: the stamped session id IS the complete identity, so the +// retired forks ride the verbatim raw id instead of forking. The ONE survivor +// is the #5095 client-DECLARED subagent lane-token tail, which still forks — +// it is a declared distinct lane, not a content guess. +// +// The flag is forced ON for this whole file. node --test gives each file its +// own process, so this env never leaks into the OFF characterization corpus in +// tests/issue2944-neutral-skeleton.test.ts (which pins the byte-identical +// legacy forks). Hermetic roots are set here because a directly-invoked single +// file does NOT get tests/preload-test-env.mjs. +import assert from "node:assert"; +import os from "node:os"; +import path from "node:path"; +import fs from "node:fs"; +import test from "node:test"; + +const XDG = fs.mkdtempSync(path.join(os.tmpdir(), "bili-tsi-")); +process.env.XDG_DATA_HOME = path.join(XDG, "data"); +process.env.XDG_STATE_HOME = path.join(XDG, "state"); +process.env.XDG_CACHE_HOME = path.join(XDG, "cache"); +process.env.XDG_CONFIG_HOME = path.join(XDG, "config"); +process.env.BILI_PERSIST = "0"; +process.env.NODE_ENV = "test"; +process.env.BILI_ROLLOUT_TRUST_STAMPED_ID = "1"; + +const { resolveSessionOrder, resetSessionOrderForTest } = await import("../src/session-resolve.ts"); + +type Msg = { role: string; content: string }; +/** Alternating user/assistant turns, ~120 chars each (same shape as the + * legacy-corpus helper). */ +function msgs(n: number, tag = "m"): Msg[] { + const out: Msg[] = []; + for (let i = 0; i < n; i++) { + const role = i % 2 === 0 ? "user" : "assistant"; + out.push({ role, content: `${tag} #${i} — body with enough prose to be a realistic cell ${"x".repeat(80)}` }); + } + return out; +} + +test("trust-stamped-id ON: first-sight shallow side request rides the verbatim id (no |sub:aux fork)", () => { + resetSessionOrderForTest(); + // A lone user turn (no assistant, no persona tag): the legacy ladder forks + // this onto `aux-id|sub:aux`; trusted, it rides the stamped id verbatim. + const r = resolveSessionOrder("aux-id", [ + { role: "user", content: "start a side thing, please be brief " + "z".repeat(80) }, + ]); + assert.equal(r.key, "aux-id"); + assert.equal(r.action, "claim"); +}); + +test("trust-stamped-id ON: growth under a claimed id continues verbatim (no fork)", () => { + resetSessionOrderForTest(); + resolveSessionOrder("grow-id", msgs(6, "seed")); + const r = resolveSessionOrder("grow-id", msgs(10, "seed")); + assert.equal(r.key, "grow-id"); + assert.equal(r.action, "continue"); +}); + +test("trust-stamped-id ON: a divergent/shorter stranger order rides the verbatim id (no |sub:task fork)", () => { + resetSessionOrderForTest(); + // Seed a main-shaped 10-turn skeleton, then a shorter, different-content + // history under the same id that tail-aligns by alternation but whose + // fragments do NOT match: the legacy ladder forks it onto + // `task-id|sub:task:` (id-reuse guard); trusted, it re-anchors to + // the stamped id. + resolveSessionOrder("task-id", msgs(10, "seed")); + const r = resolveSessionOrder("task-id", msgs(4, "other")); + assert.equal(r.key, "task-id"); +}); + +test("trust-stamped-id ON: the #5095 lane-token tail STILL forks (the declared-lane survivor)", () => { + resetSessionOrderForTest(); + // The token value the resolver sees is the BARE 12-hex (handle.ts extracts + // it via claudeSubagentLaneTokenOf → claudeLaneTokenIn, which strips the + // `bili-lane-token:` marker). isClaudeLaneToken matches exactly /^[0-9a-f]{12}$/. + const token = "001122334455"; + // The token is a client-declared subagent dispatch (handle.ts extracts it + // from the dispatch's first user message and passes it as the 5th arg). + // A declared distinct lane must survive the flag and fork — it is not a + // content guess. No persona tag is passed, so the key takes the two-segment + // form `|sub:t:`. + const r = resolveSessionOrder("sub-id", msgs(6, "seed"), undefined, undefined, token); + assert.equal(r.action, "derived-persona"); + assert.ok(r.key.startsWith("sub-id|sub:"), `expected a |sub: lane-token tail, got ${r.key}`); + assert.ok(r.key.endsWith(`t:${token}`), `expected the token tail, got ${r.key}`); +}); diff --git a/tests/zed-wire.test.ts b/tests/zed-wire.test.ts new file mode 100644 index 000000000..491bcf98d --- /dev/null +++ b/tests/zed-wire.test.ts @@ -0,0 +1,300 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import type { AddressInfo } from "node:net"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import { defaultConfig } from "acp-kernel"; +import { startServer, type ProxyOptions } from "../src/server.ts"; +import { _setStoreForTest, SessionStore } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { listSessions } from "../src/session.ts"; +import { rewrapZedEnvelope, unwrapZedEnvelope } from "../src/zed-wire.ts"; +import { preferZedThreadIdIdentity, type ConversationIdentity } from "../src/session-id.ts"; + +// zed cloud wire: cloud.zed.dev POSTs the provider request nested in a +// `{thread_id, prompt_id, provider, model, provider_request}` envelope to +// /completions. bili unwraps it into the standard provider wire (session keyed +// by the envelope thread_id), runs the pipeline, rewraps at egress, and passes +// the NDJSON response through byte-for-byte. + +const MODEL = "claude-sonnet-4-5"; + +const anthropicInner = (overrides: Record = {}) => ({ + model: MODEL, + max_tokens: 1024, + stream: true, + messages: [{ role: "user", content: [{ type: "text", text: "hello zed" }] }], + ...overrides, +}); + +const zedEnvelope = (inner: Record, overrides: Record = {}) => ({ + thread_id: "zed-thread-001", + prompt_id: "zed-prompt-001", + provider: "anthropic", + model: inner.model, + provider_request: inner, + ...overrides, +}); + +// ---- codec unit tests ------------------------------------------------------ + +test("zed codec: anthropic envelope round-trips verbatim", () => { + const inner = anthropicInner(); + const envelope = zedEnvelope(inner, { priority: "interactive" }); + const unwrapped = unwrapZedEnvelope(envelope as Record); + assert.ok(unwrapped, "valid envelope must unwrap"); + assert.equal(unwrapped!.provider, "anthropic"); + assert.equal(unwrapped!.threadId, "zed-thread-001"); + assert.equal(unwrapped!.promptId, "zed-prompt-001"); + assert.equal(unwrapped!.meta.model, MODEL); + assert.equal(unwrapped!.meta.rest.priority, "interactive"); + assert.deepEqual(rewrapZedEnvelope(inner, unwrapped!.meta), envelope); +}); + +test("zed codec: rewrap tracks a pipeline-rewritten inner model", () => { + const envelope = zedEnvelope(anthropicInner()); + const unwrapped = unwrapZedEnvelope(envelope as Record); + const inner2 = { ...anthropicInner(), model: "claude-sonnet-4-6" }; + const out = rewrapZedEnvelope(inner2, unwrapped!.meta) as Record; + assert.equal(out.model, "claude-sonnet-4-6"); + assert.equal((out.provider_request as Record).model, "claude-sonnet-4-6"); + assert.equal(out.thread_id, "zed-thread-001"); +}); + +test("zed codec: garbage envelope fields pass through verbatim", () => { + const envelope = zedEnvelope(anthropicInner(), { thread_id: 42 as unknown }); + const unwrapped = unwrapZedEnvelope(envelope as Record); + assert.ok(unwrapped, "non-string thread_id is tolerated at unwrap (no identity claim)"); + assert.equal(unwrapped!.threadId, undefined); + assert.deepEqual(rewrapZedEnvelope(anthropicInner(), unwrapped!.meta), envelope); +}); + +test("zed codec: rejects every unconvertible shape (strict fidelity)", () => { + const base = zedEnvelope(anthropicInner()); + assert.equal(unwrapZedEnvelope({ ...base, provider: "azure" } as Record), undefined); + assert.equal(unwrapZedEnvelope({ ...base, provider: 7 } as Record), undefined); + assert.equal(unwrapZedEnvelope({ ...base, provider_request: "nope" } as Record), undefined); + assert.equal(unwrapZedEnvelope({ ...base, provider_request: [1] } as Record), undefined); + assert.equal(unwrapZedEnvelope({ ...base, provider_request: undefined } as Record), undefined); + // arm-shape gates + const noMsgs = zedEnvelope({ model: MODEL, stream: true }, {}); + assert.equal(unwrapZedEnvelope(noMsgs as Record), undefined); + assert.equal(unwrapZedEnvelope(zedEnvelope({ model: MODEL, messages: [] }) as Record), undefined); + const xai = zedEnvelope({ model: "grok-4", messages: [{ role: "user", content: "hi" }] }, { provider: "x_ai" }); + assert.equal(unwrapZedEnvelope(xai as Record)?.provider, "x_ai"); + const oai = zedEnvelope({ model: "gpt-5", input: [{ role: "user", content: "hi" }] }, { provider: "open_ai" }); + assert.equal(unwrapZedEnvelope(oai as Record)?.provider, "open_ai"); + const oaiNoInput = zedEnvelope({ model: "gpt-5" }, { provider: "open_ai" }); + assert.equal(unwrapZedEnvelope(oaiNoInput as Record), undefined); + const goog = zedEnvelope({ systemInstruction: "be nice", contents: [{ role: "user", parts: [{ text: "hi" }] }] }, { provider: "google" }); + assert.equal(unwrapZedEnvelope(goog as Record)?.provider, "google"); + const googNoContents = zedEnvelope({ systemInstruction: "be nice" }, { provider: "google" }); + assert.equal(unwrapZedEnvelope(googNoContents as Record), undefined); +}); + +// ---- identity unit tests --------------------------------------------------- + +const fingerprint = (value: string): ConversationIdentity => ({ value, source: "content-fingerprint", clientProvided: false }); +const headerId = (value: string): ConversationIdentity => ({ value, source: "header", clientProvided: true }); + +test("zed identity: thread_id promotes over the content fingerprint only", () => { + const promoted = preferZedThreadIdIdentity(fingerprint("fp-abc"), "zed-thread-001"); + assert.deepEqual(promoted, { value: "zed-thread-001", source: "zed-thread-id", clientProvided: true }); + // a roster header stays stronger — the promotion guard (preferPromptCacheKeyIdentity pattern) + assert.deepEqual(preferZedThreadIdIdentity(headerId("hdr-1"), "zed-thread-001"), headerId("hdr-1")); + const bodySession: ConversationIdentity = { value: "bs-1", source: "body-session", clientProvided: true }; + assert.deepEqual(preferZedThreadIdIdentity(bodySession, "zed-thread-001"), bodySession); + const pck: ConversationIdentity = { value: "pck-1", source: "prompt-cache-key", clientProvided: true }; + assert.deepEqual(preferZedThreadIdIdentity(pck, "zed-thread-001"), pck); + // no usable thread_id -> the fingerprint (or 400-anonymous policy) stands + assert.deepEqual(preferZedThreadIdIdentity(fingerprint("fp-abc"), null), fingerprint("fp-abc")); + assert.deepEqual(preferZedThreadIdIdentity(fingerprint("fp-abc"), " "), fingerprint("fp-abc")); + assert.deepEqual(preferZedThreadIdIdentity(fingerprint("fp-abc"), 42), fingerprint("fp-abc")); + assert.equal(preferZedThreadIdIdentity(undefined, "zed-thread-001"), undefined); +}); + +// ---- handle() lane tests --------------------------------------------------- + +interface Rig { + proxyPort: number; + upstreamPort: number; + forwards: Array<{ url: string; raw: string }>; + proxy: http.Server; + upstream: http.Server; +} + +const NDJSON_RESPONSE = [ + '{"status":"queued","position":0}', + '{"status":"started"}', + '{"event":{"type":"message_start"}}', + '{"status":"stream_ended"}', +].join("\n") + "\n"; + +async function startRig(): Promise { + const forwards: Array<{ url: string; raw: string }> = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + forwards.push({ url: req.url ?? "", raw }); + let zedInner = false; + try { + const e = JSON.parse(raw) as any; + zedInner = typeof e?.provider === "string" && typeof e?.provider_request === "object" + && Array.isArray(e?.provider_request?.messages); + } catch { /* not json */ } + if (zedInner) { + res.writeHead(200, { "content-type": "application/x-ndjson" }); + res.end(NDJSON_RESPONSE); + } else { + // echo non-conversation bytes so verbatim-relay assertions compare exactly + res.writeHead(200, { "content-type": "application/json" }); + res.end(raw); + } + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as AddressInfo).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: {} }, + modelContextLimit: 200_000, + kernelConfig: defaultConfig(200_000), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + return { proxyPort: (proxy.address() as AddressInfo).port, upstreamPort, forwards, proxy, upstream }; +} + +async function closeRig(rig: Rig): Promise { + rig.proxy.close(); + await once(rig.proxy, "close"); + rig.upstream.close(); + await once(rig.upstream, "close"); +} + +async function postZed(rig: Rig, body: unknown, headers: Record = {}): Promise<{ status: number; text: string }> { + const r = await fetch(`http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/completions`, { + method: "POST", + headers: { "content-type": "application/json", ...headers }, + body: JSON.stringify(body), + }); + return { status: r.status, text: await r.text() }; +} + +test("zed lane: envelope unwrapped upstream, passthrough back down, session keyed by thread_id", async () => { + const rig = await startRig(); + try { + const out = await postZed(rig, zedEnvelope(anthropicInner())); + assert.equal(out.status, 200); + + const fwd = rig.forwards.at(-1)!; + assert.ok(fwd.url.startsWith("/completions")); + const up = JSON.parse(fwd.raw); + // the egress rewraps: the real upstream IS zed's cloud endpoint, so it + // must see the ENVELOPE again — with the ACP-tagged inner inside + assert.equal(up.thread_id, "zed-thread-001"); + assert.equal(up.prompt_id, "zed-prompt-001"); + assert.equal(up.provider, "anthropic"); + assert.equal(up.model, MODEL); + const inner = up.provider_request; + assert.ok(inner && typeof inner === "object", "rewrapped envelope must carry the provider wire in provider_request"); + assert.ok(Array.isArray(inner.messages) && inner.messages.length === 1); + assert.ok(fwd.raw.includes(" s.id === "zed-thread-001"); + assert.ok(sess, `session must be keyed by the envelope thread_id; sessions: ${listSessions().map((s) => s.id).join(",")}`); + } finally { + await closeRig(rig); + } +}); + +test("zed lane: distinct thread_ids are distinct sessions (subagent isolation)", async () => { + const rig = await startRig(); + try { + const inner = anthropicInner(); + const a = await postZed(rig, zedEnvelope(inner, { thread_id: "zed-thread-A" })); + assert.equal(a.status, 200); + const b = await postZed(rig, zedEnvelope(anthropicInner({ messages: [{ role: "user", content: [{ type: "text", text: "different subagent work" }] }] }), { thread_id: "zed-thread-B" })); + assert.equal(b.status, 200); + const ids = listSessions().map((s) => s.id).sort(); + assert.ok(ids.includes("zed-thread-A"), `sessions: ${ids.join(",")}`); + assert.ok(ids.includes("zed-thread-B"), `sessions: ${ids.join(",")}`); + assert.equal(listSessions().find((s) => s.id === "zed-thread-A")?.stats.requests, 1, "thread A must have exactly its own single turn"); + assert.equal(listSessions().find((s) => s.id === "zed-thread-B")?.stats.requests, 1, "thread B must have exactly its own single turn"); + } finally { + await closeRig(rig); + } +}); + +test("zed lane: a roster conversation header beats the envelope thread_id", async () => { + const rig = await startRig(); + try { + const out = await postZed(rig, zedEnvelope(anthropicInner(), { thread_id: "zed-thread-HDR" }), { "x-session-id": "hdr-wins" }); + assert.equal(out.status, 200); + const ids = listSessions().map((s) => s.id); + assert.ok(ids.includes("hdr-wins"), `header identity must win: ${ids.join(",")}`); + assert.ok(!ids.includes("zed-thread-HDR"), `thread_id must NOT claim a session when a header stated one: ${ids.join(",")}`); + } finally { + await closeRig(rig); + } +}); + +test("zed lane: ambiguous envelope body relays verbatim (never a partial conversion)", async () => { + const rig = await startRig(); + try { + const bad = zedEnvelope({ model: MODEL }, { thread_id: "zed-thread-AMBIG" }); // no messages -> codec rejects + const original = JSON.stringify(bad); + const out = await postZed(rig, bad); + assert.equal(out.status, 200); + assert.equal(out.text, original, "rejected envelope must round-trip byte-for-byte"); + const fwd = rig.forwards.at(-1)!; + assert.equal(fwd.raw, original); + assert.equal(listSessions().find((s) => s.id === "zed-thread-AMBIG"), undefined, "no session may be created for an unconvertible body"); + } finally { + await closeRig(rig); + } +}); + +test("zed lane: envelope-shaped body on /chat/completions is NOT the zed wire", async () => { + const rig = await startRig(); + try { + // same envelope fields, but a standard openai chat body — the path must + // not be misclassified as zed (/chat/completions endsWith /completions) + const body = zedEnvelope({ model: MODEL, messages: [{ role: "user", content: "hi" }], stream: true }, { thread_id: "zed-thread-CC" }); + const original = JSON.stringify(body); + const r = await fetch(`http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/chat/completions`, { + method: "POST", + headers: { "content-type": "application/json", "x-session-id": "not-zed" }, + body: original, + }); + assert.equal(r.status, 200); + const fwd = rig.forwards.at(-1)!; + // no messages at the TOP level of this body -> the openai arm relays it + // verbatim (#1284); the crucial negative: NO zed unwrap/rewrap happened + assert.equal(fwd.raw, original, "/chat/completions must not treat the envelope as a zed wire"); + assert.equal(listSessions().find((s) => s.id === "zed-thread-CC"), undefined, "no zed-thread session may exist for a /chat/completions request"); + } finally { + await closeRig(rig); + } +});