Skip to content

feat(sdk)!: run the Node SDK lifecycle in the shared Rust protocol - #4963

Open
ScriptedAlchemy wants to merge 2 commits into
masterfrom
triage/native-sdk
Open

ScriptedAlchemy wants to merge 2 commits into
masterfrom
triage/native-sdk

Conversation

@ScriptedAlchemy

@ScriptedAlchemy ScriptedAlchemy commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Refs #4226. This is a reviewable slice of #4226, not the whole issue. The release-workflow criteria listed below are still open, so this PR does not close it.

What changes

The Node SDK's HTTP lifecycle now runs in Rust. @tracedecay/sdk is a generated TypeScript facade over a Node-API binding (crates/tracedecay-sdk-node, napi-rs). The binding sits on a transport-free tracedecay_sdk::protocol module, which the blocking Rust client also uses. The second executable interpretation in TypeScript is deleted: SSE parsing, envelope and problem validation, cursor and reconnect logic, and request controls.

  1. fix(sdk): share one transport-free lifecycle protocol (Rust only)
    • Request preparation, envelope and problem admission, SSE framing, the delivered cursor, and the reconnect budget move into protocol, which performs no I/O.
    • codegen.rs generates OPERATION_CONTRACTS from the canonical registry for by-identifier dispatch.
    • Fixes defects the TS client already guarded against:
      • Pages decode through canonical PageState: opaque {kind,cursor} is admitted; bare strings, non-canonical cursors, and returned > total are refused.
      • Problems must be bound to the invoked binding; denials name none.
      • Receipts may not end before they start, and cancelled or timed-out receipts carry evidence.
      • Curation receipts verify the scope digest.
      • Page options are supported.
      • 401/403 and non-JSON media are refused from the response head without reading the body.
  2. feat(sdk)!: …: the binding, the TS cutover, packaging, and the ChatGPT extension.

Boundary ownership

  • Event loop: network waits run on the binding's Tokio runtime and never block it.
  • AbortSignal: interrupts in-flight native I/O and closes the connection. It never cancels the daemon operation; cancelOperation does.
  • Streams and backpressure: a stream reads its body only when the iterator asks for an event, which applies TCP backpressure. Early return, close, and abort all release the connection.
  • Errors: cross as one typed payload and map onto the unchanged public error classes.
  • MCP operations: stay on the caller's adapter and never load the binding.
  • Number handling: unchanged. Payloads cross as JSON text, and resume.nextSequence still accepts number, bigint, or decimal string; the binding parses it as u64.

Breaking change (documented in the SDK README "Migrating from 0.15")

  • ClientOptions.fetch is removed.
  • The host needs @tracedecay/sdk-<platform> or an explicit addon path.
  • Error classes are unchanged, but messages are now the Rust client's.
  • The canonical contract is enforced. These are now protocol failures:
    • non-canonical event names;
    • problem records with unknown or inconsistent fields;
    • lone-CR line endings, a BOM, or malformed UTF-8;
    • a body ending inside a frame.
  • retry: fields are ignored; the daemon never sends them.

Verification (Bazel, macOS arm64)

  • //crates/tracedecay-sdk:unit_test and :sdk_suite (45 tests, including new behavior tests for every shared fix). The problem-detail fixture is proven equal to ApplicationProblem::from_detail.
  • //sdks/codegen:unit_test, plus pnpm --dir dashboard run contracts:check reporting "contracts up to date".
  • //sdks/typescript:unit_test (110 tests over real loopback sockets) and //sdks/typescript:typecheck. Coverage includes:
    • event-loop responsiveness while a request waits;
    • abort of in-flight I/O, with the server observing the close;
    • early return releasing the transport without a cancel POST;
    • backpressure: daemon writes are refused while the consumer pauses;
    • a child process exiting on its own after interrupted and closed native calls;
    • the shared framing fixture, cursor resume, and typed refusals.
  • //plugin/chatgpt-extension:{typecheck,adapter_test,bridge_lifecycle_test,serve_client_test} and node scripts/build.mjs --check ("embedded artifacts are current").
  • rustfmt_check_2024 for both crates. bazel run //scripts:gen_builds reproduces the committed BUILD files.

Handwritten client code went from 3,103 lines to 2,764:

Before After
TS client runtime 1,253 504
Rust SDK 1,850 2,251 (includes paging and the new checks)
Node binding — 509

These are source line counts, not bundle sizes.

Still open for #4226 (why this is Refs, not Closes)

  • Release wiring (shared release files, not changed here):

    • release.yml must build //crates/tracedecay-sdk-node:addon per .github/release-targets.json target.
    • It must stage and publish the platform packages with sdks/typescript/scripts/native-packages.mjs stage.
    • It must run native-packages.mjs link before npm pack.
    • It must place tracedecay_sdk_node.node beside the tracedecay binary in each release archive.

    Until then, a published @tracedecay/sdk from this commit has no platform package, and the offline plugin's three HTTP views (code_callers, code_callees, code_symbol_search) report a typed "binding not installed" failure. MCP-backed views are unaffected.

  • Not measured: an optimized addon build, plus Linux and Windows builds. Only the macOS arm64 debug addon was built locally.

  • Not run: the clean-consumer test:installed journey (it needs a built daemon and the addon) and the typed_terminal_live daemon journey. Both are updated to load the addon.

  • Cargo.lock: besides the napi crates, cargo re-resolved existing windows-sys edges onto the already-locked 0.61.2. There are no version upgrades.

🤖 Generated with Claude Code


Devin Review

ScriptedAlchemy and others added 2 commits November 24, 2026 14:34
Move request preparation, envelope and problem admission, SSE framing,
the delivered cursor, and the reconnect budget into `protocol`, which
performs no I/O. The blocking client now only reads and writes bytes
for it, so an async transport can reuse the same rules (#4226).

Generate `OPERATION_CONTRACTS` from the canonical registry so callers
can resolve an operation's lifecycle contract by identifier.

Fix defects the TypeScript client already guarded against:
- Evidence pages decode through the canonical `PageState`: opaque
  `{kind, cursor}` continuations are admitted, bare strings and
  non-canonical cursors are refused, and `returned` may not exceed
  `total`.
- Problems must be bound to the invoked binding; denials name none.
- Receipts must not end before they start, and cancelled or timed-out
  receipts must carry cancellation evidence.
- Curation receipts must carry a scope whose digest commits to it.
- Operations accept page size and cursor options.
- 401/403 and non-JSON media are refused from the response head,
  before reading a body that would be discarded.

The shared problem-detail fixture is proven against
`ApplicationProblem::from_detail` so other clients can build canonical
problems from it.

Refs #4226

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`@tracedecay/sdk` becomes a generated TypeScript facade over a Node-API
binding (`crates/tracedecay-sdk-node`) of the Rust SDK protocol. Node and
Rust now admit the same envelopes, problems, stream frames, terminal
states and reconnects, and the TypeScript lifecycle runtime (SSE parsing,
envelope and problem validation, cursor and reconnect handling) is
deleted.

Boundary ownership:
- Network waits run on the binding's Tokio runtime; the event loop is
  never blocked.
- An AbortSignal interrupts the in-flight native request and closes its
  connection. It never cancels the daemon operation; `cancelOperation`
  does.
- A stream reads its body only when the iterator asks for an event, so
  a slow consumer applies TCP backpressure. Early return, `close`, or
  abort release the connection.
- Errors cross as one typed payload and map onto the unchanged public
  error classes.
- MCP-backed operations stay on the caller's adapter and never load the
  binding.

Packaging: Bazel builds the addon as a `rust_shared_library` emitted by
the BUILD generator. `scripts/native-packages.mjs` stages napi-rs style
`@tracedecay/sdk-<platform>` packages from `.github/release-targets.json`
and links them as optionalDependencies at release time. Hosts can pass
an explicit `addon` path; the ChatGPT extension loads the binding
shipped beside the daemon binary, because its embedded server is a
single bundled file.

Conformance runs on real loopback sockets: event-loop responsiveness,
abort of in-flight I/O, early-return transport release without
cancellation, backpressure, process exit after settled calls, framing
limits from the shared fixture, cursor resume, and typed refusals.

BREAKING CHANGE: `ClientOptions.fetch` is removed. A Node >= 20 host
needs the platform package for its OS/arch, or an explicit `addon`
path. Error classes are unchanged but messages now come from the Rust
client. Event names outside the canonical set, problem records with
unknown or inconsistent fields, lone-CR line endings, a byte-order mark,
malformed UTF-8, and a body ending inside a frame are protocol failures.
`retry:` fields are ignored. The README documents the migration.

Refs #4226

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ScriptedAlchemy
ScriptedAlchemy enabled auto-merge (squash) November 24, 2026 23:01

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 2 potential issues.

4 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment on lines +502 to +512
if let Some(cancellation) = execution.get("cancellation")
&& !cancellation.is_null()
{
if !contract.cancellable {
return Err(protocol(
status,
format!(
"daemon returned cancellation evidence for non-cancellable {}",
contract.operation_id
),
));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Valid workflow timeout receipts rejected

When an admitted workflow change times out, admit_response rejects its deadline observation because the operation is not cancellable. It also requires a typed payload, but workflow_effect_outcome returns only the receipt. Node callers get a malformed-response error instead of the timeout receipt.

Learn more

The WorkflowActivateDefinition contract permits the timed-out terminal state even though callers cannot cancel the operation. workflow_effect_outcome builds a timed-out effect with no payload, and work_effect records a before_effect deadline observation. The shared decoder rejects that observation for a non-cancellable operation. It also exempts only evidence outcomes from result deserialization when the payload is null, so accepting the observation alone would not restore Node behavior. The existing timeout test exercises the generated decoder directly, not the native transport.

Example: A workflow_activate_definition request passes admission but reaches its deadline before writing the change. The daemon returns a timed_out effect receipt with cancellation.stage: "before_effect" and payload: null. The Node call rejects instead of returning that receipt.

Recommended fix: Distinguish deadline observations from caller cancellation when validating a legal timed-out terminal, and admit receipt-only outcomes where the canonical effect contract permits a null payload. Exercise the public Node operation over HTTP in the regression test.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +306 to +310
call = this.#client().prepareOperation(
operationId,
JSON.stringify(request),
JSON.stringify(controls),
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Invalid deadlines silently omitted

When deadlineMicros is NaN or infinite, #requestHttp serializes it as null. CallOptions treats null as absent, so the SDK sends the operation without a caller deadline instead of rejecting it.

Learn more

The JSON boundary cannot represent NaN or infinity as numbers. CallOptions decodes the resulting null as None, and apply_request_headers then omits the deadline header. The same conversion silently drops a non-finite page size and defaults a non-finite reconnect budget to zero in StreamConfig.

Example: A caller computes deadlineMicros using Date.parse(timestamp) * 1000 and receives NaN from an invalid timestamp. The SDK sends the operation under the daemon’s defaults rather than rejecting before I/O.

Recommended fix: Check that supplied numeric controls are safe integers before JSON encoding. Leave Rust responsible for operation-specific constraints and ranges, and assert that invalid numbers cause no HTTP request.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant