@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.
- package/LICENSE +21 -0
- package/README.md +91 -3
- package/dist/index.d.ts +2028 -0
- package/dist/index.js +2547 -0
- package/dist/index.js.map +6 -0
- package/dist/node/service-host.d.ts +1418 -0
- package/dist/node/service-host.js +1379 -0
- package/dist/node/service-host.js.map +6 -0
- package/dist/protocol.d.ts +2378 -0
- package/dist/protocol.js +1822 -0
- package/dist/protocol.js.map +6 -0
- package/package.json +46 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,2547 @@
|
|
|
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 keys2 = Reflect.ownKeys(value);
|
|
42
|
+
if (!keys2.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 keys2 = Reflect.ownKeys(v);
|
|
154
|
+
if (list && keys2.length !== v.length + 1) return false;
|
|
155
|
+
return keys2.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/service.ts
|
|
175
|
+
function fields(value, required, optional = []) {
|
|
176
|
+
if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
|
|
177
|
+
return false;
|
|
178
|
+
return required.every((k) => Object.hasOwn(value, k)) && Reflect.ownKeys(value).every((k) => {
|
|
179
|
+
const d = Object.getOwnPropertyDescriptor(value, k);
|
|
180
|
+
return typeof k === "string" && [...required, ...optional].includes(k) && d.enumerable && Object.hasOwn(d, "value");
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
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(
|
|
184
|
+
v
|
|
185
|
+
);
|
|
186
|
+
function json2(value, ancestors = /* @__PURE__ */ new Set(), depth = 0) {
|
|
187
|
+
if (depth > 100) return false;
|
|
188
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
189
|
+
return true;
|
|
190
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
191
|
+
if (typeof value !== "object" || ancestors.has(value)) return false;
|
|
192
|
+
const array2 = Array.isArray(value);
|
|
193
|
+
if (array2 ? Object.getPrototypeOf(value) !== Array.prototype || Reflect.ownKeys(value).length !== value.length + 1 : ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
|
|
194
|
+
return false;
|
|
195
|
+
ancestors.add(value);
|
|
196
|
+
const result = Reflect.ownKeys(value).every((k) => {
|
|
197
|
+
if (array2 && k === "length") return true;
|
|
198
|
+
const d = Object.getOwnPropertyDescriptor(value, k);
|
|
199
|
+
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);
|
|
200
|
+
});
|
|
201
|
+
ancestors.delete(value);
|
|
202
|
+
return result;
|
|
203
|
+
}
|
|
204
|
+
function validServiceStatus(value) {
|
|
205
|
+
return fields(value, ["state"], ["reason", "instanceId", "apiVersion"]) && [
|
|
206
|
+
"absent",
|
|
207
|
+
"unauthorized",
|
|
208
|
+
"stopped",
|
|
209
|
+
"starting",
|
|
210
|
+
"recovering",
|
|
211
|
+
"ready",
|
|
212
|
+
"failed"
|
|
213
|
+
].includes(value.state) && (!Object.hasOwn(value, "reason") || [
|
|
214
|
+
"dependency_missing",
|
|
215
|
+
"service_start_failed",
|
|
216
|
+
"service_unavailable",
|
|
217
|
+
"result_unknown",
|
|
218
|
+
"incompatible",
|
|
219
|
+
"revoked"
|
|
220
|
+
].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"));
|
|
221
|
+
}
|
|
222
|
+
function validWork(value) {
|
|
223
|
+
return fields(value, ["requestId", "state", "updatedAt"], ["result", "error"]) && typeof value.requestId === "string" && HOST_REQUEST_ID.test(value.requestId) && [
|
|
224
|
+
"not_accepted",
|
|
225
|
+
"accepted",
|
|
226
|
+
"running",
|
|
227
|
+
"completed",
|
|
228
|
+
"failed",
|
|
229
|
+
"interrupted",
|
|
230
|
+
"unknown"
|
|
231
|
+
].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(
|
|
232
|
+
value.updatedAt
|
|
233
|
+
) && Number.isFinite(Date.parse(value.updatedAt)) && ["result", "error"].every(
|
|
234
|
+
(k) => !Object.hasOwn(value, k) || json2(value[k]) && new TextEncoder().encode(JSON.stringify(value[k])).length <= 16384
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
function validServiceResult(method, value) {
|
|
238
|
+
switch (method) {
|
|
239
|
+
case "service.getStatus":
|
|
240
|
+
return validServiceStatus(value);
|
|
241
|
+
case "service.getConnection":
|
|
242
|
+
return fields(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);
|
|
243
|
+
case "service.getWork":
|
|
244
|
+
return validWork(value);
|
|
245
|
+
case "service.listWork":
|
|
246
|
+
return Array.isArray(value) && value.length <= 5120 && value.every(validWork) && new Set(value.map((w) => w.requestId)).size === value.length;
|
|
247
|
+
case "service.interruptWork":
|
|
248
|
+
return fields(value, ["requested"]) && typeof value.requested === "boolean";
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function validServiceConnectionInput(value) {
|
|
252
|
+
return fields(value, ["apiRange"]) && typeof value.apiRange === "string" && !!value.apiRange.trim() && value.apiRange.length <= 256;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// ../domain-contracts/src/app-host/fetch.ts
|
|
256
|
+
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"];
|
|
257
|
+
var FETCH_CHUNK_BYTES = 64 * 1024;
|
|
258
|
+
var FETCH_INLINE_BODY_BYTES = 8 * 1024;
|
|
259
|
+
var FETCH_WINDOW_CHUNKS = 4;
|
|
260
|
+
var FETCH_MAX_STREAMS = 16;
|
|
261
|
+
var FETCH_METADATA_BYTES = 64 * 1024;
|
|
262
|
+
var FETCH_HEADERS_TIMEOUT_MS = 3e4;
|
|
263
|
+
var FETCH_IDLE_TIMEOUT_MS = 12e4;
|
|
264
|
+
function isPageFetchFrame(value) {
|
|
265
|
+
let size = 0;
|
|
266
|
+
const visit = (entry, depth, binary = false) => {
|
|
267
|
+
if (depth > 10) return false;
|
|
268
|
+
if (entry instanceof Uint8Array) {
|
|
269
|
+
if (!binary || Object.getPrototypeOf(entry) !== Uint8Array.prototype || ["buffer", "byteLength", "byteOffset", "length"].some((key) => Object.hasOwn(entry, key))) return false;
|
|
270
|
+
const buffer = entry.buffer;
|
|
271
|
+
return buffer instanceof ArrayBuffer && !Object.hasOwn(buffer, "byteLength") && buffer.byteLength <= FETCH_CHUNK_BYTES && entry.byteLength > 0 && entry.byteLength <= FETCH_CHUNK_BYTES;
|
|
272
|
+
}
|
|
273
|
+
if (entry === null || typeof entry === "boolean" || typeof entry === "number" && Number.isFinite(entry)) {
|
|
274
|
+
size += 8;
|
|
275
|
+
return true;
|
|
276
|
+
}
|
|
277
|
+
if (typeof entry === "string") {
|
|
278
|
+
size += new TextEncoder().encode(entry).byteLength + 2;
|
|
279
|
+
return size <= FETCH_METADATA_BYTES;
|
|
280
|
+
}
|
|
281
|
+
if (!entry || typeof entry !== "object") return false;
|
|
282
|
+
const array2 = Array.isArray(entry);
|
|
283
|
+
if (array2 ? Object.getPrototypeOf(entry) !== Array.prototype : ![Object.prototype, null].includes(Object.getPrototypeOf(entry))) return false;
|
|
284
|
+
const keys2 = Reflect.ownKeys(entry);
|
|
285
|
+
if (keys2.length > FETCH_METADATA_BYTES || array2 && keys2.length !== entry.length + 1) return false;
|
|
286
|
+
return keys2.every((key) => {
|
|
287
|
+
if (array2 && key === "length") return true;
|
|
288
|
+
const d = Object.getOwnPropertyDescriptor(entry, key);
|
|
289
|
+
size += typeof key === "string" ? key.length + 3 : 0;
|
|
290
|
+
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;
|
|
291
|
+
});
|
|
292
|
+
};
|
|
293
|
+
if (!visit(value, 0) || !value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
294
|
+
const v = value;
|
|
295
|
+
if (v.protocol !== 2 || typeof v.type !== "string") return false;
|
|
296
|
+
const fields4 = {
|
|
297
|
+
"fetch-open": ["id", "connectionId", "url", "method", "headers", "hasBody"],
|
|
298
|
+
"fetch-headers": ["id", "status", "statusText", "headers", "hasBody"],
|
|
299
|
+
"fetch-credit": ["id", "direction", "sequence", "chunks", "bytes"],
|
|
300
|
+
"fetch-chunk": ["id", "direction", "sequence", "bytes"],
|
|
301
|
+
"fetch-end": ["id", "direction", "sequence"],
|
|
302
|
+
"fetch-consumed": ["id", "direction", "sequence"],
|
|
303
|
+
"fetch-cancel": ["id"],
|
|
304
|
+
"fetch-error": ["id", "error"],
|
|
305
|
+
"fetch-close": ["connectionId"]
|
|
306
|
+
};
|
|
307
|
+
const required = fields4[v.type];
|
|
308
|
+
const inline = v.type === "fetch-open" && Object.hasOwn(v, "inlineBody");
|
|
309
|
+
if (!required || Object.keys(v).length !== required.length + 2 + Number(inline) || !required.every((k) => Object.hasOwn(v, k))) return false;
|
|
310
|
+
if (inline && (v.hasBody !== true || typeof v.inlineBody !== "string" || new TextEncoder().encode(v.inlineBody).byteLength > FETCH_INLINE_BODY_BYTES)) return false;
|
|
311
|
+
const id3 = (x) => typeof x === "string" && x.length > 0 && x.length <= 128;
|
|
312
|
+
if (v.type === "fetch-close") return id3(v.connectionId);
|
|
313
|
+
if (!id3(v.id)) return false;
|
|
314
|
+
if (v.type === "fetch-consumed") return v.direction === "download" && Number.isSafeInteger(v.sequence) && v.sequence >= 0;
|
|
315
|
+
if (["fetch-chunk", "fetch-credit", "fetch-end"].includes(v.type) && (!["upload", "download"].includes(v.direction) || !Number.isSafeInteger(v.sequence) || v.sequence < 0)) return false;
|
|
316
|
+
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;
|
|
317
|
+
if (v.type === "fetch-chunk") return v.bytes instanceof Uint8Array;
|
|
318
|
+
if (v.type === "fetch-error") return isAppHostErrorInfo(v.error);
|
|
319
|
+
if (v.type === "fetch-open" || v.type === "fetch-headers") {
|
|
320
|
+
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;
|
|
321
|
+
if (v.type === "fetch-open") return id3(v.connectionId) && typeof v.url === "string" && typeof v.method === "string" && /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(v.method);
|
|
322
|
+
return Number.isInteger(v.status) && v.status >= 200 && v.status <= 599 && typeof v.statusText === "string";
|
|
323
|
+
}
|
|
324
|
+
return true;
|
|
325
|
+
}
|
|
326
|
+
function pageFetchPath(baseUrl, input) {
|
|
327
|
+
if (/[\\\s#]/.test(input)) throw new TypeError("Invalid fetch URL");
|
|
328
|
+
const rawPath = input.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/]+/, "").split("?")[0];
|
|
329
|
+
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");
|
|
330
|
+
const base = new URL(baseUrl), url = new URL(input);
|
|
331
|
+
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");
|
|
332
|
+
return (url.pathname.slice(base.pathname.length) || "/") + url.search;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// ../domain-contracts/src/app-host/service-host-protocol.ts
|
|
336
|
+
var SERVICE_HOST_MAX_FRAME_BYTES = 512 * 1024;
|
|
337
|
+
var worktreeBody = { workspaceId: id, expectedHead: text(256), branch: text(1024) };
|
|
338
|
+
var worktreeReceipt = object({ requestId: id, state: enumeration("accepted", "completed", "failed", "unknown") }, { result: object({ executionRoot: id, workspaceId: id, branch: text(1024), sourceHead: text(256) }) });
|
|
339
|
+
|
|
340
|
+
// ../domain-contracts/src/app-host/workspace-conversations.ts
|
|
341
|
+
var validWorkspaceConversation = (value) => {
|
|
342
|
+
if (!object(
|
|
343
|
+
{ dataScopeId: text(), requestId: id, sessionId: id, taskLocation: enumeration("current", "worktree"), configuration: json },
|
|
344
|
+
{ workspaceId: id, outsideProject: (v) => v === true, preparationRevision: text() }
|
|
345
|
+
)(value)) return false;
|
|
346
|
+
const input = value;
|
|
347
|
+
return input.workspaceId !== void 0 ? input.outsideProject !== true : input.outsideProject === true && input.taskLocation === "current";
|
|
348
|
+
};
|
|
349
|
+
var sessionText = (value) => typeof value === "string";
|
|
350
|
+
var sessionRecord = object({
|
|
351
|
+
id,
|
|
352
|
+
cwd: sessionText,
|
|
353
|
+
title: sessionText,
|
|
354
|
+
model: sessionText,
|
|
355
|
+
status: enumeration("idle", "running", "closing", "archived", "error"),
|
|
356
|
+
metadata: jsonObject,
|
|
357
|
+
createdAt: count,
|
|
358
|
+
updatedAt: count
|
|
359
|
+
}, {
|
|
360
|
+
storage: enumeration("sqlite", "memory"),
|
|
361
|
+
parentId: sessionText,
|
|
362
|
+
projectId: sessionText,
|
|
363
|
+
cwdRelative: sessionText,
|
|
364
|
+
agent: sessionText,
|
|
365
|
+
archivedAt: count
|
|
366
|
+
});
|
|
367
|
+
var workspaceConversationResult = object({
|
|
368
|
+
dataScopeId: text(),
|
|
369
|
+
sessionId: id,
|
|
370
|
+
requestId: id,
|
|
371
|
+
action: (v) => v === "create-session",
|
|
372
|
+
state: enumeration("prepared", "completed", "unknown")
|
|
373
|
+
}, {
|
|
374
|
+
configuration: json,
|
|
375
|
+
revision: count,
|
|
376
|
+
session: sessionRecord,
|
|
377
|
+
operationState: enumeration("prepared", "running", "completed", "failed", "unknown"),
|
|
378
|
+
indexBindingPending: (v) => v === true,
|
|
379
|
+
workspaceId: id,
|
|
380
|
+
executionRoot: id,
|
|
381
|
+
privateSessionId: id,
|
|
382
|
+
worktree: json
|
|
383
|
+
});
|
|
384
|
+
var validWorkspaceConversationResult = (value) => {
|
|
385
|
+
if (!workspaceConversationResult(value)) return false;
|
|
386
|
+
const result = value;
|
|
387
|
+
return !result.session || result.state === "completed" && result.session.id === result.sessionId;
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
// ../domain-contracts/src/app-host/session-controls.ts
|
|
391
|
+
var option = object({ id: text(), name: text() });
|
|
392
|
+
var choices = array(option);
|
|
393
|
+
var effortChoices = array(object({ id: text(1024, true), name: text() }));
|
|
394
|
+
var receiptShape = object({ dataScopeId: text(), sessionId: text(), requestId: id, action: enumeration("fork", "configure", "compact"), state: enumeration("prepared", "created", "completed", "unknown") }, { revision: count, targetSessionId: text() });
|
|
395
|
+
var receipt = receiptShape;
|
|
396
|
+
function validSessionControlOriginal(value) {
|
|
397
|
+
if (!object({ action: text(), body: json })(value)) return false;
|
|
398
|
+
const v = value;
|
|
399
|
+
if (v.action === "compact") return object({ requestId: id, expectedRevision: count })(v.body);
|
|
400
|
+
return v.action === "fork" && object({ requestId: id, id: text() }, { copyHistory: bool, beforeMessageId: text(), afterMessageId: text(), storage: enumeration("sqlite") })(v.body);
|
|
401
|
+
}
|
|
402
|
+
function validSessionControlInput(method, value) {
|
|
403
|
+
if (!json(value)) return false;
|
|
404
|
+
if (method === "sessions.getDraftComposerOptions") {
|
|
405
|
+
if (!object({ source: enumeration("instance") }, { workspaceId: id, outsideProject: bool, roleId: (v2) => v2 === null || text(256)(v2) })(value)) return false;
|
|
406
|
+
const target2 = value;
|
|
407
|
+
return target2.workspaceId !== void 0 ? target2.outsideProject !== true : target2.outsideProject === true;
|
|
408
|
+
}
|
|
409
|
+
if (method === "sessions.bindConversationIndex") return object({ original: validWorkspaceConversation, dataScopeId: text() })(value);
|
|
410
|
+
if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult") return validWorkspaceConversation(value);
|
|
411
|
+
if (method === "sessions.getControls") return object({ connectionId: text(), sessionId: text() })(value);
|
|
412
|
+
if (!object({ requestId: id, sessionId: text(), original: validSessionControlOriginal }, { connectionId: text() })(value)) return false;
|
|
413
|
+
const v = value;
|
|
414
|
+
return v.original.body.requestId === v.requestId && !!v.connectionId;
|
|
415
|
+
}
|
|
416
|
+
function validSessionControlResult(method, value) {
|
|
417
|
+
if (!json(value)) return false;
|
|
418
|
+
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);
|
|
419
|
+
if (method === "sessions.bindConversationIndex") return validWorkspaceConversationResult(value);
|
|
420
|
+
if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult")
|
|
421
|
+
return method === "sessions.getConversationCreationResult" && value === null || validWorkspaceConversationResult(value);
|
|
422
|
+
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);
|
|
423
|
+
if (method === "sessions.getControlResult") return value === null || receipt(value);
|
|
424
|
+
if (!receipt(value)) return false;
|
|
425
|
+
return false;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// ../domain-contracts/src/app-host/workspace.ts
|
|
429
|
+
function fields2(v, required, optional = []) {
|
|
430
|
+
if (!v || typeof v !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
|
|
431
|
+
return required.every((k) => Object.hasOwn(v, k)) && Reflect.ownKeys(v).every((k) => {
|
|
432
|
+
const d = Object.getOwnPropertyDescriptor(v, k);
|
|
433
|
+
return typeof k === "string" && [...required, ...optional].includes(k) && d.enumerable && Object.hasOwn(d, "value");
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
var uuid = (v) => typeof v === "string" && HOST_REQUEST_ID.test(v);
|
|
437
|
+
var str = (v) => typeof v === "string";
|
|
438
|
+
function rows(v, check) {
|
|
439
|
+
if (!Array.isArray(v) || Object.getPrototypeOf(v) !== Array.prototype || v.length > 200 || Reflect.ownKeys(v).length !== v.length + 1) return false;
|
|
440
|
+
for (let i = 0; i < v.length; i++) {
|
|
441
|
+
const d = Object.getOwnPropertyDescriptor(v, String(i));
|
|
442
|
+
if (!d?.enumerable || !Object.hasOwn(d, "value") || !check(d.value)) return false;
|
|
443
|
+
}
|
|
444
|
+
return true;
|
|
445
|
+
}
|
|
446
|
+
var ref = (v) => fields2(v, ["id", "displayName"]) && uuid(v.id) && str(v.displayName) && v.displayName.length > 0;
|
|
447
|
+
function validWorkspaceInput(method, v) {
|
|
448
|
+
switch (method) {
|
|
449
|
+
case "workspace.select":
|
|
450
|
+
case "workspace.getSelection":
|
|
451
|
+
return fields2(v, ["requestId"]) && uuid(v.requestId);
|
|
452
|
+
case "workspace.get":
|
|
453
|
+
return fields2(v, ["workspaceId"]) && uuid(v.workspaceId);
|
|
454
|
+
case "workspace.listFiles":
|
|
455
|
+
return fields2(v, ["workspaceId", "directory"], ["cursor"]) && uuid(v.workspaceId) && str(v.directory) && (!Object.hasOwn(v, "cursor") || uuid(v.cursor));
|
|
456
|
+
case "workspace.readText":
|
|
457
|
+
return fields2(v, ["workspaceId", "path"]) && uuid(v.workspaceId) && str(v.path) && v.path.length > 0;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
function validWorkspaceResult(method, v) {
|
|
461
|
+
switch (method) {
|
|
462
|
+
case "workspace.select":
|
|
463
|
+
return v === null || ref(v);
|
|
464
|
+
case "workspace.get":
|
|
465
|
+
return ref(v);
|
|
466
|
+
case "workspace.getSelection":
|
|
467
|
+
if (!fields2(v, ["requestId", "status"], ["workspace", "unavailable"]) || !uuid(v.requestId)) return false;
|
|
468
|
+
if (v.status === "completed") return fields2(v, ["requestId", "status", "workspace"]) && ref(v.workspace) || fields2(v, ["requestId", "status", "unavailable"]) && v.unavailable === true;
|
|
469
|
+
return fields2(v, ["requestId", "status"]) && ["pending", "cancelled", "expired", "failed", "unknown"].includes(v.status);
|
|
470
|
+
case "workspace.listFiles":
|
|
471
|
+
return fields2(v, ["entries"], ["nextCursor"]) && rows(v.entries, (e) => fields2(e, ["path", "name", "kind"]) && str(e.path) && str(e.name) && (e.kind === "file" || e.kind === "directory")) && (!Object.hasOwn(v, "nextCursor") || uuid(v.nextCursor));
|
|
472
|
+
case "workspace.readText":
|
|
473
|
+
return fields2(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);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// src/commands.ts
|
|
478
|
+
var COMMANDS_METHODS = [
|
|
479
|
+
"commands.register",
|
|
480
|
+
"commands.update",
|
|
481
|
+
"commands.dispose"
|
|
482
|
+
];
|
|
483
|
+
var isCommandsMethod = (method) => COMMANDS_METHODS.includes(method);
|
|
484
|
+
var identifier = (v) => text(128)(v) && /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(v);
|
|
485
|
+
var label = text(512);
|
|
486
|
+
var shortcut = object(
|
|
487
|
+
{
|
|
488
|
+
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(
|
|
489
|
+
v
|
|
490
|
+
),
|
|
491
|
+
modifiers: array(
|
|
492
|
+
enumeration("Primary", "Control", "Meta", "Alt", "Shift"),
|
|
493
|
+
5
|
|
494
|
+
)
|
|
495
|
+
},
|
|
496
|
+
{ scope: enumeration("application", "global") }
|
|
497
|
+
);
|
|
498
|
+
function validAppCommandSnapshot(value) {
|
|
499
|
+
if (!json(value) || !object(
|
|
500
|
+
{
|
|
501
|
+
commands: array(
|
|
502
|
+
object(
|
|
503
|
+
{ id: identifier, label },
|
|
504
|
+
{ enabled: bool, checked: bool, shortcuts: array(shortcut, 8) }
|
|
505
|
+
),
|
|
506
|
+
128
|
|
507
|
+
),
|
|
508
|
+
menus: array(
|
|
509
|
+
object({
|
|
510
|
+
id: identifier,
|
|
511
|
+
label,
|
|
512
|
+
items: array(
|
|
513
|
+
(v2) => object({ command: identifier })(v2) || object({ separator: enumeration(true) })(v2),
|
|
514
|
+
64
|
|
515
|
+
)
|
|
516
|
+
}),
|
|
517
|
+
8
|
|
518
|
+
)
|
|
519
|
+
},
|
|
520
|
+
{
|
|
521
|
+
toolbar: object(
|
|
522
|
+
{},
|
|
523
|
+
{ back: identifier, forward: identifier, sidebar: identifier }
|
|
524
|
+
)
|
|
525
|
+
}
|
|
526
|
+
)(value))
|
|
527
|
+
return false;
|
|
528
|
+
const v = value;
|
|
529
|
+
const ids = new Set(v.commands.map((c) => c.id));
|
|
530
|
+
if (ids.size !== v.commands.length || new Set(v.menus.map((m) => m.id)).size !== v.menus.length || v.menus.some(
|
|
531
|
+
(m) => m.items.some((i) => "command" in i && !ids.has(i.command))
|
|
532
|
+
) || Object.values(v.toolbar ?? {}).some((x) => !ids.has(x)))
|
|
533
|
+
return false;
|
|
534
|
+
const keys2 = /* @__PURE__ */ new Set();
|
|
535
|
+
for (const command of v.commands)
|
|
536
|
+
for (const key of command.shortcuts ?? []) {
|
|
537
|
+
const mods = new Set(key.modifiers);
|
|
538
|
+
if (mods.size !== key.modifiers.length || mods.has("Primary") && (mods.has("Meta") || mods.has("Control")))
|
|
539
|
+
return false;
|
|
540
|
+
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")
|
|
541
|
+
return false;
|
|
542
|
+
const signature = `${[...mods].map((m) => m === "Control" || m === "Meta" ? "Primary" : m).sort().join("+")}:${key.code}`;
|
|
543
|
+
if (keys2.has(signature)) return false;
|
|
544
|
+
keys2.add(signature);
|
|
545
|
+
}
|
|
546
|
+
return true;
|
|
547
|
+
}
|
|
548
|
+
var validCommandReceipt = object(
|
|
549
|
+
{ registrationId: id, revision: count },
|
|
550
|
+
{ shortcutConflicts: array(identifier, 128) }
|
|
551
|
+
);
|
|
552
|
+
var validCommandInvocation = (v) => json(v) && object({
|
|
553
|
+
type: enumeration("command-invoked"),
|
|
554
|
+
registrationId: id,
|
|
555
|
+
revision: count,
|
|
556
|
+
commandId: identifier
|
|
557
|
+
})(v);
|
|
558
|
+
function createAppCommandsApi(rpc) {
|
|
559
|
+
return {
|
|
560
|
+
async register(snapshot, invoke) {
|
|
561
|
+
if (!validAppCommandSnapshot(snapshot) || typeof invoke !== "function")
|
|
562
|
+
throw new AppHostError("invalid_request");
|
|
563
|
+
rpc.requireFeature();
|
|
564
|
+
snapshot = structuredClone(snapshot);
|
|
565
|
+
const registrationId = crypto.randomUUID();
|
|
566
|
+
let revision3 = 0;
|
|
567
|
+
let disposed = false;
|
|
568
|
+
let remoteValid = true;
|
|
569
|
+
let disposal;
|
|
570
|
+
let current = snapshot;
|
|
571
|
+
let conflicts = [];
|
|
572
|
+
let queue = Promise.resolve();
|
|
573
|
+
const off = rpc.onInvoke((event) => {
|
|
574
|
+
if (!disposed && event.registrationId === registrationId && event.revision === revision3 && current.commands.some(
|
|
575
|
+
(c) => c.id === event.commandId && c.enabled !== false
|
|
576
|
+
)) {
|
|
577
|
+
void Promise.resolve().then(() => {
|
|
578
|
+
if (!disposed && event.revision === revision3)
|
|
579
|
+
return invoke(event.commandId);
|
|
580
|
+
}).catch(() => {
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
const stop = () => {
|
|
585
|
+
if (!disposed) {
|
|
586
|
+
disposed = true;
|
|
587
|
+
off();
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
const invalidate = () => {
|
|
591
|
+
remoteValid = false;
|
|
592
|
+
stop();
|
|
593
|
+
};
|
|
594
|
+
const offClose = rpc.onClose(invalidate);
|
|
595
|
+
const call = async (method, next) => {
|
|
596
|
+
const params = {
|
|
597
|
+
registrationId,
|
|
598
|
+
revision: revision3,
|
|
599
|
+
...next === void 0 ? {} : { snapshot: next }
|
|
600
|
+
};
|
|
601
|
+
const result = await rpc.request(
|
|
602
|
+
method,
|
|
603
|
+
params
|
|
604
|
+
);
|
|
605
|
+
if (!validCommandReceipt(result) || result.registrationId !== registrationId || result.revision !== revision3)
|
|
606
|
+
throw new AppHostError("host_unavailable");
|
|
607
|
+
conflicts = [...result.shortcutConflicts ?? []];
|
|
608
|
+
};
|
|
609
|
+
const abandon = async () => {
|
|
610
|
+
invalidate();
|
|
611
|
+
offClose();
|
|
612
|
+
try {
|
|
613
|
+
await rpc.request("commands.dispose", {
|
|
614
|
+
registrationId,
|
|
615
|
+
revision: ++revision3
|
|
616
|
+
});
|
|
617
|
+
} catch {
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
try {
|
|
621
|
+
await call("commands.register", snapshot);
|
|
622
|
+
} catch (error) {
|
|
623
|
+
await abandon();
|
|
624
|
+
throw error;
|
|
625
|
+
}
|
|
626
|
+
return {
|
|
627
|
+
get shortcutConflicts() {
|
|
628
|
+
return [...conflicts];
|
|
629
|
+
},
|
|
630
|
+
update(next) {
|
|
631
|
+
if (disposed)
|
|
632
|
+
return Promise.reject(new AppHostError("connection_revoked"));
|
|
633
|
+
if (!validAppCommandSnapshot(next))
|
|
634
|
+
return Promise.reject(new AppHostError("invalid_request"));
|
|
635
|
+
next = structuredClone(next);
|
|
636
|
+
const task = queue.then(async () => {
|
|
637
|
+
if (disposed) throw new AppHostError("connection_revoked");
|
|
638
|
+
rpc.requireFeature();
|
|
639
|
+
revision3++;
|
|
640
|
+
current = next;
|
|
641
|
+
try {
|
|
642
|
+
await call("commands.update", next);
|
|
643
|
+
} catch (error) {
|
|
644
|
+
await abandon();
|
|
645
|
+
throw error;
|
|
646
|
+
}
|
|
647
|
+
});
|
|
648
|
+
queue = task.catch(() => {
|
|
649
|
+
});
|
|
650
|
+
return task;
|
|
651
|
+
},
|
|
652
|
+
dispose() {
|
|
653
|
+
if (disposal) return disposal;
|
|
654
|
+
stop();
|
|
655
|
+
disposal = queue.then(async () => {
|
|
656
|
+
if (!remoteValid) return;
|
|
657
|
+
revision3++;
|
|
658
|
+
try {
|
|
659
|
+
await call("commands.dispose");
|
|
660
|
+
} finally {
|
|
661
|
+
remoteValid = false;
|
|
662
|
+
}
|
|
663
|
+
}).finally(offClose);
|
|
664
|
+
queue = disposal.catch(() => {
|
|
665
|
+
});
|
|
666
|
+
return disposal;
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// src/resource-catalog.ts
|
|
674
|
+
var RESOURCE_CATALOG_METHODS = ["workspace.list"];
|
|
675
|
+
var isResourceCatalogMethod = (m) => RESOURCE_CATALOG_METHODS.includes(m);
|
|
676
|
+
var cursor = { cursor: id };
|
|
677
|
+
var nextCursor = { nextCursor: id };
|
|
678
|
+
var validResourceChanged = (v) => json(v) && object({ type: enumeration("resources-changed"), directory: enumeration("workspaces"), revision: text(256) })(v);
|
|
679
|
+
function validResourceCatalogInput(_method, v) {
|
|
680
|
+
return json(v) && object({}, cursor)(v);
|
|
681
|
+
}
|
|
682
|
+
function validResourceCatalogResult(method, v) {
|
|
683
|
+
if (!json(v)) return false;
|
|
684
|
+
return object({ revision: text(256), entries: array(object({ id, displayName: text(1024) }), 200) }, nextCursor)(v);
|
|
685
|
+
}
|
|
686
|
+
function createResourceCatalogApi(rpc) {
|
|
687
|
+
const call = async (method, params) => {
|
|
688
|
+
if (!validResourceCatalogInput(method, params)) throw new AppHostError("invalid_request");
|
|
689
|
+
rpc.requireFeature();
|
|
690
|
+
const result = await rpc.request(method, params);
|
|
691
|
+
if (!validResourceCatalogResult(method, result)) throw new AppHostError("host_unavailable");
|
|
692
|
+
return result;
|
|
693
|
+
};
|
|
694
|
+
return { list: (input = {}) => call("workspace.list", input) };
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// src/session-controls.ts
|
|
698
|
+
var CONVERSATION_PREPARATION_METHODS = [
|
|
699
|
+
"sessions.createConversation",
|
|
700
|
+
"sessions.getConversationCreationResult",
|
|
701
|
+
"sessions.bindConversationIndex"
|
|
702
|
+
];
|
|
703
|
+
function isConversationPreparationMethod(method) {
|
|
704
|
+
return CONVERSATION_PREPARATION_METHODS.includes(method);
|
|
705
|
+
}
|
|
706
|
+
function validConversationPreparationResult(method, result) {
|
|
707
|
+
return validSessionControlResult(method, result);
|
|
708
|
+
}
|
|
709
|
+
function createConversationPreparationApi(rpc) {
|
|
710
|
+
const call = async (method, input) => {
|
|
711
|
+
if (!validSessionControlInput(method, input)) throw new AppHostError("invalid_request");
|
|
712
|
+
rpc.requireFeature();
|
|
713
|
+
const result = await rpc.request(method, input);
|
|
714
|
+
if (!validSessionControlResult(method, result)) throw new AppHostError("host_unavailable");
|
|
715
|
+
return result;
|
|
716
|
+
};
|
|
717
|
+
return {
|
|
718
|
+
createConversation: (input) => call("sessions.createConversation", input),
|
|
719
|
+
getConversationCreationResult: (input) => call("sessions.getConversationCreationResult", input),
|
|
720
|
+
async bindConversationIndex(input) {
|
|
721
|
+
const result = await call("sessions.bindConversationIndex", input);
|
|
722
|
+
if (result.dataScopeId !== input.dataScopeId || result.sessionId !== input.original.sessionId || result.requestId !== input.original.requestId || result.state !== "completed") throw new AppHostError("host_unavailable");
|
|
723
|
+
return result;
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// src/client-connections.ts
|
|
729
|
+
var connections = /* @__PURE__ */ new WeakMap();
|
|
730
|
+
function createClientConnection(wire, streams) {
|
|
731
|
+
const record3 = { owner: streams, id: wire.connectionId, closed: false };
|
|
732
|
+
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() {
|
|
733
|
+
return record3.closed || streams.isClosed?.(wire.connectionId) === true;
|
|
734
|
+
}, close() {
|
|
735
|
+
if (!record3.closed) {
|
|
736
|
+
record3.closed = true;
|
|
737
|
+
streams.close(wire.connectionId);
|
|
738
|
+
}
|
|
739
|
+
} };
|
|
740
|
+
connections.set(connection, record3);
|
|
741
|
+
return connection;
|
|
742
|
+
}
|
|
743
|
+
function resolveClientConnection(connection, owner) {
|
|
744
|
+
const record3 = connections.get(connection);
|
|
745
|
+
if (!record3 || record3.owner !== owner || record3.closed || owner.isClosed?.(record3.id)) throw new AppHostError("connection_revoked");
|
|
746
|
+
return record3.id;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
// src/desktop.ts
|
|
750
|
+
var BROWSER_CAPTURE_PREVIEW_MAX_BYTES = 8 * 1024 * 1024;
|
|
751
|
+
var target = { targetId: text(256) };
|
|
752
|
+
var mount = { ...target, mountId: text(256) };
|
|
753
|
+
var source = object({ sessionId: text(), appId: text() });
|
|
754
|
+
var action = { ...mount, source, requestId: id, expectedRevision: count };
|
|
755
|
+
var page = { ...target, tabId: text(256), pageRevision: count };
|
|
756
|
+
var mode = enumeration("off", "pick", "review");
|
|
757
|
+
var voidResult = (v) => v === void 0;
|
|
758
|
+
var finite = (v) => typeof v === "number" && Number.isFinite(v);
|
|
759
|
+
var rect = object({ x: finite, y: finite, width: finite, height: finite });
|
|
760
|
+
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) };
|
|
761
|
+
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: finite, height: finite })), 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) });
|
|
762
|
+
var root = object({ path: text(32768), identity: object({ dev: text(), ino: text() }) }, { workspaceId: text() });
|
|
763
|
+
var validDesktopTarget = object({ id: text(), dataScopeId: text(), draftId: text(), draftRevision: count }, { root, sessionId: text() });
|
|
764
|
+
var kind = enumeration("files.writeText", "git.switchBranch", "git.createBranch", "git.createTaskWorktree");
|
|
765
|
+
var validWorkspaceOperation = object({ requestId: id, kind, state: enumeration("prepared", "running", "completed", "failed", "unknown"), createdAt: count, updatedAt: count }, { result: json, error: object({ code: text(128) }) });
|
|
766
|
+
var origin = (v) => object({ kind: enumeration("surface"), surfaceId: text() })(v) || object({ kind: enumeration("tool-result"), sourcePartId: text() })(v);
|
|
767
|
+
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() });
|
|
768
|
+
var policy = object({ confirmation: enumeration("required", "granted"), maxArgumentsBytes: count }, { authorization: enumeration("plugin-data-write") });
|
|
769
|
+
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 })) });
|
|
770
|
+
var mounted = object({ mountId: text(), url: text(16384), state });
|
|
771
|
+
var runStatus = enumeration("pending", "running", "completed", "failed", "interrupted");
|
|
772
|
+
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") });
|
|
773
|
+
var submission = object({ source, requestId: id, inputId: text(), runId: text(), expectedRevision: count, status: runStatus });
|
|
774
|
+
var windowResult = object({ requestId: id, targetId: text(), state: enumeration("opening", "open", "closing", "closed") }, { windowId: count });
|
|
775
|
+
var positive = (v) => count(v) && v > 0 && v <= 1e4;
|
|
776
|
+
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;
|
|
777
|
+
var terminalResult = object({ resourceId: text(), terminalId: text(), cwd: text(32768), status: enumeration("running", "exited") });
|
|
778
|
+
var terminalOriginal = (v) => object({ kind: enumeration("create"), cols: positive, rows: positive }, { name: text(256) })(v) || object({ kind: enumeration("restart"), terminalId: text() })(v);
|
|
779
|
+
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);
|
|
780
|
+
var rules = {
|
|
781
|
+
"desktop.bindTarget": { input: object({ draftId: text(), draftRevision: count }, { directory: text(32768), workspaceId: text(), connectionId: text(), sessionId: text() }), result: validDesktopTarget },
|
|
782
|
+
"desktop.releaseTarget": { input: object(target), result: voidResult },
|
|
783
|
+
"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) }) },
|
|
784
|
+
"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 }) },
|
|
785
|
+
"desktop.files.openRead": { input: object({ ...target, path: text(32768) }), result: validConnection },
|
|
786
|
+
"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 }) },
|
|
787
|
+
"desktop.files.writeText": { input: object({ ...target, requestId: id, path: text(32768), expectedSha256: digest, text: text(8 * 1024 * 1024, true) }), result: validWorkspaceOperation },
|
|
788
|
+
"desktop.files.getOperation": { input: object({ ...target, requestId: id, original: object({ kind, body: json }) }), result: nullable(validWorkspaceOperation) },
|
|
789
|
+
"desktop.files.revealPath": { input: object({ ...target, path: text(32768) }), result: voidResult },
|
|
790
|
+
"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) },
|
|
791
|
+
"desktop.files.openWith": { input: object({ ...target, path: text(32768), openerId: text(256) }), result: voidResult },
|
|
792
|
+
"desktop.clipboard.readText": { input: object(target), result: text(8 * 1024 * 1024, true) },
|
|
793
|
+
"desktop.clipboard.writeText": { input: object({ ...target, text: text(8 * 1024 * 1024, true) }), result: voidResult },
|
|
794
|
+
"desktop.clipboard.showTextMenu": { input: object({ ...target, editable: bool, hasSelection: bool }), result: nullable(enumeration("copy", "select-all")) },
|
|
795
|
+
"desktop.windows.openExternal": { input: object({ ...target, url: text(16384) }), result: voidResult },
|
|
796
|
+
"desktop.windows.getZoom": { input: object(target), result: object({ factor: (v) => finite(v) && v >= 0.5 && v <= 2 }) },
|
|
797
|
+
"desktop.windows.setZoom": { input: object({ ...target, factor: (v) => finite(v) && v >= 0.5 && v <= 2 }), result: object({ factor: (v) => finite(v) && v >= 0.5 && v <= 2 }) },
|
|
798
|
+
"desktop.windows.edit": { input: object({ ...target, action: enumeration("undo", "redo", "cut", "copy", "paste", "selectAll") }), result: voidResult },
|
|
799
|
+
"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) }) },
|
|
800
|
+
"desktop.git.listBranches": { input: object(target), result: object({ branches: array(text(1024), 1e4) }) },
|
|
801
|
+
"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 }) },
|
|
802
|
+
"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 }) },
|
|
803
|
+
"desktop.git.switchBranch": { input: object({ ...target, requestId: id, expectedHead: text(), branch: text() }), result: validWorkspaceOperation },
|
|
804
|
+
"desktop.git.createBranch": { input: object({ ...target, requestId: id, expectedHead: text(), branch: text() }), result: validWorkspaceOperation },
|
|
805
|
+
"desktop.git.createTaskWorktree": { input: object({ ...target, requestId: id, expectedHead: text(), branch: text() }), result: validWorkspaceOperation },
|
|
806
|
+
"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") }) },
|
|
807
|
+
"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(finite) }), 1e4) },
|
|
808
|
+
"desktop.terminals.restart": { input: object({ ...target, terminalId: text(), requestId: id }), result: object({ resourceId: text(), terminalId: text(), cwd: text(32768), status: enumeration("running", "exited") }) },
|
|
809
|
+
"desktop.terminals.getRequest": { input: object({ ...target, requestId: id, original: terminalOriginal }), result: terminalReceipt },
|
|
810
|
+
"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 }) },
|
|
811
|
+
"desktop.terminals.subscribe": { input: object({ ...target, terminalId: text() }), result: voidResult },
|
|
812
|
+
"desktop.terminals.write": { input: object({ ...target, terminalId: text(), data: text(1024 * 1024, true) }), result: voidResult },
|
|
813
|
+
"desktop.terminals.resize": { input: object({ ...target, terminalId: text(), cols: positive, rows: positive }), result: voidResult },
|
|
814
|
+
"desktop.terminals.close": { input: (v) => object(target, { terminalId: text(), requestId: id })(v) && Object.hasOwn(v, "terminalId") !== Object.hasOwn(v, "requestId"), result: voidResult },
|
|
815
|
+
"desktop.windows.open": { input: object({ ...target, requestId: id, mode: enumeration("application", "content"), url: text(32768) }), result: windowResult },
|
|
816
|
+
"desktop.windows.adopt": { input: object({ ...target, requestId: id, windowId: count }), result: windowResult },
|
|
817
|
+
"desktop.windows.get": { input: object({ ...target, requestId: id }), result: nullable(windowResult) },
|
|
818
|
+
"desktop.windows.close": { input: object({ ...target, requestId: id }), result: windowResult },
|
|
819
|
+
"desktop.windows.setAlwaysOnTop": { input: object({ ...target, alwaysOnTop: bool }, { requestId: id }), result: object({ alwaysOnTop: bool }) },
|
|
820
|
+
"desktop.windows.focus": { input: object(target, { requestId: id }), result: object({ focused: bool, visible: bool, minimized: bool }) },
|
|
821
|
+
"desktop.browser.register": { input: object({ ...target, tabId: text(), guestId: count }), result: validBrowserSnapshot },
|
|
822
|
+
"desktop.browser.openLocalFile": { input: object({ ...target, path: text(32768) }), result: object({ url: text(32768) }) },
|
|
823
|
+
"desktop.browser.unregister": { input: object({ ...target, tabId: text() }), result: voidResult },
|
|
824
|
+
"desktop.browser.setActive": { input: object({ ...target, tabId: text() }), result: voidResult },
|
|
825
|
+
"desktop.browser.readAnnotations": { input: object(page), result: validBrowserSnapshot },
|
|
826
|
+
"desktop.browser.setAnnotationMode": { input: object({ ...page, mode }), result: validBrowserSnapshot },
|
|
827
|
+
"desktop.browser.addAnnotation": { input: object({ ...page, selectionId: text(), comment: text(65536, true) }), result: validBrowserSnapshot },
|
|
828
|
+
"desktop.browser.focusAnnotation": { input: object({ ...page, annotationId: text() }), result: validBrowserSnapshot },
|
|
829
|
+
"desktop.browser.removeAnnotation": { input: object({ ...page, annotationId: text() }), result: validBrowserSnapshot },
|
|
830
|
+
"desktop.browser.capturePreview": { input: object(page), result: object({ bytes: capturePreviewBytes, width: positive, height: positive }) },
|
|
831
|
+
"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") })) })) }) },
|
|
832
|
+
"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) },
|
|
833
|
+
"desktop.pluginApps.open": { input: object({ ...target, requestId: id, pluginId: text(), surfaceId: text() }, { expectedRevision: count }), result: mounted },
|
|
834
|
+
"desktop.pluginApps.openToolResult": { input: object({ ...target, sourcePartId: text() }), result: object({ mounted, initial: object({ sourcePartId: text(), arguments: jsonObject, result: json }, { dataError: text(128) }) }) },
|
|
835
|
+
"desktop.pluginApps.mount": { input: object({ ...target, source }), result: mounted },
|
|
836
|
+
"desktop.pluginApps.refresh": { input: object(mount), result: state },
|
|
837
|
+
"desktop.pluginApps.rejectMenuOpen": { input: object({ ...mount, requestId: id, menuOpeningRevision: count }), result: object({ closed: bool }) },
|
|
838
|
+
"desktop.pluginApps.prepareTool": { input: object({ ...action, name: text(), arguments: jsonObject }), result: object({ requestId: id, toolName: text(), args: jsonObject, expectedRevision: count }, { policy }) },
|
|
839
|
+
"desktop.pluginApps.invokeTool": { input: object(action), result: (v) => actionResult(v) || object({ code: enumeration("plugin_app_busy"), notAccepted: enumeration(true), requestId: id })(v) },
|
|
840
|
+
"desktop.pluginApps.getAction": { input: (v) => object(action)(v) || object({ ...target, source, requestId: id, expectedRevision: count, original: object({ toolName: text(), args: jsonObject }) })(v), result: actionResult },
|
|
841
|
+
"desktop.pluginApps.cancelTool": { input: object(action), result: voidResult },
|
|
842
|
+
"desktop.pluginApps.readResource": { input: object({ ...mount, source, uri: text(8192) }), result: object({ contents: array(json, 4096) }) },
|
|
843
|
+
"desktop.pluginApps.listResources": { input: object({ ...mount, source }, { cursor: text(8192) }), result: object({ resources: array(json, 4096) }, { nextCursor: text(8192) }) },
|
|
844
|
+
"desktop.pluginApps.listResourceTemplates": { input: object({ ...mount, source }, { cursor: text(8192) }), result: object({ resourceTemplates: array(json, 4096) }, { nextCursor: text(8192) }) },
|
|
845
|
+
"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 }) },
|
|
846
|
+
"desktop.pluginApps.submitMessage": { input: object(action), result: submission },
|
|
847
|
+
"desktop.pluginApps.getMessageSubmission": { input: object(action), result: submission },
|
|
848
|
+
"desktop.pluginApps.cancelMessage": { input: object(action), result: voidResult },
|
|
849
|
+
"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 }) },
|
|
850
|
+
"desktop.pluginApps.release": { input: object(mount), result: voidResult },
|
|
851
|
+
"desktop.pluginApps.closePanel": { input: object(mount), result: voidResult },
|
|
852
|
+
"desktop.pluginApps.closeApp": { input: object(action), result: object({ app: appRecord }) }
|
|
853
|
+
};
|
|
854
|
+
var DESKTOP_METHODS = Object.keys(rules);
|
|
855
|
+
function isDesktopMethod(method) {
|
|
856
|
+
return Object.hasOwn(rules, method);
|
|
857
|
+
}
|
|
858
|
+
function validDesktopInput(method, v) {
|
|
859
|
+
return json(v) && rules[method].input(v);
|
|
860
|
+
}
|
|
861
|
+
function validDesktopResult(method, v) {
|
|
862
|
+
return (method === "desktop.browser.capturePreview" || v === void 0 || json(v)) && rules[method].result(v);
|
|
863
|
+
}
|
|
864
|
+
function validDesktopResultForInput(method, input, result) {
|
|
865
|
+
if (!validDesktopResult(method, result)) return false;
|
|
866
|
+
if (!result || typeof result !== "object") return true;
|
|
867
|
+
const params = input, value = result;
|
|
868
|
+
if (Object.hasOwn(params, "requestId") && Object.hasOwn(value, "requestId") && value.requestId !== params.requestId) return false;
|
|
869
|
+
if (Object.hasOwn(value, "targetId") && value.targetId !== params.targetId) return false;
|
|
870
|
+
if (method.startsWith("desktop.browser.") && method !== "desktop.browser.readAnnotations" && Object.hasOwn(params, "pageRevision") && Object.hasOwn(value, "pageRevision") && value.pageRevision !== params.pageRevision) return false;
|
|
871
|
+
if (method.startsWith("desktop.pluginApps.") && Object.hasOwn(params, "requestId") && Object.hasOwn(value, "receipt") && value.receipt.requestId !== params.requestId) return false;
|
|
872
|
+
if ((method === "desktop.pluginApps.prepareTool" || method === "desktop.pluginApps.prepareMessage") && (value.expectedRevision !== params.expectedRevision || value.requestId !== params.requestId)) return false;
|
|
873
|
+
if (method === "desktop.files.getOperation" && value.kind !== params.original.kind) return false;
|
|
874
|
+
return true;
|
|
875
|
+
}
|
|
876
|
+
var browserChangeEvent = object(
|
|
877
|
+
{ type: enumeration("browser-changed"), targetId: text(), tabId: text(), pageRevision: count, snapshot: validBrowserSnapshot },
|
|
878
|
+
{ invalidated: enumeration(true) }
|
|
879
|
+
);
|
|
880
|
+
function validDesktopEvent(v) {
|
|
881
|
+
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(finite) })(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);
|
|
882
|
+
if (!json(v)) return false;
|
|
883
|
+
if (browserChangeEvent(v)) {
|
|
884
|
+
const event = v;
|
|
885
|
+
return event.pageRevision === event.snapshot.pageRevision;
|
|
886
|
+
}
|
|
887
|
+
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);
|
|
888
|
+
}
|
|
889
|
+
function createAppDesktopApi(rpc, owner, filesFeature = () => {
|
|
890
|
+
}) {
|
|
891
|
+
const call = async (method, params) => {
|
|
892
|
+
if (!validDesktopInput(method, params)) throw new AppHostError("invalid_request");
|
|
893
|
+
rpc.requireFeature(method);
|
|
894
|
+
const value = await rpc.request(method, params);
|
|
895
|
+
if (!validDesktopResultForInput(method, params, value)) throw new AppHostError("host_unavailable");
|
|
896
|
+
return value;
|
|
897
|
+
};
|
|
898
|
+
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)]));
|
|
899
|
+
return { bindTarget(input) {
|
|
900
|
+
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");
|
|
901
|
+
const { connection, ...rest } = input;
|
|
902
|
+
return call("desktop.bindTarget", { ...rest, ...connection === void 0 ? {} : { connectionId: resolveClientConnection(connection, owner) } });
|
|
903
|
+
}, releaseTarget: (input) => call("desktop.releaseTarget", input), files: Object.assign(group("files"), { async readFile(input, options = {}) {
|
|
904
|
+
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");
|
|
905
|
+
filesFeature();
|
|
906
|
+
const { range: range2, ...params } = input;
|
|
907
|
+
const wire = await call("desktop.files.openRead", params);
|
|
908
|
+
const fetchFile = owner.fetchFor(wire.connectionId, wire.baseUrl);
|
|
909
|
+
try {
|
|
910
|
+
return await fetchFile(wire.baseUrl + "/", { ...options.signal ? { signal: options.signal } : {}, ...range2 ? { headers: { Range: `bytes=${range2.start}-${range2.end ?? ""}` } } : {} });
|
|
911
|
+
} catch (error) {
|
|
912
|
+
owner.close(wire.connectionId);
|
|
913
|
+
throw error;
|
|
914
|
+
}
|
|
915
|
+
} }), clipboard: group("clipboard"), git: group("git"), terminals: group("terminals"), windows: group("windows"), browser: group("browser"), pluginApps: group("pluginApps") };
|
|
916
|
+
}
|
|
917
|
+
function canonicalDesktopRequest(value) {
|
|
918
|
+
if (!json(value)) throw new AppHostError("invalid_request");
|
|
919
|
+
const normalize = (v) => {
|
|
920
|
+
if (v === null || typeof v === "string" || typeof v === "boolean" || typeof v === "number") return v;
|
|
921
|
+
if (Array.isArray(v)) return v.map(normalize);
|
|
922
|
+
return Object.fromEntries(Object.keys(v).sort().map((k) => [k, normalize(v[k])]));
|
|
923
|
+
};
|
|
924
|
+
return JSON.stringify(normalize(value));
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// src/extensions.ts
|
|
928
|
+
var empty = object({});
|
|
929
|
+
var cwd = object({ cwd: text(4096) });
|
|
930
|
+
var plugin = object({ cwd: text(4096), pluginId: text(256) });
|
|
931
|
+
var selection = object({ cwd: text(4096), selectionId: text(256) });
|
|
932
|
+
var cancel = object({ selectionId: text(256) });
|
|
933
|
+
var name = object({ name: text(256) });
|
|
934
|
+
var login = object({ loginId: text(256) });
|
|
935
|
+
var EXTENSION_INPUTS = {
|
|
936
|
+
context: empty,
|
|
937
|
+
"plugins.loadIcon": object({ src: text(8192) }),
|
|
938
|
+
"plugins.snapshot": cwd,
|
|
939
|
+
"plugins.enable": plugin,
|
|
940
|
+
"plugins.disable": plugin,
|
|
941
|
+
"plugins.uninstall": plugin,
|
|
942
|
+
"plugins.reload": cwd,
|
|
943
|
+
"plugins.importArchive": cwd,
|
|
944
|
+
"plugins.confirmArchive": selection,
|
|
945
|
+
"plugins.cancelArchive": cancel,
|
|
946
|
+
"plugins.importGit": object({ cwd: text(4096), url: text(8192) }, { ref: text(1024) }),
|
|
947
|
+
"plugins.confirmGit": selection,
|
|
948
|
+
"plugins.cancelGit": cancel,
|
|
949
|
+
"plugins.marketplaceCatalog": object({ cwd: text(4096) }, { refresh: bool }),
|
|
950
|
+
"plugins.marketplaceAddSource": object({ url: text(8192) }),
|
|
951
|
+
"plugins.marketplaceSetSourceEnabled": object({ sourceId: text(256), enabled: bool }),
|
|
952
|
+
"plugins.marketplaceRemoveSource": object({ sourceId: text(256) }),
|
|
953
|
+
"plugins.marketplacePreview": object({ cwd: text(4096), sourceId: text(256), pluginId: text(256) }, { version: text(256) }),
|
|
954
|
+
"plugins.marketplaceConfirm": selection,
|
|
955
|
+
"plugins.marketplaceCancel": cancel,
|
|
956
|
+
"plugins.marketplaceOperation": object({ cwd: text(4096), operationId: text(256) }),
|
|
957
|
+
"skills.snapshot": object({ projectPath: text(4096) }),
|
|
958
|
+
"skills.remove": object({ id: text(4096), expectedContent: text(8 * 1024 * 1024, true), projectPath: text(4096) }),
|
|
959
|
+
"mcp.snapshot": empty,
|
|
960
|
+
"mcp.exportConfig": empty,
|
|
961
|
+
"mcp.getConfig": name,
|
|
962
|
+
"mcp.add": object({ name: text(256), config: jsonObject }),
|
|
963
|
+
"mcp.update": object({ name: text(256), config: jsonObject, expectedConfig: jsonObject }),
|
|
964
|
+
"mcp.remove": name,
|
|
965
|
+
"mcp.setEnabled": object({ name: text(256), enabled: bool }),
|
|
966
|
+
"mcp.login": object({ name: text(256), scopes: array(text(2048), 128) }),
|
|
967
|
+
"mcp.loginStatus": login,
|
|
968
|
+
"mcp.cancelLogin": login,
|
|
969
|
+
"mcp.logout": name
|
|
970
|
+
};
|
|
971
|
+
function validExtensionRequest(value) {
|
|
972
|
+
if (!object({ operation: text(128), input: jsonObject })(value)) return false;
|
|
973
|
+
const request = value;
|
|
974
|
+
return Object.hasOwn(EXTENSION_INPUTS, request.operation) && EXTENSION_INPUTS[request.operation](request.input);
|
|
975
|
+
}
|
|
976
|
+
var validExtensionResult = (value) => value === void 0 || json(value);
|
|
977
|
+
|
|
978
|
+
// src/projects.ts
|
|
979
|
+
var id2 = text(256);
|
|
980
|
+
var scope = { dataScopeId: id2 };
|
|
981
|
+
var project = { ...scope, projectId: id2, workspaceId: id2 };
|
|
982
|
+
function validProjectRequest(value) {
|
|
983
|
+
const action2 = value && typeof value === "object" ? Object.getOwnPropertyDescriptor(value, "action")?.value : void 0;
|
|
984
|
+
switch (action2) {
|
|
985
|
+
case "list":
|
|
986
|
+
return object({ action: (v) => v === "list" })(value);
|
|
987
|
+
case "register":
|
|
988
|
+
return object({ action: (v) => v === "register", ...scope, workspaceId: id2 })(value);
|
|
989
|
+
case "setDefaultShell":
|
|
990
|
+
return object({ action: (v) => v === "setDefaultShell", ...project, shell: (v) => v === null || text(4096)(v) })(value);
|
|
991
|
+
case "archive":
|
|
992
|
+
return object({ action: (v) => v === "archive", ...project })(value);
|
|
993
|
+
case "rebind":
|
|
994
|
+
return object({ action: (v) => v === "rebind", ...scope, workspaceId: id2, previousWorkspaceId: id2 }, { projectId: id2, previousPath: text(32768) })(value);
|
|
995
|
+
default:
|
|
996
|
+
return false;
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
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);
|
|
1000
|
+
|
|
1001
|
+
// ../domain-contracts/src/app-host/model-providers.ts
|
|
1002
|
+
var provider = text(256);
|
|
1003
|
+
var imageInputSupport = enumeration("native", "unsupported", "unknown");
|
|
1004
|
+
var limits = { contextWindow: count, maxOutputTokens: count };
|
|
1005
|
+
function headerValues(check) {
|
|
1006
|
+
return (value) => {
|
|
1007
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1008
|
+
const keys2 = Object.keys(value);
|
|
1009
|
+
return keys2.length <= 128 && keys2.every((key) => /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,256}$/.test(key)) && object(Object.fromEntries(keys2.map((key) => [key, check])))(value);
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
var headers = headerValues(text(8192, true));
|
|
1013
|
+
var secretHeaders = headerValues(nullable(text(8192)));
|
|
1014
|
+
var customProvider = object({
|
|
1015
|
+
id: provider,
|
|
1016
|
+
displayName: text(1024),
|
|
1017
|
+
baseUrl: text(4096),
|
|
1018
|
+
apiFormat: enumeration("openai"),
|
|
1019
|
+
models: array(object({ id: text(1024), displayName: text(1024) }, { imageInputSupport, ...limits }), 16384)
|
|
1020
|
+
}, { apiKey: text(8192), headers, secretHeaders });
|
|
1021
|
+
function validModelProviderRequest(value) {
|
|
1022
|
+
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);
|
|
1023
|
+
}
|
|
1024
|
+
var validModel = object({ id: text(1024), label: text(1024) }, { imageInputSupport, declaredLimits: object({}, limits) });
|
|
1025
|
+
var validConnection2 = object({
|
|
1026
|
+
name: provider,
|
|
1027
|
+
displayName: text(1024),
|
|
1028
|
+
connected: bool,
|
|
1029
|
+
active: bool,
|
|
1030
|
+
credentialSource: enumeration("credentials", "environment", "subscription", "local", "configured", "none"),
|
|
1031
|
+
models: array(validModel, 16384)
|
|
1032
|
+
}, { source: enumeration("builtin", "catalog", "custom", "subscription"), custom: bool, credentialLabel: text(1024), baseUrl: text(4096), headers, secretHeaderNames: array(text(256), 128) });
|
|
1033
|
+
function validModelProviderConnections(value) {
|
|
1034
|
+
return array(validConnection2, 4096)(value);
|
|
1035
|
+
}
|
|
1036
|
+
var modelId = text(1024);
|
|
1037
|
+
var effort = nullable(text(256));
|
|
1038
|
+
var revision = text(8192);
|
|
1039
|
+
function validProviderDefaultsRequest(value) {
|
|
1040
|
+
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);
|
|
1041
|
+
}
|
|
1042
|
+
var verifiedProvider = object({ model: modelId, checkedAt: count });
|
|
1043
|
+
var verified = (value) => {
|
|
1044
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1045
|
+
const keys2 = Object.keys(value);
|
|
1046
|
+
return keys2.length <= 4096 && keys2.every(provider) && object(Object.fromEntries(keys2.map((key) => [key, verifiedProvider])))(value);
|
|
1047
|
+
};
|
|
1048
|
+
var defaultsModel = object({ id: modelId, label: text(1024), provider: text(1024), providerName: provider }, {
|
|
1049
|
+
reasoningEfforts: array(text(256, true)),
|
|
1050
|
+
contextWindow: count,
|
|
1051
|
+
inputModalities: array(text(256)),
|
|
1052
|
+
inputCapabilities: object({ image: imageInputSupport })
|
|
1053
|
+
});
|
|
1054
|
+
var validProviderDefaultsSnapshot = object({
|
|
1055
|
+
models: array(defaultsModel, 16384),
|
|
1056
|
+
provider: nullable(provider),
|
|
1057
|
+
model: nullable(modelId),
|
|
1058
|
+
effort,
|
|
1059
|
+
disabled: bool,
|
|
1060
|
+
revision,
|
|
1061
|
+
verified,
|
|
1062
|
+
fastModeAvailable: enumeration(false),
|
|
1063
|
+
fastModeReason: text(1024)
|
|
1064
|
+
});
|
|
1065
|
+
var validProviderConnectionTestResult = object({
|
|
1066
|
+
status: enumeration("verified", "failed"),
|
|
1067
|
+
detail: text(8192),
|
|
1068
|
+
checkedAt: count
|
|
1069
|
+
}, { category: enumeration("authentication", "address", "network", "model", "unsupported", "service") });
|
|
1070
|
+
|
|
1071
|
+
// src/system.ts
|
|
1072
|
+
var SYSTEM_SETTINGS_SECTIONS = [
|
|
1073
|
+
"general",
|
|
1074
|
+
"notifications",
|
|
1075
|
+
"profile",
|
|
1076
|
+
"appearance",
|
|
1077
|
+
"keyboard",
|
|
1078
|
+
"providers",
|
|
1079
|
+
"permissions",
|
|
1080
|
+
"personalization",
|
|
1081
|
+
"billing",
|
|
1082
|
+
"connections",
|
|
1083
|
+
"terminal",
|
|
1084
|
+
"git",
|
|
1085
|
+
"runtime",
|
|
1086
|
+
"storage",
|
|
1087
|
+
"diagnostics"
|
|
1088
|
+
];
|
|
1089
|
+
var SYSTEM_SHORTCUT_IDS = [
|
|
1090
|
+
"searchChats",
|
|
1091
|
+
"newConversation",
|
|
1092
|
+
"chooseProject",
|
|
1093
|
+
"closeConversation",
|
|
1094
|
+
"quit",
|
|
1095
|
+
"toggleSidebar",
|
|
1096
|
+
"togglePanel",
|
|
1097
|
+
"openBrowser",
|
|
1098
|
+
"openFiles",
|
|
1099
|
+
"openTerminal",
|
|
1100
|
+
"previousSession",
|
|
1101
|
+
"nextSession",
|
|
1102
|
+
"goBack",
|
|
1103
|
+
"goForward",
|
|
1104
|
+
"zoomIn",
|
|
1105
|
+
"zoomOut",
|
|
1106
|
+
"resetZoom",
|
|
1107
|
+
"showShortcuts"
|
|
1108
|
+
];
|
|
1109
|
+
var SYSTEM_METHODS = [
|
|
1110
|
+
"system.projects",
|
|
1111
|
+
"system.extensions",
|
|
1112
|
+
"system.modelProviders",
|
|
1113
|
+
"system.providerDefaults",
|
|
1114
|
+
"system.open",
|
|
1115
|
+
"system.getPresentationPreferences",
|
|
1116
|
+
"system.setTheme",
|
|
1117
|
+
"system.setWindowMaterial",
|
|
1118
|
+
"system.copyText",
|
|
1119
|
+
"system.openExternal",
|
|
1120
|
+
"system.markSessionRead",
|
|
1121
|
+
"system.navigationReady",
|
|
1122
|
+
"system.completeNavigation"
|
|
1123
|
+
];
|
|
1124
|
+
var hex = (v) => typeof v === "string" && /^#[a-fA-F0-9]{6}$/.test(v);
|
|
1125
|
+
var palette = object({
|
|
1126
|
+
background: nullable(hex),
|
|
1127
|
+
foreground: nullable(hex)
|
|
1128
|
+
});
|
|
1129
|
+
var range = (min, max) => (v) => count(v) && v >= min && v <= max;
|
|
1130
|
+
var themeMode = enumeration("system", "light", "dark");
|
|
1131
|
+
var appearance = object({
|
|
1132
|
+
version: enumeration(1),
|
|
1133
|
+
theme: themeMode,
|
|
1134
|
+
accent: (v) => object({
|
|
1135
|
+
kind: enumeration("preset"),
|
|
1136
|
+
id: enumeration("neutral", "blue", "violet", "terracotta", "green")
|
|
1137
|
+
})(v) || object({ kind: enumeration("custom"), value: hex })(v),
|
|
1138
|
+
colors: object({ light: palette, dark: palette }),
|
|
1139
|
+
uiFont: enumeration("system", "segoe-ui", "inter"),
|
|
1140
|
+
codeFont: enumeration(
|
|
1141
|
+
"system",
|
|
1142
|
+
"cascadia-code",
|
|
1143
|
+
"cascadia-mono",
|
|
1144
|
+
"geist-mono",
|
|
1145
|
+
"consolas"
|
|
1146
|
+
),
|
|
1147
|
+
uiFontSize: range(12, 18),
|
|
1148
|
+
codeFontSize: range(11, 18),
|
|
1149
|
+
reducedMotion: enumeration("system", "on", "off"),
|
|
1150
|
+
streamingTextAnimation: bool,
|
|
1151
|
+
glassStrength: range(0, 100)
|
|
1152
|
+
});
|
|
1153
|
+
var overrides = object(
|
|
1154
|
+
{},
|
|
1155
|
+
Object.fromEntries(
|
|
1156
|
+
SYSTEM_SHORTCUT_IDS.map((id3) => [
|
|
1157
|
+
id3,
|
|
1158
|
+
object({ binding: text(256, true), keys: text(128, true) })
|
|
1159
|
+
])
|
|
1160
|
+
)
|
|
1161
|
+
);
|
|
1162
|
+
var validPresentationSnapshot = (v) => object({
|
|
1163
|
+
revision: count,
|
|
1164
|
+
appearance,
|
|
1165
|
+
editor: object({
|
|
1166
|
+
readOnly: bool,
|
|
1167
|
+
wordWrap: bool,
|
|
1168
|
+
tabSize: enumeration(2, 4)
|
|
1169
|
+
}),
|
|
1170
|
+
shortcutOverrides: overrides
|
|
1171
|
+
})(v);
|
|
1172
|
+
var validDesktopNavigationTarget = (v) => object(
|
|
1173
|
+
{
|
|
1174
|
+
id: text(256),
|
|
1175
|
+
dataScopeId: text(256),
|
|
1176
|
+
kind: enumeration("session"),
|
|
1177
|
+
sessionId: text(256)
|
|
1178
|
+
},
|
|
1179
|
+
{ messageId: text(256), permissionId: text(256), attentionId: text(256) }
|
|
1180
|
+
)(v) || object(
|
|
1181
|
+
{
|
|
1182
|
+
id: text(256),
|
|
1183
|
+
dataScopeId: text(256),
|
|
1184
|
+
kind: enumeration("scheduled"),
|
|
1185
|
+
taskId: text(256),
|
|
1186
|
+
scheduledRunId: text(256)
|
|
1187
|
+
},
|
|
1188
|
+
{ sessionId: text(256) }
|
|
1189
|
+
)(v);
|
|
1190
|
+
function isSystemMethod(v) {
|
|
1191
|
+
return SYSTEM_METHODS.includes(v);
|
|
1192
|
+
}
|
|
1193
|
+
function validSessionSettingsTarget(value) {
|
|
1194
|
+
if (object({
|
|
1195
|
+
kind: enumeration("connection"),
|
|
1196
|
+
connectionId: text(256),
|
|
1197
|
+
sessionId: text(256)
|
|
1198
|
+
})(value))
|
|
1199
|
+
return true;
|
|
1200
|
+
const v = value;
|
|
1201
|
+
if (!v || v.kind !== "fork") return false;
|
|
1202
|
+
const { kind: kind2, ...query } = v;
|
|
1203
|
+
return validSessionControlInput("sessions.getControlResult", query) && "original" in v && v.original.action === "fork";
|
|
1204
|
+
}
|
|
1205
|
+
function validSystemInput(method, value) {
|
|
1206
|
+
switch (method) {
|
|
1207
|
+
case "system.projects":
|
|
1208
|
+
return validProjectRequest(value);
|
|
1209
|
+
case "system.extensions":
|
|
1210
|
+
return validExtensionRequest(value);
|
|
1211
|
+
case "system.modelProviders":
|
|
1212
|
+
return validModelProviderRequest(value);
|
|
1213
|
+
case "system.providerDefaults":
|
|
1214
|
+
return validProviderDefaultsRequest(value);
|
|
1215
|
+
case "system.setTheme":
|
|
1216
|
+
return object({ theme: themeMode })(value);
|
|
1217
|
+
case "system.setWindowMaterial":
|
|
1218
|
+
return object({ preference: enumeration("glass", "opaque") })(value);
|
|
1219
|
+
case "system.copyText":
|
|
1220
|
+
return object({ text: text(8 * 1024 * 1024, true) })(value);
|
|
1221
|
+
case "system.openExternal":
|
|
1222
|
+
return object({ url: text(16384) })(value);
|
|
1223
|
+
case "system.open":
|
|
1224
|
+
return object({ page: enumeration("notes") }, { noteId: text(256) })(value) || object(
|
|
1225
|
+
{ page: enumeration("scheduled") },
|
|
1226
|
+
{ taskId: text(256), scheduledRunId: text(256) }
|
|
1227
|
+
)(value) && (!Object.hasOwn(value, "scheduledRunId") || Object.hasOwn(value, "taskId")) || object(
|
|
1228
|
+
{ page: enumeration("extensions") },
|
|
1229
|
+
{ tab: enumeration("plugins", "skills", "mcp") }
|
|
1230
|
+
)(value) || object(
|
|
1231
|
+
{ page: enumeration("settings") },
|
|
1232
|
+
{ section: enumeration(...SYSTEM_SETTINGS_SECTIONS) }
|
|
1233
|
+
)(value) || object({ page: enumeration("pet") })(value) || object(
|
|
1234
|
+
{ page: enumeration("search") },
|
|
1235
|
+
{ query: text(2e3, true) }
|
|
1236
|
+
)(value) || object({
|
|
1237
|
+
page: enumeration("session-settings"),
|
|
1238
|
+
target: validSessionSettingsTarget
|
|
1239
|
+
})(value);
|
|
1240
|
+
case "system.markSessionRead":
|
|
1241
|
+
return object({
|
|
1242
|
+
connectionId: text(256),
|
|
1243
|
+
sessionId: text(256),
|
|
1244
|
+
throughSeq: count
|
|
1245
|
+
})(value);
|
|
1246
|
+
case "system.completeNavigation":
|
|
1247
|
+
return object({
|
|
1248
|
+
id: text(256),
|
|
1249
|
+
status: enumeration(
|
|
1250
|
+
"opened",
|
|
1251
|
+
"unavailable",
|
|
1252
|
+
"permission_required",
|
|
1253
|
+
"cancelled"
|
|
1254
|
+
)
|
|
1255
|
+
})(value);
|
|
1256
|
+
default:
|
|
1257
|
+
return object({})(value);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
function validSystemResult(method, value) {
|
|
1261
|
+
switch (method) {
|
|
1262
|
+
case "system.projects":
|
|
1263
|
+
return validProjectSnapshot(value);
|
|
1264
|
+
case "system.extensions":
|
|
1265
|
+
return validExtensionResult(value);
|
|
1266
|
+
case "system.modelProviders":
|
|
1267
|
+
return validModelProviderConnections(value);
|
|
1268
|
+
case "system.providerDefaults":
|
|
1269
|
+
return validProviderDefaultsSnapshot(value) || validProviderConnectionTestResult(value);
|
|
1270
|
+
case "system.open":
|
|
1271
|
+
return object({ opened: enumeration(true) })(value);
|
|
1272
|
+
case "system.getPresentationPreferences":
|
|
1273
|
+
return validPresentationSnapshot(value);
|
|
1274
|
+
case "system.setTheme":
|
|
1275
|
+
return validPresentationSnapshot(value);
|
|
1276
|
+
case "system.navigationReady":
|
|
1277
|
+
return object({ pending: nullable(validDesktopNavigationTarget) })(value);
|
|
1278
|
+
default:
|
|
1279
|
+
return value === void 0;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
function validSystemEvent(value) {
|
|
1283
|
+
return object({
|
|
1284
|
+
type: enumeration("system-navigation-requested"),
|
|
1285
|
+
viewEpoch: count,
|
|
1286
|
+
target: validDesktopNavigationTarget
|
|
1287
|
+
})(value) || object({
|
|
1288
|
+
type: enumeration("presentation-preferences-changed"),
|
|
1289
|
+
revision: count
|
|
1290
|
+
})(value) || object({
|
|
1291
|
+
type: enumeration("git-preferences-changed"),
|
|
1292
|
+
defaultTaskLocation: enumeration("current", "worktree")
|
|
1293
|
+
})(value);
|
|
1294
|
+
}
|
|
1295
|
+
function createAppSystemApi(requester, connectionOwner) {
|
|
1296
|
+
function send(method, params) {
|
|
1297
|
+
requester.requireFeature();
|
|
1298
|
+
if (!validSystemInput(method, params))
|
|
1299
|
+
throw new AppHostError("invalid_request");
|
|
1300
|
+
return requester.request(method, params);
|
|
1301
|
+
}
|
|
1302
|
+
return {
|
|
1303
|
+
projects: (input) => send("system.projects", input),
|
|
1304
|
+
extensions: (input) => send("system.extensions", input),
|
|
1305
|
+
modelProviders: (input) => send("system.modelProviders", input),
|
|
1306
|
+
providerDefaults: (async (input) => {
|
|
1307
|
+
const result = await send("system.providerDefaults", input);
|
|
1308
|
+
if (!(input.action === "test" ? validProviderConnectionTestResult(result) : validProviderDefaultsSnapshot(result)))
|
|
1309
|
+
throw new AppHostError("invalid_request");
|
|
1310
|
+
return result;
|
|
1311
|
+
}),
|
|
1312
|
+
open: (input) => {
|
|
1313
|
+
if (input.page !== "session-settings") return send("system.open", input);
|
|
1314
|
+
const { target: target2 } = input;
|
|
1315
|
+
const wire = "connection" in target2 ? (() => {
|
|
1316
|
+
const { connection, ...rest } = target2;
|
|
1317
|
+
return {
|
|
1318
|
+
...rest,
|
|
1319
|
+
connectionId: resolveClientConnection(
|
|
1320
|
+
connection,
|
|
1321
|
+
connectionOwner
|
|
1322
|
+
)
|
|
1323
|
+
};
|
|
1324
|
+
})() : target2;
|
|
1325
|
+
return send("system.open", { page: "session-settings", target: wire });
|
|
1326
|
+
},
|
|
1327
|
+
getPresentationPreferences: () => send("system.getPresentationPreferences", {}),
|
|
1328
|
+
setTheme: (theme) => send("system.setTheme", { theme }),
|
|
1329
|
+
setWindowMaterial: (preference) => send("system.setWindowMaterial", { preference }),
|
|
1330
|
+
copyText: (text2) => send("system.copyText", { text: text2 }),
|
|
1331
|
+
openExternal: (url) => send("system.openExternal", { url }),
|
|
1332
|
+
markSessionRead: ({ connection, sessionId, throughSeq }) => send("system.markSessionRead", {
|
|
1333
|
+
connectionId: resolveClientConnection(connection, connectionOwner),
|
|
1334
|
+
sessionId,
|
|
1335
|
+
throughSeq
|
|
1336
|
+
}),
|
|
1337
|
+
navigationReady: () => send("system.navigationReady", {}),
|
|
1338
|
+
completeNavigation: (input) => send("system.completeNavigation", input)
|
|
1339
|
+
};
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
// src/window.ts
|
|
1343
|
+
var WINDOW_METHODS = ["window.getState", "window.minimize", "window.toggleMaximize", "window.requestClose", "window.openHost", "window.reportStartup"];
|
|
1344
|
+
var finite2 = (value) => typeof value === "number" && Number.isFinite(value);
|
|
1345
|
+
var material = object({
|
|
1346
|
+
preference: enumeration("glass", "opaque"),
|
|
1347
|
+
active: enumeration("glass", "opaque"),
|
|
1348
|
+
shell: enumeration("solid", "translucent", "transparent"),
|
|
1349
|
+
unavailableReason: nullable(enumeration("unsupported-platform", "unsupported-system", "reduced-transparency", "material-error"))
|
|
1350
|
+
});
|
|
1351
|
+
var validAppWindowState = (value) => object({
|
|
1352
|
+
platform: enumeration("win32", "darwin", "linux"),
|
|
1353
|
+
maximized: bool,
|
|
1354
|
+
titleBar: enumeration("host", "custom", "native"),
|
|
1355
|
+
trafficLightInset: (value2) => finite2(value2) && value2 >= 0,
|
|
1356
|
+
material
|
|
1357
|
+
})(value);
|
|
1358
|
+
function isWindowMethod(value) {
|
|
1359
|
+
return WINDOW_METHODS.includes(value);
|
|
1360
|
+
}
|
|
1361
|
+
function validWindowInput(method, value) {
|
|
1362
|
+
switch (method) {
|
|
1363
|
+
case "window.openHost":
|
|
1364
|
+
return object({ page: enumeration("manage", "settings", "about", "recovery") })(value);
|
|
1365
|
+
case "window.reportStartup":
|
|
1366
|
+
return object({ status: enumeration("ready") })(value) || object({ status: enumeration("failed"), message: text(2048) })(value);
|
|
1367
|
+
default:
|
|
1368
|
+
return object({})(value);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
function validWindowResult(method, value) {
|
|
1372
|
+
switch (method) {
|
|
1373
|
+
case "window.getState":
|
|
1374
|
+
return validAppWindowState(value);
|
|
1375
|
+
default:
|
|
1376
|
+
return value === void 0;
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
function validWindowEvent(value) {
|
|
1380
|
+
return object({ type: enumeration("window-state-changed"), state: validAppWindowState })(value);
|
|
1381
|
+
}
|
|
1382
|
+
function createAppWindowApi(requester) {
|
|
1383
|
+
async function send(method, params) {
|
|
1384
|
+
requester.requireFeature();
|
|
1385
|
+
if (!validWindowInput(method, params)) throw new AppHostError("invalid_request");
|
|
1386
|
+
return requester.request(method, params);
|
|
1387
|
+
}
|
|
1388
|
+
return {
|
|
1389
|
+
getState: () => send("window.getState", {}),
|
|
1390
|
+
minimize: () => send("window.minimize", {}),
|
|
1391
|
+
toggleMaximize: () => send("window.toggleMaximize", {}),
|
|
1392
|
+
requestClose: () => send("window.requestClose", {}),
|
|
1393
|
+
openHost: (input) => send("window.openHost", input),
|
|
1394
|
+
reportStartup: (input) => send("window.reportStartup", input),
|
|
1395
|
+
onStateChanged: (listener) => {
|
|
1396
|
+
requester.requireFeature();
|
|
1397
|
+
if (typeof listener !== "function") throw new AppHostError("invalid_request");
|
|
1398
|
+
return requester.onEvent((event) => {
|
|
1399
|
+
if (event.type === "window-state-changed") listener(event.state);
|
|
1400
|
+
});
|
|
1401
|
+
}
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
// src/attachments.ts
|
|
1406
|
+
var ATTACHMENTS_METHODS = ["attachments.getConnection"];
|
|
1407
|
+
function validAttachmentsInput(v) {
|
|
1408
|
+
return object({ targetId: text(256) })(v);
|
|
1409
|
+
}
|
|
1410
|
+
var validAttachmentsResult = validConnection;
|
|
1411
|
+
function createAppAttachmentsApi(rpc, streams) {
|
|
1412
|
+
return { async getConnection(input) {
|
|
1413
|
+
if (!validAttachmentsInput(input)) throw new AppHostError("invalid_request");
|
|
1414
|
+
rpc.requireFeature();
|
|
1415
|
+
const wire = await rpc.request("attachments.getConnection", input);
|
|
1416
|
+
if (!validConnection(wire)) throw new AppHostError("host_unavailable");
|
|
1417
|
+
return createClientConnection(wire, streams);
|
|
1418
|
+
} };
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
// src/auxiliary.ts
|
|
1422
|
+
var AUXILIARY_METHODS = ["sessions.getAuxiliaryOptions", "sessions.openAuxiliary", "sessions.getAuxiliary", "sessions.closeAuxiliary"];
|
|
1423
|
+
var selection2 = object({ optionsRevision: text(), model: text(), workMode: text(), effort: text(1024, true) });
|
|
1424
|
+
var tuple = object({ connectionId: text(), sessionId: text(), requestId: id, id: text(), selection: selection2 });
|
|
1425
|
+
var receipt2 = object({ requestId: id, id: text(), state: enumeration("opening", "open", "closing", "closed") }, { leaseId: text(), sessionId: text() });
|
|
1426
|
+
function isAuxiliaryMethod(method) {
|
|
1427
|
+
return AUXILIARY_METHODS.includes(method);
|
|
1428
|
+
}
|
|
1429
|
+
function validAuxiliaryInput(method, v) {
|
|
1430
|
+
return json(v) && (method === "sessions.getAuxiliaryOptions" ? object({ connectionId: text(), sessionId: text() })(v) : tuple(v));
|
|
1431
|
+
}
|
|
1432
|
+
function validAuxiliaryResult(method, v) {
|
|
1433
|
+
if (!json(v)) return false;
|
|
1434
|
+
if (method === "sessions.getAuxiliaryOptions") {
|
|
1435
|
+
const choice = array(object({ id: text(), name: text() }));
|
|
1436
|
+
return object({ optionsRevision: text(), models: choice, workModes: choice, efforts: array(object({ id: text(1024, true), name: text() })) })(v);
|
|
1437
|
+
}
|
|
1438
|
+
if (method === "sessions.getAuxiliary") return v === null || receipt2(v);
|
|
1439
|
+
if (method === "sessions.closeAuxiliary") return receipt2(v);
|
|
1440
|
+
if (!object({ receipt: receipt2, connectionId: text(), baseUrl: text(2048) })(v)) return false;
|
|
1441
|
+
const wire = v;
|
|
1442
|
+
return wire.receipt.state === "open" && !!wire.receipt.leaseId && !!wire.receipt.sessionId && validConnection({ connectionId: wire.connectionId, baseUrl: wire.baseUrl });
|
|
1443
|
+
}
|
|
1444
|
+
function createAppAuxiliarySessionsApi(rpc, streams) {
|
|
1445
|
+
const request = async (method, input) => {
|
|
1446
|
+
if (!validAuxiliaryInput(method, input)) throw new AppHostError("invalid_request");
|
|
1447
|
+
rpc.requireFeature();
|
|
1448
|
+
const value = await rpc.request(method, input);
|
|
1449
|
+
if (!validAuxiliaryResult(method, value)) throw new AppHostError("host_unavailable");
|
|
1450
|
+
if (method !== "sessions.getAuxiliaryOptions" && value !== null) {
|
|
1451
|
+
const original = input;
|
|
1452
|
+
const settled = method === "sessions.openAuxiliary" ? value.receipt : value;
|
|
1453
|
+
if (settled.requestId !== original.requestId || settled.id !== original.id) throw new AppHostError("host_unavailable");
|
|
1454
|
+
}
|
|
1455
|
+
return value;
|
|
1456
|
+
};
|
|
1457
|
+
const resolve = (input) => {
|
|
1458
|
+
const { connection, ...rest } = input;
|
|
1459
|
+
return { ...rest, connectionId: resolveClientConnection(connection, streams) };
|
|
1460
|
+
};
|
|
1461
|
+
return { getAuxiliaryOptions: (input) => request("sessions.getAuxiliaryOptions", { sessionId: input.sessionId, connectionId: resolveClientConnection(input.connection, streams) }), async openAuxiliary(input) {
|
|
1462
|
+
const wire = await request("sessions.openAuxiliary", resolve(input));
|
|
1463
|
+
return { leaseId: wire.receipt.leaseId, sessionId: wire.receipt.sessionId, connection: createClientConnection(wire, streams) };
|
|
1464
|
+
}, getAuxiliary: (input) => request("sessions.getAuxiliary", resolve(input)), closeAuxiliary: (input) => request("sessions.closeAuxiliary", resolve(input)) };
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
// src/workspace.ts
|
|
1468
|
+
function createAppWorkspaceApi(input) {
|
|
1469
|
+
async function call(method, params) {
|
|
1470
|
+
if (!validWorkspaceInput(method, params)) throw new AppHostError("invalid_request");
|
|
1471
|
+
input.requireFeature();
|
|
1472
|
+
const value = await input.request(method, params);
|
|
1473
|
+
if (!validWorkspaceResult(method, value)) throw new AppHostError("host_unavailable");
|
|
1474
|
+
return value;
|
|
1475
|
+
}
|
|
1476
|
+
return { select: (x) => call("workspace.select", x), getSelection: (x) => call("workspace.getSelection", x), get: (id3) => call("workspace.get", { workspaceId: id3 }), listFiles: (x) => call("workspace.listFiles", x), readText: (x) => call("workspace.readText", x) };
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
// src/session-resources.ts
|
|
1480
|
+
function resourceFields(v, required, optional = []) {
|
|
1481
|
+
if (!v || typeof v !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
|
|
1482
|
+
return required.every((k) => Object.hasOwn(v, k)) && Reflect.ownKeys(v).every((k) => {
|
|
1483
|
+
const d = Object.getOwnPropertyDescriptor(v, k);
|
|
1484
|
+
return typeof k === "string" && [...required, ...optional].includes(k) && d.enumerable && Object.hasOwn(d, "value");
|
|
1485
|
+
});
|
|
1486
|
+
}
|
|
1487
|
+
var str2 = (v, max = 256) => typeof v === "string" && v.length > 0 && v.length <= max;
|
|
1488
|
+
function validSessionResourceResult(_method, v) {
|
|
1489
|
+
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}`;
|
|
1490
|
+
}
|
|
1491
|
+
function createAppSessionsApi(input, streams) {
|
|
1492
|
+
return {
|
|
1493
|
+
async getConnection(...args) {
|
|
1494
|
+
if (args.length !== 0) throw new AppHostError("invalid_request");
|
|
1495
|
+
input.requireFeature();
|
|
1496
|
+
const wire = await input.request("sessions.getConnection", {});
|
|
1497
|
+
if (!validSessionResourceResult("sessions.getConnection", wire)) throw new AppHostError("host_unavailable");
|
|
1498
|
+
return createClientConnection(wire, streams);
|
|
1499
|
+
}
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
// src/service.ts
|
|
1504
|
+
function createAppServiceApi(rpc, streams) {
|
|
1505
|
+
const request = async (method, params) => {
|
|
1506
|
+
const value = await rpc.request(method, params);
|
|
1507
|
+
if (!validServiceResult(method, value))
|
|
1508
|
+
throw new AppHostError("host_unavailable");
|
|
1509
|
+
return value;
|
|
1510
|
+
};
|
|
1511
|
+
const work = (method, requestId) => {
|
|
1512
|
+
if (typeof requestId !== "string" || !HOST_REQUEST_ID.test(requestId))
|
|
1513
|
+
return Promise.reject(new AppHostError("invalid_request"));
|
|
1514
|
+
return request(method, { requestId });
|
|
1515
|
+
};
|
|
1516
|
+
return {
|
|
1517
|
+
getStatus: () => request("service.getStatus", {}),
|
|
1518
|
+
listWork: () => request("service.listWork", {}),
|
|
1519
|
+
getWork: (id3) => work("service.getWork", id3),
|
|
1520
|
+
interruptWork: (id3) => work("service.interruptWork", id3),
|
|
1521
|
+
async getConnection(input) {
|
|
1522
|
+
if (!validServiceConnectionInput(input))
|
|
1523
|
+
throw new AppHostError("invalid_request");
|
|
1524
|
+
const descriptor = await request(
|
|
1525
|
+
"service.getConnection",
|
|
1526
|
+
input
|
|
1527
|
+
);
|
|
1528
|
+
let closed = false;
|
|
1529
|
+
return {
|
|
1530
|
+
baseUrl: descriptor.baseUrl,
|
|
1531
|
+
apiVersion: descriptor.apiVersion,
|
|
1532
|
+
fetch: streams.fetchFor(descriptor.connectionId, descriptor.baseUrl),
|
|
1533
|
+
isClosed() {
|
|
1534
|
+
return closed || streams.isClosed(descriptor.connectionId);
|
|
1535
|
+
},
|
|
1536
|
+
close() {
|
|
1537
|
+
if (!closed) {
|
|
1538
|
+
closed = true;
|
|
1539
|
+
streams.close(descriptor.connectionId);
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
};
|
|
1543
|
+
}
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
// src/lifecycle.ts
|
|
1548
|
+
function isAppLifecycleFrame(value) {
|
|
1549
|
+
if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return false;
|
|
1550
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
1551
|
+
if (Reflect.ownKeys(descriptors).some((key) => typeof key !== "string" || !descriptors[key].enumerable || !Object.hasOwn(descriptors[key], "value"))) return false;
|
|
1552
|
+
const frame = value;
|
|
1553
|
+
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;
|
|
1554
|
+
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;
|
|
1555
|
+
return frame.type === "lifecycle-prepare" ? ["switch", "reload", "disable", "quit"].includes(frame.reason) : frame.type === "lifecycle-result" ? typeof frame.ready === "boolean" : true;
|
|
1556
|
+
}
|
|
1557
|
+
function createAppLifecycle(options) {
|
|
1558
|
+
const handlers = /* @__PURE__ */ new Set();
|
|
1559
|
+
let active;
|
|
1560
|
+
const cancel2 = () => {
|
|
1561
|
+
const old = active;
|
|
1562
|
+
active = void 0;
|
|
1563
|
+
old?.controller.abort();
|
|
1564
|
+
};
|
|
1565
|
+
const api = {
|
|
1566
|
+
onPrepareUnload(handler) {
|
|
1567
|
+
options.requireFeature();
|
|
1568
|
+
if (typeof handler !== "function") throw new TypeError("Unload handler must be a function");
|
|
1569
|
+
handlers.add(handler);
|
|
1570
|
+
return () => {
|
|
1571
|
+
handlers.delete(handler);
|
|
1572
|
+
if (active?.handlers.has(handler)) finish(active, false);
|
|
1573
|
+
};
|
|
1574
|
+
}
|
|
1575
|
+
};
|
|
1576
|
+
const finish = (pending, ready) => {
|
|
1577
|
+
if (active !== pending || pending.controller.signal.aborted) return;
|
|
1578
|
+
if (!ready) cancel2();
|
|
1579
|
+
options.send({ protocol: 1, type: "lifecycle-result", id: pending.id, ready });
|
|
1580
|
+
};
|
|
1581
|
+
return {
|
|
1582
|
+
api,
|
|
1583
|
+
receive(frame) {
|
|
1584
|
+
if (frame.type === "lifecycle-cancel") {
|
|
1585
|
+
if (active?.id === frame.id) cancel2();
|
|
1586
|
+
return;
|
|
1587
|
+
}
|
|
1588
|
+
if (active) {
|
|
1589
|
+
options.send({ protocol: 1, type: "lifecycle-result", id: frame.id, ready: false });
|
|
1590
|
+
return;
|
|
1591
|
+
}
|
|
1592
|
+
const pending = { id: frame.id, controller: new AbortController(), handlers: new Set(handlers) };
|
|
1593
|
+
active = pending;
|
|
1594
|
+
const request = { id: frame.id, reason: frame.reason, signal: pending.controller.signal };
|
|
1595
|
+
void Promise.all([...pending.handlers].map((handler) => Promise.resolve().then(() => {
|
|
1596
|
+
if (active !== pending) return false;
|
|
1597
|
+
return handler(request);
|
|
1598
|
+
}).then((ready) => {
|
|
1599
|
+
if (ready !== true) throw new Error("Unload was not prepared");
|
|
1600
|
+
}))).then(() => finish(pending, true), () => finish(pending, false));
|
|
1601
|
+
},
|
|
1602
|
+
close() {
|
|
1603
|
+
cancel2();
|
|
1604
|
+
handlers.clear();
|
|
1605
|
+
}
|
|
1606
|
+
};
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
// src/protocol.ts
|
|
1610
|
+
var APP_HOST_PROTOCOL = 1;
|
|
1611
|
+
var APP_HOST_READY = "nomi.app-host.ready";
|
|
1612
|
+
var APP_HOST_PORT = "nomi.app-host.port";
|
|
1613
|
+
var APP_HOST_MAX_PENDING = 64;
|
|
1614
|
+
var APP_HOST_MAX_PAYLOAD_BYTES = 12 * 1024 * 1024;
|
|
1615
|
+
var APP_HOST_REQUEST_TIMEOUT_MS = 3e4;
|
|
1616
|
+
var APP_HOST_PORT_TIMEOUT_MS = 1e4;
|
|
1617
|
+
var APP_HOST_LOGIN_TIMEOUT_MS = 3e5;
|
|
1618
|
+
var APP_HOST_LOGIN_TRANSPORT_TIMEOUT_MS = APP_HOST_LOGIN_TIMEOUT_MS + 3e4;
|
|
1619
|
+
var APP_HOST_METHODS = [
|
|
1620
|
+
"connect",
|
|
1621
|
+
"negotiate",
|
|
1622
|
+
"getContext",
|
|
1623
|
+
"storage.get",
|
|
1624
|
+
"storage.set",
|
|
1625
|
+
"storage.delete",
|
|
1626
|
+
"sessions.getConnection",
|
|
1627
|
+
"service.getStatus",
|
|
1628
|
+
"service.getConnection",
|
|
1629
|
+
"service.listWork",
|
|
1630
|
+
"service.getWork",
|
|
1631
|
+
"service.interruptWork",
|
|
1632
|
+
"storage.putFile",
|
|
1633
|
+
"storage.readFile",
|
|
1634
|
+
"storage.deleteFile",
|
|
1635
|
+
"auth.openLogin",
|
|
1636
|
+
"workspace.select",
|
|
1637
|
+
"workspace.getSelection",
|
|
1638
|
+
"workspace.get",
|
|
1639
|
+
"workspace.listFiles",
|
|
1640
|
+
"workspace.readText",
|
|
1641
|
+
...COMMANDS_METHODS,
|
|
1642
|
+
...RESOURCE_CATALOG_METHODS,
|
|
1643
|
+
...CONVERSATION_PREPARATION_METHODS,
|
|
1644
|
+
...DESKTOP_METHODS,
|
|
1645
|
+
...ATTACHMENTS_METHODS,
|
|
1646
|
+
...AUXILIARY_METHODS,
|
|
1647
|
+
...SYSTEM_METHODS,
|
|
1648
|
+
...WINDOW_METHODS
|
|
1649
|
+
];
|
|
1650
|
+
|
|
1651
|
+
// src/transport/fetch-client.ts
|
|
1652
|
+
function createPageFetchClient(options) {
|
|
1653
|
+
const streams = /* @__PURE__ */ new Map(), closedTargets = /* @__PURE__ */ new Set();
|
|
1654
|
+
let nextId = 0, closed = false;
|
|
1655
|
+
let offMessage = () => {
|
|
1656
|
+
}, offClose = () => {
|
|
1657
|
+
};
|
|
1658
|
+
const error = (code) => new AppHostError(code);
|
|
1659
|
+
const send = (frame) => {
|
|
1660
|
+
try {
|
|
1661
|
+
options.send(frame);
|
|
1662
|
+
} catch {
|
|
1663
|
+
const reason = error("host_unavailable");
|
|
1664
|
+
if ("id" in frame) {
|
|
1665
|
+
const s = streams.get(frame.id);
|
|
1666
|
+
if (s) finish(s, reason);
|
|
1667
|
+
}
|
|
1668
|
+
shutdown();
|
|
1669
|
+
throw reason;
|
|
1670
|
+
}
|
|
1671
|
+
};
|
|
1672
|
+
const finish = (s, reason, notify = false) => {
|
|
1673
|
+
if (s.stopped) return;
|
|
1674
|
+
s.stopped = true;
|
|
1675
|
+
streams.delete(s.id);
|
|
1676
|
+
s.wake?.();
|
|
1677
|
+
s.wake = void 0;
|
|
1678
|
+
clearTimeout(s.headTimer);
|
|
1679
|
+
clearTimeout(s.idleTimer);
|
|
1680
|
+
s.offAbort();
|
|
1681
|
+
if (notify) {
|
|
1682
|
+
try {
|
|
1683
|
+
send({ protocol: 2, type: "fetch-cancel", id: s.id });
|
|
1684
|
+
} catch {
|
|
1685
|
+
shutdown();
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
if (reason) {
|
|
1689
|
+
s.reject(reason);
|
|
1690
|
+
try {
|
|
1691
|
+
s.controller?.error(reason);
|
|
1692
|
+
} catch {
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
if (s.reader) {
|
|
1696
|
+
const reader = s.reader;
|
|
1697
|
+
s.reader = void 0;
|
|
1698
|
+
void reader.cancel(reason).catch(() => {
|
|
1699
|
+
}).finally(() => {
|
|
1700
|
+
try {
|
|
1701
|
+
reader.releaseLock();
|
|
1702
|
+
} catch {
|
|
1703
|
+
}
|
|
1704
|
+
});
|
|
1705
|
+
} else if (!s.uploadDone) void s.request.body?.cancel(reason).catch(() => {
|
|
1706
|
+
});
|
|
1707
|
+
};
|
|
1708
|
+
const complete = (s) => {
|
|
1709
|
+
if (s.uploadDone && s.downloadDone) finish(s);
|
|
1710
|
+
};
|
|
1711
|
+
const consumeDownload = (s) => {
|
|
1712
|
+
if (s.stopped || !s.downloadEnded || s.downloadDone || s.controller && s.controller.desiredSize !== FETCH_WINDOW_CHUNKS) return;
|
|
1713
|
+
s.downloadDone = true;
|
|
1714
|
+
s.controller?.close();
|
|
1715
|
+
send({ protocol: 2, type: "fetch-consumed", id: s.id, direction: "download", sequence: s.downloadSequence });
|
|
1716
|
+
complete(s);
|
|
1717
|
+
};
|
|
1718
|
+
const touch = (s) => {
|
|
1719
|
+
if (s.stopped || closed) return;
|
|
1720
|
+
clearTimeout(s.idleTimer);
|
|
1721
|
+
s.idleTimer = setTimeout(() => finish(s, error("host_unavailable"), true), FETCH_IDLE_TIMEOUT_MS);
|
|
1722
|
+
};
|
|
1723
|
+
const shutdown = () => {
|
|
1724
|
+
if (closed) return;
|
|
1725
|
+
closed = true;
|
|
1726
|
+
offMessage();
|
|
1727
|
+
offClose();
|
|
1728
|
+
for (const s of [...streams.values()]) finish(s, error("connection_revoked"));
|
|
1729
|
+
closedTargets.clear();
|
|
1730
|
+
};
|
|
1731
|
+
const pump = async (s) => {
|
|
1732
|
+
if (s.pumping || s.stopped || s.uploadDone) return;
|
|
1733
|
+
s.pumping = true;
|
|
1734
|
+
try {
|
|
1735
|
+
s.reader ??= s.request.body.getReader();
|
|
1736
|
+
const reader = s.reader;
|
|
1737
|
+
while (!s.stopped && s.credit > 0) {
|
|
1738
|
+
const item = await reader.read();
|
|
1739
|
+
if (s.stopped) return;
|
|
1740
|
+
if (item.done) {
|
|
1741
|
+
s.uploadDone = true;
|
|
1742
|
+
s.reader = void 0;
|
|
1743
|
+
reader.releaseLock();
|
|
1744
|
+
send({ protocol: 2, type: "fetch-end", id: s.id, direction: "upload", sequence: s.uploadSequence });
|
|
1745
|
+
complete(s);
|
|
1746
|
+
return;
|
|
1747
|
+
}
|
|
1748
|
+
if (!(item.value instanceof Uint8Array)) throw error("invalid_request");
|
|
1749
|
+
for (let offset = 0; offset < item.value.byteLength; ) {
|
|
1750
|
+
if (s.stopped) return;
|
|
1751
|
+
if (!s.credit) {
|
|
1752
|
+
await new Promise((resolve) => {
|
|
1753
|
+
s.wake = resolve;
|
|
1754
|
+
});
|
|
1755
|
+
s.wake = void 0;
|
|
1756
|
+
if (s.stopped) return;
|
|
1757
|
+
}
|
|
1758
|
+
const bytes = new Uint8Array(item.value.subarray(offset, offset + FETCH_CHUNK_BYTES));
|
|
1759
|
+
s.credit--;
|
|
1760
|
+
offset += bytes.byteLength;
|
|
1761
|
+
send({ protocol: 2, type: "fetch-chunk", id: s.id, direction: "upload", sequence: s.uploadSequence++, bytes });
|
|
1762
|
+
if (s.stopped || closed) return;
|
|
1763
|
+
touch(s);
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
} catch {
|
|
1767
|
+
finish(s, error("host_unavailable"), true);
|
|
1768
|
+
} finally {
|
|
1769
|
+
s.pumping = false;
|
|
1770
|
+
}
|
|
1771
|
+
};
|
|
1772
|
+
const stopTarget = (connectionId) => {
|
|
1773
|
+
closedTargets.add(connectionId);
|
|
1774
|
+
for (const s of [...streams.values()]) if (s.connectionId === connectionId) finish(s, error("connection_revoked"));
|
|
1775
|
+
};
|
|
1776
|
+
const receive = (message) => {
|
|
1777
|
+
if (!message || typeof message !== "object" || typeof Object.getOwnPropertyDescriptor(message, "type")?.value !== "string" || !Object.getOwnPropertyDescriptor(message, "type").value.startsWith("fetch-")) return;
|
|
1778
|
+
if (!isPageFetchFrame(message)) {
|
|
1779
|
+
shutdown();
|
|
1780
|
+
return;
|
|
1781
|
+
}
|
|
1782
|
+
if (message.type === "fetch-close" && options.allowsTargetClose?.()) {
|
|
1783
|
+
stopTarget(message.connectionId);
|
|
1784
|
+
return;
|
|
1785
|
+
}
|
|
1786
|
+
if (!("id" in message)) {
|
|
1787
|
+
shutdown();
|
|
1788
|
+
return;
|
|
1789
|
+
}
|
|
1790
|
+
const s = streams.get(message.id);
|
|
1791
|
+
if (!s) return;
|
|
1792
|
+
touch(s);
|
|
1793
|
+
try {
|
|
1794
|
+
switch (message.type) {
|
|
1795
|
+
case "fetch-headers": {
|
|
1796
|
+
if (s.headers || message.hasBody && (s.request.method === "HEAD" || [204, 205, 304].includes(message.status))) throw error("invalid_request");
|
|
1797
|
+
s.headers = true;
|
|
1798
|
+
clearTimeout(s.headTimer);
|
|
1799
|
+
const body = message.hasBody ? new ReadableStream({
|
|
1800
|
+
start(controller) {
|
|
1801
|
+
s.controller = controller;
|
|
1802
|
+
},
|
|
1803
|
+
pull(controller) {
|
|
1804
|
+
if (s.stopped || s.downloadDone) return;
|
|
1805
|
+
touch(s);
|
|
1806
|
+
if (s.downloadEnded) {
|
|
1807
|
+
consumeDownload(s);
|
|
1808
|
+
return;
|
|
1809
|
+
}
|
|
1810
|
+
const slots = Math.floor(controller.desiredSize ?? 0) - s.outstanding;
|
|
1811
|
+
if (slots > 0) {
|
|
1812
|
+
s.outstanding += slots;
|
|
1813
|
+
try {
|
|
1814
|
+
send({ protocol: 2, type: "fetch-credit", id: s.id, direction: "download", sequence: s.grantSequence++, chunks: slots, bytes: slots * FETCH_CHUNK_BYTES });
|
|
1815
|
+
} catch {
|
|
1816
|
+
finish(s, error("host_unavailable"), true);
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
},
|
|
1820
|
+
cancel() {
|
|
1821
|
+
finish(s, error("connection_revoked"), true);
|
|
1822
|
+
}
|
|
1823
|
+
}, { highWaterMark: FETCH_WINDOW_CHUNKS, size: () => 1 }) : null;
|
|
1824
|
+
const response = new Response(body, { status: message.status, statusText: message.statusText, headers: message.headers });
|
|
1825
|
+
s.resolve(response);
|
|
1826
|
+
if (!message.hasBody) {
|
|
1827
|
+
s.downloadEnded = true;
|
|
1828
|
+
consumeDownload(s);
|
|
1829
|
+
}
|
|
1830
|
+
break;
|
|
1831
|
+
}
|
|
1832
|
+
case "fetch-credit":
|
|
1833
|
+
if (message.direction !== "upload") throw error("invalid_request");
|
|
1834
|
+
if (s.uploadDone) break;
|
|
1835
|
+
if (message.sequence !== s.creditSequence++ || s.credit + message.chunks > FETCH_WINDOW_CHUNKS) throw error("invalid_request");
|
|
1836
|
+
s.credit += message.chunks;
|
|
1837
|
+
s.wake?.();
|
|
1838
|
+
void pump(s);
|
|
1839
|
+
break;
|
|
1840
|
+
case "fetch-chunk":
|
|
1841
|
+
if (message.direction !== "download" || !s.headers || s.downloadEnded || message.sequence !== s.downloadSequence++ || s.outstanding <= 0) throw error("invalid_request");
|
|
1842
|
+
s.outstanding--;
|
|
1843
|
+
s.controller.enqueue(message.bytes);
|
|
1844
|
+
break;
|
|
1845
|
+
case "fetch-end":
|
|
1846
|
+
if (message.direction !== "download" || !s.headers || s.downloadEnded || message.sequence !== s.downloadSequence) throw error("invalid_request");
|
|
1847
|
+
s.downloadEnded = true;
|
|
1848
|
+
consumeDownload(s);
|
|
1849
|
+
break;
|
|
1850
|
+
case "fetch-error":
|
|
1851
|
+
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 } }));
|
|
1852
|
+
break;
|
|
1853
|
+
case "fetch-cancel":
|
|
1854
|
+
finish(s, error("connection_revoked"));
|
|
1855
|
+
break;
|
|
1856
|
+
default:
|
|
1857
|
+
throw error("invalid_request");
|
|
1858
|
+
}
|
|
1859
|
+
} catch {
|
|
1860
|
+
finish(s, error("host_unavailable"), true);
|
|
1861
|
+
}
|
|
1862
|
+
};
|
|
1863
|
+
offMessage = options.onMessage(receive);
|
|
1864
|
+
offClose = options.onClose(shutdown);
|
|
1865
|
+
if (closed) {
|
|
1866
|
+
offMessage();
|
|
1867
|
+
offClose();
|
|
1868
|
+
}
|
|
1869
|
+
return {
|
|
1870
|
+
fetchFor(connectionId, baseUrl) {
|
|
1871
|
+
pageFetchPath(baseUrl, baseUrl);
|
|
1872
|
+
return async (input, init) => {
|
|
1873
|
+
if (closed || closedTargets.has(connectionId)) throw error("connection_revoked");
|
|
1874
|
+
const inputUrl = input instanceof Request ? input.url : String(input);
|
|
1875
|
+
const request = new Request(input, init);
|
|
1876
|
+
const id3 = String(nextId + 1);
|
|
1877
|
+
let frame;
|
|
1878
|
+
try {
|
|
1879
|
+
pageFetchPath(baseUrl, inputUrl);
|
|
1880
|
+
pageFetchPath(baseUrl, request.url);
|
|
1881
|
+
if (request.signal.aborted) throw new DOMException("The operation was aborted", "AbortError");
|
|
1882
|
+
if (streams.size >= FETCH_MAX_STREAMS) throw error("invalid_request");
|
|
1883
|
+
frame = { protocol: 2, type: "fetch-open", id: id3, connectionId, url: request.url, method: request.method, headers: [...request.headers], hasBody: !!request.body };
|
|
1884
|
+
if (!isPageFetchFrame(frame)) throw error("invalid_request");
|
|
1885
|
+
const body = init?.body;
|
|
1886
|
+
if (options.allowsInlineBody?.() && typeof body === "string" && body.length <= FETCH_INLINE_BODY_BYTES && request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() === "application/json") {
|
|
1887
|
+
const inline = { ...frame, inlineBody: body };
|
|
1888
|
+
if (isPageFetchFrame(inline)) frame = inline;
|
|
1889
|
+
}
|
|
1890
|
+
} catch (reason) {
|
|
1891
|
+
void request.body?.cancel(reason).catch(() => {
|
|
1892
|
+
});
|
|
1893
|
+
throw reason;
|
|
1894
|
+
}
|
|
1895
|
+
nextId++;
|
|
1896
|
+
return new Promise((resolve, reject) => {
|
|
1897
|
+
const abort = () => finish(s, new DOMException("The operation was aborted", "AbortError"), true);
|
|
1898
|
+
const s = {
|
|
1899
|
+
id: id3,
|
|
1900
|
+
connectionId,
|
|
1901
|
+
request,
|
|
1902
|
+
resolve,
|
|
1903
|
+
reject,
|
|
1904
|
+
headers: false,
|
|
1905
|
+
stopped: false,
|
|
1906
|
+
uploadDone: !request.body || frame.inlineBody !== void 0,
|
|
1907
|
+
downloadEnded: false,
|
|
1908
|
+
downloadDone: false,
|
|
1909
|
+
pumping: false,
|
|
1910
|
+
credit: 0,
|
|
1911
|
+
creditSequence: 0,
|
|
1912
|
+
uploadSequence: 0,
|
|
1913
|
+
outstanding: 0,
|
|
1914
|
+
grantSequence: 0,
|
|
1915
|
+
downloadSequence: 0,
|
|
1916
|
+
headTimer: setTimeout(() => finish(s, error("host_unavailable"), true), FETCH_HEADERS_TIMEOUT_MS),
|
|
1917
|
+
idleTimer: setTimeout(() => finish(s, error("host_unavailable"), true), FETCH_IDLE_TIMEOUT_MS),
|
|
1918
|
+
offAbort: () => request.signal.removeEventListener("abort", abort)
|
|
1919
|
+
};
|
|
1920
|
+
streams.set(id3, s);
|
|
1921
|
+
request.signal.addEventListener("abort", abort, { once: true });
|
|
1922
|
+
try {
|
|
1923
|
+
send(frame);
|
|
1924
|
+
} catch {
|
|
1925
|
+
finish(s, error("host_unavailable"));
|
|
1926
|
+
shutdown();
|
|
1927
|
+
}
|
|
1928
|
+
});
|
|
1929
|
+
};
|
|
1930
|
+
},
|
|
1931
|
+
isClosed(connectionId) {
|
|
1932
|
+
return closed || closedTargets.has(connectionId);
|
|
1933
|
+
},
|
|
1934
|
+
close(connectionId) {
|
|
1935
|
+
if (closed || closedTargets.has(connectionId)) return;
|
|
1936
|
+
const frame = { protocol: 2, type: "fetch-close", connectionId };
|
|
1937
|
+
if (!isPageFetchFrame(frame)) throw error("invalid_request");
|
|
1938
|
+
stopTarget(connectionId);
|
|
1939
|
+
try {
|
|
1940
|
+
send(frame);
|
|
1941
|
+
} catch {
|
|
1942
|
+
shutdown();
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
};
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
// src/connection.ts
|
|
1949
|
+
var failure = (code) => new AppHostError(code);
|
|
1950
|
+
var hostFailure = (reason, requestId) => {
|
|
1951
|
+
const details = { reason };
|
|
1952
|
+
return new AppHostError("host_unavailable", appHostErrorMessage("host_unavailable", details), {
|
|
1953
|
+
details,
|
|
1954
|
+
...requestId === void 0 ? {} : { requestId }
|
|
1955
|
+
});
|
|
1956
|
+
};
|
|
1957
|
+
function record(value) {
|
|
1958
|
+
return value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
1959
|
+
}
|
|
1960
|
+
function keys(value, required, optional = []) {
|
|
1961
|
+
if (!record(value)) return false;
|
|
1962
|
+
const own = Reflect.ownKeys(value);
|
|
1963
|
+
return required.every((k) => Object.hasOwn(value, k)) && own.every((k) => typeof k === "string" && (required.includes(k) || optional.includes(k)) && Object.getOwnPropertyDescriptor(value, k)?.enumerable && Object.hasOwn(Object.getOwnPropertyDescriptor(value, k), "value"));
|
|
1964
|
+
}
|
|
1965
|
+
function dataArray(value) {
|
|
1966
|
+
if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || Reflect.ownKeys(value).length !== value.length + 1) return false;
|
|
1967
|
+
for (let i = 0; i < value.length; i++) {
|
|
1968
|
+
const d = Object.getOwnPropertyDescriptor(value, String(i));
|
|
1969
|
+
if (!d?.enumerable || !Object.hasOwn(d, "value")) return false;
|
|
1970
|
+
}
|
|
1971
|
+
return true;
|
|
1972
|
+
}
|
|
1973
|
+
function nonempty(value) {
|
|
1974
|
+
return typeof value === "string" && value.length > 0;
|
|
1975
|
+
}
|
|
1976
|
+
function json3(value, ancestors = /* @__PURE__ */ new Set()) {
|
|
1977
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
1978
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
1979
|
+
if (typeof value !== "object" || !record(value) && !Array.isArray(value) || ancestors.has(value)) return false;
|
|
1980
|
+
if (Array.isArray(value) && (Object.getPrototypeOf(value) !== Array.prototype || Reflect.ownKeys(value).length !== value.length + 1)) return false;
|
|
1981
|
+
ancestors.add(value);
|
|
1982
|
+
try {
|
|
1983
|
+
return Reflect.ownKeys(value).every((k) => {
|
|
1984
|
+
if (Array.isArray(value) && k === "length") return true;
|
|
1985
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, k);
|
|
1986
|
+
return typeof k === "string" && descriptor.enumerable && Object.hasOwn(descriptor, "value") && (!Array.isArray(value) || /^(0|[1-9][0-9]*)$/.test(k) && Number(k) < value.length) && json3(descriptor.value, ancestors);
|
|
1987
|
+
});
|
|
1988
|
+
} finally {
|
|
1989
|
+
ancestors.delete(value);
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
function payloadSize(value) {
|
|
1993
|
+
if (value instanceof Uint8Array) return value.byteLength;
|
|
1994
|
+
if (record(value) && value.bytes instanceof Uint8Array) {
|
|
1995
|
+
const { bytes, ...metadata } = value;
|
|
1996
|
+
return bytes.byteLength + new TextEncoder().encode(JSON.stringify(metadata)).byteLength;
|
|
1997
|
+
}
|
|
1998
|
+
if (!json3(value)) throw failure("invalid_request");
|
|
1999
|
+
return new TextEncoder().encode(JSON.stringify(value)).byteLength;
|
|
2000
|
+
}
|
|
2001
|
+
function validContext(value) {
|
|
2002
|
+
return keys(value, ["appId", "appVersion", "installationId", "hostVersion", "hostApiVersion", "uiType", "theme", "locale", "capabilities", "storageQuotaBytes"]) && ["appId", "appVersion", "installationId", "hostVersion", "hostApiVersion", "locale"].every((k) => nonempty(value[k])) && ["bundled", "remote"].includes(value.uiType) && ["light", "dark"].includes(value.theme) && Number.isSafeInteger(value.storageQuotaBytes) && value.storageQuotaBytes > 0 && record(value.capabilities) && Object.values(value.capabilities).every((c) => keys(c, ["granted"], ["reason"]) && typeof c.granted === "boolean" && (!Object.hasOwn(c, "reason") || typeof c.reason === "string"));
|
|
2003
|
+
}
|
|
2004
|
+
function validEvent(value) {
|
|
2005
|
+
if (!record(value)) return false;
|
|
2006
|
+
if (validCommandInvocation(value) || validResourceChanged(value)) return true;
|
|
2007
|
+
if (validSystemEvent(value)) return true;
|
|
2008
|
+
if (validWindowEvent(value)) return true;
|
|
2009
|
+
if (validDesktopEvent(value)) return true;
|
|
2010
|
+
switch (value.type) {
|
|
2011
|
+
case "service-changed":
|
|
2012
|
+
return keys(value, ["type", "service"]) && validServiceStatus(value.service);
|
|
2013
|
+
case "visibility":
|
|
2014
|
+
return keys(value, ["type", "visible"]) && typeof value.visible === "boolean";
|
|
2015
|
+
case "context-changed":
|
|
2016
|
+
return keys(value, ["type", "context"]) && validContext(value.context);
|
|
2017
|
+
case "connection-revoked":
|
|
2018
|
+
return keys(value, ["type", "reason"]) && typeof value.reason === "string";
|
|
2019
|
+
case "before-unload":
|
|
2020
|
+
return keys(value, ["type", "reason"]) && ["switch", "reload", "disable", "quit"].includes(value.reason);
|
|
2021
|
+
default:
|
|
2022
|
+
return false;
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
function validResult(method, value) {
|
|
2026
|
+
if (isCommandsMethod(method)) return validCommandReceipt(value);
|
|
2027
|
+
if (isResourceCatalogMethod(method)) return validResourceCatalogResult(method, value);
|
|
2028
|
+
if (isSystemMethod(method)) return validSystemResult(method, value);
|
|
2029
|
+
if (isWindowMethod(method)) return validWindowResult(method, value);
|
|
2030
|
+
if (isDesktopMethod(method)) return validDesktopResult(method, value);
|
|
2031
|
+
if (method === "attachments.getConnection") return validAttachmentsResult(value);
|
|
2032
|
+
if (isAuxiliaryMethod(method)) return validAuxiliaryResult(method, value);
|
|
2033
|
+
if (isConversationPreparationMethod(method)) return validConversationPreparationResult(method, value);
|
|
2034
|
+
if (method.startsWith("sessions.")) return validSessionResourceResult(method, value);
|
|
2035
|
+
if (method.startsWith("workspace.")) return validWorkspaceResult(method, value);
|
|
2036
|
+
if (method.startsWith("service.")) return validServiceResult(method, value);
|
|
2037
|
+
switch (method) {
|
|
2038
|
+
case "negotiate":
|
|
2039
|
+
return keys(value, ["features"]) && dataArray(value.features) && value.features.length <= APP_HOST_FEATURES.length && new Set(value.features).size === value.features.length && value.features.every((f) => APP_HOST_FEATURES.includes(f));
|
|
2040
|
+
case "connect":
|
|
2041
|
+
case "getContext":
|
|
2042
|
+
return validContext(value);
|
|
2043
|
+
case "storage.get":
|
|
2044
|
+
return keys(value, ["found"], ["value"]) && (value.found === false && !Object.hasOwn(value, "value") || value.found === true && Object.hasOwn(value, "value") && json3(value.value));
|
|
2045
|
+
case "storage.putFile":
|
|
2046
|
+
return keys(value, ["id", "name", "size"]) && nonempty(value.id) && nonempty(value.name) && Number.isSafeInteger(value.size) && value.size >= 0;
|
|
2047
|
+
case "storage.readFile":
|
|
2048
|
+
return value instanceof Uint8Array;
|
|
2049
|
+
case "auth.openLogin":
|
|
2050
|
+
return keys(value, ["status"], ["callbackUrl"]) && (value.status === "cancelled" && !Object.hasOwn(value, "callbackUrl") || value.status === "completed" && nonempty(value.callbackUrl));
|
|
2051
|
+
default:
|
|
2052
|
+
return value === void 0;
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
var DocumentConnection = class {
|
|
2056
|
+
constructor(page2) {
|
|
2057
|
+
this.page = page2;
|
|
2058
|
+
page2.addEventListener("message", this.receivePort);
|
|
2059
|
+
page2.addEventListener("pagehide", this.pagehide, { once: true });
|
|
2060
|
+
page2.postMessage({ type: APP_HOST_READY, protocol: APP_HOST_PROTOCOL }, "*");
|
|
2061
|
+
}
|
|
2062
|
+
page;
|
|
2063
|
+
port;
|
|
2064
|
+
closed;
|
|
2065
|
+
nextId = 0;
|
|
2066
|
+
sequence = 0;
|
|
2067
|
+
pending = /* @__PURE__ */ new Map();
|
|
2068
|
+
listeners = /* @__PURE__ */ new Set();
|
|
2069
|
+
waiting = /* @__PURE__ */ new Set();
|
|
2070
|
+
features = /* @__PURE__ */ new Set();
|
|
2071
|
+
negotiation;
|
|
2072
|
+
fetchListeners = /* @__PURE__ */ new Set();
|
|
2073
|
+
closeListeners = /* @__PURE__ */ new Set();
|
|
2074
|
+
lifecycle = createAppLifecycle({
|
|
2075
|
+
requireFeature: () => this.requireFeature("lifecycle-v1"),
|
|
2076
|
+
send: (frame) => {
|
|
2077
|
+
if (this.closed) return;
|
|
2078
|
+
try {
|
|
2079
|
+
this.port.postMessage(frame);
|
|
2080
|
+
} catch {
|
|
2081
|
+
this.close(hostFailure("host_send_failed"));
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
});
|
|
2085
|
+
fetchClient = createPageFetchClient({
|
|
2086
|
+
allowsInlineBody: () => this.features.has("fetch-inline-body-v1"),
|
|
2087
|
+
allowsTargetClose: () => this.features.has("fetch-target-close-v1"),
|
|
2088
|
+
send: (frame) => {
|
|
2089
|
+
this.requireFeature("fetch-v2");
|
|
2090
|
+
this.port.postMessage(frame);
|
|
2091
|
+
},
|
|
2092
|
+
onMessage: (listener) => {
|
|
2093
|
+
this.fetchListeners.add(listener);
|
|
2094
|
+
return () => {
|
|
2095
|
+
this.fetchListeners.delete(listener);
|
|
2096
|
+
};
|
|
2097
|
+
},
|
|
2098
|
+
onClose: (listener) => {
|
|
2099
|
+
this.closeListeners.add(listener);
|
|
2100
|
+
return () => {
|
|
2101
|
+
this.closeListeners.delete(listener);
|
|
2102
|
+
};
|
|
2103
|
+
}
|
|
2104
|
+
});
|
|
2105
|
+
requireFeature(feature) {
|
|
2106
|
+
if (this.closed) throw this.closed;
|
|
2107
|
+
if (!this.features.has(feature)) throw failure("incompatible");
|
|
2108
|
+
}
|
|
2109
|
+
pagehide = () => this.close(failure("connection_revoked"));
|
|
2110
|
+
receivePort = (event) => {
|
|
2111
|
+
if (event.source !== this.page || !keys(event.data, ["type", "protocol"]) || event.data.type !== APP_HOST_PORT || event.data.protocol !== APP_HOST_PROTOCOL || event.ports.length !== 1) return;
|
|
2112
|
+
const port = event.ports[0];
|
|
2113
|
+
if (this.port || this.closed) {
|
|
2114
|
+
if (port !== this.port) port.close();
|
|
2115
|
+
return;
|
|
2116
|
+
}
|
|
2117
|
+
this.port = port;
|
|
2118
|
+
this.page.removeEventListener("message", this.receivePort);
|
|
2119
|
+
port.addEventListener("message", this.receive);
|
|
2120
|
+
port.addEventListener("messageerror", this.broken);
|
|
2121
|
+
port.addEventListener("close", this.broken);
|
|
2122
|
+
port.start();
|
|
2123
|
+
for (const waiter of this.waiting) waiter.resolve();
|
|
2124
|
+
this.waiting.clear();
|
|
2125
|
+
};
|
|
2126
|
+
broken = () => this.close(failure("connection_revoked"));
|
|
2127
|
+
close(error) {
|
|
2128
|
+
if (this.closed) return;
|
|
2129
|
+
this.closed = error;
|
|
2130
|
+
this.lifecycle.close();
|
|
2131
|
+
for (const listener of this.closeListeners) listener();
|
|
2132
|
+
this.closeListeners.clear();
|
|
2133
|
+
this.fetchListeners.clear();
|
|
2134
|
+
this.page.removeEventListener("message", this.receivePort);
|
|
2135
|
+
this.page.removeEventListener("pagehide", this.pagehide);
|
|
2136
|
+
this.port?.removeEventListener("message", this.receive);
|
|
2137
|
+
this.port?.removeEventListener("messageerror", this.broken);
|
|
2138
|
+
this.port?.removeEventListener("close", this.broken);
|
|
2139
|
+
this.port?.close();
|
|
2140
|
+
for (const p of this.pending.values()) {
|
|
2141
|
+
clearTimeout(p.timer);
|
|
2142
|
+
p.reject(error);
|
|
2143
|
+
}
|
|
2144
|
+
this.pending.clear();
|
|
2145
|
+
for (const w of this.waiting) w.reject(error);
|
|
2146
|
+
this.waiting.clear();
|
|
2147
|
+
this.listeners.clear();
|
|
2148
|
+
}
|
|
2149
|
+
receive = (event) => {
|
|
2150
|
+
const data = event.data;
|
|
2151
|
+
try {
|
|
2152
|
+
if (!record(data)) throw failure("host_unavailable");
|
|
2153
|
+
const frameType = Object.getOwnPropertyDescriptor(data, "type")?.value;
|
|
2154
|
+
if (typeof frameType === "string" && frameType.startsWith("fetch-")) {
|
|
2155
|
+
if (!isPageFetchFrame(data)) throw failure("host_unavailable");
|
|
2156
|
+
this.requireFeature("fetch-v2");
|
|
2157
|
+
for (const listener of this.fetchListeners) listener(data);
|
|
2158
|
+
return;
|
|
2159
|
+
}
|
|
2160
|
+
if (data.protocol !== APP_HOST_PROTOCOL) throw failure("host_unavailable");
|
|
2161
|
+
if (typeof data.type === "string" && data.type.startsWith("lifecycle-")) {
|
|
2162
|
+
this.requireFeature("lifecycle-v1");
|
|
2163
|
+
if (!isAppLifecycleFrame(data) || data.type === "lifecycle-result") throw failure("host_unavailable");
|
|
2164
|
+
this.lifecycle.receive(data);
|
|
2165
|
+
return;
|
|
2166
|
+
}
|
|
2167
|
+
if (data.type === "event") {
|
|
2168
|
+
if (!keys(data, ["protocol", "type", "sequence", "event"]) || !Number.isSafeInteger(data.sequence) || data.sequence <= 0 || !validEvent(data.event) || payloadSize(data.event) > APP_HOST_MAX_PAYLOAD_BYTES) throw failure("host_unavailable");
|
|
2169
|
+
if (data.sequence <= this.sequence) return;
|
|
2170
|
+
if (data.sequence !== this.sequence + 1) throw failure("host_unavailable");
|
|
2171
|
+
this.sequence = data.sequence;
|
|
2172
|
+
const appEvent = data.event;
|
|
2173
|
+
if (appEvent.type === "command-invoked") this.requireFeature("commands-v1");
|
|
2174
|
+
if (appEvent.type === "resources-changed") this.requireFeature("resource-catalog-v1");
|
|
2175
|
+
if (appEvent.type === "service-changed") this.requireFeature("service-v1");
|
|
2176
|
+
if (validDesktopEvent(appEvent)) {
|
|
2177
|
+
this.requireFeature("trusted-desktop-v1");
|
|
2178
|
+
if (appEvent.type === "browser-changed" && appEvent.invalidated)
|
|
2179
|
+
this.requireFeature("browser-binding-invalidation-v1");
|
|
2180
|
+
}
|
|
2181
|
+
if (validSystemEvent(appEvent)) this.requireFeature("system-ui-v1");
|
|
2182
|
+
if (validWindowEvent(appEvent)) this.requireFeature("window-chrome-v1");
|
|
2183
|
+
const observers = [...this.listeners];
|
|
2184
|
+
if (appEvent.type === "connection-revoked") this.close(failure("connection_revoked"));
|
|
2185
|
+
for (const listener of observers) {
|
|
2186
|
+
try {
|
|
2187
|
+
listener(appEvent);
|
|
2188
|
+
} catch {
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
return;
|
|
2192
|
+
}
|
|
2193
|
+
if (data.type !== "response" || typeof data.id !== "string") throw failure("host_unavailable");
|
|
2194
|
+
const p = this.pending.get(data.id);
|
|
2195
|
+
if (!p) return;
|
|
2196
|
+
if (data.ok === true) {
|
|
2197
|
+
if (!keys(data, ["protocol", "type", "id", "ok"], ["value"]) || !validResult(p.method, data.value) || data.value !== void 0 && payloadSize(data.value) > APP_HOST_MAX_PAYLOAD_BYTES) throw failure("host_unavailable");
|
|
2198
|
+
clearTimeout(p.timer);
|
|
2199
|
+
this.pending.delete(data.id);
|
|
2200
|
+
p.resolve(data.value);
|
|
2201
|
+
} else {
|
|
2202
|
+
if (!keys(data, ["protocol", "type", "id", "ok", "error"]) || data.ok !== false || !isAppHostErrorInfo(data.error) || payloadSize(data.error) > APP_HOST_MAX_PAYLOAD_BYTES) throw failure("host_unavailable");
|
|
2203
|
+
const error = new AppHostError(data.error.code, appHostErrorMessage(data.error.code, data.error.details), { ...data.error.requestId === void 0 ? {} : { requestId: data.error.requestId }, ...data.error.details === void 0 ? {} : { details: data.error.details } });
|
|
2204
|
+
clearTimeout(p.timer);
|
|
2205
|
+
this.pending.delete(data.id);
|
|
2206
|
+
p.reject(error);
|
|
2207
|
+
}
|
|
2208
|
+
} catch {
|
|
2209
|
+
this.close(hostFailure("host_invalid_response"));
|
|
2210
|
+
}
|
|
2211
|
+
};
|
|
2212
|
+
waitForPort() {
|
|
2213
|
+
if (this.closed) return Promise.reject(this.closed);
|
|
2214
|
+
if (this.port) return Promise.resolve();
|
|
2215
|
+
return new Promise((resolve, reject) => {
|
|
2216
|
+
const waiter = { resolve: () => {
|
|
2217
|
+
clearTimeout(timer);
|
|
2218
|
+
resolve();
|
|
2219
|
+
}, reject: (error) => {
|
|
2220
|
+
clearTimeout(timer);
|
|
2221
|
+
reject(error);
|
|
2222
|
+
} };
|
|
2223
|
+
const timer = setTimeout(() => {
|
|
2224
|
+
this.waiting.delete(waiter);
|
|
2225
|
+
reject(hostFailure("host_port_timeout"));
|
|
2226
|
+
}, APP_HOST_PORT_TIMEOUT_MS);
|
|
2227
|
+
this.waiting.add(waiter);
|
|
2228
|
+
});
|
|
2229
|
+
}
|
|
2230
|
+
async connect(params) {
|
|
2231
|
+
await this.waitForPort();
|
|
2232
|
+
await this.request("connect", params);
|
|
2233
|
+
this.negotiation ??= this.request("negotiate", { features: [...APP_HOST_FEATURES] }).then((result) => {
|
|
2234
|
+
this.features = new Set(result.features);
|
|
2235
|
+
});
|
|
2236
|
+
await this.negotiation;
|
|
2237
|
+
const catalog = createResourceCatalogApi({ requireFeature: () => this.requireFeature("resource-catalog-v1"), request: (method, params2) => this.request(method, params2) });
|
|
2238
|
+
const conversationPreparation = createConversationPreparationApi({
|
|
2239
|
+
requireFeature: () => this.requireFeature("session-controls-v1"),
|
|
2240
|
+
request: (method, params2) => this.request(method, params2)
|
|
2241
|
+
});
|
|
2242
|
+
return {
|
|
2243
|
+
hasFeature: (feature) => this.features.has(feature),
|
|
2244
|
+
commands: createAppCommandsApi({ requireFeature: () => this.requireFeature("commands-v1"), request: (method, params2) => this.request(method, params2), onInvoke: (listener) => {
|
|
2245
|
+
const handler = (event) => {
|
|
2246
|
+
if (event.type === "command-invoked") listener(event);
|
|
2247
|
+
};
|
|
2248
|
+
this.listeners.add(handler);
|
|
2249
|
+
return () => {
|
|
2250
|
+
this.listeners.delete(handler);
|
|
2251
|
+
};
|
|
2252
|
+
}, onClose: (listener) => {
|
|
2253
|
+
this.closeListeners.add(listener);
|
|
2254
|
+
return () => {
|
|
2255
|
+
this.closeListeners.delete(listener);
|
|
2256
|
+
};
|
|
2257
|
+
} }),
|
|
2258
|
+
lifecycle: this.lifecycle.api,
|
|
2259
|
+
system: createAppSystemApi({ requireFeature: () => this.requireFeature("system-ui-v1"), request: (method, params2) => this.request(method, params2) }, this.fetchClient),
|
|
2260
|
+
window: createAppWindowApi({ requireFeature: () => this.requireFeature("window-chrome-v1"), request: (method, params2) => this.request(method, params2), onEvent: (listener) => {
|
|
2261
|
+
this.listeners.add(listener);
|
|
2262
|
+
return () => {
|
|
2263
|
+
this.listeners.delete(listener);
|
|
2264
|
+
};
|
|
2265
|
+
} }),
|
|
2266
|
+
desktop: createAppDesktopApi({
|
|
2267
|
+
requireFeature: (method) => {
|
|
2268
|
+
this.requireFeature("trusted-desktop-v1");
|
|
2269
|
+
if (method === "desktop.browser.capturePreview") this.requireFeature("browser-capture-preview-v1");
|
|
2270
|
+
},
|
|
2271
|
+
request: (method, params2) => this.request(method, params2)
|
|
2272
|
+
}, this.fetchClient, () => this.requireFeature("file-content-v1")),
|
|
2273
|
+
attachments: createAppAttachmentsApi({ requireFeature: () => this.requireFeature("attachments-v1"), request: (method, params2) => this.request(method, params2) }, this.fetchClient),
|
|
2274
|
+
sessions: Object.assign(conversationPreparation, createAppSessionsApi({ requireFeature: () => this.requireFeature("session-resources-v1"), request: (method, params2) => this.request(method, params2) }, this.fetchClient), createAppAuxiliarySessionsApi({ requireFeature: () => this.requireFeature("auxiliary-sessions-v1"), request: (method, params2) => this.request(method, params2) }, this.fetchClient)),
|
|
2275
|
+
workspace: Object.assign({ list: catalog.list }, createAppWorkspaceApi({ requireFeature: () => this.requireFeature("workspace-v1"), request: (method, params2) => this.request(method, params2) })),
|
|
2276
|
+
service: createAppServiceApi({ request: (method, params2) => {
|
|
2277
|
+
this.requireFeature("service-v1");
|
|
2278
|
+
return this.request(method, params2);
|
|
2279
|
+
} }, this.fetchClient),
|
|
2280
|
+
getContext: () => this.request("getContext", {}),
|
|
2281
|
+
onEvent: (listener) => {
|
|
2282
|
+
if (!this.closed) this.listeners.add(listener);
|
|
2283
|
+
return () => {
|
|
2284
|
+
this.listeners.delete(listener);
|
|
2285
|
+
};
|
|
2286
|
+
},
|
|
2287
|
+
storage: {
|
|
2288
|
+
get: (key) => this.request("storage.get", { key }),
|
|
2289
|
+
set: (key, value) => this.request("storage.set", { key, value }),
|
|
2290
|
+
delete: (key) => this.request("storage.delete", { key }),
|
|
2291
|
+
putFile: async (name2, data) => {
|
|
2292
|
+
if (!(data instanceof Blob) || !nonempty(name2) || data.size + new TextEncoder().encode(JSON.stringify({ name: name2 })).byteLength > APP_HOST_MAX_PAYLOAD_BYTES) throw failure("invalid_request");
|
|
2293
|
+
return this.request("storage.putFile", { name: name2, bytes: new Uint8Array(await data.arrayBuffer()) });
|
|
2294
|
+
},
|
|
2295
|
+
readFile: async (id3) => {
|
|
2296
|
+
const bytes = await this.request("storage.readFile", { id: id3 });
|
|
2297
|
+
return new Response(new Uint8Array(bytes), { headers: { "content-type": "application/octet-stream" } });
|
|
2298
|
+
},
|
|
2299
|
+
deleteFile: (id3) => this.request("storage.deleteFile", { id: id3 })
|
|
2300
|
+
},
|
|
2301
|
+
auth: { openLogin: (input) => this.login(input) }
|
|
2302
|
+
};
|
|
2303
|
+
}
|
|
2304
|
+
async login(input) {
|
|
2305
|
+
if (!keys(input, ["url"]) || !nonempty(input.url)) throw failure("invalid_request");
|
|
2306
|
+
try {
|
|
2307
|
+
if (new URL(input.url).protocol !== "https:") throw failure("invalid_request");
|
|
2308
|
+
} catch {
|
|
2309
|
+
throw failure("invalid_request");
|
|
2310
|
+
}
|
|
2311
|
+
return this.request("auth.openLogin", input);
|
|
2312
|
+
}
|
|
2313
|
+
async request(method, params) {
|
|
2314
|
+
if (this.closed) throw this.closed;
|
|
2315
|
+
if (Object.entries(params).some(([key, value]) => ["key", "id", "name"].includes(key) && !nonempty(value)) || this.pending.size >= APP_HOST_MAX_PENDING || payloadSize(params) > APP_HOST_MAX_PAYLOAD_BYTES) throw failure("invalid_request");
|
|
2316
|
+
const mutationRequestId = (isDesktopMethod(method) || isAuxiliaryMethod(method)) && "requestId" in params && typeof params.requestId === "string" && HOST_REQUEST_ID.test(params.requestId) ? params.requestId : void 0;
|
|
2317
|
+
const selectionRequestId = method === "workspace.select" ? params.requestId : void 0;
|
|
2318
|
+
return new Promise((resolve, reject) => {
|
|
2319
|
+
const id3 = String(++this.nextId);
|
|
2320
|
+
const timer = setTimeout(() => {
|
|
2321
|
+
this.pending.delete(id3);
|
|
2322
|
+
reject(mutationRequestId ? new AppHostError("result_unknown", "result_unknown", { requestId: mutationRequestId }) : hostFailure("host_response_timeout", selectionRequestId));
|
|
2323
|
+
}, method === "auth.openLogin" || method === "workspace.select" ? APP_HOST_LOGIN_TRANSPORT_TIMEOUT_MS : APP_HOST_REQUEST_TIMEOUT_MS);
|
|
2324
|
+
this.pending.set(id3, { method, resolve: (value) => resolve(value), reject, timer });
|
|
2325
|
+
try {
|
|
2326
|
+
this.port.postMessage({ protocol: APP_HOST_PROTOCOL, type: "request", id: id3, method, params });
|
|
2327
|
+
} catch {
|
|
2328
|
+
this.close(hostFailure("host_send_failed"));
|
|
2329
|
+
}
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
};
|
|
2333
|
+
var documents = /* @__PURE__ */ new WeakMap();
|
|
2334
|
+
async function connectAppHost(options) {
|
|
2335
|
+
if (!keys(options, ["hostApi"]) || !nonempty(options.hostApi)) throw failure("invalid_request");
|
|
2336
|
+
if (typeof window === "undefined") throw failure("host_unavailable");
|
|
2337
|
+
let connection = documents.get(window);
|
|
2338
|
+
if (!connection) {
|
|
2339
|
+
connection = new DocumentConnection(window);
|
|
2340
|
+
documents.set(window, connection);
|
|
2341
|
+
}
|
|
2342
|
+
return connection.connect({ hostApi: options.hostApi });
|
|
2343
|
+
}
|
|
2344
|
+
|
|
2345
|
+
// ../json-data/src/json.ts
|
|
2346
|
+
var JsonCopyError = class extends Error {
|
|
2347
|
+
constructor(reason) {
|
|
2348
|
+
super(reason);
|
|
2349
|
+
this.reason = reason;
|
|
2350
|
+
this.name = "JsonCopyError";
|
|
2351
|
+
}
|
|
2352
|
+
reason;
|
|
2353
|
+
};
|
|
2354
|
+
function copyBoundedJson(value, options) {
|
|
2355
|
+
const { maxBytes, maxDepth } = options;
|
|
2356
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
2357
|
+
let budget = maxBytes;
|
|
2358
|
+
const spend = (text2) => {
|
|
2359
|
+
budget -= new TextEncoder().encode(text2).byteLength;
|
|
2360
|
+
if (budget < 0) throw new JsonCopyError("too_large");
|
|
2361
|
+
};
|
|
2362
|
+
const copy = (item, depth) => {
|
|
2363
|
+
if (item === null || typeof item === "boolean" || typeof item === "string" || typeof item === "number" && Number.isFinite(item)) {
|
|
2364
|
+
spend(JSON.stringify(item));
|
|
2365
|
+
return item;
|
|
2366
|
+
}
|
|
2367
|
+
if (typeof item !== "object" || item === null || depth >= maxDepth || ancestors.has(item)) throw new JsonCopyError("invalid_json");
|
|
2368
|
+
const array2 = Array.isArray(item);
|
|
2369
|
+
if (!array2 && Object.getPrototypeOf(item) !== Object.prototype && Object.getPrototypeOf(item) !== null) throw new JsonCopyError("invalid_json");
|
|
2370
|
+
const descriptors = Object.getOwnPropertyDescriptors(item);
|
|
2371
|
+
if (Object.getOwnPropertySymbols(item).length || Object.values(descriptors).some((descriptor) => descriptor.get || descriptor.set)) throw new JsonCopyError("invalid_json");
|
|
2372
|
+
ancestors.add(item);
|
|
2373
|
+
spend(array2 ? "[]" : "{}");
|
|
2374
|
+
try {
|
|
2375
|
+
if (array2) {
|
|
2376
|
+
const result2 = [];
|
|
2377
|
+
if (Object.keys(item).length !== item.length) throw new JsonCopyError("invalid_json");
|
|
2378
|
+
for (let index = 0; index < item.length; index++) {
|
|
2379
|
+
if (index) spend(",");
|
|
2380
|
+
result2.push(copy(descriptors[index].value, depth + 1));
|
|
2381
|
+
}
|
|
2382
|
+
return result2;
|
|
2383
|
+
}
|
|
2384
|
+
const result = {};
|
|
2385
|
+
let count2 = 0;
|
|
2386
|
+
for (const key of Object.keys(item).sort()) {
|
|
2387
|
+
if (count2++) spend(",");
|
|
2388
|
+
spend(`${JSON.stringify(key)}:`);
|
|
2389
|
+
Object.defineProperty(result, key, { value: copy(descriptors[key].value, depth + 1), enumerable: true, writable: true, configurable: true });
|
|
2390
|
+
}
|
|
2391
|
+
return result;
|
|
2392
|
+
} finally {
|
|
2393
|
+
ancestors.delete(item);
|
|
2394
|
+
}
|
|
2395
|
+
};
|
|
2396
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || !Number.isSafeInteger(maxDepth) || maxDepth < 0) throw new JsonCopyError("invalid_limit");
|
|
2397
|
+
return copy(value, 0);
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2400
|
+
// ../plugin-contracts/src/manifest/limits.ts
|
|
2401
|
+
var PLUGIN_APP_MANIFEST_LIMITS = Object.freeze({
|
|
2402
|
+
manifestCount: 8,
|
|
2403
|
+
manifestBytes: 256 * 1024,
|
|
2404
|
+
backendCount: 32,
|
|
2405
|
+
surfaceCount: 32
|
|
2406
|
+
});
|
|
2407
|
+
var PLUGIN_APP_RESOURCE_LIMITS = Object.freeze({ htmlBytes: 16 * 1024 * 1024, resourceBytes: 8 * 1024 * 1024 });
|
|
2408
|
+
var PLUGIN_APP_DATA_LIMITS = Object.freeze({ maxArgsBytes: 64 * 1024 * 1024, jsonDepth: 32 });
|
|
2409
|
+
|
|
2410
|
+
// ../plugin-contracts/src/runtime/runtime-data.ts
|
|
2411
|
+
var PluginAppValidationError = class extends Error {
|
|
2412
|
+
constructor(code) {
|
|
2413
|
+
super(code);
|
|
2414
|
+
this.code = code;
|
|
2415
|
+
this.name = "PluginAppValidationError";
|
|
2416
|
+
}
|
|
2417
|
+
code;
|
|
2418
|
+
};
|
|
2419
|
+
var PluginAppDataError = class extends PluginAppValidationError {
|
|
2420
|
+
constructor(code) {
|
|
2421
|
+
super(code);
|
|
2422
|
+
this.code = code;
|
|
2423
|
+
}
|
|
2424
|
+
code;
|
|
2425
|
+
};
|
|
2426
|
+
function copyPluginAppJson(value, maxBytes) {
|
|
2427
|
+
try {
|
|
2428
|
+
return copyBoundedJson(value, { maxBytes, maxDepth: PLUGIN_APP_DATA_LIMITS.jsonDepth });
|
|
2429
|
+
} catch (error) {
|
|
2430
|
+
if (!(error instanceof JsonCopyError)) throw error;
|
|
2431
|
+
throw new PluginAppDataError(error.reason === "too_large" ? "plugin_app_json_too_large" : error.reason === "invalid_limit" ? "plugin_app_invalid_json_limit" : "plugin_app_invalid_json");
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
|
|
2435
|
+
// ../domain-contracts/src/plugin-apps/limits.ts
|
|
2436
|
+
var PLUGIN_APP_INPUT_LIMITS = Object.freeze({ handoffBytes: 32 * 1024, messageCharacters: 4096, maxComposerContexts: 8 });
|
|
2437
|
+
|
|
2438
|
+
// ../domain-contracts/src/validation-error.ts
|
|
2439
|
+
var DomainValidationError = class extends Error {
|
|
2440
|
+
constructor(message, field, reason) {
|
|
2441
|
+
super(message);
|
|
2442
|
+
this.field = field;
|
|
2443
|
+
this.reason = reason;
|
|
2444
|
+
this.name = "DomainValidationError";
|
|
2445
|
+
}
|
|
2446
|
+
field;
|
|
2447
|
+
reason;
|
|
2448
|
+
code = "invalid_request";
|
|
2449
|
+
};
|
|
2450
|
+
|
|
2451
|
+
// ../domain-contracts/src/plugin-apps/history.ts
|
|
2452
|
+
var PLUGIN_UI_LIMITS = { dataBytes: 256 * 1024, actionArgsBytes: 64 * 1024 };
|
|
2453
|
+
|
|
2454
|
+
// ../domain-contracts/src/plugin-apps/validation.ts
|
|
2455
|
+
var InputError = class extends Error {
|
|
2456
|
+
constructor(code) {
|
|
2457
|
+
super(code);
|
|
2458
|
+
this.code = code;
|
|
2459
|
+
}
|
|
2460
|
+
code;
|
|
2461
|
+
};
|
|
2462
|
+
function validate(parse, value) {
|
|
2463
|
+
try {
|
|
2464
|
+
return { ok: true, value: parse(value) };
|
|
2465
|
+
} catch (error) {
|
|
2466
|
+
if (error instanceof InputError || error instanceof PluginAppDataError) return { ok: false, code: error.code };
|
|
2467
|
+
throw error;
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
function validatePluginAppComposerContexts(value) {
|
|
2471
|
+
return validate(parsePluginAppComposerContexts, value);
|
|
2472
|
+
}
|
|
2473
|
+
function parsePluginAppConversationInput(value) {
|
|
2474
|
+
const input = record2(copyPluginAppJson(value, PLUGIN_APP_INPUT_LIMITS.handoffBytes + 32 * 1024));
|
|
2475
|
+
fields3(input, ["source", "lease", "requestId", "expectedRevision", "text", "data"]);
|
|
2476
|
+
const lease = record2(input.lease);
|
|
2477
|
+
fields3(lease, ["token", "backendGeneration"]);
|
|
2478
|
+
if (typeof input.text !== "string" || [...input.text].length > PLUGIN_APP_INPUT_LIMITS.messageCharacters || !input.text.trim())
|
|
2479
|
+
throw new InputError("plugin_app_invalid_message");
|
|
2480
|
+
return {
|
|
2481
|
+
source: parsePluginAppSource(input.source),
|
|
2482
|
+
lease: { token: identifier2(lease.token), backendGeneration: identifier2(lease.backendGeneration) },
|
|
2483
|
+
requestId: identifier2(input.requestId),
|
|
2484
|
+
expectedRevision: revision2(input.expectedRevision),
|
|
2485
|
+
text: input.text,
|
|
2486
|
+
data: copyPluginAppJson(input.data, PLUGIN_APP_INPUT_LIMITS.handoffBytes)
|
|
2487
|
+
};
|
|
2488
|
+
}
|
|
2489
|
+
function record2(value) {
|
|
2490
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new InputError("plugin_app_invalid_request");
|
|
2491
|
+
return value;
|
|
2492
|
+
}
|
|
2493
|
+
function fields3(value, names) {
|
|
2494
|
+
if (Object.keys(value).length !== names.length || names.some((name2) => !Object.hasOwn(value, name2))) throw new InputError("plugin_app_invalid_request");
|
|
2495
|
+
}
|
|
2496
|
+
function identifier2(value) {
|
|
2497
|
+
if (typeof value !== "string" || !value.trim() || value.length > 1024) throw new InputError("plugin_app_invalid_request");
|
|
2498
|
+
return value;
|
|
2499
|
+
}
|
|
2500
|
+
function revision2(value) {
|
|
2501
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new InputError("plugin_app_invalid_request");
|
|
2502
|
+
return value;
|
|
2503
|
+
}
|
|
2504
|
+
function parsePluginAppSource(value) {
|
|
2505
|
+
const input = record2(copyPluginAppJson(value, 4096));
|
|
2506
|
+
fields3(input, ["sessionId", "appId"]);
|
|
2507
|
+
return { sessionId: identifier2(input.sessionId), appId: identifier2(input.appId) };
|
|
2508
|
+
}
|
|
2509
|
+
function parsePluginAppComposerContexts(value) {
|
|
2510
|
+
if (!Array.isArray(value) || value.length > PLUGIN_APP_INPUT_LIMITS.maxComposerContexts) throw new InputError("plugin_app_invalid_context");
|
|
2511
|
+
return value.map(parsePluginAppConversationInput);
|
|
2512
|
+
}
|
|
2513
|
+
|
|
2514
|
+
// ../domain-contracts/src/inputs/items.ts
|
|
2515
|
+
var SESSION_INPUT_LIMITS = {
|
|
2516
|
+
maxItems: 256,
|
|
2517
|
+
maxSkills: 32,
|
|
2518
|
+
maxTextBytes: 1024 * 1024,
|
|
2519
|
+
maxNameChars: 128,
|
|
2520
|
+
maxDisplayNameChars: 256
|
|
2521
|
+
};
|
|
2522
|
+
|
|
2523
|
+
// src/display-helpers.ts
|
|
2524
|
+
function parsePluginAppComposerContexts2(value) {
|
|
2525
|
+
const result = validatePluginAppComposerContexts(value);
|
|
2526
|
+
if (!result.ok) throw new DomainValidationError(result.code, result.field, result.code);
|
|
2527
|
+
return result.value;
|
|
2528
|
+
}
|
|
2529
|
+
export {
|
|
2530
|
+
AppHostError,
|
|
2531
|
+
EXTENSION_INPUTS,
|
|
2532
|
+
WINDOW_METHODS,
|
|
2533
|
+
canonicalDesktopRequest,
|
|
2534
|
+
connectAppHost,
|
|
2535
|
+
createAppWindowApi,
|
|
2536
|
+
createPageFetchClient,
|
|
2537
|
+
isWindowMethod,
|
|
2538
|
+
parsePluginAppComposerContexts2 as parsePluginAppComposerContexts,
|
|
2539
|
+
validAppCommandSnapshot,
|
|
2540
|
+
validAppWindowState,
|
|
2541
|
+
validExtensionRequest,
|
|
2542
|
+
validExtensionResult,
|
|
2543
|
+
validWindowEvent,
|
|
2544
|
+
validWindowInput,
|
|
2545
|
+
validWindowResult
|
|
2546
|
+
};
|
|
2547
|
+
//# sourceMappingURL=index.js.map
|