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/README.md +214 -2
- package/bin/ui-captions.ts +559 -0
- package/package.json +55 -4
- package/src/a2ui.ts +63 -0
- package/src/app.ts +852 -0
- package/src/catalog.ts +810 -0
- package/src/events.ts +81 -0
- package/src/files.ts +22 -0
- package/src/index.ts +135 -0
- package/src/laptop.ts +475 -0
- package/src/log.ts +373 -0
- package/src/manifest.ts +113 -0
- package/src/messages.ts +94 -0
- package/src/models.ts +512 -0
- package/src/record.ts +84 -0
- package/src/sealed.ts +177 -0
- package/src/shell.ts +244 -0
- package/src/shim.ts +302 -0
- package/src/side.ts +27 -0
- package/src/stdio.ts +27 -0
- package/src/ui.ts +67 -0
package/src/log.ts
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
// An extension's own event log: its events on its own SQLite file, with read models over them.
|
|
2
|
+
// Switch's brain write path, cut down to what an extension needs. That path follows T3 Code's
|
|
3
|
+
// orchestration-v2, MIT, Copyright (c) 2026 T3 Tools Inc.: decide, then one transaction for events
|
|
4
|
+
// and projections, then publish after commit.
|
|
5
|
+
import { Database } from "bun:sqlite"
|
|
6
|
+
import { mkdirSync } from "node:fs"
|
|
7
|
+
import path from "node:path"
|
|
8
|
+
import { Context, Effect, Layer, Option, PubSub, Result, Schema, Semaphore, Stream } from "effect"
|
|
9
|
+
import type { Scope } from "effect"
|
|
10
|
+
|
|
11
|
+
import { Rejected } from "./events.ts"
|
|
12
|
+
import type { Check, Draft, EventDef, Payload } from "./events.ts"
|
|
13
|
+
|
|
14
|
+
/** One row of the log. `payload` is the encoded JSON form. */
|
|
15
|
+
export interface StoredEvent {
|
|
16
|
+
readonly seq: number
|
|
17
|
+
readonly id: string
|
|
18
|
+
readonly time: number
|
|
19
|
+
readonly type: string
|
|
20
|
+
readonly v: number
|
|
21
|
+
readonly source: string
|
|
22
|
+
readonly payload: unknown
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What a command decides: events to write, or why not. */
|
|
26
|
+
export type Decision = { readonly events: readonly Draft[] } | { readonly reject: string }
|
|
27
|
+
|
|
28
|
+
export interface CommandDef {
|
|
29
|
+
readonly type: string
|
|
30
|
+
readonly handle: (db: Database, payload: unknown) => Decision
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A command as `defineCommand` makes it: typed, with its schema. */
|
|
34
|
+
export interface DefinedCommand<T extends string, P, S> extends CommandDef {
|
|
35
|
+
readonly type: T
|
|
36
|
+
readonly payload: Payload<P>
|
|
37
|
+
readonly load: (db: Database, payload: P) => S
|
|
38
|
+
readonly decide: (state: S, payload: P) => Decision
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** `load` reads projections; `decide` is pure. Both run in the writer's turn, so nothing interleaves. */
|
|
42
|
+
export const defineCommand = <const T extends string, P, S>(def: {
|
|
43
|
+
readonly type: T
|
|
44
|
+
readonly payload: Payload<P>
|
|
45
|
+
readonly load: (db: Database, payload: P) => S
|
|
46
|
+
readonly decide: (state: S, payload: P) => Decision
|
|
47
|
+
}): DefinedCommand<T, P, S> => {
|
|
48
|
+
const decode = Schema.decodeUnknownResult(def.payload)
|
|
49
|
+
return {
|
|
50
|
+
...def,
|
|
51
|
+
handle: (db: Database, raw: unknown): Decision => {
|
|
52
|
+
const p = decode(raw)
|
|
53
|
+
return Result.isSuccess(p)
|
|
54
|
+
? def.decide(def.load(db, p.success), p.success)
|
|
55
|
+
: { reject: `${def.type}: ${p.failure.message}` }
|
|
56
|
+
},
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** How one event type changes a projection's tables. */
|
|
61
|
+
export interface On {
|
|
62
|
+
readonly type: string
|
|
63
|
+
readonly apply: (db: Database, event: StoredEvent) => void
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const on = <P>(
|
|
67
|
+
def: { readonly type: string; readonly decode: (encoded: unknown) => P },
|
|
68
|
+
apply: (db: Database, payload: P, event: StoredEvent) => void,
|
|
69
|
+
): On => ({
|
|
70
|
+
type: def.type,
|
|
71
|
+
apply: (db, event) => {
|
|
72
|
+
apply(db, def.decode(event.payload), event)
|
|
73
|
+
},
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
/** A named read model, updated in the write transaction and rebuilt from the log when its version moves. */
|
|
77
|
+
export interface Projection {
|
|
78
|
+
readonly name: string
|
|
79
|
+
/** Bump to rebuild on next open. */
|
|
80
|
+
readonly version: number
|
|
81
|
+
readonly tables: readonly string[]
|
|
82
|
+
readonly create: string
|
|
83
|
+
readonly on: readonly On[]
|
|
84
|
+
readonly snapshot: (db: Database) => unknown
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface LogConfig {
|
|
88
|
+
/** A file path, or ":memory:". */
|
|
89
|
+
readonly path: string
|
|
90
|
+
readonly events: readonly EventDef[]
|
|
91
|
+
readonly projections: readonly Projection[]
|
|
92
|
+
readonly commands: readonly CommandDef[]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** `id` is the caller's: a retry with the same id is a no-op. */
|
|
96
|
+
export interface Command {
|
|
97
|
+
readonly id: string
|
|
98
|
+
readonly type: string
|
|
99
|
+
readonly source: string
|
|
100
|
+
readonly payload: unknown
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface Receipt {
|
|
104
|
+
readonly seq: number
|
|
105
|
+
readonly duplicate: boolean
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface Snapshot {
|
|
109
|
+
readonly seq: number
|
|
110
|
+
readonly state: Readonly<Record<string, unknown>>
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface LogShape {
|
|
114
|
+
readonly dispatch: (command: Command) => Effect.Effect<Receipt, Rejected>
|
|
115
|
+
readonly snapshot: Effect.Effect<Snapshot>
|
|
116
|
+
/** Every event after `seq`: the log first, then live, with no gap and no repeat. */
|
|
117
|
+
readonly changes: (seq: number) => Stream.Stream<StoredEvent>
|
|
118
|
+
readonly read: <A>(f: (db: Database) => A) => Effect.Effect<A>
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The `Log` service's identifier, as a requirement. */
|
|
122
|
+
export interface LogService {
|
|
123
|
+
readonly Log: unique symbol
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const SCHEMA = `
|
|
127
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
128
|
+
seq INTEGER PRIMARY KEY, id TEXT NOT NULL UNIQUE, time INTEGER NOT NULL,
|
|
129
|
+
type TEXT NOT NULL, v INTEGER NOT NULL, source TEXT NOT NULL, payload TEXT NOT NULL);
|
|
130
|
+
CREATE TABLE IF NOT EXISTS commands (id TEXT PRIMARY KEY, seq INTEGER NOT NULL);
|
|
131
|
+
CREATE TABLE IF NOT EXISTS projections (name TEXT PRIMARY KEY, version INTEGER NOT NULL);
|
|
132
|
+
`
|
|
133
|
+
|
|
134
|
+
const PAGE = 1000
|
|
135
|
+
|
|
136
|
+
interface Row {
|
|
137
|
+
readonly seq: number
|
|
138
|
+
readonly id: string
|
|
139
|
+
readonly time: number
|
|
140
|
+
readonly type: string
|
|
141
|
+
readonly v: number
|
|
142
|
+
readonly source: string
|
|
143
|
+
readonly payload: string
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
interface Prepared {
|
|
147
|
+
readonly id: string
|
|
148
|
+
readonly time: number
|
|
149
|
+
readonly type: string
|
|
150
|
+
readonly v: number
|
|
151
|
+
readonly source: string
|
|
152
|
+
readonly encoded: unknown
|
|
153
|
+
readonly json: string
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const parseJson: (json: string) => unknown = JSON.parse
|
|
157
|
+
|
|
158
|
+
const toStored = (row: Row): StoredEvent => ({ ...row, payload: parseJson(row.payload) })
|
|
159
|
+
|
|
160
|
+
const checked = (def: { readonly check: Check } | undefined, d: Draft) => {
|
|
161
|
+
if (!def) {
|
|
162
|
+
return new Rejected({ reason: `Unknown type ${d.type}` })
|
|
163
|
+
}
|
|
164
|
+
const result = def.check(d.payload)
|
|
165
|
+
return Result.isSuccess(result)
|
|
166
|
+
? { encoded: result.success, json: JSON.stringify(result.success) }
|
|
167
|
+
: new Rejected({ reason: `${d.type}: ${result.failure}` })
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const open = (file: string) => {
|
|
171
|
+
if (file !== ":memory:") {
|
|
172
|
+
mkdirSync(path.dirname(file), { recursive: true })
|
|
173
|
+
}
|
|
174
|
+
const db = new Database(file, { create: true, strict: true })
|
|
175
|
+
db.run("PRAGMA journal_mode = WAL")
|
|
176
|
+
// WAL with NORMAL survives an app crash; a power cut can lose the last commits.
|
|
177
|
+
db.run("PRAGMA synchronous = NORMAL")
|
|
178
|
+
db.run("PRAGMA busy_timeout = 5000")
|
|
179
|
+
db.run(SCHEMA)
|
|
180
|
+
return db
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const makeLog = (config: LogConfig): Effect.Effect<LogShape, never, Scope.Scope> =>
|
|
184
|
+
Effect.gen(function* making() {
|
|
185
|
+
const db = yield* Effect.acquireRelease(
|
|
186
|
+
Effect.sync(() => open(config.path)),
|
|
187
|
+
(d) =>
|
|
188
|
+
Effect.sync(() => {
|
|
189
|
+
d.close()
|
|
190
|
+
}),
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
const eventDefs = new Map(config.events.map((e) => [e.type, e]))
|
|
194
|
+
const commandDefs = new Map(config.commands.map((c) => [c.type, c]))
|
|
195
|
+
const handlers = new Map<string, On[]>()
|
|
196
|
+
for (const o of config.projections.flatMap((p) => p.on)) {
|
|
197
|
+
handlers.set(o.type, [...(handlers.get(o.type) ?? []), o])
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const insertEvent = db.query<{ seq: number }, [string, number, string, number, string, string]>(
|
|
201
|
+
"INSERT INTO events (id, time, type, v, source, payload) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING RETURNING seq",
|
|
202
|
+
)
|
|
203
|
+
const headQuery = db.query<{ seq: number | null }, []>("SELECT max(seq) AS seq FROM events")
|
|
204
|
+
const head = () => headQuery.get()?.seq ?? 0
|
|
205
|
+
const findCommand = db.query<{ seq: number }, [string]>("SELECT seq FROM commands WHERE id = ?")
|
|
206
|
+
const insertCommand = db.query("INSERT INTO commands (id, seq) VALUES (?, ?)")
|
|
207
|
+
const page = db.query<Row, [number, number, number]>(
|
|
208
|
+
"SELECT * FROM events WHERE seq > ? AND seq <= ? ORDER BY seq LIMIT ?",
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
const prepare = (events: readonly (Draft & { id: string; source: string })[]) => {
|
|
212
|
+
const out: Prepared[] = []
|
|
213
|
+
for (const e of events) {
|
|
214
|
+
const def = eventDefs.get(e.type)
|
|
215
|
+
const payload = checked(def, e)
|
|
216
|
+
if (payload instanceof Rejected) {
|
|
217
|
+
return payload
|
|
218
|
+
}
|
|
219
|
+
out.push({
|
|
220
|
+
id: e.id,
|
|
221
|
+
type: e.type,
|
|
222
|
+
source: e.source,
|
|
223
|
+
time: Date.now(),
|
|
224
|
+
v: def?.version ?? 0,
|
|
225
|
+
...payload,
|
|
226
|
+
})
|
|
227
|
+
}
|
|
228
|
+
return out
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// The one write: events (skipping ids already in the log), projections, receipt.
|
|
232
|
+
const write = db.transaction((events: readonly Prepared[], commandId: string) => {
|
|
233
|
+
const stored: StoredEvent[] = []
|
|
234
|
+
for (const e of events) {
|
|
235
|
+
const row = insertEvent.get(e.id, e.time, e.type, e.v, e.source, e.json)
|
|
236
|
+
if (row !== null) {
|
|
237
|
+
const { id, time, type, v, source } = e
|
|
238
|
+
const event: StoredEvent = { seq: row.seq, id, time, type, v, source, payload: e.encoded }
|
|
239
|
+
for (const h of handlers.get(e.type) ?? []) {
|
|
240
|
+
h.apply(db, event)
|
|
241
|
+
}
|
|
242
|
+
stored.push(event)
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const seq = stored.at(-1)?.seq ?? head()
|
|
246
|
+
insertCommand.run(commandId, seq)
|
|
247
|
+
return { stored, seq }
|
|
248
|
+
})
|
|
249
|
+
|
|
250
|
+
const live = yield* PubSub.unbounded<StoredEvent>()
|
|
251
|
+
// Commit and publish under one permit, so subscribers see events in seq order.
|
|
252
|
+
const lane = yield* Semaphore.make(1)
|
|
253
|
+
|
|
254
|
+
const decideAndWrite = (command: Command) => {
|
|
255
|
+
const def = commandDefs.get(command.type)
|
|
256
|
+
if (!def) {
|
|
257
|
+
return new Rejected({ reason: `Unknown command ${command.type}` })
|
|
258
|
+
}
|
|
259
|
+
const done = findCommand.get(command.id)
|
|
260
|
+
if (done) {
|
|
261
|
+
return { seq: done.seq, duplicate: true, stored: [] }
|
|
262
|
+
}
|
|
263
|
+
const decision = def.handle(db, command.payload)
|
|
264
|
+
if ("reject" in decision) {
|
|
265
|
+
return new Rejected({ reason: decision.reject })
|
|
266
|
+
}
|
|
267
|
+
const events = prepare(
|
|
268
|
+
decision.events.map((d, i) => ({ ...d, id: `${command.id}:${i}`, source: command.source })),
|
|
269
|
+
)
|
|
270
|
+
if (events instanceof Rejected) {
|
|
271
|
+
return events
|
|
272
|
+
}
|
|
273
|
+
const { stored, seq } = write(events, command.id)
|
|
274
|
+
return { seq, duplicate: false, stored }
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const dispatch = (command: Command) =>
|
|
278
|
+
lane.withPermit(
|
|
279
|
+
Effect.suspend(() => {
|
|
280
|
+
const r = decideAndWrite(command)
|
|
281
|
+
if (r instanceof Rejected) {
|
|
282
|
+
return Effect.fail(r)
|
|
283
|
+
}
|
|
284
|
+
return Effect.as(PubSub.publishAll(live, r.stored), {
|
|
285
|
+
seq: r.seq,
|
|
286
|
+
duplicate: r.duplicate,
|
|
287
|
+
})
|
|
288
|
+
}),
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
const since = (after: number, through: number) =>
|
|
292
|
+
Stream.paginate(after, (cursor) =>
|
|
293
|
+
Effect.sync(() => {
|
|
294
|
+
const rows = page.all(cursor, through, PAGE).map(toStored)
|
|
295
|
+
const last = rows.at(-1)
|
|
296
|
+
const next = rows.length === PAGE && last ? Option.some(last.seq) : Option.none()
|
|
297
|
+
return [rows, next] as const
|
|
298
|
+
}),
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
// T3 Code's catch-up: subscribe first, then read the head, so nothing falls between.
|
|
302
|
+
const changes = (after: number) =>
|
|
303
|
+
Stream.unwrap(
|
|
304
|
+
Effect.gen(function* subscribing() {
|
|
305
|
+
const subscription = yield* PubSub.subscribe(live)
|
|
306
|
+
const high = Math.max(head(), after)
|
|
307
|
+
return Stream.concat(
|
|
308
|
+
since(after, high),
|
|
309
|
+
Stream.fromSubscription(subscription).pipe(Stream.filter((e) => e.seq > high)),
|
|
310
|
+
)
|
|
311
|
+
}),
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
const saveVersion = db.query(
|
|
315
|
+
"INSERT INTO projections (name, version) VALUES (?, ?) ON CONFLICT (name) DO UPDATE SET version = excluded.version",
|
|
316
|
+
)
|
|
317
|
+
const rebuild = db.transaction((p: Projection) => {
|
|
318
|
+
for (const table of p.tables) {
|
|
319
|
+
db.run(`DROP TABLE IF EXISTS ${table}`)
|
|
320
|
+
}
|
|
321
|
+
db.run(p.create)
|
|
322
|
+
const types = [...new Set(p.on.map((o) => o.type))]
|
|
323
|
+
const rows = db
|
|
324
|
+
.query<Row, string[]>(
|
|
325
|
+
`SELECT * FROM events WHERE type IN (${types.map(() => "?").join(", ")}) ORDER BY seq`,
|
|
326
|
+
)
|
|
327
|
+
.iterate(...types)
|
|
328
|
+
for (const row of rows) {
|
|
329
|
+
const version = eventDefs.get(row.type)?.version
|
|
330
|
+
if (row.v !== version) {
|
|
331
|
+
throw new Error(`No upcast for ${row.type} v${row.v} to v${version}`)
|
|
332
|
+
}
|
|
333
|
+
const event = toStored(row)
|
|
334
|
+
for (const o of p.on) {
|
|
335
|
+
if (o.type === row.type) {
|
|
336
|
+
o.apply(db, event)
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
saveVersion.run(p.name, p.version)
|
|
341
|
+
})
|
|
342
|
+
const versions = db.query<{ version: number }, [string]>(
|
|
343
|
+
"SELECT version FROM projections WHERE name = ?",
|
|
344
|
+
)
|
|
345
|
+
for (const p of config.projections) {
|
|
346
|
+
if (versions.get(p.name)?.version !== p.version) {
|
|
347
|
+
rebuild(p)
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return {
|
|
352
|
+
dispatch,
|
|
353
|
+
snapshot: Effect.sync(() => ({
|
|
354
|
+
seq: head(),
|
|
355
|
+
state: Object.fromEntries(config.projections.map((p) => [p.name, p.snapshot(db)])),
|
|
356
|
+
})),
|
|
357
|
+
changes,
|
|
358
|
+
read: (f) => Effect.sync(() => f(db)),
|
|
359
|
+
} satisfies LogShape
|
|
360
|
+
})
|
|
361
|
+
|
|
362
|
+
const logKey: Context.Service<LogService, LogShape> = Context.Service<LogService, LogShape>(
|
|
363
|
+
"switch-ext-kit/Log",
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
const logLayer = (config: LogConfig): Layer.Layer<LogService> =>
|
|
367
|
+
Layer.effect(logKey, makeLog(config))
|
|
368
|
+
|
|
369
|
+
/** An extension's own event log, on its own file. */
|
|
370
|
+
export const Log: Context.Service<LogService, LogShape> & {
|
|
371
|
+
/** Opens the log at `config.path`, rebuilding a projection whose version moved. */
|
|
372
|
+
readonly layer: typeof logLayer
|
|
373
|
+
} = Object.assign(logKey, { layer: logLayer })
|
package/src/manifest.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// What an extension says about itself before it runs: the `extension` key of its package.json. The
|
|
2
|
+
// host reads it when it installs the package; the core decides from it which machine runs the
|
|
3
|
+
// extension.
|
|
4
|
+
import { existsSync, readFileSync } from "node:fs"
|
|
5
|
+
import path from "node:path"
|
|
6
|
+
import { Schema } from "effect"
|
|
7
|
+
|
|
8
|
+
/** An account an extension needs the user to connect: its provider, the scopes, one or many. */
|
|
9
|
+
export interface Need {
|
|
10
|
+
/** Whose account: "google", "github". */
|
|
11
|
+
readonly provider: string
|
|
12
|
+
readonly scopes: readonly string[]
|
|
13
|
+
/** Any number of accounts, not one. */
|
|
14
|
+
readonly multiple: boolean
|
|
15
|
+
/**
|
|
16
|
+
* How it's connected: OAuth (the default, for a provider Switch knows), a key the user gives
|
|
17
|
+
* (an API key, a bot token), or a session the extension holds itself (a signed-in browser).
|
|
18
|
+
*/
|
|
19
|
+
readonly kind?: "oauth" | "key" | "session"
|
|
20
|
+
/** Session tools: signIn prepares the user's browser; status returns its current accounts. */
|
|
21
|
+
readonly session?: { readonly signIn: string; readonly status: string }
|
|
22
|
+
/** Its name to the user, for a provider Switch doesn't know. */
|
|
23
|
+
readonly label?: string
|
|
24
|
+
/** The Keychain service it kept these accounts in before connections: moved in once, then emptied. */
|
|
25
|
+
readonly legacy?: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const need: Schema.Codec<Need> = Schema.Struct({
|
|
29
|
+
provider: Schema.String,
|
|
30
|
+
scopes: Schema.Array(Schema.String),
|
|
31
|
+
multiple: Schema.Boolean,
|
|
32
|
+
kind: Schema.optionalKey(Schema.Literals(["oauth", "key", "session"])),
|
|
33
|
+
session: Schema.optionalKey(Schema.Struct({ signIn: Schema.String, status: Schema.String })),
|
|
34
|
+
label: Schema.optionalKey(Schema.String),
|
|
35
|
+
legacy: Schema.optionalKey(Schema.String),
|
|
36
|
+
})
|
|
37
|
+
/** What an extension says about itself: the `extension` key of its package.json. */
|
|
38
|
+
export interface Manifest {
|
|
39
|
+
/** Its name to Switch: its tools are `<name>_<tool>`, its events `<name>.<event>`. */
|
|
40
|
+
readonly name: string
|
|
41
|
+
/** Its entry, from the package's folder: run with bun, it serves MCP on stdio. */
|
|
42
|
+
readonly main?: string
|
|
43
|
+
/** Or what runs it instead of `main`: an argv, its `./` paths from the package's folder. */
|
|
44
|
+
readonly command?: readonly string[]
|
|
45
|
+
/** A Switchboard appendage (sbmcp), made an extension by the shim. */
|
|
46
|
+
readonly shim?: "switchboard"
|
|
47
|
+
/** What the machine running it must provide: "macos", "lan:printers". */
|
|
48
|
+
readonly needs?: readonly string[]
|
|
49
|
+
/** It runs on every machine with what it needs, one per machine, instead of on one. */
|
|
50
|
+
readonly every?: boolean
|
|
51
|
+
/**
|
|
52
|
+
* How often, at most ms apart, each of its heartbeats (`<name>.heartbeat`,
|
|
53
|
+
* `<name>.<part>.heartbeat`) says how it is while it runs: missing three in a row is trouble.
|
|
54
|
+
*/
|
|
55
|
+
readonly heartbeat?: number
|
|
56
|
+
/** Accounts it needs the user to connect. */
|
|
57
|
+
readonly connections?: readonly Need[]
|
|
58
|
+
/** The widgets it publishes, by name. */
|
|
59
|
+
readonly widgets?: readonly string[]
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export const manifest: Schema.Codec<Manifest> = Schema.Struct({
|
|
63
|
+
/** Its name to Switch: its tools are `<name>_<tool>`, its events `<name>.<event>`. */
|
|
64
|
+
name: Schema.String,
|
|
65
|
+
/** Its entry, from the package's folder: run with bun, it serves MCP on stdio. */
|
|
66
|
+
main: Schema.optionalKey(Schema.String),
|
|
67
|
+
command: Schema.optionalKey(Schema.Array(Schema.String)),
|
|
68
|
+
shim: Schema.optionalKey(Schema.Literal("switchboard")),
|
|
69
|
+
/** What the machine running it must provide: "macos", "lan:printers". */
|
|
70
|
+
needs: Schema.optionalKey(Schema.Array(Schema.String)),
|
|
71
|
+
/** It runs on every machine with what it needs, one per machine, instead of on one. */
|
|
72
|
+
every: Schema.optionalKey(Schema.Boolean),
|
|
73
|
+
/** How often, at most ms apart, each of its heartbeats says how it is while it runs. */
|
|
74
|
+
heartbeat: Schema.optionalKey(Schema.Number.check(Schema.isGreaterThan(0))),
|
|
75
|
+
/** Accounts it needs the user to connect. */
|
|
76
|
+
connections: Schema.optionalKey(Schema.Array(need)),
|
|
77
|
+
/** The widgets it publishes, by name. */
|
|
78
|
+
widgets: Schema.optionalKey(Schema.Array(Schema.String)),
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
const pkg = Schema.Struct({
|
|
82
|
+
name: Schema.String,
|
|
83
|
+
version: Schema.optionalKey(Schema.String),
|
|
84
|
+
extension: Schema.optionalKey(manifest),
|
|
85
|
+
/** The key's name before extensions were renamed: still read, never written. */
|
|
86
|
+
spur: Schema.optionalKey(manifest),
|
|
87
|
+
})
|
|
88
|
+
const decodePkg = Schema.decodeUnknownResult(Schema.fromJsonString(pkg))
|
|
89
|
+
|
|
90
|
+
/** An installed package's manifest, its package name and version; why not, if it isn't an extension. */
|
|
91
|
+
export const readManifest = (
|
|
92
|
+
dir: string,
|
|
93
|
+
):
|
|
94
|
+
| { readonly package: string; readonly version: string; readonly manifest: Manifest }
|
|
95
|
+
| { readonly error: string } => {
|
|
96
|
+
const at = path.join(dir, "package.json")
|
|
97
|
+
if (!existsSync(at)) {
|
|
98
|
+
return { error: "No package.json" }
|
|
99
|
+
}
|
|
100
|
+
const read = decodePkg(readFileSync(at, "utf-8"))
|
|
101
|
+
if (read._tag === "Failure") {
|
|
102
|
+
return { error: `Not an extension: ${read.failure.message}` }
|
|
103
|
+
}
|
|
104
|
+
const p = read.success
|
|
105
|
+
const m = p.extension ?? p.spur
|
|
106
|
+
if (m === undefined) {
|
|
107
|
+
return { error: "Not an extension: no `extension` key" }
|
|
108
|
+
}
|
|
109
|
+
if ((m.main === undefined) === (m.command === undefined)) {
|
|
110
|
+
return { error: "An extension has main or command, one of them" }
|
|
111
|
+
}
|
|
112
|
+
return { package: p.name, version: p.version ?? "0.0.0", manifest: m }
|
|
113
|
+
}
|
package/src/messages.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Messages, whatever extension they come from. An extension's event that is a message carries,
|
|
2
|
+
// beside its own payload, who sent it (`sender`: a person or someone's agent) and what it is
|
|
3
|
+
// (`message`), in these shapes. Switch knows no extension: the inbox, Contacts' links and the
|
|
4
|
+
// tagger read only these.
|
|
5
|
+
import type { Json } from "./shim.ts"
|
|
6
|
+
|
|
7
|
+
export interface Sender {
|
|
8
|
+
/** E.164 phone, lowercase email, or a username: what Contacts matches on. */
|
|
9
|
+
readonly handle: string
|
|
10
|
+
/** What the handle is: "phone", "email", or a service ("instagram", "github"). */
|
|
11
|
+
readonly via: string
|
|
12
|
+
readonly name?: string
|
|
13
|
+
/** The user, sending. */
|
|
14
|
+
readonly me?: boolean
|
|
15
|
+
/** Someone's agent or a machine, not a person. */
|
|
16
|
+
readonly agent?: boolean
|
|
17
|
+
/** Their Contacts id, once linked. */
|
|
18
|
+
readonly person?: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface Message {
|
|
22
|
+
/** Stable across updates of the same message (read, relabeled). */
|
|
23
|
+
readonly id: string
|
|
24
|
+
/** Its conversation: a chat, an email thread, a DM thread, a caller. */
|
|
25
|
+
readonly conversation: string
|
|
26
|
+
readonly text: string
|
|
27
|
+
/** When it was sent, ms. */
|
|
28
|
+
readonly at: number
|
|
29
|
+
readonly subject?: string
|
|
30
|
+
/** From someone else, not yet read. */
|
|
31
|
+
readonly unread?: boolean
|
|
32
|
+
/** What it came on, as shown: "texts", "email". */
|
|
33
|
+
readonly channel?: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const SENDER_SCHEMA: Readonly<Record<string, unknown>> = {
|
|
37
|
+
type: "object",
|
|
38
|
+
properties: {
|
|
39
|
+
handle: { type: "string" },
|
|
40
|
+
via: { type: "string" },
|
|
41
|
+
name: { type: "string" },
|
|
42
|
+
me: { type: "boolean" },
|
|
43
|
+
agent: { type: "boolean" },
|
|
44
|
+
person: { type: "string" },
|
|
45
|
+
},
|
|
46
|
+
required: ["handle", "via"],
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const MESSAGE_SCHEMA: Readonly<Record<string, unknown>> = {
|
|
50
|
+
type: "object",
|
|
51
|
+
properties: {
|
|
52
|
+
id: { type: "string" },
|
|
53
|
+
conversation: { type: "string" },
|
|
54
|
+
text: { type: "string" },
|
|
55
|
+
at: { type: "number" },
|
|
56
|
+
subject: { type: "string" },
|
|
57
|
+
unread: { type: "boolean" },
|
|
58
|
+
channel: { type: "string" },
|
|
59
|
+
},
|
|
60
|
+
required: ["id", "conversation", "text"],
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const isJson = (v: unknown): v is Json => typeof v === "object" && v !== null && !Array.isArray(v)
|
|
64
|
+
|
|
65
|
+
export const isSender = (v: unknown): v is Sender =>
|
|
66
|
+
isJson(v) && typeof v.handle === "string" && typeof v.via === "string"
|
|
67
|
+
|
|
68
|
+
const isMessage = (v: unknown): v is Message =>
|
|
69
|
+
isJson(v) &&
|
|
70
|
+
typeof v.id === "string" &&
|
|
71
|
+
typeof v.conversation === "string" &&
|
|
72
|
+
typeof v.text === "string"
|
|
73
|
+
|
|
74
|
+
/** A message as the inbox reads it: what it is, who sent it, and its extension. */
|
|
75
|
+
export interface Received extends Message {
|
|
76
|
+
readonly sender: Sender
|
|
77
|
+
readonly extension: string
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A stored event as a message, if it is one. `time` stands in for a missing `at`. */
|
|
81
|
+
export const messageOf = (type: string, payload: unknown, time: number): Received | null => {
|
|
82
|
+
if (!isJson(payload) || !isSender(payload.sender) || !isMessage(payload.message)) {
|
|
83
|
+
return null
|
|
84
|
+
}
|
|
85
|
+
const m = payload.message
|
|
86
|
+
const extension = type.split(".")[0] ?? ""
|
|
87
|
+
return {
|
|
88
|
+
...m,
|
|
89
|
+
at: typeof m.at === "number" && m.at > 0 ? m.at : time,
|
|
90
|
+
channel: m.channel ?? extension,
|
|
91
|
+
sender: payload.sender,
|
|
92
|
+
extension,
|
|
93
|
+
}
|
|
94
|
+
}
|