dsh-workplan 1.5.2 → 1.7.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/CHANGELOG.md +180 -1
- package/README.en.md +20 -6
- package/README.md +20 -8
- package/client.js +196 -29
- package/lib/host.js +78 -6
- package/lib/plan.js +474 -11
- package/lib/runtime.js +619 -87
- package/package.json +1 -1
- package/src/client.ts +193 -32
- package/src/host.ts +81 -5
- package/src/plan.ts +476 -11
- package/src/runtime.ts +608 -83
package/lib/runtime.js
CHANGED
|
@@ -12,7 +12,9 @@
|
|
|
12
12
|
* in this file is allowed to escape as an unhandled rejection from a listener.
|
|
13
13
|
*/
|
|
14
14
|
import { randomUUID } from 'node:crypto';
|
|
15
|
-
import {
|
|
15
|
+
import { existsSync } from 'node:fs';
|
|
16
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
17
|
+
import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, createStatuses, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isStatusQuestion, isVagueContinuation, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, MAX_CONVERSATION_CHARS, parseUpdateMessage, buildUpdateMessage, } from './plan.js';
|
|
16
18
|
import { createProgressWatchdog, describeError } from './watchdog.js';
|
|
17
19
|
export const PLANNER_TIMEOUT_MS = 120000;
|
|
18
20
|
/**
|
|
@@ -87,7 +89,7 @@ function taskTextFromMessages(messages) {
|
|
|
87
89
|
* it to both the planner and every child. Plugin-generated plan/result rows are
|
|
88
90
|
* excluded to avoid feeding the plan back into itself.
|
|
89
91
|
*/
|
|
90
|
-
function recentConversation(session, maxChars =
|
|
92
|
+
function recentConversation(session, maxChars = MAX_CONVERSATION_CHARS) {
|
|
91
93
|
if (!session || typeof session.eventAt !== 'function')
|
|
92
94
|
return '';
|
|
93
95
|
const parts = [];
|
|
@@ -174,7 +176,7 @@ async function collectStream(stream) {
|
|
|
174
176
|
return text;
|
|
175
177
|
}
|
|
176
178
|
async function runPlanner(ctx, options) {
|
|
177
|
-
const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '' } = options;
|
|
179
|
+
const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '', budget = {} } = options;
|
|
178
180
|
let lastErrors = [];
|
|
179
181
|
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
180
182
|
if (signal.aborted)
|
|
@@ -186,7 +188,7 @@ async function runPlanner(ctx, options) {
|
|
|
186
188
|
controller.abort(new PlanError('规划器超时', 'PLANNER_TIMEOUT'));
|
|
187
189
|
}, PLANNER_TIMEOUT_MS);
|
|
188
190
|
try {
|
|
189
|
-
let prompt = buildPlannerPrompt(taskText, cwd, conversationContext);
|
|
191
|
+
let prompt = buildPlannerPrompt(taskText, cwd, conversationContext, budget);
|
|
190
192
|
if (lastErrors.length > 0) {
|
|
191
193
|
prompt += [
|
|
192
194
|
'',
|
|
@@ -329,7 +331,7 @@ export function normaliseIdleTimeout(value) {
|
|
|
329
331
|
function writeSubtaskStatus(record, subtaskId, patch, guard) {
|
|
330
332
|
if (guard.timedOut)
|
|
331
333
|
return false;
|
|
332
|
-
record.statuses = applyStatus(record.statuses, subtaskId, patch);
|
|
334
|
+
record.statuses = applyStatus(record.statuses, subtaskId, { updatedBy: 'child', ...patch });
|
|
333
335
|
record.updatedAt = Date.now();
|
|
334
336
|
return true;
|
|
335
337
|
}
|
|
@@ -338,9 +340,107 @@ function recordSubtaskError(record, subtaskId, message, guard) {
|
|
|
338
340
|
return;
|
|
339
341
|
record.errors = [...record.errors, `${subtaskId}: ${truncate(message, 500)}`].slice(-20);
|
|
340
342
|
}
|
|
343
|
+
/**
|
|
344
|
+
* Resolve one artifact reference against the round's working directory.
|
|
345
|
+
*
|
|
346
|
+
* Relative refs are what a child is asked to report, so they must be resolved
|
|
347
|
+
* the same way for every check; an empty ref is never "present".
|
|
348
|
+
*/
|
|
349
|
+
function resolveArtifactPath(ref, cwd) {
|
|
350
|
+
const text = typeof ref === 'string' ? ref.trim() : '';
|
|
351
|
+
if (!text)
|
|
352
|
+
return '';
|
|
353
|
+
if (isAbsolute(text))
|
|
354
|
+
return text;
|
|
355
|
+
const base = typeof cwd === 'string' && cwd ? cwd : process.cwd();
|
|
356
|
+
return resolve(base, text);
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* [1.7.0] Check the files a child declared.
|
|
360
|
+
*
|
|
361
|
+
* Only `kind:'file'` is verifiable here. A url or a note is taken at face
|
|
362
|
+
* value; pretending to verify them would be worse than not checking at all.
|
|
363
|
+
* The verdict is recorded rather than enforced: a missing file makes the
|
|
364
|
+
* dependency gate fail, but it does not silently rewrite "done" to "blocked".
|
|
365
|
+
*/
|
|
366
|
+
export function checkArtifacts(artifacts, cwd, artifactExists = existsSync) {
|
|
367
|
+
const list = Array.isArray(artifacts) ? artifacts : [];
|
|
368
|
+
const missingArtifacts = [];
|
|
369
|
+
const checked = list.map((item) => {
|
|
370
|
+
if (!isRecord(item) || item.kind !== 'file')
|
|
371
|
+
return item;
|
|
372
|
+
const target = resolveArtifactPath(item.ref, cwd);
|
|
373
|
+
let exists = false;
|
|
374
|
+
try {
|
|
375
|
+
exists = target ? artifactExists(target) === true : false;
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
exists = false;
|
|
379
|
+
}
|
|
380
|
+
if (!exists)
|
|
381
|
+
missingArtifacts.push(String(item.ref));
|
|
382
|
+
return { ...item, exists };
|
|
383
|
+
});
|
|
384
|
+
return { artifacts: checked, missingArtifacts };
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Turn one child output into a status verdict.
|
|
388
|
+
*
|
|
389
|
+
* The decision lives in `adjudicateResult` (a pure function) so the runtime and
|
|
390
|
+
* the session replay cannot disagree. This wrapper only adds the two things
|
|
391
|
+
* that need the environment: the strict/legacy switch and the file check.
|
|
392
|
+
*/
|
|
393
|
+
function settleFromOutput(record, subtask, output, guard, options) {
|
|
394
|
+
const verdict = adjudicateResult({ output, strict: options.strictEvidence !== false });
|
|
395
|
+
const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists);
|
|
396
|
+
writeSubtaskStatus(record, subtask.id, {
|
|
397
|
+
status: verdict.status,
|
|
398
|
+
progress: 100,
|
|
399
|
+
finishedAt: Date.now(),
|
|
400
|
+
summary: truncate(output, 3000),
|
|
401
|
+
error: verdict.error,
|
|
402
|
+
verification: verdict.verification,
|
|
403
|
+
acceptance: verdict.acceptance,
|
|
404
|
+
artifacts: checked.artifacts.length > 0 ? checked.artifacts : undefined,
|
|
405
|
+
missingArtifacts: checked.missingArtifacts.length > 0 ? checked.missingArtifacts : undefined,
|
|
406
|
+
needs: verdict.needs.length > 0 ? verdict.needs : undefined,
|
|
407
|
+
}, guard);
|
|
408
|
+
if (verdict.status === 'blocked') {
|
|
409
|
+
recordSubtaskError(record, subtask.id, verdict.error ?? '未完成', guard);
|
|
410
|
+
}
|
|
411
|
+
else if (checked.missingArtifacts.length > 0) {
|
|
412
|
+
recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard);
|
|
413
|
+
}
|
|
414
|
+
return verdict;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Retry policy for one child attempt.
|
|
418
|
+
*
|
|
419
|
+
* A wedged child (no event for the whole idle window) is worth one fresh
|
|
420
|
+
* attempt. A hard ceiling means the budget is gone, and an abort is a decision,
|
|
421
|
+
* so neither is retried. `CHILD_NOT_COMPLETED` is retried only while there is
|
|
422
|
+
* more than one idle window left, otherwise the retry itself would just be
|
|
423
|
+
* killed by the same watchdog.
|
|
424
|
+
*/
|
|
425
|
+
export function shouldRetryAttempt(error, attempt, remainingMs, idleTimeoutMs) {
|
|
426
|
+
if (attempt >= 2)
|
|
427
|
+
return false;
|
|
428
|
+
const code = error?.code;
|
|
429
|
+
if (code === 'CHILD_TIMEOUT' || code === 'ABORTED' || code === 'TOTAL_TIMEOUT')
|
|
430
|
+
return false;
|
|
431
|
+
if (/aborted|refusal/i.test(String(error?.message ?? '')))
|
|
432
|
+
return false;
|
|
433
|
+
if (code === 'CHILD_STALLED')
|
|
434
|
+
return true;
|
|
435
|
+
if (code === 'CHILD_NOT_COMPLETED') {
|
|
436
|
+
return Number(remainingMs) > Number(idleTimeoutMs);
|
|
437
|
+
}
|
|
438
|
+
return true;
|
|
439
|
+
}
|
|
341
440
|
async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
342
441
|
const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options;
|
|
343
442
|
let lastError = null;
|
|
443
|
+
let lastFailure = null;
|
|
344
444
|
try {
|
|
345
445
|
if (!writeSubtaskStatus(record, subtask.id, {
|
|
346
446
|
status: 'in_progress',
|
|
@@ -380,6 +480,8 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
380
480
|
})),
|
|
381
481
|
cwd: options.cwd,
|
|
382
482
|
conversationContext,
|
|
483
|
+
statuses: record.statuses,
|
|
484
|
+
previousFailure: attempt > 1 ? lastFailure : null,
|
|
383
485
|
}),
|
|
384
486
|
}],
|
|
385
487
|
parent: options.agent,
|
|
@@ -450,24 +552,16 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
450
552
|
}
|
|
451
553
|
if (!output)
|
|
452
554
|
throw new PlanError('子 Agent 没有返回文本结果', 'EMPTY_CHILD_OUTPUT');
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
}
|
|
464
|
-
writeSubtaskStatus(record, subtask.id, {
|
|
465
|
-
status: 'done',
|
|
466
|
-
progress: 100,
|
|
467
|
-
finishedAt: Date.now(),
|
|
468
|
-
summary: truncate(output, 3000),
|
|
469
|
-
error: null,
|
|
470
|
-
}, guard);
|
|
555
|
+
/*
|
|
556
|
+
* [1.7.0] Evidence decides the verdict.
|
|
557
|
+
*
|
|
558
|
+
* The old rule was "not BLOCKED => done", so a child that reported
|
|
559
|
+
* unverified or failed self-checks was still counted as finished and
|
|
560
|
+
* the main Agent had nothing to review but prose. `adjudicateResult`
|
|
561
|
+
* is the single deterministic table; `settleFromOutput` adds the
|
|
562
|
+
* environment-dependent artifact check.
|
|
563
|
+
*/
|
|
564
|
+
settleFromOutput(record, subtask, output, guard, options);
|
|
471
565
|
return;
|
|
472
566
|
}
|
|
473
567
|
catch (error) {
|
|
@@ -475,27 +569,37 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
475
569
|
if (guard.timedOut)
|
|
476
570
|
break;
|
|
477
571
|
const isAbort = parentSignal.aborted || child.controller.signal.aborted;
|
|
572
|
+
const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs);
|
|
573
|
+
const remaining = deadline - Date.now();
|
|
478
574
|
/*
|
|
479
|
-
*
|
|
575
|
+
* [1.7.0] The retry carries the previous failure with it.
|
|
480
576
|
*
|
|
481
|
-
*
|
|
482
|
-
*
|
|
483
|
-
*
|
|
484
|
-
*
|
|
577
|
+
* Retrying with an identical prompt made the child repeat the same
|
|
578
|
+
* dead end and produced the same error twice. The next attempt now
|
|
579
|
+
* receives the code, message and attempt number, so it can change
|
|
580
|
+
* approach — or stop honestly.
|
|
485
581
|
*/
|
|
486
|
-
|
|
487
|
-
|
|
582
|
+
lastFailure = {
|
|
583
|
+
attempt,
|
|
584
|
+
code: error?.code ?? 'UNKNOWN',
|
|
585
|
+
message: describeError(error),
|
|
586
|
+
};
|
|
587
|
+
const retry = !isAbort && shouldRetryAttempt(error, attempt, remaining, idleTimeoutMs);
|
|
588
|
+
if (retry) {
|
|
488
589
|
record.errors = [
|
|
489
590
|
...record.errors,
|
|
490
|
-
`${subtask.id}: 第 ${attempt}
|
|
591
|
+
`${subtask.id}: 第 ${attempt} 次执行失败(${lastFailure.code}),已带上失败原因重试`,
|
|
491
592
|
].slice(-20);
|
|
492
593
|
writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard);
|
|
493
594
|
continue;
|
|
494
595
|
}
|
|
495
|
-
if (isAbort
|
|
496
|
-
|
|
596
|
+
if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
|
|
597
|
+
record.errors = [
|
|
598
|
+
...record.errors,
|
|
599
|
+
`${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
|
|
600
|
+
].slice(-20);
|
|
497
601
|
}
|
|
498
|
-
|
|
602
|
+
break;
|
|
499
603
|
}
|
|
500
604
|
finally {
|
|
501
605
|
if (activation) {
|
|
@@ -626,6 +730,30 @@ async function runWithConcurrency(items, limit, worker) {
|
|
|
626
730
|
* @param limits - resolved runtime limits (the resume budget comes from here).
|
|
627
731
|
* @returns a user message carrying the `workplan-result` payload.
|
|
628
732
|
*/
|
|
733
|
+
/**
|
|
734
|
+
* The subtask rows a dispatch/status tool returns to the model.
|
|
735
|
+
*
|
|
736
|
+
* One definition, because the same plan was described in three slightly
|
|
737
|
+
* different shapes (dispatch tail, already-running branch, status tool) and the
|
|
738
|
+
* model could see three different answers in one turn.
|
|
739
|
+
*/
|
|
740
|
+
export function modelStatusLines(statuses) {
|
|
741
|
+
const list = Array.isArray(statuses) ? statuses : [];
|
|
742
|
+
return list.map((item) => ({
|
|
743
|
+
subtaskId: item.subtaskId,
|
|
744
|
+
title: item.title,
|
|
745
|
+
department: item.department,
|
|
746
|
+
status: item.status,
|
|
747
|
+
progress: item.progress,
|
|
748
|
+
summary: truncate(item.summary ?? item.error ?? '', 2000),
|
|
749
|
+
error: item.error ?? null,
|
|
750
|
+
verification: item.verification ?? null,
|
|
751
|
+
revision: Number(item.revision ?? 0),
|
|
752
|
+
updatedBy: item.updatedBy ?? null,
|
|
753
|
+
missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
|
|
754
|
+
needs: Array.isArray(item.needs) ? item.needs : [],
|
|
755
|
+
}));
|
|
756
|
+
}
|
|
629
757
|
export function buildRoundResult(record, sessionId, limits) {
|
|
630
758
|
const { statuses, stats } = derivePlanSnapshot(record.statuses);
|
|
631
759
|
return buildResultMessage({
|
|
@@ -705,7 +833,18 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
705
833
|
throw abortError();
|
|
706
834
|
if (Date.now() >= deadline)
|
|
707
835
|
throw new PlanError('总执行超时', 'TOTAL_TIMEOUT');
|
|
708
|
-
|
|
836
|
+
/*
|
|
837
|
+
* [1.7.0] A `done` upstream only unblocks its dependents when the files it
|
|
838
|
+
* declared actually exist. The check is opt-out (`artifactGate:false`) so
|
|
839
|
+
* an older plan or a debugging session can keep plain status semantics.
|
|
840
|
+
*/
|
|
841
|
+
const gate = options.artifactGate !== false;
|
|
842
|
+
const ready = readySubtasks(record.plan, record.statuses, gate
|
|
843
|
+
? {
|
|
844
|
+
dependencyOk: (dependency) => dependency?.status === 'done'
|
|
845
|
+
&& !(Array.isArray(dependency?.missingArtifacts) && dependency.missingArtifacts.length > 0),
|
|
846
|
+
}
|
|
847
|
+
: {});
|
|
709
848
|
if (ready.length === 0) {
|
|
710
849
|
const pending = record.statuses.filter((item) => item.status === 'pending');
|
|
711
850
|
for (const item of pending) {
|
|
@@ -733,13 +872,27 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
733
872
|
modelSelection,
|
|
734
873
|
cwd,
|
|
735
874
|
conversationContext,
|
|
875
|
+
strictEvidence: options.strictEvidence,
|
|
876
|
+
artifactExists: options.artifactExists,
|
|
736
877
|
});
|
|
737
878
|
});
|
|
738
879
|
const blocked = record.statuses
|
|
739
880
|
.filter((item) => item.status === 'blocked')
|
|
740
881
|
.map((item) => item.subtaskId);
|
|
741
882
|
for (const id of blocked) {
|
|
742
|
-
|
|
883
|
+
/*
|
|
884
|
+
* Carry the actual cause downstream. The main Agent used to receive
|
|
885
|
+
* "上游子任务受阻: T2" with no reason and no missing artifacts, so it
|
|
886
|
+
* had to re-read the whole plan to guess what to repair.
|
|
887
|
+
*/
|
|
888
|
+
const upstream = record.statuses.find((item) => item.subtaskId === id);
|
|
889
|
+
const cause = upstream
|
|
890
|
+
? {
|
|
891
|
+
reason: upstream.error,
|
|
892
|
+
missingArtifacts: Array.isArray(upstream.missingArtifacts) ? upstream.missingArtifacts : [],
|
|
893
|
+
}
|
|
894
|
+
: null;
|
|
895
|
+
record.statuses = markDependentsBlocked(record.plan, record.statuses, id, cause);
|
|
743
896
|
}
|
|
744
897
|
/*
|
|
745
898
|
* No stats refresh here any more: `serialisePlan` derives the counts from
|
|
@@ -842,6 +995,59 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
842
995
|
}
|
|
843
996
|
return record;
|
|
844
997
|
}
|
|
998
|
+
/*
|
|
999
|
+
* [1.6.0] 会话「这一轮到底还在不在跑」的唯一事实源。
|
|
1000
|
+
*
|
|
1001
|
+
* 事故(session-7129faea…):会话早已结束,面板仍把计划列在「进行中」组,
|
|
1002
|
+
* 卡片写着「预算用完,可续跑」——没有任何东西在跑,状态却表示正在跑。
|
|
1003
|
+
*
|
|
1004
|
+
* 根因:插件只订阅 `agent/pre-step`,`turn/end`、`session/disposed` 全都收不到;
|
|
1005
|
+
* 计划状态因此只由「派发结果」驱动,而派发结束后不再有任何事件把它收敛。
|
|
1006
|
+
*
|
|
1007
|
+
* 修复不引入第二个事件订阅(跨 scope 的事件投递受 scope 过滤,不可靠;而且
|
|
1008
|
+
* 订阅只覆盖实时路径,刷新/重启后全靠回放,两条链路一旦不同源就会来回翻转)。
|
|
1009
|
+
* 这里直接读会话日志本身——它既是实时事实,也是回放事实:
|
|
1010
|
+
*
|
|
1011
|
+
* - 从末尾向前找最近的一条「轮次边界」事件:先遇到 `turn/end` ⇒ 这一轮已结束;
|
|
1012
|
+
* 先遇到 `turn/start` ⇒ 这一轮还开着;都没找到 ⇒ 未知,调用方保持原判定。
|
|
1013
|
+
* - 不存在「会话已结束」这种事件:宿主只有每轮 `turn/end`。因此**不能**把
|
|
1014
|
+
* `turn/end` 直接等同于「计划取消/完成」——一轮结束后可以随时续跑,这也是
|
|
1015
|
+
* 卡片提供「可续跑」的原因。它只证明「此刻没有东西在跑」。
|
|
1016
|
+
* - 向后扫描设上限,避免越界;超过上限就返回 unknown,绝不猜测。
|
|
1017
|
+
*/
|
|
1018
|
+
const TURN_BOUNDARY_SCAN = 200;
|
|
1019
|
+
export function sessionTurnState(session) {
|
|
1020
|
+
const total = Number(session?.seq);
|
|
1021
|
+
if (!Number.isFinite(total) || total <= 0 || typeof session?.eventAt !== 'function') {
|
|
1022
|
+
return { state: 'unknown', reason: null, reasonDetail: null, at: null };
|
|
1023
|
+
}
|
|
1024
|
+
const floor = Math.max(0, Math.floor(total) - TURN_BOUNDARY_SCAN);
|
|
1025
|
+
for (let seq = Math.floor(total) - 1; seq >= floor; seq -= 1) {
|
|
1026
|
+
let event;
|
|
1027
|
+
try {
|
|
1028
|
+
event = session.eventAt(seq);
|
|
1029
|
+
}
|
|
1030
|
+
catch {
|
|
1031
|
+
return { state: 'unknown', reason: null, reasonDetail: null, at: null };
|
|
1032
|
+
}
|
|
1033
|
+
if (!event)
|
|
1034
|
+
continue;
|
|
1035
|
+
if (event.type === 'turn/start')
|
|
1036
|
+
return { state: 'open', reason: null, reasonDetail: null, at: null };
|
|
1037
|
+
if (event.type === 'turn/end') {
|
|
1038
|
+
const reason = event.data?.reason ?? null;
|
|
1039
|
+
const detail = reason && reason.kind === 'aborted' ? (reason.reason?.kind ?? null) : null;
|
|
1040
|
+
const at = Number(event.time);
|
|
1041
|
+
return {
|
|
1042
|
+
state: 'ended',
|
|
1043
|
+
reason: typeof reason?.kind === 'string' ? reason.kind : 'completed',
|
|
1044
|
+
reasonDetail: typeof detail === 'string' ? detail : null,
|
|
1045
|
+
at: Number.isFinite(at) ? at : null,
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
return { state: 'unknown', reason: null, reasonDetail: null, at: null };
|
|
1050
|
+
}
|
|
845
1051
|
function serialisePlan(record, session) {
|
|
846
1052
|
const plan = record.plan ?? null;
|
|
847
1053
|
/*
|
|
@@ -872,6 +1078,36 @@ function serialisePlan(record, session) {
|
|
|
872
1078
|
if (phase === 'pending' && !record.dispatchedAt && plan?.createdAt && Date.now() - plan.createdAt > STALE_PENDING_MS) {
|
|
873
1079
|
phase = 'cancelled';
|
|
874
1080
|
}
|
|
1081
|
+
/*
|
|
1082
|
+
* [1.6.0] 终态收敛:这一轮已经结束,而计划没有完成 ⇒ 不许再显示「进行中」。
|
|
1083
|
+
*
|
|
1084
|
+
* `phase` 到这里为止只由「派发动作」写入(executing / paused / blocked …),
|
|
1085
|
+
* 而派发结束后没有任何事件把它改回来,于是会话结束、进程空闲、面板却仍在
|
|
1086
|
+
* 「进行中」组里(事故截图)。上面 `sessionTurnState` 用会话日志回答
|
|
1087
|
+
* 「此刻还有没有东西在跑」,这里把答案落成独立阶段 `ended`:
|
|
1088
|
+
*
|
|
1089
|
+
* - done / cancelled 已经是终态,不再改写(done 改写会直接违反不变量 I8);
|
|
1090
|
+
* - 其余阶段一律收敛为 `ended`,并把原阶段留在 `suspendedPhase` 里,
|
|
1091
|
+
* 卡片因此仍能显示「预算用完,可续跑」「卡住了」这类二级事实,不丢信息;
|
|
1092
|
+
* - 只改**下发出去的那一份**,不动 `record.phase`:用户说「继续」后同一轮
|
|
1093
|
+
* 重新开始(日志里出现新的 turn/start),下一份 payload 自然回到原来的
|
|
1094
|
+
* 派发状态,不需要任何反向迁移逻辑;
|
|
1095
|
+
* - 实时路径与回放路径都经过本函数,因此刷新前后结论必然一致(T4 硬约束)。
|
|
1096
|
+
*/
|
|
1097
|
+
let suspendedPhase = null;
|
|
1098
|
+
let endReason = null;
|
|
1099
|
+
let endReasonDetail = null;
|
|
1100
|
+
let endedAt = null;
|
|
1101
|
+
if (phase !== 'done' && phase !== 'cancelled') {
|
|
1102
|
+
const turn = sessionTurnState(session);
|
|
1103
|
+
if (turn.state === 'ended') {
|
|
1104
|
+
suspendedPhase = phase;
|
|
1105
|
+
endReason = turn.reason;
|
|
1106
|
+
endReasonDetail = turn.reasonDetail;
|
|
1107
|
+
endedAt = turn.at;
|
|
1108
|
+
phase = 'ended';
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
875
1111
|
/*
|
|
876
1112
|
* 每次真正下发前跑一遍跨字段不变量(I1–I10)。正常情况下恒为空;一旦某个
|
|
877
1113
|
* 未来改动重新引入「进度与状态打架」,这里会把它连同具体字段值一起带出去,
|
|
@@ -883,6 +1119,7 @@ function serialisePlan(record, session) {
|
|
|
883
1119
|
planId: record.planId ?? plan?.planId ?? null,
|
|
884
1120
|
title: plan?.title ?? record.title ?? '任务进度',
|
|
885
1121
|
phase,
|
|
1122
|
+
...(phase === 'ended' ? { suspendedPhase, endReason, endReasonDetail, endedAt } : {}),
|
|
886
1123
|
...(violations.length ? { violations } : {}),
|
|
887
1124
|
degraded: record.degraded === true,
|
|
888
1125
|
error: record.error ? truncate(record.error, 2000) : null,
|
|
@@ -950,6 +1187,8 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
950
1187
|
* plan and let the caller ask for a specific one.
|
|
951
1188
|
*/
|
|
952
1189
|
const finished = [];
|
|
1190
|
+
/** [1.6.0] callId → 待确认的 update 写入;只有配对的 tool/result 才能定案。 */
|
|
1191
|
+
const pendingToolCalls = new Map();
|
|
953
1192
|
const snapshot = () => ({ plan, statuses, resultPhase, resultSeen, resumeCount, cancelled });
|
|
954
1193
|
for (let seq = start; seq < session.seq; seq += 1) {
|
|
955
1194
|
let event;
|
|
@@ -996,26 +1235,77 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
996
1235
|
resultPhase = typeof result.phase === 'string' ? result.phase : '';
|
|
997
1236
|
resultSeen = true;
|
|
998
1237
|
}
|
|
1238
|
+
/*
|
|
1239
|
+
* [1.7.0] Manual re-adjudications replay in order.
|
|
1240
|
+
*
|
|
1241
|
+
* `dsh_workplan_update` used to live only in the live cache, so a refresh
|
|
1242
|
+
* reverted the dashboard to the child's original verdict. The durable
|
|
1243
|
+
* `workplan-update` message is small and append-only, so replay is just
|
|
1244
|
+
* "apply it when its turn comes"; a lower revision never overwrites a
|
|
1245
|
+
* newer one (see `applyResultStatuses`).
|
|
1246
|
+
*/
|
|
1247
|
+
const update = parseUpdateMessage(event.data);
|
|
1248
|
+
if (update && plan && update.planId === plan.planId && typeof update.subtaskId === 'string') {
|
|
1249
|
+
try {
|
|
1250
|
+
statuses = applyStatus(statuses, update.subtaskId, {
|
|
1251
|
+
status: update.status,
|
|
1252
|
+
progress: typeof update.progress === 'number' ? update.progress : undefined,
|
|
1253
|
+
summary: typeof update.note === 'string' ? update.note : undefined,
|
|
1254
|
+
revision: Number.isInteger(update.revision) ? update.revision : undefined,
|
|
1255
|
+
updatedBy: 'agent',
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
catch {
|
|
1259
|
+
// An invalid historical update is ignored; the rest still replays.
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
999
1262
|
const cancel = parseCancelMessage(event.data);
|
|
1000
1263
|
if (cancel && plan && cancel.planId === plan.planId) {
|
|
1001
1264
|
cancelled = true;
|
|
1002
1265
|
}
|
|
1003
1266
|
}
|
|
1004
1267
|
else if (event.type === 'tool/call' && plan) {
|
|
1268
|
+
/*
|
|
1269
|
+
* [1.6.0] 只登记,不下结论。
|
|
1270
|
+
*
|
|
1271
|
+
* 回放原来一见到 `dsh_workplan_update` 的调用就 applyStatus,但调用发起不等于
|
|
1272
|
+
* 状态写入成功:宿主的 tool/result 带着 `message.isError`。会话
|
|
1273
|
+
* session-7129faea 里就有一次失败的 update 被回放记成完成,于是刷新后面板显示
|
|
1274
|
+
* 7/12,而真实只完成 6/12 —— 回放比实时“更乐观”,这是第二个数据源打架点。
|
|
1275
|
+
* 现在一律等对应的 tool/result:成功才采纳,失败或没有结果都不采纳。
|
|
1276
|
+
*/
|
|
1005
1277
|
const data = event.data;
|
|
1006
|
-
if (data?.name === 'dsh_workplan_update') {
|
|
1278
|
+
if (data?.name === 'dsh_workplan_update' && typeof data.callId === 'string') {
|
|
1007
1279
|
const args = readToolArguments(data.arguments);
|
|
1008
1280
|
if (args && typeof args.subtaskId === 'string' && typeof args.status === 'string') {
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1281
|
+
pendingToolCalls.set(data.callId, { args, planId: plan.planId });
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
else if (event.type === 'tool/result') {
|
|
1286
|
+
const message = event.data?.message;
|
|
1287
|
+
const callId = message?.role === 'tool' ? message.toolCallId : null;
|
|
1288
|
+
if (typeof callId !== 'string')
|
|
1289
|
+
continue;
|
|
1290
|
+
const pending = pendingToolCalls.get(callId);
|
|
1291
|
+
pendingToolCalls.delete(callId);
|
|
1292
|
+
if (!pending || !plan || pending.planId !== plan.planId) {
|
|
1293
|
+
// 结果晚于新计划到达:旧计划的写入不污染新计划的状态表。
|
|
1294
|
+
}
|
|
1295
|
+
else if (message.isError === true) {
|
|
1296
|
+
// 失败的更新不是完成:状态表保持原样。
|
|
1297
|
+
}
|
|
1298
|
+
else {
|
|
1299
|
+
const args = pending.args;
|
|
1300
|
+
try {
|
|
1301
|
+
statuses = applyStatus(statuses, args.subtaskId, {
|
|
1302
|
+
status: args.status,
|
|
1303
|
+
progress: typeof args.progress === 'number' ? args.progress : undefined,
|
|
1304
|
+
summary: typeof args.note === 'string' ? args.note : undefined,
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
catch {
|
|
1308
|
+
// An invalid historical call is ignored; the live cache remains authoritative.
|
|
1019
1309
|
}
|
|
1020
1310
|
}
|
|
1021
1311
|
}
|
|
@@ -1160,7 +1450,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1160
1450
|
if (downstream?.kind !== 'enter')
|
|
1161
1451
|
return downstream;
|
|
1162
1452
|
try {
|
|
1163
|
-
return await maybePlan(ctx, state, payload, downstream, options);
|
|
1453
|
+
return await maybePlan(ctx, state, payload, downstream, { ...options, limits });
|
|
1164
1454
|
}
|
|
1165
1455
|
catch (error) {
|
|
1166
1456
|
try {
|
|
@@ -1220,14 +1510,78 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1220
1510
|
? args.evidence.filter((item) => typeof item === 'string').join(';')
|
|
1221
1511
|
: '';
|
|
1222
1512
|
const summary = [note, evidence].filter(Boolean).join('|');
|
|
1513
|
+
const current = record.statuses.find((item) => item.subtaskId === subtaskId);
|
|
1514
|
+
/*
|
|
1515
|
+
* [1.7.0] Two write guards, both non-throwing.
|
|
1516
|
+
*
|
|
1517
|
+
* 1. A stale revision means the caller is looking at an older snapshot; the
|
|
1518
|
+
* write is refused instead of silently overwriting newer evidence.
|
|
1519
|
+
* 2. While the plan is running, the child owns the status of the subtask it
|
|
1520
|
+
* is executing. An agent edit would race the child's settlement (and the
|
|
1521
|
+
* child would overwrite it back). `force:true` is the explicit override,
|
|
1522
|
+
* recorded as a manual re-adjudication.
|
|
1523
|
+
*/
|
|
1524
|
+
if (Number.isInteger(args?.expectedRevision) && (current?.revision ?? 0) !== args.expectedRevision) {
|
|
1525
|
+
return {
|
|
1526
|
+
ok: false,
|
|
1527
|
+
code: 'STALE_WRITE',
|
|
1528
|
+
planId: record.plan.planId,
|
|
1529
|
+
subtaskId,
|
|
1530
|
+
current: {
|
|
1531
|
+
status: current?.status ?? null,
|
|
1532
|
+
revision: current?.revision ?? 0,
|
|
1533
|
+
updatedBy: current?.updatedBy ?? null,
|
|
1534
|
+
},
|
|
1535
|
+
hint: `该子任务已被更新(当前 revision ${current?.revision ?? 0},你基于 ${args.expectedRevision});请重新读取状态后再改。`,
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
const running = Boolean(record.dispatchPromise);
|
|
1539
|
+
const writeWhileRunning = running && !args?.force && (current?.status === 'pending' || current?.status === 'in_progress');
|
|
1540
|
+
if (writeWhileRunning) {
|
|
1541
|
+
return {
|
|
1542
|
+
ok: false,
|
|
1543
|
+
code: 'TASK_RUNNING',
|
|
1544
|
+
planId: record.plan.planId,
|
|
1545
|
+
subtaskId,
|
|
1546
|
+
current: {
|
|
1547
|
+
status: current?.status ?? null,
|
|
1548
|
+
revision: current?.revision ?? 0,
|
|
1549
|
+
updatedBy: current?.updatedBy ?? null,
|
|
1550
|
+
},
|
|
1551
|
+
hint: '该子任务正在执行;请等待本轮结束,或传 force:true 覆盖(会被记录为人工改判)。',
|
|
1552
|
+
};
|
|
1553
|
+
}
|
|
1554
|
+
const revision = Number(current?.revision ?? 0) + 1;
|
|
1223
1555
|
record.statuses = applyStatus(record.statuses, subtaskId, {
|
|
1224
1556
|
status,
|
|
1225
1557
|
progress: typeof args?.progress === 'number' ? args.progress : undefined,
|
|
1226
1558
|
summary: summary || undefined,
|
|
1227
1559
|
error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
|
|
1560
|
+
revision,
|
|
1561
|
+
updatedBy: 'agent',
|
|
1228
1562
|
});
|
|
1229
1563
|
if (status === 'blocked') {
|
|
1230
|
-
record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId);
|
|
1564
|
+
record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId, { reason: summary || '主 Agent 标记受阻' });
|
|
1565
|
+
}
|
|
1566
|
+
/*
|
|
1567
|
+
* [1.7.0] A re-adjudication is durable.
|
|
1568
|
+
*
|
|
1569
|
+
* `applyStatus` only touched the in-memory record, so after a refresh the
|
|
1570
|
+
* manual verdict vanished and the dashboard fell back to the old child
|
|
1571
|
+
* result. Appending one small message keeps the replay path honest.
|
|
1572
|
+
*/
|
|
1573
|
+
try {
|
|
1574
|
+
session.append('user/message', buildUpdateMessage({
|
|
1575
|
+
planId: record.plan.planId,
|
|
1576
|
+
subtaskId,
|
|
1577
|
+
status,
|
|
1578
|
+
progress: typeof args?.progress === 'number' ? args.progress : undefined,
|
|
1579
|
+
note: summary || undefined,
|
|
1580
|
+
revision,
|
|
1581
|
+
}), { surfaceOp: 'append' });
|
|
1582
|
+
}
|
|
1583
|
+
catch (error) {
|
|
1584
|
+
pushRecordError(record, error);
|
|
1231
1585
|
}
|
|
1232
1586
|
/*
|
|
1233
1587
|
* [1.5.2] 这里曾是「100% + 正在收尾」的直接入口。
|
|
@@ -1241,11 +1595,14 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1241
1595
|
record.phase = reconcilePhase(record.phase, record.statuses);
|
|
1242
1596
|
record.updatedAt = Date.now();
|
|
1243
1597
|
const snapshot = derivePlanSnapshot(record.statuses);
|
|
1598
|
+
const written = snapshot.statuses.find((item) => item.subtaskId === subtaskId);
|
|
1244
1599
|
return {
|
|
1245
1600
|
ok: true,
|
|
1246
1601
|
planId: record.plan.planId,
|
|
1247
1602
|
subtaskId,
|
|
1248
|
-
status:
|
|
1603
|
+
status: written?.status ?? status,
|
|
1604
|
+
revision: written?.revision ?? revision,
|
|
1605
|
+
updatedBy: written?.updatedBy ?? 'agent',
|
|
1249
1606
|
stats: snapshot.stats,
|
|
1250
1607
|
};
|
|
1251
1608
|
}
|
|
@@ -1333,6 +1690,91 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1333
1690
|
stats: derivePlanSnapshot(record.statuses).stats,
|
|
1334
1691
|
};
|
|
1335
1692
|
}
|
|
1693
|
+
/**
|
|
1694
|
+
* Persist the round result and settle the phase.
|
|
1695
|
+
*
|
|
1696
|
+
* Extracted from the wait path so an async dispatch reaches exactly the same
|
|
1697
|
+
* end state: a durable result message plus a reconciled phase. Anything less
|
|
1698
|
+
* would make "start now, read later" a second, divergent code path.
|
|
1699
|
+
*/
|
|
1700
|
+
function finishRound(record, session) {
|
|
1701
|
+
if (!record.resultWritten) {
|
|
1702
|
+
const resultMessage = buildRoundResult(record, session.id, limits);
|
|
1703
|
+
try {
|
|
1704
|
+
session.append('user/message', resultMessage, { surfaceOp: 'append' });
|
|
1705
|
+
record.resultWritten = true;
|
|
1706
|
+
}
|
|
1707
|
+
catch (error) {
|
|
1708
|
+
ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`);
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
/*
|
|
1712
|
+
* [1.5.2] 终态不再依赖「结果消息写成功」这个副作用。
|
|
1713
|
+
*
|
|
1714
|
+
* 旧代码只有 `record.resultWritten === true` 时才把 phase 升成 done,
|
|
1715
|
+
* 于是 session.append 抛错(或该轮根本没有派发)就会永久停在 integrating。
|
|
1716
|
+
* 完成语义由 statuses 决定;结果消息只负责持久化,不负责定义完成。
|
|
1717
|
+
*/
|
|
1718
|
+
record.phase = reconcilePhase(record.phase, record.statuses);
|
|
1719
|
+
return record;
|
|
1720
|
+
}
|
|
1721
|
+
function dispatchSnapshotOf(record, extra = {}) {
|
|
1722
|
+
const snapshot = derivePlanSnapshot(record.statuses);
|
|
1723
|
+
return {
|
|
1724
|
+
ok: true,
|
|
1725
|
+
planId: record.plan.planId,
|
|
1726
|
+
alreadyRunning: false,
|
|
1727
|
+
...extra,
|
|
1728
|
+
phase: record.phase,
|
|
1729
|
+
stats: snapshot.stats,
|
|
1730
|
+
statuses: modelStatusLines(snapshot.statuses),
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
/**
|
|
1734
|
+
* Read-only progress probe for the main Agent.
|
|
1735
|
+
*
|
|
1736
|
+
* With async dispatch the model no longer blocks until the round ends, so it
|
|
1737
|
+
* needs a supported way to answer "做成什么样了" without guessing. This is the
|
|
1738
|
+
* only source it should read: same `derivePlanSnapshot` as the dashboard and
|
|
1739
|
+
* the result message, so all three cannot disagree.
|
|
1740
|
+
*/
|
|
1741
|
+
async function statusTool(agent, args) {
|
|
1742
|
+
const session = agent?.session;
|
|
1743
|
+
if (!session)
|
|
1744
|
+
throw new PlanError('只能在会话内查看计划', 'NO_SESSION');
|
|
1745
|
+
const requestedPlanId = typeof args?.planId === 'string' ? args.planId : undefined;
|
|
1746
|
+
let record = state.records.get(session.id);
|
|
1747
|
+
if (!record?.plan || (requestedPlanId && record.plan.planId !== requestedPlanId)) {
|
|
1748
|
+
const rebuilt = reconstructFromSession(session, requestedPlanId);
|
|
1749
|
+
if (rebuilt?.plan)
|
|
1750
|
+
record = rebuilt;
|
|
1751
|
+
}
|
|
1752
|
+
if (!record?.plan) {
|
|
1753
|
+
return {
|
|
1754
|
+
ok: false,
|
|
1755
|
+
code: 'NO_PLAN',
|
|
1756
|
+
running: false,
|
|
1757
|
+
error: '当前会话没有可查看的计划',
|
|
1758
|
+
hint: '先让本轮生成计划并调用 dsh_workplan_dispatch。',
|
|
1759
|
+
};
|
|
1760
|
+
}
|
|
1761
|
+
const running = Boolean(record.dispatchPromise);
|
|
1762
|
+
const snapshot = derivePlanSnapshot(record.statuses);
|
|
1763
|
+
return {
|
|
1764
|
+
ok: true,
|
|
1765
|
+
planId: record.plan.planId,
|
|
1766
|
+
running,
|
|
1767
|
+
phase: record.phase,
|
|
1768
|
+
elapsedMs: record.dispatchStartedAt ? Date.now() - record.dispatchStartedAt : null,
|
|
1769
|
+
stats: snapshot.stats,
|
|
1770
|
+
statuses: modelStatusLines(snapshot.statuses),
|
|
1771
|
+
errors: (record.errors ?? []).slice(-10),
|
|
1772
|
+
resumeLimit: Number(record.resumeLimit ?? limits.maxResumes),
|
|
1773
|
+
...(running
|
|
1774
|
+
? { hint: '计划仍在执行:先向用户报告进度,不要声称完成;等结果消息出现后再逐项核对证据。' }
|
|
1775
|
+
: { hint: '当前没有正在执行的派发。若仍有 pending/blocked,可再次调用 dsh_workplan_dispatch 续跑。' }),
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1336
1778
|
async function dispatchTool(agent, args, signal) {
|
|
1337
1779
|
const session = agent?.session;
|
|
1338
1780
|
if (!session)
|
|
@@ -1377,6 +1819,36 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1377
1819
|
if (args?.planId && record.plan.planId !== args.planId) {
|
|
1378
1820
|
throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH');
|
|
1379
1821
|
}
|
|
1822
|
+
/*
|
|
1823
|
+
* [1.7.0] Two dispatch modes.
|
|
1824
|
+
*
|
|
1825
|
+
* `wait` (default, backward compatible) blocks until the round ends.
|
|
1826
|
+
* `async` starts the round and returns immediately, so the main Agent can
|
|
1827
|
+
* answer the user and keep integrating instead of sitting blind inside a
|
|
1828
|
+
* tool call for twenty minutes (the top-ranked collaboration break C1).
|
|
1829
|
+
*/
|
|
1830
|
+
const mode = args?.mode === 'async' ? 'async' : 'wait';
|
|
1831
|
+
if (mode === 'wait' && record.dispatchPromise) {
|
|
1832
|
+
/*
|
|
1833
|
+
* A wait caller that meets an in-flight round joins it instead of being
|
|
1834
|
+
* told "already running" — the old answer carried no results at all, so
|
|
1835
|
+
* a model that missed the async result message had nothing to integrate.
|
|
1836
|
+
* A wedged promise keeps the old stale escape hatch (see below).
|
|
1837
|
+
*/
|
|
1838
|
+
const startedAt = Number(record.dispatchStartedAt ?? 0);
|
|
1839
|
+
const staleAfter = limits.totalTimeoutMs + 120000;
|
|
1840
|
+
if (!(startedAt > 0 && Date.now() - startedAt > staleAfter)) {
|
|
1841
|
+
try {
|
|
1842
|
+
await record.dispatchPromise;
|
|
1843
|
+
}
|
|
1844
|
+
catch (error) {
|
|
1845
|
+
pushRecordError(record, error);
|
|
1846
|
+
}
|
|
1847
|
+
finishRound(record, session);
|
|
1848
|
+
state.records.set(session.id, record);
|
|
1849
|
+
return dispatchSnapshotOf(record, { joined: true });
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1380
1852
|
if (record.dispatchPromise) {
|
|
1381
1853
|
/*
|
|
1382
1854
|
* "Already running" must not become a permanent answer.
|
|
@@ -1403,7 +1875,25 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1403
1875
|
hint: '请主 Agent 直接接手完成剩余子任务,不要再次派发;并在答复中说明本次是直接执行而非派发。',
|
|
1404
1876
|
};
|
|
1405
1877
|
}
|
|
1406
|
-
|
|
1878
|
+
/*
|
|
1879
|
+
* [1.7.0] The idempotent answer now carries the progress itself.
|
|
1880
|
+
*
|
|
1881
|
+
* It used to say only `alreadyRunning: true`, so a second dispatch gave
|
|
1882
|
+
* the model strictly less information than doing nothing.
|
|
1883
|
+
*/
|
|
1884
|
+
const live = derivePlanSnapshot(record.statuses);
|
|
1885
|
+
return {
|
|
1886
|
+
ok: true,
|
|
1887
|
+
planId: record.plan.planId,
|
|
1888
|
+
alreadyRunning: true,
|
|
1889
|
+
running: true,
|
|
1890
|
+
phase: record.phase,
|
|
1891
|
+
startedAt: startedAt || null,
|
|
1892
|
+
elapsedMs: startedAt ? Date.now() - startedAt : null,
|
|
1893
|
+
stats: live.stats,
|
|
1894
|
+
statuses: modelStatusLines(live.statuses),
|
|
1895
|
+
hint: '计划仍在执行:先向用户报告进度,不要声称完成;用 dsh_workplan_status 查看实时状态。',
|
|
1896
|
+
};
|
|
1407
1897
|
}
|
|
1408
1898
|
/*
|
|
1409
1899
|
* Refuse with an explanation instead of silently "succeeding".
|
|
@@ -1464,47 +1954,47 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1464
1954
|
record.abortDispatch = null;
|
|
1465
1955
|
signal?.removeEventListener?.('abort', onToolAbort);
|
|
1466
1956
|
});
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1957
|
+
if (mode === 'async') {
|
|
1958
|
+
/*
|
|
1959
|
+
* Settlement happens in the background: the same durable result message
|
|
1960
|
+
* is appended when the round ends, so a page refresh (or a later turn)
|
|
1961
|
+
* still sees the outcome. The returned values are a *starting* snapshot,
|
|
1962
|
+
* never a completion claim.
|
|
1963
|
+
*/
|
|
1964
|
+
const startedAt = record.dispatchStartedAt;
|
|
1965
|
+
record.dispatchPromise
|
|
1966
|
+
.then(() => {
|
|
1967
|
+
finishRound(record, session);
|
|
1968
|
+
state.records.set(session.id, record);
|
|
1969
|
+
})
|
|
1970
|
+
.catch((error) => {
|
|
1971
|
+
pushRecordError(record, error);
|
|
1972
|
+
finishRound(record, session);
|
|
1973
|
+
state.records.set(session.id, record);
|
|
1974
|
+
});
|
|
1975
|
+
const live = derivePlanSnapshot(record.statuses);
|
|
1976
|
+
return {
|
|
1977
|
+
ok: true,
|
|
1978
|
+
planId: record.plan.planId,
|
|
1979
|
+
mode: 'async',
|
|
1980
|
+
running: true,
|
|
1981
|
+
alreadyRunning: false,
|
|
1982
|
+
phase: record.phase,
|
|
1983
|
+
startedAt,
|
|
1984
|
+
stats: live.stats,
|
|
1985
|
+
statuses: modelStatusLines(live.statuses),
|
|
1986
|
+
hint: '计划已开跑,尚未完成:先向用户说明“已派发、正在执行”,不要声称完成;'
|
|
1987
|
+
+ '结果消息会在本轮结束时自动出现,期间可用 dsh_workplan_status 查看进度。',
|
|
1988
|
+
};
|
|
1477
1989
|
}
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
*
|
|
1481
|
-
* 旧代码只有 `record.resultWritten === true` 时才把 phase 升成 done,
|
|
1482
|
-
* 于是 session.append 抛错(或该轮根本没有派发)就会永久停在 integrating。
|
|
1483
|
-
* 完成语义由 statuses 决定;结果消息只负责持久化,不负责定义完成。
|
|
1484
|
-
*/
|
|
1485
|
-
record.phase = reconcilePhase(record.phase, record.statuses);
|
|
1990
|
+
await record.dispatchPromise;
|
|
1991
|
+
finishRound(record, session);
|
|
1486
1992
|
/*
|
|
1487
1993
|
* The model's dispatch result reports the same snapshot the dashboard will
|
|
1488
1994
|
* show. It used to send `record.stats` while the status list below was read
|
|
1489
1995
|
* fresh, so one reply could say “已完成 11” next to twelve finished rows.
|
|
1490
1996
|
*/
|
|
1491
|
-
|
|
1492
|
-
return {
|
|
1493
|
-
ok: true,
|
|
1494
|
-
planId: record.plan.planId,
|
|
1495
|
-
alreadyRunning: false,
|
|
1496
|
-
phase: record.phase,
|
|
1497
|
-
stats: snapshot.stats,
|
|
1498
|
-
statuses: snapshot.statuses.map((item) => ({
|
|
1499
|
-
subtaskId: item.subtaskId,
|
|
1500
|
-
title: item.title,
|
|
1501
|
-
department: item.department,
|
|
1502
|
-
status: item.status,
|
|
1503
|
-
progress: item.progress,
|
|
1504
|
-
summary: truncate(item.summary ?? item.error ?? '', 2000),
|
|
1505
|
-
error: item.error ?? null,
|
|
1506
|
-
})),
|
|
1507
|
-
};
|
|
1997
|
+
return dispatchSnapshotOf(record);
|
|
1508
1998
|
}
|
|
1509
1999
|
function plansPayload(sessionId) {
|
|
1510
2000
|
return buildPlansPayload(ctx, state, sessionId);
|
|
@@ -1582,6 +2072,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1582
2072
|
updateStatus,
|
|
1583
2073
|
cancelPlan,
|
|
1584
2074
|
dispatchTool,
|
|
2075
|
+
statusTool,
|
|
1585
2076
|
plansPayload,
|
|
1586
2077
|
route,
|
|
1587
2078
|
dispose,
|
|
@@ -1696,6 +2187,18 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
1696
2187
|
modelSelection,
|
|
1697
2188
|
signal: payload.signal,
|
|
1698
2189
|
conversationContext,
|
|
2190
|
+
/*
|
|
2191
|
+
* Hand the real limits to the planner. Without them it had no idea the
|
|
2192
|
+
* round budget was 20 minutes and happily planned 15 heavy subtasks,
|
|
2193
|
+
* which then died at the budget wall. The prompt now states the budget
|
|
2194
|
+
* and asks for `estimateMinutes` on every subtask.
|
|
2195
|
+
*/
|
|
2196
|
+
budget: {
|
|
2197
|
+
totalMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
|
|
2198
|
+
childMinutes: Math.max(1, Math.round(Number(options?.limits?.childTimeoutMs ?? CHILD_TIMEOUT_MS) / 60000)),
|
|
2199
|
+
concurrency: MAX_CONCURRENT,
|
|
2200
|
+
maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
|
|
2201
|
+
},
|
|
1699
2202
|
});
|
|
1700
2203
|
}
|
|
1701
2204
|
catch (error) {
|
|
@@ -1758,7 +2261,10 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
1758
2261
|
* tool appends the durable result after the children finish, and tools.guard
|
|
1759
2262
|
* stops the main Agent from doing other work before dispatching.
|
|
1760
2263
|
*/
|
|
1761
|
-
const planMessage = buildPlanMessage(fullPlan
|
|
2264
|
+
const planMessage = buildPlanMessage(fullPlan, {
|
|
2265
|
+
totalBudgetMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
|
|
2266
|
+
maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
|
|
2267
|
+
});
|
|
1762
2268
|
if (!planMode)
|
|
1763
2269
|
return enterDecision(downstream, [planMessage]);
|
|
1764
2270
|
/*
|
|
@@ -1806,6 +2312,27 @@ export function updateToolOutputSchema() {
|
|
|
1806
2312
|
additionalProperties: true,
|
|
1807
2313
|
};
|
|
1808
2314
|
}
|
|
2315
|
+
export function statusToolOutputSchema() {
|
|
2316
|
+
return {
|
|
2317
|
+
type: 'object',
|
|
2318
|
+
properties: {
|
|
2319
|
+
ok: { type: 'boolean' },
|
|
2320
|
+
planId: { type: 'string' },
|
|
2321
|
+
running: { type: 'boolean' },
|
|
2322
|
+
phase: { type: 'string' },
|
|
2323
|
+
elapsedMs: { type: ['number', 'null'] },
|
|
2324
|
+
stats: { type: 'object' },
|
|
2325
|
+
statuses: { type: 'array' },
|
|
2326
|
+
errors: { type: 'array' },
|
|
2327
|
+
resumeLimit: { type: 'number' },
|
|
2328
|
+
hint: { type: 'string' },
|
|
2329
|
+
error: { type: 'string' },
|
|
2330
|
+
code: { type: 'string' },
|
|
2331
|
+
},
|
|
2332
|
+
required: ['ok'],
|
|
2333
|
+
additionalProperties: true,
|
|
2334
|
+
};
|
|
2335
|
+
}
|
|
1809
2336
|
export function dispatchToolOutputSchema() {
|
|
1810
2337
|
return {
|
|
1811
2338
|
type: 'object',
|
|
@@ -1814,6 +2341,11 @@ export function dispatchToolOutputSchema() {
|
|
|
1814
2341
|
planId: { type: 'string' },
|
|
1815
2342
|
alreadyRunning: { type: 'boolean' },
|
|
1816
2343
|
stale: { type: 'boolean' },
|
|
2344
|
+
running: { type: 'boolean' },
|
|
2345
|
+
joined: { type: 'boolean' },
|
|
2346
|
+
mode: { type: 'string' },
|
|
2347
|
+
elapsedMs: { type: 'number' },
|
|
2348
|
+
statuses: { type: 'array' },
|
|
1817
2349
|
phase: { type: 'string' },
|
|
1818
2350
|
stats: { type: 'object' },
|
|
1819
2351
|
error: { type: 'string' },
|