@bobannomi/app-host 0.0.0-stage → 0.1.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1473 @@
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, empty = false) => (v) => typeof v === "string" && (empty || 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
+ function object(required, optional = {}) {
111
+ return (v) => {
112
+ if (!v || typeof v !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
113
+ if (Object.keys(required).some((k) => !Object.hasOwn(v, k))) return false;
114
+ return Reflect.ownKeys(v).every((k) => {
115
+ const d = Object.getOwnPropertyDescriptor(v, k);
116
+ return typeof k === "string" && d.enumerable && Object.hasOwn(d, "value") && (required[k] ?? optional[k])?.(d.value) === true;
117
+ });
118
+ };
119
+ }
120
+ function array(check, max = 1024) {
121
+ return (v) => {
122
+ if (!Array.isArray(v) || Object.getPrototypeOf(v) !== Array.prototype || v.length > max || Reflect.ownKeys(v).length !== v.length + 1) return false;
123
+ for (let i = 0; i < v.length; i++) {
124
+ const d = Object.getOwnPropertyDescriptor(v, String(i));
125
+ if (!d?.enumerable || !Object.hasOwn(d, "value") || !check(d.value)) return false;
126
+ }
127
+ return true;
128
+ };
129
+ }
130
+ var json = (value) => {
131
+ let size = 0;
132
+ const seen = /* @__PURE__ */ new Set();
133
+ const visit = (v, depth) => {
134
+ if (depth > 64 || size > 12 * 1024 * 1024) return false;
135
+ if (v === null || typeof v === "boolean") {
136
+ size += 5;
137
+ return true;
138
+ }
139
+ if (typeof v === "string") {
140
+ size += new TextEncoder().encode(v).byteLength + 2;
141
+ return size <= 12 * 1024 * 1024;
142
+ }
143
+ if (typeof v === "number") {
144
+ size += 32;
145
+ return Number.isFinite(v);
146
+ }
147
+ if (!v || typeof v !== "object" || seen.has(v)) return false;
148
+ const list = Array.isArray(v);
149
+ if (list ? Object.getPrototypeOf(v) !== Array.prototype : ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
150
+ seen.add(v);
151
+ try {
152
+ const keys = Reflect.ownKeys(v);
153
+ if (list && keys.length !== v.length + 1) return false;
154
+ return keys.every((k) => {
155
+ if (list && k === "length") return true;
156
+ const d = Object.getOwnPropertyDescriptor(v, k);
157
+ size += typeof k === "string" ? k.length + 3 : 0;
158
+ 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);
159
+ });
160
+ } finally {
161
+ seen.delete(v);
162
+ }
163
+ };
164
+ return visit(value, 0) && size <= 12 * 1024 * 1024;
165
+ };
166
+ var jsonObject = (v) => !!v && typeof v === "object" && !Array.isArray(v) && json(v);
167
+ var digest = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
168
+ var wireConnection = object({ connectionId: text(256), baseUrl: text(2048) });
169
+
170
+ // ../domain-contracts/src/app-host/agent.ts
171
+ function fields(value, required, optional = []) {
172
+ if (!value || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
173
+ return false;
174
+ return required.every((key) => Object.hasOwn(value, key)) && Reflect.ownKeys(value).every((key) => {
175
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
176
+ return typeof key === "string" && [...required, ...optional].includes(key) && descriptor.enumerable && Object.hasOwn(descriptor, "value");
177
+ });
178
+ }
179
+ var text2 = (value) => typeof value === "string" && value.trim().length > 0;
180
+ 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);
181
+ function rows(value, check) {
182
+ return Array.isArray(value) && value.length <= 1024 && value.every(check);
183
+ }
184
+ function validAgentInput(method, value) {
185
+ if (!json(value)) return false;
186
+ if (method === "agent.listModels" || method === "agent.listRoles") return fields(value, []);
187
+ 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;
188
+ if (method !== "agent.getConnection" || !fields(value, [], ["workspaceId", "executionRoot", "privateSessionId"])) return false;
189
+ 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"));
190
+ }
191
+ function validAgentResult(method, value) {
192
+ if (!json(value)) return false;
193
+ switch (method) {
194
+ case "agent.getConnection":
195
+ 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);
196
+ case "agent.listModels":
197
+ return rows(
198
+ value,
199
+ (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)
200
+ );
201
+ case "agent.listRoles":
202
+ return rows(
203
+ value,
204
+ (row) => fields(row, ["id", "name", "description"]) && text2(row.id) && text2(row.name) && typeof row.description === "string"
205
+ );
206
+ case "agent.resolveSkills":
207
+ return rows(
208
+ value,
209
+ (row) => fields(row, ["type", "name", "path"]) && row.type === "skill" && text2(row.name) && text2(row.path)
210
+ );
211
+ }
212
+ }
213
+
214
+ // ../domain-contracts/src/app-host/workspace-conversations.ts
215
+ var validWorkspaceConversation = (value) => {
216
+ if (!object(
217
+ { dataScopeId: text(), requestId: id, sessionId: id, taskLocation: enumeration("current", "worktree"), configuration: json },
218
+ { workspaceId: id, outsideProject: (v) => v === true, preparationRevision: text() }
219
+ )(value)) return false;
220
+ const input = value;
221
+ return input.workspaceId !== void 0 ? input.outsideProject !== true : input.outsideProject === true && input.taskLocation === "current";
222
+ };
223
+ var sessionText = (value) => typeof value === "string";
224
+ var sessionRecord = object({
225
+ id,
226
+ cwd: sessionText,
227
+ title: sessionText,
228
+ model: sessionText,
229
+ status: enumeration("idle", "running", "closing", "archived", "error"),
230
+ metadata: jsonObject,
231
+ createdAt: count,
232
+ updatedAt: count
233
+ }, {
234
+ storage: enumeration("sqlite", "memory"),
235
+ parentId: sessionText,
236
+ projectId: sessionText,
237
+ cwdRelative: sessionText,
238
+ agent: sessionText,
239
+ archivedAt: count
240
+ });
241
+ var workspaceConversationResult = object({
242
+ dataScopeId: text(),
243
+ sessionId: id,
244
+ requestId: id,
245
+ action: (v) => v === "create-session",
246
+ state: enumeration("prepared", "completed", "unknown")
247
+ }, {
248
+ configuration: json,
249
+ revision: count,
250
+ session: sessionRecord,
251
+ operationState: enumeration("prepared", "running", "completed", "failed", "unknown"),
252
+ indexBindingPending: (v) => v === true,
253
+ workspaceId: id,
254
+ executionRoot: id,
255
+ privateSessionId: id,
256
+ worktree: json
257
+ });
258
+ var validWorkspaceConversationResult = (value) => {
259
+ if (!workspaceConversationResult(value)) return false;
260
+ const result = value;
261
+ return !result.session || result.state === "completed" && result.session.id === result.sessionId;
262
+ };
263
+
264
+ // ../domain-contracts/src/app-host/session-controls.ts
265
+ var option = object({ id: text(), name: text() });
266
+ var choices = array(option);
267
+ var effortChoices = array(object({ id: text(1024, true), name: text() }));
268
+ var receiptShape = object({ dataScopeId: text(), sessionId: text(), requestId: id, action: enumeration("fork", "configure", "compact"), state: enumeration("prepared", "created", "completed", "unknown") }, { revision: count, targetSessionId: text() });
269
+ var receipt = receiptShape;
270
+ function validSessionControlOriginal(value) {
271
+ if (!object({ action: text(), body: json })(value)) return false;
272
+ const v = value;
273
+ if (v.action === "compact") return object({ requestId: id, expectedRevision: count })(v.body);
274
+ return v.action === "fork" && object({ requestId: id, id: text() }, { copyHistory: bool, beforeMessageId: text(), afterMessageId: text(), storage: enumeration("sqlite") })(v.body);
275
+ }
276
+ function validSessionControlInput(method, value) {
277
+ if (!json(value)) return false;
278
+ if (method === "sessions.getDraftComposerOptions") {
279
+ if (!object({ source: enumeration("instance") }, { workspaceId: id, outsideProject: bool, roleId: (v2) => v2 === null || text(256)(v2) })(value)) return false;
280
+ const target = value;
281
+ return target.workspaceId !== void 0 ? target.outsideProject !== true : target.outsideProject === true;
282
+ }
283
+ if (method === "sessions.bindConversationIndex") return object({ original: validWorkspaceConversation, dataScopeId: text() })(value);
284
+ if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult") return validWorkspaceConversation(value);
285
+ if (method === "sessions.getControls") return object({ connectionId: text(), sessionId: text() })(value);
286
+ if (!object({ requestId: id, sessionId: text(), original: validSessionControlOriginal }, { connectionId: text() })(value)) return false;
287
+ const v = value;
288
+ return v.original.body.requestId === v.requestId && !!v.connectionId;
289
+ }
290
+ function validSessionControlResult(method, value) {
291
+ if (!json(value)) return false;
292
+ 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);
293
+ if (method === "sessions.bindConversationIndex") return validWorkspaceConversationResult(value);
294
+ if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult")
295
+ return method === "sessions.getConversationCreationResult" && value === null || validWorkspaceConversationResult(value);
296
+ 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);
297
+ if (method === "sessions.getControlResult") return value === null || receipt(value);
298
+ if (!receipt(value)) return false;
299
+ return false;
300
+ }
301
+
302
+ // ../domain-contracts/src/app-host/service.ts
303
+ function fields2(value, required, optional = []) {
304
+ if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
305
+ return false;
306
+ return required.every((k) => Object.hasOwn(value, k)) && Reflect.ownKeys(value).every((k) => {
307
+ const d = Object.getOwnPropertyDescriptor(value, k);
308
+ return typeof k === "string" && [...required, ...optional].includes(k) && d.enumerable && Object.hasOwn(d, "value");
309
+ });
310
+ }
311
+ 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(
312
+ v
313
+ );
314
+ function json2(value, ancestors = /* @__PURE__ */ new Set(), depth = 0) {
315
+ if (depth > 100) return false;
316
+ if (value === null || typeof value === "string" || typeof value === "boolean")
317
+ return true;
318
+ if (typeof value === "number") return Number.isFinite(value);
319
+ if (typeof value !== "object" || ancestors.has(value)) return false;
320
+ const array2 = Array.isArray(value);
321
+ if (array2 ? Object.getPrototypeOf(value) !== Array.prototype || Reflect.ownKeys(value).length !== value.length + 1 : ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
322
+ return false;
323
+ ancestors.add(value);
324
+ const result = Reflect.ownKeys(value).every((k) => {
325
+ if (array2 && k === "length") return true;
326
+ const d = Object.getOwnPropertyDescriptor(value, k);
327
+ 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);
328
+ });
329
+ ancestors.delete(value);
330
+ return result;
331
+ }
332
+ function validServiceStatus(value) {
333
+ return fields2(value, ["state"], ["reason", "instanceId", "apiVersion"]) && [
334
+ "absent",
335
+ "unauthorized",
336
+ "stopped",
337
+ "starting",
338
+ "recovering",
339
+ "ready",
340
+ "failed"
341
+ ].includes(value.state) && (!Object.hasOwn(value, "reason") || [
342
+ "dependency_missing",
343
+ "service_start_failed",
344
+ "service_unavailable",
345
+ "result_unknown",
346
+ "incompatible",
347
+ "revoked"
348
+ ].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"));
349
+ }
350
+ function validWork(value) {
351
+ return fields2(value, ["requestId", "state", "updatedAt"], ["result", "error"]) && typeof value.requestId === "string" && HOST_REQUEST_ID.test(value.requestId) && [
352
+ "not_accepted",
353
+ "accepted",
354
+ "running",
355
+ "completed",
356
+ "failed",
357
+ "interrupted",
358
+ "unknown"
359
+ ].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(
360
+ value.updatedAt
361
+ ) && Number.isFinite(Date.parse(value.updatedAt)) && ["result", "error"].every(
362
+ (k) => !Object.hasOwn(value, k) || json2(value[k]) && new TextEncoder().encode(JSON.stringify(value[k])).length <= 16384
363
+ );
364
+ }
365
+ function validServiceResult(method, value) {
366
+ switch (method) {
367
+ case "service.getStatus":
368
+ return validServiceStatus(value);
369
+ case "service.getConnection":
370
+ 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);
371
+ case "service.getWork":
372
+ return validWork(value);
373
+ case "service.listWork":
374
+ return Array.isArray(value) && value.length <= 5120 && value.every(validWork) && new Set(value.map((w) => w.requestId)).size === value.length;
375
+ case "service.interruptWork":
376
+ return fields2(value, ["requested"]) && typeof value.requested === "boolean";
377
+ }
378
+ }
379
+
380
+ // ../domain-contracts/src/app-host/fetch.ts
381
+ var FETCH_CHUNK_BYTES = 64 * 1024;
382
+ var FETCH_INLINE_BODY_BYTES = 8 * 1024;
383
+ var FETCH_WINDOW_CHUNKS = 4;
384
+ var FETCH_MAX_STREAMS = 16;
385
+ var FETCH_METADATA_BYTES = 64 * 1024;
386
+ var FETCH_HEADERS_TIMEOUT_MS = 3e4;
387
+ var FETCH_IDLE_TIMEOUT_MS = 12e4;
388
+ function isPageFetchFrame(value) {
389
+ let size = 0;
390
+ const visit = (entry, depth, binary = false) => {
391
+ if (depth > 10) return false;
392
+ if (entry instanceof Uint8Array) {
393
+ if (!binary || Object.getPrototypeOf(entry) !== Uint8Array.prototype || ["buffer", "byteLength", "byteOffset", "length"].some((key) => Object.hasOwn(entry, key))) return false;
394
+ const buffer = entry.buffer;
395
+ return buffer instanceof ArrayBuffer && !Object.hasOwn(buffer, "byteLength") && buffer.byteLength <= FETCH_CHUNK_BYTES && entry.byteLength > 0 && entry.byteLength <= FETCH_CHUNK_BYTES;
396
+ }
397
+ if (entry === null || typeof entry === "boolean" || typeof entry === "number" && Number.isFinite(entry)) {
398
+ size += 8;
399
+ return true;
400
+ }
401
+ if (typeof entry === "string") {
402
+ size += new TextEncoder().encode(entry).byteLength + 2;
403
+ return size <= FETCH_METADATA_BYTES;
404
+ }
405
+ if (!entry || typeof entry !== "object") return false;
406
+ const array2 = Array.isArray(entry);
407
+ if (array2 ? Object.getPrototypeOf(entry) !== Array.prototype : ![Object.prototype, null].includes(Object.getPrototypeOf(entry))) return false;
408
+ const keys = Reflect.ownKeys(entry);
409
+ if (keys.length > FETCH_METADATA_BYTES || array2 && keys.length !== entry.length + 1) return false;
410
+ return keys.every((key) => {
411
+ if (array2 && key === "length") return true;
412
+ const d = Object.getOwnPropertyDescriptor(entry, key);
413
+ size += typeof key === "string" ? key.length + 3 : 0;
414
+ 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;
415
+ });
416
+ };
417
+ if (!visit(value, 0) || !value || typeof value !== "object" || Array.isArray(value)) return false;
418
+ const v = value;
419
+ if (v.protocol !== 2 || typeof v.type !== "string") return false;
420
+ const fields3 = {
421
+ "fetch-open": ["id", "connectionId", "url", "method", "headers", "hasBody"],
422
+ "fetch-headers": ["id", "status", "statusText", "headers", "hasBody"],
423
+ "fetch-credit": ["id", "direction", "sequence", "chunks", "bytes"],
424
+ "fetch-chunk": ["id", "direction", "sequence", "bytes"],
425
+ "fetch-end": ["id", "direction", "sequence"],
426
+ "fetch-consumed": ["id", "direction", "sequence"],
427
+ "fetch-cancel": ["id"],
428
+ "fetch-error": ["id", "error"],
429
+ "fetch-close": ["connectionId"]
430
+ };
431
+ const required = fields3[v.type];
432
+ const inline = v.type === "fetch-open" && Object.hasOwn(v, "inlineBody");
433
+ if (!required || Object.keys(v).length !== required.length + 2 + Number(inline) || !required.every((k) => Object.hasOwn(v, k))) return false;
434
+ if (inline && (v.hasBody !== true || typeof v.inlineBody !== "string" || new TextEncoder().encode(v.inlineBody).byteLength > FETCH_INLINE_BODY_BYTES)) return false;
435
+ const id2 = (x) => typeof x === "string" && x.length > 0 && x.length <= 128;
436
+ if (v.type === "fetch-close") return id2(v.connectionId);
437
+ if (!id2(v.id)) return false;
438
+ if (v.type === "fetch-consumed") return v.direction === "download" && Number.isSafeInteger(v.sequence) && v.sequence >= 0;
439
+ if (["fetch-chunk", "fetch-credit", "fetch-end"].includes(v.type) && (!["upload", "download"].includes(v.direction) || !Number.isSafeInteger(v.sequence) || v.sequence < 0)) return false;
440
+ 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;
441
+ if (v.type === "fetch-chunk") return v.bytes instanceof Uint8Array;
442
+ if (v.type === "fetch-error") return isAppHostErrorInfo(v.error);
443
+ if (v.type === "fetch-open" || v.type === "fetch-headers") {
444
+ 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;
445
+ if (v.type === "fetch-open") return id2(v.connectionId) && typeof v.url === "string" && typeof v.method === "string" && /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(v.method);
446
+ return Number.isInteger(v.status) && v.status >= 200 && v.status <= 599 && typeof v.statusText === "string";
447
+ }
448
+ return true;
449
+ }
450
+ function pageFetchPath(baseUrl, input) {
451
+ if (/[\\\s#]/.test(input)) throw new TypeError("Invalid fetch URL");
452
+ const rawPath = input.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/]+/, "").split("?")[0];
453
+ 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");
454
+ const base = new URL(baseUrl), url = new URL(input);
455
+ 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");
456
+ return (url.pathname.slice(base.pathname.length) || "/") + url.search;
457
+ }
458
+
459
+ // ../domain-contracts/src/app-host/service-host-protocol.ts
460
+ var SERVICE_HOST_METHODS = ["secrets.get", "secrets.set", "secrets.delete", "context.get", "context.resolveInvocation", "agent.listModels", "agent.listRoles", "agent.getConnection", "agent.resolveSkills", "sessions.getConnection", "sessions.getControls", "sessions.getControlResult", "workspace.gitStatus", "workspace.createTaskWorktree", "workspace.getWorktree", "workspace.releaseExecutionRoot", "work.list", "work.get"];
461
+ var SERVICE_HOST_MAX_FRAME_BYTES = 512 * 1024;
462
+ var SERVICE_HOST_MAX_PENDING = 64;
463
+ 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);
464
+ var worktreeBody = { workspaceId: id, expectedHead: text(256), branch: text(1024) };
465
+ var worktreeReceipt = object({ requestId: id, state: enumeration("accepted", "completed", "failed", "unknown") }, { result: object({ executionRoot: id, workspaceId: id, branch: text(1024), sourceHead: text(256) }) });
466
+ function validServiceHostInput(method, v) {
467
+ if (!json(v)) return false;
468
+ if (method.startsWith("agent.")) return validAgentInput(method, v);
469
+ if (["sessions.getControls", "sessions.getControlResult"].includes(method)) return validSessionControlInput(method, v) && (method !== "sessions.getControlResult" || object({ connectionId: text(256), requestId: id, sessionId: text(), original: () => true })(v));
470
+ switch (method) {
471
+ case "secrets.get":
472
+ case "secrets.delete":
473
+ return object({ key: (x) => typeof x === "string" && /^[a-zA-Z0-9._:-]{1,128}$/.test(x) })(v);
474
+ case "secrets.set":
475
+ return object({ key: (x) => typeof x === "string" && /^[a-zA-Z0-9._:-]{1,128}$/.test(x), value: text(16384) })(v);
476
+ case "context.get":
477
+ case "work.list":
478
+ return object({})(v);
479
+ case "context.resolveInvocation":
480
+ return object({ ticket: text(8192) })(v);
481
+ case "sessions.getConnection":
482
+ return object({ dataScopeId: text(256), sessionId: text(256) })(v);
483
+ case "workspace.gitStatus":
484
+ return object({ workspaceId: id })(v);
485
+ case "workspace.createTaskWorktree":
486
+ return object({ requestId: id, ...worktreeBody })(v);
487
+ case "workspace.getWorktree":
488
+ return object({ requestId: id, original: object(worktreeBody) })(v);
489
+ case "workspace.releaseExecutionRoot":
490
+ return object({ requestId: id, workspaceId: id, executionRoot: id })(v);
491
+ case "work.get":
492
+ return object({ requestId: id })(v);
493
+ default:
494
+ return false;
495
+ }
496
+ }
497
+ function validServiceHostResult(method, v) {
498
+ if (!json(v)) return false;
499
+ if (method.startsWith("agent.")) return validAgentResult(method, v);
500
+ if (["sessions.getControls", "sessions.getControlResult"].includes(method)) return validSessionControlResult(method, v);
501
+ switch (method) {
502
+ case "secrets.get":
503
+ return v === null || text(16384)(v);
504
+ case "secrets.set":
505
+ return object({ stored: enumeration(true) })(v);
506
+ case "secrets.delete":
507
+ return object({ deleted: enumeration(true) })(v);
508
+ case "context.get":
509
+ return validServiceContext(v);
510
+ case "context.resolveInvocation":
511
+ return object({ invocationId: id, dataScopeId: text(256), sessionId: text(256), runId: text(256) }, { inputId: text(256), workspaceId: id, executionRoot: id, privateSessionId: id })(v);
512
+ case "sessions.getConnection":
513
+ return validAgentResult("agent.getConnection", v);
514
+ case "workspace.gitStatus":
515
+ return object({ root: text(32768), commonDir: text(32768), head: text(256), branch: text(1024, true), changes: array(text(32768), 1e4) })(v);
516
+ case "workspace.createTaskWorktree":
517
+ return worktreeReceipt(v);
518
+ case "workspace.getWorktree":
519
+ return v === null || worktreeReceipt(v);
520
+ case "workspace.releaseExecutionRoot":
521
+ return object({ requestId: id, executionRoot: id, state: enumeration("released", "retained-dirty", "in-use", "unknown") })(v);
522
+ case "work.list":
523
+ return validServiceResult("service.listWork", v);
524
+ case "work.get":
525
+ return v === null || validServiceResult("service.getWork", v);
526
+ default:
527
+ return false;
528
+ }
529
+ }
530
+ function isServiceHostFrame(v) {
531
+ if (isPageFetchFrame(v)) return true;
532
+ 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;
533
+ const frame = v;
534
+ switch (frame.type) {
535
+ case "service-host-connect":
536
+ return object({ protocol: enumeration(1), type: enumeration(frame.type), id })(v);
537
+ case "service-host-ready":
538
+ return object({ protocol: enumeration(1), type: enumeration(frame.type), id, context: validServiceContext })(v);
539
+ case "service-host-context":
540
+ return object({ protocol: enumeration(1), type: enumeration(frame.type), context: validServiceContext })(v);
541
+ case "service-host-close":
542
+ return object({ protocol: enumeration(1), type: enumeration(frame.type) })(v);
543
+ case "service-host-request":
544
+ return object({ protocol: enumeration(1), type: enumeration(frame.type), id, method: enumeration(...SERVICE_HOST_METHODS), params: (x) => validServiceHostInput(frame.method, x) })(v);
545
+ case "service-host-response":
546
+ 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);
547
+ default:
548
+ return false;
549
+ }
550
+ }
551
+
552
+ // src/client-connections.ts
553
+ var connections = /* @__PURE__ */ new WeakMap();
554
+ function createClientConnection(wire, streams) {
555
+ const record = { owner: streams, id: wire.connectionId, closed: false };
556
+ 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() {
557
+ return record.closed || streams.isClosed?.(wire.connectionId) === true;
558
+ }, close() {
559
+ if (!record.closed) {
560
+ record.closed = true;
561
+ streams.close(wire.connectionId);
562
+ }
563
+ } };
564
+ connections.set(connection, record);
565
+ return connection;
566
+ }
567
+ function resolveClientConnection(connection, owner) {
568
+ const record = connections.get(connection);
569
+ if (!record || record.owner !== owner || record.closed || owner.isClosed?.(record.id)) throw new AppHostError("connection_revoked");
570
+ return record.id;
571
+ }
572
+
573
+ // src/node/agent.ts
574
+ function createAppAgentApi(rpc, streams) {
575
+ const request = async (method, params) => {
576
+ const value = await rpc.request(method, params);
577
+ if (!validAgentResult(method, value))
578
+ throw new AppHostError("host_unavailable");
579
+ return value;
580
+ };
581
+ return {
582
+ async getConnection(input = {}) {
583
+ if (!validAgentInput("agent.getConnection", input))
584
+ throw new AppHostError("invalid_request");
585
+ const wire = await request(
586
+ "agent.getConnection",
587
+ input
588
+ );
589
+ return createClientConnection(wire, streams);
590
+ },
591
+ listModels: () => request("agent.listModels", {}),
592
+ listRoles: () => request("agent.listRoles", {}),
593
+ async resolveSkills(skillIds) {
594
+ if (!Array.isArray(skillIds) || skillIds.length > 128 || !skillIds.every((value) => typeof value === "string" && value.trim().length > 0) || new Set(skillIds).size !== skillIds.length)
595
+ throw new AppHostError("invalid_request");
596
+ return request("agent.resolveSkills", { skillIds });
597
+ }
598
+ };
599
+ }
600
+
601
+ // src/node/session-controls.ts
602
+ function createSessionControlsApi(rpc, streams) {
603
+ const call = async (method, params) => {
604
+ if (!validSessionControlInput(method, params)) throw new AppHostError("invalid_request");
605
+ rpc.requireFeature();
606
+ const result = await rpc.request(method, params);
607
+ if (!validSessionControlResult(method, result)) throw new AppHostError("host_unavailable");
608
+ if (result && "sessionId" in result && "sessionId" in params && result.sessionId !== params.sessionId) throw new AppHostError("host_unavailable");
609
+ if (result && "requestId" in result && "requestId" in params && result.requestId !== params.requestId) throw new AppHostError("host_unavailable");
610
+ if (method === "sessions.getControlResult" && result) {
611
+ const query = params, settled = result;
612
+ if (settled.action !== query.original.action || query.original.action === "fork" && settled.targetSessionId !== query.original.body.id) throw new AppHostError("host_unavailable");
613
+ }
614
+ return result;
615
+ };
616
+ const connectionValue = (v) => !!v && typeof v === "object";
617
+ return {
618
+ getControls(value) {
619
+ if (!object({ connection: connectionValue, sessionId: text() })(value)) throw new AppHostError("invalid_request");
620
+ const { connection, ...input } = value;
621
+ return call("sessions.getControls", { ...input, connectionId: resolveClientConnection(connection, streams) });
622
+ },
623
+ getControlResult(value) {
624
+ if (!object({ requestId: id, sessionId: text(), original: validSessionControlOriginal }, { connection: connectionValue })(value)) throw new AppHostError("invalid_request");
625
+ const { connection, ...input } = value;
626
+ return call("sessions.getControlResult", { ...input, ...connection ? { connectionId: resolveClientConnection(connection, streams) } : {} });
627
+ }
628
+ };
629
+ }
630
+
631
+ // src/node/transport.ts
632
+ import process from "node:process";
633
+
634
+ // src/transport/fetch-client.ts
635
+ function createPageFetchClient(options) {
636
+ const streams = /* @__PURE__ */ new Map(), closedTargets = /* @__PURE__ */ new Set();
637
+ let nextId = 0, closed = false;
638
+ let offMessage = () => {
639
+ }, offClose = () => {
640
+ };
641
+ const error = (code) => new AppHostError(code);
642
+ const send = (frame) => {
643
+ try {
644
+ options.send(frame);
645
+ } catch {
646
+ const reason = error("host_unavailable");
647
+ if ("id" in frame) {
648
+ const s = streams.get(frame.id);
649
+ if (s) finish(s, reason);
650
+ }
651
+ shutdown();
652
+ throw reason;
653
+ }
654
+ };
655
+ const finish = (s, reason, notify = false) => {
656
+ if (s.stopped) return;
657
+ s.stopped = true;
658
+ streams.delete(s.id);
659
+ s.wake?.();
660
+ s.wake = void 0;
661
+ clearTimeout(s.headTimer);
662
+ clearTimeout(s.idleTimer);
663
+ s.offAbort();
664
+ if (notify) {
665
+ try {
666
+ send({ protocol: 2, type: "fetch-cancel", id: s.id });
667
+ } catch {
668
+ shutdown();
669
+ }
670
+ }
671
+ if (reason) {
672
+ s.reject(reason);
673
+ try {
674
+ s.controller?.error(reason);
675
+ } catch {
676
+ }
677
+ }
678
+ if (s.reader) {
679
+ const reader = s.reader;
680
+ s.reader = void 0;
681
+ void reader.cancel(reason).catch(() => {
682
+ }).finally(() => {
683
+ try {
684
+ reader.releaseLock();
685
+ } catch {
686
+ }
687
+ });
688
+ } else if (!s.uploadDone) void s.request.body?.cancel(reason).catch(() => {
689
+ });
690
+ };
691
+ const complete = (s) => {
692
+ if (s.uploadDone && s.downloadDone) finish(s);
693
+ };
694
+ const consumeDownload = (s) => {
695
+ if (s.stopped || !s.downloadEnded || s.downloadDone || s.controller && s.controller.desiredSize !== FETCH_WINDOW_CHUNKS) return;
696
+ s.downloadDone = true;
697
+ s.controller?.close();
698
+ send({ protocol: 2, type: "fetch-consumed", id: s.id, direction: "download", sequence: s.downloadSequence });
699
+ complete(s);
700
+ };
701
+ const touch = (s) => {
702
+ if (s.stopped || closed) return;
703
+ clearTimeout(s.idleTimer);
704
+ s.idleTimer = setTimeout(() => finish(s, error("host_unavailable"), true), FETCH_IDLE_TIMEOUT_MS);
705
+ };
706
+ const shutdown = () => {
707
+ if (closed) return;
708
+ closed = true;
709
+ offMessage();
710
+ offClose();
711
+ for (const s of [...streams.values()]) finish(s, error("connection_revoked"));
712
+ closedTargets.clear();
713
+ };
714
+ const pump = async (s) => {
715
+ if (s.pumping || s.stopped || s.uploadDone) return;
716
+ s.pumping = true;
717
+ try {
718
+ s.reader ??= s.request.body.getReader();
719
+ const reader = s.reader;
720
+ while (!s.stopped && s.credit > 0) {
721
+ const item = await reader.read();
722
+ if (s.stopped) return;
723
+ if (item.done) {
724
+ s.uploadDone = true;
725
+ s.reader = void 0;
726
+ reader.releaseLock();
727
+ send({ protocol: 2, type: "fetch-end", id: s.id, direction: "upload", sequence: s.uploadSequence });
728
+ complete(s);
729
+ return;
730
+ }
731
+ if (!(item.value instanceof Uint8Array)) throw error("invalid_request");
732
+ for (let offset = 0; offset < item.value.byteLength; ) {
733
+ if (s.stopped) return;
734
+ if (!s.credit) {
735
+ await new Promise((resolve) => {
736
+ s.wake = resolve;
737
+ });
738
+ s.wake = void 0;
739
+ if (s.stopped) return;
740
+ }
741
+ const bytes = new Uint8Array(item.value.subarray(offset, offset + FETCH_CHUNK_BYTES));
742
+ s.credit--;
743
+ offset += bytes.byteLength;
744
+ send({ protocol: 2, type: "fetch-chunk", id: s.id, direction: "upload", sequence: s.uploadSequence++, bytes });
745
+ if (s.stopped || closed) return;
746
+ touch(s);
747
+ }
748
+ }
749
+ } catch {
750
+ finish(s, error("host_unavailable"), true);
751
+ } finally {
752
+ s.pumping = false;
753
+ }
754
+ };
755
+ const stopTarget = (connectionId) => {
756
+ closedTargets.add(connectionId);
757
+ for (const s of [...streams.values()]) if (s.connectionId === connectionId) finish(s, error("connection_revoked"));
758
+ };
759
+ const receive = (message) => {
760
+ if (!message || typeof message !== "object" || typeof Object.getOwnPropertyDescriptor(message, "type")?.value !== "string" || !Object.getOwnPropertyDescriptor(message, "type").value.startsWith("fetch-")) return;
761
+ if (!isPageFetchFrame(message)) {
762
+ shutdown();
763
+ return;
764
+ }
765
+ if (message.type === "fetch-close" && options.allowsTargetClose?.()) {
766
+ stopTarget(message.connectionId);
767
+ return;
768
+ }
769
+ if (!("id" in message)) {
770
+ shutdown();
771
+ return;
772
+ }
773
+ const s = streams.get(message.id);
774
+ if (!s) return;
775
+ touch(s);
776
+ try {
777
+ switch (message.type) {
778
+ case "fetch-headers": {
779
+ if (s.headers || message.hasBody && (s.request.method === "HEAD" || [204, 205, 304].includes(message.status))) throw error("invalid_request");
780
+ s.headers = true;
781
+ clearTimeout(s.headTimer);
782
+ const body = message.hasBody ? new ReadableStream({
783
+ start(controller) {
784
+ s.controller = controller;
785
+ },
786
+ pull(controller) {
787
+ if (s.stopped || s.downloadDone) return;
788
+ touch(s);
789
+ if (s.downloadEnded) {
790
+ consumeDownload(s);
791
+ return;
792
+ }
793
+ const slots = Math.floor(controller.desiredSize ?? 0) - s.outstanding;
794
+ if (slots > 0) {
795
+ s.outstanding += slots;
796
+ try {
797
+ send({ protocol: 2, type: "fetch-credit", id: s.id, direction: "download", sequence: s.grantSequence++, chunks: slots, bytes: slots * FETCH_CHUNK_BYTES });
798
+ } catch {
799
+ finish(s, error("host_unavailable"), true);
800
+ }
801
+ }
802
+ },
803
+ cancel() {
804
+ finish(s, error("connection_revoked"), true);
805
+ }
806
+ }, { highWaterMark: FETCH_WINDOW_CHUNKS, size: () => 1 }) : null;
807
+ const response = new Response(body, { status: message.status, statusText: message.statusText, headers: message.headers });
808
+ s.resolve(response);
809
+ if (!message.hasBody) {
810
+ s.downloadEnded = true;
811
+ consumeDownload(s);
812
+ }
813
+ break;
814
+ }
815
+ case "fetch-credit":
816
+ if (message.direction !== "upload") throw error("invalid_request");
817
+ if (s.uploadDone) break;
818
+ if (message.sequence !== s.creditSequence++ || s.credit + message.chunks > FETCH_WINDOW_CHUNKS) throw error("invalid_request");
819
+ s.credit += message.chunks;
820
+ s.wake?.();
821
+ void pump(s);
822
+ break;
823
+ case "fetch-chunk":
824
+ if (message.direction !== "download" || !s.headers || s.downloadEnded || message.sequence !== s.downloadSequence++ || s.outstanding <= 0) throw error("invalid_request");
825
+ s.outstanding--;
826
+ s.controller.enqueue(message.bytes);
827
+ break;
828
+ case "fetch-end":
829
+ if (message.direction !== "download" || !s.headers || s.downloadEnded || message.sequence !== s.downloadSequence) throw error("invalid_request");
830
+ s.downloadEnded = true;
831
+ consumeDownload(s);
832
+ break;
833
+ case "fetch-error":
834
+ finish(s, new AppHostError(message.error.code, appHostErrorMessage(message.error.code, message.error.details), { ...message.error.requestId ? { requestId: message.error.requestId } : {}, ...message.error.details === void 0 ? {} : { details: message.error.details } }));
835
+ break;
836
+ case "fetch-cancel":
837
+ finish(s, error("connection_revoked"));
838
+ break;
839
+ default:
840
+ throw error("invalid_request");
841
+ }
842
+ } catch {
843
+ finish(s, error("host_unavailable"), true);
844
+ }
845
+ };
846
+ offMessage = options.onMessage(receive);
847
+ offClose = options.onClose(shutdown);
848
+ if (closed) {
849
+ offMessage();
850
+ offClose();
851
+ }
852
+ return {
853
+ fetchFor(connectionId, baseUrl) {
854
+ pageFetchPath(baseUrl, baseUrl);
855
+ return async (input, init) => {
856
+ if (closed || closedTargets.has(connectionId)) throw error("connection_revoked");
857
+ const inputUrl = input instanceof Request ? input.url : String(input);
858
+ const request = new Request(input, init);
859
+ const id2 = String(nextId + 1);
860
+ let frame;
861
+ try {
862
+ pageFetchPath(baseUrl, inputUrl);
863
+ pageFetchPath(baseUrl, request.url);
864
+ if (request.signal.aborted) throw new DOMException("The operation was aborted", "AbortError");
865
+ if (streams.size >= FETCH_MAX_STREAMS) throw error("invalid_request");
866
+ frame = { protocol: 2, type: "fetch-open", id: id2, connectionId, url: request.url, method: request.method, headers: [...request.headers], hasBody: !!request.body };
867
+ if (!isPageFetchFrame(frame)) throw error("invalid_request");
868
+ const body = init?.body;
869
+ if (options.allowsInlineBody?.() && typeof body === "string" && body.length <= FETCH_INLINE_BODY_BYTES && request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() === "application/json") {
870
+ const inline = { ...frame, inlineBody: body };
871
+ if (isPageFetchFrame(inline)) frame = inline;
872
+ }
873
+ } catch (reason) {
874
+ void request.body?.cancel(reason).catch(() => {
875
+ });
876
+ throw reason;
877
+ }
878
+ nextId++;
879
+ return new Promise((resolve, reject) => {
880
+ const abort = () => finish(s, new DOMException("The operation was aborted", "AbortError"), true);
881
+ const s = {
882
+ id: id2,
883
+ connectionId,
884
+ request,
885
+ resolve,
886
+ reject,
887
+ headers: false,
888
+ stopped: false,
889
+ uploadDone: !request.body || frame.inlineBody !== void 0,
890
+ downloadEnded: false,
891
+ downloadDone: false,
892
+ pumping: false,
893
+ credit: 0,
894
+ creditSequence: 0,
895
+ uploadSequence: 0,
896
+ outstanding: 0,
897
+ grantSequence: 0,
898
+ downloadSequence: 0,
899
+ headTimer: setTimeout(() => finish(s, error("host_unavailable"), true), FETCH_HEADERS_TIMEOUT_MS),
900
+ idleTimer: setTimeout(() => finish(s, error("host_unavailable"), true), FETCH_IDLE_TIMEOUT_MS),
901
+ offAbort: () => request.signal.removeEventListener("abort", abort)
902
+ };
903
+ streams.set(id2, s);
904
+ request.signal.addEventListener("abort", abort, { once: true });
905
+ try {
906
+ send(frame);
907
+ } catch {
908
+ finish(s, error("host_unavailable"));
909
+ shutdown();
910
+ }
911
+ });
912
+ };
913
+ },
914
+ isClosed(connectionId) {
915
+ return closed || closedTargets.has(connectionId);
916
+ },
917
+ close(connectionId) {
918
+ if (closed || closedTargets.has(connectionId)) return;
919
+ const frame = { protocol: 2, type: "fetch-close", connectionId };
920
+ if (!isPageFetchFrame(frame)) throw error("invalid_request");
921
+ stopTarget(connectionId);
922
+ try {
923
+ send(frame);
924
+ } catch {
925
+ shutdown();
926
+ }
927
+ }
928
+ };
929
+ }
930
+
931
+ // src/node/transport.ts
932
+ var TIMEOUT = 3e4;
933
+ async function connectServiceTransport(ipc = process) {
934
+ if (!ipc.connected || !ipc.send) throw new AppHostError("host_unavailable");
935
+ const handshake = crypto.randomUUID();
936
+ let closed = false;
937
+ let context;
938
+ const pending = /* @__PURE__ */ new Map();
939
+ const messages = /* @__PURE__ */ new Set(), closes = /* @__PURE__ */ new Set();
940
+ const targets = /* @__PURE__ */ new Set();
941
+ const readiness = /* @__PURE__ */ new Set();
942
+ let resolveHandshake, rejectHandshake;
943
+ const initial = new Promise((resolve, reject) => {
944
+ resolveHandshake = resolve;
945
+ rejectHandshake = reject;
946
+ });
947
+ const close = (reason = new AppHostError("connection_revoked")) => {
948
+ if (closed) return;
949
+ closed = true;
950
+ clearTimeout(handshakeTimer);
951
+ ipc.removeListener("message", receive);
952
+ ipc.removeListener("disconnect", disconnected);
953
+ rejectHandshake(reason);
954
+ for (const p of pending.values()) {
955
+ clearTimeout(p.timer);
956
+ p.reject(reason);
957
+ }
958
+ pending.clear();
959
+ for (const waiter of readiness) waiter.reject(reason);
960
+ readiness.clear();
961
+ for (const listener of closes) listener();
962
+ closes.clear();
963
+ messages.clear();
964
+ };
965
+ const send = (frame) => {
966
+ if (closed) throw new AppHostError("connection_revoked");
967
+ if (!isServiceHostFrame(frame)) throw new AppHostError("invalid_request");
968
+ try {
969
+ ipc.send(frame, (error) => {
970
+ if (error) close(new AppHostError("host_unavailable"));
971
+ });
972
+ } catch {
973
+ close(new AppHostError("host_unavailable"));
974
+ throw new AppHostError("host_unavailable");
975
+ }
976
+ };
977
+ const acceptContext = (next) => {
978
+ if (context) {
979
+ if (next.registrationId !== context.registrationId || next.instanceId !== context.instanceId || next.dataScopeId !== context.dataScopeId || next.scope.appId !== context.scope.appId || next.scope.installationId !== context.scope.installationId || next.scope.contentDigest !== context.scope.contentDigest || next.installationRevision !== context.installationRevision) throw new AppHostError("connection_revoked");
980
+ const transition = next.phase === context.phase || context.phase === "starting" && next.phase === "ready";
981
+ if (!transition) throw new AppHostError("connection_revoked");
982
+ }
983
+ context = next;
984
+ if (next.phase === "ready") {
985
+ for (const waiter of readiness) waiter.resolve(next);
986
+ readiness.clear();
987
+ }
988
+ };
989
+ const receive = (v) => {
990
+ try {
991
+ if (!isServiceHostFrame(v)) throw new AppHostError("host_unavailable");
992
+ if (v.type === "service-host-ready") {
993
+ if (context || v.id !== handshake) throw new AppHostError("host_unavailable");
994
+ acceptContext(v.context);
995
+ clearTimeout(handshakeTimer);
996
+ resolveHandshake(v.context);
997
+ return;
998
+ }
999
+ if (!context) throw new AppHostError("host_unavailable");
1000
+ if (isPageFetchFrame(v)) {
1001
+ for (const listener of messages) listener(v);
1002
+ return;
1003
+ }
1004
+ if (v.type === "service-host-context") {
1005
+ acceptContext(v.context);
1006
+ return;
1007
+ }
1008
+ if (v.type === "service-host-close") {
1009
+ close();
1010
+ return;
1011
+ }
1012
+ if (v.type !== "service-host-response") throw new AppHostError("host_unavailable");
1013
+ const p = pending.get(v.id);
1014
+ if (!p) return;
1015
+ if (v.ok && (!validServiceHostResult(p.method, v.value) || !correlated(p.params, v.value))) throw new AppHostError("host_unavailable");
1016
+ clearTimeout(p.timer);
1017
+ pending.delete(v.id);
1018
+ if (v.ok) {
1019
+ if (p.method === "context.get") acceptContext(v.value);
1020
+ p.resolve(v.value);
1021
+ } else {
1022
+ p.reject(new AppHostError(v.error.code, appHostErrorMessage(v.error.code, v.error.details), { ...v.error.requestId ? { requestId: v.error.requestId } : {}, ...v.error.details === void 0 ? {} : { details: v.error.details } }));
1023
+ if (v.error.code === "connection_revoked") close();
1024
+ }
1025
+ } catch {
1026
+ close(new AppHostError("host_unavailable"));
1027
+ }
1028
+ };
1029
+ const disconnected = () => close();
1030
+ const handshakeTimer = setTimeout(() => close(new AppHostError("host_unavailable")), TIMEOUT);
1031
+ ipc.on("message", receive);
1032
+ ipc.on("disconnect", disconnected);
1033
+ const baseStreams = createPageFetchClient({ send, onMessage: (listener) => {
1034
+ messages.add(listener);
1035
+ return () => {
1036
+ messages.delete(listener);
1037
+ };
1038
+ }, onClose: (listener) => {
1039
+ closes.add(listener);
1040
+ return () => {
1041
+ closes.delete(listener);
1042
+ };
1043
+ } });
1044
+ const streams = {
1045
+ fetchFor(id2, base) {
1046
+ const fetcher = baseStreams.fetchFor(id2, base);
1047
+ targets.add(id2);
1048
+ return (input, init) => {
1049
+ if (closed || !targets.has(id2)) return Promise.reject(new AppHostError("connection_revoked"));
1050
+ return fetcher(input, init);
1051
+ };
1052
+ },
1053
+ close(id2) {
1054
+ targets.delete(id2);
1055
+ baseStreams.close(id2);
1056
+ }
1057
+ };
1058
+ try {
1059
+ send({ protocol: 1, type: "service-host-connect", id: handshake });
1060
+ await initial;
1061
+ } catch (error) {
1062
+ close();
1063
+ throw error;
1064
+ }
1065
+ return {
1066
+ streams,
1067
+ request(method, params) {
1068
+ if (closed) return Promise.reject(new AppHostError("connection_revoked"));
1069
+ if ("connectionId" in params && typeof params.connectionId === "string" && !targets.has(params.connectionId)) return Promise.reject(new AppHostError("connection_revoked"));
1070
+ if (!validServiceHostInput(method, params) || pending.size >= SERVICE_HOST_MAX_PENDING) return Promise.reject(new AppHostError("invalid_request"));
1071
+ return new Promise((resolve, reject) => {
1072
+ const id2 = crypto.randomUUID();
1073
+ const mutation = ["workspace.createTaskWorktree", "workspace.releaseExecutionRoot"].includes(method);
1074
+ const requestId = mutation && "requestId" in params && typeof params.requestId === "string" ? params.requestId : void 0;
1075
+ const timer = setTimeout(() => {
1076
+ pending.delete(id2);
1077
+ reject(new AppHostError(requestId ? "result_unknown" : "host_unavailable", void 0, requestId ? { requestId } : {}));
1078
+ }, TIMEOUT);
1079
+ pending.set(id2, { method, params, resolve: (value) => resolve(value), reject, timer });
1080
+ try {
1081
+ send({ protocol: 1, type: "service-host-request", id: id2, method, params });
1082
+ } catch (error) {
1083
+ clearTimeout(timer);
1084
+ pending.delete(id2);
1085
+ reject(error);
1086
+ }
1087
+ });
1088
+ },
1089
+ whenReady() {
1090
+ if (closed) return Promise.reject(new AppHostError("connection_revoked"));
1091
+ if (context.phase === "ready") return Promise.resolve(context);
1092
+ return new Promise((resolve, reject) => {
1093
+ readiness.add({ resolve, reject });
1094
+ });
1095
+ },
1096
+ close() {
1097
+ if (!closed) {
1098
+ try {
1099
+ send({ protocol: 1, type: "service-host-close" });
1100
+ } finally {
1101
+ close();
1102
+ }
1103
+ }
1104
+ }
1105
+ };
1106
+ }
1107
+ function correlated(params, value) {
1108
+ if (!value || typeof value !== "object") return true;
1109
+ const result = value;
1110
+ return ["requestId", "sessionId", "executionRoot"].every((key) => !(key in params) || !(key in result) || result[key] === params[key]);
1111
+ }
1112
+
1113
+ // ../tools/src/schedule/scheduled-task-tools.ts
1114
+ function createScheduleTools(host) {
1115
+ const port = host && !("invoke" in host) ? host : void 0;
1116
+ function unavailable() {
1117
+ return {
1118
+ content: [
1119
+ {
1120
+ type: "text",
1121
+ text: "This host does not provide Agent scheduled tasks."
1122
+ }
1123
+ ],
1124
+ isError: true
1125
+ };
1126
+ }
1127
+ const scheduleCreateTool = {
1128
+ name: "ScheduleCreate",
1129
+ description: "Create a persistent Agent task that runs once or on an RRULE schedule. Chat destinations inherit the current conversation runtime; model, effort, permissionProfile, and projectPaths are automatically ignored for chat tasks.",
1130
+ inputSchema: {
1131
+ type: "object",
1132
+ properties: {
1133
+ name: { type: "string" },
1134
+ prompt: {
1135
+ type: "string",
1136
+ description: "Durable instructions for every scheduled Agent run"
1137
+ },
1138
+ recurrence: {
1139
+ type: "string",
1140
+ description: "ISO timestamp for once, or RFC 5545 RRULE"
1141
+ },
1142
+ recurrenceFormat: { type: "string", enum: ["rrule", "once"] },
1143
+ timezone: { type: "string", description: "IANA timezone" },
1144
+ destination: {
1145
+ type: "string",
1146
+ enum: ["standalone", "chat"],
1147
+ description: "Use chat to run in and return to the current conversation; use standalone for runtime overrides or worktree isolation"
1148
+ },
1149
+ projectPaths: { type: "array", items: { type: "string" } },
1150
+ executionMode: {
1151
+ type: "string",
1152
+ enum: ["local", "worktree"],
1153
+ default: "local"
1154
+ },
1155
+ model: { type: "string" },
1156
+ effort: { type: "string" },
1157
+ skillNames: { type: "array", items: { type: "string" } },
1158
+ pluginNames: { type: "array", items: { type: "string" } },
1159
+ permissionModeId: {
1160
+ type: "string",
1161
+ enum: ["ask", "auto_review", "full_access"]
1162
+ },
1163
+ workMode: { type: "string", enum: ["execute", "plan"] },
1164
+ pluginSelectionPolicy: { type: "string", enum: ["auto", "none"] },
1165
+ permissionProfile: permissionProfileSchema(),
1166
+ overlapPolicy: { type: "string", enum: ["skip", "queue"] },
1167
+ missedRunPolicy: { type: "string", enum: ["skip", "run_once"] },
1168
+ stopPolicy: {
1169
+ type: "object",
1170
+ properties: {
1171
+ runOnce: { type: "boolean" },
1172
+ maxRuns: { type: "number" },
1173
+ stopWhenCompleted: { type: "boolean" },
1174
+ expiresAt: { type: "number" }
1175
+ }
1176
+ }
1177
+ },
1178
+ required: [
1179
+ "name",
1180
+ "prompt",
1181
+ "recurrence",
1182
+ "recurrenceFormat",
1183
+ "timezone",
1184
+ "destination"
1185
+ ]
1186
+ },
1187
+ async execute(input, context) {
1188
+ const schedules = port;
1189
+ if (!schedules) return unavailable();
1190
+ try {
1191
+ const destination = input.destination === "chat" ? "chat" : "standalone";
1192
+ const permissionProfile = parsePermissionProfile(
1193
+ input.permissionProfile
1194
+ );
1195
+ const task = await schedules.create({
1196
+ name: String(input.name ?? ""),
1197
+ prompt: String(input.prompt ?? ""),
1198
+ recurrence: String(input.recurrence ?? ""),
1199
+ recurrenceFormat: input.recurrenceFormat === "once" ? "once" : "rrule",
1200
+ timezone: String(input.timezone ?? "UTC"),
1201
+ destination,
1202
+ ...destination === "chat" && context.sessionId ? { sessionId: context.sessionId } : {},
1203
+ projectPaths: destination === "chat" ? [] : Array.isArray(input.projectPaths) ? input.projectPaths.map(String) : [],
1204
+ executionMode: input.executionMode === "worktree" ? "worktree" : "local",
1205
+ ...destination === "standalone" && typeof input.model === "string" ? { model: input.model } : {},
1206
+ ...destination === "standalone" && typeof input.effort === "string" ? { effort: input.effort } : {},
1207
+ ...Array.isArray(input.skillNames) ? { skillNames: input.skillNames.map(String) } : {},
1208
+ ...Array.isArray(input.pluginNames) ? { pluginNames: input.pluginNames.map(String) } : {},
1209
+ ...destination === "standalone" && ["ask", "auto_review", "full_access"].includes(
1210
+ String(input.permissionModeId)
1211
+ ) ? {
1212
+ permissionModeId: input.permissionModeId
1213
+ } : {},
1214
+ ...destination === "standalone" && (input.workMode === "execute" || input.workMode === "plan") ? { workMode: input.workMode } : {},
1215
+ ...destination === "standalone" && (input.pluginSelectionPolicy === "auto" || input.pluginSelectionPolicy === "none") ? { pluginSelectionPolicy: input.pluginSelectionPolicy } : {},
1216
+ ...destination === "standalone" && permissionProfile ? { permissionProfile } : {},
1217
+ ...input.overlapPolicy === "queue" || input.overlapPolicy === "skip" ? { overlapPolicy: input.overlapPolicy } : {},
1218
+ ...input.missedRunPolicy === "run_once" || input.missedRunPolicy === "skip" ? { missedRunPolicy: input.missedRunPolicy } : {},
1219
+ ...input.stopPolicy && typeof input.stopPolicy === "object" ? { stopPolicy: input.stopPolicy } : {}
1220
+ });
1221
+ return {
1222
+ content: [
1223
+ {
1224
+ type: "text",
1225
+ text: `Scheduled '${task.name}' (${task.id}); next run ${task.nextRunAt ? new Date(task.nextRunAt).toISOString() : "not scheduled"}.`
1226
+ }
1227
+ ]
1228
+ };
1229
+ } catch (error) {
1230
+ return failed(error);
1231
+ }
1232
+ }
1233
+ };
1234
+ const scheduleListTool = {
1235
+ name: "ScheduleList",
1236
+ description: "List persistent Agent scheduled tasks.",
1237
+ inputSchema: { type: "object", properties: {} },
1238
+ async execute() {
1239
+ const schedules = port;
1240
+ if (!schedules) return unavailable();
1241
+ try {
1242
+ const tasks = await schedules.list();
1243
+ return {
1244
+ content: [
1245
+ {
1246
+ type: "text",
1247
+ text: tasks.length === 0 ? "No Agent scheduled tasks configured." : tasks.map(
1248
+ (task) => `${task.id} ${task.name} [${task.status}] ${task.recurrence}`
1249
+ ).join("\n")
1250
+ }
1251
+ ]
1252
+ };
1253
+ } catch (error) {
1254
+ return failed(error);
1255
+ }
1256
+ }
1257
+ };
1258
+ const scheduleUpdateTool = {
1259
+ name: "ScheduleUpdate",
1260
+ description: "Update, pause, resume, or complete an Agent scheduled task.",
1261
+ inputSchema: {
1262
+ type: "object",
1263
+ properties: {
1264
+ id: { type: "string" },
1265
+ name: { type: "string" },
1266
+ prompt: { type: "string" },
1267
+ recurrence: { type: "string" },
1268
+ recurrenceFormat: { type: "string", enum: ["rrule", "once"] },
1269
+ timezone: { type: "string" },
1270
+ status: { type: "string", enum: ["active", "paused", "completed"] },
1271
+ stopPolicy: {
1272
+ type: "object",
1273
+ properties: {
1274
+ runOnce: { type: "boolean" },
1275
+ maxRuns: { type: "number" },
1276
+ stopWhenCompleted: { type: "boolean" },
1277
+ expiresAt: { type: "number" }
1278
+ }
1279
+ },
1280
+ model: { type: "string" },
1281
+ effort: { type: "string" },
1282
+ skillNames: { type: "array", items: { type: "string" } },
1283
+ pluginNames: { type: "array", items: { type: "string" } },
1284
+ permissionModeId: {
1285
+ type: "string",
1286
+ enum: ["ask", "auto_review", "full_access"]
1287
+ },
1288
+ workMode: { type: "string", enum: ["execute", "plan"] },
1289
+ pluginSelectionPolicy: { type: "string", enum: ["auto", "none"] },
1290
+ permissionProfile: permissionProfileSchema(),
1291
+ overlapPolicy: { type: "string", enum: ["skip", "queue"] },
1292
+ missedRunPolicy: { type: "string", enum: ["skip", "run_once"] }
1293
+ },
1294
+ required: ["id"]
1295
+ },
1296
+ async execute(input) {
1297
+ const schedules = port;
1298
+ if (!schedules) return unavailable();
1299
+ try {
1300
+ const patch = Object.fromEntries(
1301
+ [
1302
+ "name",
1303
+ "prompt",
1304
+ "recurrence",
1305
+ "recurrenceFormat",
1306
+ "timezone",
1307
+ "status",
1308
+ "model",
1309
+ "effort",
1310
+ "skillNames",
1311
+ "pluginNames",
1312
+ "permissionModeId",
1313
+ "workMode",
1314
+ "pluginSelectionPolicy",
1315
+ "permissionProfile",
1316
+ "overlapPolicy",
1317
+ "missedRunPolicy",
1318
+ "stopPolicy"
1319
+ ].filter((key) => input[key] !== void 0).map((key) => [key, input[key]])
1320
+ );
1321
+ const task = await schedules.update(String(input.id ?? ""), patch);
1322
+ return {
1323
+ content: [
1324
+ { type: "text", text: `Updated '${task.name}' (${task.status}).` }
1325
+ ]
1326
+ };
1327
+ } catch (error) {
1328
+ return failed(error);
1329
+ }
1330
+ }
1331
+ };
1332
+ const scheduleDeleteTool = {
1333
+ name: "ScheduleDelete",
1334
+ description: "Delete an Agent scheduled task and its run projections.",
1335
+ inputSchema: {
1336
+ type: "object",
1337
+ properties: { id: { type: "string" } },
1338
+ required: ["id"]
1339
+ },
1340
+ async execute(input) {
1341
+ const schedules = port;
1342
+ if (!schedules) return unavailable();
1343
+ try {
1344
+ await schedules.remove(String(input.id ?? ""));
1345
+ return {
1346
+ content: [
1347
+ { type: "text", text: `Deleted scheduled task '${input.id}'.` }
1348
+ ]
1349
+ };
1350
+ } catch (error) {
1351
+ return failed(error);
1352
+ }
1353
+ }
1354
+ };
1355
+ const scheduleRunNowTool = {
1356
+ name: "ScheduleRunNow",
1357
+ description: "Run an Agent scheduled task immediately.",
1358
+ inputSchema: {
1359
+ type: "object",
1360
+ properties: { id: { type: "string" } },
1361
+ required: ["id"]
1362
+ },
1363
+ async execute(input) {
1364
+ const schedules = port;
1365
+ if (!schedules) return unavailable();
1366
+ try {
1367
+ const run = await schedules.trigger(String(input.id ?? ""));
1368
+ const accepted = run.status === "queued" || run.status === "running";
1369
+ return {
1370
+ content: [
1371
+ {
1372
+ type: "text",
1373
+ text: accepted ? `Scheduled run '${run.id}' is ${run.status}.` : run.summary ?? run.error ?? `Scheduled run ${run.status}.`
1374
+ }
1375
+ ],
1376
+ ...!accepted && run.status !== "succeeded" ? { isError: true } : {}
1377
+ };
1378
+ } catch (error) {
1379
+ return failed(error);
1380
+ }
1381
+ }
1382
+ };
1383
+ const tools = [
1384
+ scheduleCreateTool,
1385
+ scheduleListTool,
1386
+ scheduleUpdateTool,
1387
+ scheduleDeleteTool,
1388
+ scheduleRunNowTool
1389
+ ];
1390
+ if (host && "invoke" in host) {
1391
+ return tools.map((tool) => ({
1392
+ ...tool,
1393
+ execute: (input, context) => host.invoke(tool.name, input, context)
1394
+ }));
1395
+ }
1396
+ return tools;
1397
+ }
1398
+ function failed(error) {
1399
+ return {
1400
+ content: [
1401
+ {
1402
+ type: "text",
1403
+ text: error instanceof Error ? error.message : String(error)
1404
+ }
1405
+ ],
1406
+ isError: true
1407
+ };
1408
+ }
1409
+ function permissionProfileSchema() {
1410
+ return {
1411
+ type: "object",
1412
+ properties: {
1413
+ mode: {
1414
+ type: "string",
1415
+ enum: ["read_only", "workspace_write", "full_access"]
1416
+ },
1417
+ network: { type: "boolean" },
1418
+ allowedTools: { type: "array", items: { type: "string" } },
1419
+ deniedTools: { type: "array", items: { type: "string" } }
1420
+ },
1421
+ required: ["mode"]
1422
+ };
1423
+ }
1424
+ function parsePermissionProfile(value) {
1425
+ if (!value || typeof value !== "object" || Array.isArray(value))
1426
+ return void 0;
1427
+ const input = value;
1428
+ const mode = input.mode;
1429
+ if (mode !== "read_only" && mode !== "workspace_write" && mode !== "full_access") {
1430
+ return void 0;
1431
+ }
1432
+ return {
1433
+ mode,
1434
+ ...typeof input.network === "boolean" ? { network: input.network } : {},
1435
+ ...Array.isArray(input.allowedTools) ? { allowedTools: input.allowedTools.map(String) } : {},
1436
+ ...Array.isArray(input.deniedTools) ? { deniedTools: input.deniedTools.map(String) } : {}
1437
+ };
1438
+ }
1439
+
1440
+ // src/node/service-host.ts
1441
+ var serviceHost;
1442
+ function connectServiceHost() {
1443
+ return serviceHost ??= createServiceHost();
1444
+ }
1445
+ async function createServiceHost() {
1446
+ const transport = await connectServiceTransport();
1447
+ const request = transport.request;
1448
+ const controls = createSessionControlsApi({ requireFeature() {
1449
+ }, request(method, params) {
1450
+ if (method === "sessions.getControls") return request(method, params);
1451
+ if (method === "sessions.getControlResult") return request(method, params);
1452
+ throw new TypeError("Unsupported service method");
1453
+ } }, transport.streams);
1454
+ return {
1455
+ secrets: { get: (key) => request("secrets.get", { key }), set: (key, value) => request("secrets.set", { key, value }).then(() => {
1456
+ }), delete: (key) => request("secrets.delete", { key }).then(() => {
1457
+ }) },
1458
+ context: { get: () => request("context.get", {}), whenReady: transport.whenReady, resolveInvocation: (ticket) => request("context.resolveInvocation", { ticket }) },
1459
+ agent: createAppAgentApi({ request: (method, params) => request(method, params) }, transport.streams),
1460
+ sessions: { getControls: controls.getControls, getControlResult: controls.getControlResult, async getConnection(input) {
1461
+ const wire = await request("sessions.getConnection", input);
1462
+ return createClientConnection(wire, transport.streams);
1463
+ } },
1464
+ workspace: { gitStatus: (input) => request("workspace.gitStatus", input), createTaskWorktree: (input) => request("workspace.createTaskWorktree", input), getWorktree: (input) => request("workspace.getWorktree", input), releaseExecutionRoot: (input) => request("workspace.releaseExecutionRoot", input) },
1465
+ work: { list: () => request("work.list", {}), get: (requestId) => request("work.get", { requestId }) },
1466
+ close: transport.close
1467
+ };
1468
+ }
1469
+ export {
1470
+ connectServiceHost,
1471
+ createScheduleTools
1472
+ };
1473
+ //# sourceMappingURL=service-host.js.map