@codelia/runtime 0.1.81 → 0.1.82

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.
@@ -2,6 +2,7 @@ import {
2
2
  AgentMailbox,
3
3
  AuthResolver,
4
4
  AuthStore,
5
+ OPENAI_OAUTH_BASE_URL,
5
6
  PermissionService,
6
7
  READ_ONLY_TOOLS,
7
8
  RuntimeState,
@@ -12,8 +13,11 @@ import {
12
13
  appendPermissionAllowRules,
13
14
  appendReadMetadata,
14
15
  assertExpectedContentHash,
16
+ buildConfiguredModelRegistry,
15
17
  buildSystemPermissions,
16
18
  clipUtf8,
19
+ configuredModelSpecs,
20
+ configuredProviders,
17
21
  createCommunicationTools,
18
22
  createRuntimeModel,
19
23
  createSubagentWriteTools,
@@ -23,6 +27,7 @@ import {
23
27
  generatePkce,
24
28
  generateState,
25
29
  getProcessIdentity,
30
+ getResponsesProvider,
26
31
  isDebugEnabled,
27
32
  isProcessEnabled,
28
33
  isTerminalTaskState,
@@ -38,8 +43,10 @@ import {
38
43
  requestUiConfirm,
39
44
  requestUiPick,
40
45
  requestUiPrompt,
46
+ resolveConfiguredReasoning,
41
47
  resolveExecutionEnvironmentConfig,
42
48
  resolveFastMode,
49
+ resolveImageGenerationConfig,
43
50
  resolveMcpServers,
44
51
  resolveModelConfig,
45
52
  resolvePermissionsConfig,
@@ -56,6 +63,7 @@ import {
56
63
  sendResult,
57
64
  sendRunContext,
58
65
  sendRunDiagnostics,
66
+ sendRunMetrics,
59
67
  sendRunStatus,
60
68
  sendRunStatusAsync,
61
69
  shouldAutoOpenOAuthBrowser,
@@ -63,9 +71,10 @@ import {
63
71
  subagentBootstrapSchema,
64
72
  subagentModelSelectionSchema,
65
73
  subagentNameSchema,
74
+ updateImageGeneration,
66
75
  updateModel,
67
76
  updateTuiTheme
68
- } from "./chunk-227ALRI4.js";
77
+ } from "./chunk-CGWVQ7AE.js";
69
78
 
70
79
  // src/runtime.ts
71
80
  import {
@@ -73,11 +82,1097 @@ import {
73
82
  SessionStateStoreImpl as SessionStateStoreImpl2
74
83
  } from "@codelia/storage";
75
84
 
85
+ // src/image-generation/local-store.ts
86
+ import { createHash } from "crypto";
87
+ import path from "path";
88
+ import { ImageArtifactStore, resolveStoragePaths } from "@codelia/storage";
89
+ function createLocalImageStore(workspaceRoot) {
90
+ const scope = createHash("sha256").update(path.resolve(workspaceRoot)).digest("hex");
91
+ return new ImageArtifactStore(
92
+ path.join(resolveStoragePaths().sessionsDir, "image-artifacts", scope)
93
+ );
94
+ }
95
+
96
+ // src/image-generation/route.ts
97
+ import {
98
+ OPENAI_IMAGE_MODELS,
99
+ OPENAI_CODEX_IMAGE_MODELS
100
+ } from "@codelia/config";
101
+
102
+ // src/image-generation/http.ts
103
+ var ImageGenerationError = class extends Error {
104
+ };
105
+ async function imageJson(url, init, fetcher = fetch, maxBytes = 12 * 1024 * 1024, timeoutMs = 18e4) {
106
+ const timeout = AbortSignal.timeout(timeoutMs);
107
+ const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
108
+ try {
109
+ const response = await fetcher(url, { ...init, signal, redirect: "error" });
110
+ if (!response.ok) {
111
+ await response.body?.cancel();
112
+ throw new ImageGenerationError(
113
+ `Image API request failed (HTTP ${response.status}); no fallback or automatic retry was attempted.`
114
+ );
115
+ }
116
+ if (!response.body || Number(response.headers.get("content-length") ?? 0) > maxBytes) {
117
+ await response.body?.cancel();
118
+ throw new ImageGenerationError(
119
+ "Image API response exceeded the size limit or was empty."
120
+ );
121
+ }
122
+ const reader = response.body.getReader();
123
+ const chunks = [];
124
+ let size = 0;
125
+ const cancelReader = () => {
126
+ void reader.cancel().catch(() => {
127
+ });
128
+ };
129
+ signal.addEventListener("abort", cancelReader, { once: true });
130
+ try {
131
+ while (true) {
132
+ signal.throwIfAborted();
133
+ const chunk = await reader.read();
134
+ signal.throwIfAborted();
135
+ if (chunk.done) break;
136
+ size += chunk.value.length;
137
+ if (size > maxBytes)
138
+ throw new ImageGenerationError(
139
+ "Image API response exceeded the size limit."
140
+ );
141
+ chunks.push(chunk.value);
142
+ }
143
+ } finally {
144
+ signal.removeEventListener("abort", cancelReader);
145
+ await reader.cancel().catch(() => {
146
+ });
147
+ reader.releaseLock();
148
+ }
149
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
150
+ } catch (error) {
151
+ if (init.signal?.aborted)
152
+ throw new ImageGenerationError(
153
+ "Image request cancelled; the provider may already have charged for generation. No retry was attempted."
154
+ );
155
+ if (timeout.aborted)
156
+ throw new ImageGenerationError(
157
+ "Image request timed out; the provider may already have charged for generation. No retry was attempted."
158
+ );
159
+ if (error instanceof ImageGenerationError) throw error;
160
+ throw new ImageGenerationError(
161
+ "Image API transport or response failed; no fallback or automatic retry was attempted."
162
+ );
163
+ }
164
+ }
165
+
166
+ // src/image-generation/route.ts
167
+ var localImageAuth = {
168
+ storedKey: async (provider) => {
169
+ const auth = (await new AuthStore().load()).providers[provider];
170
+ return auth?.method === "api_key" ? auth.api_key : void 0;
171
+ },
172
+ env: (name) => process.env[name]?.trim() || void 0
173
+ };
174
+ async function resolveImageRoute(config, auth, chat) {
175
+ if (config.mode === "off") return null;
176
+ let provider;
177
+ let model;
178
+ let apiKey;
179
+ if (config.mode === "builtin") {
180
+ if (chat?.provider !== "openai")
181
+ throw new ImageGenerationError(
182
+ "builtin unavailable: select an OpenAI conversation connection and sign in first; no other provider or authentication route was selected."
183
+ );
184
+ if (chat.auth.method === "oauth") {
185
+ const oauth = chat.auth.oauth;
186
+ if (!oauth.access_token.trim())
187
+ throw new ImageGenerationError(
188
+ "Codex OAuth login is missing; sign in to OpenAI again. An API key is not required."
189
+ );
190
+ const o2 = config.provider_options?.openai;
191
+ return {
192
+ authMode: "codex_oauth",
193
+ provider: "openai",
194
+ model: o2?.model ?? OPENAI_CODEX_IMAGE_MODELS[0],
195
+ endpoint: `${OPENAI_OAUTH_BASE_URL}/images/generations`,
196
+ options: {
197
+ ...o2?.quality ? { quality: o2.quality } : {},
198
+ ...o2?.size ? { size: o2.size } : {}
199
+ },
200
+ ...oauth.account_id ? { accountId: oauth.account_id } : {},
201
+ getAccessToken: chat.getOpenAiAccessToken ?? (async () => {
202
+ if (oauth.expires_at <= Date.now() + 6e4)
203
+ throw new ImageGenerationError(
204
+ "Codex OAuth refresh is unavailable; sign in to OpenAI again. An API key is not required."
205
+ );
206
+ return { token: oauth.access_token, accountId: oauth.account_id };
207
+ })
208
+ };
209
+ }
210
+ if (auth.env("OPENAI_BASE_URL"))
211
+ throw new ImageGenerationError(
212
+ "builtin unavailable: the API-key conversation uses an unsupported base URL override; no endpoint fallback was attempted."
213
+ );
214
+ provider = "openai";
215
+ model = config.provider_options?.openai?.model ?? OPENAI_IMAGE_MODELS[0];
216
+ if (!OPENAI_IMAGE_MODELS.includes(model))
217
+ throw new ImageGenerationError(
218
+ "This selected builtin image model is only configured for Codex OAuth; select an API image model explicitly."
219
+ );
220
+ apiKey = chat.auth.api_key;
221
+ } else {
222
+ provider = config.provider;
223
+ model = config.model;
224
+ apiKey = config.api_key_env ? auth.env(config.api_key_env) : await auth.storedKey(provider) || auth.env(
225
+ provider === "openai" ? "OPENAI_API_KEY" : "OPENROUTER_API_KEY"
226
+ );
227
+ }
228
+ if (!apiKey?.trim())
229
+ throw new ImageGenerationError(
230
+ "missing_api_key: set the selected runtime API-key environment variable (OPENAI_API_KEY / OPENROUTER_API_KEY by default). Chat OAuth is preserved and never used for custom images."
231
+ );
232
+ const options = {};
233
+ if (provider === "openai") {
234
+ const o2 = config.provider_options?.openai;
235
+ if (o2?.quality) options.quality = o2.quality;
236
+ if (o2?.size) options.size = o2.size;
237
+ return {
238
+ authMode: "api_key",
239
+ provider,
240
+ model,
241
+ apiKey,
242
+ endpoint: "https://api.openai.com/v1/images/generations",
243
+ options
244
+ };
245
+ }
246
+ const o = config.provider_options?.openrouter;
247
+ if (!o?.endpoint)
248
+ throw new ImageGenerationError(
249
+ "Select an OpenRouter image endpoint with /image-model; automatic endpoint fallback is disabled."
250
+ );
251
+ if (o.quality) options.quality = o.quality;
252
+ if (o.resolution) options.resolution = o.resolution;
253
+ if (o.aspect_ratio) options.aspect_ratio = o.aspect_ratio;
254
+ return {
255
+ authMode: "api_key",
256
+ provider,
257
+ model,
258
+ apiKey,
259
+ endpoint: o.endpoint,
260
+ options
261
+ };
262
+ }
263
+
264
+ // src/image-generation/tools.ts
265
+ import {
266
+ defineTool,
267
+ ToolPermissionDenied
268
+ } from "@codelia/core";
269
+ import { z as z4 } from "zod";
270
+
271
+ // src/image-generation/adapter.ts
272
+ import { IMAGE_MAX_BYTES } from "@codelia/storage";
273
+ import { z as z3 } from "zod";
274
+
275
+ // src/image-generation/catalog.ts
276
+ import { z } from "zod";
277
+ var slug = z.string().max(160).regex(/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/);
278
+ var descriptor = z.union([
279
+ z.object({
280
+ type: z.literal("enum"),
281
+ values: z.array(z.string().max(100)).max(128)
282
+ }),
283
+ z.object({
284
+ type: z.literal("range"),
285
+ min: z.number().finite(),
286
+ max: z.number().finite()
287
+ }),
288
+ z.object({ type: z.literal("boolean") })
289
+ ]);
290
+ var endpointSchema = z.object({
291
+ provider_tag: slug.nullable(),
292
+ supported_parameters: z.record(z.string(), descriptor)
293
+ });
294
+ var ImageCatalog = class {
295
+ constructor(fetcher = fetch) {
296
+ this.fetcher = fetcher;
297
+ }
298
+ fetcher;
299
+ cached;
300
+ async list() {
301
+ if (this.cached && this.cached.expires > Date.now())
302
+ return { ...this.cached, stale: false };
303
+ try {
304
+ const raw = await imageJson(
305
+ "https://openrouter.ai/api/v1/images/models",
306
+ {},
307
+ this.fetcher,
308
+ 4 * 1024 * 1024,
309
+ 15e3
310
+ );
311
+ const parsed = z.object({
312
+ data: z.array(
313
+ z.object({
314
+ id: slug,
315
+ name: z.string().max(256),
316
+ architecture: z.object({
317
+ output_modalities: z.array(z.string())
318
+ })
319
+ })
320
+ ).max(2e3)
321
+ }).safeParse(raw);
322
+ if (!parsed.success)
323
+ throw new ImageGenerationError("Invalid image model catalog.");
324
+ const models = parsed.data.data.filter((m) => m.architecture.output_modalities.includes("image")).map((m) => ({
325
+ id: m.id,
326
+ name: [...m.name].filter((c) => c.charCodeAt(0) >= 32 && c.charCodeAt(0) !== 127).join("")
327
+ }));
328
+ this.cached = {
329
+ models,
330
+ fetched_at: (/* @__PURE__ */ new Date()).toISOString(),
331
+ expires: Date.now() + 3e5
332
+ };
333
+ return { ...this.cached, stale: false };
334
+ } catch (error) {
335
+ if (this.cached) return { ...this.cached, stale: true };
336
+ throw error;
337
+ }
338
+ }
339
+ async endpoints(model, signal) {
340
+ if (!slug.safeParse(model).success)
341
+ throw new ImageGenerationError("Invalid image model id.");
342
+ const raw = await imageJson(
343
+ `https://openrouter.ai/api/v1/images/models/${model.split("/").map(encodeURIComponent).join("/")}/endpoints`,
344
+ { signal },
345
+ this.fetcher,
346
+ 1024 * 1024,
347
+ 15e3
348
+ );
349
+ const parsed = z.object({ endpoints: z.array(endpointSchema).max(100) }).safeParse(raw);
350
+ if (!parsed.success)
351
+ throw new ImageGenerationError("Invalid image endpoint catalog.");
352
+ return parsed.data.endpoints.filter(
353
+ (e) => e.provider_tag && (!e.supported_parameters.output_format || acceptsParameter(e, "output_format", "png"))
354
+ );
355
+ }
356
+ };
357
+ function acceptsParameter(endpoint, key, value) {
358
+ const rule = endpoint.supported_parameters[key];
359
+ if (!rule) return false;
360
+ if (rule.type === "enum")
361
+ return typeof value === "string" && rule.values.includes(value);
362
+ if (rule.type === "range")
363
+ return typeof value === "number" && Number.isInteger(value) && value >= rule.min && value <= rule.max;
364
+ return true;
365
+ }
366
+
367
+ // src/image-generation/codex.ts
368
+ import { randomUUID } from "crypto";
369
+
370
+ // src/image-generation/references.ts
371
+ import { IMAGE_REFERENCE_MAX_COUNT } from "@codelia/shared-types";
372
+ import { imageSize } from "image-size";
373
+ import { z as z2 } from "zod";
374
+ var IMAGE_REFERENCE_MAX_BYTES = 8 * 1024 * 1024;
375
+ var IMAGE_REFERENCE_TOTAL_BYTES = 32 * 1024 * 1024;
376
+ var imageArtifactId = z2.string().regex(/^codelia-image-[0-9a-f-]{36}$/);
377
+ var imageSourceSchema = z2.discriminatedUnion("type", [
378
+ z2.object({
379
+ type: z2.literal("url"),
380
+ url: z2.url({ protocol: /^https?$/ }).max(8192).refine((value) => {
381
+ if (!URL.canParse(value)) return false;
382
+ const url = new URL(value);
383
+ return !url.username && !url.password && !url.hash;
384
+ }, "Image URL must not contain credentials or fragments").describe(
385
+ "Public direct PNG/JPEG/WebP URL on port 80/443, not a web page; no credentials or secrets. Downloaded in memory after approval; redirects and private network destinations are rejected."
386
+ )
387
+ }).strict(),
388
+ z2.object({
389
+ type: z2.literal("file"),
390
+ file_path: z2.string().min(1).max(4096).describe(
391
+ "Runtime-host image path; sandbox-bounded unless full-access. Original bytes are read after approval."
392
+ )
393
+ }).strict(),
394
+ z2.object({ type: z2.literal("artifact"), artifact_id: imageArtifactId }).strict()
395
+ ]);
396
+ function validateImageReference(bytes) {
397
+ if (!bytes.length || bytes.length > IMAGE_REFERENCE_MAX_BYTES)
398
+ throw new ImageGenerationError(
399
+ "Image reference is empty or exceeds 8 MiB; no generation was attempted."
400
+ );
401
+ try {
402
+ const header = Buffer.from(bytes.subarray(0, 12));
403
+ const png = header.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
404
+ const jpeg = header[0] === 255 && header[1] === 216 && header[2] === 255;
405
+ const webp = header.toString("ascii", 0, 4) === "RIFF" && header.toString("ascii", 8, 12) === "WEBP";
406
+ if (!png && !jpeg && !webp) throw new Error("unsupported signature");
407
+ const dimensions = imageSize(bytes);
408
+ const media_type = dimensions.type === "png" ? "image/png" : dimensions.type === "jpg" ? "image/jpeg" : dimensions.type === "webp" ? "image/webp" : null;
409
+ if (!media_type || !dimensions.width || !dimensions.height || dimensions.width > 4096 || dimensions.height > 4096 || dimensions.width * dimensions.height > 16e6)
410
+ throw new Error("unsupported image headers");
411
+ return { type: "bytes", bytes, media_type };
412
+ } catch {
413
+ throw new ImageGenerationError(
414
+ "Image reference must have valid PNG/JPEG/WebP headers, at most 4096 pixels per side and 16 MP; no generation was attempted."
415
+ );
416
+ }
417
+ }
418
+ function imageReferenceDataUrl(reference) {
419
+ return `data:${reference.media_type};base64,${Buffer.from(reference.bytes).toString("base64")}`;
420
+ }
421
+ async function resolveImageSources(sources, store, readSource, signal) {
422
+ if (sources.length > IMAGE_REFERENCE_MAX_COUNT)
423
+ throw new ImageGenerationError(
424
+ "Too many image references; no generation was attempted."
425
+ );
426
+ const references = [];
427
+ let total = 0;
428
+ try {
429
+ for (const source of sources) {
430
+ signal?.throwIfAborted();
431
+ let bytes;
432
+ if (source.type === "artifact")
433
+ bytes = (await store.read(source.artifact_id)).bytes;
434
+ else {
435
+ if (!readSource)
436
+ throw new ImageGenerationError(
437
+ "URL/file image references are unavailable in this environment; no generation was attempted."
438
+ );
439
+ bytes = await readSource(source, signal);
440
+ }
441
+ signal?.throwIfAborted();
442
+ const reference = validateImageReference(bytes);
443
+ total += bytes.length;
444
+ if (total > IMAGE_REFERENCE_TOTAL_BYTES)
445
+ throw new ImageGenerationError(
446
+ "Image references exceed the 32 MiB combined limit; no generation was attempted."
447
+ );
448
+ references.push(reference);
449
+ }
450
+ return references;
451
+ } catch (error) {
452
+ if (error instanceof ImageGenerationError) throw error;
453
+ throw new ImageGenerationError(
454
+ "Image reference could not be read or was cancelled; no generation was attempted."
455
+ );
456
+ }
457
+ }
458
+
459
+ // src/image-generation/codex.ts
460
+ async function requestCodexImage(route, prompt, references, signal, fetcher) {
461
+ if (route.endpoint !== `${OPENAI_OAUTH_BASE_URL}/images/generations`)
462
+ throw new ImageGenerationError(
463
+ "Invalid Codex image endpoint; OAuth was not sent."
464
+ );
465
+ signal?.throwIfAborted();
466
+ let credentials;
467
+ try {
468
+ credentials = await route.getAccessToken();
469
+ } catch {
470
+ throw new ImageGenerationError(
471
+ "Codex OAuth authentication/refresh failed; sign in to OpenAI again. No image request or API-key fallback was attempted."
472
+ );
473
+ }
474
+ signal?.throwIfAborted();
475
+ if (!credentials.token.trim())
476
+ throw new ImageGenerationError(
477
+ "Codex OAuth login is missing; sign in to OpenAI again. An API key is not required."
478
+ );
479
+ if (route.accountId && credentials.accountId !== route.accountId)
480
+ throw new ImageGenerationError(
481
+ "The Codex OAuth account changed; start a new run before generating images. No request was sent to another account."
482
+ );
483
+ const headers = {
484
+ Authorization: `Bearer ${credentials.token}`,
485
+ "Content-Type": "application/json",
486
+ originator: "codelia",
487
+ "User-Agent": "codelia-cli",
488
+ "x-codex-image-turn-id": `codelia-image-${randomUUID()}`,
489
+ ...credentials.accountId ? { "ChatGPT-Account-ID": credentials.accountId } : {}
490
+ };
491
+ const body = {
492
+ model: route.model,
493
+ prompt,
494
+ background: "auto",
495
+ quality: route.options.quality ?? "auto",
496
+ size: route.options.size ?? "auto",
497
+ ...references.length ? {
498
+ images: references.map((reference) => ({
499
+ image_url: imageReferenceDataUrl(reference)
500
+ }))
501
+ } : {}
502
+ };
503
+ return imageJson(
504
+ `${OPENAI_OAUTH_BASE_URL}/images/${references.length ? "edits" : "generations"}`,
505
+ {
506
+ method: "POST",
507
+ headers,
508
+ body: JSON.stringify(body),
509
+ signal
510
+ },
511
+ fetcher
512
+ );
513
+ }
514
+
515
+ // src/image-generation/adapter.ts
516
+ var responseSchema = z3.object({
517
+ data: z3.array(
518
+ z3.object({
519
+ b64_json: z3.string().min(1).max(Math.ceil(IMAGE_MAX_BYTES / 3) * 4),
520
+ media_type: z3.literal("image/png").optional()
521
+ })
522
+ ).length(1),
523
+ model: z3.string().max(160).regex(/^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$/).optional(),
524
+ usage: z3.object({
525
+ input_tokens: z3.number().finite().nonnegative().optional(),
526
+ output_tokens: z3.number().finite().nonnegative().optional(),
527
+ prompt_tokens: z3.number().finite().nonnegative().optional(),
528
+ completion_tokens: z3.number().finite().nonnegative().optional(),
529
+ cost: z3.number().finite().nonnegative().optional()
530
+ }).optional()
531
+ });
532
+ async function prepareImageGeneration(route, referenceCount, signal, fetcher = fetch) {
533
+ signal?.throwIfAborted();
534
+ const max = route.authMode === "codex_oauth" ? 5 : IMAGE_REFERENCE_MAX_COUNT;
535
+ if (!Number.isInteger(referenceCount) || referenceCount < 0 || referenceCount > max)
536
+ throw new ImageGenerationError(
537
+ `Selected image route supports at most ${max} references; no generation was attempted.`
538
+ );
539
+ let endpoint;
540
+ if (route.provider === "openrouter") {
541
+ endpoint = (await new ImageCatalog(fetcher).endpoints(route.model, signal)).find((e) => e.provider_tag === route.endpoint);
542
+ if (!endpoint)
543
+ throw new ImageGenerationError(
544
+ "Selected image endpoint is unavailable or explicitly excludes PNG output."
545
+ );
546
+ if (endpoint.supported_parameters.n && !acceptsParameter(endpoint, "n", 1))
547
+ throw new ImageGenerationError(
548
+ "Selected image endpoint does not support a single image."
549
+ );
550
+ for (const [key, value] of Object.entries(route.options))
551
+ if (!acceptsParameter(endpoint, key, value))
552
+ throw new ImageGenerationError(
553
+ `Selected image endpoint does not support configured ${key}.`
554
+ );
555
+ if (referenceCount && !acceptsParameter(endpoint, "input_references", referenceCount))
556
+ throw new ImageGenerationError(
557
+ "Selected image endpoint does not support this reference count; no generation was attempted."
558
+ );
559
+ }
560
+ return async (prompt, references) => {
561
+ if (references.length !== referenceCount)
562
+ throw new ImageGenerationError(
563
+ "Image reference count changed after preparation; no generation was attempted."
564
+ );
565
+ let total = 0;
566
+ for (const reference of references) {
567
+ const validated = validateImageReference(reference.bytes);
568
+ if (validated.media_type !== reference.media_type)
569
+ throw new ImageGenerationError(
570
+ "Image reference media type mismatch; no generation was attempted."
571
+ );
572
+ total += reference.bytes.length;
573
+ }
574
+ if (total > IMAGE_REFERENCE_TOTAL_BYTES)
575
+ throw new ImageGenerationError(
576
+ "Image references exceed the 32 MiB combined limit; no generation was attempted."
577
+ );
578
+ return sendImage(route, prompt, references, signal, fetcher, endpoint);
579
+ };
580
+ }
581
+ async function sendImage(route, prompt, references, signal, fetcher = fetch, endpoint) {
582
+ if (route.authMode === "codex_oauth")
583
+ return parseImageResponse(
584
+ await requestCodexImage(route, prompt, references, signal, fetcher)
585
+ );
586
+ let url = route.endpoint;
587
+ let body;
588
+ const headers = {
589
+ Authorization: `Bearer ${route.apiKey}`
590
+ };
591
+ if (route.provider === "openai" && references.length) {
592
+ url = "https://api.openai.com/v1/images/edits";
593
+ const form = new FormData();
594
+ form.set("model", route.model);
595
+ form.set("prompt", prompt);
596
+ form.set("n", "1");
597
+ form.set("output_format", "png");
598
+ for (const [key, value] of Object.entries(route.options))
599
+ form.set(key, value);
600
+ for (const [i, reference] of references.entries())
601
+ form.append(
602
+ "image[]",
603
+ new Blob([new Uint8Array(reference.bytes)], {
604
+ type: reference.media_type
605
+ }),
606
+ `reference-${i}.${reference.media_type.split("/")[1]}`
607
+ );
608
+ body = form;
609
+ } else {
610
+ const fields = {
611
+ model: route.model,
612
+ prompt,
613
+ n: 1,
614
+ output_format: "png",
615
+ ...route.options
616
+ };
617
+ if (route.provider === "openrouter") {
618
+ url = "https://openrouter.ai/api/v1/images";
619
+ if (!endpoint)
620
+ throw new ImageGenerationError(
621
+ "Selected image endpoint is unavailable or explicitly excludes PNG output."
622
+ );
623
+ if (!endpoint.supported_parameters.output_format)
624
+ delete fields.output_format;
625
+ if (!endpoint.supported_parameters.n) delete fields.n;
626
+ fields.provider = { only: [route.endpoint], allow_fallbacks: false };
627
+ if (references.length) {
628
+ fields.input_references = references.map((reference) => ({
629
+ type: "image_url",
630
+ image_url: {
631
+ url: imageReferenceDataUrl(reference)
632
+ }
633
+ }));
634
+ }
635
+ }
636
+ headers["Content-Type"] = "application/json";
637
+ body = JSON.stringify(fields);
638
+ }
639
+ signal?.throwIfAborted();
640
+ return parseImageResponse(
641
+ await imageJson(url, { method: "POST", headers, body, signal }, fetcher)
642
+ );
643
+ }
644
+ function parseImageResponse(raw) {
645
+ const parsed = responseSchema.safeParse(raw);
646
+ if (!parsed.success)
647
+ throw new ImageGenerationError(
648
+ "Image API returned no complete supported image; generation was not recorded as successful."
649
+ );
650
+ const base64 = parsed.data.data[0]?.b64_json ?? "";
651
+ const bytes = Buffer.from(base64, "base64");
652
+ if (!bytes.length || bytes.length > IMAGE_MAX_BYTES || bytes.toString("base64") !== base64)
653
+ throw new ImageGenerationError(
654
+ "Image API returned invalid or oversized base64."
655
+ );
656
+ const u = parsed.data.usage;
657
+ const usage = u ? {
658
+ input_tokens: u.input_tokens ?? u.prompt_tokens,
659
+ output_tokens: u.output_tokens ?? u.completion_tokens,
660
+ cost_usd: u.cost
661
+ } : void 0;
662
+ return {
663
+ bytes,
664
+ ...parsed.data.model ? { effective_model: parsed.data.model } : {},
665
+ ...usage ? { usage } : {}
666
+ };
667
+ }
668
+
669
+ // src/image-generation/tools.ts
670
+ var imageParts = (m, ref) => {
671
+ const provenance = m.kind === "attachment" ? "Source: user attachment (not generated)." : `Provider: ${m.provider}; requested model: ${m.requested_model}; effective model: ${m.effective_model ?? "unknown"}. Cost: ${m.usage?.cost_usd === void 0 ? "unknown" : `${m.usage.cost_usd} USD`}.`;
672
+ return [
673
+ {
674
+ type: "text",
675
+ text: `Image artifact: ${m.artifact_id}
676
+ ${m.width}x${m.height}, ${m.byte_size} bytes, ${m.media_type}
677
+ ${provenance}
678
+ Preview: /image-artifact ${m.artifact_id}
679
+ Use image_inspect to revisit; image_generate images with type=artifact to edit. Original is immutable.${ref.model_view ? " Model input uses a fixed JPEG quality-90 view; inspect with original=true for exact pixels." : ""}
680
+ `
681
+ },
682
+ { type: "image_ref", image_ref: ref }
683
+ ];
684
+ };
685
+ function createImageTools(input) {
686
+ const tools = [
687
+ defineTool({
688
+ name: "image_inspect",
689
+ description: "Revisit one saved image artifact in this workspace without generating or charging. Generated opaque images use a smaller fixed JPEG view by default. Use original=true for exact pixels or fine text; this does not replace earlier images. Attachments and transparent images keep originals.",
690
+ input: z4.object({
691
+ artifact_id: imageArtifactId.describe(
692
+ "Saved codelia-image artifact id from a prior image result."
693
+ ),
694
+ original: z4.boolean().optional().describe(
695
+ "Use original pixels for this inspection instead of the generated-image JPEG view."
696
+ )
697
+ }),
698
+ execute: async ({ artifact_id, original }) => imageParts(
699
+ (await input.store.read(artifact_id)).metadata,
700
+ await input.store.modelReference(artifact_id, original)
701
+ )
702
+ })
703
+ ];
704
+ const exportImage = input.exportImage;
705
+ if (exportImage)
706
+ tools.push(
707
+ defineTool({
708
+ name: "image_export",
709
+ description: "Export an immutable generated image to a new PNG file in the runtime workspace. No generation or charge; never overwrites an existing file. Parent directory must exist. SSH paths remain runtime-host paths.",
710
+ input: z4.object({
711
+ artifact_id: imageArtifactId.describe("Saved image artifact id."),
712
+ output_path: z4.string().min(1).max(4096).describe(
713
+ "New .png file inside the runtime workspace; parent directory must already exist."
714
+ )
715
+ }),
716
+ execute: async (args, ctx) => {
717
+ const raw = JSON.stringify(args);
718
+ const decision = await input.authorize(
719
+ {
720
+ id: "codelia-image-export",
721
+ type: "function",
722
+ function: { name: "image_export", arguments: raw }
723
+ },
724
+ raw,
725
+ ctx
726
+ );
727
+ if (decision.decision !== "allow")
728
+ throw new ToolPermissionDenied(decision);
729
+ ctx.signal?.throwIfAborted();
730
+ const { bytes, metadata } = await input.store.read(args.artifact_id);
731
+ if (metadata.media_type !== "image/png")
732
+ throw new ImageGenerationError(
733
+ "PNG export only; this attachment's original format is not PNG. No conversion was performed."
734
+ );
735
+ return `Image exported (runtime host path): ${await exportImage(args.output_path, bytes)}
736
+ Original artifact unchanged: ${args.artifact_id}`;
737
+ }
738
+ })
739
+ );
740
+ const route = input.route;
741
+ if (!route) return tools;
742
+ const billing = route.authMode === "codex_oauth" ? "current Codex OAuth account; image usage/limits apply; no public API-key billing fallback" : "chargeable image API; price unknown unless reported";
743
+ let busy = false;
744
+ tools.push(
745
+ defineTool({
746
+ name: "image_generate",
747
+ description: `Generate or edit one PNG using selected ${route.provider}/${route.model} (${route.endpoint}); ${billing}. Only use when the user requests images. Supply images explicitly; viewing an image does not select it. Returns immutable artifact and image input. No automatic retry or fallback; timeout may consume usage. Output max 8 MiB/4096px/16 MP.`,
748
+ input: z4.object({
749
+ prompt: z4.string().trim().min(1).max(16e3).describe(
750
+ "Image generation/edit instruction; refer to images by their 1-based order and describe what to preserve/change. Do not include credentials or unrelated private data."
751
+ ),
752
+ images: z4.array(imageSourceSchema).max(IMAGE_REFERENCE_MAX_COUNT).optional().describe(
753
+ "Ordered reference images (URL/file/artifact); omit for text-only generation. Up to 16 total, further limited by route: Codex 5, OpenAI public 16, OpenRouter endpoint-specific. PNG/JPEG/WebP, max 8 MiB each/32 MiB combined, 4096px per side/16 MP. Original bytes are acquired after approval; failure aborts generation. Cannot combine with reference_artifact_ids."
754
+ ),
755
+ reference_artifact_ids: z4.array(imageArtifactId).max(IMAGE_REFERENCE_MAX_COUNT).optional().describe(
756
+ "Legacy artifact-only alternative to images, subject to the same route/count/byte limits. Do not combine with images; prefer images with type=artifact."
757
+ )
758
+ }).refine(
759
+ (args) => args.images === void 0 || args.reference_artifact_ids === void 0,
760
+ "Provide images or reference_artifact_ids, not both"
761
+ ),
762
+ execute: async (args, ctx) => {
763
+ if (busy)
764
+ throw new ImageGenerationError(
765
+ "An image generation request is already active; wait for it rather than retrying."
766
+ );
767
+ busy = true;
768
+ try {
769
+ const raw = {
770
+ ...args,
771
+ provider: route.provider,
772
+ requested_model: route.model,
773
+ endpoint: route.endpoint,
774
+ auth_mode: route.authMode,
775
+ billing
776
+ };
777
+ const decision = await input.authorize(
778
+ {
779
+ id: "codelia-image-generation",
780
+ type: "function",
781
+ function: {
782
+ name: "image_generate",
783
+ arguments: JSON.stringify(raw)
784
+ }
785
+ },
786
+ JSON.stringify(raw),
787
+ ctx
788
+ );
789
+ if (decision.decision !== "allow")
790
+ throw new ToolPermissionDenied(decision);
791
+ ctx.signal?.throwIfAborted();
792
+ const sources = args.images ?? (args.reference_artifact_ids ?? []).map((artifact_id) => ({
793
+ type: "artifact",
794
+ artifact_id
795
+ }));
796
+ const generate = await prepareImageGeneration(
797
+ route,
798
+ sources.length,
799
+ ctx.signal,
800
+ input.fetcher
801
+ );
802
+ const references = await resolveImageSources(
803
+ sources,
804
+ input.store,
805
+ input.readSource,
806
+ ctx.signal
807
+ );
808
+ const ids = sources.flatMap(
809
+ (source) => source.type === "artifact" ? [source.artifact_id] : []
810
+ );
811
+ const result = await generate(args.prompt, references);
812
+ ctx.signal?.throwIfAborted();
813
+ const metadata = await input.store.save(result.bytes, {
814
+ provider: route.provider,
815
+ requested_model: route.model,
816
+ endpoint: route.endpoint,
817
+ parent_artifact_ids: ids,
818
+ ...result.effective_model ? { effective_model: result.effective_model } : {},
819
+ ...result.usage ? { usage: result.usage } : {}
820
+ });
821
+ try {
822
+ return imageParts(
823
+ metadata,
824
+ await input.store.modelReference(metadata.artifact_id)
825
+ );
826
+ } catch {
827
+ const {
828
+ artifact_id,
829
+ sha256,
830
+ media_type,
831
+ byte_size,
832
+ width,
833
+ height
834
+ } = metadata;
835
+ return [
836
+ ...imageParts(metadata, {
837
+ artifact_id,
838
+ sha256,
839
+ media_type,
840
+ byte_size,
841
+ width,
842
+ height
843
+ }),
844
+ {
845
+ type: "text",
846
+ text: "JPEG model view could not be prepared. Generation succeeded and the original is saved; this new reference uses original pixels. Do not regenerate. Inspect with original=true or export the saved artifact."
847
+ }
848
+ ];
849
+ }
850
+ } catch (error) {
851
+ if (error instanceof ToolPermissionDenied || error instanceof ImageGenerationError)
852
+ throw error;
853
+ throw new ImageGenerationError(
854
+ "Image generation or artifact persistence failed. No fallback or automatic retry was attempted; the provider may already have charged. Check runtime storage and selected route."
855
+ );
856
+ } finally {
857
+ busy = false;
858
+ }
859
+ }
860
+ })
861
+ );
862
+ return tools;
863
+ }
864
+
865
+ // src/image-generation/export.ts
866
+ import { open, realpath } from "fs/promises";
867
+ import path2 from "path";
868
+ async function exportImageBytes(workspaceRoot, outputPath, bytes) {
869
+ if (!outputPath || outputPath.length > 4096 || [...outputPath].some(
870
+ (c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127
871
+ ) || path2.extname(outputPath).toLowerCase() !== ".png")
872
+ throw new ImageGenerationError(
873
+ "Image export requires a PNG path in this workspace."
874
+ );
875
+ const target = path2.resolve(workspaceRoot, outputPath);
876
+ try {
877
+ const root = await realpath(workspaceRoot);
878
+ const parent = await realpath(path2.dirname(target));
879
+ const relative = path2.relative(root, parent);
880
+ if (relative === ".." || relative.startsWith(`..${path2.sep}`) || path2.isAbsolute(relative))
881
+ throw new Error("outside workspace");
882
+ const destination = path2.join(parent, path2.basename(target));
883
+ const file = await open(destination, "wx", 384);
884
+ try {
885
+ await file.writeFile(bytes);
886
+ await file.sync();
887
+ } finally {
888
+ await file.close();
889
+ }
890
+ return destination;
891
+ } catch {
892
+ throw new ImageGenerationError(
893
+ "Image export failed: destination must be a new file in an existing workspace directory. No original was modified."
894
+ );
895
+ }
896
+ }
897
+
898
+ // src/image-generation/source-reader.ts
899
+ import { lookup } from "dns/promises";
900
+ import { constants } from "fs";
901
+ import { open as open2, realpath as realpath2 } from "fs/promises";
902
+ import { request as httpRequest } from "http";
903
+ import { request as httpsRequest } from "https";
904
+ import { BlockList, isIP } from "net";
905
+ import path3 from "path";
906
+ var blocked = new BlockList();
907
+ for (const [address, prefix] of [
908
+ ["0.0.0.0", 8],
909
+ ["10.0.0.0", 8],
910
+ ["100.64.0.0", 10],
911
+ ["127.0.0.0", 8],
912
+ ["169.254.0.0", 16],
913
+ ["172.16.0.0", 12],
914
+ ["192.0.0.0", 24],
915
+ ["192.0.2.0", 24],
916
+ ["192.88.99.0", 24],
917
+ ["192.168.0.0", 16],
918
+ ["198.18.0.0", 15],
919
+ ["198.51.100.0", 24],
920
+ ["203.0.113.0", 24],
921
+ ["224.0.0.0", 4],
922
+ ["240.0.0.0", 4]
923
+ ])
924
+ blocked.addSubnet(address, prefix, "ipv4");
925
+ var globalV6 = new BlockList();
926
+ globalV6.addSubnet("2000::", 3, "ipv6");
927
+ for (const [address, prefix] of [
928
+ ["2001::", 23],
929
+ ["2001:db8::", 32],
930
+ ["2002::", 16],
931
+ ["3fff::", 20]
932
+ ])
933
+ blocked.addSubnet(address, prefix, "ipv6");
934
+ function isPublicImageAddress(address) {
935
+ const family = isIP(address);
936
+ return family === 4 ? !blocked.check(address, "ipv4") : family === 6 && globalV6.check(address, "ipv6") && !blocked.check(address, "ipv6");
937
+ }
938
+ function createImageLookup(resolve = (hostname) => lookup(hostname, { all: true, verbatim: true })) {
939
+ return (hostname, options, callback) => {
940
+ void resolve(hostname).then(
941
+ (addresses) => {
942
+ if (!addresses.length || addresses.some((entry) => !isPublicImageAddress(entry.address))) {
943
+ callback(new Error("Image source destination is not public"), "");
944
+ return;
945
+ }
946
+ const family = options.family === "IPv4" ? 4 : options.family === "IPv6" ? 6 : options.family;
947
+ const selected = addresses.filter(
948
+ (entry) => !family || entry.family === family
949
+ );
950
+ const first = selected[0];
951
+ if (!first)
952
+ callback(
953
+ new Error("Image source has no compatible public address"),
954
+ ""
955
+ );
956
+ else if (options.all) callback(null, selected);
957
+ else callback(null, first.address, first.family);
958
+ },
959
+ () => callback(new Error("Image source DNS failed"), "")
960
+ );
961
+ };
962
+ }
963
+ function imageSourceUrl(value) {
964
+ try {
965
+ const url = new URL(value);
966
+ const host = url.hostname.replace(/^\[|\]$/g, "");
967
+ if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.hash || value.length > 8192 || url.port && url.port !== "80" && url.port !== "443" || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || isIP(host) && !isPublicImageAddress(host))
968
+ throw new Error("invalid source");
969
+ return url;
970
+ } catch {
971
+ throw new ImageGenerationError(
972
+ "Image source requires a public HTTP(S) URL on port 80/443 without credentials or fragments; no generation was attempted."
973
+ );
974
+ }
975
+ }
976
+ var requestImage = (url, options) => new Promise((resolve, reject) => {
977
+ if (process.versions.bun && [
978
+ "HTTP_PROXY",
979
+ "HTTPS_PROXY",
980
+ "ALL_PROXY",
981
+ "http_proxy",
982
+ "https_proxy",
983
+ "all_proxy"
984
+ ].some((name) => process.env[name]))
985
+ throw new ImageGenerationError(
986
+ "Image URL references require a direct connection; proxy-configured Bun is unsupported. Use a local file/artifact reference. No generation was attempted."
987
+ );
988
+ const request = (url.protocol === "https:" ? httpsRequest : httpRequest)(
989
+ url,
990
+ options
991
+ );
992
+ const cleanup = () => options.signal?.removeEventListener("abort", abort);
993
+ const abort = () => {
994
+ cleanup();
995
+ reject(new Error("Image source request cancelled"));
996
+ request.destroy();
997
+ };
998
+ request.once("response", (response) => {
999
+ cleanup();
1000
+ resolve(response);
1001
+ });
1002
+ request.on("error", (error) => {
1003
+ cleanup();
1004
+ reject(error);
1005
+ });
1006
+ request.once("close", () => {
1007
+ cleanup();
1008
+ reject(new Error("Image source closed before response"));
1009
+ });
1010
+ options.signal?.addEventListener("abort", abort, { once: true });
1011
+ if (options.signal?.aborted) abort();
1012
+ else request.end();
1013
+ });
1014
+ async function downloadImageSource(value, callerSignal, transport = requestImage, timeoutMs = 15e3) {
1015
+ const url = imageSourceUrl(value);
1016
+ const signal = callerSignal ? AbortSignal.any([callerSignal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
1017
+ let response;
1018
+ try {
1019
+ signal.throwIfAborted();
1020
+ response = await transport(url, {
1021
+ method: "GET",
1022
+ agent: false,
1023
+ lookup: createImageLookup(),
1024
+ // Preserve the original authority when Bun connects to a validated DNS IP.
1025
+ ...url.protocol === "https:" && !isIP(url.hostname.replace(/^\[|\]$/g, "")) ? { servername: url.hostname } : {},
1026
+ signal,
1027
+ headers: {
1028
+ Host: url.host,
1029
+ Accept: "image/png,image/jpeg,image/webp",
1030
+ "Accept-Encoding": "identity"
1031
+ }
1032
+ });
1033
+ signal.throwIfAborted();
1034
+ if (response.statusCode !== 200)
1035
+ throw new Error("non-200 source (redirects are not followed)");
1036
+ if (response.headers["content-encoding"] && response.headers["content-encoding"] !== "identity")
1037
+ throw new Error("compressed transfer unsupported");
1038
+ if (Number(response.headers["content-length"] ?? 0) > IMAGE_REFERENCE_MAX_BYTES)
1039
+ throw new Error("source too large");
1040
+ const stream = response;
1041
+ const abort = () => stream.destroy(new Error("Image source read cancelled"));
1042
+ signal.addEventListener("abort", abort, { once: true });
1043
+ try {
1044
+ const chunks = [];
1045
+ let size = 0;
1046
+ for await (const chunk of stream) {
1047
+ signal.throwIfAborted();
1048
+ if (!(chunk instanceof Uint8Array)) throw new Error("nonbinary source");
1049
+ size += chunk.length;
1050
+ if (size > IMAGE_REFERENCE_MAX_BYTES)
1051
+ throw new Error("source too large");
1052
+ chunks.push(chunk);
1053
+ }
1054
+ signal.throwIfAborted();
1055
+ if (!size) throw new Error("empty source");
1056
+ return Buffer.concat(chunks);
1057
+ } finally {
1058
+ signal.removeEventListener("abort", abort);
1059
+ }
1060
+ } catch (error) {
1061
+ if (error instanceof ImageGenerationError) throw error;
1062
+ throw new ImageGenerationError(
1063
+ "Image source download failed, timed out, was cancelled, or exceeded limits; redirects/private destinations are not allowed. No generation was attempted."
1064
+ );
1065
+ } finally {
1066
+ response?.destroy();
1067
+ }
1068
+ }
1069
+ async function readImageFile(sandbox, filePath, signal) {
1070
+ try {
1071
+ signal?.throwIfAborted();
1072
+ const target = await realpath2(sandbox.resolvePath(filePath));
1073
+ if (sandbox.approvalMode !== "full-access") {
1074
+ const root = await realpath2(sandbox.rootDir);
1075
+ const relative = path3.relative(root, target);
1076
+ if (relative === ".." || relative.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative))
1077
+ throw new Error("outside sandbox");
1078
+ }
1079
+ const handle = await open2(
1080
+ target,
1081
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
1082
+ );
1083
+ try {
1084
+ const stat = await handle.stat();
1085
+ if (!stat.isFile() || stat.size <= 0 || stat.size > IMAGE_REFERENCE_MAX_BYTES)
1086
+ throw new Error("invalid source file");
1087
+ const bytes = Buffer.alloc(stat.size + 1);
1088
+ let offset = 0;
1089
+ while (offset < bytes.length) {
1090
+ signal?.throwIfAborted();
1091
+ const result = await handle.read(
1092
+ bytes,
1093
+ offset,
1094
+ Math.min(bytes.length - offset, 65536),
1095
+ offset
1096
+ );
1097
+ if (!result.bytesRead) break;
1098
+ offset += result.bytesRead;
1099
+ }
1100
+ if (offset !== stat.size)
1101
+ throw new Error("source file changed during read");
1102
+ signal?.throwIfAborted();
1103
+ return bytes.subarray(0, offset);
1104
+ } finally {
1105
+ await handle.close();
1106
+ }
1107
+ } catch {
1108
+ throw new ImageGenerationError(
1109
+ "Image reference file is unavailable, outside the sandbox, not a bounded regular file, or reading was cancelled; no generation was attempted."
1110
+ );
1111
+ }
1112
+ }
1113
+ function createLocalImageSourceReader(sandbox) {
1114
+ return (source, signal) => source.type === "url" ? downloadImageSource(source.url, signal) : readImageFile(sandbox, source.file_path, signal);
1115
+ }
1116
+
1117
+ // src/image-generation/attachments.ts
1118
+ async function persistImageAttachments(input, store) {
1119
+ if (typeof input === "string") return input;
1120
+ const result = [];
1121
+ let imageNumber = 0;
1122
+ for (const part of input) {
1123
+ if (part.type !== "image_url") {
1124
+ result.push(part);
1125
+ continue;
1126
+ }
1127
+ imageNumber++;
1128
+ const url = part.image_url.url;
1129
+ if (!url.startsWith("data:")) {
1130
+ result.push(part);
1131
+ continue;
1132
+ }
1133
+ if (url.length > Math.ceil(IMAGE_REFERENCE_MAX_BYTES / 3) * 4 + 64)
1134
+ throw new Error("Image attachment exceeds 8 MiB");
1135
+ const match = /^data:(image\/(?:png|jpeg|webp|gif));base64,([A-Za-z0-9+/]*={0,2})$/.exec(
1136
+ url
1137
+ );
1138
+ if (!match)
1139
+ throw new Error(
1140
+ "Image attachment must be a PNG/JPEG/WebP/GIF base64 data URL"
1141
+ );
1142
+ const mediaType = match[1];
1143
+ const encoded = match[2] ?? "";
1144
+ const bytes = Buffer.from(encoded, "base64");
1145
+ if (!encoded || bytes.toString("base64") !== encoded || part.image_url.media_type && part.image_url.media_type !== mediaType)
1146
+ throw new Error("Invalid image attachment encoding or MIME mismatch");
1147
+ const metadata = await store.saveAttachment(bytes, mediaType);
1148
+ const { artifact_id, sha256, media_type, byte_size, width, height } = metadata;
1149
+ result.push(
1150
+ {
1151
+ type: "text",
1152
+ text: `[Attached image ${imageNumber}: ${artifact_id}. To use this image as a generation reference, explicitly supply images: [{"type":"artifact","artifact_id":"${artifact_id}"}].]`
1153
+ },
1154
+ {
1155
+ type: "image_ref",
1156
+ image_ref: {
1157
+ artifact_id,
1158
+ sha256,
1159
+ media_type,
1160
+ byte_size,
1161
+ width,
1162
+ height
1163
+ },
1164
+ ...part.image_url.detail ? { detail: part.image_url.detail } : {}
1165
+ }
1166
+ );
1167
+ }
1168
+ return result;
1169
+ }
1170
+
76
1171
  // src/agent-factory.ts
77
1172
  import {
78
1173
  Agent,
79
1174
  DEFAULT_MODEL_REGISTRY as DEFAULT_MODEL_REGISTRY2,
80
- ToolPermissionDenied
1175
+ ToolPermissionDenied as ToolPermissionDenied2
81
1176
  } from "@codelia/core";
82
1177
  import { ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl2 } from "@codelia/storage";
83
1178
 
@@ -90,41 +1185,41 @@ var getAgentsResolver = async (ctx, key) => ctx.resolve(key);
90
1185
 
91
1186
  // src/agents/resolver.ts
92
1187
  import { promises as fs } from "fs";
93
- import path from "path";
1188
+ import path4 from "path";
94
1189
 
95
1190
  // src/agents/schema.ts
96
- import { z } from "zod";
97
- var AgentsConfigSchema = z.object({
98
- enabled: z.boolean().optional(),
99
- root: z.object({
100
- projectRootOverride: z.string().optional(),
101
- markers: z.array(z.string()).optional(),
102
- stopAtFsRoot: z.boolean().optional()
1191
+ import { z as z5 } from "zod";
1192
+ var AgentsConfigSchema = z5.object({
1193
+ enabled: z5.boolean().optional(),
1194
+ root: z5.object({
1195
+ projectRootOverride: z5.string().optional(),
1196
+ markers: z5.array(z5.string()).optional(),
1197
+ stopAtFsRoot: z5.boolean().optional()
103
1198
  }).optional(),
104
- initial: z.object({
105
- maxFiles: z.number().int().positive().optional(),
106
- maxBytes: z.number().int().positive().optional()
1199
+ initial: z5.object({
1200
+ maxFiles: z5.number().int().positive().optional(),
1201
+ maxBytes: z5.number().int().positive().optional()
107
1202
  }).optional(),
108
- resolver: z.object({
109
- enabled: z.boolean().optional(),
110
- maxFilesPerResolve: z.number().int().positive().optional()
1203
+ resolver: z5.object({
1204
+ enabled: z5.boolean().optional(),
1205
+ maxFilesPerResolve: z5.number().int().positive().optional()
111
1206
  }).optional()
112
1207
  }).strict();
113
- var ResolvedAgentFileSchema = z.object({
114
- path: z.string(),
115
- mtimeMs: z.number().nonnegative(),
116
- sizeBytes: z.number().int().nonnegative()
1208
+ var ResolvedAgentFileSchema = z5.object({
1209
+ path: z5.string(),
1210
+ mtimeMs: z5.number().nonnegative(),
1211
+ sizeBytes: z5.number().int().nonnegative()
117
1212
  }).strict();
118
- var ResolvedAgentsSchema = z.object({
119
- files: z.array(ResolvedAgentFileSchema)
1213
+ var ResolvedAgentsSchema = z5.object({
1214
+ files: z5.array(ResolvedAgentFileSchema)
120
1215
  }).strict();
121
- var SystemReminderTypeSchema = z.enum([
1216
+ var SystemReminderTypeSchema = z5.enum([
122
1217
  "agents.resolve.paths",
123
1218
  "session.resume.diff",
124
1219
  "tool.output.trimmed",
125
1220
  "permission.decision"
126
1221
  ]);
127
- var AgentsResolveReasonSchema = z.enum(["new", "updated"]);
1222
+ var AgentsResolveReasonSchema = z5.enum(["new", "updated"]);
128
1223
 
129
1224
  // src/agents/resolver.ts
130
1225
  var DEFAULT_MARKERS = [".codelia", ".git", ".jj"];
@@ -166,23 +1261,23 @@ var exists = async (targetPath) => {
166
1261
  var normalizeMtime = (value) => Number.isFinite(value) && value >= 0 ? value : 0;
167
1262
  var normalizeSize = (value) => Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 0;
168
1263
  var resolvePathChain = (rootDir, targetDir) => {
169
- const normalizedRoot = path.resolve(rootDir);
170
- const normalizedTarget = path.resolve(targetDir);
171
- const relative = path.relative(normalizedRoot, normalizedTarget);
172
- if (relative.startsWith("..") || path.isAbsolute(relative) || relative === "..") {
1264
+ const normalizedRoot = path4.resolve(rootDir);
1265
+ const normalizedTarget = path4.resolve(targetDir);
1266
+ const relative = path4.relative(normalizedRoot, normalizedTarget);
1267
+ if (relative.startsWith("..") || path4.isAbsolute(relative) || relative === "..") {
173
1268
  return [];
174
1269
  }
175
- const parts = relative.split(path.sep).filter((part) => part.length > 0);
1270
+ const parts = relative.split(path4.sep).filter((part) => part.length > 0);
176
1271
  const chain = [normalizedRoot];
177
1272
  let current = normalizedRoot;
178
1273
  for (const part of parts) {
179
- current = path.join(current, part);
1274
+ current = path4.join(current, part);
180
1275
  chain.push(current);
181
1276
  }
182
1277
  return chain;
183
1278
  };
184
1279
  var readAgentsStat = async (directoryPath) => {
185
- const filePath = path.join(directoryPath, "AGENTS.md");
1280
+ const filePath = path4.join(directoryPath, "AGENTS.md");
186
1281
  let stat;
187
1282
  try {
188
1283
  stat = await fs.stat(filePath);
@@ -201,22 +1296,22 @@ var resolveTargetDirectory = async (targetPath) => {
201
1296
  try {
202
1297
  stat = await fs.stat(targetPath);
203
1298
  } catch {
204
- return path.dirname(targetPath);
1299
+ return path4.dirname(targetPath);
205
1300
  }
206
- return stat.isDirectory() ? targetPath : path.dirname(targetPath);
1301
+ return stat.isDirectory() ? targetPath : path4.dirname(targetPath);
207
1302
  };
208
1303
  var findRootByMarkers = async (workingDir, markers, stopAtFsRoot) => {
209
- let current = path.resolve(workingDir);
1304
+ let current = path4.resolve(workingDir);
210
1305
  while (true) {
211
1306
  for (const marker of markers) {
212
- const markerPath = path.join(current, marker);
1307
+ const markerPath = path4.join(current, marker);
213
1308
  if (await exists(markerPath)) {
214
1309
  return current;
215
1310
  }
216
1311
  }
217
- const parent = path.dirname(current);
1312
+ const parent = path4.dirname(current);
218
1313
  if (parent === current) {
219
- return path.resolve(workingDir);
1314
+ return path4.resolve(workingDir);
220
1315
  }
221
1316
  if (!stopAtFsRoot) {
222
1317
  current = parent;
@@ -262,7 +1357,7 @@ var mergeConfig = (config, env = process.env) => {
262
1357
  return {
263
1358
  enabled: merged.enabled ?? true,
264
1359
  root: {
265
- projectRootOverride: merged.root?.projectRootOverride ? path.resolve(merged.root.projectRootOverride) : void 0,
1360
+ projectRootOverride: merged.root?.projectRootOverride ? path4.resolve(merged.root.projectRootOverride) : void 0,
266
1361
  markers: merged.root?.markers?.length ? merged.root.markers : [...DEFAULT_MARKERS],
267
1362
  stopAtFsRoot: merged.root?.stopAtFsRoot ?? true
268
1363
  },
@@ -290,9 +1385,9 @@ var AgentsResolver = class _AgentsResolver {
290
1385
  this.initialFiles = options.initialFiles;
291
1386
  }
292
1387
  static async create(workingDir, config, env = process.env) {
293
- const normalizedWorkingDir = path.resolve(workingDir);
1388
+ const normalizedWorkingDir = path4.resolve(workingDir);
294
1389
  const merged = mergeConfig(config, env);
295
- const rootDir = merged.root.projectRootOverride ? path.resolve(merged.root.projectRootOverride) : await findRootByMarkers(
1390
+ const rootDir = merged.root.projectRootOverride ? path4.resolve(merged.root.projectRootOverride) : await findRootByMarkers(
296
1391
  normalizedWorkingDir,
297
1392
  merged.root.markers,
298
1393
  merged.root.stopAtFsRoot
@@ -307,16 +1402,16 @@ var AgentsResolver = class _AgentsResolver {
307
1402
  return resolver;
308
1403
  }
309
1404
  registerLoaded(file) {
310
- const normalizedPath = path.resolve(file.path);
1405
+ const normalizedPath = path4.resolve(file.path);
311
1406
  this.loadedFiles.set(normalizedPath, {
312
1407
  path: normalizedPath,
313
1408
  mtimeMs: normalizeMtime(file.mtimeMs),
314
1409
  sizeBytes: normalizeSize(file.sizeBytes)
315
1410
  });
316
- this.coveredDirs.add(path.dirname(normalizedPath));
1411
+ this.coveredDirs.add(path4.dirname(normalizedPath));
317
1412
  }
318
1413
  getLoadedFile(filePath) {
319
- return this.loadedFiles.get(path.resolve(filePath));
1414
+ return this.loadedFiles.get(path4.resolve(filePath));
320
1415
  }
321
1416
  async loadInitialChain() {
322
1417
  if (!this.config.enabled) {
@@ -367,7 +1462,7 @@ ${body}
367
1462
  if (!this.config.enabled || !this.config.resolver.enabled) {
368
1463
  return [];
369
1464
  }
370
- const normalizedTargetPath = path.resolve(targetPath);
1465
+ const normalizedTargetPath = path4.resolve(targetPath);
371
1466
  const targetDir = await resolveTargetDirectory(normalizedTargetPath);
372
1467
  const directories = resolvePathChain(this.rootDir, targetDir);
373
1468
  if (!directories.length) {
@@ -586,7 +1681,9 @@ var createEnvironmentAuthResolver = async (state, log2) => {
586
1681
  getOpenAiAccessToken: provider.getOpenAiAccessToken
587
1682
  };
588
1683
  }
589
- return AuthResolver.create(state, log2);
1684
+ const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0;
1685
+ const config = await resolveEnvironmentModelConfig(state, workingDir);
1686
+ return AuthResolver.create(state, log2, config.providers);
590
1687
  };
591
1688
 
592
1689
  // src/effective-model.ts
@@ -658,7 +1755,7 @@ var applySessionModelOverrideFromMeta = (state, meta) => {
658
1755
 
659
1756
  // src/execution-environment.ts
660
1757
  import os from "os";
661
- import path2 from "path";
1758
+ import path5 from "path";
662
1759
 
663
1760
  // src/tasks/shell-executor.ts
664
1761
  import { spawn as spawn2 } from "child_process";
@@ -1068,7 +2165,7 @@ var shellQuote = (value) => {
1068
2165
  var buildShellCommand = (command) => command.map((part) => shellQuote(part)).join(" ");
1069
2166
  var describeExecutionEnvironmentHost = () => {
1070
2167
  const shellPath = process.platform === "win32" ? "" : process.env.SHELL?.trim() || "";
1071
- const bashSyntaxGuaranteed = shellPath.length > 0 && path2.basename(shellPath).toLowerCase() === "bash";
2168
+ const bashSyntaxGuaranteed = shellPath.length > 0 && path5.basename(shellPath).toLowerCase() === "bash";
1072
2169
  return {
1073
2170
  osDescription: `${os.type()} ${os.release()} (${process.platform} ${os.arch()})`,
1074
2171
  shellExecution: shellPath.length > 0 ? `${shellPath} -lc` : "platform shell via spawn(shell=true)",
@@ -1606,15 +2703,12 @@ var withOpenRouterDynamicModel = (registry, llm, entry) => {
1606
2703
  const aliases = [llm.model, `${llm.provider}/${normalized}`].filter((value) => value !== normalized).filter((value, index, array) => array.indexOf(value) === index);
1607
2704
  const next = {
1608
2705
  modelsById: { ...registry.modelsById },
1609
- aliasesByProvider: {
1610
- openai: { ...registry.aliasesByProvider.openai },
1611
- anthropic: { ...registry.aliasesByProvider.anthropic },
1612
- openrouter: { ...registry.aliasesByProvider.openrouter },
1613
- google: { ...registry.aliasesByProvider.google },
1614
- moonshot: { ...registry.aliasesByProvider.moonshot },
1615
- zai: { ...registry.aliasesByProvider.zai },
1616
- xai: { ...registry.aliasesByProvider.xai }
1617
- }
2706
+ aliasesByProvider: Object.fromEntries(
2707
+ Object.entries(registry.aliasesByProvider).map(([provider, aliases2]) => [
2708
+ provider,
2709
+ { ...aliases2 }
2710
+ ])
2711
+ )
1618
2712
  };
1619
2713
  registerModels(next, [
1620
2714
  {
@@ -1629,6 +2723,12 @@ var withOpenRouterDynamicModel = (registry, llm, entry) => {
1629
2723
  return next;
1630
2724
  };
1631
2725
  var buildModelRegistry = async (llm, options = {}) => {
2726
+ if (options.providers && Object.hasOwn(options.providers, llm.provider)) {
2727
+ const registry = buildConfiguredModelRegistry(options.providers);
2728
+ if (!isUsableModelSpec(resolveModel(registry, llm.model, llm.provider)))
2729
+ throw new Error(`Unknown configured model: ${llm.provider}/${llm.model}`);
2730
+ return registry;
2731
+ }
1632
2732
  const strict = options.strict ?? true;
1633
2733
  const metadataService = options.metadataService ?? new ModelMetadataServiceImpl({
1634
2734
  storagePathService: new StoragePathServiceImpl()
@@ -1660,16 +2760,17 @@ var buildModelRegistry = async (llm, options = {}) => {
1660
2760
  const baseRegistry = applyModelMetadata(DEFAULT_MODEL_REGISTRY, {
1661
2761
  models: entries
1662
2762
  });
2763
+ registerModels(baseRegistry, configuredModelSpecs(options.providers));
1663
2764
  return resolvedEntry ? withOpenRouterDynamicModel(baseRegistry, llm, resolvedEntry) : baseRegistry;
1664
2765
  };
1665
2766
 
1666
2767
  // src/permissions/approval-mode.ts
1667
2768
  import { promises as fs2 } from "fs";
1668
- import path3 from "path";
2769
+ import path6 from "path";
1669
2770
  import { parseApprovalMode } from "@codelia/shared-types";
1670
2771
  import { ProjectsPolicyStore } from "@codelia/storage";
1671
2772
  var normalizePath = async (value) => {
1672
- const absolute = path3.resolve(value);
2773
+ const absolute = path6.resolve(value);
1673
2774
  try {
1674
2775
  return await fs2.realpath(absolute);
1675
2776
  } catch {
@@ -1814,7 +2915,7 @@ import { promises as fs4 } from "fs";
1814
2915
  // src/sandbox/context.ts
1815
2916
  import crypto2 from "crypto";
1816
2917
  import { promises as fs3 } from "fs";
1817
- import path4 from "path";
2918
+ import path7 from "path";
1818
2919
  var SecurityError = class extends Error {
1819
2920
  constructor(message) {
1820
2921
  super(message);
@@ -1834,7 +2935,7 @@ var SandboxContext = class _SandboxContext {
1834
2935
  }
1835
2936
  static async create(rootDir, options = {}) {
1836
2937
  const sessionId = crypto2.randomUUID().slice(0, 8);
1837
- const root = rootDir ? path4.resolve(rootDir) : process.cwd();
2938
+ const root = rootDir ? path7.resolve(rootDir) : process.cwd();
1838
2939
  await fs3.mkdir(root, { recursive: true });
1839
2940
  return new _SandboxContext({
1840
2941
  rootDir: root,
@@ -1844,12 +2945,12 @@ var SandboxContext = class _SandboxContext {
1844
2945
  });
1845
2946
  }
1846
2947
  resolvePath(targetPath) {
1847
- const resolved = path4.isAbsolute(targetPath) ? path4.resolve(targetPath) : path4.resolve(this.workingDir, targetPath);
2948
+ const resolved = path7.isAbsolute(targetPath) ? path7.resolve(targetPath) : path7.resolve(this.workingDir, targetPath);
1848
2949
  if (this.approvalMode === "full-access") {
1849
2950
  return resolved;
1850
2951
  }
1851
- const relative = path4.relative(this.rootDir, resolved);
1852
- if (relative === "" || !relative.startsWith("..") && !path4.isAbsolute(relative)) {
2952
+ const relative = path7.relative(this.rootDir, resolved);
2953
+ if (relative === "" || !relative.startsWith("..") && !path7.isAbsolute(relative)) {
1853
2954
  return resolved;
1854
2955
  }
1855
2956
  throw new SecurityError(
@@ -2027,9 +3128,9 @@ var normalizeLanguage = (value) => {
2027
3128
  };
2028
3129
  var languageFromFilePath = (filePath) => {
2029
3130
  if (!filePath) return void 0;
2030
- const path18 = filePath.trim().replace(/^["']|["']$/g, "");
2031
- if (!path18 || path18 === "/dev/null") return void 0;
2032
- const normalizedPath = path18.replace(/^a\//, "").replace(/^b\//, "");
3131
+ const path21 = filePath.trim().replace(/^["']|["']$/g, "");
3132
+ if (!path21 || path21 === "/dev/null") return void 0;
3133
+ const normalizedPath = path21.replace(/^a\//, "").replace(/^b\//, "");
2033
3134
  const lastSlash = Math.max(
2034
3135
  normalizedPath.lastIndexOf("/"),
2035
3136
  normalizedPath.lastIndexOf("\\")
@@ -2429,7 +3530,7 @@ var getSkillsResolver = async (ctx, key) => ctx.resolve(key);
2429
3530
  import crypto3 from "crypto";
2430
3531
  import { promises as fs5 } from "fs";
2431
3532
  import os2 from "os";
2432
- import path5 from "path";
3533
+ import path8 from "path";
2433
3534
  var DEFAULT_MARKERS2 = [".codelia", ".git", ".jj"];
2434
3535
  var SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2435
3536
  var MAX_SKILL_FILES = 200;
@@ -2455,38 +3556,38 @@ var exists2 = async (targetPath) => {
2455
3556
  };
2456
3557
  var normalizeMtime2 = (value) => Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 0;
2457
3558
  var resolvePathChain2 = (rootDir, targetDir) => {
2458
- const normalizedRoot = path5.resolve(rootDir);
2459
- const normalizedTarget = path5.resolve(targetDir);
2460
- const relative = path5.relative(normalizedRoot, normalizedTarget);
2461
- if (relative.startsWith("..") || path5.isAbsolute(relative) || relative === "..") {
3559
+ const normalizedRoot = path8.resolve(rootDir);
3560
+ const normalizedTarget = path8.resolve(targetDir);
3561
+ const relative = path8.relative(normalizedRoot, normalizedTarget);
3562
+ if (relative.startsWith("..") || path8.isAbsolute(relative) || relative === "..") {
2462
3563
  return [];
2463
3564
  }
2464
- const parts = relative.split(path5.sep).filter((part) => part.length > 0);
3565
+ const parts = relative.split(path8.sep).filter((part) => part.length > 0);
2465
3566
  const chain = [normalizedRoot];
2466
3567
  let current = normalizedRoot;
2467
3568
  for (const part of parts) {
2468
- current = path5.join(current, part);
3569
+ current = path8.join(current, part);
2469
3570
  chain.push(current);
2470
3571
  }
2471
3572
  return chain;
2472
3573
  };
2473
3574
  var findRootByMarkers2 = async (workingDir, markers) => {
2474
- let current = path5.resolve(workingDir);
3575
+ let current = path8.resolve(workingDir);
2475
3576
  while (true) {
2476
3577
  for (const marker of markers) {
2477
- if (await exists2(path5.join(current, marker))) {
3578
+ if (await exists2(path8.join(current, marker))) {
2478
3579
  return current;
2479
3580
  }
2480
3581
  }
2481
- const parent = path5.dirname(current);
3582
+ const parent = path8.dirname(current);
2482
3583
  if (parent === current) {
2483
- return path5.resolve(workingDir);
3584
+ return path8.resolve(workingDir);
2484
3585
  }
2485
3586
  current = parent;
2486
3587
  }
2487
3588
  };
2488
3589
  var tryResolvePath = async (targetPath) => {
2489
- const resolved = path5.resolve(targetPath);
3590
+ const resolved = path8.resolve(targetPath);
2490
3591
  try {
2491
3592
  return { resolved, canonical: await fs5.realpath(resolved) };
2492
3593
  } catch {
@@ -2494,8 +3595,8 @@ var tryResolvePath = async (targetPath) => {
2494
3595
  }
2495
3596
  };
2496
3597
  var isWithin = (basePath, candidatePath) => {
2497
- const relative = path5.relative(basePath, candidatePath);
2498
- return relative === "" || !relative.startsWith("..") && !path5.isAbsolute(relative);
3598
+ const relative = path8.relative(basePath, candidatePath);
3599
+ return relative === "" || !relative.startsWith("..") && !path8.isAbsolute(relative);
2499
3600
  };
2500
3601
  var hashPath = (value) => crypto3.createHash("sha256").update(value).digest("hex").slice(0, 24);
2501
3602
  var parseFrontmatter = (content) => {
@@ -2544,12 +3645,12 @@ var SkillsResolver = class _SkillsResolver {
2544
3645
  }
2545
3646
  static async create(options) {
2546
3647
  const env = options.env ?? process.env;
2547
- const workingDir = path5.resolve(options.workingDir);
3648
+ const workingDir = path8.resolve(options.workingDir);
2548
3649
  const rootOverride = toTrimmed2(env.CODELIA_AGENTS_ROOT);
2549
3650
  const markers = parseMarkers2(env.CODELIA_AGENTS_MARKERS) ?? DEFAULT_MARKERS2;
2550
- const rootDir = rootOverride ? path5.resolve(rootOverride) : await findRootByMarkers2(workingDir, markers);
3651
+ const rootDir = rootOverride ? path8.resolve(rootOverride) : await findRootByMarkers2(workingDir, markers);
2551
3652
  const homeDir = toTrimmed2(env.HOME) ?? os2.homedir();
2552
- const userSkillsDir = path5.join(path5.resolve(homeDir), ".agents", "skills");
3653
+ const userSkillsDir = path8.join(path8.resolve(homeDir), ".agents", "skills");
2553
3654
  const resolver = new _SkillsResolver({
2554
3655
  workingDir,
2555
3656
  rootDir,
@@ -2572,7 +3673,7 @@ var SkillsResolver = class _SkillsResolver {
2572
3673
  return;
2573
3674
  }
2574
3675
  for (const entry of entries) {
2575
- const entryPath = path5.join(dirPath, entry.name);
3676
+ const entryPath = path8.join(dirPath, entry.name);
2576
3677
  if (entry.isDirectory()) {
2577
3678
  await walk(entryPath);
2578
3679
  continue;
@@ -2589,7 +3690,7 @@ var SkillsResolver = class _SkillsResolver {
2589
3690
  const directories = resolvePathChain2(this.rootDir, this.workingDir);
2590
3691
  const skillFiles = [];
2591
3692
  for (const directoryPath of directories) {
2592
- const skillsRoot = path5.join(directoryPath, ".agents", "skills");
3693
+ const skillsRoot = path8.join(directoryPath, ".agents", "skills");
2593
3694
  if (!await exists2(skillsRoot)) continue;
2594
3695
  const files = await this.collectSkillFilesInTree(skillsRoot);
2595
3696
  skillFiles.push(...files);
@@ -2646,8 +3747,8 @@ var SkillsResolver = class _SkillsResolver {
2646
3747
  }
2647
3748
  };
2648
3749
  }
2649
- const dir = path5.dirname(normalized.canonical);
2650
- if (path5.basename(dir) !== name) {
3750
+ const dir = path8.dirname(normalized.canonical);
3751
+ if (path8.basename(dir) !== name) {
2651
3752
  return {
2652
3753
  error: {
2653
3754
  path: normalized.canonical,
@@ -2796,7 +3897,7 @@ var SkillsResolver = class _SkillsResolver {
2796
3897
  }
2797
3898
  const catalog = await this.getCatalog();
2798
3899
  const normalizedQuery = query.toLowerCase();
2799
- const queryPathCandidate = path5.resolve(this.workingDir, query);
3900
+ const queryPathCandidate = path8.resolve(this.workingDir, query);
2800
3901
  const queryTokens = new Set(tokenize(normalizedQuery));
2801
3902
  const scored = [];
2802
3903
  for (const skill of catalog.skills) {
@@ -2854,7 +3955,7 @@ var SkillsResolver = class _SkillsResolver {
2854
3955
  try {
2855
3956
  rootReal = await fs5.realpath(skillDir);
2856
3957
  } catch {
2857
- rootReal = path5.resolve(skillDir);
3958
+ rootReal = path8.resolve(skillDir);
2858
3959
  }
2859
3960
  const files = [];
2860
3961
  let bytes = 0;
@@ -2872,7 +3973,7 @@ var SkillsResolver = class _SkillsResolver {
2872
3973
  }
2873
3974
  for (const entry of entries) {
2874
3975
  if (truncated) break;
2875
- const entryPath = path5.join(dirPath, entry.name);
3976
+ const entryPath = path8.join(dirPath, entry.name);
2876
3977
  if (entry.isSymbolicLink()) {
2877
3978
  continue;
2878
3979
  }
@@ -2887,7 +3988,7 @@ var SkillsResolver = class _SkillsResolver {
2887
3988
  try {
2888
3989
  realPath = await fs5.realpath(entryPath);
2889
3990
  } catch {
2890
- realPath = path5.resolve(entryPath);
3991
+ realPath = path8.resolve(entryPath);
2891
3992
  }
2892
3993
  if (!isWithin(rootReal, realPath)) {
2893
3994
  continue;
@@ -2916,7 +4017,7 @@ var SkillsResolver = class _SkillsResolver {
2916
4017
  return { files, truncated };
2917
4018
  }
2918
4019
  async resolveByPath(pathInput) {
2919
- const resolved = path5.isAbsolute(pathInput) ? path5.resolve(pathInput) : path5.resolve(this.workingDir, pathInput);
4020
+ const resolved = path8.isAbsolute(pathInput) ? path8.resolve(pathInput) : path8.resolve(this.workingDir, pathInput);
2920
4021
  const resolvedTry = await tryResolvePath(resolved);
2921
4022
  const byCanonical = this.catalog.skills.find(
2922
4023
  (entry) => entry.path === resolvedTry.canonical
@@ -2986,7 +4087,7 @@ var SkillsResolver = class _SkillsResolver {
2986
4087
  }
2987
4088
  const list = await this.listSkillFiles(selected.dir);
2988
4089
  const filesXml = list.files.map((entry) => `<file>${entry}</file>`).join("\n");
2989
- const trailingSlashDir = selected.dir.endsWith(path5.sep) ? selected.dir : `${selected.dir}${path5.sep}`;
4090
+ const trailingSlashDir = selected.dir.endsWith(path8.sep) ? selected.dir : `${selected.dir}${path8.sep}`;
2990
4091
  const content = [
2991
4092
  `<skill_context name="${xmlEscape(selected.name)}" path="${xmlEscape(selected.path)}">`,
2992
4093
  skillBody.trimEnd(),
@@ -3029,13 +4130,13 @@ ${skillsCatalog}`;
3029
4130
  };
3030
4131
 
3031
4132
  // src/subagents/coordinator.ts
3032
- import { createHash, randomUUID as randomUUID2 } from "crypto";
4133
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "crypto";
3033
4134
  import { SUBAGENT_MAX_CONCURRENT_LIMIT } from "@codelia/config";
3034
- import { z as z3 } from "zod";
4135
+ import { z as z7 } from "zod";
3035
4136
 
3036
4137
  // src/subagents/parent-channel.ts
3037
- import { randomUUID } from "crypto";
3038
- import { z as z2 } from "zod";
4138
+ import { randomUUID as randomUUID2 } from "crypto";
4139
+ import { z as z6 } from "zod";
3039
4140
 
3040
4141
  // src/volatile-stores.ts
3041
4142
  var stringifyMessageContent = (value) => {
@@ -3157,9 +4258,9 @@ var subagentTaskInfo = (task) => ({
3157
4258
  });
3158
4259
 
3159
4260
  // src/subagents/parent-channel.ts
3160
- var shellInput = z2.object({
3161
- command: z2.string().min(1).max(32768),
3162
- timeout_seconds: z2.number().int().min(1).max(300).optional()
4261
+ var shellInput = z6.object({
4262
+ command: z6.string().min(1).max(32768),
4263
+ timeout_seconds: z6.number().int().min(1).max(300).optional()
3163
4264
  }).strict();
3164
4265
  var createParentChannel = ({
3165
4266
  tasks,
@@ -3204,11 +4305,11 @@ var createParentChannel = ({
3204
4305
  throw new Error("sender_finished");
3205
4306
  }
3206
4307
  if (operation === "send") {
3207
- const params2 = z2.object({ recipient: z2.string().min(1), content: z2.string() }).strict().parse(raw);
4308
+ const params2 = z6.object({ recipient: z6.string().min(1), content: z6.string() }).strict().parse(raw);
3208
4309
  return mailbox.send(owner, sender, params2.recipient, params2.content);
3209
4310
  }
3210
4311
  if (operation === "receive") {
3211
- const params2 = z2.object({ wait_seconds: z2.number().min(0).max(120).optional() }).strict().parse(raw);
4312
+ const params2 = z6.object({ wait_seconds: z6.number().min(0).max(120).optional() }).strict().parse(raw);
3212
4313
  return mailbox.receive(owner, sender, params2.wait_seconds ?? 0, signal);
3213
4314
  }
3214
4315
  if (operation === "list")
@@ -3244,7 +4345,7 @@ var createParentChannel = ({
3244
4345
  signal?.throwIfAborted();
3245
4346
  const task = await tasks.spawn(
3246
4347
  {
3247
- task_id: randomUUID(),
4348
+ task_id: randomUUID2(),
3248
4349
  kind: "shell",
3249
4350
  parent_session_id: owner,
3250
4351
  parent_tool_call_id: sender,
@@ -3284,38 +4385,38 @@ var createParentChannel = ({
3284
4385
 
3285
4386
  // src/subagents/coordinator.ts
3286
4387
  var DEFAULT_MAX_CONCURRENT = 8;
3287
- var subagentSpawnSchema = z3.object({
3288
- kind: z3.literal("subagent").default("subagent"),
3289
- prompt: z3.string().trim().min(1).max(32768).describe(
4388
+ var subagentSpawnSchema = z7.object({
4389
+ kind: z7.literal("subagent").default("subagent"),
4390
+ prompt: z7.string().trim().min(1).max(32768).describe(
3290
4391
  "Self-contained delegated task; child has no parent conversation. Maximum 32768 characters."
3291
4392
  ),
3292
4393
  name: subagentNameSchema.describe(
3293
4394
  "Choose a short, distinctive agent code name; vary freely using invented words or combinations instead of a fixed roster or numbered sequence. Required, 1-48 characters; start with a letter and use letters, digits, spaces, periods, apostrophes or hyphens. Unique in this parent session, including completed tasks; parent is reserved. On collision choose another name. Use label for the assignment and task_id for addressing."
3294
4395
  ),
3295
- profile: z3.string().trim().min(1).max(64).optional().describe(
4396
+ profile: z7.string().trim().min(1).max(64).optional().describe(
3296
4397
  "Configured purpose-specific model profile from <subagent_model_profiles>. Use when requested by the user or when its described purpose matches the delegated work. Mutually exclusive with model. Unknown profiles fail; no fallback."
3297
4398
  ),
3298
4399
  model: subagentModelSelectionSchema.optional().describe(
3299
4400
  "Use the user-requested model for this child. Omit model and profile to use the configured default_profile, or the parent model if unconfigured. Do not combine model with profile. An explicit selection replaces model settings; no credential/model probe or automatic fallback. Authentication and provider errors return through the task result."
3300
4401
  ),
3301
- label: z3.string().max(80).optional().describe(
4402
+ label: z7.string().max(80).optional().describe(
3302
4403
  "Work assignment, such as API implementation; separate from the child's agent name."
3303
4404
  ),
3304
- background: z3.boolean().optional().describe(
4405
+ background: z7.boolean().optional().describe(
3305
4406
  "Default true: return task_id immediately. False attaches a cancellable wait; the child survives parent-turn stop."
3306
4407
  ),
3307
- context_mode: z3.literal("fresh").optional().describe("Only fresh sessions are supported."),
3308
- workspace_mode: z3.literal("live_workspace").optional(),
3309
- workspace_access: z3.enum(["read-only", "read-write"]).optional().describe(
4408
+ context_mode: z7.literal("fresh").optional().describe("Only fresh sessions are supported."),
4409
+ workspace_mode: z7.literal("live_workspace").optional(),
4410
+ workspace_access: z7.enum(["read-only", "read-write"]).optional().describe(
3310
4411
  "Default read-write in the shared workspace. For read-only research choose read-only and omit tool_allowlist: read, read_line, list_files, search_files remain available. Read-only never permits edit, write, or shell (even for read-only commands)."
3311
4412
  ),
3312
- tool_allowlist: z3.array(z3.enum(WRITABLE_TOOLS)).max(7).optional().describe(
4413
+ tool_allowlist: z7.array(z7.enum(WRITABLE_TOOLS)).max(7).optional().describe(
3313
4414
  "Usually omit: workspace_access selects the complete allowed tool set. Supply only to restrict it further. Read-only permits read, read_line, list_files, search_files; read-write additionally permits edit, write, shell. Messages are always available; no recursive delegation."
3314
4415
  ),
3315
- max_steps: z3.number().int().min(1).max(200).optional().describe(
4416
+ max_steps: z7.number().int().min(1).max(200).optional().describe(
3316
4417
  "Child iteration limit; default 50. Exhaustion returns failed/max_steps with partial results."
3317
4418
  ),
3318
- timeout_seconds: z3.number().int().min(1).max(3600).optional().describe(
4419
+ timeout_seconds: z7.number().int().min(1).max(3600).optional().describe(
3319
4420
  "Optional execution deadline in seconds (1\u20133600), covering bootstrap through final result. Omit for no time limit; separate from the parent's wait timeout."
3320
4421
  )
3321
4422
  }).strict().superRefine((input, ctx) => {
@@ -3362,7 +4463,7 @@ var AgentTreeCoordinator = class {
3362
4463
  });
3363
4464
  }
3364
4465
  configure(parent) {
3365
- z3.number().int().min(1).max(SUBAGENT_MAX_CONCURRENT_LIMIT).parse(parent.subagent?.max_concurrent ?? DEFAULT_MAX_CONCURRENT);
4466
+ z7.number().int().min(1).max(SUBAGENT_MAX_CONCURRENT_LIMIT).parse(parent.subagent?.max_concurrent ?? DEFAULT_MAX_CONCURRENT);
3366
4467
  this.parent = structuredClone(parent);
3367
4468
  }
3368
4469
  isAvailable() {
@@ -3410,7 +4511,7 @@ var AgentTreeCoordinator = class {
3410
4511
  for (const tool of allowlist)
3411
4512
  if (permissions.evaluate(tool, "{}").decision === "deny")
3412
4513
  throw new Error("delegated tool denied by parent policy");
3413
- const task_id = randomUUID2();
4514
+ const task_id = randomUUID3();
3414
4515
  const permission = {
3415
4516
  tool_allowlist: allowlist,
3416
4517
  workspace_access: workspaceAccess,
@@ -3431,7 +4532,7 @@ var AgentTreeCoordinator = class {
3431
4532
  0
3432
4533
  ) + 1,
3433
4534
  context_mode: "fresh",
3434
- effective_policy_id: createHash("sha256").update(JSON.stringify({ permission, root: parent.workspace_root })).digest("hex"),
4535
+ effective_policy_id: createHash2("sha256").update(JSON.stringify({ permission, root: parent.workspace_root })).digest("hex"),
3435
4536
  workspace_lease_id: task_id
3436
4537
  };
3437
4538
  const profileName = input.model ? void 0 : input.profile ?? parent.subagent?.default_profile;
@@ -3441,6 +4542,10 @@ var AgentTreeCoordinator = class {
3441
4542
  }
3442
4543
  const requestedModel = input.model ?? (profileName ? profiles?.[profileName].model : void 0);
3443
4544
  const selectedModel = requestedModel ? subagentModelSelectionSchema.parse(requestedModel) : void 0;
4545
+ const selectedProvider = selectedModel?.provider ?? parent.model.provider;
4546
+ if (selectedProvider && !configuredProviders(parent.model.providers).includes(selectedProvider)) {
4547
+ throw new Error(`Unsupported subagent provider: ${selectedProvider}`);
4548
+ }
3444
4549
  const launch = {
3445
4550
  version: 1,
3446
4551
  task_id,
@@ -3449,7 +4554,8 @@ var AgentTreeCoordinator = class {
3449
4554
  workspace_root: parent.workspace_root,
3450
4555
  model: selectedModel ? {
3451
4556
  ...selectedModel,
3452
- provider: selectedModel.provider ?? parent.model.provider
4557
+ ...parent.model.providers ? { providers: parent.model.providers } : {},
4558
+ provider: selectedProvider
3453
4559
  } : parent.model,
3454
4560
  permission
3455
4561
  };
@@ -3520,8 +4626,8 @@ var AgentTreeCoordinator = class {
3520
4626
  };
3521
4627
 
3522
4628
  // src/tools/search.ts
3523
- import { defineTool } from "@codelia/core";
3524
- import { z as z4 } from "zod";
4629
+ import { defineTool as defineTool2 } from "@codelia/core";
4630
+ import { z as z8 } from "zod";
3525
4631
  var normalizeDomain = (value) => value.trim().toLowerCase().replace(/\.+$/, "");
3526
4632
  var shouldKeepUrl = (url, allowedDomains) => {
3527
4633
  if (!allowedDomains.length) return true;
@@ -3637,14 +4743,14 @@ var runBraveSearch = async (query, maxResults, allowedDomains, apiKey) => {
3637
4743
  const parsed = parseBrave(payload);
3638
4744
  return normalizeEntries(parsed, allowedDomains, maxResults);
3639
4745
  };
3640
- var createSearchTool = (options) => defineTool({
4746
+ var createSearchTool = (options) => defineTool2({
3641
4747
  name: "search",
3642
4748
  description: "Search the web and return concise source candidates.",
3643
- input: z4.object({
3644
- query: z4.string().min(1).describe("Search query."),
3645
- max_results: z4.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
3646
- backend: z4.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
3647
- allowed_domains: z4.array(z4.string().min(1)).optional().describe("Optional allowlist of domains.")
4749
+ input: z8.object({
4750
+ query: z8.string().min(1).describe("Search query."),
4751
+ max_results: z8.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
4752
+ backend: z8.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
4753
+ allowed_domains: z8.array(z8.string().min(1)).optional().describe("Optional allowlist of domains.")
3648
4754
  }),
3649
4755
  execute: async (input) => {
3650
4756
  const backend = input.backend ?? options.defaultBackend;
@@ -3726,6 +4832,7 @@ var loadRuntimeHostTools = async (providers) => {
3726
4832
  var composeRuntimeTools = async ({
3727
4833
  provider,
3728
4834
  baseTools,
4835
+ imageTools = [],
3729
4836
  mcpTools,
3730
4837
  hostTools,
3731
4838
  searchConfig
@@ -3745,7 +4852,17 @@ var composeRuntimeTools = async ({
3745
4852
  braveApiKeyEnv: searchConfig.local.braveApiKeyEnv
3746
4853
  })
3747
4854
  ] : [];
3748
- const tools = [...baseTools, ...localSearchTools, ...mcpTools, ...hostTools];
4855
+ const tools = [
4856
+ ...baseTools,
4857
+ ...imageTools,
4858
+ ...localSearchTools,
4859
+ ...mcpTools,
4860
+ ...hostTools
4861
+ ];
4862
+ for (const imageTool of imageTools) {
4863
+ if (tools.filter((tool) => tool.name === imageTool.name).length !== 1)
4864
+ throw new Error(`Image tool name conflict: ${imageTool.name}`);
4865
+ }
3749
4866
  return {
3750
4867
  tools,
3751
4868
  toolDefinitions: [...tools.map((tool) => tool.definition), ...hostedTools],
@@ -3759,13 +4876,13 @@ var composeRuntimeTools = async ({
3759
4876
  };
3760
4877
 
3761
4878
  // src/tools/agents-resolve.ts
3762
- import { defineTool as defineTool2 } from "@codelia/core";
3763
- import { z as z5 } from "zod";
3764
- var createAgentsResolveTool = (sandboxKey, agentsResolverKey) => defineTool2({
4879
+ import { defineTool as defineTool3 } from "@codelia/core";
4880
+ import { z as z9 } from "zod";
4881
+ var createAgentsResolveTool = (sandboxKey, agentsResolverKey) => defineTool3({
3765
4882
  name: "agents_resolve",
3766
4883
  description: "Resolve AGENTS.md files applicable to a target path (metadata only).",
3767
- input: z5.object({
3768
- path: z5.string().describe(
4884
+ input: z9.object({
4885
+ path: z9.string().describe(
3769
4886
  "Target file or directory path to resolve AGENTS.md scope for."
3770
4887
  )
3771
4888
  }),
@@ -3799,9 +4916,9 @@ var createAgentsResolveTool = (sandboxKey, agentsResolverKey) => defineTool2({
3799
4916
 
3800
4917
  // src/tools/apply-patch.ts
3801
4918
  import { promises as fs6 } from "fs";
3802
- import path6 from "path";
3803
- import { defineTool as defineTool3 } from "@codelia/core";
3804
- import { z as z6 } from "zod";
4919
+ import path9 from "path";
4920
+ import { defineTool as defineTool4 } from "@codelia/core";
4921
+ import { z as z10 } from "zod";
3805
4922
 
3806
4923
  // src/tools/diff-payload.ts
3807
4924
  import crypto4 from "crypto";
@@ -4352,7 +5469,7 @@ var applyPreparedChanges = async (changes) => {
4352
5469
  continue;
4353
5470
  }
4354
5471
  if (change.kind === "move" && change.resolvedMoveTo) {
4355
- await fs6.mkdir(path6.dirname(change.resolvedMoveTo), { recursive: true });
5472
+ await fs6.mkdir(path9.dirname(change.resolvedMoveTo), { recursive: true });
4356
5473
  await fs6.writeFile(change.resolvedMoveTo, change.after, "utf8");
4357
5474
  if (typeof change.sourceMode === "number") {
4358
5475
  await fs6.chmod(change.resolvedMoveTo, change.sourceMode);
@@ -4360,7 +5477,7 @@ var applyPreparedChanges = async (changes) => {
4360
5477
  await fs6.unlink(change.resolvedPath);
4361
5478
  continue;
4362
5479
  }
4363
- await fs6.mkdir(path6.dirname(change.resolvedPath), { recursive: true });
5480
+ await fs6.mkdir(path9.dirname(change.resolvedPath), { recursive: true });
4364
5481
  await fs6.writeFile(change.resolvedPath, change.after, "utf8");
4365
5482
  }
4366
5483
  };
@@ -4401,12 +5518,12 @@ var summarizeChanges = (changes, dryRun) => {
4401
5518
  files: fileSummaries
4402
5519
  };
4403
5520
  };
4404
- var createApplyPatchTool = (sandboxKey, outputCacheStore) => defineTool3({
5521
+ var createApplyPatchTool = (sandboxKey, outputCacheStore) => defineTool4({
4405
5522
  name: "apply_patch",
4406
5523
  description: "Apply a codex-style multi-file patch; use dry_run to preview only.",
4407
- input: z6.object({
4408
- patch: z6.string().min(1).describe("Full patch text between *** Begin Patch and *** End Patch."),
4409
- dry_run: z6.boolean().optional().describe("Preview the patch without writing files. Default false.")
5524
+ input: z10.object({
5525
+ patch: z10.string().min(1).describe("Full patch text between *** Begin Patch and *** End Patch."),
5526
+ dry_run: z10.boolean().optional().describe("Preview the patch without writing files. Default false.")
4410
5527
  }),
4411
5528
  execute: async (input, ctx) => {
4412
5529
  const dryRun = input.dry_run ?? false;
@@ -4437,13 +5554,13 @@ var createApplyPatchTool = (sandboxKey, outputCacheStore) => defineTool3({
4437
5554
  });
4438
5555
 
4439
5556
  // src/tools/done.ts
4440
- import { defineTool as defineTool4, TaskComplete } from "@codelia/core";
4441
- import { z as z7 } from "zod";
4442
- var createDoneTool = () => defineTool4({
5557
+ import { defineTool as defineTool5, TaskComplete } from "@codelia/core";
5558
+ import { z as z11 } from "zod";
5559
+ var createDoneTool = () => defineTool5({
4443
5560
  name: "done",
4444
5561
  description: "Mark the task as complete and return a final message.",
4445
- input: z7.object({
4446
- message: z7.string().describe("Final user-facing completion message.")
5562
+ input: z11.object({
5563
+ message: z11.string().describe("Final user-facing completion message.")
4447
5564
  }),
4448
5565
  execute: async (input) => {
4449
5566
  throw new TaskComplete(input.message);
@@ -4452,9 +5569,9 @@ var createDoneTool = () => defineTool4({
4452
5569
 
4453
5570
  // src/tools/edit.ts
4454
5571
  import { promises as fs7 } from "fs";
4455
- import path7 from "path";
4456
- import { defineTool as defineTool5 } from "@codelia/core";
4457
- import { z as z8 } from "zod";
5572
+ import path10 from "path";
5573
+ import { defineTool as defineTool6 } from "@codelia/core";
5574
+ import { z as z12 } from "zod";
4458
5575
  var trimLine = (line) => line.replace(/\r$/, "").trim();
4459
5576
  var lineRangeToIndices = (lines, startLine, lineCount) => {
4460
5577
  let startIndex = 0;
@@ -4561,23 +5678,23 @@ var applyReplacements = (content, matches, replacement) => {
4561
5678
  }
4562
5679
  return next;
4563
5680
  };
4564
- var createEditTool = (sandboxKey, outputCacheStore) => defineTool5({
5681
+ var createEditTool = (sandboxKey, outputCacheStore) => defineTool6({
4565
5682
  name: "edit",
4566
5683
  description: "Edit a file by replacing matched text with new text; supports guarded match modes and dry-run preview.",
4567
- input: z8.object({
4568
- file_path: z8.string().describe(
5684
+ input: z12.object({
5685
+ file_path: z12.string().describe(
4569
5686
  "File path. Sandbox-bounded unless full-access mode is active."
4570
5687
  ),
4571
- old_string: z8.string().describe(
5688
+ old_string: z12.string().describe(
4572
5689
  "Text to find. Use empty string to replace the whole file content."
4573
5690
  ),
4574
- new_string: z8.string().describe("Replacement text."),
4575
- replace_all: z8.boolean().optional().describe("Replace all matches when true. Default false."),
4576
- match_mode: z8.enum(["exact", "line_trimmed", "block_anchor", "auto"]).optional().describe(
5691
+ new_string: z12.string().describe("Replacement text."),
5692
+ replace_all: z12.boolean().optional().describe("Replace all matches when true. Default false."),
5693
+ match_mode: z12.enum(["exact", "line_trimmed", "block_anchor", "auto"]).optional().describe(
4577
5694
  "Match strategy: exact, line_trimmed, block_anchor, or auto (tries exact -> line_trimmed -> block_anchor). Default auto."
4578
5695
  ),
4579
- expected_replacements: z8.number().int().nonnegative().optional().describe("Expected replacement count (guard)."),
4580
- dry_run: z8.boolean().optional().describe("Preview diff only when true. Default false."),
5696
+ expected_replacements: z12.number().int().nonnegative().optional().describe("Expected replacement count (guard)."),
5697
+ dry_run: z12.boolean().optional().describe("Preview diff only when true. Default false."),
4581
5698
  expected_hash: expectedContentHashSchema
4582
5699
  }),
4583
5700
  execute: async (input, ctx) => {
@@ -4678,7 +5795,7 @@ var createEditTool = (sandboxKey, outputCacheStore) => defineTool5({
4678
5795
  };
4679
5796
  }
4680
5797
  try {
4681
- await fs7.mkdir(path7.dirname(resolved), { recursive: true });
5798
+ await fs7.mkdir(path10.dirname(resolved), { recursive: true });
4682
5799
  await fs7.writeFile(resolved, nextContent, "utf8");
4683
5800
  } catch (error) {
4684
5801
  throw new Error(`Error editing file: ${String(error)}`);
@@ -4694,14 +5811,14 @@ var createEditTool = (sandboxKey, outputCacheStore) => defineTool5({
4694
5811
  });
4695
5812
 
4696
5813
  // src/tools/lane.ts
4697
- import { defineTool as defineTool6 } from "@codelia/core";
4698
- import { z as z9 } from "zod";
5814
+ import { defineTool as defineTool7 } from "@codelia/core";
5815
+ import { z as z13 } from "zod";
4699
5816
 
4700
5817
  // src/lanes/manager.ts
4701
5818
  import crypto5 from "crypto";
4702
5819
  import { promises as fs9 } from "fs";
4703
5820
  import os3 from "os";
4704
- import path9 from "path";
5821
+ import path12 from "path";
4705
5822
 
4706
5823
  // src/lanes/command.ts
4707
5824
  import { spawn as spawn3 } from "child_process";
@@ -4784,8 +5901,8 @@ ${stdout}`.trim();
4784
5901
 
4785
5902
  // src/lanes/registry.ts
4786
5903
  import { promises as fs8 } from "fs";
4787
- import path8 from "path";
4788
- import { resolveStoragePaths } from "@codelia/storage";
5904
+ import path11 from "path";
5905
+ import { resolveStoragePaths as resolveStoragePaths2 } from "@codelia/storage";
4789
5906
  var REGISTRY_DIRNAME = "lanes";
4790
5907
  var REGISTRY_FILENAME = "registry.json";
4791
5908
  var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
@@ -4806,9 +5923,9 @@ var readJsonFile = async (filePath) => {
4806
5923
  }
4807
5924
  };
4808
5925
  var atomicWrite = async (filePath, payload) => {
4809
- const dir = path8.dirname(filePath);
4810
- const base = path8.basename(filePath);
4811
- const tmp = path8.join(
5926
+ const dir = path11.dirname(filePath);
5927
+ const base = path11.basename(filePath);
5928
+ const tmp = path11.join(
4812
5929
  dir,
4813
5930
  `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
4814
5931
  );
@@ -4822,11 +5939,11 @@ var LaneRegistryStore = class {
4822
5939
  this.registryPath = registryPath;
4823
5940
  return;
4824
5941
  }
4825
- const root = resolveStoragePaths().root;
4826
- this.registryPath = path8.join(root, REGISTRY_DIRNAME, REGISTRY_FILENAME);
5942
+ const root = resolveStoragePaths2().root;
5943
+ this.registryPath = path11.join(root, REGISTRY_DIRNAME, REGISTRY_FILENAME);
4827
5944
  }
4828
5945
  async ensureDir() {
4829
- await fs8.mkdir(path8.dirname(this.registryPath), { recursive: true });
5946
+ await fs8.mkdir(path11.dirname(this.registryPath), { recursive: true });
4830
5947
  }
4831
5948
  async readAll() {
4832
5949
  await this.ensureDir();
@@ -4926,7 +6043,7 @@ var LaneManager = class {
4926
6043
  this.now = options.now ?? nowIso2;
4927
6044
  this.randomId = options.randomId ?? (() => crypto5.randomUUID());
4928
6045
  this.launchCommand = options.launchCommand ?? process.env.CODELIA_LANE_LAUNCH_COMMAND?.trim() ?? "codelia";
4929
- this.defaultWorktreeRoot = options.defaultWorktreeRoot ?? path9.join(os3.homedir(), ".codelia", "worktrees");
6046
+ this.defaultWorktreeRoot = options.defaultWorktreeRoot ?? path12.join(os3.homedir(), ".codelia", "worktrees");
4930
6047
  }
4931
6048
  async cmd(command, args, options) {
4932
6049
  debugLog(`lane.cmd ${command} ${args.join(" ")}`);
@@ -5049,9 +6166,9 @@ var LaneManager = class {
5049
6166
  "rev-parse",
5050
6167
  "--git-common-dir"
5051
6168
  ]);
5052
- const commonDir = path9.resolve(worktreePath, stdout.trim());
5053
- if (path9.basename(commonDir) === ".git") {
5054
- return path9.dirname(commonDir);
6169
+ const commonDir = path12.resolve(worktreePath, stdout.trim());
6170
+ if (path12.basename(commonDir) === ".git") {
6171
+ return path12.dirname(commonDir);
5055
6172
  }
5056
6173
  return await this.resolveRepoRoot(worktreePath);
5057
6174
  }
@@ -5093,10 +6210,10 @@ var LaneManager = class {
5093
6210
  await this.preflightBackend(backend);
5094
6211
  const repoRoot = await this.resolveRepoRoot(options.workingDir);
5095
6212
  const laneId = this.randomId();
5096
- const slug = toSlug(taskId);
6213
+ const slug2 = toSlug(taskId);
5097
6214
  const shortId = laneId.slice(0, 8);
5098
- const branchName = `lane/${slug}-${shortId}`;
5099
- const worktreePath = input.worktree_path ? path9.resolve(options.workingDir, input.worktree_path) : path9.join(this.defaultWorktreeRoot, `${slug}-${shortId}`);
6215
+ const branchName = `lane/${slug2}-${shortId}`;
6216
+ const worktreePath = input.worktree_path ? path12.resolve(options.workingDir, input.worktree_path) : path12.join(this.defaultWorktreeRoot, `${slug2}-${shortId}`);
5100
6217
  const muxTarget = `codelia-lane-${shortId}`;
5101
6218
  const createdAt = this.now();
5102
6219
  const record = {
@@ -5114,7 +6231,7 @@ var LaneManager = class {
5114
6231
  };
5115
6232
  await this.registry.upsert(record);
5116
6233
  try {
5117
- await fs9.mkdir(path9.dirname(worktreePath), { recursive: true });
6234
+ await fs9.mkdir(path12.dirname(worktreePath), { recursive: true });
5118
6235
  await this.cmd("git", [
5119
6236
  "-C",
5120
6237
  repoRoot,
@@ -5267,7 +6384,7 @@ var LaneManager = class {
5267
6384
 
5268
6385
  // src/tools/lane.ts
5269
6386
  var laneManager = new LaneManager();
5270
- var backendSchema = z9.enum(["tmux", "zellij"]);
6387
+ var backendSchema = z13.enum(["tmux", "zellij"]);
5271
6388
  var formatError = (error) => {
5272
6389
  if (error instanceof LaneManagerError) {
5273
6390
  return new Error(`${error.code}: ${error.message}`);
@@ -5294,17 +6411,17 @@ var buildLaneHints = (lane) => {
5294
6411
  }
5295
6412
  };
5296
6413
  };
5297
- var createLaneCreateTool = (sandboxKey) => defineTool6({
6414
+ var createLaneCreateTool = (sandboxKey) => defineTool7({
5298
6415
  name: "lane_create",
5299
6416
  description: "Create a Task lane (worktree slot) and start autonomous execution in tmux/zellij.",
5300
- input: z9.object({
5301
- task_id: z9.string().describe("Task identifier."),
5302
- base_ref: z9.string().optional().describe("Base git ref. Default: HEAD."),
5303
- worktree_path: z9.string().optional().describe(
6417
+ input: z13.object({
6418
+ task_id: z13.string().describe("Task identifier."),
6419
+ base_ref: z13.string().optional().describe("Base git ref. Default: HEAD."),
6420
+ worktree_path: z13.string().optional().describe(
5304
6421
  "Optional worktree path override. Default: ~/.codelia/worktrees/<task-slug>-<lane-id8>."
5305
6422
  ),
5306
6423
  mux_backend: backendSchema.optional().describe("Multiplexer backend. Default: tmux."),
5307
- seed_context: z9.string().optional().describe("Optional initial text context.")
6424
+ seed_context: z13.string().optional().describe("Optional initial text context.")
5308
6425
  }),
5309
6426
  execute: async (input, ctx) => {
5310
6427
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -5329,11 +6446,11 @@ var createLaneCreateTool = (sandboxKey) => defineTool6({
5329
6446
  }
5330
6447
  }
5331
6448
  });
5332
- var createLaneListTool = (sandboxKey) => defineTool6({
6449
+ var createLaneListTool = (sandboxKey) => defineTool7({
5333
6450
  name: "lane_list",
5334
6451
  description: "List Task lanes (worktree slots) and current states.",
5335
- input: z9.object({
5336
- include_closed: z9.boolean().optional().describe("Include closed lanes. Default: false.")
6452
+ input: z13.object({
6453
+ include_closed: z13.boolean().optional().describe("Include closed lanes. Default: false.")
5337
6454
  }),
5338
6455
  execute: async (input, ctx) => {
5339
6456
  await getSandboxContext(ctx, sandboxKey);
@@ -5353,11 +6470,11 @@ var createLaneListTool = (sandboxKey) => defineTool6({
5353
6470
  }
5354
6471
  }
5355
6472
  });
5356
- var createLaneStatusTool = (sandboxKey) => defineTool6({
6473
+ var createLaneStatusTool = (sandboxKey) => defineTool7({
5357
6474
  name: "lane_status",
5358
6475
  description: "Get Task lane status and backend liveness.",
5359
- input: z9.object({
5360
- lane_id: z9.string().describe("Lane id.")
6476
+ input: z13.object({
6477
+ lane_id: z13.string().describe("Lane id.")
5361
6478
  }),
5362
6479
  execute: async (input, ctx) => {
5363
6480
  await getSandboxContext(ctx, sandboxKey);
@@ -5372,13 +6489,13 @@ var createLaneStatusTool = (sandboxKey) => defineTool6({
5372
6489
  }
5373
6490
  }
5374
6491
  });
5375
- var createLaneCloseTool = (sandboxKey) => defineTool6({
6492
+ var createLaneCloseTool = (sandboxKey) => defineTool7({
5376
6493
  name: "lane_close",
5377
6494
  description: "Close a Task lane and optionally remove its worktree.",
5378
- input: z9.object({
5379
- lane_id: z9.string().describe("Lane id."),
5380
- remove_worktree: z9.boolean().optional().describe("Remove worktree. Default: true."),
5381
- force: z9.boolean().optional().describe("Force close/cleanup. Default: false.")
6495
+ input: z13.object({
6496
+ lane_id: z13.string().describe("Lane id."),
6497
+ remove_worktree: z13.boolean().optional().describe("Remove worktree. Default: true."),
6498
+ force: z13.boolean().optional().describe("Force close/cleanup. Default: false.")
5382
6499
  }),
5383
6500
  execute: async (input, ctx) => {
5384
6501
  await getSandboxContext(ctx, sandboxKey);
@@ -5397,13 +6514,13 @@ var createLaneCloseTool = (sandboxKey) => defineTool6({
5397
6514
  }
5398
6515
  }
5399
6516
  });
5400
- var createLaneGcTool = (sandboxKey) => defineTool6({
6517
+ var createLaneGcTool = (sandboxKey) => defineTool7({
5401
6518
  name: "lane_gc",
5402
6519
  description: "Close stale finished/error lanes after idle TTL.",
5403
- input: z9.object({
5404
- idle_ttl_minutes: z9.number().int().positive().describe("Idle TTL in minutes."),
5405
- remove_worktree: z9.boolean().optional().describe("Remove worktree on close. Default: false."),
5406
- force: z9.boolean().optional().describe("Force cleanup for dirty worktrees. Default: false.")
6520
+ input: z13.object({
6521
+ idle_ttl_minutes: z13.number().int().positive().describe("Idle TTL in minutes."),
6522
+ remove_worktree: z13.boolean().optional().describe("Remove worktree on close. Default: false."),
6523
+ force: z13.boolean().optional().describe("Force cleanup for dirty worktrees. Default: false.")
5407
6524
  }),
5408
6525
  execute: async (input, ctx) => {
5409
6526
  await getSandboxContext(ctx, sandboxKey);
@@ -5421,8 +6538,8 @@ var createLaneGcTool = (sandboxKey) => defineTool6({
5421
6538
 
5422
6539
  // src/tools/read.ts
5423
6540
  import { promises as fs10 } from "fs";
5424
- import { defineTool as defineTool7 } from "@codelia/core";
5425
- import { z as z10 } from "zod";
6541
+ import { defineTool as defineTool8 } from "@codelia/core";
6542
+ import { z as z14 } from "zod";
5426
6543
  var DEFAULT_READ_LIMIT = 2e3;
5427
6544
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
5428
6545
  var DEFAULT_MAX_BYTES = 64 * 1024;
@@ -5476,15 +6593,15 @@ var buildTruncatedLinesSummary = (lineNumbers) => {
5476
6593
  }
5477
6594
  return `[truncated lines: ${lineNumbers.join(", ")}]`;
5478
6595
  };
5479
- var createReadTool = (sandboxKey) => defineTool7({
6596
+ var createReadTool = (sandboxKey) => defineTool8({
5480
6597
  name: "read",
5481
6598
  description: "Read a bounded text-file preview by 0-based line offset/limit and return the full UTF-8 content SHA-256 metadata for edit.expected_hash; large output is truncated and long lines should fall back to read_line.",
5482
- input: z10.object({
5483
- file_path: z10.string().describe(
6599
+ input: z14.object({
6600
+ file_path: z14.string().describe(
5484
6601
  "Text file path. Sandbox-bounded unless full-access mode is active."
5485
6602
  ),
5486
- offset: z10.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
5487
- limit: z10.number().int().positive().optional().describe("Max preview lines to read. Default 2000.")
6603
+ offset: z14.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
6604
+ limit: z14.number().int().positive().optional().describe("Max preview lines to read. Default 2000.")
5488
6605
  }),
5489
6606
  execute: async (input, ctx) => {
5490
6607
  let resolved;
@@ -5583,24 +6700,24 @@ For full long-line content, use read_line({"file_path":${JSON.stringify(input.fi
5583
6700
 
5584
6701
  // src/tools/read-line.ts
5585
6702
  import { promises as fs11 } from "fs";
5586
- import { defineTool as defineTool8 } from "@codelia/core";
5587
- import { z as z11 } from "zod";
6703
+ import { defineTool as defineTool9 } from "@codelia/core";
6704
+ import { z as z15 } from "zod";
5588
6705
  var DEFAULT_CHAR_LIMIT = 1e4;
5589
6706
  var MAX_CHAR_LIMIT = 1e5;
5590
6707
  var GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, {
5591
6708
  granularity: "grapheme"
5592
6709
  });
5593
6710
  var splitGraphemes = (value) => Array.from(GRAPHEME_SEGMENTER.segment(value), ({ segment }) => segment);
5594
- var createReadLineTool = (sandboxKey) => defineTool8({
6711
+ var createReadLineTool = (sandboxKey) => defineTool9({
5595
6712
  name: "read_line",
5596
6713
  description: "Read one physical line as paged grapheme-based text by 1-based line number and 0-based char offset, with the full UTF-8 content SHA-256 metadata for edit.expected_hash.",
5597
- input: z11.object({
5598
- file_path: z11.string().describe(
6714
+ input: z15.object({
6715
+ file_path: z15.string().describe(
5599
6716
  "Text file path. Sandbox-bounded unless full-access mode is active."
5600
6717
  ),
5601
- line_number: z11.number().int().positive().describe("1-based line number to read."),
5602
- char_offset: z11.number().int().nonnegative().optional().describe("0-based grapheme offset in the target line. Default 0."),
5603
- char_limit: z11.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe(
6718
+ line_number: z15.number().int().positive().describe("1-based line number to read."),
6719
+ char_offset: z15.number().int().nonnegative().optional().describe("0-based grapheme offset in the target line. Default 0."),
6720
+ char_limit: z15.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe(
5604
6721
  `Max graphemes to return. Default 10000, Max ${MAX_CHAR_LIMIT}.`
5605
6722
  )
5606
6723
  }),
@@ -5661,9 +6778,9 @@ read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${input.
5661
6778
 
5662
6779
  // src/tools/shell.ts
5663
6780
  import crypto6 from "crypto";
5664
- import { defineTool as defineTool9 } from "@codelia/core";
6781
+ import { defineTool as defineTool10 } from "@codelia/core";
5665
6782
  import { ToolOutputCacheStoreImpl } from "@codelia/storage";
5666
- import { z as z12 } from "zod";
6783
+ import { z as z16 } from "zod";
5667
6784
 
5668
6785
  // src/tools/session-context.ts
5669
6786
  var createToolSessionContextKey = (getSessionId) => ({
@@ -5716,37 +6833,37 @@ var SHELL_LIST_DEFAULT_LIMIT = 20;
5716
6833
  var SHELL_LIST_MAX_LIMIT = 100;
5717
6834
  var SHELL_LOGS_MAX_TAIL_LINES = 500;
5718
6835
  var SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT = false;
5719
- var shellStdinModeSchema = z12.enum(["closed", "pipe"]);
5720
- var shellStateSchema = z12.enum([
6836
+ var shellStdinModeSchema = z16.enum(["closed", "pipe"]);
6837
+ var shellStateSchema = z16.enum([
5721
6838
  "queued",
5722
6839
  "running",
5723
6840
  "completed",
5724
6841
  "failed",
5725
6842
  "cancelled"
5726
6843
  ]);
5727
- var shellRunSchema = z12.object({
5728
- command: z12.string().describe(
6844
+ var shellRunSchema = z16.object({
6845
+ command: z16.string().describe(
5729
6846
  "Shell command to execute as a runtime-managed child process in the current workspace."
5730
6847
  ),
5731
- label: z12.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
6848
+ label: z16.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
5732
6849
  `Short label used to build the returned task key. Max ${SHELL_LABEL_MAX_CHARS} chars.`
5733
6850
  ),
5734
- timeout: z12.number().int().positive().optional().describe(
6851
+ timeout: z16.number().int().positive().optional().describe(
5735
6852
  `Execution timeout in seconds. Foreground: default ${DEFAULT_TIMEOUT_SECONDS}, max ${MAX_TIMEOUT_SECONDS}. Detached: max ${MAX_EXECUTION_TIMEOUT_SECONDS}; omit for no execution timer.`
5736
6853
  ),
5737
- detached_wait: z12.boolean().optional().describe(
6854
+ detached_wait: z16.boolean().optional().describe(
5738
6855
  "Return a task key immediately instead of waiting. The runtime owns the child until completion, cancellation, or runtime exit; use follow-up shell tools. Default: false."
5739
6856
  ),
5740
6857
  stdin_mode: shellStdinModeSchema.optional().describe(
5741
6858
  "Child stdin: closed (default) or pipe. pipe requires detached_wait=true and shell_stdin_write."
5742
6859
  ),
5743
- include_stderr_on_success: z12.boolean().optional().describe(
6860
+ include_stderr_on_success: z16.boolean().optional().describe(
5744
6861
  `Include stderr on success. Default: ${String(SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT)}.`
5745
6862
  )
5746
6863
  }).superRefine((input, ctx) => {
5747
6864
  if (input.stdin_mode === "pipe" && input.detached_wait !== true) {
5748
6865
  ctx.addIssue({
5749
- code: z12.ZodIssueCode.custom,
6866
+ code: z16.ZodIssueCode.custom,
5750
6867
  path: ["stdin_mode"],
5751
6868
  message: "stdin_mode=pipe requires detached_wait=true."
5752
6869
  });
@@ -5757,7 +6874,7 @@ var shellRunSchema = z12.object({
5757
6874
  if (input.detached_wait ?? false) {
5758
6875
  if (input.timeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
5759
6876
  ctx.addIssue({
5760
- code: z12.ZodIssueCode.custom,
6877
+ code: z16.ZodIssueCode.custom,
5761
6878
  path: ["timeout"],
5762
6879
  message: `Detached-wait timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
5763
6880
  });
@@ -5766,61 +6883,61 @@ var shellRunSchema = z12.object({
5766
6883
  }
5767
6884
  if (input.timeout > MAX_TIMEOUT_SECONDS) {
5768
6885
  ctx.addIssue({
5769
- code: z12.ZodIssueCode.custom,
6886
+ code: z16.ZodIssueCode.custom,
5770
6887
  path: ["timeout"],
5771
6888
  message: `Foreground timeout must be ${MAX_TIMEOUT_SECONDS} seconds or less.`
5772
6889
  });
5773
6890
  }
5774
6891
  });
5775
- var shellTaskKeySchema = z12.object({
5776
- key: z12.string().describe("Canonical shell task key returned by shell or shell_list.")
6892
+ var shellTaskKeySchema = z16.object({
6893
+ key: z16.string().describe("Canonical shell task key returned by shell or shell_list.")
5777
6894
  });
5778
6895
  var shellStdinWriteSchema = shellTaskKeySchema.extend({
5779
- text: z12.string().describe("UTF-8 text to write to the task stdin pipe."),
5780
- append_newline: z12.boolean().optional().describe("Append one newline before writing. Default: false."),
5781
- close: z12.boolean().optional().describe("Close stdin after this write completes. Default: false.")
6896
+ text: z16.string().describe("UTF-8 text to write to the task stdin pipe."),
6897
+ append_newline: z16.boolean().optional().describe("Append one newline before writing. Default: false."),
6898
+ close: z16.boolean().optional().describe("Close stdin after this write completes. Default: false.")
5782
6899
  }).superRefine((input, ctx) => {
5783
6900
  const close = input.close ?? false;
5784
6901
  const text = `${input.text}${input.append_newline ? "\n" : ""}`;
5785
6902
  if (text.length === 0 && !close) {
5786
6903
  ctx.addIssue({
5787
- code: z12.ZodIssueCode.custom,
6904
+ code: z16.ZodIssueCode.custom,
5788
6905
  path: ["text"],
5789
6906
  message: "text must be non-empty unless close=true."
5790
6907
  });
5791
6908
  }
5792
6909
  if (utf8ByteLength3(text) > MAX_STDIN_WRITE_BYTES) {
5793
6910
  ctx.addIssue({
5794
- code: z12.ZodIssueCode.custom,
6911
+ code: z16.ZodIssueCode.custom,
5795
6912
  path: ["text"],
5796
6913
  message: `stdin writes are limited to ${MAX_STDIN_WRITE_BYTES} UTF-8 bytes after append_newline.`
5797
6914
  });
5798
6915
  }
5799
6916
  });
5800
6917
  var shellSuccessStderrSchema = {
5801
- include_stderr_on_success: z12.boolean().optional().describe(
6918
+ include_stderr_on_success: z16.boolean().optional().describe(
5802
6919
  `Include stderr on success. Default: ${String(SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT)}.`
5803
6920
  )
5804
6921
  };
5805
6922
  var shellWaitSchema = shellTaskKeySchema.extend({
5806
- wait_timeout: z12.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
6923
+ wait_timeout: z16.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
5807
6924
  `Attached wait window in seconds. Default: ${DEFAULT_TIMEOUT_SECONDS}. Max ${MAX_TIMEOUT_SECONDS}. If the task is still running when the window expires, the tool returns compact status JSON instead of hanging.`
5808
6925
  ),
5809
6926
  ...shellSuccessStderrSchema
5810
6927
  });
5811
6928
  var shellResultSchema = shellTaskKeySchema.extend(shellSuccessStderrSchema);
5812
- var shellStreamSchema = z12.enum(["stdout", "stderr"]);
5813
- var shellListSchema = z12.object({
5814
- limit: z12.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
6929
+ var shellStreamSchema = z16.enum(["stdout", "stderr"]);
6930
+ var shellListSchema = z16.object({
6931
+ limit: z16.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
5815
6932
  `Max tasks to return. Default: ${SHELL_LIST_DEFAULT_LIMIT}. Max ${SHELL_LIST_MAX_LIMIT}.`
5816
6933
  ),
5817
6934
  state: shellStateSchema.optional().describe("Exact state filter. Default: active tasks only."),
5818
- include_terminal: z12.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
6935
+ include_terminal: z16.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
5819
6936
  });
5820
- var shellLogsSchema = z12.object({
5821
- key: z12.string().describe("Canonical shell task key returned by shell or shell_list."),
6937
+ var shellLogsSchema = z16.object({
6938
+ key: z16.string().describe("Canonical shell task key returned by shell or shell_list."),
5822
6939
  stream: shellStreamSchema.optional().describe("Stream to read. Default: stdout."),
5823
- tail_lines: z12.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
6940
+ tail_lines: z16.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
5824
6941
  `Return only the last N lines. Max ${SHELL_LOGS_MAX_TAIL_LINES}.`
5825
6942
  )
5826
6943
  });
@@ -5857,8 +6974,8 @@ var normalizeShellTaskKey = (value) => {
5857
6974
  var getShellTaskKey = (task) => task.key ?? `${toShellKeyBase(task.label)}-${compactTaskId(task.task_id).slice(0, 8)}`;
5858
6975
  var toShellKeyBase = (label) => {
5859
6976
  const source = label?.trim() ?? "";
5860
- const slug = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
5861
- return slug || "shell";
6977
+ const slug2 = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
6978
+ return slug2 || "shell";
5862
6979
  };
5863
6980
  var compactTaskId = (taskId) => {
5864
6981
  const compact = taskId.toLowerCase().replaceAll(/[^a-z0-9]+/g, "");
@@ -6171,7 +7288,7 @@ var waitForManagedTaskWindow = async (tasks, taskId, options) => {
6171
7288
  };
6172
7289
  var createShellTool = (sandboxKey, options = {}) => {
6173
7290
  const shared = getSharedDeps(options);
6174
- return defineTool9({
7291
+ return defineTool10({
6175
7292
  name: "shell",
6176
7293
  description: "Run a shell command as a managed child process in the sandbox. It waits with stdin closed by default; use detached_wait for a task key and stdin_mode=pipe only when follow-up shell_stdin_write calls are needed.",
6177
7294
  input: shellRunSchema,
@@ -6239,7 +7356,7 @@ var createShellTool = (sandboxKey, options = {}) => {
6239
7356
  };
6240
7357
  var createShellStdinWriteTool = (options = {}) => {
6241
7358
  const shared = getSharedDeps(options);
6242
- return defineTool9({
7359
+ return defineTool10({
6243
7360
  name: "shell_stdin_write",
6244
7361
  description: "Write up to 64 KiB of UTF-8 text to a live shell task started with detached_wait=true and stdin_mode=pipe; use shell_logs or shell_wait afterward.",
6245
7362
  input: shellStdinWriteSchema,
@@ -6267,7 +7384,7 @@ var createShellStdinWriteTool = (options = {}) => {
6267
7384
  };
6268
7385
  var createShellListTool = (options = {}) => {
6269
7386
  const shared = getSharedDeps(options);
6270
- return defineTool9({
7387
+ return defineTool10({
6271
7388
  name: "shell_list",
6272
7389
  description: "List retained shell tasks with compact summaries, defaulting to active tasks.",
6273
7390
  input: shellListSchema,
@@ -6298,7 +7415,7 @@ var createShellListTool = (options = {}) => {
6298
7415
  };
6299
7416
  var createShellStatusTool = (options = {}) => {
6300
7417
  const shared = getSharedDeps(options);
6301
- return defineTool9({
7418
+ return defineTool10({
6302
7419
  name: "shell_status",
6303
7420
  description: "Get the current state for a shell task as compact JSON.",
6304
7421
  input: shellTaskKeySchema,
@@ -6314,7 +7431,7 @@ var createShellStatusTool = (options = {}) => {
6314
7431
  };
6315
7432
  var createShellLogsTool = (options = {}) => {
6316
7433
  const shared = getSharedDeps(options);
6317
- return defineTool9({
7434
+ return defineTool10({
6318
7435
  name: "shell_logs",
6319
7436
  description: "Read recent stdout or stderr for a running or finished shell task. Use this when a compact shell terminal result omitted a stream, such as `stderr` on success.",
6320
7437
  input: shellLogsSchema,
@@ -6336,7 +7453,7 @@ var createShellLogsTool = (options = {}) => {
6336
7453
  };
6337
7454
  var createShellWaitTool = (options = {}) => {
6338
7455
  const shared = getSharedDeps(options);
6339
- return defineTool9({
7456
+ return defineTool10({
6340
7457
  name: "shell_wait",
6341
7458
  description: "Wait within a bounded window for a shell task, returning compact running status or its terminal stdout/stderr result.",
6342
7459
  input: shellWaitSchema,
@@ -6371,7 +7488,7 @@ var createShellWaitTool = (options = {}) => {
6371
7488
  };
6372
7489
  var createShellResultTool = (options = {}) => {
6373
7490
  const shared = getSharedDeps(options);
6374
- return defineTool9({
7491
+ return defineTool10({
6375
7492
  name: "shell_result",
6376
7493
  description: "Read a shell task's retained terminal stdout/stderr result, or its current status if still running.",
6377
7494
  input: shellResultSchema,
@@ -6390,7 +7507,7 @@ var createShellResultTool = (options = {}) => {
6390
7507
  };
6391
7508
  var createShellCancelTool = (options = {}) => {
6392
7509
  const shared = getSharedDeps(options);
6393
- return defineTool9({
7510
+ return defineTool10({
6394
7511
  name: "shell_cancel",
6395
7512
  description: "Cancel a running shell task and return compact JSON for the cancelled state.",
6396
7513
  input: shellTaskKeySchema,
@@ -6409,16 +7526,16 @@ var createShellCancelTool = (options = {}) => {
6409
7526
  };
6410
7527
 
6411
7528
  // src/tools/skill-load.ts
6412
- import { defineTool as defineTool10 } from "@codelia/core";
6413
- import { z as z13 } from "zod";
6414
- var SkillLoadInputSchema = z13.object({
6415
- name: z13.string().min(1).optional().describe("Exact skill name to load."),
6416
- path: z13.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
7529
+ import { defineTool as defineTool11 } from "@codelia/core";
7530
+ import { z as z17 } from "zod";
7531
+ var SkillLoadInputSchema = z17.object({
7532
+ name: z17.string().min(1).optional().describe("Exact skill name to load."),
7533
+ path: z17.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
6417
7534
  }).refine((value) => !!value.name || !!value.path, {
6418
7535
  message: "name or path is required",
6419
7536
  path: ["name"]
6420
7537
  });
6421
- var createSkillLoadTool = (skillsResolverKey) => defineTool10({
7538
+ var createSkillLoadTool = (skillsResolverKey) => defineTool11({
6422
7539
  name: "skill_load",
6423
7540
  description: "Load full SKILL.md content by exact name or path.",
6424
7541
  input: SkillLoadInputSchema,
@@ -6464,17 +7581,17 @@ var createSkillLoadTool = (skillsResolverKey) => defineTool10({
6464
7581
  });
6465
7582
 
6466
7583
  // src/tools/skill-search.ts
6467
- import { defineTool as defineTool11 } from "@codelia/core";
6468
- import { z as z14 } from "zod";
6469
- var createSkillSearchTool = (skillsResolverKey) => defineTool11({
7584
+ import { defineTool as defineTool12 } from "@codelia/core";
7585
+ import { z as z18 } from "zod";
7586
+ var createSkillSearchTool = (skillsResolverKey) => defineTool12({
6470
7587
  name: "skill_search",
6471
7588
  description: "Search installed local skills by name, description, or path.",
6472
- input: z14.object({
6473
- query: z14.string().min(1).describe("Search query text."),
6474
- limit: z14.number().int().positive().optional().describe(
7589
+ input: z18.object({
7590
+ query: z18.string().min(1).describe("Search query text."),
7591
+ limit: z18.number().int().positive().optional().describe(
6475
7592
  "Optional max result count. Higher values may be clamped by config."
6476
7593
  ),
6477
- scope: z14.enum(["repo", "user"]).optional().describe("Optional scope filter.")
7594
+ scope: z18.enum(["repo", "user"]).optional().describe("Optional scope filter.")
6478
7595
  }),
6479
7596
  execute: async (input, ctx) => {
6480
7597
  try {
@@ -6497,8 +7614,8 @@ var createSkillSearchTool = (skillsResolverKey) => defineTool11({
6497
7614
  });
6498
7615
 
6499
7616
  // src/tools/todo-mutate.ts
6500
- import { defineTool as defineTool12 } from "@codelia/core";
6501
- import { z as z15 } from "zod";
7617
+ import { defineTool as defineTool13 } from "@codelia/core";
7618
+ import { z as z19 } from "zod";
6502
7619
 
6503
7620
  // src/tools/todo-store.ts
6504
7621
  var TODO_SESSION_META_KEY = "codelia_todos";
@@ -6608,39 +7725,39 @@ var pickNextTodo = (todos) => {
6608
7725
  var todoStore = /* @__PURE__ */ new Map();
6609
7726
 
6610
7727
  // src/tools/todo-mutate.ts
6611
- var todoStatusSchema = z15.enum(["pending", "in_progress", "completed"]);
6612
- var todoPrioritySchema = z15.number().int().min(1).max(5);
6613
- var todoItemSchema = z15.object({
6614
- id: z15.string().min(1).optional().describe(
7728
+ var todoStatusSchema = z19.enum(["pending", "in_progress", "completed"]);
7729
+ var todoPrioritySchema = z19.number().int().min(1).max(5);
7730
+ var todoItemSchema = z19.object({
7731
+ id: z19.string().min(1).optional().describe(
6615
7732
  "Stable ID. Omit to generate one; preserve the existing ID when replacing a known item."
6616
7733
  ),
6617
- content: z15.string().min(1).describe("Todo item text."),
7734
+ content: z19.string().min(1).describe("Todo item text."),
6618
7735
  status: todoStatusSchema.describe("Todo status."),
6619
7736
  priority: todoPrioritySchema.optional().describe("Priority 1(high)-5(low). Default is 3."),
6620
- notes: z15.string().optional().describe("Implementation notes."),
6621
- activeForm: z15.string().optional().describe("In-progress phrasing for UI display.")
7737
+ notes: z19.string().optional().describe("Implementation notes."),
7738
+ activeForm: z19.string().optional().describe("In-progress phrasing for UI display.")
6622
7739
  });
6623
- var todoPatchItemSchema = z15.object({
6624
- id: z15.string().min(1).describe("Target todo ID."),
6625
- remove: z15.boolean().optional().describe("Set true to remove the todo item."),
6626
- content: z15.string().min(1).optional().describe("New todo text; omit to keep the current value."),
7740
+ var todoPatchItemSchema = z19.object({
7741
+ id: z19.string().min(1).describe("Target todo ID."),
7742
+ remove: z19.boolean().optional().describe("Set true to remove the todo item."),
7743
+ content: z19.string().min(1).optional().describe("New todo text; omit to keep the current value."),
6627
7744
  status: todoStatusSchema.optional().describe("New status; omit to keep the current value."),
6628
7745
  priority: todoPrioritySchema.optional().describe("New priority; omit to keep the current value."),
6629
- notes: z15.string().optional().describe("New notes; omit to keep the current value, empty clears."),
6630
- activeForm: z15.string().optional().describe(
7746
+ notes: z19.string().optional().describe("New notes; omit to keep the current value, empty clears."),
7747
+ activeForm: z19.string().optional().describe(
6631
7748
  "New in-progress phrasing; omit to keep the current value, empty clears."
6632
7749
  )
6633
7750
  });
6634
- var todoNewInputSchema = z15.object({
6635
- todos: z15.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
7751
+ var todoNewInputSchema = z19.object({
7752
+ todos: z19.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
6636
7753
  }).strict();
6637
- var todoAppendInputSchema = z15.object({
6638
- todos: z15.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
7754
+ var todoAppendInputSchema = z19.object({
7755
+ todos: z19.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
6639
7756
  }).strict();
6640
- var todoPatchInputSchema = z15.object({
6641
- updates: z15.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
7757
+ var todoPatchInputSchema = z19.object({
7758
+ updates: z19.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
6642
7759
  }).strict();
6643
- var todoClearInputSchema = z15.object({}).strict();
7760
+ var todoClearInputSchema = z19.object({}).strict();
6644
7761
  var statusSymbol = {
6645
7762
  pending: "[ ]",
6646
7763
  in_progress: "[>]",
@@ -6735,7 +7852,7 @@ var applyTodoMutation = (sessionId, input, outputMode) => {
6735
7852
  }
6736
7853
  return formatSuccess(outputMode, nextTodos);
6737
7854
  };
6738
- var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => defineTool12({
7855
+ var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => defineTool13({
6739
7856
  name,
6740
7857
  description,
6741
7858
  input,
@@ -6790,17 +7907,17 @@ var createTodoClearTool = (sandboxKey, sessionContextKey) => createTodoMutationT
6790
7907
  );
6791
7908
 
6792
7909
  // src/tools/todo-read.ts
6793
- import { defineTool as defineTool13 } from "@codelia/core";
6794
- import { z as z16 } from "zod";
7910
+ import { defineTool as defineTool14 } from "@codelia/core";
7911
+ import { z as z20 } from "zod";
6795
7912
  var statusSymbol2 = {
6796
7913
  pending: "[ ]",
6797
7914
  in_progress: "[>]",
6798
7915
  completed: "[x]"
6799
7916
  };
6800
- var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool13({
7917
+ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool14({
6801
7918
  name: "todo_read",
6802
7919
  description: "Read the in-session todo plan with execution order and next step.",
6803
- input: z16.object({}),
7920
+ input: z20.object({}),
6804
7921
  execute: async (_input, ctx) => {
6805
7922
  const sandbox = await getSandboxContext(ctx, sandboxKey);
6806
7923
  const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
@@ -6836,15 +7953,15 @@ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool13({
6836
7953
  });
6837
7954
 
6838
7955
  // src/tools/tool-output-cache.ts
6839
- import { defineTool as defineTool14 } from "@codelia/core";
6840
- import { z as z17 } from "zod";
6841
- var createToolOutputCacheTool = (store) => defineTool14({
7956
+ import { defineTool as defineTool15 } from "@codelia/core";
7957
+ import { z as z21 } from "zod";
7958
+ var createToolOutputCacheTool = (store) => defineTool15({
6842
7959
  name: "tool_output_cache",
6843
7960
  description: "Read cached tool output by ref_id.",
6844
- input: z17.object({
6845
- ref_id: z17.string().describe("Tool output reference ID."),
6846
- offset: z17.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
6847
- limit: z17.number().int().positive().optional().describe("Optional max number of lines to return.")
7961
+ input: z21.object({
7962
+ ref_id: z21.string().describe("Tool output reference ID."),
7963
+ offset: z21.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
7964
+ limit: z21.number().int().positive().optional().describe("Optional max number of lines to return.")
6848
7965
  }),
6849
7966
  execute: async (input) => {
6850
7967
  if (!store.read) {
@@ -6860,14 +7977,14 @@ var createToolOutputCacheTool = (store) => defineTool14({
6860
7977
  }
6861
7978
  }
6862
7979
  });
6863
- var createToolOutputCacheLineTool = (store) => defineTool14({
7980
+ var createToolOutputCacheLineTool = (store) => defineTool15({
6864
7981
  name: "tool_output_cache_line",
6865
7982
  description: "Read a single cached output line segment by line number and char offset.",
6866
- input: z17.object({
6867
- ref_id: z17.string().describe("Tool output reference ID."),
6868
- line_number: z17.number().int().positive().describe("1-based line number to read."),
6869
- char_offset: z17.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
6870
- char_limit: z17.number().int().positive().optional().describe("Max chars to return.")
7983
+ input: z21.object({
7984
+ ref_id: z21.string().describe("Tool output reference ID."),
7985
+ line_number: z21.number().int().positive().describe("1-based line number to read."),
7986
+ char_offset: z21.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7987
+ char_limit: z21.number().int().positive().optional().describe("Max chars to return.")
6871
7988
  }),
6872
7989
  execute: async (input) => {
6873
7990
  if (!store.readLine) {
@@ -6884,16 +8001,16 @@ var createToolOutputCacheLineTool = (store) => defineTool14({
6884
8001
  }
6885
8002
  }
6886
8003
  });
6887
- var createToolOutputCacheGrepTool = (store) => defineTool14({
8004
+ var createToolOutputCacheGrepTool = (store) => defineTool15({
6888
8005
  name: "tool_output_cache_grep",
6889
8006
  description: "Search cached tool output by ref_id.",
6890
- input: z17.object({
6891
- ref_id: z17.string().describe("Tool output reference ID."),
6892
- pattern: z17.string().describe("Text or regex pattern to search for."),
6893
- regex: z17.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
6894
- before: z17.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
6895
- after: z17.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
6896
- max_matches: z17.number().int().positive().optional().describe("Maximum number of matches to return.")
8007
+ input: z21.object({
8008
+ ref_id: z21.string().describe("Tool output reference ID."),
8009
+ pattern: z21.string().describe("Text or regex pattern to search for."),
8010
+ regex: z21.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
8011
+ before: z21.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
8012
+ after: z21.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
8013
+ max_matches: z21.number().int().positive().optional().describe("Maximum number of matches to return.")
6897
8014
  }),
6898
8015
  execute: async (input) => {
6899
8016
  if (!store.grep) {
@@ -6915,9 +8032,9 @@ var createToolOutputCacheGrepTool = (store) => defineTool14({
6915
8032
 
6916
8033
  // src/tools/view-image.ts
6917
8034
  import { promises as fs12 } from "fs";
6918
- import path10 from "path";
6919
- import { defineTool as defineTool15 } from "@codelia/core";
6920
- import { z as z18 } from "zod";
8035
+ import path13 from "path";
8036
+ import { defineTool as defineTool16 } from "@codelia/core";
8037
+ import { z as z22 } from "zod";
6921
8038
  var DEFAULT_MAX_BYTES2 = 5 * 1024 * 1024;
6922
8039
  var MAX_MAX_BYTES = 10 * 1024 * 1024;
6923
8040
  var MIME_BY_EXTENSION = {
@@ -6928,21 +8045,51 @@ var MIME_BY_EXTENSION = {
6928
8045
  ".gif": "image/gif"
6929
8046
  };
6930
8047
  var resolveImageMime = (filePath) => {
6931
- return MIME_BY_EXTENSION[path10.extname(filePath).toLowerCase()] ?? null;
8048
+ return MIME_BY_EXTENSION[path13.extname(filePath).toLowerCase()] ?? null;
6932
8049
  };
6933
- var createViewImageTool = (sandboxKey) => defineTool15({
8050
+ var createViewImageTool = (sandboxKey) => defineTool16({
6934
8051
  name: "view_image",
6935
- description: "Load one local png/jpeg/webp/gif image (default max 5MB) for multimodal inspection.",
6936
- input: z18.object({
6937
- file_path: z18.string().describe(
6938
- "Single local png/jpeg/webp/gif image path. Sandbox-bounded unless full-access mode is active."
8052
+ description: "Inspect one local image or direct HTTP(S) image URL; URLs are passed to the model provider without local download (provider URL support required; Moonshot unsupported).",
8053
+ input: z22.object({
8054
+ file_path: z22.string().min(1).optional().describe(
8055
+ "Local png/jpeg/webp/gif path; provide exactly one of file_path or url. Sandbox-bounded unless full-access mode is active."
6939
8056
  ),
6940
- detail: z18.enum(["auto", "low", "high"]).optional().describe(
8057
+ url: z22.url({ protocol: /^https?$/ }).refine((value) => {
8058
+ if (!URL.canParse(value)) return false;
8059
+ const parsed = new URL(value);
8060
+ return !parsed.username && !parsed.password;
8061
+ }, "Image URL must not contain credentials").optional().describe(
8062
+ "Publicly accessible direct image URL, not a web page; provide exactly one of url or file_path. Provider fetches it; runtime does not verify availability, format, or size. Do not include secrets."
8063
+ ),
8064
+ detail: z22.enum(["auto", "low", "high"]).optional().describe(
6941
8065
  "Model image-detail hint (`auto`/`low`/`high`). Default auto."
6942
8066
  ),
6943
- max_bytes: z18.number().int().positive().max(MAX_MAX_BYTES).optional().describe("Max file size in bytes. Default 5242880, Max 10485760.")
6944
- }),
8067
+ max_bytes: z22.number().int().positive().max(MAX_MAX_BYTES).optional().describe(
8068
+ "Local files only: max bytes. Default 5242880, Max 10485760; omit with url."
8069
+ )
8070
+ }).refine(
8071
+ (input) => input.file_path !== void 0 !== (input.url !== void 0),
8072
+ "Provide exactly one of file_path or url"
8073
+ ).refine(
8074
+ (input) => input.url === void 0 || input.max_bytes === void 0,
8075
+ "max_bytes is only supported for local files"
8076
+ ),
6945
8077
  execute: async (input, ctx) => {
8078
+ if (input.url !== void 0) {
8079
+ return [
8080
+ {
8081
+ type: "text",
8082
+ text: "Image URL supplied for provider inspection (not fetched locally).\n"
8083
+ },
8084
+ {
8085
+ type: "image_url",
8086
+ image_url: { url: input.url, detail: input.detail ?? "auto" }
8087
+ }
8088
+ ];
8089
+ }
8090
+ if (input.file_path === void 0) {
8091
+ throw new Error("Provide exactly one of file_path or url");
8092
+ }
6946
8093
  let resolved;
6947
8094
  try {
6948
8095
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -6990,8 +8137,8 @@ var createViewImageTool = (sandboxKey) => defineTool15({
6990
8137
  });
6991
8138
 
6992
8139
  // src/tools/webfetch.ts
6993
- import { defineTool as defineTool16 } from "@codelia/core";
6994
- import { z as z19 } from "zod";
8140
+ import { defineTool as defineTool17 } from "@codelia/core";
8141
+ import { z as z23 } from "zod";
6995
8142
  var DEFAULT_TIMEOUT_MS2 = 1e4;
6996
8143
  var MAX_TIMEOUT_MS = 3e4;
6997
8144
  var DEFAULT_MAX_BYTES3 = 2e5;
@@ -7244,16 +8391,16 @@ var classifyFetchError = (error, timeoutMs) => {
7244
8391
  })
7245
8392
  };
7246
8393
  };
7247
- var createWebfetchTool = () => defineTool16({
8394
+ var createWebfetchTool = () => defineTool17({
7248
8395
  name: "webfetch",
7249
8396
  description: "Fetch an HTTP(S) URL and return bounded normalized markdown/text/html for textual content, not binary downloads.",
7250
- input: z19.object({
7251
- url: z19.string().min(1).describe("HTTP(S) URL to fetch."),
7252
- output_format: z19.enum(["markdown", "text", "html"]).optional().describe("Normalized output format. Default markdown."),
7253
- timeout_ms: z19.number().int().positive().max(MAX_TIMEOUT_MS).optional().describe(
8397
+ input: z23.object({
8398
+ url: z23.string().min(1).describe("HTTP(S) URL to fetch."),
8399
+ output_format: z23.enum(["markdown", "text", "html"]).optional().describe("Normalized output format. Default markdown."),
8400
+ timeout_ms: z23.number().int().positive().max(MAX_TIMEOUT_MS).optional().describe(
7254
8401
  `Fetch timeout in ms. Default ${DEFAULT_TIMEOUT_MS2}, Max ${MAX_TIMEOUT_MS}.`
7255
8402
  ),
7256
- max_bytes: z19.number().int().positive().max(MAX_MAX_BYTES2).optional().describe(
8403
+ max_bytes: z23.number().int().positive().max(MAX_MAX_BYTES2).optional().describe(
7257
8404
  `Max response bytes to keep. Default ${DEFAULT_MAX_BYTES3}, Max ${MAX_MAX_BYTES2}.`
7258
8405
  )
7259
8406
  }),
@@ -7325,17 +8472,17 @@ var createWebfetchTool = () => defineTool16({
7325
8472
 
7326
8473
  // src/tools/write.ts
7327
8474
  import { promises as fs13 } from "fs";
7328
- import path11 from "path";
7329
- import { defineTool as defineTool17 } from "@codelia/core";
7330
- import { z as z20 } from "zod";
7331
- var createWriteTool = (sandboxKey, outputCacheStore) => defineTool17({
8475
+ import path14 from "path";
8476
+ import { defineTool as defineTool18 } from "@codelia/core";
8477
+ import { z as z24 } from "zod";
8478
+ var createWriteTool = (sandboxKey, outputCacheStore) => defineTool18({
7332
8479
  name: "write",
7333
8480
  description: "Write full UTF-8 text to a file, replacing any existing contents and creating parent directories if needed; supports the same full-content hash guard as edit.",
7334
- input: z20.object({
7335
- file_path: z20.string().describe(
8481
+ input: z24.object({
8482
+ file_path: z24.string().describe(
7336
8483
  "File path. Sandbox-bounded unless full-access mode is active."
7337
8484
  ),
7338
- content: z20.string().describe("Full replacement UTF-8 text content to write."),
8485
+ content: z24.string().describe("Full replacement UTF-8 text content to write."),
7339
8486
  expected_hash: expectedContentHashSchema
7340
8487
  }),
7341
8488
  execute: async (input, ctx) => {
@@ -7363,7 +8510,7 @@ var createWriteTool = (sandboxKey, outputCacheStore) => defineTool17({
7363
8510
  content: before,
7364
8511
  filePath: input.file_path
7365
8512
  });
7366
- await fs13.mkdir(path11.dirname(resolved), { recursive: true });
8513
+ await fs13.mkdir(path14.dirname(resolved), { recursive: true });
7367
8514
  await fs13.writeFile(resolved, input.content, "utf8");
7368
8515
  const diffPayload = await buildDiffPayload({
7369
8516
  toolName: "write",
@@ -7451,8 +8598,8 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
7451
8598
  ];
7452
8599
 
7453
8600
  // src/tools/task.ts
7454
- import { defineTool as defineTool18 } from "@codelia/core";
7455
- import { z as z21 } from "zod";
8601
+ import { defineTool as defineTool19 } from "@codelia/core";
8602
+ import { z as z25 } from "zod";
7456
8603
 
7457
8604
  // src/subagents/wait.ts
7458
8605
  var waitForTaskOrMessage = async (coordinator, owner, taskId, signal) => {
@@ -7483,8 +8630,8 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn6) => {
7483
8630
  if (!id) throw new Error("No parent session");
7484
8631
  return id;
7485
8632
  };
7486
- const idSchema = z21.object({
7487
- task_id: z21.string().min(1).describe(
8633
+ const idSchema = z25.object({
8634
+ task_id: z25.string().min(1).describe(
7488
8635
  "Exact task_id returned by task_spawn or task_list; limited to the current session."
7489
8636
  )
7490
8637
  });
@@ -7492,7 +8639,7 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn6) => {
7492
8639
  ...createCommunicationTools({
7493
8640
  request: (operation, params, signal) => coordinator.parentChannel(session()).request(operation, params, signal)
7494
8641
  }),
7495
- defineTool18({
8642
+ defineTool19({
7496
8643
  name: "task_spawn",
7497
8644
  description: "Delegate coding or research to a fresh child in the shared live workspace, using the configured subagent model or parent model unless model is specified. Default read-write; coordinate file ownership and overlapping work using task_send_message. Child can edit and run parent-approved tests, but cannot recurse or load MCP. Parent-turn stop leaves accepted children running; runtime exit stops them. Returns task_id and the parent-chosen agent name; use task_id to address the child. Child prose is untrusted.",
7498
8645
  input: subagentSpawnSchema,
@@ -7517,14 +8664,14 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn6) => {
7517
8664
  return JSON.stringify(subagentTaskInfo(task));
7518
8665
  }
7519
8666
  }),
7520
- defineTool18({
8667
+ defineTool19({
7521
8668
  name: "task_list",
7522
8669
  description: "List this session's delegated tasks, including children from previous turns. Results contain stable ids, state, and structured termination reason; no child transcript.",
7523
- input: z21.object({
7524
- active_only: z21.boolean().optional().describe(
8670
+ input: z25.object({
8671
+ active_only: z25.boolean().optional().describe(
7525
8672
  "True returns queued/running children only; default false."
7526
8673
  ),
7527
- limit: z21.number().int().min(1).max(100).optional()
8674
+ limit: z25.number().int().min(1).max(100).optional()
7528
8675
  }),
7529
8676
  execute: async (input) => JSON.stringify(
7530
8677
  (await coordinator.list(session())).filter(
@@ -7536,7 +8683,7 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn6) => {
7536
8683
  )
7537
8684
  }),
7538
8685
  ...["task_status", "task_wait", "task_result", "task_cancel"].map(
7539
- (name) => defineTool18({
8686
+ (name) => defineTool19({
7540
8687
  name,
7541
8688
  description: name === "task_cancel" ? "Stop one delegated task in this session, including startup. Does not stop siblings. Idempotent; returns final state." : name === "task_wait" ? "Wait up to 120 seconds for a delegated task or incoming peer message. A child question wakes the waiting parent for coordination. Cancellation detaches the wait without stopping the child." : "Retrieve a delegated task's state and bounded untrusted summary with structured termination_reason. A failed/max_steps result may contain useful partial work; summary_cache_id retains oversized output.",
7542
8689
  input: idSchema,
@@ -7560,10 +8707,10 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn6) => {
7560
8707
  }
7561
8708
  })
7562
8709
  ),
7563
- defineTool18({
8710
+ defineTool19({
7564
8711
  name: "task_cancel_all",
7565
8712
  description: "Explicitly stop all delegated tasks belonging to the current session, including startup. Use only when the user or task requires stopping the entire group; parent-turn cancellation does not call this operation.",
7566
- input: z21.object({}),
8713
+ input: z25.object({}),
7567
8714
  execute: async () => JSON.stringify(
7568
8715
  (await coordinator.cancelAll(session())).map(subagentTaskInfo)
7569
8716
  )
@@ -7836,6 +8983,41 @@ ${JSON.stringify(subagentConfig)}
7836
8983
  const authResolver = await createEnvironmentAuthResolver(state, log);
7837
8984
  const provider = await authResolver.resolveProvider(modelConfig.provider);
7838
8985
  const providerAuth = await authResolver.resolveProviderAuth(provider);
8986
+ const imageStore = isTuiLocalEnvironment(environment) && workspaceRoot ? createLocalImageStore(workspaceRoot) : void 0;
8987
+ state.prepareRunImages = imageStore ? (input) => persistImageAttachments(input, imageStore) : void 0;
8988
+ let authorizeImage = () => ({
8989
+ decision: "deny",
8990
+ reason: "image permissions unavailable"
8991
+ });
8992
+ let imageTools = [];
8993
+ if (imageStore) {
8994
+ const imageConfig = await resolveImageGenerationConfig(workspaceRoot);
8995
+ let route = null;
8996
+ if (imageConfig.mode !== "off") {
8997
+ try {
8998
+ route = await resolveImageRoute(imageConfig, localImageAuth, {
8999
+ provider,
9000
+ auth: providerAuth,
9001
+ ...authResolver.getOpenAiAccessToken ? {
9002
+ getOpenAiAccessToken: authResolver.getOpenAiAccessToken.bind(authResolver)
9003
+ } : {}
9004
+ });
9005
+ } catch (error) {
9006
+ log(
9007
+ error instanceof ImageGenerationError ? error.message : "Image configuration/auth unavailable; chat remains enabled."
9008
+ );
9009
+ }
9010
+ }
9011
+ imageTools = createImageTools({
9012
+ store: imageStore,
9013
+ route,
9014
+ authorize: (...args) => authorizeImage(...args),
9015
+ ...ctx ? { readSource: createLocalImageSourceReader(ctx) } : {},
9016
+ ...workspaceRoot ? {
9017
+ exportImage: (outputPath, bytes) => exportImageBytes(workspaceRoot, outputPath, bytes)
9018
+ } : {}
9019
+ });
9020
+ }
7839
9021
  const searchConfig = environment.tools.search === "from-config" ? await resolveEnvironmentSearchConfig(state, workspaceRoot) : void 0;
7840
9022
  const {
7841
9023
  tools,
@@ -7847,6 +9029,7 @@ ${JSON.stringify(subagentConfig)}
7847
9029
  } = await composeRuntimeTools({
7848
9030
  provider,
7849
9031
  baseTools: baseLocalTools,
9032
+ imageTools,
7850
9033
  mcpTools,
7851
9034
  hostTools,
7852
9035
  ...searchConfig ? { searchConfig } : {}
@@ -7871,9 +9054,10 @@ ${JSON.stringify(subagentConfig)}
7871
9054
  state.currentModelProvider = provider;
7872
9055
  state.currentModelName = resolvedModelName;
7873
9056
  state.currentModelSource = modelConfig.source;
7874
- const modelRegistry = environment.persistence.mode === "runtime" ? await buildModelRegistry(llm, {
7875
- strict: provider !== "openrouter"
7876
- }) : DEFAULT_MODEL_REGISTRY2;
9057
+ const modelRegistry = environment.persistence.mode === "runtime" || getResponsesProvider(modelConfig, provider) ? await buildModelRegistry(llm, {
9058
+ strict: provider !== "openrouter",
9059
+ providers: modelConfig.providers
9060
+ }) : buildConfiguredModelRegistry(modelConfig.providers);
7877
9061
  const totalBudgetTrimEnabled = envTruthy(
7878
9062
  process.env.CODELIA_TOOL_OUTPUT_TOTAL_TRIM
7879
9063
  );
@@ -7931,6 +9115,7 @@ ${request.raw_args}`,
7931
9115
  subagent: subagentConfig,
7932
9116
  workspace_root: workspaceRoot,
7933
9117
  model: {
9118
+ providers: modelConfig.providers,
7934
9119
  provider,
7935
9120
  name: resolvedModelName,
7936
9121
  reasoning: modelConfig.reasoning,
@@ -7960,7 +9145,7 @@ ${request.raw_args}`,
7960
9145
  toolContext
7961
9146
  );
7962
9147
  if (decision.decision !== "allow")
7963
- throw new ToolPermissionDenied(decision);
9148
+ throw new ToolPermissionDenied2(decision);
7964
9149
  if (state.sessionId !== sessionId || runId && (state.activeRunId !== runId || state.cancelRequested))
7965
9150
  throw new Error("Parent turn stopped before admission");
7966
9151
  return coordinator.spawn(params, {
@@ -7970,17 +9155,23 @@ ${request.raw_args}`,
7970
9155
  });
7971
9156
  };
7972
9157
  }
9158
+ authorizeImage = canExecuteTool;
9159
+ const endpointModel = getResponsesProvider(modelConfig, provider)?.models[resolvedModelName];
9160
+ const modelToolsEnabled = !endpointModel || endpointModel.supports_tools === true;
7973
9161
  const agent = new Agent({
7974
9162
  llm,
7975
- tools,
7976
- hostedTools,
9163
+ tools: modelToolsEnabled ? tools : [],
9164
+ hostedTools: modelToolsEnabled ? hostedTools : [],
7977
9165
  systemPrompt,
7978
9166
  modelRegistry: modelRegistry ?? DEFAULT_MODEL_REGISTRY2,
7979
9167
  toolOutputCache: {
7980
9168
  totalBudgetTrim: totalBudgetTrimEnabled
7981
9169
  },
7982
- services: { toolOutputCacheStore },
7983
- canExecuteTool: (call, raw, ctx2) => options.subagents?.isAvailable() && workspaceRoot && call.function.name === "task_spawn" ? { decision: "allow" } : canExecuteTool(call, raw, ctx2)
9170
+ services: {
9171
+ toolOutputCacheStore,
9172
+ ...imageStore ? { resolveImage: imageStore.resolve.bind(imageStore) } : {}
9173
+ },
9174
+ canExecuteTool: (call, raw, ctx2) => imageTools.some((tool) => tool.name === call.function.name) && call.function.name !== "image_inspect" ? { decision: "allow" } : options.subagents?.isAvailable() && workspaceRoot && call.function.name === "task_spawn" ? { decision: "allow" } : canExecuteTool(call, raw, ctx2)
7984
9175
  });
7985
9176
  if (approvalModeResolution.persistSelection) {
7986
9177
  await approvalModeResolution.persistSelection();
@@ -8510,8 +9701,8 @@ var parseAuthorizationServerMetadata = (value) => {
8510
9701
  var buildAuthorizationServerMetadataUrl = (issuer) => {
8511
9702
  try {
8512
9703
  const parsed = new URL(issuer);
8513
- const path18 = parsed.pathname === "/" ? "" : parsed.pathname;
8514
- const basePath = path18.startsWith("/") ? path18 : `/${path18}`;
9704
+ const path21 = parsed.pathname === "/" ? "" : parsed.pathname;
9705
+ const basePath = path21.startsWith("/") ? path21 : `/${path21}`;
8515
9706
  const metadataPath = `/.well-known/oauth-authorization-server${basePath}`;
8516
9707
  return new URL(metadataPath, `${parsed.origin}/`).toString();
8517
9708
  } catch {
@@ -8615,8 +9806,8 @@ var MAX_TOOLS_LIST_PAGES = 100;
8615
9806
  var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8616
9807
  var isMcpToolDescriptor = (value) => isRecord6(value) && typeof value.name === "string";
8617
9808
  var toSlug2 = (value) => {
8618
- const slug = value.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
8619
- return slug || "tool";
9809
+ const slug2 = value.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
9810
+ return slug2 || "tool";
8620
9811
  };
8621
9812
  var hash8 = (value) => crypto7.createHash("sha256").update(value).digest("hex").slice(0, 8);
8622
9813
  var clampToolName = (value) => {
@@ -9170,7 +10361,7 @@ var McpManager = class {
9170
10361
 
9171
10362
  // src/rpc/handlers.ts
9172
10363
  import {
9173
- RPC_ERROR_CODE as RPC_ERROR_CODE9
10364
+ RPC_ERROR_CODE as RPC_ERROR_CODE11
9174
10365
  } from "@codelia/protocol";
9175
10366
  import {
9176
10367
  RunEventStoreFactoryImpl,
@@ -9326,12 +10517,12 @@ var createContextHandlers = ({
9326
10517
 
9327
10518
  // src/rpc/history.ts
9328
10519
  import { createReadStream, promises as fs14 } from "fs";
9329
- import path12 from "path";
10520
+ import path15 from "path";
9330
10521
  import { createInterface as createInterface2 } from "readline";
9331
10522
  import {
9332
10523
  RPC_ERROR_CODE as RPC_ERROR_CODE2
9333
10524
  } from "@codelia/protocol";
9334
- import { resolveStoragePaths as resolveStoragePaths2 } from "@codelia/storage";
10525
+ import { resolveStoragePaths as resolveStoragePaths3 } from "@codelia/storage";
9335
10526
  var DEFAULT_HISTORY_RUNS = 20;
9336
10527
  var DEFAULT_HISTORY_EVENTS = 1500;
9337
10528
  var runStartInputToHiddenMessage = (input) => {
@@ -9386,7 +10577,7 @@ var readFirstLine = async (filePath) => {
9386
10577
  }
9387
10578
  };
9388
10579
  var collectRunCandidates = async (log2) => {
9389
- const paths = resolveStoragePaths2();
10580
+ const paths = resolveStoragePaths3();
9390
10581
  const sessionsDir = paths.sessionsDir;
9391
10582
  let yearEntries;
9392
10583
  try {
@@ -9402,7 +10593,7 @@ var collectRunCandidates = async (log2) => {
9402
10593
  for (const yearEntry of yearEntries) {
9403
10594
  if (!yearEntry.isDirectory()) continue;
9404
10595
  if (!/^\d{4}$/.test(yearEntry.name)) continue;
9405
- const yearPath = path12.join(sessionsDir, yearEntry.name);
10596
+ const yearPath = path15.join(sessionsDir, yearEntry.name);
9406
10597
  let monthEntries;
9407
10598
  try {
9408
10599
  monthEntries = await fs14.readdir(yearPath, {
@@ -9415,7 +10606,7 @@ var collectRunCandidates = async (log2) => {
9415
10606
  for (const monthEntry of monthEntries) {
9416
10607
  if (!monthEntry.isDirectory()) continue;
9417
10608
  if (!/^\d{2}$/.test(monthEntry.name)) continue;
9418
- const monthPath = path12.join(yearPath, monthEntry.name);
10609
+ const monthPath = path15.join(yearPath, monthEntry.name);
9419
10610
  let dayEntries;
9420
10611
  try {
9421
10612
  dayEntries = await fs14.readdir(monthPath, {
@@ -9428,7 +10619,7 @@ var collectRunCandidates = async (log2) => {
9428
10619
  for (const dayEntry of dayEntries) {
9429
10620
  if (!dayEntry.isDirectory()) continue;
9430
10621
  if (!/^\d{2}$/.test(dayEntry.name)) continue;
9431
- const dayPath = path12.join(monthPath, dayEntry.name);
10622
+ const dayPath = path15.join(monthPath, dayEntry.name);
9432
10623
  let files;
9433
10624
  try {
9434
10625
  files = await fs14.readdir(dayPath, {
@@ -9441,7 +10632,7 @@ var collectRunCandidates = async (log2) => {
9441
10632
  for (const file of files) {
9442
10633
  if (!file.isFile()) continue;
9443
10634
  if (!file.name.endsWith(".jsonl")) continue;
9444
- const filePath = path12.join(dayPath, file.name);
10635
+ const filePath = path15.join(dayPath, file.name);
9445
10636
  try {
9446
10637
  const stat = await fs14.stat(filePath);
9447
10638
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
@@ -9469,7 +10660,7 @@ var collectSessionRuns = async (sessionId, maxRuns, log2) => {
9469
10660
  const header = parseRunHeader(headerLine);
9470
10661
  if (!header) continue;
9471
10662
  if (header.session_id !== sessionId) continue;
9472
- const runId = header.run_id ?? path12.basename(candidate.path, ".jsonl");
10663
+ const runId = header.run_id ?? path15.basename(candidate.path, ".jsonl");
9473
10664
  const startedAt = header.started_at ?? new Date(candidate.mtimeMs).toISOString();
9474
10665
  runs.push({
9475
10666
  path: candidate.path,
@@ -9524,7 +10715,7 @@ var createHistoryHandlers = ({
9524
10715
  if (typeof value !== "string") return void 0;
9525
10716
  const trimmed = value.trim();
9526
10717
  if (!trimmed) return void 0;
9527
- return path12.resolve(trimmed);
10718
+ return path15.resolve(trimmed);
9528
10719
  };
9529
10720
  const handleSessionList = async (id, params) => {
9530
10721
  const limit = params?.limit ?? 50;
@@ -9624,16 +10815,276 @@ var createHistoryHandlers = ({
9624
10815
  log2(`session.history resume diff error: ${String(error)}`);
9625
10816
  }
9626
10817
  }
9627
- const result = {
9628
- runs: runs.length,
9629
- events_sent: selectedEvents.length,
9630
- ...truncated ? { truncated: true } : {},
9631
- ...resumeDiff ? { resume_diff: resumeDiff } : {}
9632
- };
9633
- sendResult(id, result);
10818
+ const result = {
10819
+ runs: runs.length,
10820
+ events_sent: selectedEvents.length,
10821
+ ...truncated ? { truncated: true } : {},
10822
+ ...resumeDiff ? { resume_diff: resumeDiff } : {}
10823
+ };
10824
+ sendResult(id, result);
10825
+ };
10826
+ return { handleSessionList, handleSessionHistory };
10827
+ };
10828
+
10829
+ // src/rpc/image.ts
10830
+ import {
10831
+ OPENAI_CODEX_IMAGE_MODELS as OPENAI_CODEX_IMAGE_MODELS2,
10832
+ OPENAI_IMAGE_MODELS as OPENAI_IMAGE_MODELS2,
10833
+ parseImageGenerationConfig
10834
+ } from "@codelia/config";
10835
+ import {
10836
+ RPC_ERROR_CODE as RPC_ERROR_CODE3
10837
+ } from "@codelia/protocol";
10838
+ import { z as z26 } from "zod";
10839
+ var paramsSchema = z26.object({
10840
+ mode: z26.enum(["off", "builtin", "custom"]).optional(),
10841
+ provider: z26.enum(["openai", "openrouter"]).optional(),
10842
+ model: z26.string().max(160).optional(),
10843
+ endpoint: z26.string().max(160).optional(),
10844
+ api_key_env: z26.string().max(128).optional()
10845
+ }).strict();
10846
+ function createImageHandlers(state) {
10847
+ const catalog = new ImageCatalog();
10848
+ let configuring = false;
10849
+ const workspace = () => {
10850
+ const env = state.effectiveEnvironment;
10851
+ if (!isTuiLocalEnvironment(env))
10852
+ throw new ImageGenerationError(
10853
+ "Image services are unavailable in this embedding environment."
10854
+ );
10855
+ return env.workspace.root ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? process.cwd();
10856
+ };
10857
+ const currentChat = async () => {
10858
+ const model = await resolveEffectiveModelConfig(state, workspace());
10859
+ const provider = model.provider ?? state.currentModelProvider ?? "openai";
10860
+ const saved = (await new AuthStore().load()).providers[provider];
10861
+ if (saved) return { provider, auth: saved };
10862
+ const key = provider === "openai" ? localImageAuth.env("OPENAI_API_KEY") : void 0;
10863
+ return key ? { provider, auth: { method: "api_key", api_key: key } } : void 0;
10864
+ };
10865
+ const status = async (config) => {
10866
+ try {
10867
+ const chat = config.mode === "builtin" ? await currentChat() : void 0;
10868
+ const route = await resolveImageRoute(config, localImageAuth, chat);
10869
+ if (!route)
10870
+ return {
10871
+ requested_mode: config.mode,
10872
+ state: "disabled",
10873
+ message: "Image generation is off. Conversation model is unchanged."
10874
+ };
10875
+ if (route.provider === "openrouter" && !(await catalog.endpoints(route.model)).some(
10876
+ (e) => e.provider_tag === route.endpoint
10877
+ ))
10878
+ throw new ImageGenerationError(
10879
+ "Selected image endpoint is unavailable; select another explicitly."
10880
+ );
10881
+ return {
10882
+ requested_mode: config.mode,
10883
+ state: "available",
10884
+ provider: route.provider,
10885
+ requested_model: route.model,
10886
+ endpoint: route.endpoint,
10887
+ auth_mode: route.authMode,
10888
+ message: `Image generation: ${config.mode} / ${route.provider} / ${route.model}. ${route.authMode === "codex_oauth" ? "Uses the current Codex OAuth login; no API key required. Account image usage/limits apply." : "Chargeable public Image API using an API key."} Account/model access and cost are not proven by selection. PNG only (8 MiB/4096px/16 MP); other outputs are rejected, possibly after usage is consumed. No automatic fallback. Conversation model is unchanged.`
10889
+ };
10890
+ } catch (error) {
10891
+ return {
10892
+ requested_mode: config.mode,
10893
+ state: "unavailable",
10894
+ message: error instanceof ImageGenerationError ? error.message : "Image configuration/auth unavailable; chat is unchanged."
10895
+ };
10896
+ }
10897
+ };
10898
+ const pick = async (title, items) => {
10899
+ const result = await requestUiPick(state, { title, items });
10900
+ const selected = result?.ids[0];
10901
+ return items.some((i) => i.id === selected) ? selected : void 0;
10902
+ };
10903
+ const choose = async () => {
10904
+ if (!state.uiCapabilities?.supports_pick)
10905
+ throw new ImageGenerationError(
10906
+ "This client cannot open the image picker. Supply explicit mode/provider/model settings."
10907
+ );
10908
+ const mode = await pick(
10909
+ "Image generation (separate from conversation model)",
10910
+ [
10911
+ {
10912
+ id: "off",
10913
+ label: "Off",
10914
+ detail: "No image generation or image API spending"
10915
+ },
10916
+ {
10917
+ id: "builtin",
10918
+ label: "Builtin: current conversation connection",
10919
+ detail: "Use current OpenAI login: Codex OAuth or API key; no authentication switch"
10920
+ },
10921
+ {
10922
+ id: "custom",
10923
+ label: "Custom: independent image provider/model",
10924
+ detail: "API key required; does not change chat authentication"
10925
+ }
10926
+ ]
10927
+ );
10928
+ if (!mode) return null;
10929
+ if (mode === "off") return { mode };
10930
+ const provider = mode === "builtin" ? "openai" : await pick("Image API provider", [
10931
+ { id: "openai", label: "OpenAI Image API" },
10932
+ { id: "openrouter", label: "OpenRouter Image API" }
10933
+ ]);
10934
+ if (!provider) return null;
10935
+ let model;
10936
+ let endpoint;
10937
+ if (provider === "openai") {
10938
+ const chat = mode === "builtin" ? await currentChat() : void 0;
10939
+ if (mode === "builtin" && chat?.provider !== "openai")
10940
+ throw new ImageGenerationError(
10941
+ "Builtin images require an OpenAI conversation login. Sign in first; no API key is required for Codex OAuth."
10942
+ );
10943
+ const codex = chat?.auth.method === "oauth";
10944
+ model = await pick(
10945
+ codex ? "Codex OAuth image model (current login; account-specific limits)" : "Image model (API billed; availability is account-specific)",
10946
+ (codex ? OPENAI_CODEX_IMAGE_MODELS2 : OPENAI_IMAGE_MODELS2).map((id) => ({
10947
+ id,
10948
+ label: id,
10949
+ ...codex ? {
10950
+ detail: id === "gpt-image-2" ? "Inspected Codex tool default" : "Explicit request; support/effective model depends on the Codex backend"
10951
+ } : {}
10952
+ }))
10953
+ );
10954
+ } else {
10955
+ const listing = await catalog.list();
10956
+ model = await pick(
10957
+ `OpenRouter image models (${listing.stale ? "stale" : "fetched"} ${listing.fetched_at})`,
10958
+ listing.models.map((m) => ({ id: m.id, label: m.name, detail: m.id }))
10959
+ );
10960
+ if (!model) return null;
10961
+ const endpoints = await catalog.endpoints(model);
10962
+ if (!endpoints.length)
10963
+ throw new ImageGenerationError(
10964
+ "This model has no supported pin-able PNG endpoint. Choose another image model."
10965
+ );
10966
+ endpoint = await pick(
10967
+ "Pin image endpoint (no fallback)",
10968
+ endpoints.flatMap(
10969
+ (e) => e.provider_tag ? [{ id: e.provider_tag, label: e.provider_tag }] : []
10970
+ )
10971
+ );
10972
+ if (!endpoint) return null;
10973
+ }
10974
+ if (!model) return null;
10975
+ return parseImageGenerationConfig(
10976
+ mode === "builtin" ? { mode, provider_options: { openai: { model } } } : {
10977
+ mode,
10978
+ provider,
10979
+ model,
10980
+ ...endpoint ? { provider_options: { openrouter: { endpoint } } } : {}
10981
+ }
10982
+ );
10983
+ };
10984
+ const handle = async (id, operation, params) => {
10985
+ let ownsConfiguration = false;
10986
+ try {
10987
+ const root = workspace();
10988
+ if (operation === "artifact") {
10989
+ const parsed2 = z26.object({
10990
+ artifact_id: z26.string().regex(/^codelia-image-[0-9a-f-]{36}$/)
10991
+ }).strict().safeParse(params);
10992
+ if (!parsed2.success)
10993
+ throw new ImageGenerationError("Invalid image artifact request.");
10994
+ const { metadata, bytes } = await createLocalImageStore(root).read(
10995
+ parsed2.data.artifact_id
10996
+ );
10997
+ sendResult(id, {
10998
+ metadata,
10999
+ data_url: `data:${metadata.media_type};base64,${bytes.toString("base64")}`
11000
+ });
11001
+ return;
11002
+ }
11003
+ if (operation === "get") {
11004
+ sendResult(id, await status(await resolveImageGenerationConfig(root)));
11005
+ return;
11006
+ }
11007
+ if (state.activeRunId || configuring)
11008
+ throw new ImageGenerationError(
11009
+ "Wait for the active run or image settings dialog before changing image settings."
11010
+ );
11011
+ configuring = true;
11012
+ ownsConfiguration = true;
11013
+ const parsed = paramsSchema.safeParse(params ?? {});
11014
+ if (!parsed.success)
11015
+ throw new ImageGenerationError("Invalid image model settings.");
11016
+ const p = parsed.data;
11017
+ let config;
11018
+ if (p.mode) {
11019
+ if (p.mode !== "custom" && (p.provider || p.endpoint || p.api_key_env))
11020
+ throw new ImageGenerationError(
11021
+ "Provider, endpoint and api_key_env are custom-only."
11022
+ );
11023
+ config = parseImageGenerationConfig(
11024
+ p.mode === "off" ? { mode: p.mode, ...p.model ? { model: p.model } : {} } : p.mode === "builtin" ? {
11025
+ mode: p.mode,
11026
+ ...p.model ? { provider_options: { openai: { model: p.model } } } : {}
11027
+ } : {
11028
+ mode: p.mode,
11029
+ provider: p.provider,
11030
+ model: p.model,
11031
+ ...p.api_key_env ? { api_key_env: p.api_key_env } : {},
11032
+ ...p.endpoint ? {
11033
+ provider_options: {
11034
+ openrouter: { endpoint: p.endpoint }
11035
+ }
11036
+ } : {}
11037
+ }
11038
+ );
11039
+ } else {
11040
+ if (Object.keys(p).length)
11041
+ throw new ImageGenerationError(
11042
+ "mode is required for explicit image settings."
11043
+ );
11044
+ config = await choose();
11045
+ }
11046
+ if (!config) {
11047
+ sendResult(id, { message: "Image settings unchanged." });
11048
+ return;
11049
+ }
11050
+ const next = await status(config);
11051
+ if (config.mode !== "off") {
11052
+ if (!state.uiCapabilities?.supports_confirm)
11053
+ throw new ImageGenerationError(
11054
+ "Image route changes require a confirmation-capable UI; headless users can explicitly edit image_generation in config.json."
11055
+ );
11056
+ const confirm = await requestUiConfirm(state, {
11057
+ title: "Save image generation route?",
11058
+ message: `${next.message}
11059
+ This saves image settings only; generation requests use the tool permission policy. ${next.auth_mode === "codex_oauth" ? "Uses your existing OpenAI login; no API key setup is needed." : config.mode === "custom" ? "Missing API keys must be supplied in the runtime environment." : "If login is missing, sign in to OpenAI first."}`,
11060
+ confirm_label: "Save",
11061
+ cancel_label: "Cancel"
11062
+ });
11063
+ if (!confirm?.ok) {
11064
+ sendResult(id, { message: "Image settings unchanged." });
11065
+ return;
11066
+ }
11067
+ }
11068
+ if (state.activeRunId)
11069
+ throw new ImageGenerationError(
11070
+ "A run started; image settings were not changed. Try again after it finishes."
11071
+ );
11072
+ await updateImageGeneration(root, config);
11073
+ state.agent = null;
11074
+ state.tools = null;
11075
+ state.toolDefinitions = null;
11076
+ sendResult(id, next);
11077
+ } catch (error) {
11078
+ sendError(id, {
11079
+ code: RPC_ERROR_CODE3.INVALID_PARAMS,
11080
+ message: error instanceof ImageGenerationError ? error.message : "Image operation failed; check settings, artifact and runtime storage. No credentials were changed."
11081
+ });
11082
+ } finally {
11083
+ if (ownsConfiguration) configuring = false;
11084
+ }
9634
11085
  };
9635
- return { handleSessionList, handleSessionHistory };
9636
- };
11086
+ return { handle };
11087
+ }
9637
11088
 
9638
11089
  // src/rpc/model.ts
9639
11090
  import {
@@ -9646,9 +11097,9 @@ import {
9646
11097
  } from "@codelia/core";
9647
11098
  import { ModelMetadataServiceImpl as ModelMetadataServiceImpl2 } from "@codelia/model-metadata";
9648
11099
  import {
9649
- RPC_ERROR_CODE as RPC_ERROR_CODE3
11100
+ RPC_ERROR_CODE as RPC_ERROR_CODE4
9650
11101
  } from "@codelia/protocol";
9651
- var isSupportedProvider = (provider) => provider === "openai" || provider === "anthropic" || provider === "openrouter" || provider === "moonshot" || provider === "zai" || provider === "xai";
11102
+ var isSupportedProvider = (provider, providers) => SUPPORTED_PROVIDERS.includes(provider) || Boolean(providers && Object.hasOwn(providers, provider));
9652
11103
  var resolveProviderModelEntry2 = (providerEntries, provider, model) => {
9653
11104
  if (!providerEntries) {
9654
11105
  return null;
@@ -9897,8 +11348,34 @@ var buildProviderModelList = async ({
9897
11348
  includeDetails,
9898
11349
  state,
9899
11350
  log: log2,
9900
- providerEntriesOverride
11351
+ providerEntriesOverride,
11352
+ providers
9901
11353
  }) => {
11354
+ const effectiveProviders = providers ?? (state ? (await resolveEnvironmentModelConfig(
11355
+ state,
11356
+ state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0
11357
+ )).providers : void 0);
11358
+ const endpoint = getResponsesProvider(
11359
+ { providers: effectiveProviders },
11360
+ provider
11361
+ );
11362
+ if (endpoint) {
11363
+ const models2 = Object.keys(endpoint.models);
11364
+ const details2 = includeDetails ? Object.fromEntries(
11365
+ models2.map((model) => {
11366
+ const spec = endpoint.models[model];
11367
+ return [
11368
+ model,
11369
+ {
11370
+ context_window: spec.context_window,
11371
+ max_input_tokens: spec.max_input_tokens,
11372
+ max_output_tokens: spec.max_output_tokens
11373
+ }
11374
+ ];
11375
+ })
11376
+ ) : void 0;
11377
+ return { models: models2, ...details2 ? { details: details2 } : {} };
11378
+ }
9902
11379
  if (provider === "openrouter") {
9903
11380
  return buildOpenRouterModelList({ includeDetails, state, log: log2 });
9904
11381
  }
@@ -9972,13 +11449,7 @@ var createModelHandlers = ({
9972
11449
  const handleModelList = async (id, params) => {
9973
11450
  const requestedProvider = params?.provider;
9974
11451
  const includeDetails = params?.include_details ?? false;
9975
- if (requestedProvider && !isSupportedProvider(requestedProvider)) {
9976
- sendError(id, {
9977
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
9978
- message: `unsupported provider: ${requestedProvider}`
9979
- });
9980
- return;
9981
- }
11452
+ let providers;
9982
11453
  let current;
9983
11454
  let source = "config";
9984
11455
  let configuredProvider;
@@ -9987,6 +11458,7 @@ var createModelHandlers = ({
9987
11458
  try {
9988
11459
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0;
9989
11460
  const config = await resolveEffectiveModelConfig(state, workingDir);
11461
+ providers = config.providers;
9990
11462
  source = config.source;
9991
11463
  configuredProvider = config.provider ?? "openai";
9992
11464
  configuredReasoning = resolveReasoningEffort(config.reasoning);
@@ -10002,15 +11474,15 @@ var createModelHandlers = ({
10002
11474
  }
10003
11475
  } catch (error) {
10004
11476
  sendError(id, {
10005
- code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
11477
+ code: RPC_ERROR_CODE4.RUNTIME_INTERNAL,
10006
11478
  message: String(error)
10007
11479
  });
10008
11480
  return;
10009
11481
  }
10010
11482
  const provider = requestedProvider ?? configuredProvider ?? "openai";
10011
- if (!isSupportedProvider(provider)) {
11483
+ if (!isSupportedProvider(provider, providers)) {
10012
11484
  sendError(id, {
10013
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11485
+ code: RPC_ERROR_CODE4.INVALID_PARAMS,
10014
11486
  message: `unsupported provider: ${provider}`
10015
11487
  });
10016
11488
  return;
@@ -10021,6 +11493,7 @@ var createModelHandlers = ({
10021
11493
  const result2 = await buildProviderModelList({
10022
11494
  provider,
10023
11495
  includeDetails,
11496
+ providers,
10024
11497
  state,
10025
11498
  log: log2
10026
11499
  });
@@ -10028,7 +11501,7 @@ var createModelHandlers = ({
10028
11501
  details = result2.details;
10029
11502
  } catch (error) {
10030
11503
  sendError(id, {
10031
- code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
11504
+ code: RPC_ERROR_CODE4.RUNTIME_INTERNAL,
10032
11505
  message: String(error)
10033
11506
  });
10034
11507
  return;
@@ -10036,8 +11509,17 @@ var createModelHandlers = ({
10036
11509
  if (current && !models.includes(current)) {
10037
11510
  current = void 0;
10038
11511
  }
11512
+ const endpoint = getResponsesProvider({ providers }, provider);
11513
+ const reasoningLevels = endpoint ? Object.fromEntries(
11514
+ Object.entries(endpoint.models).map(([name, spec]) => [
11515
+ name,
11516
+ spec.supports_reasoning ? spec.reasoning_levels ?? ["low", "medium", "high"] : []
11517
+ ])
11518
+ ) : void 0;
10039
11519
  const result = {
11520
+ ...reasoningLevels ? { reasoning_levels: reasoningLevels } : {},
10040
11521
  provider,
11522
+ providers: configuredProviders(providers),
10041
11523
  models,
10042
11524
  current,
10043
11525
  source,
@@ -10050,7 +11532,7 @@ var createModelHandlers = ({
10050
11532
  const handleModelSet = async (id, params) => {
10051
11533
  if (state.activeRunId) {
10052
11534
  sendError(id, {
10053
- code: RPC_ERROR_CODE3.RUNTIME_BUSY,
11535
+ code: RPC_ERROR_CODE4.RUNTIME_BUSY,
10054
11536
  message: "runtime busy"
10055
11537
  });
10056
11538
  return;
@@ -10058,7 +11540,7 @@ var createModelHandlers = ({
10058
11540
  const scope = params?.scope ?? "config";
10059
11541
  if (scope !== "config" && scope !== "session") {
10060
11542
  sendError(id, {
10061
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11543
+ code: RPC_ERROR_CODE4.INVALID_PARAMS,
10062
11544
  message: `unsupported model scope: ${scope}`
10063
11545
  });
10064
11546
  return;
@@ -10067,7 +11549,7 @@ var createModelHandlers = ({
10067
11549
  if (params?.reset) {
10068
11550
  if (scope !== "session") {
10069
11551
  sendError(id, {
10070
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11552
+ code: RPC_ERROR_CODE4.INVALID_PARAMS,
10071
11553
  message: "model reset is only supported for session scope"
10072
11554
  });
10073
11555
  return;
@@ -10080,7 +11562,7 @@ var createModelHandlers = ({
10080
11562
  const name2 = config.name;
10081
11563
  if (!name2) {
10082
11564
  sendError(id, {
10083
- code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
11565
+ code: RPC_ERROR_CODE4.RUNTIME_INTERNAL,
10084
11566
  message: "configured model name is missing"
10085
11567
  });
10086
11568
  return;
@@ -10106,7 +11588,7 @@ var createModelHandlers = ({
10106
11588
  log2(`model.set reset session override -> ${provider2}/${name2}`);
10107
11589
  } catch (error) {
10108
11590
  sendError(id, {
10109
- code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
11591
+ code: RPC_ERROR_CODE4.RUNTIME_INTERNAL,
10110
11592
  message: String(error)
10111
11593
  });
10112
11594
  }
@@ -10116,7 +11598,7 @@ var createModelHandlers = ({
10116
11598
  const name = params?.name?.trim();
10117
11599
  if (!name) {
10118
11600
  sendError(id, {
10119
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11601
+ code: RPC_ERROR_CODE4.INVALID_PARAMS,
10120
11602
  message: "model name is required"
10121
11603
  });
10122
11604
  return;
@@ -10127,24 +11609,47 @@ var createModelHandlers = ({
10127
11609
  reasoning = resolveReasoningEffort(params.reasoning);
10128
11610
  } catch (error) {
10129
11611
  sendError(id, {
10130
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11612
+ code: RPC_ERROR_CODE4.INVALID_PARAMS,
10131
11613
  message: String(error)
10132
11614
  });
10133
11615
  return;
10134
11616
  }
10135
11617
  }
10136
- if (provider !== "openai" && provider !== "anthropic" && provider !== "openrouter" && provider !== "moonshot" && provider !== "zai" && provider !== "xai") {
11618
+ const configured = await resolveEnvironmentModelConfig(state, workingDir);
11619
+ const endpoint = getResponsesProvider(configured, provider);
11620
+ if (!isSupportedProvider(provider, configured.providers)) {
10137
11621
  sendError(id, {
10138
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11622
+ code: RPC_ERROR_CODE4.INVALID_PARAMS,
10139
11623
  message: `unsupported provider: ${provider}`
10140
11624
  });
10141
11625
  return;
10142
11626
  }
11627
+ if (endpoint) {
11628
+ try {
11629
+ if (reasoning && !endpoint.models[name]?.supports_reasoning)
11630
+ throw new Error(`Reasoning is disabled for ${provider}/${name}`);
11631
+ resolveConfiguredReasoning(
11632
+ { ...configured, reasoning: reasoning ?? configured.reasoning },
11633
+ provider,
11634
+ name
11635
+ );
11636
+ } catch (error) {
11637
+ sendError(id, {
11638
+ code: RPC_ERROR_CODE4.INVALID_PARAMS,
11639
+ message: String(error)
11640
+ });
11641
+ return;
11642
+ }
11643
+ }
10143
11644
  if (provider !== "openrouter") {
10144
- const spec = resolveModel2(DEFAULT_MODEL_REGISTRY3, name, provider);
11645
+ const spec = resolveModel2(
11646
+ buildConfiguredModelRegistry(configured.providers),
11647
+ name,
11648
+ provider
11649
+ );
10145
11650
  if (!spec) {
10146
11651
  sendError(id, {
10147
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11652
+ code: RPC_ERROR_CODE4.INVALID_PARAMS,
10148
11653
  message: `unknown model: ${name}`
10149
11654
  });
10150
11655
  return;
@@ -10204,7 +11709,7 @@ var createModelHandlers = ({
10204
11709
  );
10205
11710
  } catch (error) {
10206
11711
  sendError(id, {
10207
- code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
11712
+ code: RPC_ERROR_CODE4.RUNTIME_INTERNAL,
10208
11713
  message: String(error)
10209
11714
  });
10210
11715
  }
@@ -10214,7 +11719,7 @@ var createModelHandlers = ({
10214
11719
 
10215
11720
  // src/rpc/resume-context.ts
10216
11721
  import { promises as fs15 } from "fs";
10217
- import path13 from "path";
11722
+ import path16 from "path";
10218
11723
  var RESUME_CONTEXT_META_KEY = "codelia_resume_context";
10219
11724
  var RESUME_CONTEXT_SCHEMA_VERSION = 1;
10220
11725
  var RESUME_DIFF_TAG = '<system-reminder type="session.resume.diff">';
@@ -10223,7 +11728,7 @@ var normalizePath2 = (value) => {
10223
11728
  if (typeof value !== "string") return void 0;
10224
11729
  const trimmed = value.trim();
10225
11730
  if (!trimmed) return void 0;
10226
- return path13.resolve(trimmed);
11731
+ return path16.resolve(trimmed);
10227
11732
  };
10228
11733
  var normalizeMtime3 = (value) => {
10229
11734
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
@@ -10586,7 +12091,7 @@ var buildResumeDiff = async (meta, state, options = {}) => {
10586
12091
 
10587
12092
  // src/rpc/run.ts
10588
12093
  import {
10589
- RPC_ERROR_CODE as RPC_ERROR_CODE4
12094
+ RPC_ERROR_CODE as RPC_ERROR_CODE5
10590
12095
  } from "@codelia/protocol";
10591
12096
 
10592
12097
  // src/rpc/client-tool-requests.ts
@@ -10901,6 +12406,17 @@ var summarizeProviderMeta = (value) => {
10901
12406
  if (typeof value === "object") {
10902
12407
  const obj = value;
10903
12408
  const details = [];
12409
+ const codex = obj.codex_metadata;
12410
+ if (codex && typeof codex === "object" && !Array.isArray(codex)) {
12411
+ const metadata = codex;
12412
+ if (typeof metadata.server_model === "string" && /^[a-zA-Z0-9._/-]{1,128}$/.test(metadata.server_model))
12413
+ details.push(`server_model=${metadata.server_model}`);
12414
+ if (Array.isArray(metadata.model_verifications) && metadata.model_verifications.includes("trusted_access_for_cyber"))
12415
+ details.push("verification=trusted_access_for_cyber");
12416
+ if (metadata.moderation_metadata_present === true)
12417
+ details.push("moderation_metadata=present");
12418
+ if (metadata.safety_buffering) details.push("safety_buffering=observed");
12419
+ }
10904
12420
  if (typeof obj.transport === "string") {
10905
12421
  details.push(`transport=${obj.transport}`);
10906
12422
  }
@@ -11054,6 +12570,24 @@ var runInputLengthForDebug = (input) => {
11054
12570
  return total;
11055
12571
  };
11056
12572
 
12573
+ // src/rpc/run-metrics.ts
12574
+ var buildRunMetrics = (record) => {
12575
+ const timing = record.output.timing;
12576
+ const tokens = record.output.usage?.output_tokens;
12577
+ const duration = timing?.generation_duration_ms;
12578
+ const reasoning = record.output.usage?.output_reasoning_tokens;
12579
+ const matchedReasoning = reasoning === void 0 || reasoning === null || Number.isFinite(reasoning) && reasoning >= 0 && reasoning <= (tokens ?? 0) && (reasoning === 0 || timing?.generation_start_source === "reasoning_item" && typeof timing.generation_start_ms === "number");
12580
+ const validTiming = timing && Number.isFinite(timing.time_to_first_token_ms) && timing.time_to_first_token_ms >= 0 && typeof duration === "number" && Number.isFinite(duration) && duration >= 0 && (timing.generation_start_ms === void 0 || Number.isFinite(timing.generation_start_ms) && timing.generation_start_ms >= 0 && timing.generation_start_ms <= timing.time_to_first_token_ms);
12581
+ const rate = validTiming && matchedReasoning && typeof tokens === "number" && Number.isFinite(tokens) && tokens >= 0 && // Very short/batched streams do not expose a useful generation interval.
12582
+ duration >= 250 ? tokens * 1e3 / duration : null;
12583
+ return {
12584
+ run_id: record.run_id,
12585
+ seq: record.seq,
12586
+ output_tokens_per_second: rate !== null && Number.isFinite(rate) ? rate : null,
12587
+ ...validTiming ? { timing } : {}
12588
+ };
12589
+ };
12590
+
11057
12591
  // src/rpc/run.ts
11058
12592
  var nowIso4 = () => (/* @__PURE__ */ new Date()).toISOString();
11059
12593
  var SESSION_STATE_SAVE_DEBOUNCE_MS = 1500;
@@ -11178,7 +12712,7 @@ var createRunHandlers = ({
11178
12712
  normalizedInput = normalizeRunInput(params.input);
11179
12713
  } catch (error) {
11180
12714
  sendError(id, {
11181
- code: RPC_ERROR_CODE4.INVALID_PARAMS,
12715
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
11182
12716
  message: String(error)
11183
12717
  });
11184
12718
  return;
@@ -11188,7 +12722,7 @@ var createRunHandlers = ({
11188
12722
  await beforeRunStart();
11189
12723
  } catch (error) {
11190
12724
  sendError(id, {
11191
- code: RPC_ERROR_CODE4.RUNTIME_INTERNAL,
12725
+ code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
11192
12726
  message: `startup onboarding failed: ${String(error)}`
11193
12727
  });
11194
12728
  return;
@@ -11196,7 +12730,7 @@ var createRunHandlers = ({
11196
12730
  }
11197
12731
  if (state.activeRunId) {
11198
12732
  sendError(id, {
11199
- code: RPC_ERROR_CODE4.RUNTIME_BUSY,
12733
+ code: RPC_ERROR_CODE5.RUNTIME_BUSY,
11200
12734
  message: "runtime busy"
11201
12735
  });
11202
12736
  return;
@@ -11211,14 +12745,14 @@ var createRunHandlers = ({
11211
12745
  resumeState = await sessionStateStore.load(requestedSessionId);
11212
12746
  } catch (error) {
11213
12747
  sendError(id, {
11214
- code: RPC_ERROR_CODE4.SESSION_LOAD_FAILED,
12748
+ code: RPC_ERROR_CODE5.SESSION_LOAD_FAILED,
11215
12749
  message: `session load failed: ${String(error)}`
11216
12750
  });
11217
12751
  return;
11218
12752
  }
11219
12753
  if (!resumeState) {
11220
12754
  sendError(id, {
11221
- code: RPC_ERROR_CODE4.SESSION_NOT_FOUND,
12755
+ code: RPC_ERROR_CODE5.SESSION_NOT_FOUND,
11222
12756
  message: "session not found"
11223
12757
  });
11224
12758
  return;
@@ -11229,7 +12763,7 @@ var createRunHandlers = ({
11229
12763
  resumeState = await sessionStateStore.load(state.sessionId);
11230
12764
  } catch (error) {
11231
12765
  sendError(id, {
11232
- code: RPC_ERROR_CODE4.SESSION_LOAD_FAILED,
12766
+ code: RPC_ERROR_CODE5.SESSION_LOAD_FAILED,
11233
12767
  message: `session reload failed: ${String(error)}`
11234
12768
  });
11235
12769
  return;
@@ -11240,7 +12774,7 @@ var createRunHandlers = ({
11240
12774
  }
11241
12775
  if (resumeState?.meta?.codelia_subagent) {
11242
12776
  sendError(id, {
11243
- code: RPC_ERROR_CODE4.INVALID_PARAMS,
12777
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
11244
12778
  message: "Delegated sessions cannot be resumed as a root run"
11245
12779
  });
11246
12780
  return;
@@ -11248,9 +12782,12 @@ var createRunHandlers = ({
11248
12782
  let runtimeAgent;
11249
12783
  try {
11250
12784
  runtimeAgent = await getAgent();
12785
+ if (!params.force_compaction && state.prepareRunImages) {
12786
+ normalizedInput = await state.prepareRunImages(normalizedInput);
12787
+ }
11251
12788
  } catch (error) {
11252
12789
  sendError(id, {
11253
- code: RPC_ERROR_CODE4.RUNTIME_INTERNAL,
12790
+ code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
11254
12791
  message: String(error)
11255
12792
  });
11256
12793
  return;
@@ -11311,7 +12848,7 @@ var createRunHandlers = ({
11311
12848
  );
11312
12849
  } catch (error) {
11313
12850
  sendError(id, {
11314
- code: RPC_ERROR_CODE4.INVALID_PARAMS,
12851
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
11315
12852
  message: String(error)
11316
12853
  });
11317
12854
  return;
@@ -11365,6 +12902,24 @@ var createRunHandlers = ({
11365
12902
  }
11366
12903
  };
11367
12904
  const sessionAppend = (record) => {
12905
+ if (record.type === "llm.request") {
12906
+ try {
12907
+ sendRunMetrics(state, {
12908
+ run_id: record.run_id,
12909
+ seq: record.seq,
12910
+ output_tokens_per_second: null
12911
+ });
12912
+ } catch (error) {
12913
+ log2(`run metrics reset failed: ${String(error)}`);
12914
+ }
12915
+ }
12916
+ if (record.type === "llm.response") {
12917
+ try {
12918
+ sendRunMetrics(state, buildRunMetrics(record));
12919
+ } catch (error) {
12920
+ log2(`run metrics emit failed: ${String(error)}`);
12921
+ }
12922
+ }
11368
12923
  if (state.diagnosticsEnabled) {
11369
12924
  try {
11370
12925
  if (record.type === "llm.request") {
@@ -11387,6 +12942,7 @@ var createRunHandlers = ({
11387
12942
  const requestTsMs = request ? toTimestampMs(request.ts) : null;
11388
12943
  const latencyMs = responseTsMs !== null && requestTsMs !== null ? Math.max(0, responseTsMs - requestTsMs) : 0;
11389
12944
  const model = usage?.model ?? request?.model ?? "unknown";
12945
+ const metrics = buildRunMetrics(record);
11390
12946
  const diagnostics = {
11391
12947
  run_id: runId,
11392
12948
  seq: record.seq,
@@ -11395,6 +12951,8 @@ var createRunHandlers = ({
11395
12951
  request_ts: request?.ts ?? record.ts,
11396
12952
  response_ts: record.ts,
11397
12953
  latency_ms: latencyMs,
12954
+ ...metrics.timing ? { timing: metrics.timing } : {},
12955
+ output_tokens_per_second: metrics.output_tokens_per_second,
11398
12956
  stop_reason: record.output.stop_reason ?? null,
11399
12957
  usage,
11400
12958
  cache: {
@@ -11475,7 +13033,7 @@ var createRunHandlers = ({
11475
13033
  run_id: runId,
11476
13034
  session_id: sessionId,
11477
13035
  ts: nowIso4(),
11478
- input: params.input,
13036
+ input: Array.isArray(normalizedInput) && normalizedInput.some((part) => part.type === "image_ref") ? { type: "parts", parts: normalizedInput } : params.input,
11479
13037
  ui_context: params.ui_context,
11480
13038
  meta: params.meta
11481
13039
  });
@@ -11681,7 +13239,7 @@ var createRunHandlers = ({
11681
13239
  return;
11682
13240
  }
11683
13241
  sendError(id, {
11684
- code: RPC_ERROR_CODE4.RUN_NOT_FOUND,
13242
+ code: RPC_ERROR_CODE5.RUN_NOT_FOUND,
11685
13243
  message: "run not found"
11686
13244
  });
11687
13245
  };
@@ -11689,9 +13247,9 @@ var createRunHandlers = ({
11689
13247
  };
11690
13248
 
11691
13249
  // src/rpc/shell.ts
11692
- import path14 from "path";
13250
+ import path17 from "path";
11693
13251
  import {
11694
- RPC_ERROR_CODE as RPC_ERROR_CODE5
13252
+ RPC_ERROR_CODE as RPC_ERROR_CODE6
11695
13253
  } from "@codelia/protocol";
11696
13254
  import {
11697
13255
  ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl3
@@ -11708,14 +13266,14 @@ var truncateCommandPreview = (value) => {
11708
13266
  return `${trimmed.slice(0, COMMAND_PREVIEW_CHARS)}...[truncated]`;
11709
13267
  };
11710
13268
  var isWithin2 = (basePath, candidatePath) => {
11711
- const relative = path14.relative(basePath, candidatePath);
11712
- return relative === "" || !relative.startsWith("..") && !path14.isAbsolute(relative);
13269
+ const relative = path17.relative(basePath, candidatePath);
13270
+ return relative === "" || !relative.startsWith("..") && !path17.isAbsolute(relative);
11713
13271
  };
11714
13272
  var resolveShellCwd = (state, requestedCwd) => {
11715
13273
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
11716
13274
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
11717
13275
  if (!requestedCwd) return workingDir;
11718
- const resolved = path14.resolve(workingDir, requestedCwd);
13276
+ const resolved = path17.resolve(workingDir, requestedCwd);
11719
13277
  if (!isWithin2(rootDir, resolved)) {
11720
13278
  return null;
11721
13279
  }
@@ -11750,7 +13308,7 @@ var parseShellOutputRequest = (params) => {
11750
13308
  if (!taskId) {
11751
13309
  return {
11752
13310
  error: {
11753
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13311
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11754
13312
  message: "task_id is required"
11755
13313
  }
11756
13314
  };
@@ -11758,7 +13316,7 @@ var parseShellOutputRequest = (params) => {
11758
13316
  if (params?.stream !== "stdout" && params?.stream !== "stderr") {
11759
13317
  return {
11760
13318
  error: {
11761
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13319
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11762
13320
  message: "stream must be stdout or stderr"
11763
13321
  }
11764
13322
  };
@@ -11766,7 +13324,7 @@ var parseShellOutputRequest = (params) => {
11766
13324
  if (params.line_number !== void 0 && (params.offset !== void 0 || params.limit !== void 0)) {
11767
13325
  return {
11768
13326
  error: {
11769
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13327
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11770
13328
  message: "line_number cannot be combined with offset or limit"
11771
13329
  }
11772
13330
  };
@@ -11774,7 +13332,7 @@ var parseShellOutputRequest = (params) => {
11774
13332
  if (params.line_number === void 0 && (params.char_offset !== void 0 || params.char_limit !== void 0)) {
11775
13333
  return {
11776
13334
  error: {
11777
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13335
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11778
13336
  message: "char_offset/char_limit require line_number"
11779
13337
  }
11780
13338
  };
@@ -11782,7 +13340,7 @@ var parseShellOutputRequest = (params) => {
11782
13340
  if (params.offset !== void 0 && (!Number.isFinite(params.offset) || params.offset < 0)) {
11783
13341
  return {
11784
13342
  error: {
11785
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13343
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11786
13344
  message: "offset must be a non-negative number"
11787
13345
  }
11788
13346
  };
@@ -11790,7 +13348,7 @@ var parseShellOutputRequest = (params) => {
11790
13348
  if (params.limit !== void 0 && (!Number.isFinite(params.limit) || params.limit <= 0)) {
11791
13349
  return {
11792
13350
  error: {
11793
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13351
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11794
13352
  message: "limit must be a positive number"
11795
13353
  }
11796
13354
  };
@@ -11798,7 +13356,7 @@ var parseShellOutputRequest = (params) => {
11798
13356
  if (params.line_number !== void 0 && (!Number.isFinite(params.line_number) || params.line_number <= 0)) {
11799
13357
  return {
11800
13358
  error: {
11801
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13359
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11802
13360
  message: "line_number must be a positive number"
11803
13361
  }
11804
13362
  };
@@ -11806,7 +13364,7 @@ var parseShellOutputRequest = (params) => {
11806
13364
  if (params.char_offset !== void 0 && (!Number.isFinite(params.char_offset) || params.char_offset < 0)) {
11807
13365
  return {
11808
13366
  error: {
11809
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13367
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11810
13368
  message: "char_offset must be a non-negative number"
11811
13369
  }
11812
13370
  };
@@ -11814,7 +13372,7 @@ var parseShellOutputRequest = (params) => {
11814
13372
  if (params.char_limit !== void 0 && (!Number.isFinite(params.char_limit) || params.char_limit <= 0)) {
11815
13373
  return {
11816
13374
  error: {
11817
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13375
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11818
13376
  message: "char_limit must be a positive number"
11819
13377
  }
11820
13378
  };
@@ -11868,7 +13426,7 @@ var parseTaskId = (value) => {
11868
13426
  var toTaskRpcError = (error) => {
11869
13427
  if (!(error instanceof TaskManagerError)) {
11870
13428
  return {
11871
- code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
13429
+ code: RPC_ERROR_CODE6.RUNTIME_INTERNAL,
11872
13430
  message: String(error)
11873
13431
  };
11874
13432
  }
@@ -11877,17 +13435,17 @@ var toTaskRpcError = (error) => {
11877
13435
  case "invalid_task_id":
11878
13436
  case "unsupported_workspace_mode":
11879
13437
  return {
11880
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13438
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11881
13439
  message: error.message
11882
13440
  };
11883
13441
  case "manager_shutting_down":
11884
13442
  return {
11885
- code: RPC_ERROR_CODE5.RUNTIME_BUSY,
13443
+ code: RPC_ERROR_CODE6.RUNTIME_BUSY,
11886
13444
  message: error.message
11887
13445
  };
11888
13446
  default:
11889
13447
  return {
11890
- code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
13448
+ code: RPC_ERROR_CODE6.RUNTIME_INTERNAL,
11891
13449
  message: error.message
11892
13450
  };
11893
13451
  }
@@ -11911,7 +13469,7 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
11911
13469
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
11912
13470
  return {
11913
13471
  error: {
11914
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13472
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11915
13473
  message: "timeout_seconds must be a positive number"
11916
13474
  }
11917
13475
  };
@@ -11925,7 +13483,7 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
11925
13483
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
11926
13484
  return {
11927
13485
  error: {
11928
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13486
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11929
13487
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
11930
13488
  }
11931
13489
  };
@@ -11939,7 +13497,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
11939
13497
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
11940
13498
  return {
11941
13499
  error: {
11942
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13500
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11943
13501
  message: "wait_timeout_seconds must be a positive number"
11944
13502
  }
11945
13503
  };
@@ -11947,7 +13505,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
11947
13505
  if (requestedTimeout > MAX_TIMEOUT_SECONDS) {
11948
13506
  return {
11949
13507
  error: {
11950
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13508
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11951
13509
  message: `wait_timeout_seconds must be ${MAX_TIMEOUT_SECONDS} seconds or less`
11952
13510
  }
11953
13511
  };
@@ -11962,7 +13520,7 @@ var parseShellStartRequest = (state, params, options) => {
11962
13520
  if (!command) {
11963
13521
  return {
11964
13522
  error: {
11965
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13523
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11966
13524
  message: "command is required"
11967
13525
  }
11968
13526
  };
@@ -11978,7 +13536,7 @@ var parseShellStartRequest = (state, params, options) => {
11978
13536
  if (!cwd) {
11979
13537
  return {
11980
13538
  error: {
11981
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13539
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11982
13540
  message: "cwd is outside sandbox root"
11983
13541
  }
11984
13542
  };
@@ -12073,7 +13631,7 @@ var createShellHandlers = ({
12073
13631
  const requestedLimit = params?.limit;
12074
13632
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
12075
13633
  sendError(id, {
12076
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13634
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
12077
13635
  message: "limit must be a positive number"
12078
13636
  });
12079
13637
  return;
@@ -12091,7 +13649,7 @@ var createShellHandlers = ({
12091
13649
  const taskId = parseTaskId(params?.task_id);
12092
13650
  if (!taskId) {
12093
13651
  sendError(id, {
12094
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13652
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
12095
13653
  message: "task_id is required"
12096
13654
  });
12097
13655
  return;
@@ -12119,7 +13677,7 @@ var createShellHandlers = ({
12119
13677
  );
12120
13678
  if (!cacheId && liveContent === null && !isTerminalTaskState(task.state)) {
12121
13679
  sendError(id, {
12122
- code: RPC_ERROR_CODE5.RUNTIME_BUSY,
13680
+ code: RPC_ERROR_CODE6.RUNTIME_BUSY,
12123
13681
  message: `shell output is not retained yet for running task: ${parsed.taskId}`
12124
13682
  });
12125
13683
  return;
@@ -12156,7 +13714,7 @@ var createShellHandlers = ({
12156
13714
  const taskId = parseTaskId(params?.task_id);
12157
13715
  if (!taskId) {
12158
13716
  sendError(id, {
12159
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13717
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
12160
13718
  message: "task_id is required"
12161
13719
  });
12162
13720
  return;
@@ -12240,7 +13798,7 @@ var createShellHandlers = ({
12240
13798
  const taskId = parseTaskId(params?.task_id);
12241
13799
  if (!taskId) {
12242
13800
  sendError(id, {
12243
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13801
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
12244
13802
  message: "task_id is required"
12245
13803
  });
12246
13804
  return;
@@ -12250,7 +13808,7 @@ var createShellHandlers = ({
12250
13808
  const waits = activeShellWaits.get(taskId);
12251
13809
  if (!waits || waits.size === 0) {
12252
13810
  sendError(id, {
12253
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13811
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
12254
13812
  message: `no active shell.wait to detach for task: ${taskId}`
12255
13813
  });
12256
13814
  return;
@@ -12272,7 +13830,7 @@ var createShellHandlers = ({
12272
13830
  const taskId = parseTaskId(params?.task_id);
12273
13831
  if (!taskId) {
12274
13832
  sendError(id, {
12275
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13833
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
12276
13834
  message: "task_id is required"
12277
13835
  });
12278
13836
  return;
@@ -12300,16 +13858,16 @@ var createShellHandlers = ({
12300
13858
  };
12301
13859
 
12302
13860
  // src/rpc/skills.ts
12303
- import path15 from "path";
13861
+ import path18 from "path";
12304
13862
  import {
12305
- RPC_ERROR_CODE as RPC_ERROR_CODE6
13863
+ RPC_ERROR_CODE as RPC_ERROR_CODE7
12306
13864
  } from "@codelia/protocol";
12307
13865
  var createSkillsHandlers = ({
12308
13866
  state,
12309
13867
  log: log2
12310
13868
  }) => {
12311
13869
  const handleSkillsList = async (id, params) => {
12312
- const requestedCwd = params?.cwd ? path15.resolve(params.cwd) : void 0;
13870
+ const requestedCwd = params?.cwd ? path18.resolve(params.cwd) : void 0;
12313
13871
  const workingDir = requestedCwd ?? state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
12314
13872
  const forceReload = params?.force_reload ?? false;
12315
13873
  if (!forceReload) {
@@ -12333,7 +13891,7 @@ var createSkillsHandlers = ({
12333
13891
  });
12334
13892
  } catch (error) {
12335
13893
  sendError(id, {
12336
- code: RPC_ERROR_CODE6.RUNTIME_INTERNAL,
13894
+ code: RPC_ERROR_CODE7.RUNTIME_INTERNAL,
12337
13895
  message: `skills resolver init failed: ${String(error)}`
12338
13896
  });
12339
13897
  return;
@@ -12355,7 +13913,7 @@ var createSkillsHandlers = ({
12355
13913
  } catch (error) {
12356
13914
  log2(`skills.list error: ${String(error)}`);
12357
13915
  sendError(id, {
12358
- code: RPC_ERROR_CODE6.RUNTIME_INTERNAL,
13916
+ code: RPC_ERROR_CODE7.RUNTIME_INTERNAL,
12359
13917
  message: `skills list failed: ${String(error)}`
12360
13918
  });
12361
13919
  }
@@ -12364,15 +13922,15 @@ var createSkillsHandlers = ({
12364
13922
  };
12365
13923
 
12366
13924
  // src/rpc/task.ts
12367
- import path16 from "path";
13925
+ import path19 from "path";
12368
13926
  import {
12369
- RPC_ERROR_CODE as RPC_ERROR_CODE8
13927
+ RPC_ERROR_CODE as RPC_ERROR_CODE9
12370
13928
  } from "@codelia/protocol";
12371
13929
  import { ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl4 } from "@codelia/storage";
12372
13930
 
12373
13931
  // src/rpc/tool.ts
12374
13932
  import {
12375
- RPC_ERROR_CODE as RPC_ERROR_CODE7
13933
+ RPC_ERROR_CODE as RPC_ERROR_CODE8
12376
13934
  } from "@codelia/protocol";
12377
13935
  var normalizeToolResult = (result) => {
12378
13936
  switch (result.type) {
@@ -12409,7 +13967,7 @@ var createToolHandlers = ({
12409
13967
  const toolName = params?.name;
12410
13968
  if (!toolName) {
12411
13969
  sendError(id, {
12412
- code: RPC_ERROR_CODE7.INVALID_PARAMS,
13970
+ code: RPC_ERROR_CODE8.INVALID_PARAMS,
12413
13971
  message: "tool name is required"
12414
13972
  });
12415
13973
  return;
@@ -12420,7 +13978,7 @@ var createToolHandlers = ({
12420
13978
  const tool = state.tools?.find((entry) => entry.name === toolName);
12421
13979
  if (!tool) {
12422
13980
  sendError(id, {
12423
- code: RPC_ERROR_CODE7.INVALID_PARAMS,
13981
+ code: RPC_ERROR_CODE8.INVALID_PARAMS,
12424
13982
  message: `unknown tool: ${toolName}`
12425
13983
  });
12426
13984
  return;
@@ -12437,7 +13995,7 @@ var createToolHandlers = ({
12437
13995
  sendResult(id, response);
12438
13996
  } catch (error) {
12439
13997
  sendError(id, {
12440
- code: RPC_ERROR_CODE7.RUNTIME_INTERNAL,
13998
+ code: RPC_ERROR_CODE8.RUNTIME_INTERNAL,
12441
13999
  message: `tool call failed: ${String(error)}`
12442
14000
  });
12443
14001
  }
@@ -12461,8 +14019,8 @@ var truncateCommandPreview2 = (value) => {
12461
14019
  };
12462
14020
  var toShellKeyBase2 = (label) => {
12463
14021
  const source = label?.trim() ?? "";
12464
- const slug = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
12465
- return slug || "shell";
14022
+ const slug2 = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
14023
+ return slug2 || "shell";
12466
14024
  };
12467
14025
  var compactTaskId2 = (taskId) => {
12468
14026
  const compact = taskId.toLowerCase().replaceAll(/[^a-z0-9]+/g, "");
@@ -12480,14 +14038,14 @@ var getPublicTaskKey = (task) => {
12480
14038
  return suffix ? `${toShellKeyBase2(task.label)}-${suffix}` : void 0;
12481
14039
  };
12482
14040
  var isWithin3 = (basePath, candidatePath) => {
12483
- const relative = path16.relative(basePath, candidatePath);
12484
- return relative === "" || !relative.startsWith("..") && !path16.isAbsolute(relative);
14041
+ const relative = path19.relative(basePath, candidatePath);
14042
+ return relative === "" || !relative.startsWith("..") && !path19.isAbsolute(relative);
12485
14043
  };
12486
14044
  var resolveShellCwd2 = (state, requestedCwd) => {
12487
14045
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
12488
14046
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
12489
14047
  if (!requestedCwd) return workingDir;
12490
- const resolved = path16.resolve(workingDir, requestedCwd);
14048
+ const resolved = path19.resolve(workingDir, requestedCwd);
12491
14049
  if (!isWithin3(rootDir, resolved)) {
12492
14050
  return null;
12493
14051
  }
@@ -12500,7 +14058,7 @@ var parseTaskId2 = (value) => {
12500
14058
  var toTaskRpcError2 = (error) => {
12501
14059
  if (!(error instanceof TaskManagerError)) {
12502
14060
  return {
12503
- code: RPC_ERROR_CODE8.RUNTIME_INTERNAL,
14061
+ code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
12504
14062
  message: String(error)
12505
14063
  };
12506
14064
  }
@@ -12509,17 +14067,17 @@ var toTaskRpcError2 = (error) => {
12509
14067
  case "invalid_task_id":
12510
14068
  case "unsupported_workspace_mode":
12511
14069
  return {
12512
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14070
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12513
14071
  message: error.message
12514
14072
  };
12515
14073
  case "manager_shutting_down":
12516
14074
  return {
12517
- code: RPC_ERROR_CODE8.RUNTIME_BUSY,
14075
+ code: RPC_ERROR_CODE9.RUNTIME_BUSY,
12518
14076
  message: error.message
12519
14077
  };
12520
14078
  default:
12521
14079
  return {
12522
- code: RPC_ERROR_CODE8.RUNTIME_INTERNAL,
14080
+ code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
12523
14081
  message: error.message
12524
14082
  };
12525
14083
  }
@@ -12570,7 +14128,7 @@ var resolveShellTimeoutSeconds3 = (requestedTimeout, background) => {
12570
14128
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
12571
14129
  return {
12572
14130
  error: {
12573
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14131
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12574
14132
  message: "timeout_seconds must be a positive number"
12575
14133
  }
12576
14134
  };
@@ -12584,7 +14142,7 @@ var resolveShellTimeoutSeconds3 = (requestedTimeout, background) => {
12584
14142
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
12585
14143
  return {
12586
14144
  error: {
12587
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14145
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12588
14146
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
12589
14147
  }
12590
14148
  };
@@ -12599,7 +14157,7 @@ var parseShellSpawnRequest = (state, params, options) => {
12599
14157
  if (!command) {
12600
14158
  return {
12601
14159
  error: {
12602
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14160
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12603
14161
  message: "command is required for shell tasks"
12604
14162
  }
12605
14163
  };
@@ -12615,7 +14173,7 @@ var parseShellSpawnRequest = (state, params, options) => {
12615
14173
  if (!cwd) {
12616
14174
  return {
12617
14175
  error: {
12618
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14176
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12619
14177
  message: "cwd is outside sandbox root"
12620
14178
  }
12621
14179
  };
@@ -12646,7 +14204,7 @@ var createTaskHandlers = ({
12646
14204
  const handleTaskSpawn = async (id, params) => {
12647
14205
  if (!params || !isTaskKind(params.kind)) {
12648
14206
  sendError(id, {
12649
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14207
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12650
14208
  message: "kind must be shell or subagent"
12651
14209
  });
12652
14210
  return;
@@ -12674,7 +14232,7 @@ var createTaskHandlers = ({
12674
14232
  }
12675
14233
  if (params.kind !== "shell") {
12676
14234
  sendError(id, {
12677
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14235
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12678
14236
  message: `task kind ${params.kind} is not supported yet.`
12679
14237
  });
12680
14238
  return;
@@ -12718,21 +14276,21 @@ var createTaskHandlers = ({
12718
14276
  const requestedLimit = params?.limit;
12719
14277
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
12720
14278
  sendError(id, {
12721
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14279
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12722
14280
  message: "limit must be a positive number"
12723
14281
  });
12724
14282
  return;
12725
14283
  }
12726
14284
  if (params?.kind !== void 0 && !isTaskKind(params.kind)) {
12727
14285
  sendError(id, {
12728
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14286
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12729
14287
  message: "kind must be shell or subagent"
12730
14288
  });
12731
14289
  return;
12732
14290
  }
12733
14291
  if (params?.state !== void 0 && !isTaskState(params.state)) {
12734
14292
  sendError(id, {
12735
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14293
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12736
14294
  message: "invalid task state"
12737
14295
  });
12738
14296
  return;
@@ -12752,7 +14310,7 @@ var createTaskHandlers = ({
12752
14310
  const taskId = parseTaskId2(params?.task_id);
12753
14311
  if (!taskId) {
12754
14312
  sendError(id, {
12755
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14313
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12756
14314
  message: "task_id is required"
12757
14315
  });
12758
14316
  return;
@@ -12776,7 +14334,7 @@ var createTaskHandlers = ({
12776
14334
  const taskId = parseTaskId2(params?.task_id);
12777
14335
  if (!taskId) {
12778
14336
  sendError(id, {
12779
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14337
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12780
14338
  message: "task_id is required"
12781
14339
  });
12782
14340
  return;
@@ -12794,7 +14352,7 @@ var createTaskHandlers = ({
12794
14352
  const taskId = parseTaskId2(params?.task_id);
12795
14353
  if (!taskId) {
12796
14354
  sendError(id, {
12797
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14355
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12798
14356
  message: "task_id is required"
12799
14357
  });
12800
14358
  return;
@@ -12814,7 +14372,7 @@ var createTaskHandlers = ({
12814
14372
  const taskId = parseTaskId2(params?.task_id);
12815
14373
  if (!taskId) {
12816
14374
  sendError(id, {
12817
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14375
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12818
14376
  message: "task_id is required"
12819
14377
  });
12820
14378
  return;
@@ -12844,6 +14402,114 @@ var createTaskHandlers = ({
12844
14402
  };
12845
14403
  };
12846
14404
 
14405
+ // src/rpc/auth.ts
14406
+ import {
14407
+ RPC_ERROR_CODE as RPC_ERROR_CODE10
14408
+ } from "@codelia/protocol";
14409
+ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
14410
+ if (state.activeRunId) {
14411
+ sendError(id, {
14412
+ code: RPC_ERROR_CODE10.RUNTIME_BUSY,
14413
+ message: "runtime busy"
14414
+ });
14415
+ return;
14416
+ }
14417
+ const provider = params?.provider;
14418
+ if (provider !== void 0 && (typeof provider !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(provider))) {
14419
+ sendError(id, {
14420
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
14421
+ message: "invalid logout provider name"
14422
+ });
14423
+ return;
14424
+ }
14425
+ try {
14426
+ const hostAuth = state.effectiveEnvironment.auth.model === "host";
14427
+ const config = provider ? await resolveEnvironmentModelConfig(
14428
+ state,
14429
+ state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0
14430
+ ) : void 0;
14431
+ const currentProvider = state.currentModelProvider ?? state.sessionModelOverride?.provider ?? config?.provider ?? (hostAuth ? void 0 : "openai");
14432
+ const affectsCurrent = provider === void 0 || provider === currentProvider;
14433
+ const clearSession = (params?.clear_session ?? true) && affectsCurrent;
14434
+ if (hostAuth) {
14435
+ const credentials = state.effectiveEnvironment.adapters.credentialProvider;
14436
+ if (provider ? !credentials?.clearProviderAuth : !credentials?.clearAuth) {
14437
+ sendError(id, {
14438
+ code: RPC_ERROR_CODE10.RUNTIME_INTERNAL,
14439
+ message: provider ? "host auth provider does not support scoped logout" : "host auth provider does not support logout"
14440
+ });
14441
+ return;
14442
+ }
14443
+ if (provider) await credentials?.clearProviderAuth?.(provider);
14444
+ else await credentials?.clearAuth?.();
14445
+ } else {
14446
+ const store = new AuthStore();
14447
+ if (provider) {
14448
+ const auth = await store.load();
14449
+ if (!Object.hasOwn(auth.providers, provider) && !configuredProviders(config?.providers).includes(provider)) {
14450
+ sendError(id, {
14451
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
14452
+ message: `unknown logout provider: ${provider}`
14453
+ });
14454
+ return;
14455
+ }
14456
+ }
14457
+ if (!state.uiCapabilities?.supports_confirm) {
14458
+ sendError(id, {
14459
+ code: RPC_ERROR_CODE10.RUNTIME_INTERNAL,
14460
+ message: "UI confirmation is required for logout"
14461
+ });
14462
+ return;
14463
+ }
14464
+ const confirm = await requestUiConfirm(state, {
14465
+ title: provider ? `Log out of ${provider}` : "Confirm logout",
14466
+ message: provider ? `This clears saved credentials for ${provider} only.${clearSession ? " The current session will be reset." : " The current session will be kept."} Continue?` : `This clears all local auth credentials.${clearSession ? " The current session will be reset." : " The current session will be kept."} Continue?`,
14467
+ confirm_label: "Yes",
14468
+ cancel_label: "No",
14469
+ danger_level: "danger",
14470
+ allow_remember: false,
14471
+ allow_reason: false
14472
+ });
14473
+ if (!confirm?.ok) {
14474
+ sendResult(id, {
14475
+ ok: false,
14476
+ auth_cleared: false,
14477
+ session_cleared: false,
14478
+ cancelled: true,
14479
+ ...provider ? { provider } : {}
14480
+ });
14481
+ return;
14482
+ }
14483
+ if (provider) {
14484
+ const auth = await store.load();
14485
+ delete auth.providers[provider];
14486
+ await store.save(auth);
14487
+ } else await store.save({ version: 1, providers: {} });
14488
+ }
14489
+ if (affectsCurrent) state.agent = null;
14490
+ if (clearSession) {
14491
+ state.sessionId = null;
14492
+ state.sessionMeta = null;
14493
+ state.sessionAppend = null;
14494
+ state.sessionModelOverride = null;
14495
+ }
14496
+ sendResult(id, {
14497
+ ok: true,
14498
+ auth_cleared: true,
14499
+ session_cleared: clearSession,
14500
+ ...provider ? { provider } : {}
14501
+ });
14502
+ log2(
14503
+ `auth.logout provider=${provider ?? "all"} session_cleared=${clearSession}`
14504
+ );
14505
+ } catch {
14506
+ sendError(id, {
14507
+ code: RPC_ERROR_CODE10.RUNTIME_INTERNAL,
14508
+ message: "auth logout failed"
14509
+ });
14510
+ }
14511
+ };
14512
+
12847
14513
  // src/rpc/handlers.ts
12848
14514
  var SUPPORTED_TUI_THEMES = /* @__PURE__ */ new Set([
12849
14515
  "codelia",
@@ -12870,6 +14536,7 @@ var createRuntimeHandlers = ({
12870
14536
  subagents
12871
14537
  }) => {
12872
14538
  const environment = state.effectiveEnvironment;
14539
+ const imageHandlers = createImageHandlers(state);
12873
14540
  const sessionStateStore = injectedSessionStateStore ?? environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new SessionStateStoreImpl({
12874
14541
  onError: (error, context) => {
12875
14542
  log2(
@@ -12927,9 +14594,14 @@ var createRuntimeHandlers = ({
12927
14594
  if (authResolver.hasAnyAvailableAuth()) {
12928
14595
  return;
12929
14596
  }
14597
+ const onboardingConfig = await resolveEnvironmentModelConfig(
14598
+ state,
14599
+ state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0
14600
+ );
14601
+ const providers = configuredProviders(onboardingConfig.providers);
12930
14602
  const providerPick = await requestUiPick(state, {
12931
14603
  title: "Let's set up your provider to get started.",
12932
- items: SUPPORTED_PROVIDERS.map((provider2) => ({
14604
+ items: providers.map((provider2) => ({
12933
14605
  id: provider2,
12934
14606
  label: provider2,
12935
14607
  detail: provider2 === "openai" ? "OAuth (ChatGPT Plus/Pro) or API key" : provider2 === "openrouter" ? "API key (OpenRouter)" : provider2 === "moonshot" ? "API key (Moonshot)" : provider2 === "zai" ? "API key (Z.ai)" : provider2 === "xai" ? "API key (xAI)" : "API key"
@@ -12937,7 +14609,7 @@ var createRuntimeHandlers = ({
12937
14609
  multi: false
12938
14610
  });
12939
14611
  const pickedProvider = providerPick?.ids?.[0];
12940
- if (!pickedProvider || !SUPPORTED_PROVIDERS.includes(pickedProvider)) {
14612
+ if (!pickedProvider || !providers.includes(pickedProvider)) {
12941
14613
  log2("startup onboarding skipped (provider not selected)");
12942
14614
  return;
12943
14615
  }
@@ -13089,10 +14761,22 @@ var createRuntimeHandlers = ({
13089
14761
  const mcpEnabled = environment2.tools.mcp === "from-config";
13090
14762
  const skillsEnabled = environment2.context.skills === "from-config";
13091
14763
  const themeSetEnabled = isTuiLocalEnvironment(environment2) && environment2.config.source !== "disabled";
14764
+ let modelProviders = [...SUPPORTED_PROVIDERS];
14765
+ try {
14766
+ const config = await resolveEnvironmentModelConfig(
14767
+ state,
14768
+ state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0
14769
+ );
14770
+ modelProviders = configuredProviders(config.providers);
14771
+ } catch (error) {
14772
+ log2(`initialize provider config load failed: ${String(error)}`);
14773
+ }
13092
14774
  const result = {
14775
+ model_providers: modelProviders,
13093
14776
  protocol_version: PROTOCOL_VERSION,
13094
14777
  server: { name: SERVER_NAME, version: SERVER_VERSION },
13095
14778
  server_capabilities: {
14779
+ supports_scoped_logout: environment2.auth.model === "runtime-default" || Boolean(environment2.adapters.credentialProvider?.clearProviderAuth),
13096
14780
  supports_run_cancel: true,
13097
14781
  supports_run_diagnostics: true,
13098
14782
  supports_shell_exec: processEnabled,
@@ -13107,6 +14791,7 @@ var createRuntimeHandlers = ({
13107
14791
  supports_context_inspect: true,
13108
14792
  supports_tool_call: true,
13109
14793
  supports_theme_set: themeSetEnabled,
14794
+ supports_image_generation: isTuiLocalEnvironment(environment2),
13110
14795
  supports_permission_preflight_events: true
13111
14796
  },
13112
14797
  ...resolvedTheme ? { tui: { theme: resolvedTheme } } : {}
@@ -13126,7 +14811,7 @@ var createRuntimeHandlers = ({
13126
14811
  const handleThemeSet = async (id, params) => {
13127
14812
  if (state.activeRunId) {
13128
14813
  sendError(id, {
13129
- code: RPC_ERROR_CODE9.RUNTIME_BUSY,
14814
+ code: RPC_ERROR_CODE11.RUNTIME_BUSY,
13130
14815
  message: "runtime busy"
13131
14816
  });
13132
14817
  return;
@@ -13134,14 +14819,14 @@ var createRuntimeHandlers = ({
13134
14819
  const name = params?.name?.trim().toLowerCase();
13135
14820
  if (!name) {
13136
14821
  sendError(id, {
13137
- code: RPC_ERROR_CODE9.INVALID_PARAMS,
14822
+ code: RPC_ERROR_CODE11.INVALID_PARAMS,
13138
14823
  message: "theme name is required"
13139
14824
  });
13140
14825
  return;
13141
14826
  }
13142
14827
  if (!SUPPORTED_TUI_THEMES.has(name)) {
13143
14828
  sendError(id, {
13144
- code: RPC_ERROR_CODE9.INVALID_PARAMS,
14829
+ code: RPC_ERROR_CODE11.INVALID_PARAMS,
13145
14830
  message: `unsupported theme: ${name}`
13146
14831
  });
13147
14832
  return;
@@ -13158,104 +14843,18 @@ var createRuntimeHandlers = ({
13158
14843
  log2(`theme.set ${name} scope=${target.scope} path=${target.path}`);
13159
14844
  } catch (error) {
13160
14845
  sendError(id, {
13161
- code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
14846
+ code: RPC_ERROR_CODE11.RUNTIME_INTERNAL,
13162
14847
  message: String(error)
13163
14848
  });
13164
14849
  }
13165
14850
  };
13166
- const handleAuthLogout = async (id, params) => {
13167
- if (state.activeRunId) {
13168
- sendError(id, {
13169
- code: RPC_ERROR_CODE9.RUNTIME_BUSY,
13170
- message: "runtime busy"
13171
- });
13172
- return;
13173
- }
13174
- const clearSession = params?.clear_session ?? true;
13175
- try {
13176
- if (state.effectiveEnvironment.auth.model === "host") {
13177
- const clearAuth = state.effectiveEnvironment.adapters.credentialProvider?.clearAuth;
13178
- if (!clearAuth) {
13179
- sendError(id, {
13180
- code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
13181
- message: "host auth provider does not support logout"
13182
- });
13183
- return;
13184
- }
13185
- await clearAuth();
13186
- state.agent = null;
13187
- if (clearSession) {
13188
- state.sessionId = null;
13189
- state.sessionMeta = null;
13190
- state.sessionAppend = null;
13191
- state.sessionModelOverride = null;
13192
- }
13193
- sendResult(id, {
13194
- ok: true,
13195
- auth_cleared: true,
13196
- session_cleared: clearSession
13197
- });
13198
- log2(`auth.logout host session_cleared=${clearSession}`);
13199
- return;
13200
- }
13201
- const supportsConfirm = !!state.uiCapabilities?.supports_confirm;
13202
- if (!supportsConfirm) {
13203
- sendError(id, {
13204
- code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
13205
- message: "UI confirmation is required for logout"
13206
- });
13207
- return;
13208
- }
13209
- const confirm = await requestUiConfirm(state, {
13210
- title: "Confirm logout",
13211
- message: "This clears local auth credentials and resets the current session. Continue?",
13212
- confirm_label: "Yes",
13213
- cancel_label: "No",
13214
- danger_level: "danger",
13215
- allow_remember: false,
13216
- allow_reason: false
13217
- });
13218
- if (!confirm?.ok) {
13219
- const result2 = {
13220
- ok: false,
13221
- auth_cleared: false,
13222
- session_cleared: false,
13223
- cancelled: true
13224
- };
13225
- sendResult(id, result2);
13226
- log2("auth.logout cancelled");
13227
- return;
13228
- }
13229
- const store = new AuthStore();
13230
- const cleared = { version: 1, providers: {} };
13231
- await store.save(cleared);
13232
- state.agent = null;
13233
- if (clearSession) {
13234
- state.sessionId = null;
13235
- state.sessionMeta = null;
13236
- state.sessionAppend = null;
13237
- state.sessionModelOverride = null;
13238
- }
13239
- const result = {
13240
- ok: true,
13241
- auth_cleared: true,
13242
- session_cleared: clearSession
13243
- };
13244
- sendResult(id, result);
13245
- log2(`auth.logout session_cleared=${clearSession}`);
13246
- } catch (error) {
13247
- sendError(id, {
13248
- code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
13249
- message: `auth logout failed: ${String(error)}`
13250
- });
13251
- }
13252
- };
14851
+ const handleAuthLogout = createAuthLogoutHandler({ state, log: log2 });
13253
14852
  const handleRequest = async (req) => {
13254
14853
  const mcpEnabled = state.effectiveEnvironment.tools.mcp === "from-config";
13255
14854
  const skillsEnabled = state.effectiveEnvironment.context.skills === "from-config";
13256
14855
  const themeSetEnabled = isTuiLocalEnvironment(state.effectiveEnvironment) && state.effectiveEnvironment.config.source !== "disabled";
13257
14856
  const rejectDisabled = (message) => sendError(req.id, {
13258
- code: RPC_ERROR_CODE9.INVALID_PARAMS,
14857
+ code: RPC_ERROR_CODE11.INVALID_PARAMS,
13259
14858
  message
13260
14859
  });
13261
14860
  switch (req.method) {
@@ -13273,6 +14872,12 @@ var createRuntimeHandlers = ({
13273
14872
  return handleAuthLogout(req.id, req.params);
13274
14873
  case "model.list":
13275
14874
  return handleModelList(req.id, req.params);
14875
+ case "image.model.get":
14876
+ return imageHandlers.handle(req.id, "get", req.params);
14877
+ case "image.model.configure":
14878
+ return imageHandlers.handle(req.id, "configure", req.params);
14879
+ case "image.artifact.get":
14880
+ return imageHandlers.handle(req.id, "artifact", req.params);
13276
14881
  case "model.set":
13277
14882
  return handleModelSet(req.id, req.params);
13278
14883
  case "tool.call":
@@ -13395,7 +15000,7 @@ var createRuntimeHandlers = ({
13395
15000
  return handleThemeSet(req.id, req.params);
13396
15001
  default:
13397
15002
  return sendError(req.id, {
13398
- code: RPC_ERROR_CODE9.METHOD_NOT_FOUND,
15003
+ code: RPC_ERROR_CODE11.METHOD_NOT_FOUND,
13399
15004
  message: "method not found"
13400
15005
  });
13401
15006
  }
@@ -13426,12 +15031,12 @@ var createRuntimeHandlers = ({
13426
15031
  // src/subagents/process-executor.ts
13427
15032
  import { spawn as spawn5 } from "child_process";
13428
15033
  import { existsSync } from "fs";
13429
- import path17 from "path";
15034
+ import path20 from "path";
13430
15035
  import { fileURLToPath } from "url";
13431
- var moduleDir = typeof __dirname === "string" ? __dirname : path17.dirname(fileURLToPath(import.meta.url));
13432
- var defaultEntry = path17.join(
15036
+ var moduleDir = typeof __dirname === "string" ? __dirname : path20.dirname(fileURLToPath(import.meta.url));
15037
+ var defaultEntry = path20.join(
13433
15038
  moduleDir,
13434
- existsSync(path17.join(moduleDir, "child-entry.ts")) ? "child-entry.ts" : "subagents/child-entry.js"
15039
+ existsSync(path20.join(moduleDir, "child-entry.ts")) ? "child-entry.ts" : "subagents/child-entry.js"
13435
15040
  );
13436
15041
  var createProcessSubagentFactory = (options = {}) => ({
13437
15042
  isAvailable: () => ["darwin", "linux"].includes(process.platform) && existsSync(options.entry ?? defaultEntry),