@wakeshift/sdk 0.4.0 → 0.5.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 +16 -4
- package/README.md +8 -8
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/toolcall.d.ts +5 -5
- package/dist/toolcall.js +7 -7
- package/dist/toolcall.js.map +1 -1
- package/dist/wakeshift.d.ts +10 -7
- package/dist/wakeshift.js +35 -24
- package/dist/wakeshift.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
What changed in each release of `@wakeshift/sdk`. 0.4.0 is the first published release: to start with it, read the [README](README.md). Its notes below, and the earlier releases', are for apps that ran the preview builds.
|
|
4
4
|
|
|
5
|
+
## 0.5.0 (2026-10-29)
|
|
6
|
+
|
|
7
|
+
### Breaking
|
|
8
|
+
|
|
9
|
+
- **`recognised` is now `recognized`.** The `Recognised` type is `Recognized`, and `Subscription.recognised` and `ToolCall.recognised` are `recognized`. Rename them where you read them: `sub.recognised.harness` becomes `sub.recognized.harness`. What they hold is unchanged.
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- **Processes that share your key no longer remove each other's events.** In 0.4.0 every process sent the events it defined as your app's whole list. With an MCP server and a separate emitter on one key, whichever sent last removed the other's events, and the other's emits failed with `unknown_event` until it restarted. Now only your MCP server, the process that calls `attach`, sends the manifest automatically, and Wakeshift merges it into the one it has: it adds or updates your events and the settings you passed to `publishManifest`, and never removes an event or clears a setting. A process that doesn't call `attach` never sends it, whatever it calls (`emit`, `status`). `publishManifest` still replaces the whole manifest, and is how you remove an event.
|
|
14
|
+
- A process with no events defined never sends the manifest. In 0.4.0 any app call from one (even a status read) sent an empty list, which removed every one of your app's events.
|
|
15
|
+
- If an event is defined only in a process that emits it, define it in your MCP server too (or publish it with `publishManifest`): until a server sends it, emitting it fails with `unknown_event`.
|
|
16
|
+
|
|
5
17
|
## 0.4.0 (2026-10-29)
|
|
6
18
|
|
|
7
19
|
Define your app's events (`defineEvent`), attach Wakeshift to your MCP server (`attach`), subscribe the conversations that call your own tools (`attached.events`, `call.subscribe`), and emit to them (`emit`). The rest of this section is what changed since 0.3.0.
|
|
@@ -108,7 +120,7 @@ Errors the SDK throws before asking Wakeshift have the status and code Wakeshift
|
|
|
108
120
|
- Topics and their types: `wake.subscribe`, `wake.unsubscribe`, `wake.publish`, `wake.send`, `wake.topicStatus`, `wake.subscriptionStatus`, `wake.publishUrl(topic)`, `wake.closeTopic`, `wake.endSubscription`, `wake.unsubscribeUser`; `TopicSubscription`, `TopicEvent`, `TopicStatus`, `SubscriptionStatus`, `SendStatus`, `SubscribeOptions` and `Published` (its `matched` and `duplicate` are on `Emitted`). `PublishUrl.topic` goes with them.
|
|
109
121
|
- `wake.args`: `attached.inputs(shape)`.
|
|
110
122
|
- `wake.call`, `wake.callOf`, `Call`, `CallOptions`, `ClientInfoSource`, `applyAddition`, `wake.addition`, `wake.annotate` and `Addition`: the wrapper.
|
|
111
|
-
- `UNKNOWN_CLIENT_WARNING`, which only the removed calls gave. A wrapped tool's `call.recognised` says what Wakeshift
|
|
123
|
+
- `UNKNOWN_CLIENT_WARNING`, which only the removed calls gave. A wrapped tool's `call.recognised` says what Wakeshift recognized the agent as.
|
|
112
124
|
- `AgentScope.groups`.
|
|
113
125
|
- `AppKey.mode` and `wake.mode`, which meant nothing since current keys came in. Older keys (`wst_test_…`, `wst_live_…`) still work and name their app; a `wst_test_` key still needs a core.
|
|
114
126
|
- `session` as a hidden alias of `session_key`: a wrapped tool takes `session_key` only, and a `session` argument is dropped like any other the tool doesn't take.
|
|
@@ -134,8 +146,8 @@ Kept: `defineEvent`, `emit`, `event.publishUrl`, `event.status` and `event.statu
|
|
|
134
146
|
### Changed
|
|
135
147
|
|
|
136
148
|
- A wrapped tool's reply carries one Wakeshift block, however many subscriptions the call makes, and only what the conversation needs.
|
|
137
|
-
- A subscription a failed tool call made is ended: a call that throws, returns `isError`, returns output its `outputSchema` refuses, or is
|
|
138
|
-
- A client that speaks MCP Events is told which event to subscribe to, or that it has: `call.native` is true, and `call.subscribe` makes nothing. The SDK
|
|
149
|
+
- A subscription a failed tool call made is ended: a call that throws, returns `isError`, returns output its `outputSchema` refuses, or is canceled.
|
|
150
|
+
- A client that speaks MCP Events is told which event to subscribe to, or that it has: `call.native` is true, and `call.subscribe` makes nothing. The SDK recognizes ChatGPT's `_meta["openai/session"]`, its client name or User-Agent, and clients that declare MCP Events, on stateless servers too; `attach`'s `events.native(extra)` names callers it can't recognize, such as your own agents.
|
|
139
151
|
- `session_key` is the one name for the session argument.
|
|
140
152
|
- `attach`'s own tools (`subscribe_events`, `unsubscribe_events`, `list_subscriptions`) describe `session_key` to the agent as a wrapped tool does.
|
|
141
153
|
- `list_subscriptions` is marked read-only and idempotent (`readOnlyHint: true`, `idempotentHint: true`), so clients that run read-only tools without asking (Codex, by default) don't ask before it.
|
|
@@ -148,7 +160,7 @@ Kept: `defineEvent`, `emit`, `event.publishUrl`, `event.status` and `event.statu
|
|
|
148
160
|
- A successful answer that is a JSON array is a `bad_response` error, as it is in the Go and Python SDKs.
|
|
149
161
|
- An error whose `code` isn't a string has an empty code, and one whose `message` is empty takes the body's start, else the status's text.
|
|
150
162
|
- An MCP Events client gets "Wakeshift couldn't be reached" when the core is unreachable, without the core's address; a `callback_failed` error's `data.reason` is always a string.
|
|
151
|
-
- Google's 500 page is
|
|
163
|
+
- Google's 500 page is recognized by "Server Error" within the body's first 4 KB.
|
|
152
164
|
- A failed tool call's rollback no longer ends a subscription that another call on the same conversation renewed in the meantime (two calls in parallel, or a second call while the first was still running). The call that renewed it told the agent it would be woken; now it is.
|
|
153
165
|
- `defineEvent` no longer adds the default route's filter to the `filter` object you passed: it copies it.
|
|
154
166
|
- A personal event's `emit` without `to` says to pass the subscribers it's for, not one.
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ Install the package, not a checkout of this repository (a `file:` dependency): a
|
|
|
14
14
|
|
|
15
15
|
## Quickstart: a CI bot
|
|
16
16
|
|
|
17
|
-
You have an MCP server and a GitHub webhook handler. Register an app in the Wakeshift console (Build), and put its key in `WAKESHIFT_KEY` (`wst_` and 50 characters). The SDK talks to `https://app.wakeshift.ai` unless `WAKESHIFT_CORE` names another address. Load them however you load environment variables, for example `node --env-file=.env server.ts`.
|
|
17
|
+
You have an MCP server and a GitHub webhook handler. Register an app in the Wakeshift console (Build), and put its key in `WAKESHIFT_KEY` (`wst_` and 50 characters). The SDK talks to `https://app.wakeshift.ai` unless `WAKESHIFT_CORE` names another address. Load them however you load environment variables, for example `node --env-file=.env server.ts` (Node 22.18 or later runs a `.ts` file directly).
|
|
18
18
|
|
|
19
19
|
```ts
|
|
20
20
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
|
|
@@ -27,7 +27,7 @@ const ciFinished = wake.defineEvent("ci.finished", {
|
|
|
27
27
|
description: "CI finished on a GitHub repo",
|
|
28
28
|
args: z.object({ owner: z.string(), repo: z.string(), branch: z.string().optional() }),
|
|
29
29
|
payload: z.object({ branch: z.string(), conclusion: z.string(), name: z.string(), url: z.string() }),
|
|
30
|
-
authorize: (subscriber, { owner, repo }) => canSeeRepo(subscriber, `${owner}/${repo}`),
|
|
30
|
+
authorize: (subscriber, { owner, repo }) => canSeeRepo(subscriber.user, `${owner}/${repo}`),
|
|
31
31
|
text: (run, { owner, repo }) => `CI ${run.conclusion} on ${owner}/${repo} ${run.branch}: ${run.name}`,
|
|
32
32
|
})
|
|
33
33
|
|
|
@@ -96,7 +96,7 @@ await turn.emit({ table: "juniper" }, { hole: ["As", "Kd"], toCall: 2 }, { to: "
|
|
|
96
96
|
|
|
97
97
|
- **`wake.defineEvent(name, { description, args, payload, text, authorize?, personal?, deleteOnDelivery? })`** returns the event. `args` is what a subscriber picks; its required string, integer and boolean fields route occurrences, so their values are lowercase IDs (a-z 0-9 . _ -), and an optional one filters on the payload field of the same name. `authorize(subscriber, args)` decides who may subscribe. With `deleteOnDelivery: true`, Wakeshift deletes each occurrence's text and payload once it's delivered. Define every event before `attach`, which throws with none.
|
|
98
98
|
- **`event.emit(args, payload, { id?, to? })`** checks the payload against its schema and sends it to everyone subscribed with those arguments. A personal event goes to its recipients, `to`: users (the `user` attach's `identify` gives for them), `{ user, subscription }` (exactly one conversation's subscription, the `id` `call.subscribe` returned) and `{ native: user }` (only that user's own MCP Events subscriptions), mixable, up to 1,000. It returns `{ matched, duplicate, unmatched, ended }`: `matched` counts the conversations woken, `unmatched` the users with nothing subscribed, `ended` the subscriptions no longer live (forget them). `id` makes retries emit once; a retry must name the same recipients.
|
|
99
|
-
- **`wake.attach(server, { identify?, tools?, events? })`** attaches Wakeshift to your MCP server and returns the handle your own tools use (below). It serves `events/list`, `events/subscribe` and `events/unsubscribe` to clients that speak MCP Events, and adds `subscribe_events` (for everyone else), `unsubscribe_events` and `list_subscriptions` (for every client, so a person can always see and stop what they're subscribed to); `tools` names fewer of them (`BUILTIN_TOOLS`; `[]` for none). `identify(extra)` says who is behind a request, as `{ user, client? }`: `user` is your app's ID for the person, from your own sign-in; without it, requests have no user, so personal events and `list_subscriptions` refuse. On a stateless server, which never sees `initialize`, `client` is the MCP client's name as your sign-in knows it (an OAuth registration's `client_name`, say): Wakeshift reads it to tell which program the agent runs in. A name the request carries wins.
|
|
99
|
+
- **`wake.attach(server, { identify?, tools?, events? })`** attaches Wakeshift to your MCP server and returns the handle your own tools use (below). It serves `events/list`, `events/subscribe` and `events/unsubscribe` to clients that speak MCP Events, and adds `subscribe_events` (for everyone else), `unsubscribe_events` and `list_subscriptions` (for every client, so a person can always see and stop what they're subscribed to); `tools` names fewer of them (`BUILTIN_TOOLS`; `[]` for none). `identify(extra)` says who is behind a request, as `{ user, client? }`: `user` is your app's ID for the person, from your own sign-in; without it, requests have no user, so personal events and `list_subscriptions` refuse. On a stateless server, which never sees `initialize`, `client` is the MCP client's name as your sign-in knows it (an OAuth registration's `client_name`, say): Wakeshift reads it to tell which program the agent runs in. A name the request carries wins. It also sends your app's manifest, with your events, the first time they're needed: it adds them and never removes one. A separate process that only emits never sends it.
|
|
100
100
|
- **`event.end(user, id)`** ends one of a user's subscriptions by its ID, outside a tool (a player who timed out, a member removed).
|
|
101
101
|
- **`event.status(args, { to? })`** counts the conversations subscribed with those arguments (a personal event: one user's), how many are connected now, and how: `{ subscriptions, connected, via: { stream, poll, hooks, webhook } }`. **`event.statusOf([{ user, subscription }, …])`** reads up to 1,000 subscriptions by ID: `[{ id, user, live, connected, via? }]`. Both only read.
|
|
102
102
|
- **`event.publishUrl(args, { to? })`** returns `{ id, event, url }`, a capability URL that emits the event with those arguments (a personal event: to one user) for services that only send webhooks. A POST's JSON body is the payload, checked against the event's schema. `wake.revokePublishUrl(id)` stops it.
|
|
@@ -121,10 +121,10 @@ server.registerTool(
|
|
|
121
121
|
|
|
122
122
|
- **`attached.inputs(shape)`** is `shape` plus Wakeshift's three optional arguments, `session_key`, `harness` and `conversation_id`. A tool wrapped with `attached.events` needs them: without them it doesn't compile. An argument a tool doesn't declare is ignored, not refused.
|
|
123
123
|
- **`attached.events(name, handler)`** wraps the callback of the tool registered as `name` (the MCP SDK doesn't tell a callback its tool's name; the first call checks it). The handler gets the tool's own arguments and a `call`, and returns a string or a `CallToolResult`.
|
|
124
|
-
- **`call`**: `user` (from `identify`), `tool`, `native` and `nativeConversation`, `session` (the `session_key` passed; after a subscribe, the conversation's session), `
|
|
125
|
-
- **`await call.subscribe(event, args, { ttl?, reason?, label? })`** subscribes the calling conversation, or renews its subscription, and resolves to `{ id, user, created, session,
|
|
126
|
-
- **A failed call**: one that throws, returns `isError`, returns output its `outputSchema` refuses, or is
|
|
127
|
-
- **Clients that subscribe themselves** (MCP Events: ChatGPT and others) aren't subscribed: `call.native` is true, and the reply tells them which event to subscribe to. `attach`'s `events.native(extra)` tells the SDK about callers it can't
|
|
124
|
+
- **`call`**: `user` (from `identify`), `tool`, `native` and `nativeConversation`, `session` (the `session_key` passed; after a subscribe, the conversation's session), `recognized` (which program Wakeshift recognized the agent as, `null` before a subscribe) and `extra` (MCP's own). It works until the handler returns.
|
|
125
|
+
- **`await call.subscribe(event, args, { ttl?, reason?, label? })`** subscribes the calling conversation, or renews its subscription, and resolves to `{ id, user, created, session, recognized, native }`. `reason` is shown in your console. Your tool decides who may (`authorize` isn't consulted). **`await call.unsubscribe(event, args)`** ends it; **`await call.resolveSession()`** finds or starts the conversation's session without subscribing it.
|
|
126
|
+
- **A failed call**: one that throws, returns `isError`, returns output its `outputSchema` refuses, or is canceled, ends every subscription it made, and its reply gets nothing from Wakeshift.
|
|
127
|
+
- **Clients that subscribe themselves** (MCP Events: ChatGPT and others) aren't subscribed: `call.native` is true, and the reply tells them which event to subscribe to. `attach`'s `events.native(extra)` tells the SDK about callers it can't recognize, such as your own agents.
|
|
128
128
|
- **Structured output**: some hosts show the model only `structuredContent`. Make the tool's `outputSchema` with `attached.output(shape)`, and its `wakeshift` field carries what Wakeshift adds, too.
|
|
129
129
|
|
|
130
130
|
```ts
|
|
@@ -169,7 +169,7 @@ A wrapped tool that subscribes to nothing, like `look`, still gets what Wakeshif
|
|
|
169
169
|
|
|
170
170
|
### Manifest and workspaces
|
|
171
171
|
|
|
172
|
-
- `wake.publishManifest({ description?, agent?, events?, others_can_wake?, preapprove_tools? })`: what your app may do; returns it as Wakeshift keeps it. `agent`: `{ wake, post, ttl_days, wake_limits?, start_prompt? }`, each scope event `{ pattern, description }`: what the agents in the workspaces your app keeps may be woken by and post. `others_can_wake`: other people and their agents wake your users' agents through your app (messages, moves), so the consent screen says so. `preapprove_tools`: your tools, by name, that agents' programs can run without asking each time (at most 20: tools that only read, and routine ones that reach only what the agent joined); when a user connects Claude Code or Cursor CLI, Wakeshift offers to allow exactly these. You needn't call it:
|
|
172
|
+
- `wake.publishManifest({ description?, agent?, events?, others_can_wake?, preapprove_tools? })`: what your app may do; returns it as Wakeshift keeps it. `agent`: `{ wake, post, ttl_days, wake_limits?, start_prompt? }`, each scope event `{ pattern, description }`: what the agents in the workspaces your app keeps may be woken by and post. `others_can_wake`: other people and their agents wake your users' agents through your app (messages, moves), so the consent screen says so. `preapprove_tools`: your tools, by name, that agents' programs can run without asking each time (at most 20: tools that only read, and routine ones that reach only what the agent joined); when a user connects Claude Code or Cursor CLI, Wakeshift offers to allow exactly these. It replaces the manifest, so it's the way to remove an event. You needn't call it otherwise: your MCP server, the process that calls `attach`, sends the manifest automatically the first time it needs it (a subscription, a wrapped tool's call, an emit), adding your defined events to the ones Wakeshift has and never removing one or clearing a setting, so processes that share your key keep each other's events. A process that only emits never sends it. Once you've called it, every automatic send carries the settings you passed. `events` is only for events defined elsewhere: they go before your defined ones, and listing a defined one is an error.
|
|
173
173
|
- Your app identifies its own users with its own sign-in, and acts for the agents in the workspaces it keeps.
|
|
174
174
|
- `wake.workspace(user, name)`, `wake.addAgent(workspace, agent, displayName)`, `wake.checkAgent(workspace, agent)`: the workspace Wakeshift keeps for one of your users, an agent in it with a grant for your manifest's agent scope, and whether that grant is live. Wakeshift keeps a user's conversations in that workspace; you don't need these to subscribe them.
|
|
175
175
|
- `harnessAgent(clientName)`: the agent ID a client name maps to (`"Claude Code"` is `claude-code`), as Wakeshift names it.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { Wakeshift, DEFAULT_CORE, SESSION_ARG, HARNESS_ARG, CONVERSATION_ARG, type WakeshiftOptions, type AppInfo, type Duration, type
|
|
1
|
+
export { Wakeshift, DEFAULT_CORE, SESSION_ARG, HARNESS_ARG, CONVERSATION_ARG, type WakeshiftOptions, type AppInfo, type Duration, type Recognized, type Emitted, type Recipient, type Via, type PublishUrl, type ToolExtra, type Manifest, type AgentScope, type ScopeEvent, } from "./wakeshift.js";
|
|
2
2
|
export { harnessAgent } from "./harness.js";
|
|
3
3
|
export { WakeshiftError, isCode } from "./errors.js";
|
|
4
4
|
export { parseKey, signAssertion, type AppKey } from "./key.js";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,YAAY,EACZ,WAAW,EACX,WAAW,EACX,gBAAgB,GAajB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAe,MAAM,UAAU,CAAC;AAChE,OAAO,EACL,SAAS,EACT,SAAS,EACT,eAAe,EACf,0BAA0B,EAC1B,4BAA4B,EAC5B,qBAAqB,EACrB,aAAa,EAMb,wBAAwB,GAKzB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,SAAS,GAaV,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,QAAQ,IAAI,eAAe,EAAE,MAAM,WAAW,CAAC","sourcesContent":["export {\n Wakeshift,\n DEFAULT_CORE,\n SESSION_ARG,\n HARNESS_ARG,\n CONVERSATION_ARG,\n type WakeshiftOptions,\n type AppInfo,\n type Duration,\n type
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,YAAY,EACZ,WAAW,EACX,WAAW,EACX,gBAAgB,GAajB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAe,MAAM,UAAU,CAAC;AAChE,OAAO,EACL,SAAS,EACT,SAAS,EACT,eAAe,EACf,0BAA0B,EAC1B,4BAA4B,EAC5B,qBAAqB,EACrB,aAAa,EAMb,wBAAwB,GAKzB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,SAAS,GAaV,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,QAAQ,IAAI,eAAe,EAAE,MAAM,WAAW,CAAC","sourcesContent":["export {\n Wakeshift,\n DEFAULT_CORE,\n SESSION_ARG,\n HARNESS_ARG,\n CONVERSATION_ARG,\n type WakeshiftOptions,\n type AppInfo,\n type Duration,\n type Recognized,\n type Emitted,\n type Recipient,\n type Via,\n type PublishUrl,\n type ToolExtra,\n type Manifest,\n type AgentScope,\n type ScopeEvent,\n} from \"./wakeshift.js\";\nexport { harnessAgent } from \"./harness.js\";\nexport { WakeshiftError, isCode } from \"./errors.js\";\nexport { parseKey, signAssertion, type AppKey } from \"./key.js\";\nexport {\n WakeEvent,\n ArgsError,\n EVENT_TOOL_TEXT,\n SUBSCRIBE_TOOL_DESCRIPTION,\n UNSUBSCRIBE_TOOL_DESCRIPTION,\n LIST_TOOL_DESCRIPTION,\n BUILTIN_TOOLS,\n type BuiltinTool,\n type EventOptions,\n type EmitOptions,\n type EventStatus,\n type EventSubscriptionStatus,\n MAX_STATUS_SUBSCRIPTIONS,\n type EventTypeManifest,\n type AttachOptions,\n type Identity,\n type Subscriber,\n} from \"./events.js\";\nexport {\n CallEnded,\n type Attached,\n type AppArgs,\n type EventsOptions,\n type Subscription,\n type ToolCall,\n type ToolCallExtra,\n type ToolSubscribeOptions,\n type WakeInputs,\n type WakeKey,\n type WakeOutputShape,\n type WakeShape,\n type WrappedResult,\n} from \"./toolcall.js\";\nexport { EXTENSION_KEY, TEXT_META, REVISION as EVENTS_REVISION } from \"./spec.js\";\n"]}
|
package/dist/toolcall.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { ToolCallback } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
|
4
4
|
import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
5
5
|
import { type AnySchema, type SchemaInput, type ShapeOutput, type ZodRawShapeCompat } from "@modelcontextprotocol/sdk/server/zod-compat.js";
|
|
6
6
|
import type { WakeEvent } from "./events.js";
|
|
7
|
-
import { type Duration, type
|
|
7
|
+
import { type Duration, type Recognized } from "./wakeshift.js";
|
|
8
8
|
declare const SESSION_ARG = "session_key";
|
|
9
9
|
declare const HARNESS_ARG = "harness";
|
|
10
10
|
declare const CONVERSATION_ARG = "conversation_id";
|
|
@@ -44,8 +44,8 @@ export interface Subscription {
|
|
|
44
44
|
created: boolean;
|
|
45
45
|
/** The conversation's session. A secret: don't show, store or log it. */
|
|
46
46
|
session: string;
|
|
47
|
-
/** What Wakeshift
|
|
48
|
-
|
|
47
|
+
/** What Wakeshift recognized the agent's program as. */
|
|
48
|
+
recognized: Recognized;
|
|
49
49
|
/** The caller subscribes itself (call.native): nothing was made, id is "", and the block tells it what to subscribe to. */
|
|
50
50
|
native: boolean;
|
|
51
51
|
}
|
|
@@ -78,8 +78,8 @@ export interface ToolCall {
|
|
|
78
78
|
readonly nativeConversation: string | null;
|
|
79
79
|
/** The session_key passed; after a subscribe or resolveSession, the conversation's session. */
|
|
80
80
|
readonly session: string | null;
|
|
81
|
-
/** What Wakeshift
|
|
82
|
-
readonly
|
|
81
|
+
/** What Wakeshift recognized the agent's program as: null until a subscribe or resolveSession. */
|
|
82
|
+
readonly recognized: Recognized | null;
|
|
83
83
|
/** MCP's own extra for the call. */
|
|
84
84
|
readonly extra: ToolCallExtra;
|
|
85
85
|
/**
|
package/dist/toolcall.js
CHANGED
|
@@ -198,7 +198,7 @@ class CallScope {
|
|
|
198
198
|
native = false;
|
|
199
199
|
nativeConversation = null;
|
|
200
200
|
session;
|
|
201
|
-
|
|
201
|
+
recognized = null;
|
|
202
202
|
extra;
|
|
203
203
|
ended = false;
|
|
204
204
|
pending = "";
|
|
@@ -260,7 +260,7 @@ class CallScope {
|
|
|
260
260
|
const known = event.parseArgs(args);
|
|
261
261
|
if (this.native) {
|
|
262
262
|
this.addNative(event.name, known);
|
|
263
|
-
return { id: "", user: this.user ?? "", created: false, session: "",
|
|
263
|
+
return { id: "", user: this.user ?? "", created: false, session: "", recognized: { harness: null, via: null, claimed: null }, native: true };
|
|
264
264
|
}
|
|
265
265
|
if (event.personal && !this.user) {
|
|
266
266
|
throw new WakeshiftError(400, "bad_arguments", `${event.name} is personal: call.subscribe needs a user (attach's identify), who the subscription belongs to`);
|
|
@@ -279,12 +279,12 @@ class CallScope {
|
|
|
279
279
|
this.pending = out.pending;
|
|
280
280
|
this.armed = true;
|
|
281
281
|
this.session = out.session;
|
|
282
|
-
const rec =
|
|
283
|
-
this.
|
|
282
|
+
const rec = recognizedOf(out.agent);
|
|
283
|
+
this.recognized = rec;
|
|
284
284
|
const es = out.event_subscription;
|
|
285
285
|
if (es.created)
|
|
286
286
|
this.created.push({ name: event.name, arguments: known, session: out.session, pending: out.pending ?? this.pending });
|
|
287
|
-
return { id: es.id, user: es.user ?? this.user ?? "", created: !!es.created, session: out.session,
|
|
287
|
+
return { id: es.id, user: es.user ?? this.user ?? "", created: !!es.created, session: out.session, recognized: rec, native: false };
|
|
288
288
|
});
|
|
289
289
|
}
|
|
290
290
|
unsubscribe(event, args) {
|
|
@@ -304,7 +304,7 @@ class CallScope {
|
|
|
304
304
|
const out = await this.at.wake.requestApp("POST", "/calls/session", { call: this.wire() });
|
|
305
305
|
this.pending = out.pending;
|
|
306
306
|
this.session = out.session;
|
|
307
|
-
this.
|
|
307
|
+
this.recognized = recognizedOf(out.agent);
|
|
308
308
|
return out.session;
|
|
309
309
|
});
|
|
310
310
|
}
|
|
@@ -385,7 +385,7 @@ class CallScope {
|
|
|
385
385
|
}
|
|
386
386
|
}
|
|
387
387
|
}
|
|
388
|
-
function
|
|
388
|
+
function recognizedOf(a) {
|
|
389
389
|
return { harness: a?.harness ?? null, via: a?.via ?? null, claimed: a?.claimed ?? null };
|
|
390
390
|
}
|
|
391
391
|
function headerOf(extra, name) {
|
package/dist/toolcall.js.map
CHANGED
|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AG,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;AAC3E,2EAA2E;AAC3E,4EAA4E;AAC5E,yEAAyE;AACzE,yDAAyD;AACzD,EAAE;AACF,6FAA6F;AAC7F,gC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,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 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\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/**\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 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 });\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: 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"]}
|
package/dist/wakeshift.d.ts
CHANGED
|
@@ -46,14 +46,14 @@ export interface AppInfo {
|
|
|
46
46
|
};
|
|
47
47
|
}
|
|
48
48
|
/**
|
|
49
|
-
* What Wakeshift
|
|
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
|
|
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
|
|
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:
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
*
|
|
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
|
@@ -180,10 +180,12 @@ export class Wakeshift {
|
|
|
180
180
|
* Tells Wakeshift what the app may do, replacing what it said before: m,
|
|
181
181
|
* with the events you defined (defineEvent) after m's own events. An
|
|
182
182
|
* event both defined and listed in m.events is an error, and nothing is
|
|
183
|
-
* sent. You needn't call it:
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
183
|
+
* sent. You needn't call it: a process that serves your tools (attach)
|
|
184
|
+
* sends the manifest automatically, merged into the one Wakeshift has.
|
|
185
|
+
* Call it to remove an event or clear a setting. Once called, m's
|
|
186
|
+
* settings are what every automatic send carries (even if this one
|
|
187
|
+
* failed), with the events defined by then. Returns the manifest as
|
|
188
|
+
* Wakeshift keeps it.
|
|
187
189
|
*/
|
|
188
190
|
async publishManifest(m) {
|
|
189
191
|
const version = this.manifestVersion; // before the body: a later defineEvent is sent again
|
|
@@ -228,30 +230,30 @@ export class Wakeshift {
|
|
|
228
230
|
const { events: _listed, ...rest } = m;
|
|
229
231
|
return events.length > 0 ? { ...rest, events } : rest;
|
|
230
232
|
}
|
|
231
|
-
// The automatic send
|
|
232
|
-
// settings
|
|
233
|
-
//
|
|
233
|
+
// The automatic send, from a process that serves the app's tools: the
|
|
234
|
+
// settings the app last published (only those it set), with the defined
|
|
235
|
+
// events, merged into the manifest Wakeshift has, so it never removes an
|
|
236
|
+
// event or clears a setting another process sent.
|
|
234
237
|
async sendManifest() {
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
+
const body = {};
|
|
239
|
+
for (const [k, v] of Object.entries(this.manifestBody(this.manifestBase ?? {}))) {
|
|
240
|
+
if (v === undefined || v === null || v === "" || v === false || (Array.isArray(v) && v.length === 0))
|
|
241
|
+
continue;
|
|
242
|
+
body[k] = v;
|
|
238
243
|
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
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));
|
|
244
|
+
if (!body.events)
|
|
245
|
+
return; // nothing to add (attach refuses with no events, but never send an empty list)
|
|
246
|
+
await this.request("POST", "/manifest/merge", body);
|
|
248
247
|
}
|
|
249
248
|
// ── Events (MCP Events, natively or bridged) ──────────────────────────
|
|
250
249
|
events = new Map();
|
|
251
|
-
// What publishManifest was last given (null: nothing yet); whether
|
|
252
|
-
//
|
|
253
|
-
//
|
|
250
|
+
// What publishManifest was last given (null: nothing yet); whether this
|
|
251
|
+
// process serves the app's tools (attach: only then is the manifest sent
|
|
252
|
+
// automatically); whether Wakeshift has the manifest for the events
|
|
253
|
+
// defined now (the send; null: not yet, or a defineEvent since); and how
|
|
254
|
+
// many defineEvents there were.
|
|
254
255
|
manifestBase = null;
|
|
256
|
+
serving = false;
|
|
255
257
|
published = null;
|
|
256
258
|
manifestVersion = 0;
|
|
257
259
|
/**
|
|
@@ -293,10 +295,19 @@ export class Wakeshift {
|
|
|
293
295
|
* Wakeshift's arguments with attached.inputs.
|
|
294
296
|
*/
|
|
295
297
|
attach(server, opts = {}) {
|
|
296
|
-
|
|
298
|
+
const attached = attachEvents(this, server, [...this.events.values()], opts);
|
|
299
|
+
this.serving = true; // the manifest is sent automatically from now on
|
|
300
|
+
return attached;
|
|
297
301
|
}
|
|
298
|
-
/**
|
|
302
|
+
/**
|
|
303
|
+
* @internal Sends the manifest with the defined events, once (again after
|
|
304
|
+
* a defineEvent), from a process that serves the app's tools (attach). A
|
|
305
|
+
* process that only emits never sends it: its events may be fewer, or
|
|
306
|
+
* older, than its server's.
|
|
307
|
+
*/
|
|
299
308
|
ensureEvents() {
|
|
309
|
+
if (!this.serving)
|
|
310
|
+
return Promise.resolve();
|
|
300
311
|
if (!this.published)
|
|
301
312
|
this.track(this.serial(() => this.sendManifest()), this.manifestVersion);
|
|
302
313
|
return this.published;
|
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;AAC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E,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 { 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 recognised 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 recognised\n * as (the claim only refines it: Cursor's calls may be Grok Bot's).\n */\nexport interface Recognised {\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: Wakeshift gets the manifest automatically\n * when the app first needs it. Once called, m is what every automatic\n * send carries (even if this one failed), with the events defined by\n * then. Returns the manifest as 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: the manifest the app last published, or else the\n // settings Wakeshift has (asked for first, so the send never wipes what\n // was published separately), with the defined events.\n private async sendManifest(): Promise<void> {\n if (this.manifestBase) {\n await this.request(\"PUT\", \"/manifest\", this.manifestBody(this.manifestBase));\n return;\n }\n const stored = await this.request<Record<string, unknown>>(\"GET\", \"/manifest\");\n const kept: Manifest = { description: typeof stored.description === \"string\" ? stored.description : \"\" };\n if (stored.agent !== null && typeof stored.agent === \"object\") kept.agent = stored.agent as AgentScope;\n if (stored.others_can_wake === true) kept.others_can_wake = true;\n if (Array.isArray(stored.preapprove_tools) && stored.preapprove_tools.length > 0) kept.preapprove_tools = stored.preapprove_tools as string[];\n await this.request(\"PUT\", \"/manifest\", this.manifestBody(kept));\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\n // Wakeshift has the manifest for the events defined now (the send; null:\n // not yet, or a defineEvent since); and how many defineEvents there were.\n private manifestBase: Manifest | null = null;\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 return attachEvents(this, server, [...this.events.values()], opts);\n }\n\n /** @internal Sends the manifest with the defined events, once (again after a defineEvent). */\n ensureEvents(): Promise<void> {\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":"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,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;AAkGlD,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,CAA4B,CAAC;YACvC,IAAI,OAAO,CAAC,CAAC,MAAM,KAAK,Q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AAI,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;QAC9B,MAAM,CAAC,GAAG,GAAmG,CAAC;QAC9G,MAAM,GAAG,GACP,CAAC,EAAE,IAAI,KAAK,cAAc,IAAI,CAAC,EAAE,IAAI,KAAK,YAAY;YACpD,CAAC,CAAC,oBAAoB,IAAI,CAAC,SAAS,GAAG,IAAI,GAAG;YAC9C,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 { 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"]}
|
package/package.json
CHANGED