dsh-agy-link 0.6.54 → 0.6.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/dist/cli-image.mjs +1053 -269
- package/dist/client.js +1851 -311
- package/dist/index.js +4960 -540
- package/package.json +1 -1
package/dist/cli-image.mjs
CHANGED
|
@@ -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: "
|
|
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() ||
|
|
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
|
|
2869
|
-
"image/
|
|
2870
|
-
"
|
|
2871
|
-
"
|
|
2872
|
-
"
|
|
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 =
|
|
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 `
|
|
2898
|
-
* reference them by absolute path.
|
|
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
|
|
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.
|
|
2907
|
-
if (budget > 0 && opts.
|
|
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
|
-
|
|
2910
|
-
for (const ref of opts.images) {
|
|
3198
|
+
for (const ref of opts.items) {
|
|
2911
3199
|
if (staged.length >= budget) {
|
|
2912
|
-
skipped += opts.
|
|
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 (
|
|
3206
|
+
if (kind === null) {
|
|
2917
3207
|
skipped++;
|
|
2918
|
-
lines.push("[
|
|
2919
|
-
i++;
|
|
3208
|
+
lines.push("[attachment skipped: \"" + label + "\" unsupported type " + ref.mediaType + "]");
|
|
2920
3209
|
continue;
|
|
2921
3210
|
}
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
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("[
|
|
2931
|
-
|
|
3221
|
+
lines.push("[" + kind + " unavailable: \"" + label + "\" could not be read from attachment storage]");
|
|
3222
|
+
continue;
|
|
3223
|
+
}
|
|
3224
|
+
if (data.byteLength > cap) {
|
|
3225
|
+
skipped++;
|
|
3226
|
+
lines.push("[" + kind + " skipped: \"" + label + "\" exceeds " + capLabel + "]");
|
|
2932
3227
|
continue;
|
|
2933
3228
|
}
|
|
2934
|
-
const path = stagedPath(opts.dir, opts.key, ref.attachmentId,
|
|
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:
|
|
2940
|
-
height:
|
|
2941
|
-
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 + " (" +
|
|
2946
|
-
|
|
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
|
-
|
|
3102
|
-
|
|
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 === "
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
|
|
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
|
-
|
|
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 `}`})`;
|
|
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;
|
|
@@ -3920,6 +4298,29 @@ function buildToolCallBlock(input) {
|
|
|
3920
4298
|
}
|
|
3921
4299
|
//#endregion
|
|
3922
4300
|
//#region src/provider/mapper/event-mapper.ts
|
|
4301
|
+
function formatRunningToolFallback(toolName, rawArgs) {
|
|
4302
|
+
const unwrapped = unwrapMcpTool(toolName, rawArgs);
|
|
4303
|
+
const a = unwrapped.input;
|
|
4304
|
+
const str = (...keys) => {
|
|
4305
|
+
for (const k of keys) {
|
|
4306
|
+
const v = a[k];
|
|
4307
|
+
if (typeof v === "string" && v.trim() !== "") return v.trim();
|
|
4308
|
+
if (typeof v === "number" && Number.isFinite(v)) return String(v);
|
|
4309
|
+
}
|
|
4310
|
+
return "";
|
|
4311
|
+
};
|
|
4312
|
+
if (unwrapped.tool === "schedule") {
|
|
4313
|
+
const cron = str("CronExpression", "cron_expression");
|
|
4314
|
+
const dur = str("DurationSeconds", "duration_seconds");
|
|
4315
|
+
const prompt = str("Prompt", "prompt");
|
|
4316
|
+
const timing = cron ? `cron ${cron}` : dur ? `${dur}s timer` : "schedule";
|
|
4317
|
+
return prompt ? `Schedule active (${timing}): ${prompt}` : `Schedule active (${timing})`;
|
|
4318
|
+
}
|
|
4319
|
+
const cmd = str("CommandLine", "command_line", "command", "cmd");
|
|
4320
|
+
const taskId = str("TaskId", "taskId", "task_id", "bgTaskId");
|
|
4321
|
+
if (cmd !== "") return `Tool is running as a background task${taskId ? ` (${taskId})` : ""}: ${cmd}`;
|
|
4322
|
+
return taskId ? `Tool is running as a background task (${taskId})` : "Tool is running as a background task";
|
|
4323
|
+
}
|
|
3923
4324
|
var EventMapper = class {
|
|
3924
4325
|
opts;
|
|
3925
4326
|
blockIdx = 0;
|
|
@@ -3943,6 +4344,7 @@ var EventMapper = class {
|
|
|
3943
4344
|
sawTextStep;
|
|
3944
4345
|
finished = false;
|
|
3945
4346
|
totalTextOutput = "";
|
|
4347
|
+
pendingEmbedFrag = "";
|
|
3946
4348
|
toolCallStates = /* @__PURE__ */ new Map();
|
|
3947
4349
|
emittedCompactionNotice = false;
|
|
3948
4350
|
constructor(opts) {
|
|
@@ -3953,8 +4355,21 @@ var EventMapper = class {
|
|
|
3953
4355
|
get isFinished() {
|
|
3954
4356
|
return this.finished;
|
|
3955
4357
|
}
|
|
4358
|
+
formatAssistantText(text) {
|
|
4359
|
+
const withEmbeds = rewriteAgentEmbeds(text, this.opts.mediaBaseUrl ? this.opts.mediaBaseUrl.replace(/\/media\/?$/, "/embed") : void 0);
|
|
4360
|
+
return normalizeFileLinks(this.opts.mediaBaseUrl ? rewriteImageMarkdown(withEmbeds, this.opts.mediaBaseUrl) : withEmbeds);
|
|
4361
|
+
}
|
|
4362
|
+
*flushPendingEmbed() {
|
|
4363
|
+
if (this.pendingEmbedFrag === "") return;
|
|
4364
|
+
const raw = this.pendingEmbedFrag;
|
|
4365
|
+
this.pendingEmbedFrag = "";
|
|
4366
|
+
yield* this.ensureBlock("text");
|
|
4367
|
+
const d = this.appendDelta(this.formatAssistantText(raw));
|
|
4368
|
+
if (d) yield d;
|
|
4369
|
+
}
|
|
3956
4370
|
*ensureBlock(type) {
|
|
3957
4371
|
if (this.openType === type) return;
|
|
4372
|
+
if (this.openType === "text" && type !== "text") yield* this.flushPendingEmbed();
|
|
3958
4373
|
const close = this.closeOpen();
|
|
3959
4374
|
if (close) yield close;
|
|
3960
4375
|
this.openType = type;
|
|
@@ -4088,13 +4503,18 @@ var EventMapper = class {
|
|
|
4088
4503
|
}
|
|
4089
4504
|
this.sawTextStep = true;
|
|
4090
4505
|
yield* this.ensureBlock("text");
|
|
4091
|
-
let d;
|
|
4092
|
-
const processedText = normalizeFileLinks(this.opts.mediaBaseUrl ? rewriteImageMarkdown(ev.text, this.opts.mediaBaseUrl) : ev.text);
|
|
4506
|
+
let d = null;
|
|
4093
4507
|
if (ev.fragment === true) {
|
|
4094
|
-
const
|
|
4095
|
-
this.
|
|
4096
|
-
|
|
4508
|
+
const { ready, pending } = splitPendingEmbedFragment(this.pendingEmbedFrag + ev.text);
|
|
4509
|
+
this.pendingEmbedFrag = pending;
|
|
4510
|
+
if (ready !== "") {
|
|
4511
|
+
const processedText = this.formatAssistantText(ready);
|
|
4512
|
+
const acc = (this.emittedByKey.get(ev.stepKey) ?? "") + processedText;
|
|
4513
|
+
this.emittedByKey.set(ev.stepKey, acc);
|
|
4514
|
+
d = this.appendDelta(processedText);
|
|
4515
|
+
}
|
|
4097
4516
|
} else {
|
|
4517
|
+
const processedText = this.formatAssistantText(ev.text);
|
|
4098
4518
|
const delta = suffixDelta(this.emittedByKey.get(ev.stepKey) ?? "", processedText);
|
|
4099
4519
|
this.emittedByKey.set(ev.stepKey, processedText);
|
|
4100
4520
|
d = this.appendDelta(delta);
|
|
@@ -4143,11 +4563,12 @@ var EventMapper = class {
|
|
|
4143
4563
|
}
|
|
4144
4564
|
return;
|
|
4145
4565
|
}
|
|
4146
|
-
if (ev.state === "RUNNING" && ev.tool.output === void 0) ev.tool.output = ev.text !== "" ? ev.text :
|
|
4566
|
+
if (ev.state === "RUNNING" && (ev.tool.output === void 0 || ev.tool.output === "")) ev.tool.output = ev.text !== "" ? ev.text : formatRunningToolFallback(ev.tool.name, ev.tool.args);
|
|
4147
4567
|
if (this.announcedTools.has(ev.stepKey)) return;
|
|
4148
4568
|
this.announcedTools.add(ev.stepKey);
|
|
4149
4569
|
if (!this.opts.cutOnTool) return;
|
|
4150
4570
|
yield* this.flushBannerOnlyThoughts();
|
|
4571
|
+
yield* this.flushPendingEmbed();
|
|
4151
4572
|
const close = this.closeOpen();
|
|
4152
4573
|
if (close) yield close;
|
|
4153
4574
|
const block = buildToolCallBlock({
|
|
@@ -4170,7 +4591,7 @@ var EventMapper = class {
|
|
|
4170
4591
|
}
|
|
4171
4592
|
if (!ev.ok) {
|
|
4172
4593
|
if (ev.response === "") return;
|
|
4173
|
-
const respText =
|
|
4594
|
+
const respText = this.formatAssistantText(ev.response);
|
|
4174
4595
|
if (!this.sawTextStep) {
|
|
4175
4596
|
yield* this.ensureBlock("text");
|
|
4176
4597
|
const d = this.appendDelta(respText);
|
|
@@ -4183,10 +4604,11 @@ var EventMapper = class {
|
|
|
4183
4604
|
}
|
|
4184
4605
|
} else if (!this.sawTextStep && ev.response !== "") {
|
|
4185
4606
|
yield* this.ensureBlock("text");
|
|
4186
|
-
const d = this.appendDelta(
|
|
4607
|
+
const d = this.appendDelta(this.formatAssistantText(ev.response));
|
|
4187
4608
|
if (d) yield d;
|
|
4188
4609
|
}
|
|
4189
4610
|
yield* this.flushBannerOnlyThoughts();
|
|
4611
|
+
yield* this.flushPendingEmbed();
|
|
4190
4612
|
const close = this.closeOpen();
|
|
4191
4613
|
if (close) yield close;
|
|
4192
4614
|
yield {
|
|
@@ -4232,6 +4654,7 @@ var EventMapper = class {
|
|
|
4232
4654
|
*/
|
|
4233
4655
|
*emitFailure(kind, code, message, retryAfterMs) {
|
|
4234
4656
|
if (this.finished) return;
|
|
4657
|
+
yield* this.flushPendingEmbed();
|
|
4235
4658
|
const close = this.closeOpen();
|
|
4236
4659
|
if (close) yield close;
|
|
4237
4660
|
const tracked = this.opts.usage?.finalUsage({});
|
|
@@ -5366,10 +5789,10 @@ function writeFileAtomicSync(file, data, mode = 384) {
|
|
|
5366
5789
|
const tmp = atomicTmpPath(file);
|
|
5367
5790
|
try {
|
|
5368
5791
|
mkdirSync(dirname(file), { recursive: true });
|
|
5369
|
-
writeFileSync(tmp, data, {
|
|
5792
|
+
writeFileSync(tmp, data, typeof data === "string" ? {
|
|
5370
5793
|
encoding: "utf8",
|
|
5371
5794
|
mode
|
|
5372
|
-
});
|
|
5795
|
+
} : { mode });
|
|
5373
5796
|
renameSync(tmp, file);
|
|
5374
5797
|
} catch (err) {
|
|
5375
5798
|
try {
|
|
@@ -5988,7 +6411,7 @@ var ModelCatalog = class ModelCatalog {
|
|
|
5988
6411
|
//#endregion
|
|
5989
6412
|
//#region src/domain/models/quota-catalog.ts
|
|
5990
6413
|
/** Families whose quota rows describe models the picker may offer. */
|
|
5991
|
-
const QUOTA_FAMILIES = [
|
|
6414
|
+
const QUOTA_FAMILIES$1 = [
|
|
5992
6415
|
"google",
|
|
5993
6416
|
"argon",
|
|
5994
6417
|
"anthropic",
|
|
@@ -6006,7 +6429,7 @@ function quotaModelsForAccount(account) {
|
|
|
6006
6429
|
if (!quotas) return [];
|
|
6007
6430
|
const out = [];
|
|
6008
6431
|
const seen = /* @__PURE__ */ new Set();
|
|
6009
|
-
for (const family of QUOTA_FAMILIES) {
|
|
6432
|
+
for (const family of QUOTA_FAMILIES$1) {
|
|
6010
6433
|
const rows = quotas[family]?.models;
|
|
6011
6434
|
if (!Array.isArray(rows)) continue;
|
|
6012
6435
|
for (const row of rows) {
|
|
@@ -6636,22 +7059,28 @@ function mergeSentImageIds(existing, added, max = 64) {
|
|
|
6636
7059
|
//#region src/provider/account-selection.ts
|
|
6637
7060
|
/** Upper bound on the self-heal refresh so a slow network cannot stall a turn. */
|
|
6638
7061
|
const MODEL_HEAL_TIMEOUT_MS = 2e4;
|
|
6639
|
-
/** Session affinity: reuse the account this session last ran
|
|
7062
|
+
/** Session affinity: reuse the account this session last ran for THIS family, if eligible and not superseded by a manual switch. */
|
|
6640
7063
|
function stickyAccount(deps, family, sessionKey, model) {
|
|
6641
7064
|
const pool = deps.pool;
|
|
6642
7065
|
if (pool === void 0 || sessionKey === "") return void 0;
|
|
6643
|
-
const
|
|
7066
|
+
const poolData = pool.getPoolData();
|
|
7067
|
+
const familyPinAt = Math.max(poolData.manualPinAt ?? 0, poolData.manualPinAtByFamily?.[family] ?? 0);
|
|
6644
7068
|
const prefix = `${sessionKey}:`;
|
|
6645
7069
|
let mostRecent;
|
|
6646
7070
|
let latestUpdated = -1;
|
|
6647
7071
|
for (const [k, b] of Object.entries(deps.store.all())) {
|
|
6648
|
-
if (!k.startsWith(prefix)
|
|
6649
|
-
if (manualPinAt > 0 && b.updatedAt < manualPinAt) continue;
|
|
7072
|
+
if (!k.startsWith(prefix)) continue;
|
|
6650
7073
|
const boundAcc = pool.getAccount(k.slice(prefix.length));
|
|
6651
|
-
if (boundAcc
|
|
7074
|
+
if (boundAcc === void 0) {
|
|
7075
|
+
deps.store.delete(k);
|
|
7076
|
+
continue;
|
|
7077
|
+
}
|
|
7078
|
+
if (b.model && b.model.trim() !== "" && modelFamilyOf(b.model) !== family) continue;
|
|
7079
|
+
if (familyPinAt > 0 && b.updatedAt < familyPinAt) continue;
|
|
7080
|
+
if (b.updatedAt > latestUpdated) {
|
|
6652
7081
|
mostRecent = boundAcc;
|
|
6653
7082
|
latestUpdated = b.updatedAt;
|
|
6654
|
-
}
|
|
7083
|
+
}
|
|
6655
7084
|
}
|
|
6656
7085
|
return mostRecent !== void 0 && (typeof pool.isAccountEligibleForModel === "function" ? pool.isAccountEligibleForModel(mostRecent, family, model) : pool.isAccountEligible(mostRecent, family)) ? mostRecent : void 0;
|
|
6657
7086
|
}
|
|
@@ -6747,7 +7176,7 @@ async function selectSessionAccount(input) {
|
|
|
6747
7176
|
if (pool !== void 0 && !isAux && sessionKey !== "" && process.platform === "win32" && cfg.parallelSameAccount) account = pool.selectAccount(family, activeModel) ?? void 0;
|
|
6748
7177
|
if (account === void 0 && pool !== void 0 && !isAux && sessionKey !== "") account = stickyAccount(deps, family, sessionKey, activeModel);
|
|
6749
7178
|
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) {
|
|
7179
|
+
if (account !== void 0 && pool !== void 0 && (family === "google" || !pool.getPoolData().lastActiveAccountId) && pool.getPoolData().lastActiveAccountId !== account.id) {
|
|
6751
7180
|
if (typeof pool.markAccountActive === "function") pool.markAccountActive(account.id);
|
|
6752
7181
|
else pool.setActiveAccount(account.id, family);
|
|
6753
7182
|
}
|
|
@@ -6862,7 +7291,7 @@ async function buildPromptPlan(input) {
|
|
|
6862
7291
|
deps
|
|
6863
7292
|
});
|
|
6864
7293
|
prompt = staged.prompt;
|
|
6865
|
-
if (staged.stagedDir !== null) stagedDirs
|
|
7294
|
+
if (staged.stagedDir !== null && !stagedDirs.includes(staged.stagedDir)) stagedDirs.push(staged.stagedDir);
|
|
6866
7295
|
newlySentImageIds.push(...staged.stagedIds);
|
|
6867
7296
|
if (prompt.trim() === "") throw new LlmError("request carries no user text or images to forward to agy", Err.AGY_ERROR);
|
|
6868
7297
|
} else if (prompt.trim() === "") throw new LlmError("request carries no user text to forward to agy", Err.AGY_ERROR);
|
|
@@ -7076,23 +7505,32 @@ async function stagePromptImages(input) {
|
|
|
7076
7505
|
const { cfg, ctx, messages, trailingUser, binding, deps } = input;
|
|
7077
7506
|
let prompt = input.prompt;
|
|
7078
7507
|
const sentIds = binding?.sentImageIds ?? [];
|
|
7079
|
-
const
|
|
7508
|
+
const mediaRefs = collectUnsentMediaRefs(messages, trailingUser, binding !== void 0 ? binding.lastMessageCount : 0, sentIds);
|
|
7080
7509
|
const readImage = deps.readImage;
|
|
7081
|
-
if (
|
|
7510
|
+
if (mediaRefs.length === 0) return {
|
|
7511
|
+
prompt,
|
|
7512
|
+
stagedDir: null,
|
|
7513
|
+
stagedIds: []
|
|
7514
|
+
};
|
|
7515
|
+
if (!readImage && mediaRefs.every((r) => r.data === void 0 && r.path === void 0)) return {
|
|
7082
7516
|
prompt,
|
|
7083
7517
|
stagedDir: null,
|
|
7084
7518
|
stagedIds: []
|
|
7085
7519
|
};
|
|
7086
7520
|
const dir = cfg.mediaDir !== "" ? cfg.mediaDir : defaultMediaDir(stateDir());
|
|
7087
|
-
const res = await
|
|
7521
|
+
const res = await stageMedia({
|
|
7088
7522
|
dir,
|
|
7089
7523
|
key: ctx.sessionKey !== "" ? ctx.sessionKey.replace(/[^a-zA-Z0-9_-]+/g, "_") : "anon",
|
|
7090
|
-
|
|
7091
|
-
readImage,
|
|
7092
|
-
|
|
7093
|
-
|
|
7524
|
+
items: mediaRefs,
|
|
7525
|
+
...readImage ? { readMedia: (ref) => readImage(ref) } : {},
|
|
7526
|
+
maxItems: cfg.mediaMaxImages,
|
|
7527
|
+
maxImageBytes: cfg.mediaMaxBytes,
|
|
7528
|
+
maxFileBytes: cfg.mediaMaxFileBytes
|
|
7094
7529
|
});
|
|
7095
|
-
if (res.promptSuffix !== "")
|
|
7530
|
+
if (res.promptSuffix !== "") {
|
|
7531
|
+
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.]";
|
|
7532
|
+
prompt = prompt === "" ? res.promptSuffix + "\n\n" + onlyAttachmentsHint : prompt + "\n\n" + res.promptSuffix;
|
|
7533
|
+
}
|
|
7096
7534
|
return {
|
|
7097
7535
|
prompt,
|
|
7098
7536
|
stagedDir: res.staged.length > 0 ? dir : null,
|
|
@@ -7853,6 +8291,23 @@ function defaultPoolDir(home) {
|
|
|
7853
8291
|
/** Proactive rotation thresholds: bench accounts at or below these remaining fractions until reset. */
|
|
7854
8292
|
const LOW_QUOTA_5H = .1;
|
|
7855
8293
|
const LOW_QUOTA_WEEKLY = .05;
|
|
8294
|
+
/** Ordered quota families tracked on an account card. */
|
|
8295
|
+
const QUOTA_FAMILIES = [
|
|
8296
|
+
"google",
|
|
8297
|
+
"argon",
|
|
8298
|
+
"anthropic",
|
|
8299
|
+
"openai"
|
|
8300
|
+
];
|
|
8301
|
+
/** Normalize user/CLI/HTTP model-family aliases onto canonical `ModelFamily` keys. */
|
|
8302
|
+
function normalizeModelFamily(raw) {
|
|
8303
|
+
if (!raw) return void 0;
|
|
8304
|
+
const clean = raw.trim().toLowerCase();
|
|
8305
|
+
if (clean === "google" || clean === "gemini") return "google";
|
|
8306
|
+
if (clean === "argon") return "argon";
|
|
8307
|
+
if (clean === "anthropic" || clean === "claude") return "anthropic";
|
|
8308
|
+
if (clean === "openai" || clean === "gpt" || clean === "gpt-oss") return "openai";
|
|
8309
|
+
if (clean === "unknown") return "unknown";
|
|
8310
|
+
}
|
|
7856
8311
|
function isWindowBenched(fraction, resetTime, threshold, now) {
|
|
7857
8312
|
if (typeof fraction !== "number" || fraction > threshold) return false;
|
|
7858
8313
|
if (!resetTime) return true;
|
|
@@ -8048,6 +8503,21 @@ function orderByExpiry(accounts, candidates, family, fromId, now) {
|
|
|
8048
8503
|
return da !== db ? da - db : a.index - b.index;
|
|
8049
8504
|
}).map((e) => e.acc);
|
|
8050
8505
|
}
|
|
8506
|
+
/**
|
|
8507
|
+
* Pure, side-effect-free lookup of the active eligible account ID for a given
|
|
8508
|
+
* family. Honors a still-eligible family pin first, then falls back to the
|
|
8509
|
+
* first eligible candidate in rotation order without mutating pool state.
|
|
8510
|
+
*/
|
|
8511
|
+
function resolveEligibleActiveAccountId(accounts, activeAccountIds, family, pool, now = Date.now(), model) {
|
|
8512
|
+
const pinnedId = activeAccountIds?.[family];
|
|
8513
|
+
if (pinnedId) {
|
|
8514
|
+
const pinned = accounts.find((a) => a.id === pinnedId);
|
|
8515
|
+
if (pinned && isAccountEligible(pinned, family, now, pool, model)) return pinned.id;
|
|
8516
|
+
}
|
|
8517
|
+
const candidates = accounts.filter((acc) => isAccountEligible(acc, family, now, pool, model));
|
|
8518
|
+
if (candidates.length === 0) return void 0;
|
|
8519
|
+
return orderByExpiry(accounts, candidates, family, pinnedId, now)[0]?.id;
|
|
8520
|
+
}
|
|
8051
8521
|
//#endregion
|
|
8052
8522
|
//#region src/domain/accounts/admin.ts
|
|
8053
8523
|
var PoolAdmin = class {
|
|
@@ -8213,21 +8683,20 @@ var PoolAdmin = class {
|
|
|
8213
8683
|
this.deps.persist();
|
|
8214
8684
|
}
|
|
8215
8685
|
/**
|
|
8216
|
-
* Manually pin the active slot for one family (console "
|
|
8217
|
-
*
|
|
8218
|
-
*
|
|
8219
|
-
* eligibility, so pinning an ineligible slot simply does not stick.
|
|
8686
|
+
* Manually pin the active slot for one family (console per-family "设为当前").
|
|
8687
|
+
* Strictly family-scoped: pinning one family never mutates or clears another
|
|
8688
|
+
* family's active slot or session stickiness.
|
|
8220
8689
|
*/
|
|
8221
8690
|
setActiveAccount(id, family = "google") {
|
|
8222
8691
|
const data = this.deps.getData();
|
|
8223
8692
|
const acc = this.account(id);
|
|
8224
|
-
|
|
8693
|
+
const now = Date.now();
|
|
8694
|
+
if (!acc || !isAccountEligible(acc, family, now, this.deps.pool)) return false;
|
|
8225
8695
|
if (!data.activeAccountIds) data.activeAccountIds = {};
|
|
8226
8696
|
data.activeAccountIds[family] = id;
|
|
8227
|
-
data.
|
|
8228
|
-
data.
|
|
8229
|
-
if (!
|
|
8230
|
-
else data.activeAccountIds.argon = id;
|
|
8697
|
+
if (!data.manualPinAtByFamily) data.manualPinAtByFamily = {};
|
|
8698
|
+
data.manualPinAtByFamily[family] = now;
|
|
8699
|
+
if (family === "google" || !data.lastActiveAccountId) data.lastActiveAccountId = id;
|
|
8231
8700
|
this.deps.persist();
|
|
8232
8701
|
return true;
|
|
8233
8702
|
}
|
|
@@ -8329,12 +8798,12 @@ var PoolAdmin = class {
|
|
|
8329
8798
|
data.activeAccountIds = {
|
|
8330
8799
|
google: id,
|
|
8331
8800
|
anthropic: id,
|
|
8332
|
-
openai: id
|
|
8333
|
-
...accountHasArgon(acc, this.deps.pool) ? { argon: id } : {}
|
|
8801
|
+
openai: id
|
|
8334
8802
|
};
|
|
8335
8803
|
data.lastActiveAccountId = id;
|
|
8336
8804
|
}
|
|
8337
8805
|
data.manualPinAt = Date.now();
|
|
8806
|
+
data.manualPinAtByFamily = {};
|
|
8338
8807
|
this.deps.persist();
|
|
8339
8808
|
return true;
|
|
8340
8809
|
}
|
|
@@ -8354,6 +8823,7 @@ var PoolAdmin = class {
|
|
|
8354
8823
|
data.activeAccountIds = {};
|
|
8355
8824
|
data.lastActiveAccountId = void 0;
|
|
8356
8825
|
data.manualPinAt = Date.now();
|
|
8826
|
+
data.manualPinAtByFamily = {};
|
|
8357
8827
|
this.deps.persist();
|
|
8358
8828
|
return true;
|
|
8359
8829
|
}
|
|
@@ -8383,7 +8853,8 @@ var PoolAdmin = class {
|
|
|
8383
8853
|
reason,
|
|
8384
8854
|
consecutiveFailures: failures
|
|
8385
8855
|
};
|
|
8386
|
-
|
|
8856
|
+
const famPinned = data.activeAccountIds?.[family];
|
|
8857
|
+
if (famPinned === id || famPinned === void 0 && data.lastActiveAccountId === id) this.advanceAccount(id, family);
|
|
8387
8858
|
this.deps.persist();
|
|
8388
8859
|
}
|
|
8389
8860
|
/**
|
|
@@ -8417,15 +8888,15 @@ var PoolAdmin = class {
|
|
|
8417
8888
|
const next = orderByExpiry(data.accounts, candidates, family, fromId, Date.now())[0];
|
|
8418
8889
|
if (!data.activeAccountIds) data.activeAccountIds = {};
|
|
8419
8890
|
data.activeAccountIds[family] = next.id;
|
|
8420
|
-
data.lastActiveAccountId = next.id;
|
|
8891
|
+
if (family === "google" || !data.lastActiveAccountId) data.lastActiveAccountId = next.id;
|
|
8421
8892
|
this.deps.persist();
|
|
8422
8893
|
return next.id;
|
|
8423
8894
|
}
|
|
8424
8895
|
/**
|
|
8425
|
-
* Returns the currently active and healthy account ID
|
|
8426
|
-
*
|
|
8427
|
-
*
|
|
8428
|
-
*
|
|
8896
|
+
* Returns the currently active and healthy account ID for `family`.
|
|
8897
|
+
* Checks this family's active pointer first; only checks `lastActiveAccountId`
|
|
8898
|
+
* when this family has no pointer yet, otherwise selects the next eligible
|
|
8899
|
+
* candidate strictly within `family`.
|
|
8429
8900
|
*/
|
|
8430
8901
|
getActiveAccountId(family = "google", model) {
|
|
8431
8902
|
const data = this.deps.getData();
|
|
@@ -8435,7 +8906,7 @@ var PoolAdmin = class {
|
|
|
8435
8906
|
const pinned = data.accounts.find((a) => a.id === pinnedId);
|
|
8436
8907
|
if (pinned && isAccountEligible(pinned, family, now, this.deps.pool, model)) return pinned.id;
|
|
8437
8908
|
}
|
|
8438
|
-
if (data.lastActiveAccountId) {
|
|
8909
|
+
if (pinnedId === void 0 && data.lastActiveAccountId) {
|
|
8439
8910
|
const active = data.accounts.find((a) => a.id === data.lastActiveAccountId);
|
|
8440
8911
|
if (active && isAccountEligible(active, family, now, this.deps.pool, model)) return active.id;
|
|
8441
8912
|
}
|
|
@@ -8745,6 +9216,152 @@ var PoolStore = class {
|
|
|
8745
9216
|
//#endregion
|
|
8746
9217
|
//#region src/host/wincred.ts
|
|
8747
9218
|
const IS_WIN = process.platform === "win32";
|
|
9219
|
+
const WIN_CRED_CS_SRC = `using System;
|
|
9220
|
+
using System.Runtime.InteropServices;
|
|
9221
|
+
|
|
9222
|
+
public static class WinCredCli {
|
|
9223
|
+
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
9224
|
+
public static extern bool CredWrite([In] ref CREDENTIAL userCredential, [In] uint flags);
|
|
9225
|
+
|
|
9226
|
+
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
9227
|
+
public static extern bool CredRead(string target, int type, int flags, out IntPtr credential);
|
|
9228
|
+
|
|
9229
|
+
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
9230
|
+
public static extern bool CredDelete(string target, int type, int flags);
|
|
9231
|
+
|
|
9232
|
+
[DllImport("advapi32.dll", SetLastError = true)]
|
|
9233
|
+
public static extern void CredFree(IntPtr cred);
|
|
9234
|
+
|
|
9235
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
9236
|
+
public struct CREDENTIAL {
|
|
9237
|
+
public int Flags;
|
|
9238
|
+
public int Type;
|
|
9239
|
+
public string TargetName;
|
|
9240
|
+
public string Comment;
|
|
9241
|
+
public long LastWritten;
|
|
9242
|
+
public int CredentialBlobSize;
|
|
9243
|
+
public IntPtr CredentialBlob;
|
|
9244
|
+
public int Persist;
|
|
9245
|
+
public int AttributeCount;
|
|
9246
|
+
public IntPtr Attributes;
|
|
9247
|
+
public string TargetAlias;
|
|
9248
|
+
public string UserName;
|
|
9249
|
+
}
|
|
9250
|
+
|
|
9251
|
+
public static int Main(string[] args) {
|
|
9252
|
+
if (args.Length < 2) return 2;
|
|
9253
|
+
string action = args[0];
|
|
9254
|
+
string target = args[1];
|
|
9255
|
+
string user = args.Length > 2 ? args[2] : "antigravity";
|
|
9256
|
+
if (action == "read") {
|
|
9257
|
+
IntPtr p;
|
|
9258
|
+
if (!CredRead(target, 1, 0, out p)) return 0;
|
|
9259
|
+
try {
|
|
9260
|
+
CREDENTIAL c = (CREDENTIAL)Marshal.PtrToStructure(p, typeof(CREDENTIAL));
|
|
9261
|
+
byte[] b = new byte[c.CredentialBlobSize];
|
|
9262
|
+
if (c.CredentialBlobSize > 0 && c.CredentialBlob != IntPtr.Zero) {
|
|
9263
|
+
Marshal.Copy(c.CredentialBlob, b, 0, c.CredentialBlobSize);
|
|
9264
|
+
}
|
|
9265
|
+
Console.Out.Write(Convert.ToBase64String(b));
|
|
9266
|
+
} finally {
|
|
9267
|
+
CredFree(p);
|
|
9268
|
+
}
|
|
9269
|
+
return 0;
|
|
9270
|
+
}
|
|
9271
|
+
if (action == "write") {
|
|
9272
|
+
string payload = Console.In.ReadToEnd().Trim();
|
|
9273
|
+
byte[] secret = Convert.FromBase64String(payload);
|
|
9274
|
+
CREDENTIAL c = new CREDENTIAL();
|
|
9275
|
+
c.Type = 1;
|
|
9276
|
+
c.TargetName = target;
|
|
9277
|
+
c.UserName = user;
|
|
9278
|
+
c.Persist = 2;
|
|
9279
|
+
c.CredentialBlobSize = secret.Length;
|
|
9280
|
+
IntPtr p = Marshal.AllocHGlobal(secret.Length);
|
|
9281
|
+
Marshal.Copy(secret, 0, p, secret.Length);
|
|
9282
|
+
c.CredentialBlob = p;
|
|
9283
|
+
bool ok;
|
|
9284
|
+
try {
|
|
9285
|
+
ok = CredWrite(ref c, 0);
|
|
9286
|
+
} finally {
|
|
9287
|
+
Marshal.FreeHGlobal(p);
|
|
9288
|
+
}
|
|
9289
|
+
Console.Out.Write(ok ? "True" : "False");
|
|
9290
|
+
return ok ? 0 : 1;
|
|
9291
|
+
}
|
|
9292
|
+
if (action == "delete") {
|
|
9293
|
+
bool ok = CredDelete(target, 1, 0);
|
|
9294
|
+
Console.Out.Write(ok ? "True" : "False");
|
|
9295
|
+
return 0;
|
|
9296
|
+
}
|
|
9297
|
+
return 2;
|
|
9298
|
+
}
|
|
9299
|
+
}
|
|
9300
|
+
`;
|
|
9301
|
+
const WIN_CRED_HASH = createHash("sha256").update(WIN_CRED_CS_SRC).digest("hex").slice(0, 8);
|
|
9302
|
+
let helperDisabled = false;
|
|
9303
|
+
let cachedHelperPath = null;
|
|
9304
|
+
function findCscExe() {
|
|
9305
|
+
const windir = process.env.WINDIR || process.env.SystemRoot || "C:\\Windows";
|
|
9306
|
+
const candidates = [join(windir, "Microsoft.NET", "Framework64", "v4.0.30319", "csc.exe"), join(windir, "Microsoft.NET", "Framework", "v4.0.30319", "csc.exe")];
|
|
9307
|
+
for (const cand of candidates) if (existsSync(cand)) return cand;
|
|
9308
|
+
return null;
|
|
9309
|
+
}
|
|
9310
|
+
/**
|
|
9311
|
+
* Compile and cache a tiny standalone .NET Win32 helper once per source hash so
|
|
9312
|
+
* Credential Manager reads/writes take ~15ms instead of ~1.5-3s per powershell.exe
|
|
9313
|
+
* Add-Type cold compilation. Falls back cleanly to PowerShell if csc.exe is absent.
|
|
9314
|
+
*/
|
|
9315
|
+
function ensureWinCredHelper() {
|
|
9316
|
+
if (!IS_WIN || helperDisabled) return null;
|
|
9317
|
+
if (cachedHelperPath && existsSync(cachedHelperPath)) return cachedHelperPath;
|
|
9318
|
+
const csc = findCscExe();
|
|
9319
|
+
if (!csc) {
|
|
9320
|
+
helperDisabled = true;
|
|
9321
|
+
return null;
|
|
9322
|
+
}
|
|
9323
|
+
const binDir = join(stateDir(), "bin");
|
|
9324
|
+
const finalExe = join(binDir, `wincred-v1-${WIN_CRED_HASH}.exe`);
|
|
9325
|
+
if (existsSync(finalExe)) {
|
|
9326
|
+
cachedHelperPath = finalExe;
|
|
9327
|
+
return finalExe;
|
|
9328
|
+
}
|
|
9329
|
+
const stamp = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
|
|
9330
|
+
const tmpCs = join(binDir, `wincred-${stamp}.cs`);
|
|
9331
|
+
const tmpExe = join(binDir, `wincred-${stamp}.exe`);
|
|
9332
|
+
try {
|
|
9333
|
+
mkdirSync(binDir, { recursive: true });
|
|
9334
|
+
writeFileSync(tmpCs, WIN_CRED_CS_SRC, "utf8");
|
|
9335
|
+
execFileSync(csc, [
|
|
9336
|
+
"/nologo",
|
|
9337
|
+
"/optimize+",
|
|
9338
|
+
"/target:exe",
|
|
9339
|
+
`/out:${tmpExe}`,
|
|
9340
|
+
tmpCs
|
|
9341
|
+
], {
|
|
9342
|
+
timeout: 2e4,
|
|
9343
|
+
windowsHide: true,
|
|
9344
|
+
stdio: "ignore"
|
|
9345
|
+
});
|
|
9346
|
+
try {
|
|
9347
|
+
renameSync(tmpExe, finalExe);
|
|
9348
|
+
} catch {
|
|
9349
|
+
if (!existsSync(finalExe)) throw new Error("failed to finalize wincred helper");
|
|
9350
|
+
}
|
|
9351
|
+
cachedHelperPath = finalExe;
|
|
9352
|
+
return finalExe;
|
|
9353
|
+
} catch {
|
|
9354
|
+
helperDisabled = true;
|
|
9355
|
+
return null;
|
|
9356
|
+
} finally {
|
|
9357
|
+
try {
|
|
9358
|
+
rmSync(tmpCs, { force: true });
|
|
9359
|
+
} catch {}
|
|
9360
|
+
try {
|
|
9361
|
+
rmSync(tmpExe, { force: true });
|
|
9362
|
+
} catch {}
|
|
9363
|
+
}
|
|
9364
|
+
}
|
|
8748
9365
|
const WIN_CRED_SCRIPT = `
|
|
8749
9366
|
param($target, $user, $action, $payload)
|
|
8750
9367
|
|
|
@@ -8829,8 +9446,29 @@ if ($action -eq "write") {
|
|
|
8829
9446
|
[Console]::Out.Write($ok)
|
|
8830
9447
|
}
|
|
8831
9448
|
`;
|
|
8832
|
-
/** Execute an action against Windows Credential Manager. */
|
|
8833
|
-
function
|
|
9449
|
+
/** Execute an action against Windows Credential Manager (fast cached .exe with PowerShell fallback). */
|
|
9450
|
+
function runWinCred(target, user, action, payload = "") {
|
|
9451
|
+
const timeout = action === "write" ? 3e4 : 8e3;
|
|
9452
|
+
const helper = ensureWinCredHelper();
|
|
9453
|
+
if (helper) try {
|
|
9454
|
+
return execFileSync(helper, action === "write" ? [
|
|
9455
|
+
action,
|
|
9456
|
+
target,
|
|
9457
|
+
user
|
|
9458
|
+
] : [action, target], {
|
|
9459
|
+
encoding: "utf8",
|
|
9460
|
+
timeout,
|
|
9461
|
+
windowsHide: true,
|
|
9462
|
+
input: action === "write" ? payload : void 0,
|
|
9463
|
+
stdio: [
|
|
9464
|
+
action === "write" ? "pipe" : "ignore",
|
|
9465
|
+
"pipe",
|
|
9466
|
+
"ignore"
|
|
9467
|
+
]
|
|
9468
|
+
}).trim();
|
|
9469
|
+
} catch {
|
|
9470
|
+
helperDisabled = true;
|
|
9471
|
+
}
|
|
8834
9472
|
return execFileSync("powershell.exe", [
|
|
8835
9473
|
"-NoProfile",
|
|
8836
9474
|
"-NonInteractive",
|
|
@@ -8844,7 +9482,7 @@ function runWinCredPs(target, user, action, payload = "") {
|
|
|
8844
9482
|
payload
|
|
8845
9483
|
], {
|
|
8846
9484
|
encoding: "utf8",
|
|
8847
|
-
timeout
|
|
9485
|
+
timeout,
|
|
8848
9486
|
windowsHide: true,
|
|
8849
9487
|
stdio: [
|
|
8850
9488
|
"ignore",
|
|
@@ -8860,7 +9498,7 @@ function readWindowsCredentialRaw(target = "gemini:antigravity", maxAgeMs = 2500
|
|
|
8860
9498
|
const now = Date.now();
|
|
8861
9499
|
if (cachedWinCredRaw && cachedWinCredRaw.target === target && now - cachedWinCredRaw.time < maxAgeMs) return cachedWinCredRaw.val;
|
|
8862
9500
|
try {
|
|
8863
|
-
const out =
|
|
9501
|
+
const out = runWinCred(target, "antigravity", "read");
|
|
8864
9502
|
const val = out ? Buffer.from(out, "base64").toString("utf8") : null;
|
|
8865
9503
|
cachedWinCredRaw = {
|
|
8866
9504
|
target,
|
|
@@ -8876,7 +9514,7 @@ function readWindowsCredentialRaw(target = "gemini:antigravity", maxAgeMs = 2500
|
|
|
8876
9514
|
function writeWindowsCredentialRaw(secret, target = "gemini:antigravity", userName = "antigravity") {
|
|
8877
9515
|
if (!IS_WIN) return false;
|
|
8878
9516
|
try {
|
|
8879
|
-
const ok =
|
|
9517
|
+
const ok = runWinCred(target, userName, "write", Buffer.from(secret, "utf8").toString("base64")).toLowerCase() === "true";
|
|
8880
9518
|
if (ok) cachedWinCredRaw = {
|
|
8881
9519
|
target,
|
|
8882
9520
|
val: secret,
|
|
@@ -9130,8 +9768,19 @@ var AccountPoolManager = class {
|
|
|
9130
9768
|
}
|
|
9131
9769
|
getPoolData(defaultProxy) {
|
|
9132
9770
|
const sysProxy = defaultProxy || detectSystemProxy();
|
|
9771
|
+
const now = Date.now();
|
|
9772
|
+
const resolvedActiveAccountIds = {};
|
|
9773
|
+
const source = {
|
|
9774
|
+
hasDedicatedGroup: (id, fam) => this.hasDedicatedGroup(id, fam),
|
|
9775
|
+
isModelSupported: (acc, model) => this.isModelSupported(acc, model)
|
|
9776
|
+
};
|
|
9777
|
+
for (const fam of QUOTA_FAMILIES) {
|
|
9778
|
+
const resolved = resolveEligibleActiveAccountId(this.data.accounts, this.data.activeAccountIds, fam, source, now);
|
|
9779
|
+
if (resolved) resolvedActiveAccountIds[fam] = resolved;
|
|
9780
|
+
}
|
|
9133
9781
|
return {
|
|
9134
9782
|
...this.data,
|
|
9783
|
+
resolvedActiveAccountIds,
|
|
9135
9784
|
activeAccountId: this.getActiveAccountId("google"),
|
|
9136
9785
|
...sysProxy ? { systemProxy: sysProxy } : {}
|
|
9137
9786
|
};
|
|
@@ -9304,8 +9953,12 @@ var AccountPoolManager = class {
|
|
|
9304
9953
|
if (isExhausted5h || isExhaustedWeekly) {
|
|
9305
9954
|
const clearedAt = acc.quotaGateClearedAt?.[famKey];
|
|
9306
9955
|
const gateCleared = clearedAt !== void 0 && (info.updatedAt ?? 0) <= clearedAt;
|
|
9307
|
-
|
|
9308
|
-
|
|
9956
|
+
const famPinned = this.data.activeAccountIds?.[famKey];
|
|
9957
|
+
const ownsFamily = famPinned === id || famPinned === void 0 && this.data.lastActiveAccountId === id;
|
|
9958
|
+
if (!gateCleared && ownsFamily) this.advanceAccount(id, famKey);
|
|
9959
|
+
const argonPinned = this.data.activeAccountIds?.argon;
|
|
9960
|
+
const ownsArgon = argonPinned === id || argonPinned === void 0 && this.data.lastActiveAccountId === id;
|
|
9961
|
+
if (!gateCleared && famKey === "google" && !acc.quotas?.argon && ownsArgon) this.advanceAccount(id, "argon");
|
|
9309
9962
|
}
|
|
9310
9963
|
}
|
|
9311
9964
|
this.persist();
|
|
@@ -9388,12 +10041,13 @@ var AccountPoolManager = class {
|
|
|
9388
10041
|
*/
|
|
9389
10042
|
clearCooldown(id, family, includeQuotaBench = false) {
|
|
9390
10043
|
const now = Date.now();
|
|
10044
|
+
const targetFamily = family ? normalizeModelFamily(family) ?? family : void 0;
|
|
9391
10045
|
const clearOne = (acc) => {
|
|
9392
10046
|
acc.cooldowns ??= {};
|
|
9393
|
-
if (
|
|
10047
|
+
if (targetFamily) delete acc.cooldowns[targetFamily];
|
|
9394
10048
|
else acc.cooldowns = {};
|
|
9395
10049
|
if (!includeQuotaBench) return;
|
|
9396
|
-
const families =
|
|
10050
|
+
const families = targetFamily ? [targetFamily] : Object.keys(acc.quotas ?? {});
|
|
9397
10051
|
if (families.length === 0) return;
|
|
9398
10052
|
acc.quotaGateClearedAt ??= {};
|
|
9399
10053
|
for (const fam of families) {
|
|
@@ -9423,7 +10077,7 @@ var AccountPoolManager = class {
|
|
|
9423
10077
|
const prevId = this.data.activeAccountIds?.[family];
|
|
9424
10078
|
if (!this.data.activeAccountIds) this.data.activeAccountIds = {};
|
|
9425
10079
|
this.data.activeAccountIds[family] = picked.id;
|
|
9426
|
-
this.data.lastActiveAccountId = picked.id;
|
|
10080
|
+
if (family === "google" || !this.data.lastActiveAccountId) this.data.lastActiveAccountId = picked.id;
|
|
9427
10081
|
this.persist();
|
|
9428
10082
|
if (prevId && prevId !== picked.id) this.onAccountSwitch?.(picked.id, family);
|
|
9429
10083
|
}
|
|
@@ -9433,7 +10087,7 @@ var AccountPoolManager = class {
|
|
|
9433
10087
|
if (activeId) {
|
|
9434
10088
|
const activeCandidate = candidates.find((a) => a.id === activeId);
|
|
9435
10089
|
if (activeCandidate) {
|
|
9436
|
-
if (this.data.lastActiveAccountId !== activeCandidate.id) {
|
|
10090
|
+
if ((family === "google" || !this.data.lastActiveAccountId) && this.data.lastActiveAccountId !== activeCandidate.id) {
|
|
9437
10091
|
this.data.lastActiveAccountId = activeCandidate.id;
|
|
9438
10092
|
this.persist();
|
|
9439
10093
|
}
|
|
@@ -9443,7 +10097,7 @@ var AccountPoolManager = class {
|
|
|
9443
10097
|
const nextAccount = this.orderByExpiry(candidates, family, activeId)[0];
|
|
9444
10098
|
if (!this.data.activeAccountIds) this.data.activeAccountIds = {};
|
|
9445
10099
|
this.data.activeAccountIds[family] = nextAccount.id;
|
|
9446
|
-
this.data.lastActiveAccountId = nextAccount.id;
|
|
10100
|
+
if (family === "google" || !this.data.lastActiveAccountId) this.data.lastActiveAccountId = nextAccount.id;
|
|
9447
10101
|
this.persist();
|
|
9448
10102
|
if (activeId && activeId !== nextAccount.id) this.onAccountSwitch?.(nextAccount.id, family);
|
|
9449
10103
|
return nextAccount;
|
|
@@ -22438,7 +23092,7 @@ var require_snapshot_utils = /* @__PURE__ */ __commonJSMin(((exports, module) =>
|
|
|
22438
23092
|
//#endregion
|
|
22439
23093
|
//#region node_modules/undici/lib/mock/snapshot-recorder.js
|
|
22440
23094
|
var require_snapshot_recorder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
22441
|
-
const { writeFile: writeFile$1, readFile, mkdir: mkdir$1 } = __require("node:fs/promises");
|
|
23095
|
+
const { writeFile: writeFile$1, readFile: readFile$1, mkdir: mkdir$1 } = __require("node:fs/promises");
|
|
22442
23096
|
const { dirname: dirname$1, resolve: resolve$1 } = __require("node:path");
|
|
22443
23097
|
const { setTimeout: setTimeout$1, clearTimeout: clearTimeout$1 } = __require("node:timers");
|
|
22444
23098
|
const { InvalidArgumentError, UndiciError } = require_errors();
|
|
@@ -22738,7 +23392,7 @@ var require_snapshot_recorder = /* @__PURE__ */ __commonJSMin(((exports, module)
|
|
|
22738
23392
|
const path = filePath || this.#snapshotPath;
|
|
22739
23393
|
if (!path) throw new InvalidArgumentError("Snapshot path is required");
|
|
22740
23394
|
try {
|
|
22741
|
-
const data = await readFile(resolve$1(path), "utf8");
|
|
23395
|
+
const data = await readFile$1(resolve$1(path), "utf8");
|
|
22742
23396
|
const parsed = JSON.parse(data);
|
|
22743
23397
|
if (Array.isArray(parsed)) {
|
|
22744
23398
|
this.#snapshots.clear();
|
|
@@ -34077,6 +34731,205 @@ function buildAgyEnv(input) {
|
|
|
34077
34731
|
return env;
|
|
34078
34732
|
}
|
|
34079
34733
|
//#endregion
|
|
34734
|
+
//#region src/features/subagent/task-activity.ts
|
|
34735
|
+
const MAX_READ_BYTES_PER_POLL = 131072;
|
|
34736
|
+
const MAX_LINES_PER_POLL = 20;
|
|
34737
|
+
const MAX_LINE_CHARS = 220;
|
|
34738
|
+
const MAX_MESSAGE_CHARS = 240;
|
|
34739
|
+
function noteWarn(log, context, err) {
|
|
34740
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
34741
|
+
log?.(`[task-activity] ${context}: ${detail}`);
|
|
34742
|
+
}
|
|
34743
|
+
function clipSingleLine(text, maxChars) {
|
|
34744
|
+
const single = text.replace(/\r/g, "").replace(/\s+/g, " ").trim();
|
|
34745
|
+
if (single.length <= maxChars) return single;
|
|
34746
|
+
return single.slice(0, Math.max(0, maxChars - 1)) + "…";
|
|
34747
|
+
}
|
|
34748
|
+
function formatTaskLogLine(taskId, line) {
|
|
34749
|
+
return `[后台任务 · ${taskId}] ${clipSingleLine(line, MAX_LINE_CHARS)}`;
|
|
34750
|
+
}
|
|
34751
|
+
function summarizeMessageJson(rawObj, fallbackName = "message") {
|
|
34752
|
+
if (!rawObj || typeof rawObj !== "object") return null;
|
|
34753
|
+
const obj = rawObj;
|
|
34754
|
+
const id = typeof obj.id === "string" && obj.id.trim() !== "" ? obj.id.trim() : "";
|
|
34755
|
+
const rawSender = typeof obj.sender === "string" ? obj.sender.trim() : "";
|
|
34756
|
+
const senderLabel = rawSender.includes("/") ? rawSender.slice(rawSender.lastIndexOf("/") + 1) : rawSender || "system";
|
|
34757
|
+
const details = obj.renderDetails && typeof obj.renderDetails === "object" ? obj.renderDetails : void 0;
|
|
34758
|
+
const title = typeof details?.messageTitle === "string" ? clipSingleLine(details.messageTitle, 120) : "";
|
|
34759
|
+
const content = typeof obj.content === "string" ? clipSingleLine(obj.content, MAX_MESSAGE_CHARS) : "";
|
|
34760
|
+
if (title === "" && content === "") return null;
|
|
34761
|
+
const body = title !== "" && content !== "" && !content.toLowerCase().includes(title.toLowerCase()) ? `${title} — ${content}` : content !== "" ? content : title;
|
|
34762
|
+
return {
|
|
34763
|
+
dedupKey: id !== "" ? id : fallbackName,
|
|
34764
|
+
text: `[后台通知 · ${senderLabel}] ${body}`
|
|
34765
|
+
};
|
|
34766
|
+
}
|
|
34767
|
+
function listFilesSafe(dir, suffix) {
|
|
34768
|
+
if (!existsSync(dir)) return [];
|
|
34769
|
+
try {
|
|
34770
|
+
return readdirSync(dir).filter((f) => f.endsWith(suffix)).sort();
|
|
34771
|
+
} catch {
|
|
34772
|
+
return [];
|
|
34773
|
+
}
|
|
34774
|
+
}
|
|
34775
|
+
var TaskActivityTracker = class {
|
|
34776
|
+
log;
|
|
34777
|
+
logs = /* @__PURE__ */ new Map();
|
|
34778
|
+
seenMessageFiles = /* @__PURE__ */ new Set();
|
|
34779
|
+
seenMessageIds = /* @__PURE__ */ new Set();
|
|
34780
|
+
baselined = false;
|
|
34781
|
+
constructor(log) {
|
|
34782
|
+
this.log = log;
|
|
34783
|
+
}
|
|
34784
|
+
reset() {
|
|
34785
|
+
this.logs.clear();
|
|
34786
|
+
this.seenMessageFiles.clear();
|
|
34787
|
+
this.seenMessageIds.clear();
|
|
34788
|
+
this.baselined = false;
|
|
34789
|
+
}
|
|
34790
|
+
/** Record pre-existing logs and messages at EOF so resumed runs only emit new activity. */
|
|
34791
|
+
baseline(brainDir) {
|
|
34792
|
+
this.baselined = true;
|
|
34793
|
+
this.scanTaskLogs(brainDir, true, () => {});
|
|
34794
|
+
this.scanMessages(brainDir, true, () => {});
|
|
34795
|
+
}
|
|
34796
|
+
poll(brainDir, emit) {
|
|
34797
|
+
try {
|
|
34798
|
+
this.scanTaskLogs(brainDir, false, emit);
|
|
34799
|
+
this.scanMessages(brainDir, false, emit);
|
|
34800
|
+
} catch (err) {
|
|
34801
|
+
noteWarn(this.log, "poll", err);
|
|
34802
|
+
}
|
|
34803
|
+
}
|
|
34804
|
+
scanTaskLogs(brainDir, baselineOnly, emit) {
|
|
34805
|
+
const tasksDir = join(brainDir, ".system_generated", "tasks");
|
|
34806
|
+
for (const file of listFilesSafe(tasksDir, ".log")) {
|
|
34807
|
+
const taskId = file.slice(0, -4);
|
|
34808
|
+
const fullPath = join(tasksDir, file);
|
|
34809
|
+
let tracked = this.logs.get(file);
|
|
34810
|
+
if (!tracked) {
|
|
34811
|
+
let initialOffset = 0;
|
|
34812
|
+
if (baselineOnly || this.baselined) {
|
|
34813
|
+
if (baselineOnly) try {
|
|
34814
|
+
const st = statSync(fullPath);
|
|
34815
|
+
if (st.isFile()) initialOffset = st.size;
|
|
34816
|
+
} catch {
|
|
34817
|
+
initialOffset = 0;
|
|
34818
|
+
}
|
|
34819
|
+
}
|
|
34820
|
+
tracked = {
|
|
34821
|
+
taskId,
|
|
34822
|
+
filePath: fullPath,
|
|
34823
|
+
offset: initialOffset,
|
|
34824
|
+
decoder: new StringDecoder("utf8"),
|
|
34825
|
+
rest: "",
|
|
34826
|
+
seq: 0
|
|
34827
|
+
};
|
|
34828
|
+
this.logs.set(file, tracked);
|
|
34829
|
+
}
|
|
34830
|
+
if (baselineOnly) continue;
|
|
34831
|
+
this.pollSingleTaskLog(tracked, emit);
|
|
34832
|
+
}
|
|
34833
|
+
}
|
|
34834
|
+
pollSingleTaskLog(tracked, emit) {
|
|
34835
|
+
let size;
|
|
34836
|
+
try {
|
|
34837
|
+
const st = statSync(tracked.filePath);
|
|
34838
|
+
if (!st.isFile()) return;
|
|
34839
|
+
size = st.size;
|
|
34840
|
+
} catch {
|
|
34841
|
+
return;
|
|
34842
|
+
}
|
|
34843
|
+
if (size < tracked.offset) {
|
|
34844
|
+
tracked.offset = 0;
|
|
34845
|
+
tracked.decoder = new StringDecoder("utf8");
|
|
34846
|
+
tracked.rest = "";
|
|
34847
|
+
}
|
|
34848
|
+
if (size === tracked.offset) return;
|
|
34849
|
+
const toRead = Math.min(size - tracked.offset, MAX_READ_BYTES_PER_POLL);
|
|
34850
|
+
const buffer = Buffer.allocUnsafe(toRead);
|
|
34851
|
+
let bytesRead = 0;
|
|
34852
|
+
try {
|
|
34853
|
+
const fd = openSync(tracked.filePath, "r");
|
|
34854
|
+
try {
|
|
34855
|
+
bytesRead = readSync(fd, buffer, 0, toRead, tracked.offset);
|
|
34856
|
+
} finally {
|
|
34857
|
+
closeSync(fd);
|
|
34858
|
+
}
|
|
34859
|
+
} catch {
|
|
34860
|
+
return;
|
|
34861
|
+
}
|
|
34862
|
+
if (bytesRead <= 0) return;
|
|
34863
|
+
tracked.offset += bytesRead;
|
|
34864
|
+
const parts = (tracked.rest + tracked.decoder.write(buffer.subarray(0, bytesRead))).split("\n");
|
|
34865
|
+
tracked.rest = size > tracked.offset ? "" : parts.pop() ?? "";
|
|
34866
|
+
if (size > tracked.offset) {
|
|
34867
|
+
tracked.offset = size;
|
|
34868
|
+
tracked.decoder = new StringDecoder("utf8");
|
|
34869
|
+
}
|
|
34870
|
+
const lines = parts.map((l) => l.trim()).filter((l) => l !== "");
|
|
34871
|
+
if (lines.length === 0) return;
|
|
34872
|
+
const skipped = Math.max(0, lines.length - MAX_LINES_PER_POLL);
|
|
34873
|
+
const visible = skipped > 0 ? lines.slice(-20) : lines;
|
|
34874
|
+
if (skipped > 0) {
|
|
34875
|
+
tracked.seq += 1;
|
|
34876
|
+
emit({
|
|
34877
|
+
stepKey: `task-log-${tracked.taskId}-${tracked.seq}`,
|
|
34878
|
+
text: `[后台任务 · ${tracked.taskId}] … 跳过 ${skipped} 行中间输出,最新日志如下\n`,
|
|
34879
|
+
raw: {
|
|
34880
|
+
kind: "task-log",
|
|
34881
|
+
taskId: tracked.taskId,
|
|
34882
|
+
skipped
|
|
34883
|
+
}
|
|
34884
|
+
});
|
|
34885
|
+
}
|
|
34886
|
+
for (const line of visible) {
|
|
34887
|
+
tracked.seq += 1;
|
|
34888
|
+
emit({
|
|
34889
|
+
stepKey: `task-log-${tracked.taskId}-${tracked.seq}`,
|
|
34890
|
+
text: `${formatTaskLogLine(tracked.taskId, line)}\n`,
|
|
34891
|
+
raw: {
|
|
34892
|
+
kind: "task-log",
|
|
34893
|
+
taskId: tracked.taskId,
|
|
34894
|
+
line
|
|
34895
|
+
}
|
|
34896
|
+
});
|
|
34897
|
+
}
|
|
34898
|
+
}
|
|
34899
|
+
scanMessages(brainDir, baselineOnly, emit) {
|
|
34900
|
+
const baseDir = join(brainDir, ".system_generated", "messages");
|
|
34901
|
+
const dirs = [{
|
|
34902
|
+
tag: "delivered",
|
|
34903
|
+
path: baseDir
|
|
34904
|
+
}, {
|
|
34905
|
+
tag: "undelivered",
|
|
34906
|
+
path: join(baseDir, "undelivered")
|
|
34907
|
+
}];
|
|
34908
|
+
for (const dir of dirs) for (const file of listFilesSafe(dir.path, ".json")) {
|
|
34909
|
+
const fileKey = `${dir.tag}:${file}`;
|
|
34910
|
+
if (this.seenMessageFiles.has(fileKey)) continue;
|
|
34911
|
+
this.seenMessageFiles.add(fileKey);
|
|
34912
|
+
const stem = file.slice(0, -5);
|
|
34913
|
+
let parsed;
|
|
34914
|
+
try {
|
|
34915
|
+
parsed = JSON.parse(readFileSync(join(dir.path, file), "utf8"));
|
|
34916
|
+
} catch {
|
|
34917
|
+
continue;
|
|
34918
|
+
}
|
|
34919
|
+
const summary = summarizeMessageJson(parsed, stem);
|
|
34920
|
+
if (!summary) continue;
|
|
34921
|
+
if (this.seenMessageIds.has(summary.dedupKey)) continue;
|
|
34922
|
+
this.seenMessageIds.add(summary.dedupKey);
|
|
34923
|
+
if (baselineOnly) continue;
|
|
34924
|
+
emit({
|
|
34925
|
+
stepKey: `task-msg-${summary.dedupKey}`,
|
|
34926
|
+
text: `${summary.text}\n`,
|
|
34927
|
+
raw: parsed
|
|
34928
|
+
});
|
|
34929
|
+
}
|
|
34930
|
+
}
|
|
34931
|
+
};
|
|
34932
|
+
//#endregion
|
|
34080
34933
|
//#region src/features/subagent/tracker.ts
|
|
34081
34934
|
/**
|
|
34082
34935
|
* Swallow the failures a live transcript produces by design — a row still being
|
|
@@ -34159,6 +35012,7 @@ var SubagentTracker = class {
|
|
|
34159
35012
|
brainDir = null;
|
|
34160
35013
|
trackedSubagents = /* @__PURE__ */ new Map();
|
|
34161
35014
|
seenStepKeys = /* @__PURE__ */ new Set();
|
|
35015
|
+
taskActivity;
|
|
34162
35016
|
timer = null;
|
|
34163
35017
|
active = false;
|
|
34164
35018
|
polling = false;
|
|
@@ -34168,6 +35022,7 @@ var SubagentTracker = class {
|
|
|
34168
35022
|
this.conversationId = opts.conversationId ?? "";
|
|
34169
35023
|
this.accountHome = opts.accountHome;
|
|
34170
35024
|
this.pollIntervalMs = opts.pollIntervalMs ?? 500;
|
|
35025
|
+
this.taskActivity = new TaskActivityTracker(opts.log);
|
|
34171
35026
|
}
|
|
34172
35027
|
/** Follow the conversation agy reported in its stream-json init/result envelope. */
|
|
34173
35028
|
setConversationId(cid) {
|
|
@@ -34175,6 +35030,7 @@ var SubagentTracker = class {
|
|
|
34175
35030
|
this.conversationId = cid;
|
|
34176
35031
|
this.brainDir = null;
|
|
34177
35032
|
this.baselined = false;
|
|
35033
|
+
this.taskActivity.reset();
|
|
34178
35034
|
if (this.active) {
|
|
34179
35035
|
if (this.opts.resumed === true) {
|
|
34180
35036
|
this.baselined = true;
|
|
@@ -34199,6 +35055,7 @@ var SubagentTracker = class {
|
|
|
34199
35055
|
try {
|
|
34200
35056
|
if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
|
|
34201
35057
|
if (!this.brainDir) return;
|
|
35058
|
+
this.taskActivity.baseline(this.brainDir);
|
|
34202
35059
|
this.scanSubagentsForConv(this.conversationId, true);
|
|
34203
35060
|
for (const cid of Array.from(this.trackedSubagents.keys())) this.scanSubagentsForConv(cid, true);
|
|
34204
35061
|
} catch (err) {
|
|
@@ -34206,10 +35063,14 @@ var SubagentTracker = class {
|
|
|
34206
35063
|
}
|
|
34207
35064
|
}
|
|
34208
35065
|
stop() {
|
|
34209
|
-
|
|
34210
|
-
|
|
34211
|
-
|
|
34212
|
-
this.
|
|
35066
|
+
try {
|
|
35067
|
+
if (this.active && !this.polling && this.conversationId !== "") this.poll();
|
|
35068
|
+
} finally {
|
|
35069
|
+
this.active = false;
|
|
35070
|
+
if (this.timer) {
|
|
35071
|
+
clearInterval(this.timer);
|
|
35072
|
+
this.timer = null;
|
|
35073
|
+
}
|
|
34213
35074
|
}
|
|
34214
35075
|
}
|
|
34215
35076
|
/** Run one scan across known conversations and subagents. */
|
|
@@ -34220,6 +35081,9 @@ var SubagentTracker = class {
|
|
|
34220
35081
|
try {
|
|
34221
35082
|
if (!this.brainDir) this.brainDir = findBrainDir(this.conversationId, this.accountHome);
|
|
34222
35083
|
if (!this.brainDir) return;
|
|
35084
|
+
this.taskActivity.poll(this.brainDir, (ev) => {
|
|
35085
|
+
this.emitSubagentEvent(ev.stepKey, ev.text, ev.raw);
|
|
35086
|
+
});
|
|
34223
35087
|
const convsToScan = [this.conversationId, ...Array.from(this.trackedSubagents.keys())];
|
|
34224
35088
|
for (const cid of convsToScan) this.scanSubagentsForConv(cid);
|
|
34225
35089
|
for (const sub of this.trackedSubagents.values()) if (!sub.terminal) this.pollSubagentTranscript(sub);
|
|
@@ -34380,6 +35244,24 @@ function brief$1(s) {
|
|
|
34380
35244
|
const flat = s.trim().replace(/\s+/g, " ");
|
|
34381
35245
|
return flat.length > 300 ? flat.slice(0, 300) + "..." : flat;
|
|
34382
35246
|
}
|
|
35247
|
+
function serializeOpt(v) {
|
|
35248
|
+
if (typeof v === "string") return v.trim() !== "" ? v.trim() : void 0;
|
|
35249
|
+
if (v && typeof v === "object") return JSON.stringify(v);
|
|
35250
|
+
}
|
|
35251
|
+
function resolveAttemptOverrides(options, cfg) {
|
|
35252
|
+
const agent = typeof options.agyAgent === "string" ? options.agyAgent.trim() : cfg.agent.trim();
|
|
35253
|
+
const agySettings = serializeOpt(options.agySettings) ?? serializeOpt(cfg.agySettings);
|
|
35254
|
+
const jsonSchema = serializeOpt(options.agyJsonSchema);
|
|
35255
|
+
const sandbox = options.agySandbox ?? cfg.sandbox;
|
|
35256
|
+
const transport = options.agyTransport ?? cfg.transport;
|
|
35257
|
+
return {
|
|
35258
|
+
...agent !== "" ? { agent } : {},
|
|
35259
|
+
...agySettings !== void 0 ? { agySettings } : {},
|
|
35260
|
+
...jsonSchema !== void 0 ? { jsonSchema } : {},
|
|
35261
|
+
sandbox,
|
|
35262
|
+
transport
|
|
35263
|
+
};
|
|
35264
|
+
}
|
|
34383
35265
|
/** Pure argv builder for one agy call (same body as AgyAdapter.buildArgs). */
|
|
34384
35266
|
function buildAgyArgs(opts) {
|
|
34385
35267
|
const args = [
|
|
@@ -34390,6 +35272,10 @@ function buildAgyArgs(opts) {
|
|
|
34390
35272
|
];
|
|
34391
35273
|
if (opts.permissionMode === "skip") args.push("--dangerously-skip-permissions");
|
|
34392
35274
|
else args.push("--mode", opts.permissionMode);
|
|
35275
|
+
if (opts.sandbox === true) args.push("--sandbox");
|
|
35276
|
+
if (opts.agent && opts.agent.trim() !== "") args.push("--agent", opts.agent.trim());
|
|
35277
|
+
if (opts.agySettings && opts.agySettings.trim() !== "") args.push("--settings", opts.agySettings.trim());
|
|
35278
|
+
if (opts.jsonSchema && opts.jsonSchema.trim() !== "") args.push("--json-schema", opts.jsonSchema.trim());
|
|
34393
35279
|
const effectiveModel = resolveModelSlug(opts.model);
|
|
34394
35280
|
if (effectiveModel !== "") args.push("--model", effectiveModel);
|
|
34395
35281
|
const effortModel = effectiveModel.toLowerCase();
|
|
@@ -34423,7 +35309,11 @@ function buildSpawnArgs(input, printTimeoutMinutes, log) {
|
|
|
34423
35309
|
timeoutMs: input.cfg.timeoutMs,
|
|
34424
35310
|
printTimeoutMinutes,
|
|
34425
35311
|
extraArgs: input.cfg.extraArgs,
|
|
34426
|
-
addDirs: input.addDirs
|
|
35312
|
+
addDirs: input.addDirs,
|
|
35313
|
+
sandbox: input.sandbox ?? input.cfg.sandbox,
|
|
35314
|
+
...(input.agent ?? input.cfg.agent).trim() !== "" ? { agent: (input.agent ?? input.cfg.agent).trim() } : {},
|
|
35315
|
+
...(input.agySettings ?? input.cfg.agySettings).trim() !== "" ? { agySettings: (input.agySettings ?? input.cfg.agySettings).trim() } : {},
|
|
35316
|
+
...input.jsonSchema && input.jsonSchema.trim() !== "" ? { jsonSchema: input.jsonSchema.trim() } : {}
|
|
34427
35317
|
};
|
|
34428
35318
|
const argsBase = buildAgyArgs(base);
|
|
34429
35319
|
const promptViaStdin = shouldUsePromptStdin(argsBase);
|
|
@@ -34471,6 +35361,9 @@ function createAttemptRecorder(deps, cfg, account, initialConversationId, trackS
|
|
|
34471
35361
|
tracker?.start();
|
|
34472
35362
|
proc.outcome.finally(() => tracker?.stop());
|
|
34473
35363
|
},
|
|
35364
|
+
startTracker: () => {
|
|
35365
|
+
tracker?.start();
|
|
35366
|
+
},
|
|
34474
35367
|
feedLine: (line, onEvent, onFirstEvent) => {
|
|
34475
35368
|
watchdog.markEvent();
|
|
34476
35369
|
onFirstEvent?.();
|
|
@@ -35204,6 +36097,16 @@ async function* runAgyAttempt(deps, input) {
|
|
|
35204
36097
|
...input,
|
|
35205
36098
|
prompt: spawn.prompt
|
|
35206
36099
|
});
|
|
36100
|
+
if ((input.transport ?? input.cfg.transport) === "acp" && deps.runAcp && !input.jsonSchema && !input.agySettings && !input.isAux) {
|
|
36101
|
+
const acpRec = await deps.runAcp(deps, {
|
|
36102
|
+
...input,
|
|
36103
|
+
prompt: spawn.prompt
|
|
36104
|
+
}, slot).catch(() => null);
|
|
36105
|
+
if (acpRec !== null) {
|
|
36106
|
+
recorder.stop();
|
|
36107
|
+
return acpRec;
|
|
36108
|
+
}
|
|
36109
|
+
}
|
|
35207
36110
|
handleAttemptOutcome(deps, input, {
|
|
35208
36111
|
...await startAttemptProcess(deps, input, spawn, recorder, slot),
|
|
35209
36112
|
recorder,
|
|
@@ -35459,7 +36362,7 @@ var AgyAdapter = class extends LlmAdapter {
|
|
|
35459
36362
|
const account = selection.account;
|
|
35460
36363
|
let family = selection.family;
|
|
35461
36364
|
let activeModel = selection.activeModel;
|
|
35462
|
-
if (account && !isAux) this.deps.pool?.markAccountActive(account.id);
|
|
36365
|
+
if (account && !isAux && (family === "google" || !this.deps.pool?.getPoolData().lastActiveAccountId)) this.deps.pool?.markAccountActive(account.id);
|
|
35463
36366
|
const onAccount = options.agyOnAccount;
|
|
35464
36367
|
if (typeof onAccount === "function" && account) try {
|
|
35465
36368
|
onAccount({
|
|
@@ -35525,22 +36428,25 @@ var AgyAdapter = class extends LlmAdapter {
|
|
|
35525
36428
|
}
|
|
35526
36429
|
if (samePrompt && prevPrompt !== void 0 && prevPrompt.inFlight && liveRun === void 0 && now - prevPrompt.startedAt < 2e3) throw new LlmError("Duplicate request ignored: an identical request is already running for this session.", Err.BUSY);
|
|
35527
36430
|
if (runLive && !samePrompt) {
|
|
35528
|
-
const liveCid = (liveRun.accountHome ?? "") === (account?.dir ?? "") ? liveRun.conversationId : null;
|
|
35529
|
-
if (liveCid !== null && binding === void 0 && !isAux && sessionAccountKey !== "") binding = {
|
|
35530
|
-
conversationId: liveCid,
|
|
35531
|
-
lastMessageCount: Math.max(0, lastAssistantIdx + 1),
|
|
35532
|
-
updatedAt: Date.now(),
|
|
35533
|
-
model: currentModel,
|
|
35534
|
-
interrupted: true
|
|
35535
|
-
};
|
|
35536
|
-
else if (binding !== void 0) binding.interrupted = true;
|
|
35537
36431
|
if (liveRun.hasResult) {
|
|
35538
36432
|
if (!await waitForRunSettle(liveRun, 1500)) this.deps.log?.("previous agy run did not exit within 1.5s after producing its result — preempting it");
|
|
35539
36433
|
}
|
|
36434
|
+
const wasConsumable = liveRun.hasConsumableResult;
|
|
35540
36435
|
if (!liveRun.isSettled) {
|
|
36436
|
+
const liveCid = (liveRun.accountHome ?? "") === (account?.dir ?? "") ? liveRun.conversationId : null;
|
|
36437
|
+
if (!wasConsumable) {
|
|
36438
|
+
if (liveCid !== null && binding === void 0 && !isAux && sessionAccountKey !== "") binding = {
|
|
36439
|
+
conversationId: liveCid,
|
|
36440
|
+
lastMessageCount: Math.max(0, lastAssistantIdx + 1),
|
|
36441
|
+
updatedAt: Date.now(),
|
|
36442
|
+
model: currentModel,
|
|
36443
|
+
interrupted: true
|
|
36444
|
+
};
|
|
36445
|
+
else if (binding !== void 0) binding.interrupted = true;
|
|
36446
|
+
}
|
|
35541
36447
|
liveRun.requestAbort?.();
|
|
35542
36448
|
if (!await waitForRunSettle(liveRun, 3500)) this.warnOnce("settle-timeout:" + sessionKey, "the preempted agy run did not exit within 3.5s — starting the replacement anyway; its late write-back is ignored because the newer run owns the session");
|
|
35543
|
-
if (!prompt.includes("the previous turn was interrupted")) prompt = "[the previous turn was interrupted before it finished — do not continue or answer that unfinished work; respond only to the newest request below]\n\n" + prompt;
|
|
36449
|
+
if (!wasConsumable && !prompt.includes("the previous turn was interrupted")) prompt = "[the previous turn was interrupted before it finished — do not continue or answer that unfinished work; respond only to the newest request below]\n\n" + prompt;
|
|
35544
36450
|
}
|
|
35545
36451
|
}
|
|
35546
36452
|
this.activeSessionPrompts.set(sessionKey, {
|
|
@@ -35570,7 +36476,8 @@ var AgyAdapter = class extends LlmAdapter {
|
|
|
35570
36476
|
sharesSingleEgress: () => this.sharesSingleEgress(),
|
|
35571
36477
|
lastAccountSpawnTime: this.lastAccountSpawnTime,
|
|
35572
36478
|
minSpawnIntervalMs: this.minSpawnIntervalMs,
|
|
35573
|
-
spawnLimiter: this.spawnLimiter
|
|
36479
|
+
spawnLimiter: this.spawnLimiter,
|
|
36480
|
+
...this.deps.runAcp === void 0 ? {} : { runAcp: this.deps.runAcp }
|
|
35574
36481
|
}, {
|
|
35575
36482
|
cfg,
|
|
35576
36483
|
bin,
|
|
@@ -35591,7 +36498,8 @@ var AgyAdapter = class extends LlmAdapter {
|
|
|
35591
36498
|
sessionAccountKey,
|
|
35592
36499
|
family,
|
|
35593
36500
|
signal: options.signal,
|
|
35594
|
-
agyOnEvent: options.agyOnEvent
|
|
36501
|
+
agyOnEvent: options.agyOnEvent,
|
|
36502
|
+
...resolveAttemptOverrides(options, cfg)
|
|
35595
36503
|
});
|
|
35596
36504
|
yield* driveSpan(this.deps, rec, 0, policy.mirrorTools && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal, compactionNotice);
|
|
35597
36505
|
}
|
|
@@ -35612,9 +36520,9 @@ const USAGE = `dsh-agy-image — 用 agy 内置的 generate_image 生成图片
|
|
|
35612
36520
|
-i, --image, --ref <path> 参考图/源图(可重复;用于改图)
|
|
35613
36521
|
-o, --out <path> 把成图复制到该路径(或目录)
|
|
35614
36522
|
--model <id> 驱动调用的模型(默认跟随插件配置)
|
|
35615
|
-
--effort <level> 思考档(默认
|
|
36523
|
+
--effort <level> 思考档(默认 medium)
|
|
35616
36524
|
--timeout <seconds> 整次生成超时(默认 240)
|
|
35617
|
-
--permission-mode <m> skip | plan | accept-edits(默认跟随插件配置)
|
|
36525
|
+
--permission-mode <m> skip | auto | plan | accept-edits(默认跟随插件配置)
|
|
35618
36526
|
--max-bytes <n> 接受的最大产物字节数(默认 20MiB)
|
|
35619
36527
|
--json 输出结构化 JSON(含 ok/path/width/height/mime/...)
|
|
35620
36528
|
--force 忽略本进程内的结果缓存,重新生成
|
|
@@ -35636,6 +36544,7 @@ const USAGE = `dsh-agy-image — 用 agy 内置的 generate_image 生成图片
|
|
|
35636
36544
|
`;
|
|
35637
36545
|
const MODES = [
|
|
35638
36546
|
"skip",
|
|
36547
|
+
"auto",
|
|
35639
36548
|
"plan",
|
|
35640
36549
|
"accept-edits"
|
|
35641
36550
|
];
|
|
@@ -35772,144 +36681,17 @@ function exitCodeFor(res) {
|
|
|
35772
36681
|
default: return 4;
|
|
35773
36682
|
}
|
|
35774
36683
|
}
|
|
35775
|
-
|
|
35776
|
-
|
|
35777
|
-
return {
|
|
35778
|
-
|
|
35779
|
-
|
|
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
|
-
};
|
|
36684
|
+
/** Hydrate the cached catalog from disk without spawning `agy models`. */
|
|
36685
|
+
function createImageCatalog(cfg) {
|
|
36686
|
+
return new ModelCatalog(async () => {
|
|
36687
|
+
throw new Error("model discovery is disabled for the image CLI");
|
|
36688
|
+
}, cfg.fallbackModels, 3e5, void 0, { cacheFile: join(stateDir(), "model-catalog.json") });
|
|
35905
36689
|
}
|
|
35906
36690
|
/** Build the real adapter (same deps as the smoke scripts / host). */
|
|
35907
|
-
function createImageAdapter(cfg, log) {
|
|
36691
|
+
function createImageAdapter(cfg, log, catalog = createImageCatalog(cfg)) {
|
|
35908
36692
|
return new AgyAdapter({
|
|
35909
36693
|
getConfig: () => cfg,
|
|
35910
|
-
catalog
|
|
35911
|
-
throw new Error("model discovery is disabled for the image CLI");
|
|
35912
|
-
}, cfg.fallbackModels, 3e5),
|
|
36694
|
+
catalog,
|
|
35913
36695
|
store: new SessionStore(join(stateDir(), "cli-image-sessions.json")),
|
|
35914
36696
|
pool: new AccountPoolManager(),
|
|
35915
36697
|
bin: () => resolveAgyBin(cfg),
|
|
@@ -35923,11 +36705,13 @@ function createDefaultImageService(args, _req, writeErr) {
|
|
|
35923
36705
|
const cfg = resolveConfig(void 0);
|
|
35924
36706
|
if (cfg.workspaceRoot === "") cfg.workspaceRoot = process.cwd();
|
|
35925
36707
|
const bin = resolveAgyBin(cfg);
|
|
35926
|
-
const
|
|
36708
|
+
const catalog = createImageCatalog(cfg);
|
|
36709
|
+
const adapter = createImageAdapter(cfg, args.quiet ? void 0 : (m) => writeErr("[agy] " + m + "\n"), catalog);
|
|
35927
36710
|
return new ImageService({
|
|
35928
36711
|
cfg: () => cfg,
|
|
35929
36712
|
bin: () => bin,
|
|
35930
36713
|
run: (call) => runViaAdapter(adapter, call),
|
|
36714
|
+
catalog: () => catalog.get(),
|
|
35931
36715
|
...args.quiet ? {} : { log: (m) => writeErr("[image] " + m + "\n") }
|
|
35932
36716
|
});
|
|
35933
36717
|
}
|