@niq.run/worker-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,80 @@
1
+ # @niq.run/worker-sdk
2
+
3
+ TypeScript SDK for authoring **niq Workers** that connect to a niq event bus
4
+ over HTTP (SSE + POST).
5
+
6
+ > **This is one implementation of the niq bus protocol.** The transport is the
7
+ > contract — you can connect a Worker written in any language that speaks HTTP
8
+ > + SSE. This package is just the TS convenience layer.
9
+
10
+ ## What it is / is not
11
+
12
+ | Included | Not included |
13
+ |---|---|
14
+ | Connect to a bus over HTTP (`GET /events` SSE stream) | Identity registration (control-plane / `registryapi`) |
15
+ | `send` (directed) and `broadcast` (subscription-matched) | Worker runtime / swarm assembly |
16
+ | Receive routed events (`tool.requested`, etc.) | Program compilation |
17
+ | Protocol event type constants | — |
18
+ | Event construction helpers (`createEvent`, correctly timestamped + UUIDv7 ids) | — |
19
+
20
+ Identity must already be registered on the bus (offline, by the control plane)
21
+ before a worker connects. This SDK only establishes the connection.
22
+
23
+ ## Usage
24
+
25
+ ```ts
26
+ import { HTTPWorkerClient, createEvent, EventType } from "@niq.run/worker-sdk";
27
+
28
+ const worker = new HTTPWorkerClient({
29
+ baseURL: "http://localhost:8080",
30
+ workerID: "my-worker@me",
31
+ credential: "the-credential-issued-at-registration",
32
+ });
33
+
34
+ await worker.connect();
35
+
36
+ // Handle events routed to this worker.
37
+ for await (const evt of worker.events()) {
38
+ // respond to tool.requested, worker.input, ...
39
+ }
40
+
41
+ // Directed delivery — "I know who should handle this."
42
+ await worker.send(
43
+ createEvent(EventType.ToolCompleted, { result: "ok" }),
44
+ "reason.0",
45
+ );
46
+
47
+ // Broadcast — "whoever subscribes handles it."
48
+ await worker.broadcast(createEvent("stats.heartbeat", { uptime: 42 }));
49
+
50
+ await worker.close();
51
+ ```
52
+
53
+ ## Protocol notes
54
+
55
+ - **Every request carries its own `worker_id` + `credential`** — no session
56
+ token. The SSE stream is the connection anchor: the bus requires it open
57
+ before it accepts publishes, and keeps one live connection per worker.
58
+ - **You must supply `id` and `timestamp`** — the bus does not fill them.
59
+ Use `createEvent` (UUIDv7 id + unix-seconds timestamp + `specversion`).
60
+ - **Do not set `worker_id` yourself** — the bus overwrites it on receipt
61
+ (anti-spoofing, design D8). The client stamps it at publish time.
62
+ - `send` requires at least one target; use `broadcast` for undirected delivery.
63
+ - If no one subscribes, a broadcast silently disappears — that is a valid end
64
+ of the execution path, not an error.
65
+
66
+ ## Development
67
+
68
+ ```sh
69
+ npm install
70
+ npm run typecheck
71
+ npm test # vitest
72
+ npm run build # tsc → dist/
73
+ ```
74
+
75
+ ## Status
76
+
77
+ Early, moving fast. Pre-1.0; the wire protocol is stabilizing alongside
78
+ `core/bus` and the Go `httptrans` transport.
79
+
80
+ `node >= 18` (uses global `fetch` and `ReadableStream`).
@@ -0,0 +1,35 @@
1
+ import type { Event } from "./types.js";
2
+ /**
3
+ * WorkerSideChannel — the worker's view of a connection to the bus.
4
+ *
5
+ * Mirrors `core/bus.WorkerSideChannel`. Implementations hide whether the bus
6
+ * is in-process, over HTTP, or behind a relay; the interface is the same.
7
+ *
8
+ * Semantics of Send vs Broadcast (deliberately distinct, not interchangeable):
9
+ * - Send — "I know who should handle this." Directed to explicit targets.
10
+ * targets must be non-empty (use Broadcast for undirected).
11
+ * - Broadcast — "Whoever is interested handles it." Delivered to all online
12
+ * workers whose subscription matches. If no one subscribes, the
13
+ * event silently disappears — a valid end of the execution path.
14
+ */
15
+ export interface WorkerSideChannel {
16
+ /** Transport-level connection identifier (this worker's ID). */
17
+ readonly id: string;
18
+ /**
19
+ * Establish the connection to the bus. No-op if already connected.
20
+ * @throws if the transport rejects the connection (bad credential, etc.)
21
+ */
22
+ connect(): Promise<void>;
23
+ /** Send a directed event to specific target workers. targets must be non-empty. */
24
+ send(event: Event, ...targets: string[]): Promise<void>;
25
+ /** Broadcast an event to all matching subscribers. */
26
+ broadcast(event: Event): Promise<void>;
27
+ /**
28
+ * Iterate events routed to this worker (directed or broadcast).
29
+ * The stream ends when the connection closes.
30
+ */
31
+ events(): AsyncIterable<Event>;
32
+ /** Close the connection and release resources. */
33
+ close(): Promise<void>;
34
+ }
35
+ //# sourceMappingURL=channel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channel.d.ts","sourceRoot":"","sources":["../src/channel.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAExC;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,iBAAiB;IAChC,gEAAgE;IAChE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzB,mFAAmF;IACnF,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAExD,sDAAsD;IACtD,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvC;;;OAGG;IACH,MAAM,IAAI,aAAa,CAAC,KAAK,CAAC,CAAC;IAE/B,kDAAkD;IAClD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=channel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channel.js","sourceRoot":"","sources":["../src/channel.ts"],"names":[],"mappings":""}
@@ -0,0 +1,48 @@
1
+ import type { Event } from "./types.js";
2
+ import type { WorkerSideChannel } from "./channel.js";
3
+ export interface HTTPWorkerClientOptions {
4
+ /** Base URL of the niq bus, e.g. `http://localhost:8080`. Trailing slash optional. */
5
+ baseURL: string;
6
+ /** Worker identity registered on the bus (control plane created it). */
7
+ workerID: string;
8
+ /** Credential for this worker, verified at connect/publish time. */
9
+ credential: string;
10
+ /** Injectable fetch (e.g. for tests / proxies). Defaults to global fetch. */
11
+ fetchImpl?: typeof fetch;
12
+ }
13
+ /**
14
+ * A WorkerSideChannel over the niq HTTP transport.
15
+ *
16
+ * The protocol — mirroring the Go `httptrans` package:
17
+ * - Connect: open `GET /events?worker_id=&credential=` as an SSE stream.
18
+ * - Send/Broadcast: `POST /publish` with a {@link WorkerMessage} body.
19
+ *
20
+ * Every request carries its own `worker_id` + `credential`; there is no session
21
+ * token. The SSE stream acts as the connection anchor: the bus requires it to
22
+ * be open before it accepts publishes, and only one live connection per worker
23
+ * is kept. Closing the SSE stream marks the worker offline (identity is
24
+ * retained and can reconnect).
25
+ *
26
+ * Identity registration is NOT part of this SDK — it is a control-plane
27
+ * operation (registryapi) performed before the worker connects.
28
+ */
29
+ export declare class HTTPWorkerClient implements WorkerSideChannel {
30
+ readonly id: string;
31
+ private readonly baseURL;
32
+ private readonly workerID;
33
+ private readonly credential;
34
+ private readonly fetchImpl;
35
+ private es?;
36
+ private controller?;
37
+ private connected;
38
+ private closed;
39
+ constructor(opts: HTTPWorkerClientOptions);
40
+ connect(): Promise<void>;
41
+ send(event: Event, ...targets: string[]): Promise<void>;
42
+ broadcast(event: Event): Promise<void>;
43
+ events(): AsyncIterable<Event>;
44
+ close(): Promise<void>;
45
+ private assertOpen;
46
+ private publish;
47
+ }
48
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAiB,MAAM,YAAY,CAAC;AACvD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAatD,MAAM,WAAW,uBAAuB;IACtC,sFAAsF;IACtF,OAAO,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,QAAQ,EAAE,MAAM,CAAC;IACjB,oEAAoE;IACpE,UAAU,EAAE,MAAM,CAAC;IACnB,6EAA6E;IAC7E,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;CAC1B;AAED;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,gBAAiB,YAAW,iBAAiB;IACxD,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IAEpB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAe;IAEzC,OAAO,CAAC,EAAE,CAAC,CAA6B;IACxC,OAAO,CAAC,UAAU,CAAC,CAAkB;IACrC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,MAAM,CAAS;gBAEX,IAAI,EAAE,uBAAuB;IAQnC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAuBxB,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAQvD,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAK5C,MAAM,IAAI,aAAa,CAAC,KAAK,CAAC;IAOxB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B,OAAO,CAAC,UAAU;YAIJ,OAAO;CAgCtB"}
package/dist/client.js ADDED
@@ -0,0 +1,114 @@
1
+ import { parseEventStream } from "./sse.js";
2
+ /**
3
+ * A WorkerSideChannel over the niq HTTP transport.
4
+ *
5
+ * The protocol — mirroring the Go `httptrans` package:
6
+ * - Connect: open `GET /events?worker_id=&credential=` as an SSE stream.
7
+ * - Send/Broadcast: `POST /publish` with a {@link WorkerMessage} body.
8
+ *
9
+ * Every request carries its own `worker_id` + `credential`; there is no session
10
+ * token. The SSE stream acts as the connection anchor: the bus requires it to
11
+ * be open before it accepts publishes, and only one live connection per worker
12
+ * is kept. Closing the SSE stream marks the worker offline (identity is
13
+ * retained and can reconnect).
14
+ *
15
+ * Identity registration is NOT part of this SDK — it is a control-plane
16
+ * operation (registryapi) performed before the worker connects.
17
+ */
18
+ export class HTTPWorkerClient {
19
+ id;
20
+ baseURL;
21
+ workerID;
22
+ credential;
23
+ fetchImpl;
24
+ es;
25
+ controller;
26
+ connected = false;
27
+ closed = false;
28
+ constructor(opts) {
29
+ this.id = opts.workerID;
30
+ this.baseURL = opts.baseURL.replace(/\/+$/, "");
31
+ this.workerID = opts.workerID;
32
+ this.credential = opts.credential;
33
+ this.fetchImpl = opts.fetchImpl ?? fetch;
34
+ }
35
+ async connect() {
36
+ if (this.connected)
37
+ return;
38
+ if (this.closed)
39
+ throw new Error("niq: client is closed");
40
+ const url = `${this.baseURL}/events?worker_id=${encodeURIComponent(this.workerID)}&credential=${encodeURIComponent(this.credential)}`;
41
+ const controller = new AbortController();
42
+ let resp;
43
+ try {
44
+ resp = await this.fetchImpl(url, { signal: controller.signal });
45
+ }
46
+ catch (err) {
47
+ throw new Error(`niq: SSE connect failed: ${err.message}`);
48
+ }
49
+ if (!resp.ok || !resp.body) {
50
+ throw new Error(`niq: SSE connect failed with status ${resp.status}`);
51
+ }
52
+ this.es = resp.body;
53
+ this.controller = controller;
54
+ this.connected = true;
55
+ }
56
+ async send(event, ...targets) {
57
+ this.assertOpen();
58
+ if (targets.length === 0) {
59
+ throw new Error("niq: send requires at least one target; use broadcast() for undirected delivery");
60
+ }
61
+ await this.publish("send", event, targets);
62
+ }
63
+ async broadcast(event) {
64
+ this.assertOpen();
65
+ await this.publish("broadcast", event, undefined);
66
+ }
67
+ events() {
68
+ if (!this.connected)
69
+ throw new Error("niq: not connected");
70
+ const stream = this.es;
71
+ if (!stream)
72
+ throw new Error("niq: no event stream");
73
+ return parseEventStream(stream);
74
+ }
75
+ async close() {
76
+ if (this.closed)
77
+ return;
78
+ this.closed = true;
79
+ this.connected = false;
80
+ this.controller?.abort();
81
+ }
82
+ assertOpen() {
83
+ if (!this.connected)
84
+ throw new Error(`niq: worker ${this.workerID} not connected`);
85
+ }
86
+ async publish(type, event, targets) {
87
+ // Stamp authorship. The bus overwrites it anyway (anti-spoofing), but this
88
+ // is done at the edge so a caller cannot accidentally attribute to another.
89
+ const stamped = { ...event, worker_id: this.workerID };
90
+ const body = {
91
+ worker_id: this.workerID,
92
+ credential: this.credential,
93
+ type,
94
+ events: [stamped],
95
+ ...(targets ? { targets } : {}),
96
+ };
97
+ let resp;
98
+ try {
99
+ resp = await this.fetchImpl(`${this.baseURL}/publish`, {
100
+ method: "POST",
101
+ headers: { "Content-Type": "application/json" },
102
+ body: JSON.stringify(body),
103
+ });
104
+ }
105
+ catch (err) {
106
+ throw new Error(`niq: publish failed: ${err.message}`);
107
+ }
108
+ if (!resp.ok) {
109
+ const detail = await resp.text().catch(() => "");
110
+ throw new Error(`niq: publish failed (${resp.status}): ${detail}`);
111
+ }
112
+ }
113
+ }
114
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAuB5C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,gBAAgB;IAClB,EAAE,CAAS;IAEH,OAAO,CAAS;IAChB,QAAQ,CAAS;IACjB,UAAU,CAAS;IACnB,SAAS,CAAe;IAEjC,EAAE,CAA8B;IAChC,UAAU,CAAmB;IAC7B,SAAS,GAAG,KAAK,CAAC;IAClB,MAAM,GAAG,KAAK,CAAC;IAEvB,YAAY,IAA6B;QACvC,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAC;QACxB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QAChD,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC9B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,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CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAChC,CAAC;QAEF,IAAI,IAAc,CAAC;QACnB,IAAI,CAAC;YACH,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,OAAO,UAAU,EAAE;gBACrD,MAAM,EAAE,MAAM;gBACd,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;gBAC/C,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;aAC3B,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,wBAAyB,GAAa,CAAC,OAAO,EAAE,CAAC,CAAC;QACpE,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC;YACb,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;YACjD,MAAM,IAAI,KAAK,CAAC,wBAAwB,IAAI,CAAC,MAAM,MAAM,MAAM,EAAE,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=client.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.test.d.ts","sourceRoot":"","sources":["../src/client.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,82 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { HTTPWorkerClient } from "./client.js";
3
+ function isEvents(url) {
4
+ return new URL(url).pathname === "/events";
5
+ }
6
+ function sseStream(payloads) {
7
+ const body = payloads.map((p) => `data: ${p}\n\n`).join("");
8
+ return new ReadableStream({
9
+ start(controller) {
10
+ controller.enqueue(new TextEncoder().encode(body));
11
+ controller.close();
12
+ },
13
+ });
14
+ }
15
+ describe("publish wire shape", () => {
16
+ it("sends a directed event with targets and stamps worker_id", async () => {
17
+ let body;
18
+ const fetchImpl = (async (url, init) => {
19
+ if (isEvents(String(url))) {
20
+ return new Response(sseStream(["{}"]), { status: 200 });
21
+ }
22
+ body = JSON.parse(init.body);
23
+ return new Response(JSON.stringify({ status: "ok" }), { status: 200 });
24
+ });
25
+ const client = new HTTPWorkerClient({
26
+ baseURL: "http://localhost:8080",
27
+ workerID: "w1",
28
+ credential: "secret",
29
+ fetchImpl,
30
+ });
31
+ await client.connect();
32
+ await client.send({ id: "e1", type: "tool.requested", status: "created", worker_id: "attacker", payload: {}, timestamp: 1 }, "target");
33
+ expect(body).toEqual({
34
+ worker_id: "w1",
35
+ credential: "secret",
36
+ type: "send",
37
+ events: [
38
+ {
39
+ id: "e1",
40
+ type: "tool.requested",
41
+ status: "created",
42
+ worker_id: "w1", // overwritten at the edge
43
+ payload: {},
44
+ timestamp: 1,
45
+ },
46
+ ],
47
+ targets: ["target"],
48
+ });
49
+ });
50
+ it("rejects send with no targets", async () => {
51
+ const fetchImpl = (async () => new Response(sseStream(["{}"]), { status: 200 }));
52
+ const client = new HTTPWorkerClient({
53
+ baseURL: "http://localhost:8080",
54
+ workerID: "w1",
55
+ credential: "secret",
56
+ fetchImpl,
57
+ });
58
+ await client.connect();
59
+ await expect(client.send({ id: "e", type: "x", status: "created", worker_id: "", payload: {}, timestamp: 1 })).rejects.toThrow(/at least one target/);
60
+ });
61
+ });
62
+ describe("SSE parsing", () => {
63
+ it("parses JSON events from the event stream", async () => {
64
+ const fetchImpl = (async () => new Response(sseStream([
65
+ JSON.stringify({ id: "1", type: "tool.completed" }),
66
+ JSON.stringify({ id: "2", type: "tool.completed" }),
67
+ ]), { status: 200 }));
68
+ const client = new HTTPWorkerClient({
69
+ baseURL: "http://b:8080",
70
+ workerID: "w",
71
+ credential: "c",
72
+ fetchImpl,
73
+ });
74
+ await client.connect();
75
+ const got = [];
76
+ for await (const evt of client.events()) {
77
+ got.push(evt.id);
78
+ }
79
+ expect(got).toEqual(["1", "2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C,CAAC;QACnB,CAAC;QACD,MAAM,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;IAClC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,10 @@
1
+ import type { Event } from "./types.js";
2
+ /**
3
+ * Create a new Event with defaults, mirroring `core/event.New`.
4
+ *
5
+ * The bus overwrites `worker_id` on receipt (anti-spoofing, per design D8), so
6
+ * it is intentionally not set here — the client stamps it during publish. The
7
+ * caller supplies `type` and `payload`; everything else is deterministic.
8
+ */
9
+ export declare function createEvent(type: string, payload?: Record<string, unknown>, now?: number): Event;
10
+ //# sourceMappingURL=createEvent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createEvent.d.ts","sourceRoot":"","sources":["../src/createEvent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAe,MAAM,YAAY,CAAC;AAGrD;;;;;;GAMG;AACH,wBAAgB,WAAW,CACzB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,EACrC,GAAG,SAAa,GACf,KAAK,CAUP"}
@@ -0,0 +1,20 @@
1
+ import { newId } from "./id.js";
2
+ /**
3
+ * Create a new Event with defaults, mirroring `core/event.New`.
4
+ *
5
+ * The bus overwrites `worker_id` on receipt (anti-spoofing, per design D8), so
6
+ * it is intentionally not set here — the client stamps it during publish. The
7
+ * caller supplies `type` and `payload`; everything else is deterministic.
8
+ */
9
+ export function createEvent(type, payload = {}, now = Date.now()) {
10
+ return {
11
+ id: newId(now),
12
+ type,
13
+ status: "created",
14
+ payload,
15
+ worker_id: "", // stamped by the client at publish time
16
+ timestamp: Math.floor(now / 1000), // unix seconds, mirrors Go
17
+ specversion: "niq/1.0",
18
+ };
19
+ }
20
+ //# sourceMappingURL=createEvent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createEvent.js","sourceRoot":"","sources":["../src/createEvent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAEhC;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CACzB,IAAY,EACZ,UAAmC,EAAE,EACrC,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE;IAEhB,OAAO;QACL,EAAE,EAAE,KAAK,CAAC,GAAG,CAAC;QACd,IAAI;QACJ,MAAM,EAAE,SAAwB;QAChC,OAAO;QACP,SAAS,EAAE,EAAE,EAAE,wCAAwC;QACvD,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,EAAE,2BAA2B;QAC9D,WAAW,EAAE,SAAS;KACvB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=createEvent.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createEvent.test.d.ts","sourceRoot":"","sources":["../src/createEvent.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,20 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { createEvent } from "./createEvent.js";
3
+ describe("createEvent", () => {
4
+ it("fills deterministic defaults", () => {
5
+ const evt = createEvent("tool.requested", { tool: "x" }, 1_700_000_000_000);
6
+ expect(evt.type).toBe("tool.requested");
7
+ expect(evt.status).toBe("created");
8
+ expect(evt.payload).toEqual({ tool: "x" });
9
+ expect(evt.worker_id).toBe(""); // stamped by the client at publish time
10
+ expect(evt.timestamp).toBe(1_700_000_000); // unix seconds
11
+ expect(evt.specversion).toBe("niq/1.0");
12
+ expect(evt.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); // UUIDv7
13
+ });
14
+ it("generates unique, time-ordered ids", () => {
15
+ const a = createEvent("a");
16
+ const b = createEvent("b", {}, Date.now() + 1);
17
+ expect(a.id).not.toBe(b.id);
18
+ });
19
+ });
20
+ //#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E,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;QAC/C,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC9B,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Universal bus protocol event types.
3
+ *
4
+ * Every worker must use these exact names to interoperate — a worker
5
+ * implementing a capability must publish/subscribe with the matching event
6
+ * type. Worker-specific domain events (e.g. `reason.*`, `timer.*`) are not
7
+ * listed here; they are defined by their owning worker.
8
+ *
9
+ * Mirrors `core/event` constants.
10
+ */
11
+ export declare const EventType: {
12
+ readonly WorkerReady: "worker.ready";
13
+ readonly WorkerGone: "worker.gone";
14
+ readonly WorkerDiscover: "worker.discover";
15
+ readonly WorkerInput: "worker.input";
16
+ readonly WorkerAbort: "worker.abort";
17
+ readonly ToolRequested: "tool.requested";
18
+ readonly ToolCancel: "tool.cancel";
19
+ readonly ToolCompleted: "tool.completed";
20
+ readonly ToolFailed: "tool.failed";
21
+ readonly ToolRejected: "tool.rejected";
22
+ readonly ToolPartial: "tool.partial";
23
+ };
24
+ export type EventTypeName = (typeof EventType)[keyof typeof EventType];
25
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,eAAO,MAAM,SAAS;;;;;;;;;;;;CAeZ,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,SAAS,CAAC,CAAC,MAAM,OAAO,SAAS,CAAC,CAAC"}
package/dist/events.js ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Universal bus protocol event types.
3
+ *
4
+ * Every worker must use these exact names to interoperate — a worker
5
+ * implementing a capability must publish/subscribe with the matching event
6
+ * type. Worker-specific domain events (e.g. `reason.*`, `timer.*`) are not
7
+ * listed here; they are defined by their owning worker.
8
+ *
9
+ * Mirrors `core/event` constants.
10
+ */
11
+ export const EventType = {
12
+ // Worker presence and lifecycle.
13
+ WorkerReady: "worker.ready",
14
+ WorkerGone: "worker.gone",
15
+ WorkerDiscover: "worker.discover",
16
+ WorkerInput: "worker.input",
17
+ WorkerAbort: "worker.abort",
18
+ // Tool invocation lifecycle.
19
+ ToolRequested: "tool.requested",
20
+ ToolCancel: "tool.cancel",
21
+ ToolCompleted: "tool.completed",
22
+ ToolFailed: "tool.failed",
23
+ ToolRejected: "tool.rejected",
24
+ ToolPartial: "tool.partial",
25
+ };
26
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,iCAAiC;IACjC,WAAW,EAAE,cAAc;IAC3B,UAAU,EAAE,aAAa;IACzB,cAAc,EAAE,iBAAiB;IACjC,WAAW,EAAE,cAAc;IAC3B,WAAW,EAAE,cAAc;IAE3B,6BAA6B;IAC7B,aAAa,EAAE,gBAAgB;IAC/B,UAAU,EAAE,aAAa;IACzB,aAAa,EAAE,gBAAgB;IAC/B,UAAU,EAAE,aAAa;IACzB,YAAY,EAAE,eAAe;IAC7B,WAAW,EAAE,cAAc;CACnB,CAAC"}
package/dist/id.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Generate a time-ordered UUIDv7 string.
3
+ *
4
+ * Mirrors `core/event.newID` (github.com/google/uuid v7): globally unique and
5
+ * sortable by generation time, suitable as a durable key and for chronological
6
+ * audit/replay. Falls back to an unguessable random v4 when crypto is
7
+ * unavailable (should not happen in Node).
8
+ */
9
+ export declare function newId(now?: number): string;
10
+ //# sourceMappingURL=id.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"id.d.ts","sourceRoot":"","sources":["../src/id.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,wBAAgB,KAAK,CAAC,GAAG,SAAa,GAAG,MAAM,CAiB9C"}
package/dist/id.js ADDED
@@ -0,0 +1,26 @@
1
+ import { randomBytes } from "node:crypto";
2
+ /**
3
+ * Generate a time-ordered UUIDv7 string.
4
+ *
5
+ * Mirrors `core/event.newID` (github.com/google/uuid v7): globally unique and
6
+ * sortable by generation time, suitable as a durable key and for chronological
7
+ * audit/replay. Falls back to an unguessable random v4 when crypto is
8
+ * unavailable (should not happen in Node).
9
+ */
10
+ export function newId(now = Date.now()) {
11
+ // UUIDv7: 48-bit unix-ms timestamp + version nibble, then random bits.
12
+ const bytes = randomBytes(16);
13
+ const timeMillis = BigInt(now);
14
+ bytes[0] = Number((timeMillis >> 40n) & 0xffn);
15
+ bytes[1] = Number((timeMillis >> 32n) & 0xffn);
16
+ bytes[2] = Number((timeMillis >> 24n) & 0xffn);
17
+ bytes[3] = Number((timeMillis >> 16n) & 0xffn);
18
+ bytes[4] = Number((timeMillis >> 8n) & 0xffn);
19
+ bytes[5] = Number(timeMillis & 0xffn);
20
+ // Set version (7) and variant (RFC 4122 10xx).
21
+ bytes[6] = (bytes[6] & 0x0f) | 0x70;
22
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
23
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
24
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
25
+ }
26
+ //# sourceMappingURL=id.js.map
package/dist/id.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"id.js","sourceRoot":"","sources":["../src/id.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C;;;;;;;GAOG;AACH,MAAM,UAAU,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE;IACpC,uEAAuE;IACvE,MAAM,KAAK,GAAG,W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EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC;AAC7G,CAAC"}
@@ -0,0 +1,10 @@
1
+ export { HTTPWorkerClient } from "./client.js";
2
+ export type { HTTPWorkerClientOptions } from "./client.js";
3
+ export type { WorkerSideChannel } from "./channel.js";
4
+ export { createEvent } from "./createEvent.js";
5
+ export { EventType } from "./events.js";
6
+ export type { EventTypeName } from "./events.js";
7
+ export { newId } from "./id.js";
8
+ export { parseEventStream } from "./sse.js";
9
+ export type { Event, EventPattern, EventStatus, Identity, MessageType, RequestType, WorkerMessage, } from "./types.js";
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,YAAY,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAE3D,YAAY,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEtD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,YAAY,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAE5C,YAAY,EACV,KAAK,EACL,YAAY,EACZ,WAAW,EACX,QAAQ,EACR,WAAW,EACX,WAAW,EACX,aAAa,GACd,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { HTTPWorkerClient } from "./client.js";
2
+ export { createEvent } from "./createEvent.js";
3
+ export { EventType } from "./events.js";
4
+ export { newId } from "./id.js";
5
+ export { parseEventStream } from "./sse.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAK/C,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAGxC,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC"}
package/dist/sse.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import type { Event } from "./types.js";
2
+ /**
3
+ * Parse a Node ReadableStream of SSE bytes into Event objects, one per
4
+ * `data:` block. The Go httptrans server writes a single `data: {json}\n\n`
5
+ * per event (single line, compact JSON), but this parser is tolerant of
6
+ * multi-line data blocks and ignores comment lines for robustness.
7
+ *
8
+ * Yields nothing until the first complete event; on parse failure of a block
9
+ * it skips that block (mirrors the Go worker's `continue` on bad JSON).
10
+ */
11
+ export declare function parseEventStream(stream: ReadableStream<Uint8Array>): AsyncGenerator<Event>;
12
+ //# sourceMappingURL=sse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAExC;;;;;;;;GAQG;AACH,wBAAuB,gBAAgB,CACrC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GACjC,cAAc,CAAC,KAAK,CAAC,CAiCvB"}
package/dist/sse.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Parse a Node ReadableStream of SSE bytes into Event objects, one per
3
+ * `data:` block. The Go httptrans server writes a single `data: {json}\n\n`
4
+ * per event (single line, compact JSON), but this parser is tolerant of
5
+ * multi-line data blocks and ignores comment lines for robustness.
6
+ *
7
+ * Yields nothing until the first complete event; on parse failure of a block
8
+ * it skips that block (mirrors the Go worker's `continue` on bad JSON).
9
+ */
10
+ export async function* parseEventStream(stream) {
11
+ const reader = stream.getReader();
12
+ const decoder = new TextDecoder();
13
+ let buffer = "";
14
+ try {
15
+ while (true) {
16
+ const { done, value } = await reader.read();
17
+ if (done)
18
+ break;
19
+ buffer += decoder.decode(value, { stream: true });
20
+ // SSE frames are separated by a blank line. Split conservatively so a
21
+ // partial line at the tail is retained until the next chunk arrives.
22
+ let sep;
23
+ while ((sep = buffer.indexOf("\n\n")) !== -1) {
24
+ const frame = buffer.slice(0, sep);
25
+ buffer = buffer.slice(sep + 2);
26
+ const dataLines = frame
27
+ .split("\n")
28
+ .filter((l) => l.startsWith("data:"))
29
+ .map((l) => l.slice(5).trimStart());
30
+ if (dataLines.length === 0)
31
+ continue;
32
+ const payload = dataLines.join("\n");
33
+ try {
34
+ yield JSON.parse(payload);
35
+ }
36
+ catch {
37
+ // skip malformed event, matching Go `continue`
38
+ }
39
+ }
40
+ }
41
+ }
42
+ finally {
43
+ reader.releaseLock();
44
+ }
45
+ }
46
+ //# sourceMappingURL=sse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.js","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,gBAAgB,CACrC,MAAkC;IAElC,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;IAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAEhB,IAAI,CAAC;QACH,OAAO,IAAI,EAAE,CAAC;YACZ,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;YAC5C,IAAI,IAAI;gBAAE,MAAM;YAChB,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;YAElD,sEAAsE;YACtE,qEAAqE;YACrE,IAAI,GAAW,CAAC;YAChB,OAAO,CAAC,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;gBAC7C,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;gBACnC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;gBAC/B,MAAM,SAAS,GAAG,KAAK;qBACpB,KAAK,CAAC,IAAI,CAAC;qBACX,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;qBACpC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC;gBACtC,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC;oBAAE,SAAS;gBACrC,MAAM,OAAO,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBACrC,IAAI,CAAC;oBACH,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAU,CAAC;gBACrC,CAAC;gBAAC,MAAM,CAAC;oBACP,+CAA+C;gBACjD,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,WAAW,EAAE,CAAC;IACvB,CAAC;AACH,CAAC"}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * RequestType classifies a delivery request sent from a worker to the bus.
3
+ *
4
+ * These are the API-names in the `type` field of the HTTP publish payload —
5
+ * never change the serialized strings without changing the Go transport.
6
+ */
7
+ export type RequestType = "send" | "broadcast";
8
+ /** Message type sent from a worker to the bus (worker → bus direction). */
9
+ export type MessageType = RequestType | "heartbeat" | "disconnect";
10
+ /** Lifecycle stage of an event. Mirrors `core/event.EventStatus`. */
11
+ export type EventStatus = "created" | "routed" | "delivered";
12
+ /**
13
+ * Subscription declaration: an event of a type, optionally from a specific
14
+ * source worker. Mirrors `core/event.EventPattern`.
15
+ *
16
+ * `type` supports exact match, `"*"` (any), and `"Prefix.*"` (prefix wildcard —
17
+ * also matches the bare prefix, e.g. `"github.*"` matches `"github"` and
18
+ * `"github.issue.new"`). An empty `type` matches nothing (fails closed).
19
+ */
20
+ export interface EventPattern {
21
+ type: string;
22
+ source_id?: string;
23
+ }
24
+ /**
25
+ * The core data unit of the niq event bus. Field names are the wire names
26
+ * (`snake_case`) and must match `core/event.Event` exactly.
27
+ *
28
+ * Note on authorship: the bus overwrites `worker_id` on receipt (anti-spoofing).
29
+ * The worker MUST supply `id` and `timestamp` — the bus does not fill them.
30
+ * Use {@link createEvent} to get these right.
31
+ */
32
+ export interface Event {
33
+ id: string;
34
+ type: string;
35
+ status: EventStatus;
36
+ payload: Record<string, unknown>;
37
+ worker_id: string;
38
+ target_worker_id?: string;
39
+ trace_id?: string;
40
+ specversion?: string;
41
+ dataschema?: string;
42
+ timestamp: number;
43
+ recipients?: string[];
44
+ }
45
+ /**
46
+ * A delivery request from a worker to the bus. Mirrors `core/bus.Request`.
47
+ * Serialized over HTTP as the publish body; `MessageType` is the wire `type`.
48
+ */
49
+ export interface WorkerMessage {
50
+ type: MessageType;
51
+ events: Event[];
52
+ targets?: string[];
53
+ trace_id?: string;
54
+ }
55
+ /** Publish detail: which event types a worker may publish. */
56
+ export interface Identity {
57
+ worker_id: string;
58
+ credential: string;
59
+ publish_allow?: string[];
60
+ subscribe_allow?: EventPattern[];
61
+ }
62
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GAAG,MAA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"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@niq.run/worker-sdk",
3
+ "version": "0.1.0",
4
+ "description": "TypeScript SDK for authoring niq Workers that connect to a niq bus over HTTP (SSE + POST).",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "publishConfig": {
18
+ "registry": "https://registry.npmjs.org/",
19
+ "access": "public"
20
+ },
21
+ "scripts": {
22
+ "build": "tsc -p tsconfig.json",
23
+ "test": "vitest run",
24
+ "typecheck": "tsc --noEmit"
25
+ },
26
+ "engines": {
27
+ "node": ">=18"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^24.13.3",
31
+ "typescript": "^5.8.3",
32
+ "vitest": "^3.2.0"
33
+ },
34
+ "license": "MIT"
35
+ }