@goodtiming/baton-sdk 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -261,7 +261,7 @@ None of it blocks the quickstart above.
261
261
  - Only the high-level `McpServer`. The low-level `Server` is not wrapped.
262
262
  - **Task-based tools are not wrapped, and are not left alone either.** A 1.x tool registered with an object at `.handler` rather than a function produces no `tool_call_*` events at all, and nothing reports that. It still gets the intent parameters added to its advertised schema, because injection runs before the wrap is skipped and the strip only happens inside the wrapper. So `user_goal` can arrive in your own handler's arguments. Tools on the same server registered the ordinary way are unaffected. ⚠ **The request-level seam above does not rescue this one**: it reports only on tools this package wrapped, so a task-based tool emits nothing even for a rejected argument, where an unknown tool now emits a `tool_call_error`.
263
263
  - Intent parameters need a Zod schema. On the 2.x SDK a tool registered with a non-Zod standard schema is still wrapped and still emits `tool_call_*`; it just advertises no intent parameters.
264
- - v2's `createMcpHandler` is untested. A server built per request by your own code is supported: see [A server per request](#a-server-per-request).
264
+ - v2's `createMcpHandler` is tested only for calls that pause for input. A server built per request by your own code is supported: see [A server per request](#a-server-per-request).
265
265
 
266
266
  ## Wire compatibility
267
267
 
package/dist/index.cjs CHANGED
@@ -76,6 +76,7 @@ __export(index_exports, {
76
76
  ResourceReadStartPayloadSchema: () => ResourceReadStartPayloadSchema,
77
77
  SDK_VERSION: () => SDK_VERSION,
78
78
  Scrubber: () => Scrubber,
79
+ SinkClosedError: () => SinkClosedError,
79
80
  StdoutSink: () => StdoutSink,
80
81
  SurfaceSnapshotEventSchema: () => SurfaceSnapshotEventSchema,
81
82
  SurfaceSnapshotPayloadSchema: () => SurfaceSnapshotPayloadSchema,
@@ -102,7 +103,7 @@ __export(index_exports, {
102
103
  module.exports = __toCommonJS(index_exports);
103
104
 
104
105
  // src/version.ts
105
- var SDK_VERSION = "ts-0.6.2";
106
+ var SDK_VERSION = "ts-0.6.3";
106
107
 
107
108
  // src/events.ts
108
109
  var import_zod = require("zod");
@@ -711,10 +712,24 @@ function nextClockSequence() {
711
712
  // src/sinks.ts
712
713
  var REFUSAL_BODY_MAX_LEN = 500;
713
714
  var REFUSAL_LOG_MS = 6e4;
715
+ var SinkClosedError = class extends Error {
716
+ name = "SinkClosedError";
717
+ };
718
+ function isSinkClosed(err) {
719
+ return err instanceof Error && err.name === "SinkClosedError";
720
+ }
721
+ var warnedClosed = /* @__PURE__ */ new WeakSet();
722
+ function droppedAfterClose(sink) {
723
+ PROCESS_DROPS.add("after_close");
724
+ if (warnedClosed.has(sink)) return;
725
+ warnedClosed.add(sink);
726
+ warn("baton: the sink is closed; further events are dropped.");
727
+ }
714
728
  async function safeWrite(sink, event) {
715
729
  try {
716
730
  await sink.write(event);
717
731
  } catch (err) {
732
+ if (isSinkClosed(err)) return droppedAfterClose(sink);
718
733
  PROCESS_DROPS.add("write_failed");
719
734
  process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
720
735
  `);
@@ -767,7 +782,7 @@ var StdoutSink = class {
767
782
  this.stream = options.stream ?? process.stderr;
768
783
  }
769
784
  async write(event) {
770
- if (this.closed) throw new Error("StdoutSink is closed");
785
+ if (this.closed) throw new SinkClosedError("StdoutSink is closed");
771
786
  this.stream.write(JSON.stringify(event) + "\n");
772
787
  }
773
788
  async flush() {
@@ -784,7 +799,7 @@ var FileSink = class {
784
799
  fd = null;
785
800
  closed = false;
786
801
  async write(event) {
787
- if (this.closed) throw new Error("FileSink is closed");
802
+ if (this.closed) throw new SinkClosedError("FileSink is closed");
788
803
  this.fd ??= (0, import_node_fs.openSync)(this.path, "a");
789
804
  (0, import_node_fs.writeSync)(this.fd, JSON.stringify(event) + "\n");
790
805
  }
@@ -822,9 +837,11 @@ var MultiSink = class {
822
837
  }
823
838
  async fanOut(op) {
824
839
  const results = await Promise.allSettled(this.sinks.map(async (sink) => op(sink)));
825
- const errors = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
826
- if (errors.length === 1) throw errors[0];
827
- if (errors.length > 1) throw new AggregateError(errors, "MultiSink fan-out failures");
840
+ let errors = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
841
+ if (errors.length < results.length) errors = errors.filter((e) => !isSinkClosed(e));
842
+ if (errors.length === 0) return;
843
+ if (errors.length === 1 || errors.every(isSinkClosed)) throw errors[0];
844
+ throw new AggregateError(errors, "MultiSink fan-out failures");
828
845
  }
829
846
  };
830
847
  var CircuitBreaker = class {
@@ -923,7 +940,7 @@ var HttpSink = class _HttpSink {
923
940
  return this.closing.signal.aborted;
924
941
  }
925
942
  async write(event) {
926
- if (this.closed) throw new Error("HttpSink is closed");
943
+ if (this.closed) throw new SinkClosedError("HttpSink is closed");
927
944
  this.enqueue(event);
928
945
  this.unsentWarned = false;
929
946
  void this.scheduleDrain();
@@ -2360,6 +2377,24 @@ var DisabledSink = class {
2360
2377
  }
2361
2378
  };
2362
2379
 
2380
+ // src/integrations/mcp/inputRequired.ts
2381
+ function isInputRequired(result) {
2382
+ try {
2383
+ return isRecord(result) && result.resultType === "input_required";
2384
+ } catch {
2385
+ return false;
2386
+ }
2387
+ }
2388
+ function resumesPausedCall(extra) {
2389
+ try {
2390
+ const req = extra?.mcpReq;
2391
+ if (req === void 0) return false;
2392
+ return req.inputResponses !== void 0 || req.requestState?.() !== void 0;
2393
+ } catch {
2394
+ return false;
2395
+ }
2396
+ }
2397
+
2363
2398
  // src/integrations/mcp/handle.ts
2364
2399
  var BatonHandle = class {
2365
2400
  sink;
@@ -2713,6 +2748,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
2713
2748
  runtime_meta: scrubbedMeta,
2714
2749
  call_id: uuid7()
2715
2750
  };
2751
+ if (resumesPausedCall(extra)) return { common, session };
2716
2752
  await emit(
2717
2753
  ctx.sink,
2718
2754
  () => ToolCallStartEventSchema.parse({
@@ -2744,20 +2780,19 @@ function batonWrap(nameRef, original, ctx) {
2744
2780
  const { common, session } = await openCall(ctx, toolName, extra, params, retired);
2745
2781
  const terminate = async (build, replacement) => {
2746
2782
  if (!slot) {
2747
- await emit(ctx.sink, build);
2783
+ if (build !== null) await emit(ctx.sink, build);
2748
2784
  return;
2749
2785
  }
2750
2786
  const earlier = slot.flushTerminal;
2751
2787
  if (earlier !== null) await earlier(CLEAN_OUTCOME);
2752
2788
  slot.flushTerminal = async (outcome) => {
2753
- await emit(
2754
- ctx.sink,
2755
- () => replacement !== null && outcome.failed ? replacement(outcome) : build()
2756
- );
2789
+ if (replacement !== null && outcome.failed) await emit(ctx.sink, () => replacement(outcome));
2790
+ else if (build !== null) await emit(ctx.sink, build);
2757
2791
  };
2758
2792
  };
2759
2793
  const parkFailure = (build) => terminate(build, null);
2760
2794
  const parkSuccess = (build, replacement) => terminate(build, replacement);
2795
+ const parkPause = (replacement) => terminate(null, replacement);
2761
2796
  const startedAt = performance.now();
2762
2797
  let result;
2763
2798
  try {
@@ -2800,6 +2835,59 @@ function batonWrap(nameRef, original, ctx) {
2800
2835
  throw err;
2801
2836
  }
2802
2837
  const durationMs = Math.round(performance.now() - startedAt);
2838
+ const failedAbove = (outcome, failureKind) => ToolCallErrorEventSchema.parse({
2839
+ ...common,
2840
+ sequence_number: ctx.counter.nextFor(session),
2841
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2842
+ payload: {
2843
+ tool_name: toolName,
2844
+ // The lane the OUTER came back on, not this one's: on 2.x the
2845
+ // conversion failure is converted to a returned `isError` inside
2846
+ // `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
2847
+ // right there. A pause the SDK rejects on 2026-07-28 raises, so
2848
+ // both lanes are reachable.
2849
+ error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2850
+ // ⚠ The INNER's measurement — the vendor's handler duration —
2851
+ // not the outer's. Every other leg means the same thing by this
2852
+ // member, and widening it here for one failure kind would make
2853
+ // `duration_ms` mean two things in one column.
2854
+ duration_ms: durationMs,
2855
+ // Omitted, not null, when undetermined: SPEC §11.4.3 says MUST OMIT.
2856
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
2857
+ // ⚠ **WITHHELD under `"off"`, unlike the three request-side
2858
+ // kinds.** The message quotes the value the tool returned
2859
+ // ("`'not-an-int'` is not of type `integer`"), so it is
2860
+ // result-derived by provenance and goes — which leaves
2861
+ // `failure_kind` as the ONLY surviving signal for an
2862
+ // `output_schema_mismatch` under `"off"`, and is the measurement
2863
+ // that justified putting the member on the wire at all.
2864
+ //
2865
+ // ⚠ `result` is what the CLIENT received — the SDK's own error
2866
+ // envelope — not the vendor's rejected return value. §11.4.3
2867
+ // asks for the envelope that holds the flag and the reason, and
2868
+ // this package's own invariant is that it agrees with the
2869
+ // caller. Recording the rejected output TOO would need a member
2870
+ // nothing on the wire has; the loss is deliberate and worth
2871
+ // knowing when debugging one of these.
2872
+ ...resultDerivedFields(
2873
+ ctx.resultCaptureMode,
2874
+ () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2875
+ // ⚠ `null` on the `raised` lane, never `undefined`, and the
2876
+ // union is what forces the branch rather than a comment: the
2877
+ // scrubber would answer `undefined` and DROP the key, where the
2878
+ // sibling raise lane a few lines up declares `result: null`
2879
+ // explicitly, for the reason `ToolCallErrorPayloadSchema`
2880
+ // records. One shape for "no result object existed", not two.
2881
+ outcome.raised ? null : outcome.result ?? null,
2882
+ (text) => errorBody(ctx, text),
2883
+ ctx.scrubber
2884
+ )
2885
+ }
2886
+ });
2887
+ if (isInputRequired(result)) {
2888
+ await parkPause(failedAbove);
2889
+ return result;
2890
+ }
2803
2891
  if (isErrorResult(result)) {
2804
2892
  await parkFailure(
2805
2893
  () => ToolCallErrorEventSchema.parse({
@@ -2842,61 +2930,7 @@ function batonWrap(nameRef, original, ctx) {
2842
2930
  ...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
2843
2931
  }
2844
2932
  }),
2845
- // The handler returned something this sensor reads as a success, and
2846
- // then the outer seam saw the call fail anyway — so what failed is the
2847
- // producer's own conversion of the output (SPEC §11.4.3's
2848
- // `output_schema_mismatch`). Correcting this is the whole point of the
2849
- // second seam: without it this is a `tool_call_end` for a call the
2850
- // CALLER saw fail, which is a success the product invented.
2851
- (outcome) => ToolCallErrorEventSchema.parse({
2852
- ...common,
2853
- sequence_number: ctx.counter.nextFor(session),
2854
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2855
- payload: {
2856
- tool_name: toolName,
2857
- // The lane the OUTER came back on, not this one's: on 2.x the
2858
- // conversion failure is converted to a returned `isError` inside
2859
- // `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
2860
- // right there. A throw out of the handler is unreachable on
2861
- // either major today for this lane; spelled anyway, because the
2862
- // alternative is a crash on the day it stops being.
2863
- error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2864
- // ⚠ The INNER's measurement — the vendor's handler duration —
2865
- // not the outer's. Every other leg means the same thing by this
2866
- // member, and widening it here for one failure kind would make
2867
- // `duration_ms` mean two things in one column.
2868
- duration_ms: durationMs,
2869
- failure_kind: OUTPUT_SCHEMA_MISMATCH,
2870
- // ⚠ **WITHHELD under `"off"`, unlike the three request-side
2871
- // kinds.** The message quotes the value the tool returned
2872
- // ("`'not-an-int'` is not of type `integer`"), so it is
2873
- // result-derived by provenance and goes — which leaves
2874
- // `failure_kind` as the ONLY surviving signal for this failure
2875
- // under `"off"`, and is the measurement that justified putting
2876
- // the member on the wire at all.
2877
- //
2878
- // ⚠ `result` is what the CLIENT received — the SDK's own error
2879
- // envelope — not the vendor's rejected return value. §11.4.3
2880
- // asks for the envelope that holds the flag and the reason, and
2881
- // this package's own invariant is that it agrees with the
2882
- // caller. Recording the rejected output TOO would need a member
2883
- // nothing on the wire has; the loss is deliberate and worth
2884
- // knowing when debugging one of these.
2885
- ...resultDerivedFields(
2886
- ctx.resultCaptureMode,
2887
- () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2888
- // ⚠ `null` on the `raised` lane, never `undefined`, and the
2889
- // union is what forces the branch rather than a comment: the
2890
- // scrubber would answer `undefined` and DROP the key, where the
2891
- // sibling raise lane a few lines up declares `result: null`
2892
- // explicitly, for the reason `ToolCallErrorPayloadSchema`
2893
- // records. One shape for "no result object existed", not two.
2894
- outcome.raised ? null : outcome.result ?? null,
2895
- (text) => errorBody(ctx, text),
2896
- ctx.scrubber
2897
- )
2898
- }
2899
- })
2933
+ (outcome) => failedAbove(outcome, OUTPUT_SCHEMA_MISMATCH)
2900
2934
  );
2901
2935
  return result;
2902
2936
  };
@@ -3062,11 +3096,12 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
3062
3096
  })
3063
3097
  );
3064
3098
  };
3065
- await fire(spec.schemas.start, spec.startParams(requestParams));
3099
+ if (!resumesPausedCall(extra)) await fire(spec.schemas.start, spec.startParams(requestParams));
3066
3100
  const startedAt = performance.now();
3067
3101
  const elapsed = () => Math.round(performance.now() - startedAt);
3068
3102
  try {
3069
3103
  const result = await handler(...args);
3104
+ if (isInputRequired(result)) return result;
3070
3105
  await fire(spec.schemas.end, {
3071
3106
  ...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
3072
3107
  duration_ms: elapsed()
@@ -3494,7 +3529,12 @@ function install(server, supplied, resolved, sentSurfaces, warned3) {
3494
3529
  seam_augmentations: snapshot.seam_augmentations
3495
3530
  }
3496
3531
  });
3497
- await sink.write(event);
3532
+ try {
3533
+ await sink.write(event);
3534
+ } catch (err) {
3535
+ if (isSinkClosed(err)) return droppedAfterClose(sink);
3536
+ throw err;
3537
+ }
3498
3538
  };
3499
3539
  const bustSchemaMemo = (name) => {
3500
3540
  const memo = internals._toolInputSchemaJson;
@@ -3956,6 +3996,7 @@ var Core = class {
3956
3996
  try {
3957
3997
  await this.sink.write(event);
3958
3998
  } catch (err) {
3999
+ if (isSinkClosed(err)) return droppedAfterClose(this.sink);
3959
4000
  process.stderr.write(`baton: surface snapshot not sent; will retry: ${printable(err)}
3960
4001
  `);
3961
4002
  this.sentSurfaces.unmark(surface.digest);
@@ -4312,6 +4353,7 @@ var Client = class {
4312
4353
  ResourceReadStartPayloadSchema,
4313
4354
  SDK_VERSION,
4314
4355
  Scrubber,
4356
+ SinkClosedError,
4315
4357
  StdoutSink,
4316
4358
  SurfaceSnapshotEventSchema,
4317
4359
  SurfaceSnapshotPayloadSchema,