switch-ext-kit 0.2.0 → 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/README.md CHANGED
@@ -85,7 +85,9 @@ A widget is A2UI 1.0, drawn by every client in Switch's look, from two catalogs
85
85
  - **Switch's catalog** (`SWITCH_CATALOG`, `SWITCH_PARTS`, its types in `SwitchParts`): the house
86
86
  parts `Line`, `Slot`, `Field`, `Title`, `Row`, `Pick`, `Feed`, `Gallery` (`images: [{ url, description? }]`, a row that scrolls sideways),
87
87
  `Check`, `Entry`, `Playing` (what's playing: art, title, who by, back, play/pause and next keys
88
- calling its tools, a rule running while it plays; paused, one quiet line), and charts that
88
+ calling its tools, a rule running while it plays; paused, one quiet line), `Document` (a
89
+ document its extension reads: a line that opens it, and in its own window the reader, its words,
90
+ lookups, threads and highlights from its tools), and charts that
89
91
  take plain data: `BarChart` (grouped or `stacked`, `horizontal`), `LineChart`, `AreaChart`,
90
92
  `Sparkline`, `DonutChart`, `ScatterChart`, `Histogram`, `CalendarHeatmap` and `Meter`.
91
93
 
@@ -95,6 +97,8 @@ A widget is A2UI 1.0, drawn by every client in Switch's look, from two catalogs
95
97
  ```
96
98
 
97
99
  A property can be bound to the widget's data (its tool's result): `series: { "@path": "/series" }`.
100
+ The data comes again whenever an event its `refresh` names lands: a type, or `*.<name>` for any
101
+ extension's `<extension>.<name>`.
98
102
  `McpApp` (`mcpApp`) is for drawing neither catalog can.
99
103
 
100
104
  ## UI copy
@@ -155,7 +159,10 @@ it was answered. `openSealed(secretKey, item, use, { enc, ct })` gives the secre
155
159
 
156
160
  Switch installs it from a git URL or package name: `extensions_install`, or Extensions in the desktop. A
157
161
  monorepo folder is installed at a commit from the core machine's `~/.switch/extensions.json`
158
- (`{ "source": "github:<owner>/<repo>#<commit>", "path": "<folder>" }`), packed from that folder.
162
+ (`{ "source": "github:<owner>/<repo>#<commit>", "path": "<folder>" }`), packed from that folder. Code
163
+ extensions share lives once in the repo, linked from each one's folder: a symlink out of the folder
164
+ packs as what it points to at that commit (Switch's vitals widget, `packages/vitals`), so a change
165
+ reaches each extension as it's pinned, with no release.
159
166
 
160
167
  ## Progress
161
168
 
@@ -171,6 +178,26 @@ account)` for a connection it needs, `request` for anything else, and `follow(ty
171
178
  brain's events (named in `reaches.follows`): each handled once, in order, resuming after the last
172
179
  one handled (`follow.json` in its folder) on every new client.
173
180
 
181
+ ## The agent
182
+
183
+ `Switch` (provided by `Models.layer`) reaches Switch itself, through a host that declares
184
+ `ax.switch/agent`:
185
+
186
+ - `ask({ key, text, space?, note?, title?, id? }, progress?)` asks the agent: a real turn of
187
+ Switch's (its memory, tools and the space's context) in the extension's own side thread `key` in
188
+ `space` (Home when absent), with `note` beside the user's words. What it says comes back
189
+ (`said`, with the turn's `status`), never in the space's chat; the space's own turns see these
190
+ threads and `history_search` finds them. `progress` hears the words as they stream. The same `id`
191
+ again (after a restart) answers from the turn that took it in. The thread is
192
+ `side:<extension>:<space>:<key>`.
193
+ - `steer(thread, text)` puts words into a live session, between its tool calls, or a turn of their
194
+ own: the extension's own side threads, or work its manifest's `reaches.steers` names (`task-*`).
195
+ - `read(query)` reads the brain as `brain_query` does, within its reach: the log's events of its own
196
+ and the types it follows, and its own side threads (`from: "work"`).
197
+
198
+ An event of its own named `<name>.wake` (or `<name>.<part>.wake`), with `{ text, space? }`, always
199
+ wakes a turn in that space (else Home) with `text`, as the senses wake one: not left to triage.
200
+
174
201
  ## Ported appendages
175
202
 
176
203
  An extension ported from a Switchboard appendage emits what the shim made of its events:
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "switch-ext-kit",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "The extension convention for Switch: tools, events, widgets and a manifest, served as MCP.",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
8
- "url": "git+https://github.com/zachsents/switch.git",
8
+ "url": "https://github.com/zachsents/switch",
9
9
  "directory": "packages/kit"
10
10
  },
11
11
  "bin": {
12
- "ui-captions": "bin/ui-captions.ts"
12
+ "ui-captions": "./bin/ui-captions.ts"
13
13
  },
14
14
  "files": [
15
15
  "src",
package/src/app.ts CHANGED
@@ -39,8 +39,9 @@ export const VERSION = "ax.switch/version"
39
39
  export const CONNECTIONS = "ax.switch/connections"
40
40
  /**
41
41
  * What an extension reaches beyond itself, in its handshake: other extensions' tools it calls
42
- * (`switch/call`) and the brain's event types it follows (`switch/follow`), each a name or a
43
- * prefix ending in `*`. Nothing else is answered.
42
+ * (`switch/call`), the brain's event types it follows (`switch/follow`) and the work whose live
43
+ * sessions it may steer beyond its own side threads (`switch/steer`), each a name or a prefix
44
+ * ending in `*`. Nothing else is answered.
44
45
  */
45
46
  export const REACHES = "ax.switch/reaches"
46
47
  /**
@@ -111,6 +112,8 @@ export interface Tool<R> {
111
112
  readonly name: string
112
113
  readonly description: string
113
114
  readonly readOnly: boolean
115
+ /** What it changes stays in Switch: the brain, or the user's own chat (MCP's openWorldHint false). */
116
+ readonly closed: boolean
114
117
  /** It sends something out in the user's name: the Outbound gate reads it first. */
115
118
  readonly speaks: boolean
116
119
  /** Only the user's clients call it, never the agent (MCP Apps' `visibility: ["app"]`). */
@@ -126,6 +129,8 @@ interface ToolOptions {
126
129
  readonly description: string
127
130
  /** It only looks, changing nothing. */
128
131
  readonly readOnly?: boolean
132
+ /** What it changes stays in Switch: the brain, or the user's own chat. */
133
+ readonly closed?: boolean
129
134
  /** It sends something out in the user's name (a text, an email, a call). */
130
135
  readonly speaks?: boolean
131
136
  /** Only the user's clients call it, never the agent. */
@@ -153,6 +158,7 @@ export function tool<R>(
153
158
  name,
154
159
  description: options.description,
155
160
  readOnly: options.readOnly === true,
161
+ closed: options.closed === true,
156
162
  speaks: options.speaks === true,
157
163
  appOnly: options.appOnly === true,
158
164
  input: input && standard(input),
@@ -225,7 +231,8 @@ export interface Widget {
225
231
  readonly surfaces: readonly Surface[]
226
232
  /** Its content: a `ui://` resource of A2UI messages. */
227
233
  readonly resource: string
228
- /** The read-only tool whose structured result is its data model, and the events that refresh it. */
234
+ /** The read-only tool whose structured result is its data model, and the events that refresh it
235
+ * (a type, or `*.<name>`: any extension's `<extension>.<name>`). */
229
236
  readonly tool?: string
230
237
  readonly refresh?: readonly string[]
231
238
  /** How it sits in a space's grid; none is `auto`. */
@@ -240,7 +247,8 @@ export const widget: Schema.Codec<Widget> = Schema.Struct({
240
247
  surfaces: Schema.Array(surface),
241
248
  /** Its content: a `ui://` resource of A2UI messages. */
242
249
  resource: Schema.String,
243
- /** The read-only tool whose structured result is its data model, and the events that refresh it. */
250
+ /** The read-only tool whose structured result is its data model, and the events that refresh it
251
+ * (a type, or `*.<name>`: any extension's `<extension>.<name>`). */
244
252
  tool: Schema.optionalKey(Schema.String),
245
253
  refresh: Schema.optionalKey(Schema.Array(Schema.String)),
246
254
  /** How it sits in a space's grid; none is `auto`. */
@@ -261,7 +269,7 @@ export interface App<R = never> {
261
269
  readonly version: string
262
270
  readonly instructions?: string
263
271
  readonly connections: readonly Need[]
264
- /** What it reaches beyond itself (`REACHES`): tools it calls, brain event types it follows. */
272
+ /** What it reaches beyond itself (`REACHES`): tools it calls, events it follows, work it steers. */
265
273
  readonly reaches?: Reaches
266
274
  readonly tools: readonly Tool<R>[]
267
275
  /** Its own events plus the UI analytics family, which every app publishes. */
@@ -269,10 +277,15 @@ export interface App<R = never> {
269
277
  readonly widgets: readonly WidgetDef[]
270
278
  }
271
279
 
272
- /** Tools an extension calls (`switch/call`) and brain event types it follows (`switch/follow`). */
280
+ /**
281
+ * Tools an extension calls (`switch/call`), brain event types it follows (`switch/follow`), and
282
+ * threads whose live sessions it steers beyond its own side threads (`switch/steer`): `task-*`,
283
+ * `space:*`, or one.
284
+ */
273
285
  export interface Reaches {
274
286
  readonly calls?: readonly string[]
275
287
  readonly follows?: readonly string[]
288
+ readonly steers?: readonly string[]
276
289
  }
277
290
 
278
291
  export const defineApp = <R = never>(app: {
@@ -571,6 +584,8 @@ const again = (name: string, finished: boolean): CallToolResult =>
571
584
  }
572
585
 
573
586
  const anything = Schema.toStandardSchemaV1(Schema.Record(Schema.String, Schema.Unknown))
587
+ /** How long a request that says how it's going may go without a word before it's given up. */
588
+ const PROGRESS_SILENCE_MS = 90_000
574
589
  const streamParams = Schema.toStandardSchemaV1(
575
590
  Schema.Struct({
576
591
  name: Schema.String,
@@ -612,6 +627,7 @@ export const serve: <R>(
612
627
  [REACHES]: {
613
628
  ...(app.reaches.calls !== undefined && { calls: [...app.reaches.calls] }),
614
629
  ...(app.reaches.follows !== undefined && { follows: [...app.reaches.follows] }),
630
+ ...(app.reaches.steers !== undefined && { steers: [...app.reaches.steers] }),
615
631
  },
616
632
  }),
617
633
  },
@@ -627,7 +643,11 @@ export const serve: <R>(
627
643
  const fed = app.widgets.find((w) => w.tool === t.name)
628
644
  const config = {
629
645
  description: t.description,
630
- annotations: { readOnlyHint: t.readOnly, ...(t.speaks && { speaksForPerson: true }) },
646
+ annotations: {
647
+ readOnlyHint: t.readOnly,
648
+ ...(t.closed && { openWorldHint: false }),
649
+ ...(t.speaks && { speaksForPerson: true }),
650
+ },
631
651
  _meta: {
632
652
  ui: {
633
653
  ...(fed && { resourceUri: fed.resource }),
@@ -783,8 +803,26 @@ export const serve: <R>(
783
803
  // Models through the client, once it's connected. A client that doesn't answer them (no
784
804
  // `ax.switch/models`) fails each request, and the call with it.
785
805
  const peer = yield* Effect.serviceOption(Peer)
786
- const send = async (method: string, params: Readonly<Record<string, unknown>>) =>
787
- await mcp.server.request({ method, params: { ...params } }, anything)
806
+ // A request that says how it's going (`progress`) waits as long as it does: each word of it
807
+ // starts the wait again.
808
+ const send = async (
809
+ method: string,
810
+ params: Readonly<Record<string, unknown>>,
811
+ progress?: (message: string) => void,
812
+ ) =>
813
+ await mcp.server.request(
814
+ { method, params: { ...params } },
815
+ anything,
816
+ progress === undefined
817
+ ? undefined
818
+ : {
819
+ timeout: PROGRESS_SILENCE_MS,
820
+ resetTimeoutOnProgress: true,
821
+ onprogress: (p) => {
822
+ progress(p.message ?? "")
823
+ },
824
+ },
825
+ )
788
826
  // MCP's own hooks, not DOM targets.
789
827
  Object.assign(mcp.server, {
790
828
  onclose: () => {
package/src/catalog.ts CHANGED
@@ -173,6 +173,39 @@ export interface Playing {
173
173
  readonly next: string
174
174
  }
175
175
 
176
+ /**
177
+ * A document its extension reads: in a chat or a space, a line that opens it; in a window of its
178
+ * own (its `widget` with `{ doc }`), the reader, its words a section at a time from `tools.content`
179
+ * (`{ doc }` gives `{ sections: [{ label?, markdown }] }`), a selection's lookup from `tools.define`
180
+ * (`{ term | url, doc }`), threads asked with `tools.ask` (`{ doc, thread, question, quote? }`) and
181
+ * highlights with `tools.highlight` and `tools.unhighlight`. A passage (`quote`) is
182
+ * `{ section, exact, prefix?, suffix? }`.
183
+ */
184
+ export interface Document {
185
+ readonly doc: Bound<string>
186
+ readonly title: Bound<string>
187
+ /** Its kind (`pdf` numbers its pages). */
188
+ readonly format?: Bound<string>
189
+ /** Its size, in a few words. */
190
+ readonly detail?: Bound<string>
191
+ /** Moves when its words change, so they're read again. */
192
+ readonly version?: Bound<number>
193
+ readonly highlights?: Bound<readonly unknown[]>
194
+ readonly threads?: Bound<readonly unknown[]>
195
+ /** A thread to show open. */
196
+ readonly open?: Bound<string>
197
+ readonly threadCount?: Bound<number>
198
+ /** The widget that is the document in its own window. */
199
+ readonly widget: string
200
+ readonly tools: {
201
+ readonly content: string
202
+ readonly define?: string
203
+ readonly ask?: string
204
+ readonly highlight?: string
205
+ readonly unhighlight?: string
206
+ }
207
+ }
208
+
176
209
  /** A line to write in: Enter calls `action` with `args` and the words under `field`. */
177
210
  export interface Entry {
178
211
  readonly placeholder?: Bound<string>
@@ -287,6 +320,7 @@ export interface SwitchParts {
287
320
  readonly Check: Check
288
321
  readonly Entry: Entry
289
322
  readonly Playing: Playing
323
+ readonly Document: Document
290
324
  readonly BarChart: BarChart
291
325
  readonly LineChart: LineChart
292
326
  readonly AreaChart: AreaChart
@@ -399,6 +433,25 @@ export const SWITCH_PARTS: { readonly [K in keyof SwitchParts]: Schema.Codec<Swi
399
433
  toggle: Schema.String,
400
434
  next: Schema.String,
401
435
  }),
436
+ Document: Schema.Struct({
437
+ doc: text,
438
+ title: text,
439
+ format: Schema.optionalKey(text),
440
+ detail: Schema.optionalKey(text),
441
+ version: Schema.optionalKey(number),
442
+ highlights: Schema.optionalKey(bound(Schema.Array(Schema.Unknown))),
443
+ threads: Schema.optionalKey(bound(Schema.Array(Schema.Unknown))),
444
+ open: Schema.optionalKey(text),
445
+ threadCount: Schema.optionalKey(number),
446
+ widget: Schema.String,
447
+ tools: Schema.Struct({
448
+ content: Schema.String,
449
+ define: Schema.optionalKey(Schema.String),
450
+ ask: Schema.optionalKey(Schema.String),
451
+ highlight: Schema.optionalKey(Schema.String),
452
+ unhighlight: Schema.optionalKey(Schema.String),
453
+ }),
454
+ }),
402
455
  BarChart: Schema.Struct({
403
456
  ...lines,
404
457
  stacked: Schema.optionalKey(Schema.Boolean),
package/src/index.ts CHANGED
@@ -79,7 +79,7 @@ export type {
79
79
  StoredEvent,
80
80
  } from "./log.ts"
81
81
  export { manifest, need, readManifest } from "./manifest.ts"
82
- export { Asks, ASKS, Host, ModelError, Models, MODELS, Peer } from "./models.ts"
82
+ export { AGENT, Asks, ASKS, Host, ModelError, Models, MODELS, Peer, Switch } from "./models.ts"
83
83
  export type {
84
84
  AskAttachment,
85
85
  AskDraft,
@@ -101,12 +101,17 @@ export type {
101
101
  Question,
102
102
  Role,
103
103
  Send,
104
+ SwitchAnswer,
105
+ SwitchAsk,
106
+ SwitchService,
107
+ SwitchShape,
104
108
  } from "./models.ts"
105
109
  export type { Manifest, Need } from "./manifest.ts"
106
110
  export { chain, isJson, readOnly, switchboard } from "./shim.ts"
107
111
  export type { Filter, Json } from "./shim.ts"
108
112
  export { OUTBOX_FILE, serveStdio } from "./stdio.ts"
109
113
  export { writeFileAtomic } from "./files.ts"
114
+ export { SIDE, sideOfThread, sideThread } from "./side.ts"
110
115
  export { defineRecord, RecordPayload } from "./record.ts"
111
116
  export type { Envelope, RecordEvent, RecordShape } from "./record.ts"
112
117
  export { BACKED_OUT_MS, BackedOut, Dwelled, left, Switched, uiEvents, Viewed } from "./ui.ts"
package/src/models.ts CHANGED
@@ -3,7 +3,9 @@
3
3
  // them with the user's own profile: `models/decide` picks among choices, `models/complete` writes
4
4
  // text. The same connection carries an extension's action items (`ax.switch/asks`): `asks/open` and
5
5
  // `asks/close`, and the rest it asks of the host (`Host`): other extensions' tools, the user's
6
- // connections, and brain events it follows.
6
+ // connections, and brain events it follows. And it reaches the agent itself (`Switch`, under
7
+ // `ax.switch/agent`): asks it in a side thread of its own, steers a live session, reads the brain
8
+ // within its reach.
7
9
  import { existsSync, readFileSync } from "node:fs"
8
10
  import path from "node:path"
9
11
  import { Context, Deferred, Effect, Layer, Option, Queue, Schema } from "effect"
@@ -94,8 +96,15 @@ export interface ModelsService {
94
96
  readonly Models: unique symbol
95
97
  }
96
98
 
97
- /** Sends one request to the client and decodes its result. */
98
- export type Send = (method: string, params: Readonly<Record<string, unknown>>) => Promise<unknown>
99
+ /**
100
+ * Sends one request to the client. With `progress`, it hears how the request is going and waits as
101
+ * long as that goes on.
102
+ */
103
+ export type Send = (
104
+ method: string,
105
+ params: Readonly<Record<string, unknown>>,
106
+ progress?: (message: string) => void,
107
+ ) => Promise<unknown>
99
108
 
100
109
  /** A brain event an extension follows (`switch/follow`), as the host sends it (`switch/event`). */
101
110
  export interface Followed {
@@ -186,6 +195,13 @@ export interface AskInput {
186
195
  readonly answerTo?: string
187
196
  /** A sealed ask's one-time key (`sealedKey().key`) and what the secret is for. */
188
197
  readonly sealed?: { readonly key: string; readonly use: string }
198
+ /**
199
+ * Approved only with the user's passkey: one of its own tools (best `appOnly`) the core calls with
200
+ * `{ item, step: "options", origin, rp }`, answering `{ mode: "create" | "get", challenge, … }`
201
+ * for the page its link opens, then `{ item, step: "verify", origin, rp, credential, window }`
202
+ * with what the authenticator answered, answering `{ ok, said? }`. It verifies and closes the item.
203
+ */
204
+ readonly passkey?: string
189
205
  }
190
206
 
191
207
  export interface AsksShape {
@@ -264,117 +280,221 @@ const FOLLOW_FILE = "follow.json"
264
280
  const matches = (patterns: readonly string[], type: string) =>
265
281
  patterns.some((p) => (p.endsWith("*") ? type.startsWith(p.slice(0, -1)) : p === type))
266
282
 
267
- const modelsLayer: Layer.Layer<ModelsService | AsksService | HostService | PeerService> =
268
- Layer.effectContext(
269
- Effect.gen(function* making() {
270
- const ready = yield* Deferred.make<Send | null>()
271
- let current: Send | null = null
272
- const handlers: {
273
- readonly types: readonly string[]
274
- readonly handle: (e: Followed) => Effect.Effect<void>
275
- }[] = []
276
- const file = path.resolve(FOLLOW_FILE)
277
- let after = Option.match(
278
- existsSync(file) ? lastHandled(readFileSync(file, "utf-8")) : Option.none(),
279
- { onNone: () => 0, onSome: (x) => x.after },
280
- )
281
- const heard = yield* Queue.unbounded<Followed>()
282
- yield* Effect.forkScoped(
283
- Effect.forever(
284
- Effect.gen(function* handling() {
285
- const e = yield* Queue.take(heard)
286
- if (e.seq <= after) {
287
- return
288
- }
289
- for (const h of handlers) {
290
- if (matches(h.types, e.type)) {
291
- yield* h.handle(e)
292
- }
293
- }
294
- after = e.seq
295
- writeFileAtomic(file, JSON.stringify({ after }))
296
- }),
297
- ),
298
- )
299
- const refollow = (send: Send) => {
300
- const types = [...new Set(handlers.flatMap((h) => h.types))]
301
- if (types.length > 0) {
302
- void send("switch/follow", { types, after }).catch(() => {
303
- /* the next client follows again */
304
- })
305
- }
306
- }
307
- const peer: PeerShape = {
308
- attach: (send) => {
309
- current = send
310
- Deferred.doneUnsafe(ready, Effect.succeed(send))
311
- if (send !== null) {
312
- refollow(send)
283
+ /** The client capability extension a host declares when it reaches the agent for extensions. */
284
+ export const AGENT = "ax.switch/agent"
285
+
286
+ /**
287
+ * An ask of the agent: the user's words (`text`), asked in the extension's side thread `key` (its
288
+ * own name for it: 1 to 64 letters, digits, `_`, `.` or `-`) in `space` (an id or a name; Home
289
+ * when absent). `note` goes beside the words for the agent: what they're about (a document, the
290
+ * passage). `title` names the thread when it opens. `id` makes it once: the same id again (after a
291
+ * restart) answers from the same turn; a fresh one when absent.
292
+ */
293
+ export interface SwitchAsk {
294
+ readonly key: string
295
+ readonly text: string
296
+ readonly space?: string
297
+ readonly note?: string
298
+ readonly title?: string
299
+ readonly id?: string
300
+ }
301
+
302
+ /**
303
+ * What the turn that took it in said back (each say, in order), its thread (`side:<app>:<space>:<key>`)
304
+ * and turn, and how it ended: `done`, or `interrupted`, `failed` or `limited` with `result` saying why.
305
+ */
306
+ export interface SwitchAnswer {
307
+ readonly thread: string
308
+ readonly turn: string | null
309
+ readonly said: readonly string[]
310
+ readonly status: string
311
+ readonly result: string
312
+ }
313
+
314
+ export interface SwitchShape {
315
+ /**
316
+ * Asks the agent: a real turn of Switch's, the space's memory and context in it, in a thread the
317
+ * extension owns, never in the space's chat. `progress` hears its words as they stream: the turn's
318
+ * text so far, then what it said.
319
+ */
320
+ readonly ask: (
321
+ ask: SwitchAsk,
322
+ progress?: (soFar: string) => Effect.Effect<void>,
323
+ ) => Effect.Effect<SwitchAnswer, ModelError>
324
+ /**
325
+ * Words into a live session, between its tool calls, or a turn of their own: one of its own side
326
+ * threads, or work its manifest's `reaches.steers` names.
327
+ */
328
+ readonly steer: (thread: string, text: string) => Effect.Effect<void, ModelError>
329
+ /**
330
+ * The brain, as `brain_query` reads it, within its reach: the log's events of its own and of the
331
+ * types it follows (`from: "events"`), and its own side threads (`from: "work"`).
332
+ */
333
+ readonly read: (
334
+ query: Readonly<Record<string, unknown>>,
335
+ ) => Effect.Effect<readonly Readonly<Record<string, unknown>>[], ModelError>
336
+ }
337
+
338
+ /** The `Switch` service's identifier, as a requirement. */
339
+ export interface SwitchService {
340
+ readonly Switch: unique symbol
341
+ }
342
+
343
+ const switchKey: Context.Service<SwitchService, SwitchShape> = Context.Service<
344
+ SwitchService,
345
+ SwitchShape
346
+ >("switch-ext-kit/Switch")
347
+
348
+ const switchAnswer = Schema.Struct({
349
+ thread: Schema.String,
350
+ turn: Schema.NullOr(Schema.String),
351
+ said: Schema.Array(Schema.String),
352
+ status: Schema.String,
353
+ result: Schema.String,
354
+ })
355
+ const rows = Schema.Struct({ rows: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)) })
356
+
357
+ /** What `Models.layer` provides. */
358
+ type HostServices = ModelsService | AsksService | HostService | PeerService | SwitchService
359
+
360
+ const modelsLayer: Layer.Layer<HostServices> = Layer.effectContext(
361
+ Effect.gen(function* making() {
362
+ const ready = yield* Deferred.make<Send | null>()
363
+ let current: Send | null = null
364
+ const handlers: {
365
+ readonly types: readonly string[]
366
+ readonly handle: (e: Followed) => Effect.Effect<void>
367
+ }[] = []
368
+ const file = path.resolve(FOLLOW_FILE)
369
+ let after = Option.match(
370
+ existsSync(file) ? lastHandled(readFileSync(file, "utf-8")) : Option.none(),
371
+ { onNone: () => 0, onSome: (x) => x.after },
372
+ )
373
+ const heard = yield* Queue.unbounded<Followed>()
374
+ yield* Effect.forkScoped(
375
+ Effect.forever(
376
+ Effect.gen(function* handling() {
377
+ const e = yield* Queue.take(heard)
378
+ if (e.seq <= after) {
379
+ return
313
380
  }
314
- },
315
- heard: (raw) => {
316
- const e = decodeFollowed(raw)
317
- if (Option.isSome(e)) {
318
- Queue.offerUnsafe(heard, e.value)
381
+ for (const h of handlers) {
382
+ if (matches(h.types, e.type)) {
383
+ yield* h.handle(e)
384
+ }
319
385
  }
320
- },
386
+ after = e.seq
387
+ writeFileAtomic(file, JSON.stringify({ after }))
388
+ }),
389
+ ),
390
+ )
391
+ const refollow = (send: Send) => {
392
+ const types = [...new Set(handlers.flatMap((h) => h.types))]
393
+ if (types.length > 0) {
394
+ void send("switch/follow", { types, after }).catch(() => {
395
+ /* the next client follows again */
396
+ })
321
397
  }
322
- const ask = <A>(
323
- method: string,
324
- params: Readonly<Record<string, unknown>>,
325
- result: Schema.Codec<A, unknown>,
326
- ) =>
398
+ }
399
+ const peer: PeerShape = {
400
+ attach: (send) => {
401
+ current = send
402
+ Deferred.doneUnsafe(ready, Effect.succeed(send))
403
+ if (send !== null) {
404
+ refollow(send)
405
+ }
406
+ },
407
+ heard: (raw) => {
408
+ const e = decodeFollowed(raw)
409
+ if (Option.isSome(e)) {
410
+ Queue.offerUnsafe(heard, e.value)
411
+ }
412
+ },
413
+ }
414
+ const ask = <A>(
415
+ method: string,
416
+ params: Readonly<Record<string, unknown>>,
417
+ result: Schema.Codec<A, unknown>,
418
+ progress?: (message: string) => void,
419
+ ) =>
420
+ Effect.gen(function* asking() {
421
+ const send = yield* Deferred.await(ready).pipe(
422
+ Effect.timeoutOrElse({
423
+ duration: CONNECT_MS,
424
+ orElse: () => Effect.fail(new ModelError({ message: "No host connected" })),
425
+ }),
426
+ )
427
+ const now = current ?? send
428
+ if (now === null) {
429
+ return yield* Effect.fail(new ModelError({ message: "The host offers none" }))
430
+ }
431
+ const raw = yield* Effect.tryPromise({
432
+ try: async () => await now(method, params, progress),
433
+ catch: failed,
434
+ })
435
+ return yield* Schema.decodeUnknownEffect(result)(raw).pipe(Effect.mapError(failed))
436
+ })
437
+ const models: ModelsShape = {
438
+ decide: (input, questions, role = "decision") =>
439
+ ask("models/decide", { input, questions, role }, decision),
440
+ complete: (role, system, prompt) =>
441
+ ask("models/complete", { role, system, prompt }, completion),
442
+ }
443
+ const asks: AsksShape = {
444
+ open: (input, id) =>
445
+ ask("asks/open", { ask: input, ...(id !== undefined && { id }) }, opened),
446
+ close: (id, status) => Effect.asVoid(ask("asks/close", { id, status }, Schema.Unknown)),
447
+ }
448
+ const host: HostShape = {
449
+ request: ask,
450
+ call: (name, args) => ask("switch/call", { name, arguments: args }, record),
451
+ accounts: (provider) =>
452
+ Effect.map(ask("connections/list", { provider }, accountList), (r) =>
453
+ r.accounts.map((a) => a.account),
454
+ ),
455
+ token: (provider, account) =>
456
+ Effect.map(ask("connections/token", { provider, account }, tokenOf), (t) => t.token),
457
+ follow: (types, handle) =>
458
+ Effect.gen(function* following() {
459
+ handlers.push({ types, handle })
460
+ const all = [...new Set(handlers.flatMap((h) => h.types))]
461
+ yield* ask("switch/follow", { types: all, after }, Schema.Unknown)
462
+ }),
463
+ }
464
+ const agent: SwitchShape = {
465
+ ask: (input, progress) =>
327
466
  Effect.gen(function* asking() {
328
- const send = yield* Deferred.await(ready).pipe(
329
- Effect.timeoutOrElse({
330
- duration: CONNECT_MS,
331
- orElse: () => Effect.fail(new ModelError({ message: "No host connected" })),
332
- }),
333
- )
334
- const now = current ?? send
335
- if (now === null) {
336
- return yield* Effect.fail(new ModelError({ message: "The host offers none" }))
467
+ const id = input.id ?? crypto.randomUUID()
468
+ const streamed = yield* Queue.unbounded<string>()
469
+ const telling = progress
470
+ if (telling !== undefined) {
471
+ yield* Effect.forkScoped(
472
+ Effect.forever(Effect.flatMap(Queue.take(streamed), (t) => telling(t))),
473
+ )
337
474
  }
338
- const raw = yield* Effect.tryPromise({
339
- try: async () => await now(method, params),
340
- catch: failed,
475
+ return yield* ask("switch/ask", { ...input, id }, switchAnswer, (message) => {
476
+ Queue.offerUnsafe(streamed, message)
341
477
  })
342
- return yield* Schema.decodeUnknownEffect(result)(raw).pipe(Effect.mapError(failed))
343
- })
344
- const models: ModelsShape = {
345
- decide: (input, questions, role = "decision") =>
346
- ask("models/decide", { input, questions, role }, decision),
347
- complete: (role, system, prompt) =>
348
- ask("models/complete", { role, system, prompt }, completion),
349
- }
350
- const asks: AsksShape = {
351
- open: (input, id) =>
352
- ask("asks/open", { ask: input, ...(id !== undefined && { id }) }, opened),
353
- close: (id, status) => Effect.asVoid(ask("asks/close", { id, status }, Schema.Unknown)),
354
- }
355
- const host: HostShape = {
356
- request: ask,
357
- call: (name, args) => ask("switch/call", { name, arguments: args }, record),
358
- accounts: (provider) =>
359
- Effect.map(ask("connections/list", { provider }, accountList), (r) =>
360
- r.accounts.map((a) => a.account),
361
- ),
362
- token: (provider, account) =>
363
- Effect.map(ask("connections/token", { provider, account }, tokenOf), (t) => t.token),
364
- follow: (types, handle) =>
365
- Effect.gen(function* following() {
366
- handlers.push({ types, handle })
367
- const all = [...new Set(handlers.flatMap((h) => h.types))]
368
- yield* ask("switch/follow", { types: all, after }, Schema.Unknown)
369
- }),
370
- }
371
- return Context.make(modelsKey, models).pipe(
372
- Context.add(asksKey, asks),
373
- Context.add(hostKey, host),
374
- Context.add(Peer, peer),
375
- )
376
- }),
377
- )
478
+ }).pipe(Effect.scoped),
479
+ steer: (thread, text) =>
480
+ Effect.asVoid(
481
+ ask("switch/steer", { thread, text, id: crypto.randomUUID() }, Schema.Unknown),
482
+ ),
483
+ read: (query) => Effect.map(ask("switch/read", query, rows), (r) => r.rows),
484
+ }
485
+ return Context.make(modelsKey, models).pipe(
486
+ Context.add(asksKey, asks),
487
+ Context.add(hostKey, host),
488
+ Context.add(switchKey, agent),
489
+ Context.add(Peer, peer),
490
+ )
491
+ }),
492
+ )
493
+
494
+ /** The agent through the host: provided by `Models.layer`, which `serve` connects. */
495
+ export const Switch: Context.Service<SwitchService, SwitchShape> & {
496
+ readonly layer: typeof modelsLayer
497
+ } = Object.assign(switchKey, { layer: modelsLayer })
378
498
 
379
499
  /** The host's other services (calls, connections, follows): provided by `Models.layer`. */
380
500
  export const Host: Context.Service<HostService, HostShape> & {
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
+ }