@bobannomi/app-host 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1822 @@
1
+ // ../domain-contracts/src/app-host/app-types.ts
2
+ var APP_HOST_ERROR_RETRY = {
3
+ incompatible: "never",
4
+ permission_denied: "never",
5
+ origin_denied: "never",
6
+ connection_revoked: "safe",
7
+ storage_full: "never",
8
+ invalid_request: "never",
9
+ host_unavailable: "never",
10
+ dependency_missing: "never",
11
+ service_start_failed: "safe",
12
+ service_unavailable: "safe",
13
+ activity_conflict: "query",
14
+ result_unknown: "query",
15
+ resource_unavailable: "never",
16
+ missing_source_evidence: "never",
17
+ control_conflict: "query",
18
+ configuration_changed: "query",
19
+ root_changed: "never",
20
+ resource_revision_conflict: "query",
21
+ request_conflict: "never",
22
+ cursor_stale: "query"
23
+ };
24
+ var HOST_REQUEST_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
25
+ function isSafeErrorDetails(value, depth = 0) {
26
+ if (depth > 8) return false;
27
+ if (value === null || typeof value === "boolean") return true;
28
+ if (typeof value === "number") return Number.isFinite(value);
29
+ if (typeof value === "string") return value.length <= 128 && /^[a-zA-Z0-9_. -]*$/.test(value);
30
+ if (typeof value !== "object" || value === null) return false;
31
+ if (Array.isArray(value)) return value.length <= 64 && Reflect.ownKeys(value).length === value.length + 1 && value.every((item) => isSafeErrorDetails(item, depth + 1));
32
+ if (![Object.prototype, null].includes(Object.getPrototypeOf(value))) return false;
33
+ const entries = Reflect.ownKeys(value);
34
+ return entries.length <= 32 && entries.every((key) => {
35
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
36
+ return typeof key === "string" && ["state", "reason", "capability", "dependency", "count", "limit", "retryAfterMs", "available"].includes(key) && descriptor.enumerable && Object.hasOwn(descriptor, "value") && isSafeErrorDetails(descriptor.value, depth + 1);
37
+ });
38
+ }
39
+ function isAppHostErrorInfo(value) {
40
+ if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return false;
41
+ const keys = Reflect.ownKeys(value);
42
+ if (!keys.every((key) => typeof key === "string" && ["code", "message", "retry", "requestId", "details"].includes(key) && Object.hasOwn(Object.getOwnPropertyDescriptor(value, key), "value"))) return false;
43
+ const error = value;
44
+ return Object.hasOwn(APP_HOST_ERROR_RETRY, error.code) && typeof error.message === "string" && (!Object.hasOwn(error, "retry") || error.retry === APP_HOST_ERROR_RETRY[error.code]) && (!Object.hasOwn(error, "requestId") || typeof error.requestId === "string" && HOST_REQUEST_ID.test(error.requestId)) && (!Object.hasOwn(error, "details") || isSafeErrorDetails(error.details));
45
+ }
46
+ function appHostErrorMessage(code, details) {
47
+ const reason = details && typeof details === "object" && !Array.isArray(details) ? details.reason : void 0;
48
+ if (code === "host_unavailable") {
49
+ switch (reason) {
50
+ case "host_port_timeout":
51
+ return "Timed out connecting to the desktop host.";
52
+ case "host_response_timeout":
53
+ return "The desktop host did not respond in time.";
54
+ case "host_invalid_response":
55
+ return "The desktop host returned an invalid response.";
56
+ case "host_send_failed":
57
+ return "The request could not be sent to the desktop host.";
58
+ case "host_initialization_failed":
59
+ return "The desktop host could not initialize services for this page.";
60
+ case "host_rebind_failed":
61
+ return "The desktop host could not reconnect services for this page.";
62
+ case "host_access_check_failed":
63
+ return "The desktop host could not verify access for this page.";
64
+ default:
65
+ return "The desktop host could not complete the operation.";
66
+ }
67
+ }
68
+ if (code === "resource_unavailable") {
69
+ switch (reason) {
70
+ case "browser_binding_invalid":
71
+ return "The browser tab is no longer linked to this page.";
72
+ case "browser_target_invalid":
73
+ return "The browser target is no longer available to this page.";
74
+ case "file_not_found":
75
+ return "The requested file could not be found.";
76
+ case "desktop_target_unavailable":
77
+ return "The desktop tool target is no longer available to this page.";
78
+ case "desktop_root_required":
79
+ return "This desktop tool requires a working directory.";
80
+ case "desktop_root_not_directory":
81
+ return "The desktop tool's working path is not a directory.";
82
+ default:
83
+ return "The requested resource is missing or unavailable to this connection.";
84
+ }
85
+ }
86
+ return code;
87
+ }
88
+ var AppHostError = class extends Error {
89
+ constructor(code, message = code, options = {}) {
90
+ super(message);
91
+ this.code = code;
92
+ if (!isAppHostErrorInfo({ code, message, ...options })) throw new TypeError("Invalid app host error");
93
+ this.name = "AppHostError";
94
+ this.retry = APP_HOST_ERROR_RETRY[code];
95
+ this.requestId = options.requestId;
96
+ this.details = options.details === void 0 ? void 0 : structuredClone(options.details);
97
+ }
98
+ code;
99
+ retry;
100
+ requestId;
101
+ details;
102
+ };
103
+
104
+ // ../domain-contracts/src/app-host/wire-validation.ts
105
+ var text = (max = 1024, empty2 = false) => (v) => typeof v === "string" && (empty2 || v.length > 0) && new TextEncoder().encode(v).byteLength <= max;
106
+ var id = (v) => typeof v === "string" && HOST_REQUEST_ID.test(v);
107
+ var count = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
108
+ var bool = (v) => typeof v === "boolean";
109
+ var enumeration = (...values) => (v) => values.includes(v);
110
+ var nullable = (check) => (v) => v === null || check(v);
111
+ function object(required, optional = {}) {
112
+ return (v) => {
113
+ if (!v || typeof v !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
114
+ if (Object.keys(required).some((k) => !Object.hasOwn(v, k))) return false;
115
+ return Reflect.ownKeys(v).every((k) => {
116
+ const d = Object.getOwnPropertyDescriptor(v, k);
117
+ return typeof k === "string" && d.enumerable && Object.hasOwn(d, "value") && (required[k] ?? optional[k])?.(d.value) === true;
118
+ });
119
+ };
120
+ }
121
+ function array(check, max = 1024) {
122
+ return (v) => {
123
+ if (!Array.isArray(v) || Object.getPrototypeOf(v) !== Array.prototype || v.length > max || Reflect.ownKeys(v).length !== v.length + 1) return false;
124
+ for (let i = 0; i < v.length; i++) {
125
+ const d = Object.getOwnPropertyDescriptor(v, String(i));
126
+ if (!d?.enumerable || !Object.hasOwn(d, "value") || !check(d.value)) return false;
127
+ }
128
+ return true;
129
+ };
130
+ }
131
+ var json = (value) => {
132
+ let size = 0;
133
+ const seen = /* @__PURE__ */ new Set();
134
+ const visit = (v, depth) => {
135
+ if (depth > 64 || size > 12 * 1024 * 1024) return false;
136
+ if (v === null || typeof v === "boolean") {
137
+ size += 5;
138
+ return true;
139
+ }
140
+ if (typeof v === "string") {
141
+ size += new TextEncoder().encode(v).byteLength + 2;
142
+ return size <= 12 * 1024 * 1024;
143
+ }
144
+ if (typeof v === "number") {
145
+ size += 32;
146
+ return Number.isFinite(v);
147
+ }
148
+ if (!v || typeof v !== "object" || seen.has(v)) return false;
149
+ const list = Array.isArray(v);
150
+ if (list ? Object.getPrototypeOf(v) !== Array.prototype : ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
151
+ seen.add(v);
152
+ try {
153
+ const keys = Reflect.ownKeys(v);
154
+ if (list && keys.length !== v.length + 1) return false;
155
+ return keys.every((k) => {
156
+ if (list && k === "length") return true;
157
+ const d = Object.getOwnPropertyDescriptor(v, k);
158
+ size += typeof k === "string" ? k.length + 3 : 0;
159
+ return typeof k === "string" && d.enumerable && Object.hasOwn(d, "value") && (!list || /^(0|[1-9][0-9]*)$/.test(k) && Number(k) < v.length) && visit(d.value, depth + 1);
160
+ });
161
+ } finally {
162
+ seen.delete(v);
163
+ }
164
+ };
165
+ return visit(value, 0) && size <= 12 * 1024 * 1024;
166
+ };
167
+ var jsonObject = (v) => !!v && typeof v === "object" && !Array.isArray(v) && json(v);
168
+ var digest = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
169
+ var wireConnection = object({ connectionId: text(256), baseUrl: text(2048) });
170
+ function validConnection(v) {
171
+ return wireConnection(v) && /^[A-Za-z0-9-]+$/.test(v.connectionId) && v.baseUrl === `https://app-host.invalid/connections/${v.connectionId}`;
172
+ }
173
+
174
+ // ../domain-contracts/src/app-host/agent.ts
175
+ function fields(value, required, optional = []) {
176
+ if (!value || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
177
+ return false;
178
+ return required.every((key) => Object.hasOwn(value, key)) && Reflect.ownKeys(value).every((key) => {
179
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
180
+ return typeof key === "string" && [...required, ...optional].includes(key) && descriptor.enumerable && Object.hasOwn(descriptor, "value");
181
+ });
182
+ }
183
+ var text2 = (value) => typeof value === "string" && value.trim().length > 0;
184
+ var workspaceId = (value) => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
185
+ function rows(value, check) {
186
+ return Array.isArray(value) && value.length <= 1024 && value.every(check);
187
+ }
188
+ function validAgentInput(method, value) {
189
+ if (!json(value)) return false;
190
+ if (method === "agent.listModels") return fields(value, []);
191
+ if (method === "agent.resolveSkills") return fields(value, ["skillIds"]) && Array.isArray(value.skillIds) && value.skillIds.length <= 128 && value.skillIds.every((v) => text(256)(v)) && new Set(value.skillIds).size === value.skillIds.length;
192
+ if (method !== "agent.getConnection" || !fields(value, [], ["workspaceId", "executionRoot", "privateSessionId"])) return false;
193
+ return (!Object.hasOwn(value, "workspaceId") || workspaceId(value.workspaceId)) && (!Object.hasOwn(value, "privateSessionId") || workspaceId(value.privateSessionId) && !Object.hasOwn(value, "workspaceId") && !Object.hasOwn(value, "executionRoot")) && (!Object.hasOwn(value, "executionRoot") || workspaceId(value.executionRoot) && Object.hasOwn(value, "workspaceId"));
194
+ }
195
+ function validAgentResult(method, value) {
196
+ if (!json(value)) return false;
197
+ switch (method) {
198
+ case "agent.getConnection":
199
+ return fields(value, ["connectionId", "baseUrl"], ["cwd", "defaultTaskLocation"]) && (!Object.hasOwn(value, "defaultTaskLocation") || value.defaultTaskLocation === "current" || value.defaultTaskLocation === "worktree") && (!Object.hasOwn(value, "cwd") || text2(value.cwd)) && text2(value.connectionId) && value.baseUrl === `https://app-host.invalid/connections/${value.connectionId}` && /^[A-Za-z0-9-]+$/.test(value.connectionId);
200
+ case "agent.listModels":
201
+ return rows(
202
+ value,
203
+ (row) => fields(row, ["id", "name"], ["reasoning", "reasoningEfforts", "vision", "contextWindow", "outputLimit", "inputModalities", "toolCalling"]) && text2(row.id) && text2(row.name) && ["reasoning", "vision", "toolCalling"].every((key) => !Object.hasOwn(row, key) || typeof row[key] === "boolean") && ["contextWindow", "outputLimit"].every((key) => !Object.hasOwn(row, key) || Number.isSafeInteger(row[key]) && row[key] > 0) && ["reasoningEfforts", "inputModalities"].every((key) => !Object.hasOwn(row, key) || Array.isArray(row[key]) && row[key].length <= 32 && row[key].every((value2) => text(128)(value2)) && new Set(row[key]).size === row[key].length)
204
+ );
205
+ case "agent.resolveSkills":
206
+ return rows(
207
+ value,
208
+ (row) => fields(row, ["type", "name", "path"]) && row.type === "skill" && text2(row.name) && text2(row.path)
209
+ );
210
+ }
211
+ return false;
212
+ }
213
+
214
+ // ../domain-contracts/src/app-host/service.ts
215
+ function fields2(value, required, optional = []) {
216
+ if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
217
+ return false;
218
+ return required.every((k) => Object.hasOwn(value, k)) && Reflect.ownKeys(value).every((k) => {
219
+ const d = Object.getOwnPropertyDescriptor(value, k);
220
+ return typeof k === "string" && [...required, ...optional].includes(k) && d.enumerable && Object.hasOwn(d, "value");
221
+ });
222
+ }
223
+ var version = (v) => typeof v === "string" && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$/.test(
224
+ v
225
+ );
226
+ function json2(value, ancestors = /* @__PURE__ */ new Set(), depth = 0) {
227
+ if (depth > 100) return false;
228
+ if (value === null || typeof value === "string" || typeof value === "boolean")
229
+ return true;
230
+ if (typeof value === "number") return Number.isFinite(value);
231
+ if (typeof value !== "object" || ancestors.has(value)) return false;
232
+ const array2 = Array.isArray(value);
233
+ if (array2 ? Object.getPrototypeOf(value) !== Array.prototype || Reflect.ownKeys(value).length !== value.length + 1 : ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
234
+ return false;
235
+ ancestors.add(value);
236
+ const result = Reflect.ownKeys(value).every((k) => {
237
+ if (array2 && k === "length") return true;
238
+ const d = Object.getOwnPropertyDescriptor(value, k);
239
+ return typeof k === "string" && (!array2 || /^(0|[1-9]\d*)$/.test(k) && Number(k) < value.length) && d.enumerable && Object.hasOwn(d, "value") && json2(d.value, ancestors, depth + 1);
240
+ });
241
+ ancestors.delete(value);
242
+ return result;
243
+ }
244
+ function validServiceStatus(value) {
245
+ return fields2(value, ["state"], ["reason", "instanceId", "apiVersion"]) && [
246
+ "absent",
247
+ "unauthorized",
248
+ "stopped",
249
+ "starting",
250
+ "recovering",
251
+ "ready",
252
+ "failed"
253
+ ].includes(value.state) && (!Object.hasOwn(value, "reason") || [
254
+ "dependency_missing",
255
+ "service_start_failed",
256
+ "service_unavailable",
257
+ "result_unknown",
258
+ "incompatible",
259
+ "revoked"
260
+ ].includes(value.reason)) && (!Object.hasOwn(value, "instanceId") || typeof value.instanceId === "string" && HOST_REQUEST_ID.test(value.instanceId)) && (!Object.hasOwn(value, "apiVersion") || version(value.apiVersion)) && (value.state !== "ready" || Object.hasOwn(value, "instanceId") && Object.hasOwn(value, "apiVersion"));
261
+ }
262
+ function validWork(value) {
263
+ return fields2(value, ["requestId", "state", "updatedAt"], ["result", "error"]) && typeof value.requestId === "string" && HOST_REQUEST_ID.test(value.requestId) && [
264
+ "not_accepted",
265
+ "accepted",
266
+ "running",
267
+ "completed",
268
+ "failed",
269
+ "interrupted",
270
+ "unknown"
271
+ ].includes(value.state) && typeof value.updatedAt === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(
272
+ value.updatedAt
273
+ ) && Number.isFinite(Date.parse(value.updatedAt)) && ["result", "error"].every(
274
+ (k) => !Object.hasOwn(value, k) || json2(value[k]) && new TextEncoder().encode(JSON.stringify(value[k])).length <= 16384
275
+ );
276
+ }
277
+ function validServiceResult(method, value) {
278
+ switch (method) {
279
+ case "service.getStatus":
280
+ return validServiceStatus(value);
281
+ case "service.getConnection":
282
+ return fields2(value, ["connectionId", "baseUrl", "apiVersion"]) && typeof value.connectionId === "string" && /^[A-Za-z0-9-]+$/.test(value.connectionId) && value.baseUrl === `https://app-host.invalid/connections/${value.connectionId}` && version(value.apiVersion);
283
+ case "service.getWork":
284
+ return validWork(value);
285
+ case "service.listWork":
286
+ return Array.isArray(value) && value.length <= 5120 && value.every(validWork) && new Set(value.map((w) => w.requestId)).size === value.length;
287
+ case "service.interruptWork":
288
+ return fields2(value, ["requested"]) && typeof value.requested === "boolean";
289
+ }
290
+ }
291
+
292
+ // ../domain-contracts/src/app-host/fetch.ts
293
+ var APP_HOST_FEATURES = ["fetch-v2", "fetch-inline-body-v1", "fetch-target-close-v1", "service-v1", "extended-errors-v1", "workspace-v1", "session-resources-v1", "session-controls-v1", "conversation-creation-session-v1", "trusted-desktop-v1", "attachments-v1", "auxiliary-sessions-v1", "system-ui-v1", "lifecycle-v1", "commands-v1", "resource-catalog-v1", "file-content-v1", "window-chrome-v1", "embedded-browser-v1", "browser-binding-invalidation-v1", "browser-capture-preview-v1"];
294
+ var FETCH_CHUNK_BYTES = 64 * 1024;
295
+ var FETCH_INLINE_BODY_BYTES = 8 * 1024;
296
+ var FETCH_WINDOW_CHUNKS = 4;
297
+ var FETCH_MAX_STREAMS = 16;
298
+ var FETCH_METADATA_BYTES = 64 * 1024;
299
+ var FETCH_HEADERS_TIMEOUT_MS = 3e4;
300
+ var FETCH_IDLE_TIMEOUT_MS = 12e4;
301
+ function isPageFetchFrame(value) {
302
+ let size = 0;
303
+ const visit = (entry, depth, binary = false) => {
304
+ if (depth > 10) return false;
305
+ if (entry instanceof Uint8Array) {
306
+ if (!binary || Object.getPrototypeOf(entry) !== Uint8Array.prototype || ["buffer", "byteLength", "byteOffset", "length"].some((key) => Object.hasOwn(entry, key))) return false;
307
+ const buffer = entry.buffer;
308
+ return buffer instanceof ArrayBuffer && !Object.hasOwn(buffer, "byteLength") && buffer.byteLength <= FETCH_CHUNK_BYTES && entry.byteLength > 0 && entry.byteLength <= FETCH_CHUNK_BYTES;
309
+ }
310
+ if (entry === null || typeof entry === "boolean" || typeof entry === "number" && Number.isFinite(entry)) {
311
+ size += 8;
312
+ return true;
313
+ }
314
+ if (typeof entry === "string") {
315
+ size += new TextEncoder().encode(entry).byteLength + 2;
316
+ return size <= FETCH_METADATA_BYTES;
317
+ }
318
+ if (!entry || typeof entry !== "object") return false;
319
+ const array2 = Array.isArray(entry);
320
+ if (array2 ? Object.getPrototypeOf(entry) !== Array.prototype : ![Object.prototype, null].includes(Object.getPrototypeOf(entry))) return false;
321
+ const keys = Reflect.ownKeys(entry);
322
+ if (keys.length > FETCH_METADATA_BYTES || array2 && keys.length !== entry.length + 1) return false;
323
+ return keys.every((key) => {
324
+ if (array2 && key === "length") return true;
325
+ const d = Object.getOwnPropertyDescriptor(entry, key);
326
+ size += typeof key === "string" ? key.length + 3 : 0;
327
+ return typeof key === "string" && d.enumerable && Object.hasOwn(d, "value") && (!array2 || /^(0|[1-9][0-9]*)$/.test(key) && Number(key) < entry.length) && visit(d.value, depth + 1, depth === 0 && key === "bytes") && size <= FETCH_METADATA_BYTES;
328
+ });
329
+ };
330
+ if (!visit(value, 0) || !value || typeof value !== "object" || Array.isArray(value)) return false;
331
+ const v = value;
332
+ if (v.protocol !== 2 || typeof v.type !== "string") return false;
333
+ const fields4 = {
334
+ "fetch-open": ["id", "connectionId", "url", "method", "headers", "hasBody"],
335
+ "fetch-headers": ["id", "status", "statusText", "headers", "hasBody"],
336
+ "fetch-credit": ["id", "direction", "sequence", "chunks", "bytes"],
337
+ "fetch-chunk": ["id", "direction", "sequence", "bytes"],
338
+ "fetch-end": ["id", "direction", "sequence"],
339
+ "fetch-consumed": ["id", "direction", "sequence"],
340
+ "fetch-cancel": ["id"],
341
+ "fetch-error": ["id", "error"],
342
+ "fetch-close": ["connectionId"]
343
+ };
344
+ const required = fields4[v.type];
345
+ const inline = v.type === "fetch-open" && Object.hasOwn(v, "inlineBody");
346
+ if (!required || Object.keys(v).length !== required.length + 2 + Number(inline) || !required.every((k) => Object.hasOwn(v, k))) return false;
347
+ if (inline && (v.hasBody !== true || typeof v.inlineBody !== "string" || new TextEncoder().encode(v.inlineBody).byteLength > FETCH_INLINE_BODY_BYTES)) return false;
348
+ const id3 = (x) => typeof x === "string" && x.length > 0 && x.length <= 128;
349
+ if (v.type === "fetch-close") return id3(v.connectionId);
350
+ if (!id3(v.id)) return false;
351
+ if (v.type === "fetch-consumed") return v.direction === "download" && Number.isSafeInteger(v.sequence) && v.sequence >= 0;
352
+ if (["fetch-chunk", "fetch-credit", "fetch-end"].includes(v.type) && (!["upload", "download"].includes(v.direction) || !Number.isSafeInteger(v.sequence) || v.sequence < 0)) return false;
353
+ if (v.type === "fetch-credit") return Number.isInteger(v.chunks) && v.chunks > 0 && v.chunks <= FETCH_WINDOW_CHUNKS && v.bytes === v.chunks * FETCH_CHUNK_BYTES;
354
+ if (v.type === "fetch-chunk") return v.bytes instanceof Uint8Array;
355
+ if (v.type === "fetch-error") return isAppHostErrorInfo(v.error);
356
+ if (v.type === "fetch-open" || v.type === "fetch-headers") {
357
+ if (!Array.isArray(v.headers) || !v.headers.every((h) => Array.isArray(h) && h.length === 2 && h.every((x) => typeof x === "string")) || typeof v.hasBody !== "boolean") return false;
358
+ if (v.type === "fetch-open") return id3(v.connectionId) && typeof v.url === "string" && typeof v.method === "string" && /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(v.method);
359
+ return Number.isInteger(v.status) && v.status >= 200 && v.status <= 599 && typeof v.statusText === "string";
360
+ }
361
+ return true;
362
+ }
363
+ function pageFetchPath(baseUrl, input) {
364
+ if (/[\\\s#]/.test(input)) throw new TypeError("Invalid fetch URL");
365
+ const rawPath = input.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/]+/, "").split("?")[0];
366
+ if (rawPath.includes("//") || /%(?:2e|2f|5c|25)/i.test(rawPath) || rawPath.split("/").some((p) => p === "." || p === "..") || /[\u0000-\u001f\u007f]/.test(decodeURIComponent(rawPath))) throw new TypeError("Ambiguous fetch path");
367
+ const base = new URL(baseUrl), url = new URL(input);
368
+ if (base.protocol !== "https:" || base.hostname !== "app-host.invalid" || base.username || base.password || base.search || base.hash || url.origin !== base.origin || url.username || url.password || url.hash || url.pathname !== base.pathname && !url.pathname.startsWith(base.pathname + "/")) throw new TypeError("Fetch target mismatch");
369
+ return (url.pathname.slice(base.pathname.length) || "/") + url.search;
370
+ }
371
+
372
+ // ../domain-contracts/src/app-host/service-host-protocol.ts
373
+ var SERVICE_HOST_METHODS = ["secrets.get", "secrets.set", "secrets.delete", "context.get", "context.resolveInvocation", "agent.listModels", "agent.getConnection", "agent.resolveSkills", "sessions.getConnection", "workspace.gitStatus", "workspace.createTaskWorktree", "workspace.getWorktree", "workspace.releaseExecutionRoot", "work.list", "work.get"];
374
+ var SERVICE_HOST_MAX_FRAME_BYTES = 512 * 1024;
375
+ var SERVICE_HOST_MAX_PENDING = 64;
376
+ var validServiceContext = (v) => json(v) && object({ protocolVersion: enumeration(1), registrationId: id, instanceId: id, dataScopeId: text(256), scope: object({ appId: text(256), installationId: id, contentDigest: digest }), installationRevision: count, phase: enumeration("starting", "ready") })(v);
377
+ var worktreeBody = { workspaceId: id, expectedHead: text(256), branch: text(1024) };
378
+ var worktreeReceipt = object({ requestId: id, state: enumeration("accepted", "completed", "failed", "unknown") }, { result: object({ executionRoot: id, workspaceId: id, branch: text(1024), sourceHead: text(256) }) });
379
+ function validServiceHostInput(method, v) {
380
+ if (!json(v)) return false;
381
+ if (method.startsWith("agent.")) return validAgentInput(method, v);
382
+ switch (method) {
383
+ case "secrets.get":
384
+ case "secrets.delete":
385
+ return object({ key: (x) => typeof x === "string" && /^[a-zA-Z0-9._:-]{1,128}$/.test(x) })(v);
386
+ case "secrets.set":
387
+ return object({ key: (x) => typeof x === "string" && /^[a-zA-Z0-9._:-]{1,128}$/.test(x), value: text(16384) })(v);
388
+ case "context.get":
389
+ case "work.list":
390
+ return object({})(v);
391
+ case "context.resolveInvocation":
392
+ return object({ ticket: text(8192) })(v);
393
+ case "sessions.getConnection":
394
+ return object({ dataScopeId: text(256), sessionId: text(256) })(v);
395
+ case "workspace.gitStatus":
396
+ return object({ workspaceId: id })(v);
397
+ case "workspace.createTaskWorktree":
398
+ return object({ requestId: id, ...worktreeBody })(v);
399
+ case "workspace.getWorktree":
400
+ return object({ requestId: id, original: object(worktreeBody) })(v);
401
+ case "workspace.releaseExecutionRoot":
402
+ return object({ requestId: id, workspaceId: id, executionRoot: id })(v);
403
+ case "work.get":
404
+ return object({ requestId: id })(v);
405
+ default:
406
+ return false;
407
+ }
408
+ }
409
+ function validServiceHostResult(method, v) {
410
+ if (!json(v)) return false;
411
+ if (method.startsWith("agent.")) return validAgentResult(method, v);
412
+ switch (method) {
413
+ case "secrets.get":
414
+ return v === null || text(16384)(v);
415
+ case "secrets.set":
416
+ return object({ stored: enumeration(true) })(v);
417
+ case "secrets.delete":
418
+ return object({ deleted: enumeration(true) })(v);
419
+ case "context.get":
420
+ return validServiceContext(v);
421
+ case "context.resolveInvocation":
422
+ return object({ invocationId: id, dataScopeId: text(256), sessionId: text(256), runId: text(256) }, { inputId: text(256), workspaceId: id, executionRoot: id, privateSessionId: id })(v);
423
+ case "sessions.getConnection":
424
+ return validAgentResult("agent.getConnection", v);
425
+ case "workspace.gitStatus":
426
+ return object({ root: text(32768), commonDir: text(32768), head: text(256), branch: text(1024, true), changes: array(text(32768), 1e4) })(v);
427
+ case "workspace.createTaskWorktree":
428
+ return worktreeReceipt(v);
429
+ case "workspace.getWorktree":
430
+ return v === null || worktreeReceipt(v);
431
+ case "workspace.releaseExecutionRoot":
432
+ return object({ requestId: id, executionRoot: id, state: enumeration("released", "retained-dirty", "in-use", "unknown") })(v);
433
+ case "work.list":
434
+ return validServiceResult("service.listWork", v);
435
+ case "work.get":
436
+ return v === null || validServiceResult("service.getWork", v);
437
+ default:
438
+ return false;
439
+ }
440
+ }
441
+ function isServiceHostFrame(v) {
442
+ if (isPageFetchFrame(v)) return true;
443
+ if (!json(v) || new TextEncoder().encode(JSON.stringify(v)).byteLength > SERVICE_HOST_MAX_FRAME_BYTES || !object({ protocol: enumeration(1), type: text(64) }, { id, context: validServiceContext, method: enumeration(...SERVICE_HOST_METHODS), params: json, ok: enumeration(true, false), value: json, error: isAppHostErrorInfo })(v)) return false;
444
+ const frame = v;
445
+ switch (frame.type) {
446
+ case "service-host-connect":
447
+ return object({ protocol: enumeration(1), type: enumeration(frame.type), id })(v);
448
+ case "service-host-ready":
449
+ return object({ protocol: enumeration(1), type: enumeration(frame.type), id, context: validServiceContext })(v);
450
+ case "service-host-context":
451
+ return object({ protocol: enumeration(1), type: enumeration(frame.type), context: validServiceContext })(v);
452
+ case "service-host-close":
453
+ return object({ protocol: enumeration(1), type: enumeration(frame.type) })(v);
454
+ case "service-host-request":
455
+ return object({ protocol: enumeration(1), type: enumeration(frame.type), id, method: enumeration(...SERVICE_HOST_METHODS), params: (x) => validServiceHostInput(frame.method, x) })(v);
456
+ case "service-host-response":
457
+ return frame.ok ? object({ protocol: enumeration(1), type: enumeration(frame.type), id, ok: enumeration(true), value: json })(v) : object({ protocol: enumeration(1), type: enumeration(frame.type), id, ok: enumeration(false), error: isAppHostErrorInfo })(v);
458
+ default:
459
+ return false;
460
+ }
461
+ }
462
+
463
+ // ../domain-contracts/src/app-host/agent-api-policy.ts
464
+ var routes = [
465
+ { method: "GET", pattern: /^\/schedules\/(status|tasks(?:\/[^/]+)?|runs)$/, id: "schedules.read" },
466
+ { method: "POST", pattern: /^\/schedules\/tasks(?:\/[^/]+\/run)?$/, id: "schedules.create" },
467
+ { method: "PATCH", pattern: /^\/schedules\/(tasks\/[^/]+|runs\/[^/]+\/read)$/, id: "schedules.update" },
468
+ { method: "DELETE", pattern: /^\/schedules\/tasks\/[^/]+$/, id: "schedules.delete" },
469
+ { method: "GET", pattern: /^\/(health|capabilities)$/, id: "protocol.read" },
470
+ { method: "GET", pattern: /^\/(models|agent-personas|skills)$/, id: "resources.read" },
471
+ { method: "GET", pattern: /^\/sessions\/[^/]+\/goal(?:\/requests\/[^/]+)?$/, id: "goals.read" },
472
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/goals$/, id: "goals.write" },
473
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/goals\/[^/]+\/actions$/, id: "goals.actions" },
474
+ { method: "PATCH", pattern: /^\/sessions\/[^/]+\/goals\/[^/]+$/, id: "goals.update" },
475
+ { method: "GET", pattern: /^\/sessions\/[^/]+\/controls$/, id: "sessions.controls" },
476
+ { method: "GET", pattern: /^\/sessions\/[^/]+\/configuration$/, id: "sessions.configuration" },
477
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/configuration-result$/, id: "sessions.configuration-result" },
478
+ { method: "GET", pattern: /^\/sessions\/[^/]+\/context-usage$/, id: "sessions.context-usage" },
479
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/(configure|compact)$/, id: "sessions.control" },
480
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/control-result$/, id: "sessions.control-result" },
481
+ { method: "GET", pattern: /^\/sessions$/, id: "sessions.list" },
482
+ { method: "GET", pattern: /^\/sessions\/search$/, id: "sessions.search" },
483
+ { method: "GET", pattern: /^\/sessions\/(directory|activity)$/, id: "sessions.directory" },
484
+ { method: "GET", pattern: /^\/sessions\/configuration-options$/, id: "sessions.configuration-options" },
485
+ { method: "POST", pattern: /^\/sessions\/creation-result$/, id: "sessions.creation-result" },
486
+ { method: "GET", pattern: /^\/sessions\/[^/]+\/resource-revision$/, id: "sessions.resource-revision" },
487
+ { method: "GET", pattern: /^\/sessions\/[^/]+\/resource-mutations\/[^/]+$/, id: "sessions.resource-mutation" },
488
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/resource-actions\/(rename|pin|archive|delete)$/, id: "sessions.resource-action" },
489
+ { method: "POST", pattern: /^\/sessions$/, id: "sessions.create" },
490
+ { method: "GET", pattern: /^\/sessions\/[^/]+$/, id: "sessions.get" },
491
+ { method: "GET", pattern: /^\/sessions\/[^/]+\/terminals(?:\/[^/]+\/(output|stream))?$/, id: "terminals.read" },
492
+ { method: "GET", pattern: /^\/sessions\/[^/]+\/files(?:\/(stat|text|find|search))?$/, id: "files.read" },
493
+ { method: "GET", pattern: /^\/sessions\/[^/]+\/(state|messages|parts|usage|mcp)$/, id: "sessions.detail" },
494
+ { method: "GET", pattern: /^\/sessions\/[^/]+\/messages\/[^/]+\/parts\/[^/]+$/, id: "parts.get" },
495
+ { method: "PATCH", pattern: /^\/sessions\/[^/]+$/, id: "sessions.update" },
496
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/fork$/, id: "sessions.fork" },
497
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/prompts$/, id: "prompts.admit" },
498
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/prompts\/latest\/edit$/, id: "prompts.edit" },
499
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/prompts\/[^/]+\/promote$/, id: "prompts.promote" },
500
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/runs\/[^/]+\/resume$/, id: "runs.resume" },
501
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/prompts\/[^/]+\/cancel$/, id: "prompts.cancel" },
502
+ { method: "POST", pattern: /^\/sessions\/[^/]+\/interrupt$/, id: "sessions.interrupt" },
503
+ { method: "GET", pattern: /^\/permissions$/, id: "permissions.list" },
504
+ { method: "POST", pattern: /^\/permissions\/[^/]+\/answer$/, id: "questions.answer" },
505
+ { method: "POST", pattern: /^\/permissions\/[^/]+\/reply$/, id: "permissions.reply" },
506
+ { method: "POST", pattern: /^\/attachments$/, id: "attachments.upload" },
507
+ { method: "GET", pattern: /^\/attachments\/[^/]+(?:\/content)?$/, id: "attachments.read" },
508
+ { method: "DELETE", pattern: /^\/attachments\/[^/]+$/, id: "attachments.delete" },
509
+ { method: "GET", pattern: /^\/events(?:\/stream)?$/, id: "events.read" },
510
+ { method: "GET", pattern: /^\/jobs(?:\/[^/]+)?$/, id: "jobs.read" },
511
+ { method: "POST", pattern: /^\/jobs\/[^/]+\/wait$/, id: "jobs.wait" },
512
+ { method: "POST", pattern: /^\/jobs\/[^/]+\/cancel$/, id: "jobs.cancel" }
513
+ ];
514
+ function matchAgentApiRoute(method, path) {
515
+ return routes.find((route) => route.method === method && route.pattern.test(path));
516
+ }
517
+ function normalizeAgentApiPath(raw) {
518
+ const invalid = () => {
519
+ throw new Error("invalid_request");
520
+ };
521
+ const path = raw.split("?", 1)[0];
522
+ if (!path.startsWith("/") || path.startsWith("//") || /[\\#\u0000-\u0020\u007f]/.test(path) || /%(?:2f|5c|00)/i.test(path)) invalid();
523
+ let decoded;
524
+ try {
525
+ decoded = decodeURIComponent(path);
526
+ } catch {
527
+ return invalid();
528
+ }
529
+ if (/[\\%\u0000-\u0020\u007f]/.test(decoded) || decoded.split("/").some((p) => p === "." || p === "..")) invalid();
530
+ return decoded;
531
+ }
532
+
533
+ // ../domain-contracts/src/app-host/workspace-conversations.ts
534
+ var validWorkspaceConversation = (value) => {
535
+ if (!object(
536
+ { dataScopeId: text(), requestId: id, sessionId: id, taskLocation: enumeration("current", "worktree"), configuration: json },
537
+ { workspaceId: id, outsideProject: (v) => v === true, preparationRevision: text() }
538
+ )(value)) return false;
539
+ const input = value;
540
+ return input.workspaceId !== void 0 ? input.outsideProject !== true : input.outsideProject === true && input.taskLocation === "current";
541
+ };
542
+ var sessionText = (value) => typeof value === "string";
543
+ var sessionRecord = object({
544
+ id,
545
+ cwd: sessionText,
546
+ title: sessionText,
547
+ model: sessionText,
548
+ status: enumeration("idle", "running", "closing", "archived", "error"),
549
+ metadata: jsonObject,
550
+ createdAt: count,
551
+ updatedAt: count
552
+ }, {
553
+ storage: enumeration("sqlite", "memory"),
554
+ parentId: sessionText,
555
+ projectId: sessionText,
556
+ cwdRelative: sessionText,
557
+ agent: sessionText,
558
+ archivedAt: count
559
+ });
560
+ var workspaceConversationResult = object({
561
+ dataScopeId: text(),
562
+ sessionId: id,
563
+ requestId: id,
564
+ action: (v) => v === "create-session",
565
+ state: enumeration("prepared", "completed", "unknown")
566
+ }, {
567
+ configuration: json,
568
+ revision: count,
569
+ session: sessionRecord,
570
+ operationState: enumeration("prepared", "running", "completed", "failed", "unknown"),
571
+ indexBindingPending: (v) => v === true,
572
+ workspaceId: id,
573
+ executionRoot: id,
574
+ privateSessionId: id,
575
+ worktree: json
576
+ });
577
+ var validWorkspaceConversationResult = (value) => {
578
+ if (!workspaceConversationResult(value)) return false;
579
+ const result = value;
580
+ return !result.session || result.state === "completed" && result.session.id === result.sessionId;
581
+ };
582
+
583
+ // ../domain-contracts/src/app-host/session-controls.ts
584
+ var option = object({ id: text(), name: text() });
585
+ var choices = array(option);
586
+ var effortChoices = array(object({ id: text(1024, true), name: text() }));
587
+ var receiptShape = object({ dataScopeId: text(), sessionId: text(), requestId: id, action: enumeration("fork", "configure", "compact"), state: enumeration("prepared", "created", "completed", "unknown") }, { revision: count, targetSessionId: text() });
588
+ var receipt = receiptShape;
589
+ function validSessionControlOriginal(value) {
590
+ if (!object({ action: text(), body: json })(value)) return false;
591
+ const v = value;
592
+ if (v.action === "compact") return object({ requestId: id, expectedRevision: count })(v.body);
593
+ return v.action === "fork" && object({ requestId: id, id: text() }, { copyHistory: bool, beforeMessageId: text(), afterMessageId: text(), storage: enumeration("sqlite") })(v.body);
594
+ }
595
+ function validSessionControlInput(method, value) {
596
+ if (!json(value)) return false;
597
+ if (method === "sessions.getDraftComposerOptions") {
598
+ if (!object({ source: enumeration("instance") }, { workspaceId: id, outsideProject: bool, roleId: (v2) => v2 === null || text(256)(v2) })(value)) return false;
599
+ const target2 = value;
600
+ return target2.workspaceId !== void 0 ? target2.outsideProject !== true : target2.outsideProject === true;
601
+ }
602
+ if (method === "sessions.bindConversationIndex") return object({ original: validWorkspaceConversation, dataScopeId: text() })(value);
603
+ if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult") return validWorkspaceConversation(value);
604
+ if (method === "sessions.getControls") return object({ connectionId: text(), sessionId: text() })(value);
605
+ if (!object({ requestId: id, sessionId: text(), original: validSessionControlOriginal }, { connectionId: text() })(value)) return false;
606
+ const v = value;
607
+ return v.original.body.requestId === v.requestId && !!v.connectionId;
608
+ }
609
+ function validSessionControlResult(method, value) {
610
+ if (!json(value)) return false;
611
+ if (method === "sessions.getDraftComposerOptions") return object({ source: enumeration("instance"), optionsRevision: text(), skills: array(object({ id: text(), name: text(), path: text(4096, true) }, { source: enumeration("bundled", "user", "project", "plugin") }), 128), plugins: array(object({ id: text(), name: text(), agents: array(option, 128) }), 128) })(value);
612
+ if (method === "sessions.bindConversationIndex") return validWorkspaceConversationResult(value);
613
+ if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult")
614
+ return method === "sessions.getConversationCreationResult" && value === null || validWorkspaceConversationResult(value);
615
+ if (method === "sessions.getControls") return object({ dataScopeId: text(), sessionId: text(), source: enumeration("instance", "auxiliary", "im"), revision: count, optionsRevision: text(), actions: object(Object.fromEntries(["readContext", "configure", "compact", "edit", "fork", "resume", "goalRead", "goalWrite", "goalStop"].map((k) => [k, bool]))), models: choices, roles: choices, efforts: effortChoices, workModes: choices, skills: array(object({ id: text(), name: text(), path: text(4096, true) }, { source: enumeration("bundled", "user", "project", "plugin") })), commands: choices, contexts: choices }, { permissionModes: array(option, 128), appServiceBindings: array(option, 128), plugins: array(object({ id: text(), name: text(), agents: choices })) })(value);
616
+ if (method === "sessions.getControlResult") return value === null || receipt(value);
617
+ if (!receipt(value)) return false;
618
+ return false;
619
+ }
620
+
621
+ // ../domain-contracts/src/app-host/workspace.ts
622
+ function fields3(v, required, optional = []) {
623
+ if (!v || typeof v !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
624
+ return required.every((k) => Object.hasOwn(v, k)) && Reflect.ownKeys(v).every((k) => {
625
+ const d = Object.getOwnPropertyDescriptor(v, k);
626
+ return typeof k === "string" && [...required, ...optional].includes(k) && d.enumerable && Object.hasOwn(d, "value");
627
+ });
628
+ }
629
+ var uuid = (v) => typeof v === "string" && HOST_REQUEST_ID.test(v);
630
+ var str = (v) => typeof v === "string";
631
+ function rows2(v, check) {
632
+ if (!Array.isArray(v) || Object.getPrototypeOf(v) !== Array.prototype || v.length > 200 || Reflect.ownKeys(v).length !== v.length + 1) return false;
633
+ for (let i = 0; i < v.length; i++) {
634
+ const d = Object.getOwnPropertyDescriptor(v, String(i));
635
+ if (!d?.enumerable || !Object.hasOwn(d, "value") || !check(d.value)) return false;
636
+ }
637
+ return true;
638
+ }
639
+ var ref = (v) => fields3(v, ["id", "displayName"]) && uuid(v.id) && str(v.displayName) && v.displayName.length > 0;
640
+ function validWorkspaceInput(method, v) {
641
+ switch (method) {
642
+ case "workspace.select":
643
+ case "workspace.getSelection":
644
+ return fields3(v, ["requestId"]) && uuid(v.requestId);
645
+ case "workspace.get":
646
+ return fields3(v, ["workspaceId"]) && uuid(v.workspaceId);
647
+ case "workspace.listFiles":
648
+ return fields3(v, ["workspaceId", "directory"], ["cursor"]) && uuid(v.workspaceId) && str(v.directory) && (!Object.hasOwn(v, "cursor") || uuid(v.cursor));
649
+ case "workspace.readText":
650
+ return fields3(v, ["workspaceId", "path"]) && uuid(v.workspaceId) && str(v.path) && v.path.length > 0;
651
+ }
652
+ }
653
+ function validWorkspaceResult(method, v) {
654
+ switch (method) {
655
+ case "workspace.select":
656
+ return v === null || ref(v);
657
+ case "workspace.get":
658
+ return ref(v);
659
+ case "workspace.getSelection":
660
+ if (!fields3(v, ["requestId", "status"], ["workspace", "unavailable"]) || !uuid(v.requestId)) return false;
661
+ if (v.status === "completed") return fields3(v, ["requestId", "status", "workspace"]) && ref(v.workspace) || fields3(v, ["requestId", "status", "unavailable"]) && v.unavailable === true;
662
+ return fields3(v, ["requestId", "status"]) && ["pending", "cancelled", "expired", "failed", "unknown"].includes(v.status);
663
+ case "workspace.listFiles":
664
+ return fields3(v, ["entries"], ["nextCursor"]) && rows2(v.entries, (e) => fields3(e, ["path", "name", "kind"]) && str(e.path) && str(e.name) && (e.kind === "file" || e.kind === "directory")) && (!Object.hasOwn(v, "nextCursor") || uuid(v.nextCursor));
665
+ case "workspace.readText":
666
+ return fields3(v, ["path", "text", "revision"]) && str(v.path) && v.path.length > 0 && str(v.text) && typeof v.revision === "string" && /^[a-f0-9]{64}$/.test(v.revision);
667
+ }
668
+ }
669
+
670
+ // src/commands.ts
671
+ var COMMANDS_METHODS = [
672
+ "commands.register",
673
+ "commands.update",
674
+ "commands.dispose"
675
+ ];
676
+ var isCommandsMethod = (method) => COMMANDS_METHODS.includes(method);
677
+ var identifier = (v) => text(128)(v) && /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(v);
678
+ var label = text(512);
679
+ var shortcut = object(
680
+ {
681
+ code: (v) => text(64)(v) && /^(Key[A-Z]|Digit[0-9]|F(?:[1-9]|1[0-9]|2[0-4])|Arrow(?:Left|Right|Up|Down)|Enter|Escape|Space|Tab|Backspace|Delete|Home|End|PageUp|PageDown|Comma|Period|Slash|Backslash|Semicolon|Quote|Backquote|Minus|Equal|BracketLeft|BracketRight|NumpadAdd|NumpadSubtract|Numpad0)$/.test(
682
+ v
683
+ ),
684
+ modifiers: array(
685
+ enumeration("Primary", "Control", "Meta", "Alt", "Shift"),
686
+ 5
687
+ )
688
+ },
689
+ { scope: enumeration("application", "global") }
690
+ );
691
+ function validAppCommandSnapshot(value) {
692
+ if (!json(value) || !object(
693
+ {
694
+ commands: array(
695
+ object(
696
+ { id: identifier, label },
697
+ { enabled: bool, checked: bool, shortcuts: array(shortcut, 8) }
698
+ ),
699
+ 128
700
+ ),
701
+ menus: array(
702
+ object({
703
+ id: identifier,
704
+ label,
705
+ items: array(
706
+ (v2) => object({ command: identifier })(v2) || object({ separator: enumeration(true) })(v2),
707
+ 64
708
+ )
709
+ }),
710
+ 8
711
+ )
712
+ },
713
+ {
714
+ toolbar: object(
715
+ {},
716
+ { back: identifier, forward: identifier, sidebar: identifier }
717
+ )
718
+ }
719
+ )(value))
720
+ return false;
721
+ const v = value;
722
+ const ids = new Set(v.commands.map((c) => c.id));
723
+ if (ids.size !== v.commands.length || new Set(v.menus.map((m) => m.id)).size !== v.menus.length || v.menus.some(
724
+ (m) => m.items.some((i) => "command" in i && !ids.has(i.command))
725
+ ) || Object.values(v.toolbar ?? {}).some((x) => !ids.has(x)))
726
+ return false;
727
+ const keys = /* @__PURE__ */ new Set();
728
+ for (const command of v.commands)
729
+ for (const key of command.shortcuts ?? []) {
730
+ const mods = new Set(key.modifiers);
731
+ if (mods.size !== key.modifiers.length || mods.has("Primary") && (mods.has("Meta") || mods.has("Control")))
732
+ return false;
733
+ if ((mods.has("Primary") || mods.has("Meta") || mods.has("Control")) && ["KeyQ", "KeyR"].includes(key.code) || mods.has("Alt") && ["F4", "Tab", "Space"].includes(key.code) || mods.has("Meta") && ["Space", "Tab"].includes(key.code) || mods.has("Control") && mods.has("Alt") && key.code === "Delete" || key.code === "F5" || key.code === "F11" || key.code === "F12")
734
+ return false;
735
+ const signature = `${[...mods].map((m) => m === "Control" || m === "Meta" ? "Primary" : m).sort().join("+")}:${key.code}`;
736
+ if (keys.has(signature)) return false;
737
+ keys.add(signature);
738
+ }
739
+ return true;
740
+ }
741
+ var validCommandReceipt = object(
742
+ { registrationId: id, revision: count },
743
+ { shortcutConflicts: array(identifier, 128) }
744
+ );
745
+ var validCommandInvocation = (v) => json(v) && object({
746
+ type: enumeration("command-invoked"),
747
+ registrationId: id,
748
+ revision: count,
749
+ commandId: identifier
750
+ })(v);
751
+ function validCommandsInput(method, v) {
752
+ return json(v) && object({
753
+ registrationId: id,
754
+ revision: count,
755
+ ...method === "commands.dispose" ? {} : { snapshot: validAppCommandSnapshot }
756
+ })(v) && (method !== "commands.register" || v.revision === 0);
757
+ }
758
+ function createAppCommandsApi(rpc) {
759
+ return {
760
+ async register(snapshot, invoke) {
761
+ if (!validAppCommandSnapshot(snapshot) || typeof invoke !== "function")
762
+ throw new AppHostError("invalid_request");
763
+ rpc.requireFeature();
764
+ snapshot = structuredClone(snapshot);
765
+ const registrationId = crypto.randomUUID();
766
+ let revision2 = 0;
767
+ let disposed = false;
768
+ let remoteValid = true;
769
+ let disposal;
770
+ let current = snapshot;
771
+ let conflicts = [];
772
+ let queue = Promise.resolve();
773
+ const off = rpc.onInvoke((event) => {
774
+ if (!disposed && event.registrationId === registrationId && event.revision === revision2 && current.commands.some(
775
+ (c) => c.id === event.commandId && c.enabled !== false
776
+ )) {
777
+ void Promise.resolve().then(() => {
778
+ if (!disposed && event.revision === revision2)
779
+ return invoke(event.commandId);
780
+ }).catch(() => {
781
+ });
782
+ }
783
+ });
784
+ const stop = () => {
785
+ if (!disposed) {
786
+ disposed = true;
787
+ off();
788
+ }
789
+ };
790
+ const invalidate = () => {
791
+ remoteValid = false;
792
+ stop();
793
+ };
794
+ const offClose = rpc.onClose(invalidate);
795
+ const call = async (method, next) => {
796
+ const params = {
797
+ registrationId,
798
+ revision: revision2,
799
+ ...next === void 0 ? {} : { snapshot: next }
800
+ };
801
+ const result = await rpc.request(
802
+ method,
803
+ params
804
+ );
805
+ if (!validCommandReceipt(result) || result.registrationId !== registrationId || result.revision !== revision2)
806
+ throw new AppHostError("host_unavailable");
807
+ conflicts = [...result.shortcutConflicts ?? []];
808
+ };
809
+ const abandon = async () => {
810
+ invalidate();
811
+ offClose();
812
+ try {
813
+ await rpc.request("commands.dispose", {
814
+ registrationId,
815
+ revision: ++revision2
816
+ });
817
+ } catch {
818
+ }
819
+ };
820
+ try {
821
+ await call("commands.register", snapshot);
822
+ } catch (error) {
823
+ await abandon();
824
+ throw error;
825
+ }
826
+ return {
827
+ get shortcutConflicts() {
828
+ return [...conflicts];
829
+ },
830
+ update(next) {
831
+ if (disposed)
832
+ return Promise.reject(new AppHostError("connection_revoked"));
833
+ if (!validAppCommandSnapshot(next))
834
+ return Promise.reject(new AppHostError("invalid_request"));
835
+ next = structuredClone(next);
836
+ const task = queue.then(async () => {
837
+ if (disposed) throw new AppHostError("connection_revoked");
838
+ rpc.requireFeature();
839
+ revision2++;
840
+ current = next;
841
+ try {
842
+ await call("commands.update", next);
843
+ } catch (error) {
844
+ await abandon();
845
+ throw error;
846
+ }
847
+ });
848
+ queue = task.catch(() => {
849
+ });
850
+ return task;
851
+ },
852
+ dispose() {
853
+ if (disposal) return disposal;
854
+ stop();
855
+ disposal = queue.then(async () => {
856
+ if (!remoteValid) return;
857
+ revision2++;
858
+ try {
859
+ await call("commands.dispose");
860
+ } finally {
861
+ remoteValid = false;
862
+ }
863
+ }).finally(offClose);
864
+ queue = disposal.catch(() => {
865
+ });
866
+ return disposal;
867
+ }
868
+ };
869
+ }
870
+ };
871
+ }
872
+
873
+ // src/window.ts
874
+ var WINDOW_METHODS = ["window.getState", "window.minimize", "window.toggleMaximize", "window.requestClose", "window.openHost", "window.reportStartup"];
875
+ var finite = (value) => typeof value === "number" && Number.isFinite(value);
876
+ var material = object({
877
+ preference: enumeration("glass", "opaque"),
878
+ active: enumeration("glass", "opaque"),
879
+ shell: enumeration("solid", "translucent", "transparent"),
880
+ unavailableReason: nullable(enumeration("unsupported-platform", "unsupported-system", "reduced-transparency", "material-error"))
881
+ });
882
+ var validAppWindowState = (value) => object({
883
+ platform: enumeration("win32", "darwin", "linux"),
884
+ maximized: bool,
885
+ titleBar: enumeration("host", "custom", "native"),
886
+ trafficLightInset: (value2) => finite(value2) && value2 >= 0,
887
+ material
888
+ })(value);
889
+ function isWindowMethod(value) {
890
+ return WINDOW_METHODS.includes(value);
891
+ }
892
+ function validWindowInput(method, value) {
893
+ switch (method) {
894
+ case "window.openHost":
895
+ return object({ page: enumeration("manage", "settings", "about", "recovery") })(value);
896
+ case "window.reportStartup":
897
+ return object({ status: enumeration("ready") })(value) || object({ status: enumeration("failed"), message: text(2048) })(value);
898
+ default:
899
+ return object({})(value);
900
+ }
901
+ }
902
+ function validWindowResult(method, value) {
903
+ switch (method) {
904
+ case "window.getState":
905
+ return validAppWindowState(value);
906
+ default:
907
+ return value === void 0;
908
+ }
909
+ }
910
+ function validWindowEvent(value) {
911
+ return object({ type: enumeration("window-state-changed"), state: validAppWindowState })(value);
912
+ }
913
+ function createAppWindowApi(requester) {
914
+ async function send(method, params) {
915
+ requester.requireFeature();
916
+ if (!validWindowInput(method, params)) throw new AppHostError("invalid_request");
917
+ return requester.request(method, params);
918
+ }
919
+ return {
920
+ getState: () => send("window.getState", {}),
921
+ minimize: () => send("window.minimize", {}),
922
+ toggleMaximize: () => send("window.toggleMaximize", {}),
923
+ requestClose: () => send("window.requestClose", {}),
924
+ openHost: (input) => send("window.openHost", input),
925
+ reportStartup: (input) => send("window.reportStartup", input),
926
+ onStateChanged: (listener) => {
927
+ requester.requireFeature();
928
+ if (typeof listener !== "function") throw new AppHostError("invalid_request");
929
+ return requester.onEvent((event) => {
930
+ if (event.type === "window-state-changed") listener(event.state);
931
+ });
932
+ }
933
+ };
934
+ }
935
+
936
+ // src/resource-catalog.ts
937
+ var RESOURCE_CATALOG_METHODS = ["workspace.list"];
938
+ var isResourceCatalogMethod = (m) => RESOURCE_CATALOG_METHODS.includes(m);
939
+ var cursor = { cursor: id };
940
+ var nextCursor = { nextCursor: id };
941
+ var validResourceChanged = (v) => json(v) && object({ type: enumeration("resources-changed"), directory: enumeration("workspaces"), revision: text(256) })(v);
942
+ function validResourceCatalogInput(_method, v) {
943
+ return json(v) && object({}, cursor)(v);
944
+ }
945
+ function validResourceCatalogResult(method, v) {
946
+ if (!json(v)) return false;
947
+ return object({ revision: text(256), entries: array(object({ id, displayName: text(1024) }), 200) }, nextCursor)(v);
948
+ }
949
+ function createResourceCatalogApi(rpc) {
950
+ const call = async (method, params) => {
951
+ if (!validResourceCatalogInput(method, params)) throw new AppHostError("invalid_request");
952
+ rpc.requireFeature();
953
+ const result = await rpc.request(method, params);
954
+ if (!validResourceCatalogResult(method, result)) throw new AppHostError("host_unavailable");
955
+ return result;
956
+ };
957
+ return { list: (input = {}) => call("workspace.list", input) };
958
+ }
959
+
960
+ // src/session-controls.ts
961
+ var CONVERSATION_PREPARATION_METHODS = [
962
+ "sessions.createConversation",
963
+ "sessions.getConversationCreationResult",
964
+ "sessions.bindConversationIndex"
965
+ ];
966
+ function isConversationPreparationMethod(method) {
967
+ return CONVERSATION_PREPARATION_METHODS.includes(method);
968
+ }
969
+ function validConversationPreparationInput(method, input) {
970
+ return validSessionControlInput(method, input);
971
+ }
972
+ function validConversationPreparationResult(method, result) {
973
+ return validSessionControlResult(method, result);
974
+ }
975
+
976
+ // src/client-connections.ts
977
+ var connections = /* @__PURE__ */ new WeakMap();
978
+ function createClientConnection(wire, streams) {
979
+ const record = { owner: streams, id: wire.connectionId, closed: false };
980
+ const connection = { ...wire.defaultTaskLocation === void 0 ? {} : { defaultTaskLocation: wire.defaultTaskLocation }, ...wire.cwd === void 0 ? {} : { cwd: wire.cwd }, clientOptions: { baseUrl: wire.baseUrl, fetch: streams.fetchFor(wire.connectionId, wire.baseUrl) }, isClosed() {
981
+ return record.closed || streams.isClosed?.(wire.connectionId) === true;
982
+ }, close() {
983
+ if (!record.closed) {
984
+ record.closed = true;
985
+ streams.close(wire.connectionId);
986
+ }
987
+ } };
988
+ connections.set(connection, record);
989
+ return connection;
990
+ }
991
+ function resolveClientConnection(connection, owner) {
992
+ const record = connections.get(connection);
993
+ if (!record || record.owner !== owner || record.closed || owner.isClosed?.(record.id)) throw new AppHostError("connection_revoked");
994
+ return record.id;
995
+ }
996
+
997
+ // src/desktop.ts
998
+ var BROWSER_CAPTURE_PREVIEW_MAX_BYTES = 8 * 1024 * 1024;
999
+ var target = { targetId: text(256) };
1000
+ var mount = { ...target, mountId: text(256) };
1001
+ var source = object({ sessionId: text(), appId: text() });
1002
+ var action = { ...mount, source, requestId: id, expectedRevision: count };
1003
+ var page = { ...target, tabId: text(256), pageRevision: count };
1004
+ var mode = enumeration("off", "pick", "review");
1005
+ var voidResult = (v) => v === void 0;
1006
+ var finite2 = (v) => typeof v === "number" && Number.isFinite(v);
1007
+ var rect = object({ x: finite2, y: finite2, width: finite2, height: finite2 });
1008
+ var annotationFields = { target: text(8192), selector: text(8192), locatorKind: enumeration("unique-id", "semantic", "path"), tagName: text(256, true), role: text(1024, true), name: text(8192, true) };
1009
+ var validBrowserSnapshot = object({ pageUrl: text(16384, true), pageRevision: count, ready: bool, mode, interactionVersion: count, eventSequence: count, selection: nullable(object({ selectionId: text(), target: object(annotationFields), rect })), focusedAnnotationId: nullable(text()), viewport: nullable(object({ width: finite2, height: finite2 })), annotations: array(object({ record: object({ ...annotationFields, id: text(), pageUrl: text(16384, true), comment: text(65536, true) }), status: enumeration("visible", "offscreen", "missing"), rect: nullable(rect) }), 4096) });
1010
+ var root = object({ path: text(32768), identity: object({ dev: text(), ino: text() }) }, { workspaceId: text() });
1011
+ var validDesktopTarget = object({ id: text(), dataScopeId: text(), draftId: text(), draftRevision: count }, { root, sessionId: text() });
1012
+ var kind = enumeration("files.writeText", "git.switchBranch", "git.createBranch", "git.createTaskWorktree");
1013
+ var validWorkspaceOperation = object({ requestId: id, kind, state: enumeration("prepared", "running", "completed", "failed", "unknown"), createdAt: count, updatedAt: count }, { result: json, error: object({ code: text(128) }) });
1014
+ var origin = (v) => object({ kind: enumeration("surface"), surfaceId: text() })(v) || object({ kind: enumeration("tool-result"), sourcePartId: text() })(v);
1015
+ var appRecord = object({ id: text(), sessionId: text(), pluginId: text(), pluginVersion: text(), pluginDigest: text(), definitionDigest: text(), backendId: text(), backendKind: enumeration("native-tools", "mcp-server"), resourceUri: text(8192), origin, logicalKey: text(8192), status: enumeration("open", "closed", "revoked"), controlRevision: count, createdAt: count, updatedAt: count }, { activeActionRunId: text(), lastActionRunId: text() });
1016
+ var policy = object({ confirmation: enumeration("required", "granted"), maxArgumentsBytes: count }, { authorization: enumeration("plugin-data-write") });
1017
+ var state = object({ source, app: appRecord, availability: object({ canReadResource: bool, canInvokeTools: bool, canMessage: bool }, { reason: enumeration("closed", "revoked", "session-unavailable", "snapshot-changed", "permission-missing", "runtime-unavailable", "action-unconfirmed") }), online: bool }, { tools: array(object({ name: text(), description: text(65536, true), inputSchema: jsonObject }, { policy })) });
1018
+ var mounted = object({ mountId: text(), url: text(16384), state });
1019
+ var runStatus = enumeration("pending", "running", "completed", "failed", "interrupted");
1020
+ var actionResult = object({ receipt: object({ source, requestId: id, runId: text(), expectedRevision: count, acceptedRevision: count, status: runStatus, executionState: enumeration("not_started", "completed", "unknown") }) }, { result: object({ content: array(json, 4096) }, { structuredContent: jsonObject, isError: bool }), dataError: enumeration("plugin_app_invalid_data", "plugin_app_data_too_large", "plugin_app_unsupported_content", "plugin_app_result_unavailable") });
1021
+ var submission = object({ source, requestId: id, inputId: text(), runId: text(), expectedRevision: count, status: runStatus });
1022
+ var windowResult = object({ requestId: id, targetId: text(), state: enumeration("opening", "open", "closing", "closed") }, { windowId: count });
1023
+ var positive = (v) => count(v) && v > 0 && v <= 1e4;
1024
+ var capturePreviewBytes = (value) => value instanceof Uint8Array && value.buffer instanceof ArrayBuffer && value.byteOffset === 0 && value.byteLength === value.buffer.byteLength && value.byteLength > 0 && value.byteLength <= BROWSER_CAPTURE_PREVIEW_MAX_BYTES;
1025
+ var terminalResult = object({ resourceId: text(), terminalId: text(), cwd: text(32768), status: enumeration("running", "exited") });
1026
+ var terminalOriginal = (v) => object({ kind: enumeration("create"), cols: positive, rows: positive }, { name: text(256) })(v) || object({ kind: enumeration("restart"), terminalId: text() })(v);
1027
+ var terminalReceipt = (v) => object({ requestId: id, state: enumeration("pending", "failed", "unknown", "closed") }, { terminal: terminalResult, error: object({ code: text(128) }) })(v) || object({ requestId: id, state: enumeration("completed"), terminal: terminalResult })(v);
1028
+ var rules = {
1029
+ "desktop.bindTarget": { input: object({ draftId: text(), draftRevision: count }, { directory: text(32768), workspaceId: text(), connectionId: text(), sessionId: text() }), result: validDesktopTarget },
1030
+ "desktop.releaseTarget": { input: object(target), result: voidResult },
1031
+ "desktop.files.listFiles": { input: object(target, { directory: text(32768, true), recursive: bool }), result: object({ entries: array(object({ path: text(32768), name: text(32768), kind: enumeration("file", "directory") }), 1e4) }) },
1032
+ "desktop.files.search": { input: object({ ...target, query: text(4096, true) }, { directory: text(32768, true), limit: positive }), result: object({ matches: array(object({ path: text(32768), line: count, text: text(65536, true) }), 1e4), truncated: bool }) },
1033
+ "desktop.files.openRead": { input: object({ ...target, path: text(32768) }), result: validConnection },
1034
+ "desktop.files.readText": { input: object({ ...target, path: text(32768) }), result: object({ path: text(32768), text: text(8 * 1024 * 1024, true), sha256: digest, byteLength: count, encoding: enumeration("utf-8"), truncated: bool }) },
1035
+ "desktop.files.writeText": { input: object({ ...target, requestId: id, path: text(32768), expectedSha256: digest, text: text(8 * 1024 * 1024, true) }), result: validWorkspaceOperation },
1036
+ "desktop.files.getOperation": { input: object({ ...target, requestId: id, original: object({ kind, body: json }) }), result: nullable(validWorkspaceOperation) },
1037
+ "desktop.files.revealPath": { input: object({ ...target, path: text(32768) }), result: voidResult },
1038
+ "desktop.files.listOpeners": { input: object(target), result: array(object({ id: text(256), label: text(1024), kind: enumeration("editor", "folder", "terminal"), iconDataUrl: nullable(text(1024 * 1024)) }, { isDefault: bool }), 256) },
1039
+ "desktop.files.openWith": { input: object({ ...target, path: text(32768), openerId: text(256) }), result: voidResult },
1040
+ "desktop.clipboard.readText": { input: object(target), result: text(8 * 1024 * 1024, true) },
1041
+ "desktop.clipboard.writeText": { input: object({ ...target, text: text(8 * 1024 * 1024, true) }), result: voidResult },
1042
+ "desktop.clipboard.showTextMenu": { input: object({ ...target, editable: bool, hasSelection: bool }), result: nullable(enumeration("copy", "select-all")) },
1043
+ "desktop.windows.openExternal": { input: object({ ...target, url: text(16384) }), result: voidResult },
1044
+ "desktop.windows.getZoom": { input: object(target), result: object({ factor: (v) => finite2(v) && v >= 0.5 && v <= 2 }) },
1045
+ "desktop.windows.setZoom": { input: object({ ...target, factor: (v) => finite2(v) && v >= 0.5 && v <= 2 }), result: object({ factor: (v) => finite2(v) && v >= 0.5 && v <= 2 }) },
1046
+ "desktop.windows.edit": { input: object({ ...target, action: enumeration("undo", "redo", "cut", "copy", "paste", "selectAll") }), result: voidResult },
1047
+ "desktop.git.status": { input: object(target), result: object({ root: text(32768), commonDir: text(32768), head: text(), branch: text(1024, true), changes: array(text(32768), 1e4) }) },
1048
+ "desktop.git.listBranches": { input: object(target), result: object({ branches: array(text(1024), 1e4) }) },
1049
+ "desktop.git.changes": { input: object(target, { range: enumeration("uncommitted", "working", "staged"), ignoreWhitespace: bool }), result: object({ files: array(object({ path: text(32768), status: enumeration("added", "modified", "deleted", "renamed", "copied", "untracked"), additions: nullable(count), deletions: nullable(count), binary: bool }, { oldPath: text(32768) }), 1e4), totalAdditions: count, totalDeletions: count }) },
1050
+ "desktop.git.diff": { input: object(target, { path: text(32768), base: text(), head: text(), range: enumeration("uncommitted", "working", "staged"), ignoreWhitespace: bool }), result: object({ text: text(8 * 1024 * 1024, true), truncated: bool }) },
1051
+ "desktop.git.switchBranch": { input: object({ ...target, requestId: id, expectedHead: text(), branch: text() }), result: validWorkspaceOperation },
1052
+ "desktop.git.createBranch": { input: object({ ...target, requestId: id, expectedHead: text(), branch: text() }), result: validWorkspaceOperation },
1053
+ "desktop.git.createTaskWorktree": { input: object({ ...target, requestId: id, expectedHead: text(), branch: text() }), result: validWorkspaceOperation },
1054
+ "desktop.terminals.create": { input: object({ ...target, requestId: id, cols: positive, rows: positive }, { name: text(256) }), result: object({ resourceId: text(), terminalId: text(), cwd: text(32768), status: enumeration("running", "exited") }) },
1055
+ "desktop.terminals.list": { input: object(target), result: array(object({ id: text(), name: text(1024, true), scope: (v) => object({ kind: enumeration("session"), sessionId: text() })(v) || object({ kind: enumeration("project"), projectId: text() })(v), runtime: enumeration("local", "environment"), source: enumeration("user", "agent"), status: enumeration("running", "stopping", "completed", "killed", "failed"), cwd: text(32768), shell: text(32768, true), cols: positive, rows: positive, createdAt: text() }, { projectId: text(), sessionId: text(), environmentKind: enumeration("native", "wsl"), distribution: text(), command: text(65536, true), exitedAt: text(), exitCode: nullable(finite2) }), 1e4) },
1056
+ "desktop.terminals.restart": { input: object({ ...target, terminalId: text(), requestId: id }), result: object({ resourceId: text(), terminalId: text(), cwd: text(32768), status: enumeration("running", "exited") }) },
1057
+ "desktop.terminals.getRequest": { input: object({ ...target, requestId: id, original: terminalOriginal }), result: terminalReceipt },
1058
+ "desktop.terminals.snapshot": { input: object({ ...target, terminalId: text() }, { after: count, maxChars: positive }), result: object({ terminalId: text(), data: text(8 * 1024 * 1024, true), sequence: count, truncated: bool }) },
1059
+ "desktop.terminals.subscribe": { input: object({ ...target, terminalId: text() }), result: voidResult },
1060
+ "desktop.terminals.write": { input: object({ ...target, terminalId: text(), data: text(1024 * 1024, true) }), result: voidResult },
1061
+ "desktop.terminals.resize": { input: object({ ...target, terminalId: text(), cols: positive, rows: positive }), result: voidResult },
1062
+ "desktop.terminals.close": { input: (v) => object(target, { terminalId: text(), requestId: id })(v) && Object.hasOwn(v, "terminalId") !== Object.hasOwn(v, "requestId"), result: voidResult },
1063
+ "desktop.windows.open": { input: object({ ...target, requestId: id, mode: enumeration("application", "content"), url: text(32768) }), result: windowResult },
1064
+ "desktop.windows.adopt": { input: object({ ...target, requestId: id, windowId: count }), result: windowResult },
1065
+ "desktop.windows.get": { input: object({ ...target, requestId: id }), result: nullable(windowResult) },
1066
+ "desktop.windows.close": { input: object({ ...target, requestId: id }), result: windowResult },
1067
+ "desktop.windows.setAlwaysOnTop": { input: object({ ...target, alwaysOnTop: bool }, { requestId: id }), result: object({ alwaysOnTop: bool }) },
1068
+ "desktop.windows.focus": { input: object(target, { requestId: id }), result: object({ focused: bool, visible: bool, minimized: bool }) },
1069
+ "desktop.browser.register": { input: object({ ...target, tabId: text(), guestId: count }), result: validBrowserSnapshot },
1070
+ "desktop.browser.openLocalFile": { input: object({ ...target, path: text(32768) }), result: object({ url: text(32768) }) },
1071
+ "desktop.browser.unregister": { input: object({ ...target, tabId: text() }), result: voidResult },
1072
+ "desktop.browser.setActive": { input: object({ ...target, tabId: text() }), result: voidResult },
1073
+ "desktop.browser.readAnnotations": { input: object(page), result: validBrowserSnapshot },
1074
+ "desktop.browser.setAnnotationMode": { input: object({ ...page, mode }), result: validBrowserSnapshot },
1075
+ "desktop.browser.addAnnotation": { input: object({ ...page, selectionId: text(), comment: text(65536, true) }), result: validBrowserSnapshot },
1076
+ "desktop.browser.focusAnnotation": { input: object({ ...page, annotationId: text() }), result: validBrowserSnapshot },
1077
+ "desktop.browser.removeAnnotation": { input: object({ ...page, annotationId: text() }), result: validBrowserSnapshot },
1078
+ "desktop.browser.capturePreview": { input: object(page), result: object({ bytes: capturePreviewBytes, width: positive, height: positive }) },
1079
+ "desktop.pluginApps.catalog": { input: object(target), result: object({ backends: array(object({ pluginId: text(), pluginVersion: text(), pluginDigest: text(), definitionDigest: text(), backendId: text(), backendKind: enumeration("native-tools", "mcp-server"), surfaces: array(object({ id: text(), title: text(), backend: text(), resourceUri: text(8192), availability: enumeration("session") })) })) }) },
1080
+ "desktop.pluginApps.composerContext": { input: object({ ...target, contextIds: array(id, 8) }), result: array(object({ source, lease: object({ token: text(), backendGeneration: text() }), requestId: id, expectedRevision: count, text: text(8 * 1024 * 1024, true), data: json }), 8) },
1081
+ "desktop.pluginApps.open": { input: object({ ...target, requestId: id, pluginId: text(), surfaceId: text() }, { expectedRevision: count }), result: mounted },
1082
+ "desktop.pluginApps.openToolResult": { input: object({ ...target, sourcePartId: text() }), result: object({ mounted, initial: object({ sourcePartId: text(), arguments: jsonObject, result: json }, { dataError: text(128) }) }) },
1083
+ "desktop.pluginApps.mount": { input: object({ ...target, source }), result: mounted },
1084
+ "desktop.pluginApps.refresh": { input: object(mount), result: state },
1085
+ "desktop.pluginApps.rejectMenuOpen": { input: object({ ...mount, requestId: id, menuOpeningRevision: count }), result: object({ closed: bool }) },
1086
+ "desktop.pluginApps.prepareTool": { input: object({ ...action, name: text(), arguments: jsonObject }), result: object({ requestId: id, toolName: text(), args: jsonObject, expectedRevision: count }, { policy }) },
1087
+ "desktop.pluginApps.invokeTool": { input: object(action), result: (v) => actionResult(v) || object({ code: enumeration("plugin_app_busy"), notAccepted: enumeration(true), requestId: id })(v) },
1088
+ "desktop.pluginApps.getAction": { input: (v) => object(action)(v) || object({ ...target, source, requestId: id, expectedRevision: count, original: object({ toolName: text(), args: jsonObject }) })(v), result: actionResult },
1089
+ "desktop.pluginApps.cancelTool": { input: object(action), result: voidResult },
1090
+ "desktop.pluginApps.readResource": { input: object({ ...mount, source, uri: text(8192) }), result: object({ contents: array(json, 4096) }) },
1091
+ "desktop.pluginApps.listResources": { input: object({ ...mount, source }, { cursor: text(8192) }), result: object({ resources: array(json, 4096) }, { nextCursor: text(8192) }) },
1092
+ "desktop.pluginApps.listResourceTemplates": { input: object({ ...mount, source }, { cursor: text(8192) }), result: object({ resourceTemplates: array(json, 4096) }, { nextCursor: text(8192) }) },
1093
+ "desktop.pluginApps.prepareMessage": { input: object({ ...action, content: json, role: json }), result: object({ pluginId: text(), source, requestId: id, text: text(8 * 1024 * 1024, true), data: json, expectedRevision: count }) },
1094
+ "desktop.pluginApps.submitMessage": { input: object(action), result: submission },
1095
+ "desktop.pluginApps.getMessageSubmission": { input: object(action), result: submission },
1096
+ "desktop.pluginApps.cancelMessage": { input: object(action), result: voidResult },
1097
+ "desktop.pluginApps.updateModelContext": { input: object(action, { content: json, structuredContent: json }), result: object({ id: text(), source, pluginId: text(), text: text(8 * 1024 * 1024, true), data: json }) },
1098
+ "desktop.pluginApps.release": { input: object(mount), result: voidResult },
1099
+ "desktop.pluginApps.closePanel": { input: object(mount), result: voidResult },
1100
+ "desktop.pluginApps.closeApp": { input: object(action), result: object({ app: appRecord }) }
1101
+ };
1102
+ var DESKTOP_METHODS = Object.keys(rules);
1103
+ function isDesktopMethod(method) {
1104
+ return Object.hasOwn(rules, method);
1105
+ }
1106
+ function validDesktopInput(method, v) {
1107
+ return json(v) && rules[method].input(v);
1108
+ }
1109
+ function validDesktopResult(method, v) {
1110
+ return (method === "desktop.browser.capturePreview" || v === void 0 || json(v)) && rules[method].result(v);
1111
+ }
1112
+ function validDesktopResultForInput(method, input, result) {
1113
+ if (!validDesktopResult(method, result)) return false;
1114
+ if (!result || typeof result !== "object") return true;
1115
+ const params = input, value = result;
1116
+ if (Object.hasOwn(params, "requestId") && Object.hasOwn(value, "requestId") && value.requestId !== params.requestId) return false;
1117
+ if (Object.hasOwn(value, "targetId") && value.targetId !== params.targetId) return false;
1118
+ if (method.startsWith("desktop.browser.") && method !== "desktop.browser.readAnnotations" && Object.hasOwn(params, "pageRevision") && Object.hasOwn(value, "pageRevision") && value.pageRevision !== params.pageRevision) return false;
1119
+ if (method.startsWith("desktop.pluginApps.") && Object.hasOwn(params, "requestId") && Object.hasOwn(value, "receipt") && value.receipt.requestId !== params.requestId) return false;
1120
+ if ((method === "desktop.pluginApps.prepareTool" || method === "desktop.pluginApps.prepareMessage") && (value.expectedRevision !== params.expectedRevision || value.requestId !== params.requestId)) return false;
1121
+ if (method === "desktop.files.getOperation" && value.kind !== params.original.kind) return false;
1122
+ return true;
1123
+ }
1124
+ var browserChangeEvent = object(
1125
+ { type: enumeration("browser-changed"), targetId: text(), tabId: text(), pageRevision: count, snapshot: validBrowserSnapshot },
1126
+ { invalidated: enumeration(true) }
1127
+ );
1128
+ function validDesktopEvent(v) {
1129
+ const terminalEvent = (e) => object({ type: enumeration("data"), terminalId: text(), data: text(8 * 1024 * 1024, true), sequence: count })(e) || object({ type: enumeration("exit"), terminalId: text(), exitCode: nullable(finite2) })(e) || object({ type: enumeration("status"), terminalId: text(), status: enumeration("stopping", "killed") })(e) || object({ type: enumeration("title"), terminalId: text(), title: text(8192, true) })(e) || object({ type: enumeration("error"), terminalId: text(), message: text(8192, true) })(e);
1130
+ if (!json(v)) return false;
1131
+ if (browserChangeEvent(v)) {
1132
+ const event = v;
1133
+ return event.pageRevision === event.snapshot.pageRevision;
1134
+ }
1135
+ return object({ type: enumeration("browser-open-requested"), sessionId: text() })(v) || object({ type: enumeration("plugin-app-resources-changed", "plugin-app-revoked"), targetId: text(), mountId: text() })(v) || object({ type: enumeration("terminal-event"), targetId: text(), event: terminalEvent })(v);
1136
+ }
1137
+ function createAppDesktopApi(rpc, owner, filesFeature = () => {
1138
+ }) {
1139
+ const call = async (method, params) => {
1140
+ if (!validDesktopInput(method, params)) throw new AppHostError("invalid_request");
1141
+ rpc.requireFeature(method);
1142
+ const value = await rpc.request(method, params);
1143
+ if (!validDesktopResultForInput(method, params, value)) throw new AppHostError("host_unavailable");
1144
+ return value;
1145
+ };
1146
+ const group = (name2) => Object.fromEntries(DESKTOP_METHODS.filter((m) => m !== "desktop.files.openRead" && m.startsWith(`desktop.${name2}.`)).map((method) => [method.split(".")[2], (params) => call(method, params)]));
1147
+ return { bindTarget(input) {
1148
+ if (!object({ draftId: text(), draftRevision: count }, { directory: text(32768), workspaceId: text(), connection: (v) => !!v && typeof v === "object", sessionId: text() })(input)) throw new AppHostError("invalid_request");
1149
+ const { connection, ...rest } = input;
1150
+ return call("desktop.bindTarget", { ...rest, ...connection === void 0 ? {} : { connectionId: resolveClientConnection(connection, owner) } });
1151
+ }, releaseTarget: (input) => call("desktop.releaseTarget", input), files: Object.assign(group("files"), { async readFile(input, options = {}) {
1152
+ if (!object({ ...target, path: text(32768) }, { range: object({ start: count }, { end: count }) })(input) || input.range?.end !== void 0 && input.range.end < input.range.start) throw new AppHostError("invalid_request");
1153
+ filesFeature();
1154
+ const { range: range2, ...params } = input;
1155
+ const wire = await call("desktop.files.openRead", params);
1156
+ const fetchFile = owner.fetchFor(wire.connectionId, wire.baseUrl);
1157
+ try {
1158
+ return await fetchFile(wire.baseUrl + "/", { ...options.signal ? { signal: options.signal } : {}, ...range2 ? { headers: { Range: `bytes=${range2.start}-${range2.end ?? ""}` } } : {} });
1159
+ } catch (error) {
1160
+ owner.close(wire.connectionId);
1161
+ throw error;
1162
+ }
1163
+ } }), clipboard: group("clipboard"), git: group("git"), terminals: group("terminals"), windows: group("windows"), browser: group("browser"), pluginApps: group("pluginApps") };
1164
+ }
1165
+ function canonicalDesktopRequest(value) {
1166
+ if (!json(value)) throw new AppHostError("invalid_request");
1167
+ const normalize = (v) => {
1168
+ if (v === null || typeof v === "string" || typeof v === "boolean" || typeof v === "number") return v;
1169
+ if (Array.isArray(v)) return v.map(normalize);
1170
+ return Object.fromEntries(Object.keys(v).sort().map((k) => [k, normalize(v[k])]));
1171
+ };
1172
+ return JSON.stringify(normalize(value));
1173
+ }
1174
+
1175
+ // src/attachments.ts
1176
+ var ATTACHMENTS_METHODS = ["attachments.getConnection"];
1177
+ function validAttachmentsInput(v) {
1178
+ return object({ targetId: text(256) })(v);
1179
+ }
1180
+ var validAttachmentsResult = validConnection;
1181
+ function createAppAttachmentsApi(rpc, streams) {
1182
+ return { async getConnection(input) {
1183
+ if (!validAttachmentsInput(input)) throw new AppHostError("invalid_request");
1184
+ rpc.requireFeature();
1185
+ const wire = await rpc.request("attachments.getConnection", input);
1186
+ if (!validConnection(wire)) throw new AppHostError("host_unavailable");
1187
+ return createClientConnection(wire, streams);
1188
+ } };
1189
+ }
1190
+
1191
+ // src/auxiliary.ts
1192
+ var AUXILIARY_METHODS = ["sessions.getAuxiliaryOptions", "sessions.openAuxiliary", "sessions.getAuxiliary", "sessions.closeAuxiliary"];
1193
+ var selection = object({ optionsRevision: text(), model: text(), workMode: text(), effort: text(1024, true) });
1194
+ var tuple = object({ connectionId: text(), sessionId: text(), requestId: id, id: text(), selection });
1195
+ var receipt2 = object({ requestId: id, id: text(), state: enumeration("opening", "open", "closing", "closed") }, { leaseId: text(), sessionId: text() });
1196
+ function isAuxiliaryMethod(method) {
1197
+ return AUXILIARY_METHODS.includes(method);
1198
+ }
1199
+ function validAuxiliaryInput(method, v) {
1200
+ return json(v) && (method === "sessions.getAuxiliaryOptions" ? object({ connectionId: text(), sessionId: text() })(v) : tuple(v));
1201
+ }
1202
+ function validAuxiliaryResult(method, v) {
1203
+ if (!json(v)) return false;
1204
+ if (method === "sessions.getAuxiliaryOptions") {
1205
+ const choice = array(object({ id: text(), name: text() }));
1206
+ return object({ optionsRevision: text(), models: choice, workModes: choice, efforts: array(object({ id: text(1024, true), name: text() })) })(v);
1207
+ }
1208
+ if (method === "sessions.getAuxiliary") return v === null || receipt2(v);
1209
+ if (method === "sessions.closeAuxiliary") return receipt2(v);
1210
+ if (!object({ receipt: receipt2, connectionId: text(), baseUrl: text(2048) })(v)) return false;
1211
+ const wire = v;
1212
+ return wire.receipt.state === "open" && !!wire.receipt.leaseId && !!wire.receipt.sessionId && validConnection({ connectionId: wire.connectionId, baseUrl: wire.baseUrl });
1213
+ }
1214
+ function createAppAuxiliarySessionsApi(rpc, streams) {
1215
+ const request = async (method, input) => {
1216
+ if (!validAuxiliaryInput(method, input)) throw new AppHostError("invalid_request");
1217
+ rpc.requireFeature();
1218
+ const value = await rpc.request(method, input);
1219
+ if (!validAuxiliaryResult(method, value)) throw new AppHostError("host_unavailable");
1220
+ if (method !== "sessions.getAuxiliaryOptions" && value !== null) {
1221
+ const original = input;
1222
+ const settled = method === "sessions.openAuxiliary" ? value.receipt : value;
1223
+ if (settled.requestId !== original.requestId || settled.id !== original.id) throw new AppHostError("host_unavailable");
1224
+ }
1225
+ return value;
1226
+ };
1227
+ const resolve = (input) => {
1228
+ const { connection, ...rest } = input;
1229
+ return { ...rest, connectionId: resolveClientConnection(connection, streams) };
1230
+ };
1231
+ return { getAuxiliaryOptions: (input) => request("sessions.getAuxiliaryOptions", { sessionId: input.sessionId, connectionId: resolveClientConnection(input.connection, streams) }), async openAuxiliary(input) {
1232
+ const wire = await request("sessions.openAuxiliary", resolve(input));
1233
+ return { leaseId: wire.receipt.leaseId, sessionId: wire.receipt.sessionId, connection: createClientConnection(wire, streams) };
1234
+ }, getAuxiliary: (input) => request("sessions.getAuxiliary", resolve(input)), closeAuxiliary: (input) => request("sessions.closeAuxiliary", resolve(input)) };
1235
+ }
1236
+
1237
+ // src/extensions.ts
1238
+ var empty = object({});
1239
+ var cwd = object({ cwd: text(4096) });
1240
+ var plugin = object({ cwd: text(4096), pluginId: text(256) });
1241
+ var selection2 = object({ cwd: text(4096), selectionId: text(256) });
1242
+ var cancel = object({ selectionId: text(256) });
1243
+ var name = object({ name: text(256) });
1244
+ var login = object({ loginId: text(256) });
1245
+ var EXTENSION_INPUTS = {
1246
+ context: empty,
1247
+ "plugins.loadIcon": object({ src: text(8192) }),
1248
+ "plugins.snapshot": cwd,
1249
+ "plugins.enable": plugin,
1250
+ "plugins.disable": plugin,
1251
+ "plugins.uninstall": plugin,
1252
+ "plugins.reload": cwd,
1253
+ "plugins.importArchive": cwd,
1254
+ "plugins.confirmArchive": selection2,
1255
+ "plugins.cancelArchive": cancel,
1256
+ "plugins.importGit": object({ cwd: text(4096), url: text(8192) }, { ref: text(1024) }),
1257
+ "plugins.confirmGit": selection2,
1258
+ "plugins.cancelGit": cancel,
1259
+ "plugins.marketplaceCatalog": object({ cwd: text(4096) }, { refresh: bool }),
1260
+ "plugins.marketplaceAddSource": object({ url: text(8192) }),
1261
+ "plugins.marketplaceSetSourceEnabled": object({ sourceId: text(256), enabled: bool }),
1262
+ "plugins.marketplaceRemoveSource": object({ sourceId: text(256) }),
1263
+ "plugins.marketplacePreview": object({ cwd: text(4096), sourceId: text(256), pluginId: text(256) }, { version: text(256) }),
1264
+ "plugins.marketplaceConfirm": selection2,
1265
+ "plugins.marketplaceCancel": cancel,
1266
+ "plugins.marketplaceOperation": object({ cwd: text(4096), operationId: text(256) }),
1267
+ "skills.snapshot": object({ projectPath: text(4096) }),
1268
+ "skills.remove": object({ id: text(4096), expectedContent: text(8 * 1024 * 1024, true), projectPath: text(4096) }),
1269
+ "mcp.snapshot": empty,
1270
+ "mcp.exportConfig": empty,
1271
+ "mcp.getConfig": name,
1272
+ "mcp.add": object({ name: text(256), config: jsonObject }),
1273
+ "mcp.update": object({ name: text(256), config: jsonObject, expectedConfig: jsonObject }),
1274
+ "mcp.remove": name,
1275
+ "mcp.setEnabled": object({ name: text(256), enabled: bool }),
1276
+ "mcp.login": object({ name: text(256), scopes: array(text(2048), 128) }),
1277
+ "mcp.loginStatus": login,
1278
+ "mcp.cancelLogin": login,
1279
+ "mcp.logout": name
1280
+ };
1281
+ function validExtensionRequest(value) {
1282
+ if (!object({ operation: text(128), input: jsonObject })(value)) return false;
1283
+ const request = value;
1284
+ return Object.hasOwn(EXTENSION_INPUTS, request.operation) && EXTENSION_INPUTS[request.operation](request.input);
1285
+ }
1286
+ var validExtensionResult = (value) => value === void 0 || json(value);
1287
+
1288
+ // src/projects.ts
1289
+ var id2 = text(256);
1290
+ var scope = { dataScopeId: id2 };
1291
+ var project = { ...scope, projectId: id2, workspaceId: id2 };
1292
+ function validProjectRequest(value) {
1293
+ const action2 = value && typeof value === "object" ? Object.getOwnPropertyDescriptor(value, "action")?.value : void 0;
1294
+ switch (action2) {
1295
+ case "list":
1296
+ return object({ action: (v) => v === "list" })(value);
1297
+ case "register":
1298
+ return object({ action: (v) => v === "register", ...scope, workspaceId: id2 })(value);
1299
+ case "setDefaultShell":
1300
+ return object({ action: (v) => v === "setDefaultShell", ...project, shell: (v) => v === null || text(4096)(v) })(value);
1301
+ case "archive":
1302
+ return object({ action: (v) => v === "archive", ...project })(value);
1303
+ case "rebind":
1304
+ return object({ action: (v) => v === "rebind", ...scope, workspaceId: id2, previousWorkspaceId: id2 }, { projectId: id2, previousPath: text(32768) })(value);
1305
+ default:
1306
+ return false;
1307
+ }
1308
+ }
1309
+ var validProjectSnapshot = (value) => object({ dataScopeId: id2, projects: array(object({ workspaceId: id2, name: text(1024), path: text(32768), available: bool, lastOpenedAt: count }, { projectId: id2, defaultShell: text(4096) }), 1e4) })(value);
1310
+
1311
+ // ../domain-contracts/src/app-host/model-providers.ts
1312
+ var provider = text(256);
1313
+ var imageInputSupport = enumeration("native", "unsupported", "unknown");
1314
+ var limits = { contextWindow: count, maxOutputTokens: count };
1315
+ function headerValues(check) {
1316
+ return (value) => {
1317
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1318
+ const keys = Object.keys(value);
1319
+ return keys.length <= 128 && keys.every((key) => /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,256}$/.test(key)) && object(Object.fromEntries(keys.map((key) => [key, check])))(value);
1320
+ };
1321
+ }
1322
+ var headers = headerValues(text(8192, true));
1323
+ var secretHeaders = headerValues(nullable(text(8192)));
1324
+ var customProvider = object({
1325
+ id: provider,
1326
+ displayName: text(1024),
1327
+ baseUrl: text(4096),
1328
+ apiFormat: enumeration("openai"),
1329
+ models: array(object({ id: text(1024), displayName: text(1024) }, { imageInputSupport, ...limits }), 16384)
1330
+ }, { apiKey: text(8192), headers, secretHeaders });
1331
+ function validModelProviderRequest(value) {
1332
+ return object({ action: enumeration("list", "refresh") })(value) || object({ action: enumeration("connect"), provider, apiKey: text(8192) }, { headers, secretHeaders })(value) || object({ action: enumeration("updateHeaders"), provider, headers }, { secretHeaders })(value) || object({ action: enumeration("createCustom"), value: customProvider })(value) || object({ action: enumeration("updateCustom"), provider, value: customProvider })(value) || object({ action: enumeration("disconnect", "removeCustom"), provider }, { disableDefault: bool })(value) || object({ action: enumeration("disconnect", "removeCustom"), provider, replacement: object({ provider, model: text(1024) }) })(value);
1333
+ }
1334
+ var validModel = object({ id: text(1024), label: text(1024) }, { imageInputSupport, declaredLimits: object({}, limits) });
1335
+ var validConnection2 = object({
1336
+ name: provider,
1337
+ displayName: text(1024),
1338
+ connected: bool,
1339
+ active: bool,
1340
+ credentialSource: enumeration("credentials", "environment", "subscription", "local", "configured", "none"),
1341
+ models: array(validModel, 16384)
1342
+ }, { source: enumeration("builtin", "catalog", "custom", "subscription"), custom: bool, credentialLabel: text(1024), baseUrl: text(4096), headers, secretHeaderNames: array(text(256), 128) });
1343
+ function validModelProviderConnections(value) {
1344
+ return array(validConnection2, 4096)(value);
1345
+ }
1346
+ var modelId = text(1024);
1347
+ var effort = nullable(text(256));
1348
+ var revision = text(8192);
1349
+ function validProviderDefaultsRequest(value) {
1350
+ return object({ action: enumeration("snapshot") })(value) || object({ action: enumeration("updateModel"), model: modelId }, { provider, effort, expectedRevision: revision })(value) || object({ action: enumeration("updateEffort"), effort, expectedRevision: revision })(value) || object({ action: enumeration("test"), provider, model: modelId })(value);
1351
+ }
1352
+ var verifiedProvider = object({ model: modelId, checkedAt: count });
1353
+ var verified = (value) => {
1354
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1355
+ const keys = Object.keys(value);
1356
+ return keys.length <= 4096 && keys.every(provider) && object(Object.fromEntries(keys.map((key) => [key, verifiedProvider])))(value);
1357
+ };
1358
+ var defaultsModel = object({ id: modelId, label: text(1024), provider: text(1024), providerName: provider }, {
1359
+ reasoningEfforts: array(text(256, true)),
1360
+ contextWindow: count,
1361
+ inputModalities: array(text(256)),
1362
+ inputCapabilities: object({ image: imageInputSupport })
1363
+ });
1364
+ var validProviderDefaultsSnapshot = object({
1365
+ models: array(defaultsModel, 16384),
1366
+ provider: nullable(provider),
1367
+ model: nullable(modelId),
1368
+ effort,
1369
+ disabled: bool,
1370
+ revision,
1371
+ verified,
1372
+ fastModeAvailable: enumeration(false),
1373
+ fastModeReason: text(1024)
1374
+ });
1375
+ var validProviderConnectionTestResult = object({
1376
+ status: enumeration("verified", "failed"),
1377
+ detail: text(8192),
1378
+ checkedAt: count
1379
+ }, { category: enumeration("authentication", "address", "network", "model", "unsupported", "service") });
1380
+
1381
+ // src/system.ts
1382
+ var SYSTEM_SETTINGS_SECTIONS = [
1383
+ "general",
1384
+ "notifications",
1385
+ "profile",
1386
+ "appearance",
1387
+ "keyboard",
1388
+ "providers",
1389
+ "permissions",
1390
+ "personalization",
1391
+ "billing",
1392
+ "connections",
1393
+ "terminal",
1394
+ "git",
1395
+ "runtime",
1396
+ "storage",
1397
+ "diagnostics"
1398
+ ];
1399
+ var SYSTEM_SHORTCUT_IDS = [
1400
+ "searchChats",
1401
+ "newConversation",
1402
+ "chooseProject",
1403
+ "closeConversation",
1404
+ "quit",
1405
+ "toggleSidebar",
1406
+ "togglePanel",
1407
+ "openBrowser",
1408
+ "openFiles",
1409
+ "openTerminal",
1410
+ "previousSession",
1411
+ "nextSession",
1412
+ "goBack",
1413
+ "goForward",
1414
+ "zoomIn",
1415
+ "zoomOut",
1416
+ "resetZoom",
1417
+ "showShortcuts"
1418
+ ];
1419
+ var SYSTEM_METHODS = [
1420
+ "system.projects",
1421
+ "system.extensions",
1422
+ "system.modelProviders",
1423
+ "system.providerDefaults",
1424
+ "system.open",
1425
+ "system.getPresentationPreferences",
1426
+ "system.setTheme",
1427
+ "system.setWindowMaterial",
1428
+ "system.copyText",
1429
+ "system.openExternal",
1430
+ "system.markSessionRead",
1431
+ "system.navigationReady",
1432
+ "system.completeNavigation"
1433
+ ];
1434
+ var hex = (v) => typeof v === "string" && /^#[a-fA-F0-9]{6}$/.test(v);
1435
+ var palette = object({
1436
+ background: nullable(hex),
1437
+ foreground: nullable(hex)
1438
+ });
1439
+ var range = (min, max) => (v) => count(v) && v >= min && v <= max;
1440
+ var themeMode = enumeration("system", "light", "dark");
1441
+ var appearance = object({
1442
+ version: enumeration(1),
1443
+ theme: themeMode,
1444
+ accent: (v) => object({
1445
+ kind: enumeration("preset"),
1446
+ id: enumeration("neutral", "blue", "violet", "terracotta", "green")
1447
+ })(v) || object({ kind: enumeration("custom"), value: hex })(v),
1448
+ colors: object({ light: palette, dark: palette }),
1449
+ uiFont: enumeration("system", "segoe-ui", "inter"),
1450
+ codeFont: enumeration(
1451
+ "system",
1452
+ "cascadia-code",
1453
+ "cascadia-mono",
1454
+ "geist-mono",
1455
+ "consolas"
1456
+ ),
1457
+ uiFontSize: range(12, 18),
1458
+ codeFontSize: range(11, 18),
1459
+ reducedMotion: enumeration("system", "on", "off"),
1460
+ streamingTextAnimation: bool,
1461
+ glassStrength: range(0, 100)
1462
+ });
1463
+ var overrides = object(
1464
+ {},
1465
+ Object.fromEntries(
1466
+ SYSTEM_SHORTCUT_IDS.map((id3) => [
1467
+ id3,
1468
+ object({ binding: text(256, true), keys: text(128, true) })
1469
+ ])
1470
+ )
1471
+ );
1472
+ var validPresentationSnapshot = (v) => object({
1473
+ revision: count,
1474
+ appearance,
1475
+ editor: object({
1476
+ readOnly: bool,
1477
+ wordWrap: bool,
1478
+ tabSize: enumeration(2, 4)
1479
+ }),
1480
+ shortcutOverrides: overrides
1481
+ })(v);
1482
+ var validDesktopNavigationTarget = (v) => object(
1483
+ {
1484
+ id: text(256),
1485
+ dataScopeId: text(256),
1486
+ kind: enumeration("session"),
1487
+ sessionId: text(256)
1488
+ },
1489
+ { messageId: text(256), permissionId: text(256), attentionId: text(256) }
1490
+ )(v) || object(
1491
+ {
1492
+ id: text(256),
1493
+ dataScopeId: text(256),
1494
+ kind: enumeration("scheduled"),
1495
+ taskId: text(256),
1496
+ scheduledRunId: text(256)
1497
+ },
1498
+ { sessionId: text(256) }
1499
+ )(v);
1500
+ function isSystemMethod(v) {
1501
+ return SYSTEM_METHODS.includes(v);
1502
+ }
1503
+ function validSessionSettingsTarget(value) {
1504
+ if (object({
1505
+ kind: enumeration("connection"),
1506
+ connectionId: text(256),
1507
+ sessionId: text(256)
1508
+ })(value))
1509
+ return true;
1510
+ const v = value;
1511
+ if (!v || v.kind !== "fork") return false;
1512
+ const { kind: kind2, ...query } = v;
1513
+ return validSessionControlInput("sessions.getControlResult", query) && "original" in v && v.original.action === "fork";
1514
+ }
1515
+ function validSystemInput(method, value) {
1516
+ switch (method) {
1517
+ case "system.projects":
1518
+ return validProjectRequest(value);
1519
+ case "system.extensions":
1520
+ return validExtensionRequest(value);
1521
+ case "system.modelProviders":
1522
+ return validModelProviderRequest(value);
1523
+ case "system.providerDefaults":
1524
+ return validProviderDefaultsRequest(value);
1525
+ case "system.setTheme":
1526
+ return object({ theme: themeMode })(value);
1527
+ case "system.setWindowMaterial":
1528
+ return object({ preference: enumeration("glass", "opaque") })(value);
1529
+ case "system.copyText":
1530
+ return object({ text: text(8 * 1024 * 1024, true) })(value);
1531
+ case "system.openExternal":
1532
+ return object({ url: text(16384) })(value);
1533
+ case "system.open":
1534
+ return object({ page: enumeration("notes") }, { noteId: text(256) })(value) || object(
1535
+ { page: enumeration("scheduled") },
1536
+ { taskId: text(256), scheduledRunId: text(256) }
1537
+ )(value) && (!Object.hasOwn(value, "scheduledRunId") || Object.hasOwn(value, "taskId")) || object(
1538
+ { page: enumeration("extensions") },
1539
+ { tab: enumeration("plugins", "skills", "mcp") }
1540
+ )(value) || object(
1541
+ { page: enumeration("settings") },
1542
+ { section: enumeration(...SYSTEM_SETTINGS_SECTIONS) }
1543
+ )(value) || object({ page: enumeration("pet") })(value) || object(
1544
+ { page: enumeration("search") },
1545
+ { query: text(2e3, true) }
1546
+ )(value) || object({
1547
+ page: enumeration("session-settings"),
1548
+ target: validSessionSettingsTarget
1549
+ })(value);
1550
+ case "system.markSessionRead":
1551
+ return object({
1552
+ connectionId: text(256),
1553
+ sessionId: text(256),
1554
+ throughSeq: count
1555
+ })(value);
1556
+ case "system.completeNavigation":
1557
+ return object({
1558
+ id: text(256),
1559
+ status: enumeration(
1560
+ "opened",
1561
+ "unavailable",
1562
+ "permission_required",
1563
+ "cancelled"
1564
+ )
1565
+ })(value);
1566
+ default:
1567
+ return object({})(value);
1568
+ }
1569
+ }
1570
+ function validSystemResult(method, value) {
1571
+ switch (method) {
1572
+ case "system.projects":
1573
+ return validProjectSnapshot(value);
1574
+ case "system.extensions":
1575
+ return validExtensionResult(value);
1576
+ case "system.modelProviders":
1577
+ return validModelProviderConnections(value);
1578
+ case "system.providerDefaults":
1579
+ return validProviderDefaultsSnapshot(value) || validProviderConnectionTestResult(value);
1580
+ case "system.open":
1581
+ return object({ opened: enumeration(true) })(value);
1582
+ case "system.getPresentationPreferences":
1583
+ return validPresentationSnapshot(value);
1584
+ case "system.setTheme":
1585
+ return validPresentationSnapshot(value);
1586
+ case "system.navigationReady":
1587
+ return object({ pending: nullable(validDesktopNavigationTarget) })(value);
1588
+ default:
1589
+ return value === void 0;
1590
+ }
1591
+ }
1592
+ function validSystemEvent(value) {
1593
+ return object({
1594
+ type: enumeration("system-navigation-requested"),
1595
+ viewEpoch: count,
1596
+ target: validDesktopNavigationTarget
1597
+ })(value) || object({
1598
+ type: enumeration("presentation-preferences-changed"),
1599
+ revision: count
1600
+ })(value) || object({
1601
+ type: enumeration("git-preferences-changed"),
1602
+ defaultTaskLocation: enumeration("current", "worktree")
1603
+ })(value);
1604
+ }
1605
+ function createAppSystemApi(requester, connectionOwner) {
1606
+ function send(method, params) {
1607
+ requester.requireFeature();
1608
+ if (!validSystemInput(method, params))
1609
+ throw new AppHostError("invalid_request");
1610
+ return requester.request(method, params);
1611
+ }
1612
+ return {
1613
+ projects: (input) => send("system.projects", input),
1614
+ extensions: (input) => send("system.extensions", input),
1615
+ modelProviders: (input) => send("system.modelProviders", input),
1616
+ providerDefaults: (async (input) => {
1617
+ const result = await send("system.providerDefaults", input);
1618
+ if (!(input.action === "test" ? validProviderConnectionTestResult(result) : validProviderDefaultsSnapshot(result)))
1619
+ throw new AppHostError("invalid_request");
1620
+ return result;
1621
+ }),
1622
+ open: (input) => {
1623
+ if (input.page !== "session-settings") return send("system.open", input);
1624
+ const { target: target2 } = input;
1625
+ const wire = "connection" in target2 ? (() => {
1626
+ const { connection, ...rest } = target2;
1627
+ return {
1628
+ ...rest,
1629
+ connectionId: resolveClientConnection(
1630
+ connection,
1631
+ connectionOwner
1632
+ )
1633
+ };
1634
+ })() : target2;
1635
+ return send("system.open", { page: "session-settings", target: wire });
1636
+ },
1637
+ getPresentationPreferences: () => send("system.getPresentationPreferences", {}),
1638
+ setTheme: (theme) => send("system.setTheme", { theme }),
1639
+ setWindowMaterial: (preference) => send("system.setWindowMaterial", { preference }),
1640
+ copyText: (text3) => send("system.copyText", { text: text3 }),
1641
+ openExternal: (url) => send("system.openExternal", { url }),
1642
+ markSessionRead: ({ connection, sessionId, throughSeq }) => send("system.markSessionRead", {
1643
+ connectionId: resolveClientConnection(connection, connectionOwner),
1644
+ sessionId,
1645
+ throughSeq
1646
+ }),
1647
+ navigationReady: () => send("system.navigationReady", {}),
1648
+ completeNavigation: (input) => send("system.completeNavigation", input)
1649
+ };
1650
+ }
1651
+
1652
+ // src/session-resources.ts
1653
+ function resourceFields(v, required, optional = []) {
1654
+ if (!v || typeof v !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
1655
+ return required.every((k) => Object.hasOwn(v, k)) && Reflect.ownKeys(v).every((k) => {
1656
+ const d = Object.getOwnPropertyDescriptor(v, k);
1657
+ return typeof k === "string" && [...required, ...optional].includes(k) && d.enumerable && Object.hasOwn(d, "value");
1658
+ });
1659
+ }
1660
+ var str2 = (v, max = 256) => typeof v === "string" && v.length > 0 && v.length <= max;
1661
+ function validSessionResourceInput(method, v) {
1662
+ return method === "sessions.getConnection" && resourceFields(v, []);
1663
+ }
1664
+ function validSessionResourceResult(_method, v) {
1665
+ return resourceFields(v, ["connectionId", "baseUrl"], ["defaultTaskLocation"]) && (!Object.hasOwn(v, "defaultTaskLocation") || v.defaultTaskLocation === "current" || v.defaultTaskLocation === "worktree") && str2(v.connectionId) && /^[A-Za-z0-9-]+$/.test(v.connectionId) && v.baseUrl === `https://app-host.invalid/connections/${v.connectionId}`;
1666
+ }
1667
+
1668
+ // src/lifecycle.ts
1669
+ function isAppLifecycleFrame(value) {
1670
+ if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return false;
1671
+ const descriptors = Object.getOwnPropertyDescriptors(value);
1672
+ if (Reflect.ownKeys(descriptors).some((key) => typeof key !== "string" || !descriptors[key].enumerable || !Object.hasOwn(descriptors[key], "value"))) return false;
1673
+ const frame = value;
1674
+ const fields4 = frame.type === "lifecycle-prepare" ? ["protocol", "type", "id", "reason"] : frame.type === "lifecycle-cancel" ? ["protocol", "type", "id"] : frame.type === "lifecycle-result" ? ["protocol", "type", "id", "ready"] : void 0;
1675
+ if (!fields4 || Reflect.ownKeys(value).length !== fields4.length || !fields4.every((key) => Object.hasOwn(value, key)) || frame.protocol !== 1 || typeof frame.id !== "string" || !HOST_REQUEST_ID.test(frame.id)) return false;
1676
+ return frame.type === "lifecycle-prepare" ? ["switch", "reload", "disable", "quit"].includes(frame.reason) : frame.type === "lifecycle-result" ? typeof frame.ready === "boolean" : true;
1677
+ }
1678
+
1679
+ // src/protocol.ts
1680
+ var APP_HOST_PROTOCOL = 1;
1681
+ var APP_HOST_READY = "nomi.app-host.ready";
1682
+ var APP_HOST_PORT = "nomi.app-host.port";
1683
+ var APP_HOST_MAX_PENDING = 64;
1684
+ var APP_HOST_MAX_PAYLOAD_BYTES = 12 * 1024 * 1024;
1685
+ var APP_HOST_REQUEST_TIMEOUT_MS = 3e4;
1686
+ var APP_HOST_PORT_TIMEOUT_MS = 1e4;
1687
+ var APP_HOST_LOGIN_TIMEOUT_MS = 3e5;
1688
+ var APP_HOST_LOGIN_TRANSPORT_TIMEOUT_MS = APP_HOST_LOGIN_TIMEOUT_MS + 3e4;
1689
+ var APP_HOST_METHODS = [
1690
+ "connect",
1691
+ "negotiate",
1692
+ "getContext",
1693
+ "storage.get",
1694
+ "storage.set",
1695
+ "storage.delete",
1696
+ "sessions.getConnection",
1697
+ "service.getStatus",
1698
+ "service.getConnection",
1699
+ "service.listWork",
1700
+ "service.getWork",
1701
+ "service.interruptWork",
1702
+ "storage.putFile",
1703
+ "storage.readFile",
1704
+ "storage.deleteFile",
1705
+ "auth.openLogin",
1706
+ "workspace.select",
1707
+ "workspace.getSelection",
1708
+ "workspace.get",
1709
+ "workspace.listFiles",
1710
+ "workspace.readText",
1711
+ ...COMMANDS_METHODS,
1712
+ ...RESOURCE_CATALOG_METHODS,
1713
+ ...CONVERSATION_PREPARATION_METHODS,
1714
+ ...DESKTOP_METHODS,
1715
+ ...ATTACHMENTS_METHODS,
1716
+ ...AUXILIARY_METHODS,
1717
+ ...SYSTEM_METHODS,
1718
+ ...WINDOW_METHODS
1719
+ ];
1720
+ export {
1721
+ APP_HOST_ERROR_RETRY,
1722
+ APP_HOST_FEATURES,
1723
+ APP_HOST_LOGIN_TIMEOUT_MS,
1724
+ APP_HOST_LOGIN_TRANSPORT_TIMEOUT_MS,
1725
+ APP_HOST_MAX_PAYLOAD_BYTES,
1726
+ APP_HOST_MAX_PENDING,
1727
+ APP_HOST_METHODS,
1728
+ APP_HOST_PORT,
1729
+ APP_HOST_PORT_TIMEOUT_MS,
1730
+ APP_HOST_PROTOCOL,
1731
+ APP_HOST_READY,
1732
+ APP_HOST_REQUEST_TIMEOUT_MS,
1733
+ ATTACHMENTS_METHODS,
1734
+ AUXILIARY_METHODS,
1735
+ AppHostError,
1736
+ BROWSER_CAPTURE_PREVIEW_MAX_BYTES,
1737
+ COMMANDS_METHODS,
1738
+ DESKTOP_METHODS,
1739
+ EXTENSION_INPUTS,
1740
+ FETCH_CHUNK_BYTES,
1741
+ FETCH_HEADERS_TIMEOUT_MS,
1742
+ FETCH_IDLE_TIMEOUT_MS,
1743
+ FETCH_INLINE_BODY_BYTES,
1744
+ FETCH_MAX_STREAMS,
1745
+ FETCH_METADATA_BYTES,
1746
+ FETCH_WINDOW_CHUNKS,
1747
+ HOST_REQUEST_ID,
1748
+ RESOURCE_CATALOG_METHODS,
1749
+ SERVICE_HOST_MAX_FRAME_BYTES,
1750
+ SERVICE_HOST_MAX_PENDING,
1751
+ SERVICE_HOST_METHODS,
1752
+ SYSTEM_METHODS,
1753
+ SYSTEM_SETTINGS_SECTIONS,
1754
+ SYSTEM_SHORTCUT_IDS,
1755
+ WINDOW_METHODS,
1756
+ appHostErrorMessage,
1757
+ canonicalDesktopRequest,
1758
+ createAppAttachmentsApi,
1759
+ createAppAuxiliarySessionsApi,
1760
+ createAppCommandsApi,
1761
+ createAppDesktopApi,
1762
+ createAppSystemApi,
1763
+ createAppWindowApi,
1764
+ createResourceCatalogApi,
1765
+ isAppHostErrorInfo,
1766
+ isAppLifecycleFrame,
1767
+ isAuxiliaryMethod,
1768
+ isCommandsMethod,
1769
+ isConversationPreparationMethod,
1770
+ isDesktopMethod,
1771
+ isPageFetchFrame,
1772
+ isResourceCatalogMethod,
1773
+ isSafeErrorDetails,
1774
+ isServiceHostFrame,
1775
+ isSystemMethod,
1776
+ isWindowMethod,
1777
+ matchAgentApiRoute,
1778
+ normalizeAgentApiPath,
1779
+ pageFetchPath,
1780
+ validAppCommandSnapshot,
1781
+ validAppWindowState,
1782
+ validAttachmentsInput,
1783
+ validAttachmentsResult,
1784
+ validAuxiliaryInput,
1785
+ validAuxiliaryResult,
1786
+ validBrowserSnapshot,
1787
+ validCommandInvocation,
1788
+ validCommandReceipt,
1789
+ validCommandsInput,
1790
+ validConversationPreparationInput,
1791
+ validConversationPreparationResult,
1792
+ validDesktopEvent,
1793
+ validDesktopInput,
1794
+ validDesktopNavigationTarget,
1795
+ validDesktopResult,
1796
+ validDesktopResultForInput,
1797
+ validDesktopTarget,
1798
+ validExtensionRequest,
1799
+ validExtensionResult,
1800
+ validPresentationSnapshot,
1801
+ validProjectRequest,
1802
+ validProjectSnapshot,
1803
+ validResourceCatalogInput,
1804
+ validResourceCatalogResult,
1805
+ validResourceChanged,
1806
+ validServiceContext,
1807
+ validServiceHostInput,
1808
+ validServiceHostResult,
1809
+ validSessionResourceInput,
1810
+ validSessionResourceResult,
1811
+ validSessionSettingsTarget,
1812
+ validSystemEvent,
1813
+ validSystemInput,
1814
+ validSystemResult,
1815
+ validWindowEvent,
1816
+ validWindowInput,
1817
+ validWindowResult,
1818
+ validWorkspaceInput,
1819
+ validWorkspaceOperation,
1820
+ validWorkspaceResult
1821
+ };
1822
+ //# sourceMappingURL=protocol.js.map