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/src/runtime.ts
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { randomUUID } from 'node:crypto'
|
|
16
|
+
import { existsSync } from 'node:fs'
|
|
17
|
+
import { isAbsolute, resolve } from 'node:path'
|
|
16
18
|
|
|
17
19
|
import {
|
|
18
20
|
MAX_CONCURRENT,
|
|
@@ -48,6 +50,10 @@ import {
|
|
|
48
50
|
truncate,
|
|
49
51
|
validatePlan,
|
|
50
52
|
applyResultStatuses,
|
|
53
|
+
adjudicateResult,
|
|
54
|
+
MAX_CONVERSATION_CHARS,
|
|
55
|
+
parseUpdateMessage,
|
|
56
|
+
buildUpdateMessage,
|
|
51
57
|
} from './plan.js'
|
|
52
58
|
import { createProgressWatchdog, describeError } from './watchdog.js'
|
|
53
59
|
|
|
@@ -121,7 +127,7 @@ function taskTextFromMessages(messages: any) {
|
|
|
121
127
|
* it to both the planner and every child. Plugin-generated plan/result rows are
|
|
122
128
|
* excluded to avoid feeding the plan back into itself.
|
|
123
129
|
*/
|
|
124
|
-
function recentConversation(session: any, maxChars =
|
|
130
|
+
function recentConversation(session: any, maxChars = MAX_CONVERSATION_CHARS) {
|
|
125
131
|
if (!session || typeof session.eventAt !== 'function') return ''
|
|
126
132
|
const parts: string[] = []
|
|
127
133
|
let seq = typeof session.seq === 'number' ? session.seq - 1 : -1
|
|
@@ -203,7 +209,7 @@ async function collectStream(stream: any) {
|
|
|
203
209
|
}
|
|
204
210
|
|
|
205
211
|
async function runPlanner(ctx: any, options: any) {
|
|
206
|
-
const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '' } = options
|
|
212
|
+
const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '', budget = {} } = options
|
|
207
213
|
let lastErrors: string[] = []
|
|
208
214
|
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
209
215
|
if (signal.aborted) throw abortError()
|
|
@@ -214,7 +220,7 @@ async function runPlanner(ctx: any, options: any) {
|
|
|
214
220
|
controller.abort(new PlanError('规划器超时', 'PLANNER_TIMEOUT'))
|
|
215
221
|
}, PLANNER_TIMEOUT_MS)
|
|
216
222
|
try {
|
|
217
|
-
let prompt = buildPlannerPrompt(taskText, cwd, conversationContext)
|
|
223
|
+
let prompt = buildPlannerPrompt(taskText, cwd, conversationContext, budget)
|
|
218
224
|
if (lastErrors.length > 0) {
|
|
219
225
|
prompt += [
|
|
220
226
|
'',
|
|
@@ -362,7 +368,7 @@ export function normaliseIdleTimeout(value: any) {
|
|
|
362
368
|
*/
|
|
363
369
|
function writeSubtaskStatus(record: any, subtaskId: any, patch: any, guard: SubtaskGuard) {
|
|
364
370
|
if (guard.timedOut) return false
|
|
365
|
-
record.statuses = applyStatus(record.statuses, subtaskId, patch)
|
|
371
|
+
record.statuses = applyStatus(record.statuses, subtaskId, { updatedBy: 'child', ...patch })
|
|
366
372
|
record.updatedAt = Date.now()
|
|
367
373
|
return true
|
|
368
374
|
}
|
|
@@ -372,9 +378,101 @@ function recordSubtaskError(record: any, subtaskId: any, message: any, guard: Su
|
|
|
372
378
|
record.errors = [...record.errors, `${subtaskId}: ${truncate(message, 500)}`].slice(-20)
|
|
373
379
|
}
|
|
374
380
|
|
|
381
|
+
/**
|
|
382
|
+
* Resolve one artifact reference against the round's working directory.
|
|
383
|
+
*
|
|
384
|
+
* Relative refs are what a child is asked to report, so they must be resolved
|
|
385
|
+
* the same way for every check; an empty ref is never "present".
|
|
386
|
+
*/
|
|
387
|
+
function resolveArtifactPath(ref: any, cwd: any) {
|
|
388
|
+
const text = typeof ref === 'string' ? ref.trim() : ''
|
|
389
|
+
if (!text) return ''
|
|
390
|
+
if (isAbsolute(text)) return text
|
|
391
|
+
const base = typeof cwd === 'string' && cwd ? cwd : process.cwd()
|
|
392
|
+
return resolve(base, text)
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* [1.7.0] Check the files a child declared.
|
|
397
|
+
*
|
|
398
|
+
* Only `kind:'file'` is verifiable here. A url or a note is taken at face
|
|
399
|
+
* value; pretending to verify them would be worse than not checking at all.
|
|
400
|
+
* The verdict is recorded rather than enforced: a missing file makes the
|
|
401
|
+
* dependency gate fail, but it does not silently rewrite "done" to "blocked".
|
|
402
|
+
*/
|
|
403
|
+
export function checkArtifacts(artifacts: any, cwd: any, artifactExists: any = existsSync) {
|
|
404
|
+
const list = Array.isArray(artifacts) ? artifacts : []
|
|
405
|
+
const missingArtifacts: string[] = []
|
|
406
|
+
const checked = list.map((item: any) => {
|
|
407
|
+
if (!isRecord(item) || item.kind !== 'file') return item
|
|
408
|
+
const target = resolveArtifactPath(item.ref, cwd)
|
|
409
|
+
let exists = false
|
|
410
|
+
try {
|
|
411
|
+
exists = target ? artifactExists(target) === true : false
|
|
412
|
+
} catch {
|
|
413
|
+
exists = false
|
|
414
|
+
}
|
|
415
|
+
if (!exists) missingArtifacts.push(String(item.ref))
|
|
416
|
+
return { ...item, exists }
|
|
417
|
+
})
|
|
418
|
+
return { artifacts: checked, missingArtifacts }
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Turn one child output into a status verdict.
|
|
423
|
+
*
|
|
424
|
+
* The decision lives in `adjudicateResult` (a pure function) so the runtime and
|
|
425
|
+
* the session replay cannot disagree. This wrapper only adds the two things
|
|
426
|
+
* that need the environment: the strict/legacy switch and the file check.
|
|
427
|
+
*/
|
|
428
|
+
function settleFromOutput(record: any, subtask: any, output: any, guard: SubtaskGuard, options: any) {
|
|
429
|
+
const verdict = adjudicateResult({ output, strict: options.strictEvidence !== false })
|
|
430
|
+
const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists)
|
|
431
|
+
writeSubtaskStatus(record, subtask.id, {
|
|
432
|
+
status: verdict.status,
|
|
433
|
+
progress: 100,
|
|
434
|
+
finishedAt: Date.now(),
|
|
435
|
+
summary: truncate(output, 3000),
|
|
436
|
+
error: verdict.error,
|
|
437
|
+
verification: verdict.verification,
|
|
438
|
+
acceptance: verdict.acceptance,
|
|
439
|
+
artifacts: checked.artifacts.length > 0 ? checked.artifacts : undefined,
|
|
440
|
+
missingArtifacts: checked.missingArtifacts.length > 0 ? checked.missingArtifacts : undefined,
|
|
441
|
+
needs: verdict.needs.length > 0 ? verdict.needs : undefined,
|
|
442
|
+
}, guard)
|
|
443
|
+
if (verdict.status === 'blocked') {
|
|
444
|
+
recordSubtaskError(record, subtask.id, verdict.error ?? '未完成', guard)
|
|
445
|
+
} else if (checked.missingArtifacts.length > 0) {
|
|
446
|
+
recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard)
|
|
447
|
+
}
|
|
448
|
+
return verdict
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Retry policy for one child attempt.
|
|
453
|
+
*
|
|
454
|
+
* A wedged child (no event for the whole idle window) is worth one fresh
|
|
455
|
+
* attempt. A hard ceiling means the budget is gone, and an abort is a decision,
|
|
456
|
+
* so neither is retried. `CHILD_NOT_COMPLETED` is retried only while there is
|
|
457
|
+
* more than one idle window left, otherwise the retry itself would just be
|
|
458
|
+
* killed by the same watchdog.
|
|
459
|
+
*/
|
|
460
|
+
export function shouldRetryAttempt(error: any, attempt: any, remainingMs: any, idleTimeoutMs: any) {
|
|
461
|
+
if (attempt >= 2) return false
|
|
462
|
+
const code = error?.code
|
|
463
|
+
if (code === 'CHILD_TIMEOUT' || code === 'ABORTED' || code === 'TOTAL_TIMEOUT') return false
|
|
464
|
+
if (/aborted|refusal/i.test(String(error?.message ?? ''))) return false
|
|
465
|
+
if (code === 'CHILD_STALLED') return true
|
|
466
|
+
if (code === 'CHILD_NOT_COMPLETED') {
|
|
467
|
+
return Number(remainingMs) > Number(idleTimeoutMs)
|
|
468
|
+
}
|
|
469
|
+
return true
|
|
470
|
+
}
|
|
471
|
+
|
|
375
472
|
async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
|
|
376
473
|
const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options
|
|
377
474
|
let lastError: any = null
|
|
475
|
+
let lastFailure: any = null
|
|
378
476
|
try {
|
|
379
477
|
if (!writeSubtaskStatus(record, subtask.id, {
|
|
380
478
|
status: 'in_progress',
|
|
@@ -411,6 +509,8 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
411
509
|
})),
|
|
412
510
|
cwd: options.cwd,
|
|
413
511
|
conversationContext,
|
|
512
|
+
statuses: record.statuses,
|
|
513
|
+
previousFailure: attempt > 1 ? lastFailure : null,
|
|
414
514
|
}),
|
|
415
515
|
}],
|
|
416
516
|
parent: options.agent,
|
|
@@ -482,50 +582,52 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
482
582
|
)
|
|
483
583
|
}
|
|
484
584
|
if (!output) throw new PlanError('子 Agent 没有返回文本结果', 'EMPTY_CHILD_OUTPUT')
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
}
|
|
496
|
-
writeSubtaskStatus(record, subtask.id, {
|
|
497
|
-
status: 'done',
|
|
498
|
-
progress: 100,
|
|
499
|
-
finishedAt: Date.now(),
|
|
500
|
-
summary: truncate(output, 3000),
|
|
501
|
-
error: null,
|
|
502
|
-
}, guard)
|
|
585
|
+
/*
|
|
586
|
+
* [1.7.0] Evidence decides the verdict.
|
|
587
|
+
*
|
|
588
|
+
* The old rule was "not BLOCKED => done", so a child that reported
|
|
589
|
+
* unverified or failed self-checks was still counted as finished and
|
|
590
|
+
* the main Agent had nothing to review but prose. `adjudicateResult`
|
|
591
|
+
* is the single deterministic table; `settleFromOutput` adds the
|
|
592
|
+
* environment-dependent artifact check.
|
|
593
|
+
*/
|
|
594
|
+
settleFromOutput(record, subtask, output, guard, options)
|
|
503
595
|
return
|
|
504
596
|
} catch (error: any) {
|
|
505
597
|
lastError = error
|
|
506
598
|
if (guard.timedOut) break
|
|
507
599
|
const isAbort = parentSignal.aborted || child.controller.signal.aborted
|
|
600
|
+
const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
|
|
601
|
+
const remaining = deadline - Date.now()
|
|
508
602
|
/*
|
|
509
|
-
*
|
|
603
|
+
* [1.7.0] The retry carries the previous failure with it.
|
|
510
604
|
*
|
|
511
|
-
*
|
|
512
|
-
*
|
|
513
|
-
*
|
|
514
|
-
*
|
|
605
|
+
* Retrying with an identical prompt made the child repeat the same
|
|
606
|
+
* dead end and produced the same error twice. The next attempt now
|
|
607
|
+
* receives the code, message and attempt number, so it can change
|
|
608
|
+
* approach — or stop honestly.
|
|
515
609
|
*/
|
|
516
|
-
|
|
517
|
-
|
|
610
|
+
lastFailure = {
|
|
611
|
+
attempt,
|
|
612
|
+
code: error?.code ?? 'UNKNOWN',
|
|
613
|
+
message: describeError(error),
|
|
614
|
+
}
|
|
615
|
+
const retry = !isAbort && shouldRetryAttempt(error, attempt, remaining, idleTimeoutMs)
|
|
616
|
+
if (retry) {
|
|
518
617
|
record.errors = [
|
|
519
618
|
...record.errors,
|
|
520
|
-
`${subtask.id}: 第 ${attempt}
|
|
619
|
+
`${subtask.id}: 第 ${attempt} 次执行失败(${lastFailure.code}),已带上失败原因重试`,
|
|
521
620
|
].slice(-20)
|
|
522
621
|
writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard)
|
|
523
622
|
continue
|
|
524
623
|
}
|
|
525
|
-
if (isAbort
|
|
526
|
-
|
|
624
|
+
if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
|
|
625
|
+
record.errors = [
|
|
626
|
+
...record.errors,
|
|
627
|
+
`${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
|
|
628
|
+
].slice(-20)
|
|
527
629
|
}
|
|
528
|
-
|
|
630
|
+
break
|
|
529
631
|
} finally {
|
|
530
632
|
if (activation) {
|
|
531
633
|
await disposeActivation(activation, record, subtask.id, guard)
|
|
@@ -652,6 +754,31 @@ async function runWithConcurrency(items: any, limit: any, worker: any) {
|
|
|
652
754
|
* @param limits - resolved runtime limits (the resume budget comes from here).
|
|
653
755
|
* @returns a user message carrying the `workplan-result` payload.
|
|
654
756
|
*/
|
|
757
|
+
/**
|
|
758
|
+
* The subtask rows a dispatch/status tool returns to the model.
|
|
759
|
+
*
|
|
760
|
+
* One definition, because the same plan was described in three slightly
|
|
761
|
+
* different shapes (dispatch tail, already-running branch, status tool) and the
|
|
762
|
+
* model could see three different answers in one turn.
|
|
763
|
+
*/
|
|
764
|
+
export function modelStatusLines(statuses: any) {
|
|
765
|
+
const list = Array.isArray(statuses) ? statuses : []
|
|
766
|
+
return list.map((item: any) => ({
|
|
767
|
+
subtaskId: item.subtaskId,
|
|
768
|
+
title: item.title,
|
|
769
|
+
department: item.department,
|
|
770
|
+
status: item.status,
|
|
771
|
+
progress: item.progress,
|
|
772
|
+
summary: truncate(item.summary ?? item.error ?? '', 2000),
|
|
773
|
+
error: item.error ?? null,
|
|
774
|
+
verification: item.verification ?? null,
|
|
775
|
+
revision: Number(item.revision ?? 0),
|
|
776
|
+
updatedBy: item.updatedBy ?? null,
|
|
777
|
+
missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
|
|
778
|
+
needs: Array.isArray(item.needs) ? item.needs : [],
|
|
779
|
+
}))
|
|
780
|
+
}
|
|
781
|
+
|
|
655
782
|
export function buildRoundResult(record: any, sessionId: any, limits: any) {
|
|
656
783
|
const { statuses, stats } = derivePlanSnapshot(record.statuses)
|
|
657
784
|
return buildResultMessage({
|
|
@@ -725,7 +852,18 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
725
852
|
if (guard > 200) throw new PlanError('调度次数异常', 'DISPATCH_LOOP')
|
|
726
853
|
if (parentSignal.aborted) throw abortError()
|
|
727
854
|
if (Date.now() >= deadline) throw new PlanError('总执行超时', 'TOTAL_TIMEOUT')
|
|
728
|
-
|
|
855
|
+
/*
|
|
856
|
+
* [1.7.0] A `done` upstream only unblocks its dependents when the files it
|
|
857
|
+
* declared actually exist. The check is opt-out (`artifactGate:false`) so
|
|
858
|
+
* an older plan or a debugging session can keep plain status semantics.
|
|
859
|
+
*/
|
|
860
|
+
const gate = options.artifactGate !== false
|
|
861
|
+
const ready = readySubtasks(record.plan, record.statuses, gate
|
|
862
|
+
? {
|
|
863
|
+
dependencyOk: (dependency: any) => dependency?.status === 'done'
|
|
864
|
+
&& !(Array.isArray(dependency?.missingArtifacts) && dependency.missingArtifacts.length > 0),
|
|
865
|
+
}
|
|
866
|
+
: {})
|
|
729
867
|
if (ready.length === 0) {
|
|
730
868
|
const pending = record.statuses.filter((item: any) => item.status === 'pending')
|
|
731
869
|
for (const item of pending) {
|
|
@@ -752,13 +890,27 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
752
890
|
modelSelection,
|
|
753
891
|
cwd,
|
|
754
892
|
conversationContext,
|
|
893
|
+
strictEvidence: options.strictEvidence,
|
|
894
|
+
artifactExists: options.artifactExists,
|
|
755
895
|
})
|
|
756
896
|
})
|
|
757
897
|
const blocked = record.statuses
|
|
758
898
|
.filter((item: any) => item.status === 'blocked')
|
|
759
899
|
.map((item: any) => item.subtaskId)
|
|
760
900
|
for (const id of blocked) {
|
|
761
|
-
|
|
901
|
+
/*
|
|
902
|
+
* Carry the actual cause downstream. The main Agent used to receive
|
|
903
|
+
* "上游子任务受阻: T2" with no reason and no missing artifacts, so it
|
|
904
|
+
* had to re-read the whole plan to guess what to repair.
|
|
905
|
+
*/
|
|
906
|
+
const upstream = record.statuses.find((item: any) => item.subtaskId === id)
|
|
907
|
+
const cause = upstream
|
|
908
|
+
? {
|
|
909
|
+
reason: upstream.error,
|
|
910
|
+
missingArtifacts: Array.isArray(upstream.missingArtifacts) ? upstream.missingArtifacts : [],
|
|
911
|
+
}
|
|
912
|
+
: null
|
|
913
|
+
record.statuses = markDependentsBlocked(record.plan, record.statuses, id, cause)
|
|
762
914
|
}
|
|
763
915
|
/*
|
|
764
916
|
* No stats refresh here any more: `serialisePlan` derives the counts from
|
|
@@ -856,6 +1008,58 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
856
1008
|
return record
|
|
857
1009
|
}
|
|
858
1010
|
|
|
1011
|
+
/*
|
|
1012
|
+
* [1.6.0] 会话「这一轮到底还在不在跑」的唯一事实源。
|
|
1013
|
+
*
|
|
1014
|
+
* 事故(session-7129faea…):会话早已结束,面板仍把计划列在「进行中」组,
|
|
1015
|
+
* 卡片写着「预算用完,可续跑」——没有任何东西在跑,状态却表示正在跑。
|
|
1016
|
+
*
|
|
1017
|
+
* 根因:插件只订阅 `agent/pre-step`,`turn/end`、`session/disposed` 全都收不到;
|
|
1018
|
+
* 计划状态因此只由「派发结果」驱动,而派发结束后不再有任何事件把它收敛。
|
|
1019
|
+
*
|
|
1020
|
+
* 修复不引入第二个事件订阅(跨 scope 的事件投递受 scope 过滤,不可靠;而且
|
|
1021
|
+
* 订阅只覆盖实时路径,刷新/重启后全靠回放,两条链路一旦不同源就会来回翻转)。
|
|
1022
|
+
* 这里直接读会话日志本身——它既是实时事实,也是回放事实:
|
|
1023
|
+
*
|
|
1024
|
+
* - 从末尾向前找最近的一条「轮次边界」事件:先遇到 `turn/end` ⇒ 这一轮已结束;
|
|
1025
|
+
* 先遇到 `turn/start` ⇒ 这一轮还开着;都没找到 ⇒ 未知,调用方保持原判定。
|
|
1026
|
+
* - 不存在「会话已结束」这种事件:宿主只有每轮 `turn/end`。因此**不能**把
|
|
1027
|
+
* `turn/end` 直接等同于「计划取消/完成」——一轮结束后可以随时续跑,这也是
|
|
1028
|
+
* 卡片提供「可续跑」的原因。它只证明「此刻没有东西在跑」。
|
|
1029
|
+
* - 向后扫描设上限,避免越界;超过上限就返回 unknown,绝不猜测。
|
|
1030
|
+
*/
|
|
1031
|
+
const TURN_BOUNDARY_SCAN = 200
|
|
1032
|
+
|
|
1033
|
+
export function sessionTurnState(session: any) {
|
|
1034
|
+
const total = Number(session?.seq)
|
|
1035
|
+
if (!Number.isFinite(total) || total <= 0 || typeof session?.eventAt !== 'function') {
|
|
1036
|
+
return { state: 'unknown', reason: null, reasonDetail: null, at: null }
|
|
1037
|
+
}
|
|
1038
|
+
const floor = Math.max(0, Math.floor(total) - TURN_BOUNDARY_SCAN)
|
|
1039
|
+
for (let seq = Math.floor(total) - 1; seq >= floor; seq -= 1) {
|
|
1040
|
+
let event
|
|
1041
|
+
try {
|
|
1042
|
+
event = session.eventAt(seq)
|
|
1043
|
+
} catch {
|
|
1044
|
+
return { state: 'unknown', reason: null, reasonDetail: null, at: null }
|
|
1045
|
+
}
|
|
1046
|
+
if (!event) continue
|
|
1047
|
+
if (event.type === 'turn/start') return { state: 'open', reason: null, reasonDetail: null, at: null }
|
|
1048
|
+
if (event.type === 'turn/end') {
|
|
1049
|
+
const reason = event.data?.reason ?? null
|
|
1050
|
+
const detail = reason && reason.kind === 'aborted' ? (reason.reason?.kind ?? null) : null
|
|
1051
|
+
const at = Number(event.time)
|
|
1052
|
+
return {
|
|
1053
|
+
state: 'ended',
|
|
1054
|
+
reason: typeof reason?.kind === 'string' ? reason.kind : 'completed',
|
|
1055
|
+
reasonDetail: typeof detail === 'string' ? detail : null,
|
|
1056
|
+
at: Number.isFinite(at) ? at : null,
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
return { state: 'unknown', reason: null, reasonDetail: null, at: null }
|
|
1061
|
+
}
|
|
1062
|
+
|
|
859
1063
|
function serialisePlan(record: any, session: any) {
|
|
860
1064
|
const plan = record.plan ?? null
|
|
861
1065
|
/*
|
|
@@ -888,6 +1092,36 @@ function serialisePlan(record: any, session: any) {
|
|
|
888
1092
|
if (phase === 'pending' && !record.dispatchedAt && plan?.createdAt && Date.now() - plan.createdAt > STALE_PENDING_MS) {
|
|
889
1093
|
phase = 'cancelled'
|
|
890
1094
|
}
|
|
1095
|
+
/*
|
|
1096
|
+
* [1.6.0] 终态收敛:这一轮已经结束,而计划没有完成 ⇒ 不许再显示「进行中」。
|
|
1097
|
+
*
|
|
1098
|
+
* `phase` 到这里为止只由「派发动作」写入(executing / paused / blocked …),
|
|
1099
|
+
* 而派发结束后没有任何事件把它改回来,于是会话结束、进程空闲、面板却仍在
|
|
1100
|
+
* 「进行中」组里(事故截图)。上面 `sessionTurnState` 用会话日志回答
|
|
1101
|
+
* 「此刻还有没有东西在跑」,这里把答案落成独立阶段 `ended`:
|
|
1102
|
+
*
|
|
1103
|
+
* - done / cancelled 已经是终态,不再改写(done 改写会直接违反不变量 I8);
|
|
1104
|
+
* - 其余阶段一律收敛为 `ended`,并把原阶段留在 `suspendedPhase` 里,
|
|
1105
|
+
* 卡片因此仍能显示「预算用完,可续跑」「卡住了」这类二级事实,不丢信息;
|
|
1106
|
+
* - 只改**下发出去的那一份**,不动 `record.phase`:用户说「继续」后同一轮
|
|
1107
|
+
* 重新开始(日志里出现新的 turn/start),下一份 payload 自然回到原来的
|
|
1108
|
+
* 派发状态,不需要任何反向迁移逻辑;
|
|
1109
|
+
* - 实时路径与回放路径都经过本函数,因此刷新前后结论必然一致(T4 硬约束)。
|
|
1110
|
+
*/
|
|
1111
|
+
let suspendedPhase: any = null
|
|
1112
|
+
let endReason: any = null
|
|
1113
|
+
let endReasonDetail: any = null
|
|
1114
|
+
let endedAt: any = null
|
|
1115
|
+
if (phase !== 'done' && phase !== 'cancelled') {
|
|
1116
|
+
const turn = sessionTurnState(session)
|
|
1117
|
+
if (turn.state === 'ended') {
|
|
1118
|
+
suspendedPhase = phase
|
|
1119
|
+
endReason = turn.reason
|
|
1120
|
+
endReasonDetail = turn.reasonDetail
|
|
1121
|
+
endedAt = turn.at
|
|
1122
|
+
phase = 'ended'
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
891
1125
|
/*
|
|
892
1126
|
* 每次真正下发前跑一遍跨字段不变量(I1–I10)。正常情况下恒为空;一旦某个
|
|
893
1127
|
* 未来改动重新引入「进度与状态打架」,这里会把它连同具体字段值一起带出去,
|
|
@@ -899,6 +1133,7 @@ function serialisePlan(record: any, session: any) {
|
|
|
899
1133
|
planId: record.planId ?? plan?.planId ?? null,
|
|
900
1134
|
title: plan?.title ?? record.title ?? '任务进度',
|
|
901
1135
|
phase,
|
|
1136
|
+
...(phase === 'ended' ? { suspendedPhase, endReason, endReasonDetail, endedAt } : {}),
|
|
902
1137
|
...(violations.length ? { violations } : {}),
|
|
903
1138
|
degraded: record.degraded === true,
|
|
904
1139
|
error: record.error ? truncate(record.error, 2000) : null,
|
|
@@ -966,6 +1201,8 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
966
1201
|
* plan and let the caller ask for a specific one.
|
|
967
1202
|
*/
|
|
968
1203
|
const finished: any[] = []
|
|
1204
|
+
/** [1.6.0] callId → 待确认的 update 写入;只有配对的 tool/result 才能定案。 */
|
|
1205
|
+
const pendingToolCalls = new Map<string, any>()
|
|
969
1206
|
const snapshot = () => ({ plan, statuses, resultPhase, resultSeen, resumeCount, cancelled })
|
|
970
1207
|
for (let seq = start; seq < session.seq; seq += 1) {
|
|
971
1208
|
let event
|
|
@@ -1008,24 +1245,70 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
1008
1245
|
resultPhase = typeof result.phase === 'string' ? result.phase : ''
|
|
1009
1246
|
resultSeen = true
|
|
1010
1247
|
}
|
|
1248
|
+
/*
|
|
1249
|
+
* [1.7.0] Manual re-adjudications replay in order.
|
|
1250
|
+
*
|
|
1251
|
+
* `dsh_workplan_update` used to live only in the live cache, so a refresh
|
|
1252
|
+
* reverted the dashboard to the child's original verdict. The durable
|
|
1253
|
+
* `workplan-update` message is small and append-only, so replay is just
|
|
1254
|
+
* "apply it when its turn comes"; a lower revision never overwrites a
|
|
1255
|
+
* newer one (see `applyResultStatuses`).
|
|
1256
|
+
*/
|
|
1257
|
+
const update = parseUpdateMessage(event.data)
|
|
1258
|
+
if (update && plan && update.planId === plan.planId && typeof update.subtaskId === 'string') {
|
|
1259
|
+
try {
|
|
1260
|
+
statuses = applyStatus(statuses, update.subtaskId, {
|
|
1261
|
+
status: update.status,
|
|
1262
|
+
progress: typeof update.progress === 'number' ? update.progress : undefined,
|
|
1263
|
+
summary: typeof update.note === 'string' ? update.note : undefined,
|
|
1264
|
+
revision: Number.isInteger(update.revision) ? update.revision : undefined,
|
|
1265
|
+
updatedBy: 'agent',
|
|
1266
|
+
})
|
|
1267
|
+
} catch {
|
|
1268
|
+
// An invalid historical update is ignored; the rest still replays.
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1011
1271
|
const cancel = parseCancelMessage(event.data)
|
|
1012
1272
|
if (cancel && plan && cancel.planId === plan.planId) {
|
|
1013
1273
|
cancelled = true
|
|
1014
1274
|
}
|
|
1015
1275
|
} else if (event.type === 'tool/call' && plan) {
|
|
1276
|
+
/*
|
|
1277
|
+
* [1.6.0] 只登记,不下结论。
|
|
1278
|
+
*
|
|
1279
|
+
* 回放原来一见到 `dsh_workplan_update` 的调用就 applyStatus,但调用发起不等于
|
|
1280
|
+
* 状态写入成功:宿主的 tool/result 带着 `message.isError`。会话
|
|
1281
|
+
* session-7129faea 里就有一次失败的 update 被回放记成完成,于是刷新后面板显示
|
|
1282
|
+
* 7/12,而真实只完成 6/12 —— 回放比实时“更乐观”,这是第二个数据源打架点。
|
|
1283
|
+
* 现在一律等对应的 tool/result:成功才采纳,失败或没有结果都不采纳。
|
|
1284
|
+
*/
|
|
1016
1285
|
const data = event.data
|
|
1017
|
-
if (data?.name === 'dsh_workplan_update') {
|
|
1286
|
+
if (data?.name === 'dsh_workplan_update' && typeof data.callId === 'string') {
|
|
1018
1287
|
const args = readToolArguments(data.arguments)
|
|
1019
1288
|
if (args && typeof args.subtaskId === 'string' && typeof args.status === 'string') {
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1289
|
+
pendingToolCalls.set(data.callId, { args, planId: plan.planId })
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
} else if (event.type === 'tool/result') {
|
|
1293
|
+
const message = event.data?.message
|
|
1294
|
+
const callId = message?.role === 'tool' ? message.toolCallId : null
|
|
1295
|
+
if (typeof callId !== 'string') continue
|
|
1296
|
+
const pending = pendingToolCalls.get(callId)
|
|
1297
|
+
pendingToolCalls.delete(callId)
|
|
1298
|
+
if (!pending || !plan || pending.planId !== plan.planId) {
|
|
1299
|
+
// 结果晚于新计划到达:旧计划的写入不污染新计划的状态表。
|
|
1300
|
+
} else if (message.isError === true) {
|
|
1301
|
+
// 失败的更新不是完成:状态表保持原样。
|
|
1302
|
+
} else {
|
|
1303
|
+
const args = pending.args
|
|
1304
|
+
try {
|
|
1305
|
+
statuses = applyStatus(statuses, args.subtaskId, {
|
|
1306
|
+
status: args.status,
|
|
1307
|
+
progress: typeof args.progress === 'number' ? args.progress : undefined,
|
|
1308
|
+
summary: typeof args.note === 'string' ? args.note : undefined,
|
|
1309
|
+
})
|
|
1310
|
+
} catch {
|
|
1311
|
+
// An invalid historical call is ignored; the live cache remains authoritative.
|
|
1029
1312
|
}
|
|
1030
1313
|
}
|
|
1031
1314
|
}
|
|
@@ -1177,7 +1460,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1177
1460
|
}
|
|
1178
1461
|
if (downstream?.kind !== 'enter') return downstream
|
|
1179
1462
|
try {
|
|
1180
|
-
return await maybePlan(ctx, state, payload, downstream, options)
|
|
1463
|
+
return await maybePlan(ctx, state, payload, downstream, { ...options, limits })
|
|
1181
1464
|
} catch (error) {
|
|
1182
1465
|
try {
|
|
1183
1466
|
const session = payload.agent?.session
|
|
@@ -1232,14 +1515,77 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1232
1515
|
? args.evidence.filter((item: any) => typeof item === 'string').join(';')
|
|
1233
1516
|
: ''
|
|
1234
1517
|
const summary = [note, evidence].filter(Boolean).join('|')
|
|
1518
|
+
const current = record.statuses.find((item: any) => item.subtaskId === subtaskId)
|
|
1519
|
+
/*
|
|
1520
|
+
* [1.7.0] Two write guards, both non-throwing.
|
|
1521
|
+
*
|
|
1522
|
+
* 1. A stale revision means the caller is looking at an older snapshot; the
|
|
1523
|
+
* write is refused instead of silently overwriting newer evidence.
|
|
1524
|
+
* 2. While the plan is running, the child owns the status of the subtask it
|
|
1525
|
+
* is executing. An agent edit would race the child's settlement (and the
|
|
1526
|
+
* child would overwrite it back). `force:true` is the explicit override,
|
|
1527
|
+
* recorded as a manual re-adjudication.
|
|
1528
|
+
*/
|
|
1529
|
+
if (Number.isInteger(args?.expectedRevision) && (current?.revision ?? 0) !== args.expectedRevision) {
|
|
1530
|
+
return {
|
|
1531
|
+
ok: false,
|
|
1532
|
+
code: 'STALE_WRITE',
|
|
1533
|
+
planId: record.plan.planId,
|
|
1534
|
+
subtaskId,
|
|
1535
|
+
current: {
|
|
1536
|
+
status: current?.status ?? null,
|
|
1537
|
+
revision: current?.revision ?? 0,
|
|
1538
|
+
updatedBy: current?.updatedBy ?? null,
|
|
1539
|
+
},
|
|
1540
|
+
hint: `该子任务已被更新(当前 revision ${current?.revision ?? 0},你基于 ${args.expectedRevision});请重新读取状态后再改。`,
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
const running = Boolean(record.dispatchPromise)
|
|
1544
|
+
const writeWhileRunning = running && !args?.force && (current?.status === 'pending' || current?.status === 'in_progress')
|
|
1545
|
+
if (writeWhileRunning) {
|
|
1546
|
+
return {
|
|
1547
|
+
ok: false,
|
|
1548
|
+
code: 'TASK_RUNNING',
|
|
1549
|
+
planId: record.plan.planId,
|
|
1550
|
+
subtaskId,
|
|
1551
|
+
current: {
|
|
1552
|
+
status: current?.status ?? null,
|
|
1553
|
+
revision: current?.revision ?? 0,
|
|
1554
|
+
updatedBy: current?.updatedBy ?? null,
|
|
1555
|
+
},
|
|
1556
|
+
hint: '该子任务正在执行;请等待本轮结束,或传 force:true 覆盖(会被记录为人工改判)。',
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
const revision = Number(current?.revision ?? 0) + 1
|
|
1235
1560
|
record.statuses = applyStatus(record.statuses, subtaskId, {
|
|
1236
1561
|
status,
|
|
1237
1562
|
progress: typeof args?.progress === 'number' ? args.progress : undefined,
|
|
1238
1563
|
summary: summary || undefined,
|
|
1239
1564
|
error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
|
|
1565
|
+
revision,
|
|
1566
|
+
updatedBy: 'agent',
|
|
1240
1567
|
})
|
|
1241
1568
|
if (status === 'blocked') {
|
|
1242
|
-
record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId)
|
|
1569
|
+
record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId, { reason: summary || '主 Agent 标记受阻' })
|
|
1570
|
+
}
|
|
1571
|
+
/*
|
|
1572
|
+
* [1.7.0] A re-adjudication is durable.
|
|
1573
|
+
*
|
|
1574
|
+
* `applyStatus` only touched the in-memory record, so after a refresh the
|
|
1575
|
+
* manual verdict vanished and the dashboard fell back to the old child
|
|
1576
|
+
* result. Appending one small message keeps the replay path honest.
|
|
1577
|
+
*/
|
|
1578
|
+
try {
|
|
1579
|
+
session.append('user/message', buildUpdateMessage({
|
|
1580
|
+
planId: record.plan.planId,
|
|
1581
|
+
subtaskId,
|
|
1582
|
+
status,
|
|
1583
|
+
progress: typeof args?.progress === 'number' ? args.progress : undefined,
|
|
1584
|
+
note: summary || undefined,
|
|
1585
|
+
revision,
|
|
1586
|
+
}), { surfaceOp: 'append' })
|
|
1587
|
+
} catch (error) {
|
|
1588
|
+
pushRecordError(record, error)
|
|
1243
1589
|
}
|
|
1244
1590
|
/*
|
|
1245
1591
|
* [1.5.2] 这里曾是「100% + 正在收尾」的直接入口。
|
|
@@ -1253,11 +1599,14 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1253
1599
|
record.phase = reconcilePhase(record.phase, record.statuses)
|
|
1254
1600
|
record.updatedAt = Date.now()
|
|
1255
1601
|
const snapshot = derivePlanSnapshot(record.statuses)
|
|
1602
|
+
const written = snapshot.statuses.find((item: any) => item.subtaskId === subtaskId)
|
|
1256
1603
|
return {
|
|
1257
1604
|
ok: true,
|
|
1258
1605
|
planId: record.plan.planId,
|
|
1259
1606
|
subtaskId,
|
|
1260
|
-
status:
|
|
1607
|
+
status: written?.status ?? status,
|
|
1608
|
+
revision: written?.revision ?? revision,
|
|
1609
|
+
updatedBy: written?.updatedBy ?? 'agent',
|
|
1261
1610
|
stats: snapshot.stats,
|
|
1262
1611
|
}
|
|
1263
1612
|
}
|
|
@@ -1342,6 +1691,91 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1342
1691
|
}
|
|
1343
1692
|
}
|
|
1344
1693
|
|
|
1694
|
+
/**
|
|
1695
|
+
* Persist the round result and settle the phase.
|
|
1696
|
+
*
|
|
1697
|
+
* Extracted from the wait path so an async dispatch reaches exactly the same
|
|
1698
|
+
* end state: a durable result message plus a reconciled phase. Anything less
|
|
1699
|
+
* would make "start now, read later" a second, divergent code path.
|
|
1700
|
+
*/
|
|
1701
|
+
function finishRound(record: any, session: any) {
|
|
1702
|
+
if (!record.resultWritten) {
|
|
1703
|
+
const resultMessage = buildRoundResult(record, session.id, limits)
|
|
1704
|
+
try {
|
|
1705
|
+
session.append('user/message', resultMessage, { surfaceOp: 'append' })
|
|
1706
|
+
record.resultWritten = true
|
|
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
|
+
|
|
1722
|
+
function dispatchSnapshotOf(record: any, extra: any = {}) {
|
|
1723
|
+
const snapshot = derivePlanSnapshot(record.statuses)
|
|
1724
|
+
return {
|
|
1725
|
+
ok: true,
|
|
1726
|
+
planId: record.plan.planId,
|
|
1727
|
+
alreadyRunning: false,
|
|
1728
|
+
...extra,
|
|
1729
|
+
phase: record.phase,
|
|
1730
|
+
stats: snapshot.stats,
|
|
1731
|
+
statuses: modelStatusLines(snapshot.statuses),
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
/**
|
|
1736
|
+
* Read-only progress probe for the main Agent.
|
|
1737
|
+
*
|
|
1738
|
+
* With async dispatch the model no longer blocks until the round ends, so it
|
|
1739
|
+
* needs a supported way to answer "做成什么样了" without guessing. This is the
|
|
1740
|
+
* only source it should read: same `derivePlanSnapshot` as the dashboard and
|
|
1741
|
+
* the result message, so all three cannot disagree.
|
|
1742
|
+
*/
|
|
1743
|
+
async function statusTool(agent: any, args: any) {
|
|
1744
|
+
const session = agent?.session
|
|
1745
|
+
if (!session) throw new PlanError('只能在会话内查看计划', 'NO_SESSION')
|
|
1746
|
+
const requestedPlanId = typeof args?.planId === 'string' ? args.planId : undefined
|
|
1747
|
+
let record = state.records.get(session.id)
|
|
1748
|
+
if (!record?.plan || (requestedPlanId && record.plan.planId !== requestedPlanId)) {
|
|
1749
|
+
const rebuilt = reconstructFromSession(session, requestedPlanId)
|
|
1750
|
+
if (rebuilt?.plan) 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
|
+
}
|
|
1778
|
+
|
|
1345
1779
|
async function dispatchTool(agent: any, args: any, signal: any) {
|
|
1346
1780
|
const session = agent?.session
|
|
1347
1781
|
if (!session) throw new PlanError('只能在会话内派发计划', 'NO_SESSION')
|
|
@@ -1383,6 +1817,35 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1383
1817
|
if (args?.planId && record.plan.planId !== args.planId) {
|
|
1384
1818
|
throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
|
|
1385
1819
|
}
|
|
1820
|
+
/*
|
|
1821
|
+
* [1.7.0] Two dispatch modes.
|
|
1822
|
+
*
|
|
1823
|
+
* `wait` (default, backward compatible) blocks until the round ends.
|
|
1824
|
+
* `async` starts the round and returns immediately, so the main Agent can
|
|
1825
|
+
* answer the user and keep integrating instead of sitting blind inside a
|
|
1826
|
+
* tool call for twenty minutes (the top-ranked collaboration break C1).
|
|
1827
|
+
*/
|
|
1828
|
+
const mode = args?.mode === 'async' ? 'async' : 'wait'
|
|
1829
|
+
if (mode === 'wait' && record.dispatchPromise) {
|
|
1830
|
+
/*
|
|
1831
|
+
* A wait caller that meets an in-flight round joins it instead of being
|
|
1832
|
+
* told "already running" — the old answer carried no results at all, so
|
|
1833
|
+
* a model that missed the async result message had nothing to integrate.
|
|
1834
|
+
* A wedged promise keeps the old stale escape hatch (see below).
|
|
1835
|
+
*/
|
|
1836
|
+
const startedAt = Number(record.dispatchStartedAt ?? 0)
|
|
1837
|
+
const staleAfter = limits.totalTimeoutMs + 120000
|
|
1838
|
+
if (!(startedAt > 0 && Date.now() - startedAt > staleAfter)) {
|
|
1839
|
+
try {
|
|
1840
|
+
await record.dispatchPromise
|
|
1841
|
+
} catch (error) {
|
|
1842
|
+
pushRecordError(record, error)
|
|
1843
|
+
}
|
|
1844
|
+
finishRound(record, session)
|
|
1845
|
+
state.records.set(session.id, record)
|
|
1846
|
+
return dispatchSnapshotOf(record, { joined: true })
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1386
1849
|
if (record.dispatchPromise) {
|
|
1387
1850
|
/*
|
|
1388
1851
|
* "Already running" must not become a permanent answer.
|
|
@@ -1409,7 +1872,25 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1409
1872
|
hint: '请主 Agent 直接接手完成剩余子任务,不要再次派发;并在答复中说明本次是直接执行而非派发。',
|
|
1410
1873
|
}
|
|
1411
1874
|
}
|
|
1412
|
-
|
|
1875
|
+
/*
|
|
1876
|
+
* [1.7.0] The idempotent answer now carries the progress itself.
|
|
1877
|
+
*
|
|
1878
|
+
* It used to say only `alreadyRunning: true`, so a second dispatch gave
|
|
1879
|
+
* the model strictly less information than doing nothing.
|
|
1880
|
+
*/
|
|
1881
|
+
const live = derivePlanSnapshot(record.statuses)
|
|
1882
|
+
return {
|
|
1883
|
+
ok: true,
|
|
1884
|
+
planId: record.plan.planId,
|
|
1885
|
+
alreadyRunning: true,
|
|
1886
|
+
running: true,
|
|
1887
|
+
phase: record.phase,
|
|
1888
|
+
startedAt: startedAt || null,
|
|
1889
|
+
elapsedMs: startedAt ? Date.now() - startedAt : null,
|
|
1890
|
+
stats: live.stats,
|
|
1891
|
+
statuses: modelStatusLines(live.statuses),
|
|
1892
|
+
hint: '计划仍在执行:先向用户报告进度,不要声称完成;用 dsh_workplan_status 查看实时状态。',
|
|
1893
|
+
}
|
|
1413
1894
|
}
|
|
1414
1895
|
/*
|
|
1415
1896
|
* Refuse with an explanation instead of silently "succeeding".
|
|
@@ -1468,46 +1949,47 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1468
1949
|
record.abortDispatch = null
|
|
1469
1950
|
signal?.removeEventListener?.('abort', onToolAbort)
|
|
1470
1951
|
})
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1952
|
+
if (mode === 'async') {
|
|
1953
|
+
/*
|
|
1954
|
+
* Settlement happens in the background: the same durable result message
|
|
1955
|
+
* is appended when the round ends, so a page refresh (or a later turn)
|
|
1956
|
+
* still sees the outcome. The returned values are a *starting* snapshot,
|
|
1957
|
+
* never a completion claim.
|
|
1958
|
+
*/
|
|
1959
|
+
const startedAt = record.dispatchStartedAt
|
|
1960
|
+
record.dispatchPromise
|
|
1961
|
+
.then(() => {
|
|
1962
|
+
finishRound(record, session)
|
|
1963
|
+
state.records.set(session.id, record)
|
|
1964
|
+
})
|
|
1965
|
+
.catch((error: any) => {
|
|
1966
|
+
pushRecordError(record, error)
|
|
1967
|
+
finishRound(record, session)
|
|
1968
|
+
state.records.set(session.id, record)
|
|
1969
|
+
})
|
|
1970
|
+
const live = derivePlanSnapshot(record.statuses)
|
|
1971
|
+
return {
|
|
1972
|
+
ok: true,
|
|
1973
|
+
planId: record.plan.planId,
|
|
1974
|
+
mode: 'async',
|
|
1975
|
+
running: true,
|
|
1976
|
+
alreadyRunning: false,
|
|
1977
|
+
phase: record.phase,
|
|
1978
|
+
startedAt,
|
|
1979
|
+
stats: live.stats,
|
|
1980
|
+
statuses: modelStatusLines(live.statuses),
|
|
1981
|
+
hint: '计划已开跑,尚未完成:先向用户说明“已派发、正在执行”,不要声称完成;'
|
|
1982
|
+
+ '结果消息会在本轮结束时自动出现,期间可用 dsh_workplan_status 查看进度。',
|
|
1479
1983
|
}
|
|
1480
1984
|
}
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
*
|
|
1484
|
-
* 旧代码只有 `record.resultWritten === true` 时才把 phase 升成 done,
|
|
1485
|
-
* 于是 session.append 抛错(或该轮根本没有派发)就会永久停在 integrating。
|
|
1486
|
-
* 完成语义由 statuses 决定;结果消息只负责持久化,不负责定义完成。
|
|
1487
|
-
*/
|
|
1488
|
-
record.phase = reconcilePhase(record.phase, record.statuses)
|
|
1985
|
+
await record.dispatchPromise
|
|
1986
|
+
finishRound(record, session)
|
|
1489
1987
|
/*
|
|
1490
1988
|
* The model's dispatch result reports the same snapshot the dashboard will
|
|
1491
1989
|
* show. It used to send `record.stats` while the status list below was read
|
|
1492
1990
|
* fresh, so one reply could say “已完成 11” next to twelve finished rows.
|
|
1493
1991
|
*/
|
|
1494
|
-
|
|
1495
|
-
return {
|
|
1496
|
-
ok: true,
|
|
1497
|
-
planId: record.plan.planId,
|
|
1498
|
-
alreadyRunning: false,
|
|
1499
|
-
phase: record.phase,
|
|
1500
|
-
stats: snapshot.stats,
|
|
1501
|
-
statuses: snapshot.statuses.map((item: any) => ({
|
|
1502
|
-
subtaskId: item.subtaskId,
|
|
1503
|
-
title: item.title,
|
|
1504
|
-
department: item.department,
|
|
1505
|
-
status: item.status,
|
|
1506
|
-
progress: item.progress,
|
|
1507
|
-
summary: truncate(item.summary ?? item.error ?? '', 2000),
|
|
1508
|
-
error: item.error ?? null,
|
|
1509
|
-
})),
|
|
1510
|
-
}
|
|
1992
|
+
return dispatchSnapshotOf(record)
|
|
1511
1993
|
}
|
|
1512
1994
|
|
|
1513
1995
|
function plansPayload(sessionId: any) {
|
|
@@ -1586,6 +2068,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1586
2068
|
updateStatus,
|
|
1587
2069
|
cancelPlan,
|
|
1588
2070
|
dispatchTool,
|
|
2071
|
+
statusTool,
|
|
1589
2072
|
plansPayload,
|
|
1590
2073
|
route,
|
|
1591
2074
|
dispose,
|
|
@@ -1691,6 +2174,18 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
1691
2174
|
modelSelection,
|
|
1692
2175
|
signal: payload.signal,
|
|
1693
2176
|
conversationContext,
|
|
2177
|
+
/*
|
|
2178
|
+
* Hand the real limits to the planner. Without them it had no idea the
|
|
2179
|
+
* round budget was 20 minutes and happily planned 15 heavy subtasks,
|
|
2180
|
+
* which then died at the budget wall. The prompt now states the budget
|
|
2181
|
+
* and asks for `estimateMinutes` on every subtask.
|
|
2182
|
+
*/
|
|
2183
|
+
budget: {
|
|
2184
|
+
totalMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
|
|
2185
|
+
childMinutes: Math.max(1, Math.round(Number(options?.limits?.childTimeoutMs ?? CHILD_TIMEOUT_MS) / 60000)),
|
|
2186
|
+
concurrency: MAX_CONCURRENT,
|
|
2187
|
+
maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
|
|
2188
|
+
},
|
|
1694
2189
|
})
|
|
1695
2190
|
} catch (error) {
|
|
1696
2191
|
if (payload.signal.aborted) return downstream
|
|
@@ -1751,7 +2246,10 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
1751
2246
|
* tool appends the durable result after the children finish, and tools.guard
|
|
1752
2247
|
* stops the main Agent from doing other work before dispatching.
|
|
1753
2248
|
*/
|
|
1754
|
-
const planMessage = buildPlanMessage(fullPlan
|
|
2249
|
+
const planMessage = buildPlanMessage(fullPlan, {
|
|
2250
|
+
totalBudgetMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
|
|
2251
|
+
maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
|
|
2252
|
+
})
|
|
1755
2253
|
if (!planMode) return enterDecision(downstream, [planMessage])
|
|
1756
2254
|
/*
|
|
1757
2255
|
* Plan mode is a planning-only collaboration state: the plugin must still
|
|
@@ -1801,6 +2299,28 @@ export function updateToolOutputSchema() {
|
|
|
1801
2299
|
}
|
|
1802
2300
|
}
|
|
1803
2301
|
|
|
2302
|
+
export function statusToolOutputSchema() {
|
|
2303
|
+
return {
|
|
2304
|
+
type: 'object',
|
|
2305
|
+
properties: {
|
|
2306
|
+
ok: { type: 'boolean' },
|
|
2307
|
+
planId: { type: 'string' },
|
|
2308
|
+
running: { type: 'boolean' },
|
|
2309
|
+
phase: { type: 'string' },
|
|
2310
|
+
elapsedMs: { type: ['number', 'null'] },
|
|
2311
|
+
stats: { type: 'object' },
|
|
2312
|
+
statuses: { type: 'array' },
|
|
2313
|
+
errors: { type: 'array' },
|
|
2314
|
+
resumeLimit: { type: 'number' },
|
|
2315
|
+
hint: { type: 'string' },
|
|
2316
|
+
error: { type: 'string' },
|
|
2317
|
+
code: { type: 'string' },
|
|
2318
|
+
},
|
|
2319
|
+
required: ['ok'],
|
|
2320
|
+
additionalProperties: true,
|
|
2321
|
+
}
|
|
2322
|
+
}
|
|
2323
|
+
|
|
1804
2324
|
export function dispatchToolOutputSchema() {
|
|
1805
2325
|
return {
|
|
1806
2326
|
type: 'object',
|
|
@@ -1809,6 +2329,11 @@ export function dispatchToolOutputSchema() {
|
|
|
1809
2329
|
planId: { type: 'string' },
|
|
1810
2330
|
alreadyRunning: { type: 'boolean' },
|
|
1811
2331
|
stale: { type: 'boolean' },
|
|
2332
|
+
running: { type: 'boolean' },
|
|
2333
|
+
joined: { type: 'boolean' },
|
|
2334
|
+
mode: { type: 'string' },
|
|
2335
|
+
elapsedMs: { type: 'number' },
|
|
2336
|
+
statuses: { type: 'array' },
|
|
1812
2337
|
phase: { type: 'string' },
|
|
1813
2338
|
stats: { type: 'object' },
|
|
1814
2339
|
error: { type: 'string' },
|