dsh-taskbridge 1.5.4 → 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.
Files changed (74) hide show
  1. package/CHANGELOG.md +80 -59
  2. package/README.md +51 -50
  3. package/THIRD_PARTY_NOTICES.txt +23 -0
  4. package/bin/dsh-delegate-mcp.d.ts +1 -0
  5. package/bin/dsh-delegate-mcp.js +1 -0
  6. package/codex/dsh-taskbridge.toml +148 -71
  7. package/docs/INTRODUCTION.md +44 -22
  8. package/docs/INTRODUCTION.zh.md +32 -26
  9. package/docs/codex-integration.md +99 -19
  10. package/docs/contracts-stage-b.md +4 -4
  11. package/docs/conversation-placement.md +25 -7
  12. package/docs/plugin-market.md +1 -1
  13. package/docs/releases/1.6.0.zh.md +11 -0
  14. package/docs/releases/1.7.0.zh.md +11 -0
  15. package/docs/runtime-compatibility.md +10 -11
  16. package/docs/silent-wait.md +69 -31
  17. package/docs/taskbridge-upgrade.md +1 -1
  18. package/docs/worker-permissions.md +11 -21
  19. package/docs/workspace-grouping.md +126 -0
  20. package/lib/client.d.ts +581 -0
  21. package/lib/client.js +332 -3461
  22. package/locale/en.json +1 -1
  23. package/locale/zh.json +1 -1
  24. package/package.json +7 -19
  25. package/src/client/api.js +895 -90
  26. package/src/client/index.jsx +1363 -296
  27. package/src/client/sidebar.jsx +862 -0
  28. package/src/client/styles.js +340 -0
  29. package/src/client/task-cleanup.js +304 -0
  30. package/src/client/task-records-table.jsx +217 -0
  31. package/src/client/task-view.js +307 -0
  32. package/src/client/workspace-groups.js +482 -0
  33. package/src/client/workspaces-browser.jsx +770 -0
  34. package/src/codex/agent-ownership.js +270 -0
  35. package/src/codex/installer.js +528 -35
  36. package/src/codex/seam.js +5 -0
  37. package/src/config/defaults.js +63 -17
  38. package/src/config/settings.js +60 -62
  39. package/src/config/validate.js +126 -71
  40. package/src/http/execution-plane.js +200 -1
  41. package/src/http/respond.js +26 -2
  42. package/src/http/user-plane.js +566 -2
  43. package/src/index.d.ts +55 -0
  44. package/src/index.js +58 -42
  45. package/src/jobs/activity.js +968 -78
  46. package/src/jobs/engine.js +1010 -230
  47. package/src/jobs/history.js +224 -12
  48. package/src/jobs/plan-store.js +1020 -0
  49. package/src/jobs/record-cleanup.js +196 -0
  50. package/src/jobs/task-display.js +73 -0
  51. package/src/jobs/task-tree.js +786 -0
  52. package/src/jobs/title.js +129 -12
  53. package/src/mcp/server.js +206 -10
  54. package/src/mcp/wait.js +64 -5
  55. package/src/runtime/agent-runner.js +101 -15
  56. package/src/runtime/worker-prompt.js +53 -0
  57. package/src/workspace/locks.js +288 -167
  58. package/docs/assets/taskbridge-workflow.en.png +0 -0
  59. package/docs/assets/taskbridge-workflow.zh.png +0 -0
  60. package/docs/releases/1.4.0-token-benchmark.zh.md +0 -40
  61. package/docs/releases/1.4.0.zh.md +0 -54
  62. package/docs/releases/1.4.1.zh.md +0 -59
  63. package/docs/releases/1.4.2.zh.md +0 -23
  64. package/docs/releases/1.5.0-token-benchmark.zh.md +0 -73
  65. package/docs/releases/1.5.0.zh.md +0 -51
  66. package/docs/releases/1.5.1.zh.md +0 -70
  67. package/docs/releases/1.5.2.zh.md +0 -30
  68. package/docs/releases/1.5.3-test.1.zh.md +0 -28
  69. package/docs/releases/1.5.3-test.2.zh.md +0 -24
  70. package/docs/releases/1.5.3.zh.md +0 -33
  71. package/docs/releases/1.5.4.zh.md +0 -25
  72. package/src/review/preset.js +0 -868
  73. package/src/review/prompts.js +0 -145
  74. package/src/review/reviewer.js +0 -933
package/src/jobs/title.js CHANGED
@@ -1,17 +1,134 @@
1
1
  import { redactText } from '../config/redact.js';
2
2
 
3
- /** A display title is task content, never a directory name or routing instruction. */
4
- export function taskTitle(title, prompt = '') {
5
- const lines = String(prompt).split(/\r?\n/u).map(line => line.trim()).filter(Boolean);
6
- const goal = lines.findIndex(line => /^(?:#{1,6}\s*)?(?:目标|任务目标|工作内容|任务|goal|objective|task)(?:\s*[::]|\s*$)/iu.test(line));
7
- let text = typeof title === 'string' ? title.trim() : '';
8
- if (!text && goal >= 0) {
9
- text = lines[goal].replace(/^(?:#{1,6}\s*)?(?:目标|任务目标|工作内容|任务|goal|objective|task)\s*[::]?\s*/iu, '') || lines[goal + 1] || '';
3
+ const GOAL = /^(?:目标|任务目标|工作内容|任务|goal|objective|task)(?:\s*[::]\s*|$)(.*)$/iu;
4
+ const ROLE = /^(?:you are\b|you're\b|you will\b|you must\b|act as\b|your (?:role|task|job|objective)\b|as an?\b|你是|您是一名|你负责|你需要|你的(?:角色|任务|职责)|请作为|作为一)/iu;
5
+ const RULE = /^(?:instructions?|execution task rules?|task rules?|rules?|guidelines?|constraints?|requirements?|role|persona|system|context|background|overview|summary|steps?|procedure|执行任务规则|执行规则|任务规则|规则|约束|限制|要求|角色|身份|系统|背景|上下文|说明|验收|范围|步骤|流程|概述)(?:\s*[::].*|\s*)$/iu;
6
+ const RESTRICTION = /^(?:不要|不准|不得|禁止|必须|务必|请勿|别|do not\b|don't\b|never\b|must\b|always\b|avoid\b|use only\b)/iu;
7
+ const METADATA = /^(?:workspace|worktree|source|repo|repository|branch|commit|path|路径|工作区|仓库|分支|目录|提交)\s*[::]/iu;
8
+ const IDENTIFIER = /^(?:task-[0-9a-z][0-9a-z-]{5,}|[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}|sha256:[\da-f]{64})[::]?$/iu;
9
+ const ROOTED_PATH = /^(?:[a-z]:[\\/]|\\\\|\/|~\/)/iu;
10
+ const RELATIVE_PATH = /^(?:[^\s\\/]+[\\/])+[^\s\\/]+$/u;
11
+
12
+ /**
13
+ * Common work actions. A title is "path + work", not "path", only when one of these starts
14
+ * the description AND that description has an object. Deliberately short: a wording
15
+ * heuristic, not natural-language parsing.
16
+ */
17
+ const CJK_ACTION = /^(?:修复|修改|修正|整改|更新|升级|补充|补齐|完善|新增|添加|删除|移除|替换|重构|重写|实现|支持|接入|迁移|优化|调整|对齐|统一|清理|整理|检查|校验|验证|排查|复现|回归|覆盖|编写|生成|同步|合并|拆分|提取|封装|加固|收紧|收口|处理|解决)/u;
18
+ const LATIN_ACTION = /^(?:fix(?:es|ed|ing)?|add(?:s|ed|ing)?|update(?:s|d|ing)?|remove(?:s|d|ing)?|delete(?:s|d|ing)?|refactor(?:s|ed|ing)?|implement(?:s|ed|ing)?|support(?:s|ed|ing)?|migrate|improve[sd]?|optimi[sz]e[sd]?|rename[sd]?|clean(?:s|ed|ing)?|test(?:s|ed|ing)?|check(?:s|ed|ing)?|review(?:s|ed|ing)?|sync(?:s|ed|ing)?|extract(?:s|ed|ing)?|merge[sd]?|align(?:s|ed|ing)?|tighten(?:s|ed|ing)?)\b/iu;
19
+
20
+ /**
21
+ * The object that starts a description, after its action, or '' when there is none.
22
+ *
23
+ * A description needs something to act ON, so a bare verb (`Fix:`, an isolated `测试`) never
24
+ * qualifies. Chinese attaches its object directly (`修复API显示`), while a Latin verb must be
25
+ * separated from its object by whitespace or a colon — which is also why `Fix:` alone, with
26
+ * nothing after the colon, has no object.
27
+ * @param {string} text - the text right after the action.
28
+ * @returns {string} the object text, or '' when the action has no object.
29
+ */
30
+ function actionObject(text) {
31
+ const trimmed = text.trim();
32
+ // A separator that leads nowhere (`Fix:` / `修复:`) is not an object.
33
+ return trimmed.replace(/^[::]+/u, '').trim();
34
+ }
35
+
36
+ /**
37
+ * Whether one rooted (absolute) line carries a work description after its path.
38
+ *
39
+ * A rooted line is ambiguous: `E:/repo 修复API显示` is a work title, while `E:/资料/修复记录`
40
+ * is a path whose last segment merely STARTS with a verb. Splitting on the first space
41
+ * cannot decide that — a path may itself contain spaces (`E:/资料/My Project 修复登录错误`) —
42
+ * so the boundary is searched for inside the LAST path segment:
43
+ *
44
+ * * a description may only begin at whitespace that follows at least one non-space path
45
+ * character, so index 0 and leading whitespace are never a boundary (that is what made
46
+ * `修复记录` and `Update notes` read as work);
47
+ * * the description may not cross a path separator, so `测试/历史` stays a path segment;
48
+ * * the action must have an object (see {@link actionObject});
49
+ * * Chinese attaches its object directly; Latin must be separated by whitespace or colon.
50
+ *
51
+ * A directory literally named after an action plus its object stays genuinely ambiguous;
52
+ * that is documented in the delivery, and no filesystem access is attempted.
53
+ * @param {string} line - one trimmed candidate line.
54
+ * @returns {boolean} true when the line reads as "path + work", not "path".
55
+ */
56
+ function describesWorkAfterPath(line) {
57
+ // Everything after the last separator is the final segment, which may hold the description.
58
+ const slash = Math.max(line.lastIndexOf('/'), line.lastIndexOf('\\'));
59
+ const segment = slash >= 0 ? line.slice(slash + 1) : line;
60
+ for (let index = 1; index < segment.length; index += 1) {
61
+ // A boundary is whitespace preceded by a path character: never the segment start.
62
+ if (!/\s/u.test(segment[index]) || /\s/u.test(segment[index - 1])) continue;
63
+ const rest = segment.slice(index).trim();
64
+ if (rest === '') continue;
65
+ const cjk = CJK_ACTION.exec(rest);
66
+ if (cjk !== null && actionObject(rest.slice(cjk[0].length)) !== '') return true;
67
+ const latin = LATIN_ACTION.exec(rest);
68
+ // Latin needs an explicit separator, so `Fixings` or `Update` alone never matches.
69
+ if (latin !== null && /^[\s::]/u.test(rest.slice(latin[0].length)) && actionObject(rest.slice(latin[0].length)) !== '') {
70
+ return true;
71
+ }
10
72
  }
11
- if (!text) {
12
- text = lines.find(line => !/^(?:you are\b|act as\b|你是|你负责|```|#{1,6}\s*(?:instructions|角色|执行规则))/iu.test(line)) || '委派任务';
73
+ return false;
74
+ }
75
+
76
+ function textLines(value) {
77
+ return typeof value === 'string' ? value.split(/\r\n?|\n/u).map((line) => line.trim()) : [];
78
+ }
79
+
80
+ function plainLine(line) {
81
+ return line.replace(/^(?:#{1,6}\s*|(?:\d+[.)、]|[-*+])\s+)/u, '').trim();
82
+ }
83
+
84
+ function outsideFences(value) {
85
+ let open = null;
86
+ return textLines(value).map((line) => {
87
+ const fence = /^(\x60{3,}|~{3,})(.*)$/u.exec(line);
88
+ if (open !== null) {
89
+ if (fence?.[1][0] === open[0] && fence[1].length >= open.length && fence[2].trim() === '') open = null;
90
+ return null;
91
+ }
92
+ if (fence) {
93
+ open = fence[1];
94
+ return null;
95
+ }
96
+ return plainLine(line);
97
+ });
98
+ }
99
+
100
+ function candidate(line) {
101
+ if (!line || /^(?:[|>]|[-*_]{3,}|\x60[^\x60]*\x60$)/u.test(line)) return '';
102
+ if (ROLE.test(line) || RULE.test(line) || RESTRICTION.test(line) || METADATA.test(line) || IDENTIFIER.test(line)) return '';
103
+ if (ROOTED_PATH.test(line) && !describesWorkAfterPath(line)) return '';
104
+ if (RELATIVE_PATH.test(line) && !/\p{Script=Han}/u.test(line)) return '';
105
+ return redactText(line).replace(/[\u0000-\u001f\u007f]/gu, ' ').replace(/\s+/gu, ' ').trim();
106
+ }
107
+
108
+ /** Use a short title, a structured goal, or one readable line from older callers. */
109
+ export function taskTitle(title, prompt = '') {
110
+ const explicit = outsideFences(title).map(candidate).find((line) => line && GOAL.exec(line)?.[1] !== '');
111
+ if (explicit) return boundedTitle(explicit);
112
+
113
+ const lines = outsideFences(prompt);
114
+ for (const [index, line] of lines.entries()) {
115
+ if (!line) continue;
116
+ const goal = GOAL.exec(line);
117
+ if (!goal) continue;
118
+ let body = goal[1];
119
+ if (body === '') {
120
+ let next = index + 1;
121
+ while (lines[next] === '') next += 1;
122
+ body = lines[next];
123
+ }
124
+ const text = candidate(body);
125
+ if (text && !GOAL.test(text)) return boundedTitle(text);
13
126
  }
14
- text = redactText(text).replace(/^[#*\-\d.\s]+/u, '').replace(/[\u0000-\u001f\u007f]+/gu, ' ').replace(/\s+/gu, ' ').trim();
15
- const chars = Array.from(text || '委派任务');
16
- return chars.length > 48 ? chars.slice(0, 47).join('') + '…' : chars.join('');
127
+ const fallback = lines.map(candidate).find((line) => line && !GOAL.test(line));
128
+ return boundedTitle(fallback || '委派任务');
129
+ }
130
+
131
+ function boundedTitle(title) {
132
+ const chars = Array.from(title);
133
+ return chars.length > 48 ? chars.slice(0, 47).join('') + '…' : title;
17
134
  }
package/src/mcp/server.js CHANGED
@@ -95,6 +95,10 @@ import {
95
95
  canonicalTaskDescription,
96
96
  readTaskDescription,
97
97
  } from '../jobs/task-descriptions.js';
98
+ import {
99
+ MAX_PLAN_BATCH,
100
+ PLAN_TITLE_MAX_CHARS,
101
+ } from '../jobs/plan-store.js';
98
102
  import { waitForTask } from './wait.js';
99
103
  import { QUESTION_ANSWER_KIND, createCallMetrics, correlationId } from './metrics.js';
100
104
  // The engine's own per-call permission bounds. Imported rather than re-stated so this
@@ -342,12 +346,18 @@ export const TOOLS = Object.freeze([
342
346
  type: 'boolean',
343
347
  description: 'OPTIONAL. Your Agent Teams decision for THIS task\u2019s own DSH Session: the same switch the '
344
348
  + 'DSH model menu exposes as \u300cUse Agent Teams\u300d/\u300c\u542f\u7528\u667a\u80fd\u4f53\u56e2\u961f\u534f\u4f5c\u300d. '
345
- + 'The plugin applies it to this run only and never opens a global default. Use `true` only when independent '
346
- + 'modules can proceed in parallel and the gain covers the coordination cost; single-file work and '
347
- + 'strongly ordered changes should stay `false`. Omit it to make no choice: the run then keeps whatever '
348
- + 'selection the Session already has. Teams never replaces your approval or your final review, and this '
349
- + 'flag never selects a model or an effort \u2014 those come from the task\u2019s frozen configuration. The task '
350
- + 'record reports `agentTeams` (your request) and `team` (what DSH confirmed, or why it could not).',
349
+ + 'Send `true` or `false` only when the operator chooses a mode for this task. An explicit value wins over the operator\u2019s '
350
+ + 'TaskBridge default. Leave it absent, including inside overrides, when the operator leaves it unspecified. A new task follows the operator\u2019s '
351
+ + '\u300c\u65b0\u4efb\u52a1\u9ed8\u8ba4\u5f00\u542f\u667a\u80fd\u4f53\u534f\u4f5c\u300d setting (off on a fresh install and after an '
352
+ + 'upgrade), and a follow-up (`continueFromTaskId`) keeps the mode the task it continues ran with \u2014 if that '
353
+ + 'task recorded none, its Session keeps the existing mode. '
354
+ + 'The plugin applies it to this run only and never opens a global default. Teams never replaces your '
355
+ + 'approval or your final review, and this flag never selects a model or an effort \u2014 those come from the '
356
+ + 'task\u2019s frozen configuration. On a DSH without agent-teams support, an explicit `true` or `false` is '
357
+ + 'REFUSED (the worker is not prompted and the task records why); only the operator\u2019s implicit off default '
358
+ + 'still runs, reported as not applied. The task record reports `agentTeams` (the choice that was '
359
+ + 'applied), `agentTeamsOrigin` (`request`, `continuation` or `settings-default`) and `team` (what DSH '
360
+ + 'confirmed, or why it could not).',
351
361
  },
352
362
  continueFromTaskId: {
353
363
  type: 'string',
@@ -374,6 +384,24 @@ export const TOOLS = Object.freeze([
374
384
  + 'returns and of `delegate_result`; it is never derived from the prompt, a parent task or the result, '
375
385
  + 'and it does not change what the worker is told.',
376
386
  },
387
+ planNodeId: {
388
+ type: 'string',
389
+ minLength: 1,
390
+ maxLength: 256,
391
+ description: 'OPTIONAL. The `nodeId` (`plan-...`) of an existing planning node created with `delegate_plan` '
392
+ + 'that THIS execution task carries out. Starts a new DSH Session for that planned item; later '
393
+ + 'rectification rounds of this same item use `continueFromTaskId` and automatically inherit `planNodeId`. '
394
+ + 'Do NOT pass a sibling subtask\u2019s `planNodeId` together with `continueFromTaskId`.',
395
+ },
396
+ parentNodeId: {
397
+ type: 'string',
398
+ minLength: 1,
399
+ maxLength: 256,
400
+ description: 'OPTIONAL. The `nodeId` (`plan-...`) or `taskId` (`task-...`) of the parent goal or parent task '
401
+ + 'when submitting a child subtask directly without pre-creating a leaf `planNodeId`. Starts a NEW DSH '
402
+ + 'Session under that parent; never reuses the parent\u2019s Session (`continueFromTaskId` is for rectification '
403
+ + 'rounds of the SAME item only).',
404
+ },
377
405
  },
378
406
  required: ['workspacePath', 'prompt'],
379
407
  additionalProperties: false,
@@ -787,6 +815,104 @@ export const TOOLS = Object.freeze([
787
815
  additionalProperties: false,
788
816
  }),
789
817
  }),
818
+ Object.freeze({
819
+ name: 'delegate_plan',
820
+ title: 'Manage multi-level task plan tree',
821
+ description: 'Create, update, review or read durable planning nodes (`plan-...`) for a multi-stage goal without '
822
+ + 'fabricating dummy worker executions. Use `action: "create"` to record a root goal and optional multi-level '
823
+ + 'subtask breakdown (single node via `title`, or atomic batch via `nodes[]` using `key`/`parentKey` or '
824
+ + '`parentNodeId`). Then dispatch each executable leaf packet with `delegate_submit` passing `planNodeId` (or '
825
+ + '`parentNodeId` for a direct child subtask); use `continueFromTaskId` ONLY for rectification rounds of that '
826
+ + 'same node. Use `action: "review"` to record the commander\u2019s conclusion (`accepted` or `changes-requested`, '
827
+ + '`note`, optional `completionSummary`) on a goal/plan node once its required children are verified. Use '
828
+ + '`action: "get"` or `action: "list"` to inspect planning nodes, hierarchy, orphans and source-project grouping. '
829
+ + 'Creates no grant, changes no setting/provider/switch, and starts no worker.',
830
+ annotations: Object.freeze({
831
+ title: 'Manage multi-level task plan tree',
832
+ readOnlyHint: false,
833
+ destructiveHint: false,
834
+ idempotentHint: false,
835
+ openWorldHint: false,
836
+ }),
837
+ inputSchema: Object.freeze({
838
+ type: 'object',
839
+ properties: {
840
+ action: {
841
+ type: 'string',
842
+ enum: ['create', 'update', 'review', 'get', 'list'],
843
+ description: 'Operation to perform on the plan store.',
844
+ },
845
+ nodeId: {
846
+ type: 'string',
847
+ minLength: 1,
848
+ maxLength: 256,
849
+ description: 'Target `plan-...` node id (required for `update`, `review` and `get`).',
850
+ },
851
+ parentNodeId: {
852
+ type: 'string',
853
+ minLength: 1,
854
+ maxLength: 256,
855
+ description: 'Optional existing parent `plan-...` or `task-...` id when creating child plan node(s).',
856
+ },
857
+ workspacePath: {
858
+ type: 'string',
859
+ minLength: 1,
860
+ maxLength: 4096,
861
+ description: 'Absolute path of the operator-authorized SOURCE repository this goal belongs to (used for '
862
+ + 'verified project grouping and source consistency checks; filter on `list`).',
863
+ },
864
+ title: {
865
+ type: 'string',
866
+ minLength: 1,
867
+ maxLength: PLAN_TITLE_MAX_CHARS,
868
+ codePointLength: true,
869
+ description: 'Readable node title (1..120 Unicode code points; required for single-node `create`).',
870
+ },
871
+ goalDescription: {
872
+ type: 'string',
873
+ maxLength: MAX_TASK_DESCRIPTION_CHARS,
874
+ codePointLength: true,
875
+ description: 'Optional planned objective of this node (at most 2000 Unicode code points).',
876
+ },
877
+ decision: {
878
+ type: 'string',
879
+ enum: ['accepted', 'changes-requested'],
880
+ description: 'Commander review decision for `action: "review"`.',
881
+ },
882
+ note: {
883
+ type: 'string',
884
+ maxLength: MAX_REVIEW_NOTE_CHARS,
885
+ codePointLength: true,
886
+ description: 'Required review conclusion note (at most 8000 Unicode code points) for `action: "review"`.',
887
+ },
888
+ completionSummary: {
889
+ type: 'string',
890
+ maxLength: MAX_TASK_DESCRIPTION_CHARS,
891
+ codePointLength: true,
892
+ description: 'Optional summary of what was actually accomplished (at most 2000 Unicode code points) for `action: "review"`.',
893
+ },
894
+ nodes: {
895
+ type: 'array',
896
+ description: `Optional atomic batch of 1..${MAX_PLAN_BATCH} plan nodes for \`action: "create"\`.`,
897
+ items: {
898
+ type: 'object',
899
+ properties: {
900
+ key: { type: 'string', minLength: 1, maxLength: 64, description: 'Local batch key so children in the same batch can reference `parentKey`.' },
901
+ parentKey: { type: 'string', minLength: 1, maxLength: 64, description: 'References `key` of a parent item in this same `nodes` batch.' },
902
+ parentNodeId: { type: 'string', minLength: 1, maxLength: 256, description: 'References an already-stored `plan-...` or `task-...` parent (mutually exclusive with `parentKey`).' },
903
+ title: { type: 'string', minLength: 1, maxLength: PLAN_TITLE_MAX_CHARS, codePointLength: true, description: 'Node title (1..120 Unicode code points).' },
904
+ goalDescription: { type: 'string', maxLength: MAX_TASK_DESCRIPTION_CHARS, codePointLength: true, description: 'Optional planned objective (at most 2000 Unicode code points).' },
905
+ workspacePath: { type: 'string', minLength: 1, maxLength: 4096, description: 'Optional absolute source repository path (must match parent when parent has one).' },
906
+ },
907
+ required: ['title'],
908
+ additionalProperties: false,
909
+ },
910
+ },
911
+ },
912
+ required: ['action'],
913
+ additionalProperties: false,
914
+ }),
915
+ }),
790
916
  Object.freeze({
791
917
  name: 'delegate_preflight',
792
918
  title: 'Inspect workspace before dispatch',
@@ -877,6 +1003,7 @@ const TOOL_ROUTES = Object.freeze({
877
1003
  delegate_permission_decide: 'permission',
878
1004
  delegate_question_answer: 'question',
879
1005
  delegate_review: 'review',
1006
+ delegate_plan: 'plan',
880
1007
  delegate_preflight: 'preflight',
881
1008
  // No plane route: the census is this process's own and travels to no backend.
882
1009
  delegate_metrics: null,
@@ -949,11 +1076,22 @@ function validateArrayItem(tool, key, items, entry, index) {
949
1076
  const value = entry[field];
950
1077
  if (declared.type === 'string') {
951
1078
  if (typeof value !== 'string') throw new McpError('MCP_ARGUMENT_TYPE', `${where}.${field} must be a string`);
952
- if (typeof declared.maxLength === 'number' && value.length > declared.maxLength) {
1079
+ if (typeof declared.maxLength === 'number' && declared.codePointLength === true) {
1080
+ const points = reviewNoteLength(normalizeReviewNote(value));
1081
+ if (points > declared.maxLength) {
1082
+ throw new McpError('MCP_ARGUMENT_RANGE',
1083
+ `${where}.${field} must be at most ${declared.maxLength} Unicode code points, but it is ${points}`);
1084
+ }
1085
+ } else if (typeof declared.maxLength === 'number' && value.length > declared.maxLength) {
953
1086
  throw new McpError('MCP_ARGUMENT_RANGE',
954
1087
  `${where}.${field} must be at most ${declared.maxLength} characters`);
955
1088
  }
956
- out[field] = value;
1089
+ if (typeof declared.minLength === 'number' && value.trim().length < declared.minLength) {
1090
+ throw new McpError('MCP_ARGUMENT_REQUIRED', `${where}.${field} must not be empty`);
1091
+ }
1092
+ out[field] = (field === TASK_DESCRIPTION_FIELDS.goal || field === TASK_DESCRIPTION_FIELDS.summary)
1093
+ ? canonicalizeToolDescription({ name: where }, field, value)
1094
+ : value;
957
1095
  continue;
958
1096
  }
959
1097
  if (declared.type === 'array') {
@@ -1101,9 +1239,65 @@ function validateArgs(tool, args) {
1101
1239
  throw new McpError('MCP_ARGUMENTS_INVALID', 'delegate_result cannot combine reviewNoteOffset and completionSummaryOffset');
1102
1240
  }
1103
1241
  }
1242
+ if (tool.name === 'delegate_plan') {
1243
+ validatePlanArgs(out);
1244
+ }
1104
1245
  return out;
1105
1246
  }
1106
1247
 
1248
+ const PLAN_ACTION_ALLOWED = Object.freeze({
1249
+ create: Object.freeze(['action', 'title', 'goalDescription', 'parentNodeId', 'workspacePath', 'nodes']),
1250
+ update: Object.freeze(['action', 'nodeId', 'title', 'goalDescription', 'workspacePath']),
1251
+ review: Object.freeze(['action', 'nodeId', 'decision', 'note', 'completionSummary']),
1252
+ get: Object.freeze(['action', 'nodeId']),
1253
+ list: Object.freeze(['action', 'workspacePath']),
1254
+ });
1255
+
1256
+ function validatePlanArgs(out) {
1257
+ const action = out.action;
1258
+ const allowed = PLAN_ACTION_ALLOWED[action];
1259
+ for (const key of Object.keys(out)) {
1260
+ if (!allowed.includes(key)) {
1261
+ throw new McpError('MCP_ARGUMENTS_INVALID', `delegate_plan action "${action}" does not accept ${JSON.stringify(key)}`);
1262
+ }
1263
+ }
1264
+ if (action === 'create') {
1265
+ if (out.nodes !== undefined) {
1266
+ if (out.nodes.length === 0 || out.nodes.length > MAX_PLAN_BATCH) {
1267
+ throw new McpError('MCP_ARGUMENT_RANGE', `delegate_plan.nodes must contain 1..${MAX_PLAN_BATCH} items`);
1268
+ }
1269
+ if (out.title !== undefined || out.goalDescription !== undefined) {
1270
+ throw new McpError('MCP_ARGUMENTS_INVALID', 'delegate_plan cannot combine batch `nodes` with top-level `title` or `goalDescription`');
1271
+ }
1272
+ } else if (typeof out.title !== 'string' || out.title.trim() === '') {
1273
+ throw new McpError('MCP_ARGUMENT_REQUIRED', 'delegate_plan create requires `title` (or a non-empty `nodes` batch)');
1274
+ }
1275
+ return;
1276
+ }
1277
+ if (action === 'update') {
1278
+ if (typeof out.nodeId !== 'string' || out.nodeId.trim() === '') {
1279
+ throw new McpError('MCP_ARGUMENT_REQUIRED', 'delegate_plan update requires `nodeId`');
1280
+ }
1281
+ if (out.title === undefined && out.goalDescription === undefined && out.workspacePath === undefined) {
1282
+ throw new McpError('MCP_ARGUMENT_REQUIRED', 'delegate_plan update requires at least one of `title`, `goalDescription` or `workspacePath`');
1283
+ }
1284
+ return;
1285
+ }
1286
+ if (action === 'review') {
1287
+ for (const req of ['nodeId', 'decision', 'note']) {
1288
+ if (typeof out[req] !== 'string' || out[req].trim() === '') {
1289
+ throw new McpError('MCP_ARGUMENT_REQUIRED', `delegate_plan review requires a non-empty \`${req}\``);
1290
+ }
1291
+ }
1292
+ return;
1293
+ }
1294
+ if (action === 'get') {
1295
+ if (typeof out.nodeId !== 'string' || out.nodeId.trim() === '') {
1296
+ throw new McpError('MCP_ARGUMENT_REQUIRED', 'delegate_plan get requires `nodeId`');
1297
+ }
1298
+ }
1299
+ }
1300
+
1107
1301
  // ---------------------------------------------------------------------------
1108
1302
  // Bounded projection
1109
1303
  // ---------------------------------------------------------------------------
@@ -1655,8 +1849,10 @@ function skeletonize(task, path, cap, collect, stage = {}) {
1655
1849
  for (const key of ['taskId', 'state', 'phase', 'route', 'reviewRoute', 'reviewRouteError', 'execution', 'error',
1656
1850
  'hostAcceptance', 'selfApproved', 'cancelledBy', 'createdAt', 'endedAt',
1657
1851
  // The Agent Teams verdict is four booleans and a short reason: it survives every
1658
- // bound so a compressed answer still says whether teams are on for this run.
1659
- 'agentTeams', 'team']) {
1852
+ // bound so a compressed answer still says whether teams are on for this run. The
1853
+ // origin is one closed word, and it is what separates "you asked for this" from
1854
+ // "the operator's new-task default decided it".
1855
+ 'agentTeams', 'agentTeamsOrigin', 'team']) {
1660
1856
  if (key === 'hostAcceptance') {
1661
1857
  // Projected directly from the uncut review block so the generic per-string cap never
1662
1858
  // shortens `completionSummary` or `note` before their field-specific rules run.
package/src/mcp/wait.js CHANGED
@@ -43,6 +43,7 @@ import {
43
43
  isQuestionAnswerable,
44
44
  } from './server.js';
45
45
  import { REPEATED_FAILURE_KIND } from '../jobs/diagnostics.js';
46
+ import { CHECKPOINTS } from '../jobs/activity.js';
46
47
 
47
48
  /** Re-exported so a caller can assert the discriminator without importing the engine. */
48
49
  export { REPEATED_FAILURE_KIND };
@@ -101,6 +102,10 @@ const TASK_FIELDS = Object.freeze([
101
102
  // are on for this run (`applied`/`enabled`) or why they are not (`reason`) without
102
103
  // reading the full result. Four booleans plus a bounded reason — no team content.
103
104
  'agentTeams',
105
+ // Where that frozen decision came from (`request` / `continuation` / `settings-default`),
106
+ // so a wait answer distinguishes "you asked for this" from "the operator's setting
107
+ // decided it" without reading the full result.
108
+ 'agentTeamsOrigin',
104
109
  'team',
105
110
  ]);
106
111
 
@@ -252,10 +257,22 @@ function resolvedTaskState(task, reason) {
252
257
 
253
258
  /**
254
259
  * The instructions a host reads in a wait answer.
260
+ *
261
+ * The `attention` wording is chosen by `facts.checkpoint` — a scheduled progress
262
+ * check of a still-active run, the repeated-failure reminder, or the delivery
263
+ * interval — because the correct response differs. Every branch keeps the same two
264
+ * invariants: nothing was changed automatically, and the host keeps waiting on the
265
+ * SAME task unless it has a concrete reason to act.
266
+ *
267
+ * The progress branch is worded in terms of what the product actually measures: nothing new
268
+ * was RETURNED to the host. A local self-check read, internal model/tool activity, a heartbeat
269
+ * and the check itself are not results, and the wording must not imply that they are.
255
270
  * @param {string} reason - the reported reason.
256
- * @param {{ resolved?: boolean, taskState?: string | null, kind?: string }} [facts] - `resolved`: the
257
- * reason was settled by {@link resolveInterruption} rather than read verbatim;
258
- * `taskState`: the state the answer reports, for the `interrupted` wording.
271
+ * @param {{ resolved?: boolean, taskState?: string | null, kind?: string, checkpoint?: string | null,
272
+ * progress?: object | null }} [facts] - `resolved`: the reason was settled by
273
+ * {@link resolveInterruption} rather than read verbatim; `taskState`: the state the
274
+ * answer reports, for the `interrupted` wording; `checkpoint`: which `attention`
275
+ * reminder this is; `progress`: its bounded diagnostic.
259
276
  * @returns {string} one actionable sentence.
260
277
  */
261
278
  function instructionFor(reason, facts = {}) {
@@ -269,13 +286,31 @@ function instructionFor(reason, facts = {}) {
269
286
  + 'permission.requestId (and permission.fingerprint for allow-once), or reject it. The task is still '
270
287
  + 'running and waiting.';
271
288
  case 'attention':
272
- if (facts.failureKind === REPEATED_FAILURE_KIND) {
289
+ if (facts.checkpoint === REPEATED_FAILURE_KIND || facts.failureKind === REPEATED_FAILURE_KIND) {
273
290
  return 'The worker has repeated the SAME tool operation and failed the same way several times in a row, '
274
291
  + 'while the task is still running. See `failure` (toolName, failureCode, consecutive). This is a '
275
292
  + 'question, not a verdict: decide deliberately whether to keep waiting, cancel, or follow up. Nothing '
276
293
  + 'was cancelled or changed automatically, and the run is still going.';
277
294
  }
278
- return 'No activity has been observed for the configured inactivity threshold (ten minutes by default) '
295
+ if (facts.checkpoint === CHECKPOINTS.progress) {
296
+ // The run progress check: the host is asked to look, and the default answer is
297
+ // to keep waiting on the SAME task. It is NOT reported because the task has run
298
+ // for a long time — only because nothing new was DELIVERED back to the host for the
299
+ // interval. A local self-check diagnostic, internal model or tool activity, heartbeats
300
+ // and this check itself are not deliveries.
301
+ const idle = Number.isFinite(facts.progress?.noDeliveryMinutes)
302
+ ? `for about ${facts.progress.noDeliveryMinutes} minutes`
303
+ : 'for the configured interval';
304
+ return `Run progress check: nothing new has been returned ${idle} while the task is still `
305
+ + 'running (see `progress`: `noDeliveryForMs` is how long nothing came back, `activity` is what DSH is '
306
+ + 'doing right now, and `selfCheckVerdict` is the last local inspection). This is a checkpoint, NOT a '
307
+ + 'failure and NOT a verdict on the run\'s total duration: a task that keeps delivering results '
308
+ + 'never produces one, and reading the local self-check is not itself a result. Check whether the work so '
309
+ + 'far still matches the goal, and then KEEP WAITING on the SAME taskId unless you find a concrete error or '
310
+ + 'a real drift from the goal. Nothing was cancelled, restarted, resubmitted or re-queued, and this '
311
+ + 'interval will not be reported again.';
312
+ }
313
+ return 'Nothing has been reported back for the configured no-progress threshold (ten minutes by default) '
279
314
  + 'while the task is still running. The run may be stuck. Check the current tool and idle time; cancel '
280
315
  + 'or follow up deliberately rather than assuming completion.';
281
316
  case 'ready':
@@ -714,6 +749,24 @@ export async function waitForTask(options) {
714
749
  && typeof observation?.failure === 'object'
715
750
  ? observation.failure
716
751
  : null;
752
+ // WHICH `attention` reminder this is: the run progress check (`progress`) or the
753
+ // repeated-failure reminder (`failure`). They need different responses, and a host
754
+ // must not have to guess from prose. Derived from the engine's own claim when it
755
+ // published one; otherwise from the `failure` block, so an older engine that predates
756
+ // the field still classifies its reminders correctly.
757
+ //
758
+ // The classification is closed: an engine (or a fixture) that leaked a checkpoint
759
+ // onto a reason that is not `attention` — a terminal outcome, a pending decision —
760
+ // cannot make this answer claim one.
761
+ const checkpoint = reason === 'attention'
762
+ ? (typeof observation?.checkpoint === 'string' && CHECKPOINTS[observation.checkpoint] !== undefined
763
+ ? observation.checkpoint
764
+ : (failure !== null ? CHECKPOINTS.failure : CHECKPOINTS.progress))
765
+ : null;
766
+ const progress = checkpoint === CHECKPOINTS.progress && observation?.progress !== null
767
+ && typeof observation?.progress === 'object'
768
+ ? observation.progress
769
+ : null;
717
770
  const out = {
718
771
  taskId: typeof task.taskId === 'string' ? task.taskId : taskId,
719
772
  state,
@@ -731,11 +784,17 @@ export async function waitForTask(options) {
731
784
  taskState: state,
732
785
  kind: facts.kind,
733
786
  failureKind: failure?.kind ?? null,
787
+ checkpoint,
788
+ progress,
734
789
  }),
735
790
  task,
736
791
  metrics: metrics(1),
737
792
  };
738
793
  if (failure !== null) out.failure = failure;
794
+ if (checkpoint !== null) out.checkpoint = checkpoint;
795
+ // The bounded progress diagnostic (elapsed, interval, phase, open tool, silence)
796
+ // — facts the engine already held, no output, diff or review prose.
797
+ if (progress !== null) out.progress = progress;
739
798
  // The permission block is carried WHOLE — identity, fingerprint, completeness
740
799
  // flags and the redacted operation — because a host that had to read
741
800
  // `delegate_result` first would be doing two round trips to answer one question,