zcode-acp-server 0.91.0 → 0.93.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/backend/client.d.ts +9 -0
- package/dist/backend/client.d.ts.map +1 -1
- package/dist/backend/client.js +31 -0
- package/dist/backend/client.js.map +1 -1
- package/dist/backend/listener.d.ts +26 -0
- package/dist/backend/listener.d.ts.map +1 -1
- package/dist/backend/listener.js +61 -0
- package/dist/backend/listener.js.map +1 -1
- package/dist/code-fingerprint.json +2 -2
- package/dist/config/account-provider.d.ts +64 -2
- package/dist/config/account-provider.d.ts.map +1 -1
- package/dist/config/account-provider.js +10 -4
- package/dist/config/account-provider.js.map +1 -1
- package/dist/config/model-cache.d.ts.map +1 -1
- package/dist/config/model-cache.js +5 -6
- package/dist/config/model-cache.js.map +1 -1
- package/dist/config/options.d.ts +25 -5
- package/dist/config/options.d.ts.map +1 -1
- package/dist/config/options.js +36 -8
- package/dist/config/options.js.map +1 -1
- package/dist/config/registry-context-window.d.ts +53 -0
- package/dist/config/registry-context-window.d.ts.map +1 -0
- package/dist/config/registry-context-window.js +305 -0
- package/dist/config/registry-context-window.js.map +1 -0
- package/dist/config/reply-language.d.ts +18 -0
- package/dist/config/reply-language.d.ts.map +1 -0
- package/dist/config/reply-language.js +35 -0
- package/dist/config/reply-language.js.map +1 -0
- package/dist/config/user-config.d.ts +13 -0
- package/dist/config/user-config.d.ts.map +1 -1
- package/dist/config/user-config.js +11 -0
- package/dist/config/user-config.js.map +1 -1
- package/dist/config/workflow-gate.d.ts +39 -21
- package/dist/config/workflow-gate.d.ts.map +1 -1
- package/dist/config/workflow-gate.js +45 -29
- package/dist/config/workflow-gate.js.map +1 -1
- package/dist/handlers/background-tasks.d.ts +36 -0
- package/dist/handlers/background-tasks.d.ts.map +1 -1
- package/dist/handlers/background-tasks.js +125 -12
- package/dist/handlers/background-tasks.js.map +1 -1
- package/dist/handlers/dispatch.js +9 -10
- package/dist/handlers/dispatch.js.map +1 -1
- package/dist/handlers/extensions.d.ts.map +1 -1
- package/dist/handlers/extensions.js +8 -2
- package/dist/handlers/extensions.js.map +1 -1
- package/dist/handlers/session.d.ts +12 -0
- package/dist/handlers/session.d.ts.map +1 -1
- package/dist/handlers/session.js +316 -65
- package/dist/handlers/session.js.map +1 -1
- package/dist/i18n.d.ts +3 -0
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +2 -0
- package/dist/i18n.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/dist/remote/settings-endpoint.d.ts.map +1 -1
- package/dist/remote/settings-endpoint.js +64 -11
- package/dist/remote/settings-endpoint.js.map +1 -1
- package/dist/server.d.ts +18 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +29 -14
- package/dist/server.js.map +1 -1
- package/dist/settings/workflow.d.ts +5 -4
- package/dist/settings/workflow.d.ts.map +1 -1
- package/dist/settings/workflow.js +5 -4
- package/dist/settings/workflow.js.map +1 -1
- package/dist/translators/event-translator.d.ts +25 -0
- package/dist/translators/event-translator.d.ts.map +1 -1
- package/dist/translators/event-translator.js +95 -4
- package/dist/translators/event-translator.js.map +1 -1
- package/dist/workflow/quota-resume.d.ts.map +1 -1
- package/dist/workflow/quota-resume.js +6 -5
- package/dist/workflow/quota-resume.js.map +1 -1
- package/docs/BACKLOG.md +100 -0
- package/package.json +1 -1
package/dist/handlers/session.js
CHANGED
|
@@ -21,7 +21,7 @@ import { backendCapabilities } from "../backend/adapter.js";
|
|
|
21
21
|
import { EventStreamListener, TurnMonitor } from "../backend/listener.js";
|
|
22
22
|
import { disallowedToolList } from "../backend/resolve.js";
|
|
23
23
|
import { resolveReal } from "../backend/sandbox.js";
|
|
24
|
-
import { buildModes, buildConfigOptions, buildInitialConfigOptions, defaultModelCandidates, defaultModelRef, formatModelValue, isModelUsable, loadAllModels,
|
|
24
|
+
import { buildModes, buildConfigOptions, buildInitialConfigOptions, defaultModelCandidates, defaultModelRef, formatModelValue, isModelUsable, loadAllModels, modelRetired, parseModelValue, rememberModelChoice, usageWindowSize, } from "../config/options.js";
|
|
25
25
|
import { currentModelCached, emitInitialUsage } from "../config/model-cache.js";
|
|
26
26
|
import { forceRefreshQuota, scheduleQuotaDockBackstop, startQuotaRefresher, } from "../quota/live.js";
|
|
27
27
|
import { warmStartPlanVerdict } from "../quota/startplan.js";
|
|
@@ -714,6 +714,7 @@ function emitBootUsageUpdate(server, acpSid) {
|
|
|
714
714
|
try {
|
|
715
715
|
const zcodeSid = server.resolveSid(acpSid);
|
|
716
716
|
let used = 0;
|
|
717
|
+
let backendSize;
|
|
717
718
|
if (zcodeSid) {
|
|
718
719
|
const backend = await server.ensureBackend();
|
|
719
720
|
const resp = await backend.request(server.nextId(), "session/read",
|
|
@@ -725,6 +726,7 @@ function emitBootUsageUpdate(server, acpSid) {
|
|
|
725
726
|
// consumption) for the meter — boot shows size first, used stays 0
|
|
726
727
|
// until the backend reports real occupancy.
|
|
727
728
|
used = proj?.contextUsed ?? 0;
|
|
729
|
+
backendSize = proj?.contextWindow;
|
|
728
730
|
}
|
|
729
731
|
const fallback = defaultModelRef();
|
|
730
732
|
let providerId = fallback.providerId;
|
|
@@ -732,10 +734,11 @@ function emitBootUsageUpdate(server, acpSid) {
|
|
|
732
734
|
if (zcodeSid) {
|
|
733
735
|
({ providerId, modelId } = parseModelValue(await currentModelCached(server, zcodeSid)));
|
|
734
736
|
}
|
|
737
|
+
// The same context-window ladder as every other usage_update.
|
|
735
738
|
await sendSessionUpdate(cx, acpSid, {
|
|
736
739
|
sessionUpdate: "usage_update",
|
|
737
740
|
used,
|
|
738
|
-
size:
|
|
741
|
+
size: usageWindowSize(providerId, modelId, backendSize),
|
|
739
742
|
});
|
|
740
743
|
}
|
|
741
744
|
catch (e) {
|
|
@@ -2251,6 +2254,19 @@ export async function runOneTurn(server, opts) {
|
|
|
2251
2254
|
if (sendAttempt > 1 || (cancelledRecently && !drainRan)) {
|
|
2252
2255
|
differ.markSeen(await fetchMessagesSinceAnchor(server, zcodeSid, differ.historyAnchor));
|
|
2253
2256
|
}
|
|
2257
|
+
// A backend-owned follow-up turn (a finished background task's
|
|
2258
|
+
// notification turn) can END while this send was busy-retrying:
|
|
2259
|
+
// with no preempt/cancel the attribution gate below is unarmed,
|
|
2260
|
+
// so the finished turn's queued tail would be translated as THIS
|
|
2261
|
+
// prompt's output (its turn.completed flipping turnDone). Cut the
|
|
2262
|
+
// queue through that turn's terminal. Self-limiting, hence run on
|
|
2263
|
+
// EVERY accepted send — it also closes the narrow window where a
|
|
2264
|
+
// follow-up turn ends between the subscribe and a first-attempt
|
|
2265
|
+
// accept.
|
|
2266
|
+
const droppedBacklog = listener.dropBacklogBeforeOwnTurn();
|
|
2267
|
+
if (droppedBacklog > 0) {
|
|
2268
|
+
log(` [send] dropped ${droppedBacklog} backlog events of a finished follow-up turn`);
|
|
2269
|
+
}
|
|
2254
2270
|
// From this moment the turn may own a running generation —
|
|
2255
2271
|
// stopBackendTurn's compaction guard no longer spares it.
|
|
2256
2272
|
turn.sendAccepted = true;
|
|
@@ -2382,6 +2398,21 @@ export async function runOneTurn(server, opts) {
|
|
|
2382
2398
|
return result;
|
|
2383
2399
|
}
|
|
2384
2400
|
catch (e) {
|
|
2401
|
+
// Held prompt chain: the ORIGINAL prompt was already delivered and
|
|
2402
|
+
// its reply is in the context (primaryDone = the first backend turn
|
|
2403
|
+
// of this prompt reached its terminal). A failure of an ADOPTED
|
|
2404
|
+
// follow-up turn — or a backend loss while holding — must NOT
|
|
2405
|
+
// respawn+resend and must NOT re-enter the send ladder: upstream
|
|
2406
|
+
// does not re-deliver a failed follow-up either. One notice, then a
|
|
2407
|
+
// normal end_turn. Goal-loop rounds keep throwing so the driver
|
|
2408
|
+
// pauses as today; a cancelled turn keeps propagating as today.
|
|
2409
|
+
if (turn.primaryDone && !turn.cancelled && e instanceof TurnFailedError) {
|
|
2410
|
+
if (turn.goalLoop)
|
|
2411
|
+
throw turnFailureRequestError(e);
|
|
2412
|
+
warn(`held prompt: adopted follow-up turn failed (${formatTurnError(e.turnError)}); keeping the session usable`);
|
|
2413
|
+
await sendTextChunk(cx, acpSid, messages().heldFollowUpFailed, randomUUID());
|
|
2414
|
+
return { stopReason: "end_turn" };
|
|
2415
|
+
}
|
|
2385
2416
|
// Backend lost (process died / storage closed mid-turn): recover by
|
|
2386
2417
|
// respawning the backend and reloading the session, then retry the
|
|
2387
2418
|
// turn. The session file is intact — only the process is gone.
|
|
@@ -3815,6 +3846,26 @@ export function turnResult(translator, stopReason) {
|
|
|
3815
3846
|
_meta: { zcode: { usage: extras } },
|
|
3816
3847
|
};
|
|
3817
3848
|
}
|
|
3849
|
+
/**
|
|
3850
|
+
* Quiet grace after the last outstanding subagent work cleared before a held
|
|
3851
|
+
* prompt turn ends its chain: a follow-up backend turn starting inside the
|
|
3852
|
+
* window is still adopted; past it the prompt completes normally. Exported
|
|
3853
|
+
* for tests (the chain tests assert against it).
|
|
3854
|
+
*/
|
|
3855
|
+
export const HELD_PROMPT_GRACE_MS = 2_000;
|
|
3856
|
+
/**
|
|
3857
|
+
* Hold-window heartbeat cadence: re-emits `in_progress` for the outstanding
|
|
3858
|
+
* `bg_*` cards and polls the subagent roster (the stale-outstanding safety
|
|
3859
|
+
* net ticks on the same beat). Clients enforce ~300s idle deadlines, so 60s
|
|
3860
|
+
* keeps them alive. Module-level so tests can shorten it — the safety net
|
|
3861
|
+
* needs two beats and no chain test can wait 2 minutes. Test-only mutation
|
|
3862
|
+
* via {@link setHeldPromptHeartbeatMsForTests}.
|
|
3863
|
+
*/
|
|
3864
|
+
let heldPromptHeartbeatMs = 60_000;
|
|
3865
|
+
/** @internal Test seam — hermetic hold timing without fake timers. */
|
|
3866
|
+
export function setHeldPromptHeartbeatMsForTests(ms) {
|
|
3867
|
+
heldPromptHeartbeatMs = ms ?? 60_000;
|
|
3868
|
+
}
|
|
3818
3869
|
/**
|
|
3819
3870
|
* Event-driven turn loop: translate zcode events via EventTranslator and
|
|
3820
3871
|
* dispatch each internal event to the ACP client. No-progress timeout is 120s
|
|
@@ -3884,6 +3935,40 @@ export async function runEventTurn(server, listener, monitor, differ, cx, acpSid
|
|
|
3884
3935
|
let turnStartedAt = null;
|
|
3885
3936
|
let thinkingHintSent = false;
|
|
3886
3937
|
const THINKING_HINT_DELAY_MS = 1200;
|
|
3938
|
+
// messageId base for the thinking hint — extended per chain turn so a
|
|
3939
|
+
// re-armed hint in an adopted turn never reuses the previous turn's id.
|
|
3940
|
+
let hintIdBase = chunkMsgId;
|
|
3941
|
+
// Held prompt chain: while `turn.holding`, this loop stays open BETWEEN
|
|
3942
|
+
// backend turns so the next one (the backend's follow-up for a finished
|
|
3943
|
+
// background subagent task) is ADOPTED into this same prompt turn. bgTasks
|
|
3944
|
+
// is the session-scoped BackgroundTaskListener — may be missing on partial
|
|
3945
|
+
// test fakes, which reads as "no outstanding work" (chain never holds).
|
|
3946
|
+
const bgTasks = server.backgroundListeners?.get(turn.zcodeSid);
|
|
3947
|
+
const skippedTurnIds = new Set();
|
|
3948
|
+
// When the last outstanding subagent work cleared (grace window open).
|
|
3949
|
+
let outstandingClearedAt = null;
|
|
3950
|
+
// Consecutive heartbeat rosters reporting ZERO running subagents while the
|
|
3951
|
+
// tracked state still says outstanding — two in a row trips the safety net.
|
|
3952
|
+
let emptyRosterStreak = 0;
|
|
3953
|
+
let lastHoldHeartbeatAt = Date.now();
|
|
3954
|
+
// Chain member index (0 = the primary turn) — drives per-turn message ids.
|
|
3955
|
+
let chainTurnSeq = 0;
|
|
3956
|
+
// Per-chain-member reset: the same per-turn counters a fresh loop start
|
|
3957
|
+
// would have, so an adopted turn behaves like a first turn (its own
|
|
3958
|
+
// thinking-hint window, its own no-progress clocks, fresh emitted flags).
|
|
3959
|
+
const chainResetCounters = () => {
|
|
3960
|
+
turnStartedAt = Date.now();
|
|
3961
|
+
thinkingHintSent = false;
|
|
3962
|
+
emittedText = false;
|
|
3963
|
+
emittedOutput = false;
|
|
3964
|
+
lastProtocolProgressAt = Date.now();
|
|
3965
|
+
nextNoProgressDecisionAt = lastProtocolProgressAt + NO_PROGRESS_MS;
|
|
3966
|
+
lastWatermarkAdvanceAt = Date.now();
|
|
3967
|
+
lastUpstreamProgressAt = lastProtocolProgressAt;
|
|
3968
|
+
lastStallCheck = Date.now();
|
|
3969
|
+
chainTurnSeq++;
|
|
3970
|
+
hintIdBase = `${chunkMsgId}_c${chainTurnSeq}`;
|
|
3971
|
+
};
|
|
3887
3972
|
// Sub-agent visibility (session/subagents RPC, 0.16.9): the model can run
|
|
3888
3973
|
// sub-agents for minutes behind a silent stream — the watermark keeps
|
|
3889
3974
|
// moving but the editor shows nothing. Piggyback on the stall-reconcile
|
|
@@ -3896,9 +3981,15 @@ export async function runEventTurn(server, listener, monitor, differ, cx, acpSid
|
|
|
3896
3981
|
let subagentEndedBaseline = null;
|
|
3897
3982
|
let subagentEndedLineSent = false;
|
|
3898
3983
|
const turnEpoch = Date.now();
|
|
3984
|
+
/**
|
|
3985
|
+
* Poll the backend's sub-agent roster once. Returns the RUNNING count, or
|
|
3986
|
+
* null when the probe is unavailable (old backend answers -32601, request
|
|
3987
|
+
* failure) — the held-loop safety net keys off the count and must never
|
|
3988
|
+
* fire on a broken probe.
|
|
3989
|
+
*/
|
|
3899
3990
|
const pollSubagentsOnce = async () => {
|
|
3900
3991
|
if (turn.cancelled)
|
|
3901
|
-
return;
|
|
3992
|
+
return null;
|
|
3902
3993
|
let result;
|
|
3903
3994
|
try {
|
|
3904
3995
|
const resp = await backend.request(server.nextId(), "session/subagents",
|
|
@@ -3908,11 +3999,11 @@ export async function runEventTurn(server, listener, monitor, differ, cx, acpSid
|
|
|
3908
3999
|
// always exact, only the per-status counts were truncated.
|
|
3909
4000
|
{ sessionId: turn.zcodeSid, endedLimit: 100 }, 8000);
|
|
3910
4001
|
if (resp.error || resp.result === undefined)
|
|
3911
|
-
return;
|
|
4002
|
+
return null;
|
|
3912
4003
|
result = resp.result;
|
|
3913
4004
|
}
|
|
3914
4005
|
catch {
|
|
3915
|
-
return;
|
|
4006
|
+
return null;
|
|
3916
4007
|
}
|
|
3917
4008
|
const roster = result;
|
|
3918
4009
|
const running = Array.isArray(roster.running) ? roster.running : [];
|
|
@@ -3952,6 +4043,7 @@ export async function runEventTurn(server, listener, monitor, differ, cx, acpSid
|
|
|
3952
4043
|
}
|
|
3953
4044
|
}
|
|
3954
4045
|
}
|
|
4046
|
+
return running.length;
|
|
3955
4047
|
};
|
|
3956
4048
|
const recordProtocolProgress = () => {
|
|
3957
4049
|
lastProtocolProgressAt = Date.now();
|
|
@@ -4017,75 +4109,134 @@ export async function runEventTurn(server, listener, monitor, differ, cx, acpSid
|
|
|
4017
4109
|
return turnResult(translator, "end_turn");
|
|
4018
4110
|
};
|
|
4019
4111
|
while (true) {
|
|
4020
|
-
if (
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4028
|
-
|
|
4029
|
-
|
|
4030
|
-
|
|
4112
|
+
if (turn.holding) {
|
|
4113
|
+
// HELD PROMPT: the last backend turn finished; the prompt stays open
|
|
4114
|
+
// for outstanding subagent work. No no-progress/stall decision may
|
|
4115
|
+
// fire here (the backend owns no turn of ours between chain turns).
|
|
4116
|
+
const outstanding = bgTasks?.subagentWorkOutstanding() ?? false;
|
|
4117
|
+
if (!outstanding) {
|
|
4118
|
+
if (outstandingClearedAt === null) {
|
|
4119
|
+
outstandingClearedAt = Date.now();
|
|
4120
|
+
log(" [hold] no outstanding subagent work; grace window open");
|
|
4121
|
+
}
|
|
4122
|
+
if (Date.now() - outstandingClearedAt >= HELD_PROMPT_GRACE_MS) {
|
|
4123
|
+
// Chain end: nothing adopted within the grace — the normal
|
|
4124
|
+
// completion path (mode emit + end_turn) runs exactly once here.
|
|
4125
|
+
log(" [hold] chain settled after grace; ending prompt turn");
|
|
4126
|
+
turn.primaryDone = true;
|
|
4127
|
+
await emitModeIfChanged(server, cx, acpSid, turn.zcodeSid);
|
|
4128
|
+
return turnResult(translator, "end_turn");
|
|
4129
|
+
}
|
|
4031
4130
|
}
|
|
4032
4131
|
else {
|
|
4033
|
-
|
|
4034
|
-
|
|
4035
|
-
|
|
4036
|
-
//
|
|
4037
|
-
//
|
|
4038
|
-
|
|
4039
|
-
|
|
4040
|
-
|
|
4041
|
-
|
|
4042
|
-
|
|
4132
|
+
outstandingClearedAt = null;
|
|
4133
|
+
if (Date.now() - lastHoldHeartbeatAt >= heldPromptHeartbeatMs) {
|
|
4134
|
+
lastHoldHeartbeatAt = Date.now();
|
|
4135
|
+
// Keep clients' ~300s idle deadlines fed: refresh the outstanding
|
|
4136
|
+
// bg_* cards, then poll the roster for the stale-outstanding net.
|
|
4137
|
+
for (const cardId of bgTasks?.outstandingSubagentCallIds() ?? []) {
|
|
4138
|
+
try {
|
|
4139
|
+
await sendSessionUpdate(cx, acpSid, {
|
|
4140
|
+
sessionUpdate: "tool_call_update",
|
|
4141
|
+
toolCallId: cardId,
|
|
4142
|
+
status: "in_progress",
|
|
4143
|
+
});
|
|
4144
|
+
}
|
|
4145
|
+
catch (e) {
|
|
4146
|
+
warn(`hold heartbeat card refresh failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
4147
|
+
}
|
|
4148
|
+
}
|
|
4149
|
+
const roster = await pollSubagentsOnce();
|
|
4150
|
+
if (roster === 0) {
|
|
4151
|
+
emptyRosterStreak++;
|
|
4152
|
+
if (emptyRosterStreak >= 2 && bgTasks?.subagentWorkOutstanding()) {
|
|
4153
|
+
// A dropped task-terminal would otherwise hold forever; the
|
|
4154
|
+
// listener's warn line is the audit trail.
|
|
4155
|
+
bgTasks.markOutstandingSubagentsTerminal();
|
|
4156
|
+
emptyRosterStreak = 0;
|
|
4157
|
+
}
|
|
4158
|
+
}
|
|
4159
|
+
else if (roster !== null) {
|
|
4160
|
+
// Live work or a recovered probe — the streak only counts
|
|
4161
|
+
// consecutive empty rosters; a broken probe never trips the net.
|
|
4162
|
+
emptyRosterStreak = 0;
|
|
4163
|
+
}
|
|
4164
|
+
if (!bgTasks?.subagentWorkOutstanding())
|
|
4165
|
+
outstandingClearedAt = Date.now();
|
|
4043
4166
|
}
|
|
4044
|
-
|
|
4045
|
-
|
|
4046
|
-
|
|
4047
|
-
|
|
4048
|
-
|
|
4049
|
-
|
|
4050
|
-
|
|
4167
|
+
}
|
|
4168
|
+
}
|
|
4169
|
+
if (!turn.holding) {
|
|
4170
|
+
if (Date.now() >= nextNoProgressDecisionAt) {
|
|
4171
|
+
if (listener.hasQueuedEvents()) {
|
|
4172
|
+
// An event that arrived exactly at the deadline is real protocol
|
|
4173
|
+
// progress. Consume it below before making any terminal decision.
|
|
4174
|
+
recordProtocolProgress();
|
|
4051
4175
|
}
|
|
4052
|
-
else if (
|
|
4053
|
-
//
|
|
4054
|
-
//
|
|
4055
|
-
|
|
4056
|
-
|
|
4057
|
-
log(` [stall] watermark frozen ${Math.round(frozenMs / 1000)}s; ending turn after delivered output`);
|
|
4058
|
-
return turnResult(translator, "end_turn");
|
|
4176
|
+
else if (turn.cancelled) {
|
|
4177
|
+
// Preserve the pre-existing bounded cancel behaviour. A stuck prompt
|
|
4178
|
+
// lock after stop must not keep a user-cancelled turn alive forever.
|
|
4179
|
+
void stopBackendTurn(server, turn.zcodeSid, turn);
|
|
4180
|
+
return turnResult(translator, "max_turn_requests");
|
|
4059
4181
|
}
|
|
4060
4182
|
else {
|
|
4061
|
-
const
|
|
4062
|
-
|
|
4063
|
-
|
|
4064
|
-
|
|
4183
|
+
const frozenMs = Date.now() - lastWatermarkAdvanceAt;
|
|
4184
|
+
const activeTools = [...translator.seenToolIds].filter((toolId) => !translator.finalToolIds.has(toolId)).length;
|
|
4185
|
+
if (activeTools > 0) {
|
|
4186
|
+
// A nonterminal foreground tool is direct evidence that the turn is
|
|
4187
|
+
// not complete, even when token/turn counters are quiet. In
|
|
4188
|
+
// particular, TaskOutput can legitimately span the generic stale
|
|
4189
|
+
// budget while the backend still owns the prompt. Keep forwarding
|
|
4190
|
+
// its state-bearing refreshes instead of inventing end_turn.
|
|
4191
|
+
log(` [stall] watermark frozen ${Math.round(frozenMs / 1000)}s with ${activeTools} active tool(s); deferring terminal decision`);
|
|
4192
|
+
nextNoProgressDecisionAt = Date.now() + NO_PROGRESS_MS;
|
|
4193
|
+
}
|
|
4194
|
+
else if (frozenMs < STALE_FREEZE_MS) {
|
|
4195
|
+
// The read watermark moved recently — direct evidence the backend is
|
|
4196
|
+
// still making progress (typically a sub-agent or slow tool working
|
|
4197
|
+
// behind a silent stream). Keep waiting; the 15s stall-reconcile
|
|
4198
|
+
// below keeps refreshing the watermark via session/read.
|
|
4199
|
+
log(` [stall] watermark advanced within the last ${Math.round(frozenMs / 1000)}s (activeTools=${activeTools}); deferring terminal decision`);
|
|
4200
|
+
nextNoProgressDecisionAt = Date.now() + NO_PROGRESS_MS;
|
|
4201
|
+
}
|
|
4202
|
+
else if (emittedText || emittedOutput) {
|
|
4203
|
+
// Watermark frozen past the budget and something was already
|
|
4204
|
+
// delivered — treat as a completed-but-terminal-event-lost turn
|
|
4205
|
+
// (never compress its context; the completion is inferred).
|
|
4065
4206
|
turn.stallRecovered = true;
|
|
4066
|
-
log(` [stall] watermark frozen ${Math.round(frozenMs / 1000)}s;
|
|
4207
|
+
log(` [stall] watermark frozen ${Math.round(frozenMs / 1000)}s; ending turn after delivered output`);
|
|
4067
4208
|
return turnResult(translator, "end_turn");
|
|
4068
4209
|
}
|
|
4069
|
-
|
|
4070
|
-
|
|
4071
|
-
|
|
4210
|
+
else {
|
|
4211
|
+
const reply = await fetchLastReply(server, turn.zcodeSid, differ);
|
|
4212
|
+
if (reply) {
|
|
4213
|
+
registerFetchedReply(translator, differ, reply);
|
|
4214
|
+
await sendTextChunk(cx, acpSid, reply.text, chunkMsgId);
|
|
4215
|
+
turn.stallRecovered = true;
|
|
4216
|
+
log(` [stall] watermark frozen ${Math.round(frozenMs / 1000)}s; recovered reply via session/messages`);
|
|
4217
|
+
return turnResult(translator, "end_turn");
|
|
4218
|
+
}
|
|
4219
|
+
log(` [stall] watermark frozen ${Math.round(frozenMs / 1000)}s with no output; stopping backend turn`);
|
|
4220
|
+
void stopBackendTurn(server, turn.zcodeSid, turn);
|
|
4221
|
+
return turnResult(translator, "max_turn_requests");
|
|
4222
|
+
}
|
|
4072
4223
|
}
|
|
4073
4224
|
}
|
|
4074
|
-
|
|
4075
|
-
|
|
4076
|
-
|
|
4077
|
-
|
|
4078
|
-
|
|
4079
|
-
|
|
4080
|
-
|
|
4081
|
-
|
|
4082
|
-
|
|
4083
|
-
|
|
4084
|
-
|
|
4085
|
-
|
|
4086
|
-
|
|
4087
|
-
|
|
4088
|
-
|
|
4225
|
+
// Drain + handle server→client requests (interaction/*). Refreshes the
|
|
4226
|
+
// no-progress timer when any are handled. Pass `turn` so interaction
|
|
4227
|
+
// requests become turn-cancel aware (user stop aborts pending popups).
|
|
4228
|
+
// Best-effort containment: a throw here would kill the turn loop (and the
|
|
4229
|
+
// prompt response with it); warn and keep draining instead.
|
|
4230
|
+
let handled = false;
|
|
4231
|
+
try {
|
|
4232
|
+
handled = await handleServerRequests(server, backend, cx, acpSid, turn);
|
|
4233
|
+
}
|
|
4234
|
+
catch (e) {
|
|
4235
|
+
warn(`handleServerRequests threw: ${e instanceof Error ? e.message : String(e)}`);
|
|
4236
|
+
}
|
|
4237
|
+
if (handled) {
|
|
4238
|
+
recordProtocolProgress();
|
|
4239
|
+
}
|
|
4089
4240
|
}
|
|
4090
4241
|
if (turn.cancelled) {
|
|
4091
4242
|
// Cancel requested: fire the stop (cancel()/preempt normally already
|
|
@@ -4119,6 +4270,12 @@ export async function runEventTurn(server, listener, monitor, differ, cx, acpSid
|
|
|
4119
4270
|
cause: { code: "ERR_INVALID_STATE", message: "reader dead" },
|
|
4120
4271
|
});
|
|
4121
4272
|
}
|
|
4273
|
+
if (turn.holding) {
|
|
4274
|
+
// Held prompt: no thinking hint, no stall reconciliation — the
|
|
4275
|
+
// backend owns no turn of ours between chain turns, so silence here
|
|
4276
|
+
// is just the wait for the next turn.started (or the grace expiry).
|
|
4277
|
+
continue;
|
|
4278
|
+
}
|
|
4122
4279
|
// Thinking-phase hint: if the turn has started but produced no output
|
|
4123
4280
|
// yet (no text/reasoning/tool streamed), and we've been silent longer
|
|
4124
4281
|
// than the threshold, emit a single "thinking" thought chunk so the
|
|
@@ -4134,7 +4291,7 @@ export async function runEventTurn(server, listener, monitor, differ, cx, acpSid
|
|
|
4134
4291
|
await sendSessionUpdate(cx, acpSid, {
|
|
4135
4292
|
sessionUpdate: "agent_thought_chunk",
|
|
4136
4293
|
content: { type: "text", text: messages().thinkingPlaceholder },
|
|
4137
|
-
messageId: `thinking_${
|
|
4294
|
+
messageId: `thinking_${hintIdBase}`,
|
|
4138
4295
|
});
|
|
4139
4296
|
}
|
|
4140
4297
|
// Stall reconciliation: probe authoritative status after 15s of silence.
|
|
@@ -4218,6 +4375,65 @@ export async function runEventTurn(server, listener, monitor, differ, cx, acpSid
|
|
|
4218
4375
|
if (ev.type === "turn.steerDrained") {
|
|
4219
4376
|
echoSteeredInputs(server, acpSid, ev.payload);
|
|
4220
4377
|
}
|
|
4378
|
+
if (turn.holding) {
|
|
4379
|
+
if (turn.cancelled) {
|
|
4380
|
+
// Cancelled while holding: drain without adopting — the head check
|
|
4381
|
+
// above ends the turn as cancelled on the next pass, and a turn
|
|
4382
|
+
// arriving after the user's stop must not re-arm this prompt.
|
|
4383
|
+
continue;
|
|
4384
|
+
}
|
|
4385
|
+
// HELD PROMPT event filter. Between chain turns the loop owns nothing,
|
|
4386
|
+
// so almost everything is drained and dropped WITHOUT translation
|
|
4387
|
+
// (mirrored subagent tool events included — the session-scoped
|
|
4388
|
+
// BackgroundTaskListener handles the task cards). Only a turn.started
|
|
4389
|
+
// can change the state: adopt it into this prompt, or skip it.
|
|
4390
|
+
const evTurnId = ev.turnId ?? ev.payload?.["turnId"] ?? "";
|
|
4391
|
+
if (ev.type === "turn.started") {
|
|
4392
|
+
const payload = ev.payload;
|
|
4393
|
+
const skip = payload?.executionKind === "controlOnly" ||
|
|
4394
|
+
// The manual /compact internal turn: a NON-background turn starting
|
|
4395
|
+
// while the compaction flag is set. Its id is remembered so it stays
|
|
4396
|
+
// skipped even after the flag clears mid-run.
|
|
4397
|
+
(!!evTurnId &&
|
|
4398
|
+
payload?.inputSource !== "background_task" &&
|
|
4399
|
+
server.autoCompactInFlight.has(turn.zcodeSid)) ||
|
|
4400
|
+
// A rewind-claimed replacement turn: the notification-forwarding
|
|
4401
|
+
// path owns its text; adopting it would render it twice.
|
|
4402
|
+
(!!evTurnId && bgTasks?.isForwardingTurn(evTurnId) === true);
|
|
4403
|
+
if (skip) {
|
|
4404
|
+
if (evTurnId)
|
|
4405
|
+
skippedTurnIds.add(evTurnId);
|
|
4406
|
+
log(` [hold] turn.started (${evTurnId.slice(-8) || "?"}) skipped while holding`);
|
|
4407
|
+
continue;
|
|
4408
|
+
}
|
|
4409
|
+
// ADOPT: this backend turn (background follow-up or a user-steered
|
|
4410
|
+
// turn) joins the prompt. The translator's armed adopt consumes the
|
|
4411
|
+
// turn.started; per-turn counters reset for the new chain member.
|
|
4412
|
+
turn.holding = false;
|
|
4413
|
+
skippedTurnIds.clear();
|
|
4414
|
+
outstandingClearedAt = null;
|
|
4415
|
+
emptyRosterStreak = 0;
|
|
4416
|
+
chainResetCounters();
|
|
4417
|
+
log(` [hold] adopted turn ${evTurnId.slice(-8) || "?"} into held prompt`);
|
|
4418
|
+
// Fall through: the turn.started capture below takes
|
|
4419
|
+
// foregroundExecutionId, translate() consumes the adopt, and the
|
|
4420
|
+
// turn runs the full existing path.
|
|
4421
|
+
}
|
|
4422
|
+
else if (ev.type === "turn.completed" || ev.type === "turn.failed") {
|
|
4423
|
+
if (evTurnId && skippedTurnIds.has(evTurnId)) {
|
|
4424
|
+
// Terminal of a skipped turn: drop it and prune the skip set.
|
|
4425
|
+
skippedTurnIds.delete(evTurnId);
|
|
4426
|
+
log(` [hold] skipped turn ${evTurnId.slice(-8)} terminal dropped`);
|
|
4427
|
+
}
|
|
4428
|
+
continue;
|
|
4429
|
+
}
|
|
4430
|
+
else if (evTurnId && skippedTurnIds.has(evTurnId)) {
|
|
4431
|
+
continue; // event of a skipped turn
|
|
4432
|
+
}
|
|
4433
|
+
else {
|
|
4434
|
+
continue; // everything else drains without translation
|
|
4435
|
+
}
|
|
4436
|
+
}
|
|
4221
4437
|
// Turn-attribution gate: before this turn's own turn.started arrives, any
|
|
4222
4438
|
// event is leftover from a prior turn (cancelled/preempted but still
|
|
4223
4439
|
// finalising) that landed in the queue while send was retrying on a busy
|
|
@@ -4237,7 +4453,11 @@ export async function runEventTurn(server, listener, monitor, differ, cx, acpSid
|
|
|
4237
4453
|
// a send is accepted only after the prior turn released the lock, so the
|
|
4238
4454
|
// residue can only arrive BEFORE this turn's turn.started. (A send that
|
|
4239
4455
|
// lands mid-generation instead is a steer whose input is dropped — the
|
|
4240
|
-
// turn.steerQueued guard above reports that at once.)
|
|
4456
|
+
// turn.steerQueued guard above reports that at once.) A follow-up turn
|
|
4457
|
+
// that already ENDED while the send was busy-retrying leaves no residue
|
|
4458
|
+
// for this gate — the send-accept path cuts its backlog through the
|
|
4459
|
+
// terminal (EventStreamListener.dropBacklogBeforeOwnTurn) — which is one
|
|
4460
|
+
// reason the gate stays unarmed without a preempt/cancel.
|
|
4241
4461
|
if (shouldDropEventForTurnAttribution(ev, translator.turnStarted, gateArmed)) {
|
|
4242
4462
|
continue;
|
|
4243
4463
|
}
|
|
@@ -4478,6 +4698,34 @@ export async function runEventTurn(server, listener, monitor, differ, cx, acpSid
|
|
|
4478
4698
|
}
|
|
4479
4699
|
await dispatchEvent(server, cx, acpSid, iev, chunkMsgId);
|
|
4480
4700
|
}
|
|
4701
|
+
// Held prompt chain: advance the differ anchor past this turn's
|
|
4702
|
+
// messages so the NEXT chain member's completion diff (scoped
|
|
4703
|
+
// afterMessageId: anchor) cannot replay them — the same re-baseline
|
|
4704
|
+
// the send-accept path performs across turns.
|
|
4705
|
+
differ.markSeen(snapshot.messages ?? []);
|
|
4706
|
+
if (bgTasks?.subagentWorkOutstanding()) {
|
|
4707
|
+
// HOLD: subagent-kind background work is outstanding — keep
|
|
4708
|
+
// session/prompt open for the backend's follow-up turn. Per-chain
|
|
4709
|
+
// resets + translator re-arm; emitModeIfChanged / turnResult wait
|
|
4710
|
+
// for the chain end (loop-top hold block, grace expiry) — an
|
|
4711
|
+
// adopted turn re-enters this block at ITS terminal instead.
|
|
4712
|
+
turn.primaryDone = true;
|
|
4713
|
+
turn.holding = true;
|
|
4714
|
+
differ.resetTurn();
|
|
4715
|
+
emittedText = false;
|
|
4716
|
+
emittedOutput = false;
|
|
4717
|
+
thinkingHintSent = false;
|
|
4718
|
+
turnStartedAt = null;
|
|
4719
|
+
lastProtocolProgressAt = Date.now();
|
|
4720
|
+
nextNoProgressDecisionAt = lastProtocolProgressAt + NO_PROGRESS_MS;
|
|
4721
|
+
lastWatermarkAdvanceAt = Date.now();
|
|
4722
|
+
lastUpstreamProgressAt = lastProtocolProgressAt;
|
|
4723
|
+
lastStallCheck = Date.now();
|
|
4724
|
+
translator.beginChainedTurn();
|
|
4725
|
+
log(" [hold] backend turn done; holding prompt for outstanding subagent work");
|
|
4726
|
+
continue;
|
|
4727
|
+
}
|
|
4728
|
+
turn.primaryDone = true;
|
|
4481
4729
|
// Mode reconciliation: an in-turn tool (EnterPlanMode/ExitPlanMode) can
|
|
4482
4730
|
// switch the session mode without the bridge intermediating, so no
|
|
4483
4731
|
// session/setMode notification fires. Re-read the authoritative mode and
|
|
@@ -4499,6 +4747,9 @@ export async function runEventTurn(server, listener, monitor, differ, cx, acpSid
|
|
|
4499
4747
|
* time — e.g. the main-branch turn auto-resumed after a compaction — which
|
|
4500
4748
|
* this send was steered into and which emits no new `turn.started`; dropping
|
|
4501
4749
|
* those events would silently swallow the whole turn's output in the UI.
|
|
4750
|
+
* A follow-up turn that already ENDED before the subscribe is handled
|
|
4751
|
+
* earlier instead: the send-accept path cuts its queued backlog through the
|
|
4752
|
+
* terminal (EventStreamListener.dropBacklogBeforeOwnTurn).
|
|
4502
4753
|
*/
|
|
4503
4754
|
export function shouldDropEventForTurnAttribution(ev, turnStarted, preempted) {
|
|
4504
4755
|
return !turnStarted && preempted && ev.type !== "turn.started";
|