@niq.run/worker-sdk 0.1.0 → 0.3.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 +55 -3
- package/dist/baseworker.d.ts +70 -0
- package/dist/baseworker.d.ts.map +1 -0
- package/dist/baseworker.js +163 -0
- package/dist/baseworker.js.map +1 -0
- package/dist/baseworker.test.d.ts +2 -0
- package/dist/baseworker.test.d.ts.map +1 -0
- package/dist/baseworker.test.js +181 -0
- package/dist/baseworker.test.js.map +1 -0
- package/dist/client.d.ts +15 -2
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +57 -3
- package/dist/client.js.map +1 -1
- package/dist/client.test.js +47 -2
- package/dist/client.test.js.map +1 -1
- package/dist/createEvent.d.ts +1 -1
- package/dist/createEvent.d.ts.map +1 -1
- package/dist/createEvent.test.js +2 -2
- package/dist/createEvent.test.js.map +1 -1
- package/dist/env.d.ts +26 -0
- package/dist/env.d.ts.map +1 -0
- package/dist/env.js +33 -0
- package/dist/env.js.map +1 -0
- package/dist/env.test.d.ts +2 -0
- package/dist/env.test.d.ts.map +1 -0
- package/dist/env.test.js +31 -0
- package/dist/env.test.js.map +1 -0
- package/dist/index.d.ts +3 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/sse.d.ts +1 -1
- package/dist/sse.d.ts.map +1 -1
- package/dist/types/channel.d.ts +35 -0
- package/dist/types/channel.d.ts.map +1 -0
- package/dist/types/channel.js +2 -0
- package/dist/types/channel.js.map +1 -0
- package/dist/types/event.d.ts +54 -0
- package/dist/types/event.d.ts.map +1 -0
- package/dist/types/event.js +2 -0
- package/dist/types/event.js.map +1 -0
- package/dist/types/events.d.ts +26 -0
- package/dist/types/events.d.ts.map +1 -0
- package/dist/types/events.js +34 -0
- package/dist/types/events.js.map +1 -0
- package/dist/types/extension.d.ts +37 -0
- package/dist/types/extension.d.ts.map +1 -0
- package/dist/types/extension.js +2 -0
- package/dist/types/extension.js.map +1 -0
- package/dist/types/index.d.ts +7 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +2 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/message.d.ts +28 -0
- package/dist/types/message.d.ts.map +1 -0
- package/dist/types/message.js +2 -0
- package/dist/types/message.js.map +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -13,7 +13,8 @@ over HTTP (SSE + POST).
|
|
|
13
13
|
|---|---|
|
|
14
14
|
| Connect to a bus over HTTP (`GET /events` SSE stream) | Identity registration (control-plane / `registryapi`) |
|
|
15
15
|
| `send` (directed) and `broadcast` (subscription-matched) | Worker runtime / swarm assembly |
|
|
16
|
-
| Receive routed events (`
|
|
16
|
+
| Receive routed events (`request.completed`, etc.) | Program compilation |
|
|
17
|
+
| Base worker (`BaseWorker`: extension registry, tool replies, presence announcement) | — |
|
|
17
18
|
| Protocol event type constants | — |
|
|
18
19
|
| Event construction helpers (`createEvent`, correctly timestamped + UUIDv7 ids) | — |
|
|
19
20
|
|
|
@@ -35,12 +36,12 @@ await worker.connect();
|
|
|
35
36
|
|
|
36
37
|
// Handle events routed to this worker.
|
|
37
38
|
for await (const evt of worker.events()) {
|
|
38
|
-
// respond to
|
|
39
|
+
// respond to request.completed, worker.input, ...
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
// Directed delivery — "I know who should handle this."
|
|
42
43
|
await worker.send(
|
|
43
|
-
createEvent(EventType.
|
|
44
|
+
createEvent(EventType.RequestCompleted, { result: "ok" }),
|
|
44
45
|
"reason.0",
|
|
45
46
|
);
|
|
46
47
|
|
|
@@ -50,6 +51,53 @@ await worker.broadcast(createEvent("stats.heartbeat", { uptime: 42 }));
|
|
|
50
51
|
await worker.close();
|
|
51
52
|
```
|
|
52
53
|
|
|
54
|
+
```ts
|
|
55
|
+
import { HTTPWorkerClient, readBusEnv } from "@niq.run/worker-sdk";
|
|
56
|
+
|
|
57
|
+
// Launched by the niq supervisor? Connect straight from the environment.
|
|
58
|
+
const client = new HTTPWorkerClient(readBusEnv());
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Base worker
|
|
62
|
+
|
|
63
|
+
`BaseWorker` (mirrors Go `pkg/baseworker`) layers the shared worker plumbing
|
|
64
|
+
on top of a `WorkerSideChannel`: an extension registry (what the worker
|
|
65
|
+
responds to and how), tool-request reply plumbing, and the `worker.ready`
|
|
66
|
+
presence announcement.
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { BaseWorker, HTTPWorkerClient, parseToolCall, EventType } from "@niq.run/worker-sdk";
|
|
70
|
+
|
|
71
|
+
const worker = new BaseWorker({
|
|
72
|
+
id: "echo@me",
|
|
73
|
+
subscriptions: [{ type: "tool.invoke" }],
|
|
74
|
+
channel: new HTTPWorkerClient({
|
|
75
|
+
baseURL: "http://localhost:8080",
|
|
76
|
+
workerID: "echo@me",
|
|
77
|
+
credential: "...",
|
|
78
|
+
}),
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// Declare what this worker responds to. Safe at any time — before or after
|
|
82
|
+
// connecting. Same (event, keyField, key) re-registration replaces the handler.
|
|
83
|
+
worker.register(
|
|
84
|
+
{ event: "tool.invoke", keyField: "name", key: "echo", description: "Echo a message" },
|
|
85
|
+
(evt) => {
|
|
86
|
+
const call = parseToolCall(evt);
|
|
87
|
+
worker.replyCompleted(call.callerID, call.callID, call.name, `echo: ${call.args["text"] ?? ""}`, call.traceID);
|
|
88
|
+
},
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
await worker.channel.connect();
|
|
92
|
+
await worker.announceReady("echo"); // broadcast worker.ready, self excluded
|
|
93
|
+
|
|
94
|
+
for await (const evt of worker.channel.events()) {
|
|
95
|
+
if (!worker.dispatchExtension(evt)) {
|
|
96
|
+
// no handler matched — e.g. replyUnknownTool(parseToolCall(evt))
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
53
101
|
## Protocol notes
|
|
54
102
|
|
|
55
103
|
- **Every request carries its own `worker_id` + `credential`** — no session
|
|
@@ -60,6 +108,10 @@ await worker.close();
|
|
|
60
108
|
- **Do not set `worker_id` yourself** — the bus overwrites it on receipt
|
|
61
109
|
(anti-spoofing, design D8). The client stamps it at publish time.
|
|
62
110
|
- `send` requires at least one target; use `broadcast` for undirected delivery.
|
|
111
|
+
- **Environment bootstrap**: when the niq project supervisor launches an
|
|
112
|
+
external worker, it injects `NIQ_BUS_URL`, `NIQ_WORKER_ID` and
|
|
113
|
+
`NIQ_WORKER_CREDENTIAL`. Use `readBusEnv()` to read them (throws, naming the
|
|
114
|
+
missing variables, when absent) and construct the client from the result:
|
|
63
115
|
- If no one subscribes, a broadcast silently disappears — that is a valid end
|
|
64
116
|
of the execution path, not an error.
|
|
65
117
|
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { Event, EventPattern, Extension, ExtensionHandler, ToolCall, WorkerSideChannel } from "./types/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* BaseWorker — the shared base implementation every worker builds on,
|
|
4
|
+
* mirroring Go `pkg/baseworker.BaseWorker`. It holds identity, subscription
|
|
5
|
+
* declarations and the worker-side bus channel; the extension registry (the
|
|
6
|
+
* uniform way to declare what the worker responds to and how); tool-request
|
|
7
|
+
* reply plumbing; and the `worker.ready` presence announcement.
|
|
8
|
+
*
|
|
9
|
+
* Registering an extension is safe at any time — before connecting or at
|
|
10
|
+
* runtime from within a handler. Registering the same (event, keyField, key)
|
|
11
|
+
* replaces the previous registration.
|
|
12
|
+
*/
|
|
13
|
+
export declare class BaseWorker {
|
|
14
|
+
readonly id: string;
|
|
15
|
+
readonly subscriptions: EventPattern[];
|
|
16
|
+
readonly channel: WorkerSideChannel;
|
|
17
|
+
private readonly regs;
|
|
18
|
+
constructor(opts: {
|
|
19
|
+
id: string;
|
|
20
|
+
subscriptions?: EventPattern[];
|
|
21
|
+
channel: WorkerSideChannel;
|
|
22
|
+
});
|
|
23
|
+
/** Bind an extension to a handler. Safe at any time, including at runtime. */
|
|
24
|
+
register(ext: Extension, handler: ExtensionHandler): void;
|
|
25
|
+
/**
|
|
26
|
+
* Route an event to the registered extension matching its event type.
|
|
27
|
+
* Returns whether a handler ran; the first matching registration wins. Async
|
|
28
|
+
* handlers are not awaited.
|
|
29
|
+
*/
|
|
30
|
+
dispatchExtension(evt: Event): boolean;
|
|
31
|
+
/** Snapshot of the registered extensions (insertion order). */
|
|
32
|
+
extensions(): Extension[];
|
|
33
|
+
/**
|
|
34
|
+
* Render the registry into the `worker.ready` "watch" wire format.
|
|
35
|
+
* `includeSelfOnly` controls whether SelfOnly extensions are rendered: a
|
|
36
|
+
* peer-facing broadcast leaves them out (they are not callable by peers).
|
|
37
|
+
*/
|
|
38
|
+
watchEntries(includeSelfOnly: boolean): Record<string, unknown>[];
|
|
39
|
+
/**
|
|
40
|
+
* Broadcast this worker's presence on the bus: the externally callable
|
|
41
|
+
* contract (SelfOnly left out), self excluded via `exclude_worker_id`.
|
|
42
|
+
* `publishes` is the wire form of the events this worker declares it emits
|
|
43
|
+
* (`worker.ready` "publishes").
|
|
44
|
+
*/
|
|
45
|
+
announceReady(workerType: string, publishes?: Record<string, unknown>[]): Promise<void>;
|
|
46
|
+
/** Answer a request caller with a request.completed result. */
|
|
47
|
+
replyCompleted(callerID: string, callID: string, result: string, traceID?: string): Promise<void>;
|
|
48
|
+
/** Answer a request caller with a request.failed error message. */
|
|
49
|
+
replyFailed(callerID: string, callID: string, error: string, traceID?: string): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Answer a request caller with a request.rejected, carrying the reason.
|
|
52
|
+
* Used when the worker declines a call based on its own rules (e.g. a
|
|
53
|
+
* safety guard) or after a human-in-the-loop approval is denied.
|
|
54
|
+
*/
|
|
55
|
+
replyRejected(callerID: string, callID: string, reason: string, traceID?: string): Promise<void>;
|
|
56
|
+
/** Reply to a tool-invocation whose name no handler matched. */
|
|
57
|
+
replyUnknownTool(tc: ToolCall): Promise<void>;
|
|
58
|
+
private reply;
|
|
59
|
+
}
|
|
60
|
+
/** Extract the common fields from a tool-invocation event. Mirrors `baseworker.ParseToolCall`. */
|
|
61
|
+
export declare function parseToolCall(evt: Event): ToolCall;
|
|
62
|
+
/** Return the string value of a tool argument, or "" if absent. */
|
|
63
|
+
export declare function argString(args: Record<string, unknown>, key: string): string;
|
|
64
|
+
/**
|
|
65
|
+
* Return the numeric value of a tool argument truncated to an integer, or
|
|
66
|
+
* `def` if absent. JSON numbers decode as float64, so all numeric forms are
|
|
67
|
+
* accepted. Mirrors `baseworker.ArgInt`.
|
|
68
|
+
*/
|
|
69
|
+
export declare function argInt(args: Record<string, unknown>, key: string, def: number): number;
|
|
70
|
+
//# sourceMappingURL=baseworker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"baseworker.d.ts","sourceRoot":"","sources":["../src/baseworker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,KAAK,EACL,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,QAAQ,EACR,iBAAiB,EAClB,MAAM,kBAAkB,CAAC;AAI1B;;;;;;;;;;GAUG;AACH,qBAAa,UAAU;IACrB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,aAAa,EAAE,YAAY,EAAE,CAAC;IACvC,QAAQ,CAAC,OAAO,EAAE,iBAAiB,CAAC;IAEpC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAGjB;gBAEQ,IAAI,EAAE;QAChB,EAAE,EAAE,MAAM,CAAC;QACX,aAAa,CAAC,EAAE,YAAY,EAAE,CAAC;QAC/B,OAAO,EAAE,iBAAiB,CAAC;KAC5B;IAMD,8EAA8E;IAC9E,QAAQ,CAAC,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE,gBAAgB,GAAG,IAAI;IAIzD;;;;OAIG;IACH,iBAAiB,CAAC,GAAG,EAAE,KAAK,GAAG,OAAO;IAStC,+DAA+D;IAC/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0,0 +1,163 @@
|
|
|
1
|
+
import { EventType } from "./types/index.js";
|
|
2
|
+
import { createEvent } from "./createEvent.js";
|
|
3
|
+
/**
|
|
4
|
+
* BaseWorker — the shared base implementation every worker builds on,
|
|
5
|
+
* mirroring Go `pkg/baseworker.BaseWorker`. It holds identity, subscription
|
|
6
|
+
* declarations and the worker-side bus channel; the extension registry (the
|
|
7
|
+
* uniform way to declare what the worker responds to and how); tool-request
|
|
8
|
+
* reply plumbing; and the `worker.ready` presence announcement.
|
|
9
|
+
*
|
|
10
|
+
* Registering an extension is safe at any time — before connecting or at
|
|
11
|
+
* runtime from within a handler. Registering the same (event, keyField, key)
|
|
12
|
+
* replaces the previous registration.
|
|
13
|
+
*/
|
|
14
|
+
export class BaseWorker {
|
|
15
|
+
id;
|
|
16
|
+
subscriptions;
|
|
17
|
+
channel;
|
|
18
|
+
regs = new Map();
|
|
19
|
+
constructor(opts) {
|
|
20
|
+
this.id = opts.id;
|
|
21
|
+
this.subscriptions = opts.subscriptions ?? [];
|
|
22
|
+
this.channel = opts.channel;
|
|
23
|
+
}
|
|
24
|
+
/** Bind an extension to a handler. Safe at any time, including at runtime. */
|
|
25
|
+
register(ext, handler) {
|
|
26
|
+
this.regs.set(extensionKey(ext), { ext, handler });
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Route an event to the registered extension matching its event type.
|
|
30
|
+
* Returns whether a handler ran; the first matching registration wins. Async
|
|
31
|
+
* handlers are not awaited.
|
|
32
|
+
*/
|
|
33
|
+
dispatchExtension(evt) {
|
|
34
|
+
for (const { ext, handler } of this.regs.values()) {
|
|
35
|
+
if (ext.event !== evt.type)
|
|
36
|
+
continue;
|
|
37
|
+
void handler(evt);
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
/** Snapshot of the registered extensions (insertion order). */
|
|
43
|
+
extensions() {
|
|
44
|
+
return [...this.regs.values()].map((r) => r.ext);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Render the registry into the `worker.ready` "watch" wire format.
|
|
48
|
+
* `includeSelfOnly` controls whether SelfOnly extensions are rendered: a
|
|
49
|
+
* peer-facing broadcast leaves them out (they are not callable by peers).
|
|
50
|
+
*/
|
|
51
|
+
watchEntries(includeSelfOnly) {
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const ext of this.extensions()) {
|
|
54
|
+
if (ext.selfOnly && !includeSelfOnly)
|
|
55
|
+
continue;
|
|
56
|
+
const entry = {
|
|
57
|
+
event: ext.event,
|
|
58
|
+
desc: ext.description,
|
|
59
|
+
};
|
|
60
|
+
if (ext.parameters) {
|
|
61
|
+
entry["parameters"] = ext.parameters;
|
|
62
|
+
}
|
|
63
|
+
out.push(entry);
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Broadcast this worker's presence on the bus: the externally callable
|
|
69
|
+
* contract (SelfOnly left out), self excluded via `exclude_worker_id`.
|
|
70
|
+
* `publishes` is the wire form of the events this worker declares it emits
|
|
71
|
+
* (`worker.ready` "publishes").
|
|
72
|
+
*/
|
|
73
|
+
async announceReady(workerType, publishes) {
|
|
74
|
+
const payload = {
|
|
75
|
+
type: workerType,
|
|
76
|
+
watch: this.watchEntries(false),
|
|
77
|
+
};
|
|
78
|
+
if (publishes && publishes.length > 0) {
|
|
79
|
+
payload["publishes"] = publishes;
|
|
80
|
+
}
|
|
81
|
+
const presence = createEvent(EventType.WorkerReady, payload);
|
|
82
|
+
presence.exclude_worker_id = this.id;
|
|
83
|
+
try {
|
|
84
|
+
await this.channel.broadcast(presence);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
// Presence announcements are best-effort, mirroring Go.
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
// ── Tool-serving helpers ──
|
|
91
|
+
//
|
|
92
|
+
// The repetitive parts every tool-serving worker repeats: replying to a
|
|
93
|
+
// tool-invocation with a request.completed / request.failed /
|
|
94
|
+
// request.rejected result, echoing the request's id and propagating the
|
|
95
|
+
// trace ID. Reply errors are ignored, mirroring Go.
|
|
96
|
+
/** Answer a request caller with a request.completed result. */
|
|
97
|
+
async replyCompleted(callerID, callID, result, traceID) {
|
|
98
|
+
await this.reply(EventType.RequestCompleted, callerID, callID, { result }, traceID);
|
|
99
|
+
}
|
|
100
|
+
/** Answer a request caller with a request.failed error message. */
|
|
101
|
+
async replyFailed(callerID, callID, error, traceID) {
|
|
102
|
+
await this.reply(EventType.RequestFailed, callerID, callID, { error }, traceID);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Answer a request caller with a request.rejected, carrying the reason.
|
|
106
|
+
* Used when the worker declines a call based on its own rules (e.g. a
|
|
107
|
+
* safety guard) or after a human-in-the-loop approval is denied.
|
|
108
|
+
*/
|
|
109
|
+
async replyRejected(callerID, callID, reason, traceID) {
|
|
110
|
+
await this.reply(EventType.RequestRejected, callerID, callID, { reason }, traceID);
|
|
111
|
+
}
|
|
112
|
+
/** Reply to a tool-invocation whose name no handler matched. */
|
|
113
|
+
async replyUnknownTool(tc) {
|
|
114
|
+
await this.replyFailed(tc.callerID, tc.callID, "unknown tool: " + tc.name, tc.traceID);
|
|
115
|
+
}
|
|
116
|
+
async reply(type, callerID, callID, payload, traceID) {
|
|
117
|
+
const evt = createEvent(type, payload);
|
|
118
|
+
evt.request_id = callID;
|
|
119
|
+
evt.trace_id = traceID;
|
|
120
|
+
try {
|
|
121
|
+
await this.channel.send(evt, callerID);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
// Reply failures are ignored, mirroring Go `_ = w.Channel.Send(...)`.
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Extract the common fields from a tool-invocation event. Mirrors `baseworker.ParseToolCall`. */
|
|
129
|
+
export function parseToolCall(evt) {
|
|
130
|
+
return {
|
|
131
|
+
callID: evt.request_id ?? "",
|
|
132
|
+
name: evt.type,
|
|
133
|
+
callerID: evt.worker_id,
|
|
134
|
+
args: isRecord(evt.payload) ? evt.payload : {},
|
|
135
|
+
traceID: evt.trace_id ?? "",
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/** Return the string value of a tool argument, or "" if absent. */
|
|
139
|
+
export function argString(args, key) {
|
|
140
|
+
const v = args[key];
|
|
141
|
+
return typeof v === "string" ? v : "";
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Return the numeric value of a tool argument truncated to an integer, or
|
|
145
|
+
* `def` if absent. JSON numbers decode as float64, so all numeric forms are
|
|
146
|
+
* accepted. Mirrors `baseworker.ArgInt`.
|
|
147
|
+
*/
|
|
148
|
+
export function argInt(args, key, def) {
|
|
149
|
+
const v = args[key];
|
|
150
|
+
if (typeof v === "number" && Number.isFinite(v))
|
|
151
|
+
return Math.trunc(v);
|
|
152
|
+
return def;
|
|
153
|
+
}
|
|
154
|
+
// The registry key is the event type with a NUL (\x00) suffix, which never
|
|
155
|
+
// occurs in an event-type identifier, so distinct extensions can never
|
|
156
|
+
// collide. Internal-only; never surfaced on the wire.
|
|
157
|
+
function extensionKey(ext) {
|
|
158
|
+
return `${ext.event}\x00`;
|
|
159
|
+
}
|
|
160
|
+
function isRecord(v) {
|
|
161
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
162
|
+
}
|
|
163
|
+
//# sourceMappingURL=baseworker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"baseworker.js","sourceRoot":"","sources":["../src/baseworker.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C;;;;;;;;;;GAUG;AACH,MAAM,OAAO,UAAU;IACZ,EAAE,CAAS;IACX,aAAa,CAAiB;IAC9B,OAAO,CAAoB;IAEnB,IAAI,GAAG,IAAI,GAAG,EAG5B,CAAC;IAE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AAG,CAAC,QAAQ,IAAI,EAAE;KAC5B,CAAC;AACJ,CAAC;AAED,mEAAmE;AACnE,MAAM,UAAU,SAAS,CAAC,IAA6B,EAAE,GAAW;IAClE,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;IACpB,OAAO,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACxC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,MAAM,CACpB,IAA6B,EAC7B,GAAW,EACX,GAAW;IAEX,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;IACpB,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;QAAE,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACtE,OAAO,GAAG,CAAC;AACb,CAAC;AAED,2EAA2E;AAC3E,uEAAuE;AACvE,sDAAsD;AACtD,SAAS,YAAY,CAAC,GAAc;IAClC,OAAO,GAAG,GAAG,CAAC,KAAK,MAAM,CAAC;AAC5B,CAAC;AAED,SAAS,QAAQ,CAAC,CAAU;IAC1B,OAAO,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAClE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"baseworker.test.d.ts","sourceRoot":"","sources":["../src/baseworker.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { BaseWorker, argInt, argString, parseToolCall } from "./baseworker.js";
|
|
3
|
+
import { EventType } from "./types/index.js";
|
|
4
|
+
class FakeChannel {
|
|
5
|
+
id = "fake";
|
|
6
|
+
sent = [];
|
|
7
|
+
broadcasts = [];
|
|
8
|
+
async connect() { }
|
|
9
|
+
async send(evt, ...targets) {
|
|
10
|
+
this.sent.push({ evt, targets });
|
|
11
|
+
}
|
|
12
|
+
async broadcast(evt) {
|
|
13
|
+
this.broadcasts.push(evt);
|
|
14
|
+
}
|
|
15
|
+
// eslint-disable-next-line require-yield
|
|
16
|
+
async *events() { }
|
|
17
|
+
async close() { }
|
|
18
|
+
}
|
|
19
|
+
function makeEvent(overrides) {
|
|
20
|
+
return {
|
|
21
|
+
id: "evt-1",
|
|
22
|
+
type: "tool.invoke",
|
|
23
|
+
status: "created",
|
|
24
|
+
payload: {},
|
|
25
|
+
worker_id: "caller.0",
|
|
26
|
+
timestamp: 1_700_000_000,
|
|
27
|
+
...overrides,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function makeWorker(channel) {
|
|
31
|
+
return new BaseWorker({
|
|
32
|
+
id: "echo.0",
|
|
33
|
+
subscriptions: [{ type: "tool.invoke" }],
|
|
34
|
+
channel,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
describe("extension registry", () => {
|
|
38
|
+
it("dispatches by event type", async () => {
|
|
39
|
+
const w = makeWorker(new FakeChannel());
|
|
40
|
+
const seen = [];
|
|
41
|
+
w.register({ event: "tool.invoke" }, (evt) => {
|
|
42
|
+
seen.push(evt);
|
|
43
|
+
});
|
|
44
|
+
const evt = makeEvent({});
|
|
45
|
+
expect(w.dispatchExtension(evt)).toBe(true);
|
|
46
|
+
expect(seen).toEqual([evt]);
|
|
47
|
+
});
|
|
48
|
+
it("replaces same-event registrations", () => {
|
|
49
|
+
const w = makeWorker(new FakeChannel());
|
|
50
|
+
const hits = [];
|
|
51
|
+
w.register({ event: "tool.upper" }, () => {
|
|
52
|
+
hits.push("upper");
|
|
53
|
+
});
|
|
54
|
+
w.register({ event: "tool.lower" }, () => {
|
|
55
|
+
hits.push("lower");
|
|
56
|
+
});
|
|
57
|
+
// Re-registering the same event replaces it.
|
|
58
|
+
w.register({ event: "tool.upper" }, () => {
|
|
59
|
+
hits.push("upper-2");
|
|
60
|
+
});
|
|
61
|
+
expect(w.dispatchExtension(makeEvent({ type: "tool.lower" }))).toBe(true);
|
|
62
|
+
expect(w.dispatchExtension(makeEvent({ type: "tool.upper" }))).toBe(true);
|
|
63
|
+
// An event no worker handles does not match.
|
|
64
|
+
expect(w.dispatchExtension(makeEvent({ type: "tool.other" }))).toBe(false);
|
|
65
|
+
expect(hits).toEqual(["lower", "upper-2"]);
|
|
66
|
+
});
|
|
67
|
+
it("returns false when nothing matches", () => {
|
|
68
|
+
const w = makeWorker(new FakeChannel());
|
|
69
|
+
expect(w.dispatchExtension(makeEvent({ type: "other.event" }))).toBe(false);
|
|
70
|
+
});
|
|
71
|
+
it("renders watch entries, omitting selfOnly for peers", () => {
|
|
72
|
+
const w = makeWorker(new FakeChannel());
|
|
73
|
+
w.register({
|
|
74
|
+
event: "tool.invoke",
|
|
75
|
+
description: "Echo a message",
|
|
76
|
+
parameters: { prefix: "..." },
|
|
77
|
+
}, () => { });
|
|
78
|
+
w.register({ event: "self.list_workers", selfOnly: true, description: "my view" }, () => { });
|
|
79
|
+
expect(w.watchEntries(false)).toEqual([
|
|
80
|
+
{
|
|
81
|
+
event: "tool.invoke",
|
|
82
|
+
desc: "Echo a message",
|
|
83
|
+
parameters: { prefix: "..." },
|
|
84
|
+
},
|
|
85
|
+
]);
|
|
86
|
+
expect(w.watchEntries(true)).toHaveLength(2);
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
describe("tool call parsing", () => {
|
|
90
|
+
it("extracts common fields and defaults args to an empty object", () => {
|
|
91
|
+
const evt = makeEvent({
|
|
92
|
+
request_id: "req-7",
|
|
93
|
+
trace_id: "trace-1",
|
|
94
|
+
type: "echo",
|
|
95
|
+
payload: { text: "hi" },
|
|
96
|
+
});
|
|
97
|
+
expect(parseToolCall(evt)).toEqual({
|
|
98
|
+
callID: "req-7",
|
|
99
|
+
name: "echo",
|
|
100
|
+
callerID: "caller.0",
|
|
101
|
+
args: { text: "hi" },
|
|
102
|
+
traceID: "trace-1",
|
|
103
|
+
});
|
|
104
|
+
const bare = parseToolCall(makeEvent({ type: "echo", payload: {} }));
|
|
105
|
+
expect(bare.callID).toBe("");
|
|
106
|
+
expect(bare.name).toBe("echo");
|
|
107
|
+
expect(bare.args).toEqual({});
|
|
108
|
+
});
|
|
109
|
+
it("reads scalar args with defaults", () => {
|
|
110
|
+
const args = { s: "x", n: 2.9, gone: undefined };
|
|
111
|
+
expect(argString(args, "s")).toBe("x");
|
|
112
|
+
expect(argString(args, "missing")).toBe("");
|
|
113
|
+
expect(argInt(args, "n", 0)).toBe(2);
|
|
114
|
+
expect(argInt(args, "gone", 5)).toBe(5);
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
describe("replies", () => {
|
|
118
|
+
it("replyCompleted sends request.completed echoing the request id", async () => {
|
|
119
|
+
const ch = new FakeChannel();
|
|
120
|
+
const w = makeWorker(ch);
|
|
121
|
+
await w.replyCompleted("caller.0", "req-7", "ok", "trace-1");
|
|
122
|
+
expect(ch.sent).toHaveLength(1);
|
|
123
|
+
const { evt, targets } = ch.sent[0];
|
|
124
|
+
expect(targets).toEqual(["caller.0"]);
|
|
125
|
+
expect(evt.type).toBe(EventType.RequestCompleted);
|
|
126
|
+
expect(evt.request_id).toBe("req-7");
|
|
127
|
+
expect(evt.trace_id).toBe("trace-1");
|
|
128
|
+
expect(evt.payload).toEqual({ result: "ok" });
|
|
129
|
+
});
|
|
130
|
+
it("replyFailed and replyRejected carry error / reason", async () => {
|
|
131
|
+
const ch = new FakeChannel();
|
|
132
|
+
const w = makeWorker(ch);
|
|
133
|
+
await w.replyFailed("caller.0", "r", "boom");
|
|
134
|
+
await w.replyRejected("caller.0", "r", "unsafe");
|
|
135
|
+
expect(ch.sent.map((s) => s.evt.type)).toEqual([
|
|
136
|
+
EventType.RequestFailed,
|
|
137
|
+
EventType.RequestRejected,
|
|
138
|
+
]);
|
|
139
|
+
expect(ch.sent[0].evt.payload).toEqual({ error: "boom" });
|
|
140
|
+
expect(ch.sent[1].evt.payload).toEqual({ reason: "unsafe" });
|
|
141
|
+
});
|
|
142
|
+
it("replyUnknownTool answers with a request.failed naming the tool", async () => {
|
|
143
|
+
const ch = new FakeChannel();
|
|
144
|
+
const w = makeWorker(ch);
|
|
145
|
+
await w.replyUnknownTool(parseToolCall(makeEvent({
|
|
146
|
+
type: "nope",
|
|
147
|
+
request_id: "req-9",
|
|
148
|
+
trace_id: "t",
|
|
149
|
+
payload: {},
|
|
150
|
+
})));
|
|
151
|
+
const { evt } = ch.sent[0];
|
|
152
|
+
expect(evt.type).toBe(EventType.RequestFailed);
|
|
153
|
+
expect(evt.request_id).toBe("req-9");
|
|
154
|
+
expect(evt.payload).toEqual({ error: "unknown tool: nope" });
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
describe("announceReady", () => {
|
|
158
|
+
it("broadcasts worker.ready with the peer-facing contract, self excluded", async () => {
|
|
159
|
+
const ch = new FakeChannel();
|
|
160
|
+
const w = makeWorker(ch);
|
|
161
|
+
w.register({ event: "tool.invoke", description: "Echo" }, () => { });
|
|
162
|
+
w.register({ event: "self.x", selfOnly: true, description: "hidden" }, () => { });
|
|
163
|
+
await w.announceReady("echo", [{ event: "echo.done" }]);
|
|
164
|
+
expect(ch.broadcasts).toHaveLength(1);
|
|
165
|
+
const presence = ch.broadcasts[0];
|
|
166
|
+
expect(presence.type).toBe(EventType.WorkerReady);
|
|
167
|
+
expect(presence.exclude_worker_id).toBe("echo.0");
|
|
168
|
+
expect(presence.payload).toEqual({
|
|
169
|
+
type: "echo",
|
|
170
|
+
watch: [{ event: "tool.invoke", desc: "Echo" }],
|
|
171
|
+
publishes: [{ event: "echo.done" }],
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
it("omits publishes when empty", async () => {
|
|
175
|
+
const ch = new FakeChannel();
|
|
176
|
+
const w = makeWorker(ch);
|
|
177
|
+
await w.announceReady("echo");
|
|
178
|
+
expect("publishes" in ch.broadcasts[0].payload).toBe(false);
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
//# sourceMappingURL=baseworker.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"baseworker.test.js","sourceRoot":"","sources":["../src/baseworker.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAE/E,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE7C,MAAM,WAAW;IACN,EAAE,GAAG,MAAM,CAAC;IACrB,IAAI,GAA6C,EAAE,CAAC;IACpD,UAAU,GAAY,EAAE,CAAC;IAEzB,KAAK,CAAC,OAAO,KAAmB,CAAC;IACjC,KAAK,CAAC,IAAI,CAAC,GAAU,EAAE,GAAG,OAAiB;QACzC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC;IACnC,CAAC;IACD,KAAK,CAAC,SAAS,CAAC,GAAU;QACxB,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC5B,CAAC;IACD,yCAAyC;IACzC,KAAK,CAAC,CAAC,MAAM,KAA0B,CAAC;IACxC,KAAK,CAAC,KAAK,KAAmB,CAAC;CAChC;AAED,SAAS,SAAS,CAAC,SAAyB;IAC1C,OAAO;QACL,EAAE,EAAE,OAAO;QACX,IAAI,EAAE,aAAa;QACnB,MAAM,EAAE,SAAS;QACjB,OAAO,EAAE,EAAE;QACX,SAAS,EAAE,UAAU;QACrB,SAAS,EAAE,aAAa;QACxB,GAAG,SAAS;KACb,CAAC;AACJ,CAAC;AAED,SAAS,UAAU,CAAC,OAAoB;IACtC,OAAO,IAAI,UAAU,CAAC;QACpB,EAAE,EAAE,QAAQ;QACZ,aAAa,EA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./types/index.js";
|
|
2
|
+
import type { WorkerSideChannel } from "./types/index.js";
|
|
3
3
|
export interface HTTPWorkerClientOptions {
|
|
4
4
|
/** Base URL of the niq bus, e.g. `http://localhost:8080`. Trailing slash optional. */
|
|
5
5
|
baseURL: string;
|
|
@@ -9,6 +9,8 @@ export interface HTTPWorkerClientOptions {
|
|
|
9
9
|
credential: string;
|
|
10
10
|
/** Injectable fetch (e.g. for tests / proxies). Defaults to global fetch. */
|
|
11
11
|
fetchImpl?: typeof fetch;
|
|
12
|
+
/** Optional logger for reconnect / network diagnostics (defaults to none). */
|
|
13
|
+
logger?: Pick<Console, "debug" | "warn">;
|
|
12
14
|
}
|
|
13
15
|
/**
|
|
14
16
|
* A WorkerSideChannel over the niq HTTP transport.
|
|
@@ -32,12 +34,23 @@ export declare class HTTPWorkerClient implements WorkerSideChannel {
|
|
|
32
34
|
private readonly workerID;
|
|
33
35
|
private readonly credential;
|
|
34
36
|
private readonly fetchImpl;
|
|
37
|
+
private readonly logger?;
|
|
35
38
|
private es?;
|
|
36
39
|
private controller?;
|
|
37
40
|
private connected;
|
|
38
41
|
private closed;
|
|
42
|
+
private reconnectPromise?;
|
|
39
43
|
constructor(opts: HTTPWorkerClientOptions);
|
|
40
44
|
connect(): Promise<void>;
|
|
45
|
+
private openSSE;
|
|
46
|
+
/**
|
|
47
|
+
* Re-establish the SSE stream (the client's session anchor on the bus).
|
|
48
|
+
* Used when the bus no longer has a session for us (publish 400
|
|
49
|
+
* "worker not connected"), e.g. after the bus restarted or our connection
|
|
50
|
+
* was silently torn down. Concurrent callers share one in-flight attempt.
|
|
51
|
+
*/
|
|
52
|
+
private reconnectSSE;
|
|
53
|
+
private doReconnect;
|
|
41
54
|
send(event: Event, ...targets: string[]): Promise<void>;
|
|
42
55
|
broadcast(event: Event): Promise<void>;
|
|
43
56
|
events(): AsyncIterable<Event>;
|
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAiB,MAAM,
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAiB,MAAM,kBAAkB,CAAC;AAC7D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAa1D,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;IACzB,8EAA8E;IAC9E,MAAM,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC,CAAC;CAC1C;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;IACzC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAkC;IAE1D,OAAO,CAAC,EAAE,CAAC,CAA6B;IACxC,OAAO,CAAC,UAAU,CAAC,CAAkB;IACrC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,gBAAgB,CAAC,CAAgB;gBAE7B,IAAI,EAAE,uBAAuB;IASnC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;YAShB,OAAO;IAqBrB;;;;;OAKG;IACH,OAAO,CAAC,YAAY;Y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