@wrongstack/core 0.77.0 → 0.84.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/dist/{agent-bridge-EWdqs8v6.d.ts → agent-bridge-C9P_HPez.d.ts} +2 -2
- package/dist/{agent-subagent-runner-D8qW8OSC.d.ts → agent-subagent-runner-2Aq0jOSj.d.ts} +107 -102
- package/dist/{compactor-D_ExJajC.d.ts → compactor-CJq7LQev.d.ts} +3 -3
- package/dist/{config-Dy0CK_o6.d.ts → config-_DZ7dN-T.d.ts} +77 -75
- package/dist/{context-y87Jc5ei.d.ts → context-ToHAp4-U.d.ts} +119 -90
- package/dist/coordination/index.d.ts +16 -16
- package/dist/coordination/index.js +318 -37
- package/dist/coordination/index.js.map +1 -1
- package/dist/defaults/index.d.ts +32 -32
- package/dist/defaults/index.js +433 -81
- package/dist/defaults/index.js.map +1 -1
- package/dist/{director-state-BmYi3DGA.d.ts → director-state-CgIc30qi.d.ts} +19 -19
- package/dist/{events-CYaoLN5_.d.ts → events-DnRqXaZ3.d.ts} +43 -42
- package/dist/execution/index.d.ts +53 -53
- package/dist/execution/index.js +72 -29
- package/dist/execution/index.js.map +1 -1
- package/dist/extension/index.d.ts +9 -9
- package/dist/extension/index.js +8 -1
- package/dist/extension/index.js.map +1 -1
- package/dist/{goal-store-C7jcumEh.d.ts → goal-store-DvWLNu52.d.ts} +4 -4
- package/dist/{index-DIxjTOga.d.ts → index-BNOLadHw.d.ts} +28 -28
- package/dist/{index-Dsda0uCn.d.ts → index-N0_c4bHQ.d.ts} +45 -45
- package/dist/index.d.ts +167 -167
- package/dist/index.js +617 -155
- package/dist/index.js.map +1 -1
- package/dist/infrastructure/index.d.ts +9 -9
- package/dist/infrastructure/index.js +13 -5
- package/dist/infrastructure/index.js.map +1 -1
- package/dist/kernel/index.d.ts +14 -14
- package/dist/kernel/index.js +7 -0
- package/dist/kernel/index.js.map +1 -1
- package/dist/logger-B72yyPc6.d.ts +12 -0
- package/dist/{logger-BppKxDqZ.d.ts → logger-C_27pj9i.d.ts} +6 -7
- package/dist/{mcp-servers-T0O6UN_w.d.ts → mcp-servers-Dck3T85_.d.ts} +20 -20
- package/dist/{mode-BO4SEUIv.d.ts → mode-CHo2XtHs.d.ts} +4 -4
- package/dist/models/index.d.ts +10 -10
- package/dist/models/index.js +8 -2
- package/dist/models/index.js.map +1 -1
- package/dist/{models-registry-BcYJDKLm.d.ts → models-registry-Be3osGt5.d.ts} +28 -28
- package/dist/{models-registry-Cuq1C8V9.d.ts → models-registry-Boz639EI.d.ts} +12 -12
- package/dist/{multi-agent-coordinator-DpbG3wiy.d.ts → multi-agent-coordinator-DllpCVkF.d.ts} +12 -12
- package/dist/{null-fleet-bus-u5ys3lW_.d.ts → null-fleet-bus-BY0AN-sr.d.ts} +121 -121
- package/dist/observability/index.d.ts +41 -41
- package/dist/observability/index.js.map +1 -1
- package/dist/{observability-BhnVLBLS.d.ts → observability-CoSNZdhX.d.ts} +4 -4
- package/dist/{parallel-eternal-engine-Dn0P8Pbj.d.ts → parallel-eternal-engine-D402RASp.d.ts} +49 -49
- package/dist/{path-resolver-B32v2JIq.d.ts → path-resolver-UPFTsDyD.d.ts} +6 -6
- package/dist/{permission-V5BLOrY6.d.ts → permission-14CChMmO.d.ts} +10 -8
- package/dist/{permission-policy-CBVx-d-8.d.ts → permission-policy-gW5htOo1.d.ts} +7 -7
- package/dist/{plan-templates-BcUwLlMQ.d.ts → plan-templates-DRvPgkfZ.d.ts} +65 -32
- package/dist/{provider-runner-CSi_7l0h.d.ts → provider-runner-COAJM8tC.d.ts} +6 -6
- package/dist/{retry-policy-CG3qvH_e.d.ts → retry-policy-DSu6O6rD.d.ts} +4 -4
- package/dist/sdd/index.d.ts +47 -47
- package/dist/sdd/index.js +47 -22
- package/dist/sdd/index.js.map +1 -1
- package/dist/{secret-scrubber-7rSC_emZ.d.ts → secret-scrubber-yGBFQYju.d.ts} +10 -2
- package/dist/security/index.d.ts +7 -7
- package/dist/security/index.js +15 -8
- package/dist/security/index.js.map +1 -1
- package/dist/{selector-RvBR_YRW.d.ts → selector-11-fm95U.d.ts} +2 -2
- package/dist/{session-event-bridge-CDHxcmQU.d.ts → session-event-bridge-D0u-x576.d.ts} +7 -7
- package/dist/{session-reader-BIpwM60D.d.ts → session-reader-BQU-toaN.d.ts} +23 -23
- package/dist/{skill-CxuWrsKK.d.ts → skill-BJeF2DwY.d.ts} +1 -1
- package/dist/skills/index.d.ts +9 -9
- package/dist/skills/index.js +15 -3
- package/dist/skills/index.js.map +1 -1
- package/dist/storage/index.d.ts +15 -15
- package/dist/storage/index.js +378 -76
- package/dist/storage/index.js.map +1 -1
- package/dist/{system-prompt-CA11g6Jo.d.ts → system-prompt-C0rLCeyn.d.ts} +16 -11
- package/dist/{task-graph-D1YQbpxF.d.ts → task-graph-CikNdRTG.d.ts} +22 -22
- package/dist/types/index.d.ts +26 -26
- package/dist/types/index.js +53 -17
- package/dist/types/index.js.map +1 -1
- package/dist/utils/index.d.ts +57 -45
- package/dist/utils/index.js +66 -12
- package/dist/utils/index.js.map +1 -1
- package/dist/{wstack-paths-D7evAFWM.d.ts → wstack-paths-BQMvEllz.d.ts} +2 -2
- package/package.json +1 -1
- package/dist/logger-DDd5C--Z.d.ts +0 -12
package/dist/index.js
CHANGED
|
@@ -419,6 +419,13 @@ var Container = class {
|
|
|
419
419
|
has(token) {
|
|
420
420
|
return this.entries.has(token);
|
|
421
421
|
}
|
|
422
|
+
/**
|
|
423
|
+
* Resolve a token if it is bound, otherwise return undefined.
|
|
424
|
+
* Unlike resolve(), this does not throw if the token is unbound.
|
|
425
|
+
*/
|
|
426
|
+
safeResolve(token) {
|
|
427
|
+
return this.has(token) ? this.resolve(token) : void 0;
|
|
428
|
+
}
|
|
422
429
|
ownerOf(token) {
|
|
423
430
|
return this.entries.get(token)?.owner;
|
|
424
431
|
}
|
|
@@ -1166,20 +1173,20 @@ var DefaultSecretVault = class {
|
|
|
1166
1173
|
return key;
|
|
1167
1174
|
}
|
|
1168
1175
|
};
|
|
1169
|
-
function decryptConfigSecrets(cfg, vault) {
|
|
1176
|
+
function decryptConfigSecrets(cfg, vault, opts) {
|
|
1177
|
+
const warn = opts?.warn ?? ((msg) => console.warn(msg));
|
|
1170
1178
|
return walk(cfg, vault, (v, key) => {
|
|
1171
1179
|
try {
|
|
1172
1180
|
return vault.decrypt(v);
|
|
1173
1181
|
} catch (err) {
|
|
1174
|
-
|
|
1175
|
-
`[secret-vault] Failed to decrypt "${key}"
|
|
1176
|
-
err instanceof Error ? err.message : err
|
|
1182
|
+
warn(
|
|
1183
|
+
`[secret-vault] Failed to decrypt "${key}": ${err instanceof Error ? err.message : err}`
|
|
1177
1184
|
);
|
|
1178
1185
|
return "";
|
|
1179
1186
|
}
|
|
1180
1187
|
});
|
|
1181
1188
|
}
|
|
1182
|
-
function encryptConfigSecrets(cfg, vault) {
|
|
1189
|
+
function encryptConfigSecrets(cfg, vault, _opts) {
|
|
1183
1190
|
return walk(cfg, vault, (v) => vault.encrypt(v));
|
|
1184
1191
|
}
|
|
1185
1192
|
function walk(node, vault, transform) {
|
|
@@ -1240,7 +1247,8 @@ async function migratePlaintextSecrets(configPath, vault) {
|
|
|
1240
1247
|
await restrictFilePermissions(configPath);
|
|
1241
1248
|
return { migrated: counter.n, file: configPath };
|
|
1242
1249
|
}
|
|
1243
|
-
async function restrictFilePermissions(filePath) {
|
|
1250
|
+
async function restrictFilePermissions(filePath, opts) {
|
|
1251
|
+
const warn = ((msg) => console.warn(msg));
|
|
1244
1252
|
if (process.platform === "win32") {
|
|
1245
1253
|
try {
|
|
1246
1254
|
const { execFile: execFile2 } = await import('child_process');
|
|
@@ -1248,7 +1256,7 @@ async function restrictFilePermissions(filePath) {
|
|
|
1248
1256
|
const execFileAsync = promisify2(execFile2);
|
|
1249
1257
|
await execFileAsync("icacls", [filePath, "/inheritance:r", "/grant:r", `${process.env.USERNAME}:(F)`]);
|
|
1250
1258
|
} catch {
|
|
1251
|
-
|
|
1259
|
+
warn(`[secret-vault] Could not restrict permissions on ${filePath} \u2014 config file may be readable by other users on this system.`);
|
|
1252
1260
|
}
|
|
1253
1261
|
} else {
|
|
1254
1262
|
try {
|
|
@@ -1338,9 +1346,20 @@ function setRawMode(input, mode) {
|
|
|
1338
1346
|
input.setRawMode(mode);
|
|
1339
1347
|
return true;
|
|
1340
1348
|
}
|
|
1349
|
+
var activeOutputGuard = null;
|
|
1350
|
+
function setOutputLineGuard(guard) {
|
|
1351
|
+
activeOutputGuard = guard;
|
|
1352
|
+
}
|
|
1341
1353
|
function writeTo(s, stream) {
|
|
1342
1354
|
if (!stream || typeof stream.write !== "function") return false;
|
|
1355
|
+
const guard = activeOutputGuard;
|
|
1356
|
+
if (!guard) {
|
|
1357
|
+
stream.write(s);
|
|
1358
|
+
return true;
|
|
1359
|
+
}
|
|
1360
|
+
guard.suspend();
|
|
1343
1361
|
stream.write(s);
|
|
1362
|
+
guard.resume();
|
|
1344
1363
|
return true;
|
|
1345
1364
|
}
|
|
1346
1365
|
function writeOut(s, stream = process.stdout) {
|
|
@@ -1515,7 +1534,7 @@ var DefaultTokenCounter = class {
|
|
|
1515
1534
|
} else if (this.registry && this.providerId && model) {
|
|
1516
1535
|
if (this.priceCache.size >= PRICE_CACHE_MAX_SIZE) {
|
|
1517
1536
|
const keys = [...this.priceCache.keys()];
|
|
1518
|
-
this.priceCache.delete(keys[0]);
|
|
1537
|
+
this.priceCache.delete(keys[0] ?? "");
|
|
1519
1538
|
}
|
|
1520
1539
|
void this.registry.getModel(this.providerId, model).then((m) => {
|
|
1521
1540
|
if (m) {
|
|
@@ -1540,7 +1559,7 @@ var DefaultTokenCounter = class {
|
|
|
1540
1559
|
const price = priceFromModel(resolved);
|
|
1541
1560
|
if (this.priceCache.size >= PRICE_CACHE_MAX_SIZE) {
|
|
1542
1561
|
const keys = [...this.priceCache.keys()];
|
|
1543
|
-
this.priceCache.delete(keys[0]);
|
|
1562
|
+
this.priceCache.delete(keys[0] ?? "");
|
|
1544
1563
|
}
|
|
1545
1564
|
this.priceCache.set(resolved.modelId, price);
|
|
1546
1565
|
this.applyPrice(usage, price);
|
|
@@ -1608,6 +1627,12 @@ function round4(n) {
|
|
|
1608
1627
|
}
|
|
1609
1628
|
|
|
1610
1629
|
// src/utils/token-estimate.ts
|
|
1630
|
+
function expectDefined(value) {
|
|
1631
|
+
if (value === null || value === void 0) {
|
|
1632
|
+
throw new Error("Expected value to be defined");
|
|
1633
|
+
}
|
|
1634
|
+
return value;
|
|
1635
|
+
}
|
|
1611
1636
|
var RoughTokenEstimate = (text, charsPerToken = 3.5) => Math.max(1, Math.ceil(text.length / charsPerToken));
|
|
1612
1637
|
var _cal = {
|
|
1613
1638
|
ratio: 1,
|
|
@@ -1628,7 +1653,7 @@ function getCachedEstimate(key, compute) {
|
|
|
1628
1653
|
if (ESTIMATE_CACHE.size >= ESTIMATE_CACHE_MAX_SIZE) {
|
|
1629
1654
|
const keys = [...ESTIMATE_CACHE.keys()];
|
|
1630
1655
|
for (let i = 0; i < Math.floor(ESTIMATE_CACHE_MAX_SIZE / 4); i++) {
|
|
1631
|
-
ESTIMATE_CACHE.delete(keys[i]);
|
|
1656
|
+
ESTIMATE_CACHE.delete(expectDefined(keys[i]));
|
|
1632
1657
|
}
|
|
1633
1658
|
}
|
|
1634
1659
|
const estimate = compute();
|
|
@@ -1741,6 +1766,12 @@ function resetCalibration() {
|
|
|
1741
1766
|
}
|
|
1742
1767
|
|
|
1743
1768
|
// src/utils/message-invariants.ts
|
|
1769
|
+
function expectDefined2(value) {
|
|
1770
|
+
if (value === null || value === void 0) {
|
|
1771
|
+
throw new Error("Expected value to be defined");
|
|
1772
|
+
}
|
|
1773
|
+
return value;
|
|
1774
|
+
}
|
|
1744
1775
|
function repairToolUseAdjacency(messages) {
|
|
1745
1776
|
const removedToolUses = [];
|
|
1746
1777
|
const removedToolResults = [];
|
|
@@ -1748,7 +1779,7 @@ function repairToolUseAdjacency(messages) {
|
|
|
1748
1779
|
let changed = false;
|
|
1749
1780
|
const out = [];
|
|
1750
1781
|
for (let i = 0; i < messages.length; i++) {
|
|
1751
|
-
const original = messages[i];
|
|
1782
|
+
const original = expectDefined2(messages[i]);
|
|
1752
1783
|
let msg = original;
|
|
1753
1784
|
if (hasToolUse(msg)) {
|
|
1754
1785
|
const nextIds = toolResultIds(messages[i + 1]);
|
|
@@ -2906,6 +2937,12 @@ Remember: your job is to make the user a better developer, not just to complete
|
|
|
2906
2937
|
];
|
|
2907
2938
|
|
|
2908
2939
|
// src/types/context-window.ts
|
|
2940
|
+
function expectDefined3(value) {
|
|
2941
|
+
if (value === null || value === void 0) {
|
|
2942
|
+
throw new Error("Expected value to be defined");
|
|
2943
|
+
}
|
|
2944
|
+
return value;
|
|
2945
|
+
}
|
|
2909
2946
|
var DEFAULT_CONTEXT_WINDOW_MODE_ID = "balanced";
|
|
2910
2947
|
var CONTEXT_WINDOW_MODES = Object.freeze([
|
|
2911
2948
|
{
|
|
@@ -2962,7 +2999,7 @@ function isContextWindowModeId(id) {
|
|
|
2962
2999
|
}
|
|
2963
3000
|
function resolveContextWindowPolicy(config = {}, overrideMode) {
|
|
2964
3001
|
const requested = overrideMode ?? config.mode ?? DEFAULT_CONTEXT_WINDOW_MODE_ID;
|
|
2965
|
-
const mode = getContextWindowMode(requested) ?? getContextWindowMode(DEFAULT_CONTEXT_WINDOW_MODE_ID);
|
|
3002
|
+
const mode = getContextWindowMode(requested) ?? expectDefined3(getContextWindowMode(DEFAULT_CONTEXT_WINDOW_MODE_ID));
|
|
2966
3003
|
if (mode.id !== DEFAULT_CONTEXT_WINDOW_MODE_ID) {
|
|
2967
3004
|
return mode;
|
|
2968
3005
|
}
|
|
@@ -3013,7 +3050,7 @@ var InMemoryBridgeTransport = class {
|
|
|
3013
3050
|
}
|
|
3014
3051
|
subscribe(agentId, handler) {
|
|
3015
3052
|
if (!this.subs.has(agentId)) this.subs.set(agentId, /* @__PURE__ */ new Set());
|
|
3016
|
-
this.subs.get(agentId)
|
|
3053
|
+
this.subs.get(agentId)?.add(handler);
|
|
3017
3054
|
return () => this.subs.get(agentId)?.delete(handler);
|
|
3018
3055
|
}
|
|
3019
3056
|
close(agentId) {
|
|
@@ -3442,6 +3479,12 @@ function sizeSignals(toolName, content) {
|
|
|
3442
3479
|
}
|
|
3443
3480
|
|
|
3444
3481
|
// src/execution/tool-executor.ts
|
|
3482
|
+
function expectDefined4(value) {
|
|
3483
|
+
if (value === null || value === void 0) {
|
|
3484
|
+
throw new Error("Expected value to be defined");
|
|
3485
|
+
}
|
|
3486
|
+
return value;
|
|
3487
|
+
}
|
|
3445
3488
|
var ToolExecutor = class {
|
|
3446
3489
|
constructor(registry, opts) {
|
|
3447
3490
|
this.registry = registry;
|
|
@@ -3730,6 +3773,9 @@ ${post.additionalContext}` };
|
|
|
3730
3773
|
async runStreamedTool(tool, input, ctx, signal, toolUseId) {
|
|
3731
3774
|
let finalOutput;
|
|
3732
3775
|
let sawFinal = false;
|
|
3776
|
+
if (!tool.executeStream) {
|
|
3777
|
+
throw new Error(`Tool "${tool.name}" does not support streaming execution`);
|
|
3778
|
+
}
|
|
3733
3779
|
const stream = tool.executeStream(input, ctx, { signal });
|
|
3734
3780
|
for await (const ev of stream) {
|
|
3735
3781
|
if (ev.type === "final") {
|
|
@@ -3834,7 +3880,7 @@ function hasMalformedArguments(input) {
|
|
|
3834
3880
|
function extractMalformedRaw(input) {
|
|
3835
3881
|
if (!hasMalformedArguments(input)) return void 0;
|
|
3836
3882
|
const obj = input;
|
|
3837
|
-
const value = obj[Object.keys(obj)[0]];
|
|
3883
|
+
const value = obj[expectDefined4(Object.keys(obj)[0])];
|
|
3838
3884
|
if (value === void 0 || value === null) return void 0;
|
|
3839
3885
|
if (typeof value === "string") return value;
|
|
3840
3886
|
try {
|
|
@@ -3881,6 +3927,12 @@ function compileUserRegex(pattern, flags) {
|
|
|
3881
3927
|
}
|
|
3882
3928
|
|
|
3883
3929
|
// src/storage/session-reader.ts
|
|
3930
|
+
function expectDefined5(value) {
|
|
3931
|
+
if (value === null || value === void 0) {
|
|
3932
|
+
throw new Error("Expected value to be defined");
|
|
3933
|
+
}
|
|
3934
|
+
return value;
|
|
3935
|
+
}
|
|
3884
3936
|
var DefaultSessionReader = class {
|
|
3885
3937
|
store;
|
|
3886
3938
|
constructor(opts) {
|
|
@@ -3942,7 +3994,7 @@ var DefaultSessionReader = class {
|
|
|
3942
3994
|
continue;
|
|
3943
3995
|
}
|
|
3944
3996
|
for (let i = 0; i < data.events.length; i++) {
|
|
3945
|
-
const ev = data.events[i];
|
|
3997
|
+
const ev = expectDefined5(data.events[i]);
|
|
3946
3998
|
if (allowedTypes && !allowedTypes.has(ev.type)) continue;
|
|
3947
3999
|
const text = eventText(ev);
|
|
3948
4000
|
if (text === null) continue;
|
|
@@ -4210,7 +4262,7 @@ function escapeControlCharsInStrings(s) {
|
|
|
4210
4262
|
let inString = false;
|
|
4211
4263
|
let out = "";
|
|
4212
4264
|
for (let i = 0; i < s.length; i++) {
|
|
4213
|
-
const c = s
|
|
4265
|
+
const c = s.charAt(i);
|
|
4214
4266
|
if (c === '"' && (i === 0 || s[i - 1] !== "\\")) {
|
|
4215
4267
|
inString = !inString;
|
|
4216
4268
|
out += c;
|
|
@@ -4248,12 +4300,12 @@ function stripSingleLineComments(s) {
|
|
|
4248
4300
|
const chars = [];
|
|
4249
4301
|
let i = 0;
|
|
4250
4302
|
while (i < s.length) {
|
|
4251
|
-
const c = s
|
|
4252
|
-
if (c === '"' && (i === 0 || s
|
|
4303
|
+
const c = s.charAt(i);
|
|
4304
|
+
if (c === '"' && (i === 0 || s.charAt(i - 1) !== "\\")) {
|
|
4253
4305
|
inString = !inString;
|
|
4254
4306
|
chars.push(c);
|
|
4255
|
-
} else if (c === "/" && s
|
|
4256
|
-
while (i < s.length && s
|
|
4307
|
+
} else if (c === "/" && s.charAt(i + 1) === "/" && !inString) {
|
|
4308
|
+
while (i < s.length && s.charAt(i) !== "\n") i++;
|
|
4257
4309
|
} else {
|
|
4258
4310
|
chars.push(c);
|
|
4259
4311
|
}
|
|
@@ -4310,6 +4362,12 @@ function formatTodosList(todos) {
|
|
|
4310
4362
|
}
|
|
4311
4363
|
|
|
4312
4364
|
// src/utils/glob-match.ts
|
|
4365
|
+
function expectDefined6(value) {
|
|
4366
|
+
if (value === null || value === void 0) {
|
|
4367
|
+
throw new Error("Expected value to be defined");
|
|
4368
|
+
}
|
|
4369
|
+
return value;
|
|
4370
|
+
}
|
|
4313
4371
|
function escapeRegex(s) {
|
|
4314
4372
|
return s.replace(/[.+^${}()|\\]/g, "\\$&");
|
|
4315
4373
|
}
|
|
@@ -4321,7 +4379,7 @@ function getCachedGlob(pattern) {
|
|
|
4321
4379
|
if (COMPILED_GLOB_CACHE.size >= CACHE_MAX_SIZE) {
|
|
4322
4380
|
const keys = [...COMPILED_GLOB_CACHE.keys()];
|
|
4323
4381
|
for (let i = 0; i < Math.floor(CACHE_MAX_SIZE / 4); i++) {
|
|
4324
|
-
COMPILED_GLOB_CACHE.delete(keys[i]);
|
|
4382
|
+
COMPILED_GLOB_CACHE.delete(expectDefined6(keys[i]));
|
|
4325
4383
|
}
|
|
4326
4384
|
}
|
|
4327
4385
|
const re = compileGlob(pattern);
|
|
@@ -4676,6 +4734,25 @@ function buildChildEnv(optsOrSessionId) {
|
|
|
4676
4734
|
if (opts.sessionId) out["WRONGSTACK_SESSION_ID"] = opts.sessionId;
|
|
4677
4735
|
return out;
|
|
4678
4736
|
}
|
|
4737
|
+
|
|
4738
|
+
// src/utils/sleep.ts
|
|
4739
|
+
function sleep(ms) {
|
|
4740
|
+
return new Promise((resolve13) => setTimeout(resolve13, ms));
|
|
4741
|
+
}
|
|
4742
|
+
|
|
4743
|
+
// src/utils/expect-defined.ts
|
|
4744
|
+
function expectDefined7(value) {
|
|
4745
|
+
if (value === null || value === void 0) {
|
|
4746
|
+
throw new Error("Expected value to be defined");
|
|
4747
|
+
}
|
|
4748
|
+
return value;
|
|
4749
|
+
}
|
|
4750
|
+
function expectDefined8(value) {
|
|
4751
|
+
if (value === null || value === void 0) {
|
|
4752
|
+
throw new Error("Expected value to be defined");
|
|
4753
|
+
}
|
|
4754
|
+
return value;
|
|
4755
|
+
}
|
|
4679
4756
|
var GLOB_CHARS = /* @__PURE__ */ new Set(["*", "?", "["]);
|
|
4680
4757
|
var IS_WINDOWS = process.platform === "win32";
|
|
4681
4758
|
var SEP = IS_WINDOWS ? "\\" : "/";
|
|
@@ -4689,7 +4766,7 @@ function globToRegex(pat) {
|
|
|
4689
4766
|
let i = 0;
|
|
4690
4767
|
let re = "^";
|
|
4691
4768
|
while (i < pat.length) {
|
|
4692
|
-
const c = pat[i];
|
|
4769
|
+
const c = expectDefined8(pat[i]);
|
|
4693
4770
|
if (c === "*") {
|
|
4694
4771
|
if (pat[i + 1] === "*") {
|
|
4695
4772
|
re += ".*";
|
|
@@ -4728,7 +4805,7 @@ function globToRegex(pat) {
|
|
|
4728
4805
|
}
|
|
4729
4806
|
function baseDir(pat) {
|
|
4730
4807
|
let i = pat.length - 1;
|
|
4731
|
-
while (i >= 0 && !GLOB_CHARS.has(pat[i]) && pat[i] !== SEP && pat[i] !== "/") i--;
|
|
4808
|
+
while (i >= 0 && !GLOB_CHARS.has(expectDefined8(pat[i])) && pat[i] !== SEP && pat[i] !== "/") i--;
|
|
4732
4809
|
const cut = i >= 0 ? pat.lastIndexOf(SEP, i) : pat.lastIndexOf("/", i);
|
|
4733
4810
|
return cut < 0 ? "." : pat.slice(0, cut);
|
|
4734
4811
|
}
|
|
@@ -4793,6 +4870,12 @@ async function expandGlob(pattern) {
|
|
|
4793
4870
|
}
|
|
4794
4871
|
|
|
4795
4872
|
// src/utils/json-repair.ts
|
|
4873
|
+
function expectDefined9(value) {
|
|
4874
|
+
if (value === null || value === void 0) {
|
|
4875
|
+
throw new Error("Expected value to be defined");
|
|
4876
|
+
}
|
|
4877
|
+
return value;
|
|
4878
|
+
}
|
|
4796
4879
|
function completePartialObject(s) {
|
|
4797
4880
|
if (!s.trim().startsWith("{")) return s;
|
|
4798
4881
|
if (tryParse(s).ok) return s;
|
|
@@ -4804,7 +4887,7 @@ function completePartialObject(s) {
|
|
|
4804
4887
|
let contentEnd = 0;
|
|
4805
4888
|
let stringBraceDepth = 0;
|
|
4806
4889
|
for (let i = 0; i < s.length; i++) {
|
|
4807
|
-
const ch = s[i];
|
|
4890
|
+
const ch = expectDefined9(s[i]);
|
|
4808
4891
|
if (inString) {
|
|
4809
4892
|
contentEnd = i + 1;
|
|
4810
4893
|
if (escaped) {
|
|
@@ -4900,6 +4983,12 @@ function mergeCustomModelDefs(providerCustomModels, configModels) {
|
|
|
4900
4983
|
|
|
4901
4984
|
// src/storage/session-store.ts
|
|
4902
4985
|
init_atomic_write();
|
|
4986
|
+
function expectDefined10(value) {
|
|
4987
|
+
if (value === null || value === void 0) {
|
|
4988
|
+
throw new Error("Expected value to be defined");
|
|
4989
|
+
}
|
|
4990
|
+
return value;
|
|
4991
|
+
}
|
|
4903
4992
|
function sanitizeModel(model) {
|
|
4904
4993
|
return model.replace(/[^a-zA-Z0-9_-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
|
|
4905
4994
|
}
|
|
@@ -4910,7 +4999,7 @@ function generateSessionId(startedAt, model) {
|
|
|
4910
4999
|
const modelPart = model ? `_${sanitizeModel(model)}` : "";
|
|
4911
5000
|
return `${date}/${time}Z${modelPart}_${suffix}`;
|
|
4912
5001
|
}
|
|
4913
|
-
var DefaultSessionStore = class {
|
|
5002
|
+
var DefaultSessionStore = class _DefaultSessionStore {
|
|
4914
5003
|
dir;
|
|
4915
5004
|
events;
|
|
4916
5005
|
secretScrubber;
|
|
@@ -4919,6 +5008,10 @@ var DefaultSessionStore = class {
|
|
|
4919
5008
|
this.events = opts.events;
|
|
4920
5009
|
this.secretScrubber = opts.secretScrubber;
|
|
4921
5010
|
}
|
|
5011
|
+
/** Absolute path to the session index file. */
|
|
5012
|
+
get indexFile() {
|
|
5013
|
+
return path6.join(this.dir, "_index.jsonl");
|
|
5014
|
+
}
|
|
4922
5015
|
/** Join session ID to its absolute path within the store directory. */
|
|
4923
5016
|
sessionPath(id, ext) {
|
|
4924
5017
|
return path6.join(this.dir, `${id}${ext}`);
|
|
@@ -4951,7 +5044,8 @@ var DefaultSessionStore = class {
|
|
|
4951
5044
|
return new FileSessionWriter(id, handle, startedAt, meta, this.events, {
|
|
4952
5045
|
dir: shardDir,
|
|
4953
5046
|
filePath: file,
|
|
4954
|
-
secretScrubber: this.secretScrubber
|
|
5047
|
+
secretScrubber: this.secretScrubber,
|
|
5048
|
+
onClose: (s) => this.appendToIndex(s)
|
|
4955
5049
|
});
|
|
4956
5050
|
} catch (err) {
|
|
4957
5051
|
await handle.close().catch(() => {
|
|
@@ -4982,7 +5076,7 @@ var DefaultSessionStore = class {
|
|
|
4982
5076
|
provider: data.metadata.provider
|
|
4983
5077
|
},
|
|
4984
5078
|
this.events,
|
|
4985
|
-
{ resumed: true, dir: this.dir, filePath: file, secretScrubber: this.secretScrubber }
|
|
5079
|
+
{ resumed: true, dir: this.dir, filePath: file, secretScrubber: this.secretScrubber, onClose: (s) => this.appendToIndex(s) }
|
|
4986
5080
|
);
|
|
4987
5081
|
return { writer, data };
|
|
4988
5082
|
} catch (err) {
|
|
@@ -5012,6 +5106,15 @@ var DefaultSessionStore = class {
|
|
|
5012
5106
|
async list(limit = 20) {
|
|
5013
5107
|
try {
|
|
5014
5108
|
await ensureDir(this.dir);
|
|
5109
|
+
const indexed = await this.readIndex();
|
|
5110
|
+
if (indexed.length > 0) {
|
|
5111
|
+
indexed.sort((a, b) => {
|
|
5112
|
+
if (a.startedAt < b.startedAt) return 1;
|
|
5113
|
+
if (a.startedAt > b.startedAt) return -1;
|
|
5114
|
+
return a.id.localeCompare(b.id);
|
|
5115
|
+
});
|
|
5116
|
+
return indexed.slice(0, limit);
|
|
5117
|
+
}
|
|
5015
5118
|
const ids = await this.collectSessionIds(this.dir);
|
|
5016
5119
|
const sessions = await Promise.all(ids.map((id) => this.summaryFor(id).catch(() => null)));
|
|
5017
5120
|
const out = sessions.filter((s) => s !== null);
|
|
@@ -5025,16 +5128,121 @@ var DefaultSessionStore = class {
|
|
|
5025
5128
|
return [];
|
|
5026
5129
|
}
|
|
5027
5130
|
}
|
|
5028
|
-
|
|
5029
|
-
|
|
5131
|
+
// ── Session index (_index.jsonl) ─────────────────────────────────────────
|
|
5132
|
+
//
|
|
5133
|
+
// One JSON line per closed session, appended atomically on close().
|
|
5134
|
+
// When a session is deleted, a tombstone {action:"delete",id:"..."} is
|
|
5135
|
+
// appended. On read, tombstones filter out matching session entries.
|
|
5136
|
+
// This keeps listing O(lines-in-index) instead of O(files-on-disk).
|
|
5137
|
+
//
|
|
5138
|
+
// The index auto-compacts every N appends to prevent unbounded growth
|
|
5139
|
+
// from tombstones and duplicate entries (resume cycles).
|
|
5140
|
+
indexAppendCount = 0;
|
|
5141
|
+
static COMPACT_EVERY = 30;
|
|
5142
|
+
/** Append a session summary to the index. */
|
|
5143
|
+
async appendToIndex(summary) {
|
|
5144
|
+
try {
|
|
5145
|
+
await ensureDir(this.dir);
|
|
5146
|
+
const line = JSON.stringify(summary) + "\n";
|
|
5147
|
+
await fsp3.appendFile(this.indexFile, line, "utf8");
|
|
5148
|
+
this.indexAppendCount++;
|
|
5149
|
+
if (this.indexAppendCount >= _DefaultSessionStore.COMPACT_EVERY) {
|
|
5150
|
+
await this.compactIndex();
|
|
5151
|
+
this.indexAppendCount = 0;
|
|
5152
|
+
}
|
|
5153
|
+
} catch {
|
|
5154
|
+
}
|
|
5155
|
+
}
|
|
5156
|
+
/** Append a tombstone entry for a deleted session. */
|
|
5157
|
+
async writeTombstone(id) {
|
|
5158
|
+
try {
|
|
5159
|
+
await ensureDir(this.dir);
|
|
5160
|
+
const line = JSON.stringify({ action: "delete", id }) + "\n";
|
|
5161
|
+
await fsp3.appendFile(this.indexFile, line, "utf8");
|
|
5162
|
+
this.indexAppendCount++;
|
|
5163
|
+
} catch {
|
|
5164
|
+
}
|
|
5165
|
+
}
|
|
5166
|
+
/**
|
|
5167
|
+
* Compact the index: read all entries, drop tombstones, deduplicate
|
|
5168
|
+
* (keep latest per session), and rewrite. Atomic via temp+rename.
|
|
5169
|
+
*/
|
|
5170
|
+
async compactIndex() {
|
|
5171
|
+
const entries = await this.readIndex();
|
|
5172
|
+
if (entries.length === 0) return;
|
|
5173
|
+
const tmp = `${this.indexFile}.compact.tmp`;
|
|
5174
|
+
const lines = entries.map((s) => JSON.stringify(s)).join("\n") + "\n";
|
|
5175
|
+
await fsp3.writeFile(tmp, lines, "utf8");
|
|
5176
|
+
await fsp3.rename(tmp, this.indexFile);
|
|
5177
|
+
}
|
|
5178
|
+
/**
|
|
5179
|
+
* Read the index file and return deduplicated session summaries.
|
|
5180
|
+
* Entries with a matching tombstone are filtered out.
|
|
5181
|
+
* Returns empty array when the index doesn't exist or is corrupt.
|
|
5182
|
+
*/
|
|
5183
|
+
async readIndex() {
|
|
5184
|
+
let raw;
|
|
5185
|
+
try {
|
|
5186
|
+
raw = await fsp3.readFile(this.indexFile, "utf8");
|
|
5187
|
+
} catch {
|
|
5188
|
+
return [];
|
|
5189
|
+
}
|
|
5190
|
+
const deleted = /* @__PURE__ */ new Set();
|
|
5191
|
+
const seen = /* @__PURE__ */ new Map();
|
|
5192
|
+
for (const line of raw.split("\n")) {
|
|
5193
|
+
if (!line.trim()) continue;
|
|
5194
|
+
try {
|
|
5195
|
+
const entry = JSON.parse(line);
|
|
5196
|
+
if (entry.action === "delete" && entry.id) {
|
|
5197
|
+
deleted.add(entry.id);
|
|
5198
|
+
seen.delete(entry.id);
|
|
5199
|
+
continue;
|
|
5200
|
+
}
|
|
5201
|
+
if (entry.id && !deleted.has(entry.id)) {
|
|
5202
|
+
seen.set(entry.id, entry);
|
|
5203
|
+
}
|
|
5204
|
+
} catch {
|
|
5205
|
+
}
|
|
5206
|
+
}
|
|
5207
|
+
return Array.from(seen.values());
|
|
5208
|
+
}
|
|
5209
|
+
/**
|
|
5210
|
+
* Rebuild the index from disk by scanning all sessions and writing a
|
|
5211
|
+
* fresh _index.jsonl. Useful after manual cleanup or index corruption.
|
|
5212
|
+
*/
|
|
5213
|
+
async rebuildIndex() {
|
|
5214
|
+
const ids = await this.collectSessionIds(this.dir);
|
|
5215
|
+
const summaries = await Promise.all(ids.map((id) => this.summaryFor(id).catch(() => null)));
|
|
5216
|
+
const valid = summaries.filter((s) => s !== null);
|
|
5217
|
+
const tmp = `${this.indexFile}.tmp`;
|
|
5218
|
+
const lines = valid.map((s) => JSON.stringify(s)).join("\n") + "\n";
|
|
5219
|
+
await fsp3.writeFile(tmp, lines, "utf8");
|
|
5220
|
+
await fsp3.rename(tmp, this.indexFile);
|
|
5221
|
+
return valid.length;
|
|
5222
|
+
}
|
|
5223
|
+
/** Recursively collect session IDs from date-shard subdirectories.
|
|
5224
|
+
* IDs include the date-prefix path (e.g. "2026-06-06/17-46-57Z_…").
|
|
5225
|
+
* Skips `.jsonl`/`.summary.json` root files, dot-files, and
|
|
5226
|
+
* sub-directories that belong to fleet/subagent sessions. */
|
|
5227
|
+
async collectSessionIds(dir, prefix = "", depth = 0) {
|
|
5030
5228
|
const ids = [];
|
|
5031
|
-
|
|
5229
|
+
let entries;
|
|
5230
|
+
try {
|
|
5231
|
+
entries = await fsp3.readdir(dir, { withFileTypes: true });
|
|
5232
|
+
} catch {
|
|
5233
|
+
return ids;
|
|
5234
|
+
}
|
|
5032
5235
|
for (const entry of entries) {
|
|
5033
|
-
|
|
5236
|
+
if (entry.name.startsWith(".") && entry.name !== ".wrongstack") continue;
|
|
5237
|
+
if (entry.name === "shared" || entry.name === "subagents" || entry.name === "attachments")
|
|
5238
|
+
continue;
|
|
5034
5239
|
if (entry.isDirectory()) {
|
|
5035
|
-
|
|
5240
|
+
const childPrefix = depth === 0 ? entry.name : `${prefix}/${entry.name}`;
|
|
5241
|
+
ids.push(...await this.collectSessionIds(path6.join(dir, entry.name), childPrefix, depth + 1));
|
|
5036
5242
|
} else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
|
|
5037
|
-
|
|
5243
|
+
if (entry.name === "_index.jsonl") continue;
|
|
5244
|
+
const base = entry.name.replace(/\.jsonl$/, "");
|
|
5245
|
+
ids.push(prefix ? `${prefix}/${base}` : base);
|
|
5038
5246
|
}
|
|
5039
5247
|
}
|
|
5040
5248
|
return ids;
|
|
@@ -5057,9 +5265,70 @@ var DefaultSessionStore = class {
|
|
|
5057
5265
|
return summary;
|
|
5058
5266
|
}
|
|
5059
5267
|
}
|
|
5060
|
-
|
|
5061
|
-
|
|
5268
|
+
/**
|
|
5269
|
+
* Delete a session and all associated files: JSONL, summary, plan/todos
|
|
5270
|
+
* sidecars, and the session directory (fleet.json, shared/, subagents/).
|
|
5271
|
+
*/
|
|
5272
|
+
async deleteSession(id) {
|
|
5273
|
+
await fsp3.unlink(this.sessionPath(id, ".jsonl")).catch(() => void 0);
|
|
5062
5274
|
await fsp3.unlink(this.sessionPath(id, ".summary.json")).catch(() => void 0);
|
|
5275
|
+
const shardDir = path6.dirname(path6.join(this.dir, id));
|
|
5276
|
+
const base = path6.basename(id);
|
|
5277
|
+
for (const ext of [".plan.json", ".todos.json"]) {
|
|
5278
|
+
await fsp3.unlink(path6.join(shardDir, `${base}${ext}`)).catch(() => void 0);
|
|
5279
|
+
}
|
|
5280
|
+
const sessDir = path6.join(shardDir, base);
|
|
5281
|
+
await fsp3.rm(sessDir, { recursive: true, force: true }).catch(() => void 0);
|
|
5282
|
+
await this.writeTombstone(id);
|
|
5283
|
+
}
|
|
5284
|
+
async delete(id) {
|
|
5285
|
+
await this.deleteSession(id);
|
|
5286
|
+
}
|
|
5287
|
+
async prune(maxAgeDays = 30) {
|
|
5288
|
+
const cutoff = Date.now() - maxAgeDays * 864e5;
|
|
5289
|
+
let deleted = 0;
|
|
5290
|
+
let activeSessionId = null;
|
|
5291
|
+
try {
|
|
5292
|
+
const raw = await fsp3.readFile(path6.join(this.dir, "active.json"), "utf8");
|
|
5293
|
+
const active = JSON.parse(raw);
|
|
5294
|
+
activeSessionId = active.sessionId ?? null;
|
|
5295
|
+
} catch {
|
|
5296
|
+
}
|
|
5297
|
+
const entries = await fsp3.readdir(this.dir, { withFileTypes: true }).catch(() => []);
|
|
5298
|
+
for (const entry of entries) {
|
|
5299
|
+
if (!entry.isDirectory()) continue;
|
|
5300
|
+
const dateDir = path6.join(this.dir, entry.name);
|
|
5301
|
+
const files = await fsp3.readdir(dateDir, { withFileTypes: true }).catch(() => []);
|
|
5302
|
+
for (const file of files) {
|
|
5303
|
+
if (!file.isFile() || !file.name.endsWith(".jsonl")) continue;
|
|
5304
|
+
const jsonlPath = path6.join(dateDir, file.name);
|
|
5305
|
+
try {
|
|
5306
|
+
const stat10 = await fsp3.stat(jsonlPath);
|
|
5307
|
+
if (stat10.mtimeMs >= cutoff) continue;
|
|
5308
|
+
} catch {
|
|
5309
|
+
continue;
|
|
5310
|
+
}
|
|
5311
|
+
const id = `${entry.name}/${file.name.replace(/\.jsonl$/, "")}`;
|
|
5312
|
+
if (activeSessionId && id === activeSessionId) continue;
|
|
5313
|
+
await this.deleteSession(id);
|
|
5314
|
+
deleted++;
|
|
5315
|
+
}
|
|
5316
|
+
}
|
|
5317
|
+
if (deleted > 0) {
|
|
5318
|
+
await this.compactIndex().catch(() => void 0);
|
|
5319
|
+
}
|
|
5320
|
+
for (const entry of entries) {
|
|
5321
|
+
if (!entry.isDirectory()) continue;
|
|
5322
|
+
const dateDir = path6.join(this.dir, entry.name);
|
|
5323
|
+
try {
|
|
5324
|
+
const remaining = await fsp3.readdir(dateDir);
|
|
5325
|
+
if (remaining.length === 0) {
|
|
5326
|
+
await fsp3.rmdir(dateDir).catch(() => void 0);
|
|
5327
|
+
}
|
|
5328
|
+
} catch {
|
|
5329
|
+
}
|
|
5330
|
+
}
|
|
5331
|
+
return deleted;
|
|
5063
5332
|
}
|
|
5064
5333
|
async clearHistory(id) {
|
|
5065
5334
|
await this.ensureShardDir(id);
|
|
@@ -5081,13 +5350,42 @@ var DefaultSessionStore = class {
|
|
|
5081
5350
|
const data = await this.load(id);
|
|
5082
5351
|
const firstUser = data.events.find((e) => e.type === "user_input");
|
|
5083
5352
|
const title = firstUser && firstUser.type === "user_input" ? userInputTitle(firstUser.content) : "(empty session)";
|
|
5353
|
+
let iterationCount = 0;
|
|
5354
|
+
let toolCallCount = 0;
|
|
5355
|
+
let toolErrorCount = 0;
|
|
5356
|
+
let fileChangeCount = 0;
|
|
5357
|
+
const toolBreakdown = {};
|
|
5358
|
+
let outcome = void 0;
|
|
5359
|
+
const lastEvent = data.events[data.events.length - 1];
|
|
5360
|
+
for (const e of data.events) {
|
|
5361
|
+
if (e.type === "in_flight_start") iterationCount++;
|
|
5362
|
+
else if (e.type === "tool_call_start") {
|
|
5363
|
+
toolCallCount++;
|
|
5364
|
+
toolBreakdown[e.name] = (toolBreakdown[e.name] ?? 0) + 1;
|
|
5365
|
+
} else if (e.type === "tool_result" && e.isError) toolErrorCount++;
|
|
5366
|
+
else if (e.type === "file_snapshot") fileChangeCount += e.files.length;
|
|
5367
|
+
}
|
|
5368
|
+
if (lastEvent?.type === "session_end") {
|
|
5369
|
+
outcome = "completed";
|
|
5370
|
+
} else if (lastEvent?.type === "in_flight_start") {
|
|
5371
|
+
outcome = "aborted";
|
|
5372
|
+
} else if (data.events.some((e) => e.type === "error")) {
|
|
5373
|
+
outcome = "error";
|
|
5374
|
+
}
|
|
5084
5375
|
return {
|
|
5085
5376
|
id,
|
|
5086
5377
|
title,
|
|
5087
5378
|
startedAt: data.metadata.startedAt,
|
|
5379
|
+
endedAt: data.metadata.endedAt,
|
|
5088
5380
|
model: data.metadata.model ?? "unknown",
|
|
5089
5381
|
provider: data.metadata.provider ?? "unknown",
|
|
5090
|
-
tokenTotal: data.usage.input + data.usage.output
|
|
5382
|
+
tokenTotal: data.usage.input + data.usage.output,
|
|
5383
|
+
iterationCount: iterationCount > 0 ? iterationCount : void 0,
|
|
5384
|
+
toolCallCount: toolCallCount > 0 ? toolCallCount : void 0,
|
|
5385
|
+
toolErrorCount: toolErrorCount > 0 ? toolErrorCount : void 0,
|
|
5386
|
+
fileChangeCount: fileChangeCount > 0 ? fileChangeCount : void 0,
|
|
5387
|
+
toolBreakdown: Object.keys(toolBreakdown).length > 0 ? toolBreakdown : {},
|
|
5388
|
+
outcome
|
|
5091
5389
|
};
|
|
5092
5390
|
} catch {
|
|
5093
5391
|
return {
|
|
@@ -5186,9 +5484,10 @@ var FileSessionWriter = class {
|
|
|
5186
5484
|
this.meta = meta;
|
|
5187
5485
|
this.events = events;
|
|
5188
5486
|
this.resumed = opts.resumed ?? false;
|
|
5189
|
-
this.manifestFile = opts.dir ? path6.join(opts.dir, `${id}.summary.json`) : "";
|
|
5487
|
+
this.manifestFile = opts.dir ? path6.join(opts.dir, `${path6.basename(id)}.summary.json`) : "";
|
|
5190
5488
|
this.filePath = opts.filePath ?? "";
|
|
5191
5489
|
this.secretScrubber = opts.secretScrubber;
|
|
5490
|
+
this.onCloseCb = opts.onClose;
|
|
5192
5491
|
this.summary = {
|
|
5193
5492
|
id,
|
|
5194
5493
|
title: "(empty session)",
|
|
@@ -5218,6 +5517,15 @@ var FileSessionWriter = class {
|
|
|
5218
5517
|
appendFailCount = 0;
|
|
5219
5518
|
lastAppendWarnAt = 0;
|
|
5220
5519
|
secretScrubber;
|
|
5520
|
+
onCloseCb;
|
|
5521
|
+
// ── Enriched summary tracking ──────────────────────────────────────────
|
|
5522
|
+
iterationCount = 0;
|
|
5523
|
+
toolCallCount = 0;
|
|
5524
|
+
toolErrorCount = 0;
|
|
5525
|
+
toolBreakdown = {};
|
|
5526
|
+
fileChangeCount = 0;
|
|
5527
|
+
compactionCount = 0;
|
|
5528
|
+
outcome = void 0;
|
|
5221
5529
|
/**
|
|
5222
5530
|
* Scrub secrets out of conversation-turn events before they are observed
|
|
5223
5531
|
* for the summary, written to the JSONL log, or surfaced on resume. Only
|
|
@@ -5295,8 +5603,22 @@ var FileSessionWriter = class {
|
|
|
5295
5603
|
observeForSummary(event) {
|
|
5296
5604
|
if (event.type === "tool_use") {
|
|
5297
5605
|
this.openToolUses.add(event.id);
|
|
5606
|
+
} else if (event.type === "tool_call_start") {
|
|
5607
|
+
this.toolCallCount++;
|
|
5608
|
+
this.toolBreakdown[event.name] = (this.toolBreakdown[event.name] ?? 0) + 1;
|
|
5298
5609
|
} else if (event.type === "tool_result") {
|
|
5299
5610
|
this.openToolUses.delete(event.id);
|
|
5611
|
+
if (event.isError) {
|
|
5612
|
+
this.toolErrorCount++;
|
|
5613
|
+
this.outcome = "error";
|
|
5614
|
+
}
|
|
5615
|
+
} else if (event.type === "file_snapshot") {
|
|
5616
|
+
this.fileChangeCount += event.files.length;
|
|
5617
|
+
} else if (event.type === "compaction") {
|
|
5618
|
+
this.compactionCount++;
|
|
5619
|
+
}
|
|
5620
|
+
if (event.type === "error" || event.type === "provider_error") {
|
|
5621
|
+
this.outcome = "error";
|
|
5300
5622
|
}
|
|
5301
5623
|
if (event.type === "user_input" && this.summary.title === "(empty session)") {
|
|
5302
5624
|
this.summary = { ...this.summary, title: userInputTitle(event.content) };
|
|
@@ -5307,18 +5629,35 @@ var FileSessionWriter = class {
|
|
|
5307
5629
|
} else if (event.type === "session_end") {
|
|
5308
5630
|
const total = event.usage.input + event.usage.output;
|
|
5309
5631
|
if (total > 0) this.summary = { ...this.summary, tokenTotal: total };
|
|
5632
|
+
} else if (event.type === "in_flight_start") {
|
|
5633
|
+
this.iterationCount++;
|
|
5310
5634
|
}
|
|
5311
5635
|
}
|
|
5312
5636
|
async close() {
|
|
5313
5637
|
if (this.closing) return;
|
|
5314
5638
|
this.closing = true;
|
|
5315
5639
|
this.closed = true;
|
|
5640
|
+
this.summary = {
|
|
5641
|
+
...this.summary,
|
|
5642
|
+
endedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5643
|
+
iterationCount: this.iterationCount,
|
|
5644
|
+
toolCallCount: this.toolCallCount,
|
|
5645
|
+
toolErrorCount: this.toolErrorCount,
|
|
5646
|
+
fileChangeCount: this.fileChangeCount,
|
|
5647
|
+
compactionCount: this.compactionCount > 0 ? this.compactionCount : void 0,
|
|
5648
|
+
toolBreakdown: { ...this.toolBreakdown },
|
|
5649
|
+
outcome: this.outcome ?? "completed"
|
|
5650
|
+
};
|
|
5316
5651
|
if (this.manifestFile) {
|
|
5317
5652
|
try {
|
|
5318
5653
|
await atomicWrite(this.manifestFile, JSON.stringify(this.summary), { mode: 384 });
|
|
5319
5654
|
} catch {
|
|
5320
5655
|
}
|
|
5321
5656
|
}
|
|
5657
|
+
try {
|
|
5658
|
+
await this.onCloseCb?.(this.summary);
|
|
5659
|
+
} catch {
|
|
5660
|
+
}
|
|
5322
5661
|
try {
|
|
5323
5662
|
await this.handle.close();
|
|
5324
5663
|
} catch {
|
|
@@ -5360,7 +5699,7 @@ var FileSessionWriter = class {
|
|
|
5360
5699
|
let targetCheckpointLine = -1;
|
|
5361
5700
|
let afterTarget = false;
|
|
5362
5701
|
for (let i = 0; i < lines.length; i++) {
|
|
5363
|
-
const line = lines[i];
|
|
5702
|
+
const line = expectDefined10(lines[i]);
|
|
5364
5703
|
if (!line.trim()) continue;
|
|
5365
5704
|
let event;
|
|
5366
5705
|
try {
|
|
@@ -6497,8 +6836,11 @@ var SessionAnalyzer = class {
|
|
|
6497
6836
|
}
|
|
6498
6837
|
calcDuration(events) {
|
|
6499
6838
|
if (events.length < 2) return 0;
|
|
6500
|
-
const
|
|
6501
|
-
const
|
|
6839
|
+
const firstEvent = events[0];
|
|
6840
|
+
const lastEvent = events[events.length - 1];
|
|
6841
|
+
if (!firstEvent || !lastEvent) return 0;
|
|
6842
|
+
const first = new Date(firstEvent.ts).getTime();
|
|
6843
|
+
const last = new Date(lastEvent.ts).getTime();
|
|
6502
6844
|
return last - first;
|
|
6503
6845
|
}
|
|
6504
6846
|
};
|
|
@@ -7607,13 +7949,11 @@ function parseDescription(raw) {
|
|
|
7607
7949
|
const scope = [];
|
|
7608
7950
|
const coversMatch = /(?:covers|for|including)\s+([^.]+)/i.exec(desc);
|
|
7609
7951
|
if (coversMatch) {
|
|
7610
|
-
const items = coversMatch[1].replace(/[·•]/g, ",").split(",").map((s) => s.trim()).filter(Boolean);
|
|
7952
|
+
const items = coversMatch[1] ?? "".replace(/[·•]/g, ",").split(",").map((s) => s.trim()).filter(Boolean);
|
|
7611
7953
|
scope.push(...items);
|
|
7612
7954
|
}
|
|
7613
7955
|
return { trigger, scope };
|
|
7614
7956
|
}
|
|
7615
|
-
|
|
7616
|
-
// src/core/streaming-response-builder.ts
|
|
7617
7957
|
function buildResponse(state) {
|
|
7618
7958
|
const content = [];
|
|
7619
7959
|
for (const b of state.blockOrder) {
|
|
@@ -7672,7 +8012,7 @@ function handleContentBlockStart(state, ev) {
|
|
|
7672
8012
|
state.textBuffers.push("");
|
|
7673
8013
|
state.blockOrder.push({ kind: "text", idx: state.currentTextIndex });
|
|
7674
8014
|
} else if (kind === "tool_use") {
|
|
7675
|
-
const id = ev.id ??
|
|
8015
|
+
const id = ev.id ?? randomUUID();
|
|
7676
8016
|
state.tools.set(id, { name: ev.name ?? "unknown", partial: "" });
|
|
7677
8017
|
state.blockOrder.push({ kind: "tool", id });
|
|
7678
8018
|
state.currentTextIndex = -1;
|
|
@@ -8062,7 +8402,7 @@ var IntelligentCompactor = class {
|
|
|
8062
8402
|
maxTokens: 1024
|
|
8063
8403
|
};
|
|
8064
8404
|
const ac = ctx.signal ? void 0 : new AbortController();
|
|
8065
|
-
const signal = ctx.signal ?? ac
|
|
8405
|
+
const signal = ctx.signal ?? ac?.signal;
|
|
8066
8406
|
const res = await this.provider.complete(req, { signal });
|
|
8067
8407
|
const textBlocks = res.content.filter(isTextBlock);
|
|
8068
8408
|
return textBlocks.map((b) => b.text).join("\n").trim() || "(empty summary)";
|
|
@@ -8165,6 +8505,12 @@ var IntelligentCompactor = class {
|
|
|
8165
8505
|
};
|
|
8166
8506
|
|
|
8167
8507
|
// src/models/llm-selector.ts
|
|
8508
|
+
function expectDefined11(value) {
|
|
8509
|
+
if (value === null || value === void 0) {
|
|
8510
|
+
throw new Error("Expected value to be defined");
|
|
8511
|
+
}
|
|
8512
|
+
return value;
|
|
8513
|
+
}
|
|
8168
8514
|
var DEFAULT_SYSTEM_PROMPT = `You are a context pruning assistant. Given a conversation history and a token budget, decide which message ranges are worth keeping verbatim and which should be collapsed into summaries.
|
|
8169
8515
|
|
|
8170
8516
|
Output a JSON object with this structure:
|
|
@@ -8205,7 +8551,7 @@ function formatMessages(messages, maxChars = 8e3) {
|
|
|
8205
8551
|
const lines = [];
|
|
8206
8552
|
let used = 0;
|
|
8207
8553
|
for (let i = 0; i < messages.length; i++) {
|
|
8208
|
-
const m = messages[i];
|
|
8554
|
+
const m = expectDefined11(messages[i]);
|
|
8209
8555
|
const role = m.role.padEnd(10, " ");
|
|
8210
8556
|
let text;
|
|
8211
8557
|
if (typeof m.content === "string") {
|
|
@@ -8270,7 +8616,7 @@ IMPORTANT: Total conversation (${totalTokens} tokens) exceeds budget (${effectiv
|
|
|
8270
8616
|
let tokenCount = 0;
|
|
8271
8617
|
let startIdx = 0;
|
|
8272
8618
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
8273
|
-
const m = messages[i];
|
|
8619
|
+
const m = expectDefined11(messages[i]);
|
|
8274
8620
|
const cost = typeof m.content === "string" ? Math.ceil(m.content.length / 4) : m.content.reduce(
|
|
8275
8621
|
(acc, b) => acc + (b.type === "text" ? Math.ceil(b.text.length / 4) : Math.ceil(JSON.stringify(b).length / 4)),
|
|
8276
8622
|
0
|
|
@@ -8481,6 +8827,7 @@ Summarize the following message range:`;
|
|
|
8481
8827
|
let boundary = preserveIdx;
|
|
8482
8828
|
for (let i = preserveIdx; i < messages.length && i < preserveIdx + 6; i++) {
|
|
8483
8829
|
const m = messages[i];
|
|
8830
|
+
if (!m) continue;
|
|
8484
8831
|
if (m.role === "user" && this.hasTextContent(m)) {
|
|
8485
8832
|
boundary = i;
|
|
8486
8833
|
break;
|
|
@@ -9579,9 +9926,6 @@ ${recentJournal}` : "No prior iterations.",
|
|
|
9579
9926
|
await saveGoal(this.goalPath, { ...current, engineState: state });
|
|
9580
9927
|
}
|
|
9581
9928
|
};
|
|
9582
|
-
function sleep(ms) {
|
|
9583
|
-
return new Promise((resolve13) => setTimeout(resolve13, ms));
|
|
9584
|
-
}
|
|
9585
9929
|
|
|
9586
9930
|
// src/coordination/subagent-budget.ts
|
|
9587
9931
|
var BudgetExceededError = class extends Error {
|
|
@@ -9745,16 +10089,16 @@ var SubagentBudget = class _SubagentBudget {
|
|
|
9745
10089
|
}
|
|
9746
10090
|
if (exceeded.length === 0) return [];
|
|
9747
10091
|
if (!this._onThreshold) {
|
|
9748
|
-
const first2 = exceeded[0];
|
|
10092
|
+
const first2 = exceeded[0] ?? { kind: "iterations", limit: 0, used: 0 };
|
|
9749
10093
|
throw new BudgetExceededError(first2.kind, first2.limit, first2.used);
|
|
9750
10094
|
}
|
|
9751
10095
|
if (this._mode === "sync") {
|
|
9752
|
-
const first2 = exceeded[0];
|
|
10096
|
+
const first2 = exceeded[0] ?? { kind: "iterations", limit: 0, used: 0 };
|
|
9753
10097
|
throw new BudgetExceededError(first2.kind, first2.limit, first2.used);
|
|
9754
10098
|
}
|
|
9755
10099
|
const bus = this._events;
|
|
9756
10100
|
if (!bus || !bus.hasListenerFor("budget.threshold_reached")) {
|
|
9757
|
-
const first2 = exceeded[0];
|
|
10101
|
+
const first2 = exceeded[0] ?? { kind: "iterations", limit: 0, used: 0 };
|
|
9758
10102
|
throw new BudgetExceededError(first2.kind, first2.limit, first2.used);
|
|
9759
10103
|
}
|
|
9760
10104
|
for (const entry of exceeded) {
|
|
@@ -9762,8 +10106,9 @@ var SubagentBudget = class _SubagentBudget {
|
|
|
9762
10106
|
const decision2 = this._negotiateExtension(entry.kind, exceeded);
|
|
9763
10107
|
this._pendingNegotiations.set(entry.kind, decision2);
|
|
9764
10108
|
}
|
|
9765
|
-
const first = exceeded[0];
|
|
10109
|
+
const first = exceeded[0] ?? { kind: "iterations", limit: 0, used: 0 };
|
|
9766
10110
|
const decision = this._pendingNegotiations.get(first.kind);
|
|
10111
|
+
if (!decision) throw new Error(`No pending negotiation for ${first.kind}`);
|
|
9767
10112
|
throw new BudgetThresholdSignal(first.kind, first.limit, first.used, decision);
|
|
9768
10113
|
}
|
|
9769
10114
|
/**
|
|
@@ -9785,8 +10130,11 @@ var SubagentBudget = class _SubagentBudget {
|
|
|
9785
10130
|
* a fresh signal.
|
|
9786
10131
|
*/
|
|
9787
10132
|
async _negotiateExtension(kind, exceeded) {
|
|
10133
|
+
if (!this._onThreshold) {
|
|
10134
|
+
return "stop";
|
|
10135
|
+
}
|
|
9788
10136
|
try {
|
|
9789
|
-
const first = exceeded[0];
|
|
10137
|
+
const first = exceeded[0] ?? { kind: "iterations", limit: 0, used: 0 };
|
|
9790
10138
|
const result = this._onThreshold({
|
|
9791
10139
|
kind: first.kind,
|
|
9792
10140
|
used: first.used,
|
|
@@ -12269,6 +12617,11 @@ function getAgentDefinition(role) {
|
|
|
12269
12617
|
|
|
12270
12618
|
// src/coordination/dispatcher.ts
|
|
12271
12619
|
var DEFAULT_DISPATCH_ROLE = "executor";
|
|
12620
|
+
var FALLBACK_DEFINITION = {
|
|
12621
|
+
config: { role: "unknown", name: "Unknown Agent" },
|
|
12622
|
+
budget: {},
|
|
12623
|
+
capability: { phase: "meta", summary: "", keywords: [] }
|
|
12624
|
+
};
|
|
12272
12625
|
function normalize2(text) {
|
|
12273
12626
|
return ` ${text.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
|
|
12274
12627
|
}
|
|
@@ -12296,7 +12649,7 @@ function scoreAgents(task, catalog = AGENT_CATALOG) {
|
|
|
12296
12649
|
}
|
|
12297
12650
|
function heuristicConfidence(candidates) {
|
|
12298
12651
|
if (candidates.length === 0) return 0;
|
|
12299
|
-
const top = candidates[0]
|
|
12652
|
+
const top = candidates[0]?.score ?? 0;
|
|
12300
12653
|
const second = candidates[1]?.score ?? 0;
|
|
12301
12654
|
const strength = Math.min(1, top / 3);
|
|
12302
12655
|
const margin = (top - second + 1) / (top + 1);
|
|
@@ -12312,7 +12665,7 @@ async function dispatchAgent(task, opts = {}) {
|
|
|
12312
12665
|
if (top && confidence >= threshold) {
|
|
12313
12666
|
return {
|
|
12314
12667
|
role: top.role,
|
|
12315
|
-
definition: catalog[top.role],
|
|
12668
|
+
definition: catalog[top.role] ?? FALLBACK_DEFINITION,
|
|
12316
12669
|
confidence,
|
|
12317
12670
|
method: "heuristic",
|
|
12318
12671
|
reason: `Matched keywords: ${top.matched.slice(0, 4).join(", ")}`,
|
|
@@ -12320,7 +12673,7 @@ async function dispatchAgent(task, opts = {}) {
|
|
|
12320
12673
|
};
|
|
12321
12674
|
}
|
|
12322
12675
|
if (opts.classifier) {
|
|
12323
|
-
const pool = (candidates.length > 0 ? candidates.slice(0, maxCandidates).map((c) => catalog[c.role]) : ALL_AGENT_DEFINITIONS).map((d) => ({
|
|
12676
|
+
const pool = (candidates.length > 0 ? candidates.slice(0, maxCandidates).map((c) => catalog[c.role] ?? FALLBACK_DEFINITION) : ALL_AGENT_DEFINITIONS).map((d) => ({
|
|
12324
12677
|
role: d.config.role,
|
|
12325
12678
|
name: d.config.name,
|
|
12326
12679
|
summary: d.capability.summary
|
|
@@ -12330,7 +12683,7 @@ async function dispatchAgent(task, opts = {}) {
|
|
|
12330
12683
|
if (choice && catalog[choice.role]) {
|
|
12331
12684
|
return {
|
|
12332
12685
|
role: choice.role,
|
|
12333
|
-
definition: catalog[choice.role],
|
|
12686
|
+
definition: catalog[choice.role] ?? FALLBACK_DEFINITION,
|
|
12334
12687
|
confidence: 1,
|
|
12335
12688
|
method: "llm",
|
|
12336
12689
|
reason: choice.reason ?? "Selected by LLM classifier",
|
|
@@ -12343,17 +12696,17 @@ async function dispatchAgent(task, opts = {}) {
|
|
|
12343
12696
|
if (top) {
|
|
12344
12697
|
return {
|
|
12345
12698
|
role: top.role,
|
|
12346
|
-
definition: catalog[top.role],
|
|
12699
|
+
definition: catalog[top.role] ?? FALLBACK_DEFINITION,
|
|
12347
12700
|
confidence,
|
|
12348
12701
|
method: "heuristic",
|
|
12349
12702
|
reason: `Weak match (${top.matched.slice(0, 3).join(", ") || "low signal"})`,
|
|
12350
12703
|
alternatives: candidates.slice(1, maxCandidates)
|
|
12351
12704
|
};
|
|
12352
12705
|
}
|
|
12353
|
-
const fallbackRole = catalog[DEFAULT_DISPATCH_ROLE] ? DEFAULT_DISPATCH_ROLE : Object.keys(catalog)[0];
|
|
12706
|
+
const fallbackRole = catalog[DEFAULT_DISPATCH_ROLE] ? DEFAULT_DISPATCH_ROLE : Object.keys(catalog)[0] ?? DEFAULT_DISPATCH_ROLE;
|
|
12354
12707
|
return {
|
|
12355
12708
|
role: fallbackRole,
|
|
12356
|
-
definition: catalog[fallbackRole],
|
|
12709
|
+
definition: catalog[fallbackRole] ?? FALLBACK_DEFINITION,
|
|
12357
12710
|
confidence: 0,
|
|
12358
12711
|
method: "fallback",
|
|
12359
12712
|
reason: "No keyword signal; defaulting to the generalist Executor",
|
|
@@ -13166,6 +13519,7 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
|
|
|
13166
13519
|
takeNextDispatchableTask() {
|
|
13167
13520
|
for (let i = 0; i < this.pendingTasks.length; i++) {
|
|
13168
13521
|
const task = this.pendingTasks[i];
|
|
13522
|
+
if (!task) continue;
|
|
13169
13523
|
const subagentId = task.subagentId ? this.isIdleSubagent(task.subagentId) ? task.subagentId : null : this.findIdleSubagent();
|
|
13170
13524
|
if (!subagentId) continue;
|
|
13171
13525
|
this.pendingTasks.splice(i, 1);
|
|
@@ -13357,14 +13711,14 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
|
|
|
13357
13711
|
const idleExceeded = idleLimit !== void 0 && budget.idleMs() >= idleLimit;
|
|
13358
13712
|
if (idleExceeded && !wallExceeded) {
|
|
13359
13713
|
this.subagents.get(ctx.subagentId)?.abortController.abort();
|
|
13360
|
-
reject(new BudgetExceededError("timeout", idleLimit, budget.idleMs()));
|
|
13714
|
+
reject(new BudgetExceededError("timeout", idleLimit ?? 0, budget.idleMs()));
|
|
13361
13715
|
return;
|
|
13362
13716
|
}
|
|
13363
13717
|
if (!wallExceeded) {
|
|
13364
13718
|
scheduleNext();
|
|
13365
13719
|
return;
|
|
13366
13720
|
}
|
|
13367
|
-
const limit = wallLimit;
|
|
13721
|
+
const limit = wallLimit ?? 0;
|
|
13368
13722
|
if (!budget.onThreshold) {
|
|
13369
13723
|
this.subagents.get(ctx.subagentId)?.abortController.abort();
|
|
13370
13724
|
reject(new BudgetExceededError("timeout", limit, elapsed));
|
|
@@ -13523,8 +13877,11 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
|
|
|
13523
13877
|
};
|
|
13524
13878
|
|
|
13525
13879
|
// src/execution/parallel-eternal-engine.ts
|
|
13526
|
-
function
|
|
13527
|
-
|
|
13880
|
+
function expectDefined12(value) {
|
|
13881
|
+
if (value === null || value === void 0) {
|
|
13882
|
+
throw new Error("Expected value to be defined");
|
|
13883
|
+
}
|
|
13884
|
+
return value;
|
|
13528
13885
|
}
|
|
13529
13886
|
var GOAL_COMPLETE_MARKER2 = /^\s*\[goal[_\s-]?complete\]\s*$/im;
|
|
13530
13887
|
var ParallelEternalEngine = class {
|
|
@@ -13600,7 +13957,7 @@ var ParallelEternalEngine = class {
|
|
|
13600
13957
|
);
|
|
13601
13958
|
}
|
|
13602
13959
|
if (this.stopRequested) break;
|
|
13603
|
-
await
|
|
13960
|
+
await sleep(2e3);
|
|
13604
13961
|
}
|
|
13605
13962
|
} finally {
|
|
13606
13963
|
this.state = "stopped";
|
|
@@ -13681,7 +14038,7 @@ var ParallelEternalEngine = class {
|
|
|
13681
14038
|
// Fan-out
|
|
13682
14039
|
// -------------------------------------------------------------------------
|
|
13683
14040
|
async fanOut(goal, tasks) {
|
|
13684
|
-
const coordinator = this.coordinator;
|
|
14041
|
+
const coordinator = expectDefined12(this.coordinator);
|
|
13685
14042
|
const slotCount = Math.min(this.slots, tasks.length);
|
|
13686
14043
|
const routes = this.dispatchEnabled ? await Promise.all(
|
|
13687
14044
|
tasks.slice(0, slotCount).map(
|
|
@@ -13713,7 +14070,7 @@ ${recentJournal}` : "No prior iterations.",
|
|
|
13713
14070
|
const routeInfo = [];
|
|
13714
14071
|
const spawnPromises = [];
|
|
13715
14072
|
for (let i = 0; i < slotCount; i++) {
|
|
13716
|
-
const task = tasks[i];
|
|
14073
|
+
const task = expectDefined12(tasks[i]);
|
|
13717
14074
|
const route = routes[i] ?? null;
|
|
13718
14075
|
const subagentId = `parallel-${this.iterations}-${i}`;
|
|
13719
14076
|
const taskId = randomUUID();
|
|
@@ -14216,7 +14573,7 @@ var CollabSession = class extends EventEmitter {
|
|
|
14216
14573
|
this.emit("session.error", error);
|
|
14217
14574
|
throw error;
|
|
14218
14575
|
}
|
|
14219
|
-
for (const result of results
|
|
14576
|
+
for (const result of results?.flat() ?? []) {
|
|
14220
14577
|
await this.parseAndEmit(result);
|
|
14221
14578
|
}
|
|
14222
14579
|
const report = this.assembleReport();
|
|
@@ -14277,7 +14634,7 @@ var CollabSession = class extends EventEmitter {
|
|
|
14277
14634
|
}
|
|
14278
14635
|
budgetForRole(role) {
|
|
14279
14636
|
if (this.options.budgetOverrides?.[role]) {
|
|
14280
|
-
return this.options.budgetOverrides[role];
|
|
14637
|
+
return this.options.budgetOverrides[role] ?? { maxIterations: 0, maxToolCalls: 0, timeoutMs: 0 };
|
|
14281
14638
|
}
|
|
14282
14639
|
const defaults = {
|
|
14283
14640
|
"bug-hunter": { maxIterations: 2e3, maxToolCalls: 5e3, timeoutMs: 10 * 60 * 1e3 },
|
|
@@ -14730,7 +15087,7 @@ function makeSpawnTool(director, roster) {
|
|
|
14730
15087
|
});
|
|
14731
15088
|
const dispatchRole = dispatchResult.role;
|
|
14732
15089
|
if (roster?.[dispatchRole]) {
|
|
14733
|
-
cfg = instantiateRosterConfig(dispatchRole, roster[dispatchRole]);
|
|
15090
|
+
cfg = instantiateRosterConfig(dispatchRole, roster[dispatchRole] ?? {});
|
|
14734
15091
|
} else {
|
|
14735
15092
|
const def = dispatchResult.definition;
|
|
14736
15093
|
cfg = {
|
|
@@ -17039,7 +17396,10 @@ function attachAutoExtend(events, policy = {}) {
|
|
|
17039
17396
|
if (kind === "timeout" || kind === "idle_timeout") {
|
|
17040
17397
|
if (progress > lastTimeoutProgress) {
|
|
17041
17398
|
lastTimeoutProgress = progress;
|
|
17042
|
-
const next2 = Math.min(
|
|
17399
|
+
const next2 = Math.min(
|
|
17400
|
+
Math.ceil(limit * (1 + factor)),
|
|
17401
|
+
ceiling.timeoutMs ?? DEFAULT_CEILING.timeoutMs
|
|
17402
|
+
);
|
|
17043
17403
|
extend({ timeoutMs: next2 });
|
|
17044
17404
|
} else {
|
|
17045
17405
|
deny();
|
|
@@ -17053,7 +17413,7 @@ function attachAutoExtend(events, policy = {}) {
|
|
|
17053
17413
|
}
|
|
17054
17414
|
extendCounts.set(kind, count + 1);
|
|
17055
17415
|
const field = FIELD_BY_KIND[kind];
|
|
17056
|
-
const cap = ceiling[field];
|
|
17416
|
+
const cap = ceiling[field] ?? DEFAULT_CEILING[field];
|
|
17057
17417
|
const next = Math.min(Math.ceil(limit * (1 + factor)), cap);
|
|
17058
17418
|
extend({ [field]: next });
|
|
17059
17419
|
})
|
|
@@ -17698,7 +18058,7 @@ var TaskTracker = class {
|
|
|
17698
18058
|
if (filter.type?.length && !filter.type.includes(n.type)) return false;
|
|
17699
18059
|
if (filter.assignee?.length && n.assignee && !filter.assignee.includes(n.assignee))
|
|
17700
18060
|
return false;
|
|
17701
|
-
if (filter.tags?.length && n.tags && !n.tags.some((t2) => filter.tags
|
|
18061
|
+
if (filter.tags?.length && n.tags && !n.tags.some((t2) => filter.tags?.includes(t2)))
|
|
17702
18062
|
return false;
|
|
17703
18063
|
if (filter.specRequirementId && n.specRequirementId !== filter.specRequirementId)
|
|
17704
18064
|
return false;
|
|
@@ -18212,6 +18572,12 @@ var TaskGraphStore = class {
|
|
|
18212
18572
|
};
|
|
18213
18573
|
|
|
18214
18574
|
// src/sdd/spec-builder.ts
|
|
18575
|
+
function expectDefined13(value) {
|
|
18576
|
+
if (value === null || value === void 0) {
|
|
18577
|
+
throw new Error("Expected value to be defined");
|
|
18578
|
+
}
|
|
18579
|
+
return value;
|
|
18580
|
+
}
|
|
18215
18581
|
function buildQuestioningPrompt(session, min, max) {
|
|
18216
18582
|
const answered = session.answers.length;
|
|
18217
18583
|
const remaining = Math.max(0, min - answered);
|
|
@@ -18257,7 +18623,7 @@ function buildQuestioningPrompt(session, min, max) {
|
|
|
18257
18623
|
if (answered > 0) {
|
|
18258
18624
|
lines.push("", "**Conversation so far:**");
|
|
18259
18625
|
for (let i = 0; i < answered; i++) {
|
|
18260
|
-
const a = session.answers[i];
|
|
18626
|
+
const a = expectDefined13(session.answers[i]);
|
|
18261
18627
|
lines.push(``, `Q${i + 1}: ${a.question}`, `A${i + 1}: ${a.answer}`);
|
|
18262
18628
|
}
|
|
18263
18629
|
}
|
|
@@ -18999,6 +19365,12 @@ function truncate2(str, maxLen) {
|
|
|
18999
19365
|
}
|
|
19000
19366
|
|
|
19001
19367
|
// src/sdd/critical-path.ts
|
|
19368
|
+
function expectDefined14(value) {
|
|
19369
|
+
if (value === null || value === void 0) {
|
|
19370
|
+
throw new Error("Expected value to be defined");
|
|
19371
|
+
}
|
|
19372
|
+
return value;
|
|
19373
|
+
}
|
|
19002
19374
|
function analyzeCriticalPath(graph) {
|
|
19003
19375
|
const nodes = Array.from(graph.nodes.values());
|
|
19004
19376
|
const topoOrder = topologicalSort(graph);
|
|
@@ -19007,9 +19379,9 @@ function analyzeCriticalPath(graph) {
|
|
|
19007
19379
|
for (const edge of graph.edges) {
|
|
19008
19380
|
if (edge.type === "depends_on") {
|
|
19009
19381
|
if (!blockedByMap.has(edge.from)) blockedByMap.set(edge.from, /* @__PURE__ */ new Set());
|
|
19010
|
-
blockedByMap.get(edge.from)
|
|
19382
|
+
blockedByMap.get(edge.from)?.add(edge.to);
|
|
19011
19383
|
if (!blocksMap.has(edge.to)) blocksMap.set(edge.to, /* @__PURE__ */ new Set());
|
|
19012
|
-
blocksMap.get(edge.to)
|
|
19384
|
+
blocksMap.get(edge.to)?.add(edge.from);
|
|
19013
19385
|
}
|
|
19014
19386
|
}
|
|
19015
19387
|
const readyTasks = [];
|
|
@@ -19074,7 +19446,7 @@ function getTransitiveBlocked(_graph, taskId, blocksMap) {
|
|
|
19074
19446
|
const visited = /* @__PURE__ */ new Set();
|
|
19075
19447
|
const queue = [taskId];
|
|
19076
19448
|
while (queue.length > 0) {
|
|
19077
|
-
const current = queue.shift();
|
|
19449
|
+
const current = expectDefined14(queue.shift());
|
|
19078
19450
|
const blocked = blocksMap.get(current);
|
|
19079
19451
|
if (!blocked) continue;
|
|
19080
19452
|
for (const id of blocked) {
|
|
@@ -19099,7 +19471,7 @@ function computeCriticalPath(graph, _topoOrder, blockedByMap) {
|
|
|
19099
19471
|
for (const [taskId, blockers] of blockedByMap) {
|
|
19100
19472
|
for (const blockerId of blockers) {
|
|
19101
19473
|
if (!blocksMap.has(blockerId)) blocksMap.set(blockerId, /* @__PURE__ */ new Set());
|
|
19102
|
-
blocksMap.get(blockerId)
|
|
19474
|
+
blocksMap.get(blockerId)?.add(taskId);
|
|
19103
19475
|
}
|
|
19104
19476
|
}
|
|
19105
19477
|
const n = allIds.length;
|
|
@@ -19120,7 +19492,7 @@ function computeCriticalPath(graph, _topoOrder, blockedByMap) {
|
|
|
19120
19492
|
if (!changed) break;
|
|
19121
19493
|
}
|
|
19122
19494
|
let maxDist = 0;
|
|
19123
|
-
let maxId = allIds[0];
|
|
19495
|
+
let maxId = expectDefined14(allIds[0]);
|
|
19124
19496
|
for (const id of allIds) {
|
|
19125
19497
|
const d = dist.get(id) ?? 0;
|
|
19126
19498
|
if (d > maxDist) {
|
|
@@ -19589,6 +19961,12 @@ var SddTaskDecomposer = class {
|
|
|
19589
19961
|
return nodes.some((n) => n.status === "blocked");
|
|
19590
19962
|
}
|
|
19591
19963
|
};
|
|
19964
|
+
function expectDefined15(value) {
|
|
19965
|
+
if (value === null || value === void 0) {
|
|
19966
|
+
throw new Error("Expected value to be defined");
|
|
19967
|
+
}
|
|
19968
|
+
return value;
|
|
19969
|
+
}
|
|
19592
19970
|
var SddParallelRun = class {
|
|
19593
19971
|
constructor(opts) {
|
|
19594
19972
|
this.opts = opts;
|
|
@@ -19689,8 +20067,10 @@ var SddParallelRun = class {
|
|
|
19689
20067
|
"\u2022 Do not ask before routine in-project tool use; if a permission gate appears, wait for that flow.",
|
|
19690
20068
|
"\u2022 Keep output concise \u2014 summarize changes, do not transcribe files."
|
|
19691
20069
|
].join("\n");
|
|
20070
|
+
if (!this.coordinator) throw new Error("SDD parallel runner requires a coordinator");
|
|
20071
|
+
const coordinator = this.coordinator;
|
|
19692
20072
|
const spawns = subagentIds.map(
|
|
19693
|
-
(subagentId) =>
|
|
20073
|
+
(subagentId) => coordinator.spawn({
|
|
19694
20074
|
id: subagentId,
|
|
19695
20075
|
name: subagentId,
|
|
19696
20076
|
role: "executor",
|
|
@@ -19698,12 +20078,12 @@ var SddParallelRun = class {
|
|
|
19698
20078
|
})
|
|
19699
20079
|
);
|
|
19700
20080
|
const spawnResults = await Promise.all(spawns);
|
|
19701
|
-
if (!spawnResults.every((r) => r.subagentId)) {
|
|
20081
|
+
if (!spawnResults.every((r) => Boolean(r.subagentId))) {
|
|
19702
20082
|
throw new Error("One or more subagent spawns failed");
|
|
19703
20083
|
}
|
|
19704
20084
|
const assignPromises = tasks.map((task, i) => {
|
|
19705
20085
|
const spec = {
|
|
19706
|
-
id: taskIds[i],
|
|
20086
|
+
id: taskIds[i] ?? task.id,
|
|
19707
20087
|
description: [
|
|
19708
20088
|
directivePreamble,
|
|
19709
20089
|
"",
|
|
@@ -19712,15 +20092,15 @@ var SddParallelRun = class {
|
|
|
19712
20092
|
"",
|
|
19713
20093
|
task.description
|
|
19714
20094
|
].join("\n"),
|
|
19715
|
-
subagentId: subagentIds[i],
|
|
20095
|
+
subagentId: subagentIds[i] ?? spawnResults[i]?.subagentId ?? task.id,
|
|
19716
20096
|
timeoutMs: this.timeoutMs
|
|
19717
20097
|
};
|
|
19718
|
-
return this.coordinator
|
|
20098
|
+
return this.coordinator?.assign(spec);
|
|
19719
20099
|
});
|
|
19720
20100
|
await Promise.all(assignPromises);
|
|
19721
20101
|
let results;
|
|
19722
20102
|
try {
|
|
19723
|
-
results = await
|
|
20103
|
+
results = await coordinator.awaitTasks(taskIds);
|
|
19724
20104
|
} catch (err) {
|
|
19725
20105
|
results = taskIds.map((id) => ({
|
|
19726
20106
|
subagentId: "",
|
|
@@ -19735,8 +20115,8 @@ var SddParallelRun = class {
|
|
|
19735
20115
|
const successCount = results.filter((r) => r.status === "success").length;
|
|
19736
20116
|
const failCount = results.length - successCount;
|
|
19737
20117
|
for (let i = 0; i < results.length; i++) {
|
|
19738
|
-
const result = results[i];
|
|
19739
|
-
const taskId = taskIds[i];
|
|
20118
|
+
const result = expectDefined15(results[i]);
|
|
20119
|
+
const taskId = expectDefined15(taskIds[i]);
|
|
19740
20120
|
if (result.status === "success") {
|
|
19741
20121
|
this.opts.tracker.updateNodeStatus(taskId, "completed");
|
|
19742
20122
|
} else {
|
|
@@ -20843,6 +21223,12 @@ var allServers = () => ({
|
|
|
20843
21223
|
"zai-vision": { ...zaiVisionServer(), enabled: false },
|
|
20844
21224
|
"minimax-vision": { ...miniMaxVisionServer(), enabled: false }
|
|
20845
21225
|
});
|
|
21226
|
+
function expectDefined16(value) {
|
|
21227
|
+
if (value === null || value === void 0) {
|
|
21228
|
+
throw new Error("Expected value to be defined");
|
|
21229
|
+
}
|
|
21230
|
+
return value;
|
|
21231
|
+
}
|
|
20846
21232
|
function parseSkillRef(input) {
|
|
20847
21233
|
const trimmed = input.trim().replace(/^https?:\/\/github\.com\//, "").replace(/\.git$/, "");
|
|
20848
21234
|
const atIdx = trimmed.indexOf("@");
|
|
@@ -20859,7 +21245,7 @@ function parseSkillRef(input) {
|
|
|
20859
21245
|
if (parts.length < 2) {
|
|
20860
21246
|
throw new Error(`Invalid skill reference "${input}". Expected format: user/repo or user/repo@ref`);
|
|
20861
21247
|
}
|
|
20862
|
-
return { owner: parts[0], repo: parts[1], ref };
|
|
21248
|
+
return { owner: expectDefined16(parts[0]), repo: expectDefined16(parts[1]), ref };
|
|
20863
21249
|
}
|
|
20864
21250
|
var MAX_TARBALL_SIZE = 50 * 1024 * 1024;
|
|
20865
21251
|
async function downloadGitHubTarball(parsed) {
|
|
@@ -21028,6 +21414,12 @@ var SkillManifestStore = class {
|
|
|
21028
21414
|
};
|
|
21029
21415
|
|
|
21030
21416
|
// src/skills/skill-installer.ts
|
|
21417
|
+
function expectDefined17(value) {
|
|
21418
|
+
if (value === null || value === void 0) {
|
|
21419
|
+
throw new Error("Expected value to be defined");
|
|
21420
|
+
}
|
|
21421
|
+
return value;
|
|
21422
|
+
}
|
|
21031
21423
|
var MAX_SKILL_FILE_SIZE = 100 * 1024;
|
|
21032
21424
|
var SkillInstaller = class {
|
|
21033
21425
|
opts;
|
|
@@ -21149,10 +21541,10 @@ var SkillInstaller = class {
|
|
|
21149
21541
|
for (const entry of targets) {
|
|
21150
21542
|
const key = `${entry.source}@${entry.ref}`;
|
|
21151
21543
|
if (!bySource.has(key)) bySource.set(key, []);
|
|
21152
|
-
bySource.get(key)
|
|
21544
|
+
bySource.get(key)?.push(entry);
|
|
21153
21545
|
}
|
|
21154
21546
|
for (const [, entries] of bySource) {
|
|
21155
|
-
const first = entries[0];
|
|
21547
|
+
const first = expectDefined17(entries[0]);
|
|
21156
21548
|
const scope = first.scope;
|
|
21157
21549
|
const isGlobal = scope === "user";
|
|
21158
21550
|
try {
|
|
@@ -21322,6 +21714,12 @@ async function collectFiles(dir, baseDir2) {
|
|
|
21322
21714
|
|
|
21323
21715
|
// src/storage/annotations-store.ts
|
|
21324
21716
|
init_atomic_write();
|
|
21717
|
+
function expectDefined18(value) {
|
|
21718
|
+
if (value === null || value === void 0) {
|
|
21719
|
+
throw new Error("Expected value to be defined");
|
|
21720
|
+
}
|
|
21721
|
+
return value;
|
|
21722
|
+
}
|
|
21325
21723
|
var FILE_VERSION = 1;
|
|
21326
21724
|
var MAX_TEXT_LENGTH = 2e3;
|
|
21327
21725
|
var MAX_ANNOTATIONS = 1e3;
|
|
@@ -21413,7 +21811,7 @@ var AnnotationsStore = class {
|
|
|
21413
21811
|
return;
|
|
21414
21812
|
}
|
|
21415
21813
|
const next = {
|
|
21416
|
-
...all[idx],
|
|
21814
|
+
...expectDefined18(all[idx]),
|
|
21417
21815
|
resolved: true,
|
|
21418
21816
|
resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
21419
21817
|
resolvedBy: input.resolvedBy
|
|
@@ -21649,6 +22047,12 @@ var ReplayLogStore = class {
|
|
|
21649
22047
|
return next;
|
|
21650
22048
|
}
|
|
21651
22049
|
};
|
|
22050
|
+
function expectDefined19(value) {
|
|
22051
|
+
if (value === null || value === void 0) {
|
|
22052
|
+
throw new Error("Expected value to be defined");
|
|
22053
|
+
}
|
|
22054
|
+
return value;
|
|
22055
|
+
}
|
|
21652
22056
|
var SessionRecovery = class {
|
|
21653
22057
|
constructor(dir) {
|
|
21654
22058
|
this.dir = dir;
|
|
@@ -21689,7 +22093,7 @@ var SessionRecovery = class {
|
|
|
21689
22093
|
const lines = raw.split("\n").filter((l) => l.trim());
|
|
21690
22094
|
for (let i = lines.length - 1; i >= 0; i--) {
|
|
21691
22095
|
try {
|
|
21692
|
-
const ev = JSON.parse(lines[i]);
|
|
22096
|
+
const ev = JSON.parse(expectDefined19(lines[i]));
|
|
21693
22097
|
if (ev.type === "in_flight_start") {
|
|
21694
22098
|
return {
|
|
21695
22099
|
sessionId,
|
|
@@ -21741,13 +22145,13 @@ var SessionRecovery = class {
|
|
|
21741
22145
|
let lastCheckpoint = null;
|
|
21742
22146
|
let lastCheckpointIdx = -1;
|
|
21743
22147
|
for (let i = 0; i < events.length; i++) {
|
|
21744
|
-
if (events[i]
|
|
21745
|
-
lastCheckpoint = events[i];
|
|
22148
|
+
if (events[i]?.type === "checkpoint") {
|
|
22149
|
+
lastCheckpoint = expectDefined19(events[i]);
|
|
21746
22150
|
lastCheckpointIdx = i;
|
|
21747
22151
|
}
|
|
21748
22152
|
}
|
|
21749
22153
|
const pendingEvents = lastCheckpointIdx >= 0 ? events.slice(lastCheckpointIdx + 1) : events;
|
|
21750
|
-
const lastEv = events[events.length - 1];
|
|
22154
|
+
const lastEv = expectDefined19(events[events.length - 1]);
|
|
21751
22155
|
const inFlightStart = lastEv.type === "in_flight_start" ? lastEv : null;
|
|
21752
22156
|
const context = inFlightStart && inFlightStart.type === "in_flight_start" ? inFlightStart.context : null;
|
|
21753
22157
|
return {
|
|
@@ -21790,6 +22194,12 @@ var SessionRecovery = class {
|
|
|
21790
22194
|
return path6.join(this.dir, `${sessionId}.jsonl`);
|
|
21791
22195
|
}
|
|
21792
22196
|
};
|
|
22197
|
+
function expectDefined20(value) {
|
|
22198
|
+
if (value === null || value === void 0) {
|
|
22199
|
+
throw new Error("Expected value to be defined");
|
|
22200
|
+
}
|
|
22201
|
+
return value;
|
|
22202
|
+
}
|
|
21793
22203
|
var GENESIS_PREV = "0".repeat(64);
|
|
21794
22204
|
var DEFAULT_FSYNC_EVERY = 100;
|
|
21795
22205
|
var ToolAuditLog = class {
|
|
@@ -21856,7 +22266,7 @@ var ToolAuditLog = class {
|
|
|
21856
22266
|
async verify(sessionId) {
|
|
21857
22267
|
const entries = await this.readAll(sessionId);
|
|
21858
22268
|
if (entries.length === 0) return { ok: true, entries: 0 };
|
|
21859
|
-
if (entries[0]
|
|
22269
|
+
if (entries[0]?.prevHash !== GENESIS_PREV) {
|
|
21860
22270
|
return {
|
|
21861
22271
|
ok: false,
|
|
21862
22272
|
brokenAt: 0,
|
|
@@ -21865,7 +22275,7 @@ var ToolAuditLog = class {
|
|
|
21865
22275
|
}
|
|
21866
22276
|
let prevHash = GENESIS_PREV;
|
|
21867
22277
|
for (let i = 0; i < entries.length; i++) {
|
|
21868
|
-
const e = entries[i];
|
|
22278
|
+
const e = expectDefined20(entries[i]);
|
|
21869
22279
|
if (e.prevHash !== prevHash) {
|
|
21870
22280
|
return {
|
|
21871
22281
|
ok: false,
|
|
@@ -21984,6 +22394,12 @@ function sortKeys2(value) {
|
|
|
21984
22394
|
|
|
21985
22395
|
// src/storage/session-rewinder.ts
|
|
21986
22396
|
init_atomic_write();
|
|
22397
|
+
function expectDefined21(value) {
|
|
22398
|
+
if (value === null || value === void 0) {
|
|
22399
|
+
throw new Error("Expected value to be defined");
|
|
22400
|
+
}
|
|
22401
|
+
return value;
|
|
22402
|
+
}
|
|
21987
22403
|
var DefaultSessionRewinder = class {
|
|
21988
22404
|
constructor(sessionsDir, projectRoot) {
|
|
21989
22405
|
this.sessionsDir = sessionsDir;
|
|
@@ -22022,7 +22438,7 @@ var DefaultSessionRewinder = class {
|
|
|
22022
22438
|
const events = parseEvents(raw);
|
|
22023
22439
|
let targetIdx = -1;
|
|
22024
22440
|
for (let i = 0; i < events.length; i++) {
|
|
22025
|
-
const event = events[i];
|
|
22441
|
+
const event = expectDefined21(events[i]);
|
|
22026
22442
|
if (event.type === "checkpoint") {
|
|
22027
22443
|
const checkpointEvent = event;
|
|
22028
22444
|
if (checkpointEvent.promptIndex === checkpointIndex) {
|
|
@@ -22036,7 +22452,7 @@ var DefaultSessionRewinder = class {
|
|
|
22036
22452
|
}
|
|
22037
22453
|
const snapshotsToRevert = [];
|
|
22038
22454
|
for (let i = targetIdx + 1; i < events.length; i++) {
|
|
22039
|
-
const event = events[i];
|
|
22455
|
+
const event = expectDefined21(events[i]);
|
|
22040
22456
|
if (event.type === "checkpoint") {
|
|
22041
22457
|
break;
|
|
22042
22458
|
}
|
|
@@ -22218,6 +22634,12 @@ var DefaultPromptStore = class {
|
|
|
22218
22634
|
};
|
|
22219
22635
|
}
|
|
22220
22636
|
};
|
|
22637
|
+
function expectDefined22(value) {
|
|
22638
|
+
if (value === null || value === void 0) {
|
|
22639
|
+
throw new Error("Expected value to be defined");
|
|
22640
|
+
}
|
|
22641
|
+
return value;
|
|
22642
|
+
}
|
|
22221
22643
|
var ALL_SYNC_CATEGORIES = ["settings", "skills", "prompts", "memory", "history"];
|
|
22222
22644
|
var CloudSync = class {
|
|
22223
22645
|
constructor(paths, getConfig, setConfig) {
|
|
@@ -22260,8 +22682,8 @@ var CloudSync = class {
|
|
|
22260
22682
|
const cfg = this.getConfig();
|
|
22261
22683
|
if (!cfg?.enabled) return { ok: false, action: "push", categories: [], message: "Not enabled." };
|
|
22262
22684
|
const parts = cfg.repo.split("/");
|
|
22263
|
-
const owner = parts[0];
|
|
22264
|
-
const repoName = parts[1];
|
|
22685
|
+
const owner = expectDefined22(parts[0]);
|
|
22686
|
+
const repoName = expectDefined22(parts[1]);
|
|
22265
22687
|
const branch = "main";
|
|
22266
22688
|
const baseTreeSha = this.state?.sha;
|
|
22267
22689
|
const { treeEntries, rev } = await this.buildLocalTree(cfg.categories);
|
|
@@ -22313,8 +22735,8 @@ var CloudSync = class {
|
|
|
22313
22735
|
const cfg = this.getConfig();
|
|
22314
22736
|
if (!cfg?.enabled) return { ok: false, action: "pull", categories: [], message: "Not enabled." };
|
|
22315
22737
|
const pullParts = cfg.repo.split("/");
|
|
22316
|
-
const owner = pullParts[0];
|
|
22317
|
-
const repoName = pullParts[1];
|
|
22738
|
+
const owner = expectDefined22(pullParts[0]);
|
|
22739
|
+
const repoName = expectDefined22(pullParts[1]);
|
|
22318
22740
|
const branchData = await this.getRef(token, owner, repoName, "main");
|
|
22319
22741
|
const currentSha = branchData.object.sha;
|
|
22320
22742
|
const commitData = await this.getCommit(token, owner, repoName, currentSha);
|
|
@@ -22369,7 +22791,7 @@ var CloudSync = class {
|
|
|
22369
22791
|
// ── GitHub API helpers ──────────────────────────────────────────────
|
|
22370
22792
|
async githubFetch(token, owner, repo, method, pathSegment, body) {
|
|
22371
22793
|
const url = `https://api.github.com/repos/${owner}/${repo}${pathSegment}`;
|
|
22372
|
-
const
|
|
22794
|
+
const init = {
|
|
22373
22795
|
signal: AbortSignal.timeout(15e3),
|
|
22374
22796
|
method,
|
|
22375
22797
|
headers: {
|
|
@@ -22377,9 +22799,10 @@ var CloudSync = class {
|
|
|
22377
22799
|
Accept: "application/vnd.github+json",
|
|
22378
22800
|
"X-GitHub-Api-Version": "2022-11-28",
|
|
22379
22801
|
"Content-Type": "application/json"
|
|
22380
|
-
}
|
|
22381
|
-
|
|
22382
|
-
|
|
22802
|
+
}
|
|
22803
|
+
};
|
|
22804
|
+
if (body !== void 0) init.body = JSON.stringify(body);
|
|
22805
|
+
const res = await fetch(url, init);
|
|
22383
22806
|
if (!res.ok) {
|
|
22384
22807
|
const errText = await res.text();
|
|
22385
22808
|
throw new Error(`GitHub API ${method} ${pathSegment} failed (${res.status}): ${errText}`);
|
|
@@ -23514,7 +23937,7 @@ var ReportGenerator = class {
|
|
|
23514
23937
|
if (groups[finding.category] === void 0) {
|
|
23515
23938
|
groups[finding.category] = [];
|
|
23516
23939
|
}
|
|
23517
|
-
groups[finding.category]
|
|
23940
|
+
groups[finding.category]?.push(finding);
|
|
23518
23941
|
}
|
|
23519
23942
|
return groups;
|
|
23520
23943
|
}
|
|
@@ -23659,6 +24082,12 @@ var defaultGitignoreUpdater = new GitignoreUpdater();
|
|
|
23659
24082
|
|
|
23660
24083
|
// src/security-scanner/orchestrator.ts
|
|
23661
24084
|
init_atomic_write();
|
|
24085
|
+
function expectDefined23(value) {
|
|
24086
|
+
if (value === null || value === void 0) {
|
|
24087
|
+
throw new Error("Expected value to be defined");
|
|
24088
|
+
}
|
|
24089
|
+
return value;
|
|
24090
|
+
}
|
|
23662
24091
|
var SecurityScannerOrchestrator = class {
|
|
23663
24092
|
constructor(retryPolicy, errorHandler) {
|
|
23664
24093
|
this.retryPolicy = retryPolicy;
|
|
@@ -23708,7 +24137,7 @@ var SecurityScannerOrchestrator = class {
|
|
|
23708
24137
|
if (detectionResult.detectedStacks.length === 0) {
|
|
23709
24138
|
throw new Error(`No supported tech stack detected in ${projectRoot}`);
|
|
23710
24139
|
}
|
|
23711
|
-
const techStack = detectionResult.detectedStacks[0];
|
|
24140
|
+
const techStack = expectDefined23(detectionResult.detectedStacks[0]);
|
|
23712
24141
|
const generatedSkill = await this.generateSkillLLM(provider, model, projectRoot, techStack);
|
|
23713
24142
|
const scanResult = await this.scanWithLLM(provider, model, projectRoot, generatedSkill, techStack, options);
|
|
23714
24143
|
const synthesizedReport = await this.synthesizeReportLLM(provider, model, projectRoot, techStack, scanResult);
|
|
@@ -23789,7 +24218,7 @@ Return ONLY the JSON object, no markdown, no explanation.`;
|
|
|
23789
24218
|
const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("");
|
|
23790
24219
|
const jsonMatch = text.match(/\{[\s\S]*\}/);
|
|
23791
24220
|
if (jsonMatch) {
|
|
23792
|
-
const sanitized = sanitizeJsonString(jsonMatch[0]) || jsonMatch[0];
|
|
24221
|
+
const sanitized = sanitizeJsonString(expectDefined23(jsonMatch[0])) || expectDefined23(jsonMatch[0]);
|
|
23793
24222
|
const skillData = JSON.parse(sanitized);
|
|
23794
24223
|
return {
|
|
23795
24224
|
name: skillData.name || `security-scanner-${techStack.stack}`,
|
|
@@ -23909,7 +24338,7 @@ Return ONLY the JSON array. If no issues found, return [].`;
|
|
|
23909
24338
|
const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("");
|
|
23910
24339
|
const jsonMatch = text.match(/\[[\s\S]*\]/);
|
|
23911
24340
|
if (jsonMatch) {
|
|
23912
|
-
const sanitized = sanitizeJsonString(jsonMatch[0]) || jsonMatch[0];
|
|
24341
|
+
const sanitized = sanitizeJsonString(expectDefined23(jsonMatch[0])) || expectDefined23(jsonMatch[0]);
|
|
23913
24342
|
const parsed = JSON.parse(sanitized);
|
|
23914
24343
|
return parsed.map((item, idx) => ({
|
|
23915
24344
|
id: `llm-finding-${idx}-${Date.now()}`,
|
|
@@ -24149,7 +24578,7 @@ ${dirs.join(", ")}`);
|
|
|
24149
24578
|
if (detectionResult.detectedStacks.length === 0) {
|
|
24150
24579
|
throw new Error(`No supported tech stack detected in ${projectRoot}`);
|
|
24151
24580
|
}
|
|
24152
|
-
const techStack = detectionResult.detectedStacks[0];
|
|
24581
|
+
const techStack = expectDefined23(detectionResult.detectedStacks[0]);
|
|
24153
24582
|
return {
|
|
24154
24583
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
24155
24584
|
projectRoot,
|
|
@@ -24757,6 +25186,12 @@ var FleetManager = class {
|
|
|
24757
25186
|
this.usage.dispose();
|
|
24758
25187
|
}
|
|
24759
25188
|
};
|
|
25189
|
+
function expectDefined24(value) {
|
|
25190
|
+
if (value === null || value === void 0) {
|
|
25191
|
+
throw new Error("Expected value to be defined");
|
|
25192
|
+
}
|
|
25193
|
+
return value;
|
|
25194
|
+
}
|
|
24760
25195
|
function createMcpControlTool(opts) {
|
|
24761
25196
|
const { getConfig, configPath, registry } = opts;
|
|
24762
25197
|
const inputSchema = {
|
|
@@ -24802,11 +25237,11 @@ async function mcpControlDispatch(input, deps) {
|
|
|
24802
25237
|
case "search":
|
|
24803
25238
|
return renderSearch(query ?? "", deps);
|
|
24804
25239
|
case "enable":
|
|
24805
|
-
return runEnable(server, deps);
|
|
25240
|
+
return server ? runEnable(server, deps) : "`server` is required for enable.";
|
|
24806
25241
|
case "disable":
|
|
24807
|
-
return runDisable(server, deps);
|
|
25242
|
+
return server ? runDisable(server, deps) : "`server` is required for disable.";
|
|
24808
25243
|
case "restart":
|
|
24809
|
-
return runRestart(server, deps);
|
|
25244
|
+
return server ? runRestart(server, deps) : "`server` is required for restart.";
|
|
24810
25245
|
default:
|
|
24811
25246
|
return `Unknown action "${action}". Use one of: list, search, enable, disable, restart.`;
|
|
24812
25247
|
}
|
|
@@ -24908,7 +25343,7 @@ async function runDisable(name, deps) {
|
|
|
24908
25343
|
const mcpServers = {
|
|
24909
25344
|
...full.mcpServers ?? {}
|
|
24910
25345
|
};
|
|
24911
|
-
const existing = mcpServers[name];
|
|
25346
|
+
const existing = expectDefined24(mcpServers[name]);
|
|
24912
25347
|
mcpServers[name] = { ...existing, enabled: false };
|
|
24913
25348
|
full.mcpServers = mcpServers;
|
|
24914
25349
|
await writeConfig(deps.configPath, full);
|
|
@@ -24979,6 +25414,12 @@ function badge(state) {
|
|
|
24979
25414
|
}
|
|
24980
25415
|
|
|
24981
25416
|
// src/extension/registry.ts
|
|
25417
|
+
function expectDefined25(value) {
|
|
25418
|
+
if (value === null || value === void 0) {
|
|
25419
|
+
throw new Error("Expected value to be defined");
|
|
25420
|
+
}
|
|
25421
|
+
return value;
|
|
25422
|
+
}
|
|
24982
25423
|
var ExtensionRegistry = class {
|
|
24983
25424
|
extensions = [];
|
|
24984
25425
|
promptContributors = [];
|
|
@@ -25144,11 +25585,12 @@ var ExtensionRegistry = class {
|
|
|
25144
25585
|
* default runner, each subsequent wrapper wraps the previous.
|
|
25145
25586
|
*/
|
|
25146
25587
|
wrapProviderRunner(inner) {
|
|
25147
|
-
const wrappers = this.extensions.filter((e) => e.wrapProviderRunner).map((e) => ({ name: e.name, wrap: e.wrapProviderRunner }));
|
|
25588
|
+
const wrappers = this.extensions.filter((e) => e.wrapProviderRunner).map((e) => ({ name: e.name, wrap: expectDefined25(e.wrapProviderRunner) }));
|
|
25148
25589
|
if (wrappers.length === 0) return inner;
|
|
25149
25590
|
let composed = inner;
|
|
25150
25591
|
for (let i = wrappers.length - 1; i >= 0; i--) {
|
|
25151
25592
|
const wrapper = wrappers[i];
|
|
25593
|
+
if (!wrapper) continue;
|
|
25152
25594
|
const next = composed;
|
|
25153
25595
|
composed = async (ctx, req) => {
|
|
25154
25596
|
try {
|
|
@@ -25247,7 +25689,7 @@ function createAgentToolHandler(a) {
|
|
|
25247
25689
|
const useById = new Map(selectedToolUses.map((u) => [u.id, u]));
|
|
25248
25690
|
const resultsForMessage = [];
|
|
25249
25691
|
for (const { result, tool, durationMs } of outputs) {
|
|
25250
|
-
if (result.type === "tool_confirm_pending") {
|
|
25692
|
+
if (result.type === "tool_confirm_pending" && tool) {
|
|
25251
25693
|
const decision = await waitForConfirm({
|
|
25252
25694
|
tool,
|
|
25253
25695
|
input: result.input,
|
|
@@ -25309,6 +25751,7 @@ function createAgentToolHandler(a) {
|
|
|
25309
25751
|
resultsForMessage.push(reRunResult.result);
|
|
25310
25752
|
continue;
|
|
25311
25753
|
}
|
|
25754
|
+
if (result.type !== "tool_result") continue;
|
|
25312
25755
|
resultsForMessage.push(result);
|
|
25313
25756
|
const use = useById.get(result.tool_use_id);
|
|
25314
25757
|
if (!use) continue;
|
|
@@ -25608,7 +26051,7 @@ function createAgentLoopHandler(a, handlers) {
|
|
|
25608
26051
|
return { status: "aborted", iterations };
|
|
25609
26052
|
}
|
|
25610
26053
|
await a.ctx.session.writeInFlightMarker(`iteration ${i} / max ${a.maxIterations}`).catch((err) => {
|
|
25611
|
-
a.logger.debug?.(
|
|
26054
|
+
(a.logger.debug ?? a.logger.warn)?.(
|
|
25612
26055
|
`in-flight marker write failed: ${err instanceof Error ? err.message : String(err)}`
|
|
25613
26056
|
);
|
|
25614
26057
|
});
|
|
@@ -25739,7 +26182,7 @@ function createAgentLoopHandler(a, handlers) {
|
|
|
25739
26182
|
offSubagentDone();
|
|
25740
26183
|
const reason = controller.signal.aborted ? "aborted" : "clean";
|
|
25741
26184
|
await a.ctx.session.clearInFlightMarker(reason).catch((err) => {
|
|
25742
|
-
a.logger.debug?.(
|
|
26185
|
+
(a.logger.debug ?? a.logger.warn)?.(
|
|
25743
26186
|
`in-flight marker clear failed: ${err instanceof Error ? err.message : String(err)}`
|
|
25744
26187
|
);
|
|
25745
26188
|
});
|
|
@@ -25824,13 +26267,12 @@ var Agent = class {
|
|
|
25824
26267
|
return this.container.resolve(TOKENS.PermissionPolicy);
|
|
25825
26268
|
}
|
|
25826
26269
|
get renderer() {
|
|
25827
|
-
return this.container.
|
|
26270
|
+
return this.container.safeResolve(TOKENS.Renderer);
|
|
25828
26271
|
}
|
|
25829
26272
|
disableInteractiveConfirmation() {
|
|
25830
26273
|
this.toolExecutor.clearConfirmAwaiter();
|
|
25831
|
-
|
|
25832
|
-
|
|
25833
|
-
policy.setPromptDelegate(void 0);
|
|
26274
|
+
if (typeof this.permission.setPromptDelegate === "function") {
|
|
26275
|
+
this.permission.setPromptDelegate(void 0);
|
|
25834
26276
|
}
|
|
25835
26277
|
}
|
|
25836
26278
|
register(tool) {
|
|
@@ -25860,6 +26302,7 @@ var Agent = class {
|
|
|
25860
26302
|
const signal = controller.signal;
|
|
25861
26303
|
this.ctx.signal = signal;
|
|
25862
26304
|
controller.onAbort(() => this.ctx.drainAbortHooks());
|
|
26305
|
+
this.ctx.tools = this.tools.list();
|
|
25863
26306
|
const span = this.tracer?.startSpan("agent.run", {
|
|
25864
26307
|
"agent.model": opts.model ?? this.ctx.model,
|
|
25865
26308
|
"agent.executionStrategy": opts.executionStrategy ?? this.executionStrategy
|
|
@@ -25876,7 +26319,8 @@ var Agent = class {
|
|
|
25876
26319
|
return result;
|
|
25877
26320
|
} catch (err) {
|
|
25878
26321
|
const wse = err instanceof AgentError ? err : toWrongStackError(err);
|
|
25879
|
-
|
|
26322
|
+
const safeError = err instanceof Error ? new Error(err.message) : new Error(String(err));
|
|
26323
|
+
this.events.emit("error", { err: safeError, phase: "agent", _original: err instanceof Error ? err : void 0 });
|
|
25880
26324
|
if (err instanceof Error) span?.recordError(err);
|
|
25881
26325
|
span?.setAttribute("agent.status", "failed");
|
|
25882
26326
|
const result = {
|
|
@@ -27907,7 +28351,7 @@ function buildRefinerInput(text, history) {
|
|
|
27907
28351
|
}
|
|
27908
28352
|
async function enhanceUserPrompt(opts) {
|
|
27909
28353
|
const { provider, model, text } = opts;
|
|
27910
|
-
const timeoutMs = opts.timeoutMs ??
|
|
28354
|
+
const timeoutMs = opts.timeoutMs ?? 9e4;
|
|
27911
28355
|
const maxTokens = opts.maxTokens ?? 2048;
|
|
27912
28356
|
const req = {
|
|
27913
28357
|
model,
|
|
@@ -27972,7 +28416,7 @@ var PhaseGraphBuilder = class _PhaseGraphBuilder {
|
|
|
27972
28416
|
const phases = /* @__PURE__ */ new Map();
|
|
27973
28417
|
const phaseIds = [];
|
|
27974
28418
|
for (let i = 0; i < this.opts.phases.length; i++) {
|
|
27975
|
-
const tmpl = this.opts.phases[i];
|
|
28419
|
+
const tmpl = this.opts.phases[i] ?? { name: "", description: "", taskTemplates: [], parallelizable: false, priority: "medium", estimateHours: 0 };
|
|
27976
28420
|
const phaseId = crypto.randomUUID();
|
|
27977
28421
|
phaseIds.push(phaseId);
|
|
27978
28422
|
const store = this.opts.externalTaskStore ?? new DefaultTaskStore();
|
|
@@ -27997,8 +28441,8 @@ var PhaseGraphBuilder = class _PhaseGraphBuilder {
|
|
|
27997
28441
|
description: tmpl.description,
|
|
27998
28442
|
status: "pending",
|
|
27999
28443
|
taskGraph,
|
|
28000
|
-
dependsOn: i > 0 ? [phaseIds[i - 1]] : [],
|
|
28001
|
-
nextPhases: i < this.opts.phases.length - 1 ? [phaseIds[i + 1]] : [],
|
|
28444
|
+
dependsOn: i > 0 ? [phaseIds[i - 1] ?? ""] : [],
|
|
28445
|
+
nextPhases: i < this.opts.phases.length - 1 ? [phaseIds[i + 1] ?? ""] : [],
|
|
28002
28446
|
parallelizable: tmpl.parallelizable,
|
|
28003
28447
|
priority: tmpl.priority,
|
|
28004
28448
|
estimateHours: tmpl.estimateHours,
|
|
@@ -28011,15 +28455,16 @@ var PhaseGraphBuilder = class _PhaseGraphBuilder {
|
|
|
28011
28455
|
const phaseArray = Array.from(phases.values());
|
|
28012
28456
|
for (let i = 0; i < phaseArray.length; i++) {
|
|
28013
28457
|
const phase = phaseArray[i];
|
|
28014
|
-
phase
|
|
28015
|
-
phase.
|
|
28458
|
+
if (!phase) continue;
|
|
28459
|
+
phase.nextPhases = i < phaseArray.length - 1 ? [phaseArray[i + 1]?.id ?? ""] : [];
|
|
28460
|
+
phase.dependsOn = i > 0 ? [phaseArray[i - 1]?.id ?? ""] : [];
|
|
28016
28461
|
}
|
|
28017
28462
|
const graph = {
|
|
28018
28463
|
id: graphId,
|
|
28019
28464
|
title: this.opts.title,
|
|
28020
28465
|
description: this.opts.description ?? "",
|
|
28021
28466
|
phases,
|
|
28022
|
-
rootPhaseIds: phaseIds.length > 0 ? [phaseIds[0]] : [],
|
|
28467
|
+
rootPhaseIds: phaseIds.length > 0 ? [phaseIds[0] ?? ""] : [],
|
|
28023
28468
|
activePhaseIds: [],
|
|
28024
28469
|
completedPhaseIds: [],
|
|
28025
28470
|
failedPhaseIds: [],
|
|
@@ -28201,7 +28646,7 @@ var PhaseOrchestrator = class {
|
|
|
28201
28646
|
return;
|
|
28202
28647
|
}
|
|
28203
28648
|
if (this.opts.stopOnFailure && this.graph.failedPhaseIds.length > 0) {
|
|
28204
|
-
const failedPhase = this.graph.phases.get(this.graph.failedPhaseIds[0]);
|
|
28649
|
+
const failedPhase = this.graph.phases.get(this.graph.failedPhaseIds[0] ?? "");
|
|
28205
28650
|
if (failedPhase) {
|
|
28206
28651
|
this.onGraphFailed(failedPhase);
|
|
28207
28652
|
}
|
|
@@ -28377,9 +28822,14 @@ var PhaseOrchestrator = class {
|
|
|
28377
28822
|
name: phase.name,
|
|
28378
28823
|
files: info.conflictFiles
|
|
28379
28824
|
});
|
|
28380
|
-
|
|
28825
|
+
const resolved = await this.ctx.resolveConflict?.(phase, info);
|
|
28826
|
+
return resolved ?? false;
|
|
28381
28827
|
} : void 0;
|
|
28382
|
-
const
|
|
28828
|
+
const mergeOpts = {
|
|
28829
|
+
squash: true
|
|
28830
|
+
};
|
|
28831
|
+
if (resolve13 !== void 0) mergeOpts.resolve = resolve13;
|
|
28832
|
+
const result = await this.worktrees.merge(handle, mergeOpts);
|
|
28383
28833
|
if (result.resolved) {
|
|
28384
28834
|
this.emit("phase.conflictResolved", { phaseId: phase.id, name: phase.name });
|
|
28385
28835
|
}
|
|
@@ -28773,9 +29223,6 @@ var AutoPhaseRunner = class {
|
|
|
28773
29223
|
this.graph = await builder.build();
|
|
28774
29224
|
const ctx = {
|
|
28775
29225
|
executeTask: this.opts.executeTask,
|
|
28776
|
-
verifyPhase: this.opts.verifyPhase,
|
|
28777
|
-
repairPhase: this.opts.repairPhase,
|
|
28778
|
-
resolveConflict: this.opts.resolveConflict,
|
|
28779
29226
|
brain: this.opts.brain,
|
|
28780
29227
|
onPhaseComplete: (phase) => {
|
|
28781
29228
|
this.opts.onPhaseComplete?.(phase);
|
|
@@ -28787,6 +29234,9 @@ var AutoPhaseRunner = class {
|
|
|
28787
29234
|
this.opts.onTick?.(tickCtx);
|
|
28788
29235
|
}
|
|
28789
29236
|
};
|
|
29237
|
+
if (this.opts.verifyPhase !== void 0) ctx.verifyPhase = this.opts.verifyPhase;
|
|
29238
|
+
if (this.opts.repairPhase !== void 0) ctx.repairPhase = this.opts.repairPhase;
|
|
29239
|
+
if (this.opts.resolveConflict !== void 0) ctx.resolveConflict = this.opts.resolveConflict;
|
|
28790
29240
|
this.orchestrator = new PhaseOrchestrator({
|
|
28791
29241
|
graph: this.graph,
|
|
28792
29242
|
ctx,
|
|
@@ -28802,8 +29252,8 @@ var AutoPhaseRunner = class {
|
|
|
28802
29252
|
});
|
|
28803
29253
|
if (this.opts.onProgress) {
|
|
28804
29254
|
this.progressInterval = setInterval(() => {
|
|
28805
|
-
const progress = this.orchestrator
|
|
28806
|
-
this.opts.onProgress(progress);
|
|
29255
|
+
const progress = this.orchestrator?.getProgress();
|
|
29256
|
+
if (progress) this.opts.onProgress?.(progress);
|
|
28807
29257
|
}, 2e3);
|
|
28808
29258
|
}
|
|
28809
29259
|
if (this.opts.events) {
|
|
@@ -29023,7 +29473,7 @@ function firstBalancedArray(text) {
|
|
|
29023
29473
|
let inString = false;
|
|
29024
29474
|
let escaped = false;
|
|
29025
29475
|
for (let i = start; i < text.length; i++) {
|
|
29026
|
-
const ch = text[i];
|
|
29476
|
+
const ch = text[i] ?? "";
|
|
29027
29477
|
if (inString) {
|
|
29028
29478
|
if (escaped) {
|
|
29029
29479
|
escaped = false;
|
|
@@ -29533,7 +29983,7 @@ ${merged.stderr}`);
|
|
|
29533
29983
|
async tryResolveConflict(handle, conflictFiles, opts) {
|
|
29534
29984
|
let resolved = false;
|
|
29535
29985
|
try {
|
|
29536
|
-
resolved = await opts.resolve({ conflictFiles, cwd: this.projectRoot });
|
|
29986
|
+
resolved = opts.resolve ? await opts.resolve({ conflictFiles, cwd: this.projectRoot }) : false;
|
|
29537
29987
|
} catch {
|
|
29538
29988
|
resolved = false;
|
|
29539
29989
|
}
|
|
@@ -30056,6 +30506,12 @@ var ReplayProviderRunner = class {
|
|
|
30056
30506
|
};
|
|
30057
30507
|
|
|
30058
30508
|
// src/plugins/prompts-plugin.ts
|
|
30509
|
+
function expectDefined26(value) {
|
|
30510
|
+
if (value === null || value === void 0) {
|
|
30511
|
+
throw new Error("Expected value to be defined");
|
|
30512
|
+
}
|
|
30513
|
+
return value;
|
|
30514
|
+
}
|
|
30059
30515
|
function createPromptsPlugin(opts) {
|
|
30060
30516
|
let store = null;
|
|
30061
30517
|
return {
|
|
@@ -30109,7 +30565,7 @@ ${lines.join("\n")}
|
|
|
30109
30565
|
if (!restJoined) return { message: "Usage: /prompts view <title>" };
|
|
30110
30566
|
const matches = await store.find(restJoined);
|
|
30111
30567
|
if (matches.length === 0) return { message: `No prompt matching "${restJoined}".` };
|
|
30112
|
-
const entry = matches.find((m) => m.title.toLowerCase() === restJoined.toLowerCase()) ?? matches[0];
|
|
30568
|
+
const entry = matches.find((m) => m.title.toLowerCase() === restJoined.toLowerCase()) ?? expectDefined26(matches[0]);
|
|
30113
30569
|
const tags = entry.tags.length > 0 ? ` [${entry.tags.join(", ")}]` : "";
|
|
30114
30570
|
return {
|
|
30115
30571
|
message: `# ${entry.title}${tags}
|
|
@@ -30132,7 +30588,7 @@ ${dim2(`id: ${entry.id} | created: ${entry.createdAt}`)}`
|
|
|
30132
30588
|
if (!restJoined) return { message: "Usage: /prompts delete <title>" };
|
|
30133
30589
|
const matches = await store.find(restJoined);
|
|
30134
30590
|
if (matches.length === 0) return { message: `No prompt matching "${restJoined}".` };
|
|
30135
|
-
const exact = matches.find((m) => m.title.toLowerCase() === restJoined.toLowerCase()) ?? matches[0];
|
|
30591
|
+
const exact = matches.find((m) => m.title.toLowerCase() === restJoined.toLowerCase()) ?? expectDefined26(matches[0]);
|
|
30136
30592
|
const deleted = await store.delete(exact.id);
|
|
30137
30593
|
return { message: deleted ? `Deleted "${exact.title}".` : "Delete failed." };
|
|
30138
30594
|
}
|
|
@@ -30142,7 +30598,7 @@ ${dim2(`id: ${entry.id} | created: ${entry.createdAt}`)}`
|
|
|
30142
30598
|
if (!parsed.title) return { message: 'Usage: /prompts edit "title" "new content"' };
|
|
30143
30599
|
const matches = await store.find(parsed.title);
|
|
30144
30600
|
if (matches.length === 0) return { message: `No prompt matching "${parsed.title}".` };
|
|
30145
|
-
const exact = matches.find((m) => m.title.toLowerCase() === parsed.title
|
|
30601
|
+
const exact = matches.find((m) => m.title.toLowerCase() === parsed.title?.toLowerCase()) ?? expectDefined26(matches[0]);
|
|
30146
30602
|
exact.content = parsed.content;
|
|
30147
30603
|
exact.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
30148
30604
|
await store.save(exact);
|
|
@@ -30154,7 +30610,7 @@ ${dim2(`id: ${entry.id} | created: ${entry.createdAt}`)}`
|
|
|
30154
30610
|
if (!parsed.title) return { message: 'Usage: /prompts extend "title" <instructions>' };
|
|
30155
30611
|
const matches = await store.find(parsed.title);
|
|
30156
30612
|
if (matches.length === 0) return { message: `No prompt matching "${parsed.title}".` };
|
|
30157
|
-
const exact = matches.find((m) => m.title.toLowerCase() === parsed.title
|
|
30613
|
+
const exact = matches.find((m) => m.title.toLowerCase() === parsed.title?.toLowerCase()) ?? expectDefined26(matches[0]);
|
|
30158
30614
|
const prov = ctx.provider;
|
|
30159
30615
|
if (!prov?.complete) return { message: "LLM not available. Configure a provider first." };
|
|
30160
30616
|
const enhanced = await prov.complete(ctx.model, [
|
|
@@ -30189,9 +30645,9 @@ function parseTitleContent(args) {
|
|
|
30189
30645
|
const trimmed = args.trim();
|
|
30190
30646
|
if (!trimmed) return { title: "", content: "" };
|
|
30191
30647
|
const doubleMatch = /^"([^"]+)"\s+"([^"]+)"$/.exec(trimmed) || /^'([^']+)'\s+'([^']+)'$/.exec(trimmed);
|
|
30192
|
-
if (doubleMatch) return { title: doubleMatch[1], content: doubleMatch[2] };
|
|
30648
|
+
if (doubleMatch) return { title: expectDefined26(doubleMatch[1]), content: expectDefined26(doubleMatch[2]) };
|
|
30193
30649
|
const singleMatch = /^'([^']+)'\s+(.+)$/.exec(trimmed);
|
|
30194
|
-
if (singleMatch) return { title: singleMatch[1], content: singleMatch[2] };
|
|
30650
|
+
if (singleMatch) return { title: expectDefined26(singleMatch[1]), content: expectDefined26(singleMatch[2]) };
|
|
30195
30651
|
const firstSpace = trimmed.indexOf(" ");
|
|
30196
30652
|
if (firstSpace === -1) return { title: trimmed, content: "" };
|
|
30197
30653
|
return { title: trimmed.slice(0, firstSpace), content: trimmed.slice(firstSpace + 1) };
|
|
@@ -30202,6 +30658,12 @@ function dim2(s) {
|
|
|
30202
30658
|
|
|
30203
30659
|
// src/plugins/sync-plugin.ts
|
|
30204
30660
|
init_atomic_write();
|
|
30661
|
+
function expectDefined27(value) {
|
|
30662
|
+
if (value === null || value === void 0) {
|
|
30663
|
+
throw new Error("Expected value to be defined");
|
|
30664
|
+
}
|
|
30665
|
+
return value;
|
|
30666
|
+
}
|
|
30205
30667
|
function createSyncPlugin(opts) {
|
|
30206
30668
|
let cloud = null;
|
|
30207
30669
|
let configStore;
|
|
@@ -30227,11 +30689,11 @@ function createSyncPlugin(opts) {
|
|
|
30227
30689
|
cloud = new CloudSync(
|
|
30228
30690
|
paths,
|
|
30229
30691
|
() => {
|
|
30230
|
-
const cfg = configStore
|
|
30692
|
+
const cfg = configStore?.get();
|
|
30231
30693
|
return cfg.sync;
|
|
30232
30694
|
},
|
|
30233
30695
|
async (cfg) => {
|
|
30234
|
-
configStore
|
|
30696
|
+
configStore?.update({ sync: cfg });
|
|
30235
30697
|
}
|
|
30236
30698
|
);
|
|
30237
30699
|
void cloud.loadState();
|
|
@@ -30275,7 +30737,7 @@ function buildSyncCommand(cloud, configStore, vault, syncConfigPath) {
|
|
|
30275
30737
|
if (!repo || !repo.includes("/")) {
|
|
30276
30738
|
return { message: 'Invalid repo format. Expected "owner/repo".' };
|
|
30277
30739
|
}
|
|
30278
|
-
const storedToken = vault ? vault.encrypt(token) : token;
|
|
30740
|
+
const storedToken = vault ? vault.encrypt(expectDefined27(token)) : expectDefined27(token);
|
|
30279
30741
|
const syncConfig = {
|
|
30280
30742
|
enabled: true,
|
|
30281
30743
|
repo,
|
|
@@ -30515,7 +30977,7 @@ async function generateCommitMessageHeuristics(cwd) {
|
|
|
30515
30977
|
const commitType = detectCommitType(statsResult.stdout);
|
|
30516
30978
|
let scope = "";
|
|
30517
30979
|
if (files.length > 0) {
|
|
30518
|
-
const primary = files[0]
|
|
30980
|
+
const primary = files[0]?.split("/")[0];
|
|
30519
30981
|
if (primary && primary !== "packages" && primary !== "apps" && primary !== "node_modules") {
|
|
30520
30982
|
scope = `(${primary})`;
|
|
30521
30983
|
}
|
|
@@ -31112,6 +31574,6 @@ ${formatPlan(updated)}`
|
|
|
31112
31574
|
};
|
|
31113
31575
|
}
|
|
31114
31576
|
|
|
31115
|
-
export { ACP_AGENTS, AGENTS_BY_PHASE, AGENT_CATALOG, AISpecBuilder, ALL_AGENT_DEFINITIONS, ALL_FLEET_AGENTS, ALL_SYNC_CATEGORIES, AUDIT_LOG_AGENT, Agent, AgentError, AnnotationsStore, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutoPhasePlanner, AutoPhaseRunner, AutonomousRunner, BUG_HUNTER_AGENT, BrainDecisionQueue, BudgetExceededError, CONTEXT_WINDOW_MODES, CORE_RECONSTRUCT_EVENTS, CheckpointManager, CloudSync, CollaborationBus, ConfigError, ConfigMigrationError, Container, Context, ConversationState, DEFAULT_AUTONOMY_CONFIG, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_CONFIG, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_DISPATCH_ROLE, DEFAULT_MAX_ITERATIONS, DEFAULT_MODES, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SESSION_LOGGING_CONFIG, DEFAULT_SPEC_TEMPLATE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DefaultAttachmentStore, DefaultBrainArbiter, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultPluginAPI, DefaultPromptStore, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionRewinder, DefaultSessionStore, DefaultSkillLoader, DefaultSystemPromptBuilder, DefaultTaskStore, DefaultTokenCounter, Director, DirectorStateCheckpoint, DoneConditionChecker, ENHANCER_SYSTEM_PROMPT, ERROR_CODES, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, HookRegistry, HookRunner, HumanEscalatingBrainArbiter, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MATRIX_PHASE_KEYS, MAX_JOURNAL_ENTRIES, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, ObservableBrainArbiter, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, PhaseGraphBuilder, PhaseOrchestrator, PhaseStore, Pipeline, PluginError, ProviderError, ProviderRegistry, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, ReplayLogStore, ReplayProviderRunner, ReportGenerator, RunController, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, STANDARD_AUDIT_EVENTS, ScopedEventBus, SddParallelRun, SddTaskDecomposer, SecurityScanner, SecurityScannerOrchestrator, SelectiveCompactor, SessionAnalyzer, SessionError, SessionRecovery, SkillGenerator, SkillInstaller, SkillManifestStore, SlashCommandRegistry, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TOKENS, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, TechStackDetector, ToolAuditLog, ToolError, ToolExecutor, ToolRegistry, WorktreeManager, WrongStackError, addPlanItem, allServers, analyzeCriticalPath, appendJournal, applyRosterBudget, asBlocks, asText, assertSafePath, atomicWrite, attachAutoExtend, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, bootConfig, braveSearchServer, buildBtwBlock, buildChildEnv, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, buildRecoveryStrategies, classifyFamily, clearPlan, collabInjectMiddleware, collabPauseMiddleware, color, compileGlob, compileUserRegex, completePartialObject, composeDirectorPrompt, composeSubagentPrompt, computeTaskProgress, consumeBtwNotes, context7Server, contextManagerTool, createAutoExecutor, createAutoPhaseFromTaskGraph, createContextManagerTool, createDefaultPipelines, createDelegateTool, createGitPlugin, createMcpControlTool, createMessage, createObservabilityPlugin, createPlanPlugin, createPromptsPlugin, createSecurityPlugin, createSecuritySlashCommand, createSessionEventBridge, createSkillsPlugin, createSyncPlugin, createToolOutputSerializer, decryptConfigSecrets, defaultGitignoreUpdater, defaultOrchestrator, defaultReportGenerator, defaultSecurityScanner, defaultSkillGenerator, defaultTechStackDetector, deriveTodosFromPlanItem, detectNewlineStyle, dispatchAgent, downloadGitHubTarball, emptyGoal, emptyPlan, encryptConfigSecrets, enhanceUserPrompt, ensureDir, estimateRequestTokens, estimateRequestTokensCalibrated, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, expandGlob, extractRunEnv, filesystemServer, findCriticalPath, flagsToConfigPatch, formatContextWindowModeList, formatGoal, formatHumanPrompt, formatPlan, formatPlanTemplates, formatTodosList, getAgentDefinition, getCalibrationState, getContextWindowMode, getPlanTemplate, getTemplate, getTermSize, githubServer, goalFilePath, googleMapsServer, hashRequest, hookMatcherMatches, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isInteractive, isPluginError, isSessionError, isStdinTTY, isStdoutTTY, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isValidMatrixKey, isWrongStackError, listContextWindowModes, listPlanTemplates, listTemplates, loadDirectorState, loadGoal, loadPlan, loadPlugins, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAskTool, makeAssignTool, makeAutonomyPromptContributor, makeAwaitTasksTool, makeCollabDebugTool, makeContinueToNextIterationTool, makeDirectorSessionFactory, makeFleetEmitTool, makeFleetHealthTool, makeFleetSessionTool, makeFleetStatusTool, makeFleetUsageTool, makeLLMClassifier, makeRollUpTool, makeSpawnTool, makeTerminateTool, matchAny, matchGlob, matrixKeyKind, mergeCustomModelDefs, mergeModelsPayload, migratePlaintextSecrets, miniMaxVisionServer, normalizeToLf, normalizedEqual, onResize, parseContinueDirective, parseSkillRef, pendingBtwCount, phaseForRole, projectHash, projectSlug, recentTextTurns, recordActualUsage, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resetCalibration, resolveAuditLevel, resolveContextWindowPolicy, resolveModelMatrix, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, runProviderWithRetry, runShellHook, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTodosCheckpoint, scoreAgents, securitySlashCommand, sentinelServer, setBtwNote, setPlanItemStatus, setRawMode, shouldEnhance, slackServer, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, wrapAsState, writeErr, writeOut, zaiVisionServer };
|
|
31577
|
+
export { ACP_AGENTS, AGENTS_BY_PHASE, AGENT_CATALOG, AISpecBuilder, ALL_AGENT_DEFINITIONS, ALL_FLEET_AGENTS, ALL_SYNC_CATEGORIES, AUDIT_LOG_AGENT, Agent, AgentError, AnnotationsStore, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutoPhasePlanner, AutoPhaseRunner, AutonomousRunner, BUG_HUNTER_AGENT, BrainDecisionQueue, BudgetExceededError, CONTEXT_WINDOW_MODES, CORE_RECONSTRUCT_EVENTS, CheckpointManager, CloudSync, CollaborationBus, ConfigError, ConfigMigrationError, Container, Context, ConversationState, DEFAULT_AUTONOMY_CONFIG, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_CONFIG, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_DISPATCH_ROLE, DEFAULT_MAX_ITERATIONS, DEFAULT_MODES, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SESSION_LOGGING_CONFIG, DEFAULT_SPEC_TEMPLATE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DefaultAttachmentStore, DefaultBrainArbiter, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultPluginAPI, DefaultPromptStore, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionRewinder, DefaultSessionStore, DefaultSkillLoader, DefaultSystemPromptBuilder, DefaultTaskStore, DefaultTokenCounter, Director, DirectorStateCheckpoint, DoneConditionChecker, ENHANCER_SYSTEM_PROMPT, ERROR_CODES, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, HookRegistry, HookRunner, HumanEscalatingBrainArbiter, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MATRIX_PHASE_KEYS, MAX_JOURNAL_ENTRIES, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, ObservableBrainArbiter, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, PhaseGraphBuilder, PhaseOrchestrator, PhaseStore, Pipeline, PluginError, ProviderError, ProviderRegistry, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, ReplayLogStore, ReplayProviderRunner, ReportGenerator, RunController, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, STANDARD_AUDIT_EVENTS, ScopedEventBus, SddParallelRun, SddTaskDecomposer, SecurityScanner, SecurityScannerOrchestrator, SelectiveCompactor, SessionAnalyzer, SessionError, SessionRecovery, SkillGenerator, SkillInstaller, SkillManifestStore, SlashCommandRegistry, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TOKENS, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, TechStackDetector, ToolAuditLog, ToolError, ToolExecutor, ToolRegistry, WorktreeManager, WrongStackError, addPlanItem, allServers, analyzeCriticalPath, appendJournal, applyRosterBudget, asBlocks, asText, assertSafePath, atomicWrite, attachAutoExtend, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, bootConfig, braveSearchServer, buildBtwBlock, buildChildEnv, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, buildRecoveryStrategies, classifyFamily, clearPlan, collabInjectMiddleware, collabPauseMiddleware, color, compileGlob, compileUserRegex, completePartialObject, composeDirectorPrompt, composeSubagentPrompt, computeTaskProgress, consumeBtwNotes, context7Server, contextManagerTool, createAutoExecutor, createAutoPhaseFromTaskGraph, createContextManagerTool, createDefaultPipelines, createDelegateTool, createGitPlugin, createMcpControlTool, createMessage, createObservabilityPlugin, createPlanPlugin, createPromptsPlugin, createSecurityPlugin, createSecuritySlashCommand, createSessionEventBridge, createSkillsPlugin, createSyncPlugin, createToolOutputSerializer, decryptConfigSecrets, defaultGitignoreUpdater, defaultOrchestrator, defaultReportGenerator, defaultSecurityScanner, defaultSkillGenerator, defaultTechStackDetector, deriveTodosFromPlanItem, detectNewlineStyle, dispatchAgent, downloadGitHubTarball, emptyGoal, emptyPlan, encryptConfigSecrets, enhanceUserPrompt, ensureDir, estimateRequestTokens, estimateRequestTokensCalibrated, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, expandGlob, expectDefined7 as expectDefined, extractRunEnv, filesystemServer, findCriticalPath, flagsToConfigPatch, formatContextWindowModeList, formatGoal, formatHumanPrompt, formatPlan, formatPlanTemplates, formatTodosList, getAgentDefinition, getCalibrationState, getContextWindowMode, getPlanTemplate, getTemplate, getTermSize, githubServer, goalFilePath, googleMapsServer, hashRequest, hookMatcherMatches, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isInteractive, isPluginError, isSessionError, isStdinTTY, isStdoutTTY, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isValidMatrixKey, isWrongStackError, listContextWindowModes, listPlanTemplates, listTemplates, loadDirectorState, loadGoal, loadPlan, loadPlugins, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAskTool, makeAssignTool, makeAutonomyPromptContributor, makeAwaitTasksTool, makeCollabDebugTool, makeContinueToNextIterationTool, makeDirectorSessionFactory, makeFleetEmitTool, makeFleetHealthTool, makeFleetSessionTool, makeFleetStatusTool, makeFleetUsageTool, makeLLMClassifier, makeRollUpTool, makeSpawnTool, makeTerminateTool, matchAny, matchGlob, matrixKeyKind, mergeCustomModelDefs, mergeModelsPayload, migratePlaintextSecrets, miniMaxVisionServer, normalizeToLf, normalizedEqual, onResize, parseContinueDirective, parseSkillRef, pendingBtwCount, phaseForRole, projectHash, projectSlug, recentTextTurns, recordActualUsage, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resetCalibration, resolveAuditLevel, resolveContextWindowPolicy, resolveModelMatrix, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, runProviderWithRetry, runShellHook, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTodosCheckpoint, scoreAgents, securitySlashCommand, sentinelServer, setBtwNote, setOutputLineGuard, setPlanItemStatus, setRawMode, shouldEnhance, slackServer, sleep, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, wrapAsState, writeErr, writeOut, zaiVisionServer };
|
|
31116
31578
|
//# sourceMappingURL=index.js.map
|
|
31117
31579
|
//# sourceMappingURL=index.js.map
|