@wakeshift/sdk 0.5.0 → 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/CHANGELOG.md +40 -0
- package/README.md +58 -4
- package/dist/discover.d.ts +4 -0
- package/dist/discover.js +128 -0
- package/dist/discover.js.map +1 -0
- package/dist/events.d.ts +14 -9
- package/dist/events.js +131 -88
- package/dist/events.js.map +1 -1
- package/dist/host.d.ts +2 -0
- package/dist/host.js +203 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +92 -0
- package/dist/mcp.js +22 -0
- package/dist/mcp.js.map +1 -0
- package/dist/spec.d.ts +4 -2
- package/dist/spec.js +4 -2
- package/dist/spec.js.map +1 -1
- package/dist/tasks.d.ts +33 -0
- package/dist/tasks.js +159 -0
- package/dist/tasks.js.map +1 -0
- package/dist/toolcall.d.ts +74 -22
- package/dist/toolcall.js +127 -66
- package/dist/toolcall.js.map +1 -1
- package/dist/wakeshift.d.ts +7 -3
- package/dist/wakeshift.js +29 -18
- package/dist/wakeshift.js.map +1 -1
- package/dist/zod.d.ts +16 -0
- package/dist/zod.js +95 -0
- package/dist/zod.js.map +1 -0
- package/package.json +15 -2
package/dist/wakeshift.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wakeshift.js","sourceRoot":"","sources":["../src/wakeshift.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,YAAY,EAAiE,MAAM,aAAa,CAAC;AAErH,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAe,SAAS,EAAE,MAAM,UAAU,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,iIAAiI;AACjI,MAAM,CAAC,MAAM,YAAY,GAAG,0BAA0B,CAAC;AAEvD,oFAA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vB,CAAC,EACD,aAAa,EACb,4BAA4B,IAAI,CAAC,IAAI,KAAK,GAAG,oGAAoG,EACjJ,EAAE,KAAK,EAAE,GAAG,EAAE,CACf,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { AnySchema } from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport { WakeshiftError } from \"./errors.js\";\nimport { WakeEvent, attachEvents, type AttachOptions, type EventOptions, type EventTypeManifest } from \"./events.js\";\nimport type { Attached } from \"./toolcall.js\";\nimport { parseKey, signAssertion, type AppKey, isTestKey } from \"./key.js\";\nimport { retryRefused } from \"./retry.js\";\n\n/** Wakeshift's production core, the default for every key but an older wst_test_ one. Override with `core` or WAKESHIFT_CORE. */\nexport const DEFAULT_CORE = \"https://app.wakeshift.ai\";\n\n/** The tool argument an agent passes its session key in (a result gives it one). */\nexport const SESSION_ARG = \"session_key\";\n\n/** The tool argument an agent says which program it runs in with. */\nexport const HARNESS_ARG = \"harness\";\n\n/**\n * The tool argument an agent passes its own ID for the conversation in,\n * when its program gives it one (Cursor and Grok Bot: CURSOR_CONVERSATION_ID).\n */\nexport const CONVERSATION_ARG = \"conversation_id\";\n\nexport interface WakeshiftOptions {\n /** The app key from the console: wst_ and 50 characters (or an older wst_test_… or wst_live_… key). */\n key: string;\n /**\n * Wakeshift's base URL: the console you got the key from. Default:\n * WAKESHIFT_CORE from the environment, else https://app.wakeshift.ai.\n * An older wst_test_… key has no default: it needs one of the two.\n */\n core?: string;\n /** Default: the global fetch. */\n fetch?: typeof fetch;\n /** Per-request timeout in milliseconds. Default 20000. */\n timeoutMs?: number;\n /**\n * Called with a problem that doesn't fail the call but makes it work less\n * well: each time for a failure, such as a failed call's subscription\n * that couldn't be rolled back, and once for each kind of misuse, such as\n * a wrapped tool that returned with a subscribe still in flight. Default:\n * console.warn.\n */\n onWarning?: (message: string) => void;\n}\n\n/** Which app a key is, as Wakeshift says (wake.app()). */\nexport interface AppInfo {\n id: string;\n name: string;\n /** The key: the console's ID for it, and its name (\"\" if Wakeshift didn't say). */\n key: { id: string; name: string };\n}\n\n/**\n * @internal A tool call as Wakeshift takes it: who called, from which\n * client, in which conversation. The wrapper (attached.events) and attach's\n * own tools pack it.\n */\nexport interface Call {\n /** The app's own ID for the person (optional). */\n user?: string;\n /** The MCP client's name (initialize's clientInfo.name); a stateless server has none. */\n client: string;\n /** The tool call's _meta (Codex sends its thread there). */\n meta?: Record<string, unknown>;\n /** The session handle an earlier result gave the agent. */\n session?: string;\n /** The MCP request's HTTP User-Agent. */\n user_agent?: string;\n /** The conversation's ID as the agent passed it (conversation_id). */\n conversation?: string;\n /** The program the agent says it runs in (harness): a hint, never a credential. */\n harness?: string;\n /** The name of the tool being called: a connector beacon in its result names it. */\n tool?: string;\n}\n\n/**\n * What Wakeshift recognized the calling conversation's harness as, and by\n * which signal (\"claim\": only the agent's harness argument named it); both\n * null when nothing named one. claimed is what the agent said (normalized:\n * \"Grok Bot\" is grok-bot), null if it didn't; a claimed that differs from\n * harness was ignored, since it contradicted what the call was recognized\n * as (the claim only refines it: Cursor's calls may be Grok Bot's).\n */\nexport interface Recognized {\n harness: string | null;\n via: \"client\" | \"meta\" | \"user_agent\" | \"claim\" | null;\n claimed: string | null;\n}\n\n/**\n * Seconds, or a string like \"90s\", \"5m\", \"2h\", \"30d\". Wakeshift checks the\n * value: days must be whole (\"1.5d\" is a bad_request; use \"36h\").\n */\nexport type Duration = number | `${number}${\"s\" | \"m\" | \"h\" | \"d\"}`;\n\n/**\n * One recipient of a personal event's emit, beside a plain user (the app's\n * ID for them: every subscription they have to the event with these\n * arguments): `{ user, subscription }`, exactly that subscription of that\n * user's; `{ native: user }`, only that user's native (webhook)\n * subscriptions to the event with these arguments.\n */\nexport type Recipient = { user: string; subscription: string } | { native: string };\n\n/** What an event's emit did. */\nexport interface Emitted {\n /** Conversations it woke (or will). */\n matched: number;\n /** An earlier emit had this occurrence's id. */\n duplicate: boolean;\n /** User and native recipients with no live subscription it reached (an emit to several recipients only). */\n unmatched: (string | Recipient)[];\n /** Subscription recipients no longer live (or not that user's). */\n ended: (string | Recipient)[];\n}\n\n// recipientsOf reads an emit's unmatched or ended list: \"user\",\n// { native: user } or { user, subscription }.\nfunction recipientsOf(raw: unknown): (string | Recipient)[] {\n if (!Array.isArray(raw)) return [];\n const out: (string | Recipient)[] = [];\n for (const r of raw) {\n if (typeof r === \"string\") out.push(r);\n else if (r && typeof r === \"object\") {\n const m = r as Record<string, unknown>;\n if (typeof m.native === \"string\" && m.native) out.push({ native: m.native });\n else if (typeof m.user === \"string\") out.push({ user: m.user, subscription: typeof m.subscription === \"string\" ? m.subscription : \"\" });\n }\n }\n return out;\n}\n\n/**\n * How a connected conversation receives what it's woken by: stream (it holds\n * a connection to Wakeshift open), poll (it asked Wakeshift for messages\n * within the last minute), hooks (Wakeshift's connector on the user's\n * computer delivers to it) or webhook (its client subscribed with MCP\n * Events, and Wakeshift sends to the client's webhook).\n */\nexport type Via = \"stream\" | \"poll\" | \"hooks\" | \"webhook\";\n\n/** An event's publish URL (`event.publishUrl`). */\nexport interface PublishUrl {\n id: string;\n event?: string;\n url: string;\n}\n\n/** An event pattern a manifest asks for, and what the person is told it's for. */\nexport interface ScopeEvent {\n pattern: string;\n description: string;\n}\n\n/** What the app may do with the agents in the workspaces it keeps (manifest.agent). */\nexport interface AgentScope {\n wake: ScopeEvent[];\n post: ScopeEvent[];\n /** Days the person's consent lasts. */\n ttl_days: number;\n /** At most max wake-ups in any seconds, on top of Wakeshift's own limits. */\n wake_limits?: { seconds: number; max: number }[];\n /** What the person should say to their agent once it's connected; at most 120 characters. */\n start_prompt?: string;\n}\n\n/** What the app tells Wakeshift it may do (see wake.publishManifest). */\nexport interface Manifest {\n description?: string;\n agent?: AgentScope;\n /** Event types defined elsewhere, not with defineEvent: Wakeshift gets these, then the defined ones. Listing a defined one is an error. */\n events?: EventTypeManifest[];\n /** Your app wakes its users' agents with what other people and their agents do there (messages, moves): the consent screen says agents of people they don't know can wake theirs. */\n others_can_wake?: boolean;\n /**\n * Your MCP tools (as your server lists them) that agents' programs can run without asking each time:\n * tools that only read, and routine ones the agent calls on every wake that reach only what it already joined.\n * Never one that deletes, spends, or reaches people the user hasn't chosen. When a user connects Claude Code\n * or Cursor CLI, Wakeshift offers to allow exactly these, by name, in the same question as its install.\n * Letters, digits, _ and -; at most 20.\n */\n preapprove_tools?: string[];\n}\n\n/** The parts of an MCP tool callback's `extra` that Wakeshift reads. */\nexport interface ToolExtra {\n _meta?: Record<string, unknown>;\n requestInfo?: { headers?: Record<string, string | string[] | undefined> };\n}\n\n// userAgentOf is the User-Agent of the HTTP request a tool call came in\n// (\"\" if there's none, e.g. over stdio).\nfunction userAgentOf(extra: ToolExtra | undefined): string {\n const headers = extra?.requestInfo?.headers;\n if (!headers) return \"\";\n const v = headers[\"user-agent\"] ?? headers[\"User-Agent\"];\n return (Array.isArray(v) ? v[0] : v) ?? \"\";\n}\n\n/** @internal Packs a tool call as Wakeshift takes it: empty fields left out, the agent's claims trimmed. */\nexport function packCall(c: {\n meta?: Record<string, unknown>;\n clientName: string;\n user?: string;\n session?: string;\n userAgent?: string;\n harness?: string;\n conversation?: string;\n tool?: string;\n}): Call {\n const out: Call = { client: c.clientName ?? \"\" };\n if (c.user) out.user = c.user;\n if (c.meta && Object.keys(c.meta).length > 0) out.meta = c.meta;\n if (c.session) out.session = c.session;\n if (c.userAgent) out.user_agent = c.userAgent;\n if (c.harness?.trim()) out.harness = c.harness.trim();\n if (c.conversation?.trim()) out.conversation = c.conversation.trim();\n if (c.tool?.trim()) out.tool = c.tool.trim();\n return out;\n}\n\n/**\n * @internal The call to one of attach's own tools (subscribe_events and the\n * others): its _meta and User-Agent, the client's name, the user, and\n * session_key, harness and conversation_id from its arguments.\n */\nexport function toolCallOf(extra: ToolExtra | undefined, client: string, user: string | undefined, args: Record<string, unknown>, tool: string): Call {\n return packCall({\n meta: extra?._meta,\n clientName: client,\n user,\n session: str(args, SESSION_ARG),\n userAgent: userAgentOf(extra),\n harness: str(args, HARNESS_ARG),\n conversation: str(args, CONVERSATION_ARG),\n tool,\n });\n}\n\n// str is a tool argument's value if it's a string.\nfunction str(args: Record<string, unknown> | undefined, name: string): string | undefined {\n return typeof args?.[name] === \"string\" ? (args[name] as string) : undefined;\n}\n\n/**\n * The Wakeshift client for an app: define the events your app offers,\n * attach them to your MCP server, and emit them when they happen.\n */\nexport class Wakeshift {\n readonly core: string;\n private readonly key: AppKey;\n // The app's ID: from the key, if it names the app, or else from app().\n private knownAppId: string | null;\n private appInfo?: Promise<AppInfo>;\n private readonly fetchFn: typeof fetch;\n private readonly timeoutMs: number;\n private readonly warnFn: (message: string) => void;\n private readonly warned = new Set<string>();\n\n constructor(opts: WakeshiftOptions) {\n if (!opts?.key) throw new Error(\"wakeshift: no app key (WAKESHIFT_KEY?)\");\n this.key = parseKey(opts.key);\n this.knownAppId = this.key.appId;\n // Test keys come from staging and local consoles, and one sent to\n // production fails in a way that's hard to read: ask for the core.\n const core = opts.core || process.env.WAKESHIFT_CORE || (isTestKey(opts.key) ? \"\" : DEFAULT_CORE);\n if (!core) {\n throw new Error(\n \"wakeshift: no core URL for this test key: set WAKESHIFT_CORE, or pass { core }, to the address of the console the key came from (for example https://app.staging.wakeshift.ai)\",\n );\n }\n this.core = core.replace(/\\/+$/, \"\");\n // A request the load balancer refused during a rollout is sent again (retry.ts).\n this.fetchFn = retryRefused(opts.fetch ?? globalThis.fetch);\n this.timeoutMs = opts.timeoutMs ?? 20_000;\n this.warnFn = opts.onWarning ?? ((m) => console.warn(m));\n }\n\n /**\n * The app's ID. An older key (wst_test_…, wst_live_…) names it; for a\n * current key, which doesn't, this throws until `await wake.app()` has\n * asked Wakeshift.\n */\n get appId(): string {\n if (!this.knownAppId) throw new Error(\"wakeshift: call await wake.app() first: this key doesn't name its app\");\n return this.knownAppId;\n }\n\n /**\n * Which app the key is, as Wakeshift says: its ID and name, and the\n * key's. Asks once\n * (GET /api/apps/v1/app) and remembers the answer; afterwards\n * `wake.appId` works for any key.\n */\n app(): Promise<AppInfo> {\n this.appInfo ??= this.request<{ id?: unknown; name?: unknown; key?: { key_id?: unknown; name?: unknown } }>(\"GET\", \"/app\")\n .then((r) => {\n if (typeof r.id !== \"string\" || !r.id) {\n throw new WakeshiftError(200, \"bad_response\", `Wakeshift at ${this.core} didn't say which app this key is`);\n }\n const id = this.knownAppId ?? r.id;\n this.knownAppId = id;\n const str = (v: unknown) => (typeof v === \"string\" ? v : \"\");\n return { id, name: str(r.name), key: { id: str(r.key?.key_id), name: str(r.key?.name) } };\n })\n .catch((err: unknown) => {\n this.appInfo = undefined; // a later call asks again\n throw err;\n });\n return this.appInfo;\n }\n\n /** @internal The app's ID if it's known yet (the key names it, or app() has answered), else null. */\n knownApp(): string | null {\n return this.knownAppId;\n }\n\n // A fresh assertion of the app's identity, naming the app once it's known.\n private assertion(): string {\n return signAssertion(this.key, this.core, Date.now(), this.knownAppId);\n }\n\n /** @internal Reports a problem through onWarning, every time. */\n warn(message: string): void {\n this.warnFn(message);\n }\n\n /** @internal Reports a warning, once per kind. */\n warnOnce(kind: string, message: string): void {\n if (this.warned.has(kind)) return;\n this.warned.add(kind);\n this.warnFn(message);\n }\n\n /** Stops a publish URL working (410 from then on). */\n async revokePublishUrl(id: string): Promise<void> {\n await this.request(\"DELETE\", `/events/publish-urls/${encodeURIComponent(id)}`);\n }\n\n /**\n * Deletes everything Wakeshift keeps for one of the app's users: their\n * conversations, subscriptions, events and deliveries, publish URLs for\n * them, and their ID. Open streams close. Returns false if there was nothing to forget.\n */\n async forgetUser(user: string): Promise<boolean> {\n return (await this.request<{ forgotten: boolean }>(\"POST\", \"/users/forget\", { user })).forgotten;\n }\n\n /**\n * Tells Wakeshift what the app may do, replacing what it said before: m,\n * with the events you defined (defineEvent) after m's own events. An\n * event both defined and listed in m.events is an error, and nothing is\n * sent. You needn't call it: a process that serves your tools (attach)\n * sends the manifest automatically, merged into the one Wakeshift has.\n * Call it to remove an event or clear a setting. Once called, m's\n * settings are what every automatic send carries (even if this one\n * failed), with the events defined by then. Returns the manifest as\n * Wakeshift keeps it.\n */\n async publishManifest(m: Manifest): Promise<Manifest> {\n const version = this.manifestVersion; // before the body: a later defineEvent is sent again\n const body = this.manifestBody(m);\n this.manifestBase = m;\n const run = this.serial(() => this.request<Manifest>(\"PUT\", \"/manifest\", body));\n this.track(run, version);\n return run;\n }\n\n // serial runs a send after every send before it, explicit or automatic,\n // so the last manifest Wakeshift gets is the newest.\n private sending: Promise<unknown> = Promise.resolve();\n private serial<T>(send: () => Promise<T>): Promise<T> {\n const run = this.sending.then(send, send);\n this.sending = run.catch(() => undefined);\n return run;\n }\n\n // track makes a send the one event calls wait for: once it's done,\n // Wakeshift has the manifest for the events defined at version, unless it\n // failed (the next call sends again) or an event was defined since.\n private track(send: Promise<unknown>, version: number): void {\n const p: Promise<void> = send.then(() => {\n if (this.manifestVersion !== version && this.published === p) this.published = null;\n });\n this.published = p;\n p.catch(() => {\n if (this.published === p) this.published = null;\n });\n }\n\n // The manifest as Wakeshift gets it: m's events, then the defined ones,\n // refusing a name in both.\n private manifestBody(m: Manifest): Manifest {\n const listed = m.events ?? [];\n for (const name of this.events.keys()) {\n if (listed.some((e) => e.name === name)) {\n throw new Error(`wakeshift: event ${name} is defined with defineEvent and listed in the manifest's events: keep one`);\n }\n }\n const events = [...listed, ...[...this.events.values()].map((e) => e.manifest)];\n const { events: _listed, ...rest } = m;\n return events.length > 0 ? { ...rest, events } : rest;\n }\n\n // The automatic send, from a process that serves the app's tools: the\n // settings the app last published (only those it set), with the defined\n // events, merged into the manifest Wakeshift has, so it never removes an\n // event or clears a setting another process sent.\n private async sendManifest(): Promise<void> {\n const body: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(this.manifestBody(this.manifestBase ?? {}))) {\n if (v === undefined || v === null || v === \"\" || v === false || (Array.isArray(v) && v.length === 0)) continue;\n body[k] = v;\n }\n if (!body.events) return; // nothing to add (attach refuses with no events, but never send an empty list)\n await this.request(\"POST\", \"/manifest/merge\", body);\n }\n\n // ── Events (MCP Events, natively or bridged) ──────────────────────────\n\n private readonly events = new Map<string, WakeEvent>();\n // What publishManifest was last given (null: nothing yet); whether this\n // process serves the app's tools (attach: only then is the manifest sent\n // automatically); whether Wakeshift has the manifest for the events\n // defined now (the send; null: not yet, or a defineEvent since); and how\n // many defineEvents there were.\n private manifestBase: Manifest | null = null;\n private serving = false;\n private published: Promise<void> | null = null;\n private manifestVersion = 0;\n\n /**\n * Defines one of the app's event types: what a subscriber picks (args),\n * what each occurrence carries (payload), and the line an agent reads\n * first (text). Returns the event, whose emit sends occurrences. Define\n * every event before attach.\n *\n * const message = wake.defineEvent(\"chat.message\", {\n * description: \"A new message in a channel\",\n * args: z.object({ channel: z.string() }),\n * payload: z.object({ from: z.string(), text: z.string() }),\n * text: (m) => `${m.from}: ${m.text}`,\n * })\n * await message.emit({ channel: \"eng\" }, { from: \"ada\", text: \"shipped\" })\n */\n defineEvent<A extends AnySchema, P extends AnySchema>(name: string, opts: EventOptions<A, P>): WakeEvent<A, P> {\n if (this.events.has(name)) throw new Error(`wakeshift: event ${name} is defined twice`);\n const ev = new WakeEvent<A, P>(this, name, opts);\n this.events.set(name, ev as unknown as WakeEvent);\n this.published = null; // the manifest changed: sent again when next needed\n this.manifestVersion++;\n return ev;\n }\n\n /**\n * Attaches Wakeshift to your MCP server, before you connect it: the one\n * call that connects the two. Today it serves the defined events: MCP\n * Events (events/list, events/subscribe, events/unsubscribe) for clients\n * that speak it, such as ChatGPT, and the subscribe_events tool for\n * everyone else, whom Wakeshift wakes its own ways; plus\n * unsubscribe_events and list_subscriptions for every client, so a person\n * can always see and stop what they're subscribed to.\n *\n * const attached = wake.attach(server, { identify: (extra) => ({ user: myUser(extra) }) })\n *\n * It returns the handle your own tools use to subscribe the conversation\n * calling them: wrap a tool's callback with attached.events, and give it\n * Wakeshift's arguments with attached.inputs.\n */\n attach(server: McpServer, opts: AttachOptions = {}): Attached {\n const attached = attachEvents(this, server, [...this.events.values()], opts);\n this.serving = true; // the manifest is sent automatically from now on\n return attached;\n }\n\n /**\n * @internal Sends the manifest with the defined events, once (again after\n * a defineEvent), from a process that serves the app's tools (attach). A\n * process that only emits never sends it: its events may be fewer, or\n * older, than its server's.\n */\n ensureEvents(): Promise<void> {\n if (!this.serving) return Promise.resolve();\n if (!this.published) this.track(this.serial(() => this.sendManifest()), this.manifestVersion);\n return this.published!;\n }\n\n /** @internal An event's emit. */\n async emitEvent(e: { name: string; arguments: unknown; payload: unknown; text: string; id?: string; to?: string | (string | Recipient)[] }): Promise<Emitted> {\n await this.ensureEvents();\n const body: Record<string, unknown> = { name: e.name, arguments: e.arguments, payload: e.payload, text: e.text };\n if (e.id) body.id = e.id;\n if (e.to) body.to = e.to;\n const out = await this.request<{ matched: number; duplicate?: boolean; unmatched?: unknown; ended?: unknown }>(\"POST\", \"/events/emit\", body);\n return { matched: out.matched, duplicate: !!out.duplicate, unmatched: recipientsOf(out.unmatched), ended: recipientsOf(out.ended) };\n }\n\n /** @internal A call to the app API (the events machinery's), after the manifest with the defined events is published. */\n async requestApp<T>(method: string, path: string, body?: unknown): Promise<T> {\n await this.ensureEvents();\n return this.request<T>(method, path, body);\n }\n\n // ── Users' workspaces ──────────────────────────────────────────────────\n\n /**\n * The workspace Wakeshift keeps for one of the app's users (user: the\n * app's own ID for them, as attach's identify gives it), created on first\n * use. Wakeshift keeps that user's conversations there.\n */\n async workspace(user: string, name: string): Promise<string> {\n return (await this.request<{ workspace: string }>(\"POST\", \"/workspaces\", { external_id: user, name })).workspace;\n }\n\n /** Creates an agent in one of the app's workspaces (if new), and its grant for the app's manifest scope. Returns the grant's ID. */\n async addAgent(workspace: string, agent: string, displayName: string): Promise<string> {\n return (await this.request<{ grant: string }>(\"POST\", `/workspaces/${encodeURIComponent(workspace)}/agents`, { agent, display_name: displayName })).grant;\n }\n\n /**\n * Checks that one of the app's agents still has a live grant, asking\n * Wakeshift each time. Throws a WakeshiftError: no_grant once the grant is\n * revoked, unknown_workspace once the workspace is forgotten.\n */\n async checkAgent(workspace: string, agent: string): Promise<void> {\n await this.request(\"POST\", `/workspaces/${encodeURIComponent(workspace)}/agents/${encodeURIComponent(agent)}/token`);\n }\n\n private async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const headers: Record<string, string> = { Authorization: \"Bearer \" + this.assertion() };\n if (body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n let resp: Response;\n let text: string;\n try {\n resp = await this.fetchFn(this.core + \"/api/apps/v1\" + path, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n text = await resp.text();\n } catch (err) {\n throw this.unreachable(err);\n }\n let json: any;\n try {\n json = text ? JSON.parse(text) : undefined;\n } catch {\n json = undefined;\n }\n if (!resp.ok) {\n // Wakeshift's code, message and reason where it sent them as strings, else\n // the body's start, else the status's text, as every SDK reads it (test/errors.json).\n const e = json?.error !== null && typeof json?.error === \"object\" ? json.error : {};\n const str = (v: unknown) => (typeof v === \"string\" ? v : \"\");\n throw new WakeshiftError(resp.status, str(e.code), str(e.message) || text.slice(0, 200) || resp.statusText, {\n reason: str(e.reason) || undefined,\n });\n }\n // A 2xx that isn't Wakeshift's JSON: a proxy's page, or a wrong core.\n if (json === null || typeof json !== \"object\" || Array.isArray(json)) {\n throw new WakeshiftError(\n resp.status,\n \"bad_response\",\n `Wakeshift at ${this.core} answered ${resp.status} without a JSON object. Check that WAKESHIFT_CORE, or the core option, is the address of the console your key came from`,\n );\n }\n return json as T;\n }\n\n // A request that got no answer. Name the core it went to: a wrong or\n // missing WAKESHIFT_CORE is the usual cause.\n private unreachable(err: unknown): WakeshiftError {\n const e = err as { name?: string; message?: string; cause?: { code?: string; message?: string } } | undefined;\n const why =\n e?.name === \"TimeoutError\" || e?.name === \"AbortError\"\n ? `no answer within ${this.timeoutMs / 1000}s`\n : [e?.message, e?.cause?.code ?? e?.cause?.message].filter(Boolean).join(\": \") || String(err);\n return new WakeshiftError(\n 0,\n \"unreachable\",\n `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`,\n { cause: err },\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"wakeshift.js","sourceRoot":"","sources":["../src/wakeshift.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAG7C,OAAO,EAAE,KAAK,EAAY,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,YAAY,EAAiE,MAAM,aAAa,CAAC;AAErH,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAe,SAAS,EAAE,MAAM,UAAU,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,iIAAiI;AACjI,MAAM,CAAC,MAAM,YAAY,GAAG,0BAA0B,CAAC;AAEvD,oFAAoF;AACpF,MAAM,CAAC,MAAM,WAAW,GAAG,aAAa,CAAC;AAEzC,qEAAqE;AACrE,MAAM,CAAC,MAAM,WAAW,GAAG,SAAS,CAAC;AAErC;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,iBAAiB,CAAC;AA0GlD,gEAAgE;AAChE,8CAA8C;AAC9C,SAAS,YAAY,CAAC,GAAY;IAChC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;QAAE,OAAO,EAAE,CAAC;IACnC,MAAM,GAAG,GAA2B,EAAE,CAAC;IACvC,KAAK,MAAM,CAAC,IAAI,GAAG,EAAE,CAAC;QACpB,IAAI,OAAO,CAAC,KAAK,QAAQ;YAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;aAClC,IAAI,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,EAAE,CAAC;YACpC,MAAM,CAAC,GAAG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CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,IAAI,CAAC,UAAU,EAAE;gBAC1G,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,SAAS;aACnC,CAAC,CAAC;QACL,CAAC;QACD,sEAAsE;QACtE,IAAI,IAAI,KAAK,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;YACrE,MAAM,IAAI,cAAc,CACtB,IAAI,CAAC,MAAM,EACX,cAAc,EACd,gBAAgB,IAAI,CAAC,IAAI,aAAa,IAAI,CAAC,MAAM,yHAAyH,CAC3K,CAAC;QACJ,CAAC;QACD,OAAO,IAAS,CAAC;IACnB,CAAC;IAED,qEAAqE;IACrE,6CAA6C;IACrC,WAAW,CAAC,GAAY,EAAE,SAAS,GAAG,IAAI,CAAC,SAAS;QAC1D,MAAM,CAAC,GAAG,GAAmG,CAAC;QAC9G,MAAM,GAAG,GACP,CAAC,EAAE,IAAI,KAAK,cAAc,IAAI,CAAC,EAAE,IAAI,KAAK,YAAY;YACpD,CAAC,CAAC,oBAAoB,SAAS,GAAG,IAAI,GAAG;YACzC,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,IAAI,IAAI,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC;QAClG,OAAO,IAAI,cAAc,CACvB,CAAC,EACD,aAAa,EACb,4BAA4B,IAAI,CAAC,IAAI,KAAK,GAAG,oGAAoG,EACjJ,EAAE,KAAK,EAAE,GAAG,EAAE,CACf,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { WakeshiftError } from \"./errors.js\";\nimport type { AnySchema } from \"./zod.js\";\nimport type { HostContext, McpServerLike } from \"./mcp.js\";\nimport { v1Req, type Req } from \"./host.js\";\nimport { WakeEvent, attachEvents, type AttachOptions, type EventOptions, type EventTypeManifest } from \"./events.js\";\nimport type { Attached } from \"./toolcall.js\";\nimport { parseKey, signAssertion, type AppKey, isTestKey } from \"./key.js\";\nimport { retryRefused } from \"./retry.js\";\nimport { takesTasks } from \"./discover.js\";\n\n/** Wakeshift's production core, the default for every key but an older wst_test_ one. Override with `core` or WAKESHIFT_CORE. */\nexport const DEFAULT_CORE = \"https://app.wakeshift.ai\";\n\n/** The tool argument an agent passes its session key in (a result gives it one). */\nexport const SESSION_ARG = \"session_key\";\n\n/** The tool argument an agent says which program it runs in with. */\nexport const HARNESS_ARG = \"harness\";\n\n/**\n * The tool argument an agent passes its own ID for the conversation in,\n * when its program gives it one (Cursor and Grok Bot: CURSOR_CONVERSATION_ID).\n */\nexport const CONVERSATION_ARG = \"conversation_id\";\n\nexport interface WakeshiftOptions {\n /** The app key from the console: wst_ and 50 characters (or an older wst_test_… or wst_live_… key). */\n key: string;\n /**\n * Wakeshift's base URL: the console you got the key from. Default:\n * WAKESHIFT_CORE from the environment, else https://app.wakeshift.ai.\n * An older wst_test_… key has no default: it needs one of the two.\n */\n core?: string;\n /** Default: the global fetch. */\n fetch?: typeof fetch;\n /** Per-request timeout in milliseconds. Default 20000. */\n timeoutMs?: number;\n /**\n * Called with a problem that doesn't fail the call but makes it work less\n * well: each time for a failure, such as a failed call's subscription\n * that couldn't be rolled back, and once for each kind of misuse, such as\n * a wrapped tool that returned with a subscribe still in flight. Default:\n * console.warn.\n */\n onWarning?: (message: string) => void;\n}\n\n/** @internal How one request to Wakeshift differs: a longer timeout, and a signal that ends it early. */\nexport interface RequestOptions {\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\n/** Which app a key is, as Wakeshift says (wake.app()). */\nexport interface AppInfo {\n id: string;\n name: string;\n /** The key: the console's ID for it, and its name (\"\" if Wakeshift didn't say). */\n key: { id: string; name: string };\n}\n\n/**\n * @internal A tool call as Wakeshift takes it: who called, from which\n * client, in which conversation. The wrapper (attached.events) and attach's\n * own tools pack it.\n */\nexport interface Call {\n /** The app's own ID for the person (optional). */\n user?: string;\n /** The MCP client's name (initialize's clientInfo.name); a stateless server has none. */\n client: string;\n /** The tool call's _meta (Codex sends its thread there). */\n meta?: Record<string, unknown>;\n /** The session handle an earlier result gave the agent. */\n session?: string;\n /** The MCP request's HTTP User-Agent. */\n user_agent?: string;\n /** The conversation's ID as the agent passed it (conversation_id). */\n conversation?: string;\n /** The program the agent says it runs in (harness): a hint, never a credential. */\n harness?: string;\n /** The name of the tool being called: a connector beacon in its result names it. */\n tool?: string;\n /** The client takes MCP tasks (protocol 2026-07-28 with the tasks extension), and attach serves the wait tool for it (tasks.ts). */\n tasks?: boolean;\n}\n\n/**\n * What Wakeshift recognized the calling conversation's harness as, and by\n * which signal (\"claim\": only the agent's harness argument named it); both\n * null when nothing named one. claimed is what the agent said (normalized:\n * \"Grok Bot\" is grok-bot), null if it didn't; a claimed that differs from\n * harness was ignored, since it contradicted what the call was recognized\n * as (the claim only refines it: Cursor's calls may be Grok Bot's).\n */\nexport interface Recognized {\n harness: string | null;\n via: \"client\" | \"meta\" | \"user_agent\" | \"claim\" | null;\n claimed: string | null;\n}\n\n/**\n * Seconds, or a string like \"90s\", \"5m\", \"2h\", \"30d\". Wakeshift checks the\n * value: days must be whole (\"1.5d\" is a bad_request; use \"36h\").\n */\nexport type Duration = number | `${number}${\"s\" | \"m\" | \"h\" | \"d\"}`;\n\n/**\n * One recipient of a personal event's emit, beside a plain user (the app's\n * ID for them: every subscription they have to the event with these\n * arguments): `{ user, subscription }`, exactly that subscription of that\n * user's; `{ native: user }`, only that user's native (webhook)\n * subscriptions to the event with these arguments.\n */\nexport type Recipient = { user: string; subscription: string } | { native: string };\n\n/** What an event's emit did. */\nexport interface Emitted {\n /** Conversations it woke (or will). */\n matched: number;\n /** An earlier emit had this occurrence's id. */\n duplicate: boolean;\n /** User and native recipients with no live subscription it reached (an emit to several recipients only). */\n unmatched: (string | Recipient)[];\n /** Subscription recipients no longer live (or not that user's). */\n ended: (string | Recipient)[];\n}\n\n// recipientsOf reads an emit's unmatched or ended list: \"user\",\n// { native: user } or { user, subscription }.\nfunction recipientsOf(raw: unknown): (string | Recipient)[] {\n if (!Array.isArray(raw)) return [];\n const out: (string | Recipient)[] = [];\n for (const r of raw) {\n if (typeof r === \"string\") out.push(r);\n else if (r && typeof r === \"object\") {\n const m = r as Record<string, unknown>;\n if (typeof m.native === \"string\" && m.native) out.push({ native: m.native });\n else if (typeof m.user === \"string\") out.push({ user: m.user, subscription: typeof m.subscription === \"string\" ? m.subscription : \"\" });\n }\n }\n return out;\n}\n\n/**\n * How a connected conversation receives what it's woken by: stream (it holds\n * a connection to Wakeshift open), poll (it asked Wakeshift for messages\n * within the last minute), hooks (Wakeshift's connector on the user's\n * computer delivers to it) or webhook (its client subscribed with MCP\n * Events, and Wakeshift sends to the client's webhook).\n */\nexport type Via = \"stream\" | \"poll\" | \"hooks\" | \"webhook\";\n\n/** An event's publish URL (`event.publishUrl`). */\nexport interface PublishUrl {\n id: string;\n event?: string;\n url: string;\n}\n\n/** An event pattern a manifest asks for, and what the person is told it's for. */\nexport interface ScopeEvent {\n pattern: string;\n description: string;\n}\n\n/** What the app may do with the agents in the workspaces it keeps (manifest.agent). */\nexport interface AgentScope {\n wake: ScopeEvent[];\n post: ScopeEvent[];\n /** Days the person's consent lasts. */\n ttl_days: number;\n /** At most max wake-ups in any seconds, on top of Wakeshift's own limits. */\n wake_limits?: { seconds: number; max: number }[];\n /** What the person should say to their agent once it's connected; at most 120 characters. */\n start_prompt?: string;\n}\n\n/** What the app tells Wakeshift it may do (see wake.publishManifest). */\nexport interface Manifest {\n description?: string;\n agent?: AgentScope;\n /** Event types defined elsewhere, not with defineEvent: Wakeshift gets these, then the defined ones. Listing a defined one is an error. */\n events?: EventTypeManifest[];\n /** Your app wakes its users' agents with what other people and their agents do there (messages, moves): the consent screen says agents of people they don't know can wake theirs. */\n others_can_wake?: boolean;\n /**\n * Your MCP tools (as your server lists them) that agents' programs can run without asking each time:\n * tools that only read, and routine ones the agent calls on every wake that reach only what it already joined.\n * Never one that deletes, spends, or reaches people the user hasn't chosen. When a user connects Claude Code\n * or Cursor CLI, Wakeshift offers to allow exactly these, by name, in the same question as its install.\n * Letters, digits, _ and -; at most 20.\n */\n preapprove_tools?: string[];\n}\n\n/** The parts of an MCP tool callback's `extra` that Wakeshift reads. */\nexport interface ToolExtra {\n _meta?: Record<string, unknown>;\n requestInfo?: { headers?: Record<string, string | string[] | undefined> };\n}\n\n/** @internal The User-Agent of the HTTP request a tool call came in (\"\" if there's none, e.g. over stdio). */\nexport function userAgentOf(req: Req): string {\n return req.header(\"user-agent\") || req.header(\"User-Agent\");\n}\n\n/** @internal Packs a tool call as Wakeshift takes it: empty fields left out, the agent's claims trimmed. */\nexport function packCall(c: {\n meta?: Record<string, unknown>;\n clientName: string;\n user?: string;\n session?: string;\n userAgent?: string;\n harness?: string;\n conversation?: string;\n tool?: string;\n tasks?: boolean;\n}): Call {\n const out: Call = { client: c.clientName ?? \"\" };\n if (c.user) out.user = c.user;\n if (c.meta && Object.keys(c.meta).length > 0) out.meta = c.meta;\n if (c.session) out.session = c.session;\n if (c.userAgent) out.user_agent = c.userAgent;\n if (c.harness?.trim()) out.harness = c.harness.trim();\n if (c.conversation?.trim()) out.conversation = c.conversation.trim();\n if (c.tool?.trim()) out.tool = c.tool.trim();\n if (c.tasks) out.tasks = true;\n return out;\n}\n\n/**\n * @internal The call to one of attach's own tools (subscribe_events and the\n * others): its _meta and User-Agent, the client's name, the user, and\n * session_key, harness and conversation_id from its arguments.\n */\nexport function toolCallOf(extra: Req | ToolExtra | undefined, client: string, user: string | undefined, args: Record<string, unknown>, tool: string): Call {\n const req = v1Req(extra); // a request already read passes through\n return packCall({\n meta: req.meta,\n clientName: client,\n user,\n session: str(args, SESSION_ARG),\n userAgent: userAgentOf(req),\n harness: str(args, HARNESS_ARG),\n conversation: str(args, CONVERSATION_ARG),\n tool,\n tasks: takesTasks(req.meta, req),\n });\n}\n\n// str is a tool argument's value if it's a string.\nfunction str(args: Record<string, unknown> | undefined, name: string): string | undefined {\n return typeof args?.[name] === \"string\" ? (args[name] as string) : undefined;\n}\n\n/**\n * The Wakeshift client for an app: define the events your app offers,\n * attach them to your MCP server, and emit them when they happen.\n */\nexport class Wakeshift {\n readonly core: string;\n private readonly key: AppKey;\n // The app's ID: from the key, if it names the app, or else from app().\n private knownAppId: string | null;\n private appInfo?: Promise<AppInfo>;\n private readonly fetchFn: typeof fetch;\n private readonly timeoutMs: number;\n private readonly warnFn: (message: string) => void;\n private readonly warned = new Set<string>();\n\n constructor(opts: WakeshiftOptions) {\n if (!opts?.key) throw new Error(\"wakeshift: no app key (WAKESHIFT_KEY?)\");\n this.key = parseKey(opts.key);\n this.knownAppId = this.key.appId;\n // Test keys come from staging and local consoles, and one sent to\n // production fails in a way that's hard to read: ask for the core.\n const core = opts.core || process.env.WAKESHIFT_CORE || (isTestKey(opts.key) ? \"\" : DEFAULT_CORE);\n if (!core) {\n throw new Error(\n \"wakeshift: no core URL for this test key: set WAKESHIFT_CORE, or pass { core }, to the address of the console the key came from (for example https://app.staging.wakeshift.ai)\",\n );\n }\n this.core = core.replace(/\\/+$/, \"\");\n // A request the load balancer refused during a rollout is sent again (retry.ts).\n this.fetchFn = retryRefused(opts.fetch ?? globalThis.fetch);\n this.timeoutMs = opts.timeoutMs ?? 20_000;\n this.warnFn = opts.onWarning ?? ((m) => console.warn(m));\n }\n\n /**\n * The app's ID. An older key (wst_test_…, wst_live_…) names it; for a\n * current key, which doesn't, this throws until `await wake.app()` has\n * asked Wakeshift.\n */\n get appId(): string {\n if (!this.knownAppId) throw new Error(\"wakeshift: call await wake.app() first: this key doesn't name its app\");\n return this.knownAppId;\n }\n\n /**\n * Which app the key is, as Wakeshift says: its ID and name, and the\n * key's. Asks once\n * (GET /api/apps/v1/app) and remembers the answer; afterwards\n * `wake.appId` works for any key.\n */\n app(): Promise<AppInfo> {\n this.appInfo ??= this.request<{ id?: unknown; name?: unknown; key?: { key_id?: unknown; name?: unknown } }>(\"GET\", \"/app\")\n .then((r) => {\n if (typeof r.id !== \"string\" || !r.id) {\n throw new WakeshiftError(200, \"bad_response\", `Wakeshift at ${this.core} didn't say which app this key is`);\n }\n const id = this.knownAppId ?? r.id;\n this.knownAppId = id;\n const str = (v: unknown) => (typeof v === \"string\" ? v : \"\");\n return { id, name: str(r.name), key: { id: str(r.key?.key_id), name: str(r.key?.name) } };\n })\n .catch((err: unknown) => {\n this.appInfo = undefined; // a later call asks again\n throw err;\n });\n return this.appInfo;\n }\n\n /** @internal The app's ID if it's known yet (the key names it, or app() has answered), else null. */\n knownApp(): string | null {\n return this.knownAppId;\n }\n\n // A fresh assertion of the app's identity, naming the app once it's known.\n private assertion(): string {\n return signAssertion(this.key, this.core, Date.now(), this.knownAppId);\n }\n\n /** @internal Reports a problem through onWarning, every time. */\n warn(message: string): void {\n this.warnFn(message);\n }\n\n /** @internal Reports a warning, once per kind. */\n warnOnce(kind: string, message: string): void {\n if (this.warned.has(kind)) return;\n this.warned.add(kind);\n this.warnFn(message);\n }\n\n /** Stops a publish URL working (410 from then on). */\n async revokePublishUrl(id: string): Promise<void> {\n await this.request(\"DELETE\", `/events/publish-urls/${encodeURIComponent(id)}`);\n }\n\n /**\n * Deletes everything Wakeshift keeps for one of the app's users: their\n * conversations, subscriptions, events and deliveries, publish URLs for\n * them, and their ID. Open streams close. Returns false if there was nothing to forget.\n */\n async forgetUser(user: string): Promise<boolean> {\n return (await this.request<{ forgotten: boolean }>(\"POST\", \"/users/forget\", { user })).forgotten;\n }\n\n /**\n * Tells Wakeshift what the app may do, replacing what it said before: m,\n * with the events you defined (defineEvent) after m's own events. An\n * event both defined and listed in m.events is an error, and nothing is\n * sent. You needn't call it: a process that serves your tools (attach)\n * sends the manifest automatically, merged into the one Wakeshift has.\n * Call it to remove an event or clear a setting. Once called, m's\n * settings are what every automatic send carries (even if this one\n * failed), with the events defined by then. Returns the manifest as\n * Wakeshift keeps it.\n */\n async publishManifest(m: Manifest): Promise<Manifest> {\n const version = this.manifestVersion; // before the body: a later defineEvent is sent again\n const body = this.manifestBody(m);\n this.manifestBase = m;\n const run = this.serial(() => this.request<Manifest>(\"PUT\", \"/manifest\", body));\n this.track(run, version);\n return run;\n }\n\n // serial runs a send after every send before it, explicit or automatic,\n // so the last manifest Wakeshift gets is the newest.\n private sending: Promise<unknown> = Promise.resolve();\n private serial<T>(send: () => Promise<T>): Promise<T> {\n const run = this.sending.then(send, send);\n this.sending = run.catch(() => undefined);\n return run;\n }\n\n // track makes a send the one event calls wait for: once it's done,\n // Wakeshift has the manifest for the events defined at version, unless it\n // failed (the next call sends again) or an event was defined since.\n private track(send: Promise<unknown>, version: number): void {\n const p: Promise<void> = send.then(() => {\n if (this.manifestVersion !== version && this.published === p) this.published = null;\n });\n this.published = p;\n p.catch(() => {\n if (this.published === p) this.published = null;\n });\n }\n\n // The manifest as Wakeshift gets it: m's events, then the defined ones,\n // refusing a name in both.\n private manifestBody(m: Manifest): Manifest {\n const listed = m.events ?? [];\n for (const name of this.events.keys()) {\n if (listed.some((e) => e.name === name)) {\n throw new Error(`wakeshift: event ${name} is defined with defineEvent and listed in the manifest's events: keep one`);\n }\n }\n const events = [...listed, ...[...this.events.values()].map((e) => e.manifest)];\n const { events: _listed, ...rest } = m;\n return events.length > 0 ? { ...rest, events } : rest;\n }\n\n // The automatic send, from a process that serves the app's tools: the\n // settings the app last published (only those it set), with the defined\n // events, merged into the manifest Wakeshift has, so it never removes an\n // event or clears a setting another process sent.\n private async sendManifest(): Promise<void> {\n const body: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(this.manifestBody(this.manifestBase ?? {}))) {\n if (v === undefined || v === null || v === \"\" || v === false || (Array.isArray(v) && v.length === 0)) continue;\n body[k] = v;\n }\n if (!body.events) return; // nothing to add (attach refuses with no events, but never send an empty list)\n await this.request(\"POST\", \"/manifest/merge\", body);\n }\n\n // ── Events (MCP Events, natively or bridged) ──────────────────────────\n\n private readonly events = new Map<string, WakeEvent>();\n // What publishManifest was last given (null: nothing yet); whether this\n // process serves the app's tools (attach: only then is the manifest sent\n // automatically); whether Wakeshift has the manifest for the events\n // defined now (the send; null: not yet, or a defineEvent since); and how\n // many defineEvents there were.\n private manifestBase: Manifest | null = null;\n private serving = false;\n private published: Promise<void> | null = null;\n private manifestVersion = 0;\n\n /**\n * Defines one of the app's event types: what a subscriber picks (args),\n * what each occurrence carries (payload), and the line an agent reads\n * first (text). Returns the event, whose emit sends occurrences. Define\n * every event before attach.\n *\n * const message = wake.defineEvent(\"chat.message\", {\n * description: \"A new message in a channel\",\n * args: z.object({ channel: z.string() }),\n * payload: z.object({ from: z.string(), text: z.string() }),\n * text: (m) => `${m.from}: ${m.text}`,\n * })\n * await message.emit({ channel: \"eng\" }, { from: \"ada\", text: \"shipped\" })\n */\n defineEvent<A extends AnySchema, P extends AnySchema>(name: string, opts: EventOptions<A, P>): WakeEvent<A, P> {\n if (this.events.has(name)) throw new Error(`wakeshift: event ${name} is defined twice`);\n const ev = new WakeEvent<A, P>(this, name, opts);\n this.events.set(name, ev as unknown as WakeEvent);\n this.published = null; // the manifest changed: sent again when next needed\n this.manifestVersion++;\n return ev;\n }\n\n /**\n * Attaches Wakeshift to your MCP server, before you connect it: the one\n * call that connects the two. Today it serves the defined events: MCP\n * Events (events/list, events/subscribe, events/unsubscribe) for clients\n * that speak it, such as ChatGPT, and the subscribe_events tool for\n * everyone else, whom Wakeshift wakes its own ways; plus\n * unsubscribe_events and list_subscriptions for every client, so a person\n * can always see and stop what they're subscribed to.\n *\n * const attached = wake.attach(server, { identify: (extra) => ({ user: myUser(extra) }) })\n *\n * It returns the handle your own tools use to subscribe the conversation\n * calling them: wrap a tool's callback with attached.events, and give it\n * Wakeshift's arguments with attached.inputs.\n *\n * server is an McpServer from @modelcontextprotocol/server 2.x or\n * @modelcontextprotocol/sdk 1.x; identify gets that SDK's own request\n * context (2.x's ctx, 1.x's extra).\n */\n attach<S extends McpServerLike>(server: S, opts: AttachOptions<HostContext<S>> = {}): Attached<HostContext<S>> {\n const attached = attachEvents(this, server, [...this.events.values()], opts);\n this.serving = true; // the manifest is sent automatically from now on\n return attached;\n }\n\n /**\n * @internal Sends the manifest with the defined events, once (again after\n * a defineEvent), from a process that serves the app's tools (attach). A\n * process that only emits never sends it: its events may be fewer, or\n * older, than its server's.\n */\n ensureEvents(): Promise<void> {\n if (!this.serving) return Promise.resolve();\n if (!this.published) this.track(this.serial(() => this.sendManifest()), this.manifestVersion);\n return this.published!;\n }\n\n /** @internal An event's emit. */\n async emitEvent(e: { name: string; arguments: unknown; payload: unknown; text: string; id?: string; to?: string | (string | Recipient)[] }): Promise<Emitted> {\n await this.ensureEvents();\n const body: Record<string, unknown> = { name: e.name, arguments: e.arguments, payload: e.payload, text: e.text };\n if (e.id) body.id = e.id;\n if (e.to) body.to = e.to;\n const out = await this.request<{ matched: number; duplicate?: boolean; unmatched?: unknown; ended?: unknown }>(\"POST\", \"/events/emit\", body);\n return { matched: out.matched, duplicate: !!out.duplicate, unmatched: recipientsOf(out.unmatched), ended: recipientsOf(out.ended) };\n }\n\n /**\n * @internal A call to the app API (the events machinery's), after the\n * manifest with the defined events is published. opts: a longer timeout\n * (a held tasks/get), and a signal that ends it early.\n */\n async requestApp<T>(method: string, path: string, body?: unknown, opts: RequestOptions = {}): Promise<T> {\n await this.ensureEvents();\n return this.request<T>(method, path, body, opts);\n }\n\n // ── Users' workspaces ──────────────────────────────────────────────────\n\n /**\n * The workspace Wakeshift keeps for one of the app's users (user: the\n * app's own ID for them, as attach's identify gives it), created on first\n * use. Wakeshift keeps that user's conversations there.\n */\n async workspace(user: string, name: string): Promise<string> {\n return (await this.request<{ workspace: string }>(\"POST\", \"/workspaces\", { external_id: user, name })).workspace;\n }\n\n /** Creates an agent in one of the app's workspaces (if new), and its grant for the app's manifest scope. Returns the grant's ID. */\n async addAgent(workspace: string, agent: string, displayName: string): Promise<string> {\n return (await this.request<{ grant: string }>(\"POST\", `/workspaces/${encodeURIComponent(workspace)}/agents`, { agent, display_name: displayName })).grant;\n }\n\n /**\n * Checks that one of the app's agents still has a live grant, asking\n * Wakeshift each time. Throws a WakeshiftError: no_grant once the grant is\n * revoked, unknown_workspace once the workspace is forgotten.\n */\n async checkAgent(workspace: string, agent: string): Promise<void> {\n await this.request(\"POST\", `/workspaces/${encodeURIComponent(workspace)}/agents/${encodeURIComponent(agent)}/token`);\n }\n\n private async request<T>(method: string, path: string, body?: unknown, opts: RequestOptions = {}): Promise<T> {\n const headers: Record<string, string> = { Authorization: \"Bearer \" + this.assertion() };\n if (body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n let resp: Response;\n let text: string;\n const timeoutMs = Math.max(opts.timeoutMs ?? 0, this.timeoutMs);\n const timeout = AbortSignal.timeout(timeoutMs);\n try {\n resp = await this.fetchFn(this.core + \"/api/apps/v1\" + path, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: opts.signal ? AbortSignal.any([timeout, opts.signal]) : timeout,\n });\n text = await resp.text();\n } catch (err) {\n throw this.unreachable(err, timeoutMs);\n }\n let json: any;\n try {\n json = text ? JSON.parse(text) : undefined;\n } catch {\n json = undefined;\n }\n if (!resp.ok) {\n // Wakeshift's code, message and reason where it sent them as strings, else\n // the body's start, else the status's text, as every SDK reads it (test/errors.json).\n const e = json?.error !== null && typeof json?.error === \"object\" ? json.error : {};\n const str = (v: unknown) => (typeof v === \"string\" ? v : \"\");\n throw new WakeshiftError(resp.status, str(e.code), str(e.message) || text.slice(0, 200) || resp.statusText, {\n reason: str(e.reason) || undefined,\n });\n }\n // A 2xx that isn't Wakeshift's JSON: a proxy's page, or a wrong core.\n if (json === null || typeof json !== \"object\" || Array.isArray(json)) {\n throw new WakeshiftError(\n resp.status,\n \"bad_response\",\n `Wakeshift at ${this.core} answered ${resp.status} without a JSON object. Check that WAKESHIFT_CORE, or the core option, is the address of the console your key came from`,\n );\n }\n return json as T;\n }\n\n // A request that got no answer. Name the core it went to: a wrong or\n // missing WAKESHIFT_CORE is the usual cause.\n private unreachable(err: unknown, timeoutMs = this.timeoutMs): WakeshiftError {\n const e = err as { name?: string; message?: string; cause?: { code?: string; message?: string } } | undefined;\n const why =\n e?.name === \"TimeoutError\" || e?.name === \"AbortError\"\n ? `no answer within ${timeoutMs / 1000}s`\n : [e?.message, e?.cause?.code ?? e?.cause?.message].filter(Boolean).join(\": \") || String(err);\n return new WakeshiftError(\n 0,\n \"unreachable\",\n `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`,\n { cause: err },\n );\n }\n}\n"]}
|
package/dist/zod.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type * as z3 from "zod/v3";
|
|
2
|
+
import type * as z4 from "zod/v4/core";
|
|
3
|
+
/** A zod schema, from zod 3's API or zod 4's (classic or mini). */
|
|
4
|
+
export type AnySchema = z3.ZodTypeAny | z4.$ZodType;
|
|
5
|
+
/** An object schema, or any schema (as the MCP SDK takes it). */
|
|
6
|
+
export type AnyObjectSchema = z3.AnyZodObject | z4.$ZodObject | AnySchema;
|
|
7
|
+
/** A zod shape: { field: schema }. */
|
|
8
|
+
export type ZodRawShapeCompat = Record<string, AnySchema>;
|
|
9
|
+
/** What a schema parses to. */
|
|
10
|
+
export type SchemaOutput<S> = S extends z3.ZodTypeAny ? z3.infer<S> : S extends z4.$ZodType ? z4.output<S> : never;
|
|
11
|
+
/** What a schema takes. */
|
|
12
|
+
export type SchemaInput<S> = S extends z3.ZodTypeAny ? z3.input<S> : S extends z4.$ZodType ? z4.input<S> : never;
|
|
13
|
+
/** What a shape parses to, field by field. */
|
|
14
|
+
export type ShapeOutput<Shape extends ZodRawShapeCompat> = {
|
|
15
|
+
[K in keyof Shape]: SchemaOutput<Shape[K]>;
|
|
16
|
+
};
|
package/dist/zod.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// zod 3 and zod 4 side by side, without either MCP SDK: the types and
|
|
2
|
+
// helpers the SDK used to take from @modelcontextprotocol/sdk's
|
|
3
|
+
// zod-compat, so it loads whichever MCP SDK an app has (host.ts). The
|
|
4
|
+
// definitions follow that module's, so a schema is read, checked and
|
|
5
|
+
// rendered as JSON Schema the same way as before.
|
|
6
|
+
import * as z3rt from "zod/v3";
|
|
7
|
+
import * as z4mini from "zod/v4-mini";
|
|
8
|
+
/** @internal Whether a schema is zod 4's (classic or mini). */
|
|
9
|
+
export function isZ4Schema(s) {
|
|
10
|
+
return !!s?._zod;
|
|
11
|
+
}
|
|
12
|
+
/** @internal Whether a value is a zod schema of either major. */
|
|
13
|
+
export function isSchema(v) {
|
|
14
|
+
return !!v && typeof v === "object" && ("_def" in v || "_zod" in v);
|
|
15
|
+
}
|
|
16
|
+
/** @internal An object schema of a shape, in the zod API its fields use (zod 4 mini for an empty shape). */
|
|
17
|
+
export function objectFromShape(shape) {
|
|
18
|
+
const values = Object.values(shape);
|
|
19
|
+
if (values.length === 0)
|
|
20
|
+
return z4mini.object({});
|
|
21
|
+
if (values.every(isZ4Schema))
|
|
22
|
+
return z4mini.object(shape);
|
|
23
|
+
if (values.every((s) => !isZ4Schema(s)))
|
|
24
|
+
return z3rt.object(shape);
|
|
25
|
+
throw new Error("wakeshift: a shape mixes zod 3 and zod 4 schemas");
|
|
26
|
+
}
|
|
27
|
+
/** @internal Parses with either major. */
|
|
28
|
+
export function safeParse(schema, data) {
|
|
29
|
+
if (isZ4Schema(schema))
|
|
30
|
+
return z4mini.safeParse(schema, data);
|
|
31
|
+
return schema.safeParse(data);
|
|
32
|
+
}
|
|
33
|
+
/** @internal Parses with either major, allowing async refinements. */
|
|
34
|
+
export async function safeParseAsync(schema, data) {
|
|
35
|
+
if (isZ4Schema(schema))
|
|
36
|
+
return (await z4mini.safeParseAsync(schema, data));
|
|
37
|
+
return (await schema.safeParseAsync(data));
|
|
38
|
+
}
|
|
39
|
+
/** @internal An object schema's shape (undefined for anything else). */
|
|
40
|
+
export function getObjectShape(schema) {
|
|
41
|
+
if (!schema)
|
|
42
|
+
return undefined;
|
|
43
|
+
const raw = isZ4Schema(schema)
|
|
44
|
+
? schema._zod?.def?.shape
|
|
45
|
+
: schema.shape;
|
|
46
|
+
if (!raw)
|
|
47
|
+
return undefined;
|
|
48
|
+
if (typeof raw === "function") {
|
|
49
|
+
try {
|
|
50
|
+
return raw();
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return raw;
|
|
57
|
+
}
|
|
58
|
+
/** @internal A schema or shape as an object schema (a shape is wrapped); undefined if it's neither. */
|
|
59
|
+
export function normalizeObjectSchema(schema) {
|
|
60
|
+
if (!schema || typeof schema !== "object")
|
|
61
|
+
return undefined;
|
|
62
|
+
const s = schema;
|
|
63
|
+
if (!s._def && !s._zod) {
|
|
64
|
+
const values = Object.values(schema);
|
|
65
|
+
const looksLikeShape = values.length > 0 &&
|
|
66
|
+
values.every((v) => typeof v === "object" && v !== null && (v._def !== undefined || v._zod !== undefined || typeof v.parse === "function"));
|
|
67
|
+
if (looksLikeShape)
|
|
68
|
+
return objectFromShape(schema);
|
|
69
|
+
}
|
|
70
|
+
if (isZ4Schema(schema)) {
|
|
71
|
+
const def = s._zod?.def;
|
|
72
|
+
if (def && (def.type === "object" || def.shape !== undefined))
|
|
73
|
+
return schema;
|
|
74
|
+
}
|
|
75
|
+
else if (s.shape !== undefined) {
|
|
76
|
+
return schema;
|
|
77
|
+
}
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
// zod 3 schemas are rendered by @modelcontextprotocol/sdk's own converter
|
|
81
|
+
// (zod-to-json-schema, which it depends on), loaded only if it's installed:
|
|
82
|
+
// zod 4 renders its own. An app on @modelcontextprotocol/server 2.x writes
|
|
83
|
+
// zod 4 schemas, as that SDK requires.
|
|
84
|
+
const v1JsonSchema = await import(
|
|
85
|
+
/* webpackIgnore: true */ String("@modelcontextprotocol/sdk/server/zod-json-schema-compat.js")).catch(() => undefined);
|
|
86
|
+
/** @internal A schema as JSON Schema, the way the MCP SDK 1.x renders one for tools/list (draft-7, input side). */
|
|
87
|
+
export function toJsonSchema(schema) {
|
|
88
|
+
if (isZ4Schema(schema))
|
|
89
|
+
return z4mini.toJSONSchema(schema, { target: "draft-7", io: "input" });
|
|
90
|
+
if (!v1JsonSchema) {
|
|
91
|
+
throw new Error("wakeshift: a zod 3 schema needs @modelcontextprotocol/sdk 1.x installed to render as JSON Schema: write it with zod 4 (import { z } from \"zod/v4\")");
|
|
92
|
+
}
|
|
93
|
+
return v1JsonSchema.toJsonSchemaCompat(schema);
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=zod.js.map
|
package/dist/zod.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"zod.js","sourceRoot":"","sources":["../src/zod.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,gEAAgE;AAChE,sEAAsE;AACtE,qEAAqE;AACrE,kDAAkD;AAIlD,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AAiBtC,+DAA+D;AAC/D,MAAM,UAAU,UAAU,CAAC,CAAU;IACnC,OAAO,CAAC,CAAE,CAA+B,EAAE,IAAI,CAAC;AAClD,CAAC;AAED,iEAAiE;AACjE,MAAM,UAAU,QAAQ,CAAC,CAAU;IACjC,OAAO,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,MAAM,IAAK,CAAY,IAAI,MAAM,IAAK,CAAY,CAAC,CAAC;AAC9F,CAAC;AAED,4GAA4G;AAC5G,MAAM,UAAU,eAAe,CAAC,KAAwB;IACtD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,MAAM,CA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C;AAED,0EAA0E;AAC1E,4EAA4E;AAC5E,2EAA2E;AAC3E,uCAAuC;AACvC,MAAM,YAAY,GAAiG,MAAM,MAAM;AAC7H,yBAAyB,CAAC,MAAM,CAAC,4DAA4D,CAAC,CAC/F,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;AAEzB,mHAAmH;AACnH,MAAM,UAAU,YAAY,CAAC,MAAiB;IAC5C,IAAI,UAAU,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAC,YAAY,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,EAAE,OAAO,EAAE,CAA4B,CAAC;IAC1H,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CAAC,sJAAsJ,CAAC,CAAC;IAC1K,CAAC;IACD,OAAO,YAAY,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC;AACjD,CAAC","sourcesContent":["// zod 3 and zod 4 side by side, without either MCP SDK: the types and\n// helpers the SDK used to take from @modelcontextprotocol/sdk's\n// zod-compat, so it loads whichever MCP SDK an app has (host.ts). The\n// definitions follow that module's, so a schema is read, checked and\n// rendered as JSON Schema the same way as before.\n\nimport type * as z3 from \"zod/v3\";\nimport type * as z4 from \"zod/v4/core\";\nimport * as z3rt from \"zod/v3\";\nimport * as z4mini from \"zod/v4-mini\";\n\n/** A zod schema, from zod 3's API or zod 4's (classic or mini). */\nexport type AnySchema = z3.ZodTypeAny | z4.$ZodType;\n/** An object schema, or any schema (as the MCP SDK takes it). */\nexport type AnyObjectSchema = z3.AnyZodObject | z4.$ZodObject | AnySchema;\n/** A zod shape: { field: schema }. */\nexport type ZodRawShapeCompat = Record<string, AnySchema>;\n/** What a schema parses to. */\nexport type SchemaOutput<S> = S extends z3.ZodTypeAny ? z3.infer<S> : S extends z4.$ZodType ? z4.output<S> : never;\n/** What a schema takes. */\nexport type SchemaInput<S> = S extends z3.ZodTypeAny ? z3.input<S> : S extends z4.$ZodType ? z4.input<S> : never;\n/** What a shape parses to, field by field. */\nexport type ShapeOutput<Shape extends ZodRawShapeCompat> = { [K in keyof Shape]: SchemaOutput<Shape[K]> };\n\ntype ParseResult<T> = { success: true; data: T } | { success: false; error: unknown };\n\n/** @internal Whether a schema is zod 4's (classic or mini). */\nexport function isZ4Schema(s: unknown): s is z4.$ZodType {\n return !!(s as { _zod?: unknown } | null)?._zod;\n}\n\n/** @internal Whether a value is a zod schema of either major. */\nexport function isSchema(v: unknown): v is AnySchema {\n return !!v && typeof v === \"object\" && (\"_def\" in (v as object) || \"_zod\" in (v as object));\n}\n\n/** @internal An object schema of a shape, in the zod API its fields use (zod 4 mini for an empty shape). */\nexport function objectFromShape(shape: ZodRawShapeCompat): AnyObjectSchema {\n const values = Object.values(shape);\n if (values.length === 0) return z4mini.object({});\n if (values.every(isZ4Schema)) return z4mini.object(shape as Record<string, z4.$ZodType>);\n if (values.every((s) => !isZ4Schema(s))) return z3rt.object(shape as Record<string, z3.ZodTypeAny>);\n throw new Error(\"wakeshift: a shape mixes zod 3 and zod 4 schemas\");\n}\n\n/** @internal Parses with either major. */\nexport function safeParse<S extends AnySchema>(schema: S, data: unknown): ParseResult<SchemaOutput<S>> {\n if (isZ4Schema(schema)) return z4mini.safeParse(schema, data) as ParseResult<SchemaOutput<S>>;\n return (schema as z3.ZodTypeAny).safeParse(data) as ParseResult<SchemaOutput<S>>;\n}\n\n/** @internal Parses with either major, allowing async refinements. */\nexport async function safeParseAsync<S extends AnySchema>(schema: S, data: unknown): Promise<ParseResult<SchemaOutput<S>>> {\n if (isZ4Schema(schema)) return (await z4mini.safeParseAsync(schema, data)) as ParseResult<SchemaOutput<S>>;\n return (await (schema as z3.ZodTypeAny).safeParseAsync(data)) as ParseResult<SchemaOutput<S>>;\n}\n\n/** @internal An object schema's shape (undefined for anything else). */\nexport function getObjectShape(schema: unknown): Record<string, AnySchema> | undefined {\n if (!schema) return undefined;\n const raw = isZ4Schema(schema)\n ? (schema as { _zod?: { def?: { shape?: unknown } } })._zod?.def?.shape\n : (schema as { shape?: unknown }).shape;\n if (!raw) return undefined;\n if (typeof raw === \"function\") {\n try {\n return raw() as Record<string, AnySchema>;\n } catch {\n return undefined;\n }\n }\n return raw as Record<string, AnySchema>;\n}\n\n/** @internal A schema or shape as an object schema (a shape is wrapped); undefined if it's neither. */\nexport function normalizeObjectSchema(schema: unknown): AnyObjectSchema | undefined {\n if (!schema || typeof schema !== \"object\") return undefined;\n const s = schema as { _def?: unknown; _zod?: { def?: { type?: string; shape?: unknown } }; shape?: unknown };\n if (!s._def && !s._zod) {\n const values = Object.values(schema);\n const looksLikeShape =\n values.length > 0 &&\n values.every((v) => typeof v === \"object\" && v !== null && ((v as { _def?: unknown })._def !== undefined || (v as { _zod?: unknown })._zod !== undefined || typeof (v as { parse?: unknown }).parse === \"function\"));\n if (looksLikeShape) return objectFromShape(schema as ZodRawShapeCompat);\n }\n if (isZ4Schema(schema)) {\n const def = s._zod?.def;\n if (def && (def.type === \"object\" || def.shape !== undefined)) return schema as AnyObjectSchema;\n } else if (s.shape !== undefined) {\n return schema as AnyObjectSchema;\n }\n return undefined;\n}\n\n// zod 3 schemas are rendered by @modelcontextprotocol/sdk's own converter\n// (zod-to-json-schema, which it depends on), loaded only if it's installed:\n// zod 4 renders its own. An app on @modelcontextprotocol/server 2.x writes\n// zod 4 schemas, as that SDK requires.\nconst v1JsonSchema: { toJsonSchemaCompat(schema: unknown, opts?: unknown): Record<string, unknown> } | undefined = await import(\n /* webpackIgnore: true */ String(\"@modelcontextprotocol/sdk/server/zod-json-schema-compat.js\")\n).catch(() => undefined);\n\n/** @internal A schema as JSON Schema, the way the MCP SDK 1.x renders one for tools/list (draft-7, input side). */\nexport function toJsonSchema(schema: AnySchema): Record<string, unknown> {\n if (isZ4Schema(schema)) return z4mini.toJSONSchema(schema, { target: \"draft-7\", io: \"input\" }) as Record<string, unknown>;\n if (!v1JsonSchema) {\n throw new Error(\"wakeshift: a zod 3 schema needs @modelcontextprotocol/sdk 1.x installed to render as JSON Schema: write it with zod 4 (import { z } from \\\"zod/v4\\\")\");\n }\n return v1JsonSchema.toJsonSchemaCompat(schema);\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wakeshift/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Let agents subscribe to things in your app: Wakeshift wakes them when you emit an event.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Clawvisor Inc. <support@wakeshift.ai>",
|
|
@@ -48,14 +48,27 @@
|
|
|
48
48
|
"examples": "node scripts/check-examples.mjs",
|
|
49
49
|
"e2e": "sh scripts/e2e.sh",
|
|
50
50
|
"prepack": "npm run build",
|
|
51
|
-
"pack-check": "sh scripts/pack-check.sh"
|
|
51
|
+
"pack-check": "sh scripts/pack-check.sh",
|
|
52
|
+
"test:v2": "tsc -p tsconfig.test.json && WAKESHIFT_TEST_MCP=v2 node --test 'build-test/test/*.test.js'"
|
|
52
53
|
},
|
|
53
54
|
"peerDependencies": {
|
|
54
55
|
"@modelcontextprotocol/sdk": "^1.23.0",
|
|
56
|
+
"@modelcontextprotocol/server": "^2.0.0",
|
|
55
57
|
"zod": "^3.25.0 || ^4.0.0"
|
|
56
58
|
},
|
|
59
|
+
"peerDependenciesMeta": {
|
|
60
|
+
"@modelcontextprotocol/sdk": {
|
|
61
|
+
"optional": true
|
|
62
|
+
},
|
|
63
|
+
"@modelcontextprotocol/server": {
|
|
64
|
+
"optional": true
|
|
65
|
+
}
|
|
66
|
+
},
|
|
57
67
|
"devDependencies": {
|
|
68
|
+
"@modelcontextprotocol/client": "^2.4.0",
|
|
69
|
+
"@modelcontextprotocol/node": "^2.1.2",
|
|
58
70
|
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
71
|
+
"@modelcontextprotocol/server": "^2.4.0",
|
|
59
72
|
"@types/node": "^22.20.5",
|
|
60
73
|
"expect-type": "^1.4.0",
|
|
61
74
|
"typescript": "^7.0.2",
|