cc-viewer 1.9.21 → 1.9.23
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 +2 -1
- package/cli.js +50 -14
- package/dist/assets/{App-C4f2Dpy9.js → App-DEA3HoZr.js} +2 -2
- package/dist/assets/{MdxEditorPanel-D7aQDQJp.js → MdxEditorPanel-CTAS2DJv.js} +1 -1
- package/dist/assets/{Mobile-D9ekLQFS.js → Mobile-CgVpXvs2.js} +1 -1
- package/dist/assets/{ProxyStatsModal-CWpgyVKI.js → ProxyStatsModal-C4sl-cuB.js} +1 -1
- package/dist/assets/index-CS47d9oh.js +2 -0
- package/dist/assets/seqResourceLoaders-CORH46PN.js +2 -0
- package/dist/assets/seqResourceLoaders-v4YzKhTS.css +41 -0
- package/dist/index.html +1 -1
- package/findcc.js +4 -4
- package/node_modules/@ccv/core/src/contentFilter.js +4 -1
- package/node_modules/@ccv/core/src/ultraplanTemplates.js +199 -0
- package/package.json +1 -1
- package/server/i18n.js +97 -14
- package/server/interceptor.js +6 -0
- package/server/lib/async-write-queue.js +18 -0
- package/server/lib/auth.js +11 -3
- package/server/lib/base-path.js +89 -18
- package/server/lib/base-url.js +209 -0
- package/server/lib/ensure-hooks.js +134 -2
- package/server/lib/im/im-bridge-core.js +16 -0
- package/server/lib/log-management.js +21 -1
- package/server/lib/plugin-runtime.js +24 -5
- package/server/lib/scheduled-task-executor.js +14 -2
- package/server/lib/scheduled-task-store.js +129 -18
- package/server/lib/sdk-manager.js +113 -11
- package/server/lib/v2/adapter.js +147 -15
- package/server/lib/v2/conversation-store.js +9 -0
- package/server/lib/v2/journal.js +35 -0
- package/server/lib/v2/layout.js +67 -1
- package/server/lib/v2/live-feed.js +15 -0
- package/server/lib/v2/replay.js +11 -3
- package/server/lib/v2/session-select.js +34 -2
- package/server/lib/v2/shard-manager.js +249 -0
- package/server/lib/v2/v2-writer.js +252 -6
- package/server/pty-manager.js +103 -4
- package/server/routes/events.js +75 -4
- package/server/routes/logs.js +47 -16
- package/server/routes/misc.js +15 -5
- package/server/routes/scheduled-tasks.js +13 -0
- package/server/server.js +123 -23
- package/dist/assets/index-CocpEURl.js +0 -2
- package/dist/assets/seqResourceLoaders-BhiCEaUt.js +0 -2
- package/dist/assets/seqResourceLoaders-DbccWwKz.css +0 -41
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
// Boundary: L1-lib. Imports L1 (cron/schedule-model/json-store/scheduled-task-runs-store)
|
|
32
32
|
// + L0-leaf (pid-alive) + node builtins. Must NOT import L2 (pty-manager/sdk-manager/…).
|
|
33
33
|
|
|
34
|
-
import { join } from 'node:path';
|
|
34
|
+
import { join, isAbsolute } from 'node:path';
|
|
35
35
|
import { randomBytes } from 'node:crypto';
|
|
36
36
|
import { existsSync, readFileSync } from 'node:fs';
|
|
37
37
|
import { mutateJson, readJsonStrict } from './json-store.js';
|
|
@@ -39,6 +39,7 @@ import { isPidAlive } from './pid-alive.js';
|
|
|
39
39
|
import { normalizeSchedule, nextBaseFor, occurrencesAtOrBefore, jitterForTaskId } from './schedule-model.js';
|
|
40
40
|
import { appendRuns, appendRun, deleteRunsForTask, findRunByClaimId } from './scheduled-task-runs-store.js';
|
|
41
41
|
import { reportSwallowed } from './error-report.js';
|
|
42
|
+
import { assembleScheduledPrompt } from '@ccv/core/ultraplanTemplates';
|
|
42
43
|
|
|
43
44
|
const LEGACY_FILE_NAME = 'scheduled-tasks.json';
|
|
44
45
|
const PREFS_FILE_NAME = 'preferences.json';
|
|
@@ -46,6 +47,11 @@ const VERSION = 1;
|
|
|
46
47
|
const MAX_TASKS_PER_PROJECT = 50;
|
|
47
48
|
const MAX_RUNS = 20;
|
|
48
49
|
const MAX_PROMPT_LEN = 20_000;
|
|
50
|
+
// Attachments ride the task so the executor can prefix quoted paths at fire time
|
|
51
|
+
// (the stored prompt stays the raw user text). Bounded: prefs is pretty-printed and
|
|
52
|
+
// rewritten on every claim/finalize, so strings must not be unbounded.
|
|
53
|
+
const MAX_ATTACHMENTS = 20;
|
|
54
|
+
const MAX_ATTACHMENT_STR = 1024;
|
|
49
55
|
const SUMMARY_LEN = 200;
|
|
50
56
|
const CATCH_UP_WINDOW_MS = 7 * 24 * 3600 * 1000; // 7 days
|
|
51
57
|
// A claim whose owner pid is unreadable is reclaimed after this age (pid-reuse
|
|
@@ -152,13 +158,79 @@ export function mutateScheduledTasks(root, mutator) {
|
|
|
152
158
|
}
|
|
153
159
|
|
|
154
160
|
function _newId(prefix) { return `${prefix}_${randomBytes(8).toString('hex')}`; }
|
|
161
|
+
|
|
162
|
+
// A stored path becomes a quoted prefix in the fire-time prompt, so it must be a
|
|
163
|
+
// plain absolute path: no quotes, no control chars (LF/CR/ESC would break the
|
|
164
|
+
// single-line structure and could smuggle hidden instructions into the prompt).
|
|
165
|
+
function _isValidAttachmentPath(p) {
|
|
166
|
+
if (typeof p !== 'string' || !p || p.length > MAX_ATTACHMENT_STR) return false;
|
|
167
|
+
if (!isAbsolute(p)) return false;
|
|
168
|
+
// eslint-disable-next-line no-control-regex
|
|
169
|
+
if (/[\x00-\x1f\x7f"\\]/.test(p)) return false;
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Validate + normalize a task's UltraPlan fields. Absent fields → {} (no change /
|
|
174
|
+
// not set), so old clients and partial updates (pause/resume) are unaffected.
|
|
175
|
+
// Returns { ok:true, fields } | { ok:false, reason }.
|
|
176
|
+
function _normalizeUltraplanFields(draft) {
|
|
177
|
+
const fields = {};
|
|
178
|
+
if (draft.template !== undefined) {
|
|
179
|
+
if (typeof draft.template !== 'string' || !draft.template || draft.template.length > 200) {
|
|
180
|
+
return { ok: false, reason: 'invalid_template' };
|
|
181
|
+
}
|
|
182
|
+
fields.template = draft.template;
|
|
183
|
+
}
|
|
184
|
+
if (draft.templateContent !== undefined) {
|
|
185
|
+
if (typeof draft.templateContent !== 'string' || draft.templateContent.length > MAX_PROMPT_LEN) {
|
|
186
|
+
return { ok: false, reason: 'invalid_template' };
|
|
187
|
+
}
|
|
188
|
+
fields.templateContent = draft.templateContent;
|
|
189
|
+
}
|
|
190
|
+
if (draft.attachments !== undefined) {
|
|
191
|
+
const list = draft.attachments;
|
|
192
|
+
if (!Array.isArray(list) || list.length > MAX_ATTACHMENTS) return { ok: false, reason: 'invalid_attachments' };
|
|
193
|
+
for (const a of list) {
|
|
194
|
+
if (!a || typeof a !== 'object'
|
|
195
|
+
|| typeof a.name !== 'string' || !a.name || a.name.length > MAX_ATTACHMENT_STR
|
|
196
|
+
|| !_isValidAttachmentPath(a.path)) {
|
|
197
|
+
return { ok: false, reason: 'invalid_attachments' };
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
fields.attachments = list.map(a => ({ name: a.name, path: a.path }));
|
|
201
|
+
}
|
|
202
|
+
return { ok: true, fields };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Final bound on what actually gets dispatched. The per-field caps above allow a
|
|
206
|
+
// combined ~60KB prompt (20k text + 20k template + 20×1KB paths); cap the assembled
|
|
207
|
+
// result so the injected prompt stays within the documented maximum.
|
|
208
|
+
function _assembledWithinLimit(fields, task) {
|
|
209
|
+
const probe = {
|
|
210
|
+
prompt: fields.prompt !== undefined ? fields.prompt : task?.prompt,
|
|
211
|
+
template: fields.template !== undefined ? fields.template : task?.template,
|
|
212
|
+
templateContent: fields.templateContent !== undefined ? fields.templateContent : task?.templateContent,
|
|
213
|
+
attachments: fields.attachments !== undefined ? fields.attachments : task?.attachments,
|
|
214
|
+
};
|
|
215
|
+
return assembleScheduledPrompt(probe).length <= MAX_PROMPT_LEN;
|
|
216
|
+
}
|
|
217
|
+
|
|
155
218
|
function _summarize(prompt) {
|
|
156
219
|
const s = String(prompt == null ? '' : prompt).replace(/\s+/g, ' ').trim();
|
|
157
220
|
return s.length > SUMMARY_LEN ? `${s.slice(0, SUMMARY_LEN - 1)}…` : s;
|
|
158
221
|
}
|
|
159
222
|
|
|
223
|
+
// Attachments-only tasks have an empty prompt — fall back to the attachment names so
|
|
224
|
+
// run history and completion toasts never render a blank summary.
|
|
225
|
+
function _summarizeTask(task) {
|
|
226
|
+
const s = _summarize(task.prompt);
|
|
227
|
+
if (s) return s;
|
|
228
|
+
const names = (Array.isArray(task.attachments) ? task.attachments : []).map(a => a.name).filter(Boolean);
|
|
229
|
+
return names.length ? `[${names.join(', ')}]` : s;
|
|
230
|
+
}
|
|
231
|
+
|
|
160
232
|
function _makeRun(task, fields) {
|
|
161
|
-
return { id: _newId('run'), summary:
|
|
233
|
+
return { id: _newId('run'), summary: _summarizeTask(task), ...fields };
|
|
162
234
|
}
|
|
163
235
|
|
|
164
236
|
// History is best-effort: a flush failure is reported but never fails the state change
|
|
@@ -207,16 +279,23 @@ export function getTask(root, id) {
|
|
|
207
279
|
}
|
|
208
280
|
|
|
209
281
|
/**
|
|
210
|
-
* Create a task. draft = { project, cwd, prompt, mode, schedule, enabled
|
|
282
|
+
* Create a task. draft = { project, cwd, prompt, mode, schedule, enabled,
|
|
283
|
+
* template?, templateContent?, attachments? }. prompt is the RAW user text; the
|
|
284
|
+
* UltraPlan wrapper + attachment paths are assembled at fire time (executor).
|
|
211
285
|
* The ONLY writer allowed to create the `scheduledTasks` prefs key (legacy tombstone).
|
|
212
286
|
*/
|
|
213
287
|
export async function createTask(root, draft, now = Date.now()) {
|
|
214
288
|
const norm = normalizeSchedule(draft.schedule, now);
|
|
215
289
|
if (!norm.ok) return { ok: false, reason: norm.error, detail: norm.detail };
|
|
216
290
|
const prompt = String(draft.prompt == null ? '' : draft.prompt).trim();
|
|
217
|
-
if (!prompt) return { ok: false, reason: 'invalid_prompt' };
|
|
218
|
-
if (prompt.length > MAX_PROMPT_LEN) return { ok: false, reason: 'invalid_prompt', detail: 'too long' };
|
|
219
291
|
if (draft.mode !== 'inject' && draft.mode !== 'spawn') return { ok: false, reason: 'invalid_mode' };
|
|
292
|
+
const ultra = _normalizeUltraplanFields(draft);
|
|
293
|
+
if (!ultra.ok) return { ok: false, reason: ultra.reason };
|
|
294
|
+
// An empty prompt is fine when attachments carry the task (they become the fire-time
|
|
295
|
+
// prompt prefix); "both empty" is rejected.
|
|
296
|
+
if (!prompt && (ultra.fields.attachments || []).length === 0) return { ok: false, reason: 'invalid_prompt' };
|
|
297
|
+
if (prompt.length > MAX_PROMPT_LEN) return { ok: false, reason: 'invalid_prompt', detail: 'too long' };
|
|
298
|
+
if (!_assembledWithinLimit(ultra.fields, { prompt })) return { ok: false, reason: 'invalid_prompt', detail: 'assembled too long' };
|
|
220
299
|
|
|
221
300
|
return mutateScheduledTasks(root, (reg) => {
|
|
222
301
|
const sameProject = reg.tasks.filter(t => t.project === draft.project);
|
|
@@ -229,6 +308,10 @@ export async function createTask(root, draft, now = Date.now()) {
|
|
|
229
308
|
mode: draft.mode,
|
|
230
309
|
schedule: norm.schedule,
|
|
231
310
|
permissionMode: draft.mode === 'spawn' ? (draft.permissionMode === 'inherit' ? 'inherit' : 'default') : undefined,
|
|
311
|
+
// UltraPlan fields are omitted (not null) when absent so old tasks keep their shape.
|
|
312
|
+
...(ultra.fields.template !== undefined ? { template: ultra.fields.template } : {}),
|
|
313
|
+
...(ultra.fields.templateContent !== undefined ? { templateContent: ultra.fields.templateContent } : {}),
|
|
314
|
+
...(ultra.fields.attachments !== undefined ? { attachments: ultra.fields.attachments } : {}),
|
|
232
315
|
enabled: draft.enabled !== false,
|
|
233
316
|
jitterMs: undefined,
|
|
234
317
|
nextBaseAt: null,
|
|
@@ -249,12 +332,33 @@ export async function createTask(root, draft, now = Date.now()) {
|
|
|
249
332
|
}
|
|
250
333
|
|
|
251
334
|
/**
|
|
252
|
-
* Update prompt / mode / schedule / enabled
|
|
253
|
-
*
|
|
254
|
-
*
|
|
335
|
+
* Update prompt / mode / schedule / enabled and the UltraPlan fields (template,
|
|
336
|
+
* templateContent, attachments — absent = no change). Recomputes next ONLY when
|
|
337
|
+
* schedule or enabled changed. Never clobbers an active claim. Resume does NOT catch
|
|
338
|
+
* up; it records a skipped/paused run (flushed to the runs file after the prefs write).
|
|
339
|
+
*
|
|
340
|
+
* Validation is fully staged BEFORE any mutation: mutateJson writes the file even when
|
|
341
|
+
* the mutator reports failure, so validating after mutating would persist a
|
|
342
|
+
* half-applied patch on a rejected update.
|
|
255
343
|
*/
|
|
256
344
|
export async function updateTask(root, id, patch, now = Date.now()) {
|
|
257
345
|
if (_isLegacy(root)) return { ok: false, reason: 'task_not_found' };
|
|
346
|
+
// Field-shape validation first (cheap, no lock).
|
|
347
|
+
const ultra = _normalizeUltraplanFields(patch);
|
|
348
|
+
if (!ultra.ok) return { ok: false, reason: ultra.reason };
|
|
349
|
+
if (patch.prompt !== undefined) {
|
|
350
|
+
const p = String(patch.prompt).trim();
|
|
351
|
+
if (p.length > MAX_PROMPT_LEN) return { ok: false, reason: 'invalid_prompt' };
|
|
352
|
+
}
|
|
353
|
+
if (patch.mode !== undefined && patch.mode !== 'inject' && patch.mode !== 'spawn') {
|
|
354
|
+
return { ok: false, reason: 'invalid_mode' };
|
|
355
|
+
}
|
|
356
|
+
// Schedule validation before the lock too (it only depends on the patch + now).
|
|
357
|
+
let stagedNorm;
|
|
358
|
+
if (patch.schedule !== undefined) {
|
|
359
|
+
const norm = normalizeSchedule(patch.schedule, now);
|
|
360
|
+
stagedNorm = norm; // once_in_past may still be forgiven inside the lock (at unchanged)
|
|
361
|
+
}
|
|
258
362
|
const pendingRuns = [];
|
|
259
363
|
const out = await mutateScheduledTasks(root, (reg) => {
|
|
260
364
|
const task = reg.tasks.find(t => t.id === id);
|
|
@@ -262,15 +366,6 @@ export async function updateTask(root, id, patch, now = Date.now()) {
|
|
|
262
366
|
let scheduleChanged = false;
|
|
263
367
|
let enabledChanged = false;
|
|
264
368
|
|
|
265
|
-
if (patch.prompt !== undefined) {
|
|
266
|
-
const prompt = String(patch.prompt).trim();
|
|
267
|
-
if (!prompt || prompt.length > MAX_PROMPT_LEN) return { ok: false, reason: 'invalid_prompt' };
|
|
268
|
-
task.prompt = prompt;
|
|
269
|
-
}
|
|
270
|
-
if (patch.mode !== undefined) {
|
|
271
|
-
if (patch.mode !== 'inject' && patch.mode !== 'spawn') return { ok: false, reason: 'invalid_mode' };
|
|
272
|
-
task.mode = patch.mode;
|
|
273
|
-
}
|
|
274
369
|
if (patch.schedule !== undefined) {
|
|
275
370
|
// once.at>=now+60s is only enforced when `at` itself changes: the UI always sends the
|
|
276
371
|
// full schedule back on save, so a prompt edit on an expired once task would otherwise
|
|
@@ -278,7 +373,7 @@ export async function updateTask(root, id, patch, now = Date.now()) {
|
|
|
278
373
|
const atUnchanged = patch.schedule && patch.schedule.kind === 'once'
|
|
279
374
|
&& task.schedule && task.schedule.kind === 'once'
|
|
280
375
|
&& Number(patch.schedule.at) === Number(task.schedule.at);
|
|
281
|
-
const norm =
|
|
376
|
+
const norm = stagedNorm;
|
|
282
377
|
if (!norm.ok) {
|
|
283
378
|
if (!(atUnchanged && norm.error === 'once_in_past')) {
|
|
284
379
|
return { ok: false, reason: norm.error, detail: norm.detail };
|
|
@@ -288,6 +383,22 @@ export async function updateTask(root, id, patch, now = Date.now()) {
|
|
|
288
383
|
if (!atUnchanged) delete task.jitterMs;
|
|
289
384
|
scheduleChanged = true;
|
|
290
385
|
}
|
|
386
|
+
if (patch.mode !== undefined) task.mode = patch.mode;
|
|
387
|
+
// Cross-field invariant on the MERGED result, computed BEFORE any mutation:
|
|
388
|
+
// mutateJson persists even when the mutator reports failure, so a both-empty
|
|
389
|
+
// rejection must not leave attachments/prompt half-cleared on disk.
|
|
390
|
+
const mergedPrompt = patch.prompt !== undefined ? String(patch.prompt).trim() : task.prompt;
|
|
391
|
+
const mergedAttachments = ultra.fields.attachments !== undefined ? ultra.fields.attachments : (task.attachments || []);
|
|
392
|
+
if (!String(mergedPrompt || '').trim() && mergedAttachments.length === 0) {
|
|
393
|
+
return { ok: false, reason: 'invalid_prompt' };
|
|
394
|
+
}
|
|
395
|
+
if (!_assembledWithinLimit({ ...ultra.fields, prompt: mergedPrompt }, task)) {
|
|
396
|
+
return { ok: false, reason: 'invalid_prompt', detail: 'assembled too long' };
|
|
397
|
+
}
|
|
398
|
+
if (ultra.fields.template !== undefined) task.template = ultra.fields.template;
|
|
399
|
+
if (ultra.fields.templateContent !== undefined) task.templateContent = ultra.fields.templateContent;
|
|
400
|
+
if (ultra.fields.attachments !== undefined) task.attachments = ultra.fields.attachments;
|
|
401
|
+
if (patch.prompt !== undefined) task.prompt = mergedPrompt;
|
|
291
402
|
if (patch.enabled !== undefined && patch.enabled !== task.enabled) {
|
|
292
403
|
task.enabled = !!patch.enabled;
|
|
293
404
|
enabledChanged = true;
|
|
@@ -36,6 +36,7 @@ import { createHash, randomBytes } from 'node:crypto';
|
|
|
36
36
|
import { registerSdkSessionLister } from './sdk-session-index.js';
|
|
37
37
|
import { readPrefsRaw } from './prefs-store.js';
|
|
38
38
|
import { projectKeyForCwd } from './system-prompt-snapshots.js';
|
|
39
|
+
import { AGENT_PROMPT_SNIPPET_LEN } from '@ccv/core/contentFilter';
|
|
39
40
|
import {
|
|
40
41
|
computeAutoApprove,
|
|
41
42
|
createAutoApproveState,
|
|
@@ -328,18 +329,17 @@ function _isBareClearCommand(text) {
|
|
|
328
329
|
* delta for the client to apply, and `skip_transcript` is forwarded as
|
|
329
330
|
* `skipTranscript` so the UI stage can decide whether to hide ambient tasks.
|
|
330
331
|
*
|
|
331
|
-
* Two constraints the UI stage MUST respect
|
|
332
|
+
* Two constraints the UI stage MUST respect:
|
|
332
333
|
* - TWO status vocabularies share the wire: `task_notification.status` is
|
|
333
334
|
* `completed|failed|stopped`, while `task_updated.patch.status` is
|
|
334
335
|
* `pending|running|completed|failed|killed` — adjacent but disjoint domains.
|
|
335
336
|
* A client that naively merges `{...task, ...frame}` then `{...frame.patch}`
|
|
336
337
|
* will mis-render; discriminate by `subtype` before reading `status`.
|
|
337
|
-
* -
|
|
338
|
-
*
|
|
339
|
-
*
|
|
340
|
-
*
|
|
341
|
-
*
|
|
342
|
-
* reducer semantics rather than growing a second table here).
|
|
338
|
+
* - The live relay is delta-only, but every frame is ALSO folded into a bounded
|
|
339
|
+
* per-session table (taskId → latest folded state, cap 64, reset on session
|
|
340
|
+
* boundaries) and replayed as an authoritative `sdk-task-snapshot` on WS
|
|
341
|
+
* reconnect — a frame missed during a gap is recoverable, and an empty table
|
|
342
|
+
* replays as `tasks: []` so the client reconciles to "no tasks".
|
|
343
343
|
*
|
|
344
344
|
* Note: the 4 subtypes relayed here are the PUBLIC contract (sdk.d.ts SDKMessage
|
|
345
345
|
* union). The SDK additionally emits @internal `task_summary` / `post_turn_summary`
|
|
@@ -386,6 +386,41 @@ function _normalizeSdkTask(msg) {
|
|
|
386
386
|
return out;
|
|
387
387
|
}
|
|
388
388
|
|
|
389
|
+
/**
|
|
390
|
+
* Fold one normalized sdk-task frame into a server-side table entry (the latest
|
|
391
|
+
* known state per taskId). task_started seeds; task_progress/updated merge fields
|
|
392
|
+
* (patch.status is authoritative for updated); task_notification marks terminal.
|
|
393
|
+
* Kept deliberately small — the full prompt is retained only as a bounded snippet,
|
|
394
|
+
* shared via @ccv/core's AGENT_PROMPT_SNIPPET_LEN so the client tracker truncates
|
|
395
|
+
* identically.
|
|
396
|
+
*/
|
|
397
|
+
const _SDK_TASK_TERMINAL = new Set(['completed', 'failed', 'stopped', 'killed']);
|
|
398
|
+
function _foldSdkTask(prev, frame) {
|
|
399
|
+
const next = { ...(prev || {}), taskId: frame.taskId };
|
|
400
|
+
if (frame.sessionId != null) next.sessionId = frame.sessionId;
|
|
401
|
+
if (frame.toolUseId != null) next.toolUseId = frame.toolUseId;
|
|
402
|
+
if (frame.taskType != null) next.taskType = frame.taskType;
|
|
403
|
+
if (frame.description != null) next.description = frame.description;
|
|
404
|
+
if (frame.patch && frame.patch.description != null) next.description = frame.patch.description; // task_updated delta
|
|
405
|
+
if (frame.summary != null) next.summary = frame.summary;
|
|
406
|
+
if (frame.prompt != null) next.promptSnippet = String(frame.prompt).slice(0, AGENT_PROMPT_SNIPPET_LEN);
|
|
407
|
+
// Retained so getSdkTaskSnapshot can hide ambient tasks from the replay while the
|
|
408
|
+
// entry still participates in session-boundary detection (a skipTranscript first
|
|
409
|
+
// frame may be the only task frame carrying the new sessionId).
|
|
410
|
+
if (frame.skipTranscript != null) next.skipTranscript = frame.skipTranscript === true;
|
|
411
|
+
if (frame.workflowName != null) next.workflowName = frame.workflowName;
|
|
412
|
+
if (frame.lastToolName != null) next.lastToolName = frame.lastToolName;
|
|
413
|
+
if (frame.usage != null) next.usage = frame.usage;
|
|
414
|
+
// Status: notification carries the terminal word; updated carries it in patch.
|
|
415
|
+
if (frame.subtype === 'task_notification' && frame.status != null) next.status = frame.status;
|
|
416
|
+
else if (frame.patch && frame.patch.status != null) next.status = frame.patch.status;
|
|
417
|
+
else if (frame.status != null) next.status = frame.status;
|
|
418
|
+
else if (!next.status) next.status = frame.subtype === 'task_started' ? 'running' : 'pending';
|
|
419
|
+
next.terminal = _SDK_TASK_TERMINAL.has(next.status);
|
|
420
|
+
next.updatedAt = Date.now();
|
|
421
|
+
return next;
|
|
422
|
+
}
|
|
423
|
+
|
|
389
424
|
// ── Per-session factory ──────────────────────────────────────────────────────
|
|
390
425
|
// ONE closure = ONE workspace's resident SDK session. Every variable the current
|
|
391
426
|
// (single-session) module held in module-level `let` lives here EXCEPT the ones
|
|
@@ -491,6 +526,15 @@ function _createSession(key, cwd) {
|
|
|
491
526
|
// turn-correlated, so it gets no turn-end/compact trigger and none of the in-flight gate
|
|
492
527
|
// (fetching/queued/seq) machinery above. It reuses the same CTX_USAGE_TIMEOUT_MS bound.
|
|
493
528
|
let _lastMcpStatus = null;
|
|
529
|
+
// Bounded server-side sdk-task table (review: stale active-agents strip). Until now
|
|
530
|
+
// the relay was stateless — a frame missed during a WS gap was unrecoverable, so a
|
|
531
|
+
// late/refreshed client never learned an in-flight agent, and a client whose
|
|
532
|
+
// terminal frame was lost kept the agent "active" forever. This bounded map (one
|
|
533
|
+
// entry per taskId, per sessionId) lets a reconnecting client reconcile to the
|
|
534
|
+
// server's authoritative view. Cleared on session boundaries like _lastInitSnapshot.
|
|
535
|
+
let _sdkTaskTable = new Map(); // taskId -> normalized sdk-task frame (latest)
|
|
536
|
+
let _sdkTaskTableSessionId = null; // sessionId the table belongs to
|
|
537
|
+
const _SDK_TASK_TABLE_CAP = 64; // bounded: oldest evicted beyond this
|
|
494
538
|
// Pending canUseTool promises: id → { kind, resolve, replay, startedAt, timeoutMs }
|
|
495
539
|
// replay is the exact broadcast payload that announced this approval — retained so a
|
|
496
540
|
// fresh WS connection can re-announce it (server.js connection replay), otherwise a
|
|
@@ -1556,6 +1600,14 @@ function _createSession(key, cwd) {
|
|
|
1556
1600
|
// /clear may reinitialize instead of returning a normal result. The new session is
|
|
1557
1601
|
// now authoritative, so context reads may resume (without resuming the old session).
|
|
1558
1602
|
if (_ctxUsageClearPending && msg.session_id) _ctxUsageClearPending = false;
|
|
1603
|
+
// Session boundary for the task table: /clear re-inits with a new session_id but
|
|
1604
|
+
// may emit no task frame until the next task starts (the task-frame boundary in
|
|
1605
|
+
// the task branch only fires once one arrives), and a task that was in flight
|
|
1606
|
+
// gets no terminal frame — without this reset a reconnect would resurrect it.
|
|
1607
|
+
if (msg.session_id && msg.session_id !== _sdkTaskTableSessionId) {
|
|
1608
|
+
_sdkTaskTable = new Map();
|
|
1609
|
+
_sdkTaskTableSessionId = msg.session_id;
|
|
1610
|
+
}
|
|
1559
1611
|
if (_broadcastWs && Array.isArray(msg.slash_commands) && msg.slash_commands.length > 0
|
|
1560
1612
|
&& msg.session_id !== _initAnnouncedSid) {
|
|
1561
1613
|
_initAnnouncedSid = msg.session_id;
|
|
@@ -1602,10 +1654,26 @@ function _createSession(key, cwd) {
|
|
|
1602
1654
|
// SDK background-task / subagent progress (SDK 0.2.x system subtypes). The TODO
|
|
1603
1655
|
// HUD (TaskProgressHud) is hook-fed and never fires in SDK mode; this is a
|
|
1604
1656
|
// separate, lossless relay so clients can observe task lifecycle (incl.
|
|
1605
|
-
// failed/stopped/killed terminal states the TODO HUD vocabulary lacks).
|
|
1606
|
-
//
|
|
1607
|
-
//
|
|
1608
|
-
|
|
1657
|
+
// failed/stopped/killed terminal states the TODO HUD vocabulary lacks). Folded
|
|
1658
|
+
// into a bounded server-side table for reconnect replay (a frame lost in a WS
|
|
1659
|
+
// gap is no longer unrecoverable); merge semantics stay client-side.
|
|
1660
|
+
const sdkTaskFrame = { type: 'sdk-task', cwd: _cwd, instanceKey, ..._normalizeSdkTask(msg) };
|
|
1661
|
+
// Maintain the authoritative table (sessionId-scoped, bounded). A new sessionId
|
|
1662
|
+
// resets the table so a /clear or in-place resume never leaks the prior session's
|
|
1663
|
+
// tasks into a reconnecting client's view.
|
|
1664
|
+
if (sdkTaskFrame.taskId) {
|
|
1665
|
+
if (sdkTaskFrame.sessionId && sdkTaskFrame.sessionId !== _sdkTaskTableSessionId) {
|
|
1666
|
+
_sdkTaskTable = new Map();
|
|
1667
|
+
_sdkTaskTableSessionId = sdkTaskFrame.sessionId;
|
|
1668
|
+
}
|
|
1669
|
+
_sdkTaskTable.delete(sdkTaskFrame.taskId); // re-insert for LRU order
|
|
1670
|
+
_sdkTaskTable.set(sdkTaskFrame.taskId, _foldSdkTask(_sdkTaskTable.get(sdkTaskFrame.taskId), sdkTaskFrame));
|
|
1671
|
+
while (_sdkTaskTable.size > _SDK_TASK_TABLE_CAP) {
|
|
1672
|
+
const oldest = _sdkTaskTable.keys().next().value;
|
|
1673
|
+
_sdkTaskTable.delete(oldest);
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
_broadcastWs(sdkTaskFrame);
|
|
1609
1677
|
}
|
|
1610
1678
|
break;
|
|
1611
1679
|
|
|
@@ -2627,6 +2695,8 @@ function _createSession(key, cwd) {
|
|
|
2627
2695
|
_lastInitSnapshot = null; // don't replay the OLD session's sdk-init to the new one
|
|
2628
2696
|
_lastSkillsSnapshot = null; // same for the skill surface
|
|
2629
2697
|
_lastSessionState = null; // same for the session-state snapshot — new session starts idle
|
|
2698
|
+
_sdkTaskTable = new Map(); // drop the outgoing session's task table
|
|
2699
|
+
_sdkTaskTableSessionId = null;
|
|
2630
2700
|
_clearStateHeartbeat();
|
|
2631
2701
|
_suspectGeneration = false;
|
|
2632
2702
|
_lastFailedTurn = null; // the failure belongs to the outgoing session — never retry it into this one
|
|
@@ -2651,6 +2721,8 @@ function _createSession(key, cwd) {
|
|
|
2651
2721
|
_initAnnouncedSid = '';
|
|
2652
2722
|
_lastInitSnapshot = null;
|
|
2653
2723
|
_lastSkillsSnapshot = null;
|
|
2724
|
+
_sdkTaskTable = new Map(); // full reset: drop the task table too
|
|
2725
|
+
_sdkTaskTableSessionId = null;
|
|
2654
2726
|
// Tell clients BEFORE nulling the snapshot: a re-init/launch mid-turn would
|
|
2655
2727
|
// otherwise leave the spinner lit with no frame ever clearing it (the new
|
|
2656
2728
|
// session starts idle and the state-change guard would swallow the first
|
|
@@ -2725,6 +2797,19 @@ function _createSession(key, cwd) {
|
|
|
2725
2797
|
getContextUsageSnapshot: () => _lastContextUsage,
|
|
2726
2798
|
getMcpStatusSnapshot: () => _lastMcpStatus,
|
|
2727
2799
|
getSkillsSnapshot: () => _lastSkillsSnapshot,
|
|
2800
|
+
// Authoritative sdk-task table for WS reconnect replay: a refreshed/reconnected
|
|
2801
|
+
// client reconciles its delta-only tracker to this snapshot (sessionId-scoped).
|
|
2802
|
+
// ALWAYS returns a frame — an empty `tasks: []` is authoritative ("no tasks"),
|
|
2803
|
+
// otherwise a client that missed the session boundary keeps its stale agents.
|
|
2804
|
+
// skipTranscript entries are tracked (they carry the session boundary) but hidden
|
|
2805
|
+
// from the replay, matching the live path that never shows ambient tasks.
|
|
2806
|
+
getSdkTaskSnapshot: () => ({
|
|
2807
|
+
type: 'sdk-task-snapshot',
|
|
2808
|
+
cwd: _cwd,
|
|
2809
|
+
instanceKey,
|
|
2810
|
+
sessionId: _sdkTaskTableSessionId,
|
|
2811
|
+
tasks: [..._sdkTaskTable.values()].filter((t) => t.skipTranscript !== true),
|
|
2812
|
+
}),
|
|
2728
2813
|
fetchContextUsage: async () => {
|
|
2729
2814
|
// On-demand fetch for the HTTP route: refresh the snapshot, broadcast to all clients,
|
|
2730
2815
|
// then reply. Unlike _refreshContextUsage this bypasses the in-flight gate (an explicit
|
|
@@ -3236,6 +3321,23 @@ export function getMcpStatusSnapshot(anchor) {
|
|
|
3236
3321
|
return sess ? sess.getMcpStatusSnapshot() : null;
|
|
3237
3322
|
}
|
|
3238
3323
|
|
|
3324
|
+
/**
|
|
3325
|
+
* WS reconnect replay getter for the authoritative sdk-task table.
|
|
3326
|
+
*
|
|
3327
|
+
* `anchor` (optional, skills-snapshot parity — resolved by _sessionForAnchor):
|
|
3328
|
+
* - { instanceKey } exact registered instance
|
|
3329
|
+
* - { cwd } exact normalized cwd
|
|
3330
|
+
* - { project } sanitized/raw basename; ambiguous → null
|
|
3331
|
+
* No anchor → the ACTIVE session. Returns the always-present `sdk-task-snapshot`
|
|
3332
|
+
* frame ({ type, cwd, instanceKey, sessionId, tasks }) — tasks may be empty — or
|
|
3333
|
+
* null only when the anchor resolves to no registered session (the caller sends
|
|
3334
|
+
* nothing; an anchor failure must not replay a foreign workspace's table).
|
|
3335
|
+
*/
|
|
3336
|
+
export function getSdkTaskSnapshot(anchor) {
|
|
3337
|
+
const sess = anchor ? _sessionForAnchor(anchor) : _active();
|
|
3338
|
+
return sess ? sess.getSdkTaskSnapshot() : null;
|
|
3339
|
+
}
|
|
3340
|
+
|
|
3239
3341
|
/**
|
|
3240
3342
|
* On-demand context-usage fetch for the HTTP route (see the Session factory's
|
|
3241
3343
|
* fetchContextUsage). No anchor → the active session. Returns
|