blun-king-cli 9.1.519 → 9.1.523
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/LIESMICH.txt +1 -1
- package/README.md +1 -1
- package/agent-spine-plugin/blun.plugin.json +1 -1
- package/agent-spine-plugin/hooks/codex.json +1 -1
- package/bin/telegram-approval-relay.cjs +2 -0
- package/blun.mjs +20 -4
- package/package.json +4 -2
- package/scripts/check-approval-observability-regression.js +111 -0
- package/scripts/check-session-start-hook-context-regression.js +114 -1
- package/scripts/check-slash-escape-regression.js +89 -0
- package/telegram-plugin/bin/telegram-approval-relay.cjs +2 -1
- package/bin/tool-result-offload-policy.cjs.vor-historical-preview-20260831-210300 +0 -317
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 9.1.523 - 2026-09-01
|
|
4
|
+
|
|
5
|
+
- Makes `Escape` cancel an open slash-command menu and clear its slash draft in one action instead of leaving the command text behind.
|
|
6
|
+
- Lets `Ctrl+S` pass a slash draft into the existing queue-and-drain path even when the surface currently reports idle, instead of silently returning before the flush.
|
|
7
|
+
- Preserves ordinary drafts when `Escape` only dismisses non-slash autocomplete.
|
|
8
|
+
- Adds red-to-green runtime regressions for both shortcuts against the exact 9.1.522 package behavior.
|
|
9
|
+
|
|
10
|
+
## 9.1.522 - 2026-09-01
|
|
11
|
+
|
|
12
|
+
- Writes `permission.approval_requested` to the session wire as soon as a tool approval opens, so an unattended King no longer looks like a silent model or provider stall while it is waiting for an operator.
|
|
13
|
+
- Reuses the existing Telegram approval buttons automatically when the allowlist contains exactly one private chat plus any number of groups; ambiguous private recipients remain fail-closed unless `BLUN_TELEGRAM_APPROVAL_CHAT_ID` is set.
|
|
14
|
+
- Adds a red-to-green regression for immediate wire visibility, unique-private-chat routing, explicit target precedence, and ambiguous-recipient rejection in both packaged relay copies.
|
|
15
|
+
|
|
16
|
+
## 9.1.521 - 2026-09-01
|
|
17
|
+
|
|
18
|
+
- Runs the AgentSpine `SessionStart` scan outside the interactive startup path, so a cold 123.6-second home-directory scan cannot hold the editor or prevent the first user prompt from reaching the wire.
|
|
19
|
+
- Keeps successful SessionStart output automatic: the completed background hook still persists its scoped briefing into the session context.
|
|
20
|
+
- Extends the cold-scan budget to 180 seconds and adds a red-to-green runtime regression proving that startup returns before a slow hook while the hook can still finish afterward.
|
|
21
|
+
|
|
22
|
+
## 9.1.520 - 2026-08-31
|
|
23
|
+
|
|
24
|
+
- Gives AgentSpine's `SessionStart` hook a 60-second cold-project budget, so startup and `/reload` can persist the automatic briefing even when the measured source scan exceeds the former 15-second limit.
|
|
25
|
+
- Keeps prompt, tool, compact, stop, and subagent hook budgets unchanged; only the full SessionStart briefing receives the larger allowance.
|
|
26
|
+
- Extends the SessionStart regression with the packaged AgentSpine manifests and a real hook-process output probe instead of relying only on a simulated result.
|
|
27
|
+
|
|
3
28
|
## 9.1.519 - 2026-08-31
|
|
4
29
|
|
|
5
30
|
- Persists successful `SessionStart` hook output before startup or reload returns, so AgentSpine readiness reaches the resumed model context automatically instead of waiting for the first user prompt.
|
package/LIESMICH.txt
CHANGED
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
}
|
|
16
16
|
},
|
|
17
17
|
"hooks": [
|
|
18
|
-
{ "event": "SessionStart", "command": "node \"./src/hook.js\"", "timeout":
|
|
18
|
+
{ "event": "SessionStart", "command": "node \"./src/hook.js\"", "timeout": 180 },
|
|
19
19
|
{ "event": "UserPromptSubmit", "command": "node \"./src/hook.js\"", "timeout": 15 },
|
|
20
20
|
{ "event": "PreToolUse", "matcher": "Edit|Write|apply_patch|Bash|exec_command", "command": "node \"./src/hook.js\"", "timeout": 15 },
|
|
21
21
|
{ "event": "PostToolUse", "command": "node \"./src/hook.js\"", "timeout": 15 },
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"SessionStart": [
|
|
5
5
|
{
|
|
6
6
|
"matcher": "startup|resume|clear|compact",
|
|
7
|
-
"hooks": [{ "type": "command", "command": "node \"${PLUGIN_ROOT}/src/hook.js\"", "timeout":
|
|
7
|
+
"hooks": [{ "type": "command", "command": "node \"${PLUGIN_ROOT}/src/hook.js\"", "timeout": 180 }]
|
|
8
8
|
}
|
|
9
9
|
],
|
|
10
10
|
"UserPromptSubmit": [
|
|
@@ -68,6 +68,8 @@ function resolveTelegramApprovalTarget(allowFrom, configuredChatId) {
|
|
|
68
68
|
: [];
|
|
69
69
|
const configured = String(configuredChatId ?? '').trim();
|
|
70
70
|
if (configured.length > 0) return allowed.includes(configured) ? configured : null;
|
|
71
|
+
const privateChats = allowed.filter((value) => /^[1-9]\d*$/u.test(value));
|
|
72
|
+
if (privateChats.length === 1) return privateChats[0];
|
|
71
73
|
return allowed.length === 1 ? allowed[0] : null;
|
|
72
74
|
}
|
|
73
75
|
|
package/blun.mjs
CHANGED
|
@@ -234150,6 +234150,15 @@ var init_permission = __esmMin((() => {
|
|
|
234150
234150
|
let requestedApproval = false;
|
|
234151
234151
|
if (this.agent.rpc?.requestApproval) {
|
|
234152
234152
|
requestedApproval = true;
|
|
234153
|
+
this.agent.records.logRecord({
|
|
234154
|
+
type: "permission.approval_requested",
|
|
234155
|
+
turnId: Number(context.turnId),
|
|
234156
|
+
toolCallId: id,
|
|
234157
|
+
toolName: name,
|
|
234158
|
+
action,
|
|
234159
|
+
display,
|
|
234160
|
+
policyName: policyName ?? null
|
|
234161
|
+
});
|
|
234153
234162
|
this.agent.hooks?.fireAndForgetTrigger?.("PermissionRequest", {
|
|
234154
234163
|
matcherValue: name,
|
|
234155
234164
|
inputData: {
|
|
@@ -297952,7 +297961,7 @@ var init_session$1 = __esmMin((() => {
|
|
|
297952
297961
|
const { agent } = await this.createAgent({ type: "main" }, { profile: DEFAULT_AGENT_PROFILES["agent"] });
|
|
297953
297962
|
const mc = this.options.missionContract;
|
|
297954
297963
|
if (mc && Array.isArray(mc.acceptanceCriteria) && mc.acceptanceCriteria.length > 0) await agent.injection.setMissionContract(mc);
|
|
297955
|
-
|
|
297964
|
+
this.scheduleSessionStart("startup");
|
|
297956
297965
|
return agent;
|
|
297957
297966
|
}
|
|
297958
297967
|
async resume() {
|
|
@@ -297965,7 +297974,7 @@ var init_session$1 = __esmMin((() => {
|
|
|
297965
297974
|
const profile = DEFAULT_AGENT_PROFILES["agent"];
|
|
297966
297975
|
if (main !== void 0 && profile !== void 0 && main.config.systemPrompt === "") await this.bootstrapAgentProfile(main, profile);
|
|
297967
297976
|
if (main !== void 0) this.ensureBaselineSkill(main);
|
|
297968
|
-
|
|
297977
|
+
this.scheduleSessionStart("resume");
|
|
297969
297978
|
return { warning };
|
|
297970
297979
|
}
|
|
297971
297980
|
async close() {
|
|
@@ -298500,6 +298509,11 @@ var init_session$1 = __esmMin((() => {
|
|
|
298500
298509
|
if (agent === void 0) throw new BlunError(ErrorCodes.AGENT_NOT_FOUND, "Main agent was not found");
|
|
298501
298510
|
return agent;
|
|
298502
298511
|
}
|
|
298512
|
+
scheduleSessionStart(source) {
|
|
298513
|
+
void this.triggerSessionStart(source).catch((error) => {
|
|
298514
|
+
this.log.warn("session start hook failed", { source, error });
|
|
298515
|
+
});
|
|
298516
|
+
}
|
|
298503
298517
|
async triggerSessionStart(source) {
|
|
298504
298518
|
const results = await this.hookEngine.trigger("SessionStart", {
|
|
298505
298519
|
matcherValue: source,
|
|
@@ -505909,6 +505923,7 @@ var EditorKeyboardController = class {
|
|
|
505909
505923
|
return;
|
|
505910
505924
|
}
|
|
505911
505925
|
if (autocompleteCancelled) {
|
|
505926
|
+
if (editor.inputMode === "prompt" && editor.getText().trimStart().startsWith("/")) editor.setText("");
|
|
505912
505927
|
this.clearPendingUndoEsc();
|
|
505913
505928
|
return;
|
|
505914
505929
|
}
|
|
@@ -505949,8 +505964,9 @@ var EditorKeyboardController = class {
|
|
|
505949
505964
|
return true;
|
|
505950
505965
|
};
|
|
505951
505966
|
editor.onCtrlS = () => {
|
|
505952
|
-
|
|
505953
|
-
host.
|
|
505967
|
+
const draft = editor.getText().trim();
|
|
505968
|
+
if (!host.streamingUI.hasActiveTurn() && host.state.appState.streamingPhase === "idle" && !draft.trimStart().startsWith("/")) return;
|
|
505969
|
+
host.flushQueuedMessages(draft, editor.inputMode);
|
|
505954
505970
|
host.updateQueueDisplay();
|
|
505955
505971
|
host.state.ui.requestRender();
|
|
505956
505972
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "blun-king-cli",
|
|
3
|
-
"version": "9.1.
|
|
3
|
+
"version": "9.1.523",
|
|
4
4
|
"description": "BLUN CLI - your own AI agent with a Telegram channel. Get it done. With BLUN.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"bin": {
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
},
|
|
10
10
|
"scripts": {
|
|
11
11
|
"test": "node --test test/*.test.js",
|
|
12
|
-
"prepack": "node scripts/check-release-metadata.js && node scripts/check-todo-loop-regression.js && node scripts/check-todo-recovery-catalog-regression.js && node scripts/check-historical-tool-result-preview-regression.js && node scripts/check-session-start-hook-context-regression.js && node scripts/check-queue-controls-regression.js && node scripts/check-approval-queue-shortcuts-regression.js && node scripts/check-telegram-bridge-watchdog.js && node scripts/check-resume-replay-regression.js && node scripts/check-session-cancel-regression.js && node scripts/check-plugin-startup-regression.js && node scripts/check-active-profile-plugin-startup.js && node scripts/check-mcp-startup-wait-budget.js",
|
|
12
|
+
"prepack": "node scripts/check-release-metadata.js && node scripts/check-todo-loop-regression.js && node scripts/check-todo-recovery-catalog-regression.js && node scripts/check-historical-tool-result-preview-regression.js && node scripts/check-session-start-hook-context-regression.js && node scripts/check-queue-controls-regression.js && node scripts/check-approval-queue-shortcuts-regression.js && node scripts/check-approval-observability-regression.js && node scripts/check-slash-escape-regression.js && node scripts/check-telegram-bridge-watchdog.js && node scripts/check-resume-replay-regression.js && node scripts/check-session-cancel-regression.js && node scripts/check-plugin-startup-regression.js && node scripts/check-active-profile-plugin-startup.js && node scripts/check-mcp-startup-wait-budget.js",
|
|
13
13
|
"release:verify": "node scripts/check-release-metadata.js --external",
|
|
14
14
|
"postinstall": "node scripts/fix-node-pty-perms.js"
|
|
15
15
|
},
|
|
@@ -38,6 +38,8 @@
|
|
|
38
38
|
"scripts/check-package-regression.js",
|
|
39
39
|
"scripts/check-active-profile-plugin-startup.js",
|
|
40
40
|
"scripts/check-approval-queue-shortcuts-regression.js",
|
|
41
|
+
"scripts/check-approval-observability-regression.js",
|
|
42
|
+
"scripts/check-slash-escape-regression.js",
|
|
41
43
|
"scripts/check-mcp-startup-wait-budget.js",
|
|
42
44
|
"scripts/check-plugin-startup-regression.js",
|
|
43
45
|
"scripts/check-queue-controls-regression.js",
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const assert = require('node:assert/strict');
|
|
5
|
+
const fs = require('node:fs');
|
|
6
|
+
const path = require('node:path');
|
|
7
|
+
|
|
8
|
+
const packageRoot = path.resolve(__dirname, '..');
|
|
9
|
+
const bundlePath = process.env.BLUN_BUNDLE_UNDER_TEST
|
|
10
|
+
? path.resolve(process.env.BLUN_BUNDLE_UNDER_TEST)
|
|
11
|
+
: path.join(packageRoot, 'blun.mjs');
|
|
12
|
+
const relayPath = process.env.BLUN_APPROVAL_RELAY_UNDER_TEST
|
|
13
|
+
? path.resolve(process.env.BLUN_APPROVAL_RELAY_UNDER_TEST)
|
|
14
|
+
: path.join(packageRoot, 'bin', 'telegram-approval-relay.cjs');
|
|
15
|
+
const pluginRelayPath = process.env.BLUN_PLUGIN_APPROVAL_RELAY_UNDER_TEST
|
|
16
|
+
? path.resolve(process.env.BLUN_PLUGIN_APPROVAL_RELAY_UNDER_TEST)
|
|
17
|
+
: path.join(packageRoot, 'telegram-plugin', 'bin', 'telegram-approval-relay.cjs');
|
|
18
|
+
|
|
19
|
+
const bundle = fs.readFileSync(bundlePath, 'utf8');
|
|
20
|
+
const requestToolApproval = bundle.match(
|
|
21
|
+
/async requestToolApproval\(context, result, policyName\) \{[\s\S]*?\n\t\t\}/,
|
|
22
|
+
);
|
|
23
|
+
assert(requestToolApproval, 'APPROVAL_OBSERVABILITY_REGRESSION: requestToolApproval is missing');
|
|
24
|
+
assert.match(
|
|
25
|
+
requestToolApproval[0],
|
|
26
|
+
/this\.agent\.records\.logRecord\(\{[\s\S]*?type: "permission\.approval_requested"[\s\S]*?toolCallId: id[\s\S]*?toolName: name/,
|
|
27
|
+
'APPROVAL_OBSERVABILITY_REGRESSION: opening an approval is invisible in the wire',
|
|
28
|
+
);
|
|
29
|
+
assert(
|
|
30
|
+
requestToolApproval[0].indexOf('type: "permission.approval_requested"')
|
|
31
|
+
< requestToolApproval[0].indexOf('await this.agent.rpc.requestApproval'),
|
|
32
|
+
'APPROVAL_OBSERVABILITY_REGRESSION: approval wire event is emitted too late',
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
const ApprovalProbe = Function(`return class ApprovalProbe {${requestToolApproval[0]}};`)();
|
|
36
|
+
const wireRecords = [];
|
|
37
|
+
const probe = new ApprovalProbe();
|
|
38
|
+
probe.agent = {
|
|
39
|
+
records: { logRecord(record) { wireRecords.push(record); } },
|
|
40
|
+
rpc: { async requestApproval() { return { decision: 'approved' }; } },
|
|
41
|
+
hooks: { fireAndForgetTrigger() {} },
|
|
42
|
+
telemetry: { track() {} },
|
|
43
|
+
};
|
|
44
|
+
probe.recordApprovalResult = () => {};
|
|
45
|
+
probe.permissionPolicyResolutionToPrepare = () => undefined;
|
|
46
|
+
probe.formatApprovalRejectionMessage = () => '';
|
|
47
|
+
|
|
48
|
+
const approvalRun = probe.requestToolApproval({
|
|
49
|
+
signal: new AbortController().signal,
|
|
50
|
+
turnId: 7,
|
|
51
|
+
toolCall: { id: 'tool-7', name: 'Bash' },
|
|
52
|
+
execution: {
|
|
53
|
+
description: 'Run command',
|
|
54
|
+
display: { kind: 'command', command: 'echo ok' },
|
|
55
|
+
},
|
|
56
|
+
args: { command: 'echo ok' },
|
|
57
|
+
}, {}, 'manual-approval');
|
|
58
|
+
assert.equal(wireRecords.length, 1, 'approval request must be written before awaiting a response');
|
|
59
|
+
assert.deepEqual(
|
|
60
|
+
wireRecords[0],
|
|
61
|
+
{
|
|
62
|
+
type: 'permission.approval_requested',
|
|
63
|
+
turnId: 7,
|
|
64
|
+
toolCallId: 'tool-7',
|
|
65
|
+
toolName: 'Bash',
|
|
66
|
+
action: 'Run command',
|
|
67
|
+
display: { kind: 'command', command: 'echo ok' },
|
|
68
|
+
policyName: 'manual-approval',
|
|
69
|
+
},
|
|
70
|
+
'approval wire record lost identifying fields',
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
function checkRelay(modulePath, label) {
|
|
74
|
+
delete require.cache[require.resolve(modulePath)];
|
|
75
|
+
const { resolveTelegramApprovalTarget } = require(modulePath);
|
|
76
|
+
assert.equal(
|
|
77
|
+
resolveTelegramApprovalTarget(['1605241602', '-1003927574737']),
|
|
78
|
+
'1605241602',
|
|
79
|
+
`${label}: one authorized private chat must be selected even when groups are also allowed`,
|
|
80
|
+
);
|
|
81
|
+
assert.equal(
|
|
82
|
+
resolveTelegramApprovalTarget(['0', '-1003927574737']),
|
|
83
|
+
null,
|
|
84
|
+
`${label}: zero is not a positive private Telegram chat ID`,
|
|
85
|
+
);
|
|
86
|
+
assert.equal(
|
|
87
|
+
resolveTelegramApprovalTarget(['1605241602', '8711923962', '-1003927574737']),
|
|
88
|
+
null,
|
|
89
|
+
`${label}: multiple authorized private chats must remain fail-closed`,
|
|
90
|
+
);
|
|
91
|
+
assert.equal(
|
|
92
|
+
resolveTelegramApprovalTarget(['1605241602', '8711923962'], '8711923962'),
|
|
93
|
+
'8711923962',
|
|
94
|
+
`${label}: an explicitly configured authorized chat must win`,
|
|
95
|
+
);
|
|
96
|
+
assert.equal(
|
|
97
|
+
resolveTelegramApprovalTarget(['1605241602'], '-1003927574737'),
|
|
98
|
+
null,
|
|
99
|
+
`${label}: an unauthorized configured chat must be rejected`,
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
checkRelay(relayPath, 'package relay');
|
|
104
|
+
checkRelay(pluginRelayPath, 'plugin relay');
|
|
105
|
+
|
|
106
|
+
approvalRun.then(() => {
|
|
107
|
+
process.stdout.write('approval-observability-regression PASS\n');
|
|
108
|
+
}).catch((error) => {
|
|
109
|
+
process.stderr.write(`${error.stack || error.message}\n`);
|
|
110
|
+
process.exitCode = 1;
|
|
111
|
+
});
|
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
const fs = require('node:fs');
|
|
5
|
+
const os = require('node:os');
|
|
5
6
|
const path = require('node:path');
|
|
7
|
+
const { spawnSync } = require('node:child_process');
|
|
6
8
|
|
|
7
9
|
const bundlePath = process.env.BLUN_BUNDLE_UNDER_TEST
|
|
8
10
|
? path.resolve(process.env.BLUN_BUNDLE_UNDER_TEST)
|
|
@@ -31,6 +33,15 @@ const stringPredicate = bundle.match(
|
|
|
31
33
|
const trigger = bundle.match(
|
|
32
34
|
/async triggerSessionStart\(source\) \{[\s\S]*?\n\t\t\}/,
|
|
33
35
|
);
|
|
36
|
+
const scheduler = bundle.match(
|
|
37
|
+
/scheduleSessionStart\(source\) \{[\s\S]*?\n\t\t\}/,
|
|
38
|
+
);
|
|
39
|
+
const createMain = bundle.match(
|
|
40
|
+
/async createMain\(\) \{[\s\S]*?\n\t\t\}/,
|
|
41
|
+
);
|
|
42
|
+
const resume = bundle.match(
|
|
43
|
+
/async resume\(\) \{[\s\S]*?\n\t\t\}/,
|
|
44
|
+
);
|
|
34
45
|
|
|
35
46
|
assert(renderer, 'SESSION_START_HOOK_CONTEXT_REGRESSION: SessionStart renderer is missing');
|
|
36
47
|
assert(allowRenderer, 'SESSION_START_HOOK_CONTEXT_REGRESSION: shared allow renderer is missing');
|
|
@@ -38,6 +49,9 @@ assert(wrapperRenderer, 'SESSION_START_HOOK_CONTEXT_REGRESSION: hook wrapper ren
|
|
|
38
49
|
assert(messageSelector, 'SESSION_START_HOOK_CONTEXT_REGRESSION: hook message selector is missing');
|
|
39
50
|
assert(stringPredicate, 'SESSION_START_HOOK_CONTEXT_REGRESSION: hook string predicate is missing');
|
|
40
51
|
assert(trigger, 'SESSION_START_HOOK_CONTEXT_REGRESSION: SessionStart trigger is missing');
|
|
52
|
+
assert(scheduler, 'SESSION_START_HOOK_CONTEXT_REGRESSION: non-blocking SessionStart scheduler is missing');
|
|
53
|
+
assert(createMain, 'SESSION_START_HOOK_CONTEXT_REGRESSION: createMain is missing');
|
|
54
|
+
assert(resume, 'SESSION_START_HOOK_CONTEXT_REGRESSION: resume is missing');
|
|
41
55
|
assert(
|
|
42
56
|
/renderAllowHookResult\("SessionStart", results\)/.test(renderer[0]),
|
|
43
57
|
'SESSION_START_HOOK_CONTEXT_REGRESSION: SessionStart output is not rendered',
|
|
@@ -56,16 +70,98 @@ assert(
|
|
|
56
70
|
);
|
|
57
71
|
assert(
|
|
58
72
|
/await mainAgent\.records\.flush\(\)/.test(trigger[0]),
|
|
59
|
-
'SESSION_START_HOOK_CONTEXT_REGRESSION: SessionStart reminder is not flushed
|
|
73
|
+
'SESSION_START_HOOK_CONTEXT_REGRESSION: completed SessionStart reminder is not flushed',
|
|
74
|
+
);
|
|
75
|
+
assert(
|
|
76
|
+
/this\.scheduleSessionStart\("startup"\)/.test(createMain[0])
|
|
77
|
+
&& !/await this\.triggerSessionStart\("startup"\)/.test(createMain[0]),
|
|
78
|
+
'SESSION_START_HOOK_CONTEXT_REGRESSION: fresh-session input is still blocked by SessionStart',
|
|
79
|
+
);
|
|
80
|
+
assert(
|
|
81
|
+
/this\.scheduleSessionStart\("resume"\)/.test(resume[0])
|
|
82
|
+
&& !/await this\.triggerSessionStart\("resume"\)/.test(resume[0]),
|
|
83
|
+
'SESSION_START_HOOK_CONTEXT_REGRESSION: resumed-session input is still blocked by SessionStart',
|
|
84
|
+
);
|
|
85
|
+
assert(
|
|
86
|
+
/void this\.triggerSessionStart\(source\)\.catch\(/.test(scheduler[0]),
|
|
87
|
+
'SESSION_START_HOOK_CONTEXT_REGRESSION: SessionStart is not detached from interactive startup',
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
const packageRoot = path.resolve(__dirname, '..');
|
|
91
|
+
const agentSpineRoot = path.join(packageRoot, 'agent-spine-plugin');
|
|
92
|
+
const agentSpineManifest = JSON.parse(
|
|
93
|
+
fs.readFileSync(path.join(agentSpineRoot, 'blun.plugin.json'), 'utf8'),
|
|
94
|
+
);
|
|
95
|
+
const agentSpineCodexHooks = JSON.parse(
|
|
96
|
+
fs.readFileSync(path.join(agentSpineRoot, 'hooks', 'codex.json'), 'utf8'),
|
|
97
|
+
);
|
|
98
|
+
const blunSessionStart = agentSpineManifest.hooks.find(
|
|
99
|
+
(hook) => hook.event === 'SessionStart',
|
|
100
|
+
);
|
|
101
|
+
const codexSessionStart = agentSpineCodexHooks.hooks.SessionStart?.[0]?.hooks?.[0];
|
|
102
|
+
|
|
103
|
+
assert(
|
|
104
|
+
blunSessionStart?.timeout >= 180,
|
|
105
|
+
'SESSION_START_HOOK_CONTEXT_REGRESSION: BLUN AgentSpine SessionStart timeout must cover the measured 123.6 s cold scan',
|
|
60
106
|
);
|
|
107
|
+
assert(
|
|
108
|
+
codexSessionStart?.timeout >= 180,
|
|
109
|
+
'SESSION_START_HOOK_CONTEXT_REGRESSION: Codex AgentSpine SessionStart timeout must match the BLUN runtime budget',
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
const probeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'blun-session-start-hook-'));
|
|
113
|
+
try {
|
|
114
|
+
fs.mkdirSync(path.join(probeRoot, '.git'));
|
|
115
|
+
fs.writeFileSync(
|
|
116
|
+
path.join(probeRoot, 'AGENTS.md'),
|
|
117
|
+
'# SessionStart probe\n\nLoad this project instruction automatically.\n',
|
|
118
|
+
);
|
|
119
|
+
const stateRoot = path.join(probeRoot, '.agentspine-state');
|
|
120
|
+
const hookRun = spawnSync(process.execPath, [path.join(agentSpineRoot, 'src', 'hook.js')], {
|
|
121
|
+
cwd: agentSpineRoot,
|
|
122
|
+
input: JSON.stringify({
|
|
123
|
+
hook_event_name: 'SessionStart',
|
|
124
|
+
session_id: 'session-start-regression',
|
|
125
|
+
cwd: probeRoot,
|
|
126
|
+
source: 'resume',
|
|
127
|
+
}),
|
|
128
|
+
encoding: 'utf8',
|
|
129
|
+
timeout: 30_000,
|
|
130
|
+
env: {
|
|
131
|
+
...process.env,
|
|
132
|
+
BLUN_HOME: probeRoot,
|
|
133
|
+
BLUN_PLUGIN_ROOT: agentSpineRoot,
|
|
134
|
+
AGENTSPINE_STATE_DIR: stateRoot,
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
assert(
|
|
138
|
+
hookRun.error === undefined && hookRun.status === 0,
|
|
139
|
+
`SESSION_START_HOOK_CONTEXT_REGRESSION: real AgentSpine hook failed: ${hookRun.error?.message || hookRun.stderr}`,
|
|
140
|
+
);
|
|
141
|
+
const hookOutput = JSON.parse(hookRun.stdout.trim());
|
|
142
|
+
assert(
|
|
143
|
+
hookOutput.hookSpecificOutput?.hookEventName === 'SessionStart'
|
|
144
|
+
&& hookOutput.hookSpecificOutput?.message?.includes('AgentSpine'),
|
|
145
|
+
`SESSION_START_HOOK_CONTEXT_REGRESSION: real AgentSpine process output is not injectable: ${hookRun.stdout.trim()}`,
|
|
146
|
+
);
|
|
147
|
+
} finally {
|
|
148
|
+
fs.rmSync(probeRoot, { recursive: true, force: true });
|
|
149
|
+
}
|
|
61
150
|
|
|
62
151
|
const triggerFunction = trigger[0].replace(
|
|
63
152
|
/^async triggerSessionStart/,
|
|
64
153
|
'async function triggerSessionStart',
|
|
65
154
|
);
|
|
155
|
+
const schedulerFunction = scheduler[0].replace(
|
|
156
|
+
/^scheduleSessionStart/,
|
|
157
|
+
'function scheduleSessionStart',
|
|
158
|
+
);
|
|
66
159
|
const runTrigger = Function(
|
|
67
160
|
`${wrapperRenderer[0]}\n${messageSelector[0]}\n${stringPredicate[0]}\n${allowRenderer[0]}\n${renderer[0]}\n${triggerFunction}\nreturn triggerSessionStart;`,
|
|
68
161
|
)();
|
|
162
|
+
const scheduleTrigger = Function(
|
|
163
|
+
`${schedulerFunction}\nreturn scheduleSessionStart;`,
|
|
164
|
+
)();
|
|
69
165
|
|
|
70
166
|
(async () => {
|
|
71
167
|
const reminders = [];
|
|
@@ -108,6 +204,23 @@ const runTrigger = Function(
|
|
|
108
204
|
'runtime probe used the wrong reminder origin',
|
|
109
205
|
);
|
|
110
206
|
|
|
207
|
+
let detachedCompleted = false;
|
|
208
|
+
const detachedStartedAt = Date.now();
|
|
209
|
+
scheduleTrigger.call({
|
|
210
|
+
async triggerSessionStart(source) {
|
|
211
|
+
assert(source === 'startup', 'detached runtime probe lost the startup source');
|
|
212
|
+
await new Promise((resolve) => setTimeout(resolve, 75));
|
|
213
|
+
detachedCompleted = true;
|
|
214
|
+
},
|
|
215
|
+
log: { warn() {} },
|
|
216
|
+
}, 'startup');
|
|
217
|
+
assert(
|
|
218
|
+
Date.now() - detachedStartedAt < 50 && detachedCompleted === false,
|
|
219
|
+
'SessionStart scheduler still waits for the hook before returning',
|
|
220
|
+
);
|
|
221
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
222
|
+
assert(detachedCompleted, 'detached SessionStart hook did not finish in the background');
|
|
223
|
+
|
|
111
224
|
process.stdout.write('session-start-hook-context-regression PASS\n');
|
|
112
225
|
})().catch((error) => {
|
|
113
226
|
process.stderr.write(`${error.stack || error.message}\n`);
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
const assert = require('node:assert/strict');
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
|
|
5
|
+
const packageRoot = path.resolve(__dirname, '..');
|
|
6
|
+
const bundle = fs.readFileSync(path.join(packageRoot, 'blun.mjs'), 'utf8');
|
|
7
|
+
const match = /editor\.onEscape = \(autocompleteCancelled = false\) => \{([\s\S]*?)\n\t\t\};\n\t\teditor\.onShiftTab =/.exec(bundle);
|
|
8
|
+
assert(match, 'SLASH_ESCAPE_REGRESSION: editor.onEscape handler is missing');
|
|
9
|
+
|
|
10
|
+
const runEscape = Function('host', 'editor', 'autocompleteCancelled', match[1]);
|
|
11
|
+
const ctrlSMatch = /editor\.onCtrlS = \(\) => \{([\s\S]*?)\n\t\t\};\n\t\teditor\.onCtrlB =/.exec(bundle);
|
|
12
|
+
assert(ctrlSMatch, 'SLASH_ESCAPE_REGRESSION: editor.onCtrlS handler is missing');
|
|
13
|
+
const runCtrlS = Function('host', 'editor', ctrlSMatch[1]);
|
|
14
|
+
|
|
15
|
+
function probe(initialText, autocompleteCancelled) {
|
|
16
|
+
let text = initialText;
|
|
17
|
+
const editor = {
|
|
18
|
+
inputMode: 'prompt',
|
|
19
|
+
getText: () => text,
|
|
20
|
+
setText: (value) => { text = value; },
|
|
21
|
+
};
|
|
22
|
+
const host = {
|
|
23
|
+
cancelInFlight: undefined,
|
|
24
|
+
queueSteerInFlight: undefined,
|
|
25
|
+
state: {
|
|
26
|
+
activeDialog: null,
|
|
27
|
+
appState: {
|
|
28
|
+
isCompacting: false,
|
|
29
|
+
streamingPhase: 'idle',
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
streamingUI: { hasActiveTurn: () => false },
|
|
33
|
+
btwPanelController: { closeOrCancel: () => false },
|
|
34
|
+
};
|
|
35
|
+
const controller = {
|
|
36
|
+
pendingExit: null,
|
|
37
|
+
pendingUndoEsc: null,
|
|
38
|
+
clearPendingExit() {},
|
|
39
|
+
clearPendingUndoEsc() {},
|
|
40
|
+
armPendingUndoEsc() {},
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
runEscape.call(controller, host, editor, autocompleteCancelled);
|
|
44
|
+
return text;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
assert.equal(
|
|
48
|
+
probe('/reload', true),
|
|
49
|
+
'',
|
|
50
|
+
'SLASH_ESCAPE_REGRESSION: Escape must cancel the open slash-command draft together with its menu',
|
|
51
|
+
);
|
|
52
|
+
assert.equal(
|
|
53
|
+
probe('ordinary draft', true),
|
|
54
|
+
'ordinary draft',
|
|
55
|
+
'SLASH_ESCAPE_REGRESSION: cancelling ordinary autocomplete must preserve the draft',
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
let flushed = null;
|
|
59
|
+
const idleHost = {
|
|
60
|
+
streamingUI: { hasActiveTurn: () => false },
|
|
61
|
+
state: {
|
|
62
|
+
appState: { streamingPhase: 'idle' },
|
|
63
|
+
ui: { requestRender() {} },
|
|
64
|
+
},
|
|
65
|
+
flushQueuedMessages: (draft, mode) => { flushed = { draft, mode }; },
|
|
66
|
+
updateQueueDisplay() {},
|
|
67
|
+
};
|
|
68
|
+
const slashEditor = {
|
|
69
|
+
inputMode: 'prompt',
|
|
70
|
+
getText: () => '/reload',
|
|
71
|
+
};
|
|
72
|
+
runCtrlS(idleHost, slashEditor);
|
|
73
|
+
assert.deepEqual(
|
|
74
|
+
flushed,
|
|
75
|
+
{ draft: '/reload', mode: 'prompt' },
|
|
76
|
+
'SLASH_ESCAPE_REGRESSION: Ctrl+S must hand an idle slash draft to the existing queue drain',
|
|
77
|
+
);
|
|
78
|
+
flushed = null;
|
|
79
|
+
runCtrlS(idleHost, {
|
|
80
|
+
inputMode: 'prompt',
|
|
81
|
+
getText: () => 'ordinary draft',
|
|
82
|
+
});
|
|
83
|
+
assert.equal(
|
|
84
|
+
flushed,
|
|
85
|
+
null,
|
|
86
|
+
'SLASH_ESCAPE_REGRESSION: the existing idle behavior for ordinary drafts must stay unchanged',
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
console.log('slash-escape-regression PASS (Escape + Ctrl+S)');
|
|
@@ -68,6 +68,8 @@ function resolveTelegramApprovalTarget(allowFrom, configuredChatId) {
|
|
|
68
68
|
: [];
|
|
69
69
|
const configured = String(configuredChatId ?? '').trim();
|
|
70
70
|
if (configured.length > 0) return allowed.includes(configured) ? configured : null;
|
|
71
|
+
const privateChats = allowed.filter((value) => /^[1-9]\d*$/u.test(value));
|
|
72
|
+
if (privateChats.length === 1) return privateChats[0];
|
|
71
73
|
return allowed.length === 1 ? allowed[0] : null;
|
|
72
74
|
}
|
|
73
75
|
|
|
@@ -280,4 +282,3 @@ module.exports = {
|
|
|
280
282
|
wasTelegramApprovalSent,
|
|
281
283
|
writeTelegramApprovalResponse,
|
|
282
284
|
};
|
|
283
|
-
|
|
@@ -1,317 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const TOOL_RESULT_MAX_CHARS = 12_000;
|
|
4
|
-
const TOOL_RESULT_PREVIEW_CHARS = 2_000;
|
|
5
|
-
const TOOL_RESULT_RECOVERY_PAGE_LINES = 20;
|
|
6
|
-
const TOOL_RESULT_OFFLOAD_MARKER = '[Tool result offloaded]';
|
|
7
|
-
const TOOL_RESULT_BATCH_MAX_CHARS = TOOL_RESULT_MAX_CHARS;
|
|
8
|
-
const TOOL_RESULT_BATCH_MIN_ITEM_CHARS = 3_000;
|
|
9
|
-
const TOOL_RESULT_BATCH_REPLACEMENT_BUDGET_CHARS = 2_500;
|
|
10
|
-
const TOOL_RESULT_HISTORICAL_KEEP_RECENT_MESSAGES = 4;
|
|
11
|
-
const TOOL_RESULT_HISTORICAL_MAX_CHARS = TOOL_RESULT_BATCH_MAX_CHARS;
|
|
12
|
-
const TOOL_RESULT_HISTORICAL_MIN_ITEM_CHARS = 600;
|
|
13
|
-
const TOOL_RESULT_HISTORICAL_REPLACEMENT_BUDGET_CHARS = 600;
|
|
14
|
-
const TOOL_RESULT_SUCCESS_KEEP_RECENT_MESSAGES = 12;
|
|
15
|
-
const TOOL_RESULT_HISTORICAL_SUCCESS_MARKER = '[Old tool result content cleared]';
|
|
16
|
-
const TOOL_RESULT_REPEAT_MARKER = '[Repeated tool result omitted]';
|
|
17
|
-
const READ_CONTINUATION_LINE_OFFSET_RE = /^Continue reading with line_offset=(\d+)\. Do not assume you have reached the end of the file\.$/mu;
|
|
18
|
-
|
|
19
|
-
function shouldOffloadToolResult(textLength) {
|
|
20
|
-
return Number.isFinite(textLength) && textLength > TOOL_RESULT_MAX_CHARS;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
function shouldKeepFreshToolResult(toolName) {
|
|
24
|
-
return toolName === 'Read';
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function createToolResultPreview(text) {
|
|
28
|
-
if (text.length <= TOOL_RESULT_PREVIEW_CHARS) return text;
|
|
29
|
-
|
|
30
|
-
const headChars = Math.ceil(TOOL_RESULT_PREVIEW_CHARS / 2);
|
|
31
|
-
const tailChars = TOOL_RESULT_PREVIEW_CHARS - headChars;
|
|
32
|
-
const omittedChars = text.length - headChars - tailChars;
|
|
33
|
-
return `${text.slice(0, headChars)}\n\n[... ${String(omittedChars)} characters omitted ...]\n\n${text.slice(-tailChars)}`;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function readContinuationLineOffset(text) {
|
|
37
|
-
if (typeof text !== 'string') return undefined;
|
|
38
|
-
const value = Number(text.match(READ_CONTINUATION_LINE_OFFSET_RE)?.[1]);
|
|
39
|
-
return Number.isSafeInteger(value) && value >= 1 ? value : undefined;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function isPersistedToolResultReference(content) {
|
|
43
|
-
if (!Array.isArray(content)) return false;
|
|
44
|
-
|
|
45
|
-
return content.some((part) => {
|
|
46
|
-
if (part?.type !== 'text' || typeof part.text !== 'string') return false;
|
|
47
|
-
if (!part.text.includes('\noutput_path: ')) return false;
|
|
48
|
-
return part.text.startsWith(`${TOOL_RESULT_OFFLOAD_MARKER}\n`)
|
|
49
|
-
|| /^Tool output exceeded \d+ characters; showing a preview only\.\n/u.test(part.text);
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function freshToolResultIds(messages) {
|
|
54
|
-
if (!Array.isArray(messages) || messages.length === 0) return new Set();
|
|
55
|
-
|
|
56
|
-
let assistantIndex = -1;
|
|
57
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
58
|
-
if (messages[index]?.role !== 'assistant') continue;
|
|
59
|
-
assistantIndex = index;
|
|
60
|
-
break;
|
|
61
|
-
}
|
|
62
|
-
if (assistantIndex < 0 || !Array.isArray(messages[assistantIndex].toolCalls)) return new Set();
|
|
63
|
-
|
|
64
|
-
const requestedIds = new Set(messages[assistantIndex].toolCalls
|
|
65
|
-
.map((call) => call?.id ?? call?.toolCallId)
|
|
66
|
-
.filter((id) => typeof id === 'string' && id.length > 0));
|
|
67
|
-
if (requestedIds.size === 0) return new Set();
|
|
68
|
-
|
|
69
|
-
const resultIds = new Set();
|
|
70
|
-
for (let index = assistantIndex + 1; index < messages.length; index += 1) {
|
|
71
|
-
const message = messages[index];
|
|
72
|
-
if (message?.role === 'tool' && requestedIds.has(message.toolCallId)) {
|
|
73
|
-
resultIds.add(message.toolCallId);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
return resultIds;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function compactPersistedToolResultReference(content) {
|
|
80
|
-
if (!isPersistedToolResultReference(content)) return content;
|
|
81
|
-
|
|
82
|
-
let changed = false;
|
|
83
|
-
const compacted = content.map((part) => {
|
|
84
|
-
if (part?.type !== 'text' || typeof part.text !== 'string') return part;
|
|
85
|
-
const previewIndex = part.text.indexOf('\n[preview: head and tail]\n');
|
|
86
|
-
const referenceText = previewIndex < 0
|
|
87
|
-
? part.text
|
|
88
|
-
: part.text.slice(0, previewIndex).trimEnd();
|
|
89
|
-
if (!referenceText.startsWith(`${TOOL_RESULT_OFFLOAD_MARKER}\n`)) {
|
|
90
|
-
if (referenceText === part.text) return part;
|
|
91
|
-
changed = true;
|
|
92
|
-
return { ...part, text: referenceText };
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const lines = referenceText.split(/\r?\n/u);
|
|
96
|
-
const outputPath = lines.find((line) => line.startsWith('output_path: '));
|
|
97
|
-
if (outputPath === undefined) return part;
|
|
98
|
-
const recoveryLines = [TOOL_RESULT_OFFLOAD_MARKER];
|
|
99
|
-
for (const prefix of ['tool_name: ', 'output_size_chars: ', 'next_line_offset: ']) {
|
|
100
|
-
const line = lines.find((candidate) => candidate.startsWith(prefix));
|
|
101
|
-
if (line !== undefined) recoveryLines.push(line);
|
|
102
|
-
}
|
|
103
|
-
if (recoveryLines.some((line) => line.startsWith('next_line_offset: '))) {
|
|
104
|
-
const nextStep = lines.find((line) => line.startsWith('next_step: '));
|
|
105
|
-
if (nextStep !== undefined) recoveryLines.push(nextStep);
|
|
106
|
-
}
|
|
107
|
-
recoveryLines.push(outputPath);
|
|
108
|
-
const text = recoveryLines.join('\n');
|
|
109
|
-
if (text === part.text) return part;
|
|
110
|
-
changed = true;
|
|
111
|
-
return {
|
|
112
|
-
...part,
|
|
113
|
-
text,
|
|
114
|
-
};
|
|
115
|
-
});
|
|
116
|
-
|
|
117
|
-
return changed ? compacted : content;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function compactHistoricalSuccessfulToolResults(messages) {
|
|
121
|
-
if (!Array.isArray(messages) || messages.length === 0) return messages;
|
|
122
|
-
|
|
123
|
-
const recentStart = Math.max(0, messages.length - TOOL_RESULT_SUCCESS_KEEP_RECENT_MESSAGES);
|
|
124
|
-
const freshIds = freshToolResultIds(messages);
|
|
125
|
-
let changed = false;
|
|
126
|
-
const projected = messages.map((message, index) => {
|
|
127
|
-
if (
|
|
128
|
-
index >= recentStart
|
|
129
|
-
|| message?.role !== 'tool'
|
|
130
|
-
|| freshIds.has(message.toolCallId)
|
|
131
|
-
|| message.isError === true
|
|
132
|
-
|| !Array.isArray(message.content)
|
|
133
|
-
|| isPersistedToolResultReference(message.content)
|
|
134
|
-
|| !message.content.every((part) => part?.type === 'text' && typeof part.text === 'string')
|
|
135
|
-
) return message;
|
|
136
|
-
|
|
137
|
-
const textChars = message.content.reduce((total, part) => total + part.text.length, 0);
|
|
138
|
-
if (textChars <= TOOL_RESULT_HISTORICAL_SUCCESS_MARKER.length) return message;
|
|
139
|
-
changed = true;
|
|
140
|
-
return {
|
|
141
|
-
...message,
|
|
142
|
-
content: [{ type: 'text', text: TOOL_RESULT_HISTORICAL_SUCCESS_MARKER }],
|
|
143
|
-
};
|
|
144
|
-
});
|
|
145
|
-
|
|
146
|
-
return changed ? projected : messages;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
function toolCallSignaturesById(messages) {
|
|
150
|
-
const signatures = new Map();
|
|
151
|
-
|
|
152
|
-
for (const message of messages) {
|
|
153
|
-
if (!Array.isArray(message?.toolCalls)) continue;
|
|
154
|
-
for (const call of message.toolCalls) {
|
|
155
|
-
const id = call?.id ?? call?.toolCallId;
|
|
156
|
-
if (typeof id !== 'string' || typeof call?.name !== 'string') continue;
|
|
157
|
-
const args = typeof call.arguments === 'string'
|
|
158
|
-
? call.arguments
|
|
159
|
-
: JSON.stringify(call.arguments ?? null);
|
|
160
|
-
signatures.set(id, `${call.name}\n${args}`);
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
return signatures;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
function repeatedToolResultReference(newestToolCallId) {
|
|
168
|
-
return [
|
|
169
|
-
TOOL_RESULT_REPEAT_MARKER,
|
|
170
|
-
`same_as_tool_call_id: ${newestToolCallId}`,
|
|
171
|
-
'reason: identical successful result for the same tool call arguments',
|
|
172
|
-
].join('\n');
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
function dedupeRepeatedSuccessfulToolResults(sourceMessages, projectedMessages = sourceMessages) {
|
|
176
|
-
if (
|
|
177
|
-
!Array.isArray(sourceMessages)
|
|
178
|
-
|| !Array.isArray(projectedMessages)
|
|
179
|
-
|| sourceMessages.length === 0
|
|
180
|
-
|| sourceMessages.length !== projectedMessages.length
|
|
181
|
-
) return projectedMessages;
|
|
182
|
-
|
|
183
|
-
const callSignatures = toolCallSignaturesById(sourceMessages);
|
|
184
|
-
const seenResultsByCall = new Map();
|
|
185
|
-
let changed = false;
|
|
186
|
-
const projected = projectedMessages.slice();
|
|
187
|
-
|
|
188
|
-
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
|
|
189
|
-
const message = sourceMessages[index];
|
|
190
|
-
const toolCallId = message?.toolCallId;
|
|
191
|
-
if (
|
|
192
|
-
message?.role !== 'tool'
|
|
193
|
-
|| message.isError === true
|
|
194
|
-
|| typeof toolCallId !== 'string'
|
|
195
|
-
|| !Array.isArray(message.content)
|
|
196
|
-
|| message.content.length === 0
|
|
197
|
-
|| isPersistedToolResultReference(message.content)
|
|
198
|
-
|| !message.content.every((part) => part?.type === 'text' && typeof part.text === 'string')
|
|
199
|
-
) continue;
|
|
200
|
-
|
|
201
|
-
const callSignature = callSignatures.get(toolCallId);
|
|
202
|
-
if (callSignature === undefined) continue;
|
|
203
|
-
const resultShape = message.content.length;
|
|
204
|
-
const resultSignature = resultShape === 1
|
|
205
|
-
? message.content[0].text
|
|
206
|
-
: JSON.stringify(message.content.map((part) => part.text));
|
|
207
|
-
let seenResults = seenResultsByCall.get(callSignature);
|
|
208
|
-
if (seenResults === undefined) {
|
|
209
|
-
seenResults = new Map();
|
|
210
|
-
seenResultsByCall.set(callSignature, seenResults);
|
|
211
|
-
}
|
|
212
|
-
let seenResultsForShape = seenResults.get(resultShape);
|
|
213
|
-
if (seenResultsForShape === undefined) {
|
|
214
|
-
seenResultsForShape = new Map();
|
|
215
|
-
seenResults.set(resultShape, seenResultsForShape);
|
|
216
|
-
}
|
|
217
|
-
const newest = seenResultsForShape.get(resultSignature);
|
|
218
|
-
if (newest === undefined) {
|
|
219
|
-
seenResultsForShape.set(resultSignature, { toolCallId, index });
|
|
220
|
-
continue;
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
const reference = repeatedToolResultReference(newest.toolCallId);
|
|
224
|
-
const textChars = message.content.reduce((total, part) => total + part.text.length, 0);
|
|
225
|
-
const projectedMessage = projected[index];
|
|
226
|
-
if (
|
|
227
|
-
reference.length >= textChars
|
|
228
|
-
|| projectedMessage?.role !== 'tool'
|
|
229
|
-
|| projectedMessage.toolCallId !== toolCallId
|
|
230
|
-
) continue;
|
|
231
|
-
projected[index] = {
|
|
232
|
-
...projectedMessage,
|
|
233
|
-
content: [{ type: 'text', text: reference }],
|
|
234
|
-
};
|
|
235
|
-
projected[newest.index] = {
|
|
236
|
-
...projected[newest.index],
|
|
237
|
-
content: sourceMessages[newest.index].content,
|
|
238
|
-
};
|
|
239
|
-
changed = true;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
return changed ? projected : projectedMessages;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
function selectToolResultBatchOffloads(textLengths) {
|
|
246
|
-
if (!Array.isArray(textLengths) || textLengths.length < 2) return [];
|
|
247
|
-
|
|
248
|
-
const normalized = textLengths.map((length) => (
|
|
249
|
-
Number.isFinite(length) && length > 0 ? Math.floor(length) : 0
|
|
250
|
-
));
|
|
251
|
-
const totalChars = normalized.reduce((total, length) => total + length, 0);
|
|
252
|
-
if (totalChars <= TOOL_RESULT_BATCH_MAX_CHARS) return [];
|
|
253
|
-
|
|
254
|
-
let projectedChars = totalChars;
|
|
255
|
-
const selected = [];
|
|
256
|
-
const candidates = normalized
|
|
257
|
-
.map((length, index) => ({ index, length }))
|
|
258
|
-
.filter(({ length }) => (
|
|
259
|
-
length >= TOOL_RESULT_BATCH_MIN_ITEM_CHARS
|
|
260
|
-
&& length <= TOOL_RESULT_MAX_CHARS
|
|
261
|
-
&& length > TOOL_RESULT_BATCH_REPLACEMENT_BUDGET_CHARS
|
|
262
|
-
))
|
|
263
|
-
.sort((left, right) => right.length - left.length || left.index - right.index);
|
|
264
|
-
|
|
265
|
-
for (const candidate of candidates) {
|
|
266
|
-
if (projectedChars <= TOOL_RESULT_BATCH_MAX_CHARS) break;
|
|
267
|
-
projectedChars -= candidate.length - TOOL_RESULT_BATCH_REPLACEMENT_BUDGET_CHARS;
|
|
268
|
-
selected.push(candidate.index);
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
return projectedChars <= TOOL_RESULT_BATCH_MAX_CHARS
|
|
272
|
-
? selected.sort((left, right) => left - right)
|
|
273
|
-
: [];
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
function selectHistoricalToolResultOffloads(textLengths) {
|
|
277
|
-
if (!Array.isArray(textLengths) || textLengths.length === 0) return [];
|
|
278
|
-
|
|
279
|
-
const normalized = textLengths.map((length) => (
|
|
280
|
-
Number.isFinite(length) && length > 0 ? Math.floor(length) : 0
|
|
281
|
-
));
|
|
282
|
-
return normalized
|
|
283
|
-
.map((length, index) => ({ index, length }))
|
|
284
|
-
.filter(({ length }) => (
|
|
285
|
-
length >= TOOL_RESULT_HISTORICAL_MIN_ITEM_CHARS
|
|
286
|
-
&& length > TOOL_RESULT_HISTORICAL_REPLACEMENT_BUDGET_CHARS
|
|
287
|
-
))
|
|
288
|
-
.map(({ index }) => index);
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
module.exports = {
|
|
292
|
-
TOOL_RESULT_BATCH_MAX_CHARS,
|
|
293
|
-
TOOL_RESULT_BATCH_MIN_ITEM_CHARS,
|
|
294
|
-
TOOL_RESULT_BATCH_REPLACEMENT_BUDGET_CHARS,
|
|
295
|
-
TOOL_RESULT_HISTORICAL_KEEP_RECENT_MESSAGES,
|
|
296
|
-
TOOL_RESULT_HISTORICAL_MAX_CHARS,
|
|
297
|
-
TOOL_RESULT_HISTORICAL_MIN_ITEM_CHARS,
|
|
298
|
-
TOOL_RESULT_HISTORICAL_REPLACEMENT_BUDGET_CHARS,
|
|
299
|
-
TOOL_RESULT_HISTORICAL_SUCCESS_MARKER,
|
|
300
|
-
TOOL_RESULT_REPEAT_MARKER,
|
|
301
|
-
TOOL_RESULT_MAX_CHARS,
|
|
302
|
-
TOOL_RESULT_PREVIEW_CHARS,
|
|
303
|
-
TOOL_RESULT_RECOVERY_PAGE_LINES,
|
|
304
|
-
TOOL_RESULT_OFFLOAD_MARKER,
|
|
305
|
-
TOOL_RESULT_SUCCESS_KEEP_RECENT_MESSAGES,
|
|
306
|
-
compactHistoricalSuccessfulToolResults,
|
|
307
|
-
compactPersistedToolResultReference,
|
|
308
|
-
createToolResultPreview,
|
|
309
|
-
dedupeRepeatedSuccessfulToolResults,
|
|
310
|
-
freshToolResultIds,
|
|
311
|
-
isPersistedToolResultReference,
|
|
312
|
-
readContinuationLineOffset,
|
|
313
|
-
selectHistoricalToolResultOffloads,
|
|
314
|
-
selectToolResultBatchOffloads,
|
|
315
|
-
shouldKeepFreshToolResult,
|
|
316
|
-
shouldOffloadToolResult,
|
|
317
|
-
};
|