@wakeshift/sdk 0.4.0 → 0.5.2

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.
@@ -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;AAErD,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,CAAC;AAK3C,wEAAwE;AACxE,2BAA2B;AAC3B,MAAM,uBAAuB,GAC3B,mKAAmK,CAAC;AACtK,MAAM,mBAAmB,GACvB,6QAA6Q,CAAC;AAChR,MAAM,wBAAwB,GAC5B,4MAA4M,CAAC;AAC/M,MAAM,4BAA4B,GAAG,gFAAgF,CAAC;AAEtH,MAAM,UAAU,GAAG;IACjB,CAAC,WAAW,CAAC,EA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AAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,mEAAmE,QAAQ,CAAC,GAAG,CAAC,eAAe,EAAE,CAAC,EAAE,CAAC;QAC/J,CAAC;QACD,MAAM,GAAG,GAAG,UAAU,CAAC,MAAM,EAAE,GAAG,IAAI,EAAE,EAAE,UAAU,CAAC,CAAC;QACtD,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,IAAI,GAAG,CAAC,iBAAiB,EAAE,CAAC;YACrE,IAAI,CAAC,EAAE,CAAC,QAAQ,CACd,SAAS,GAAG,IAAI,EAChB,+BAA+B,IAAI,qIAAqI,CACzK,CAAC;QACJ,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;CACF;AAED,2EAA2E;AAC3E,yEAAyE;AACzE,KAAK,UAAU,WAAW,CAAC,YAAmC,EAAE,MAAqB;IACnF,IAAI,CAAC,YAAY;QAAE,OAAO,IAAI,CAAC;IAC/B,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,iBAAiB;QAAE,OAAO,KAAK,CAAC;IAC1E,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 type { Identity, WakeEvent } from \"./events.js\";\nimport { packCall, type Call, type Duration, type Recognised, 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\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 recognised the agent's program as. */\n recognised: Recognised;\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 recognised the agent's program as: null until a subscribe or resolveSession. */\n readonly recognised: Recognised | 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/**\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. With wakeOutput,\n * structuredContent's wakeshift is the block's text. test/wrapped-block.json\n * is the shape, shared with the other SDKs.\n */\nexport function mergeBlock(result: WrappedResult, add: CallAddition, wakeOutput: boolean): 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 && wakeOutput && out.structuredContent && typeof out.structuredContent === \"object\" && !Array.isArray(out.structuredContent)) {\n out.structuredContent = { ...out.structuredContent, wakeshift: 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 recognised: Recognised | 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 });\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: \"\", recognised: { 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<Recognised>;\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 = recognisedOf(out.agent);\n this.recognised = 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, recognised: 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<Recognised> }>(\"POST\", \"/calls/session\", { call: this.wire() });\n this.pending = out.pending;\n this.session = out.session;\n this.recognised = recognisedOf(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 recognisedOf(a: Partial<Recognised> | undefined): Recognised {\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: the wrapper sets it to the block's text (without the\n * beacon line), for hosts that show the model only structuredContent.\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 wakeOutput = false;\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 const out = getObjectShape(normalizeObjectSchema(outputSchema));\n wakeOutput = !!out && \"wakeshift\" in out;\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 ?? {}, wakeOutput);\n if ((add?.text ?? \"\").trim() && !wakeOutput && out.structuredContent) {\n this.at.warnOnce(\n \"output:\" + name,\n `wakeshift: the wrapped tool ${name} returns structuredContent without attached.output: hosts that show only structuredContent won't see how this conversation is woken`,\n );\n }\n return out;\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;AA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AAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACtC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAsD,CAAC;YACxE,IAAI,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,YAAY;gBAAE,SAAS;YACxH,MAAM,MAAM,GAAG,kBAAkB,CAAC,CAAC,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;AAED,2EAA2E;AAC3E,yEAAyE;AACzE,KAAK,UAAU,WAAW,CAAC,YAAmC,EAAE,MAAqB;IACnF,IAAI,CAAC,YAAY;QAAE,OAAO,IAAI,CAAC;IAC/B,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,iBAAiB;QAAE,OAAO,KAAK,CAAC;IAC1E,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"]}
@@ -46,14 +46,14 @@ export interface AppInfo {
46
46
  };
47
47
  }
48
48
  /**
49
- * What Wakeshift recognised the calling conversation's harness as, and by
49
+ * What Wakeshift recognized the calling conversation's harness as, and by
50
50
  * which signal ("claim": only the agent's harness argument named it); both
51
51
  * null when nothing named one. claimed is what the agent said (normalized:
52
52
  * "Grok Bot" is grok-bot), null if it didn't; a claimed that differs from
53
- * harness was ignored, since it contradicted what the call was recognised
53
+ * harness was ignored, since it contradicted what the call was recognized
54
54
  * as (the claim only refines it: Cursor's calls may be Grok Bot's).
55
55
  */
56
- export interface Recognised {
56
+ export interface Recognized {
57
57
  harness: string | null;
58
58
  via: "client" | "meta" | "user_agent" | "claim" | null;
59
59
  claimed: string | null;
@@ -184,10 +184,12 @@ export declare class Wakeshift {
184
184
  * Tells Wakeshift what the app may do, replacing what it said before: m,
185
185
  * with the events you defined (defineEvent) after m's own events. An
186
186
  * event both defined and listed in m.events is an error, and nothing is
187
- * sent. You needn't call it: Wakeshift gets the manifest automatically
188
- * when the app first needs it. Once called, m is what every automatic
189
- * send carries (even if this one failed), with the events defined by
190
- * then. Returns the manifest as Wakeshift keeps it.
187
+ * sent. You needn't call it: a process that serves your tools (attach)
188
+ * sends the manifest automatically, merged into the one Wakeshift has.
189
+ * Call it to remove an event or clear a setting. Once called, m's
190
+ * settings are what every automatic send carries (even if this one
191
+ * failed), with the events defined by then. Returns the manifest as
192
+ * Wakeshift keeps it.
191
193
  */
192
194
  publishManifest(m: Manifest): Promise<Manifest>;
193
195
  private sending;
@@ -197,6 +199,7 @@ export declare class Wakeshift {
197
199
  private sendManifest;
198
200
  private readonly events;
199
201
  private manifestBase;
202
+ private serving;
200
203
  private published;
201
204
  private manifestVersion;
202
205
  /**
package/dist/wakeshift.js CHANGED
@@ -2,6 +2,7 @@ import { WakeshiftError } from "./errors.js";
2
2
  import { WakeEvent, attachEvents } from "./events.js";
3
3
  import { parseKey, signAssertion, isTestKey } from "./key.js";
4
4
  import { retryRefused } from "./retry.js";
5
+ import { takesTasks } from "./discover.js";
5
6
  /** Wakeshift's production core, the default for every key but an older wst_test_ one. Override with `core` or WAKESHIFT_CORE. */
6
7
  export const DEFAULT_CORE = "https://app.wakeshift.ai";
7
8
  /** The tool argument an agent passes its session key in (a result gives it one). */
@@ -58,6 +59,8 @@ export function packCall(c) {
58
59
  out.conversation = c.conversation.trim();
59
60
  if (c.tool?.trim())
60
61
  out.tool = c.tool.trim();
62
+ if (c.tasks)
63
+ out.tasks = true;
61
64
  return out;
62
65
  }
63
66
  /**
@@ -75,6 +78,7 @@ export function toolCallOf(extra, client, user, args, tool) {
75
78
  harness: str(args, HARNESS_ARG),
76
79
  conversation: str(args, CONVERSATION_ARG),
77
80
  tool,
81
+ tasks: takesTasks(extra?._meta, extra),
78
82
  });
79
83
  }
80
84
  // str is a tool argument's value if it's a string.
@@ -180,10 +184,12 @@ export class Wakeshift {
180
184
  * Tells Wakeshift what the app may do, replacing what it said before: m,
181
185
  * with the events you defined (defineEvent) after m's own events. An
182
186
  * event both defined and listed in m.events is an error, and nothing is
183
- * sent. You needn't call it: Wakeshift gets the manifest automatically
184
- * when the app first needs it. Once called, m is what every automatic
185
- * send carries (even if this one failed), with the events defined by
186
- * then. Returns the manifest as Wakeshift keeps it.
187
+ * sent. You needn't call it: a process that serves your tools (attach)
188
+ * sends the manifest automatically, merged into the one Wakeshift has.
189
+ * Call it to remove an event or clear a setting. Once called, m's
190
+ * settings are what every automatic send carries (even if this one
191
+ * failed), with the events defined by then. Returns the manifest as
192
+ * Wakeshift keeps it.
187
193
  */
188
194
  async publishManifest(m) {
189
195
  const version = this.manifestVersion; // before the body: a later defineEvent is sent again
@@ -228,30 +234,30 @@ export class Wakeshift {
228
234
  const { events: _listed, ...rest } = m;
229
235
  return events.length > 0 ? { ...rest, events } : rest;
230
236
  }
231
- // The automatic send: the manifest the app last published, or else the
232
- // settings Wakeshift has (asked for first, so the send never wipes what
233
- // was published separately), with the defined events.
237
+ // The automatic send, from a process that serves the app's tools: the
238
+ // settings the app last published (only those it set), with the defined
239
+ // events, merged into the manifest Wakeshift has, so it never removes an
240
+ // event or clears a setting another process sent.
234
241
  async sendManifest() {
235
- if (this.manifestBase) {
236
- await this.request("PUT", "/manifest", this.manifestBody(this.manifestBase));
237
- return;
242
+ const body = {};
243
+ for (const [k, v] of Object.entries(this.manifestBody(this.manifestBase ?? {}))) {
244
+ if (v === undefined || v === null || v === "" || v === false || (Array.isArray(v) && v.length === 0))
245
+ continue;
246
+ body[k] = v;
238
247
  }
239
- const stored = await this.request("GET", "/manifest");
240
- const kept = { description: typeof stored.description === "string" ? stored.description : "" };
241
- if (stored.agent !== null && typeof stored.agent === "object")
242
- kept.agent = stored.agent;
243
- if (stored.others_can_wake === true)
244
- kept.others_can_wake = true;
245
- if (Array.isArray(stored.preapprove_tools) && stored.preapprove_tools.length > 0)
246
- kept.preapprove_tools = stored.preapprove_tools;
247
- await this.request("PUT", "/manifest", this.manifestBody(kept));
248
+ if (!body.events)
249
+ return; // nothing to add (attach refuses with no events, but never send an empty list)
250
+ await this.request("POST", "/manifest/merge", body);
248
251
  }
249
252
  // ── Events (MCP Events, natively or bridged) ──────────────────────────
250
253
  events = new Map();
251
- // What publishManifest was last given (null: nothing yet); whether
252
- // Wakeshift has the manifest for the events defined now (the send; null:
253
- // not yet, or a defineEvent since); and how many defineEvents there were.
254
+ // What publishManifest was last given (null: nothing yet); whether this
255
+ // process serves the app's tools (attach: only then is the manifest sent
256
+ // automatically); whether Wakeshift has the manifest for the events
257
+ // defined now (the send; null: not yet, or a defineEvent since); and how
258
+ // many defineEvents there were.
254
259
  manifestBase = null;
260
+ serving = false;
255
261
  published = null;
256
262
  manifestVersion = 0;
257
263
  /**
@@ -293,10 +299,19 @@ export class Wakeshift {
293
299
  * Wakeshift's arguments with attached.inputs.
294
300
  */
295
301
  attach(server, opts = {}) {
296
- return attachEvents(this, server, [...this.events.values()], opts);
302
+ const attached = attachEvents(this, server, [...this.events.values()], opts);
303
+ this.serving = true; // the manifest is sent automatically from now on
304
+ return attached;
297
305
  }
298
- /** @internal Sends the manifest with the defined events, once (again after a defineEvent). */
306
+ /**
307
+ * @internal Sends the manifest with the defined events, once (again after
308
+ * a defineEvent), from a process that serves the app's tools (attach). A
309
+ * process that only emits never sends it: its events may be fewer, or
310
+ * older, than its server's.
311
+ */
299
312
  ensureEvents() {
313
+ if (!this.serving)
314
+ return Promise.resolve();
300
315
  if (!this.published)
301
316
  this.track(this.serial(() => this.sendManifest()), this.manifestVersion);
302
317
  return this.published;
@@ -312,10 +327,14 @@ export class Wakeshift {
312
327
  const out = await this.request("POST", "/events/emit", body);
313
328
  return { matched: out.matched, duplicate: !!out.duplicate, unmatched: recipientsOf(out.unmatched), ended: recipientsOf(out.ended) };
314
329
  }
315
- /** @internal A call to the app API (the events machinery's), after the manifest with the defined events is published. */
316
- async requestApp(method, path, body) {
330
+ /**
331
+ * @internal A call to the app API (the events machinery's), after the
332
+ * manifest with the defined events is published. opts: a longer timeout
333
+ * (a held tasks/get), and a signal that ends it early.
334
+ */
335
+ async requestApp(method, path, body, opts = {}) {
317
336
  await this.ensureEvents();
318
- return this.request(method, path, body);
337
+ return this.request(method, path, body, opts);
319
338
  }
320
339
  // ── Users' workspaces ──────────────────────────────────────────────────
321
340
  /**
@@ -338,23 +357,25 @@ export class Wakeshift {
338
357
  async checkAgent(workspace, agent) {
339
358
  await this.request("POST", `/workspaces/${encodeURIComponent(workspace)}/agents/${encodeURIComponent(agent)}/token`);
340
359
  }
341
- async request(method, path, body) {
360
+ async request(method, path, body, opts = {}) {
342
361
  const headers = { Authorization: "Bearer " + this.assertion() };
343
362
  if (body !== undefined)
344
363
  headers["Content-Type"] = "application/json";
345
364
  let resp;
346
365
  let text;
366
+ const timeoutMs = Math.max(opts.timeoutMs ?? 0, this.timeoutMs);
367
+ const timeout = AbortSignal.timeout(timeoutMs);
347
368
  try {
348
369
  resp = await this.fetchFn(this.core + "/api/apps/v1" + path, {
349
370
  method,
350
371
  headers,
351
372
  body: body === undefined ? undefined : JSON.stringify(body),
352
- signal: AbortSignal.timeout(this.timeoutMs),
373
+ signal: opts.signal ? AbortSignal.any([timeout, opts.signal]) : timeout,
353
374
  });
354
375
  text = await resp.text();
355
376
  }
356
377
  catch (err) {
357
- throw this.unreachable(err);
378
+ throw this.unreachable(err, timeoutMs);
358
379
  }
359
380
  let json;
360
381
  try {
@@ -380,10 +401,10 @@ export class Wakeshift {
380
401
  }
381
402
  // A request that got no answer. Name the core it went to: a wrong or
382
403
  // missing WAKESHIFT_CORE is the usual cause.
383
- unreachable(err) {
404
+ unreachable(err, timeoutMs = this.timeoutMs) {
384
405
  const e = err;
385
406
  const why = e?.name === "TimeoutError" || e?.name === "AbortError"
386
- ? `no answer within ${this.timeoutMs / 1000}s`
407
+ ? `no answer within ${timeoutMs / 1000}s`
387
408
  : [e?.message, e?.cause?.code ?? e?.cause?.message].filter(Boolean).join(": ") || String(err);
388
409
  return new WakeshiftError(0, "unreachable", `can't reach Wakeshift at ${this.core} (${why}). Check that WAKESHIFT_CORE, or the core option, is the address of the console your key came from`, { cause: err });
389
410
  }