@wakeshift/sdk 0.5.2 → 0.6.0

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/dist/toolcall.js CHANGED
@@ -18,11 +18,12 @@
18
18
  import { z } from "zod";
19
19
  import * as z3 from "zod/v3";
20
20
  import * as z4 from "zod/v4";
21
- import { getObjectShape, isZ4Schema, normalizeObjectSchema, safeParseAsync } from "@modelcontextprotocol/sdk/server/zod-compat.js";
21
+ import * as z4mini from "zod/v4-mini";
22
+ import { getObjectShape, isSchema, isZ4Schema, normalizeObjectSchema } from "./zod.js";
22
23
  import { WakeshiftError } from "./errors.js";
23
24
  import { EXTENSION_KEY, dialectOf } from "./spec.js";
24
25
  import { takesTasks } from "./discover.js";
25
- import { packCall } from "./wakeshift.js";
26
+ import { packCall, userAgentOf } from "./wakeshift.js";
26
27
  // Wakeshift's three arguments (wakeshift.ts's SESSION_ARG, HARNESS_ARG and
27
28
  // CONVERSATION_ARG, repeated: that module imports this one).
28
29
  const SESSION_ARG = "session_key";
@@ -66,12 +67,26 @@ const byVersion = {
66
67
  },
67
68
  };
68
69
  // fieldsFor is Wakeshift's fields in the zod API shape's own fields use
69
- // (the default import's for an empty shape).
70
- function fieldsFor(shape, kind) {
70
+ // (for an empty shape, the default import's, or zod 4's for the MCP SDK
71
+ // 2.x, which takes only zod 4).
72
+ function fieldsFor(shape, kind, host) {
71
73
  const first = Object.values(shape ?? {})[0];
72
- const fields = !first ? (kind === "inputs" ? wakeInputs : wakeOutput) : byVersion[isZ4Schema(first) ? "v4" : "v3"][kind];
74
+ const version = first ? (isZ4Schema(first) ? "v4" : "v3") : host?.version === 2 ? "v4" : null;
75
+ const fields = version ? byVersion[version][kind] : kind === "inputs" ? wakeInputs : wakeOutput;
73
76
  return fields;
74
77
  }
78
+ /** @internal Wakeshift's three arguments as attach's own tools take them, in the zod the host's MCP SDK takes. */
79
+ export function wakeInputsFor(host) {
80
+ return host.version === 2 ? byVersion.v4.inputs : wakeInputs;
81
+ }
82
+ // withFields is an object schema with fields added, in the schema's own zod
83
+ // API (zod 3, zod 4 classic or mini).
84
+ function withFields(schema, fields) {
85
+ const s = schema;
86
+ if (typeof s.extend === "function")
87
+ return s.extend(fields);
88
+ return z4mini.extend(schema, fields);
89
+ }
75
90
  const WAKE_KEYS = [SESSION_ARG, HARNESS_ARG, CONVERSATION_ARG];
76
91
  /**
77
92
  * @internal The tools/call _meta keys a harness names its conversation in
@@ -209,12 +224,6 @@ function sameJSON(a, b) {
209
224
  function detailOf(err) {
210
225
  return err instanceof WakeshiftError ? err.detail : String(err?.message ?? err);
211
226
  }
212
- function registeredTool(server, name) {
213
- const tools = server._registeredTools;
214
- if (!tools || typeof tools !== "object")
215
- return null; // an MCP SDK that keeps them elsewhere
216
- return tools[name];
217
- }
218
227
  /** One tools/call of a wrapped tool: what its handler subscribed, for the block and the rollback. */
219
228
  class CallScope {
220
229
  at;
@@ -252,17 +261,18 @@ class CallScope {
252
261
  // User-Agent, the agent's harness and conversation_id arguments, the
253
262
  // conversation's session, and who's calling.
254
263
  wire(session = this.session) {
255
- const meta = this.extra._meta;
264
+ const req = this.at.host.req(this.extra);
265
+ const meta = req.meta;
256
266
  return packCall({
257
267
  meta,
258
268
  clientName: this.at.clientOf(meta, this.identified),
259
269
  user: this.user,
260
270
  session: session ?? undefined,
261
- userAgent: userAgentOf(this.extra),
271
+ userAgent: userAgentOf(req),
262
272
  harness: this.args.harness,
263
273
  conversation: this.args.conversation,
264
274
  tool: this.tool,
265
- tasks: takesTasks(meta, this.extra),
275
+ tasks: takesTasks(meta, req),
266
276
  });
267
277
  }
268
278
  // request runs one request of the call to Wakeshift, after any before it
@@ -415,19 +425,12 @@ class CallScope {
415
425
  function recognizedOf(a) {
416
426
  return { harness: a?.harness ?? null, via: a?.via ?? null, claimed: a?.claimed ?? null };
417
427
  }
418
- function headerOf(extra, name) {
419
- const h = extra?.requestInfo?.headers;
420
- if (!h)
421
- return "";
422
- const v = h[name] ?? h[name.toLowerCase()];
423
- return (Array.isArray(v) ? v[0] : v) ?? "";
424
- }
425
- function userAgentOf(extra) {
426
- return headerOf(extra, "user-agent") || headerOf(extra, "User-Agent");
427
- }
428
428
  function hasKey(o, key) {
429
429
  return !!o && typeof o === "object" && !Array.isArray(o) && o[key] !== undefined;
430
430
  }
431
+ function isRecord(v) {
432
+ return !!v && typeof v === "object" && !Array.isArray(v);
433
+ }
431
434
  /**
432
435
  * @internal Whether a call comes from a client that subscribes to the app's
433
436
  * events itself, on stateless servers too (which never see initialize), in
@@ -438,15 +441,16 @@ function hasKey(o, key) {
438
441
  * _meta's). conversation is ChatGPT's conversation, when it names one.
439
442
  */
440
443
  export function nativeOf(at, extra, identified) {
441
- const meta = (extra._meta ?? {});
444
+ const req = at.host.req(extra);
445
+ const meta = (req.meta ?? {});
442
446
  const conversation = typeof meta["openai/session"] === "string" && meta["openai/session"] ? meta["openai/session"] : null;
443
447
  if (at.events.native?.(extra))
444
448
  return { native: true, conversation };
445
449
  if (conversation)
446
450
  return { native: true, conversation };
447
- if (dialectOf(at.clientOf(meta, identified), userAgentOf(extra)) === "chatgpt")
451
+ if (dialectOf(at.clientOf(meta, identified), userAgentOf(req)) === "chatgpt")
448
452
  return { native: true, conversation: null };
449
- const caps = at.server.server.getClientCapabilities();
453
+ const caps = at.host.clientCapabilities();
450
454
  if (hasKey(caps?.extensions, EXTENSION_KEY))
451
455
  return { native: true, conversation: null };
452
456
  const metaCaps = meta["io.modelcontextprotocol/clientCapabilities"];
@@ -457,7 +461,9 @@ export function nativeOf(at, extra, identified) {
457
461
  /**
458
462
  * Wakeshift attached to an MCP server: the handle `wake.attach` returns.
459
463
  * Wrap a tool's callback with events, and give its input schema
460
- * Wakeshift's three arguments with inputs.
464
+ * Wakeshift's three arguments with inputs. C is your MCP SDK's request
465
+ * context (2.x's ctx, 1.x's extra), which a wrapped call carries as
466
+ * `call.extra`.
461
467
  */
462
468
  export class Attached {
463
469
  at;
@@ -467,29 +473,33 @@ export class Attached {
467
473
  constructor(at) {
468
474
  this.at = at;
469
475
  }
470
- /**
471
- * shape plus Wakeshift's three optional arguments (session_key, harness
472
- * and conversation_id), for a wrapped tool's inputSchema:
473
- * `inputSchema: attached.inputs({ table: z.string() })`.
474
- */
475
476
  inputs(shape) {
477
+ if (isSchema(shape)) {
478
+ const own = getObjectShape(shape);
479
+ if (!own)
480
+ throw new Error("wakeshift: attached.inputs takes a zod object or a shape");
481
+ for (const k of WAKE_KEYS)
482
+ if (k in own)
483
+ throw new Error(`wakeshift: attached.inputs adds ${k} itself: leave it out of the schema`);
484
+ return withFields(shape, byVersion[isZ4Schema(shape) ? "v4" : "v3"].inputs);
485
+ }
476
486
  for (const k of WAKE_KEYS)
477
487
  if (k in (shape ?? {}))
478
488
  throw new Error(`wakeshift: attached.inputs adds ${k} itself: leave it out of the shape`);
479
- return { ...shape, ...fieldsFor(shape, "inputs") };
489
+ return { ...shape, ...fieldsFor(shape, "inputs", this.at.host) };
480
490
  }
481
- /**
482
- * shape plus an optional wakeshift string, for a wrapped tool's
483
- * outputSchema. Optional: every structured result of a wrapped tool gets
484
- * the block's text (without the beacon line) in wakeshift, for hosts that
485
- * show the model only structuredContent, and tools/list names it in the
486
- * tool's output schema; this declares it in your own schema and types.
487
- * The block stays in the content too.
488
- */
489
491
  output(shape) {
492
+ if (isSchema(shape)) {
493
+ const own = getObjectShape(shape);
494
+ if (!own)
495
+ throw new Error("wakeshift: attached.output takes a zod object or a shape");
496
+ if (WAKESHIFT_FIELD in own)
497
+ throw new Error("wakeshift: attached.output adds wakeshift itself: leave it out of the schema");
498
+ return withFields(shape, byVersion[isZ4Schema(shape) ? "v4" : "v3"].output);
499
+ }
490
500
  if ("wakeshift" in (shape ?? {}))
491
501
  throw new Error("wakeshift: attached.output adds wakeshift itself: leave it out of the shape");
492
- return { ...shape, ...fieldsFor(shape, "output") };
502
+ return { ...shape, ...fieldsFor(shape, "output", this.at.host) };
493
503
  }
494
504
  /**
495
505
  * Wraps a tool's callback, for `server.registerTool(name, …)` with the
@@ -509,7 +519,8 @@ export class Attached {
509
519
  return cb;
510
520
  }
511
521
  async run(name, cb, handler, input, extra) {
512
- const tool = registeredTool(this.at.server, name);
522
+ const host = this.at.host;
523
+ const tool = host.registeredTool(name);
513
524
  if (tool === undefined || (tool && (tool.handler ?? tool.callback) !== cb)) {
514
525
  throw new Error(`wakeshift: attached.events("${name}", …) isn't the tool named ${name} on the server passed to attach: register it with the same name, on that server`);
515
526
  }
@@ -547,7 +558,7 @@ export class Attached {
547
558
  await call.rollback();
548
559
  return result;
549
560
  }
550
- if ((typeof result === "object" && result.isError) || extra?.signal?.aborted || !(await validOutput(outputSchema, result))) {
561
+ if ((typeof result === "object" && result.isError) || host.req(extra).signal?.aborted || !(await host.validOutput(outputSchema, result))) {
551
562
  await call.rollback();
552
563
  return typeof result === "string" ? { content: [{ type: "text", text: result }] } : result;
553
564
  }
@@ -563,7 +574,7 @@ export class Attached {
563
574
  return { isError: true, content: [{ type: "text", text: `Wakeshift couldn't finish setting up this conversation's wakes (${detailOf(err)}). Try again.` }] };
564
575
  }
565
576
  const out = mergeBlock(result, add ?? {});
566
- if (out.structuredContent && WAKESHIFT_FIELD in out.structuredContent && !(await validOutput(outputSchema, out))) {
577
+ if (isRecord(out.structuredContent) && WAKESHIFT_FIELD in out.structuredContent && !(await host.validOutput(outputSchema, out))) {
567
578
  // A schema that refuses fields it doesn't name (a strict object):
568
579
  // MCP would refuse the result, so it goes without the field.
569
580
  const { [WAKESHIFT_FIELD]: _dropped, ...own } = out.structuredContent;
@@ -579,8 +590,8 @@ export class Attached {
579
590
  * attach, so a later set is wrapped too (as tasks.ts does).
580
591
  */
581
592
  amendToolsList() {
582
- const handlers = this.at.server.server._requestHandlers;
583
- if (!(handlers instanceof Map))
593
+ const handlers = this.at.host.handlers();
594
+ if (!handlers)
584
595
  return; // a future SDK: schemas stay as registered
585
596
  const wrap = (h) => async (request, extra) => {
586
597
  const out = await h(request, extra);
@@ -605,16 +616,4 @@ export class Attached {
605
616
  }
606
617
  }
607
618
  }
608
- // validOutput mirrors McpServer's own check of a result against the tool's
609
- // outputSchema (validateToolOutput): one it would refuse fails the call.
610
- async function validOutput(outputSchema, result) {
611
- if (!outputSchema)
612
- return true;
613
- if (typeof result === "string" || !result.structuredContent)
614
- return false;
615
- const obj = normalizeObjectSchema(outputSchema);
616
- if (!obj)
617
- return true;
618
- return (await safeParseAsync(obj, result.structuredContent)).success;
619
- }
620
619
  //# sourceMappingURL=toolcall.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"toolcall.js","sourceRoot":"","sources":["../src/toolcall.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,yEAAyE;AACzE,wEAAwE;AACxE,2EAA2E;AAC3E,2EAA2E;AAC3E,4EAA4E;AAC5E,yEAAyE;AACzE,yDAAyD;AACzD,EAAE;AACF,6FAA6F;AAC7F,gCAAgC;AAChC,iFAAiF;AACjF,2DAA2D;AAC3D,6FAA6F;AAC7F,qDAAqD;AACrD,4CAA4C;AAC5C,UAAU;AAEV,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAI7B,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,qBAAqB,EAAE,cAAc,EAA8E,MAAM,gDAAgD,CAAC;AAC/M,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,EAAE,QAAQ,EAA6D,MAAM,gBAAgB,CAAC;AAErG,2EAA2E;AAC3E,6DAA6D;AAC7D,MAAM,WAAW,GAAG,aAAa,CAAC;AAClC,MAAM,WAAW,GAAG,SAAS,CAAC;AAC9B,MAAM,gBAAgB,GAAG,iBAAiB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C1E,MAAM,GAAG,GAAG,qBAAqB,CAAC,YAAY,CAAC,CAAC;IAChD,IAAI,CAAC,GAAG;QAAE,OAAO,IAAI,CAAC;IACtB,OAAO,CAAC,MAAM,cAAc,CAAC,GAAG,EAAE,MAAM,CAAC,iBAAiB,CAAC,CAAC,CAAC,OAAO,CAAC;AACvE,CAAC","sourcesContent":["// One way to subscribe from a tool (docs/subscribe-from-tools.md): a tool\n// callback wrapped by the handle attach returns (attached.events) gets a\n// ToolCall, and subscribes the calling conversation with call.subscribe\n// (ends it with call.unsubscribe). The wrapper adds one Wakeshift block to\n// whatever the handler returns, so a conversation can't be left unwakeable\n// by a forgotten argument, a wrong tool name or an unreturned result; and a\n// call that fails ends the subscriptions it made. A port of the Go SDK's\n// appkit.Events (pkg/appkit/toolcall.go, attachcall.go).\n//\n// const attached = wake.attach(server, { identify: (extra) => ({ user: userOf(extra) }) })\n// server.registerTool(\"join\",\n// { description: \"…\", inputSchema: attached.inputs({ table: z.string() }) },\n// attached.events(\"join\", async ({ table }, call) => {\n// const sub = await call.subscribe(turn, { table }, { reason: `Playing at ${table}` })\n// await casino.seat(call.user!, table, sub.id)\n// return `You're seated at ${table}.`\n// }))\n\nimport { z } from \"zod\";\nimport * as z3 from \"zod/v3\";\nimport * as z4 from \"zod/v4\";\nimport type { CallToolResult, ServerNotification, ServerRequest } from \"@modelcontextprotocol/sdk/types.js\";\nimport type { McpServer, ToolCallback } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport { getObjectShape, isZ4Schema, normalizeObjectSchema, safeParseAsync, type AnySchema, type SchemaInput, type ShapeOutput, type ZodRawShapeCompat } from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport { WakeshiftError } from \"./errors.js\";\nimport { EXTENSION_KEY, dialectOf } from \"./spec.js\";\nimport { takesTasks } from \"./discover.js\";\nimport type { Identity, WakeEvent } from \"./events.js\";\nimport { packCall, type Call, type Duration, type Recognized, type Wakeshift } from \"./wakeshift.js\";\n\n// Wakeshift's three arguments (wakeshift.ts's SESSION_ARG, HARNESS_ARG and\n// CONVERSATION_ARG, repeated: that module imports this one).\nconst SESSION_ARG = \"session_key\";\nconst HARNESS_ARG = \"harness\";\nconst CONVERSATION_ARG = \"conversation_id\";\n\n/** MCP's own extra for a tool call: the request's signal, auth, _meta, HTTP request. */\nexport type ToolCallExtra = RequestHandlerExtra<ServerRequest, ServerNotification>;\n\n// What the agent is told each of Wakeshift's arguments is: the Go SDK's\n// WakeArgs, word for word.\nconst SESSION_KEY_DESCRIPTION =\n \"This conversation's session_key, from an earlier result (a secret token, or a handle such as claude-code#2). Keep it to this conversation; don't share or log it.\";\nconst HARNESS_DESCRIPTION =\n \"The program you're running in: codex, claude-code, cursor (local CLI or IDE), cursor-cloud (Cursor cloud agent), grok-bot, copilot-cli, opencode, antigravity, openclaw (even when it runs your turns in Codex), hermes, chatgpt, or your program's name if it isn't listed\";\nconst CONVERSATION_DESCRIPTION =\n \"Your own ID for this conversation, if your program gives you one. Cursor and Grok Bot: the output of `printenv CURSOR_CONVERSATION_ID`. Codex and Antigravity send it automatically; others leave it empty\";\nconst WAKESHIFT_OUTPUT_DESCRIPTION = \"What Wakeshift adds for this conversation: how it's woken by this app's events\";\n/** @internal Wakeshift's three arguments' descriptions, for a tool whose input schema is written out (the wait tool, tasks.ts). */\nexport const WAKE_ARG_DESCRIPTIONS = { session_key: SESSION_KEY_DESCRIPTION, harness: HARNESS_DESCRIPTION, conversation_id: CONVERSATION_DESCRIPTION } as const;\n\nconst wakeInputs = {\n [SESSION_ARG]: z.string().optional().describe(SESSION_KEY_DESCRIPTION),\n [HARNESS_ARG]: z.string().optional().describe(HARNESS_DESCRIPTION),\n [CONVERSATION_ARG]: z.string().optional().describe(CONVERSATION_DESCRIPTION),\n};\n/** @internal Wakeshift's three arguments as attach's own tools take them: worded as a wrapped tool's (test/events-list.json pins it). */\nexport const toolArgs = wakeInputs;\nconst wakeOutput = { wakeshift: z.string().optional().describe(WAKESHIFT_OUTPUT_DESCRIPTION) };\n\n// The same in each of zod's two APIs: MCP refuses a shape that mixes them,\n// so a shape written with zod/v3 (or zod/v4) gets Wakeshift's fields in its\n// own (zod 3.25 and later carry both).\nconst byVersion = {\n v3: {\n inputs: {\n [SESSION_ARG]: z3.string().optional().describe(SESSION_KEY_DESCRIPTION),\n [HARNESS_ARG]: z3.string().optional().describe(HARNESS_DESCRIPTION),\n [CONVERSATION_ARG]: z3.string().optional().describe(CONVERSATION_DESCRIPTION),\n },\n output: { wakeshift: z3.string().optional().describe(WAKESHIFT_OUTPUT_DESCRIPTION) },\n },\n v4: {\n inputs: {\n [SESSION_ARG]: z4.string().optional().describe(SESSION_KEY_DESCRIPTION),\n [HARNESS_ARG]: z4.string().optional().describe(HARNESS_DESCRIPTION),\n [CONVERSATION_ARG]: z4.string().optional().describe(CONVERSATION_DESCRIPTION),\n },\n output: { wakeshift: z4.string().optional().describe(WAKESHIFT_OUTPUT_DESCRIPTION) },\n },\n};\n\n// fieldsFor is Wakeshift's fields in the zod API shape's own fields use\n// (the default import's for an empty shape).\nfunction fieldsFor<K extends \"inputs\" | \"output\">(shape: ZodRawShapeCompat, kind: K): K extends \"inputs\" ? WakeInputs : WakeOutputShape {\n const first = Object.values(shape ?? {})[0];\n const fields = !first ? (kind === \"inputs\" ? wakeInputs : wakeOutput) : byVersion[isZ4Schema(first) ? \"v4\" : \"v3\"][kind];\n return fields as any;\n}\n\n/** Wakeshift's three arguments, as attached.inputs adds them. */\nexport type WakeInputs = typeof wakeInputs;\n/** The optional wakeshift string attached.output adds. */\nexport type WakeOutputShape = typeof wakeOutput;\n/** The names of Wakeshift's three arguments. */\nexport type WakeKey = typeof SESSION_ARG | typeof HARNESS_ARG | typeof CONVERSATION_ARG;\n/** An input shape with Wakeshift's three arguments in it (attached.inputs'). */\nexport type WakeShape = ZodRawShapeCompat & { [K in WakeKey]: AnySchema };\n/** What a wrapped handler gets: the tool's own arguments, without Wakeshift's three. */\nexport type AppArgs<S extends ZodRawShapeCompat> = Omit<ShapeOutput<S>, WakeKey>;\n/** What a wrapped handler returns: a string (one text block) or a CallToolResult. */\nexport type WrappedResult = string | CallToolResult;\n\nconst WAKE_KEYS: readonly WakeKey[] = [SESSION_ARG, HARNESS_ARG, CONVERSATION_ARG];\n\n/**\n * @internal The tools/call _meta keys a harness names its conversation in\n * (the core's harnesses ConversationMeta, dotted for nested objects):\n * test/conversation-meta.json, which a Go test keeps current.\n */\nexport const CONVERSATION_META: readonly string[] = [\n \"agent-session-id\",\n \"antigravity.google/conversation_id\",\n \"vscode.conversationId\",\n \"wakeshift/conversation\",\n \"x-codex-turn-metadata.thread_id\",\n];\n\n/**\n * The calling conversation's subscription, made or renewed by\n * call.subscribe. id and user address it later: emit's\n * `to: [{ user, subscription: id }]`, or `event.end(user, id)`.\n */\nexport interface Subscription {\n id: string;\n user: string;\n /** False for a renewal. */\n created: boolean;\n /** The conversation's session. A secret: don't show, store or log it. */\n session: string;\n /** What Wakeshift recognized the agent's program as. */\n recognized: Recognized;\n /** The caller subscribes itself (call.native): nothing was made, id is \"\", and the block tells it what to subscribe to. */\n native: boolean;\n}\n\n/** How call.subscribe subscribes. */\nexport interface ToolSubscribeOptions {\n /** End after this long without a delivery or a fresh subscribe (default 30 days). */\n ttl?: Duration;\n /** Why the app subscribes the conversation, shown in the console (at most 200 characters). */\n reason?: string;\n /** Names a new session (agent@label), for an app acting for its agents. */\n label?: string;\n}\n\n/**\n * One call of a wrapped tool (attached.events): who's calling, and the\n * calls that subscribe the calling conversation. Only the wrapper makes\n * one, and it works until the handler returns (then CallEnded).\n */\nexport interface ToolCall {\n /** Who attach's identify says is calling (undefined for none). */\n readonly user: string | undefined;\n /** The tool being called. */\n readonly tool: string;\n /**\n * The client subscribes to the app's events itself (MCP Events: ChatGPT,\n * the house agents). call.subscribe then makes no conversation\n * subscription, and the block tells it what to subscribe to.\n */\n readonly native: boolean;\n /** A native client's conversation, when it names one (ChatGPT's _meta[\"openai/session\"]). */\n readonly nativeConversation: string | null;\n /** The session_key passed; after a subscribe or resolveSession, the conversation's session. */\n readonly session: string | null;\n /** What Wakeshift recognized the agent's program as: null until a subscribe or resolveSession. */\n readonly recognized: Recognized | null;\n /** MCP's own extra for the call. */\n readonly extra: ToolCallExtra;\n /**\n * Subscribes the calling conversation to event with args, or renews its\n * subscription. The reply then carries what the conversation needs to be\n * woken (one block for the call, however many subscribes it makes), and\n * if the call fails, the subscription is ended. For a native caller\n * nothing is made. Your tool decides who may: authorize isn't consulted.\n * A personal event needs a user (identify's).\n */\n subscribe<A extends AnySchema>(event: WakeEvent<A, any>, args: SchemaInput<A>, opts?: ToolSubscribeOptions): Promise<Subscription>;\n /**\n * Ends the calling conversation's subscription to event with args,\n * resolving to whether one ended. For a native caller it ends the user's\n * own (webhook) subscriptions to the event with those arguments.\n */\n unsubscribe<A extends AnySchema>(event: WakeEvent<A, any>, args: SchemaInput<A>): Promise<boolean>;\n /** Finds or starts the calling conversation's session without subscribing it (it doesn't make it wakeable). */\n resolveSession(): Promise<string>;\n}\n\n/** A ToolCall used after its handler returned. */\nexport class CallEnded extends Error {\n constructor() {\n super(\"wakeshift: the tool call has ended: subscribe before the handler returns\");\n this.name = \"CallEnded\";\n }\n}\n\n/** attach's event options. */\nexport interface EventsOptions {\n /**\n * Asked first whether a wrapped tool's call comes from a client that\n * subscribes to the app's events itself (call.native), for callers the\n * SDK can't tell (an app's own house agents). False leaves it to the\n * SDK's own checks.\n */\n native?: (extra: ToolCallExtra) => boolean;\n}\n\n// The line a text-carried beacon is on (the core's beacon.Text), which a\n// harness's hook reads only as the last line of a result's text.\nconst BEACON_LINE_PREFIX = \"(For Wakeshift's hook on this computer, not for you: wakeshift-beacon: \";\nconst CONNECTOR_META_KEY = \"wakeshift/connector\";\n// The most native lines Wakeshift takes for one call.\nconst MAX_NATIVE_LINES = 20;\n\n/** /calls/addition's answer. */\nexport interface CallAddition {\n text?: string;\n trailer?: string;\n meta?: Record<string, unknown>;\n}\n\ntype Content = CallToolResult[\"content\"][number];\n\n// takeTrailer takes a beacon line off the end of the result's text\n// (dropping its block if nothing else is in it), returning it (\"\" if\n// there's none).\nfunction takeTrailer(content: Content[]): string {\n const last = content.at(-1);\n if (!last || last.type !== \"text\") return \"\";\n const text = last.text.replace(/[ \\t\\r\\n]+$/, \"\");\n const i = text.lastIndexOf(\"\\n\");\n const line = i >= 0 ? text.slice(i + 1) : text;\n if (!line.startsWith(BEACON_LINE_PREFIX) || !line.endsWith(\")\")) return \"\";\n const rest = i >= 0 ? text.slice(0, i).replace(/[ \\t\\r\\n]+$/, \"\") : \"\";\n if (rest === \"\") content.pop();\n else content[content.length - 1] = { ...last, text: rest };\n return line;\n}\n\n/** The structuredContent field a wrapped tool's structured result carries Wakeshift's block in (the same in every SDK). */\nexport const WAKESHIFT_FIELD = \"wakeshift\";\n\n/**\n * @internal An object output schema (JSON Schema, as tools/list gives it)\n * with an optional wakeshift string added, as a copy, so a client that\n * checks structuredContent against it takes the block. Anything else, or a\n * schema that already names it, comes back as it was.\n * test/wrapped-block.json (output_schemas) pins it.\n */\nexport function withWakeshiftField(schema: unknown): unknown {\n if (!schema || typeof schema !== \"object\" || Array.isArray(schema)) return schema;\n const s = schema as Record<string, unknown>;\n if (s.type !== \"object\") return schema;\n const props = s.properties;\n if (props !== undefined && (!props || typeof props !== \"object\" || Array.isArray(props))) return schema;\n if (props && WAKESHIFT_FIELD in (props as object)) return schema;\n return { ...s, properties: { ...((props as object) ?? {}), [WAKESHIFT_FIELD]: { type: \"string\", description: WAKESHIFT_OUTPUT_DESCRIPTION } } };\n}\n\n/**\n * @internal Adds the call's block to a wrapped handler's result: Wakeshift's\n * text as a block after the app's content, then a text-carried beacon last,\n * and _meta; a string result stays one text block. A result that already\n * carries a beacon keeps it, last, and gets no second one. A structured\n * result (structuredContent an object) gets the block's text in its\n * wakeshift field too. test/wrapped-block.json is the shape, shared with\n * the other SDKs.\n */\nexport function mergeBlock(result: WrappedResult, add: CallAddition): CallToolResult {\n const isString = typeof result === \"string\";\n const base: CallToolResult = isString ? { content: [{ type: \"text\", text: result }] } : result;\n const out: CallToolResult = { ...base, content: [...(base.content ?? [])] };\n const text = (add.text ?? \"\").trim();\n const metaBeacon = !!out._meta && CONNECTOR_META_KEY in out._meta;\n const existing = takeTrailer(out.content);\n if (text) out.content.push({ type: \"text\", text });\n const has = metaBeacon || existing !== \"\";\n if (existing) out.content.push({ type: \"text\", text: existing });\n else if (!has && add.trailer) out.content.push({ type: \"text\", text: add.trailer });\n for (const [k, v] of Object.entries(add.meta ?? {})) {\n if (k === CONNECTOR_META_KEY && has) continue;\n out._meta = { ...(out._meta ?? {}), [k]: v };\n }\n if (isString) {\n const texts = out.content.map((c) => (c.type === \"text\" ? c.text : \"\")).filter((t) => t !== \"\");\n out.content = [{ type: \"text\", text: texts.join(\"\\n\\n\") }];\n }\n if (text && out.structuredContent && typeof out.structuredContent === \"object\" && !Array.isArray(out.structuredContent)) {\n out.structuredContent = { ...out.structuredContent, [WAKESHIFT_FIELD]: text };\n }\n return out;\n}\n\n// metaString is the string at key in a tool call's _meta: the key itself,\n// else a dotted path into nested objects (the core's harnesses.metaString).\nfunction metaString(meta: Record<string, unknown> | undefined, key: string): string {\n if (!meta) return \"\";\n const limit = (s: unknown) => (typeof s === \"string\" && s.length <= 200 ? s : \"\");\n if (typeof meta[key] === \"string\") return limit(meta[key]);\n let cur: unknown = meta;\n for (const part of key.split(\".\")) {\n if (!cur || typeof cur !== \"object\" || Array.isArray(cur)) return \"\";\n cur = (cur as Record<string, unknown>)[part];\n }\n return limit(cur);\n}\n\n/** @internal Whether a tool call's _meta names its conversation, the way a harness puts it there (test/conversation-meta.json). */\nexport function namesConversation(meta: Record<string, unknown> | undefined): boolean {\n return CONVERSATION_META.some((k) => metaString(meta, k) !== \"\");\n}\n\nfunction sameJSON(a: unknown, b: unknown): boolean {\n const norm = (v: unknown): unknown =>\n v === null || v === undefined\n ? {}\n : Array.isArray(v)\n ? v.map(norm)\n : typeof v === \"object\"\n ? Object.fromEntries(Object.keys(v as object).sort().map((k) => [k, norm((v as Record<string, unknown>)[k])]))\n : v;\n return JSON.stringify(norm(a)) === JSON.stringify(norm(b));\n}\n\nfunction detailOf(err: unknown): string {\n return err instanceof WakeshiftError ? err.detail : String((err as Error)?.message ?? err);\n}\n\n// The parts of an McpServer the wrapper reads that aren't public: its\n// registered tools (the handler, input and output schemas). A unit test pins\n// them against the supported MCP SDK versions.\ninterface RegisteredToolInternal {\n inputSchema?: AnySchema;\n outputSchema?: AnySchema;\n handler?: unknown;\n callback?: unknown;\n}\n\nfunction registeredTool(server: McpServer, name: string): RegisteredToolInternal | undefined | null {\n const tools = (server as unknown as { _registeredTools?: Record<string, RegisteredToolInternal> })._registeredTools;\n if (!tools || typeof tools !== \"object\") return null; // an MCP SDK that keeps them elsewhere\n return tools[name];\n}\n\ninterface CreatedSub {\n name: string;\n arguments: unknown;\n session: string;\n pending: string; // the call's pending-addition record, which made it\n}\n\ninterface NativeLine {\n name: string;\n arguments: unknown;\n}\n\n/** @internal What the wrapper needs of attach: the client, the server, who's calling, the event options. */\nexport interface AttachContext {\n wake: Wakeshift;\n server: McpServer;\n /** Who attach's identify says is calling: its user and client. */\n identify(extra: ToolCallExtra): Identity | undefined;\n /** The client's name: the request's (initialize's, else _meta's), else identified (identify's), else \"\". */\n clientOf(meta: Record<string, unknown> | undefined, identified?: string): string;\n events: EventsOptions;\n warnOnce(key: string, message: string): void;\n}\n\n/** One tools/call of a wrapped tool: what its handler subscribed, for the block and the rollback. */\nclass CallScope implements ToolCall {\n user: string | undefined;\n tool: string;\n native = false;\n nativeConversation: string | null = null;\n session: string | null;\n recognized: Recognized | null = null;\n extra: ToolCallExtra;\n\n ended = false;\n pending = \"\";\n armed = false;\n created: CreatedSub[] = [];\n nativeLines: NativeLine[] = [];\n inflight = new Set<Promise<unknown>>();\n private queue: Promise<unknown> = Promise.resolve();\n // The client's name identify gave, for a request that names none.\n private readonly identified: string | undefined;\n\n constructor(\n private readonly at: AttachContext,\n tool: string,\n extra: ToolCallExtra,\n private readonly args: { session?: string; harness?: string; conversation?: string },\n ) {\n this.tool = tool;\n this.extra = extra;\n const id = at.identify(extra);\n this.user = id?.user;\n this.identified = id?.client;\n this.session = args.session || null;\n const n = nativeOf(at, extra, this.identified);\n this.native = n.native;\n this.nativeConversation = n.conversation;\n }\n\n // wire is the call as Wakeshift takes it: the request's client, _meta and\n // User-Agent, the agent's harness and conversation_id arguments, the\n // conversation's session, and who's calling.\n wire(session = this.session): Call {\n const meta = this.extra._meta as Record<string, unknown> | undefined;\n return packCall({\n meta,\n clientName: this.at.clientOf(meta, this.identified),\n user: this.user,\n session: session ?? undefined,\n userAgent: userAgentOf(this.extra),\n harness: this.args.harness,\n conversation: this.args.conversation,\n tool: this.tool,\n tasks: takesTasks(meta, this.extra),\n });\n }\n\n // request runs one request of the call to Wakeshift, after any before it\n // (one at a time per call), refusing once the handler has returned.\n private request<T>(fn: () => Promise<T>): Promise<T> {\n if (this.ended) return Promise.reject(new CallEnded());\n const run = this.queue.then(() => (this.ended ? Promise.reject(new CallEnded()) : fn()));\n this.queue = run.catch(() => undefined);\n this.inflight.add(run);\n run.then(\n () => this.inflight.delete(run),\n () => this.inflight.delete(run),\n );\n return run;\n }\n\n private checkEvent(event: WakeEvent<any, any>): void {\n if (!event || typeof event.owner !== \"function\" || event.owner() !== this.at.wake) {\n throw new WakeshiftError(404, \"unknown_event\", `${event?.name ?? \"that\"} is another app's event: this app doesn't offer it`);\n }\n }\n\n subscribe<A extends AnySchema>(event: WakeEvent<A, any>, args: SchemaInput<A>, opts: ToolSubscribeOptions = {}): Promise<Subscription> {\n return this.request(async () => {\n this.checkEvent(event);\n const known = event.parseArgs(args);\n if (this.native) {\n this.addNative(event.name, known);\n return { id: \"\", user: this.user ?? \"\", created: false, session: \"\", recognized: { harness: null, via: null, claimed: null }, native: true };\n }\n if (event.personal && !this.user) {\n throw new WakeshiftError(400, \"bad_arguments\", `${event.name} is personal: call.subscribe needs a user (attach's identify), who the subscription belongs to`);\n }\n const body: Record<string, unknown> = { call: this.wire(), name: event.name, arguments: known, defer_addition: true };\n if (this.pending) body.pending = this.pending;\n if (opts.ttl !== undefined) body.ttl = opts.ttl;\n if (opts.reason) body.reason = opts.reason;\n if (opts.label) body.label = opts.label;\n const out = await this.at.wake.requestApp<{\n event_subscription: { id: string; user?: string; created: boolean };\n session: string;\n agent?: Partial<Recognized>;\n pending?: string;\n }>(\"POST\", \"/event-subscriptions\", body);\n if (out.pending) this.pending = out.pending;\n this.armed = true;\n this.session = out.session;\n const rec = recognizedOf(out.agent);\n this.recognized = rec;\n const es = out.event_subscription;\n if (es.created) this.created.push({ name: event.name, arguments: known, session: out.session, pending: out.pending ?? this.pending });\n return { id: es.id, user: es.user ?? this.user ?? \"\", created: !!es.created, session: out.session, recognized: rec, native: false };\n });\n }\n\n unsubscribe<A extends AnySchema>(event: WakeEvent<A, any>, args: SchemaInput<A>): Promise<boolean> {\n return this.request(async () => {\n this.checkEvent(event);\n const known = event.parseArgs(args);\n if (this.native) return this.endNative(event.name, known);\n const out = await this.at.wake.requestApp<{ ended?: boolean }>(\"POST\", \"/event-subscriptions/unsubscribe\", { call: this.wire(), name: event.name, arguments: known });\n return !!out.ended;\n });\n }\n\n resolveSession(): Promise<string> {\n return this.request(async () => {\n if (this.pending && this.session) return this.session;\n const out = await this.at.wake.requestApp<{ session: string; pending: string; agent?: Partial<Recognized> }>(\"POST\", \"/calls/session\", { call: this.wire() });\n this.pending = out.pending;\n this.session = out.session;\n this.recognized = recognizedOf(out.agent);\n return out.session;\n });\n }\n\n // endNative ends the user's webhook subscriptions to event with these arguments.\n private async endNative(name: string, args: unknown): Promise<boolean> {\n if (!this.user) return false;\n const out = await this.at.wake.requestApp<{ subscriptions?: { id: string; event: string; arguments: unknown; destination: string }[] }>(\"POST\", \"/event-subscriptions/list\", {\n user: this.user,\n });\n let ended = false;\n for (const s of out.subscriptions ?? []) {\n if (s.event !== name || s.destination !== \"webhook\" || !sameJSON(s.arguments, args)) continue;\n const r = await this.at.wake.requestApp<{ ended?: boolean }>(\"POST\", \"/event-subscriptions/end\", { user: this.user, id: s.id });\n ended = ended || !!r.ended;\n }\n return ended;\n }\n\n // addNative adds a native line, once per event and arguments.\n private addNative(name: string, args: unknown): void {\n if (this.nativeLines.some((l) => l.name === name && sameJSON(l.arguments, args))) return;\n if (this.nativeLines.length === MAX_NATIVE_LINES) {\n this.at.warnOnce(\n \"native:\" + this.tool,\n `wakeshift: the wrapped tool ${this.tool} subscribed a native client to more than ${MAX_NATIVE_LINES} events in one call; only ${MAX_NATIVE_LINES} are named`,\n );\n return;\n }\n this.nativeLines.push({ name, arguments: args });\n }\n\n // end closes the call to further requests, after waiting for any in\n // flight (warning once per tool: the handler should have waited for them).\n async end(): Promise<void> {\n if (this.inflight.size > 0) {\n this.at.warnOnce(\n \"inflight:\" + this.tool,\n `wakeshift: the wrapped tool ${this.tool} returned while a subscribe was in flight; it was waited for: await call.subscribe, call.unsubscribe and call.resolveSession before returning`,\n );\n await Promise.allSettled([...this.inflight]);\n }\n this.ended = true;\n }\n\n // rollback ends every subscription the call created and no other call\n // has renewed since (the core checks the pending record that made it),\n // with reason rolled_back (audited as such, no \"ended\" notice), whatever\n // became of the request.\n async rollback(): Promise<void> {\n for (const c of this.created) {\n try {\n await this.at.wake.requestApp(\"POST\", \"/event-subscriptions/unsubscribe\", { call: this.wire(c.session), name: c.name, arguments: c.arguments, reason: \"rolled_back\", pending: c.pending });\n } catch (err) {\n this.at.wake.warn(`wakeshift: rolling back a failed tool call's subscription (${this.tool}, ${c.name}): ${detailOf(err)}`);\n }\n }\n this.created = [];\n }\n\n // addition asks Wakeshift for the call's block: what the conversation\n // needs to be woken (from the call's pending-addition record, if a\n // subscribe or resolveSession made one; otherwise what any other tool\n // result of the app's carries), and a line per event a native caller\n // should subscribe to. A call that names no conversation, and subscribed\n // nothing, gets nothing (null). Only a failure for a call that subscribed\n // is thrown: without a subscription, the block is a courtesy.\n async addition(): Promise<CallAddition | null> {\n const wire = this.wire();\n if (!this.pending && this.nativeLines.length === 0 && !wire.session && !wire.conversation && !namesConversation(wire.meta)) return null;\n const body: Record<string, unknown> = { call: wire };\n if (this.pending) body.pending = this.pending;\n if (this.nativeLines.length > 0) body.native = this.nativeLines;\n try {\n return await this.at.wake.requestApp<CallAddition>(\"POST\", \"/calls/addition\", body);\n } catch (err) {\n if (this.armed || this.nativeLines.length > 0) throw err;\n this.at.wake.warn(`wakeshift: Wakeshift's addition to a result of ${this.tool}: ${detailOf(err)}`);\n return null;\n }\n }\n}\n\nfunction recognizedOf(a: Partial<Recognized> | undefined): Recognized {\n return { harness: a?.harness ?? null, via: a?.via ?? null, claimed: a?.claimed ?? null };\n}\n\nfunction headerOf(extra: ToolCallExtra, name: string): string {\n const h = extra?.requestInfo?.headers as Record<string, string | string[] | undefined> | undefined;\n if (!h) return \"\";\n const v = h[name] ?? h[name.toLowerCase()];\n return (Array.isArray(v) ? v[0] : v) ?? \"\";\n}\n\nfunction userAgentOf(extra: ToolCallExtra): string {\n return headerOf(extra, \"user-agent\") || headerOf(extra, \"User-Agent\");\n}\n\nfunction hasKey(o: unknown, key: string): boolean {\n return !!o && typeof o === \"object\" && !Array.isArray(o) && (o as Record<string, unknown>)[key] !== undefined;\n}\n\n/**\n * @internal Whether a call comes from a client that subscribes to the app's\n * events itself, on stateless servers too (which never see initialize), in\n * this order: the app's override (events.native); ChatGPT's\n * _meta[\"openai/session\"]; a client name (initialize's, or _meta's, else\n * identify's) or User-Agent of a known native client; a client that\n * declares the MCP Events extension (initialize's capabilities, or\n * _meta's). conversation is ChatGPT's conversation, when it names one.\n */\nexport function nativeOf(\n at: Pick<AttachContext, \"server\" | \"clientOf\" | \"events\">,\n extra: ToolCallExtra,\n identified?: string,\n): { native: boolean; conversation: string | null } {\n const meta = (extra._meta ?? {}) as Record<string, unknown>;\n const conversation = typeof meta[\"openai/session\"] === \"string\" && meta[\"openai/session\"] ? (meta[\"openai/session\"] as string) : null;\n if (at.events.native?.(extra)) return { native: true, conversation };\n if (conversation) return { native: true, conversation };\n if (dialectOf(at.clientOf(meta, identified), userAgentOf(extra)) === \"chatgpt\") return { native: true, conversation: null };\n const caps = at.server.server.getClientCapabilities() as Record<string, unknown> | undefined;\n if (hasKey(caps?.extensions, EXTENSION_KEY)) return { native: true, conversation: null };\n const metaCaps = meta[\"io.modelcontextprotocol/clientCapabilities\"] as Record<string, unknown> | undefined;\n if (hasKey(metaCaps?.extensions, EXTENSION_KEY)) return { native: true, conversation: null };\n return { native: false, conversation: null };\n}\n\n/**\n * Wakeshift attached to an MCP server: the handle `wake.attach` returns.\n * Wrap a tool's callback with events, and give its input schema\n * Wakeshift's three arguments with inputs.\n */\nexport class Attached {\n /** @internal */\n private readonly wrapped = new Map<string, unknown>();\n\n /** @internal Use wake.attach. */\n constructor(private readonly at: AttachContext) {}\n\n /**\n * shape plus Wakeshift's three optional arguments (session_key, harness\n * and conversation_id), for a wrapped tool's inputSchema:\n * `inputSchema: attached.inputs({ table: z.string() })`.\n */\n inputs<S extends ZodRawShapeCompat>(shape: S): S & WakeInputs {\n for (const k of WAKE_KEYS) if (k in (shape ?? {})) throw new Error(`wakeshift: attached.inputs adds ${k} itself: leave it out of the shape`);\n return { ...shape, ...fieldsFor(shape, \"inputs\") };\n }\n\n /**\n * shape plus an optional wakeshift string, for a wrapped tool's\n * outputSchema. Optional: every structured result of a wrapped tool gets\n * the block's text (without the beacon line) in wakeshift, for hosts that\n * show the model only structuredContent, and tools/list names it in the\n * tool's output schema; this declares it in your own schema and types.\n * The block stays in the content too.\n */\n output<S extends ZodRawShapeCompat>(shape: S): S & WakeOutputShape {\n if (\"wakeshift\" in (shape ?? {})) throw new Error(\"wakeshift: attached.output adds wakeshift itself: leave it out of the shape\");\n return { ...shape, ...fieldsFor(shape, \"output\") };\n }\n\n /**\n * Wraps a tool's callback, for `server.registerTool(name, …)` with the\n * same name (MCP doesn't tell a callback its tool's name): the handler\n * gets the tool's own arguments and a ToolCall, and returns a string or\n * a CallToolResult; the reply gets Wakeshift's block. The tool's\n * inputSchema must come from attached.inputs (a type error otherwise).\n * Register it on the server passed to attach.\n */\n events<S extends WakeShape>(name: string, handler: (args: AppArgs<S>, call: ToolCall) => WrappedResult | Promise<WrappedResult>): ToolCallback<S> {\n if (!name || typeof name !== \"string\") throw new Error(\"wakeshift: attached.events needs the tool's name, as registered\");\n if (typeof handler !== \"function\") throw new Error(\"wakeshift: attached.events needs a handler\");\n const cb = (async (args: Record<string, unknown>, extra: ToolCallExtra) => this.run(name, cb, handler as any, args ?? {}, extra)) as unknown as ToolCallback<S>;\n this.wrapped.set(name, cb);\n return cb;\n }\n\n private async run(\n name: string,\n cb: unknown,\n handler: (args: Record<string, unknown>, call: ToolCall) => WrappedResult | Promise<WrappedResult>,\n input: Record<string, unknown>,\n extra: ToolCallExtra,\n ): Promise<CallToolResult> {\n const tool = registeredTool(this.at.server, name);\n if (tool === undefined || (tool && (tool.handler ?? tool.callback) !== cb)) {\n throw new Error(`wakeshift: attached.events(\"${name}\", …) isn't the tool named ${name} on the server passed to attach: register it with the same name, on that server`);\n }\n let outputSchema: AnySchema | undefined;\n if (tool) {\n const shape = getObjectShape(normalizeObjectSchema(tool.inputSchema));\n if (!shape || WAKE_KEYS.some((k) => !(k in shape))) {\n throw new Error(`wakeshift: the tool ${name} doesn't take Wakeshift's arguments: make its inputSchema with attached.inputs(…)`);\n }\n outputSchema = tool.outputSchema;\n } else {\n this.at.warnOnce(\"internals\", \"wakeshift: this MCP SDK keeps its tools where Wakeshift can't read them, so wrapped tools' registration and output aren't checked\");\n }\n const str = (k: string) => (typeof input[k] === \"string\" && (input[k] as string) ? (input[k] as string) : undefined);\n const call = new CallScope(this.at, name, extra, { session: str(SESSION_ARG), harness: str(HARNESS_ARG), conversation: str(CONVERSATION_ARG) });\n const appArgs: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(input)) if (!(WAKE_KEYS as readonly string[]).includes(k)) appArgs[k] = v;\n\n let result: WrappedResult;\n try {\n result = await handler(appArgs, call);\n } catch (err) {\n await call.end();\n await call.rollback();\n throw err;\n }\n await call.end();\n // Rollback is decided from the final result, the one the client would\n // receive: MCP validates the output after this callback returns, so\n // the wrapper checks it the same way first.\n if (result === null || result === undefined || (typeof result !== \"string\" && typeof result !== \"object\")) {\n await call.rollback();\n return result as unknown as CallToolResult;\n }\n if ((typeof result === \"object\" && result.isError) || extra?.signal?.aborted || !(await validOutput(outputSchema, result))) {\n await call.rollback();\n return typeof result === \"string\" ? { content: [{ type: \"text\", text: result }] } : result;\n }\n let add: CallAddition | null;\n try {\n add = await call.addition();\n } catch (err) {\n // The conversation is subscribed but wouldn't learn how it's woken:\n // the call fails, as one whose handler failed does.\n await call.rollback();\n this.at.wake.warn(`wakeshift: Wakeshift's block for a result of ${name} failed, so the call's subscriptions were rolled back: ${detailOf(err)}`);\n return { isError: true, content: [{ type: \"text\", text: `Wakeshift couldn't finish setting up this conversation's wakes (${detailOf(err)}). Try again.` }] };\n }\n const out = mergeBlock(result, add ?? {});\n if (out.structuredContent && WAKESHIFT_FIELD in out.structuredContent && !(await validOutput(outputSchema, out))) {\n // A schema that refuses fields it doesn't name (a strict object):\n // MCP would refuse the result, so it goes without the field.\n const { [WAKESHIFT_FIELD]: _dropped, ...own } = out.structuredContent;\n out.structuredContent = own;\n this.at.warnOnce(\n \"output:\" + name,\n `wakeshift: the wrapped tool ${name}'s outputSchema refuses a wakeshift field, so hosts that show only structuredContent won't see how this conversation is woken: make it with attached.output`,\n );\n }\n return out;\n }\n\n /**\n * @internal Wraps the server's tools/list handler so each wrapped tool's\n * object output schema names wakeshift (withWakeshiftField). McpServer\n * sets the handler when the first tool is registered, perhaps after\n * attach, so a later set is wrapped too (as tasks.ts does).\n */\n amendToolsList(): void {\n type Handler = (request: any, extra: any) => Promise<any>;\n const handlers = (this.at.server.server as any)._requestHandlers as Map<string, Handler> | undefined;\n if (!(handlers instanceof Map)) return; // a future SDK: schemas stay as registered\n const wrap =\n (h: Handler): Handler =>\n async (request, extra) => {\n const out = await h(request, extra);\n if (out && Array.isArray(out.tools)) this.amendTools(out.tools);\n return out;\n };\n const h = handlers.get(\"tools/list\");\n if (h) Map.prototype.set.call(handlers, \"tools/list\", wrap(h));\n const set = handlers.set.bind(handlers);\n handlers.set = (method: string, h: Handler) => set(method, method === \"tools/list\" ? wrap(h) : h);\n }\n\n private amendTools(tools: unknown[]): void {\n for (let i = 0; i < tools.length; i++) {\n const t = tools[i] as { name?: unknown; outputSchema?: unknown } | null;\n if (!t || typeof t !== \"object\" || typeof t.name !== \"string\" || !this.wrapped.has(t.name) || !t.outputSchema) continue;\n const schema = withWakeshiftField(t.outputSchema);\n if (schema !== t.outputSchema) tools[i] = { ...t, outputSchema: schema };\n }\n }\n}\n\n// validOutput mirrors McpServer's own check of a result against the tool's\n// outputSchema (validateToolOutput): one it would refuse fails the call.\nasync function validOutput(outputSchema: AnySchema | undefined, result: WrappedResult): Promise<boolean> {\n if (!outputSchema) return true;\n if (typeof result === \"string\" || !result.structuredContent) return false;\n const obj = normalizeObjectSchema(outputSchema);\n if (!obj) return true;\n return (await safeParseAsync(obj, result.structuredContent)).success;\n}\n"]}
1
+ {"version":3,"file":"toolcall.js","sourceRoot":"","sources":["../src/toolcall.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,yEAAyE;AACzE,wEAAwE;AACxE,2EAA2E;AAC3E,2EAA2E;AAC3E,4EAA4E;AAC5E,yEAAyE;AACzE,yDAAyD;AACzD,EAAE;AACF,6FAA6F;AAC7F,gCAAgC;AAChC,iFAAiF;AACjF,2DAA2D;AAC3D,6FAA6F;AAC7F,qDAAqD;AACrD,4CAA4C;AAC5C,UAAU;AAEV,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7B,OAA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AAC,CAAC,YAAY,CAAC,CAAC;YAClD,IAAI,MAAM,KAAK,CAAC,CAAC,YAAY;gBAAE,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC;QAC3E,CAAC;IACH,CAAC;CACF","sourcesContent":["// One way to subscribe from a tool (docs/subscribe-from-tools.md): a tool\n// callback wrapped by the handle attach returns (attached.events) gets a\n// ToolCall, and subscribes the calling conversation with call.subscribe\n// (ends it with call.unsubscribe). The wrapper adds one Wakeshift block to\n// whatever the handler returns, so a conversation can't be left unwakeable\n// by a forgotten argument, a wrong tool name or an unreturned result; and a\n// call that fails ends the subscriptions it made. A port of the Go SDK's\n// appkit.Events (pkg/appkit/toolcall.go, attachcall.go).\n//\n// const attached = wake.attach(server, { identify: (extra) => ({ user: userOf(extra) }) })\n// server.registerTool(\"join\",\n// { description: \"…\", inputSchema: attached.inputs({ table: z.string() }) },\n// attached.events(\"join\", async ({ table }, call) => {\n// const sub = await call.subscribe(turn, { table }, { reason: `Playing at ${table}` })\n// await casino.seat(call.user!, table, sub.id)\n// return `You're seated at ${table}.`\n// }))\n\nimport { z } from \"zod\";\nimport * as z3 from \"zod/v3\";\nimport * as z4 from \"zod/v4\";\nimport * as z4mini from \"zod/v4-mini\";\nimport type { CallToolResult, ToolCallExtra } from \"./mcp.js\";\nimport { getObjectShape, isSchema, isZ4Schema, normalizeObjectSchema, type AnySchema, type SchemaInput, type ShapeOutput, type ZodRawShapeCompat } from \"./zod.js\";\nimport type { Host } from \"./host.js\";\nimport { WakeshiftError } from \"./errors.js\";\nimport { EXTENSION_KEY, dialectOf } from \"./spec.js\";\nimport { takesTasks } from \"./discover.js\";\nimport type { Identity, WakeEvent } from \"./events.js\";\nimport { packCall, userAgentOf, type Call, type Duration, type Recognized, type Wakeshift } from \"./wakeshift.js\";\n\n// Wakeshift's three arguments (wakeshift.ts's SESSION_ARG, HARNESS_ARG and\n// CONVERSATION_ARG, repeated: that module imports this one).\nconst SESSION_ARG = \"session_key\";\nconst HARNESS_ARG = \"harness\";\nconst CONVERSATION_ARG = \"conversation_id\";\n\nexport type { ToolCallExtra };\n\n// What the agent is told each of Wakeshift's arguments is: the Go SDK's\n// WakeArgs, word for word.\nconst SESSION_KEY_DESCRIPTION =\n \"This conversation's session_key, from an earlier result (a secret token, or a handle such as claude-code#2). Keep it to this conversation; don't share or log it.\";\nconst HARNESS_DESCRIPTION =\n \"The program you're running in: codex, claude-code, cursor (local CLI or IDE), cursor-cloud (Cursor cloud agent), grok-bot, copilot-cli, opencode, antigravity, openclaw (even when it runs your turns in Codex), hermes, chatgpt, or your program's name if it isn't listed\";\nconst CONVERSATION_DESCRIPTION =\n \"Your own ID for this conversation, if your program gives you one. Cursor and Grok Bot: the output of `printenv CURSOR_CONVERSATION_ID`. Codex and Antigravity send it automatically; others leave it empty\";\nconst WAKESHIFT_OUTPUT_DESCRIPTION = \"What Wakeshift adds for this conversation: how it's woken by this app's events\";\n/** @internal Wakeshift's three arguments' descriptions, for a tool whose input schema is written out (the wait tool, tasks.ts). */\nexport const WAKE_ARG_DESCRIPTIONS = { session_key: SESSION_KEY_DESCRIPTION, harness: HARNESS_DESCRIPTION, conversation_id: CONVERSATION_DESCRIPTION } as const;\n\nconst wakeInputs = {\n [SESSION_ARG]: z.string().optional().describe(SESSION_KEY_DESCRIPTION),\n [HARNESS_ARG]: z.string().optional().describe(HARNESS_DESCRIPTION),\n [CONVERSATION_ARG]: z.string().optional().describe(CONVERSATION_DESCRIPTION),\n};\n/** @internal Wakeshift's three arguments as attach's own tools take them: worded as a wrapped tool's (test/events-list.json pins it). */\nexport const toolArgs = wakeInputs;\nconst wakeOutput = { wakeshift: z.string().optional().describe(WAKESHIFT_OUTPUT_DESCRIPTION) };\n\n// The same in each of zod's two APIs: MCP refuses a shape that mixes them,\n// so a shape written with zod/v3 (or zod/v4) gets Wakeshift's fields in its\n// own (zod 3.25 and later carry both).\nconst byVersion = {\n v3: {\n inputs: {\n [SESSION_ARG]: z3.string().optional().describe(SESSION_KEY_DESCRIPTION),\n [HARNESS_ARG]: z3.string().optional().describe(HARNESS_DESCRIPTION),\n [CONVERSATION_ARG]: z3.string().optional().describe(CONVERSATION_DESCRIPTION),\n },\n output: { wakeshift: z3.string().optional().describe(WAKESHIFT_OUTPUT_DESCRIPTION) },\n },\n v4: {\n inputs: {\n [SESSION_ARG]: z4.string().optional().describe(SESSION_KEY_DESCRIPTION),\n [HARNESS_ARG]: z4.string().optional().describe(HARNESS_DESCRIPTION),\n [CONVERSATION_ARG]: z4.string().optional().describe(CONVERSATION_DESCRIPTION),\n },\n output: { wakeshift: z4.string().optional().describe(WAKESHIFT_OUTPUT_DESCRIPTION) },\n },\n};\n\n// fieldsFor is Wakeshift's fields in the zod API shape's own fields use\n// (for an empty shape, the default import's, or zod 4's for the MCP SDK\n// 2.x, which takes only zod 4).\nfunction fieldsFor<K extends \"inputs\" | \"output\">(shape: ZodRawShapeCompat, kind: K, host?: Host): K extends \"inputs\" ? WakeInputs : WakeOutputShape {\n const first = Object.values(shape ?? {})[0];\n const version = first ? (isZ4Schema(first) ? \"v4\" : \"v3\") : host?.version === 2 ? \"v4\" : null;\n const fields = version ? byVersion[version][kind] : kind === \"inputs\" ? wakeInputs : wakeOutput;\n return fields as any;\n}\n\n/** @internal Wakeshift's three arguments as attach's own tools take them, in the zod the host's MCP SDK takes. */\nexport function wakeInputsFor(host: Host): ZodRawShapeCompat {\n return host.version === 2 ? byVersion.v4.inputs : wakeInputs;\n}\n\n// withFields is an object schema with fields added, in the schema's own zod\n// API (zod 3, zod 4 classic or mini).\nfunction withFields(schema: AnySchema, fields: ZodRawShapeCompat): AnySchema {\n const s = schema as { extend?: (f: ZodRawShapeCompat) => AnySchema };\n if (typeof s.extend === \"function\") return s.extend(fields);\n return z4mini.extend(schema as any, fields as any) as AnySchema;\n}\n\n/** Wakeshift's three arguments, as attached.inputs adds them. */\nexport type WakeInputs = typeof wakeInputs;\n/** The optional wakeshift string attached.output adds. */\nexport type WakeOutputShape = typeof wakeOutput;\n/** Wakeshift's three arguments in zod 4, as attached.inputs adds them to a zod 4 object. */\nexport type WakeInputsV4 = typeof byVersion.v4.inputs;\n/** Wakeshift's three arguments in zod 3, as attached.inputs adds them to a zod 3 object. */\nexport type WakeInputsV3 = typeof byVersion.v3.inputs;\n/** The optional wakeshift string in zod 4, as attached.output adds it to a zod 4 object. */\nexport type WakeOutputV4 = typeof byVersion.v4.output;\n/** The optional wakeshift string in zod 3, as attached.output adds it to a zod 3 object. */\nexport type WakeOutputV3 = typeof byVersion.v3.output;\n/** What a wrapped tool's arguments must include: Wakeshift's three (attached.inputs adds them). */\nexport type WakeArgs = { [K in WakeKey]?: string | undefined };\n/**\n * The callback attached.events returns, for `server.registerTool`: it takes\n * the tool's arguments (A, Wakeshift's three included) and your MCP SDK's\n * request context (C).\n */\nexport type WrappedCallback<A, C> = (args: A, extra: C) => Promise<any>;\n/** The names of Wakeshift's three arguments. */\nexport type WakeKey = typeof SESSION_ARG | typeof HARNESS_ARG | typeof CONVERSATION_ARG;\n/** An input shape with Wakeshift's three arguments in it (attached.inputs'). */\nexport type WakeShape = ZodRawShapeCompat & { [K in WakeKey]: AnySchema };\n/** What a wrapped handler gets: the tool's own arguments, without Wakeshift's three. */\nexport type AppArgs<S extends ZodRawShapeCompat> = Omit<ShapeOutput<S>, WakeKey>;\n/** What a wrapped handler returns: a string (one text block) or a CallToolResult. */\nexport type WrappedResult = string | CallToolResult;\n\nconst WAKE_KEYS: readonly WakeKey[] = [SESSION_ARG, HARNESS_ARG, CONVERSATION_ARG];\n\n/**\n * @internal The tools/call _meta keys a harness names its conversation in\n * (the core's harnesses ConversationMeta, dotted for nested objects):\n * test/conversation-meta.json, which a Go test keeps current.\n */\nexport const CONVERSATION_META: readonly string[] = [\n \"agent-session-id\",\n \"antigravity.google/conversation_id\",\n \"vscode.conversationId\",\n \"wakeshift/conversation\",\n \"x-codex-turn-metadata.thread_id\",\n];\n\n/**\n * The calling conversation's subscription, made or renewed by\n * call.subscribe. id and user address it later: emit's\n * `to: [{ user, subscription: id }]`, or `event.end(user, id)`.\n */\nexport interface Subscription {\n id: string;\n user: string;\n /** False for a renewal. */\n created: boolean;\n /** The conversation's session. A secret: don't show, store or log it. */\n session: string;\n /** What Wakeshift recognized the agent's program as. */\n recognized: Recognized;\n /** The caller subscribes itself (call.native): nothing was made, id is \"\", and the block tells it what to subscribe to. */\n native: boolean;\n}\n\n/** How call.subscribe subscribes. */\nexport interface ToolSubscribeOptions {\n /** End after this long without a delivery or a fresh subscribe (default 30 days). */\n ttl?: Duration;\n /** Why the app subscribes the conversation, shown in the console (at most 200 characters). */\n reason?: string;\n /** Names a new session (agent@label), for an app acting for its agents. */\n label?: string;\n}\n\n/**\n * One call of a wrapped tool (attached.events): who's calling, and the\n * calls that subscribe the calling conversation. Only the wrapper makes\n * one, and it works until the handler returns (then CallEnded).\n */\nexport interface ToolCall<C = any> {\n /** Who attach's identify says is calling (undefined for none). */\n readonly user: string | undefined;\n /** The tool being called. */\n readonly tool: string;\n /**\n * The client subscribes to the app's events itself (MCP Events: ChatGPT,\n * the house agents). call.subscribe then makes no conversation\n * subscription, and the block tells it what to subscribe to.\n */\n readonly native: boolean;\n /** A native client's conversation, when it names one (ChatGPT's _meta[\"openai/session\"]). */\n readonly nativeConversation: string | null;\n /** The session_key passed; after a subscribe or resolveSession, the conversation's session. */\n readonly session: string | null;\n /** What Wakeshift recognized the agent's program as: null until a subscribe or resolveSession. */\n readonly recognized: Recognized | null;\n /** The call's request context, as your MCP SDK passes it to the tool's callback: 2.x's ctx, 1.x's extra. */\n readonly extra: C;\n /**\n * Subscribes the calling conversation to event with args, or renews its\n * subscription. The reply then carries what the conversation needs to be\n * woken (one block for the call, however many subscribes it makes), and\n * if the call fails, the subscription is ended. For a native caller\n * nothing is made. Your tool decides who may: authorize isn't consulted.\n * A personal event needs a user (identify's).\n */\n subscribe<A extends AnySchema>(event: WakeEvent<A, any>, args: SchemaInput<A>, opts?: ToolSubscribeOptions): Promise<Subscription>;\n /**\n * Ends the calling conversation's subscription to event with args,\n * resolving to whether one ended. For a native caller it ends the user's\n * own (webhook) subscriptions to the event with those arguments.\n */\n unsubscribe<A extends AnySchema>(event: WakeEvent<A, any>, args: SchemaInput<A>): Promise<boolean>;\n /** Finds or starts the calling conversation's session without subscribing it (it doesn't make it wakeable). */\n resolveSession(): Promise<string>;\n}\n\n/** A ToolCall used after its handler returned. */\nexport class CallEnded extends Error {\n constructor() {\n super(\"wakeshift: the tool call has ended: subscribe before the handler returns\");\n this.name = \"CallEnded\";\n }\n}\n\n/** attach's event options. */\nexport interface EventsOptions<C = any> {\n /**\n * Asked first whether a wrapped tool's call comes from a client that\n * subscribes to the app's events itself (call.native), for callers the\n * SDK can't tell (an app's own house agents). False leaves it to the\n * SDK's own checks. It gets the call's request context, as identify does.\n */\n native?(extra: C): boolean;\n}\n\n// The line a text-carried beacon is on (the core's beacon.Text), which a\n// harness's hook reads only as the last line of a result's text.\nconst BEACON_LINE_PREFIX = \"(For Wakeshift's hook on this computer, not for you: wakeshift-beacon: \";\nconst CONNECTOR_META_KEY = \"wakeshift/connector\";\n// The most native lines Wakeshift takes for one call.\nconst MAX_NATIVE_LINES = 20;\n\n/** /calls/addition's answer. */\nexport interface CallAddition {\n text?: string;\n trailer?: string;\n meta?: Record<string, unknown>;\n}\n\ntype Content = CallToolResult[\"content\"][number];\n\n// takeTrailer takes a beacon line off the end of the result's text\n// (dropping its block if nothing else is in it), returning it (\"\" if\n// there's none).\nfunction takeTrailer(content: Content[]): string {\n const last = content.at(-1);\n if (!last || last.type !== \"text\") return \"\";\n const text = last.text.replace(/[ \\t\\r\\n]+$/, \"\");\n const i = text.lastIndexOf(\"\\n\");\n const line = i >= 0 ? text.slice(i + 1) : text;\n if (!line.startsWith(BEACON_LINE_PREFIX) || !line.endsWith(\")\")) return \"\";\n const rest = i >= 0 ? text.slice(0, i).replace(/[ \\t\\r\\n]+$/, \"\") : \"\";\n if (rest === \"\") content.pop();\n else content[content.length - 1] = { ...last, text: rest };\n return line;\n}\n\n/** The structuredContent field a wrapped tool's structured result carries Wakeshift's block in (the same in every SDK). */\nexport const WAKESHIFT_FIELD = \"wakeshift\";\n\n/**\n * @internal An object output schema (JSON Schema, as tools/list gives it)\n * with an optional wakeshift string added, as a copy, so a client that\n * checks structuredContent against it takes the block. Anything else, or a\n * schema that already names it, comes back as it was.\n * test/wrapped-block.json (output_schemas) pins it.\n */\nexport function withWakeshiftField(schema: unknown): unknown {\n if (!schema || typeof schema !== \"object\" || Array.isArray(schema)) return schema;\n const s = schema as Record<string, unknown>;\n if (s.type !== \"object\") return schema;\n const props = s.properties;\n if (props !== undefined && (!props || typeof props !== \"object\" || Array.isArray(props))) return schema;\n if (props && WAKESHIFT_FIELD in (props as object)) return schema;\n return { ...s, properties: { ...((props as object) ?? {}), [WAKESHIFT_FIELD]: { type: \"string\", description: WAKESHIFT_OUTPUT_DESCRIPTION } } };\n}\n\n/**\n * @internal Adds the call's block to a wrapped handler's result: Wakeshift's\n * text as a block after the app's content, then a text-carried beacon last,\n * and _meta; a string result stays one text block. A result that already\n * carries a beacon keeps it, last, and gets no second one. A structured\n * result (structuredContent an object) gets the block's text in its\n * wakeshift field too. test/wrapped-block.json is the shape, shared with\n * the other SDKs.\n */\nexport function mergeBlock(result: WrappedResult, add: CallAddition): CallToolResult {\n const isString = typeof result === \"string\";\n const base: CallToolResult = isString ? { content: [{ type: \"text\", text: result }] } : result;\n const out: CallToolResult = { ...base, content: [...(base.content ?? [])] };\n const text = (add.text ?? \"\").trim();\n const metaBeacon = !!out._meta && CONNECTOR_META_KEY in out._meta;\n const existing = takeTrailer(out.content);\n if (text) out.content.push({ type: \"text\", text });\n const has = metaBeacon || existing !== \"\";\n if (existing) out.content.push({ type: \"text\", text: existing });\n else if (!has && add.trailer) out.content.push({ type: \"text\", text: add.trailer });\n for (const [k, v] of Object.entries(add.meta ?? {})) {\n if (k === CONNECTOR_META_KEY && has) continue;\n out._meta = { ...(out._meta ?? {}), [k]: v };\n }\n if (isString) {\n const texts = out.content.map((c) => (c.type === \"text\" ? c.text : \"\")).filter((t) => t !== \"\");\n out.content = [{ type: \"text\", text: texts.join(\"\\n\\n\") }];\n }\n if (text && out.structuredContent && typeof out.structuredContent === \"object\" && !Array.isArray(out.structuredContent)) {\n out.structuredContent = { ...(out.structuredContent as Record<string, unknown>), [WAKESHIFT_FIELD]: text };\n }\n return out;\n}\n\n// metaString is the string at key in a tool call's _meta: the key itself,\n// else a dotted path into nested objects (the core's harnesses.metaString).\nfunction metaString(meta: Record<string, unknown> | undefined, key: string): string {\n if (!meta) return \"\";\n const limit = (s: unknown) => (typeof s === \"string\" && s.length <= 200 ? s : \"\");\n if (typeof meta[key] === \"string\") return limit(meta[key]);\n let cur: unknown = meta;\n for (const part of key.split(\".\")) {\n if (!cur || typeof cur !== \"object\" || Array.isArray(cur)) return \"\";\n cur = (cur as Record<string, unknown>)[part];\n }\n return limit(cur);\n}\n\n/** @internal Whether a tool call's _meta names its conversation, the way a harness puts it there (test/conversation-meta.json). */\nexport function namesConversation(meta: Record<string, unknown> | undefined): boolean {\n return CONVERSATION_META.some((k) => metaString(meta, k) !== \"\");\n}\n\nfunction sameJSON(a: unknown, b: unknown): boolean {\n const norm = (v: unknown): unknown =>\n v === null || v === undefined\n ? {}\n : Array.isArray(v)\n ? v.map(norm)\n : typeof v === \"object\"\n ? Object.fromEntries(Object.keys(v as object).sort().map((k) => [k, norm((v as Record<string, unknown>)[k])]))\n : v;\n return JSON.stringify(norm(a)) === JSON.stringify(norm(b));\n}\n\nfunction detailOf(err: unknown): string {\n return err instanceof WakeshiftError ? err.detail : String((err as Error)?.message ?? err);\n}\n\ninterface CreatedSub {\n name: string;\n arguments: unknown;\n session: string;\n pending: string; // the call's pending-addition record, which made it\n}\n\ninterface NativeLine {\n name: string;\n arguments: unknown;\n}\n\n/** @internal What the wrapper needs of attach: the client, the server, who's calling, the event options. */\nexport interface AttachContext {\n wake: Wakeshift;\n /** The server, through what attach needs of its MCP SDK (host.ts). */\n host: Host;\n /** Who attach's identify says is calling: its user and client (raw: the MCP SDK's own request context). */\n identify(raw: unknown): Identity | undefined;\n /** The client's name: the request's (initialize's, else _meta's), else identified (identify's), else \"\". */\n clientOf(meta: Record<string, unknown> | undefined, identified?: string): string;\n events: EventsOptions<any>;\n warnOnce(key: string, message: string): void;\n}\n\n/** One tools/call of a wrapped tool: what its handler subscribed, for the block and the rollback. */\nclass CallScope<C> implements ToolCall<C> {\n user: string | undefined;\n tool: string;\n native = false;\n nativeConversation: string | null = null;\n session: string | null;\n recognized: Recognized | null = null;\n extra: C;\n\n ended = false;\n pending = \"\";\n armed = false;\n created: CreatedSub[] = [];\n nativeLines: NativeLine[] = [];\n inflight = new Set<Promise<unknown>>();\n private queue: Promise<unknown> = Promise.resolve();\n // The client's name identify gave, for a request that names none.\n private readonly identified: string | undefined;\n\n constructor(\n private readonly at: AttachContext,\n tool: string,\n extra: C,\n private readonly args: { session?: string; harness?: string; conversation?: string },\n ) {\n this.tool = tool;\n this.extra = extra;\n const id = at.identify(extra);\n this.user = id?.user;\n this.identified = id?.client;\n this.session = args.session || null;\n const n = nativeOf(at, extra, this.identified);\n this.native = n.native;\n this.nativeConversation = n.conversation;\n }\n\n // wire is the call as Wakeshift takes it: the request's client, _meta and\n // User-Agent, the agent's harness and conversation_id arguments, the\n // conversation's session, and who's calling.\n wire(session = this.session): Call {\n const req = this.at.host.req(this.extra);\n const meta = req.meta;\n return packCall({\n meta,\n clientName: this.at.clientOf(meta, this.identified),\n user: this.user,\n session: session ?? undefined,\n userAgent: userAgentOf(req),\n harness: this.args.harness,\n conversation: this.args.conversation,\n tool: this.tool,\n tasks: takesTasks(meta, req),\n });\n }\n\n // request runs one request of the call to Wakeshift, after any before it\n // (one at a time per call), refusing once the handler has returned.\n private request<T>(fn: () => Promise<T>): Promise<T> {\n if (this.ended) return Promise.reject(new CallEnded());\n const run = this.queue.then(() => (this.ended ? Promise.reject(new CallEnded()) : fn()));\n this.queue = run.catch(() => undefined);\n this.inflight.add(run);\n run.then(\n () => this.inflight.delete(run),\n () => this.inflight.delete(run),\n );\n return run;\n }\n\n private checkEvent(event: WakeEvent<any, any>): void {\n if (!event || typeof event.owner !== \"function\" || event.owner() !== this.at.wake) {\n throw new WakeshiftError(404, \"unknown_event\", `${event?.name ?? \"that\"} is another app's event: this app doesn't offer it`);\n }\n }\n\n subscribe<A extends AnySchema>(event: WakeEvent<A, any>, args: SchemaInput<A>, opts: ToolSubscribeOptions = {}): Promise<Subscription> {\n return this.request(async () => {\n this.checkEvent(event);\n const known = event.parseArgs(args);\n if (this.native) {\n this.addNative(event.name, known);\n return { id: \"\", user: this.user ?? \"\", created: false, session: \"\", recognized: { harness: null, via: null, claimed: null }, native: true };\n }\n if (event.personal && !this.user) {\n throw new WakeshiftError(400, \"bad_arguments\", `${event.name} is personal: call.subscribe needs a user (attach's identify), who the subscription belongs to`);\n }\n const body: Record<string, unknown> = { call: this.wire(), name: event.name, arguments: known, defer_addition: true };\n if (this.pending) body.pending = this.pending;\n if (opts.ttl !== undefined) body.ttl = opts.ttl;\n if (opts.reason) body.reason = opts.reason;\n if (opts.label) body.label = opts.label;\n const out = await this.at.wake.requestApp<{\n event_subscription: { id: string; user?: string; created: boolean };\n session: string;\n agent?: Partial<Recognized>;\n pending?: string;\n }>(\"POST\", \"/event-subscriptions\", body);\n if (out.pending) this.pending = out.pending;\n this.armed = true;\n this.session = out.session;\n const rec = recognizedOf(out.agent);\n this.recognized = rec;\n const es = out.event_subscription;\n if (es.created) this.created.push({ name: event.name, arguments: known, session: out.session, pending: out.pending ?? this.pending });\n return { id: es.id, user: es.user ?? this.user ?? \"\", created: !!es.created, session: out.session, recognized: rec, native: false };\n });\n }\n\n unsubscribe<A extends AnySchema>(event: WakeEvent<A, any>, args: SchemaInput<A>): Promise<boolean> {\n return this.request(async () => {\n this.checkEvent(event);\n const known = event.parseArgs(args);\n if (this.native) return this.endNative(event.name, known);\n const out = await this.at.wake.requestApp<{ ended?: boolean }>(\"POST\", \"/event-subscriptions/unsubscribe\", { call: this.wire(), name: event.name, arguments: known });\n return !!out.ended;\n });\n }\n\n resolveSession(): Promise<string> {\n return this.request(async () => {\n if (this.pending && this.session) return this.session;\n const out = await this.at.wake.requestApp<{ session: string; pending: string; agent?: Partial<Recognized> }>(\"POST\", \"/calls/session\", { call: this.wire() });\n this.pending = out.pending;\n this.session = out.session;\n this.recognized = recognizedOf(out.agent);\n return out.session;\n });\n }\n\n // endNative ends the user's webhook subscriptions to event with these arguments.\n private async endNative(name: string, args: unknown): Promise<boolean> {\n if (!this.user) return false;\n const out = await this.at.wake.requestApp<{ subscriptions?: { id: string; event: string; arguments: unknown; destination: string }[] }>(\"POST\", \"/event-subscriptions/list\", {\n user: this.user,\n });\n let ended = false;\n for (const s of out.subscriptions ?? []) {\n if (s.event !== name || s.destination !== \"webhook\" || !sameJSON(s.arguments, args)) continue;\n const r = await this.at.wake.requestApp<{ ended?: boolean }>(\"POST\", \"/event-subscriptions/end\", { user: this.user, id: s.id });\n ended = ended || !!r.ended;\n }\n return ended;\n }\n\n // addNative adds a native line, once per event and arguments.\n private addNative(name: string, args: unknown): void {\n if (this.nativeLines.some((l) => l.name === name && sameJSON(l.arguments, args))) return;\n if (this.nativeLines.length === MAX_NATIVE_LINES) {\n this.at.warnOnce(\n \"native:\" + this.tool,\n `wakeshift: the wrapped tool ${this.tool} subscribed a native client to more than ${MAX_NATIVE_LINES} events in one call; only ${MAX_NATIVE_LINES} are named`,\n );\n return;\n }\n this.nativeLines.push({ name, arguments: args });\n }\n\n // end closes the call to further requests, after waiting for any in\n // flight (warning once per tool: the handler should have waited for them).\n async end(): Promise<void> {\n if (this.inflight.size > 0) {\n this.at.warnOnce(\n \"inflight:\" + this.tool,\n `wakeshift: the wrapped tool ${this.tool} returned while a subscribe was in flight; it was waited for: await call.subscribe, call.unsubscribe and call.resolveSession before returning`,\n );\n await Promise.allSettled([...this.inflight]);\n }\n this.ended = true;\n }\n\n // rollback ends every subscription the call created and no other call\n // has renewed since (the core checks the pending record that made it),\n // with reason rolled_back (audited as such, no \"ended\" notice), whatever\n // became of the request.\n async rollback(): Promise<void> {\n for (const c of this.created) {\n try {\n await this.at.wake.requestApp(\"POST\", \"/event-subscriptions/unsubscribe\", { call: this.wire(c.session), name: c.name, arguments: c.arguments, reason: \"rolled_back\", pending: c.pending });\n } catch (err) {\n this.at.wake.warn(`wakeshift: rolling back a failed tool call's subscription (${this.tool}, ${c.name}): ${detailOf(err)}`);\n }\n }\n this.created = [];\n }\n\n // addition asks Wakeshift for the call's block: what the conversation\n // needs to be woken (from the call's pending-addition record, if a\n // subscribe or resolveSession made one; otherwise what any other tool\n // result of the app's carries), and a line per event a native caller\n // should subscribe to. A call that names no conversation, and subscribed\n // nothing, gets nothing (null). Only a failure for a call that subscribed\n // is thrown: without a subscription, the block is a courtesy.\n async addition(): Promise<CallAddition | null> {\n const wire = this.wire();\n if (!this.pending && this.nativeLines.length === 0 && !wire.session && !wire.conversation && !namesConversation(wire.meta)) return null;\n const body: Record<string, unknown> = { call: wire };\n if (this.pending) body.pending = this.pending;\n if (this.nativeLines.length > 0) body.native = this.nativeLines;\n try {\n return await this.at.wake.requestApp<CallAddition>(\"POST\", \"/calls/addition\", body);\n } catch (err) {\n if (this.armed || this.nativeLines.length > 0) throw err;\n this.at.wake.warn(`wakeshift: Wakeshift's addition to a result of ${this.tool}: ${detailOf(err)}`);\n return null;\n }\n }\n}\n\nfunction recognizedOf(a: Partial<Recognized> | undefined): Recognized {\n return { harness: a?.harness ?? null, via: a?.via ?? null, claimed: a?.claimed ?? null };\n}\n\nfunction hasKey(o: unknown, key: string): boolean {\n return !!o && typeof o === \"object\" && !Array.isArray(o) && (o as Record<string, unknown>)[key] !== undefined;\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return !!v && typeof v === \"object\" && !Array.isArray(v);\n}\n\n/**\n * @internal Whether a call comes from a client that subscribes to the app's\n * events itself, on stateless servers too (which never see initialize), in\n * this order: the app's override (events.native); ChatGPT's\n * _meta[\"openai/session\"]; a client name (initialize's, or _meta's, else\n * identify's) or User-Agent of a known native client; a client that\n * declares the MCP Events extension (initialize's capabilities, or\n * _meta's). conversation is ChatGPT's conversation, when it names one.\n */\nexport function nativeOf(at: Pick<AttachContext, \"host\" | \"clientOf\" | \"events\">, extra: unknown, identified?: string): { native: boolean; conversation: string | null } {\n const req = at.host.req(extra);\n const meta = (req.meta ?? {}) as Record<string, unknown>;\n const conversation = typeof meta[\"openai/session\"] === \"string\" && meta[\"openai/session\"] ? (meta[\"openai/session\"] as string) : null;\n if (at.events.native?.(extra)) return { native: true, conversation };\n if (conversation) return { native: true, conversation };\n if (dialectOf(at.clientOf(meta, identified), userAgentOf(req)) === \"chatgpt\") return { native: true, conversation: null };\n const caps = at.host.clientCapabilities();\n if (hasKey(caps?.extensions, EXTENSION_KEY)) return { native: true, conversation: null };\n const metaCaps = meta[\"io.modelcontextprotocol/clientCapabilities\"] as Record<string, unknown> | undefined;\n if (hasKey(metaCaps?.extensions, EXTENSION_KEY)) return { native: true, conversation: null };\n return { native: false, conversation: null };\n}\n\n/**\n * Wakeshift attached to an MCP server: the handle `wake.attach` returns.\n * Wrap a tool's callback with events, and give its input schema\n * Wakeshift's three arguments with inputs. C is your MCP SDK's request\n * context (2.x's ctx, 1.x's extra), which a wrapped call carries as\n * `call.extra`.\n */\nexport class Attached<C = any> {\n /** @internal */\n private readonly wrapped = new Map<string, unknown>();\n\n /** @internal Use wake.attach. */\n constructor(private readonly at: AttachContext) {}\n\n /**\n * A tool's input schema plus Wakeshift's three optional arguments\n * (session_key, harness and conversation_id), for a wrapped tool's\n * inputSchema: a zod object, `inputSchema: attached.inputs(z.object({ table: z.string() }))`\n * (as @modelcontextprotocol/server 2.x takes it), or a shape,\n * `inputSchema: attached.inputs({ table: z.string() })`.\n */\n inputs<O extends z4.ZodObject>(schema: O): z4.ZodObject<O[\"shape\"] & WakeInputsV4, O[\"_zod\"][\"config\"]>;\n inputs<O extends z3.AnyZodObject>(schema: O): z3.ZodObject<O[\"shape\"] & WakeInputsV3, O[\"_def\"][\"unknownKeys\"], O[\"_def\"][\"catchall\"]>;\n inputs<S extends ZodRawShapeCompat>(shape: S): S & WakeInputs;\n inputs(shape: ZodRawShapeCompat | AnySchema): unknown {\n if (isSchema(shape)) {\n const own = getObjectShape(shape);\n if (!own) throw new Error(\"wakeshift: attached.inputs takes a zod object or a shape\");\n for (const k of WAKE_KEYS) if (k in own) throw new Error(`wakeshift: attached.inputs adds ${k} itself: leave it out of the schema`);\n return withFields(shape, byVersion[isZ4Schema(shape) ? \"v4\" : \"v3\"].inputs);\n }\n for (const k of WAKE_KEYS) if (k in (shape ?? {})) throw new Error(`wakeshift: attached.inputs adds ${k} itself: leave it out of the shape`);\n return { ...shape, ...fieldsFor(shape, \"inputs\", this.at.host) };\n }\n\n /**\n * A tool's output schema plus an optional wakeshift string, for a wrapped\n * tool's outputSchema (a zod object or a shape, as inputs takes).\n * Optional: every structured result of a wrapped tool gets the block's\n * text (without the beacon line) in wakeshift, for hosts that show the\n * model only structuredContent, and tools/list names it in the tool's\n * output schema; this declares it in your own schema and types. The\n * block stays in the content too.\n */\n output<O extends z4.ZodObject>(schema: O): z4.ZodObject<O[\"shape\"] & WakeOutputV4, O[\"_zod\"][\"config\"]>;\n output<O extends z3.AnyZodObject>(schema: O): z3.ZodObject<O[\"shape\"] & WakeOutputV3, O[\"_def\"][\"unknownKeys\"], O[\"_def\"][\"catchall\"]>;\n output<S extends ZodRawShapeCompat>(shape: S): S & WakeOutputShape;\n output(shape: ZodRawShapeCompat | AnySchema): unknown {\n if (isSchema(shape)) {\n const own = getObjectShape(shape);\n if (!own) throw new Error(\"wakeshift: attached.output takes a zod object or a shape\");\n if (WAKESHIFT_FIELD in own) throw new Error(\"wakeshift: attached.output adds wakeshift itself: leave it out of the schema\");\n return withFields(shape, byVersion[isZ4Schema(shape) ? \"v4\" : \"v3\"].output);\n }\n if (\"wakeshift\" in (shape ?? {})) throw new Error(\"wakeshift: attached.output adds wakeshift itself: leave it out of the shape\");\n return { ...shape, ...fieldsFor(shape, \"output\", this.at.host) };\n }\n\n /**\n * Wraps a tool's callback, for `server.registerTool(name, …)` with the\n * same name (MCP doesn't tell a callback its tool's name): the handler\n * gets the tool's own arguments and a ToolCall, and returns a string or\n * a CallToolResult; the reply gets Wakeshift's block. The tool's\n * inputSchema must come from attached.inputs (a type error otherwise).\n * Register it on the server passed to attach.\n */\n events<A extends WakeArgs>(name: string, handler: (args: Omit<A, WakeKey>, call: ToolCall<C>) => WrappedResult | Promise<WrappedResult>): WrappedCallback<A, C> {\n if (!name || typeof name !== \"string\") throw new Error(\"wakeshift: attached.events needs the tool's name, as registered\");\n if (typeof handler !== \"function\") throw new Error(\"wakeshift: attached.events needs a handler\");\n const cb = (async (args: Record<string, unknown>, extra: C) => this.run(name, cb, handler as any, args ?? {}, extra)) as unknown as WrappedCallback<A, C>;\n this.wrapped.set(name, cb);\n return cb;\n }\n\n private async run(\n name: string,\n cb: unknown,\n handler: (args: Record<string, unknown>, call: ToolCall<C>) => WrappedResult | Promise<WrappedResult>,\n input: Record<string, unknown>,\n extra: C,\n ): Promise<CallToolResult> {\n const host = this.at.host;\n const tool = host.registeredTool(name);\n if (tool === undefined || (tool && (tool.handler ?? tool.callback) !== cb)) {\n throw new Error(`wakeshift: attached.events(\"${name}\", …) isn't the tool named ${name} on the server passed to attach: register it with the same name, on that server`);\n }\n let outputSchema: unknown;\n if (tool) {\n const shape = getObjectShape(normalizeObjectSchema(tool.inputSchema));\n if (!shape || WAKE_KEYS.some((k) => !(k in shape))) {\n throw new Error(`wakeshift: the tool ${name} doesn't take Wakeshift's arguments: make its inputSchema with attached.inputs(…)`);\n }\n outputSchema = tool.outputSchema;\n } else {\n this.at.warnOnce(\"internals\", \"wakeshift: this MCP SDK keeps its tools where Wakeshift can't read them, so wrapped tools' registration and output aren't checked\");\n }\n const str = (k: string) => (typeof input[k] === \"string\" && (input[k] as string) ? (input[k] as string) : undefined);\n const call = new CallScope<C>(this.at, name, extra, { session: str(SESSION_ARG), harness: str(HARNESS_ARG), conversation: str(CONVERSATION_ARG) });\n const appArgs: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(input)) if (!(WAKE_KEYS as readonly string[]).includes(k)) appArgs[k] = v;\n\n let result: WrappedResult;\n try {\n result = await handler(appArgs, call);\n } catch (err) {\n await call.end();\n await call.rollback();\n throw err;\n }\n await call.end();\n // Rollback is decided from the final result, the one the client would\n // receive: MCP validates the output after this callback returns, so\n // the wrapper checks it the same way first.\n if (result === null || result === undefined || (typeof result !== \"string\" && typeof result !== \"object\")) {\n await call.rollback();\n return result as unknown as CallToolResult;\n }\n if ((typeof result === \"object\" && result.isError) || host.req(extra).signal?.aborted || !(await host.validOutput(outputSchema, result))) {\n await call.rollback();\n return typeof result === \"string\" ? { content: [{ type: \"text\", text: result }] } : result;\n }\n let add: CallAddition | null;\n try {\n add = await call.addition();\n } catch (err) {\n // The conversation is subscribed but wouldn't learn how it's woken:\n // the call fails, as one whose handler failed does.\n await call.rollback();\n this.at.wake.warn(`wakeshift: Wakeshift's block for a result of ${name} failed, so the call's subscriptions were rolled back: ${detailOf(err)}`);\n return { isError: true, content: [{ type: \"text\", text: `Wakeshift couldn't finish setting up this conversation's wakes (${detailOf(err)}). Try again.` }] };\n }\n const out = mergeBlock(result, add ?? {});\n if (isRecord(out.structuredContent) && WAKESHIFT_FIELD in out.structuredContent && !(await host.validOutput(outputSchema, out))) {\n // A schema that refuses fields it doesn't name (a strict object):\n // MCP would refuse the result, so it goes without the field.\n const { [WAKESHIFT_FIELD]: _dropped, ...own } = out.structuredContent;\n out.structuredContent = own;\n this.at.warnOnce(\n \"output:\" + name,\n `wakeshift: the wrapped tool ${name}'s outputSchema refuses a wakeshift field, so hosts that show only structuredContent won't see how this conversation is woken: make it with attached.output`,\n );\n }\n return out;\n }\n\n /**\n * @internal Wraps the server's tools/list handler so each wrapped tool's\n * object output schema names wakeshift (withWakeshiftField). McpServer\n * sets the handler when the first tool is registered, perhaps after\n * attach, so a later set is wrapped too (as tasks.ts does).\n */\n amendToolsList(): void {\n type Handler = (request: any, extra: any) => Promise<any>;\n const handlers = this.at.host.handlers();\n if (!handlers) return; // a future SDK: schemas stay as registered\n const wrap =\n (h: Handler): Handler =>\n async (request, extra) => {\n const out = await h(request, extra);\n if (out && Array.isArray(out.tools)) this.amendTools(out.tools);\n return out;\n };\n const h = handlers.get(\"tools/list\");\n if (h) Map.prototype.set.call(handlers, \"tools/list\", wrap(h));\n const set = handlers.set.bind(handlers);\n handlers.set = (method: string, h: Handler) => set(method, method === \"tools/list\" ? wrap(h) : h);\n }\n\n private amendTools(tools: unknown[]): void {\n for (let i = 0; i < tools.length; i++) {\n const t = tools[i] as { name?: unknown; outputSchema?: unknown } | null;\n if (!t || typeof t !== \"object\" || typeof t.name !== \"string\" || !this.wrapped.has(t.name) || !t.outputSchema) continue;\n const schema = withWakeshiftField(t.outputSchema);\n if (schema !== t.outputSchema) tools[i] = { ...t, outputSchema: schema };\n }\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
- import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- import type { AnySchema } from "@modelcontextprotocol/sdk/server/zod-compat.js";
1
+ import type { AnySchema } from "./zod.js";
2
+ import type { HostContext, McpServerLike } from "./mcp.js";
3
3
  import { WakeEvent, type AttachOptions, type EventOptions, type EventTypeManifest } from "./events.js";
4
4
  import type { Attached } from "./toolcall.js";
5
5
  /** Wakeshift's production core, the default for every key but an older wst_test_ one. Override with `core` or WAKESHIFT_CORE. */
@@ -231,8 +231,12 @@ export declare class Wakeshift {
231
231
  * It returns the handle your own tools use to subscribe the conversation
232
232
  * calling them: wrap a tool's callback with attached.events, and give it
233
233
  * Wakeshift's arguments with attached.inputs.
234
+ *
235
+ * server is an McpServer from @modelcontextprotocol/server 2.x or
236
+ * @modelcontextprotocol/sdk 1.x; identify gets that SDK's own request
237
+ * context (2.x's ctx, 1.x's extra).
234
238
  */
235
- attach(server: McpServer, opts?: AttachOptions): Attached;
239
+ attach<S extends McpServerLike>(server: S, opts?: AttachOptions<HostContext<S>>): Attached<HostContext<S>>;
236
240
  /**
237
241
  * The workspace Wakeshift keeps for one of the app's users (user: the
238
242
  * app's own ID for them, as attach's identify gives it), created on first