dsh-agy-link 0.6.53 → 0.6.55

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.
@@ -4,10 +4,10 @@ import { accessSync, closeSync, constants, copyFileSync, existsSync, mkdirSync,
4
4
  import path, { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { homedir } from "node:os";
7
- import { copyFile, mkdir, open, readdir, stat, unlink, writeFile } from "node:fs/promises";
7
+ import { copyFile, mkdir, open, readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
8
8
  import * as dshLlm from "@deepseek-ai/dsh-llm";
9
9
  import { LlmAdapter, LlmError } from "@deepseek-ai/dsh-llm";
10
- import { randomUUID } from "node:crypto";
10
+ import { createHash, randomUUID } from "node:crypto";
11
11
  import { execFile, execFileSync, spawn } from "node:child_process";
12
12
  import { promisify } from "node:util";
13
13
  import "@deepseek-ai/dsh-tools";
@@ -20,6 +20,8 @@ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
20
20
  //#region src/common/model-lineup.ts
21
21
  /** Gemini Flash — the cheap, always-available workhorse. */
22
22
  const PREFERRED_GEMINI_FLASH = "gemini-3.8-flash";
23
+ /** Gemini 4 Hydrogen — fast, balanced Gemini 4 workhorse (Pro & Ultra plans). */
24
+ const PREFERRED_GEMINI_HYDROGEN = "gemini-4-hydrogen";
23
25
  /** Anthropic tier (Sonnet — the default Anthropic pick). */
24
26
  const PREFERRED_CLAUDE = "claude-sonnet-5-5";
25
27
  /** Anthropic top tier; reached through the bare `claude-opus` alias. */
@@ -95,6 +97,13 @@ function defaultConfig() {
95
97
  agyBin: "",
96
98
  extraArgs: [],
97
99
  permissionMode: "skip",
100
+ sandbox: false,
101
+ agent: "",
102
+ agySettings: "",
103
+ transport: "cli",
104
+ imageTool: true,
105
+ syncAccountCustomizations: true,
106
+ mediaMaxFileBytes: 20971520,
98
107
  defaultModel: "",
99
108
  defaultEffort: "high",
100
109
  timeoutMs: 6e5,
@@ -176,7 +185,7 @@ function defaultConfig() {
176
185
  showTranslateAction: true,
177
186
  poolWideCatalog: false,
178
187
  imageModel: "",
179
- imageEffort: "low",
188
+ imageEffort: "medium",
180
189
  imageTimeoutMs: 24e4,
181
190
  imageMaxBytes: 20971520,
182
191
  imageOutputDir: "",
@@ -567,12 +576,18 @@ function asStringArray(v) {
567
576
  }
568
577
  const MODES$1 = [
569
578
  "skip",
579
+ "auto",
570
580
  "plan",
571
581
  "accept-edits"
572
582
  ];
573
583
  function asMode(v) {
574
584
  return typeof v === "string" && MODES$1.includes(v) ? v : void 0;
575
585
  }
586
+ function asTransport(v) {
587
+ if (typeof v !== "string") return void 0;
588
+ const s = v.trim().toLowerCase();
589
+ return s === "cli" || s === "acp" ? s : void 0;
590
+ }
576
591
  /** Layered config read; cheap enough to call per request (thunk pattern). */
577
592
  function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
578
593
  const base = defaultConfig();
@@ -586,6 +601,13 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
586
601
  agyBin: asString(get("agyBin")) ?? base.agyBin,
587
602
  extraArgs: Array.isArray(get("extraArgs")) ? get("extraArgs").filter((x) => typeof x === "string") : base.extraArgs,
588
603
  permissionMode: asMode(get("permissionMode")) ?? base.permissionMode,
604
+ sandbox: asBool(get("sandbox")) ?? base.sandbox,
605
+ agent: asString(get("agent")) ?? base.agent,
606
+ agySettings: asString(get("agySettings")) ?? base.agySettings,
607
+ transport: asTransport(get("transport")) ?? base.transport,
608
+ imageTool: asBool(get("imageTool")) ?? base.imageTool,
609
+ syncAccountCustomizations: asBool(get("syncAccountCustomizations")) ?? base.syncAccountCustomizations,
610
+ mediaMaxFileBytes: asNum(get("mediaMaxFileBytes")) ?? base.mediaMaxFileBytes,
589
611
  defaultModel: asString(get("defaultModel")) ?? base.defaultModel,
590
612
  defaultEffort: asString(get("defaultEffort")) ?? base.defaultEffort,
591
613
  timeoutMs: asNum(get("timeoutMs")) ?? base.timeoutMs,
@@ -658,6 +680,28 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
658
680
  const skip = asBool(env.DSH_AGY_SKIP_PERMISSIONS);
659
681
  if (skip !== void 0) cfg.permissionMode = skip ? "skip" : "plan";
660
682
  }
683
+ if (env.DSH_AGY_SANDBOX !== void 0) {
684
+ const sb = asBool(env.DSH_AGY_SANDBOX);
685
+ if (sb !== void 0) cfg.sandbox = sb;
686
+ }
687
+ if (env.DSH_AGY_AGENT !== void 0) cfg.agent = env.DSH_AGY_AGENT;
688
+ if (env.DSH_AGY_SETTINGS !== void 0) cfg.agySettings = env.DSH_AGY_SETTINGS;
689
+ if (env.DSH_AGY_TRANSPORT) {
690
+ const t = asTransport(env.DSH_AGY_TRANSPORT);
691
+ if (t) cfg.transport = t;
692
+ }
693
+ if (env.DSH_AGY_IMAGE_TOOL !== void 0) {
694
+ const it = asBool(env.DSH_AGY_IMAGE_TOOL);
695
+ if (it !== void 0) cfg.imageTool = it;
696
+ }
697
+ if (env.DSH_AGY_SYNC_CUSTOMIZATIONS !== void 0) {
698
+ const sc = asBool(env.DSH_AGY_SYNC_CUSTOMIZATIONS);
699
+ if (sc !== void 0) cfg.syncAccountCustomizations = sc;
700
+ }
701
+ if (env.DSH_AGY_MEDIA_MAX_FILE_BYTES) {
702
+ const v = asNum(env.DSH_AGY_MEDIA_MAX_FILE_BYTES);
703
+ if (v !== void 0 && v > 0) cfg.mediaMaxFileBytes = v;
704
+ }
661
705
  if (env.DSH_AGY_DEFAULT_MODEL) cfg.defaultModel = env.DSH_AGY_DEFAULT_MODEL;
662
706
  if (env.DSH_AGY_DEFAULT_EFFORT) cfg.defaultEffort = env.DSH_AGY_DEFAULT_EFFORT;
663
707
  if (env.DSH_AGY_TIMEOUT_MS) {
@@ -826,9 +870,10 @@ function normalizeImageName(value, now) {
826
870
  const ascii = raw.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/_+/g, "_").replace(/^[._-]+|[._-]+$/g, "").slice(0, 80);
827
871
  return ascii === "" ? fallback : ascii;
828
872
  }
829
- function resolveImageTarget(cfg, override) {
873
+ function resolveImageTarget(cfg, override, catalog) {
874
+ const autoModel = catalog?.source === "discovered" && catalog.models.some((m) => m.id === "gemini-4-hydrogen") ? PREFERRED_GEMINI_HYDROGEN : PREFERRED_GEMINI_FLASH;
830
875
  return {
831
- model: (override?.model ?? cfg.imageModel ?? "").trim() || (cfg.defaultModel ?? "").trim() || "gemini-3.8-flash",
876
+ model: (override?.model ?? cfg.imageModel ?? "").trim() || (cfg.defaultModel ?? "").trim() || autoModel,
832
877
  effort: (override?.effort ?? cfg.imageEffort ?? "").trim()
833
878
  };
834
879
  }
@@ -1146,7 +1191,7 @@ var ImageService = class {
1146
1191
  return this.deps.now?.() ?? Date.now();
1147
1192
  }
1148
1193
  target(override) {
1149
- return resolveImageTarget(this.deps.cfg(), override);
1194
+ return resolveImageTarget(this.deps.cfg(), override, this.deps.catalog?.());
1150
1195
  }
1151
1196
  cacheKey(req, target) {
1152
1197
  return JSON.stringify([
@@ -1451,6 +1496,138 @@ function formatBytes(n) {
1451
1496
  return (n / 1048576).toFixed(1) + " MB";
1452
1497
  }
1453
1498
  //#endregion
1499
+ //#region src/features/image/adapter-runner.ts
1500
+ function toolCallFrom(ev) {
1501
+ if (ev.kind !== "step" || ev.tool === void 0) return null;
1502
+ return {
1503
+ name: ev.tool.name,
1504
+ ...ev.tool.args === void 0 ? {} : { args: ev.tool.args },
1505
+ ...ev.tool.output === void 0 ? {} : { output: String(ev.tool.output) },
1506
+ ...ev.tool.error === void 0 ? {} : { error: ev.tool.error }
1507
+ };
1508
+ }
1509
+ function subagentsFrom(ev) {
1510
+ if (ev.kind !== "step") return [];
1511
+ const list = ev.raw?.subagent_info?.subagents;
1512
+ if (!Array.isArray(list)) return [];
1513
+ const out = [];
1514
+ for (const d of list) {
1515
+ const one = d;
1516
+ out.push({
1517
+ ...typeof one.conversation_id === "string" ? { conversationId: one.conversation_id } : {},
1518
+ ...typeof one.log_uri === "string" ? { logUri: one.log_uri } : {}
1519
+ });
1520
+ }
1521
+ return out;
1522
+ }
1523
+ /**
1524
+ * Drive one image generation attempt through the real adapter.
1525
+ */
1526
+ async function runViaAdapter(adapter, call) {
1527
+ const started = Date.now();
1528
+ const toolCalls = [];
1529
+ const subagents = [];
1530
+ const textParts = [];
1531
+ let responseText = "";
1532
+ let conversationId;
1533
+ let home;
1534
+ let accountId;
1535
+ let failure = null;
1536
+ let timedOut = false;
1537
+ const controller = new AbortController();
1538
+ const timer = setTimeout(() => {
1539
+ timedOut = true;
1540
+ controller.abort();
1541
+ }, call.timeoutMs);
1542
+ timer.unref?.();
1543
+ const signal = call.signal === void 0 ? controller.signal : AbortSignal.any([call.signal, controller.signal]);
1544
+ const options = {
1545
+ provider: PROVIDER_ID,
1546
+ model: call.model,
1547
+ ...call.effort === "" ? {} : { reasoningEffort: call.effort },
1548
+ messages: [{
1549
+ role: "user",
1550
+ content: [{
1551
+ type: "text",
1552
+ text: call.prompt
1553
+ }],
1554
+ source: { kind: "user" }
1555
+ }],
1556
+ maxTokens: 4096,
1557
+ purpose: "image",
1558
+ signal,
1559
+ agyImagePrompt: call.prompt,
1560
+ agyPermissionMode: call.permissionMode,
1561
+ agyOnAccount: (info) => {
1562
+ if (typeof info.id === "string") accountId = info.id;
1563
+ if (typeof info.home === "string" && info.home !== "") home = info.home;
1564
+ },
1565
+ agyOnEvent: (ev) => {
1566
+ if (ev.kind === "init" && ev.conversationId !== void 0) conversationId = ev.conversationId;
1567
+ if (ev.kind === "step") {
1568
+ if (ev.stepKind === "text" && ev.text !== "") textParts.push(ev.text);
1569
+ const tc = toolCallFrom(ev);
1570
+ if (tc !== null) toolCalls.push(tc);
1571
+ for (const s of subagentsFrom(ev)) subagents.push(s);
1572
+ }
1573
+ if (ev.kind === "result") {
1574
+ if (ev.conversationId !== "") conversationId = ev.conversationId;
1575
+ if (ev.response !== "") responseText = ev.response;
1576
+ const err = ev.raw?.result?.error;
1577
+ if (typeof err === "string" && err !== "") failure = { message: err };
1578
+ }
1579
+ }
1580
+ };
1581
+ try {
1582
+ for await (const chunk of adapter.stream(options)) {
1583
+ if (chunk.type === "text-delta" && typeof chunk.text === "string") textParts.push(chunk.text);
1584
+ if (chunk.type === "finish") {
1585
+ const reason = chunk.reason;
1586
+ if (reason?.kind === "error" || reason?.kind === "aborted") failure = {
1587
+ ...typeof reason.failure?.code === "string" ? { code: reason.failure.code } : {},
1588
+ ...typeof reason.failure?.message === "string" ? { message: reason.failure.message } : {}
1589
+ };
1590
+ }
1591
+ }
1592
+ } catch (e) {
1593
+ const err = e;
1594
+ const message = typeof err.message === "string" ? err.message : String(e);
1595
+ const code = typeof err.code === "string" ? err.code : /accounts are unavailable|no account/i.test(message) ? "RATE_LIMIT" : void 0;
1596
+ failure = {
1597
+ ...code === void 0 ? {} : { code },
1598
+ message
1599
+ };
1600
+ } finally {
1601
+ clearTimeout(timer);
1602
+ }
1603
+ const text = (textParts.join("\n").trim() || responseText).trim();
1604
+ if (failure !== null) {
1605
+ const code = timedOut ? "TIMEOUT" : failure.code ?? "AGY_ERROR";
1606
+ return {
1607
+ ok: false,
1608
+ text,
1609
+ toolCalls,
1610
+ subagents,
1611
+ ...conversationId === void 0 ? {} : { conversationId },
1612
+ ...home === void 0 ? {} : { home },
1613
+ ...accountId === void 0 ? {} : { accountId },
1614
+ code,
1615
+ error: timedOut ? "timed out after " + call.timeoutMs + "ms" : failure.message ?? "image generation failed",
1616
+ durationMs: Date.now() - started
1617
+ };
1618
+ }
1619
+ return {
1620
+ ok: true,
1621
+ text,
1622
+ toolCalls,
1623
+ subagents,
1624
+ ...conversationId === void 0 ? {} : { conversationId },
1625
+ ...home === void 0 ? {} : { home },
1626
+ ...accountId === void 0 ? {} : { accountId },
1627
+ durationMs: Date.now() - started
1628
+ };
1629
+ }
1630
+ //#endregion
1454
1631
  //#region src/common/pool-types.ts
1455
1632
  /** Check if a model identifier belongs to the Gemini 4 Argon family. */
1456
1633
  function isArgonModel(modelId) {
@@ -1711,7 +1888,7 @@ function resolveCallContext(input) {
1711
1888
  const isImage = purpose === "image";
1712
1889
  const isAux = isCompaction || isTitle || isReview || isTranslate || isImage;
1713
1890
  const imageMode = isImage ? options.agyPermissionMode : void 0;
1714
- const permissionMode = imageMode === "skip" || imageMode === "plan" || imageMode === "accept-edits" ? imageMode : isAux && !isTitle && !isImage ? "plan" : cfg.permissionMode;
1891
+ const permissionMode = imageMode === "skip" || imageMode === "auto" || imageMode === "plan" || imageMode === "accept-edits" ? imageMode : isAux && !isTitle && !isImage ? "plan" : cfg.permissionMode;
1715
1892
  const rawTranslate = isTranslate ? options.agyTranslateSession : void 0;
1716
1893
  const translateSession = rawTranslate === void 0 ? null : {
1717
1894
  setup: String(rawTranslate.setup ?? ""),
@@ -2865,12 +3042,107 @@ function startAgyProcess(opts) {
2865
3042
  }
2866
3043
  //#endregion
2867
3044
  //#region src/host/media.ts
2868
- const EXT = {
2869
- "image/png": "png",
2870
- "image/jpeg": "jpg",
2871
- "image/webp": "webp",
2872
- "image/gif": "gif"
3045
+ const MIME_ALIASES = {
3046
+ "image/jpg": "image/jpeg",
3047
+ "audio/wave": "audio/wav",
3048
+ "audio/x-wav": "audio/wav",
3049
+ "audio/x-m4a": "audio/mp4",
3050
+ "audio/m4a": "audio/mp4",
3051
+ "audio/mp3": "audio/mpeg"
2873
3052
  };
3053
+ const EXT_BY_MIME = {
3054
+ "image/png": {
3055
+ ext: "png",
3056
+ kind: "image"
3057
+ },
3058
+ "image/jpeg": {
3059
+ ext: "jpg",
3060
+ kind: "image"
3061
+ },
3062
+ "image/webp": {
3063
+ ext: "webp",
3064
+ kind: "image"
3065
+ },
3066
+ "image/gif": {
3067
+ ext: "gif",
3068
+ kind: "image"
3069
+ },
3070
+ "image/bmp": {
3071
+ ext: "bmp",
3072
+ kind: "image"
3073
+ },
3074
+ "image/avif": {
3075
+ ext: "avif",
3076
+ kind: "image"
3077
+ },
3078
+ "application/pdf": {
3079
+ ext: "pdf",
3080
+ kind: "pdf"
3081
+ },
3082
+ "audio/mpeg": {
3083
+ ext: "mp3",
3084
+ kind: "audio"
3085
+ },
3086
+ "audio/wav": {
3087
+ ext: "wav",
3088
+ kind: "audio"
3089
+ },
3090
+ "audio/mp4": {
3091
+ ext: "m4a",
3092
+ kind: "audio"
3093
+ },
3094
+ "audio/aac": {
3095
+ ext: "aac",
3096
+ kind: "audio"
3097
+ },
3098
+ "audio/flac": {
3099
+ ext: "flac",
3100
+ kind: "audio"
3101
+ },
3102
+ "audio/opus": {
3103
+ ext: "opus",
3104
+ kind: "audio"
3105
+ },
3106
+ "audio/ogg": {
3107
+ ext: "ogg",
3108
+ kind: "audio"
3109
+ },
3110
+ "audio/webm": {
3111
+ ext: "webm",
3112
+ kind: "audio"
3113
+ },
3114
+ "video/mp4": {
3115
+ ext: "mp4",
3116
+ kind: "video"
3117
+ },
3118
+ "video/webm": {
3119
+ ext: "webm",
3120
+ kind: "video"
3121
+ },
3122
+ "video/quicktime": {
3123
+ ext: "mov",
3124
+ kind: "video"
3125
+ },
3126
+ "video/x-matroska": {
3127
+ ext: "mkv",
3128
+ kind: "video"
3129
+ },
3130
+ "video/ogg": {
3131
+ ext: "ogv",
3132
+ kind: "video"
3133
+ }
3134
+ };
3135
+ /** Normalize parameterized MIME types (e.g. `audio/webm; codecs=opus`) and aliases. */
3136
+ function normalizeMediaType(raw) {
3137
+ const base = raw.split(";")[0]?.trim().toLowerCase() ?? "";
3138
+ return MIME_ALIASES[base] ?? base;
3139
+ }
3140
+ function mediaKindFor(mediaType) {
3141
+ return EXT_BY_MIME[normalizeMediaType(mediaType)]?.kind ?? null;
3142
+ }
3143
+ function mediaExtFor(mediaType) {
3144
+ return EXT_BY_MIME[normalizeMediaType(mediaType)]?.ext ?? "bin";
3145
+ }
2874
3146
  /**
2875
3147
  * Sanitize an attachment id into a stable filename fragment. Ids whose
2876
3148
  * sanitized form collides (e.g. "a/b" vs "a_b") get a short raw-id hash
@@ -2890,60 +3162,88 @@ function idFragment(attachmentId) {
2890
3162
  * legitimately re-references it overwrites instead of accumulating copies.
2891
3163
  */
2892
3164
  function stagedPath(dir, key, attachmentId, mediaType) {
2893
- const ext = EXT[mediaType] ?? "png";
3165
+ const ext = mediaExtFor(mediaType);
2894
3166
  return join(dir, key + "-" + idFragment(attachmentId) + "." + ext);
2895
3167
  }
3168
+ async function resolveMediaBytes(ref, readMedia) {
3169
+ if (ref.data instanceof Uint8Array) return ref.data;
3170
+ if (typeof ref.data === "string" && ref.data !== "") try {
3171
+ return Buffer.from(ref.data.replace(/^data:[^;]+;base64,/, ""), "base64");
3172
+ } catch {
3173
+ return null;
3174
+ }
3175
+ if (readMedia) try {
3176
+ const data = await readMedia(ref);
3177
+ if (data) return data;
3178
+ } catch {}
3179
+ if (typeof ref.path === "string" && ref.path !== "") try {
3180
+ return await readFile(ref.path);
3181
+ } catch {
3182
+ return null;
3183
+ }
3184
+ return null;
3185
+ }
2896
3186
  /**
2897
- * Stage up to `maxImages` images into `dir`, returning prompt lines that
2898
- * reference them by absolute path. Deterministic names mean a retried or
2899
- * replayed turn overwrites the same file instead of accumulating copies.
3187
+ * Stage up to `maxItems` (or `maxImages`) attachments (images, PDF, audio,
3188
+ * video) into `dir`, returning prompt lines that reference them by absolute path.
2900
3189
  */
2901
- async function stageImages(opts) {
3190
+ async function stageMedia(opts) {
2902
3191
  const staged = [];
2903
3192
  const stagedIds = [];
2904
3193
  const lines = [];
2905
3194
  let skipped = 0;
2906
- const budget = Math.max(0, opts.maxImages);
2907
- if (budget > 0 && opts.images.length > 0) {
3195
+ const budget = Math.max(0, opts.maxItems ?? 8);
3196
+ if (budget > 0 && opts.items.length > 0) {
2908
3197
  await mkdir(opts.dir, { recursive: true });
2909
- let i = 0;
2910
- for (const ref of opts.images) {
3198
+ for (const ref of opts.items) {
2911
3199
  if (staged.length >= budget) {
2912
- skipped += opts.images.length - staged.length - skipped;
3200
+ skipped += opts.items.length - staged.length - skipped;
2913
3201
  break;
2914
3202
  }
3203
+ const normType = normalizeMediaType(ref.mediaType);
3204
+ const kind = mediaKindFor(normType);
2915
3205
  const label = ref.name ?? ref.attachmentId;
2916
- if (ref.bytes > opts.maxBytes) {
3206
+ if (kind === null) {
2917
3207
  skipped++;
2918
- lines.push("[image skipped: \"" + label + "\" exceeds mediaMaxBytes]");
2919
- i++;
3208
+ lines.push("[attachment skipped: \"" + label + "\" unsupported type " + ref.mediaType + "]");
2920
3209
  continue;
2921
3210
  }
2922
- let data = null;
2923
- try {
2924
- data = await opts.readImage(ref);
2925
- } catch {
2926
- data = null;
3211
+ const cap = kind === "image" ? opts.maxImageBytes : opts.maxFileBytes;
3212
+ const capLabel = kind === "image" ? "mediaMaxBytes" : "mediaMaxFileBytes";
3213
+ if (typeof ref.bytes === "number" && ref.bytes > cap) {
3214
+ skipped++;
3215
+ lines.push("[" + kind + " skipped: \"" + label + "\" exceeds " + capLabel + "]");
3216
+ continue;
2927
3217
  }
3218
+ const data = await resolveMediaBytes(ref, opts.readMedia);
2928
3219
  if (!data) {
2929
3220
  skipped++;
2930
- lines.push("[image unavailable: \"" + label + "\" could not be read from attachment storage]");
2931
- i++;
3221
+ lines.push("[" + kind + " unavailable: \"" + label + "\" could not be read from attachment storage]");
2932
3222
  continue;
2933
3223
  }
2934
- const path = stagedPath(opts.dir, opts.key, ref.attachmentId, ref.mediaType);
3224
+ if (data.byteLength > cap) {
3225
+ skipped++;
3226
+ lines.push("[" + kind + " skipped: \"" + label + "\" exceeds " + capLabel + "]");
3227
+ continue;
3228
+ }
3229
+ const path = stagedPath(opts.dir, opts.key, ref.attachmentId, normType);
2935
3230
  await writeFile(path, data);
3231
+ const w = ref.width ?? 0;
3232
+ const h = ref.height ?? 0;
3233
+ const bytes = ref.bytes ?? data.byteLength;
2936
3234
  staged.push({
2937
3235
  path,
2938
3236
  name: label,
2939
- width: ref.width,
2940
- height: ref.height,
2941
- bytes: ref.bytes,
2942
- attachmentId: ref.attachmentId
3237
+ width: w,
3238
+ height: h,
3239
+ bytes,
3240
+ attachmentId: ref.attachmentId,
3241
+ kind,
3242
+ mediaType: normType
2943
3243
  });
2944
3244
  stagedIds.push(ref.attachmentId);
2945
- lines.push("[image attached: \"" + label + "\" — staged at " + path + " (" + ref.width + "x" + ref.height + ", " + ref.bytes + " bytes). Inspect it using the view_file tool with AbsolutePath: \"" + path + "\"]");
2946
- i++;
3245
+ if (kind === "image") lines.push("[image attached: \"" + label + "\" — staged at " + path + " (" + w + "x" + h + ", " + bytes + " bytes). Inspect it using the view_file tool with AbsolutePath: \"" + path + "\"]");
3246
+ else lines.push("[" + kind + " attached: \"" + label + "\" (" + normType + ", " + bytes + " bytes) — staged at " + path + ". Inspect it using read_file with Path: \"" + path + "\"]");
2947
3247
  }
2948
3248
  }
2949
3249
  return {
@@ -3098,16 +3398,46 @@ function latestUserMessageAny(messages) {
3098
3398
  }
3099
3399
  return "";
3100
3400
  }
3101
- /** Collect image refs from a message, walking nested tool-result payloads. */
3102
- function collectImageRefs(m, out) {
3401
+ const MULTIMODAL_BLOCK_TYPES = /* @__PURE__ */ new Set([
3402
+ "image",
3403
+ "file",
3404
+ "document",
3405
+ "pdf",
3406
+ "audio",
3407
+ "video",
3408
+ "attachment"
3409
+ ]);
3410
+ function mediaRefFromBlock(b) {
3411
+ const src = (b.attachment && typeof b.attachment === "object" ? b.attachment : null) ?? b;
3412
+ const rawType = typeof src.mediaType === "string" ? src.mediaType : typeof src.mimeType === "string" ? src.mimeType : "";
3413
+ const fallbackType = b.type === "pdf" ? "application/pdf" : "";
3414
+ const mediaType = rawType || fallbackType;
3415
+ if (mediaType === "" || mediaKindFor(mediaType) === null) return null;
3416
+ const rawPath = typeof src.path === "string" ? src.path : void 0;
3417
+ const rawName = typeof src.name === "string" ? src.name : void 0;
3418
+ const id = typeof src.attachmentId === "string" && src.attachmentId !== "" ? src.attachmentId : rawPath ?? (rawName ? `${rawName}:${mediaType}` : "");
3419
+ if (id === "") return null;
3420
+ return {
3421
+ attachmentId: id,
3422
+ mediaType,
3423
+ ...typeof src.bytes === "number" ? { bytes: src.bytes } : {},
3424
+ ...typeof src.width === "number" ? { width: src.width } : {},
3425
+ ...typeof src.height === "number" ? { height: src.height } : {},
3426
+ ...rawName !== void 0 ? { name: rawName } : {},
3427
+ ...rawPath !== void 0 ? { path: rawPath } : {},
3428
+ ...src.data instanceof Uint8Array || typeof src.data === "string" ? { data: src.data } : {}
3429
+ };
3430
+ }
3431
+ function collectMediaRefs(m, out) {
3103
3432
  const walk = (blocks) => {
3104
3433
  for (const raw of blocks ?? []) {
3105
3434
  const b = raw;
3106
3435
  if (b === void 0) continue;
3107
- if (b.type === "image") {
3108
- if (b.attachment && typeof b.attachment === "object") out.push(b.attachment);
3109
- else if (typeof b.attachmentId === "string") out.push(b);
3110
- } else if (b.type === "tool-result" && Array.isArray(b.content)) walk(b.content);
3436
+ if (b.type === "tool-result" && Array.isArray(b.content)) walk(b.content);
3437
+ else if (typeof b.type === "string" && MULTIMODAL_BLOCK_TYPES.has(b.type)) {
3438
+ const ref = mediaRefFromBlock(b);
3439
+ if (ref !== null) out.push(ref);
3440
+ }
3111
3441
  }
3112
3442
  };
3113
3443
  walk(m.content);
@@ -3116,20 +3446,13 @@ function digestLabel(m) {
3116
3446
  if (isToolResultMessage(m)) return "Tool result: ";
3117
3447
  return m.role === "user" ? "User: " : "Assistant: ";
3118
3448
  }
3119
- /**
3120
- * Images this hop should forward, minus what the current agy conversation
3121
- * has already received. Trailing-span attachments come first (this hop's
3122
- * screenshots), then any user-turn attachments since `fromIdx` that carry
3123
- * unseen ids (tool-hop continuations and foreign-model turns used to fall
3124
- * into a "re-send every historical screenshot" path).
3125
- */
3126
- function collectUnsentImageRefs(messages, trailingUser, fromIdx, sentIds) {
3449
+ function collectUnsentMediaRefs(messages, trailingUser, fromIdx, sentIds) {
3127
3450
  const sent = new Set(sentIds);
3128
3451
  const seen = /* @__PURE__ */ new Set();
3129
3452
  const out = [];
3130
3453
  const push = (m) => {
3131
3454
  const refs = [];
3132
- collectImageRefs(m, refs);
3455
+ collectMediaRefs(m, refs);
3133
3456
  for (const r of refs) {
3134
3457
  const id = r.attachmentId;
3135
3458
  if (typeof id !== "string" || id === "" || sent.has(id) || seen.has(id)) continue;
@@ -3816,6 +4139,61 @@ function rewriteImageMarkdown(text, mediaBaseUrl) {
3816
4139
  return `![${alt}](${`${mediaBaseUrl}?path=${encodeURIComponent(cleanTarget)}`})`;
3817
4140
  });
3818
4141
  }
4142
+ /** Rewrite `<agent-embed src="...">` tags into embed widget links that the DSH client upgrades to sandboxed iframes. */
4143
+ function rewriteAgentEmbeds(text, embedBaseUrl) {
4144
+ if (!text || !/<agent-embed\b/i.test(text)) return text;
4145
+ const base = embedBaseUrl || "/plugins/agy-link/embed";
4146
+ return text.replace(/<agent-embed\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>(?:\s*<\/agent-embed>)?/gi, (_match, rawSrc) => {
4147
+ const cleanSrc = rawSrc.trim();
4148
+ if (cleanSrc === "") return "";
4149
+ return `\n\n[Widget: ${cleanSrc.replace(/^file:\/+/i, "").split(/[/\\?#]/).filter(Boolean).pop() || "widget.html"}](${`${base}?path=${encodeURIComponent(cleanSrc)}&agy_embed=1`})\n\n`;
4150
+ });
4151
+ }
4152
+ /**
4153
+ * Split a streaming text chunk so an incomplete `<agent-embed ...>` tag
4154
+ * straddling chunk boundaries is held back in `pending` until completed or
4155
+ * flushed at block end.
4156
+ */
4157
+ function splitPendingEmbedFragment(text) {
4158
+ const lastLt = text.lastIndexOf("<");
4159
+ if (lastLt < 0) return {
4160
+ ready: text,
4161
+ pending: ""
4162
+ };
4163
+ const tail = text.slice(lastLt);
4164
+ const lower = tail.toLowerCase();
4165
+ const openTag = "<agent-embed";
4166
+ if (lower.length < 12) {
4167
+ if (openTag.startsWith(lower)) return {
4168
+ ready: text.slice(0, lastLt),
4169
+ pending: tail
4170
+ };
4171
+ return {
4172
+ ready: text,
4173
+ pending: ""
4174
+ };
4175
+ }
4176
+ if (/^<agent-embed(?=[\s>\/]|$)/i.test(tail)) {
4177
+ const gt = tail.indexOf(">");
4178
+ if (gt < 0) return {
4179
+ ready: text.slice(0, lastLt),
4180
+ pending: tail
4181
+ };
4182
+ if (tail[gt - 1] === "/") return {
4183
+ ready: text,
4184
+ pending: ""
4185
+ };
4186
+ const afterGt = tail.slice(gt + 1);
4187
+ if (!/<\/agent-embed>/i.test(afterGt) && "</agent-embed>".startsWith(afterGt.trim().toLowerCase())) return {
4188
+ ready: text.slice(0, lastLt),
4189
+ pending: tail
4190
+ };
4191
+ }
4192
+ return {
4193
+ ready: text,
4194
+ pending: ""
4195
+ };
4196
+ }
3819
4197
  /** Normalize Markdown file links: strip file:/// prefix so DSH's native markdown compiler treats them as local files and opens them in the native right sidebar. */
3820
4198
  function normalizeFileLinks(text) {
3821
4199
  if (!text) return text;
@@ -3943,6 +4321,7 @@ var EventMapper = class {
3943
4321
  sawTextStep;
3944
4322
  finished = false;
3945
4323
  totalTextOutput = "";
4324
+ pendingEmbedFrag = "";
3946
4325
  toolCallStates = /* @__PURE__ */ new Map();
3947
4326
  emittedCompactionNotice = false;
3948
4327
  constructor(opts) {
@@ -3953,8 +4332,21 @@ var EventMapper = class {
3953
4332
  get isFinished() {
3954
4333
  return this.finished;
3955
4334
  }
4335
+ formatAssistantText(text) {
4336
+ const withEmbeds = rewriteAgentEmbeds(text, this.opts.mediaBaseUrl ? this.opts.mediaBaseUrl.replace(/\/media\/?$/, "/embed") : void 0);
4337
+ return normalizeFileLinks(this.opts.mediaBaseUrl ? rewriteImageMarkdown(withEmbeds, this.opts.mediaBaseUrl) : withEmbeds);
4338
+ }
4339
+ *flushPendingEmbed() {
4340
+ if (this.pendingEmbedFrag === "") return;
4341
+ const raw = this.pendingEmbedFrag;
4342
+ this.pendingEmbedFrag = "";
4343
+ yield* this.ensureBlock("text");
4344
+ const d = this.appendDelta(this.formatAssistantText(raw));
4345
+ if (d) yield d;
4346
+ }
3956
4347
  *ensureBlock(type) {
3957
4348
  if (this.openType === type) return;
4349
+ if (this.openType === "text" && type !== "text") yield* this.flushPendingEmbed();
3958
4350
  const close = this.closeOpen();
3959
4351
  if (close) yield close;
3960
4352
  this.openType = type;
@@ -4088,13 +4480,18 @@ var EventMapper = class {
4088
4480
  }
4089
4481
  this.sawTextStep = true;
4090
4482
  yield* this.ensureBlock("text");
4091
- let d;
4092
- const processedText = normalizeFileLinks(this.opts.mediaBaseUrl ? rewriteImageMarkdown(ev.text, this.opts.mediaBaseUrl) : ev.text);
4483
+ let d = null;
4093
4484
  if (ev.fragment === true) {
4094
- const acc = (this.emittedByKey.get(ev.stepKey) ?? "") + processedText;
4095
- this.emittedByKey.set(ev.stepKey, acc);
4096
- d = this.appendDelta(processedText);
4485
+ const { ready, pending } = splitPendingEmbedFragment(this.pendingEmbedFrag + ev.text);
4486
+ this.pendingEmbedFrag = pending;
4487
+ if (ready !== "") {
4488
+ const processedText = this.formatAssistantText(ready);
4489
+ const acc = (this.emittedByKey.get(ev.stepKey) ?? "") + processedText;
4490
+ this.emittedByKey.set(ev.stepKey, acc);
4491
+ d = this.appendDelta(processedText);
4492
+ }
4097
4493
  } else {
4494
+ const processedText = this.formatAssistantText(ev.text);
4098
4495
  const delta = suffixDelta(this.emittedByKey.get(ev.stepKey) ?? "", processedText);
4099
4496
  this.emittedByKey.set(ev.stepKey, processedText);
4100
4497
  d = this.appendDelta(delta);
@@ -4148,6 +4545,7 @@ var EventMapper = class {
4148
4545
  this.announcedTools.add(ev.stepKey);
4149
4546
  if (!this.opts.cutOnTool) return;
4150
4547
  yield* this.flushBannerOnlyThoughts();
4548
+ yield* this.flushPendingEmbed();
4151
4549
  const close = this.closeOpen();
4152
4550
  if (close) yield close;
4153
4551
  const block = buildToolCallBlock({
@@ -4170,7 +4568,7 @@ var EventMapper = class {
4170
4568
  }
4171
4569
  if (!ev.ok) {
4172
4570
  if (ev.response === "") return;
4173
- const respText = normalizeFileLinks(ev.response);
4571
+ const respText = this.formatAssistantText(ev.response);
4174
4572
  if (!this.sawTextStep) {
4175
4573
  yield* this.ensureBlock("text");
4176
4574
  const d = this.appendDelta(respText);
@@ -4183,10 +4581,11 @@ var EventMapper = class {
4183
4581
  }
4184
4582
  } else if (!this.sawTextStep && ev.response !== "") {
4185
4583
  yield* this.ensureBlock("text");
4186
- const d = this.appendDelta(normalizeFileLinks(ev.response));
4584
+ const d = this.appendDelta(this.formatAssistantText(ev.response));
4187
4585
  if (d) yield d;
4188
4586
  }
4189
4587
  yield* this.flushBannerOnlyThoughts();
4588
+ yield* this.flushPendingEmbed();
4190
4589
  const close = this.closeOpen();
4191
4590
  if (close) yield close;
4192
4591
  yield {
@@ -4232,6 +4631,7 @@ var EventMapper = class {
4232
4631
  */
4233
4632
  *emitFailure(kind, code, message, retryAfterMs) {
4234
4633
  if (this.finished) return;
4634
+ yield* this.flushPendingEmbed();
4235
4635
  const close = this.closeOpen();
4236
4636
  if (close) yield close;
4237
4637
  const tracked = this.opts.usage?.finalUsage({});
@@ -5366,10 +5766,10 @@ function writeFileAtomicSync(file, data, mode = 384) {
5366
5766
  const tmp = atomicTmpPath(file);
5367
5767
  try {
5368
5768
  mkdirSync(dirname(file), { recursive: true });
5369
- writeFileSync(tmp, data, {
5769
+ writeFileSync(tmp, data, typeof data === "string" ? {
5370
5770
  encoding: "utf8",
5371
5771
  mode
5372
- });
5772
+ } : { mode });
5373
5773
  renameSync(tmp, file);
5374
5774
  } catch (err) {
5375
5775
  try {
@@ -5988,7 +6388,7 @@ var ModelCatalog = class ModelCatalog {
5988
6388
  //#endregion
5989
6389
  //#region src/domain/models/quota-catalog.ts
5990
6390
  /** Families whose quota rows describe models the picker may offer. */
5991
- const QUOTA_FAMILIES = [
6391
+ const QUOTA_FAMILIES$1 = [
5992
6392
  "google",
5993
6393
  "argon",
5994
6394
  "anthropic",
@@ -6006,7 +6406,7 @@ function quotaModelsForAccount(account) {
6006
6406
  if (!quotas) return [];
6007
6407
  const out = [];
6008
6408
  const seen = /* @__PURE__ */ new Set();
6009
- for (const family of QUOTA_FAMILIES) {
6409
+ for (const family of QUOTA_FAMILIES$1) {
6010
6410
  const rows = quotas[family]?.models;
6011
6411
  if (!Array.isArray(rows)) continue;
6012
6412
  for (const row of rows) {
@@ -6636,22 +7036,28 @@ function mergeSentImageIds(existing, added, max = 64) {
6636
7036
  //#region src/provider/account-selection.ts
6637
7037
  /** Upper bound on the self-heal refresh so a slow network cannot stall a turn. */
6638
7038
  const MODEL_HEAL_TIMEOUT_MS = 2e4;
6639
- /** Session affinity: reuse the account this session last ran on, if eligible and not superseded by a manual switch. */
7039
+ /** Session affinity: reuse the account this session last ran for THIS family, if eligible and not superseded by a manual switch. */
6640
7040
  function stickyAccount(deps, family, sessionKey, model) {
6641
7041
  const pool = deps.pool;
6642
7042
  if (pool === void 0 || sessionKey === "") return void 0;
6643
- const manualPinAt = pool.getPoolData().manualPinAt ?? 0;
7043
+ const poolData = pool.getPoolData();
7044
+ const familyPinAt = Math.max(poolData.manualPinAt ?? 0, poolData.manualPinAtByFamily?.[family] ?? 0);
6644
7045
  const prefix = `${sessionKey}:`;
6645
7046
  let mostRecent;
6646
7047
  let latestUpdated = -1;
6647
7048
  for (const [k, b] of Object.entries(deps.store.all())) {
6648
- if (!k.startsWith(prefix) || b.updatedAt <= latestUpdated) continue;
6649
- if (manualPinAt > 0 && b.updatedAt < manualPinAt) continue;
7049
+ if (!k.startsWith(prefix)) continue;
6650
7050
  const boundAcc = pool.getAccount(k.slice(prefix.length));
6651
- if (boundAcc !== void 0) {
7051
+ if (boundAcc === void 0) {
7052
+ deps.store.delete(k);
7053
+ continue;
7054
+ }
7055
+ if (b.model && b.model.trim() !== "" && modelFamilyOf(b.model) !== family) continue;
7056
+ if (familyPinAt > 0 && b.updatedAt < familyPinAt) continue;
7057
+ if (b.updatedAt > latestUpdated) {
6652
7058
  mostRecent = boundAcc;
6653
7059
  latestUpdated = b.updatedAt;
6654
- } else deps.store.delete(k);
7060
+ }
6655
7061
  }
6656
7062
  return mostRecent !== void 0 && (typeof pool.isAccountEligibleForModel === "function" ? pool.isAccountEligibleForModel(mostRecent, family, model) : pool.isAccountEligible(mostRecent, family)) ? mostRecent : void 0;
6657
7063
  }
@@ -6747,7 +7153,7 @@ async function selectSessionAccount(input) {
6747
7153
  if (pool !== void 0 && !isAux && sessionKey !== "" && process.platform === "win32" && cfg.parallelSameAccount) account = pool.selectAccount(family, activeModel) ?? void 0;
6748
7154
  if (account === void 0 && pool !== void 0 && !isAux && sessionKey !== "") account = stickyAccount(deps, family, sessionKey, activeModel);
6749
7155
  if (account === void 0 && pool !== void 0) account = pool.selectAccount(family, activeModel) ?? void 0;
6750
- if (account !== void 0 && pool !== void 0 && pool.getPoolData().lastActiveAccountId !== account.id) {
7156
+ if (account !== void 0 && pool !== void 0 && (family === "google" || !pool.getPoolData().lastActiveAccountId) && pool.getPoolData().lastActiveAccountId !== account.id) {
6751
7157
  if (typeof pool.markAccountActive === "function") pool.markAccountActive(account.id);
6752
7158
  else pool.setActiveAccount(account.id, family);
6753
7159
  }
@@ -6862,7 +7268,7 @@ async function buildPromptPlan(input) {
6862
7268
  deps
6863
7269
  });
6864
7270
  prompt = staged.prompt;
6865
- if (staged.stagedDir !== null) stagedDirs = [staged.stagedDir];
7271
+ if (staged.stagedDir !== null && !stagedDirs.includes(staged.stagedDir)) stagedDirs.push(staged.stagedDir);
6866
7272
  newlySentImageIds.push(...staged.stagedIds);
6867
7273
  if (prompt.trim() === "") throw new LlmError("request carries no user text or images to forward to agy", Err.AGY_ERROR);
6868
7274
  } else if (prompt.trim() === "") throw new LlmError("request carries no user text to forward to agy", Err.AGY_ERROR);
@@ -7076,23 +7482,32 @@ async function stagePromptImages(input) {
7076
7482
  const { cfg, ctx, messages, trailingUser, binding, deps } = input;
7077
7483
  let prompt = input.prompt;
7078
7484
  const sentIds = binding?.sentImageIds ?? [];
7079
- const imageRefs = collectUnsentImageRefs(messages, trailingUser, binding !== void 0 ? binding.lastMessageCount : 0, sentIds);
7485
+ const mediaRefs = collectUnsentMediaRefs(messages, trailingUser, binding !== void 0 ? binding.lastMessageCount : 0, sentIds);
7080
7486
  const readImage = deps.readImage;
7081
- if (imageRefs.length === 0 || !readImage) return {
7487
+ if (mediaRefs.length === 0) return {
7488
+ prompt,
7489
+ stagedDir: null,
7490
+ stagedIds: []
7491
+ };
7492
+ if (!readImage && mediaRefs.every((r) => r.data === void 0 && r.path === void 0)) return {
7082
7493
  prompt,
7083
7494
  stagedDir: null,
7084
7495
  stagedIds: []
7085
7496
  };
7086
7497
  const dir = cfg.mediaDir !== "" ? cfg.mediaDir : defaultMediaDir(stateDir());
7087
- const res = await stageImages({
7498
+ const res = await stageMedia({
7088
7499
  dir,
7089
7500
  key: ctx.sessionKey !== "" ? ctx.sessionKey.replace(/[^a-zA-Z0-9_-]+/g, "_") : "anon",
7090
- images: imageRefs,
7091
- readImage,
7092
- maxImages: cfg.mediaMaxImages,
7093
- maxBytes: cfg.mediaMaxBytes
7501
+ items: mediaRefs,
7502
+ ...readImage ? { readMedia: (ref) => readImage(ref) } : {},
7503
+ maxItems: cfg.mediaMaxImages,
7504
+ maxImageBytes: cfg.mediaMaxBytes,
7505
+ maxFileBytes: cfg.mediaMaxFileBytes
7094
7506
  });
7095
- if (res.promptSuffix !== "") prompt = prompt === "" ? res.promptSuffix + "\n\n[Please inspect the attached image(s) using view_file and assist the user.]" : prompt + "\n\n" + res.promptSuffix;
7507
+ if (res.promptSuffix !== "") {
7508
+ const onlyAttachmentsHint = res.staged.some((s) => s.kind !== void 0 && s.kind !== "image") ? "[Please inspect the attached file(s) using view_file / read_file and assist the user.]" : "[Please inspect the attached image(s) using view_file and assist the user.]";
7509
+ prompt = prompt === "" ? res.promptSuffix + "\n\n" + onlyAttachmentsHint : prompt + "\n\n" + res.promptSuffix;
7510
+ }
7096
7511
  return {
7097
7512
  prompt,
7098
7513
  stagedDir: res.staged.length > 0 ? dir : null,
@@ -7853,6 +8268,23 @@ function defaultPoolDir(home) {
7853
8268
  /** Proactive rotation thresholds: bench accounts at or below these remaining fractions until reset. */
7854
8269
  const LOW_QUOTA_5H = .1;
7855
8270
  const LOW_QUOTA_WEEKLY = .05;
8271
+ /** Ordered quota families tracked on an account card. */
8272
+ const QUOTA_FAMILIES = [
8273
+ "google",
8274
+ "argon",
8275
+ "anthropic",
8276
+ "openai"
8277
+ ];
8278
+ /** Normalize user/CLI/HTTP model-family aliases onto canonical `ModelFamily` keys. */
8279
+ function normalizeModelFamily(raw) {
8280
+ if (!raw) return void 0;
8281
+ const clean = raw.trim().toLowerCase();
8282
+ if (clean === "google" || clean === "gemini") return "google";
8283
+ if (clean === "argon") return "argon";
8284
+ if (clean === "anthropic" || clean === "claude") return "anthropic";
8285
+ if (clean === "openai" || clean === "gpt" || clean === "gpt-oss") return "openai";
8286
+ if (clean === "unknown") return "unknown";
8287
+ }
7856
8288
  function isWindowBenched(fraction, resetTime, threshold, now) {
7857
8289
  if (typeof fraction !== "number" || fraction > threshold) return false;
7858
8290
  if (!resetTime) return true;
@@ -8048,6 +8480,21 @@ function orderByExpiry(accounts, candidates, family, fromId, now) {
8048
8480
  return da !== db ? da - db : a.index - b.index;
8049
8481
  }).map((e) => e.acc);
8050
8482
  }
8483
+ /**
8484
+ * Pure, side-effect-free lookup of the active eligible account ID for a given
8485
+ * family. Honors a still-eligible family pin first, then falls back to the
8486
+ * first eligible candidate in rotation order without mutating pool state.
8487
+ */
8488
+ function resolveEligibleActiveAccountId(accounts, activeAccountIds, family, pool, now = Date.now(), model) {
8489
+ const pinnedId = activeAccountIds?.[family];
8490
+ if (pinnedId) {
8491
+ const pinned = accounts.find((a) => a.id === pinnedId);
8492
+ if (pinned && isAccountEligible(pinned, family, now, pool, model)) return pinned.id;
8493
+ }
8494
+ const candidates = accounts.filter((acc) => isAccountEligible(acc, family, now, pool, model));
8495
+ if (candidates.length === 0) return void 0;
8496
+ return orderByExpiry(accounts, candidates, family, pinnedId, now)[0]?.id;
8497
+ }
8051
8498
  //#endregion
8052
8499
  //#region src/domain/accounts/admin.ts
8053
8500
  var PoolAdmin = class {
@@ -8213,21 +8660,20 @@ var PoolAdmin = class {
8213
8660
  this.deps.persist();
8214
8661
  }
8215
8662
  /**
8216
- * Manually pin the active slot for one family (console "设为当前使用").
8217
- * The pin survives until the scheduler legitimately rotates away (quota
8218
- * exhaustion / cooldown / auth flag) — getActiveAccountId still enforces
8219
- * eligibility, so pinning an ineligible slot simply does not stick.
8663
+ * Manually pin the active slot for one family (console per-family "设为当前").
8664
+ * Strictly family-scoped: pinning one family never mutates or clears another
8665
+ * family's active slot or session stickiness.
8220
8666
  */
8221
8667
  setActiveAccount(id, family = "google") {
8222
8668
  const data = this.deps.getData();
8223
8669
  const acc = this.account(id);
8224
- if (!acc || !isAccountEligible(acc, family, Date.now(), this.deps.pool)) return false;
8670
+ const now = Date.now();
8671
+ if (!acc || !isAccountEligible(acc, family, now, this.deps.pool)) return false;
8225
8672
  if (!data.activeAccountIds) data.activeAccountIds = {};
8226
8673
  data.activeAccountIds[family] = id;
8227
- data.lastActiveAccountId = id;
8228
- data.manualPinAt = Date.now();
8229
- if (!accountHasArgon(acc, this.deps.pool)) delete data.activeAccountIds.argon;
8230
- else data.activeAccountIds.argon = id;
8674
+ if (!data.manualPinAtByFamily) data.manualPinAtByFamily = {};
8675
+ data.manualPinAtByFamily[family] = now;
8676
+ if (family === "google" || !data.lastActiveAccountId) data.lastActiveAccountId = id;
8231
8677
  this.deps.persist();
8232
8678
  return true;
8233
8679
  }
@@ -8329,12 +8775,12 @@ var PoolAdmin = class {
8329
8775
  data.activeAccountIds = {
8330
8776
  google: id,
8331
8777
  anthropic: id,
8332
- openai: id,
8333
- ...accountHasArgon(acc, this.deps.pool) ? { argon: id } : {}
8778
+ openai: id
8334
8779
  };
8335
8780
  data.lastActiveAccountId = id;
8336
8781
  }
8337
8782
  data.manualPinAt = Date.now();
8783
+ data.manualPinAtByFamily = {};
8338
8784
  this.deps.persist();
8339
8785
  return true;
8340
8786
  }
@@ -8354,6 +8800,7 @@ var PoolAdmin = class {
8354
8800
  data.activeAccountIds = {};
8355
8801
  data.lastActiveAccountId = void 0;
8356
8802
  data.manualPinAt = Date.now();
8803
+ data.manualPinAtByFamily = {};
8357
8804
  this.deps.persist();
8358
8805
  return true;
8359
8806
  }
@@ -8383,7 +8830,8 @@ var PoolAdmin = class {
8383
8830
  reason,
8384
8831
  consecutiveFailures: failures
8385
8832
  };
8386
- if (data.activeAccountIds?.[family] === id || data.lastActiveAccountId === id) this.advanceAccount(id, family);
8833
+ const famPinned = data.activeAccountIds?.[family];
8834
+ if (famPinned === id || famPinned === void 0 && data.lastActiveAccountId === id) this.advanceAccount(id, family);
8387
8835
  this.deps.persist();
8388
8836
  }
8389
8837
  /**
@@ -8417,15 +8865,15 @@ var PoolAdmin = class {
8417
8865
  const next = orderByExpiry(data.accounts, candidates, family, fromId, Date.now())[0];
8418
8866
  if (!data.activeAccountIds) data.activeAccountIds = {};
8419
8867
  data.activeAccountIds[family] = next.id;
8420
- data.lastActiveAccountId = next.id;
8868
+ if (family === "google" || !data.lastActiveAccountId) data.lastActiveAccountId = next.id;
8421
8869
  this.deps.persist();
8422
8870
  return next.id;
8423
8871
  }
8424
8872
  /**
8425
- * Returns the currently active and healthy account ID.
8426
- * If the recorded lastActiveAccountId is healthy, returns it;
8427
- * otherwise falls back to the scheduler (selectAccount) to advance to the next
8428
- * healthy candidate, or primaryAccountId if all are exhausted.
8873
+ * Returns the currently active and healthy account ID for `family`.
8874
+ * Checks this family's active pointer first; only checks `lastActiveAccountId`
8875
+ * when this family has no pointer yet, otherwise selects the next eligible
8876
+ * candidate strictly within `family`.
8429
8877
  */
8430
8878
  getActiveAccountId(family = "google", model) {
8431
8879
  const data = this.deps.getData();
@@ -8435,7 +8883,7 @@ var PoolAdmin = class {
8435
8883
  const pinned = data.accounts.find((a) => a.id === pinnedId);
8436
8884
  if (pinned && isAccountEligible(pinned, family, now, this.deps.pool, model)) return pinned.id;
8437
8885
  }
8438
- if (data.lastActiveAccountId) {
8886
+ if (pinnedId === void 0 && data.lastActiveAccountId) {
8439
8887
  const active = data.accounts.find((a) => a.id === data.lastActiveAccountId);
8440
8888
  if (active && isAccountEligible(active, family, now, this.deps.pool, model)) return active.id;
8441
8889
  }
@@ -8745,6 +9193,152 @@ var PoolStore = class {
8745
9193
  //#endregion
8746
9194
  //#region src/host/wincred.ts
8747
9195
  const IS_WIN = process.platform === "win32";
9196
+ const WIN_CRED_CS_SRC = `using System;
9197
+ using System.Runtime.InteropServices;
9198
+
9199
+ public static class WinCredCli {
9200
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
9201
+ public static extern bool CredWrite([In] ref CREDENTIAL userCredential, [In] uint flags);
9202
+
9203
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
9204
+ public static extern bool CredRead(string target, int type, int flags, out IntPtr credential);
9205
+
9206
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
9207
+ public static extern bool CredDelete(string target, int type, int flags);
9208
+
9209
+ [DllImport("advapi32.dll", SetLastError = true)]
9210
+ public static extern void CredFree(IntPtr cred);
9211
+
9212
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
9213
+ public struct CREDENTIAL {
9214
+ public int Flags;
9215
+ public int Type;
9216
+ public string TargetName;
9217
+ public string Comment;
9218
+ public long LastWritten;
9219
+ public int CredentialBlobSize;
9220
+ public IntPtr CredentialBlob;
9221
+ public int Persist;
9222
+ public int AttributeCount;
9223
+ public IntPtr Attributes;
9224
+ public string TargetAlias;
9225
+ public string UserName;
9226
+ }
9227
+
9228
+ public static int Main(string[] args) {
9229
+ if (args.Length < 2) return 2;
9230
+ string action = args[0];
9231
+ string target = args[1];
9232
+ string user = args.Length > 2 ? args[2] : "antigravity";
9233
+ if (action == "read") {
9234
+ IntPtr p;
9235
+ if (!CredRead(target, 1, 0, out p)) return 0;
9236
+ try {
9237
+ CREDENTIAL c = (CREDENTIAL)Marshal.PtrToStructure(p, typeof(CREDENTIAL));
9238
+ byte[] b = new byte[c.CredentialBlobSize];
9239
+ if (c.CredentialBlobSize > 0 && c.CredentialBlob != IntPtr.Zero) {
9240
+ Marshal.Copy(c.CredentialBlob, b, 0, c.CredentialBlobSize);
9241
+ }
9242
+ Console.Out.Write(Convert.ToBase64String(b));
9243
+ } finally {
9244
+ CredFree(p);
9245
+ }
9246
+ return 0;
9247
+ }
9248
+ if (action == "write") {
9249
+ string payload = Console.In.ReadToEnd().Trim();
9250
+ byte[] secret = Convert.FromBase64String(payload);
9251
+ CREDENTIAL c = new CREDENTIAL();
9252
+ c.Type = 1;
9253
+ c.TargetName = target;
9254
+ c.UserName = user;
9255
+ c.Persist = 2;
9256
+ c.CredentialBlobSize = secret.Length;
9257
+ IntPtr p = Marshal.AllocHGlobal(secret.Length);
9258
+ Marshal.Copy(secret, 0, p, secret.Length);
9259
+ c.CredentialBlob = p;
9260
+ bool ok;
9261
+ try {
9262
+ ok = CredWrite(ref c, 0);
9263
+ } finally {
9264
+ Marshal.FreeHGlobal(p);
9265
+ }
9266
+ Console.Out.Write(ok ? "True" : "False");
9267
+ return ok ? 0 : 1;
9268
+ }
9269
+ if (action == "delete") {
9270
+ bool ok = CredDelete(target, 1, 0);
9271
+ Console.Out.Write(ok ? "True" : "False");
9272
+ return 0;
9273
+ }
9274
+ return 2;
9275
+ }
9276
+ }
9277
+ `;
9278
+ const WIN_CRED_HASH = createHash("sha256").update(WIN_CRED_CS_SRC).digest("hex").slice(0, 8);
9279
+ let helperDisabled = false;
9280
+ let cachedHelperPath = null;
9281
+ function findCscExe() {
9282
+ const windir = process.env.WINDIR || process.env.SystemRoot || "C:\\Windows";
9283
+ const candidates = [join(windir, "Microsoft.NET", "Framework64", "v4.0.30319", "csc.exe"), join(windir, "Microsoft.NET", "Framework", "v4.0.30319", "csc.exe")];
9284
+ for (const cand of candidates) if (existsSync(cand)) return cand;
9285
+ return null;
9286
+ }
9287
+ /**
9288
+ * Compile and cache a tiny standalone .NET Win32 helper once per source hash so
9289
+ * Credential Manager reads/writes take ~15ms instead of ~1.5-3s per powershell.exe
9290
+ * Add-Type cold compilation. Falls back cleanly to PowerShell if csc.exe is absent.
9291
+ */
9292
+ function ensureWinCredHelper() {
9293
+ if (!IS_WIN || helperDisabled) return null;
9294
+ if (cachedHelperPath && existsSync(cachedHelperPath)) return cachedHelperPath;
9295
+ const csc = findCscExe();
9296
+ if (!csc) {
9297
+ helperDisabled = true;
9298
+ return null;
9299
+ }
9300
+ const binDir = join(stateDir(), "bin");
9301
+ const finalExe = join(binDir, `wincred-v1-${WIN_CRED_HASH}.exe`);
9302
+ if (existsSync(finalExe)) {
9303
+ cachedHelperPath = finalExe;
9304
+ return finalExe;
9305
+ }
9306
+ const stamp = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
9307
+ const tmpCs = join(binDir, `wincred-${stamp}.cs`);
9308
+ const tmpExe = join(binDir, `wincred-${stamp}.exe`);
9309
+ try {
9310
+ mkdirSync(binDir, { recursive: true });
9311
+ writeFileSync(tmpCs, WIN_CRED_CS_SRC, "utf8");
9312
+ execFileSync(csc, [
9313
+ "/nologo",
9314
+ "/optimize+",
9315
+ "/target:exe",
9316
+ `/out:${tmpExe}`,
9317
+ tmpCs
9318
+ ], {
9319
+ timeout: 2e4,
9320
+ windowsHide: true,
9321
+ stdio: "ignore"
9322
+ });
9323
+ try {
9324
+ renameSync(tmpExe, finalExe);
9325
+ } catch {
9326
+ if (!existsSync(finalExe)) throw new Error("failed to finalize wincred helper");
9327
+ }
9328
+ cachedHelperPath = finalExe;
9329
+ return finalExe;
9330
+ } catch {
9331
+ helperDisabled = true;
9332
+ return null;
9333
+ } finally {
9334
+ try {
9335
+ rmSync(tmpCs, { force: true });
9336
+ } catch {}
9337
+ try {
9338
+ rmSync(tmpExe, { force: true });
9339
+ } catch {}
9340
+ }
9341
+ }
8748
9342
  const WIN_CRED_SCRIPT = `
8749
9343
  param($target, $user, $action, $payload)
8750
9344
 
@@ -8829,8 +9423,29 @@ if ($action -eq "write") {
8829
9423
  [Console]::Out.Write($ok)
8830
9424
  }
8831
9425
  `;
8832
- /** Execute an action against Windows Credential Manager. */
8833
- function runWinCredPs(target, user, action, payload = "") {
9426
+ /** Execute an action against Windows Credential Manager (fast cached .exe with PowerShell fallback). */
9427
+ function runWinCred(target, user, action, payload = "") {
9428
+ const timeout = action === "write" ? 3e4 : 8e3;
9429
+ const helper = ensureWinCredHelper();
9430
+ if (helper) try {
9431
+ return execFileSync(helper, action === "write" ? [
9432
+ action,
9433
+ target,
9434
+ user
9435
+ ] : [action, target], {
9436
+ encoding: "utf8",
9437
+ timeout,
9438
+ windowsHide: true,
9439
+ input: action === "write" ? payload : void 0,
9440
+ stdio: [
9441
+ action === "write" ? "pipe" : "ignore",
9442
+ "pipe",
9443
+ "ignore"
9444
+ ]
9445
+ }).trim();
9446
+ } catch {
9447
+ helperDisabled = true;
9448
+ }
8834
9449
  return execFileSync("powershell.exe", [
8835
9450
  "-NoProfile",
8836
9451
  "-NonInteractive",
@@ -8844,7 +9459,7 @@ function runWinCredPs(target, user, action, payload = "") {
8844
9459
  payload
8845
9460
  ], {
8846
9461
  encoding: "utf8",
8847
- timeout: action === "write" ? 3e4 : 8e3,
9462
+ timeout,
8848
9463
  windowsHide: true,
8849
9464
  stdio: [
8850
9465
  "ignore",
@@ -8860,7 +9475,7 @@ function readWindowsCredentialRaw(target = "gemini:antigravity", maxAgeMs = 2500
8860
9475
  const now = Date.now();
8861
9476
  if (cachedWinCredRaw && cachedWinCredRaw.target === target && now - cachedWinCredRaw.time < maxAgeMs) return cachedWinCredRaw.val;
8862
9477
  try {
8863
- const out = runWinCredPs(target, "antigravity", "read");
9478
+ const out = runWinCred(target, "antigravity", "read");
8864
9479
  const val = out ? Buffer.from(out, "base64").toString("utf8") : null;
8865
9480
  cachedWinCredRaw = {
8866
9481
  target,
@@ -8876,7 +9491,7 @@ function readWindowsCredentialRaw(target = "gemini:antigravity", maxAgeMs = 2500
8876
9491
  function writeWindowsCredentialRaw(secret, target = "gemini:antigravity", userName = "antigravity") {
8877
9492
  if (!IS_WIN) return false;
8878
9493
  try {
8879
- const ok = runWinCredPs(target, userName, "write", Buffer.from(secret, "utf8").toString("base64")).toLowerCase() === "true";
9494
+ const ok = runWinCred(target, userName, "write", Buffer.from(secret, "utf8").toString("base64")).toLowerCase() === "true";
8880
9495
  if (ok) cachedWinCredRaw = {
8881
9496
  target,
8882
9497
  val: secret,
@@ -9130,8 +9745,19 @@ var AccountPoolManager = class {
9130
9745
  }
9131
9746
  getPoolData(defaultProxy) {
9132
9747
  const sysProxy = defaultProxy || detectSystemProxy();
9748
+ const now = Date.now();
9749
+ const resolvedActiveAccountIds = {};
9750
+ const source = {
9751
+ hasDedicatedGroup: (id, fam) => this.hasDedicatedGroup(id, fam),
9752
+ isModelSupported: (acc, model) => this.isModelSupported(acc, model)
9753
+ };
9754
+ for (const fam of QUOTA_FAMILIES) {
9755
+ const resolved = resolveEligibleActiveAccountId(this.data.accounts, this.data.activeAccountIds, fam, source, now);
9756
+ if (resolved) resolvedActiveAccountIds[fam] = resolved;
9757
+ }
9133
9758
  return {
9134
9759
  ...this.data,
9760
+ resolvedActiveAccountIds,
9135
9761
  activeAccountId: this.getActiveAccountId("google"),
9136
9762
  ...sysProxy ? { systemProxy: sysProxy } : {}
9137
9763
  };
@@ -9304,8 +9930,12 @@ var AccountPoolManager = class {
9304
9930
  if (isExhausted5h || isExhaustedWeekly) {
9305
9931
  const clearedAt = acc.quotaGateClearedAt?.[famKey];
9306
9932
  const gateCleared = clearedAt !== void 0 && (info.updatedAt ?? 0) <= clearedAt;
9307
- if (!gateCleared && (this.data.activeAccountIds?.[famKey] === id || this.data.lastActiveAccountId === id)) this.advanceAccount(id, famKey);
9308
- if (!gateCleared && famKey === "google" && !acc.quotas?.argon && this.data.activeAccountIds?.argon === id) this.advanceAccount(id, "argon");
9933
+ const famPinned = this.data.activeAccountIds?.[famKey];
9934
+ const ownsFamily = famPinned === id || famPinned === void 0 && this.data.lastActiveAccountId === id;
9935
+ if (!gateCleared && ownsFamily) this.advanceAccount(id, famKey);
9936
+ const argonPinned = this.data.activeAccountIds?.argon;
9937
+ const ownsArgon = argonPinned === id || argonPinned === void 0 && this.data.lastActiveAccountId === id;
9938
+ if (!gateCleared && famKey === "google" && !acc.quotas?.argon && ownsArgon) this.advanceAccount(id, "argon");
9309
9939
  }
9310
9940
  }
9311
9941
  this.persist();
@@ -9388,12 +10018,13 @@ var AccountPoolManager = class {
9388
10018
  */
9389
10019
  clearCooldown(id, family, includeQuotaBench = false) {
9390
10020
  const now = Date.now();
10021
+ const targetFamily = family ? normalizeModelFamily(family) ?? family : void 0;
9391
10022
  const clearOne = (acc) => {
9392
10023
  acc.cooldowns ??= {};
9393
- if (family) delete acc.cooldowns[family];
10024
+ if (targetFamily) delete acc.cooldowns[targetFamily];
9394
10025
  else acc.cooldowns = {};
9395
10026
  if (!includeQuotaBench) return;
9396
- const families = family ? [family] : Object.keys(acc.quotas ?? {});
10027
+ const families = targetFamily ? [targetFamily] : Object.keys(acc.quotas ?? {});
9397
10028
  if (families.length === 0) return;
9398
10029
  acc.quotaGateClearedAt ??= {};
9399
10030
  for (const fam of families) {
@@ -9423,7 +10054,7 @@ var AccountPoolManager = class {
9423
10054
  const prevId = this.data.activeAccountIds?.[family];
9424
10055
  if (!this.data.activeAccountIds) this.data.activeAccountIds = {};
9425
10056
  this.data.activeAccountIds[family] = picked.id;
9426
- this.data.lastActiveAccountId = picked.id;
10057
+ if (family === "google" || !this.data.lastActiveAccountId) this.data.lastActiveAccountId = picked.id;
9427
10058
  this.persist();
9428
10059
  if (prevId && prevId !== picked.id) this.onAccountSwitch?.(picked.id, family);
9429
10060
  }
@@ -9433,7 +10064,7 @@ var AccountPoolManager = class {
9433
10064
  if (activeId) {
9434
10065
  const activeCandidate = candidates.find((a) => a.id === activeId);
9435
10066
  if (activeCandidate) {
9436
- if (this.data.lastActiveAccountId !== activeCandidate.id) {
10067
+ if ((family === "google" || !this.data.lastActiveAccountId) && this.data.lastActiveAccountId !== activeCandidate.id) {
9437
10068
  this.data.lastActiveAccountId = activeCandidate.id;
9438
10069
  this.persist();
9439
10070
  }
@@ -9443,7 +10074,7 @@ var AccountPoolManager = class {
9443
10074
  const nextAccount = this.orderByExpiry(candidates, family, activeId)[0];
9444
10075
  if (!this.data.activeAccountIds) this.data.activeAccountIds = {};
9445
10076
  this.data.activeAccountIds[family] = nextAccount.id;
9446
- this.data.lastActiveAccountId = nextAccount.id;
10077
+ if (family === "google" || !this.data.lastActiveAccountId) this.data.lastActiveAccountId = nextAccount.id;
9447
10078
  this.persist();
9448
10079
  if (activeId && activeId !== nextAccount.id) this.onAccountSwitch?.(nextAccount.id, family);
9449
10080
  return nextAccount;
@@ -22438,7 +23069,7 @@ var require_snapshot_utils = /* @__PURE__ */ __commonJSMin(((exports, module) =>
22438
23069
  //#endregion
22439
23070
  //#region node_modules/undici/lib/mock/snapshot-recorder.js
22440
23071
  var require_snapshot_recorder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
22441
- const { writeFile: writeFile$1, readFile, mkdir: mkdir$1 } = __require("node:fs/promises");
23072
+ const { writeFile: writeFile$1, readFile: readFile$1, mkdir: mkdir$1 } = __require("node:fs/promises");
22442
23073
  const { dirname: dirname$1, resolve: resolve$1 } = __require("node:path");
22443
23074
  const { setTimeout: setTimeout$1, clearTimeout: clearTimeout$1 } = __require("node:timers");
22444
23075
  const { InvalidArgumentError, UndiciError } = require_errors();
@@ -22738,7 +23369,7 @@ var require_snapshot_recorder = /* @__PURE__ */ __commonJSMin(((exports, module)
22738
23369
  const path = filePath || this.#snapshotPath;
22739
23370
  if (!path) throw new InvalidArgumentError("Snapshot path is required");
22740
23371
  try {
22741
- const data = await readFile(resolve$1(path), "utf8");
23372
+ const data = await readFile$1(resolve$1(path), "utf8");
22742
23373
  const parsed = JSON.parse(data);
22743
23374
  if (Array.isArray(parsed)) {
22744
23375
  this.#snapshots.clear();
@@ -34380,6 +35011,24 @@ function brief$1(s) {
34380
35011
  const flat = s.trim().replace(/\s+/g, " ");
34381
35012
  return flat.length > 300 ? flat.slice(0, 300) + "..." : flat;
34382
35013
  }
35014
+ function serializeOpt(v) {
35015
+ if (typeof v === "string") return v.trim() !== "" ? v.trim() : void 0;
35016
+ if (v && typeof v === "object") return JSON.stringify(v);
35017
+ }
35018
+ function resolveAttemptOverrides(options, cfg) {
35019
+ const agent = typeof options.agyAgent === "string" ? options.agyAgent.trim() : cfg.agent.trim();
35020
+ const agySettings = serializeOpt(options.agySettings) ?? serializeOpt(cfg.agySettings);
35021
+ const jsonSchema = serializeOpt(options.agyJsonSchema);
35022
+ const sandbox = options.agySandbox ?? cfg.sandbox;
35023
+ const transport = options.agyTransport ?? cfg.transport;
35024
+ return {
35025
+ ...agent !== "" ? { agent } : {},
35026
+ ...agySettings !== void 0 ? { agySettings } : {},
35027
+ ...jsonSchema !== void 0 ? { jsonSchema } : {},
35028
+ sandbox,
35029
+ transport
35030
+ };
35031
+ }
34383
35032
  /** Pure argv builder for one agy call (same body as AgyAdapter.buildArgs). */
34384
35033
  function buildAgyArgs(opts) {
34385
35034
  const args = [
@@ -34390,6 +35039,10 @@ function buildAgyArgs(opts) {
34390
35039
  ];
34391
35040
  if (opts.permissionMode === "skip") args.push("--dangerously-skip-permissions");
34392
35041
  else args.push("--mode", opts.permissionMode);
35042
+ if (opts.sandbox === true) args.push("--sandbox");
35043
+ if (opts.agent && opts.agent.trim() !== "") args.push("--agent", opts.agent.trim());
35044
+ if (opts.agySettings && opts.agySettings.trim() !== "") args.push("--settings", opts.agySettings.trim());
35045
+ if (opts.jsonSchema && opts.jsonSchema.trim() !== "") args.push("--json-schema", opts.jsonSchema.trim());
34393
35046
  const effectiveModel = resolveModelSlug(opts.model);
34394
35047
  if (effectiveModel !== "") args.push("--model", effectiveModel);
34395
35048
  const effortModel = effectiveModel.toLowerCase();
@@ -34423,7 +35076,11 @@ function buildSpawnArgs(input, printTimeoutMinutes, log) {
34423
35076
  timeoutMs: input.cfg.timeoutMs,
34424
35077
  printTimeoutMinutes,
34425
35078
  extraArgs: input.cfg.extraArgs,
34426
- addDirs: input.addDirs
35079
+ addDirs: input.addDirs,
35080
+ sandbox: input.sandbox ?? input.cfg.sandbox,
35081
+ ...(input.agent ?? input.cfg.agent).trim() !== "" ? { agent: (input.agent ?? input.cfg.agent).trim() } : {},
35082
+ ...(input.agySettings ?? input.cfg.agySettings).trim() !== "" ? { agySettings: (input.agySettings ?? input.cfg.agySettings).trim() } : {},
35083
+ ...input.jsonSchema && input.jsonSchema.trim() !== "" ? { jsonSchema: input.jsonSchema.trim() } : {}
34427
35084
  };
34428
35085
  const argsBase = buildAgyArgs(base);
34429
35086
  const promptViaStdin = shouldUsePromptStdin(argsBase);
@@ -35204,6 +35861,16 @@ async function* runAgyAttempt(deps, input) {
35204
35861
  ...input,
35205
35862
  prompt: spawn.prompt
35206
35863
  });
35864
+ if ((input.transport ?? input.cfg.transport) === "acp" && deps.runAcp && !input.jsonSchema && !input.agySettings && !input.isAux) {
35865
+ const acpRec = await deps.runAcp(deps, {
35866
+ ...input,
35867
+ prompt: spawn.prompt
35868
+ }, slot).catch(() => null);
35869
+ if (acpRec !== null) {
35870
+ recorder.stop();
35871
+ return acpRec;
35872
+ }
35873
+ }
35207
35874
  handleAttemptOutcome(deps, input, {
35208
35875
  ...await startAttemptProcess(deps, input, spawn, recorder, slot),
35209
35876
  recorder,
@@ -35459,7 +36126,7 @@ var AgyAdapter = class extends LlmAdapter {
35459
36126
  const account = selection.account;
35460
36127
  let family = selection.family;
35461
36128
  let activeModel = selection.activeModel;
35462
- if (account && !isAux) this.deps.pool?.markAccountActive(account.id);
36129
+ if (account && !isAux && (family === "google" || !this.deps.pool?.getPoolData().lastActiveAccountId)) this.deps.pool?.markAccountActive(account.id);
35463
36130
  const onAccount = options.agyOnAccount;
35464
36131
  if (typeof onAccount === "function" && account) try {
35465
36132
  onAccount({
@@ -35570,7 +36237,8 @@ var AgyAdapter = class extends LlmAdapter {
35570
36237
  sharesSingleEgress: () => this.sharesSingleEgress(),
35571
36238
  lastAccountSpawnTime: this.lastAccountSpawnTime,
35572
36239
  minSpawnIntervalMs: this.minSpawnIntervalMs,
35573
- spawnLimiter: this.spawnLimiter
36240
+ spawnLimiter: this.spawnLimiter,
36241
+ ...this.deps.runAcp === void 0 ? {} : { runAcp: this.deps.runAcp }
35574
36242
  }, {
35575
36243
  cfg,
35576
36244
  bin,
@@ -35591,7 +36259,8 @@ var AgyAdapter = class extends LlmAdapter {
35591
36259
  sessionAccountKey,
35592
36260
  family,
35593
36261
  signal: options.signal,
35594
- agyOnEvent: options.agyOnEvent
36262
+ agyOnEvent: options.agyOnEvent,
36263
+ ...resolveAttemptOverrides(options, cfg)
35595
36264
  });
35596
36265
  yield* driveSpan(this.deps, rec, 0, policy.mirrorTools && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal, compactionNotice);
35597
36266
  }
@@ -35612,9 +36281,9 @@ const USAGE = `dsh-agy-image — 用 agy 内置的 generate_image 生成图片
35612
36281
  -i, --image, --ref <path> 参考图/源图(可重复;用于改图)
35613
36282
  -o, --out <path> 把成图复制到该路径(或目录)
35614
36283
  --model <id> 驱动调用的模型(默认跟随插件配置)
35615
- --effort <level> 思考档(默认 low)
36284
+ --effort <level> 思考档(默认 medium)
35616
36285
  --timeout <seconds> 整次生成超时(默认 240)
35617
- --permission-mode <m> skip | plan | accept-edits(默认跟随插件配置)
36286
+ --permission-mode <m> skip | auto | plan | accept-edits(默认跟随插件配置)
35618
36287
  --max-bytes <n> 接受的最大产物字节数(默认 20MiB)
35619
36288
  --json 输出结构化 JSON(含 ok/path/width/height/mime/...)
35620
36289
  --force 忽略本进程内的结果缓存,重新生成
@@ -35636,6 +36305,7 @@ const USAGE = `dsh-agy-image — 用 agy 内置的 generate_image 生成图片
35636
36305
  `;
35637
36306
  const MODES = [
35638
36307
  "skip",
36308
+ "auto",
35639
36309
  "plan",
35640
36310
  "accept-edits"
35641
36311
  ];
@@ -35772,144 +36442,17 @@ function exitCodeFor(res) {
35772
36442
  default: return 4;
35773
36443
  }
35774
36444
  }
35775
- function toolCallFrom(ev) {
35776
- if (ev.kind !== "step" || ev.tool === void 0) return null;
35777
- return {
35778
- name: ev.tool.name,
35779
- ...ev.tool.args === void 0 ? {} : { args: ev.tool.args },
35780
- ...ev.tool.output === void 0 ? {} : { output: String(ev.tool.output) },
35781
- ...ev.tool.error === void 0 ? {} : { error: ev.tool.error }
35782
- };
35783
- }
35784
- function subagentsFrom(ev) {
35785
- if (ev.kind !== "step") return [];
35786
- const list = ev.raw?.subagent_info?.subagents;
35787
- if (!Array.isArray(list)) return [];
35788
- const out = [];
35789
- for (const d of list) {
35790
- const one = d;
35791
- out.push({
35792
- ...typeof one.conversation_id === "string" ? { conversationId: one.conversation_id } : {},
35793
- ...typeof one.log_uri === "string" ? { logUri: one.log_uri } : {}
35794
- });
35795
- }
35796
- return out;
35797
- }
35798
- /**
35799
- * One image attempt through the real adapter. This is the only place that
35800
- * knows how to turn an `AgyAdapter` stream into the service's event contract.
35801
- */
35802
- async function runViaAdapter(adapter, call) {
35803
- const started = Date.now();
35804
- const toolCalls = [];
35805
- const subagents = [];
35806
- const textParts = [];
35807
- let responseText = "";
35808
- let conversationId;
35809
- let home;
35810
- let accountId;
35811
- let failure = null;
35812
- let timedOut = false;
35813
- const controller = new AbortController();
35814
- const timer = setTimeout(() => {
35815
- timedOut = true;
35816
- controller.abort();
35817
- }, call.timeoutMs);
35818
- timer.unref?.();
35819
- const signal = call.signal === void 0 ? controller.signal : AbortSignal.any([call.signal, controller.signal]);
35820
- const options = {
35821
- provider: PROVIDER_ID,
35822
- model: call.model,
35823
- ...call.effort === "" ? {} : { reasoningEffort: call.effort },
35824
- messages: [{
35825
- role: "user",
35826
- content: [{
35827
- type: "text",
35828
- text: call.prompt
35829
- }],
35830
- source: { kind: "user" }
35831
- }],
35832
- maxTokens: 4096,
35833
- purpose: "image",
35834
- signal,
35835
- agyImagePrompt: call.prompt,
35836
- agyPermissionMode: call.permissionMode,
35837
- agyOnAccount: (info) => {
35838
- if (typeof info.id === "string") accountId = info.id;
35839
- if (typeof info.home === "string" && info.home !== "") home = info.home;
35840
- },
35841
- agyOnEvent: (ev) => {
35842
- if (ev.kind === "init" && ev.conversationId !== void 0) conversationId = ev.conversationId;
35843
- if (ev.kind === "step") {
35844
- if (ev.stepKind === "text" && ev.text !== "") textParts.push(ev.text);
35845
- const tc = toolCallFrom(ev);
35846
- if (tc !== null) toolCalls.push(tc);
35847
- for (const s of subagentsFrom(ev)) subagents.push(s);
35848
- }
35849
- if (ev.kind === "result") {
35850
- if (ev.conversationId !== "") conversationId = ev.conversationId;
35851
- if (ev.response !== "") responseText = ev.response;
35852
- const err = ev.raw?.result?.error;
35853
- if (typeof err === "string" && err !== "") failure = { message: err };
35854
- }
35855
- }
35856
- };
35857
- try {
35858
- for await (const chunk of adapter.stream(options)) {
35859
- if (chunk.type === "text-delta" && typeof chunk.text === "string") textParts.push(chunk.text);
35860
- if (chunk.type === "finish") {
35861
- const reason = chunk.reason;
35862
- if (reason?.kind === "error" || reason?.kind === "aborted") failure = {
35863
- ...typeof reason.failure?.code === "string" ? { code: reason.failure.code } : {},
35864
- ...typeof reason.failure?.message === "string" ? { message: reason.failure.message } : {}
35865
- };
35866
- }
35867
- }
35868
- } catch (e) {
35869
- const err = e;
35870
- const message = typeof err.message === "string" ? err.message : String(e);
35871
- const code = typeof err.code === "string" ? err.code : /accounts are unavailable|no account/i.test(message) ? "RATE_LIMIT" : void 0;
35872
- failure = {
35873
- ...code === void 0 ? {} : { code },
35874
- message
35875
- };
35876
- } finally {
35877
- clearTimeout(timer);
35878
- }
35879
- const text = (textParts.join("\n").trim() || responseText).trim();
35880
- if (failure !== null) {
35881
- const code = timedOut ? "TIMEOUT" : failure.code ?? "AGY_ERROR";
35882
- return {
35883
- ok: false,
35884
- text,
35885
- toolCalls,
35886
- subagents,
35887
- ...conversationId === void 0 ? {} : { conversationId },
35888
- ...home === void 0 ? {} : { home },
35889
- ...accountId === void 0 ? {} : { accountId },
35890
- code,
35891
- error: timedOut ? "timed out after " + call.timeoutMs + "ms" : failure.message ?? "image generation failed",
35892
- durationMs: Date.now() - started
35893
- };
35894
- }
35895
- return {
35896
- ok: true,
35897
- text,
35898
- toolCalls,
35899
- subagents,
35900
- ...conversationId === void 0 ? {} : { conversationId },
35901
- ...home === void 0 ? {} : { home },
35902
- ...accountId === void 0 ? {} : { accountId },
35903
- durationMs: Date.now() - started
35904
- };
36445
+ /** Hydrate the cached catalog from disk without spawning `agy models`. */
36446
+ function createImageCatalog(cfg) {
36447
+ return new ModelCatalog(async () => {
36448
+ throw new Error("model discovery is disabled for the image CLI");
36449
+ }, cfg.fallbackModels, 3e5, void 0, { cacheFile: join(stateDir(), "model-catalog.json") });
35905
36450
  }
35906
36451
  /** Build the real adapter (same deps as the smoke scripts / host). */
35907
- function createImageAdapter(cfg, log) {
36452
+ function createImageAdapter(cfg, log, catalog = createImageCatalog(cfg)) {
35908
36453
  return new AgyAdapter({
35909
36454
  getConfig: () => cfg,
35910
- catalog: new ModelCatalog(async () => {
35911
- throw new Error("model discovery is disabled for the image CLI");
35912
- }, cfg.fallbackModels, 3e5),
36455
+ catalog,
35913
36456
  store: new SessionStore(join(stateDir(), "cli-image-sessions.json")),
35914
36457
  pool: new AccountPoolManager(),
35915
36458
  bin: () => resolveAgyBin(cfg),
@@ -35923,11 +36466,13 @@ function createDefaultImageService(args, _req, writeErr) {
35923
36466
  const cfg = resolveConfig(void 0);
35924
36467
  if (cfg.workspaceRoot === "") cfg.workspaceRoot = process.cwd();
35925
36468
  const bin = resolveAgyBin(cfg);
35926
- const adapter = createImageAdapter(cfg, args.quiet ? void 0 : (m) => writeErr("[agy] " + m + "\n"));
36469
+ const catalog = createImageCatalog(cfg);
36470
+ const adapter = createImageAdapter(cfg, args.quiet ? void 0 : (m) => writeErr("[agy] " + m + "\n"), catalog);
35927
36471
  return new ImageService({
35928
36472
  cfg: () => cfg,
35929
36473
  bin: () => bin,
35930
36474
  run: (call) => runViaAdapter(adapter, call),
36475
+ catalog: () => catalog.get(),
35931
36476
  ...args.quiet ? {} : { log: (m) => writeErr("[image] " + m + "\n") }
35932
36477
  });
35933
36478
  }