Repository navigation
refactor(packages): consolidate protocol and stream ownership - #172991
Conversation
Use one tuple-preserving ordered literal-union constructor without changing Gateway protocol JSON, exported shapes, or static inference. Share Anthropic request, refusal, reducer, compaction and terminal ownership while preserving the SDK/fetch adapters and their error profiles. Reuse the existing abort race. Reuse prepared compaction details and table widths, trust typed internal file metadata inputs, and leave the Agent loop as the sole message-snapshot owner. Replace the primitive-only session-options deep clone with a shallow copy. Remove write-only transport scratch indices and duplicate outer cleanup; reuse prepared Markdown token projections. Route Completions context budgeting through the shared calibrated CJK estimator, correcting underestimated rare/halfwidth and supplementary input. Add request-budget regression cases. Best-effort tradeoffs accepted: - Malformed internal assistant/tool-name values violating AgentMessage can throw instead of being silently omitted. The guards came from extractions #85341/#123467, with no cited human malformed-message incident. External tool arguments and patch-result metadata remain validated. - An impossible table column/width mismatch no longer gets a custom error. The removed throw came from strict-index ratchet #104577, not an actual-use report; columns and widths still come from the same ordered allocation. No Phase E standalone session-memory backend, security authority, public protocol/config/SDK contract, schema, dependency or durability change.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
|
Codex review: needs changes before merge. What this changesThis PR consolidates protocol construction and stream bookkeeping while correcting Unicode input estimates for compatible Completions endpoints. Example: A compatible Completions endpoint has a 10,000-token context and receives a system prompt containing 1,000 halfwidth コ characters.
Review scores
ProductKind: Refactor · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 1 item remains Keep open: this maintainer-directed consolidation has concrete value, including corrected Unicode budgeting, and no definite introduced defect was established; the failing Anthropic cancellation check still needs attribution. Priority: P2 Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherGateway schemas validate client payloads, while AI provider adapters turn conversation context into requests and reduce provider events into assistant messages. flowchart LR
Clients --> ProtocolSchemas
LiteralUnionHelper --> ProtocolSchemas
ConversationContext --> ProviderAdapters
UnicodeEstimator --> ProviderAdapters
ProviderAdapters --> StreamLifecycle
StreamLifecycle --> AssistantMessages
Technical reviewBest possible solution: Retain the consolidation and shared Unicode estimator while resolving the cancellation check's attribution through the existing stream owner. Do we have a high-confidence way to reproduce the issue? Source establishes the stale estimator path and the three independent request-budget cases; no target code was executed during this read-only review. Is this the best way to solve the issue? Reusing the calibrated estimator and retaining distinct transport adapters is a sound ownership consolidation; source inspection found no definite regression. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 8aeab56e8e25. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource -503, Tests +64, Other -1. Total -440 across 77 files. Added test files: 1. View PR surface stats
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 15, 2026, 5:49 AM ET / 09:49 UTC. |
Hold the Anthropic fixture's second pull on its existing cleanup gate so the custom cancellation work is actually admitted before testing its ownership. An upstream fetch abort may otherwise error the wrapper before cancel runs, making the test demand settlement of work that was never accepted. Keep every origin-context, drainage, lifetime and reuse assertion unchanged. No production behavior, timeout, retry or skip changes.
|
Exact-head landing evidence for the coordinator-authorized inherited-red exception. Head:
All exact-head check runs were enumerated. Attempt-1 SDK/gate failures are historical, not hidden or relabeled green. Attempt-2 security-fast The retained tested merge is Compiler-work diagnosis: both cold full declaration builds passed using the same pinned compiler/options, head then merge-base. Types +0.0669%, Instantiations +0.0515%, Symbols +0.2864%, Check time ratio 0.874x. The PR body contains exact counts and isolated proof details. These comparable counts, followed by the one successful SDK rerun, satisfy the coordinator's infra ruling. Net production reduction remains 503 LOC. Protocol shapes/types, security/durability contracts, and the entire named Phase E standalone session-memory KEEP surface remain preserved. Failed CI is not claimed green; merge remains pinned to the reviewed head and subject to native live admission. |
|
Admin merge of exact head 7de4cdc (coordinator, wave-5 deslop).
The earlier plugin-sdk boundary dts timeout was diagnosed as infra, not compiler growth: The native landing admission could not run because GitHub returned HTTP 502 for the 100-job inventory page; this merge uses the same exact-head SHA guard instead. |
…aw#172991) * refactor(packages): consolidate protocol and stream ownership Use one tuple-preserving ordered literal-union constructor without changing Gateway protocol JSON, exported shapes, or static inference. Share Anthropic request, refusal, reducer, compaction and terminal ownership while preserving the SDK/fetch adapters and their error profiles. Reuse the existing abort race. Reuse prepared compaction details and table widths, trust typed internal file metadata inputs, and leave the Agent loop as the sole message-snapshot owner. Replace the primitive-only session-options deep clone with a shallow copy. Remove write-only transport scratch indices and duplicate outer cleanup; reuse prepared Markdown token projections. Route Completions context budgeting through the shared calibrated CJK estimator, correcting underestimated rare/halfwidth and supplementary input. Add request-budget regression cases. Best-effort tradeoffs accepted: - Malformed internal assistant/tool-name values violating AgentMessage can throw instead of being silently omitted. The guards came from extractions openclaw#85341/openclaw#123467, with no cited human malformed-message incident. External tool arguments and patch-result metadata remain validated. - An impossible table column/width mismatch no longer gets a custom error. The removed throw came from strict-index ratchet openclaw#104577, not an actual-use report; columns and widths still come from the same ordered allocation. No Phase E standalone session-memory backend, security authority, public protocol/config/SDK contract, schema, dependency or durability change. * test(plugins): make cancellation ownership fixture deterministic Hold the Anthropic fixture's second pull on its existing cleanup gate so the custom cancellation work is actually admitted before testing its ownership. An upstream fetch abort may otherwise error the wrapper before cancel runs, making the test demand settlement of work that was never accepted. Keep every origin-context, drainage, lifetime and reuse assertion unchanged. No production behavior, timeout, retry or skip changes.
Related: #114386, #139935, #162491, #168834
What Problem This Solves
Maintainer-requested packages cleanup removes duplicated construction and stream bookkeeping; it also fixes Completions' stale Unicode input-budget estimator.
User Impact
Halfwidth, rare-BMP, and supplementary Unicode prompts receive more conservative automatic output caps on compatible Completions endpoints. Other changes are internal simplifications. Gateway schema JSON, static types, SDK/config surfaces, security checks, and transcript durability are preserved. No migration or operator action is required. The standalone Phase E session-memory backend and its tests are untouched.
Why This Change Was Made
One private tuple-preserving helper replaces 285 ordered literal-union constructors. Anthropic's SDK/fetch adapters share lifecycle ownership while keeping their existing profiles. Stream reducers retain authoritative cleanup; duplicate outer cleanup and write-only scratch indices are removed. Compaction, Markdown annotation, table rendering, and Agent snapshots reuse prepared facts instead of repeating work.
Completions retained a CJK estimator extracted before #114386 established the calibrated shared owner. It now consumes that owner rather than maintaining an older, underweighted copy. For a 10,000-token context with 1,000 repeated characters, the real request builder's output caps change from 9,686 to 7,499 for halfwidth text, and from 8,749 to 6,249 / 4,999 for rare BMP / supplementary ideographs. ASCII/common-Han behavior remains unchanged. These are budgeting estimates, not new live-provider or tokenizer measurements.
Net production reduction: 503 lines (981 additions, 1,484 deletions), excluding tests, fixtures, test support, generated files, declarations, and shrink-only assertion-baseline edits.
Best-effort tradeoffs accepted
AgentMessagevalues may throw instead of being ignored. The guard came from extraction work refactor: internalize OpenClaw agent runtime #85341/fix: retain file changes across conversation compaction #123467, with no cited human actual-use malformed-message incident; external arguments and patch-result details remain validated.Evidence
ProtocolSchemas; emitted consumer checks preserve exact literal unions and registry mutability. Later helper corrections were type-only and separately checked.38713648791completed with every selected job passing except UI E2E 3/4, Node compact-large 9, and the aggregate gate. The UI label mismatch is identical on scheduled main run38713991924, headdb0369215d8b35e17c72cebffcb59306899d3dbb, job116352521404(UI 8/9): expected#103469, receivedopenclaw/openclaw#103469at the unchanged E2E line 167.38717584131, exact head7de4cdc590e939acf2945d1aac6e3f2f3f69591b, completed. Every selected Node shard, types/lint, budgets, build, protocol, security and other selected job passed except the two nonaggregate jobs below. CI was not rerun, and the failed aggregate gate is not claimed green.116364651770#103469, while rendering now returnsopenclaw/openclaw#103469. Identical failure on main run38713991924, headdb0369215d8b35e17c72cebffcb59306899d3dbb, job116352521404; unrelated #172836 updated rendering but missed this E2E expectation. No UI edits.116364652101116387294571in attempt 2 on the unchanged exact head, passed at 11:09:29 UTC. No source fix or green-chasing push. Main's WhatsApp TS4058 is a different signature and is not used as matching inherited proof for the timeout.openclaw/ci-gate,116370925616An earlier isolated full-SDK preparation replay also hit the unchanged 300,000ms limit on the heavily loaded local host (Node 26.5.0, not CI's Node 24/Linux). It emitted no source diagnostic. That wall-time replay alone was inconclusive and is not the basis of attribution.
SDK compiler-work diagnosis
At the coordinator's direction, the same pinned native TypeScript
7.1.0-dev.20260928.1compiler behindplugin-sdk boundary dtsran full cold declaration builds with--extendedDiagnostics, first at head7de4cdc590e939acf2945d1aac6e3f2f3f69591b, then at merge-base9e3e16c224697b9a5cb24e7ede12ac4992a97a87. Both passed. Same full project, declaration-only single-threaded emit, frozen dependencies and compiler options; incremental reuse disabled on both. Both commands use isolated HOME/OpenClaw/XDG state. Manifest, lockfile and project configs are identical. Baseline membership was checked; its three shared session-url-contract source files are byte-identical, and no changed lane source is shared.Both programs contain 16,506 files. Types/Instantiations are comparable, far below the coordinator's material-growth threshold. Check time remains load-sensitive. Under the explicit ruling, the timeout is diagnosed infra and one SDK-job rerun was authorized. No timeout, retry, skip, dependency, baseline or compiler setting was changed. The first protected API request was definitively rejected by GitHub's REST quota before starting a rerun; the run remained on attempt 1. After the reported reset, quota/head/attempt were revalidated and GitHub accepted the single SDK-job rerun: run
38717584131, attempt 2, unchanged exact head7de4cdc590e939acf2945d1aac6e3f2f3f69591b. That SDK job116387294571passed at 11:09:29 UTC. No second rerun will be requested.Known local gaps remain visible: the broader changed checker was stopped in its expensive SQLite inventory, so its umbrella result is not green. Its environment-name budget failure reproduces on the clean base (455 versus 454); this patch adds no environment names. A mixed focused run's gateway-client shard was killed with SIGKILL before assertions, leaving its later memory shard unrun. The unchanged timed Agent retention test hit its deadline; the direct retention entry point completed with no retained histories, but the timed harness route is not claimed green. No timeout, retry, skip, suppression, assertion, or retained-behavior baseline was weakened. Hosted CI on the exact pushed head is the broad gate.
Lane coverage ledger
The pass covered three-day additions, fourteen-day additions, then eligible packages largest-file-first. The complete PR-tool import closure was excluded. A whole-function clone scan and further prepared-fact/dead-cleanup passes found the following coherent cuts and retained boundaries.
gateway-protocol/src/schema/string-literal-union.ts:1and 57 schema modulesai/src/providers/anthropic.ts:102,ai/src/transports/anthropic-stream-lifecycle.ts:1ai/src/transports/anthropic-stream-reducer.ts:50ai/src/transports/openai-completions-params.ts:1agent-core/src/harness/compaction/compaction.ts,utils.tsagent-core/src/agent.ts:555runAgentLoopsynchronously owns the copy before any event/await. Keep public state and tools copies.markdown-core/src/assistant-transcript.ts:202memory-host-sdk/src/host/session-files.tsterminal-core/src/table.ts:517