@spencerboucher/switchyard 0.11.0 → 0.12.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.
Files changed (101) hide show
  1. package/README.md +3 -0
  2. package/dist/bridge/agent-channel.js +449 -0
  3. package/dist/bridge/agent-tools.js +235 -0
  4. package/dist/bridge/message-delivery.js +185 -0
  5. package/dist/bridge/policy.js +213 -0
  6. package/dist/bridge/switchyard-bridge.js +73 -3
  7. package/dist/bridge/switchyard-terminal.js +77 -11
  8. package/dist/bridge/tool-preflight.js +155 -0
  9. package/dist/policies/worker.js +2877 -0
  10. package/dist/switchyard.mjs +15943 -7214
  11. package/package.json +3 -1
  12. package/web-dist/assets/AutomationView-BRVq9y-T.js +2 -0
  13. package/web-dist/assets/AutomationView-BRVq9y-T.js.map +1 -0
  14. package/web-dist/assets/{Card-XMb6DfZU.js → Card-BqrWFEYY.js} +2 -2
  15. package/web-dist/assets/{Card-XMb6DfZU.js.map → Card-BqrWFEYY.js.map} +1 -1
  16. package/web-dist/assets/{Checkbox-CeUPbVi7.js → Checkbox-DExv3fUO.js} +2 -2
  17. package/web-dist/assets/{Checkbox-CeUPbVi7.js.map → Checkbox-DExv3fUO.js.map} +1 -1
  18. package/web-dist/assets/{Copy-CGnl0Vga.js → Copy-BuBbxEQI.js} +2 -2
  19. package/web-dist/assets/{Copy-CGnl0Vga.js.map → Copy-BuBbxEQI.js.map} +1 -1
  20. package/web-dist/assets/{InteractionCard-1ePc4XOF.js → InteractionCard-0PH6pIkH.js} +4 -4
  21. package/web-dist/assets/{InteractionCard-1ePc4XOF.js.map → InteractionCard-0PH6pIkH.js.map} +1 -1
  22. package/web-dist/assets/{Menu-CYZQ97c0.js → Menu-BJ3Gyh5V.js} +2 -2
  23. package/web-dist/assets/{Menu-CYZQ97c0.js.map → Menu-BJ3Gyh5V.js.map} +1 -1
  24. package/web-dist/assets/{Overlay-DlLhg1cK.js → Overlay-BgqVqKc6.js} +2 -2
  25. package/web-dist/assets/{Overlay-DlLhg1cK.js.map → Overlay-BgqVqKc6.js.map} +1 -1
  26. package/web-dist/assets/{Priority-BCHLJqWN.js → Priority-B2tdgI2D.js} +2 -2
  27. package/web-dist/assets/{Priority-BCHLJqWN.js.map → Priority-B2tdgI2D.js.map} +1 -1
  28. package/web-dist/assets/{SegmentedControl-CSO0EMTX.js → SegmentedControl-DzwdZG6q.js} +2 -2
  29. package/web-dist/assets/{SegmentedControl-CSO0EMTX.js.map → SegmentedControl-DzwdZG6q.js.map} +1 -1
  30. package/web-dist/assets/{Select-Dgmnmpz3.js → Select-DZ-qJ_AO.js} +2 -2
  31. package/web-dist/assets/{Select-Dgmnmpz3.js.map → Select-DZ-qJ_AO.js.map} +1 -1
  32. package/web-dist/assets/{Switch-DS4NRENd.js → Switch-DKiwAXXz.js} +2 -2
  33. package/web-dist/assets/{Switch-DS4NRENd.js.map → Switch-DKiwAXXz.js.map} +1 -1
  34. package/web-dist/assets/{Tabs-9xp-tGja.js → Tabs-HOeWNnHD.js} +2 -2
  35. package/web-dist/assets/{Tabs-9xp-tGja.js.map → Tabs-HOeWNnHD.js.map} +1 -1
  36. package/web-dist/assets/{TextArea-PfVKaz29.js → TextArea-DK1uv3xX.js} +2 -2
  37. package/web-dist/assets/{TextArea-PfVKaz29.js.map → TextArea-DK1uv3xX.js.map} +1 -1
  38. package/web-dist/assets/{TextLink-CYqiAUlK.js → TextLink-BoFPQuaH.js} +2 -2
  39. package/web-dist/assets/{TextLink-CYqiAUlK.js.map → TextLink-BoFPQuaH.js.map} +1 -1
  40. package/web-dist/assets/attention-D1G0KCOr.js +2 -0
  41. package/web-dist/assets/{attention-CTkX5JXq.js.map → attention-D1G0KCOr.js.map} +1 -1
  42. package/web-dist/assets/automations-DUUAfMK8.js +2 -0
  43. package/web-dist/assets/{automations-CsdtA3xp.js.map → automations-DUUAfMK8.js.map} +1 -1
  44. package/web-dist/assets/board-tIuyEKO0.js +10 -0
  45. package/web-dist/assets/board-tIuyEKO0.js.map +1 -0
  46. package/web-dist/assets/code-O-DyPB50.js +25 -0
  47. package/web-dist/assets/code-O-DyPB50.js.map +1 -0
  48. package/web-dist/assets/{describe-DjRsBpcB.js → describe-BW5uUuvy.js} +3 -3
  49. package/web-dist/assets/{describe-DjRsBpcB.js.map → describe-BW5uUuvy.js.map} +1 -1
  50. package/web-dist/assets/enroll-CL0BGGhd.js +2 -0
  51. package/web-dist/assets/{enroll-DcEYGgoX.js.map → enroll-CL0BGGhd.js.map} +1 -1
  52. package/web-dist/assets/index-D-JHf__5.css +2 -0
  53. package/web-dist/assets/{index-DSJZdQ79.js → index-K0QOY1Li.js} +4 -4
  54. package/web-dist/assets/{index-DSJZdQ79.js.map → index-K0QOY1Li.js.map} +1 -1
  55. package/web-dist/assets/{more-BQSa_-H6.js → more-DNN_mtX8.js} +2 -2
  56. package/web-dist/assets/{more-BQSa_-H6.js.map → more-DNN_mtX8.js.map} +1 -1
  57. package/web-dist/assets/policyLogic-BKSj6mhC.js +2 -0
  58. package/web-dist/assets/policyLogic-BKSj6mhC.js.map +1 -0
  59. package/web-dist/assets/{preload-helper-Huh16h6r.js → preload-helper-BudhqmWi.js} +4 -4
  60. package/web-dist/assets/{preload-helper-Huh16h6r.js.map → preload-helper-BudhqmWi.js.map} +1 -1
  61. package/web-dist/assets/{queue-CCjBjQhT.js → queue-k4o-I9uY.js} +2 -2
  62. package/web-dist/assets/{queue-CCjBjQhT.js.map → queue-k4o-I9uY.js.map} +1 -1
  63. package/web-dist/assets/{repo-pkFfpra6.js → repo-CSQAnBaF.js} +2 -2
  64. package/web-dist/assets/{repo-pkFfpra6.js.map → repo-CSQAnBaF.js.map} +1 -1
  65. package/web-dist/assets/settings-CrYZRJ7E.js +7 -0
  66. package/web-dist/assets/settings-CrYZRJ7E.js.map +1 -0
  67. package/web-dist/assets/shared-DIA598ns.js +3 -0
  68. package/web-dist/assets/shared-DIA598ns.js.map +1 -0
  69. package/web-dist/assets/states-C8oEFqek.js +58 -0
  70. package/web-dist/assets/states-C8oEFqek.js.map +1 -0
  71. package/web-dist/assets/{terminal-login-D9enO0EH.js → terminal-login-M5orrPPe.js} +2 -2
  72. package/web-dist/assets/{terminal-login-D9enO0EH.js.map → terminal-login-M5orrPPe.js.map} +1 -1
  73. package/web-dist/assets/{useBreakpoint-LY_qlpRG.js → useBreakpoint-CA0Mbmvv.js} +2 -2
  74. package/web-dist/assets/{useBreakpoint-LY_qlpRG.js.map → useBreakpoint-CA0Mbmvv.js.map} +1 -1
  75. package/web-dist/assets/useNow-Dx0MCCez.js +2 -0
  76. package/web-dist/assets/useNow-Dx0MCCez.js.map +1 -0
  77. package/web-dist/assets/{useResource-Dul6MTDM.js → useResource-BTjwa4tV.js} +2 -2
  78. package/web-dist/assets/{useResource-Dul6MTDM.js.map → useResource-BTjwa4tV.js.map} +1 -1
  79. package/web-dist/index.html +8 -8
  80. package/web-dist/sw.js +1 -1
  81. package/web-dist/sw.js.map +1 -1
  82. package/web-dist/assets/AutomationView-CrKqim2i.js +0 -2
  83. package/web-dist/assets/AutomationView-CrKqim2i.js.map +0 -1
  84. package/web-dist/assets/Field-DVurWE-E.js +0 -2
  85. package/web-dist/assets/Field-DVurWE-E.js.map +0 -1
  86. package/web-dist/assets/attention-CTkX5JXq.js +0 -2
  87. package/web-dist/assets/automations-CsdtA3xp.js +0 -2
  88. package/web-dist/assets/board-CJL75uGb.js +0 -10
  89. package/web-dist/assets/board-CJL75uGb.js.map +0 -1
  90. package/web-dist/assets/code-CEYPZt-J.js +0 -21
  91. package/web-dist/assets/code-CEYPZt-J.js.map +0 -1
  92. package/web-dist/assets/enroll-DcEYGgoX.js +0 -2
  93. package/web-dist/assets/index-BeJqGnFE.css +0 -2
  94. package/web-dist/assets/settings-vrxspmWN.js +0 -7
  95. package/web-dist/assets/settings-vrxspmWN.js.map +0 -1
  96. package/web-dist/assets/shared-Bm6Rhfqw.js +0 -3
  97. package/web-dist/assets/shared-Bm6Rhfqw.js.map +0 -1
  98. package/web-dist/assets/states-BQxrRFdh.js +0 -56
  99. package/web-dist/assets/states-BQxrRFdh.js.map +0 -1
  100. package/web-dist/assets/useNow-BUvGqrfn.js +0 -2
  101. package/web-dist/assets/useNow-BUvGqrfn.js.map +0 -1
@@ -0,0 +1,2877 @@
1
+ // packages/coordinator/dist/policies/worker.js
2
+ import { parentPort } from "node:worker_threads";
3
+ import { Environment } from "@marcbachmann/cel-js";
4
+
5
+ // packages/protocol/dist/agent-wire.js
6
+ import { z as z3 } from "zod";
7
+
8
+ // packages/protocol/dist/errors.js
9
+ import { z } from "zod";
10
+ var ERROR_CODES = [
11
+ "unauthorized",
12
+ "forbidden",
13
+ "not_found",
14
+ "invalid_request",
15
+ "conflict",
16
+ "already_answered",
17
+ "stale_control",
18
+ "host_unreachable",
19
+ "pi_incompatible",
20
+ "native_session_missing",
21
+ "invalid_transition",
22
+ "dependency_cycle",
23
+ "workspace_dirty",
24
+ "workspace_unmerged",
25
+ "workspace_active_sessions",
26
+ "branch_invalid",
27
+ "path_collision",
28
+ "not_a_git_repo",
29
+ "repo_mismatch",
30
+ "enrollment_expired",
31
+ "enrollment_used",
32
+ "device_revoked",
33
+ "unsupported_capability",
34
+ "too_large",
35
+ "ui_tree_too_large",
36
+ "timeout",
37
+ "rate_limited",
38
+ "internal"
39
+ ];
40
+ var ErrorCode = z.enum(ERROR_CODES);
41
+ var ErrorBody = z.object({
42
+ code: ErrorCode,
43
+ message: z.string(),
44
+ details: z.unknown().optional()
45
+ });
46
+ var ApiError = z.object({ error: ErrorBody });
47
+
48
+ // packages/protocol/dist/policies.js
49
+ import { z as z2 } from "zod";
50
+ var Id = z2.string().min(1).max(200);
51
+ var Revision = z2.number().int().safe().min(1);
52
+ var Instant = z2.string().refine((s) => {
53
+ try {
54
+ return new Date(s).toISOString() === s;
55
+ } catch {
56
+ return false;
57
+ }
58
+ });
59
+ var Text = z2.string().max(4e3);
60
+ var Reason = Text.min(1);
61
+ var Fingerprint = z2.string().regex(/^[0-9a-f]{64}$/);
62
+ var forbidden = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
63
+ var bytes = (s) => new TextEncoder().encode(s).length;
64
+ function validJson(value, depth = 0, seen = /* @__PURE__ */ new Set()) {
65
+ if (depth > 20)
66
+ return false;
67
+ if (value === null || typeof value === "string" || typeof value === "boolean")
68
+ return true;
69
+ if (typeof value === "number")
70
+ return Number.isFinite(value) && (!Number.isInteger(value) || Number.isSafeInteger(value));
71
+ if (typeof value !== "object" || seen.has(value))
72
+ return false;
73
+ const prototype = Object.getPrototypeOf(value);
74
+ if (Array.isArray(value) ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null)
75
+ return false;
76
+ seen.add(value);
77
+ try {
78
+ const descriptors = Object.getOwnPropertyDescriptors(value);
79
+ const keys = Reflect.ownKeys(descriptors);
80
+ if (Array.isArray(value) && keys.length !== value.length + 1)
81
+ return false;
82
+ return keys.every((key) => {
83
+ if (typeof key !== "string" || forbidden.has(key))
84
+ return false;
85
+ if (Array.isArray(value)) {
86
+ if (key === "length")
87
+ return true;
88
+ if (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length)
89
+ return false;
90
+ }
91
+ const descriptor = descriptors[key];
92
+ return descriptor.enumerable === true && "value" in descriptor && validJson(descriptor.value, depth + 1, seen);
93
+ });
94
+ } finally {
95
+ seen.delete(value);
96
+ }
97
+ }
98
+ var JsonObject = z2.custom((v) => !!v && typeof v === "object" && !Array.isArray(v) && validJson(v));
99
+ var CompletedUsageWatermark = z2.object({ runtimeId: Id, settleSeq: Revision }).strict();
100
+ var scopeShape = { scope: z2.enum(["session", "profile", "server"]), scopeId: Id.nullable() };
101
+ var scopeValid = (v) => v.scope === "server" === (v.scopeId === null);
102
+ var PolicyPhase = z2.enum(["tool_call", "request"]);
103
+ var PolicyVerdict = z2.enum(["ALLOW", "ASK", "DENY"]);
104
+ var PolicyRequestAction = z2.enum([
105
+ "task.create",
106
+ "message.send",
107
+ "inbox.read",
108
+ "run.continue"
109
+ ]);
110
+ var PolicyScope = scopeShape.scope;
111
+ var PolicyCounterMap = z2.record(z2.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/).refine((k) => !forbidden.has(k)), z2.number().int().safe()).refine((v) => Object.keys(v).length <= 64);
112
+ var phases = z2.array(PolicyPhase).min(1).max(2).refine((v) => new Set(v).size === v.length);
113
+ var ruleFields = {
114
+ priority: z2.number().int().safe().min(-1e6).max(1e6),
115
+ enabled: z2.boolean(),
116
+ phases,
117
+ name: z2.string().min(1).max(120),
118
+ expression: z2.string().min(1).max(8192)
119
+ };
120
+ var PolicyRule = z2.object({
121
+ id: Id,
122
+ ...scopeShape,
123
+ ...ruleFields,
124
+ revision: Revision,
125
+ builtIn: z2.boolean(),
126
+ createdAt: Instant,
127
+ updatedAt: Instant
128
+ }).strict().refine(scopeValid);
129
+ var PolicyToolSafety = z2.object({
130
+ destructiveDelete: z2.boolean(),
131
+ forcePush: z2.boolean(),
132
+ defaultBranchPush: z2.boolean(),
133
+ uncertain: z2.boolean(),
134
+ reasons: z2.array(z2.string().min(1).max(1e3)).max(16)
135
+ }).strict();
136
+ function normalizePosixPath(value) {
137
+ const parts = [];
138
+ for (const part of value.split("/")) {
139
+ if (part === "..")
140
+ parts.pop();
141
+ else if (part && part !== ".")
142
+ parts.push(part);
143
+ }
144
+ return `/${parts.join("/")}`;
145
+ }
146
+ var hostPath = z2.string().min(1).max(8192).refine((value) => value.startsWith("/") && !value.includes("\0"), "Expected absolute POSIX path").transform(normalizePosixPath);
147
+ function relativePosixPath(from, to) {
148
+ const fromParts = from.split("/").filter(Boolean);
149
+ const toParts = to.split("/").filter(Boolean);
150
+ let shared = 0;
151
+ while (shared < fromParts.length && fromParts[shared] === toParts[shared])
152
+ shared++;
153
+ return [...fromParts.slice(shared).map(() => ".."), ...toParts.slice(shared)].join("/");
154
+ }
155
+ var HostPolicyBoundary = z2.object({
156
+ cwd: hostPath,
157
+ workspaceRoot: hostPath,
158
+ cwdReal: hostPath,
159
+ workspaceRootReal: hostPath
160
+ }).strict().refine((boundary) => {
161
+ const relative = relativePosixPath(boundary.workspaceRootReal, boundary.cwdReal);
162
+ return relative !== ".." && !relative.startsWith("../");
163
+ }, "Real cwd must be within the real workspace boundary.");
164
+ var HostToolPolicyContext = z2.object({
165
+ version: z2.literal(1),
166
+ toolCallId: Id,
167
+ toolHash: Fingerprint,
168
+ boundary: HostPolicyBoundary,
169
+ defaultBranch: z2.string().min(1).max(255).nullable(),
170
+ safety: PolicyToolSafety
171
+ }).strict();
172
+ var PolicyToolContext = z2.object({ name: Id, args: JsonObject, safety: PolicyToolSafety }).strict();
173
+ var PolicyRequestContext = z2.object({ method: PolicyRequestAction, args: JsonObject }).strict();
174
+ var absolutePath = z2.string().min(1).max(8192).refine((v) => v.startsWith("/") || /^[A-Za-z]:[\\/]/.test(v));
175
+ var controlMode = z2.enum(["human", "automation"]);
176
+ var PolicySessionContext = z2.object({
177
+ id: Id,
178
+ hostId: Id,
179
+ nativeSessionId: Id.nullable(),
180
+ runtimeId: Id.nullable(),
181
+ profileId: Id,
182
+ projectId: Id.nullable(),
183
+ taskId: Id.nullable(),
184
+ runId: Id.nullable(),
185
+ controlMode,
186
+ controlRevision: Revision,
187
+ cwd: absolutePath,
188
+ workspaceRoot: absolutePath,
189
+ repository: z2.string().min(1).max(2048).nullable(),
190
+ defaultBranch: z2.string().min(1).max(255).nullable(),
191
+ readOnly: z2.boolean()
192
+ }).strict();
193
+ var PolicyTaskContext = z2.object({
194
+ id: Id,
195
+ projectId: Id,
196
+ rootTaskId: Id,
197
+ parentTaskId: Id.nullable(),
198
+ title: z2.string().min(1).max(300),
199
+ state: z2.enum(["backlog", "ready", "in_progress", "review", "done", "canceled"])
200
+ }).strict();
201
+ var PolicyTargetContext = z2.object({
202
+ id: Id,
203
+ hostId: Id,
204
+ projectId: Id.nullable(),
205
+ taskId: Id.nullable(),
206
+ controlMode,
207
+ controlRevision: Revision,
208
+ runtime: z2.enum([
209
+ "starting",
210
+ "idle",
211
+ "running",
212
+ "waiting_input",
213
+ "interrupted",
214
+ "failed",
215
+ "stopped"
216
+ ]),
217
+ readOnly: z2.boolean()
218
+ }).strict();
219
+ var PolicyCostContext = z2.object({
220
+ tokens: z2.number().int().safe().nonnegative().nullable(),
221
+ costUsd: z2.number().finite().nonnegative().nullable(),
222
+ maxTokens: z2.number().int().safe().positive().nullable(),
223
+ maxCostUsd: z2.number().finite().positive().nullable(),
224
+ accounting: z2.enum(["available", "unavailable"]),
225
+ fresh: z2.boolean(),
226
+ watermark: CompletedUsageWatermark.nullable(),
227
+ provider: Id.nullable(),
228
+ modelId: z2.string().min(1).max(512).nullable(),
229
+ classification: z2.enum(["cheap", "expensive", "unclassified"]),
230
+ expensive: z2.boolean()
231
+ }).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));
232
+ var PolicyContext = z2.object({
233
+ phase: PolicyPhase,
234
+ action: z2.union([z2.literal("tool.call"), PolicyRequestAction]),
235
+ tool: PolicyToolContext.nullable(),
236
+ request: PolicyRequestContext.nullable(),
237
+ session: PolicySessionContext,
238
+ task: PolicyTaskContext.nullable(),
239
+ target: PolicyTargetContext.nullable(),
240
+ cost: PolicyCostContext,
241
+ counters: PolicyCounterMap
242
+ }).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) => bytes(JSON.stringify(v)) <= 65536, "Policy input is too large to evaluate.");
243
+ var PolicyRuleResult = z2.union([
244
+ z2.null(),
245
+ z2.object({ verdict: PolicyVerdict, reason: Text, state_updates: PolicyCounterMap.optional() }).strict().refine((v) => v.verdict === "ALLOW" || v.reason.length > 0)
246
+ ]);
247
+ var webUrl = z2.string().max(4096).refine((s) => {
248
+ try {
249
+ const u = new URL(s);
250
+ return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password;
251
+ } catch {
252
+ return false;
253
+ }
254
+ });
255
+ var PolicyEvaluation = z2.discriminatedUnion("verdict", [
256
+ z2.object({ verdict: z2.literal("ALLOW") }).strict(),
257
+ z2.object({ verdict: z2.literal("DENY"), reason: Reason }).strict(),
258
+ z2.object({
259
+ verdict: z2.literal("ASK"),
260
+ decisionId: Id,
261
+ interactionId: Id,
262
+ interactionUrl: webUrl
263
+ }).strict()
264
+ ]);
265
+ var PolicyPermission = z2.object({
266
+ kind: z2.literal("policy"),
267
+ decisionId: Id,
268
+ rootTaskId: Id.nullable(),
269
+ ruleId: Id,
270
+ ruleRevision: Revision,
271
+ fingerprint: Fingerprint
272
+ }).strict();
273
+ var PolicyGrant = z2.object({
274
+ id: Id,
275
+ scope: z2.object({ kind: z2.enum(["task", "session"]), id: Id }).strict(),
276
+ ruleId: Id,
277
+ ruleRevision: Revision,
278
+ fingerprint: Fingerprint,
279
+ approvedByDeviceId: Id,
280
+ approvedAt: Instant
281
+ }).strict();
282
+ var trimmed = (max) => z2.string().min(1).max(max).refine((s) => s.trim() === s);
283
+ var PolicyModelClassification = z2.object({
284
+ provider: trimmed(200),
285
+ modelId: trimmed(512),
286
+ classification: z2.enum(["cheap", "expensive"])
287
+ }).strict();
288
+ var classifications = z2.array(PolicyModelClassification).max(1e3).refine((v) => new Set(v.map((x) => JSON.stringify([x.provider, x.modelId]))).size === v.length);
289
+ var PolicySettings = z2.object({ revision: Revision, modelClassifications: classifications, updatedAt: Instant }).strict();
290
+ var toolInput = z2.object({ name: Id, args: JsonObject }).strict();
291
+ var sampleIdentity = { sessionId: Id, nativeSessionId: Id, runtimeId: Id, sampleId: Id };
292
+ var HostPolicySampleRequest = z2.object({ ...sampleIdentity, tool: toolInput }).strict();
293
+ var HostPolicySampleResult = z2.object({
294
+ ...sampleIdentity,
295
+ toolHash: Fingerprint,
296
+ boundary: HostPolicyBoundary,
297
+ defaultBranch: z2.string().min(1).max(255).nullable(),
298
+ safety: PolicyToolSafety
299
+ }).strict();
300
+ var PolicyEvaluateRequest = z2.object({ evaluationId: Id, toolCallId: Id, tool: toolInput }).strict();
301
+ var PolicyStatusRequest = z2.object({ decisionId: Id, waitMs: z2.literal(25e3) }).strict();
302
+ var PolicyStatusResult = z2.discriminatedUnion("state", [
303
+ z2.object({ state: z2.literal("pending") }).strict(),
304
+ z2.object({ state: z2.literal("allowed") }).strict(),
305
+ z2.object({ state: z2.literal("denied"), reason: Reason }).strict(),
306
+ z2.object({ state: z2.literal("canceled"), reason: Reason }).strict()
307
+ ]);
308
+ var PolicyCancelRequest = z2.object({ decisionId: Id }).strict();
309
+ var PolicyCancelResult = z2.object({ state: z2.enum(["canceled", "already_resolved"]) }).strict();
310
+ var PolicyTrace = z2.object({
311
+ ruleId: Id,
312
+ ruleRevision: Revision,
313
+ ...scopeShape,
314
+ verdict: PolicyVerdict.nullable(),
315
+ reason: Text.nullable(),
316
+ granted: z2.boolean(),
317
+ overridden: z2.boolean(),
318
+ proposedStateUpdates: PolicyCounterMap
319
+ }).strict().refine(scopeValid);
320
+ var PolicyTestResult = z2.object({
321
+ verdict: PolicyVerdict,
322
+ reason: Text.nullable(),
323
+ trace: z2.array(PolicyTrace).max(128),
324
+ proposedStateUpdates: z2.record(Id, PolicyCounterMap),
325
+ enforcement: z2.object({
326
+ phases: z2.array(PolicyPhase),
327
+ modelRequest: z2.literal(false),
328
+ explanation: z2.string()
329
+ }).strict()
330
+ }).strict();
331
+ var CreatePolicyRuleRequest = z2.object({ ...scopeShape, ...ruleFields }).strict().refine(scopeValid);
332
+ var UpdatePolicyRuleRequest = z2.object({
333
+ expectedRevision: Revision,
334
+ name: ruleFields.name.optional(),
335
+ priority: ruleFields.priority.optional(),
336
+ enabled: z2.boolean().optional(),
337
+ phases: phases.optional(),
338
+ expression: ruleFields.expression.optional()
339
+ }).strict().refine((v) => Object.keys(v).length > 1);
340
+ var DeletePolicyRuleQuery = z2.object({ expectedRevision: Revision }).strict();
341
+ var UpdatePolicySettingsRequest = z2.object({ expectedRevision: Revision, modelClassifications: classifications }).strict();
342
+ var PolicyTestRequest = z2.object({
343
+ sessionId: Id,
344
+ phase: PolicyPhase,
345
+ tool: toolInput.nullable(),
346
+ request: PolicyRequestContext.nullable()
347
+ }).strict().refine((v) => v.phase === "tool_call" ? v.tool !== null && v.request === null : v.tool === null && v.request !== null);
348
+
349
+ // packages/protocol/dist/agent-wire.js
350
+ var Id2 = z3.string().min(1).max(200);
351
+ var Instant2 = z3.string().refine((value) => {
352
+ const date = new Date(value);
353
+ return Number.isFinite(date.getTime()) && date.toISOString() === value;
354
+ }, "Expected canonical UTC timestamp");
355
+ var AGENT_FRAME_MAX_BYTES = 128 * 1024;
356
+ var AgentMethod = z3.enum([
357
+ "session.bind",
358
+ "task.create",
359
+ "message.send",
360
+ "inbox.read",
361
+ "receipt.peek",
362
+ "policy.evaluate",
363
+ "policy.status",
364
+ "policy.cancel"
365
+ ]);
366
+ var AgentToolMethod = z3.enum(["task.create", "message.send", "inbox.read"]);
367
+ var RequestHash = z3.string().regex(/^[a-f0-9]{64}$/);
368
+ var AgentReceiptPeekRequest = z3.object({ method: AgentToolMethod, args: z3.record(z3.string(), z3.json()) }).strict();
369
+ var AgentReceiptPeekResult = z3.discriminatedUnion("found", [
370
+ z3.object({ found: z3.literal(false) }).strict(),
371
+ z3.object({ found: z3.literal(true), requestHash: RequestHash }).strict()
372
+ ]);
373
+ var AgentReceiptReplay = z3.object({ requestHash: RequestHash }).strict();
374
+ var CreateAgentTask = z3.object({
375
+ objective: z3.string().min(1).max(16e3),
376
+ acceptance: z3.array(z3.string().min(1).max(2e3)).max(100).default([]),
377
+ dependencies: z3.array(Id2).max(100).default([]),
378
+ parentTaskId: Id2.nullable().optional(),
379
+ hostId: Id2.optional(),
380
+ profileId: Id2.optional(),
381
+ notifyOnFinish: z3.boolean().default(true)
382
+ });
383
+ var SendAgentMessage = z3.object({
384
+ sessionId: Id2,
385
+ body: z3.string().min(1).max(16e3),
386
+ mode: z3.enum(["steer", "queue"]),
387
+ replyTo: Id2.optional()
388
+ });
389
+ var ReadAgentInbox = z3.object({
390
+ after: z3.number().int().nonnegative().default(0),
391
+ limit: z3.number().int().min(1).max(100).default(20)
392
+ });
393
+ var DeliveryState = z3.enum([
394
+ "pending",
395
+ "held",
396
+ "deferred",
397
+ "accepted",
398
+ "queued",
399
+ "appended",
400
+ "uncertain",
401
+ "failed"
402
+ ]);
403
+ var AgentMessageFields = {
404
+ seq: z3.number().int().positive(),
405
+ id: Id2,
406
+ recipientSessionId: Id2,
407
+ replyTo: Id2.nullable(),
408
+ chainId: Id2,
409
+ depth: z3.number().int().min(0).max(4),
410
+ body: z3.unknown(),
411
+ requestedMode: z3.enum(["steer", "queue"]),
412
+ deliveryState: DeliveryState,
413
+ holdUntil: z3.string(),
414
+ readAt: z3.string().nullable(),
415
+ createdAt: z3.string()
416
+ };
417
+ var AgentMessage = z3.discriminatedUnion("kind", [
418
+ z3.object({ ...AgentMessageFields, kind: z3.literal("message"), senderSessionId: Id2 }),
419
+ z3.object({
420
+ ...AgentMessageFields,
421
+ kind: z3.literal("completion"),
422
+ senderSessionId: Id2.nullable()
423
+ })
424
+ ]);
425
+ var AgentInbox = z3.object({
426
+ messages: z3.array(AgentMessage),
427
+ nextAfter: z3.number().int().nonnegative(),
428
+ hasMore: z3.boolean()
429
+ });
430
+ var AgentToolPolicyWait = PolicyEvaluation.options[2].omit({ verdict: true }).extend({ type: z3.literal("policy.required") }).strict();
431
+ var AgentRequestFrame = z3.object({
432
+ type: z3.literal("agent.request"),
433
+ requestId: Id2,
434
+ sessionId: Id2,
435
+ nativeSessionId: Id2,
436
+ runtimeId: Id2,
437
+ context: z3.object({ humanInputId: Id2.nullable(), causalMessageId: Id2.nullable() }).strict(),
438
+ toolCallId: Id2.optional(),
439
+ receiptReplay: AgentReceiptReplay.optional(),
440
+ // Tool-method ingress requires this separately; legacy/non-tool frames remain compatible.
441
+ deadlineAt: Instant2.optional(),
442
+ method: AgentMethod,
443
+ args: z3.unknown()
444
+ }).strict().superRefine((frame, ctx) => {
445
+ if (frame.method === "receipt.peek") {
446
+ if (!frame.toolCallId) {
447
+ ctx.addIssue({
448
+ code: "custom",
449
+ path: ["toolCallId"],
450
+ message: "Receipt lookup requires a tool call ID."
451
+ });
452
+ }
453
+ }
454
+ if (Object.hasOwn(frame, "receiptReplay") && !AgentToolMethod.safeParse(frame.method).success) {
455
+ ctx.addIssue({
456
+ code: "custom",
457
+ path: ["receiptReplay"],
458
+ message: "Receipt replay is only valid for tool methods."
459
+ });
460
+ }
461
+ });
462
+ var AgentResultFrame = z3.discriminatedUnion("ok", [
463
+ z3.object({
464
+ type: z3.literal("agent.result"),
465
+ requestId: Id2,
466
+ runtimeId: Id2,
467
+ ok: z3.literal(true),
468
+ result: z3.unknown()
469
+ }),
470
+ z3.object({
471
+ type: z3.literal("agent.result"),
472
+ requestId: Id2,
473
+ runtimeId: Id2,
474
+ ok: z3.literal(false),
475
+ error: ErrorBody
476
+ })
477
+ ]);
478
+
479
+ // packages/protocol/dist/api.js
480
+ import { z as z10 } from "zod";
481
+
482
+ // packages/protocol/dist/entities.js
483
+ import { z as z6 } from "zod";
484
+
485
+ // packages/protocol/dist/github.js
486
+ import { z as z4 } from "zod";
487
+ var Id3 = z4.string().min(1).max(200);
488
+ var Instant3 = z4.string().refine((s) => {
489
+ try {
490
+ return new Date(s).toISOString() === s;
491
+ } catch {
492
+ return false;
493
+ }
494
+ });
495
+ var positive = z4.number().int().safe().positive();
496
+ var nonnegative = z4.number().int().safe().nonnegative();
497
+ var reason = z4.string().min(1).max(2e3);
498
+ var hash = z4.string().regex(/^[0-9a-f]{64}$/);
499
+ var actionsId = z4.string().regex(/^[1-9][0-9]{0,19}$/);
500
+ var bytes2 = (s) => new TextEncoder().encode(s).length;
501
+ var displayUrl = z4.string().max(4096).refine((s) => {
502
+ try {
503
+ const u = new URL(s);
504
+ return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password;
505
+ } catch {
506
+ return false;
507
+ }
508
+ });
509
+ var githubUrl = displayUrl.refine((s) => {
510
+ try {
511
+ const u = new URL(s);
512
+ return u.protocol === "https:" && u.hostname === "github.com" && !u.port && /^https:\/\/github\.com(?:[/?#]|$)/i.test(s);
513
+ } catch {
514
+ return false;
515
+ }
516
+ });
517
+ 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}$/);
518
+ var issuePath = /^[hH][tT][tT][pP][sS]:\/\/[gG][iI][tT][hH][uU][bB]\.[cC][oO][mM]\/([^/]+)\/([^/]+)\/issues\/([1-9][0-9]*)$/;
519
+ var GitHubIssueUrl = z4.string().trim().transform((raw, ctx) => {
520
+ const match = issuePath.exec(raw);
521
+ const number = match ? Number(match[3]) : NaN;
522
+ if (!match || !GitHubRepository.safeParse(`${match[1]}/${match[2]}`).success || !Number.isSafeInteger(number)) {
523
+ ctx.addIssue({ code: "custom", message: "Invalid GitHub issue URL" });
524
+ return z4.NEVER;
525
+ }
526
+ return `https://github.com/${match[1]}/${match[2]}/issues/${number}`;
527
+ });
528
+ function issueParts(url) {
529
+ const match = issuePath.exec(url);
530
+ return { repository: `${match[1]}/${match[2]}`, number: Number(match[3]) };
531
+ }
532
+ function issuePrompt(url) {
533
+ return `${url}
534
+
535
+ Read it with \`gh issue view ${url}\`.`;
536
+ }
537
+ var GitHubIssueIdentity = z4.object({
538
+ repository: GitHubRepository,
539
+ number: positive,
540
+ url: GitHubIssueUrl
541
+ }).strict().refine((v) => {
542
+ const parts = issueParts(v.url);
543
+ return v.repository === parts.repository && v.number === parts.number;
544
+ });
545
+ var GitHubIssue = z4.object({
546
+ repository: GitHubRepository,
547
+ number: positive,
548
+ url: GitHubIssueUrl,
549
+ launchPrompt: z4.string()
550
+ }).strict().refine((v) => {
551
+ const parts = issueParts(v.url);
552
+ return v.repository === parts.repository && v.number === parts.number && v.launchPrompt === issuePrompt(v.url);
553
+ });
554
+ function githubIssueFromUrl(raw) {
555
+ const url = GitHubIssueUrl.parse(raw);
556
+ return { ...issueParts(url), url, launchPrompt: issuePrompt(url) };
557
+ }
558
+ var GitHubSha = z4.string().regex(/^[0-9a-f]{40}$/);
559
+ var prUrl = githubUrl.refine((s) => {
560
+ try {
561
+ const u = new URL(s);
562
+ return /^\/[^/]+\/[^/]+\/pull\/[1-9][0-9]*$/.test(u.pathname) && !u.search && !u.hash;
563
+ } catch {
564
+ return false;
565
+ }
566
+ });
567
+ function matchesPr(url, repository, number) {
568
+ try {
569
+ const u = new URL(url);
570
+ return u.pathname.toLowerCase() === `/${repository}/pull/${number}`.toLowerCase();
571
+ } catch {
572
+ return false;
573
+ }
574
+ }
575
+ var HostGitHub = z4.object({ available: z4.boolean(), reason: reason.nullable() }).strict().refine((v) => v.available === (v.reason === null));
576
+ var GitHubCheck = z4.object({
577
+ id: hash,
578
+ name: z4.string().min(1).max(300),
579
+ state: z4.string().min(1).max(100),
580
+ bucket: z4.enum(["pass", "fail", "pending", "skipping", "cancel", "unknown"]),
581
+ link: displayUrl.nullable(),
582
+ workflow: z4.string().max(300).nullable(),
583
+ event: z4.string().max(100).nullable(),
584
+ startedAt: Instant3.nullable(),
585
+ completedAt: Instant3.nullable(),
586
+ description: z4.string().max(2e3).nullable(),
587
+ actionsJob: z4.object({ runId: actionsId, jobId: actionsId, attempt: positive }).strict().nullable()
588
+ }).strict();
589
+ var GitHubComment = z4.object({
590
+ id: Id3,
591
+ author: z4.string().min(1).max(200).nullable(),
592
+ body: z4.string().refine((v) => [...v].length <= 8e3),
593
+ bodyTruncated: z4.boolean(),
594
+ url: githubUrl,
595
+ createdAt: Instant3.nullable()
596
+ }).strict();
597
+ var GitHubThread = z4.object({
598
+ id: Id3,
599
+ isResolved: z4.literal(false),
600
+ isOutdated: z4.boolean(),
601
+ path: z4.string().max(8192).nullable(),
602
+ line: positive.nullable(),
603
+ startLine: positive.nullable(),
604
+ side: z4.enum(["LEFT", "RIGHT"]).nullable(),
605
+ comments: z4.array(GitHubComment).max(10),
606
+ commentsComplete: z4.boolean()
607
+ }).strict();
608
+ var GitHubPullRequest = z4.object({
609
+ nodeId: z4.string().min(1).optional(),
610
+ number: positive,
611
+ url: prUrl,
612
+ title: z4.string().min(1).max(1e3),
613
+ state: z4.enum(["OPEN", "CLOSED", "MERGED"]),
614
+ isDraft: z4.boolean(),
615
+ headRefName: z4.string().min(1).max(255),
616
+ headRefOid: GitHubSha,
617
+ headRepository: GitHubRepository.nullable(),
618
+ baseRefName: z4.string().min(1).max(255),
619
+ mergeable: z4.string().min(1).max(100),
620
+ mergeStateStatus: z4.string().min(1).max(100),
621
+ reviewDecision: z4.enum(["APPROVED", "REVIEW_REQUIRED", "CHANGES_REQUESTED"]).nullable(),
622
+ mergeQueueEnabled: z4.boolean(),
623
+ inMergeQueue: z4.boolean(),
624
+ autoMergeEnabled: z4.boolean(),
625
+ squashMergeAllowed: z4.boolean()
626
+ }).strict().refine((v) => {
627
+ try {
628
+ return new URL(v.url).pathname.endsWith(`/pull/${v.number}`);
629
+ } catch {
630
+ return false;
631
+ }
632
+ });
633
+ var WorkspaceGitHub = z4.object({
634
+ repository: GitHubRepository.nullable(),
635
+ headRepository: GitHubRepository.nullable(),
636
+ branch: z4.string().min(1).max(255).nullable(),
637
+ fetchedAt: Instant3.nullable(),
638
+ attemptedAt: Instant3,
639
+ status: z4.enum(["ready", "unavailable", "error", "ambiguous"]),
640
+ reason: reason.nullable(),
641
+ pullRequest: GitHubPullRequest.nullable(),
642
+ checks: z4.array(GitHubCheck).max(500),
643
+ checksComplete: z4.boolean(),
644
+ threads: z4.array(GitHubThread).max(500),
645
+ threadsComplete: z4.boolean(),
646
+ truncated: z4.boolean()
647
+ }).strict().refine((v) => {
648
+ if (bytes2(JSON.stringify(v)) > 512 * 1024 || new Set(v.checks.map((c) => c.id)).size !== v.checks.length)
649
+ return false;
650
+ if (v.pullRequest && (!v.repository || !matchesPr(v.pullRequest.url, v.repository, v.pullRequest.number)))
651
+ return false;
652
+ if (v.threads.some((t) => !t.commentsComplete || t.comments.some((c) => c.bodyTruncated)) && (v.threadsComplete || !v.truncated))
653
+ return false;
654
+ if (v.status !== "ready")
655
+ return v.reason !== null && !v.checksComplete && !v.threadsComplete;
656
+ 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);
657
+ });
658
+ var GitHubViewResult = z4.object({ github: HostGitHub, snapshot: WorkspaceGitHub }).strict();
659
+ var GitHubViewResponse = z4.object({ github: HostGitHub.nullable(), snapshot: WorkspaceGitHub.nullable() }).strict();
660
+ function lineCount(s) {
661
+ if (!s)
662
+ return 0;
663
+ const lines = s.replace(/\r\n/g, "\n").split("\n");
664
+ if (lines[lines.length - 1] === "")
665
+ lines.pop();
666
+ return lines.length;
667
+ }
668
+ var GitHubJobLog = z4.object({
669
+ checkId: hash,
670
+ name: z4.string().min(1).max(300),
671
+ url: displayUrl.nullable(),
672
+ runId: actionsId.nullable(),
673
+ jobId: actionsId.nullable(),
674
+ attempt: positive.nullable(),
675
+ status: z4.enum([
676
+ "available",
677
+ "unmapped",
678
+ "incomplete",
679
+ "expired",
680
+ "forbidden",
681
+ "timeout",
682
+ "error"
683
+ ]),
684
+ outputTail: z4.string().nullable(),
685
+ lineCount: nonnegative.max(150),
686
+ truncated: z4.boolean(),
687
+ reason: reason.nullable()
688
+ }).strict().refine((v) => v.status === "available" ? v.runId !== null && v.jobId !== null && v.attempt !== null && v.outputTail !== null && bytes2(v.outputTail) <= 65536 && lineCount(v.outputTail) === v.lineCount && v.reason === null : v.outputTail === null && v.lineCount === 0 && v.reason !== null);
689
+ var GitHubLogs = z4.object({
690
+ github: HostGitHub,
691
+ repository: GitHubRepository,
692
+ number: positive,
693
+ headOid: GitHubSha,
694
+ fetchedAt: Instant3,
695
+ status: z4.enum(["ready", "unavailable", "error"]),
696
+ reason: reason.nullable(),
697
+ jobs: z4.array(GitHubJobLog).max(10),
698
+ complete: z4.boolean(),
699
+ truncated: z4.boolean(),
700
+ omittedJobs: nonnegative.nullable()
701
+ }).strict().refine((v) => bytes2(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));
702
+ var GitHubLogsRequest = z4.object({ expectedHeadOid: GitHubSha }).strict();
703
+ var GitHubMergeRequest = z4.object({ expectedHeadOid: GitHubSha }).strict();
704
+ var mergeFields = {
705
+ github: HostGitHub,
706
+ repository: GitHubRepository,
707
+ number: positive,
708
+ url: prUrl,
709
+ expectedHeadOid: GitHubSha
710
+ };
711
+ var GitHubMergeResult = z4.discriminatedUnion("status", [
712
+ z4.object({
713
+ status: z4.literal("merged"),
714
+ ...mergeFields,
715
+ mergeCommitOid: GitHubSha.nullable(),
716
+ confirmedAt: Instant3
717
+ }).strict(),
718
+ z4.object({
719
+ status: z4.literal("outcome_unknown"),
720
+ ...mergeFields,
721
+ reason,
722
+ attemptedAt: Instant3
723
+ }).strict()
724
+ ]).refine((v) => matchesPr(v.url, v.repository, v.number));
725
+ var path = z4.string().min(1).max(8192);
726
+ var GitHubHostViewRequest = z4.object({ path }).strict();
727
+ var GitHubHostLogsRequest = z4.object({ path, repository: GitHubRepository, number: positive, expectedHeadOid: GitHubSha }).strict();
728
+ var GitHubHostMergeRequest = GitHubHostLogsRequest.extend({
729
+ expectedPullRequestNodeId: z4.string().min(1)
730
+ });
731
+
732
+ // packages/protocol/dist/ui.js
733
+ import { z as z5 } from "zod";
734
+ var ToneSchema = z5.enum(["default", "muted", "success", "warning", "danger"]);
735
+ var ShowIfSchema = z5.object({ field: z5.string(), values: z5.array(z5.string()) });
736
+ var OptionSchema = z5.object({
737
+ value: z5.string(),
738
+ label: z5.string(),
739
+ description: z5.string().optional(),
740
+ preview: z5.string().optional()
741
+ });
742
+ var AllowOther = z5.object({ label: z5.string(), placeholder: z5.string().optional() });
743
+ var FieldSchema = z5.discriminatedUnion("kind", [
744
+ z5.object({
745
+ kind: z5.literal("select"),
746
+ name: z5.string(),
747
+ label: z5.string(),
748
+ options: z5.array(OptionSchema),
749
+ allowOther: AllowOther.optional(),
750
+ showIf: ShowIfSchema.optional()
751
+ }),
752
+ z5.object({
753
+ kind: z5.literal("multiselect"),
754
+ name: z5.string(),
755
+ label: z5.string(),
756
+ options: z5.array(OptionSchema),
757
+ allowOther: AllowOther.optional(),
758
+ min: z5.number().int().min(0).optional(),
759
+ max: z5.number().int().min(1).optional(),
760
+ showIf: ShowIfSchema.optional()
761
+ }),
762
+ z5.object({
763
+ kind: z5.literal("text"),
764
+ name: z5.string(),
765
+ label: z5.string(),
766
+ placeholder: z5.string().optional(),
767
+ multiline: z5.boolean().optional(),
768
+ prefill: z5.string().optional(),
769
+ showIf: ShowIfSchema.optional()
770
+ })
771
+ ]);
772
+ var RefSchema = z5.discriminatedUnion("kind", [
773
+ z5.object({ kind: z5.literal("file"), path: z5.string() }),
774
+ z5.object({ kind: z5.literal("session"), sessionId: z5.string() }),
775
+ z5.object({ kind: z5.literal("task"), taskId: z5.string() }),
776
+ z5.object({ kind: z5.literal("native_session"), hostId: z5.string(), sessionFile: z5.string() })
777
+ ]);
778
+ var UINodeSchema = z5.lazy(() => z5.discriminatedUnion("t", [
779
+ z5.object({ t: z5.literal("text"), text: z5.string(), tone: ToneSchema.optional() }),
780
+ z5.object({ t: z5.literal("markdown"), text: z5.string() }),
781
+ z5.object({ t: z5.literal("code"), text: z5.string(), lang: z5.string().optional() }),
782
+ z5.object({ t: z5.literal("diff"), patch: z5.string() }),
783
+ z5.object({
784
+ t: z5.literal("list"),
785
+ items: z5.array(UINodeSchema),
786
+ ordered: z5.boolean().optional()
787
+ }),
788
+ z5.object({
789
+ t: z5.literal("table"),
790
+ columns: z5.array(z5.string()),
791
+ rows: z5.array(z5.array(z5.string()))
792
+ }),
793
+ z5.object({
794
+ t: z5.literal("section"),
795
+ title: z5.string().optional(),
796
+ collapsible: z5.boolean().optional(),
797
+ children: z5.array(UINodeSchema)
798
+ }),
799
+ z5.object({
800
+ t: z5.literal("tabs"),
801
+ tabs: z5.array(z5.object({ id: z5.string(), label: z5.string(), children: z5.array(UINodeSchema) }))
802
+ }),
803
+ z5.object({
804
+ t: z5.literal("progress"),
805
+ label: z5.string(),
806
+ value: z5.number().min(0).max(1).optional(),
807
+ status: z5.enum(["running", "ok", "error"]).optional()
808
+ }),
809
+ z5.object({ t: z5.literal("ref"), ref: RefSchema, label: z5.string() }),
810
+ z5.object({
811
+ t: z5.literal("form"),
812
+ formId: z5.string(),
813
+ fields: z5.array(FieldSchema),
814
+ submitLabel: z5.string(),
815
+ cancelLabel: z5.string().optional()
816
+ }),
817
+ z5.object({
818
+ t: z5.literal("confirm"),
819
+ message: z5.string(),
820
+ confirmLabel: z5.string(),
821
+ cancelLabel: z5.string(),
822
+ destructive: z5.boolean().optional()
823
+ }),
824
+ z5.object({
825
+ t: z5.literal("actions"),
826
+ actions: z5.array(z5.object({
827
+ id: z5.string(),
828
+ label: z5.string(),
829
+ tone: z5.enum(["default", "primary", "danger"]).optional()
830
+ }))
831
+ })
832
+ ]));
833
+ var FormValueSchema = z5.union([
834
+ z5.string(),
835
+ z5.array(z5.string()),
836
+ z5.object({ other: z5.string() })
837
+ ]);
838
+ var InteractionResponseSchema = z5.discriminatedUnion("kind", [
839
+ z5.object({ kind: z5.literal("form"), values: z5.record(z5.string(), FormValueSchema) }),
840
+ z5.object({ kind: z5.literal("confirm"), confirmed: z5.boolean() }),
841
+ z5.object({ kind: z5.literal("action"), actionId: z5.string() }),
842
+ z5.object({ kind: z5.literal("cancel") })
843
+ ]);
844
+
845
+ // packages/protocol/dist/entities.js
846
+ var Iso = z6.string();
847
+ var Id4 = z6.string();
848
+ var Connectivity = z6.enum(["connected", "reconnecting", "unreachable"]);
849
+ var ControlMode = z6.enum(["automation", "human"]);
850
+ var Platform = z6.enum(["darwin", "linux"]);
851
+ var DeviceKind = z6.enum(["browser", "pwa", "terminal", "cli"]);
852
+ var DiagnosticLevel = z6.enum(["info", "warning", "error"]);
853
+ var DEFAULT_WORKTREE_DIR = ".worktrees";
854
+ var CoreCapabilities = z6.object({
855
+ prompt: z6.boolean(),
856
+ steer: z6.boolean(),
857
+ followUp: z6.boolean(),
858
+ abort: z6.boolean(),
859
+ resume: z6.boolean(),
860
+ rename: z6.boolean(),
861
+ importInactive: z6.boolean(),
862
+ extensionDialogs: z6.boolean(),
863
+ customUi: z6.boolean(),
864
+ widgetsText: z6.boolean(),
865
+ widgetsComponent: z6.boolean(),
866
+ tokenAccounting: z6.boolean(),
867
+ costAccounting: z6.boolean()
868
+ });
869
+ var CAPABILITY_KEYS = CoreCapabilities.keyof().options;
870
+ var RuntimeCapabilities = CoreCapabilities.extend({
871
+ /** The host runs sessions as interactive Pi in a terminal that clients can attach to. */
872
+ terminal: z6.boolean().optional(),
873
+ /** The host answers session.models, session.commands, session.setModel, session.setThinking and session.compact. */
874
+ sessionControls: z6.boolean().optional(),
875
+ /** The host answers session.navigate for terminal sessions. */
876
+ treeNavigation: z6.boolean().optional(),
877
+ agentRequests: z6.boolean().optional(),
878
+ messageDelivery: z6.boolean().optional(),
879
+ policies: z6.boolean().optional(),
880
+ unsupported: z6.array(z6.object({ capability: z6.string(), reason: z6.string() }))
881
+ });
882
+ var ProjectScan = z6.object({
883
+ state: z6.enum(["running", "done", "failed"]),
884
+ startedAt: Iso,
885
+ finishedAt: Iso.nullable(),
886
+ /** Repositories found across all folders. */
887
+ repositories: z6.number().int(),
888
+ /** New projects created by this scan. */
889
+ projectsCreated: z6.number().int(),
890
+ /** New checkouts (including the ones of new projects). */
891
+ checkoutsAdded: z6.number().int(),
892
+ /** "<folder>: <message>" per folder that failed; for state "failed", the reason last. */
893
+ errors: z6.array(z6.string())
894
+ });
895
+ var UsageWindow = z6.object({
896
+ id: z6.enum(["five_hour", "weekly"]),
897
+ usedPct: z6.number(),
898
+ resetsAt: Iso.nullable()
899
+ });
900
+ var ProviderUsage = z6.object({
901
+ provider: z6.enum(["anthropic", "openai-codex"]),
902
+ status: z6.enum(["available", "expired", "rejected", "error"]),
903
+ message: z6.string().nullable(),
904
+ windows: z6.array(UsageWindow),
905
+ fetchedAt: Iso
906
+ });
907
+ var Host = z6.object({
908
+ id: Id4,
909
+ name: z6.string(),
910
+ platform: Platform,
911
+ agentVersion: z6.string(),
912
+ piVersion: z6.string().nullable(),
913
+ piCompatible: z6.boolean(),
914
+ capabilities: RuntimeCapabilities.nullable(),
915
+ connectivity: Connectivity,
916
+ lastSeenAt: Iso.nullable(),
917
+ revokedAt: Iso.nullable(),
918
+ createdAt: Iso,
919
+ /** Folders on the host whose git repositories become projects (absolute or ~/...). */
920
+ projectFolders: z6.array(z6.string()).optional(),
921
+ projectScan: ProjectScan.nullable().optional(),
922
+ /** Subscription limits (host-reported, refreshed every few minutes). */
923
+ usage: z6.array(ProviderUsage).optional(),
924
+ github: HostGitHub.optional()
925
+ });
926
+ var WorktreeDir = z6.string().min(1).refine((d) => !d.startsWith("/") && !d.includes("\\"), "must be a relative path").refine((d) => !d.split("/").includes(".."), "must stay inside the repository").refine((d) => d.split("/").every((s) => s.length > 0 && s !== "."), "must be a plain relative path");
927
+ var Project = z6.object({
928
+ id: Id4,
929
+ name: z6.string().min(1),
930
+ repoIdentity: z6.string(),
931
+ defaultProfileId: Id4.nullable(),
932
+ defaultHostId: Id4.nullable(),
933
+ maxConcurrentRuns: z6.number().int().min(1).max(32),
934
+ automationEnabled: z6.boolean(),
935
+ setupCommand: z6.string().nullable(),
936
+ checks: z6.array(z6.string()),
937
+ workspaceSharing: z6.enum(["single_writer", "shared"]),
938
+ worktreeDir: WorktreeDir.default(DEFAULT_WORKTREE_DIR),
939
+ createdAt: Iso,
940
+ updatedAt: Iso
941
+ });
942
+ var Checkout = z6.object({
943
+ id: Id4,
944
+ projectId: Id4,
945
+ hostId: Id4,
946
+ path: z6.string(),
947
+ commonDir: z6.string(),
948
+ defaultBranch: z6.string(),
949
+ createdAt: Iso
950
+ });
951
+ var GitState = z6.object({
952
+ dirty: z6.boolean(),
953
+ changedFiles: z6.number().int(),
954
+ ahead: z6.number().int(),
955
+ behind: z6.number().int(),
956
+ unmerged: z6.boolean()
957
+ });
958
+ var Workspace = z6.object({
959
+ id: Id4,
960
+ checkoutId: Id4,
961
+ projectId: Id4,
962
+ hostId: Id4,
963
+ path: z6.string(),
964
+ branch: z6.string().nullable(),
965
+ baseBranch: z6.string().nullable(),
966
+ provenance: z6.enum(["managed", "discovered", "main"]),
967
+ git: GitState,
968
+ setup: z6.object({
969
+ state: z6.enum(["none", "running", "succeeded", "failed"]),
970
+ log: z6.string()
971
+ }),
972
+ archivedAt: Iso.nullable(),
973
+ updatedAt: Iso,
974
+ github: WorkspaceGitHub.optional()
975
+ });
976
+ var ThinkingLevel = z6.enum(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
977
+ var SessionModel = z6.object({
978
+ provider: z6.string(),
979
+ id: z6.string(),
980
+ name: z6.string().nullable(),
981
+ contextWindow: z6.number().nullable(),
982
+ reasoning: z6.boolean(),
983
+ /** In Pi's scoped (favorite) model list; set only when Pi has one. */
984
+ scoped: z6.boolean().optional(),
985
+ /** Effort levels this model accepts, in Pi's order; ["off"] without reasoning. */
986
+ thinkingLevels: z6.array(ThinkingLevel),
987
+ /** Prompt-cache lifetimes in seconds from Pi's model metadata. */
988
+ promptCache: z6.object({ short: z6.number().optional(), long: z6.number().optional() }).nullable().optional()
989
+ });
990
+ var SlashCommand = z6.object({
991
+ name: z6.string().min(1),
992
+ description: z6.string().nullable(),
993
+ source: z6.enum(["extension", "prompt", "skill"]),
994
+ argumentHint: z6.string().nullable().optional()
995
+ });
996
+ var ContextUsage = z6.object({
997
+ /** Estimated tokens in context; null right after compaction until the next reply. */
998
+ tokens: z6.number().nullable(),
999
+ window: z6.number(),
1000
+ percent: z6.number().nullable()
1001
+ });
1002
+ var FORBIDDEN_EXTRA_ARGS = ["--mode", "--fork", "--no-session", "-e", "--extension"];
1003
+ var ExtraArg = z6.string().refine((a) => a.startsWith("--") || !a.startsWith("-"), "extra args must be long flags").refine((a) => !FORBIDDEN_EXTRA_ARGS.includes(a.split("=")[0]) && !a.startsWith("--session"), "this flag is managed by Switchyard");
1004
+ var Profile = z6.object({
1005
+ id: Id4,
1006
+ name: z6.string().min(1),
1007
+ provider: z6.string().nullable(),
1008
+ model: z6.string().nullable(),
1009
+ thinking: ThinkingLevel.nullable(),
1010
+ projectTrust: z6.enum(["ask", "approve", "ignore"]),
1011
+ extraArgs: z6.array(ExtraArg),
1012
+ /** "vanilla": --no-extensions --no-skills --no-prompt-templates. Undefined means "all". */
1013
+ resources: z6.enum(["all", "vanilla"]).optional()
1014
+ });
1015
+ var ViewClient = z6.object({
1016
+ /** `${kind}:${name}@${machine}` */
1017
+ id: z6.string().min(1),
1018
+ kind: z6.enum(["herdr", "tmux"]),
1019
+ name: z6.string().min(1),
1020
+ machine: z6.string().min(1),
1021
+ lastSeenAt: Iso
1022
+ });
1023
+ var View = z6.object({
1024
+ id: Id4,
1025
+ name: z6.string().min(1).max(60),
1026
+ mode: z6.enum(["all", "pinned"]),
1027
+ projectIds: z6.array(z6.string()).nullable(),
1028
+ hostIds: z6.array(z6.string()).nullable(),
1029
+ sessionIds: z6.array(z6.string()),
1030
+ clients: z6.array(ViewClient),
1031
+ createdAt: Iso,
1032
+ updatedAt: Iso
1033
+ });
1034
+ var RuntimeState = z6.enum([
1035
+ "starting",
1036
+ "idle",
1037
+ "running",
1038
+ "waiting_input",
1039
+ "interrupted",
1040
+ "failed",
1041
+ "stopped"
1042
+ ]);
1043
+ var NativeHandle = z6.object({ sessionId: z6.string(), sessionFile: z6.string() });
1044
+ var SessionStats = z6.object({
1045
+ tokens: z6.number().nullable(),
1046
+ costUsd: z6.number().nullable(),
1047
+ /** Completed usage, refreshed for this exact settlement; absent on older hosts or failure. */
1048
+ watermark: CompletedUsageWatermark.optional(),
1049
+ context: ContextUsage.nullable().optional()
1050
+ });
1051
+ var PromptCacheInfo = z6.object({
1052
+ at: Iso,
1053
+ provider: z6.string(),
1054
+ model: z6.string(),
1055
+ cacheRead: z6.number(),
1056
+ cacheWrite: z6.number(),
1057
+ cacheWrite1h: z6.number()
1058
+ });
1059
+ var Session = z6.object({
1060
+ id: Id4,
1061
+ title: z6.string(),
1062
+ subtitle: z6.string().nullable(),
1063
+ hostId: Id4,
1064
+ workspaceId: Id4.nullable(),
1065
+ projectId: Id4.nullable(),
1066
+ cwd: z6.string(),
1067
+ nativeHandle: NativeHandle.nullable(),
1068
+ profileSnapshot: Profile,
1069
+ runtime: RuntimeState,
1070
+ runtimeDetail: z6.string().nullable(),
1071
+ connectivity: Connectivity,
1072
+ runId: Id4.nullable(),
1073
+ taskId: Id4.nullable(),
1074
+ provenance: z6.enum(["created", "imported", "subagent"]),
1075
+ readOnly: z6.boolean(),
1076
+ lastActivityAt: Iso,
1077
+ archivedAt: Iso.nullable(),
1078
+ queue: z6.object({ steering: z6.array(z6.string()), followUp: z6.array(z6.string()) }),
1079
+ stats: SessionStats.nullable(),
1080
+ /** The live model (host-owned; last known when stopped). */
1081
+ model: SessionModel.nullable().optional(),
1082
+ /** The live effort (Pi's thinking level). */
1083
+ thinking: ThinkingLevel.nullable().optional(),
1084
+ /** Pi is compacting the context. */
1085
+ compacting: z6.boolean().optional(),
1086
+ lastAssistantText: z6.string().nullable(),
1087
+ createdAt: Iso,
1088
+ /** A live terminal session: `switchyard tui` can attach to its Pi terminal. */
1089
+ terminal: z6.boolean().optional(),
1090
+ /** Set when the session finished or failed with nobody viewing it; cleared when viewed (coordinator-owned). */
1091
+ unreadSince: Iso.nullable().optional(),
1092
+ /** Bumped when the transcript is rebuilt (rewind); clients drop cached copies (coordinator-owned). */
1093
+ transcriptEpoch: z6.number().int().min(0).optional(),
1094
+ bridge: z6.object({
1095
+ version: z6.literal(1),
1096
+ runtimeId: Id4,
1097
+ nativeSessionId: Id4,
1098
+ /** Host-generated local-controller identity, not Pi's private binding credential. */
1099
+ controllerEpoch: Id4.optional(),
1100
+ agentTools: z6.boolean(),
1101
+ messageDelivery: z6.boolean(),
1102
+ policyState: z6.enum(["initializing", "active", "unsupported", "lost"]),
1103
+ policyPhases: z6.array(PolicyPhase)
1104
+ }).optional(),
1105
+ /** Last assistant message's cache usage (host-owned). */
1106
+ promptCache: PromptCacheInfo.nullable().optional(),
1107
+ /** Warn before the prompt cache expires; non-null means on (coordinator-owned). */
1108
+ cacheAlert: z6.object({ ttlSec: z6.number().int().min(60).max(86400).nullable(), warnedFor: Iso.nullable() }).nullable().optional()
1109
+ });
1110
+ var ContinuationPolicy = z6.discriminatedUnion("enabled", [
1111
+ z6.object({ enabled: z6.literal(false) }),
1112
+ z6.object({
1113
+ enabled: z6.literal(true),
1114
+ objective: z6.string().min(1),
1115
+ maxContinuations: z6.number().int().min(1).max(50),
1116
+ maxElapsedMinutes: z6.number().int().min(1).max(1440),
1117
+ maxTokens: z6.number().int().positive().nullable(),
1118
+ maxCostUsd: z6.number().positive().nullable()
1119
+ })
1120
+ ]);
1121
+ var CompletionPolicy = z6.object({
1122
+ checks: z6.array(z6.string()).nullable(),
1123
+ requireHumanReview: z6.boolean()
1124
+ });
1125
+ var WorkspacePolicy = z6.discriminatedUnion("mode", [
1126
+ z6.object({
1127
+ mode: z6.literal("new_worktree"),
1128
+ branch: z6.string().nullable(),
1129
+ base: z6.string().nullable()
1130
+ }),
1131
+ z6.object({ mode: z6.literal("existing"), workspaceId: Id4 })
1132
+ ]);
1133
+ var TaskPolicy = z6.object({
1134
+ hostId: Id4.nullable(),
1135
+ profileId: Id4.nullable(),
1136
+ workspace: WorkspacePolicy,
1137
+ continuation: ContinuationPolicy,
1138
+ completion: CompletionPolicy
1139
+ });
1140
+ var TaskState = z6.enum(["backlog", "ready", "in_progress", "review", "done", "canceled"]);
1141
+ var Priority = z6.union([z6.literal(0), z6.literal(1), z6.literal(2), z6.literal(3)]);
1142
+ var TaskOrigin = z6.discriminatedUnion("kind", [
1143
+ z6.object({ kind: z6.literal("manual") }),
1144
+ z6.object({
1145
+ kind: z6.literal("automation"),
1146
+ automationId: Id4,
1147
+ occurrenceId: Id4,
1148
+ routine: z6.boolean()
1149
+ })
1150
+ ]);
1151
+ var Task = z6.object({
1152
+ id: Id4,
1153
+ projectId: Id4,
1154
+ title: z6.string().min(1),
1155
+ objective: z6.string(),
1156
+ acceptanceCriteria: z6.array(z6.string()),
1157
+ dependencies: z6.array(Id4),
1158
+ priority: Priority,
1159
+ position: z6.number(),
1160
+ state: TaskState,
1161
+ blocked: z6.object({ reason: z6.string() }).nullable(),
1162
+ notBefore: Iso.nullable(),
1163
+ policy: TaskPolicy,
1164
+ origin: TaskOrigin,
1165
+ groupingKey: z6.string().nullable(),
1166
+ parentTaskId: Id4.nullable().optional(),
1167
+ agentOrigin: z6.object({ sessionId: Id4, toolCallId: Id4 }).optional(),
1168
+ githubIssue: GitHubIssue.optional(),
1169
+ currentRunId: Id4.nullable(),
1170
+ sessionId: Id4.nullable(),
1171
+ review: z6.object({ feedback: z6.array(z6.string()), changesRequested: z6.boolean() }),
1172
+ hiddenFromBoard: z6.boolean(),
1173
+ lastActivityAt: Iso,
1174
+ createdAt: Iso,
1175
+ updatedAt: Iso
1176
+ });
1177
+ var RunState = z6.enum([
1178
+ "queued",
1179
+ "dispatching",
1180
+ "uncertain",
1181
+ "running",
1182
+ "waiting_input",
1183
+ "checking",
1184
+ "succeeded",
1185
+ "failed",
1186
+ "interrupted",
1187
+ "canceled"
1188
+ ]);
1189
+ var CheckResult = z6.object({
1190
+ command: z6.string(),
1191
+ exitCode: z6.number().int().nullable(),
1192
+ outputTail: z6.string()
1193
+ });
1194
+ var Run = z6.object({
1195
+ id: Id4,
1196
+ taskId: Id4,
1197
+ sessionId: Id4.nullable(),
1198
+ hostId: Id4.nullable(),
1199
+ dispatchKey: z6.string(),
1200
+ attempt: z6.number().int().min(1),
1201
+ state: RunState,
1202
+ controlMode: ControlMode,
1203
+ controlRevision: z6.number().int().min(1),
1204
+ continuationsUsed: z6.number().int().min(0),
1205
+ infraRetries: z6.number().int().min(0),
1206
+ nextAttemptAt: Iso.nullable(),
1207
+ startedAt: Iso.nullable(),
1208
+ endedAt: Iso.nullable(),
1209
+ outcome: z6.object({
1210
+ kind: z6.enum(["review", "failed", "blocked", "no_change", "canceled"]),
1211
+ summary: z6.string()
1212
+ }).nullable(),
1213
+ limits: ContinuationPolicy,
1214
+ usage: z6.object({
1215
+ tokens: z6.number().nullable(),
1216
+ costUsd: z6.number().nullable(),
1217
+ accounting: z6.enum(["available", "unavailable"]),
1218
+ note: z6.string().nullable()
1219
+ }),
1220
+ checks: z6.array(CheckResult),
1221
+ createdAt: Iso,
1222
+ updatedAt: Iso
1223
+ });
1224
+ var Trigger = z6.discriminatedUnion("kind", [
1225
+ z6.object({ kind: z6.literal("manual") }),
1226
+ z6.object({ kind: z6.literal("once"), at: Iso }),
1227
+ z6.object({ kind: z6.literal("cron"), expr: z6.string().min(1), timezone: z6.string().min(1) }),
1228
+ z6.object({ kind: z6.literal("webhook") }),
1229
+ z6.object({ kind: z6.literal("dependency"), taskId: Id4 })
1230
+ ]);
1231
+ var TaskTemplate = z6.object({
1232
+ title: z6.string().min(1),
1233
+ objective: z6.string(),
1234
+ acceptanceCriteria: z6.array(z6.string()),
1235
+ priority: Priority
1236
+ });
1237
+ var Automation = z6.object({
1238
+ id: Id4,
1239
+ name: z6.string().min(1),
1240
+ enabled: z6.boolean(),
1241
+ projectId: Id4,
1242
+ trigger: Trigger,
1243
+ filters: z6.array(z6.object({ path: z6.string(), equals: z6.string() })),
1244
+ template: TaskTemplate,
1245
+ hostId: Id4.nullable(),
1246
+ profileId: Id4.nullable(),
1247
+ mode: z6.enum(["fresh", "continue", "watch"]),
1248
+ groupingKey: z6.string().nullable(),
1249
+ overlap: z6.enum(["skip", "queue_one", "append"]),
1250
+ missed: z6.enum(["skip", "run_once"]),
1251
+ continuation: ContinuationPolicy,
1252
+ completion: CompletionPolicy,
1253
+ nextAt: Iso.nullable(),
1254
+ lastEvaluatedAt: Iso.nullable(),
1255
+ lastOutcome: z6.string().nullable(),
1256
+ failureCount: z6.number().int().min(0),
1257
+ webhookTokenSet: z6.boolean(),
1258
+ createdAt: Iso,
1259
+ updatedAt: Iso
1260
+ });
1261
+ var OccurrenceState = z6.enum([
1262
+ "fired",
1263
+ "skipped_overlap",
1264
+ "skipped_missed",
1265
+ "queued",
1266
+ "appended",
1267
+ "failed",
1268
+ "filtered"
1269
+ ]);
1270
+ var Occurrence = z6.object({
1271
+ id: Id4,
1272
+ automationId: Id4,
1273
+ key: z6.string(),
1274
+ scheduledFor: Iso.nullable(),
1275
+ state: OccurrenceState,
1276
+ taskId: Id4.nullable(),
1277
+ reason: z6.string().nullable(),
1278
+ outcome: z6.string().nullable(),
1279
+ createdAt: Iso
1280
+ });
1281
+ var InteractionState = z6.preprocess((v) => v === "cancelled" ? "canceled" : v, z6.enum(["pending", "resolved", "expired", "canceled", "unsupported"]));
1282
+ var Interaction = z6.object({
1283
+ id: Id4,
1284
+ sessionId: Id4,
1285
+ revision: z6.number().int().min(1),
1286
+ source: z6.discriminatedUnion("kind", [
1287
+ z6.object({
1288
+ kind: z6.literal("extension_ui"),
1289
+ method: z6.enum(["select", "confirm", "input", "editor"]),
1290
+ piRequestIds: z6.array(z6.string())
1291
+ }),
1292
+ z6.object({ kind: z6.literal("unsupported_custom"), title: z6.string().nullable() })
1293
+ ]),
1294
+ adapterId: z6.string().nullable(),
1295
+ permission: PolicyPermission.optional(),
1296
+ title: z6.string(),
1297
+ presentation: UINodeSchema,
1298
+ state: InteractionState,
1299
+ resolution: z6.object({ by: z6.string(), summary: z6.string(), at: Iso }).nullable(),
1300
+ createdAt: Iso
1301
+ });
1302
+ var AttentionReason = z6.enum([
1303
+ "needs_input",
1304
+ "failed",
1305
+ "ready_for_review",
1306
+ "unsupported_interaction",
1307
+ "host_unreachable",
1308
+ "cache_expiring"
1309
+ ]);
1310
+ var AttentionItem = z6.object({
1311
+ id: Id4,
1312
+ sessionId: Id4.nullable(),
1313
+ taskId: Id4.nullable(),
1314
+ projectId: Id4.nullable(),
1315
+ reason: AttentionReason,
1316
+ severity: z6.enum(["info", "warning", "critical"]),
1317
+ summary: z6.string(),
1318
+ interactionId: Id4.nullable(),
1319
+ deepLink: z6.string(),
1320
+ acknowledgedAt: Iso.nullable(),
1321
+ resolvedAt: Iso.nullable(),
1322
+ createdAt: Iso
1323
+ });
1324
+ var Device = z6.object({
1325
+ id: Id4,
1326
+ name: z6.string(),
1327
+ kind: DeviceKind,
1328
+ createdAt: Iso,
1329
+ lastSeenAt: Iso.nullable(),
1330
+ revokedAt: Iso.nullable(),
1331
+ push: z6.object({
1332
+ subscribed: z6.boolean(),
1333
+ permission: z6.enum(["granted", "denied", "default", "unknown"])
1334
+ }),
1335
+ preferredMobile: z6.boolean(),
1336
+ enrolledVia: z6.enum(["enrollment", "passkey", "oidc", "admin", "approval"]).default("enrollment")
1337
+ });
1338
+ var ToolItemData = z6.object({
1339
+ toolCallId: z6.string(),
1340
+ name: z6.string(),
1341
+ status: z6.enum(["running", "ok", "error"]),
1342
+ args: z6.unknown(),
1343
+ summary: z6.string(),
1344
+ output: z6.string(),
1345
+ startedAt: Iso,
1346
+ durationMs: z6.number().nullable(),
1347
+ card: UINodeSchema.nullable(),
1348
+ adapterId: z6.string().nullable()
1349
+ });
1350
+ var TranscriptItem = z6.discriminatedUnion("kind", [
1351
+ z6.object({
1352
+ id: Id4,
1353
+ sessionId: Id4,
1354
+ order: z6.number().int(),
1355
+ at: Iso,
1356
+ kind: z6.literal("user"),
1357
+ data: z6.object({
1358
+ text: z6.string(),
1359
+ images: z6.number().int().optional(),
1360
+ /** Pi session entry id, for rewind and fork from this message. */
1361
+ entryId: z6.string().optional()
1362
+ })
1363
+ }),
1364
+ z6.object({
1365
+ id: Id4,
1366
+ sessionId: Id4,
1367
+ order: z6.number().int(),
1368
+ at: Iso,
1369
+ kind: z6.literal("assistant"),
1370
+ data: z6.object({ text: z6.string(), streaming: z6.boolean().optional() })
1371
+ }),
1372
+ z6.object({
1373
+ id: Id4,
1374
+ sessionId: Id4,
1375
+ order: z6.number().int(),
1376
+ at: Iso,
1377
+ kind: z6.literal("thinking"),
1378
+ data: z6.object({ text: z6.string() })
1379
+ }),
1380
+ z6.object({
1381
+ id: Id4,
1382
+ sessionId: Id4,
1383
+ order: z6.number().int(),
1384
+ at: Iso,
1385
+ kind: z6.literal("tool"),
1386
+ data: ToolItemData
1387
+ }),
1388
+ z6.object({
1389
+ id: Id4,
1390
+ sessionId: Id4,
1391
+ order: z6.number().int(),
1392
+ at: Iso,
1393
+ kind: z6.literal("notice"),
1394
+ data: z6.object({ level: DiagnosticLevel, text: z6.string() })
1395
+ }),
1396
+ z6.object({
1397
+ id: Id4,
1398
+ sessionId: Id4,
1399
+ order: z6.number().int(),
1400
+ at: Iso,
1401
+ kind: z6.literal("interaction"),
1402
+ data: z6.object({ interactionId: Id4 })
1403
+ }),
1404
+ z6.object({
1405
+ id: Id4,
1406
+ sessionId: Id4,
1407
+ order: z6.number().int(),
1408
+ at: Iso,
1409
+ kind: z6.literal("subagent"),
1410
+ data: z6.object({
1411
+ runId: z6.string(),
1412
+ label: z6.string(),
1413
+ status: z6.string(),
1414
+ sessionFile: z6.string().nullable(),
1415
+ linkedSessionId: Id4.nullable()
1416
+ })
1417
+ }),
1418
+ z6.object({
1419
+ id: Id4,
1420
+ sessionId: Id4,
1421
+ order: z6.number().int(),
1422
+ at: Iso,
1423
+ kind: z6.literal("system"),
1424
+ data: z6.object({ text: z6.string(), suggestion: z6.boolean().optional() })
1425
+ })
1426
+ ]);
1427
+ var Panel = z6.object({
1428
+ sessionId: Id4,
1429
+ adapterId: z6.string(),
1430
+ slot: z6.string(),
1431
+ title: z6.string(),
1432
+ node: UINodeSchema.nullable(),
1433
+ webRenderer: z6.boolean(),
1434
+ mobileFallback: z6.string().nullable(),
1435
+ updatedAt: Iso
1436
+ });
1437
+ var Diagnostic = z6.object({
1438
+ sessionId: Id4.nullable(),
1439
+ adapterId: z6.string().nullable(),
1440
+ level: DiagnosticLevel,
1441
+ message: z6.string(),
1442
+ at: Iso
1443
+ });
1444
+ var AdapterInfo = z6.object({
1445
+ id: z6.string(),
1446
+ version: z6.string(),
1447
+ tier: z6.enum(["project", "owner", "plugin", "bundled"]),
1448
+ target: z6.object({
1449
+ extension: z6.string(),
1450
+ versionRange: z6.string(),
1451
+ testedVersions: z6.array(z6.string())
1452
+ }),
1453
+ capabilities: z6.array(z6.string()),
1454
+ webRenderer: z6.boolean(),
1455
+ status: z6.enum(["active", "disabled", "error"]),
1456
+ detail: z6.string().nullable()
1457
+ });
1458
+ var Passkey = z6.object({
1459
+ id: z6.string(),
1460
+ name: z6.string(),
1461
+ createdAt: Iso,
1462
+ lastUsedAt: Iso.nullable(),
1463
+ transports: z6.array(z6.string())
1464
+ });
1465
+
1466
+ // packages/protocol/dist/host-wire.js
1467
+ import { z as z9 } from "zod";
1468
+
1469
+ // packages/protocol/dist/events.js
1470
+ import { z as z7 } from "zod";
1471
+ var EventDataSchemas = {
1472
+ "host.updated": Host,
1473
+ "project.updated": Project,
1474
+ "project.deleted": z7.object({ id: z7.string() }),
1475
+ "checkout.updated": Checkout,
1476
+ "workspace.updated": Workspace,
1477
+ "workspace.deleted": z7.object({ id: z7.string() }),
1478
+ "profile.updated": Profile,
1479
+ "profile.deleted": z7.object({ id: z7.string() }),
1480
+ "view.updated": View,
1481
+ "view.deleted": z7.object({ id: z7.string() }),
1482
+ "session.updated": Session,
1483
+ "transcript.item": TranscriptItem,
1484
+ "transcript.reset": z7.object({ sessionId: z7.string(), epoch: z7.number().int() }),
1485
+ "interaction.updated": Interaction,
1486
+ "panel.updated": Panel,
1487
+ "adapters.updated": z7.object({ hostId: z7.string(), adapters: z7.array(AdapterInfo) }),
1488
+ diagnostic: Diagnostic,
1489
+ "task.updated": Task,
1490
+ "task.deleted": z7.object({ id: z7.string() }),
1491
+ "run.updated": Run,
1492
+ "automation.updated": Automation,
1493
+ "automation.deleted": z7.object({ id: z7.string() }),
1494
+ "occurrence.created": Occurrence,
1495
+ "occurrence.updated": Occurrence,
1496
+ "attention.updated": AttentionItem,
1497
+ "device.updated": Device,
1498
+ "settings.updated": z7.object({ dispatchPaused: z7.boolean() })
1499
+ };
1500
+ var EVENT_TYPES = Object.keys(EventDataSchemas);
1501
+ var LEGACY_EVENT_TYPES = {
1502
+ "workspace.removed": "workspace.deleted"
1503
+ };
1504
+ function canonicalEventType(type) {
1505
+ return LEGACY_EVENT_TYPES[type] ?? type;
1506
+ }
1507
+ var canonical = (v) => typeof v === "string" ? canonicalEventType(v) : v;
1508
+ var EventTypeSchema = z7.preprocess(canonical, z7.enum(EVENT_TYPES));
1509
+ var EventScope = z7.object({
1510
+ hostId: z7.string().optional(),
1511
+ sessionId: z7.string().optional(),
1512
+ taskId: z7.string().optional(),
1513
+ projectId: z7.string().optional()
1514
+ });
1515
+ var EventEnvelope = EventScope.extend({
1516
+ seq: z7.number().int(),
1517
+ id: z7.string(),
1518
+ type: EventTypeSchema,
1519
+ at: z7.string(),
1520
+ data: z7.unknown()
1521
+ });
1522
+ var HOST_EVENT_TYPES = [
1523
+ "session.updated",
1524
+ "transcript.item",
1525
+ "interaction.updated",
1526
+ "panel.updated",
1527
+ "adapters.updated",
1528
+ "diagnostic",
1529
+ "workspace.updated",
1530
+ "workspace.deleted"
1531
+ ];
1532
+ var HostEvent = EventScope.extend({
1533
+ eventId: z7.string(),
1534
+ type: z7.preprocess(canonical, z7.enum(HOST_EVENT_TYPES)),
1535
+ at: z7.string(),
1536
+ data: z7.unknown()
1537
+ });
1538
+ var StreamDelta = z7.object({
1539
+ sessionId: z7.string(),
1540
+ itemId: z7.string(),
1541
+ kind: z7.enum(["text", "thinking", "tool_args", "tool_output"]),
1542
+ delta: z7.string(),
1543
+ order: z7.number().int().optional()
1544
+ });
1545
+
1546
+ // packages/protocol/dist/terminal-wire.js
1547
+ import { z as z8 } from "zod";
1548
+ var Cols = z8.number().int().min(10).max(1e3);
1549
+ var Rows = z8.number().int().min(5).max(500);
1550
+ var TermViewerToServer = z8.discriminatedUnion("t", [
1551
+ z8.object({ t: z8.literal("in"), d: z8.string() }),
1552
+ z8.object({ t: z8.literal("resize"), cols: Cols, rows: Rows }),
1553
+ z8.object({ t: z8.literal("claim") })
1554
+ ]);
1555
+ var TermServerToViewer = z8.discriminatedUnion("t", [
1556
+ z8.object({ t: z8.literal("out"), d: z8.string() }),
1557
+ z8.object({ t: z8.literal("closed"), reason: z8.string() }),
1558
+ z8.object({ t: z8.literal("size"), cols: Cols, rows: Rows, owner: z8.boolean() })
1559
+ ]);
1560
+ var TermCoordinatorMsg = z8.discriminatedUnion("t", [
1561
+ z8.object({
1562
+ t: z8.literal("open"),
1563
+ sessionId: z8.string(),
1564
+ cols: Cols,
1565
+ rows: Rows,
1566
+ passive: z8.boolean().optional()
1567
+ }),
1568
+ z8.object({ t: z8.literal("claim") }),
1569
+ z8.object({ t: z8.literal("in"), d: z8.string() }),
1570
+ z8.object({ t: z8.literal("resize"), cols: Cols, rows: Rows }),
1571
+ z8.object({ t: z8.literal("close") })
1572
+ ]);
1573
+
1574
+ // packages/protocol/dist/host-wire.js
1575
+ var Origin = z9.enum(["human", "automation"]);
1576
+ var HostCommand = z9.discriminatedUnion("type", [
1577
+ z9.object({
1578
+ type: z9.literal("session.start"),
1579
+ sessionId: z9.string(),
1580
+ title: z9.string(),
1581
+ workspacePath: z9.string(),
1582
+ projectId: z9.string().nullable(),
1583
+ profile: Profile,
1584
+ nativeHandle: NativeHandle.nullable(),
1585
+ initialPrompt: z9.string().nullable(),
1586
+ dispatchKey: z9.string().nullable(),
1587
+ controlRevision: z9.number().int(),
1588
+ controlMode: ControlMode,
1589
+ origin: Origin,
1590
+ readOnly: z9.boolean().default(false),
1591
+ policyRequired: z9.boolean().optional()
1592
+ }),
1593
+ z9.object({
1594
+ type: z9.literal("session.deliverMessage"),
1595
+ sessionId: z9.string(),
1596
+ messageId: z9.string(),
1597
+ payload: z9.object({
1598
+ deliveryId: z9.string(),
1599
+ kind: z9.enum(["message", "completion"]),
1600
+ text: z9.string()
1601
+ }),
1602
+ mode: z9.enum(["steer", "queue"]),
1603
+ holdUntil: z9.string()
1604
+ }),
1605
+ HostPolicySampleRequest.extend({ type: z9.literal("session.classifyPolicySample") }),
1606
+ z9.object({
1607
+ type: z9.literal("session.messageStatus"),
1608
+ sessionId: z9.string(),
1609
+ messageIds: z9.array(z9.string().min(1)).min(1).max(100)
1610
+ }),
1611
+ z9.object({
1612
+ type: z9.literal("session.prompt"),
1613
+ sessionId: z9.string(),
1614
+ text: z9.string(),
1615
+ images: z9.array(z9.object({ mimeType: z9.string(), data: z9.string() })).default([]),
1616
+ mode: z9.enum(["prompt", "steer", "followUp"]),
1617
+ origin: Origin,
1618
+ controlRevision: z9.number().int()
1619
+ }),
1620
+ z9.object({ type: z9.literal("session.abort"), sessionId: z9.string(), clearQueue: z9.boolean() }),
1621
+ z9.object({ type: z9.literal("session.stop"), sessionId: z9.string() }),
1622
+ z9.object({
1623
+ type: z9.literal("session.answer"),
1624
+ sessionId: z9.string(),
1625
+ interactionId: z9.string(),
1626
+ revision: z9.number().int(),
1627
+ response: InteractionResponseSchema,
1628
+ deviceId: z9.string()
1629
+ }),
1630
+ z9.object({
1631
+ type: z9.literal("session.adapterAction"),
1632
+ sessionId: z9.string(),
1633
+ adapterId: z9.string(),
1634
+ actionId: z9.string(),
1635
+ payload: z9.unknown()
1636
+ }),
1637
+ z9.object({
1638
+ type: z9.literal("session.setControl"),
1639
+ sessionId: z9.string(),
1640
+ controlRevision: z9.number().int(),
1641
+ mode: ControlMode
1642
+ }),
1643
+ z9.object({ type: z9.literal("session.rename"), sessionId: z9.string(), title: z9.string() }),
1644
+ z9.object({ type: z9.literal("session.importable") }),
1645
+ z9.object({ type: z9.literal("session.readNative"), sessionFile: z9.string() }),
1646
+ z9.object({ type: z9.literal("session.snapshot"), sessionId: z9.string() }),
1647
+ z9.object({ type: z9.literal("session.models"), sessionId: z9.string() }),
1648
+ z9.object({ type: z9.literal("session.commands"), sessionId: z9.string() }),
1649
+ z9.object({
1650
+ type: z9.literal("session.complete"),
1651
+ sessionId: z9.string(),
1652
+ text: z9.string().max(500)
1653
+ }),
1654
+ z9.object({ type: z9.literal("session.tree"), sessionId: z9.string() }),
1655
+ z9.object({
1656
+ type: z9.literal("session.branch"),
1657
+ sessionId: z9.string(),
1658
+ entryId: z9.string().nullable(),
1659
+ fork: z9.boolean()
1660
+ }),
1661
+ z9.object({
1662
+ type: z9.literal("session.navigate"),
1663
+ sessionId: z9.string(),
1664
+ entryId: z9.string(),
1665
+ summarize: z9.boolean(),
1666
+ instructions: z9.string().max(2e3).nullable()
1667
+ }),
1668
+ z9.object({ type: z9.literal("session.reload"), sessionId: z9.string() }),
1669
+ z9.object({ type: z9.literal("session.export"), sessionId: z9.string() }),
1670
+ z9.object({
1671
+ type: z9.literal("session.setModel"),
1672
+ sessionId: z9.string(),
1673
+ provider: z9.string().min(1),
1674
+ modelId: z9.string().min(1)
1675
+ }),
1676
+ z9.object({ type: z9.literal("session.setThinking"), sessionId: z9.string(), level: ThinkingLevel }),
1677
+ z9.object({
1678
+ type: z9.literal("session.compact"),
1679
+ sessionId: z9.string(),
1680
+ instructions: z9.string().nullable()
1681
+ }),
1682
+ z9.object({ type: z9.literal("checkout.inspect"), path: z9.string() }),
1683
+ z9.object({ type: z9.literal("projects.scan"), folder: z9.string().min(1) }),
1684
+ z9.object({
1685
+ type: z9.literal("projects.suggest"),
1686
+ days: z9.number().int().min(1).max(365).default(30)
1687
+ }),
1688
+ z9.object({
1689
+ type: z9.literal("workspace.discover"),
1690
+ checkoutPath: z9.string(),
1691
+ worktreeDir: z9.string().default(DEFAULT_WORKTREE_DIR)
1692
+ }),
1693
+ z9.object({
1694
+ type: z9.literal("workspace.create"),
1695
+ checkoutPath: z9.string(),
1696
+ branch: z9.string(),
1697
+ base: z9.string(),
1698
+ setupCommand: z9.string().nullable(),
1699
+ worktreeDir: z9.string().default(DEFAULT_WORKTREE_DIR)
1700
+ }),
1701
+ z9.object({ type: z9.literal("workspace.status"), path: z9.string(), base: z9.string().nullable() }),
1702
+ z9.object({
1703
+ type: z9.literal("workspace.remove"),
1704
+ path: z9.string(),
1705
+ checkoutPath: z9.string(),
1706
+ base: z9.string().nullable(),
1707
+ force: z9.object({ dirty: z9.boolean(), unmerged: z9.boolean() })
1708
+ }),
1709
+ z9.object({
1710
+ type: z9.literal("workspace.diff"),
1711
+ path: z9.string(),
1712
+ base: z9.string().nullable(),
1713
+ file: z9.string().nullable()
1714
+ }),
1715
+ z9.object({ type: z9.literal("workspace.files"), path: z9.string(), dir: z9.string() }),
1716
+ z9.object({ type: z9.literal("workspace.readFile"), path: z9.string(), file: z9.string() }),
1717
+ GitHubHostViewRequest.extend({ type: z9.literal("workspace.prView") }),
1718
+ GitHubHostLogsRequest.extend({ type: z9.literal("workspace.prFailedLogs") }),
1719
+ GitHubHostMergeRequest.extend({ type: z9.literal("workspace.prMerge") }),
1720
+ z9.object({
1721
+ type: z9.literal("dispatch.start"),
1722
+ dispatchKey: z9.string(),
1723
+ runId: z9.string(),
1724
+ taskId: z9.string(),
1725
+ sessionId: z9.string(),
1726
+ projectId: z9.string(),
1727
+ title: z9.string(),
1728
+ workspace: z9.union([
1729
+ z9.object({ path: z9.string() }),
1730
+ z9.object({
1731
+ createFrom: z9.object({
1732
+ checkoutPath: z9.string(),
1733
+ branch: z9.string(),
1734
+ base: z9.string(),
1735
+ setupCommand: z9.string().nullable(),
1736
+ worktreeDir: z9.string().default(DEFAULT_WORKTREE_DIR)
1737
+ })
1738
+ })
1739
+ ]),
1740
+ nativeHandle: NativeHandle.nullable(),
1741
+ profile: Profile,
1742
+ prompt: z9.string(),
1743
+ /** The launch's own revision; a takeover always carries a newer one. */
1744
+ controlRevision: z9.number().int(),
1745
+ controlMode: ControlMode.default("automation"),
1746
+ policyRequired: z9.boolean().optional()
1747
+ }),
1748
+ z9.object({ type: z9.literal("dispatch.reconcile"), dispatchKey: z9.string() }),
1749
+ z9.object({
1750
+ type: z9.literal("checks.run"),
1751
+ sessionId: z9.string(),
1752
+ path: z9.string(),
1753
+ commands: z9.array(z9.string())
1754
+ })
1755
+ ]);
1756
+ var ImportableSession = z9.object({
1757
+ sessionFile: z9.string(),
1758
+ sessionId: z9.string(),
1759
+ cwd: z9.string(),
1760
+ name: z9.string().nullable(),
1761
+ mtime: z9.string(),
1762
+ inactive: z9.boolean()
1763
+ });
1764
+ var DiscoveredWorktree = z9.object({
1765
+ path: z9.string(),
1766
+ head: z9.string().nullable(),
1767
+ branch: z9.string().nullable(),
1768
+ bare: z9.boolean(),
1769
+ detached: z9.boolean(),
1770
+ locked: z9.boolean(),
1771
+ prunable: z9.boolean(),
1772
+ provenance: z9.enum(["managed", "discovered", "main"]),
1773
+ git: GitState.nullable()
1774
+ });
1775
+ var CheckoutInfo = z9.object({
1776
+ root: z9.string(),
1777
+ commonDir: z9.string(),
1778
+ repoIdentity: z9.string(),
1779
+ defaultBranch: z9.string()
1780
+ });
1781
+ var ScannedRepository = CheckoutInfo.extend({ name: z9.string() });
1782
+ var ProjectFolderScan = z9.object({
1783
+ /** The folder, ~ expanded and realpath'd. */
1784
+ folder: z9.string(),
1785
+ repositories: z9.array(ScannedRepository)
1786
+ });
1787
+ var ProjectSuggestion = z9.object({
1788
+ rootPath: z9.string(),
1789
+ sessionCount: z9.number().int(),
1790
+ lastActivityAt: z9.string()
1791
+ });
1792
+ var ProjectSuggestions = z9.object({ suggestions: z9.array(ProjectSuggestion) });
1793
+ var DiffFile = z9.object({
1794
+ path: z9.string(),
1795
+ oldPath: z9.string().nullable(),
1796
+ added: z9.number().int(),
1797
+ deleted: z9.number().int(),
1798
+ status: z9.enum(["added", "modified", "deleted", "renamed", "untracked", "binary"])
1799
+ });
1800
+ var DiffResult = z9.object({
1801
+ base: z9.string(),
1802
+ files: z9.array(DiffFile),
1803
+ patch: z9.string().nullable()
1804
+ });
1805
+ var FileEntry = z9.object({
1806
+ name: z9.string(),
1807
+ path: z9.string(),
1808
+ kind: z9.enum(["file", "dir", "symlink"]),
1809
+ size: z9.number().int().nullable()
1810
+ });
1811
+ var ReconcileResult = z9.union([
1812
+ z9.object({ known: z9.literal(false) }),
1813
+ z9.object({
1814
+ known: z9.literal(true),
1815
+ sessionId: z9.string().nullable(),
1816
+ state: z9.enum(["accepted", "workspace_ready", "started", "failed"]),
1817
+ runtime: RuntimeState.nullable(),
1818
+ workspacePath: z9.string().nullable(),
1819
+ nativeHandle: NativeHandle.nullable(),
1820
+ error: z9.string().nullable(),
1821
+ /** `{started: "unknown"}` when the host restarted after Pi may have been spawned. */
1822
+ errorDetails: z9.record(z9.string(), z9.unknown()).nullable().default(null)
1823
+ })
1824
+ ]);
1825
+ var DispatchStartResult = z9.object({
1826
+ sessionId: z9.string(),
1827
+ workspacePath: z9.string(),
1828
+ nativeHandle: NativeHandle.nullable(),
1829
+ reused: z9.boolean(),
1830
+ /** Why the launch prompt was not delivered to Pi (the session itself started), if it was not. */
1831
+ promptError: z9.string().nullable().optional()
1832
+ });
1833
+ var AnswerResult = z9.object({
1834
+ status: z9.enum(["answered", "already_answered"]),
1835
+ interaction: Interaction
1836
+ });
1837
+ var SnapshotResult = z9.object({
1838
+ partial: z9.array(TranscriptItem),
1839
+ pendingInteractions: z9.array(Interaction)
1840
+ });
1841
+ var ChecksResult = z9.object({ results: z9.array(CheckResult) });
1842
+ var Receipt = z9.union([
1843
+ z9.object({ commandId: z9.string(), ok: z9.literal(true), result: z9.unknown() }),
1844
+ z9.object({ commandId: z9.string(), ok: z9.literal(false), error: ErrorBody })
1845
+ ]);
1846
+ var HostAgentRequestFrame = AgentRequestFrame.safeExtend({
1847
+ policyContext: HostToolPolicyContext.optional()
1848
+ }).strict().superRefine((frame, ctx) => {
1849
+ if (frame.method === "policy.evaluate" ? frame.policyContext === void 0 : Object.hasOwn(frame, "policyContext")) {
1850
+ ctx.addIssue({
1851
+ code: "custom",
1852
+ path: ["policyContext"],
1853
+ message: "Host policy context is required only for policy.evaluate."
1854
+ });
1855
+ }
1856
+ try {
1857
+ if (new TextEncoder().encode(JSON.stringify(frame)).length <= AGENT_FRAME_MAX_BYTES)
1858
+ return;
1859
+ } catch {
1860
+ }
1861
+ ctx.addIssue({ code: "custom", message: "Host agent frame exceeds 128 KiB or is not JSON." });
1862
+ });
1863
+ var HostToCoordinator = z9.discriminatedUnion("type", [
1864
+ z9.object({
1865
+ type: z9.literal("hello"),
1866
+ hostId: z9.string(),
1867
+ credential: z9.string(),
1868
+ name: z9.string(),
1869
+ agentVersion: z9.string(),
1870
+ piVersion: z9.string().nullable(),
1871
+ piCompatible: z9.boolean(),
1872
+ platform: Platform,
1873
+ capabilities: RuntimeCapabilities.nullable(),
1874
+ github: HostGitHub.optional(),
1875
+ protocolVersion: z9.number().int(),
1876
+ features: z9.array(z9.string()).optional()
1877
+ }),
1878
+ HostAgentRequestFrame,
1879
+ z9.object({ type: z9.literal("event"), hostSeq: z9.number().int(), event: HostEvent }),
1880
+ z9.object({ type: z9.literal("stream"), delta: StreamDelta }),
1881
+ z9.object({ type: z9.literal("receipt"), receipt: Receipt }),
1882
+ z9.object({ type: z9.literal("pong") }),
1883
+ z9.object({ type: z9.literal("usage"), usage: z9.array(ProviderUsage) }),
1884
+ z9.object({ type: z9.literal("term"), streamId: z9.string(), msg: TermServerToViewer })
1885
+ ]);
1886
+ var CoordinatorToHost = z9.discriminatedUnion("type", [
1887
+ z9.object({
1888
+ type: z9.literal("welcome"),
1889
+ coordinatorVersion: z9.string(),
1890
+ ackedHostSeq: z9.number().int(),
1891
+ features: z9.array(z9.string()).optional()
1892
+ }),
1893
+ AgentResultFrame,
1894
+ z9.object({ type: z9.literal("ack"), hostSeq: z9.number().int() }),
1895
+ z9.object({ type: z9.literal("command"), commandId: z9.string(), command: HostCommand }),
1896
+ z9.object({ type: z9.literal("ping") }),
1897
+ z9.object({ type: z9.literal("reject"), error: ErrorBody }),
1898
+ z9.object({ type: z9.literal("term"), streamId: z9.string(), msg: TermCoordinatorMsg })
1899
+ ]);
1900
+
1901
+ // packages/protocol/dist/api.js
1902
+ var EnrollRequest = z10.object({
1903
+ token: z10.string().min(1),
1904
+ name: z10.string().min(1).max(80),
1905
+ kind: DeviceKind
1906
+ });
1907
+ var EnrollResponse = z10.object({ deviceId: z10.string(), credential: z10.string() });
1908
+ var CreateEnrollmentRequest = z10.object({ kind: z10.enum(["device", "host"]) });
1909
+ var CreateEnrollmentResponse = z10.object({
1910
+ token: z10.string(),
1911
+ url: z10.string(),
1912
+ expiresAt: z10.string(),
1913
+ qrSvg: z10.string(),
1914
+ command: z10.string().nullable()
1915
+ });
1916
+ var HostEnrollRequest = z10.union([
1917
+ z10.object({
1918
+ token: z10.string().min(1),
1919
+ name: z10.string().min(1).max(80),
1920
+ platform: Platform
1921
+ }),
1922
+ z10.object({
1923
+ secret: z10.string().min(1),
1924
+ name: z10.string().min(1).max(80),
1925
+ platform: Platform
1926
+ })
1927
+ ]);
1928
+ var HostEnrollResponse = z10.object({ hostId: z10.string(), credential: z10.string() });
1929
+ var CreateProjectRequest = z10.object({
1930
+ name: z10.string().min(1),
1931
+ hostId: z10.string(),
1932
+ path: z10.string().min(1),
1933
+ defaultProfileId: z10.string().nullable().optional(),
1934
+ setupCommand: z10.string().nullable().optional(),
1935
+ checks: z10.array(z10.string()).optional(),
1936
+ maxConcurrentRuns: z10.number().int().min(1).max(32).optional(),
1937
+ worktreeDir: WorktreeDir.optional()
1938
+ });
1939
+ var UpdateProjectRequest = z10.object({
1940
+ name: z10.string().min(1).optional(),
1941
+ defaultProfileId: z10.string().nullable().optional(),
1942
+ defaultHostId: z10.string().nullable().optional(),
1943
+ maxConcurrentRuns: z10.number().int().min(1).max(32).optional(),
1944
+ automationEnabled: z10.boolean().optional(),
1945
+ setupCommand: z10.string().nullable().optional(),
1946
+ checks: z10.array(z10.string()).optional(),
1947
+ workspaceSharing: z10.enum(["single_writer", "shared"]).optional(),
1948
+ worktreeDir: WorktreeDir.optional()
1949
+ });
1950
+ var AddCheckoutRequest = z10.object({ hostId: z10.string(), path: z10.string().min(1) });
1951
+ function isProjectFolderPath(s) {
1952
+ if (s.includes("\0"))
1953
+ return false;
1954
+ return s === "~" || s.startsWith("~/") || s.startsWith("/");
1955
+ }
1956
+ var ProjectFolder = z10.string().trim().min(1).max(1024).refine(isProjectFolderPath, "must be an absolute path or start with ~/");
1957
+ var UpdateHostRequest = z10.object({
1958
+ projectFolders: z10.array(ProjectFolder).max(20).optional()
1959
+ });
1960
+ var ProjectScanResult = ProjectScan.extend({
1961
+ added: z10.array(z10.object({
1962
+ projectId: z10.string(),
1963
+ name: z10.string(),
1964
+ path: z10.string(),
1965
+ newProject: z10.boolean()
1966
+ }))
1967
+ });
1968
+ var ProfileInput = z10.object({
1969
+ name: z10.string().min(1),
1970
+ provider: z10.string().nullable().default(null),
1971
+ model: z10.string().nullable().default(null),
1972
+ thinking: ThinkingLevel.nullable().default(null),
1973
+ projectTrust: z10.enum(["ask", "approve", "ignore"]).default("ask"),
1974
+ extraArgs: z10.array(ExtraArg).default([]),
1975
+ resources: z10.enum(["all", "vanilla"]).default("all")
1976
+ });
1977
+ var CreateWorkspaceRequest = z10.object({
1978
+ checkoutId: z10.string(),
1979
+ branch: z10.string().min(1),
1980
+ base: z10.string().nullable().optional()
1981
+ });
1982
+ var RemoveWorkspaceRequest = z10.object({
1983
+ force: z10.object({ dirty: z10.boolean(), unmerged: z10.boolean() }).default({ dirty: false, unmerged: false })
1984
+ });
1985
+ var CreateSessionRequest = z10.object({
1986
+ projectId: z10.string(),
1987
+ workspace: z10.union([
1988
+ z10.object({ existingId: z10.string() }),
1989
+ z10.object({
1990
+ checkoutId: z10.string(),
1991
+ newBranch: z10.string().min(1),
1992
+ base: z10.string().nullable().optional()
1993
+ })
1994
+ ]),
1995
+ profileId: z10.string().nullable().optional(),
1996
+ prompt: z10.string().default(""),
1997
+ title: z10.string().optional(),
1998
+ viewId: z10.string().optional()
1999
+ });
2000
+ var PromptRequest = z10.object({
2001
+ text: z10.string().min(1),
2002
+ mode: z10.enum(["prompt", "steer", "followUp"]).default("prompt"),
2003
+ images: z10.array(z10.object({ mimeType: z10.string(), data: z10.string() })).default([]),
2004
+ clientMessageId: z10.string().optional()
2005
+ });
2006
+ var CacheAlertRequest = z10.object({
2007
+ enabled: z10.boolean(),
2008
+ ttlSec: z10.number().int().min(60).max(86400).nullable().default(null)
2009
+ });
2010
+ var RenameRequest = z10.object({ title: z10.string().min(1).max(200) });
2011
+ var SetModelRequest = z10.object({
2012
+ provider: z10.string().min(1),
2013
+ modelId: z10.string().min(1)
2014
+ });
2015
+ var SetThinkingRequest = z10.object({ level: ThinkingLevel });
2016
+ var CompactRequest = z10.object({ instructions: z10.string().max(4e3).optional() });
2017
+ var SessionModelsResult = z10.object({ models: z10.array(SessionModel) });
2018
+ var SessionCommandsResult = z10.object({ commands: z10.array(SlashCommand) });
2019
+ var CompleteRequest = z10.object({ text: z10.string().min(1).max(500) });
2020
+ var CompletionItem = z10.object({
2021
+ value: z10.string(),
2022
+ label: z10.string(),
2023
+ description: z10.string().nullable()
2024
+ });
2025
+ var SessionCompleteResult = z10.object({
2026
+ items: z10.array(CompletionItem).max(50),
2027
+ prefix: z10.string()
2028
+ });
2029
+ var TreeRow = z10.object({
2030
+ entryId: z10.string(),
2031
+ parentId: z10.string().nullable(),
2032
+ depth: z10.number().int(),
2033
+ role: z10.enum(["user", "assistant"]),
2034
+ text: z10.string(),
2035
+ activeBranch: z10.boolean(),
2036
+ leaf: z10.boolean(),
2037
+ label: z10.string().nullable(),
2038
+ at: z10.string().nullable()
2039
+ });
2040
+ var SessionTreeResult = z10.object({ rows: z10.array(TreeRow) });
2041
+ var BranchRequest = z10.object({
2042
+ entryId: z10.string().nullable(),
2043
+ fork: z10.boolean().default(false)
2044
+ });
2045
+ var HostBranchResult = z10.object({
2046
+ sessionFile: z10.string().nullable(),
2047
+ prefill: z10.string().nullable()
2048
+ });
2049
+ var TranscriptPage = z10.object({
2050
+ items: z10.array(TranscriptItem),
2051
+ hasMore: z10.boolean(),
2052
+ epoch: z10.number().int().optional(),
2053
+ rev: z10.number().int().optional(),
2054
+ delta: z10.boolean().optional(),
2055
+ reset: z10.boolean().optional()
2056
+ });
2057
+ var NavigateRequest = z10.object({
2058
+ entryId: z10.string().min(1),
2059
+ summarize: z10.boolean().default(false),
2060
+ instructions: z10.string().max(2e3).nullable().default(null)
2061
+ });
2062
+ var HostNavigateResult = z10.object({
2063
+ items: z10.array(TranscriptItem),
2064
+ prefill: z10.string().nullable()
2065
+ });
2066
+ var NavigateResult = z10.object({
2067
+ prefill: z10.string().nullable(),
2068
+ epoch: z10.number().int()
2069
+ });
2070
+ var BranchResult = z10.object({
2071
+ session: Session.nullable(),
2072
+ prefill: z10.string().nullable()
2073
+ });
2074
+ var SessionExportResult = z10.object({ fileName: z10.string(), content: z10.string() });
2075
+ var CommandViewAction = z10.object({
2076
+ label: z10.string().min(1).max(80),
2077
+ command: z10.string().startsWith("/").max(500),
2078
+ tone: z10.enum(["default", "primary", "danger"]).optional()
2079
+ });
2080
+ var CommandView = z10.object({
2081
+ title: z10.string().min(1).max(200),
2082
+ body: UINodeSchema,
2083
+ actions: z10.array(CommandViewAction).max(30).default([])
2084
+ });
2085
+ var ModelStateResult = z10.object({
2086
+ model: SessionModel.nullable(),
2087
+ thinking: ThinkingLevel.nullable()
2088
+ });
2089
+ var ImportSessionRequest = z10.object({
2090
+ hostId: z10.string(),
2091
+ sessionFile: z10.string(),
2092
+ projectId: z10.string().nullable().optional()
2093
+ });
2094
+ var AnswerRequest = z10.object({
2095
+ revision: z10.number().int(),
2096
+ response: InteractionResponseSchema
2097
+ });
2098
+ var AdapterActionRequest = z10.object({
2099
+ adapterId: z10.string(),
2100
+ actionId: z10.string(),
2101
+ payload: z10.unknown().optional()
2102
+ });
2103
+ var TaskPolicyPatch = z10.object({
2104
+ hostId: z10.string().nullable().optional(),
2105
+ profileId: z10.string().nullable().optional(),
2106
+ workspace: z10.object({
2107
+ mode: z10.enum(["new_worktree", "existing"]).optional(),
2108
+ branch: z10.string().nullable().optional(),
2109
+ base: z10.string().nullable().optional(),
2110
+ workspaceId: z10.string().optional()
2111
+ }).optional(),
2112
+ continuation: z10.object({
2113
+ enabled: z10.boolean().optional(),
2114
+ objective: z10.string().min(1).optional(),
2115
+ maxContinuations: z10.number().int().min(1).max(50).optional(),
2116
+ maxElapsedMinutes: z10.number().int().min(1).max(1440).optional(),
2117
+ maxTokens: z10.number().int().positive().nullable().optional(),
2118
+ maxCostUsd: z10.number().positive().nullable().optional()
2119
+ }).optional(),
2120
+ completion: CompletionPolicy.partial().optional()
2121
+ });
2122
+ var CreateTaskRequest = z10.object({
2123
+ projectId: z10.string(),
2124
+ title: z10.string().max(300).optional(),
2125
+ githubIssueUrl: GitHubIssueUrl.optional(),
2126
+ githubIssue: z10.never().optional(),
2127
+ launchPrompt: z10.never().optional(),
2128
+ objective: z10.string().default(""),
2129
+ acceptanceCriteria: z10.array(z10.string()).default([]),
2130
+ dependencies: z10.array(z10.string()).default([]),
2131
+ parentTaskId: z10.string().nullable().optional(),
2132
+ priority: Priority.default(2),
2133
+ state: z10.enum(["backlog", "ready"]).default("backlog"),
2134
+ notBefore: z10.string().nullable().optional(),
2135
+ policy: TaskPolicyPatch.optional()
2136
+ }).superRefine((v, ctx) => {
2137
+ if (v.githubIssueUrl === void 0) {
2138
+ if (v.title === void 0 || v.title.length === 0)
2139
+ ctx.addIssue({ code: "custom", path: ["title"], message: "Title is required." });
2140
+ return;
2141
+ }
2142
+ if (v.objective.trim())
2143
+ ctx.addIssue({
2144
+ code: "custom",
2145
+ path: ["objective"],
2146
+ message: "Issue imports use the issue as their initial objective; leave Objective empty."
2147
+ });
2148
+ if (v.acceptanceCriteria.length)
2149
+ ctx.addIssue({
2150
+ code: "custom",
2151
+ path: ["acceptanceCriteria"],
2152
+ message: "Issue imports read acceptance from the issue; leave acceptance criteria empty at creation."
2153
+ });
2154
+ if (v.policy?.continuation?.enabled === true)
2155
+ ctx.addIssue({
2156
+ code: "custom",
2157
+ path: ["policy", "continuation", "enabled"],
2158
+ message: "Issue imports start with continuation disabled."
2159
+ });
2160
+ if (v.policy?.completion?.requireHumanReview === false)
2161
+ ctx.addIssue({
2162
+ code: "custom",
2163
+ path: ["policy", "completion", "requireHumanReview"],
2164
+ message: "Issue imports require human review when created."
2165
+ });
2166
+ }).transform((v) => {
2167
+ if (v.githubIssueUrl === void 0)
2168
+ return { ...v, title: v.title };
2169
+ const issue = githubIssueFromUrl(v.githubIssueUrl);
2170
+ return { ...v, title: v.title?.trim() || `${issue.repository} #${issue.number}` };
2171
+ });
2172
+ var UpdateTaskRequest = z10.object({
2173
+ githubIssueUrl: z10.never().optional(),
2174
+ githubIssue: z10.never().optional(),
2175
+ launchPrompt: z10.never().optional(),
2176
+ title: z10.string().min(1).max(300).optional(),
2177
+ objective: z10.string().optional(),
2178
+ acceptanceCriteria: z10.array(z10.string()).optional(),
2179
+ dependencies: z10.array(z10.string()).optional(),
2180
+ parentTaskId: z10.string().nullable().optional(),
2181
+ priority: Priority.optional(),
2182
+ position: z10.number().optional(),
2183
+ notBefore: z10.string().nullable().optional(),
2184
+ policy: TaskPolicyPatch.optional()
2185
+ });
2186
+ var MoveTaskRequest = z10.object({
2187
+ to: TaskState,
2188
+ confirm: z10.boolean().optional(),
2189
+ onRunning: z10.enum(["pause", "stop"]).optional(),
2190
+ position: z10.number().optional()
2191
+ });
2192
+ var RequestChangesRequest = z10.object({ feedback: z10.array(z10.string().min(1)).min(1) });
2193
+ var Eligibility = z10.union([
2194
+ z10.object({ eligible: z10.literal(true), hostId: z10.string(), hostName: z10.string() }),
2195
+ z10.object({
2196
+ eligible: z10.literal(false),
2197
+ wait: z10.enum([
2198
+ "dependency",
2199
+ "host_offline",
2200
+ "project_limit",
2201
+ "workspace_occupied",
2202
+ "scheduled_time",
2203
+ "invalid_configuration",
2204
+ "dispatch_paused",
2205
+ "project_automation_disabled",
2206
+ "not_ready",
2207
+ "already_dispatched",
2208
+ "retry_backoff"
2209
+ ]),
2210
+ message: z10.string()
2211
+ })
2212
+ ]);
2213
+ var NowResponse = z10.object({
2214
+ running: z10.array(z10.object({ taskId: z10.string(), runId: z10.string(), sessionId: z10.string().nullable() })),
2215
+ queued: z10.array(z10.object({ taskId: z10.string(), eligibility: Eligibility })),
2216
+ dispatchPaused: z10.boolean()
2217
+ });
2218
+ var AutomationInput = z10.object({
2219
+ name: z10.string().min(1),
2220
+ enabled: z10.boolean().default(true),
2221
+ projectId: z10.string(),
2222
+ trigger: Trigger,
2223
+ filters: z10.array(z10.object({ path: z10.string(), equals: z10.string() })).default([]),
2224
+ template: TaskTemplate,
2225
+ hostId: z10.string().nullable().default(null),
2226
+ profileId: z10.string().nullable().default(null),
2227
+ mode: z10.enum(["fresh", "continue", "watch"]).default("fresh"),
2228
+ groupingKey: z10.string().nullable().default(null),
2229
+ overlap: z10.enum(["skip", "queue_one", "append"]).default("skip"),
2230
+ missed: z10.enum(["skip", "run_once"]).default("skip"),
2231
+ continuation: ContinuationPolicy.default({ enabled: false }),
2232
+ completion: CompletionPolicy.default({ checks: null, requireHumanReview: true })
2233
+ });
2234
+ var AutomationView = Automation.extend({ summary: z10.string() });
2235
+ var AutomationPreview = z10.object({
2236
+ summary: z10.string(),
2237
+ task: TaskTemplate,
2238
+ next: z10.array(z10.string())
2239
+ });
2240
+ var WebhookTokenResponse = z10.object({ token: z10.string(), url: z10.string() });
2241
+ var PushSubscriptionRequest = z10.object({
2242
+ endpoint: z10.string().url(),
2243
+ keys: z10.object({ p256dh: z10.string(), auth: z10.string() }),
2244
+ permission: z10.enum(["granted", "denied", "default", "unknown"]).default("granted")
2245
+ });
2246
+ var NotificationSettings = z10.object({
2247
+ quietHours: z10.object({
2248
+ start: z10.string().regex(/^\d{2}:\d{2}$/),
2249
+ end: z10.string().regex(/^\d{2}:\d{2}$/),
2250
+ timezone: z10.string()
2251
+ }).nullable(),
2252
+ privatePreviews: z10.boolean(),
2253
+ preferredDeviceId: z10.string().nullable()
2254
+ });
2255
+ var PushPayload = z10.union([
2256
+ z10.object({
2257
+ type: z10.literal("show"),
2258
+ title: z10.string(),
2259
+ body: z10.string(),
2260
+ tag: z10.string(),
2261
+ url: z10.string(),
2262
+ renotify: z10.boolean()
2263
+ }),
2264
+ z10.object({ type: z10.literal("clear"), tag: z10.string() })
2265
+ ]);
2266
+ var SetupState = z10.object({
2267
+ passkey: z10.object({
2268
+ available: z10.boolean(),
2269
+ registered: z10.boolean(),
2270
+ reason: z10.string().nullable()
2271
+ }),
2272
+ oidc: z10.object({ label: z10.string() }).nullable()
2273
+ });
2274
+ var PasskeyRegisterOptionsResponse = z10.object({
2275
+ challengeId: z10.string(),
2276
+ options: z10.unknown()
2277
+ });
2278
+ var PasskeyRegisterVerifyRequest = z10.object({
2279
+ challengeId: z10.string(),
2280
+ name: z10.string().min(1).max(80),
2281
+ response: z10.unknown()
2282
+ });
2283
+ var PasskeySignInOptionsResponse = z10.object({
2284
+ challengeId: z10.string(),
2285
+ options: z10.unknown()
2286
+ });
2287
+ var PasskeySignInVerifyRequest = z10.object({
2288
+ challengeId: z10.string(),
2289
+ response: z10.unknown(),
2290
+ deviceName: z10.string().min(1).max(80),
2291
+ kind: DeviceKind.extract(["browser", "pwa"])
2292
+ });
2293
+ var OidcBeginRequest = z10.object({
2294
+ deviceName: z10.string().min(1).max(80),
2295
+ kind: DeviceKind.extract(["browser", "pwa"]),
2296
+ next: z10.string().default("/"),
2297
+ handoff: z10.boolean().default(false)
2298
+ });
2299
+ var OidcBeginResponse = z10.object({
2300
+ authorizeUrl: z10.string(),
2301
+ flowId: z10.string().nullable(),
2302
+ pollToken: z10.string().nullable()
2303
+ });
2304
+ var OidcClaimRequest = z10.object({ flowId: z10.string(), pollToken: z10.string() });
2305
+ var OidcClaimResponse = z10.union([
2306
+ z10.object({ status: z10.literal("pending") }),
2307
+ z10.object({ status: z10.literal("done"), deviceId: z10.string() })
2308
+ ]);
2309
+ var TerminalLoginStartRequest = z10.object({ name: z10.string().min(1).max(80) });
2310
+ var TerminalLoginStartResponse = z10.object({
2311
+ userCode: z10.string(),
2312
+ pollToken: z10.string(),
2313
+ verifyUrl: z10.string(),
2314
+ expiresAt: z10.string(),
2315
+ intervalMs: z10.number().int()
2316
+ });
2317
+ var TerminalLoginClaimRequest = z10.object({
2318
+ userCode: z10.string().min(1),
2319
+ pollToken: z10.string().min(1)
2320
+ });
2321
+ var TerminalLoginClaimResponse = z10.union([
2322
+ z10.object({ status: z10.literal("pending") }),
2323
+ z10.object({ status: z10.literal("denied") }),
2324
+ z10.object({ status: z10.literal("done"), deviceId: z10.string(), credential: z10.string() })
2325
+ ]);
2326
+ var TerminalLoginRequest = z10.object({
2327
+ userCode: z10.string(),
2328
+ name: z10.string(),
2329
+ requestedFrom: z10.string(),
2330
+ createdAt: z10.string(),
2331
+ expiresAt: z10.string(),
2332
+ status: z10.enum(["pending", "approved", "denied"])
2333
+ });
2334
+ var AuthMethods = z10.object({
2335
+ passkeys: z10.array(Passkey),
2336
+ passkeyAvailability: z10.object({ available: z10.boolean(), reason: z10.string().nullable() }),
2337
+ oidc: z10.object({
2338
+ issuer: z10.string(),
2339
+ label: z10.string(),
2340
+ ownerMatch: z10.string(),
2341
+ status: z10.enum(["ready", "error"]),
2342
+ error: z10.string().nullable()
2343
+ }).nullable()
2344
+ });
2345
+ var MeResponse = z10.object({
2346
+ device: Device,
2347
+ admin: z10.boolean(),
2348
+ publicUrl: z10.string()
2349
+ });
2350
+ var ViewInput = View.pick({
2351
+ name: true,
2352
+ mode: true,
2353
+ projectIds: true,
2354
+ hostIds: true
2355
+ }).partial({
2356
+ mode: true,
2357
+ projectIds: true,
2358
+ hostIds: true
2359
+ });
2360
+ var ViewPatch = ViewInput.partial();
2361
+ var ViewClientReport = ViewClient.omit({ lastSeenAt: true });
2362
+ var ProjectSuggestionsResponse = z10.object({
2363
+ suggestions: z10.array(ProjectSuggestion.extend({ name: z10.string(), preselected: z10.boolean() }))
2364
+ });
2365
+
2366
+ // packages/protocol/dist/client-wire.js
2367
+ import { z as z11 } from "zod";
2368
+ var SyncState = z11.object({
2369
+ hosts: z11.array(Host),
2370
+ projects: z11.array(Project),
2371
+ checkouts: z11.array(Checkout),
2372
+ workspaces: z11.array(Workspace),
2373
+ profiles: z11.array(Profile),
2374
+ views: z11.array(View),
2375
+ sessions: z11.array(Session),
2376
+ tasks: z11.array(Task),
2377
+ runs: z11.array(Run),
2378
+ automations: z11.array(Automation),
2379
+ attention: z11.array(AttentionItem),
2380
+ interactions: z11.array(Interaction),
2381
+ panels: z11.array(Panel),
2382
+ devices: z11.array(Device),
2383
+ adapters: z11.record(z11.string(), z11.array(AdapterInfo)),
2384
+ dispatchPaused: z11.boolean()
2385
+ });
2386
+ var Presence = z11.object({
2387
+ foreground: z11.boolean(),
2388
+ interactedAt: z11.string().nullable(),
2389
+ viewing: z11.object({ sessionId: z11.string() }).nullable()
2390
+ });
2391
+ var ClientToServer = z11.discriminatedUnion("type", [
2392
+ z11.object({ type: z11.literal("hello"), cursor: z11.number().int().nullable() }),
2393
+ z11.object({ type: z11.literal("presence"), presence: Presence }),
2394
+ z11.object({ type: z11.literal("ping") })
2395
+ ]);
2396
+ var ServerToClient = z11.discriminatedUnion("type", [
2397
+ z11.object({
2398
+ type: z11.literal("replay"),
2399
+ seq: z11.number().int(),
2400
+ events: z11.array(EventEnvelope)
2401
+ }),
2402
+ z11.object({ type: z11.literal("snapshot"), seq: z11.number().int(), state: SyncState }),
2403
+ z11.object({ type: z11.literal("event"), event: EventEnvelope }),
2404
+ z11.object({ type: z11.literal("stream"), delta: StreamDelta }),
2405
+ z11.object({ type: z11.literal("pong") }),
2406
+ z11.object({ type: z11.literal("force_logout"), reason: z11.string() })
2407
+ ]);
2408
+
2409
+ // packages/protocol/dist/ids.js
2410
+ import { monotonicFactory } from "ulid";
2411
+ var ulid = monotonicFactory();
2412
+
2413
+ // packages/protocol/dist/views.js
2414
+ var CLIENT_OPEN_MS = 10 * 6e4;
2415
+
2416
+ // packages/protocol/dist/web-bridge.js
2417
+ import { z as z12 } from "zod";
2418
+ var FRAME_MAX_HEIGHT = 4e3;
2419
+ var FrameToParentMessageSchema = z12.discriminatedUnion("type", [
2420
+ z12.object({
2421
+ type: z12.literal("action"),
2422
+ actionId: z12.string().min(1).max(200),
2423
+ payload: z12.unknown().optional()
2424
+ }),
2425
+ z12.object({
2426
+ type: z12.literal("resize"),
2427
+ height: z12.number().finite().min(0).max(FRAME_MAX_HEIGHT)
2428
+ })
2429
+ ]);
2430
+
2431
+ // packages/coordinator/dist/policies/evaluator.js
2432
+ import { existsSync } from "node:fs";
2433
+ import { Worker } from "node:worker_threads";
2434
+ var PolicyEvaluatorError = class extends Error {
2435
+ failure;
2436
+ constructor(failure) {
2437
+ super(failure.message);
2438
+ this.failure = failure;
2439
+ this.name = "PolicyEvaluatorError";
2440
+ }
2441
+ };
2442
+ var forbidden2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
2443
+ var fail = (kind, message) => new PolicyEvaluatorError({ kind, message, range: null });
2444
+ function checkPolicyJson(value, maxBytes, context = false) {
2445
+ let bytes3 = 0;
2446
+ const ancestors = /* @__PURE__ */ new Set();
2447
+ const add = (n) => {
2448
+ bytes3 += n;
2449
+ if (bytes3 > maxBytes)
2450
+ throw fail("limit", "Policy input is too large to evaluate.");
2451
+ };
2452
+ const visit = (v, path2) => {
2453
+ if (path2.length > 20)
2454
+ throw fail("limit", "Policy input exceeds depth 20.");
2455
+ if (v === null || typeof v === "boolean")
2456
+ return add(v === null ? 4 : v ? 4 : 5);
2457
+ if (typeof v === "string")
2458
+ return add(Buffer.byteLength(JSON.stringify(v)));
2459
+ if (typeof v === "number") {
2460
+ const usd = context && path2.length === 2 && path2[0] === "cost" && (path2[1] === "costUsd" || path2[1] === "maxCostUsd");
2461
+ if (!Number.isFinite(v) || !usd && Number.isInteger(v) && !Number.isSafeInteger(v))
2462
+ throw fail("limit", "Policy numbers must be finite and integers must be safe.");
2463
+ return add(Buffer.byteLength(JSON.stringify(v)));
2464
+ }
2465
+ if (typeof v !== "object" || ancestors.has(v))
2466
+ throw fail("limit", "Policy input must be acyclic JSON.");
2467
+ const array = Array.isArray(v);
2468
+ if (Object.getPrototypeOf(v) !== (array ? Array.prototype : Object.prototype) && Object.getPrototypeOf(v) !== null)
2469
+ throw fail("limit", "Policy input must contain only plain JSON objects.");
2470
+ if (Object.getOwnPropertySymbols(v).length)
2471
+ throw fail("limit", "Policy input has symbol keys.");
2472
+ const keys = Object.getOwnPropertyNames(v).filter((k) => !array || k !== "length");
2473
+ if (array && (keys.length !== v.length || keys.some((k, i) => k !== String(i))))
2474
+ throw fail("limit", "Policy input must contain dense JSON arrays.");
2475
+ ancestors.add(v);
2476
+ add(2);
2477
+ for (const [i, key] of keys.entries()) {
2478
+ const descriptor = Object.getOwnPropertyDescriptor(v, key);
2479
+ if (forbidden2.has(key) || !descriptor.enumerable || !("value" in descriptor))
2480
+ throw fail("limit", "Policy input has a forbidden key or non-JSON property.");
2481
+ if (i)
2482
+ add(1);
2483
+ if (!array)
2484
+ add(Buffer.byteLength(JSON.stringify(key)) + 1);
2485
+ visit(descriptor.value, [...path2, key]);
2486
+ }
2487
+ ancestors.delete(v);
2488
+ };
2489
+ visit(value, []);
2490
+ return bytes3;
2491
+ }
2492
+ function workerUrl() {
2493
+ for (const path2 of ["./worker.js", "./policies/worker.js", "../../dist/policies/worker.js"]) {
2494
+ const url = new URL(path2, import.meta.url);
2495
+ if (existsSync(url))
2496
+ return url;
2497
+ }
2498
+ throw fail("worker", "Policy worker is missing. Build the coordinator before evaluating policies.");
2499
+ }
2500
+ var PolicyEvaluator = class {
2501
+ slots = [];
2502
+ queue = [];
2503
+ sequence = 0;
2504
+ closed = false;
2505
+ closing;
2506
+ terminations = /* @__PURE__ */ new Set();
2507
+ /** Parse and type-check off-thread. Does not evaluate the expression or change counters. */
2508
+ async validateRule(rule) {
2509
+ try {
2510
+ checkPolicyJson(rule, 2 * 1024 * 1024);
2511
+ return await this.submit({ type: "validate", rule });
2512
+ } catch (error) {
2513
+ return {
2514
+ valid: false,
2515
+ error: error instanceof PolicyEvaluatorError ? error.failure : {
2516
+ kind: "worker",
2517
+ message: "Policy validation failed.",
2518
+ range: null
2519
+ }
2520
+ };
2521
+ }
2522
+ }
2523
+ /** One result per supplied rule, in order. Inapplicable rules are no-match.
2524
+ * Rule state is isolated by id; pool/input failures return result:null,error for every rule.
2525
+ */
2526
+ async evaluateRules(rules, context, countersByRule) {
2527
+ if (!Array.isArray(rules) || Object.keys(rules).length !== rules.length)
2528
+ throw fail("limit", "Policy rules must be a dense JSON array.");
2529
+ const identities = Array.isArray(rules) ? Array.from({ length: rules.length }, (_, i) => {
2530
+ const rule = Object.getOwnPropertyDescriptor(rules, String(i))?.value;
2531
+ return {
2532
+ ruleId: rule && typeof rule === "object" ? Object.getOwnPropertyDescriptor(rule, "id")?.value : "",
2533
+ ruleRevision: rule && typeof rule === "object" ? Object.getOwnPropertyDescriptor(rule, "revision")?.value : 0
2534
+ };
2535
+ }) : [];
2536
+ try {
2537
+ const ruleBytes = checkPolicyJson(rules, 2 * 1024 * 1024);
2538
+ const contextBytes = checkPolicyJson(context, 65536, true);
2539
+ const counterBytes = checkPolicyJson(countersByRule, 2 * 1024 * 1024);
2540
+ if (!Array.isArray(rules) || rules.some((rule) => !rule || typeof rule !== "object") || !context || typeof context !== "object" || Array.isArray(context) || !countersByRule || typeof countersByRule !== "object" || Array.isArray(countersByRule))
2541
+ throw fail("limit", "Invalid policy evaluation input.");
2542
+ if (ruleBytes + contextBytes + counterBytes > 2 * 1024 * 1024)
2543
+ throw fail("limit", "Policy input is too large to evaluate.");
2544
+ if (rules.filter((rule) => rule.enabled).length > 128)
2545
+ throw fail("limit", "At most 128 enabled policy rules may be evaluated.");
2546
+ for (const rule of rules) {
2547
+ if (!rule.enabled)
2548
+ continue;
2549
+ const counters = Object.hasOwn(countersByRule, rule.id) ? countersByRule[rule.id] : {};
2550
+ checkPolicyJson({ ...context, counters }, 65536, true);
2551
+ }
2552
+ return await this.submit({
2553
+ type: "evaluate",
2554
+ rules,
2555
+ context,
2556
+ countersByRule
2557
+ });
2558
+ } catch (error) {
2559
+ const failure = error instanceof PolicyEvaluatorError ? error.failure : {
2560
+ kind: "worker",
2561
+ message: "Policy evaluator failed.",
2562
+ range: null
2563
+ };
2564
+ return identities.map((identity) => ({ ...identity, result: null, error: failure }));
2565
+ }
2566
+ }
2567
+ submit(input) {
2568
+ if (this.closed)
2569
+ return Promise.reject(fail("worker", "Policy evaluator is closed."));
2570
+ if (this.queue.length >= 256)
2571
+ return Promise.reject(fail("limit", "Policy evaluator queue is full."));
2572
+ const json = JSON.stringify(input);
2573
+ if (Buffer.byteLength(json) > 2 * 1024 * 1024)
2574
+ return Promise.reject(fail("limit", "Policy input is too large to evaluate."));
2575
+ return new Promise((resolve, reject) => {
2576
+ this.queue.push({ id: ++this.sequence, input: JSON.parse(json), resolve, reject });
2577
+ this.fill();
2578
+ });
2579
+ }
2580
+ fill() {
2581
+ if (this.closed)
2582
+ return;
2583
+ try {
2584
+ while (this.slots.length < 2)
2585
+ this.start();
2586
+ } catch (error) {
2587
+ this.rejectQueue(error instanceof PolicyEvaluatorError ? error : fail("worker", "Policy worker could not be started."));
2588
+ for (const slot of this.slots)
2589
+ if (slot.ready && !slot.job)
2590
+ slot.worker.unref();
2591
+ return;
2592
+ }
2593
+ for (const slot of this.slots) {
2594
+ if (!slot.ready || slot.job)
2595
+ continue;
2596
+ const job = this.queue.shift();
2597
+ if (!job) {
2598
+ slot.worker.unref();
2599
+ continue;
2600
+ }
2601
+ slot.job = job;
2602
+ slot.worker.ref();
2603
+ slot.timer = setTimeout(() => this.broken(slot, fail("timeout", "Policy evaluation exceeded 250 ms.")), 250);
2604
+ try {
2605
+ slot.worker.postMessage({ id: job.id, job: job.input });
2606
+ } catch {
2607
+ this.broken(slot, fail("worker", "Policy worker could not accept the job."));
2608
+ }
2609
+ }
2610
+ }
2611
+ start() {
2612
+ const worker = new Worker(workerUrl(), {
2613
+ execArgv: [],
2614
+ resourceLimits: { maxOldGenerationSizeMb: 64, stackSizeMb: 4 }
2615
+ });
2616
+ const slot = { worker, ready: false };
2617
+ this.slots.push(slot);
2618
+ slot.timer = setTimeout(() => this.broken(slot, fail("timeout", "Policy worker startup exceeded 5 seconds.")), 5e3);
2619
+ worker.on("message", (reply) => {
2620
+ if (!this.slots.includes(slot))
2621
+ return;
2622
+ if (reply.type === "ready" && !slot.ready) {
2623
+ clearTimeout(slot.timer);
2624
+ slot.ready = true;
2625
+ this.fill();
2626
+ } else if (slot.ready && slot.job && reply.type !== "ready" && reply.id === slot.job.id) {
2627
+ clearTimeout(slot.timer);
2628
+ const job = slot.job;
2629
+ slot.job = void 0;
2630
+ if (reply.type === "failure")
2631
+ job.reject(new PolicyEvaluatorError(reply.error));
2632
+ else
2633
+ job.resolve(reply.value);
2634
+ this.fill();
2635
+ } else
2636
+ this.broken(slot, fail("worker", "Invalid policy worker response."));
2637
+ });
2638
+ worker.on("error", () => this.broken(slot, fail("worker", "Policy worker failed or exceeded its resource limits.")));
2639
+ worker.on("exit", () => this.broken(slot, fail("worker", "Policy worker exited unexpectedly.")));
2640
+ }
2641
+ rejectQueue(error) {
2642
+ for (const job of this.queue.splice(0))
2643
+ job.reject(error);
2644
+ }
2645
+ broken(slot, error) {
2646
+ if (!this.slots.includes(slot))
2647
+ return;
2648
+ this.slots.splice(this.slots.indexOf(slot), 1);
2649
+ clearTimeout(slot.timer);
2650
+ slot.job?.reject(error);
2651
+ this.terminate(slot.worker);
2652
+ if (!slot.ready)
2653
+ this.rejectQueue(error);
2654
+ if (!this.closed && slot.ready)
2655
+ this.fill();
2656
+ }
2657
+ terminate(worker) {
2658
+ const pending = worker.terminate();
2659
+ this.terminations.add(pending);
2660
+ void pending.then(() => this.terminations.delete(pending), () => this.terminations.delete(pending));
2661
+ }
2662
+ close() {
2663
+ if (this.closing)
2664
+ return this.closing;
2665
+ this.closed = true;
2666
+ const error = fail("worker", "Policy evaluator is closed.");
2667
+ this.rejectQueue(error);
2668
+ for (const slot of this.slots.splice(0)) {
2669
+ clearTimeout(slot.timer);
2670
+ slot.job?.reject(error);
2671
+ this.terminate(slot.worker);
2672
+ }
2673
+ this.closing = Promise.all(this.terminations).then(() => void 0);
2674
+ return this.closing;
2675
+ }
2676
+ };
2677
+ var evaluator = new PolicyEvaluator();
2678
+
2679
+ // packages/coordinator/dist/policies/worker.js
2680
+ var env = new Environment({
2681
+ unlistedVariablesAreDyn: false,
2682
+ homogeneousAggregateLiterals: false,
2683
+ limits: {
2684
+ maxAstNodes: 2e3,
2685
+ maxDepth: 40,
2686
+ maxListElements: 100,
2687
+ maxMapEntries: 100,
2688
+ maxCallArguments: 16
2689
+ }
2690
+ });
2691
+ for (const name of [
2692
+ "phase",
2693
+ "action",
2694
+ "tool",
2695
+ "request",
2696
+ "session",
2697
+ "task",
2698
+ "target",
2699
+ "cost",
2700
+ "counters"
2701
+ ]) {
2702
+ env.registerVariable(name, name === "phase" || name === "action" ? "string" : name === "counters" ? "map<string, int>" : "dyn");
2703
+ }
2704
+ var cache = /* @__PURE__ */ new Map();
2705
+ function compile(rule) {
2706
+ const key = JSON.stringify([rule.id, rule.revision]);
2707
+ const cached = cache.get(key);
2708
+ if (cached) {
2709
+ if (cached.expression !== rule.expression)
2710
+ throw new PolicyEvaluatorError({
2711
+ kind: "type",
2712
+ message: "Policy expression changed without a new revision.",
2713
+ range: null
2714
+ });
2715
+ cache.delete(key);
2716
+ cache.set(key, cached);
2717
+ return cached;
2718
+ }
2719
+ let callable;
2720
+ try {
2721
+ callable = env.parse(rule.expression);
2722
+ } catch (error) {
2723
+ throw new PolicyEvaluatorError(diagnostic(error, "parse"));
2724
+ }
2725
+ checkMapKeys(callable.ast);
2726
+ const checked = callable.check();
2727
+ if (!checked.valid)
2728
+ throw new PolicyEvaluatorError(diagnostic(checked.error, "type"));
2729
+ const returnType = checked.type === "null" ? "null_type" : checked.type;
2730
+ if (returnType !== "null_type" && returnType !== "dyn" && returnType !== "map" && !returnType.startsWith("map<"))
2731
+ throw new PolicyEvaluatorError({
2732
+ kind: "type",
2733
+ message: "Policy expression must return null or a verdict map.",
2734
+ range: null
2735
+ });
2736
+ cache.set(key, { expression: rule.expression, callable, returnType });
2737
+ if (cache.size > 256)
2738
+ cache.delete(cache.keys().next().value);
2739
+ return { callable, returnType };
2740
+ }
2741
+ function checkMapKeys(node) {
2742
+ if (node.op === "map") {
2743
+ for (const [key] of node.args) {
2744
+ if (key.op === "value" && ["__proto__", "prototype", "constructor"].includes(String(key.args)))
2745
+ throw new PolicyEvaluatorError({
2746
+ kind: "type",
2747
+ message: "Policy maps contain a forbidden key.",
2748
+ range: key.range
2749
+ });
2750
+ }
2751
+ }
2752
+ const visit = (value) => {
2753
+ if (Array.isArray(value))
2754
+ value.forEach(visit);
2755
+ else if (value && typeof value === "object" && "op" in value && "args" in value)
2756
+ checkMapKeys(value);
2757
+ };
2758
+ visit(node.args);
2759
+ }
2760
+ function diagnostic(error, kind) {
2761
+ if (error instanceof PolicyEvaluatorError)
2762
+ return error.failure;
2763
+ const e = error;
2764
+ return {
2765
+ kind,
2766
+ message: (e?.message || "Policy evaluation failed.").slice(0, 4e3),
2767
+ range: e?.range ? { start: e.range.start, end: e.range.end } : null
2768
+ };
2769
+ }
2770
+ function toCel(value, path2 = []) {
2771
+ if (typeof value === "number") {
2772
+ const usd = path2.length === 2 && path2[0] === "cost" && (path2[1] === "costUsd" || path2[1] === "maxCostUsd");
2773
+ return Number.isInteger(value) && !usd ? BigInt(value) : value;
2774
+ }
2775
+ if (value === null || typeof value !== "object")
2776
+ return value;
2777
+ if (Array.isArray(value))
2778
+ return value.map((v, i) => toCel(v, [...path2, String(i)]));
2779
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toCel(v, [...path2, k])]));
2780
+ }
2781
+ function fromCel(value, depth = 0) {
2782
+ if (depth > 20)
2783
+ throw new Error("Policy result exceeds depth 20.");
2784
+ if (typeof value === "bigint") {
2785
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER))
2786
+ throw new Error("Policy result integer is outside the safe JSON range.");
2787
+ return Number(value);
2788
+ }
2789
+ if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number")
2790
+ return value;
2791
+ if (Array.isArray(value))
2792
+ return value.map((v) => fromCel(v, depth + 1));
2793
+ if (value instanceof Map) {
2794
+ if ([...value.keys()].some((key) => typeof key !== "string"))
2795
+ throw new Error("Policy result map keys must be strings.");
2796
+ return Object.fromEntries([...value].map(([key, v]) => [key, fromCel(v, depth + 1)]));
2797
+ }
2798
+ if (typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
2799
+ throw new Error("Policy result must be JSON.");
2800
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, fromCel(v, depth + 1)]));
2801
+ }
2802
+ function evaluate(job) {
2803
+ checkPolicyJson(job.rules, 2 * 1024 * 1024);
2804
+ checkPolicyJson(job.context, 65536, true);
2805
+ checkPolicyJson(job.countersByRule, 2 * 1024 * 1024);
2806
+ if (Buffer.byteLength(JSON.stringify(job)) > 2 * 1024 * 1024)
2807
+ throw new PolicyEvaluatorError({
2808
+ kind: "limit",
2809
+ message: "Policy input is too large to evaluate.",
2810
+ range: null
2811
+ });
2812
+ const rules = job.rules.map((r) => PolicyRule.parse(r));
2813
+ if (rules.filter((r) => r.enabled).length > 128)
2814
+ throw new Error("At most 128 enabled policy rules may be evaluated.");
2815
+ PolicyContext.parse({ ...job.context, counters: {} });
2816
+ return rules.map((rule) => {
2817
+ const identity = { ruleId: rule.id, ruleRevision: rule.revision };
2818
+ if (!rule.enabled || !rule.phases.includes(job.context.phase))
2819
+ return { ...identity, result: null, error: null };
2820
+ try {
2821
+ const counters = PolicyCounterMap.parse(Object.hasOwn(job.countersByRule, rule.id) ? job.countersByRule[rule.id] : {});
2822
+ const input = { ...job.context, counters };
2823
+ checkPolicyJson(input, 65536, true);
2824
+ const context = PolicyContext.parse(input);
2825
+ const { callable } = compile(rule);
2826
+ let raw;
2827
+ try {
2828
+ raw = callable(toCel(context));
2829
+ } catch (error) {
2830
+ throw new PolicyEvaluatorError(diagnostic(error, "runtime"));
2831
+ }
2832
+ try {
2833
+ if (raw && typeof raw === "object" && "state_updates" in raw) {
2834
+ const updates = raw.state_updates;
2835
+ if (!updates || typeof updates !== "object" || Array.isArray(updates) || (updates instanceof Map ? [...updates.values()] : Object.values(updates)).some((v) => typeof v !== "bigint"))
2836
+ throw new Error("Policy state_updates must be a map of CEL int values.");
2837
+ }
2838
+ const result = fromCel(raw);
2839
+ checkPolicyJson(result, 65536);
2840
+ const parsed = PolicyRuleResult.parse(result);
2841
+ if (parsed?.state_updates)
2842
+ PolicyCounterMap.parse({ ...counters, ...parsed.state_updates });
2843
+ return { ...identity, result: parsed, error: null };
2844
+ } catch (error) {
2845
+ throw new PolicyEvaluatorError(diagnostic(error, "runtime"));
2846
+ }
2847
+ } catch (error) {
2848
+ return { ...identity, result: null, error: diagnostic(error, "type") };
2849
+ }
2850
+ });
2851
+ }
2852
+ if (parentPort) {
2853
+ const port = parentPort;
2854
+ port.on("message", ({ id, job }) => {
2855
+ let reply;
2856
+ try {
2857
+ if (job.type === "validate") {
2858
+ try {
2859
+ checkPolicyJson(job.rule, 2 * 1024 * 1024);
2860
+ const { returnType } = compile(PolicyRule.parse(job.rule));
2861
+ reply = { type: "result", id, value: { valid: true, returnType } };
2862
+ } catch (error) {
2863
+ reply = {
2864
+ type: "result",
2865
+ id,
2866
+ value: { valid: false, error: diagnostic(error, "type") }
2867
+ };
2868
+ }
2869
+ } else
2870
+ reply = { type: "result", id, value: evaluate(job) };
2871
+ } catch (error) {
2872
+ reply = { type: "failure", id, error: diagnostic(error, "type") };
2873
+ }
2874
+ port.postMessage(reply);
2875
+ });
2876
+ port.postMessage({ type: "ready" });
2877
+ }