toc-ocra 0.3.18 → 0.3.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/cli.mjs +314 -136
- package/dist/service/agent.mjs +301 -123
- package/dist/src/acp/acp-launch-specs.js +3 -0
- package/dist/src/acp/acp-launch-specs.js.map +1 -1
- package/dist/src/acp/chat-session.d.ts +8 -0
- package/dist/src/acp/chat-session.js +31 -2
- package/dist/src/acp/chat-session.js.map +1 -1
- package/dist/src/providers/claude-quota.d.ts +4 -0
- package/dist/src/providers/claude-quota.js +92 -0
- package/dist/src/providers/claude-quota.js.map +1 -0
- package/dist/src/providers/claude-sessions.d.ts +10 -0
- package/dist/src/providers/claude-sessions.js +27 -0
- package/dist/src/providers/claude-sessions.js.map +1 -0
- package/dist/src/providers/model-catalog.d.ts +9 -2
- package/dist/src/providers/model-catalog.js +85 -9
- package/dist/src/providers/model-catalog.js.map +1 -1
- package/dist/src/providers/registry.js +2 -1
- package/dist/src/providers/registry.js.map +1 -1
- package/package.json +1 -1
package/dist/cli/cli.mjs
CHANGED
|
@@ -4576,10 +4576,10 @@ var require_lib = __commonJS({
|
|
|
4576
4576
|
// src/index.ts
|
|
4577
4577
|
import { spawnSync } from "node:child_process";
|
|
4578
4578
|
import { createHash as createHash5 } from "node:crypto";
|
|
4579
|
-
import { existsSync as
|
|
4579
|
+
import { existsSync as existsSync8, mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
|
|
4580
4580
|
import { tmpdir as tmpdir4 } from "node:os";
|
|
4581
4581
|
import { createRequire } from "node:module";
|
|
4582
|
-
import { dirname as dirname11, join as
|
|
4582
|
+
import { dirname as dirname11, join as join25, resolve as resolve9 } from "node:path";
|
|
4583
4583
|
import { fileURLToPath as fileURLToPath3, pathToFileURL as pathToFileURL2 } from "node:url";
|
|
4584
4584
|
|
|
4585
4585
|
// src/config.ts
|
|
@@ -25374,15 +25374,32 @@ function textRows(prefix, text3, maxRows = 40) {
|
|
|
25374
25374
|
|
|
25375
25375
|
// src/acp/acp-launch-specs.ts
|
|
25376
25376
|
import { realpathSync as realpathSync2 } from "node:fs";
|
|
25377
|
-
import { join as
|
|
25377
|
+
import { join as join13 } from "node:path";
|
|
25378
|
+
|
|
25379
|
+
// src/providers/claude-sessions.ts
|
|
25380
|
+
import { existsSync as existsSync4, readdirSync as readdirSync3 } from "node:fs";
|
|
25381
|
+
import { homedir as homedir4 } from "node:os";
|
|
25382
|
+
import { join as join7 } from "node:path";
|
|
25383
|
+
function claudeSessionSaved(sessionId, env = process.env) {
|
|
25384
|
+
const id = sessionId.trim();
|
|
25385
|
+
if (!id || /[/\\]/.test(id) || id.includes("..")) return false;
|
|
25386
|
+
const projects = join7(env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir4(), ".claude"), "projects");
|
|
25387
|
+
let folders;
|
|
25388
|
+
try {
|
|
25389
|
+
folders = readdirSync3(projects);
|
|
25390
|
+
} catch (error62) {
|
|
25391
|
+
return error62.code !== "ENOENT";
|
|
25392
|
+
}
|
|
25393
|
+
return folders.some((folder) => existsSync4(join7(projects, folder, `${id}.jsonl`)));
|
|
25394
|
+
}
|
|
25378
25395
|
|
|
25379
25396
|
// src/providers/cli/codex-catalog.ts
|
|
25380
25397
|
import { spawn as spawn3 } from "node:child_process";
|
|
25381
25398
|
import { statSync as statSync3 } from "node:fs";
|
|
25382
25399
|
import { chmod as chmod3, mkdir as mkdir3, readFile as readFile2, rename as rename3, stat, writeFile as writeFile3 } from "node:fs/promises";
|
|
25383
|
-
import { homedir as
|
|
25384
|
-
import { dirname as dirname5, isAbsolute, join as
|
|
25385
|
-
var codexHome = () => process.env.CODEX_HOME?.trim() ||
|
|
25400
|
+
import { homedir as homedir5 } from "node:os";
|
|
25401
|
+
import { dirname as dirname5, isAbsolute, join as join8, resolve as resolve2 } from "node:path";
|
|
25402
|
+
var codexHome = () => process.env.CODEX_HOME?.trim() || join8(homedir5(), ".codex");
|
|
25386
25403
|
var BUNDLED_TIMEOUT_MS = 1e4;
|
|
25387
25404
|
function configuredCatalogPath(config2, home = codexHome()) {
|
|
25388
25405
|
const value = config2.match(/^\s*model_catalog_json\s*=\s*["']([^"']+)["']\s*(?:#.*)?$/m)?.[1]?.trim();
|
|
@@ -25460,11 +25477,11 @@ function fileStamp(path) {
|
|
|
25460
25477
|
}
|
|
25461
25478
|
var stampOf = (configPath, sourcePath) => `${fileStamp(configPath)}|${fileStamp(sourcePath)}`;
|
|
25462
25479
|
function overlayPath() {
|
|
25463
|
-
return
|
|
25480
|
+
return join8(agentDataDir(), "codex", "model-catalog.json");
|
|
25464
25481
|
}
|
|
25465
25482
|
async function rebuild() {
|
|
25466
25483
|
const home = codexHome();
|
|
25467
|
-
const configPath =
|
|
25484
|
+
const configPath = join8(home, "config.toml");
|
|
25468
25485
|
const config2 = await readFile2(configPath, "utf8").catch(() => "");
|
|
25469
25486
|
const sourcePath = configuredCatalogPath(config2, home);
|
|
25470
25487
|
if (!sourcePath) {
|
|
@@ -25518,21 +25535,21 @@ function codexCatalogArgs() {
|
|
|
25518
25535
|
|
|
25519
25536
|
// src/providers/model-catalog.ts
|
|
25520
25537
|
import { spawn as spawn5 } from "node:child_process";
|
|
25521
|
-
import { readFile as readFile3 } from "node:fs/promises";
|
|
25522
|
-
import { homedir as
|
|
25523
|
-
import { isAbsolute as isAbsolute2, join as
|
|
25538
|
+
import { readdir, readFile as readFile3 } from "node:fs/promises";
|
|
25539
|
+
import { homedir as homedir7 } from "node:os";
|
|
25540
|
+
import { isAbsolute as isAbsolute2, join as join10, resolve as resolve3 } from "node:path";
|
|
25524
25541
|
|
|
25525
25542
|
// src/providers/kiro-auth.ts
|
|
25526
25543
|
import { execFile as execFile3 } from "node:child_process";
|
|
25527
|
-
import { homedir as
|
|
25528
|
-
import { join as
|
|
25544
|
+
import { homedir as homedir6 } from "node:os";
|
|
25545
|
+
import { join as join9 } from "node:path";
|
|
25529
25546
|
import { promisify } from "node:util";
|
|
25530
25547
|
var execFileAsync = promisify(execFile3);
|
|
25531
25548
|
var NOT_AUTHENTICATED = "Kiro CLI \u672A\u767B\u5F55\u6216\u65E0\u6CD5\u786E\u8BA4\u767B\u5F55\u72B6\u6001\uFF0C\u8BF7\u5728\u672C\u673A\u767B\u5F55\u540E\u91CD\u8BD5";
|
|
25532
25549
|
var knownUnauthenticated = false;
|
|
25533
25550
|
async function hasStoredAuthentication(environment) {
|
|
25534
25551
|
if (environment.KIRO_API_KEY?.trim()) return true;
|
|
25535
|
-
const database = process.platform === "darwin" ?
|
|
25552
|
+
const database = process.platform === "darwin" ? join9(homedir6(), "Library", "Application Support", "kiro-cli", "data.sqlite3") : process.platform === "win32" ? join9(environment.LOCALAPPDATA || join9(homedir6(), "AppData", "Local"), "Kiro-Cli", "data.sqlite3") : join9(environment.XDG_DATA_HOME || join9(homedir6(), ".local", "share"), "kiro-cli", "data.sqlite3");
|
|
25536
25553
|
const sql = "SELECT 1 FROM auth_kv WHERE key IN ('kirocli:odic:token', 'codewhisperer:odic:token', 'kirocli:external-idp:token', 'kirocli:social:token') AND (json_extract(value, '$.expires_at') IS NULL OR julianday(json_extract(value, '$.expires_at')) > julianday('now')) LIMIT 1;";
|
|
25537
25554
|
try {
|
|
25538
25555
|
const { stdout } = await execFileAsync("sqlite3", ["-readonly", database, sql], {
|
|
@@ -25651,9 +25668,40 @@ var CLAUDE_REASONING_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
|
25651
25668
|
var CLAUDE_BUILTIN_MODELS = [
|
|
25652
25669
|
{ id: "opus", name: "Opus" },
|
|
25653
25670
|
{ id: "sonnet", name: "Sonnet" },
|
|
25654
|
-
{ id: "haiku", name: "Haiku" }
|
|
25671
|
+
{ id: "haiku", name: "Haiku" },
|
|
25672
|
+
{ id: "fable", name: "Fable" }
|
|
25655
25673
|
];
|
|
25656
|
-
function
|
|
25674
|
+
function parseClaudeCachedModels(cache) {
|
|
25675
|
+
const listed = objectValue(objectValue(objectValue(cache).catalog).config).models;
|
|
25676
|
+
if (!Array.isArray(listed)) return [];
|
|
25677
|
+
const entries = [];
|
|
25678
|
+
const seen = /* @__PURE__ */ new Set();
|
|
25679
|
+
for (const raw of listed) {
|
|
25680
|
+
const model = objectValue(raw);
|
|
25681
|
+
const id = stringValue(model.id);
|
|
25682
|
+
if (!id || model.disabled === true || seen.has(id)) continue;
|
|
25683
|
+
seen.add(id);
|
|
25684
|
+
const runtime = objectValue(model.runtime);
|
|
25685
|
+
const efforts = Array.isArray(runtime.effort_levels) ? runtime.effort_levels.filter((value) => typeof value === "string" && value.trim() !== "") : [];
|
|
25686
|
+
const name = stringValue(model.name);
|
|
25687
|
+
const description = stringValue(model.description);
|
|
25688
|
+
const defaultEffort = stringValue(runtime.default_effort);
|
|
25689
|
+
const section = stringValue(model.section);
|
|
25690
|
+
entries.push({
|
|
25691
|
+
...section && { section },
|
|
25692
|
+
entry: {
|
|
25693
|
+
id,
|
|
25694
|
+
name: name ?? id,
|
|
25695
|
+
...description && { description },
|
|
25696
|
+
...defaultEffort && efforts.includes(defaultEffort) && { default_reasoning_effort: defaultEffort },
|
|
25697
|
+
supported_reasoning_efforts: efforts
|
|
25698
|
+
}
|
|
25699
|
+
});
|
|
25700
|
+
}
|
|
25701
|
+
const main2 = entries.filter((item) => item.section === "main");
|
|
25702
|
+
return (main2.length ? main2 : entries).map((item) => item.entry);
|
|
25703
|
+
}
|
|
25704
|
+
function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt = (/* @__PURE__ */ new Date()).toISOString(), cachedModels = []) {
|
|
25657
25705
|
const source = objectValue(settings);
|
|
25658
25706
|
const mergedEnv = { ...objectValue(source.env), ...environment };
|
|
25659
25707
|
const models2 = /* @__PURE__ */ new Map();
|
|
@@ -25677,8 +25725,18 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
|
|
|
25677
25725
|
}
|
|
25678
25726
|
const defaultModel = stringValue(mergedEnv.ANTHROPIC_MODEL) ?? stringValue(source.model);
|
|
25679
25727
|
if (models2.size === 0) {
|
|
25680
|
-
if (
|
|
25681
|
-
|
|
25728
|
+
if (cachedModels.length) {
|
|
25729
|
+
for (const model of cachedModels) if (!models2.has(model.id)) models2.set(model.id, model);
|
|
25730
|
+
if (defaultModel && !models2.has(defaultModel)) {
|
|
25731
|
+
const rest = [...models2.values()];
|
|
25732
|
+
models2.clear();
|
|
25733
|
+
addModel(defaultModel);
|
|
25734
|
+
for (const model of rest) models2.set(model.id, model);
|
|
25735
|
+
}
|
|
25736
|
+
} else {
|
|
25737
|
+
if (defaultModel) addModel(defaultModel);
|
|
25738
|
+
for (const model of CLAUDE_BUILTIN_MODELS) addModel(model.id, model.name);
|
|
25739
|
+
}
|
|
25682
25740
|
}
|
|
25683
25741
|
return {
|
|
25684
25742
|
agent_type: "claude",
|
|
@@ -25687,15 +25745,15 @@ function parseClaudeModelCatalog(settings, environment = process.env, fetchedAt
|
|
|
25687
25745
|
models: [...models2.values()]
|
|
25688
25746
|
};
|
|
25689
25747
|
}
|
|
25690
|
-
var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() ||
|
|
25691
|
-
var codexHome2 = () => process.env.CODEX_HOME?.trim() ||
|
|
25692
|
-
var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() ||
|
|
25693
|
-
var grokHome = () => process.env.GROK_HOME?.trim() ||
|
|
25694
|
-
var opencodeHome = () =>
|
|
25695
|
-
var kiroHome = () =>
|
|
25748
|
+
var claudeHome = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join10(homedir7(), ".claude");
|
|
25749
|
+
var codexHome2 = () => process.env.CODEX_HOME?.trim() || join10(homedir7(), ".codex");
|
|
25750
|
+
var geminiHome = () => process.env.GEMINI_CLI_HOME?.trim() || join10(homedir7(), ".gemini");
|
|
25751
|
+
var grokHome = () => process.env.GROK_HOME?.trim() || join10(homedir7(), ".grok");
|
|
25752
|
+
var opencodeHome = () => join10(process.env.XDG_CONFIG_HOME?.trim() || join10(homedir7(), ".config"), "opencode");
|
|
25753
|
+
var kiroHome = () => join10(homedir7(), ".kiro");
|
|
25696
25754
|
async function readClaudeModelCatalog() {
|
|
25697
25755
|
const home = claudeHome();
|
|
25698
|
-
const content = await readFile3(
|
|
25756
|
+
const content = await readFile3(join10(home, "settings.json"), "utf8").catch(() => "");
|
|
25699
25757
|
let settings = {};
|
|
25700
25758
|
if (content) {
|
|
25701
25759
|
try {
|
|
@@ -25704,7 +25762,23 @@ async function readClaudeModelCatalog() {
|
|
|
25704
25762
|
throw new Error("Claude \u672C\u673A settings.json \u4E0D\u662F\u6709\u6548 JSON");
|
|
25705
25763
|
}
|
|
25706
25764
|
}
|
|
25707
|
-
return parseClaudeModelCatalog(settings);
|
|
25765
|
+
return parseClaudeModelCatalog(settings, process.env, (/* @__PURE__ */ new Date()).toISOString(), await readClaudeCachedModels(home));
|
|
25766
|
+
}
|
|
25767
|
+
async function readClaudeCachedModels(home) {
|
|
25768
|
+
const dir = join10(home, "cache", "model-catalog");
|
|
25769
|
+
const names = await readdir(dir).catch(() => []);
|
|
25770
|
+
let newest;
|
|
25771
|
+
for (const name of names) {
|
|
25772
|
+
if (!name.endsWith(".json")) continue;
|
|
25773
|
+
try {
|
|
25774
|
+
const cache = JSON.parse(await readFile3(join10(dir, name), "utf8"));
|
|
25775
|
+
const models2 = parseClaudeCachedModels(cache);
|
|
25776
|
+
const fetchedAt = Number(objectValue(cache).fetchedAt) || 0;
|
|
25777
|
+
if (models2.length && (!newest || fetchedAt > newest.fetchedAt)) newest = { fetchedAt, models: models2 };
|
|
25778
|
+
} catch {
|
|
25779
|
+
}
|
|
25780
|
+
}
|
|
25781
|
+
return newest?.models ?? [];
|
|
25708
25782
|
}
|
|
25709
25783
|
function configValue(content, key) {
|
|
25710
25784
|
const match = content.match(new RegExp(`^\\s*${key}\\s*=\\s*["']([^"']+)["']\\s*(?:#.*)?$`, "m"));
|
|
@@ -25753,13 +25827,13 @@ async function readCodexModels(codexHome3, config2) {
|
|
|
25753
25827
|
const configuredModels = parseCodexModels(await readFile3(catalogPath, "utf8").catch(() => ""));
|
|
25754
25828
|
if (configuredModels?.length) return configuredModels;
|
|
25755
25829
|
}
|
|
25756
|
-
const cached3 = parseCodexModels(await readFile3(
|
|
25830
|
+
const cached3 = parseCodexModels(await readFile3(join10(codexHome3, "models_cache.json"), "utf8").catch(() => ""));
|
|
25757
25831
|
if (cached3?.length) return cached3;
|
|
25758
25832
|
return codexModelsFrom(await codexBundledCatalog().catch(() => void 0), { listedOnly: true }) ?? [];
|
|
25759
25833
|
}
|
|
25760
25834
|
async function readCodexModelCatalog() {
|
|
25761
25835
|
const home = codexHome2();
|
|
25762
|
-
const config2 = await readFile3(
|
|
25836
|
+
const config2 = await readFile3(join10(home, "config.toml"), "utf8").catch(() => "");
|
|
25763
25837
|
const models2 = await readCodexModels(home, config2);
|
|
25764
25838
|
const defaultModel = configValue(config2, "model");
|
|
25765
25839
|
const defaultReasoningEffort = configValue(config2, "model_reasoning_effort");
|
|
@@ -25873,7 +25947,7 @@ async function readKiroModelCatalog(options = {}) {
|
|
|
25873
25947
|
if (current) return known.catalog;
|
|
25874
25948
|
try {
|
|
25875
25949
|
const launch = launchCli({ spec: kiro, args: ["acp", "--trust-tools="], env: environment });
|
|
25876
|
-
const catalog = await readKiroNativeModels(launch,
|
|
25950
|
+
const catalog = await readKiroNativeModels(launch, homedir7(), { catalog: base });
|
|
25877
25951
|
kiroEfforts = { signature, readAt: Date.now(), catalog };
|
|
25878
25952
|
return catalog;
|
|
25879
25953
|
} catch {
|
|
@@ -25882,7 +25956,7 @@ async function readKiroModelCatalog(options = {}) {
|
|
|
25882
25956
|
};
|
|
25883
25957
|
const [payload, content] = await Promise.all([
|
|
25884
25958
|
readEfforts(),
|
|
25885
|
-
readFile3(
|
|
25959
|
+
readFile3(join10(kiroHome(), "settings", "cli.json"), "utf8").catch(() => "{}")
|
|
25886
25960
|
]);
|
|
25887
25961
|
let settings;
|
|
25888
25962
|
try {
|
|
@@ -25939,7 +26013,7 @@ function geminiModelsUrl(baseUrl) {
|
|
|
25939
26013
|
}
|
|
25940
26014
|
async function readGeminiModelCatalog() {
|
|
25941
26015
|
const fileEnvironment = parseEnvFile(
|
|
25942
|
-
await readFile3(
|
|
26016
|
+
await readFile3(join10(geminiHome(), ".env"), "utf8").catch(() => "")
|
|
25943
26017
|
);
|
|
25944
26018
|
const environment = { ...fileEnvironment, ...process.env };
|
|
25945
26019
|
const baseUrl = environment.GOOGLE_GEMINI_BASE_URL?.trim();
|
|
@@ -25984,7 +26058,7 @@ function parseGrokModelCatalog(output2, config2 = "", fetchedAt = (/* @__PURE__
|
|
|
25984
26058
|
return catalog;
|
|
25985
26059
|
}
|
|
25986
26060
|
async function readGrokModelCatalog() {
|
|
25987
|
-
const config2 = await readFile3(
|
|
26061
|
+
const config2 = await readFile3(join10(grokHome(), "config.toml"), "utf8").catch(() => "");
|
|
25988
26062
|
const output2 = await runModelListCommand(cliExecutable("grok"), ["models"], "grok");
|
|
25989
26063
|
const catalog = parseGrokModelCatalog(output2, config2);
|
|
25990
26064
|
if (catalog.models.length === 0) throw new Error("Grok \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
|
|
@@ -26003,7 +26077,7 @@ function parseOpencodeModelCatalog(output2, config2 = "", fetchedAt = (/* @__PUR
|
|
|
26003
26077
|
return catalog;
|
|
26004
26078
|
}
|
|
26005
26079
|
async function readOpencodeModelCatalog() {
|
|
26006
|
-
const config2 = await readFile3(
|
|
26080
|
+
const config2 = await readFile3(join10(opencodeHome(), "opencode.json"), "utf8").catch(() => "") || await readFile3(join10(opencodeHome(), "opencode.jsonc"), "utf8").catch(() => "");
|
|
26007
26081
|
const output2 = await runModelListCommand(cliExecutable("opencode"), ["models"], "opencode");
|
|
26008
26082
|
const catalog = parseOpencodeModelCatalog(output2, config2);
|
|
26009
26083
|
if (catalog.models.length === 0) throw new Error("OpenCode \u672C\u673A\u672A\u8FD4\u56DE\u53EF\u7528\u6A21\u578B");
|
|
@@ -26011,22 +26085,22 @@ async function readOpencodeModelCatalog() {
|
|
|
26011
26085
|
}
|
|
26012
26086
|
var TEN_MINUTES = 10 * 60 * 1e3;
|
|
26013
26087
|
var MODEL_SOURCES = {
|
|
26014
|
-
claude: { read: readClaudeModelCatalog, watchFiles: () => [
|
|
26088
|
+
claude: { read: readClaudeModelCatalog, watchFiles: () => [join10(claudeHome(), "settings.json"), join10(claudeHome(), "cache", "model-catalog")] },
|
|
26015
26089
|
codex: {
|
|
26016
26090
|
read: readCodexModelCatalog,
|
|
26017
26091
|
watchFiles: () => {
|
|
26018
26092
|
const home = codexHome2();
|
|
26019
|
-
return [
|
|
26093
|
+
return [join10(home, "config.toml"), join10(home, "models_cache.json")];
|
|
26020
26094
|
},
|
|
26021
26095
|
// model_catalog_json may point anywhere; a periodic re-read covers it.
|
|
26022
26096
|
refreshEveryMs: TEN_MINUTES
|
|
26023
26097
|
},
|
|
26024
|
-
gemini: { read: readGeminiModelCatalog, watchFiles: () => [
|
|
26025
|
-
grok: { read: readGrokModelCatalog, watchFiles: () => [
|
|
26026
|
-
kiro: { read: readKiroModelCatalog, watchFiles: () => [
|
|
26098
|
+
gemini: { read: readGeminiModelCatalog, watchFiles: () => [join10(geminiHome(), ".env")], refreshEveryMs: TEN_MINUTES },
|
|
26099
|
+
grok: { read: readGrokModelCatalog, watchFiles: () => [join10(grokHome(), "config.toml")], refreshEveryMs: TEN_MINUTES },
|
|
26100
|
+
kiro: { read: readKiroModelCatalog, watchFiles: () => [join10(kiroHome(), "settings", "cli.json")] },
|
|
26027
26101
|
opencode: {
|
|
26028
26102
|
read: readOpencodeModelCatalog,
|
|
26029
|
-
watchFiles: () => [
|
|
26103
|
+
watchFiles: () => [join10(opencodeHome(), "opencode.json"), join10(opencodeHome(), "opencode.jsonc")],
|
|
26030
26104
|
refreshEveryMs: TEN_MINUTES
|
|
26031
26105
|
}
|
|
26032
26106
|
};
|
|
@@ -26139,12 +26213,12 @@ function classifySpawnError(error62, context) {
|
|
|
26139
26213
|
}
|
|
26140
26214
|
|
|
26141
26215
|
// src/providers/cli/kiro-session-log.ts
|
|
26142
|
-
import { open as open2, readdir, readFile as readFile4, stat as stat2 } from "node:fs/promises";
|
|
26143
|
-
import { homedir as
|
|
26144
|
-
import { join as
|
|
26216
|
+
import { open as open2, readdir as readdir2, readFile as readFile4, stat as stat2 } from "node:fs/promises";
|
|
26217
|
+
import { homedir as homedir8 } from "node:os";
|
|
26218
|
+
import { join as join11 } from "node:path";
|
|
26145
26219
|
var SHELL_TOOLS = /* @__PURE__ */ new Set(["shell", "execute_bash", "bash"]);
|
|
26146
26220
|
function kiroSessionsDirectory() {
|
|
26147
|
-
return process.env.TOC_OCRA_KIRO_SESSIONS_DIR ||
|
|
26221
|
+
return process.env.TOC_OCRA_KIRO_SESSIONS_DIR || join11(homedir8(), ".kiro", "sessions", "cli");
|
|
26148
26222
|
}
|
|
26149
26223
|
var KiroSessionLog = class {
|
|
26150
26224
|
constructor(options) {
|
|
@@ -26163,7 +26237,7 @@ var KiroSessionLog = class {
|
|
|
26163
26237
|
/** Called before the CLI starts: a resumed log is followed from its current end. */
|
|
26164
26238
|
async begin() {
|
|
26165
26239
|
if (!this.options.sessionId) return;
|
|
26166
|
-
this.path =
|
|
26240
|
+
this.path = join11(this.directory, `${this.options.sessionId}.jsonl`);
|
|
26167
26241
|
this.offset = await stat2(this.path).then((info) => info.size, () => 0);
|
|
26168
26242
|
}
|
|
26169
26243
|
/**
|
|
@@ -26172,15 +26246,15 @@ var KiroSessionLog = class {
|
|
|
26172
26246
|
* in the same folder) leave it unknown.
|
|
26173
26247
|
*/
|
|
26174
26248
|
async findFreshLog() {
|
|
26175
|
-
const names = await
|
|
26249
|
+
const names = await readdir2(this.directory).catch(() => []);
|
|
26176
26250
|
const found = [];
|
|
26177
26251
|
for (const name of names) {
|
|
26178
26252
|
if (!name.endsWith(".json")) continue;
|
|
26179
|
-
const meta3 = await readFile4(
|
|
26253
|
+
const meta3 = await readFile4(join11(this.directory, name), "utf8").then((text3) => JSON.parse(text3), () => void 0);
|
|
26180
26254
|
const created = meta3?.created_at ? Date.parse(meta3.created_at) : NaN;
|
|
26181
26255
|
if (meta3?.cwd && sameFolder(meta3.cwd, this.options.workdir) && created >= this.options.startedAt - 2e3) found.push(name.slice(0, -5));
|
|
26182
26256
|
}
|
|
26183
|
-
if (found.length === 1) this.path =
|
|
26257
|
+
if (found.length === 1) this.path = join11(this.directory, `${found[0]}.jsonl`);
|
|
26184
26258
|
}
|
|
26185
26259
|
/** Reads entries appended since the last call. */
|
|
26186
26260
|
async refresh() {
|
|
@@ -26549,9 +26623,9 @@ var OPENCODE_ACP_DIALECT = {
|
|
|
26549
26623
|
// src/acp/vendor.ts
|
|
26550
26624
|
import { spawn as spawn6 } from "node:child_process";
|
|
26551
26625
|
import { createHash } from "node:crypto";
|
|
26552
|
-
import { existsSync as
|
|
26626
|
+
import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
|
|
26553
26627
|
import { copyFile, mkdir as mkdir4, rename as rename4, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
|
|
26554
|
-
import { dirname as dirname6, join as
|
|
26628
|
+
import { dirname as dirname6, join as join12, resolve as resolve4 } from "node:path";
|
|
26555
26629
|
import { fileURLToPath } from "node:url";
|
|
26556
26630
|
var AcpRuntimeUnavailable = class extends Error {
|
|
26557
26631
|
constructor(message) {
|
|
@@ -26564,7 +26638,7 @@ function packageRoot() {
|
|
|
26564
26638
|
let directory = dirname6(fileURLToPath(import.meta.url));
|
|
26565
26639
|
while (true) {
|
|
26566
26640
|
const path = resolve4(directory, "package.json");
|
|
26567
|
-
if (
|
|
26641
|
+
if (existsSync5(path)) {
|
|
26568
26642
|
try {
|
|
26569
26643
|
if (JSON.parse(readFileSync4(path, "utf8")).name === "toc-ocra") return directory;
|
|
26570
26644
|
} catch {
|
|
@@ -26584,21 +26658,21 @@ function agentPackageVersion() {
|
|
|
26584
26658
|
const directory = agentRoot();
|
|
26585
26659
|
if (!directory) return "0";
|
|
26586
26660
|
try {
|
|
26587
|
-
return JSON.parse(readFileSync4(
|
|
26661
|
+
return JSON.parse(readFileSync4(join12(directory, "package.json"), "utf8")).version ?? "0";
|
|
26588
26662
|
} catch {
|
|
26589
26663
|
return "0";
|
|
26590
26664
|
}
|
|
26591
26665
|
}
|
|
26592
26666
|
function vendoredAdapter(name) {
|
|
26593
26667
|
const directory = agentRoot();
|
|
26594
|
-
const entry = directory ?
|
|
26595
|
-
return entry &&
|
|
26668
|
+
const entry = directory ? join12(directory, "assets", "acp", name, "index.mjs") : void 0;
|
|
26669
|
+
return entry && existsSync5(entry) ? entry : void 0;
|
|
26596
26670
|
}
|
|
26597
26671
|
var installs = /* @__PURE__ */ new Map();
|
|
26598
26672
|
function ensureClaudeRuntime(dataDir2) {
|
|
26599
26673
|
const entry = vendoredAdapter("claude");
|
|
26600
26674
|
if (!entry) return Promise.reject(new AcpRuntimeUnavailable("\u8FD9\u4E2A\u7248\u672C\u7684\u8BBE\u5907\u4EE3\u7406\u6CA1\u6709\u9644\u5E26 Claude ACP \u9002\u914D\u5668"));
|
|
26601
|
-
const manifestPath =
|
|
26675
|
+
const manifestPath = join12(dirname6(entry), "runtime.json");
|
|
26602
26676
|
let manifest;
|
|
26603
26677
|
try {
|
|
26604
26678
|
manifest = JSON.parse(readFileSync4(manifestPath, "utf8"));
|
|
@@ -26606,7 +26680,7 @@ function ensureClaudeRuntime(dataDir2) {
|
|
|
26606
26680
|
return Promise.reject(new AcpRuntimeUnavailable("Claude ACP \u9002\u914D\u5668\u7F3A\u5C11 runtime.json"));
|
|
26607
26681
|
}
|
|
26608
26682
|
const hash2 = createHash("sha256").update(readFileSync4(entry)).digest("hex").slice(0, 12);
|
|
26609
|
-
const directory =
|
|
26683
|
+
const directory = join12(dataDir2, "acp-runtimes", `claude-${manifest.adapterVersion}-sdk-${manifest.sdk.version}-${hash2}`);
|
|
26610
26684
|
const existing = installs.get(directory);
|
|
26611
26685
|
if (existing) return existing;
|
|
26612
26686
|
const install = installClaudeRuntime(directory, entry, manifest).catch((error62) => {
|
|
@@ -26617,19 +26691,19 @@ function ensureClaudeRuntime(dataDir2) {
|
|
|
26617
26691
|
return install;
|
|
26618
26692
|
}
|
|
26619
26693
|
async function installClaudeRuntime(directory, entry, manifest) {
|
|
26620
|
-
const sdkPackage =
|
|
26621
|
-
if (
|
|
26694
|
+
const sdkPackage = join12(directory, "node_modules", ...manifest.sdk.name.split("/"), "package.json");
|
|
26695
|
+
if (existsSync5(sdkPackage) && existsSync5(join12(directory, "index.mjs"))) return directory;
|
|
26622
26696
|
const temporary = `${directory}.tmp-${process.pid}-${Date.now()}`;
|
|
26623
26697
|
await mkdir4(temporary, { recursive: true, mode: 448 });
|
|
26624
26698
|
try {
|
|
26625
|
-
await writeFile4(
|
|
26699
|
+
await writeFile4(join12(temporary, "package.json"), JSON.stringify({
|
|
26626
26700
|
name: "toc-ocra-claude-acp-runtime",
|
|
26627
26701
|
private: true,
|
|
26628
26702
|
type: "module",
|
|
26629
26703
|
dependencies: { [manifest.sdk.name]: manifest.sdk.version }
|
|
26630
26704
|
}, null, 2));
|
|
26631
26705
|
await runNpm(["install", "--omit=optional", "--no-audit", "--no-fund", "--no-package-lock", "--loglevel=error"], temporary);
|
|
26632
|
-
await copyFile(entry,
|
|
26706
|
+
await copyFile(entry, join12(temporary, "index.mjs"));
|
|
26633
26707
|
await rm2(directory, { recursive: true, force: true });
|
|
26634
26708
|
await rename4(temporary, directory);
|
|
26635
26709
|
} catch (error62) {
|
|
@@ -26752,13 +26826,15 @@ var CLAUDE_LAUNCH_SPEC = {
|
|
|
26752
26826
|
const executable = installedCli(claude);
|
|
26753
26827
|
const runtime = await ensureClaudeRuntime(dataDir2);
|
|
26754
26828
|
return {
|
|
26755
|
-
launch: { executable: process.execPath, args: [
|
|
26829
|
+
launch: { executable: process.execPath, args: [join13(runtime, "index.mjs")], env: { ...providerEnvironment(), CLAUDE_CODE_EXECUTABLE: executable }, cwd: workdir },
|
|
26756
26830
|
fingerprint: `claude:${runtime}:${executable}`
|
|
26757
26831
|
};
|
|
26758
26832
|
},
|
|
26759
26833
|
// Manual mode asks for every edit and command; the user or the level's policy answers.
|
|
26760
26834
|
permissionModeConfig: { values: { ask: "default", acceptEdits: "acceptEdits", bypassPermissions: "bypassPermissions", plan: "plan" } },
|
|
26761
26835
|
resumePreference: "resume",
|
|
26836
|
+
// The adapter accepts `session/resume` of a conversation Claude no longer has; only the prompt fails.
|
|
26837
|
+
resumable: (sessionId) => claudeSessionSaved(sessionId, providerEnvironment()),
|
|
26762
26838
|
dialect: { failureRules: [{ kind: "sessionMissing", pattern: /No conversation found with session ID|session[^\n]{0,40}not found/i }] },
|
|
26763
26839
|
modelDiscovery: { kind: "reader", source: MODEL_SOURCES.claude }
|
|
26764
26840
|
};
|
|
@@ -26869,7 +26945,7 @@ var ACP_CHAT_IDS = [...ACP_CHAT.keys()];
|
|
|
26869
26945
|
// src/acp/acp-model-catalog-probe.ts
|
|
26870
26946
|
import { mkdtemp, rm as rm3 } from "node:fs/promises";
|
|
26871
26947
|
import { tmpdir } from "node:os";
|
|
26872
|
-
import { join as
|
|
26948
|
+
import { join as join14 } from "node:path";
|
|
26873
26949
|
|
|
26874
26950
|
// src/acp/acp-options.ts
|
|
26875
26951
|
var text = (value) => typeof value === "string" && value ? value : void 0;
|
|
@@ -27502,9 +27578,9 @@ async function readSessionModels(row, clientVersion = "1") {
|
|
|
27502
27578
|
const discovery = row.modelDiscovery;
|
|
27503
27579
|
if (discovery.kind !== "session") throw new Error(`${row.agent} does not list its models in a session`);
|
|
27504
27580
|
const cli = requireCliSpec(row.agent);
|
|
27505
|
-
const folder = await mkdtemp(
|
|
27581
|
+
const folder = await mkdtemp(join14(tmpdir(), `toc-ocra-acp-models-${row.agent}-`));
|
|
27506
27582
|
try {
|
|
27507
|
-
const folderArgs = discovery.sessionFolderArgs?.(
|
|
27583
|
+
const folderArgs = discovery.sessionFolderArgs?.(join14(folder, "sessions")) ?? [];
|
|
27508
27584
|
const args = [...row.args({ access: "read-only", model: "", reasoningEffort: "" }), ...folderArgs];
|
|
27509
27585
|
const launch = launchCli({ spec: cli, args, env: { ...providerEnvironment(), ...row.env } });
|
|
27510
27586
|
const connection = await AcpConnection.open({ executable: launch.executable, args: launch.args, env: launch.env, cwd: folder }, {
|
|
@@ -28133,14 +28209,14 @@ function isWriterConflict(message) {
|
|
|
28133
28209
|
}
|
|
28134
28210
|
|
|
28135
28211
|
// src/providers/cli/claude.ts
|
|
28136
|
-
import { readdirSync as
|
|
28137
|
-
import { homedir as
|
|
28138
|
-
import { join as
|
|
28212
|
+
import { readdirSync as readdirSync4, readFileSync as readFileSync5 } from "node:fs";
|
|
28213
|
+
import { homedir as homedir9 } from "node:os";
|
|
28214
|
+
import { join as join15 } from "node:path";
|
|
28139
28215
|
var CLAUDE = requireCliSpec("claude");
|
|
28140
28216
|
function claudeProjectRoots() {
|
|
28141
28217
|
const configured = process.env.CLAUDE_CONFIG_DIR;
|
|
28142
|
-
const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [
|
|
28143
|
-
return dirs.map((dir) =>
|
|
28218
|
+
const dirs = configured ? configured.split(process.platform === "win32" ? ";" : ":").map((entry) => entry.trim()).filter(Boolean) : [join15(homedir9(), ".claude")];
|
|
28219
|
+
return dirs.map((dir) => join15(dir, "projects"));
|
|
28144
28220
|
}
|
|
28145
28221
|
function claudeTranscriptExists(sessionId) {
|
|
28146
28222
|
return claudeTranscriptPath(sessionId) !== void 0;
|
|
@@ -28150,13 +28226,13 @@ function claudeTranscriptPath(sessionId) {
|
|
|
28150
28226
|
for (const root2 of claudeProjectRoots()) {
|
|
28151
28227
|
let projects;
|
|
28152
28228
|
try {
|
|
28153
|
-
projects =
|
|
28229
|
+
projects = readdirSync4(root2);
|
|
28154
28230
|
} catch {
|
|
28155
28231
|
continue;
|
|
28156
28232
|
}
|
|
28157
28233
|
for (const project of projects) {
|
|
28158
28234
|
try {
|
|
28159
|
-
if (
|
|
28235
|
+
if (readdirSync4(join15(root2, project)).includes(file2)) return join15(root2, project, file2);
|
|
28160
28236
|
} catch {
|
|
28161
28237
|
}
|
|
28162
28238
|
}
|
|
@@ -28200,7 +28276,7 @@ var claudeProvider = {
|
|
|
28200
28276
|
settings.disableAllHooks = true;
|
|
28201
28277
|
args.push("--restricted", "--permission-mode", "plan", "--tools", "Read,Glob,Grep", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--disallowedTools", "mcp__*");
|
|
28202
28278
|
try {
|
|
28203
|
-
const userSettings = JSON.parse(readFileSync5(
|
|
28279
|
+
const userSettings = JSON.parse(readFileSync5(join15(homedir9(), ".claude", "settings.json"), "utf8"));
|
|
28204
28280
|
for (const [key, value] of Object.entries(userSettings.env ?? {})) {
|
|
28205
28281
|
if (/^ANTHROPIC_[A-Z0-9_]+$/.test(key) && typeof value === "string" && env[key] === void 0) env[key] = value;
|
|
28206
28282
|
}
|
|
@@ -29010,6 +29086,82 @@ var opencodeProvider = {
|
|
|
29010
29086
|
}
|
|
29011
29087
|
};
|
|
29012
29088
|
|
|
29089
|
+
// src/providers/claude-quota.ts
|
|
29090
|
+
import { execFile as execFile5 } from "node:child_process";
|
|
29091
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
29092
|
+
import { homedir as homedir10 } from "node:os";
|
|
29093
|
+
import { join as join16 } from "node:path";
|
|
29094
|
+
import { promisify as promisify3 } from "node:util";
|
|
29095
|
+
var execFileAsync3 = promisify3(execFile5);
|
|
29096
|
+
var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
29097
|
+
var WINDOWS = [
|
|
29098
|
+
{ key: "five_hour", label: "5 \u5C0F\u65F6\u989D\u5EA6", seconds: 5 * 3600 },
|
|
29099
|
+
{ key: "seven_day", label: "\u6BCF\u5468\u989D\u5EA6", seconds: 7 * 86400 },
|
|
29100
|
+
{ key: "seven_day_opus", label: "Opus \xB7 \u6BCF\u5468\u989D\u5EA6", seconds: 7 * 86400 },
|
|
29101
|
+
{ key: "seven_day_sonnet", label: "Sonnet \xB7 \u6BCF\u5468\u989D\u5EA6", seconds: 7 * 86400 }
|
|
29102
|
+
];
|
|
29103
|
+
function objectValue2(value) {
|
|
29104
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
29105
|
+
}
|
|
29106
|
+
function resetSeconds(value) {
|
|
29107
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0) return Math.floor(value > 1e10 ? value / 1e3 : value);
|
|
29108
|
+
if (typeof value === "string" && value.trim()) {
|
|
29109
|
+
const parsed = Date.parse(value);
|
|
29110
|
+
if (Number.isFinite(parsed)) return Math.floor(parsed / 1e3);
|
|
29111
|
+
}
|
|
29112
|
+
return 0;
|
|
29113
|
+
}
|
|
29114
|
+
function parseClaudeQuota(body) {
|
|
29115
|
+
const source = objectValue2(body);
|
|
29116
|
+
const windows = [];
|
|
29117
|
+
for (const { key, label, seconds } of WINDOWS) {
|
|
29118
|
+
const raw = source[key];
|
|
29119
|
+
if (!raw || typeof raw !== "object") continue;
|
|
29120
|
+
const window = objectValue2(raw);
|
|
29121
|
+
const utilization = Number(window.utilization);
|
|
29122
|
+
windows.push({
|
|
29123
|
+
key: `claude:${key}`,
|
|
29124
|
+
label,
|
|
29125
|
+
resets_at: resetSeconds(window.resets_at),
|
|
29126
|
+
window_seconds: seconds,
|
|
29127
|
+
...window.utilization !== null && Number.isFinite(utilization) && utilization >= 0 ? { used_percent: Math.min(100, Math.round(utilization * 100) / 100) } : {}
|
|
29128
|
+
});
|
|
29129
|
+
}
|
|
29130
|
+
return windows;
|
|
29131
|
+
}
|
|
29132
|
+
var claudeHome2 = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join16(homedir10(), ".claude");
|
|
29133
|
+
function tokenFrom(content) {
|
|
29134
|
+
try {
|
|
29135
|
+
const token = objectValue2(objectValue2(JSON.parse(content)).claudeAiOauth).accessToken;
|
|
29136
|
+
return typeof token === "string" && token.trim() ? token.trim() : void 0;
|
|
29137
|
+
} catch {
|
|
29138
|
+
return void 0;
|
|
29139
|
+
}
|
|
29140
|
+
}
|
|
29141
|
+
async function readClaudeAccessToken() {
|
|
29142
|
+
const fromEnv = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
|
|
29143
|
+
if (fromEnv) return fromEnv;
|
|
29144
|
+
const fromFile = tokenFrom(await readFile5(join16(claudeHome2(), ".credentials.json"), "utf8").catch(() => ""));
|
|
29145
|
+
if (fromFile) return fromFile;
|
|
29146
|
+
if (process.platform !== "darwin") return void 0;
|
|
29147
|
+
const { stdout } = await execFileAsync3("security", ["find-generic-password", "-s", "Claude Code-credentials", "-w"], { timeout: 1e4 }).catch(() => ({ stdout: "" }));
|
|
29148
|
+
return tokenFrom(String(stdout).trim());
|
|
29149
|
+
}
|
|
29150
|
+
async function readClaudeQuotaWindows() {
|
|
29151
|
+
const token = await readClaudeAccessToken();
|
|
29152
|
+
if (!token) throw new Error("Claude Code \u672A\u4F7F\u7528 Claude \u8D26\u53F7\u767B\u5F55\uFF08API Key \u65B9\u5F0F\u6CA1\u6709\u5957\u9910\u989D\u5EA6\uFF09\uFF0C\u8BF7\u5728\u672C\u673A\u8FD0\u884C claude \u5E76 /login");
|
|
29153
|
+
const response = await fetch(CLAUDE_USAGE_URL, {
|
|
29154
|
+
headers: { authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20", accept: "application/json" },
|
|
29155
|
+
redirect: "error",
|
|
29156
|
+
signal: AbortSignal.timeout(15e3)
|
|
29157
|
+
});
|
|
29158
|
+
if (response.status === 401 || response.status === 403) throw new Error("Claude Code \u767B\u5F55\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u5728\u672C\u673A\u8FD0\u884C\u4E00\u6B21 claude \u5237\u65B0\u767B\u5F55\u540E\u518D\u8BD5");
|
|
29159
|
+
if (!response.ok) throw new Error(`Claude \u989D\u5EA6\u63A5\u53E3\u8BF7\u6C42\u5931\u8D25 (${response.status})`);
|
|
29160
|
+
const windows = parseClaudeQuota(await response.json());
|
|
29161
|
+
if (!windows.length) throw new Error("Claude \u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u989D\u5EA6\u7A97\u53E3");
|
|
29162
|
+
return windows;
|
|
29163
|
+
}
|
|
29164
|
+
|
|
29013
29165
|
// src/providers/codex-quota.ts
|
|
29014
29166
|
import { spawn as spawn8 } from "node:child_process";
|
|
29015
29167
|
import { createInterface as createInterface4 } from "node:readline";
|
|
@@ -29108,10 +29260,10 @@ async function readCodexQuotaWindows() {
|
|
|
29108
29260
|
}
|
|
29109
29261
|
|
|
29110
29262
|
// src/providers/kiro-quota.ts
|
|
29111
|
-
import { execFile as
|
|
29263
|
+
import { execFile as execFile6 } from "node:child_process";
|
|
29112
29264
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
29113
|
-
import { promisify as
|
|
29114
|
-
var
|
|
29265
|
+
import { promisify as promisify4, stripVTControlCharacters } from "node:util";
|
|
29266
|
+
var execFileAsync4 = promisify4(execFile6);
|
|
29115
29267
|
var amount = (value) => Number(value.replace(/,/g, ""));
|
|
29116
29268
|
var rounded = (value) => Math.round(value * 100) / 100;
|
|
29117
29269
|
function parseKiroQuota(stdout, now = /* @__PURE__ */ new Date()) {
|
|
@@ -29171,7 +29323,7 @@ async function readKiroQuotaWindows() {
|
|
|
29171
29323
|
const launch = launchCli({ spec: requireCliSpec("kiro"), args: ["chat", "--no-interactive", "/usage"] });
|
|
29172
29324
|
await requireKiroAuthentication(launch.env);
|
|
29173
29325
|
try {
|
|
29174
|
-
const { stdout, stderr } = await
|
|
29326
|
+
const { stdout, stderr } = await execFileAsync4(launch.executable, launch.args, { env: launch.env, cwd: tmpdir2(), timeout: 3e4, maxBuffer: 1024 * 1024, windowsHide: true });
|
|
29175
29327
|
return parseKiroQuota(`${stdout}
|
|
29176
29328
|
${stderr}`);
|
|
29177
29329
|
} catch (error62) {
|
|
@@ -29184,7 +29336,7 @@ ${stderr}`);
|
|
|
29184
29336
|
var ALL_LEVELS = ["read-only", "acceptEdits", "bypassPermissions"];
|
|
29185
29337
|
var NATIVE = {
|
|
29186
29338
|
codex: { headless: codexProvider, chat: codexChatProvider, models: MODEL_SOURCES.codex, quota: readCodexQuotaWindows, runSettings: { permissionModes: ALL_LEVELS, plan: "prompt", fast: true } },
|
|
29187
|
-
claude: { headless: claudeProvider, chat: (_request, attachments) => claudeChatProvider(attachments), models: MODEL_SOURCES.claude, runSettings: { permissionModes: ALL_LEVELS, plan: "native", fast: true } }
|
|
29339
|
+
claude: { headless: claudeProvider, chat: (_request, attachments) => claudeChatProvider(attachments), models: MODEL_SOURCES.claude, quota: readClaudeQuotaWindows, runSettings: { permissionModes: ALL_LEVELS, plan: "native", fast: true } }
|
|
29188
29340
|
};
|
|
29189
29341
|
var ACP_EXTRAS = {
|
|
29190
29342
|
kiro: { quota: readKiroQuotaWindows, legacy: { headless: kiroProvider, restrictedPermission: true, runSettings: { permissionModes: ["read-only", "bypassPermissions"], plan: "prompt" } } },
|
|
@@ -29371,12 +29523,12 @@ var cliDetection = new CliDetectionService();
|
|
|
29371
29523
|
// src/smoke/cli-smoke.ts
|
|
29372
29524
|
import { mkdtemp as mkdtemp2, realpath as realpath3, rm as rm5 } from "node:fs/promises";
|
|
29373
29525
|
import { tmpdir as tmpdir3 } from "node:os";
|
|
29374
|
-
import { join as
|
|
29526
|
+
import { join as join21 } from "node:path";
|
|
29375
29527
|
|
|
29376
29528
|
// src/runs/run-supervisor.ts
|
|
29377
29529
|
import { spawn as spawn11 } from "node:child_process";
|
|
29378
29530
|
import { mkdir as mkdir7, realpath as realpath2, stat as stat5, writeFile as writeFile7 } from "node:fs/promises";
|
|
29379
|
-
import { basename as basename2, isAbsolute as isAbsolute4, join as
|
|
29531
|
+
import { basename as basename2, isAbsolute as isAbsolute4, join as join20, relative as relative2, resolve as resolve5 } from "node:path";
|
|
29380
29532
|
import { createInterface as createInterface6 } from "node:readline";
|
|
29381
29533
|
|
|
29382
29534
|
// src/providers/chat/index.ts
|
|
@@ -29745,19 +29897,19 @@ async function forkCodexThread(options) {
|
|
|
29745
29897
|
|
|
29746
29898
|
// src/runs/run-recorder.ts
|
|
29747
29899
|
import { appendFileSync, mkdirSync as mkdirSync2 } from "node:fs";
|
|
29748
|
-
import { homedir as
|
|
29749
|
-
import { join as
|
|
29900
|
+
import { homedir as homedir11 } from "node:os";
|
|
29901
|
+
import { join as join17 } from "node:path";
|
|
29750
29902
|
var RunRecorder = class _RunRecorder {
|
|
29751
29903
|
constructor(path) {
|
|
29752
29904
|
this.path = path;
|
|
29753
29905
|
}
|
|
29754
29906
|
path;
|
|
29755
|
-
home =
|
|
29907
|
+
home = homedir11();
|
|
29756
29908
|
static fromEnvironment(runId, meta3) {
|
|
29757
29909
|
const directory = process.env.TOC_OCRA_RECORD_DIR?.trim();
|
|
29758
29910
|
if (!directory) return void 0;
|
|
29759
29911
|
mkdirSync2(directory, { recursive: true });
|
|
29760
|
-
const recorder = new _RunRecorder(
|
|
29912
|
+
const recorder = new _RunRecorder(join17(directory, `${String(meta3.agent ?? "cli")}-${runId}.jsonl`));
|
|
29761
29913
|
recorder.write({ meta: meta3 });
|
|
29762
29914
|
return recorder;
|
|
29763
29915
|
}
|
|
@@ -29772,8 +29924,8 @@ var RunRecorder = class _RunRecorder {
|
|
|
29772
29924
|
};
|
|
29773
29925
|
|
|
29774
29926
|
// src/runs/run-transcript.ts
|
|
29775
|
-
import { chmod as chmod4, mkdir as mkdir5, readdir as
|
|
29776
|
-
import { join as
|
|
29927
|
+
import { chmod as chmod4, mkdir as mkdir5, readdir as readdir3, readFile as readFile6, rename as rename5, stat as stat3, unlink, writeFile as writeFile5 } from "node:fs/promises";
|
|
29928
|
+
import { join as join18 } from "node:path";
|
|
29777
29929
|
var MAX_TRANSCRIPT_ITEMS = 5e3;
|
|
29778
29930
|
var MAX_TRANSCRIPT_TEXT = 2e5;
|
|
29779
29931
|
var MAX_TRANSCRIPT_LINES = 2e4;
|
|
@@ -30038,7 +30190,7 @@ function transcriptFileName(runId) {
|
|
|
30038
30190
|
var TranscriptStore = class {
|
|
30039
30191
|
constructor(dataDir2, logger, env = process.env) {
|
|
30040
30192
|
this.logger = logger;
|
|
30041
|
-
this.directory = dataDir2 ?
|
|
30193
|
+
this.directory = dataDir2 ? join18(dataDir2, "transcripts") : "";
|
|
30042
30194
|
this.enabled = Boolean(dataDir2) && transcriptsOnDisk(env);
|
|
30043
30195
|
}
|
|
30044
30196
|
logger;
|
|
@@ -30093,7 +30245,7 @@ var TranscriptStore = class {
|
|
|
30093
30245
|
await this.writes.get(runId);
|
|
30094
30246
|
let text3;
|
|
30095
30247
|
try {
|
|
30096
|
-
text3 = await
|
|
30248
|
+
text3 = await readFile6(join18(this.directory, name), "utf8");
|
|
30097
30249
|
} catch (error62) {
|
|
30098
30250
|
if (errorCode(error62) !== "ENOENT") this.logger.warn("run-transcript-read-failed", { runId, error: errorMessage(error62) });
|
|
30099
30251
|
return void 0;
|
|
@@ -30158,7 +30310,7 @@ var TranscriptStore = class {
|
|
|
30158
30310
|
transcript.dirty = false;
|
|
30159
30311
|
const body = JSON.stringify(transcript.toFile());
|
|
30160
30312
|
await this.ensureDirectory();
|
|
30161
|
-
const file2 =
|
|
30313
|
+
const file2 = join18(this.directory, name);
|
|
30162
30314
|
const temporary = `${file2}.${process.pid}.tmp`;
|
|
30163
30315
|
await writeFile5(temporary, body, { mode: 384 });
|
|
30164
30316
|
await rename5(temporary, file2);
|
|
@@ -30187,7 +30339,7 @@ var TranscriptStore = class {
|
|
|
30187
30339
|
async pruneOnce() {
|
|
30188
30340
|
let names;
|
|
30189
30341
|
try {
|
|
30190
|
-
names = await
|
|
30342
|
+
names = await readdir3(this.directory);
|
|
30191
30343
|
} catch (error62) {
|
|
30192
30344
|
if (errorCode(error62) === "ENOENT") return;
|
|
30193
30345
|
throw error62;
|
|
@@ -30195,7 +30347,7 @@ var TranscriptStore = class {
|
|
|
30195
30347
|
const now = Date.now();
|
|
30196
30348
|
const files = [];
|
|
30197
30349
|
for (const name of names) {
|
|
30198
|
-
const path =
|
|
30350
|
+
const path = join18(this.directory, name);
|
|
30199
30351
|
if (name.endsWith(".tmp")) {
|
|
30200
30352
|
const info2 = await stat3(path).catch(() => void 0);
|
|
30201
30353
|
if (info2?.isFile() && now - info2.mtimeMs > STALE_TEMPORARY_MS) await unlink(path).catch(() => void 0);
|
|
@@ -30245,7 +30397,7 @@ function errorMessage(error62) {
|
|
|
30245
30397
|
import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
|
|
30246
30398
|
import { constants as constants2 } from "node:fs";
|
|
30247
30399
|
import { lstat, mkdir as mkdir6, open as open3, realpath, rename as rename6, rm as rm4, writeFile as writeFile6 } from "node:fs/promises";
|
|
30248
|
-
import { basename, isAbsolute as isAbsolute3, join as
|
|
30400
|
+
import { basename, isAbsolute as isAbsolute3, join as join19, relative } from "node:path";
|
|
30249
30401
|
function within(root2, path) {
|
|
30250
30402
|
const segment = relative(root2, path);
|
|
30251
30403
|
return segment === "" || !segment.startsWith("..") && !isAbsolute3(segment);
|
|
@@ -30253,7 +30405,7 @@ function within(root2, path) {
|
|
|
30253
30405
|
async function attachmentDirectory(workdir, messageId) {
|
|
30254
30406
|
let directory = workdir;
|
|
30255
30407
|
for (const segment of [".echo", "attachments", `message-${encodeURIComponent(messageId).slice(0, 180)}`]) {
|
|
30256
|
-
directory =
|
|
30408
|
+
directory = join19(directory, segment);
|
|
30257
30409
|
await mkdir6(directory, { mode: 448 }).catch((error62) => {
|
|
30258
30410
|
if (error62.code !== "EEXIST") throw error62;
|
|
30259
30411
|
});
|
|
@@ -30261,7 +30413,7 @@ async function attachmentDirectory(workdir, messageId) {
|
|
|
30261
30413
|
if (metadata.isSymbolicLink() || !metadata.isDirectory() || !within(workdir, await realpath(directory))) {
|
|
30262
30414
|
throw new Error("\u9644\u4EF6\u76EE\u5F55\u5FC5\u987B\u4F4D\u4E8E CLI \u5DE5\u4F5C\u76EE\u5F55\u5185\uFF0C\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5");
|
|
30263
30415
|
}
|
|
30264
|
-
if (segment === ".echo") await writeFile6(
|
|
30416
|
+
if (segment === ".echo") await writeFile6(join19(directory, ".gitignore"), "*\n", { flag: "wx", mode: 384 }).catch((error62) => {
|
|
30265
30417
|
if (error62.code !== "EEXIST") throw error62;
|
|
30266
30418
|
});
|
|
30267
30419
|
}
|
|
@@ -30298,9 +30450,9 @@ async function prepareTaskAttachments(payload, workdir, download, signal2) {
|
|
|
30298
30450
|
const characters = Array.from(basename(file2.name.replace(/\\/g, "/")).replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/\.+$/u, ""));
|
|
30299
30451
|
while (Buffer.byteLength(characters.join("")) > 160) characters.shift();
|
|
30300
30452
|
const name = characters.join("") || "attachment";
|
|
30301
|
-
const path =
|
|
30453
|
+
const path = join19(directory, `${file2.file_id}-${name}`);
|
|
30302
30454
|
if (!await matches(path, file2.size, file2.sha256, signal2)) {
|
|
30303
|
-
const temporary =
|
|
30455
|
+
const temporary = join19(directory, `.download-${file2.file_id}-${randomUUID2()}.part`);
|
|
30304
30456
|
try {
|
|
30305
30457
|
await download(payload.run_id, file2.file_id, temporary, file2.size, file2.sha256, signal2);
|
|
30306
30458
|
signal2.throwIfAborted();
|
|
@@ -30415,7 +30567,7 @@ var ChatEventForwarder = class {
|
|
|
30415
30567
|
|
|
30416
30568
|
// src/acp/chat-session.ts
|
|
30417
30569
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
30418
|
-
import { readFile as
|
|
30570
|
+
import { readFile as readFile7, stat as stat4 } from "node:fs/promises";
|
|
30419
30571
|
import { extname } from "node:path";
|
|
30420
30572
|
import { pathToFileURL } from "node:url";
|
|
30421
30573
|
|
|
@@ -30700,6 +30852,7 @@ var QUESTION_OPTIONS = [
|
|
|
30700
30852
|
{ optionId: "answer", name: "Submit answers", kind: "allow_once" },
|
|
30701
30853
|
{ optionId: "cancel", name: "Cancel", kind: "reject_once" }
|
|
30702
30854
|
];
|
|
30855
|
+
var TURN_OUTPUT = /* @__PURE__ */ new Set(["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"]);
|
|
30703
30856
|
var CANCEL_GRACE_MS = 1e4;
|
|
30704
30857
|
var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
30705
30858
|
var IMAGE_TYPES = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp" };
|
|
@@ -30732,14 +30885,15 @@ var AcpChatSession = class {
|
|
|
30732
30885
|
this.clearIdle();
|
|
30733
30886
|
this.lastUsedAt = Date.now();
|
|
30734
30887
|
const transcript = new TurnTranscript((events) => sink.events(events), (rows) => sink.rows(rows));
|
|
30735
|
-
const turn = { runId: request.runId, phase: "starting", request, transcript, sink, cancelRequested: false, loading: false, queued: [], awaiting: /* @__PURE__ */ new Map(), pending: /* @__PURE__ */ new Map(), usage: new UsageTally() };
|
|
30888
|
+
const turn = { runId: request.runId, phase: "starting", request, transcript, sink, cancelRequested: false, loading: false, queued: [], awaiting: /* @__PURE__ */ new Map(), pending: /* @__PURE__ */ new Map(), usage: new UsageTally(), output: false };
|
|
30736
30889
|
this.turn = turn;
|
|
30737
30890
|
for (const note of request.notes) transcript.note(note);
|
|
30738
30891
|
let result;
|
|
30739
30892
|
try {
|
|
30740
30893
|
result = await this.execute(turn, launch);
|
|
30741
30894
|
} catch (error62) {
|
|
30742
|
-
|
|
30895
|
+
const failure2 = this.classify(error62);
|
|
30896
|
+
result = this.startsFresh(turn, failure2) ? await this.runFresh(turn, launch) : this.failed(turn, failure2);
|
|
30743
30897
|
} finally {
|
|
30744
30898
|
if (turn.cancelTimer) clearTimeout(turn.cancelTimer);
|
|
30745
30899
|
}
|
|
@@ -30758,6 +30912,28 @@ var AcpChatSession = class {
|
|
|
30758
30912
|
this.scheduleIdle();
|
|
30759
30913
|
return result;
|
|
30760
30914
|
}
|
|
30915
|
+
/**
|
|
30916
|
+
* Whether a failed turn runs again in a new session: the saved session it
|
|
30917
|
+
* reopened turned out to be gone before the agent answered anything (Claude
|
|
30918
|
+
* Code accepts `session/resume` of a conversation it no longer has and fails
|
|
30919
|
+
* only at the prompt).
|
|
30920
|
+
*/
|
|
30921
|
+
startsFresh(turn, failure2) {
|
|
30922
|
+
return Boolean(turn.reopened) && !turn.output && !turn.cancelRequested && failure2.kind === "sessionMissing";
|
|
30923
|
+
}
|
|
30924
|
+
async runFresh(turn, launch) {
|
|
30925
|
+
turn.transcript.note(`\u539F\u4F1A\u8BDD ${turn.reopened} \u5DF2\u65E0\u6CD5\u7EE7\u7EED\uFF0C\u672C\u8F6E\u5F00\u59CB\u65B0\u4F1A\u8BDD`);
|
|
30926
|
+
this.deps.logger.info("acp-session-missing-restart", { session: this.key, sessionId: turn.reopened });
|
|
30927
|
+
turn.request = { ...turn.request, sessionId: "" };
|
|
30928
|
+
turn.reopened = void 0;
|
|
30929
|
+
turn.phase = "starting";
|
|
30930
|
+
this.session = void 0;
|
|
30931
|
+
try {
|
|
30932
|
+
return await this.execute(turn, launch);
|
|
30933
|
+
} catch (error62) {
|
|
30934
|
+
return this.failed(turn, this.classify(error62));
|
|
30935
|
+
}
|
|
30936
|
+
}
|
|
30761
30937
|
/** Stops the running turn: `session/cancel`, then the process if the agent does not stop. */
|
|
30762
30938
|
cancel() {
|
|
30763
30939
|
const turn = this.turn;
|
|
@@ -30943,6 +31119,7 @@ var AcpChatSession = class {
|
|
|
30943
31119
|
transcript.note(`\u4F1A\u8BDD ${wanted} \u5DF2\u53D6\u6D88\u5F52\u6863`);
|
|
30944
31120
|
this.session = await connection.openSaved(wanted, request.workdir, reopen);
|
|
30945
31121
|
}
|
|
31122
|
+
turn.reopened = wanted;
|
|
30946
31123
|
transcript.note(`\u7EE7\u7EED\u4F1A\u8BDD ${wanted}`);
|
|
30947
31124
|
return this.session;
|
|
30948
31125
|
} catch (error62) {
|
|
@@ -30998,7 +31175,7 @@ var AcpChatSession = class {
|
|
|
30998
31175
|
if (file2.kind === "image" && mimeType && connection.imagePrompts) {
|
|
30999
31176
|
const size = await stat4(file2.path).then((info) => info.size).catch(() => 0);
|
|
31000
31177
|
if (size > 0 && size <= MAX_IMAGE_BYTES) {
|
|
31001
|
-
blocks.push({ type: "image", mimeType, data: (await
|
|
31178
|
+
blocks.push({ type: "image", mimeType, data: (await readFile7(file2.path)).toString("base64") });
|
|
31002
31179
|
continue;
|
|
31003
31180
|
}
|
|
31004
31181
|
}
|
|
@@ -31016,6 +31193,7 @@ var AcpChatSession = class {
|
|
|
31016
31193
|
const sessionLevel = kind === "available_commands_update" || kind === "current_mode_update" || kind === "config_option_update";
|
|
31017
31194
|
if (this.session ? sessionId !== this.session.sessionId : !sessionLevel) return;
|
|
31018
31195
|
if (turn.loading && !sessionLevel) return;
|
|
31196
|
+
if (typeof kind === "string" && TURN_OUTPUT.has(kind)) turn.output = true;
|
|
31019
31197
|
const normalize = this.spec.dialect?.normalizeToolUpdate;
|
|
31020
31198
|
turn.transcript.update(normalize && (kind === "tool_call" || kind === "tool_call_update") ? normalize(update2) : update2);
|
|
31021
31199
|
}
|
|
@@ -31339,7 +31517,7 @@ var AcpChatHost = class {
|
|
|
31339
31517
|
};
|
|
31340
31518
|
|
|
31341
31519
|
// src/memory/providers.ts
|
|
31342
|
-
import { execFile as
|
|
31520
|
+
import { execFile as execFile7 } from "node:child_process";
|
|
31343
31521
|
var MemoryCreateInputSchema = external_exports.object({
|
|
31344
31522
|
id: external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/),
|
|
31345
31523
|
name: external_exports.string().trim().min(1).max(200),
|
|
@@ -31361,7 +31539,7 @@ var runNmem = (args) => {
|
|
|
31361
31539
|
const env = providerEnvironment();
|
|
31362
31540
|
const launch = resolveExecutable("nmem", args, env, process.env.TOC_OCRA_NMEM_PATH);
|
|
31363
31541
|
return new Promise((resolve10) => {
|
|
31364
|
-
|
|
31542
|
+
execFile7(launch.executable, launch.args, { env: launch.env, timeout: COMMAND_TIMEOUT_MS, maxBuffer: MAX_OUTPUT_BYTES, windowsHide: true }, (error62, stdout) => {
|
|
31365
31543
|
if (!error62) {
|
|
31366
31544
|
resolve10({ stdout: String(stdout) });
|
|
31367
31545
|
return;
|
|
@@ -32339,12 +32517,12 @@ ${PLAN_MODE_PREFIX}` : payload.prompt;
|
|
|
32339
32517
|
async prepareChatAttachments(payload) {
|
|
32340
32518
|
if (!payload.attachments?.length) return [];
|
|
32341
32519
|
if (!this.reporter.chatMedia) throw new Error("\u9644\u4EF6\u8F6C\u53D1\u672A\u914D\u7F6E");
|
|
32342
|
-
const directory =
|
|
32520
|
+
const directory = join20(this.config.dataDir, "chat-media", encodeURIComponent(payload.chat_session_id ?? payload.run_id));
|
|
32343
32521
|
await mkdir7(directory, { recursive: true, mode: 448 });
|
|
32344
32522
|
const files = [];
|
|
32345
32523
|
for (const attachment of payload.attachments) {
|
|
32346
32524
|
const name = basename2(attachment.name).replace(/[^\p{L}\p{N}._-]/gu, "_").slice(-120) || "attachment";
|
|
32347
|
-
const path =
|
|
32525
|
+
const path = join20(directory, `${encodeURIComponent(attachment.media_id)}-${name}`);
|
|
32348
32526
|
const existing = await stat5(path).catch(() => void 0);
|
|
32349
32527
|
if (!existing?.isFile()) {
|
|
32350
32528
|
const data = await this.reporter.chatMedia(payload.run_id, attachment.media_id);
|
|
@@ -32545,7 +32723,7 @@ var silent = { debug() {
|
|
|
32545
32723
|
async function runCliSmoke(options = {}) {
|
|
32546
32724
|
const detection = await cliDetection.detect(true);
|
|
32547
32725
|
const ids = options.only?.length ? options.only.map((id) => catalogEntry(id)?.id ?? id) : CLI_CATALOG.filter((entry) => entry.headless && detection.detectedIds.includes(entry.id)).map((entry) => entry.id);
|
|
32548
|
-
const root2 = await realpath3(await mkdtemp2(
|
|
32726
|
+
const root2 = await realpath3(await mkdtemp2(join21(tmpdir3(), "toc-ocra-smoke-")));
|
|
32549
32727
|
const finished = /* @__PURE__ */ new Map();
|
|
32550
32728
|
const config2 = { allowedRoots: [root2], maxConcurrentRuns: 0, maxRunSeconds: options.timeoutSeconds ?? 300, dataDir: root2 };
|
|
32551
32729
|
const supervisor = new RunSupervisor(config2, silent, {
|
|
@@ -32617,12 +32795,12 @@ async function runCliSmoke(options = {}) {
|
|
|
32617
32795
|
}
|
|
32618
32796
|
|
|
32619
32797
|
// src/runtime/run-service.ts
|
|
32620
|
-
import { existsSync as
|
|
32798
|
+
import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
|
|
32621
32799
|
import { dirname as dirname10, resolve as resolve8 } from "node:path";
|
|
32622
32800
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
32623
32801
|
|
|
32624
32802
|
// src/health/server.ts
|
|
32625
|
-
import { readFile as
|
|
32803
|
+
import { readFile as readFile8 } from "node:fs/promises";
|
|
32626
32804
|
import { createServer } from "node:http";
|
|
32627
32805
|
var ControlError = class extends Error {
|
|
32628
32806
|
constructor(status, message, code2 = "bad_request") {
|
|
@@ -32803,7 +32981,7 @@ var HealthServer = class {
|
|
|
32803
32981
|
}
|
|
32804
32982
|
async recentEvents() {
|
|
32805
32983
|
try {
|
|
32806
|
-
const raw = await
|
|
32984
|
+
const raw = await readFile8(this.logFile, "utf8");
|
|
32807
32985
|
return raw.trim().split("\n").slice(-60).flatMap((line) => {
|
|
32808
32986
|
try {
|
|
32809
32987
|
const parsed = JSON.parse(line);
|
|
@@ -32860,7 +33038,7 @@ async function readJson(request) {
|
|
|
32860
33038
|
import {
|
|
32861
33039
|
appendFileSync as appendFileSync2,
|
|
32862
33040
|
chmodSync,
|
|
32863
|
-
existsSync as
|
|
33041
|
+
existsSync as existsSync6,
|
|
32864
33042
|
mkdirSync as mkdirSync3,
|
|
32865
33043
|
readFileSync as readFileSync6,
|
|
32866
33044
|
renameSync,
|
|
@@ -32894,7 +33072,7 @@ function createDiagnosticLogger(filePath, options = {}) {
|
|
|
32894
33072
|
try {
|
|
32895
33073
|
mkdirSync3(dirname7(filePath), { recursive: true });
|
|
32896
33074
|
pruneExpired();
|
|
32897
|
-
currentBytes =
|
|
33075
|
+
currentBytes = existsSync6(filePath) ? statSync4(filePath).size : 0;
|
|
32898
33076
|
} catch {
|
|
32899
33077
|
disabled = true;
|
|
32900
33078
|
}
|
|
@@ -32904,8 +33082,8 @@ function createDiagnosticLogger(filePath, options = {}) {
|
|
|
32904
33082
|
for (let index = maxRotatedFiles; index >= 1; index -= 1) {
|
|
32905
33083
|
const source = index === 1 ? filePath : `${filePath}.${index - 1}`;
|
|
32906
33084
|
const destination = `${filePath}.${index}`;
|
|
32907
|
-
if (!
|
|
32908
|
-
if (
|
|
33085
|
+
if (!existsSync6(source)) continue;
|
|
33086
|
+
if (existsSync6(destination)) unlinkSync(destination);
|
|
32909
33087
|
renameSync(source, destination);
|
|
32910
33088
|
}
|
|
32911
33089
|
currentBytes = 0;
|
|
@@ -32919,7 +33097,7 @@ function createDiagnosticLogger(filePath, options = {}) {
|
|
|
32919
33097
|
try {
|
|
32920
33098
|
for (let index = 0; index <= maxRotatedFiles; index += 1) {
|
|
32921
33099
|
const path = index === 0 ? filePath : `${filePath}.${index}`;
|
|
32922
|
-
if (!
|
|
33100
|
+
if (!existsSync6(path)) continue;
|
|
32923
33101
|
const kept = readFileSync6(path, "utf8").split("\n").filter((line) => {
|
|
32924
33102
|
if (!line.trim()) return false;
|
|
32925
33103
|
try {
|
|
@@ -32980,7 +33158,7 @@ function createDiagnosticLogger(filePath, options = {}) {
|
|
|
32980
33158
|
|
|
32981
33159
|
// src/runtime/agent-runtime.ts
|
|
32982
33160
|
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
32983
|
-
import { join as
|
|
33161
|
+
import { join as join24 } from "node:path";
|
|
32984
33162
|
|
|
32985
33163
|
// src/exec/script-runner.ts
|
|
32986
33164
|
import { spawn as spawn12 } from "node:child_process";
|
|
@@ -33151,16 +33329,16 @@ async function readCLIQuotaReport(agentType) {
|
|
|
33151
33329
|
}
|
|
33152
33330
|
|
|
33153
33331
|
// src/providers/tb-switch-control.ts
|
|
33154
|
-
import { readFile as
|
|
33155
|
-
import { homedir as
|
|
33156
|
-
import { join as
|
|
33332
|
+
import { readFile as readFile9 } from "node:fs/promises";
|
|
33333
|
+
import { homedir as homedir12 } from "node:os";
|
|
33334
|
+
import { join as join22 } from "node:path";
|
|
33157
33335
|
function dataDir() {
|
|
33158
|
-
return process.env.TB_SWITCH_HOME?.trim() ||
|
|
33336
|
+
return process.env.TB_SWITCH_HOME?.trim() || join22(homedir12(), ".tb-switch");
|
|
33159
33337
|
}
|
|
33160
33338
|
async function readLocalService() {
|
|
33161
33339
|
let discovery;
|
|
33162
33340
|
try {
|
|
33163
|
-
discovery = JSON.parse(await
|
|
33341
|
+
discovery = JSON.parse(await readFile9(join22(dataDir(), "api.json"), "utf8"));
|
|
33164
33342
|
} catch {
|
|
33165
33343
|
throw new Error("\u8FD9\u53F0\u8BBE\u5907\u4E0A\u7684 TB Switch \u670D\u52A1\u672A\u8FD0\u884C\uFF0C\u8BF7\u6253\u5F00\u684C\u9762\u7AEF\u63D2\u4EF6\u540E\u91CD\u8BD5\u3002");
|
|
33166
33344
|
}
|
|
@@ -33176,7 +33354,7 @@ async function readLocalService() {
|
|
|
33176
33354
|
}
|
|
33177
33355
|
let token = process.env.TB_SWITCH_API_TOKEN?.trim() ?? "";
|
|
33178
33356
|
try {
|
|
33179
|
-
token = (await
|
|
33357
|
+
token = (await readFile9(join22(dataDir(), "api-token"), "utf8")).trim();
|
|
33180
33358
|
} catch {
|
|
33181
33359
|
}
|
|
33182
33360
|
if (!token) throw new Error("\u65E0\u6CD5\u8BFB\u53D6 TB Switch \u672C\u673A\u670D\u52A1\u51ED\u636E\uFF0C\u8BF7\u91CD\u542F\u684C\u9762\u7AEF\u63D2\u4EF6\u540E\u91CD\u8BD5\u3002");
|
|
@@ -33266,7 +33444,7 @@ async function controlTbSwitch(payload) {
|
|
|
33266
33444
|
}
|
|
33267
33445
|
|
|
33268
33446
|
// src/runs/orphan-registry.ts
|
|
33269
|
-
import { mkdir as mkdir8, readFile as
|
|
33447
|
+
import { mkdir as mkdir8, readFile as readFile10, rename as rename7, writeFile as writeFile8 } from "node:fs/promises";
|
|
33270
33448
|
import { basename as basename3, dirname as dirname8 } from "node:path";
|
|
33271
33449
|
var OrphanRegistry = class {
|
|
33272
33450
|
constructor(file2) {
|
|
@@ -33295,7 +33473,7 @@ var OrphanRegistry = class {
|
|
|
33295
33473
|
async reapPrevious() {
|
|
33296
33474
|
let previous = [];
|
|
33297
33475
|
try {
|
|
33298
|
-
previous = JSON.parse(await
|
|
33476
|
+
previous = JSON.parse(await readFile10(this.file, "utf8"));
|
|
33299
33477
|
} catch {
|
|
33300
33478
|
return [];
|
|
33301
33479
|
}
|
|
@@ -33447,17 +33625,17 @@ var GatewayClient = class {
|
|
|
33447
33625
|
};
|
|
33448
33626
|
|
|
33449
33627
|
// src/workspace/directory-browser.ts
|
|
33450
|
-
import { mkdir as mkdir9, readdir as
|
|
33451
|
-
import { homedir as
|
|
33628
|
+
import { mkdir as mkdir9, readdir as readdir4, realpath as realpath4, stat as stat7 } from "node:fs/promises";
|
|
33629
|
+
import { homedir as homedir13 } from "node:os";
|
|
33452
33630
|
import { dirname as dirname9, isAbsolute as isAbsolute5, parse as parse3, resolve as resolve6 } from "node:path";
|
|
33453
33631
|
var MAX_ENTRIES = 1e3;
|
|
33454
33632
|
async function listDirectory(requested, allowedRoots) {
|
|
33455
|
-
const raw = requested.trim().replace(/^~(?=$|[\\/])/,
|
|
33633
|
+
const raw = requested.trim().replace(/^~(?=$|[\\/])/, homedir13()) || homedir13();
|
|
33456
33634
|
const directory = await realpath4(resolve6(raw)).catch(() => {
|
|
33457
33635
|
throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${requested}`);
|
|
33458
33636
|
});
|
|
33459
33637
|
if (!(await stat7(directory)).isDirectory()) throw new Error("\u8FD9\u4E0D\u662F\u4E00\u4E2A\u76EE\u5F55");
|
|
33460
|
-
const entries = await
|
|
33638
|
+
const entries = await readdir4(directory, { withFileTypes: true }).catch((error62) => {
|
|
33461
33639
|
throw new Error(error62.code === "EACCES" || error62.code === "EPERM" ? "\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u8FD9\u4E2A\u76EE\u5F55" : error62.message);
|
|
33462
33640
|
});
|
|
33463
33641
|
const byName = (a, b) => a.name.localeCompare(b.name, void 0, { sensitivity: "base", numeric: true });
|
|
@@ -33470,8 +33648,8 @@ async function listDirectory(requested, allowedRoots) {
|
|
|
33470
33648
|
else if (entry.isFile()) files.push(item);
|
|
33471
33649
|
}
|
|
33472
33650
|
const parent = dirname9(directory);
|
|
33473
|
-
const places = [{ label: "\u4E3B\u76EE\u5F55", path:
|
|
33474
|
-
for (const root2 of allowedRoots) if (root2 !==
|
|
33651
|
+
const places = [{ label: "\u4E3B\u76EE\u5F55", path: homedir13() }];
|
|
33652
|
+
for (const root2 of allowedRoots) if (root2 !== homedir13()) places.push({ label: "\u5141\u8BB8\u7684\u76EE\u5F55", path: root2 });
|
|
33475
33653
|
places.push({ label: "\u6839\u76EE\u5F55", path: process.platform === "win32" ? parse3(directory).root : "/" });
|
|
33476
33654
|
return {
|
|
33477
33655
|
path: directory,
|
|
@@ -33509,7 +33687,7 @@ async function createDirectory(parentRequested, name) {
|
|
|
33509
33687
|
// src/workspace/workspace-manager.ts
|
|
33510
33688
|
import { spawn as spawn13 } from "node:child_process";
|
|
33511
33689
|
import { opendir, realpath as realpath5, stat as stat8 } from "node:fs/promises";
|
|
33512
|
-
import { homedir as
|
|
33690
|
+
import { homedir as homedir14 } from "node:os";
|
|
33513
33691
|
import { isAbsolute as isAbsolute6, relative as relative3, resolve as resolve7 } from "node:path";
|
|
33514
33692
|
var MAX_NODES = 2e3;
|
|
33515
33693
|
var MAX_DIRECTORY_ENTRIES = 12e3;
|
|
@@ -33545,7 +33723,7 @@ var WorkspaceManager = class {
|
|
|
33545
33723
|
return { root_path: rootPath, nodes, truncated: nodes.length >= MAX_NODES, duration_ms: Date.now() - startedAt };
|
|
33546
33724
|
}
|
|
33547
33725
|
validateRootPath(value) {
|
|
33548
|
-
const raw = value.trim().replace(/^~(?=$|[\\/])/,
|
|
33726
|
+
const raw = value.trim().replace(/^~(?=$|[\\/])/, homedir14());
|
|
33549
33727
|
const root2 = resolve7(raw);
|
|
33550
33728
|
if (!isAbsolute6(raw)) throw new Error("\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
|
|
33551
33729
|
if (relative3(root2, resolve7(root2, "..")) === "") throw new Error("\u4E0D\u80FD\u628A\u6587\u4EF6\u7CFB\u7EDF\u6839\u76EE\u5F55\u4F5C\u4E3A\u76EE\u5F55\u6839");
|
|
@@ -33885,7 +34063,7 @@ var AgentRuntime = class {
|
|
|
33885
34063
|
}
|
|
33886
34064
|
};
|
|
33887
34065
|
this.workspaces = new WorkspaceManager(config2, this.logger);
|
|
33888
|
-
this.orphans = new OrphanRegistry(
|
|
34066
|
+
this.orphans = new OrphanRegistry(join24(config2.dataDir, "active-runs.json"));
|
|
33889
34067
|
this.runs = new RunSupervisor(config2, this.logger, reporter, this.orphans);
|
|
33890
34068
|
}
|
|
33891
34069
|
config;
|
|
@@ -34595,7 +34773,7 @@ function agentPackageRoot() {
|
|
|
34595
34773
|
let directory = dirname10(fileURLToPath2(import.meta.url));
|
|
34596
34774
|
while (true) {
|
|
34597
34775
|
const packagePath = resolve8(directory, "package.json");
|
|
34598
|
-
if (
|
|
34776
|
+
if (existsSync7(packagePath)) {
|
|
34599
34777
|
try {
|
|
34600
34778
|
const info = JSON.parse(readFileSync7(packagePath, "utf8"));
|
|
34601
34779
|
if (info.name === PACKAGE_NAME && typeof info.version === "string") return directory;
|
|
@@ -34658,7 +34836,7 @@ async function runService(options = {}) {
|
|
|
34658
34836
|
}
|
|
34659
34837
|
|
|
34660
34838
|
// src/index.ts
|
|
34661
|
-
var { currentInstallation, installShared, ensureIdle, compareVersions: compareVersions2 } = createRequire(import.meta.url)(
|
|
34839
|
+
var { currentInstallation, installShared, ensureIdle, compareVersions: compareVersions2 } = createRequire(import.meta.url)(join25(agentPackageRoot(), "scripts", "installation.cjs"));
|
|
34662
34840
|
async function run() {
|
|
34663
34841
|
try {
|
|
34664
34842
|
await runService();
|
|
@@ -34771,7 +34949,7 @@ async function setup(args) {
|
|
|
34771
34949
|
}
|
|
34772
34950
|
function manageService(action, args) {
|
|
34773
34951
|
const script = resolve9(dirname11(fileURLToPath3(import.meta.url)), "../../scripts/service.mjs");
|
|
34774
|
-
if (!
|
|
34952
|
+
if (!existsSync8(script)) throw new Error(`service manager is missing: ${script}`);
|
|
34775
34953
|
const result = spawnSync(process.execPath, [script, action, ...args], { stdio: "inherit", shell: false });
|
|
34776
34954
|
if (result.error) throw result.error;
|
|
34777
34955
|
if (result.status !== 0) {
|
|
@@ -34785,7 +34963,7 @@ async function update(args) {
|
|
|
34785
34963
|
if (customConfig) process.env.TOC_OCRA_CONFIG = resolve9(customConfig);
|
|
34786
34964
|
await ensureIdle();
|
|
34787
34965
|
const npmPath = resolveCliCommand("npm");
|
|
34788
|
-
const temporary = mkdtempSync(
|
|
34966
|
+
const temporary = mkdtempSync(join25(tmpdir4(), "toc-ocra-update-"));
|
|
34789
34967
|
try {
|
|
34790
34968
|
const metadataResponse = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}`, { headers: { accept: "application/json", "cache-control": "no-cache" }, signal: AbortSignal.timeout(15e3) });
|
|
34791
34969
|
if (!metadataResponse.ok) throw new Error("\u65E0\u6CD5\u8BFB\u53D6 npm \u6700\u65B0\u7248\u672C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
|
|
@@ -34812,7 +34990,7 @@ async function update(args) {
|
|
|
34812
34990
|
}
|
|
34813
34991
|
const archive = Buffer.concat(chunks);
|
|
34814
34992
|
if (`sha512-${createHash5("sha512").update(archive).digest("base64")}` !== dist.integrity) throw new Error("\u8BBE\u5907\u4EE3\u7406\u5B89\u88C5\u5305\u6821\u9A8C\u5931\u8D25\uFF0C\u5DF2\u505C\u6B62\u5347\u7EA7");
|
|
34815
|
-
const archivePath =
|
|
34993
|
+
const archivePath = join25(temporary, "toc-ocra.tgz");
|
|
34816
34994
|
writeFileSync3(archivePath, archive, { mode: 384 });
|
|
34817
34995
|
const npm = directLaunch2(npmPath, ["install", "--prefix", temporary, "--ignore-scripts", "--omit=dev", "--no-package-lock", "--no-audit", "--no-fund", "--prefer-online", "--registry=https://registry.npmjs.org", archivePath]);
|
|
34818
34996
|
const install = spawnSync(npm.executable, npm.args, { stdio: "inherit", shell: false, windowsHide: true });
|
|
@@ -34822,7 +35000,7 @@ async function update(args) {
|
|
|
34822
35000
|
return;
|
|
34823
35001
|
}
|
|
34824
35002
|
const previousVersion = agentVersion();
|
|
34825
|
-
const current = await installShared(
|
|
35003
|
+
const current = await installShared(join25(temporary, "node_modules", PACKAGE_NAME), { startService: existsSync8(defaultConfigPath()) });
|
|
34826
35004
|
if (current.version === previousVersion) process.stdout.write(`toc-ocra \u5DF2\u662F\u6700\u65B0\u7248\u672C ${current.version}
|
|
34827
35005
|
`);
|
|
34828
35006
|
else process.stdout.write(`toc-ocra \u5DF2\u5347\u7EA7\u5230 ${current.version}\uFF0C\u7EC8\u7AEF\u4E0E Echo \u63D2\u4EF6\u5171\u7528\u6B64\u7248\u672C
|
|
@@ -34850,7 +35028,7 @@ async function main() {
|
|
|
34850
35028
|
const selected = !shared || compareVersions2(agentVersion(), shared.version) > 0 ? await installShared(root2) : shared;
|
|
34851
35029
|
const same = (a, b) => process.platform === "win32" ? resolve9(a).toLowerCase() === resolve9(b).toLowerCase() : resolve9(a) === resolve9(b);
|
|
34852
35030
|
if (!same(selected.root, root2)) {
|
|
34853
|
-
await import(pathToFileURL2(
|
|
35031
|
+
await import(pathToFileURL2(join25(selected.root, "dist", "cli", "cli.mjs")).href);
|
|
34854
35032
|
return;
|
|
34855
35033
|
}
|
|
34856
35034
|
}
|