@spencerboucher/switchyard-client 0.0.0-stage → 0.14.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/dist/index.js ADDED
@@ -0,0 +1,3842 @@
1
+ // packages/client/dist/api.js
2
+ var ApiRequestError = class extends Error {
3
+ status;
4
+ code;
5
+ details;
6
+ constructor(status, code, message, details) {
7
+ super(message);
8
+ this.status = status;
9
+ this.code = code;
10
+ this.details = details;
11
+ this.name = "ApiRequestError";
12
+ }
13
+ };
14
+ var ApiClient = class {
15
+ baseUrl;
16
+ credential;
17
+ doFetch;
18
+ constructor(opts) {
19
+ this.baseUrl = opts.coordinatorUrl.replace(/\/+$/, "");
20
+ this.credential = opts.credential;
21
+ this.doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
22
+ }
23
+ async request(method, path2, body, options) {
24
+ const headers = { accept: "application/json" };
25
+ if (this.credential)
26
+ headers.authorization = `Bearer ${this.credential}`;
27
+ if (body !== void 0)
28
+ headers["content-type"] = "application/json";
29
+ let res;
30
+ try {
31
+ res = await this.doFetch(`${this.baseUrl}${path2}`, {
32
+ method,
33
+ headers,
34
+ signal: options?.signal,
35
+ body: body === void 0 ? void 0 : JSON.stringify(body)
36
+ });
37
+ } catch (err) {
38
+ if (options?.signal?.aborted || err instanceof Error && err.name === "AbortError")
39
+ throw err;
40
+ throw new ApiRequestError(0, "host_unreachable", `Cannot reach coordinator ${this.baseUrl}: ${err.message}`);
41
+ }
42
+ const text = await res.text();
43
+ let json = null;
44
+ if (text) {
45
+ try {
46
+ json = JSON.parse(text);
47
+ } catch {
48
+ if (res.ok)
49
+ throw new ApiRequestError(res.status, "invalid_response", `Invalid JSON for ${method} ${path2}`);
50
+ }
51
+ }
52
+ if (!res.ok) {
53
+ const e = json?.error;
54
+ throw new ApiRequestError(res.status, e?.code ?? (res.status === 401 ? "unauthorized" : res.status === 403 ? "forbidden" : "internal"), e?.message ?? `HTTP ${res.status} for ${method} ${path2}`, e?.details);
55
+ }
56
+ return json;
57
+ }
58
+ get(path2, options) {
59
+ return this.request("GET", path2, void 0, options);
60
+ }
61
+ post(path2, body = {}, options) {
62
+ return this.request("POST", path2, body, options);
63
+ }
64
+ };
65
+
66
+ // packages/protocol/dist/adapter-preview.js
67
+ import { z as z7 } from "zod";
68
+
69
+ // packages/protocol/dist/contributions.js
70
+ import { z as z3 } from "zod";
71
+
72
+ // packages/protocol/dist/ui.js
73
+ import { z as z2 } from "zod";
74
+
75
+ // packages/protocol/dist/errors.js
76
+ import { z } from "zod";
77
+ var ERROR_CODES = [
78
+ "unauthorized",
79
+ "forbidden",
80
+ "not_found",
81
+ "invalid_request",
82
+ "conflict",
83
+ "already_answered",
84
+ "stale_control",
85
+ "host_unreachable",
86
+ "pi_incompatible",
87
+ "native_session_missing",
88
+ "invalid_transition",
89
+ "dependency_cycle",
90
+ "workspace_dirty",
91
+ "workspace_unmerged",
92
+ "workspace_active_sessions",
93
+ "branch_invalid",
94
+ "path_collision",
95
+ "not_a_git_repo",
96
+ "repo_mismatch",
97
+ "enrollment_expired",
98
+ "enrollment_used",
99
+ "device_revoked",
100
+ "unsupported_capability",
101
+ "too_large",
102
+ "ui_tree_too_large",
103
+ "timeout",
104
+ "rate_limited",
105
+ "internal"
106
+ ];
107
+ var ErrorCode = z.enum(ERROR_CODES);
108
+ var ErrorBody = z.object({
109
+ code: ErrorCode,
110
+ message: z.string(),
111
+ details: z.unknown().optional()
112
+ });
113
+ var ApiError = z.object({ error: ErrorBody });
114
+ var SwitchyardError = class extends Error {
115
+ code;
116
+ details;
117
+ constructor(code, message, details) {
118
+ super(message);
119
+ this.name = "SwitchyardError";
120
+ this.code = code;
121
+ this.details = details;
122
+ }
123
+ toBody() {
124
+ return this.details === void 0 ? { code: this.code, message: this.message } : { code: this.code, message: this.message, details: this.details };
125
+ }
126
+ };
127
+
128
+ // packages/protocol/dist/ui.js
129
+ var ToneSchema = z2.enum(["default", "muted", "success", "warning", "danger"]);
130
+ var ShowIfSchema = z2.object({ field: z2.string(), values: z2.array(z2.string()) });
131
+ var OptionSchema = z2.object({
132
+ value: z2.string(),
133
+ label: z2.string(),
134
+ description: z2.string().optional(),
135
+ preview: z2.string().optional()
136
+ });
137
+ var AllowOther = z2.object({ label: z2.string(), placeholder: z2.string().optional() });
138
+ var FieldSchema = z2.discriminatedUnion("kind", [
139
+ z2.object({
140
+ kind: z2.literal("select"),
141
+ name: z2.string(),
142
+ label: z2.string(),
143
+ options: z2.array(OptionSchema),
144
+ allowOther: AllowOther.optional(),
145
+ showIf: ShowIfSchema.optional()
146
+ }),
147
+ z2.object({
148
+ kind: z2.literal("multiselect"),
149
+ name: z2.string(),
150
+ label: z2.string(),
151
+ options: z2.array(OptionSchema),
152
+ allowOther: AllowOther.optional(),
153
+ min: z2.number().int().min(0).optional(),
154
+ max: z2.number().int().min(1).optional(),
155
+ showIf: ShowIfSchema.optional()
156
+ }),
157
+ z2.object({
158
+ kind: z2.literal("text"),
159
+ name: z2.string(),
160
+ label: z2.string(),
161
+ placeholder: z2.string().optional(),
162
+ multiline: z2.boolean().optional(),
163
+ prefill: z2.string().optional(),
164
+ showIf: ShowIfSchema.optional()
165
+ })
166
+ ]);
167
+ var RefSchema = z2.discriminatedUnion("kind", [
168
+ z2.object({ kind: z2.literal("file"), path: z2.string() }),
169
+ z2.object({ kind: z2.literal("session"), sessionId: z2.string() }),
170
+ z2.object({ kind: z2.literal("task"), taskId: z2.string() }),
171
+ z2.object({ kind: z2.literal("native_session"), hostId: z2.string(), sessionFile: z2.string() })
172
+ ]);
173
+ var UINodeSchema = z2.lazy(() => z2.discriminatedUnion("t", [
174
+ z2.object({ t: z2.literal("text"), text: z2.string(), tone: ToneSchema.optional() }),
175
+ z2.object({ t: z2.literal("markdown"), text: z2.string() }),
176
+ z2.object({ t: z2.literal("code"), text: z2.string(), lang: z2.string().optional() }),
177
+ z2.object({ t: z2.literal("diff"), patch: z2.string() }),
178
+ z2.object({
179
+ t: z2.literal("list"),
180
+ items: z2.array(UINodeSchema),
181
+ ordered: z2.boolean().optional()
182
+ }),
183
+ z2.object({
184
+ t: z2.literal("table"),
185
+ columns: z2.array(z2.string()),
186
+ rows: z2.array(z2.array(z2.string()))
187
+ }),
188
+ z2.object({
189
+ t: z2.literal("section"),
190
+ title: z2.string().optional(),
191
+ collapsible: z2.boolean().optional(),
192
+ children: z2.array(UINodeSchema)
193
+ }),
194
+ z2.object({
195
+ t: z2.literal("tabs"),
196
+ tabs: z2.array(z2.object({ id: z2.string(), label: z2.string(), children: z2.array(UINodeSchema) }))
197
+ }),
198
+ z2.object({
199
+ t: z2.literal("progress"),
200
+ label: z2.string(),
201
+ value: z2.number().min(0).max(1).optional(),
202
+ status: z2.enum(["running", "ok", "error"]).optional()
203
+ }),
204
+ z2.object({ t: z2.literal("ref"), ref: RefSchema, label: z2.string() }),
205
+ z2.object({
206
+ t: z2.literal("form"),
207
+ formId: z2.string(),
208
+ fields: z2.array(FieldSchema),
209
+ submitLabel: z2.string(),
210
+ cancelLabel: z2.string().optional()
211
+ }),
212
+ z2.object({
213
+ t: z2.literal("confirm"),
214
+ message: z2.string(),
215
+ confirmLabel: z2.string(),
216
+ cancelLabel: z2.string(),
217
+ destructive: z2.boolean().optional()
218
+ }),
219
+ z2.object({
220
+ t: z2.literal("actions"),
221
+ actions: z2.array(z2.object({
222
+ id: z2.string(),
223
+ label: z2.string(),
224
+ tone: z2.enum(["default", "primary", "danger"]).optional()
225
+ }))
226
+ })
227
+ ]));
228
+ var UI_MAX_DEPTH = 12;
229
+ var UI_MAX_NODES = 2e3;
230
+ function children(node) {
231
+ switch (node.t) {
232
+ case "list":
233
+ return node.items;
234
+ case "section":
235
+ return node.children;
236
+ case "tabs":
237
+ return node.tabs.flatMap((tab) => tab.children);
238
+ default:
239
+ return [];
240
+ }
241
+ }
242
+ function validateUINode(input) {
243
+ const node = UINodeSchema.parse(input);
244
+ let count = 0;
245
+ const walk = (n, depth) => {
246
+ count++;
247
+ if (depth > UI_MAX_DEPTH) {
248
+ throw new SwitchyardError("ui_tree_too_large", `UI tree deeper than ${UI_MAX_DEPTH}`);
249
+ }
250
+ if (count > UI_MAX_NODES) {
251
+ throw new SwitchyardError("ui_tree_too_large", `UI tree has more than ${UI_MAX_NODES} nodes`);
252
+ }
253
+ for (const c of children(n))
254
+ walk(c, depth + 1);
255
+ };
256
+ walk(node, 1);
257
+ return node;
258
+ }
259
+ var FormValueSchema = z2.union([
260
+ z2.string(),
261
+ z2.array(z2.string()),
262
+ z2.object({ other: z2.string() })
263
+ ]);
264
+ var InteractionResponseSchema = z2.discriminatedUnion("kind", [
265
+ z2.object({ kind: z2.literal("form"), values: z2.record(z2.string(), FormValueSchema) }),
266
+ z2.object({ kind: z2.literal("confirm"), confirmed: z2.boolean() }),
267
+ z2.object({ kind: z2.literal("action"), actionId: z2.string() }),
268
+ z2.object({ kind: z2.literal("cancel") })
269
+ ]);
270
+
271
+ // packages/protocol/dist/contributions.js
272
+ var ContributionPlacement = z3.enum([
273
+ "sidebar.header",
274
+ "sidebar.footer",
275
+ "session.panel",
276
+ "composer.pill",
277
+ "palette.item",
278
+ "slash.command"
279
+ ]);
280
+ var Id = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
281
+ var ActionId = z3.string().min(1).max(200);
282
+ var Keywords = z3.array(z3.string().min(1).max(80)).max(20);
283
+ var Common = {
284
+ placement: ContributionPlacement,
285
+ order: z3.number().int().min(-1e3).max(1e3).optional(),
286
+ actionId: ActionId.optional()
287
+ };
288
+ var ContributionDescriptor = z3.object({
289
+ id: Id,
290
+ ...Common,
291
+ name: z3.string().regex(/^[a-z][a-z0-9-]{0,39}$/).optional(),
292
+ keywords: Keywords.optional()
293
+ }).strict().superRefine((v, ctx) => {
294
+ if (v.placement === "slash.command" && (!v.name || !v.actionId)) {
295
+ ctx.addIssue({ code: "custom", message: "Slash commands need name and actionId" });
296
+ }
297
+ if (v.placement === "palette.item" && !v.actionId) {
298
+ ctx.addIssue({ code: "custom", message: "Palette items need actionId" });
299
+ }
300
+ if (v.placement !== "slash.command" && v.name !== void 0) {
301
+ ctx.addIssue({ code: "custom", message: "Only slash commands have names" });
302
+ }
303
+ if (v.placement !== "palette.item" && v.keywords !== void 0) {
304
+ ctx.addIssue({ code: "custom", message: "Only palette items have keywords" });
305
+ }
306
+ if (v.placement === "composer.pill" && v.actionId !== void 0) {
307
+ ctx.addIssue({ code: "custom", message: "Composer pills are not interactive" });
308
+ }
309
+ });
310
+ var ContributionInput = z3.object({
311
+ ...Common,
312
+ title: z3.string().min(1).max(100),
313
+ node: z3.unknown(),
314
+ mobileFallback: z3.string().min(1).max(2e3),
315
+ state: z3.unknown().optional(),
316
+ name: z3.string().regex(/^[a-z][a-z0-9-]{0,39}$/).optional(),
317
+ keywords: Keywords.optional()
318
+ }).strict();
319
+ function boundContributionJson(value, maxBytes = 256 * 1024) {
320
+ const stack = [{ value, depth: 0 }];
321
+ const ancestors = /* @__PURE__ */ new Set();
322
+ let count = 0;
323
+ let characterCount = 0;
324
+ while (stack.length) {
325
+ const { value: v, depth, leave } = stack.pop();
326
+ if (leave) {
327
+ ancestors.delete(v);
328
+ continue;
329
+ }
330
+ if (++count > 2e4 || depth > 32)
331
+ throw new Error("Contribution exceeds complexity limit");
332
+ if (typeof v === "string") {
333
+ characterCount += v.length;
334
+ if (characterCount > maxBytes)
335
+ throw new Error("Contribution exceeds size limit");
336
+ }
337
+ if (v === null || typeof v === "string" || typeof v === "boolean")
338
+ continue;
339
+ if (typeof v === "number" && Number.isFinite(v))
340
+ continue;
341
+ if (!v || typeof v !== "object")
342
+ throw new Error("Contribution contains a non-JSON value");
343
+ if (ancestors.has(v))
344
+ throw new Error("Contribution contains a cycle");
345
+ ancestors.add(v);
346
+ stack.push({ value: v, depth, leave: true });
347
+ if (Array.isArray(v)) {
348
+ for (const child of v)
349
+ stack.push({ value: child, depth: depth + 1 });
350
+ } else {
351
+ if (Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) {
352
+ throw new Error("Contribution contains a non-plain object");
353
+ }
354
+ for (const [key, child] of Object.entries(v)) {
355
+ characterCount += key.length;
356
+ if (characterCount > maxBytes)
357
+ throw new Error("Contribution exceeds size limit");
358
+ stack.push({ value: child, depth: depth + 1 });
359
+ }
360
+ }
361
+ }
362
+ const json = JSON.stringify(value);
363
+ let bytes3 = 0;
364
+ for (const char of json) {
365
+ const code = char.codePointAt(0);
366
+ bytes3 += code < 128 ? 1 : code < 2048 ? 2 : code < 65536 ? 3 : 4;
367
+ if (bytes3 > maxBytes)
368
+ throw new Error("Contribution exceeds size limit");
369
+ }
370
+ }
371
+ function hasInteractive(node) {
372
+ if (node.t === "form" || node.t === "confirm")
373
+ return true;
374
+ if (node.t === "section")
375
+ return node.children.some(hasInteractive);
376
+ if (node.t === "list")
377
+ return node.items.some(hasInteractive);
378
+ if (node.t === "tabs")
379
+ return node.tabs.some((t) => t.children.some(hasInteractive));
380
+ return false;
381
+ }
382
+ function validateContribution(id, input) {
383
+ Id.parse(id);
384
+ boundContributionJson(input);
385
+ const parsed = ContributionInput.parse(input);
386
+ const node = validateUINode(parsed.node);
387
+ const { title, mobileFallback, state, node: _node, ...meta } = parsed;
388
+ const descriptor = ContributionDescriptor.parse({ ...meta, id });
389
+ if (descriptor.placement === "slash.command" && node.t !== "form") {
390
+ throw new Error("Slash command content must be a form");
391
+ }
392
+ if (descriptor.placement === "composer.pill" && node.t !== "text" && node.t !== "progress") {
393
+ throw new Error("Composer pill content must be text or progress");
394
+ }
395
+ if (descriptor.placement !== "session.panel" && state !== void 0) {
396
+ throw new Error("Only session panels accept renderer state");
397
+ }
398
+ if (state !== void 0)
399
+ boundContributionJson(state, 64 * 1024);
400
+ if (hasInteractive(node) && !descriptor.actionId) {
401
+ throw new Error("Interactive content requires actionId");
402
+ }
403
+ return { descriptor, title, node, mobileFallback, ...state === void 0 ? {} : { state } };
404
+ }
405
+ function validateContributionCard(node) {
406
+ boundContributionJson(node);
407
+ const checked = validateUINode(node);
408
+ if (hasInteractive(checked))
409
+ throw new Error("Timeline cards cannot contain forms or confirms");
410
+ return checked;
411
+ }
412
+ function contributionSlot(id) {
413
+ return `@slot/${Id.parse(id)}`;
414
+ }
415
+
416
+ // packages/protocol/dist/entities.js
417
+ import { z as z6 } from "zod";
418
+
419
+ // packages/protocol/dist/github.js
420
+ import { z as z4 } from "zod";
421
+ var Id2 = z4.string().min(1).max(200);
422
+ var Instant = z4.string().refine((s) => {
423
+ try {
424
+ return new Date(s).toISOString() === s;
425
+ } catch {
426
+ return false;
427
+ }
428
+ });
429
+ var positive = z4.number().int().safe().positive();
430
+ var nonnegative = z4.number().int().safe().nonnegative();
431
+ var reason = z4.string().min(1).max(2e3);
432
+ var hash = z4.string().regex(/^[0-9a-f]{64}$/);
433
+ var actionsId = z4.string().regex(/^[1-9][0-9]{0,19}$/);
434
+ var bytes = (s) => new TextEncoder().encode(s).length;
435
+ var displayUrl = z4.string().max(4096).refine((s) => {
436
+ try {
437
+ const u = new URL(s);
438
+ return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password;
439
+ } catch {
440
+ return false;
441
+ }
442
+ });
443
+ var githubUrl = displayUrl.refine((s) => {
444
+ try {
445
+ const u = new URL(s);
446
+ return u.protocol === "https:" && u.hostname === "github.com" && !u.port && /^https:\/\/github\.com(?:[/?#]|$)/i.test(s);
447
+ } catch {
448
+ return false;
449
+ }
450
+ });
451
+ var GitHubRepository = z4.string().regex(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?\/(?!\.{1,2}$)[A-Za-z0-9_.-]{1,100}$/);
452
+ var issuePath = /^[hH][tT][tT][pP][sS]:\/\/[gG][iI][tT][hH][uU][bB]\.[cC][oO][mM]\/([^/]+)\/([^/]+)\/issues\/([1-9][0-9]*)$/;
453
+ var GitHubIssueUrl = z4.string().trim().transform((raw, ctx) => {
454
+ const match = issuePath.exec(raw);
455
+ const number = match ? Number(match[3]) : NaN;
456
+ if (!match || !GitHubRepository.safeParse(`${match[1]}/${match[2]}`).success || !Number.isSafeInteger(number)) {
457
+ ctx.addIssue({ code: "custom", message: "Invalid GitHub issue URL" });
458
+ return z4.NEVER;
459
+ }
460
+ return `https://github.com/${match[1]}/${match[2]}/issues/${number}`;
461
+ });
462
+ function issueParts(url) {
463
+ const match = issuePath.exec(url);
464
+ return { repository: `${match[1]}/${match[2]}`, number: Number(match[3]) };
465
+ }
466
+ function issuePrompt(url) {
467
+ return `${url}
468
+
469
+ Read it with \`gh issue view ${url}\`.`;
470
+ }
471
+ var GitHubIssueIdentity = z4.object({
472
+ repository: GitHubRepository,
473
+ number: positive,
474
+ url: GitHubIssueUrl
475
+ }).strict().refine((v) => {
476
+ const parts = issueParts(v.url);
477
+ return v.repository === parts.repository && v.number === parts.number;
478
+ });
479
+ var GitHubIssue = z4.object({
480
+ repository: GitHubRepository,
481
+ number: positive,
482
+ url: GitHubIssueUrl,
483
+ launchPrompt: z4.string()
484
+ }).strict().refine((v) => {
485
+ const parts = issueParts(v.url);
486
+ return v.repository === parts.repository && v.number === parts.number && v.launchPrompt === issuePrompt(v.url);
487
+ });
488
+ function githubIssueFromUrl(raw) {
489
+ const url = GitHubIssueUrl.parse(raw);
490
+ return { ...issueParts(url), url, launchPrompt: issuePrompt(url) };
491
+ }
492
+ var GitHubSha = z4.string().regex(/^[0-9a-f]{40}$/);
493
+ var prUrl = githubUrl.refine((s) => {
494
+ try {
495
+ const u = new URL(s);
496
+ return /^\/[^/]+\/[^/]+\/pull\/[1-9][0-9]*$/.test(u.pathname) && !u.search && !u.hash;
497
+ } catch {
498
+ return false;
499
+ }
500
+ });
501
+ function matchesPr(url, repository, number) {
502
+ try {
503
+ const u = new URL(url);
504
+ return u.pathname.toLowerCase() === `/${repository}/pull/${number}`.toLowerCase();
505
+ } catch {
506
+ return false;
507
+ }
508
+ }
509
+ var HostGitHub = z4.object({ available: z4.boolean(), reason: reason.nullable() }).strict().refine((v) => v.available === (v.reason === null));
510
+ var GitHubCheck = z4.object({
511
+ id: hash,
512
+ name: z4.string().min(1).max(300),
513
+ state: z4.string().min(1).max(100),
514
+ bucket: z4.enum(["pass", "fail", "pending", "skipping", "cancel", "unknown"]),
515
+ link: displayUrl.nullable(),
516
+ workflow: z4.string().max(300).nullable(),
517
+ event: z4.string().max(100).nullable(),
518
+ startedAt: Instant.nullable(),
519
+ completedAt: Instant.nullable(),
520
+ description: z4.string().max(2e3).nullable(),
521
+ actionsJob: z4.object({ runId: actionsId, jobId: actionsId, attempt: positive }).strict().nullable()
522
+ }).strict();
523
+ var GitHubComment = z4.object({
524
+ id: Id2,
525
+ author: z4.string().min(1).max(200).nullable(),
526
+ body: z4.string().refine((v) => [...v].length <= 8e3),
527
+ bodyTruncated: z4.boolean(),
528
+ url: githubUrl,
529
+ createdAt: Instant.nullable()
530
+ }).strict();
531
+ var GitHubThread = z4.object({
532
+ id: Id2,
533
+ isResolved: z4.literal(false),
534
+ isOutdated: z4.boolean(),
535
+ path: z4.string().max(8192).nullable(),
536
+ line: positive.nullable(),
537
+ startLine: positive.nullable(),
538
+ side: z4.enum(["LEFT", "RIGHT"]).nullable(),
539
+ comments: z4.array(GitHubComment).max(10),
540
+ commentsComplete: z4.boolean()
541
+ }).strict();
542
+ var GitHubPullRequest = z4.object({
543
+ nodeId: z4.string().min(1).optional(),
544
+ number: positive,
545
+ url: prUrl,
546
+ title: z4.string().min(1).max(1e3),
547
+ state: z4.enum(["OPEN", "CLOSED", "MERGED"]),
548
+ isDraft: z4.boolean(),
549
+ headRefName: z4.string().min(1).max(255),
550
+ headRefOid: GitHubSha,
551
+ headRepository: GitHubRepository.nullable(),
552
+ baseRefName: z4.string().min(1).max(255),
553
+ mergeable: z4.string().min(1).max(100),
554
+ mergeStateStatus: z4.string().min(1).max(100),
555
+ reviewDecision: z4.enum(["APPROVED", "REVIEW_REQUIRED", "CHANGES_REQUESTED"]).nullable(),
556
+ mergeQueueEnabled: z4.boolean(),
557
+ inMergeQueue: z4.boolean(),
558
+ autoMergeEnabled: z4.boolean(),
559
+ squashMergeAllowed: z4.boolean()
560
+ }).strict().refine((v) => {
561
+ try {
562
+ return new URL(v.url).pathname.endsWith(`/pull/${v.number}`);
563
+ } catch {
564
+ return false;
565
+ }
566
+ });
567
+ var WorkspaceGitHub = z4.object({
568
+ repository: GitHubRepository.nullable(),
569
+ headRepository: GitHubRepository.nullable(),
570
+ branch: z4.string().min(1).max(255).nullable(),
571
+ fetchedAt: Instant.nullable(),
572
+ attemptedAt: Instant,
573
+ status: z4.enum(["ready", "unavailable", "error", "ambiguous"]),
574
+ reason: reason.nullable(),
575
+ pullRequest: GitHubPullRequest.nullable(),
576
+ checks: z4.array(GitHubCheck).max(500),
577
+ checksComplete: z4.boolean(),
578
+ threads: z4.array(GitHubThread).max(500),
579
+ threadsComplete: z4.boolean(),
580
+ truncated: z4.boolean()
581
+ }).strict().refine((v) => {
582
+ if (bytes(JSON.stringify(v)) > 512 * 1024 || new Set(v.checks.map((c) => c.id)).size !== v.checks.length)
583
+ return false;
584
+ if (v.pullRequest && (!v.repository || !matchesPr(v.pullRequest.url, v.repository, v.pullRequest.number)))
585
+ return false;
586
+ if (v.threads.some((t) => !t.commentsComplete || t.comments.some((c) => c.bodyTruncated)) && (v.threadsComplete || !v.truncated))
587
+ return false;
588
+ if (v.status !== "ready")
589
+ return v.reason !== null && !v.checksComplete && !v.threadsComplete;
590
+ return v.reason === null && v.fetchedAt !== null && v.repository !== null && v.headRepository !== null && v.branch !== null && (v.pullRequest !== null || v.checks.length === 0 && v.threads.length === 0 && v.checksComplete && v.threadsComplete);
591
+ });
592
+ var GitHubViewResult = z4.object({ github: HostGitHub, snapshot: WorkspaceGitHub }).strict();
593
+ var GitHubViewResponse = z4.object({ github: HostGitHub.nullable(), snapshot: WorkspaceGitHub.nullable() }).strict();
594
+ function lineCount(s) {
595
+ if (!s)
596
+ return 0;
597
+ const lines = s.replace(/\r\n/g, "\n").split("\n");
598
+ if (lines[lines.length - 1] === "")
599
+ lines.pop();
600
+ return lines.length;
601
+ }
602
+ var GitHubJobLog = z4.object({
603
+ checkId: hash,
604
+ name: z4.string().min(1).max(300),
605
+ url: displayUrl.nullable(),
606
+ runId: actionsId.nullable(),
607
+ jobId: actionsId.nullable(),
608
+ attempt: positive.nullable(),
609
+ status: z4.enum([
610
+ "available",
611
+ "unmapped",
612
+ "incomplete",
613
+ "expired",
614
+ "forbidden",
615
+ "timeout",
616
+ "error"
617
+ ]),
618
+ outputTail: z4.string().nullable(),
619
+ lineCount: nonnegative.max(150),
620
+ truncated: z4.boolean(),
621
+ reason: reason.nullable()
622
+ }).strict().refine((v) => v.status === "available" ? v.runId !== null && v.jobId !== null && v.attempt !== null && v.outputTail !== null && bytes(v.outputTail) <= 65536 && lineCount(v.outputTail) === v.lineCount && v.reason === null : v.outputTail === null && v.lineCount === 0 && v.reason !== null);
623
+ var GitHubLogs = z4.object({
624
+ github: HostGitHub,
625
+ repository: GitHubRepository,
626
+ number: positive,
627
+ headOid: GitHubSha,
628
+ fetchedAt: Instant,
629
+ status: z4.enum(["ready", "unavailable", "error"]),
630
+ reason: reason.nullable(),
631
+ jobs: z4.array(GitHubJobLog).max(10),
632
+ complete: z4.boolean(),
633
+ truncated: z4.boolean(),
634
+ omittedJobs: nonnegative.nullable()
635
+ }).strict().refine((v) => bytes(JSON.stringify(v)) <= 1024 * 1024 && (v.status === "ready" ? v.github.available && v.reason === null && (!v.complete || v.omittedJobs === 0 && v.jobs.every((j) => j.status === "available")) : v.reason !== null && v.jobs.length === 0 && !v.complete));
636
+ var GitHubLogsRequest = z4.object({ expectedHeadOid: GitHubSha }).strict();
637
+ var GitHubMergeRequest = z4.object({ expectedHeadOid: GitHubSha }).strict();
638
+ var mergeFields = {
639
+ github: HostGitHub,
640
+ repository: GitHubRepository,
641
+ number: positive,
642
+ url: prUrl,
643
+ expectedHeadOid: GitHubSha
644
+ };
645
+ var GitHubMergeResult = z4.discriminatedUnion("status", [
646
+ z4.object({
647
+ status: z4.literal("merged"),
648
+ ...mergeFields,
649
+ mergeCommitOid: GitHubSha.nullable(),
650
+ confirmedAt: Instant
651
+ }).strict(),
652
+ z4.object({
653
+ status: z4.literal("outcome_unknown"),
654
+ ...mergeFields,
655
+ reason,
656
+ attemptedAt: Instant
657
+ }).strict()
658
+ ]).refine((v) => matchesPr(v.url, v.repository, v.number));
659
+ var path = z4.string().min(1).max(8192);
660
+ var GitHubHostViewRequest = z4.object({ path }).strict();
661
+ var GitHubHostLogsRequest = z4.object({ path, repository: GitHubRepository, number: positive, expectedHeadOid: GitHubSha }).strict();
662
+ var GitHubHostMergeRequest = GitHubHostLogsRequest.extend({
663
+ expectedPullRequestNodeId: z4.string().min(1)
664
+ });
665
+
666
+ // packages/protocol/dist/policies.js
667
+ import { z as z5 } from "zod";
668
+ var Id3 = z5.string().min(1).max(200);
669
+ var Revision = z5.number().int().safe().min(1);
670
+ var Instant2 = z5.string().refine((s) => {
671
+ try {
672
+ return new Date(s).toISOString() === s;
673
+ } catch {
674
+ return false;
675
+ }
676
+ });
677
+ var Text = z5.string().max(4e3);
678
+ var Reason = Text.min(1);
679
+ var Fingerprint = z5.string().regex(/^[0-9a-f]{64}$/);
680
+ var forbidden = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
681
+ var bytes2 = (s) => new TextEncoder().encode(s).length;
682
+ function validJson(value, depth = 0, seen = /* @__PURE__ */ new Set()) {
683
+ if (depth > 20)
684
+ return false;
685
+ if (value === null || typeof value === "string" || typeof value === "boolean")
686
+ return true;
687
+ if (typeof value === "number")
688
+ return Number.isFinite(value) && (!Number.isInteger(value) || Number.isSafeInteger(value));
689
+ if (typeof value !== "object" || seen.has(value))
690
+ return false;
691
+ const prototype = Object.getPrototypeOf(value);
692
+ if (Array.isArray(value) ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null)
693
+ return false;
694
+ seen.add(value);
695
+ try {
696
+ const descriptors = Object.getOwnPropertyDescriptors(value);
697
+ const keys = Reflect.ownKeys(descriptors);
698
+ if (Array.isArray(value) && keys.length !== value.length + 1)
699
+ return false;
700
+ return keys.every((key) => {
701
+ if (typeof key !== "string" || forbidden.has(key))
702
+ return false;
703
+ if (Array.isArray(value)) {
704
+ if (key === "length")
705
+ return true;
706
+ if (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length)
707
+ return false;
708
+ }
709
+ const descriptor = descriptors[key];
710
+ return descriptor.enumerable === true && "value" in descriptor && validJson(descriptor.value, depth + 1, seen);
711
+ });
712
+ } finally {
713
+ seen.delete(value);
714
+ }
715
+ }
716
+ var JsonObject = z5.custom((v) => !!v && typeof v === "object" && !Array.isArray(v) && validJson(v));
717
+ var CompletedUsageWatermark = z5.object({ runtimeId: Id3, settleSeq: Revision }).strict();
718
+ var scopeShape = { scope: z5.enum(["session", "profile", "server"]), scopeId: Id3.nullable() };
719
+ var scopeValid = (v) => v.scope === "server" === (v.scopeId === null);
720
+ var PolicyPhase = z5.enum(["tool_call", "request"]);
721
+ var PolicyVerdict = z5.enum(["ALLOW", "ASK", "DENY"]);
722
+ var PolicyRequestAction = z5.enum([
723
+ "task.create",
724
+ "message.send",
725
+ "inbox.read",
726
+ "run.continue"
727
+ ]);
728
+ var PolicyScope = scopeShape.scope;
729
+ var PolicyCounterMap = z5.record(z5.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/).refine((k) => !forbidden.has(k)), z5.number().int().safe()).refine((v) => Object.keys(v).length <= 64);
730
+ var phases = z5.array(PolicyPhase).min(1).max(2).refine((v) => new Set(v).size === v.length);
731
+ var ruleFields = {
732
+ priority: z5.number().int().safe().min(-1e6).max(1e6),
733
+ enabled: z5.boolean(),
734
+ phases,
735
+ name: z5.string().min(1).max(120),
736
+ expression: z5.string().min(1).max(8192)
737
+ };
738
+ var PolicyRule = z5.object({
739
+ id: Id3,
740
+ ...scopeShape,
741
+ ...ruleFields,
742
+ revision: Revision,
743
+ builtIn: z5.boolean(),
744
+ createdAt: Instant2,
745
+ updatedAt: Instant2
746
+ }).strict().refine(scopeValid);
747
+ var PolicyToolSafety = z5.object({
748
+ destructiveDelete: z5.boolean(),
749
+ forcePush: z5.boolean(),
750
+ defaultBranchPush: z5.boolean(),
751
+ uncertain: z5.boolean(),
752
+ reasons: z5.array(z5.string().min(1).max(1e3)).max(16)
753
+ }).strict();
754
+ function normalizePosixPath(value) {
755
+ const parts = [];
756
+ for (const part of value.split("/")) {
757
+ if (part === "..")
758
+ parts.pop();
759
+ else if (part && part !== ".")
760
+ parts.push(part);
761
+ }
762
+ return `/${parts.join("/")}`;
763
+ }
764
+ var hostPath = z5.string().min(1).max(8192).refine((value) => value.startsWith("/") && !value.includes("\0"), "Expected absolute POSIX path").transform(normalizePosixPath);
765
+ function relativePosixPath(from, to) {
766
+ const fromParts = from.split("/").filter(Boolean);
767
+ const toParts = to.split("/").filter(Boolean);
768
+ let shared = 0;
769
+ while (shared < fromParts.length && fromParts[shared] === toParts[shared])
770
+ shared++;
771
+ return [...fromParts.slice(shared).map(() => ".."), ...toParts.slice(shared)].join("/");
772
+ }
773
+ var HostPolicyBoundary = z5.object({
774
+ cwd: hostPath,
775
+ workspaceRoot: hostPath,
776
+ cwdReal: hostPath,
777
+ workspaceRootReal: hostPath
778
+ }).strict().refine((boundary) => {
779
+ const relative = relativePosixPath(boundary.workspaceRootReal, boundary.cwdReal);
780
+ return relative !== ".." && !relative.startsWith("../");
781
+ }, "Real cwd must be within the real workspace boundary.");
782
+ var HostToolPolicyContext = z5.object({
783
+ version: z5.literal(1),
784
+ toolCallId: Id3,
785
+ toolHash: Fingerprint,
786
+ boundary: HostPolicyBoundary,
787
+ defaultBranch: z5.string().min(1).max(255).nullable(),
788
+ safety: PolicyToolSafety
789
+ }).strict();
790
+ var PolicyToolContext = z5.object({ name: Id3, args: JsonObject, safety: PolicyToolSafety }).strict();
791
+ var PolicyRequestContext = z5.object({ method: PolicyRequestAction, args: JsonObject }).strict();
792
+ var absolutePath = z5.string().min(1).max(8192).refine((v) => v.startsWith("/") || /^[A-Za-z]:[\\/]/.test(v));
793
+ var controlMode = z5.enum(["human", "automation"]);
794
+ var PolicySessionContext = z5.object({
795
+ id: Id3,
796
+ hostId: Id3,
797
+ nativeSessionId: Id3.nullable(),
798
+ runtimeId: Id3.nullable(),
799
+ profileId: Id3,
800
+ projectId: Id3.nullable(),
801
+ taskId: Id3.nullable(),
802
+ runId: Id3.nullable(),
803
+ controlMode,
804
+ controlRevision: Revision,
805
+ cwd: absolutePath,
806
+ workspaceRoot: absolutePath,
807
+ repository: z5.string().min(1).max(2048).nullable(),
808
+ defaultBranch: z5.string().min(1).max(255).nullable(),
809
+ readOnly: z5.boolean()
810
+ }).strict();
811
+ var PolicyTaskContext = z5.object({
812
+ id: Id3,
813
+ projectId: Id3,
814
+ rootTaskId: Id3,
815
+ parentTaskId: Id3.nullable(),
816
+ title: z5.string().min(1).max(300),
817
+ state: z5.enum(["backlog", "ready", "in_progress", "review", "done", "canceled"])
818
+ }).strict();
819
+ var PolicyTargetContext = z5.object({
820
+ id: Id3,
821
+ hostId: Id3,
822
+ projectId: Id3.nullable(),
823
+ taskId: Id3.nullable(),
824
+ controlMode,
825
+ controlRevision: Revision,
826
+ runtime: z5.enum([
827
+ "starting",
828
+ "idle",
829
+ "running",
830
+ "waiting_input",
831
+ "interrupted",
832
+ "failed",
833
+ "stopped"
834
+ ]),
835
+ readOnly: z5.boolean()
836
+ }).strict();
837
+ var PolicyCostContext = z5.object({
838
+ tokens: z5.number().int().safe().nonnegative().nullable(),
839
+ costUsd: z5.number().finite().nonnegative().nullable(),
840
+ maxTokens: z5.number().int().safe().positive().nullable(),
841
+ maxCostUsd: z5.number().finite().positive().nullable(),
842
+ accounting: z5.enum(["available", "unavailable"]),
843
+ fresh: z5.boolean(),
844
+ watermark: CompletedUsageWatermark.nullable(),
845
+ provider: Id3.nullable(),
846
+ modelId: z5.string().min(1).max(512).nullable(),
847
+ classification: z5.enum(["cheap", "expensive", "unclassified"]),
848
+ expensive: z5.boolean()
849
+ }).strict().refine((v) => v.expensive === (v.classification !== "cheap") && (v.provider !== null && v.modelId !== null || v.classification === "unclassified") && v.accounting === "available" === (v.tokens !== null || v.costUsd !== null));
850
+ var PolicyContext = z5.object({
851
+ phase: PolicyPhase,
852
+ action: z5.union([z5.literal("tool.call"), PolicyRequestAction]),
853
+ tool: PolicyToolContext.nullable(),
854
+ request: PolicyRequestContext.nullable(),
855
+ session: PolicySessionContext,
856
+ task: PolicyTaskContext.nullable(),
857
+ target: PolicyTargetContext.nullable(),
858
+ cost: PolicyCostContext,
859
+ counters: PolicyCounterMap
860
+ }).strict().refine((v) => (v.phase === "tool_call" ? v.action === "tool.call" && v.tool !== null && v.request === null : v.tool === null && v.request !== null && v.action === v.request.method) && (v.action === "message.send" ? v.target !== null : v.target === null)).refine((v) => bytes2(JSON.stringify(v)) <= 65536, "Policy input is too large to evaluate.");
861
+ var PolicyRuleResult = z5.union([
862
+ z5.null(),
863
+ z5.object({ verdict: PolicyVerdict, reason: Text, state_updates: PolicyCounterMap.optional() }).strict().refine((v) => v.verdict === "ALLOW" || v.reason.length > 0)
864
+ ]);
865
+ var webUrl = z5.string().max(4096).refine((s) => {
866
+ try {
867
+ const u = new URL(s);
868
+ return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password;
869
+ } catch {
870
+ return false;
871
+ }
872
+ });
873
+ var PolicyEvaluation = z5.discriminatedUnion("verdict", [
874
+ z5.object({ verdict: z5.literal("ALLOW") }).strict(),
875
+ z5.object({ verdict: z5.literal("DENY"), reason: Reason }).strict(),
876
+ z5.object({
877
+ verdict: z5.literal("ASK"),
878
+ decisionId: Id3,
879
+ interactionId: Id3,
880
+ interactionUrl: webUrl
881
+ }).strict()
882
+ ]);
883
+ var PolicyPermission = z5.object({
884
+ kind: z5.literal("policy"),
885
+ decisionId: Id3,
886
+ rootTaskId: Id3.nullable(),
887
+ ruleId: Id3,
888
+ ruleRevision: Revision,
889
+ fingerprint: Fingerprint
890
+ }).strict();
891
+ var PolicyGrant = z5.object({
892
+ id: Id3,
893
+ scope: z5.object({ kind: z5.enum(["task", "session"]), id: Id3 }).strict(),
894
+ ruleId: Id3,
895
+ ruleRevision: Revision,
896
+ fingerprint: Fingerprint,
897
+ approvedByDeviceId: Id3,
898
+ approvedAt: Instant2
899
+ }).strict();
900
+ var trimmed = (max) => z5.string().min(1).max(max).refine((s) => s.trim() === s);
901
+ var PolicyModelClassification = z5.object({
902
+ provider: trimmed(200),
903
+ modelId: trimmed(512),
904
+ classification: z5.enum(["cheap", "expensive"])
905
+ }).strict();
906
+ var classifications = z5.array(PolicyModelClassification).max(1e3).refine((v) => new Set(v.map((x) => JSON.stringify([x.provider, x.modelId]))).size === v.length);
907
+ var PolicySettings = z5.object({ revision: Revision, modelClassifications: classifications, updatedAt: Instant2 }).strict();
908
+ var toolInput = z5.object({ name: Id3, args: JsonObject }).strict();
909
+ var sampleIdentity = { sessionId: Id3, nativeSessionId: Id3, runtimeId: Id3, sampleId: Id3 };
910
+ var HostPolicySampleRequest = z5.object({ ...sampleIdentity, tool: toolInput }).strict();
911
+ var HostPolicySampleResult = z5.object({
912
+ ...sampleIdentity,
913
+ toolHash: Fingerprint,
914
+ boundary: HostPolicyBoundary,
915
+ defaultBranch: z5.string().min(1).max(255).nullable(),
916
+ safety: PolicyToolSafety
917
+ }).strict();
918
+ var PolicyEvaluateRequest = z5.object({ evaluationId: Id3, toolCallId: Id3, tool: toolInput }).strict();
919
+ var PolicyStatusRequest = z5.object({ decisionId: Id3, waitMs: z5.literal(25e3) }).strict();
920
+ var PolicyStatusResult = z5.discriminatedUnion("state", [
921
+ z5.object({ state: z5.literal("pending") }).strict(),
922
+ z5.object({ state: z5.literal("allowed") }).strict(),
923
+ z5.object({ state: z5.literal("denied"), reason: Reason }).strict(),
924
+ z5.object({ state: z5.literal("canceled"), reason: Reason }).strict()
925
+ ]);
926
+ var PolicyCancelRequest = z5.object({ decisionId: Id3 }).strict();
927
+ var PolicyCancelResult = z5.object({ state: z5.enum(["canceled", "already_resolved"]) }).strict();
928
+ var PolicyTrace = z5.object({
929
+ ruleId: Id3,
930
+ ruleRevision: Revision,
931
+ ...scopeShape,
932
+ verdict: PolicyVerdict.nullable(),
933
+ reason: Text.nullable(),
934
+ granted: z5.boolean(),
935
+ overridden: z5.boolean(),
936
+ proposedStateUpdates: PolicyCounterMap
937
+ }).strict().refine(scopeValid);
938
+ var PolicyTestResult = z5.object({
939
+ verdict: PolicyVerdict,
940
+ reason: Text.nullable(),
941
+ trace: z5.array(PolicyTrace).max(128),
942
+ proposedStateUpdates: z5.record(Id3, PolicyCounterMap),
943
+ enforcement: z5.object({
944
+ phases: z5.array(PolicyPhase),
945
+ modelRequest: z5.literal(false),
946
+ explanation: z5.string()
947
+ }).strict()
948
+ }).strict();
949
+ var CreatePolicyRuleRequest = z5.object({ ...scopeShape, ...ruleFields }).strict().refine(scopeValid);
950
+ var UpdatePolicyRuleRequest = z5.object({
951
+ expectedRevision: Revision,
952
+ name: ruleFields.name.optional(),
953
+ priority: ruleFields.priority.optional(),
954
+ enabled: z5.boolean().optional(),
955
+ phases: phases.optional(),
956
+ expression: ruleFields.expression.optional()
957
+ }).strict().refine((v) => Object.keys(v).length > 1);
958
+ var DeletePolicyRuleQuery = z5.object({ expectedRevision: Revision }).strict();
959
+ var UpdatePolicySettingsRequest = z5.object({ expectedRevision: Revision, modelClassifications: classifications }).strict();
960
+ var PolicyTestRequest = z5.object({
961
+ sessionId: Id3,
962
+ phase: PolicyPhase,
963
+ tool: toolInput.nullable(),
964
+ request: PolicyRequestContext.nullable()
965
+ }).strict().refine((v) => v.phase === "tool_call" ? v.tool !== null && v.request === null : v.tool === null && v.request !== null);
966
+
967
+ // packages/protocol/dist/entities.js
968
+ var Iso = z6.string();
969
+ var Id4 = z6.string();
970
+ var Connectivity = z6.enum(["connected", "reconnecting", "unreachable"]);
971
+ var ControlMode = z6.enum(["automation", "human"]);
972
+ var Platform = z6.enum(["darwin", "linux"]);
973
+ var DeviceKind = z6.enum(["browser", "pwa", "terminal", "cli"]);
974
+ var DiagnosticLevel = z6.enum(["info", "warning", "error"]);
975
+ var DEFAULT_WORKTREE_DIR = ".worktrees";
976
+ var CoreCapabilities = z6.object({
977
+ prompt: z6.boolean(),
978
+ steer: z6.boolean(),
979
+ followUp: z6.boolean(),
980
+ abort: z6.boolean(),
981
+ resume: z6.boolean(),
982
+ rename: z6.boolean(),
983
+ importInactive: z6.boolean(),
984
+ extensionDialogs: z6.boolean(),
985
+ customUi: z6.boolean(),
986
+ widgetsText: z6.boolean(),
987
+ widgetsComponent: z6.boolean(),
988
+ tokenAccounting: z6.boolean(),
989
+ costAccounting: z6.boolean()
990
+ });
991
+ var CAPABILITY_KEYS = CoreCapabilities.keyof().options;
992
+ var RuntimeCapabilities = CoreCapabilities.extend({
993
+ /** The host runs sessions as interactive Pi in a terminal that clients can attach to. */
994
+ terminal: z6.boolean().optional(),
995
+ /** The host answers session.models, session.commands, session.setModel, session.setThinking and session.compact. */
996
+ sessionControls: z6.boolean().optional(),
997
+ /** The host answers session.navigate for terminal sessions. */
998
+ treeNavigation: z6.boolean().optional(),
999
+ agentRequests: z6.boolean().optional(),
1000
+ messageDelivery: z6.boolean().optional(),
1001
+ policies: z6.boolean().optional(),
1002
+ /** Session-scoped adapter inspection and safe reload. */
1003
+ adapterDevelopment: z6.boolean().optional(),
1004
+ unsupported: z6.array(z6.object({ capability: z6.string(), reason: z6.string() }))
1005
+ });
1006
+ var ProjectScan = z6.object({
1007
+ state: z6.enum(["running", "done", "failed"]),
1008
+ startedAt: Iso,
1009
+ finishedAt: Iso.nullable(),
1010
+ /** Repositories found across all folders. */
1011
+ repositories: z6.number().int(),
1012
+ /** New projects created by this scan. */
1013
+ projectsCreated: z6.number().int(),
1014
+ /** New checkouts (including the ones of new projects). */
1015
+ checkoutsAdded: z6.number().int(),
1016
+ /** "<folder>: <message>" per folder that failed; for state "failed", the reason last. */
1017
+ errors: z6.array(z6.string())
1018
+ });
1019
+ var UsageWindow = z6.object({
1020
+ id: z6.enum(["five_hour", "weekly"]),
1021
+ usedPct: z6.number(),
1022
+ resetsAt: Iso.nullable()
1023
+ });
1024
+ var ProviderUsage = z6.object({
1025
+ provider: z6.enum(["anthropic", "openai-codex"]),
1026
+ status: z6.enum(["available", "expired", "rejected", "error"]),
1027
+ message: z6.string().nullable(),
1028
+ windows: z6.array(UsageWindow),
1029
+ fetchedAt: Iso
1030
+ });
1031
+ var Host = z6.object({
1032
+ id: Id4,
1033
+ name: z6.string(),
1034
+ platform: Platform,
1035
+ agentVersion: z6.string(),
1036
+ piVersion: z6.string().nullable(),
1037
+ piCompatible: z6.boolean(),
1038
+ capabilities: RuntimeCapabilities.nullable(),
1039
+ connectivity: Connectivity,
1040
+ lastSeenAt: Iso.nullable(),
1041
+ revokedAt: Iso.nullable(),
1042
+ createdAt: Iso,
1043
+ /** Folders on the host whose git repositories become projects (absolute or ~/...). */
1044
+ projectFolders: z6.array(z6.string()).optional(),
1045
+ projectScan: ProjectScan.nullable().optional(),
1046
+ /** Subscription limits (host-reported, refreshed every few minutes). */
1047
+ usage: z6.array(ProviderUsage).optional(),
1048
+ github: HostGitHub.optional()
1049
+ });
1050
+ var WorktreeDir = z6.string().min(1).refine((d) => !d.startsWith("/") && !d.includes("\\"), "must be a relative path").refine((d) => !d.split("/").includes(".."), "must stay inside the repository").refine((d) => d.split("/").every((s) => s.length > 0 && s !== "."), "must be a plain relative path");
1051
+ var Project = z6.object({
1052
+ id: Id4,
1053
+ name: z6.string().min(1),
1054
+ repoIdentity: z6.string(),
1055
+ defaultProfileId: Id4.nullable(),
1056
+ defaultHostId: Id4.nullable(),
1057
+ maxConcurrentRuns: z6.number().int().min(1).max(32),
1058
+ automationEnabled: z6.boolean(),
1059
+ setupCommand: z6.string().nullable(),
1060
+ checks: z6.array(z6.string()),
1061
+ workspaceSharing: z6.enum(["single_writer", "shared"]),
1062
+ worktreeDir: WorktreeDir.default(DEFAULT_WORKTREE_DIR),
1063
+ createdAt: Iso,
1064
+ updatedAt: Iso
1065
+ });
1066
+ var Checkout = z6.object({
1067
+ id: Id4,
1068
+ projectId: Id4,
1069
+ hostId: Id4,
1070
+ path: z6.string(),
1071
+ commonDir: z6.string(),
1072
+ defaultBranch: z6.string(),
1073
+ createdAt: Iso
1074
+ });
1075
+ var GitState = z6.object({
1076
+ dirty: z6.boolean(),
1077
+ changedFiles: z6.number().int(),
1078
+ ahead: z6.number().int(),
1079
+ behind: z6.number().int(),
1080
+ unmerged: z6.boolean()
1081
+ });
1082
+ var Workspace = z6.object({
1083
+ id: Id4,
1084
+ checkoutId: Id4,
1085
+ projectId: Id4,
1086
+ hostId: Id4,
1087
+ path: z6.string(),
1088
+ branch: z6.string().nullable(),
1089
+ baseBranch: z6.string().nullable(),
1090
+ provenance: z6.enum(["managed", "discovered", "main"]),
1091
+ git: GitState,
1092
+ setup: z6.object({
1093
+ state: z6.enum(["none", "running", "succeeded", "failed"]),
1094
+ log: z6.string()
1095
+ }),
1096
+ archivedAt: Iso.nullable(),
1097
+ updatedAt: Iso,
1098
+ github: WorkspaceGitHub.optional()
1099
+ });
1100
+ var ThinkingLevel = z6.enum(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
1101
+ var SessionModel = z6.object({
1102
+ provider: z6.string(),
1103
+ id: z6.string(),
1104
+ name: z6.string().nullable(),
1105
+ contextWindow: z6.number().nullable(),
1106
+ reasoning: z6.boolean(),
1107
+ /** In Pi's scoped (favorite) model list; set only when Pi has one. */
1108
+ scoped: z6.boolean().optional(),
1109
+ /** Effort levels this model accepts, in Pi's order; ["off"] without reasoning. */
1110
+ thinkingLevels: z6.array(ThinkingLevel),
1111
+ /** Prompt-cache lifetimes in seconds from Pi's model metadata. */
1112
+ promptCache: z6.object({ short: z6.number().optional(), long: z6.number().optional() }).nullable().optional()
1113
+ });
1114
+ var SlashCommand = z6.object({
1115
+ name: z6.string().min(1),
1116
+ description: z6.string().nullable(),
1117
+ source: z6.enum(["extension", "prompt", "skill"]),
1118
+ argumentHint: z6.string().nullable().optional()
1119
+ });
1120
+ var ContextUsage = z6.object({
1121
+ /** Estimated tokens in context; null right after compaction until the next reply. */
1122
+ tokens: z6.number().nullable(),
1123
+ window: z6.number(),
1124
+ percent: z6.number().nullable()
1125
+ });
1126
+ var FORBIDDEN_EXTRA_ARGS = ["--mode", "--fork", "--no-session", "-e", "--extension"];
1127
+ var ExtraArg = z6.string().refine((a) => a.startsWith("--") || !a.startsWith("-"), "extra args must be long flags").refine((a) => !FORBIDDEN_EXTRA_ARGS.includes(a.split("=")[0]) && !a.startsWith("--session"), "this flag is managed by Switchyard");
1128
+ var Profile = z6.object({
1129
+ id: Id4,
1130
+ name: z6.string().min(1),
1131
+ provider: z6.string().nullable(),
1132
+ model: z6.string().nullable(),
1133
+ thinking: ThinkingLevel.nullable(),
1134
+ projectTrust: z6.enum(["ask", "approve", "ignore"]),
1135
+ extraArgs: z6.array(ExtraArg),
1136
+ /** "vanilla": --no-extensions --no-skills --no-prompt-templates. Undefined means "all". */
1137
+ resources: z6.enum(["all", "vanilla"]).optional()
1138
+ });
1139
+ var ViewClient = z6.object({
1140
+ /** `${kind}:${name}@${machine}` */
1141
+ id: z6.string().min(1),
1142
+ kind: z6.enum(["herdr", "tmux"]),
1143
+ name: z6.string().min(1),
1144
+ machine: z6.string().min(1),
1145
+ lastSeenAt: Iso
1146
+ });
1147
+ var View = z6.object({
1148
+ id: Id4,
1149
+ name: z6.string().min(1).max(60),
1150
+ mode: z6.enum(["all", "pinned"]),
1151
+ projectIds: z6.array(z6.string()).nullable(),
1152
+ hostIds: z6.array(z6.string()).nullable(),
1153
+ sessionIds: z6.array(z6.string()),
1154
+ clients: z6.array(ViewClient),
1155
+ createdAt: Iso,
1156
+ updatedAt: Iso
1157
+ });
1158
+ var RuntimeState = z6.enum([
1159
+ "starting",
1160
+ "idle",
1161
+ "running",
1162
+ "waiting_input",
1163
+ "interrupted",
1164
+ "failed",
1165
+ "stopped"
1166
+ ]);
1167
+ var NativeHandle = z6.object({ sessionId: z6.string(), sessionFile: z6.string() });
1168
+ var SessionStats = z6.object({
1169
+ tokens: z6.number().nullable(),
1170
+ costUsd: z6.number().nullable(),
1171
+ /** Completed usage, refreshed for this exact settlement; absent on older hosts or failure. */
1172
+ watermark: CompletedUsageWatermark.optional(),
1173
+ context: ContextUsage.nullable().optional()
1174
+ });
1175
+ var PromptCacheInfo = z6.object({
1176
+ at: Iso,
1177
+ provider: z6.string(),
1178
+ model: z6.string(),
1179
+ cacheRead: z6.number(),
1180
+ cacheWrite: z6.number(),
1181
+ cacheWrite1h: z6.number()
1182
+ });
1183
+ var Session = z6.object({
1184
+ id: Id4,
1185
+ title: z6.string(),
1186
+ subtitle: z6.string().nullable(),
1187
+ hostId: Id4,
1188
+ workspaceId: Id4.nullable(),
1189
+ projectId: Id4.nullable(),
1190
+ cwd: z6.string(),
1191
+ nativeHandle: NativeHandle.nullable(),
1192
+ profileSnapshot: Profile,
1193
+ runtime: RuntimeState,
1194
+ runtimeDetail: z6.string().nullable(),
1195
+ connectivity: Connectivity,
1196
+ runId: Id4.nullable(),
1197
+ taskId: Id4.nullable(),
1198
+ provenance: z6.enum(["created", "imported", "subagent"]),
1199
+ readOnly: z6.boolean(),
1200
+ lastActivityAt: Iso,
1201
+ archivedAt: Iso.nullable(),
1202
+ queue: z6.object({ steering: z6.array(z6.string()), followUp: z6.array(z6.string()) }),
1203
+ stats: SessionStats.nullable(),
1204
+ /** The live model (host-owned; last known when stopped). */
1205
+ model: SessionModel.nullable().optional(),
1206
+ /** The live effort (Pi's thinking level). */
1207
+ thinking: ThinkingLevel.nullable().optional(),
1208
+ /** Pi is compacting the context. */
1209
+ compacting: z6.boolean().optional(),
1210
+ lastAssistantText: z6.string().nullable(),
1211
+ createdAt: Iso,
1212
+ /** A live terminal session: `switchyard tui` can attach to its Pi terminal. */
1213
+ terminal: z6.boolean().optional(),
1214
+ /** Set when the session finished or failed with nobody viewing it; cleared when viewed (coordinator-owned). */
1215
+ unreadSince: Iso.nullable().optional(),
1216
+ /** Identity of the adapter presentation currently installed on the host. */
1217
+ adapterGeneration: z6.string().uuid().optional(),
1218
+ /** Bumped when the transcript is rebuilt (rewind); clients drop cached copies (coordinator-owned). */
1219
+ transcriptEpoch: z6.number().int().min(0).optional(),
1220
+ bridge: z6.object({
1221
+ version: z6.literal(1),
1222
+ runtimeId: Id4,
1223
+ nativeSessionId: Id4,
1224
+ /** Host-generated local-controller identity, not Pi's private binding credential. */
1225
+ controllerEpoch: Id4.optional(),
1226
+ agentTools: z6.boolean(),
1227
+ messageDelivery: z6.boolean(),
1228
+ policyState: z6.enum(["initializing", "active", "unsupported", "lost"]),
1229
+ policyPhases: z6.array(PolicyPhase)
1230
+ }).optional(),
1231
+ /** Last assistant message's cache usage (host-owned). */
1232
+ promptCache: PromptCacheInfo.nullable().optional(),
1233
+ /** Warn before the prompt cache expires; non-null means on (coordinator-owned). */
1234
+ cacheAlert: z6.object({ ttlSec: z6.number().int().min(60).max(86400).nullable(), warnedFor: Iso.nullable() }).nullable().optional()
1235
+ });
1236
+ var ContinuationPolicy = z6.discriminatedUnion("enabled", [
1237
+ z6.object({ enabled: z6.literal(false) }),
1238
+ z6.object({
1239
+ enabled: z6.literal(true),
1240
+ objective: z6.string().min(1),
1241
+ maxContinuations: z6.number().int().min(1).max(50),
1242
+ maxElapsedMinutes: z6.number().int().min(1).max(1440),
1243
+ maxTokens: z6.number().int().positive().nullable(),
1244
+ maxCostUsd: z6.number().positive().nullable()
1245
+ })
1246
+ ]);
1247
+ var CompletionPolicy = z6.object({
1248
+ checks: z6.array(z6.string()).nullable(),
1249
+ requireHumanReview: z6.boolean()
1250
+ });
1251
+ var WorkspacePolicy = z6.discriminatedUnion("mode", [
1252
+ z6.object({
1253
+ mode: z6.literal("new_worktree"),
1254
+ branch: z6.string().nullable(),
1255
+ base: z6.string().nullable()
1256
+ }),
1257
+ z6.object({ mode: z6.literal("existing"), workspaceId: Id4 })
1258
+ ]);
1259
+ var TaskPolicy = z6.object({
1260
+ hostId: Id4.nullable(),
1261
+ profileId: Id4.nullable(),
1262
+ workspace: WorkspacePolicy,
1263
+ continuation: ContinuationPolicy,
1264
+ completion: CompletionPolicy
1265
+ });
1266
+ var TaskState = z6.enum(["backlog", "ready", "in_progress", "review", "done", "canceled"]);
1267
+ var Priority = z6.union([z6.literal(0), z6.literal(1), z6.literal(2), z6.literal(3)]);
1268
+ var TaskOrigin = z6.discriminatedUnion("kind", [
1269
+ z6.object({ kind: z6.literal("manual") }),
1270
+ z6.object({
1271
+ kind: z6.literal("automation"),
1272
+ automationId: Id4,
1273
+ occurrenceId: Id4,
1274
+ routine: z6.boolean()
1275
+ })
1276
+ ]);
1277
+ var Task = z6.object({
1278
+ id: Id4,
1279
+ projectId: Id4,
1280
+ title: z6.string().min(1),
1281
+ objective: z6.string(),
1282
+ acceptanceCriteria: z6.array(z6.string()),
1283
+ dependencies: z6.array(Id4),
1284
+ priority: Priority,
1285
+ position: z6.number(),
1286
+ state: TaskState,
1287
+ blocked: z6.object({ reason: z6.string() }).nullable(),
1288
+ notBefore: Iso.nullable(),
1289
+ policy: TaskPolicy,
1290
+ origin: TaskOrigin,
1291
+ groupingKey: z6.string().nullable(),
1292
+ parentTaskId: Id4.nullable().optional(),
1293
+ agentOrigin: z6.object({ sessionId: Id4, toolCallId: Id4 }).optional(),
1294
+ githubIssue: GitHubIssue.optional(),
1295
+ currentRunId: Id4.nullable(),
1296
+ sessionId: Id4.nullable(),
1297
+ review: z6.object({ feedback: z6.array(z6.string()), changesRequested: z6.boolean() }),
1298
+ hiddenFromBoard: z6.boolean(),
1299
+ lastActivityAt: Iso,
1300
+ createdAt: Iso,
1301
+ updatedAt: Iso
1302
+ });
1303
+ var RunState = z6.enum([
1304
+ "queued",
1305
+ "dispatching",
1306
+ "uncertain",
1307
+ "running",
1308
+ "waiting_input",
1309
+ "checking",
1310
+ "succeeded",
1311
+ "failed",
1312
+ "interrupted",
1313
+ "canceled"
1314
+ ]);
1315
+ var CheckResult = z6.object({
1316
+ command: z6.string(),
1317
+ exitCode: z6.number().int().nullable(),
1318
+ outputTail: z6.string()
1319
+ });
1320
+ var Run = z6.object({
1321
+ id: Id4,
1322
+ taskId: Id4,
1323
+ sessionId: Id4.nullable(),
1324
+ hostId: Id4.nullable(),
1325
+ dispatchKey: z6.string(),
1326
+ attempt: z6.number().int().min(1),
1327
+ state: RunState,
1328
+ controlMode: ControlMode,
1329
+ controlRevision: z6.number().int().min(1),
1330
+ continuationsUsed: z6.number().int().min(0),
1331
+ infraRetries: z6.number().int().min(0),
1332
+ nextAttemptAt: Iso.nullable(),
1333
+ startedAt: Iso.nullable(),
1334
+ endedAt: Iso.nullable(),
1335
+ outcome: z6.object({
1336
+ kind: z6.enum(["review", "failed", "blocked", "no_change", "canceled"]),
1337
+ summary: z6.string()
1338
+ }).nullable(),
1339
+ limits: ContinuationPolicy,
1340
+ usage: z6.object({
1341
+ tokens: z6.number().nullable(),
1342
+ costUsd: z6.number().nullable(),
1343
+ accounting: z6.enum(["available", "unavailable"]),
1344
+ note: z6.string().nullable()
1345
+ }),
1346
+ checks: z6.array(CheckResult),
1347
+ createdAt: Iso,
1348
+ updatedAt: Iso
1349
+ });
1350
+ var Trigger = z6.discriminatedUnion("kind", [
1351
+ z6.object({ kind: z6.literal("manual") }),
1352
+ z6.object({ kind: z6.literal("once"), at: Iso }),
1353
+ z6.object({ kind: z6.literal("cron"), expr: z6.string().min(1), timezone: z6.string().min(1) }),
1354
+ z6.object({ kind: z6.literal("webhook") }),
1355
+ z6.object({ kind: z6.literal("dependency"), taskId: Id4 })
1356
+ ]);
1357
+ var TaskTemplate = z6.object({
1358
+ title: z6.string().min(1),
1359
+ objective: z6.string(),
1360
+ acceptanceCriteria: z6.array(z6.string()),
1361
+ priority: Priority
1362
+ });
1363
+ var Automation = z6.object({
1364
+ id: Id4,
1365
+ name: z6.string().min(1),
1366
+ enabled: z6.boolean(),
1367
+ projectId: Id4,
1368
+ trigger: Trigger,
1369
+ filters: z6.array(z6.object({ path: z6.string(), equals: z6.string() })),
1370
+ template: TaskTemplate,
1371
+ hostId: Id4.nullable(),
1372
+ profileId: Id4.nullable(),
1373
+ mode: z6.enum(["fresh", "continue", "watch"]),
1374
+ groupingKey: z6.string().nullable(),
1375
+ overlap: z6.enum(["skip", "queue_one", "append"]),
1376
+ missed: z6.enum(["skip", "run_once"]),
1377
+ continuation: ContinuationPolicy,
1378
+ completion: CompletionPolicy,
1379
+ nextAt: Iso.nullable(),
1380
+ lastEvaluatedAt: Iso.nullable(),
1381
+ lastOutcome: z6.string().nullable(),
1382
+ failureCount: z6.number().int().min(0),
1383
+ webhookTokenSet: z6.boolean(),
1384
+ createdAt: Iso,
1385
+ updatedAt: Iso
1386
+ });
1387
+ var OccurrenceState = z6.enum([
1388
+ "fired",
1389
+ "skipped_overlap",
1390
+ "skipped_missed",
1391
+ "queued",
1392
+ "appended",
1393
+ "failed",
1394
+ "filtered"
1395
+ ]);
1396
+ var Occurrence = z6.object({
1397
+ id: Id4,
1398
+ automationId: Id4,
1399
+ key: z6.string(),
1400
+ scheduledFor: Iso.nullable(),
1401
+ state: OccurrenceState,
1402
+ taskId: Id4.nullable(),
1403
+ reason: z6.string().nullable(),
1404
+ outcome: z6.string().nullable(),
1405
+ createdAt: Iso
1406
+ });
1407
+ var InteractionState = z6.preprocess((v) => v === "cancelled" ? "canceled" : v, z6.enum(["pending", "resolved", "expired", "canceled", "unsupported"]));
1408
+ var Interaction = z6.object({
1409
+ id: Id4,
1410
+ sessionId: Id4,
1411
+ revision: z6.number().int().min(1),
1412
+ source: z6.discriminatedUnion("kind", [
1413
+ z6.object({
1414
+ kind: z6.literal("extension_ui"),
1415
+ method: z6.enum(["select", "confirm", "input", "editor"]),
1416
+ piRequestIds: z6.array(z6.string())
1417
+ }),
1418
+ z6.object({ kind: z6.literal("unsupported_custom"), title: z6.string().nullable() })
1419
+ ]),
1420
+ adapterId: z6.string().nullable(),
1421
+ permission: PolicyPermission.optional(),
1422
+ title: z6.string(),
1423
+ presentation: UINodeSchema,
1424
+ state: InteractionState,
1425
+ resolution: z6.object({ by: z6.string(), summary: z6.string(), at: Iso }).nullable(),
1426
+ createdAt: Iso
1427
+ });
1428
+ var AttentionReason = z6.enum([
1429
+ "needs_input",
1430
+ "failed",
1431
+ "ready_for_review",
1432
+ "unsupported_interaction",
1433
+ "host_unreachable",
1434
+ "cache_expiring"
1435
+ ]);
1436
+ var AttentionItem = z6.object({
1437
+ id: Id4,
1438
+ sessionId: Id4.nullable(),
1439
+ taskId: Id4.nullable(),
1440
+ projectId: Id4.nullable(),
1441
+ reason: AttentionReason,
1442
+ severity: z6.enum(["info", "warning", "critical"]),
1443
+ summary: z6.string(),
1444
+ interactionId: Id4.nullable(),
1445
+ deepLink: z6.string(),
1446
+ acknowledgedAt: Iso.nullable(),
1447
+ resolvedAt: Iso.nullable(),
1448
+ createdAt: Iso
1449
+ });
1450
+ var Device = z6.object({
1451
+ id: Id4,
1452
+ name: z6.string(),
1453
+ kind: DeviceKind,
1454
+ createdAt: Iso,
1455
+ lastSeenAt: Iso.nullable(),
1456
+ revokedAt: Iso.nullable(),
1457
+ push: z6.object({
1458
+ subscribed: z6.boolean(),
1459
+ permission: z6.enum(["granted", "denied", "default", "unknown"])
1460
+ }),
1461
+ preferredMobile: z6.boolean(),
1462
+ enrolledVia: z6.enum(["enrollment", "passkey", "oidc", "admin", "approval"]).default("enrollment")
1463
+ });
1464
+ var ToolItemData = z6.object({
1465
+ toolCallId: z6.string(),
1466
+ name: z6.string(),
1467
+ status: z6.enum(["running", "ok", "error"]),
1468
+ args: z6.unknown(),
1469
+ summary: z6.string(),
1470
+ output: z6.string(),
1471
+ startedAt: Iso,
1472
+ durationMs: z6.number().nullable(),
1473
+ card: UINodeSchema.nullable(),
1474
+ adapterId: z6.string().nullable(),
1475
+ adapterGeneration: z6.string().uuid().optional()
1476
+ });
1477
+ var TranscriptItem = z6.discriminatedUnion("kind", [
1478
+ z6.object({
1479
+ id: Id4,
1480
+ sessionId: Id4,
1481
+ order: z6.number().int(),
1482
+ at: Iso,
1483
+ kind: z6.literal("user"),
1484
+ data: z6.object({
1485
+ text: z6.string(),
1486
+ images: z6.number().int().optional(),
1487
+ /** Pi session entry id, for rewind and fork from this message. */
1488
+ entryId: z6.string().optional()
1489
+ })
1490
+ }),
1491
+ z6.object({
1492
+ id: Id4,
1493
+ sessionId: Id4,
1494
+ order: z6.number().int(),
1495
+ at: Iso,
1496
+ kind: z6.literal("assistant"),
1497
+ data: z6.object({ text: z6.string(), streaming: z6.boolean().optional() })
1498
+ }),
1499
+ z6.object({
1500
+ id: Id4,
1501
+ sessionId: Id4,
1502
+ order: z6.number().int(),
1503
+ at: Iso,
1504
+ kind: z6.literal("thinking"),
1505
+ data: z6.object({ text: z6.string() })
1506
+ }),
1507
+ z6.object({
1508
+ id: Id4,
1509
+ sessionId: Id4,
1510
+ order: z6.number().int(),
1511
+ at: Iso,
1512
+ kind: z6.literal("tool"),
1513
+ data: ToolItemData
1514
+ }),
1515
+ z6.object({
1516
+ id: Id4,
1517
+ sessionId: Id4,
1518
+ order: z6.number().int(),
1519
+ at: Iso,
1520
+ kind: z6.literal("notice"),
1521
+ data: z6.object({
1522
+ level: DiagnosticLevel,
1523
+ text: z6.string(),
1524
+ customType: z6.string().min(1).max(200).optional(),
1525
+ card: UINodeSchema.optional(),
1526
+ adapterId: z6.string().optional(),
1527
+ adapterGeneration: z6.string().uuid().optional()
1528
+ }).refine((data) => !data.card || !!data.adapterId, "Card requires adapterId")
1529
+ }),
1530
+ z6.object({
1531
+ id: Id4,
1532
+ sessionId: Id4,
1533
+ order: z6.number().int(),
1534
+ at: Iso,
1535
+ kind: z6.literal("interaction"),
1536
+ data: z6.object({ interactionId: Id4 })
1537
+ }),
1538
+ z6.object({
1539
+ id: Id4,
1540
+ sessionId: Id4,
1541
+ order: z6.number().int(),
1542
+ at: Iso,
1543
+ kind: z6.literal("subagent"),
1544
+ data: z6.object({
1545
+ runId: z6.string(),
1546
+ label: z6.string(),
1547
+ status: z6.string(),
1548
+ sessionFile: z6.string().nullable(),
1549
+ linkedSessionId: Id4.nullable()
1550
+ })
1551
+ }),
1552
+ z6.object({
1553
+ id: Id4,
1554
+ sessionId: Id4,
1555
+ order: z6.number().int(),
1556
+ at: Iso,
1557
+ kind: z6.literal("system"),
1558
+ data: z6.object({ text: z6.string(), suggestion: z6.boolean().optional() })
1559
+ })
1560
+ ]);
1561
+ var Panel = z6.object({
1562
+ sessionId: Id4,
1563
+ adapterId: z6.string(),
1564
+ slot: z6.string(),
1565
+ title: z6.string(),
1566
+ node: UINodeSchema.nullable(),
1567
+ webRenderer: z6.boolean(),
1568
+ mobileFallback: z6.string().nullable(),
1569
+ contribution: ContributionDescriptor.optional(),
1570
+ state: z6.unknown().optional(),
1571
+ adapterGeneration: z6.string().uuid().optional(),
1572
+ updatedAt: Iso
1573
+ });
1574
+ var Diagnostic = z6.object({
1575
+ sessionId: Id4.nullable(),
1576
+ adapterId: z6.string().nullable(),
1577
+ level: DiagnosticLevel,
1578
+ message: z6.string(),
1579
+ at: Iso
1580
+ });
1581
+ var AdapterInfo = z6.object({
1582
+ id: z6.string(),
1583
+ version: z6.string(),
1584
+ tier: z6.enum(["project", "owner", "plugin", "bundled"]),
1585
+ target: z6.object({
1586
+ extension: z6.string(),
1587
+ versionRange: z6.string(),
1588
+ testedVersions: z6.array(z6.string())
1589
+ }),
1590
+ capabilities: z6.array(z6.string()),
1591
+ webRenderer: z6.boolean(),
1592
+ status: z6.enum(["active", "disabled", "error"]),
1593
+ detail: z6.string().nullable()
1594
+ });
1595
+ var Passkey = z6.object({
1596
+ id: z6.string(),
1597
+ name: z6.string(),
1598
+ createdAt: Iso,
1599
+ lastUsedAt: Iso.nullable(),
1600
+ transports: z6.array(z6.string())
1601
+ });
1602
+
1603
+ // packages/protocol/dist/adapter-preview.js
1604
+ var ADAPTER_PREVIEW_MAX_BYTES = 1024 * 1024;
1605
+ var ADAPTER_PREVIEW_MAX_STEPS = 200;
1606
+ var ADAPTER_PREVIEW_SESSION_ID = "ses_adapter_preview";
1607
+ function bounded(input, ctx) {
1608
+ try {
1609
+ boundContributionJson(input, ADAPTER_PREVIEW_MAX_BYTES);
1610
+ return input;
1611
+ } catch (error) {
1612
+ ctx.addIssue({ code: "custom", message: error.message });
1613
+ return z7.NEVER;
1614
+ }
1615
+ }
1616
+ var Id5 = z7.string().min(1).max(200);
1617
+ var Text2 = z7.string().max(64 * 1024);
1618
+ var Tool = { toolCallId: Id5, name: Id5, args: z7.unknown() };
1619
+ var DialogCommon = { id: Id5, title: Text2 };
1620
+ var AdapterPreviewPiUiRequestSchema = z7.discriminatedUnion("method", [
1621
+ z7.object({
1622
+ ...DialogCommon,
1623
+ method: z7.literal("select"),
1624
+ options: z7.array(Text2).max(200),
1625
+ timeout: z7.number().nonnegative().optional()
1626
+ }).strict(),
1627
+ z7.object({
1628
+ ...DialogCommon,
1629
+ method: z7.literal("confirm"),
1630
+ message: Text2,
1631
+ timeout: z7.number().nonnegative().optional()
1632
+ }).strict(),
1633
+ z7.object({
1634
+ ...DialogCommon,
1635
+ method: z7.literal("input"),
1636
+ placeholder: Text2.optional(),
1637
+ timeout: z7.number().nonnegative().optional()
1638
+ }).strict(),
1639
+ z7.object({ ...DialogCommon, method: z7.literal("editor"), prefill: Text2.optional() }).strict()
1640
+ ]);
1641
+ var AdapterPreviewStepSchema = z7.discriminatedUnion("kind", [
1642
+ z7.object({ kind: z7.literal("restore") }).strict(),
1643
+ z7.object({ kind: z7.literal("toolStart"), data: z7.object(Tool).strict() }).strict(),
1644
+ z7.object({
1645
+ kind: z7.literal("toolUpdate"),
1646
+ data: z7.object({ ...Tool, partialResult: z7.unknown(), details: z7.unknown().optional() }).strict()
1647
+ }).strict(),
1648
+ z7.object({
1649
+ kind: z7.literal("toolEnd"),
1650
+ data: z7.object({
1651
+ ...Tool,
1652
+ result: z7.unknown(),
1653
+ isError: z7.boolean(),
1654
+ details: z7.unknown().optional()
1655
+ }).strict()
1656
+ }).strict(),
1657
+ z7.object({
1658
+ kind: z7.literal("status"),
1659
+ data: z7.object({ key: Id5, text: Text2.optional() }).strict()
1660
+ }).strict(),
1661
+ z7.object({
1662
+ kind: z7.literal("widget"),
1663
+ data: z7.object({ key: Id5, lines: z7.array(Text2).max(200).optional() }).strict()
1664
+ }).strict(),
1665
+ z7.object({ kind: z7.literal("dialog"), data: AdapterPreviewPiUiRequestSchema }).strict(),
1666
+ z7.object({
1667
+ kind: z7.literal("answer"),
1668
+ data: z7.object({ requestId: Id5, response: InteractionResponseSchema }).strict()
1669
+ }).strict(),
1670
+ z7.object({
1671
+ kind: z7.literal("customMessage"),
1672
+ data: z7.object({
1673
+ customType: Id5,
1674
+ content: z7.unknown(),
1675
+ display: z7.boolean().optional(),
1676
+ details: z7.unknown().optional()
1677
+ }).strict()
1678
+ }).strict(),
1679
+ z7.object({
1680
+ kind: z7.literal("action"),
1681
+ data: z7.object({ actionId: Id5, payload: z7.unknown() }).strict()
1682
+ }).strict()
1683
+ ]);
1684
+ var AdapterPreviewFixtureSchema = z7.unknown().transform(bounded).pipe(z7.object({
1685
+ version: z7.literal(1),
1686
+ name: z7.string().min(1).max(200),
1687
+ initialState: z7.record(z7.string(), z7.record(z7.string(), z7.unknown())).optional(),
1688
+ steps: z7.array(AdapterPreviewStepSchema).max(ADAPTER_PREVIEW_MAX_STEPS)
1689
+ }).strict());
1690
+ var PortableNode = z7.unknown().transform((input, ctx) => {
1691
+ try {
1692
+ return validateUINode(input);
1693
+ } catch (error) {
1694
+ ctx.addIssue({ code: "custom", message: error.message });
1695
+ return z7.NEVER;
1696
+ }
1697
+ });
1698
+ var PreviewPanel = Panel.extend({ webRenderer: z7.literal(false) }).superRefine((panel, ctx) => {
1699
+ try {
1700
+ if (panel.sessionId !== ADAPTER_PREVIEW_SESSION_ID)
1701
+ throw new Error("Preview panels must use the fake preview session");
1702
+ if (panel.node !== null)
1703
+ validateUINode(panel.node);
1704
+ if (panel.contribution) {
1705
+ const { id, ...descriptor } = panel.contribution;
1706
+ if (panel.slot !== contributionSlot(id))
1707
+ throw new Error("Contribution slot does not match its id");
1708
+ validateContribution(id, {
1709
+ ...descriptor,
1710
+ title: panel.title,
1711
+ node: panel.node,
1712
+ mobileFallback: panel.mobileFallback,
1713
+ ...panel.state === void 0 ? {} : { state: panel.state }
1714
+ });
1715
+ }
1716
+ } catch (error) {
1717
+ ctx.addIssue({ code: "custom", message: error.message });
1718
+ }
1719
+ });
1720
+ var AdapterPreviewSchema = z7.unknown().transform(bounded).pipe(z7.object({
1721
+ version: z7.literal(1),
1722
+ name: z7.string().min(1).max(200),
1723
+ adapter: z7.object({ id: Id5, version: Id5 }).strict(),
1724
+ steps: z7.array(z7.object({
1725
+ index: z7.number().int().min(0).max(ADAPTER_PREVIEW_MAX_STEPS - 1),
1726
+ kind: z7.enum([
1727
+ "restore",
1728
+ "toolStart",
1729
+ "toolUpdate",
1730
+ "toolEnd",
1731
+ "status",
1732
+ "widget",
1733
+ "dialog",
1734
+ "answer",
1735
+ "customMessage",
1736
+ "action"
1737
+ ]),
1738
+ ok: z7.boolean(),
1739
+ error: z7.string().max(4e3).nullable()
1740
+ }).strict()).max(ADAPTER_PREVIEW_MAX_STEPS),
1741
+ panels: z7.array(PreviewPanel).max(256),
1742
+ interactions: z7.array(z7.object({
1743
+ request: AdapterPreviewPiUiRequestSchema,
1744
+ presentation: PortableNode,
1745
+ state: z7.enum(["pending", "resolved"])
1746
+ }).strict()).max(ADAPTER_PREVIEW_MAX_STEPS),
1747
+ cards: z7.array(z7.unknown().transform((input, ctx) => {
1748
+ try {
1749
+ return validateContributionCard(input);
1750
+ } catch (error) {
1751
+ ctx.addIssue({ code: "custom", message: error.message });
1752
+ return z7.NEVER;
1753
+ }
1754
+ })).max(ADAPTER_PREVIEW_MAX_STEPS * 3),
1755
+ diagnostics: z7.array(Diagnostic.extend({ message: z7.string().max(4e3) }).refine((d) => d.sessionId === null || d.sessionId === ADAPTER_PREVIEW_SESSION_ID, "Preview diagnostics must use the fake preview session")).max(200)
1756
+ }).strict().superRefine((preview, ctx) => {
1757
+ const slots = /* @__PURE__ */ new Set();
1758
+ let contributions = 0;
1759
+ for (const panel of preview.panels) {
1760
+ if (panel.adapterId !== preview.adapter.id)
1761
+ ctx.addIssue({
1762
+ code: "custom",
1763
+ message: "Preview panel belongs to a different adapter"
1764
+ });
1765
+ const key = JSON.stringify([panel.adapterId, panel.slot]);
1766
+ if (slots.has(key))
1767
+ ctx.addIssue({ code: "custom", message: "Duplicate preview panel slot" });
1768
+ slots.add(key);
1769
+ if (panel.contribution && ++contributions > 64)
1770
+ ctx.addIssue({
1771
+ code: "custom",
1772
+ message: "At most 64 contributions per adapter/session"
1773
+ });
1774
+ }
1775
+ const requests = /* @__PURE__ */ new Set();
1776
+ for (const interaction of preview.interactions) {
1777
+ if (requests.has(interaction.request.id))
1778
+ ctx.addIssue({ code: "custom", message: "Duplicate preview dialog" });
1779
+ requests.add(interaction.request.id);
1780
+ }
1781
+ }));
1782
+
1783
+ // packages/protocol/dist/adapters.js
1784
+ import { z as z8 } from "zod";
1785
+ var Path = z8.string().max(4096);
1786
+ var SessionAdapterInfo = AdapterInfo.extend({
1787
+ runtimeStatus: z8.enum(["active", "disabled", "unavailable"]),
1788
+ runtimeDetail: z8.string().max(4e3).nullable(),
1789
+ provenance: z8.object({
1790
+ scope: z8.enum(["user", "project", "explicit"]),
1791
+ source: Path.nullable(),
1792
+ packageDir: Path.nullable(),
1793
+ manifestPath: Path.nullable(),
1794
+ targetVersion: z8.string().nullable(),
1795
+ entrypoints: z8.array(Path).max(128),
1796
+ evidence: z8.enum(["runtime-reported", "package-level", "explicit"])
1797
+ })
1798
+ });
1799
+ var SessionAdaptersResult = z8.object({
1800
+ generation: z8.string().uuid().nullable(),
1801
+ runtimeId: z8.string().nullable(),
1802
+ reloadable: z8.boolean(),
1803
+ blockedReason: z8.string().nullable(),
1804
+ adapters: z8.array(SessionAdapterInfo).max(256),
1805
+ diagnostics: z8.array(Diagnostic).max(100)
1806
+ });
1807
+
1808
+ // packages/protocol/dist/agent-wire.js
1809
+ import { z as z9 } from "zod";
1810
+ var Id6 = z9.string().min(1).max(200);
1811
+ var Instant3 = z9.string().refine((value) => {
1812
+ const date = new Date(value);
1813
+ return Number.isFinite(date.getTime()) && date.toISOString() === value;
1814
+ }, "Expected canonical UTC timestamp");
1815
+ var AGENT_FRAME_MAX_BYTES = 128 * 1024;
1816
+ var AgentMethod = z9.enum([
1817
+ "session.bind",
1818
+ "task.create",
1819
+ "message.send",
1820
+ "inbox.read",
1821
+ "receipt.peek",
1822
+ "policy.evaluate",
1823
+ "policy.status",
1824
+ "policy.cancel"
1825
+ ]);
1826
+ var AgentToolMethod = z9.enum(["task.create", "message.send", "inbox.read"]);
1827
+ var RequestHash = z9.string().regex(/^[a-f0-9]{64}$/);
1828
+ var AgentReceiptPeekRequest = z9.object({ method: AgentToolMethod, args: z9.record(z9.string(), z9.json()) }).strict();
1829
+ var AgentReceiptPeekResult = z9.discriminatedUnion("found", [
1830
+ z9.object({ found: z9.literal(false) }).strict(),
1831
+ z9.object({ found: z9.literal(true), requestHash: RequestHash }).strict()
1832
+ ]);
1833
+ var AgentReceiptReplay = z9.object({ requestHash: RequestHash }).strict();
1834
+ var CreateAgentTask = z9.object({
1835
+ objective: z9.string().min(1).max(16e3),
1836
+ acceptance: z9.array(z9.string().min(1).max(2e3)).max(100).default([]),
1837
+ dependencies: z9.array(Id6).max(100).default([]),
1838
+ parentTaskId: Id6.nullable().optional(),
1839
+ hostId: Id6.optional(),
1840
+ profileId: Id6.optional(),
1841
+ notifyOnFinish: z9.boolean().default(true)
1842
+ });
1843
+ var SendAgentMessage = z9.object({
1844
+ sessionId: Id6,
1845
+ body: z9.string().min(1).max(16e3),
1846
+ mode: z9.enum(["steer", "queue"]),
1847
+ replyTo: Id6.optional()
1848
+ });
1849
+ var ReadAgentInbox = z9.object({
1850
+ after: z9.number().int().nonnegative().default(0),
1851
+ limit: z9.number().int().min(1).max(100).default(20)
1852
+ });
1853
+ var DeliveryState = z9.enum([
1854
+ "pending",
1855
+ "held",
1856
+ "deferred",
1857
+ "accepted",
1858
+ "queued",
1859
+ "appended",
1860
+ "uncertain",
1861
+ "failed"
1862
+ ]);
1863
+ var AgentMessageFields = {
1864
+ seq: z9.number().int().positive(),
1865
+ id: Id6,
1866
+ recipientSessionId: Id6,
1867
+ replyTo: Id6.nullable(),
1868
+ chainId: Id6,
1869
+ depth: z9.number().int().min(0).max(4),
1870
+ body: z9.unknown(),
1871
+ requestedMode: z9.enum(["steer", "queue"]),
1872
+ deliveryState: DeliveryState,
1873
+ holdUntil: z9.string(),
1874
+ readAt: z9.string().nullable(),
1875
+ createdAt: z9.string()
1876
+ };
1877
+ var AgentMessage = z9.discriminatedUnion("kind", [
1878
+ z9.object({ ...AgentMessageFields, kind: z9.literal("message"), senderSessionId: Id6 }),
1879
+ z9.object({
1880
+ ...AgentMessageFields,
1881
+ kind: z9.literal("completion"),
1882
+ senderSessionId: Id6.nullable()
1883
+ })
1884
+ ]);
1885
+ var AgentInbox = z9.object({
1886
+ messages: z9.array(AgentMessage),
1887
+ nextAfter: z9.number().int().nonnegative(),
1888
+ hasMore: z9.boolean()
1889
+ });
1890
+ var AgentToolPolicyWait = PolicyEvaluation.options[2].omit({ verdict: true }).extend({ type: z9.literal("policy.required") }).strict();
1891
+ var AgentRequestFrame = z9.object({
1892
+ type: z9.literal("agent.request"),
1893
+ requestId: Id6,
1894
+ sessionId: Id6,
1895
+ nativeSessionId: Id6,
1896
+ runtimeId: Id6,
1897
+ context: z9.object({ humanInputId: Id6.nullable(), causalMessageId: Id6.nullable() }).strict(),
1898
+ toolCallId: Id6.optional(),
1899
+ receiptReplay: AgentReceiptReplay.optional(),
1900
+ // Tool-method ingress requires this separately; legacy/non-tool frames remain compatible.
1901
+ deadlineAt: Instant3.optional(),
1902
+ method: AgentMethod,
1903
+ args: z9.unknown()
1904
+ }).strict().superRefine((frame, ctx) => {
1905
+ if (frame.method === "receipt.peek") {
1906
+ if (!frame.toolCallId) {
1907
+ ctx.addIssue({
1908
+ code: "custom",
1909
+ path: ["toolCallId"],
1910
+ message: "Receipt lookup requires a tool call ID."
1911
+ });
1912
+ }
1913
+ }
1914
+ if (Object.hasOwn(frame, "receiptReplay") && !AgentToolMethod.safeParse(frame.method).success) {
1915
+ ctx.addIssue({
1916
+ code: "custom",
1917
+ path: ["receiptReplay"],
1918
+ message: "Receipt replay is only valid for tool methods."
1919
+ });
1920
+ }
1921
+ });
1922
+ var AgentResultFrame = z9.discriminatedUnion("ok", [
1923
+ z9.object({
1924
+ type: z9.literal("agent.result"),
1925
+ requestId: Id6,
1926
+ runtimeId: Id6,
1927
+ ok: z9.literal(true),
1928
+ result: z9.unknown()
1929
+ }),
1930
+ z9.object({
1931
+ type: z9.literal("agent.result"),
1932
+ requestId: Id6,
1933
+ runtimeId: Id6,
1934
+ ok: z9.literal(false),
1935
+ error: ErrorBody
1936
+ })
1937
+ ]);
1938
+
1939
+ // packages/protocol/dist/api.js
1940
+ import { z as z13 } from "zod";
1941
+
1942
+ // packages/protocol/dist/host-wire.js
1943
+ import { z as z12 } from "zod";
1944
+
1945
+ // packages/protocol/dist/events.js
1946
+ import { z as z10 } from "zod";
1947
+ var EventDataSchemas = {
1948
+ "host.updated": Host,
1949
+ "project.updated": Project,
1950
+ "project.deleted": z10.object({ id: z10.string() }),
1951
+ "checkout.updated": Checkout,
1952
+ "workspace.updated": Workspace,
1953
+ "workspace.deleted": z10.object({ id: z10.string() }),
1954
+ "profile.updated": Profile,
1955
+ "profile.deleted": z10.object({ id: z10.string() }),
1956
+ "view.updated": View,
1957
+ "view.deleted": z10.object({ id: z10.string() }),
1958
+ "session.updated": Session,
1959
+ "transcript.item": TranscriptItem,
1960
+ "transcript.reset": z10.object({ sessionId: z10.string(), epoch: z10.number().int() }),
1961
+ "interaction.updated": Interaction,
1962
+ "panel.updated": Panel,
1963
+ "adapters.updated": z10.object({ hostId: z10.string(), adapters: z10.array(AdapterInfo) }),
1964
+ diagnostic: Diagnostic,
1965
+ "task.updated": Task,
1966
+ "task.deleted": z10.object({ id: z10.string() }),
1967
+ "run.updated": Run,
1968
+ "automation.updated": Automation,
1969
+ "automation.deleted": z10.object({ id: z10.string() }),
1970
+ "occurrence.created": Occurrence,
1971
+ "occurrence.updated": Occurrence,
1972
+ "attention.updated": AttentionItem,
1973
+ "device.updated": Device,
1974
+ "settings.updated": z10.object({ dispatchPaused: z10.boolean() })
1975
+ };
1976
+ var EVENT_TYPES = Object.keys(EventDataSchemas);
1977
+ var LEGACY_EVENT_TYPES = {
1978
+ "workspace.removed": "workspace.deleted"
1979
+ };
1980
+ function canonicalEventType(type) {
1981
+ return LEGACY_EVENT_TYPES[type] ?? type;
1982
+ }
1983
+ var canonical = (v) => typeof v === "string" ? canonicalEventType(v) : v;
1984
+ var EventTypeSchema = z10.preprocess(canonical, z10.enum(EVENT_TYPES));
1985
+ var EventScope = z10.object({
1986
+ hostId: z10.string().optional(),
1987
+ sessionId: z10.string().optional(),
1988
+ taskId: z10.string().optional(),
1989
+ projectId: z10.string().optional()
1990
+ });
1991
+ var EventEnvelope = EventScope.extend({
1992
+ seq: z10.number().int(),
1993
+ id: z10.string(),
1994
+ type: EventTypeSchema,
1995
+ at: z10.string(),
1996
+ data: z10.unknown()
1997
+ });
1998
+ var HOST_EVENT_TYPES = [
1999
+ "session.updated",
2000
+ "transcript.item",
2001
+ "interaction.updated",
2002
+ "panel.updated",
2003
+ "adapters.updated",
2004
+ "diagnostic",
2005
+ "workspace.updated",
2006
+ "workspace.deleted"
2007
+ ];
2008
+ var HostEvent = EventScope.extend({
2009
+ eventId: z10.string(),
2010
+ type: z10.preprocess(canonical, z10.enum(HOST_EVENT_TYPES)),
2011
+ at: z10.string(),
2012
+ data: z10.unknown()
2013
+ });
2014
+ var StreamDelta = z10.object({
2015
+ sessionId: z10.string(),
2016
+ itemId: z10.string(),
2017
+ kind: z10.enum(["text", "thinking", "tool_args", "tool_output"]),
2018
+ delta: z10.string(),
2019
+ order: z10.number().int().optional()
2020
+ });
2021
+
2022
+ // packages/protocol/dist/terminal-wire.js
2023
+ import { z as z11 } from "zod";
2024
+ var Cols = z11.number().int().min(10).max(1e3);
2025
+ var Rows = z11.number().int().min(5).max(500);
2026
+ var TermViewerToServer = z11.discriminatedUnion("t", [
2027
+ z11.object({ t: z11.literal("in"), d: z11.string() }),
2028
+ z11.object({ t: z11.literal("resize"), cols: Cols, rows: Rows }),
2029
+ z11.object({ t: z11.literal("claim") })
2030
+ ]);
2031
+ var TermServerToViewer = z11.discriminatedUnion("t", [
2032
+ z11.object({ t: z11.literal("out"), d: z11.string() }),
2033
+ z11.object({ t: z11.literal("closed"), reason: z11.string() }),
2034
+ z11.object({ t: z11.literal("size"), cols: Cols, rows: Rows, owner: z11.boolean() })
2035
+ ]);
2036
+ var TermCoordinatorMsg = z11.discriminatedUnion("t", [
2037
+ z11.object({
2038
+ t: z11.literal("open"),
2039
+ sessionId: z11.string(),
2040
+ cols: Cols,
2041
+ rows: Rows,
2042
+ passive: z11.boolean().optional()
2043
+ }),
2044
+ z11.object({ t: z11.literal("claim") }),
2045
+ z11.object({ t: z11.literal("in"), d: z11.string() }),
2046
+ z11.object({ t: z11.literal("resize"), cols: Cols, rows: Rows }),
2047
+ z11.object({ t: z11.literal("close") })
2048
+ ]);
2049
+
2050
+ // packages/protocol/dist/host-wire.js
2051
+ var Origin = z12.enum(["human", "automation"]);
2052
+ var HostCommand = z12.discriminatedUnion("type", [
2053
+ z12.object({
2054
+ type: z12.literal("session.start"),
2055
+ sessionId: z12.string(),
2056
+ title: z12.string(),
2057
+ workspacePath: z12.string(),
2058
+ projectId: z12.string().nullable(),
2059
+ profile: Profile,
2060
+ nativeHandle: NativeHandle.nullable(),
2061
+ initialPrompt: z12.string().nullable(),
2062
+ dispatchKey: z12.string().nullable(),
2063
+ controlRevision: z12.number().int(),
2064
+ controlMode: ControlMode,
2065
+ origin: Origin,
2066
+ readOnly: z12.boolean().default(false),
2067
+ policyRequired: z12.boolean().optional()
2068
+ }),
2069
+ z12.object({
2070
+ type: z12.literal("session.deliverMessage"),
2071
+ sessionId: z12.string(),
2072
+ messageId: z12.string(),
2073
+ payload: z12.object({
2074
+ deliveryId: z12.string(),
2075
+ kind: z12.enum(["message", "completion"]),
2076
+ text: z12.string()
2077
+ }),
2078
+ mode: z12.enum(["steer", "queue"]),
2079
+ holdUntil: z12.string()
2080
+ }),
2081
+ HostPolicySampleRequest.extend({ type: z12.literal("session.classifyPolicySample") }),
2082
+ z12.object({
2083
+ type: z12.literal("session.messageStatus"),
2084
+ sessionId: z12.string(),
2085
+ messageIds: z12.array(z12.string().min(1)).min(1).max(100)
2086
+ }),
2087
+ z12.object({
2088
+ type: z12.literal("session.prompt"),
2089
+ sessionId: z12.string(),
2090
+ text: z12.string(),
2091
+ images: z12.array(z12.object({ mimeType: z12.string(), data: z12.string() })).default([]),
2092
+ mode: z12.enum(["prompt", "steer", "followUp"]),
2093
+ origin: Origin,
2094
+ controlRevision: z12.number().int()
2095
+ }),
2096
+ z12.object({ type: z12.literal("session.abort"), sessionId: z12.string(), clearQueue: z12.boolean() }),
2097
+ z12.object({ type: z12.literal("session.stop"), sessionId: z12.string() }),
2098
+ z12.object({
2099
+ type: z12.literal("session.answer"),
2100
+ sessionId: z12.string(),
2101
+ interactionId: z12.string(),
2102
+ revision: z12.number().int(),
2103
+ response: InteractionResponseSchema,
2104
+ deviceId: z12.string()
2105
+ }),
2106
+ z12.object({
2107
+ type: z12.literal("session.adapterAction"),
2108
+ sessionId: z12.string(),
2109
+ generation: z12.string().uuid().optional(),
2110
+ adapterId: z12.string(),
2111
+ actionId: z12.string(),
2112
+ payload: z12.unknown()
2113
+ }),
2114
+ z12.object({
2115
+ type: z12.literal("session.setControl"),
2116
+ sessionId: z12.string(),
2117
+ controlRevision: z12.number().int(),
2118
+ mode: ControlMode
2119
+ }),
2120
+ z12.object({ type: z12.literal("session.rename"), sessionId: z12.string(), title: z12.string() }),
2121
+ z12.object({ type: z12.literal("session.importable") }),
2122
+ z12.object({ type: z12.literal("session.readNative"), sessionFile: z12.string() }),
2123
+ z12.object({ type: z12.literal("session.snapshot"), sessionId: z12.string() }),
2124
+ z12.object({ type: z12.literal("session.models"), sessionId: z12.string() }),
2125
+ z12.object({ type: z12.literal("session.commands"), sessionId: z12.string() }),
2126
+ z12.object({
2127
+ type: z12.literal("session.complete"),
2128
+ sessionId: z12.string(),
2129
+ text: z12.string().max(500)
2130
+ }),
2131
+ z12.object({ type: z12.literal("session.tree"), sessionId: z12.string() }),
2132
+ z12.object({
2133
+ type: z12.literal("session.branch"),
2134
+ sessionId: z12.string(),
2135
+ entryId: z12.string().nullable(),
2136
+ fork: z12.boolean()
2137
+ }),
2138
+ z12.object({
2139
+ type: z12.literal("session.navigate"),
2140
+ sessionId: z12.string(),
2141
+ entryId: z12.string(),
2142
+ summarize: z12.boolean(),
2143
+ instructions: z12.string().max(2e3).nullable()
2144
+ }),
2145
+ z12.object({ type: z12.literal("session.reload"), sessionId: z12.string() }),
2146
+ z12.object({ type: z12.literal("session.adapters"), sessionId: z12.string() }),
2147
+ z12.object({ type: z12.literal("session.reloadAdapters"), sessionId: z12.string() }),
2148
+ z12.object({ type: z12.literal("session.export"), sessionId: z12.string() }),
2149
+ z12.object({
2150
+ type: z12.literal("session.setModel"),
2151
+ sessionId: z12.string(),
2152
+ provider: z12.string().min(1),
2153
+ modelId: z12.string().min(1)
2154
+ }),
2155
+ z12.object({ type: z12.literal("session.setThinking"), sessionId: z12.string(), level: ThinkingLevel }),
2156
+ z12.object({
2157
+ type: z12.literal("session.compact"),
2158
+ sessionId: z12.string(),
2159
+ instructions: z12.string().nullable()
2160
+ }),
2161
+ z12.object({ type: z12.literal("checkout.inspect"), path: z12.string() }),
2162
+ z12.object({ type: z12.literal("projects.scan"), folder: z12.string().min(1) }),
2163
+ z12.object({
2164
+ type: z12.literal("projects.suggest"),
2165
+ days: z12.number().int().min(1).max(365).default(30)
2166
+ }),
2167
+ z12.object({
2168
+ type: z12.literal("workspace.discover"),
2169
+ checkoutPath: z12.string(),
2170
+ worktreeDir: z12.string().default(DEFAULT_WORKTREE_DIR)
2171
+ }),
2172
+ z12.object({
2173
+ type: z12.literal("workspace.create"),
2174
+ checkoutPath: z12.string(),
2175
+ branch: z12.string(),
2176
+ base: z12.string(),
2177
+ setupCommand: z12.string().nullable(),
2178
+ worktreeDir: z12.string().default(DEFAULT_WORKTREE_DIR)
2179
+ }),
2180
+ z12.object({ type: z12.literal("workspace.status"), path: z12.string(), base: z12.string().nullable() }),
2181
+ z12.object({
2182
+ type: z12.literal("workspace.remove"),
2183
+ path: z12.string(),
2184
+ checkoutPath: z12.string(),
2185
+ base: z12.string().nullable(),
2186
+ force: z12.object({ dirty: z12.boolean(), unmerged: z12.boolean() })
2187
+ }),
2188
+ z12.object({
2189
+ type: z12.literal("workspace.diff"),
2190
+ path: z12.string(),
2191
+ base: z12.string().nullable(),
2192
+ file: z12.string().nullable()
2193
+ }),
2194
+ z12.object({ type: z12.literal("workspace.files"), path: z12.string(), dir: z12.string() }),
2195
+ z12.object({ type: z12.literal("workspace.readFile"), path: z12.string(), file: z12.string() }),
2196
+ GitHubHostViewRequest.extend({ type: z12.literal("workspace.prView") }),
2197
+ GitHubHostLogsRequest.extend({ type: z12.literal("workspace.prFailedLogs") }),
2198
+ GitHubHostMergeRequest.extend({ type: z12.literal("workspace.prMerge") }),
2199
+ z12.object({
2200
+ type: z12.literal("dispatch.start"),
2201
+ dispatchKey: z12.string(),
2202
+ runId: z12.string(),
2203
+ taskId: z12.string(),
2204
+ sessionId: z12.string(),
2205
+ projectId: z12.string(),
2206
+ title: z12.string(),
2207
+ workspace: z12.union([
2208
+ z12.object({ path: z12.string() }),
2209
+ z12.object({
2210
+ createFrom: z12.object({
2211
+ checkoutPath: z12.string(),
2212
+ branch: z12.string(),
2213
+ base: z12.string(),
2214
+ setupCommand: z12.string().nullable(),
2215
+ worktreeDir: z12.string().default(DEFAULT_WORKTREE_DIR)
2216
+ })
2217
+ })
2218
+ ]),
2219
+ nativeHandle: NativeHandle.nullable(),
2220
+ profile: Profile,
2221
+ prompt: z12.string(),
2222
+ /** The launch's own revision; a takeover always carries a newer one. */
2223
+ controlRevision: z12.number().int(),
2224
+ controlMode: ControlMode.default("automation"),
2225
+ policyRequired: z12.boolean().optional()
2226
+ }),
2227
+ z12.object({ type: z12.literal("dispatch.reconcile"), dispatchKey: z12.string() }),
2228
+ z12.object({
2229
+ type: z12.literal("checks.run"),
2230
+ sessionId: z12.string(),
2231
+ path: z12.string(),
2232
+ commands: z12.array(z12.string())
2233
+ })
2234
+ ]);
2235
+ var ImportableSession = z12.object({
2236
+ sessionFile: z12.string(),
2237
+ sessionId: z12.string(),
2238
+ cwd: z12.string(),
2239
+ name: z12.string().nullable(),
2240
+ mtime: z12.string(),
2241
+ inactive: z12.boolean()
2242
+ });
2243
+ var DiscoveredWorktree = z12.object({
2244
+ path: z12.string(),
2245
+ head: z12.string().nullable(),
2246
+ branch: z12.string().nullable(),
2247
+ bare: z12.boolean(),
2248
+ detached: z12.boolean(),
2249
+ locked: z12.boolean(),
2250
+ prunable: z12.boolean(),
2251
+ provenance: z12.enum(["managed", "discovered", "main"]),
2252
+ git: GitState.nullable()
2253
+ });
2254
+ var CheckoutInfo = z12.object({
2255
+ root: z12.string(),
2256
+ commonDir: z12.string(),
2257
+ repoIdentity: z12.string(),
2258
+ defaultBranch: z12.string()
2259
+ });
2260
+ var ScannedRepository = CheckoutInfo.extend({ name: z12.string() });
2261
+ var ProjectFolderScan = z12.object({
2262
+ /** The folder, ~ expanded and realpath'd. */
2263
+ folder: z12.string(),
2264
+ repositories: z12.array(ScannedRepository)
2265
+ });
2266
+ var ProjectSuggestion = z12.object({
2267
+ rootPath: z12.string(),
2268
+ sessionCount: z12.number().int(),
2269
+ lastActivityAt: z12.string()
2270
+ });
2271
+ var ProjectSuggestions = z12.object({ suggestions: z12.array(ProjectSuggestion) });
2272
+ var DiffFile = z12.object({
2273
+ path: z12.string(),
2274
+ oldPath: z12.string().nullable(),
2275
+ added: z12.number().int(),
2276
+ deleted: z12.number().int(),
2277
+ status: z12.enum(["added", "modified", "deleted", "renamed", "untracked", "binary"])
2278
+ });
2279
+ var DiffResult = z12.object({
2280
+ base: z12.string(),
2281
+ files: z12.array(DiffFile),
2282
+ patch: z12.string().nullable()
2283
+ });
2284
+ var FileEntry = z12.object({
2285
+ name: z12.string(),
2286
+ path: z12.string(),
2287
+ kind: z12.enum(["file", "dir", "symlink"]),
2288
+ size: z12.number().int().nullable()
2289
+ });
2290
+ var ReconcileResult = z12.union([
2291
+ z12.object({ known: z12.literal(false) }),
2292
+ z12.object({
2293
+ known: z12.literal(true),
2294
+ sessionId: z12.string().nullable(),
2295
+ state: z12.enum(["accepted", "workspace_ready", "started", "failed"]),
2296
+ runtime: RuntimeState.nullable(),
2297
+ workspacePath: z12.string().nullable(),
2298
+ nativeHandle: NativeHandle.nullable(),
2299
+ error: z12.string().nullable(),
2300
+ /** `{started: "unknown"}` when the host restarted after Pi may have been spawned. */
2301
+ errorDetails: z12.record(z12.string(), z12.unknown()).nullable().default(null)
2302
+ })
2303
+ ]);
2304
+ var DispatchStartResult = z12.object({
2305
+ sessionId: z12.string(),
2306
+ workspacePath: z12.string(),
2307
+ nativeHandle: NativeHandle.nullable(),
2308
+ reused: z12.boolean(),
2309
+ /** Why the launch prompt was not delivered to Pi (the session itself started), if it was not. */
2310
+ promptError: z12.string().nullable().optional()
2311
+ });
2312
+ var AnswerResult = z12.object({
2313
+ status: z12.enum(["answered", "already_answered"]),
2314
+ interaction: Interaction
2315
+ });
2316
+ var SnapshotResult = z12.object({
2317
+ partial: z12.array(TranscriptItem),
2318
+ pendingInteractions: z12.array(Interaction)
2319
+ });
2320
+ var ChecksResult = z12.object({ results: z12.array(CheckResult) });
2321
+ var Receipt = z12.union([
2322
+ z12.object({ commandId: z12.string(), ok: z12.literal(true), result: z12.unknown() }),
2323
+ z12.object({ commandId: z12.string(), ok: z12.literal(false), error: ErrorBody })
2324
+ ]);
2325
+ var HostAgentRequestFrame = AgentRequestFrame.safeExtend({
2326
+ policyContext: HostToolPolicyContext.optional()
2327
+ }).strict().superRefine((frame, ctx) => {
2328
+ if (frame.method === "policy.evaluate" ? frame.policyContext === void 0 : Object.hasOwn(frame, "policyContext")) {
2329
+ ctx.addIssue({
2330
+ code: "custom",
2331
+ path: ["policyContext"],
2332
+ message: "Host policy context is required only for policy.evaluate."
2333
+ });
2334
+ }
2335
+ try {
2336
+ if (new TextEncoder().encode(JSON.stringify(frame)).length <= AGENT_FRAME_MAX_BYTES)
2337
+ return;
2338
+ } catch {
2339
+ }
2340
+ ctx.addIssue({ code: "custom", message: "Host agent frame exceeds 128 KiB or is not JSON." });
2341
+ });
2342
+ var HostToCoordinator = z12.discriminatedUnion("type", [
2343
+ z12.object({
2344
+ type: z12.literal("hello"),
2345
+ hostId: z12.string(),
2346
+ credential: z12.string(),
2347
+ name: z12.string(),
2348
+ agentVersion: z12.string(),
2349
+ piVersion: z12.string().nullable(),
2350
+ piCompatible: z12.boolean(),
2351
+ platform: Platform,
2352
+ capabilities: RuntimeCapabilities.nullable(),
2353
+ github: HostGitHub.optional(),
2354
+ protocolVersion: z12.number().int(),
2355
+ features: z12.array(z12.string()).optional()
2356
+ }),
2357
+ HostAgentRequestFrame,
2358
+ z12.object({ type: z12.literal("event"), hostSeq: z12.number().int(), event: HostEvent }),
2359
+ z12.object({ type: z12.literal("stream"), delta: StreamDelta }),
2360
+ z12.object({ type: z12.literal("receipt"), receipt: Receipt }),
2361
+ z12.object({ type: z12.literal("pong") }),
2362
+ z12.object({ type: z12.literal("usage"), usage: z12.array(ProviderUsage) }),
2363
+ z12.object({ type: z12.literal("term"), streamId: z12.string(), msg: TermServerToViewer })
2364
+ ]);
2365
+ var CoordinatorToHost = z12.discriminatedUnion("type", [
2366
+ z12.object({
2367
+ type: z12.literal("welcome"),
2368
+ coordinatorVersion: z12.string(),
2369
+ ackedHostSeq: z12.number().int(),
2370
+ features: z12.array(z12.string()).optional()
2371
+ }),
2372
+ AgentResultFrame,
2373
+ z12.object({ type: z12.literal("ack"), hostSeq: z12.number().int() }),
2374
+ z12.object({ type: z12.literal("command"), commandId: z12.string(), command: HostCommand }),
2375
+ z12.object({ type: z12.literal("ping") }),
2376
+ z12.object({ type: z12.literal("reject"), error: ErrorBody }),
2377
+ z12.object({ type: z12.literal("term"), streamId: z12.string(), msg: TermCoordinatorMsg })
2378
+ ]);
2379
+
2380
+ // packages/protocol/dist/api.js
2381
+ var EnrollRequest = z13.object({
2382
+ token: z13.string().min(1),
2383
+ name: z13.string().min(1).max(80),
2384
+ kind: DeviceKind
2385
+ });
2386
+ var EnrollResponse = z13.object({ deviceId: z13.string(), credential: z13.string() });
2387
+ var CreateEnrollmentRequest = z13.object({ kind: z13.enum(["device", "host"]) });
2388
+ var CreateEnrollmentResponse = z13.object({
2389
+ token: z13.string(),
2390
+ url: z13.string(),
2391
+ expiresAt: z13.string(),
2392
+ qrSvg: z13.string(),
2393
+ command: z13.string().nullable()
2394
+ });
2395
+ var HostEnrollRequest = z13.union([
2396
+ z13.object({
2397
+ token: z13.string().min(1),
2398
+ name: z13.string().min(1).max(80),
2399
+ platform: Platform
2400
+ }),
2401
+ z13.object({
2402
+ secret: z13.string().min(1),
2403
+ name: z13.string().min(1).max(80),
2404
+ platform: Platform
2405
+ })
2406
+ ]);
2407
+ var HostEnrollResponse = z13.object({ hostId: z13.string(), credential: z13.string() });
2408
+ var CreateProjectRequest = z13.object({
2409
+ name: z13.string().min(1),
2410
+ hostId: z13.string(),
2411
+ path: z13.string().min(1),
2412
+ defaultProfileId: z13.string().nullable().optional(),
2413
+ setupCommand: z13.string().nullable().optional(),
2414
+ checks: z13.array(z13.string()).optional(),
2415
+ maxConcurrentRuns: z13.number().int().min(1).max(32).optional(),
2416
+ worktreeDir: WorktreeDir.optional()
2417
+ });
2418
+ var UpdateProjectRequest = z13.object({
2419
+ name: z13.string().min(1).optional(),
2420
+ defaultProfileId: z13.string().nullable().optional(),
2421
+ defaultHostId: z13.string().nullable().optional(),
2422
+ maxConcurrentRuns: z13.number().int().min(1).max(32).optional(),
2423
+ automationEnabled: z13.boolean().optional(),
2424
+ setupCommand: z13.string().nullable().optional(),
2425
+ checks: z13.array(z13.string()).optional(),
2426
+ workspaceSharing: z13.enum(["single_writer", "shared"]).optional(),
2427
+ worktreeDir: WorktreeDir.optional()
2428
+ });
2429
+ var AddCheckoutRequest = z13.object({ hostId: z13.string(), path: z13.string().min(1) });
2430
+ function isProjectFolderPath(s) {
2431
+ if (s.includes("\0"))
2432
+ return false;
2433
+ return s === "~" || s.startsWith("~/") || s.startsWith("/");
2434
+ }
2435
+ var ProjectFolder = z13.string().trim().min(1).max(1024).refine(isProjectFolderPath, "must be an absolute path or start with ~/");
2436
+ var UpdateHostRequest = z13.object({
2437
+ projectFolders: z13.array(ProjectFolder).max(20).optional()
2438
+ });
2439
+ var ProjectScanResult = ProjectScan.extend({
2440
+ added: z13.array(z13.object({
2441
+ projectId: z13.string(),
2442
+ name: z13.string(),
2443
+ path: z13.string(),
2444
+ newProject: z13.boolean()
2445
+ }))
2446
+ });
2447
+ var ProfileInput = z13.object({
2448
+ name: z13.string().min(1),
2449
+ provider: z13.string().nullable().default(null),
2450
+ model: z13.string().nullable().default(null),
2451
+ thinking: ThinkingLevel.nullable().default(null),
2452
+ projectTrust: z13.enum(["ask", "approve", "ignore"]).default("ask"),
2453
+ extraArgs: z13.array(ExtraArg).default([]),
2454
+ resources: z13.enum(["all", "vanilla"]).default("all")
2455
+ });
2456
+ var CreateWorkspaceRequest = z13.object({
2457
+ checkoutId: z13.string(),
2458
+ branch: z13.string().min(1),
2459
+ base: z13.string().nullable().optional()
2460
+ });
2461
+ var RemoveWorkspaceRequest = z13.object({
2462
+ force: z13.object({ dirty: z13.boolean(), unmerged: z13.boolean() }).default({ dirty: false, unmerged: false })
2463
+ });
2464
+ var CreateSessionRequest = z13.object({
2465
+ projectId: z13.string(),
2466
+ workspace: z13.union([
2467
+ z13.object({ existingId: z13.string() }),
2468
+ z13.object({
2469
+ checkoutId: z13.string(),
2470
+ newBranch: z13.string().min(1),
2471
+ base: z13.string().nullable().optional()
2472
+ })
2473
+ ]),
2474
+ profileId: z13.string().nullable().optional(),
2475
+ prompt: z13.string().default(""),
2476
+ title: z13.string().optional(),
2477
+ viewId: z13.string().optional()
2478
+ });
2479
+ var PromptRequest = z13.object({
2480
+ text: z13.string().min(1),
2481
+ mode: z13.enum(["prompt", "steer", "followUp"]).default("prompt"),
2482
+ images: z13.array(z13.object({ mimeType: z13.string(), data: z13.string() })).default([]),
2483
+ clientMessageId: z13.string().optional()
2484
+ });
2485
+ var CacheAlertRequest = z13.object({
2486
+ enabled: z13.boolean(),
2487
+ ttlSec: z13.number().int().min(60).max(86400).nullable().default(null)
2488
+ });
2489
+ var RenameRequest = z13.object({ title: z13.string().min(1).max(200) });
2490
+ var SetModelRequest = z13.object({
2491
+ provider: z13.string().min(1),
2492
+ modelId: z13.string().min(1)
2493
+ });
2494
+ var SetThinkingRequest = z13.object({ level: ThinkingLevel });
2495
+ var CompactRequest = z13.object({ instructions: z13.string().max(4e3).optional() });
2496
+ var SessionModelsResult = z13.object({ models: z13.array(SessionModel) });
2497
+ var SessionCommandsResult = z13.object({ commands: z13.array(SlashCommand) });
2498
+ var CompleteRequest = z13.object({ text: z13.string().min(1).max(500) });
2499
+ var CompletionItem = z13.object({
2500
+ value: z13.string(),
2501
+ label: z13.string(),
2502
+ description: z13.string().nullable()
2503
+ });
2504
+ var SessionCompleteResult = z13.object({
2505
+ items: z13.array(CompletionItem).max(50),
2506
+ prefix: z13.string()
2507
+ });
2508
+ var TreeRow = z13.object({
2509
+ entryId: z13.string(),
2510
+ parentId: z13.string().nullable(),
2511
+ depth: z13.number().int(),
2512
+ role: z13.enum(["user", "assistant"]),
2513
+ text: z13.string(),
2514
+ activeBranch: z13.boolean(),
2515
+ leaf: z13.boolean(),
2516
+ label: z13.string().nullable(),
2517
+ at: z13.string().nullable()
2518
+ });
2519
+ var SessionTreeResult = z13.object({ rows: z13.array(TreeRow) });
2520
+ var BranchRequest = z13.object({
2521
+ entryId: z13.string().nullable(),
2522
+ fork: z13.boolean().default(false)
2523
+ });
2524
+ var HostBranchResult = z13.object({
2525
+ sessionFile: z13.string().nullable(),
2526
+ prefill: z13.string().nullable()
2527
+ });
2528
+ var TranscriptPage = z13.object({
2529
+ items: z13.array(TranscriptItem),
2530
+ hasMore: z13.boolean(),
2531
+ epoch: z13.number().int().optional(),
2532
+ rev: z13.number().int().optional(),
2533
+ delta: z13.boolean().optional(),
2534
+ reset: z13.boolean().optional()
2535
+ });
2536
+ var NavigateRequest = z13.object({
2537
+ entryId: z13.string().min(1),
2538
+ summarize: z13.boolean().default(false),
2539
+ instructions: z13.string().max(2e3).nullable().default(null)
2540
+ });
2541
+ var HostNavigateResult = z13.object({
2542
+ items: z13.array(TranscriptItem),
2543
+ prefill: z13.string().nullable()
2544
+ });
2545
+ var NavigateResult = z13.object({
2546
+ prefill: z13.string().nullable(),
2547
+ epoch: z13.number().int()
2548
+ });
2549
+ var BranchResult = z13.object({
2550
+ session: Session.nullable(),
2551
+ prefill: z13.string().nullable()
2552
+ });
2553
+ var SessionExportResult = z13.object({ fileName: z13.string(), content: z13.string() });
2554
+ var CommandViewAction = z13.object({
2555
+ label: z13.string().min(1).max(80),
2556
+ command: z13.string().startsWith("/").max(500),
2557
+ tone: z13.enum(["default", "primary", "danger"]).optional()
2558
+ });
2559
+ var CommandView = z13.object({
2560
+ title: z13.string().min(1).max(200),
2561
+ body: UINodeSchema,
2562
+ actions: z13.array(CommandViewAction).max(30).default([])
2563
+ });
2564
+ var ModelStateResult = z13.object({
2565
+ model: SessionModel.nullable(),
2566
+ thinking: ThinkingLevel.nullable()
2567
+ });
2568
+ var ImportSessionRequest = z13.object({
2569
+ hostId: z13.string(),
2570
+ sessionFile: z13.string(),
2571
+ projectId: z13.string().nullable().optional()
2572
+ });
2573
+ var AnswerRequest = z13.object({
2574
+ revision: z13.number().int(),
2575
+ response: InteractionResponseSchema
2576
+ });
2577
+ var AdapterActionRequest = z13.object({
2578
+ generation: z13.string().uuid().optional(),
2579
+ adapterId: z13.string(),
2580
+ actionId: z13.string(),
2581
+ payload: z13.unknown().optional()
2582
+ });
2583
+ var TaskPolicyPatch = z13.object({
2584
+ hostId: z13.string().nullable().optional(),
2585
+ profileId: z13.string().nullable().optional(),
2586
+ workspace: z13.object({
2587
+ mode: z13.enum(["new_worktree", "existing"]).optional(),
2588
+ branch: z13.string().nullable().optional(),
2589
+ base: z13.string().nullable().optional(),
2590
+ workspaceId: z13.string().optional()
2591
+ }).optional(),
2592
+ continuation: z13.object({
2593
+ enabled: z13.boolean().optional(),
2594
+ objective: z13.string().min(1).optional(),
2595
+ maxContinuations: z13.number().int().min(1).max(50).optional(),
2596
+ maxElapsedMinutes: z13.number().int().min(1).max(1440).optional(),
2597
+ maxTokens: z13.number().int().positive().nullable().optional(),
2598
+ maxCostUsd: z13.number().positive().nullable().optional()
2599
+ }).optional(),
2600
+ completion: CompletionPolicy.partial().optional()
2601
+ });
2602
+ var CreateTaskRequest = z13.object({
2603
+ projectId: z13.string(),
2604
+ title: z13.string().max(300).optional(),
2605
+ githubIssueUrl: GitHubIssueUrl.optional(),
2606
+ githubIssue: z13.never().optional(),
2607
+ launchPrompt: z13.never().optional(),
2608
+ objective: z13.string().default(""),
2609
+ acceptanceCriteria: z13.array(z13.string()).default([]),
2610
+ dependencies: z13.array(z13.string()).default([]),
2611
+ parentTaskId: z13.string().nullable().optional(),
2612
+ priority: Priority.default(2),
2613
+ state: z13.enum(["backlog", "ready"]).default("backlog"),
2614
+ notBefore: z13.string().nullable().optional(),
2615
+ policy: TaskPolicyPatch.optional()
2616
+ }).superRefine((v, ctx) => {
2617
+ if (v.githubIssueUrl === void 0) {
2618
+ if (v.title === void 0 || v.title.length === 0)
2619
+ ctx.addIssue({ code: "custom", path: ["title"], message: "Title is required." });
2620
+ return;
2621
+ }
2622
+ if (v.objective.trim())
2623
+ ctx.addIssue({
2624
+ code: "custom",
2625
+ path: ["objective"],
2626
+ message: "Issue imports use the issue as their initial objective; leave Objective empty."
2627
+ });
2628
+ if (v.acceptanceCriteria.length)
2629
+ ctx.addIssue({
2630
+ code: "custom",
2631
+ path: ["acceptanceCriteria"],
2632
+ message: "Issue imports read acceptance from the issue; leave acceptance criteria empty at creation."
2633
+ });
2634
+ if (v.policy?.continuation?.enabled === true)
2635
+ ctx.addIssue({
2636
+ code: "custom",
2637
+ path: ["policy", "continuation", "enabled"],
2638
+ message: "Issue imports start with continuation disabled."
2639
+ });
2640
+ if (v.policy?.completion?.requireHumanReview === false)
2641
+ ctx.addIssue({
2642
+ code: "custom",
2643
+ path: ["policy", "completion", "requireHumanReview"],
2644
+ message: "Issue imports require human review when created."
2645
+ });
2646
+ }).transform((v) => {
2647
+ if (v.githubIssueUrl === void 0)
2648
+ return { ...v, title: v.title };
2649
+ const issue = githubIssueFromUrl(v.githubIssueUrl);
2650
+ return { ...v, title: v.title?.trim() || `${issue.repository} #${issue.number}` };
2651
+ });
2652
+ var UpdateTaskRequest = z13.object({
2653
+ githubIssueUrl: z13.never().optional(),
2654
+ githubIssue: z13.never().optional(),
2655
+ launchPrompt: z13.never().optional(),
2656
+ title: z13.string().min(1).max(300).optional(),
2657
+ objective: z13.string().optional(),
2658
+ acceptanceCriteria: z13.array(z13.string()).optional(),
2659
+ dependencies: z13.array(z13.string()).optional(),
2660
+ parentTaskId: z13.string().nullable().optional(),
2661
+ priority: Priority.optional(),
2662
+ position: z13.number().optional(),
2663
+ notBefore: z13.string().nullable().optional(),
2664
+ policy: TaskPolicyPatch.optional()
2665
+ });
2666
+ var MoveTaskRequest = z13.object({
2667
+ to: TaskState,
2668
+ confirm: z13.boolean().optional(),
2669
+ onRunning: z13.enum(["pause", "stop"]).optional(),
2670
+ position: z13.number().optional()
2671
+ });
2672
+ var RequestChangesRequest = z13.object({ feedback: z13.array(z13.string().min(1)).min(1) });
2673
+ var Eligibility = z13.union([
2674
+ z13.object({ eligible: z13.literal(true), hostId: z13.string(), hostName: z13.string() }),
2675
+ z13.object({
2676
+ eligible: z13.literal(false),
2677
+ wait: z13.enum([
2678
+ "dependency",
2679
+ "host_offline",
2680
+ "project_limit",
2681
+ "workspace_occupied",
2682
+ "scheduled_time",
2683
+ "invalid_configuration",
2684
+ "dispatch_paused",
2685
+ "project_automation_disabled",
2686
+ "not_ready",
2687
+ "already_dispatched",
2688
+ "retry_backoff"
2689
+ ]),
2690
+ message: z13.string()
2691
+ })
2692
+ ]);
2693
+ var NowResponse = z13.object({
2694
+ running: z13.array(z13.object({ taskId: z13.string(), runId: z13.string(), sessionId: z13.string().nullable() })),
2695
+ queued: z13.array(z13.object({ taskId: z13.string(), eligibility: Eligibility })),
2696
+ dispatchPaused: z13.boolean()
2697
+ });
2698
+ var AutomationInput = z13.object({
2699
+ name: z13.string().min(1),
2700
+ enabled: z13.boolean().default(true),
2701
+ projectId: z13.string(),
2702
+ trigger: Trigger,
2703
+ filters: z13.array(z13.object({ path: z13.string(), equals: z13.string() })).default([]),
2704
+ template: TaskTemplate,
2705
+ hostId: z13.string().nullable().default(null),
2706
+ profileId: z13.string().nullable().default(null),
2707
+ mode: z13.enum(["fresh", "continue", "watch"]).default("fresh"),
2708
+ groupingKey: z13.string().nullable().default(null),
2709
+ overlap: z13.enum(["skip", "queue_one", "append"]).default("skip"),
2710
+ missed: z13.enum(["skip", "run_once"]).default("skip"),
2711
+ continuation: ContinuationPolicy.default({ enabled: false }),
2712
+ completion: CompletionPolicy.default({ checks: null, requireHumanReview: true })
2713
+ });
2714
+ var AutomationView = Automation.extend({ summary: z13.string() });
2715
+ var AutomationPreview = z13.object({
2716
+ summary: z13.string(),
2717
+ task: TaskTemplate,
2718
+ next: z13.array(z13.string())
2719
+ });
2720
+ var WebhookTokenResponse = z13.object({ token: z13.string(), url: z13.string() });
2721
+ var PushSubscriptionRequest = z13.object({
2722
+ endpoint: z13.string().url(),
2723
+ keys: z13.object({ p256dh: z13.string(), auth: z13.string() }),
2724
+ permission: z13.enum(["granted", "denied", "default", "unknown"]).default("granted")
2725
+ });
2726
+ var NotificationSettings = z13.object({
2727
+ quietHours: z13.object({
2728
+ start: z13.string().regex(/^\d{2}:\d{2}$/),
2729
+ end: z13.string().regex(/^\d{2}:\d{2}$/),
2730
+ timezone: z13.string()
2731
+ }).nullable(),
2732
+ privatePreviews: z13.boolean(),
2733
+ preferredDeviceId: z13.string().nullable()
2734
+ });
2735
+ var PushPayload = z13.union([
2736
+ z13.object({
2737
+ type: z13.literal("show"),
2738
+ title: z13.string(),
2739
+ body: z13.string(),
2740
+ tag: z13.string(),
2741
+ url: z13.string(),
2742
+ renotify: z13.boolean()
2743
+ }),
2744
+ z13.object({ type: z13.literal("clear"), tag: z13.string() })
2745
+ ]);
2746
+ var SetupState = z13.object({
2747
+ passkey: z13.object({
2748
+ available: z13.boolean(),
2749
+ registered: z13.boolean(),
2750
+ reason: z13.string().nullable()
2751
+ }),
2752
+ oidc: z13.object({ label: z13.string() }).nullable()
2753
+ });
2754
+ var PasskeyRegisterOptionsResponse = z13.object({
2755
+ challengeId: z13.string(),
2756
+ options: z13.unknown()
2757
+ });
2758
+ var PasskeyRegisterVerifyRequest = z13.object({
2759
+ challengeId: z13.string(),
2760
+ name: z13.string().min(1).max(80),
2761
+ response: z13.unknown()
2762
+ });
2763
+ var PasskeySignInOptionsResponse = z13.object({
2764
+ challengeId: z13.string(),
2765
+ options: z13.unknown()
2766
+ });
2767
+ var PasskeySignInVerifyRequest = z13.object({
2768
+ challengeId: z13.string(),
2769
+ response: z13.unknown(),
2770
+ deviceName: z13.string().min(1).max(80),
2771
+ kind: DeviceKind.extract(["browser", "pwa"])
2772
+ });
2773
+ var OidcBeginRequest = z13.object({
2774
+ deviceName: z13.string().min(1).max(80),
2775
+ kind: DeviceKind.extract(["browser", "pwa"]),
2776
+ next: z13.string().default("/"),
2777
+ handoff: z13.boolean().default(false)
2778
+ });
2779
+ var OidcBeginResponse = z13.object({
2780
+ authorizeUrl: z13.string(),
2781
+ flowId: z13.string().nullable(),
2782
+ pollToken: z13.string().nullable()
2783
+ });
2784
+ var OidcClaimRequest = z13.object({ flowId: z13.string(), pollToken: z13.string() });
2785
+ var OidcClaimResponse = z13.union([
2786
+ z13.object({ status: z13.literal("pending") }),
2787
+ z13.object({ status: z13.literal("done"), deviceId: z13.string() })
2788
+ ]);
2789
+ var TerminalLoginStartRequest = z13.object({ name: z13.string().min(1).max(80) });
2790
+ var TerminalLoginStartResponse = z13.object({
2791
+ userCode: z13.string(),
2792
+ pollToken: z13.string(),
2793
+ verifyUrl: z13.string(),
2794
+ expiresAt: z13.string(),
2795
+ intervalMs: z13.number().int()
2796
+ });
2797
+ var TerminalLoginClaimRequest = z13.object({
2798
+ userCode: z13.string().min(1),
2799
+ pollToken: z13.string().min(1)
2800
+ });
2801
+ var TerminalLoginClaimResponse = z13.union([
2802
+ z13.object({ status: z13.literal("pending") }),
2803
+ z13.object({ status: z13.literal("denied") }),
2804
+ z13.object({ status: z13.literal("done"), deviceId: z13.string(), credential: z13.string() })
2805
+ ]);
2806
+ var TerminalLoginRequest = z13.object({
2807
+ userCode: z13.string(),
2808
+ name: z13.string(),
2809
+ requestedFrom: z13.string(),
2810
+ createdAt: z13.string(),
2811
+ expiresAt: z13.string(),
2812
+ status: z13.enum(["pending", "approved", "denied"])
2813
+ });
2814
+ var AuthMethods = z13.object({
2815
+ passkeys: z13.array(Passkey),
2816
+ passkeyAvailability: z13.object({ available: z13.boolean(), reason: z13.string().nullable() }),
2817
+ oidc: z13.object({
2818
+ issuer: z13.string(),
2819
+ label: z13.string(),
2820
+ ownerMatch: z13.string(),
2821
+ status: z13.enum(["ready", "error"]),
2822
+ error: z13.string().nullable()
2823
+ }).nullable()
2824
+ });
2825
+ var MeResponse = z13.object({
2826
+ device: Device,
2827
+ admin: z13.boolean(),
2828
+ publicUrl: z13.string()
2829
+ });
2830
+ var ViewInput = View.pick({
2831
+ name: true,
2832
+ mode: true,
2833
+ projectIds: true,
2834
+ hostIds: true
2835
+ }).partial({
2836
+ mode: true,
2837
+ projectIds: true,
2838
+ hostIds: true
2839
+ });
2840
+ var ViewPatch = ViewInput.partial();
2841
+ var ViewClientReport = ViewClient.omit({ lastSeenAt: true });
2842
+ var ProjectSuggestionsResponse = z13.object({
2843
+ suggestions: z13.array(ProjectSuggestion.extend({ name: z13.string(), preselected: z13.boolean() }))
2844
+ });
2845
+
2846
+ // packages/protocol/dist/backoff.js
2847
+ var RECONNECT_BACKOFF_MS = [1e3, 2e3, 5e3, 1e4, 2e4, 3e4];
2848
+ function reconnectDelay(attempt, steps = RECONNECT_BACKOFF_MS, random = Math.random) {
2849
+ const base = steps[Math.min(Math.max(attempt, 0), steps.length - 1)] ?? 3e4;
2850
+ return Math.max(0, Math.round(base * (0.8 + random() * 0.4)));
2851
+ }
2852
+
2853
+ // packages/protocol/dist/client-wire.js
2854
+ import { z as z14 } from "zod";
2855
+ var SyncState = z14.object({
2856
+ hosts: z14.array(Host),
2857
+ projects: z14.array(Project),
2858
+ checkouts: z14.array(Checkout),
2859
+ workspaces: z14.array(Workspace),
2860
+ profiles: z14.array(Profile),
2861
+ views: z14.array(View),
2862
+ sessions: z14.array(Session),
2863
+ tasks: z14.array(Task),
2864
+ runs: z14.array(Run),
2865
+ automations: z14.array(Automation),
2866
+ attention: z14.array(AttentionItem),
2867
+ interactions: z14.array(Interaction),
2868
+ panels: z14.array(Panel),
2869
+ devices: z14.array(Device),
2870
+ adapters: z14.record(z14.string(), z14.array(AdapterInfo)),
2871
+ dispatchPaused: z14.boolean()
2872
+ });
2873
+ var Presence = z14.object({
2874
+ foreground: z14.boolean(),
2875
+ interactedAt: z14.string().nullable(),
2876
+ viewing: z14.object({ sessionId: z14.string() }).nullable()
2877
+ });
2878
+ var CLIENT_CAPABILITIES = ["adapter.slots.v1", "timeline.cards.v1"];
2879
+ var ClientToServer = z14.discriminatedUnion("type", [
2880
+ z14.object({
2881
+ type: z14.literal("hello"),
2882
+ cursor: z14.number().int().nullable(),
2883
+ capabilities: z14.array(z14.string().min(1).max(80)).max(32).optional(),
2884
+ projectionId: z14.string().max(256).nullable().optional()
2885
+ }),
2886
+ z14.object({ type: z14.literal("presence"), presence: Presence }),
2887
+ z14.object({ type: z14.literal("ping") })
2888
+ ]);
2889
+ var ServerToClient = z14.discriminatedUnion("type", [
2890
+ z14.object({
2891
+ type: z14.literal("replay"),
2892
+ seq: z14.number().int(),
2893
+ events: z14.array(EventEnvelope),
2894
+ capabilities: z14.array(z14.enum(CLIENT_CAPABILITIES)).optional(),
2895
+ projectionId: z14.string().optional()
2896
+ }),
2897
+ z14.object({
2898
+ type: z14.literal("snapshot"),
2899
+ seq: z14.number().int(),
2900
+ state: SyncState,
2901
+ capabilities: z14.array(z14.enum(CLIENT_CAPABILITIES)).optional(),
2902
+ projectionId: z14.string().optional()
2903
+ }),
2904
+ z14.object({ type: z14.literal("event"), event: EventEnvelope }),
2905
+ z14.object({ type: z14.literal("stream"), delta: StreamDelta }),
2906
+ z14.object({ type: z14.literal("pong") }),
2907
+ z14.object({ type: z14.literal("force_logout"), reason: z14.string() })
2908
+ ]);
2909
+
2910
+ // node_modules/.pnpm/ulid@3.0.2/node_modules/ulid/dist/node/index.js
2911
+ import crypto from "node:crypto";
2912
+ var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
2913
+ var ENCODING_LEN = 32;
2914
+ var RANDOM_LEN = 16;
2915
+ var TIME_LEN = 10;
2916
+ var TIME_MAX = 281474976710655;
2917
+ var ULIDErrorCode;
2918
+ (function(ULIDErrorCode2) {
2919
+ ULIDErrorCode2["Base32IncorrectEncoding"] = "B32_ENC_INVALID";
2920
+ ULIDErrorCode2["DecodeTimeInvalidCharacter"] = "DEC_TIME_CHAR";
2921
+ ULIDErrorCode2["DecodeTimeValueMalformed"] = "DEC_TIME_MALFORMED";
2922
+ ULIDErrorCode2["EncodeTimeNegative"] = "ENC_TIME_NEG";
2923
+ ULIDErrorCode2["EncodeTimeSizeExceeded"] = "ENC_TIME_SIZE_EXCEED";
2924
+ ULIDErrorCode2["EncodeTimeValueMalformed"] = "ENC_TIME_MALFORMED";
2925
+ ULIDErrorCode2["PRNGDetectFailure"] = "PRNG_DETECT";
2926
+ ULIDErrorCode2["ULIDInvalid"] = "ULID_INVALID";
2927
+ ULIDErrorCode2["Unexpected"] = "UNEXPECTED";
2928
+ ULIDErrorCode2["UUIDInvalid"] = "UUID_INVALID";
2929
+ })(ULIDErrorCode || (ULIDErrorCode = {}));
2930
+ var ULIDError = class extends Error {
2931
+ constructor(errorCode, message) {
2932
+ super(`${message} (${errorCode})`);
2933
+ this.name = "ULIDError";
2934
+ this.code = errorCode;
2935
+ }
2936
+ };
2937
+ function randomChar(prng) {
2938
+ const randomPosition = Math.floor(prng() * ENCODING_LEN) % ENCODING_LEN;
2939
+ return ENCODING.charAt(randomPosition);
2940
+ }
2941
+ function replaceCharAt(str, index, char) {
2942
+ if (index > str.length - 1) {
2943
+ return str;
2944
+ }
2945
+ return str.substr(0, index) + char + str.substr(index + 1);
2946
+ }
2947
+ function incrementBase32(str) {
2948
+ let done = void 0, index = str.length, char, charIndex, output = str;
2949
+ const maxCharIndex = ENCODING_LEN - 1;
2950
+ while (!done && index-- >= 0) {
2951
+ char = output[index];
2952
+ charIndex = ENCODING.indexOf(char);
2953
+ if (charIndex === -1) {
2954
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Incorrectly encoded string");
2955
+ }
2956
+ if (charIndex === maxCharIndex) {
2957
+ output = replaceCharAt(output, index, ENCODING[0]);
2958
+ continue;
2959
+ }
2960
+ done = replaceCharAt(output, index, ENCODING[charIndex + 1]);
2961
+ }
2962
+ if (typeof done === "string") {
2963
+ return done;
2964
+ }
2965
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Failed incrementing string");
2966
+ }
2967
+ function detectPRNG(root) {
2968
+ const rootLookup = detectRoot();
2969
+ const globalCrypto = rootLookup && (rootLookup.crypto || rootLookup.msCrypto) || (typeof crypto !== "undefined" ? crypto : null);
2970
+ if (typeof globalCrypto?.getRandomValues === "function") {
2971
+ return () => {
2972
+ const buffer = new Uint8Array(1);
2973
+ globalCrypto.getRandomValues(buffer);
2974
+ return buffer[0] / 256;
2975
+ };
2976
+ } else if (typeof globalCrypto?.randomBytes === "function") {
2977
+ return () => globalCrypto.randomBytes(1).readUInt8() / 256;
2978
+ } else if (crypto?.randomBytes) {
2979
+ return () => crypto.randomBytes(1).readUInt8() / 256;
2980
+ }
2981
+ throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
2982
+ }
2983
+ function detectRoot() {
2984
+ if (inWebWorker())
2985
+ return self;
2986
+ if (typeof window !== "undefined") {
2987
+ return window;
2988
+ }
2989
+ if (typeof global !== "undefined") {
2990
+ return global;
2991
+ }
2992
+ if (typeof globalThis !== "undefined") {
2993
+ return globalThis;
2994
+ }
2995
+ return null;
2996
+ }
2997
+ function encodeRandom(len, prng) {
2998
+ let str = "";
2999
+ for (; len > 0; len--) {
3000
+ str = randomChar(prng) + str;
3001
+ }
3002
+ return str;
3003
+ }
3004
+ function encodeTime(now, len = TIME_LEN) {
3005
+ if (isNaN(now)) {
3006
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be a number: ${now}`);
3007
+ } else if (now > TIME_MAX) {
3008
+ throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded, `Cannot encode a time larger than ${TIME_MAX}: ${now}`);
3009
+ } else if (now < 0) {
3010
+ throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now}`);
3011
+ } else if (Number.isInteger(now) === false) {
3012
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be an integer: ${now}`);
3013
+ }
3014
+ let mod, str = "";
3015
+ for (let currentLen = len; currentLen > 0; currentLen--) {
3016
+ mod = now % ENCODING_LEN;
3017
+ str = ENCODING.charAt(mod) + str;
3018
+ now = (now - mod) / ENCODING_LEN;
3019
+ }
3020
+ return str;
3021
+ }
3022
+ function inWebWorker() {
3023
+ return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
3024
+ }
3025
+ function monotonicFactory(prng) {
3026
+ const currentPRNG = prng || detectPRNG();
3027
+ let lastTime = 0, lastRandom;
3028
+ return function _ulid(seedTime) {
3029
+ const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
3030
+ if (seed <= lastTime) {
3031
+ const incrementedRandom = lastRandom = incrementBase32(lastRandom);
3032
+ return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
3033
+ }
3034
+ lastTime = seed;
3035
+ const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currentPRNG);
3036
+ return encodeTime(seed, TIME_LEN) + newRandom;
3037
+ };
3038
+ }
3039
+
3040
+ // packages/protocol/dist/ids.js
3041
+ var ulid = monotonicFactory();
3042
+
3043
+ // packages/protocol/dist/views.js
3044
+ var CLIENT_OPEN_MS = 10 * 6e4;
3045
+
3046
+ // packages/protocol/dist/web-bridge.js
3047
+ import { z as z15 } from "zod";
3048
+ var FRAME_MAX_HEIGHT = 4e3;
3049
+ var FrameToParentMessageSchema = z15.discriminatedUnion("type", [
3050
+ z15.object({
3051
+ type: z15.literal("action"),
3052
+ actionId: z15.string().min(1).max(200),
3053
+ payload: z15.unknown().optional()
3054
+ }),
3055
+ z15.object({
3056
+ type: z15.literal("resize"),
3057
+ height: z15.number().finite().min(0).max(FRAME_MAX_HEIGHT)
3058
+ })
3059
+ ]);
3060
+
3061
+ // packages/client/dist/connection.js
3062
+ import WebSocket from "ws";
3063
+
3064
+ // packages/client/dist/store.js
3065
+ function emptyState() {
3066
+ return {
3067
+ seq: null,
3068
+ synced: false,
3069
+ connection: { state: "connecting", attempts: 0, reason: null },
3070
+ hosts: {},
3071
+ projects: {},
3072
+ checkouts: {},
3073
+ workspaces: {},
3074
+ profiles: {},
3075
+ views: {},
3076
+ sessions: {},
3077
+ tasks: {},
3078
+ runs: {},
3079
+ automations: {},
3080
+ attention: {},
3081
+ interactions: {},
3082
+ panels: {},
3083
+ devices: {},
3084
+ dispatchPaused: false
3085
+ };
3086
+ }
3087
+ function panelKey(sessionId, adapterId, slot) {
3088
+ return `${sessionId}:${adapterId}:${slot}`;
3089
+ }
3090
+ function keepPanel(p) {
3091
+ return p.node !== null || p.webRenderer;
3092
+ }
3093
+ function byId(list) {
3094
+ const out = {};
3095
+ for (const x of list)
3096
+ out[x.id] = x;
3097
+ return out;
3098
+ }
3099
+ function put(map, id, value) {
3100
+ return { ...map, [id]: value };
3101
+ }
3102
+ function drop(map, id) {
3103
+ if (!(id in map))
3104
+ return map;
3105
+ const next = { ...map };
3106
+ delete next[id];
3107
+ return next;
3108
+ }
3109
+ function applySnapshot(state, seq, snap) {
3110
+ const panels = {};
3111
+ for (const p of snap.panels) {
3112
+ if (keepPanel(p))
3113
+ panels[panelKey(p.sessionId, p.adapterId, p.slot)] = p;
3114
+ }
3115
+ return {
3116
+ ...state,
3117
+ seq,
3118
+ synced: true,
3119
+ hosts: byId(snap.hosts),
3120
+ projects: byId(snap.projects),
3121
+ checkouts: byId(snap.checkouts),
3122
+ workspaces: byId(snap.workspaces),
3123
+ profiles: byId(snap.profiles),
3124
+ views: byId(snap.views),
3125
+ sessions: byId(snap.sessions),
3126
+ tasks: byId(snap.tasks),
3127
+ runs: byId(snap.runs),
3128
+ automations: byId(snap.automations),
3129
+ attention: byId(snap.attention.filter((a) => a.resolvedAt === null)),
3130
+ interactions: byId(snap.interactions),
3131
+ panels,
3132
+ devices: byId(snap.devices),
3133
+ dispatchPaused: snap.dispatchPaused
3134
+ };
3135
+ }
3136
+ function upsertInteraction(state, i) {
3137
+ const prev = state.interactions[i.id];
3138
+ if (prev && prev.revision > i.revision)
3139
+ return state;
3140
+ return { ...state, interactions: put(state.interactions, i.id, i) };
3141
+ }
3142
+ function applyEvent(state, event) {
3143
+ if (state.seq !== null && event.seq <= state.seq)
3144
+ return state;
3145
+ const next = reduceEvent(state, canonicalEventType(event.type), event.data);
3146
+ return { ...next, seq: event.seq };
3147
+ }
3148
+ function applyReplay(state, seq, events) {
3149
+ let s = state;
3150
+ for (const e of [...events].sort((a, b) => a.seq - b.seq))
3151
+ s = applyEvent(s, e);
3152
+ return { ...s, seq: Math.max(s.seq ?? 0, seq), synced: true };
3153
+ }
3154
+ function reduceEvent(state, type, data) {
3155
+ switch (type) {
3156
+ case "host.updated": {
3157
+ const d = data;
3158
+ return { ...state, hosts: put(state.hosts, d.id, d) };
3159
+ }
3160
+ case "project.updated": {
3161
+ const d = data;
3162
+ return { ...state, projects: put(state.projects, d.id, d) };
3163
+ }
3164
+ case "project.deleted": {
3165
+ const d = data;
3166
+ return { ...state, projects: drop(state.projects, d.id) };
3167
+ }
3168
+ case "checkout.updated": {
3169
+ const d = data;
3170
+ return { ...state, checkouts: put(state.checkouts, d.id, d) };
3171
+ }
3172
+ case "workspace.updated": {
3173
+ const d = data;
3174
+ return {
3175
+ ...state,
3176
+ workspaces: d.archivedAt ? drop(state.workspaces, d.id) : put(state.workspaces, d.id, d)
3177
+ };
3178
+ }
3179
+ case "workspace.deleted": {
3180
+ const d = data;
3181
+ return { ...state, workspaces: drop(state.workspaces, d.id) };
3182
+ }
3183
+ case "profile.updated": {
3184
+ const d = data;
3185
+ return { ...state, profiles: put(state.profiles, d.id, d) };
3186
+ }
3187
+ case "view.updated": {
3188
+ const d = data;
3189
+ return { ...state, views: put(state.views, d.id, d) };
3190
+ }
3191
+ case "view.deleted": {
3192
+ const d = data;
3193
+ return { ...state, views: drop(state.views, d.id) };
3194
+ }
3195
+ case "profile.deleted": {
3196
+ const d = data;
3197
+ return { ...state, profiles: drop(state.profiles, d.id) };
3198
+ }
3199
+ case "session.updated": {
3200
+ const d = data;
3201
+ return { ...state, sessions: put(state.sessions, d.id, d) };
3202
+ }
3203
+ case "interaction.updated":
3204
+ return upsertInteraction(state, data);
3205
+ case "panel.updated": {
3206
+ const d = data;
3207
+ const key = panelKey(d.sessionId, d.adapterId, d.slot);
3208
+ return {
3209
+ ...state,
3210
+ panels: keepPanel(d) ? put(state.panels, key, d) : drop(state.panels, key)
3211
+ };
3212
+ }
3213
+ case "task.updated": {
3214
+ const d = data;
3215
+ return { ...state, tasks: put(state.tasks, d.id, d) };
3216
+ }
3217
+ case "task.deleted": {
3218
+ const d = data;
3219
+ return { ...state, tasks: drop(state.tasks, d.id) };
3220
+ }
3221
+ case "run.updated": {
3222
+ const d = data;
3223
+ return { ...state, runs: put(state.runs, d.id, d) };
3224
+ }
3225
+ case "automation.updated": {
3226
+ const d = data;
3227
+ return { ...state, automations: put(state.automations, d.id, d) };
3228
+ }
3229
+ case "automation.deleted": {
3230
+ const d = data;
3231
+ return { ...state, automations: drop(state.automations, d.id) };
3232
+ }
3233
+ case "attention.updated": {
3234
+ const d = data;
3235
+ return {
3236
+ ...state,
3237
+ attention: d.resolvedAt ? drop(state.attention, d.id) : put(state.attention, d.id, d)
3238
+ };
3239
+ }
3240
+ case "device.updated": {
3241
+ const d = data;
3242
+ return {
3243
+ ...state,
3244
+ devices: d.revokedAt ? drop(state.devices, d.id) : put(state.devices, d.id, d)
3245
+ };
3246
+ }
3247
+ case "settings.updated": {
3248
+ const d = data;
3249
+ return { ...state, dispatchPaused: d.dispatchPaused };
3250
+ }
3251
+ default:
3252
+ return state;
3253
+ }
3254
+ }
3255
+ function setConnection(state, connection) {
3256
+ return { ...state, connection: { ...state.connection, ...connection } };
3257
+ }
3258
+ var Store = class {
3259
+ state = emptyState();
3260
+ listeners = /* @__PURE__ */ new Set();
3261
+ versions = /* @__PURE__ */ new Map();
3262
+ resetVersion = 0;
3263
+ revision(kind, id) {
3264
+ return (this.versions.get(`${kind}:${id}`) ?? 0) + this.resetVersion;
3265
+ }
3266
+ getState = () => this.state;
3267
+ subscribe = (fn) => {
3268
+ this.listeners.add(fn);
3269
+ return () => this.listeners.delete(fn);
3270
+ };
3271
+ update(fn, reset = false) {
3272
+ const previous = this.state;
3273
+ const next = fn(previous);
3274
+ if (next === previous && !reset)
3275
+ return;
3276
+ if (reset)
3277
+ this.resetVersion++;
3278
+ for (const kind of ["sessions", "tasks"]) {
3279
+ const ids = /* @__PURE__ */ new Set([...Object.keys(previous[kind]), ...Object.keys(next[kind])]);
3280
+ for (const id of ids) {
3281
+ if (reset || previous[kind][id] !== next[kind][id]) {
3282
+ const key = `${kind}:${id}`;
3283
+ this.versions.set(key, (this.versions.get(key) ?? 0) + 1);
3284
+ }
3285
+ }
3286
+ }
3287
+ this.state = next;
3288
+ for (const l of this.listeners)
3289
+ l();
3290
+ }
3291
+ };
3292
+
3293
+ // packages/client/dist/connection.js
3294
+ function wsUrlFor(coordinatorUrl) {
3295
+ const u = new URL(coordinatorUrl.replace(/\/+$/, ""));
3296
+ u.protocol = u.protocol === "https:" ? "wss:" : "ws:";
3297
+ u.pathname = `${u.pathname.replace(/\/+$/, "")}/ws/client`;
3298
+ u.search = "";
3299
+ u.hash = "";
3300
+ return u.toString();
3301
+ }
3302
+ var PING_INTERVAL_MS = 25e3;
3303
+ var PONG_TIMEOUT_MS = 1e4;
3304
+ var ClientConnection = class {
3305
+ api;
3306
+ store = new Store();
3307
+ opts;
3308
+ ws = null;
3309
+ stopped = true;
3310
+ revoked = false;
3311
+ attempts = 0;
3312
+ retryTimer = null;
3313
+ pingTimer = null;
3314
+ pongTimer = null;
3315
+ logoutListeners = /* @__PURE__ */ new Set();
3316
+ liveListeners = /* @__PURE__ */ new Set();
3317
+ closeListeners = /* @__PURE__ */ new Set();
3318
+ noticeListeners = /* @__PURE__ */ new Set();
3319
+ cursor;
3320
+ projectionId;
3321
+ capabilities = [];
3322
+ constructor(opts) {
3323
+ this.opts = opts;
3324
+ this.api = new ApiClient(opts);
3325
+ if (opts.initialCursor !== void 0 && (!Number.isSafeInteger(opts.initialCursor) || opts.initialCursor < 0))
3326
+ throw new RangeError("Invalid cursor");
3327
+ this.cursor = opts.initialCursor ?? null;
3328
+ this.projectionId = opts.projectionId ?? null;
3329
+ }
3330
+ connect() {
3331
+ if (!this.stopped || this.revoked)
3332
+ return;
3333
+ this.stopped = false;
3334
+ this.open();
3335
+ }
3336
+ close() {
3337
+ if (this.stopped && !this.ws)
3338
+ return;
3339
+ this.stopped = true;
3340
+ this.clearTimers();
3341
+ const ws = this.ws;
3342
+ this.ws = null;
3343
+ ws?.removeAllListeners();
3344
+ ws?.on("error", () => void 0);
3345
+ try {
3346
+ if (ws?.readyState === WebSocket.CONNECTING)
3347
+ ws.terminate();
3348
+ else
3349
+ ws?.close(1e3, "client closed");
3350
+ } catch {
3351
+ ws?.terminate();
3352
+ }
3353
+ for (const fn of this.closeListeners)
3354
+ fn();
3355
+ }
3356
+ onLogout(fn) {
3357
+ this.logoutListeners.add(fn);
3358
+ return () => this.logoutListeners.delete(fn);
3359
+ }
3360
+ /** Called each time the connection becomes live (after replay or snapshot). */
3361
+ onLive(fn) {
3362
+ this.liveListeners.add(fn);
3363
+ return () => this.liveListeners.delete(fn);
3364
+ }
3365
+ onClose(fn) {
3366
+ this.closeListeners.add(fn);
3367
+ return () => this.closeListeners.delete(fn);
3368
+ }
3369
+ onNotice(fn) {
3370
+ this.noticeListeners.add(fn);
3371
+ return () => this.noticeListeners.delete(fn);
3372
+ }
3373
+ send(msg) {
3374
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN)
3375
+ return false;
3376
+ this.ws.send(JSON.stringify(msg));
3377
+ return true;
3378
+ }
3379
+ open() {
3380
+ if (this.stopped)
3381
+ return;
3382
+ const Impl = this.opts.WebSocketImpl ?? WebSocket;
3383
+ const headers = {};
3384
+ if (this.opts.credential)
3385
+ headers.authorization = `Bearer ${this.opts.credential}`;
3386
+ let ws;
3387
+ try {
3388
+ ws = new Impl(wsUrlFor(this.opts.coordinatorUrl), { headers });
3389
+ } catch {
3390
+ this.scheduleReconnect();
3391
+ return;
3392
+ }
3393
+ this.ws = ws;
3394
+ ws.on("open", () => {
3395
+ if (this.ws !== ws)
3396
+ return;
3397
+ ws.send(JSON.stringify({
3398
+ type: "hello",
3399
+ cursor: this.cursor,
3400
+ capabilities: [...CLIENT_CAPABILITIES],
3401
+ projectionId: this.projectionId
3402
+ }));
3403
+ });
3404
+ ws.on("message", (raw) => {
3405
+ if (this.ws !== ws)
3406
+ return;
3407
+ let msg;
3408
+ try {
3409
+ msg = JSON.parse(raw.toString());
3410
+ } catch {
3411
+ return;
3412
+ }
3413
+ this.handle(msg);
3414
+ });
3415
+ ws.on("unexpected-response", (_req, res) => {
3416
+ if (this.ws !== ws)
3417
+ return;
3418
+ const code = res.statusCode ?? 0;
3419
+ res.resume();
3420
+ if (code === 401 || code === 403) {
3421
+ this.logout(code === 401 ? "This device's credential was rejected" : "Forbidden");
3422
+ return;
3423
+ }
3424
+ this.ws = null;
3425
+ ws.terminate();
3426
+ this.scheduleReconnect();
3427
+ });
3428
+ ws.on("close", (code, reason2) => {
3429
+ if (this.ws !== ws)
3430
+ return;
3431
+ this.ws = null;
3432
+ this.clearTimers();
3433
+ if (this.stopped)
3434
+ return;
3435
+ if (code === 4401 || code === 4403) {
3436
+ this.logout(reason2.toString() || "unauthorized");
3437
+ return;
3438
+ }
3439
+ this.scheduleReconnect();
3440
+ });
3441
+ ws.on("error", () => {
3442
+ });
3443
+ }
3444
+ handle(msg) {
3445
+ switch (msg.type) {
3446
+ case "snapshot":
3447
+ this.acknowledge(msg);
3448
+ this.cursor = msg.seq;
3449
+ this.store.update((s) => applySnapshot(s, msg.seq, msg.state), true);
3450
+ this.emitNotice({
3451
+ type: "reset",
3452
+ seq: msg.seq,
3453
+ state: msg.state,
3454
+ projectionId: this.projectionId
3455
+ });
3456
+ this.becomeLive();
3457
+ break;
3458
+ case "replay":
3459
+ this.acknowledge(msg);
3460
+ for (const event of [...msg.events].sort((a, b) => a.seq - b.seq)) {
3461
+ if (this.cursor !== null && event.seq <= this.cursor)
3462
+ continue;
3463
+ this.cursor = event.seq;
3464
+ this.store.update((s) => applyEvent(s, event));
3465
+ this.emitNotice({ type: "event", event, projectionId: this.projectionId });
3466
+ }
3467
+ this.cursor = Math.max(this.cursor ?? 0, msg.seq);
3468
+ this.store.update((s) => applyReplay(s, msg.seq, []));
3469
+ this.becomeLive();
3470
+ break;
3471
+ case "event":
3472
+ if (this.cursor !== null && msg.event.seq <= this.cursor)
3473
+ break;
3474
+ this.cursor = msg.event.seq;
3475
+ this.store.update((s) => applyEvent(s, msg.event));
3476
+ this.emitNotice({ type: "event", event: msg.event, projectionId: this.projectionId });
3477
+ break;
3478
+ case "pong":
3479
+ if (this.pongTimer)
3480
+ clearTimeout(this.pongTimer);
3481
+ this.pongTimer = null;
3482
+ break;
3483
+ case "force_logout":
3484
+ this.logout(msg.reason);
3485
+ break;
3486
+ }
3487
+ }
3488
+ acknowledge(msg) {
3489
+ this.capabilities = (msg.capabilities ?? []).filter((name) => CLIENT_CAPABILITIES.includes(name));
3490
+ this.projectionId = msg.projectionId ?? null;
3491
+ }
3492
+ emitNotice(notice) {
3493
+ for (const fn of [...this.noticeListeners])
3494
+ fn(notice);
3495
+ }
3496
+ becomeLive() {
3497
+ if (this.stopped)
3498
+ return;
3499
+ this.attempts = 0;
3500
+ this.store.update((s) => setConnection(s, { state: "live", attempts: 0, reason: null }));
3501
+ this.startPing();
3502
+ for (const fn of this.liveListeners)
3503
+ fn();
3504
+ }
3505
+ logout(reason2) {
3506
+ if (this.revoked)
3507
+ return;
3508
+ this.revoked = true;
3509
+ this.store.update((s) => setConnection(s, { state: "logged_out", reason: reason2 }));
3510
+ for (const fn of [...this.logoutListeners])
3511
+ fn(reason2);
3512
+ this.close();
3513
+ }
3514
+ startPing() {
3515
+ if (this.pingTimer)
3516
+ clearInterval(this.pingTimer);
3517
+ this.pingTimer = setInterval(() => {
3518
+ if (!this.send({ type: "ping" }))
3519
+ return;
3520
+ if (this.pongTimer)
3521
+ return;
3522
+ const socket = this.ws;
3523
+ this.pongTimer = setTimeout(() => {
3524
+ this.pongTimer = null;
3525
+ if (this.ws === socket)
3526
+ socket?.terminate();
3527
+ }, PONG_TIMEOUT_MS);
3528
+ }, this.opts.pingIntervalMs ?? PING_INTERVAL_MS);
3529
+ this.pingTimer.unref?.();
3530
+ }
3531
+ scheduleReconnect() {
3532
+ if (this.stopped)
3533
+ return;
3534
+ this.attempts++;
3535
+ this.store.update((s) => setConnection(s, {
3536
+ state: s.synced ? "reconnecting" : "connecting",
3537
+ attempts: this.attempts
3538
+ }));
3539
+ if (this.retryTimer)
3540
+ clearTimeout(this.retryTimer);
3541
+ this.retryTimer = setTimeout(() => {
3542
+ this.retryTimer = null;
3543
+ this.open();
3544
+ }, reconnectDelay(this.attempts - 1, void 0, this.opts.random));
3545
+ this.retryTimer.unref?.();
3546
+ }
3547
+ clearTimers() {
3548
+ if (this.retryTimer)
3549
+ clearTimeout(this.retryTimer);
3550
+ if (this.pingTimer)
3551
+ clearInterval(this.pingTimer);
3552
+ if (this.pongTimer)
3553
+ clearTimeout(this.pongTimer);
3554
+ this.retryTimer = null;
3555
+ this.pingTimer = null;
3556
+ this.pongTimer = null;
3557
+ }
3558
+ };
3559
+
3560
+ // packages/client/dist/wait.js
3561
+ var WaitError = class extends Error {
3562
+ code;
3563
+ lastEntity;
3564
+ constructor(code, message, lastEntity = null) {
3565
+ super(message);
3566
+ this.code = code;
3567
+ this.lastEntity = lastEntity;
3568
+ this.name = "WaitError";
3569
+ }
3570
+ };
3571
+ function waitForEntity(connection, kind, id, decide, options = {}) {
3572
+ const timeoutMs = options.timeoutMs ?? 3e5;
3573
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)
3574
+ throw new RangeError("timeoutMs must be a positive finite integer");
3575
+ return new Promise((resolve, reject) => {
3576
+ let finished = false;
3577
+ let reading = false;
3578
+ let rerun = false;
3579
+ let last = null;
3580
+ let poll;
3581
+ const pending = /* @__PURE__ */ new Set();
3582
+ const unsub = [];
3583
+ const cleanup = () => {
3584
+ if (poll)
3585
+ clearTimeout(poll);
3586
+ clearTimeout(deadline);
3587
+ options.signal?.removeEventListener("abort", abort);
3588
+ for (const fn of unsub)
3589
+ fn();
3590
+ for (const controller of pending)
3591
+ controller.abort();
3592
+ pending.clear();
3593
+ };
3594
+ const fail = (code, message) => {
3595
+ if (finished)
3596
+ return;
3597
+ finished = true;
3598
+ cleanup();
3599
+ reject(new WaitError(code, message, last));
3600
+ };
3601
+ const succeed = (entity) => {
3602
+ if (finished)
3603
+ return;
3604
+ finished = true;
3605
+ cleanup();
3606
+ resolve(entity);
3607
+ };
3608
+ const evaluate = (entity) => {
3609
+ if (finished || !entity)
3610
+ return;
3611
+ last = entity;
3612
+ const result = decide(entity);
3613
+ if (result.error)
3614
+ fail(result.error, `${kind} ${id} entered ${result.error}`);
3615
+ else if (result.done)
3616
+ succeed(entity);
3617
+ };
3618
+ const fromStore = () => {
3619
+ const state = connection.store.getState();
3620
+ const entity = state[kind][id];
3621
+ if (!state.synced)
3622
+ return;
3623
+ evaluate(entity);
3624
+ };
3625
+ const schedule = () => {
3626
+ if (finished)
3627
+ return;
3628
+ poll = setTimeout(() => {
3629
+ poll = void 0;
3630
+ void refresh();
3631
+ }, 2e3);
3632
+ poll.unref?.();
3633
+ };
3634
+ const refresh = async () => {
3635
+ if (finished)
3636
+ return;
3637
+ if (poll) {
3638
+ clearTimeout(poll);
3639
+ poll = void 0;
3640
+ }
3641
+ if (reading) {
3642
+ rerun = true;
3643
+ return;
3644
+ }
3645
+ reading = true;
3646
+ const revision = connection.store.revision(kind, id);
3647
+ const controller = new AbortController();
3648
+ pending.add(controller);
3649
+ try {
3650
+ const entity = await connection.api.get(`/api/${kind}/${encodeURIComponent(id)}`, {
3651
+ signal: controller.signal
3652
+ });
3653
+ if (!finished) {
3654
+ if (revision !== connection.store.revision(kind, id)) {
3655
+ fromStore();
3656
+ if (!finished)
3657
+ rerun = true;
3658
+ } else
3659
+ evaluate(entity);
3660
+ }
3661
+ } catch (error) {
3662
+ if (!finished && error instanceof ApiRequestError) {
3663
+ if (error.status === 404) {
3664
+ if (revision !== connection.store.revision(kind, id)) {
3665
+ fromStore();
3666
+ if (!finished)
3667
+ rerun = true;
3668
+ } else
3669
+ fail("not_found", error.message);
3670
+ } else if (error.status === 401 || error.status === 403)
3671
+ fail("unauthorized", error.message);
3672
+ else if (error.status >= 400 && error.status < 500)
3673
+ fail("invalid_request", error.message);
3674
+ }
3675
+ } finally {
3676
+ pending.delete(controller);
3677
+ reading = false;
3678
+ if (!finished) {
3679
+ if (rerun) {
3680
+ rerun = false;
3681
+ void refresh();
3682
+ } else
3683
+ schedule();
3684
+ }
3685
+ }
3686
+ };
3687
+ const abort = () => fail("aborted", "Wait aborted");
3688
+ const deadline = setTimeout(() => fail("timeout", `Wait timed out after ${timeoutMs} ms`), timeoutMs);
3689
+ unsub.push(connection.store.subscribe(fromStore));
3690
+ unsub.push(connection.onNotice((notice) => {
3691
+ if (notice.type === "event" && notice.event.type === "task.deleted" && kind === "tasks" && notice.event.data.id === id) {
3692
+ fail("not_found", `tasks ${id} was removed`);
3693
+ }
3694
+ }));
3695
+ unsub.push(connection.onLive(() => {
3696
+ void refresh();
3697
+ }));
3698
+ unsub.push(connection.onLogout((reason2) => fail("unauthorized", reason2)));
3699
+ unsub.push(connection.onClose(() => fail("closed", "Client closed")));
3700
+ options.signal?.addEventListener("abort", abort, { once: true });
3701
+ if (options.signal?.aborted)
3702
+ abort();
3703
+ if (!finished) {
3704
+ fromStore();
3705
+ if (!finished) {
3706
+ connection.connect();
3707
+ void refresh();
3708
+ }
3709
+ }
3710
+ });
3711
+ }
3712
+
3713
+ // packages/client/dist/client.js
3714
+ function queryPath(path2, values) {
3715
+ const query = new URLSearchParams();
3716
+ for (const [key, value] of Object.entries(values))
3717
+ if (value !== void 0)
3718
+ query.set(key, String(value));
3719
+ const suffix = query.toString();
3720
+ return suffix ? `${path2}?${suffix}` : path2;
3721
+ }
3722
+ var entityPath = (kind, id) => `/api/${kind}/${encodeURIComponent(id)}`;
3723
+ var SwitchyardClient = class {
3724
+ connection;
3725
+ opts;
3726
+ closed = false;
3727
+ subscriptions = /* @__PURE__ */ new Set();
3728
+ constructor(options) {
3729
+ this.opts = options;
3730
+ this.connection = new ClientConnection(options);
3731
+ }
3732
+ connect() {
3733
+ if (this.closed)
3734
+ throw new Error("Client closed");
3735
+ this.connection.connect();
3736
+ }
3737
+ close() {
3738
+ if (this.closed)
3739
+ return;
3740
+ this.closed = true;
3741
+ for (const unsubscribe of [...this.subscriptions])
3742
+ unsubscribe();
3743
+ this.connection.close();
3744
+ }
3745
+ sessions = {
3746
+ create: (input, options) => this.connection.api.post("/api/sessions", input, options),
3747
+ send: (id, input, options) => this.connection.api.post(`${entityPath("sessions", id)}/prompt`, input, options),
3748
+ transcript: (id, query = {}, options) => {
3749
+ if (query.before !== void 0 && query.afterRev !== void 0)
3750
+ throw new TypeError("before and afterRev are mutually exclusive");
3751
+ if (query.afterRev !== void 0 && query.epoch === void 0)
3752
+ throw new TypeError("epoch is required with afterRev");
3753
+ return this.connection.api.get(queryPath(`${entityPath("sessions", id)}/transcript`, {
3754
+ limit: query.limit,
3755
+ before: query.before,
3756
+ afterRev: query.afterRev,
3757
+ epoch: query.epoch
3758
+ }), options);
3759
+ },
3760
+ waitForFinish: (id, options) => this.closed ? Promise.reject(new WaitError("closed", "Client closed")) : waitForEntity(this.connection, "sessions", id, (s) => {
3761
+ if (s.runtime === "failed" || s.runtime === "interrupted" || s.runtime === "stopped")
3762
+ return { error: `session_${s.runtime}` };
3763
+ return {
3764
+ done: s.runtime === "idle" && s.queue.steering.length === 0 && s.queue.followUp.length === 0
3765
+ };
3766
+ }, options)
3767
+ };
3768
+ tasks = {
3769
+ create: (input, options) => this.connection.api.post("/api/tasks", input, options),
3770
+ list: (query = {}, options) => this.connection.api.get(queryPath("/api/tasks", {
3771
+ projectId: query.projectId,
3772
+ state: query.state?.join(","),
3773
+ includeHidden: query.includeHidden
3774
+ }), options),
3775
+ waitForState: (id, states, options) => {
3776
+ const wanted = Array.isArray(states) ? states : [states];
3777
+ if (!wanted.length)
3778
+ throw new TypeError("states must not be empty");
3779
+ if (this.closed)
3780
+ return Promise.reject(new WaitError("closed", "Client closed"));
3781
+ return waitForEntity(this.connection, "tasks", id, (task) => ({
3782
+ done: wanted.includes(task.state),
3783
+ error: task.state === "canceled" && !wanted.includes("canceled") ? "task_canceled" : void 0
3784
+ }), options);
3785
+ }
3786
+ };
3787
+ events = {
3788
+ subscribe: (listener, options = {}) => {
3789
+ if (this.closed)
3790
+ throw new Error("Client closed");
3791
+ const connection = new ClientConnection({
3792
+ ...this.opts,
3793
+ initialCursor: options.cursor,
3794
+ projectionId: options.projectionId ?? null
3795
+ });
3796
+ let active = true;
3797
+ const unsubscribe = () => {
3798
+ if (!active)
3799
+ return;
3800
+ active = false;
3801
+ this.subscriptions.delete(unsubscribe);
3802
+ options.signal?.removeEventListener("abort", unsubscribe);
3803
+ connection.close();
3804
+ };
3805
+ const error = (reason2) => {
3806
+ if (!active)
3807
+ return;
3808
+ try {
3809
+ options.onError?.(reason2);
3810
+ } finally {
3811
+ unsubscribe();
3812
+ }
3813
+ };
3814
+ connection.onNotice((notice) => {
3815
+ if (!active)
3816
+ return;
3817
+ try {
3818
+ listener(notice);
3819
+ } catch (cause) {
3820
+ error(cause instanceof Error ? cause : new Error(String(cause)));
3821
+ }
3822
+ });
3823
+ connection.onLogout((reason2) => error(new Error(reason2)));
3824
+ this.subscriptions.add(unsubscribe);
3825
+ options.signal?.addEventListener("abort", unsubscribe, { once: true });
3826
+ if (options.signal?.aborted)
3827
+ unsubscribe();
3828
+ else
3829
+ connection.connect();
3830
+ return unsubscribe;
3831
+ }
3832
+ };
3833
+ };
3834
+ export {
3835
+ ApiClient,
3836
+ ApiRequestError,
3837
+ ClientConnection,
3838
+ Store,
3839
+ SwitchyardClient,
3840
+ WaitError,
3841
+ wsUrlFor
3842
+ };