@codelia/runtime 0.1.81 → 0.1.83

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,17 +13,23 @@ import {
12
13
  appendPermissionAllowRules,
13
14
  appendReadMetadata,
14
15
  assertExpectedContentHash,
16
+ assertUltrafastAuth,
17
+ buildConfiguredModelRegistry,
15
18
  buildSystemPermissions,
16
19
  clipUtf8,
20
+ configuredModelSpecs,
21
+ configuredProviders,
17
22
  createCommunicationTools,
18
23
  createRuntimeModel,
19
24
  createSubagentWriteTools,
20
25
  debugLog,
26
+ effectiveFastMode,
21
27
  expectedContentHashSchema,
22
28
  formatAgentMessages,
23
29
  generatePkce,
24
30
  generateState,
25
31
  getProcessIdentity,
32
+ getResponsesProvider,
26
33
  isDebugEnabled,
27
34
  isProcessEnabled,
28
35
  isTerminalTaskState,
@@ -38,8 +45,9 @@ import {
38
45
  requestUiConfirm,
39
46
  requestUiPick,
40
47
  requestUiPrompt,
48
+ resolveConfiguredReasoning,
41
49
  resolveExecutionEnvironmentConfig,
42
- resolveFastMode,
50
+ resolveImageGenerationConfig,
43
51
  resolveMcpServers,
44
52
  resolveModelConfig,
45
53
  resolvePermissionsConfig,
@@ -56,6 +64,7 @@ import {
56
64
  sendResult,
57
65
  sendRunContext,
58
66
  sendRunDiagnostics,
67
+ sendRunMetrics,
59
68
  sendRunStatus,
60
69
  sendRunStatusAsync,
61
70
  shouldAutoOpenOAuthBrowser,
@@ -63,9 +72,10 @@ import {
63
72
  subagentBootstrapSchema,
64
73
  subagentModelSelectionSchema,
65
74
  subagentNameSchema,
75
+ updateImageGeneration,
66
76
  updateModel,
67
77
  updateTuiTheme
68
- } from "./chunk-227ALRI4.js";
78
+ } from "./chunk-A6CO4J5P.js";
69
79
 
70
80
  // src/runtime.ts
71
81
  import {
@@ -77,7 +87,7 @@ import {
77
87
  import {
78
88
  Agent,
79
89
  DEFAULT_MODEL_REGISTRY as DEFAULT_MODEL_REGISTRY2,
80
- ToolPermissionDenied
90
+ ToolPermissionDenied as ToolPermissionDenied2
81
91
  } from "@codelia/core";
82
92
  import { ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl2 } from "@codelia/storage";
83
93
 
@@ -442,6 +452,9 @@ var appendInitialAgentsContext = (systemPrompt, agentsContext) => {
442
452
  ${agentsContext}`;
443
453
  };
444
454
 
455
+ // src/effective-model.ts
456
+ import { isModelFastMode } from "@codelia/shared-types";
457
+
445
458
  // src/environment-services.ts
446
459
  var requireConfigProviderMethod = (method) => new Error(`host config provider does not implement ${method}`);
447
460
  var resolveEnvironmentModelConfig = async (state, workingDir) => {
@@ -586,7 +599,9 @@ var createEnvironmentAuthResolver = async (state, log2) => {
586
599
  getOpenAiAccessToken: provider.getOpenAiAccessToken
587
600
  };
588
601
  }
589
- return AuthResolver.create(state, log2);
602
+ const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0;
603
+ const config = await resolveEnvironmentModelConfig(state, workingDir);
604
+ return AuthResolver.create(state, log2, config.providers);
590
605
  };
591
606
 
592
607
  // src/effective-model.ts
@@ -635,7 +650,7 @@ var readSessionModelOverride = (meta) => {
635
650
  provider,
636
651
  name,
637
652
  ...reasoning ? { reasoning } : {},
638
- ...typeof raw.fast === "boolean" ? { fast: raw.fast } : {}
653
+ ...isModelFastMode(raw.fast) ? { fast: raw.fast } : {}
639
654
  };
640
655
  };
641
656
  var mergeSessionModelOverrideIntoMeta = (meta, override) => {
@@ -1220,6 +1235,1090 @@ ${executionEnvironmentContext}`
1220
1235
  return true;
1221
1236
  };
1222
1237
 
1238
+ // src/image-generation/references.ts
1239
+ import { IMAGE_REFERENCE_MAX_COUNT } from "@codelia/shared-types";
1240
+ import { imageSize } from "image-size";
1241
+ import { z as z2 } from "zod";
1242
+
1243
+ // src/image-generation/http.ts
1244
+ var ImageGenerationError = class extends Error {
1245
+ };
1246
+ async function imageJson(url, init, fetcher = fetch, maxBytes = 12 * 1024 * 1024, timeoutMs = 18e4) {
1247
+ const timeout = AbortSignal.timeout(timeoutMs);
1248
+ const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
1249
+ try {
1250
+ const response = await fetcher(url, { ...init, signal, redirect: "error" });
1251
+ if (!response.ok) {
1252
+ await response.body?.cancel();
1253
+ throw new ImageGenerationError(
1254
+ `Image API request failed (HTTP ${response.status}); no fallback or automatic retry was attempted.`
1255
+ );
1256
+ }
1257
+ if (!response.body || Number(response.headers.get("content-length") ?? 0) > maxBytes) {
1258
+ await response.body?.cancel();
1259
+ throw new ImageGenerationError(
1260
+ "Image API response exceeded the size limit or was empty."
1261
+ );
1262
+ }
1263
+ const reader = response.body.getReader();
1264
+ const chunks = [];
1265
+ let size = 0;
1266
+ const cancelReader = () => {
1267
+ void reader.cancel().catch(() => {
1268
+ });
1269
+ };
1270
+ signal.addEventListener("abort", cancelReader, { once: true });
1271
+ try {
1272
+ while (true) {
1273
+ signal.throwIfAborted();
1274
+ const chunk = await reader.read();
1275
+ signal.throwIfAborted();
1276
+ if (chunk.done) break;
1277
+ size += chunk.value.length;
1278
+ if (size > maxBytes)
1279
+ throw new ImageGenerationError(
1280
+ "Image API response exceeded the size limit."
1281
+ );
1282
+ chunks.push(chunk.value);
1283
+ }
1284
+ } finally {
1285
+ signal.removeEventListener("abort", cancelReader);
1286
+ await reader.cancel().catch(() => {
1287
+ });
1288
+ reader.releaseLock();
1289
+ }
1290
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
1291
+ } catch (error) {
1292
+ if (init.signal?.aborted)
1293
+ throw new ImageGenerationError(
1294
+ "Image request cancelled; the provider may already have charged for generation. No retry was attempted."
1295
+ );
1296
+ if (timeout.aborted)
1297
+ throw new ImageGenerationError(
1298
+ "Image request timed out; the provider may already have charged for generation. No retry was attempted."
1299
+ );
1300
+ if (error instanceof ImageGenerationError) throw error;
1301
+ throw new ImageGenerationError(
1302
+ "Image API transport or response failed; no fallback or automatic retry was attempted."
1303
+ );
1304
+ }
1305
+ }
1306
+
1307
+ // src/image-generation/references.ts
1308
+ var IMAGE_REFERENCE_MAX_BYTES = 8 * 1024 * 1024;
1309
+ var IMAGE_REFERENCE_TOTAL_BYTES = 32 * 1024 * 1024;
1310
+ var imageArtifactId = z2.string().regex(/^codelia-image-[0-9a-f-]{36}$/);
1311
+ var imageSourceSchema = z2.discriminatedUnion("type", [
1312
+ z2.object({
1313
+ type: z2.literal("url"),
1314
+ url: z2.url({ protocol: /^https?$/ }).max(8192).refine((value) => {
1315
+ if (!URL.canParse(value)) return false;
1316
+ const url = new URL(value);
1317
+ return !url.username && !url.password && !url.hash;
1318
+ }, "Image URL must not contain credentials or fragments").describe(
1319
+ "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."
1320
+ )
1321
+ }).strict(),
1322
+ z2.object({
1323
+ type: z2.literal("file"),
1324
+ file_path: z2.string().min(1).max(4096).describe(
1325
+ "Runtime-host image path; sandbox-bounded unless full-access. Original bytes are read after approval."
1326
+ )
1327
+ }).strict(),
1328
+ z2.object({ type: z2.literal("artifact"), artifact_id: imageArtifactId }).strict()
1329
+ ]);
1330
+ function validateImageReference(bytes) {
1331
+ if (!bytes.length || bytes.length > IMAGE_REFERENCE_MAX_BYTES)
1332
+ throw new ImageGenerationError(
1333
+ "Image reference is empty or exceeds 8 MiB; no generation was attempted."
1334
+ );
1335
+ try {
1336
+ const header = Buffer.from(bytes.subarray(0, 12));
1337
+ const png = header.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
1338
+ const jpeg = header[0] === 255 && header[1] === 216 && header[2] === 255;
1339
+ const webp = header.toString("ascii", 0, 4) === "RIFF" && header.toString("ascii", 8, 12) === "WEBP";
1340
+ if (!png && !jpeg && !webp) throw new Error("unsupported signature");
1341
+ const dimensions = imageSize(bytes);
1342
+ const media_type = dimensions.type === "png" ? "image/png" : dimensions.type === "jpg" ? "image/jpeg" : dimensions.type === "webp" ? "image/webp" : null;
1343
+ if (!media_type || !dimensions.width || !dimensions.height || dimensions.width > 4096 || dimensions.height > 4096 || dimensions.width * dimensions.height > 16e6)
1344
+ throw new Error("unsupported image headers");
1345
+ return { type: "bytes", bytes, media_type };
1346
+ } catch {
1347
+ throw new ImageGenerationError(
1348
+ "Image reference must have valid PNG/JPEG/WebP headers, at most 4096 pixels per side and 16 MP; no generation was attempted."
1349
+ );
1350
+ }
1351
+ }
1352
+ function imageReferenceDataUrl(reference) {
1353
+ return `data:${reference.media_type};base64,${Buffer.from(reference.bytes).toString("base64")}`;
1354
+ }
1355
+ async function resolveImageSources(sources, store, readSource, signal) {
1356
+ if (sources.length > IMAGE_REFERENCE_MAX_COUNT)
1357
+ throw new ImageGenerationError(
1358
+ "Too many image references; no generation was attempted."
1359
+ );
1360
+ const references = [];
1361
+ let total = 0;
1362
+ try {
1363
+ for (const source of sources) {
1364
+ signal?.throwIfAborted();
1365
+ let bytes;
1366
+ if (source.type === "artifact")
1367
+ bytes = (await store.read(source.artifact_id)).bytes;
1368
+ else {
1369
+ if (!readSource)
1370
+ throw new ImageGenerationError(
1371
+ "URL/file image references are unavailable in this environment; no generation was attempted."
1372
+ );
1373
+ bytes = await readSource(source, signal);
1374
+ }
1375
+ signal?.throwIfAborted();
1376
+ const reference = validateImageReference(bytes);
1377
+ total += bytes.length;
1378
+ if (total > IMAGE_REFERENCE_TOTAL_BYTES)
1379
+ throw new ImageGenerationError(
1380
+ "Image references exceed the 32 MiB combined limit; no generation was attempted."
1381
+ );
1382
+ references.push(reference);
1383
+ }
1384
+ return references;
1385
+ } catch (error) {
1386
+ if (error instanceof ImageGenerationError) throw error;
1387
+ throw new ImageGenerationError(
1388
+ "Image reference could not be read or was cancelled; no generation was attempted."
1389
+ );
1390
+ }
1391
+ }
1392
+
1393
+ // src/image-generation/attachments.ts
1394
+ async function persistImageAttachments(input, store) {
1395
+ if (typeof input === "string") return input;
1396
+ const result = [];
1397
+ let imageNumber = 0;
1398
+ for (const part of input) {
1399
+ if (part.type !== "image_url") {
1400
+ result.push(part);
1401
+ continue;
1402
+ }
1403
+ imageNumber++;
1404
+ const url = part.image_url.url;
1405
+ if (!url.startsWith("data:")) {
1406
+ result.push(part);
1407
+ continue;
1408
+ }
1409
+ if (url.length > Math.ceil(IMAGE_REFERENCE_MAX_BYTES / 3) * 4 + 64)
1410
+ throw new Error("Image attachment exceeds 8 MiB");
1411
+ const match = /^data:(image\/(?:png|jpeg|webp|gif));base64,([A-Za-z0-9+/]*={0,2})$/.exec(
1412
+ url
1413
+ );
1414
+ if (!match)
1415
+ throw new Error(
1416
+ "Image attachment must be a PNG/JPEG/WebP/GIF base64 data URL"
1417
+ );
1418
+ const mediaType = match[1];
1419
+ const encoded = match[2] ?? "";
1420
+ const bytes = Buffer.from(encoded, "base64");
1421
+ if (!encoded || bytes.toString("base64") !== encoded || part.image_url.media_type && part.image_url.media_type !== mediaType)
1422
+ throw new Error("Invalid image attachment encoding or MIME mismatch");
1423
+ const metadata = await store.saveAttachment(bytes, mediaType);
1424
+ const { artifact_id, sha256, media_type, byte_size, width, height } = metadata;
1425
+ result.push(
1426
+ {
1427
+ type: "text",
1428
+ text: `[Attached image ${imageNumber}: ${artifact_id}. To use this image as a generation reference, explicitly supply images: [{"type":"artifact","artifact_id":"${artifact_id}"}].]`
1429
+ },
1430
+ {
1431
+ type: "image_ref",
1432
+ image_ref: {
1433
+ artifact_id,
1434
+ sha256,
1435
+ media_type,
1436
+ byte_size,
1437
+ width,
1438
+ height
1439
+ },
1440
+ ...part.image_url.detail ? { detail: part.image_url.detail } : {}
1441
+ }
1442
+ );
1443
+ }
1444
+ return result;
1445
+ }
1446
+
1447
+ // src/image-generation/export.ts
1448
+ import { open, realpath } from "fs/promises";
1449
+ import path3 from "path";
1450
+ async function exportImageBytes(workspaceRoot, outputPath, bytes) {
1451
+ if (!outputPath || outputPath.length > 4096 || [...outputPath].some(
1452
+ (c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127
1453
+ ) || path3.extname(outputPath).toLowerCase() !== ".png")
1454
+ throw new ImageGenerationError(
1455
+ "Image export requires a PNG path in this workspace."
1456
+ );
1457
+ const target = path3.resolve(workspaceRoot, outputPath);
1458
+ try {
1459
+ const root = await realpath(workspaceRoot);
1460
+ const parent = await realpath(path3.dirname(target));
1461
+ const relative = path3.relative(root, parent);
1462
+ if (relative === ".." || relative.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative))
1463
+ throw new Error("outside workspace");
1464
+ const destination = path3.join(parent, path3.basename(target));
1465
+ const file = await open(destination, "wx", 384);
1466
+ try {
1467
+ await file.writeFile(bytes);
1468
+ await file.sync();
1469
+ } finally {
1470
+ await file.close();
1471
+ }
1472
+ return destination;
1473
+ } catch {
1474
+ throw new ImageGenerationError(
1475
+ "Image export failed: destination must be a new file in an existing workspace directory. No original was modified."
1476
+ );
1477
+ }
1478
+ }
1479
+
1480
+ // src/image-generation/local-store.ts
1481
+ import { createHash } from "crypto";
1482
+ import path4 from "path";
1483
+ import { ImageArtifactStore, resolveStoragePaths } from "@codelia/storage";
1484
+ function createLocalImageStore(workspaceRoot) {
1485
+ const scope = createHash("sha256").update(path4.resolve(workspaceRoot)).digest("hex");
1486
+ return new ImageArtifactStore(
1487
+ path4.join(resolveStoragePaths().sessionsDir, "image-artifacts", scope)
1488
+ );
1489
+ }
1490
+
1491
+ // src/image-generation/route.ts
1492
+ import {
1493
+ OPENAI_IMAGE_MODELS,
1494
+ OPENAI_CODEX_IMAGE_MODELS
1495
+ } from "@codelia/config";
1496
+ var localImageAuth = {
1497
+ storedKey: async (provider) => {
1498
+ const auth = (await new AuthStore().load()).providers[provider];
1499
+ return auth?.method === "api_key" ? auth.api_key : void 0;
1500
+ },
1501
+ env: (name) => process.env[name]?.trim() || void 0
1502
+ };
1503
+ async function resolveImageRoute(config, auth, chat) {
1504
+ if (config.mode === "off") return null;
1505
+ let provider;
1506
+ let model;
1507
+ let apiKey;
1508
+ if (config.mode === "builtin") {
1509
+ if (chat?.provider !== "openai")
1510
+ throw new ImageGenerationError(
1511
+ "builtin unavailable: select an OpenAI conversation connection and sign in first; no other provider or authentication route was selected."
1512
+ );
1513
+ if (chat.auth.method === "oauth") {
1514
+ const oauth = chat.auth.oauth;
1515
+ if (!oauth.access_token.trim())
1516
+ throw new ImageGenerationError(
1517
+ "Codex OAuth login is missing; sign in to OpenAI again. An API key is not required."
1518
+ );
1519
+ const o2 = config.provider_options?.openai;
1520
+ return {
1521
+ authMode: "codex_oauth",
1522
+ provider: "openai",
1523
+ model: o2?.model ?? OPENAI_CODEX_IMAGE_MODELS[0],
1524
+ endpoint: `${OPENAI_OAUTH_BASE_URL}/images/generations`,
1525
+ options: {
1526
+ ...o2?.quality ? { quality: o2.quality } : {},
1527
+ ...o2?.size ? { size: o2.size } : {}
1528
+ },
1529
+ ...oauth.account_id ? { accountId: oauth.account_id } : {},
1530
+ getAccessToken: chat.getOpenAiAccessToken ?? (async () => {
1531
+ if (oauth.expires_at <= Date.now() + 6e4)
1532
+ throw new ImageGenerationError(
1533
+ "Codex OAuth refresh is unavailable; sign in to OpenAI again. An API key is not required."
1534
+ );
1535
+ return { token: oauth.access_token, accountId: oauth.account_id };
1536
+ })
1537
+ };
1538
+ }
1539
+ if (auth.env("OPENAI_BASE_URL"))
1540
+ throw new ImageGenerationError(
1541
+ "builtin unavailable: the API-key conversation uses an unsupported base URL override; no endpoint fallback was attempted."
1542
+ );
1543
+ provider = "openai";
1544
+ model = config.provider_options?.openai?.model ?? OPENAI_IMAGE_MODELS[0];
1545
+ if (!OPENAI_IMAGE_MODELS.includes(model))
1546
+ throw new ImageGenerationError(
1547
+ "This selected builtin image model is only configured for Codex OAuth; select an API image model explicitly."
1548
+ );
1549
+ apiKey = chat.auth.api_key;
1550
+ } else {
1551
+ provider = config.provider;
1552
+ model = config.model;
1553
+ apiKey = config.api_key_env ? auth.env(config.api_key_env) : await auth.storedKey(provider) || auth.env(
1554
+ provider === "openai" ? "OPENAI_API_KEY" : "OPENROUTER_API_KEY"
1555
+ );
1556
+ }
1557
+ if (!apiKey?.trim())
1558
+ throw new ImageGenerationError(
1559
+ "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."
1560
+ );
1561
+ const options = {};
1562
+ if (provider === "openai") {
1563
+ const o2 = config.provider_options?.openai;
1564
+ if (o2?.quality) options.quality = o2.quality;
1565
+ if (o2?.size) options.size = o2.size;
1566
+ return {
1567
+ authMode: "api_key",
1568
+ provider,
1569
+ model,
1570
+ apiKey,
1571
+ endpoint: "https://api.openai.com/v1/images/generations",
1572
+ options
1573
+ };
1574
+ }
1575
+ const o = config.provider_options?.openrouter;
1576
+ if (!o?.endpoint)
1577
+ throw new ImageGenerationError(
1578
+ "Select an OpenRouter image endpoint with /image-model; automatic endpoint fallback is disabled."
1579
+ );
1580
+ if (o.quality) options.quality = o.quality;
1581
+ if (o.resolution) options.resolution = o.resolution;
1582
+ if (o.aspect_ratio) options.aspect_ratio = o.aspect_ratio;
1583
+ return {
1584
+ authMode: "api_key",
1585
+ provider,
1586
+ model,
1587
+ apiKey,
1588
+ endpoint: o.endpoint,
1589
+ options
1590
+ };
1591
+ }
1592
+
1593
+ // src/image-generation/source-reader.ts
1594
+ import { lookup } from "dns/promises";
1595
+ import { constants } from "fs";
1596
+ import { open as open2, realpath as realpath2 } from "fs/promises";
1597
+ import { request as httpRequest } from "http";
1598
+ import { request as httpsRequest } from "https";
1599
+ import { BlockList, isIP } from "net";
1600
+ import path5 from "path";
1601
+ var blocked = new BlockList();
1602
+ for (const [address, prefix] of [
1603
+ ["0.0.0.0", 8],
1604
+ ["10.0.0.0", 8],
1605
+ ["100.64.0.0", 10],
1606
+ ["127.0.0.0", 8],
1607
+ ["169.254.0.0", 16],
1608
+ ["172.16.0.0", 12],
1609
+ ["192.0.0.0", 24],
1610
+ ["192.0.2.0", 24],
1611
+ ["192.88.99.0", 24],
1612
+ ["192.168.0.0", 16],
1613
+ ["198.18.0.0", 15],
1614
+ ["198.51.100.0", 24],
1615
+ ["203.0.113.0", 24],
1616
+ ["224.0.0.0", 4],
1617
+ ["240.0.0.0", 4]
1618
+ ])
1619
+ blocked.addSubnet(address, prefix, "ipv4");
1620
+ var globalV6 = new BlockList();
1621
+ globalV6.addSubnet("2000::", 3, "ipv6");
1622
+ for (const [address, prefix] of [
1623
+ ["2001::", 23],
1624
+ ["2001:db8::", 32],
1625
+ ["2002::", 16],
1626
+ ["3fff::", 20]
1627
+ ])
1628
+ blocked.addSubnet(address, prefix, "ipv6");
1629
+ function isPublicImageAddress(address) {
1630
+ const family = isIP(address);
1631
+ return family === 4 ? !blocked.check(address, "ipv4") : family === 6 && globalV6.check(address, "ipv6") && !blocked.check(address, "ipv6");
1632
+ }
1633
+ function createImageLookup(resolve = (hostname) => lookup(hostname, { all: true, verbatim: true })) {
1634
+ return (hostname, options, callback) => {
1635
+ void resolve(hostname).then(
1636
+ (addresses) => {
1637
+ if (!addresses.length || addresses.some((entry) => !isPublicImageAddress(entry.address))) {
1638
+ callback(new Error("Image source destination is not public"), "");
1639
+ return;
1640
+ }
1641
+ const family = options.family === "IPv4" ? 4 : options.family === "IPv6" ? 6 : options.family;
1642
+ const selected = addresses.filter(
1643
+ (entry) => !family || entry.family === family
1644
+ );
1645
+ const first = selected[0];
1646
+ if (!first)
1647
+ callback(
1648
+ new Error("Image source has no compatible public address"),
1649
+ ""
1650
+ );
1651
+ else if (options.all) callback(null, selected);
1652
+ else callback(null, first.address, first.family);
1653
+ },
1654
+ () => callback(new Error("Image source DNS failed"), "")
1655
+ );
1656
+ };
1657
+ }
1658
+ function imageSourceUrl(value) {
1659
+ try {
1660
+ const url = new URL(value);
1661
+ const host = url.hostname.replace(/^\[|\]$/g, "");
1662
+ 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))
1663
+ throw new Error("invalid source");
1664
+ return url;
1665
+ } catch {
1666
+ throw new ImageGenerationError(
1667
+ "Image source requires a public HTTP(S) URL on port 80/443 without credentials or fragments; no generation was attempted."
1668
+ );
1669
+ }
1670
+ }
1671
+ var requestImage = (url, options) => new Promise((resolve, reject) => {
1672
+ if (process.versions.bun && [
1673
+ "HTTP_PROXY",
1674
+ "HTTPS_PROXY",
1675
+ "ALL_PROXY",
1676
+ "http_proxy",
1677
+ "https_proxy",
1678
+ "all_proxy"
1679
+ ].some((name) => process.env[name]))
1680
+ throw new ImageGenerationError(
1681
+ "Image URL references require a direct connection; proxy-configured Bun is unsupported. Use a local file/artifact reference. No generation was attempted."
1682
+ );
1683
+ const request = (url.protocol === "https:" ? httpsRequest : httpRequest)(
1684
+ url,
1685
+ options
1686
+ );
1687
+ const cleanup = () => options.signal?.removeEventListener("abort", abort);
1688
+ const abort = () => {
1689
+ cleanup();
1690
+ reject(new Error("Image source request cancelled"));
1691
+ request.destroy();
1692
+ };
1693
+ request.once("response", (response) => {
1694
+ cleanup();
1695
+ resolve(response);
1696
+ });
1697
+ request.on("error", (error) => {
1698
+ cleanup();
1699
+ reject(error);
1700
+ });
1701
+ request.once("close", () => {
1702
+ cleanup();
1703
+ reject(new Error("Image source closed before response"));
1704
+ });
1705
+ options.signal?.addEventListener("abort", abort, { once: true });
1706
+ if (options.signal?.aborted) abort();
1707
+ else request.end();
1708
+ });
1709
+ async function downloadImageSource(value, callerSignal, transport = requestImage, timeoutMs = 15e3) {
1710
+ const url = imageSourceUrl(value);
1711
+ const signal = callerSignal ? AbortSignal.any([callerSignal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
1712
+ let response;
1713
+ try {
1714
+ signal.throwIfAborted();
1715
+ response = await transport(url, {
1716
+ method: "GET",
1717
+ agent: false,
1718
+ lookup: createImageLookup(),
1719
+ // Preserve the original authority when Bun connects to a validated DNS IP.
1720
+ ...url.protocol === "https:" && !isIP(url.hostname.replace(/^\[|\]$/g, "")) ? { servername: url.hostname } : {},
1721
+ signal,
1722
+ headers: {
1723
+ Host: url.host,
1724
+ Accept: "image/png,image/jpeg,image/webp",
1725
+ "Accept-Encoding": "identity"
1726
+ }
1727
+ });
1728
+ signal.throwIfAborted();
1729
+ if (response.statusCode !== 200)
1730
+ throw new Error("non-200 source (redirects are not followed)");
1731
+ if (response.headers["content-encoding"] && response.headers["content-encoding"] !== "identity")
1732
+ throw new Error("compressed transfer unsupported");
1733
+ if (Number(response.headers["content-length"] ?? 0) > IMAGE_REFERENCE_MAX_BYTES)
1734
+ throw new Error("source too large");
1735
+ const stream = response;
1736
+ const abort = () => stream.destroy(new Error("Image source read cancelled"));
1737
+ signal.addEventListener("abort", abort, { once: true });
1738
+ try {
1739
+ const chunks = [];
1740
+ let size = 0;
1741
+ for await (const chunk of stream) {
1742
+ signal.throwIfAborted();
1743
+ if (!(chunk instanceof Uint8Array)) throw new Error("nonbinary source");
1744
+ size += chunk.length;
1745
+ if (size > IMAGE_REFERENCE_MAX_BYTES)
1746
+ throw new Error("source too large");
1747
+ chunks.push(chunk);
1748
+ }
1749
+ signal.throwIfAborted();
1750
+ if (!size) throw new Error("empty source");
1751
+ return Buffer.concat(chunks);
1752
+ } finally {
1753
+ signal.removeEventListener("abort", abort);
1754
+ }
1755
+ } catch (error) {
1756
+ if (error instanceof ImageGenerationError) throw error;
1757
+ throw new ImageGenerationError(
1758
+ "Image source download failed, timed out, was cancelled, or exceeded limits; redirects/private destinations are not allowed. No generation was attempted."
1759
+ );
1760
+ } finally {
1761
+ response?.destroy();
1762
+ }
1763
+ }
1764
+ async function readImageFile(sandbox, filePath, signal) {
1765
+ try {
1766
+ signal?.throwIfAborted();
1767
+ const target = await realpath2(sandbox.resolvePath(filePath));
1768
+ if (sandbox.approvalMode !== "full-access") {
1769
+ const root = await realpath2(sandbox.rootDir);
1770
+ const relative = path5.relative(root, target);
1771
+ if (relative === ".." || relative.startsWith(`..${path5.sep}`) || path5.isAbsolute(relative))
1772
+ throw new Error("outside sandbox");
1773
+ }
1774
+ const handle = await open2(
1775
+ target,
1776
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
1777
+ );
1778
+ try {
1779
+ const stat = await handle.stat();
1780
+ if (!stat.isFile() || stat.size <= 0 || stat.size > IMAGE_REFERENCE_MAX_BYTES)
1781
+ throw new Error("invalid source file");
1782
+ const bytes = Buffer.alloc(stat.size + 1);
1783
+ let offset = 0;
1784
+ while (offset < bytes.length) {
1785
+ signal?.throwIfAborted();
1786
+ const result = await handle.read(
1787
+ bytes,
1788
+ offset,
1789
+ Math.min(bytes.length - offset, 65536),
1790
+ offset
1791
+ );
1792
+ if (!result.bytesRead) break;
1793
+ offset += result.bytesRead;
1794
+ }
1795
+ if (offset !== stat.size)
1796
+ throw new Error("source file changed during read");
1797
+ signal?.throwIfAborted();
1798
+ return bytes.subarray(0, offset);
1799
+ } finally {
1800
+ await handle.close();
1801
+ }
1802
+ } catch {
1803
+ throw new ImageGenerationError(
1804
+ "Image reference file is unavailable, outside the sandbox, not a bounded regular file, or reading was cancelled; no generation was attempted."
1805
+ );
1806
+ }
1807
+ }
1808
+ function createLocalImageSourceReader(sandbox) {
1809
+ return (source, signal) => source.type === "url" ? downloadImageSource(source.url, signal) : readImageFile(sandbox, source.file_path, signal);
1810
+ }
1811
+
1812
+ // src/image-generation/tools.ts
1813
+ import {
1814
+ defineTool,
1815
+ ToolPermissionDenied
1816
+ } from "@codelia/core";
1817
+ import { z as z5 } from "zod";
1818
+
1819
+ // src/image-generation/adapter.ts
1820
+ import { IMAGE_MAX_BYTES } from "@codelia/storage";
1821
+ import { z as z4 } from "zod";
1822
+
1823
+ // src/image-generation/catalog.ts
1824
+ import { z as z3 } from "zod";
1825
+ var slug = z3.string().max(160).regex(/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/);
1826
+ var descriptor = z3.union([
1827
+ z3.object({
1828
+ type: z3.literal("enum"),
1829
+ values: z3.array(z3.string().max(100)).max(128)
1830
+ }),
1831
+ z3.object({
1832
+ type: z3.literal("range"),
1833
+ min: z3.number().finite(),
1834
+ max: z3.number().finite()
1835
+ }),
1836
+ z3.object({ type: z3.literal("boolean") })
1837
+ ]);
1838
+ var endpointSchema = z3.object({
1839
+ provider_tag: slug.nullable(),
1840
+ supported_parameters: z3.record(z3.string(), descriptor)
1841
+ });
1842
+ var ImageCatalog = class {
1843
+ constructor(fetcher = fetch) {
1844
+ this.fetcher = fetcher;
1845
+ }
1846
+ fetcher;
1847
+ cached;
1848
+ async list() {
1849
+ if (this.cached && this.cached.expires > Date.now())
1850
+ return { ...this.cached, stale: false };
1851
+ try {
1852
+ const raw = await imageJson(
1853
+ "https://openrouter.ai/api/v1/images/models",
1854
+ {},
1855
+ this.fetcher,
1856
+ 4 * 1024 * 1024,
1857
+ 15e3
1858
+ );
1859
+ const parsed = z3.object({
1860
+ data: z3.array(
1861
+ z3.object({
1862
+ id: slug,
1863
+ name: z3.string().max(256),
1864
+ architecture: z3.object({
1865
+ output_modalities: z3.array(z3.string())
1866
+ })
1867
+ })
1868
+ ).max(2e3)
1869
+ }).safeParse(raw);
1870
+ if (!parsed.success)
1871
+ throw new ImageGenerationError("Invalid image model catalog.");
1872
+ const models = parsed.data.data.filter((m) => m.architecture.output_modalities.includes("image")).map((m) => ({
1873
+ id: m.id,
1874
+ name: [...m.name].filter((c) => c.charCodeAt(0) >= 32 && c.charCodeAt(0) !== 127).join("")
1875
+ }));
1876
+ this.cached = {
1877
+ models,
1878
+ fetched_at: (/* @__PURE__ */ new Date()).toISOString(),
1879
+ expires: Date.now() + 3e5
1880
+ };
1881
+ return { ...this.cached, stale: false };
1882
+ } catch (error) {
1883
+ if (this.cached) return { ...this.cached, stale: true };
1884
+ throw error;
1885
+ }
1886
+ }
1887
+ async endpoints(model, signal) {
1888
+ if (!slug.safeParse(model).success)
1889
+ throw new ImageGenerationError("Invalid image model id.");
1890
+ const raw = await imageJson(
1891
+ `https://openrouter.ai/api/v1/images/models/${model.split("/").map(encodeURIComponent).join("/")}/endpoints`,
1892
+ { signal },
1893
+ this.fetcher,
1894
+ 1024 * 1024,
1895
+ 15e3
1896
+ );
1897
+ const parsed = z3.object({ endpoints: z3.array(endpointSchema).max(100) }).safeParse(raw);
1898
+ if (!parsed.success)
1899
+ throw new ImageGenerationError("Invalid image endpoint catalog.");
1900
+ return parsed.data.endpoints.filter(
1901
+ (e) => e.provider_tag && (!e.supported_parameters.output_format || acceptsParameter(e, "output_format", "png"))
1902
+ );
1903
+ }
1904
+ };
1905
+ function acceptsParameter(endpoint, key, value) {
1906
+ const rule = endpoint.supported_parameters[key];
1907
+ if (!rule) return false;
1908
+ if (rule.type === "enum")
1909
+ return typeof value === "string" && rule.values.includes(value);
1910
+ if (rule.type === "range")
1911
+ return typeof value === "number" && Number.isInteger(value) && value >= rule.min && value <= rule.max;
1912
+ return true;
1913
+ }
1914
+
1915
+ // src/image-generation/codex.ts
1916
+ import { randomUUID } from "crypto";
1917
+ async function requestCodexImage(route, prompt, references, signal, fetcher) {
1918
+ if (route.endpoint !== `${OPENAI_OAUTH_BASE_URL}/images/generations`)
1919
+ throw new ImageGenerationError(
1920
+ "Invalid Codex image endpoint; OAuth was not sent."
1921
+ );
1922
+ signal?.throwIfAborted();
1923
+ let credentials;
1924
+ try {
1925
+ credentials = await route.getAccessToken();
1926
+ } catch {
1927
+ throw new ImageGenerationError(
1928
+ "Codex OAuth authentication/refresh failed; sign in to OpenAI again. No image request or API-key fallback was attempted."
1929
+ );
1930
+ }
1931
+ signal?.throwIfAborted();
1932
+ if (!credentials.token.trim())
1933
+ throw new ImageGenerationError(
1934
+ "Codex OAuth login is missing; sign in to OpenAI again. An API key is not required."
1935
+ );
1936
+ if (route.accountId && credentials.accountId !== route.accountId)
1937
+ throw new ImageGenerationError(
1938
+ "The Codex OAuth account changed; start a new run before generating images. No request was sent to another account."
1939
+ );
1940
+ const headers = {
1941
+ Authorization: `Bearer ${credentials.token}`,
1942
+ "Content-Type": "application/json",
1943
+ originator: "codelia",
1944
+ "User-Agent": "codelia-cli",
1945
+ "x-codex-image-turn-id": `codelia-image-${randomUUID()}`,
1946
+ ...credentials.accountId ? { "ChatGPT-Account-ID": credentials.accountId } : {}
1947
+ };
1948
+ const body = {
1949
+ model: route.model,
1950
+ prompt,
1951
+ background: "auto",
1952
+ quality: route.options.quality ?? "auto",
1953
+ size: route.options.size ?? "auto",
1954
+ ...references.length ? {
1955
+ images: references.map((reference) => ({
1956
+ image_url: imageReferenceDataUrl(reference)
1957
+ }))
1958
+ } : {}
1959
+ };
1960
+ return imageJson(
1961
+ `${OPENAI_OAUTH_BASE_URL}/images/${references.length ? "edits" : "generations"}`,
1962
+ {
1963
+ method: "POST",
1964
+ headers,
1965
+ body: JSON.stringify(body),
1966
+ signal
1967
+ },
1968
+ fetcher
1969
+ );
1970
+ }
1971
+
1972
+ // src/image-generation/adapter.ts
1973
+ var responseSchema = z4.object({
1974
+ data: z4.array(
1975
+ z4.object({
1976
+ b64_json: z4.string().min(1).max(Math.ceil(IMAGE_MAX_BYTES / 3) * 4),
1977
+ media_type: z4.literal("image/png").optional()
1978
+ })
1979
+ ).length(1),
1980
+ model: z4.string().max(160).regex(/^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$/).optional(),
1981
+ usage: z4.object({
1982
+ input_tokens: z4.number().finite().nonnegative().optional(),
1983
+ output_tokens: z4.number().finite().nonnegative().optional(),
1984
+ prompt_tokens: z4.number().finite().nonnegative().optional(),
1985
+ completion_tokens: z4.number().finite().nonnegative().optional(),
1986
+ cost: z4.number().finite().nonnegative().optional()
1987
+ }).optional()
1988
+ });
1989
+ async function prepareImageGeneration(route, referenceCount, signal, fetcher = fetch) {
1990
+ signal?.throwIfAborted();
1991
+ const max = route.authMode === "codex_oauth" ? 5 : IMAGE_REFERENCE_MAX_COUNT;
1992
+ if (!Number.isInteger(referenceCount) || referenceCount < 0 || referenceCount > max)
1993
+ throw new ImageGenerationError(
1994
+ `Selected image route supports at most ${max} references; no generation was attempted.`
1995
+ );
1996
+ let endpoint;
1997
+ if (route.provider === "openrouter") {
1998
+ endpoint = (await new ImageCatalog(fetcher).endpoints(route.model, signal)).find((e) => e.provider_tag === route.endpoint);
1999
+ if (!endpoint)
2000
+ throw new ImageGenerationError(
2001
+ "Selected image endpoint is unavailable or explicitly excludes PNG output."
2002
+ );
2003
+ if (endpoint.supported_parameters.n && !acceptsParameter(endpoint, "n", 1))
2004
+ throw new ImageGenerationError(
2005
+ "Selected image endpoint does not support a single image."
2006
+ );
2007
+ for (const [key, value] of Object.entries(route.options))
2008
+ if (!acceptsParameter(endpoint, key, value))
2009
+ throw new ImageGenerationError(
2010
+ `Selected image endpoint does not support configured ${key}.`
2011
+ );
2012
+ if (referenceCount && !acceptsParameter(endpoint, "input_references", referenceCount))
2013
+ throw new ImageGenerationError(
2014
+ "Selected image endpoint does not support this reference count; no generation was attempted."
2015
+ );
2016
+ }
2017
+ return async (prompt, references) => {
2018
+ if (references.length !== referenceCount)
2019
+ throw new ImageGenerationError(
2020
+ "Image reference count changed after preparation; no generation was attempted."
2021
+ );
2022
+ let total = 0;
2023
+ for (const reference of references) {
2024
+ const validated = validateImageReference(reference.bytes);
2025
+ if (validated.media_type !== reference.media_type)
2026
+ throw new ImageGenerationError(
2027
+ "Image reference media type mismatch; no generation was attempted."
2028
+ );
2029
+ total += reference.bytes.length;
2030
+ }
2031
+ if (total > IMAGE_REFERENCE_TOTAL_BYTES)
2032
+ throw new ImageGenerationError(
2033
+ "Image references exceed the 32 MiB combined limit; no generation was attempted."
2034
+ );
2035
+ return sendImage(route, prompt, references, signal, fetcher, endpoint);
2036
+ };
2037
+ }
2038
+ async function sendImage(route, prompt, references, signal, fetcher = fetch, endpoint) {
2039
+ if (route.authMode === "codex_oauth")
2040
+ return parseImageResponse(
2041
+ await requestCodexImage(route, prompt, references, signal, fetcher)
2042
+ );
2043
+ let url = route.endpoint;
2044
+ let body;
2045
+ const headers = {
2046
+ Authorization: `Bearer ${route.apiKey}`
2047
+ };
2048
+ if (route.provider === "openai" && references.length) {
2049
+ url = "https://api.openai.com/v1/images/edits";
2050
+ const form = new FormData();
2051
+ form.set("model", route.model);
2052
+ form.set("prompt", prompt);
2053
+ form.set("n", "1");
2054
+ form.set("output_format", "png");
2055
+ for (const [key, value] of Object.entries(route.options))
2056
+ form.set(key, value);
2057
+ for (const [i, reference] of references.entries())
2058
+ form.append(
2059
+ "image[]",
2060
+ new Blob([new Uint8Array(reference.bytes)], {
2061
+ type: reference.media_type
2062
+ }),
2063
+ `reference-${i}.${reference.media_type.split("/")[1]}`
2064
+ );
2065
+ body = form;
2066
+ } else {
2067
+ const fields = {
2068
+ model: route.model,
2069
+ prompt,
2070
+ n: 1,
2071
+ output_format: "png",
2072
+ ...route.options
2073
+ };
2074
+ if (route.provider === "openrouter") {
2075
+ url = "https://openrouter.ai/api/v1/images";
2076
+ if (!endpoint)
2077
+ throw new ImageGenerationError(
2078
+ "Selected image endpoint is unavailable or explicitly excludes PNG output."
2079
+ );
2080
+ if (!endpoint.supported_parameters.output_format)
2081
+ delete fields.output_format;
2082
+ if (!endpoint.supported_parameters.n) delete fields.n;
2083
+ fields.provider = { only: [route.endpoint], allow_fallbacks: false };
2084
+ if (references.length) {
2085
+ fields.input_references = references.map((reference) => ({
2086
+ type: "image_url",
2087
+ image_url: {
2088
+ url: imageReferenceDataUrl(reference)
2089
+ }
2090
+ }));
2091
+ }
2092
+ }
2093
+ headers["Content-Type"] = "application/json";
2094
+ body = JSON.stringify(fields);
2095
+ }
2096
+ signal?.throwIfAborted();
2097
+ return parseImageResponse(
2098
+ await imageJson(url, { method: "POST", headers, body, signal }, fetcher)
2099
+ );
2100
+ }
2101
+ function parseImageResponse(raw) {
2102
+ const parsed = responseSchema.safeParse(raw);
2103
+ if (!parsed.success)
2104
+ throw new ImageGenerationError(
2105
+ "Image API returned no complete supported image; generation was not recorded as successful."
2106
+ );
2107
+ const base64 = parsed.data.data[0]?.b64_json ?? "";
2108
+ const bytes = Buffer.from(base64, "base64");
2109
+ if (!bytes.length || bytes.length > IMAGE_MAX_BYTES || bytes.toString("base64") !== base64)
2110
+ throw new ImageGenerationError(
2111
+ "Image API returned invalid or oversized base64."
2112
+ );
2113
+ const u = parsed.data.usage;
2114
+ const usage = u ? {
2115
+ input_tokens: u.input_tokens ?? u.prompt_tokens,
2116
+ output_tokens: u.output_tokens ?? u.completion_tokens,
2117
+ cost_usd: u.cost
2118
+ } : void 0;
2119
+ return {
2120
+ bytes,
2121
+ ...parsed.data.model ? { effective_model: parsed.data.model } : {},
2122
+ ...usage ? { usage } : {}
2123
+ };
2124
+ }
2125
+
2126
+ // src/image-generation/tools.ts
2127
+ var imageParts = (m, ref) => {
2128
+ 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`}.`;
2129
+ return [
2130
+ {
2131
+ type: "text",
2132
+ text: `Image artifact: ${m.artifact_id}
2133
+ ${m.width}x${m.height}, ${m.byte_size} bytes, ${m.media_type}
2134
+ ${provenance}
2135
+ Preview: /image-artifact ${m.artifact_id}
2136
+ 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." : ""}
2137
+ `
2138
+ },
2139
+ { type: "image_ref", image_ref: ref }
2140
+ ];
2141
+ };
2142
+ function createImageTools(input) {
2143
+ const tools = [
2144
+ defineTool({
2145
+ name: "image_inspect",
2146
+ 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.",
2147
+ input: z5.object({
2148
+ artifact_id: imageArtifactId.describe(
2149
+ "Saved codelia-image artifact id from a prior image result."
2150
+ ),
2151
+ original: z5.boolean().optional().describe(
2152
+ "Use original pixels for this inspection instead of the generated-image JPEG view."
2153
+ )
2154
+ }),
2155
+ execute: async ({ artifact_id, original }) => imageParts(
2156
+ (await input.store.read(artifact_id)).metadata,
2157
+ await input.store.modelReference(artifact_id, original)
2158
+ )
2159
+ })
2160
+ ];
2161
+ const exportImage = input.exportImage;
2162
+ if (exportImage)
2163
+ tools.push(
2164
+ defineTool({
2165
+ name: "image_export",
2166
+ 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.",
2167
+ input: z5.object({
2168
+ artifact_id: imageArtifactId.describe("Saved image artifact id."),
2169
+ output_path: z5.string().min(1).max(4096).describe(
2170
+ "New .png file inside the runtime workspace; parent directory must already exist."
2171
+ )
2172
+ }),
2173
+ execute: async (args, ctx) => {
2174
+ const raw = JSON.stringify(args);
2175
+ const decision = await input.authorize(
2176
+ {
2177
+ id: "codelia-image-export",
2178
+ type: "function",
2179
+ function: { name: "image_export", arguments: raw }
2180
+ },
2181
+ raw,
2182
+ ctx
2183
+ );
2184
+ if (decision.decision !== "allow")
2185
+ throw new ToolPermissionDenied(decision);
2186
+ ctx.signal?.throwIfAborted();
2187
+ const { bytes, metadata } = await input.store.read(args.artifact_id);
2188
+ if (metadata.media_type !== "image/png")
2189
+ throw new ImageGenerationError(
2190
+ "PNG export only; this attachment's original format is not PNG. No conversion was performed."
2191
+ );
2192
+ return `Image exported (runtime host path): ${await exportImage(args.output_path, bytes)}
2193
+ Original artifact unchanged: ${args.artifact_id}`;
2194
+ }
2195
+ })
2196
+ );
2197
+ const route = input.route;
2198
+ if (!route) return tools;
2199
+ 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";
2200
+ let busy = false;
2201
+ tools.push(
2202
+ defineTool({
2203
+ name: "image_generate",
2204
+ 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.`,
2205
+ input: z5.object({
2206
+ prompt: z5.string().trim().min(1).max(16e3).describe(
2207
+ "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."
2208
+ ),
2209
+ images: z5.array(imageSourceSchema).max(IMAGE_REFERENCE_MAX_COUNT).optional().describe(
2210
+ "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."
2211
+ ),
2212
+ reference_artifact_ids: z5.array(imageArtifactId).max(IMAGE_REFERENCE_MAX_COUNT).optional().describe(
2213
+ "Legacy artifact-only alternative to images, subject to the same route/count/byte limits. Do not combine with images; prefer images with type=artifact."
2214
+ )
2215
+ }).refine(
2216
+ (args) => args.images === void 0 || args.reference_artifact_ids === void 0,
2217
+ "Provide images or reference_artifact_ids, not both"
2218
+ ),
2219
+ execute: async (args, ctx) => {
2220
+ if (busy)
2221
+ throw new ImageGenerationError(
2222
+ "An image generation request is already active; wait for it rather than retrying."
2223
+ );
2224
+ busy = true;
2225
+ try {
2226
+ const raw = {
2227
+ ...args,
2228
+ provider: route.provider,
2229
+ requested_model: route.model,
2230
+ endpoint: route.endpoint,
2231
+ auth_mode: route.authMode,
2232
+ billing
2233
+ };
2234
+ const decision = await input.authorize(
2235
+ {
2236
+ id: "codelia-image-generation",
2237
+ type: "function",
2238
+ function: {
2239
+ name: "image_generate",
2240
+ arguments: JSON.stringify(raw)
2241
+ }
2242
+ },
2243
+ JSON.stringify(raw),
2244
+ ctx
2245
+ );
2246
+ if (decision.decision !== "allow")
2247
+ throw new ToolPermissionDenied(decision);
2248
+ ctx.signal?.throwIfAborted();
2249
+ const sources = args.images ?? (args.reference_artifact_ids ?? []).map((artifact_id) => ({
2250
+ type: "artifact",
2251
+ artifact_id
2252
+ }));
2253
+ const generate = await prepareImageGeneration(
2254
+ route,
2255
+ sources.length,
2256
+ ctx.signal,
2257
+ input.fetcher
2258
+ );
2259
+ const references = await resolveImageSources(
2260
+ sources,
2261
+ input.store,
2262
+ input.readSource,
2263
+ ctx.signal
2264
+ );
2265
+ const ids = sources.flatMap(
2266
+ (source) => source.type === "artifact" ? [source.artifact_id] : []
2267
+ );
2268
+ const result = await generate(args.prompt, references);
2269
+ ctx.signal?.throwIfAborted();
2270
+ const metadata = await input.store.save(result.bytes, {
2271
+ provider: route.provider,
2272
+ requested_model: route.model,
2273
+ endpoint: route.endpoint,
2274
+ parent_artifact_ids: ids,
2275
+ ...result.effective_model ? { effective_model: result.effective_model } : {},
2276
+ ...result.usage ? { usage: result.usage } : {}
2277
+ });
2278
+ try {
2279
+ return imageParts(
2280
+ metadata,
2281
+ await input.store.modelReference(metadata.artifact_id)
2282
+ );
2283
+ } catch {
2284
+ const {
2285
+ artifact_id,
2286
+ sha256,
2287
+ media_type,
2288
+ byte_size,
2289
+ width,
2290
+ height
2291
+ } = metadata;
2292
+ return [
2293
+ ...imageParts(metadata, {
2294
+ artifact_id,
2295
+ sha256,
2296
+ media_type,
2297
+ byte_size,
2298
+ width,
2299
+ height
2300
+ }),
2301
+ {
2302
+ type: "text",
2303
+ 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."
2304
+ }
2305
+ ];
2306
+ }
2307
+ } catch (error) {
2308
+ if (error instanceof ToolPermissionDenied || error instanceof ImageGenerationError)
2309
+ throw error;
2310
+ throw new ImageGenerationError(
2311
+ "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."
2312
+ );
2313
+ } finally {
2314
+ busy = false;
2315
+ }
2316
+ }
2317
+ })
2318
+ );
2319
+ return tools;
2320
+ }
2321
+
1223
2322
  // src/mcp/oauth.ts
1224
2323
  var DEFAULT_MCP_OAUTH_PORT = 1456;
1225
2324
  var DEFAULT_MCP_OAUTH_WAIT_TIMEOUT_MS = 18e4;
@@ -1606,15 +2705,12 @@ var withOpenRouterDynamicModel = (registry, llm, entry) => {
1606
2705
  const aliases = [llm.model, `${llm.provider}/${normalized}`].filter((value) => value !== normalized).filter((value, index, array) => array.indexOf(value) === index);
1607
2706
  const next = {
1608
2707
  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
- }
2708
+ aliasesByProvider: Object.fromEntries(
2709
+ Object.entries(registry.aliasesByProvider).map(([provider, aliases2]) => [
2710
+ provider,
2711
+ { ...aliases2 }
2712
+ ])
2713
+ )
1618
2714
  };
1619
2715
  registerModels(next, [
1620
2716
  {
@@ -1629,6 +2725,12 @@ var withOpenRouterDynamicModel = (registry, llm, entry) => {
1629
2725
  return next;
1630
2726
  };
1631
2727
  var buildModelRegistry = async (llm, options = {}) => {
2728
+ if (options.providers && Object.hasOwn(options.providers, llm.provider)) {
2729
+ const registry = buildConfiguredModelRegistry(options.providers);
2730
+ if (!isUsableModelSpec(resolveModel(registry, llm.model, llm.provider)))
2731
+ throw new Error(`Unknown configured model: ${llm.provider}/${llm.model}`);
2732
+ return registry;
2733
+ }
1632
2734
  const strict = options.strict ?? true;
1633
2735
  const metadataService = options.metadataService ?? new ModelMetadataServiceImpl({
1634
2736
  storagePathService: new StoragePathServiceImpl()
@@ -1660,16 +2762,17 @@ var buildModelRegistry = async (llm, options = {}) => {
1660
2762
  const baseRegistry = applyModelMetadata(DEFAULT_MODEL_REGISTRY, {
1661
2763
  models: entries
1662
2764
  });
2765
+ registerModels(baseRegistry, configuredModelSpecs(options.providers));
1663
2766
  return resolvedEntry ? withOpenRouterDynamicModel(baseRegistry, llm, resolvedEntry) : baseRegistry;
1664
2767
  };
1665
2768
 
1666
2769
  // src/permissions/approval-mode.ts
1667
2770
  import { promises as fs2 } from "fs";
1668
- import path3 from "path";
2771
+ import path6 from "path";
1669
2772
  import { parseApprovalMode } from "@codelia/shared-types";
1670
2773
  import { ProjectsPolicyStore } from "@codelia/storage";
1671
2774
  var normalizePath = async (value) => {
1672
- const absolute = path3.resolve(value);
2775
+ const absolute = path6.resolve(value);
1673
2776
  try {
1674
2777
  return await fs2.realpath(absolute);
1675
2778
  } catch {
@@ -1814,7 +2917,7 @@ import { promises as fs4 } from "fs";
1814
2917
  // src/sandbox/context.ts
1815
2918
  import crypto2 from "crypto";
1816
2919
  import { promises as fs3 } from "fs";
1817
- import path4 from "path";
2920
+ import path7 from "path";
1818
2921
  var SecurityError = class extends Error {
1819
2922
  constructor(message) {
1820
2923
  super(message);
@@ -1834,7 +2937,7 @@ var SandboxContext = class _SandboxContext {
1834
2937
  }
1835
2938
  static async create(rootDir, options = {}) {
1836
2939
  const sessionId = crypto2.randomUUID().slice(0, 8);
1837
- const root = rootDir ? path4.resolve(rootDir) : process.cwd();
2940
+ const root = rootDir ? path7.resolve(rootDir) : process.cwd();
1838
2941
  await fs3.mkdir(root, { recursive: true });
1839
2942
  return new _SandboxContext({
1840
2943
  rootDir: root,
@@ -1844,12 +2947,12 @@ var SandboxContext = class _SandboxContext {
1844
2947
  });
1845
2948
  }
1846
2949
  resolvePath(targetPath) {
1847
- const resolved = path4.isAbsolute(targetPath) ? path4.resolve(targetPath) : path4.resolve(this.workingDir, targetPath);
2950
+ const resolved = path7.isAbsolute(targetPath) ? path7.resolve(targetPath) : path7.resolve(this.workingDir, targetPath);
1848
2951
  if (this.approvalMode === "full-access") {
1849
2952
  return resolved;
1850
2953
  }
1851
- const relative = path4.relative(this.rootDir, resolved);
1852
- if (relative === "" || !relative.startsWith("..") && !path4.isAbsolute(relative)) {
2954
+ const relative = path7.relative(this.rootDir, resolved);
2955
+ if (relative === "" || !relative.startsWith("..") && !path7.isAbsolute(relative)) {
1853
2956
  return resolved;
1854
2957
  }
1855
2958
  throw new SecurityError(
@@ -2027,9 +3130,9 @@ var normalizeLanguage = (value) => {
2027
3130
  };
2028
3131
  var languageFromFilePath = (filePath) => {
2029
3132
  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\//, "");
3133
+ const path21 = filePath.trim().replace(/^["']|["']$/g, "");
3134
+ if (!path21 || path21 === "/dev/null") return void 0;
3135
+ const normalizedPath = path21.replace(/^a\//, "").replace(/^b\//, "");
2033
3136
  const lastSlash = Math.max(
2034
3137
  normalizedPath.lastIndexOf("/"),
2035
3138
  normalizedPath.lastIndexOf("\\")
@@ -2429,7 +3532,7 @@ var getSkillsResolver = async (ctx, key) => ctx.resolve(key);
2429
3532
  import crypto3 from "crypto";
2430
3533
  import { promises as fs5 } from "fs";
2431
3534
  import os2 from "os";
2432
- import path5 from "path";
3535
+ import path8 from "path";
2433
3536
  var DEFAULT_MARKERS2 = [".codelia", ".git", ".jj"];
2434
3537
  var SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2435
3538
  var MAX_SKILL_FILES = 200;
@@ -2455,38 +3558,38 @@ var exists2 = async (targetPath) => {
2455
3558
  };
2456
3559
  var normalizeMtime2 = (value) => Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 0;
2457
3560
  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 === "..") {
3561
+ const normalizedRoot = path8.resolve(rootDir);
3562
+ const normalizedTarget = path8.resolve(targetDir);
3563
+ const relative = path8.relative(normalizedRoot, normalizedTarget);
3564
+ if (relative.startsWith("..") || path8.isAbsolute(relative) || relative === "..") {
2462
3565
  return [];
2463
3566
  }
2464
- const parts = relative.split(path5.sep).filter((part) => part.length > 0);
3567
+ const parts = relative.split(path8.sep).filter((part) => part.length > 0);
2465
3568
  const chain = [normalizedRoot];
2466
3569
  let current = normalizedRoot;
2467
3570
  for (const part of parts) {
2468
- current = path5.join(current, part);
3571
+ current = path8.join(current, part);
2469
3572
  chain.push(current);
2470
3573
  }
2471
3574
  return chain;
2472
3575
  };
2473
3576
  var findRootByMarkers2 = async (workingDir, markers) => {
2474
- let current = path5.resolve(workingDir);
3577
+ let current = path8.resolve(workingDir);
2475
3578
  while (true) {
2476
3579
  for (const marker of markers) {
2477
- if (await exists2(path5.join(current, marker))) {
3580
+ if (await exists2(path8.join(current, marker))) {
2478
3581
  return current;
2479
3582
  }
2480
3583
  }
2481
- const parent = path5.dirname(current);
3584
+ const parent = path8.dirname(current);
2482
3585
  if (parent === current) {
2483
- return path5.resolve(workingDir);
3586
+ return path8.resolve(workingDir);
2484
3587
  }
2485
3588
  current = parent;
2486
3589
  }
2487
3590
  };
2488
3591
  var tryResolvePath = async (targetPath) => {
2489
- const resolved = path5.resolve(targetPath);
3592
+ const resolved = path8.resolve(targetPath);
2490
3593
  try {
2491
3594
  return { resolved, canonical: await fs5.realpath(resolved) };
2492
3595
  } catch {
@@ -2494,8 +3597,8 @@ var tryResolvePath = async (targetPath) => {
2494
3597
  }
2495
3598
  };
2496
3599
  var isWithin = (basePath, candidatePath) => {
2497
- const relative = path5.relative(basePath, candidatePath);
2498
- return relative === "" || !relative.startsWith("..") && !path5.isAbsolute(relative);
3600
+ const relative = path8.relative(basePath, candidatePath);
3601
+ return relative === "" || !relative.startsWith("..") && !path8.isAbsolute(relative);
2499
3602
  };
2500
3603
  var hashPath = (value) => crypto3.createHash("sha256").update(value).digest("hex").slice(0, 24);
2501
3604
  var parseFrontmatter = (content) => {
@@ -2544,12 +3647,12 @@ var SkillsResolver = class _SkillsResolver {
2544
3647
  }
2545
3648
  static async create(options) {
2546
3649
  const env = options.env ?? process.env;
2547
- const workingDir = path5.resolve(options.workingDir);
3650
+ const workingDir = path8.resolve(options.workingDir);
2548
3651
  const rootOverride = toTrimmed2(env.CODELIA_AGENTS_ROOT);
2549
3652
  const markers = parseMarkers2(env.CODELIA_AGENTS_MARKERS) ?? DEFAULT_MARKERS2;
2550
- const rootDir = rootOverride ? path5.resolve(rootOverride) : await findRootByMarkers2(workingDir, markers);
3653
+ const rootDir = rootOverride ? path8.resolve(rootOverride) : await findRootByMarkers2(workingDir, markers);
2551
3654
  const homeDir = toTrimmed2(env.HOME) ?? os2.homedir();
2552
- const userSkillsDir = path5.join(path5.resolve(homeDir), ".agents", "skills");
3655
+ const userSkillsDir = path8.join(path8.resolve(homeDir), ".agents", "skills");
2553
3656
  const resolver = new _SkillsResolver({
2554
3657
  workingDir,
2555
3658
  rootDir,
@@ -2572,7 +3675,7 @@ var SkillsResolver = class _SkillsResolver {
2572
3675
  return;
2573
3676
  }
2574
3677
  for (const entry of entries) {
2575
- const entryPath = path5.join(dirPath, entry.name);
3678
+ const entryPath = path8.join(dirPath, entry.name);
2576
3679
  if (entry.isDirectory()) {
2577
3680
  await walk(entryPath);
2578
3681
  continue;
@@ -2589,7 +3692,7 @@ var SkillsResolver = class _SkillsResolver {
2589
3692
  const directories = resolvePathChain2(this.rootDir, this.workingDir);
2590
3693
  const skillFiles = [];
2591
3694
  for (const directoryPath of directories) {
2592
- const skillsRoot = path5.join(directoryPath, ".agents", "skills");
3695
+ const skillsRoot = path8.join(directoryPath, ".agents", "skills");
2593
3696
  if (!await exists2(skillsRoot)) continue;
2594
3697
  const files = await this.collectSkillFilesInTree(skillsRoot);
2595
3698
  skillFiles.push(...files);
@@ -2646,8 +3749,8 @@ var SkillsResolver = class _SkillsResolver {
2646
3749
  }
2647
3750
  };
2648
3751
  }
2649
- const dir = path5.dirname(normalized.canonical);
2650
- if (path5.basename(dir) !== name) {
3752
+ const dir = path8.dirname(normalized.canonical);
3753
+ if (path8.basename(dir) !== name) {
2651
3754
  return {
2652
3755
  error: {
2653
3756
  path: normalized.canonical,
@@ -2796,7 +3899,7 @@ var SkillsResolver = class _SkillsResolver {
2796
3899
  }
2797
3900
  const catalog = await this.getCatalog();
2798
3901
  const normalizedQuery = query.toLowerCase();
2799
- const queryPathCandidate = path5.resolve(this.workingDir, query);
3902
+ const queryPathCandidate = path8.resolve(this.workingDir, query);
2800
3903
  const queryTokens = new Set(tokenize(normalizedQuery));
2801
3904
  const scored = [];
2802
3905
  for (const skill of catalog.skills) {
@@ -2854,7 +3957,7 @@ var SkillsResolver = class _SkillsResolver {
2854
3957
  try {
2855
3958
  rootReal = await fs5.realpath(skillDir);
2856
3959
  } catch {
2857
- rootReal = path5.resolve(skillDir);
3960
+ rootReal = path8.resolve(skillDir);
2858
3961
  }
2859
3962
  const files = [];
2860
3963
  let bytes = 0;
@@ -2872,7 +3975,7 @@ var SkillsResolver = class _SkillsResolver {
2872
3975
  }
2873
3976
  for (const entry of entries) {
2874
3977
  if (truncated) break;
2875
- const entryPath = path5.join(dirPath, entry.name);
3978
+ const entryPath = path8.join(dirPath, entry.name);
2876
3979
  if (entry.isSymbolicLink()) {
2877
3980
  continue;
2878
3981
  }
@@ -2887,7 +3990,7 @@ var SkillsResolver = class _SkillsResolver {
2887
3990
  try {
2888
3991
  realPath = await fs5.realpath(entryPath);
2889
3992
  } catch {
2890
- realPath = path5.resolve(entryPath);
3993
+ realPath = path8.resolve(entryPath);
2891
3994
  }
2892
3995
  if (!isWithin(rootReal, realPath)) {
2893
3996
  continue;
@@ -2916,7 +4019,7 @@ var SkillsResolver = class _SkillsResolver {
2916
4019
  return { files, truncated };
2917
4020
  }
2918
4021
  async resolveByPath(pathInput) {
2919
- const resolved = path5.isAbsolute(pathInput) ? path5.resolve(pathInput) : path5.resolve(this.workingDir, pathInput);
4022
+ const resolved = path8.isAbsolute(pathInput) ? path8.resolve(pathInput) : path8.resolve(this.workingDir, pathInput);
2920
4023
  const resolvedTry = await tryResolvePath(resolved);
2921
4024
  const byCanonical = this.catalog.skills.find(
2922
4025
  (entry) => entry.path === resolvedTry.canonical
@@ -2986,7 +4089,7 @@ var SkillsResolver = class _SkillsResolver {
2986
4089
  }
2987
4090
  const list = await this.listSkillFiles(selected.dir);
2988
4091
  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}`;
4092
+ const trailingSlashDir = selected.dir.endsWith(path8.sep) ? selected.dir : `${selected.dir}${path8.sep}`;
2990
4093
  const content = [
2991
4094
  `<skill_context name="${xmlEscape(selected.name)}" path="${xmlEscape(selected.path)}">`,
2992
4095
  skillBody.trimEnd(),
@@ -3029,13 +4132,13 @@ ${skillsCatalog}`;
3029
4132
  };
3030
4133
 
3031
4134
  // src/subagents/coordinator.ts
3032
- import { createHash, randomUUID as randomUUID2 } from "crypto";
4135
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "crypto";
3033
4136
  import { SUBAGENT_MAX_CONCURRENT_LIMIT } from "@codelia/config";
3034
- import { z as z3 } from "zod";
4137
+ import { z as z7 } from "zod";
3035
4138
 
3036
4139
  // src/subagents/parent-channel.ts
3037
- import { randomUUID } from "crypto";
3038
- import { z as z2 } from "zod";
4140
+ import { randomUUID as randomUUID2 } from "crypto";
4141
+ import { z as z6 } from "zod";
3039
4142
 
3040
4143
  // src/volatile-stores.ts
3041
4144
  var stringifyMessageContent = (value) => {
@@ -3157,9 +4260,9 @@ var subagentTaskInfo = (task) => ({
3157
4260
  });
3158
4261
 
3159
4262
  // 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()
4263
+ var shellInput = z6.object({
4264
+ command: z6.string().min(1).max(32768),
4265
+ timeout_seconds: z6.number().int().min(1).max(300).optional()
3163
4266
  }).strict();
3164
4267
  var createParentChannel = ({
3165
4268
  tasks,
@@ -3204,11 +4307,11 @@ var createParentChannel = ({
3204
4307
  throw new Error("sender_finished");
3205
4308
  }
3206
4309
  if (operation === "send") {
3207
- const params2 = z2.object({ recipient: z2.string().min(1), content: z2.string() }).strict().parse(raw);
4310
+ const params2 = z6.object({ recipient: z6.string().min(1), content: z6.string() }).strict().parse(raw);
3208
4311
  return mailbox.send(owner, sender, params2.recipient, params2.content);
3209
4312
  }
3210
4313
  if (operation === "receive") {
3211
- const params2 = z2.object({ wait_seconds: z2.number().min(0).max(120).optional() }).strict().parse(raw);
4314
+ const params2 = z6.object({ wait_seconds: z6.number().min(0).max(120).optional() }).strict().parse(raw);
3212
4315
  return mailbox.receive(owner, sender, params2.wait_seconds ?? 0, signal);
3213
4316
  }
3214
4317
  if (operation === "list")
@@ -3244,7 +4347,7 @@ var createParentChannel = ({
3244
4347
  signal?.throwIfAborted();
3245
4348
  const task = await tasks.spawn(
3246
4349
  {
3247
- task_id: randomUUID(),
4350
+ task_id: randomUUID2(),
3248
4351
  kind: "shell",
3249
4352
  parent_session_id: owner,
3250
4353
  parent_tool_call_id: sender,
@@ -3284,38 +4387,38 @@ var createParentChannel = ({
3284
4387
 
3285
4388
  // src/subagents/coordinator.ts
3286
4389
  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(
4390
+ var subagentSpawnSchema = z7.object({
4391
+ kind: z7.literal("subagent").default("subagent"),
4392
+ prompt: z7.string().trim().min(1).max(32768).describe(
3290
4393
  "Self-contained delegated task; child has no parent conversation. Maximum 32768 characters."
3291
4394
  ),
3292
4395
  name: subagentNameSchema.describe(
3293
4396
  "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
4397
  ),
3295
- profile: z3.string().trim().min(1).max(64).optional().describe(
4398
+ profile: z7.string().trim().min(1).max(64).optional().describe(
3296
4399
  "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
4400
  ),
3298
4401
  model: subagentModelSelectionSchema.optional().describe(
3299
4402
  "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
4403
  ),
3301
- label: z3.string().max(80).optional().describe(
4404
+ label: z7.string().max(80).optional().describe(
3302
4405
  "Work assignment, such as API implementation; separate from the child's agent name."
3303
4406
  ),
3304
- background: z3.boolean().optional().describe(
4407
+ background: z7.boolean().optional().describe(
3305
4408
  "Default true: return task_id immediately. False attaches a cancellable wait; the child survives parent-turn stop."
3306
4409
  ),
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(
4410
+ context_mode: z7.literal("fresh").optional().describe("Only fresh sessions are supported."),
4411
+ workspace_mode: z7.literal("live_workspace").optional(),
4412
+ workspace_access: z7.enum(["read-only", "read-write"]).optional().describe(
3310
4413
  "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
4414
  ),
3312
- tool_allowlist: z3.array(z3.enum(WRITABLE_TOOLS)).max(7).optional().describe(
4415
+ tool_allowlist: z7.array(z7.enum(WRITABLE_TOOLS)).max(7).optional().describe(
3313
4416
  "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
4417
  ),
3315
- max_steps: z3.number().int().min(1).max(200).optional().describe(
4418
+ max_steps: z7.number().int().min(1).max(200).optional().describe(
3316
4419
  "Child iteration limit; default 50. Exhaustion returns failed/max_steps with partial results."
3317
4420
  ),
3318
- timeout_seconds: z3.number().int().min(1).max(3600).optional().describe(
4421
+ timeout_seconds: z7.number().int().min(1).max(3600).optional().describe(
3319
4422
  "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
4423
  )
3321
4424
  }).strict().superRefine((input, ctx) => {
@@ -3362,7 +4465,7 @@ var AgentTreeCoordinator = class {
3362
4465
  });
3363
4466
  }
3364
4467
  configure(parent) {
3365
- z3.number().int().min(1).max(SUBAGENT_MAX_CONCURRENT_LIMIT).parse(parent.subagent?.max_concurrent ?? DEFAULT_MAX_CONCURRENT);
4468
+ z7.number().int().min(1).max(SUBAGENT_MAX_CONCURRENT_LIMIT).parse(parent.subagent?.max_concurrent ?? DEFAULT_MAX_CONCURRENT);
3366
4469
  this.parent = structuredClone(parent);
3367
4470
  }
3368
4471
  isAvailable() {
@@ -3410,7 +4513,7 @@ var AgentTreeCoordinator = class {
3410
4513
  for (const tool of allowlist)
3411
4514
  if (permissions.evaluate(tool, "{}").decision === "deny")
3412
4515
  throw new Error("delegated tool denied by parent policy");
3413
- const task_id = randomUUID2();
4516
+ const task_id = randomUUID3();
3414
4517
  const permission = {
3415
4518
  tool_allowlist: allowlist,
3416
4519
  workspace_access: workspaceAccess,
@@ -3431,7 +4534,7 @@ var AgentTreeCoordinator = class {
3431
4534
  0
3432
4535
  ) + 1,
3433
4536
  context_mode: "fresh",
3434
- effective_policy_id: createHash("sha256").update(JSON.stringify({ permission, root: parent.workspace_root })).digest("hex"),
4537
+ effective_policy_id: createHash2("sha256").update(JSON.stringify({ permission, root: parent.workspace_root })).digest("hex"),
3435
4538
  workspace_lease_id: task_id
3436
4539
  };
3437
4540
  const profileName = input.model ? void 0 : input.profile ?? parent.subagent?.default_profile;
@@ -3441,6 +4544,10 @@ var AgentTreeCoordinator = class {
3441
4544
  }
3442
4545
  const requestedModel = input.model ?? (profileName ? profiles?.[profileName].model : void 0);
3443
4546
  const selectedModel = requestedModel ? subagentModelSelectionSchema.parse(requestedModel) : void 0;
4547
+ const selectedProvider = selectedModel?.provider ?? parent.model.provider;
4548
+ if (selectedProvider && !configuredProviders(parent.model.providers).includes(selectedProvider)) {
4549
+ throw new Error(`Unsupported subagent provider: ${selectedProvider}`);
4550
+ }
3444
4551
  const launch = {
3445
4552
  version: 1,
3446
4553
  task_id,
@@ -3449,7 +4556,8 @@ var AgentTreeCoordinator = class {
3449
4556
  workspace_root: parent.workspace_root,
3450
4557
  model: selectedModel ? {
3451
4558
  ...selectedModel,
3452
- provider: selectedModel.provider ?? parent.model.provider
4559
+ ...parent.model.providers ? { providers: parent.model.providers } : {},
4560
+ provider: selectedProvider
3453
4561
  } : parent.model,
3454
4562
  permission
3455
4563
  };
@@ -3520,8 +4628,8 @@ var AgentTreeCoordinator = class {
3520
4628
  };
3521
4629
 
3522
4630
  // src/tools/search.ts
3523
- import { defineTool } from "@codelia/core";
3524
- import { z as z4 } from "zod";
4631
+ import { defineTool as defineTool2 } from "@codelia/core";
4632
+ import { z as z8 } from "zod";
3525
4633
  var normalizeDomain = (value) => value.trim().toLowerCase().replace(/\.+$/, "");
3526
4634
  var shouldKeepUrl = (url, allowedDomains) => {
3527
4635
  if (!allowedDomains.length) return true;
@@ -3637,14 +4745,14 @@ var runBraveSearch = async (query, maxResults, allowedDomains, apiKey) => {
3637
4745
  const parsed = parseBrave(payload);
3638
4746
  return normalizeEntries(parsed, allowedDomains, maxResults);
3639
4747
  };
3640
- var createSearchTool = (options) => defineTool({
4748
+ var createSearchTool = (options) => defineTool2({
3641
4749
  name: "search",
3642
4750
  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.")
4751
+ input: z8.object({
4752
+ query: z8.string().min(1).describe("Search query."),
4753
+ max_results: z8.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
4754
+ backend: z8.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
4755
+ allowed_domains: z8.array(z8.string().min(1)).optional().describe("Optional allowlist of domains.")
3648
4756
  }),
3649
4757
  execute: async (input) => {
3650
4758
  const backend = input.backend ?? options.defaultBackend;
@@ -3726,6 +4834,7 @@ var loadRuntimeHostTools = async (providers) => {
3726
4834
  var composeRuntimeTools = async ({
3727
4835
  provider,
3728
4836
  baseTools,
4837
+ imageTools = [],
3729
4838
  mcpTools,
3730
4839
  hostTools,
3731
4840
  searchConfig
@@ -3745,7 +4854,17 @@ var composeRuntimeTools = async ({
3745
4854
  braveApiKeyEnv: searchConfig.local.braveApiKeyEnv
3746
4855
  })
3747
4856
  ] : [];
3748
- const tools = [...baseTools, ...localSearchTools, ...mcpTools, ...hostTools];
4857
+ const tools = [
4858
+ ...baseTools,
4859
+ ...imageTools,
4860
+ ...localSearchTools,
4861
+ ...mcpTools,
4862
+ ...hostTools
4863
+ ];
4864
+ for (const imageTool of imageTools) {
4865
+ if (tools.filter((tool) => tool.name === imageTool.name).length !== 1)
4866
+ throw new Error(`Image tool name conflict: ${imageTool.name}`);
4867
+ }
3749
4868
  return {
3750
4869
  tools,
3751
4870
  toolDefinitions: [...tools.map((tool) => tool.definition), ...hostedTools],
@@ -3759,13 +4878,13 @@ var composeRuntimeTools = async ({
3759
4878
  };
3760
4879
 
3761
4880
  // 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({
4881
+ import { defineTool as defineTool3 } from "@codelia/core";
4882
+ import { z as z9 } from "zod";
4883
+ var createAgentsResolveTool = (sandboxKey, agentsResolverKey) => defineTool3({
3765
4884
  name: "agents_resolve",
3766
4885
  description: "Resolve AGENTS.md files applicable to a target path (metadata only).",
3767
- input: z5.object({
3768
- path: z5.string().describe(
4886
+ input: z9.object({
4887
+ path: z9.string().describe(
3769
4888
  "Target file or directory path to resolve AGENTS.md scope for."
3770
4889
  )
3771
4890
  }),
@@ -3799,9 +4918,9 @@ var createAgentsResolveTool = (sandboxKey, agentsResolverKey) => defineTool2({
3799
4918
 
3800
4919
  // src/tools/apply-patch.ts
3801
4920
  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";
4921
+ import path9 from "path";
4922
+ import { defineTool as defineTool4 } from "@codelia/core";
4923
+ import { z as z10 } from "zod";
3805
4924
 
3806
4925
  // src/tools/diff-payload.ts
3807
4926
  import crypto4 from "crypto";
@@ -4352,7 +5471,7 @@ var applyPreparedChanges = async (changes) => {
4352
5471
  continue;
4353
5472
  }
4354
5473
  if (change.kind === "move" && change.resolvedMoveTo) {
4355
- await fs6.mkdir(path6.dirname(change.resolvedMoveTo), { recursive: true });
5474
+ await fs6.mkdir(path9.dirname(change.resolvedMoveTo), { recursive: true });
4356
5475
  await fs6.writeFile(change.resolvedMoveTo, change.after, "utf8");
4357
5476
  if (typeof change.sourceMode === "number") {
4358
5477
  await fs6.chmod(change.resolvedMoveTo, change.sourceMode);
@@ -4360,7 +5479,7 @@ var applyPreparedChanges = async (changes) => {
4360
5479
  await fs6.unlink(change.resolvedPath);
4361
5480
  continue;
4362
5481
  }
4363
- await fs6.mkdir(path6.dirname(change.resolvedPath), { recursive: true });
5482
+ await fs6.mkdir(path9.dirname(change.resolvedPath), { recursive: true });
4364
5483
  await fs6.writeFile(change.resolvedPath, change.after, "utf8");
4365
5484
  }
4366
5485
  };
@@ -4401,12 +5520,12 @@ var summarizeChanges = (changes, dryRun) => {
4401
5520
  files: fileSummaries
4402
5521
  };
4403
5522
  };
4404
- var createApplyPatchTool = (sandboxKey, outputCacheStore) => defineTool3({
5523
+ var createApplyPatchTool = (sandboxKey, outputCacheStore) => defineTool4({
4405
5524
  name: "apply_patch",
4406
5525
  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.")
5526
+ input: z10.object({
5527
+ patch: z10.string().min(1).describe("Full patch text between *** Begin Patch and *** End Patch."),
5528
+ dry_run: z10.boolean().optional().describe("Preview the patch without writing files. Default false.")
4410
5529
  }),
4411
5530
  execute: async (input, ctx) => {
4412
5531
  const dryRun = input.dry_run ?? false;
@@ -4437,13 +5556,13 @@ var createApplyPatchTool = (sandboxKey, outputCacheStore) => defineTool3({
4437
5556
  });
4438
5557
 
4439
5558
  // src/tools/done.ts
4440
- import { defineTool as defineTool4, TaskComplete } from "@codelia/core";
4441
- import { z as z7 } from "zod";
4442
- var createDoneTool = () => defineTool4({
5559
+ import { defineTool as defineTool5, TaskComplete } from "@codelia/core";
5560
+ import { z as z11 } from "zod";
5561
+ var createDoneTool = () => defineTool5({
4443
5562
  name: "done",
4444
5563
  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.")
5564
+ input: z11.object({
5565
+ message: z11.string().describe("Final user-facing completion message.")
4447
5566
  }),
4448
5567
  execute: async (input) => {
4449
5568
  throw new TaskComplete(input.message);
@@ -4452,9 +5571,9 @@ var createDoneTool = () => defineTool4({
4452
5571
 
4453
5572
  // src/tools/edit.ts
4454
5573
  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";
5574
+ import path10 from "path";
5575
+ import { defineTool as defineTool6 } from "@codelia/core";
5576
+ import { z as z12 } from "zod";
4458
5577
  var trimLine = (line) => line.replace(/\r$/, "").trim();
4459
5578
  var lineRangeToIndices = (lines, startLine, lineCount) => {
4460
5579
  let startIndex = 0;
@@ -4561,23 +5680,23 @@ var applyReplacements = (content, matches, replacement) => {
4561
5680
  }
4562
5681
  return next;
4563
5682
  };
4564
- var createEditTool = (sandboxKey, outputCacheStore) => defineTool5({
5683
+ var createEditTool = (sandboxKey, outputCacheStore) => defineTool6({
4565
5684
  name: "edit",
4566
5685
  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(
5686
+ input: z12.object({
5687
+ file_path: z12.string().describe(
4569
5688
  "File path. Sandbox-bounded unless full-access mode is active."
4570
5689
  ),
4571
- old_string: z8.string().describe(
5690
+ old_string: z12.string().describe(
4572
5691
  "Text to find. Use empty string to replace the whole file content."
4573
5692
  ),
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(
5693
+ new_string: z12.string().describe("Replacement text."),
5694
+ replace_all: z12.boolean().optional().describe("Replace all matches when true. Default false."),
5695
+ match_mode: z12.enum(["exact", "line_trimmed", "block_anchor", "auto"]).optional().describe(
4577
5696
  "Match strategy: exact, line_trimmed, block_anchor, or auto (tries exact -> line_trimmed -> block_anchor). Default auto."
4578
5697
  ),
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."),
5698
+ expected_replacements: z12.number().int().nonnegative().optional().describe("Expected replacement count (guard)."),
5699
+ dry_run: z12.boolean().optional().describe("Preview diff only when true. Default false."),
4581
5700
  expected_hash: expectedContentHashSchema
4582
5701
  }),
4583
5702
  execute: async (input, ctx) => {
@@ -4678,7 +5797,7 @@ var createEditTool = (sandboxKey, outputCacheStore) => defineTool5({
4678
5797
  };
4679
5798
  }
4680
5799
  try {
4681
- await fs7.mkdir(path7.dirname(resolved), { recursive: true });
5800
+ await fs7.mkdir(path10.dirname(resolved), { recursive: true });
4682
5801
  await fs7.writeFile(resolved, nextContent, "utf8");
4683
5802
  } catch (error) {
4684
5803
  throw new Error(`Error editing file: ${String(error)}`);
@@ -4694,14 +5813,14 @@ var createEditTool = (sandboxKey, outputCacheStore) => defineTool5({
4694
5813
  });
4695
5814
 
4696
5815
  // src/tools/lane.ts
4697
- import { defineTool as defineTool6 } from "@codelia/core";
4698
- import { z as z9 } from "zod";
5816
+ import { defineTool as defineTool7 } from "@codelia/core";
5817
+ import { z as z13 } from "zod";
4699
5818
 
4700
5819
  // src/lanes/manager.ts
4701
5820
  import crypto5 from "crypto";
4702
5821
  import { promises as fs9 } from "fs";
4703
5822
  import os3 from "os";
4704
- import path9 from "path";
5823
+ import path12 from "path";
4705
5824
 
4706
5825
  // src/lanes/command.ts
4707
5826
  import { spawn as spawn3 } from "child_process";
@@ -4784,8 +5903,8 @@ ${stdout}`.trim();
4784
5903
 
4785
5904
  // src/lanes/registry.ts
4786
5905
  import { promises as fs8 } from "fs";
4787
- import path8 from "path";
4788
- import { resolveStoragePaths } from "@codelia/storage";
5906
+ import path11 from "path";
5907
+ import { resolveStoragePaths as resolveStoragePaths2 } from "@codelia/storage";
4789
5908
  var REGISTRY_DIRNAME = "lanes";
4790
5909
  var REGISTRY_FILENAME = "registry.json";
4791
5910
  var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
@@ -4806,9 +5925,9 @@ var readJsonFile = async (filePath) => {
4806
5925
  }
4807
5926
  };
4808
5927
  var atomicWrite = async (filePath, payload) => {
4809
- const dir = path8.dirname(filePath);
4810
- const base = path8.basename(filePath);
4811
- const tmp = path8.join(
5928
+ const dir = path11.dirname(filePath);
5929
+ const base = path11.basename(filePath);
5930
+ const tmp = path11.join(
4812
5931
  dir,
4813
5932
  `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
4814
5933
  );
@@ -4822,11 +5941,11 @@ var LaneRegistryStore = class {
4822
5941
  this.registryPath = registryPath;
4823
5942
  return;
4824
5943
  }
4825
- const root = resolveStoragePaths().root;
4826
- this.registryPath = path8.join(root, REGISTRY_DIRNAME, REGISTRY_FILENAME);
5944
+ const root = resolveStoragePaths2().root;
5945
+ this.registryPath = path11.join(root, REGISTRY_DIRNAME, REGISTRY_FILENAME);
4827
5946
  }
4828
5947
  async ensureDir() {
4829
- await fs8.mkdir(path8.dirname(this.registryPath), { recursive: true });
5948
+ await fs8.mkdir(path11.dirname(this.registryPath), { recursive: true });
4830
5949
  }
4831
5950
  async readAll() {
4832
5951
  await this.ensureDir();
@@ -4926,7 +6045,7 @@ var LaneManager = class {
4926
6045
  this.now = options.now ?? nowIso2;
4927
6046
  this.randomId = options.randomId ?? (() => crypto5.randomUUID());
4928
6047
  this.launchCommand = options.launchCommand ?? process.env.CODELIA_LANE_LAUNCH_COMMAND?.trim() ?? "codelia";
4929
- this.defaultWorktreeRoot = options.defaultWorktreeRoot ?? path9.join(os3.homedir(), ".codelia", "worktrees");
6048
+ this.defaultWorktreeRoot = options.defaultWorktreeRoot ?? path12.join(os3.homedir(), ".codelia", "worktrees");
4930
6049
  }
4931
6050
  async cmd(command, args, options) {
4932
6051
  debugLog(`lane.cmd ${command} ${args.join(" ")}`);
@@ -5049,9 +6168,9 @@ var LaneManager = class {
5049
6168
  "rev-parse",
5050
6169
  "--git-common-dir"
5051
6170
  ]);
5052
- const commonDir = path9.resolve(worktreePath, stdout.trim());
5053
- if (path9.basename(commonDir) === ".git") {
5054
- return path9.dirname(commonDir);
6171
+ const commonDir = path12.resolve(worktreePath, stdout.trim());
6172
+ if (path12.basename(commonDir) === ".git") {
6173
+ return path12.dirname(commonDir);
5055
6174
  }
5056
6175
  return await this.resolveRepoRoot(worktreePath);
5057
6176
  }
@@ -5093,10 +6212,10 @@ var LaneManager = class {
5093
6212
  await this.preflightBackend(backend);
5094
6213
  const repoRoot = await this.resolveRepoRoot(options.workingDir);
5095
6214
  const laneId = this.randomId();
5096
- const slug = toSlug(taskId);
6215
+ const slug2 = toSlug(taskId);
5097
6216
  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}`);
6217
+ const branchName = `lane/${slug2}-${shortId}`;
6218
+ const worktreePath = input.worktree_path ? path12.resolve(options.workingDir, input.worktree_path) : path12.join(this.defaultWorktreeRoot, `${slug2}-${shortId}`);
5100
6219
  const muxTarget = `codelia-lane-${shortId}`;
5101
6220
  const createdAt = this.now();
5102
6221
  const record = {
@@ -5114,7 +6233,7 @@ var LaneManager = class {
5114
6233
  };
5115
6234
  await this.registry.upsert(record);
5116
6235
  try {
5117
- await fs9.mkdir(path9.dirname(worktreePath), { recursive: true });
6236
+ await fs9.mkdir(path12.dirname(worktreePath), { recursive: true });
5118
6237
  await this.cmd("git", [
5119
6238
  "-C",
5120
6239
  repoRoot,
@@ -5267,7 +6386,7 @@ var LaneManager = class {
5267
6386
 
5268
6387
  // src/tools/lane.ts
5269
6388
  var laneManager = new LaneManager();
5270
- var backendSchema = z9.enum(["tmux", "zellij"]);
6389
+ var backendSchema = z13.enum(["tmux", "zellij"]);
5271
6390
  var formatError = (error) => {
5272
6391
  if (error instanceof LaneManagerError) {
5273
6392
  return new Error(`${error.code}: ${error.message}`);
@@ -5294,17 +6413,17 @@ var buildLaneHints = (lane) => {
5294
6413
  }
5295
6414
  };
5296
6415
  };
5297
- var createLaneCreateTool = (sandboxKey) => defineTool6({
6416
+ var createLaneCreateTool = (sandboxKey) => defineTool7({
5298
6417
  name: "lane_create",
5299
6418
  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(
6419
+ input: z13.object({
6420
+ task_id: z13.string().describe("Task identifier."),
6421
+ base_ref: z13.string().optional().describe("Base git ref. Default: HEAD."),
6422
+ worktree_path: z13.string().optional().describe(
5304
6423
  "Optional worktree path override. Default: ~/.codelia/worktrees/<task-slug>-<lane-id8>."
5305
6424
  ),
5306
6425
  mux_backend: backendSchema.optional().describe("Multiplexer backend. Default: tmux."),
5307
- seed_context: z9.string().optional().describe("Optional initial text context.")
6426
+ seed_context: z13.string().optional().describe("Optional initial text context.")
5308
6427
  }),
5309
6428
  execute: async (input, ctx) => {
5310
6429
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -5329,11 +6448,11 @@ var createLaneCreateTool = (sandboxKey) => defineTool6({
5329
6448
  }
5330
6449
  }
5331
6450
  });
5332
- var createLaneListTool = (sandboxKey) => defineTool6({
6451
+ var createLaneListTool = (sandboxKey) => defineTool7({
5333
6452
  name: "lane_list",
5334
6453
  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.")
6454
+ input: z13.object({
6455
+ include_closed: z13.boolean().optional().describe("Include closed lanes. Default: false.")
5337
6456
  }),
5338
6457
  execute: async (input, ctx) => {
5339
6458
  await getSandboxContext(ctx, sandboxKey);
@@ -5353,11 +6472,11 @@ var createLaneListTool = (sandboxKey) => defineTool6({
5353
6472
  }
5354
6473
  }
5355
6474
  });
5356
- var createLaneStatusTool = (sandboxKey) => defineTool6({
6475
+ var createLaneStatusTool = (sandboxKey) => defineTool7({
5357
6476
  name: "lane_status",
5358
6477
  description: "Get Task lane status and backend liveness.",
5359
- input: z9.object({
5360
- lane_id: z9.string().describe("Lane id.")
6478
+ input: z13.object({
6479
+ lane_id: z13.string().describe("Lane id.")
5361
6480
  }),
5362
6481
  execute: async (input, ctx) => {
5363
6482
  await getSandboxContext(ctx, sandboxKey);
@@ -5372,13 +6491,13 @@ var createLaneStatusTool = (sandboxKey) => defineTool6({
5372
6491
  }
5373
6492
  }
5374
6493
  });
5375
- var createLaneCloseTool = (sandboxKey) => defineTool6({
6494
+ var createLaneCloseTool = (sandboxKey) => defineTool7({
5376
6495
  name: "lane_close",
5377
6496
  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.")
6497
+ input: z13.object({
6498
+ lane_id: z13.string().describe("Lane id."),
6499
+ remove_worktree: z13.boolean().optional().describe("Remove worktree. Default: true."),
6500
+ force: z13.boolean().optional().describe("Force close/cleanup. Default: false.")
5382
6501
  }),
5383
6502
  execute: async (input, ctx) => {
5384
6503
  await getSandboxContext(ctx, sandboxKey);
@@ -5397,13 +6516,13 @@ var createLaneCloseTool = (sandboxKey) => defineTool6({
5397
6516
  }
5398
6517
  }
5399
6518
  });
5400
- var createLaneGcTool = (sandboxKey) => defineTool6({
6519
+ var createLaneGcTool = (sandboxKey) => defineTool7({
5401
6520
  name: "lane_gc",
5402
6521
  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.")
6522
+ input: z13.object({
6523
+ idle_ttl_minutes: z13.number().int().positive().describe("Idle TTL in minutes."),
6524
+ remove_worktree: z13.boolean().optional().describe("Remove worktree on close. Default: false."),
6525
+ force: z13.boolean().optional().describe("Force cleanup for dirty worktrees. Default: false.")
5407
6526
  }),
5408
6527
  execute: async (input, ctx) => {
5409
6528
  await getSandboxContext(ctx, sandboxKey);
@@ -5421,8 +6540,8 @@ var createLaneGcTool = (sandboxKey) => defineTool6({
5421
6540
 
5422
6541
  // src/tools/read.ts
5423
6542
  import { promises as fs10 } from "fs";
5424
- import { defineTool as defineTool7 } from "@codelia/core";
5425
- import { z as z10 } from "zod";
6543
+ import { defineTool as defineTool8 } from "@codelia/core";
6544
+ import { z as z14 } from "zod";
5426
6545
  var DEFAULT_READ_LIMIT = 2e3;
5427
6546
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
5428
6547
  var DEFAULT_MAX_BYTES = 64 * 1024;
@@ -5476,15 +6595,15 @@ var buildTruncatedLinesSummary = (lineNumbers) => {
5476
6595
  }
5477
6596
  return `[truncated lines: ${lineNumbers.join(", ")}]`;
5478
6597
  };
5479
- var createReadTool = (sandboxKey) => defineTool7({
6598
+ var createReadTool = (sandboxKey) => defineTool8({
5480
6599
  name: "read",
5481
6600
  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(
6601
+ input: z14.object({
6602
+ file_path: z14.string().describe(
5484
6603
  "Text file path. Sandbox-bounded unless full-access mode is active."
5485
6604
  ),
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.")
6605
+ offset: z14.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
6606
+ limit: z14.number().int().positive().optional().describe("Max preview lines to read. Default 2000.")
5488
6607
  }),
5489
6608
  execute: async (input, ctx) => {
5490
6609
  let resolved;
@@ -5583,24 +6702,24 @@ For full long-line content, use read_line({"file_path":${JSON.stringify(input.fi
5583
6702
 
5584
6703
  // src/tools/read-line.ts
5585
6704
  import { promises as fs11 } from "fs";
5586
- import { defineTool as defineTool8 } from "@codelia/core";
5587
- import { z as z11 } from "zod";
6705
+ import { defineTool as defineTool9 } from "@codelia/core";
6706
+ import { z as z15 } from "zod";
5588
6707
  var DEFAULT_CHAR_LIMIT = 1e4;
5589
6708
  var MAX_CHAR_LIMIT = 1e5;
5590
6709
  var GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, {
5591
6710
  granularity: "grapheme"
5592
6711
  });
5593
6712
  var splitGraphemes = (value) => Array.from(GRAPHEME_SEGMENTER.segment(value), ({ segment }) => segment);
5594
- var createReadLineTool = (sandboxKey) => defineTool8({
6713
+ var createReadLineTool = (sandboxKey) => defineTool9({
5595
6714
  name: "read_line",
5596
6715
  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(
6716
+ input: z15.object({
6717
+ file_path: z15.string().describe(
5599
6718
  "Text file path. Sandbox-bounded unless full-access mode is active."
5600
6719
  ),
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(
6720
+ line_number: z15.number().int().positive().describe("1-based line number to read."),
6721
+ char_offset: z15.number().int().nonnegative().optional().describe("0-based grapheme offset in the target line. Default 0."),
6722
+ char_limit: z15.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe(
5604
6723
  `Max graphemes to return. Default 10000, Max ${MAX_CHAR_LIMIT}.`
5605
6724
  )
5606
6725
  }),
@@ -5661,9 +6780,9 @@ read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${input.
5661
6780
 
5662
6781
  // src/tools/shell.ts
5663
6782
  import crypto6 from "crypto";
5664
- import { defineTool as defineTool9 } from "@codelia/core";
6783
+ import { defineTool as defineTool10 } from "@codelia/core";
5665
6784
  import { ToolOutputCacheStoreImpl } from "@codelia/storage";
5666
- import { z as z12 } from "zod";
6785
+ import { z as z16 } from "zod";
5667
6786
 
5668
6787
  // src/tools/session-context.ts
5669
6788
  var createToolSessionContextKey = (getSessionId) => ({
@@ -5716,37 +6835,37 @@ var SHELL_LIST_DEFAULT_LIMIT = 20;
5716
6835
  var SHELL_LIST_MAX_LIMIT = 100;
5717
6836
  var SHELL_LOGS_MAX_TAIL_LINES = 500;
5718
6837
  var SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT = false;
5719
- var shellStdinModeSchema = z12.enum(["closed", "pipe"]);
5720
- var shellStateSchema = z12.enum([
6838
+ var shellStdinModeSchema = z16.enum(["closed", "pipe"]);
6839
+ var shellStateSchema = z16.enum([
5721
6840
  "queued",
5722
6841
  "running",
5723
6842
  "completed",
5724
6843
  "failed",
5725
6844
  "cancelled"
5726
6845
  ]);
5727
- var shellRunSchema = z12.object({
5728
- command: z12.string().describe(
6846
+ var shellRunSchema = z16.object({
6847
+ command: z16.string().describe(
5729
6848
  "Shell command to execute as a runtime-managed child process in the current workspace."
5730
6849
  ),
5731
- label: z12.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
6850
+ label: z16.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
5732
6851
  `Short label used to build the returned task key. Max ${SHELL_LABEL_MAX_CHARS} chars.`
5733
6852
  ),
5734
- timeout: z12.number().int().positive().optional().describe(
6853
+ timeout: z16.number().int().positive().optional().describe(
5735
6854
  `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
6855
  ),
5737
- detached_wait: z12.boolean().optional().describe(
6856
+ detached_wait: z16.boolean().optional().describe(
5738
6857
  "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
6858
  ),
5740
6859
  stdin_mode: shellStdinModeSchema.optional().describe(
5741
6860
  "Child stdin: closed (default) or pipe. pipe requires detached_wait=true and shell_stdin_write."
5742
6861
  ),
5743
- include_stderr_on_success: z12.boolean().optional().describe(
6862
+ include_stderr_on_success: z16.boolean().optional().describe(
5744
6863
  `Include stderr on success. Default: ${String(SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT)}.`
5745
6864
  )
5746
6865
  }).superRefine((input, ctx) => {
5747
6866
  if (input.stdin_mode === "pipe" && input.detached_wait !== true) {
5748
6867
  ctx.addIssue({
5749
- code: z12.ZodIssueCode.custom,
6868
+ code: z16.ZodIssueCode.custom,
5750
6869
  path: ["stdin_mode"],
5751
6870
  message: "stdin_mode=pipe requires detached_wait=true."
5752
6871
  });
@@ -5757,7 +6876,7 @@ var shellRunSchema = z12.object({
5757
6876
  if (input.detached_wait ?? false) {
5758
6877
  if (input.timeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
5759
6878
  ctx.addIssue({
5760
- code: z12.ZodIssueCode.custom,
6879
+ code: z16.ZodIssueCode.custom,
5761
6880
  path: ["timeout"],
5762
6881
  message: `Detached-wait timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
5763
6882
  });
@@ -5766,61 +6885,61 @@ var shellRunSchema = z12.object({
5766
6885
  }
5767
6886
  if (input.timeout > MAX_TIMEOUT_SECONDS) {
5768
6887
  ctx.addIssue({
5769
- code: z12.ZodIssueCode.custom,
6888
+ code: z16.ZodIssueCode.custom,
5770
6889
  path: ["timeout"],
5771
6890
  message: `Foreground timeout must be ${MAX_TIMEOUT_SECONDS} seconds or less.`
5772
6891
  });
5773
6892
  }
5774
6893
  });
5775
- var shellTaskKeySchema = z12.object({
5776
- key: z12.string().describe("Canonical shell task key returned by shell or shell_list.")
6894
+ var shellTaskKeySchema = z16.object({
6895
+ key: z16.string().describe("Canonical shell task key returned by shell or shell_list.")
5777
6896
  });
5778
6897
  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.")
6898
+ text: z16.string().describe("UTF-8 text to write to the task stdin pipe."),
6899
+ append_newline: z16.boolean().optional().describe("Append one newline before writing. Default: false."),
6900
+ close: z16.boolean().optional().describe("Close stdin after this write completes. Default: false.")
5782
6901
  }).superRefine((input, ctx) => {
5783
6902
  const close = input.close ?? false;
5784
6903
  const text = `${input.text}${input.append_newline ? "\n" : ""}`;
5785
6904
  if (text.length === 0 && !close) {
5786
6905
  ctx.addIssue({
5787
- code: z12.ZodIssueCode.custom,
6906
+ code: z16.ZodIssueCode.custom,
5788
6907
  path: ["text"],
5789
6908
  message: "text must be non-empty unless close=true."
5790
6909
  });
5791
6910
  }
5792
6911
  if (utf8ByteLength3(text) > MAX_STDIN_WRITE_BYTES) {
5793
6912
  ctx.addIssue({
5794
- code: z12.ZodIssueCode.custom,
6913
+ code: z16.ZodIssueCode.custom,
5795
6914
  path: ["text"],
5796
6915
  message: `stdin writes are limited to ${MAX_STDIN_WRITE_BYTES} UTF-8 bytes after append_newline.`
5797
6916
  });
5798
6917
  }
5799
6918
  });
5800
6919
  var shellSuccessStderrSchema = {
5801
- include_stderr_on_success: z12.boolean().optional().describe(
6920
+ include_stderr_on_success: z16.boolean().optional().describe(
5802
6921
  `Include stderr on success. Default: ${String(SHELL_INCLUDE_STDERR_ON_SUCCESS_DEFAULT)}.`
5803
6922
  )
5804
6923
  };
5805
6924
  var shellWaitSchema = shellTaskKeySchema.extend({
5806
- wait_timeout: z12.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
6925
+ wait_timeout: z16.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
5807
6926
  `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
6927
  ),
5809
6928
  ...shellSuccessStderrSchema
5810
6929
  });
5811
6930
  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(
6931
+ var shellStreamSchema = z16.enum(["stdout", "stderr"]);
6932
+ var shellListSchema = z16.object({
6933
+ limit: z16.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
5815
6934
  `Max tasks to return. Default: ${SHELL_LIST_DEFAULT_LIMIT}. Max ${SHELL_LIST_MAX_LIMIT}.`
5816
6935
  ),
5817
6936
  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.")
6937
+ include_terminal: z16.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
5819
6938
  });
5820
- var shellLogsSchema = z12.object({
5821
- key: z12.string().describe("Canonical shell task key returned by shell or shell_list."),
6939
+ var shellLogsSchema = z16.object({
6940
+ key: z16.string().describe("Canonical shell task key returned by shell or shell_list."),
5822
6941
  stream: shellStreamSchema.optional().describe("Stream to read. Default: stdout."),
5823
- tail_lines: z12.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
6942
+ tail_lines: z16.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
5824
6943
  `Return only the last N lines. Max ${SHELL_LOGS_MAX_TAIL_LINES}.`
5825
6944
  )
5826
6945
  });
@@ -5857,8 +6976,8 @@ var normalizeShellTaskKey = (value) => {
5857
6976
  var getShellTaskKey = (task) => task.key ?? `${toShellKeyBase(task.label)}-${compactTaskId(task.task_id).slice(0, 8)}`;
5858
6977
  var toShellKeyBase = (label) => {
5859
6978
  const source = label?.trim() ?? "";
5860
- const slug = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
5861
- return slug || "shell";
6979
+ const slug2 = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
6980
+ return slug2 || "shell";
5862
6981
  };
5863
6982
  var compactTaskId = (taskId) => {
5864
6983
  const compact = taskId.toLowerCase().replaceAll(/[^a-z0-9]+/g, "");
@@ -6171,7 +7290,7 @@ var waitForManagedTaskWindow = async (tasks, taskId, options) => {
6171
7290
  };
6172
7291
  var createShellTool = (sandboxKey, options = {}) => {
6173
7292
  const shared = getSharedDeps(options);
6174
- return defineTool9({
7293
+ return defineTool10({
6175
7294
  name: "shell",
6176
7295
  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
7296
  input: shellRunSchema,
@@ -6239,7 +7358,7 @@ var createShellTool = (sandboxKey, options = {}) => {
6239
7358
  };
6240
7359
  var createShellStdinWriteTool = (options = {}) => {
6241
7360
  const shared = getSharedDeps(options);
6242
- return defineTool9({
7361
+ return defineTool10({
6243
7362
  name: "shell_stdin_write",
6244
7363
  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
7364
  input: shellStdinWriteSchema,
@@ -6267,7 +7386,7 @@ var createShellStdinWriteTool = (options = {}) => {
6267
7386
  };
6268
7387
  var createShellListTool = (options = {}) => {
6269
7388
  const shared = getSharedDeps(options);
6270
- return defineTool9({
7389
+ return defineTool10({
6271
7390
  name: "shell_list",
6272
7391
  description: "List retained shell tasks with compact summaries, defaulting to active tasks.",
6273
7392
  input: shellListSchema,
@@ -6298,7 +7417,7 @@ var createShellListTool = (options = {}) => {
6298
7417
  };
6299
7418
  var createShellStatusTool = (options = {}) => {
6300
7419
  const shared = getSharedDeps(options);
6301
- return defineTool9({
7420
+ return defineTool10({
6302
7421
  name: "shell_status",
6303
7422
  description: "Get the current state for a shell task as compact JSON.",
6304
7423
  input: shellTaskKeySchema,
@@ -6314,7 +7433,7 @@ var createShellStatusTool = (options = {}) => {
6314
7433
  };
6315
7434
  var createShellLogsTool = (options = {}) => {
6316
7435
  const shared = getSharedDeps(options);
6317
- return defineTool9({
7436
+ return defineTool10({
6318
7437
  name: "shell_logs",
6319
7438
  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
7439
  input: shellLogsSchema,
@@ -6336,7 +7455,7 @@ var createShellLogsTool = (options = {}) => {
6336
7455
  };
6337
7456
  var createShellWaitTool = (options = {}) => {
6338
7457
  const shared = getSharedDeps(options);
6339
- return defineTool9({
7458
+ return defineTool10({
6340
7459
  name: "shell_wait",
6341
7460
  description: "Wait within a bounded window for a shell task, returning compact running status or its terminal stdout/stderr result.",
6342
7461
  input: shellWaitSchema,
@@ -6371,7 +7490,7 @@ var createShellWaitTool = (options = {}) => {
6371
7490
  };
6372
7491
  var createShellResultTool = (options = {}) => {
6373
7492
  const shared = getSharedDeps(options);
6374
- return defineTool9({
7493
+ return defineTool10({
6375
7494
  name: "shell_result",
6376
7495
  description: "Read a shell task's retained terminal stdout/stderr result, or its current status if still running.",
6377
7496
  input: shellResultSchema,
@@ -6390,7 +7509,7 @@ var createShellResultTool = (options = {}) => {
6390
7509
  };
6391
7510
  var createShellCancelTool = (options = {}) => {
6392
7511
  const shared = getSharedDeps(options);
6393
- return defineTool9({
7512
+ return defineTool10({
6394
7513
  name: "shell_cancel",
6395
7514
  description: "Cancel a running shell task and return compact JSON for the cancelled state.",
6396
7515
  input: shellTaskKeySchema,
@@ -6409,16 +7528,16 @@ var createShellCancelTool = (options = {}) => {
6409
7528
  };
6410
7529
 
6411
7530
  // 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.")
7531
+ import { defineTool as defineTool11 } from "@codelia/core";
7532
+ import { z as z17 } from "zod";
7533
+ var SkillLoadInputSchema = z17.object({
7534
+ name: z17.string().min(1).optional().describe("Exact skill name to load."),
7535
+ path: z17.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
6417
7536
  }).refine((value) => !!value.name || !!value.path, {
6418
7537
  message: "name or path is required",
6419
7538
  path: ["name"]
6420
7539
  });
6421
- var createSkillLoadTool = (skillsResolverKey) => defineTool10({
7540
+ var createSkillLoadTool = (skillsResolverKey) => defineTool11({
6422
7541
  name: "skill_load",
6423
7542
  description: "Load full SKILL.md content by exact name or path.",
6424
7543
  input: SkillLoadInputSchema,
@@ -6464,17 +7583,17 @@ var createSkillLoadTool = (skillsResolverKey) => defineTool10({
6464
7583
  });
6465
7584
 
6466
7585
  // 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({
7586
+ import { defineTool as defineTool12 } from "@codelia/core";
7587
+ import { z as z18 } from "zod";
7588
+ var createSkillSearchTool = (skillsResolverKey) => defineTool12({
6470
7589
  name: "skill_search",
6471
7590
  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(
7591
+ input: z18.object({
7592
+ query: z18.string().min(1).describe("Search query text."),
7593
+ limit: z18.number().int().positive().optional().describe(
6475
7594
  "Optional max result count. Higher values may be clamped by config."
6476
7595
  ),
6477
- scope: z14.enum(["repo", "user"]).optional().describe("Optional scope filter.")
7596
+ scope: z18.enum(["repo", "user"]).optional().describe("Optional scope filter.")
6478
7597
  }),
6479
7598
  execute: async (input, ctx) => {
6480
7599
  try {
@@ -6497,8 +7616,8 @@ var createSkillSearchTool = (skillsResolverKey) => defineTool11({
6497
7616
  });
6498
7617
 
6499
7618
  // src/tools/todo-mutate.ts
6500
- import { defineTool as defineTool12 } from "@codelia/core";
6501
- import { z as z15 } from "zod";
7619
+ import { defineTool as defineTool13 } from "@codelia/core";
7620
+ import { z as z19 } from "zod";
6502
7621
 
6503
7622
  // src/tools/todo-store.ts
6504
7623
  var TODO_SESSION_META_KEY = "codelia_todos";
@@ -6608,39 +7727,39 @@ var pickNextTodo = (todos) => {
6608
7727
  var todoStore = /* @__PURE__ */ new Map();
6609
7728
 
6610
7729
  // 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(
7730
+ var todoStatusSchema = z19.enum(["pending", "in_progress", "completed"]);
7731
+ var todoPrioritySchema = z19.number().int().min(1).max(5);
7732
+ var todoItemSchema = z19.object({
7733
+ id: z19.string().min(1).optional().describe(
6615
7734
  "Stable ID. Omit to generate one; preserve the existing ID when replacing a known item."
6616
7735
  ),
6617
- content: z15.string().min(1).describe("Todo item text."),
7736
+ content: z19.string().min(1).describe("Todo item text."),
6618
7737
  status: todoStatusSchema.describe("Todo status."),
6619
7738
  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.")
7739
+ notes: z19.string().optional().describe("Implementation notes."),
7740
+ activeForm: z19.string().optional().describe("In-progress phrasing for UI display.")
6622
7741
  });
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."),
7742
+ var todoPatchItemSchema = z19.object({
7743
+ id: z19.string().min(1).describe("Target todo ID."),
7744
+ remove: z19.boolean().optional().describe("Set true to remove the todo item."),
7745
+ content: z19.string().min(1).optional().describe("New todo text; omit to keep the current value."),
6627
7746
  status: todoStatusSchema.optional().describe("New status; omit to keep the current value."),
6628
7747
  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(
7748
+ notes: z19.string().optional().describe("New notes; omit to keep the current value, empty clears."),
7749
+ activeForm: z19.string().optional().describe(
6631
7750
  "New in-progress phrasing; omit to keep the current value, empty clears."
6632
7751
  )
6633
7752
  });
6634
- var todoNewInputSchema = z15.object({
6635
- todos: z15.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
7753
+ var todoNewInputSchema = z19.object({
7754
+ todos: z19.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
6636
7755
  }).strict();
6637
- var todoAppendInputSchema = z15.object({
6638
- todos: z15.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
7756
+ var todoAppendInputSchema = z19.object({
7757
+ todos: z19.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
6639
7758
  }).strict();
6640
- var todoPatchInputSchema = z15.object({
6641
- updates: z15.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
7759
+ var todoPatchInputSchema = z19.object({
7760
+ updates: z19.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
6642
7761
  }).strict();
6643
- var todoClearInputSchema = z15.object({}).strict();
7762
+ var todoClearInputSchema = z19.object({}).strict();
6644
7763
  var statusSymbol = {
6645
7764
  pending: "[ ]",
6646
7765
  in_progress: "[>]",
@@ -6735,7 +7854,7 @@ var applyTodoMutation = (sessionId, input, outputMode) => {
6735
7854
  }
6736
7855
  return formatSuccess(outputMode, nextTodos);
6737
7856
  };
6738
- var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => defineTool12({
7857
+ var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => defineTool13({
6739
7858
  name,
6740
7859
  description,
6741
7860
  input,
@@ -6790,17 +7909,17 @@ var createTodoClearTool = (sandboxKey, sessionContextKey) => createTodoMutationT
6790
7909
  );
6791
7910
 
6792
7911
  // src/tools/todo-read.ts
6793
- import { defineTool as defineTool13 } from "@codelia/core";
6794
- import { z as z16 } from "zod";
7912
+ import { defineTool as defineTool14 } from "@codelia/core";
7913
+ import { z as z20 } from "zod";
6795
7914
  var statusSymbol2 = {
6796
7915
  pending: "[ ]",
6797
7916
  in_progress: "[>]",
6798
7917
  completed: "[x]"
6799
7918
  };
6800
- var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool13({
7919
+ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool14({
6801
7920
  name: "todo_read",
6802
7921
  description: "Read the in-session todo plan with execution order and next step.",
6803
- input: z16.object({}),
7922
+ input: z20.object({}),
6804
7923
  execute: async (_input, ctx) => {
6805
7924
  const sandbox = await getSandboxContext(ctx, sandboxKey);
6806
7925
  const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
@@ -6836,15 +7955,15 @@ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool13({
6836
7955
  });
6837
7956
 
6838
7957
  // 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({
7958
+ import { defineTool as defineTool15 } from "@codelia/core";
7959
+ import { z as z21 } from "zod";
7960
+ var createToolOutputCacheTool = (store) => defineTool15({
6842
7961
  name: "tool_output_cache",
6843
7962
  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.")
7963
+ input: z21.object({
7964
+ ref_id: z21.string().describe("Tool output reference ID."),
7965
+ offset: z21.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
7966
+ limit: z21.number().int().positive().optional().describe("Optional max number of lines to return.")
6848
7967
  }),
6849
7968
  execute: async (input) => {
6850
7969
  if (!store.read) {
@@ -6860,14 +7979,14 @@ var createToolOutputCacheTool = (store) => defineTool14({
6860
7979
  }
6861
7980
  }
6862
7981
  });
6863
- var createToolOutputCacheLineTool = (store) => defineTool14({
7982
+ var createToolOutputCacheLineTool = (store) => defineTool15({
6864
7983
  name: "tool_output_cache_line",
6865
7984
  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.")
7985
+ input: z21.object({
7986
+ ref_id: z21.string().describe("Tool output reference ID."),
7987
+ line_number: z21.number().int().positive().describe("1-based line number to read."),
7988
+ char_offset: z21.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7989
+ char_limit: z21.number().int().positive().optional().describe("Max chars to return.")
6871
7990
  }),
6872
7991
  execute: async (input) => {
6873
7992
  if (!store.readLine) {
@@ -6884,16 +8003,16 @@ var createToolOutputCacheLineTool = (store) => defineTool14({
6884
8003
  }
6885
8004
  }
6886
8005
  });
6887
- var createToolOutputCacheGrepTool = (store) => defineTool14({
8006
+ var createToolOutputCacheGrepTool = (store) => defineTool15({
6888
8007
  name: "tool_output_cache_grep",
6889
8008
  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.")
8009
+ input: z21.object({
8010
+ ref_id: z21.string().describe("Tool output reference ID."),
8011
+ pattern: z21.string().describe("Text or regex pattern to search for."),
8012
+ regex: z21.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
8013
+ before: z21.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
8014
+ after: z21.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
8015
+ max_matches: z21.number().int().positive().optional().describe("Maximum number of matches to return.")
6897
8016
  }),
6898
8017
  execute: async (input) => {
6899
8018
  if (!store.grep) {
@@ -6915,9 +8034,9 @@ var createToolOutputCacheGrepTool = (store) => defineTool14({
6915
8034
 
6916
8035
  // src/tools/view-image.ts
6917
8036
  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";
8037
+ import path13 from "path";
8038
+ import { defineTool as defineTool16 } from "@codelia/core";
8039
+ import { z as z22 } from "zod";
6921
8040
  var DEFAULT_MAX_BYTES2 = 5 * 1024 * 1024;
6922
8041
  var MAX_MAX_BYTES = 10 * 1024 * 1024;
6923
8042
  var MIME_BY_EXTENSION = {
@@ -6928,21 +8047,51 @@ var MIME_BY_EXTENSION = {
6928
8047
  ".gif": "image/gif"
6929
8048
  };
6930
8049
  var resolveImageMime = (filePath) => {
6931
- return MIME_BY_EXTENSION[path10.extname(filePath).toLowerCase()] ?? null;
8050
+ return MIME_BY_EXTENSION[path13.extname(filePath).toLowerCase()] ?? null;
6932
8051
  };
6933
- var createViewImageTool = (sandboxKey) => defineTool15({
8052
+ var createViewImageTool = (sandboxKey) => defineTool16({
6934
8053
  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."
8054
+ 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).",
8055
+ input: z22.object({
8056
+ file_path: z22.string().min(1).optional().describe(
8057
+ "Local png/jpeg/webp/gif path; provide exactly one of file_path or url. Sandbox-bounded unless full-access mode is active."
6939
8058
  ),
6940
- detail: z18.enum(["auto", "low", "high"]).optional().describe(
8059
+ url: z22.url({ protocol: /^https?$/ }).refine((value) => {
8060
+ if (!URL.canParse(value)) return false;
8061
+ const parsed = new URL(value);
8062
+ return !parsed.username && !parsed.password;
8063
+ }, "Image URL must not contain credentials").optional().describe(
8064
+ "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."
8065
+ ),
8066
+ detail: z22.enum(["auto", "low", "high"]).optional().describe(
6941
8067
  "Model image-detail hint (`auto`/`low`/`high`). Default auto."
6942
8068
  ),
6943
- max_bytes: z18.number().int().positive().max(MAX_MAX_BYTES).optional().describe("Max file size in bytes. Default 5242880, Max 10485760.")
6944
- }),
8069
+ max_bytes: z22.number().int().positive().max(MAX_MAX_BYTES).optional().describe(
8070
+ "Local files only: max bytes. Default 5242880, Max 10485760; omit with url."
8071
+ )
8072
+ }).refine(
8073
+ (input) => input.file_path !== void 0 !== (input.url !== void 0),
8074
+ "Provide exactly one of file_path or url"
8075
+ ).refine(
8076
+ (input) => input.url === void 0 || input.max_bytes === void 0,
8077
+ "max_bytes is only supported for local files"
8078
+ ),
6945
8079
  execute: async (input, ctx) => {
8080
+ if (input.url !== void 0) {
8081
+ return [
8082
+ {
8083
+ type: "text",
8084
+ text: "Image URL supplied for provider inspection (not fetched locally).\n"
8085
+ },
8086
+ {
8087
+ type: "image_url",
8088
+ image_url: { url: input.url, detail: input.detail ?? "auto" }
8089
+ }
8090
+ ];
8091
+ }
8092
+ if (input.file_path === void 0) {
8093
+ throw new Error("Provide exactly one of file_path or url");
8094
+ }
6946
8095
  let resolved;
6947
8096
  try {
6948
8097
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -6990,8 +8139,8 @@ var createViewImageTool = (sandboxKey) => defineTool15({
6990
8139
  });
6991
8140
 
6992
8141
  // src/tools/webfetch.ts
6993
- import { defineTool as defineTool16 } from "@codelia/core";
6994
- import { z as z19 } from "zod";
8142
+ import { defineTool as defineTool17 } from "@codelia/core";
8143
+ import { z as z23 } from "zod";
6995
8144
  var DEFAULT_TIMEOUT_MS2 = 1e4;
6996
8145
  var MAX_TIMEOUT_MS = 3e4;
6997
8146
  var DEFAULT_MAX_BYTES3 = 2e5;
@@ -7244,16 +8393,16 @@ var classifyFetchError = (error, timeoutMs) => {
7244
8393
  })
7245
8394
  };
7246
8395
  };
7247
- var createWebfetchTool = () => defineTool16({
8396
+ var createWebfetchTool = () => defineTool17({
7248
8397
  name: "webfetch",
7249
8398
  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(
8399
+ input: z23.object({
8400
+ url: z23.string().min(1).describe("HTTP(S) URL to fetch."),
8401
+ output_format: z23.enum(["markdown", "text", "html"]).optional().describe("Normalized output format. Default markdown."),
8402
+ timeout_ms: z23.number().int().positive().max(MAX_TIMEOUT_MS).optional().describe(
7254
8403
  `Fetch timeout in ms. Default ${DEFAULT_TIMEOUT_MS2}, Max ${MAX_TIMEOUT_MS}.`
7255
8404
  ),
7256
- max_bytes: z19.number().int().positive().max(MAX_MAX_BYTES2).optional().describe(
8405
+ max_bytes: z23.number().int().positive().max(MAX_MAX_BYTES2).optional().describe(
7257
8406
  `Max response bytes to keep. Default ${DEFAULT_MAX_BYTES3}, Max ${MAX_MAX_BYTES2}.`
7258
8407
  )
7259
8408
  }),
@@ -7325,17 +8474,17 @@ var createWebfetchTool = () => defineTool16({
7325
8474
 
7326
8475
  // src/tools/write.ts
7327
8476
  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({
8477
+ import path14 from "path";
8478
+ import { defineTool as defineTool18 } from "@codelia/core";
8479
+ import { z as z24 } from "zod";
8480
+ var createWriteTool = (sandboxKey, outputCacheStore) => defineTool18({
7332
8481
  name: "write",
7333
8482
  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(
8483
+ input: z24.object({
8484
+ file_path: z24.string().describe(
7336
8485
  "File path. Sandbox-bounded unless full-access mode is active."
7337
8486
  ),
7338
- content: z20.string().describe("Full replacement UTF-8 text content to write."),
8487
+ content: z24.string().describe("Full replacement UTF-8 text content to write."),
7339
8488
  expected_hash: expectedContentHashSchema
7340
8489
  }),
7341
8490
  execute: async (input, ctx) => {
@@ -7363,7 +8512,7 @@ var createWriteTool = (sandboxKey, outputCacheStore) => defineTool17({
7363
8512
  content: before,
7364
8513
  filePath: input.file_path
7365
8514
  });
7366
- await fs13.mkdir(path11.dirname(resolved), { recursive: true });
8515
+ await fs13.mkdir(path14.dirname(resolved), { recursive: true });
7367
8516
  await fs13.writeFile(resolved, input.content, "utf8");
7368
8517
  const diffPayload = await buildDiffPayload({
7369
8518
  toolName: "write",
@@ -7451,8 +8600,8 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
7451
8600
  ];
7452
8601
 
7453
8602
  // src/tools/task.ts
7454
- import { defineTool as defineTool18 } from "@codelia/core";
7455
- import { z as z21 } from "zod";
8603
+ import { defineTool as defineTool19 } from "@codelia/core";
8604
+ import { z as z25 } from "zod";
7456
8605
 
7457
8606
  // src/subagents/wait.ts
7458
8607
  var waitForTaskOrMessage = async (coordinator, owner, taskId, signal) => {
@@ -7483,8 +8632,8 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn6) => {
7483
8632
  if (!id) throw new Error("No parent session");
7484
8633
  return id;
7485
8634
  };
7486
- const idSchema = z21.object({
7487
- task_id: z21.string().min(1).describe(
8635
+ const idSchema = z25.object({
8636
+ task_id: z25.string().min(1).describe(
7488
8637
  "Exact task_id returned by task_spawn or task_list; limited to the current session."
7489
8638
  )
7490
8639
  });
@@ -7492,7 +8641,7 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn6) => {
7492
8641
  ...createCommunicationTools({
7493
8642
  request: (operation, params, signal) => coordinator.parentChannel(session()).request(operation, params, signal)
7494
8643
  }),
7495
- defineTool18({
8644
+ defineTool19({
7496
8645
  name: "task_spawn",
7497
8646
  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
8647
  input: subagentSpawnSchema,
@@ -7517,14 +8666,14 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn6) => {
7517
8666
  return JSON.stringify(subagentTaskInfo(task));
7518
8667
  }
7519
8668
  }),
7520
- defineTool18({
8669
+ defineTool19({
7521
8670
  name: "task_list",
7522
8671
  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(
8672
+ input: z25.object({
8673
+ active_only: z25.boolean().optional().describe(
7525
8674
  "True returns queued/running children only; default false."
7526
8675
  ),
7527
- limit: z21.number().int().min(1).max(100).optional()
8676
+ limit: z25.number().int().min(1).max(100).optional()
7528
8677
  }),
7529
8678
  execute: async (input) => JSON.stringify(
7530
8679
  (await coordinator.list(session())).filter(
@@ -7536,7 +8685,7 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn6) => {
7536
8685
  )
7537
8686
  }),
7538
8687
  ...["task_status", "task_wait", "task_result", "task_cancel"].map(
7539
- (name) => defineTool18({
8688
+ (name) => defineTool19({
7540
8689
  name,
7541
8690
  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
8691
  input: idSchema,
@@ -7560,10 +8709,10 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn6) => {
7560
8709
  }
7561
8710
  })
7562
8711
  ),
7563
- defineTool18({
8712
+ defineTool19({
7564
8713
  name: "task_cancel_all",
7565
8714
  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({}),
8715
+ input: z25.object({}),
7567
8716
  execute: async () => JSON.stringify(
7568
8717
  (await coordinator.cancelAll(session())).map(subagentTaskInfo)
7569
8718
  )
@@ -7836,6 +8985,43 @@ ${JSON.stringify(subagentConfig)}
7836
8985
  const authResolver = await createEnvironmentAuthResolver(state, log);
7837
8986
  const provider = await authResolver.resolveProvider(modelConfig.provider);
7838
8987
  const providerAuth = await authResolver.resolveProviderAuth(provider);
8988
+ const cachedAuthProviders = /* @__PURE__ */ new Set([provider]);
8989
+ const imageStore = isTuiLocalEnvironment(environment) && workspaceRoot ? createLocalImageStore(workspaceRoot) : void 0;
8990
+ state.prepareRunImages = imageStore ? (input) => persistImageAttachments(input, imageStore) : void 0;
8991
+ let authorizeImage = () => ({
8992
+ decision: "deny",
8993
+ reason: "image permissions unavailable"
8994
+ });
8995
+ let imageTools = [];
8996
+ if (imageStore) {
8997
+ const imageConfig = await resolveImageGenerationConfig(workspaceRoot);
8998
+ let route = null;
8999
+ if (imageConfig.mode !== "off") {
9000
+ try {
9001
+ route = await resolveImageRoute(imageConfig, localImageAuth, {
9002
+ provider,
9003
+ auth: providerAuth,
9004
+ ...authResolver.getOpenAiAccessToken ? {
9005
+ getOpenAiAccessToken: authResolver.getOpenAiAccessToken.bind(authResolver)
9006
+ } : {}
9007
+ });
9008
+ } catch (error) {
9009
+ log(
9010
+ error instanceof ImageGenerationError ? error.message : "Image configuration/auth unavailable; chat remains enabled."
9011
+ );
9012
+ }
9013
+ }
9014
+ if (route) cachedAuthProviders.add(route.provider);
9015
+ imageTools = createImageTools({
9016
+ store: imageStore,
9017
+ route,
9018
+ authorize: (...args) => authorizeImage(...args),
9019
+ ...ctx ? { readSource: createLocalImageSourceReader(ctx) } : {},
9020
+ ...workspaceRoot ? {
9021
+ exportImage: (outputPath, bytes) => exportImageBytes(workspaceRoot, outputPath, bytes)
9022
+ } : {}
9023
+ });
9024
+ }
7839
9025
  const searchConfig = environment.tools.search === "from-config" ? await resolveEnvironmentSearchConfig(state, workspaceRoot) : void 0;
7840
9026
  const {
7841
9027
  tools,
@@ -7847,6 +9033,7 @@ ${JSON.stringify(subagentConfig)}
7847
9033
  } = await composeRuntimeTools({
7848
9034
  provider,
7849
9035
  baseTools: baseLocalTools,
9036
+ imageTools,
7850
9037
  mcpTools,
7851
9038
  hostTools,
7852
9039
  ...searchConfig ? { searchConfig } : {}
@@ -7859,6 +9046,7 @@ ${JSON.stringify(subagentConfig)}
7859
9046
  }
7860
9047
  state.tools = tools;
7861
9048
  state.toolDefinitions = toolDefinitions;
9049
+ state.cachedAuthProviders = cachedAuthProviders;
7862
9050
  const getOpenAiAccessToken = authResolver.getOpenAiAccessToken?.bind(authResolver);
7863
9051
  const { llm, resolvedModelName } = await createRuntimeModel({
7864
9052
  provider,
@@ -7871,9 +9059,10 @@ ${JSON.stringify(subagentConfig)}
7871
9059
  state.currentModelProvider = provider;
7872
9060
  state.currentModelName = resolvedModelName;
7873
9061
  state.currentModelSource = modelConfig.source;
7874
- const modelRegistry = environment.persistence.mode === "runtime" ? await buildModelRegistry(llm, {
7875
- strict: provider !== "openrouter"
7876
- }) : DEFAULT_MODEL_REGISTRY2;
9062
+ const modelRegistry = environment.persistence.mode === "runtime" || getResponsesProvider(modelConfig, provider) ? await buildModelRegistry(llm, {
9063
+ strict: provider !== "openrouter",
9064
+ providers: modelConfig.providers
9065
+ }) : buildConfiguredModelRegistry(modelConfig.providers);
7877
9066
  const totalBudgetTrimEnabled = envTruthy(
7878
9067
  process.env.CODELIA_TOOL_OUTPUT_TOTAL_TRIM
7879
9068
  );
@@ -7931,6 +9120,7 @@ ${request.raw_args}`,
7931
9120
  subagent: subagentConfig,
7932
9121
  workspace_root: workspaceRoot,
7933
9122
  model: {
9123
+ providers: modelConfig.providers,
7934
9124
  provider,
7935
9125
  name: resolvedModelName,
7936
9126
  reasoning: modelConfig.reasoning,
@@ -7960,7 +9150,7 @@ ${request.raw_args}`,
7960
9150
  toolContext
7961
9151
  );
7962
9152
  if (decision.decision !== "allow")
7963
- throw new ToolPermissionDenied(decision);
9153
+ throw new ToolPermissionDenied2(decision);
7964
9154
  if (state.sessionId !== sessionId || runId && (state.activeRunId !== runId || state.cancelRequested))
7965
9155
  throw new Error("Parent turn stopped before admission");
7966
9156
  return coordinator.spawn(params, {
@@ -7970,17 +9160,23 @@ ${request.raw_args}`,
7970
9160
  });
7971
9161
  };
7972
9162
  }
9163
+ authorizeImage = canExecuteTool;
9164
+ const endpointModel = getResponsesProvider(modelConfig, provider)?.models[resolvedModelName];
9165
+ const modelToolsEnabled = !endpointModel || endpointModel.supports_tools === true;
7973
9166
  const agent = new Agent({
7974
9167
  llm,
7975
- tools,
7976
- hostedTools,
9168
+ tools: modelToolsEnabled ? tools : [],
9169
+ hostedTools: modelToolsEnabled ? hostedTools : [],
7977
9170
  systemPrompt,
7978
9171
  modelRegistry: modelRegistry ?? DEFAULT_MODEL_REGISTRY2,
7979
9172
  toolOutputCache: {
7980
9173
  totalBudgetTrim: totalBudgetTrimEnabled
7981
9174
  },
7982
- services: { toolOutputCacheStore },
7983
- canExecuteTool: (call, raw, ctx2) => options.subagents?.isAvailable() && workspaceRoot && call.function.name === "task_spawn" ? { decision: "allow" } : canExecuteTool(call, raw, ctx2)
9175
+ services: {
9176
+ toolOutputCacheStore,
9177
+ ...imageStore ? { resolveImage: imageStore.resolve.bind(imageStore) } : {}
9178
+ },
9179
+ 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
9180
  });
7985
9181
  if (approvalModeResolution.persistSelection) {
7986
9182
  await approvalModeResolution.persistSelection();
@@ -8510,8 +9706,8 @@ var parseAuthorizationServerMetadata = (value) => {
8510
9706
  var buildAuthorizationServerMetadataUrl = (issuer) => {
8511
9707
  try {
8512
9708
  const parsed = new URL(issuer);
8513
- const path18 = parsed.pathname === "/" ? "" : parsed.pathname;
8514
- const basePath = path18.startsWith("/") ? path18 : `/${path18}`;
9709
+ const path21 = parsed.pathname === "/" ? "" : parsed.pathname;
9710
+ const basePath = path21.startsWith("/") ? path21 : `/${path21}`;
8515
9711
  const metadataPath = `/.well-known/oauth-authorization-server${basePath}`;
8516
9712
  return new URL(metadataPath, `${parsed.origin}/`).toString();
8517
9713
  } catch {
@@ -8615,8 +9811,8 @@ var MAX_TOOLS_LIST_PAGES = 100;
8615
9811
  var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8616
9812
  var isMcpToolDescriptor = (value) => isRecord6(value) && typeof value.name === "string";
8617
9813
  var toSlug2 = (value) => {
8618
- const slug = value.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
8619
- return slug || "tool";
9814
+ const slug2 = value.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
9815
+ return slug2 || "tool";
8620
9816
  };
8621
9817
  var hash8 = (value) => crypto7.createHash("sha256").update(value).digest("hex").slice(0, 8);
8622
9818
  var clampToolName = (value) => {
@@ -9170,7 +10366,7 @@ var McpManager = class {
9170
10366
 
9171
10367
  // src/rpc/handlers.ts
9172
10368
  import {
9173
- RPC_ERROR_CODE as RPC_ERROR_CODE9
10369
+ RPC_ERROR_CODE as RPC_ERROR_CODE11
9174
10370
  } from "@codelia/protocol";
9175
10371
  import {
9176
10372
  RunEventStoreFactoryImpl,
@@ -9182,10 +10378,123 @@ var SERVER_NAME = "codelia-runtime";
9182
10378
  var SERVER_VERSION = "0.1.0";
9183
10379
  var PROTOCOL_VERSION = "0";
9184
10380
 
9185
- // src/rpc/context.ts
10381
+ // src/rpc/auth.ts
9186
10382
  import {
9187
10383
  RPC_ERROR_CODE
9188
10384
  } from "@codelia/protocol";
10385
+ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
10386
+ if (state.activeRunId) {
10387
+ sendError(id, {
10388
+ code: RPC_ERROR_CODE.RUNTIME_BUSY,
10389
+ message: "runtime busy"
10390
+ });
10391
+ return;
10392
+ }
10393
+ const provider = params?.provider;
10394
+ if (provider !== void 0 && (typeof provider !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(provider))) {
10395
+ sendError(id, {
10396
+ code: RPC_ERROR_CODE.INVALID_PARAMS,
10397
+ message: "invalid logout provider name"
10398
+ });
10399
+ return;
10400
+ }
10401
+ try {
10402
+ const hostAuth = state.effectiveEnvironment.auth.model === "host";
10403
+ const config = provider ? await resolveEnvironmentModelConfig(
10404
+ state,
10405
+ state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0
10406
+ ) : void 0;
10407
+ const currentProvider = state.currentModelProvider ?? state.sessionModelOverride?.provider ?? config?.provider ?? (hostAuth ? void 0 : "openai");
10408
+ const affectsCurrent = provider === void 0 || provider === currentProvider;
10409
+ const clearSession = (params?.clear_session ?? true) && affectsCurrent;
10410
+ if (hostAuth) {
10411
+ const credentials = state.effectiveEnvironment.adapters.credentialProvider;
10412
+ if (provider ? !credentials?.clearProviderAuth : !credentials?.clearAuth) {
10413
+ sendError(id, {
10414
+ code: RPC_ERROR_CODE.RUNTIME_INTERNAL,
10415
+ message: provider ? "host auth provider does not support scoped logout" : "host auth provider does not support logout"
10416
+ });
10417
+ return;
10418
+ }
10419
+ if (provider) await credentials?.clearProviderAuth?.(provider);
10420
+ else await credentials?.clearAuth?.();
10421
+ } else {
10422
+ const store = new AuthStore();
10423
+ if (provider) {
10424
+ const auth = await store.load();
10425
+ if (!Object.hasOwn(auth.providers, provider) && !configuredProviders(config?.providers).includes(provider)) {
10426
+ sendError(id, {
10427
+ code: RPC_ERROR_CODE.INVALID_PARAMS,
10428
+ message: `unknown logout provider: ${provider}`
10429
+ });
10430
+ return;
10431
+ }
10432
+ }
10433
+ if (!state.uiCapabilities?.supports_confirm) {
10434
+ sendError(id, {
10435
+ code: RPC_ERROR_CODE.RUNTIME_INTERNAL,
10436
+ message: "UI confirmation is required for logout"
10437
+ });
10438
+ return;
10439
+ }
10440
+ const confirm = await requestUiConfirm(state, {
10441
+ title: provider ? `Log out of ${provider}` : "Confirm logout",
10442
+ 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?`,
10443
+ confirm_label: "Yes",
10444
+ cancel_label: "No",
10445
+ danger_level: "danger",
10446
+ allow_remember: false,
10447
+ allow_reason: false
10448
+ });
10449
+ if (!confirm?.ok) {
10450
+ sendResult(id, {
10451
+ ok: false,
10452
+ auth_cleared: false,
10453
+ session_cleared: false,
10454
+ cancelled: true,
10455
+ ...provider ? { provider } : {}
10456
+ });
10457
+ return;
10458
+ }
10459
+ if (provider) {
10460
+ const auth = await store.load();
10461
+ delete auth.providers[provider];
10462
+ await store.save(auth);
10463
+ } else await store.save({ version: 1, providers: {} });
10464
+ }
10465
+ if (affectsCurrent || provider && state.cachedAuthProviders.has(provider)) {
10466
+ state.agent = null;
10467
+ state.tools = null;
10468
+ state.toolDefinitions = null;
10469
+ state.cachedAuthProviders = /* @__PURE__ */ new Set();
10470
+ }
10471
+ if (clearSession) {
10472
+ state.sessionId = null;
10473
+ state.sessionMeta = null;
10474
+ state.sessionAppend = null;
10475
+ state.sessionModelOverride = null;
10476
+ }
10477
+ sendResult(id, {
10478
+ ok: true,
10479
+ auth_cleared: true,
10480
+ session_cleared: clearSession,
10481
+ ...provider ? { provider } : {}
10482
+ });
10483
+ log2(
10484
+ `auth.logout provider=${provider ?? "all"} session_cleared=${clearSession}`
10485
+ );
10486
+ } catch {
10487
+ sendError(id, {
10488
+ code: RPC_ERROR_CODE.RUNTIME_INTERNAL,
10489
+ message: "auth logout failed"
10490
+ });
10491
+ }
10492
+ };
10493
+
10494
+ // src/rpc/context.ts
10495
+ import {
10496
+ RPC_ERROR_CODE as RPC_ERROR_CODE2
10497
+ } from "@codelia/protocol";
9189
10498
  var createContextHandlers = ({
9190
10499
  state,
9191
10500
  log: log2
@@ -9316,7 +10625,7 @@ var createContextHandlers = ({
9316
10625
  sendResult(id, result);
9317
10626
  } catch (error) {
9318
10627
  sendError(id, {
9319
- code: RPC_ERROR_CODE.RUNTIME_INTERNAL,
10628
+ code: RPC_ERROR_CODE2.RUNTIME_INTERNAL,
9320
10629
  message: `context.inspect failed: ${String(error)}`
9321
10630
  });
9322
10631
  }
@@ -9326,12 +10635,12 @@ var createContextHandlers = ({
9326
10635
 
9327
10636
  // src/rpc/history.ts
9328
10637
  import { createReadStream, promises as fs14 } from "fs";
9329
- import path12 from "path";
10638
+ import path15 from "path";
9330
10639
  import { createInterface as createInterface2 } from "readline";
9331
10640
  import {
9332
- RPC_ERROR_CODE as RPC_ERROR_CODE2
10641
+ RPC_ERROR_CODE as RPC_ERROR_CODE3
9333
10642
  } from "@codelia/protocol";
9334
- import { resolveStoragePaths as resolveStoragePaths2 } from "@codelia/storage";
10643
+ import { resolveStoragePaths as resolveStoragePaths3 } from "@codelia/storage";
9335
10644
  var DEFAULT_HISTORY_RUNS = 20;
9336
10645
  var DEFAULT_HISTORY_EVENTS = 1500;
9337
10646
  var runStartInputToHiddenMessage = (input) => {
@@ -9386,7 +10695,7 @@ var readFirstLine = async (filePath) => {
9386
10695
  }
9387
10696
  };
9388
10697
  var collectRunCandidates = async (log2) => {
9389
- const paths = resolveStoragePaths2();
10698
+ const paths = resolveStoragePaths3();
9390
10699
  const sessionsDir = paths.sessionsDir;
9391
10700
  let yearEntries;
9392
10701
  try {
@@ -9402,7 +10711,7 @@ var collectRunCandidates = async (log2) => {
9402
10711
  for (const yearEntry of yearEntries) {
9403
10712
  if (!yearEntry.isDirectory()) continue;
9404
10713
  if (!/^\d{4}$/.test(yearEntry.name)) continue;
9405
- const yearPath = path12.join(sessionsDir, yearEntry.name);
10714
+ const yearPath = path15.join(sessionsDir, yearEntry.name);
9406
10715
  let monthEntries;
9407
10716
  try {
9408
10717
  monthEntries = await fs14.readdir(yearPath, {
@@ -9415,7 +10724,7 @@ var collectRunCandidates = async (log2) => {
9415
10724
  for (const monthEntry of monthEntries) {
9416
10725
  if (!monthEntry.isDirectory()) continue;
9417
10726
  if (!/^\d{2}$/.test(monthEntry.name)) continue;
9418
- const monthPath = path12.join(yearPath, monthEntry.name);
10727
+ const monthPath = path15.join(yearPath, monthEntry.name);
9419
10728
  let dayEntries;
9420
10729
  try {
9421
10730
  dayEntries = await fs14.readdir(monthPath, {
@@ -9428,7 +10737,7 @@ var collectRunCandidates = async (log2) => {
9428
10737
  for (const dayEntry of dayEntries) {
9429
10738
  if (!dayEntry.isDirectory()) continue;
9430
10739
  if (!/^\d{2}$/.test(dayEntry.name)) continue;
9431
- const dayPath = path12.join(monthPath, dayEntry.name);
10740
+ const dayPath = path15.join(monthPath, dayEntry.name);
9432
10741
  let files;
9433
10742
  try {
9434
10743
  files = await fs14.readdir(dayPath, {
@@ -9441,7 +10750,7 @@ var collectRunCandidates = async (log2) => {
9441
10750
  for (const file of files) {
9442
10751
  if (!file.isFile()) continue;
9443
10752
  if (!file.name.endsWith(".jsonl")) continue;
9444
- const filePath = path12.join(dayPath, file.name);
10753
+ const filePath = path15.join(dayPath, file.name);
9445
10754
  try {
9446
10755
  const stat = await fs14.stat(filePath);
9447
10756
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
@@ -9469,7 +10778,7 @@ var collectSessionRuns = async (sessionId, maxRuns, log2) => {
9469
10778
  const header = parseRunHeader(headerLine);
9470
10779
  if (!header) continue;
9471
10780
  if (header.session_id !== sessionId) continue;
9472
- const runId = header.run_id ?? path12.basename(candidate.path, ".jsonl");
10781
+ const runId = header.run_id ?? path15.basename(candidate.path, ".jsonl");
9473
10782
  const startedAt = header.started_at ?? new Date(candidate.mtimeMs).toISOString();
9474
10783
  runs.push({
9475
10784
  path: candidate.path,
@@ -9524,7 +10833,7 @@ var createHistoryHandlers = ({
9524
10833
  if (typeof value !== "string") return void 0;
9525
10834
  const trimmed = value.trim();
9526
10835
  if (!trimmed) return void 0;
9527
- return path12.resolve(trimmed);
10836
+ return path15.resolve(trimmed);
9528
10837
  };
9529
10838
  const handleSessionList = async (id, params) => {
9530
10839
  const limit = params?.limit ?? 50;
@@ -9534,7 +10843,7 @@ var createHistoryHandlers = ({
9534
10843
  sessions = await sessionStateStore.list();
9535
10844
  } catch (error) {
9536
10845
  sendError(id, {
9537
- code: RPC_ERROR_CODE2.SESSION_LIST_FAILED,
10846
+ code: RPC_ERROR_CODE3.SESSION_LIST_FAILED,
9538
10847
  message: `session list failed: ${String(error)}`
9539
10848
  });
9540
10849
  return;
@@ -9559,7 +10868,7 @@ var createHistoryHandlers = ({
9559
10868
  const sessionId = params?.session_id?.trim();
9560
10869
  if (!sessionId) {
9561
10870
  sendError(id, {
9562
- code: RPC_ERROR_CODE2.INVALID_PARAMS,
10871
+ code: RPC_ERROR_CODE3.INVALID_PARAMS,
9563
10872
  message: "session_id is required"
9564
10873
  });
9565
10874
  return;
@@ -9607,33 +10916,293 @@ var createHistoryHandlers = ({
9607
10916
  });
9608
10917
  }
9609
10918
  }
9610
- }
9611
- const truncated = replayEvents.length > maxEvents;
9612
- const selectedEvents = truncated ? replayEvents.slice(replayEvents.length - maxEvents) : replayEvents;
9613
- for (const event of selectedEvents) {
9614
- await emitHistoryEvent(event.runId, event.seq, event.event);
9615
- }
9616
- let resumeDiff;
9617
- if (buildResumeDiffSummary) {
9618
- try {
9619
- const sessionState = await sessionStateStore.load(sessionId);
9620
- resumeDiff = sessionState ? await buildResumeDiffSummary(
9621
- sessionState.meta ?? void 0
9622
- ) : void 0;
9623
- } catch (error) {
9624
- log2(`session.history resume diff error: ${String(error)}`);
10919
+ }
10920
+ const truncated = replayEvents.length > maxEvents;
10921
+ const selectedEvents = truncated ? replayEvents.slice(replayEvents.length - maxEvents) : replayEvents;
10922
+ for (const event of selectedEvents) {
10923
+ await emitHistoryEvent(event.runId, event.seq, event.event);
10924
+ }
10925
+ let resumeDiff;
10926
+ if (buildResumeDiffSummary) {
10927
+ try {
10928
+ const sessionState = await sessionStateStore.load(sessionId);
10929
+ resumeDiff = sessionState ? await buildResumeDiffSummary(
10930
+ sessionState.meta ?? void 0
10931
+ ) : void 0;
10932
+ } catch (error) {
10933
+ log2(`session.history resume diff error: ${String(error)}`);
10934
+ }
10935
+ }
10936
+ const result = {
10937
+ runs: runs.length,
10938
+ events_sent: selectedEvents.length,
10939
+ ...truncated ? { truncated: true } : {},
10940
+ ...resumeDiff ? { resume_diff: resumeDiff } : {}
10941
+ };
10942
+ sendResult(id, result);
10943
+ };
10944
+ return { handleSessionList, handleSessionHistory };
10945
+ };
10946
+
10947
+ // src/rpc/image.ts
10948
+ import {
10949
+ OPENAI_CODEX_IMAGE_MODELS as OPENAI_CODEX_IMAGE_MODELS2,
10950
+ OPENAI_IMAGE_MODELS as OPENAI_IMAGE_MODELS2,
10951
+ parseImageGenerationConfig
10952
+ } from "@codelia/config";
10953
+ import {
10954
+ RPC_ERROR_CODE as RPC_ERROR_CODE4
10955
+ } from "@codelia/protocol";
10956
+ import { z as z26 } from "zod";
10957
+ var paramsSchema = z26.object({
10958
+ mode: z26.enum(["off", "builtin", "custom"]).optional(),
10959
+ provider: z26.enum(["openai", "openrouter"]).optional(),
10960
+ model: z26.string().max(160).optional(),
10961
+ endpoint: z26.string().max(160).optional(),
10962
+ api_key_env: z26.string().max(128).optional()
10963
+ }).strict();
10964
+ function createImageHandlers(state) {
10965
+ const catalog = new ImageCatalog();
10966
+ let configuring = false;
10967
+ const workspace = () => {
10968
+ const env = state.effectiveEnvironment;
10969
+ if (!isTuiLocalEnvironment(env))
10970
+ throw new ImageGenerationError(
10971
+ "Image services are unavailable in this embedding environment."
10972
+ );
10973
+ return env.workspace.root ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? process.cwd();
10974
+ };
10975
+ const currentChat = async () => {
10976
+ const model = await resolveEffectiveModelConfig(state, workspace());
10977
+ const provider = model.provider ?? state.currentModelProvider ?? "openai";
10978
+ const saved = (await new AuthStore().load()).providers[provider];
10979
+ if (saved) return { provider, auth: saved };
10980
+ const key = provider === "openai" ? localImageAuth.env("OPENAI_API_KEY") : void 0;
10981
+ return key ? { provider, auth: { method: "api_key", api_key: key } } : void 0;
10982
+ };
10983
+ const status = async (config) => {
10984
+ try {
10985
+ const chat = config.mode === "builtin" ? await currentChat() : void 0;
10986
+ const route = await resolveImageRoute(config, localImageAuth, chat);
10987
+ if (!route)
10988
+ return {
10989
+ requested_mode: config.mode,
10990
+ state: "disabled",
10991
+ message: "Image generation is off. Conversation model is unchanged."
10992
+ };
10993
+ if (route.provider === "openrouter" && !(await catalog.endpoints(route.model)).some(
10994
+ (e) => e.provider_tag === route.endpoint
10995
+ ))
10996
+ throw new ImageGenerationError(
10997
+ "Selected image endpoint is unavailable; select another explicitly."
10998
+ );
10999
+ return {
11000
+ requested_mode: config.mode,
11001
+ state: "available",
11002
+ provider: route.provider,
11003
+ requested_model: route.model,
11004
+ endpoint: route.endpoint,
11005
+ auth_mode: route.authMode,
11006
+ 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.`
11007
+ };
11008
+ } catch (error) {
11009
+ return {
11010
+ requested_mode: config.mode,
11011
+ state: "unavailable",
11012
+ message: error instanceof ImageGenerationError ? error.message : "Image configuration/auth unavailable; chat is unchanged."
11013
+ };
11014
+ }
11015
+ };
11016
+ const pick = async (title, items) => {
11017
+ const result = await requestUiPick(state, { title, items });
11018
+ const selected = result?.ids[0];
11019
+ return items.some((i) => i.id === selected) ? selected : void 0;
11020
+ };
11021
+ const choose = async () => {
11022
+ if (!state.uiCapabilities?.supports_pick)
11023
+ throw new ImageGenerationError(
11024
+ "This client cannot open the image picker. Supply explicit mode/provider/model settings."
11025
+ );
11026
+ const mode = await pick(
11027
+ "Image generation (separate from conversation model)",
11028
+ [
11029
+ {
11030
+ id: "off",
11031
+ label: "Off",
11032
+ detail: "No image generation or image API spending"
11033
+ },
11034
+ {
11035
+ id: "builtin",
11036
+ label: "Builtin: current conversation connection",
11037
+ detail: "Use current OpenAI login: Codex OAuth or API key; no authentication switch"
11038
+ },
11039
+ {
11040
+ id: "custom",
11041
+ label: "Custom: independent image provider/model",
11042
+ detail: "API key required; does not change chat authentication"
11043
+ }
11044
+ ]
11045
+ );
11046
+ if (!mode) return null;
11047
+ if (mode === "off") return { mode };
11048
+ const provider = mode === "builtin" ? "openai" : await pick("Image API provider", [
11049
+ { id: "openai", label: "OpenAI Image API" },
11050
+ { id: "openrouter", label: "OpenRouter Image API" }
11051
+ ]);
11052
+ if (!provider) return null;
11053
+ let model;
11054
+ let endpoint;
11055
+ if (provider === "openai") {
11056
+ const chat = mode === "builtin" ? await currentChat() : void 0;
11057
+ if (mode === "builtin" && chat?.provider !== "openai")
11058
+ throw new ImageGenerationError(
11059
+ "Builtin images require an OpenAI conversation login. Sign in first; no API key is required for Codex OAuth."
11060
+ );
11061
+ const codex = chat?.auth.method === "oauth";
11062
+ model = await pick(
11063
+ codex ? "Codex OAuth image model (current login; account-specific limits)" : "Image model (API billed; availability is account-specific)",
11064
+ (codex ? OPENAI_CODEX_IMAGE_MODELS2 : OPENAI_IMAGE_MODELS2).map((id) => ({
11065
+ id,
11066
+ label: id,
11067
+ ...codex ? {
11068
+ detail: id === "gpt-image-2" ? "Inspected Codex tool default" : "Explicit request; support/effective model depends on the Codex backend"
11069
+ } : {}
11070
+ }))
11071
+ );
11072
+ } else {
11073
+ const listing = await catalog.list();
11074
+ model = await pick(
11075
+ `OpenRouter image models (${listing.stale ? "stale" : "fetched"} ${listing.fetched_at})`,
11076
+ listing.models.map((m) => ({ id: m.id, label: m.name, detail: m.id }))
11077
+ );
11078
+ if (!model) return null;
11079
+ const endpoints = await catalog.endpoints(model);
11080
+ if (!endpoints.length)
11081
+ throw new ImageGenerationError(
11082
+ "This model has no supported pin-able PNG endpoint. Choose another image model."
11083
+ );
11084
+ endpoint = await pick(
11085
+ "Pin image endpoint (no fallback)",
11086
+ endpoints.flatMap(
11087
+ (e) => e.provider_tag ? [{ id: e.provider_tag, label: e.provider_tag }] : []
11088
+ )
11089
+ );
11090
+ if (!endpoint) return null;
11091
+ }
11092
+ if (!model) return null;
11093
+ return parseImageGenerationConfig(
11094
+ mode === "builtin" ? { mode, provider_options: { openai: { model } } } : {
11095
+ mode,
11096
+ provider,
11097
+ model,
11098
+ ...endpoint ? { provider_options: { openrouter: { endpoint } } } : {}
11099
+ }
11100
+ );
11101
+ };
11102
+ const handle = async (id, operation, params) => {
11103
+ let ownsConfiguration = false;
11104
+ try {
11105
+ const root = workspace();
11106
+ if (operation === "artifact") {
11107
+ const parsed2 = z26.object({
11108
+ artifact_id: z26.string().regex(/^codelia-image-[0-9a-f-]{36}$/)
11109
+ }).strict().safeParse(params);
11110
+ if (!parsed2.success)
11111
+ throw new ImageGenerationError("Invalid image artifact request.");
11112
+ const { metadata, bytes } = await createLocalImageStore(root).read(
11113
+ parsed2.data.artifact_id
11114
+ );
11115
+ sendResult(id, {
11116
+ metadata,
11117
+ data_url: `data:${metadata.media_type};base64,${bytes.toString("base64")}`
11118
+ });
11119
+ return;
11120
+ }
11121
+ if (operation === "get") {
11122
+ sendResult(id, await status(await resolveImageGenerationConfig(root)));
11123
+ return;
11124
+ }
11125
+ if (state.activeRunId || configuring)
11126
+ throw new ImageGenerationError(
11127
+ "Wait for the active run or image settings dialog before changing image settings."
11128
+ );
11129
+ configuring = true;
11130
+ ownsConfiguration = true;
11131
+ const parsed = paramsSchema.safeParse(params ?? {});
11132
+ if (!parsed.success)
11133
+ throw new ImageGenerationError("Invalid image model settings.");
11134
+ const p = parsed.data;
11135
+ let config;
11136
+ if (p.mode) {
11137
+ if (p.mode !== "custom" && (p.provider || p.endpoint || p.api_key_env))
11138
+ throw new ImageGenerationError(
11139
+ "Provider, endpoint and api_key_env are custom-only."
11140
+ );
11141
+ config = parseImageGenerationConfig(
11142
+ p.mode === "off" ? { mode: p.mode, ...p.model ? { model: p.model } : {} } : p.mode === "builtin" ? {
11143
+ mode: p.mode,
11144
+ ...p.model ? { provider_options: { openai: { model: p.model } } } : {}
11145
+ } : {
11146
+ mode: p.mode,
11147
+ provider: p.provider,
11148
+ model: p.model,
11149
+ ...p.api_key_env ? { api_key_env: p.api_key_env } : {},
11150
+ ...p.endpoint ? {
11151
+ provider_options: {
11152
+ openrouter: { endpoint: p.endpoint }
11153
+ }
11154
+ } : {}
11155
+ }
11156
+ );
11157
+ } else {
11158
+ if (Object.keys(p).length)
11159
+ throw new ImageGenerationError(
11160
+ "mode is required for explicit image settings."
11161
+ );
11162
+ config = await choose();
11163
+ }
11164
+ if (!config) {
11165
+ sendResult(id, { message: "Image settings unchanged." });
11166
+ return;
11167
+ }
11168
+ const next = await status(config);
11169
+ if (config.mode !== "off") {
11170
+ if (!state.uiCapabilities?.supports_confirm)
11171
+ throw new ImageGenerationError(
11172
+ "Image route changes require a confirmation-capable UI; headless users can explicitly edit image_generation in config.json."
11173
+ );
11174
+ const confirm = await requestUiConfirm(state, {
11175
+ title: "Save image generation route?",
11176
+ message: `${next.message}
11177
+ 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."}`,
11178
+ confirm_label: "Save",
11179
+ cancel_label: "Cancel"
11180
+ });
11181
+ if (!confirm?.ok) {
11182
+ sendResult(id, { message: "Image settings unchanged." });
11183
+ return;
11184
+ }
9625
11185
  }
11186
+ if (state.activeRunId)
11187
+ throw new ImageGenerationError(
11188
+ "A run started; image settings were not changed. Try again after it finishes."
11189
+ );
11190
+ await updateImageGeneration(root, config);
11191
+ state.agent = null;
11192
+ state.tools = null;
11193
+ state.toolDefinitions = null;
11194
+ sendResult(id, next);
11195
+ } catch (error) {
11196
+ sendError(id, {
11197
+ code: RPC_ERROR_CODE4.INVALID_PARAMS,
11198
+ message: error instanceof ImageGenerationError ? error.message : "Image operation failed; check settings, artifact and runtime storage. No credentials were changed."
11199
+ });
11200
+ } finally {
11201
+ if (ownsConfiguration) configuring = false;
9626
11202
  }
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);
9634
11203
  };
9635
- return { handleSessionList, handleSessionHistory };
9636
- };
11204
+ return { handle };
11205
+ }
9637
11206
 
9638
11207
  // src/rpc/model.ts
9639
11208
  import {
@@ -9646,9 +11215,12 @@ import {
9646
11215
  } from "@codelia/core";
9647
11216
  import { ModelMetadataServiceImpl as ModelMetadataServiceImpl2 } from "@codelia/model-metadata";
9648
11217
  import {
9649
- RPC_ERROR_CODE as RPC_ERROR_CODE3
11218
+ RPC_ERROR_CODE as RPC_ERROR_CODE5
9650
11219
  } from "@codelia/protocol";
9651
- var isSupportedProvider = (provider) => provider === "openai" || provider === "anthropic" || provider === "openrouter" || provider === "moonshot" || provider === "zai" || provider === "xai";
11220
+ import {
11221
+ isModelFastMode as isModelFastMode2
11222
+ } from "@codelia/shared-types";
11223
+ var isSupportedProvider = (provider, providers) => SUPPORTED_PROVIDERS.includes(provider) || Boolean(providers && Object.hasOwn(providers, provider));
9652
11224
  var resolveProviderModelEntry2 = (providerEntries, provider, model) => {
9653
11225
  if (!providerEntries) {
9654
11226
  return null;
@@ -9897,8 +11469,34 @@ var buildProviderModelList = async ({
9897
11469
  includeDetails,
9898
11470
  state,
9899
11471
  log: log2,
9900
- providerEntriesOverride
11472
+ providerEntriesOverride,
11473
+ providers
9901
11474
  }) => {
11475
+ const effectiveProviders = providers ?? (state ? (await resolveEnvironmentModelConfig(
11476
+ state,
11477
+ state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0
11478
+ )).providers : void 0);
11479
+ const endpoint = getResponsesProvider(
11480
+ { providers: effectiveProviders },
11481
+ provider
11482
+ );
11483
+ if (endpoint) {
11484
+ const models2 = Object.keys(endpoint.models);
11485
+ const details2 = includeDetails ? Object.fromEntries(
11486
+ models2.map((model) => {
11487
+ const spec = endpoint.models[model];
11488
+ return [
11489
+ model,
11490
+ {
11491
+ context_window: spec.context_window,
11492
+ max_input_tokens: spec.max_input_tokens,
11493
+ max_output_tokens: spec.max_output_tokens
11494
+ }
11495
+ ];
11496
+ })
11497
+ ) : void 0;
11498
+ return { models: models2, ...details2 ? { details: details2 } : {} };
11499
+ }
9902
11500
  if (provider === "openrouter") {
9903
11501
  return buildOpenRouterModelList({ includeDetails, state, log: log2 });
9904
11502
  }
@@ -9954,6 +11552,21 @@ var createModelHandlers = ({
9954
11552
  log: log2,
9955
11553
  sessionStateStore
9956
11554
  }) => {
11555
+ const validateFastSelection = async (provider, name, fast) => {
11556
+ const effectiveFast = effectiveFastMode({
11557
+ provider,
11558
+ model: name,
11559
+ requested: fast
11560
+ });
11561
+ if (fast === "ultrafast") {
11562
+ const auth = state.effectiveEnvironment.auth.model === "host" ? await state.effectiveEnvironment.adapters.credentialProvider?.resolveProviderAuth(
11563
+ provider
11564
+ ) : (await new AuthStore().load()).providers[provider];
11565
+ const method = auth?.method ?? (state.effectiveEnvironment.auth.model !== "host" && readEnvValue("OPENAI_API_KEY") ? "api_key" : "missing");
11566
+ assertUltrafastAuth(fast, method);
11567
+ }
11568
+ return effectiveFast;
11569
+ };
9957
11570
  const persistSessionModelOverride = async () => {
9958
11571
  const sessionId = state.sessionId;
9959
11572
  const snapshot = sessionId && sessionStateStore ? await sessionStateStore.load(sessionId) : null;
@@ -9972,13 +11585,7 @@ var createModelHandlers = ({
9972
11585
  const handleModelList = async (id, params) => {
9973
11586
  const requestedProvider = params?.provider;
9974
11587
  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
- }
11588
+ let providers;
9982
11589
  let current;
9983
11590
  let source = "config";
9984
11591
  let configuredProvider;
@@ -9987,6 +11594,7 @@ var createModelHandlers = ({
9987
11594
  try {
9988
11595
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0;
9989
11596
  const config = await resolveEffectiveModelConfig(state, workingDir);
11597
+ providers = config.providers;
9990
11598
  source = config.source;
9991
11599
  configuredProvider = config.provider ?? "openai";
9992
11600
  configuredReasoning = resolveReasoningEffort(config.reasoning);
@@ -9994,23 +11602,23 @@ var createModelHandlers = ({
9994
11602
  current = config.name;
9995
11603
  }
9996
11604
  if (config.fast !== void 0 && config.name && isSupportedProvider(configuredProvider)) {
9997
- configuredFast = resolveFastMode({
11605
+ configuredFast = effectiveFastMode({
9998
11606
  provider: configuredProvider,
9999
11607
  model: config.name,
10000
11608
  requested: config.fast
10001
- }).enabled;
11609
+ });
10002
11610
  }
10003
11611
  } catch (error) {
10004
11612
  sendError(id, {
10005
- code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
11613
+ code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
10006
11614
  message: String(error)
10007
11615
  });
10008
11616
  return;
10009
11617
  }
10010
11618
  const provider = requestedProvider ?? configuredProvider ?? "openai";
10011
- if (!isSupportedProvider(provider)) {
11619
+ if (!isSupportedProvider(provider, providers)) {
10012
11620
  sendError(id, {
10013
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11621
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
10014
11622
  message: `unsupported provider: ${provider}`
10015
11623
  });
10016
11624
  return;
@@ -10021,6 +11629,7 @@ var createModelHandlers = ({
10021
11629
  const result2 = await buildProviderModelList({
10022
11630
  provider,
10023
11631
  includeDetails,
11632
+ providers,
10024
11633
  state,
10025
11634
  log: log2
10026
11635
  });
@@ -10028,7 +11637,7 @@ var createModelHandlers = ({
10028
11637
  details = result2.details;
10029
11638
  } catch (error) {
10030
11639
  sendError(id, {
10031
- code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
11640
+ code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
10032
11641
  message: String(error)
10033
11642
  });
10034
11643
  return;
@@ -10036,8 +11645,17 @@ var createModelHandlers = ({
10036
11645
  if (current && !models.includes(current)) {
10037
11646
  current = void 0;
10038
11647
  }
11648
+ const endpoint = getResponsesProvider({ providers }, provider);
11649
+ const reasoningLevels = endpoint ? Object.fromEntries(
11650
+ Object.entries(endpoint.models).map(([name, spec]) => [
11651
+ name,
11652
+ spec.supports_reasoning ? spec.reasoning_levels ?? ["low", "medium", "high"] : []
11653
+ ])
11654
+ ) : void 0;
10039
11655
  const result = {
11656
+ ...reasoningLevels ? { reasoning_levels: reasoningLevels } : {},
10040
11657
  provider,
11658
+ providers: configuredProviders(providers),
10041
11659
  models,
10042
11660
  current,
10043
11661
  source,
@@ -10050,7 +11668,7 @@ var createModelHandlers = ({
10050
11668
  const handleModelSet = async (id, params) => {
10051
11669
  if (state.activeRunId) {
10052
11670
  sendError(id, {
10053
- code: RPC_ERROR_CODE3.RUNTIME_BUSY,
11671
+ code: RPC_ERROR_CODE5.RUNTIME_BUSY,
10054
11672
  message: "runtime busy"
10055
11673
  });
10056
11674
  return;
@@ -10058,7 +11676,7 @@ var createModelHandlers = ({
10058
11676
  const scope = params?.scope ?? "config";
10059
11677
  if (scope !== "config" && scope !== "session") {
10060
11678
  sendError(id, {
10061
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11679
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
10062
11680
  message: `unsupported model scope: ${scope}`
10063
11681
  });
10064
11682
  return;
@@ -10067,34 +11685,44 @@ var createModelHandlers = ({
10067
11685
  if (params?.reset) {
10068
11686
  if (scope !== "session") {
10069
11687
  sendError(id, {
10070
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11688
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
10071
11689
  message: "model reset is only supported for session scope"
10072
11690
  });
10073
11691
  return;
10074
11692
  }
10075
11693
  try {
10076
- clearSessionModelOverride(state);
10077
- await persistSessionModelOverride();
10078
11694
  const config = await resolveEnvironmentModelConfig(state, workingDir);
10079
11695
  const provider2 = config.provider ?? "openai";
10080
11696
  const name2 = config.name;
10081
11697
  if (!name2) {
10082
11698
  sendError(id, {
10083
- code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
11699
+ code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
10084
11700
  message: "configured model name is missing"
10085
11701
  });
10086
11702
  return;
10087
11703
  }
11704
+ let effectiveReasoning;
11705
+ let effectiveFast;
11706
+ try {
11707
+ effectiveReasoning = getResponsesProvider(config, provider2) ? resolveConfiguredReasoning(config, provider2, name2) : resolveReasoningEffort(config.reasoning);
11708
+ effectiveFast = await validateFastSelection(
11709
+ provider2,
11710
+ name2,
11711
+ config.fast
11712
+ );
11713
+ } catch (error) {
11714
+ sendError(id, {
11715
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
11716
+ message: String(error)
11717
+ });
11718
+ return;
11719
+ }
11720
+ clearSessionModelOverride(state);
11721
+ await persistSessionModelOverride();
10088
11722
  state.currentModelProvider = provider2;
10089
11723
  state.currentModelName = name2;
10090
11724
  state.currentModelSource = "config";
10091
11725
  state.agent = null;
10092
- const effectiveReasoning = resolveReasoningEffort(config.reasoning);
10093
- const effectiveFast = isSupportedProvider(provider2) ? resolveFastMode({
10094
- provider: provider2,
10095
- model: name2,
10096
- requested: config.fast
10097
- }).enabled : false;
10098
11726
  const result = {
10099
11727
  provider: provider2,
10100
11728
  name: name2,
@@ -10106,7 +11734,7 @@ var createModelHandlers = ({
10106
11734
  log2(`model.set reset session override -> ${provider2}/${name2}`);
10107
11735
  } catch (error) {
10108
11736
  sendError(id, {
10109
- code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
11737
+ code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
10110
11738
  message: String(error)
10111
11739
  });
10112
11740
  }
@@ -10116,7 +11744,7 @@ var createModelHandlers = ({
10116
11744
  const name = params?.name?.trim();
10117
11745
  if (!name) {
10118
11746
  sendError(id, {
10119
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11747
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
10120
11748
  message: "model name is required"
10121
11749
  });
10122
11750
  return;
@@ -10127,29 +11755,61 @@ var createModelHandlers = ({
10127
11755
  reasoning = resolveReasoningEffort(params.reasoning);
10128
11756
  } catch (error) {
10129
11757
  sendError(id, {
10130
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11758
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
10131
11759
  message: String(error)
10132
11760
  });
10133
11761
  return;
10134
11762
  }
10135
11763
  }
10136
- if (provider !== "openai" && provider !== "anthropic" && provider !== "openrouter" && provider !== "moonshot" && provider !== "zai" && provider !== "xai") {
11764
+ const configured = await resolveEnvironmentModelConfig(state, workingDir);
11765
+ const endpoint = getResponsesProvider(configured, provider);
11766
+ if (!isSupportedProvider(provider, configured.providers)) {
10137
11767
  sendError(id, {
10138
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11768
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
10139
11769
  message: `unsupported provider: ${provider}`
10140
11770
  });
10141
11771
  return;
10142
11772
  }
10143
11773
  if (provider !== "openrouter") {
10144
- const spec = resolveModel2(DEFAULT_MODEL_REGISTRY3, name, provider);
11774
+ const spec = resolveModel2(
11775
+ buildConfiguredModelRegistry(configured.providers),
11776
+ name,
11777
+ provider
11778
+ );
10145
11779
  if (!spec) {
10146
11780
  sendError(id, {
10147
- code: RPC_ERROR_CODE3.INVALID_PARAMS,
11781
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
10148
11782
  message: `unknown model: ${name}`
10149
11783
  });
10150
11784
  return;
10151
11785
  }
10152
11786
  }
11787
+ const baseConfig = scope === "session" ? mergeModelOverride(configured, state.sessionModelOverride) : configured;
11788
+ const candidate = {
11789
+ ...baseConfig,
11790
+ provider,
11791
+ name,
11792
+ reasoning: reasoning ?? baseConfig.reasoning,
11793
+ fast: params.fast ?? baseConfig.fast
11794
+ };
11795
+ try {
11796
+ if (endpoint) {
11797
+ if (reasoning && !endpoint.models[name]?.supports_reasoning)
11798
+ throw new Error(`Reasoning is disabled for ${provider}/${name}`);
11799
+ resolveConfiguredReasoning(candidate, provider, name);
11800
+ }
11801
+ candidate.reasoning = resolveReasoningEffort(candidate.reasoning);
11802
+ if (params.fast !== void 0 && !isModelFastMode2(params.fast)) {
11803
+ throw new Error('model.fast must be true, false, or "ultrafast"');
11804
+ }
11805
+ await validateFastSelection(provider, name, candidate.fast);
11806
+ } catch (error) {
11807
+ sendError(id, {
11808
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
11809
+ message: String(error)
11810
+ });
11811
+ return;
11812
+ }
10153
11813
  try {
10154
11814
  let target = null;
10155
11815
  if (scope === "config") {
@@ -10162,15 +11822,11 @@ var createModelHandlers = ({
10162
11822
  clearSessionModelOverride(state);
10163
11823
  await persistSessionModelOverride();
10164
11824
  } else {
10165
- const baseConfig = await resolveEnvironmentModelConfig(
10166
- state,
10167
- workingDir
10168
- );
10169
- setSessionModelOverride(state, baseConfig, {
11825
+ setSessionModelOverride(state, configured, {
10170
11826
  provider,
10171
11827
  name,
10172
- ...reasoning ? { reasoning } : {},
10173
- ...params.fast !== void 0 ? { fast: params.fast } : {}
11828
+ reasoning: resolveReasoningEffort(candidate.reasoning),
11829
+ fast: candidate.fast
10174
11830
  });
10175
11831
  await persistSessionModelOverride();
10176
11832
  }
@@ -10185,11 +11841,11 @@ var createModelHandlers = ({
10185
11841
  const effectiveReasoning = resolveReasoningEffort(
10186
11842
  updatedConfig.reasoning
10187
11843
  );
10188
- const effectiveFast = resolveFastMode({
11844
+ const effectiveFast = effectiveFastMode({
10189
11845
  provider,
10190
11846
  model: name,
10191
11847
  requested: updatedConfig.fast
10192
- }).enabled;
11848
+ });
10193
11849
  const result = {
10194
11850
  provider,
10195
11851
  name,
@@ -10204,7 +11860,7 @@ var createModelHandlers = ({
10204
11860
  );
10205
11861
  } catch (error) {
10206
11862
  sendError(id, {
10207
- code: RPC_ERROR_CODE3.RUNTIME_INTERNAL,
11863
+ code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
10208
11864
  message: String(error)
10209
11865
  });
10210
11866
  }
@@ -10214,7 +11870,7 @@ var createModelHandlers = ({
10214
11870
 
10215
11871
  // src/rpc/resume-context.ts
10216
11872
  import { promises as fs15 } from "fs";
10217
- import path13 from "path";
11873
+ import path16 from "path";
10218
11874
  var RESUME_CONTEXT_META_KEY = "codelia_resume_context";
10219
11875
  var RESUME_CONTEXT_SCHEMA_VERSION = 1;
10220
11876
  var RESUME_DIFF_TAG = '<system-reminder type="session.resume.diff">';
@@ -10223,7 +11879,7 @@ var normalizePath2 = (value) => {
10223
11879
  if (typeof value !== "string") return void 0;
10224
11880
  const trimmed = value.trim();
10225
11881
  if (!trimmed) return void 0;
10226
- return path13.resolve(trimmed);
11882
+ return path16.resolve(trimmed);
10227
11883
  };
10228
11884
  var normalizeMtime3 = (value) => {
10229
11885
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
@@ -10586,7 +12242,7 @@ var buildResumeDiff = async (meta, state, options = {}) => {
10586
12242
 
10587
12243
  // src/rpc/run.ts
10588
12244
  import {
10589
- RPC_ERROR_CODE as RPC_ERROR_CODE4
12245
+ RPC_ERROR_CODE as RPC_ERROR_CODE6
10590
12246
  } from "@codelia/protocol";
10591
12247
 
10592
12248
  // src/rpc/client-tool-requests.ts
@@ -10901,6 +12557,17 @@ var summarizeProviderMeta = (value) => {
10901
12557
  if (typeof value === "object") {
10902
12558
  const obj = value;
10903
12559
  const details = [];
12560
+ const codex = obj.codex_metadata;
12561
+ if (codex && typeof codex === "object" && !Array.isArray(codex)) {
12562
+ const metadata = codex;
12563
+ if (typeof metadata.server_model === "string" && /^[a-zA-Z0-9._/-]{1,128}$/.test(metadata.server_model))
12564
+ details.push(`server_model=${metadata.server_model}`);
12565
+ if (Array.isArray(metadata.model_verifications) && metadata.model_verifications.includes("trusted_access_for_cyber"))
12566
+ details.push("verification=trusted_access_for_cyber");
12567
+ if (metadata.moderation_metadata_present === true)
12568
+ details.push("moderation_metadata=present");
12569
+ if (metadata.safety_buffering) details.push("safety_buffering=observed");
12570
+ }
10904
12571
  if (typeof obj.transport === "string") {
10905
12572
  details.push(`transport=${obj.transport}`);
10906
12573
  }
@@ -11054,6 +12721,24 @@ var runInputLengthForDebug = (input) => {
11054
12721
  return total;
11055
12722
  };
11056
12723
 
12724
+ // src/rpc/run-metrics.ts
12725
+ var buildRunMetrics = (record) => {
12726
+ const timing = record.output.timing;
12727
+ const tokens = record.output.usage?.output_tokens;
12728
+ const duration = timing?.generation_duration_ms;
12729
+ const reasoning = record.output.usage?.output_reasoning_tokens;
12730
+ 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");
12731
+ 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);
12732
+ const rate = validTiming && matchedReasoning && typeof tokens === "number" && Number.isFinite(tokens) && tokens >= 0 && // Very short/batched streams do not expose a useful generation interval.
12733
+ duration >= 250 ? tokens * 1e3 / duration : null;
12734
+ return {
12735
+ run_id: record.run_id,
12736
+ seq: record.seq,
12737
+ output_tokens_per_second: rate !== null && Number.isFinite(rate) ? rate : null,
12738
+ ...validTiming ? { timing } : {}
12739
+ };
12740
+ };
12741
+
11057
12742
  // src/rpc/run.ts
11058
12743
  var nowIso4 = () => (/* @__PURE__ */ new Date()).toISOString();
11059
12744
  var SESSION_STATE_SAVE_DEBOUNCE_MS = 1500;
@@ -11178,7 +12863,7 @@ var createRunHandlers = ({
11178
12863
  normalizedInput = normalizeRunInput(params.input);
11179
12864
  } catch (error) {
11180
12865
  sendError(id, {
11181
- code: RPC_ERROR_CODE4.INVALID_PARAMS,
12866
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11182
12867
  message: String(error)
11183
12868
  });
11184
12869
  return;
@@ -11188,7 +12873,7 @@ var createRunHandlers = ({
11188
12873
  await beforeRunStart();
11189
12874
  } catch (error) {
11190
12875
  sendError(id, {
11191
- code: RPC_ERROR_CODE4.RUNTIME_INTERNAL,
12876
+ code: RPC_ERROR_CODE6.RUNTIME_INTERNAL,
11192
12877
  message: `startup onboarding failed: ${String(error)}`
11193
12878
  });
11194
12879
  return;
@@ -11196,7 +12881,7 @@ var createRunHandlers = ({
11196
12881
  }
11197
12882
  if (state.activeRunId) {
11198
12883
  sendError(id, {
11199
- code: RPC_ERROR_CODE4.RUNTIME_BUSY,
12884
+ code: RPC_ERROR_CODE6.RUNTIME_BUSY,
11200
12885
  message: "runtime busy"
11201
12886
  });
11202
12887
  return;
@@ -11211,14 +12896,14 @@ var createRunHandlers = ({
11211
12896
  resumeState = await sessionStateStore.load(requestedSessionId);
11212
12897
  } catch (error) {
11213
12898
  sendError(id, {
11214
- code: RPC_ERROR_CODE4.SESSION_LOAD_FAILED,
12899
+ code: RPC_ERROR_CODE6.SESSION_LOAD_FAILED,
11215
12900
  message: `session load failed: ${String(error)}`
11216
12901
  });
11217
12902
  return;
11218
12903
  }
11219
12904
  if (!resumeState) {
11220
12905
  sendError(id, {
11221
- code: RPC_ERROR_CODE4.SESSION_NOT_FOUND,
12906
+ code: RPC_ERROR_CODE6.SESSION_NOT_FOUND,
11222
12907
  message: "session not found"
11223
12908
  });
11224
12909
  return;
@@ -11229,7 +12914,7 @@ var createRunHandlers = ({
11229
12914
  resumeState = await sessionStateStore.load(state.sessionId);
11230
12915
  } catch (error) {
11231
12916
  sendError(id, {
11232
- code: RPC_ERROR_CODE4.SESSION_LOAD_FAILED,
12917
+ code: RPC_ERROR_CODE6.SESSION_LOAD_FAILED,
11233
12918
  message: `session reload failed: ${String(error)}`
11234
12919
  });
11235
12920
  return;
@@ -11240,7 +12925,7 @@ var createRunHandlers = ({
11240
12925
  }
11241
12926
  if (resumeState?.meta?.codelia_subagent) {
11242
12927
  sendError(id, {
11243
- code: RPC_ERROR_CODE4.INVALID_PARAMS,
12928
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11244
12929
  message: "Delegated sessions cannot be resumed as a root run"
11245
12930
  });
11246
12931
  return;
@@ -11248,9 +12933,12 @@ var createRunHandlers = ({
11248
12933
  let runtimeAgent;
11249
12934
  try {
11250
12935
  runtimeAgent = await getAgent();
12936
+ if (!params.force_compaction && state.prepareRunImages) {
12937
+ normalizedInput = await state.prepareRunImages(normalizedInput);
12938
+ }
11251
12939
  } catch (error) {
11252
12940
  sendError(id, {
11253
- code: RPC_ERROR_CODE4.RUNTIME_INTERNAL,
12941
+ code: RPC_ERROR_CODE6.RUNTIME_INTERNAL,
11254
12942
  message: String(error)
11255
12943
  });
11256
12944
  return;
@@ -11311,7 +12999,7 @@ var createRunHandlers = ({
11311
12999
  );
11312
13000
  } catch (error) {
11313
13001
  sendError(id, {
11314
- code: RPC_ERROR_CODE4.INVALID_PARAMS,
13002
+ code: RPC_ERROR_CODE6.INVALID_PARAMS,
11315
13003
  message: String(error)
11316
13004
  });
11317
13005
  return;
@@ -11365,6 +13053,24 @@ var createRunHandlers = ({
11365
13053
  }
11366
13054
  };
11367
13055
  const sessionAppend = (record) => {
13056
+ if (record.type === "llm.request") {
13057
+ try {
13058
+ sendRunMetrics(state, {
13059
+ run_id: record.run_id,
13060
+ seq: record.seq,
13061
+ output_tokens_per_second: null
13062
+ });
13063
+ } catch (error) {
13064
+ log2(`run metrics reset failed: ${String(error)}`);
13065
+ }
13066
+ }
13067
+ if (record.type === "llm.response") {
13068
+ try {
13069
+ sendRunMetrics(state, buildRunMetrics(record));
13070
+ } catch (error) {
13071
+ log2(`run metrics emit failed: ${String(error)}`);
13072
+ }
13073
+ }
11368
13074
  if (state.diagnosticsEnabled) {
11369
13075
  try {
11370
13076
  if (record.type === "llm.request") {
@@ -11387,6 +13093,7 @@ var createRunHandlers = ({
11387
13093
  const requestTsMs = request ? toTimestampMs(request.ts) : null;
11388
13094
  const latencyMs = responseTsMs !== null && requestTsMs !== null ? Math.max(0, responseTsMs - requestTsMs) : 0;
11389
13095
  const model = usage?.model ?? request?.model ?? "unknown";
13096
+ const metrics = buildRunMetrics(record);
11390
13097
  const diagnostics = {
11391
13098
  run_id: runId,
11392
13099
  seq: record.seq,
@@ -11395,6 +13102,8 @@ var createRunHandlers = ({
11395
13102
  request_ts: request?.ts ?? record.ts,
11396
13103
  response_ts: record.ts,
11397
13104
  latency_ms: latencyMs,
13105
+ ...metrics.timing ? { timing: metrics.timing } : {},
13106
+ output_tokens_per_second: metrics.output_tokens_per_second,
11398
13107
  stop_reason: record.output.stop_reason ?? null,
11399
13108
  usage,
11400
13109
  cache: {
@@ -11475,7 +13184,7 @@ var createRunHandlers = ({
11475
13184
  run_id: runId,
11476
13185
  session_id: sessionId,
11477
13186
  ts: nowIso4(),
11478
- input: params.input,
13187
+ input: Array.isArray(normalizedInput) && normalizedInput.some((part) => part.type === "image_ref") ? { type: "parts", parts: normalizedInput } : params.input,
11479
13188
  ui_context: params.ui_context,
11480
13189
  meta: params.meta
11481
13190
  });
@@ -11681,7 +13390,7 @@ var createRunHandlers = ({
11681
13390
  return;
11682
13391
  }
11683
13392
  sendError(id, {
11684
- code: RPC_ERROR_CODE4.RUN_NOT_FOUND,
13393
+ code: RPC_ERROR_CODE6.RUN_NOT_FOUND,
11685
13394
  message: "run not found"
11686
13395
  });
11687
13396
  };
@@ -11689,9 +13398,9 @@ var createRunHandlers = ({
11689
13398
  };
11690
13399
 
11691
13400
  // src/rpc/shell.ts
11692
- import path14 from "path";
13401
+ import path17 from "path";
11693
13402
  import {
11694
- RPC_ERROR_CODE as RPC_ERROR_CODE5
13403
+ RPC_ERROR_CODE as RPC_ERROR_CODE7
11695
13404
  } from "@codelia/protocol";
11696
13405
  import {
11697
13406
  ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl3
@@ -11708,14 +13417,14 @@ var truncateCommandPreview = (value) => {
11708
13417
  return `${trimmed.slice(0, COMMAND_PREVIEW_CHARS)}...[truncated]`;
11709
13418
  };
11710
13419
  var isWithin2 = (basePath, candidatePath) => {
11711
- const relative = path14.relative(basePath, candidatePath);
11712
- return relative === "" || !relative.startsWith("..") && !path14.isAbsolute(relative);
13420
+ const relative = path17.relative(basePath, candidatePath);
13421
+ return relative === "" || !relative.startsWith("..") && !path17.isAbsolute(relative);
11713
13422
  };
11714
13423
  var resolveShellCwd = (state, requestedCwd) => {
11715
13424
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
11716
13425
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
11717
13426
  if (!requestedCwd) return workingDir;
11718
- const resolved = path14.resolve(workingDir, requestedCwd);
13427
+ const resolved = path17.resolve(workingDir, requestedCwd);
11719
13428
  if (!isWithin2(rootDir, resolved)) {
11720
13429
  return null;
11721
13430
  }
@@ -11750,7 +13459,7 @@ var parseShellOutputRequest = (params) => {
11750
13459
  if (!taskId) {
11751
13460
  return {
11752
13461
  error: {
11753
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13462
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11754
13463
  message: "task_id is required"
11755
13464
  }
11756
13465
  };
@@ -11758,7 +13467,7 @@ var parseShellOutputRequest = (params) => {
11758
13467
  if (params?.stream !== "stdout" && params?.stream !== "stderr") {
11759
13468
  return {
11760
13469
  error: {
11761
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13470
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11762
13471
  message: "stream must be stdout or stderr"
11763
13472
  }
11764
13473
  };
@@ -11766,7 +13475,7 @@ var parseShellOutputRequest = (params) => {
11766
13475
  if (params.line_number !== void 0 && (params.offset !== void 0 || params.limit !== void 0)) {
11767
13476
  return {
11768
13477
  error: {
11769
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13478
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11770
13479
  message: "line_number cannot be combined with offset or limit"
11771
13480
  }
11772
13481
  };
@@ -11774,7 +13483,7 @@ var parseShellOutputRequest = (params) => {
11774
13483
  if (params.line_number === void 0 && (params.char_offset !== void 0 || params.char_limit !== void 0)) {
11775
13484
  return {
11776
13485
  error: {
11777
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13486
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11778
13487
  message: "char_offset/char_limit require line_number"
11779
13488
  }
11780
13489
  };
@@ -11782,7 +13491,7 @@ var parseShellOutputRequest = (params) => {
11782
13491
  if (params.offset !== void 0 && (!Number.isFinite(params.offset) || params.offset < 0)) {
11783
13492
  return {
11784
13493
  error: {
11785
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13494
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11786
13495
  message: "offset must be a non-negative number"
11787
13496
  }
11788
13497
  };
@@ -11790,7 +13499,7 @@ var parseShellOutputRequest = (params) => {
11790
13499
  if (params.limit !== void 0 && (!Number.isFinite(params.limit) || params.limit <= 0)) {
11791
13500
  return {
11792
13501
  error: {
11793
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13502
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11794
13503
  message: "limit must be a positive number"
11795
13504
  }
11796
13505
  };
@@ -11798,7 +13507,7 @@ var parseShellOutputRequest = (params) => {
11798
13507
  if (params.line_number !== void 0 && (!Number.isFinite(params.line_number) || params.line_number <= 0)) {
11799
13508
  return {
11800
13509
  error: {
11801
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13510
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11802
13511
  message: "line_number must be a positive number"
11803
13512
  }
11804
13513
  };
@@ -11806,7 +13515,7 @@ var parseShellOutputRequest = (params) => {
11806
13515
  if (params.char_offset !== void 0 && (!Number.isFinite(params.char_offset) || params.char_offset < 0)) {
11807
13516
  return {
11808
13517
  error: {
11809
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13518
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11810
13519
  message: "char_offset must be a non-negative number"
11811
13520
  }
11812
13521
  };
@@ -11814,7 +13523,7 @@ var parseShellOutputRequest = (params) => {
11814
13523
  if (params.char_limit !== void 0 && (!Number.isFinite(params.char_limit) || params.char_limit <= 0)) {
11815
13524
  return {
11816
13525
  error: {
11817
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13526
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11818
13527
  message: "char_limit must be a positive number"
11819
13528
  }
11820
13529
  };
@@ -11868,7 +13577,7 @@ var parseTaskId = (value) => {
11868
13577
  var toTaskRpcError = (error) => {
11869
13578
  if (!(error instanceof TaskManagerError)) {
11870
13579
  return {
11871
- code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
13580
+ code: RPC_ERROR_CODE7.RUNTIME_INTERNAL,
11872
13581
  message: String(error)
11873
13582
  };
11874
13583
  }
@@ -11877,17 +13586,17 @@ var toTaskRpcError = (error) => {
11877
13586
  case "invalid_task_id":
11878
13587
  case "unsupported_workspace_mode":
11879
13588
  return {
11880
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13589
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11881
13590
  message: error.message
11882
13591
  };
11883
13592
  case "manager_shutting_down":
11884
13593
  return {
11885
- code: RPC_ERROR_CODE5.RUNTIME_BUSY,
13594
+ code: RPC_ERROR_CODE7.RUNTIME_BUSY,
11886
13595
  message: error.message
11887
13596
  };
11888
13597
  default:
11889
13598
  return {
11890
- code: RPC_ERROR_CODE5.RUNTIME_INTERNAL,
13599
+ code: RPC_ERROR_CODE7.RUNTIME_INTERNAL,
11891
13600
  message: error.message
11892
13601
  };
11893
13602
  }
@@ -11911,7 +13620,7 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
11911
13620
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
11912
13621
  return {
11913
13622
  error: {
11914
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13623
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11915
13624
  message: "timeout_seconds must be a positive number"
11916
13625
  }
11917
13626
  };
@@ -11925,7 +13634,7 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
11925
13634
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
11926
13635
  return {
11927
13636
  error: {
11928
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13637
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11929
13638
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
11930
13639
  }
11931
13640
  };
@@ -11939,7 +13648,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
11939
13648
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
11940
13649
  return {
11941
13650
  error: {
11942
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13651
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11943
13652
  message: "wait_timeout_seconds must be a positive number"
11944
13653
  }
11945
13654
  };
@@ -11947,7 +13656,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
11947
13656
  if (requestedTimeout > MAX_TIMEOUT_SECONDS) {
11948
13657
  return {
11949
13658
  error: {
11950
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13659
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11951
13660
  message: `wait_timeout_seconds must be ${MAX_TIMEOUT_SECONDS} seconds or less`
11952
13661
  }
11953
13662
  };
@@ -11962,7 +13671,7 @@ var parseShellStartRequest = (state, params, options) => {
11962
13671
  if (!command) {
11963
13672
  return {
11964
13673
  error: {
11965
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13674
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11966
13675
  message: "command is required"
11967
13676
  }
11968
13677
  };
@@ -11978,7 +13687,7 @@ var parseShellStartRequest = (state, params, options) => {
11978
13687
  if (!cwd) {
11979
13688
  return {
11980
13689
  error: {
11981
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13690
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
11982
13691
  message: "cwd is outside sandbox root"
11983
13692
  }
11984
13693
  };
@@ -12073,7 +13782,7 @@ var createShellHandlers = ({
12073
13782
  const requestedLimit = params?.limit;
12074
13783
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
12075
13784
  sendError(id, {
12076
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13785
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
12077
13786
  message: "limit must be a positive number"
12078
13787
  });
12079
13788
  return;
@@ -12091,7 +13800,7 @@ var createShellHandlers = ({
12091
13800
  const taskId = parseTaskId(params?.task_id);
12092
13801
  if (!taskId) {
12093
13802
  sendError(id, {
12094
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13803
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
12095
13804
  message: "task_id is required"
12096
13805
  });
12097
13806
  return;
@@ -12119,7 +13828,7 @@ var createShellHandlers = ({
12119
13828
  );
12120
13829
  if (!cacheId && liveContent === null && !isTerminalTaskState(task.state)) {
12121
13830
  sendError(id, {
12122
- code: RPC_ERROR_CODE5.RUNTIME_BUSY,
13831
+ code: RPC_ERROR_CODE7.RUNTIME_BUSY,
12123
13832
  message: `shell output is not retained yet for running task: ${parsed.taskId}`
12124
13833
  });
12125
13834
  return;
@@ -12156,7 +13865,7 @@ var createShellHandlers = ({
12156
13865
  const taskId = parseTaskId(params?.task_id);
12157
13866
  if (!taskId) {
12158
13867
  sendError(id, {
12159
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13868
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
12160
13869
  message: "task_id is required"
12161
13870
  });
12162
13871
  return;
@@ -12240,7 +13949,7 @@ var createShellHandlers = ({
12240
13949
  const taskId = parseTaskId(params?.task_id);
12241
13950
  if (!taskId) {
12242
13951
  sendError(id, {
12243
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13952
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
12244
13953
  message: "task_id is required"
12245
13954
  });
12246
13955
  return;
@@ -12250,7 +13959,7 @@ var createShellHandlers = ({
12250
13959
  const waits = activeShellWaits.get(taskId);
12251
13960
  if (!waits || waits.size === 0) {
12252
13961
  sendError(id, {
12253
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13962
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
12254
13963
  message: `no active shell.wait to detach for task: ${taskId}`
12255
13964
  });
12256
13965
  return;
@@ -12272,7 +13981,7 @@ var createShellHandlers = ({
12272
13981
  const taskId = parseTaskId(params?.task_id);
12273
13982
  if (!taskId) {
12274
13983
  sendError(id, {
12275
- code: RPC_ERROR_CODE5.INVALID_PARAMS,
13984
+ code: RPC_ERROR_CODE7.INVALID_PARAMS,
12276
13985
  message: "task_id is required"
12277
13986
  });
12278
13987
  return;
@@ -12300,16 +14009,16 @@ var createShellHandlers = ({
12300
14009
  };
12301
14010
 
12302
14011
  // src/rpc/skills.ts
12303
- import path15 from "path";
14012
+ import path18 from "path";
12304
14013
  import {
12305
- RPC_ERROR_CODE as RPC_ERROR_CODE6
14014
+ RPC_ERROR_CODE as RPC_ERROR_CODE8
12306
14015
  } from "@codelia/protocol";
12307
14016
  var createSkillsHandlers = ({
12308
14017
  state,
12309
14018
  log: log2
12310
14019
  }) => {
12311
14020
  const handleSkillsList = async (id, params) => {
12312
- const requestedCwd = params?.cwd ? path15.resolve(params.cwd) : void 0;
14021
+ const requestedCwd = params?.cwd ? path18.resolve(params.cwd) : void 0;
12313
14022
  const workingDir = requestedCwd ?? state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
12314
14023
  const forceReload = params?.force_reload ?? false;
12315
14024
  if (!forceReload) {
@@ -12333,7 +14042,7 @@ var createSkillsHandlers = ({
12333
14042
  });
12334
14043
  } catch (error) {
12335
14044
  sendError(id, {
12336
- code: RPC_ERROR_CODE6.RUNTIME_INTERNAL,
14045
+ code: RPC_ERROR_CODE8.RUNTIME_INTERNAL,
12337
14046
  message: `skills resolver init failed: ${String(error)}`
12338
14047
  });
12339
14048
  return;
@@ -12355,7 +14064,7 @@ var createSkillsHandlers = ({
12355
14064
  } catch (error) {
12356
14065
  log2(`skills.list error: ${String(error)}`);
12357
14066
  sendError(id, {
12358
- code: RPC_ERROR_CODE6.RUNTIME_INTERNAL,
14067
+ code: RPC_ERROR_CODE8.RUNTIME_INTERNAL,
12359
14068
  message: `skills list failed: ${String(error)}`
12360
14069
  });
12361
14070
  }
@@ -12364,15 +14073,15 @@ var createSkillsHandlers = ({
12364
14073
  };
12365
14074
 
12366
14075
  // src/rpc/task.ts
12367
- import path16 from "path";
14076
+ import path19 from "path";
12368
14077
  import {
12369
- RPC_ERROR_CODE as RPC_ERROR_CODE8
14078
+ RPC_ERROR_CODE as RPC_ERROR_CODE10
12370
14079
  } from "@codelia/protocol";
12371
14080
  import { ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl4 } from "@codelia/storage";
12372
14081
 
12373
14082
  // src/rpc/tool.ts
12374
14083
  import {
12375
- RPC_ERROR_CODE as RPC_ERROR_CODE7
14084
+ RPC_ERROR_CODE as RPC_ERROR_CODE9
12376
14085
  } from "@codelia/protocol";
12377
14086
  var normalizeToolResult = (result) => {
12378
14087
  switch (result.type) {
@@ -12409,7 +14118,7 @@ var createToolHandlers = ({
12409
14118
  const toolName = params?.name;
12410
14119
  if (!toolName) {
12411
14120
  sendError(id, {
12412
- code: RPC_ERROR_CODE7.INVALID_PARAMS,
14121
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12413
14122
  message: "tool name is required"
12414
14123
  });
12415
14124
  return;
@@ -12420,7 +14129,7 @@ var createToolHandlers = ({
12420
14129
  const tool = state.tools?.find((entry) => entry.name === toolName);
12421
14130
  if (!tool) {
12422
14131
  sendError(id, {
12423
- code: RPC_ERROR_CODE7.INVALID_PARAMS,
14132
+ code: RPC_ERROR_CODE9.INVALID_PARAMS,
12424
14133
  message: `unknown tool: ${toolName}`
12425
14134
  });
12426
14135
  return;
@@ -12437,7 +14146,7 @@ var createToolHandlers = ({
12437
14146
  sendResult(id, response);
12438
14147
  } catch (error) {
12439
14148
  sendError(id, {
12440
- code: RPC_ERROR_CODE7.RUNTIME_INTERNAL,
14149
+ code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
12441
14150
  message: `tool call failed: ${String(error)}`
12442
14151
  });
12443
14152
  }
@@ -12461,8 +14170,8 @@ var truncateCommandPreview2 = (value) => {
12461
14170
  };
12462
14171
  var toShellKeyBase2 = (label) => {
12463
14172
  const source = label?.trim() ?? "";
12464
- const slug = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
12465
- return slug || "shell";
14173
+ const slug2 = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
14174
+ return slug2 || "shell";
12466
14175
  };
12467
14176
  var compactTaskId2 = (taskId) => {
12468
14177
  const compact = taskId.toLowerCase().replaceAll(/[^a-z0-9]+/g, "");
@@ -12480,14 +14189,14 @@ var getPublicTaskKey = (task) => {
12480
14189
  return suffix ? `${toShellKeyBase2(task.label)}-${suffix}` : void 0;
12481
14190
  };
12482
14191
  var isWithin3 = (basePath, candidatePath) => {
12483
- const relative = path16.relative(basePath, candidatePath);
12484
- return relative === "" || !relative.startsWith("..") && !path16.isAbsolute(relative);
14192
+ const relative = path19.relative(basePath, candidatePath);
14193
+ return relative === "" || !relative.startsWith("..") && !path19.isAbsolute(relative);
12485
14194
  };
12486
14195
  var resolveShellCwd2 = (state, requestedCwd) => {
12487
14196
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
12488
14197
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
12489
14198
  if (!requestedCwd) return workingDir;
12490
- const resolved = path16.resolve(workingDir, requestedCwd);
14199
+ const resolved = path19.resolve(workingDir, requestedCwd);
12491
14200
  if (!isWithin3(rootDir, resolved)) {
12492
14201
  return null;
12493
14202
  }
@@ -12500,7 +14209,7 @@ var parseTaskId2 = (value) => {
12500
14209
  var toTaskRpcError2 = (error) => {
12501
14210
  if (!(error instanceof TaskManagerError)) {
12502
14211
  return {
12503
- code: RPC_ERROR_CODE8.RUNTIME_INTERNAL,
14212
+ code: RPC_ERROR_CODE10.RUNTIME_INTERNAL,
12504
14213
  message: String(error)
12505
14214
  };
12506
14215
  }
@@ -12509,17 +14218,17 @@ var toTaskRpcError2 = (error) => {
12509
14218
  case "invalid_task_id":
12510
14219
  case "unsupported_workspace_mode":
12511
14220
  return {
12512
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14221
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12513
14222
  message: error.message
12514
14223
  };
12515
14224
  case "manager_shutting_down":
12516
14225
  return {
12517
- code: RPC_ERROR_CODE8.RUNTIME_BUSY,
14226
+ code: RPC_ERROR_CODE10.RUNTIME_BUSY,
12518
14227
  message: error.message
12519
14228
  };
12520
14229
  default:
12521
14230
  return {
12522
- code: RPC_ERROR_CODE8.RUNTIME_INTERNAL,
14231
+ code: RPC_ERROR_CODE10.RUNTIME_INTERNAL,
12523
14232
  message: error.message
12524
14233
  };
12525
14234
  }
@@ -12570,7 +14279,7 @@ var resolveShellTimeoutSeconds3 = (requestedTimeout, background) => {
12570
14279
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
12571
14280
  return {
12572
14281
  error: {
12573
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14282
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12574
14283
  message: "timeout_seconds must be a positive number"
12575
14284
  }
12576
14285
  };
@@ -12584,7 +14293,7 @@ var resolveShellTimeoutSeconds3 = (requestedTimeout, background) => {
12584
14293
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
12585
14294
  return {
12586
14295
  error: {
12587
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14296
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12588
14297
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
12589
14298
  }
12590
14299
  };
@@ -12599,7 +14308,7 @@ var parseShellSpawnRequest = (state, params, options) => {
12599
14308
  if (!command) {
12600
14309
  return {
12601
14310
  error: {
12602
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14311
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12603
14312
  message: "command is required for shell tasks"
12604
14313
  }
12605
14314
  };
@@ -12615,7 +14324,7 @@ var parseShellSpawnRequest = (state, params, options) => {
12615
14324
  if (!cwd) {
12616
14325
  return {
12617
14326
  error: {
12618
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14327
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12619
14328
  message: "cwd is outside sandbox root"
12620
14329
  }
12621
14330
  };
@@ -12646,7 +14355,7 @@ var createTaskHandlers = ({
12646
14355
  const handleTaskSpawn = async (id, params) => {
12647
14356
  if (!params || !isTaskKind(params.kind)) {
12648
14357
  sendError(id, {
12649
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14358
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12650
14359
  message: "kind must be shell or subagent"
12651
14360
  });
12652
14361
  return;
@@ -12674,7 +14383,7 @@ var createTaskHandlers = ({
12674
14383
  }
12675
14384
  if (params.kind !== "shell") {
12676
14385
  sendError(id, {
12677
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14386
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12678
14387
  message: `task kind ${params.kind} is not supported yet.`
12679
14388
  });
12680
14389
  return;
@@ -12718,21 +14427,21 @@ var createTaskHandlers = ({
12718
14427
  const requestedLimit = params?.limit;
12719
14428
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
12720
14429
  sendError(id, {
12721
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14430
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12722
14431
  message: "limit must be a positive number"
12723
14432
  });
12724
14433
  return;
12725
14434
  }
12726
14435
  if (params?.kind !== void 0 && !isTaskKind(params.kind)) {
12727
14436
  sendError(id, {
12728
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14437
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12729
14438
  message: "kind must be shell or subagent"
12730
14439
  });
12731
14440
  return;
12732
14441
  }
12733
14442
  if (params?.state !== void 0 && !isTaskState(params.state)) {
12734
14443
  sendError(id, {
12735
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14444
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12736
14445
  message: "invalid task state"
12737
14446
  });
12738
14447
  return;
@@ -12752,7 +14461,7 @@ var createTaskHandlers = ({
12752
14461
  const taskId = parseTaskId2(params?.task_id);
12753
14462
  if (!taskId) {
12754
14463
  sendError(id, {
12755
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14464
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12756
14465
  message: "task_id is required"
12757
14466
  });
12758
14467
  return;
@@ -12776,7 +14485,7 @@ var createTaskHandlers = ({
12776
14485
  const taskId = parseTaskId2(params?.task_id);
12777
14486
  if (!taskId) {
12778
14487
  sendError(id, {
12779
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14488
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12780
14489
  message: "task_id is required"
12781
14490
  });
12782
14491
  return;
@@ -12794,7 +14503,7 @@ var createTaskHandlers = ({
12794
14503
  const taskId = parseTaskId2(params?.task_id);
12795
14504
  if (!taskId) {
12796
14505
  sendError(id, {
12797
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14506
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12798
14507
  message: "task_id is required"
12799
14508
  });
12800
14509
  return;
@@ -12814,7 +14523,7 @@ var createTaskHandlers = ({
12814
14523
  const taskId = parseTaskId2(params?.task_id);
12815
14524
  if (!taskId) {
12816
14525
  sendError(id, {
12817
- code: RPC_ERROR_CODE8.INVALID_PARAMS,
14526
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
12818
14527
  message: "task_id is required"
12819
14528
  });
12820
14529
  return;
@@ -12870,6 +14579,7 @@ var createRuntimeHandlers = ({
12870
14579
  subagents
12871
14580
  }) => {
12872
14581
  const environment = state.effectiveEnvironment;
14582
+ const imageHandlers = createImageHandlers(state);
12873
14583
  const sessionStateStore = injectedSessionStateStore ?? environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new SessionStateStoreImpl({
12874
14584
  onError: (error, context) => {
12875
14585
  log2(
@@ -12927,9 +14637,14 @@ var createRuntimeHandlers = ({
12927
14637
  if (authResolver.hasAnyAvailableAuth()) {
12928
14638
  return;
12929
14639
  }
14640
+ const onboardingConfig = await resolveEnvironmentModelConfig(
14641
+ state,
14642
+ state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0
14643
+ );
14644
+ const providers = configuredProviders(onboardingConfig.providers);
12930
14645
  const providerPick = await requestUiPick(state, {
12931
14646
  title: "Let's set up your provider to get started.",
12932
- items: SUPPORTED_PROVIDERS.map((provider2) => ({
14647
+ items: providers.map((provider2) => ({
12933
14648
  id: provider2,
12934
14649
  label: provider2,
12935
14650
  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 +14652,7 @@ var createRuntimeHandlers = ({
12937
14652
  multi: false
12938
14653
  });
12939
14654
  const pickedProvider = providerPick?.ids?.[0];
12940
- if (!pickedProvider || !SUPPORTED_PROVIDERS.includes(pickedProvider)) {
14655
+ if (!pickedProvider || !providers.includes(pickedProvider)) {
12941
14656
  log2("startup onboarding skipped (provider not selected)");
12942
14657
  return;
12943
14658
  }
@@ -13089,10 +14804,23 @@ var createRuntimeHandlers = ({
13089
14804
  const mcpEnabled = environment2.tools.mcp === "from-config";
13090
14805
  const skillsEnabled = environment2.context.skills === "from-config";
13091
14806
  const themeSetEnabled = isTuiLocalEnvironment(environment2) && environment2.config.source !== "disabled";
14807
+ let modelProviders = [...SUPPORTED_PROVIDERS];
14808
+ try {
14809
+ const config = await resolveEnvironmentModelConfig(
14810
+ state,
14811
+ state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0
14812
+ );
14813
+ modelProviders = configuredProviders(config.providers);
14814
+ } catch (error) {
14815
+ log2(`initialize provider config load failed: ${String(error)}`);
14816
+ }
13092
14817
  const result = {
14818
+ model_providers: modelProviders,
13093
14819
  protocol_version: PROTOCOL_VERSION,
13094
14820
  server: { name: SERVER_NAME, version: SERVER_VERSION },
13095
14821
  server_capabilities: {
14822
+ supports_model_ultrafast: true,
14823
+ supports_scoped_logout: environment2.auth.model === "runtime-default" || Boolean(environment2.adapters.credentialProvider?.clearProviderAuth),
13096
14824
  supports_run_cancel: true,
13097
14825
  supports_run_diagnostics: true,
13098
14826
  supports_shell_exec: processEnabled,
@@ -13107,6 +14835,7 @@ var createRuntimeHandlers = ({
13107
14835
  supports_context_inspect: true,
13108
14836
  supports_tool_call: true,
13109
14837
  supports_theme_set: themeSetEnabled,
14838
+ supports_image_generation: isTuiLocalEnvironment(environment2),
13110
14839
  supports_permission_preflight_events: true
13111
14840
  },
13112
14841
  ...resolvedTheme ? { tui: { theme: resolvedTheme } } : {}
@@ -13126,7 +14855,7 @@ var createRuntimeHandlers = ({
13126
14855
  const handleThemeSet = async (id, params) => {
13127
14856
  if (state.activeRunId) {
13128
14857
  sendError(id, {
13129
- code: RPC_ERROR_CODE9.RUNTIME_BUSY,
14858
+ code: RPC_ERROR_CODE11.RUNTIME_BUSY,
13130
14859
  message: "runtime busy"
13131
14860
  });
13132
14861
  return;
@@ -13134,14 +14863,14 @@ var createRuntimeHandlers = ({
13134
14863
  const name = params?.name?.trim().toLowerCase();
13135
14864
  if (!name) {
13136
14865
  sendError(id, {
13137
- code: RPC_ERROR_CODE9.INVALID_PARAMS,
14866
+ code: RPC_ERROR_CODE11.INVALID_PARAMS,
13138
14867
  message: "theme name is required"
13139
14868
  });
13140
14869
  return;
13141
14870
  }
13142
14871
  if (!SUPPORTED_TUI_THEMES.has(name)) {
13143
14872
  sendError(id, {
13144
- code: RPC_ERROR_CODE9.INVALID_PARAMS,
14873
+ code: RPC_ERROR_CODE11.INVALID_PARAMS,
13145
14874
  message: `unsupported theme: ${name}`
13146
14875
  });
13147
14876
  return;
@@ -13158,104 +14887,18 @@ var createRuntimeHandlers = ({
13158
14887
  log2(`theme.set ${name} scope=${target.scope} path=${target.path}`);
13159
14888
  } catch (error) {
13160
14889
  sendError(id, {
13161
- code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
14890
+ code: RPC_ERROR_CODE11.RUNTIME_INTERNAL,
13162
14891
  message: String(error)
13163
14892
  });
13164
14893
  }
13165
14894
  };
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
- };
14895
+ const handleAuthLogout = createAuthLogoutHandler({ state, log: log2 });
13253
14896
  const handleRequest = async (req) => {
13254
14897
  const mcpEnabled = state.effectiveEnvironment.tools.mcp === "from-config";
13255
14898
  const skillsEnabled = state.effectiveEnvironment.context.skills === "from-config";
13256
14899
  const themeSetEnabled = isTuiLocalEnvironment(state.effectiveEnvironment) && state.effectiveEnvironment.config.source !== "disabled";
13257
14900
  const rejectDisabled = (message) => sendError(req.id, {
13258
- code: RPC_ERROR_CODE9.INVALID_PARAMS,
14901
+ code: RPC_ERROR_CODE11.INVALID_PARAMS,
13259
14902
  message
13260
14903
  });
13261
14904
  switch (req.method) {
@@ -13273,6 +14916,12 @@ var createRuntimeHandlers = ({
13273
14916
  return handleAuthLogout(req.id, req.params);
13274
14917
  case "model.list":
13275
14918
  return handleModelList(req.id, req.params);
14919
+ case "image.model.get":
14920
+ return imageHandlers.handle(req.id, "get", req.params);
14921
+ case "image.model.configure":
14922
+ return imageHandlers.handle(req.id, "configure", req.params);
14923
+ case "image.artifact.get":
14924
+ return imageHandlers.handle(req.id, "artifact", req.params);
13276
14925
  case "model.set":
13277
14926
  return handleModelSet(req.id, req.params);
13278
14927
  case "tool.call":
@@ -13395,7 +15044,7 @@ var createRuntimeHandlers = ({
13395
15044
  return handleThemeSet(req.id, req.params);
13396
15045
  default:
13397
15046
  return sendError(req.id, {
13398
- code: RPC_ERROR_CODE9.METHOD_NOT_FOUND,
15047
+ code: RPC_ERROR_CODE11.METHOD_NOT_FOUND,
13399
15048
  message: "method not found"
13400
15049
  });
13401
15050
  }
@@ -13426,12 +15075,12 @@ var createRuntimeHandlers = ({
13426
15075
  // src/subagents/process-executor.ts
13427
15076
  import { spawn as spawn5 } from "child_process";
13428
15077
  import { existsSync } from "fs";
13429
- import path17 from "path";
15078
+ import path20 from "path";
13430
15079
  import { fileURLToPath } from "url";
13431
- var moduleDir = typeof __dirname === "string" ? __dirname : path17.dirname(fileURLToPath(import.meta.url));
13432
- var defaultEntry = path17.join(
15080
+ var moduleDir = typeof __dirname === "string" ? __dirname : path20.dirname(fileURLToPath(import.meta.url));
15081
+ var defaultEntry = path20.join(
13433
15082
  moduleDir,
13434
- existsSync(path17.join(moduleDir, "child-entry.ts")) ? "child-entry.ts" : "subagents/child-entry.js"
15083
+ existsSync(path20.join(moduleDir, "child-entry.ts")) ? "child-entry.ts" : "subagents/child-entry.js"
13435
15084
  );
13436
15085
  var createProcessSubagentFactory = (options = {}) => ({
13437
15086
  isAvailable: () => ["darwin", "linux"].includes(process.platform) && existsSync(options.entry ?? defaultEntry),