@bobannomi/client 0.0.0-stage → 0.1.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4501 @@
1
+ // ../domain-contracts/src/sessions/records.ts
2
+ var SESSION_EVENT_SCHEMA_VERSION = 1;
3
+ var SESSION_EVENT_SCHEMA_VERSIONS = {
4
+ "session.input.admitted": 2
5
+ };
6
+ function sessionEventSchemaVersion(type) {
7
+ return SESSION_EVENT_SCHEMA_VERSIONS[type] ?? SESSION_EVENT_SCHEMA_VERSION;
8
+ }
9
+
10
+ // ../domain-contracts/src/sessions/model-metadata.ts
11
+ var SESSION_MODEL_FAILURE_KINDS = /* @__PURE__ */ new Set([
12
+ "network",
13
+ "timeout",
14
+ "rate_limit",
15
+ "server",
16
+ "stream_incomplete",
17
+ "authentication",
18
+ "invalid_request",
19
+ "quota",
20
+ "protocol",
21
+ "unknown"
22
+ ]);
23
+ function isRecordValue(value) {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ }
26
+ function readNonEmptyString(value) {
27
+ return typeof value === "string" && value.trim() ? value : void 0;
28
+ }
29
+ function readPositiveInteger(value) {
30
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1 ? value : void 0;
31
+ }
32
+ function readNonNegativeInteger(value) {
33
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
34
+ }
35
+ function readFiniteNumber(value) {
36
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
37
+ }
38
+ function readSessionModelRetryState(metadata) {
39
+ if (!isRecordValue(metadata)) return void 0;
40
+ const raw = metadata.modelRetry;
41
+ if (!isRecordValue(raw)) return void 0;
42
+ const generationId = readNonEmptyString(raw.generationId);
43
+ const attempt = readPositiveInteger(raw.attempt);
44
+ const retryNumber = readPositiveInteger(raw.retryNumber);
45
+ const maxRetries = readNonNegativeInteger(raw.maxRetries);
46
+ const reason = readNonEmptyString(raw.reason);
47
+ const nextRetryAt = readFiniteNumber(raw.nextRetryAt);
48
+ const recoveryDeadlineAt = readFiniteNumber(raw.recoveryDeadlineAt);
49
+ if (!generationId || attempt === void 0 || retryNumber === void 0 || maxRetries === void 0 || !reason || !SESSION_MODEL_FAILURE_KINDS.has(reason) || nextRetryAt === void 0 || recoveryDeadlineAt === void 0) {
50
+ return void 0;
51
+ }
52
+ return {
53
+ generationId,
54
+ attempt,
55
+ retryNumber,
56
+ maxRetries,
57
+ reason,
58
+ nextRetryAt,
59
+ recoveryDeadlineAt
60
+ };
61
+ }
62
+ function readModelGenerationMetadata(metadata) {
63
+ if (!isRecordValue(metadata)) return void 0;
64
+ const raw = metadata.modelGeneration;
65
+ if (!isRecordValue(raw)) return void 0;
66
+ const generationId = readNonEmptyString(raw.generationId);
67
+ const attempt = readPositiveInteger(raw.attempt);
68
+ if (!generationId || attempt === void 0) return void 0;
69
+ return {
70
+ generationId,
71
+ attempt,
72
+ ...raw.superseded === true ? { superseded: true } : {},
73
+ ...raw.committed === true ? { committed: true } : {}
74
+ };
75
+ }
76
+ function isSupersededModelPart(part) {
77
+ return readModelGenerationMetadata(part.metadata)?.superseded === true;
78
+ }
79
+ function readSessionModelUsage(metadata) {
80
+ if (!isRecordValue(metadata)) return void 0;
81
+ const raw = metadata.modelUsage;
82
+ if (!isRecordValue(raw)) return void 0;
83
+ return {
84
+ incomplete: raw.incomplete === true,
85
+ unknownAttempts: readNonNegativeInteger(raw.unknownAttempts) ?? 0,
86
+ partialAttempts: readNonNegativeInteger(raw.partialAttempts) ?? 0
87
+ };
88
+ }
89
+
90
+ // ../agent-contracts/src/conversation/reply-style.ts
91
+ function isReplyStyle(value) {
92
+ return value === "collaborative" || value === "direct" || value === "explanatory";
93
+ }
94
+
95
+ // ../domain-contracts/src/validation-error.ts
96
+ var DomainValidationError = class extends Error {
97
+ constructor(message, field, reason) {
98
+ super(message);
99
+ this.field = field;
100
+ this.reason = reason;
101
+ this.name = "DomainValidationError";
102
+ }
103
+ field;
104
+ reason;
105
+ code = "invalid_request";
106
+ };
107
+
108
+ // ../domain-contracts/src/sessions/runtime-config.ts
109
+ function isRecord(value) {
110
+ return !!value && typeof value === "object" && !Array.isArray(value);
111
+ }
112
+ function numberValue(value) {
113
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
114
+ }
115
+ function permissionModeValue(value) {
116
+ return value === "default" || value === "plan" || value === "full_auto" ? value : void 0;
117
+ }
118
+ function effortValue(value) {
119
+ if (typeof value !== "string") return void 0;
120
+ const trimmed = value.trim();
121
+ return trimmed.length > 0 ? trimmed : "";
122
+ }
123
+ function sessionModeValue(value) {
124
+ return value === "coordinator" ? "coordinator" : value === "direct" ? "direct" : void 0;
125
+ }
126
+ function apiFormatValue(value) {
127
+ return value === "anthropic" || value === "openai" ? value : void 0;
128
+ }
129
+ function booleanValue(value) {
130
+ return typeof value === "boolean" ? value : void 0;
131
+ }
132
+ function readRuntimeMetadata(metadata) {
133
+ const runtime = metadata?.runtime;
134
+ if (runtime === void 0) return {};
135
+ if (!isRecord(runtime)) throw new DomainValidationError("metadata.runtime must be an object", "metadata.runtime");
136
+ for (const [field, value] of Object.entries(runtime)) {
137
+ let valid = false;
138
+ switch (field) {
139
+ case "model":
140
+ case "provider":
141
+ case "baseUrl":
142
+ case "systemPrompt":
143
+ case "identityPrompt":
144
+ valid = typeof value === "string";
145
+ break;
146
+ case "apiFormat":
147
+ valid = apiFormatValue(value) !== void 0;
148
+ break;
149
+ case "permissionMode":
150
+ valid = permissionModeValue(value) !== void 0;
151
+ break;
152
+ case "approvalMode":
153
+ valid = value === "ask" || value === "auto_review" || value === "full_access";
154
+ break;
155
+ case "workMode":
156
+ valid = value === "execute" || value === "plan";
157
+ break;
158
+ case "effort":
159
+ valid = effortValue(value) !== void 0;
160
+ break;
161
+ case "replyStyle":
162
+ valid = value === "inherit" || isReplyStyle(value);
163
+ break;
164
+ case "sessionMode":
165
+ valid = sessionModeValue(value) !== void 0;
166
+ break;
167
+ case "maxTurns":
168
+ valid = numberValue(value) !== void 0;
169
+ break;
170
+ case "memoryEnabled":
171
+ case "pluginsEnabled":
172
+ case "pluginAutoSelectionEnabled":
173
+ valid = booleanValue(value) !== void 0;
174
+ break;
175
+ case "appServiceBindings":
176
+ valid = Array.isArray(value) && value.length <= 128 && value.every((item) => typeof item === "string" && /^service:[a-f0-9]{64}$/.test(item)) && new Set(value).size === value.length;
177
+ break;
178
+ case "allowedTools":
179
+ case "disallowedTools":
180
+ valid = Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim().length > 0);
181
+ break;
182
+ }
183
+ if (!valid) {
184
+ throw new DomainValidationError(`Invalid runtime config field metadata.runtime.${field}`, `metadata.runtime.${field}`);
185
+ }
186
+ }
187
+ return runtime;
188
+ }
189
+
190
+ // ../domain-contracts/src/sessions/resource-actions.ts
191
+ var record = (v) => !!v && typeof v === "object" && !Array.isArray(v) && [Object.prototype, null].includes(Object.getPrototypeOf(v));
192
+ var exact = (v, required, optional = []) => record(v) && required.every((k) => Object.hasOwn(v, k)) && Reflect.ownKeys(v).every((k) => {
193
+ const d = Object.getOwnPropertyDescriptor(v, k);
194
+ return typeof k === "string" && [...required, ...optional].includes(k) && d.enumerable && Object.hasOwn(d, "value");
195
+ });
196
+ var text = (v) => typeof v === "string" && v.trim().length > 0 && v.length <= 1024;
197
+ var count = (v) => Number.isSafeInteger(v) && v >= 0;
198
+ var uuid = (v) => typeof v === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v);
199
+ var invalid = () => {
200
+ throw new DomainValidationError("Invalid session resource request");
201
+ };
202
+ function parseSessionManagementAction(v) {
203
+ if (!["rename", "pin", "archive", "delete"].includes(v)) invalid();
204
+ return v;
205
+ }
206
+ function parseSessionResourceMutation(action, value) {
207
+ const required = ["requestId", ...action === "rename" ? ["title", "expectedRevision"] : action === "pin" ? ["pinned", "expectedRevision"] : ["expectedTreeRevision"]];
208
+ if (!exact(value, required) || !uuid(value.requestId)) return invalid();
209
+ if (action === "rename" && (typeof value.title !== "string" || value.title.length > 2e3 || !count(value.expectedRevision)) || action === "pin" && (typeof value.pinned !== "boolean" || !count(value.expectedRevision)) || ["archive", "delete"].includes(action) && !text(value.expectedTreeRevision)) invalid();
210
+ return value;
211
+ }
212
+ function decodeSessionResourceRevision(v) {
213
+ if (!exact(v, ["revision"], ["treeRevision"]) || !count(v.revision) || Object.hasOwn(v, "treeRevision") && !text(v.treeRevision)) return invalid();
214
+ return v;
215
+ }
216
+ function decodeSessionMutationReceipt(v) {
217
+ if (!exact(v, ["dataScopeId", "sessionId", "requestId", "result"]) || !text(v.dataScopeId) || !text(v.sessionId) || !uuid(v.requestId) || !exact(v.result, ["sessionId", "action"], ["revision", "deletedSessionIds"]) || v.result.sessionId !== v.sessionId) return invalid();
218
+ parseSessionManagementAction(v.result.action);
219
+ if (Object.hasOwn(v.result, "revision") && !count(v.result.revision)) invalid();
220
+ if (Object.hasOwn(v.result, "deletedSessionIds") && (!Array.isArray(v.result.deletedSessionIds) || v.result.deletedSessionIds.length > 1e4 || !v.result.deletedSessionIds.every(text) || new Set(v.result.deletedSessionIds).size !== v.result.deletedSessionIds.length)) invalid();
221
+ return v;
222
+ }
223
+
224
+ // ../domain-contracts/src/request-fields.ts
225
+ function record2(value) {
226
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
227
+ throw new DomainValidationError("Request body must be a JSON object");
228
+ }
229
+ return value;
230
+ }
231
+ function requiredString(body, field) {
232
+ const value = body[field];
233
+ if (typeof value !== "string") {
234
+ throw new DomainValidationError(`${field} is required`, field);
235
+ }
236
+ return value;
237
+ }
238
+ function optionalString(body, field) {
239
+ const value = body[field];
240
+ if (value === void 0) return void 0;
241
+ if (typeof value !== "string") {
242
+ throw new DomainValidationError(`${field} must be a string`, field);
243
+ }
244
+ return value;
245
+ }
246
+ function optionalNumber(body, field, options = {}) {
247
+ const value = body[field];
248
+ if (value === void 0) return void 0;
249
+ if (value === null && options.nullable) return null;
250
+ if (typeof value !== "number" || !Number.isFinite(value) || options.integer && !Number.isInteger(value) || options.minimum !== void 0 && value < options.minimum) {
251
+ throw new DomainValidationError(`${field} must be a valid number`, field);
252
+ }
253
+ return value;
254
+ }
255
+ function optionalBoolean(body, field) {
256
+ const value = body[field];
257
+ if (value === void 0) return void 0;
258
+ if (typeof value !== "boolean") {
259
+ throw new DomainValidationError(`${field} must be a boolean`, field);
260
+ }
261
+ return value;
262
+ }
263
+ function optionalStringArray(body, field) {
264
+ const value = body[field];
265
+ if (value === void 0) return void 0;
266
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
267
+ throw new DomainValidationError(
268
+ `${field} must be an array of strings`,
269
+ field
270
+ );
271
+ }
272
+ return [...value];
273
+ }
274
+ function optionalEnum(body, field, values) {
275
+ const value = body[field];
276
+ if (value === void 0) return void 0;
277
+ if (typeof value !== "string" || !values.includes(value)) {
278
+ throw new DomainValidationError(
279
+ `${field} must be one of: ${values.join(", ")}`,
280
+ field
281
+ );
282
+ }
283
+ return value;
284
+ }
285
+ function fields(body, allowed) {
286
+ for (const key of Object.keys(body)) if (!allowed.includes(key)) throw new DomainValidationError(`Unknown field ${key}`, key);
287
+ }
288
+
289
+ // ../domain-contracts/src/sessions/configuration-validation.ts
290
+ function parseSessionConfiguration(value) {
291
+ const body = record2(value);
292
+ fields(body, ["model", "roleId", "systemPrompt", "executionInstructions", "effort", "workMode", "maxTurns", "sessionMode", "replyStyle", "approvalMode", "tools", "pluginsEnabled", "pluginAutoSelectionEnabled", "activePluginId", "pluginIds", "serviceBindings", "memory"]);
293
+ for (const key of ["roleId", "systemPrompt", "effort", "activePluginId"]) if (body[key] !== null) optionalString(body, key);
294
+ for (const key of ["pluginsEnabled", "pluginAutoSelectionEnabled"]) optionalBoolean(body, key);
295
+ optionalEnum(body, "workMode", ["execute", "plan"]);
296
+ optionalEnum(body, "sessionMode", ["direct", "coordinator"]);
297
+ optionalEnum(body, "replyStyle", ["collaborative", "direct", "explanatory"]);
298
+ optionalEnum(body, "approvalMode", ["ask", "auto_review", "full_access"]);
299
+ optionalNumber(body, "maxTurns", { integer: true, minimum: 0 });
300
+ for (const key of ["pluginIds", "serviceBindings"]) optionalStringArray(body, key);
301
+ if (body.model !== void 0) {
302
+ const model = record2(body.model);
303
+ fields(model, ["provider", "model"]);
304
+ for (const key of ["provider", "model"]) if (!requiredString(model, key).trim()) throw new DomainValidationError(`${key} cannot be empty`, `model.${key}`);
305
+ }
306
+ if (body.executionInstructions !== void 0 && body.executionInstructions !== null) {
307
+ const instructions = record2(body.executionInstructions);
308
+ fields(instructions, ["revision", "content"]);
309
+ if (optionalNumber(instructions, "revision", { integer: true, minimum: 0 }) === void 0) throw new DomainValidationError("revision required", "executionInstructions.revision");
310
+ requiredString(instructions, "content");
311
+ }
312
+ if (body.tools !== void 0) {
313
+ const tools = record2(body.tools);
314
+ fields(tools, ["allowed", "denied"]);
315
+ optionalStringArray(tools, "allowed");
316
+ optionalStringArray(tools, "denied");
317
+ }
318
+ if (body.memory !== void 0) {
319
+ const memory = record2(body.memory);
320
+ fields(memory, ["enabled"]);
321
+ if (optionalBoolean(memory, "enabled") === void 0) throw new DomainValidationError("enabled required", "memory.enabled");
322
+ }
323
+ return structuredClone(body);
324
+ }
325
+
326
+ // ../domain-contracts/src/inputs/items.ts
327
+ var SESSION_INPUT_LIMITS = {
328
+ maxItems: 256,
329
+ maxSkills: 32,
330
+ maxTextBytes: 1024 * 1024,
331
+ maxNameChars: 128,
332
+ maxDisplayNameChars: 256
333
+ };
334
+
335
+ // ../domain-contracts/src/inputs/validation.ts
336
+ var CONTROL_CHARACTER_PATTERN = /[\u0000-\u001F\u007F-\u009F]/;
337
+ var TEXT_CONTROL_CHARACTER_PATTERN = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/;
338
+ function validateSessionUserInputItems(items) {
339
+ if (items.length > SESSION_INPUT_LIMITS.maxItems) throw new DomainValidationError("item_limit_exceeded");
340
+ let skillCount = 0;
341
+ let textBytes = 0;
342
+ for (const item of items) {
343
+ if (item.type === "text") {
344
+ assertValidText(item.text);
345
+ textBytes += new TextEncoder().encode(item.text).byteLength;
346
+ continue;
347
+ }
348
+ if (item.type === "context") {
349
+ if (item.kind !== "conversation") throw new DomainValidationError("invalid_context_kind");
350
+ assertValidString(item.id, "id");
351
+ assertValidString(item.displayName, "displayName");
352
+ assertMaximumLength(item.id, SESSION_INPUT_LIMITS.maxNameChars, "id");
353
+ assertMaximumLength(item.displayName, SESSION_INPUT_LIMITS.maxDisplayNameChars, "displayName");
354
+ continue;
355
+ }
356
+ if (item.type === "capability") {
357
+ if (item.kind !== "plugin" && item.kind !== "plugin_agent") throw new DomainValidationError("invalid_capability_kind");
358
+ assertValidString(item.pluginId, "pluginId");
359
+ assertValidString(item.displayName, "displayName");
360
+ assertMaximumLength(item.pluginId, SESSION_INPUT_LIMITS.maxNameChars, "pluginId");
361
+ assertMaximumLength(item.displayName, SESSION_INPUT_LIMITS.maxDisplayNameChars, "displayName");
362
+ if (item.kind === "plugin_agent") {
363
+ assertValidString(item.agentId, "agentId");
364
+ assertMaximumLength(item.agentId, SESSION_INPUT_LIMITS.maxNameChars, "agentId");
365
+ }
366
+ continue;
367
+ }
368
+ assertValidString(item.name, "name");
369
+ assertValidString(item.path, "path");
370
+ assertMaximumLength(item.name, SESSION_INPUT_LIMITS.maxNameChars, "name");
371
+ if (item.displayName !== void 0) {
372
+ assertValidString(item.displayName, "displayName");
373
+ assertMaximumLength(item.displayName, SESSION_INPUT_LIMITS.maxDisplayNameChars, "displayName");
374
+ }
375
+ if (item.type === "skill") {
376
+ skillCount += 1;
377
+ if (item.source !== void 0 && !isSkillSource(item.source)) throw new DomainValidationError("invalid_skill_source");
378
+ }
379
+ }
380
+ if (skillCount > SESSION_INPUT_LIMITS.maxSkills) throw new DomainValidationError("skill_item_limit_exceeded");
381
+ if (textBytes > SESSION_INPUT_LIMITS.maxTextBytes) throw new DomainValidationError("text_byte_limit_exceeded");
382
+ return [...items];
383
+ }
384
+ function normalizeSessionUserInputItems(items) {
385
+ const normalized = [];
386
+ for (const item of validateSessionUserInputItems(items)) {
387
+ if (item.type !== "text") {
388
+ normalized.push(item);
389
+ } else if (item.text.length > 0) {
390
+ const previous = normalized.at(-1);
391
+ if (previous?.type === "text") previous.text += item.text;
392
+ else normalized.push({ type: "text", text: item.text });
393
+ }
394
+ }
395
+ return normalized;
396
+ }
397
+ function assertValidString(value, field) {
398
+ if (typeof value !== "string" || CONTROL_CHARACTER_PATTERN.test(value)) throw new DomainValidationError(`invalid_${field}`);
399
+ }
400
+ function assertValidText(value) {
401
+ if (typeof value !== "string" || TEXT_CONTROL_CHARACTER_PATTERN.test(value)) throw new DomainValidationError("invalid_text");
402
+ }
403
+ function assertMaximumLength(value, maximum, field) {
404
+ if (value.length > maximum) throw new DomainValidationError(`${field}_limit_exceeded`);
405
+ }
406
+ function isSkillSource(value) {
407
+ return value === "bundled" || value === "user" || value === "project" || value === "plugin";
408
+ }
409
+ function parseSessionInputItems(value) {
410
+ if (!Array.isArray(value)) {
411
+ throw new DomainValidationError("items must be an array", "items");
412
+ }
413
+ const items = value.map((entry, index) => {
414
+ const field = `items[${index}]`;
415
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
416
+ throw new DomainValidationError(`${field} must be an object`, field);
417
+ }
418
+ const item = entry;
419
+ if (item.type === "text") {
420
+ if (typeof item.text !== "string") {
421
+ throw new DomainValidationError(
422
+ `${field}.text must be a string`,
423
+ `${field}.text`
424
+ );
425
+ }
426
+ return { type: "text", text: item.text };
427
+ }
428
+ if (item.type === "context") {
429
+ if (item.kind !== "conversation" || typeof item.id !== "string" || typeof item.displayName !== "string") {
430
+ throw new DomainValidationError(
431
+ `${field} requires kind, id and displayName`,
432
+ field
433
+ );
434
+ }
435
+ return {
436
+ type: "context",
437
+ kind: "conversation",
438
+ id: item.id,
439
+ displayName: item.displayName
440
+ };
441
+ }
442
+ if (item.type === "capability") {
443
+ if (item.kind !== "plugin" && item.kind !== "plugin_agent" || typeof item.pluginId !== "string" || typeof item.displayName !== "string" || item.kind === "plugin_agent" && typeof item.agentId !== "string") {
444
+ throw new DomainValidationError(
445
+ `${field} requires a valid kind, pluginId, displayName and agentId`,
446
+ field
447
+ );
448
+ }
449
+ return item.kind === "plugin" ? {
450
+ type: "capability",
451
+ kind: "plugin",
452
+ pluginId: item.pluginId,
453
+ displayName: item.displayName
454
+ } : {
455
+ type: "capability",
456
+ kind: "plugin_agent",
457
+ pluginId: item.pluginId,
458
+ agentId: item.agentId,
459
+ displayName: item.displayName
460
+ };
461
+ }
462
+ if (item.type !== "skill" && item.type !== "mention") {
463
+ throw new DomainValidationError(
464
+ `${field}.type is invalid`,
465
+ `${field}.type`
466
+ );
467
+ }
468
+ if (typeof item.name !== "string" || typeof item.path !== "string") {
469
+ throw new DomainValidationError(
470
+ `${field} requires name and path`,
471
+ field
472
+ );
473
+ }
474
+ if (item.displayName !== void 0 && typeof item.displayName !== "string") {
475
+ throw new DomainValidationError(
476
+ `${field}.displayName must be a string`,
477
+ `${field}.displayName`
478
+ );
479
+ }
480
+ if (item.type === "mention") {
481
+ return {
482
+ type: "mention",
483
+ name: item.name,
484
+ path: item.path,
485
+ ...typeof item.displayName === "string" ? { displayName: item.displayName } : {}
486
+ };
487
+ }
488
+ if (item.source !== void 0 && item.source !== "bundled" && item.source !== "user" && item.source !== "project" && item.source !== "plugin") {
489
+ throw new DomainValidationError(
490
+ `${field}.source is invalid`,
491
+ `${field}.source`
492
+ );
493
+ }
494
+ return {
495
+ type: "skill",
496
+ name: item.name,
497
+ path: item.path,
498
+ ...typeof item.displayName === "string" ? { displayName: item.displayName } : {},
499
+ ...item.source !== void 0 ? { source: item.source } : {}
500
+ };
501
+ });
502
+ try {
503
+ return normalizeSessionUserInputItems(items);
504
+ } catch (error) {
505
+ if (!(error instanceof DomainValidationError)) throw error;
506
+ throw new DomainValidationError(
507
+ error instanceof DomainValidationError ? error.message : "items are invalid",
508
+ "items"
509
+ );
510
+ }
511
+ }
512
+ function parsePromptAttachments(value) {
513
+ if (value === void 0) return [];
514
+ if (!Array.isArray(value)) {
515
+ throw new DomainValidationError(
516
+ "attachments must be an array",
517
+ "attachments"
518
+ );
519
+ }
520
+ return value.map((entry, index) => {
521
+ const field = `attachments[${index}]`;
522
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
523
+ throw new DomainValidationError(`${field} must be an object`, field);
524
+ }
525
+ const item = entry;
526
+ const assetId = item.assetId;
527
+ if (typeof assetId !== "string" || assetId.length === 0) {
528
+ throw new DomainValidationError(
529
+ `${field}.assetId must be a non-empty string`,
530
+ `${field}.assetId`
531
+ );
532
+ }
533
+ const draftId = item.draftId;
534
+ if (draftId !== void 0 && (typeof draftId !== "string" || draftId.length === 0)) throw new DomainValidationError(`${field}.draftId must be a non-empty string`, `${field}.draftId`);
535
+ const intent = item.intent;
536
+ const allowedIntents = [
537
+ "auto",
538
+ "vision",
539
+ "ocr",
540
+ "document",
541
+ "tool_resource",
542
+ "workspace_reference"
543
+ ];
544
+ if (intent !== void 0 && (typeof intent !== "string" || !allowedIntents.includes(intent))) {
545
+ throw new DomainValidationError(
546
+ `${field}.intent must be one of: ${allowedIntents.join(", ")}`,
547
+ `${field}.intent`
548
+ );
549
+ }
550
+ const displayName = item.displayName;
551
+ if (displayName !== void 0 && typeof displayName !== "string") {
552
+ throw new DomainValidationError(
553
+ `${field}.displayName must be a string`,
554
+ `${field}.displayName`
555
+ );
556
+ }
557
+ return {
558
+ assetId,
559
+ ...draftId !== void 0 ? { draftId } : {},
560
+ ...intent !== void 0 ? { intent } : {},
561
+ ...displayName !== void 0 ? { displayName } : {}
562
+ };
563
+ });
564
+ }
565
+
566
+ // ../domain-contracts/src/inputs/metadata.ts
567
+ function assertPromptMetadataAllowed(input) {
568
+ for (const namespace of ["metadata", "runMetadata"]) {
569
+ const metadata = input[namespace];
570
+ if (!metadata || typeof metadata !== "object") continue;
571
+ if (Object.hasOwn(metadata, "outputSchema")) {
572
+ const field = `${namespace}.outputSchema`;
573
+ throw new DomainValidationError(`${field} is a stored snapshot; use explicit outputSchema`, field);
574
+ }
575
+ for (const name of ["pluginUi", "uiAction", "pluginUiSubmission", "pluginAppAction", "pluginAppSubmission", "pluginAppSource", "consumedForkHistory", "executionBinding", "configurationBinding", "initialConfigurationBinding", "steeredRunId", "sessionObservationGrant", "sessionObservationAccess"]) {
576
+ if (Object.hasOwn(metadata, name)) {
577
+ const field = `${namespace}.${name}`;
578
+ throw new DomainValidationError(
579
+ `${field} is reserved for the host`,
580
+ field
581
+ );
582
+ }
583
+ }
584
+ }
585
+ }
586
+
587
+ // ../domain-contracts/src/approvals/auto-review.ts
588
+ var AUTO_REVIEW_MODES = ["off", "risk_based"];
589
+ var AUTO_REVIEW_RISK_LEVELS = ["none", "low", "medium", "high", "unknown"];
590
+ var AUTO_REVIEW_STATUSES = [
591
+ "disabled",
592
+ "captured",
593
+ "skipped",
594
+ "pending",
595
+ "passed",
596
+ "findings",
597
+ "partial",
598
+ "failed",
599
+ "timed_out",
600
+ "unavailable"
601
+ ];
602
+ var AUTO_REVIEW_VERDICTS = ["pass", "fail", "partial"];
603
+ var AUTO_REVIEW_SEVERITIES = ["critical", "important", "minor"];
604
+ var AUTO_REVIEW_REASONS = [
605
+ "mode_off",
606
+ "no_changes",
607
+ "low_risk_change",
608
+ "source_change",
609
+ "large_change",
610
+ "many_files",
611
+ "sensitive_path",
612
+ "sensitive_content_path",
613
+ "production_delete_or_rename",
614
+ "patch_truncated",
615
+ "not_git_repository",
616
+ "preexisting_dirty_overlap",
617
+ "non_linear_head_change",
618
+ "post_commit_worktree_changed",
619
+ "git_inspection_failed",
620
+ "review_output_invalid",
621
+ "review_child_failed",
622
+ "review_child_timed_out",
623
+ "review_preempted_by_user",
624
+ "parent_run_not_completed",
625
+ "daemon_restarted",
626
+ "concurrent_run_overlap",
627
+ "execution_environment_unavailable",
628
+ "observation_budget_exceeded",
629
+ "observation_cancelled"
630
+ ];
631
+ var AUTO_REVIEW_MODE_SET = new Set(AUTO_REVIEW_MODES);
632
+ var AUTO_REVIEW_RISK_LEVEL_SET = new Set(AUTO_REVIEW_RISK_LEVELS);
633
+ var AUTO_REVIEW_STATUS_SET = new Set(AUTO_REVIEW_STATUSES);
634
+ var AUTO_REVIEW_VERDICT_SET = new Set(AUTO_REVIEW_VERDICTS);
635
+ var AUTO_REVIEW_SEVERITY_SET = new Set(AUTO_REVIEW_SEVERITIES);
636
+ var AUTO_REVIEW_REASON_SET = new Set(AUTO_REVIEW_REASONS);
637
+
638
+ // ../json-data/src/json.ts
639
+ function isJsonObject(value) {
640
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
641
+ const prototype = Object.getPrototypeOf(value);
642
+ return prototype === Object.prototype || prototype === null;
643
+ }
644
+ function isJsonRecord(value, byteLimit) {
645
+ return validateJsonRecord(value, byteLimit).valid;
646
+ }
647
+ function validateJsonRecord(value, byteLimit) {
648
+ if (!isJsonObject(value)) return { valid: false, reason: "invalid_json" };
649
+ try {
650
+ if (new TextEncoder().encode(stringifyCanonicalJson(value)).byteLength > byteLimit) {
651
+ return { valid: false, reason: "payload_too_large" };
652
+ }
653
+ return { valid: true, value };
654
+ } catch {
655
+ return { valid: false, reason: "invalid_json" };
656
+ }
657
+ }
658
+ function stringifyCanonicalJson(value) {
659
+ const render = (item, depth) => {
660
+ if (item === null || typeof item === "string" || typeof item === "boolean") {
661
+ return JSON.stringify(item);
662
+ }
663
+ if (typeof item === "number" && Number.isFinite(item))
664
+ return JSON.stringify(item);
665
+ if (typeof item !== "object" || item === null)
666
+ throw new Error("Finite requires JSON data");
667
+ if (depth >= 20)
668
+ throw new Error("Finite JSON nesting limit exceeded");
669
+ if (Array.isArray(item)) {
670
+ return `[${Array.from(item, (child) => render(child, depth + 1)).join(",")}]`;
671
+ }
672
+ const prototype = Object.getPrototypeOf(item);
673
+ if (prototype !== Object.prototype && prototype !== null) {
674
+ throw new Error("Finite requires plain JSON objects");
675
+ }
676
+ const record5 = item;
677
+ return `{${Object.keys(record5).sort().map((key) => `${JSON.stringify(key)}:${render(record5[key], depth + 1)}`).join(",")}}`;
678
+ };
679
+ return render(value, 0);
680
+ }
681
+
682
+ // ../plugin-contracts/src/manifest/limits.ts
683
+ var PLUGIN_APP_MANIFEST_LIMITS = Object.freeze({
684
+ manifestCount: 8,
685
+ manifestBytes: 256 * 1024,
686
+ backendCount: 32,
687
+ surfaceCount: 32
688
+ });
689
+ var PLUGIN_APP_RESOURCE_LIMITS = Object.freeze({ htmlBytes: 16 * 1024 * 1024, resourceBytes: 8 * 1024 * 1024 });
690
+ var PLUGIN_APP_DATA_LIMITS = Object.freeze({ maxArgsBytes: 64 * 1024 * 1024, jsonDepth: 32 });
691
+
692
+ // ../domain-contracts/src/plugin-apps/limits.ts
693
+ var PLUGIN_APP_INPUT_LIMITS = Object.freeze({ handoffBytes: 32 * 1024, messageCharacters: 4096, maxComposerContexts: 8 });
694
+
695
+ // ../domain-contracts/src/plugin-apps/history.ts
696
+ var isPluginUiRevision = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
697
+ var isPluginUiUuid = (value) => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
698
+ var PLUGIN_UI_LIMITS = { dataBytes: 256 * 1024, actionArgsBytes: 64 * 1024 };
699
+ function exactFields(record5, required, optional = []) {
700
+ return required.every((key) => Object.hasOwn(record5, key)) && Object.keys(record5).every(
701
+ (key) => required.includes(key) || optional.includes(key)
702
+ );
703
+ }
704
+ function nonempty(value) {
705
+ return typeof value === "string" && value.trim().length > 0;
706
+ }
707
+ function digest(value) {
708
+ return typeof value === "string" && /^[0-9a-f]{64}$/i.test(value);
709
+ }
710
+ function finite(value) {
711
+ return typeof value === "number" && Number.isFinite(value);
712
+ }
713
+ function readPluginUiInstance(metadata) {
714
+ if (!isJsonObject(metadata) || !Object.hasOwn(metadata, "pluginUi"))
715
+ return void 0;
716
+ const record5 = metadata.pluginUi;
717
+ const source = [
718
+ "sessionId",
719
+ "sourceRunId",
720
+ "sourcePartId",
721
+ "sourceToolUseId",
722
+ "sourceToolName",
723
+ "pluginId",
724
+ "pluginVersion",
725
+ "componentId",
726
+ "title"
727
+ ];
728
+ if (!isJsonObject(record5) || !exactFields(
729
+ record5,
730
+ [
731
+ "schemaVersion",
732
+ "instanceId",
733
+ ...source,
734
+ "pluginDigest",
735
+ "componentDigest",
736
+ "surface",
737
+ "status",
738
+ "revision",
739
+ "data",
740
+ "createdAt",
741
+ "updatedAt"
742
+ ],
743
+ ["activeActionRunId", "lastActionRunId", "dismissal"]
744
+ ))
745
+ return void 0;
746
+ if (record5.schemaVersion !== 2 || !isPluginUiUuid(record5.instanceId) || !source.every((key) => nonempty(record5[key])) || !digest(record5.pluginDigest) || !digest(record5.componentDigest) || record5.surface !== "tool-result" && record5.surface !== "session-sidebar" || !["open", "resolved", "dismissed"].includes(record5.status) || !isPluginUiRevision(record5.revision) || !finite(record5.createdAt) || !finite(record5.updatedAt) || !isJsonRecord(record5.data, PLUGIN_UI_LIMITS.dataBytes))
747
+ return void 0;
748
+ for (const key of ["activeActionRunId", "lastActionRunId"]) {
749
+ if (Object.hasOwn(record5, key) && !nonempty(record5[key])) return void 0;
750
+ }
751
+ if (Object.hasOwn(record5, "dismissal")) {
752
+ const dismissal = record5.dismissal;
753
+ if (!isJsonObject(dismissal) || !exactFields(dismissal, [
754
+ "requestId",
755
+ "requestFingerprint",
756
+ "expectedRevision",
757
+ "revision",
758
+ "dismissedAt"
759
+ ]) || !isPluginUiUuid(dismissal.requestId) || !digest(dismissal.requestFingerprint) || !isPluginUiRevision(dismissal.expectedRevision) || !isPluginUiRevision(dismissal.revision) || !finite(dismissal.dismissedAt))
760
+ return void 0;
761
+ }
762
+ return record5;
763
+ }
764
+
765
+ // ../protocol/src/serialization/json.ts
766
+ function isUuid(value) {
767
+ return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
768
+ value
769
+ );
770
+ }
771
+ function isNonnegativeInteger(value) {
772
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
773
+ }
774
+
775
+ // ../protocol/src/requests/requests.ts
776
+ function parseCancelResponseMode(value) {
777
+ if (value === void 0 || value === "snapshot") return "snapshot";
778
+ if (value === "receipt") return "receipt";
779
+ throw new ProtocolValidationError("Unsupported cancellation response mode", "responseMode");
780
+ }
781
+ var ProtocolValidationError = class extends Error {
782
+ code = "invalid_request";
783
+ details;
784
+ constructor(message, field, reason) {
785
+ super(message);
786
+ this.name = "ProtocolValidationError";
787
+ this.details = field || reason !== void 0 ? {
788
+ ...field ? { field } : {},
789
+ ...reason !== void 0 ? { reason } : {}
790
+ } : void 0;
791
+ }
792
+ toProtocolError() {
793
+ return {
794
+ code: this.code,
795
+ message: this.message,
796
+ ...this.details ? { details: this.details } : {}
797
+ };
798
+ }
799
+ };
800
+ function assertPromptMetadataAllowed2(input) {
801
+ adaptDomainInput(() => assertPromptMetadataAllowed(input));
802
+ }
803
+ function record3(value) {
804
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
805
+ throw new ProtocolValidationError("Request body must be a JSON object");
806
+ }
807
+ return value;
808
+ }
809
+ function requiredString2(body, field) {
810
+ const value = body[field];
811
+ if (typeof value !== "string") {
812
+ throw new ProtocolValidationError(`${field} is required`, field);
813
+ }
814
+ return value;
815
+ }
816
+ function optionalString2(body, field) {
817
+ const value = body[field];
818
+ if (value === void 0) return void 0;
819
+ if (typeof value !== "string") {
820
+ throw new ProtocolValidationError(`${field} must be a string`, field);
821
+ }
822
+ return value;
823
+ }
824
+ function optionalBoolean2(body, field) {
825
+ const value = body[field];
826
+ if (value === void 0) return void 0;
827
+ if (typeof value !== "boolean") {
828
+ throw new ProtocolValidationError(`${field} must be a boolean`, field);
829
+ }
830
+ return value;
831
+ }
832
+ function optionalRecord(body, field) {
833
+ const value = body[field];
834
+ if (value === void 0) return void 0;
835
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
836
+ throw new ProtocolValidationError(`${field} must be an object`, field);
837
+ }
838
+ return value;
839
+ }
840
+ function optionalEnum2(body, field, values) {
841
+ const value = body[field];
842
+ if (value === void 0) return void 0;
843
+ if (typeof value !== "string" || !values.includes(value)) {
844
+ throw new ProtocolValidationError(
845
+ `${field} must be one of: ${values.join(", ")}`,
846
+ field
847
+ );
848
+ }
849
+ return value;
850
+ }
851
+ function fields2(body, allowed) {
852
+ for (const key of Object.keys(body)) if (!allowed.includes(key)) throw new ProtocolValidationError(`Unknown field ${key}`, key);
853
+ }
854
+ function parseSessionConfiguration2(value) {
855
+ return adaptDomainInput(() => parseSessionConfiguration(value));
856
+ }
857
+ function parseConfigureSessionRequest(value) {
858
+ const body = record3(value);
859
+ fields2(body, ["requestId", "expectedRevision", "configuration", "optionsRevision"]);
860
+ const { requestId, expectedRevision } = body;
861
+ if (!isUuid(requestId)) throw new ProtocolValidationError("requestId must be a UUID", "requestId");
862
+ if (!isNonnegativeInteger(expectedRevision)) throw new ProtocolValidationError("expectedRevision must be a nonnegative integer", "expectedRevision");
863
+ const optionsRevision = optionalString2(body, "optionsRevision");
864
+ return { requestId, expectedRevision, configuration: parseSessionConfiguration2(body.configuration), ...optionsRevision === void 0 ? {} : { optionsRevision } };
865
+ }
866
+ function parseConfigurationResultRequest(value) {
867
+ const body = record3(value);
868
+ fields2(body, ["requestId", "original"]);
869
+ const original = parseConfigureSessionRequest(body.original);
870
+ if (body.requestId !== original.requestId) throw new ProtocolValidationError("requestId must match original.requestId", "requestId");
871
+ return { requestId: original.requestId, original };
872
+ }
873
+ function appMetadata(value) {
874
+ const metadata = record3(value);
875
+ fields2(metadata, ["app"]);
876
+ optionalRecord(metadata, "app");
877
+ return metadata;
878
+ }
879
+ function parseCreateSessionRequest(value) {
880
+ const body = record3(value);
881
+ fields2(body, ["id", "requestId", "cwd", "projectId", "title", "storage", "configuration", "optionsRevision", "metadata"]);
882
+ const cwd = requiredString2(body, "cwd");
883
+ const id2 = requiredString2(body, "id");
884
+ const requestId = requiredString2(body, "requestId");
885
+ if (!cwd.trim() || !id2.trim() || !requestId.trim()) throw new ProtocolValidationError("cwd, id and requestId cannot be empty");
886
+ const result = { id: id2, requestId, cwd };
887
+ for (const key of ["projectId", "title", "optionsRevision"]) if (body[key] !== void 0) result[key] = optionalString2(body, key);
888
+ if (body.storage !== void 0) result.storage = optionalEnum2(body, "storage", ["sqlite", "memory"]);
889
+ if (body.configuration !== void 0) result.configuration = parseSessionConfiguration2(body.configuration);
890
+ if (body.metadata !== void 0) result.metadata = appMetadata(optionalRecord(body, "metadata"));
891
+ return result;
892
+ }
893
+ function parseForkSessionRequest(value) {
894
+ const body = record3(value);
895
+ const beforeMessageId = optionalString2(body, "beforeMessageId");
896
+ const afterMessageId = optionalString2(body, "afterMessageId");
897
+ const storage = optionalEnum2(body, "storage", ["sqlite", "memory"]);
898
+ const copyHistory = optionalBoolean2(body, "copyHistory");
899
+ if (copyHistory === false && (beforeMessageId !== void 0 || afterMessageId !== void 0)) {
900
+ throw new ProtocolValidationError(
901
+ "copyHistory=false cannot select a fork point",
902
+ "copyHistory"
903
+ );
904
+ }
905
+ return {
906
+ ...body.id !== void 0 ? { id: optionalString2(body, "id") } : {},
907
+ ...body.requestId !== void 0 ? { requestId: optionalString2(body, "requestId") } : {},
908
+ ...copyHistory !== void 0 ? { copyHistory } : {},
909
+ ...beforeMessageId !== void 0 ? { beforeMessageId } : {},
910
+ ...afterMessageId !== void 0 ? { afterMessageId } : {},
911
+ ...storage !== void 0 ? { storage } : {}
912
+ };
913
+ }
914
+ function parseUpdateSessionRequest(value) {
915
+ const body = record3(value);
916
+ fields2(body, ["title", "metadata"]);
917
+ const title = optionalString2(body, "title");
918
+ const metadata = body.metadata === void 0 ? void 0 : appMetadata(optionalRecord(body, "metadata"));
919
+ return { ...title === void 0 ? {} : { title }, ...metadata === void 0 ? {} : { metadata } };
920
+ }
921
+ function adaptDomainInput(read) {
922
+ try {
923
+ return read();
924
+ } catch (error) {
925
+ if (error instanceof DomainValidationError) throw new ProtocolValidationError(error.message, error.field, error.reason);
926
+ throw error;
927
+ }
928
+ }
929
+
930
+ // ../protocol/src/requests/domain-validation.ts
931
+ function adaptDomainValidation(work) {
932
+ try {
933
+ return work();
934
+ } catch (error) {
935
+ if (error instanceof DomainValidationError) throw new ProtocolValidationError(error.message, error.field, error.reason);
936
+ throw error;
937
+ }
938
+ }
939
+
940
+ // ../protocol/src/session/session-resource-actions.ts
941
+ var parseSessionManagementAction2 = (...args) => adaptDomainValidation(() => parseSessionManagementAction(...args));
942
+ var parseSessionResourceMutation2 = (...args) => adaptDomainValidation(() => parseSessionResourceMutation(...args));
943
+ var decodeSessionResourceRevision2 = (...args) => adaptDomainValidation(() => decodeSessionResourceRevision(...args));
944
+ var decodeSessionMutationReceipt2 = (...args) => adaptDomainValidation(() => decodeSessionMutationReceipt(...args));
945
+
946
+ // ../protocol/src/serialization/serialization.ts
947
+ function decodeSessionConfigurationSnapshot(value) {
948
+ const snapshot = object(value, "configurationSnapshot"), root = object(snapshot.configurationRoot, "configurationSnapshot.configurationRoot");
949
+ if (Object.keys(snapshot).some((key) => !["revision", "configuration", "configurationRoot"].includes(key)) || !isNonnegativeInteger(snapshot.revision) || Object.keys(root).some((key) => !["cwd", "settingsRoot"].includes(key))) throw new ProtocolDataError("Invalid configuration snapshot");
950
+ const cwd = stringField(root, "cwd", "configurationRoot"), settingsRoot = stringField(root, "settingsRoot", "configurationRoot");
951
+ if (!cwd.trim() || !settingsRoot.trim()) throw new ProtocolDataError("Configuration roots are required");
952
+ let configuration;
953
+ try {
954
+ configuration = parseSessionConfiguration2(snapshot.configuration);
955
+ } catch {
956
+ throw new ProtocolDataError("Invalid resolved configuration");
957
+ }
958
+ const required = ["model", "roleId", "systemPrompt", "executionInstructions", "effort", "workMode", "maxTurns", "sessionMode", "replyStyle", "approvalMode", "tools", "pluginsEnabled", "pluginAutoSelectionEnabled", "activePluginId", "pluginIds", "serviceBindings", "memory"];
959
+ if (required.some((key) => !Object.hasOwn(configuration, key)) || !configuration.tools?.allowed || !configuration.tools.denied) throw new ProtocolDataError("Resolved configuration is incomplete");
960
+ return { revision: snapshot.revision, configuration, configurationRoot: { cwd, settingsRoot } };
961
+ }
962
+ var ProtocolDataError = class extends Error {
963
+ code = "invalid_protocol_data";
964
+ details;
965
+ constructor(message, path2) {
966
+ super(message);
967
+ this.name = "ProtocolDataError";
968
+ this.details = path2 ? { path: path2 } : void 0;
969
+ }
970
+ toProtocolError() {
971
+ return {
972
+ code: this.code,
973
+ message: this.message,
974
+ ...this.details ? { details: this.details } : {}
975
+ };
976
+ }
977
+ };
978
+ function object(value, path2) {
979
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
980
+ throw new ProtocolDataError(`${path2} must be an object`, path2);
981
+ }
982
+ return value;
983
+ }
984
+ function stringField(value, field, path2) {
985
+ const fieldPath = `${path2}.${field}`;
986
+ if (typeof value[field] !== "string") {
987
+ throw new ProtocolDataError(`${fieldPath} must be a string`, fieldPath);
988
+ }
989
+ return value[field];
990
+ }
991
+ function optionalString3(value, field, path2) {
992
+ const fieldValue = value[field];
993
+ if (fieldValue !== void 0 && typeof fieldValue !== "string") {
994
+ const fieldPath = `${path2}.${field}`;
995
+ throw new ProtocolDataError(`${fieldPath} must be a string`, fieldPath);
996
+ }
997
+ }
998
+ function numberField(value, field, path2) {
999
+ const fieldPath = `${path2}.${field}`;
1000
+ const fieldValue = value[field];
1001
+ if (typeof fieldValue !== "number" || !Number.isFinite(fieldValue)) {
1002
+ throw new ProtocolDataError(`${fieldPath} must be a finite number`, fieldPath);
1003
+ }
1004
+ return fieldValue;
1005
+ }
1006
+ function optionalNumber2(value, field, path2, nullable2 = false) {
1007
+ const fieldValue = value[field];
1008
+ if (fieldValue === void 0 || nullable2 && fieldValue === null) return;
1009
+ if (typeof fieldValue !== "number" || !Number.isFinite(fieldValue)) {
1010
+ const fieldPath = `${path2}.${field}`;
1011
+ throw new ProtocolDataError(`${fieldPath} must be a finite number`, fieldPath);
1012
+ }
1013
+ }
1014
+ function booleanField(value, field, path2) {
1015
+ const fieldPath = `${path2}.${field}`;
1016
+ if (typeof value[field] !== "boolean") {
1017
+ throw new ProtocolDataError(`${fieldPath} must be a boolean`, fieldPath);
1018
+ }
1019
+ return value[field];
1020
+ }
1021
+ function recordField(value, field, path2) {
1022
+ return object(value[field], `${path2}.${field}`);
1023
+ }
1024
+ function optionalRecord2(value, field, path2) {
1025
+ if (value[field] !== void 0) object(value[field], `${path2}.${field}`);
1026
+ }
1027
+ function enumField(value, field, path2, allowed) {
1028
+ const fieldPath = `${path2}.${field}`;
1029
+ const fieldValue = value[field];
1030
+ if (typeof fieldValue !== "string" || !allowed.includes(fieldValue)) {
1031
+ throw new ProtocolDataError(
1032
+ `${fieldPath} must be one of: ${allowed.join(", ")}`,
1033
+ fieldPath
1034
+ );
1035
+ }
1036
+ return fieldValue;
1037
+ }
1038
+ function arrayField(value, field, path2, validate) {
1039
+ const fieldPath = `${path2}.${field}`;
1040
+ const items = value[field];
1041
+ if (!Array.isArray(items)) {
1042
+ throw new ProtocolDataError(`${fieldPath} must be an array`, fieldPath);
1043
+ }
1044
+ return items.map((item, index) => validate(item, `${fieldPath}[${index}]`));
1045
+ }
1046
+ function validateSession(value, path2) {
1047
+ const item = object(value, path2);
1048
+ stringField(item, "id", path2);
1049
+ stringField(item, "cwd", path2);
1050
+ stringField(item, "title", path2);
1051
+ stringField(item, "model", path2);
1052
+ enumField(item, "status", path2, ["idle", "running", "closing", "archived", "error"]);
1053
+ if (item.storage !== void 0) enumField(item, "storage", path2, ["sqlite", "memory"]);
1054
+ recordField(item, "metadata", path2);
1055
+ numberField(item, "createdAt", path2);
1056
+ numberField(item, "updatedAt", path2);
1057
+ for (const field of ["parentId", "projectId", "cwdRelative", "agent"]) {
1058
+ optionalString3(item, field, path2);
1059
+ }
1060
+ optionalNumber2(item, "archivedAt", path2);
1061
+ return item;
1062
+ }
1063
+ function validateInput(value, path2) {
1064
+ const item = object(value, path2);
1065
+ stringField(item, "id", path2);
1066
+ stringField(item, "sessionId", path2);
1067
+ numberField(item, "seq", path2);
1068
+ enumField(item, "delivery", path2, ["queue", "steer"]);
1069
+ stringField(item, "content", path2);
1070
+ const attachments = arrayField(item, "attachments", path2, validateInputAttachment);
1071
+ const assetIds = /* @__PURE__ */ new Set();
1072
+ for (const [index, attachment] of attachments.entries()) {
1073
+ const attachmentPath = `${path2}.attachments[${index}]`;
1074
+ if (attachment.sessionId !== item.sessionId) {
1075
+ throw new ProtocolDataError(
1076
+ `${attachmentPath}.sessionId must match ${path2}.sessionId`,
1077
+ `${attachmentPath}.sessionId`
1078
+ );
1079
+ }
1080
+ if (attachment.inputId !== item.id) {
1081
+ throw new ProtocolDataError(
1082
+ `${attachmentPath}.inputId must match ${path2}.id`,
1083
+ `${attachmentPath}.inputId`
1084
+ );
1085
+ }
1086
+ if (attachment.seq !== index) {
1087
+ throw new ProtocolDataError(
1088
+ `${attachmentPath}.seq must equal its array index`,
1089
+ `${attachmentPath}.seq`
1090
+ );
1091
+ }
1092
+ if (assetIds.has(attachment.assetId)) {
1093
+ throw new ProtocolDataError(
1094
+ `${attachmentPath}.assetId must be unique within the input`,
1095
+ `${attachmentPath}.assetId`
1096
+ );
1097
+ }
1098
+ assetIds.add(attachment.assetId);
1099
+ }
1100
+ optionalString3(item, "promotedMessageId", path2);
1101
+ recordField(item, "metadata", path2);
1102
+ numberField(item, "createdAt", path2);
1103
+ return item;
1104
+ }
1105
+ function validateInputAttachment(value, path2) {
1106
+ const item = object(value, path2);
1107
+ for (const field of ["id", "sessionId", "inputId", "assetId", "displayName", "mediaType"]) {
1108
+ stringField(item, field, path2);
1109
+ }
1110
+ optionalString3(item, "draftId", path2);
1111
+ numberField(item, "seq", path2);
1112
+ enumField(item, "intent", path2, [
1113
+ "auto",
1114
+ "vision",
1115
+ "ocr",
1116
+ "document",
1117
+ "tool_resource",
1118
+ "workspace_reference"
1119
+ ]);
1120
+ numberField(item, "sizeBytes", path2);
1121
+ recordField(item, "metadata", path2);
1122
+ numberField(item, "createdAt", path2);
1123
+ return item;
1124
+ }
1125
+ function validateMessage(value, path2) {
1126
+ const item = object(value, path2);
1127
+ stringField(item, "id", path2);
1128
+ stringField(item, "sessionId", path2);
1129
+ numberField(item, "seq", path2);
1130
+ enumField(item, "role", path2, ["system", "user", "assistant"]);
1131
+ optionalString3(item, "runId", path2);
1132
+ optionalString3(item, "inputId", path2);
1133
+ recordField(item, "metadata", path2);
1134
+ numberField(item, "createdAt", path2);
1135
+ numberField(item, "updatedAt", path2);
1136
+ return item;
1137
+ }
1138
+ function validatePart(value, path2) {
1139
+ const item = object(value, path2);
1140
+ stringField(item, "id", path2);
1141
+ stringField(item, "sessionId", path2);
1142
+ stringField(item, "messageId", path2);
1143
+ numberField(item, "seq", path2);
1144
+ const type = enumField(item, "type", path2, [
1145
+ "text",
1146
+ "attachment",
1147
+ "transformation",
1148
+ "reasoning",
1149
+ "tool",
1150
+ "tool_result",
1151
+ "error",
1152
+ "log"
1153
+ ]);
1154
+ enumField(item, "status", path2, ["pending", "running", "completed", "failed", "interrupted"]);
1155
+ for (const field of ["text", "toolUseId", "toolName"]) optionalString3(item, field, path2);
1156
+ optionalRecord2(item, "input", path2);
1157
+ if (item.bodyView !== void 0) {
1158
+ const view = object(item.bodyView, `${path2}.bodyView`);
1159
+ for (const field of ["input", "output"]) enumField(view, field, `${path2}.bodyView`, ["full", "preview", "unavailable"]);
1160
+ if (view.outputReferences !== void 0 && (!Array.isArray(view.outputReferences) || !view.outputReferences.every((ref) => typeof ref === "string")))
1161
+ throw new ProtocolDataError(`${path2}.bodyView.outputReferences must be strings`, `${path2}.bodyView.outputReferences`);
1162
+ }
1163
+ if (item.isError !== void 0 && typeof item.isError !== "boolean") {
1164
+ throw new ProtocolDataError(`${path2}.isError must be a boolean`, `${path2}.isError`);
1165
+ }
1166
+ if (type === "attachment") {
1167
+ for (const field of ["assetId", "displayName", "mediaType"]) {
1168
+ stringField(item, field, path2);
1169
+ }
1170
+ enumField(item, "intent", path2, [
1171
+ "auto",
1172
+ "vision",
1173
+ "ocr",
1174
+ "document",
1175
+ "tool_resource",
1176
+ "workspace_reference"
1177
+ ]);
1178
+ numberField(item, "sizeBytes", path2);
1179
+ }
1180
+ if (type === "transformation") {
1181
+ stringField(item, "assetId", path2);
1182
+ enumField(item, "kind", path2, ["direct", "document_extract", "tool_mount"]);
1183
+ for (const field of ["representationId", "processor", "transformationError"]) {
1184
+ optionalString3(item, field, path2);
1185
+ }
1186
+ }
1187
+ recordField(item, "metadata", path2);
1188
+ numberField(item, "createdAt", path2);
1189
+ numberField(item, "updatedAt", path2);
1190
+ return item;
1191
+ }
1192
+ function validateRun(value, path2) {
1193
+ const item = object(value, path2);
1194
+ stringField(item, "id", path2);
1195
+ stringField(item, "sessionId", path2);
1196
+ optionalString3(item, "inputId", path2);
1197
+ enumField(item, "status", path2, ["pending", "running", "completed", "failed", "interrupted"]);
1198
+ optionalNumber2(item, "startedAt", path2);
1199
+ optionalNumber2(item, "finishedAt", path2);
1200
+ optionalString3(item, "error", path2);
1201
+ recordField(item, "metadata", path2);
1202
+ numberField(item, "createdAt", path2);
1203
+ numberField(item, "updatedAt", path2);
1204
+ return item;
1205
+ }
1206
+ function validateAttempt(value, path2) {
1207
+ const item = object(value, path2);
1208
+ stringField(item, "id", path2);
1209
+ stringField(item, "runId", path2);
1210
+ numberField(item, "sequence", path2);
1211
+ enumField(item, "status", path2, ["pending", "running", "completed", "failed", "cancelled"]);
1212
+ for (const field of ["provider", "model", "retryReason", "errorKind", "error"]) {
1213
+ optionalString3(item, field, path2);
1214
+ }
1215
+ for (const field of ["inputTokens", "outputTokens", "startedAt", "finishedAt"]) {
1216
+ optionalNumber2(item, field, path2);
1217
+ }
1218
+ numberField(item, "createdAt", path2);
1219
+ numberField(item, "updatedAt", path2);
1220
+ return item;
1221
+ }
1222
+ function validateTask(value, path2) {
1223
+ const item = object(value, path2);
1224
+ for (const field of ["id", "sessionId", "type", "description", "cwd"]) {
1225
+ stringField(item, field, path2);
1226
+ }
1227
+ for (const field of ["childSessionId", "runId", "requestNamespace", "requestId", "output", "error"]) {
1228
+ optionalString3(item, field, path2);
1229
+ }
1230
+ enumField(item, "status", path2, ["pending", "running", "completed", "failed", "stopped", "interrupted"]);
1231
+ recordField(item, "metadata", path2);
1232
+ numberField(item, "createdAt", path2);
1233
+ optionalNumber2(item, "startedAt", path2);
1234
+ optionalNumber2(item, "finishedAt", path2);
1235
+ numberField(item, "updatedAt", path2);
1236
+ return item;
1237
+ }
1238
+ function validatePermission(value, path2) {
1239
+ const item = object(value, path2);
1240
+ for (const field of ["id", "sessionId", "toolName"]) stringField(item, field, path2);
1241
+ optionalString3(item, "runId", path2);
1242
+ recordField(item, "payload", path2);
1243
+ enumField(item, "status", path2, ["pending", "approved", "denied", "expired"]);
1244
+ optionalString3(item, "decision", path2);
1245
+ optionalString3(item, "decidedByClientId", path2);
1246
+ numberField(item, "createdAt", path2);
1247
+ numberField(item, "updatedAt", path2);
1248
+ return item;
1249
+ }
1250
+ function decodeSessionEventRecord(value) {
1251
+ const event = object(value, "event");
1252
+ stringField(event, "id", "event");
1253
+ numberField(event, "seq", "event");
1254
+ stringField(event, "type", "event");
1255
+ numberField(event, "schemaVersion", "event");
1256
+ optionalString3(event, "sessionId", "event");
1257
+ recordField(event, "payload", "event");
1258
+ numberField(event, "createdAt", "event");
1259
+ return event;
1260
+ }
1261
+ function validateSessionStateSnapshot(value) {
1262
+ const snapshot = object(value, "snapshot");
1263
+ numberField(snapshot, "cursor", "snapshot");
1264
+ validateSession(snapshot.session, "snapshot.session");
1265
+ arrayField(snapshot, "inputs", "snapshot", validateInput);
1266
+ arrayField(snapshot, "messages", "snapshot", validateMessage);
1267
+ arrayField(snapshot, "parts", "snapshot", validatePart);
1268
+ arrayField(snapshot, "runs", "snapshot", validateRun);
1269
+ arrayField(snapshot, "attempts", "snapshot", validateAttempt);
1270
+ if (snapshot.tasks !== void 0) arrayField(snapshot, "tasks", "snapshot", validateTask);
1271
+ arrayField(snapshot, "permissions", "snapshot", validatePermission);
1272
+ return snapshot;
1273
+ }
1274
+ function decodeAgentSessionStateSnapshot(value) {
1275
+ const snapshot = validateSessionStateSnapshot(value);
1276
+ const { cursor, session, inputs, messages, parts, runs, attempts, tasks, permissions, goal } = snapshot;
1277
+ return { cursor, session, inputs, messages, parts, runs, attempts, ...tasks !== void 0 ? { tasks } : {}, permissions, ...goal !== void 0 ? { goal } : {} };
1278
+ }
1279
+ function decodeSessionConfigurationReceipt(value, expected) {
1280
+ const path2 = "configurationReceipt";
1281
+ const receipt2 = object(value, path2);
1282
+ if (Object.keys(receipt2).some((key) => !["dataScopeId", "sessionId", "requestId", "action", "state", "revision"].includes(key))) throw new ProtocolDataError("Unexpected configuration receipt field", path2);
1283
+ const dataScopeId = stringField(receipt2, "dataScopeId", path2);
1284
+ const state = enumField(receipt2, "state", path2, ["prepared", "completed", "unknown"]);
1285
+ if (!dataScopeId.trim() || receipt2.sessionId !== expected.sessionId || receipt2.requestId !== expected.requestId || receipt2.action !== "configure") throw new ProtocolDataError("Configuration receipt does not match the original request", path2);
1286
+ const { revision: revision2 } = receipt2;
1287
+ if ((revision2 !== void 0 || state === "completed") && !isNonnegativeInteger(revision2)) throw new ProtocolDataError("Configuration receipt revision is invalid", `${path2}.revision`);
1288
+ return { dataScopeId, ...expected, action: "configure", state, ...typeof revision2 === "number" ? { revision: revision2 } : {} };
1289
+ }
1290
+ function decodeJobTarget(value) {
1291
+ const target = object(value, "jobTarget");
1292
+ const kind = enumField(target, "kind", "jobTarget", ["terminal", "shell", "agent", "dream", "workflow"]);
1293
+ if (!stringField(target, "jobId", "jobTarget").trim()) throw new ProtocolDataError("jobTarget.jobId is required", "jobTarget.jobId");
1294
+ if (kind === "agent" && !stringField(target, "runId", "jobTarget").trim()) throw new ProtocolDataError("jobTarget.runId is required", "jobTarget.runId");
1295
+ return target;
1296
+ }
1297
+ function decodeJobInputReceipt(value) {
1298
+ const receipt2 = object(value, "jobInputReceipt");
1299
+ for (const field of ["sessionId", "inputId", "runId"]) {
1300
+ if (!stringField(receipt2, field, "jobInputReceipt").trim()) throw new ProtocolDataError(`jobInputReceipt.${field} is required`, `jobInputReceipt.${field}`);
1301
+ }
1302
+ return receipt2;
1303
+ }
1304
+ function decodeJobListResult(value) {
1305
+ const result = object(value, "jobListResult");
1306
+ if (!Array.isArray(result.jobs) || !Array.isArray(result.errors)) throw new ProtocolDataError("Jobs list requires jobs and errors arrays", "jobListResult");
1307
+ result.jobs.forEach(decodeJobSnapshot);
1308
+ for (const error of result.errors) {
1309
+ const item = object(error, "jobListResult.errors");
1310
+ enumField(item, "kind", "jobListResult.errors", ["terminal", "shell", "agent", "dream", "workflow"]);
1311
+ stringField(item, "message", "jobListResult.errors");
1312
+ }
1313
+ return result;
1314
+ }
1315
+ function cancellationReceipt(value, fields3) {
1316
+ const envelope = object(value, "cancelResponse"), receipt2 = object(envelope.receipt, "cancelResponse.receipt");
1317
+ if (Object.keys(envelope).some((key) => key !== "receipt") || Object.keys(receipt2).some((key) => !fields3.includes(key))) throw new ProtocolDataError("Unexpected cancellation receipt field");
1318
+ for (const field of fields3.filter((field2) => field2 !== "status")) if (!stringField(receipt2, field, "cancelResponse.receipt").trim()) throw new ProtocolDataError("Cancellation receipt ID must not be empty");
1319
+ return receipt2;
1320
+ }
1321
+ function decodeJobCancelReceipt(value) {
1322
+ const receipt2 = cancellationReceipt(value, ["id", "status"]);
1323
+ enumField(receipt2, "status", "cancelResponse.receipt", ["running", "stopping", "completed", "killed", "failed"]);
1324
+ return receipt2;
1325
+ }
1326
+ function decodeQueuedPromptCancelReceipt(value) {
1327
+ const receipt2 = cancellationReceipt(value, ["inputId", "queuedRunId", "status"]);
1328
+ enumField(receipt2, "status", "cancelResponse.receipt", ["interrupted"]);
1329
+ return receipt2;
1330
+ }
1331
+ function decodeJobSnapshot(value) {
1332
+ const job = object(value, "job");
1333
+ for (const field of ["id", "label", "ownerSession", "cwd"]) stringField(job, field, "job");
1334
+ enumField(job, "kind", "job", ["terminal", "shell", "agent", "dream", "workflow"]);
1335
+ const target = decodeJobTarget(job.target);
1336
+ if (target.kind !== job.kind || target.jobId !== job.id) throw new ProtocolDataError("job target does not match snapshot", "job.target");
1337
+ enumField(job, "status", "job", ["running", "stopping", "completed", "killed", "failed"]);
1338
+ const capabilities = recordField(job, "capabilities", "job");
1339
+ for (const field of ["read", "wait", "send", "cancel"]) {
1340
+ booleanField(capabilities, field, "job.capabilities");
1341
+ }
1342
+ numberField(job, "startedAt", "job");
1343
+ numberField(job, "updatedAt", "job");
1344
+ optionalNumber2(job, "finishedAt", "job");
1345
+ const exitCode = job.exitCode;
1346
+ if (exitCode !== void 0 && exitCode !== null && (typeof exitCode !== "number" || !Number.isInteger(exitCode))) {
1347
+ throw new ProtocolDataError("job.exitCode must be an integer or null", "job.exitCode");
1348
+ }
1349
+ optionalString3(job, "detail", "job");
1350
+ optionalRecord2(job, "metadata", "job");
1351
+ return job;
1352
+ }
1353
+ function decodeJobReadResult(value) {
1354
+ const result = object(value, "jobReadResult");
1355
+ stringField(result, "text", "jobReadResult");
1356
+ numberField(result, "cursor", "jobReadResult");
1357
+ booleanField(result, "truncated", "jobReadResult");
1358
+ decodeJobSnapshot(result.snapshot);
1359
+ optionalRecord2(result, "details", "jobReadResult");
1360
+ return result;
1361
+ }
1362
+ function decodeJobWaitResult(value) {
1363
+ const result = object(value, "jobWaitResult");
1364
+ decodeJobReadResult(result);
1365
+ booleanField(result, "timedOut", "jobWaitResult");
1366
+ return result;
1367
+ }
1368
+ function decodeTerminalSessionInfo(value) {
1369
+ const terminal = object(value, "terminal");
1370
+ for (const field of ["id", "name", "cwd", "shell", "createdAt"]) {
1371
+ stringField(terminal, field, "terminal");
1372
+ }
1373
+ const scope = recordField(terminal, "scope", "terminal");
1374
+ const scopeKind = enumField(scope, "kind", "terminal.scope", ["project", "session"]);
1375
+ if (scopeKind === "project") {
1376
+ const projectId = stringField(scope, "projectId", "terminal.scope");
1377
+ optionalString3(terminal, "projectId", "terminal");
1378
+ if (terminal.projectId !== void 0 && terminal.projectId !== projectId) {
1379
+ throw new ProtocolDataError(
1380
+ "terminal.projectId must match terminal.scope.projectId",
1381
+ "terminal.projectId"
1382
+ );
1383
+ }
1384
+ } else {
1385
+ const sessionId = stringField(scope, "sessionId", "terminal.scope");
1386
+ optionalString3(terminal, "sessionId", "terminal");
1387
+ if (terminal.sessionId !== void 0 && terminal.sessionId !== sessionId) {
1388
+ throw new ProtocolDataError(
1389
+ "terminal.sessionId must match terminal.scope.sessionId",
1390
+ "terminal.sessionId"
1391
+ );
1392
+ }
1393
+ }
1394
+ optionalString3(terminal, "projectId", "terminal");
1395
+ optionalString3(terminal, "sessionId", "terminal");
1396
+ enumField(terminal, "runtime", "terminal", ["local", "environment"]);
1397
+ enumField(terminal, "source", "terminal", ["user", "agent"]);
1398
+ enumField(terminal, "status", "terminal", ["running", "stopping", "completed", "killed", "failed"]);
1399
+ numberField(terminal, "cols", "terminal");
1400
+ numberField(terminal, "rows", "terminal");
1401
+ optionalString3(terminal, "exitedAt", "terminal");
1402
+ optionalNumber2(terminal, "exitCode", "terminal", true);
1403
+ return terminal;
1404
+ }
1405
+ function decodeTerminalEvent(value) {
1406
+ const event = object(value, "terminalEvent");
1407
+ const type = enumField(event, "type", "terminalEvent", ["data", "status", "exit", "title", "error"]);
1408
+ stringField(event, "terminalId", "terminalEvent");
1409
+ if (type === "data") {
1410
+ stringField(event, "data", "terminalEvent");
1411
+ numberField(event, "sequence", "terminalEvent");
1412
+ } else if (type === "status") {
1413
+ enumField(event, "status", "terminalEvent", ["stopping", "killed"]);
1414
+ } else if (type === "exit") {
1415
+ optionalNumber2(event, "exitCode", "terminalEvent", true);
1416
+ if (!("exitCode" in event)) {
1417
+ throw new ProtocolDataError("terminalEvent.exitCode is required", "terminalEvent.exitCode");
1418
+ }
1419
+ } else if (type === "title") {
1420
+ stringField(event, "title", "terminalEvent");
1421
+ } else {
1422
+ stringField(event, "message", "terminalEvent");
1423
+ }
1424
+ return event;
1425
+ }
1426
+ function decodeTerminalReadResult(value) {
1427
+ const result = object(value, "terminalReadResult");
1428
+ stringField(result, "terminalId", "terminalReadResult");
1429
+ stringField(result, "data", "terminalReadResult");
1430
+ numberField(result, "sequence", "terminalReadResult");
1431
+ booleanField(result, "truncated", "terminalReadResult");
1432
+ return result;
1433
+ }
1434
+
1435
+ // ../protocol/src/runtime/runtime-config.ts
1436
+ function adaptRuntimeData(work) {
1437
+ try {
1438
+ return work();
1439
+ } catch (error) {
1440
+ if (error instanceof DomainValidationError) throw new ProtocolDataError(error.message, error.field);
1441
+ throw error;
1442
+ }
1443
+ }
1444
+ function readRuntimeMetadata2(metadata) {
1445
+ return adaptRuntimeData(() => readRuntimeMetadata(metadata));
1446
+ }
1447
+
1448
+ // ../domain-contracts/src/attachments/validation.ts
1449
+ function parseAttachmentLimits(value) {
1450
+ const record5 = recordValue(value, "attachment limits");
1451
+ const limits2 = {
1452
+ maxFilesPerPrompt: positiveInteger(
1453
+ record5.maxFilesPerPrompt,
1454
+ "maxFilesPerPrompt"
1455
+ ),
1456
+ maxBytesPerFile: positiveInteger(record5.maxBytesPerFile, "maxBytesPerFile"),
1457
+ maxBytesPerPrompt: positiveInteger(
1458
+ record5.maxBytesPerPrompt,
1459
+ "maxBytesPerPrompt"
1460
+ ),
1461
+ maxSessionReferencedBytes: positiveInteger(
1462
+ record5.maxSessionReferencedBytes,
1463
+ "maxSessionReferencedBytes"
1464
+ ),
1465
+ resumableThresholdBytes: positiveInteger(
1466
+ record5.resumableThresholdBytes,
1467
+ "resumableThresholdBytes"
1468
+ ),
1469
+ uploadSessionTtlMs: positiveInteger(
1470
+ record5.uploadSessionTtlMs,
1471
+ "uploadSessionTtlMs"
1472
+ ),
1473
+ stagingTtlMs: positiveInteger(record5.stagingTtlMs, "stagingTtlMs")
1474
+ };
1475
+ if (limits2.resumableThresholdBytes > limits2.maxBytesPerFile) {
1476
+ throw new Error("resumableThresholdBytes must not exceed maxBytesPerFile");
1477
+ }
1478
+ if (limits2.maxBytesPerFile > limits2.maxBytesPerPrompt) {
1479
+ throw new Error("maxBytesPerFile must not exceed maxBytesPerPrompt");
1480
+ }
1481
+ if (limits2.maxBytesPerPrompt > limits2.maxSessionReferencedBytes) {
1482
+ throw new Error(
1483
+ "maxBytesPerPrompt must not exceed maxSessionReferencedBytes"
1484
+ );
1485
+ }
1486
+ return limits2;
1487
+ }
1488
+ function parseAttachmentAssetRecord(value) {
1489
+ const record5 = recordValue(value, "attachment asset");
1490
+ const status = enumValue(
1491
+ record5.status,
1492
+ ["importing", "ready", "failed", "deleted"],
1493
+ "status"
1494
+ );
1495
+ const asset = {
1496
+ id: nonEmptyString(record5.id, "id"),
1497
+ displayName: nonEmptyString(record5.displayName, "displayName"),
1498
+ status,
1499
+ createdAt: nonNegativeInteger(record5.createdAt, "createdAt"),
1500
+ updatedAt: nonNegativeInteger(record5.updatedAt, "updatedAt")
1501
+ };
1502
+ const declaredMediaType = optionalNonEmptyString(
1503
+ record5.declaredMediaType,
1504
+ "declaredMediaType"
1505
+ );
1506
+ const mediaType = optionalNonEmptyString(record5.mediaType, "mediaType");
1507
+ const sizeBytes = optionalNonNegativeInteger(record5.sizeBytes, "sizeBytes");
1508
+ const sha256 = optionalSha256(record5.sha256);
1509
+ const failureCode = optionalNonEmptyString(record5.failureCode, "failureCode");
1510
+ const deletedAt = optionalNonNegativeInteger(record5.deletedAt, "deletedAt");
1511
+ if (declaredMediaType !== void 0) asset.declaredMediaType = declaredMediaType;
1512
+ if (mediaType !== void 0) asset.mediaType = mediaType;
1513
+ if (sizeBytes !== void 0) asset.sizeBytes = sizeBytes;
1514
+ if (sha256 !== void 0) asset.sha256 = sha256;
1515
+ if (failureCode !== void 0) asset.failureCode = failureCode;
1516
+ if (deletedAt !== void 0) asset.deletedAt = deletedAt;
1517
+ if (record5.chatSources !== void 0) {
1518
+ if (!Array.isArray(record5.chatSources)) throw new Error("chatSources must be an array");
1519
+ asset.chatSources = record5.chatSources.map(parseChatResourceSource);
1520
+ }
1521
+ if (status === "ready" || status === "deleted") {
1522
+ if (asset.mediaType === void 0) throw new Error("mediaType is required");
1523
+ if (asset.sizeBytes === void 0) throw new Error("sizeBytes is required");
1524
+ if (asset.sha256 === void 0) throw new Error("sha256 is required");
1525
+ }
1526
+ if (status === "failed" && asset.failureCode === void 0) {
1527
+ throw new Error("failureCode is required");
1528
+ }
1529
+ if (status === "deleted" && asset.deletedAt === void 0) {
1530
+ throw new Error("deletedAt is required");
1531
+ }
1532
+ return asset;
1533
+ }
1534
+ function parseChatResourceSource(value) {
1535
+ const record5 = recordValue(value, "chat resource source");
1536
+ const source = {
1537
+ storage: enumValue(record5.storage, ["memory", "sqlite"], "storage"),
1538
+ sessionId: nonEmptyString(record5.sessionId, "sessionId")
1539
+ };
1540
+ for (const field of ["sourceSessionId", "inputId", "runId"]) {
1541
+ const id2 = optionalNonEmptyString(record5[field], field);
1542
+ if (id2 !== void 0) source[field] = id2;
1543
+ }
1544
+ return source;
1545
+ }
1546
+ function recordValue(value, field) {
1547
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1548
+ throw new Error(`${field} must be an object`);
1549
+ }
1550
+ return value;
1551
+ }
1552
+ function positiveInteger(value, field) {
1553
+ if (!Number.isSafeInteger(value) || Number(value) < 1) {
1554
+ throw new Error(`${field} must be a positive safe integer`);
1555
+ }
1556
+ return Number(value);
1557
+ }
1558
+ function nonNegativeInteger(value, field) {
1559
+ if (!Number.isSafeInteger(value) || Number(value) < 0) {
1560
+ throw new Error(`${field} must be a non-negative safe integer`);
1561
+ }
1562
+ return Number(value);
1563
+ }
1564
+ function optionalNonNegativeInteger(value, field) {
1565
+ return value === void 0 ? void 0 : nonNegativeInteger(value, field);
1566
+ }
1567
+ function nonEmptyString(value, field) {
1568
+ if (typeof value !== "string" || value.length === 0) {
1569
+ throw new Error(`${field} must be a non-empty string`);
1570
+ }
1571
+ return value;
1572
+ }
1573
+ function optionalNonEmptyString(value, field) {
1574
+ return value === void 0 ? void 0 : nonEmptyString(value, field);
1575
+ }
1576
+ function optionalSha256(value) {
1577
+ if (value === void 0) return void 0;
1578
+ if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) {
1579
+ throw new Error("sha256 must be 64 lowercase hexadecimal characters");
1580
+ }
1581
+ return value;
1582
+ }
1583
+ function enumValue(value, allowed, field) {
1584
+ if (typeof value !== "string" || !allowed.includes(value)) {
1585
+ throw new Error(`${field} must be one of: ${allowed.join(", ")}`);
1586
+ }
1587
+ return value;
1588
+ }
1589
+ function parseAttachmentUploadRequest(value) {
1590
+ const record5 = recordValue(value, "attachment upload");
1591
+ const result = { requestId: nonEmptyString(record5.requestId, "requestId"), draftId: nonEmptyString(record5.draftId, "draftId"), displayName: nonEmptyString(record5.displayName, "displayName"), expectedSha256: optionalSha256(record5.expectedSha256), byteLength: nonNegativeInteger(record5.byteLength, "byteLength") };
1592
+ if (!result.expectedSha256) throw new Error("expectedSha256 is required");
1593
+ const declaredMediaType = optionalNonEmptyString(record5.declaredMediaType, "declaredMediaType");
1594
+ return { ...result, expectedSha256: result.expectedSha256, ...declaredMediaType ? { declaredMediaType } : {} };
1595
+ }
1596
+
1597
+ // ../protocol/src/runtime/capabilities.ts
1598
+ var CURRENT_PROTOCOL_VERSION = 7;
1599
+ var PROTOCOL_VERSION_HEADER = "x-bobannomi-protocol-version";
1600
+ function parseServerCapabilities(value) {
1601
+ if (!isRecord2(value))
1602
+ throw new Error("Capabilities response must be an object");
1603
+ if (typeof value.serverVersion !== "string")
1604
+ throw new Error("serverVersion must be a string");
1605
+ if (!isRecord2(value.protocol)) throw new Error("protocol must be an object");
1606
+ const version = positiveInteger2(value.protocol.version, "protocol.version");
1607
+ if (!isRecord2(value.features)) throw new Error("features must be an object");
1608
+ const features = {};
1609
+ for (const [name, version2] of Object.entries(value.features)) {
1610
+ features[name] = positiveInteger2(version2, `features.${name}`);
1611
+ }
1612
+ const attachments = parseAttachmentTransferCapabilities(value.attachments);
1613
+ const agentEnvironments = parseAgentEnvironmentCapabilities(
1614
+ value.agentEnvironments
1615
+ );
1616
+ const mcpOAuth = parseMcpOAuthCapabilities(value.mcpOAuth);
1617
+ if (value.dataScopeId !== void 0 && (typeof value.dataScopeId !== "string" || !value.dataScopeId || value.dataScopeId.length > 256)) throw new Error("dataScopeId must be a bounded non-empty string");
1618
+ const storage = value.daemonStorage;
1619
+ if (storage !== void 0 && (!isRecord2(storage) || !Number.isInteger(storage.pid) || Number(storage.pid) <= 0 || ["instanceId", "configDir", "dataDir", "storePath"].some((key) => typeof storage[key] !== "string" || !storage[key].length))) throw new Error("daemonStorage is invalid");
1620
+ return {
1621
+ ...storage ? { daemonStorage: storage } : {},
1622
+ ...value.dataScopeId === void 0 ? {} : { dataScopeId: value.dataScopeId },
1623
+ serverVersion: value.serverVersion,
1624
+ protocol: { version },
1625
+ features,
1626
+ ...attachments ? { attachments } : {},
1627
+ ...agentEnvironments ? { agentEnvironments } : {},
1628
+ ...mcpOAuth ? { mcpOAuth } : {}
1629
+ };
1630
+ }
1631
+ function parseMcpOAuthCapabilities(value) {
1632
+ if (value === void 0) return void 0;
1633
+ if (!isRecord2(value) || typeof value.instanceId !== "string" || value.instanceId.length === 0 || value.instanceId.length > 200) {
1634
+ throw new Error("mcpOAuth.instanceId must be a bounded non-empty string");
1635
+ }
1636
+ return { instanceId: value.instanceId };
1637
+ }
1638
+ function parseAgentEnvironmentCapabilities(value) {
1639
+ if (value === void 0) return void 0;
1640
+ if (!isRecord2(value) || value.native !== true || typeof value.wsl !== "boolean") {
1641
+ throw new Error(
1642
+ "agentEnvironments must contain native=true and a boolean wsl value"
1643
+ );
1644
+ }
1645
+ const active = value.activeDefault;
1646
+ if (active !== void 0 && (!isRecord2(active) || active.kind !== "native" && active.kind !== "wsl" || typeof active.fingerprint !== "string" || active.distribution !== void 0 && typeof active.distribution !== "string")) throw new Error("agentEnvironments.activeDefault is invalid");
1647
+ return { native: true, wsl: value.wsl, ...active ? { activeDefault: active } : {} };
1648
+ }
1649
+ function checkProtocolCompatibility(server, client) {
1650
+ if (client.version !== server.protocol.version) {
1651
+ return {
1652
+ compatible: false,
1653
+ reason: `Client protocol ${client.version} does not match server protocol ${server.protocol.version}`
1654
+ };
1655
+ }
1656
+ return { compatible: true };
1657
+ }
1658
+ function supportsFeature(capabilities, feature, minimumVersion = 1) {
1659
+ return (capabilities.features[feature] ?? 0) >= minimumVersion;
1660
+ }
1661
+ function positiveInteger2(value, field) {
1662
+ if (!Number.isInteger(value) || Number(value) < 1)
1663
+ throw new Error(`${field} must be a positive integer`);
1664
+ return Number(value);
1665
+ }
1666
+ function isRecord2(value) {
1667
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1668
+ }
1669
+ function parseAttachmentTransferCapabilities(value) {
1670
+ if (value === void 0) return void 0;
1671
+ if (!isRecord2(value)) throw new Error("attachments must be an object");
1672
+ if (!Array.isArray(value.uploadModes) || value.uploadModes.length === 0) {
1673
+ throw new Error("attachments.uploadModes must be a non-empty array");
1674
+ }
1675
+ if (value.uploadModes[0] !== "single" || value.uploadModes.length > 2 || value.uploadModes.length === 2 && value.uploadModes[1] !== "resumable") {
1676
+ throw new Error(
1677
+ 'attachments.uploadModes must be ["single"] or ["single", "resumable"]'
1678
+ );
1679
+ }
1680
+ const uploadModes = value.uploadModes;
1681
+ return {
1682
+ limits: parseAttachmentLimits(value.limits),
1683
+ uploadModes
1684
+ };
1685
+ }
1686
+
1687
+ // ../domain-contracts/src/goals/records.ts
1688
+ var MAX_GOAL_AUTO_TURNS = 1e3;
1689
+ var MAX_GOAL_OBJECTIVE_CHARS = 32e3;
1690
+
1691
+ // ../domain-contracts/src/goals/validation.ts
1692
+ function parseCreateSessionGoalInput(value) {
1693
+ const record5 = goalRecord(value);
1694
+ assertGoalFields(record5, ["requestId", "objective", "maxAutoTurns", "tokenBudget", "items", "attachments"]);
1695
+ return {
1696
+ requestId: requiredGoalString(record5.requestId, "requestId", 128),
1697
+ objective: requiredGoalString(record5.objective, "objective", MAX_GOAL_OBJECTIVE_CHARS),
1698
+ ...record5.tokenBudget === void 0 ? {} : { tokenBudget: goalPositiveTimestamp(record5.tokenBudget, "tokenBudget") },
1699
+ ...record5.maxAutoTurns === void 0 ? {} : {
1700
+ maxAutoTurns: goalPositiveInteger(record5.maxAutoTurns, "maxAutoTurns", true)
1701
+ },
1702
+ ...parseGoalContent(record5)
1703
+ };
1704
+ }
1705
+ function parseUpdateSessionGoalInput(value) {
1706
+ const record5 = goalRecord(value);
1707
+ assertGoalFields(record5, ["requestId", "expectedRevision", "objective", "items", "attachments"]);
1708
+ return {
1709
+ requestId: requiredGoalString(record5.requestId, "requestId", 128),
1710
+ expectedRevision: goalNonNegativeInteger(record5.expectedRevision, "expectedRevision"),
1711
+ objective: requiredGoalString(record5.objective, "objective", MAX_GOAL_OBJECTIVE_CHARS),
1712
+ ...parseGoalContent(record5)
1713
+ };
1714
+ }
1715
+ function parseGoalActionInput(value) {
1716
+ const record5 = goalRecord(value);
1717
+ if (record5.action !== "pause" && record5.action !== "resume" && record5.action !== "cancel" && record5.action !== "budget" && record5.action !== "cancel_resume") {
1718
+ throw new DomainValidationError("invalid_goal_action", "action");
1719
+ }
1720
+ const common = {
1721
+ requestId: requiredGoalString(record5.requestId, "requestId", 128),
1722
+ expectedRevision: goalNonNegativeInteger(record5.expectedRevision, "expectedRevision")
1723
+ };
1724
+ if (record5.action === "budget") {
1725
+ assertGoalFields(record5, ["requestId", "expectedRevision", "action", "tokenBudget"]);
1726
+ return { ...common, action: "budget", tokenBudget: record5.tokenBudget === null ? null : goalPositiveTimestamp(record5.tokenBudget, "tokenBudget") };
1727
+ }
1728
+ assertGoalFields(record5, record5.action === "resume" ? ["requestId", "expectedRevision", "action", "additionalAutoTurns", "questionId", "response", "objectiveVersion"] : ["requestId", "expectedRevision", "action"]);
1729
+ if (record5.questionId !== void 0) goalPositiveTimestamp(record5.objectiveVersion, "objectiveVersion");
1730
+ else if (record5.objectiveVersion !== void 0) throw new DomainValidationError("goal_version_requires_answer", "objectiveVersion");
1731
+ return {
1732
+ ...common,
1733
+ action: record5.action,
1734
+ ...record5.questionId === void 0 ? {} : { questionId: requiredGoalString(record5.questionId, "questionId", 256), objectiveVersion: goalPositiveTimestamp(record5.objectiveVersion, "objectiveVersion") },
1735
+ ...record5.response === void 0 ? {} : { response: requiredGoalString(record5.response, "response", MAX_GOAL_OBJECTIVE_CHARS) },
1736
+ ...record5.additionalAutoTurns === void 0 ? {} : { additionalAutoTurns: goalPositiveInteger(record5.additionalAutoTurns, "additionalAutoTurns") }
1737
+ };
1738
+ }
1739
+ function assertGoalFields(record5, fields3) {
1740
+ for (const field of Object.keys(record5)) if (!fields3.includes(field)) throw new DomainValidationError(`invalid_goal_${field}`, field);
1741
+ }
1742
+ function goalRecord(value) {
1743
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new DomainValidationError("invalid_goal_input", "goal");
1744
+ return value;
1745
+ }
1746
+ function requiredGoalString(value, field, max) {
1747
+ if (typeof value !== "string" || !value.trim() || /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/.test(value)) throw new DomainValidationError(`invalid_goal_${field}`, field);
1748
+ const normalized = value.trim();
1749
+ if (normalized.length > max) throw new DomainValidationError(`goal_${field}_limit_exceeded`, field);
1750
+ return normalized;
1751
+ }
1752
+ function goalNonNegativeInteger(value, field) {
1753
+ if (!Number.isSafeInteger(value) || value < 0) throw new DomainValidationError(`invalid_goal_${field}`, field);
1754
+ return value;
1755
+ }
1756
+ function goalPositiveInteger(value, field, allowUnlimited = false) {
1757
+ const integer = goalNonNegativeInteger(value, field);
1758
+ if (integer < (allowUnlimited ? 0 : 1) || integer > MAX_GOAL_AUTO_TURNS) throw new DomainValidationError(`invalid_goal_${field}`, field);
1759
+ return integer;
1760
+ }
1761
+ function parseGoalContent(record5) {
1762
+ return {
1763
+ ...record5.items === void 0 ? {} : { items: parseSessionInputItems(record5.items) },
1764
+ ...record5.attachments === void 0 ? {} : { attachments: parsePromptAttachments(record5.attachments) }
1765
+ };
1766
+ }
1767
+ function goalPositiveTimestamp(value, field) {
1768
+ if (!Number.isSafeInteger(value) || value <= 0) throw new DomainValidationError(`invalid_goal_${field}`, field);
1769
+ return value;
1770
+ }
1771
+
1772
+ // ../protocol/src/session/session-goals.ts
1773
+ function parseCreateSessionGoalInput2(value) {
1774
+ return adaptDomainValidation(() => parseCreateSessionGoalInput(value));
1775
+ }
1776
+ function parseUpdateSessionGoalInput2(value) {
1777
+ return adaptDomainValidation(() => parseUpdateSessionGoalInput(value));
1778
+ }
1779
+ function parseGoalActionInput2(value) {
1780
+ return adaptDomainValidation(() => parseGoalActionInput(value));
1781
+ }
1782
+ function decodeSessionGoalRequestReceipt(value) {
1783
+ const fail = () => {
1784
+ throw new ProtocolDataError("Invalid Goal request receipt");
1785
+ };
1786
+ const object4 = (item, allowed) => {
1787
+ if (!item || typeof item !== "object" || Array.isArray(item) || Object.keys(item).some((key) => !allowed.includes(key))) return fail();
1788
+ return item;
1789
+ };
1790
+ const strings = (item, required, optional = []) => {
1791
+ for (const key of required) if (typeof item[key] !== "string" || !item[key]) fail();
1792
+ for (const key of optional) if (item[key] !== void 0 && typeof item[key] !== "string") fail();
1793
+ };
1794
+ const numbers = (item, required, optional = []) => {
1795
+ for (const key of required) if (!Number.isSafeInteger(item[key]) || item[key] < 0) fail();
1796
+ for (const key of optional) if (item[key] !== void 0 && (!Number.isSafeInteger(item[key]) || item[key] < 0)) fail();
1797
+ };
1798
+ const envelope = object4(value, ["request"]), receipt2 = object4(envelope.request, ["requestId", "sessionId", "fingerprint", "status", "goalId", "result", "error", "createdAt", "updatedAt"]);
1799
+ strings(receipt2, ["requestId", "sessionId", "fingerprint"], ["goalId", "error"]);
1800
+ numbers(receipt2, ["createdAt", "updatedAt"]);
1801
+ if (!["pending", "completed", "failed"].includes(String(receipt2.status))) fail();
1802
+ if (receipt2.result !== void 0) {
1803
+ const result = object4(receipt2.result, ["goal", "runId", "inputId", "phase"]);
1804
+ strings(result, [], ["runId", "inputId", "phase"]);
1805
+ if (result.goal !== void 0) {
1806
+ const goal = object4(result.goal, ["id", "sessionId", "objective", "objectiveVersion", "pluginId", "revision", "status", "maxAutoTurns", "tokenBudget", "usage", "autoTurnsUsed", "currentRunId", "queuedResume", "reason", "stopReason", "wait", "createdAt", "updatedAt"]);
1807
+ strings(goal, ["id", "sessionId", "objective"], ["pluginId", "currentRunId", "reason"]);
1808
+ numbers(goal, ["objectiveVersion", "revision", "maxAutoTurns", "autoTurnsUsed", "createdAt", "updatedAt"], ["tokenBudget"]);
1809
+ if (goal.sessionId !== receipt2.sessionId || receipt2.goalId !== void 0 && goal.id !== receipt2.goalId || !["active", "waiting_user", "blocked", "paused", "completed", "cancelled"].includes(String(goal.status))) fail();
1810
+ const usage = object4(goal.usage, ["knownTokens", "incomplete", "unknownAttempts", "partialAttempts", "inFlightAttempts", "runTimeMs", "seq", "updatedAt"]);
1811
+ numbers(usage, ["knownTokens", "unknownAttempts", "partialAttempts", "inFlightAttempts", "runTimeMs", "seq", "updatedAt"]);
1812
+ if (typeof usage.incomplete !== "boolean") fail();
1813
+ if (goal.queuedResume !== void 0) strings(object4(goal.queuedResume, ["requestId"]), ["requestId"]);
1814
+ if (goal.stopReason !== void 0) {
1815
+ const stop = object4(goal.stopReason, ["code", "at", "runId", "detail"]);
1816
+ strings(stop, ["code"], ["runId", "detail"]);
1817
+ numbers(stop, ["at"]);
1818
+ }
1819
+ if (goal.wait !== void 0) {
1820
+ const wait = goal.wait;
1821
+ if (wait?.kind === "user") {
1822
+ const item = object4(wait, ["kind", "questionId", "question", "objectiveVersion", "replyInputId", "response"]);
1823
+ strings(item, ["questionId", "question"], ["replyInputId", "response"]);
1824
+ numbers(item, ["objectiveVersion"]);
1825
+ } else if (wait?.kind === "approval") strings(object4(wait, ["kind", "permissionRequestId"]), ["permissionRequestId"]);
1826
+ else if (wait?.kind === "external") {
1827
+ const item = object4(wait, ["kind", "targetRunId", "ownerRunId", "goalId", "objectiveVersion", "deadlineAt", "observedStatus"]);
1828
+ strings(item, ["targetRunId", "ownerRunId", "goalId"], ["observedStatus"]);
1829
+ numbers(item, ["objectiveVersion", "deadlineAt"]);
1830
+ } else fail();
1831
+ }
1832
+ }
1833
+ }
1834
+ return receipt2;
1835
+ }
1836
+
1837
+ // ../protocol/src/runtime/execution-observability.ts
1838
+ var EXECUTION_KINDS = [
1839
+ "root_agent_run",
1840
+ "child_agent_run",
1841
+ "workflow_run",
1842
+ "workflow_task"
1843
+ ];
1844
+ var EXECUTION_OUTCOMES = [
1845
+ "completed",
1846
+ "failed",
1847
+ "timed_out",
1848
+ "cancelled",
1849
+ "blocked",
1850
+ "skipped",
1851
+ "running",
1852
+ "pending",
1853
+ "unknown"
1854
+ ];
1855
+ var EXECUTION_FAILURE_KINDS = [
1856
+ "model_error",
1857
+ "tool_error",
1858
+ "timeout",
1859
+ "permission_denied",
1860
+ "budget_exceeded",
1861
+ "dependency_failed",
1862
+ "cancelled_by_user",
1863
+ "cancelled_by_parent",
1864
+ "recovery_failed",
1865
+ "conflict",
1866
+ "unknown"
1867
+ ];
1868
+ var EXECUTION_KIND_SET = new Set(EXECUTION_KINDS);
1869
+ var EXECUTION_OUTCOME_SET = new Set(EXECUTION_OUTCOMES);
1870
+ var EXECUTION_FAILURE_KIND_SET = new Set(EXECUTION_FAILURE_KINDS);
1871
+ var AUTO_REVIEW_STATUS_SET2 = new Set(AUTO_REVIEW_STATUSES);
1872
+ var AUTO_REVIEW_RISK_LEVEL_SET2 = new Set(AUTO_REVIEW_RISK_LEVELS);
1873
+
1874
+ // ../domain-contracts/src/workspace-changes/records.ts
1875
+ var WORKSPACE_CHANGE_MAX_FILES = 128;
1876
+ var WORKSPACE_CHANGE_MAX_PATH_LENGTH = 1024;
1877
+ var WORKSPACE_CHANGE_REASONS = [
1878
+ "not_git_repository",
1879
+ "preexisting_dirty_overlap",
1880
+ "non_linear_head_change",
1881
+ "post_commit_worktree_changed",
1882
+ "git_inspection_failed",
1883
+ "sensitive_content_path",
1884
+ "concurrent_run_overlap",
1885
+ "execution_environment_unavailable",
1886
+ "daemon_restarted",
1887
+ "observation_budget_exceeded",
1888
+ "observation_cancelled"
1889
+ ];
1890
+ function readWorkspaceChangesMetadata(value) {
1891
+ if (!record4(value) || value.version !== 1 || typeof value.status !== "string" || !["captured", "complete", "unavailable"].includes(value.status)) return void 0;
1892
+ if (!Array.isArray(value.files) || value.files.length > WORKSPACE_CHANGE_MAX_FILES || !count2(value.fileCount) || !count2(value.totalLines) || typeof value.truncated !== "boolean") return void 0;
1893
+ if (value.reason !== void 0 && !WORKSPACE_CHANGE_REASONS.includes(value.reason)) return void 0;
1894
+ if (value.repositoryRoot !== void 0 && !rootPath(value.repositoryRoot)) return void 0;
1895
+ if (value.status === "unavailable" && value.reason === void 0) return void 0;
1896
+ if (value.status !== "unavailable" && (value.reason !== void 0 || value.repositoryRoot === void 0)) return void 0;
1897
+ const files = [];
1898
+ const paths = /* @__PURE__ */ new Set();
1899
+ for (const file of value.files) {
1900
+ if (!record4(file) || !relativePath(file.path) || paths.has(file.path) || file.oldPath !== void 0 && !relativePath(file.oldPath) || !count2(file.lines) || typeof file.status !== "string" || !["added", "modified", "deleted", "renamed", "copied", "unknown"].includes(file.status)) return void 0;
1901
+ if (!lineSplit(file)) return void 0;
1902
+ paths.add(file.path);
1903
+ files.push({
1904
+ path: file.path,
1905
+ status: file.status,
1906
+ lines: file.lines,
1907
+ ...typeof file.oldPath === "string" ? { oldPath: file.oldPath } : {},
1908
+ ...typeof file.additions === "number" ? { additions: file.additions, deletions: file.deletions } : {}
1909
+ });
1910
+ }
1911
+ if (value.fileCount < files.length || !value.truncated && value.fileCount !== files.length || files.reduce((sum, file) => sum + file.lines, 0) > value.totalLines) return void 0;
1912
+ if (value.status !== "complete" && (files.length > 0 || value.fileCount !== 0 || value.totalLines !== 0 || value.truncated)) return void 0;
1913
+ return {
1914
+ version: 1,
1915
+ status: value.status,
1916
+ files,
1917
+ fileCount: value.fileCount,
1918
+ totalLines: value.totalLines,
1919
+ truncated: value.truncated,
1920
+ ...value.reason ? { reason: value.reason } : {},
1921
+ ...typeof value.repositoryRoot === "string" ? { repositoryRoot: value.repositoryRoot } : {}
1922
+ };
1923
+ }
1924
+ function record4(value) {
1925
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1926
+ }
1927
+ function count2(value) {
1928
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1929
+ }
1930
+ function lineSplit(file) {
1931
+ if (file.additions === void 0 && file.deletions === void 0) return true;
1932
+ return count2(file.additions) && count2(file.deletions) && file.additions + file.deletions === file.lines;
1933
+ }
1934
+ function textPath(value) {
1935
+ return typeof value === "string" && value.length > 0 && value.length <= WORKSPACE_CHANGE_MAX_PATH_LENGTH && !/[\u0000-\u001f\u007f]/.test(value);
1936
+ }
1937
+ function rootPath(value) {
1938
+ return textPath(value) && /^(?:\/|[A-Za-z]:[\\/])/.test(value);
1939
+ }
1940
+ function relativePath(value) {
1941
+ return textPath(value) && !/^[\\/]|^[A-Za-z]:/.test(value) && !value.replace(/\\/g, "/").split("/").some((part) => part === ".." || part === "." || part === "");
1942
+ }
1943
+
1944
+ // ../domain-contracts/src/files/validation.ts
1945
+ function isSessionFileDataObject(value) {
1946
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1947
+ const prototype = Object.getPrototypeOf(value);
1948
+ return prototype === Object.prototype || prototype === null;
1949
+ }
1950
+ function isSessionFileRelativePath(value) {
1951
+ return value.length > 0 && value.length <= 4096 && !value.startsWith("/") && !/^[a-zA-Z]:\//.test(value) && !value.includes("\\") && !value.includes("\0") && !value.split("/").includes("..");
1952
+ }
1953
+
1954
+ // ../protocol/src/files/session-files.ts
1955
+ function responseObject(value) {
1956
+ if (!isSessionFileDataObject(value)) throw new ProtocolDataError("File response must be an object");
1957
+ return value;
1958
+ }
1959
+ function responseString(value, field) {
1960
+ if (typeof value !== "string") throw new ProtocolDataError(`File response ${field} must be a string`, field);
1961
+ return value;
1962
+ }
1963
+ function responsePath(value) {
1964
+ const path2 = responseString(value, "path");
1965
+ if (!isSessionFileRelativePath(path2)) throw new ProtocolDataError("File response path must be relative to the workspace", "path");
1966
+ return path2;
1967
+ }
1968
+ function responseTruncated(value) {
1969
+ if (typeof value !== "boolean") throw new ProtocolDataError("File response truncated must be a boolean", "truncated");
1970
+ return value;
1971
+ }
1972
+ function responseArray(value, field, decode) {
1973
+ if (!Array.isArray(value)) throw new ProtocolDataError(`File response ${field} must be an array`, field);
1974
+ return value.map(decode);
1975
+ }
1976
+ function decodeSessionFileInfo(value) {
1977
+ const data = responseObject(value);
1978
+ const path2 = responsePath(data.path);
1979
+ const name = responseString(data.name, "name");
1980
+ if (!name || /[/\\\0]/.test(name)) throw new ProtocolDataError("File response name must be a filename", "name");
1981
+ const kind = data.kind;
1982
+ if (kind !== "file" && kind !== "directory" && kind !== "symlink" && kind !== "other") {
1983
+ throw new ProtocolDataError("File response kind is invalid", "kind");
1984
+ }
1985
+ const sizeBytes = data.sizeBytes;
1986
+ if (sizeBytes !== void 0 && (typeof sizeBytes !== "number" || !Number.isSafeInteger(sizeBytes) || sizeBytes < 0)) {
1987
+ throw new ProtocolDataError("File response sizeBytes must be a nonnegative integer", "sizeBytes");
1988
+ }
1989
+ const modifiedAt = data.modifiedAt;
1990
+ if (modifiedAt !== void 0 && (typeof modifiedAt !== "number" || !Number.isFinite(modifiedAt) || modifiedAt < 0)) {
1991
+ throw new ProtocolDataError("File response modifiedAt must be a nonnegative timestamp", "modifiedAt");
1992
+ }
1993
+ return { path: path2, name, kind, ...sizeBytes === void 0 ? {} : { sizeBytes }, ...modifiedAt === void 0 ? {} : { modifiedAt } };
1994
+ }
1995
+ function decodeSessionDirectoryResult(value) {
1996
+ const data = responseObject(value);
1997
+ return { path: responsePath(data.path), entries: responseArray(data.entries, "entries", decodeSessionFileInfo), truncated: responseTruncated(data.truncated) };
1998
+ }
1999
+ function decodeSessionTextFileResult(value) {
2000
+ const data = responseObject(value);
2001
+ if (data.encoding !== "utf-8") throw new ProtocolDataError("File response encoding must be utf-8", "encoding");
2002
+ return { path: responsePath(data.path), content: responseString(data.content, "content"), encoding: "utf-8", truncated: responseTruncated(data.truncated) };
2003
+ }
2004
+ function decodeSessionFindFilesResult(value) {
2005
+ const data = responseObject(value);
2006
+ return { path: responsePath(data.path), files: responseArray(data.files, "files", responsePath), truncated: responseTruncated(data.truncated) };
2007
+ }
2008
+ function decodeSearchMatch(value) {
2009
+ const data = responseObject(value);
2010
+ const line = data.line;
2011
+ if (typeof line !== "number" || !Number.isSafeInteger(line) || line < 1) throw new ProtocolDataError("File match line must be a positive integer", "line");
2012
+ return { path: responsePath(data.path), line, text: responseString(data.text, "text") };
2013
+ }
2014
+ function decodeSessionSearchFilesResult(value) {
2015
+ const data = responseObject(value);
2016
+ return { path: responsePath(data.path), matches: responseArray(data.matches, "matches", decodeSearchMatch), truncated: responseTruncated(data.truncated) };
2017
+ }
2018
+
2019
+ // ../agent-contracts/src/tools/tool-data.ts
2020
+ var MCP_CALL_RESULT_MAX_BYTES = 1024 * 1024;
2021
+ var McpResultDataError = class extends Error {
2022
+ constructor(message) {
2023
+ super(message);
2024
+ this.name = "McpResultDataError";
2025
+ }
2026
+ };
2027
+ function object2(value) {
2028
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2029
+ }
2030
+ function parseMcpCallResultData(value) {
2031
+ const ancestors = /* @__PURE__ */ new Set();
2032
+ let nodes = 0;
2033
+ let stringBytes = 0;
2034
+ const encoder = new TextEncoder();
2035
+ const visit = (item, depth) => {
2036
+ if (++nodes > 1e5 || depth > 32) throw new McpResultDataError("MCP result exceeds JSON complexity limit");
2037
+ if (item === null || typeof item === "boolean") return item;
2038
+ if (typeof item === "number" && Number.isFinite(item)) return item;
2039
+ if (typeof item === "string") {
2040
+ stringBytes += encoder.encode(item).byteLength;
2041
+ if (stringBytes > MCP_CALL_RESULT_MAX_BYTES) throw new McpResultDataError("MCP result exceeds 1 MiB limit");
2042
+ return item;
2043
+ }
2044
+ if (!item || typeof item !== "object" || ancestors.has(item)) throw new McpResultDataError("MCP result must contain finite JSON data");
2045
+ const prototype = Object.getPrototypeOf(item);
2046
+ if (Array.isArray(item) ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {
2047
+ throw new McpResultDataError("MCP result must contain plain JSON data");
2048
+ }
2049
+ ancestors.add(item);
2050
+ const entries = [];
2051
+ for (const key of Reflect.ownKeys(item)) {
2052
+ if (Array.isArray(item) && key === "length") continue;
2053
+ const descriptor = Object.getOwnPropertyDescriptor(item, key);
2054
+ if (typeof key !== "string" || !descriptor.enumerable || !("value" in descriptor)) throw new McpResultDataError("MCP result must contain plain JSON data");
2055
+ if (Array.isArray(item) && !/^(0|[1-9][0-9]*)$/.test(key)) throw new McpResultDataError("MCP result must contain plain JSON arrays");
2056
+ stringBytes += encoder.encode(key).byteLength;
2057
+ if (stringBytes > MCP_CALL_RESULT_MAX_BYTES) throw new McpResultDataError("MCP result exceeds 1 MiB limit");
2058
+ entries.push([key, visit(descriptor.value, depth + 1)]);
2059
+ }
2060
+ ancestors.delete(item);
2061
+ if (Array.isArray(item)) {
2062
+ if (entries.length !== item.length) throw new McpResultDataError("MCP result must not contain sparse arrays");
2063
+ return entries.map(([, entry]) => entry);
2064
+ }
2065
+ return Object.fromEntries(entries);
2066
+ };
2067
+ const copied = visit(value, 0);
2068
+ if (!object2(copied) || !Array.isArray(copied.content) || !copied.content.every((block) => object2(block) && typeof block.type === "string" && (block.type !== "text" || typeof block.text === "string")) || copied.structuredContent !== void 0 && !object2(copied.structuredContent) || copied._meta !== void 0 && !object2(copied._meta) || copied.isError !== void 0 && typeof copied.isError !== "boolean") {
2069
+ throw new McpResultDataError("Invalid MCP call result shape");
2070
+ }
2071
+ if (encoder.encode(JSON.stringify(copied)).byteLength > MCP_CALL_RESULT_MAX_BYTES) throw new McpResultDataError("MCP result exceeds 1 MiB limit");
2072
+ return copied;
2073
+ }
2074
+
2075
+ // ../domain-contracts/src/app-host/app-types.ts
2076
+ 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;
2077
+
2078
+ // ../domain-contracts/src/app-host/wire-validation.ts
2079
+ var text2 = (max = 1024, empty = false) => (v) => typeof v === "string" && (empty || v.length > 0) && new TextEncoder().encode(v).byteLength <= max;
2080
+ var id = (v) => typeof v === "string" && HOST_REQUEST_ID.test(v);
2081
+ var count3 = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
2082
+ var bool = (v) => typeof v === "boolean";
2083
+ var enumeration = (...values) => (v) => values.includes(v);
2084
+ var nullable = (check) => (v) => v === null || check(v);
2085
+ function object3(required, optional = {}) {
2086
+ return (v) => {
2087
+ if (!v || typeof v !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
2088
+ if (Object.keys(required).some((k) => !Object.hasOwn(v, k))) return false;
2089
+ return Reflect.ownKeys(v).every((k) => {
2090
+ const d = Object.getOwnPropertyDescriptor(v, k);
2091
+ return typeof k === "string" && d.enumerable && Object.hasOwn(d, "value") && (required[k] ?? optional[k])?.(d.value) === true;
2092
+ });
2093
+ };
2094
+ }
2095
+ function array(check, max = 1024) {
2096
+ return (v) => {
2097
+ if (!Array.isArray(v) || Object.getPrototypeOf(v) !== Array.prototype || v.length > max || Reflect.ownKeys(v).length !== v.length + 1) return false;
2098
+ for (let i = 0; i < v.length; i++) {
2099
+ const d = Object.getOwnPropertyDescriptor(v, String(i));
2100
+ if (!d?.enumerable || !Object.hasOwn(d, "value") || !check(d.value)) return false;
2101
+ }
2102
+ return true;
2103
+ };
2104
+ }
2105
+ var json = (value) => {
2106
+ let size = 0;
2107
+ const seen = /* @__PURE__ */ new Set();
2108
+ const visit = (v, depth) => {
2109
+ if (depth > 64 || size > 12 * 1024 * 1024) return false;
2110
+ if (v === null || typeof v === "boolean") {
2111
+ size += 5;
2112
+ return true;
2113
+ }
2114
+ if (typeof v === "string") {
2115
+ size += new TextEncoder().encode(v).byteLength + 2;
2116
+ return size <= 12 * 1024 * 1024;
2117
+ }
2118
+ if (typeof v === "number") {
2119
+ size += 32;
2120
+ return Number.isFinite(v);
2121
+ }
2122
+ if (!v || typeof v !== "object" || seen.has(v)) return false;
2123
+ const list = Array.isArray(v);
2124
+ if (list ? Object.getPrototypeOf(v) !== Array.prototype : ![Object.prototype, null].includes(Object.getPrototypeOf(v))) return false;
2125
+ seen.add(v);
2126
+ try {
2127
+ const keys = Reflect.ownKeys(v);
2128
+ if (list && keys.length !== v.length + 1) return false;
2129
+ return keys.every((k) => {
2130
+ if (list && k === "length") return true;
2131
+ const d = Object.getOwnPropertyDescriptor(v, k);
2132
+ size += typeof k === "string" ? k.length + 3 : 0;
2133
+ 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);
2134
+ });
2135
+ } finally {
2136
+ seen.delete(v);
2137
+ }
2138
+ };
2139
+ return visit(value, 0) && size <= 12 * 1024 * 1024;
2140
+ };
2141
+ var jsonObject = (v) => !!v && typeof v === "object" && !Array.isArray(v) && json(v);
2142
+ var wireConnection = object3({ connectionId: text2(256), baseUrl: text2(2048) });
2143
+
2144
+ // ../domain-contracts/src/app-host/workspace-conversations.ts
2145
+ var validWorkspaceConversation = (value) => {
2146
+ if (!object3(
2147
+ { dataScopeId: text2(), requestId: id, sessionId: id, taskLocation: enumeration("current", "worktree"), configuration: json },
2148
+ { workspaceId: id, outsideProject: (v) => v === true, preparationRevision: text2() }
2149
+ )(value)) return false;
2150
+ const input = value;
2151
+ return input.workspaceId !== void 0 ? input.outsideProject !== true : input.outsideProject === true && input.taskLocation === "current";
2152
+ };
2153
+ var sessionText = (value) => typeof value === "string";
2154
+ var sessionRecord = object3({
2155
+ id,
2156
+ cwd: sessionText,
2157
+ title: sessionText,
2158
+ model: sessionText,
2159
+ status: enumeration("idle", "running", "closing", "archived", "error"),
2160
+ metadata: jsonObject,
2161
+ createdAt: count3,
2162
+ updatedAt: count3
2163
+ }, {
2164
+ storage: enumeration("sqlite", "memory"),
2165
+ parentId: sessionText,
2166
+ projectId: sessionText,
2167
+ cwdRelative: sessionText,
2168
+ agent: sessionText,
2169
+ archivedAt: count3
2170
+ });
2171
+ var workspaceConversationResult = object3({
2172
+ dataScopeId: text2(),
2173
+ sessionId: id,
2174
+ requestId: id,
2175
+ action: (v) => v === "create-session",
2176
+ state: enumeration("prepared", "completed", "unknown")
2177
+ }, {
2178
+ configuration: json,
2179
+ revision: count3,
2180
+ session: sessionRecord,
2181
+ operationState: enumeration("prepared", "running", "completed", "failed", "unknown"),
2182
+ indexBindingPending: (v) => v === true,
2183
+ workspaceId: id,
2184
+ executionRoot: id,
2185
+ privateSessionId: id,
2186
+ worktree: json
2187
+ });
2188
+ var validWorkspaceConversationResult = (value) => {
2189
+ if (!workspaceConversationResult(value)) return false;
2190
+ const result = value;
2191
+ return !result.session || result.state === "completed" && result.session.id === result.sessionId;
2192
+ };
2193
+
2194
+ // ../domain-contracts/src/app-host/session-controls.ts
2195
+ var option = object3({ id: text2(), name: text2() });
2196
+ var choices = array(option);
2197
+ var effortChoices = array(object3({ id: text2(1024, true), name: text2() }));
2198
+ var receiptShape = object3({ dataScopeId: text2(), sessionId: text2(), requestId: id, action: enumeration("fork", "configure", "compact"), state: enumeration("prepared", "created", "completed", "unknown") }, { revision: count3, targetSessionId: text2() });
2199
+ var receipt = receiptShape;
2200
+ function validSessionControlOriginal(value) {
2201
+ if (!object3({ action: text2(), body: json })(value)) return false;
2202
+ const v = value;
2203
+ if (v.action === "compact") return object3({ requestId: id, expectedRevision: count3 })(v.body);
2204
+ return v.action === "fork" && object3({ requestId: id, id: text2() }, { copyHistory: bool, beforeMessageId: text2(), afterMessageId: text2(), storage: enumeration("sqlite") })(v.body);
2205
+ }
2206
+ function validSessionControlInput(method, value) {
2207
+ if (!json(value)) return false;
2208
+ if (method === "sessions.getDraftComposerOptions") {
2209
+ if (!object3({ source: enumeration("instance") }, { workspaceId: id, outsideProject: bool, roleId: (v2) => v2 === null || text2(256)(v2) })(value)) return false;
2210
+ const target = value;
2211
+ return target.workspaceId !== void 0 ? target.outsideProject !== true : target.outsideProject === true;
2212
+ }
2213
+ if (method === "sessions.bindConversationIndex") return object3({ original: validWorkspaceConversation, dataScopeId: text2() })(value);
2214
+ if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult") return validWorkspaceConversation(value);
2215
+ if (method === "sessions.getControls") return object3({ connectionId: text2(), sessionId: text2() })(value);
2216
+ if (!object3({ requestId: id, sessionId: text2(), original: validSessionControlOriginal }, { connectionId: text2() })(value)) return false;
2217
+ const v = value;
2218
+ return v.original.body.requestId === v.requestId && !!v.connectionId;
2219
+ }
2220
+ function validSessionControlResult(method, value) {
2221
+ if (!json(value)) return false;
2222
+ if (method === "sessions.getDraftComposerOptions") return object3({ source: enumeration("instance"), optionsRevision: text2(), skills: array(object3({ id: text2(), name: text2(), path: text2(4096, true) }, { source: enumeration("bundled", "user", "project", "plugin") }), 128), plugins: array(object3({ id: text2(), name: text2(), agents: array(option, 128) }), 128) })(value);
2223
+ if (method === "sessions.bindConversationIndex") return validWorkspaceConversationResult(value);
2224
+ if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult")
2225
+ return method === "sessions.getConversationCreationResult" && value === null || validWorkspaceConversationResult(value);
2226
+ if (method === "sessions.getControls") return object3({ dataScopeId: text2(), sessionId: text2(), source: enumeration("instance", "auxiliary", "im"), revision: count3, optionsRevision: text2(), actions: object3(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(object3({ id: text2(), name: text2(), path: text2(4096, true) }, { source: enumeration("bundled", "user", "project", "plugin") })), commands: choices, contexts: choices }, { permissionModes: array(option, 128), appServiceBindings: array(option, 128), plugins: array(object3({ id: text2(), name: text2(), agents: choices })) })(value);
2227
+ if (method === "sessions.getControlResult") return value === null || receipt(value);
2228
+ if (!receipt(value)) return false;
2229
+ return false;
2230
+ }
2231
+
2232
+ // ../domain-contracts/src/app-host/fetch.ts
2233
+ var FETCH_CHUNK_BYTES = 64 * 1024;
2234
+ var FETCH_INLINE_BODY_BYTES = 8 * 1024;
2235
+ var FETCH_METADATA_BYTES = 64 * 1024;
2236
+
2237
+ // ../domain-contracts/src/app-host/service-host-protocol.ts
2238
+ var SERVICE_HOST_MAX_FRAME_BYTES = 512 * 1024;
2239
+ var worktreeBody = { workspaceId: id, expectedHead: text2(256), branch: text2(1024) };
2240
+ var worktreeReceipt = object3({ requestId: id, state: enumeration("accepted", "completed", "failed", "unknown") }, { result: object3({ executionRoot: id, workspaceId: id, branch: text2(1024), sourceHead: text2(256) }) });
2241
+
2242
+ // ../domain-contracts/src/app-host/model-providers.ts
2243
+ var provider = text2(256);
2244
+ var imageInputSupport = enumeration("native", "unsupported", "unknown");
2245
+ var limits = { contextWindow: count3, maxOutputTokens: count3 };
2246
+ function headerValues(check) {
2247
+ return (value) => {
2248
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2249
+ const keys = Object.keys(value);
2250
+ return keys.length <= 128 && keys.every((key) => /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,256}$/.test(key)) && object3(Object.fromEntries(keys.map((key) => [key, check])))(value);
2251
+ };
2252
+ }
2253
+ var headers = headerValues(text2(8192, true));
2254
+ var secretHeaders = headerValues(nullable(text2(8192)));
2255
+ var customProvider = object3({
2256
+ id: provider,
2257
+ displayName: text2(1024),
2258
+ baseUrl: text2(4096),
2259
+ apiFormat: enumeration("openai"),
2260
+ models: array(object3({ id: text2(1024), displayName: text2(1024) }, { imageInputSupport, ...limits }), 16384)
2261
+ }, { apiKey: text2(8192), headers, secretHeaders });
2262
+ var validModel = object3({ id: text2(1024), label: text2(1024) }, { imageInputSupport, declaredLimits: object3({}, limits) });
2263
+ var validConnection = object3({
2264
+ name: provider,
2265
+ displayName: text2(1024),
2266
+ connected: bool,
2267
+ active: bool,
2268
+ credentialSource: enumeration("credentials", "environment", "subscription", "local", "configured", "none"),
2269
+ models: array(validModel, 16384)
2270
+ }, { source: enumeration("builtin", "catalog", "custom", "subscription"), custom: bool, credentialLabel: text2(1024), baseUrl: text2(4096), headers, secretHeaderNames: array(text2(256), 128) });
2271
+ function validModelProviderConnections(value) {
2272
+ return array(validConnection, 4096)(value);
2273
+ }
2274
+ var modelId = text2(1024);
2275
+ var effort = nullable(text2(256));
2276
+ var revision = text2(8192);
2277
+ var verifiedProvider = object3({ model: modelId, checkedAt: count3 });
2278
+ var verified = (value) => {
2279
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2280
+ const keys = Object.keys(value);
2281
+ return keys.length <= 4096 && keys.every(provider) && object3(Object.fromEntries(keys.map((key) => [key, verifiedProvider])))(value);
2282
+ };
2283
+ var defaultsModel = object3({ id: modelId, label: text2(1024), provider: text2(1024), providerName: provider }, {
2284
+ reasoningEfforts: array(text2(256, true)),
2285
+ contextWindow: count3,
2286
+ inputModalities: array(text2(256)),
2287
+ inputCapabilities: object3({ image: imageInputSupport })
2288
+ });
2289
+ var validProviderDefaultsSnapshot = object3({
2290
+ models: array(defaultsModel, 16384),
2291
+ provider: nullable(provider),
2292
+ model: nullable(modelId),
2293
+ effort,
2294
+ disabled: bool,
2295
+ revision,
2296
+ verified,
2297
+ fastModeAvailable: enumeration(false),
2298
+ fastModeReason: text2(1024)
2299
+ });
2300
+ var validProviderConnectionTestResult = object3({
2301
+ status: enumeration("verified", "failed"),
2302
+ detail: text2(8192),
2303
+ checkedAt: count3
2304
+ }, { category: enumeration("authentication", "address", "network", "model", "unsupported", "service") });
2305
+
2306
+ // src/protocol/protocol-client.ts
2307
+ var IncompatibleProtocolError = class extends Error {
2308
+ constructor(capabilities, message) {
2309
+ super(message);
2310
+ this.capabilities = capabilities;
2311
+ this.name = "IncompatibleProtocolError";
2312
+ }
2313
+ capabilities;
2314
+ };
2315
+ var ProtocolClient = class {
2316
+ constructor(transport) {
2317
+ this.transport = transport;
2318
+ }
2319
+ transport;
2320
+ /** `GET /health` */
2321
+ async health(options = {}) {
2322
+ return this.transport.request("/health", {
2323
+ auth: false,
2324
+ signal: options.signal
2325
+ });
2326
+ }
2327
+ /**
2328
+ * `GET /capabilities`
2329
+ * 连接产品应先调用它,再根据 features 决定显示哪些功能。
2330
+ */
2331
+ async capabilities(options = {}) {
2332
+ const value = await this.transport.request("/capabilities", {
2333
+ auth: options.authenticated === true,
2334
+ ...options.scope === "protocol" ? { headers: { "x-bobannomi-capability-scope": "protocol" } } : {},
2335
+ signal: options.signal
2336
+ });
2337
+ const capabilities = parseServerCapabilities(value);
2338
+ const compatibility = checkProtocolCompatibility(
2339
+ capabilities,
2340
+ options.support ?? { version: CURRENT_PROTOCOL_VERSION }
2341
+ );
2342
+ if (!compatibility.compatible) {
2343
+ throw new IncompatibleProtocolError(
2344
+ capabilities,
2345
+ compatibility.reason ?? "Client and server protocol versions are incompatible"
2346
+ );
2347
+ }
2348
+ if (options.authenticated === true && options.support === void 0) {
2349
+ this.transport.rememberProtocol(capabilities);
2350
+ }
2351
+ return capabilities;
2352
+ }
2353
+ };
2354
+
2355
+ // src/transport/http-transport.ts
2356
+ var BobanNomiApiError = class extends Error {
2357
+ constructor(message, status, body) {
2358
+ super(message);
2359
+ this.status = status;
2360
+ this.body = body;
2361
+ this.name = "BobanNomiApiError";
2362
+ }
2363
+ status;
2364
+ body;
2365
+ };
2366
+ function responseField(value, field) {
2367
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2368
+ throw new ProtocolDataError("Response body must be an object");
2369
+ }
2370
+ if (!(field in value)) {
2371
+ throw new ProtocolDataError(`Response body is missing ${field}`, field);
2372
+ }
2373
+ return value[field];
2374
+ }
2375
+ function responseArray2(value, field, decode) {
2376
+ const items = responseField(value, field);
2377
+ if (!Array.isArray(items)) {
2378
+ throw new ProtocolDataError(`Response ${field} must be an array`, field);
2379
+ }
2380
+ return items.map(decode);
2381
+ }
2382
+ function normalizeDaemonBaseUrl(value) {
2383
+ const raw = value.trim();
2384
+ if (!raw) throw new Error("Daemon URL is required");
2385
+ let url;
2386
+ try {
2387
+ url = new URL(raw);
2388
+ } catch {
2389
+ throw new Error("Daemon URL must be an absolute http or https URL");
2390
+ }
2391
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
2392
+ throw new Error("Daemon URL must use http or https");
2393
+ }
2394
+ if (url.username || url.password) {
2395
+ throw new Error(
2396
+ "Daemon URL must not contain credentials; use a bearer token instead"
2397
+ );
2398
+ }
2399
+ if (url.search || url.hash) {
2400
+ throw new Error(
2401
+ "Daemon URL must not contain query parameters or a fragment"
2402
+ );
2403
+ }
2404
+ const pathname = url.pathname.replace(/\/+$/, "");
2405
+ return `${url.origin}${pathname === "/" ? "" : pathname}`;
2406
+ }
2407
+ function isReadableStream(value) {
2408
+ return typeof ReadableStream !== "undefined" && value instanceof ReadableStream;
2409
+ }
2410
+ function attachmentRangeHeader(range) {
2411
+ if (!range) return void 0;
2412
+ const { start, end, suffixBytes } = range;
2413
+ if (suffixBytes !== void 0) {
2414
+ if (start !== void 0 || end !== void 0) {
2415
+ throw new Error("suffixBytes cannot be combined with start or end");
2416
+ }
2417
+ assertPositiveSafeInteger(suffixBytes, "suffixBytes");
2418
+ return `bytes=-${suffixBytes}`;
2419
+ }
2420
+ if (start === void 0 && end === void 0) return void 0;
2421
+ if (start === void 0) {
2422
+ throw new Error("range start is required when end is provided");
2423
+ }
2424
+ assertNonNegativeSafeInteger(start, "start");
2425
+ if (end === void 0) return `bytes=${start}-`;
2426
+ assertNonNegativeSafeInteger(end, "end");
2427
+ if (end < start) throw new Error("range end must not be less than start");
2428
+ return `bytes=${start}-${end}`;
2429
+ }
2430
+ function assertNonNegativeSafeInteger(value, field) {
2431
+ if (!Number.isSafeInteger(value) || value < 0) {
2432
+ throw new Error(`${field} must be a non-negative safe integer`);
2433
+ }
2434
+ }
2435
+ function assertPositiveSafeInteger(value, field) {
2436
+ if (!Number.isSafeInteger(value) || value < 1) {
2437
+ throw new Error(`${field} must be a positive safe integer`);
2438
+ }
2439
+ }
2440
+ async function throwResponseError(response) {
2441
+ let body;
2442
+ try {
2443
+ body = await response.json();
2444
+ } catch {
2445
+ body = await response.text().catch(() => "");
2446
+ }
2447
+ const message = body && typeof body === "object" && "error" in body && typeof body.error === "string" ? body.error : body && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : `BobanNomi API request failed with ${response.status}`;
2448
+ throw new BobanNomiApiError(message, response.status, body);
2449
+ }
2450
+ var HttpTransport = class {
2451
+ protocolHandshake;
2452
+ protocolVerified = false;
2453
+ baseUrl;
2454
+ token;
2455
+ fetchImpl;
2456
+ constructor(options) {
2457
+ this.baseUrl = normalizeDaemonBaseUrl(options.baseUrl);
2458
+ this.token = options.token;
2459
+ this.fetchImpl = options.fetch ?? fetch;
2460
+ }
2461
+ isHandshakeExempt(pathname) {
2462
+ const path2 = pathname.split("?")[0];
2463
+ return path2 === "/health" || path2 === "/capabilities";
2464
+ }
2465
+ rememberProtocol(capabilities) {
2466
+ if (this.protocolHandshake) return;
2467
+ this.protocolHandshake = Promise.resolve(structuredClone(capabilities));
2468
+ this.protocolVerified = true;
2469
+ }
2470
+ ensureProtocol(signal) {
2471
+ signal?.throwIfAborted();
2472
+ this.protocolHandshake ??= this.requestUnknown("/capabilities", {
2473
+ auth: false,
2474
+ headers: { "x-bobannomi-capability-scope": "protocol" }
2475
+ }).then((value) => {
2476
+ const capabilities = parseServerCapabilities(value);
2477
+ const result = checkProtocolCompatibility(capabilities, { version: CURRENT_PROTOCOL_VERSION });
2478
+ if (!result.compatible) {
2479
+ throw new IncompatibleProtocolError(capabilities, result.reason);
2480
+ }
2481
+ this.protocolVerified = true;
2482
+ return capabilities;
2483
+ }).catch((error) => {
2484
+ this.protocolHandshake = void 0;
2485
+ throw error;
2486
+ });
2487
+ if (!signal) return this.protocolHandshake;
2488
+ return new Promise((resolve, reject) => {
2489
+ const onAbort = () => reject(signal.reason);
2490
+ signal.addEventListener("abort", onAbort, { once: true });
2491
+ this.protocolHandshake.then(resolve, reject).finally(() => {
2492
+ signal.removeEventListener("abort", onAbort);
2493
+ });
2494
+ });
2495
+ }
2496
+ headers(jsonOrOptions = false, auth = true) {
2497
+ let json2 = false;
2498
+ let authHeader = auth;
2499
+ let extra;
2500
+ if (typeof jsonOrOptions === "object" && jsonOrOptions !== null) {
2501
+ json2 = jsonOrOptions.json ?? false;
2502
+ authHeader = jsonOrOptions.auth ?? true;
2503
+ extra = jsonOrOptions.extra;
2504
+ } else {
2505
+ json2 = Boolean(jsonOrOptions);
2506
+ authHeader = auth;
2507
+ }
2508
+ return {
2509
+ ...authHeader && this.token ? { authorization: `Bearer ${this.token}` } : {},
2510
+ ...json2 ? { "content-type": "application/json" } : {},
2511
+ ...extra ?? {}
2512
+ };
2513
+ }
2514
+ path(pathname, query = {}) {
2515
+ const params = new URLSearchParams();
2516
+ for (const [key, value] of Object.entries(query)) {
2517
+ if (value === void 0 || value === null || value === false) continue;
2518
+ params.set(key, String(value));
2519
+ }
2520
+ const qs = params.toString();
2521
+ return qs ? `${pathname}?${qs}` : pathname;
2522
+ }
2523
+ resolveUrl(pathname, query) {
2524
+ const resolvedPath = query ? this.path(pathname, query) : pathname;
2525
+ return `${this.baseUrl}${resolvedPath}`;
2526
+ }
2527
+ async request(path2, options = {}) {
2528
+ const business = !this.isHandshakeExempt(path2);
2529
+ if (business && !this.protocolVerified) await this.ensureProtocol(options.signal);
2530
+ options.signal?.throwIfAborted();
2531
+ const url = this.resolveUrl(path2, options.query);
2532
+ const hasJsonBody = options.body !== void 0;
2533
+ const headers2 = mergeHeaders(
2534
+ this.headers(hasJsonBody, options.auth ?? true),
2535
+ options.headers
2536
+ );
2537
+ if (business) headers2[PROTOCOL_VERSION_HEADER] = String(CURRENT_PROTOCOL_VERSION);
2538
+ const response = await this.fetchImpl(url, {
2539
+ method: options.method ?? "GET",
2540
+ headers: headers2,
2541
+ body: hasJsonBody ? JSON.stringify(options.body) : void 0,
2542
+ signal: options.signal
2543
+ });
2544
+ if (!response.ok) {
2545
+ await throwResponseError(response);
2546
+ }
2547
+ return await response.json();
2548
+ }
2549
+ async requestUnknown(path2, options = {}) {
2550
+ return this.request(path2, options);
2551
+ }
2552
+ async requestResponse(path2, options = {}) {
2553
+ const business = !this.isHandshakeExempt(path2);
2554
+ if (business) await this.ensureProtocol(options.signal ?? void 0);
2555
+ options.signal?.throwIfAborted();
2556
+ const url = this.resolveUrl(path2, options.query);
2557
+ const auth = options.auth ?? true;
2558
+ const headers2 = mergeHeaders(this.headers(false, auth), options.headers);
2559
+ if (business) headers2[PROTOCOL_VERSION_HEADER] = String(CURRENT_PROTOCOL_VERSION);
2560
+ const init = {
2561
+ ...options,
2562
+ headers: headers2
2563
+ };
2564
+ if (isReadableStream(init.body) && !init.duplex) {
2565
+ init.duplex = "half";
2566
+ }
2567
+ const response = await this.fetchImpl(url, init);
2568
+ if (!response.ok) {
2569
+ await throwResponseError(response);
2570
+ }
2571
+ return response;
2572
+ }
2573
+ async throwResponseError(response) {
2574
+ return throwResponseError(response);
2575
+ }
2576
+ };
2577
+ function mergeHeaders(defaults, overrides) {
2578
+ const headers2 = new Headers(defaults);
2579
+ if (overrides) {
2580
+ new Headers(overrides).forEach((value, key) => headers2.set(key, value));
2581
+ }
2582
+ return Object.fromEntries(headers2.entries());
2583
+ }
2584
+
2585
+ // src/transport/sse-transport.ts
2586
+ function parseRawSseFrame(frame) {
2587
+ let id2;
2588
+ let event;
2589
+ let retry;
2590
+ const dataLines = [];
2591
+ for (const line of frame.split(/\r?\n/)) {
2592
+ if (!line || line.startsWith(":")) continue;
2593
+ if (line.startsWith("data:")) {
2594
+ dataLines.push(line.startsWith("data: ") ? line.slice(6) : line.slice(5));
2595
+ } else if (line.startsWith("event:")) {
2596
+ event = (line.startsWith("event: ") ? line.slice(7) : line.slice(6)).trim();
2597
+ } else if (line.startsWith("id:")) {
2598
+ id2 = (line.startsWith("id: ") ? line.slice(4) : line.slice(3)).trim();
2599
+ } else if (line.startsWith("retry:")) {
2600
+ const value = (line.startsWith("retry: ") ? line.slice(7) : line.slice(6)).trim();
2601
+ const parsed = parseInt(value, 10);
2602
+ if (!Number.isNaN(parsed)) {
2603
+ retry = parsed;
2604
+ }
2605
+ }
2606
+ }
2607
+ if (dataLines.length === 0 && !id2 && !event && retry === void 0) {
2608
+ return void 0;
2609
+ }
2610
+ return {
2611
+ id: id2,
2612
+ event,
2613
+ retry,
2614
+ data: dataLines.length > 0 ? dataLines.join("\n") : void 0
2615
+ };
2616
+ }
2617
+ function parseSseFrame(frame) {
2618
+ let data = "";
2619
+ for (const line of frame.split(/\r?\n/)) {
2620
+ if (!line || line.startsWith(":")) continue;
2621
+ if (line.startsWith("data:")) {
2622
+ const slice = line.slice(5).trimStart();
2623
+ data = data ? `${data}
2624
+ ${slice}` : slice;
2625
+ }
2626
+ }
2627
+ if (!data) return void 0;
2628
+ return JSON.parse(data);
2629
+ }
2630
+ async function* streamServerSentEvents(open, decode = (value) => value) {
2631
+ const reader = (await open()).getReader();
2632
+ const decoder = new TextDecoder();
2633
+ let buffer = "";
2634
+ try {
2635
+ while (true) {
2636
+ const chunk = await reader.read();
2637
+ if (chunk.done) break;
2638
+ buffer += decoder.decode(chunk.value, { stream: true });
2639
+ const frames = buffer.split(/\r?\n\r?\n/);
2640
+ buffer = frames.pop() ?? "";
2641
+ for (const frame of frames) {
2642
+ const event = parseSseFrame(frame);
2643
+ if (event !== void 0) yield decode(event);
2644
+ }
2645
+ }
2646
+ } finally {
2647
+ try {
2648
+ await reader.cancel();
2649
+ } catch {
2650
+ } finally {
2651
+ reader.releaseLock();
2652
+ }
2653
+ }
2654
+ }
2655
+ var SseTransport = class {
2656
+ constructor(transport) {
2657
+ this.transport = transport;
2658
+ }
2659
+ transport;
2660
+ streamFromReader(open, decode = (val) => val) {
2661
+ return streamServerSentEvents(open, decode);
2662
+ }
2663
+ async *stream(url, options = {}) {
2664
+ let lastEventId = options.lastEventId;
2665
+ let reconnectDelayMs = options.reconnectDelayMs ?? 250;
2666
+ let connected = false;
2667
+ while (!options.signal?.aborted) {
2668
+ const connection = new AbortController();
2669
+ const onOuterAbort = () => connection.abort(options.signal?.reason);
2670
+ options.signal?.addEventListener("abort", onOuterAbort, { once: true });
2671
+ let idleTimer;
2672
+ let idleExpired = false;
2673
+ const resetIdleTimer = () => {
2674
+ if (!options.idleTimeoutMs || options.idleTimeoutMs <= 0) return;
2675
+ if (idleTimer) clearTimeout(idleTimer);
2676
+ idleTimer = setTimeout(() => {
2677
+ idleExpired = true;
2678
+ connection.abort("sse_idle_timeout");
2679
+ }, options.idleTimeoutMs);
2680
+ };
2681
+ try {
2682
+ const headers2 = new Headers(options.headers);
2683
+ if (lastEventId) headers2.set("Last-Event-ID", lastEventId);
2684
+ const requestUrl = connected && lastEventId ? withoutCursor(url) : url;
2685
+ const response = await this.transport.requestResponse(
2686
+ requestUrl.slice(this.transport.baseUrl.length),
2687
+ { headers: headers2, signal: connection.signal }
2688
+ );
2689
+ connected = true;
2690
+ if (!response.body) {
2691
+ throw new Error(
2692
+ options.noBodyMessage ?? "Event stream response has no body"
2693
+ );
2694
+ }
2695
+ options.onOpen?.();
2696
+ resetIdleTimer();
2697
+ try {
2698
+ for await (const frame of readRawSseFrames(
2699
+ response.body,
2700
+ resetIdleTimer
2701
+ )) {
2702
+ if (frame.retry !== void 0) reconnectDelayMs = frame.retry;
2703
+ if (frame.data !== void 0) {
2704
+ const value = (options.decode ?? ((value2) => value2))(
2705
+ JSON.parse(frame.data)
2706
+ );
2707
+ if (frame.id !== void 0) lastEventId = frame.id;
2708
+ yield value;
2709
+ }
2710
+ }
2711
+ } catch (error) {
2712
+ if (!idleExpired) throw error;
2713
+ }
2714
+ } finally {
2715
+ connection.abort();
2716
+ if (idleTimer) clearTimeout(idleTimer);
2717
+ options.signal?.removeEventListener("abort", onOuterAbort);
2718
+ }
2719
+ if (!options.reconnect || options.signal?.aborted) return;
2720
+ await waitForReconnect(reconnectDelayMs, options.signal);
2721
+ }
2722
+ }
2723
+ };
2724
+ async function* readRawSseFrames(stream, onFrame) {
2725
+ const reader = stream.getReader();
2726
+ const decoder = new TextDecoder();
2727
+ let buffer = "";
2728
+ try {
2729
+ while (true) {
2730
+ const chunk = await reader.read();
2731
+ if (chunk.done) break;
2732
+ buffer += decoder.decode(chunk.value, { stream: true });
2733
+ const frames = buffer.split(/\r?\n\r?\n/);
2734
+ buffer = frames.pop() ?? "";
2735
+ for (const value of frames) {
2736
+ onFrame?.();
2737
+ const frame = parseRawSseFrame(value);
2738
+ if (frame) yield frame;
2739
+ }
2740
+ }
2741
+ } finally {
2742
+ try {
2743
+ await reader.cancel();
2744
+ } catch {
2745
+ } finally {
2746
+ reader.releaseLock();
2747
+ }
2748
+ }
2749
+ }
2750
+ function waitForReconnect(ms, signal) {
2751
+ if (signal?.aborted) return Promise.reject(abortError(signal));
2752
+ return new Promise((resolve, reject) => {
2753
+ const timer = setTimeout(
2754
+ () => {
2755
+ signal?.removeEventListener("abort", onAbort);
2756
+ resolve();
2757
+ },
2758
+ Math.max(0, ms)
2759
+ );
2760
+ const onAbort = () => {
2761
+ clearTimeout(timer);
2762
+ reject(abortError(signal));
2763
+ };
2764
+ signal?.addEventListener("abort", onAbort, { once: true });
2765
+ });
2766
+ }
2767
+ function abortError(signal) {
2768
+ if (signal.reason instanceof Error) return signal.reason;
2769
+ return new DOMException("Aborted", "AbortError");
2770
+ }
2771
+ function withoutCursor(url) {
2772
+ const parsed = new URL(url);
2773
+ parsed.searchParams.delete("cursor");
2774
+ return parsed.toString();
2775
+ }
2776
+
2777
+ // src/resources/schedule-resource.ts
2778
+ var ScheduleResource = class {
2779
+ constructor(transport) {
2780
+ this.transport = transport;
2781
+ }
2782
+ transport;
2783
+ async getStatus(options = {}) {
2784
+ return await this.transport.request("/schedules/status", {
2785
+ signal: options.signal
2786
+ });
2787
+ }
2788
+ async listTasks(options = {}) {
2789
+ const { signal, ...query } = options;
2790
+ const response = await this.transport.request(
2791
+ this.transport.path("/schedules/tasks", query),
2792
+ { signal }
2793
+ );
2794
+ return response.tasks;
2795
+ }
2796
+ async getTask(id2, options = {}) {
2797
+ const response = await this.transport.request(
2798
+ `/schedules/tasks/${encodeURIComponent(id2)}`,
2799
+ { signal: options.signal }
2800
+ );
2801
+ return response.task;
2802
+ }
2803
+ async createTask(input, options = {}) {
2804
+ const response = await this.transport.request(
2805
+ "/schedules/tasks",
2806
+ {
2807
+ method: "POST",
2808
+ body: input,
2809
+ signal: options.signal
2810
+ }
2811
+ );
2812
+ return response.task;
2813
+ }
2814
+ async updateTask(id2, input, options = {}) {
2815
+ const response = await this.transport.request(
2816
+ `/schedules/tasks/${encodeURIComponent(id2)}`,
2817
+ { method: "PATCH", body: input, signal: options.signal }
2818
+ );
2819
+ return response.task;
2820
+ }
2821
+ async removeTask(id2, options = {}) {
2822
+ await this.transport.request(
2823
+ `/schedules/tasks/${encodeURIComponent(id2)}`,
2824
+ {
2825
+ method: "DELETE",
2826
+ signal: options.signal
2827
+ }
2828
+ );
2829
+ }
2830
+ async triggerTask(id2, options = {}) {
2831
+ const response = await this.transport.request(
2832
+ this.transport.path(`/schedules/tasks/${encodeURIComponent(id2)}/run`, { requestId: options.requestId }),
2833
+ { method: "POST", signal: options.signal }
2834
+ );
2835
+ return response.run;
2836
+ }
2837
+ async listRuns(options = {}) {
2838
+ const { signal, ...query } = options;
2839
+ const response = await this.transport.request(
2840
+ this.transport.path("/schedules/runs", query),
2841
+ { signal }
2842
+ );
2843
+ return response.runs;
2844
+ }
2845
+ async setRunUnread(id2, unread, options = {}) {
2846
+ const response = await this.transport.request(
2847
+ `/schedules/runs/${encodeURIComponent(id2)}/read`,
2848
+ { method: "PATCH", body: { unread }, signal: options.signal }
2849
+ );
2850
+ return response.run;
2851
+ }
2852
+ };
2853
+
2854
+ // src/resources/runtime/runtime-resource.ts
2855
+ var RuntimeResource = class {
2856
+ constructor(transport) {
2857
+ this.transport = transport;
2858
+ }
2859
+ transport;
2860
+ async listModels(options = {}) {
2861
+ const response = await this.transport.request("/models", options);
2862
+ return response.providers;
2863
+ }
2864
+ async modelProviders(input = { action: "list" }, options = {}) {
2865
+ const response = await this.transport.request("/providers/manage", { ...options, method: "POST", body: input });
2866
+ if (!validModelProviderConnections(response?.providers)) throw new Error("Invalid model provider response");
2867
+ return response.providers;
2868
+ }
2869
+ async providerDefaults(input = { action: "snapshot" }, options = {}) {
2870
+ const result = await this.transport.request("/providers/defaults", { ...options, method: "POST", body: input });
2871
+ const valid = input.action === "test" ? validProviderConnectionTestResult(result) : validProviderDefaultsSnapshot(result);
2872
+ if (!valid) throw new Error("Invalid provider defaults response");
2873
+ return result;
2874
+ }
2875
+ async listAgentPersonas(options = {}) {
2876
+ const response = await this.transport.request("/agent-personas", options);
2877
+ return response.agents;
2878
+ }
2879
+ listSkills(options = {}) {
2880
+ return this.transport.request("/skills", options);
2881
+ }
2882
+ async getSessionMcp(sessionId, options = {}) {
2883
+ const response = await this.transport.request(`/sessions/${encodeURIComponent(sessionId)}/mcp`, options);
2884
+ return response.servers;
2885
+ }
2886
+ };
2887
+
2888
+ // src/resources/session/session-terminal-resource.ts
2889
+ var SessionTerminalResource = class {
2890
+ constructor(transport) {
2891
+ this.transport = transport;
2892
+ }
2893
+ transport;
2894
+ async list(sessionId, options = {}) {
2895
+ const response = await this.transport.requestUnknown(path(sessionId), options);
2896
+ return responseArray2(response, "terminals", decodeTerminalSessionInfo);
2897
+ }
2898
+ async read(sessionId, terminalId, options = {}) {
2899
+ const { signal, ...query } = options;
2900
+ const response = await this.transport.requestUnknown(path(sessionId, terminalId) + "/output", { signal, query });
2901
+ return decodeTerminalReadResult(responseField(response, "snapshot"));
2902
+ }
2903
+ async stream(sessionId, terminalId, options = {}) {
2904
+ const response = await this.transport.requestResponse(path(sessionId, terminalId) + "/stream", options);
2905
+ const body = response.body;
2906
+ if (!body) throw new Error("Terminal event stream did not return a body");
2907
+ return streamServerSentEvents(async () => body, decodeTerminalEvent);
2908
+ }
2909
+ };
2910
+ function path(sessionId, terminalId) {
2911
+ return `/sessions/${encodeURIComponent(sessionId)}/terminals${terminalId === void 0 ? "" : `/${encodeURIComponent(terminalId)}`}`;
2912
+ }
2913
+
2914
+ // src/resources/session/session-management-resource.ts
2915
+ var SessionManagementResource = class {
2916
+ constructor(transport) {
2917
+ this.transport = transport;
2918
+ }
2919
+ transport;
2920
+ authenticatedCapabilities;
2921
+ async ready(signal) {
2922
+ let capabilities = await this.transport.ensureProtocol(signal);
2923
+ if ((capabilities.features.sessionResources ?? 0) < 1) throw new Error("Server does not support session resources");
2924
+ if (!capabilities.dataScopeId) {
2925
+ capabilities = this.authenticatedCapabilities ?? await new ProtocolClient(this.transport).capabilities({ authenticated: true, signal });
2926
+ if (!capabilities.dataScopeId || (capabilities.features.sessionResources ?? 0) < 1) throw new Error("Server does not support session resources");
2927
+ this.authenticatedCapabilities = capabilities;
2928
+ }
2929
+ return capabilities;
2930
+ }
2931
+ async getRevision(sessionId, input, options = {}) {
2932
+ await this.ready(options.signal);
2933
+ parseSessionManagementAction2(input.action);
2934
+ const response = await this.transport.request(this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/resource-revision`, { action: input.action }), options);
2935
+ return decodeSessionResourceRevision2(response);
2936
+ }
2937
+ async mutate(sessionId, action, input, options) {
2938
+ const body = parseSessionResourceMutation2(action, input), capabilities = await this.ready(options.signal);
2939
+ const response = await this.transport.request(`/sessions/${encodeURIComponent(sessionId)}/resource-actions/${action}`, { method: "POST", body, signal: options.signal });
2940
+ const receipt2 = decodeSessionMutationReceipt2(response.receipt);
2941
+ if (receipt2.dataScopeId !== capabilities.dataScopeId || receipt2.sessionId !== sessionId || receipt2.requestId !== body.requestId || receipt2.result.action !== action) throw new Error("Mutation receipt does not match original request");
2942
+ return receipt2;
2943
+ }
2944
+ rename(id2, input, options = {}) {
2945
+ return this.mutate(id2, "rename", input, options);
2946
+ }
2947
+ setPinned(id2, input, options = {}) {
2948
+ return this.mutate(id2, "pin", input, options);
2949
+ }
2950
+ archive(id2, input, options = {}) {
2951
+ return this.mutate(id2, "archive", input, options);
2952
+ }
2953
+ delete(id2, input, options = {}) {
2954
+ return this.mutate(id2, "delete", input, options);
2955
+ }
2956
+ async getMutation(sessionId, requestId, options = {}) {
2957
+ const capabilities = await this.ready(options.signal);
2958
+ const response = await this.transport.request(`/sessions/${encodeURIComponent(sessionId)}/resource-mutations/${encodeURIComponent(requestId)}`, options);
2959
+ if (response.receipt === null) return null;
2960
+ const receipt2 = decodeSessionMutationReceipt2(response.receipt);
2961
+ if (receipt2.dataScopeId !== capabilities.dataScopeId || receipt2.sessionId !== sessionId || receipt2.requestId !== requestId) throw new Error("Mutation receipt does not match query");
2962
+ return receipt2;
2963
+ }
2964
+ };
2965
+
2966
+ // src/resources/session/session-resource.ts
2967
+ var promptRequestCounter = 0;
2968
+ function createPromptRequestId() {
2969
+ if (typeof globalThis.crypto?.randomUUID === "function") {
2970
+ return globalThis.crypto.randomUUID();
2971
+ }
2972
+ promptRequestCounter += 1;
2973
+ return `prompt-${Date.now().toString(36)}-${promptRequestCounter.toString(36)}`;
2974
+ }
2975
+ var SessionResource = class {
2976
+ constructor(transport) {
2977
+ this.transport = transport;
2978
+ this.resources = new SessionManagementResource(transport);
2979
+ this.terminals = new SessionTerminalResource(transport);
2980
+ }
2981
+ transport;
2982
+ resources;
2983
+ terminals;
2984
+ checkOutputSchema(input, signal) {
2985
+ assertPromptMetadataAllowed2(input);
2986
+ if (input.outputSchema === void 0) return;
2987
+ return this.transport.ensureProtocol(signal).then((capabilities) => {
2988
+ if ((capabilities.features.structuredDelivery ?? 0) < 1) {
2989
+ throw new Error(
2990
+ "Server does not support structured delivery (outputSchema)"
2991
+ );
2992
+ }
2993
+ });
2994
+ }
2995
+ /** `GET /sessions/search` - search saved conversation text without opening it. */
2996
+ async search(options) {
2997
+ const { signal, ...query } = options;
2998
+ const response = await this.transport.request(this.transport.path("/sessions/search", query), { signal });
2999
+ return response.results;
3000
+ }
3001
+ /** `GET /sessions` */
3002
+ async list(options = {}) {
3003
+ const { signal, ...query } = options;
3004
+ const response = await this.transport.request(this.transport.path("/sessions", query), { signal });
3005
+ return response.sessions;
3006
+ }
3007
+ listDirectory(options = {}) {
3008
+ const { signal, ...query } = options;
3009
+ return this.transport.request(
3010
+ this.transport.path("/sessions/directory", query),
3011
+ { signal }
3012
+ );
3013
+ }
3014
+ getActivity(options = {}) {
3015
+ return this.transport.request("/sessions/activity", {
3016
+ signal: options.signal
3017
+ });
3018
+ }
3019
+ async getDraftComposerOptions(input, options = {}) {
3020
+ if (!validSessionControlInput("sessions.getDraftComposerOptions", input))
3021
+ throw new ProtocolDataError("Invalid draft composer target");
3022
+ const { workspaceId, outsideProject, roleId } = input;
3023
+ const path2 = this.transport.path("/sessions/configuration-options", {
3024
+ kind: "draft",
3025
+ workspaceId,
3026
+ outsideProject,
3027
+ roleId: roleId ?? void 0
3028
+ });
3029
+ const result = await this.transport.request(path2, {
3030
+ signal: options.signal
3031
+ });
3032
+ if (!validSessionControlResult("sessions.getDraftComposerOptions", result) || result.source !== input.source) {
3033
+ throw new ProtocolDataError("Draft composer options do not match target");
3034
+ }
3035
+ return result;
3036
+ }
3037
+ async getControls(sessionId, options = {}) {
3038
+ const result = await this.transport.request(
3039
+ `/sessions/${encodeURIComponent(sessionId)}/controls`,
3040
+ { signal: options.signal }
3041
+ );
3042
+ if (!validSessionControlResult("sessions.getControls", result) || result.sessionId !== sessionId) {
3043
+ throw new ProtocolDataError("Session controls do not match target");
3044
+ }
3045
+ return result;
3046
+ }
3047
+ async getControlResult(sessionId, input, options = {}) {
3048
+ const { requestId, original } = input;
3049
+ if (!validSessionControlOriginal(original) || original.body.requestId !== requestId) throw new ProtocolDataError("Invalid original control request");
3050
+ const result = await this.transport.request(
3051
+ `/sessions/${encodeURIComponent(sessionId)}/control-result`,
3052
+ {
3053
+ method: "POST",
3054
+ body: { requestId, original },
3055
+ signal: options.signal
3056
+ }
3057
+ );
3058
+ if (!validSessionControlResult("sessions.getControlResult", result) || result && (result.sessionId !== sessionId || result.requestId !== requestId || result.action !== original.action || original.action === "fork" && result.targetSessionId !== original.body.id))
3059
+ throw new ProtocolDataError(
3060
+ "Control receipt does not match original request"
3061
+ );
3062
+ return result;
3063
+ }
3064
+ /** Current context assembly requires execution authority; /usage is historical billing. */
3065
+ async getContextUsage(sessionId, options = {}) {
3066
+ return this.transport.request(
3067
+ `/sessions/${encodeURIComponent(sessionId)}/context-usage`,
3068
+ { signal: options.signal }
3069
+ );
3070
+ }
3071
+ /** `GET /sessions/:id` */
3072
+ async get(sessionId, options = {}) {
3073
+ const response = await this.transport.request(
3074
+ `/sessions/${encodeURIComponent(sessionId)}`,
3075
+ {
3076
+ signal: options.signal
3077
+ }
3078
+ );
3079
+ return response.session;
3080
+ }
3081
+ /** `POST /sessions` */
3082
+ async create(input, options = {}) {
3083
+ const response = await this.transport.request(
3084
+ "/sessions",
3085
+ {
3086
+ method: "POST",
3087
+ body: parseCreateSessionRequest({
3088
+ ...input,
3089
+ id: input.id ?? createPromptRequestId(),
3090
+ requestId: input.requestId ?? createPromptRequestId()
3091
+ }),
3092
+ signal: options.signal
3093
+ }
3094
+ );
3095
+ return response.session;
3096
+ }
3097
+ async getConfigurationOptions(input, options = {}) {
3098
+ return this.transport.request(
3099
+ this.transport.path("/sessions/configuration-options", input),
3100
+ { signal: options.signal }
3101
+ );
3102
+ }
3103
+ async getCreationResult(input, options = {}) {
3104
+ return this.transport.request("/sessions/creation-result", {
3105
+ method: "POST",
3106
+ body: input,
3107
+ signal: options.signal
3108
+ });
3109
+ }
3110
+ async getConfiguration(sessionId, options = {}) {
3111
+ const value = await this.transport.requestUnknown(
3112
+ `/sessions/${encodeURIComponent(sessionId)}/configuration`,
3113
+ { signal: options.signal }
3114
+ );
3115
+ return decodeSessionConfigurationSnapshot(value);
3116
+ }
3117
+ async configure(sessionId, input, options = {}) {
3118
+ const body = parseConfigureSessionRequest(input);
3119
+ const response = await this.transport.requestUnknown(
3120
+ `/sessions/${encodeURIComponent(sessionId)}/configure`,
3121
+ { method: "POST", body, signal: options.signal }
3122
+ );
3123
+ return decodeSessionConfigurationReceipt(response, {
3124
+ sessionId,
3125
+ requestId: body.requestId
3126
+ });
3127
+ }
3128
+ async getConfigurationResult(sessionId, input, options = {}) {
3129
+ const body = parseConfigurationResultRequest(input);
3130
+ const response = await this.transport.requestUnknown(
3131
+ `/sessions/${encodeURIComponent(sessionId)}/configuration-result`,
3132
+ { method: "POST", body, signal: options.signal }
3133
+ );
3134
+ return response === null ? null : decodeSessionConfigurationReceipt(response, {
3135
+ sessionId,
3136
+ requestId: body.requestId
3137
+ });
3138
+ }
3139
+ /** `PATCH /sessions/:id` - update title or application metadata. */
3140
+ async update(sessionId, input, options = {}) {
3141
+ const response = await this.transport.request(
3142
+ `/sessions/${encodeURIComponent(sessionId)}`,
3143
+ {
3144
+ method: "PATCH",
3145
+ body: parseUpdateSessionRequest(input),
3146
+ signal: options.signal
3147
+ }
3148
+ );
3149
+ return response.session;
3150
+ }
3151
+ /** `POST /sessions/:id/fork` */
3152
+ async fork(sessionId, input = {}, options = {}) {
3153
+ const response = await this.transport.request(
3154
+ `/sessions/${encodeURIComponent(sessionId)}/fork`,
3155
+ {
3156
+ method: "POST",
3157
+ body: parseForkSessionRequest({
3158
+ ...input,
3159
+ id: input.id ?? createPromptRequestId(),
3160
+ requestId: input.requestId ?? createPromptRequestId()
3161
+ }),
3162
+ signal: options.signal
3163
+ }
3164
+ );
3165
+ return response.session;
3166
+ }
3167
+ /** `DELETE /sessions/:id` */
3168
+ async archive(sessionId, options = {}) {
3169
+ const response = await this.transport.request(
3170
+ `/sessions/${encodeURIComponent(sessionId)}`,
3171
+ {
3172
+ method: "DELETE",
3173
+ signal: options.signal
3174
+ }
3175
+ );
3176
+ return response.session;
3177
+ }
3178
+ /** `DELETE /sessions/:id/hard` */
3179
+ async delete(sessionId, options = {}) {
3180
+ const response = await this.transport.request(`/sessions/${encodeURIComponent(sessionId)}/hard`, {
3181
+ method: "DELETE",
3182
+ signal: options.signal
3183
+ });
3184
+ return response.deletedSessionIds;
3185
+ }
3186
+ /** `GET /sessions/:id/state` - atomic attach snapshot plus SSE cursor. */
3187
+ async getState(sessionId, options = {}) {
3188
+ const response = await this.transport.request(
3189
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/state`, {
3190
+ partView: options.partView
3191
+ }),
3192
+ {
3193
+ signal: options.signal
3194
+ }
3195
+ );
3196
+ return decodeAgentSessionStateSnapshot(response);
3197
+ }
3198
+ /** `GET /sessions/:id/messages` */
3199
+ async listMessages(sessionId, options = {}) {
3200
+ const { signal, ...query } = options;
3201
+ const response = await this.transport.request(
3202
+ this.transport.path(
3203
+ `/sessions/${encodeURIComponent(sessionId)}/messages`,
3204
+ query
3205
+ ),
3206
+ { signal }
3207
+ );
3208
+ return response.messages;
3209
+ }
3210
+ /** `GET /sessions/:id/parts` */
3211
+ async listMessageParts(sessionId, options = {}) {
3212
+ const { signal, ...query } = options;
3213
+ const response = await this.transport.request(
3214
+ this.transport.path(
3215
+ `/sessions/${encodeURIComponent(sessionId)}/parts`,
3216
+ query
3217
+ ),
3218
+ { signal }
3219
+ );
3220
+ return response.parts;
3221
+ }
3222
+ /** Read full canonical content for one part in its session/message scope. */
3223
+ async getMessagePart(sessionId, messageId, partId, options = {}) {
3224
+ const response = await this.transport.request(
3225
+ `/sessions/${encodeURIComponent(sessionId)}/messages/${encodeURIComponent(messageId)}/parts/${encodeURIComponent(partId)}`,
3226
+ options
3227
+ );
3228
+ return response.part;
3229
+ }
3230
+ /** `POST /sessions/:id/prompts` — 提交用户输入并触发/排队一次 run。 */
3231
+ async admitPrompt(sessionId, input, options = {}) {
3232
+ const schemaCheck = this.checkOutputSchema(input, options.signal);
3233
+ if (schemaCheck) await schemaCheck;
3234
+ return await this.transport.request(
3235
+ `/sessions/${encodeURIComponent(sessionId)}/prompts`,
3236
+ {
3237
+ method: "POST",
3238
+ body: { ...input, id: input.id ?? createPromptRequestId() },
3239
+ signal: options.signal
3240
+ }
3241
+ );
3242
+ }
3243
+ /** `POST /sessions/:id/prompts/latest/edit` */
3244
+ async editLatestPrompt(sessionId, input, options = {}) {
3245
+ await this.checkOutputSchema(input, options.signal);
3246
+ return await this.transport.request(
3247
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/latest/edit`,
3248
+ {
3249
+ method: "POST",
3250
+ body: input,
3251
+ signal: options.signal
3252
+ }
3253
+ );
3254
+ }
3255
+ /** Promote one durable queued prompt into the exact active run. */
3256
+ async promoteQueuedPrompt(sessionId, inputId, input, options = {}) {
3257
+ return await this.transport.request(
3258
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/promote`,
3259
+ { method: "POST", body: input, signal: options.signal }
3260
+ );
3261
+ }
3262
+ async cancelQueuedPrompt(sessionId, inputId, input, options = {}) {
3263
+ const mode = parseCancelResponseMode(options.responseMode);
3264
+ const response = await this.transport.request(
3265
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/cancel`,
3266
+ {
3267
+ method: "POST",
3268
+ body: {
3269
+ ...input,
3270
+ ...options.responseMode ? { responseMode: mode } : {}
3271
+ },
3272
+ signal: options.signal
3273
+ }
3274
+ );
3275
+ if (mode === "receipt") {
3276
+ const receipt2 = decodeQueuedPromptCancelReceipt(response);
3277
+ if (receipt2.inputId !== inputId || receipt2.queuedRunId !== input.queuedRunId)
3278
+ throw new ProtocolDataError(
3279
+ "Cancellation receipt does not match target"
3280
+ );
3281
+ return receipt2;
3282
+ }
3283
+ return response;
3284
+ }
3285
+ /**
3286
+ * `POST /sessions/:id/runs/:runId/resume` — 显式重放一次中断 run 的原始 prompt。
3287
+ * 不会继续旧 provider stream;服务端会创建一个带恢复溯源的新 input/run。
3288
+ */
3289
+ async resumeInterruptedRun(sessionId, runId, input = {}, options = {}) {
3290
+ await this.checkOutputSchema(input, options.signal);
3291
+ return await this.transport.request(
3292
+ `/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}/resume`,
3293
+ {
3294
+ method: "POST",
3295
+ body: { ...input, id: input.id ?? createPromptRequestId() },
3296
+ signal: options.signal
3297
+ }
3298
+ );
3299
+ }
3300
+ /** `POST /sessions/:id/interrupt` — 中断当前/排队中的 run。 */
3301
+ async interrupt(sessionId, options = {}) {
3302
+ return await this.transport.request(
3303
+ `/sessions/${encodeURIComponent(sessionId)}/interrupt`,
3304
+ {
3305
+ method: "POST",
3306
+ body: options.expectedRunId || options.source ? {
3307
+ ...options.expectedRunId ? { expectedRunId: options.expectedRunId } : {},
3308
+ ...options.source ? { source: options.source } : {}
3309
+ } : void 0,
3310
+ signal: options.signal
3311
+ }
3312
+ );
3313
+ }
3314
+ /** `POST /sessions/:id/compact` */
3315
+ async compact(sessionId, options = {}) {
3316
+ return await this.transport.request(
3317
+ `/sessions/${encodeURIComponent(sessionId)}/compact`,
3318
+ {
3319
+ method: "POST",
3320
+ signal: options.signal,
3321
+ ...options.requestId ? {
3322
+ body: {
3323
+ requestId: options.requestId,
3324
+ expectedRevision: options.expectedRevision
3325
+ }
3326
+ } : {}
3327
+ }
3328
+ );
3329
+ }
3330
+ /** `POST /sessions/:id/rewind` */
3331
+ async rewind(sessionId, input = {}, options = {}) {
3332
+ return await this.transport.request(
3333
+ `/sessions/${encodeURIComponent(sessionId)}/rewind`,
3334
+ { method: "POST", body: input, signal: options.signal }
3335
+ );
3336
+ }
3337
+ /** `POST /sessions/:id/remember` */
3338
+ async remember(sessionId, options = {}) {
3339
+ return await this.transport.request(
3340
+ `/sessions/${encodeURIComponent(sessionId)}/remember`,
3341
+ { method: "POST", signal: options.signal }
3342
+ );
3343
+ }
3344
+ /** `POST /sessions/:id/export` */
3345
+ async export(sessionId, input = {}, options = {}) {
3346
+ return await this.transport.request(
3347
+ `/sessions/${encodeURIComponent(sessionId)}/export`,
3348
+ { method: "POST", body: input, signal: options.signal }
3349
+ );
3350
+ }
3351
+ /** `GET /sessions/:id/usage` */
3352
+ async getUsage(sessionId, options = {}) {
3353
+ return await this.transport.request(
3354
+ `/sessions/${encodeURIComponent(sessionId)}/usage`,
3355
+ { signal: options.signal }
3356
+ );
3357
+ }
3358
+ /** `GET /sessions/:id/goal` */
3359
+ async getGoal(sessionId) {
3360
+ const response = await this.transport.request(
3361
+ `/sessions/${encodeURIComponent(sessionId)}/goal`
3362
+ );
3363
+ return response.goal;
3364
+ }
3365
+ /** Reads the original durable action receipt after a response was lost. */
3366
+ async getGoalRequest(sessionId, requestId) {
3367
+ const receipt2 = decodeSessionGoalRequestReceipt(
3368
+ await this.transport.request(
3369
+ `/sessions/${encodeURIComponent(sessionId)}/goal/requests/${encodeURIComponent(requestId)}`
3370
+ )
3371
+ );
3372
+ if (receipt2.sessionId !== sessionId || receipt2.requestId !== requestId)
3373
+ throw new ProtocolDataError(
3374
+ "Goal request receipt does not match request"
3375
+ );
3376
+ return receipt2;
3377
+ }
3378
+ /** `POST /sessions/:id/goals` */
3379
+ async createGoal(sessionId, input) {
3380
+ const response = await this.transport.request(
3381
+ `/sessions/${encodeURIComponent(sessionId)}/goals`,
3382
+ { method: "POST", body: input }
3383
+ );
3384
+ return response.goal;
3385
+ }
3386
+ /** `PATCH /sessions/:id/goals/:goalId` */
3387
+ async updateGoal(sessionId, goalId, input) {
3388
+ const response = await this.transport.request(
3389
+ `/sessions/${encodeURIComponent(sessionId)}/goals/${encodeURIComponent(goalId)}`,
3390
+ { method: "PATCH", body: input }
3391
+ );
3392
+ return response.goal;
3393
+ }
3394
+ /** `POST /sessions/:id/goals/:goalId/actions` */
3395
+ async applyGoalAction(sessionId, goalId, input) {
3396
+ const response = await this.transport.request(
3397
+ `/sessions/${encodeURIComponent(sessionId)}/goals/${encodeURIComponent(goalId)}/actions`,
3398
+ { method: "POST", body: input }
3399
+ );
3400
+ return response.goal;
3401
+ }
3402
+ };
3403
+
3404
+ // src/resources/session/attachment-resource.ts
3405
+ var AttachmentResource = class {
3406
+ constructor(transport) {
3407
+ this.transport = transport;
3408
+ }
3409
+ transport;
3410
+ /** `POST /attachments` — upload bytes without JSON or multipart buffering. */
3411
+ async upload(input) {
3412
+ const headers2 = uploadIdentityHeaders(input);
3413
+ headers2["x-bobannomi-filename"] = encodeURIComponent(input.displayName);
3414
+ if (input.mediaType) headers2["content-type"] = input.mediaType;
3415
+ const response = await this.transport.requestResponse("/attachments", {
3416
+ method: "POST",
3417
+ headers: headers2,
3418
+ body: input.body,
3419
+ signal: input.signal
3420
+ });
3421
+ return parseAttachmentAssetRecord(await response.json());
3422
+ }
3423
+ async getUpload(input) {
3424
+ const response = await this.transport.requestResponse("/attachments/uploads", { headers: uploadIdentityHeaders(input), signal: input.signal });
3425
+ const value = await response.json();
3426
+ return value === null ? null : parseAttachmentAssetRecord(value);
3427
+ }
3428
+ async get(id2, options = {}) {
3429
+ const value = await this.transport.request(
3430
+ `/attachments/${encodeURIComponent(id2)}`,
3431
+ { signal: options.signal }
3432
+ );
3433
+ return parseAttachmentAssetRecord(value);
3434
+ }
3435
+ /** Returns the raw response so callers can consume the body as a stream. */
3436
+ async download(id2, options = {}) {
3437
+ const range = attachmentRangeHeader(options.range);
3438
+ const headers2 = {};
3439
+ if (range) headers2.range = range;
3440
+ return await this.transport.requestResponse(
3441
+ `/attachments/${encodeURIComponent(id2)}/content`,
3442
+ { method: "GET", headers: headers2, signal: options.signal }
3443
+ );
3444
+ }
3445
+ async delete(id2, options = {}) {
3446
+ const value = await this.transport.request(
3447
+ `/attachments/${encodeURIComponent(id2)}`,
3448
+ { method: "DELETE", signal: options.signal }
3449
+ );
3450
+ return parseAttachmentAssetRecord(value);
3451
+ }
3452
+ };
3453
+ function uploadIdentityHeaders(input) {
3454
+ parseAttachmentUploadRequest({ ...input, declaredMediaType: input.mediaType });
3455
+ return { "x-bobannomi-request-id": input.requestId, "x-bobannomi-draft-id": input.draftId, "x-bobannomi-sha256": input.expectedSha256, "x-bobannomi-byte-length": String(input.byteLength), "x-bobannomi-filename": encodeURIComponent(input.displayName), ...input.mediaType ? { "content-type": input.mediaType } : {} };
3456
+ }
3457
+
3458
+ // src/resources/configuration/permission-resource.ts
3459
+ var PermissionResource = class {
3460
+ constructor(transport) {
3461
+ this.transport = transport;
3462
+ }
3463
+ transport;
3464
+ /** Answer an actual AskUser question; this cannot approve tools. */
3465
+ async answerQuestion(requestId, input, options = {}) {
3466
+ const capabilities = await this.transport.ensureProtocol(options.signal);
3467
+ if ((capabilities.features.questions ?? 0) < 1) throw new Error("Server does not support questions");
3468
+ const response = await this.transport.request(
3469
+ `/permissions/${encodeURIComponent(requestId)}/answer`,
3470
+ { method: "POST", body: input, signal: options.signal }
3471
+ );
3472
+ return response.request;
3473
+ }
3474
+ async listApprovals() {
3475
+ const response = await this.transport.request("/permissions/approvals");
3476
+ return response.requests;
3477
+ }
3478
+ async revokeApproval(requestId) {
3479
+ const response = await this.transport.request(
3480
+ `/permissions/${encodeURIComponent(requestId)}/revoke`,
3481
+ { method: "POST" }
3482
+ );
3483
+ return response.request;
3484
+ }
3485
+ /** `GET /permissions` */
3486
+ async list(options = {}) {
3487
+ const { signal, ...query } = options;
3488
+ const response = await this.transport.request(this.transport.path("/permissions", query), { signal });
3489
+ return response.requests;
3490
+ }
3491
+ /** `POST /permissions/:id/reply` — 批准/拒绝工具权限请求。 */
3492
+ async reply(requestId, input, options = {}) {
3493
+ const response = await this.transport.request(
3494
+ `/permissions/${encodeURIComponent(requestId)}/reply`,
3495
+ {
3496
+ method: "POST",
3497
+ body: input,
3498
+ signal: options.signal
3499
+ }
3500
+ );
3501
+ return response.request;
3502
+ }
3503
+ };
3504
+
3505
+ // src/resources/runtime/job-resource.ts
3506
+ var JobResource = class {
3507
+ constructor(transport) {
3508
+ this.transport = transport;
3509
+ }
3510
+ transport;
3511
+ async list(options) {
3512
+ const { signal, kinds, statuses, includeFinished, ...query } = options;
3513
+ const response = await this.transport.request(
3514
+ this.transport.path("/jobs", {
3515
+ ...query,
3516
+ ...kinds ? { kinds: kinds.join(",") } : {},
3517
+ ...statuses ? { statuses: statuses.join(",") } : {},
3518
+ ...includeFinished !== void 0 ? { includeFinished: String(includeFinished) } : {}
3519
+ }),
3520
+ { signal }
3521
+ );
3522
+ return decodeJobListResult(response);
3523
+ }
3524
+ async createBackgroundShell(input, options = {}) {
3525
+ return await this.transport.request(
3526
+ "/background-shells",
3527
+ {
3528
+ method: "POST",
3529
+ body: input,
3530
+ signal: options.signal
3531
+ }
3532
+ );
3533
+ }
3534
+ async read(target, options) {
3535
+ const { signal, ...query } = options;
3536
+ const response = await this.transport.request(
3537
+ this.transport.path(`/jobs/${encodeURIComponent(target.jobId)}`, { ...query, kind: target.kind, ...target.kind === "agent" ? { runId: target.runId } : {} }),
3538
+ { signal }
3539
+ );
3540
+ return decodeJobReadResult(response);
3541
+ }
3542
+ async wait(target, input, options = {}) {
3543
+ const response = await this.transport.request(
3544
+ `/jobs/${encodeURIComponent(target.jobId)}/wait`,
3545
+ {
3546
+ method: "POST",
3547
+ body: { ...input, target },
3548
+ signal: options.signal
3549
+ }
3550
+ );
3551
+ return decodeJobWaitResult(response);
3552
+ }
3553
+ async send(target, input, options = {}) {
3554
+ const response = await this.transport.request(`/jobs/${encodeURIComponent(target.jobId)}/input`, {
3555
+ method: "POST",
3556
+ body: { ...input, target },
3557
+ signal: options.signal
3558
+ });
3559
+ if (responseField(response, "sent") !== true) throw new ProtocolDataError("Job input was not accepted", "sent");
3560
+ const receipt2 = response.receipt;
3561
+ return receipt2 === void 0 ? void 0 : decodeJobInputReceipt(receipt2);
3562
+ }
3563
+ async cancel(target, input, options = {}) {
3564
+ const mode = parseCancelResponseMode(options.responseMode);
3565
+ const response = await this.transport.request(
3566
+ `/jobs/${encodeURIComponent(target.jobId)}/cancel`,
3567
+ { method: "POST", body: { ...input, target, ...options.responseMode ? { responseMode: mode } : {} }, signal: options.signal }
3568
+ );
3569
+ if (mode === "receipt") {
3570
+ const receipt2 = decodeJobCancelReceipt(response);
3571
+ if (receipt2.id !== target.jobId) throw new ProtocolDataError("Cancellation receipt does not match target");
3572
+ return receipt2;
3573
+ }
3574
+ return decodeJobSnapshot(responseField(response, "snapshot"));
3575
+ }
3576
+ };
3577
+
3578
+ // src/resources/session/event-resource.ts
3579
+ var EventResource = class {
3580
+ constructor(transport, sse) {
3581
+ this.transport = transport;
3582
+ this.sse = sse;
3583
+ }
3584
+ transport;
3585
+ sse;
3586
+ /** `GET /events` — 用于 attach 时的历史 replay。 */
3587
+ async list(options = {}) {
3588
+ const { signal, ...query } = options;
3589
+ const response = await this.transport.request(
3590
+ this.transport.path("/events", query),
3591
+ { signal }
3592
+ );
3593
+ return responseArray2(response, "events", decodeSessionEventRecord);
3594
+ }
3595
+ stream(options = {}) {
3596
+ const query = {
3597
+ partView: options.partView,
3598
+ cursor: options.cursor,
3599
+ sessionId: options.sessionId
3600
+ };
3601
+ return this.sse.stream(this.transport.resolveUrl("/events/stream", query), {
3602
+ headers: this.transport.headers(),
3603
+ signal: options.signal,
3604
+ decode: decodeSessionEventRecord,
3605
+ reconnect: options.transportReconnect ?? false,
3606
+ onOpen: options.onOpen,
3607
+ idleTimeoutMs: options.idleTimeoutMs
3608
+ });
3609
+ }
3610
+ };
3611
+
3612
+ // src/resources/files/files-resource.ts
3613
+ var FilesResource = class {
3614
+ constructor(transport) {
3615
+ this.transport = transport;
3616
+ }
3617
+ transport;
3618
+ async list(sessionId, options = {}) {
3619
+ const { signal, ...query } = options;
3620
+ const response = await this.transport.request(
3621
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files`, query),
3622
+ { signal }
3623
+ );
3624
+ return decodeSessionDirectoryResult(response);
3625
+ }
3626
+ async stat(sessionId, path2, options = {}) {
3627
+ const response = await this.transport.request(
3628
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/stat`, { path: path2 }),
3629
+ { signal: options.signal }
3630
+ );
3631
+ return decodeSessionFileInfo(response);
3632
+ }
3633
+ async readText(sessionId, path2, options = {}) {
3634
+ const { signal, ...query } = options;
3635
+ const response = await this.transport.request(
3636
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/text`, { path: path2, ...query }),
3637
+ { signal }
3638
+ );
3639
+ return decodeSessionTextFileResult(response);
3640
+ }
3641
+ async find(sessionId, options) {
3642
+ const { signal, ...query } = options;
3643
+ const response = await this.transport.request(
3644
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/find`, query),
3645
+ { signal }
3646
+ );
3647
+ return decodeSessionFindFilesResult(response);
3648
+ }
3649
+ async search(sessionId, options) {
3650
+ const { signal, caseSensitive, ...query } = options;
3651
+ const response = await this.transport.request(
3652
+ this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/search`, {
3653
+ ...query,
3654
+ ...caseSensitive === void 0 ? {} : { caseSensitive: String(caseSensitive) }
3655
+ }),
3656
+ { signal }
3657
+ );
3658
+ return decodeSessionSearchFilesResult(response);
3659
+ }
3660
+ };
3661
+
3662
+ // src/transport/http-client.ts
3663
+ var BobanNomiClient = class {
3664
+ protocol;
3665
+ runtime;
3666
+ schedules;
3667
+ sessions;
3668
+ attachments;
3669
+ permissions;
3670
+ jobs;
3671
+ events;
3672
+ files;
3673
+ constructor(options) {
3674
+ const transport = new HttpTransport(options);
3675
+ const sse = new SseTransport(transport);
3676
+ this.protocol = new ProtocolClient(transport);
3677
+ this.runtime = new RuntimeResource(transport);
3678
+ this.schedules = new ScheduleResource(transport);
3679
+ this.sessions = new SessionResource(transport);
3680
+ this.attachments = new AttachmentResource(transport);
3681
+ this.permissions = new PermissionResource(transport);
3682
+ this.jobs = new JobResource(transport);
3683
+ this.events = new EventResource(transport, sse);
3684
+ this.files = new FilesResource(transport);
3685
+ }
3686
+ };
3687
+
3688
+ // src/state/reducer.ts
3689
+ var UnsupportedSessionEventSchemaVersionError = class extends Error {
3690
+ event;
3691
+ constructor(event) {
3692
+ const expected = sessionEventSchemaVersion(event.type);
3693
+ super(
3694
+ `Unsupported session event schema version ${event.schemaVersion} for ${event.type} at sequence ${event.seq}; expected ${expected}`
3695
+ );
3696
+ this.name = "UnsupportedSessionEventSchemaVersionError";
3697
+ this.event = {
3698
+ seq: event.seq,
3699
+ type: event.type,
3700
+ schemaVersion: event.schemaVersion
3701
+ };
3702
+ }
3703
+ };
3704
+ function createInitialClientState() {
3705
+ return {
3706
+ sessions: {},
3707
+ sessionOrder: [],
3708
+ buckets: {},
3709
+ eventsBySeq: {},
3710
+ snapshotCursorBySession: {},
3711
+ transientCursor: 0,
3712
+ lastSeq: 0
3713
+ };
3714
+ }
3715
+ function applyEvents(state, events) {
3716
+ let next = state;
3717
+ for (const event of events) next = applyEvent(next, event);
3718
+ return next;
3719
+ }
3720
+ function applySessionSnapshot(state, snapshot) {
3721
+ const knownCursor = state.snapshotCursorBySession[snapshot.session.id] ?? 0;
3722
+ if (snapshot.cursor < knownCursor) return state;
3723
+ if (Object.values(state.eventsBySeq).some((event) => event.sessionId === snapshot.session.id && event.seq > snapshot.cursor)) return state;
3724
+ const partsByMessageId = {};
3725
+ for (const part of snapshot.parts) {
3726
+ const parts = partsByMessageId[part.messageId] ?? [];
3727
+ parts.push(part);
3728
+ partsByMessageId[part.messageId] = parts;
3729
+ }
3730
+ for (const parts of Object.values(partsByMessageId)) parts.sort((a, b) => a.seq - b.seq);
3731
+ const sessions = { ...state.sessions, [snapshot.session.id]: snapshot.session };
3732
+ return {
3733
+ ...state,
3734
+ sessions,
3735
+ sessionOrder: sortSessionOrder(sessions),
3736
+ buckets: {
3737
+ ...state.buckets,
3738
+ [snapshot.session.id]: {
3739
+ goal: snapshot.goal,
3740
+ session: snapshot.session,
3741
+ inputs: [...snapshot.inputs].sort((a, b) => a.seq - b.seq),
3742
+ messages: [...snapshot.messages].sort((a, b) => a.seq - b.seq),
3743
+ partsByMessageId,
3744
+ runs: Object.fromEntries(snapshot.runs.map((run) => [run.id, run])),
3745
+ attempts: Object.fromEntries((snapshot.attempts ?? []).map((attempt) => [attempt.id, attempt])),
3746
+ tasks: Object.fromEntries((snapshot.tasks ?? []).map((task) => [task.id, task])),
3747
+ permissions: Object.fromEntries(snapshot.permissions.map((request) => [request.id, request]))
3748
+ }
3749
+ },
3750
+ snapshotCursorBySession: {
3751
+ ...state.snapshotCursorBySession,
3752
+ [snapshot.session.id]: Math.max(
3753
+ state.snapshotCursorBySession[snapshot.session.id] ?? 0,
3754
+ snapshot.cursor
3755
+ )
3756
+ },
3757
+ transientCursor: Math.max(state.transientCursor, snapshot.cursor),
3758
+ lastSeq: Math.max(state.lastSeq, snapshot.cursor)
3759
+ };
3760
+ }
3761
+ function applyEvent(state, event) {
3762
+ if (event.schemaVersion !== sessionEventSchemaVersion(event.type)) {
3763
+ throw new UnsupportedSessionEventSchemaVersionError(event);
3764
+ }
3765
+ const transient = event.type === "session.message.part.delta";
3766
+ const snapshotCursor = event.sessionId ? state.snapshotCursorBySession[event.sessionId] ?? 0 : 0;
3767
+ if (event.seq <= snapshotCursor) return state;
3768
+ if (transient && event.seq <= state.transientCursor) return state;
3769
+ if (!transient && state.eventsBySeq[event.seq]) return state;
3770
+ if (!transient) state.eventsBySeq[event.seq] = event;
3771
+ let next = {
3772
+ ...state,
3773
+ eventsBySeq: state.eventsBySeq,
3774
+ transientCursor: transient ? event.seq : state.transientCursor,
3775
+ lastSeq: Math.max(state.lastSeq, event.seq)
3776
+ };
3777
+ switch (event.type) {
3778
+ case "session.goal.created":
3779
+ case "session.goal.updated": {
3780
+ const goal = readPayloadRecord(event, "goal");
3781
+ if (goal && goal.sessionId === event.sessionId) {
3782
+ const bucket = cloneBucket(next.buckets[goal.sessionId]);
3783
+ if (!bucket.goal || goal.revision >= bucket.goal.revision) bucket.goal = goal;
3784
+ next = { ...next, buckets: { ...next.buckets, [goal.sessionId]: bucket } };
3785
+ }
3786
+ break;
3787
+ }
3788
+ case "session.goal.usage.updated": {
3789
+ const bucket = event.sessionId ? next.buckets[event.sessionId] : void 0;
3790
+ const usage = readPayloadRecord(event, "usage");
3791
+ if (bucket?.goal && bucket.goal.id === event.payload.goalId && usage && usage.seq > bucket.goal.usage.seq) {
3792
+ next = { ...next, buckets: { ...next.buckets, [event.sessionId]: { ...bucket, goal: { ...bucket.goal, usage } } } };
3793
+ }
3794
+ break;
3795
+ }
3796
+ case "session.created":
3797
+ case "session.updated":
3798
+ next = upsertSession(next, readPayloadRecord(event, "session"));
3799
+ break;
3800
+ case "session.archived":
3801
+ next = archiveSession(next, event);
3802
+ break;
3803
+ case "session.deleted":
3804
+ next = deleteSessions(next, event);
3805
+ break;
3806
+ case "session.input.admitted":
3807
+ next = upsertInput(next, readPayloadRecord(event, "input"));
3808
+ break;
3809
+ case "session.message.created":
3810
+ next = upsertMessage(next, readPayloadRecord(event, "message"));
3811
+ break;
3812
+ case "session.transcript.replaced":
3813
+ next = replaceTranscript(next, event);
3814
+ break;
3815
+ case "session.message.part.updated":
3816
+ next = upsertPart(next, readPayloadRecord(event, "part"));
3817
+ break;
3818
+ case "session.message.part.delta":
3819
+ next = appendPartDelta(next, event);
3820
+ break;
3821
+ case "session.run.created":
3822
+ case "session.run.updated":
3823
+ next = upsertRun(next, readPayloadRecord(event, "run"));
3824
+ break;
3825
+ case "session.run_attempt.created":
3826
+ case "session.run_attempt.updated":
3827
+ next = upsertRunAttempt(next, readPayloadRecord(event, "attempt"));
3828
+ break;
3829
+ case "session.task.created":
3830
+ case "session.task.updated":
3831
+ next = upsertTask(next, readPayloadRecord(event, "task"));
3832
+ break;
3833
+ case "permission.asked":
3834
+ case "permission.replied":
3835
+ next = upsertPermission(next, readPayloadRecord(event, "request"));
3836
+ break;
3837
+ }
3838
+ return next;
3839
+ }
3840
+ function readPayloadRecord(event, key) {
3841
+ const value = event.payload[key];
3842
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3843
+ }
3844
+ function upsertSession(state, session) {
3845
+ if (!session) return state;
3846
+ const bucket = cloneBucket(state.buckets[session.id]);
3847
+ bucket.session = session;
3848
+ const sessions = { ...state.sessions, [session.id]: session };
3849
+ return {
3850
+ ...state,
3851
+ sessions,
3852
+ sessionOrder: sortSessionOrder(sessions),
3853
+ buckets: { ...state.buckets, [session.id]: bucket }
3854
+ };
3855
+ }
3856
+ function archiveSession(state, event) {
3857
+ const sessionId = typeof event.payload.sessionId === "string" ? event.payload.sessionId : event.sessionId;
3858
+ if (!sessionId) return state;
3859
+ const current = state.sessions[sessionId];
3860
+ if (!current) return state;
3861
+ const archived = {
3862
+ ...current,
3863
+ status: "archived",
3864
+ archivedAt: current.archivedAt ?? event.createdAt,
3865
+ updatedAt: Math.max(current.updatedAt, event.createdAt)
3866
+ };
3867
+ return upsertSession(state, archived);
3868
+ }
3869
+ function deleteSessions(state, event) {
3870
+ const ids = new Set(Array.isArray(event.payload.sessionIds) ? event.payload.sessionIds.filter((id2) => typeof id2 === "string") : []);
3871
+ if (ids.size === 0) return state;
3872
+ return {
3873
+ ...state,
3874
+ sessions: Object.fromEntries(Object.entries(state.sessions).filter(([id2]) => !ids.has(id2))),
3875
+ sessionOrder: state.sessionOrder.filter((id2) => !ids.has(id2)),
3876
+ buckets: Object.fromEntries(Object.entries(state.buckets).filter(([id2]) => !ids.has(id2))),
3877
+ snapshotCursorBySession: Object.fromEntries(Object.entries(state.snapshotCursorBySession).filter(([id2]) => !ids.has(id2))),
3878
+ eventsBySeq: Object.fromEntries(Object.entries(state.eventsBySeq).filter(([, item]) => !item.sessionId || !ids.has(item.sessionId)))
3879
+ };
3880
+ }
3881
+ function upsertInput(state, input) {
3882
+ if (!input) return state;
3883
+ const bucket = cloneBucket(state.buckets[input.sessionId]);
3884
+ bucket.inputs = upsertSorted(bucket.inputs, input, (row) => row.seq);
3885
+ return { ...state, buckets: { ...state.buckets, [input.sessionId]: bucket } };
3886
+ }
3887
+ function upsertMessage(state, message) {
3888
+ if (!message) return state;
3889
+ const bucket = cloneBucket(state.buckets[message.sessionId]);
3890
+ bucket.messages = upsertSorted(bucket.messages, message, (row) => row.seq);
3891
+ return { ...state, buckets: { ...state.buckets, [message.sessionId]: bucket } };
3892
+ }
3893
+ function replaceTranscript(state, event) {
3894
+ const sessionId = event.sessionId;
3895
+ if (!sessionId) return state;
3896
+ const messages = Array.isArray(event.payload.messages) ? event.payload.messages.filter((row) => !!row && typeof row === "object" && !Array.isArray(row) && typeof row.id === "string") : [];
3897
+ const parts = Array.isArray(event.payload.parts) ? event.payload.parts.filter((row) => !!row && typeof row === "object" && !Array.isArray(row) && typeof row.id === "string") : [];
3898
+ const bucket = cloneBucket(state.buckets[sessionId]);
3899
+ const partsByMessageId = {};
3900
+ for (const part of parts) {
3901
+ const rows = partsByMessageId[part.messageId] ?? [];
3902
+ rows.push(part);
3903
+ partsByMessageId[part.messageId] = rows;
3904
+ }
3905
+ for (const rows of Object.values(partsByMessageId)) rows.sort((a, b) => a.seq - b.seq);
3906
+ bucket.messages = [...messages].sort((a, b) => a.seq - b.seq);
3907
+ bucket.partsByMessageId = partsByMessageId;
3908
+ if (bucket.session) {
3909
+ bucket.session = {
3910
+ ...bucket.session,
3911
+ updatedAt: Math.max(bucket.session.updatedAt, event.createdAt)
3912
+ };
3913
+ }
3914
+ const sessions = bucket.session ? { ...state.sessions, [sessionId]: bucket.session } : state.sessions;
3915
+ return {
3916
+ ...state,
3917
+ sessions,
3918
+ sessionOrder: sortSessionOrder(sessions),
3919
+ buckets: { ...state.buckets, [sessionId]: bucket }
3920
+ };
3921
+ }
3922
+ function upsertPart(state, part) {
3923
+ if (!part) return state;
3924
+ const bucket = cloneBucketForPartWrite(state.buckets[part.sessionId]);
3925
+ const existing = bucket.partsByMessageId[part.messageId] ?? [];
3926
+ bucket.partsByMessageId = {
3927
+ ...bucket.partsByMessageId,
3928
+ [part.messageId]: upsertSorted(existing, part, (row) => row.seq)
3929
+ };
3930
+ return { ...state, buckets: { ...state.buckets, [part.sessionId]: bucket } };
3931
+ }
3932
+ function appendPartDelta(state, event) {
3933
+ const sessionId = typeof event.payload.sessionId === "string" ? event.payload.sessionId : event.sessionId;
3934
+ const messageId = typeof event.payload.messageId === "string" ? event.payload.messageId : void 0;
3935
+ const partId = typeof event.payload.partId === "string" ? event.payload.partId : void 0;
3936
+ const field = event.payload.field;
3937
+ const delta = typeof event.payload.delta === "string" ? event.payload.delta : void 0;
3938
+ if (field !== "text" && field !== "reasoning") return state;
3939
+ if (!sessionId || !messageId || !partId || delta === void 0) return state;
3940
+ const bucket = cloneBucketForPartWrite(state.buckets[sessionId]);
3941
+ const currentParts = bucket.partsByMessageId[messageId] ?? [];
3942
+ const index = currentParts.findIndex((part) => part.id === partId);
3943
+ const nextParts = [...currentParts];
3944
+ if (index >= 0) {
3945
+ const current = nextParts[index];
3946
+ if (isSupersededModelPart(current)) return state;
3947
+ nextParts[index] = {
3948
+ ...current,
3949
+ text: `${current.text ?? ""}${delta}`,
3950
+ updatedAt: Math.max(current.updatedAt, event.createdAt)
3951
+ };
3952
+ } else {
3953
+ const seq = currentParts.reduce((max, part) => Math.max(max, part.seq), 0) + 1;
3954
+ nextParts.push({
3955
+ id: partId,
3956
+ sessionId,
3957
+ messageId,
3958
+ seq,
3959
+ type: field === "reasoning" ? "reasoning" : "text",
3960
+ status: "running",
3961
+ text: delta,
3962
+ metadata: {},
3963
+ createdAt: event.createdAt,
3964
+ updatedAt: event.createdAt
3965
+ });
3966
+ }
3967
+ const sortedParts = index >= 0 ? nextParts : nextParts.sort((a, b) => a.seq - b.seq);
3968
+ bucket.partsByMessageId = {
3969
+ ...bucket.partsByMessageId,
3970
+ [messageId]: sortedParts
3971
+ };
3972
+ return { ...state, buckets: { ...state.buckets, [sessionId]: bucket } };
3973
+ }
3974
+ function upsertRun(state, run) {
3975
+ if (!run) return state;
3976
+ const bucket = cloneBucket(state.buckets[run.sessionId]);
3977
+ bucket.runs = { ...bucket.runs, [run.id]: run };
3978
+ const session = refreshSessionStatusFromRuns(bucket.session, bucket.runs, run.updatedAt);
3979
+ bucket.session = session;
3980
+ const sessions = session ? { ...state.sessions, [run.sessionId]: session } : state.sessions;
3981
+ return {
3982
+ ...state,
3983
+ sessions,
3984
+ sessionOrder: session ? sortSessionOrder(sessions) : state.sessionOrder,
3985
+ buckets: { ...state.buckets, [run.sessionId]: bucket }
3986
+ };
3987
+ }
3988
+ function upsertRunAttempt(state, attempt) {
3989
+ if (!attempt) return state;
3990
+ const run = Object.values(state.buckets).flatMap((bucket2) => Object.values(bucket2.runs)).find((candidate) => candidate.id === attempt.runId);
3991
+ if (!run) return state;
3992
+ const bucket = cloneBucket(state.buckets[run.sessionId]);
3993
+ bucket.attempts = { ...bucket.attempts, [attempt.id]: attempt };
3994
+ return { ...state, buckets: { ...state.buckets, [run.sessionId]: bucket } };
3995
+ }
3996
+ function refreshSessionStatusFromRuns(session, runs, updatedAt) {
3997
+ if (!session || session.status === "archived" || session.status === "closing") return session;
3998
+ const running = Object.values(runs).some(
3999
+ (candidate) => candidate.status === "pending" || candidate.status === "running"
4000
+ );
4001
+ return {
4002
+ ...session,
4003
+ status: running ? "running" : "idle",
4004
+ updatedAt: Math.max(session.updatedAt, updatedAt)
4005
+ };
4006
+ }
4007
+ function upsertPermission(state, request) {
4008
+ if (!request) return state;
4009
+ const bucket = cloneBucket(state.buckets[request.sessionId]);
4010
+ bucket.permissions = { ...bucket.permissions, [request.id]: request };
4011
+ return { ...state, buckets: { ...state.buckets, [request.sessionId]: bucket } };
4012
+ }
4013
+ function upsertTask(state, task) {
4014
+ if (!task) return state;
4015
+ const bucket = cloneBucket(state.buckets[task.sessionId]);
4016
+ bucket.tasks = { ...bucket.tasks, [task.id]: task };
4017
+ return { ...state, buckets: { ...state.buckets, [task.sessionId]: bucket } };
4018
+ }
4019
+ function cloneBucket(bucket) {
4020
+ return {
4021
+ ...bucket?.goal !== void 0 ? { goal: bucket.goal } : {},
4022
+ session: bucket?.session,
4023
+ inputs: bucket?.inputs ? [...bucket.inputs] : [],
4024
+ messages: bucket?.messages ? [...bucket.messages] : [],
4025
+ partsByMessageId: bucket?.partsByMessageId ? Object.fromEntries(Object.entries(bucket.partsByMessageId).map(([id2, parts]) => [id2, [...parts]])) : {},
4026
+ runs: bucket?.runs ? { ...bucket.runs } : {},
4027
+ attempts: bucket?.attempts ? { ...bucket.attempts } : {},
4028
+ tasks: bucket?.tasks ? { ...bucket.tasks } : {},
4029
+ permissions: bucket?.permissions ? { ...bucket.permissions } : {}
4030
+ };
4031
+ }
4032
+ function cloneBucketForPartWrite(bucket) {
4033
+ return {
4034
+ ...bucket?.goal !== void 0 ? { goal: bucket.goal } : {},
4035
+ session: bucket?.session,
4036
+ inputs: bucket?.inputs ?? [],
4037
+ messages: bucket?.messages ?? [],
4038
+ partsByMessageId: bucket?.partsByMessageId ?? {},
4039
+ runs: bucket?.runs ?? {},
4040
+ attempts: bucket?.attempts ?? {},
4041
+ tasks: bucket?.tasks ?? {},
4042
+ permissions: bucket?.permissions ?? {}
4043
+ };
4044
+ }
4045
+ function upsertSorted(rows, row, sortKey) {
4046
+ const without = rows.filter((existing) => existing.id !== row.id);
4047
+ without.push(row);
4048
+ return without.sort((a, b) => sortKey(a) - sortKey(b));
4049
+ }
4050
+ function sortSessionOrder(sessions) {
4051
+ return Object.values(sessions).sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id)).map((session) => session.id);
4052
+ }
4053
+
4054
+ // src/state/selectors.ts
4055
+ function selectSessionMessagesWithParts(bucket) {
4056
+ if (!bucket) return [];
4057
+ return [...bucket.messages].sort((a, b) => a.seq - b.seq).map((message) => ({
4058
+ message,
4059
+ parts: [...bucket.partsByMessageId[message.id] ?? []].sort((a, b) => a.seq - b.seq)
4060
+ }));
4061
+ }
4062
+ function selectVisibleSessionMessagesWithParts(bucket) {
4063
+ return selectSessionMessagesWithParts(bucket).map(({ message, parts }) => ({
4064
+ message,
4065
+ parts: parts.filter((part) => !isSupersededModelPart(part))
4066
+ })).filter(
4067
+ ({ message, parts }) => parts.length > 0 || message.role !== "assistant"
4068
+ );
4069
+ }
4070
+ function selectSessionInputs(bucket) {
4071
+ if (!bucket) return [];
4072
+ return [...bucket.inputs].sort((a, b) => a.seq - b.seq);
4073
+ }
4074
+ function selectSessionOrderedMessages(bucket) {
4075
+ if (!bucket) return [];
4076
+ return [...bucket.messages].sort((a, b) => a.seq - b.seq);
4077
+ }
4078
+ function selectSessionParts(bucket) {
4079
+ if (!bucket) return [];
4080
+ return Object.values(bucket.partsByMessageId).flat().sort((a, b) => a.seq - b.seq);
4081
+ }
4082
+ function selectSessionRuns(bucket) {
4083
+ if (!bucket) return [];
4084
+ return Object.values(bucket.runs);
4085
+ }
4086
+ function selectSessionModelRetry(bucket) {
4087
+ if (!bucket) return void 0;
4088
+ const active = Object.values(bucket.runs).filter((run) => run.status === "running" || run.status === "pending").sort((a, b) => b.updatedAt - a.updatedAt);
4089
+ for (const run of active) {
4090
+ const state = readSessionModelRetryState(run.metadata);
4091
+ if (state) return state;
4092
+ }
4093
+ return void 0;
4094
+ }
4095
+ function selectSessionModelUsage(bucket) {
4096
+ if (!bucket) return void 0;
4097
+ const runs = Object.values(bucket.runs).sort((a, b) => b.updatedAt - a.updatedAt);
4098
+ for (const run of runs) {
4099
+ const usage = readSessionModelUsage(run.metadata);
4100
+ if (usage) return usage;
4101
+ }
4102
+ return void 0;
4103
+ }
4104
+ function selectSessionTasks(bucket) {
4105
+ if (!bucket) return [];
4106
+ return Object.values(bucket.tasks);
4107
+ }
4108
+ function selectSessionPermissions(bucket) {
4109
+ if (!bucket) return [];
4110
+ return Object.values(bucket.permissions);
4111
+ }
4112
+ function selectFirstPendingPermission(state, sessionId) {
4113
+ if (!sessionId) return void 0;
4114
+ const bucket = state.buckets[sessionId];
4115
+ if (!bucket) return void 0;
4116
+ return Object.values(bucket.permissions).filter((request) => request.status === "pending").sort((a, b) => a.createdAt - b.createdAt).at(0);
4117
+ }
4118
+
4119
+ // src/state/session-stream-state.ts
4120
+ function applySessionStreamEvent(state, event) {
4121
+ if (event.seq <= state.lastSeq) return state;
4122
+ const next = applyEvent({ ...state, eventsBySeq: {} }, event);
4123
+ return { ...next, eventsBySeq: {} };
4124
+ }
4125
+ function applySessionStreamSnapshot(state, snapshot) {
4126
+ if (snapshot.cursor < state.lastSeq) return state;
4127
+ return { ...applySessionSnapshot(state, snapshot), eventsBySeq: {} };
4128
+ }
4129
+
4130
+ // src/state/sync.ts
4131
+ var DEFAULT_RECONNECT_DELAY_MS = (attempt) => Math.min(3e4, 250 * 2 ** Math.max(0, attempt));
4132
+ var DEFAULT_SESSION_IDLE_TIMEOUT_MS = 6e4;
4133
+ var EVENT_REPLAY_PAGE_SIZE = 128;
4134
+ function hydrateState(events) {
4135
+ return applyEvents(createInitialClientState(), events);
4136
+ }
4137
+ async function* syncEvents(client, options = {}) {
4138
+ yield* runEventSync(client, {
4139
+ ...options,
4140
+ // 会话迭代接口从完整快照开始;只有全局 replay 使用调用方游标。
4141
+ cursor: options.sessionId ? void 0 : options.cursor,
4142
+ idleTimeoutMs: options.idleTimeoutMs ?? DEFAULT_SESSION_IDLE_TIMEOUT_MS
4143
+ });
4144
+ }
4145
+ async function* runEventSync(client, options, initialState = createInitialClientState(), onLiveEvent) {
4146
+ let state = initialState;
4147
+ let cursor = Math.max(0, options.cursor ?? 0, state.lastSeq);
4148
+ let attempt = 0;
4149
+ const signal = options.signal;
4150
+ const delayMs = options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS;
4151
+ const reduce = options.sessionId ? applySessionStreamEvent : options.globalReducer ?? applyEvent;
4152
+ if (signal?.aborted) return;
4153
+ const refreshSession = async (initial) => {
4154
+ const snapshot = await client.sessions.getState(options.sessionId, {
4155
+ signal,
4156
+ partView: options.partView
4157
+ });
4158
+ if (signal?.aborted) return;
4159
+ const next = initial ? applySessionSnapshot(state, snapshot) : applySessionStreamSnapshot(state, snapshot);
4160
+ state = Object.keys(next.eventsBySeq).length ? { ...next, eventsBySeq: {} } : next;
4161
+ cursor = Math.max(cursor, snapshot.cursor, state.lastSeq);
4162
+ };
4163
+ const replayHistory = async function* (initial) {
4164
+ let pageCursor = cursor;
4165
+ while (!signal?.aborted) {
4166
+ const page = await client.events.list({
4167
+ cursor: pageCursor,
4168
+ limit: EVENT_REPLAY_PAGE_SIZE,
4169
+ partView: options.partView,
4170
+ signal
4171
+ });
4172
+ if (signal?.aborted) return;
4173
+ for (const event of page) {
4174
+ if (signal?.aborted) return;
4175
+ const before = state;
4176
+ state = reduce(state, event);
4177
+ cursor = Math.max(cursor, event.seq, state.lastSeq);
4178
+ if (initial || state !== before) yield { event, state, source: "replay" };
4179
+ }
4180
+ const through = page.at(-1)?.seq ?? pageCursor;
4181
+ if (page.length < EVENT_REPLAY_PAGE_SIZE || through <= pageCursor) return;
4182
+ pageCursor = through;
4183
+ }
4184
+ };
4185
+ try {
4186
+ if (options.sessionId) {
4187
+ await refreshSession(true);
4188
+ } else {
4189
+ yield* replayHistory(true);
4190
+ }
4191
+ if (signal?.aborted) return;
4192
+ yield { state, source: "snapshot" };
4193
+ let needsSnapshot = false;
4194
+ while (!signal?.aborted) {
4195
+ try {
4196
+ if (needsSnapshot) {
4197
+ await refreshSession(false);
4198
+ if (signal?.aborted) return;
4199
+ needsSnapshot = false;
4200
+ yield { state, source: "snapshot" };
4201
+ }
4202
+ if (signal?.aborted) return;
4203
+ for await (const event of client.events.stream({
4204
+ cursor,
4205
+ sessionId: options.sessionId,
4206
+ signal,
4207
+ partView: options.partView,
4208
+ transportReconnect: false,
4209
+ idleTimeoutMs: options.idleTimeoutMs
4210
+ })) {
4211
+ if (signal?.aborted) return;
4212
+ onLiveEvent?.();
4213
+ if (signal?.aborted) return;
4214
+ attempt = 0;
4215
+ if (event.seq > cursor + 1 && !options.sessionId) {
4216
+ yield* replayHistory(false);
4217
+ }
4218
+ if (signal?.aborted) return;
4219
+ const before = state;
4220
+ state = reduce(state, event);
4221
+ cursor = Math.max(cursor, event.seq, state.lastSeq);
4222
+ if (state !== before) yield { event, state, source: "live" };
4223
+ }
4224
+ } catch (error) {
4225
+ if (error instanceof UnsupportedSessionEventSchemaVersionError) throw error;
4226
+ if (isAbortError(error) || signal?.aborted) return;
4227
+ if (options.shouldRetry?.(error) === false) throw error;
4228
+ if (error instanceof BobanNomiApiError && error.status >= 400 && error.status < 500 && ![408, 425, 429].includes(error.status)) throw error;
4229
+ }
4230
+ if (signal?.aborted) return;
4231
+ needsSnapshot = Boolean(options.sessionId);
4232
+ yield { state, source: "reconnecting" };
4233
+ if (!await waitForReconnect2(delayMs(attempt), signal)) return;
4234
+ attempt += 1;
4235
+ }
4236
+ } catch (error) {
4237
+ if (!isAbortError(error) && !signal?.aborted) throw error;
4238
+ }
4239
+ }
4240
+ async function waitForReconnect2(ms, signal) {
4241
+ if (signal?.aborted) return false;
4242
+ if (ms <= 0) return true;
4243
+ return new Promise((resolve) => {
4244
+ const onAbort = () => {
4245
+ clearTimeout(timer);
4246
+ resolve(false);
4247
+ };
4248
+ const timer = setTimeout(() => {
4249
+ signal?.removeEventListener("abort", onAbort);
4250
+ resolve(!signal?.aborted);
4251
+ }, ms);
4252
+ signal?.addEventListener("abort", onAbort, { once: true });
4253
+ });
4254
+ }
4255
+ function isAbortError(error) {
4256
+ return Boolean(error && typeof error === "object" && "name" in error && error.name === "AbortError");
4257
+ }
4258
+
4259
+ // src/state/session-sync-controller.ts
4260
+ var SessionSyncController = class {
4261
+ options;
4262
+ initialCursor;
4263
+ generation;
4264
+ abortController = new AbortController();
4265
+ state;
4266
+ status = "idle";
4267
+ running = false;
4268
+ constructor(options) {
4269
+ this.options = { ...options };
4270
+ this.state = options.initialState ?? createInitialClientState();
4271
+ if ((options.cursor ?? 0) > 0 && !options.initialState) {
4272
+ throw new Error("A non-zero cursor requires initialState so durable state is not skipped");
4273
+ }
4274
+ this.initialCursor = Math.max(0, options.cursor ?? 0, this.state.lastSeq);
4275
+ this.generation = options.generation ?? 0;
4276
+ if (options.signal?.aborted) {
4277
+ this.abortController.abort(options.signal.reason);
4278
+ } else {
4279
+ options.signal?.addEventListener("abort", () => this.abort(options.signal?.reason), { once: true });
4280
+ }
4281
+ }
4282
+ get currentStatus() {
4283
+ return this.status;
4284
+ }
4285
+ get currentState() {
4286
+ return this.state;
4287
+ }
4288
+ get currentGeneration() {
4289
+ return this.generation;
4290
+ }
4291
+ get signal() {
4292
+ return this.abortController.signal;
4293
+ }
4294
+ abort(reason) {
4295
+ this.abortController.abort(reason);
4296
+ }
4297
+ setStatus(status) {
4298
+ if (this.status === status) return;
4299
+ this.status = status;
4300
+ this.options.onStatusChange?.(status, this.generation);
4301
+ }
4302
+ /** 不可恢复错误通过 onError 上报;取消和正常结束都 resolve。 */
4303
+ async start() {
4304
+ if (this.running) return;
4305
+ const signal = this.signal;
4306
+ if (signal.aborted) {
4307
+ this.setStatus("idle");
4308
+ return;
4309
+ }
4310
+ this.running = true;
4311
+ try {
4312
+ this.setStatus("connecting");
4313
+ for await (const update of runEventSync(this.options.client, {
4314
+ sessionId: this.options.sessionId,
4315
+ cursor: this.initialCursor,
4316
+ signal,
4317
+ reconnectDelayMs: this.options.reconnectDelayMs,
4318
+ shouldRetry: this.options.shouldRetry
4319
+ }, this.state, () => this.setStatus("connected"))) {
4320
+ if (signal.aborted) return;
4321
+ this.state = update.state;
4322
+ if (update.source === "reconnecting") this.setStatus("reconnecting");
4323
+ else if (update.source !== "replay") this.setStatus("connected");
4324
+ if (signal.aborted) return;
4325
+ if (update.source === "snapshot" && !this.options.sessionId) continue;
4326
+ this.options.onUpdate?.(update, this.generation);
4327
+ }
4328
+ } catch (error) {
4329
+ if (!signal.aborted && !(error instanceof Error && error.name === "AbortError")) {
4330
+ this.setStatus("error");
4331
+ this.options.onError?.(error, this.generation);
4332
+ }
4333
+ } finally {
4334
+ this.running = false;
4335
+ if (signal.aborted && this.status !== "error") this.setStatus("idle");
4336
+ }
4337
+ }
4338
+ };
4339
+
4340
+ // src/state/wait-for-run.ts
4341
+ async function waitForRun(client, options) {
4342
+ options.signal?.throwIfAborted();
4343
+ for await (const update of syncEvents(client, { sessionId: options.sessionId, signal: options.signal })) {
4344
+ options.signal?.throwIfAborted();
4345
+ const bucket = update.state.buckets[options.sessionId];
4346
+ const run = bucket?.runs[options.runId];
4347
+ if (!run || run.status === "pending" || run.status === "running") continue;
4348
+ return {
4349
+ run,
4350
+ messages: selectVisibleSessionMessagesWithParts(bucket).filter((item) => item.message.runId === options.runId)
4351
+ };
4352
+ }
4353
+ options.signal?.throwIfAborted();
4354
+ throw new Error(`Run ${options.runId} observation ended before a terminal state was available`);
4355
+ }
4356
+
4357
+ // src/configuration/runtime-configuration.ts
4358
+ function normalizeApprovalMode(value) {
4359
+ if (value === "ask" || value === "auto_review" || value === "full_access") return value;
4360
+ if (value === "default" || value === "plan") return "ask";
4361
+ if (value === "full_auto") return "auto_review";
4362
+ return void 0;
4363
+ }
4364
+ function isWorkMode(value) {
4365
+ return value === "execute" || value === "plan";
4366
+ }
4367
+ function displayPermissionMode(approval, work) {
4368
+ return work === "plan" ? "plan" : approval === "full_access" ? "full_auto" : "default";
4369
+ }
4370
+ function stringValue(value) {
4371
+ return typeof value === "string" && value.trim() ? value : void 0;
4372
+ }
4373
+ function numberValue2(value) {
4374
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
4375
+ }
4376
+ function stringArrayValue(value) {
4377
+ if (!Array.isArray(value)) return void 0;
4378
+ const items = value.filter((item) => typeof item === "string" && item.trim().length > 0);
4379
+ return items.length > 0 ? items : void 0;
4380
+ }
4381
+ function effortValue2(value) {
4382
+ if (typeof value !== "string") return void 0;
4383
+ const trimmed = value.trim();
4384
+ return trimmed.length > 0 ? trimmed : "";
4385
+ }
4386
+ function sessionModeValue2(value) {
4387
+ return value === "coordinator" ? "coordinator" : value === "direct" ? "direct" : void 0;
4388
+ }
4389
+ function apiFormatValue2(value) {
4390
+ return value === "anthropic" || value === "openai" ? value : void 0;
4391
+ }
4392
+ function booleanValue2(value) {
4393
+ return typeof value === "boolean" ? value : void 0;
4394
+ }
4395
+ function readSessionRuntimeConfig(session, defaults) {
4396
+ const runtime = readRuntimeMetadata2(session.metadata);
4397
+ const model = stringValue(runtime.model);
4398
+ if (!model) {
4399
+ throw new Error(`Session runtime config is missing metadata.runtime.model: ${session.id}`);
4400
+ }
4401
+ const approvalMode = normalizeApprovalMode(runtime.approvalMode ?? runtime.permissionMode) ?? defaults?.approvalMode ?? normalizeApprovalMode(defaults?.permissionMode);
4402
+ const workMode = isWorkMode(runtime.workMode) ? runtime.workMode : runtime.permissionMode === "plan" ? "plan" : defaults?.workMode ?? "execute";
4403
+ return {
4404
+ model,
4405
+ ...approvalMode ? { approvalMode } : {},
4406
+ ...approvalMode || isWorkMode(runtime.workMode) || defaults?.workMode ? { workMode } : {},
4407
+ ...stringValue(runtime.provider) ?? defaults?.provider ? { provider: stringValue(runtime.provider) ?? defaults?.provider } : {},
4408
+ ...stringValue(runtime.baseUrl) ?? defaults?.baseUrl ? { baseUrl: stringValue(runtime.baseUrl) ?? defaults?.baseUrl } : {},
4409
+ ...apiFormatValue2(runtime.apiFormat) ?? defaults?.apiFormat ? { apiFormat: apiFormatValue2(runtime.apiFormat) ?? defaults?.apiFormat } : {},
4410
+ ...approvalMode ? { permissionMode: displayPermissionMode(approvalMode, workMode) } : {},
4411
+ ...(numberValue2(runtime.maxTurns) ?? defaults?.maxTurns) !== void 0 ? { maxTurns: numberValue2(runtime.maxTurns) ?? defaults?.maxTurns } : {},
4412
+ ...effortValue2(runtime.effort) ?? defaults?.effort ? { effort: effortValue2(runtime.effort) ?? defaults?.effort } : {},
4413
+ ...sessionModeValue2(runtime.sessionMode) ?? defaults?.sessionMode ? { sessionMode: sessionModeValue2(runtime.sessionMode) ?? defaults?.sessionMode } : {},
4414
+ ...stringValue(runtime.systemPrompt) ?? defaults?.systemPrompt ? { systemPrompt: stringValue(runtime.systemPrompt) ?? defaults?.systemPrompt } : {},
4415
+ ...stringArrayValue(runtime.allowedTools) ?? defaults?.allowedTools ? { allowedTools: stringArrayValue(runtime.allowedTools) ?? defaults?.allowedTools } : {},
4416
+ ...stringArrayValue(runtime.disallowedTools) ?? defaults?.disallowedTools ? { disallowedTools: stringArrayValue(runtime.disallowedTools) ?? defaults?.disallowedTools } : {},
4417
+ ...(booleanValue2(runtime.pluginsEnabled) ?? defaults?.pluginsEnabled) !== void 0 ? { pluginsEnabled: booleanValue2(runtime.pluginsEnabled) ?? defaults?.pluginsEnabled } : {},
4418
+ ...(booleanValue2(runtime.pluginAutoSelectionEnabled) ?? defaults?.pluginAutoSelectionEnabled) !== void 0 ? { pluginAutoSelectionEnabled: booleanValue2(runtime.pluginAutoSelectionEnabled) ?? defaults?.pluginAutoSelectionEnabled } : {}
4419
+ };
4420
+ }
4421
+ function patchSessionRuntimeMetadata(metadata, patch) {
4422
+ const runtime = {
4423
+ ...readRuntimeMetadata2(metadata),
4424
+ ...stripUndefined(patch)
4425
+ };
4426
+ if (runtime.permissionMode !== void 0 && (patch.approvalMode !== void 0 || patch.workMode !== void 0)) {
4427
+ runtime.approvalMode ??= normalizeApprovalMode(runtime.permissionMode) ?? "ask";
4428
+ runtime.workMode ??= runtime.permissionMode === "plan" ? "plan" : "execute";
4429
+ delete runtime.permissionMode;
4430
+ }
4431
+ readRuntimeMetadata2({ runtime });
4432
+ return {
4433
+ ...metadata,
4434
+ runtime
4435
+ };
4436
+ }
4437
+ function stripUndefined(input) {
4438
+ return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0));
4439
+ }
4440
+ export {
4441
+ AttachmentResource,
4442
+ BobanNomiApiError,
4443
+ BobanNomiClient,
4444
+ CURRENT_PROTOCOL_VERSION,
4445
+ EventResource,
4446
+ FilesResource,
4447
+ HttpTransport,
4448
+ IncompatibleProtocolError,
4449
+ JobResource,
4450
+ PermissionResource,
4451
+ ProtocolClient,
4452
+ ProtocolValidationError,
4453
+ RuntimeResource,
4454
+ ScheduleResource,
4455
+ SessionManagementResource,
4456
+ SessionResource,
4457
+ SessionSyncController,
4458
+ SseTransport,
4459
+ UnsupportedSessionEventSchemaVersionError,
4460
+ applyEvent,
4461
+ applyEvents,
4462
+ applySessionSnapshot,
4463
+ attachmentRangeHeader,
4464
+ checkProtocolCompatibility,
4465
+ createInitialClientState,
4466
+ createPromptRequestId,
4467
+ hydrateState,
4468
+ isSupersededModelPart,
4469
+ isWorkMode,
4470
+ normalizeApprovalMode,
4471
+ normalizeDaemonBaseUrl,
4472
+ parseCreateSessionGoalInput2 as parseCreateSessionGoalInput,
4473
+ parseGoalActionInput2 as parseGoalActionInput,
4474
+ parseMcpCallResultData,
4475
+ parseUpdateSessionGoalInput2 as parseUpdateSessionGoalInput,
4476
+ patchSessionRuntimeMetadata,
4477
+ readPluginUiInstance,
4478
+ readRuntimeMetadata2 as readRuntimeMetadata,
4479
+ readSessionModelRetryState,
4480
+ readSessionModelUsage,
4481
+ readSessionRuntimeConfig,
4482
+ readWorkspaceChangesMetadata,
4483
+ responseArray2 as responseArray,
4484
+ responseField,
4485
+ selectFirstPendingPermission,
4486
+ selectSessionInputs,
4487
+ selectSessionMessagesWithParts,
4488
+ selectSessionModelRetry,
4489
+ selectSessionModelUsage,
4490
+ selectSessionOrderedMessages,
4491
+ selectSessionParts,
4492
+ selectSessionPermissions,
4493
+ selectSessionRuns,
4494
+ selectSessionTasks,
4495
+ selectVisibleSessionMessagesWithParts,
4496
+ streamServerSentEvents,
4497
+ supportsFeature,
4498
+ syncEvents,
4499
+ waitForRun
4500
+ };
4501
+ //# sourceMappingURL=index.js.map