@cydm/pie 2.8.0 → 2.8.1
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/README.md +18 -0
- package/dist/builtin/extensions/ask-user/index.js +4 -3
- package/dist/builtin/extensions/cron/index.js +265 -31
- package/dist/builtin/extensions/im-forward/index.js +13 -2
- package/dist/builtin/extensions/memory/index.js +275 -83
- package/dist/builtin/extensions/memory/package.json +2 -1
- package/dist/builtin/extensions/plan-mode/index.js +4 -3
- package/dist/builtin/extensions/subagent/index.js +6 -5
- package/dist/builtin/extensions/todo/index.js +4 -3
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +6 -1
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
- package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
- package/dist/chunks/{chunk-JNOFHHLZ.js → chunk-3BC5KGDQ.js} +383 -185
- package/dist/chunks/chunk-3NHP7HK5.js +298 -0
- package/dist/chunks/chunk-6DNYGVZP.js +278 -0
- package/dist/chunks/{chunk-NEES4EBX.js → chunk-GDIYSMTS.js} +6 -4
- package/dist/chunks/{chunk-HGC25NYB.js → chunk-GH4VW2OT.js} +1 -1
- package/dist/chunks/{chunk-5353DEEC.js → chunk-ILUHTKF3.js} +20 -1
- package/dist/chunks/{chunk-LJXHECZ7.js → chunk-PK72LVWQ.js} +13867 -19759
- package/dist/chunks/chunk-RSL7E4R7.js +9634 -0
- package/dist/chunks/chunk-YRR6C43W.js +1740 -0
- package/dist/chunks/config-74AUVDLT.js +46 -0
- package/dist/chunks/model-registry-LI5THXV4.js +17 -0
- package/dist/chunks/src-66XSMIAM.js +134 -0
- package/dist/chunks/src-BPSQMSSC.js +431 -0
- package/dist/chunks/src-OPPYTPWG.js +285 -0
- package/dist/chunks/{src-5XOKRS6F.js → src-YG5M2H44.js} +2 -2
- package/dist/chunks/{test-stream-5SDHKKDB.js → test-stream-JBWXKOQA.js} +1 -1
- package/dist/cli.js +970 -2283
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
3
|
+
import {
|
|
4
|
+
ModelRegistry
|
|
5
|
+
} from "./chunks/chunk-YRR6C43W.js";
|
|
6
|
+
import {
|
|
7
|
+
distillWorkerLogPath,
|
|
8
|
+
readDistillWorkerLog,
|
|
9
|
+
runDistillAuto,
|
|
10
|
+
runDistillWorkerMain,
|
|
11
|
+
spawnDistillAutoWorker,
|
|
12
|
+
spawnDistillWorker
|
|
13
|
+
} from "./chunks/chunk-3NHP7HK5.js";
|
|
3
14
|
import {
|
|
4
15
|
CLI_RETRY_MAX_RETRIES,
|
|
5
16
|
classifyCliFailure,
|
|
@@ -16,7 +27,11 @@ import {
|
|
|
16
27
|
logTransportLifecycle,
|
|
17
28
|
setYoloGrantListener,
|
|
18
29
|
truncateHeadTail
|
|
19
|
-
} from "./chunks/chunk-
|
|
30
|
+
} from "./chunks/chunk-GDIYSMTS.js";
|
|
31
|
+
import {
|
|
32
|
+
AuthStorage,
|
|
33
|
+
FileAuthStorageBackend
|
|
34
|
+
} from "./chunks/chunk-6DNYGVZP.js";
|
|
20
35
|
import {
|
|
21
36
|
VERSION,
|
|
22
37
|
getAgentDir,
|
|
@@ -31,44 +46,56 @@ import {
|
|
|
31
46
|
getSettingsPath,
|
|
32
47
|
getThemesDir,
|
|
33
48
|
migrateConfigFromAgentDir
|
|
34
|
-
} from "./chunks/chunk-
|
|
49
|
+
} from "./chunks/chunk-ILUHTKF3.js";
|
|
35
50
|
import {
|
|
36
|
-
AGENTS_CONTEXT_FILE_NAME,
|
|
37
|
-
AgentSessionController,
|
|
38
|
-
AttentionCoordinator,
|
|
39
51
|
BUILTIN_TOOL_CAPABILITY_METADATA,
|
|
40
|
-
|
|
41
|
-
ExtensionResourceScope,
|
|
42
|
-
FileSessionStore,
|
|
43
|
-
SessionTraceSnapshotWriter,
|
|
52
|
+
MemoryStore,
|
|
44
53
|
abortExecutionState,
|
|
45
|
-
attachAgentEventsToSessionTrace,
|
|
46
54
|
buildExecutionReminder,
|
|
47
|
-
buildProjectContextSection,
|
|
48
55
|
buildToolsPromptSection,
|
|
49
|
-
|
|
56
|
+
consumptionSummary,
|
|
50
57
|
continueExecutionState,
|
|
51
|
-
createCompactionSummary,
|
|
52
58
|
createEmptyExecutionState,
|
|
53
59
|
createExecutionStateStore,
|
|
54
60
|
createFileObservationState,
|
|
55
|
-
createHostEnvelopeProjectorRegistry,
|
|
56
61
|
createPolicyEnforcedTools,
|
|
57
62
|
createReadFileUnderstandingHandler,
|
|
58
63
|
createSearchContextTool,
|
|
59
|
-
createSessionManager,
|
|
60
64
|
createSharedFileSystemTools,
|
|
61
65
|
createSharedWebSearchTool,
|
|
62
66
|
createTodoWidgetView,
|
|
63
67
|
createTwoFilesPatch,
|
|
64
|
-
estimateContextTokens,
|
|
65
|
-
estimateTokens,
|
|
66
68
|
evaluateTodoClosureAfterCompletedTurn,
|
|
67
69
|
evaluateTodoClosureAfterFailedTurn,
|
|
70
|
+
formatSkillSummariesForPrompt,
|
|
71
|
+
isToolAllowedInPlanMode,
|
|
72
|
+
maybeAdvanceTodoExecutionState,
|
|
73
|
+
modalityForReadFileUnderstandingKind,
|
|
74
|
+
pauseExecutionState,
|
|
75
|
+
restoreExecutionState,
|
|
76
|
+
shouldPreserveExecutionStateForUserText,
|
|
77
|
+
supersedeExecutionState,
|
|
78
|
+
todayKey
|
|
79
|
+
} from "./chunks/chunk-PK72LVWQ.js";
|
|
80
|
+
import {
|
|
81
|
+
AGENTS_CONTEXT_FILE_NAME,
|
|
82
|
+
AgentSessionController,
|
|
83
|
+
AttentionCoordinator,
|
|
84
|
+
DEFAULT_COMPACTION_CONFIG,
|
|
85
|
+
ExtensionResourceScope,
|
|
86
|
+
FileSessionStore,
|
|
87
|
+
SessionTraceSnapshotWriter,
|
|
88
|
+
attachAgentEventsToSessionTrace,
|
|
89
|
+
buildProjectContextSection,
|
|
90
|
+
calculateTotalTokens,
|
|
91
|
+
createCompactionSummary,
|
|
92
|
+
createHostEnvelopeProjectorRegistry,
|
|
93
|
+
createSessionManager,
|
|
94
|
+
estimateContextTokens,
|
|
95
|
+
estimateTokens,
|
|
68
96
|
extensionFallbackName,
|
|
69
97
|
extractExtensionSettings,
|
|
70
98
|
findFirstKeptEntrySummaryId,
|
|
71
|
-
formatSkillSummariesForPrompt,
|
|
72
99
|
generateEntryId,
|
|
73
100
|
getAutoCompactTokenLimit,
|
|
74
101
|
getExtensionEnablementEntry,
|
|
@@ -78,30 +105,23 @@ import {
|
|
|
78
105
|
isCompactSummaryMessage,
|
|
79
106
|
isExtensionEnabled,
|
|
80
107
|
isHostContextBlock,
|
|
81
|
-
|
|
82
|
-
maybeAdvanceTodoExecutionState,
|
|
83
|
-
modalityForReadFileUnderstandingKind,
|
|
84
|
-
pauseExecutionState,
|
|
108
|
+
manifestDefaultLayer,
|
|
85
109
|
prepareSessionCompaction,
|
|
86
110
|
projectHostEnvelopes,
|
|
87
111
|
registerInteractionHandler,
|
|
88
112
|
requestInteraction,
|
|
89
113
|
resolveExtensionIdentity,
|
|
90
|
-
restoreExecutionState,
|
|
91
114
|
setEnablementInMap,
|
|
92
115
|
setExtensionEnabledInSettings,
|
|
93
|
-
shouldPreserveExecutionStateForUserText,
|
|
94
|
-
supersedeExecutionState,
|
|
95
116
|
verifyPreparedCompactionCommit
|
|
96
|
-
} from "./chunks/chunk-
|
|
97
|
-
import "./chunks/chunk-
|
|
117
|
+
} from "./chunks/chunk-RSL7E4R7.js";
|
|
118
|
+
import "./chunks/chunk-GH4VW2OT.js";
|
|
98
119
|
import {
|
|
99
120
|
Deref,
|
|
100
121
|
Errors,
|
|
101
122
|
ExtendsUndefinedCheck,
|
|
102
123
|
HasTransform,
|
|
103
124
|
Hash,
|
|
104
|
-
MODEL_CLASS_FALLBACK_ORDER,
|
|
105
125
|
TransformDecode,
|
|
106
126
|
TransformDecodeCheckError,
|
|
107
127
|
TransformEncode,
|
|
@@ -111,13 +131,10 @@ import {
|
|
|
111
131
|
format_exports,
|
|
112
132
|
getLogger,
|
|
113
133
|
getModelCacheCapability,
|
|
114
|
-
modelSupportsToolPurpose,
|
|
115
|
-
requiredCapabilityForToolPurpose,
|
|
116
134
|
setLogger,
|
|
117
|
-
sortToolModelCandidatesByCapability,
|
|
118
135
|
streamSimple,
|
|
119
136
|
type_exports
|
|
120
|
-
} from "./chunks/chunk-
|
|
137
|
+
} from "./chunks/chunk-3BC5KGDQ.js";
|
|
121
138
|
import {
|
|
122
139
|
IsArray,
|
|
123
140
|
IsBigInt,
|
|
@@ -1945,7 +1962,7 @@ var require_core = __commonJS({
|
|
|
1945
1962
|
return match && match.index === 0;
|
|
1946
1963
|
}
|
|
1947
1964
|
var BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
|
|
1948
|
-
function
|
|
1965
|
+
function join23(regexps, separator = "|") {
|
|
1949
1966
|
let numCaptures = 0;
|
|
1950
1967
|
return regexps.map((regex) => {
|
|
1951
1968
|
numCaptures += 1;
|
|
@@ -2249,7 +2266,7 @@ var require_core = __commonJS({
|
|
|
2249
2266
|
this.exec = () => null;
|
|
2250
2267
|
}
|
|
2251
2268
|
const terminators = this.regexes.map((el) => el[1]);
|
|
2252
|
-
this.matcherRe = langRe(
|
|
2269
|
+
this.matcherRe = langRe(join23(terminators), true);
|
|
2253
2270
|
this.lastIndex = 0;
|
|
2254
2271
|
}
|
|
2255
2272
|
/** @param {string} s */
|
|
@@ -34341,13 +34358,13 @@ var require_yaml = __commonJS({
|
|
|
34341
34358
|
{ begin: /[^\s,{}[\]]+/ }
|
|
34342
34359
|
]
|
|
34343
34360
|
});
|
|
34344
|
-
var
|
|
34361
|
+
var DATE_RE2 = "[0-9]{4}(-[0-9][0-9]){0,2}";
|
|
34345
34362
|
var TIME_RE = "([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?";
|
|
34346
34363
|
var FRACTION_RE = "(\\.[0-9]*)?";
|
|
34347
34364
|
var ZONE_RE = "([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?";
|
|
34348
34365
|
var TIMESTAMP = {
|
|
34349
34366
|
className: "number",
|
|
34350
|
-
begin: "\\b" +
|
|
34367
|
+
begin: "\\b" + DATE_RE2 + TIME_RE + FRACTION_RE + ZONE_RE + "\\b"
|
|
34351
34368
|
};
|
|
34352
34369
|
var VALUE_CONTAINER = {
|
|
34353
34370
|
end: ",",
|
|
@@ -47941,10 +47958,10 @@ var require_resolve_block_map = __commonJS({
|
|
|
47941
47958
|
let offset = bm.offset;
|
|
47942
47959
|
let commentEnd = null;
|
|
47943
47960
|
for (const collItem of bm.items) {
|
|
47944
|
-
const { start, key, sep:
|
|
47961
|
+
const { start, key, sep: sep2, value } = collItem;
|
|
47945
47962
|
const keyProps = resolveProps.resolveProps(start, {
|
|
47946
47963
|
indicator: "explicit-key-ind",
|
|
47947
|
-
next: key ??
|
|
47964
|
+
next: key ?? sep2?.[0],
|
|
47948
47965
|
offset,
|
|
47949
47966
|
onError,
|
|
47950
47967
|
parentIndent: bm.indent,
|
|
@@ -47958,7 +47975,7 @@ var require_resolve_block_map = __commonJS({
|
|
|
47958
47975
|
else if ("indent" in key && key.indent !== bm.indent)
|
|
47959
47976
|
onError(offset, "BAD_INDENT", startColMsg);
|
|
47960
47977
|
}
|
|
47961
|
-
if (!keyProps.anchor && !keyProps.tag && !
|
|
47978
|
+
if (!keyProps.anchor && !keyProps.tag && !sep2) {
|
|
47962
47979
|
commentEnd = keyProps.end;
|
|
47963
47980
|
if (keyProps.comment) {
|
|
47964
47981
|
if (map.comment)
|
|
@@ -47982,7 +47999,7 @@ var require_resolve_block_map = __commonJS({
|
|
|
47982
47999
|
ctx.atKey = false;
|
|
47983
48000
|
if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
|
|
47984
48001
|
onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
|
|
47985
|
-
const valueProps = resolveProps.resolveProps(
|
|
48002
|
+
const valueProps = resolveProps.resolveProps(sep2 ?? [], {
|
|
47986
48003
|
indicator: "map-value-ind",
|
|
47987
48004
|
next: value,
|
|
47988
48005
|
offset: keyNode.range[2],
|
|
@@ -47998,7 +48015,7 @@ var require_resolve_block_map = __commonJS({
|
|
|
47998
48015
|
if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
|
|
47999
48016
|
onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
|
|
48000
48017
|
}
|
|
48001
|
-
const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset,
|
|
48018
|
+
const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep2, null, valueProps, onError);
|
|
48002
48019
|
if (ctx.schema.compat)
|
|
48003
48020
|
utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
|
|
48004
48021
|
offset = valueNode.range[2];
|
|
@@ -48089,7 +48106,7 @@ var require_resolve_end = __commonJS({
|
|
|
48089
48106
|
let comment = "";
|
|
48090
48107
|
if (end) {
|
|
48091
48108
|
let hasSpace = false;
|
|
48092
|
-
let
|
|
48109
|
+
let sep2 = "";
|
|
48093
48110
|
for (const token of end) {
|
|
48094
48111
|
const { source, type } = token;
|
|
48095
48112
|
switch (type) {
|
|
@@ -48103,13 +48120,13 @@ var require_resolve_end = __commonJS({
|
|
|
48103
48120
|
if (!comment)
|
|
48104
48121
|
comment = cb;
|
|
48105
48122
|
else
|
|
48106
|
-
comment +=
|
|
48107
|
-
|
|
48123
|
+
comment += sep2 + cb;
|
|
48124
|
+
sep2 = "";
|
|
48108
48125
|
break;
|
|
48109
48126
|
}
|
|
48110
48127
|
case "newline":
|
|
48111
48128
|
if (comment)
|
|
48112
|
-
|
|
48129
|
+
sep2 += source;
|
|
48113
48130
|
hasSpace = true;
|
|
48114
48131
|
break;
|
|
48115
48132
|
default:
|
|
@@ -48152,18 +48169,18 @@ var require_resolve_flow_collection = __commonJS({
|
|
|
48152
48169
|
let offset = fc.offset + fc.start.source.length;
|
|
48153
48170
|
for (let i = 0; i < fc.items.length; ++i) {
|
|
48154
48171
|
const collItem = fc.items[i];
|
|
48155
|
-
const { start, key, sep:
|
|
48172
|
+
const { start, key, sep: sep2, value } = collItem;
|
|
48156
48173
|
const props = resolveProps.resolveProps(start, {
|
|
48157
48174
|
flow: fcName,
|
|
48158
48175
|
indicator: "explicit-key-ind",
|
|
48159
|
-
next: key ??
|
|
48176
|
+
next: key ?? sep2?.[0],
|
|
48160
48177
|
offset,
|
|
48161
48178
|
onError,
|
|
48162
48179
|
parentIndent: fc.indent,
|
|
48163
48180
|
startOnNewline: false
|
|
48164
48181
|
});
|
|
48165
48182
|
if (!props.found) {
|
|
48166
|
-
if (!props.anchor && !props.tag && !
|
|
48183
|
+
if (!props.anchor && !props.tag && !sep2 && !value) {
|
|
48167
48184
|
if (i === 0 && props.comma)
|
|
48168
48185
|
onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
|
|
48169
48186
|
else if (i < fc.items.length - 1)
|
|
@@ -48217,8 +48234,8 @@ var require_resolve_flow_collection = __commonJS({
|
|
|
48217
48234
|
}
|
|
48218
48235
|
}
|
|
48219
48236
|
}
|
|
48220
|
-
if (!isMap && !
|
|
48221
|
-
const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end,
|
|
48237
|
+
if (!isMap && !sep2 && !props.found) {
|
|
48238
|
+
const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep2, null, props, onError);
|
|
48222
48239
|
coll.items.push(valueNode);
|
|
48223
48240
|
offset = valueNode.range[2];
|
|
48224
48241
|
if (isBlock(value))
|
|
@@ -48230,7 +48247,7 @@ var require_resolve_flow_collection = __commonJS({
|
|
|
48230
48247
|
if (isBlock(key))
|
|
48231
48248
|
onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
|
|
48232
48249
|
ctx.atKey = false;
|
|
48233
|
-
const valueProps = resolveProps.resolveProps(
|
|
48250
|
+
const valueProps = resolveProps.resolveProps(sep2 ?? [], {
|
|
48234
48251
|
flow: fcName,
|
|
48235
48252
|
indicator: "map-value-ind",
|
|
48236
48253
|
next: value,
|
|
@@ -48241,8 +48258,8 @@ var require_resolve_flow_collection = __commonJS({
|
|
|
48241
48258
|
});
|
|
48242
48259
|
if (valueProps.found) {
|
|
48243
48260
|
if (!isMap && !props.found && ctx.options.strict) {
|
|
48244
|
-
if (
|
|
48245
|
-
for (const st of
|
|
48261
|
+
if (sep2)
|
|
48262
|
+
for (const st of sep2) {
|
|
48246
48263
|
if (st === valueProps.found)
|
|
48247
48264
|
break;
|
|
48248
48265
|
if (st.type === "newline") {
|
|
@@ -48259,7 +48276,7 @@ var require_resolve_flow_collection = __commonJS({
|
|
|
48259
48276
|
else
|
|
48260
48277
|
onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
|
|
48261
48278
|
}
|
|
48262
|
-
const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end,
|
|
48279
|
+
const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep2, null, valueProps, onError) : null;
|
|
48263
48280
|
if (valueNode) {
|
|
48264
48281
|
if (isBlock(value))
|
|
48265
48282
|
onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
|
|
@@ -48439,7 +48456,7 @@ var require_resolve_block_scalar = __commonJS({
|
|
|
48439
48456
|
chompStart = i + 1;
|
|
48440
48457
|
}
|
|
48441
48458
|
let value = "";
|
|
48442
|
-
let
|
|
48459
|
+
let sep2 = "";
|
|
48443
48460
|
let prevMoreIndented = false;
|
|
48444
48461
|
for (let i = 0; i < contentStart; ++i)
|
|
48445
48462
|
value += lines[i][0].slice(trimIndent) + "\n";
|
|
@@ -48456,24 +48473,24 @@ var require_resolve_block_scalar = __commonJS({
|
|
|
48456
48473
|
indent = "";
|
|
48457
48474
|
}
|
|
48458
48475
|
if (type === Scalar.Scalar.BLOCK_LITERAL) {
|
|
48459
|
-
value +=
|
|
48460
|
-
|
|
48476
|
+
value += sep2 + indent.slice(trimIndent) + content;
|
|
48477
|
+
sep2 = "\n";
|
|
48461
48478
|
} else if (indent.length > trimIndent || content[0] === " ") {
|
|
48462
|
-
if (
|
|
48463
|
-
|
|
48464
|
-
else if (!prevMoreIndented &&
|
|
48465
|
-
|
|
48466
|
-
value +=
|
|
48467
|
-
|
|
48479
|
+
if (sep2 === " ")
|
|
48480
|
+
sep2 = "\n";
|
|
48481
|
+
else if (!prevMoreIndented && sep2 === "\n")
|
|
48482
|
+
sep2 = "\n\n";
|
|
48483
|
+
value += sep2 + indent.slice(trimIndent) + content;
|
|
48484
|
+
sep2 = "\n";
|
|
48468
48485
|
prevMoreIndented = true;
|
|
48469
48486
|
} else if (content === "") {
|
|
48470
|
-
if (
|
|
48487
|
+
if (sep2 === "\n")
|
|
48471
48488
|
value += "\n";
|
|
48472
48489
|
else
|
|
48473
|
-
|
|
48490
|
+
sep2 = "\n";
|
|
48474
48491
|
} else {
|
|
48475
|
-
value +=
|
|
48476
|
-
|
|
48492
|
+
value += sep2 + content;
|
|
48493
|
+
sep2 = " ";
|
|
48477
48494
|
prevMoreIndented = false;
|
|
48478
48495
|
}
|
|
48479
48496
|
}
|
|
@@ -48655,25 +48672,25 @@ var require_resolve_flow_scalar = __commonJS({
|
|
|
48655
48672
|
if (!match)
|
|
48656
48673
|
return source;
|
|
48657
48674
|
let res = match[1];
|
|
48658
|
-
let
|
|
48675
|
+
let sep2 = " ";
|
|
48659
48676
|
let pos = first.lastIndex;
|
|
48660
48677
|
line.lastIndex = pos;
|
|
48661
48678
|
while (match = line.exec(source)) {
|
|
48662
48679
|
if (match[1] === "") {
|
|
48663
|
-
if (
|
|
48664
|
-
res +=
|
|
48680
|
+
if (sep2 === "\n")
|
|
48681
|
+
res += sep2;
|
|
48665
48682
|
else
|
|
48666
|
-
|
|
48683
|
+
sep2 = "\n";
|
|
48667
48684
|
} else {
|
|
48668
|
-
res +=
|
|
48669
|
-
|
|
48685
|
+
res += sep2 + match[1];
|
|
48686
|
+
sep2 = " ";
|
|
48670
48687
|
}
|
|
48671
48688
|
pos = line.lastIndex;
|
|
48672
48689
|
}
|
|
48673
48690
|
const last = /[ \t]*(.*)/sy;
|
|
48674
48691
|
last.lastIndex = pos;
|
|
48675
48692
|
match = last.exec(source);
|
|
48676
|
-
return res +
|
|
48693
|
+
return res + sep2 + (match?.[1] ?? "");
|
|
48677
48694
|
}
|
|
48678
48695
|
function doubleQuotedValue(source, onError) {
|
|
48679
48696
|
let res = "";
|
|
@@ -49480,14 +49497,14 @@ var require_cst_stringify = __commonJS({
|
|
|
49480
49497
|
}
|
|
49481
49498
|
}
|
|
49482
49499
|
}
|
|
49483
|
-
function stringifyItem({ start, key, sep:
|
|
49500
|
+
function stringifyItem({ start, key, sep: sep2, value }) {
|
|
49484
49501
|
let res = "";
|
|
49485
49502
|
for (const st of start)
|
|
49486
49503
|
res += st.source;
|
|
49487
49504
|
if (key)
|
|
49488
49505
|
res += stringifyToken(key);
|
|
49489
|
-
if (
|
|
49490
|
-
for (const st of
|
|
49506
|
+
if (sep2)
|
|
49507
|
+
for (const st of sep2)
|
|
49491
49508
|
res += st.source;
|
|
49492
49509
|
if (value)
|
|
49493
49510
|
res += stringifyToken(value);
|
|
@@ -50637,18 +50654,18 @@ var require_parser2 = __commonJS({
|
|
|
50637
50654
|
if (this.type === "map-value-ind") {
|
|
50638
50655
|
const prev = getPrevProps(this.peek(2));
|
|
50639
50656
|
const start = getFirstKeyStartProps(prev);
|
|
50640
|
-
let
|
|
50657
|
+
let sep2;
|
|
50641
50658
|
if (scalar.end) {
|
|
50642
|
-
|
|
50643
|
-
|
|
50659
|
+
sep2 = scalar.end;
|
|
50660
|
+
sep2.push(this.sourceToken);
|
|
50644
50661
|
delete scalar.end;
|
|
50645
50662
|
} else
|
|
50646
|
-
|
|
50663
|
+
sep2 = [this.sourceToken];
|
|
50647
50664
|
const map = {
|
|
50648
50665
|
type: "block-map",
|
|
50649
50666
|
offset: scalar.offset,
|
|
50650
50667
|
indent: scalar.indent,
|
|
50651
|
-
items: [{ start, key: scalar, sep:
|
|
50668
|
+
items: [{ start, key: scalar, sep: sep2 }]
|
|
50652
50669
|
};
|
|
50653
50670
|
this.onKeyLine = true;
|
|
50654
50671
|
this.stack[this.stack.length - 1] = map;
|
|
@@ -50801,15 +50818,15 @@ var require_parser2 = __commonJS({
|
|
|
50801
50818
|
} else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
|
|
50802
50819
|
const start2 = getFirstKeyStartProps(it.start);
|
|
50803
50820
|
const key = it.key;
|
|
50804
|
-
const
|
|
50805
|
-
|
|
50821
|
+
const sep2 = it.sep;
|
|
50822
|
+
sep2.push(this.sourceToken);
|
|
50806
50823
|
delete it.key;
|
|
50807
50824
|
delete it.sep;
|
|
50808
50825
|
this.stack.push({
|
|
50809
50826
|
type: "block-map",
|
|
50810
50827
|
offset: this.offset,
|
|
50811
50828
|
indent: this.indent,
|
|
50812
|
-
items: [{ start: start2, key, sep:
|
|
50829
|
+
items: [{ start: start2, key, sep: sep2 }]
|
|
50813
50830
|
});
|
|
50814
50831
|
} else if (start.length > 0) {
|
|
50815
50832
|
it.sep = it.sep.concat(start, this.sourceToken);
|
|
@@ -51003,13 +51020,13 @@ var require_parser2 = __commonJS({
|
|
|
51003
51020
|
const prev = getPrevProps(parent);
|
|
51004
51021
|
const start = getFirstKeyStartProps(prev);
|
|
51005
51022
|
fixFlowSeqItems(fc);
|
|
51006
|
-
const
|
|
51007
|
-
|
|
51023
|
+
const sep2 = fc.end.splice(1, fc.end.length);
|
|
51024
|
+
sep2.push(this.sourceToken);
|
|
51008
51025
|
const map = {
|
|
51009
51026
|
type: "block-map",
|
|
51010
51027
|
offset: fc.offset,
|
|
51011
51028
|
indent: fc.indent,
|
|
51012
|
-
items: [{ start, key: fc, sep:
|
|
51029
|
+
items: [{ start, key: fc, sep: sep2 }]
|
|
51013
51030
|
};
|
|
51014
51031
|
this.onKeyLine = true;
|
|
51015
51032
|
this.stack[this.stack.length - 1] = map;
|
|
@@ -51300,6 +51317,7 @@ function parseCliInvocation(args) {
|
|
|
51300
51317
|
let command;
|
|
51301
51318
|
let showHelp2 = false;
|
|
51302
51319
|
let testCommand;
|
|
51320
|
+
let sessionId;
|
|
51303
51321
|
const positionals = [];
|
|
51304
51322
|
for (let i = 0; i < args.length; i += 1) {
|
|
51305
51323
|
const arg = args[i];
|
|
@@ -51319,6 +51337,18 @@ function parseCliInvocation(args) {
|
|
|
51319
51337
|
}
|
|
51320
51338
|
continue;
|
|
51321
51339
|
}
|
|
51340
|
+
if (arg === "--session-id") {
|
|
51341
|
+
const next = args[i + 1];
|
|
51342
|
+
if (next && !next.startsWith("-")) {
|
|
51343
|
+
sessionId = next;
|
|
51344
|
+
i += 1;
|
|
51345
|
+
}
|
|
51346
|
+
continue;
|
|
51347
|
+
}
|
|
51348
|
+
if (arg.startsWith("--session-id=")) {
|
|
51349
|
+
sessionId = arg.slice("--session-id=".length);
|
|
51350
|
+
continue;
|
|
51351
|
+
}
|
|
51322
51352
|
if (FLAGS_WITH_VALUES.has(arg)) {
|
|
51323
51353
|
i += 1;
|
|
51324
51354
|
continue;
|
|
@@ -51338,11 +51368,15 @@ function parseCliInvocation(args) {
|
|
|
51338
51368
|
return { showHelp: true };
|
|
51339
51369
|
}
|
|
51340
51370
|
if (testCommand) {
|
|
51341
|
-
return { showHelp: false, testCommand };
|
|
51371
|
+
return sessionId !== void 0 ? { showHelp: false, testCommand, sessionId } : { showHelp: false, testCommand };
|
|
51372
|
+
}
|
|
51373
|
+
const initialPrompt = positionals.join(" ").trim() || void 0;
|
|
51374
|
+
if (sessionId !== void 0) {
|
|
51375
|
+
return { showHelp: false, initialPrompt, sessionId };
|
|
51342
51376
|
}
|
|
51343
51377
|
return {
|
|
51344
51378
|
showHelp: false,
|
|
51345
|
-
initialPrompt
|
|
51379
|
+
initialPrompt
|
|
51346
51380
|
};
|
|
51347
51381
|
}
|
|
51348
51382
|
function parseRepeatedFlag(args, flag) {
|
|
@@ -51704,1968 +51738,14 @@ function installInteractiveConsoleInterception(runtimeLogger) {
|
|
|
51704
51738
|
// src/doctor.ts
|
|
51705
51739
|
import { spawnSync } from "node:child_process";
|
|
51706
51740
|
import { createRequire } from "node:module";
|
|
51707
|
-
import * as
|
|
51741
|
+
import * as fs3 from "node:fs";
|
|
51708
51742
|
import * as os from "node:os";
|
|
51709
|
-
import * as
|
|
51743
|
+
import * as path3 from "node:path";
|
|
51710
51744
|
import { delimiter } from "node:path";
|
|
51711
51745
|
|
|
51712
|
-
// src/core/
|
|
51746
|
+
// src/core/settings-manager.ts
|
|
51713
51747
|
import * as fs2 from "fs";
|
|
51714
51748
|
import * as path2 from "path";
|
|
51715
|
-
var AUTH_LOCK_WRITE_GRACE_MS = 1e3;
|
|
51716
|
-
var DEFAULT_AUTH_LOCK_WAIT_MS = 2e3;
|
|
51717
|
-
var OAUTH_EXPIRY_SKEW_MS = 3e4;
|
|
51718
|
-
function syncSleepMs(ms) {
|
|
51719
|
-
if (ms <= 0) return;
|
|
51720
|
-
const cell = new Int32Array(new SharedArrayBuffer(4));
|
|
51721
|
-
Atomics.wait(cell, 0, 0, ms);
|
|
51722
|
-
}
|
|
51723
|
-
function processIsAlive(pid) {
|
|
51724
|
-
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
51725
|
-
try {
|
|
51726
|
-
process.kill(pid, 0);
|
|
51727
|
-
return true;
|
|
51728
|
-
} catch (error) {
|
|
51729
|
-
return error.code === "EPERM";
|
|
51730
|
-
}
|
|
51731
|
-
}
|
|
51732
|
-
var InMemoryAuthStorageBackend = class {
|
|
51733
|
-
snapshot = { oauth: {} };
|
|
51734
|
-
read() {
|
|
51735
|
-
return { oauth: { ...this.snapshot.oauth } };
|
|
51736
|
-
}
|
|
51737
|
-
write(snapshot) {
|
|
51738
|
-
this.snapshot = { oauth: { ...snapshot.oauth } };
|
|
51739
|
-
}
|
|
51740
|
-
};
|
|
51741
|
-
var AUTH_FILE_VERSION = 1;
|
|
51742
|
-
var FileAuthStorageBackend = class {
|
|
51743
|
-
constructor(authPath = path2.join(getConfigDir(), "auth.json"), lockWaitMs = DEFAULT_AUTH_LOCK_WAIT_MS) {
|
|
51744
|
-
this.authPath = authPath;
|
|
51745
|
-
this.lockWaitMs = lockWaitMs;
|
|
51746
|
-
}
|
|
51747
|
-
authPath;
|
|
51748
|
-
lockWaitMs;
|
|
51749
|
-
errors = [];
|
|
51750
|
-
read() {
|
|
51751
|
-
try {
|
|
51752
|
-
if (!fs2.existsSync(this.authPath)) return { oauth: {} };
|
|
51753
|
-
const raw = JSON.parse(fs2.readFileSync(this.authPath, "utf8"));
|
|
51754
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { oauth: {} };
|
|
51755
|
-
const oauth = raw.oauth;
|
|
51756
|
-
if (!oauth || typeof oauth !== "object" || Array.isArray(oauth)) return { oauth: {} };
|
|
51757
|
-
return { oauth: { ...oauth } };
|
|
51758
|
-
} catch (error) {
|
|
51759
|
-
this.errors.push(error instanceof Error ? error : new Error(String(error)));
|
|
51760
|
-
return { oauth: {} };
|
|
51761
|
-
}
|
|
51762
|
-
}
|
|
51763
|
-
/** A lock whose owner is gone (or that never got populated) may be reclaimed. */
|
|
51764
|
-
lockIsStale(lockPath) {
|
|
51765
|
-
const stat2 = fs2.lstatSync(lockPath);
|
|
51766
|
-
if (stat2.isSymbolicLink() || !stat2.isFile()) return true;
|
|
51767
|
-
let owner;
|
|
51768
|
-
try {
|
|
51769
|
-
owner = JSON.parse(fs2.readFileSync(lockPath, "utf8"));
|
|
51770
|
-
} catch {
|
|
51771
|
-
}
|
|
51772
|
-
const age = Date.now() - stat2.mtimeMs;
|
|
51773
|
-
const validOwner = owner?.version === 1 && Number.isSafeInteger(owner.pid) && typeof owner.token === "string" && typeof owner.createdAt === "number";
|
|
51774
|
-
if (validOwner && processIsAlive(Number(owner.pid))) return false;
|
|
51775
|
-
return validOwner || age > AUTH_LOCK_WRITE_GRACE_MS;
|
|
51776
|
-
}
|
|
51777
|
-
/** Atomically claim a stale lock via hard-link identity comparison before removing it. */
|
|
51778
|
-
reclaimStaleLock(lockPath) {
|
|
51779
|
-
if (!this.lockIsStale(lockPath)) return false;
|
|
51780
|
-
const claimPath = `${lockPath}.reclaim-${process.pid}-${Math.random().toString(36).slice(2)}`;
|
|
51781
|
-
try {
|
|
51782
|
-
fs2.linkSync(lockPath, claimPath);
|
|
51783
|
-
const claimed = fs2.lstatSync(claimPath);
|
|
51784
|
-
const current = fs2.lstatSync(lockPath);
|
|
51785
|
-
if (claimed.isSymbolicLink() || !claimed.isFile() || current.isSymbolicLink() || !current.isFile()) return false;
|
|
51786
|
-
if (claimed.dev !== current.dev || claimed.ino !== current.ino) return false;
|
|
51787
|
-
fs2.unlinkSync(lockPath);
|
|
51788
|
-
return true;
|
|
51789
|
-
} catch (error) {
|
|
51790
|
-
const code = error.code;
|
|
51791
|
-
if (code === "ENOENT" || code === "EEXIST") return false;
|
|
51792
|
-
throw error;
|
|
51793
|
-
} finally {
|
|
51794
|
-
try {
|
|
51795
|
-
fs2.unlinkSync(claimPath);
|
|
51796
|
-
} catch {
|
|
51797
|
-
}
|
|
51798
|
-
}
|
|
51799
|
-
}
|
|
51800
|
-
/** Acquire the fixed-path cross-process lock; the release fn is token-checked. */
|
|
51801
|
-
acquireLock(directory, lockPath) {
|
|
51802
|
-
fs2.mkdirSync(directory, { recursive: true, mode: 448 });
|
|
51803
|
-
const deadline = Date.now() + this.lockWaitMs;
|
|
51804
|
-
while (true) {
|
|
51805
|
-
const token = `${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
|
|
51806
|
-
try {
|
|
51807
|
-
const fd = fs2.openSync(lockPath, "wx", 384);
|
|
51808
|
-
try {
|
|
51809
|
-
fs2.writeFileSync(fd, `${JSON.stringify({ version: 1, pid: process.pid, token, createdAt: Date.now() })}
|
|
51810
|
-
`);
|
|
51811
|
-
} finally {
|
|
51812
|
-
fs2.closeSync(fd);
|
|
51813
|
-
}
|
|
51814
|
-
return () => {
|
|
51815
|
-
try {
|
|
51816
|
-
const owner = JSON.parse(fs2.readFileSync(lockPath, "utf8"));
|
|
51817
|
-
if (owner?.token === token) fs2.unlinkSync(lockPath);
|
|
51818
|
-
} catch {
|
|
51819
|
-
}
|
|
51820
|
-
};
|
|
51821
|
-
} catch (error) {
|
|
51822
|
-
if (error.code !== "EEXIST") throw error;
|
|
51823
|
-
try {
|
|
51824
|
-
if (this.reclaimStaleLock(lockPath)) continue;
|
|
51825
|
-
} catch (reclaimError) {
|
|
51826
|
-
if (reclaimError.code === "ENOENT") continue;
|
|
51827
|
-
throw reclaimError;
|
|
51828
|
-
}
|
|
51829
|
-
if (Date.now() >= deadline) throw new Error(`timed out waiting for auth storage lock: ${lockPath}`);
|
|
51830
|
-
syncSleepMs(25);
|
|
51831
|
-
}
|
|
51832
|
-
}
|
|
51833
|
-
}
|
|
51834
|
-
/**
|
|
51835
|
-
* Merge-on-write under a fixed-path cross-process lock: re-read the file,
|
|
51836
|
-
* apply explicit removals (logout), merge our snapshot's oauth entries
|
|
51837
|
-
* over whatever is on disk (preserving unrelated edits), then write back
|
|
51838
|
-
* atomically with 0600 permissions.
|
|
51839
|
-
*/
|
|
51840
|
-
write(snapshot) {
|
|
51841
|
-
const directory = path2.dirname(this.authPath);
|
|
51842
|
-
const lockPath = `${this.authPath}.lock`;
|
|
51843
|
-
let release;
|
|
51844
|
-
try {
|
|
51845
|
-
release = this.acquireLock(directory, lockPath);
|
|
51846
|
-
try {
|
|
51847
|
-
const onDisk = this.read();
|
|
51848
|
-
const mergedOauth = { ...onDisk.oauth };
|
|
51849
|
-
for (const removed of snapshot.removedOauth ?? []) {
|
|
51850
|
-
delete mergedOauth[removed];
|
|
51851
|
-
}
|
|
51852
|
-
Object.assign(mergedOauth, snapshot.oauth);
|
|
51853
|
-
const merged = {
|
|
51854
|
-
version: AUTH_FILE_VERSION,
|
|
51855
|
-
oauth: mergedOauth
|
|
51856
|
-
};
|
|
51857
|
-
const temporary = `${this.authPath}.${process.pid}.tmp`;
|
|
51858
|
-
try {
|
|
51859
|
-
fs2.writeFileSync(temporary, `${JSON.stringify(merged, null, 2)}
|
|
51860
|
-
`, { flag: "wx", mode: 384 });
|
|
51861
|
-
fs2.renameSync(temporary, this.authPath);
|
|
51862
|
-
} finally {
|
|
51863
|
-
if (fs2.existsSync(temporary)) fs2.unlinkSync(temporary);
|
|
51864
|
-
}
|
|
51865
|
-
} finally {
|
|
51866
|
-
release();
|
|
51867
|
-
}
|
|
51868
|
-
} catch (error) {
|
|
51869
|
-
this.errors.push(error instanceof Error ? error : new Error(String(error)));
|
|
51870
|
-
}
|
|
51871
|
-
}
|
|
51872
|
-
drainErrors() {
|
|
51873
|
-
return this.errors.splice(0);
|
|
51874
|
-
}
|
|
51875
|
-
};
|
|
51876
|
-
var AuthStorage = class _AuthStorage {
|
|
51877
|
-
providerApiKeys = /* @__PURE__ */ new Map();
|
|
51878
|
-
runtimeApiKeys = /* @__PURE__ */ new Map();
|
|
51879
|
-
providerEnvVars = /* @__PURE__ */ new Map();
|
|
51880
|
-
legacyApiKey;
|
|
51881
|
-
oauthCredentials = /* @__PURE__ */ new Map();
|
|
51882
|
-
removedOauthProviders = /* @__PURE__ */ new Set();
|
|
51883
|
-
backend;
|
|
51884
|
-
constructor(backend) {
|
|
51885
|
-
this.backend = backend;
|
|
51886
|
-
if (backend) {
|
|
51887
|
-
for (const [provider, credentials] of Object.entries(backend.read().oauth)) {
|
|
51888
|
-
this.oauthCredentials.set(provider, credentials);
|
|
51889
|
-
}
|
|
51890
|
-
}
|
|
51891
|
-
}
|
|
51892
|
-
/** Runtime-only storage (no persistence). */
|
|
51893
|
-
static create() {
|
|
51894
|
-
return new _AuthStorage();
|
|
51895
|
-
}
|
|
51896
|
-
/** Storage bound to a persistence backend (OAuth credentials survive restarts). */
|
|
51897
|
-
static fromStorage(backend) {
|
|
51898
|
-
return new _AuthStorage(backend);
|
|
51899
|
-
}
|
|
51900
|
-
/** In-memory backend, for tests and embedders that manage their own persistence. */
|
|
51901
|
-
static inMemory() {
|
|
51902
|
-
return new _AuthStorage(new InMemoryAuthStorageBackend());
|
|
51903
|
-
}
|
|
51904
|
-
/** Drain buffered backend I/O errors (file backend only). */
|
|
51905
|
-
drainErrors() {
|
|
51906
|
-
const backend = this.backend;
|
|
51907
|
-
if (backend && typeof backend.drainErrors === "function") {
|
|
51908
|
-
return backend.drainErrors();
|
|
51909
|
-
}
|
|
51910
|
-
return [];
|
|
51911
|
-
}
|
|
51912
|
-
setLegacyApiKey(apiKey) {
|
|
51913
|
-
this.legacyApiKey = apiKey;
|
|
51914
|
-
}
|
|
51915
|
-
setProviderApiKey(provider, apiKey) {
|
|
51916
|
-
if (!apiKey) {
|
|
51917
|
-
this.providerApiKeys.delete(provider);
|
|
51918
|
-
return;
|
|
51919
|
-
}
|
|
51920
|
-
this.providerApiKeys.set(provider, apiKey);
|
|
51921
|
-
}
|
|
51922
|
-
setRuntimeApiKey(provider, apiKey) {
|
|
51923
|
-
if (!apiKey) {
|
|
51924
|
-
this.runtimeApiKeys.delete(provider);
|
|
51925
|
-
return;
|
|
51926
|
-
}
|
|
51927
|
-
this.runtimeApiKeys.set(provider, apiKey);
|
|
51928
|
-
}
|
|
51929
|
-
setProviderEnvVar(provider, envVar) {
|
|
51930
|
-
if (!envVar) {
|
|
51931
|
-
this.providerEnvVars.delete(provider);
|
|
51932
|
-
return;
|
|
51933
|
-
}
|
|
51934
|
-
this.providerEnvVars.set(provider, envVar);
|
|
51935
|
-
}
|
|
51936
|
-
getProviderEnvVar(provider) {
|
|
51937
|
-
return this.providerEnvVars.get(provider);
|
|
51938
|
-
}
|
|
51939
|
-
setOAuthCredentials(provider, credentials) {
|
|
51940
|
-
if (!credentials) {
|
|
51941
|
-
this.oauthCredentials.delete(provider);
|
|
51942
|
-
this.removedOauthProviders.add(provider);
|
|
51943
|
-
this.runtimeApiKeys.delete(provider);
|
|
51944
|
-
} else {
|
|
51945
|
-
this.oauthCredentials.set(provider, credentials);
|
|
51946
|
-
this.removedOauthProviders.delete(provider);
|
|
51947
|
-
}
|
|
51948
|
-
this.persistOAuth();
|
|
51949
|
-
}
|
|
51950
|
-
getOAuthCredentials(provider) {
|
|
51951
|
-
return this.oauthCredentials.get(provider);
|
|
51952
|
-
}
|
|
51953
|
-
/** Providers with persisted OAuth credentials (for restore/refresh passes). */
|
|
51954
|
-
getOAuthProviderNames() {
|
|
51955
|
-
return [...this.oauthCredentials.keys()];
|
|
51956
|
-
}
|
|
51957
|
-
persistOAuth() {
|
|
51958
|
-
if (!this.backend) return;
|
|
51959
|
-
this.backend.write({
|
|
51960
|
-
oauth: Object.fromEntries(this.oauthCredentials),
|
|
51961
|
-
removedOauth: [...this.removedOauthProviders]
|
|
51962
|
-
});
|
|
51963
|
-
}
|
|
51964
|
-
getApiKey(provider, explicitEnvVar) {
|
|
51965
|
-
const envVar = explicitEnvVar || this.getProviderEnvVar(provider);
|
|
51966
|
-
const envApiKey = envVar && typeof process !== "undefined" ? process.env?.[envVar] : void 0;
|
|
51967
|
-
return this.runtimeApiKeys.get(provider) || this.providerApiKeys.get(provider) || envApiKey || this.usableOAuthAccessToken(provider) || this.legacyApiKey;
|
|
51968
|
-
}
|
|
51969
|
-
/** Persisted OAuth access token, when it exists and has not expired. */
|
|
51970
|
-
usableOAuthAccessToken(provider) {
|
|
51971
|
-
const credentials = this.oauthCredentials.get(provider);
|
|
51972
|
-
if (!credentials?.access) return void 0;
|
|
51973
|
-
if (credentials.expires !== void 0 && credentials.expires <= Date.now() + OAUTH_EXPIRY_SKEW_MS) {
|
|
51974
|
-
return void 0;
|
|
51975
|
-
}
|
|
51976
|
-
return credentials.access;
|
|
51977
|
-
}
|
|
51978
|
-
};
|
|
51979
|
-
|
|
51980
|
-
// src/core/model-registry.ts
|
|
51981
|
-
import * as fs3 from "fs";
|
|
51982
|
-
import * as path3 from "path";
|
|
51983
|
-
import { createHash, createHmac, randomBytes } from "node:crypto";
|
|
51984
|
-
var MODEL_OVERRIDE_KEYS = [
|
|
51985
|
-
"name",
|
|
51986
|
-
"reasoning",
|
|
51987
|
-
"input",
|
|
51988
|
-
"cost",
|
|
51989
|
-
"contextWindow",
|
|
51990
|
-
"maxTokens",
|
|
51991
|
-
"transport",
|
|
51992
|
-
"headers",
|
|
51993
|
-
"compat",
|
|
51994
|
-
"cacheCapability",
|
|
51995
|
-
"webSearch",
|
|
51996
|
-
"fileCapabilities",
|
|
51997
|
-
"displayName"
|
|
51998
|
-
];
|
|
51999
|
-
function validateExtensionProviderConfig(provider, config) {
|
|
52000
|
-
if (!provider || provider !== provider.trim() || /\s/.test(provider)) throw new Error(`registerProvider: invalid provider id "${provider}"`);
|
|
52001
|
-
if (!config || typeof config !== "object") throw new Error("registerProvider: config must be an object");
|
|
52002
|
-
if (typeof config.baseUrl !== "string" || !config.baseUrl) throw new Error(`registerProvider("${provider}"): baseUrl is required`);
|
|
52003
|
-
try {
|
|
52004
|
-
new URL(config.baseUrl);
|
|
52005
|
-
} catch {
|
|
52006
|
-
throw new Error(`registerProvider("${provider}"): baseUrl must be an absolute URL`);
|
|
52007
|
-
}
|
|
52008
|
-
assertHeadersShape(config.headers, `registerProvider("${provider}")`);
|
|
52009
|
-
validateTransport(config.transport, `registerProvider("${provider}")`);
|
|
52010
|
-
for (const model of config.models ?? []) {
|
|
52011
|
-
if (!model || typeof model.id !== "string" || !model.id.trim() || /\s/.test(model.id)) throw new Error(`registerProvider("${provider}"): invalid model id`);
|
|
52012
|
-
assertHeadersShape(model.headers, `registerProvider("${provider}") model "${model.id}"`);
|
|
52013
|
-
validateTransport(model.transport, `Model "${model.id}"`);
|
|
52014
|
-
validateCompat(model.compat, `registerProvider("${provider}") model "${model.id}" compat`);
|
|
52015
|
-
validateCacheCapability(model.cacheCapability, `registerProvider("${provider}") model "${model.id}" cacheCapability`);
|
|
52016
|
-
validateWebSearchCapability(model.webSearch, `registerProvider("${provider}") model "${model.id}" webSearch`);
|
|
52017
|
-
validateFileCapabilities(model.fileCapabilities, `registerProvider("${provider}") model "${model.id}" fileCapabilities`);
|
|
52018
|
-
}
|
|
52019
|
-
}
|
|
52020
|
-
var REMOTE_CATALOG_CACHE_VERSION = 4;
|
|
52021
|
-
var SUPPORTED_REMOTE_APIS = /* @__PURE__ */ new Set(["openai-completions", "anthropic-messages", "openai-responses"]);
|
|
52022
|
-
var MAX_REMOTE_CATALOG_BYTES = 2 * 1024 * 1024;
|
|
52023
|
-
var OAUTH_RESTORE_LEEWAY_MS = 6e4;
|
|
52024
|
-
var OAUTH_REFRESH_TIMEOUT_MS = 3e4;
|
|
52025
|
-
function withTimeout(promise, ms, timeoutMessage) {
|
|
52026
|
-
return new Promise((resolve7, reject) => {
|
|
52027
|
-
const timer = setTimeout(() => reject(new Error(timeoutMessage)), ms);
|
|
52028
|
-
Promise.resolve(promise).then(
|
|
52029
|
-
(value) => {
|
|
52030
|
-
clearTimeout(timer);
|
|
52031
|
-
resolve7(value);
|
|
52032
|
-
},
|
|
52033
|
-
(error) => {
|
|
52034
|
-
clearTimeout(timer);
|
|
52035
|
-
reject(error);
|
|
52036
|
-
}
|
|
52037
|
-
);
|
|
52038
|
-
});
|
|
52039
|
-
}
|
|
52040
|
-
var REMOTE_REFRESH_LOCK_WAIT_MS = 6e4;
|
|
52041
|
-
var REMOTE_REFRESH_LOCK_WRITE_GRACE_MS = 1e3;
|
|
52042
|
-
var remoteRefreshTails = /* @__PURE__ */ new Map();
|
|
52043
|
-
var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
|
|
52044
|
-
"connection",
|
|
52045
|
-
"keep-alive",
|
|
52046
|
-
"proxy-authenticate",
|
|
52047
|
-
"proxy-authorization",
|
|
52048
|
-
"te",
|
|
52049
|
-
"trailer",
|
|
52050
|
-
"transfer-encoding",
|
|
52051
|
-
"upgrade",
|
|
52052
|
-
"host",
|
|
52053
|
-
"content-length"
|
|
52054
|
-
]);
|
|
52055
|
-
function canonicalRemote(remote) {
|
|
52056
|
-
const url = new URL(remote.url);
|
|
52057
|
-
return { id: remote.id, url: url.href, apiKeyEnv: remote.apiKeyEnv };
|
|
52058
|
-
}
|
|
52059
|
-
function remoteIdentityDigest(remote) {
|
|
52060
|
-
return createHash("sha256").update(JSON.stringify({ version: REMOTE_CATALOG_CACHE_VERSION, ...canonicalRemote(remote) })).digest("hex");
|
|
52061
|
-
}
|
|
52062
|
-
function remoteCacheDirectory(modelsPath) {
|
|
52063
|
-
return path3.join(path3.dirname(modelsPath), "cache", "remote-catalogs");
|
|
52064
|
-
}
|
|
52065
|
-
function safeRemoteCacheDirectory(modelsPath, create) {
|
|
52066
|
-
const configDirectory = path3.dirname(modelsPath);
|
|
52067
|
-
if (!fs3.existsSync(configDirectory)) {
|
|
52068
|
-
if (!create) return void 0;
|
|
52069
|
-
fs3.mkdirSync(configDirectory, { recursive: true, mode: 448 });
|
|
52070
|
-
}
|
|
52071
|
-
const configRoot = fs3.realpathSync(configDirectory);
|
|
52072
|
-
const cacheRoot = path3.join(configDirectory, "cache");
|
|
52073
|
-
const directory = remoteCacheDirectory(modelsPath);
|
|
52074
|
-
for (const candidate of [cacheRoot, directory]) {
|
|
52075
|
-
if (!fs3.existsSync(candidate)) {
|
|
52076
|
-
if (!create) return void 0;
|
|
52077
|
-
fs3.mkdirSync(candidate, { mode: 448 });
|
|
52078
|
-
}
|
|
52079
|
-
const stat2 = fs3.lstatSync(candidate);
|
|
52080
|
-
if (stat2.isSymbolicLink() || !stat2.isDirectory()) throw new Error(`remote catalog cache path must be a real directory: ${candidate}`);
|
|
52081
|
-
const canonical = fs3.realpathSync(candidate);
|
|
52082
|
-
const relative3 = path3.relative(configRoot, canonical);
|
|
52083
|
-
if (relative3 === ".." || relative3.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative3)) {
|
|
52084
|
-
throw new Error(`remote catalog cache path escapes the config directory: ${candidate}`);
|
|
52085
|
-
}
|
|
52086
|
-
try {
|
|
52087
|
-
fs3.chmodSync(candidate, 448);
|
|
52088
|
-
} catch {
|
|
52089
|
-
}
|
|
52090
|
-
}
|
|
52091
|
-
return directory;
|
|
52092
|
-
}
|
|
52093
|
-
function remoteRefreshLockPath(modelsPath) {
|
|
52094
|
-
return path3.join(remoteCacheDirectory(modelsPath), ".refresh.lock");
|
|
52095
|
-
}
|
|
52096
|
-
function processIsAlive2(pid) {
|
|
52097
|
-
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
52098
|
-
try {
|
|
52099
|
-
process.kill(pid, 0);
|
|
52100
|
-
return true;
|
|
52101
|
-
} catch (error) {
|
|
52102
|
-
return error.code === "EPERM";
|
|
52103
|
-
}
|
|
52104
|
-
}
|
|
52105
|
-
function remoteRefreshLockIsStale(lockPath) {
|
|
52106
|
-
const stat2 = fs3.lstatSync(lockPath);
|
|
52107
|
-
if (stat2.isSymbolicLink() || !stat2.isFile()) throw new Error(`remote catalog refresh lock must be a regular file: ${lockPath}`);
|
|
52108
|
-
let owner;
|
|
52109
|
-
try {
|
|
52110
|
-
owner = JSON.parse(fs3.readFileSync(lockPath, "utf8"));
|
|
52111
|
-
} catch {
|
|
52112
|
-
}
|
|
52113
|
-
const age = Date.now() - stat2.mtimeMs;
|
|
52114
|
-
const validOwner = owner?.version === 1 && Number.isSafeInteger(owner.pid) && typeof owner.token === "string" && typeof owner.createdAt === "number";
|
|
52115
|
-
if (validOwner && processIsAlive2(Number(owner.pid))) return false;
|
|
52116
|
-
return validOwner || age > REMOTE_REFRESH_LOCK_WRITE_GRACE_MS;
|
|
52117
|
-
}
|
|
52118
|
-
function sameFileIdentity(left, right, leftPath, rightPath) {
|
|
52119
|
-
if (left.dev !== right.dev || left.ino !== right.ino) return false;
|
|
52120
|
-
if (left.ino !== 0) return true;
|
|
52121
|
-
return left.size === right.size && fs3.readFileSync(leftPath).equals(fs3.readFileSync(rightPath));
|
|
52122
|
-
}
|
|
52123
|
-
function reclaimStaleRemoteRefreshLock(lockPath) {
|
|
52124
|
-
if (!remoteRefreshLockIsStale(lockPath)) return false;
|
|
52125
|
-
const claimPath = `${lockPath}.reclaim-${process.pid}-${randomBytes(8).toString("hex")}`;
|
|
52126
|
-
try {
|
|
52127
|
-
fs3.linkSync(lockPath, claimPath);
|
|
52128
|
-
const claimed = fs3.lstatSync(claimPath);
|
|
52129
|
-
const current = fs3.lstatSync(lockPath);
|
|
52130
|
-
if (claimed.isSymbolicLink() || !claimed.isFile() || current.isSymbolicLink() || !current.isFile() || !sameFileIdentity(claimed, current, claimPath, lockPath)) return false;
|
|
52131
|
-
if (!remoteRefreshLockIsStale(claimPath)) return false;
|
|
52132
|
-
fs3.unlinkSync(lockPath);
|
|
52133
|
-
return true;
|
|
52134
|
-
} catch (error) {
|
|
52135
|
-
if (["ENOENT", "EEXIST"].includes(error.code ?? "")) return false;
|
|
52136
|
-
throw error;
|
|
52137
|
-
} finally {
|
|
52138
|
-
try {
|
|
52139
|
-
fs3.unlinkSync(claimPath);
|
|
52140
|
-
} catch {
|
|
52141
|
-
}
|
|
52142
|
-
}
|
|
52143
|
-
}
|
|
52144
|
-
async function acquireRemoteRefreshLock(modelsPath) {
|
|
52145
|
-
const directory = safeRemoteCacheDirectory(modelsPath, true);
|
|
52146
|
-
const lockPath = remoteRefreshLockPath(modelsPath);
|
|
52147
|
-
const deadline = Date.now() + REMOTE_REFRESH_LOCK_WAIT_MS;
|
|
52148
|
-
while (true) {
|
|
52149
|
-
const token = randomBytes(16).toString("hex");
|
|
52150
|
-
try {
|
|
52151
|
-
const fd = fs3.openSync(lockPath, "wx", 384);
|
|
52152
|
-
try {
|
|
52153
|
-
fs3.writeFileSync(fd, `${JSON.stringify({ version: 1, pid: process.pid, token, createdAt: Date.now() })}
|
|
52154
|
-
`);
|
|
52155
|
-
} finally {
|
|
52156
|
-
fs3.closeSync(fd);
|
|
52157
|
-
}
|
|
52158
|
-
return () => {
|
|
52159
|
-
try {
|
|
52160
|
-
const stat2 = fs3.lstatSync(lockPath);
|
|
52161
|
-
if (stat2.isSymbolicLink() || !stat2.isFile()) return;
|
|
52162
|
-
const current = JSON.parse(fs3.readFileSync(lockPath, "utf8"));
|
|
52163
|
-
if (current.token === token) fs3.unlinkSync(lockPath);
|
|
52164
|
-
} catch {
|
|
52165
|
-
}
|
|
52166
|
-
};
|
|
52167
|
-
} catch (error) {
|
|
52168
|
-
if (error.code !== "EEXIST") throw error;
|
|
52169
|
-
try {
|
|
52170
|
-
if (reclaimStaleRemoteRefreshLock(lockPath)) continue;
|
|
52171
|
-
} catch (lockError) {
|
|
52172
|
-
if (lockError.code === "ENOENT") continue;
|
|
52173
|
-
throw lockError;
|
|
52174
|
-
}
|
|
52175
|
-
if (Date.now() >= deadline) throw new Error(`timed out waiting for remote catalog refresh lock: ${lockPath}`);
|
|
52176
|
-
await new Promise((resolve7) => setTimeout(resolve7, 25));
|
|
52177
|
-
}
|
|
52178
|
-
}
|
|
52179
|
-
}
|
|
52180
|
-
function readSafeRemoteCacheFile(directory, filepath) {
|
|
52181
|
-
const stat2 = fs3.lstatSync(filepath);
|
|
52182
|
-
if (stat2.isSymbolicLink() || !stat2.isFile()) throw new Error(`remote catalog cache entry must be a regular file: ${filepath}`);
|
|
52183
|
-
const canonicalDirectory = fs3.realpathSync(directory);
|
|
52184
|
-
const canonicalFile = fs3.realpathSync(filepath);
|
|
52185
|
-
const relative3 = path3.relative(canonicalDirectory, canonicalFile);
|
|
52186
|
-
if (!relative3 || relative3 === ".." || relative3.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative3)) {
|
|
52187
|
-
throw new Error(`remote catalog cache entry escapes its cache directory: ${filepath}`);
|
|
52188
|
-
}
|
|
52189
|
-
return fs3.readFileSync(filepath);
|
|
52190
|
-
}
|
|
52191
|
-
function credentialNamespaceKey(modelsPath, create) {
|
|
52192
|
-
const directory = safeRemoteCacheDirectory(modelsPath, create);
|
|
52193
|
-
if (!directory) return void 0;
|
|
52194
|
-
const keyPath = path3.join(directory, ".credential-namespace-key");
|
|
52195
|
-
if (!fs3.existsSync(keyPath) && !create) return void 0;
|
|
52196
|
-
if (create && !fs3.existsSync(keyPath)) {
|
|
52197
|
-
try {
|
|
52198
|
-
fs3.writeFileSync(keyPath, randomBytes(32), { flag: "wx", mode: 384 });
|
|
52199
|
-
} catch (error) {
|
|
52200
|
-
if (!isPlainRecord(error) || error.code !== "EEXIST") throw error;
|
|
52201
|
-
}
|
|
52202
|
-
}
|
|
52203
|
-
const key = readSafeRemoteCacheFile(directory, keyPath);
|
|
52204
|
-
if (key.byteLength !== 32) throw new Error("remote catalog credential namespace key is invalid");
|
|
52205
|
-
try {
|
|
52206
|
-
fs3.chmodSync(keyPath, 384);
|
|
52207
|
-
} catch {
|
|
52208
|
-
}
|
|
52209
|
-
return key;
|
|
52210
|
-
}
|
|
52211
|
-
function credentialFingerprint(modelsPath, remote, credential, create = false) {
|
|
52212
|
-
const key = credentialNamespaceKey(modelsPath, create);
|
|
52213
|
-
if (!key) return void 0;
|
|
52214
|
-
return createHmac("sha256", key).update(remoteIdentityDigest(remote)).update("\0").update(credential).digest("hex");
|
|
52215
|
-
}
|
|
52216
|
-
function remoteCachePath(modelsPath, remote, fingerprint) {
|
|
52217
|
-
return path3.join(remoteCacheDirectory(modelsPath), `${remoteIdentityDigest(remote)}-${fingerprint}.json`);
|
|
52218
|
-
}
|
|
52219
|
-
function pruneLegacyRemoteCatalogCaches(modelsPath) {
|
|
52220
|
-
const directory = safeRemoteCacheDirectory(modelsPath, false);
|
|
52221
|
-
if (!directory) return;
|
|
52222
|
-
for (const name of fs3.readdirSync(directory)) {
|
|
52223
|
-
if (!name.endsWith(".json")) continue;
|
|
52224
|
-
const filepath = path3.join(directory, name);
|
|
52225
|
-
try {
|
|
52226
|
-
const value = JSON.parse(readSafeRemoteCacheFile(directory, filepath).toString("utf8"));
|
|
52227
|
-
if (value.version === REMOTE_CATALOG_CACHE_VERSION) continue;
|
|
52228
|
-
} catch {
|
|
52229
|
-
let stat2;
|
|
52230
|
-
try {
|
|
52231
|
-
stat2 = fs3.lstatSync(filepath);
|
|
52232
|
-
} catch {
|
|
52233
|
-
continue;
|
|
52234
|
-
}
|
|
52235
|
-
if (stat2.isSymbolicLink() || !stat2.isFile()) continue;
|
|
52236
|
-
}
|
|
52237
|
-
try {
|
|
52238
|
-
fs3.unlinkSync(filepath);
|
|
52239
|
-
} catch {
|
|
52240
|
-
}
|
|
52241
|
-
}
|
|
52242
|
-
}
|
|
52243
|
-
function scrubActiveSecretsFromRemoteCaches(modelsPath, activeSecrets) {
|
|
52244
|
-
if (activeSecrets.length === 0) return;
|
|
52245
|
-
const directory = safeRemoteCacheDirectory(modelsPath, false);
|
|
52246
|
-
if (!directory) return;
|
|
52247
|
-
const handle = fs3.opendirSync(directory);
|
|
52248
|
-
try {
|
|
52249
|
-
let scanned = 0;
|
|
52250
|
-
while (true) {
|
|
52251
|
-
const entry = handle.readSync();
|
|
52252
|
-
if (!entry) break;
|
|
52253
|
-
if (++scanned > 1e4) throw new Error("remote catalog cache directory exceeds the hygiene scan limit");
|
|
52254
|
-
const isCache = entry.name.endsWith(".json");
|
|
52255
|
-
const isOrphanedTemporary = /^\..+\.json\.\d+\.[0-9a-f]+\.tmp$/.test(entry.name);
|
|
52256
|
-
if (!entry.isFile() || !isCache && !isOrphanedTemporary) continue;
|
|
52257
|
-
const filepath = path3.join(directory, entry.name);
|
|
52258
|
-
try {
|
|
52259
|
-
const raw = readSafeRemoteCacheFile(directory, filepath).toString("utf8");
|
|
52260
|
-
assertNoSecretSubstrings(raw, activeSecrets, "remote catalog cache");
|
|
52261
|
-
} catch {
|
|
52262
|
-
try {
|
|
52263
|
-
const stat2 = fs3.lstatSync(filepath);
|
|
52264
|
-
if (!stat2.isSymbolicLink() && stat2.isFile()) fs3.unlinkSync(filepath);
|
|
52265
|
-
} catch {
|
|
52266
|
-
}
|
|
52267
|
-
}
|
|
52268
|
-
}
|
|
52269
|
-
} finally {
|
|
52270
|
-
handle.closeSync();
|
|
52271
|
-
}
|
|
52272
|
-
}
|
|
52273
|
-
function payloadDigest(payload) {
|
|
52274
|
-
return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
|
|
52275
|
-
}
|
|
52276
|
-
function assertNoSecretSubstrings(value, secrets, label) {
|
|
52277
|
-
const active = [...new Set(secrets.filter((secret) => secret.length > 0))];
|
|
52278
|
-
if (active.length === 0) return;
|
|
52279
|
-
const seen = /* @__PURE__ */ new Set();
|
|
52280
|
-
const visit = (candidate) => {
|
|
52281
|
-
if (typeof candidate === "string") {
|
|
52282
|
-
if (active.some((secret) => candidate.includes(secret))) throw new Error(`${label} reflects an active credential`);
|
|
52283
|
-
return;
|
|
52284
|
-
}
|
|
52285
|
-
if (!candidate || typeof candidate !== "object" || seen.has(candidate)) return;
|
|
52286
|
-
seen.add(candidate);
|
|
52287
|
-
if (Array.isArray(candidate)) {
|
|
52288
|
-
for (const item of candidate) visit(item);
|
|
52289
|
-
return;
|
|
52290
|
-
}
|
|
52291
|
-
for (const [key, item] of Object.entries(candidate)) {
|
|
52292
|
-
visit(key);
|
|
52293
|
-
visit(item);
|
|
52294
|
-
}
|
|
52295
|
-
};
|
|
52296
|
-
visit(value);
|
|
52297
|
-
const serialized = JSON.stringify(value);
|
|
52298
|
-
if (active.some((secret) => serialized.includes(secret))) throw new Error(`${label} reflects an active credential`);
|
|
52299
|
-
}
|
|
52300
|
-
function safeRemoteText(value, secrets) {
|
|
52301
|
-
let message = String(value);
|
|
52302
|
-
const active = [...new Set(secrets.filter(Boolean))];
|
|
52303
|
-
const replacement = active.some((secret) => "[REDACTED]".includes(secret)) ? "" : "[REDACTED]";
|
|
52304
|
-
for (const secret of active) message = message.split(secret).join(replacement);
|
|
52305
|
-
message = message.slice(0, 1024);
|
|
52306
|
-
if (!active.some((secret) => message.includes(secret))) return message;
|
|
52307
|
-
return "";
|
|
52308
|
-
}
|
|
52309
|
-
function safeRemoteError(error, secrets) {
|
|
52310
|
-
return safeRemoteText(error instanceof Error ? `${error.name}: ${error.message}` : String(error), secrets);
|
|
52311
|
-
}
|
|
52312
|
-
function warnRemoteCatalog(message, secrets) {
|
|
52313
|
-
console.warn(safeRemoteText(message, secrets));
|
|
52314
|
-
}
|
|
52315
|
-
function configuredRemoteCredentialValues(config) {
|
|
52316
|
-
let remotes;
|
|
52317
|
-
try {
|
|
52318
|
-
remotes = validatedRemoteCatalogs(config.remoteCatalogs);
|
|
52319
|
-
} catch {
|
|
52320
|
-
return [];
|
|
52321
|
-
}
|
|
52322
|
-
return [...new Set(remotes.map((remote) => process.env[remote.apiKeyEnv]).filter((secret) => typeof secret === "string" && secret.length > 0))];
|
|
52323
|
-
}
|
|
52324
|
-
function sameRemoteIdentity(left, right) {
|
|
52325
|
-
if (!left || typeof left !== "object" || Array.isArray(left)) return false;
|
|
52326
|
-
const value = left;
|
|
52327
|
-
const expected = canonicalRemote(right);
|
|
52328
|
-
return value.id === expected.id && value.url === expected.url && value.apiKeyEnv === expected.apiKeyEnv;
|
|
52329
|
-
}
|
|
52330
|
-
function readRemoteCache(modelsPath, remote, fingerprint, activeSecrets) {
|
|
52331
|
-
try {
|
|
52332
|
-
const directory = safeRemoteCacheDirectory(modelsPath, false);
|
|
52333
|
-
if (!directory) return void 0;
|
|
52334
|
-
const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
|
|
52335
|
-
if (fs3.existsSync(tombstone)) return void 0;
|
|
52336
|
-
const value = JSON.parse(readSafeRemoteCacheFile(directory, remoteCachePath(modelsPath, remote, fingerprint)).toString("utf8"));
|
|
52337
|
-
if (value.version !== REMOTE_CATALOG_CACHE_VERSION || !sameRemoteIdentity(value.identity, remote) || value.credentialFingerprint !== fingerprint || typeof value.payloadSha256 !== "string" || value.payloadSha256 !== payloadDigest(value.payload)) return void 0;
|
|
52338
|
-
assertNoSecretSubstrings({ etag: value.etag, payload: value.payload }, activeSecrets, "remote catalog cache");
|
|
52339
|
-
const payload = sanitizeRemotePayload(value.payload, canonicalRemote(remote), new URL(remote.url), true);
|
|
52340
|
-
if (payloadDigest(payload) !== value.payloadSha256) return void 0;
|
|
52341
|
-
return { ...value, payload };
|
|
52342
|
-
} catch {
|
|
52343
|
-
removeRemoteCache(modelsPath, remote, fingerprint);
|
|
52344
|
-
return void 0;
|
|
52345
|
-
}
|
|
52346
|
-
}
|
|
52347
|
-
function remoteCacheTombstonePath(modelsPath, remote, fingerprint) {
|
|
52348
|
-
return `${remoteCachePath(modelsPath, remote, fingerprint)}.revoked`;
|
|
52349
|
-
}
|
|
52350
|
-
function removeRemoteCache(modelsPath, remote, fingerprint) {
|
|
52351
|
-
try {
|
|
52352
|
-
const directory = safeRemoteCacheDirectory(modelsPath, false);
|
|
52353
|
-
if (!directory) return;
|
|
52354
|
-
const filepath = remoteCachePath(modelsPath, remote, fingerprint);
|
|
52355
|
-
if (fs3.existsSync(filepath)) {
|
|
52356
|
-
const stat2 = fs3.lstatSync(filepath);
|
|
52357
|
-
if (stat2.isSymbolicLink() || !stat2.isFile()) throw new Error(`remote catalog cache entry is not a regular file: ${filepath}`);
|
|
52358
|
-
fs3.unlinkSync(filepath);
|
|
52359
|
-
}
|
|
52360
|
-
const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
|
|
52361
|
-
if (fs3.existsSync(tombstone)) fs3.unlinkSync(tombstone);
|
|
52362
|
-
return;
|
|
52363
|
-
} catch (error) {
|
|
52364
|
-
const directory = safeRemoteCacheDirectory(modelsPath, true);
|
|
52365
|
-
if (!directory) throw error;
|
|
52366
|
-
const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
|
|
52367
|
-
try {
|
|
52368
|
-
fs3.writeFileSync(tombstone, `${JSON.stringify({ version: 1, revoked: true })}
|
|
52369
|
-
`, { flag: "wx", mode: 384 });
|
|
52370
|
-
} catch (tombstoneError) {
|
|
52371
|
-
if (!fs3.existsSync(tombstone)) throw tombstoneError;
|
|
52372
|
-
}
|
|
52373
|
-
}
|
|
52374
|
-
}
|
|
52375
|
-
function validateRemoteEndpoint(baseUrl, catalogUrl, label) {
|
|
52376
|
-
let endpoint;
|
|
52377
|
-
try {
|
|
52378
|
-
endpoint = new URL(baseUrl);
|
|
52379
|
-
} catch {
|
|
52380
|
-
throw new Error(`${label} baseUrl must be an absolute URL`);
|
|
52381
|
-
}
|
|
52382
|
-
if (endpoint.protocol !== "https:" && endpoint.hostname !== "127.0.0.1" && endpoint.hostname !== "localhost") {
|
|
52383
|
-
throw new Error(`${label} baseUrl must use HTTPS`);
|
|
52384
|
-
}
|
|
52385
|
-
if (endpoint.username || endpoint.password) throw new Error(`${label} baseUrl must not contain credentials`);
|
|
52386
|
-
if (endpoint.hash) throw new Error(`${label} baseUrl must not contain a fragment`);
|
|
52387
|
-
if (endpoint.search) throw new Error(`${label} baseUrl must not contain query parameters`);
|
|
52388
|
-
if (endpoint.origin !== catalogUrl.origin) throw new Error(`${label} baseUrl must use the authenticated catalog origin`);
|
|
52389
|
-
}
|
|
52390
|
-
function isPlainRecord(value) {
|
|
52391
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
52392
|
-
const prototype = Object.getPrototypeOf(value);
|
|
52393
|
-
return prototype === Object.prototype || prototype === null;
|
|
52394
|
-
}
|
|
52395
|
-
function assertOnlyKeys(value, allowed, label) {
|
|
52396
|
-
const allowedSet = new Set(allowed);
|
|
52397
|
-
const unexpected = Object.keys(value).find((key) => !allowedSet.has(key));
|
|
52398
|
-
if (unexpected) throw new Error(`${label} contains unsupported field ${unexpected}`);
|
|
52399
|
-
}
|
|
52400
|
-
function validateRemoteCatalogConfig(value, label) {
|
|
52401
|
-
if (!isPlainRecord(value)) throw new Error(`${label} must be an object`);
|
|
52402
|
-
assertOnlyKeys(value, ["id", "url", "apiKeyEnv"], label);
|
|
52403
|
-
if (typeof value.id !== "string" || !value.id.trim() || value.id !== value.id.trim() || /\s/.test(value.id)) throw new Error(`${label}.id must be a non-empty identifier without whitespace`);
|
|
52404
|
-
if (typeof value.url !== "string" || !value.url) throw new Error(`${label}.url must be a URL`);
|
|
52405
|
-
if (typeof value.apiKeyEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.apiKeyEnv)) throw new Error(`${label}.apiKeyEnv must be an environment variable name`);
|
|
52406
|
-
let url;
|
|
52407
|
-
try {
|
|
52408
|
-
url = new URL(value.url);
|
|
52409
|
-
} catch {
|
|
52410
|
-
throw new Error(`${label}.url must be an absolute URL`);
|
|
52411
|
-
}
|
|
52412
|
-
const localTestHost = url.hostname === "127.0.0.1" || url.hostname === "localhost";
|
|
52413
|
-
if (url.protocol !== "https:" && !localTestHost) throw new Error(`${label}.url must use HTTPS`);
|
|
52414
|
-
if (url.username || url.password) throw new Error(`${label}.url must not contain credentials`);
|
|
52415
|
-
if (url.hash) throw new Error(`${label}.url must not contain a fragment`);
|
|
52416
|
-
if (url.search) throw new Error(`${label}.url must not contain query parameters`);
|
|
52417
|
-
return canonicalRemote({ id: value.id, url: url.href, apiKeyEnv: value.apiKeyEnv });
|
|
52418
|
-
}
|
|
52419
|
-
function validatedRemoteCatalogs(value) {
|
|
52420
|
-
if (value === void 0) return [];
|
|
52421
|
-
if (!Array.isArray(value)) throw new Error("models.json remoteCatalogs must be an array");
|
|
52422
|
-
if (value.length === 0) throw new Error("models.json remoteCatalogs must be a non-empty array");
|
|
52423
|
-
const catalogs = value.map((item, index) => validateRemoteCatalogConfig(item, `models.json remoteCatalogs[${index}]`));
|
|
52424
|
-
const ids = /* @__PURE__ */ new Set();
|
|
52425
|
-
for (const catalog of catalogs) {
|
|
52426
|
-
if (ids.has(catalog.id)) throw new Error(`models.json remoteCatalogs contains duplicate id ${catalog.id}`);
|
|
52427
|
-
ids.add(catalog.id);
|
|
52428
|
-
}
|
|
52429
|
-
return catalogs;
|
|
52430
|
-
}
|
|
52431
|
-
function validateModelsDocumentShape(value) {
|
|
52432
|
-
if (!isPlainRecord(value)) throw new Error("models.json must be an object");
|
|
52433
|
-
assertOnlyKeys(value, ["$schema", "profiles", "remoteCatalogs", "defaults", "modelOverrides"], "models.json");
|
|
52434
|
-
if (value.$schema !== void 0 && (typeof value.$schema !== "string" || !value.$schema)) throw new Error("models.json $schema must be a non-empty string");
|
|
52435
|
-
const hasProfiles = Object.prototype.hasOwnProperty.call(value, "profiles");
|
|
52436
|
-
const hasRemoteCatalogs = Object.prototype.hasOwnProperty.call(value, "remoteCatalogs");
|
|
52437
|
-
if (!hasProfiles && !hasRemoteCatalogs) throw new Error("models.json must define profiles or remoteCatalogs");
|
|
52438
|
-
validatedRemoteCatalogs(value.remoteCatalogs);
|
|
52439
|
-
if (hasProfiles) {
|
|
52440
|
-
if (!isPlainRecord(value.profiles) || Object.keys(value.profiles).length === 0) throw new Error("models.json profiles must be a non-empty object");
|
|
52441
|
-
for (const [profileId, profile] of Object.entries(value.profiles)) {
|
|
52442
|
-
if (!profileId || profileId !== profileId.trim() || /\s/.test(profileId)) throw new Error(`models.json profile id is invalid: ${profileId}`);
|
|
52443
|
-
validateProfileConfig(profileId, profile);
|
|
52444
|
-
}
|
|
52445
|
-
}
|
|
52446
|
-
validateModelOverrides(value.modelOverrides);
|
|
52447
|
-
if (value.defaults !== void 0) {
|
|
52448
|
-
if (!isPlainRecord(value.defaults)) throw new Error("models.json defaults must be an object");
|
|
52449
|
-
assertOnlyKeys(value.defaults, ["provider", "modelId", "modelClasses", "toolModels"], "models.json defaults");
|
|
52450
|
-
assertOptionalString(value.defaults.provider, "models.json defaults.provider");
|
|
52451
|
-
assertOptionalString(value.defaults.modelId, "models.json defaults.modelId");
|
|
52452
|
-
for (const [field, allowed] of [["modelClasses", ["light", "balanced", "strong"]], ["toolModels", ["web_search", "read_file.image", "read_file.video", "read_file.audio", "read_file.document"]]]) {
|
|
52453
|
-
const routes = value.defaults[field];
|
|
52454
|
-
if (routes === void 0) continue;
|
|
52455
|
-
if (!isPlainRecord(routes)) throw new Error(`models.json defaults.${field} must be an object`);
|
|
52456
|
-
assertOnlyKeys(routes, allowed, `models.json defaults.${field}`);
|
|
52457
|
-
for (const [routeName, route] of Object.entries(routes)) {
|
|
52458
|
-
if (!isPlainRecord(route)) throw new Error(`models.json defaults.${field}.${routeName} must be an object`);
|
|
52459
|
-
assertOnlyKeys(route, ["provider", "modelId"], `models.json defaults.${field}.${routeName}`);
|
|
52460
|
-
assertOptionalString(route.provider, `models.json defaults.${field}.${routeName}.provider`);
|
|
52461
|
-
assertOptionalString(route.modelId, `models.json defaults.${field}.${routeName}.modelId`);
|
|
52462
|
-
}
|
|
52463
|
-
}
|
|
52464
|
-
}
|
|
52465
|
-
}
|
|
52466
|
-
function assertOptionalString(value, label) {
|
|
52467
|
-
if (value !== void 0 && (typeof value !== "string" || !value)) throw new Error(`${label} must be a non-empty string`);
|
|
52468
|
-
}
|
|
52469
|
-
function assertOptionalEnvName(value, label) {
|
|
52470
|
-
if (value !== void 0 && (typeof value !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value))) {
|
|
52471
|
-
throw new Error(`${label} must be an environment variable name`);
|
|
52472
|
-
}
|
|
52473
|
-
}
|
|
52474
|
-
function assertOptionalBoolean(value, label) {
|
|
52475
|
-
if (value !== void 0 && typeof value !== "boolean") throw new Error(`${label} must be a boolean`);
|
|
52476
|
-
}
|
|
52477
|
-
function validateCacheCapability(value, label) {
|
|
52478
|
-
if (value === void 0) return;
|
|
52479
|
-
if (!isPlainRecord(value) || !["none", "session_store", "prompt_cache", "usage_only"].includes(String(value.mode)) || typeof value.supported !== "boolean") throw new Error(`${label} is invalid`);
|
|
52480
|
-
assertOnlyKeys(value, ["mode", "supported", "supportsUsageMetrics", "description"], label);
|
|
52481
|
-
assertOptionalBoolean(value.supportsUsageMetrics, `${label}.supportsUsageMetrics`);
|
|
52482
|
-
assertOptionalString(value.description, `${label}.description`);
|
|
52483
|
-
}
|
|
52484
|
-
function validateWebSearchCapability(value, label) {
|
|
52485
|
-
if (value === void 0) return;
|
|
52486
|
-
if (!isPlainRecord(value) || !["anthropic_server_tool", "chat_completions_web_search", "openai_responses"].includes(String(value.type))) {
|
|
52487
|
-
throw new Error(`${label} is invalid`);
|
|
52488
|
-
}
|
|
52489
|
-
assertOnlyKeys(value, ["type", "forceToolChoice", "searchEngine", "count", "contentSize"], label);
|
|
52490
|
-
assertOptionalBoolean(value.forceToolChoice, `${label}.forceToolChoice`);
|
|
52491
|
-
assertOptionalString(value.searchEngine, `${label}.searchEngine`);
|
|
52492
|
-
if (value.count !== void 0 && (!Number.isInteger(value.count) || Number(value.count) < 1)) throw new Error(`${label}.count is invalid`);
|
|
52493
|
-
if (value.contentSize !== void 0 && !["low", "medium", "high"].includes(String(value.contentSize))) throw new Error(`${label}.contentSize is invalid`);
|
|
52494
|
-
}
|
|
52495
|
-
function validateFileCapabilities(value, label) {
|
|
52496
|
-
if (value === void 0) return;
|
|
52497
|
-
if (!isPlainRecord(value)) throw new Error(`${label} is invalid`);
|
|
52498
|
-
for (const [kind, capability] of Object.entries(value)) {
|
|
52499
|
-
if (!["image", "video", "audio", "document"].includes(kind)) throw new Error(`${label}.${kind} is unsupported`);
|
|
52500
|
-
if (typeof capability === "boolean") continue;
|
|
52501
|
-
if (!isPlainRecord(capability)) throw new Error(`${label}.${kind} is invalid`);
|
|
52502
|
-
assertOnlyKeys(capability, ["supported", "formats", "maxFileSizeMb", "maxDurationSeconds", "nativeInline"], `${label}.${kind}`);
|
|
52503
|
-
assertOptionalBoolean(capability.supported, `${label}.${kind}.supported`);
|
|
52504
|
-
assertOptionalBoolean(capability.nativeInline, `${label}.${kind}.nativeInline`);
|
|
52505
|
-
if (capability.formats !== void 0 && (!Array.isArray(capability.formats) || capability.formats.some((item) => typeof item !== "string" || !item))) {
|
|
52506
|
-
throw new Error(`${label}.${kind}.formats is invalid`);
|
|
52507
|
-
}
|
|
52508
|
-
if (Array.isArray(capability.formats) && new Set(capability.formats).size !== capability.formats.length) {
|
|
52509
|
-
throw new Error(`${label}.${kind}.formats contains duplicates`);
|
|
52510
|
-
}
|
|
52511
|
-
for (const field of ["maxFileSizeMb", "maxDurationSeconds"]) {
|
|
52512
|
-
if (capability[field] !== void 0 && (typeof capability[field] !== "number" || !Number.isFinite(capability[field]) || capability[field] <= 0)) {
|
|
52513
|
-
throw new Error(`${label}.${kind}.${field} is invalid`);
|
|
52514
|
-
}
|
|
52515
|
-
}
|
|
52516
|
-
}
|
|
52517
|
-
}
|
|
52518
|
-
function validateTransport(value, label) {
|
|
52519
|
-
if (value !== void 0 && value !== "sse" && value !== "websocket" && value !== "auto") throw new Error(`${label}.transport is invalid`);
|
|
52520
|
-
}
|
|
52521
|
-
function validateCompat(value, label) {
|
|
52522
|
-
if (value === void 0) return;
|
|
52523
|
-
if (!isPlainRecord(value)) throw new Error(`${label} is invalid`);
|
|
52524
|
-
assertOnlyKeys(value, [
|
|
52525
|
-
"forcedReasoningEffort",
|
|
52526
|
-
"store",
|
|
52527
|
-
"supportsEncryptedReasoning",
|
|
52528
|
-
"responsesContinuation",
|
|
52529
|
-
"supportsReasoningSummary",
|
|
52530
|
-
"reasoningSummary",
|
|
52531
|
-
"timeoutReplay",
|
|
52532
|
-
"supportsStore",
|
|
52533
|
-
"supportsDeveloperRole",
|
|
52534
|
-
"supportsReasoningEffort",
|
|
52535
|
-
"supportsUsageInStreaming",
|
|
52536
|
-
"maxTokensField",
|
|
52537
|
-
"requiresToolResultName",
|
|
52538
|
-
"requiresAssistantAfterToolResult",
|
|
52539
|
-
"requiresThinkingAsText",
|
|
52540
|
-
"supportsStrictMode",
|
|
52541
|
-
"streamRequiresDone",
|
|
52542
|
-
"streamRequiresFinishReason",
|
|
52543
|
-
"cacheCapability"
|
|
52544
|
-
], label);
|
|
52545
|
-
if (value.forcedReasoningEffort !== void 0 && value.forcedReasoningEffort !== "none") {
|
|
52546
|
-
throw new Error(`${label}.forcedReasoningEffort must be "none"`);
|
|
52547
|
-
}
|
|
52548
|
-
if (value.reasoningSummary !== void 0 && !["auto", "concise", "detailed", "none"].includes(String(value.reasoningSummary))) {
|
|
52549
|
-
throw new Error(`${label}.reasoningSummary must be auto | concise | detailed | none`);
|
|
52550
|
-
}
|
|
52551
|
-
for (const field of [
|
|
52552
|
-
"store",
|
|
52553
|
-
"supportsEncryptedReasoning",
|
|
52554
|
-
"responsesContinuation",
|
|
52555
|
-
"supportsReasoningSummary",
|
|
52556
|
-
"timeoutReplay",
|
|
52557
|
-
"supportsStore",
|
|
52558
|
-
"supportsDeveloperRole",
|
|
52559
|
-
"supportsReasoningEffort",
|
|
52560
|
-
"supportsUsageInStreaming",
|
|
52561
|
-
"requiresToolResultName",
|
|
52562
|
-
"requiresAssistantAfterToolResult",
|
|
52563
|
-
"requiresThinkingAsText",
|
|
52564
|
-
"supportsStrictMode",
|
|
52565
|
-
"streamRequiresDone",
|
|
52566
|
-
"streamRequiresFinishReason"
|
|
52567
|
-
]) assertOptionalBoolean(value[field], `${label}.${field}`);
|
|
52568
|
-
if (value.maxTokensField !== void 0 && value.maxTokensField !== "max_completion_tokens" && value.maxTokensField !== "max_tokens") {
|
|
52569
|
-
throw new Error(`${label}.maxTokensField is invalid`);
|
|
52570
|
-
}
|
|
52571
|
-
validateCacheCapability(value.cacheCapability, `${label}.cacheCapability`);
|
|
52572
|
-
}
|
|
52573
|
-
function validateRemoteModel(profileId, model) {
|
|
52574
|
-
if (!isPlainRecord(model) || typeof model.id !== "string" || !model.id.trim() || model.id !== model.id.trim() || /\s/.test(model.id)) throw new Error(`Remote profile "${profileId}" contains an invalid model id`);
|
|
52575
|
-
assertOnlyKeys(model, [
|
|
52576
|
-
"id",
|
|
52577
|
-
"api",
|
|
52578
|
-
"name",
|
|
52579
|
-
"reasoning",
|
|
52580
|
-
"input",
|
|
52581
|
-
"cost",
|
|
52582
|
-
"contextWindow",
|
|
52583
|
-
"maxTokens",
|
|
52584
|
-
"transport",
|
|
52585
|
-
"compat",
|
|
52586
|
-
"cacheCapability",
|
|
52587
|
-
"webSearch",
|
|
52588
|
-
"fileCapabilities",
|
|
52589
|
-
"headers",
|
|
52590
|
-
"apiKeyEnv",
|
|
52591
|
-
"displayName",
|
|
52592
|
-
"filePlatform",
|
|
52593
|
-
"attachmentPlatform"
|
|
52594
|
-
], `Remote profile "${profileId}" model "${model.id}"`);
|
|
52595
|
-
for (const field of ["name", "displayName", "filePlatform", "attachmentPlatform", "apiKeyEnv"]) {
|
|
52596
|
-
assertOptionalString(model[field], `Remote profile "${profileId}" model "${model.id}" ${field}`);
|
|
52597
|
-
}
|
|
52598
|
-
if (model.api !== void 0 && !SUPPORTED_REMOTE_APIS.has(model.api)) throw new Error(`Model "${model.id}" has unsupported api ${model.api}`);
|
|
52599
|
-
assertOptionalBoolean(model.reasoning, `Remote profile "${profileId}" model "${model.id}" reasoning`);
|
|
52600
|
-
if (!Array.isArray(model.input) || model.input.length === 0 || model.input.some((item) => !["text", "image", "audio", "video"].includes(item))) {
|
|
52601
|
-
throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid input capabilities`);
|
|
52602
|
-
}
|
|
52603
|
-
if (!isPlainRecord(model.cost)) throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid cost values`);
|
|
52604
|
-
assertOnlyKeys(model.cost, ["input", "output", "cacheRead", "cacheWrite", "cacheWriteLong"], `Remote profile "${profileId}" model "${model.id}" cost`);
|
|
52605
|
-
const invalidRate = (value) => typeof value !== "number" || !Number.isFinite(value) || value < 0;
|
|
52606
|
-
if ([model.cost.input, model.cost.output, model.cost.cacheRead, model.cost.cacheWrite].some(invalidRate) || model.cost.cacheWriteLong !== void 0 && invalidRate(model.cost.cacheWriteLong)) {
|
|
52607
|
-
throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid cost values`);
|
|
52608
|
-
}
|
|
52609
|
-
if (!Number.isSafeInteger(model.contextWindow) || Number(model.contextWindow) <= 0 || !Number.isSafeInteger(model.maxTokens) || Number(model.maxTokens) <= 0 || Number(model.maxTokens) > Number(model.contextWindow)) {
|
|
52610
|
-
throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid token limits`);
|
|
52611
|
-
}
|
|
52612
|
-
if (new Set(model.input).size !== model.input.length) throw new Error(`Remote profile "${profileId}" model "${model.id}" has duplicate input capabilities`);
|
|
52613
|
-
validateTransport(model.transport, `Model "${model.id}"`);
|
|
52614
|
-
validateCompat(model.compat, `Remote profile "${profileId}" model "${model.id}" compat`);
|
|
52615
|
-
validateCacheCapability(model.cacheCapability, `Remote profile "${profileId}" model "${model.id}" cacheCapability`);
|
|
52616
|
-
validateWebSearchCapability(model.webSearch, `Remote profile "${profileId}" model "${model.id}" webSearch`);
|
|
52617
|
-
validateFileCapabilities(model.fileCapabilities, `Remote profile "${profileId}" model "${model.id}" fileCapabilities`);
|
|
52618
|
-
}
|
|
52619
|
-
function assertHeadersShape(headers2, label) {
|
|
52620
|
-
if (headers2 === void 0) return;
|
|
52621
|
-
if (!isPlainRecord(headers2)) throw new Error(`${label} headers must be an object`);
|
|
52622
|
-
for (const [name, value] of Object.entries(headers2)) {
|
|
52623
|
-
if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw new Error(`${label} header name ${name || "(empty)"} is invalid`);
|
|
52624
|
-
if (typeof value !== "string") throw new Error(`${label} header ${name} must be a string`);
|
|
52625
|
-
if (/[\0-\x08\x0A-\x1F\x7F]/.test(value)) throw new Error(`${label} header ${name} contains an invalid control character`);
|
|
52626
|
-
}
|
|
52627
|
-
}
|
|
52628
|
-
function assertRemoteHeadersSafe(headers2, label) {
|
|
52629
|
-
assertHeadersShape(headers2, label);
|
|
52630
|
-
for (const name of Object.keys(headers2 || {})) {
|
|
52631
|
-
if (/(?:authorization|cookie|api[-_]?key|token|secret|credential)/i.test(name)) {
|
|
52632
|
-
throw new Error(`${label} must not provide credential-bearing header ${name}`);
|
|
52633
|
-
}
|
|
52634
|
-
if (HOP_BY_HOP_HEADERS.has(name.toLowerCase())) throw new Error(`${label} must not provide transport header ${name}`);
|
|
52635
|
-
}
|
|
52636
|
-
}
|
|
52637
|
-
function sanitizeRemotePayload(decoded, remote, catalogUrl, allowLocallyInjectedCredential = false) {
|
|
52638
|
-
if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) throw new Error("catalog response must be an object");
|
|
52639
|
-
assertOnlyKeys(decoded, ["profiles"], "catalog response");
|
|
52640
|
-
const sourceProfiles = decoded.profiles;
|
|
52641
|
-
if (!sourceProfiles || typeof sourceProfiles !== "object" || Array.isArray(sourceProfiles)) {
|
|
52642
|
-
throw new Error("catalog response profiles must be an object");
|
|
52643
|
-
}
|
|
52644
|
-
const profiles = /* @__PURE__ */ Object.create(null);
|
|
52645
|
-
for (const [provider, source] of Object.entries(sourceProfiles)) {
|
|
52646
|
-
if (!provider || provider !== provider.trim() || /\s/.test(provider) || !isPlainRecord(source)) throw new Error("catalog contains an invalid profile");
|
|
52647
|
-
assertOnlyKeys(source, [
|
|
52648
|
-
"baseUrl",
|
|
52649
|
-
"endpoints",
|
|
52650
|
-
"api",
|
|
52651
|
-
"apiKey",
|
|
52652
|
-
"apiKeyEnv",
|
|
52653
|
-
"headers",
|
|
52654
|
-
"displayName",
|
|
52655
|
-
"filePlatform",
|
|
52656
|
-
"attachmentPlatform",
|
|
52657
|
-
"transport",
|
|
52658
|
-
"compat",
|
|
52659
|
-
"cacheCapability",
|
|
52660
|
-
"webSearch",
|
|
52661
|
-
"fileCapabilities",
|
|
52662
|
-
"models"
|
|
52663
|
-
], `Remote profile "${provider}"`);
|
|
52664
|
-
if (Object.prototype.hasOwnProperty.call(source, "apiKey") || Object.prototype.hasOwnProperty.call(source, "apiKeyEnv") && (!allowLocallyInjectedCredential || source.apiKeyEnv !== remote.apiKeyEnv)) {
|
|
52665
|
-
throw new Error(`Remote profile "${provider}" must not declare credential fields`);
|
|
52666
|
-
}
|
|
52667
|
-
if (!source.api || !SUPPORTED_REMOTE_APIS.has(source.api)) throw new Error(`Remote profile "${provider}" has unsupported api`);
|
|
52668
|
-
if (!source.baseUrl) throw new Error(`Remote profile "${provider}" has no baseUrl`);
|
|
52669
|
-
for (const field of ["baseUrl", "api", "displayName", "filePlatform", "attachmentPlatform", "apiKeyEnv"]) {
|
|
52670
|
-
assertOptionalString(source[field], `Remote profile "${provider}" ${field}`);
|
|
52671
|
-
}
|
|
52672
|
-
validateRemoteEndpoint(source.baseUrl, catalogUrl, `Remote profile "${provider}"`);
|
|
52673
|
-
validateProfileEndpoints(source, `Remote profile "${provider}"`);
|
|
52674
|
-
for (const [api, endpoint] of Object.entries(source.endpoints ?? {})) {
|
|
52675
|
-
validateRemoteEndpoint(endpoint, catalogUrl, `Remote profile "${provider}" endpoints.${api}`);
|
|
52676
|
-
}
|
|
52677
|
-
if (!Array.isArray(source.models) || source.models.length === 0) throw new Error(`Remote profile "${provider}" has no models`);
|
|
52678
|
-
assertRemoteHeadersSafe(source.headers, `Remote profile "${provider}"`);
|
|
52679
|
-
validateTransport(source.transport, `Remote profile "${provider}"`);
|
|
52680
|
-
validateCompat(source.compat, `Remote profile "${provider}" compat`);
|
|
52681
|
-
validateCacheCapability(source.cacheCapability, `Remote profile "${provider}" cacheCapability`);
|
|
52682
|
-
validateWebSearchCapability(source.webSearch, `Remote profile "${provider}" webSearch`);
|
|
52683
|
-
validateFileCapabilities(source.fileCapabilities, `Remote profile "${provider}" fileCapabilities`);
|
|
52684
|
-
const seen = /* @__PURE__ */ new Set();
|
|
52685
|
-
for (const model of source.models) {
|
|
52686
|
-
if (isPlainRecord(model) && Object.prototype.hasOwnProperty.call(model, "apiKeyEnv") && (!allowLocallyInjectedCredential || model.apiKeyEnv !== remote.apiKeyEnv)) {
|
|
52687
|
-
throw new Error(`Remote profile "${provider}" model must not declare credential fields`);
|
|
52688
|
-
}
|
|
52689
|
-
validateRemoteModel(provider, model);
|
|
52690
|
-
assertRemoteHeadersSafe(model.headers, `Remote profile "${provider}" model "${model.id}"`);
|
|
52691
|
-
if (seen.has(model.id)) throw new Error(`Remote profile "${provider}" contains duplicate model "${model.id}"`);
|
|
52692
|
-
seen.add(model.id);
|
|
52693
|
-
}
|
|
52694
|
-
const sanitized = {
|
|
52695
|
-
baseUrl: source.baseUrl,
|
|
52696
|
-
...source.endpoints === void 0 ? {} : { endpoints: { ...source.endpoints } },
|
|
52697
|
-
api: source.api,
|
|
52698
|
-
transport: source.transport,
|
|
52699
|
-
apiKeyEnv: remote.apiKeyEnv,
|
|
52700
|
-
...source.headers === void 0 ? {} : { headers: { ...source.headers } },
|
|
52701
|
-
...source.displayName === void 0 ? {} : { displayName: source.displayName },
|
|
52702
|
-
...source.filePlatform === void 0 ? {} : { filePlatform: source.filePlatform },
|
|
52703
|
-
...source.attachmentPlatform === void 0 ? {} : { attachmentPlatform: source.attachmentPlatform },
|
|
52704
|
-
...source.compat === void 0 ? {} : { compat: { ...source.compat } },
|
|
52705
|
-
...source.cacheCapability === void 0 ? {} : { cacheCapability: { ...source.cacheCapability } },
|
|
52706
|
-
...source.webSearch === void 0 ? {} : { webSearch: { ...source.webSearch } },
|
|
52707
|
-
...source.fileCapabilities === void 0 ? {} : { fileCapabilities: { ...source.fileCapabilities } },
|
|
52708
|
-
models: source.models.map((model) => ({
|
|
52709
|
-
id: model.id,
|
|
52710
|
-
...model.api === void 0 ? {} : { api: model.api },
|
|
52711
|
-
...model.name === void 0 ? {} : { name: model.name },
|
|
52712
|
-
...model.reasoning === void 0 ? {} : { reasoning: model.reasoning },
|
|
52713
|
-
input: [...model.input],
|
|
52714
|
-
cost: {
|
|
52715
|
-
input: model.cost.input,
|
|
52716
|
-
output: model.cost.output,
|
|
52717
|
-
cacheRead: model.cost.cacheRead,
|
|
52718
|
-
cacheWrite: model.cost.cacheWrite,
|
|
52719
|
-
...model.cost.cacheWriteLong === void 0 ? {} : { cacheWriteLong: model.cost.cacheWriteLong }
|
|
52720
|
-
},
|
|
52721
|
-
contextWindow: model.contextWindow,
|
|
52722
|
-
maxTokens: model.maxTokens,
|
|
52723
|
-
...model.transport === void 0 ? {} : { transport: model.transport },
|
|
52724
|
-
...model.compat === void 0 ? {} : { compat: { ...model.compat } },
|
|
52725
|
-
...model.cacheCapability === void 0 ? {} : { cacheCapability: { ...model.cacheCapability } },
|
|
52726
|
-
...model.webSearch === void 0 ? {} : { webSearch: { ...model.webSearch } },
|
|
52727
|
-
...model.fileCapabilities === void 0 ? {} : { fileCapabilities: { ...model.fileCapabilities } },
|
|
52728
|
-
...model.headers === void 0 ? {} : { headers: { ...model.headers } },
|
|
52729
|
-
apiKeyEnv: remote.apiKeyEnv,
|
|
52730
|
-
...model.displayName === void 0 ? {} : { displayName: model.displayName },
|
|
52731
|
-
...model.filePlatform === void 0 ? {} : { filePlatform: model.filePlatform },
|
|
52732
|
-
...model.attachmentPlatform === void 0 ? {} : { attachmentPlatform: model.attachmentPlatform }
|
|
52733
|
-
}))
|
|
52734
|
-
};
|
|
52735
|
-
validateProfileConfig(provider, sanitized);
|
|
52736
|
-
Object.defineProperty(profiles, provider, { value: sanitized, enumerable: true, configurable: true, writable: true });
|
|
52737
|
-
}
|
|
52738
|
-
return { profiles };
|
|
52739
|
-
}
|
|
52740
|
-
async function readResponseTextBounded(response, maxBytes) {
|
|
52741
|
-
const reader = response.body?.getReader();
|
|
52742
|
-
if (!reader) return "";
|
|
52743
|
-
const chunks = [];
|
|
52744
|
-
let total = 0;
|
|
52745
|
-
try {
|
|
52746
|
-
while (true) {
|
|
52747
|
-
const { done, value } = await reader.read();
|
|
52748
|
-
if (done) break;
|
|
52749
|
-
if (!value) continue;
|
|
52750
|
-
total += value.byteLength;
|
|
52751
|
-
if (total > maxBytes) {
|
|
52752
|
-
await reader.cancel("catalog response is too large");
|
|
52753
|
-
throw new Error("catalog response is too large");
|
|
52754
|
-
}
|
|
52755
|
-
chunks.push(value);
|
|
52756
|
-
}
|
|
52757
|
-
return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
|
|
52758
|
-
} finally {
|
|
52759
|
-
reader.releaseLock();
|
|
52760
|
-
}
|
|
52761
|
-
}
|
|
52762
|
-
function deepMergePlainRecords(base, patch) {
|
|
52763
|
-
const result = isPlainRecord(base) ? { ...base } : {};
|
|
52764
|
-
if (!isPlainRecord(patch)) return result;
|
|
52765
|
-
for (const [key, value] of Object.entries(patch)) {
|
|
52766
|
-
const current = result[key];
|
|
52767
|
-
result[key] = isPlainRecord(current) && isPlainRecord(value) ? deepMergePlainRecords(current, value) : value;
|
|
52768
|
-
}
|
|
52769
|
-
return result;
|
|
52770
|
-
}
|
|
52771
|
-
function validateModelOverrides(value) {
|
|
52772
|
-
if (value === void 0) return;
|
|
52773
|
-
if (!isPlainRecord(value)) throw new Error("models.json modelOverrides must be an object");
|
|
52774
|
-
for (const [key, override] of Object.entries(value)) {
|
|
52775
|
-
if (!/^[^\s/]+\/[^\s/]+$/.test(key)) throw new Error(`models.json modelOverrides key must be "provider/modelId": ${key}`);
|
|
52776
|
-
if (!isPlainRecord(override)) throw new Error(`models.json modelOverrides["${key}"] must be an object`);
|
|
52777
|
-
assertOnlyKeys(override, [...MODEL_OVERRIDE_KEYS], `models.json modelOverrides["${key}"]`);
|
|
52778
|
-
if (override.name !== void 0 && (typeof override.name !== "string" || !override.name.trim())) throw new Error(`models.json modelOverrides["${key}"].name must be a non-empty string`);
|
|
52779
|
-
if (override.displayName !== void 0 && (typeof override.displayName !== "string" || !override.displayName.trim())) throw new Error(`models.json modelOverrides["${key}"].displayName must be a non-empty string`);
|
|
52780
|
-
if (override.reasoning !== void 0 && typeof override.reasoning !== "boolean") throw new Error(`models.json modelOverrides["${key}"].reasoning must be a boolean`);
|
|
52781
|
-
if (override.input !== void 0 && (!Array.isArray(override.input) || override.input.length === 0 || override.input.some((kind) => !["text", "image", "audio", "video"].includes(String(kind))))) throw new Error(`models.json modelOverrides["${key}"].input is invalid`);
|
|
52782
|
-
if (override.contextWindow !== void 0 && (!Number.isInteger(override.contextWindow) || Number(override.contextWindow) < 1)) throw new Error(`models.json modelOverrides["${key}"].contextWindow is invalid`);
|
|
52783
|
-
if (override.maxTokens !== void 0 && (!Number.isInteger(override.maxTokens) || Number(override.maxTokens) < 1)) throw new Error(`models.json modelOverrides["${key}"].maxTokens is invalid`);
|
|
52784
|
-
if (override.cost !== void 0) {
|
|
52785
|
-
if (!isPlainRecord(override.cost)) throw new Error(`models.json modelOverrides["${key}"].cost must be an object`);
|
|
52786
|
-
for (const field of ["input", "output", "cacheRead", "cacheWrite", "cacheWriteLong"]) {
|
|
52787
|
-
if (override.cost[field] !== void 0 && (typeof override.cost[field] !== "number" || !Number.isFinite(override.cost[field]) || override.cost[field] < 0)) throw new Error(`models.json modelOverrides["${key}"].cost.${field} must be a non-negative finite number`);
|
|
52788
|
-
}
|
|
52789
|
-
}
|
|
52790
|
-
if (override.headers !== void 0) {
|
|
52791
|
-
if (!isPlainRecord(override.headers)) throw new Error(`models.json modelOverrides["${key}"].headers must be an object`);
|
|
52792
|
-
for (const [headerName, headerValue] of Object.entries(override.headers)) {
|
|
52793
|
-
if (typeof headerValue !== "string") throw new Error(`models.json modelOverrides["${key}"].headers.${headerName} must be a string`);
|
|
52794
|
-
}
|
|
52795
|
-
}
|
|
52796
|
-
validateTransport(override.transport, `Model override "${key}"`);
|
|
52797
|
-
validateCompat(override.compat, `models.json modelOverrides["${key}"].compat`);
|
|
52798
|
-
validateCacheCapability(override.cacheCapability, `models.json modelOverrides["${key}"].cacheCapability`);
|
|
52799
|
-
validateWebSearchCapability(override.webSearch, `models.json modelOverrides["${key}"].webSearch`);
|
|
52800
|
-
validateFileCapabilities(override.fileCapabilities, `models.json modelOverrides["${key}"].fileCapabilities`);
|
|
52801
|
-
}
|
|
52802
|
-
}
|
|
52803
|
-
function validateProfileEndpoints(profile, label) {
|
|
52804
|
-
if (profile.endpoints === void 0) return;
|
|
52805
|
-
if (!isPlainRecord(profile.endpoints)) throw new Error(`${label} endpoints must be an object`);
|
|
52806
|
-
for (const [api, value] of Object.entries(profile.endpoints)) {
|
|
52807
|
-
if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`${label} endpoints has unsupported api ${api}`);
|
|
52808
|
-
try {
|
|
52809
|
-
if (typeof value !== "string") throw new Error("invalid URL");
|
|
52810
|
-
const endpoint = new URL(value);
|
|
52811
|
-
if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
|
|
52812
|
-
} catch {
|
|
52813
|
-
throw new Error(`${label} endpoints.${api} must be an absolute HTTP(S) URL`);
|
|
52814
|
-
}
|
|
52815
|
-
}
|
|
52816
|
-
}
|
|
52817
|
-
function resolveProfileRoute(profile, model) {
|
|
52818
|
-
const api = model.api ?? profile.api;
|
|
52819
|
-
if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`Model "${model.id}" has unsupported api ${api}`);
|
|
52820
|
-
const endpoint = profile.endpoints?.[api];
|
|
52821
|
-
if (model.api !== void 0 && endpoint === void 0 && api !== profile.api) {
|
|
52822
|
-
throw new Error(`Model "${model.id}" api ${api} requires profile endpoints.${api} (otherwise api must equal profile api)`);
|
|
52823
|
-
}
|
|
52824
|
-
return { api, baseUrl: endpoint ?? profile.baseUrl };
|
|
52825
|
-
}
|
|
52826
|
-
function validateProfileConfig(profileId, profileConfig) {
|
|
52827
|
-
if (!isPlainRecord(profileConfig)) throw new Error(`Profile "${profileId}" must be an object.`);
|
|
52828
|
-
assertOnlyKeys(profileConfig, [
|
|
52829
|
-
"baseUrl",
|
|
52830
|
-
"endpoints",
|
|
52831
|
-
"api",
|
|
52832
|
-
"apiKey",
|
|
52833
|
-
"apiKeyEnv",
|
|
52834
|
-
"headers",
|
|
52835
|
-
"displayName",
|
|
52836
|
-
"filePlatform",
|
|
52837
|
-
"attachmentPlatform",
|
|
52838
|
-
"transport",
|
|
52839
|
-
"compat",
|
|
52840
|
-
"cacheCapability",
|
|
52841
|
-
"webSearch",
|
|
52842
|
-
"fileCapabilities",
|
|
52843
|
-
"models"
|
|
52844
|
-
], `Profile "${profileId}"`);
|
|
52845
|
-
const missing = [];
|
|
52846
|
-
if (!profileConfig.api) missing.push("api");
|
|
52847
|
-
if (!profileConfig.baseUrl) missing.push("baseUrl");
|
|
52848
|
-
if (!Array.isArray(profileConfig.models) || profileConfig.models.length === 0) missing.push("models");
|
|
52849
|
-
const hasProfileKeySource = Boolean(profileConfig.apiKey || profileConfig.apiKeyEnv);
|
|
52850
|
-
const hasModelKeySource = Boolean(
|
|
52851
|
-
(profileConfig.models || []).some((model) => Boolean(model.apiKeyEnv))
|
|
52852
|
-
);
|
|
52853
|
-
if (!hasProfileKeySource && !hasModelKeySource) missing.push("apiKey or apiKeyEnv");
|
|
52854
|
-
if (missing.length > 0) {
|
|
52855
|
-
throw new Error(
|
|
52856
|
-
`Profile "${profileId}" is missing required field${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}.`
|
|
52857
|
-
);
|
|
52858
|
-
}
|
|
52859
|
-
for (const field of ["baseUrl", "api", "apiKey", "displayName", "filePlatform", "attachmentPlatform"]) {
|
|
52860
|
-
assertOptionalString(profileConfig[field], `Profile "${profileId}" ${field}`);
|
|
52861
|
-
}
|
|
52862
|
-
assertOptionalEnvName(profileConfig.apiKeyEnv, `Profile "${profileId}" apiKeyEnv`);
|
|
52863
|
-
if (!SUPPORTED_REMOTE_APIS.has(profileConfig.api)) throw new Error(`Profile "${profileId}" has unsupported api ${profileConfig.api}`);
|
|
52864
|
-
try {
|
|
52865
|
-
const endpoint = new URL(profileConfig.baseUrl);
|
|
52866
|
-
if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
|
|
52867
|
-
} catch {
|
|
52868
|
-
throw new Error(`Profile "${profileId}" baseUrl must be an absolute HTTP(S) URL`);
|
|
52869
|
-
}
|
|
52870
|
-
validateProfileEndpoints(profileConfig, `Profile "${profileId}"`);
|
|
52871
|
-
assertHeadersShape(profileConfig.headers, `Profile "${profileId}"`);
|
|
52872
|
-
validateTransport(profileConfig.transport, `Profile "${profileId}"`);
|
|
52873
|
-
validateCompat(profileConfig.compat, `Profile "${profileId}" compat`);
|
|
52874
|
-
validateCacheCapability(profileConfig.cacheCapability, `Profile "${profileId}" cacheCapability`);
|
|
52875
|
-
validateWebSearchCapability(profileConfig.webSearch, `Profile "${profileId}" webSearch`);
|
|
52876
|
-
validateFileCapabilities(profileConfig.fileCapabilities, `Profile "${profileId}" fileCapabilities`);
|
|
52877
|
-
const seenModelIds = /* @__PURE__ */ new Set();
|
|
52878
|
-
for (const [index, modelConfig] of (profileConfig.models || []).entries()) {
|
|
52879
|
-
if (!isPlainRecord(modelConfig)) throw new Error(`Profile "${profileId}" model #${index} must be an object.`);
|
|
52880
|
-
assertOnlyKeys(modelConfig, [
|
|
52881
|
-
"id",
|
|
52882
|
-
"api",
|
|
52883
|
-
"name",
|
|
52884
|
-
"reasoning",
|
|
52885
|
-
"input",
|
|
52886
|
-
"cost",
|
|
52887
|
-
"contextWindow",
|
|
52888
|
-
"maxTokens",
|
|
52889
|
-
"transport",
|
|
52890
|
-
"compat",
|
|
52891
|
-
"cacheCapability",
|
|
52892
|
-
"webSearch",
|
|
52893
|
-
"fileCapabilities",
|
|
52894
|
-
"headers",
|
|
52895
|
-
"apiKeyEnv",
|
|
52896
|
-
"displayName",
|
|
52897
|
-
"filePlatform",
|
|
52898
|
-
"attachmentPlatform"
|
|
52899
|
-
], `Profile "${profileId}" model #${index}`);
|
|
52900
|
-
const modelMissing = [];
|
|
52901
|
-
if (!modelConfig.id) modelMissing.push("id");
|
|
52902
|
-
if (!Array.isArray(modelConfig.input) || modelConfig.input.length === 0) modelMissing.push("input");
|
|
52903
|
-
if (!modelConfig.cost) modelMissing.push("cost");
|
|
52904
|
-
if (!modelConfig.contextWindow) modelMissing.push("contextWindow");
|
|
52905
|
-
if (!modelConfig.maxTokens) modelMissing.push("maxTokens");
|
|
52906
|
-
if (modelMissing.length > 0) {
|
|
52907
|
-
const label = modelConfig.id || `#${index}`;
|
|
52908
|
-
throw new Error(
|
|
52909
|
-
`Profile "${profileId}" model "${label}" is missing required field${modelMissing.length > 1 ? "s" : ""}: ${modelMissing.join(", ")}.`
|
|
52910
|
-
);
|
|
52911
|
-
}
|
|
52912
|
-
validateRemoteModel(profileId, modelConfig);
|
|
52913
|
-
resolveProfileRoute(profileConfig, modelConfig);
|
|
52914
|
-
assertHeadersShape(modelConfig.headers, `Profile "${profileId}" model "${modelConfig.id}"`);
|
|
52915
|
-
assertOptionalEnvName(modelConfig.apiKeyEnv, `Profile "${profileId}" model "${modelConfig.id}" apiKeyEnv`);
|
|
52916
|
-
if (seenModelIds.has(modelConfig.id)) throw new Error(`Profile "${profileId}" contains duplicate model "${modelConfig.id}".`);
|
|
52917
|
-
seenModelIds.add(modelConfig.id);
|
|
52918
|
-
}
|
|
52919
|
-
}
|
|
52920
|
-
var ModelRegistry = class {
|
|
52921
|
-
models = /* @__PURE__ */ new Map();
|
|
52922
|
-
loadError;
|
|
52923
|
-
authStorage;
|
|
52924
|
-
modelsPath;
|
|
52925
|
-
configDefaults;
|
|
52926
|
-
modelOrder = [];
|
|
52927
|
-
modelOverrides = {};
|
|
52928
|
-
extensionOAuthProviders = /* @__PURE__ */ new Map();
|
|
52929
|
-
usingExternalProviders = false;
|
|
52930
|
-
localProfileIds = /* @__PURE__ */ new Set();
|
|
52931
|
-
remoteCredentialEnvByProvider = /* @__PURE__ */ new Map();
|
|
52932
|
-
remoteCatalogByProvider = /* @__PURE__ */ new Map();
|
|
52933
|
-
remoteCredentialFingerprintByCatalog = /* @__PURE__ */ new Map();
|
|
52934
|
-
constructor(authStorage, modelsPath = path3.join(getConfigDir(), "models.json")) {
|
|
52935
|
-
this.authStorage = authStorage;
|
|
52936
|
-
this.modelsPath = modelsPath;
|
|
52937
|
-
this.load();
|
|
52938
|
-
}
|
|
52939
|
-
upsert(model) {
|
|
52940
|
-
let providerModels = this.models.get(model.provider);
|
|
52941
|
-
if (!providerModels) {
|
|
52942
|
-
providerModels = /* @__PURE__ */ new Map();
|
|
52943
|
-
this.models.set(model.provider, providerModels);
|
|
52944
|
-
}
|
|
52945
|
-
const key = `${model.provider}/${model.id}`;
|
|
52946
|
-
if (!providerModels.has(model.id) && !this.modelOrder.includes(key)) {
|
|
52947
|
-
this.modelOrder.push(key);
|
|
52948
|
-
}
|
|
52949
|
-
providerModels.set(model.id, model);
|
|
52950
|
-
}
|
|
52951
|
-
load() {
|
|
52952
|
-
this.loadError = void 0;
|
|
52953
|
-
this.models.clear();
|
|
52954
|
-
this.modelOrder = [];
|
|
52955
|
-
this.modelOverrides = {};
|
|
52956
|
-
this.configDefaults = void 0;
|
|
52957
|
-
this.usingExternalProviders = false;
|
|
52958
|
-
this.localProfileIds.clear();
|
|
52959
|
-
this.remoteCredentialEnvByProvider.clear();
|
|
52960
|
-
this.remoteCatalogByProvider.clear();
|
|
52961
|
-
this.remoteCredentialFingerprintByCatalog.clear();
|
|
52962
|
-
try {
|
|
52963
|
-
pruneLegacyRemoteCatalogCaches(this.modelsPath);
|
|
52964
|
-
} catch (error) {
|
|
52965
|
-
this.loadError = error instanceof Error ? error.message : String(error);
|
|
52966
|
-
return;
|
|
52967
|
-
}
|
|
52968
|
-
if (!fs3.existsSync(this.modelsPath)) {
|
|
52969
|
-
return;
|
|
52970
|
-
}
|
|
52971
|
-
try {
|
|
52972
|
-
const raw = JSON.parse(fs3.readFileSync(this.modelsPath, "utf-8"));
|
|
52973
|
-
if (raw && typeof raw === "object" && "providers" in raw) {
|
|
52974
|
-
throw new Error('Legacy models.json format is no longer supported. Use top-level "profiles".');
|
|
52975
|
-
}
|
|
52976
|
-
validateModelsDocumentShape(raw);
|
|
52977
|
-
const remotes = validatedRemoteCatalogs(raw.remoteCatalogs);
|
|
52978
|
-
this.modelOverrides = raw.modelOverrides ?? {};
|
|
52979
|
-
const activeRemoteSecrets = configuredRemoteCredentialValues(raw);
|
|
52980
|
-
scrubActiveSecretsFromRemoteCaches(this.modelsPath, activeRemoteSecrets);
|
|
52981
|
-
const configuredProviders = Object.entries(raw.profiles || {});
|
|
52982
|
-
this.localProfileIds = new Set(configuredProviders.map(([provider]) => provider));
|
|
52983
|
-
const hasConfiguredProviders = configuredProviders.length > 0;
|
|
52984
|
-
this.configDefaults = raw.defaults ? {
|
|
52985
|
-
provider: raw.defaults.provider,
|
|
52986
|
-
modelId: raw.defaults.modelId,
|
|
52987
|
-
modelClasses: raw.defaults.modelClasses,
|
|
52988
|
-
toolModels: raw.defaults.toolModels
|
|
52989
|
-
} : void 0;
|
|
52990
|
-
this.usingExternalProviders = hasConfiguredProviders;
|
|
52991
|
-
for (const [configuredProvider, providerConfig] of configuredProviders) {
|
|
52992
|
-
const provider = configuredProvider;
|
|
52993
|
-
validateProfileConfig(provider, providerConfig);
|
|
52994
|
-
if (providerConfig.apiKey) {
|
|
52995
|
-
this.authStorage.setProviderApiKey(provider, providerConfig.apiKey);
|
|
52996
|
-
}
|
|
52997
|
-
if (providerConfig.apiKeyEnv) {
|
|
52998
|
-
this.authStorage.setProviderEnvVar(
|
|
52999
|
-
provider,
|
|
53000
|
-
providerConfig.apiKeyEnv
|
|
53001
|
-
);
|
|
53002
|
-
}
|
|
53003
|
-
const existing = this.models.get(provider);
|
|
53004
|
-
if (existing && (providerConfig.baseUrl || providerConfig.api || providerConfig.headers || providerConfig.transport)) {
|
|
53005
|
-
for (const model of existing.values()) {
|
|
53006
|
-
this.upsert({
|
|
53007
|
-
...model,
|
|
53008
|
-
baseUrl: providerConfig.baseUrl || model.baseUrl,
|
|
53009
|
-
api: providerConfig.api || model.api,
|
|
53010
|
-
transport: providerConfig.transport ?? model.transport,
|
|
53011
|
-
apiKeyEnv: providerConfig.apiKeyEnv || model.apiKeyEnv,
|
|
53012
|
-
displayName: providerConfig.displayName || model.displayName || provider,
|
|
53013
|
-
filePlatform: providerConfig.filePlatform || model.filePlatform,
|
|
53014
|
-
attachmentPlatform: providerConfig.attachmentPlatform || model.attachmentPlatform,
|
|
53015
|
-
cacheCapability: providerConfig.cacheCapability || model.cacheCapability,
|
|
53016
|
-
webSearch: providerConfig.webSearch || model.webSearch,
|
|
53017
|
-
fileCapabilities: providerConfig.fileCapabilities || model.fileCapabilities,
|
|
53018
|
-
headers: providerConfig.headers ? { ...model.headers, ...providerConfig.headers } : model.headers
|
|
53019
|
-
});
|
|
53020
|
-
}
|
|
53021
|
-
}
|
|
53022
|
-
for (const customModel of providerConfig.models || []) {
|
|
53023
|
-
const baseModel = existing?.get(customModel.id);
|
|
53024
|
-
this.upsert({
|
|
53025
|
-
id: customModel.id,
|
|
53026
|
-
name: customModel.name || baseModel?.name || customModel.id,
|
|
53027
|
-
...resolveProfileRoute(providerConfig, customModel),
|
|
53028
|
-
provider,
|
|
53029
|
-
reasoning: customModel.reasoning ?? baseModel?.reasoning ?? false,
|
|
53030
|
-
input: customModel.input || baseModel?.input || ["text"],
|
|
53031
|
-
cost: customModel.cost || baseModel?.cost || { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
53032
|
-
contextWindow: customModel.contextWindow || baseModel?.contextWindow || 128e3,
|
|
53033
|
-
maxTokens: customModel.maxTokens || baseModel?.maxTokens || 8192,
|
|
53034
|
-
apiKeyEnv: customModel.apiKeyEnv || providerConfig.apiKeyEnv || baseModel?.apiKeyEnv,
|
|
53035
|
-
displayName: customModel.displayName || providerConfig.displayName || baseModel?.displayName || provider,
|
|
53036
|
-
filePlatform: customModel.filePlatform || providerConfig.filePlatform || baseModel?.filePlatform,
|
|
53037
|
-
attachmentPlatform: customModel.attachmentPlatform || providerConfig.attachmentPlatform || baseModel?.attachmentPlatform,
|
|
53038
|
-
headers: providerConfig.headers ? { ...baseModel?.headers, ...providerConfig.headers, ...customModel.headers } : customModel.headers || baseModel?.headers,
|
|
53039
|
-
transport: customModel.transport ?? providerConfig.transport ?? baseModel?.transport,
|
|
53040
|
-
compat: customModel.compat || providerConfig.compat || baseModel?.compat,
|
|
53041
|
-
cacheCapability: customModel.cacheCapability || providerConfig.cacheCapability || baseModel?.cacheCapability,
|
|
53042
|
-
webSearch: customModel.webSearch || providerConfig.webSearch || baseModel?.webSearch,
|
|
53043
|
-
fileCapabilities: customModel.fileCapabilities || providerConfig.fileCapabilities || baseModel?.fileCapabilities
|
|
53044
|
-
});
|
|
53045
|
-
}
|
|
53046
|
-
}
|
|
53047
|
-
for (const identity of remotes) {
|
|
53048
|
-
const credential = process.env[identity.apiKeyEnv];
|
|
53049
|
-
if (!credential) continue;
|
|
53050
|
-
const fingerprint = credentialFingerprint(this.modelsPath, identity, credential);
|
|
53051
|
-
if (!fingerprint) continue;
|
|
53052
|
-
const cached = readRemoteCache(this.modelsPath, identity, fingerprint, activeRemoteSecrets);
|
|
53053
|
-
if (!cached) continue;
|
|
53054
|
-
const owner = remoteIdentityDigest(identity);
|
|
53055
|
-
this.remoteCredentialFingerprintByCatalog.set(owner, fingerprint);
|
|
53056
|
-
const candidates = Object.entries(cached.payload.profiles || {}).filter(([provider]) => !this.localProfileIds.has(provider));
|
|
53057
|
-
if (candidates.some(([provider]) => {
|
|
53058
|
-
const existing = this.remoteCatalogByProvider.get(provider);
|
|
53059
|
-
return existing !== void 0 && existing !== owner;
|
|
53060
|
-
})) continue;
|
|
53061
|
-
for (const [provider, profile] of candidates) {
|
|
53062
|
-
this.registerRemoteProfile(provider, profile, identity.apiKeyEnv, owner);
|
|
53063
|
-
}
|
|
53064
|
-
}
|
|
53065
|
-
this.applyModelOverrides();
|
|
53066
|
-
} catch (error) {
|
|
53067
|
-
this.loadError = error instanceof Error ? error.message : String(error);
|
|
53068
|
-
}
|
|
53069
|
-
}
|
|
53070
|
-
/**
|
|
53071
|
-
* Re-apply models.json modelOverrides after any (re)materialization pass
|
|
53072
|
-
* (initial load, remote catalog refresh). Overrides patch descriptive
|
|
53073
|
-
* fields only; nested plain objects deep-merge, arrays/scalars replace.
|
|
53074
|
-
*/
|
|
53075
|
-
applyModelOverrides() {
|
|
53076
|
-
for (const [key, override] of Object.entries(this.modelOverrides)) {
|
|
53077
|
-
const slash = key.indexOf("/");
|
|
53078
|
-
if (slash <= 0) continue;
|
|
53079
|
-
const provider = key.slice(0, slash);
|
|
53080
|
-
const modelId = key.slice(slash + 1);
|
|
53081
|
-
const existing = this.models.get(provider)?.get(modelId);
|
|
53082
|
-
if (!existing) continue;
|
|
53083
|
-
const patched = { ...existing };
|
|
53084
|
-
if (override.name !== void 0) patched.name = override.name;
|
|
53085
|
-
if (override.displayName !== void 0) patched.displayName = override.displayName;
|
|
53086
|
-
if (override.reasoning !== void 0) patched.reasoning = override.reasoning;
|
|
53087
|
-
if (override.input !== void 0) patched.input = [...override.input];
|
|
53088
|
-
if (override.contextWindow !== void 0) patched.contextWindow = override.contextWindow;
|
|
53089
|
-
if (override.maxTokens !== void 0) patched.maxTokens = override.maxTokens;
|
|
53090
|
-
if (override.cost !== void 0) patched.cost = { ...existing.cost, ...override.cost };
|
|
53091
|
-
if (override.headers !== void 0) patched.headers = { ...existing.headers, ...override.headers };
|
|
53092
|
-
if (override.transport !== void 0) patched.transport = override.transport;
|
|
53093
|
-
if (override.compat !== void 0) patched.compat = deepMergePlainRecords(existing.compat, override.compat);
|
|
53094
|
-
if (override.cacheCapability !== void 0) patched.cacheCapability = { ...existing.cacheCapability, ...override.cacheCapability };
|
|
53095
|
-
if (override.webSearch !== void 0) patched.webSearch = { ...existing.webSearch, ...override.webSearch };
|
|
53096
|
-
if (override.fileCapabilities !== void 0) patched.fileCapabilities = deepMergePlainRecords(existing.fileCapabilities, override.fileCapabilities);
|
|
53097
|
-
this.upsert(patched);
|
|
53098
|
-
}
|
|
53099
|
-
}
|
|
53100
|
-
registerRemoteProfile(provider, providerConfig, credentialEnv, catalogId) {
|
|
53101
|
-
if (this.localProfileIds.has(provider)) return;
|
|
53102
|
-
const existingCatalog = this.remoteCatalogByProvider.get(provider);
|
|
53103
|
-
if (existingCatalog && existingCatalog !== catalogId) {
|
|
53104
|
-
throw new Error(`remote profile "${provider}" is already owned by catalog "${existingCatalog}"`);
|
|
53105
|
-
}
|
|
53106
|
-
validateProfileConfig(provider, providerConfig);
|
|
53107
|
-
this.remoteCatalogByProvider.set(provider, catalogId);
|
|
53108
|
-
this.remoteCredentialEnvByProvider.set(provider, credentialEnv);
|
|
53109
|
-
this.authStorage.setProviderEnvVar(provider, credentialEnv);
|
|
53110
|
-
for (const customModel of providerConfig.models || []) {
|
|
53111
|
-
this.upsert({
|
|
53112
|
-
id: customModel.id,
|
|
53113
|
-
name: customModel.name || customModel.id,
|
|
53114
|
-
...resolveProfileRoute(providerConfig, customModel),
|
|
53115
|
-
provider,
|
|
53116
|
-
reasoning: customModel.reasoning ?? false,
|
|
53117
|
-
input: customModel.input || ["text"],
|
|
53118
|
-
cost: customModel.cost || { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
53119
|
-
contextWindow: customModel.contextWindow || 128e3,
|
|
53120
|
-
maxTokens: customModel.maxTokens || 8192,
|
|
53121
|
-
apiKeyEnv: credentialEnv,
|
|
53122
|
-
displayName: customModel.displayName || providerConfig.displayName || provider,
|
|
53123
|
-
filePlatform: customModel.filePlatform || providerConfig.filePlatform,
|
|
53124
|
-
attachmentPlatform: customModel.attachmentPlatform || providerConfig.attachmentPlatform,
|
|
53125
|
-
headers: { ...providerConfig.headers, ...customModel.headers },
|
|
53126
|
-
transport: customModel.transport ?? providerConfig.transport,
|
|
53127
|
-
compat: customModel.compat || providerConfig.compat,
|
|
53128
|
-
cacheCapability: customModel.cacheCapability || providerConfig.cacheCapability,
|
|
53129
|
-
webSearch: customModel.webSearch || providerConfig.webSearch,
|
|
53130
|
-
fileCapabilities: customModel.fileCapabilities || providerConfig.fileCapabilities
|
|
53131
|
-
});
|
|
53132
|
-
}
|
|
53133
|
-
this.usingExternalProviders = true;
|
|
53134
|
-
}
|
|
53135
|
-
removeRemoteProvider(provider, catalogId) {
|
|
53136
|
-
if (this.remoteCatalogByProvider.get(provider) !== catalogId) return;
|
|
53137
|
-
this.models.delete(provider);
|
|
53138
|
-
this.modelOrder = this.modelOrder.filter((key) => !key.startsWith(`${provider}/`));
|
|
53139
|
-
this.remoteCatalogByProvider.delete(provider);
|
|
53140
|
-
this.remoteCredentialEnvByProvider.delete(provider);
|
|
53141
|
-
}
|
|
53142
|
-
removeRemoteCatalogProfiles(catalogId) {
|
|
53143
|
-
for (const [provider, owner] of [...this.remoteCatalogByProvider]) {
|
|
53144
|
-
if (owner === catalogId) this.removeRemoteProvider(provider, catalogId);
|
|
53145
|
-
}
|
|
53146
|
-
this.usingExternalProviders = this.localProfileIds.size > 0 || this.remoteCatalogByProvider.size > 0;
|
|
53147
|
-
}
|
|
53148
|
-
replaceRemoteCatalogProfiles(catalogId, payload, credentialEnv) {
|
|
53149
|
-
const candidates = Object.entries(payload.profiles || {}).filter(([provider]) => !this.localProfileIds.has(provider));
|
|
53150
|
-
for (const [provider, profile] of candidates) {
|
|
53151
|
-
const owner = this.remoteCatalogByProvider.get(provider);
|
|
53152
|
-
if (owner && owner !== catalogId) throw new Error(`remote profile "${provider}" is already owned by another catalog identity`);
|
|
53153
|
-
validateProfileConfig(provider, profile);
|
|
53154
|
-
}
|
|
53155
|
-
this.removeRemoteCatalogProfiles(catalogId);
|
|
53156
|
-
for (const [provider, profile] of candidates) {
|
|
53157
|
-
this.registerRemoteProfile(provider, profile, credentialEnv, catalogId);
|
|
53158
|
-
}
|
|
53159
|
-
this.applyModelOverrides();
|
|
53160
|
-
}
|
|
53161
|
-
writeRemoteCache(remote, fingerprint, value) {
|
|
53162
|
-
const directory = safeRemoteCacheDirectory(this.modelsPath, true);
|
|
53163
|
-
const target = remoteCachePath(this.modelsPath, remote, fingerprint);
|
|
53164
|
-
if (fs3.existsSync(target)) {
|
|
53165
|
-
const stat2 = fs3.lstatSync(target);
|
|
53166
|
-
if (stat2.isSymbolicLink() || !stat2.isFile()) throw new Error(`remote catalog cache entry must be a regular file: ${target}`);
|
|
53167
|
-
}
|
|
53168
|
-
const temporary = path3.join(directory, `.${path3.basename(target)}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`);
|
|
53169
|
-
try {
|
|
53170
|
-
fs3.writeFileSync(temporary, `${JSON.stringify(value)}
|
|
53171
|
-
`, { flag: "wx", mode: 384 });
|
|
53172
|
-
fs3.renameSync(temporary, target);
|
|
53173
|
-
const tombstone = remoteCacheTombstonePath(this.modelsPath, remote, fingerprint);
|
|
53174
|
-
if (fs3.existsSync(tombstone)) fs3.unlinkSync(tombstone);
|
|
53175
|
-
} finally {
|
|
53176
|
-
if (fs3.existsSync(temporary)) fs3.unlinkSync(temporary);
|
|
53177
|
-
}
|
|
53178
|
-
}
|
|
53179
|
-
refreshRemoteCatalogs() {
|
|
53180
|
-
const queueKey = path3.resolve(this.modelsPath);
|
|
53181
|
-
const previous = remoteRefreshTails.get(queueKey) ?? Promise.resolve();
|
|
53182
|
-
const refresh = previous.then(() => this.performRemoteCatalogRefresh());
|
|
53183
|
-
const tail = refresh.catch(() => void 0);
|
|
53184
|
-
remoteRefreshTails.set(queueKey, tail);
|
|
53185
|
-
void tail.finally(() => {
|
|
53186
|
-
if (remoteRefreshTails.get(queueKey) === tail) remoteRefreshTails.delete(queueKey);
|
|
53187
|
-
});
|
|
53188
|
-
return refresh;
|
|
53189
|
-
}
|
|
53190
|
-
async performRemoteCatalogRefresh() {
|
|
53191
|
-
const releaseLock = await acquireRemoteRefreshLock(this.modelsPath);
|
|
53192
|
-
try {
|
|
53193
|
-
await this.performRemoteCatalogRefreshLocked();
|
|
53194
|
-
} finally {
|
|
53195
|
-
releaseLock();
|
|
53196
|
-
}
|
|
53197
|
-
}
|
|
53198
|
-
async performRemoteCatalogRefreshLocked() {
|
|
53199
|
-
try {
|
|
53200
|
-
pruneLegacyRemoteCatalogCaches(this.modelsPath);
|
|
53201
|
-
} catch (error) {
|
|
53202
|
-
this.loadError = error instanceof Error ? error.message : String(error);
|
|
53203
|
-
return;
|
|
53204
|
-
}
|
|
53205
|
-
if (!fs3.existsSync(this.modelsPath)) {
|
|
53206
|
-
for (const owner of new Set(this.remoteCatalogByProvider.values())) this.removeRemoteCatalogProfiles(owner);
|
|
53207
|
-
this.remoteCredentialFingerprintByCatalog.clear();
|
|
53208
|
-
return;
|
|
53209
|
-
}
|
|
53210
|
-
let config;
|
|
53211
|
-
try {
|
|
53212
|
-
const decoded = JSON.parse(fs3.readFileSync(this.modelsPath, "utf8"));
|
|
53213
|
-
validateModelsDocumentShape(decoded);
|
|
53214
|
-
config = decoded;
|
|
53215
|
-
} catch {
|
|
53216
|
-
for (const owner of new Set(this.remoteCatalogByProvider.values())) this.removeRemoteCatalogProfiles(owner);
|
|
53217
|
-
this.remoteCredentialFingerprintByCatalog.clear();
|
|
53218
|
-
return;
|
|
53219
|
-
}
|
|
53220
|
-
this.modelOverrides = config.modelOverrides ?? {};
|
|
53221
|
-
let remotes;
|
|
53222
|
-
try {
|
|
53223
|
-
remotes = validatedRemoteCatalogs(config.remoteCatalogs);
|
|
53224
|
-
} catch (error) {
|
|
53225
|
-
for (const owner of new Set(this.remoteCatalogByProvider.values())) this.removeRemoteCatalogProfiles(owner);
|
|
53226
|
-
this.remoteCredentialFingerprintByCatalog.clear();
|
|
53227
|
-
this.loadError = error instanceof Error ? error.message : String(error);
|
|
53228
|
-
return;
|
|
53229
|
-
}
|
|
53230
|
-
const activeOwners = new Set(remotes.map(remoteIdentityDigest));
|
|
53231
|
-
const activeRemoteSecrets = configuredRemoteCredentialValues(config);
|
|
53232
|
-
scrubActiveSecretsFromRemoteCaches(this.modelsPath, activeRemoteSecrets);
|
|
53233
|
-
for (const owner of new Set(this.remoteCatalogByProvider.values())) {
|
|
53234
|
-
if (!activeOwners.has(owner)) this.removeRemoteCatalogProfiles(owner);
|
|
53235
|
-
}
|
|
53236
|
-
for (const owner of [...this.remoteCredentialFingerprintByCatalog.keys()]) {
|
|
53237
|
-
if (!activeOwners.has(owner)) this.remoteCredentialFingerprintByCatalog.delete(owner);
|
|
53238
|
-
}
|
|
53239
|
-
for (const identity of remotes) {
|
|
53240
|
-
const remote = identity;
|
|
53241
|
-
const url = new URL(identity.url);
|
|
53242
|
-
const catalogOwner = remoteIdentityDigest(identity);
|
|
53243
|
-
const apiKey = process.env[remote.apiKeyEnv];
|
|
53244
|
-
if (!apiKey) {
|
|
53245
|
-
this.removeRemoteCatalogProfiles(catalogOwner);
|
|
53246
|
-
this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
|
|
53247
|
-
warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" unavailable: environment variable ${remote.apiKeyEnv} is not set`, activeRemoteSecrets);
|
|
53248
|
-
continue;
|
|
53249
|
-
}
|
|
53250
|
-
const fingerprint = credentialFingerprint(this.modelsPath, identity, apiKey, true);
|
|
53251
|
-
const previousFingerprint = this.remoteCredentialFingerprintByCatalog.get(catalogOwner);
|
|
53252
|
-
if (previousFingerprint && previousFingerprint !== fingerprint) {
|
|
53253
|
-
this.removeRemoteCatalogProfiles(catalogOwner);
|
|
53254
|
-
this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
|
|
53255
|
-
}
|
|
53256
|
-
const cached = readRemoteCache(this.modelsPath, identity, fingerprint, activeRemoteSecrets);
|
|
53257
|
-
let payload = cached?.payload;
|
|
53258
|
-
let response;
|
|
53259
|
-
try {
|
|
53260
|
-
const headers2 = { Authorization: `Bearer ${apiKey}` };
|
|
53261
|
-
if (cached?.etag) headers2["If-None-Match"] = cached.etag;
|
|
53262
|
-
response = await fetch(url, {
|
|
53263
|
-
headers: headers2,
|
|
53264
|
-
redirect: "manual",
|
|
53265
|
-
signal: AbortSignal.timeout(3e3)
|
|
53266
|
-
});
|
|
53267
|
-
} catch (error) {
|
|
53268
|
-
if (!payload) {
|
|
53269
|
-
warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" unavailable: ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
|
|
53270
|
-
continue;
|
|
53271
|
-
}
|
|
53272
|
-
warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" using cached data after a transient fetch failure: ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
|
|
53273
|
-
}
|
|
53274
|
-
if (response) {
|
|
53275
|
-
if (response.status === 304 && payload && cached?.etag && (!response.headers.get("etag") || response.headers.get("etag") === cached.etag)) {
|
|
53276
|
-
} else if (response.ok) {
|
|
53277
|
-
try {
|
|
53278
|
-
const contentLength = Number(response.headers.get("content-length") || 0);
|
|
53279
|
-
if (contentLength > MAX_REMOTE_CATALOG_BYTES) throw new Error("catalog response is too large");
|
|
53280
|
-
const text = await readResponseTextBounded(response, MAX_REMOTE_CATALOG_BYTES);
|
|
53281
|
-
const decoded = JSON.parse(text);
|
|
53282
|
-
const etag = response.headers.get("etag") || void 0;
|
|
53283
|
-
assertNoSecretSubstrings({ etag, payload: decoded }, activeRemoteSecrets, "remote catalog response");
|
|
53284
|
-
payload = sanitizeRemotePayload(decoded, identity, url);
|
|
53285
|
-
const envelope = {
|
|
53286
|
-
version: REMOTE_CATALOG_CACHE_VERSION,
|
|
53287
|
-
identity,
|
|
53288
|
-
credentialFingerprint: fingerprint,
|
|
53289
|
-
etag,
|
|
53290
|
-
payload,
|
|
53291
|
-
payloadSha256: payloadDigest(payload)
|
|
53292
|
-
};
|
|
53293
|
-
this.writeRemoteCache(identity, fingerprint, envelope);
|
|
53294
|
-
} catch (error) {
|
|
53295
|
-
this.removeRemoteCatalogProfiles(catalogOwner);
|
|
53296
|
-
this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
|
|
53297
|
-
removeRemoteCache(this.modelsPath, identity, fingerprint);
|
|
53298
|
-
warnRemoteCatalog(`[Config] Rejecting invalid remote catalog "${remote.id}": ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
|
|
53299
|
-
continue;
|
|
53300
|
-
}
|
|
53301
|
-
} else if (response.status === 408 || response.status === 429 || response.status >= 500) {
|
|
53302
|
-
if (!payload) {
|
|
53303
|
-
warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" unavailable: HTTP ${response.status}`, activeRemoteSecrets);
|
|
53304
|
-
continue;
|
|
53305
|
-
}
|
|
53306
|
-
warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" using cached data after transient HTTP ${response.status}`, activeRemoteSecrets);
|
|
53307
|
-
} else {
|
|
53308
|
-
this.removeRemoteCatalogProfiles(catalogOwner);
|
|
53309
|
-
this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
|
|
53310
|
-
removeRemoteCache(this.modelsPath, identity, fingerprint);
|
|
53311
|
-
warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" rejected: HTTP ${response.status}`, activeRemoteSecrets);
|
|
53312
|
-
continue;
|
|
53313
|
-
}
|
|
53314
|
-
}
|
|
53315
|
-
if (!payload) continue;
|
|
53316
|
-
try {
|
|
53317
|
-
this.replaceRemoteCatalogProfiles(catalogOwner, payload, identity.apiKeyEnv);
|
|
53318
|
-
this.remoteCredentialFingerprintByCatalog.set(catalogOwner, fingerprint);
|
|
53319
|
-
} catch (error) {
|
|
53320
|
-
this.removeRemoteCatalogProfiles(catalogOwner);
|
|
53321
|
-
this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
|
|
53322
|
-
removeRemoteCache(this.modelsPath, identity, fingerprint);
|
|
53323
|
-
warnRemoteCatalog(`[Config] Ignoring conflicting remote catalog "${remote.id}": ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
|
|
53324
|
-
}
|
|
53325
|
-
}
|
|
53326
|
-
}
|
|
53327
|
-
getConfigDefaults() {
|
|
53328
|
-
return this.configDefaults;
|
|
53329
|
-
}
|
|
53330
|
-
resolveConfiguredRoute(purpose, route) {
|
|
53331
|
-
if (!route?.provider || !route?.modelId) return void 0;
|
|
53332
|
-
const requiredCapability = requiredCapabilityForToolPurpose(purpose);
|
|
53333
|
-
const model = this.find(route.provider, route.modelId);
|
|
53334
|
-
if (!model) {
|
|
53335
|
-
return {
|
|
53336
|
-
purpose,
|
|
53337
|
-
requiredCapability,
|
|
53338
|
-
routeSource: "unavailable",
|
|
53339
|
-
fallbackReason: `models.json defaults.toolModels.${purpose} points to missing model ${route.provider}/${route.modelId}`
|
|
53340
|
-
};
|
|
53341
|
-
}
|
|
53342
|
-
if (!modelSupportsToolPurpose(model, purpose)) {
|
|
53343
|
-
return {
|
|
53344
|
-
purpose,
|
|
53345
|
-
requiredCapability,
|
|
53346
|
-
routeSource: "unavailable",
|
|
53347
|
-
model,
|
|
53348
|
-
fallbackReason: `models.json defaults.toolModels.${purpose} points to ${model.provider}/${model.id}, but it does not declare ${requiredCapability} capability`
|
|
53349
|
-
};
|
|
53350
|
-
}
|
|
53351
|
-
const apiKey = this.getApiKey(model);
|
|
53352
|
-
if (!apiKey) {
|
|
53353
|
-
return {
|
|
53354
|
-
purpose,
|
|
53355
|
-
requiredCapability,
|
|
53356
|
-
routeSource: "unavailable",
|
|
53357
|
-
model,
|
|
53358
|
-
fallbackReason: `no API key available for models.json defaults.toolModels.${purpose} (${model.provider}/${model.id})`
|
|
53359
|
-
};
|
|
53360
|
-
}
|
|
53361
|
-
return { purpose, requiredCapability, routeSource: "explicit", model, apiKey };
|
|
53362
|
-
}
|
|
53363
|
-
resolveToolModel(purpose, currentModel) {
|
|
53364
|
-
return this.resolveToolModelCandidates(purpose, currentModel)[0] ?? {
|
|
53365
|
-
purpose,
|
|
53366
|
-
requiredCapability: requiredCapabilityForToolPurpose(purpose),
|
|
53367
|
-
routeSource: "unavailable",
|
|
53368
|
-
fallbackReason: `No configured model declares ${requiredCapabilityForToolPurpose(purpose)} capability for ${purpose}.`
|
|
53369
|
-
};
|
|
53370
|
-
}
|
|
53371
|
-
resolveToolModelCandidates(purpose, currentModel) {
|
|
53372
|
-
const requiredCapability = requiredCapabilityForToolPurpose(purpose);
|
|
53373
|
-
const candidates = [];
|
|
53374
|
-
const seen = /* @__PURE__ */ new Set();
|
|
53375
|
-
const add = (decision) => {
|
|
53376
|
-
if (!decision) return;
|
|
53377
|
-
if (!decision.model) {
|
|
53378
|
-
if (decision.routeSource === "unavailable") candidates.push(decision);
|
|
53379
|
-
return;
|
|
53380
|
-
}
|
|
53381
|
-
const key = `${decision.model.provider}/${decision.model.id}`;
|
|
53382
|
-
if (seen.has(key)) return;
|
|
53383
|
-
seen.add(key);
|
|
53384
|
-
candidates.push(decision);
|
|
53385
|
-
};
|
|
53386
|
-
const explicit = this.resolveConfiguredRoute(purpose, this.configDefaults?.toolModels?.[purpose]);
|
|
53387
|
-
add(explicit);
|
|
53388
|
-
if (currentModel && modelSupportsToolPurpose(currentModel, purpose)) {
|
|
53389
|
-
const apiKey = this.getApiKey(currentModel);
|
|
53390
|
-
if (apiKey) {
|
|
53391
|
-
add({ purpose, requiredCapability, routeSource: "current_model", model: currentModel, apiKey });
|
|
53392
|
-
}
|
|
53393
|
-
}
|
|
53394
|
-
const modelClassCandidates = [];
|
|
53395
|
-
for (const modelClass of MODEL_CLASS_FALLBACK_ORDER) {
|
|
53396
|
-
const resolved = this.resolveModelClass(modelClass);
|
|
53397
|
-
if (resolved.model && resolved.apiKey && modelSupportsToolPurpose(resolved.model, purpose)) {
|
|
53398
|
-
modelClassCandidates.push({
|
|
53399
|
-
purpose,
|
|
53400
|
-
requiredCapability,
|
|
53401
|
-
routeSource: "model_class",
|
|
53402
|
-
model: resolved.model,
|
|
53403
|
-
apiKey: resolved.apiKey
|
|
53404
|
-
});
|
|
53405
|
-
}
|
|
53406
|
-
}
|
|
53407
|
-
for (const decision of sortToolModelCandidatesByCapability(purpose, modelClassCandidates)) add(decision);
|
|
53408
|
-
const configuredCandidates = [];
|
|
53409
|
-
for (const model of this.getAllInConfigOrder()) {
|
|
53410
|
-
if (!modelSupportsToolPurpose(model, purpose)) continue;
|
|
53411
|
-
const apiKey = this.getApiKey(model);
|
|
53412
|
-
if (!apiKey) continue;
|
|
53413
|
-
configuredCandidates.push({ purpose, requiredCapability, routeSource: "configured_model", model, apiKey });
|
|
53414
|
-
}
|
|
53415
|
-
for (const decision of sortToolModelCandidatesByCapability(purpose, configuredCandidates)) add(decision);
|
|
53416
|
-
if (candidates.some((candidate) => candidate.model)) {
|
|
53417
|
-
return candidates.filter((candidate) => candidate.model);
|
|
53418
|
-
}
|
|
53419
|
-
return candidates.length > 0 ? candidates : [{
|
|
53420
|
-
purpose,
|
|
53421
|
-
requiredCapability,
|
|
53422
|
-
routeSource: "unavailable",
|
|
53423
|
-
fallbackReason: `No configured model declares ${requiredCapability} capability for ${purpose}.`
|
|
53424
|
-
}];
|
|
53425
|
-
}
|
|
53426
|
-
validateExplicitToolModelRoutes() {
|
|
53427
|
-
const routes = this.configDefaults?.toolModels || {};
|
|
53428
|
-
const results = [];
|
|
53429
|
-
for (const purpose of Object.keys(routes)) {
|
|
53430
|
-
const decision = this.resolveConfiguredRoute(purpose, routes[purpose]);
|
|
53431
|
-
if (decision) results.push(decision);
|
|
53432
|
-
}
|
|
53433
|
-
return results;
|
|
53434
|
-
}
|
|
53435
|
-
resolveModelClass(modelClass) {
|
|
53436
|
-
const configured = this.configDefaults?.modelClasses?.[modelClass];
|
|
53437
|
-
if (!configured?.provider || !configured?.modelId) {
|
|
53438
|
-
return { fallbackReason: `models.json defaults.modelClasses.${modelClass} is not configured` };
|
|
53439
|
-
}
|
|
53440
|
-
const model = this.find(configured.provider, configured.modelId);
|
|
53441
|
-
if (!model) {
|
|
53442
|
-
return { fallbackReason: `models.json defaults.modelClasses.${modelClass} points to missing model ${configured.provider}/${configured.modelId}` };
|
|
53443
|
-
}
|
|
53444
|
-
const apiKey = this.getApiKey(model);
|
|
53445
|
-
if (!apiKey) {
|
|
53446
|
-
return { model, fallbackReason: `no API key available for model class ${modelClass} (${configured.provider}/${configured.modelId})` };
|
|
53447
|
-
}
|
|
53448
|
-
return { model, apiKey };
|
|
53449
|
-
}
|
|
53450
|
-
/** Resolve an explicit model reference for user-requested overrides.
|
|
53451
|
-
* Accepts "provider/model-id" (exact lookup) or a bare model id (only
|
|
53452
|
-
* when it matches exactly one configured model). Never guesses across
|
|
53453
|
-
* providers; ambiguity and missing keys are reported as fallback reasons. */
|
|
53454
|
-
resolveModelRef(ref) {
|
|
53455
|
-
const trimmed = ref.trim();
|
|
53456
|
-
if (!trimmed) {
|
|
53457
|
-
return { fallbackReason: "empty model reference" };
|
|
53458
|
-
}
|
|
53459
|
-
const separator = trimmed.indexOf("/");
|
|
53460
|
-
if (separator >= 0) {
|
|
53461
|
-
if (separator === 0 || separator === trimmed.length - 1) {
|
|
53462
|
-
return { fallbackReason: `invalid model reference "${trimmed}"; expected provider/model-id` };
|
|
53463
|
-
}
|
|
53464
|
-
const provider = trimmed.slice(0, separator);
|
|
53465
|
-
const modelId = trimmed.slice(separator + 1);
|
|
53466
|
-
const model2 = this.find(provider, modelId);
|
|
53467
|
-
if (!model2) {
|
|
53468
|
-
return { fallbackReason: `model "${trimmed}" is not configured` };
|
|
53469
|
-
}
|
|
53470
|
-
const apiKey2 = this.getApiKey(model2);
|
|
53471
|
-
if (!apiKey2) {
|
|
53472
|
-
return { model: model2, fallbackReason: `no API key available for model "${trimmed}"` };
|
|
53473
|
-
}
|
|
53474
|
-
return { model: model2, apiKey: apiKey2 };
|
|
53475
|
-
}
|
|
53476
|
-
const matches = this.getAll().filter((model2) => model2.id === trimmed);
|
|
53477
|
-
if (matches.length === 0) {
|
|
53478
|
-
return { fallbackReason: `model "${trimmed}" is not configured; use provider/model-id` };
|
|
53479
|
-
}
|
|
53480
|
-
if (matches.length > 1) {
|
|
53481
|
-
return { fallbackReason: `model "${trimmed}" is ambiguous across providers (${matches.map((model2) => `${model2.provider}/${model2.id}`).join(", ")}); use provider/model-id` };
|
|
53482
|
-
}
|
|
53483
|
-
const model = matches[0];
|
|
53484
|
-
const apiKey = this.getApiKey(model);
|
|
53485
|
-
if (!apiKey) {
|
|
53486
|
-
return { model, fallbackReason: `no API key available for model "${model.provider}/${model.id}"` };
|
|
53487
|
-
}
|
|
53488
|
-
return { model, apiKey };
|
|
53489
|
-
}
|
|
53490
|
-
hasExternalProviderConfig() {
|
|
53491
|
-
return this.usingExternalProviders;
|
|
53492
|
-
}
|
|
53493
|
-
getLoadError() {
|
|
53494
|
-
return this.loadError;
|
|
53495
|
-
}
|
|
53496
|
-
find(provider, modelId) {
|
|
53497
|
-
return this.models.get(provider)?.get(modelId);
|
|
53498
|
-
}
|
|
53499
|
-
getAll() {
|
|
53500
|
-
const all = [];
|
|
53501
|
-
for (const providerModels of this.models.values()) {
|
|
53502
|
-
all.push(...providerModels.values());
|
|
53503
|
-
}
|
|
53504
|
-
return all.sort((a, b2) => `${a.provider}/${a.id}`.localeCompare(`${b2.provider}/${b2.id}`));
|
|
53505
|
-
}
|
|
53506
|
-
getAllInConfigOrder() {
|
|
53507
|
-
const ordered = [];
|
|
53508
|
-
const seen = /* @__PURE__ */ new Set();
|
|
53509
|
-
for (const key of this.modelOrder) {
|
|
53510
|
-
const [provider, ...modelParts] = key.split("/");
|
|
53511
|
-
const modelId = modelParts.join("/");
|
|
53512
|
-
const model = this.find(provider, modelId);
|
|
53513
|
-
if (!model) continue;
|
|
53514
|
-
ordered.push(model);
|
|
53515
|
-
seen.add(key);
|
|
53516
|
-
}
|
|
53517
|
-
for (const model of this.getAll()) {
|
|
53518
|
-
const key = `${model.provider}/${model.id}`;
|
|
53519
|
-
if (!seen.has(key)) ordered.push(model);
|
|
53520
|
-
}
|
|
53521
|
-
return ordered;
|
|
53522
|
-
}
|
|
53523
|
-
getAvailable() {
|
|
53524
|
-
return this.getAll().filter((model) => !!this.getApiKey(model));
|
|
53525
|
-
}
|
|
53526
|
-
getByProvider(provider) {
|
|
53527
|
-
return [...this.models.get(provider)?.values() || []].sort((a, b2) => a.id.localeCompare(b2.id));
|
|
53528
|
-
}
|
|
53529
|
-
listAvailableModels() {
|
|
53530
|
-
return this.getAll().map((model) => `${model.provider}/${model.id}`);
|
|
53531
|
-
}
|
|
53532
|
-
getApiKey(model) {
|
|
53533
|
-
const remoteEnv = this.remoteCredentialEnvByProvider.get(model.provider);
|
|
53534
|
-
if (remoteEnv) return typeof process !== "undefined" ? process.env?.[remoteEnv] : void 0;
|
|
53535
|
-
return this.authStorage.getApiKey(model.provider, model.apiKeyEnv);
|
|
53536
|
-
}
|
|
53537
|
-
getApiKeyForProvider(provider) {
|
|
53538
|
-
const remoteEnv = this.remoteCredentialEnvByProvider.get(provider);
|
|
53539
|
-
if (remoteEnv) return typeof process !== "undefined" ? process.env?.[remoteEnv] : void 0;
|
|
53540
|
-
return this.authStorage.getApiKey(provider);
|
|
53541
|
-
}
|
|
53542
|
-
/**
|
|
53543
|
-
* Register a provider at runtime (extension API). Not persisted to
|
|
53544
|
-
* models.json: runtime registrations live for the process unless the
|
|
53545
|
-
* extension registers them again. Returns an unregister handle that
|
|
53546
|
-
* restores the provider's previous state (models, order, env binding).
|
|
53547
|
-
*
|
|
53548
|
-
* When the provider already exists (local profile or remote catalog),
|
|
53549
|
-
* models are merged by id: registered models upsert over existing entries
|
|
53550
|
-
* with the same id; existing entries not named in `config.models` survive.
|
|
53551
|
-
* baseUrl/api/headers patch every model of that provider (existing and
|
|
53552
|
-
* new) when provided.
|
|
53553
|
-
*/
|
|
53554
|
-
registerProvider(provider, config) {
|
|
53555
|
-
validateExtensionProviderConfig(provider, config);
|
|
53556
|
-
const previousModels = this.models.get(provider) ? new Map(this.models.get(provider)) : void 0;
|
|
53557
|
-
const previousOrder = [...this.modelOrder];
|
|
53558
|
-
const previousEnvVar = this.authStorage.getProviderEnvVar(provider);
|
|
53559
|
-
if (config.apiKey) {
|
|
53560
|
-
this.authStorage.setRuntimeApiKey(provider, config.apiKey);
|
|
53561
|
-
}
|
|
53562
|
-
if (config.apiKeyEnv) {
|
|
53563
|
-
this.authStorage.setProviderEnvVar(provider, config.apiKeyEnv);
|
|
53564
|
-
}
|
|
53565
|
-
const existing = this.models.get(provider);
|
|
53566
|
-
if (existing && (config.baseUrl || config.api || config.headers || config.transport)) {
|
|
53567
|
-
for (const model of existing.values()) {
|
|
53568
|
-
this.upsert({
|
|
53569
|
-
...model,
|
|
53570
|
-
baseUrl: config.baseUrl || model.baseUrl,
|
|
53571
|
-
api: config.api || model.api,
|
|
53572
|
-
transport: config.transport ?? model.transport,
|
|
53573
|
-
headers: config.headers ? { ...model.headers, ...config.headers } : model.headers
|
|
53574
|
-
});
|
|
53575
|
-
}
|
|
53576
|
-
}
|
|
53577
|
-
for (const customModel of config.models ?? []) {
|
|
53578
|
-
const baseModel = this.models.get(provider)?.get(customModel.id);
|
|
53579
|
-
this.upsert({
|
|
53580
|
-
id: customModel.id,
|
|
53581
|
-
name: customModel.name || baseModel?.name || customModel.id,
|
|
53582
|
-
api: config.api || baseModel?.api || "openai-completions",
|
|
53583
|
-
provider,
|
|
53584
|
-
baseUrl: config.baseUrl || baseModel?.baseUrl || "",
|
|
53585
|
-
reasoning: customModel.reasoning ?? baseModel?.reasoning ?? false,
|
|
53586
|
-
input: customModel.input || baseModel?.input || ["text"],
|
|
53587
|
-
cost: customModel.cost || baseModel?.cost || { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
53588
|
-
contextWindow: customModel.contextWindow || baseModel?.contextWindow || 128e3,
|
|
53589
|
-
maxTokens: customModel.maxTokens || baseModel?.maxTokens || 8192,
|
|
53590
|
-
apiKeyEnv: config.apiKeyEnv || baseModel?.apiKeyEnv,
|
|
53591
|
-
displayName: customModel.displayName || baseModel?.displayName || provider,
|
|
53592
|
-
headers: config.headers ? { ...baseModel?.headers, ...config.headers, ...customModel.headers } : customModel.headers || baseModel?.headers,
|
|
53593
|
-
transport: customModel.transport ?? config.transport ?? baseModel?.transport,
|
|
53594
|
-
compat: customModel.compat || baseModel?.compat,
|
|
53595
|
-
cacheCapability: customModel.cacheCapability || baseModel?.cacheCapability,
|
|
53596
|
-
webSearch: customModel.webSearch || baseModel?.webSearch,
|
|
53597
|
-
fileCapabilities: customModel.fileCapabilities || baseModel?.fileCapabilities
|
|
53598
|
-
});
|
|
53599
|
-
}
|
|
53600
|
-
this.applyModelOverrides();
|
|
53601
|
-
this.usingExternalProviders = true;
|
|
53602
|
-
const registeredOAuth = config.oauth;
|
|
53603
|
-
if (registeredOAuth) this.extensionOAuthProviders.set(provider, registeredOAuth);
|
|
53604
|
-
return () => {
|
|
53605
|
-
if (previousModels) this.models.set(provider, previousModels);
|
|
53606
|
-
else this.models.delete(provider);
|
|
53607
|
-
this.modelOrder = previousOrder;
|
|
53608
|
-
this.authStorage.setRuntimeApiKey(provider, void 0);
|
|
53609
|
-
this.authStorage.setProviderEnvVar(provider, previousEnvVar);
|
|
53610
|
-
if (registeredOAuth) this.extensionOAuthProviders.delete(provider);
|
|
53611
|
-
this.applyModelOverrides();
|
|
53612
|
-
};
|
|
53613
|
-
}
|
|
53614
|
-
/** OAuth flow declared by an extension-registered provider, if any. */
|
|
53615
|
-
getExtensionOAuth(provider) {
|
|
53616
|
-
return this.extensionOAuthProviders.get(provider);
|
|
53617
|
-
}
|
|
53618
|
-
/**
|
|
53619
|
-
* Restore persisted OAuth credentials now that extensions have registered
|
|
53620
|
-
* their providers: refresh expired tokens when the extension declares
|
|
53621
|
-
* refreshToken, and drop the runtime binding when a token cannot be
|
|
53622
|
-
* recovered (getApiKey then reports the provider as unauthenticated).
|
|
53623
|
-
* Never throws; returns per-provider outcomes for the host to surface.
|
|
53624
|
-
*/
|
|
53625
|
-
async restorePersistedOAuth() {
|
|
53626
|
-
const authStorage = this.authStorage;
|
|
53627
|
-
const results = [];
|
|
53628
|
-
for (const provider of authStorage.getOAuthProviderNames()) {
|
|
53629
|
-
const credentials = authStorage.getOAuthCredentials(provider);
|
|
53630
|
-
if (!credentials?.access) continue;
|
|
53631
|
-
const expired = credentials.expires !== void 0 && credentials.expires <= Date.now() + OAUTH_RESTORE_LEEWAY_MS;
|
|
53632
|
-
if (!expired) continue;
|
|
53633
|
-
const oauth = this.extensionOAuthProviders.get(provider);
|
|
53634
|
-
if (!oauth?.refreshToken || !credentials.refresh) {
|
|
53635
|
-
authStorage.setRuntimeApiKey(provider, void 0);
|
|
53636
|
-
results.push({ provider, action: "not-refreshable", detail: "token expired and no refresh flow" });
|
|
53637
|
-
continue;
|
|
53638
|
-
}
|
|
53639
|
-
try {
|
|
53640
|
-
const next = await withTimeout(
|
|
53641
|
-
oauth.refreshToken({
|
|
53642
|
-
access: credentials.access,
|
|
53643
|
-
refresh: credentials.refresh,
|
|
53644
|
-
expires: credentials.expires
|
|
53645
|
-
}),
|
|
53646
|
-
OAUTH_REFRESH_TIMEOUT_MS,
|
|
53647
|
-
`${provider} refreshToken timed out after ${OAUTH_REFRESH_TIMEOUT_MS}ms`
|
|
53648
|
-
);
|
|
53649
|
-
const merged = { ...credentials, ...next };
|
|
53650
|
-
authStorage.setOAuthCredentials(provider, merged);
|
|
53651
|
-
authStorage.setRuntimeApiKey(provider, merged.access);
|
|
53652
|
-
results.push({ provider, action: "refreshed" });
|
|
53653
|
-
} catch (error) {
|
|
53654
|
-
authStorage.setRuntimeApiKey(provider, void 0);
|
|
53655
|
-
results.push({ provider, action: "refresh-failed", detail: error instanceof Error ? error.message : String(error) });
|
|
53656
|
-
}
|
|
53657
|
-
}
|
|
53658
|
-
return results;
|
|
53659
|
-
}
|
|
53660
|
-
/** Credential store backing this registry (for OAuth persistence). */
|
|
53661
|
-
getAuthStorage() {
|
|
53662
|
-
return this.authStorage;
|
|
53663
|
-
}
|
|
53664
|
-
};
|
|
53665
|
-
|
|
53666
|
-
// src/core/settings-manager.ts
|
|
53667
|
-
import * as fs4 from "fs";
|
|
53668
|
-
import * as path4 from "path";
|
|
53669
51749
|
function getDisabledToolNames(settingsManager) {
|
|
53670
51750
|
const disabled = new Set(typeof settingsManager?.getDisabledTools === "function" ? settingsManager.getDisabledTools() : []);
|
|
53671
51751
|
if (disabled.has("bash") || disabled.has("shell")) {
|
|
@@ -53681,8 +51761,31 @@ function filterEnabledTools(tools, settingsManager) {
|
|
|
53681
51761
|
function isPlainObject(value) {
|
|
53682
51762
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
53683
51763
|
}
|
|
51764
|
+
var COUPLED_SETTINGS_KEY_GROUPS = [
|
|
51765
|
+
// settings.json (and models-defaults views) spell the pair
|
|
51766
|
+
// defaultProvider/defaultModel; the legacy config.json mirror spells it
|
|
51767
|
+
// provider/modelId. Both documents merge through this function, and each
|
|
51768
|
+
// group is a no-op for the document that lacks its keys, so listing both
|
|
51769
|
+
// spellings closes the splice in either file.
|
|
51770
|
+
["defaultProvider", "defaultModel"],
|
|
51771
|
+
["provider", "modelId"]
|
|
51772
|
+
];
|
|
53684
51773
|
function mergeSnapshotDelta(atLoad, current, onDisk) {
|
|
53685
|
-
|
|
51774
|
+
const merged = mergeDeltaNode(atLoad, current, onDisk);
|
|
51775
|
+
if (!isPlainObject(merged) || !isPlainObject(current)) return merged;
|
|
51776
|
+
const load = isPlainObject(atLoad) ? atLoad : {};
|
|
51777
|
+
for (const group of COUPLED_SETTINGS_KEY_GROUPS) {
|
|
51778
|
+
const groupChanged = group.some(
|
|
51779
|
+
(key) => JSON.stringify(load[key]) !== JSON.stringify(current[key])
|
|
51780
|
+
);
|
|
51781
|
+
if (!groupChanged) continue;
|
|
51782
|
+
for (const key of group) {
|
|
51783
|
+
const after = Object.hasOwn(current, key) ? current[key] : void 0;
|
|
51784
|
+
if (after === void 0) delete merged[key];
|
|
51785
|
+
else setOwnDataProperty(merged, key, after);
|
|
51786
|
+
}
|
|
51787
|
+
}
|
|
51788
|
+
return merged;
|
|
53686
51789
|
}
|
|
53687
51790
|
function mergeDeltaNode(load, cur, disk) {
|
|
53688
51791
|
if (!isPlainObject(disk)) {
|
|
@@ -53742,29 +51845,29 @@ function cloneJsonDocument(value) {
|
|
|
53742
51845
|
return JSON.parse(JSON.stringify(value));
|
|
53743
51846
|
}
|
|
53744
51847
|
function writeJsonAtomic(filePath, value) {
|
|
53745
|
-
|
|
51848
|
+
fs2.mkdirSync(path2.dirname(filePath), { recursive: true });
|
|
53746
51849
|
const tempPath = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
53747
51850
|
try {
|
|
53748
|
-
const fd =
|
|
51851
|
+
const fd = fs2.openSync(tempPath, "w");
|
|
53749
51852
|
try {
|
|
53750
|
-
|
|
53751
|
-
|
|
51853
|
+
fs2.writeFileSync(fd, JSON.stringify(value, null, 2));
|
|
51854
|
+
fs2.fsyncSync(fd);
|
|
53752
51855
|
} finally {
|
|
53753
|
-
|
|
51856
|
+
fs2.closeSync(fd);
|
|
53754
51857
|
}
|
|
53755
|
-
|
|
51858
|
+
fs2.renameSync(tempPath, filePath);
|
|
53756
51859
|
try {
|
|
53757
|
-
const dirFd =
|
|
51860
|
+
const dirFd = fs2.openSync(path2.dirname(filePath), "r");
|
|
53758
51861
|
try {
|
|
53759
|
-
|
|
51862
|
+
fs2.fsyncSync(dirFd);
|
|
53760
51863
|
} finally {
|
|
53761
|
-
|
|
51864
|
+
fs2.closeSync(dirFd);
|
|
53762
51865
|
}
|
|
53763
51866
|
} catch {
|
|
53764
51867
|
}
|
|
53765
51868
|
} catch (error) {
|
|
53766
51869
|
try {
|
|
53767
|
-
|
|
51870
|
+
fs2.unlinkSync(tempPath);
|
|
53768
51871
|
} catch {
|
|
53769
51872
|
}
|
|
53770
51873
|
throw error;
|
|
@@ -53792,9 +51895,9 @@ var SettingsManager = class {
|
|
|
53792
51895
|
this.legacyConfigLastWritten = cloneJsonDocument(this.legacyConfig);
|
|
53793
51896
|
}
|
|
53794
51897
|
readJson(filePath) {
|
|
53795
|
-
if (!
|
|
51898
|
+
if (!fs2.existsSync(filePath)) return null;
|
|
53796
51899
|
try {
|
|
53797
|
-
return JSON.parse(
|
|
51900
|
+
return JSON.parse(fs2.readFileSync(filePath, "utf-8"));
|
|
53798
51901
|
} catch {
|
|
53799
51902
|
return null;
|
|
53800
51903
|
}
|
|
@@ -53806,7 +51909,7 @@ var SettingsManager = class {
|
|
|
53806
51909
|
return this.readJson(this.legacyConfigPath) || {};
|
|
53807
51910
|
}
|
|
53808
51911
|
ensureDir() {
|
|
53809
|
-
|
|
51912
|
+
fs2.mkdirSync(getConfigDir(), { recursive: true });
|
|
53810
51913
|
}
|
|
53811
51914
|
writeSettings() {
|
|
53812
51915
|
this.ensureDir();
|
|
@@ -53832,9 +51935,9 @@ var SettingsManager = class {
|
|
|
53832
51935
|
mergeOntoDisk(filePath, lastWritten, current) {
|
|
53833
51936
|
let onDisk = null;
|
|
53834
51937
|
let corrupt = false;
|
|
53835
|
-
if (
|
|
51938
|
+
if (fs2.existsSync(filePath)) {
|
|
53836
51939
|
try {
|
|
53837
|
-
onDisk = JSON.parse(
|
|
51940
|
+
onDisk = JSON.parse(fs2.readFileSync(filePath, "utf-8"));
|
|
53838
51941
|
} catch {
|
|
53839
51942
|
corrupt = true;
|
|
53840
51943
|
}
|
|
@@ -54055,19 +52158,19 @@ function checkShell() {
|
|
|
54055
52158
|
}
|
|
54056
52159
|
function canWriteDirectory(dir) {
|
|
54057
52160
|
try {
|
|
54058
|
-
|
|
54059
|
-
const probe =
|
|
54060
|
-
|
|
54061
|
-
|
|
52161
|
+
fs3.mkdirSync(dir, { recursive: true });
|
|
52162
|
+
const probe = path3.join(dir, `.pie-doctor-${process.pid}-${Date.now()}`);
|
|
52163
|
+
fs3.writeFileSync(probe, "ok", "utf8");
|
|
52164
|
+
fs3.rmSync(probe, { force: true });
|
|
54062
52165
|
return { ok: true };
|
|
54063
52166
|
} catch (error) {
|
|
54064
52167
|
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
54065
52168
|
}
|
|
54066
52169
|
}
|
|
54067
52170
|
function isExecutable(candidate) {
|
|
54068
|
-
if (!candidate || !
|
|
52171
|
+
if (!candidate || !fs3.existsSync(candidate)) return false;
|
|
54069
52172
|
try {
|
|
54070
|
-
|
|
52173
|
+
fs3.accessSync(candidate, fs3.constants.X_OK);
|
|
54071
52174
|
return true;
|
|
54072
52175
|
} catch {
|
|
54073
52176
|
return os.platform() === "win32";
|
|
@@ -54077,7 +52180,7 @@ function findOnPath(names) {
|
|
|
54077
52180
|
for (const dir of (process.env.PATH || "").split(delimiter)) {
|
|
54078
52181
|
if (!dir) continue;
|
|
54079
52182
|
for (const name of names) {
|
|
54080
|
-
const candidate =
|
|
52183
|
+
const candidate = path3.join(dir, name);
|
|
54081
52184
|
if (isExecutable(candidate)) return candidate;
|
|
54082
52185
|
}
|
|
54083
52186
|
}
|
|
@@ -54093,10 +52196,10 @@ function findDoctorChromeExecutable() {
|
|
|
54093
52196
|
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
54094
52197
|
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
|
|
54095
52198
|
] : os.platform() === "win32" ? [
|
|
54096
|
-
|
|
54097
|
-
|
|
54098
|
-
|
|
54099
|
-
|
|
52199
|
+
path3.join(process.env.PROGRAMFILES || "C:\\Program Files", "Google", "Chrome", "Application", "chrome.exe"),
|
|
52200
|
+
path3.join(process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)", "Google", "Chrome", "Application", "chrome.exe"),
|
|
52201
|
+
path3.join(process.env.LOCALAPPDATA || path3.join(home, "AppData", "Local"), "Google", "Chrome", "Application", "chrome.exe"),
|
|
52202
|
+
path3.join(process.env.PROGRAMFILES || "C:\\Program Files", "Microsoft", "Edge", "Application", "msedge.exe")
|
|
54100
52203
|
] : [
|
|
54101
52204
|
"/usr/bin/google-chrome",
|
|
54102
52205
|
"/usr/bin/google-chrome-stable",
|
|
@@ -54112,8 +52215,8 @@ function findDoctorChromeExecutable() {
|
|
|
54112
52215
|
}
|
|
54113
52216
|
function resolveDoctorChromeDevtoolsAxiCli() {
|
|
54114
52217
|
try {
|
|
54115
|
-
const runtime =
|
|
54116
|
-
return
|
|
52218
|
+
const runtime = path3.join(getBuiltinDir(), "skills", "chrome-devtools-axi", "chrome-devtools-axi-runtime.js");
|
|
52219
|
+
return fs3.existsSync(runtime) ? runtime : void 0;
|
|
54117
52220
|
} catch {
|
|
54118
52221
|
return void 0;
|
|
54119
52222
|
}
|
|
@@ -54141,10 +52244,10 @@ function checkChromeDevtoolsAxiCli() {
|
|
|
54141
52244
|
function checkComputerUse() {
|
|
54142
52245
|
if (process.platform === "darwin") {
|
|
54143
52246
|
const envAppPath = process.env.PIE_COMPUTER_USE_HELPER_APP_PATH?.trim();
|
|
54144
|
-
const systemAppPath =
|
|
54145
|
-
const systemAppUsable =
|
|
54146
|
-
const appPath = envAppPath || (systemAppUsable ? systemAppPath :
|
|
54147
|
-
const executable =
|
|
52247
|
+
const systemAppPath = path3.join("/Applications", "pie-computer-use.app");
|
|
52248
|
+
const systemAppUsable = fs3.existsSync(systemAppPath) && canWriteDirectory(path3.dirname(systemAppPath)).ok;
|
|
52249
|
+
const appPath = envAppPath || (systemAppUsable ? systemAppPath : path3.join(getConfigDir(), "computer-use", "pie-computer-use.app"));
|
|
52250
|
+
const executable = path3.join(appPath, "Contents", "MacOS", "pie-computer-use");
|
|
54148
52251
|
if (isExecutable(executable)) {
|
|
54149
52252
|
return {
|
|
54150
52253
|
id: "computer_use_helper",
|
|
@@ -54163,7 +52266,7 @@ function checkComputerUse() {
|
|
|
54163
52266
|
};
|
|
54164
52267
|
}
|
|
54165
52268
|
if (process.platform === "linux") {
|
|
54166
|
-
const helperPath = process.env.PIE_COMPUTER_USE_LINUX_HELPER_PATH ??
|
|
52269
|
+
const helperPath = process.env.PIE_COMPUTER_USE_LINUX_HELPER_PATH ?? path3.join(getConfigDir(), "helpers", "computer-use", "linux-bridge");
|
|
54167
52270
|
const installed = isExecutable(helperPath);
|
|
54168
52271
|
return {
|
|
54169
52272
|
id: "computer_use_helper",
|
|
@@ -54174,8 +52277,8 @@ function checkComputerUse() {
|
|
|
54174
52277
|
};
|
|
54175
52278
|
}
|
|
54176
52279
|
if (process.platform === "win32") {
|
|
54177
|
-
const helperPath = process.env.PIE_COMPUTER_USE_WINDOWS_HELPER_PATH ??
|
|
54178
|
-
const installed =
|
|
52280
|
+
const helperPath = process.env.PIE_COMPUTER_USE_WINDOWS_HELPER_PATH ?? path3.join(getConfigDir(), "helpers", "computer-use", "windows-bridge.exe");
|
|
52281
|
+
const installed = fs3.existsSync(helperPath);
|
|
54179
52282
|
return {
|
|
54180
52283
|
id: "computer_use_helper",
|
|
54181
52284
|
label: "computer-use helper",
|
|
@@ -54213,8 +52316,8 @@ function isLiveUnityInstance(instance, nowUnix = Math.floor(Date.now() / 1e3)) {
|
|
|
54213
52316
|
return isProcessAlive(Number(instance.pid || 0));
|
|
54214
52317
|
}
|
|
54215
52318
|
function checkUnityRegistry() {
|
|
54216
|
-
const registryDir =
|
|
54217
|
-
if (!
|
|
52319
|
+
const registryDir = path3.join(os.homedir(), ".pie-unity", "instances");
|
|
52320
|
+
if (!fs3.existsSync(registryDir)) {
|
|
54218
52321
|
return {
|
|
54219
52322
|
id: "unity_bridge",
|
|
54220
52323
|
label: "Unity bridge",
|
|
@@ -54225,12 +52328,12 @@ function checkUnityRegistry() {
|
|
|
54225
52328
|
}
|
|
54226
52329
|
try {
|
|
54227
52330
|
const nowUnix = Math.floor(Date.now() / 1e3);
|
|
54228
|
-
const files =
|
|
52331
|
+
const files = fs3.readdirSync(registryDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => path3.join(registryDir, entry.name));
|
|
54229
52332
|
let malformedFiles = 0;
|
|
54230
52333
|
let invalidFiles = 0;
|
|
54231
52334
|
const liveInstances = files.map((filePath) => {
|
|
54232
52335
|
try {
|
|
54233
|
-
const parsed = JSON.parse(
|
|
52336
|
+
const parsed = JSON.parse(fs3.readFileSync(filePath, "utf8").replace(/^\uFEFF/, ""));
|
|
54234
52337
|
if (!isRecord(parsed)) {
|
|
54235
52338
|
invalidFiles += 1;
|
|
54236
52339
|
return null;
|
|
@@ -54304,13 +52407,13 @@ async function runDoctor() {
|
|
|
54304
52407
|
const packageDir = getPackageDir();
|
|
54305
52408
|
let dir = packageDir;
|
|
54306
52409
|
let lockPath;
|
|
54307
|
-
while (dir !==
|
|
54308
|
-
const candidate =
|
|
54309
|
-
if (
|
|
52410
|
+
while (dir !== path3.dirname(dir)) {
|
|
52411
|
+
const candidate = path3.join(dir, "package-lock.json");
|
|
52412
|
+
if (fs3.existsSync(candidate)) {
|
|
54310
52413
|
lockPath = candidate;
|
|
54311
52414
|
break;
|
|
54312
52415
|
}
|
|
54313
|
-
dir =
|
|
52416
|
+
dir = path3.dirname(dir);
|
|
54314
52417
|
}
|
|
54315
52418
|
checks.push({
|
|
54316
52419
|
id: "package_lock",
|
|
@@ -54503,10 +52606,10 @@ Disable or narrow capabilities:
|
|
|
54503
52606
|
}
|
|
54504
52607
|
|
|
54505
52608
|
// src/commands/models-config.ts
|
|
54506
|
-
import * as
|
|
54507
|
-
import * as
|
|
52609
|
+
import * as fs4 from "node:fs";
|
|
52610
|
+
import * as path4 from "node:path";
|
|
54508
52611
|
function getDefaultModelsPath() {
|
|
54509
|
-
return
|
|
52612
|
+
return path4.join(getConfigDir(), "models.json");
|
|
54510
52613
|
}
|
|
54511
52614
|
function createModelsTemplate() {
|
|
54512
52615
|
const template = {
|
|
@@ -54601,7 +52704,7 @@ function createModelsTemplate() {
|
|
|
54601
52704
|
`;
|
|
54602
52705
|
}
|
|
54603
52706
|
function resolveModelsPath(input) {
|
|
54604
|
-
return input ?
|
|
52707
|
+
return input ? path4.resolve(input) : getDefaultModelsPath();
|
|
54605
52708
|
}
|
|
54606
52709
|
function initModelsConfig(options = {}) {
|
|
54607
52710
|
const targetPath = resolveModelsPath(options.path);
|
|
@@ -54609,16 +52712,16 @@ function initModelsConfig(options = {}) {
|
|
|
54609
52712
|
if (options.stdout) {
|
|
54610
52713
|
return { path: targetPath, content, wrote: false };
|
|
54611
52714
|
}
|
|
54612
|
-
if (
|
|
52715
|
+
if (fs4.existsSync(targetPath) && !options.force) {
|
|
54613
52716
|
throw new Error(`models.json already exists: ${targetPath}. Use --force to overwrite, or --stdout to print the template.`);
|
|
54614
52717
|
}
|
|
54615
|
-
|
|
54616
|
-
|
|
52718
|
+
fs4.mkdirSync(path4.dirname(targetPath), { recursive: true });
|
|
52719
|
+
fs4.writeFileSync(targetPath, content, "utf8");
|
|
54617
52720
|
return { path: targetPath, content, wrote: true };
|
|
54618
52721
|
}
|
|
54619
52722
|
function validateModelsConfig(options = {}) {
|
|
54620
52723
|
const modelsPath = resolveModelsPath(options.path);
|
|
54621
|
-
if (!
|
|
52724
|
+
if (!fs4.existsSync(modelsPath)) {
|
|
54622
52725
|
return {
|
|
54623
52726
|
ok: false,
|
|
54624
52727
|
path: modelsPath,
|
|
@@ -55413,6 +53516,456 @@ function runCapabilitiesCommand(args) {
|
|
|
55413
53516
|
console.log(formatCapabilitiesHelp(report));
|
|
55414
53517
|
}
|
|
55415
53518
|
|
|
53519
|
+
// src/commands/memory-cli.ts
|
|
53520
|
+
import * as fs5 from "node:fs";
|
|
53521
|
+
import * as path5 from "node:path";
|
|
53522
|
+
import { pathToFileURL } from "node:url";
|
|
53523
|
+
var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
53524
|
+
var MEMORY_MANAGER = "memory";
|
|
53525
|
+
function usage(code = 2) {
|
|
53526
|
+
console.log(`pie memory \u2014 session-derived memory management
|
|
53527
|
+
|
|
53528
|
+
Usage:
|
|
53529
|
+
pie memory distill [--date YYYY-MM-DD | --auto] [--memory-root <dir>] spawn detached worker
|
|
53530
|
+
pie memory distill --worker --date <d> | --auto --memory-root <dir> run in-process (worker mode)
|
|
53531
|
+
pie memory schedule on [--time HH:MM] | off | status daily managed cron job
|
|
53532
|
+
pie memory status [--memory-root <dir>] per-date checkpoints + failures
|
|
53533
|
+
pie memory log [--memory-root <dir>] [-n <lines>] tail the worker log
|
|
53534
|
+
|
|
53535
|
+
The default date is yesterday (local). --auto covers the last 7 days.`);
|
|
53536
|
+
process.exit(code);
|
|
53537
|
+
}
|
|
53538
|
+
function isFlagToken(value) {
|
|
53539
|
+
return value.startsWith("-");
|
|
53540
|
+
}
|
|
53541
|
+
function parseFlag(args, name) {
|
|
53542
|
+
const prefix = `${name}=`;
|
|
53543
|
+
for (const arg of args) {
|
|
53544
|
+
if (arg.startsWith(prefix)) {
|
|
53545
|
+
const value = arg.slice(prefix.length);
|
|
53546
|
+
if (value.length === 0) return { error: `${name}= requires a value` };
|
|
53547
|
+
return { value };
|
|
53548
|
+
}
|
|
53549
|
+
}
|
|
53550
|
+
const index = args.indexOf(name);
|
|
53551
|
+
if (index >= 0) {
|
|
53552
|
+
const value = args[index + 1];
|
|
53553
|
+
if (value === void 0) return { error: `${name} requires a value` };
|
|
53554
|
+
if (isFlagToken(value)) return { error: `${name} requires a value, got "${value}"` };
|
|
53555
|
+
return { value };
|
|
53556
|
+
}
|
|
53557
|
+
return {};
|
|
53558
|
+
}
|
|
53559
|
+
function parseDateFlag(args) {
|
|
53560
|
+
const parsed = parseFlag(args, "--date");
|
|
53561
|
+
if (parsed.error) return parsed;
|
|
53562
|
+
if (parsed.value === void 0) return {};
|
|
53563
|
+
if (!DATE_RE.test(parsed.value)) {
|
|
53564
|
+
return { error: `--date must be YYYY-MM-DD, got "${parsed.value}"` };
|
|
53565
|
+
}
|
|
53566
|
+
const probe = /* @__PURE__ */ new Date(`${parsed.value}T00:00:00`);
|
|
53567
|
+
if (Number.isNaN(probe.getTime())) return { error: `--date is not a real calendar date: "${parsed.value}"` };
|
|
53568
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
53569
|
+
const roundTrip = `${probe.getFullYear()}-${pad(probe.getMonth() + 1)}-${pad(probe.getDate())}`;
|
|
53570
|
+
if (roundTrip !== parsed.value) return { error: `--date is not a real calendar date: "${parsed.value}" (resolves to ${roundTrip})` };
|
|
53571
|
+
return { value: parsed.value };
|
|
53572
|
+
}
|
|
53573
|
+
function parseMemoryRootFlag(args) {
|
|
53574
|
+
const parsed = parseFlag(args, "--memory-root");
|
|
53575
|
+
if (parsed.error) return parsed;
|
|
53576
|
+
if (parsed.value !== void 0 && parsed.value.length === 0) return { error: "--memory-root requires a value" };
|
|
53577
|
+
return parsed;
|
|
53578
|
+
}
|
|
53579
|
+
function parseLogLimit(args) {
|
|
53580
|
+
for (const name of ["-n", "--lines"]) {
|
|
53581
|
+
const parsed = parseFlag(args, name);
|
|
53582
|
+
if (parsed.error) return { value: 20, error: parsed.error };
|
|
53583
|
+
if (parsed.value === void 0) continue;
|
|
53584
|
+
if (!/^\d+$/.test(parsed.value)) return { value: 20, error: `${name} must be a positive integer, got "${parsed.value}"` };
|
|
53585
|
+
return { value: Math.max(1, Number.parseInt(parsed.value, 10)) };
|
|
53586
|
+
}
|
|
53587
|
+
return { value: 20 };
|
|
53588
|
+
}
|
|
53589
|
+
function die(message) {
|
|
53590
|
+
console.error(`pie memory: ${message}`);
|
|
53591
|
+
process.exit(2);
|
|
53592
|
+
}
|
|
53593
|
+
async function runMemoryCommand(args) {
|
|
53594
|
+
const [sub, ...rest] = args;
|
|
53595
|
+
if (sub === void 0 || sub === "help" || sub === "--help" || sub === "-h") usage(sub === void 0 ? 2 : 0);
|
|
53596
|
+
const rootFlag = parseMemoryRootFlag(args);
|
|
53597
|
+
if (rootFlag.error) die(rootFlag.error);
|
|
53598
|
+
const root = rootFlag.value ?? path5.join(getConfigDir(), "memory");
|
|
53599
|
+
if (sub === "schedule") {
|
|
53600
|
+
if (rootFlag.value !== void 0) die("--memory-root is not supported for 'schedule' (the managed job always distills the default memory root)");
|
|
53601
|
+
return runScheduleCommand(rest);
|
|
53602
|
+
}
|
|
53603
|
+
if (sub === "distill") {
|
|
53604
|
+
const auto = rest.includes("--auto");
|
|
53605
|
+
const dateFlag = parseDateFlag(rest);
|
|
53606
|
+
if (dateFlag.error) die(dateFlag.error);
|
|
53607
|
+
if (auto && dateFlag.value !== void 0) die("--auto and --date are mutually exclusive");
|
|
53608
|
+
if (rest.includes("--worker")) {
|
|
53609
|
+
const workerRootFlag = parseMemoryRootFlag(rest);
|
|
53610
|
+
if (workerRootFlag.error) die(workerRootFlag.error);
|
|
53611
|
+
const workerRoot = workerRootFlag.value;
|
|
53612
|
+
if (!workerRoot) die("--worker requires --memory-root");
|
|
53613
|
+
if (auto) {
|
|
53614
|
+
const summary = await runDistillAuto(workerRoot);
|
|
53615
|
+
console.log(summary.lines.join("\n"));
|
|
53616
|
+
process.exitCode = summary.ok ? 0 : 1;
|
|
53617
|
+
return;
|
|
53618
|
+
}
|
|
53619
|
+
const date2 = dateFlag.value ?? yesterdayKey();
|
|
53620
|
+
const result = await runDistillWorkerMain(workerRoot, date2);
|
|
53621
|
+
if (result.busy) {
|
|
53622
|
+
console.log(`memory distill ${date2}: busy \u2014 another distillation worker holds the lock; nothing recorded, retry later`);
|
|
53623
|
+
return;
|
|
53624
|
+
}
|
|
53625
|
+
if (!result.ok) {
|
|
53626
|
+
console.error(`memory distill ${date2}: ${result.status ?? "failed"}${result.error ? `: ${result.error}` : ""}`);
|
|
53627
|
+
process.exit(1);
|
|
53628
|
+
}
|
|
53629
|
+
console.log(`memory distill ${date2}: ${result.status}`);
|
|
53630
|
+
return;
|
|
53631
|
+
}
|
|
53632
|
+
if (auto) {
|
|
53633
|
+
const spawned2 = spawnDistillAutoWorker(root);
|
|
53634
|
+
console.log(spawned2 ? `memory distill --auto: detached worker started (log: ${distillWorkerLogPath(root)})` : `memory distill --auto: could not spawn worker (log: ${distillWorkerLogPath(root)})`);
|
|
53635
|
+
process.exitCode = spawned2 ? 0 : 1;
|
|
53636
|
+
return;
|
|
53637
|
+
}
|
|
53638
|
+
const date = dateFlag.value ?? yesterdayKey();
|
|
53639
|
+
const store = new MemoryStore(root);
|
|
53640
|
+
if (store.hasRun(date)) {
|
|
53641
|
+
console.log(`memory distill ${date}: already distilled (checkpoint present)`);
|
|
53642
|
+
return;
|
|
53643
|
+
}
|
|
53644
|
+
const spawned = spawnDistillWorker(root, date);
|
|
53645
|
+
console.log(spawned ? `memory distill ${date}: detached worker started (log: ${distillWorkerLogPath(root)})` : `memory distill ${date}: could not spawn worker (log: ${distillWorkerLogPath(root)})`);
|
|
53646
|
+
process.exitCode = spawned ? 0 : 1;
|
|
53647
|
+
return;
|
|
53648
|
+
}
|
|
53649
|
+
if (sub === "status") {
|
|
53650
|
+
const store = new MemoryStore(root);
|
|
53651
|
+
const runs = Object.entries(store.loadState().runs).sort(([a], [b2]) => a < b2 ? 1 : -1);
|
|
53652
|
+
const schedule = describeMemorySchedule();
|
|
53653
|
+
if (schedule) console.log(`schedule: ${schedule}`);
|
|
53654
|
+
for (const line of consumptionSummary(store.loadEntries())) console.log(line);
|
|
53655
|
+
if (runs.length === 0) {
|
|
53656
|
+
console.log("No distillation runs recorded yet.");
|
|
53657
|
+
return;
|
|
53658
|
+
}
|
|
53659
|
+
for (const [date, run] of runs) {
|
|
53660
|
+
const failures = run.failures;
|
|
53661
|
+
const failureNote = failures && failures > 0 ? ` \xB7 failed ${failures}\xD7${run.lastError ? `: ${run.lastError}` : ""}` : "";
|
|
53662
|
+
console.log(`${date}: ${run.ops} ops at ${new Date(run.ranAt).toISOString()}${run.gated ? " (gated)" : ""}${failureNote}`);
|
|
53663
|
+
}
|
|
53664
|
+
return;
|
|
53665
|
+
}
|
|
53666
|
+
if (sub === "log") {
|
|
53667
|
+
const limit = parseLogLimit(rest);
|
|
53668
|
+
if (limit.error) die(limit.error);
|
|
53669
|
+
const lines = readDistillWorkerLog(root, limit.value);
|
|
53670
|
+
console.log(lines.length === 0 ? `No worker log yet (${distillWorkerLogPath(root)}).` : lines.join("\n"));
|
|
53671
|
+
return;
|
|
53672
|
+
}
|
|
53673
|
+
usage(2);
|
|
53674
|
+
}
|
|
53675
|
+
async function cronStore() {
|
|
53676
|
+
const entryUrl = pathToFileURL(path5.join(getBuiltinDir(), "extensions", "cron", "index.js")).href;
|
|
53677
|
+
const { Store, configPath } = await import(entryUrl);
|
|
53678
|
+
return { Store, configPath };
|
|
53679
|
+
}
|
|
53680
|
+
function managedMemoryCommand() {
|
|
53681
|
+
const entry = process.argv[1] ? path5.resolve(process.argv[1]) : null;
|
|
53682
|
+
if (!entry) throw new Error("cannot determine the CLI entrypoint for the managed schedule");
|
|
53683
|
+
return [process.execPath, entry, "memory", "distill", "--worker", "--auto", "--memory-root", path5.join(getConfigDir(), "memory")];
|
|
53684
|
+
}
|
|
53685
|
+
function timeToCron(value) {
|
|
53686
|
+
const match = value.match(/^(\d{1,2}):(\d{2})$/);
|
|
53687
|
+
if (!match) return { error: `--time must be HH:MM (local), got "${value}"` };
|
|
53688
|
+
const probe = /* @__PURE__ */ new Date();
|
|
53689
|
+
probe.setHours(Number(match[1]), Number(match[2]), 0, 0);
|
|
53690
|
+
if (Number(match[1]) > 23 || Number(match[2]) > 59) return { error: `--time out of range: "${value}"` };
|
|
53691
|
+
return { cron: `${probe.getUTCMinutes()} ${probe.getUTCHours()} * * *` };
|
|
53692
|
+
}
|
|
53693
|
+
function describeMemorySchedule() {
|
|
53694
|
+
try {
|
|
53695
|
+
const statePath = path5.join(getConfigDir(), "cron", "state.json");
|
|
53696
|
+
const raw = JSON.parse(fs5.readFileSync(statePath, "utf8"));
|
|
53697
|
+
const mine = (raw.jobs ?? []).find((job) => job.sessionId === "process" && (() => {
|
|
53698
|
+
try {
|
|
53699
|
+
return JSON.parse(job.prompt).managedBy === MEMORY_MANAGER;
|
|
53700
|
+
} catch {
|
|
53701
|
+
return false;
|
|
53702
|
+
}
|
|
53703
|
+
})());
|
|
53704
|
+
if (!mine) return void 0;
|
|
53705
|
+
const qualifier = !mine.enabled ? " (paused)" : mine.state === "blocked" ? ` (blocked: ${(mine.error ?? "").slice(0, 60)})` : "";
|
|
53706
|
+
return `on${qualifier} (job ${mine.id.slice(0, 8)}, next ${mine.next !== null ? new Date(mine.next).toISOString() : "none"})`;
|
|
53707
|
+
} catch {
|
|
53708
|
+
return void 0;
|
|
53709
|
+
}
|
|
53710
|
+
}
|
|
53711
|
+
async function runScheduleCommand(rest) {
|
|
53712
|
+
const [action, ...flags] = rest;
|
|
53713
|
+
const { Store, configPath } = await cronStore();
|
|
53714
|
+
const store = new Store(path5.join(configPath(), "cron"));
|
|
53715
|
+
if (action === "on") {
|
|
53716
|
+
const timeFlag = parseFlag(flags, "--time");
|
|
53717
|
+
if (timeFlag.error) die(timeFlag.error);
|
|
53718
|
+
const time = timeFlag.value ?? "09:00";
|
|
53719
|
+
const cron = timeToCron(time);
|
|
53720
|
+
if ("error" in cron) die(cron.error);
|
|
53721
|
+
const command = managedMemoryCommand();
|
|
53722
|
+
let job;
|
|
53723
|
+
try {
|
|
53724
|
+
job = store.addProcess(command, MEMORY_MANAGER, process.cwd(), cron);
|
|
53725
|
+
} catch (error) {
|
|
53726
|
+
die(String(error instanceof Error ? error.message : error));
|
|
53727
|
+
}
|
|
53728
|
+
console.log(`memory schedule on: daily at ${time} local (${cron.cron} UTC; fixed-UTC \u2014 DST shifts the local time). Runs: ${command.join(" ")}`);
|
|
53729
|
+
console.log("The cron extension triggers it whenever at least one cron-enabled Pie is open; missed days are caught up by --auto.");
|
|
53730
|
+
return;
|
|
53731
|
+
}
|
|
53732
|
+
if (action === "off") {
|
|
53733
|
+
const existing = store.findProcess(MEMORY_MANAGER);
|
|
53734
|
+
if (!existing) {
|
|
53735
|
+
console.log("memory schedule off: no managed job found (already off).");
|
|
53736
|
+
return;
|
|
53737
|
+
}
|
|
53738
|
+
if (existing.state === "running") die("the managed job is currently running; try again after it finishes");
|
|
53739
|
+
store.change(existing.id, "remove");
|
|
53740
|
+
console.log("memory schedule off: managed job removed.");
|
|
53741
|
+
return;
|
|
53742
|
+
}
|
|
53743
|
+
if (action === "status" || action === void 0) {
|
|
53744
|
+
const existing = store.findProcess(MEMORY_MANAGER);
|
|
53745
|
+
if (!existing) {
|
|
53746
|
+
console.log("memory schedule: off (no managed job; enable with `pie memory schedule on`)");
|
|
53747
|
+
return;
|
|
53748
|
+
}
|
|
53749
|
+
const command = (() => {
|
|
53750
|
+
try {
|
|
53751
|
+
return JSON.parse(existing.prompt).command;
|
|
53752
|
+
} catch {
|
|
53753
|
+
return void 0;
|
|
53754
|
+
}
|
|
53755
|
+
})();
|
|
53756
|
+
console.log(`memory schedule: on`);
|
|
53757
|
+
console.log(` job: ${existing.id} (state ${existing.state}, ${existing.enabled ? "enabled" : "paused"})`);
|
|
53758
|
+
console.log(` next: ${existing.next !== null ? new Date(existing.next).toISOString() : "none"}`);
|
|
53759
|
+
if (existing.error) console.log(` last error: ${existing.error}`);
|
|
53760
|
+
if (command) console.log(` command: ${command.join(" ")}`);
|
|
53761
|
+
return;
|
|
53762
|
+
}
|
|
53763
|
+
usage(2);
|
|
53764
|
+
}
|
|
53765
|
+
function yesterdayKey() {
|
|
53766
|
+
const probe = /* @__PURE__ */ new Date();
|
|
53767
|
+
probe.setDate(probe.getDate() - 1);
|
|
53768
|
+
return todayKey(probe.getTime());
|
|
53769
|
+
}
|
|
53770
|
+
|
|
53771
|
+
// src/commands/session-resume-restart.ts
|
|
53772
|
+
import { spawn } from "node:child_process";
|
|
53773
|
+
import * as fs6 from "node:fs";
|
|
53774
|
+
import * as path6 from "node:path";
|
|
53775
|
+
|
|
53776
|
+
// src/commands/session-resume-cwd.ts
|
|
53777
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
53778
|
+
var RESUME_CWD_SENTINEL_ENV = "PIE_RESUME_CWD";
|
|
53779
|
+
function buildChildArgv(argv, sessionId) {
|
|
53780
|
+
const out = [];
|
|
53781
|
+
let i = 0;
|
|
53782
|
+
let sawSessionId = false;
|
|
53783
|
+
while (i < argv.length) {
|
|
53784
|
+
const arg = argv[i];
|
|
53785
|
+
if (arg === "--session-id") {
|
|
53786
|
+
out.push(arg, sessionId);
|
|
53787
|
+
i += 2;
|
|
53788
|
+
sawSessionId = true;
|
|
53789
|
+
continue;
|
|
53790
|
+
}
|
|
53791
|
+
if (arg.startsWith("--session-id=")) {
|
|
53792
|
+
out.push(`--session-id=${sessionId}`);
|
|
53793
|
+
i += 1;
|
|
53794
|
+
sawSessionId = true;
|
|
53795
|
+
continue;
|
|
53796
|
+
}
|
|
53797
|
+
if (arg === "--no-cd") {
|
|
53798
|
+
i += 1;
|
|
53799
|
+
continue;
|
|
53800
|
+
}
|
|
53801
|
+
out.push(arg);
|
|
53802
|
+
i += 1;
|
|
53803
|
+
}
|
|
53804
|
+
if (!sawSessionId) out.push("--session-id", sessionId);
|
|
53805
|
+
return out;
|
|
53806
|
+
}
|
|
53807
|
+
var requireFs = createRequire2(import.meta.url);
|
|
53808
|
+
function defaultRealpath(p) {
|
|
53809
|
+
try {
|
|
53810
|
+
return requireFs("node:fs").realpathSync(p);
|
|
53811
|
+
} catch {
|
|
53812
|
+
return p;
|
|
53813
|
+
}
|
|
53814
|
+
}
|
|
53815
|
+
function resolveResumeRestart(inputs) {
|
|
53816
|
+
const env = inputs.env ?? {};
|
|
53817
|
+
const sentinel = env[RESUME_CWD_SENTINEL_ENV];
|
|
53818
|
+
if (sentinel !== void 0 && typeof sentinel === "string" && sentinel.length > 0) {
|
|
53819
|
+
const resolve0 = inputs.realpath ?? defaultRealpath;
|
|
53820
|
+
const resolveSafe = (p) => {
|
|
53821
|
+
try {
|
|
53822
|
+
return resolve0(p);
|
|
53823
|
+
} catch {
|
|
53824
|
+
return p;
|
|
53825
|
+
}
|
|
53826
|
+
};
|
|
53827
|
+
const stillInSentinelDir = resolveSafe(sentinel) === resolveSafe(inputs.cwd);
|
|
53828
|
+
if (stillInSentinelDir) {
|
|
53829
|
+
const metaEarly = inputs.getMetadata(inputs.sessionId);
|
|
53830
|
+
const targetEarly = typeof metaEarly?.cwd === "string" ? metaEarly.cwd : void 0;
|
|
53831
|
+
if (targetEarly !== void 0 && resolveSafe(targetEarly) === resolveSafe(sentinel)) {
|
|
53832
|
+
return { action: "none", reason: "sentinel" };
|
|
53833
|
+
}
|
|
53834
|
+
}
|
|
53835
|
+
}
|
|
53836
|
+
if (inputs.chdirEnabled === false) {
|
|
53837
|
+
return { action: "none", reason: "disabled" };
|
|
53838
|
+
}
|
|
53839
|
+
if (inputs.argv.includes("--no-cd")) {
|
|
53840
|
+
return { action: "none", reason: "disabled" };
|
|
53841
|
+
}
|
|
53842
|
+
const metadata = inputs.getMetadata(inputs.sessionId);
|
|
53843
|
+
if (!metadata) {
|
|
53844
|
+
return { action: "none", reason: "metadata-unreadable" };
|
|
53845
|
+
}
|
|
53846
|
+
const recorded = metadata.cwd;
|
|
53847
|
+
if (typeof recorded !== "string" || recorded.length === 0) {
|
|
53848
|
+
return { action: "none", reason: "no-cwd-in-metadata" };
|
|
53849
|
+
}
|
|
53850
|
+
const resolve8 = (p) => {
|
|
53851
|
+
const realpath = inputs.realpath ?? defaultRealpath;
|
|
53852
|
+
try {
|
|
53853
|
+
return realpath(p);
|
|
53854
|
+
} catch {
|
|
53855
|
+
return p;
|
|
53856
|
+
}
|
|
53857
|
+
};
|
|
53858
|
+
const here = resolve8(inputs.cwd);
|
|
53859
|
+
const target = resolve8(recorded);
|
|
53860
|
+
if (here === target) {
|
|
53861
|
+
return { action: "none", reason: "same-dir" };
|
|
53862
|
+
}
|
|
53863
|
+
const dirExists = inputs.dirExists ?? ((p) => {
|
|
53864
|
+
try {
|
|
53865
|
+
return requireFs("node:fs").statSync(p).isDirectory();
|
|
53866
|
+
} catch {
|
|
53867
|
+
return false;
|
|
53868
|
+
}
|
|
53869
|
+
});
|
|
53870
|
+
if (!dirExists(target)) {
|
|
53871
|
+
return {
|
|
53872
|
+
action: "none",
|
|
53873
|
+
reason: "missing-dir",
|
|
53874
|
+
warning: `session was recorded in ${recorded}, which does not exist; continuing in ${inputs.cwd}`
|
|
53875
|
+
};
|
|
53876
|
+
}
|
|
53877
|
+
const childArgv = buildChildArgv(inputs.argv, inputs.sessionId);
|
|
53878
|
+
const childEnv = { ...env, [RESUME_CWD_SENTINEL_ENV]: target };
|
|
53879
|
+
return {
|
|
53880
|
+
action: "restart",
|
|
53881
|
+
targetCwd: target,
|
|
53882
|
+
childArgv,
|
|
53883
|
+
childEnv,
|
|
53884
|
+
banner: `resumed session ${inputs.sessionId.slice(0, 8)}; cwd ${inputs.cwd} \u2192 ${target}`
|
|
53885
|
+
};
|
|
53886
|
+
}
|
|
53887
|
+
|
|
53888
|
+
// src/commands/session-resume-restart.ts
|
|
53889
|
+
function readResumeChdirSetting() {
|
|
53890
|
+
try {
|
|
53891
|
+
const parsed = JSON.parse(fs6.readFileSync(getSettingsPath(), "utf8"));
|
|
53892
|
+
if (!parsed || typeof parsed !== "object") return true;
|
|
53893
|
+
const session = parsed.session;
|
|
53894
|
+
if (!session || typeof session !== "object" || Array.isArray(session)) return true;
|
|
53895
|
+
if (!Object.hasOwn(session, "resume")) return true;
|
|
53896
|
+
const resume = session.resume;
|
|
53897
|
+
if (!resume || typeof resume !== "object" || Array.isArray(resume)) return true;
|
|
53898
|
+
if (!Object.hasOwn(resume, "chdir")) return true;
|
|
53899
|
+
const value = resume.chdir;
|
|
53900
|
+
return typeof value === "boolean" ? value : true;
|
|
53901
|
+
} catch {
|
|
53902
|
+
return true;
|
|
53903
|
+
}
|
|
53904
|
+
}
|
|
53905
|
+
var DROPPED_ENV_KEYS = /* @__PURE__ */ new Set();
|
|
53906
|
+
function anchorAgentDirForChild(env) {
|
|
53907
|
+
const value = env["PIE_CODING_AGENT_DIR"];
|
|
53908
|
+
if (value === void 0 || value === "" || value === "~" || value.startsWith("~/") || path6.isAbsolute(value)) {
|
|
53909
|
+
return env;
|
|
53910
|
+
}
|
|
53911
|
+
return { ...env, PIE_CODING_AGENT_DIR: path6.resolve(process.cwd(), value) };
|
|
53912
|
+
}
|
|
53913
|
+
function buildChildEnv(env) {
|
|
53914
|
+
const anchored = anchorAgentDirForChild(env);
|
|
53915
|
+
const out = {};
|
|
53916
|
+
for (const [key, value] of Object.entries(anchored)) {
|
|
53917
|
+
if (DROPPED_ENV_KEYS.has(key)) continue;
|
|
53918
|
+
out[key] = value;
|
|
53919
|
+
}
|
|
53920
|
+
return out;
|
|
53921
|
+
}
|
|
53922
|
+
function decideSessionResumeRestart(argv, sessionId, cwd) {
|
|
53923
|
+
const sessionManager = createSessionManager({ sessionsDir: getSessionsDir() });
|
|
53924
|
+
const decision = resolveResumeRestart({
|
|
53925
|
+
argv,
|
|
53926
|
+
cwd,
|
|
53927
|
+
sessionId,
|
|
53928
|
+
getMetadata: (id) => sessionManager.getMetadata(id),
|
|
53929
|
+
chdirEnabled: readResumeChdirSetting(),
|
|
53930
|
+
env: process.env
|
|
53931
|
+
});
|
|
53932
|
+
return decision.action === "none" && !decision.warning ? null : decision;
|
|
53933
|
+
}
|
|
53934
|
+
function emitOsc7Cwd(cwd) {
|
|
53935
|
+
const slashed = cwd.replace(/\\/g, "/");
|
|
53936
|
+
const prefix = slashed.startsWith("/") ? "" : "/";
|
|
53937
|
+
const encoded = `file://${prefix}${encodeURI(slashed).replace(/#/g, "%23").replace(/\?/g, "%3F")}`;
|
|
53938
|
+
process.stderr.write(`\x1B]7;${encoded}\x07`);
|
|
53939
|
+
}
|
|
53940
|
+
async function performResumeRestart(decision, onSpawnFailure) {
|
|
53941
|
+
let announced = false;
|
|
53942
|
+
const announce = () => {
|
|
53943
|
+
if (announced) return;
|
|
53944
|
+
announced = true;
|
|
53945
|
+
console.error(decision.banner);
|
|
53946
|
+
emitOsc7Cwd(decision.targetCwd);
|
|
53947
|
+
};
|
|
53948
|
+
return await new Promise((resolve8) => {
|
|
53949
|
+
const child = spawn(process.execPath, [...process.execArgv, process.argv[1] ?? ".", ...decision.childArgv], {
|
|
53950
|
+
cwd: decision.targetCwd,
|
|
53951
|
+
stdio: "inherit",
|
|
53952
|
+
env: buildChildEnv(decision.childEnv)
|
|
53953
|
+
});
|
|
53954
|
+
child.on("spawn", () => announce());
|
|
53955
|
+
child.on("error", (error) => {
|
|
53956
|
+
onSpawnFailure(`could not restart in ${decision.targetCwd} (${error.message}); continuing in ${process.cwd()}`);
|
|
53957
|
+
resolve8(null);
|
|
53958
|
+
});
|
|
53959
|
+
child.on("exit", (code, signal) => {
|
|
53960
|
+
if (signal) {
|
|
53961
|
+
process.kill(process.pid, signal);
|
|
53962
|
+
return;
|
|
53963
|
+
}
|
|
53964
|
+
resolve8(code ?? 0);
|
|
53965
|
+
});
|
|
53966
|
+
});
|
|
53967
|
+
}
|
|
53968
|
+
|
|
55416
53969
|
// src/commands/sessions.ts
|
|
55417
53970
|
import fs8 from "node:fs";
|
|
55418
53971
|
|
|
@@ -56305,7 +54858,7 @@ function isRecord2(value) {
|
|
|
56305
54858
|
import * as fs9 from "node:fs";
|
|
56306
54859
|
import * as os2 from "os";
|
|
56307
54860
|
import * as path8 from "path";
|
|
56308
|
-
import { pathToFileURL } from "node:url";
|
|
54861
|
+
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
56309
54862
|
|
|
56310
54863
|
// src/command-tree.ts
|
|
56311
54864
|
var CommandTree = class {
|
|
@@ -56683,7 +55236,7 @@ function normalizeExtensionImportPath(extensionPath) {
|
|
|
56683
55236
|
return `file:///${extensionPath.replace(/\\/g, "/")}`;
|
|
56684
55237
|
}
|
|
56685
55238
|
if (path8.isAbsolute(extensionPath)) {
|
|
56686
|
-
return
|
|
55239
|
+
return pathToFileURL2(extensionPath).href;
|
|
56687
55240
|
}
|
|
56688
55241
|
return extensionPath;
|
|
56689
55242
|
}
|
|
@@ -56739,6 +55292,7 @@ function discoverExtensionsInDir(dir, source) {
|
|
|
56739
55292
|
let packageIdentity;
|
|
56740
55293
|
let packageDescription;
|
|
56741
55294
|
let packageMainPath;
|
|
55295
|
+
let packageDefaultEnablement;
|
|
56742
55296
|
if (fs9.existsSync(packageJsonPath)) {
|
|
56743
55297
|
try {
|
|
56744
55298
|
const pkg = JSON.parse(fs9.readFileSync(packageJsonPath, "utf-8"));
|
|
@@ -56749,6 +55303,7 @@ function discoverExtensionsInDir(dir, source) {
|
|
|
56749
55303
|
fallbackName: entry.name
|
|
56750
55304
|
});
|
|
56751
55305
|
packageDescription = typeof pkg.description === "string" ? pkg.description : void 0;
|
|
55306
|
+
if (manifest?.defaultEnablement === false) packageDefaultEnablement = false;
|
|
56752
55307
|
if (typeof manifest?.main === "string" && manifest.main.trim().length > 0) {
|
|
56753
55308
|
const candidate = path8.resolve(entryPath, manifest.main);
|
|
56754
55309
|
if (fs9.existsSync(candidate)) {
|
|
@@ -56763,7 +55318,8 @@ function discoverExtensionsInDir(dir, source) {
|
|
|
56763
55318
|
entryPath: packageMainPath,
|
|
56764
55319
|
source,
|
|
56765
55320
|
identity: packageIdentity,
|
|
56766
|
-
description: packageDescription
|
|
55321
|
+
description: packageDescription,
|
|
55322
|
+
defaultEnablement: packageDefaultEnablement
|
|
56767
55323
|
});
|
|
56768
55324
|
continue;
|
|
56769
55325
|
}
|
|
@@ -56773,7 +55329,8 @@ function discoverExtensionsInDir(dir, source) {
|
|
|
56773
55329
|
entryPath: indexCjs,
|
|
56774
55330
|
source,
|
|
56775
55331
|
identity: packageIdentity ?? resolveExtensionIdentity({ fallbackName: entry.name }),
|
|
56776
|
-
description: packageDescription
|
|
55332
|
+
description: packageDescription,
|
|
55333
|
+
defaultEnablement: packageDefaultEnablement
|
|
56777
55334
|
});
|
|
56778
55335
|
continue;
|
|
56779
55336
|
}
|
|
@@ -56783,7 +55340,8 @@ function discoverExtensionsInDir(dir, source) {
|
|
|
56783
55340
|
entryPath: indexJs,
|
|
56784
55341
|
source,
|
|
56785
55342
|
identity: packageIdentity ?? resolveExtensionIdentity({ fallbackName: entry.name }),
|
|
56786
|
-
description: packageDescription
|
|
55343
|
+
description: packageDescription,
|
|
55344
|
+
defaultEnablement: packageDefaultEnablement
|
|
56787
55345
|
});
|
|
56788
55346
|
continue;
|
|
56789
55347
|
}
|
|
@@ -56793,7 +55351,8 @@ function discoverExtensionsInDir(dir, source) {
|
|
|
56793
55351
|
entryPath: indexTs,
|
|
56794
55352
|
source,
|
|
56795
55353
|
identity: packageIdentity ?? resolveExtensionIdentity({ fallbackName: entry.name }),
|
|
56796
|
-
description: packageDescription
|
|
55354
|
+
description: packageDescription,
|
|
55355
|
+
defaultEnablement: packageDefaultEnablement
|
|
56797
55356
|
});
|
|
56798
55357
|
continue;
|
|
56799
55358
|
}
|
|
@@ -56833,13 +55392,22 @@ function collectDiscoveredExtensions(configuredPaths, cwd, options) {
|
|
|
56833
55392
|
}
|
|
56834
55393
|
function discoverAllExtensions(configuredPaths, cwd, options) {
|
|
56835
55394
|
const { discovered } = collectDiscoveredExtensions(configuredPaths, cwd, options);
|
|
56836
|
-
const layers = options?.enablementLayers;
|
|
56837
|
-
|
|
55395
|
+
const layers = options?.enablementLayers ?? [];
|
|
55396
|
+
const seen = /* @__PURE__ */ new Set();
|
|
55397
|
+
const winners = [];
|
|
55398
|
+
for (const item of discovered) {
|
|
55399
|
+
if (item.identity) {
|
|
55400
|
+
if (seen.has(item.identity)) continue;
|
|
55401
|
+
seen.add(item.identity);
|
|
55402
|
+
}
|
|
55403
|
+
winners.push(item);
|
|
55404
|
+
}
|
|
55405
|
+
return winners.map((item) => ({
|
|
56838
55406
|
entryPath: item.entryPath,
|
|
56839
55407
|
source: item.source,
|
|
56840
55408
|
identity: item.identity,
|
|
56841
55409
|
description: item.description,
|
|
56842
|
-
enabled:
|
|
55410
|
+
enabled: item.identity ? isExtensionEnabled(item.identity, ...layers, manifestDefaultLayer(item.defaultEnablement)) : true
|
|
56843
55411
|
}));
|
|
56844
55412
|
}
|
|
56845
55413
|
async function loadExtensions(configuredPaths, cwd, uiContext, abortFn, isIdleFn, hasUI = true, actions, options) {
|
|
@@ -56875,14 +55443,22 @@ async function loadExtensions(configuredPaths, cwd, uiContext, abortFn, isIdleFn
|
|
|
56875
55443
|
options
|
|
56876
55444
|
);
|
|
56877
55445
|
errors.push(...discoveryErrors);
|
|
56878
|
-
const layers = options?.enablementLayers;
|
|
55446
|
+
const layers = options?.enablementLayers ?? [];
|
|
56879
55447
|
for (const discovered of allDiscovered) {
|
|
56880
|
-
if (layers && discovered.identity && !isExtensionEnabled(discovered.identity, ...layers)) {
|
|
56881
|
-
continue;
|
|
56882
|
-
}
|
|
56883
55448
|
addDiscovered(discovered);
|
|
56884
55449
|
}
|
|
56885
|
-
|
|
55450
|
+
const enabledPaths = /* @__PURE__ */ new Set();
|
|
55451
|
+
for (const [identity, entryPath] of pathByIdentity) {
|
|
55452
|
+
if (isExtensionEnabled(identity, ...layers, manifestDefaultLayer(discoveredByPath.get(entryPath)?.defaultEnablement))) {
|
|
55453
|
+
enabledPaths.add(entryPath);
|
|
55454
|
+
}
|
|
55455
|
+
}
|
|
55456
|
+
const pathsToLoad = allPaths.filter((p) => {
|
|
55457
|
+
const discovered = discoveredByPath.get(p);
|
|
55458
|
+
if (!discovered?.identity) return true;
|
|
55459
|
+
return enabledPaths.has(pathByIdentity.get(discovered.identity));
|
|
55460
|
+
});
|
|
55461
|
+
for (const extPath of pathsToLoad) {
|
|
56886
55462
|
const { extension, error } = await loadExtension(
|
|
56887
55463
|
extPath,
|
|
56888
55464
|
cwd,
|
|
@@ -64147,7 +62723,7 @@ import * as fs11 from "node:fs";
|
|
|
64147
62723
|
import koffi from "koffi";
|
|
64148
62724
|
|
|
64149
62725
|
// ../../packages/tui/src/osc-5522.ts
|
|
64150
|
-
import { randomBytes
|
|
62726
|
+
import { randomBytes } from "node:crypto";
|
|
64151
62727
|
var OSC = "\x1B]";
|
|
64152
62728
|
var ST = "\x1B\\";
|
|
64153
62729
|
var READ_TIMEOUT_MS = 8e3;
|
|
@@ -64269,14 +62845,14 @@ var Osc5522Client = class {
|
|
|
64269
62845
|
*/
|
|
64270
62846
|
async querySupport(timeoutMs = SUPPORT_TIMEOUT_MS) {
|
|
64271
62847
|
if (this.supportMode !== "unknown") return this.supportMode === "supported";
|
|
64272
|
-
return new Promise((
|
|
62848
|
+
return new Promise((resolve8) => {
|
|
64273
62849
|
let settled = false;
|
|
64274
62850
|
const settle = (supported) => {
|
|
64275
62851
|
if (settled) return;
|
|
64276
62852
|
settled = true;
|
|
64277
62853
|
clearTimeout(timer);
|
|
64278
62854
|
this.pendingSupportResolve = void 0;
|
|
64279
|
-
|
|
62855
|
+
resolve8(supported);
|
|
64280
62856
|
};
|
|
64281
62857
|
const timer = setTimeout(() => settle(false), timeoutMs);
|
|
64282
62858
|
this.pendingSupportResolve = settle;
|
|
@@ -64294,14 +62870,14 @@ var Osc5522Client = class {
|
|
|
64294
62870
|
return { ok: false, kind: "busy", message: "Another OSC 5522 read is already in flight." };
|
|
64295
62871
|
}
|
|
64296
62872
|
const session = {
|
|
64297
|
-
id: `pie-${
|
|
62873
|
+
id: `pie-${randomBytes(8).toString("hex")}`,
|
|
64298
62874
|
resolve: void 0,
|
|
64299
62875
|
timer: void 0,
|
|
64300
62876
|
chunks: [],
|
|
64301
62877
|
totalBytes: 0
|
|
64302
62878
|
};
|
|
64303
|
-
const promise = new Promise((
|
|
64304
|
-
session.resolve =
|
|
62879
|
+
const promise = new Promise((resolve8) => {
|
|
62880
|
+
session.resolve = resolve8;
|
|
64305
62881
|
});
|
|
64306
62882
|
session.timer = setTimeout(() => {
|
|
64307
62883
|
this.finishFor(session, { ok: false, kind: "timeout", message: "Terminal did not respond to the clipboard read in time." });
|
|
@@ -64464,7 +63040,7 @@ var ProcessTerminal = class {
|
|
|
64464
63040
|
const timeLeft = endTime - now;
|
|
64465
63041
|
if (timeLeft <= 0) break;
|
|
64466
63042
|
if (now - lastDataTime >= idleMs) break;
|
|
64467
|
-
await new Promise((
|
|
63043
|
+
await new Promise((resolve8) => setTimeout(resolve8, Math.min(idleMs, timeLeft)));
|
|
64468
63044
|
}
|
|
64469
63045
|
} finally {
|
|
64470
63046
|
process.stdin.removeListener("data", onData);
|
|
@@ -65395,8 +63971,8 @@ function restoreInteractiveSessionState(options) {
|
|
|
65395
63971
|
}
|
|
65396
63972
|
|
|
65397
63973
|
// src/keybindings.ts
|
|
65398
|
-
import { existsSync as
|
|
65399
|
-
import { join as
|
|
63974
|
+
import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
|
|
63975
|
+
import { join as join7 } from "path";
|
|
65400
63976
|
var DEFAULT_APP_KEYBINDINGS = {
|
|
65401
63977
|
interrupt: "escape",
|
|
65402
63978
|
clear: "ctrl+c",
|
|
@@ -65411,7 +63987,7 @@ var DEFAULT_APP_KEYBINDINGS = {
|
|
|
65411
63987
|
toggleYolo: ["ctrl+x", "alt+o"],
|
|
65412
63988
|
toggleSessionNamedFilter: "ctrl+n",
|
|
65413
63989
|
externalEditor: "ctrl+g",
|
|
65414
|
-
steer: "alt+enter",
|
|
63990
|
+
steer: ["alt+enter", "ctrl+\\"],
|
|
65415
63991
|
followUp: [],
|
|
65416
63992
|
dequeue: ["alt+up", "ctrl+shift+up"],
|
|
65417
63993
|
pasteImage: ["ctrl+v", "alt+v", "super+v"],
|
|
@@ -65462,7 +64038,7 @@ var KeybindingsManager = class _KeybindingsManager {
|
|
|
65462
64038
|
* Create from config file and set up editor keybindings.
|
|
65463
64039
|
*/
|
|
65464
64040
|
static create(agentDir = getAgentDir()) {
|
|
65465
|
-
const configPath =
|
|
64041
|
+
const configPath = join7(agentDir, "keybindings.json");
|
|
65466
64042
|
const config = _KeybindingsManager.loadFromFile(configPath);
|
|
65467
64043
|
const manager = new _KeybindingsManager(config);
|
|
65468
64044
|
const editorConfig = {};
|
|
@@ -65481,7 +64057,7 @@ var KeybindingsManager = class _KeybindingsManager {
|
|
|
65481
64057
|
return new _KeybindingsManager(config);
|
|
65482
64058
|
}
|
|
65483
64059
|
static loadFromFile(path34) {
|
|
65484
|
-
if (!
|
|
64060
|
+
if (!existsSync6(path34)) return {};
|
|
65485
64061
|
try {
|
|
65486
64062
|
return JSON.parse(readFileSync7(path34, "utf-8"));
|
|
65487
64063
|
} catch {
|
|
@@ -66889,8 +65465,8 @@ function parseSkillDescription(content) {
|
|
|
66889
65465
|
}
|
|
66890
65466
|
var USER_CONTROLLED_SOURCES = /* @__PURE__ */ new Set(["user-agents", "user"]);
|
|
66891
65467
|
function pathIsInside(child, parent) {
|
|
66892
|
-
const
|
|
66893
|
-
return
|
|
65468
|
+
const relative2 = path12.relative(parent, child);
|
|
65469
|
+
return relative2 !== "" && !relative2.startsWith(`..${path12.sep}`) && relative2 !== ".." && !path12.isAbsolute(relative2);
|
|
66894
65470
|
}
|
|
66895
65471
|
function resolveSkillSymlink(fullPath, dir, source) {
|
|
66896
65472
|
let target;
|
|
@@ -68266,11 +66842,11 @@ var FileCache = class _FileCache {
|
|
|
68266
66842
|
// Hash Computation
|
|
68267
66843
|
// ============================================================================
|
|
68268
66844
|
async computeHash(filePath) {
|
|
68269
|
-
return new Promise((
|
|
66845
|
+
return new Promise((resolve8, reject) => {
|
|
68270
66846
|
const hash = crypto.createHash("sha256");
|
|
68271
66847
|
const stream = fs18.createReadStream(filePath);
|
|
68272
66848
|
stream.on("data", (chunk) => hash.update(chunk));
|
|
68273
|
-
stream.on("end", () =>
|
|
66849
|
+
stream.on("end", () => resolve8(hash.digest("hex")));
|
|
68274
66850
|
stream.on("error", reject);
|
|
68275
66851
|
});
|
|
68276
66852
|
}
|
|
@@ -68982,7 +67558,7 @@ var SessionFileManager = class {
|
|
|
68982
67558
|
// src/files/ffmpeg-processor.ts
|
|
68983
67559
|
import * as fs20 from "node:fs";
|
|
68984
67560
|
import * as path19 from "node:path";
|
|
68985
|
-
import { spawn } from "node:child_process";
|
|
67561
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
68986
67562
|
var FFmpegProcessor = class {
|
|
68987
67563
|
ffmpegPath = "ffmpeg";
|
|
68988
67564
|
ffprobePath = "ffprobe";
|
|
@@ -68994,17 +67570,17 @@ var FFmpegProcessor = class {
|
|
|
68994
67570
|
// Detection
|
|
68995
67571
|
// ============================================================================
|
|
68996
67572
|
async checkAvailability() {
|
|
68997
|
-
return new Promise((
|
|
68998
|
-
const proc =
|
|
68999
|
-
proc.on("error", () =>
|
|
69000
|
-
proc.on("exit", (code) =>
|
|
67573
|
+
return new Promise((resolve8) => {
|
|
67574
|
+
const proc = spawn2(this.ffmpegPath, ["-version"]);
|
|
67575
|
+
proc.on("error", () => resolve8(false));
|
|
67576
|
+
proc.on("exit", (code) => resolve8(code === 0));
|
|
69001
67577
|
});
|
|
69002
67578
|
}
|
|
69003
67579
|
// ============================================================================
|
|
69004
67580
|
// Video Analysis
|
|
69005
67581
|
// ============================================================================
|
|
69006
67582
|
async analyzeVideo(videoPath) {
|
|
69007
|
-
return new Promise((
|
|
67583
|
+
return new Promise((resolve8, reject) => {
|
|
69008
67584
|
const args = [
|
|
69009
67585
|
"-v",
|
|
69010
67586
|
"error",
|
|
@@ -69016,7 +67592,7 @@ var FFmpegProcessor = class {
|
|
|
69016
67592
|
"json",
|
|
69017
67593
|
videoPath
|
|
69018
67594
|
];
|
|
69019
|
-
const proc =
|
|
67595
|
+
const proc = spawn2(this.ffprobePath, args);
|
|
69020
67596
|
let stdout = "";
|
|
69021
67597
|
let stderr = "";
|
|
69022
67598
|
proc.stdout.on("data", (data) => stdout += data);
|
|
@@ -69033,7 +67609,7 @@ var FFmpegProcessor = class {
|
|
|
69033
67609
|
}
|
|
69034
67610
|
try {
|
|
69035
67611
|
const info = this.parseProbeOutput(stdout, videoPath);
|
|
69036
|
-
|
|
67612
|
+
resolve8(info);
|
|
69037
67613
|
} catch (err) {
|
|
69038
67614
|
reject(err);
|
|
69039
67615
|
}
|
|
@@ -69228,8 +67804,8 @@ var FFmpegProcessor = class {
|
|
|
69228
67804
|
// FFmpeg Execution
|
|
69229
67805
|
// ============================================================================
|
|
69230
67806
|
runFFmpeg(args) {
|
|
69231
|
-
return new Promise((
|
|
69232
|
-
const proc =
|
|
67807
|
+
return new Promise((resolve8, reject) => {
|
|
67808
|
+
const proc = spawn2(this.ffmpegPath, args);
|
|
69233
67809
|
let stderr = "";
|
|
69234
67810
|
proc.stderr.on("data", (data) => {
|
|
69235
67811
|
stderr += data;
|
|
@@ -69243,7 +67819,7 @@ var FFmpegProcessor = class {
|
|
|
69243
67819
|
)
|
|
69244
67820
|
);
|
|
69245
67821
|
} else {
|
|
69246
|
-
|
|
67822
|
+
resolve8();
|
|
69247
67823
|
}
|
|
69248
67824
|
});
|
|
69249
67825
|
proc.on("error", (err) => {
|
|
@@ -69260,13 +67836,13 @@ var FFmpegProcessor = class {
|
|
|
69260
67836
|
// Progress Monitoring (for future use)
|
|
69261
67837
|
// ============================================================================
|
|
69262
67838
|
async runWithProgress(args, onProgress) {
|
|
69263
|
-
return new Promise((
|
|
67839
|
+
return new Promise((resolve8, reject) => {
|
|
69264
67840
|
const progressArgs = [
|
|
69265
67841
|
...args,
|
|
69266
67842
|
"-progress",
|
|
69267
67843
|
"pipe:1"
|
|
69268
67844
|
];
|
|
69269
|
-
const proc =
|
|
67845
|
+
const proc = spawn2(this.ffmpegPath, progressArgs);
|
|
69270
67846
|
let stderr = "";
|
|
69271
67847
|
let progressData = "";
|
|
69272
67848
|
proc.stdout.on("data", (data) => {
|
|
@@ -69290,7 +67866,7 @@ var FFmpegProcessor = class {
|
|
|
69290
67866
|
)
|
|
69291
67867
|
);
|
|
69292
67868
|
} else {
|
|
69293
|
-
|
|
67869
|
+
resolve8();
|
|
69294
67870
|
}
|
|
69295
67871
|
});
|
|
69296
67872
|
});
|
|
@@ -70285,7 +68861,7 @@ async function waitForReady(params) {
|
|
|
70285
68861
|
if (status.status === "error" || status.status === "expired") {
|
|
70286
68862
|
throw new Error(`Uploaded file is not ready: ${status.status}${status.error ? ` (${status.error})` : ""}`);
|
|
70287
68863
|
}
|
|
70288
|
-
await new Promise((
|
|
68864
|
+
await new Promise((resolve8) => setTimeout(resolve8, 1500));
|
|
70289
68865
|
}
|
|
70290
68866
|
throw new Error("Timed out waiting for uploaded file to become ready");
|
|
70291
68867
|
}
|
|
@@ -70382,8 +68958,8 @@ function createIsolatedRegexSession(pattern, ignoreCase) {
|
|
|
70382
68958
|
let initError;
|
|
70383
68959
|
let readyResolve;
|
|
70384
68960
|
let readyReject;
|
|
70385
|
-
const ready = new Promise((
|
|
70386
|
-
readyResolve =
|
|
68961
|
+
const ready = new Promise((resolve8, reject) => {
|
|
68962
|
+
readyResolve = resolve8;
|
|
70387
68963
|
readyReject = reject;
|
|
70388
68964
|
});
|
|
70389
68965
|
void ready.catch(() => void 0);
|
|
@@ -70405,7 +68981,7 @@ function createIsolatedRegexSession(pattern, ignoreCase) {
|
|
|
70405
68981
|
if (initError) throw initError;
|
|
70406
68982
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
70407
68983
|
const id = nextId++;
|
|
70408
|
-
return new Promise((
|
|
68984
|
+
return new Promise((resolve8, reject) => {
|
|
70409
68985
|
let settled = false;
|
|
70410
68986
|
const finish = (error, matches) => {
|
|
70411
68987
|
if (settled) return;
|
|
@@ -70415,7 +68991,7 @@ function createIsolatedRegexSession(pattern, ignoreCase) {
|
|
|
70415
68991
|
worker.off("message", onMessage);
|
|
70416
68992
|
worker.off("error", onWorkerError);
|
|
70417
68993
|
if (error) reject(error);
|
|
70418
|
-
else
|
|
68994
|
+
else resolve8(matches ?? []);
|
|
70419
68995
|
};
|
|
70420
68996
|
const terminate = (error) => {
|
|
70421
68997
|
disposed = true;
|
|
@@ -70937,7 +69513,7 @@ var SessionTraceWriter = class extends SessionTraceSnapshotWriter {
|
|
|
70937
69513
|
};
|
|
70938
69514
|
|
|
70939
69515
|
// src/runtime/context-signals.ts
|
|
70940
|
-
import { createHash as
|
|
69516
|
+
import { createHash as createHash3 } from "crypto";
|
|
70941
69517
|
function applyContextSignalsToFooter(target) {
|
|
70942
69518
|
if (!target.agent?.state) return;
|
|
70943
69519
|
const state = target.agent.state;
|
|
@@ -70959,7 +69535,7 @@ function applyContextSignalsToFooter(target) {
|
|
|
70959
69535
|
});
|
|
70960
69536
|
}
|
|
70961
69537
|
function computePromptPrefixHash(systemPrompt, tools, route) {
|
|
70962
|
-
return
|
|
69538
|
+
return createHash3("sha256").update(
|
|
70963
69539
|
JSON.stringify({
|
|
70964
69540
|
systemPrompt,
|
|
70965
69541
|
tools: tools.map((tool) => ({
|
|
@@ -70975,20 +69551,20 @@ function calculateCumulativeCacheHitRate(messages, recentTurns) {
|
|
|
70975
69551
|
const usages = [];
|
|
70976
69552
|
for (const message of messages) {
|
|
70977
69553
|
if (message.role !== "assistant") continue;
|
|
70978
|
-
const
|
|
70979
|
-
if (!
|
|
70980
|
-
usages.push(
|
|
69554
|
+
const usage2 = message.usage;
|
|
69555
|
+
if (!usage2) continue;
|
|
69556
|
+
usages.push(usage2);
|
|
70981
69557
|
}
|
|
70982
69558
|
const windowed = recentTurns !== void 0 && usages.length > recentTurns ? usages.slice(-recentTurns) : usages;
|
|
70983
69559
|
let input = 0;
|
|
70984
69560
|
let cacheRead = 0;
|
|
70985
69561
|
let cacheWrite = 0;
|
|
70986
69562
|
let cacheWriteLong = 0;
|
|
70987
|
-
for (const
|
|
70988
|
-
input +=
|
|
70989
|
-
cacheRead +=
|
|
70990
|
-
cacheWrite +=
|
|
70991
|
-
cacheWriteLong +=
|
|
69563
|
+
for (const usage2 of windowed) {
|
|
69564
|
+
input += usage2.input;
|
|
69565
|
+
cacheRead += usage2.cacheRead;
|
|
69566
|
+
cacheWrite += usage2.cacheWrite;
|
|
69567
|
+
cacheWriteLong += usage2.cacheWriteLong ?? 0;
|
|
70992
69568
|
}
|
|
70993
69569
|
const base = input + cacheRead + cacheWrite + cacheWriteLong;
|
|
70994
69570
|
return base > 0 ? cacheRead / base : null;
|
|
@@ -71115,10 +69691,10 @@ function formatSessionCwdTag(sessionCwd, currentCwd, homeDir) {
|
|
|
71115
69691
|
const normalizedSessionCwd = pathApi.normalize(sessionCwd);
|
|
71116
69692
|
if (homeDir && getPathFlavor(homeDir, sessionCwd) === sessionFlavor) {
|
|
71117
69693
|
const normalizedHome = pathApi.normalize(homeDir);
|
|
71118
|
-
const
|
|
71119
|
-
const outsideHome =
|
|
69694
|
+
const relative2 = pathApi.relative(normalizedHome, normalizedSessionCwd);
|
|
69695
|
+
const outsideHome = relative2 === ".." || relative2.startsWith(`..${pathApi.sep}`) || pathApi.isAbsolute(relative2);
|
|
71120
69696
|
if (!outsideHome) {
|
|
71121
|
-
return
|
|
69697
|
+
return relative2 ? `~${pathApi.sep}${relative2}` : "~";
|
|
71122
69698
|
}
|
|
71123
69699
|
}
|
|
71124
69700
|
return normalizedSessionCwd;
|
|
@@ -73218,15 +71794,15 @@ function calculateSessionUsageTotals(messages) {
|
|
|
73218
71794
|
let costEstimated = false;
|
|
73219
71795
|
for (const message of messages) {
|
|
73220
71796
|
if (message.role !== "assistant") continue;
|
|
73221
|
-
const
|
|
73222
|
-
if (!
|
|
73223
|
-
input +=
|
|
73224
|
-
output +=
|
|
73225
|
-
cacheRead +=
|
|
73226
|
-
cacheWrite +=
|
|
73227
|
-
cacheWriteLong +=
|
|
73228
|
-
cost +=
|
|
73229
|
-
if (
|
|
71797
|
+
const usage2 = message.usage;
|
|
71798
|
+
if (!usage2) continue;
|
|
71799
|
+
input += usage2.input;
|
|
71800
|
+
output += usage2.output;
|
|
71801
|
+
cacheRead += usage2.cacheRead;
|
|
71802
|
+
cacheWrite += usage2.cacheWrite;
|
|
71803
|
+
cacheWriteLong += usage2.cacheWriteLong ?? 0;
|
|
71804
|
+
cost += usage2.cost?.total ?? 0;
|
|
71805
|
+
if (usage2.cost?.cacheWriteLongEstimated === true) costEstimated = true;
|
|
73230
71806
|
}
|
|
73231
71807
|
return { input, output, cacheRead, cacheWrite, cacheWriteLong, cacheWriteTotal: cacheWrite + cacheWriteLong, cost, costEstimated };
|
|
73232
71808
|
}
|
|
@@ -73311,6 +71887,7 @@ function normalizeSessionTitle(raw) {
|
|
|
73311
71887
|
}
|
|
73312
71888
|
|
|
73313
71889
|
// src/commands/interactive-session-commands.ts
|
|
71890
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
73314
71891
|
function textFromContentBlock(block) {
|
|
73315
71892
|
if (!block || typeof block !== "object" || !("text" in block)) return "";
|
|
73316
71893
|
const text = block.text;
|
|
@@ -73328,6 +71905,54 @@ async function handleResumeCommand(host) {
|
|
|
73328
71905
|
const selector = new SessionSelectorComponent(sessions, {
|
|
73329
71906
|
onSelect: async (sessionId) => {
|
|
73330
71907
|
done();
|
|
71908
|
+
const decision = decideSessionResumeRestart(process.argv.slice(2), sessionId, process.cwd());
|
|
71909
|
+
if (decision && decision.action !== "restart" && decision.warning) {
|
|
71910
|
+
host.showWarning(decision.warning);
|
|
71911
|
+
}
|
|
71912
|
+
if (decision && decision.action === "restart") {
|
|
71913
|
+
const beforeSwitch = await host.extensionRunner?.emitSessionBeforeSwitch({
|
|
71914
|
+
type: "session:before_switch",
|
|
71915
|
+
reason: "resume",
|
|
71916
|
+
targetSessionId: sessionId
|
|
71917
|
+
});
|
|
71918
|
+
if (beforeSwitch?.cancel) {
|
|
71919
|
+
host.showStatus("Session switch cancelled by an extension");
|
|
71920
|
+
return;
|
|
71921
|
+
}
|
|
71922
|
+
const scheduled = scheduleResumeRestartAfterExit(() => {
|
|
71923
|
+
let announced = false;
|
|
71924
|
+
const announce = () => {
|
|
71925
|
+
if (announced) return;
|
|
71926
|
+
announced = true;
|
|
71927
|
+
console.error(decision.banner);
|
|
71928
|
+
emitOsc7Cwd(decision.targetCwd);
|
|
71929
|
+
};
|
|
71930
|
+
const child = spawn3(process.execPath, [...process.execArgv, process.argv[1] ?? ".", ...decision.childArgv], {
|
|
71931
|
+
cwd: decision.targetCwd,
|
|
71932
|
+
stdio: "inherit",
|
|
71933
|
+
env: buildChildEnv(decision.childEnv)
|
|
71934
|
+
});
|
|
71935
|
+
child.on("spawn", () => announce());
|
|
71936
|
+
child.on("exit", (code, signal) => {
|
|
71937
|
+
if (signal) {
|
|
71938
|
+
process.kill(process.pid, signal);
|
|
71939
|
+
return;
|
|
71940
|
+
}
|
|
71941
|
+
process.exit(code ?? 0);
|
|
71942
|
+
});
|
|
71943
|
+
child.on("error", (error) => {
|
|
71944
|
+
console.error(`[resume] could not restart in ${decision.targetCwd} (${error.message}).`);
|
|
71945
|
+
console.error(`[resume] the session is intact \u2014 restart manually with: pie --session-id ${sessionId}`);
|
|
71946
|
+
process.exit(1);
|
|
71947
|
+
});
|
|
71948
|
+
});
|
|
71949
|
+
if (scheduled) {
|
|
71950
|
+
host.cleanupAndExit();
|
|
71951
|
+
return;
|
|
71952
|
+
}
|
|
71953
|
+
host.showStatus("Another session switch is already in progress");
|
|
71954
|
+
return;
|
|
71955
|
+
}
|
|
73331
71956
|
await host.loadSession(sessionId);
|
|
73332
71957
|
},
|
|
73333
71958
|
onCancel: () => {
|
|
@@ -74284,10 +72909,10 @@ var shutdowns = /* @__PURE__ */ new WeakMap();
|
|
|
74284
72909
|
function shutdownInteractiveHost(host, idleTimeoutMs = 5e3) {
|
|
74285
72910
|
const existing = shutdowns.get(host);
|
|
74286
72911
|
if (existing) return existing;
|
|
74287
|
-
let
|
|
72912
|
+
let resolve8;
|
|
74288
72913
|
let reject;
|
|
74289
72914
|
const shutdown = new Promise((done, fail) => {
|
|
74290
|
-
|
|
72915
|
+
resolve8 = done;
|
|
74291
72916
|
reject = fail;
|
|
74292
72917
|
});
|
|
74293
72918
|
shutdowns.set(host, shutdown);
|
|
@@ -74335,7 +72960,7 @@ function shutdownInteractiveHost(host, idleTimeoutMs = 5e3) {
|
|
|
74335
72960
|
errors.push(error);
|
|
74336
72961
|
}
|
|
74337
72962
|
if (errors.length) throw new AggregateError(errors, "Interactive shutdown failed.");
|
|
74338
|
-
})().then(
|
|
72963
|
+
})().then(resolve8, reject);
|
|
74339
72964
|
return shutdown;
|
|
74340
72965
|
}
|
|
74341
72966
|
|
|
@@ -74976,7 +73601,7 @@ function assistantDisplayBlocks(content) {
|
|
|
74976
73601
|
}
|
|
74977
73602
|
|
|
74978
73603
|
// src/commands/interactive-debug-commands.ts
|
|
74979
|
-
import { createHash as
|
|
73604
|
+
import { createHash as createHash4 } from "crypto";
|
|
74980
73605
|
function errorMessage(error) {
|
|
74981
73606
|
return error instanceof Error ? error.message : String(error);
|
|
74982
73607
|
}
|
|
@@ -75014,7 +73639,7 @@ async function handleCacheTest(host) {
|
|
|
75014
73639
|
timestamp: fixedTimestamp
|
|
75015
73640
|
}
|
|
75016
73641
|
];
|
|
75017
|
-
const prefixHash =
|
|
73642
|
+
const prefixHash = createHash4("sha256").update(
|
|
75018
73643
|
JSON.stringify({
|
|
75019
73644
|
systemPrompt: stablePrefix,
|
|
75020
73645
|
tools: toolDefs.map((tool) => ({
|
|
@@ -75036,7 +73661,7 @@ async function handleCacheTest(host) {
|
|
|
75036
73661
|
sessionId: testSessionId,
|
|
75037
73662
|
maxTokens: Math.min(model.maxTokens, 512)
|
|
75038
73663
|
};
|
|
75039
|
-
const summarizeUsage = (
|
|
73664
|
+
const summarizeUsage = (usage2) => `Input: ${usage2.input}, Output: ${usage2.output}, Cache read: ${usage2.cacheRead}, Cache write: ${usage2.cacheWrite}`;
|
|
75040
73665
|
const reasonIfNoHit = (() => {
|
|
75041
73666
|
switch (cacheCapability.mode) {
|
|
75042
73667
|
case "none":
|
|
@@ -75064,7 +73689,7 @@ async function handleCacheTest(host) {
|
|
|
75064
73689
|
host.chatContainer.addChild(new Text(theme.fg("dim", ` ${summarizeUsage(result1.usage)}`), 1, 0));
|
|
75065
73690
|
host.chatContainer.addChild(new Text(theme.fg("dim", " Waiting 2s before replaying identical request..."), 1, 0));
|
|
75066
73691
|
host.ui.requestRender();
|
|
75067
|
-
await new Promise((
|
|
73692
|
+
await new Promise((resolve8) => setTimeout(resolve8, 2e3));
|
|
75068
73693
|
host.chatContainer.addChild(new Text(theme.fg("accent", "Request 2/2: replaying identical request..."), 1, 0));
|
|
75069
73694
|
host.ui.requestRender();
|
|
75070
73695
|
result2 = await completeSimple(model, context, options);
|
|
@@ -76187,10 +74812,10 @@ ${summary}`.slice(0, MAX_ENTRY_BODY_CHARS) || null;
|
|
|
76187
74812
|
}
|
|
76188
74813
|
if (message.role === "assistant") {
|
|
76189
74814
|
const parts = ["# assistant message"];
|
|
76190
|
-
const
|
|
76191
|
-
if (
|
|
74815
|
+
const usage2 = message.usage;
|
|
74816
|
+
if (usage2) {
|
|
76192
74817
|
parts.push(
|
|
76193
|
-
`usage: input ${
|
|
74818
|
+
`usage: input ${usage2.input} \xB7 output ${usage2.output} \xB7 cacheRead ${usage2.cacheRead} \xB7 cacheWrite ${usage2.cacheWrite}`
|
|
76194
74819
|
);
|
|
76195
74820
|
}
|
|
76196
74821
|
if (Array.isArray(message.content)) {
|
|
@@ -76231,7 +74856,7 @@ function handleContextReportCommand(host) {
|
|
|
76231
74856
|
const systemPrompt = host.agent.state.systemPrompt ?? "";
|
|
76232
74857
|
const knowledgeFiles = parseProjectContextSection(host.knowledgeSection);
|
|
76233
74858
|
const entries = host.sessionManager.getActiveContextSummaries();
|
|
76234
|
-
const
|
|
74859
|
+
const usage2 = host.calculateContextUsage();
|
|
76235
74860
|
const contextWindow = host.options.model?.contextWindow ?? 0;
|
|
76236
74861
|
const reserveTokens = host.options.settingsManager.getAutoCompactReserveTokens();
|
|
76237
74862
|
const autoCompactEnabled = host.options.settingsManager.getAutoCompactEnabled();
|
|
@@ -76271,10 +74896,10 @@ function handleContextReportCommand(host) {
|
|
|
76271
74896
|
entries,
|
|
76272
74897
|
compactionTokensBefore: (entryId) => host.sessionManager.getEntry(entryId)?.compactionData?.tokensBefore,
|
|
76273
74898
|
contextWindow,
|
|
76274
|
-
estimatedCurrentTokens:
|
|
76275
|
-
providerMeasuredTokens:
|
|
76276
|
-
providerMeasuredAt:
|
|
76277
|
-
measurementMatchesCurrentContext:
|
|
74899
|
+
estimatedCurrentTokens: usage2.estimatedCurrentTokens,
|
|
74900
|
+
providerMeasuredTokens: usage2.providerMeasuredTokens,
|
|
74901
|
+
providerMeasuredAt: usage2.providerMeasuredAt,
|
|
74902
|
+
measurementMatchesCurrentContext: usage2.measurementMatchesCurrentContext,
|
|
76278
74903
|
autoCompactEnabled,
|
|
76279
74904
|
autoCompactLimitTokens: autoCompactLimit,
|
|
76280
74905
|
reserveTokens,
|
|
@@ -77163,6 +75788,12 @@ function handleCtrlC(host) {
|
|
|
77163
75788
|
}
|
|
77164
75789
|
}
|
|
77165
75790
|
var exitingHosts = /* @__PURE__ */ new WeakSet();
|
|
75791
|
+
var pendingResumeRestart = null;
|
|
75792
|
+
function scheduleResumeRestartAfterExit(restart) {
|
|
75793
|
+
if (pendingResumeRestart) return false;
|
|
75794
|
+
pendingResumeRestart = restart;
|
|
75795
|
+
return true;
|
|
75796
|
+
}
|
|
77166
75797
|
function cleanupAndExit(host) {
|
|
77167
75798
|
if (exitingHosts.has(host)) return;
|
|
77168
75799
|
exitingHosts.add(host);
|
|
@@ -77177,6 +75808,12 @@ function cleanupAndExit(host) {
|
|
|
77177
75808
|
process.exitCode = 1;
|
|
77178
75809
|
}
|
|
77179
75810
|
console.log(`[Cleanup] Goodbye!${sessionId ? ` session: ${sessionId}` : ""}`);
|
|
75811
|
+
const restart = pendingResumeRestart;
|
|
75812
|
+
pendingResumeRestart = null;
|
|
75813
|
+
if (restart) {
|
|
75814
|
+
restart();
|
|
75815
|
+
return;
|
|
75816
|
+
}
|
|
77180
75817
|
process.exit(process.exitCode || 0);
|
|
77181
75818
|
})();
|
|
77182
75819
|
}
|
|
@@ -78295,7 +76932,7 @@ function setupInteractiveEditorSubmitHandler(host) {
|
|
|
78295
76932
|
host.chatContainer.addChild(userMsg);
|
|
78296
76933
|
host.editor.setText("");
|
|
78297
76934
|
host.ui.requestRender();
|
|
78298
|
-
await new Promise((
|
|
76935
|
+
await new Promise((resolve8) => setImmediate(resolve8));
|
|
78299
76936
|
let finalContent = messageContent;
|
|
78300
76937
|
const reminderPrefix = host.executionState.getReminder() ?? host.executionReminder;
|
|
78301
76938
|
const combinedPrefix = [reminderPrefix].filter((value) => Boolean(value)).join("");
|
|
@@ -80120,17 +78757,17 @@ function setupInteractiveKeybindings(host) {
|
|
|
80120
78757
|
}
|
|
80121
78758
|
|
|
80122
78759
|
// src/clipboard/read-clipboard-image.ts
|
|
80123
|
-
import { spawn as
|
|
80124
|
-
import { chmodSync
|
|
78760
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
78761
|
+
import { chmodSync, closeSync as closeSync2, existsSync as existsSync16, fchmodSync, mkdtempSync, openSync as openSync2, readFileSync as readFileSync17, rmdirSync, statSync as statSync12, unlinkSync as unlinkSync5, writeFileSync as writeFileSync9 } from "node:fs";
|
|
80125
78762
|
import { tmpdir } from "node:os";
|
|
80126
|
-
import { join as
|
|
78763
|
+
import { join as join19 } from "node:path";
|
|
80127
78764
|
var MAX_IMAGE_BYTES = 50 * 1024 * 1024;
|
|
80128
78765
|
var COMMAND_TIMEOUT_MS = 1e4;
|
|
80129
78766
|
function isSpawnFailure(outcome) {
|
|
80130
78767
|
return !outcome.ok;
|
|
80131
78768
|
}
|
|
80132
|
-
function defaultSpawnFn(file, args, spawnImpl =
|
|
80133
|
-
return new Promise((
|
|
78769
|
+
function defaultSpawnFn(file, args, spawnImpl = spawn4, maxBytes = MAX_IMAGE_BYTES, timeoutMs = COMMAND_TIMEOUT_MS) {
|
|
78770
|
+
return new Promise((resolve8) => {
|
|
80134
78771
|
let child;
|
|
80135
78772
|
try {
|
|
80136
78773
|
child = spawnImpl(file, args, {
|
|
@@ -80138,7 +78775,7 @@ function defaultSpawnFn(file, args, spawnImpl = spawn2, maxBytes = MAX_IMAGE_BYT
|
|
|
80138
78775
|
windowsHide: true
|
|
80139
78776
|
});
|
|
80140
78777
|
} catch (err) {
|
|
80141
|
-
|
|
78778
|
+
resolve8({ ok: false, error: "spawn-failed", message: err instanceof Error ? err.message : String(err) });
|
|
80142
78779
|
return;
|
|
80143
78780
|
}
|
|
80144
78781
|
let settled = false;
|
|
@@ -80152,13 +78789,13 @@ function defaultSpawnFn(file, args, spawnImpl = spawn2, maxBytes = MAX_IMAGE_BYT
|
|
|
80152
78789
|
child.kill("SIGKILL");
|
|
80153
78790
|
} catch {
|
|
80154
78791
|
}
|
|
80155
|
-
|
|
78792
|
+
resolve8({ ok: false, error: "timeout" });
|
|
80156
78793
|
}, timeoutMs);
|
|
80157
78794
|
child.on("error", (err) => {
|
|
80158
78795
|
if (settled) return;
|
|
80159
78796
|
settled = true;
|
|
80160
78797
|
clearTimeout(timer);
|
|
80161
|
-
|
|
78798
|
+
resolve8({ ok: false, error: err.code === "ENOENT" ? "not-found" : "spawn-failed", message: err.message });
|
|
80162
78799
|
});
|
|
80163
78800
|
child.stdout?.on("data", (chunk) => {
|
|
80164
78801
|
if (settled) return;
|
|
@@ -80166,7 +78803,7 @@ function defaultSpawnFn(file, args, spawnImpl = spawn2, maxBytes = MAX_IMAGE_BYT
|
|
|
80166
78803
|
settled = true;
|
|
80167
78804
|
clearTimeout(timer);
|
|
80168
78805
|
stdoutChunks.length = 0;
|
|
80169
|
-
|
|
78806
|
+
resolve8({ ok: false, error: "too-large" });
|
|
80170
78807
|
try {
|
|
80171
78808
|
child.kill("SIGKILL");
|
|
80172
78809
|
} catch {
|
|
@@ -80183,7 +78820,7 @@ function defaultSpawnFn(file, args, spawnImpl = spawn2, maxBytes = MAX_IMAGE_BYT
|
|
|
80183
78820
|
if (settled) return;
|
|
80184
78821
|
settled = true;
|
|
80185
78822
|
clearTimeout(timer);
|
|
80186
|
-
|
|
78823
|
+
resolve8({ ok: true, result: { code: code ?? -1, stdout: Buffer.concat(stdoutChunks, stdoutBytes), stderr: stderrText } });
|
|
80187
78824
|
});
|
|
80188
78825
|
});
|
|
80189
78826
|
}
|
|
@@ -80196,23 +78833,23 @@ var TempImageResources = class {
|
|
|
80196
78833
|
files = /* @__PURE__ */ new Set();
|
|
80197
78834
|
create = (ext) => {
|
|
80198
78835
|
if (!this.injectedPath && !this.directory) {
|
|
80199
|
-
this.directory = mkdtempSync(
|
|
80200
|
-
if (process.platform !== "win32")
|
|
78836
|
+
this.directory = mkdtempSync(join19(tmpdir(), "pie-clipboard-"));
|
|
78837
|
+
if (process.platform !== "win32") chmodSync(this.directory, 448);
|
|
80201
78838
|
}
|
|
80202
|
-
const path34 = this.injectedPath ? this.injectedPath(ext) :
|
|
80203
|
-
const fd =
|
|
78839
|
+
const path34 = this.injectedPath ? this.injectedPath(ext) : join19(this.directory, `image${ext}`);
|
|
78840
|
+
const fd = openSync2(path34, "wx", 384);
|
|
80204
78841
|
this.files.add(path34);
|
|
80205
78842
|
try {
|
|
80206
78843
|
if (process.platform !== "win32") fchmodSync(fd, 384);
|
|
80207
78844
|
} finally {
|
|
80208
|
-
|
|
78845
|
+
closeSync2(fd);
|
|
80209
78846
|
}
|
|
80210
78847
|
return path34;
|
|
80211
78848
|
};
|
|
80212
78849
|
cleanup = () => {
|
|
80213
78850
|
for (const path34 of this.files) {
|
|
80214
78851
|
try {
|
|
80215
|
-
|
|
78852
|
+
unlinkSync5(path34);
|
|
80216
78853
|
this.files.delete(path34);
|
|
80217
78854
|
} catch (err) {
|
|
80218
78855
|
if (err.code === "ENOENT") this.files.delete(path34);
|
|
@@ -80430,7 +79067,7 @@ function writeImageBytes(bytes, declaredMime, mkTempPath) {
|
|
|
80430
79067
|
const mimeType = detectMimeFromMagic(bytes) ?? declaredMime;
|
|
80431
79068
|
const targetPath = mkTempPath(extensionForMime(mimeType));
|
|
80432
79069
|
try {
|
|
80433
|
-
|
|
79070
|
+
writeFileSync9(targetPath, bytes, { flag: "r+", mode: 384 });
|
|
80434
79071
|
} catch (err) {
|
|
80435
79072
|
return { ok: false, kind: "failed", message: `Failed to write temp image: ${errorMessage4(err)}` };
|
|
80436
79073
|
}
|
|
@@ -80443,7 +79080,7 @@ function writeImageBytes(bytes, declaredMime, mkTempPath) {
|
|
|
80443
79080
|
function finalizeTempImage(path34, mimeType) {
|
|
80444
79081
|
let bytes;
|
|
80445
79082
|
try {
|
|
80446
|
-
if (!
|
|
79083
|
+
if (!existsSync16(path34)) {
|
|
80447
79084
|
return { ok: false, kind: "no-image", message: "Clipboard does not contain an image." };
|
|
80448
79085
|
}
|
|
80449
79086
|
const size = statSync12(path34).size;
|
|
@@ -80501,9 +79138,9 @@ function formatBytes2(bytes) {
|
|
|
80501
79138
|
}
|
|
80502
79139
|
|
|
80503
79140
|
// src/input/image-paste.ts
|
|
80504
|
-
import { mkdtempSync as mkdtempSync2, writeFileSync as
|
|
79141
|
+
import { mkdtempSync as mkdtempSync2, writeFileSync as writeFileSync10, rmSync as rmSync3 } from "node:fs";
|
|
80505
79142
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
80506
|
-
import { join as
|
|
79143
|
+
import { join as join20 } from "node:path";
|
|
80507
79144
|
var pastingHosts = /* @__PURE__ */ new WeakSet();
|
|
80508
79145
|
function formatPastedImageName(date, extension = ".png") {
|
|
80509
79146
|
const pad = (value) => String(value).padStart(2, "0");
|
|
@@ -80528,9 +79165,9 @@ function terminalResultToClipboardResult(result) {
|
|
|
80528
79165
|
const ext = result.mimeType === "image/jpeg" ? ".jpg" : ".png";
|
|
80529
79166
|
let dir;
|
|
80530
79167
|
try {
|
|
80531
|
-
dir = mkdtempSync2(
|
|
80532
|
-
const path34 =
|
|
80533
|
-
|
|
79168
|
+
dir = mkdtempSync2(join20(tmpdir2(), "pie-osc5522-"));
|
|
79169
|
+
const path34 = join20(dir, formatPastedImageName(/* @__PURE__ */ new Date(), ext));
|
|
79170
|
+
writeFileSync10(path34, result.bytes);
|
|
80534
79171
|
return {
|
|
80535
79172
|
ok: true,
|
|
80536
79173
|
path: path34,
|
|
@@ -80809,11 +79446,24 @@ var ExtensionStatusSlots = class {
|
|
|
80809
79446
|
clear() {
|
|
80810
79447
|
this.slots.clear();
|
|
80811
79448
|
}
|
|
80812
|
-
/** Render-ready
|
|
79449
|
+
/** Render-ready footer cluster for the extension slots, e.g.
|
|
79450
|
+
* `"git:clean · ci:running"`. Bracket-tag values ("[IM]", "[MEM]")
|
|
79451
|
+
* concatenate directly — matching the built-in [PLAN]/[CALM]/[YOLO]
|
|
79452
|
+
* convention — while free-form statuses separate with " · ". No
|
|
79453
|
+
* leading separator: the footer inserts one only before a non-tag. */
|
|
80813
79454
|
format(maxWidth = 60) {
|
|
80814
79455
|
if (this.slots.size === 0) return "";
|
|
80815
|
-
|
|
80816
|
-
|
|
79456
|
+
let joined = "";
|
|
79457
|
+
for (const value of this.slots.values()) {
|
|
79458
|
+
if (joined === "") {
|
|
79459
|
+
joined = value;
|
|
79460
|
+
} else if (/^\[[^\[\]]+\]$/.test(value) && joined.endsWith("]")) {
|
|
79461
|
+
joined += value;
|
|
79462
|
+
} else {
|
|
79463
|
+
joined += ` \xB7 ${value}`;
|
|
79464
|
+
}
|
|
79465
|
+
}
|
|
79466
|
+
return truncateToWidth(joined, maxWidth, "");
|
|
80817
79467
|
}
|
|
80818
79468
|
};
|
|
80819
79469
|
|
|
@@ -80942,27 +79592,22 @@ var FooterComponent = class {
|
|
|
80942
79592
|
if (branch) {
|
|
80943
79593
|
pwd = `${pwd} (${branch})`;
|
|
80944
79594
|
}
|
|
80945
|
-
|
|
80946
|
-
const half = Math.floor(width / 2) - 2;
|
|
80947
|
-
if (half > 1) {
|
|
80948
|
-
const total = visibleWidth(pwd);
|
|
80949
|
-
const head = sliceByColumn(pwd, 0, half);
|
|
80950
|
-
const tail = sliceByColumn(pwd, Math.max(0, total - (half - 1)), half - 1);
|
|
80951
|
-
pwd = `${head}...${tail}`;
|
|
80952
|
-
} else {
|
|
80953
|
-
pwd = truncateToWidth(pwd, width);
|
|
80954
|
-
}
|
|
80955
|
-
}
|
|
80956
|
-
const statsParts = [];
|
|
79595
|
+
const tags = [];
|
|
80957
79596
|
if (state.planMode) {
|
|
80958
|
-
|
|
79597
|
+
tags.push(theme.fg("accent", "[PLAN]"));
|
|
80959
79598
|
}
|
|
80960
79599
|
if (state.calmMode) {
|
|
80961
|
-
|
|
79600
|
+
tags.push(theme.fg("dim", "[CALM]"));
|
|
80962
79601
|
}
|
|
80963
79602
|
if (state.yoloMode) {
|
|
80964
|
-
|
|
79603
|
+
tags.push(theme.fg("warning", "[YOLO]"));
|
|
79604
|
+
}
|
|
79605
|
+
const extensionTags = this.extensionStatuses.format();
|
|
79606
|
+
let tagLine = "";
|
|
79607
|
+
if (tags.length > 0 || extensionTags) {
|
|
79608
|
+
tagLine = tags.length > 0 && extensionTags && !/^\[[^\[\]]+\]/.test(extensionTags) ? tags.join("") + " \xB7 " + extensionTags : tags.join("") + extensionTags;
|
|
80965
79609
|
}
|
|
79610
|
+
const statsParts = [];
|
|
80966
79611
|
if (state.inputTokens) statsParts.push(`\u2191${formatTokens(state.inputTokens)}`);
|
|
80967
79612
|
if (state.outputTokens) statsParts.push(`\u2193${formatTokens(state.outputTokens)}`);
|
|
80968
79613
|
if (state.cacheRead) statsParts.push(`R${formatTokens(state.cacheRead)}`);
|
|
@@ -81019,8 +79664,7 @@ var FooterComponent = class {
|
|
|
81019
79664
|
return theme.fg(statusColor[state.status], `${spinner ? `${spinner} ` : ""}${statusText}${busyElapsed}`);
|
|
81020
79665
|
})();
|
|
81021
79666
|
statsParts.push(statusWithSpinner);
|
|
81022
|
-
|
|
81023
|
-
statsLeft += this.extensionStatuses.format();
|
|
79667
|
+
const statsLeft = statsParts.join(" ");
|
|
81024
79668
|
const modelName = state.modelName || "no-model";
|
|
81025
79669
|
let rightSide = modelName;
|
|
81026
79670
|
if (state.thinkingLevel) {
|
|
@@ -81045,8 +79689,32 @@ var FooterComponent = class {
|
|
|
81045
79689
|
statsLine = truncateToWidth(statsLeft, width);
|
|
81046
79690
|
}
|
|
81047
79691
|
}
|
|
79692
|
+
const plainTags = tagLine.replace(/\x1b\[[0-9;]*m/g, "");
|
|
79693
|
+
const tagsWidth = visibleWidth(plainTags);
|
|
79694
|
+
let pwdWidth = visibleWidth(pwd);
|
|
79695
|
+
if (pwdWidth > width || tagsWidth > 0 && pwdWidth + 2 + tagsWidth > width) {
|
|
79696
|
+
const room = tagsWidth > 0 ? Math.max(0, width - 2 - tagsWidth) : width;
|
|
79697
|
+
const half = Math.floor(room / 2) - 2;
|
|
79698
|
+
if (half > 1) {
|
|
79699
|
+
const total = pwdWidth;
|
|
79700
|
+
const head = sliceByColumn(pwd, 0, half);
|
|
79701
|
+
const tail = sliceByColumn(pwd, Math.max(0, total - (half - 1)), half - 1);
|
|
79702
|
+
pwd = `${head}...${tail}`;
|
|
79703
|
+
} else {
|
|
79704
|
+
pwd = truncateToWidth(pwd, room);
|
|
79705
|
+
}
|
|
79706
|
+
pwdWidth = visibleWidth(pwd);
|
|
79707
|
+
}
|
|
79708
|
+
let firstLine;
|
|
79709
|
+
if (tagsWidth === 0) {
|
|
79710
|
+
firstLine = pwd;
|
|
79711
|
+
} else if (pwdWidth + 2 + tagsWidth <= width) {
|
|
79712
|
+
firstLine = pwd + " ".repeat(width - pwdWidth - tagsWidth) + plainTags;
|
|
79713
|
+
} else {
|
|
79714
|
+
firstLine = " ".repeat(Math.max(0, width - tagsWidth)) + truncateToWidth(plainTags, width, "");
|
|
79715
|
+
}
|
|
81048
79716
|
const lines = [
|
|
81049
|
-
truncateToWidth(theme.fg("dim",
|
|
79717
|
+
truncateToWidth(theme.fg("dim", firstLine), width),
|
|
81050
79718
|
truncateToWidth(theme.fg("dim", statsLine), width)
|
|
81051
79719
|
];
|
|
81052
79720
|
return lines;
|
|
@@ -81128,8 +79796,8 @@ function calculateCliContextUsage(params) {
|
|
|
81128
79796
|
);
|
|
81129
79797
|
const estimate = estimateContextTokens(messages);
|
|
81130
79798
|
const usageMessage = estimate.lastUsageIndex !== null ? messages[estimate.lastUsageIndex] : void 0;
|
|
81131
|
-
const
|
|
81132
|
-
const hasProviderMeasurement =
|
|
79799
|
+
const usage2 = usageMessage?.role === "assistant" ? usageMessage.usage : void 0;
|
|
79800
|
+
const hasProviderMeasurement = usage2 !== void 0 && estimate.lastUsageIndex !== null;
|
|
81133
79801
|
return {
|
|
81134
79802
|
tokens: estimate.tokens,
|
|
81135
79803
|
estimatedCurrentTokens: estimate.tokens,
|
|
@@ -81139,13 +79807,13 @@ function calculateCliContextUsage(params) {
|
|
|
81139
79807
|
// tool/user message (or a compaction reset, which zeroes stale usage)
|
|
81140
79808
|
// makes the two figures different snapshots, so no error may be shown.
|
|
81141
79809
|
measurementMatchesCurrentContext: hasProviderMeasurement && estimate.lastUsageIndex === messages.length - 1,
|
|
81142
|
-
input:
|
|
81143
|
-
output:
|
|
81144
|
-
cacheRead:
|
|
81145
|
-
cacheWrite:
|
|
81146
|
-
cacheWriteLong:
|
|
81147
|
-
cost:
|
|
81148
|
-
costEstimated:
|
|
79810
|
+
input: usage2?.input ?? 0,
|
|
79811
|
+
output: usage2?.output ?? 0,
|
|
79812
|
+
cacheRead: usage2?.cacheRead ?? 0,
|
|
79813
|
+
cacheWrite: usage2?.cacheWrite ?? 0,
|
|
79814
|
+
cacheWriteLong: usage2?.cacheWriteLong ?? 0,
|
|
79815
|
+
cost: usage2?.cost.total ?? 0,
|
|
79816
|
+
costEstimated: usage2?.cost?.cacheWriteLongEstimated === true
|
|
81149
79817
|
};
|
|
81150
79818
|
}
|
|
81151
79819
|
function createCliAutoCompactDecision(params) {
|
|
@@ -81156,18 +79824,18 @@ function createCliAutoCompactDecision(params) {
|
|
|
81156
79824
|
if (!params.autoCompactEnabled || params.contextWindow <= 0) {
|
|
81157
79825
|
return void 0;
|
|
81158
79826
|
}
|
|
81159
|
-
const
|
|
79827
|
+
const usage2 = calculateCliContextUsage({
|
|
81160
79828
|
messages: params.messages,
|
|
81161
79829
|
latestCompactionTimestamp: params.latestCompactionTimestamp
|
|
81162
79830
|
});
|
|
81163
|
-
if (!
|
|
79831
|
+
if (!usage2.tokens) {
|
|
81164
79832
|
return void 0;
|
|
81165
79833
|
}
|
|
81166
79834
|
const tokenLimit = getAutoCompactTokenLimit(params.contextWindow, params.reserveTokens);
|
|
81167
79835
|
if (tokenLimit === void 0) {
|
|
81168
79836
|
return void 0;
|
|
81169
79837
|
}
|
|
81170
|
-
return
|
|
79838
|
+
return usage2.tokens > tokenLimit ? { reason: "threshold", willRetry: false } : void 0;
|
|
81171
79839
|
}
|
|
81172
79840
|
function shouldCliAutoCompactTokens(params) {
|
|
81173
79841
|
if (!params.tokens || params.contextWindow <= 0) {
|
|
@@ -81848,7 +80516,7 @@ async function recoverHardStalledTurn(host, stalledMs) {
|
|
|
81848
80516
|
try {
|
|
81849
80517
|
await Promise.race([
|
|
81850
80518
|
host.agentSessionController?.waitForIdle() ?? Promise.resolve(),
|
|
81851
|
-
new Promise((
|
|
80519
|
+
new Promise((resolve8) => setTimeout(resolve8, 2e3))
|
|
81852
80520
|
]);
|
|
81853
80521
|
} catch (error) {
|
|
81854
80522
|
host.logDebug("continuation_timeout:hard_stall_wait_failed", {
|
|
@@ -82527,8 +81195,8 @@ async function handleDirectBash(host, command) {
|
|
|
82527
81195
|
outputContainer.addChild(new Spacer(1));
|
|
82528
81196
|
host.chatContainer.addChild(outputContainer);
|
|
82529
81197
|
host.ui.requestRender();
|
|
82530
|
-
const { spawn:
|
|
82531
|
-
const child =
|
|
81198
|
+
const { spawn: spawn5 } = await import("child_process");
|
|
81199
|
+
const child = spawn5(shellCommand.file, shellCommand.args, {
|
|
82532
81200
|
cwd: process.cwd(),
|
|
82533
81201
|
env: process.env
|
|
82534
81202
|
});
|
|
@@ -82539,7 +81207,7 @@ async function handleDirectBash(host, command) {
|
|
|
82539
81207
|
child.stderr.on("data", (data) => {
|
|
82540
81208
|
output.append(data.toString());
|
|
82541
81209
|
});
|
|
82542
|
-
return new Promise((
|
|
81210
|
+
return new Promise((resolve8) => {
|
|
82543
81211
|
let settled = false;
|
|
82544
81212
|
const finish = (code) => {
|
|
82545
81213
|
if (settled) return;
|
|
@@ -82552,7 +81220,7 @@ async function handleDirectBash(host, command) {
|
|
|
82552
81220
|
}
|
|
82553
81221
|
host.chatContainer.addChild(new Spacer(1));
|
|
82554
81222
|
host.ui.requestRender();
|
|
82555
|
-
|
|
81223
|
+
resolve8();
|
|
82556
81224
|
};
|
|
82557
81225
|
child.on("error", (error) => {
|
|
82558
81226
|
output.append(error.message);
|
|
@@ -82604,19 +81272,19 @@ function installInteractiveInteractionHandler(host) {
|
|
|
82604
81272
|
const endWaitingForUser = (resolution) => {
|
|
82605
81273
|
endExtensionWaiting(host, attentionRequest, resolution);
|
|
82606
81274
|
};
|
|
82607
|
-
const
|
|
81275
|
+
const withTimeout = async (createPromise) => {
|
|
82608
81276
|
const controller = new AbortController();
|
|
82609
81277
|
if (!("timeoutMs" in request) || !request.timeoutMs || request.timeoutMs <= 0) {
|
|
82610
81278
|
return { value: await createPromise(controller.signal), timedOut: false };
|
|
82611
81279
|
}
|
|
82612
|
-
return await new Promise((
|
|
81280
|
+
return await new Promise((resolve8, reject) => {
|
|
82613
81281
|
const timer = setTimeout(() => {
|
|
82614
81282
|
controller.abort();
|
|
82615
|
-
|
|
81283
|
+
resolve8({ timedOut: true });
|
|
82616
81284
|
}, request.timeoutMs);
|
|
82617
81285
|
createPromise(controller.signal).then((value) => {
|
|
82618
81286
|
clearTimeout(timer);
|
|
82619
|
-
|
|
81287
|
+
resolve8({ value, timedOut: false });
|
|
82620
81288
|
}).catch((error) => {
|
|
82621
81289
|
clearTimeout(timer);
|
|
82622
81290
|
reject(error);
|
|
@@ -82627,7 +81295,7 @@ function installInteractiveInteractionHandler(host) {
|
|
|
82627
81295
|
beginWaitingForUser();
|
|
82628
81296
|
let resolution = "cancelled";
|
|
82629
81297
|
try {
|
|
82630
|
-
const result = await
|
|
81298
|
+
const result = await withTimeout(createPromise);
|
|
82631
81299
|
resolution = interactionAttentionResolution(result);
|
|
82632
81300
|
return result;
|
|
82633
81301
|
} finally {
|
|
@@ -82764,12 +81432,12 @@ function showExtensionNotification(host, message, type = "info", opts) {
|
|
|
82764
81432
|
host.ui.requestRender();
|
|
82765
81433
|
}
|
|
82766
81434
|
function showExtensionSelector2(host, title, options, opts) {
|
|
82767
|
-
return new Promise((
|
|
81435
|
+
return new Promise((resolve8) => {
|
|
82768
81436
|
const promptLine = title.split("\n")[0].trim() || title.trim();
|
|
82769
81437
|
host.showStatus(`Waiting for selection: ${promptLine}`);
|
|
82770
81438
|
if (opts?.signal?.aborted) {
|
|
82771
81439
|
host.clearStatusLine?.();
|
|
82772
|
-
|
|
81440
|
+
resolve8(void 0);
|
|
82773
81441
|
return;
|
|
82774
81442
|
}
|
|
82775
81443
|
const settle = (option) => {
|
|
@@ -82779,12 +81447,12 @@ function showExtensionSelector2(host, title, options, opts) {
|
|
|
82779
81447
|
host.showStatus(`${promptLine} \u2192 ${option}`);
|
|
82780
81448
|
}
|
|
82781
81449
|
host.restoreEditor();
|
|
82782
|
-
|
|
81450
|
+
resolve8(option);
|
|
82783
81451
|
};
|
|
82784
81452
|
const onAbort = () => {
|
|
82785
81453
|
host.clearStatusLine?.();
|
|
82786
81454
|
host.restoreEditor();
|
|
82787
|
-
|
|
81455
|
+
resolve8(void 0);
|
|
82788
81456
|
};
|
|
82789
81457
|
opts?.signal?.addEventListener("abort", onAbort, { once: true });
|
|
82790
81458
|
const selector = new ExtensionSelectorComponent(
|
|
@@ -82819,17 +81487,17 @@ ${message}`, options, opts);
|
|
|
82819
81487
|
return { confirmed: result === "Yes" };
|
|
82820
81488
|
}
|
|
82821
81489
|
function showExtensionInput(host, title, placeholder, opts) {
|
|
82822
|
-
return new Promise((
|
|
81490
|
+
return new Promise((resolve8) => {
|
|
82823
81491
|
host.showStatus(`Waiting for input: ${title}`);
|
|
82824
81492
|
if (opts?.signal?.aborted) {
|
|
82825
81493
|
host.clearStatusLine?.();
|
|
82826
|
-
|
|
81494
|
+
resolve8(void 0);
|
|
82827
81495
|
return;
|
|
82828
81496
|
}
|
|
82829
81497
|
const settle = (value) => {
|
|
82830
81498
|
host.clearStatusLine?.();
|
|
82831
81499
|
host.restoreEditor();
|
|
82832
|
-
|
|
81500
|
+
resolve8(value);
|
|
82833
81501
|
};
|
|
82834
81502
|
const onAbort = () => settle(void 0);
|
|
82835
81503
|
opts?.signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -82853,12 +81521,12 @@ function showExtensionInput(host, title, placeholder, opts) {
|
|
|
82853
81521
|
});
|
|
82854
81522
|
}
|
|
82855
81523
|
function showExtensionEditor(host, title, prefill, opts) {
|
|
82856
|
-
return new Promise((
|
|
81524
|
+
return new Promise((resolve8) => {
|
|
82857
81525
|
host.showStatus(`Waiting for input: ${title}`);
|
|
82858
81526
|
const settle = (value) => {
|
|
82859
81527
|
host.clearStatusLine?.();
|
|
82860
81528
|
host.restoreEditor();
|
|
82861
|
-
|
|
81529
|
+
resolve8(value);
|
|
82862
81530
|
};
|
|
82863
81531
|
const onAbort = () => settle(void 0);
|
|
82864
81532
|
opts?.signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -82905,14 +81573,14 @@ function showExtensionEditor(host, title, prefill, opts) {
|
|
|
82905
81573
|
}
|
|
82906
81574
|
function showExtensionCustom(host, factory, options) {
|
|
82907
81575
|
const savedText = host.editor.getText();
|
|
82908
|
-
return new Promise((
|
|
81576
|
+
return new Promise((resolve8, reject) => {
|
|
82909
81577
|
let closed = false;
|
|
82910
81578
|
const close = (result) => {
|
|
82911
81579
|
if (closed) return;
|
|
82912
81580
|
closed = true;
|
|
82913
81581
|
host.restoreEditor();
|
|
82914
81582
|
host.editor.setText(savedText);
|
|
82915
|
-
|
|
81583
|
+
resolve8(result);
|
|
82916
81584
|
};
|
|
82917
81585
|
Promise.resolve(factory(host.ui, theme, close)).then((component) => {
|
|
82918
81586
|
if (closed) return;
|
|
@@ -83798,7 +82466,7 @@ var InteractiveMode = class {
|
|
|
83798
82466
|
async init() {
|
|
83799
82467
|
const activeSession = this.sessionManager.getActiveSession();
|
|
83800
82468
|
this.thinkingLevel = resolveInitialThinkingLevel({ session: activeSession, settingsManager: this.options.settingsManager });
|
|
83801
|
-
const { Agent } = await import("./chunks/src-
|
|
82469
|
+
const { Agent } = await import("./chunks/src-YG5M2H44.js");
|
|
83802
82470
|
this.agent = new Agent({
|
|
83803
82471
|
initialState: {
|
|
83804
82472
|
systemPrompt: this.buildSystemPrompt(),
|
|
@@ -84235,7 +82903,7 @@ var InteractiveMode = class {
|
|
|
84235
82903
|
};
|
|
84236
82904
|
|
|
84237
82905
|
// src/app/runtime-composition.ts
|
|
84238
|
-
import { existsSync as
|
|
82906
|
+
import { existsSync as existsSync17, mkdirSync as mkdirSync11 } from "fs";
|
|
84239
82907
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
84240
82908
|
import * as path31 from "path";
|
|
84241
82909
|
var CliMissingApiKeyError = class extends Error {
|
|
@@ -84263,8 +82931,8 @@ function getCliRuntimePaths() {
|
|
|
84263
82931
|
return { configDir, sessionsDir, skillsDir, builtinSkillsDir };
|
|
84264
82932
|
}
|
|
84265
82933
|
function ensureCliRuntimePaths(paths = getCliRuntimePaths()) {
|
|
84266
|
-
if (!
|
|
84267
|
-
|
|
82934
|
+
if (!existsSync17(paths.skillsDir)) {
|
|
82935
|
+
mkdirSync11(paths.skillsDir, { recursive: true });
|
|
84268
82936
|
}
|
|
84269
82937
|
return paths;
|
|
84270
82938
|
}
|
|
@@ -84696,7 +83364,7 @@ async function runPrintMode(params) {
|
|
|
84696
83364
|
`);
|
|
84697
83365
|
console.log("Assistant: ");
|
|
84698
83366
|
}
|
|
84699
|
-
const { Agent: AgentClass } = await import("./chunks/src-
|
|
83367
|
+
const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
|
|
84700
83368
|
let agent;
|
|
84701
83369
|
const printModeExtensions = await loadPrintModeExtensions({
|
|
84702
83370
|
cwd: runtime.cwd,
|
|
@@ -85225,7 +83893,7 @@ async function runJsonEventsMode(params) {
|
|
|
85225
83893
|
return typeof message.sessionId === "string" && message.sessionId !== sessionId;
|
|
85226
83894
|
}
|
|
85227
83895
|
function delay(ms) {
|
|
85228
|
-
return new Promise((
|
|
83896
|
+
return new Promise((resolve8) => setTimeout(resolve8, Math.max(0, ms)));
|
|
85229
83897
|
}
|
|
85230
83898
|
function touch() {
|
|
85231
83899
|
if (activeTurn) {
|
|
@@ -85591,7 +84259,7 @@ async function runJsonEventsMode(params) {
|
|
|
85591
84259
|
const sideTrace = trace;
|
|
85592
84260
|
const sideApiKey = runtime.apiKey;
|
|
85593
84261
|
const snapshot = structuredClone(parent.state.messages);
|
|
85594
|
-
const { Agent: AgentClass } = await import("./chunks/src-
|
|
84262
|
+
const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
|
|
85595
84263
|
const sideAgent = new AgentClass({
|
|
85596
84264
|
initialState: {
|
|
85597
84265
|
systemPrompt: parent.state.systemPrompt,
|
|
@@ -85908,10 +84576,10 @@ async function runJsonEventsMode(params) {
|
|
|
85908
84576
|
if (params.mockResponse !== void 0) return;
|
|
85909
84577
|
if (!params.createRuntime && !params.runtime) return;
|
|
85910
84578
|
try {
|
|
85911
|
-
await new Promise((
|
|
84579
|
+
await new Promise((resolve8, reject) => {
|
|
85912
84580
|
const timer = setTimeout(() => reject(new Error("prewarm timeout")), prewarmTimeoutMs);
|
|
85913
84581
|
timer.unref?.();
|
|
85914
|
-
void ensureRuntime().then(
|
|
84582
|
+
void ensureRuntime().then(resolve8, reject).finally(() => clearTimeout(timer));
|
|
85915
84583
|
});
|
|
85916
84584
|
} catch {
|
|
85917
84585
|
}
|
|
@@ -85955,7 +84623,7 @@ async function runJsonEventsMode(params) {
|
|
|
85955
84623
|
if (runtime.initialModel.unconfigured || controller) {
|
|
85956
84624
|
return;
|
|
85957
84625
|
}
|
|
85958
|
-
const { Agent: AgentClass } = await import("./chunks/src-
|
|
84626
|
+
const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
|
|
85959
84627
|
if (runtimeClosing) return;
|
|
85960
84628
|
const compositionRegistry = createCliHostEnvelopeRegistry();
|
|
85961
84629
|
const jsonModeExtensions = await loadJsonModeExtensions({ runtime, envelopeRegistry: compositionRegistry, getAgent: () => agent });
|
|
@@ -86022,6 +84690,9 @@ async function runJsonEventsMode(params) {
|
|
|
86022
84690
|
};
|
|
86023
84691
|
},
|
|
86024
84692
|
retry: createCliRetryPolicy(),
|
|
84693
|
+
onExecutionEnd: async ({ messages }) => {
|
|
84694
|
+
await jsonModeExtensions.runner.emit({ type: "agent:end", messages });
|
|
84695
|
+
},
|
|
86025
84696
|
getAutoCompactDecision: ({ message, messages }) => createCliAutoCompactDecision({
|
|
86026
84697
|
message,
|
|
86027
84698
|
messages,
|
|
@@ -86166,8 +84837,8 @@ async function runJsonEventsMode(params) {
|
|
|
86166
84837
|
return;
|
|
86167
84838
|
}
|
|
86168
84839
|
let releaseReady;
|
|
86169
|
-
const ready = new Promise((
|
|
86170
|
-
releaseReady =
|
|
84840
|
+
const ready = new Promise((resolve8) => {
|
|
84841
|
+
releaseReady = resolve8;
|
|
86171
84842
|
});
|
|
86172
84843
|
activeTurn = {
|
|
86173
84844
|
ready,
|
|
@@ -86594,6 +85265,7 @@ Print Mode Options:
|
|
|
86594
85265
|
--json-events Run JSONL protocol mode over stdin/stdout
|
|
86595
85266
|
--session-id Reuse or create a specific session in non-interactive mode
|
|
86596
85267
|
--resume-required In JSON-events mode, fail if --session-id cannot be resumed
|
|
85268
|
+
--no-cd Resume without restarting in the session's project directory
|
|
86597
85269
|
--developer-instructions <text> Append stable host/developer instructions in JSON-events mode
|
|
86598
85270
|
--developer-instructions-file <path> Read stable host/developer instructions from a file
|
|
86599
85271
|
--extension-path Add an extra extension search directory (repeatable)
|
|
@@ -86643,7 +85315,7 @@ async function runWithJsonEventsConsoleIsolation(fn) {
|
|
|
86643
85315
|
}
|
|
86644
85316
|
async function createCliTestStreamFnFromEnv() {
|
|
86645
85317
|
if (!process.env.PIE_TEST_MOCK_STREAM_SEQUENCE) return void 0;
|
|
86646
|
-
return (await import("./chunks/test-stream-
|
|
85318
|
+
return (await import("./chunks/test-stream-JBWXKOQA.js")).createTestStreamFnFromSequenceEnv();
|
|
86647
85319
|
}
|
|
86648
85320
|
function resolveJsonEventsDetailFlag() {
|
|
86649
85321
|
for (let index = 0; index < process.argv.length; index += 1) {
|
|
@@ -86659,13 +85331,11 @@ function resolveJsonEventsDetailFlag() {
|
|
|
86659
85331
|
}
|
|
86660
85332
|
return { value: "compact" };
|
|
86661
85333
|
}
|
|
86662
|
-
async function startChat(initialPrompt, testCommand) {
|
|
85334
|
+
async function startChat(initialPrompt, testCommand, explicitSessionId) {
|
|
86663
85335
|
const rawOutput = process.argv.includes("--raw-output");
|
|
86664
85336
|
const jsonOutput = process.argv.includes("--json-output");
|
|
86665
85337
|
const jsonEvents = process.argv.includes("--json-events");
|
|
86666
85338
|
const resumeRequired = process.argv.includes("--resume-required");
|
|
86667
|
-
const sessionIdFlagIndex = process.argv.indexOf("--session-id");
|
|
86668
|
-
const explicitSessionId = sessionIdFlagIndex >= 0 ? process.argv[sessionIdFlagIndex + 1] : void 0;
|
|
86669
85339
|
const extensionPaths = parseRepeatedFlag(process.argv, "--extension-path");
|
|
86670
85340
|
const extensionFlags = parseExtensionFlags(process.argv);
|
|
86671
85341
|
if (jsonEvents) {
|
|
@@ -86761,9 +85431,9 @@ async function startChat(initialPrompt, testCommand) {
|
|
|
86761
85431
|
if (testCommand) {
|
|
86762
85432
|
await interactive.run();
|
|
86763
85433
|
console.log(`[TEST] Auto-executing command: ${testCommand}`);
|
|
86764
|
-
await new Promise((
|
|
85434
|
+
await new Promise((resolve8) => setTimeout(resolve8, 500));
|
|
86765
85435
|
await interactive.executeCommand(testCommand);
|
|
86766
|
-
await new Promise((
|
|
85436
|
+
await new Promise((resolve8) => setTimeout(resolve8, 2e3));
|
|
86767
85437
|
console.log("[TEST] Command executed, exiting...");
|
|
86768
85438
|
process.exit(0);
|
|
86769
85439
|
return;
|
|
@@ -86819,16 +85489,33 @@ async function main() {
|
|
|
86819
85489
|
runPermissionsCommand(args.slice(1));
|
|
86820
85490
|
return;
|
|
86821
85491
|
}
|
|
85492
|
+
if (args[0] === "memory") {
|
|
85493
|
+
await runMemoryCommand(args.slice(1));
|
|
85494
|
+
return;
|
|
85495
|
+
}
|
|
86822
85496
|
const parsed = parseCliInvocation(args);
|
|
86823
85497
|
if (parsed.showHelp) {
|
|
86824
85498
|
showHelp();
|
|
86825
85499
|
return;
|
|
86826
85500
|
}
|
|
85501
|
+
if (parsed.sessionId) {
|
|
85502
|
+
const decision = decideSessionResumeRestart(args, parsed.sessionId, process.cwd());
|
|
85503
|
+
if (decision) {
|
|
85504
|
+
if (decision.action === "restart") {
|
|
85505
|
+
const code = await performResumeRestart(decision, (warning) => console.warn(`[resume] ${warning}`));
|
|
85506
|
+
if (code !== null) {
|
|
85507
|
+
process.exit(code);
|
|
85508
|
+
}
|
|
85509
|
+
} else if (decision.warning) {
|
|
85510
|
+
console.warn(`[resume] ${decision.warning}`);
|
|
85511
|
+
}
|
|
85512
|
+
}
|
|
85513
|
+
}
|
|
86827
85514
|
if (parsed.testCommand) {
|
|
86828
|
-
await startChat(void 0, parsed.testCommand);
|
|
85515
|
+
await startChat(void 0, parsed.testCommand, parsed.sessionId);
|
|
86829
85516
|
return;
|
|
86830
85517
|
}
|
|
86831
|
-
await startChat(parsed.initialPrompt);
|
|
85518
|
+
await startChat(parsed.initialPrompt, void 0, parsed.sessionId);
|
|
86832
85519
|
}
|
|
86833
85520
|
main().catch((err) => {
|
|
86834
85521
|
logError("Fatal error", err);
|