@omem-ai/plugin-sdk 0.0.0-stage → 0.0.2

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.
@@ -0,0 +1,355 @@
1
+ import type { ZodType } from "zod";
2
+ export type { CommandJudgeCall, CommandVerdict, CredentialApi, CredentialCommand, CredentialContext, CredentialDef, CredentialOutcome } from "./credential.ts";
3
+ import type { PluginConnection } from "./objects.ts";
4
+ export type CallContext = {
5
+ userId: string;
6
+ spaceId: string;
7
+ signal: AbortSignal;
8
+ connection(provider: string): Promise<PluginConnection | null>;
9
+ };
10
+ export type WriteContext = CallContext & {
11
+ idempotencyKey: string;
12
+ };
13
+ export type EventType = "item.status" | "item.created" | "review.finished" | "finding.decision" | "finding.resolution" | "finding.thread";
14
+ export type PluginEventV1 = {
15
+ v: 1;
16
+ id: string;
17
+ type: EventType;
18
+ at: string;
19
+ entity: {
20
+ kind: "item" | "run" | "finding";
21
+ id: string;
22
+ };
23
+ spaceId: string;
24
+ actor: {
25
+ kind: "user" | "agent" | "host";
26
+ id?: string;
27
+ };
28
+ data: Record<string, unknown>;
29
+ };
30
+ export type Subscription = {
31
+ id: string;
32
+ events: EventType[];
33
+ handle(ctx: CallContext, event: Readonly<PluginEventV1>): Promise<void>;
34
+ };
35
+ export type ExternalItem = {
36
+ key: string;
37
+ url: string;
38
+ title: string;
39
+ status: string;
40
+ kind?: "todo" | "watch";
41
+ assignee?: string;
42
+ parentKey?: string;
43
+ revision?: string;
44
+ updatedAt: string;
45
+ summary?: string;
46
+ };
47
+ export type ItemProvider = {
48
+ id: string;
49
+ label: string;
50
+ statuses: Record<string, "active" | "done" | "cancelled">;
51
+ /** What a subscription's target is, shown beside the box the person types it in: "仓库,写成 owner/repo". */
52
+ targetHint?: string;
53
+ pull(ctx: CallContext, req: {
54
+ target: string;
55
+ cursor?: string;
56
+ }): Promise<{
57
+ items: ExternalItem[];
58
+ cursor?: string;
59
+ done: boolean;
60
+ }>;
61
+ setStatus?(ctx: WriteContext, req: {
62
+ key: string;
63
+ status: string;
64
+ expectedRevision?: string;
65
+ }): Promise<{
66
+ revision?: string;
67
+ status: string;
68
+ }>;
69
+ };
70
+ export type MetricProvider = {
71
+ id: string;
72
+ label: string;
73
+ querySchema: ZodType;
74
+ collect(ctx: CallContext, req: {
75
+ metrics: readonly {
76
+ id: string;
77
+ query: unknown;
78
+ }[];
79
+ from: string;
80
+ to: string;
81
+ }): Promise<{
82
+ metricId: string;
83
+ at: string;
84
+ value: number;
85
+ dims?: Record<string, string>;
86
+ source?: string;
87
+ }[]>;
88
+ };
89
+ export type DiffAnchor = {
90
+ path: string;
91
+ line: number;
92
+ startLine?: number;
93
+ side: "LEFT" | "RIGHT";
94
+ head: string;
95
+ };
96
+ export type CommentRef = {
97
+ id: string;
98
+ url: string;
99
+ revision?: string;
100
+ };
101
+ export type ThreadState = {
102
+ state: "open" | "replied" | "resolved" | "outdated";
103
+ reply?: {
104
+ author: string;
105
+ at: string;
106
+ summary: string;
107
+ };
108
+ };
109
+ /** An invalid diff position is reported by throwing an Error with code REVIEW_ANCHOR_OUTDATED. */
110
+ export type ReviewProvider = {
111
+ id: string;
112
+ label: string;
113
+ objectKind: string;
114
+ publish(ctx: WriteContext, req: {
115
+ objectKey: string;
116
+ findingId: number;
117
+ anchor: DiffAnchor;
118
+ body: string;
119
+ }): Promise<CommentRef>;
120
+ readThread(ctx: CallContext, ref: CommentRef): Promise<ThreadState>;
121
+ resolve?(ctx: WriteContext, ref: CommentRef, note?: string): Promise<ThreadState>;
122
+ };
123
+ export type RetrievalKind = "chunk" | "page" | "memory";
124
+ export type RetrievalRef = {
125
+ type: RetrievalKind | "source";
126
+ id: string;
127
+ score?: number;
128
+ };
129
+ export type Retriever = {
130
+ id: string;
131
+ label: string;
132
+ search(ctx: CallContext, req: {
133
+ query: string;
134
+ spaces: string[];
135
+ kinds: RetrievalKind[];
136
+ limit: number;
137
+ }): Promise<RetrievalRef[]>;
138
+ };
139
+ export type Reranker = {
140
+ id: string;
141
+ label: string;
142
+ score(ctx: CallContext, req: {
143
+ query: string;
144
+ candidates: {
145
+ id: string;
146
+ text: string;
147
+ }[];
148
+ }): Promise<number[]>;
149
+ };
150
+ /** The host supplies texts in the plugin's authorized spaces. Content may leave this machine. */
151
+ export type EmbedderProvider = {
152
+ id: string;
153
+ name: string;
154
+ model: string;
155
+ dimensions: number;
156
+ maxBatch?: number;
157
+ maxChars?: number;
158
+ embed(texts: string[], kind: "query" | "passage", signal: AbortSignal): Promise<number[][] | Float32Array[]>;
159
+ };
160
+ export type SourceDisplay = {
161
+ kind: "table";
162
+ columns: string[];
163
+ rowLines: [number, number][];
164
+ } | {
165
+ kind: "records";
166
+ items: {
167
+ title: string;
168
+ lines: [number, number];
169
+ }[];
170
+ };
171
+ export type ParserInput = {
172
+ name: string;
173
+ url?: string;
174
+ mimeType?: string;
175
+ bytes: Uint8Array;
176
+ };
177
+ export type ParsedSource = {
178
+ title?: string;
179
+ text: string;
180
+ meta?: Record<string, string>;
181
+ display?: SourceDisplay;
182
+ };
183
+ export type SourceParser = {
184
+ id: string;
185
+ label: string;
186
+ match: {
187
+ extensions?: string[];
188
+ mimeTypes?: string[];
189
+ urlPatterns?: string[];
190
+ };
191
+ parse(ctx: CallContext, input: ParserInput): Promise<ParsedSource>;
192
+ };
193
+ export type WikiPageKind = {
194
+ kind: string;
195
+ label: string;
196
+ describe: string;
197
+ template: string;
198
+ check?(ctx: CallContext, page: {
199
+ slug: string;
200
+ title: string;
201
+ body: string;
202
+ }): Promise<{
203
+ line?: number;
204
+ message: string;
205
+ }[]>;
206
+ upkeep?: {
207
+ everyDays?: number;
208
+ onSourcesChanged?: boolean;
209
+ };
210
+ };
211
+ export type OutletIdentity = {
212
+ provider: string;
213
+ subject: string;
214
+ };
215
+ export type OutletRecipient = {
216
+ id: string;
217
+ identities: OutletIdentity[];
218
+ };
219
+ export type OutNotification = {
220
+ about?: {
221
+ title: string;
222
+ link: string;
223
+ };
224
+ user: OutletRecipient;
225
+ title: string;
226
+ body: string;
227
+ link: string | null;
228
+ urgency: "normal" | "urgent" | "silent" | "later";
229
+ dedupKey: string;
230
+ };
231
+ export type OutAsk = OutNotification & {
232
+ kind: string;
233
+ options: {
234
+ label: string;
235
+ }[];
236
+ fields: Record<string, unknown>[];
237
+ requiresApproval: boolean;
238
+ allowText: boolean;
239
+ expiresAt: string | null;
240
+ };
241
+ export type Notifier = {
242
+ id: string;
243
+ name: string;
244
+ resolve?(user: OutletRecipient, signal: AbortSignal): Promise<{
245
+ ok: boolean;
246
+ hint?: string;
247
+ }>;
248
+ deliver(n: OutNotification, signal: AbortSignal): Promise<{
249
+ ref?: string;
250
+ }>;
251
+ update?(ref: string, n: OutNotification, signal: AbortSignal): Promise<void>;
252
+ ask?(a: OutAsk, signal: AbortSignal): Promise<{
253
+ ref?: string;
254
+ }>;
255
+ retract?(ref: string, signal: AbortSignal): Promise<void>;
256
+ };
257
+ export type OutletAnswer = {
258
+ notifier: string;
259
+ ref: string;
260
+ user: OutletIdentity;
261
+ choice?: number;
262
+ values?: Record<string, unknown>;
263
+ text?: string;
264
+ approved?: boolean;
265
+ };
266
+ export type FlowEvidence = {
267
+ text: string;
268
+ link?: string;
269
+ };
270
+ export type FlowContext = {
271
+ item: {
272
+ id: string;
273
+ title: string;
274
+ spaceId: string;
275
+ };
276
+ stage: {
277
+ id: string;
278
+ name: string;
279
+ since: string;
280
+ };
281
+ with: unknown;
282
+ materials: {
283
+ kind: string;
284
+ ref: string;
285
+ }[];
286
+ };
287
+ export type FlowProvider = {
288
+ id: string;
289
+ name: string;
290
+ describe: string;
291
+ params?: Record<string, unknown>;
292
+ };
293
+ export type FlowSignal = FlowProvider & {
294
+ check(ctx: FlowContext, signal: AbortSignal): Promise<{
295
+ done: boolean;
296
+ evidence?: FlowEvidence[];
297
+ waitingOn?: string;
298
+ recheckAfterSec?: number;
299
+ }>;
300
+ };
301
+ export type RunnerResult = {
302
+ ref: string;
303
+ status: "running" | "done" | "failed";
304
+ summary?: string;
305
+ evidence?: FlowEvidence[];
306
+ };
307
+ export type StageRunner = FlowProvider & {
308
+ /** Repeat calls with the same key, including after a host restart, must return the same operation. */
309
+ start(ctx: FlowContext & {
310
+ attempt: number;
311
+ idempotencyKey: string;
312
+ settings: Record<string, unknown>;
313
+ }, signal: AbortSignal): Promise<RunnerResult>;
314
+ check?(ref: string, signal: AbortSignal): Promise<RunnerResult>;
315
+ cancel?(ref: string, signal: AbortSignal): Promise<void>;
316
+ };
317
+ export type GateScope = {
318
+ flows?: string[];
319
+ stages?: string[];
320
+ };
321
+ export type StageGate = {
322
+ id: string;
323
+ name: string;
324
+ describe: string;
325
+ applies?: GateScope;
326
+ review(ctx: Pick<FlowContext, "item" | "stage"> & {
327
+ result: {
328
+ summary: string;
329
+ evidence: FlowEvidence[];
330
+ };
331
+ by: string;
332
+ }, signal: AbortSignal): Promise<{
333
+ ok: true;
334
+ } | {
335
+ ok: false;
336
+ reason: string;
337
+ evidence?: FlowEvidence[];
338
+ }>;
339
+ };
340
+ export type ProcessApi = {
341
+ stageGate(def: StageGate): void;
342
+ stageRunner(def: StageRunner): void;
343
+ flowSignal(def: FlowSignal): void;
344
+ answerAsk(input: OutletAnswer): Promise<void>;
345
+ notifier(def: Notifier): void;
346
+ retriever(def: Retriever): void;
347
+ reranker(def: Reranker): void;
348
+ embedder(def: EmbedderProvider): void;
349
+ sourceParser(def: SourceParser): void;
350
+ wikiPageKind(def: WikiPageKind): void;
351
+ subscribe(def: Subscription): void;
352
+ reviewProvider(def: ReviewProvider): void;
353
+ itemProvider(def: ItemProvider): void;
354
+ metricProvider(def: MetricProvider): void;
355
+ };
package/dist/server.js ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Slots (docs/v2/flows.md §8, “界面插槽”): a plugin's display block shown on omem's own pages — the item
3
+ * panel, under a flow stage, the today page. Declared in `register(api)`, after the block (and the object
4
+ * kinds a condition names):
5
+ *
6
+ * api.block({ kind: "ci_summary", description: "合并请求的检查结果", display: true, schema, load, view });
7
+ * api.slot("item.panel", { block: "ci_summary", when: { object: "pull-request" } });
8
+ *
9
+ * `load` reads what the block shows, as the person looking at the page and in the item's space (the
10
+ * plugin's own space on the today page); its result must pass the block's `schema`. `view` turns it into
11
+ * display components (the ones `renderView` draws, without `page`). Only code running inside omem can
12
+ * declare slots; they go away when the plugin is turned off or its trust withdrawn.
13
+ *
14
+ * No imports here, so omem's own type checks can compare these with the host's; the main entry
15
+ * (client.ts) fills in the context and component types.
16
+ */
17
+ export type PluginSlotPlace = "item.panel" | "flow.stage" | "today";
18
+ /**
19
+ * When a slot shows; not for `today`. `object`: one of this plugin's object kinds — on `item.panel` linked
20
+ * to the item (one block per object), on `flow.stage` the kind the stage follows (`by` / `done`).
21
+ * `stage`: stage ids (`flow.stage` only); `flow`: flow ids; `space`: the item's space.
22
+ */
23
+ export type PluginSlotWhen = {
24
+ object?: string;
25
+ stage?: string | string[];
26
+ flow?: string | string[];
27
+ space?: string | string[];
28
+ };
29
+ export type PluginSlot = {
30
+ block: string;
31
+ when?: PluginSlotWhen;
32
+ };
33
+ /** What a block in a slot is shown for: the item, the stage and the object it sits by (null where there is none). */
34
+ export type PluginSlotContext = {
35
+ at: PluginSlotPlace;
36
+ item: string | null;
37
+ stage: string | null;
38
+ object: {
39
+ id: string;
40
+ kind: string;
41
+ key: string;
42
+ title: string;
43
+ status: string;
44
+ link: string;
45
+ } | null;
46
+ };
47
+ export type PluginSlotView<C = unknown> = {
48
+ title?: string;
49
+ components: C[];
50
+ };
51
+ /** The parts of a display block a slot uses (its `kind`, `schema`, `description` and `display: true` as usual). */
52
+ export type PluginSlotBlock<T, Ctx = unknown, C = unknown> = {
53
+ load(ctx: Ctx, slot: PluginSlotContext): T | Promise<T>;
54
+ view(data: T): PluginSlotView<C>;
55
+ };
56
+ export type PluginSlotApi = {
57
+ slot(at: PluginSlotPlace, def: PluginSlot): void;
58
+ };
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@omem-ai/plugin-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "SDK for omem plugin pages and services: talk to omem through the shell, draw its forms and charts, serve HTTP and WebSocket to omem.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": { "types": "./dist/client.d.ts", "default": "./dist/client.js" },
9
+ "./server": { "types": "./dist/server.d.ts", "default": "./dist/server.js" },
10
+ "./blocks": { "types": "./dist/blocks.d.ts", "default": "./dist/blocks.js" },
11
+ "./charts": { "types": "./dist/charts.d.ts", "default": "./dist/charts.js" },
12
+ "./service": "./service.mjs"
13
+ },
14
+ "files": ["dist", "service.mjs", "README.md"],
15
+ "scripts": {
16
+ "build": "vite build && tsc -p tsconfig.json"
17
+ },
18
+ "dependencies": { "zod": "4.1.12" },
19
+ "devDependencies": {
20
+ "typescript": "5.9.3",
21
+ "vite": "7.3.1"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/lejunyang/omem.git",
26
+ "directory": "packages/plugin-sdk"
27
+ },
28
+ "publishConfig": { "access": "public" }
29
+ }
package/service.mjs ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * A plugin service's side (docs/v2/plugins.md), without dependencies: a plugin in the data directory
3
+ * cannot install packages, so its service imports this through OMEM_SERVICE_SDK:
4
+ *
5
+ * const { serve } = await import(process.env.OMEM_SERVICE_SDK);
6
+ * serve({
7
+ * http: (req, res) => { res.end("ok"); },
8
+ * socket: (ws) => { ws.on("message", (data, binary) => ws.send(data)); },
9
+ * });
10
+ *
11
+ * It listens on 127.0.0.1:OMEM_SERVICE_PORT and refuses anything that does not carry omem's token,
12
+ * so only omem (which checked the owner) reaches it. WebSocket: text and binary messages, ping,
13
+ * close; messages up to 16 MB.
14
+ */
15
+ import { createHash } from "node:crypto";
16
+ import { EventEmitter } from "node:events";
17
+ import { createServer } from "node:http";
18
+
19
+ const MAX = 16 * 1024 * 1024;
20
+
21
+ export function serve({ http, socket } = {}) {
22
+ const port = Number(process.env.OMEM_SERVICE_PORT);
23
+ const token = process.env.OMEM_SERVICE_TOKEN;
24
+ if (!port || !token) throw new Error("not started by omem: OMEM_SERVICE_PORT / OMEM_SERVICE_TOKEN missing");
25
+ const authed = (req) => req.headers.authorization === `Bearer ${token}`;
26
+ const server = createServer((req, res) => {
27
+ if (!authed(req)) return void (res.writeHead(401), res.end());
28
+ if (http) return http(req, res);
29
+ res.writeHead(404);
30
+ res.end();
31
+ });
32
+ server.on("upgrade", (req, sock, head) => {
33
+ if (!authed(req) || !socket || String(req.headers.upgrade).toLowerCase() !== "websocket" || !req.headers["sec-websocket-key"]) return void sock.destroy();
34
+ const accept = createHash("sha1").update(`${req.headers["sec-websocket-key"]}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64");
35
+ sock.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
36
+ socket(wrap(sock, head), req);
37
+ });
38
+ server.listen(port, "127.0.0.1");
39
+ return server;
40
+ }
41
+
42
+ function frame(opcode, payload) {
43
+ const len = payload.length;
44
+ const head = len < 126 ? Buffer.from([0x80 | opcode, len]) : len < 65536 ? Buffer.from([0x80 | opcode, 126, len >> 8, len & 255]) : Buffer.concat([Buffer.from([0x80 | opcode, 127]), (() => { const b = Buffer.alloc(8); b.writeBigUInt64BE(BigInt(len)); return b; })()]);
45
+ return Buffer.concat([head, payload]);
46
+ }
47
+
48
+ function wrap(sock, head) {
49
+ const ws = new EventEmitter();
50
+ let buf = head?.length ? Buffer.from(head) : Buffer.alloc(0);
51
+ let parts = [];
52
+ let partOp = 0;
53
+ let open = true;
54
+ ws.send = (data) => {
55
+ if (!open) return;
56
+ const binary = typeof data !== "string";
57
+ sock.write(frame(binary ? 2 : 1, binary ? Buffer.from(data) : Buffer.from(data, "utf8")));
58
+ };
59
+ ws.close = () => {
60
+ if (!open) return;
61
+ open = false;
62
+ sock.end(frame(8, Buffer.alloc(0)));
63
+ };
64
+ const parse = () => {
65
+ for (;;) {
66
+ if (buf.length < 2) return;
67
+ const fin = buf[0] & 0x80;
68
+ const op = buf[0] & 0x0f;
69
+ const masked = buf[1] & 0x80;
70
+ let len = buf[1] & 0x7f;
71
+ let at = 2;
72
+ if (len === 126) {
73
+ if (buf.length < 4) return;
74
+ len = buf.readUInt16BE(2);
75
+ at = 4;
76
+ } else if (len === 127) {
77
+ if (buf.length < 10) return;
78
+ len = Number(buf.readBigUInt64BE(2));
79
+ at = 10;
80
+ }
81
+ if (len > MAX) return void sock.destroy();
82
+ const maskAt = at;
83
+ if (masked) at += 4;
84
+ if (buf.length < at + len) return;
85
+ let payload = buf.subarray(at, at + len);
86
+ if (masked) {
87
+ payload = Buffer.from(payload);
88
+ for (let i = 0; i < payload.length; i++) payload[i] ^= buf[maskAt + (i % 4)];
89
+ }
90
+ buf = buf.subarray(at + len);
91
+ if (op === 8) return ws.close();
92
+ if (op === 9) { sock.write(frame(10, payload)); continue; }
93
+ if (op === 10) continue;
94
+ if (op === 1 || op === 2) partOp = op;
95
+ parts.push(payload);
96
+ if (fin) {
97
+ const data = Buffer.concat(parts);
98
+ parts = [];
99
+ ws.emit("message", partOp === 1 ? data.toString("utf8") : data, partOp === 2);
100
+ }
101
+ }
102
+ };
103
+ sock.on("data", (d) => {
104
+ buf = Buffer.concat([buf, d]);
105
+ parse();
106
+ });
107
+ const gone = () => {
108
+ if (!open && ws.closed) return;
109
+ open = false;
110
+ ws.closed = true;
111
+ ws.emit("close");
112
+ };
113
+ sock.on("close", gone);
114
+ sock.on("error", gone);
115
+ if (buf.length) setImmediate(parse);
116
+ return ws;
117
+ }