teapot-coding-agent 0.37.6 → 0.37.8
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/agent.js +135 -203
- package/dist/agent/mcp-registry.js +1 -3
- package/dist/agent/tools.js +37 -40
- package/dist/master.js +55 -57
- package/dist/server/api.js +22 -26
- package/package.json +1 -1
- package/public/assets/index-B2q72L0W.css +1 -0
- package/public/assets/{index-DMSFR8IL.js → index-DyJ5ZeJH.js} +22 -22
- package/public/assets/index-DyJ5ZeJH.js.map +1 -0
- package/public/assets/{shiki-CwocaPzU.js → shiki-Dlf8liJb.js} +2 -2
- package/public/assets/{shiki-CwocaPzU.js.map → shiki-Dlf8liJb.js.map} +1 -1
- package/public/index.html +2 -2
- package/public/assets/index-DMSFR8IL.js.map +0 -1
- package/public/assets/index-UPEwVQvq.css +0 -1
package/dist/agent/agent.js
CHANGED
|
@@ -24,17 +24,17 @@ import { bus } from "../bus.js";
|
|
|
24
24
|
*
|
|
25
25
|
* Both were fixed for a reason invisible in the prose:
|
|
26
26
|
*
|
|
27
|
-
* - AUTO_CONTINUE_NUDGE
|
|
27
|
+
* - AUTO_CONTINUE_NUDGE used to say only "continue working". The model
|
|
28
28
|
* was never told HOW TO STOP, so it worked forever: it replied in prose, the
|
|
29
29
|
* loop saw an active goal and no finish(), and nudged again. The sub-agent
|
|
30
30
|
* variant already named finish() — the ROOT one did not.
|
|
31
|
-
* - PROGRESS_REQUEST
|
|
31
|
+
* - PROGRESS_REQUEST used to DESCRIBE the report instead of asking for
|
|
32
32
|
* the tool, so the model answered in prose, then — not knowing that had
|
|
33
33
|
* satisfied the request — sent a voluntary report_progress right after, and
|
|
34
34
|
* every requested report appeared TWICE on the timeline.
|
|
35
35
|
*/
|
|
36
36
|
export const AUTO_CONTINUE_NUDGE =
|
|
37
|
-
//
|
|
37
|
+
// the prefix marks this as harness text, not something the operator typed.
|
|
38
38
|
// Unprefixed, the model read it as a request to reply — and prose ends the round
|
|
39
39
|
// without finishing, which starts the next one.
|
|
40
40
|
"[harness] " +
|
|
@@ -46,10 +46,10 @@ export const AUTO_CONTINUE_NUDGE =
|
|
|
46
46
|
/**
|
|
47
47
|
* The auto-continue nudge with the CURRENT GOAL restated.
|
|
48
48
|
*
|
|
49
|
-
*
|
|
49
|
+
* the nudge said "the current goal" and never said what it was. The sub-agent
|
|
50
50
|
* variant has always included its task text for exactly this reason — a forked
|
|
51
51
|
* child otherwise drifts back into the inherited conversation and keeps going
|
|
52
|
-
* forever
|
|
52
|
+
* forever — but the ROOT nudge had no such reminder, so a root agent that
|
|
53
53
|
* had lost the thread had nothing to re-anchor on and simply continued until the
|
|
54
54
|
* `maxConsecutiveIdleRounds` valve tripped.
|
|
55
55
|
*
|
|
@@ -70,7 +70,7 @@ export const PROGRESS_REQUEST =
|
|
|
70
70
|
"what you recently tried, any problems, and your next step. Keep it under 10 lines. " +
|
|
71
71
|
// ask for the TOOL, not prose — a prose answer left the model unsure whether it
|
|
72
72
|
// had satisfied the request, so it sent a voluntary report_progress right after
|
|
73
|
-
// and every requested report appeared TWICE on the timeline
|
|
73
|
+
// and every requested report appeared TWICE on the timeline
|
|
74
74
|
"Record it with the report_progress TOOL (doing, goalStatus, recent, problems, next) — " +
|
|
75
75
|
"call that tool; do NOT answer in prose, which would just duplicate this request.";
|
|
76
76
|
/**
|
|
@@ -103,10 +103,9 @@ const KEEP_RECENT_TOKENS = 15_000;
|
|
|
103
103
|
*/
|
|
104
104
|
const PRUNE_AT_SHARE = 0.95;
|
|
105
105
|
/**
|
|
106
|
-
* Short-context mode
|
|
106
|
+
* Short-context mode: the same knobs, retuned for a window where the default
|
|
107
107
|
* tail is a large share of everything.
|
|
108
108
|
*
|
|
109
|
-
* Measured reasoning, not a guess: `KEEP_RECENT_TOKENS` is 15k, which is 5.7% of a
|
|
110
109
|
* 262k window (fine) but 47% of a 32k one — so on a small model the verbatim tail
|
|
111
110
|
* alone nearly fills the budget and the first prune does almost nothing useful.
|
|
112
111
|
* The mode therefore (a) prunes at 0.6 of the budget instead of 0.95, (b) keeps a
|
|
@@ -310,7 +309,7 @@ Most session state is not injected into prompts — fetch it with tools instead:
|
|
|
310
309
|
/**
|
|
311
310
|
* A message whose ENTIRE text is parenthesised is an acknowledgement, not work.
|
|
312
311
|
*
|
|
313
|
-
*
|
|
312
|
+
* the first version of this listed three literals — `(tool call)`,
|
|
314
313
|
* `(no content)`, `(no output)` — and caught 2 of the 10 forms actually reaching
|
|
315
314
|
* a parent. Measured across every session log, the rest are harness
|
|
316
315
|
* acknowledgements written by `answerMeta` and the meta-tool handlers:
|
|
@@ -331,7 +330,7 @@ Most session state is not injected into prompts — fetch it with tools instead:
|
|
|
331
330
|
* Harness acknowledgements — meta-lines about the run itself rather than the
|
|
332
331
|
* work ("decision recorded to decisions.md", "progress recorded", …).
|
|
333
332
|
*
|
|
334
|
-
*
|
|
333
|
+
* these are addressed to the OPERATOR, not to whoever reads the next
|
|
335
334
|
* agent's report, and they consumed slots in a six-deep window that the parent
|
|
336
335
|
* reads as its only account of the work.
|
|
337
336
|
*/
|
|
@@ -452,7 +451,7 @@ export class Agent {
|
|
|
452
451
|
* A sub-agent's latest bare text turn, held back until the round ends.
|
|
453
452
|
* Models usually end a sub-agent task with a plain message instead of calling
|
|
454
453
|
* finish(); only finish() forwards a report to the parent, so without this the
|
|
455
|
-
* parent got nothing
|
|
454
|
+
* parent got nothing. Held (not sent immediately) so a mid-task
|
|
456
455
|
* narration never pre-empts a real finish() summary.
|
|
457
456
|
*/
|
|
458
457
|
pendingSubReport = "";
|
|
@@ -467,7 +466,7 @@ export class Agent {
|
|
|
467
466
|
/** consecutive round-fatal API errors (drives the retry backoff) */
|
|
468
467
|
consecutiveApiErrors = 0;
|
|
469
468
|
/**
|
|
470
|
-
* True while the round-level retry backoff is sleeping
|
|
469
|
+
* True while the round-level retry backoff is sleeping.
|
|
471
470
|
*
|
|
472
471
|
* Separate from `status`, which must keep reading "error" so the operator sees WHAT
|
|
473
472
|
* failed while the retry is pending — but an agent waiting to retry is stoppable
|
|
@@ -475,7 +474,7 @@ export class Agent {
|
|
|
475
474
|
*/
|
|
476
475
|
retrySleeping = false;
|
|
477
476
|
/**
|
|
478
|
-
* Consecutive auto-continued rounds that did no work
|
|
477
|
+
* Consecutive auto-continued rounds that did no work.
|
|
479
478
|
*
|
|
480
479
|
* Reset by any tool call, any finish, a stop, or fresh operator input — only a
|
|
481
480
|
* round that produced neither a tool call nor a finish increments it.
|
|
@@ -484,7 +483,6 @@ export class Agent {
|
|
|
484
483
|
/**
|
|
485
484
|
* Consecutive completion audits that REJECTED, #128.
|
|
486
485
|
*
|
|
487
|
-
* Measured before this existed: a model that finishes, is rejected, finishes
|
|
488
486
|
* again, is rejected again… ran 381 audit calls in one turn. Nothing bounded it:
|
|
489
487
|
*
|
|
490
488
|
* - `maxConsecutiveIdleRounds` counts IDLE rounds, and a rejected audit is not
|
|
@@ -499,7 +497,7 @@ export class Agent {
|
|
|
499
497
|
*/
|
|
500
498
|
consecutiveAuditRejects = 0;
|
|
501
499
|
/**
|
|
502
|
-
*
|
|
500
|
+
* consecutive completion audits that produced NO verdict (empty /
|
|
503
501
|
* prose / provider throw). Fail-CLOSED — the goal stays active and the
|
|
504
502
|
* worker self-verifies again — but bounded: after 3 the retrying stops with
|
|
505
503
|
* a loud note (the same philosophy as the reject bound above), so a
|
|
@@ -518,7 +516,7 @@ export class Agent {
|
|
|
518
516
|
auditAttempts = 0;
|
|
519
517
|
lastRejectedAudit = null;
|
|
520
518
|
/**
|
|
521
|
-
* What the agent had done BEFORE an audit rejected its first finish
|
|
519
|
+
* What the agent had done BEFORE an audit rejected its first finish.
|
|
522
520
|
*
|
|
523
521
|
* Captured at rejection time because that is the last moment the pre-rejection work is still
|
|
524
522
|
* the bulk of the history. The eventual approved final would otherwise report only the retry,
|
|
@@ -535,12 +533,12 @@ export class Agent {
|
|
|
535
533
|
autoContinue: true,
|
|
536
534
|
continueDelayMs: 15_000,
|
|
537
535
|
autoCompact: true,
|
|
538
|
-
//
|
|
536
|
+
// no effort and no catalogue entry means "provider default" — the
|
|
539
537
|
// effort field is then never sent, which is the safe default
|
|
540
538
|
reasoningEffort: "",
|
|
541
539
|
// undefined, NOT []: "the endpoint published no capability list" and "the
|
|
542
540
|
// endpoint published a list that excludes this parameter" are different
|
|
543
|
-
// answers, and only the second is a definite no
|
|
541
|
+
// answers, and only the second is a definite no. An empty array here
|
|
544
542
|
// would make every silent endpoint look like an explicit refusal — measured:
|
|
545
543
|
// commandcode and google publish no list at all, so `[]` hid the very control
|
|
546
544
|
// #150 was about.
|
|
@@ -579,7 +577,7 @@ export class Agent {
|
|
|
579
577
|
{ dir: path.join(opts.workspace, "skills"), source: "workspace" },
|
|
580
578
|
...(opts.globalSkillsDir ? [{ dir: opts.globalSkillsDir, source: "global" }] : []),
|
|
581
579
|
...(opts.pluginSkillRoots ?? []),
|
|
582
|
-
// OTHER HARNESSES' skill directories
|
|
580
|
+
// OTHER HARNESSES' skill directories. The SKILL.md format is shared,
|
|
583
581
|
// so these are readable as-is — verified against real third-party skills
|
|
584
582
|
// (terminalskills/skills, trailofbits/skills, …). They sit below the
|
|
585
583
|
// workspace and teapot's own global dir so a project always wins, and
|
|
@@ -601,7 +599,7 @@ export class Agent {
|
|
|
601
599
|
readOnly: this.opts.readOnlyTools,
|
|
602
600
|
onIdlePark: (reason) => this.parkForTool(reason),
|
|
603
601
|
onIdleUnpark: () => this.unparkFromTool(),
|
|
604
|
-
//
|
|
602
|
+
// the park must not strand an already-queued prompt
|
|
605
603
|
hasPendingPrompts: () => this.pendingPrompts.length > 0,
|
|
606
604
|
onBackgroundExit: (info) => void this.onBackgroundJobExit(info),
|
|
607
605
|
onFileRead: (p) => this.trackFileRead(p),
|
|
@@ -637,7 +635,7 @@ export class Agent {
|
|
|
637
635
|
*/
|
|
638
636
|
compactRules = [];
|
|
639
637
|
/**
|
|
640
|
-
* A short human title for this session
|
|
638
|
+
* A short human title for this session, derived from the operator's first
|
|
641
639
|
* prompt. Undefined until the log is read (or when there is no usable prompt).
|
|
642
640
|
*/
|
|
643
641
|
sessionTitle;
|
|
@@ -650,7 +648,7 @@ export class Agent {
|
|
|
650
648
|
*/
|
|
651
649
|
consecutiveCompactFailures = 0;
|
|
652
650
|
/**
|
|
653
|
-
* Rescan skill roots — but only when something actually changed
|
|
651
|
+
* Rescan skill roots — but only when something actually changed.
|
|
654
652
|
* This used to run a readdir per root plus a read of every SKILL.md at the
|
|
655
653
|
* top of EVERY turn; the cache is only ever read by list_skills, so that
|
|
656
654
|
* was pure I/O on the hot path. A cheap stat fingerprint of the roots and
|
|
@@ -659,7 +657,7 @@ export class Agent {
|
|
|
659
657
|
* self-created skill still shows up on the very next turn).
|
|
660
658
|
*/
|
|
661
659
|
/**
|
|
662
|
-
* Render the skill catalogue for the system prompt
|
|
660
|
+
* Render the skill catalogue for the system prompt.
|
|
663
661
|
*
|
|
664
662
|
* Name + description only, one line each — the full SKILL.md is what
|
|
665
663
|
* load_skill() is for, and this block goes into EVERY request of the session,
|
|
@@ -670,7 +668,6 @@ export class Agent {
|
|
|
670
668
|
/**
|
|
671
669
|
* A bounded DIGEST of memory.md: every heading, plus its first line.
|
|
672
670
|
*
|
|
673
|
-
* MEASURED reason this exists. The notes are agent-scoped now (they outlive a session) and
|
|
674
671
|
* they are genuinely long — 2.6KB is the median, and the largest hold full project briefs. A
|
|
675
672
|
* model that never sees them cannot decide to consult them: that is the whole finding of #48
|
|
676
673
|
* (182 writes, 13 reads after a write). A model that sees the WHOLE file pays for it on every
|
|
@@ -760,7 +757,7 @@ export class Agent {
|
|
|
760
757
|
}
|
|
761
758
|
callLlm(messages, tools, onDelta) {
|
|
762
759
|
const fn = this.opts.chatFn ?? chatStream;
|
|
763
|
-
//
|
|
760
|
+
// carry the effort setting + the model's advertised capabilities into
|
|
764
761
|
// the request config. chat() applies effortForRequest(), which sends the
|
|
765
762
|
// field ONLY for OpenRouter endpoints whose catalogue lists support.
|
|
766
763
|
return fn(this.requestConfig({
|
|
@@ -845,34 +842,12 @@ export class Agent {
|
|
|
845
842
|
return this.manualCompactBudget;
|
|
846
843
|
}
|
|
847
844
|
/**
|
|
848
|
-
*
|
|
845
|
+
* The context size the prune/compact gates act on.
|
|
849
846
|
*
|
|
850
|
-
*
|
|
851
|
-
*
|
|
852
|
-
*
|
|
853
|
-
*
|
|
854
|
-
*
|
|
855
|
-
* maybePrune() est < budget * 0.6 -> 0 prunes, forever
|
|
856
|
-
* maybeCompact() before < budget -> 0 compactions, forever
|
|
857
|
-
*
|
|
858
|
-
* Reproduced: ~40k characters of real conversation, provider reporting
|
|
859
|
-
* `prompt_tokens: 10` — zero prunes, zero compactions, and a gauge reading 10,
|
|
860
|
-
* so nothing looks wrong. The context then overflows for real, with the
|
|
861
|
-
* defence that exists to stop exactly that switched off.
|
|
862
|
-
*
|
|
863
|
-
* So the reported number is used, but never as the ONLY number: it is floored
|
|
864
|
-
* against the local estimate. The estimate is a heuristic; the point is that
|
|
865
|
-
* `??` was the wrong way to combine a measurement with a floor — it only falls
|
|
866
|
-
* back when the value is ABSENT, so a confidently wrong value was trusted more
|
|
867
|
-
* than the guess.
|
|
868
|
-
*
|
|
869
|
-
* The floor is a HALF of the local estimate. A quarter was tried first and
|
|
870
|
-
* was too weak to clear the 0.6-of-budget threshold for a realistic session
|
|
871
|
-
* (estimate 5108 → floored 1277 against a 3600 bar), so the guard still would
|
|
872
|
-
* not have fired. Half keeps the intent — catch "reported 10 when the real
|
|
873
|
-
* prompt is large" — without arguing with a provider whose tokenizer
|
|
874
|
-
* legitimately differs from ours, since a provider within 2x of the estimate
|
|
875
|
-
* is not the failure mode being defended against.
|
|
847
|
+
* `lastUsage.input` is the provider's own count, but a proxy or shim that under-reports it would
|
|
848
|
+
* make BOTH gates believe the context is nearly empty, switching off the defence entirely. So it
|
|
849
|
+
* is floored at HALF the local estimate: a provider within 2x of our tokenizer is legitimate, a
|
|
850
|
+
* provider reporting ~10 tokens for a large prompt is not.
|
|
876
851
|
*/
|
|
877
852
|
contextSizeForBudgeting() {
|
|
878
853
|
const estimated = this.estimateTokens();
|
|
@@ -897,14 +872,14 @@ export class Agent {
|
|
|
897
872
|
*
|
|
898
873
|
* Anything keying "should this button stop or start?" off `status` alone
|
|
899
874
|
* therefore offers **start** on a working agent, and the user cannot stop it
|
|
900
|
-
*
|
|
875
|
+
* — the same trap #38 documented for editing history.
|
|
901
876
|
*/
|
|
902
877
|
isLive() {
|
|
903
|
-
//
|
|
878
|
+
// a MANUAL compaction on an idle agent was rewriting `messages` — a
|
|
904
879
|
// large, non-cancellable operation — while `isLive()` reported false, so the
|
|
905
880
|
// UI offered "start".
|
|
906
881
|
//
|
|
907
|
-
//
|
|
882
|
+
// and the reverse — after a STOP with prompts still queued, `live` stayed
|
|
908
883
|
// true forever, so the controls kept offering "stop" for an agent that was
|
|
909
884
|
// already stopped, and no amount of reloading helped. Measured:
|
|
910
885
|
//
|
|
@@ -915,7 +890,7 @@ export class Agent {
|
|
|
915
890
|
// DISCARD those prompts, so they are kept — but keeping them must not make the
|
|
916
891
|
// agent read as running. A stop outranks them.
|
|
917
892
|
//
|
|
918
|
-
//
|
|
893
|
+
// and one more, from the same family. The round-level retry backoff sets
|
|
919
894
|
// status "error" while it sleeps ("… — retrying in 60s"), and `error` is not a
|
|
920
895
|
// live status — so the UI offered "▶ start" for an agent that was waiting to
|
|
921
896
|
// retry, and there was NO stop control at all. The operator pressed what was
|
|
@@ -929,14 +904,14 @@ export class Agent {
|
|
|
929
904
|
this.pendingPrompts.length > 0 ||
|
|
930
905
|
this.compactPhase !== "" ||
|
|
931
906
|
this.retrySleeping ||
|
|
932
|
-
//
|
|
907
|
+
// a BACKGROUND job is work in flight, and `stop()` now ends it. The
|
|
933
908
|
// round that started it deliberately ended (the loop breaks rather than
|
|
934
909
|
// nagging — see hasRunningBgShells in loop()), so the status reads "idle"
|
|
935
910
|
// while a dev server / watcher / long build is still running. Without this
|
|
936
911
|
// the UI offered "▶ start" and there was no stop control for the one thing
|
|
937
912
|
// the operator most needs to stop. Note this is checked AFTER stopRequested:
|
|
938
913
|
// once stopped, the jobs are already dead, so `live` must go false or the
|
|
939
|
-
// button would offer stop forever
|
|
914
|
+
// button would offer stop forever.
|
|
940
915
|
// OWNER-SCOPED, not directory-scoped. Sub-agents inherit their parent's workspace, so
|
|
941
916
|
// asking "does this DIRECTORY have background shells?" made every stopped sibling of a
|
|
942
917
|
// busy agent report `live: true`. MEASURED: four STOPPED sub-agents in one workspace
|
|
@@ -1016,7 +991,7 @@ export class Agent {
|
|
|
1016
991
|
return true; // already parked: the tool may proceed
|
|
1017
992
|
if (this.status !== "running")
|
|
1018
993
|
return false;
|
|
1019
|
-
//
|
|
994
|
+
// a prompt queued BEFORE the park would be stranded by it — the
|
|
1020
995
|
// enqueue-time wake only handles prompts arriving DURING the park. Refuse,
|
|
1021
996
|
// so the tool stands down and the next turn boundary consumes the queue.
|
|
1022
997
|
if (this.pendingPrompts.length > 0)
|
|
@@ -1079,7 +1054,7 @@ export class Agent {
|
|
|
1079
1054
|
this.goal = stored ?? { text: "", status: "active", updatedAt: new Date().toISOString() };
|
|
1080
1055
|
// operator-maintained task list lives beside goal.md
|
|
1081
1056
|
this.todo = await fs.readFile(this.todoFile, "utf8").catch(() => "");
|
|
1082
|
-
//
|
|
1057
|
+
// NO skill scan here. It was the single largest boot cost — 493 agents
|
|
1083
1058
|
// each walking their roots (readdir + stat, recursively) measured 2120 ms of
|
|
1084
1059
|
// a 4.7 s boot. Every one of those walks was redundant:
|
|
1085
1060
|
//
|
|
@@ -1132,7 +1107,7 @@ export class Agent {
|
|
|
1132
1107
|
await this.ensureReady();
|
|
1133
1108
|
}
|
|
1134
1109
|
/**
|
|
1135
|
-
* Answer tool_calls in a RESTORED history that have no tool_result
|
|
1110
|
+
* Answer tool_calls in a RESTORED history that have no tool_result.
|
|
1136
1111
|
*
|
|
1137
1112
|
* The ordinary backstop (`answerUnansweredToolCalls`) works on an assistant
|
|
1138
1113
|
* turn inside a live loop. After a restart there is no loop: the call is in
|
|
@@ -1175,7 +1150,6 @@ export class Agent {
|
|
|
1175
1150
|
/**
|
|
1176
1151
|
* Durable notes — AGENT-scoped, not session-scoped.
|
|
1177
1152
|
*
|
|
1178
|
-
* MEASURED: memory.md lived in `sessionDir`, so starting a new session for an agent
|
|
1179
1153
|
* silently orphaned everything it had learned. Across this machine, 66 agents had more
|
|
1180
1154
|
* than one session (median 6 each) and only 5 of them had notes in any session at all —
|
|
1181
1155
|
* the notes were written, then abandoned when the next session was minted. A "durable
|
|
@@ -1349,7 +1323,7 @@ export class Agent {
|
|
|
1349
1323
|
// the whole file (not just the current branch) to match what the runtime
|
|
1350
1324
|
// panel showed before the restart.
|
|
1351
1325
|
for (const e of own) {
|
|
1352
|
-
//
|
|
1326
|
+
// the title comes from the FIRST user prompt, which never changes, so
|
|
1353
1327
|
// deriving it here is free — this loop already walks the whole log at
|
|
1354
1328
|
// restore. Only the first one is taken; later prompts are a different
|
|
1355
1329
|
// subject and would make the sidebar label churn under the reader.
|
|
@@ -1421,7 +1395,7 @@ export class Agent {
|
|
|
1421
1395
|
if (msgs.length > 0) {
|
|
1422
1396
|
this.messages = msgs;
|
|
1423
1397
|
this.currentBranch = last.branch;
|
|
1424
|
-
//
|
|
1398
|
+
// re-apply pruning to the restored history. `maybePrune` clips
|
|
1425
1399
|
// oversized tool output IN PLACE, so a live session keeps its clipped
|
|
1426
1400
|
// text while the log still holds the full result — a restart therefore
|
|
1427
1401
|
// handed the provider a strictly LARGER prompt than the one that had just
|
|
@@ -1434,7 +1408,7 @@ export class Agent {
|
|
|
1434
1408
|
// not consult the "is there room" bar — a restored context that happens to sit
|
|
1435
1409
|
// below it still has to match the prompt the provider last accepted.
|
|
1436
1410
|
await this.maybePrune(true);
|
|
1437
|
-
//
|
|
1411
|
+
// answer tool_calls the log says are still open.
|
|
1438
1412
|
//
|
|
1439
1413
|
// The restore path rebuilds `msgs` straight from the log, so a call whose
|
|
1440
1414
|
// process died mid-command comes back as an assistant turn with
|
|
@@ -1442,7 +1416,6 @@ export class Agent {
|
|
|
1442
1416
|
// not `stop()` (there is no turn to stop) and not `dispose()` (the process
|
|
1443
1417
|
// is already gone). The row then renders as still running for good.
|
|
1444
1418
|
//
|
|
1445
|
-
// Measured across every session log: 43,483 tool_calls, and 4 unanswered —
|
|
1446
1419
|
// every one a `bash`, each followed immediately by
|
|
1447
1420
|
// `session-restored` / `idle->stopped disposed`. The shape is a restart
|
|
1448
1421
|
// (or a crash) landing while a long command was in flight, which is
|
|
@@ -1485,7 +1458,7 @@ export class Agent {
|
|
|
1485
1458
|
// (wait_children does this), and queued prompts have not been consumed yet.
|
|
1486
1459
|
// Editing underneath either of those replaces the very `messages` array the
|
|
1487
1460
|
// agent is about to resume into, so its old-branch work kept running
|
|
1488
|
-
// against the new branch
|
|
1461
|
+
// against the new branch.
|
|
1489
1462
|
if (this.status === "running" || this.parkedByTool || this.pendingPrompts.length)
|
|
1490
1463
|
throw new Error("agent is running — stop it before editing history");
|
|
1491
1464
|
const all = await readEvents(this.log.filePath);
|
|
@@ -1521,14 +1494,14 @@ export class Agent {
|
|
|
1521
1494
|
const newBranch = `br${this.branchCount()}${Date.now().toString(36).slice(-4)}`;
|
|
1522
1495
|
// Quiesce BEFORE rewriting history: an in-flight LLM call, a parked tool or
|
|
1523
1496
|
// a queued prompt would otherwise resume into the NEW messages array and
|
|
1524
|
-
// keep running the old branch's work here
|
|
1497
|
+
// keep running the old branch's work here. Mirrors stop(), which is
|
|
1525
1498
|
// the only other place that cancels this state.
|
|
1526
1499
|
await this.quiesceForHistoryEdit();
|
|
1527
1500
|
// The fork event must be appended while currentBranch is still the OLD
|
|
1528
1501
|
// one. EventLog links parents PER BRANCH (lastByBranch), so appending it
|
|
1529
1502
|
// under the new branch gave it parent:null — severing the chain, and
|
|
1530
1503
|
// lineageOf() then returned only the post-fork events, so a restart rebuilt
|
|
1531
|
-
// the history with none of the pre-edit context
|
|
1504
|
+
// the history with none of the pre-edit context.
|
|
1532
1505
|
await this.log.append("fork", this.currentSession, this.currentBranch, {
|
|
1533
1506
|
fromSession: this.currentSession,
|
|
1534
1507
|
fromBranch: this.currentBranch,
|
|
@@ -1539,9 +1512,9 @@ export class Agent {
|
|
|
1539
1512
|
tailMode: tail,
|
|
1540
1513
|
});
|
|
1541
1514
|
// Seed the new branch's parent link so its first event chains across
|
|
1542
|
-
// instead of starting a disconnected parent:null history
|
|
1515
|
+
// instead of starting a disconnected parent:null history.
|
|
1543
1516
|
//
|
|
1544
|
-
//
|
|
1517
|
+
// seed from the CUT POINT, not from this branch's tip. The fork event
|
|
1545
1518
|
// records where the edit was made (`fromEvent` = the last KEPT event), but
|
|
1546
1519
|
// `lastEventId(currentBranch)` is the newest event on the branch — which is
|
|
1547
1520
|
// one of the events this edit just DISCARDED. Seeding from the tip chained
|
|
@@ -1564,7 +1537,7 @@ export class Agent {
|
|
|
1564
1537
|
* An edit rewinds the conversation, so any work still in flight belongs to
|
|
1565
1538
|
* the branch being discarded: an LLM call whose result would append to the
|
|
1566
1539
|
* new messages, a parked tool, and queued prompts that were never delivered
|
|
1567
|
-
|
|
1540
|
+
*. stopRequested is set and cleared around the wait so the agent is
|
|
1568
1541
|
* usable again once the edit lands.
|
|
1569
1542
|
*/
|
|
1570
1543
|
async quiesceForHistoryEdit() {
|
|
@@ -1810,7 +1783,6 @@ export class Agent {
|
|
|
1810
1783
|
/**
|
|
1811
1784
|
* The DISPLAYED status, which must never contradict `live`.
|
|
1812
1785
|
*
|
|
1813
|
-
* MEASURED report: "バックグラウンドbash待ちで finish_reason: stop でAIが止まると表示は
|
|
1814
1786
|
* idle なのにコントロールは stop ボタンが表示されてて微妙" — and the same for
|
|
1815
1787
|
* `wait_children`. `live` was already true for both (a parked tool and a running
|
|
1816
1788
|
* background shell are work in flight, and stop() ends them), so only the badge was
|
|
@@ -1829,7 +1801,7 @@ export class Agent {
|
|
|
1829
1801
|
* parked tool (`wait_children`) rewrites the status to "idle" while the
|
|
1830
1802
|
* loop is very much alive, so a client keying "stop vs start" off
|
|
1831
1803
|
* `status === "running"` offered **start** on a running agent and the
|
|
1832
|
-
* user could not stop it
|
|
1804
|
+
* user could not stop it. This is the same "running is not the
|
|
1833
1805
|
* only live state" fact #38 had to be taught about editing.
|
|
1834
1806
|
*/
|
|
1835
1807
|
live: this.isLive(),
|
|
@@ -1837,7 +1809,7 @@ export class Agent {
|
|
|
1837
1809
|
// through the getter, so a workspace that came back stops being reported as 👻
|
|
1838
1810
|
workspaceMissing: this.isGhost,
|
|
1839
1811
|
session: this.currentSession,
|
|
1840
|
-
//
|
|
1812
|
+
// a human label for this session, so the sidebar does not ask the
|
|
1841
1813
|
// operator to read `teapot-10-16854917`. Absent when the first prompt had
|
|
1842
1814
|
// no usable line — the UI then falls back to the id.
|
|
1843
1815
|
...(this.sessionTitle ? { sessionTitle: this.sessionTitle } : {}),
|
|
@@ -1852,7 +1824,6 @@ export class Agent {
|
|
|
1852
1824
|
* text they wrote, so a long goal stopped mid-sentence. Reported as "goalに設定されている
|
|
1853
1825
|
* 文字列が長いとフロントエンドのgoal欄で後半が切られる? 全部表示されてほしい".
|
|
1854
1826
|
*
|
|
1855
|
-
* MEASURED: a 1500-character goal reached the browser as exactly 400 characters. The
|
|
1856
1827
|
* payload argument does not survive the numbers either — this rides one `/api/agents`
|
|
1857
1828
|
* response that is already carrying every agent's stats, and a goal is a few KB at worst.
|
|
1858
1829
|
* `verify` keeps its own cap below, where the auditor writes it.
|
|
@@ -1870,7 +1841,7 @@ export class Agent {
|
|
|
1870
1841
|
effortSupported: effortChoosable(this.opts.supportedParameters),
|
|
1871
1842
|
// the levels to OFFER, when the endpoint publishes them: a model with
|
|
1872
1843
|
// ["max","high","low"] must not be shown minimal/medium, which would either be
|
|
1873
|
-
// refused or silently clamped
|
|
1844
|
+
// refused or silently clamped
|
|
1874
1845
|
...(this.opts.supportedEfforts?.length ? { effortOptions: this.opts.supportedEfforts } : {}),
|
|
1875
1846
|
sessionDir: this.opts.sessionDir,
|
|
1876
1847
|
ctx: {
|
|
@@ -1886,7 +1857,7 @@ export class Agent {
|
|
|
1886
1857
|
...(this.compactPhase ? { compacting: this.compactPhase } : {}),
|
|
1887
1858
|
},
|
|
1888
1859
|
pendingPrompts: this.pendingPrompts.length,
|
|
1889
|
-
//
|
|
1860
|
+
// the IDS as well as the count. The web UI reconciles its local echo
|
|
1890
1861
|
// list against the live queue, and it was doing that by POSITION
|
|
1891
1862
|
// (slice(0, queued)) because only a count was published — so whenever the
|
|
1892
1863
|
// count dipped below the true queue length (a mid-queue cancellation, or a
|
|
@@ -1897,7 +1868,7 @@ export class Agent {
|
|
|
1897
1868
|
// Bounded like the rest of the snapshot, and ids are opaque, so this
|
|
1898
1869
|
// cannot carry prompt text.
|
|
1899
1870
|
pendingPromptIds: this.pendingPrompts.map((p) => p.id).filter((x) => !!x).slice(0, 64),
|
|
1900
|
-
//
|
|
1871
|
+
// the QUEUE itself, not just its ids. The UI's echo rows are
|
|
1901
1872
|
// memory-only (like liveByAgent and timelineCache), so after a reload the
|
|
1902
1873
|
// queue survives on the server while the UI has nothing to render — the
|
|
1903
1874
|
// queued message then appears only as its log row, i.e. already sent.
|
|
@@ -1958,7 +1929,7 @@ export class Agent {
|
|
|
1958
1929
|
// stable id shared by the log event and the UI's pending echo — the UI
|
|
1959
1930
|
// flips its echo to "sent" when prompt-delivered carries this id back
|
|
1960
1931
|
const promptId = source === "user" ? `u${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}` : "";
|
|
1961
|
-
//
|
|
1932
|
+
// the queue entry is registered SYNCHRONOUSLY, before the async work.
|
|
1962
1933
|
//
|
|
1963
1934
|
// It used to be pushed inside the `.then()`, so it only existed once
|
|
1964
1935
|
// `ensureReady()` resolved — while `cancelPrompt` reads the array
|
|
@@ -2031,7 +2002,7 @@ export class Agent {
|
|
|
2031
2002
|
}
|
|
2032
2003
|
if (p.source === "user") {
|
|
2033
2004
|
const id = p.id ?? `u${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
|
2034
|
-
//
|
|
2005
|
+
// queued here, MARKED at the request boundary instead — see
|
|
2035
2006
|
// markDeliveredPrompts(). Text is kept so the marker can carry the same
|
|
2036
2007
|
// preview the UI shows.
|
|
2037
2008
|
this.undeliveredPrompts.push({ id, preview: p.text.slice(0, 80) });
|
|
@@ -2041,7 +2012,7 @@ export class Agent {
|
|
|
2041
2012
|
/** ids of user prompts that have entered an LLM call payload (recent first-capped) */
|
|
2042
2013
|
deliveredPrompts = [];
|
|
2043
2014
|
/**
|
|
2044
|
-
* User prompts consumed from the queue but not yet MARKED as delivered
|
|
2015
|
+
* User prompts consumed from the queue but not yet MARKED as delivered.
|
|
2045
2016
|
*
|
|
2046
2017
|
* They are drained at a turn boundary, but the `prompt-delivered` marker must
|
|
2047
2018
|
* wait until the request that carries them actually starts — which is later,
|
|
@@ -2051,7 +2022,7 @@ export class Agent {
|
|
|
2051
2022
|
/**
|
|
2052
2023
|
* Log `prompt-delivered` for every prompt whose outbound request is starting.
|
|
2053
2024
|
*
|
|
2054
|
-
*
|
|
2025
|
+
* the marker's meaning is "the request carrying this prompt has begun".
|
|
2055
2026
|
* It used to fire in drainPendingPrompts, i.e. before the request, so the
|
|
2056
2027
|
* timeline reordered by a moment the API never saw.
|
|
2057
2028
|
*/
|
|
@@ -2133,7 +2104,7 @@ export class Agent {
|
|
|
2133
2104
|
}
|
|
2134
2105
|
/** Start (or resume) autonomous operation toward the goal. */
|
|
2135
2106
|
start(reason = "start") {
|
|
2136
|
-
//
|
|
2107
|
+
// a stop() immediately followed by start() USED TO BE SILENTLY LOST.
|
|
2137
2108
|
//
|
|
2138
2109
|
// `stop()` only flips the status via an ENQUEUED task, so between the two
|
|
2139
2110
|
// calls the status is still "running" and the guard below returned early —
|
|
@@ -2149,7 +2120,7 @@ export class Agent {
|
|
|
2149
2120
|
if (this.status === "running" && !pendingStop)
|
|
2150
2121
|
return;
|
|
2151
2122
|
this.stopRequested = false;
|
|
2152
|
-
// claim the status against any stop write still queued behind us
|
|
2123
|
+
// claim the status against any stop write still queued behind us
|
|
2153
2124
|
this.stopSeq++;
|
|
2154
2125
|
this.awaitingUser = false; // a fresh start answers/resumes past any ask_user
|
|
2155
2126
|
void this.enqueue(async () => {
|
|
@@ -2166,7 +2137,7 @@ export class Agent {
|
|
|
2166
2137
|
// without aborting toolCtx.signal the park ran to its full timeout
|
|
2167
2138
|
this.abort?.abort();
|
|
2168
2139
|
this.toolAbort.abort();
|
|
2169
|
-
//
|
|
2140
|
+
// and the BACKGROUND shells, which neither signal above reaches. A job
|
|
2170
2141
|
// spawned with `background: true` is `detached` and its spawning tool returned
|
|
2171
2142
|
// long ago, so `toolAbort` has nothing on the stack to abort: the agent parked
|
|
2172
2143
|
// in its "wait for the job" idle state, the job kept running, and `stop()` —
|
|
@@ -2174,7 +2145,7 @@ export class Agent {
|
|
|
2174
2145
|
// `sleep 300` outlived both stop() and dispose().
|
|
2175
2146
|
killBgShells(this.toolCtx.cwd);
|
|
2176
2147
|
this.wake?.();
|
|
2177
|
-
//
|
|
2148
|
+
// the status write is DEFERRED onto the run chain, so it can land
|
|
2178
2149
|
// AFTER a start() that followed it. Observed: `idle -> stopped -> running ->
|
|
2179
2150
|
// running -> idle`. The agent did resume — but it flashed "stopped" on the
|
|
2180
2151
|
// way, and finished idle rather than running, so from the UI the operator's
|
|
@@ -2191,7 +2162,7 @@ export class Agent {
|
|
|
2191
2162
|
void this.enqueue(() => {
|
|
2192
2163
|
// Only a start() that arrived AFTER this stop may claim the status. The
|
|
2193
2164
|
// seq check alone does that — no status test, because a genuinely running
|
|
2194
|
-
// agent must still be reported "stopped"
|
|
2165
|
+
// agent must still be reported "stopped".
|
|
2195
2166
|
if (this.stopSeq !== stopSeq)
|
|
2196
2167
|
return Promise.resolve();
|
|
2197
2168
|
this.setStatus("stopped", reason);
|
|
@@ -2206,7 +2177,7 @@ export class Agent {
|
|
|
2206
2177
|
* CONTROL PLANE: fired on every status change, immediately, independent of the
|
|
2207
2178
|
* log.
|
|
2208
2179
|
*
|
|
2209
|
-
*
|
|
2180
|
+
* `wait_children` wakeups used to ride `EventLog.onEvent`, so a status
|
|
2210
2181
|
* change reached the parent only AFTER the write completed. After the
|
|
2211
2182
|
* write-before-notify fix that meant a FAILED or slow write left a parked parent
|
|
2212
2183
|
* waiting forever — persistence latency became control flow. Measured with every
|
|
@@ -2229,7 +2200,7 @@ export class Agent {
|
|
|
2229
2200
|
this.status = s;
|
|
2230
2201
|
this.statusReason = reason;
|
|
2231
2202
|
if (prev !== s) {
|
|
2232
|
-
//
|
|
2203
|
+
// control plane FIRST, and not via the log. A parent's wait_children
|
|
2233
2204
|
// must wake on the status change itself, not on the durability of the write
|
|
2234
2205
|
// that records it.
|
|
2235
2206
|
try {
|
|
@@ -2291,7 +2262,7 @@ export class Agent {
|
|
|
2291
2262
|
if (this.stopRequested)
|
|
2292
2263
|
break;
|
|
2293
2264
|
// fresh user input arrived while we were finishing up — another round now
|
|
2294
|
-
//
|
|
2265
|
+
// bound consecutive audit rejections.
|
|
2295
2266
|
//
|
|
2296
2267
|
// A rejected audit queues a retry prompt, so the round CONTINUES — and
|
|
2297
2268
|
// neither existing valve applies: maxConsecutiveIdleRounds counts IDLE
|
|
@@ -2331,7 +2302,7 @@ export class Agent {
|
|
|
2331
2302
|
break;
|
|
2332
2303
|
}
|
|
2333
2304
|
// A SUB-AGENT that ended its round on a bare message (no finish call)
|
|
2334
|
-
// still owes the parent a report — nothing else will carry it
|
|
2305
|
+
// still owes the parent a report — nothing else will carry it.
|
|
2335
2306
|
// Emitted HERE, after the loop, so a real finish() on a later turn
|
|
2336
2307
|
// always wins and this never pre-empts a better summary.
|
|
2337
2308
|
if (this.pendingSubReport) {
|
|
@@ -2342,7 +2313,7 @@ export class Agent {
|
|
|
2342
2313
|
finished = true; // it IS finished now — don't auto-nudge a reporter
|
|
2343
2314
|
}
|
|
2344
2315
|
}
|
|
2345
|
-
//
|
|
2316
|
+
// a round that did real work resets the idle counter. `finished`
|
|
2346
2317
|
// covers the finish() paths; a round that ran tool calls is caught by the
|
|
2347
2318
|
// turn counter below, which is checked before this point.
|
|
2348
2319
|
if (finished)
|
|
@@ -2353,33 +2324,14 @@ export class Agent {
|
|
|
2353
2324
|
this.goal.status !== "active" ||
|
|
2354
2325
|
!this.goal.text.trim())
|
|
2355
2326
|
break;
|
|
2356
|
-
// auto-continue: wait quietly, then nudge with a fresh round.
|
|
2357
|
-
//
|
|
2358
|
-
//
|
|
2359
|
-
// re-read its inherited context and drift into one of the parent's
|
|
2360
|
-
// older tasks — it would keep going forever without ever finish()ing.
|
|
2361
|
-
// #106: bound CONSECUTIVE auto-continued rounds.
|
|
2362
|
-
//
|
|
2363
|
-
// maxTurnsPerRound cannot bound this loop, and the reason is structural:
|
|
2364
|
-
// a ROOT agent that answers with a bare message ends its round after ONE
|
|
2365
|
-
// turn (`return finished` in runTurnsUntilIdle), so no single round ever
|
|
2366
|
-
// reaches the per-round cap. `finished` stays false, the goal stays
|
|
2367
|
-
// active, and auto-continue starts the next round — forever.
|
|
2327
|
+
// auto-continue: wait quietly, then nudge with a fresh round. Sub-agents get a
|
|
2328
|
+
// SCOPE-ANCHORED nudge — a generic "continue toward the goal" made a forked sub-agent drift
|
|
2329
|
+
// into one of the parent's older tasks.
|
|
2368
2330
|
//
|
|
2369
|
-
//
|
|
2370
|
-
//
|
|
2371
|
-
//
|
|
2372
|
-
//
|
|
2373
|
-
//
|
|
2374
|
-
// So the bound belongs here, where the real loop is: consecutive rounds
|
|
2375
|
-
// that produced neither a finish() nor a tool call. Any tool call resets
|
|
2376
|
-
// it — that is real work, not stalling — and so does a stop, a fresh
|
|
2377
|
-
// user prompt, or an operator reply.
|
|
2378
|
-
//
|
|
2379
|
-
// This is a SAFETY VALVE, not a policy. It is deliberately generous
|
|
2380
|
-
// (default 50) because a long autonomous stretch that keeps calling tools
|
|
2381
|
-
// resets the counter on every turn and is never affected; only a model
|
|
2382
|
-
// that never acts and never finishes trips it.
|
|
2331
|
+
// Bound CONSECUTIVE rounds that produced neither a finish() nor a tool call. Any tool call
|
|
2332
|
+
// resets it (that is real work, not stalling), as does a stop or a fresh prompt. This is a
|
|
2333
|
+
// safety valve, not a policy: a talk-only root agent ends every round after one turn, so no
|
|
2334
|
+
// per-round cap can ever see it, and `finished` stays false forever.
|
|
2383
2335
|
if (++this.consecutiveIdleRounds > this.opts.maxConsecutiveIdleRounds) {
|
|
2384
2336
|
this.consecutiveIdleRounds = 0;
|
|
2385
2337
|
await this.log.append("system_note", this.currentSession, this.currentBranch, {
|
|
@@ -2393,14 +2345,13 @@ export class Agent {
|
|
|
2393
2345
|
await this.sleepInterruptible(this.opts.continueDelayMs);
|
|
2394
2346
|
if (this.stopRequested)
|
|
2395
2347
|
break;
|
|
2396
|
-
//
|
|
2348
|
+
// do NOT pair this with a progress request.
|
|
2397
2349
|
//
|
|
2398
2350
|
// Both fire at the turn boundary and both inject a user message, so the model received two
|
|
2399
2351
|
// harness instructions back to back — "Continue working toward the current goal"
|
|
2400
2352
|
// immediately followed by "Please give a brief progress report now", which reads as the
|
|
2401
2353
|
// harness talking to itself.
|
|
2402
2354
|
//
|
|
2403
|
-
// MEASURED why `break` was wrong here (session tyb2-8-0161a4af, seq 18778-18780):
|
|
2404
2355
|
// `maybeRequestProgress` runs its OWN `llmCall` at the top of the turn, so the assistant
|
|
2405
2356
|
// message it produces is a progress REPORT, not a continuation. The round then ended,
|
|
2406
2357
|
// this branch saw the flag, logged `auto-continue-suppressed`, and BROKE — leaving the
|
|
@@ -2420,7 +2371,7 @@ export class Agent {
|
|
|
2420
2371
|
continue;
|
|
2421
2372
|
}
|
|
2422
2373
|
const isSub = !!this.opts.parent;
|
|
2423
|
-
//
|
|
2374
|
+
// the ROOT nudge now restates the goal too, exactly as the sub-agent
|
|
2424
2375
|
// one always has. Both branches need it — a child drifts back into the
|
|
2425
2376
|
// inherited conversation, a root agent loses the thread, and in both cases
|
|
2426
2377
|
// "continue toward the current goal" is unactionable without the goal text.
|
|
@@ -2456,7 +2407,7 @@ export class Agent {
|
|
|
2456
2407
|
kind: isRunaway ? "runaway" : "api",
|
|
2457
2408
|
});
|
|
2458
2409
|
this.setStatus("error", `${msg.slice(0, 220)} — retrying in ${Math.round(wait / 1000)}s`);
|
|
2459
|
-
//
|
|
2410
|
+
// while this sleeps the agent is NOT idle — it is going to try again,
|
|
2460
2411
|
// and the operator must be able to stop it. Without the flag `isLive()` read
|
|
2461
2412
|
// false (status is "error"), so the UI showed "▶ start" and offered no stop
|
|
2462
2413
|
// at all while a 5s/5s/30s…30min staircase ran.
|
|
@@ -2504,12 +2455,12 @@ export class Agent {
|
|
|
2504
2455
|
bus.emit("update", {
|
|
2505
2456
|
kind: "llm-delta",
|
|
2506
2457
|
agentId: this.opts.id,
|
|
2507
|
-
//
|
|
2458
|
+
// the bubble is session-scoped, so the stream must say which session
|
|
2508
2459
|
sessionId: this.currentSession,
|
|
2509
2460
|
text: "",
|
|
2510
2461
|
reasoning: "",
|
|
2511
2462
|
});
|
|
2512
|
-
//
|
|
2463
|
+
// `prompt-delivered` means "the outbound request CARRYING this prompt
|
|
2513
2464
|
// has started" — which is why it is emitted here and not in
|
|
2514
2465
|
// drainPendingPrompts. That runs BEFORE maybeCompact, which can itself make
|
|
2515
2466
|
// an LLM call, so the marker preceded the request and the timeline claimed a
|
|
@@ -2527,7 +2478,7 @@ export class Agent {
|
|
|
2527
2478
|
const name = err.name;
|
|
2528
2479
|
if (name === "StopRequested" || name === "AbortError" || this.stopRequested)
|
|
2529
2480
|
throw err;
|
|
2530
|
-
//
|
|
2481
|
+
// a context-overflow error is the caller's to handle, not ours to
|
|
2531
2482
|
// retry. Retrying the SAME oversized request four times with 5s/5s/30s
|
|
2532
2483
|
// waits cannot succeed, and it delays the compact-and-retry that would
|
|
2533
2484
|
// — so the overflow path never even ran. This is the same
|
|
@@ -2566,12 +2517,12 @@ export class Agent {
|
|
|
2566
2517
|
* the assistant batch;
|
|
2567
2518
|
* - `"end"` — the `return true` it replaced (`finish` only): end the whole batch, so a
|
|
2568
2519
|
* model that emits finish() plus another call cannot keep mutating the workspace
|
|
2569
|
-
* after reporting completion
|
|
2520
|
+
* after reporting completion.
|
|
2570
2521
|
*/
|
|
2571
2522
|
metaHandlers = {
|
|
2572
2523
|
finish: async (call, m) => {
|
|
2573
2524
|
this.pendingSubReport = ""; // the real summary supersedes it
|
|
2574
|
-
//
|
|
2525
|
+
// answer the tool_call BEFORE the audit runs.
|
|
2575
2526
|
//
|
|
2576
2527
|
// handleFinish() calls the auditor with `buildMessages()`, and at that
|
|
2577
2528
|
// moment the history ended at an assistant message carrying
|
|
@@ -2604,7 +2555,7 @@ export class Agent {
|
|
|
2604
2555
|
// answer the tool_call so a follow-up round stays API-valid
|
|
2605
2556
|
await this.answerMeta(call, this.goal.status === "done" ? "(goal complete)" : "(round ended)");
|
|
2606
2557
|
// the caller marks the round finished when this returns "end"
|
|
2607
|
-
//
|
|
2558
|
+
// `continue` advanced the TOOL-CALL loop, so every later call in
|
|
2608
2559
|
// this same assistant message still executed — a model emitting
|
|
2609
2560
|
// finish() plus one more call got real filesystem writes AFTER it had
|
|
2610
2561
|
// reported `final: true` and the goal was already done. The parent was
|
|
@@ -2677,7 +2628,7 @@ export class Agent {
|
|
|
2677
2628
|
this.setStatus("needs_operator", question.slice(0, 80));
|
|
2678
2629
|
// control flow: park the loop; the operator's next prompt resumes it
|
|
2679
2630
|
//
|
|
2680
|
-
//
|
|
2631
|
+
// answer the rest of this assistant batch BEFORE parking. The
|
|
2681
2632
|
// throw leaves the whole tool loop, so any EARLIER call in the same
|
|
2682
2633
|
// message that was logged but not yet run kept no tool_result — the
|
|
2683
2634
|
// comment on the backstop below says as much, and it is exactly the
|
|
@@ -2805,7 +2756,7 @@ export class Agent {
|
|
|
2805
2756
|
await this.answerMeta(call, "(memory.md is empty — nothing noted yet)");
|
|
2806
2757
|
return "next";
|
|
2807
2758
|
}
|
|
2808
|
-
//
|
|
2759
|
+
// `query` searches instead of dumping the whole file.
|
|
2809
2760
|
//
|
|
2810
2761
|
// This is the one idea worth taking from the ecosystem. MCP's reference memory
|
|
2811
2762
|
// server (the de-facto standard, used by Claude and offered by DSH as a
|
|
@@ -2814,7 +2765,6 @@ export class Agent {
|
|
|
2814
2765
|
// dependency. DSH's guidance to the model is the same shape: "when historical
|
|
2815
2766
|
// information may be relevant, search memory and use relevant results".
|
|
2816
2767
|
//
|
|
2817
|
-
// MEASURED why it matters here: `set_memory` was called 181 times but
|
|
2818
2768
|
// `read_memory` only 97 times across every session, and only 13 of those reads
|
|
2819
2769
|
// came after a write. Dumping a growing file gives the model no way to ask a
|
|
2820
2770
|
// QUESTION, so a big file is all-or-nothing — either burn the whole thing into
|
|
@@ -2877,7 +2827,7 @@ export class Agent {
|
|
|
2877
2827
|
const a = safeParse(call.function.arguments);
|
|
2878
2828
|
const content = String(a.content ?? "").slice(0, 32_000);
|
|
2879
2829
|
await fs.writeFile(this.memoryFile, content, "utf8");
|
|
2880
|
-
//
|
|
2830
|
+
// this used to say "injected into future prompts", which was false —
|
|
2881
2831
|
// memory.md is never injected. The model then behaved as if it already held
|
|
2882
2832
|
// its notes. Say what actually happened, and what the model must do instead.
|
|
2883
2833
|
await this.answerMeta(call, `memory.md REPLACED (${content.length} bytes). It is not in your prompt — call read_memory when you need it.`);
|
|
@@ -2890,7 +2840,7 @@ export class Agent {
|
|
|
2890
2840
|
await this.answerMeta(call, "forget_memory needs a `query` — nothing removed");
|
|
2891
2841
|
return "next";
|
|
2892
2842
|
}
|
|
2893
|
-
//
|
|
2843
|
+
// notes must be REMOVABLE, not only appendable.
|
|
2894
2844
|
//
|
|
2895
2845
|
// MCP's reference memory makes observations "added or removed
|
|
2896
2846
|
// independently" for exactly this reason: an append-only store accumulates
|
|
@@ -2931,7 +2881,7 @@ export class Agent {
|
|
|
2931
2881
|
await this.answerMeta(call, "add_memory needs non-empty `text` — nothing appended");
|
|
2932
2882
|
return "next";
|
|
2933
2883
|
}
|
|
2934
|
-
// APPEND rather than replace
|
|
2884
|
+
// APPEND rather than replace. `set_memory` overwrites the whole file,
|
|
2935
2885
|
// so a model that had not just read it silently ERASED everything it did not
|
|
2936
2886
|
// re-send — MEASURED on a real session: 21 writes, with the content dropping
|
|
2937
2887
|
// from 1028 to 83 bytes. Appending is the operation "remember this" actually
|
|
@@ -2959,7 +2909,7 @@ export class Agent {
|
|
|
2959
2909
|
// skills may have been created last turn — refresh the prompt listing
|
|
2960
2910
|
await this.refreshSkills();
|
|
2961
2911
|
// periodic progress report at turn boundary (no mid-turn interruption)
|
|
2962
|
-
//
|
|
2912
|
+
// the flag is per-TURN, not per-round. `maybeRequestProgress` sits
|
|
2963
2913
|
// inside the turn loop and auto-continue is checked after the round
|
|
2964
2914
|
// ends, so the flag has to mean "this boundary already carried an
|
|
2965
2915
|
// instruction" — reset here, set below if the request fires.
|
|
@@ -3111,7 +3061,7 @@ export class Agent {
|
|
|
3111
3061
|
// Models overwhelmingly prefer writing their report as the final message
|
|
3112
3062
|
// over calling finish(), and only handleFinish() emits the `final: true`
|
|
3113
3063
|
// event that onChildEvent() forwards to the parent. So that habit silently
|
|
3114
|
-
// cost the parent the ENTIRE result
|
|
3064
|
+
// cost the parent the ENTIRE result — the report existed only in the
|
|
3115
3065
|
// child's own log, which the parent's model context never replays.
|
|
3116
3066
|
// Harvest it here so both paths share one code path.
|
|
3117
3067
|
if (!m.tool_calls?.length) {
|
|
@@ -3119,7 +3069,7 @@ export class Agent {
|
|
|
3119
3069
|
// signal "I'm done" — far more often than by calling finish(), which
|
|
3120
3070
|
// the spawn directive asks for but they routinely ignore.
|
|
3121
3071
|
//
|
|
3122
|
-
// Two things were wrong
|
|
3072
|
+
// Two things were wrong:
|
|
3123
3073
|
// 1. only handleFinish() emits the `final: true` event that
|
|
3124
3074
|
// onChildEvent() forwards to the parent, so a sub-agent that ended
|
|
3125
3075
|
// with a plain message sent the parent NOTHING — the report lived
|
|
@@ -3136,7 +3086,7 @@ export class Agent {
|
|
|
3136
3086
|
// turn explicit, so a child that just wanted to narrate ends here (and
|
|
3137
3087
|
// its held report is forwarded by the loop's end-of-round path), while
|
|
3138
3088
|
// a child that has a real summary delivers it instead. A real finish()
|
|
3139
|
-
// clears the held note, so it is forwarded exactly once
|
|
3089
|
+
// clears the held note, so it is forwarded exactly once.
|
|
3140
3090
|
if (this.opts.parent) {
|
|
3141
3091
|
if (this.pendingSubReport) {
|
|
3142
3092
|
// already offered a turn after a bare message — take the held report
|
|
@@ -3158,7 +3108,7 @@ export class Agent {
|
|
|
3158
3108
|
}
|
|
3159
3109
|
for (const call of m.tool_calls) {
|
|
3160
3110
|
if (this.stopRequested) {
|
|
3161
|
-
//
|
|
3111
|
+
// this returned straight out of the turn, SKIPPING the
|
|
3162
3112
|
// answerUnansweredToolCalls backstop below — so every remaining
|
|
3163
3113
|
// tool_call in this assistant message stayed logged with NO
|
|
3164
3114
|
// tool_result anywhere, and its row rendered as "waiting for
|
|
@@ -3170,7 +3120,7 @@ export class Agent {
|
|
|
3170
3120
|
// above), so a tool the prompt advertises but the loop does not handle is a
|
|
3171
3121
|
// COMPILE error rather than a runtime "unknown tool". The two return kinds are the
|
|
3172
3122
|
// two the old if-chain had: "next" is the `continue` it replaced, "end" is
|
|
3173
|
-
// finish() ending the whole batch
|
|
3123
|
+
// finish() ending the whole batch. Anything not in the table is a real tool
|
|
3174
3124
|
// and falls through to executeTool below.
|
|
3175
3125
|
const meta = this.metaHandlers[call.function.name];
|
|
3176
3126
|
if (meta) {
|
|
@@ -3188,7 +3138,7 @@ export class Agent {
|
|
|
3188
3138
|
});
|
|
3189
3139
|
const t0 = Date.now();
|
|
3190
3140
|
// first filesystem touch creates a missing workspace (never at boot)
|
|
3191
|
-
//
|
|
3141
|
+
// this is awaited BETWEEN the tool_call append above and the
|
|
3192
3142
|
// tool_result append below, and `fs.mkdir` has no catch — so a failure
|
|
3193
3143
|
// propagated out of the whole loop, leaving the call logged with no
|
|
3194
3144
|
// result ANYWHERE, and its row read "waiting for output…" for good.
|
|
@@ -3206,9 +3156,9 @@ export class Agent {
|
|
|
3206
3156
|
result = { ok: false, result: `tool could not run: ${err.message}` };
|
|
3207
3157
|
}
|
|
3208
3158
|
this.stats.toolCalls++;
|
|
3209
|
-
//
|
|
3159
|
+
// a tool call is real work, so it clears the idle-round counter.
|
|
3210
3160
|
this.consecutiveIdleRounds = 0;
|
|
3211
|
-
//
|
|
3161
|
+
// ONE clip, applied to BOTH the log and the live message.
|
|
3212
3162
|
//
|
|
3213
3163
|
// The log stored `result.slice(0, 8000)` while `messages` kept the full
|
|
3214
3164
|
// text, and a restore rebuilds `messages` from the log — so a model
|
|
@@ -3245,7 +3195,7 @@ export class Agent {
|
|
|
3245
3195
|
`(last: ${call.function.name})`);
|
|
3246
3196
|
}
|
|
3247
3197
|
}
|
|
3248
|
-
//
|
|
3198
|
+
// every tool_call an assistant message issued must have a matching
|
|
3249
3199
|
// tool result, or the provider REJECTS the next request — which is the
|
|
3250
3200
|
// "`200 with no choices`" shape #50 traced to a malformed history.
|
|
3251
3201
|
//
|
|
@@ -3309,7 +3259,7 @@ export class Agent {
|
|
|
3309
3259
|
const sys = this.systemPrompt();
|
|
3310
3260
|
const hasSystem = this.messages[0]?.role === "system";
|
|
3311
3261
|
const head = [{ role: "system", content: sys }];
|
|
3312
|
-
// NOTE
|
|
3262
|
+
// NOTE: tool-call pairing is guaranteed one layer down, in `sanitize()`,
|
|
3313
3263
|
// because EVERY request path passes through there (turns, the summarizer, the ACP
|
|
3314
3264
|
// adapter) while this builds only an Agent's own turn. A violated pairing is refused
|
|
3315
3265
|
// with a bare "invalid request error", which is not recognisable as an overflow and
|
|
@@ -3357,7 +3307,7 @@ export class Agent {
|
|
|
3357
3307
|
wsSnapshot = "";
|
|
3358
3308
|
/**
|
|
3359
3309
|
* one-time catalogue of available skills, injected with the system prompt
|
|
3360
|
-
|
|
3310
|
+
*. Built once alongside wsSnapshot so the prompt stays byte-identical
|
|
3361
3311
|
* for the session and the provider prefix cache survives.
|
|
3362
3312
|
*/
|
|
3363
3313
|
skillCatalogue = "";
|
|
@@ -3433,7 +3383,7 @@ export class Agent {
|
|
|
3433
3383
|
this.agentsMd = "";
|
|
3434
3384
|
}
|
|
3435
3385
|
}
|
|
3436
|
-
//
|
|
3386
|
+
// capture the skill catalogue in the SAME one-shot block, so the
|
|
3437
3387
|
// system prompt stays byte-identical for the session (prefix cache).
|
|
3438
3388
|
this.skillCatalogue = this.skillCatalogueText();
|
|
3439
3389
|
this.memoryDigest = this.memoryDigestText();
|
|
@@ -3445,7 +3395,7 @@ export class Agent {
|
|
|
3445
3395
|
if (this.wsSnapshot) {
|
|
3446
3396
|
sys += `\n\n## Workspace snapshot (top level)\n${this.wsSnapshot}\nUse list_dir/read_file for anything deeper — do NOT list again what is already here.`;
|
|
3447
3397
|
}
|
|
3448
|
-
//
|
|
3398
|
+
// the catalogue of AVAILABLE SKILLS. The prompt previously named the
|
|
3449
3399
|
// skill TOOLS but never the skills themselves, so the only way to discover
|
|
3450
3400
|
// one was to spend a tool call on list_skills() — and a model that does not
|
|
3451
3401
|
// know a skill exists will never think to look.
|
|
@@ -3492,7 +3442,7 @@ export class Agent {
|
|
|
3492
3442
|
* typed into the finish() summary argument.
|
|
3493
3443
|
*
|
|
3494
3444
|
* Extracted as its own method because a REJECTED completion audit also needs
|
|
3495
|
-
* it
|
|
3445
|
+
* it — the retry prompt should carry the same context an approved one
|
|
3496
3446
|
* would — while emitting no `final: true`.
|
|
3497
3447
|
*/
|
|
3498
3448
|
async captureRecentTurns() {
|
|
@@ -3502,7 +3452,7 @@ export class Agent {
|
|
|
3502
3452
|
if (m.role === "user")
|
|
3503
3453
|
continue; // prompts/noise — keep agent output only
|
|
3504
3454
|
const text = String(m.content ?? "").trim();
|
|
3505
|
-
//
|
|
3455
|
+
// a message whose text is a PLACEHOLDER carries no information.
|
|
3506
3456
|
//
|
|
3507
3457
|
// `llm.ts` rewrites any assistant/tool message that has no usable text to
|
|
3508
3458
|
// the literal "(tool call)" or "(no content)". Those are display
|
|
@@ -3515,7 +3465,7 @@ export class Agent {
|
|
|
3515
3465
|
// follows, so dropping the placeholder loses nothing.
|
|
3516
3466
|
if (!text || PLACEHOLDER_TEXT.test(text))
|
|
3517
3467
|
continue;
|
|
3518
|
-
//
|
|
3468
|
+
// a window this small must not be spent on BOOKKEEPING. The real log
|
|
3519
3469
|
// showed a 6-slot window where two 23-char "(tool call)" placeholders and a
|
|
3520
3470
|
// 40-char "decision recorded to decisions.md" took half the slots, pushing
|
|
3521
3471
|
// out the reasoning a parent would need to judge the work. Harness
|
|
@@ -3531,7 +3481,7 @@ export class Agent {
|
|
|
3531
3481
|
}
|
|
3532
3482
|
// A generous cap, but not unbounded: one runaway turn must not blow up
|
|
3533
3483
|
// the parent's context. The old 1500 char clip cut findings in half —
|
|
3534
|
-
// a review's conclusions routinely live past that mark
|
|
3484
|
+
// a review's conclusions routinely live past that mark — and this
|
|
3535
3485
|
// text is bounded by 6 turns, so the worst case is ~120k chars.
|
|
3536
3486
|
recent.unshift(line.slice(0, 20_000));
|
|
3537
3487
|
}
|
|
@@ -3549,7 +3499,7 @@ export class Agent {
|
|
|
3549
3499
|
event: "audit-started",
|
|
3550
3500
|
verify: this.goal.verify.slice(0, 2000),
|
|
3551
3501
|
});
|
|
3552
|
-
//
|
|
3502
|
+
// number the attempts — the final carries the attempt that approved it
|
|
3553
3503
|
this.auditAttempts++;
|
|
3554
3504
|
try {
|
|
3555
3505
|
const auditPrompt = `You are an independent completion AUDITOR (not the worker). Decide whether the goal is genuinely complete.\n\n` +
|
|
@@ -3563,7 +3513,7 @@ export class Agent {
|
|
|
3563
3513
|
{ role: "user", content: auditPrompt },
|
|
3564
3514
|
], []);
|
|
3565
3515
|
const text = String(res.message.content ?? "");
|
|
3566
|
-
//
|
|
3516
|
+
// a reply that is NOT a verdict must not be read as a rejection.
|
|
3567
3517
|
//
|
|
3568
3518
|
// `/^APPROVED\b/i.test("")` is false, so an auditor that returned
|
|
3569
3519
|
// nothing — truncated, refused, or leaked provider tool-call markup —
|
|
@@ -3585,7 +3535,7 @@ export class Agent {
|
|
|
3585
3535
|
const usable = verdictLine.length > 0 && !PLACEHOLDER.test(verdictLine);
|
|
3586
3536
|
const decided = usable && /^(APPROVED|CHANGES-REQUIRED)\b/i.test(verdictLine);
|
|
3587
3537
|
if (!decided) {
|
|
3588
|
-
//
|
|
3538
|
+
// an unusable reply is NOT an approval. The old path failed
|
|
3589
3539
|
// OPEN — recorded the failure and marked the goal done anyway —
|
|
3590
3540
|
// so a verification contract was "satisfied" that nobody verified.
|
|
3591
3541
|
// Fail CLOSED instead: the goal stays active and the worker is
|
|
@@ -3616,7 +3566,7 @@ export class Agent {
|
|
|
3616
3566
|
}
|
|
3617
3567
|
const approved = /^APPROVED\b/i.test(verdictLine);
|
|
3618
3568
|
const feedback = verdictLine.replace(/^(APPROVED|CHANGES-REQUIRED)\s*[:—-]?\s*/i, "").trim();
|
|
3619
|
-
//
|
|
3569
|
+
// storing the literal "(no detail)" made the UI draw a card
|
|
3620
3570
|
// whose whole content was the absence of a reason, and that same
|
|
3621
3571
|
// string landed in goal.md for the right panel. An empty string is
|
|
3622
3572
|
// the honest value: the auditor returned a verdict and no reason,
|
|
@@ -3641,7 +3591,7 @@ export class Agent {
|
|
|
3641
3591
|
};
|
|
3642
3592
|
}
|
|
3643
3593
|
else {
|
|
3644
|
-
//
|
|
3594
|
+
// the rejection survives in memory so the eventual approved
|
|
3645
3595
|
// final can name what the first attempt was told
|
|
3646
3596
|
this.lastRejectedAudit = { feedback, attempt: this.auditAttempts };
|
|
3647
3597
|
/**
|
|
@@ -3658,7 +3608,7 @@ export class Agent {
|
|
|
3658
3608
|
// over buildMessages() + an audit prompt), so it was never in
|
|
3659
3609
|
// `this.messages` and must not come back through a restore: doing so
|
|
3660
3610
|
// injected an assistant turn that answers nothing into the model's
|
|
3661
|
-
// context, which providers answer with a 200 and no choices
|
|
3611
|
+
// context, which providers answer with a 200 and no choices.
|
|
3662
3612
|
// The rejection feedback reaches the agent as a real prompt below.
|
|
3663
3613
|
await this.log.append("message", this.currentSession, this.currentBranch, {
|
|
3664
3614
|
role: "assistant",
|
|
@@ -3669,18 +3619,18 @@ export class Agent {
|
|
|
3669
3619
|
});
|
|
3670
3620
|
if (!approved) {
|
|
3671
3621
|
this.consecutiveAuditRejects++;
|
|
3672
|
-
//
|
|
3622
|
+
// the rejection survives in memory so the eventual approved
|
|
3673
3623
|
// final can name what the first attempt was told
|
|
3674
3624
|
this.lastRejectedAudit = { feedback, attempt: this.auditAttempts };
|
|
3675
3625
|
// hand the gaps back to the worker as its next instruction.
|
|
3676
|
-
//
|
|
3626
|
+
// with the "(no detail)" placeholder gone, an empty verdict
|
|
3677
3627
|
// would leave this prompt saying "address these gaps" and then
|
|
3678
3628
|
// naming none — so restate the contract as the thing to re-check.
|
|
3679
3629
|
const gaps = feedback.trim()
|
|
3680
3630
|
? feedback.slice(0, 2000)
|
|
3681
3631
|
: `The auditor returned no specific gaps. Re-read the verification contract above and re-run it yourself, item by item, before finishing again:\n\n${this.goal.verify?.slice(0, 2000) || this.goal.text.slice(0, 2000)}`;
|
|
3682
3632
|
const retryText = `[harness] The completion audit REJECTED this finish. Address these gaps, then finish again with goalComplete=true:\n\n${gaps}`;
|
|
3683
|
-
//
|
|
3633
|
+
// counted above (consecutiveAuditRejects++ at the verdict) so
|
|
3684
3634
|
// a model that cannot satisfy the auditor cannot loop forever — the
|
|
3685
3635
|
// retry prompt is queued only while the bound is NOT yet reached,
|
|
3686
3636
|
// so the loop's cap break strands nothing (a prompt queued AT the
|
|
@@ -3694,7 +3644,7 @@ export class Agent {
|
|
|
3694
3644
|
text: retryText,
|
|
3695
3645
|
});
|
|
3696
3646
|
}
|
|
3697
|
-
//
|
|
3647
|
+
// RETURN before the final message is written.
|
|
3698
3648
|
//
|
|
3699
3649
|
// Falling through emitted `final: true` while the goal was still
|
|
3700
3650
|
// active — and that is the event onChildEvent forwards to the
|
|
@@ -3710,7 +3660,7 @@ export class Agent {
|
|
|
3710
3660
|
}
|
|
3711
3661
|
}
|
|
3712
3662
|
catch (err) {
|
|
3713
|
-
//
|
|
3663
|
+
// an auditor that THROWS is not an approval either. Same
|
|
3714
3664
|
// fail-closed treatment as a no-verdict reply: active goal, bounded
|
|
3715
3665
|
// self-verify retries, then a loud stop for the operator.
|
|
3716
3666
|
this.auditUnavailableStreak++;
|
|
@@ -3740,7 +3690,7 @@ export class Agent {
|
|
|
3740
3690
|
await this.appendFinalMessage(args);
|
|
3741
3691
|
}
|
|
3742
3692
|
/**
|
|
3743
|
-
*
|
|
3693
|
+
* the retry prompt for an audit that could not produce a verdict.
|
|
3744
3694
|
* Carries a real instruction (unlike a reason-less rejection — #90), so the
|
|
3745
3695
|
* worker re-checks the contract itself instead of being told to fix nothing.
|
|
3746
3696
|
*/
|
|
@@ -3760,7 +3710,7 @@ export class Agent {
|
|
|
3760
3710
|
async appendFinalMessage(args) {
|
|
3761
3711
|
const recent = await this.captureRecentTurns();
|
|
3762
3712
|
/**
|
|
3763
|
-
*
|
|
3713
|
+
* an APPROVED finish after a REJECTION must describe the WHOLE task.
|
|
3764
3714
|
*
|
|
3765
3715
|
* `captureRecentTurns()` reads the last six meaningful messages, which after a
|
|
3766
3716
|
* changes-required verdict is exactly the RETRY — so the parent was told about the last few
|
|
@@ -3813,7 +3763,7 @@ export class Agent {
|
|
|
3813
3763
|
this.turnsSinceProgress >= this.opts.progressMaxQuietTurns;
|
|
3814
3764
|
if (!elapsedOk || !activityOk)
|
|
3815
3765
|
return; // stalling provider → don't waste a turn asking
|
|
3816
|
-
//
|
|
3766
|
+
// remember that this boundary already carries an instruction, so the
|
|
3817
3767
|
// auto-continue nudge can stand down instead of pairing with it.
|
|
3818
3768
|
this.progressRequestedThisRound = true;
|
|
3819
3769
|
this.lastProgressAt = Date.now();
|
|
@@ -3852,7 +3802,6 @@ export class Agent {
|
|
|
3852
3802
|
*
|
|
3853
3803
|
* This loop used to answer `"progress recorded"` to whatever the model called, so a `bash`
|
|
3854
3804
|
* invocation came back with the text "progress recorded" and `durationMs: 0` — it never ran.
|
|
3855
|
-
* MEASURED in this session (seq 62247/62248): the assistant turn carried exactly one tool
|
|
3856
3805
|
* call, `bash <npm view polling loop>`, and its result was `"progress recorded"`, while the
|
|
3857
3806
|
* very next `progress` row read "(no report produced)". The command's real output appeared
|
|
3858
3807
|
* only on the NEXT turn, which is what made it look like a stray duplicate.
|
|
@@ -3938,7 +3887,7 @@ export class Agent {
|
|
|
3938
3887
|
*/
|
|
3939
3888
|
async answerMeta(call, content) {
|
|
3940
3889
|
// one tool_call gets ONE answer: the finish path answers before the audit
|
|
3941
|
-
//
|
|
3890
|
+
// AND at round end — a second answerMeta for the same id would push
|
|
3942
3891
|
// a duplicate `tool` message AND a duplicate log row, and strict
|
|
3943
3892
|
// OpenAI-compatible providers reject two responses for one call with a 400.
|
|
3944
3893
|
if (this.messages.some((m) => m.role === "tool" && m.tool_call_id === call.id))
|
|
@@ -3962,28 +3911,14 @@ export class Agent {
|
|
|
3962
3911
|
});
|
|
3963
3912
|
}
|
|
3964
3913
|
/**
|
|
3965
|
-
* Stage 1 of context management
|
|
3966
|
-
*
|
|
3967
|
-
*
|
|
3968
|
-
* protected so current work never loses its footing.
|
|
3969
|
-
*
|
|
3970
|
-
* WHEN it may run is the subtle part. It used to fire at `budget * 0.6`, and
|
|
3971
|
-
* because the budget is itself 75% of the model's window that meant clipping
|
|
3972
|
-
* history at **45% of the real window** — well before the auto-compact trigger at
|
|
3973
|
-
* 75%, i.e. while a quarter of the window was still free. The operator's report:
|
|
3974
|
-
* "compactで最初に過去履歴を落としてるけど…25%余ってるから多分あまりそれする必要ない".
|
|
3975
|
-
*
|
|
3976
|
-
* Pruning is destructive in a way compaction is not: a clipped tool result is GONE
|
|
3977
|
-
* from the model's context (the log keeps it, but the model cannot see it without
|
|
3978
|
-
* re-issuing the call), so doing it early trades real information for room that is
|
|
3979
|
-
* not needed yet. It is now a PRE-STEP OF COMPACTION — called from `maybeCompact()`
|
|
3980
|
-
* only once that pass has decided it is actually over budget — plus a margin so a
|
|
3981
|
-
* mid-size context is still tidy. `PRUNE_AT_SHARE` is a share of the BUDGET, and a
|
|
3982
|
-
* share just under 1 means "only when the next request would not fit".
|
|
3914
|
+
* Stage 1 of context management: clip OLD oversized tool outputs before paying for a full
|
|
3915
|
+
* summarise. They are the usual bulk and their details rarely matter once executed; the recent
|
|
3916
|
+
* window is protected so current work keeps its footing.
|
|
3983
3917
|
*
|
|
3984
|
-
*
|
|
3985
|
-
*
|
|
3986
|
-
* the
|
|
3918
|
+
* It runs as a PRE-STEP of `maybeCompact()`, only once that pass has decided the context is
|
|
3919
|
+
* actually over budget. Clipping is more destructive than summarising — the model cannot see a
|
|
3920
|
+
* clipped result again without re-issuing the call — so doing it while room is still free trades
|
|
3921
|
+
* real information for nothing.
|
|
3987
3922
|
*/
|
|
3988
3923
|
async maybePrune(force = false) {
|
|
3989
3924
|
const est = this.contextSizeForBudgeting(); // floored — see #73
|
|
@@ -3997,7 +3932,7 @@ export class Agent {
|
|
|
3997
3932
|
return 0;
|
|
3998
3933
|
// protect the recent tail (~half the budget in chars) from any pruning. Short mode
|
|
3999
3934
|
// protects a THIRD of it: a 2x-budget tail on a small window is most of the window,
|
|
4000
|
-
// so pruning would find nothing to do exactly when it is needed
|
|
3935
|
+
// so pruning would find nothing to do exactly when it is needed.
|
|
4001
3936
|
const protectChars = this.opts.shortContext ? Math.floor(budget * 1.2) : budget * 2;
|
|
4002
3937
|
let seen = 0;
|
|
4003
3938
|
let boundary = this.messages.length;
|
|
@@ -4063,7 +3998,7 @@ export class Agent {
|
|
|
4063
3998
|
// what would overflow the window; the char heuristic is only a fallback
|
|
4064
3999
|
// for providers that omit usage
|
|
4065
4000
|
const before = this.contextSizeForBudgeting(); // floored — see #73
|
|
4066
|
-
// SHORT-CONTEXT MODE
|
|
4001
|
+
// SHORT-CONTEXT MODE prunes INSIDE the budget, so it must run before the
|
|
4067
4002
|
// "are we over budget" return below — otherwise its lower threshold is unreachable
|
|
4068
4003
|
// and the mode does nothing at all. This is the one path where pruning deliberately
|
|
4069
4004
|
// spends information early, and it only exists because the operator asked for it.
|
|
@@ -4195,7 +4130,7 @@ export class Agent {
|
|
|
4195
4130
|
// progress is visible: announce the phase up front, then stream the
|
|
4196
4131
|
// summarizer's output as it generates (a long summarize used to look like
|
|
4197
4132
|
// the agent silently hung — hundreds of thousands of tokens take a while)
|
|
4198
|
-
//
|
|
4133
|
+
// the STATE must be established BEFORE the first notification — the
|
|
4199
4134
|
// emit used to precede `compactPhase` by an async log write, so the first
|
|
4200
4135
|
// progress event observed a snapshot with `compactPhase` still unset:
|
|
4201
4136
|
// "idle, not compacting, but a summarizing banner" from three paths at
|
|
@@ -4212,7 +4147,7 @@ export class Agent {
|
|
|
4212
4147
|
// failed compaction: isLive() keys off it, so a leaked "summarizing"
|
|
4213
4148
|
// pinned live=true forever (stop offered, never worked).
|
|
4214
4149
|
try {
|
|
4215
|
-
//
|
|
4150
|
+
// the START belongs on the timeline too. Only the right panel showed
|
|
4216
4151
|
// compaction, and it reports the *outcome*; a long summarize (hundreds of
|
|
4217
4152
|
// thousands of tokens) looks exactly like a hung agent on the timeline,
|
|
4218
4153
|
// because the first `context-compacted` event is only appended once the
|
|
@@ -4252,7 +4187,7 @@ export class Agent {
|
|
|
4252
4187
|
bus.emit("update", {
|
|
4253
4188
|
kind: "llm-delta",
|
|
4254
4189
|
agentId: this.opts.id,
|
|
4255
|
-
//
|
|
4190
|
+
// the bubble is session-scoped, so the stream must say which session
|
|
4256
4191
|
sessionId: this.currentSession,
|
|
4257
4192
|
text: `[compact] ${text}`,
|
|
4258
4193
|
reasoning: "",
|
|
@@ -4353,7 +4288,7 @@ export class Agent {
|
|
|
4353
4288
|
// with nothing. On a short history floor(oldCount/2) can round to 0, and
|
|
4354
4289
|
// the old code then bailed out silently: compaction "ran", reported
|
|
4355
4290
|
// nothing, and the context stayed over budget, so the very next provider
|
|
4356
|
-
// call overflowed — the "unstable after compact" report
|
|
4291
|
+
// call overflowed — the "unstable after compact" report. Always drop
|
|
4357
4292
|
// at least one message, and say so.
|
|
4358
4293
|
const halfCut = this.safeCut(Math.max(1, Math.floor(oldCount / 2)));
|
|
4359
4294
|
if (halfCut <= 0) {
|
|
@@ -4410,9 +4345,8 @@ export class Agent {
|
|
|
4410
4345
|
// recently read files so the model doesn't burn its first turns re-reading
|
|
4411
4346
|
// exactly what it had in context a moment ago. Budget: 3 files × 400 lines.
|
|
4412
4347
|
if (mode === "summarize") {
|
|
4413
|
-
//
|
|
4348
|
+
// the durable notes go back in HERE, and only here.
|
|
4414
4349
|
//
|
|
4415
|
-
// MEASURED before this: `set_memory` 181 times across every session but a
|
|
4416
4350
|
// `read_memory` AFTER writing only 13 times — the notes were written and
|
|
4417
4351
|
// never consulted, so the whole system was decoration. The prompt made it
|
|
4418
4352
|
// worse by claiming memory.md was injected when it never was.
|
|
@@ -4593,7 +4527,6 @@ export class Agent {
|
|
|
4593
4527
|
// and nothing at all about the call that produced the summary, so a shape that
|
|
4594
4528
|
// silently stopped sharing the prefix would look identical in the log.
|
|
4595
4529
|
//
|
|
4596
|
-
// MEASURED on the session that prompted this: the 12k-line history had 2342
|
|
4597
4530
|
// usage events, none of them the summarizer's.
|
|
4598
4531
|
if (res.usage) {
|
|
4599
4532
|
const u = res.usage;
|
|
@@ -4669,7 +4602,6 @@ export class Agent {
|
|
|
4669
4602
|
// found `wake === null`, did nothing, and the sleep it was meant to cancel
|
|
4670
4603
|
// then began on its own and ran to completion.
|
|
4671
4604
|
//
|
|
4672
|
-
// MEASURED (stop injected while `log.append("error-retry")` was in flight):
|
|
4673
4605
|
//
|
|
4674
4606
|
// PRE : status=running live=true (the stop lands here)
|
|
4675
4607
|
// POST: TIMEOUT after 6000ms status=error live=false
|
|
@@ -4771,7 +4703,7 @@ export class Agent {
|
|
|
4771
4703
|
// Where the fork leaves the source branch. Recorded on the event AND used
|
|
4772
4704
|
// to seed the new branch, so the two can never disagree.
|
|
4773
4705
|
const fromEvent = fromEventId ?? this.log.lastEventId(parentBranch);
|
|
4774
|
-
//
|
|
4706
|
+
// the fork event must be appended under the SOURCE branch. Appending it
|
|
4775
4707
|
// under the new one gave it parent:null (nothing had been written to that
|
|
4776
4708
|
// branch yet), so lineageOf() walked an empty chain and a restart rebuilt
|
|
4777
4709
|
// the fork with NO history at all — the same class of bug editPromptAt had,
|
|
@@ -4933,7 +4865,7 @@ function rebuildMessagesFrom(list) {
|
|
|
4933
4865
|
// `final` is the finish() summary; `operatorFacing` covers harness notes
|
|
4934
4866
|
// such as the completion audit verdict. Replaying either produced a
|
|
4935
4867
|
// history shape no live run emits, and a provider given that answers
|
|
4936
|
-
// 200 with zero choices
|
|
4868
|
+
// 200 with zero choices.
|
|
4937
4869
|
if (d.final === true || d.operatorFacing === true)
|
|
4938
4870
|
continue;
|
|
4939
4871
|
const role = d.role === "assistant" ? "assistant" : "user";
|
|
@@ -4944,7 +4876,7 @@ function rebuildMessagesFrom(list) {
|
|
|
4944
4876
|
// this turn, yet the restore replays it as a real utterance. sanitize()
|
|
4945
4877
|
// then rewrites blank assistant content to the literal "(no content)",
|
|
4946
4878
|
// so the agent is told it previously said a sentence it never said — a
|
|
4947
|
-
// history shape no live run produces
|
|
4879
|
+
// history shape no live run produces. A blank turn that DID call
|
|
4948
4880
|
// tools is legitimate and must stay, or its results are orphaned.
|
|
4949
4881
|
if (role === "assistant" && !content && !hasCalls)
|
|
4950
4882
|
continue;
|