switch-ext-kit 0.0.0-stage → 0.2.1

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/src/shim.ts ADDED
@@ -0,0 +1,302 @@
1
+ // Filters on an extension's MCP messages, as its host relays them. `switchboard` turns a
2
+ // Switchboard appendage (sbmcp: events with `_meta["switchboard/record"]`) into a Switch extension,
3
+ // so its tools carry over as they are; `readOnly` keeps only the tools that only look.
4
+ import { CONNECTIONS, VERSION } from "./app.ts"
5
+ import { MESSAGE_SCHEMA, SENDER_SCHEMA } from "./messages.ts"
6
+
7
+ export type Json = Record<string, unknown>
8
+
9
+ export interface Filter {
10
+ /** A message on its way to the extension: forwarded (maybe changed), or answered here instead. */
11
+ readonly inbound: (m: Json) => { readonly forward: Json | null; readonly answer: Json | null }
12
+ /** A message from the extension: passed on (maybe changed), or dropped. */
13
+ readonly outbound: (m: Json) => Json | null
14
+ }
15
+
16
+ export const isJson = (v: unknown): v is Json =>
17
+ typeof v === "object" && v !== null && !Array.isArray(v)
18
+
19
+ const field = (m: Json, key: string): Json => {
20
+ const v = m[key]
21
+ return isJson(v) ? v : {}
22
+ }
23
+
24
+ const list = (v: unknown): readonly unknown[] => (Array.isArray(v) ? v : [])
25
+
26
+ const pass = (m: Json) => ({ forward: m, answer: null })
27
+
28
+ /** Remembers the ids of requests by method, to know what a response answers. */
29
+ const asked = () => {
30
+ const ids = new Map<unknown, string>()
31
+ return {
32
+ note: (m: Json) => {
33
+ if (m.id !== undefined && typeof m.method === "string") {
34
+ ids.set(m.id, m.method)
35
+ }
36
+ },
37
+ /** The method a response answers, once; "" for anything else. */
38
+ take: (m: Json) => {
39
+ if (m.method !== undefined) {
40
+ return ""
41
+ }
42
+ const method = ids.get(m.id) ?? ""
43
+ ids.delete(m.id)
44
+ return method
45
+ },
46
+ }
47
+ }
48
+
49
+ const RECORD = "switchboard/record"
50
+
51
+ /** What a shimmed event carries: its Switchboard record, envelope and body. */
52
+ const RECORD_SCHEMA = {
53
+ type: "object",
54
+ properties: {
55
+ kind: { type: "string" },
56
+ stream: { type: "string" },
57
+ data: {},
58
+ about: { type: "array", items: { type: "string" } },
59
+ refs: { type: "array", items: { type: "string" } },
60
+ importance: { type: "number" },
61
+ sender: SENDER_SCHEMA,
62
+ message: MESSAGE_SCHEMA,
63
+ },
64
+ required: ["kind", "stream", "data"],
65
+ }
66
+
67
+ /** A channel's message (Claude Code's channels, `notifications/claude/channel`), as an event. */
68
+ const CHANNEL = "notifications/claude/channel"
69
+ const CHANNEL_EVENT = "message"
70
+
71
+ const ENVELOPE = ["about", "refs", "importance", "sender", "message"] as const
72
+
73
+ /**
74
+ * A Switchboard appendage as an extension. Its event types gain the extension's prefix (`pr` becomes
75
+ * `github-prs.pr`); each occurrence's payload is its record: `kind` and `stream` (where the type, or
76
+ * the occurrence, says it lands; else `event` in `events/<extension>`), the record's `about`, `refs` and
77
+ * `importance`, and its body as `data`. A fixed record id is the event id, so a resend is one event.
78
+ */
79
+ export const switchboard = (extension: string): Filter => {
80
+ const prefix = `${extension}.`
81
+ const requests = asked()
82
+ const placed = new Map<string, Json>()
83
+
84
+ const renamed = (e: Json): Json => {
85
+ const name = String(e.name)
86
+ placed.set(name, field(field(e, "_meta"), RECORD))
87
+ return {
88
+ ...e,
89
+ name: `${prefix}${name}`,
90
+ delivery: ["push"],
91
+ payloadSchema: RECORD_SCHEMA,
92
+ _meta: { [VERSION]: 1 },
93
+ }
94
+ }
95
+
96
+ const occurrence = (params: Json): Json => {
97
+ const name = String(params.name)
98
+ const where = placed.get(name) ?? {}
99
+ const meta = field(params, "_meta")
100
+ const envelope = field(meta, RECORD)
101
+ const stream = [envelope.stream, where.stream].find((x) => typeof x === "string")
102
+ const payload: Json = {
103
+ kind: typeof where.kind === "string" ? where.kind : "event",
104
+ stream: typeof stream === "string" ? stream : `events/${extension}`,
105
+ data: params.data ?? null,
106
+ }
107
+ for (const key of ENVELOPE) {
108
+ if (envelope[key] !== undefined) {
109
+ payload[key] = envelope[key]
110
+ }
111
+ }
112
+ const { [RECORD]: _, ...rest } = meta
113
+ return {
114
+ ...params,
115
+ name: `${prefix}${name}`,
116
+ eventId: typeof envelope.id === "string" ? envelope.id : params.eventId,
117
+ data: payload,
118
+ _meta: rest,
119
+ }
120
+ }
121
+
122
+ /**
123
+ * A channel's message: one of the user's own front doors (a bot only they can message), so its
124
+ * sender is them. Its meta's `chat_id`, `message_id`, `user` and `ts` are the channel plugins'.
125
+ */
126
+ const fromChannel = (m: Json) => {
127
+ const params = field(m, "params")
128
+ const meta = field(params, "meta")
129
+ const text = (k: string) => (typeof meta[k] === "string" ? meta[k] : "")
130
+ const id =
131
+ text("message_id") === "" ? crypto.randomUUID() : `${text("chat_id")}:${text("message_id")}`
132
+ const ts = text("ts") === "" ? new Date().toISOString() : text("ts")
133
+ const content = typeof params.content === "string" ? params.content : ""
134
+ return occurrence({
135
+ name: CHANNEL_EVENT,
136
+ eventId: id,
137
+ timestamp: ts,
138
+ // Its place in the extension's own outbox, if it keeps one: acknowledged once the brain has it.
139
+ cursor: typeof params.cursor === "string" ? params.cursor : null,
140
+ data: { content, meta },
141
+ _meta: {
142
+ [RECORD]: {
143
+ sender: { handle: text("user") || text("user_id"), via: extension, me: true },
144
+ message: {
145
+ id: `${extension}:${id}`,
146
+ conversation: `${extension}:${text("chat_id")}`,
147
+ text: content,
148
+ at: Date.parse(ts),
149
+ channel: extension,
150
+ },
151
+ },
152
+ },
153
+ })
154
+ }
155
+
156
+ // A channel server has no events of its own: its messages become one.
157
+ let channel = false
158
+ const channelEvent = (): Json => {
159
+ placed.set(CHANNEL_EVENT, { kind: "message", stream: `comms/${extension}` })
160
+ return {
161
+ name: `${prefix}${CHANNEL_EVENT}`,
162
+ delivery: ["push"],
163
+ payloadSchema: RECORD_SCHEMA,
164
+ _meta: { [VERSION]: 1 },
165
+ }
166
+ }
167
+
168
+ return {
169
+ inbound: (m) => {
170
+ requests.note(m)
171
+ const params = field(m, "params")
172
+ const { name } = params
173
+ if (channel && m.method === "events/stream" && name === `${prefix}${CHANNEL_EVENT}`) {
174
+ return { forward: null, answer: { jsonrpc: "2.0", id: m.id, result: {} } }
175
+ }
176
+ if (
177
+ (m.method === "events/stream" || m.method === "events/poll") &&
178
+ typeof name === "string" &&
179
+ name.startsWith(prefix)
180
+ ) {
181
+ return pass({ ...m, params: { ...params, name: name.slice(prefix.length) } })
182
+ }
183
+ return pass(m)
184
+ },
185
+ outbound: (m) => {
186
+ const answers = requests.take(m)
187
+ if ((answers === "initialize" || answers === "server/discover") && isJson(m.result)) {
188
+ const experimental = field(field(m.result, "capabilities"), "experimental")
189
+ channel = isJson(experimental["claude/channel"])
190
+ return m
191
+ }
192
+ if (answers === "events/list") {
193
+ const listed = isJson(m.result) ? list(m.result.events).filter(isJson).map(renamed) : []
194
+ if (!channel && !isJson(m.result)) {
195
+ return m
196
+ }
197
+ const events = channel ? [...listed, channelEvent()] : listed
198
+ return { jsonrpc: "2.0", id: m.id, result: { ...field(m, "result"), events } }
199
+ }
200
+ if (m.method === "notifications/events/event") {
201
+ return { ...m, params: occurrence(field(m, "params")) }
202
+ }
203
+ if (m.method === CHANNEL) {
204
+ return { jsonrpc: "2.0", method: "notifications/events/event", params: fromChannel(m) }
205
+ }
206
+ return m
207
+ },
208
+ }
209
+ }
210
+
211
+ const refused = (id: unknown, name: string): Json => ({
212
+ jsonrpc: "2.0",
213
+ id,
214
+ result: { content: [{ type: "text", text: `${name} isn't read-only` }], isError: true },
215
+ })
216
+
217
+ /** Read-only business tools, plus the declared account sign-in/status used privately by Connections. */
218
+ export const readOnly = (): Filter => {
219
+ const requests = asked()
220
+ const looks = new Set<string>()
221
+ const auth = new Set<string>()
222
+ return {
223
+ inbound: (m) => {
224
+ if (m.method === "tools/call") {
225
+ const name = String(field(m, "params").name)
226
+ return looks.has(name) ? pass(m) : { forward: null, answer: refused(m.id, name) }
227
+ }
228
+ requests.note(m)
229
+ return pass(m)
230
+ },
231
+ outbound: (m) => {
232
+ const method = requests.take(m)
233
+ if ((method === "initialize" || method === "server/discover") && isJson(m.result)) {
234
+ auth.clear()
235
+ looks.clear()
236
+ const connections = field(field(field(m.result, "capabilities"), "extensions"), CONNECTIONS)
237
+ for (const declared of list(connections.needs).filter(isJson)) {
238
+ if (declared.kind === "key") {
239
+ continue
240
+ }
241
+ const session = field(declared, "session")
242
+ for (const name of [session.signIn, session.status]) {
243
+ if (typeof name === "string" && name !== "") {
244
+ auth.add(name)
245
+ }
246
+ }
247
+ }
248
+ }
249
+ if (method === "tools/list" && isJson(m.result)) {
250
+ looks.clear()
251
+ const tools = list(m.result.tools)
252
+ .filter(isJson)
253
+ .filter(
254
+ (t) =>
255
+ field(t, "annotations").speaksForPerson !== true &&
256
+ (field(t, "annotations").readOnlyHint === true || auth.has(String(t.name))),
257
+ )
258
+ .map((t) =>
259
+ auth.has(String(t.name))
260
+ ? {
261
+ ...t,
262
+ _meta: {
263
+ ...field(t, "_meta"),
264
+ ui: { ...field(field(t, "_meta"), "ui"), visibility: ["app"] },
265
+ },
266
+ }
267
+ : t,
268
+ )
269
+ for (const t of tools) {
270
+ looks.add(String(t.name))
271
+ }
272
+ return { ...m, result: { ...m.result, tools } }
273
+ }
274
+ return m
275
+ },
276
+ }
277
+ }
278
+
279
+ /** Filters in order on the way in, reversed on the way out. */
280
+ export const chain = (filters: readonly Filter[]): Filter => ({
281
+ inbound: (m) => {
282
+ let current = m
283
+ for (const f of filters) {
284
+ const step = f.inbound(current)
285
+ if (step.forward === null) {
286
+ return step
287
+ }
288
+ current = step.forward
289
+ }
290
+ return pass(current)
291
+ },
292
+ outbound: (m) => {
293
+ let current: Json | null = m
294
+ for (const f of filters.toReversed()) {
295
+ if (current === null) {
296
+ return null
297
+ }
298
+ current = f.outbound(current)
299
+ }
300
+ return current
301
+ },
302
+ })
package/src/side.ts ADDED
@@ -0,0 +1,27 @@
1
+ // An extension's side thread: a real thread of the agent's in a space, which the extension asks in
2
+ // (`Switch.ask`) and its words go back to, never into the space's chat. Its id says whose it is, the
3
+ // space it's in and the extension's own key for it, `side:<extension>:<space>:<key>`, so nothing
4
+ // else records them. An event of the extension's about one names it in `side`: the thread's own
5
+ // record speaks for it, so the event has no line of its own in the agent's context.
6
+
7
+ export const SIDE = "side:"
8
+
9
+ const KEY = /^[\w.-]{1,64}$/u
10
+ const ID = /^side:(?<app>[\w-]+):(?<space>[^:\s]+):(?<key>[\w.-]{1,64})$/u
11
+
12
+ /**
13
+ * The side thread of `app`'s `key` in `space` (a space's id: Home's is `home`), or null when the key
14
+ * can't name one: 1 to 64 letters, digits, `_`, `.` or `-`.
15
+ */
16
+ export const sideThread = (app: string, space: string, key: string): string | null =>
17
+ KEY.test(key) ? `${SIDE}${app}:${space}:${key}` : null
18
+
19
+ /** Whose side thread a thread is, its space and its key; null for any other thread. */
20
+ export const sideOfThread = (
21
+ thread: string,
22
+ ): { readonly app: string; readonly space: string; readonly key: string } | null => {
23
+ const m = ID.exec(thread)?.groups
24
+ return m?.app === undefined || m.space === undefined || m.key === undefined
25
+ ? null
26
+ : { app: m.app, space: m.space, key: m.key }
27
+ }
package/src/stdio.ts ADDED
@@ -0,0 +1,27 @@
1
+ // An extension's entry: its app served as MCP on stdio, until the client (its host) goes. Its host
2
+ // runs it in its own folder, which holds its outbox (`events.db`) beside the rest of its state.
3
+ import path from "node:path"
4
+ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"
5
+ import { Effect, Layer } from "effect"
6
+
7
+ import { AppEvents, serve } from "./app.ts"
8
+ import type { App, AppEventsService } from "./app.ts"
9
+
10
+ /**
11
+ * Where an extension keeps the events it emitted until the core has them: in its folder, the
12
+ * folder it runs in. Resolved when served, never on import: the desktop webview imports this
13
+ * package's root, and there `node:path` is empty, so a call at load blanked its window.
14
+ */
15
+ export const OUTBOX_FILE = "events.db"
16
+
17
+ /** Serves `app` on stdio with `layer`, its services (`Layer.empty` for none), until stdin closes. */
18
+ export const serveStdio = async <R, E>(
19
+ app: App<R>,
20
+ layer: Layer.Layer<R, E, AppEventsService>,
21
+ ): Promise<void> => {
22
+ await Effect.runPromise(
23
+ Effect.scoped(Effect.flatten(serve(app, new StdioServerTransport()))).pipe(
24
+ Effect.provide(Layer.provideMerge(layer, AppEvents.layer(app, path.resolve(OUTBOX_FILE)))),
25
+ ),
26
+ )
27
+ }
package/src/ui.ts ADDED
@@ -0,0 +1,67 @@
1
+ // UI analytics: what the user did on a surface, felt like touch. Any app's UI emits these, under its
2
+ // app.
3
+ import { Schema } from "effect"
4
+
5
+ import type { AppEvent } from "./app.ts"
6
+ import { defineEvent } from "./events.ts"
7
+ import type { DefinedEvent, Draft } from "./events.ts"
8
+
9
+ /** `surface` is where (a screen, widget or window: "clock/timers"); `item` is what in it. */
10
+ export interface Seen {
11
+ readonly surface: string
12
+ readonly item?: string
13
+ }
14
+
15
+ /** Seen for a while: how long, in ms. */
16
+ export interface Stayed extends Seen {
17
+ readonly ms: number
18
+ }
19
+
20
+ export interface Moved {
21
+ readonly surface: string
22
+ readonly from: string
23
+ readonly to: string
24
+ }
25
+
26
+ const seen = { surface: Schema.String, item: Schema.optionalKey(Schema.String) }
27
+ const stayed = Schema.Struct({ ...seen, ms: Schema.Finite })
28
+
29
+ /** Came into view. */
30
+ export const Viewed: DefinedEvent<"ui.viewed", Seen> = defineEvent(
31
+ "ui.viewed",
32
+ 1,
33
+ Schema.Struct(seen),
34
+ )
35
+
36
+ /** Opened, then left within `BACKED_OUT_MS`. */
37
+ export const BackedOut: DefinedEvent<"ui.backed_out", Stayed> = defineEvent(
38
+ "ui.backed_out",
39
+ 1,
40
+ stayed,
41
+ )
42
+
43
+ /** Moved from one item to another on the same surface. */
44
+ export const Switched: DefinedEvent<"ui.switched", Moved> = defineEvent(
45
+ "ui.switched",
46
+ 1,
47
+ Schema.Struct({ surface: Schema.String, from: Schema.String, to: Schema.String }),
48
+ )
49
+
50
+ /** Stayed on it for `ms`, then left. */
51
+ export const Dwelled: DefinedEvent<"ui.dwelled", Stayed> = defineEvent("ui.dwelled", 1, stayed)
52
+
53
+ export const uiEvents: readonly AppEvent[] = [Viewed, BackedOut, Switched, Dwelled]
54
+
55
+ export const BACKED_OUT_MS = 2000
56
+
57
+ /** What leaving something opened at `opened` (ms) says: backed out if quick, else a dwell. */
58
+ export const left = (
59
+ surface: string,
60
+ item: string | undefined,
61
+ opened: number,
62
+ now: number = Date.now(),
63
+ ): Draft => {
64
+ const ms = Math.max(0, now - opened)
65
+ const where = item === undefined ? { surface } : { surface, item }
66
+ return ms < BACKED_OUT_MS ? BackedOut.make({ ...where, ms }) : Dwelled.make({ ...where, ms })
67
+ }