@spencerboucher/switchyard-client 0.0.0-stage → 0.16.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,4007 @@
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 z8 } 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 z7 } 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/trackers.js
968
+ import { z as z6 } from "zod";
969
+ var Iso = z6.string();
970
+ var Id4 = z6.string().min(1);
971
+ var GitHubLogin = z6.string().regex(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/);
972
+ var TrackerStatusOption = z6.object({
973
+ id: z6.string().min(1),
974
+ name: z6.string().min(1).max(200)
975
+ });
976
+ var TrackerBoard = z6.object({
977
+ projectNumber: z6.number().int().positive(),
978
+ statusField: z6.string().min(1).max(100).default("Status"),
979
+ /** Column to move a card to once its worktree exists (write-back). */
980
+ onStart: z6.string().min(1).max(200).nullable().default(null),
981
+ /** Column to move a card to once a pull request is open (write-back). */
982
+ onReview: z6.string().min(1).max(200).nullable().default(null)
983
+ });
984
+ var Tracker = z6.object({
985
+ id: Id4,
986
+ name: z6.string().min(1).max(60),
987
+ provider: z6.literal("github"),
988
+ hostId: Id4,
989
+ owner: GitHubLogin,
990
+ repositories: z6.array(GitHubRepository).min(1).max(50).nullable(),
991
+ /** Repositories outside `owner` that belong to this tracker too (never limited by `repositories`). */
992
+ extraRepositories: z6.array(GitHubRepository).max(20).optional(),
993
+ board: TrackerBoard.nullable(),
994
+ writeBack: z6.boolean(),
995
+ moveShared: z6.boolean(),
996
+ enabled: z6.boolean(),
997
+ /** The host's `gh` user, from the last sync. */
998
+ login: z6.string().nullable(),
999
+ lastSyncedAt: Iso.nullable(),
1000
+ lastError: z6.string().max(2e3).nullable(),
1001
+ createdAt: Iso,
1002
+ updatedAt: Iso
1003
+ });
1004
+ var TrackerInput = z6.object({
1005
+ name: Tracker.shape.name,
1006
+ hostId: Id4,
1007
+ owner: GitHubLogin,
1008
+ repositories: Tracker.shape.repositories.default(null),
1009
+ extraRepositories: z6.array(GitHubRepository).max(20).default([]),
1010
+ board: TrackerBoard.nullable().default(null),
1011
+ writeBack: z6.boolean().default(false),
1012
+ moveShared: z6.boolean().default(true),
1013
+ enabled: z6.boolean().default(true)
1014
+ });
1015
+ var TrackerPatch = z6.object({
1016
+ name: Tracker.shape.name.optional(),
1017
+ hostId: Id4.optional(),
1018
+ owner: GitHubLogin.optional(),
1019
+ repositories: Tracker.shape.repositories.optional(),
1020
+ extraRepositories: z6.array(GitHubRepository).max(20).optional(),
1021
+ board: TrackerBoard.nullable().optional(),
1022
+ writeBack: z6.boolean().optional(),
1023
+ moveShared: z6.boolean().optional(),
1024
+ enabled: z6.boolean().optional()
1025
+ });
1026
+ var TrackerItemBoard = z6.object({
1027
+ projectId: z6.string().min(1),
1028
+ projectItemId: z6.string().min(1),
1029
+ fieldId: z6.string().min(1),
1030
+ status: z6.string().nullable(),
1031
+ statusOptionId: z6.string().nullable(),
1032
+ options: z6.array(TrackerStatusOption).max(50)
1033
+ });
1034
+ var TrackerPullRequest = z6.object({
1035
+ number: z6.number().int().positive(),
1036
+ state: z6.enum(["OPEN", "CLOSED", "MERGED"]),
1037
+ url: z6.string().url(),
1038
+ headRefName: z6.string().min(1).max(255)
1039
+ });
1040
+ var TrackerItem = z6.object({
1041
+ itemId: z6.string().min(1),
1042
+ repository: GitHubRepository,
1043
+ number: z6.number().int().positive(),
1044
+ title: z6.string().min(1).max(1e3),
1045
+ url: GitHubIssueUrl,
1046
+ assignees: z6.array(z6.string()).max(20),
1047
+ branches: z6.array(z6.string().min(1).max(255)).max(10),
1048
+ pullRequest: TrackerPullRequest.nullable(),
1049
+ board: TrackerItemBoard.nullable()
1050
+ });
1051
+ var TrackerSyncResult = z6.object({
1052
+ login: z6.string().min(1),
1053
+ items: z6.array(TrackerItem).max(200),
1054
+ truncated: z6.boolean()
1055
+ });
1056
+ var TaskTracker = z6.object({
1057
+ trackerId: Id4,
1058
+ itemId: z6.string().min(1),
1059
+ repository: GitHubRepository,
1060
+ number: z6.number().int().positive(),
1061
+ assignees: z6.array(z6.string()).max(20),
1062
+ branch: z6.string().nullable(),
1063
+ workspaceId: Id4.nullable(),
1064
+ pullRequest: TrackerPullRequest.nullable(),
1065
+ board: TrackerItemBoard.nullable()
1066
+ });
1067
+ var TrackerSetStatusResult = z6.discriminatedUnion("status", [
1068
+ z6.object({ status: z6.literal("moved") }),
1069
+ z6.object({
1070
+ status: z6.literal("skipped"),
1071
+ reason: z6.enum(["not_assigned", "shared", "stale"])
1072
+ })
1073
+ ]);
1074
+ var TrackerStatusRequest = z6.object({ status: z6.string().min(1).max(200) });
1075
+ var TrackerHostSyncRequest = z6.object({
1076
+ owner: GitHubLogin,
1077
+ repositories: z6.array(GitHubRepository).nullable(),
1078
+ board: z6.object({ projectNumber: z6.number().int().positive(), statusField: z6.string().min(1) }).nullable()
1079
+ });
1080
+ var TrackerHostPrepareBranchRequest = z6.object({
1081
+ checkoutPath: z6.string().min(1),
1082
+ branch: z6.string().min(1).max(255)
1083
+ });
1084
+ var TrackerHostStartIssueRequest = z6.object({
1085
+ checkoutPath: z6.string().min(1),
1086
+ repository: GitHubRepository,
1087
+ number: z6.number().int().positive(),
1088
+ branch: z6.string().min(1).max(255),
1089
+ base: z6.string().min(1)
1090
+ });
1091
+ var TrackerHostSetStatusRequest = z6.object({
1092
+ projectId: z6.string().min(1),
1093
+ projectItemId: z6.string().min(1),
1094
+ fieldId: z6.string().min(1),
1095
+ statusField: z6.string().min(1),
1096
+ optionId: z6.string().min(1),
1097
+ expectedOptionId: z6.string().nullable(),
1098
+ login: z6.string().min(1),
1099
+ allowShared: z6.boolean()
1100
+ });
1101
+
1102
+ // packages/protocol/dist/entities.js
1103
+ var Iso2 = z7.string();
1104
+ var Id5 = z7.string();
1105
+ var Connectivity = z7.enum(["connected", "reconnecting", "unreachable"]);
1106
+ var ControlMode = z7.enum(["automation", "human"]);
1107
+ var Platform = z7.enum(["darwin", "linux"]);
1108
+ var DeviceKind = z7.enum(["browser", "pwa", "terminal", "cli"]);
1109
+ var DiagnosticLevel = z7.enum(["info", "warning", "error"]);
1110
+ var DEFAULT_WORKTREE_DIR = ".worktrees";
1111
+ var CoreCapabilities = z7.object({
1112
+ prompt: z7.boolean(),
1113
+ steer: z7.boolean(),
1114
+ followUp: z7.boolean(),
1115
+ abort: z7.boolean(),
1116
+ resume: z7.boolean(),
1117
+ rename: z7.boolean(),
1118
+ importInactive: z7.boolean(),
1119
+ extensionDialogs: z7.boolean(),
1120
+ customUi: z7.boolean(),
1121
+ widgetsText: z7.boolean(),
1122
+ widgetsComponent: z7.boolean(),
1123
+ tokenAccounting: z7.boolean(),
1124
+ costAccounting: z7.boolean()
1125
+ });
1126
+ var CAPABILITY_KEYS = CoreCapabilities.keyof().options;
1127
+ var RuntimeCapabilities = CoreCapabilities.extend({
1128
+ /** The host runs sessions as interactive Pi in a terminal that clients can attach to. */
1129
+ terminal: z7.boolean().optional(),
1130
+ /** The host answers session.models, session.commands, session.setModel, session.setThinking and session.compact. */
1131
+ sessionControls: z7.boolean().optional(),
1132
+ /** The host answers session.navigate for terminal sessions. */
1133
+ treeNavigation: z7.boolean().optional(),
1134
+ agentRequests: z7.boolean().optional(),
1135
+ messageDelivery: z7.boolean().optional(),
1136
+ policies: z7.boolean().optional(),
1137
+ /** Session-scoped adapter inspection and safe reload. */
1138
+ adapterDevelopment: z7.boolean().optional(),
1139
+ unsupported: z7.array(z7.object({ capability: z7.string(), reason: z7.string() }))
1140
+ });
1141
+ var ProjectScan = z7.object({
1142
+ state: z7.enum(["running", "done", "failed"]),
1143
+ startedAt: Iso2,
1144
+ finishedAt: Iso2.nullable(),
1145
+ /** Repositories found across all folders. */
1146
+ repositories: z7.number().int(),
1147
+ /** New projects created by this scan. */
1148
+ projectsCreated: z7.number().int(),
1149
+ /** New checkouts (including the ones of new projects). */
1150
+ checkoutsAdded: z7.number().int(),
1151
+ /** "<folder>: <message>" per folder that failed; for state "failed", the reason last. */
1152
+ errors: z7.array(z7.string())
1153
+ });
1154
+ var UsageWindow = z7.object({
1155
+ id: z7.enum(["five_hour", "weekly"]),
1156
+ usedPct: z7.number(),
1157
+ resetsAt: Iso2.nullable()
1158
+ });
1159
+ var ProviderUsage = z7.object({
1160
+ provider: z7.enum(["anthropic", "openai-codex"]),
1161
+ status: z7.enum(["available", "expired", "rejected", "error"]),
1162
+ message: z7.string().nullable(),
1163
+ windows: z7.array(UsageWindow),
1164
+ fetchedAt: Iso2
1165
+ });
1166
+ var Host = z7.object({
1167
+ id: Id5,
1168
+ name: z7.string(),
1169
+ platform: Platform,
1170
+ agentVersion: z7.string(),
1171
+ piVersion: z7.string().nullable(),
1172
+ piCompatible: z7.boolean(),
1173
+ capabilities: RuntimeCapabilities.nullable(),
1174
+ connectivity: Connectivity,
1175
+ lastSeenAt: Iso2.nullable(),
1176
+ revokedAt: Iso2.nullable(),
1177
+ createdAt: Iso2,
1178
+ /** Folders on the host whose git repositories become projects (absolute or ~/...). */
1179
+ projectFolders: z7.array(z7.string()).optional(),
1180
+ projectScan: ProjectScan.nullable().optional(),
1181
+ /** Subscription limits (host-reported, refreshed every few minutes). */
1182
+ usage: z7.array(ProviderUsage).optional(),
1183
+ github: HostGitHub.optional()
1184
+ });
1185
+ var WorktreeDir = z7.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");
1186
+ var Project = z7.object({
1187
+ id: Id5,
1188
+ name: z7.string().min(1),
1189
+ repoIdentity: z7.string(),
1190
+ defaultProfileId: Id5.nullable(),
1191
+ defaultHostId: Id5.nullable(),
1192
+ maxConcurrentRuns: z7.number().int().min(1).max(32),
1193
+ automationEnabled: z7.boolean(),
1194
+ setupCommand: z7.string().nullable(),
1195
+ checks: z7.array(z7.string()),
1196
+ workspaceSharing: z7.enum(["single_writer", "shared"]),
1197
+ worktreeDir: WorktreeDir.default(DEFAULT_WORKTREE_DIR),
1198
+ /** Start one session in every non-main worktree the first time it appears without one. */
1199
+ ensureSessions: z7.boolean().default(false),
1200
+ /** Archive sessions and remove a worktree (and its local branch) once its PR has merged. */
1201
+ removeLanded: z7.boolean().default(false),
1202
+ createdAt: Iso2,
1203
+ updatedAt: Iso2
1204
+ });
1205
+ var Checkout = z7.object({
1206
+ id: Id5,
1207
+ projectId: Id5,
1208
+ hostId: Id5,
1209
+ path: z7.string(),
1210
+ commonDir: z7.string(),
1211
+ defaultBranch: z7.string(),
1212
+ createdAt: Iso2
1213
+ });
1214
+ var GitState = z7.object({
1215
+ dirty: z7.boolean(),
1216
+ changedFiles: z7.number().int(),
1217
+ ahead: z7.number().int(),
1218
+ behind: z7.number().int(),
1219
+ unmerged: z7.boolean(),
1220
+ /** HEAD commit; absent from older hosts. */
1221
+ head: z7.string().regex(/^[0-9a-f]{40}$/).optional()
1222
+ });
1223
+ var Workspace = z7.object({
1224
+ id: Id5,
1225
+ checkoutId: Id5,
1226
+ projectId: Id5,
1227
+ hostId: Id5,
1228
+ path: z7.string(),
1229
+ branch: z7.string().nullable(),
1230
+ baseBranch: z7.string().nullable(),
1231
+ provenance: z7.enum(["managed", "discovered", "main"]),
1232
+ git: GitState,
1233
+ setup: z7.object({
1234
+ state: z7.enum(["none", "running", "succeeded", "failed"]),
1235
+ log: z7.string()
1236
+ }),
1237
+ archivedAt: Iso2.nullable(),
1238
+ updatedAt: Iso2,
1239
+ github: WorkspaceGitHub.optional()
1240
+ });
1241
+ var ThinkingLevel = z7.enum(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
1242
+ var SessionModel = z7.object({
1243
+ provider: z7.string(),
1244
+ id: z7.string(),
1245
+ name: z7.string().nullable(),
1246
+ contextWindow: z7.number().nullable(),
1247
+ reasoning: z7.boolean(),
1248
+ /** In Pi's scoped (favorite) model list; set only when Pi has one. */
1249
+ scoped: z7.boolean().optional(),
1250
+ /** Effort levels this model accepts, in Pi's order; ["off"] without reasoning. */
1251
+ thinkingLevels: z7.array(ThinkingLevel),
1252
+ /** Prompt-cache lifetimes in seconds from Pi's model metadata. */
1253
+ promptCache: z7.object({ short: z7.number().optional(), long: z7.number().optional() }).nullable().optional()
1254
+ });
1255
+ var SlashCommand = z7.object({
1256
+ name: z7.string().min(1),
1257
+ description: z7.string().nullable(),
1258
+ source: z7.enum(["extension", "prompt", "skill"]),
1259
+ argumentHint: z7.string().nullable().optional()
1260
+ });
1261
+ var ContextUsage = z7.object({
1262
+ /** Estimated tokens in context; null right after compaction until the next reply. */
1263
+ tokens: z7.number().nullable(),
1264
+ window: z7.number(),
1265
+ percent: z7.number().nullable()
1266
+ });
1267
+ var FORBIDDEN_EXTRA_ARGS = ["--mode", "--fork", "--no-session", "-e", "--extension"];
1268
+ var ExtraArg = z7.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");
1269
+ var Profile = z7.object({
1270
+ id: Id5,
1271
+ name: z7.string().min(1),
1272
+ provider: z7.string().nullable(),
1273
+ model: z7.string().nullable(),
1274
+ thinking: ThinkingLevel.nullable(),
1275
+ projectTrust: z7.enum(["ask", "approve", "ignore"]),
1276
+ extraArgs: z7.array(ExtraArg),
1277
+ /** "vanilla": --no-extensions --no-skills --no-prompt-templates. Undefined means "all". */
1278
+ resources: z7.enum(["all", "vanilla"]).optional()
1279
+ });
1280
+ var ViewClient = z7.object({
1281
+ /** `${kind}:${name}@${machine}` */
1282
+ id: z7.string().min(1),
1283
+ kind: z7.enum(["herdr", "tmux"]),
1284
+ name: z7.string().min(1),
1285
+ machine: z7.string().min(1),
1286
+ lastSeenAt: Iso2
1287
+ });
1288
+ var View = z7.object({
1289
+ id: Id5,
1290
+ name: z7.string().min(1).max(60),
1291
+ mode: z7.enum(["all", "pinned"]),
1292
+ projectIds: z7.array(z7.string()).nullable(),
1293
+ hostIds: z7.array(z7.string()).nullable(),
1294
+ sessionIds: z7.array(z7.string()),
1295
+ clients: z7.array(ViewClient),
1296
+ /** A tracker keeps this view's projects (see docs/trackers.md). */
1297
+ trackerId: z7.string().nullable().optional(),
1298
+ /**
1299
+ * A client as membership authority: sessions enrolled from this client (`ViewClient` id,
1300
+ * `herdr:<session>@<machine>`) are pinned here when they first appear.
1301
+ */
1302
+ clientId: z7.string().min(1).max(200).nullable().optional(),
1303
+ createdAt: Iso2,
1304
+ updatedAt: Iso2
1305
+ });
1306
+ var RuntimeState = z7.enum([
1307
+ "starting",
1308
+ "idle",
1309
+ "running",
1310
+ "waiting_input",
1311
+ "interrupted",
1312
+ "failed",
1313
+ "stopped"
1314
+ ]);
1315
+ var NativeHandle = z7.object({ sessionId: z7.string(), sessionFile: z7.string() });
1316
+ var SessionStats = z7.object({
1317
+ tokens: z7.number().nullable(),
1318
+ costUsd: z7.number().nullable(),
1319
+ /** Completed usage, refreshed for this exact settlement; absent on older hosts or failure. */
1320
+ watermark: CompletedUsageWatermark.optional(),
1321
+ context: ContextUsage.nullable().optional()
1322
+ });
1323
+ var PromptCacheInfo = z7.object({
1324
+ at: Iso2,
1325
+ provider: z7.string(),
1326
+ model: z7.string(),
1327
+ cacheRead: z7.number(),
1328
+ cacheWrite: z7.number(),
1329
+ cacheWrite1h: z7.number()
1330
+ });
1331
+ var Session = z7.object({
1332
+ id: Id5,
1333
+ title: z7.string(),
1334
+ subtitle: z7.string().nullable(),
1335
+ hostId: Id5,
1336
+ workspaceId: Id5.nullable(),
1337
+ projectId: Id5.nullable(),
1338
+ cwd: z7.string(),
1339
+ nativeHandle: NativeHandle.nullable(),
1340
+ profileSnapshot: Profile,
1341
+ runtime: RuntimeState,
1342
+ runtimeDetail: z7.string().nullable(),
1343
+ connectivity: Connectivity,
1344
+ runId: Id5.nullable(),
1345
+ taskId: Id5.nullable(),
1346
+ provenance: z7.enum(["created", "imported", "subagent"]),
1347
+ readOnly: z7.boolean(),
1348
+ lastActivityAt: Iso2,
1349
+ archivedAt: Iso2.nullable(),
1350
+ queue: z7.object({ steering: z7.array(z7.string()), followUp: z7.array(z7.string()) }),
1351
+ stats: SessionStats.nullable(),
1352
+ /** The live model (host-owned; last known when stopped). */
1353
+ model: SessionModel.nullable().optional(),
1354
+ /** The live effort (Pi's thinking level). */
1355
+ thinking: ThinkingLevel.nullable().optional(),
1356
+ /** Pi is compacting the context. */
1357
+ compacting: z7.boolean().optional(),
1358
+ lastAssistantText: z7.string().nullable(),
1359
+ createdAt: Iso2,
1360
+ /** A live terminal session: `switchyard tui` can attach to its Pi terminal. */
1361
+ terminal: z7.boolean().optional(),
1362
+ /**
1363
+ * A Pi the user started in their own terminal and enrolled (`client`: the herdr session it runs
1364
+ * in, when known). Switchyard never shows or closes that terminal.
1365
+ */
1366
+ external: z7.object({ client: z7.string().min(1).max(200).nullable() }).nullable().optional(),
1367
+ /** Set when the session finished or failed with nobody viewing it; cleared when viewed (coordinator-owned). */
1368
+ unreadSince: Iso2.nullable().optional(),
1369
+ /** Identity of the adapter presentation currently installed on the host. */
1370
+ adapterGeneration: z7.string().uuid().optional(),
1371
+ /** Bumped when the transcript is rebuilt (rewind); clients drop cached copies (coordinator-owned). */
1372
+ transcriptEpoch: z7.number().int().min(0).optional(),
1373
+ bridge: z7.object({
1374
+ version: z7.literal(1),
1375
+ runtimeId: Id5,
1376
+ nativeSessionId: Id5,
1377
+ /** Host-generated local-controller identity, not Pi's private binding credential. */
1378
+ controllerEpoch: Id5.optional(),
1379
+ agentTools: z7.boolean(),
1380
+ messageDelivery: z7.boolean(),
1381
+ policyState: z7.enum(["initializing", "active", "unsupported", "lost"]),
1382
+ policyPhases: z7.array(PolicyPhase)
1383
+ }).optional(),
1384
+ /** Last assistant message's cache usage (host-owned). */
1385
+ promptCache: PromptCacheInfo.nullable().optional(),
1386
+ /** Warn before the prompt cache expires; non-null means on (coordinator-owned). */
1387
+ cacheAlert: z7.object({ ttlSec: z7.number().int().min(60).max(86400).nullable(), warnedFor: Iso2.nullable() }).nullable().optional()
1388
+ });
1389
+ var ContinuationPolicy = z7.discriminatedUnion("enabled", [
1390
+ z7.object({ enabled: z7.literal(false) }),
1391
+ z7.object({
1392
+ enabled: z7.literal(true),
1393
+ objective: z7.string().min(1),
1394
+ maxContinuations: z7.number().int().min(1).max(50),
1395
+ maxElapsedMinutes: z7.number().int().min(1).max(1440),
1396
+ maxTokens: z7.number().int().positive().nullable(),
1397
+ maxCostUsd: z7.number().positive().nullable()
1398
+ })
1399
+ ]);
1400
+ var CompletionPolicy = z7.object({
1401
+ checks: z7.array(z7.string()).nullable(),
1402
+ requireHumanReview: z7.boolean()
1403
+ });
1404
+ var WorkspacePolicy = z7.discriminatedUnion("mode", [
1405
+ z7.object({
1406
+ mode: z7.literal("new_worktree"),
1407
+ branch: z7.string().nullable(),
1408
+ base: z7.string().nullable()
1409
+ }),
1410
+ z7.object({ mode: z7.literal("existing"), workspaceId: Id5 })
1411
+ ]);
1412
+ var TaskPolicy = z7.object({
1413
+ hostId: Id5.nullable(),
1414
+ profileId: Id5.nullable(),
1415
+ workspace: WorkspacePolicy,
1416
+ continuation: ContinuationPolicy,
1417
+ completion: CompletionPolicy
1418
+ });
1419
+ var TaskState = z7.enum(["backlog", "ready", "in_progress", "review", "done", "canceled"]);
1420
+ var Priority = z7.union([z7.literal(0), z7.literal(1), z7.literal(2), z7.literal(3)]);
1421
+ var TaskOrigin = z7.discriminatedUnion("kind", [
1422
+ z7.object({ kind: z7.literal("manual") }),
1423
+ z7.object({
1424
+ kind: z7.literal("automation"),
1425
+ automationId: Id5,
1426
+ occurrenceId: Id5,
1427
+ routine: z7.boolean()
1428
+ })
1429
+ ]);
1430
+ var Task = z7.object({
1431
+ id: Id5,
1432
+ projectId: Id5,
1433
+ title: z7.string().min(1),
1434
+ objective: z7.string(),
1435
+ acceptanceCriteria: z7.array(z7.string()),
1436
+ dependencies: z7.array(Id5),
1437
+ priority: Priority,
1438
+ position: z7.number(),
1439
+ state: TaskState,
1440
+ blocked: z7.object({ reason: z7.string() }).nullable(),
1441
+ notBefore: Iso2.nullable(),
1442
+ policy: TaskPolicy,
1443
+ origin: TaskOrigin,
1444
+ groupingKey: z7.string().nullable(),
1445
+ parentTaskId: Id5.nullable().optional(),
1446
+ agentOrigin: z7.object({ sessionId: Id5, toolCallId: Id5 }).optional(),
1447
+ githubIssue: GitHubIssue.optional(),
1448
+ /** Set while a tracker owns this task (server-owned). */
1449
+ tracker: TaskTracker.optional(),
1450
+ currentRunId: Id5.nullable(),
1451
+ sessionId: Id5.nullable(),
1452
+ review: z7.object({ feedback: z7.array(z7.string()), changesRequested: z7.boolean() }),
1453
+ hiddenFromBoard: z7.boolean(),
1454
+ lastActivityAt: Iso2,
1455
+ createdAt: Iso2,
1456
+ updatedAt: Iso2
1457
+ });
1458
+ var RunState = z7.enum([
1459
+ "queued",
1460
+ "dispatching",
1461
+ "uncertain",
1462
+ "running",
1463
+ "waiting_input",
1464
+ "checking",
1465
+ "succeeded",
1466
+ "failed",
1467
+ "interrupted",
1468
+ "canceled"
1469
+ ]);
1470
+ var CheckResult = z7.object({
1471
+ command: z7.string(),
1472
+ exitCode: z7.number().int().nullable(),
1473
+ outputTail: z7.string()
1474
+ });
1475
+ var Run = z7.object({
1476
+ id: Id5,
1477
+ taskId: Id5,
1478
+ sessionId: Id5.nullable(),
1479
+ hostId: Id5.nullable(),
1480
+ dispatchKey: z7.string(),
1481
+ attempt: z7.number().int().min(1),
1482
+ state: RunState,
1483
+ controlMode: ControlMode,
1484
+ controlRevision: z7.number().int().min(1),
1485
+ continuationsUsed: z7.number().int().min(0),
1486
+ infraRetries: z7.number().int().min(0),
1487
+ nextAttemptAt: Iso2.nullable(),
1488
+ startedAt: Iso2.nullable(),
1489
+ endedAt: Iso2.nullable(),
1490
+ outcome: z7.object({
1491
+ kind: z7.enum(["review", "failed", "blocked", "no_change", "canceled"]),
1492
+ summary: z7.string()
1493
+ }).nullable(),
1494
+ limits: ContinuationPolicy,
1495
+ usage: z7.object({
1496
+ tokens: z7.number().nullable(),
1497
+ costUsd: z7.number().nullable(),
1498
+ accounting: z7.enum(["available", "unavailable"]),
1499
+ note: z7.string().nullable()
1500
+ }),
1501
+ checks: z7.array(CheckResult),
1502
+ createdAt: Iso2,
1503
+ updatedAt: Iso2
1504
+ });
1505
+ var Trigger = z7.discriminatedUnion("kind", [
1506
+ z7.object({ kind: z7.literal("manual") }),
1507
+ z7.object({ kind: z7.literal("once"), at: Iso2 }),
1508
+ z7.object({ kind: z7.literal("cron"), expr: z7.string().min(1), timezone: z7.string().min(1) }),
1509
+ z7.object({ kind: z7.literal("webhook") }),
1510
+ z7.object({ kind: z7.literal("dependency"), taskId: Id5 })
1511
+ ]);
1512
+ var TaskTemplate = z7.object({
1513
+ title: z7.string().min(1),
1514
+ objective: z7.string(),
1515
+ acceptanceCriteria: z7.array(z7.string()),
1516
+ priority: Priority
1517
+ });
1518
+ var Automation = z7.object({
1519
+ id: Id5,
1520
+ name: z7.string().min(1),
1521
+ enabled: z7.boolean(),
1522
+ projectId: Id5,
1523
+ trigger: Trigger,
1524
+ filters: z7.array(z7.object({ path: z7.string(), equals: z7.string() })),
1525
+ template: TaskTemplate,
1526
+ hostId: Id5.nullable(),
1527
+ profileId: Id5.nullable(),
1528
+ mode: z7.enum(["fresh", "continue", "watch"]),
1529
+ groupingKey: z7.string().nullable(),
1530
+ overlap: z7.enum(["skip", "queue_one", "append"]),
1531
+ missed: z7.enum(["skip", "run_once"]),
1532
+ continuation: ContinuationPolicy,
1533
+ completion: CompletionPolicy,
1534
+ nextAt: Iso2.nullable(),
1535
+ lastEvaluatedAt: Iso2.nullable(),
1536
+ lastOutcome: z7.string().nullable(),
1537
+ failureCount: z7.number().int().min(0),
1538
+ webhookTokenSet: z7.boolean(),
1539
+ createdAt: Iso2,
1540
+ updatedAt: Iso2
1541
+ });
1542
+ var OccurrenceState = z7.enum([
1543
+ "fired",
1544
+ "skipped_overlap",
1545
+ "skipped_missed",
1546
+ "queued",
1547
+ "appended",
1548
+ "failed",
1549
+ "filtered"
1550
+ ]);
1551
+ var Occurrence = z7.object({
1552
+ id: Id5,
1553
+ automationId: Id5,
1554
+ key: z7.string(),
1555
+ scheduledFor: Iso2.nullable(),
1556
+ state: OccurrenceState,
1557
+ taskId: Id5.nullable(),
1558
+ reason: z7.string().nullable(),
1559
+ outcome: z7.string().nullable(),
1560
+ createdAt: Iso2
1561
+ });
1562
+ var InteractionState = z7.preprocess((v) => v === "cancelled" ? "canceled" : v, z7.enum(["pending", "resolved", "expired", "canceled", "unsupported"]));
1563
+ var Interaction = z7.object({
1564
+ id: Id5,
1565
+ sessionId: Id5,
1566
+ revision: z7.number().int().min(1),
1567
+ source: z7.discriminatedUnion("kind", [
1568
+ z7.object({
1569
+ kind: z7.literal("extension_ui"),
1570
+ method: z7.enum(["select", "confirm", "input", "editor"]),
1571
+ piRequestIds: z7.array(z7.string())
1572
+ }),
1573
+ z7.object({ kind: z7.literal("unsupported_custom"), title: z7.string().nullable() })
1574
+ ]),
1575
+ adapterId: z7.string().nullable(),
1576
+ permission: PolicyPermission.optional(),
1577
+ title: z7.string(),
1578
+ presentation: UINodeSchema,
1579
+ state: InteractionState,
1580
+ resolution: z7.object({ by: z7.string(), summary: z7.string(), at: Iso2 }).nullable(),
1581
+ createdAt: Iso2
1582
+ });
1583
+ var AttentionReason = z7.enum([
1584
+ "needs_input",
1585
+ "failed",
1586
+ "ready_for_review",
1587
+ "unsupported_interaction",
1588
+ "host_unreachable",
1589
+ "cache_expiring"
1590
+ ]);
1591
+ var AttentionItem = z7.object({
1592
+ id: Id5,
1593
+ sessionId: Id5.nullable(),
1594
+ taskId: Id5.nullable(),
1595
+ projectId: Id5.nullable(),
1596
+ reason: AttentionReason,
1597
+ severity: z7.enum(["info", "warning", "critical"]),
1598
+ summary: z7.string(),
1599
+ interactionId: Id5.nullable(),
1600
+ deepLink: z7.string(),
1601
+ acknowledgedAt: Iso2.nullable(),
1602
+ resolvedAt: Iso2.nullable(),
1603
+ createdAt: Iso2
1604
+ });
1605
+ var Device = z7.object({
1606
+ id: Id5,
1607
+ name: z7.string(),
1608
+ kind: DeviceKind,
1609
+ createdAt: Iso2,
1610
+ lastSeenAt: Iso2.nullable(),
1611
+ revokedAt: Iso2.nullable(),
1612
+ push: z7.object({
1613
+ subscribed: z7.boolean(),
1614
+ permission: z7.enum(["granted", "denied", "default", "unknown"])
1615
+ }),
1616
+ preferredMobile: z7.boolean(),
1617
+ enrolledVia: z7.enum(["enrollment", "passkey", "oidc", "admin", "approval"]).default("enrollment")
1618
+ });
1619
+ var ToolItemData = z7.object({
1620
+ toolCallId: z7.string(),
1621
+ name: z7.string(),
1622
+ status: z7.enum(["running", "ok", "error"]),
1623
+ args: z7.unknown(),
1624
+ summary: z7.string(),
1625
+ output: z7.string(),
1626
+ startedAt: Iso2,
1627
+ durationMs: z7.number().nullable(),
1628
+ card: UINodeSchema.nullable(),
1629
+ adapterId: z7.string().nullable(),
1630
+ adapterGeneration: z7.string().uuid().optional()
1631
+ });
1632
+ var TranscriptItem = z7.discriminatedUnion("kind", [
1633
+ z7.object({
1634
+ id: Id5,
1635
+ sessionId: Id5,
1636
+ order: z7.number().int(),
1637
+ at: Iso2,
1638
+ kind: z7.literal("user"),
1639
+ data: z7.object({
1640
+ text: z7.string(),
1641
+ images: z7.number().int().optional(),
1642
+ /** Pi session entry id, for rewind and fork from this message. */
1643
+ entryId: z7.string().optional()
1644
+ })
1645
+ }),
1646
+ z7.object({
1647
+ id: Id5,
1648
+ sessionId: Id5,
1649
+ order: z7.number().int(),
1650
+ at: Iso2,
1651
+ kind: z7.literal("assistant"),
1652
+ data: z7.object({ text: z7.string(), streaming: z7.boolean().optional() })
1653
+ }),
1654
+ z7.object({
1655
+ id: Id5,
1656
+ sessionId: Id5,
1657
+ order: z7.number().int(),
1658
+ at: Iso2,
1659
+ kind: z7.literal("thinking"),
1660
+ data: z7.object({ text: z7.string() })
1661
+ }),
1662
+ z7.object({
1663
+ id: Id5,
1664
+ sessionId: Id5,
1665
+ order: z7.number().int(),
1666
+ at: Iso2,
1667
+ kind: z7.literal("tool"),
1668
+ data: ToolItemData
1669
+ }),
1670
+ z7.object({
1671
+ id: Id5,
1672
+ sessionId: Id5,
1673
+ order: z7.number().int(),
1674
+ at: Iso2,
1675
+ kind: z7.literal("notice"),
1676
+ data: z7.object({
1677
+ level: DiagnosticLevel,
1678
+ text: z7.string(),
1679
+ customType: z7.string().min(1).max(200).optional(),
1680
+ card: UINodeSchema.optional(),
1681
+ adapterId: z7.string().optional(),
1682
+ adapterGeneration: z7.string().uuid().optional()
1683
+ }).refine((data) => !data.card || !!data.adapterId, "Card requires adapterId")
1684
+ }),
1685
+ z7.object({
1686
+ id: Id5,
1687
+ sessionId: Id5,
1688
+ order: z7.number().int(),
1689
+ at: Iso2,
1690
+ kind: z7.literal("interaction"),
1691
+ data: z7.object({ interactionId: Id5 })
1692
+ }),
1693
+ z7.object({
1694
+ id: Id5,
1695
+ sessionId: Id5,
1696
+ order: z7.number().int(),
1697
+ at: Iso2,
1698
+ kind: z7.literal("subagent"),
1699
+ data: z7.object({
1700
+ runId: z7.string(),
1701
+ label: z7.string(),
1702
+ status: z7.string(),
1703
+ sessionFile: z7.string().nullable(),
1704
+ linkedSessionId: Id5.nullable()
1705
+ })
1706
+ }),
1707
+ z7.object({
1708
+ id: Id5,
1709
+ sessionId: Id5,
1710
+ order: z7.number().int(),
1711
+ at: Iso2,
1712
+ kind: z7.literal("system"),
1713
+ data: z7.object({ text: z7.string(), suggestion: z7.boolean().optional() })
1714
+ })
1715
+ ]);
1716
+ var Panel = z7.object({
1717
+ sessionId: Id5,
1718
+ adapterId: z7.string(),
1719
+ slot: z7.string(),
1720
+ title: z7.string(),
1721
+ node: UINodeSchema.nullable(),
1722
+ webRenderer: z7.boolean(),
1723
+ mobileFallback: z7.string().nullable(),
1724
+ contribution: ContributionDescriptor.optional(),
1725
+ state: z7.unknown().optional(),
1726
+ adapterGeneration: z7.string().uuid().optional(),
1727
+ updatedAt: Iso2
1728
+ });
1729
+ var Diagnostic = z7.object({
1730
+ sessionId: Id5.nullable(),
1731
+ adapterId: z7.string().nullable(),
1732
+ level: DiagnosticLevel,
1733
+ message: z7.string(),
1734
+ at: Iso2
1735
+ });
1736
+ var AdapterInfo = z7.object({
1737
+ id: z7.string(),
1738
+ version: z7.string(),
1739
+ tier: z7.enum(["project", "owner", "plugin", "bundled"]),
1740
+ target: z7.object({
1741
+ extension: z7.string(),
1742
+ versionRange: z7.string(),
1743
+ testedVersions: z7.array(z7.string())
1744
+ }),
1745
+ capabilities: z7.array(z7.string()),
1746
+ webRenderer: z7.boolean(),
1747
+ status: z7.enum(["active", "disabled", "error"]),
1748
+ detail: z7.string().nullable()
1749
+ });
1750
+ var Passkey = z7.object({
1751
+ id: z7.string(),
1752
+ name: z7.string(),
1753
+ createdAt: Iso2,
1754
+ lastUsedAt: Iso2.nullable(),
1755
+ transports: z7.array(z7.string())
1756
+ });
1757
+
1758
+ // packages/protocol/dist/adapter-preview.js
1759
+ var ADAPTER_PREVIEW_MAX_BYTES = 1024 * 1024;
1760
+ var ADAPTER_PREVIEW_MAX_STEPS = 200;
1761
+ var ADAPTER_PREVIEW_SESSION_ID = "ses_adapter_preview";
1762
+ function bounded(input, ctx) {
1763
+ try {
1764
+ boundContributionJson(input, ADAPTER_PREVIEW_MAX_BYTES);
1765
+ return input;
1766
+ } catch (error) {
1767
+ ctx.addIssue({ code: "custom", message: error.message });
1768
+ return z8.NEVER;
1769
+ }
1770
+ }
1771
+ var Id6 = z8.string().min(1).max(200);
1772
+ var Text2 = z8.string().max(64 * 1024);
1773
+ var Tool = { toolCallId: Id6, name: Id6, args: z8.unknown() };
1774
+ var DialogCommon = { id: Id6, title: Text2 };
1775
+ var AdapterPreviewPiUiRequestSchema = z8.discriminatedUnion("method", [
1776
+ z8.object({
1777
+ ...DialogCommon,
1778
+ method: z8.literal("select"),
1779
+ options: z8.array(Text2).max(200),
1780
+ timeout: z8.number().nonnegative().optional()
1781
+ }).strict(),
1782
+ z8.object({
1783
+ ...DialogCommon,
1784
+ method: z8.literal("confirm"),
1785
+ message: Text2,
1786
+ timeout: z8.number().nonnegative().optional()
1787
+ }).strict(),
1788
+ z8.object({
1789
+ ...DialogCommon,
1790
+ method: z8.literal("input"),
1791
+ placeholder: Text2.optional(),
1792
+ timeout: z8.number().nonnegative().optional()
1793
+ }).strict(),
1794
+ z8.object({ ...DialogCommon, method: z8.literal("editor"), prefill: Text2.optional() }).strict()
1795
+ ]);
1796
+ var AdapterPreviewStepSchema = z8.discriminatedUnion("kind", [
1797
+ z8.object({ kind: z8.literal("restore") }).strict(),
1798
+ z8.object({ kind: z8.literal("toolStart"), data: z8.object(Tool).strict() }).strict(),
1799
+ z8.object({
1800
+ kind: z8.literal("toolUpdate"),
1801
+ data: z8.object({ ...Tool, partialResult: z8.unknown(), details: z8.unknown().optional() }).strict()
1802
+ }).strict(),
1803
+ z8.object({
1804
+ kind: z8.literal("toolEnd"),
1805
+ data: z8.object({
1806
+ ...Tool,
1807
+ result: z8.unknown(),
1808
+ isError: z8.boolean(),
1809
+ details: z8.unknown().optional()
1810
+ }).strict()
1811
+ }).strict(),
1812
+ z8.object({
1813
+ kind: z8.literal("status"),
1814
+ data: z8.object({ key: Id6, text: Text2.optional() }).strict()
1815
+ }).strict(),
1816
+ z8.object({
1817
+ kind: z8.literal("widget"),
1818
+ data: z8.object({ key: Id6, lines: z8.array(Text2).max(200).optional() }).strict()
1819
+ }).strict(),
1820
+ z8.object({ kind: z8.literal("dialog"), data: AdapterPreviewPiUiRequestSchema }).strict(),
1821
+ z8.object({
1822
+ kind: z8.literal("answer"),
1823
+ data: z8.object({ requestId: Id6, response: InteractionResponseSchema }).strict()
1824
+ }).strict(),
1825
+ z8.object({
1826
+ kind: z8.literal("customMessage"),
1827
+ data: z8.object({
1828
+ customType: Id6,
1829
+ content: z8.unknown(),
1830
+ display: z8.boolean().optional(),
1831
+ details: z8.unknown().optional()
1832
+ }).strict()
1833
+ }).strict(),
1834
+ z8.object({
1835
+ kind: z8.literal("action"),
1836
+ data: z8.object({ actionId: Id6, payload: z8.unknown() }).strict()
1837
+ }).strict()
1838
+ ]);
1839
+ var AdapterPreviewFixtureSchema = z8.unknown().transform(bounded).pipe(z8.object({
1840
+ version: z8.literal(1),
1841
+ name: z8.string().min(1).max(200),
1842
+ initialState: z8.record(z8.string(), z8.record(z8.string(), z8.unknown())).optional(),
1843
+ steps: z8.array(AdapterPreviewStepSchema).max(ADAPTER_PREVIEW_MAX_STEPS)
1844
+ }).strict());
1845
+ var PortableNode = z8.unknown().transform((input, ctx) => {
1846
+ try {
1847
+ return validateUINode(input);
1848
+ } catch (error) {
1849
+ ctx.addIssue({ code: "custom", message: error.message });
1850
+ return z8.NEVER;
1851
+ }
1852
+ });
1853
+ var PreviewPanel = Panel.extend({ webRenderer: z8.literal(false) }).superRefine((panel, ctx) => {
1854
+ try {
1855
+ if (panel.sessionId !== ADAPTER_PREVIEW_SESSION_ID)
1856
+ throw new Error("Preview panels must use the fake preview session");
1857
+ if (panel.node !== null)
1858
+ validateUINode(panel.node);
1859
+ if (panel.contribution) {
1860
+ const { id, ...descriptor } = panel.contribution;
1861
+ if (panel.slot !== contributionSlot(id))
1862
+ throw new Error("Contribution slot does not match its id");
1863
+ validateContribution(id, {
1864
+ ...descriptor,
1865
+ title: panel.title,
1866
+ node: panel.node,
1867
+ mobileFallback: panel.mobileFallback,
1868
+ ...panel.state === void 0 ? {} : { state: panel.state }
1869
+ });
1870
+ }
1871
+ } catch (error) {
1872
+ ctx.addIssue({ code: "custom", message: error.message });
1873
+ }
1874
+ });
1875
+ var AdapterPreviewSchema = z8.unknown().transform(bounded).pipe(z8.object({
1876
+ version: z8.literal(1),
1877
+ name: z8.string().min(1).max(200),
1878
+ adapter: z8.object({ id: Id6, version: Id6 }).strict(),
1879
+ steps: z8.array(z8.object({
1880
+ index: z8.number().int().min(0).max(ADAPTER_PREVIEW_MAX_STEPS - 1),
1881
+ kind: z8.enum([
1882
+ "restore",
1883
+ "toolStart",
1884
+ "toolUpdate",
1885
+ "toolEnd",
1886
+ "status",
1887
+ "widget",
1888
+ "dialog",
1889
+ "answer",
1890
+ "customMessage",
1891
+ "action"
1892
+ ]),
1893
+ ok: z8.boolean(),
1894
+ error: z8.string().max(4e3).nullable()
1895
+ }).strict()).max(ADAPTER_PREVIEW_MAX_STEPS),
1896
+ panels: z8.array(PreviewPanel).max(256),
1897
+ interactions: z8.array(z8.object({
1898
+ request: AdapterPreviewPiUiRequestSchema,
1899
+ presentation: PortableNode,
1900
+ state: z8.enum(["pending", "resolved"])
1901
+ }).strict()).max(ADAPTER_PREVIEW_MAX_STEPS),
1902
+ cards: z8.array(z8.unknown().transform((input, ctx) => {
1903
+ try {
1904
+ return validateContributionCard(input);
1905
+ } catch (error) {
1906
+ ctx.addIssue({ code: "custom", message: error.message });
1907
+ return z8.NEVER;
1908
+ }
1909
+ })).max(ADAPTER_PREVIEW_MAX_STEPS * 3),
1910
+ diagnostics: z8.array(Diagnostic.extend({ message: z8.string().max(4e3) }).refine((d) => d.sessionId === null || d.sessionId === ADAPTER_PREVIEW_SESSION_ID, "Preview diagnostics must use the fake preview session")).max(200)
1911
+ }).strict().superRefine((preview, ctx) => {
1912
+ const slots = /* @__PURE__ */ new Set();
1913
+ let contributions = 0;
1914
+ for (const panel of preview.panels) {
1915
+ if (panel.adapterId !== preview.adapter.id)
1916
+ ctx.addIssue({
1917
+ code: "custom",
1918
+ message: "Preview panel belongs to a different adapter"
1919
+ });
1920
+ const key = JSON.stringify([panel.adapterId, panel.slot]);
1921
+ if (slots.has(key))
1922
+ ctx.addIssue({ code: "custom", message: "Duplicate preview panel slot" });
1923
+ slots.add(key);
1924
+ if (panel.contribution && ++contributions > 64)
1925
+ ctx.addIssue({
1926
+ code: "custom",
1927
+ message: "At most 64 contributions per adapter/session"
1928
+ });
1929
+ }
1930
+ const requests = /* @__PURE__ */ new Set();
1931
+ for (const interaction of preview.interactions) {
1932
+ if (requests.has(interaction.request.id))
1933
+ ctx.addIssue({ code: "custom", message: "Duplicate preview dialog" });
1934
+ requests.add(interaction.request.id);
1935
+ }
1936
+ }));
1937
+
1938
+ // packages/protocol/dist/adapters.js
1939
+ import { z as z9 } from "zod";
1940
+ var Path = z9.string().max(4096);
1941
+ var SessionAdapterInfo = AdapterInfo.extend({
1942
+ runtimeStatus: z9.enum(["active", "disabled", "unavailable"]),
1943
+ runtimeDetail: z9.string().max(4e3).nullable(),
1944
+ provenance: z9.object({
1945
+ scope: z9.enum(["user", "project", "explicit"]),
1946
+ source: Path.nullable(),
1947
+ packageDir: Path.nullable(),
1948
+ manifestPath: Path.nullable(),
1949
+ targetVersion: z9.string().nullable(),
1950
+ entrypoints: z9.array(Path).max(128),
1951
+ evidence: z9.enum(["runtime-reported", "package-level", "explicit"])
1952
+ })
1953
+ });
1954
+ var SessionAdaptersResult = z9.object({
1955
+ generation: z9.string().uuid().nullable(),
1956
+ runtimeId: z9.string().nullable(),
1957
+ reloadable: z9.boolean(),
1958
+ blockedReason: z9.string().nullable(),
1959
+ adapters: z9.array(SessionAdapterInfo).max(256),
1960
+ diagnostics: z9.array(Diagnostic).max(100)
1961
+ });
1962
+
1963
+ // packages/protocol/dist/agent-wire.js
1964
+ import { z as z10 } from "zod";
1965
+ var Id7 = z10.string().min(1).max(200);
1966
+ var Instant3 = z10.string().refine((value) => {
1967
+ const date = new Date(value);
1968
+ return Number.isFinite(date.getTime()) && date.toISOString() === value;
1969
+ }, "Expected canonical UTC timestamp");
1970
+ var AGENT_FRAME_MAX_BYTES = 128 * 1024;
1971
+ var AgentMethod = z10.enum([
1972
+ "session.bind",
1973
+ "task.create",
1974
+ "message.send",
1975
+ "inbox.read",
1976
+ "receipt.peek",
1977
+ "policy.evaluate",
1978
+ "policy.status",
1979
+ "policy.cancel"
1980
+ ]);
1981
+ var AgentToolMethod = z10.enum(["task.create", "message.send", "inbox.read"]);
1982
+ var RequestHash = z10.string().regex(/^[a-f0-9]{64}$/);
1983
+ var AgentReceiptPeekRequest = z10.object({ method: AgentToolMethod, args: z10.record(z10.string(), z10.json()) }).strict();
1984
+ var AgentReceiptPeekResult = z10.discriminatedUnion("found", [
1985
+ z10.object({ found: z10.literal(false) }).strict(),
1986
+ z10.object({ found: z10.literal(true), requestHash: RequestHash }).strict()
1987
+ ]);
1988
+ var AgentReceiptReplay = z10.object({ requestHash: RequestHash }).strict();
1989
+ var CreateAgentTask = z10.object({
1990
+ objective: z10.string().min(1).max(16e3),
1991
+ acceptance: z10.array(z10.string().min(1).max(2e3)).max(100).default([]),
1992
+ dependencies: z10.array(Id7).max(100).default([]),
1993
+ parentTaskId: Id7.nullable().optional(),
1994
+ hostId: Id7.optional(),
1995
+ profileId: Id7.optional(),
1996
+ notifyOnFinish: z10.boolean().default(true)
1997
+ });
1998
+ var SendAgentMessage = z10.object({
1999
+ sessionId: Id7,
2000
+ body: z10.string().min(1).max(16e3),
2001
+ mode: z10.enum(["steer", "queue"]),
2002
+ replyTo: Id7.optional()
2003
+ });
2004
+ var ReadAgentInbox = z10.object({
2005
+ after: z10.number().int().nonnegative().default(0),
2006
+ limit: z10.number().int().min(1).max(100).default(20)
2007
+ });
2008
+ var DeliveryState = z10.enum([
2009
+ "pending",
2010
+ "held",
2011
+ "deferred",
2012
+ "accepted",
2013
+ "queued",
2014
+ "appended",
2015
+ "uncertain",
2016
+ "failed"
2017
+ ]);
2018
+ var AgentMessageFields = {
2019
+ seq: z10.number().int().positive(),
2020
+ id: Id7,
2021
+ recipientSessionId: Id7,
2022
+ replyTo: Id7.nullable(),
2023
+ chainId: Id7,
2024
+ depth: z10.number().int().min(0).max(4),
2025
+ body: z10.unknown(),
2026
+ requestedMode: z10.enum(["steer", "queue"]),
2027
+ deliveryState: DeliveryState,
2028
+ holdUntil: z10.string(),
2029
+ readAt: z10.string().nullable(),
2030
+ createdAt: z10.string()
2031
+ };
2032
+ var AgentMessage = z10.discriminatedUnion("kind", [
2033
+ z10.object({ ...AgentMessageFields, kind: z10.literal("message"), senderSessionId: Id7 }),
2034
+ z10.object({
2035
+ ...AgentMessageFields,
2036
+ kind: z10.literal("completion"),
2037
+ senderSessionId: Id7.nullable()
2038
+ })
2039
+ ]);
2040
+ var AgentInbox = z10.object({
2041
+ messages: z10.array(AgentMessage),
2042
+ nextAfter: z10.number().int().nonnegative(),
2043
+ hasMore: z10.boolean()
2044
+ });
2045
+ var AgentToolPolicyWait = PolicyEvaluation.options[2].omit({ verdict: true }).extend({ type: z10.literal("policy.required") }).strict();
2046
+ var AgentRequestFrame = z10.object({
2047
+ type: z10.literal("agent.request"),
2048
+ requestId: Id7,
2049
+ sessionId: Id7,
2050
+ nativeSessionId: Id7,
2051
+ runtimeId: Id7,
2052
+ context: z10.object({ humanInputId: Id7.nullable(), causalMessageId: Id7.nullable() }).strict(),
2053
+ toolCallId: Id7.optional(),
2054
+ receiptReplay: AgentReceiptReplay.optional(),
2055
+ // Tool-method ingress requires this separately; legacy/non-tool frames remain compatible.
2056
+ deadlineAt: Instant3.optional(),
2057
+ method: AgentMethod,
2058
+ args: z10.unknown()
2059
+ }).strict().superRefine((frame, ctx) => {
2060
+ if (frame.method === "receipt.peek") {
2061
+ if (!frame.toolCallId) {
2062
+ ctx.addIssue({
2063
+ code: "custom",
2064
+ path: ["toolCallId"],
2065
+ message: "Receipt lookup requires a tool call ID."
2066
+ });
2067
+ }
2068
+ }
2069
+ if (Object.hasOwn(frame, "receiptReplay") && !AgentToolMethod.safeParse(frame.method).success) {
2070
+ ctx.addIssue({
2071
+ code: "custom",
2072
+ path: ["receiptReplay"],
2073
+ message: "Receipt replay is only valid for tool methods."
2074
+ });
2075
+ }
2076
+ });
2077
+ var AgentResultFrame = z10.discriminatedUnion("ok", [
2078
+ z10.object({
2079
+ type: z10.literal("agent.result"),
2080
+ requestId: Id7,
2081
+ runtimeId: Id7,
2082
+ ok: z10.literal(true),
2083
+ result: z10.unknown()
2084
+ }),
2085
+ z10.object({
2086
+ type: z10.literal("agent.result"),
2087
+ requestId: Id7,
2088
+ runtimeId: Id7,
2089
+ ok: z10.literal(false),
2090
+ error: ErrorBody
2091
+ })
2092
+ ]);
2093
+
2094
+ // packages/protocol/dist/api.js
2095
+ import { z as z14 } from "zod";
2096
+
2097
+ // packages/protocol/dist/host-wire.js
2098
+ import { z as z13 } from "zod";
2099
+
2100
+ // packages/protocol/dist/events.js
2101
+ import { z as z11 } from "zod";
2102
+ var EventDataSchemas = {
2103
+ "host.updated": Host,
2104
+ "project.updated": Project,
2105
+ "project.deleted": z11.object({ id: z11.string() }),
2106
+ "checkout.updated": Checkout,
2107
+ "workspace.updated": Workspace,
2108
+ "workspace.deleted": z11.object({ id: z11.string() }),
2109
+ "profile.updated": Profile,
2110
+ "profile.deleted": z11.object({ id: z11.string() }),
2111
+ "view.updated": View,
2112
+ "view.deleted": z11.object({ id: z11.string() }),
2113
+ "session.updated": Session,
2114
+ "transcript.item": TranscriptItem,
2115
+ "transcript.reset": z11.object({ sessionId: z11.string(), epoch: z11.number().int() }),
2116
+ "interaction.updated": Interaction,
2117
+ "panel.updated": Panel,
2118
+ "adapters.updated": z11.object({ hostId: z11.string(), adapters: z11.array(AdapterInfo) }),
2119
+ diagnostic: Diagnostic,
2120
+ "task.updated": Task,
2121
+ "task.deleted": z11.object({ id: z11.string() }),
2122
+ "run.updated": Run,
2123
+ "automation.updated": Automation,
2124
+ "automation.deleted": z11.object({ id: z11.string() }),
2125
+ "occurrence.created": Occurrence,
2126
+ "occurrence.updated": Occurrence,
2127
+ "attention.updated": AttentionItem,
2128
+ "device.updated": Device,
2129
+ "settings.updated": z11.object({ dispatchPaused: z11.boolean() })
2130
+ };
2131
+ var EVENT_TYPES = Object.keys(EventDataSchemas);
2132
+ var LEGACY_EVENT_TYPES = {
2133
+ "workspace.removed": "workspace.deleted"
2134
+ };
2135
+ function canonicalEventType(type) {
2136
+ return LEGACY_EVENT_TYPES[type] ?? type;
2137
+ }
2138
+ var canonical = (v) => typeof v === "string" ? canonicalEventType(v) : v;
2139
+ var EventTypeSchema = z11.preprocess(canonical, z11.enum(EVENT_TYPES));
2140
+ var EventScope = z11.object({
2141
+ hostId: z11.string().optional(),
2142
+ sessionId: z11.string().optional(),
2143
+ taskId: z11.string().optional(),
2144
+ projectId: z11.string().optional()
2145
+ });
2146
+ var EventEnvelope = EventScope.extend({
2147
+ seq: z11.number().int(),
2148
+ id: z11.string(),
2149
+ type: EventTypeSchema,
2150
+ at: z11.string(),
2151
+ data: z11.unknown()
2152
+ });
2153
+ var HOST_EVENT_TYPES = [
2154
+ "session.updated",
2155
+ "transcript.item",
2156
+ "interaction.updated",
2157
+ "panel.updated",
2158
+ "adapters.updated",
2159
+ "diagnostic",
2160
+ "workspace.updated",
2161
+ "workspace.deleted"
2162
+ ];
2163
+ var HostEvent = EventScope.extend({
2164
+ eventId: z11.string(),
2165
+ type: z11.preprocess(canonical, z11.enum(HOST_EVENT_TYPES)),
2166
+ at: z11.string(),
2167
+ data: z11.unknown()
2168
+ });
2169
+ var StreamDelta = z11.object({
2170
+ sessionId: z11.string(),
2171
+ itemId: z11.string(),
2172
+ kind: z11.enum(["text", "thinking", "tool_args", "tool_output"]),
2173
+ delta: z11.string(),
2174
+ order: z11.number().int().optional()
2175
+ });
2176
+
2177
+ // packages/protocol/dist/terminal-wire.js
2178
+ import { z as z12 } from "zod";
2179
+ var Cols = z12.number().int().min(10).max(1e3);
2180
+ var Rows = z12.number().int().min(5).max(500);
2181
+ var TermViewerToServer = z12.discriminatedUnion("t", [
2182
+ z12.object({ t: z12.literal("in"), d: z12.string() }),
2183
+ z12.object({ t: z12.literal("resize"), cols: Cols, rows: Rows }),
2184
+ z12.object({ t: z12.literal("claim") })
2185
+ ]);
2186
+ var TermServerToViewer = z12.discriminatedUnion("t", [
2187
+ z12.object({ t: z12.literal("out"), d: z12.string() }),
2188
+ z12.object({ t: z12.literal("closed"), reason: z12.string() }),
2189
+ z12.object({ t: z12.literal("size"), cols: Cols, rows: Rows, owner: z12.boolean() })
2190
+ ]);
2191
+ var TermCoordinatorMsg = z12.discriminatedUnion("t", [
2192
+ z12.object({
2193
+ t: z12.literal("open"),
2194
+ sessionId: z12.string(),
2195
+ cols: Cols,
2196
+ rows: Rows,
2197
+ passive: z12.boolean().optional()
2198
+ }),
2199
+ z12.object({ t: z12.literal("claim") }),
2200
+ z12.object({ t: z12.literal("in"), d: z12.string() }),
2201
+ z12.object({ t: z12.literal("resize"), cols: Cols, rows: Rows }),
2202
+ z12.object({ t: z12.literal("close") })
2203
+ ]);
2204
+
2205
+ // packages/protocol/dist/host-wire.js
2206
+ var Origin = z13.enum(["human", "automation"]);
2207
+ var HostCommand = z13.discriminatedUnion("type", [
2208
+ z13.object({
2209
+ type: z13.literal("session.start"),
2210
+ sessionId: z13.string(),
2211
+ title: z13.string(),
2212
+ workspacePath: z13.string(),
2213
+ projectId: z13.string().nullable(),
2214
+ profile: Profile,
2215
+ nativeHandle: NativeHandle.nullable(),
2216
+ initialPrompt: z13.string().nullable(),
2217
+ dispatchKey: z13.string().nullable(),
2218
+ controlRevision: z13.number().int(),
2219
+ controlMode: ControlMode,
2220
+ origin: Origin,
2221
+ readOnly: z13.boolean().default(false),
2222
+ policyRequired: z13.boolean().optional()
2223
+ }),
2224
+ z13.object({
2225
+ type: z13.literal("session.deliverMessage"),
2226
+ sessionId: z13.string(),
2227
+ messageId: z13.string(),
2228
+ payload: z13.object({
2229
+ deliveryId: z13.string(),
2230
+ kind: z13.enum(["message", "completion"]),
2231
+ text: z13.string()
2232
+ }),
2233
+ mode: z13.enum(["steer", "queue"]),
2234
+ holdUntil: z13.string()
2235
+ }),
2236
+ HostPolicySampleRequest.extend({ type: z13.literal("session.classifyPolicySample") }),
2237
+ z13.object({
2238
+ type: z13.literal("session.messageStatus"),
2239
+ sessionId: z13.string(),
2240
+ messageIds: z13.array(z13.string().min(1)).min(1).max(100)
2241
+ }),
2242
+ z13.object({
2243
+ type: z13.literal("session.prompt"),
2244
+ sessionId: z13.string(),
2245
+ text: z13.string(),
2246
+ images: z13.array(z13.object({ mimeType: z13.string(), data: z13.string() })).default([]),
2247
+ mode: z13.enum(["prompt", "steer", "followUp"]),
2248
+ origin: Origin,
2249
+ controlRevision: z13.number().int()
2250
+ }),
2251
+ z13.object({ type: z13.literal("session.abort"), sessionId: z13.string(), clearQueue: z13.boolean() }),
2252
+ z13.object({ type: z13.literal("session.stop"), sessionId: z13.string() }),
2253
+ z13.object({
2254
+ type: z13.literal("session.answer"),
2255
+ sessionId: z13.string(),
2256
+ interactionId: z13.string(),
2257
+ revision: z13.number().int(),
2258
+ response: InteractionResponseSchema,
2259
+ deviceId: z13.string()
2260
+ }),
2261
+ z13.object({
2262
+ type: z13.literal("session.adapterAction"),
2263
+ sessionId: z13.string(),
2264
+ generation: z13.string().uuid().optional(),
2265
+ adapterId: z13.string(),
2266
+ actionId: z13.string(),
2267
+ payload: z13.unknown()
2268
+ }),
2269
+ z13.object({
2270
+ type: z13.literal("session.setControl"),
2271
+ sessionId: z13.string(),
2272
+ controlRevision: z13.number().int(),
2273
+ mode: ControlMode
2274
+ }),
2275
+ z13.object({ type: z13.literal("session.rename"), sessionId: z13.string(), title: z13.string() }),
2276
+ z13.object({ type: z13.literal("session.importable") }),
2277
+ z13.object({ type: z13.literal("session.readNative"), sessionFile: z13.string() }),
2278
+ z13.object({ type: z13.literal("session.snapshot"), sessionId: z13.string() }),
2279
+ z13.object({ type: z13.literal("session.models"), sessionId: z13.string() }),
2280
+ z13.object({ type: z13.literal("session.commands"), sessionId: z13.string() }),
2281
+ z13.object({
2282
+ type: z13.literal("session.complete"),
2283
+ sessionId: z13.string(),
2284
+ text: z13.string().max(500)
2285
+ }),
2286
+ z13.object({ type: z13.literal("session.tree"), sessionId: z13.string() }),
2287
+ z13.object({
2288
+ type: z13.literal("session.branch"),
2289
+ sessionId: z13.string(),
2290
+ entryId: z13.string().nullable(),
2291
+ fork: z13.boolean()
2292
+ }),
2293
+ z13.object({
2294
+ type: z13.literal("session.navigate"),
2295
+ sessionId: z13.string(),
2296
+ entryId: z13.string(),
2297
+ summarize: z13.boolean(),
2298
+ instructions: z13.string().max(2e3).nullable()
2299
+ }),
2300
+ z13.object({ type: z13.literal("session.reload"), sessionId: z13.string() }),
2301
+ z13.object({ type: z13.literal("session.adapters"), sessionId: z13.string() }),
2302
+ z13.object({ type: z13.literal("session.reloadAdapters"), sessionId: z13.string() }),
2303
+ z13.object({ type: z13.literal("session.export"), sessionId: z13.string() }),
2304
+ z13.object({
2305
+ type: z13.literal("session.setModel"),
2306
+ sessionId: z13.string(),
2307
+ provider: z13.string().min(1),
2308
+ modelId: z13.string().min(1)
2309
+ }),
2310
+ z13.object({ type: z13.literal("session.setThinking"), sessionId: z13.string(), level: ThinkingLevel }),
2311
+ z13.object({
2312
+ type: z13.literal("session.compact"),
2313
+ sessionId: z13.string(),
2314
+ instructions: z13.string().nullable()
2315
+ }),
2316
+ z13.object({ type: z13.literal("checkout.inspect"), path: z13.string() }),
2317
+ z13.object({ type: z13.literal("projects.scan"), folder: z13.string().min(1) }),
2318
+ z13.object({
2319
+ type: z13.literal("projects.suggest"),
2320
+ days: z13.number().int().min(1).max(365).default(30)
2321
+ }),
2322
+ z13.object({
2323
+ type: z13.literal("workspace.discover"),
2324
+ checkoutPath: z13.string(),
2325
+ worktreeDir: z13.string().default(DEFAULT_WORKTREE_DIR)
2326
+ }),
2327
+ z13.object({
2328
+ type: z13.literal("workspace.create"),
2329
+ checkoutPath: z13.string(),
2330
+ branch: z13.string(),
2331
+ base: z13.string(),
2332
+ setupCommand: z13.string().nullable(),
2333
+ worktreeDir: z13.string().default(DEFAULT_WORKTREE_DIR)
2334
+ }),
2335
+ z13.object({ type: z13.literal("workspace.status"), path: z13.string(), base: z13.string().nullable() }),
2336
+ z13.object({
2337
+ type: z13.literal("workspace.remove"),
2338
+ path: z13.string(),
2339
+ checkoutPath: z13.string(),
2340
+ base: z13.string().nullable(),
2341
+ force: z13.object({ dirty: z13.boolean(), unmerged: z13.boolean() }),
2342
+ /** Also delete the worktree's local branch (hosts before trackers ignore it). */
2343
+ deleteBranch: z13.boolean().optional()
2344
+ }),
2345
+ z13.object({
2346
+ type: z13.literal("workspace.diff"),
2347
+ path: z13.string(),
2348
+ base: z13.string().nullable(),
2349
+ file: z13.string().nullable()
2350
+ }),
2351
+ z13.object({ type: z13.literal("workspace.files"), path: z13.string(), dir: z13.string() }),
2352
+ z13.object({ type: z13.literal("workspace.readFile"), path: z13.string(), file: z13.string() }),
2353
+ GitHubHostViewRequest.extend({ type: z13.literal("workspace.prView") }),
2354
+ GitHubHostLogsRequest.extend({ type: z13.literal("workspace.prFailedLogs") }),
2355
+ GitHubHostMergeRequest.extend({ type: z13.literal("workspace.prMerge") }),
2356
+ TrackerHostSyncRequest.extend({ type: z13.literal("tracker.sync") }),
2357
+ TrackerHostPrepareBranchRequest.extend({ type: z13.literal("tracker.prepareBranch") }),
2358
+ TrackerHostStartIssueRequest.extend({ type: z13.literal("tracker.startIssue") }),
2359
+ TrackerHostSetStatusRequest.extend({ type: z13.literal("tracker.setStatus") }),
2360
+ z13.object({
2361
+ type: z13.literal("dispatch.start"),
2362
+ dispatchKey: z13.string(),
2363
+ runId: z13.string(),
2364
+ taskId: z13.string(),
2365
+ sessionId: z13.string(),
2366
+ projectId: z13.string(),
2367
+ title: z13.string(),
2368
+ workspace: z13.union([
2369
+ z13.object({ path: z13.string() }),
2370
+ z13.object({
2371
+ createFrom: z13.object({
2372
+ checkoutPath: z13.string(),
2373
+ branch: z13.string(),
2374
+ base: z13.string(),
2375
+ setupCommand: z13.string().nullable(),
2376
+ worktreeDir: z13.string().default(DEFAULT_WORKTREE_DIR)
2377
+ })
2378
+ })
2379
+ ]),
2380
+ nativeHandle: NativeHandle.nullable(),
2381
+ profile: Profile,
2382
+ prompt: z13.string(),
2383
+ /** The launch's own revision; a takeover always carries a newer one. */
2384
+ controlRevision: z13.number().int(),
2385
+ controlMode: ControlMode.default("automation"),
2386
+ policyRequired: z13.boolean().optional()
2387
+ }),
2388
+ z13.object({ type: z13.literal("dispatch.reconcile"), dispatchKey: z13.string() }),
2389
+ z13.object({
2390
+ type: z13.literal("checks.run"),
2391
+ sessionId: z13.string(),
2392
+ path: z13.string(),
2393
+ commands: z13.array(z13.string())
2394
+ })
2395
+ ]);
2396
+ var ImportableSession = z13.object({
2397
+ sessionFile: z13.string(),
2398
+ sessionId: z13.string(),
2399
+ cwd: z13.string(),
2400
+ name: z13.string().nullable(),
2401
+ mtime: z13.string(),
2402
+ inactive: z13.boolean()
2403
+ });
2404
+ var DiscoveredWorktree = z13.object({
2405
+ path: z13.string(),
2406
+ head: z13.string().nullable(),
2407
+ branch: z13.string().nullable(),
2408
+ bare: z13.boolean(),
2409
+ detached: z13.boolean(),
2410
+ locked: z13.boolean(),
2411
+ prunable: z13.boolean(),
2412
+ provenance: z13.enum(["managed", "discovered", "main"]),
2413
+ git: GitState.nullable()
2414
+ });
2415
+ var CheckoutInfo = z13.object({
2416
+ root: z13.string(),
2417
+ commonDir: z13.string(),
2418
+ repoIdentity: z13.string(),
2419
+ defaultBranch: z13.string()
2420
+ });
2421
+ var ScannedRepository = CheckoutInfo.extend({ name: z13.string() });
2422
+ var ProjectFolderScan = z13.object({
2423
+ /** The folder, ~ expanded and realpath'd. */
2424
+ folder: z13.string(),
2425
+ repositories: z13.array(ScannedRepository)
2426
+ });
2427
+ var ProjectSuggestion = z13.object({
2428
+ rootPath: z13.string(),
2429
+ sessionCount: z13.number().int(),
2430
+ lastActivityAt: z13.string()
2431
+ });
2432
+ var ProjectSuggestions = z13.object({ suggestions: z13.array(ProjectSuggestion) });
2433
+ var DiffFile = z13.object({
2434
+ path: z13.string(),
2435
+ oldPath: z13.string().nullable(),
2436
+ added: z13.number().int(),
2437
+ deleted: z13.number().int(),
2438
+ status: z13.enum(["added", "modified", "deleted", "renamed", "untracked", "binary"])
2439
+ });
2440
+ var DiffResult = z13.object({
2441
+ base: z13.string(),
2442
+ files: z13.array(DiffFile),
2443
+ patch: z13.string().nullable()
2444
+ });
2445
+ var FileEntry = z13.object({
2446
+ name: z13.string(),
2447
+ path: z13.string(),
2448
+ kind: z13.enum(["file", "dir", "symlink"]),
2449
+ size: z13.number().int().nullable()
2450
+ });
2451
+ var ReconcileResult = z13.union([
2452
+ z13.object({ known: z13.literal(false) }),
2453
+ z13.object({
2454
+ known: z13.literal(true),
2455
+ sessionId: z13.string().nullable(),
2456
+ state: z13.enum(["accepted", "workspace_ready", "started", "failed"]),
2457
+ runtime: RuntimeState.nullable(),
2458
+ workspacePath: z13.string().nullable(),
2459
+ nativeHandle: NativeHandle.nullable(),
2460
+ error: z13.string().nullable(),
2461
+ /** `{started: "unknown"}` when the host restarted after Pi may have been spawned. */
2462
+ errorDetails: z13.record(z13.string(), z13.unknown()).nullable().default(null)
2463
+ })
2464
+ ]);
2465
+ var DispatchStartResult = z13.object({
2466
+ sessionId: z13.string(),
2467
+ workspacePath: z13.string(),
2468
+ nativeHandle: NativeHandle.nullable(),
2469
+ reused: z13.boolean(),
2470
+ /** Why the launch prompt was not delivered to Pi (the session itself started), if it was not. */
2471
+ promptError: z13.string().nullable().optional()
2472
+ });
2473
+ var AnswerResult = z13.object({
2474
+ status: z13.enum(["answered", "already_answered"]),
2475
+ interaction: Interaction
2476
+ });
2477
+ var SnapshotResult = z13.object({
2478
+ partial: z13.array(TranscriptItem),
2479
+ pendingInteractions: z13.array(Interaction)
2480
+ });
2481
+ var ChecksResult = z13.object({ results: z13.array(CheckResult) });
2482
+ var Receipt = z13.union([
2483
+ z13.object({ commandId: z13.string(), ok: z13.literal(true), result: z13.unknown() }),
2484
+ z13.object({ commandId: z13.string(), ok: z13.literal(false), error: ErrorBody })
2485
+ ]);
2486
+ var HostAgentRequestFrame = AgentRequestFrame.safeExtend({
2487
+ policyContext: HostToolPolicyContext.optional()
2488
+ }).strict().superRefine((frame, ctx) => {
2489
+ if (frame.method === "policy.evaluate" ? frame.policyContext === void 0 : Object.hasOwn(frame, "policyContext")) {
2490
+ ctx.addIssue({
2491
+ code: "custom",
2492
+ path: ["policyContext"],
2493
+ message: "Host policy context is required only for policy.evaluate."
2494
+ });
2495
+ }
2496
+ try {
2497
+ if (new TextEncoder().encode(JSON.stringify(frame)).length <= AGENT_FRAME_MAX_BYTES)
2498
+ return;
2499
+ } catch {
2500
+ }
2501
+ ctx.addIssue({ code: "custom", message: "Host agent frame exceeds 128 KiB or is not JSON." });
2502
+ });
2503
+ var HostToCoordinator = z13.discriminatedUnion("type", [
2504
+ z13.object({
2505
+ type: z13.literal("hello"),
2506
+ hostId: z13.string(),
2507
+ credential: z13.string(),
2508
+ name: z13.string(),
2509
+ agentVersion: z13.string(),
2510
+ piVersion: z13.string().nullable(),
2511
+ piCompatible: z13.boolean(),
2512
+ platform: Platform,
2513
+ capabilities: RuntimeCapabilities.nullable(),
2514
+ github: HostGitHub.optional(),
2515
+ protocolVersion: z13.number().int(),
2516
+ features: z13.array(z13.string()).optional()
2517
+ }),
2518
+ HostAgentRequestFrame,
2519
+ z13.object({ type: z13.literal("event"), hostSeq: z13.number().int(), event: HostEvent }),
2520
+ z13.object({ type: z13.literal("stream"), delta: StreamDelta }),
2521
+ z13.object({ type: z13.literal("receipt"), receipt: Receipt }),
2522
+ z13.object({ type: z13.literal("pong") }),
2523
+ z13.object({ type: z13.literal("usage"), usage: z13.array(ProviderUsage) }),
2524
+ z13.object({ type: z13.literal("term"), streamId: z13.string(), msg: TermServerToViewer })
2525
+ ]);
2526
+ var CoordinatorToHost = z13.discriminatedUnion("type", [
2527
+ z13.object({
2528
+ type: z13.literal("welcome"),
2529
+ coordinatorVersion: z13.string(),
2530
+ ackedHostSeq: z13.number().int(),
2531
+ features: z13.array(z13.string()).optional()
2532
+ }),
2533
+ AgentResultFrame,
2534
+ z13.object({ type: z13.literal("ack"), hostSeq: z13.number().int() }),
2535
+ z13.object({ type: z13.literal("command"), commandId: z13.string(), command: HostCommand }),
2536
+ z13.object({ type: z13.literal("ping") }),
2537
+ z13.object({ type: z13.literal("reject"), error: ErrorBody }),
2538
+ z13.object({ type: z13.literal("term"), streamId: z13.string(), msg: TermCoordinatorMsg })
2539
+ ]);
2540
+
2541
+ // packages/protocol/dist/api.js
2542
+ var EnrollRequest = z14.object({
2543
+ token: z14.string().min(1),
2544
+ name: z14.string().min(1).max(80),
2545
+ kind: DeviceKind
2546
+ });
2547
+ var EnrollResponse = z14.object({ deviceId: z14.string(), credential: z14.string() });
2548
+ var CreateEnrollmentRequest = z14.object({ kind: z14.enum(["device", "host"]) });
2549
+ var CreateEnrollmentResponse = z14.object({
2550
+ token: z14.string(),
2551
+ url: z14.string(),
2552
+ expiresAt: z14.string(),
2553
+ qrSvg: z14.string(),
2554
+ command: z14.string().nullable()
2555
+ });
2556
+ var HostEnrollRequest = z14.union([
2557
+ z14.object({
2558
+ token: z14.string().min(1),
2559
+ name: z14.string().min(1).max(80),
2560
+ platform: Platform
2561
+ }),
2562
+ z14.object({
2563
+ secret: z14.string().min(1),
2564
+ name: z14.string().min(1).max(80),
2565
+ platform: Platform
2566
+ })
2567
+ ]);
2568
+ var HostEnrollResponse = z14.object({ hostId: z14.string(), credential: z14.string() });
2569
+ var CreateProjectRequest = z14.object({
2570
+ name: z14.string().min(1),
2571
+ hostId: z14.string(),
2572
+ path: z14.string().min(1),
2573
+ defaultProfileId: z14.string().nullable().optional(),
2574
+ setupCommand: z14.string().nullable().optional(),
2575
+ checks: z14.array(z14.string()).optional(),
2576
+ maxConcurrentRuns: z14.number().int().min(1).max(32).optional(),
2577
+ worktreeDir: WorktreeDir.optional()
2578
+ });
2579
+ var UpdateProjectRequest = z14.object({
2580
+ name: z14.string().min(1).optional(),
2581
+ defaultProfileId: z14.string().nullable().optional(),
2582
+ defaultHostId: z14.string().nullable().optional(),
2583
+ maxConcurrentRuns: z14.number().int().min(1).max(32).optional(),
2584
+ automationEnabled: z14.boolean().optional(),
2585
+ setupCommand: z14.string().nullable().optional(),
2586
+ checks: z14.array(z14.string()).optional(),
2587
+ workspaceSharing: z14.enum(["single_writer", "shared"]).optional(),
2588
+ worktreeDir: WorktreeDir.optional(),
2589
+ ensureSessions: z14.boolean().optional(),
2590
+ removeLanded: z14.boolean().optional()
2591
+ });
2592
+ var AddCheckoutRequest = z14.object({ hostId: z14.string(), path: z14.string().min(1) });
2593
+ function isProjectFolderPath(s) {
2594
+ if (s.includes("\0"))
2595
+ return false;
2596
+ return s === "~" || s.startsWith("~/") || s.startsWith("/");
2597
+ }
2598
+ var ProjectFolder = z14.string().trim().min(1).max(1024).refine(isProjectFolderPath, "must be an absolute path or start with ~/");
2599
+ var UpdateHostRequest = z14.object({
2600
+ projectFolders: z14.array(ProjectFolder).max(20).optional()
2601
+ });
2602
+ var ProjectScanResult = ProjectScan.extend({
2603
+ added: z14.array(z14.object({
2604
+ projectId: z14.string(),
2605
+ name: z14.string(),
2606
+ path: z14.string(),
2607
+ newProject: z14.boolean()
2608
+ }))
2609
+ });
2610
+ var ProfileInput = z14.object({
2611
+ name: z14.string().min(1),
2612
+ provider: z14.string().nullable().default(null),
2613
+ model: z14.string().nullable().default(null),
2614
+ thinking: ThinkingLevel.nullable().default(null),
2615
+ projectTrust: z14.enum(["ask", "approve", "ignore"]).default("ask"),
2616
+ extraArgs: z14.array(ExtraArg).default([]),
2617
+ resources: z14.enum(["all", "vanilla"]).default("all")
2618
+ });
2619
+ var CreateWorkspaceRequest = z14.object({
2620
+ checkoutId: z14.string(),
2621
+ branch: z14.string().min(1),
2622
+ base: z14.string().nullable().optional()
2623
+ });
2624
+ var RemoveWorkspaceRequest = z14.object({
2625
+ force: z14.object({ dirty: z14.boolean(), unmerged: z14.boolean() }).default({ dirty: false, unmerged: false })
2626
+ });
2627
+ var CreateSessionRequest = z14.object({
2628
+ projectId: z14.string(),
2629
+ workspace: z14.union([
2630
+ z14.object({ existingId: z14.string() }),
2631
+ z14.object({
2632
+ checkoutId: z14.string(),
2633
+ newBranch: z14.string().min(1),
2634
+ base: z14.string().nullable().optional()
2635
+ })
2636
+ ]),
2637
+ profileId: z14.string().nullable().optional(),
2638
+ prompt: z14.string().default(""),
2639
+ title: z14.string().optional(),
2640
+ viewId: z14.string().optional()
2641
+ });
2642
+ var PromptRequest = z14.object({
2643
+ text: z14.string().min(1),
2644
+ mode: z14.enum(["prompt", "steer", "followUp"]).default("prompt"),
2645
+ images: z14.array(z14.object({ mimeType: z14.string(), data: z14.string() })).default([]),
2646
+ clientMessageId: z14.string().optional()
2647
+ });
2648
+ var CacheAlertRequest = z14.object({
2649
+ enabled: z14.boolean(),
2650
+ ttlSec: z14.number().int().min(60).max(86400).nullable().default(null)
2651
+ });
2652
+ var RenameRequest = z14.object({ title: z14.string().min(1).max(200) });
2653
+ var SetModelRequest = z14.object({
2654
+ provider: z14.string().min(1),
2655
+ modelId: z14.string().min(1)
2656
+ });
2657
+ var SetThinkingRequest = z14.object({ level: ThinkingLevel });
2658
+ var CompactRequest = z14.object({ instructions: z14.string().max(4e3).optional() });
2659
+ var SessionModelsResult = z14.object({ models: z14.array(SessionModel) });
2660
+ var SessionCommandsResult = z14.object({ commands: z14.array(SlashCommand) });
2661
+ var CompleteRequest = z14.object({ text: z14.string().min(1).max(500) });
2662
+ var CompletionItem = z14.object({
2663
+ value: z14.string(),
2664
+ label: z14.string(),
2665
+ description: z14.string().nullable()
2666
+ });
2667
+ var SessionCompleteResult = z14.object({
2668
+ items: z14.array(CompletionItem).max(50),
2669
+ prefix: z14.string()
2670
+ });
2671
+ var TreeRow = z14.object({
2672
+ entryId: z14.string(),
2673
+ parentId: z14.string().nullable(),
2674
+ depth: z14.number().int(),
2675
+ role: z14.enum(["user", "assistant"]),
2676
+ text: z14.string(),
2677
+ activeBranch: z14.boolean(),
2678
+ leaf: z14.boolean(),
2679
+ label: z14.string().nullable(),
2680
+ at: z14.string().nullable()
2681
+ });
2682
+ var SessionTreeResult = z14.object({ rows: z14.array(TreeRow) });
2683
+ var BranchRequest = z14.object({
2684
+ entryId: z14.string().nullable(),
2685
+ fork: z14.boolean().default(false)
2686
+ });
2687
+ var HostBranchResult = z14.object({
2688
+ sessionFile: z14.string().nullable(),
2689
+ prefill: z14.string().nullable()
2690
+ });
2691
+ var TranscriptPage = z14.object({
2692
+ items: z14.array(TranscriptItem),
2693
+ hasMore: z14.boolean(),
2694
+ epoch: z14.number().int().optional(),
2695
+ rev: z14.number().int().optional(),
2696
+ delta: z14.boolean().optional(),
2697
+ reset: z14.boolean().optional()
2698
+ });
2699
+ var NavigateRequest = z14.object({
2700
+ entryId: z14.string().min(1),
2701
+ summarize: z14.boolean().default(false),
2702
+ instructions: z14.string().max(2e3).nullable().default(null)
2703
+ });
2704
+ var HostNavigateResult = z14.object({
2705
+ items: z14.array(TranscriptItem),
2706
+ prefill: z14.string().nullable()
2707
+ });
2708
+ var NavigateResult = z14.object({
2709
+ prefill: z14.string().nullable(),
2710
+ epoch: z14.number().int()
2711
+ });
2712
+ var BranchResult = z14.object({
2713
+ session: Session.nullable(),
2714
+ prefill: z14.string().nullable()
2715
+ });
2716
+ var SessionExportResult = z14.object({ fileName: z14.string(), content: z14.string() });
2717
+ var CommandViewAction = z14.object({
2718
+ label: z14.string().min(1).max(80),
2719
+ command: z14.string().startsWith("/").max(500),
2720
+ tone: z14.enum(["default", "primary", "danger"]).optional()
2721
+ });
2722
+ var CommandView = z14.object({
2723
+ title: z14.string().min(1).max(200),
2724
+ body: UINodeSchema,
2725
+ actions: z14.array(CommandViewAction).max(30).default([])
2726
+ });
2727
+ var ModelStateResult = z14.object({
2728
+ model: SessionModel.nullable(),
2729
+ thinking: ThinkingLevel.nullable()
2730
+ });
2731
+ var ImportSessionRequest = z14.object({
2732
+ hostId: z14.string(),
2733
+ sessionFile: z14.string(),
2734
+ projectId: z14.string().nullable().optional()
2735
+ });
2736
+ var AnswerRequest = z14.object({
2737
+ revision: z14.number().int(),
2738
+ response: InteractionResponseSchema
2739
+ });
2740
+ var AdapterActionRequest = z14.object({
2741
+ generation: z14.string().uuid().optional(),
2742
+ adapterId: z14.string(),
2743
+ actionId: z14.string(),
2744
+ payload: z14.unknown().optional()
2745
+ });
2746
+ var TaskPolicyPatch = z14.object({
2747
+ hostId: z14.string().nullable().optional(),
2748
+ profileId: z14.string().nullable().optional(),
2749
+ workspace: z14.object({
2750
+ mode: z14.enum(["new_worktree", "existing"]).optional(),
2751
+ branch: z14.string().nullable().optional(),
2752
+ base: z14.string().nullable().optional(),
2753
+ workspaceId: z14.string().optional()
2754
+ }).optional(),
2755
+ continuation: z14.object({
2756
+ enabled: z14.boolean().optional(),
2757
+ objective: z14.string().min(1).optional(),
2758
+ maxContinuations: z14.number().int().min(1).max(50).optional(),
2759
+ maxElapsedMinutes: z14.number().int().min(1).max(1440).optional(),
2760
+ maxTokens: z14.number().int().positive().nullable().optional(),
2761
+ maxCostUsd: z14.number().positive().nullable().optional()
2762
+ }).optional(),
2763
+ completion: CompletionPolicy.partial().optional()
2764
+ });
2765
+ var CreateTaskRequest = z14.object({
2766
+ projectId: z14.string(),
2767
+ title: z14.string().max(300).optional(),
2768
+ githubIssueUrl: GitHubIssueUrl.optional(),
2769
+ githubIssue: z14.never().optional(),
2770
+ launchPrompt: z14.never().optional(),
2771
+ objective: z14.string().default(""),
2772
+ acceptanceCriteria: z14.array(z14.string()).default([]),
2773
+ dependencies: z14.array(z14.string()).default([]),
2774
+ parentTaskId: z14.string().nullable().optional(),
2775
+ priority: Priority.default(2),
2776
+ state: z14.enum(["backlog", "ready"]).default("backlog"),
2777
+ notBefore: z14.string().nullable().optional(),
2778
+ policy: TaskPolicyPatch.optional()
2779
+ }).superRefine((v, ctx) => {
2780
+ if (v.githubIssueUrl === void 0) {
2781
+ if (v.title === void 0 || v.title.length === 0)
2782
+ ctx.addIssue({ code: "custom", path: ["title"], message: "Title is required." });
2783
+ return;
2784
+ }
2785
+ if (v.objective.trim())
2786
+ ctx.addIssue({
2787
+ code: "custom",
2788
+ path: ["objective"],
2789
+ message: "Issue imports use the issue as their initial objective; leave Objective empty."
2790
+ });
2791
+ if (v.acceptanceCriteria.length)
2792
+ ctx.addIssue({
2793
+ code: "custom",
2794
+ path: ["acceptanceCriteria"],
2795
+ message: "Issue imports read acceptance from the issue; leave acceptance criteria empty at creation."
2796
+ });
2797
+ if (v.policy?.continuation?.enabled === true)
2798
+ ctx.addIssue({
2799
+ code: "custom",
2800
+ path: ["policy", "continuation", "enabled"],
2801
+ message: "Issue imports start with continuation disabled."
2802
+ });
2803
+ if (v.policy?.completion?.requireHumanReview === false)
2804
+ ctx.addIssue({
2805
+ code: "custom",
2806
+ path: ["policy", "completion", "requireHumanReview"],
2807
+ message: "Issue imports require human review when created."
2808
+ });
2809
+ }).transform((v) => {
2810
+ if (v.githubIssueUrl === void 0)
2811
+ return { ...v, title: v.title };
2812
+ const issue = githubIssueFromUrl(v.githubIssueUrl);
2813
+ return { ...v, title: v.title?.trim() || `${issue.repository} #${issue.number}` };
2814
+ });
2815
+ var UpdateTaskRequest = z14.object({
2816
+ githubIssueUrl: z14.never().optional(),
2817
+ githubIssue: z14.never().optional(),
2818
+ launchPrompt: z14.never().optional(),
2819
+ tracker: z14.never().optional(),
2820
+ title: z14.string().min(1).max(300).optional(),
2821
+ objective: z14.string().optional(),
2822
+ acceptanceCriteria: z14.array(z14.string()).optional(),
2823
+ dependencies: z14.array(z14.string()).optional(),
2824
+ parentTaskId: z14.string().nullable().optional(),
2825
+ priority: Priority.optional(),
2826
+ position: z14.number().optional(),
2827
+ notBefore: z14.string().nullable().optional(),
2828
+ policy: TaskPolicyPatch.optional()
2829
+ });
2830
+ var MoveTaskRequest = z14.object({
2831
+ to: TaskState,
2832
+ confirm: z14.boolean().optional(),
2833
+ onRunning: z14.enum(["pause", "stop"]).optional(),
2834
+ position: z14.number().optional()
2835
+ });
2836
+ var RequestChangesRequest = z14.object({ feedback: z14.array(z14.string().min(1)).min(1) });
2837
+ var Eligibility = z14.union([
2838
+ z14.object({ eligible: z14.literal(true), hostId: z14.string(), hostName: z14.string() }),
2839
+ z14.object({
2840
+ eligible: z14.literal(false),
2841
+ wait: z14.enum([
2842
+ "dependency",
2843
+ "host_offline",
2844
+ "project_limit",
2845
+ "workspace_occupied",
2846
+ "scheduled_time",
2847
+ "invalid_configuration",
2848
+ "dispatch_paused",
2849
+ "project_automation_disabled",
2850
+ "not_ready",
2851
+ "already_dispatched",
2852
+ "retry_backoff"
2853
+ ]),
2854
+ message: z14.string()
2855
+ })
2856
+ ]);
2857
+ var NowResponse = z14.object({
2858
+ running: z14.array(z14.object({ taskId: z14.string(), runId: z14.string(), sessionId: z14.string().nullable() })),
2859
+ queued: z14.array(z14.object({ taskId: z14.string(), eligibility: Eligibility })),
2860
+ dispatchPaused: z14.boolean()
2861
+ });
2862
+ var AutomationInput = z14.object({
2863
+ name: z14.string().min(1),
2864
+ enabled: z14.boolean().default(true),
2865
+ projectId: z14.string(),
2866
+ trigger: Trigger,
2867
+ filters: z14.array(z14.object({ path: z14.string(), equals: z14.string() })).default([]),
2868
+ template: TaskTemplate,
2869
+ hostId: z14.string().nullable().default(null),
2870
+ profileId: z14.string().nullable().default(null),
2871
+ mode: z14.enum(["fresh", "continue", "watch"]).default("fresh"),
2872
+ groupingKey: z14.string().nullable().default(null),
2873
+ overlap: z14.enum(["skip", "queue_one", "append"]).default("skip"),
2874
+ missed: z14.enum(["skip", "run_once"]).default("skip"),
2875
+ continuation: ContinuationPolicy.default({ enabled: false }),
2876
+ completion: CompletionPolicy.default({ checks: null, requireHumanReview: true })
2877
+ });
2878
+ var AutomationView = Automation.extend({ summary: z14.string() });
2879
+ var AutomationPreview = z14.object({
2880
+ summary: z14.string(),
2881
+ task: TaskTemplate,
2882
+ next: z14.array(z14.string())
2883
+ });
2884
+ var WebhookTokenResponse = z14.object({ token: z14.string(), url: z14.string() });
2885
+ var PushSubscriptionRequest = z14.object({
2886
+ endpoint: z14.string().url(),
2887
+ keys: z14.object({ p256dh: z14.string(), auth: z14.string() }),
2888
+ permission: z14.enum(["granted", "denied", "default", "unknown"]).default("granted")
2889
+ });
2890
+ var NotificationSettings = z14.object({
2891
+ quietHours: z14.object({
2892
+ start: z14.string().regex(/^\d{2}:\d{2}$/),
2893
+ end: z14.string().regex(/^\d{2}:\d{2}$/),
2894
+ timezone: z14.string()
2895
+ }).nullable(),
2896
+ privatePreviews: z14.boolean(),
2897
+ preferredDeviceId: z14.string().nullable()
2898
+ });
2899
+ var PushPayload = z14.union([
2900
+ z14.object({
2901
+ type: z14.literal("show"),
2902
+ title: z14.string(),
2903
+ body: z14.string(),
2904
+ tag: z14.string(),
2905
+ url: z14.string(),
2906
+ renotify: z14.boolean()
2907
+ }),
2908
+ z14.object({ type: z14.literal("clear"), tag: z14.string() })
2909
+ ]);
2910
+ var SetupState = z14.object({
2911
+ passkey: z14.object({
2912
+ available: z14.boolean(),
2913
+ registered: z14.boolean(),
2914
+ reason: z14.string().nullable()
2915
+ }),
2916
+ oidc: z14.object({ label: z14.string() }).nullable()
2917
+ });
2918
+ var PasskeyRegisterOptionsResponse = z14.object({
2919
+ challengeId: z14.string(),
2920
+ options: z14.unknown()
2921
+ });
2922
+ var PasskeyRegisterVerifyRequest = z14.object({
2923
+ challengeId: z14.string(),
2924
+ name: z14.string().min(1).max(80),
2925
+ response: z14.unknown()
2926
+ });
2927
+ var PasskeySignInOptionsResponse = z14.object({
2928
+ challengeId: z14.string(),
2929
+ options: z14.unknown()
2930
+ });
2931
+ var PasskeySignInVerifyRequest = z14.object({
2932
+ challengeId: z14.string(),
2933
+ response: z14.unknown(),
2934
+ deviceName: z14.string().min(1).max(80),
2935
+ kind: DeviceKind.extract(["browser", "pwa"])
2936
+ });
2937
+ var OidcBeginRequest = z14.object({
2938
+ deviceName: z14.string().min(1).max(80),
2939
+ kind: DeviceKind.extract(["browser", "pwa"]),
2940
+ next: z14.string().default("/"),
2941
+ handoff: z14.boolean().default(false)
2942
+ });
2943
+ var OidcBeginResponse = z14.object({
2944
+ authorizeUrl: z14.string(),
2945
+ flowId: z14.string().nullable(),
2946
+ pollToken: z14.string().nullable()
2947
+ });
2948
+ var OidcClaimRequest = z14.object({ flowId: z14.string(), pollToken: z14.string() });
2949
+ var OidcClaimResponse = z14.union([
2950
+ z14.object({ status: z14.literal("pending") }),
2951
+ z14.object({ status: z14.literal("done"), deviceId: z14.string() })
2952
+ ]);
2953
+ var TerminalLoginStartRequest = z14.object({ name: z14.string().min(1).max(80) });
2954
+ var TerminalLoginStartResponse = z14.object({
2955
+ userCode: z14.string(),
2956
+ pollToken: z14.string(),
2957
+ verifyUrl: z14.string(),
2958
+ expiresAt: z14.string(),
2959
+ intervalMs: z14.number().int()
2960
+ });
2961
+ var TerminalLoginClaimRequest = z14.object({
2962
+ userCode: z14.string().min(1),
2963
+ pollToken: z14.string().min(1)
2964
+ });
2965
+ var TerminalLoginClaimResponse = z14.union([
2966
+ z14.object({ status: z14.literal("pending") }),
2967
+ z14.object({ status: z14.literal("denied") }),
2968
+ z14.object({ status: z14.literal("done"), deviceId: z14.string(), credential: z14.string() })
2969
+ ]);
2970
+ var TerminalLoginRequest = z14.object({
2971
+ userCode: z14.string(),
2972
+ name: z14.string(),
2973
+ requestedFrom: z14.string(),
2974
+ createdAt: z14.string(),
2975
+ expiresAt: z14.string(),
2976
+ status: z14.enum(["pending", "approved", "denied"])
2977
+ });
2978
+ var AuthMethods = z14.object({
2979
+ passkeys: z14.array(Passkey),
2980
+ passkeyAvailability: z14.object({ available: z14.boolean(), reason: z14.string().nullable() }),
2981
+ oidc: z14.object({
2982
+ issuer: z14.string(),
2983
+ label: z14.string(),
2984
+ ownerMatch: z14.string(),
2985
+ status: z14.enum(["ready", "error"]),
2986
+ error: z14.string().nullable()
2987
+ }).nullable()
2988
+ });
2989
+ var MeResponse = z14.object({
2990
+ device: Device,
2991
+ admin: z14.boolean(),
2992
+ publicUrl: z14.string()
2993
+ });
2994
+ var ViewInput = View.pick({
2995
+ name: true,
2996
+ mode: true,
2997
+ projectIds: true,
2998
+ hostIds: true,
2999
+ clientId: true
3000
+ }).partial({
3001
+ mode: true,
3002
+ projectIds: true,
3003
+ hostIds: true
3004
+ });
3005
+ var ViewPatch = ViewInput.partial();
3006
+ var ViewClientReport = ViewClient.omit({ lastSeenAt: true });
3007
+ var ProjectSuggestionsResponse = z14.object({
3008
+ suggestions: z14.array(ProjectSuggestion.extend({ name: z14.string(), preselected: z14.boolean() }))
3009
+ });
3010
+
3011
+ // packages/protocol/dist/backoff.js
3012
+ var RECONNECT_BACKOFF_MS = [1e3, 2e3, 5e3, 1e4, 2e4, 3e4];
3013
+ function reconnectDelay(attempt, steps = RECONNECT_BACKOFF_MS, random = Math.random) {
3014
+ const base = steps[Math.min(Math.max(attempt, 0), steps.length - 1)] ?? 3e4;
3015
+ return Math.max(0, Math.round(base * (0.8 + random() * 0.4)));
3016
+ }
3017
+
3018
+ // packages/protocol/dist/client-wire.js
3019
+ import { z as z15 } from "zod";
3020
+ var SyncState = z15.object({
3021
+ hosts: z15.array(Host),
3022
+ projects: z15.array(Project),
3023
+ checkouts: z15.array(Checkout),
3024
+ workspaces: z15.array(Workspace),
3025
+ profiles: z15.array(Profile),
3026
+ views: z15.array(View),
3027
+ sessions: z15.array(Session),
3028
+ tasks: z15.array(Task),
3029
+ runs: z15.array(Run),
3030
+ automations: z15.array(Automation),
3031
+ attention: z15.array(AttentionItem),
3032
+ interactions: z15.array(Interaction),
3033
+ panels: z15.array(Panel),
3034
+ devices: z15.array(Device),
3035
+ adapters: z15.record(z15.string(), z15.array(AdapterInfo)),
3036
+ dispatchPaused: z15.boolean()
3037
+ });
3038
+ var Presence = z15.object({
3039
+ foreground: z15.boolean(),
3040
+ interactedAt: z15.string().nullable(),
3041
+ viewing: z15.object({ sessionId: z15.string() }).nullable()
3042
+ });
3043
+ var CLIENT_CAPABILITIES = ["adapter.slots.v1", "timeline.cards.v1"];
3044
+ var ClientToServer = z15.discriminatedUnion("type", [
3045
+ z15.object({
3046
+ type: z15.literal("hello"),
3047
+ cursor: z15.number().int().nullable(),
3048
+ capabilities: z15.array(z15.string().min(1).max(80)).max(32).optional(),
3049
+ projectionId: z15.string().max(256).nullable().optional()
3050
+ }),
3051
+ z15.object({ type: z15.literal("presence"), presence: Presence }),
3052
+ z15.object({ type: z15.literal("ping") })
3053
+ ]);
3054
+ var ServerToClient = z15.discriminatedUnion("type", [
3055
+ z15.object({
3056
+ type: z15.literal("replay"),
3057
+ seq: z15.number().int(),
3058
+ events: z15.array(EventEnvelope),
3059
+ capabilities: z15.array(z15.enum(CLIENT_CAPABILITIES)).optional(),
3060
+ projectionId: z15.string().optional()
3061
+ }),
3062
+ z15.object({
3063
+ type: z15.literal("snapshot"),
3064
+ seq: z15.number().int(),
3065
+ state: SyncState,
3066
+ capabilities: z15.array(z15.enum(CLIENT_CAPABILITIES)).optional(),
3067
+ projectionId: z15.string().optional()
3068
+ }),
3069
+ z15.object({ type: z15.literal("event"), event: EventEnvelope }),
3070
+ z15.object({ type: z15.literal("stream"), delta: StreamDelta }),
3071
+ z15.object({ type: z15.literal("pong") }),
3072
+ z15.object({ type: z15.literal("force_logout"), reason: z15.string() })
3073
+ ]);
3074
+
3075
+ // node_modules/.pnpm/ulid@3.0.2/node_modules/ulid/dist/node/index.js
3076
+ import crypto from "node:crypto";
3077
+ var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
3078
+ var ENCODING_LEN = 32;
3079
+ var RANDOM_LEN = 16;
3080
+ var TIME_LEN = 10;
3081
+ var TIME_MAX = 281474976710655;
3082
+ var ULIDErrorCode;
3083
+ (function(ULIDErrorCode2) {
3084
+ ULIDErrorCode2["Base32IncorrectEncoding"] = "B32_ENC_INVALID";
3085
+ ULIDErrorCode2["DecodeTimeInvalidCharacter"] = "DEC_TIME_CHAR";
3086
+ ULIDErrorCode2["DecodeTimeValueMalformed"] = "DEC_TIME_MALFORMED";
3087
+ ULIDErrorCode2["EncodeTimeNegative"] = "ENC_TIME_NEG";
3088
+ ULIDErrorCode2["EncodeTimeSizeExceeded"] = "ENC_TIME_SIZE_EXCEED";
3089
+ ULIDErrorCode2["EncodeTimeValueMalformed"] = "ENC_TIME_MALFORMED";
3090
+ ULIDErrorCode2["PRNGDetectFailure"] = "PRNG_DETECT";
3091
+ ULIDErrorCode2["ULIDInvalid"] = "ULID_INVALID";
3092
+ ULIDErrorCode2["Unexpected"] = "UNEXPECTED";
3093
+ ULIDErrorCode2["UUIDInvalid"] = "UUID_INVALID";
3094
+ })(ULIDErrorCode || (ULIDErrorCode = {}));
3095
+ var ULIDError = class extends Error {
3096
+ constructor(errorCode, message) {
3097
+ super(`${message} (${errorCode})`);
3098
+ this.name = "ULIDError";
3099
+ this.code = errorCode;
3100
+ }
3101
+ };
3102
+ function randomChar(prng) {
3103
+ const randomPosition = Math.floor(prng() * ENCODING_LEN) % ENCODING_LEN;
3104
+ return ENCODING.charAt(randomPosition);
3105
+ }
3106
+ function replaceCharAt(str, index, char) {
3107
+ if (index > str.length - 1) {
3108
+ return str;
3109
+ }
3110
+ return str.substr(0, index) + char + str.substr(index + 1);
3111
+ }
3112
+ function incrementBase32(str) {
3113
+ let done = void 0, index = str.length, char, charIndex, output = str;
3114
+ const maxCharIndex = ENCODING_LEN - 1;
3115
+ while (!done && index-- >= 0) {
3116
+ char = output[index];
3117
+ charIndex = ENCODING.indexOf(char);
3118
+ if (charIndex === -1) {
3119
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Incorrectly encoded string");
3120
+ }
3121
+ if (charIndex === maxCharIndex) {
3122
+ output = replaceCharAt(output, index, ENCODING[0]);
3123
+ continue;
3124
+ }
3125
+ done = replaceCharAt(output, index, ENCODING[charIndex + 1]);
3126
+ }
3127
+ if (typeof done === "string") {
3128
+ return done;
3129
+ }
3130
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Failed incrementing string");
3131
+ }
3132
+ function detectPRNG(root) {
3133
+ const rootLookup = detectRoot();
3134
+ const globalCrypto = rootLookup && (rootLookup.crypto || rootLookup.msCrypto) || (typeof crypto !== "undefined" ? crypto : null);
3135
+ if (typeof globalCrypto?.getRandomValues === "function") {
3136
+ return () => {
3137
+ const buffer = new Uint8Array(1);
3138
+ globalCrypto.getRandomValues(buffer);
3139
+ return buffer[0] / 256;
3140
+ };
3141
+ } else if (typeof globalCrypto?.randomBytes === "function") {
3142
+ return () => globalCrypto.randomBytes(1).readUInt8() / 256;
3143
+ } else if (crypto?.randomBytes) {
3144
+ return () => crypto.randomBytes(1).readUInt8() / 256;
3145
+ }
3146
+ throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
3147
+ }
3148
+ function detectRoot() {
3149
+ if (inWebWorker())
3150
+ return self;
3151
+ if (typeof window !== "undefined") {
3152
+ return window;
3153
+ }
3154
+ if (typeof global !== "undefined") {
3155
+ return global;
3156
+ }
3157
+ if (typeof globalThis !== "undefined") {
3158
+ return globalThis;
3159
+ }
3160
+ return null;
3161
+ }
3162
+ function encodeRandom(len, prng) {
3163
+ let str = "";
3164
+ for (; len > 0; len--) {
3165
+ str = randomChar(prng) + str;
3166
+ }
3167
+ return str;
3168
+ }
3169
+ function encodeTime(now, len = TIME_LEN) {
3170
+ if (isNaN(now)) {
3171
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be a number: ${now}`);
3172
+ } else if (now > TIME_MAX) {
3173
+ throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded, `Cannot encode a time larger than ${TIME_MAX}: ${now}`);
3174
+ } else if (now < 0) {
3175
+ throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now}`);
3176
+ } else if (Number.isInteger(now) === false) {
3177
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be an integer: ${now}`);
3178
+ }
3179
+ let mod, str = "";
3180
+ for (let currentLen = len; currentLen > 0; currentLen--) {
3181
+ mod = now % ENCODING_LEN;
3182
+ str = ENCODING.charAt(mod) + str;
3183
+ now = (now - mod) / ENCODING_LEN;
3184
+ }
3185
+ return str;
3186
+ }
3187
+ function inWebWorker() {
3188
+ return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
3189
+ }
3190
+ function monotonicFactory(prng) {
3191
+ const currentPRNG = prng || detectPRNG();
3192
+ let lastTime = 0, lastRandom;
3193
+ return function _ulid(seedTime) {
3194
+ const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
3195
+ if (seed <= lastTime) {
3196
+ const incrementedRandom = lastRandom = incrementBase32(lastRandom);
3197
+ return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
3198
+ }
3199
+ lastTime = seed;
3200
+ const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currentPRNG);
3201
+ return encodeTime(seed, TIME_LEN) + newRandom;
3202
+ };
3203
+ }
3204
+
3205
+ // packages/protocol/dist/ids.js
3206
+ var ulid = monotonicFactory();
3207
+
3208
+ // packages/protocol/dist/views.js
3209
+ var CLIENT_OPEN_MS = 10 * 6e4;
3210
+
3211
+ // packages/protocol/dist/web-bridge.js
3212
+ import { z as z16 } from "zod";
3213
+ var FRAME_MAX_HEIGHT = 4e3;
3214
+ var FrameToParentMessageSchema = z16.discriminatedUnion("type", [
3215
+ z16.object({
3216
+ type: z16.literal("action"),
3217
+ actionId: z16.string().min(1).max(200),
3218
+ payload: z16.unknown().optional()
3219
+ }),
3220
+ z16.object({
3221
+ type: z16.literal("resize"),
3222
+ height: z16.number().finite().min(0).max(FRAME_MAX_HEIGHT)
3223
+ })
3224
+ ]);
3225
+
3226
+ // packages/client/dist/connection.js
3227
+ import WebSocket from "ws";
3228
+
3229
+ // packages/client/dist/store.js
3230
+ function emptyState() {
3231
+ return {
3232
+ seq: null,
3233
+ synced: false,
3234
+ connection: { state: "connecting", attempts: 0, reason: null },
3235
+ hosts: {},
3236
+ projects: {},
3237
+ checkouts: {},
3238
+ workspaces: {},
3239
+ profiles: {},
3240
+ views: {},
3241
+ sessions: {},
3242
+ tasks: {},
3243
+ runs: {},
3244
+ automations: {},
3245
+ attention: {},
3246
+ interactions: {},
3247
+ panels: {},
3248
+ devices: {},
3249
+ dispatchPaused: false
3250
+ };
3251
+ }
3252
+ function panelKey(sessionId, adapterId, slot) {
3253
+ return `${sessionId}:${adapterId}:${slot}`;
3254
+ }
3255
+ function keepPanel(p) {
3256
+ return p.node !== null || p.webRenderer;
3257
+ }
3258
+ function byId(list) {
3259
+ const out = {};
3260
+ for (const x of list)
3261
+ out[x.id] = x;
3262
+ return out;
3263
+ }
3264
+ function put(map, id, value) {
3265
+ return { ...map, [id]: value };
3266
+ }
3267
+ function drop(map, id) {
3268
+ if (!(id in map))
3269
+ return map;
3270
+ const next = { ...map };
3271
+ delete next[id];
3272
+ return next;
3273
+ }
3274
+ function applySnapshot(state, seq, snap) {
3275
+ const panels = {};
3276
+ for (const p of snap.panels) {
3277
+ if (keepPanel(p))
3278
+ panels[panelKey(p.sessionId, p.adapterId, p.slot)] = p;
3279
+ }
3280
+ return {
3281
+ ...state,
3282
+ seq,
3283
+ synced: true,
3284
+ hosts: byId(snap.hosts),
3285
+ projects: byId(snap.projects),
3286
+ checkouts: byId(snap.checkouts),
3287
+ workspaces: byId(snap.workspaces),
3288
+ profiles: byId(snap.profiles),
3289
+ views: byId(snap.views),
3290
+ sessions: byId(snap.sessions),
3291
+ tasks: byId(snap.tasks),
3292
+ runs: byId(snap.runs),
3293
+ automations: byId(snap.automations),
3294
+ attention: byId(snap.attention.filter((a) => a.resolvedAt === null)),
3295
+ interactions: byId(snap.interactions),
3296
+ panels,
3297
+ devices: byId(snap.devices),
3298
+ dispatchPaused: snap.dispatchPaused
3299
+ };
3300
+ }
3301
+ function upsertInteraction(state, i) {
3302
+ const prev = state.interactions[i.id];
3303
+ if (prev && prev.revision > i.revision)
3304
+ return state;
3305
+ return { ...state, interactions: put(state.interactions, i.id, i) };
3306
+ }
3307
+ function applyEvent(state, event) {
3308
+ if (state.seq !== null && event.seq <= state.seq)
3309
+ return state;
3310
+ const next = reduceEvent(state, canonicalEventType(event.type), event.data);
3311
+ return { ...next, seq: event.seq };
3312
+ }
3313
+ function applyReplay(state, seq, events) {
3314
+ let s = state;
3315
+ for (const e of [...events].sort((a, b) => a.seq - b.seq))
3316
+ s = applyEvent(s, e);
3317
+ return { ...s, seq: Math.max(s.seq ?? 0, seq), synced: true };
3318
+ }
3319
+ function reduceEvent(state, type, data) {
3320
+ switch (type) {
3321
+ case "host.updated": {
3322
+ const d = data;
3323
+ return { ...state, hosts: put(state.hosts, d.id, d) };
3324
+ }
3325
+ case "project.updated": {
3326
+ const d = data;
3327
+ return { ...state, projects: put(state.projects, d.id, d) };
3328
+ }
3329
+ case "project.deleted": {
3330
+ const d = data;
3331
+ return { ...state, projects: drop(state.projects, d.id) };
3332
+ }
3333
+ case "checkout.updated": {
3334
+ const d = data;
3335
+ return { ...state, checkouts: put(state.checkouts, d.id, d) };
3336
+ }
3337
+ case "workspace.updated": {
3338
+ const d = data;
3339
+ return {
3340
+ ...state,
3341
+ workspaces: d.archivedAt ? drop(state.workspaces, d.id) : put(state.workspaces, d.id, d)
3342
+ };
3343
+ }
3344
+ case "workspace.deleted": {
3345
+ const d = data;
3346
+ return { ...state, workspaces: drop(state.workspaces, d.id) };
3347
+ }
3348
+ case "profile.updated": {
3349
+ const d = data;
3350
+ return { ...state, profiles: put(state.profiles, d.id, d) };
3351
+ }
3352
+ case "view.updated": {
3353
+ const d = data;
3354
+ return { ...state, views: put(state.views, d.id, d) };
3355
+ }
3356
+ case "view.deleted": {
3357
+ const d = data;
3358
+ return { ...state, views: drop(state.views, d.id) };
3359
+ }
3360
+ case "profile.deleted": {
3361
+ const d = data;
3362
+ return { ...state, profiles: drop(state.profiles, d.id) };
3363
+ }
3364
+ case "session.updated": {
3365
+ const d = data;
3366
+ return { ...state, sessions: put(state.sessions, d.id, d) };
3367
+ }
3368
+ case "interaction.updated":
3369
+ return upsertInteraction(state, data);
3370
+ case "panel.updated": {
3371
+ const d = data;
3372
+ const key = panelKey(d.sessionId, d.adapterId, d.slot);
3373
+ return {
3374
+ ...state,
3375
+ panels: keepPanel(d) ? put(state.panels, key, d) : drop(state.panels, key)
3376
+ };
3377
+ }
3378
+ case "task.updated": {
3379
+ const d = data;
3380
+ return { ...state, tasks: put(state.tasks, d.id, d) };
3381
+ }
3382
+ case "task.deleted": {
3383
+ const d = data;
3384
+ return { ...state, tasks: drop(state.tasks, d.id) };
3385
+ }
3386
+ case "run.updated": {
3387
+ const d = data;
3388
+ return { ...state, runs: put(state.runs, d.id, d) };
3389
+ }
3390
+ case "automation.updated": {
3391
+ const d = data;
3392
+ return { ...state, automations: put(state.automations, d.id, d) };
3393
+ }
3394
+ case "automation.deleted": {
3395
+ const d = data;
3396
+ return { ...state, automations: drop(state.automations, d.id) };
3397
+ }
3398
+ case "attention.updated": {
3399
+ const d = data;
3400
+ return {
3401
+ ...state,
3402
+ attention: d.resolvedAt ? drop(state.attention, d.id) : put(state.attention, d.id, d)
3403
+ };
3404
+ }
3405
+ case "device.updated": {
3406
+ const d = data;
3407
+ return {
3408
+ ...state,
3409
+ devices: d.revokedAt ? drop(state.devices, d.id) : put(state.devices, d.id, d)
3410
+ };
3411
+ }
3412
+ case "settings.updated": {
3413
+ const d = data;
3414
+ return { ...state, dispatchPaused: d.dispatchPaused };
3415
+ }
3416
+ default:
3417
+ return state;
3418
+ }
3419
+ }
3420
+ function setConnection(state, connection) {
3421
+ return { ...state, connection: { ...state.connection, ...connection } };
3422
+ }
3423
+ var Store = class {
3424
+ state = emptyState();
3425
+ listeners = /* @__PURE__ */ new Set();
3426
+ versions = /* @__PURE__ */ new Map();
3427
+ resetVersion = 0;
3428
+ revision(kind, id) {
3429
+ return (this.versions.get(`${kind}:${id}`) ?? 0) + this.resetVersion;
3430
+ }
3431
+ getState = () => this.state;
3432
+ subscribe = (fn) => {
3433
+ this.listeners.add(fn);
3434
+ return () => this.listeners.delete(fn);
3435
+ };
3436
+ update(fn, reset = false) {
3437
+ const previous = this.state;
3438
+ const next = fn(previous);
3439
+ if (next === previous && !reset)
3440
+ return;
3441
+ if (reset)
3442
+ this.resetVersion++;
3443
+ for (const kind of ["sessions", "tasks"]) {
3444
+ const ids = /* @__PURE__ */ new Set([...Object.keys(previous[kind]), ...Object.keys(next[kind])]);
3445
+ for (const id of ids) {
3446
+ if (reset || previous[kind][id] !== next[kind][id]) {
3447
+ const key = `${kind}:${id}`;
3448
+ this.versions.set(key, (this.versions.get(key) ?? 0) + 1);
3449
+ }
3450
+ }
3451
+ }
3452
+ this.state = next;
3453
+ for (const l of this.listeners)
3454
+ l();
3455
+ }
3456
+ };
3457
+
3458
+ // packages/client/dist/connection.js
3459
+ function wsUrlFor(coordinatorUrl) {
3460
+ const u = new URL(coordinatorUrl.replace(/\/+$/, ""));
3461
+ u.protocol = u.protocol === "https:" ? "wss:" : "ws:";
3462
+ u.pathname = `${u.pathname.replace(/\/+$/, "")}/ws/client`;
3463
+ u.search = "";
3464
+ u.hash = "";
3465
+ return u.toString();
3466
+ }
3467
+ var PING_INTERVAL_MS = 25e3;
3468
+ var PONG_TIMEOUT_MS = 1e4;
3469
+ var ClientConnection = class {
3470
+ api;
3471
+ store = new Store();
3472
+ opts;
3473
+ ws = null;
3474
+ stopped = true;
3475
+ revoked = false;
3476
+ attempts = 0;
3477
+ retryTimer = null;
3478
+ pingTimer = null;
3479
+ pongTimer = null;
3480
+ logoutListeners = /* @__PURE__ */ new Set();
3481
+ liveListeners = /* @__PURE__ */ new Set();
3482
+ closeListeners = /* @__PURE__ */ new Set();
3483
+ noticeListeners = /* @__PURE__ */ new Set();
3484
+ cursor;
3485
+ projectionId;
3486
+ capabilities = [];
3487
+ constructor(opts) {
3488
+ this.opts = opts;
3489
+ this.api = new ApiClient(opts);
3490
+ if (opts.initialCursor !== void 0 && (!Number.isSafeInteger(opts.initialCursor) || opts.initialCursor < 0))
3491
+ throw new RangeError("Invalid cursor");
3492
+ this.cursor = opts.initialCursor ?? null;
3493
+ this.projectionId = opts.projectionId ?? null;
3494
+ }
3495
+ connect() {
3496
+ if (!this.stopped || this.revoked)
3497
+ return;
3498
+ this.stopped = false;
3499
+ this.open();
3500
+ }
3501
+ close() {
3502
+ if (this.stopped && !this.ws)
3503
+ return;
3504
+ this.stopped = true;
3505
+ this.clearTimers();
3506
+ const ws = this.ws;
3507
+ this.ws = null;
3508
+ ws?.removeAllListeners();
3509
+ ws?.on("error", () => void 0);
3510
+ try {
3511
+ if (ws?.readyState === WebSocket.CONNECTING)
3512
+ ws.terminate();
3513
+ else
3514
+ ws?.close(1e3, "client closed");
3515
+ } catch {
3516
+ ws?.terminate();
3517
+ }
3518
+ for (const fn of this.closeListeners)
3519
+ fn();
3520
+ }
3521
+ onLogout(fn) {
3522
+ this.logoutListeners.add(fn);
3523
+ return () => this.logoutListeners.delete(fn);
3524
+ }
3525
+ /** Called each time the connection becomes live (after replay or snapshot). */
3526
+ onLive(fn) {
3527
+ this.liveListeners.add(fn);
3528
+ return () => this.liveListeners.delete(fn);
3529
+ }
3530
+ onClose(fn) {
3531
+ this.closeListeners.add(fn);
3532
+ return () => this.closeListeners.delete(fn);
3533
+ }
3534
+ onNotice(fn) {
3535
+ this.noticeListeners.add(fn);
3536
+ return () => this.noticeListeners.delete(fn);
3537
+ }
3538
+ send(msg) {
3539
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN)
3540
+ return false;
3541
+ this.ws.send(JSON.stringify(msg));
3542
+ return true;
3543
+ }
3544
+ open() {
3545
+ if (this.stopped)
3546
+ return;
3547
+ const Impl = this.opts.WebSocketImpl ?? WebSocket;
3548
+ const headers = {};
3549
+ if (this.opts.credential)
3550
+ headers.authorization = `Bearer ${this.opts.credential}`;
3551
+ let ws;
3552
+ try {
3553
+ ws = new Impl(wsUrlFor(this.opts.coordinatorUrl), { headers });
3554
+ } catch {
3555
+ this.scheduleReconnect();
3556
+ return;
3557
+ }
3558
+ this.ws = ws;
3559
+ ws.on("open", () => {
3560
+ if (this.ws !== ws)
3561
+ return;
3562
+ ws.send(JSON.stringify({
3563
+ type: "hello",
3564
+ cursor: this.cursor,
3565
+ capabilities: [...CLIENT_CAPABILITIES],
3566
+ projectionId: this.projectionId
3567
+ }));
3568
+ });
3569
+ ws.on("message", (raw) => {
3570
+ if (this.ws !== ws)
3571
+ return;
3572
+ let msg;
3573
+ try {
3574
+ msg = JSON.parse(raw.toString());
3575
+ } catch {
3576
+ return;
3577
+ }
3578
+ this.handle(msg);
3579
+ });
3580
+ ws.on("unexpected-response", (_req, res) => {
3581
+ if (this.ws !== ws)
3582
+ return;
3583
+ const code = res.statusCode ?? 0;
3584
+ res.resume();
3585
+ if (code === 401 || code === 403) {
3586
+ this.logout(code === 401 ? "This device's credential was rejected" : "Forbidden");
3587
+ return;
3588
+ }
3589
+ this.ws = null;
3590
+ ws.terminate();
3591
+ this.scheduleReconnect();
3592
+ });
3593
+ ws.on("close", (code, reason2) => {
3594
+ if (this.ws !== ws)
3595
+ return;
3596
+ this.ws = null;
3597
+ this.clearTimers();
3598
+ if (this.stopped)
3599
+ return;
3600
+ if (code === 4401 || code === 4403) {
3601
+ this.logout(reason2.toString() || "unauthorized");
3602
+ return;
3603
+ }
3604
+ this.scheduleReconnect();
3605
+ });
3606
+ ws.on("error", () => {
3607
+ });
3608
+ }
3609
+ handle(msg) {
3610
+ switch (msg.type) {
3611
+ case "snapshot":
3612
+ this.acknowledge(msg);
3613
+ this.cursor = msg.seq;
3614
+ this.store.update((s) => applySnapshot(s, msg.seq, msg.state), true);
3615
+ this.emitNotice({
3616
+ type: "reset",
3617
+ seq: msg.seq,
3618
+ state: msg.state,
3619
+ projectionId: this.projectionId
3620
+ });
3621
+ this.becomeLive();
3622
+ break;
3623
+ case "replay":
3624
+ this.acknowledge(msg);
3625
+ for (const event of [...msg.events].sort((a, b) => a.seq - b.seq)) {
3626
+ if (this.cursor !== null && event.seq <= this.cursor)
3627
+ continue;
3628
+ this.cursor = event.seq;
3629
+ this.store.update((s) => applyEvent(s, event));
3630
+ this.emitNotice({ type: "event", event, projectionId: this.projectionId });
3631
+ }
3632
+ this.cursor = Math.max(this.cursor ?? 0, msg.seq);
3633
+ this.store.update((s) => applyReplay(s, msg.seq, []));
3634
+ this.becomeLive();
3635
+ break;
3636
+ case "event":
3637
+ if (this.cursor !== null && msg.event.seq <= this.cursor)
3638
+ break;
3639
+ this.cursor = msg.event.seq;
3640
+ this.store.update((s) => applyEvent(s, msg.event));
3641
+ this.emitNotice({ type: "event", event: msg.event, projectionId: this.projectionId });
3642
+ break;
3643
+ case "pong":
3644
+ if (this.pongTimer)
3645
+ clearTimeout(this.pongTimer);
3646
+ this.pongTimer = null;
3647
+ break;
3648
+ case "force_logout":
3649
+ this.logout(msg.reason);
3650
+ break;
3651
+ }
3652
+ }
3653
+ acknowledge(msg) {
3654
+ this.capabilities = (msg.capabilities ?? []).filter((name) => CLIENT_CAPABILITIES.includes(name));
3655
+ this.projectionId = msg.projectionId ?? null;
3656
+ }
3657
+ emitNotice(notice) {
3658
+ for (const fn of [...this.noticeListeners])
3659
+ fn(notice);
3660
+ }
3661
+ becomeLive() {
3662
+ if (this.stopped)
3663
+ return;
3664
+ this.attempts = 0;
3665
+ this.store.update((s) => setConnection(s, { state: "live", attempts: 0, reason: null }));
3666
+ this.startPing();
3667
+ for (const fn of this.liveListeners)
3668
+ fn();
3669
+ }
3670
+ logout(reason2) {
3671
+ if (this.revoked)
3672
+ return;
3673
+ this.revoked = true;
3674
+ this.store.update((s) => setConnection(s, { state: "logged_out", reason: reason2 }));
3675
+ for (const fn of [...this.logoutListeners])
3676
+ fn(reason2);
3677
+ this.close();
3678
+ }
3679
+ startPing() {
3680
+ if (this.pingTimer)
3681
+ clearInterval(this.pingTimer);
3682
+ this.pingTimer = setInterval(() => {
3683
+ if (!this.send({ type: "ping" }))
3684
+ return;
3685
+ if (this.pongTimer)
3686
+ return;
3687
+ const socket = this.ws;
3688
+ this.pongTimer = setTimeout(() => {
3689
+ this.pongTimer = null;
3690
+ if (this.ws === socket)
3691
+ socket?.terminate();
3692
+ }, PONG_TIMEOUT_MS);
3693
+ }, this.opts.pingIntervalMs ?? PING_INTERVAL_MS);
3694
+ this.pingTimer.unref?.();
3695
+ }
3696
+ scheduleReconnect() {
3697
+ if (this.stopped)
3698
+ return;
3699
+ this.attempts++;
3700
+ this.store.update((s) => setConnection(s, {
3701
+ state: s.synced ? "reconnecting" : "connecting",
3702
+ attempts: this.attempts
3703
+ }));
3704
+ if (this.retryTimer)
3705
+ clearTimeout(this.retryTimer);
3706
+ this.retryTimer = setTimeout(() => {
3707
+ this.retryTimer = null;
3708
+ this.open();
3709
+ }, reconnectDelay(this.attempts - 1, void 0, this.opts.random));
3710
+ this.retryTimer.unref?.();
3711
+ }
3712
+ clearTimers() {
3713
+ if (this.retryTimer)
3714
+ clearTimeout(this.retryTimer);
3715
+ if (this.pingTimer)
3716
+ clearInterval(this.pingTimer);
3717
+ if (this.pongTimer)
3718
+ clearTimeout(this.pongTimer);
3719
+ this.retryTimer = null;
3720
+ this.pingTimer = null;
3721
+ this.pongTimer = null;
3722
+ }
3723
+ };
3724
+
3725
+ // packages/client/dist/wait.js
3726
+ var WaitError = class extends Error {
3727
+ code;
3728
+ lastEntity;
3729
+ constructor(code, message, lastEntity = null) {
3730
+ super(message);
3731
+ this.code = code;
3732
+ this.lastEntity = lastEntity;
3733
+ this.name = "WaitError";
3734
+ }
3735
+ };
3736
+ function waitForEntity(connection, kind, id, decide, options = {}) {
3737
+ const timeoutMs = options.timeoutMs ?? 3e5;
3738
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)
3739
+ throw new RangeError("timeoutMs must be a positive finite integer");
3740
+ return new Promise((resolve, reject) => {
3741
+ let finished = false;
3742
+ let reading = false;
3743
+ let rerun = false;
3744
+ let last = null;
3745
+ let poll;
3746
+ const pending = /* @__PURE__ */ new Set();
3747
+ const unsub = [];
3748
+ const cleanup = () => {
3749
+ if (poll)
3750
+ clearTimeout(poll);
3751
+ clearTimeout(deadline);
3752
+ options.signal?.removeEventListener("abort", abort);
3753
+ for (const fn of unsub)
3754
+ fn();
3755
+ for (const controller of pending)
3756
+ controller.abort();
3757
+ pending.clear();
3758
+ };
3759
+ const fail = (code, message) => {
3760
+ if (finished)
3761
+ return;
3762
+ finished = true;
3763
+ cleanup();
3764
+ reject(new WaitError(code, message, last));
3765
+ };
3766
+ const succeed = (entity) => {
3767
+ if (finished)
3768
+ return;
3769
+ finished = true;
3770
+ cleanup();
3771
+ resolve(entity);
3772
+ };
3773
+ const evaluate = (entity) => {
3774
+ if (finished || !entity)
3775
+ return;
3776
+ last = entity;
3777
+ const result = decide(entity);
3778
+ if (result.error)
3779
+ fail(result.error, `${kind} ${id} entered ${result.error}`);
3780
+ else if (result.done)
3781
+ succeed(entity);
3782
+ };
3783
+ const fromStore = () => {
3784
+ const state = connection.store.getState();
3785
+ const entity = state[kind][id];
3786
+ if (!state.synced)
3787
+ return;
3788
+ evaluate(entity);
3789
+ };
3790
+ const schedule = () => {
3791
+ if (finished)
3792
+ return;
3793
+ poll = setTimeout(() => {
3794
+ poll = void 0;
3795
+ void refresh();
3796
+ }, 2e3);
3797
+ poll.unref?.();
3798
+ };
3799
+ const refresh = async () => {
3800
+ if (finished)
3801
+ return;
3802
+ if (poll) {
3803
+ clearTimeout(poll);
3804
+ poll = void 0;
3805
+ }
3806
+ if (reading) {
3807
+ rerun = true;
3808
+ return;
3809
+ }
3810
+ reading = true;
3811
+ const revision = connection.store.revision(kind, id);
3812
+ const controller = new AbortController();
3813
+ pending.add(controller);
3814
+ try {
3815
+ const entity = await connection.api.get(`/api/${kind}/${encodeURIComponent(id)}`, {
3816
+ signal: controller.signal
3817
+ });
3818
+ if (!finished) {
3819
+ if (revision !== connection.store.revision(kind, id)) {
3820
+ fromStore();
3821
+ if (!finished)
3822
+ rerun = true;
3823
+ } else
3824
+ evaluate(entity);
3825
+ }
3826
+ } catch (error) {
3827
+ if (!finished && error instanceof ApiRequestError) {
3828
+ if (error.status === 404) {
3829
+ if (revision !== connection.store.revision(kind, id)) {
3830
+ fromStore();
3831
+ if (!finished)
3832
+ rerun = true;
3833
+ } else
3834
+ fail("not_found", error.message);
3835
+ } else if (error.status === 401 || error.status === 403)
3836
+ fail("unauthorized", error.message);
3837
+ else if (error.status >= 400 && error.status < 500)
3838
+ fail("invalid_request", error.message);
3839
+ }
3840
+ } finally {
3841
+ pending.delete(controller);
3842
+ reading = false;
3843
+ if (!finished) {
3844
+ if (rerun) {
3845
+ rerun = false;
3846
+ void refresh();
3847
+ } else
3848
+ schedule();
3849
+ }
3850
+ }
3851
+ };
3852
+ const abort = () => fail("aborted", "Wait aborted");
3853
+ const deadline = setTimeout(() => fail("timeout", `Wait timed out after ${timeoutMs} ms`), timeoutMs);
3854
+ unsub.push(connection.store.subscribe(fromStore));
3855
+ unsub.push(connection.onNotice((notice) => {
3856
+ if (notice.type === "event" && notice.event.type === "task.deleted" && kind === "tasks" && notice.event.data.id === id) {
3857
+ fail("not_found", `tasks ${id} was removed`);
3858
+ }
3859
+ }));
3860
+ unsub.push(connection.onLive(() => {
3861
+ void refresh();
3862
+ }));
3863
+ unsub.push(connection.onLogout((reason2) => fail("unauthorized", reason2)));
3864
+ unsub.push(connection.onClose(() => fail("closed", "Client closed")));
3865
+ options.signal?.addEventListener("abort", abort, { once: true });
3866
+ if (options.signal?.aborted)
3867
+ abort();
3868
+ if (!finished) {
3869
+ fromStore();
3870
+ if (!finished) {
3871
+ connection.connect();
3872
+ void refresh();
3873
+ }
3874
+ }
3875
+ });
3876
+ }
3877
+
3878
+ // packages/client/dist/client.js
3879
+ function queryPath(path2, values) {
3880
+ const query = new URLSearchParams();
3881
+ for (const [key, value] of Object.entries(values))
3882
+ if (value !== void 0)
3883
+ query.set(key, String(value));
3884
+ const suffix = query.toString();
3885
+ return suffix ? `${path2}?${suffix}` : path2;
3886
+ }
3887
+ var entityPath = (kind, id) => `/api/${kind}/${encodeURIComponent(id)}`;
3888
+ var SwitchyardClient = class {
3889
+ connection;
3890
+ opts;
3891
+ closed = false;
3892
+ subscriptions = /* @__PURE__ */ new Set();
3893
+ constructor(options) {
3894
+ this.opts = options;
3895
+ this.connection = new ClientConnection(options);
3896
+ }
3897
+ connect() {
3898
+ if (this.closed)
3899
+ throw new Error("Client closed");
3900
+ this.connection.connect();
3901
+ }
3902
+ close() {
3903
+ if (this.closed)
3904
+ return;
3905
+ this.closed = true;
3906
+ for (const unsubscribe of [...this.subscriptions])
3907
+ unsubscribe();
3908
+ this.connection.close();
3909
+ }
3910
+ sessions = {
3911
+ create: (input, options) => this.connection.api.post("/api/sessions", input, options),
3912
+ send: (id, input, options) => this.connection.api.post(`${entityPath("sessions", id)}/prompt`, input, options),
3913
+ transcript: (id, query = {}, options) => {
3914
+ if (query.before !== void 0 && query.afterRev !== void 0)
3915
+ throw new TypeError("before and afterRev are mutually exclusive");
3916
+ if (query.afterRev !== void 0 && query.epoch === void 0)
3917
+ throw new TypeError("epoch is required with afterRev");
3918
+ return this.connection.api.get(queryPath(`${entityPath("sessions", id)}/transcript`, {
3919
+ limit: query.limit,
3920
+ before: query.before,
3921
+ afterRev: query.afterRev,
3922
+ epoch: query.epoch
3923
+ }), options);
3924
+ },
3925
+ waitForFinish: (id, options) => this.closed ? Promise.reject(new WaitError("closed", "Client closed")) : waitForEntity(this.connection, "sessions", id, (s) => {
3926
+ if (s.runtime === "failed" || s.runtime === "interrupted" || s.runtime === "stopped")
3927
+ return { error: `session_${s.runtime}` };
3928
+ return {
3929
+ done: s.runtime === "idle" && s.queue.steering.length === 0 && s.queue.followUp.length === 0
3930
+ };
3931
+ }, options)
3932
+ };
3933
+ tasks = {
3934
+ create: (input, options) => this.connection.api.post("/api/tasks", input, options),
3935
+ list: (query = {}, options) => this.connection.api.get(queryPath("/api/tasks", {
3936
+ projectId: query.projectId,
3937
+ state: query.state?.join(","),
3938
+ includeHidden: query.includeHidden
3939
+ }), options),
3940
+ waitForState: (id, states, options) => {
3941
+ const wanted = Array.isArray(states) ? states : [states];
3942
+ if (!wanted.length)
3943
+ throw new TypeError("states must not be empty");
3944
+ if (this.closed)
3945
+ return Promise.reject(new WaitError("closed", "Client closed"));
3946
+ return waitForEntity(this.connection, "tasks", id, (task) => ({
3947
+ done: wanted.includes(task.state),
3948
+ error: task.state === "canceled" && !wanted.includes("canceled") ? "task_canceled" : void 0
3949
+ }), options);
3950
+ }
3951
+ };
3952
+ events = {
3953
+ subscribe: (listener, options = {}) => {
3954
+ if (this.closed)
3955
+ throw new Error("Client closed");
3956
+ const connection = new ClientConnection({
3957
+ ...this.opts,
3958
+ initialCursor: options.cursor,
3959
+ projectionId: options.projectionId ?? null
3960
+ });
3961
+ let active = true;
3962
+ const unsubscribe = () => {
3963
+ if (!active)
3964
+ return;
3965
+ active = false;
3966
+ this.subscriptions.delete(unsubscribe);
3967
+ options.signal?.removeEventListener("abort", unsubscribe);
3968
+ connection.close();
3969
+ };
3970
+ const error = (reason2) => {
3971
+ if (!active)
3972
+ return;
3973
+ try {
3974
+ options.onError?.(reason2);
3975
+ } finally {
3976
+ unsubscribe();
3977
+ }
3978
+ };
3979
+ connection.onNotice((notice) => {
3980
+ if (!active)
3981
+ return;
3982
+ try {
3983
+ listener(notice);
3984
+ } catch (cause) {
3985
+ error(cause instanceof Error ? cause : new Error(String(cause)));
3986
+ }
3987
+ });
3988
+ connection.onLogout((reason2) => error(new Error(reason2)));
3989
+ this.subscriptions.add(unsubscribe);
3990
+ options.signal?.addEventListener("abort", unsubscribe, { once: true });
3991
+ if (options.signal?.aborted)
3992
+ unsubscribe();
3993
+ else
3994
+ connection.connect();
3995
+ return unsubscribe;
3996
+ }
3997
+ };
3998
+ };
3999
+ export {
4000
+ ApiClient,
4001
+ ApiRequestError,
4002
+ ClientConnection,
4003
+ Store,
4004
+ SwitchyardClient,
4005
+ WaitError,
4006
+ wsUrlFor
4007
+ };