@leavewhite9088/harness-bus 0.2.0 → 0.2.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.
Files changed (104) hide show
  1. package/ARCHITECTURE.md +81 -81
  2. package/LICENSE +21 -21
  3. package/README.md +86 -86
  4. package/SETUP_FOR_AI.md +79 -79
  5. package/package.json +4 -2
  6. package/packages/agentd/agentd.config.json +3 -1
  7. package/packages/agentd/cli/commands.mjs +854 -810
  8. package/packages/agentd/cli/format.mjs +294 -238
  9. package/packages/agentd/cli/hbus.mjs +14 -14
  10. package/packages/agentd/cli/index.mjs +4 -4
  11. package/packages/agentd/cli/skill/SKILL.md +66 -61
  12. package/packages/agentd/cli/skill/references/custom.md +12 -0
  13. package/packages/agentd/cli/skill/references/playbooks.md +89 -86
  14. package/packages/agentd/cli/skill/references/routing.md +43 -35
  15. package/packages/agentd/cli/skill-install.mjs +157 -140
  16. package/packages/agentd/cli/update.mjs +221 -221
  17. package/packages/agentd/client/index.mjs +3 -3
  18. package/packages/agentd/contexts/executor.md +13 -12
  19. package/packages/agentd/contexts/templates/architect.md +12 -12
  20. package/packages/agentd/contexts/templates/coder.md +12 -12
  21. package/packages/agentd/contexts/templates/debugger.md +12 -12
  22. package/packages/agentd/contexts/templates/researcher.md +12 -12
  23. package/packages/agentd/contexts/templates/reviewer.md +12 -12
  24. package/packages/agentd/contexts/templates/tester.md +12 -12
  25. package/packages/agentd/core/base/data-dir.mjs +39 -39
  26. package/packages/agentd/core/base/index.mjs +5 -5
  27. package/packages/agentd/core/base/protocol.mjs +13 -13
  28. package/packages/agentd/core/env/config.mjs +52 -1
  29. package/packages/agentd/core/env/index.mjs +6 -1
  30. package/packages/agentd/core/env/install.mjs +82 -4
  31. package/packages/agentd/core/pi/index.mjs +1 -1
  32. package/packages/agentd/core/pi/rpc.mjs +206 -206
  33. package/packages/agentd/core/pool/acp/client.mjs +7 -9
  34. package/packages/agentd/core/pool/acp/process.mjs +27 -18
  35. package/packages/agentd/core/pool/acp/run-tracker.mjs +293 -293
  36. package/packages/agentd/core/pool/acp/sessions.mjs +465 -465
  37. package/packages/agentd/core/pool/acp/turn-runner.mjs +5 -3
  38. package/packages/agentd/core/pool/index.mjs +2 -2
  39. package/packages/agentd/core/pool/instances.mjs +3 -5
  40. package/packages/agentd/core/pool/probe.mjs +91 -85
  41. package/packages/agentd/core/pool/registry.mjs +45 -1
  42. package/packages/agentd/core/pool/support/compaction.mjs +2 -43
  43. package/packages/agentd/core/pool/support/index.mjs +1 -1
  44. package/packages/agentd/core/prompts/index.mjs +12 -12
  45. package/packages/agentd/core/prompts/rules.mjs +22 -22
  46. package/packages/agentd/core/prompts/templates.mjs +172 -172
  47. package/packages/agentd/core/providers/index.mjs +14 -14
  48. package/packages/agentd/core/providers/store.mjs +206 -206
  49. package/packages/agentd/core/records/cleanup.mjs +51 -51
  50. package/packages/agentd/core/records/index.mjs +8 -8
  51. package/packages/agentd/core/records/metrics.mjs +73 -73
  52. package/packages/agentd/core/records/recovery.mjs +39 -39
  53. package/packages/agentd/core/records/transcripts.mjs +122 -122
  54. package/packages/agentd/core/threads/index.mjs +18 -17
  55. package/packages/agentd/core/threads/manager.mjs +498 -476
  56. package/packages/agentd/core/threads/paths.mjs +78 -78
  57. package/packages/agentd/core/threads/store.mjs +146 -125
  58. package/packages/agentd/daemon/agentd.mjs +58 -58
  59. package/packages/agentd/daemon/events.mjs +126 -126
  60. package/packages/agentd/daemon/guard.mjs +127 -127
  61. package/packages/agentd/daemon/lifecycle.mjs +61 -61
  62. package/packages/agentd/daemon/ops/index.mjs +15 -15
  63. package/packages/agentd/daemon/ops/providers.mjs +46 -46
  64. package/packages/agentd/daemon/ops/run.mjs +413 -400
  65. package/packages/agentd/daemon/ops/system.mjs +76 -69
  66. package/packages/agentd/daemon/ops/threads.mjs +156 -153
  67. package/packages/agentd/daemon/server.mjs +130 -130
  68. package/packages/agentd/package.json +1 -1
  69. package/packages/agentd/pi-adapter/acp-adapter.mjs +501 -501
  70. package/packages/agentd/scripts/restart-daemon.mjs +74 -74
  71. package/packages/agentd/scripts/run-isolated.mjs +42 -42
  72. package/packages/agentd/scripts/run-unit.mjs +28 -28
  73. package/packages/backend/src/daemon.mjs +69 -69
  74. package/packages/backend/src/server.mjs +270 -270
  75. package/packages/drivers/{agy.mjs → agy/index.mjs} +2 -1
  76. package/packages/drivers/{claude.mjs → claude/index.mjs} +23 -1
  77. package/packages/drivers/{codex.mjs → codex/index.mjs} +2 -1
  78. package/packages/drivers/{dsh.mjs → dsh/index.mjs} +3 -2
  79. package/packages/drivers/grok/index.mjs +96 -0
  80. package/packages/drivers/index.mjs +25 -12
  81. package/packages/drivers/{kimi.mjs → kimi/index.mjs} +2 -1
  82. package/packages/drivers/{mcode.mjs → mcode/index.mjs} +2 -1
  83. package/packages/drivers/{opencode.mjs → opencode/index.mjs} +2 -1
  84. package/packages/drivers/{pi.mjs → pi/index.mjs} +3 -2
  85. package/packages/drivers/probes/acp.mjs +109 -109
  86. package/packages/drivers/probes/index.mjs +131 -129
  87. package/packages/drivers/probes/provider.mjs +222 -222
  88. package/packages/drivers/qoder/index.mjs +32 -0
  89. package/packages/drivers/{bin.mjs → shared/bin.mjs} +2 -0
  90. package/packages/drivers/shared/index.mjs +2 -0
  91. package/packages/preflight/bin/preflight.mjs +116 -116
  92. package/packages/preflight/src/index.mjs +5 -5
  93. package/packages/preflight/src/report.mjs +18 -1
  94. package/packages/web/dist/apple-touch-icon.png +0 -0
  95. package/packages/web/dist/assets/index-CT8dIwav.css +2 -0
  96. package/packages/web/dist/assets/index-CypTUMFB.js +79 -0
  97. package/packages/web/dist/favicon-32.png +0 -0
  98. package/packages/web/dist/favicon.svg +19 -15
  99. package/packages/web/dist/index.html +5 -5
  100. package/packages/web/dist/assets/index-B2kdkHNw.js +0 -79
  101. package/packages/web/dist/assets/index-DQTyjC4x.css +0 -2
  102. /package/packages/drivers/{dsh-sessions.mjs → dsh/sessions.mjs} +0 -0
  103. /package/packages/drivers/{pi-catalog.mjs → pi/catalog.mjs} +0 -0
  104. /package/packages/drivers/{lib.mjs → shared/lib.mjs} +0 -0
@@ -1,293 +1,293 @@
1
- import { appendLog } from './log-writer.mjs';
2
- import { TOOL_CALL_AS_TEXT } from '../../base/index.mjs';
3
- import { appendEntry } from '../../records/index.mjs';
4
- import { entry, inputText, noteSession, outputText, saved } from '../support/index.mjs';
5
-
6
- const finished = (status) =>
7
- status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'canceled' || status === 'error' || status === 'done';
8
-
9
- export class RunTracker {
10
- constructor({ name, getRun, getContextSize = null, isCompacting = null, onAutoCompact = null }) {
11
- this.name = name;
12
- this.getRun = getRun;
13
- this.getContextSize = getContextSize;
14
- this.isCompacting = isCompacting;
15
- this.onAutoCompact = onAutoCompact;
16
- this.sink = null;
17
- this.lastSignal = Date.now();
18
- this.openTools = new Set();
19
- this.lastProgressAt = 0;
20
- this.streamedText = '';
21
- this.lastKind = null;
22
- this.textMark = 0;
23
- this.lastUsage = null;
24
- }
25
-
26
- begin() {
27
- this.lastSignal = Date.now();
28
- this.openTools.clear();
29
- }
30
-
31
- quiet() {
32
- return { forMs: Date.now() - this.lastSignal, waitingOnTool: this.openTools.size > 0 };
33
- }
34
-
35
- openToolText() {
36
- const run = this.getRun();
37
- return [...this.openTools]
38
- .map((id) => {
39
- const t = run?.tools?.get(id);
40
- return String(t?.input || t?.title || id).replace(/\s+/g, ' ').slice(0, 160);
41
- })
42
- .join('; ');
43
- }
44
-
45
- onPermission({ toolCallId = null, optionId = null, outcome = 'selected' } = {}) {
46
- this.lastSignal = Date.now();
47
- const run = this.getRun();
48
- if (!run) return;
49
- run.lastSignalAt = this.lastSignal;
50
- run.permissionsGranted = (run.permissionsGranted ?? 0) + (outcome === 'selected' ? 1 : 0);
51
- if (toolCallId) {
52
- const rec = run.tools?.get(toolCallId);
53
- if (rec) {
54
- rec.permission = optionId ?? outcome;
55
- rec.approvedAt = this.lastSignal;
56
- }
57
- }
58
- }
59
-
60
- unfinished() {
61
- if (this.lastKind === 'text') return TOOL_CALL_AS_TEXT.test(this.streamedText.slice(Math.max(this.textMark, this.streamedText.length - 600))) ? 'tool_as_text' : null;
62
- return 'no_final';
63
- }
64
-
65
- onUpdate(u, sessionId = null) {
66
- this._noteSignal(u);
67
- if (u.sessionUpdate === 'agent_message_chunk' && u.content?.text) this.lastKind = 'text';
68
- else if (u.sessionUpdate === 'agent_thought_chunk' && u.content?.text) this.lastKind = 'thought';
69
- else if (u.sessionUpdate === 'tool_call' || u.sessionUpdate === 'tool_call_update') this.lastKind = 'tool';
70
- const run = this.getRun();
71
- if (run) {
72
- run.lastSignalAt = this.lastSignal;
73
- run.lastKind = this.lastKind;
74
- run.openToolCount = this.openTools.size;
75
- }
76
- const isTool = u.sessionUpdate === 'tool_call' || u.sessionUpdate === 'tool_call_update';
77
- if (run && isTool) {
78
- const done = finished(u.status);
79
- const shortIn = inputText(u.rawInput);
80
- const clippedIn = shortIn ? String(shortIn).replace(/\s+/g, ' ').trim().slice(0, 160) : null;
81
- if (u.toolCallId) {
82
- let rec = run.tools.get(u.toolCallId);
83
- if (!rec) {
84
- rec = { id: u.toolCallId, title: u.title ?? u.kind ?? null, kind: u.kind ?? null, status: u.status ?? 'in_progress', input: clippedIn, startedAt: Date.now(), endedAt: null };
85
- run.tools.set(u.toolCallId, rec);
86
- run.toolTrace ??= [];
87
- run.toolTrace.push(rec);
88
- if (run.toolTrace.length > 40) run.toolTrace.shift();
89
- } else {
90
- if (u.title && !done && !u.title.endsWith('…')) rec.title = u.title;
91
- else if (!rec.title && u.title) rec.title = u.title;
92
- if (u.kind && !rec.kind) rec.kind = u.kind;
93
- if (clippedIn && !rec.input) rec.input = clippedIn;
94
- if (u.status) rec.status = u.status;
95
- if (done && !rec.endedAt) rec.endedAt = Date.now();
96
- }
97
- if (rec.input) run.lastToolInput = rec.input;
98
- } else if (u.sessionUpdate === 'tool_call') {
99
- run.anonToolCalls = (run.anonToolCalls ?? 0) + 1;
100
- const rec = { id: `anon-${run.anonToolCalls}`, title: u.title ?? u.kind ?? null, kind: u.kind ?? null, status: u.status ?? 'started', input: clippedIn, startedAt: Date.now(), endedAt: done ? Date.now() : null };
101
- run.toolTrace ??= [];
102
- run.toolTrace.push(rec);
103
- if (run.toolTrace.length > 40) run.toolTrace.shift();
104
- if (clippedIn) run.lastToolInput = clippedIn;
105
- }
106
- run.toolCalls = run.tools.size + (run.anonToolCalls ?? 0);
107
- if (u.sessionUpdate === 'tool_call' || (!run.lastTool && (u.title || u.kind))) {
108
- run.lastTool = u.title ?? u.kind ?? null;
109
- }
110
- this.progress(run, u.sessionUpdate === 'tool_call');
111
- }
112
-
113
- if (u.sessionUpdate === 'agent_message_chunk' && u.content?.text) {
114
- this.streamedText += u.content.text;
115
- this._text(u.content.text);
116
- return;
117
- }
118
- if (u.sessionUpdate === 'agent_thought_chunk' && u.content?.text) {
119
- this._thought(u.content.text);
120
- return;
121
- }
122
- if (u.sessionUpdate === 'usage_update') {
123
- const sid = sessionId ?? run?.sessionId ?? null;
124
- const configuredSize = this.getContextSize?.() ?? null;
125
- const prev =
126
- (sid && this.lastUsage?.sessionId === sid ? this.lastUsage : null) ??
127
- (sid ? saved(this.name, sid)?.context : null) ??
128
- (!sid ? run?.context : null);
129
- if (run) {
130
- if (u.cost) run.cost = u.cost;
131
- if (u.tokens) run.tokens = u.tokens;
132
- }
133
- const rawUsed = u.used != null ? Number(u.used) : null;
134
- const hasPositiveUsed = Number.isFinite(rawUsed) && rawUsed > 0;
135
- if (!hasPositiveUsed) {
136
- if (prev?.used > 0) {
137
- const size = configuredSize ?? u.size ?? prev.size ?? null;
138
- const ctx = {
139
- used: prev.used,
140
- size,
141
- percent: size ? +((prev.used / size) * 100).toFixed(1) : prev.percent ?? null,
142
- };
143
- if (run) run.context = ctx;
144
- this.lastUsage = { ...ctx, cost: u.cost ?? this.lastUsage?.cost ?? null, tokens: u.tokens ?? this.lastUsage?.tokens ?? null, sessionId: sid };
145
- }
146
- return;
147
- }
148
- const size = configuredSize ?? u.size ?? prev?.size ?? null;
149
- const ctx = {
150
- used: rawUsed,
151
- size,
152
- percent: size ? +((rawUsed / size) * 100).toFixed(1) : null,
153
- };
154
- if (
155
- sid &&
156
- !this.isCompacting?.() &&
157
- prev?.used >= 40_000 &&
158
- rawUsed <= prev.used * 0.65 &&
159
- prev.used - rawUsed >= 25_000
160
- ) {
161
- const e = entry(this.name, sid);
162
- if (!(e.compactedAt && Date.now() - e.compactedAt < 10_000)) {
163
- const compactions = (e.compactions ?? 0) + 1;
164
- noteSession(this.name, sid, { compactions, compactedAt: Date.now(), lastCompactUsed: prev.used });
165
- this.onAutoCompact?.({ agent: this.name, sessionId: sid, before: prev, after: ctx, threshold: null, compactions });
166
- }
167
- }
168
- if (run) run.context = ctx;
169
- this.lastUsage = { ...ctx, cost: u.cost ?? null, tokens: u.tokens ?? null, sessionId: sid };
170
- // Kept at once, not only when a run ends: a run that never ends well (stopped, failed) would leave an idle executor with no figure.
171
- if (sid && ctx.percent != null) noteSession(this.name, sid, { context: ctx });
172
- return;
173
- }
174
- if (run?.sessionId && isTool) this._tool(run, u);
175
- }
176
-
177
- _noteSignal(u) {
178
- this.lastSignal = Date.now();
179
- const id = u.toolCallId ?? null;
180
- if (u.sessionUpdate === 'tool_call' && id && !finished(u.status)) this.openTools.add(id);
181
- else if (u.sessionUpdate === 'tool_call_update' && id) {
182
- if (finished(u.status)) this.openTools.delete(id);
183
- else if (u.status === 'in_progress' || u.status === 'pending') this.openTools.add(id);
184
- }
185
- }
186
-
187
- _tool(run, u) {
188
- const done = finished(u.status);
189
- let tool = null;
190
- if (u.toolCallId) {
191
- tool = run.tools.get(u.toolCallId) ?? {};
192
- if (u.title && !done && !u.title.endsWith('…')) tool.title = u.title;
193
- else if (!tool.title && u.title && u.sessionUpdate === 'tool_call') tool.title = u.title;
194
- const input = inputText(u.rawInput);
195
- if (input) tool.input = input;
196
- run.tools.set(u.toolCallId, tool);
197
- }
198
- if (u.sessionUpdate === 'tool_call') {
199
- this.flushPieces(run);
200
- appendEntry(this.name, run.sessionId, {
201
- role: 'tool',
202
- jobId: run.jobId,
203
- toolCallId: u.toolCallId ?? null,
204
- title: tool?.title ?? u.title ?? null,
205
- kind: u.kind ?? null,
206
- status: u.status ?? 'started',
207
- input: tool?.input ?? null,
208
- });
209
- } else if (done) {
210
- appendEntry(this.name, run.sessionId, {
211
- role: 'tool',
212
- jobId: run.jobId,
213
- toolCallId: u.toolCallId ?? null,
214
- title: tool?.title ?? null,
215
- kind: u.kind ?? null,
216
- status: u.status,
217
- input: tool?.input ?? null,
218
- output: outputText(u),
219
- });
220
- }
221
- }
222
-
223
- _text(text) {
224
- const run = this.getRun();
225
- if (!run) return;
226
- if (run.firstChunkAt == null) run.firstChunkAt = Date.now();
227
- if (run.segAt == null) run.segAt = Date.now();
228
- run.text += text;
229
- run.chunks += 1;
230
- if (run.logFile) appendLog(run.logFile, text);
231
- this.progress(run);
232
- }
233
-
234
- _thought(text) {
235
- const run = this.getRun();
236
- if (!run) return;
237
- if (run.firstChunkAt == null) run.firstChunkAt = Date.now();
238
- if (run.thoughtAt == null) run.thoughtAt = Date.now();
239
- run.thoughtChars += text.length;
240
- if (run.thought.length < 20_000) run.thought += text;
241
- this.progress(run);
242
- }
243
-
244
- progress(run, force = false) {
245
- const now = Date.now();
246
- if (!this.sink || (!force && now - this.lastProgressAt < 500)) return;
247
- this.lastProgressAt = now;
248
- this.sink(run.jobId, {
249
- agent: this.name,
250
- chars: run.text.length,
251
- thinkingChars: run.thoughtChars,
252
- elapsedMs: now - run.startedAt,
253
- tool: run.lastTool ?? null,
254
- toolCalls: run.toolCalls ?? 0,
255
- openTools: this.openTools.size,
256
- });
257
- }
258
-
259
- flushPieces(run, extra = {}) {
260
- if (!run?.sessionId) return;
261
- const iso = (ms) => (ms ? new Date(ms).toISOString() : undefined);
262
- const thought = run.thought.slice(run.flushedThought).trim();
263
- if (thought) {
264
- appendEntry(this.name, run.sessionId, { role: 'thought', jobId: run.jobId, text: thought.slice(0, 12_000), chars: thought.length, startedAt: iso(run.thoughtAt) });
265
- }
266
- run.flushedThought = run.thought.length;
267
- run.thoughtAt = null;
268
- const text = run.text.slice(run.flushed).trim();
269
- if (text) {
270
- appendEntry(this.name, run.sessionId, { role: 'assistant', jobId: run.jobId, piece: true, text, startedAt: iso(run.segAt), ...extra });
271
- }
272
- run.flushed = run.text.length;
273
- run.segAt = null;
274
- }
275
-
276
- closeOpenTools(run, detail = null) {
277
- if (!run?.sessionId || !this.openTools.size) return;
278
- for (const toolCallId of [...this.openTools]) {
279
- const tool = run.tools?.get(toolCallId);
280
- appendEntry(this.name, run.sessionId, {
281
- role: 'tool',
282
- jobId: run.jobId,
283
- toolCallId,
284
- title: tool?.title ?? null,
285
- kind: null,
286
- status: 'failed',
287
- input: tool?.input ?? null,
288
- output: detail ? `中断:${String(detail).slice(0, 240)}` : '中断',
289
- });
290
- }
291
- this.openTools.clear();
292
- }
293
- }
1
+ import { appendLog } from './log-writer.mjs';
2
+ import { TOOL_CALL_AS_TEXT } from '../../base/index.mjs';
3
+ import { appendEntry } from '../../records/index.mjs';
4
+ import { entry, inputText, noteSession, outputText, saved } from '../support/index.mjs';
5
+
6
+ const finished = (status) =>
7
+ status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'canceled' || status === 'error' || status === 'done';
8
+
9
+ export class RunTracker {
10
+ constructor({ name, getRun, getContextSize = null, isCompacting = null, onAutoCompact = null }) {
11
+ this.name = name;
12
+ this.getRun = getRun;
13
+ this.getContextSize = getContextSize;
14
+ this.isCompacting = isCompacting;
15
+ this.onAutoCompact = onAutoCompact;
16
+ this.sink = null;
17
+ this.lastSignal = Date.now();
18
+ this.openTools = new Set();
19
+ this.lastProgressAt = 0;
20
+ this.streamedText = '';
21
+ this.lastKind = null;
22
+ this.textMark = 0;
23
+ this.lastUsage = null;
24
+ }
25
+
26
+ begin() {
27
+ this.lastSignal = Date.now();
28
+ this.openTools.clear();
29
+ }
30
+
31
+ quiet() {
32
+ return { forMs: Date.now() - this.lastSignal, waitingOnTool: this.openTools.size > 0 };
33
+ }
34
+
35
+ openToolText() {
36
+ const run = this.getRun();
37
+ return [...this.openTools]
38
+ .map((id) => {
39
+ const t = run?.tools?.get(id);
40
+ return String(t?.input || t?.title || id).replace(/\s+/g, ' ').slice(0, 160);
41
+ })
42
+ .join('; ');
43
+ }
44
+
45
+ onPermission({ toolCallId = null, optionId = null, outcome = 'selected' } = {}) {
46
+ this.lastSignal = Date.now();
47
+ const run = this.getRun();
48
+ if (!run) return;
49
+ run.lastSignalAt = this.lastSignal;
50
+ run.permissionsGranted = (run.permissionsGranted ?? 0) + (outcome === 'selected' ? 1 : 0);
51
+ if (toolCallId) {
52
+ const rec = run.tools?.get(toolCallId);
53
+ if (rec) {
54
+ rec.permission = optionId ?? outcome;
55
+ rec.approvedAt = this.lastSignal;
56
+ }
57
+ }
58
+ }
59
+
60
+ unfinished() {
61
+ if (this.lastKind === 'text') return TOOL_CALL_AS_TEXT.test(this.streamedText.slice(Math.max(this.textMark, this.streamedText.length - 600))) ? 'tool_as_text' : null;
62
+ return 'no_final';
63
+ }
64
+
65
+ onUpdate(u, sessionId = null) {
66
+ this._noteSignal(u);
67
+ if (u.sessionUpdate === 'agent_message_chunk' && u.content?.text) this.lastKind = 'text';
68
+ else if (u.sessionUpdate === 'agent_thought_chunk' && u.content?.text) this.lastKind = 'thought';
69
+ else if (u.sessionUpdate === 'tool_call' || u.sessionUpdate === 'tool_call_update') this.lastKind = 'tool';
70
+ const run = this.getRun();
71
+ if (run) {
72
+ run.lastSignalAt = this.lastSignal;
73
+ run.lastKind = this.lastKind;
74
+ run.openToolCount = this.openTools.size;
75
+ }
76
+ const isTool = u.sessionUpdate === 'tool_call' || u.sessionUpdate === 'tool_call_update';
77
+ if (run && isTool) {
78
+ const done = finished(u.status);
79
+ const shortIn = inputText(u.rawInput);
80
+ const clippedIn = shortIn ? String(shortIn).replace(/\s+/g, ' ').trim().slice(0, 160) : null;
81
+ if (u.toolCallId) {
82
+ let rec = run.tools.get(u.toolCallId);
83
+ if (!rec) {
84
+ rec = { id: u.toolCallId, title: u.title ?? u.kind ?? null, kind: u.kind ?? null, status: u.status ?? 'in_progress', input: clippedIn, startedAt: Date.now(), endedAt: null };
85
+ run.tools.set(u.toolCallId, rec);
86
+ run.toolTrace ??= [];
87
+ run.toolTrace.push(rec);
88
+ if (run.toolTrace.length > 40) run.toolTrace.shift();
89
+ } else {
90
+ if (u.title && !done && !u.title.endsWith('…')) rec.title = u.title;
91
+ else if (!rec.title && u.title) rec.title = u.title;
92
+ if (u.kind && !rec.kind) rec.kind = u.kind;
93
+ if (clippedIn && !rec.input) rec.input = clippedIn;
94
+ if (u.status) rec.status = u.status;
95
+ if (done && !rec.endedAt) rec.endedAt = Date.now();
96
+ }
97
+ if (rec.input) run.lastToolInput = rec.input;
98
+ } else if (u.sessionUpdate === 'tool_call') {
99
+ run.anonToolCalls = (run.anonToolCalls ?? 0) + 1;
100
+ const rec = { id: `anon-${run.anonToolCalls}`, title: u.title ?? u.kind ?? null, kind: u.kind ?? null, status: u.status ?? 'started', input: clippedIn, startedAt: Date.now(), endedAt: done ? Date.now() : null };
101
+ run.toolTrace ??= [];
102
+ run.toolTrace.push(rec);
103
+ if (run.toolTrace.length > 40) run.toolTrace.shift();
104
+ if (clippedIn) run.lastToolInput = clippedIn;
105
+ }
106
+ run.toolCalls = run.tools.size + (run.anonToolCalls ?? 0);
107
+ if (u.sessionUpdate === 'tool_call' || (!run.lastTool && (u.title || u.kind))) {
108
+ run.lastTool = u.title ?? u.kind ?? null;
109
+ }
110
+ this.progress(run, u.sessionUpdate === 'tool_call');
111
+ }
112
+
113
+ if (u.sessionUpdate === 'agent_message_chunk' && u.content?.text) {
114
+ this.streamedText += u.content.text;
115
+ this._text(u.content.text);
116
+ return;
117
+ }
118
+ if (u.sessionUpdate === 'agent_thought_chunk' && u.content?.text) {
119
+ this._thought(u.content.text);
120
+ return;
121
+ }
122
+ if (u.sessionUpdate === 'usage_update') {
123
+ const sid = sessionId ?? run?.sessionId ?? null;
124
+ const configuredSize = this.getContextSize?.() ?? null;
125
+ const prev =
126
+ (sid && this.lastUsage?.sessionId === sid ? this.lastUsage : null) ??
127
+ (sid ? saved(this.name, sid)?.context : null) ??
128
+ (!sid ? run?.context : null);
129
+ if (run) {
130
+ if (u.cost) run.cost = u.cost;
131
+ if (u.tokens) run.tokens = u.tokens;
132
+ }
133
+ const rawUsed = u.used != null ? Number(u.used) : null;
134
+ const hasPositiveUsed = Number.isFinite(rawUsed) && rawUsed > 0;
135
+ if (!hasPositiveUsed) {
136
+ if (prev?.used > 0) {
137
+ const size = configuredSize ?? u.size ?? prev.size ?? null;
138
+ const ctx = {
139
+ used: prev.used,
140
+ size,
141
+ percent: size ? +((prev.used / size) * 100).toFixed(1) : prev.percent ?? null,
142
+ };
143
+ if (run) run.context = ctx;
144
+ this.lastUsage = { ...ctx, cost: u.cost ?? this.lastUsage?.cost ?? null, tokens: u.tokens ?? this.lastUsage?.tokens ?? null, sessionId: sid };
145
+ }
146
+ return;
147
+ }
148
+ const size = configuredSize ?? u.size ?? prev?.size ?? null;
149
+ const ctx = {
150
+ used: rawUsed,
151
+ size,
152
+ percent: size ? +((rawUsed / size) * 100).toFixed(1) : null,
153
+ };
154
+ if (
155
+ sid &&
156
+ !this.isCompacting?.() &&
157
+ prev?.used >= 40_000 &&
158
+ rawUsed <= prev.used * 0.65 &&
159
+ prev.used - rawUsed >= 25_000
160
+ ) {
161
+ const e = entry(this.name, sid);
162
+ if (!(e.compactedAt && Date.now() - e.compactedAt < 10_000)) {
163
+ const compactions = (e.compactions ?? 0) + 1;
164
+ noteSession(this.name, sid, { compactions, compactedAt: Date.now(), lastCompactUsed: prev.used });
165
+ this.onAutoCompact?.({ agent: this.name, sessionId: sid, before: prev, after: ctx, threshold: null, compactions });
166
+ }
167
+ }
168
+ if (run) run.context = ctx;
169
+ this.lastUsage = { ...ctx, cost: u.cost ?? null, tokens: u.tokens ?? null, sessionId: sid };
170
+ // Kept at once, not only when a run ends: a run that never ends well (stopped, failed) would leave an idle executor with no figure.
171
+ if (sid && ctx.percent != null) noteSession(this.name, sid, { context: ctx });
172
+ return;
173
+ }
174
+ if (run?.sessionId && isTool) this._tool(run, u);
175
+ }
176
+
177
+ _noteSignal(u) {
178
+ this.lastSignal = Date.now();
179
+ const id = u.toolCallId ?? null;
180
+ if (u.sessionUpdate === 'tool_call' && id && !finished(u.status)) this.openTools.add(id);
181
+ else if (u.sessionUpdate === 'tool_call_update' && id) {
182
+ if (finished(u.status)) this.openTools.delete(id);
183
+ else if (u.status === 'in_progress' || u.status === 'pending') this.openTools.add(id);
184
+ }
185
+ }
186
+
187
+ _tool(run, u) {
188
+ const done = finished(u.status);
189
+ let tool = null;
190
+ if (u.toolCallId) {
191
+ tool = run.tools.get(u.toolCallId) ?? {};
192
+ if (u.title && !done && !u.title.endsWith('…')) tool.title = u.title;
193
+ else if (!tool.title && u.title && u.sessionUpdate === 'tool_call') tool.title = u.title;
194
+ const input = inputText(u.rawInput);
195
+ if (input) tool.input = input;
196
+ run.tools.set(u.toolCallId, tool);
197
+ }
198
+ if (u.sessionUpdate === 'tool_call') {
199
+ this.flushPieces(run);
200
+ appendEntry(this.name, run.sessionId, {
201
+ role: 'tool',
202
+ jobId: run.jobId,
203
+ toolCallId: u.toolCallId ?? null,
204
+ title: tool?.title ?? u.title ?? null,
205
+ kind: u.kind ?? null,
206
+ status: u.status ?? 'started',
207
+ input: tool?.input ?? null,
208
+ });
209
+ } else if (done) {
210
+ appendEntry(this.name, run.sessionId, {
211
+ role: 'tool',
212
+ jobId: run.jobId,
213
+ toolCallId: u.toolCallId ?? null,
214
+ title: tool?.title ?? null,
215
+ kind: u.kind ?? null,
216
+ status: u.status,
217
+ input: tool?.input ?? null,
218
+ output: outputText(u),
219
+ });
220
+ }
221
+ }
222
+
223
+ _text(text) {
224
+ const run = this.getRun();
225
+ if (!run) return;
226
+ if (run.firstChunkAt == null) run.firstChunkAt = Date.now();
227
+ if (run.segAt == null) run.segAt = Date.now();
228
+ run.text += text;
229
+ run.chunks += 1;
230
+ if (run.logFile) appendLog(run.logFile, text);
231
+ this.progress(run);
232
+ }
233
+
234
+ _thought(text) {
235
+ const run = this.getRun();
236
+ if (!run) return;
237
+ if (run.firstChunkAt == null) run.firstChunkAt = Date.now();
238
+ if (run.thoughtAt == null) run.thoughtAt = Date.now();
239
+ run.thoughtChars += text.length;
240
+ if (run.thought.length < 20_000) run.thought += text;
241
+ this.progress(run);
242
+ }
243
+
244
+ progress(run, force = false) {
245
+ const now = Date.now();
246
+ if (!this.sink || (!force && now - this.lastProgressAt < 500)) return;
247
+ this.lastProgressAt = now;
248
+ this.sink(run.jobId, {
249
+ agent: this.name,
250
+ chars: run.text.length,
251
+ thinkingChars: run.thoughtChars,
252
+ elapsedMs: now - run.startedAt,
253
+ tool: run.lastTool ?? null,
254
+ toolCalls: run.toolCalls ?? 0,
255
+ openTools: this.openTools.size,
256
+ });
257
+ }
258
+
259
+ flushPieces(run, extra = {}) {
260
+ if (!run?.sessionId) return;
261
+ const iso = (ms) => (ms ? new Date(ms).toISOString() : undefined);
262
+ const thought = run.thought.slice(run.flushedThought).trim();
263
+ if (thought) {
264
+ appendEntry(this.name, run.sessionId, { role: 'thought', jobId: run.jobId, text: thought.slice(0, 12_000), chars: thought.length, startedAt: iso(run.thoughtAt) });
265
+ }
266
+ run.flushedThought = run.thought.length;
267
+ run.thoughtAt = null;
268
+ const text = run.text.slice(run.flushed).trim();
269
+ if (text) {
270
+ appendEntry(this.name, run.sessionId, { role: 'assistant', jobId: run.jobId, piece: true, text, startedAt: iso(run.segAt), ...extra });
271
+ }
272
+ run.flushed = run.text.length;
273
+ run.segAt = null;
274
+ }
275
+
276
+ closeOpenTools(run, detail = null) {
277
+ if (!run?.sessionId || !this.openTools.size) return;
278
+ for (const toolCallId of [...this.openTools]) {
279
+ const tool = run.tools?.get(toolCallId);
280
+ appendEntry(this.name, run.sessionId, {
281
+ role: 'tool',
282
+ jobId: run.jobId,
283
+ toolCallId,
284
+ title: tool?.title ?? null,
285
+ kind: null,
286
+ status: 'failed',
287
+ input: tool?.input ?? null,
288
+ output: detail ? `中断:${String(detail).slice(0, 240)}` : '中断',
289
+ });
290
+ }
291
+ this.openTools.clear();
292
+ }
293
+ }