dsh-taskbridge 0.0.0-stage → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +754 -0
- package/LICENSE +21 -0
- package/README.md +624 -3
- package/bin/dsh-delegate-codex-agent.js +115 -0
- package/bin/dsh-delegate-control.d.ts +90 -0
- package/bin/dsh-delegate-control.js +450 -0
- package/bin/dsh-delegate-mcp.d.ts +121 -0
- package/bin/dsh-delegate-mcp.js +273 -0
- package/codex/dsh-delegate.toml +245 -0
- package/cordis.patch.yml +6 -0
- package/docs/INTRODUCTION.md +15 -0
- package/docs/INTRODUCTION.zh.md +32 -0
- package/docs/auth-contract.md +138 -0
- package/docs/claude-code.md +31 -0
- package/docs/codex-integration.md +922 -0
- package/docs/contracts-stage-b.md +443 -0
- package/docs/conversation-placement.md +293 -0
- package/docs/plugin-market.md +30 -0
- package/docs/redaction-contract.md +127 -0
- package/docs/runtime-compatibility.md +220 -0
- package/docs/silent-wait.md +191 -0
- package/docs/taskbridge-upgrade.md +28 -0
- package/docs/taskdispatch-upgrade.md +25 -0
- package/docs/worker-permissions.md +347 -0
- package/docs/workspace-contract.md +538 -0
- package/icon.svg +1 -0
- package/lib/client.d.ts +118 -0
- package/lib/client.js +3232 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +135 -4
- package/src/auth/fence.js +361 -0
- package/src/auth/grants.js +789 -0
- package/src/client/api.js +2322 -0
- package/src/client/index.jsx +2333 -0
- package/src/client/styles.js +251 -0
- package/src/codex/installer.js +3260 -0
- package/src/codex/seam.js +429 -0
- package/src/codex/toml.js +784 -0
- package/src/config/defaults.js +164 -0
- package/src/config/redact.js +184 -0
- package/src/config/settings.js +629 -0
- package/src/config/store.js +186 -0
- package/src/config/validate.js +763 -0
- package/src/credentials/seam.js +202 -0
- package/src/http/execution-plane.js +454 -0
- package/src/http/respond.js +175 -0
- package/src/http/user-plane.js +1122 -0
- package/src/index.d.ts +332 -0
- package/src/index.js +657 -0
- package/src/jobs/activity.js +1008 -0
- package/src/jobs/engine.js +3609 -0
- package/src/jobs/history.js +1467 -0
- package/src/mcp/server.js +1820 -0
- package/src/mcp/wait.js +536 -0
- package/src/model/connectivity.js +371 -0
- package/src/model/discovery.js +582 -0
- package/src/model/native-catalog.js +68 -0
- package/src/model/openai-adapter.js +671 -0
- package/src/model/probe.js +264 -0
- package/src/model/providers.js +756 -0
- package/src/model/routing.js +321 -0
- package/src/review/preset.js +868 -0
- package/src/review/prompts.js +126 -0
- package/src/review/reviewer.js +933 -0
- package/src/runtime/agent-runner.js +1738 -0
- package/src/runtime/endpoint-discovery.js +118 -0
- package/src/runtime/permissions.js +1429 -0
- package/src/runtime/sandbox.js +358 -0
- package/src/runtime/session-placement.js +1103 -0
- package/src/workspace/audit.js +775 -0
- package/src/workspace/locks.js +167 -0
- package/src/workspace/preflight.js +424 -0
- package/src/workspace/worktrees.js +613 -0
|
@@ -0,0 +1,1008 @@
|
|
|
1
|
+
// Bounded activity bookkeeping for one running delegated task.
|
|
2
|
+
//
|
|
3
|
+
// This module answers exactly one question — "has this executor been silent, and
|
|
4
|
+
// for how long?" — and records the minimum needed to answer it. It is deliberately
|
|
5
|
+
// not a transcript, not a progress model and not a log:
|
|
6
|
+
//
|
|
7
|
+
// * **Only metadata is retained.** An event contributes a KIND, a COUNT and a
|
|
8
|
+
// timestamp. Reasoning text, assistant text, tool result bodies and tool
|
|
9
|
+
// arguments are read only far enough to decide *whether the event was
|
|
10
|
+
// non-empty*; nothing derived from them is stored, so no buffer here can grow
|
|
11
|
+
// with model output and nothing here can leak a transcript into a view,
|
|
12
|
+
// a history row or a diagnostic.
|
|
13
|
+
// * **The vocabulary is the harness's own.** The classified names are the
|
|
14
|
+
// durable `SessionEventMap` types of `@deepseek-ai/dsh-session` (`step/start`,
|
|
15
|
+
// `assistant/message`, `tool/call`, `tool/result`, plus the turn/step/usage
|
|
16
|
+
// boundaries), the two stream-chunk types `@deepseek-ai/dsh-llm` emits
|
|
17
|
+
// (`text-delta`, `reasoning-delta`), and the nested streaming envelopes the
|
|
18
|
+
// runner accepts (`message/part`, `assistant/delta` wrapping a delta). An
|
|
19
|
+
// event this module does not recognise is `unrelated`, which by contract never
|
|
20
|
+
// resets idleness.
|
|
21
|
+
// * **Only real activity resets the clock.** A non-empty output or reasoning
|
|
22
|
+
// delta — top-level OR nested inside a streaming envelope — an assistant
|
|
23
|
+
// message carrying text or reasoning, a step that actually started, a native
|
|
24
|
+
// tool call and a tool result are activity. Empty deltas, bookkeeping events,
|
|
25
|
+
// connection heartbeats and result polling are NOT: if they reset the clock, a
|
|
26
|
+
// hung executor would look busy forever and the whole silent-wait mechanism
|
|
27
|
+
// would never fire.
|
|
28
|
+
// * **Silence, not duration, raises attention.** An open tool call changes how the
|
|
29
|
+
// silence is DESCRIBED (`waitingOn: 'tool'`, with the call's elapsed span and a
|
|
30
|
+
// `tool-running` self-check verdict) but not WHETHER it counts: a tool that
|
|
31
|
+
// emits nothing for five minutes gets the self-check and for ten minutes gets
|
|
32
|
+
// attention, exactly like any other silent executor. Treating an open call as
|
|
33
|
+
// proof of progress would hide a genuinely hung tool. Nothing here ever fails,
|
|
34
|
+
// cancels or restarts a run because of duration.
|
|
35
|
+
//
|
|
36
|
+
// The clock is injected (`now`) so tests can simulate twenty minutes of real
|
|
37
|
+
// progress deterministically instead of sleeping.
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* How one event kind is classified for idleness.
|
|
41
|
+
*
|
|
42
|
+
* `activity` — the executor demonstrably produced something; resets the idle clock.
|
|
43
|
+
* `structure` — a lifecycle boundary (turn/step boundaries, usage, an empty
|
|
44
|
+
* delta). Observed and counted, never treated as progress.
|
|
45
|
+
* `unrelated` — anything this build does not classify, including heartbeat and
|
|
46
|
+
* polling traffic on an unrelated channel.
|
|
47
|
+
*/
|
|
48
|
+
export const ACTIVITY_KINDS = Object.freeze({
|
|
49
|
+
activity: 'activity',
|
|
50
|
+
structure: 'structure',
|
|
51
|
+
unrelated: 'unrelated',
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
/** How many distinct event types one summary keeps counts for. */
|
|
55
|
+
const MAX_KIND_COUNTS = 32;
|
|
56
|
+
|
|
57
|
+
/** Bound on a recorded tool name or call id; they are identifiers, not content. */
|
|
58
|
+
const MAX_IDENTIFIER_CHARS = 200;
|
|
59
|
+
|
|
60
|
+
/** Settled call ids remembered so a completion can be matched to its start. */
|
|
61
|
+
const MAX_TRACKED_CALL_IDS = 64;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Session event types that are PROGRESS, keyed to the evidence they carry.
|
|
65
|
+
*
|
|
66
|
+
* These are `SessionEventMap` members of `@deepseek-ai/dsh-session` (and, for the
|
|
67
|
+
* two delta names, `StreamChunk` types of `@deepseek-ai/dsh-llm`, which reach the
|
|
68
|
+
* same listener). Whether a given event is *genuine* progress is decided by
|
|
69
|
+
* {@link observeProgress}: several of these can arrive carrying nothing.
|
|
70
|
+
*/
|
|
71
|
+
const ACTIVITY_EVENT_TYPES = Object.freeze({
|
|
72
|
+
// The loop streamed model output. Genuine only when the delta is non-empty.
|
|
73
|
+
'text-delta': 'output-delta',
|
|
74
|
+
'reasoning-delta': 'reasoning-delta',
|
|
75
|
+
// Nested streaming envelopes: `data.delta` carries the same chunk shape. The
|
|
76
|
+
// runner accepts both spellings, so both must be classified — treating them as
|
|
77
|
+
// structural would hide every token of a run that streams nested.
|
|
78
|
+
'message/part': 'output-delta',
|
|
79
|
+
'assistant/delta': 'output-delta',
|
|
80
|
+
// The settled assistant message for one step. Genuine only when it carries text
|
|
81
|
+
// or reasoning; an empty message is a structural event.
|
|
82
|
+
'assistant/message': 'assistant-message',
|
|
83
|
+
// A step actually opened: the model was called.
|
|
84
|
+
'step/start': 'model-step',
|
|
85
|
+
// The model requested one tool invocation.
|
|
86
|
+
'tool/call': 'tool-call',
|
|
87
|
+
// One tool call settled with a model-facing result.
|
|
88
|
+
'tool/result': 'tool-result',
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Session event types that only ever open, close or describe a step.
|
|
93
|
+
*
|
|
94
|
+
* `assistant/message` is handled separately: it is progress only when it carries
|
|
95
|
+
* content, which is the difference between the settled answer and an empty message.
|
|
96
|
+
*/
|
|
97
|
+
const STRUCTURE_EVENT_TYPES = Object.freeze(new Set([
|
|
98
|
+
'turn/start',
|
|
99
|
+
'turn/end',
|
|
100
|
+
'step/end',
|
|
101
|
+
'assistant/attempt',
|
|
102
|
+
'usage',
|
|
103
|
+
]));
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Classify one native event.
|
|
107
|
+
*
|
|
108
|
+
* @param {unknown} event - the object handed to `request.onEvent`.
|
|
109
|
+
* @returns {{ kind: string, type: string | null, label: string, activity: boolean, tool: object | null }} classification.
|
|
110
|
+
*/
|
|
111
|
+
export function classifyActivityEvent(event) {
|
|
112
|
+
const unrelated = { kind: ACTIVITY_KINDS.unrelated, type: null, label: 'unrelated', activity: false, tool: null };
|
|
113
|
+
if (event === null || typeof event !== 'object') return unrelated;
|
|
114
|
+
const type = typeof event.type === 'string' ? event.type : null;
|
|
115
|
+
if (type === null) return unrelated;
|
|
116
|
+
|
|
117
|
+
const progress = ACTIVITY_EVENT_TYPES[type];
|
|
118
|
+
if (progress !== undefined) {
|
|
119
|
+
const observed = observeProgress(type, event);
|
|
120
|
+
return {
|
|
121
|
+
kind: observed.activity ? ACTIVITY_KINDS.activity : ACTIVITY_KINDS.structure,
|
|
122
|
+
type,
|
|
123
|
+
label: observed.activity ? progress : `${progress}-empty`,
|
|
124
|
+
activity: observed.activity,
|
|
125
|
+
tool: observed.tool,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
if (STRUCTURE_EVENT_TYPES.has(type)) {
|
|
129
|
+
return { kind: ACTIVITY_KINDS.structure, type, label: type, activity: false, tool: null };
|
|
130
|
+
}
|
|
131
|
+
return unrelated;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Read one progress-shaped event far enough to decide whether it carried
|
|
136
|
+
* anything, and to recover the tool identity when it names one.
|
|
137
|
+
*
|
|
138
|
+
* This is the only place that touches payload fields. It reads text/content ONLY
|
|
139
|
+
* to test emptiness: no string is returned, stored or concatenated.
|
|
140
|
+
* @param {string} type - event type.
|
|
141
|
+
* @param {object} event - event object.
|
|
142
|
+
* @returns {{ activity: boolean, tool: object | null }} observation.
|
|
143
|
+
*/
|
|
144
|
+
function observeProgress(type, event) {
|
|
145
|
+
if (type === 'text-delta' || type === 'reasoning-delta') {
|
|
146
|
+
const text = payloadOf(event).text;
|
|
147
|
+
// A delta that carries no characters says nothing about progress: the loop
|
|
148
|
+
// can emit an empty chunk while waiting on the provider. A whitespace-only
|
|
149
|
+
// delta is still model output, so it counts.
|
|
150
|
+
return { activity: typeof text === 'string' && text !== '', tool: null };
|
|
151
|
+
}
|
|
152
|
+
if (type === 'message/part' || type === 'assistant/delta') {
|
|
153
|
+
// Nested streaming envelope: the chunk lives under `data.delta` (the runner
|
|
154
|
+
// accepts `data.delta`, `delta`, then `data` itself). Only the delta's TYPE and
|
|
155
|
+
// the emptiness of its text are read; the text is never returned.
|
|
156
|
+
const payload = payloadOf(event);
|
|
157
|
+
const delta = payload.delta ?? event.delta ?? payload;
|
|
158
|
+
if (delta === null || typeof delta !== 'object') return { activity: false, tool: null };
|
|
159
|
+
const deltaType = delta.type;
|
|
160
|
+
if (deltaType !== 'text-delta' && deltaType !== 'reasoning-delta') {
|
|
161
|
+
return { activity: false, tool: null };
|
|
162
|
+
}
|
|
163
|
+
const text = delta.text;
|
|
164
|
+
return { activity: typeof text === 'string' && text !== '', tool: null };
|
|
165
|
+
}
|
|
166
|
+
if (type === 'assistant/message') {
|
|
167
|
+
const payload = payloadOf(event);
|
|
168
|
+
const message = payload.message ?? event.message ?? null;
|
|
169
|
+
const content = Array.isArray(message?.content) ? message.content : [];
|
|
170
|
+
for (const block of content) {
|
|
171
|
+
if (block === null || typeof block !== 'object') continue;
|
|
172
|
+
if ((block.type === 'text' || block.type === 'reasoning')
|
|
173
|
+
&& typeof block.text === 'string' && block.text !== '') {
|
|
174
|
+
return { activity: true, tool: null };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return { activity: false, tool: null };
|
|
178
|
+
}
|
|
179
|
+
if (type === 'tool/call') {
|
|
180
|
+
// `payloadOf` already falls back to the event object itself, so this reads
|
|
181
|
+
// `data.name` when the native envelope is present and a top-level `name`
|
|
182
|
+
// otherwise. The ARGUMENTS are deliberately not read at all, so this module
|
|
183
|
+
// cannot retain or forward them.
|
|
184
|
+
const payload = payloadOf(event);
|
|
185
|
+
const name = identifier(payload.name);
|
|
186
|
+
const callId = identifier(payload.callId ?? payload.id);
|
|
187
|
+
return { activity: name !== null, tool: { name, callId } };
|
|
188
|
+
}
|
|
189
|
+
if (type === 'tool/result') {
|
|
190
|
+
// Native shape: `data.message.toolCallId` (the tool-role result message).
|
|
191
|
+
const message = payloadOf(event).message;
|
|
192
|
+
const callId = identifier(message?.toolCallId ?? payloadOf(event).callId);
|
|
193
|
+
// Any settled tool result is progress, including a failed one: the tool ran.
|
|
194
|
+
return { activity: true, tool: { name: null, callId } };
|
|
195
|
+
}
|
|
196
|
+
if (type === 'step/start') {
|
|
197
|
+
return { activity: true, tool: null };
|
|
198
|
+
}
|
|
199
|
+
return { activity: false, tool: null };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* The payload of a native event.
|
|
204
|
+
*
|
|
205
|
+
* Native events carry their payload under `data` (`{ type, seq, time, data }`),
|
|
206
|
+
* and the streaming shapes a fake or a legacy emitter produces put the same fields
|
|
207
|
+
* at the top level. Both spellings are accepted, `data` first.
|
|
208
|
+
* @param {object} event - event object.
|
|
209
|
+
* @returns {object} payload object (never null).
|
|
210
|
+
*/
|
|
211
|
+
function payloadOf(event) {
|
|
212
|
+
const data = event.data;
|
|
213
|
+
if (data !== null && typeof data === 'object' && !Array.isArray(data)) return data;
|
|
214
|
+
return event;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Bound an identifier-shaped value (a tool name or a call id).
|
|
219
|
+
*
|
|
220
|
+
* Bounded and type-checked, never interpreted: these names are published so an
|
|
221
|
+
* operator can see WHAT is running, and a pathological value cannot grow a view.
|
|
222
|
+
* @param {unknown} value - candidate.
|
|
223
|
+
* @returns {string | null} bounded identifier, or null.
|
|
224
|
+
*/
|
|
225
|
+
function identifier(value) {
|
|
226
|
+
if (typeof value !== 'string') return null;
|
|
227
|
+
const trimmed = value.slice(0, MAX_IDENTIFIER_CHARS);
|
|
228
|
+
return trimmed === '' ? null : trimmed;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Bounded activity state of one running task.
|
|
233
|
+
*
|
|
234
|
+
* Owned by the engine's per-task monitor. Every field is a scalar or a small
|
|
235
|
+
* bounded map; there is no reference to the event object that produced it.
|
|
236
|
+
*/
|
|
237
|
+
export class TaskActivity {
|
|
238
|
+
/**
|
|
239
|
+
* @param {object} [options] - `now` clock override (tests).
|
|
240
|
+
*/
|
|
241
|
+
constructor(options = {}) {
|
|
242
|
+
/** @type {() => number} */
|
|
243
|
+
this.now = typeof options.now === 'function' ? options.now : Date.now;
|
|
244
|
+
/** @type {number | null} */
|
|
245
|
+
this.lastActivityAt = null;
|
|
246
|
+
/** @type {number} */
|
|
247
|
+
this.replacements = 0;
|
|
248
|
+
/** @type {{ name: string | null, callId: string | null, startedAt: number } | null} */
|
|
249
|
+
this.tool = null;
|
|
250
|
+
/** Settled tool calls represented as a count only — never their content. */
|
|
251
|
+
this.toolCallsStarted = 0;
|
|
252
|
+
this.toolCallsFinished = 0;
|
|
253
|
+
this.lastToolName = null;
|
|
254
|
+
this.lastToolDurationMs = null;
|
|
255
|
+
/** @type {Map<string, number>} */
|
|
256
|
+
this.counts = new Map();
|
|
257
|
+
/** @type {Map<string, number>} */
|
|
258
|
+
this.openCalls = new Map();
|
|
259
|
+
/** @type {Map<string, number>} */
|
|
260
|
+
this.eventCounts = new Map();
|
|
261
|
+
/** Bumped on every genuine activity; used to reset one wait's episode view. */
|
|
262
|
+
this.sequence = 0;
|
|
263
|
+
/**
|
|
264
|
+
* Genuine activity events, counted independently of the label map.
|
|
265
|
+
*
|
|
266
|
+
* The map is bounded and its keys can be evicted, so summing it would make the
|
|
267
|
+
* published count both imprecise (structure and unrelated labels would be
|
|
268
|
+
* included) and lossy. This counter is only ever incremented for real progress.
|
|
269
|
+
*/
|
|
270
|
+
this.activityCount = 0;
|
|
271
|
+
/** Total observations, counted independently of the bounded per-type map. */
|
|
272
|
+
this.eventCount = 0;
|
|
273
|
+
/**
|
|
274
|
+
* Set once the run reached a terminal state. From then on every elapsed value is
|
|
275
|
+
* measured against the recorded end, so a stored record cannot appear to keep
|
|
276
|
+
* growing (a "tool running for 4 hours" that ended twenty minutes ago).
|
|
277
|
+
* @type {{ endedAt: number } | null}
|
|
278
|
+
*/
|
|
279
|
+
this.final = null;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Record one observation.
|
|
284
|
+
*
|
|
285
|
+
* @param {object} observation - result of {@link classifyActivityEvent}.
|
|
286
|
+
* @param {number} [at] - observation timestamp.
|
|
287
|
+
* @returns {boolean} whether this observation was real activity.
|
|
288
|
+
*/
|
|
289
|
+
record(observation, at = this.now()) {
|
|
290
|
+
assertObservation(observation);
|
|
291
|
+
if (this.final !== null) return false;
|
|
292
|
+
this.replacements += 1;
|
|
293
|
+
if (this.eventCount < Number.MAX_SAFE_INTEGER) this.eventCount += 1;
|
|
294
|
+
const counted = this.counts.get(observation.label) ?? 0;
|
|
295
|
+
if (counted < Number.MAX_SAFE_INTEGER) this.counts.set(observation.label, counted + 1);
|
|
296
|
+
if (observation.type !== null) {
|
|
297
|
+
const perType = this.eventCounts.get(observation.type) ?? 0;
|
|
298
|
+
if (perType < Number.MAX_SAFE_INTEGER) this.eventCounts.set(observation.type, perType + 1);
|
|
299
|
+
}
|
|
300
|
+
this.pruneCounts();
|
|
301
|
+
if (observation.tool !== null) this.recordTool(observation.tool, at);
|
|
302
|
+
if (observation.activity !== true) return false;
|
|
303
|
+
if (this.activityCount < Number.MAX_SAFE_INTEGER) this.activityCount += 1;
|
|
304
|
+
this.lastActivityAt = at;
|
|
305
|
+
this.sequence += 1;
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Freeze every elapsed value at the instant the run ended.
|
|
311
|
+
*
|
|
312
|
+
* Called once, when the task reaches a terminal state. A view or a stored record
|
|
313
|
+
* read an hour later then reports the span the run actually had, not an idle or
|
|
314
|
+
* tool-elapsed duration that keeps growing for a run nobody is following.
|
|
315
|
+
* @param {number} endedAt - the recorded end time.
|
|
316
|
+
* @returns {void}
|
|
317
|
+
*/
|
|
318
|
+
finalize(endedAt) {
|
|
319
|
+
if (this.final !== null) return;
|
|
320
|
+
const at = Number.isFinite(endedAt) ? endedAt : this.now();
|
|
321
|
+
this.final = { endedAt: at };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* The reference time elapsed values are measured against.
|
|
326
|
+
*
|
|
327
|
+
* Live: the caller's `at`. Finalized: the recorded end, so nothing grows.
|
|
328
|
+
* @param {number} at - requested reference time.
|
|
329
|
+
* @returns {number} the effective reference time.
|
|
330
|
+
*/
|
|
331
|
+
referenceTime(at) {
|
|
332
|
+
if (this.final !== null) return this.final.endedAt;
|
|
333
|
+
return at;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Track the tool call a `tool/call` (or `tool/result`) event named.
|
|
338
|
+
*
|
|
339
|
+
* A start opens a span; a result closes the matching span and records how long
|
|
340
|
+
* it ran. Nothing about the tool's arguments or result is kept.
|
|
341
|
+
* @param {{ name: string | null, callId: string | null }} tool - identity.
|
|
342
|
+
* @param {number} at - observation timestamp.
|
|
343
|
+
* @returns {void}
|
|
344
|
+
*/
|
|
345
|
+
recordTool(tool, at) {
|
|
346
|
+
const callId = tool.callId;
|
|
347
|
+
if (tool.name !== null) {
|
|
348
|
+
this.lastToolName = tool.name;
|
|
349
|
+
this.toolCallsStarted += 1;
|
|
350
|
+
this.tool = { name: tool.name, callId, startedAt: at };
|
|
351
|
+
if (callId !== null) {
|
|
352
|
+
this.openCalls.set(callId, at);
|
|
353
|
+
while (this.openCalls.size > MAX_TRACKED_CALL_IDS) {
|
|
354
|
+
const oldest = this.openCalls.keys().next();
|
|
355
|
+
if (oldest.done === true) break;
|
|
356
|
+
this.openCalls.delete(oldest.value);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
if (callId !== null && this.openCalls.has(callId)) {
|
|
362
|
+
const startedAt = this.openCalls.get(callId);
|
|
363
|
+
this.openCalls.delete(callId);
|
|
364
|
+
this.lastToolDurationMs = Math.max(0, at - startedAt);
|
|
365
|
+
this.toolCallsFinished += 1;
|
|
366
|
+
if (this.tool !== null && this.tool.callId === callId) this.tool = null;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Keep the counters bounded.
|
|
372
|
+
*
|
|
373
|
+
* Both maps are keyed by a closed vocabulary (the labels and types this module
|
|
374
|
+
* classifies), so they cannot grow with model output; the cap exists so a future
|
|
375
|
+
* classifier that learns more keys cannot turn this into unbounded memory.
|
|
376
|
+
* @returns {void}
|
|
377
|
+
*/
|
|
378
|
+
pruneCounts() {
|
|
379
|
+
while (this.counts.size > MAX_KIND_COUNTS) {
|
|
380
|
+
const oldest = this.counts.keys().next();
|
|
381
|
+
if (oldest.done === true) break;
|
|
382
|
+
this.counts.delete(oldest.value);
|
|
383
|
+
}
|
|
384
|
+
while (this.eventCounts.size > MAX_KIND_COUNTS) {
|
|
385
|
+
const oldest = this.eventCounts.keys().next();
|
|
386
|
+
if (oldest.done === true) break;
|
|
387
|
+
this.eventCounts.delete(oldest.value);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** @returns {number} total observations recorded. */
|
|
392
|
+
totalEvents() {
|
|
393
|
+
return this.eventCount;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** @returns {number} genuine activity events. */
|
|
397
|
+
activityEvents() {
|
|
398
|
+
return this.activityCount;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Milliseconds since the last genuine activity, or null when there was none.
|
|
403
|
+
* @param {number} [at] - reference time.
|
|
404
|
+
* @returns {number | null} idle span.
|
|
405
|
+
*/
|
|
406
|
+
idleForMs(at = this.now()) {
|
|
407
|
+
if (this.lastActivityAt === null) return null;
|
|
408
|
+
return Math.max(0, this.referenceTime(at) - this.lastActivityAt);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* The pending tool span, described without any argument or result text.
|
|
413
|
+
* @param {number} [at] - reference time.
|
|
414
|
+
* @returns {{ name: string | null, callId: string | null, startedAt: number, elapsedMs: number } | null} span.
|
|
415
|
+
*/
|
|
416
|
+
toolSpan(at = this.now()) {
|
|
417
|
+
if (this.tool === null) return null;
|
|
418
|
+
return {
|
|
419
|
+
name: this.tool.name,
|
|
420
|
+
callId: this.tool.callId,
|
|
421
|
+
startedAt: this.tool.startedAt,
|
|
422
|
+
elapsedMs: Math.max(0, this.referenceTime(at) - this.tool.startedAt),
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* The bounded, publishable summary of this activity.
|
|
428
|
+
*
|
|
429
|
+
* Everything here is a count, a timestamp or an identifier. There is no field a
|
|
430
|
+
* text fragment, an argument or a result body could be carried in.
|
|
431
|
+
* @param {object} [options] - `at` reference time, `toolActive` whether a tool
|
|
432
|
+
* call is currently outstanding.
|
|
433
|
+
* @returns {object} summary.
|
|
434
|
+
*/
|
|
435
|
+
summary({ at = this.now(), toolActive = false } = {}) {
|
|
436
|
+
const span = toolActive ? this.toolSpan(at) : null;
|
|
437
|
+
return {
|
|
438
|
+
lastActivityAt: this.lastActivityAt,
|
|
439
|
+
// `idleForMs` is the honest silence span. While a native tool call is
|
|
440
|
+
// outstanding the executor is working, not idle, so the same field reports
|
|
441
|
+
// the tool's elapsed span and `waitingOn` says which of the two it is.
|
|
442
|
+
idleForMs: span === null ? this.idleForMs(at) : span.elapsedMs,
|
|
443
|
+
waitingOn: span === null ? 'idle' : 'tool',
|
|
444
|
+
currentTool: span === null
|
|
445
|
+
? null
|
|
446
|
+
: { name: span.name, callId: span.callId, startedAt: span.startedAt, elapsedMs: span.elapsedMs },
|
|
447
|
+
lastTool: this.lastToolName === null
|
|
448
|
+
? null
|
|
449
|
+
: { name: this.lastToolName, durationMs: this.lastToolDurationMs },
|
|
450
|
+
events: this.totalEvents(),
|
|
451
|
+
activityEvents: this.activityEvents(),
|
|
452
|
+
toolCallsStarted: this.toolCallsStarted,
|
|
453
|
+
toolCallsFinished: this.toolCallsFinished,
|
|
454
|
+
// Stated when the record was frozen, so a reader can tell "this is the final
|
|
455
|
+
// span" from "this is still being measured".
|
|
456
|
+
finalizedAt: this.final === null ? null : this.final.endedAt,
|
|
457
|
+
// Per-kind counts, bounded and sorted for a stable view.
|
|
458
|
+
kinds: Object.fromEntries([...this.counts.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Guard against a caller passing a value this class cannot read.
|
|
465
|
+
* @param {unknown} observation - candidate observation.
|
|
466
|
+
* @returns {void}
|
|
467
|
+
*/
|
|
468
|
+
function assertObservation(observation) {
|
|
469
|
+
if (observation === null || typeof observation !== 'object') {
|
|
470
|
+
throw new TypeError('activity observation must be an object');
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** Why one observation wait ended. */
|
|
475
|
+
export const OBSERVE_REASONS = Object.freeze({
|
|
476
|
+
heartbeat: 'heartbeat',
|
|
477
|
+
attention: 'attention',
|
|
478
|
+
permission: 'permission',
|
|
479
|
+
ready: 'ready',
|
|
480
|
+
failed: 'failed',
|
|
481
|
+
cancelled: 'cancelled',
|
|
482
|
+
interrupted: 'interrupted',
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Reasons no caller may ever receive from {@link TaskMonitor#observe}.
|
|
487
|
+
*
|
|
488
|
+
* `heartbeat` means "nothing to report, ask again"; handing it to a caller would
|
|
489
|
+
* be indistinguishable from a real report, so the loop treats it as an internal
|
|
490
|
+
* re-wait instead.
|
|
491
|
+
*/
|
|
492
|
+
const INTERNAL_REASONS = Object.freeze(new Set([OBSERVE_REASONS.heartbeat]));
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* The task states that end an observation, mapped to the reason reported.
|
|
496
|
+
*
|
|
497
|
+
* Read from the engine's own lifecycle vocabulary rather than re-declared, so a
|
|
498
|
+
* new terminal state cannot leave the monitor silently reporting `heartbeat` for a
|
|
499
|
+
* finished run.
|
|
500
|
+
*/
|
|
501
|
+
const TERMINAL_REASON = Object.freeze({
|
|
502
|
+
'awaiting-host-review': OBSERVE_REASONS.ready,
|
|
503
|
+
failed: OBSERVE_REASONS.failed,
|
|
504
|
+
cancelled: OBSERVE_REASONS.cancelled,
|
|
505
|
+
});
|
|
506
|
+
|
|
507
|
+
/** The phase a running task reports while a permission request is outstanding. */
|
|
508
|
+
const PHASE_AWAITING_PERMISSION = 'awaiting-permission';
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* One task's activity monitor.
|
|
512
|
+
*
|
|
513
|
+
* Owned by the engine and attached to the task record, so the counters live next
|
|
514
|
+
* to the run that produced them and die with it. It owns three things and nothing
|
|
515
|
+
* else:
|
|
516
|
+
*
|
|
517
|
+
* 1. the bounded activity state ({@link TaskActivity}), fed from the native
|
|
518
|
+
* `onEvent` callback the runner already invokes;
|
|
519
|
+
* 2. the *episode* bookkeeping that makes silent waiting silent — a
|
|
520
|
+
* self-check fires once per idle episode, and an `attention` report is not
|
|
521
|
+
* repeated until the interval has really elapsed and the caller has asked
|
|
522
|
+
* again;
|
|
523
|
+
* 3. the observation wait itself, built from injected `now`/`wait` seams so a test
|
|
524
|
+
* can simulate twenty minutes in microseconds.
|
|
525
|
+
*
|
|
526
|
+
* What it must never do, and does not: run an LLM, read a diff or a workspace
|
|
527
|
+
* file, mutate the task, restart/cancel/resubmit a run, or extend a deadline. The
|
|
528
|
+
* self-check is a read of facts the engine already holds.
|
|
529
|
+
*/
|
|
530
|
+
export class TaskMonitor {
|
|
531
|
+
/**
|
|
532
|
+
* @param {object} task - the engine's own task record for this run.
|
|
533
|
+
* @param {object} [options] - seams and thresholds.
|
|
534
|
+
* @param {() => number} [options.now] - clock.
|
|
535
|
+
* @param {(ms: number) => Promise<void>} [options.wait] - bounded sleep.
|
|
536
|
+
* @param {number} [options.selfCheckSeconds] - idle span for the self-check.
|
|
537
|
+
* @param {number} [options.attentionSeconds] - idle span for `attention`.
|
|
538
|
+
* @param {number} [options.waitSliceMs] - internal polling slice.
|
|
539
|
+
* @param {(message: string, detail?: unknown) => void} [options.log] - diagnostic sink.
|
|
540
|
+
*/
|
|
541
|
+
constructor(task, options = {}) {
|
|
542
|
+
this.task = task;
|
|
543
|
+
this.now = typeof options.now === 'function' ? options.now : Date.now;
|
|
544
|
+
this.wait = typeof options.wait === 'function' ? options.wait : sleep;
|
|
545
|
+
this.selfCheckMs = secondsToMs(options.selfCheckSeconds, 300);
|
|
546
|
+
this.attentionMs = secondsToMs(options.attentionSeconds, 600);
|
|
547
|
+
this.waitSliceMs = Number.isSafeInteger(options.waitSliceMs) && options.waitSliceMs > 0
|
|
548
|
+
? options.waitSliceMs
|
|
549
|
+
: 1000;
|
|
550
|
+
this.log = typeof options.log === 'function' ? options.log : null;
|
|
551
|
+
this.activity = new TaskActivity({ now: this.now });
|
|
552
|
+
/** Episode identity: bumped whenever genuine activity ends the idle episode. */
|
|
553
|
+
this.episode = 0;
|
|
554
|
+
/** The episode the self-check already ran for, or null. */
|
|
555
|
+
this.checkedEpisode = null;
|
|
556
|
+
/** The last self-check diagnostic, published on every summary. */
|
|
557
|
+
this.selfCheck = { episode: null, checkedAt: null, verdict: null, detail: null };
|
|
558
|
+
/**
|
|
559
|
+
* When the most recent attention report was DELIVERED, and for which idle
|
|
560
|
+
* episode.
|
|
561
|
+
*
|
|
562
|
+
* Exactly one pair, never a growing collection: the cooldown is a property of
|
|
563
|
+
* the current silence, and an idle origin only moves forward, so an older entry
|
|
564
|
+
* could never be reached again. `null` means "no attention has been delivered
|
|
565
|
+
* for this episode yet".
|
|
566
|
+
* @type {{ episode: number, origin: number, at: number } | null}
|
|
567
|
+
*/
|
|
568
|
+
this.attentionDelivered = null;
|
|
569
|
+
/**
|
|
570
|
+
* Every observation currently waiting, so each one owns its own controller and
|
|
571
|
+
* one observer can never cancel another. Bounded by the number of callers; an
|
|
572
|
+
* entry is removed in its own `finally`.
|
|
573
|
+
* @type {Set<object>}
|
|
574
|
+
*/
|
|
575
|
+
this.waiters = new Set();
|
|
576
|
+
this.disposed = false;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Record one native event.
|
|
581
|
+
*
|
|
582
|
+
* Called from the runner's `onEvent` hook, which means it runs inside the
|
|
583
|
+
* native dispatch path: nothing here may throw, await, or retain the event.
|
|
584
|
+
* @param {unknown} event - native event object.
|
|
585
|
+
* @param {number} [at] - observation time.
|
|
586
|
+
* @returns {boolean} whether this event was real activity.
|
|
587
|
+
*/
|
|
588
|
+
onEvent(event, at = this.now()) {
|
|
589
|
+
if (this.disposed) return false;
|
|
590
|
+
let observation;
|
|
591
|
+
try {
|
|
592
|
+
observation = classifyActivityEvent(event);
|
|
593
|
+
} catch {
|
|
594
|
+
// A malformed event is not a reason to disturb the run that produced it.
|
|
595
|
+
return false;
|
|
596
|
+
}
|
|
597
|
+
try {
|
|
598
|
+
const active = this.activity.record(observation, at);
|
|
599
|
+
// Real activity ends the current idle episode. The episode identity is what
|
|
600
|
+
// makes "once per episode" true for the self-check and the attention latch:
|
|
601
|
+
// without it, a run that goes quiet, wakes, and goes quiet again would be
|
|
602
|
+
// treated as the SAME silence and could never alert a second time.
|
|
603
|
+
if (active) this.episode += 1;
|
|
604
|
+
return active;
|
|
605
|
+
} catch {
|
|
606
|
+
return false;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* The instant the current idle episode began.
|
|
612
|
+
*
|
|
613
|
+
* Before the executor has produced anything, the episode begins when its run
|
|
614
|
+
* began — a model that never streams a token is silent from the start, and
|
|
615
|
+
* measuring from "never" would hide it.
|
|
616
|
+
* @returns {number} epoch milliseconds.
|
|
617
|
+
*/
|
|
618
|
+
idleOrigin() {
|
|
619
|
+
if (this.activity.lastActivityAt !== null) return this.activity.lastActivityAt;
|
|
620
|
+
if (Number.isFinite(this.task?.startedAt)) return this.task.startedAt;
|
|
621
|
+
if (Number.isFinite(this.task?.createdAt)) return this.task.createdAt;
|
|
622
|
+
return this.now();
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* Whether the current inactivity episode has reached the self-check threshold.
|
|
627
|
+
* @param {number} [at] - reference time.
|
|
628
|
+
* @returns {boolean} true when one read-only inspection is due.
|
|
629
|
+
*/
|
|
630
|
+
selfCheckDue(at = this.now()) {
|
|
631
|
+
return at - this.idleOrigin() >= this.selfCheckMs;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* Perform the 5-minute read-only inspection, at most once per idle episode.
|
|
636
|
+
*
|
|
637
|
+
* The inspection reads only what the engine itself already holds: whether the
|
|
638
|
+
* task is alive, whether its executor settled, the phase, whether a permission
|
|
639
|
+
* request is pending, and which tool call is outstanding. It performs no model
|
|
640
|
+
* call, reads no diff or workspace file, changes no task state, and does not
|
|
641
|
+
* touch the deadline.
|
|
642
|
+
* @param {number} [at] - reference time.
|
|
643
|
+
* @returns {object | null} the diagnostic, or null when none was due.
|
|
644
|
+
*/
|
|
645
|
+
runSelfCheck(at = this.now()) {
|
|
646
|
+
if (this.disposed) return null;
|
|
647
|
+
if (!this.selfCheckDue(at)) return null;
|
|
648
|
+
const episode = this.episode;
|
|
649
|
+
if (this.checkedEpisode === episode) return null;
|
|
650
|
+
this.checkedEpisode = episode;
|
|
651
|
+
this.selfCheck = this.inspect(at, episode);
|
|
652
|
+
return this.selfCheck;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/**
|
|
656
|
+
* The last self-check diagnostic, or null when none ever ran.
|
|
657
|
+
* @returns {object | null} diagnostic.
|
|
658
|
+
*/
|
|
659
|
+
lastSelfCheck() {
|
|
660
|
+
return this.selfCheck.checkedAt === null ? null : this.selfCheck;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* Build the read-only diagnostic for the current episode.
|
|
665
|
+
* @param {number} at - reference time.
|
|
666
|
+
* @param {number} episode - episode identity.
|
|
667
|
+
* @returns {object} bounded diagnostic.
|
|
668
|
+
*/
|
|
669
|
+
inspect(at, episode) {
|
|
670
|
+
const task = this.task ?? {};
|
|
671
|
+
const pending = task.permission?.pending ?? null;
|
|
672
|
+
const span = this.activity.toolSpan(at);
|
|
673
|
+
const idleMs = Math.max(0, at - this.idleOrigin());
|
|
674
|
+
const nativeStarted = task.native?.started === true;
|
|
675
|
+
const nativeSettled = task.native?.settled === true;
|
|
676
|
+
let verdict;
|
|
677
|
+
if (task.state === 'pending' || task.state === 'running') {
|
|
678
|
+
if (pending !== null) verdict = 'waiting-for-permission';
|
|
679
|
+
else if (span !== null) verdict = 'tool-running';
|
|
680
|
+
else if (nativeStarted && !nativeSettled) verdict = 'executor-alive-silent';
|
|
681
|
+
else if (!nativeStarted) verdict = 'executor-not-started';
|
|
682
|
+
else verdict = 'idle-between-steps';
|
|
683
|
+
} else {
|
|
684
|
+
verdict = 'settled';
|
|
685
|
+
}
|
|
686
|
+
return {
|
|
687
|
+
episode,
|
|
688
|
+
checkedAt: at,
|
|
689
|
+
idleMs,
|
|
690
|
+
verdict,
|
|
691
|
+
detail: {
|
|
692
|
+
state: typeof task.state === 'string' ? task.state : null,
|
|
693
|
+
phase: typeof task.phase === 'string' ? task.phase : null,
|
|
694
|
+
nativeStarted,
|
|
695
|
+
nativeSettled,
|
|
696
|
+
permissionPending: pending !== null,
|
|
697
|
+
permissionRequestId: pending !== null && typeof pending.requestId === 'string' ? pending.requestId : null,
|
|
698
|
+
phaseIsPermissionWait: task.phase === PHASE_AWAITING_PERMISSION,
|
|
699
|
+
currentTool: span === null ? null : { name: span.name, callId: span.callId, elapsedMs: span.elapsedMs },
|
|
700
|
+
lastActivityAt: this.activity.lastActivityAt,
|
|
701
|
+
activityEvents: this.activity.activityEvents(),
|
|
702
|
+
events: this.activity.totalEvents(),
|
|
703
|
+
},
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Whether the current silence is old enough for an attention report, ignoring the
|
|
709
|
+
* cooldown of an earlier delivery.
|
|
710
|
+
* @param {number} [at] - reference time.
|
|
711
|
+
* @returns {boolean} true when the idle span has reached the threshold.
|
|
712
|
+
*/
|
|
713
|
+
attentionDue(at = this.now()) {
|
|
714
|
+
return at - this.idleOrigin() >= this.attentionMs;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* The instant the next attention report may be delivered, or `Infinity` while the
|
|
719
|
+
* thresholds have not been reached at all.
|
|
720
|
+
*
|
|
721
|
+
* The rule is a cooldown, not a one-shot latch: the FIRST report is due at
|
|
722
|
+
* `idleOrigin + attentionSeconds`, and every later report for the same silence
|
|
723
|
+
* needs a FURTHER `attentionSeconds` since the previous delivery. Genuine
|
|
724
|
+
* activity resets both the origin and the delivery record, so a run that goes
|
|
725
|
+
* quiet again can alert again.
|
|
726
|
+
* @returns {number} the next deliverable instant.
|
|
727
|
+
*/
|
|
728
|
+
nextAttentionAt() {
|
|
729
|
+
const origin = this.idleOrigin();
|
|
730
|
+
const delivered = this.attentionDelivered;
|
|
731
|
+
let next = origin + this.attentionMs;
|
|
732
|
+
if (delivered !== null && delivered.episode === this.episode && delivered.origin === origin) {
|
|
733
|
+
next = Math.max(next, delivered.at + this.attentionMs);
|
|
734
|
+
}
|
|
735
|
+
return next;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* Whether an attention report may be delivered at `at`, and atomically claims it
|
|
740
|
+
* if so.
|
|
741
|
+
*
|
|
742
|
+
* The claim happens in the same synchronous step as the test, so two observers
|
|
743
|
+
* reaching the threshold together cannot both return `attention`: the first
|
|
744
|
+
* claims, the second observes the fresh delivery record and keeps waiting.
|
|
745
|
+
* @param {number} [at] - delivery instant.
|
|
746
|
+
* @returns {boolean} true for the observer that won the claim.
|
|
747
|
+
*/
|
|
748
|
+
claimAttention(at = this.now()) {
|
|
749
|
+
if (at < this.nextAttentionAt()) return false;
|
|
750
|
+
this.attentionDelivered = { episode: this.episode, origin: this.idleOrigin(), at };
|
|
751
|
+
return true;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* Publishable activity summary for a task view.
|
|
756
|
+
*
|
|
757
|
+
* `toolActive` is passed by the caller because only the engine can decide what a
|
|
758
|
+
* long tool span means: a pending permission request already reports its own
|
|
759
|
+
* reason, and a settled run is not "waiting on a tool" at all.
|
|
760
|
+
* @param {object} [options] - `at` reference time, `toolActive`.
|
|
761
|
+
* @returns {object} bounded summary.
|
|
762
|
+
*/
|
|
763
|
+
snapshot({ at = this.now(), toolActive = false } = {}) {
|
|
764
|
+
const summary = this.activity.summary({ at, toolActive });
|
|
765
|
+
return {
|
|
766
|
+
...summary,
|
|
767
|
+
// Stated so a reader never has to derive the thresholds from a settings
|
|
768
|
+
// document that may have changed since this task froze its own.
|
|
769
|
+
selfCheckSeconds: Math.round(this.selfCheckMs / 1000),
|
|
770
|
+
attentionSeconds: Math.round(this.attentionMs / 1000),
|
|
771
|
+
idleForMs: this.activity.idleForMs(at),
|
|
772
|
+
selfCheck: {
|
|
773
|
+
episode: this.selfCheck.episode,
|
|
774
|
+
checkedAt: this.selfCheck.checkedAt,
|
|
775
|
+
verdict: this.selfCheck.verdict,
|
|
776
|
+
},
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/**
|
|
781
|
+
* Release every waiter this monitor owns. Called only by {@link dispose}.
|
|
782
|
+
*
|
|
783
|
+
* Each waiter aborts its own controller; one observation ending never touches
|
|
784
|
+
* another.
|
|
785
|
+
* @returns {void}
|
|
786
|
+
*/
|
|
787
|
+
releaseWaiters() {
|
|
788
|
+
for (const waiter of [...this.waiters]) {
|
|
789
|
+
try {
|
|
790
|
+
waiter.controller.abort();
|
|
791
|
+
} catch {
|
|
792
|
+
// Abort is idempotent.
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
this.waiters.clear();
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* The bounded observation wait documented for adapters (HTTP/MCP).
|
|
800
|
+
*
|
|
801
|
+
* What it reports, in precedence order, re-checked on every slice:
|
|
802
|
+
*
|
|
803
|
+
* 1. `interrupted` — this observer's own signal aborted, or the monitor was
|
|
804
|
+
* disposed. The WORKER is untouched;
|
|
805
|
+
* 2. `ready`/`failed`/`cancelled` — the task reached a terminal state. This wins
|
|
806
|
+
* over a disposal wake, so an observation released by engine teardown still
|
|
807
|
+
* reports the outcome the run actually reached;
|
|
808
|
+
* 3. `permission` — a per-call decision is outstanding. Waiting for approval is
|
|
809
|
+
* not a stall;
|
|
810
|
+
* 4. `attention` — the silence reached `attentionSeconds` (once, then on the
|
|
811
|
+
* cooldown) AND the claim was won. Genuine progress never produces this: it
|
|
812
|
+
* resets the silence instead, which is the whole point of the feature;
|
|
813
|
+
* 5. `heartbeat` — the bounded wait expired with nothing to report.
|
|
814
|
+
*
|
|
815
|
+
* The self-check runs inside the loop, so a monitor with no observer costs
|
|
816
|
+
* nothing. Every caller gets its own controller and timer, so an observation
|
|
817
|
+
* never cancels another.
|
|
818
|
+
* @param {object} [options] - `waitMs`, `signal`.
|
|
819
|
+
* @returns {Promise<{ reason: string, activitySinceWait: boolean, waitedMs: number, selfCheck: object | null }>} outcome.
|
|
820
|
+
*/
|
|
821
|
+
async observe(options = {}) {
|
|
822
|
+
const signal = options.signal ?? null;
|
|
823
|
+
// A terminal outcome is a READ of the task record, so it is answered even by a
|
|
824
|
+
// disposed monitor: engine teardown stops the observation loops, but it must
|
|
825
|
+
// never turn a finished run into "interrupted".
|
|
826
|
+
const settledNow = terminalReason(this.task);
|
|
827
|
+
if (settledNow !== null) return this.outcome(settledNow, false, 0, this.lastSelfCheck());
|
|
828
|
+
if (this.disposed) return this.outcome(OBSERVE_REASONS.interrupted, false, 0, null);
|
|
829
|
+
if (signal !== null && signal.aborted === true) return this.outcome(OBSERVE_REASONS.interrupted, false, 0, null);
|
|
830
|
+
|
|
831
|
+
const waitMs = boundedWait(options.waitMs);
|
|
832
|
+
const startedAt = this.now();
|
|
833
|
+
const startingSequence = this.activity.sequence;
|
|
834
|
+
const waiter = { controller: new AbortController() };
|
|
835
|
+
this.waiters.add(waiter);
|
|
836
|
+
const onAbort = () => {
|
|
837
|
+
try {
|
|
838
|
+
waiter.controller.abort();
|
|
839
|
+
} catch {
|
|
840
|
+
// Unreachable; abort is idempotent.
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
if (signal !== null) signal.addEventListener?.('abort', onAbort, { once: true });
|
|
844
|
+
|
|
845
|
+
let selfCheck = null;
|
|
846
|
+
try {
|
|
847
|
+
for (;;) {
|
|
848
|
+
const at = this.now();
|
|
849
|
+
const activitySinceWait = this.activity.sequence !== startingSequence;
|
|
850
|
+
// A pure read of local facts, run BEFORE any reason is returned so every
|
|
851
|
+
// report carries the diagnostic that explains the silence.
|
|
852
|
+
const checked = this.runSelfCheck(at);
|
|
853
|
+
if (checked !== null) selfCheck = checked;
|
|
854
|
+
|
|
855
|
+
// (2) The run's own outcome outranks a wake-up: a task that ended must be
|
|
856
|
+
// reported as ended even if the monitor was disposed in the same instant.
|
|
857
|
+
const terminal = terminalReason(this.task);
|
|
858
|
+
if (terminal !== null) return this.outcome(terminal, activitySinceWait, at - startedAt, selfCheck);
|
|
859
|
+
|
|
860
|
+
// (1) Only one's OWN abort (or disposal) interrupts.
|
|
861
|
+
if (this.disposed || waiter.controller.aborted === true || (signal !== null && signal.aborted === true)) {
|
|
862
|
+
return this.outcome(OBSERVE_REASONS.interrupted, activitySinceWait, at - startedAt, selfCheck);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
if (this.task?.permission?.pending !== null && this.task?.permission?.pending !== undefined) {
|
|
866
|
+
return this.outcome(OBSERVE_REASONS.permission, activitySinceWait, at - startedAt, selfCheck);
|
|
867
|
+
}
|
|
868
|
+
// (4) `claimAttention` is false while genuine progress has reset the clock,
|
|
869
|
+
// because the origin moved into the future relative to `nextAttentionAt()`.
|
|
870
|
+
if (this.claimAttention(at)) {
|
|
871
|
+
return this.outcome(OBSERVE_REASONS.attention, activitySinceWait, at - startedAt, selfCheck);
|
|
872
|
+
}
|
|
873
|
+
const elapsed = at - startedAt;
|
|
874
|
+
if (elapsed >= waitMs) {
|
|
875
|
+
return this.outcome(OBSERVE_REASONS.heartbeat, activitySinceWait, elapsed, selfCheck);
|
|
876
|
+
}
|
|
877
|
+
const untilAttention = this.nextAttentionAt() - at;
|
|
878
|
+
const slice = Math.max(1, Math.min(this.waitSliceMs, waitMs - elapsed, untilAttention));
|
|
879
|
+
try {
|
|
880
|
+
await this.wait(slice, { signal: waiter.controller.signal });
|
|
881
|
+
} catch {
|
|
882
|
+
// A wait seam that rejects ends THIS observation only. The worker and
|
|
883
|
+
// every other observer are untouched.
|
|
884
|
+
return this.outcome(OBSERVE_REASONS.interrupted, activitySinceWait, this.now() - startedAt, selfCheck);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
} finally {
|
|
888
|
+
this.waiters.delete(waiter);
|
|
889
|
+
if (signal !== null) signal.removeEventListener?.('abort', onAbort);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* Build one observation outcome.
|
|
895
|
+
* @param {string} reason - reported reason.
|
|
896
|
+
* @param {boolean} activitySinceWait - whether progress arrived during the wait.
|
|
897
|
+
* @param {number} waitedMs - observed duration.
|
|
898
|
+
* @param {object | null} selfCheck - the last self-check diagnostic.
|
|
899
|
+
* @returns {object} outcome.
|
|
900
|
+
*/
|
|
901
|
+
outcome(reason, activitySinceWait, waitedMs, selfCheck) {
|
|
902
|
+
return {
|
|
903
|
+
reason,
|
|
904
|
+
activitySinceWait: activitySinceWait === true,
|
|
905
|
+
waitedMs: Math.max(0, Math.trunc(waitedMs)),
|
|
906
|
+
selfCheck,
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/**
|
|
911
|
+
* Drop every listener/timer this monitor owns. Idempotent.
|
|
912
|
+
*
|
|
913
|
+
* Marking the activity final first freezes the elapsed values at the end
|
|
914
|
+
* recorded on the task, so nothing published afterwards grows.
|
|
915
|
+
* @param {number} [endedAt] - the run's recorded end, when known.
|
|
916
|
+
* @returns {void}
|
|
917
|
+
*/
|
|
918
|
+
dispose(endedAt = undefined) {
|
|
919
|
+
if (typeof endedAt === 'number') this.activity.finalize(endedAt);
|
|
920
|
+
if (this.disposed) return;
|
|
921
|
+
this.disposed = true;
|
|
922
|
+
this.releaseWaiters();
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* Whether one internal reason may be handed to a caller.
|
|
928
|
+
* @param {string} reason - reason value.
|
|
929
|
+
* @returns {boolean} true when a caller should receive it.
|
|
930
|
+
*/
|
|
931
|
+
export function isPublicReason(reason) {
|
|
932
|
+
return typeof reason === 'string' && Object.values(OBSERVE_REASONS).includes(reason) && !INTERNAL_REASONS.has(reason);
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* The reason a task's current state implies, or null while it is still running.
|
|
937
|
+
* @param {object} task - engine task record.
|
|
938
|
+
* @returns {string | null} reason.
|
|
939
|
+
*/
|
|
940
|
+
export function terminalReason(task) {
|
|
941
|
+
const state = task?.state;
|
|
942
|
+
if (typeof state !== 'string') return null;
|
|
943
|
+
return TERMINAL_REASON[state] ?? null;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/**
|
|
947
|
+
* Clamp a caller-requested wait to the documented bound.
|
|
948
|
+
* @param {unknown} waitMs - requested wait.
|
|
949
|
+
* @returns {number} a whole number of milliseconds within bounds.
|
|
950
|
+
*/
|
|
951
|
+
function boundedWait(waitMs) {
|
|
952
|
+
if (typeof waitMs !== 'number' || !Number.isFinite(waitMs) || waitMs <= 0) return 25_000;
|
|
953
|
+
return Math.min(25_000, Math.max(1, Math.trunc(waitMs)));
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/**
|
|
957
|
+
* Convert a validated seconds threshold to milliseconds, with the documented
|
|
958
|
+
* default when the value is absent.
|
|
959
|
+
* @param {unknown} value - seconds.
|
|
960
|
+
* @param {number} fallbackSeconds - default.
|
|
961
|
+
* @returns {number} milliseconds.
|
|
962
|
+
*/
|
|
963
|
+
function secondsToMs(value, fallbackSeconds) {
|
|
964
|
+
const seconds = Number.isSafeInteger(value) && value > 0 ? value : fallbackSeconds;
|
|
965
|
+
return seconds * 1000;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/**
|
|
969
|
+
* Default wait seam: a real, unref'd timeout that honours an abort signal.
|
|
970
|
+
*
|
|
971
|
+
* `unref()` matters: an observation waiting on a timer must not by itself keep the
|
|
972
|
+
* process alive, and the timer is cleared on abort so an abandoned observation
|
|
973
|
+
* leaves nothing behind.
|
|
974
|
+
* @param {number} ms - slice length.
|
|
975
|
+
* @param {object} [options] - `signal`.
|
|
976
|
+
* @returns {Promise<void>} resolves after the slice.
|
|
977
|
+
*/
|
|
978
|
+
export function sleep(ms, options = {}) {
|
|
979
|
+
const signal = options?.signal ?? null;
|
|
980
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
981
|
+
if (signal !== null && signal.aborted === true) {
|
|
982
|
+
rejectPromise(abortError());
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
const timer = setTimeout(() => {
|
|
986
|
+
cleanup();
|
|
987
|
+
resolvePromise();
|
|
988
|
+
}, ms);
|
|
989
|
+
timer.unref?.();
|
|
990
|
+
const onAbort = () => {
|
|
991
|
+
cleanup();
|
|
992
|
+
rejectPromise(abortError());
|
|
993
|
+
};
|
|
994
|
+
const cleanup = () => {
|
|
995
|
+
clearTimeout(timer);
|
|
996
|
+
if (signal !== null) signal.removeEventListener?.('abort', onAbort);
|
|
997
|
+
};
|
|
998
|
+
if (signal !== null) signal.addEventListener?.('abort', onAbort, { once: true });
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
/** @returns {Error} a DOM-shaped abort error. */
|
|
1003
|
+
function abortError() {
|
|
1004
|
+
const error = new Error('the wait was aborted');
|
|
1005
|
+
error.name = 'AbortError';
|
|
1006
|
+
return error;
|
|
1007
|
+
}
|
|
1008
|
+
|