@paddockai/server 0.0.0-stage → 0.0.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/dist/index.js ADDED
@@ -0,0 +1,1128 @@
1
+ // ../wire/src/types.ts
2
+ var streamEventNames = [
3
+ "session",
4
+ "message",
5
+ "turn.started",
6
+ "turn.ended",
7
+ "stop.requested",
8
+ "agent.unavailable",
9
+ "agent.available",
10
+ "daemon.outdated",
11
+ "config.applied",
12
+ "session.status",
13
+ "outbox.queued",
14
+ "outbox.delivered",
15
+ "outbox.failed",
16
+ "status.update",
17
+ "error"
18
+ ];
19
+ var messageKinds = [
20
+ "user",
21
+ "assistant",
22
+ "reasoning",
23
+ "tool_call",
24
+ "tool_result",
25
+ "unknown",
26
+ "streaming"
27
+ ];
28
+ function isKnownMessageKind(kind) {
29
+ return messageKinds.includes(kind);
30
+ }
31
+ function isStreamingMessageEvent(data) {
32
+ return data.type === "message" && data.message.kind === "streaming";
33
+ }
34
+
35
+ // ../wire/src/errors.ts
36
+ var errorBrand = /* @__PURE__ */ Symbol.for("paddock.PaddockError");
37
+ var connectionBrand = /* @__PURE__ */ Symbol.for("paddock.PaddockConnectionError");
38
+ var timeoutBrand = /* @__PURE__ */ Symbol.for("paddock.PaddockTimeoutError");
39
+ function branded(e, brand) {
40
+ return typeof e === "object" && e !== null && e[brand] === true;
41
+ }
42
+ var PaddockError = class extends Error {
43
+ status;
44
+ code;
45
+ details;
46
+ requestId;
47
+ constructor(init) {
48
+ super(init.message);
49
+ this.name = "PaddockError";
50
+ this.status = init.status;
51
+ this.code = init.code;
52
+ this.details = init.details;
53
+ this.requestId = init.requestId ?? null;
54
+ Object.defineProperty(this, errorBrand, { value: true });
55
+ }
56
+ static is(e) {
57
+ return branded(e, errorBrand);
58
+ }
59
+ };
60
+ var PaddockConnectionError = class extends Error {
61
+ constructor(message, options) {
62
+ super(message, options);
63
+ this.name = "PaddockConnectionError";
64
+ Object.defineProperty(this, connectionBrand, { value: true });
65
+ }
66
+ static is(e) {
67
+ return branded(e, connectionBrand);
68
+ }
69
+ };
70
+ var PaddockTimeoutError = class extends PaddockConnectionError {
71
+ constructor(message, options) {
72
+ super(message, options);
73
+ this.name = "PaddockTimeoutError";
74
+ Object.defineProperty(this, timeoutBrand, { value: true });
75
+ }
76
+ static is(e) {
77
+ return branded(e, timeoutBrand);
78
+ }
79
+ };
80
+ var statusOfCode = {
81
+ invalid_request: 400,
82
+ unauthorized: 401,
83
+ forbidden: 403,
84
+ not_found: 404,
85
+ conflict: 409,
86
+ payload_too_large: 413,
87
+ unsupported: 422,
88
+ unavailable: 503,
89
+ internal: 500
90
+ };
91
+ function codeOfStatus(status) {
92
+ for (const [code, s] of Object.entries(statusOfCode)) {
93
+ if (s === status) return code;
94
+ }
95
+ return "internal";
96
+ }
97
+ function errorFromBody(body, status, requestId) {
98
+ const error = body?.error;
99
+ if (error && typeof error.code === "string") {
100
+ return new PaddockError({
101
+ status: status || statusOfCode[error.code] || 500,
102
+ code: error.code,
103
+ message: typeof error.message === "string" ? error.message : error.code,
104
+ details: typeof error.details === "object" && error.details !== null ? error.details : void 0,
105
+ requestId
106
+ });
107
+ }
108
+ return new PaddockError({
109
+ status,
110
+ code: codeOfStatus(status),
111
+ message: `HTTP ${status}`,
112
+ requestId
113
+ });
114
+ }
115
+ async function errorFromResponse(res) {
116
+ const requestId = res.headers.get("Request-Id");
117
+ let body = null;
118
+ try {
119
+ const text = await res.text();
120
+ body = text ? JSON.parse(text) : null;
121
+ } catch {
122
+ body = null;
123
+ }
124
+ return errorFromBody(body, res.status, requestId);
125
+ }
126
+
127
+ // ../wire/src/transport.ts
128
+ var defaultBaseUrl = "https://api.paddockai.dev/v1";
129
+ var defaultTimeoutMs = 6e4;
130
+ var longTimeoutMs = 6e5;
131
+ var defaultMaxRetries = 2;
132
+ function sleep(ms, signal) {
133
+ return new Promise((resolve) => {
134
+ if (signal?.aborted) return resolve();
135
+ const done = () => {
136
+ clearTimeout(timer);
137
+ signal?.removeEventListener("abort", done);
138
+ resolve();
139
+ };
140
+ const timer = setTimeout(done, ms);
141
+ signal?.addEventListener("abort", done, { once: true });
142
+ });
143
+ }
144
+ function backoff(attempt, baseMs, capMs) {
145
+ const ceiling = Math.min(capMs, baseMs * 2 ** attempt);
146
+ return ceiling / 2 + Math.random() * (ceiling / 2);
147
+ }
148
+ function segment(value, keepSlashes = false) {
149
+ const s = String(value);
150
+ return keepSlashes ? s.split("/").map(encodeURIComponent).join("/") : encodeURIComponent(s);
151
+ }
152
+ var Transport = class {
153
+ baseUrl;
154
+ maxRetries;
155
+ timeoutMs;
156
+ #token;
157
+ client;
158
+ fetchFn;
159
+ sleepFn;
160
+ constructor(options) {
161
+ this.baseUrl = (options.baseUrl ?? defaultBaseUrl).replace(/\/+$/, "");
162
+ this.#token = options.token;
163
+ this.client = options.client;
164
+ this.maxRetries = Math.max(0, options.maxRetries ?? defaultMaxRetries);
165
+ this.timeoutMs = options.timeoutMs ?? defaultTimeoutMs;
166
+ this.fetchFn = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
167
+ this.sleepFn = options.sleep ?? sleep;
168
+ }
169
+ /** The URL of path with its query; arrays are comma-joined, objects are deepObject. */
170
+ url(path, query) {
171
+ const params = new URLSearchParams();
172
+ for (const [name, value] of Object.entries(query ?? {})) {
173
+ if (value === void 0) continue;
174
+ if (Array.isArray(value)) {
175
+ if (value.length > 0) params.append(name, value.join(","));
176
+ } else if (typeof value === "object") {
177
+ for (const [k, v] of Object.entries(value)) params.append(`${name}[${k}]`, v);
178
+ } else {
179
+ params.append(name, String(value));
180
+ }
181
+ }
182
+ const qs = params.toString();
183
+ return this.baseUrl + path + (qs ? `?${qs}` : "");
184
+ }
185
+ /** The headers every request carries; the token travels only in Authorization. */
186
+ headers(extra) {
187
+ const auth = this.#token ? { Authorization: `Bearer ${this.#token}` } : {};
188
+ return { ...auth, "Paddock-Client": this.client, ...extra };
189
+ }
190
+ get fetch() {
191
+ return this.fetchFn;
192
+ }
193
+ wait(ms, signal) {
194
+ return this.sleepFn(ms, signal);
195
+ }
196
+ /** Sends one request, retrying an idempotent one after a connection error, a timeout, or a 5xx. */
197
+ async request(options) {
198
+ const retries = options.method === "POST" ? 0 : this.maxRetries;
199
+ const headers = this.headers();
200
+ let body = options.body;
201
+ if (options.json !== void 0) {
202
+ body = JSON.stringify(options.json);
203
+ headers["Content-Type"] = "application/json";
204
+ } else if (options.contentType) {
205
+ headers["Content-Type"] = options.contentType;
206
+ }
207
+ const url = this.url(options.path, options.query);
208
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
209
+ for (let attempt = 0; ; attempt++) {
210
+ const ctrl = new AbortController();
211
+ let timedOut = false;
212
+ const timer = setTimeout(() => {
213
+ timedOut = true;
214
+ ctrl.abort();
215
+ }, timeoutMs);
216
+ const onAbort = () => ctrl.abort();
217
+ options.signal?.addEventListener("abort", onAbort, { once: true });
218
+ let res;
219
+ try {
220
+ res = await this.fetchFn(url, { method: options.method, headers, body, signal: ctrl.signal });
221
+ if (res.ok) return await read(res, options.read ?? "json");
222
+ } catch (e) {
223
+ if (options.signal?.aborted) throw e;
224
+ const what = `${options.method} ${options.path}`;
225
+ const failure2 = timedOut ? new PaddockTimeoutError(`${what} timed out after ${timeoutMs} ms`, { cause: e }) : new PaddockConnectionError(`${what}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
226
+ if (attempt >= retries) throw failure2;
227
+ await this.sleepFn(backoff(attempt, 500, 8e3), options.signal);
228
+ continue;
229
+ } finally {
230
+ clearTimeout(timer);
231
+ options.signal?.removeEventListener("abort", onAbort);
232
+ }
233
+ const failure = await errorFromResponse(res);
234
+ if (res.status < 500 || attempt >= retries) throw failure;
235
+ await this.sleepFn(backoff(attempt, 500, 8e3), options.signal);
236
+ }
237
+ }
238
+ };
239
+ async function read(res, how) {
240
+ switch (how) {
241
+ case "none":
242
+ await res.body?.cancel();
243
+ return void 0;
244
+ case "text":
245
+ return res.text();
246
+ case "bytes":
247
+ return new Uint8Array(await res.arrayBuffer());
248
+ case "json": {
249
+ const text = await res.text();
250
+ return text ? JSON.parse(text) : void 0;
251
+ }
252
+ }
253
+ }
254
+
255
+ // ../wire/src/sse.ts
256
+ var SSEParser = class {
257
+ decoder = new TextDecoder("utf-8");
258
+ buf = "";
259
+ event = "";
260
+ id;
261
+ data = [];
262
+ hasData = false;
263
+ /** Feeds bytes and returns the events they complete. */
264
+ push(chunk) {
265
+ this.buf += typeof chunk === "string" ? chunk : this.decoder.decode(chunk, { stream: true });
266
+ return this.consume(false);
267
+ }
268
+ /** Ends the input: a last line without a line end is parsed; an incomplete event is dropped. */
269
+ end() {
270
+ this.buf += this.decoder.decode();
271
+ return this.consume(true);
272
+ }
273
+ consume(final) {
274
+ const out = [];
275
+ let start = 0;
276
+ for (; ; ) {
277
+ const cr = this.buf.indexOf("\r", start);
278
+ const lf = this.buf.indexOf("\n", start);
279
+ let i;
280
+ if (cr < 0) i = lf;
281
+ else if (lf < 0) i = cr;
282
+ else i = Math.min(cr, lf);
283
+ if (i < 0) break;
284
+ if (this.buf[i] === "\r" && i === this.buf.length - 1 && !final) break;
285
+ const line = this.buf.slice(start, i);
286
+ start = this.buf[i] === "\r" && this.buf[i + 1] === "\n" ? i + 2 : i + 1;
287
+ const ev = this.line(line);
288
+ if (ev) out.push(ev);
289
+ }
290
+ this.buf = this.buf.slice(start);
291
+ if (final && this.buf !== "") {
292
+ const ev = this.line(this.buf);
293
+ if (ev) out.push(ev);
294
+ this.buf = "";
295
+ }
296
+ return out;
297
+ }
298
+ line(line) {
299
+ if (line === "") return this.dispatch();
300
+ if (line.startsWith(":")) return void 0;
301
+ const colon = line.indexOf(":");
302
+ const field = colon < 0 ? line : line.slice(0, colon);
303
+ let value = colon < 0 ? "" : line.slice(colon + 1);
304
+ if (value.startsWith(" ")) value = value.slice(1);
305
+ switch (field) {
306
+ case "event":
307
+ this.event = value;
308
+ break;
309
+ case "data":
310
+ this.data.push(value);
311
+ this.hasData = true;
312
+ break;
313
+ case "id":
314
+ if (!value.includes("\0")) this.id = value;
315
+ break;
316
+ }
317
+ return void 0;
318
+ }
319
+ dispatch() {
320
+ let ev;
321
+ if (this.hasData) {
322
+ ev = { event: this.event || "message", data: this.data.join("\n") };
323
+ if (this.id !== void 0) ev.id = this.id;
324
+ }
325
+ this.event = "";
326
+ this.id = void 0;
327
+ this.data = [];
328
+ this.hasData = false;
329
+ return ev;
330
+ }
331
+ };
332
+
333
+ // ../wire/src/stream.ts
334
+ var defaultStreamTiming = {
335
+ connectTimeoutMs: 1e4,
336
+ livenessMs: 45e3,
337
+ backoffBaseMs: 500,
338
+ backoffCapMs: 3e4,
339
+ stableMs: 1e4
340
+ };
341
+ function decodeStreamEvent(raw) {
342
+ if (!streamEventNames.includes(raw.event)) return void 0;
343
+ const ev = { event: raw.event, data: JSON.parse(raw.data) };
344
+ if (raw.id !== void 0) ev.id = raw.id;
345
+ return ev;
346
+ }
347
+ var EventStream = class {
348
+ constructor(transport, path, options = {}, timing = defaultStreamTiming) {
349
+ this.transport = transport;
350
+ this.path = path;
351
+ this.options = options;
352
+ this.timing = timing;
353
+ this.highest = options.after ?? 0;
354
+ this.events = this.run();
355
+ }
356
+ transport;
357
+ path;
358
+ options;
359
+ timing;
360
+ closer = new AbortController();
361
+ events;
362
+ highest;
363
+ state;
364
+ terminal;
365
+ /** The highest seq the stream has yielded, or the after it started from. */
366
+ get lastSeq() {
367
+ return this.highest;
368
+ }
369
+ [Symbol.asyncIterator]() {
370
+ return this.events;
371
+ }
372
+ /** Ends the stream; a pending next() resolves as done. */
373
+ close() {
374
+ if (this.closer.signal.aborted) return;
375
+ this.closer.abort();
376
+ this.setState("closed", null);
377
+ }
378
+ setState(state, error) {
379
+ if (this.state === state && error === null) return;
380
+ this.state = state;
381
+ this.options.onConnection?.(state, error);
382
+ }
383
+ fail(error) {
384
+ this.terminal = error;
385
+ this.closer.abort();
386
+ this.setState("closed", error);
387
+ throw error;
388
+ }
389
+ async *run() {
390
+ let attempt = 0;
391
+ try {
392
+ while (!this.closer.signal.aborted) {
393
+ let openedAt;
394
+ this.setState("connecting", null);
395
+ const conn = new AbortController();
396
+ const abort = () => conn.abort();
397
+ this.closer.signal.addEventListener("abort", abort, { once: true });
398
+ let idle;
399
+ const arm = (ms) => {
400
+ clearTimeout(idle);
401
+ idle = setTimeout(abort, ms);
402
+ };
403
+ try {
404
+ arm(this.timing.connectTimeoutMs);
405
+ const query = this.highest > 0 || this.options.after !== void 0 ? { after: this.highest } : void 0;
406
+ const res = await this.transport.fetch(this.transport.url(this.path, query), {
407
+ method: "GET",
408
+ headers: this.transport.headers({ Accept: "text/event-stream" }),
409
+ signal: conn.signal
410
+ });
411
+ if (!res.ok) {
412
+ const err = await errorFromResponse(res);
413
+ if (res.status < 500) this.fail(err);
414
+ throw err;
415
+ }
416
+ if (!res.body) throw new PaddockConnectionError("stream: response has no body");
417
+ arm(this.timing.livenessMs);
418
+ const reader = res.body.getReader();
419
+ const parser = new SSEParser();
420
+ for (; ; ) {
421
+ const { done, value } = await reader.read();
422
+ if (done) break;
423
+ arm(this.timing.livenessMs);
424
+ for (const raw of parser.push(value)) {
425
+ const ev = decodeStreamEvent(raw);
426
+ if (!ev) continue;
427
+ if (ev.event === "error") this.fail(errorFromBody(ev.data, 0, null));
428
+ if (ev.event === "session" && openedAt === void 0) {
429
+ openedAt = Date.now();
430
+ this.setState("open", null);
431
+ }
432
+ if (ev.event !== "session" && "seq" in ev.data && typeof ev.data.seq === "number") {
433
+ if (ev.data.seq <= this.highest) continue;
434
+ this.highest = ev.data.seq;
435
+ }
436
+ yield ev;
437
+ }
438
+ }
439
+ } catch {
440
+ if (this.terminal) throw this.terminal;
441
+ if (this.closer.signal.aborted) return;
442
+ } finally {
443
+ clearTimeout(idle);
444
+ this.closer.signal.removeEventListener("abort", abort);
445
+ conn.abort();
446
+ }
447
+ if (this.closer.signal.aborted) return;
448
+ if (openedAt !== void 0 && Date.now() - openedAt >= this.timing.stableMs) attempt = 0;
449
+ this.setState("reconnecting", null);
450
+ await this.transport.wait(
451
+ backoff(attempt++, this.timing.backoffBaseMs, this.timing.backoffCapMs),
452
+ this.closer.signal
453
+ );
454
+ }
455
+ } finally {
456
+ if (!this.closer.signal.aborted) this.close();
457
+ }
458
+ }
459
+ };
460
+
461
+ // ../wire/src/list.ts
462
+ var PageList = class {
463
+ constructor(fetchPage) {
464
+ this.fetchPage = fetchPage;
465
+ }
466
+ fetchPage;
467
+ first;
468
+ firstPage() {
469
+ this.first ??= this.fetchPage(void 0);
470
+ return this.first;
471
+ }
472
+ then(onfulfilled, onrejected) {
473
+ return this.firstPage().then(onfulfilled, onrejected);
474
+ }
475
+ async *[Symbol.asyncIterator]() {
476
+ let page = await this.firstPage();
477
+ for (; ; ) {
478
+ yield* page.data;
479
+ if (!page.nextCursor) return;
480
+ page = await this.fetchPage(page.nextCursor);
481
+ }
482
+ }
483
+ };
484
+
485
+ // ../wire/src/session.ts
486
+ var SessionOperations = class {
487
+ constructor(transport, id) {
488
+ this.transport = transport;
489
+ this.id = id;
490
+ const base = `/sessions/${segment(id)}`;
491
+ this.events = {
492
+ list: (o = {}) => transport.request({
493
+ method: "GET",
494
+ path: `${base}/events`,
495
+ query: { after: o.after, before: o.before, types: o.types, limit: o.limit }
496
+ })
497
+ };
498
+ this.turns = {
499
+ list: (o = {}) => new PageList(
500
+ (cursor) => transport.request({
501
+ method: "GET",
502
+ path: `${base}/turns`,
503
+ query: { limit: o.limit, cursor: cursor ?? o.cursor }
504
+ })
505
+ ),
506
+ get: (turnId) => transport.request({ method: "GET", path: `${base}/turns/${segment(turnId)}` })
507
+ };
508
+ }
509
+ transport;
510
+ id;
511
+ events;
512
+ turns;
513
+ get base() {
514
+ return `/sessions/${segment(this.id)}`;
515
+ }
516
+ /** Stores a user message; resolves with its event once stored (002#operations_2). */
517
+ send(text) {
518
+ return this.transport.request({ method: "POST", path: `${this.base}/messages`, json: { text } });
519
+ }
520
+ /** Stores a stop.requested event and resolves with it. */
521
+ stop() {
522
+ return this.transport.request({ method: "POST", path: `${this.base}/stop` });
523
+ }
524
+ /** The session's events from after, then live events, reconnecting on its own (009#stream-reconnection). */
525
+ stream(options = {}) {
526
+ return new EventStream(this.transport, `${this.base}/stream`, options);
527
+ }
528
+ /** Mints a session token for the browser. */
529
+ createToken(options) {
530
+ return this.transport.request({
531
+ method: "POST",
532
+ path: `${this.base}/tokens`,
533
+ json: { ttlSeconds: options.ttl }
534
+ });
535
+ }
536
+ /** Reads the session. */
537
+ get() {
538
+ return this.transport.request({ method: "GET", path: this.base });
539
+ }
540
+ };
541
+
542
+ // src/version.ts
543
+ var version = "0.0.1";
544
+
545
+ // src/client.ts
546
+ function nodeProcess() {
547
+ return globalThis.process;
548
+ }
549
+ function env(name) {
550
+ return nodeProcess()?.env?.[name] || void 0;
551
+ }
552
+ function nodeModules() {
553
+ const get = nodeProcess()?.getBuiltinModule;
554
+ if (typeof get !== "function") return void 0;
555
+ const fs = get("node:fs");
556
+ const os = get("node:os");
557
+ const path = get("node:path");
558
+ return fs && os && path ? { fs, os, path } : void 0;
559
+ }
560
+ function credentialsPath() {
561
+ const m = nodeModules();
562
+ if (!m) return void 0;
563
+ const xdg = env("XDG_CONFIG_HOME");
564
+ return xdg ? m.path.join(xdg, "paddock", "credentials") : m.path.join(m.os.homedir(), ".config", "paddock", "credentials");
565
+ }
566
+ var CREDENTIALS_FIX = "run paddock auth login to replace it or paddock auth logout to remove it";
567
+ function readCredentials() {
568
+ const m = nodeModules();
569
+ let path;
570
+ try {
571
+ path = credentialsPath();
572
+ } catch {
573
+ return {};
574
+ }
575
+ if (!m || !path) return {};
576
+ let text;
577
+ try {
578
+ text = m.fs.readFileSync(path, "utf8");
579
+ } catch (e) {
580
+ if (e.code === "ENOENT") return {};
581
+ throw new Error(`paddock: cannot read ${path}: ${String(e)}; ${CREDENTIALS_FIX}`);
582
+ }
583
+ let data;
584
+ try {
585
+ data = JSON.parse(text);
586
+ } catch (e) {
587
+ throw new Error(`paddock: ${path} is not a credentials file: ${String(e)}; ${CREDENTIALS_FIX}`);
588
+ }
589
+ if (typeof data !== "object" || data === null || Array.isArray(data))
590
+ throw new Error(`paddock: ${path} is not a credentials file: not a JSON object; ${CREDENTIALS_FIX}`);
591
+ const { apiKey, baseUrl } = data;
592
+ for (const [name, value] of [
593
+ ["apiKey", apiKey],
594
+ ["baseUrl", baseUrl]
595
+ ])
596
+ if (value !== void 0 && typeof value !== "string")
597
+ throw new Error(`paddock: ${path} is not a credentials file: ${name} is not a string; ${CREDENTIALS_FIX}`);
598
+ return {
599
+ apiKey: apiKey || void 0,
600
+ baseUrl: baseUrl || void 0,
601
+ path
602
+ };
603
+ }
604
+ var trimSlash = (u) => u.replace(/\/+$/, "");
605
+ function lookup(options) {
606
+ let apiKey = options.apiKey || env("PADDOCK_API_KEY");
607
+ let baseUrl = options.baseUrl || env("PADDOCK_BASE_URL");
608
+ if (!apiKey) {
609
+ const creds = readCredentials();
610
+ const own = creds.baseUrl ?? defaultBaseUrl;
611
+ if (creds.apiKey && (!baseUrl || trimSlash(baseUrl) === trimSlash(own))) apiKey = creds.apiKey;
612
+ baseUrl ||= creds.baseUrl;
613
+ }
614
+ return { apiKey: apiKey ?? "", baseUrl };
615
+ }
616
+ function templateRef(ref) {
617
+ const at = ref.lastIndexOf("@");
618
+ return at < 0 ? { name: ref, version: void 0 } : { name: ref.slice(0, at), version: ref.slice(at + 1) };
619
+ }
620
+ var Paddock = class {
621
+ templates;
622
+ models;
623
+ modelProviders;
624
+ agents;
625
+ sessions;
626
+ connectors;
627
+ outbox;
628
+ constructor(options = {}) {
629
+ const { apiKey, baseUrl } = lookup(options);
630
+ const transport = new Transport({
631
+ token: apiKey,
632
+ baseUrl,
633
+ client: `js-server/${version}`,
634
+ maxRetries: options.maxRetries,
635
+ timeoutMs: options.timeoutMs,
636
+ fetch: options.fetch
637
+ });
638
+ this.templates = new Templates(transport);
639
+ this.models = new Models(transport);
640
+ this.modelProviders = new ModelProviders(transport);
641
+ this.agents = new Agents(transport);
642
+ this.sessions = new Sessions(transport);
643
+ this.connectors = new Connectors(transport);
644
+ this.outbox = new Outbox(transport);
645
+ }
646
+ };
647
+ var Templates = class {
648
+ constructor(t) {
649
+ this.t = t;
650
+ }
651
+ t;
652
+ /**
653
+ * Saves a template document (013#template-document): a path sends the YAML file as
654
+ * it is; a document is sent as JSON. The server assigns the version; a document equal
655
+ * to the latest version returns that version. With dryRun, the server checks the
656
+ * document and returns the version a create would return, storing nothing.
657
+ */
658
+ async create(pathOrDocument, options = {}) {
659
+ const query = options.dryRun ? { dryRun: true } : void 0;
660
+ if (typeof pathOrDocument !== "string")
661
+ return this.t.request({ method: "POST", path: "/templates", query, json: pathOrDocument });
662
+ const fs = await import("fs/promises");
663
+ const yaml = await fs.readFile(pathOrDocument, "utf8");
664
+ return this.t.request({ method: "POST", path: "/templates", query, body: yaml, contentType: "application/yaml" });
665
+ }
666
+ /** "name@version" reads that version; "name" reads the latest. */
667
+ get(ref) {
668
+ const { name, version: version2 } = templateRef(ref);
669
+ const path = version2 === void 0 ? `/templates/${segment(name)}` : `/templates/${segment(name)}/versions/${segment(version2)}`;
670
+ return this.t.request({ method: "GET", path });
671
+ }
672
+ /** The latest version of each template, or with name every version of that template. */
673
+ list(options = {}) {
674
+ const path = options.name === void 0 ? "/templates" : `/templates/${segment(options.name)}/versions`;
675
+ return new PageList(
676
+ (cursor) => this.t.request({ method: "GET", path, query: { limit: options.limit, cursor: cursor ?? options.cursor } })
677
+ );
678
+ }
679
+ /** Deletes "name@version". */
680
+ async delete(ref) {
681
+ const { name, version: version2 } = templateRef(ref);
682
+ await this.t.request({
683
+ method: "DELETE",
684
+ path: `/templates/${segment(name)}/versions/${segment(version2 ?? "")}`,
685
+ read: "none"
686
+ });
687
+ }
688
+ };
689
+ var Models = class {
690
+ constructor(t) {
691
+ this.t = t;
692
+ }
693
+ t;
694
+ /** The platform models, then each provider's, in one page. */
695
+ list() {
696
+ return new PageList(() => this.t.request({ method: "GET", path: "/models" }));
697
+ }
698
+ };
699
+ var ModelProviders = class {
700
+ constructor(t) {
701
+ this.t = t;
702
+ }
703
+ t;
704
+ /** The providers, by name. */
705
+ list(options = {}) {
706
+ return new PageList(
707
+ (cursor) => this.t.request({
708
+ method: "GET",
709
+ path: "/model-providers",
710
+ query: { limit: options.limit, cursor: cursor ?? options.cursor }
711
+ })
712
+ );
713
+ }
714
+ get(name) {
715
+ return this.t.request({ method: "GET", path: `/model-providers/${segment(name)}` });
716
+ }
717
+ /** Verifies the key, then adds the provider; the key is never returned. */
718
+ create(spec) {
719
+ return this.t.request({ method: "POST", path: "/model-providers", json: spec });
720
+ }
721
+ /** An omitted field keeps its value; a new key or base URL is verified first. */
722
+ update(name, patch) {
723
+ return this.t.request({ method: "PUT", path: `/model-providers/${segment(name)}`, json: patch });
724
+ }
725
+ async delete(name) {
726
+ await this.t.request({ method: "DELETE", path: `/model-providers/${segment(name)}`, read: "none" });
727
+ }
728
+ /**
729
+ * Verifies a provider's stored key, recording its status, or a draft's key, storing
730
+ * nothing (014#key-verification).
731
+ */
732
+ test(nameOrDraft, options = {}) {
733
+ if (typeof nameOrDraft !== "string")
734
+ return this.t.request({ method: "POST", path: "/model-providers/test", json: nameOrDraft });
735
+ const json = options.testModel === void 0 ? {} : { testModel: options.testModel };
736
+ return this.t.request({ method: "POST", path: `/model-providers/${segment(nameOrDraft)}/test`, json });
737
+ }
738
+ };
739
+ var Agents = class {
740
+ constructor(t) {
741
+ this.t = t;
742
+ }
743
+ t;
744
+ async create(options) {
745
+ return agentHandle(this.t, await this.t.request({ method: "POST", path: "/agents", json: options }));
746
+ }
747
+ async get(id) {
748
+ return agentHandle(this.t, await this.t.request({ method: "GET", path: `/agents/${segment(id)}` }));
749
+ }
750
+ list(options = {}) {
751
+ return new PageList(async (cursor) => {
752
+ const page = await this.t.request({
753
+ method: "GET",
754
+ path: "/agents",
755
+ query: {
756
+ template: options.template,
757
+ metadata: options.metadata,
758
+ limit: options.limit,
759
+ cursor: cursor ?? options.cursor
760
+ }
761
+ });
762
+ return { ...page, data: page.data.map((a) => agentHandle(this.t, a)) };
763
+ });
764
+ }
765
+ async delete(id) {
766
+ await this.t.request({ method: "DELETE", path: `/agents/${segment(id)}`, read: "none" });
767
+ }
768
+ };
769
+ function agentHandle(t, agent) {
770
+ const resources = new AgentResources(t, agent.id);
771
+ const handle = { ...agent };
772
+ for (const [name, value] of Object.entries(resources)) {
773
+ Object.defineProperty(handle, name, { value, enumerable: false });
774
+ }
775
+ return handle;
776
+ }
777
+ var Collection = class {
778
+ constructor(t, base) {
779
+ this.t = t;
780
+ this.base = base;
781
+ }
782
+ t;
783
+ base;
784
+ list(options = {}) {
785
+ return new PageList(
786
+ (cursor) => this.t.request({
787
+ method: "GET",
788
+ path: this.base,
789
+ query: { limit: options.limit, cursor: cursor ?? options.cursor }
790
+ })
791
+ );
792
+ }
793
+ get(name) {
794
+ return this.t.request({ method: "GET", path: `${this.base}/${segment(name)}` });
795
+ }
796
+ /** Adds an entry, or overrides the template's entry of its name. */
797
+ add(entry) {
798
+ return this.t.request({ method: "POST", path: this.base, json: entry });
799
+ }
800
+ update(name, entry) {
801
+ return this.t.request({ method: "PUT", path: `${this.base}/${segment(name)}`, json: entry });
802
+ }
803
+ /** Removes the agent's entry; the template's entry of its name, if any, applies again. */
804
+ async delete(name) {
805
+ await this.t.request({ method: "DELETE", path: `${this.base}/${segment(name)}`, read: "none" });
806
+ }
807
+ };
808
+ var Marketplaces = class extends Collection {
809
+ /** Moves the marketplace to its repository's latest commit. */
810
+ refresh(name) {
811
+ return this.t.request({ method: "POST", path: `${this.base}/${segment(name)}/refresh` });
812
+ }
813
+ };
814
+ var SettingResource = class {
815
+ constructor(t, path) {
816
+ this.t = t;
817
+ this.path = path;
818
+ }
819
+ t;
820
+ path;
821
+ get() {
822
+ return this.t.request({ method: "GET", path: this.path });
823
+ }
824
+ set(value) {
825
+ return this.t.request({ method: "PUT", path: this.path, json: { value } });
826
+ }
827
+ /** Restores the template's value. */
828
+ async delete() {
829
+ return this.t.request({ method: "DELETE", path: this.path });
830
+ }
831
+ };
832
+ var AgentResources = class {
833
+ mcp;
834
+ marketplaces;
835
+ plugins;
836
+ env;
837
+ /** 002's agent.model setting; the agent's model field is the effective model. */
838
+ modelSetting;
839
+ /** Claude Code's small model, a session setting (014#harness-configuration). */
840
+ smallModelSetting;
841
+ /** The value is null when neither the agent nor its template sets one. */
842
+ systemPrompt;
843
+ workflows;
844
+ /** The agent's effective spec as a template document (013#export). */
845
+ export;
846
+ /**
847
+ * Sends text to the agent's default session, its newest session whose defaultSession
848
+ * metadata is "true", created on the first send; resolves with the stored user
849
+ * message, whose sessionId names that session. The sandbox wakes for it.
850
+ */
851
+ send;
852
+ permissions;
853
+ /** The key patterns the agent may send to: its own list, or else the template's (015#allow). */
854
+ outbox;
855
+ memory;
856
+ files;
857
+ sessions;
858
+ constructor(t, agentId) {
859
+ const base = `/agents/${segment(agentId)}`;
860
+ this.mcp = new Collection(t, `${base}/mcp`);
861
+ this.marketplaces = new Marketplaces(t, `${base}/marketplaces`);
862
+ this.plugins = new Collection(t, `${base}/plugins`);
863
+ this.env = new Collection(t, `${base}/env`);
864
+ this.modelSetting = new SettingResource(t, `${base}/model`);
865
+ this.smallModelSetting = new SettingResource(t, `${base}/small-model`);
866
+ this.systemPrompt = new SettingResource(t, `${base}/system-prompt`);
867
+ const workflows = new Collection(t, `${base}/workflows`);
868
+ this.workflows = { list: (o) => workflows.list(o), get: (name) => workflows.get(name) };
869
+ this.export = () => t.request({ method: "GET", path: `${base}/export` });
870
+ this.send = (text) => t.request({ method: "POST", path: `${base}/messages`, json: { text } });
871
+ this.permissions = {
872
+ get: () => t.request({ method: "GET", path: `${base}/permissions` }),
873
+ set: (spec) => t.request({ method: "PUT", path: `${base}/permissions`, json: spec })
874
+ };
875
+ this.outbox = {
876
+ get: () => t.request({ method: "GET", path: `${base}/outbox` }),
877
+ set: (spec) => t.request({ method: "PUT", path: `${base}/outbox`, json: spec }),
878
+ delete: () => t.request({ method: "DELETE", path: `${base}/outbox` })
879
+ };
880
+ const memoryPath = (p) => `${base}/memory/${segment(p, true)}`;
881
+ this.memory = {
882
+ list: () => t.request({ method: "GET", path: `${base}/memory`, timeoutMs: longTimeoutMs }),
883
+ read: (p) => t.request({ method: "GET", path: memoryPath(p), read: "text", timeoutMs: longTimeoutMs }),
884
+ write: (p, content) => t.request({
885
+ method: "PUT",
886
+ path: memoryPath(p),
887
+ body: content,
888
+ contentType: "text/plain; charset=utf-8",
889
+ timeoutMs: longTimeoutMs
890
+ }),
891
+ delete: async (p) => {
892
+ await t.request({ method: "DELETE", path: memoryPath(p), read: "none", timeoutMs: longTimeoutMs });
893
+ }
894
+ };
895
+ const filePath = (p) => `${base}/files/${segment(p, true)}`;
896
+ this.files = {
897
+ list: (dir, o = {}) => t.request({
898
+ method: "GET",
899
+ path: `${base}/files`,
900
+ query: { dir, recursive: o.recursive },
901
+ timeoutMs: longTimeoutMs
902
+ }),
903
+ read: (p) => t.request({ method: "GET", path: filePath(p), read: "bytes", timeoutMs: longTimeoutMs }),
904
+ write: (p, data) => t.request({
905
+ method: "PUT",
906
+ path: filePath(p),
907
+ body: data,
908
+ contentType: "application/octet-stream",
909
+ timeoutMs: longTimeoutMs
910
+ }),
911
+ delete: async (p, o = {}) => {
912
+ await t.request({
913
+ method: "DELETE",
914
+ path: filePath(p),
915
+ query: { recursive: o.recursive },
916
+ read: "none",
917
+ timeoutMs: longTimeoutMs
918
+ });
919
+ }
920
+ };
921
+ this.sessions = {
922
+ create: async (o = {}) => sessionHandle(t, await t.request({ method: "POST", path: `${base}/sessions`, json: o })),
923
+ list: (o = {}) => new PageList(async (cursor) => {
924
+ const page = await t.request({
925
+ method: "GET",
926
+ path: `${base}/sessions`,
927
+ query: { metadata: o.metadata, limit: o.limit, cursor: cursor ?? o.cursor }
928
+ });
929
+ return { ...page, data: page.data.map((s) => sessionHandle(t, s)) };
930
+ })
931
+ };
932
+ }
933
+ };
934
+ function sessionHandle(t, session) {
935
+ const ops = new SessionOperations(t, session.id);
936
+ const handle = { ...session };
937
+ Object.defineProperties(handle, {
938
+ send: { value: ops.send.bind(ops) },
939
+ stop: { value: ops.stop.bind(ops) },
940
+ stream: { value: ops.stream.bind(ops) },
941
+ createToken: { value: ops.createToken.bind(ops) },
942
+ events: { value: ops.events },
943
+ turns: { value: ops.turns }
944
+ });
945
+ return handle;
946
+ }
947
+ var Sessions = class {
948
+ constructor(t) {
949
+ this.t = t;
950
+ }
951
+ t;
952
+ /**
953
+ * Every session of every agent of the project, newest first by creation; agentId keeps
954
+ * one agent's, createdAfter (RFC 3339) those created at or after it, createdBefore those
955
+ * created before it.
956
+ */
957
+ list(options = {}) {
958
+ return new PageList(async (cursor) => {
959
+ const page = await this.t.request({
960
+ method: "GET",
961
+ path: "/sessions",
962
+ query: {
963
+ agentId: options.agentId,
964
+ metadata: options.metadata,
965
+ createdAfter: options.createdAfter,
966
+ createdBefore: options.createdBefore,
967
+ limit: options.limit,
968
+ cursor: cursor ?? options.cursor
969
+ }
970
+ });
971
+ return { ...page, data: page.data.map((s) => sessionHandle(this.t, s)) };
972
+ });
973
+ }
974
+ async get(id) {
975
+ return sessionHandle(this.t, await new SessionOperations(this.t, id).get());
976
+ }
977
+ async delete(id) {
978
+ await this.t.request({ method: "DELETE", path: `/sessions/${segment(id)}`, read: "none" });
979
+ }
980
+ };
981
+ var Connectors = class {
982
+ constructor(t) {
983
+ this.t = t;
984
+ }
985
+ t;
986
+ /** Creates a connector with the sides given; the secret is generated when omitted. */
987
+ async create(spec) {
988
+ return connectorHandle(
989
+ this.t,
990
+ await this.t.request({ method: "POST", path: "/connectors", json: spec })
991
+ );
992
+ }
993
+ /** The connectors, newest first. */
994
+ list(options = {}) {
995
+ return new PageList(async (cursor) => {
996
+ const page = await this.t.request({
997
+ method: "GET",
998
+ path: "/connectors",
999
+ query: { limit: options.limit, cursor: cursor ?? options.cursor }
1000
+ });
1001
+ return { ...page, data: page.data.map((c) => connectorHandle(this.t, c)) };
1002
+ });
1003
+ }
1004
+ /** By ID or by name. */
1005
+ async get(idOrName) {
1006
+ return connectorHandle(
1007
+ this.t,
1008
+ await this.t.request({ method: "GET", path: `/connectors/${segment(idOrName)}` })
1009
+ );
1010
+ }
1011
+ /** Sets which sides exist and the outbound rate limit; a side omitted or null is removed with its function. */
1012
+ async update(id, spec) {
1013
+ return connectorHandle(
1014
+ this.t,
1015
+ await this.t.request({ method: "PUT", path: `/connectors/${segment(id)}`, json: spec })
1016
+ );
1017
+ }
1018
+ /** Deletes its functions first; its URL answers 404 at once, and its deliveries and outbox messages are removed. */
1019
+ async delete(id) {
1020
+ await this.t.request({ method: "DELETE", path: `/connectors/${segment(id)}`, read: "none" });
1021
+ }
1022
+ /** Stock function code per side, in both runtimes, with the params each reads (015#presets). */
1023
+ async functionPresets() {
1024
+ const out = await this.t.request({
1025
+ method: "GET",
1026
+ path: "/connectors/function-presets"
1027
+ });
1028
+ return out.presets;
1029
+ }
1030
+ };
1031
+ var ConnectorResources = class {
1032
+ /** The connector's named secrets, whose values only these return; name defaults to "default". */
1033
+ secret;
1034
+ /** The code each side runs: inbound on every request, outbound on every message sent. */
1035
+ functions;
1036
+ deliveries;
1037
+ constructor(t, connectorId) {
1038
+ const base = `/connectors/${segment(connectorId)}`;
1039
+ this.secret = {
1040
+ get: (o = {}) => t.request({ method: "GET", path: `${base}/secret`, query: { name: o.name } }),
1041
+ rotate: (o = {}) => t.request({ method: "POST", path: `${base}/secret`, json: o }),
1042
+ delete: async (o) => {
1043
+ await t.request({ method: "DELETE", path: `${base}/secret`, query: { name: o.name }, read: "none" });
1044
+ }
1045
+ };
1046
+ const fn = (side) => `${base}/functions/${segment(side)}`;
1047
+ this.functions = {
1048
+ get: (side) => t.request({ method: "GET", path: fn(side) }),
1049
+ set: (side, spec) => t.request({ method: "PUT", path: fn(side), json: spec }),
1050
+ delete: async (side) => {
1051
+ await t.request({ method: "DELETE", path: fn(side), read: "none" });
1052
+ },
1053
+ test: (side, request) => t.request({ method: "POST", path: `${fn(side)}/test`, json: request })
1054
+ };
1055
+ this.deliveries = {
1056
+ list: (o = {}) => new PageList(
1057
+ (cursor) => t.request({
1058
+ method: "GET",
1059
+ path: `${base}/deliveries`,
1060
+ query: { status: o.status, limit: o.limit, cursor: cursor ?? o.cursor }
1061
+ })
1062
+ ),
1063
+ get: (id) => t.request({ method: "GET", path: `${base}/deliveries/${segment(id)}` }),
1064
+ replay: (id) => t.request({ method: "POST", path: `${base}/deliveries/${segment(id)}/replay` })
1065
+ };
1066
+ }
1067
+ };
1068
+ function connectorHandle(t, connector) {
1069
+ const resources = new ConnectorResources(t, connector.id);
1070
+ const handle = { ...connector };
1071
+ for (const [name, value] of Object.entries(resources)) {
1072
+ Object.defineProperty(handle, name, { value, enumerable: false });
1073
+ }
1074
+ return handle;
1075
+ }
1076
+ var Outbox = class {
1077
+ constructor(t) {
1078
+ this.t = t;
1079
+ }
1080
+ t;
1081
+ /** Newest first by createdAt; every filter given must match. */
1082
+ list(options = {}) {
1083
+ return new PageList(
1084
+ (cursor) => this.t.request({
1085
+ method: "GET",
1086
+ path: "/outbox",
1087
+ query: {
1088
+ connectorId: options.connectorId,
1089
+ sessionId: options.sessionId,
1090
+ key: options.key,
1091
+ status: options.status,
1092
+ limit: options.limit,
1093
+ cursor: cursor ?? options.cursor
1094
+ }
1095
+ })
1096
+ );
1097
+ }
1098
+ get(id) {
1099
+ return this.t.request({ method: "GET", path: `/outbox/${segment(id)}` });
1100
+ }
1101
+ /** Queues a failed message again with the same ID. */
1102
+ retry(id) {
1103
+ return this.t.request({ method: "POST", path: `/outbox/${segment(id)}/retry` });
1104
+ }
1105
+ };
1106
+ export {
1107
+ AgentResources,
1108
+ Agents,
1109
+ Collection,
1110
+ ConnectorResources,
1111
+ Connectors,
1112
+ EventStream,
1113
+ Marketplaces,
1114
+ ModelProviders,
1115
+ Models,
1116
+ Outbox,
1117
+ Paddock,
1118
+ PaddockConnectionError,
1119
+ PaddockError,
1120
+ PaddockTimeoutError,
1121
+ PageList,
1122
+ Sessions,
1123
+ SettingResource,
1124
+ Templates,
1125
+ isKnownMessageKind,
1126
+ isStreamingMessageEvent,
1127
+ version
1128
+ };