rookery-agent 0.2.0 → 0.3.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 (159) hide show
  1. package/README.md +4 -4
  2. package/package.json +3 -1
  3. package/packages/cli/dist/commands/tasks.js +1 -1
  4. package/packages/cli/dist/commands/tasks.js.map +1 -1
  5. package/packages/cli/package.json +1 -1
  6. package/packages/core/dist/agents/persona.js +1 -1
  7. package/packages/core/dist/agents/persona.js.map +1 -1
  8. package/packages/core/dist/config.d.ts +34 -1
  9. package/packages/core/dist/config.d.ts.map +1 -1
  10. package/packages/core/dist/config.js +79 -2
  11. package/packages/core/dist/config.js.map +1 -1
  12. package/packages/core/dist/cron/scheduler.d.ts +10 -3
  13. package/packages/core/dist/cron/scheduler.d.ts.map +1 -1
  14. package/packages/core/dist/cron/scheduler.js +38 -13
  15. package/packages/core/dist/cron/scheduler.js.map +1 -1
  16. package/packages/core/dist/gateway/policy.d.ts +20 -3
  17. package/packages/core/dist/gateway/policy.d.ts.map +1 -1
  18. package/packages/core/dist/gateway/policy.js +18 -2
  19. package/packages/core/dist/gateway/policy.js.map +1 -1
  20. package/packages/core/dist/index.d.ts +4 -4
  21. package/packages/core/dist/index.d.ts.map +1 -1
  22. package/packages/core/dist/index.js +3 -3
  23. package/packages/core/dist/index.js.map +1 -1
  24. package/packages/core/dist/memory/db.d.ts +1 -1
  25. package/packages/core/dist/memory/db.d.ts.map +1 -1
  26. package/packages/core/dist/memory/db.js +138 -1
  27. package/packages/core/dist/memory/db.js.map +1 -1
  28. package/packages/core/dist/org/controller.d.ts +98 -113
  29. package/packages/core/dist/org/controller.d.ts.map +1 -1
  30. package/packages/core/dist/org/controller.js +679 -726
  31. package/packages/core/dist/org/controller.js.map +1 -1
  32. package/packages/core/dist/org/prompts.d.ts +17 -16
  33. package/packages/core/dist/org/prompts.d.ts.map +1 -1
  34. package/packages/core/dist/org/prompts.js +76 -146
  35. package/packages/core/dist/org/prompts.js.map +1 -1
  36. package/packages/core/dist/org/store.d.ts +67 -5
  37. package/packages/core/dist/org/store.d.ts.map +1 -1
  38. package/packages/core/dist/org/store.js +202 -8
  39. package/packages/core/dist/org/store.js.map +1 -1
  40. package/packages/core/dist/org/tools.d.ts +9 -3
  41. package/packages/core/dist/org/tools.d.ts.map +1 -1
  42. package/packages/core/dist/org/tools.js +59 -35
  43. package/packages/core/dist/org/tools.js.map +1 -1
  44. package/packages/core/dist/providers/claude-code.d.ts +2 -1
  45. package/packages/core/dist/providers/claude-code.d.ts.map +1 -1
  46. package/packages/core/dist/providers/claude-code.js +21 -10
  47. package/packages/core/dist/providers/claude-code.js.map +1 -1
  48. package/packages/core/dist/providers/claude-tui.d.ts +120 -7
  49. package/packages/core/dist/providers/claude-tui.d.ts.map +1 -1
  50. package/packages/core/dist/providers/claude-tui.js +476 -41
  51. package/packages/core/dist/providers/claude-tui.js.map +1 -1
  52. package/packages/core/dist/runtime.d.ts +64 -12
  53. package/packages/core/dist/runtime.d.ts.map +1 -1
  54. package/packages/core/dist/runtime.js +520 -150
  55. package/packages/core/dist/runtime.js.map +1 -1
  56. package/packages/core/dist/types.d.ts +191 -13
  57. package/packages/core/dist/types.d.ts.map +1 -1
  58. package/packages/core/dist/types.js.map +1 -1
  59. package/packages/core/package.json +1 -1
  60. package/packages/server/dist/context.d.ts.map +1 -1
  61. package/packages/server/dist/context.js +11 -2
  62. package/packages/server/dist/context.js.map +1 -1
  63. package/packages/server/dist/gateways/push.d.ts.map +1 -1
  64. package/packages/server/dist/gateways/push.js +135 -69
  65. package/packages/server/dist/gateways/push.js.map +1 -1
  66. package/packages/server/dist/gateways/telegram.d.ts +31 -8
  67. package/packages/server/dist/gateways/telegram.d.ts.map +1 -1
  68. package/packages/server/dist/gateways/telegram.js +148 -47
  69. package/packages/server/dist/gateways/telegram.js.map +1 -1
  70. package/packages/server/dist/gateways/threads.d.ts +6 -1
  71. package/packages/server/dist/gateways/threads.d.ts.map +1 -1
  72. package/packages/server/dist/gateways/threads.js +21 -11
  73. package/packages/server/dist/gateways/threads.js.map +1 -1
  74. package/packages/server/dist/routes/config.d.ts.map +1 -1
  75. package/packages/server/dist/routes/config.js +27 -0
  76. package/packages/server/dist/routes/config.js.map +1 -1
  77. package/packages/server/dist/routes/org.d.ts.map +1 -1
  78. package/packages/server/dist/routes/org.js +68 -64
  79. package/packages/server/dist/routes/org.js.map +1 -1
  80. package/packages/server/dist/routes/ws.d.ts.map +1 -1
  81. package/packages/server/dist/routes/ws.js +13 -7
  82. package/packages/server/dist/routes/ws.js.map +1 -1
  83. package/packages/server/dist/schemas.d.ts +116 -68
  84. package/packages/server/dist/schemas.d.ts.map +1 -1
  85. package/packages/server/dist/schemas.js +34 -17
  86. package/packages/server/dist/schemas.js.map +1 -1
  87. package/packages/server/dist/server.d.ts.map +1 -1
  88. package/packages/server/dist/server.js +28 -4
  89. package/packages/server/dist/server.js.map +1 -1
  90. package/packages/server/dist/services/stream.d.ts +9 -4
  91. package/packages/server/dist/services/stream.d.ts.map +1 -1
  92. package/packages/server/dist/services/stream.js.map +1 -1
  93. package/packages/server/dist/services/turns.d.ts +5 -0
  94. package/packages/server/dist/services/turns.d.ts.map +1 -1
  95. package/packages/server/dist/services/turns.js +48 -0
  96. package/packages/server/dist/services/turns.js.map +1 -1
  97. package/packages/server/package.json +1 -1
  98. package/packages/web/dist/assets/{abnfDiagram-O67JEVCF-B4qWcqra.js → abnfDiagram-O67JEVCF-D7YyFndQ.js} +1 -1
  99. package/packages/web/dist/assets/{arc-CQult7TN.js → arc-C_Zgk2dJ.js} +1 -1
  100. package/packages/web/dist/assets/{architectureDiagram-NJMV4G6O-DFTRvl66.js → architectureDiagram-NJMV4G6O-eI0adu1B.js} +1 -1
  101. package/packages/web/dist/assets/{blockDiagram-BEXU5L5S-TCFoK_k-.js → blockDiagram-BEXU5L5S-WAoOFUA9.js} +1 -1
  102. package/packages/web/dist/assets/{c4Diagram-YGBWAQC7-i5_GqhJa.js → c4Diagram-YGBWAQC7-DE8Zyhng.js} +1 -1
  103. package/packages/web/dist/assets/channel-egZxcyUK.js +1 -0
  104. package/packages/web/dist/assets/{chunk-2Q5K7J3B-BK6I2wfW.js → chunk-2Q5K7J3B-bnqLP2XD.js} +1 -1
  105. package/packages/web/dist/assets/{chunk-3FUC2YCW-Dw-TfKT0.js → chunk-3FUC2YCW-Ck1_SVe0.js} +2 -2
  106. package/packages/web/dist/assets/{chunk-5VM5RSS4-AE_XRNTT.js → chunk-5VM5RSS4-hDmC41gD.js} +1 -1
  107. package/packages/web/dist/assets/{chunk-GTNCS2PH-DO18WaaJ.js → chunk-GTNCS2PH-PoWvfCrT.js} +1 -1
  108. package/packages/web/dist/assets/{chunk-GWA4HPMP-3rdjszP_.js → chunk-GWA4HPMP-D3V0IG43.js} +1 -1
  109. package/packages/web/dist/assets/{chunk-JWPE2WC7-C93LH2D0.js → chunk-JWPE2WC7-BryfpHM5.js} +1 -1
  110. package/packages/web/dist/assets/{chunk-NETBCI7D-Dj7O3-H-.js → chunk-NETBCI7D-8ic1iEdT.js} +1 -1
  111. package/packages/web/dist/assets/{chunk-WEXAMYUT-BRFvQUIn.js → chunk-WEXAMYUT-nM8tmQT2.js} +1 -1
  112. package/packages/web/dist/assets/{chunk-XXDRQBXY-CXx6HMbz.js → chunk-XXDRQBXY-Do28F482.js} +1 -1
  113. package/packages/web/dist/assets/{classDiagram-v2-NBCMYWYE-BGXszxjn.js → classDiagram-v2-NBCMYWYE-Bop9oNNO.js} +1 -1
  114. package/packages/web/dist/assets/{cose-bilkent-JH36ORCC-BAuXqkne.js → cose-bilkent-JH36ORCC-a7f_bpnt.js} +1 -1
  115. package/packages/web/dist/assets/{cynefin-OW5HDTMX-plNzhY7J.js → cynefin-OW5HDTMX-DnArcis_.js} +1 -1
  116. package/packages/web/dist/assets/{cynefinDiagram-VND7K2PF-DuPlljFS.js → cynefinDiagram-VND7K2PF-vEuTb1GD.js} +1 -1
  117. package/packages/web/dist/assets/{dagre-6A5THRUB-CXzwdR-6.js → dagre-6A5THRUB-BgG4MynJ.js} +1 -1
  118. package/packages/web/dist/assets/{diagram-22UHCM2B-B7iv_V2D.js → diagram-22UHCM2B-DRCQpafv.js} +1 -1
  119. package/packages/web/dist/assets/{diagram-3UASUU5V-BMvi7gSi.js → diagram-3UASUU5V-BKgmAXde.js} +1 -1
  120. package/packages/web/dist/assets/{diagram-ATOU4E4O-NJ7EB5Qg.js → diagram-ATOU4E4O-B6Hsy36X.js} +1 -1
  121. package/packages/web/dist/assets/{diagram-CDSNMT55-DccMMNJ-.js → diagram-CDSNMT55-JflyfyoB.js} +1 -1
  122. package/packages/web/dist/assets/{diagram-MLGK6HIB-BbwGHK4g.js → diagram-MLGK6HIB-Dd2QPJjT.js} +1 -1
  123. package/packages/web/dist/assets/{diagram-MPIPVDR6-BbSSZfM3.js → diagram-MPIPVDR6-DE5QU60x.js} +1 -1
  124. package/packages/web/dist/assets/{ebnfDiagram-ZINNZB2B-BBfPNM85.js → ebnfDiagram-ZINNZB2B-D7AQ741b.js} +1 -1
  125. package/packages/web/dist/assets/{elk-276RUBZZ-dM3Y1d2a.js → elk-276RUBZZ-CeewBVLF.js} +1 -1
  126. package/packages/web/dist/assets/{erDiagram-OPXOYQCR-iWrUegxy.js → erDiagram-OPXOYQCR-mLLYkZ5c.js} +1 -1
  127. package/packages/web/dist/assets/{flowDiagram-KWPJA3E3-B6DYlbkV.js → flowDiagram-KWPJA3E3-DtpSpsQN.js} +1 -1
  128. package/packages/web/dist/assets/{ganttDiagram-FUAMR5RP-D7dSWZcC.js → ganttDiagram-FUAMR5RP-1_lh-3ky.js} +1 -1
  129. package/packages/web/dist/assets/{gitGraphDiagram-X574FWY7-DguFgcbW.js → gitGraphDiagram-X574FWY7-DoPXZuT5.js} +1 -1
  130. package/packages/web/dist/assets/index-Cw2Opmx7.js +648 -0
  131. package/packages/web/dist/assets/index-j0zBRCgT.css +32 -0
  132. package/packages/web/dist/assets/{infoDiagram-VRGFBTTK-CuiuO3uo.js → infoDiagram-VRGFBTTK-DQpRGGiD.js} +1 -1
  133. package/packages/web/dist/assets/{ishikawaDiagram-OU5B5YK6-wBS1_40m.js → ishikawaDiagram-OU5B5YK6-gH5C9Q2e.js} +1 -1
  134. package/packages/web/dist/assets/{journeyDiagram-ZHPQQLJL-Bd1YE2gP.js → journeyDiagram-ZHPQQLJL-Bg-oeFjb.js} +1 -1
  135. package/packages/web/dist/assets/{kanban-definition-PNTS6WVX-BlQzv_X1.js → kanban-definition-PNTS6WVX-BnpI4VH8.js} +1 -1
  136. package/packages/web/dist/assets/{mermaid.core-p3CwmLUb.js → mermaid.core-BwBKxlRA.js} +4 -4
  137. package/packages/web/dist/assets/{mindmap-definition-NLK3R4M7-BlticnKl.js → mindmap-definition-NLK3R4M7-NBnnxEoO.js} +1 -1
  138. package/packages/web/dist/assets/{pegDiagram-GJSIUBJH-BbXsP47B.js → pegDiagram-GJSIUBJH-RrXXbIvO.js} +1 -1
  139. package/packages/web/dist/assets/{pieDiagram-5QR66LMP-BooBSBug.js → pieDiagram-5QR66LMP-B27q6Gso.js} +1 -1
  140. package/packages/web/dist/assets/{quadrantDiagram-O4NWA36T-CkXC6VCh.js → quadrantDiagram-O4NWA36T-DGDsdur2.js} +1 -1
  141. package/packages/web/dist/assets/{railroadDiagram-XR7U4H2S-BphzYiW-.js → railroadDiagram-XR7U4H2S-GdjkE3mI.js} +1 -1
  142. package/packages/web/dist/assets/{requirementDiagram-PLB6GJNP-PWpD4zpQ.js → requirementDiagram-PLB6GJNP-DjK0GfgO.js} +1 -1
  143. package/packages/web/dist/assets/{sankeyDiagram-IPEJSGJF-5Qm39Vfz.js → sankeyDiagram-IPEJSGJF-BG_AIkwF.js} +1 -1
  144. package/packages/web/dist/assets/{sequenceDiagram-PO4LG4MO-DA673J_w.js → sequenceDiagram-PO4LG4MO-CIQwUb4y.js} +1 -1
  145. package/packages/web/dist/assets/{sizeCapture-INFHLROL-1KsNwBhd.js → sizeCapture-INFHLROL-bpIoPxdJ.js} +1 -1
  146. package/packages/web/dist/assets/{stateDiagram-v2-GCMORJYK-D7O0UyHr.js → stateDiagram-v2-GCMORJYK-8hYXvPPv.js} +1 -1
  147. package/packages/web/dist/assets/{swimlanes-2SLR337P-culFSb1R.js → swimlanes-2SLR337P-gfflUMF9.js} +1 -1
  148. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-9wdzGXU-.js +8 -0
  149. package/packages/web/dist/assets/{timeline-definition-EJHVYXUP-6GIO5p-k.js → timeline-definition-EJHVYXUP-PHMNoGTZ.js} +1 -1
  150. package/packages/web/dist/assets/{usecaseDiagram-POWQR4AR-BAGHDBzZ.js → usecaseDiagram-POWQR4AR-B2j5iteO.js} +1 -1
  151. package/packages/web/dist/assets/{vennDiagram-UO4OBE2U-PbtBvPRE.js → vennDiagram-UO4OBE2U-BzxtZ-_2.js} +1 -1
  152. package/packages/web/dist/assets/{wardleyDiagram-VNRHLVJA-9scbtDvX.js → wardleyDiagram-VNRHLVJA-DL7YbMpY.js} +1 -1
  153. package/packages/web/dist/assets/{xychartDiagram-PMCCYNJV-C51PiF4p.js → xychartDiagram-PMCCYNJV-CisgP1cT.js} +1 -1
  154. package/packages/web/dist/index.html +2 -2
  155. package/packages/web/package.json +1 -1
  156. package/packages/web/dist/assets/channel-D_4EmqNR.js +0 -1
  157. package/packages/web/dist/assets/index-B1QvSHA5.js +0 -660
  158. package/packages/web/dist/assets/index-zwMuaz90.css +0 -32
  159. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-kzTmK2BP.js +0 -8
@@ -12,7 +12,7 @@ import { extractMemories, smallModelFor } from '../memory/extractor.js';
12
12
  import { admitCandidates, linkEntities } from '../memory/gate.js';
13
13
  import { clip, shorten, tail, titleFromBrief } from '../util/queue.js';
14
14
  import { formatAge, formatDay, formatWhen } from '../util/time.js';
15
- import { buildAgentPrompt, renderBoard, renderMail, renderOrgOverview, renderSchedules } from './prompts.js';
15
+ import { buildAgentPrompt, renderBoard, renderOrgOverview, renderSchedules, renderTaskActivity, } from './prompts.js';
16
16
  import { draftHandover, draftNote, draftReconfig, draftReplacementProposal, judgeAssignment, } from './review.js';
17
17
  import { buildTaskWaves, planTask } from './planner.js';
18
18
  import { toolsFor } from './tools.js';
@@ -33,6 +33,76 @@ const RESULT_BUDGET = 24000;
33
33
  * costs one provider process, never the assignment's place in the queue.
34
34
  */
35
35
  const MAX_PROVIDER_ATTEMPTS = 2;
36
+ /**
37
+ * How often a task run picks its own work back up because work it handed off
38
+ * in the background came back (R4). Each round is a full run of the leaf, so
39
+ * this is a ceiling on cost as much as on nesting; `org.maxTaskRuns` still
40
+ * applies on top of it.
41
+ */
42
+ const MAX_DELEGATION_ROUNDS = 2;
43
+ /**
44
+ * The notice for one ended task, in the words the assistant reads. `question`
45
+ * is what the agent asked with `ask_requester`, for a task that is waiting.
46
+ */
47
+ export function reportBackNotice(task, agent, question) {
48
+ const who = agent ? agent.name + ' (' + agent.slug + ')' : 'the agent';
49
+ const ended = task.finishedAt ?? task.updatedAt;
50
+ const took = task.startedAt && ended > task.startedAt ? ' after ' + formatAge(task.startedAt, ended, 'second') : '';
51
+ const head = '[Rookery] Background task ' + task.id.slice(0, 8) + ' "' + task.title + '", handed to ' + who + ', ';
52
+ const system = 'This message comes from the system, not from your user - do not answer it as if they wrote it. ' +
53
+ 'You handed this work off earlier in this conversation; this is the follow-up you owe them.';
54
+ switch (task.status) {
55
+ case 'done':
56
+ return (head + 'is done' + took + '.' + (task.error ? ' Note: ' + task.error : '') + '\n\n' +
57
+ 'Report:\n' + clip(task.result ?? '(no output)', RESULT_BUDGET) + '\n\n' + system + ' ' +
58
+ 'Tell the user what came of it now, in your own words: the outcome, and anything they need to decide or do. ' +
59
+ 'Keep it as short as the report allows.');
60
+ case 'blocked':
61
+ return (head + 'stopped with a question and is waiting for an answer.\n\n' +
62
+ (question ? 'The question:\n' + clip(question, RESULT_BUDGET) + '\n\n' : '') +
63
+ (task.result ? 'What it said:\n' + clip(task.result, RESULT_BUDGET) + '\n\n' : '') + system + ' ' +
64
+ 'Put the question to the user. Once they answer, pass the answer on with answer_task("' +
65
+ task.id.slice(0, 8) + '", ...) and the task picks up again, as the same task. Answer it yourself only ' +
66
+ 'if you know the answer for certain.');
67
+ case 'cancelled':
68
+ return head + 'was cancelled' + took + '.\n\n' + system + ' Tell the user briefly, unless they cancelled it themselves just now.';
69
+ default:
70
+ return (head + 'failed' + took + ': ' + (task.error ?? 'no reason given').replace(/[.\s]+$/, '') + '.' +
71
+ (task.result ? '\n\nWhat it had so far:\n' + clip(task.result, 4000) : '') + '\n\n' + system + ' ' +
72
+ 'Tell the user what went wrong and what you suggest - retrying, handing it to someone else, or dropping it.');
73
+ }
74
+ }
75
+ /**
76
+ * What the user is told when one of their cards ends or waits on them - the
77
+ * notification that replaced the status note mail. A task that is waiting
78
+ * becomes a `question` in the agent's own name; every other ending is a
79
+ * `task` notification from Rookery, carrying the result rather than a
80
+ * pointer to it (the rule `statusNote` was written for).
81
+ */
82
+ export function taskNotification(task, agent, question) {
83
+ const name = '"' + task.title + '"';
84
+ if (task.status === 'blocked') {
85
+ return {
86
+ kind: 'question',
87
+ title: (agent ? agent.name : 'An agent') + ' has a question about ' + name,
88
+ body: clip(question ?? task.result ?? 'The task is waiting for an answer.', 4000),
89
+ fromKind: agent ? 'agent' : 'system',
90
+ fromAgentId: agent?.id,
91
+ taskId: task.id,
92
+ };
93
+ }
94
+ const title = task.status === 'done'
95
+ ? 'Task ' + name + ' is done'
96
+ : task.status === 'cancelled'
97
+ ? 'Task ' + name + ' was cancelled'
98
+ : 'Task ' + name + ' failed';
99
+ const body = task.status === 'done'
100
+ ? clip(task.result?.trim() || '', 4000) + (task.error ? (task.result ? '\n\n' : '') + 'Note: ' + task.error : '')
101
+ : task.status === 'cancelled'
102
+ ? ''
103
+ : (task.error ?? 'No reason given.') + (task.result ? '\n\nWhat it had so far:\n' + clip(task.result, 2000) : '');
104
+ return { kind: 'task', title, body, fromKind: 'system', taskId: task.id };
105
+ }
36
106
  /** How much of one assignment's live log is kept, in JSON bytes. */
37
107
  const ASSIGNMENT_LOG_BYTES = 256 * 1024;
38
108
  /**
@@ -124,7 +194,12 @@ export class OrgController extends EventEmitter {
124
194
  #sleep;
125
195
  #questions;
126
196
  #canNotify;
127
- #runAssistantMail;
197
+ /**
198
+ * Runs whose agent called `ask_requester`, by assignment id. Read once when
199
+ * the run ends (`onAskedRequester`) and dropped there; in memory because a
200
+ * run that did not survive a restart has no ending left to decide.
201
+ */
202
+ #askedRequester = new Set();
128
203
  #running = 0;
129
204
  #waiting = [];
130
205
  /** Cancel hooks of assignments that are queued or running, by assignment id. */
@@ -133,6 +208,20 @@ export class OrgController extends EventEmitter {
133
208
  #logs = new Map();
134
209
  /** Abort controllers of tasks being run from the board, by task id. */
135
210
  #activeTasks = new Map();
211
+ /**
212
+ * Tasks somebody is blocked on right now - an `assign` or `run_task` with
213
+ * the caller waiting for its return value. Their ending travels back as that
214
+ * return value, so a report-back on top would say it twice. In memory on
215
+ * purpose: after a restart nobody is waiting any more, and then every run
216
+ * reports back on its own.
217
+ */
218
+ #awaited = new Set();
219
+ /**
220
+ * Work an agent handed off with `wait=false` from inside a task, by that
221
+ * task's id. The task does not end while any of it is still out (R4): its
222
+ * run waits, then picks its own work back up with the results.
223
+ */
224
+ #detached = new Map();
136
225
  constructor(options) {
137
226
  super();
138
227
  this.#store = options.store;
@@ -145,7 +234,6 @@ export class OrgController extends EventEmitter {
145
234
  this.#sleep = options.sleep;
146
235
  this.#questions = options.questions;
147
236
  this.#canNotify = options.canNotify;
148
- this.#runAssistantMail = options.runAssistantMail;
149
237
  }
150
238
  get bridge() {
151
239
  return this.#bridge;
@@ -432,31 +520,64 @@ export class OrgController extends EventEmitter {
432
520
  return { text: describeSettings(this.#config) };
433
521
  case 'update_settings':
434
522
  return this.#updateSettings(context, args);
435
- case 'send_mail':
436
- return this.#sendMail(context, text('to'), text('cc'), text('subject'), text('body'), text('inReplyTo') || undefined);
437
- case 'read_mail': {
438
- const who = context.audience === 'agent' ? { kind: 'agent', id: context.agentId } : { kind: 'assistant' };
439
- const mail = this.#store.org.unreadMailFor(context.orgId, who);
440
- if (!mail.length)
441
- return { text: 'No unread mail.' };
442
- this.#store.org.markMailReadFor(mail, who);
443
- return { text: renderMail(mail, this.snapshot(context.orgId), 'Unread mail:') };
444
- }
445
- case 'read_mail_thread': {
446
- const reference = text('thread');
447
- if (!reference)
448
- return fail('Name the thread to read.');
449
- const who = context.audience === 'agent' ? { kind: 'agent', id: context.agentId } : { kind: 'assistant' };
450
- // Either id works: a mail names its own thread, and the id an agent
451
- // has to hand is usually the mail it was woken with.
452
- const threadId = this.#store.org.getMail(reference)?.threadId ?? reference;
453
- const thread = this.#store.org.thread(context.orgId, threadId, { who });
454
- if (!thread.length)
455
- return { text: 'No mail in that thread, or none of it was addressed to you.' };
456
- // Asked for in full, answered in full: the prompt's 600-character
457
- // preview is the wrong answer to "give me the whole thread".
523
+ case 'ask_requester':
524
+ return this.#askRequester(context, text('question'));
525
+ case 'answer_task': {
526
+ const task = this.findTask(context.orgId, text('id'));
527
+ if (!task)
528
+ return fail('No task ' + text('id') + '.');
529
+ const answerer = context.audience === 'agent' ? { kind: 'agent', agentId: context.agentId } : { kind: 'assistant' };
530
+ const answered = await this.#answer(task, text('answer'), answerer, context);
531
+ if (!answered.ok)
532
+ return fail(answered.reason);
533
+ const where = context.taskId && task.parentId === context.taskId
534
+ ? 'Your own task stays open until it is back: when your run ends, you are started again with its result.'
535
+ : task.requesterSessionId && !task.parentId
536
+ ? 'When it ends, a message arrives in the conversation it came from.'
537
+ : 'How it ends is recorded on its card.';
458
538
  return {
459
- text: clip(renderMail(thread, this.snapshot(context.orgId), 'The thread, oldest first:', 4000), RESULT_BUDGET),
539
+ text: 'Answered task ' + task.id.slice(0, 8) + ' "' + task.title + '"; it runs again with your answer. ' + where,
540
+ };
541
+ }
542
+ case 'report_to_user': {
543
+ // Agents, and the one assistant run that has no conversation to speak
544
+ // in: the board watcher. An ordinary assistant turn answers the user
545
+ // directly, and `notify` is its line for what cannot wait.
546
+ if (context.audience !== 'agent' && !context.watching) {
547
+ return fail('Reach the user through your answer, or with notify for something that has to arrive now.');
548
+ }
549
+ if (!text('title') || !text('body'))
550
+ return fail('A report needs a title and a body.');
551
+ const notification = this.notifyUser({
552
+ orgId: context.orgId,
553
+ kind: context.watching ? 'watch' : 'agent',
554
+ title: text('title'),
555
+ body: text('body'),
556
+ fromKind: context.audience === 'agent' ? 'agent' : 'assistant',
557
+ fromAgentId: context.audience === 'agent' ? context.agentId : undefined,
558
+ taskId: context.taskId,
559
+ // The watcher's own run is where a reply to its report continues;
560
+ // an agent's run has no conversation of its own to point at.
561
+ sessionId: context.watching ? context.sessionId : undefined,
562
+ });
563
+ if (context.taskId && this.#store.org.getTask(context.taskId)) {
564
+ this.#taskEvent({
565
+ taskId: context.taskId,
566
+ kind: 'note',
567
+ actorKind: context.audience === 'agent' ? 'agent' : 'assistant',
568
+ actorAgentId: context.agentId,
569
+ text: 'Reported to the user: ' + notification.title + '\n\n' + notification.body,
570
+ assignmentId: context.parentAssignmentId,
571
+ });
572
+ }
573
+ return { text: 'Left the user a notification: "' + notification.title + '".' };
574
+ }
575
+ case 'task_activity': {
576
+ const task = this.findTask(context.orgId, text('id'));
577
+ if (!task)
578
+ return fail('No task ' + text('id') + '.');
579
+ return {
580
+ text: clip(renderTaskActivity(task, this.#store.org.listTaskEvents(task.id), this.snapshot(context.orgId)), RESULT_BUDGET),
460
581
  };
461
582
  }
462
583
  case 'notify': {
@@ -464,21 +585,37 @@ export class OrgController extends EventEmitter {
464
585
  return fail('Only the assistant can send notifications.');
465
586
  if (!text('text'))
466
587
  return fail('A notification needs text.');
588
+ const urgency = args.urgency === 'high' ? 'high' : 'normal';
589
+ // Kept as well as pushed: a push is gone once it is swiped away, and
590
+ // the web should be able to show what the assistant said on its own.
591
+ // The push itself still travels on the `notify` event - the
592
+ // notification is the record, so a channel must not push it twice.
593
+ const firstLine = text('text').split('\n', 1)[0] ?? '';
594
+ this.notifyUser({
595
+ orgId: context.orgId,
596
+ kind: 'system',
597
+ title: shorten(firstLine, 80),
598
+ body: text('text'),
599
+ fromKind: 'assistant',
600
+ sessionId: context.sessionId,
601
+ });
467
602
  if (!this.#canNotify || !this.#canNotify()) {
468
- return fail('No notification channel can reach the user right now - none is set up, it is ' +
469
- 'switched off, or it has no recipient. Nothing was sent.');
603
+ return {
604
+ text: 'No push channel can reach the user right now - none is set up, it is switched off, or it has ' +
605
+ 'no recipient. The message is saved in their notifications and waits there.',
606
+ };
470
607
  }
471
- const urgency = args.urgency === 'high' ? 'high' : 'normal';
472
608
  const event = { text: text('text'), urgency, at: Date.now() };
473
609
  this.emit('notify', event);
474
610
  return { text: 'Sent' + (urgency === 'high' ? ' (high urgency)' : '') + ': ' + event.text };
475
611
  }
476
612
  case 'ask_user': {
477
613
  // Only the assistant asks. An agent runs unattended by design and
478
- // reports back by mail; letting one block on a person would stall a
479
- // whole delegation chain behind somebody's inbox.
614
+ // asks whoever gave it the work (`ask_requester`); letting one block
615
+ // on a person would stall a whole delegation chain behind them.
480
616
  if (context.audience !== 'assistant') {
481
- return fail('Only the assistant can ask the user. Report what you need in your result instead.');
617
+ return fail('Only the assistant can ask the user. Inside a task, ask whoever gave you the work with ' +
618
+ 'ask_requester; otherwise say what you need in your result.');
482
619
  }
483
620
  // Belt and braces: a scheduled run is not offered the tool at all
484
621
  // (see `register`), so getting here means the list was built for a
@@ -795,12 +932,13 @@ export class OrgController extends EventEmitter {
795
932
  assigneeId: assignee?.id,
796
933
  createdBy: context.audience === 'agent' ? 'agent' : 'assistant',
797
934
  createdByAgentId: context.agentId,
935
+ // Whenever it runs, the conversation that asked for it hears how it
936
+ // ended. Inside a task there is a parent to report to instead.
937
+ requesterSessionId: context.taskId ? undefined : context.sessionId,
798
938
  });
939
+ // The card opens its own activity with the brief (`createTask`), so
940
+ // there is nothing more to write before anybody presses start.
799
941
  this.#announceTask(task, context.emit);
800
- // A task with an owner gets its thread now rather than at its first
801
- // run: the work order is the mail, and the owner should be able to
802
- // ask about it before anybody presses start.
803
- await this.#ensureTaskThread(task, context.emit);
804
942
  return { text: 'Task ' + task.id.slice(0, 8) + ' "' + task.title + '" is on the board.' };
805
943
  }
806
944
  case 'list_tasks': {
@@ -825,7 +963,9 @@ export class OrgController extends EventEmitter {
825
963
  const task = this.findTask(context.orgId, text('id'));
826
964
  if (!task)
827
965
  return fail('No task ' + text('id') + '.');
828
- const finished = await this.runTask(context, task);
966
+ const finished = await this.#runAwaited(context, task);
967
+ if (finished.status === 'blocked')
968
+ return { text: this.#waitingText(finished) };
829
969
  if (finished.status !== 'done') {
830
970
  return fail('Task "' + finished.title + '" ' + finished.status + (finished.error ? ': ' + finished.error : '.'));
831
971
  }
@@ -937,7 +1077,7 @@ export class OrgController extends EventEmitter {
937
1077
  if (cron.isRunning(job.id))
938
1078
  return { text: 'Schedule "' + job.name + '" is already running.' };
939
1079
  void cron.runNow(job.id).catch((error) => this.#log.warn('Manual schedule run failed', { error: error.message }));
940
- return { text: 'Schedule "' + job.name + '" is running now; the result will arrive in your inbox.' };
1080
+ return { text: 'Schedule "' + job.name + '" is running now; the result reaches the user as a notification.' };
941
1081
  }
942
1082
  // update_schedule
943
1083
  const patch = {};
@@ -1122,17 +1262,18 @@ export class OrgController extends EventEmitter {
1122
1262
  assigneeId: agent.id,
1123
1263
  createdBy: context.audience === 'agent' ? 'agent' : 'assistant',
1124
1264
  createdByAgentId: context.agentId,
1265
+ // Where the ending is reported (R1): the conversation for top-level
1266
+ // work, the parent task for work handed on from inside one.
1267
+ requesterSessionId: context.taskId ? undefined : context.sessionId,
1125
1268
  });
1126
1269
  this.#announceTask(board, context.emit);
1127
1270
  const shortId = board.id.slice(0, 8);
1128
- // The new task is its own errand: the mail that started the caller's run
1129
- // must not be answered by this one as well, and the note that continued
1130
- // the caller's thread is not part of this brief.
1271
+ // The new task is its own errand: the note that continued the caller's
1272
+ // task is not part of this brief.
1131
1273
  const runContext = {
1132
1274
  ...context,
1133
1275
  projectId,
1134
1276
  taskId: board.id,
1135
- sourceMail: undefined,
1136
1277
  taskNote: undefined,
1137
1278
  emit: wait ? context.emit : () => undefined,
1138
1279
  signal: wait ? context.signal : undefined,
@@ -1141,51 +1282,42 @@ export class OrgController extends EventEmitter {
1141
1282
  // Detached: the turn ends while the agent works. Its progress reaches
1142
1283
  // every socket through the org-level run events; the turn's own stream
1143
1284
  // and abort signal must not be tied to it.
1144
- const isSelf = agent.id === context.agentId;
1145
- this.runTask(runContext, board)
1146
- .then((finished) => {
1147
- if (!isSelf)
1148
- return undefined;
1149
- // A self-assignment has nobody else waiting on assignment_status,
1150
- // so it reports for itself the same way mail-triggered work does:
1151
- // a mail addressed to the user.
1152
- const body = finished.status === 'done'
1153
- ? clip(finished.result ?? '', RESULT_BUDGET)
1154
- : 'Could not finish: ' + (finished.error ?? finished.status) + '.';
1155
- return this.#deliverMail({
1156
- orgId: context.orgId,
1157
- from: { kind: 'agent', id: agent.id },
1158
- to: [{ kind: 'user' }],
1159
- cc: [],
1160
- subject: 'Re: ' + title,
1161
- body,
1162
- depth: 0,
1163
- emit: () => undefined,
1164
- });
1165
- })
1166
- .catch((error) => {
1285
+ //
1286
+ // Nobody waits on the promise here, and nobody has to: how the task
1287
+ // ends is reported back by `runTask` itself - to the conversation for
1288
+ // top-level work, to the parent task (which waits for it, R4) for work
1289
+ // handed on from inside one. It used to be dropped on the floor unless
1290
+ // an agent had assigned itself, while the tool text promised otherwise.
1291
+ const running = this.runTask(runContext, board).catch((error) => {
1167
1292
  this.#log.warn('Detached task failed', { agent: agent.slug, error: String(error) });
1293
+ return this.#store.org.getTask(board.id) ?? board;
1168
1294
  });
1295
+ if (context.taskId) {
1296
+ let pending = this.#detached.get(context.taskId);
1297
+ if (!pending) {
1298
+ pending = new Map();
1299
+ this.#detached.set(context.taskId, pending);
1300
+ }
1301
+ pending.set(board.id, running);
1302
+ }
1303
+ const whereBack = context.taskId
1304
+ ? 'Your own task stays open until it is finished: when your run ends, you are started again with its result.'
1305
+ : context.sessionId
1306
+ ? 'When it ends - done, failed or with a question - a message arrives in this conversation, and you tell the user then.'
1307
+ : 'It is on the board; how it ends is recorded on its card.';
1169
1308
  return {
1170
- text: isSelf
1171
- ? 'Started in the background as task ' + shortId + ' "' + title +
1172
- '" - I will follow up in this chat once it is done.'
1173
- : 'Handed to ' + agent.name + ' (' + agent.slug + ') as task ' + shortId + ' "' + title +
1174
- '". It runs in the background and is on the board; the user is told when it finishes.',
1309
+ text: (agent.id === context.agentId ? 'Started in the background' : 'Handed to ' + agent.name + ' (' + agent.slug + ')') +
1310
+ ' as task ' + shortId + ' "' + title + '". ' + whereBack,
1175
1311
  };
1176
1312
  }
1177
- const finished = await this.runTask(runContext, board);
1313
+ const finished = await this.#runAwaited(runContext, board);
1178
1314
  const duration = finished.startedAt && finished.finishedAt
1179
1315
  ? ', ' + Math.round((finished.finishedAt - finished.startedAt) / 1000) + ' s'
1180
1316
  : '';
1181
1317
  if (finished.status === 'blocked') {
1182
1318
  // Not a failure: the agent asked whoever wanted the work a question,
1183
1319
  // and the card stays open until it is answered.
1184
- return {
1185
- text: agent.name + ' (' + agent.slug + ') has a question about task ' + shortId + ' "' + title +
1186
- '"; it is waiting in the mail thread.' +
1187
- (finished.result ? '\n\n' + clip(finished.result, RESULT_BUDGET) : ''),
1188
- };
1320
+ return { text: this.#waitingText(finished) };
1189
1321
  }
1190
1322
  if (finished.status !== 'done') {
1191
1323
  return fail('Task ' + shortId + ' "' + title + '" with ' + agent.slug + ' ' + finished.status +
@@ -1196,534 +1328,293 @@ export class OrgController extends EventEmitter {
1196
1328
  duration + ':\n\n' + clip(finished.result ?? '', RESULT_BUDGET),
1197
1329
  };
1198
1330
  }
1199
- /** "user", "assistant", or an agent by slug/name/id - the tokens send_mail's to/cc take. */
1200
- #resolveMailTarget(orgId, token) {
1201
- const lower = token.toLowerCase();
1202
- if (lower === 'user')
1203
- return { kind: 'user' };
1204
- if (lower === 'assistant')
1205
- return { kind: 'assistant' };
1206
- const agent = this.#store.org.findAgent(orgId, token);
1207
- return agent ? { kind: 'agent', id: agent.id } : null;
1208
- }
1209
- #mailWhoLabel(who) {
1210
- if (who.kind !== 'agent')
1211
- return who.kind;
1212
- return (who.id ? this.#store.org.getAgent(who.id)?.slug : undefined) ?? 'unknown agent';
1213
- }
1331
+ /* ------------------------ questions, answers, notices ----------------------- */
1214
1332
  /**
1215
- * Whether `writer` already wrote to this recipient during the run that
1216
- * started at `since` - that is, answered the mail with `send_mail` rather
1217
- * than by ending its turn.
1218
- *
1219
- * Both are legitimate on their own: the turn's closing text is delivered
1220
- * as the reply, and `send_mail` is how anyone here writes to anyone at
1221
- * all. What is not legitimate is both, which is how a real answer was
1222
- * followed by a second mail reading "Done - the reply went out". The
1223
- * turn's own text loses, because by then the recipient has the answer in
1224
- * writing and the leftover text is bookkeeping about it.
1225
- *
1226
- * `box` narrows the question to one line of the address: for the duplicate
1227
- * reply any box counts, but a task only goes `blocked` on a To (decision
1228
- * E6) - a Cc to the requester is information, not a question.
1333
+ * What a caller that waited on a task hears when the task stopped on a
1334
+ * question: the question itself, and how to answer it. The agent's run is
1335
+ * over; the card waits, and `answer_task` is what carries it on.
1229
1336
  */
1230
- #answeredDuringTurn(orgId, writer, recipient, since, box) {
1231
- const key = (who) => who.kind + ':' + (who.id ?? '');
1232
- const wanted = key(recipient);
1233
- return this.#store.org
1234
- .mailbox(orgId, writer, 'outbox', { limit: 20 })
1235
- .some((sent) => sent.createdAt >= since &&
1236
- sent.recipients.some((entry) => (!box || entry.box === box) &&
1237
- key({ kind: entry.recipientKind, id: entry.recipientId }) === wanted));
1337
+ #waitingText(task) {
1338
+ const agent = task.assigneeId ? this.#store.org.getAgent(task.assigneeId) : null;
1339
+ const who = agent ? agent.name + ' (' + agent.slug + ')' : 'The agent';
1340
+ const question = this.#questionFor(task);
1341
+ return (who + ' has a question about task ' + task.id.slice(0, 8) + ' "' + task.title + '" and the task waits for ' +
1342
+ 'the answer.' +
1343
+ (question ? '\n\nThe question:\n' + clip(question, RESULT_BUDGET) : '') +
1344
+ (task.result ? '\n\nWhat it said:\n' + clip(task.result, RESULT_BUDGET) : '') +
1345
+ '\n\nAnswer it with answer_task("' + task.id.slice(0, 8) + '", ...) once you know the answer; the task ' +
1346
+ 'then runs again with it.');
1347
+ }
1348
+ /** The last question asked on a card, if any - what a waiting task waits on. */
1349
+ #questionFor(task) {
1350
+ return this.#store.org.lastTaskEvent(task.id, 'question')?.text || undefined;
1238
1351
  }
1239
1352
  /**
1240
- * The Cc line of a reply: everyone who was on the mail being answered,
1241
- * minus the two who are already on it - the sender, who is the reply's To,
1242
- * and the replier itself.
1353
+ * `ask_requester`: an agent inside a task asks whoever gave it the work.
1243
1354
  *
1244
- * Every automatic reply used to go out with an empty Cc, which quietly
1245
- * ended the thread for anyone looped in: somebody Cc'd on the opening mail
1246
- * saw that one line and never an answer to it, and the assistant copying
1247
- * the user in on a question it asked got the answer alone. Mail only works
1248
- * if being on a conversation means staying on it.
1355
+ * The question is written on the card, and the run is marked as having
1356
+ * asked - which is all it takes: when the run ends, its leaf reads the mark
1357
+ * and the card goes `blocked` instead of `done`, and the ending travels to
1358
+ * whoever asked like every other ending does (report-back, the parent task,
1359
+ * or a notification). This replaces a mail on the requester's To line, and
1360
+ * the outbox scan that used to recognise one.
1249
1361
  */
1250
- #replyCc(source, replier, sender) {
1251
- if (!source)
1252
- return [];
1253
- const key = (who) => who.kind + ':' + (who.id ?? '');
1254
- const seen = new Set([key(replier), key(sender)]);
1255
- const cc = [];
1256
- for (const recipient of source.recipients) {
1257
- const who = { kind: recipient.recipientKind, id: recipient.recipientId };
1258
- if (seen.has(key(who)))
1259
- continue;
1260
- seen.add(key(who));
1261
- cc.push(who);
1362
+ #askRequester(context, question) {
1363
+ const fail = (message) => ({ text: message, isError: true });
1364
+ if (context.audience !== 'agent') {
1365
+ return fail('Only an agent working on a task asks its requester. You can ask the user with ask_user.');
1262
1366
  }
1263
- // Whoever started the mail, when the reply is not addressed to them: an
1264
- // answer still concerns the person who asked, even two hops down.
1265
- const author = { kind: source.fromKind, id: source.fromAgentId };
1266
- if (!seen.has(key(author)))
1267
- cc.push(author);
1268
- return cc;
1367
+ if (!context.taskId) {
1368
+ return fail('You are not working on a task, so nobody is waiting to be asked. Put the question in your result, ' +
1369
+ 'with what you assumed in the meantime.');
1370
+ }
1371
+ const task = this.#store.org.getTask(context.taskId);
1372
+ if (!task)
1373
+ return fail('The task you are working on no longer exists.');
1374
+ if (!question)
1375
+ return fail('A question needs its text.');
1376
+ this.#taskEvent({
1377
+ taskId: task.id,
1378
+ kind: 'question',
1379
+ actorKind: 'agent',
1380
+ actorAgentId: context.agentId,
1381
+ text: question,
1382
+ assignmentId: context.parentAssignmentId,
1383
+ });
1384
+ if (context.parentAssignmentId)
1385
+ this.#askedRequester.add(context.parentAssignmentId);
1386
+ return {
1387
+ text: 'Your question is on the card of task ' + task.id.slice(0, 8) + '. End your run now with a short ' +
1388
+ 'summary of where the work stands and what you would do with each likely answer. The task waits ' +
1389
+ 'for the answer, and you are started again with it.',
1390
+ };
1269
1391
  }
1270
1392
  /**
1271
- * Deliver mail and, per the user's rule, start a real run for every To
1272
- * target that is an agent - never for Cc. Shared by the tool path
1273
- * (`#sendMail`, permission-checked) and `sendUserMail` (the user may mail
1274
- * anyone) and the automatic reply `run()` sends back when it finishes work
1275
- * that arrived as mail.
1393
+ * The one way anything reaches the user outside a conversation
1394
+ * (docs/concepts/mail-removal-notifications-and-task-activity.md). Stored,
1395
+ * so the web can show it later and mark it read; announced as a
1396
+ * `notification` event, which is what a push channel listens for. Never
1397
+ * throws: a notification that cannot be written costs the notification,
1398
+ * never the run or the status change that produced it - the returned
1399
+ * record then lives only in this one event.
1276
1400
  */
1277
- async #deliverMail(params) {
1278
- const threadId = params.threadId ?? (params.inReplyTo ? (this.#store.org.getMail(params.inReplyTo)?.threadId ?? params.inReplyTo) : undefined);
1279
- const mail = this.#store.org.sendMail({
1280
- orgId: params.orgId,
1281
- from: params.from,
1282
- subject: params.subject,
1283
- body: params.body,
1284
- to: params.to,
1285
- cc: params.cc,
1286
- threadId,
1287
- inReplyTo: params.inReplyTo,
1288
- depth: params.depth,
1289
- assignmentId: params.parentAssignmentId,
1290
- kind: params.kind,
1291
- });
1292
- this.#announce({ type: 'mail', mail }, params.emit);
1293
- // A task thread is dispatched by its task, never by the To line: the
1294
- // thread's own row decides that, not the call's `kind` (decision E4).
1295
- // Reading the parameter instead let a reply into a task thread - where
1296
- // no caller passes a kind - start a second run beside the task, on no
1297
- // board and on no card.
1298
- let triggerTo = params.to;
1299
- if (!params.autoReply && mail.threadKind === 'assignment') {
1300
- this.#continueTask(mail, params.from, params.depth);
1301
- // Who this thread belongs to has now been dealt with by the task. A
1302
- // colleague on To who neither does this task nor asked for it is being
1303
- // asked for something new, and still gets the run the agent prompt
1304
- // promises them - delegation by mail is how work moves sideways here,
1305
- // and a mail an agent writes from inside a task lands in this thread
1306
- // whether it is about the task or not (`#sendMail` inherits it).
1307
- const thread = this.#store.org.getMailThread(params.orgId, mail.threadId);
1308
- const task = thread?.taskId ? this.#store.org.getTask(thread.taskId) : null;
1309
- if (!task)
1310
- return mail;
1311
- triggerTo = params.to.filter((target) => !partyToTask(task, target));
1312
- if (!triggerTo.length)
1313
- return mail;
1314
- }
1315
- if (!params.autoReply && params.depth < this.#config.org.maxDelegationDepth) {
1316
- const senderLabel = this.#mailWhoLabel(params.from);
1317
- for (const target of triggerTo) {
1318
- if (target.kind === 'assistant' && this.#runAssistantMail) {
1319
- // Where the turn's own answer stops being the reply: if the
1320
- // assistant wrote to the sender itself while thinking, that mail
1321
- // is the answer, and delivering the turn's closing text on top of
1322
- // it is how "Done - the reply went out" arrives as a second mail.
1323
- const turnStartedAt = Date.now();
1324
- this.#runAssistantMail({
1325
- mail,
1326
- senderLabel,
1327
- thread: this.#store.org
1328
- .thread(params.orgId, mail.threadId, { who: { kind: 'assistant' } })
1329
- .filter((entry) => entry.id !== mail.id),
1330
- })
1331
- .then((reply) => {
1332
- if (!reply.trim())
1333
- return;
1334
- if (this.#answeredDuringTurn(params.orgId, { kind: 'assistant' }, params.from, turnStartedAt)) {
1335
- this.#log.debug('Mail already answered by the turn itself', { mail: mail.id });
1336
- return;
1337
- }
1338
- return this.#deliverMail({
1339
- orgId: params.orgId,
1340
- from: { kind: 'assistant' },
1341
- to: [params.from],
1342
- cc: this.#replyCc(mail, { kind: 'assistant' }, params.from),
1343
- subject: mail.subject.startsWith('Re: ') ? mail.subject : 'Re: ' + mail.subject,
1344
- body: reply,
1345
- inReplyTo: mail.id,
1346
- threadId: mail.threadId,
1347
- depth: params.depth + 1,
1348
- autoReply: true,
1349
- emit: () => undefined,
1350
- }).then(() => undefined);
1351
- })
1352
- .catch((error) => {
1353
- this.#log.warn('Mail-triggered assistant turn failed', { error: String(error) });
1354
- });
1355
- continue;
1356
- }
1357
- if (target.kind !== 'agent' || !target.id)
1358
- continue;
1359
- const agent = this.#store.org.getAgent(target.id);
1360
- if (!agent)
1361
- continue;
1362
- this.run({
1363
- orgId: params.orgId,
1364
- agent,
1365
- // A human wrote the subject line; that is already a name, and the
1366
- // same one the thread runs under (concept 7.2, source two).
1367
- title: mail.subject.trim() || titleFromBrief(params.body),
1368
- task: 'Handle mail ' + mail.id + ' from ' + senderLabel + '.\nSubject: ' + mail.subject + '\n\n' + params.body,
1369
- projectId: params.projectId,
1370
- parentId: params.parentAssignmentId,
1371
- requesterKind: params.from.kind,
1372
- requesterAgentId: params.from.kind === 'agent' ? params.from.id : undefined,
1373
- depth: params.depth,
1374
- emit: () => undefined,
1375
- sourceMail: {
1376
- id: mail.id,
1377
- threadId: mail.threadId,
1378
- depth: params.depth,
1379
- fromKind: params.from.kind,
1380
- fromAgentId: params.from.id,
1381
- subject: mail.subject,
1382
- },
1383
- }).catch((error) => {
1384
- this.#log.warn('Mail-triggered run failed', { agent: agent.slug, error: String(error) });
1385
- });
1386
- }
1401
+ notifyUser(input) {
1402
+ const orgId = input.orgId ?? this.activeOrganization().id;
1403
+ let notification;
1404
+ try {
1405
+ notification = this.#store.org.createNotification({ ...input, orgId });
1387
1406
  }
1388
- return mail;
1407
+ catch (error) {
1408
+ this.#log.warn('Notification could not be stored', { kind: input.kind, error: error.message });
1409
+ notification = {
1410
+ id: 'unsaved-' + Date.now().toString(36),
1411
+ orgId,
1412
+ kind: input.kind,
1413
+ title: input.title,
1414
+ body: input.body ?? '',
1415
+ fromKind: input.fromKind ?? 'system',
1416
+ fromAgentId: input.fromAgentId,
1417
+ taskId: input.taskId,
1418
+ cronJobId: input.cronJobId,
1419
+ cronRunId: input.cronRunId,
1420
+ sessionId: input.sessionId,
1421
+ createdAt: Date.now(),
1422
+ };
1423
+ }
1424
+ const event = { type: 'notification', notification };
1425
+ this.emit('notification', event);
1426
+ return notification;
1389
1427
  }
1390
1428
  /**
1391
- * A mail in a task thread continues its task; it never starts a run beside
1392
- * it (decision E5). The task decides what happens, not the mail: a running
1393
- * task only receives - the run it is in already has its prompt, and
1394
- * aborting it would burn work that was started in good faith (F1) - while
1395
- * a task that has stopped, however it stopped, runs again with this mail
1396
- * as its brief. The new run hangs on the same task through
1397
- * `linkTaskAssignment`, so the card keeps its whole chain, and the old
1398
- * result stands until the new run has a better one.
1429
+ * The user answers a task that is waiting on them - the entrance behind
1430
+ * `POST /api/org/tasks/:id/answer` and a Telegram reply to a `question`
1431
+ * notification. Same path as the `answer_task` tool, and like every answer
1432
+ * from a person, uncapped: they can see what came back and are deciding to
1433
+ * go again. The assistant or an agent may be named as `by` for a caller
1434
+ * that answers on their behalf; the chain of command still applies then.
1399
1435
  */
1400
- #continueTask(mail, from, depth) {
1401
- if (depth >= this.#config.org.maxDelegationDepth)
1402
- return;
1403
- const thread = this.#store.org.getMailThread(mail.orgId, mail.threadId);
1404
- // A task thread with no task: the mail that opens one arrives here
1405
- // before `sendTaskMail` has linked it, and its run is already on its
1406
- // way. Nothing else may start a run in a thread that owns no task.
1407
- if (!thread?.taskId)
1408
- return;
1409
- const task = this.#store.org.getTask(thread.taskId);
1410
- if (!task || task.status === 'running')
1411
- return;
1412
- const agent = task.assigneeId ? this.#store.org.getAgent(task.assigneeId) : null;
1413
- if (!agent)
1414
- return;
1415
- // A person writing in the thread always gets their run: they can see
1416
- // what came back and are deciding to try again. A machine writing in it
1417
- // cannot, so it gets a ceiling - without one, two agents mailing each
1418
- // other in a task thread re-run the same task until something else
1419
- // stops them, and a task that fails the same way every time costs a
1420
- // full model run per repetition.
1421
- if (from.kind !== 'user' && this.#store.org.taskRunCount(task.id) >= this.#config.org.maxTaskRuns) {
1422
- this.#log.warn('Task continuation refused: run ceiling reached', {
1423
- task: task.id,
1424
- runs: this.#store.org.taskRunCount(task.id),
1425
- });
1426
- return;
1427
- }
1428
- void this.runTask({
1429
- orgId: mail.orgId,
1430
- audience: 'assistant',
1431
- // One below the mail, so the leaf that carries out the task runs at
1432
- // the mail's own depth - exactly where the To-trigger put it.
1433
- depth: depth - 1,
1434
- projectId: task.projectId,
1435
- emit: () => undefined,
1436
- sourceMail: {
1437
- id: mail.id,
1438
- threadId: mail.threadId,
1439
- depth,
1440
- fromKind: from.kind,
1441
- fromAgentId: from.id,
1442
- subject: mail.subject,
1443
- },
1444
- taskNote: this.#mailWhoLabel(from) + ' wrote back:\n\n' + mail.body,
1445
- }, task).catch((error) => {
1446
- this.#log.warn('Task continuation failed', { task: task.id, error: String(error) });
1447
- });
1436
+ async answerTask(input) {
1437
+ const task = input.orgId
1438
+ ? this.findTask(input.orgId, input.taskId)
1439
+ : this.#store.org.getTask(input.taskId.trim());
1440
+ if (!task)
1441
+ return { ok: false, reason: 'No task ' + input.taskId + '.' };
1442
+ const answered = await this.#answer(task, input.answer.trim(), input.by ?? { kind: 'user' });
1443
+ if (!answered.ok)
1444
+ return answered;
1445
+ return { ok: true, task: this.#store.org.getTask(task.id) ?? task };
1448
1446
  }
1449
1447
  /**
1450
- * A task and the thread it is negotiated in are one thing (concept section
1451
- * 2), so a task that was not born as mail gets its work order written now:
1452
- * one mail from whoever asked for it to whoever does it, opening the
1453
- * thread the card is linked to.
1448
+ * Answer a task and carry it on. The answer goes on the card first, whatever
1449
+ * happens next - an answer that could not start a run is still the answer,
1450
+ * and the next run finds it on the card.
1454
1451
  *
1455
- * It delivers without triggering anything. An `assignment` thread is
1456
- * dispatched by its task, and at this moment the thread carries no task id
1457
- * yet - the link is made one line below - so `#continueTask` finds nothing
1458
- * and returns. Whoever created the task starts the run.
1459
- *
1460
- * A task nobody is assigned to gets no thread yet: there would be no
1461
- * second party to address, and it gets one as soon as it has an owner.
1452
+ * Who may answer is the chain of command: the user and the assistant any
1453
+ * task, an agent only the tasks it handed out itself. A running task is not
1454
+ * answered - its run has its prompt already, and aborting it would burn
1455
+ * work started in good faith (F1).
1462
1456
  */
1463
- async #ensureTaskThread(task, emit) {
1464
- if (this.#store.org.getMailThreadForTask(task.orgId, task.id))
1465
- return;
1466
- if (!task.assigneeId || !this.#store.org.getAgent(task.assigneeId))
1467
- return;
1468
- // A schedule has nobody to write to. The thread exists so a task can be
1469
- // negotiated - questions asked, results returned, an ending explained -
1470
- // and all of that presumes a counterpart who is waiting. A job that
1471
- // fires at three in the morning has none: its outcome is delivered by
1472
- // the schedule's own inbox mail. Opening a thread here meant every
1473
- // nightly run wrote a work order to the agent and, at the end, a "was
1474
- // marked as done" note to the user - two mails a night per job, for
1475
- // work nobody was following.
1476
- if (task.scheduleId)
1477
- return;
1478
- const from = task.createdBy === 'user'
1479
- ? { kind: 'user' }
1480
- : task.createdBy === 'agent' && task.createdByAgentId
1481
- ? { kind: 'agent', id: task.createdByAgentId }
1482
- : { kind: 'assistant' };
1483
- try {
1484
- const mail = await this.#deliverMail({
1485
- orgId: task.orgId,
1486
- from,
1487
- to: [{ kind: 'agent', id: task.assigneeId }],
1488
- cc: [],
1489
- subject: task.title,
1490
- body: task.description,
1491
- depth: 0,
1492
- kind: 'assignment',
1493
- projectId: task.projectId,
1494
- emit,
1495
- });
1496
- this.#store.org.linkMailThreadTask(task.orgId, mail.threadId, task.id);
1497
- }
1498
- catch (error) {
1499
- this.#log.warn('Task thread could not be opened', { task: task.id, error: String(error) });
1457
+ async #answer(task, answer, by, context) {
1458
+ if (!answer)
1459
+ return { ok: false, reason: 'An answer needs text.' };
1460
+ if (by.kind === 'agent' && (task.createdBy !== 'agent' || task.createdByAgentId !== by.agentId)) {
1461
+ return {
1462
+ ok: false,
1463
+ reason: 'Only whoever handed this task out may answer it. Tell whoever gave you your own work instead.',
1464
+ };
1500
1465
  }
1501
- }
1502
- async #sendMail(context, toRaw, ccRaw, subject, body, inReplyTo) {
1503
- const fail = (message) => ({ text: message, isError: true });
1504
- if (!toRaw)
1505
- return fail('Name at least one recipient in "to".');
1506
- if (!subject)
1507
- return fail('The mail needs a subject.');
1508
- if (!body)
1509
- return fail('The mail is empty.');
1510
- const toTokens = toRaw.split(',').map((v) => v.trim()).filter(Boolean);
1511
- const ccTokens = ccRaw.split(',').map((v) => v.trim()).filter(Boolean);
1512
- const to = [];
1513
- for (const token of toTokens) {
1514
- const target = this.#resolveMailTarget(context.orgId, token);
1515
- if (!target)
1516
- return fail('No agent "' + token + '".');
1517
- to.push(target);
1518
- }
1519
- const cc = [];
1520
- for (const token of ccTokens) {
1521
- const target = this.#resolveMailTarget(context.orgId, token);
1522
- if (!target)
1523
- return fail('No agent "' + token + '".');
1524
- cc.push(target);
1466
+ if (task.status === 'running') {
1467
+ return { ok: false, reason: 'The task is running right now. Answer it once its run has stopped.' };
1525
1468
  }
1526
- if (context.audience === 'agent') {
1527
- const self = context.agentId ? this.#store.org.getAgent(context.agentId) : null;
1528
- for (const target of [...to, ...cc]) {
1529
- if (target.kind !== 'agent')
1530
- continue; // user and assistant are always reachable
1531
- const recipient = this.#store.org.getAgent(target.id ?? '');
1532
- const allowed = recipient?.id === self?.managerId ||
1533
- recipient?.managerId === context.agentId ||
1534
- (Boolean(self?.teamId) && recipient?.teamId === self?.teamId);
1535
- if (!allowed)
1536
- return fail('You may mail your manager, your team, your reports, the assistant, or the user.');
1537
- }
1538
- }
1539
- const from = context.audience === 'agent' ? { kind: 'agent', id: context.agentId } : { kind: 'assistant' };
1540
- const depth = context.sourceMail ? context.sourceMail.depth + 1 : 0;
1541
- const mail = await this.#deliverMail({
1542
- orgId: context.orgId,
1543
- from,
1544
- to,
1545
- cc,
1546
- subject,
1547
- // A mail a scheduled run writes opens a report thread - it exists
1548
- // because a run produced it, no matter which box it came from. Replies
1549
- // inherit their thread anyway; only new threads land here.
1550
- kind: context.scheduled ? 'report' : undefined,
1551
- body,
1552
- inReplyTo,
1553
- threadId: inReplyTo ? undefined : context.sourceMail?.threadId,
1554
- depth,
1555
- parentAssignmentId: context.parentAssignmentId,
1556
- projectId: context.projectId,
1557
- emit: context.emit,
1469
+ this.#taskEvent({
1470
+ taskId: task.id,
1471
+ kind: 'answer',
1472
+ actorKind: by.kind,
1473
+ actorAgentId: by.agentId,
1474
+ text: answer,
1558
1475
  });
1559
- return { text: 'Mail sent to ' + [...to, ...cc].map((who) => this.#mailWhoLabel(who)).join(', ') + ': "' + mail.subject + '".' };
1476
+ const label = by.kind === 'agent'
1477
+ ? ((by.agentId ? this.#store.org.getAgent(by.agentId)?.slug : undefined) ?? 'an agent')
1478
+ : by.kind === 'user'
1479
+ ? 'The user'
1480
+ : 'The assistant';
1481
+ const question = this.#questionFor(task);
1482
+ const note = (question ? 'You asked:\n' + clip(question, 4000) + '\n\n' : '') +
1483
+ label + ' answered:\n\n' + answer;
1484
+ return this.#continueTask(task, by, note, context);
1560
1485
  }
1561
1486
  /**
1562
- * The user sends mail to anyone, no permission circle applied - the one
1563
- * entrance behind `POST /api/org/mail`.
1487
+ * An answered task runs again, as the same task (decision E5): the new run
1488
+ * hangs on the same card through `linkTaskAssignment`, so the card keeps
1489
+ * its whole chain, and the old result stands until the new run has a
1490
+ * better one.
1564
1491
  *
1565
- * What comes of it is read off the address line, never off a switch the
1566
- * user has to remember afterwards (decisions E2 and E3): exactly one agent
1567
- * on To is a work order and opens a task, Cc whoever you like. The
1568
- * assistant on To, the user on To, or several people on To is a
1569
- * conversation - the agents among them are woken exactly as before, and no
1570
- * card is created, because splitting work is `plan_task`'s job and not the
1571
- * address line's.
1492
+ * A person answering always gets their run. A machine answering cannot see
1493
+ * what came back, so it gets a ceiling - without one, two agents answering
1494
+ * each other re-run the same task until something else stops them, and a
1495
+ * task that fails the same way every time costs a full model run per
1496
+ * repetition.
1572
1497
  *
1573
- * A reply opens nothing either way: the thread it lands in decided long ago
1574
- * what it is, and a task thread carries its own task on (decision E5).
1498
+ * Answered from inside a task - a lead answering the question its own
1499
+ * report's card is waiting on (R4) - the continuation is work that lead
1500
+ * handed off, and its own task waits for it exactly as for an `assign`
1501
+ * with wait=false.
1575
1502
  */
1576
- async sendUserMail(input) {
1577
- const resolve = (token) => {
1578
- const target = this.#resolveMailTarget(input.orgId, token);
1579
- if (!target)
1580
- throw new Error('No agent "' + token + '".');
1581
- return target;
1582
- };
1583
- const to = input.to.map(resolve);
1584
- const soleRecipient = input.to.length === 1 ? input.to[0] : undefined;
1585
- if (!input.inReplyTo && soleRecipient !== undefined && to.length === 1 && to[0]?.kind === 'agent') {
1586
- return this.sendTaskMail({
1587
- orgId: input.orgId,
1588
- to: soleRecipient,
1589
- cc: input.cc,
1590
- subject: input.subject,
1591
- body: input.body,
1592
- projectId: input.projectId,
1593
- emit: input.emit,
1594
- });
1503
+ #continueTask(task, by, note, context) {
1504
+ const agent = task.assigneeId ? this.#store.org.getAgent(task.assigneeId) : null;
1505
+ if (!agent && !this.#store.org.listTasks(task.orgId, { parentId: task.id }).length) {
1506
+ return { ok: false, reason: 'The answer is on the card, but nobody is assigned to carry the task on.' };
1595
1507
  }
1596
- const mail = await this.#deliverMail({
1597
- orgId: input.orgId,
1598
- from: { kind: 'user' },
1599
- to,
1600
- cc: (input.cc ?? []).map(resolve),
1601
- subject: input.subject,
1602
- body: input.body,
1603
- inReplyTo: input.inReplyTo,
1604
- depth: 0,
1605
- projectId: input.projectId,
1606
- emit: input.emit ?? (() => undefined),
1607
- });
1608
- return { mail };
1609
- }
1610
- /**
1611
- * A work order as mail: one agent on the To line, one task on the board,
1612
- * one thread tying them together. The mail opens an `assignment` thread -
1613
- * delivered, but not auto-triggered, because the run happens here over the
1614
- * task, which is what keeps assignment, board and mail the same story.
1615
- * The agent's finished run replies into the thread; marking the task done
1616
- * posts a status note into it (see `notifyTaskStatus`).
1617
- */
1618
- async sendTaskMail(input) {
1619
- const target = this.#resolveMailTarget(input.orgId, input.to);
1620
- if (!target || target.kind !== 'agent' || !target.id)
1621
- throw new Error('A work order needs exactly one agent on the To line.');
1622
- const task = this.#store.org.createTask({
1623
- orgId: input.orgId,
1624
- title: input.subject.trim() || '(no subject)',
1625
- description: input.body,
1626
- assigneeId: target.id,
1627
- createdBy: 'user',
1628
- projectId: input.projectId,
1629
- });
1630
- this.#announceTask(task, input.emit ?? (() => undefined));
1631
- const mail = await this.#deliverMail({
1632
- orgId: input.orgId,
1633
- from: { kind: 'user' },
1634
- to: [target],
1635
- cc: (input.cc ?? [])
1636
- .map((token) => this.#resolveMailTarget(input.orgId, token))
1637
- .filter((who) => who !== null),
1638
- subject: input.subject,
1639
- body: input.body,
1640
- depth: 0,
1641
- kind: 'assignment',
1642
- projectId: input.projectId,
1643
- emit: input.emit ?? (() => undefined),
1644
- });
1645
- this.#store.org.linkMailThreadTask(input.orgId, mail.threadId, task.id);
1646
- // The run goes over the task, so the board keeps the assignment and the
1647
- // task's own trail. sourceMail is what makes the finished run mail its
1648
- // result back into this thread. Fire-and-forget like every delivery
1649
- // trigger: the mail exists, the answer arrives when it arrives.
1650
- void this.runTask({
1651
- orgId: input.orgId,
1652
- audience: 'assistant',
1653
- depth: -1,
1654
- projectId: input.projectId,
1508
+ const runs = this.#store.org.taskRunCount(task.id);
1509
+ if (by.kind !== 'user' && runs >= this.#config.org.maxTaskRuns) {
1510
+ this.#log.warn('Task continuation refused: run ceiling reached', { task: task.id, runs });
1511
+ return {
1512
+ ok: false,
1513
+ reason: 'The answer is on the card, but the task has already run ' + runs + ' times - the most it may run ' +
1514
+ 'without the user. It stays as it is until they pick it up.',
1515
+ };
1516
+ }
1517
+ const depth = context ? context.depth : -1;
1518
+ if (depth + 1 >= this.#config.org.maxDelegationDepth) {
1519
+ return { ok: false, reason: 'The answer is on the card, but delegation is nested too deep to run it from here.' };
1520
+ }
1521
+ const running = this.runTask({
1522
+ orgId: task.orgId,
1523
+ audience: context?.audience ?? 'assistant',
1524
+ agentId: context?.agentId,
1525
+ depth,
1526
+ projectId: task.projectId,
1527
+ parentAssignmentId: context?.parentAssignmentId,
1655
1528
  emit: () => undefined,
1656
- sourceMail: { id: mail.id, threadId: mail.threadId, depth: 0, fromKind: 'user', subject: mail.subject },
1657
- }, this.#store.org.getTask(task.id) ?? task).catch((error) => {
1658
- this.#log.warn('Task run for assignment mail failed', { task: task.id, error: String(error) });
1529
+ taskNote: note,
1530
+ }, task).catch((error) => {
1531
+ this.#log.warn('Task continuation failed', { task: task.id, error: String(error) });
1532
+ return this.#store.org.getTask(task.id) ?? task;
1659
1533
  });
1660
- return { mail, task };
1534
+ if (context?.taskId && task.parentId === context.taskId) {
1535
+ let pending = this.#detached.get(context.taskId);
1536
+ if (!pending) {
1537
+ pending = new Map();
1538
+ this.#detached.set(context.taskId, pending);
1539
+ }
1540
+ pending.set(task.id, running);
1541
+ }
1542
+ return { ok: true };
1543
+ }
1544
+ /** Append one line to a card's activity and tell everyone listening. Never throws. */
1545
+ #taskEvent(input) {
1546
+ try {
1547
+ const event = this.#store.org.addTaskEvent(input);
1548
+ const announced = { type: 'task-event', event };
1549
+ this.emit('task-event', announced);
1550
+ return event;
1551
+ }
1552
+ catch (error) {
1553
+ this.#log.warn('Task activity could not be written', { task: input.taskId, error: error.message });
1554
+ return null;
1555
+ }
1661
1556
  }
1662
1557
  /**
1663
- * A task's status change, told to its thread: a system note from the
1664
- * assistant as a reply, so the mail trail shows not just the work order
1665
- * and the result but also how the work ended. Never throws, and never
1666
- * wakes anyone - `autoReply` delivers without triggering.
1558
+ * Who hears how a task ended, once the card itself has moved - the half of
1559
+ * the old `notifyTaskStatus` that is about people rather than the thread.
1667
1560
  *
1668
- * It writes only when the thread has heard nothing else about this ending
1669
- * (decision E7). A finished run mails its result and a stuck one mails its
1670
- * question; both are the message, and a note repeating them is the same
1671
- * news twice. What the thread never hears on its own is a run that failed
1672
- * or was called off, and that is what the note is for.
1561
+ * A conversation that handed the work off hears it as a turn of its own
1562
+ * (`#reportBack`), a caller blocked on the run gets it as its return value,
1563
+ * and a parent task collects its children itself. What is left is the user
1564
+ * - a card they put up, or one the assistant made with no conversation to
1565
+ * report into - and they get a notification. An agent's own errand with no
1566
+ * parent is its own business and stays on the card.
1673
1567
  *
1674
- * `since` is when this ending began - a run passes its own start, so only
1675
- * that run's mail can speak for it. A change made by hand has no run and
1676
- * passes nothing: it happens now, the thread has said nothing about it,
1677
- * and the note always goes out. Judging every ending against the first
1678
- * run's start left a task cancelled by hand hours later silent, because
1679
- * the old result reply still counted as news about it.
1568
+ * A question is never silent. A card waiting on an answer that none of the
1569
+ * above will carry to anybody goes to the user as a `question`, schedule
1570
+ * cards included: the job fired at three in the morning, but the person it
1571
+ * works for is who can answer. The other endings keep the old silences: a
1572
+ * schedule's card (its own notification is the delivery) and a
1573
+ * cancellation the person just performed themselves.
1680
1574
  */
1681
- async notifyTaskStatus(task, status, since = Date.now()) {
1682
- const orgId = task.orgId;
1683
- const thread = this.#store.org.getMailThreadForTask(orgId, task.id);
1684
- if (!thread)
1575
+ #deliverEnding(task, status, how) {
1576
+ const userCard = task.createdBy === 'user' && !task.requesterSessionId && !task.parentId;
1577
+ const reportsBack = Boolean(task.requesterSessionId) && !task.parentId;
1578
+ const awaited = this.#awaited.has(task.id);
1579
+ if (status === 'blocked') {
1580
+ // Only a run's own ending asks anything; a card set to `blocked` by
1581
+ // hand carries no new question.
1582
+ if (!how.fromRun)
1583
+ return;
1584
+ if (!userCard) {
1585
+ if (awaited || reportsBack)
1586
+ return;
1587
+ // A lead's own report asked it: the lead's task waits for its
1588
+ // children and is started again with the question (R4), and
1589
+ // `#awaitDelegated` escalates it when it cannot be.
1590
+ if (task.createdBy === 'agent' && task.parentId)
1591
+ return;
1592
+ }
1593
+ this.#escalateQuestion(task);
1685
1594
  return;
1686
- const mails = this.#store.org.thread(orgId, thread.threadId, { limit: 50 });
1687
- const latest = mails.at(-1);
1688
- if (!latest)
1595
+ }
1596
+ if (task.scheduleId)
1689
1597
  return;
1690
- // Anyone but the person who asked: their own mail is the work order or a
1691
- // follow-up to it, never an answer. Asking "not the user" instead
1692
- // silenced every task nobody mailed in - `#ensureTaskThread` writes that
1693
- // work order from the assistant or a lead, one millisecond before the
1694
- // run starts, so a delegated task that failed said nothing at all.
1695
- const asked = (entry) => entry.fromKind === task.createdBy && (task.createdBy !== 'agent' || entry.fromAgentId === task.createdByAgentId);
1696
- if (mails.some((entry) => entry.createdAt >= since && !asked(entry)))
1598
+ if (status === 'cancelled' && how.by === 'user' && !how.fromRun)
1697
1599
  return;
1698
- // The note is addressed to whoever asked for the work, which is not always
1699
- // the user: an agent that delegates through `assign` opens a task of its
1700
- // own, and a receipt for it in the user's inbox is a receipt for something
1701
- // they never ordered. On a morning of ordinary delegation that was eight
1702
- // of them. They still see it when they are on the thread - `#replyCc`
1703
- // keeps everyone the conversation already had.
1704
- const requester = task.createdBy === 'agent' && task.createdByAgentId
1705
- ? { kind: 'agent', id: task.createdByAgentId }
1706
- : { kind: task.createdBy };
1707
- try {
1708
- await this.#deliverMail({
1709
- orgId,
1710
- from: { kind: 'assistant' },
1711
- to: [requester],
1712
- // Everyone the conversation already has stays on it; the status note
1713
- // is bookkeeping, but bookkeeping the assignee should see.
1714
- cc: this.#replyCc(latest, { kind: 'assistant' }, requester),
1715
- subject: latest.subject.startsWith('Re: ') ? latest.subject : 'Re: ' + latest.subject,
1716
- body: statusNote(task, status),
1717
- inReplyTo: latest.id,
1718
- threadId: thread.threadId,
1719
- depth: latest.depth + 1,
1720
- autoReply: true,
1721
- emit: () => undefined,
1722
- });
1723
- }
1724
- catch (error) {
1725
- this.#log.warn('Task status mail failed', { task: task.id, error: String(error) });
1600
+ // The user's own card tells them, even when the assistant happened to be
1601
+ // waiting on the run: they put it up, and the card is theirs to follow.
1602
+ if (!userCard) {
1603
+ if (awaited || reportsBack || task.parentId)
1604
+ return;
1605
+ if (task.createdBy !== 'assistant')
1606
+ return;
1726
1607
  }
1608
+ const agent = task.assigneeId ? this.#store.org.getAgent(task.assigneeId) : null;
1609
+ this.notifyUser({ orgId: task.orgId, ...taskNotification(task, agent) });
1610
+ }
1611
+ /** Put a waiting card's question to the user, in the asking agent's name. */
1612
+ #escalateQuestion(task) {
1613
+ const current = this.#store.org.getTask(task.id) ?? task;
1614
+ const asked = this.#store.org.lastTaskEvent(current.id, 'question');
1615
+ const agentId = asked?.actorAgentId ?? current.assigneeId;
1616
+ const agent = agentId ? this.#store.org.getAgent(agentId) : null;
1617
+ this.notifyUser({ orgId: current.orgId, ...taskNotification({ ...current, status: 'blocked' }, agent, asked?.text) });
1727
1618
  }
1728
1619
  /** Emit into the turn that caused an event, and to everyone listening on the controller. */
1729
1620
  #announce(event, emit) {
@@ -1753,7 +1644,7 @@ export class OrgController extends EventEmitter {
1753
1644
  /* ------------------------------ execution ------------------------------ */
1754
1645
  /**
1755
1646
  * Run one assignment to completion: a fresh provider process with the
1756
- * agent's own prompt, memory, inbox and tools. Never throws; the returned
1647
+ * agent's own prompt, memory and tools. Never throws; the returned
1757
1648
  * record says how it ended. Events flow to `input.emit` as they happen.
1758
1649
  */
1759
1650
  async run(input) {
@@ -1772,6 +1663,7 @@ export class OrgController extends EventEmitter {
1772
1663
  requesterAgentId: input.requesterAgentId,
1773
1664
  depth: input.depth,
1774
1665
  });
1666
+ input.onStarted?.(assignment);
1775
1667
  const view = (extra = {}) => toView(assignment, agent, extra);
1776
1668
  const announce = (extra = {}) => this.#announce({ type: 'assignment', assignment: view(extra) }, input.emit);
1777
1669
  const finish = (patch, extra = {}) => {
@@ -1847,21 +1739,15 @@ export class OrgController extends EventEmitter {
1847
1739
  if (!existsSync(cwd))
1848
1740
  return fail('The project directory ' + cwd + ' does not exist.', started);
1849
1741
  // Everything below is shared by every provider attempt of this
1850
- // assignment: the company, the memory, the inbox and the skills are the
1851
- // agent's, not the backend's.
1742
+ // assignment: the company, the memory and the skills are the agent's,
1743
+ // not the backend's.
1852
1744
  const snapshot = this.snapshot(input.orgId);
1853
1745
  const memories = this.#memoriesFor(agent.id, input.task);
1854
- const mailWho = { kind: 'agent', id: agent.id };
1855
- const unreadMail = org.unreadMailFor(input.orgId, mailWho);
1856
1746
  const requester = input.requesterKind === 'agent'
1857
1747
  ? (org.getAgent(input.requesterAgentId ?? '')?.name ?? 'your manager')
1858
1748
  : input.requesterKind === 'user'
1859
1749
  ? 'the user, directly'
1860
1750
  : 'the assistant';
1861
- // Read once the context is assembled: the mail is in the prompt, so a
1862
- // provider switch must not deliver it a second time.
1863
- if (unreadMail.length)
1864
- org.markMailReadFor(unreadMail, mailWho);
1865
1751
  // The project's own MCP servers - read from its `.mcp.json`, the same
1866
1752
  // file a person's own session in that folder would read - only start
1867
1753
  // once the assistant has approved this exact file (see
@@ -1902,7 +1788,6 @@ export class OrgController extends EventEmitter {
1902
1788
  emit: input.emit,
1903
1789
  signal: controller.signal,
1904
1790
  scheduled: input.scheduled,
1905
- sourceMail: input.sourceMail,
1906
1791
  });
1907
1792
  let text = '';
1908
1793
  let fatal = null;
@@ -1931,20 +1816,9 @@ export class OrgController extends EventEmitter {
1931
1816
  snapshot,
1932
1817
  project: project ?? undefined,
1933
1818
  memories,
1934
- mail: unreadMail,
1935
1819
  assignmentId: assignment.id,
1936
1820
  requestedBy: requester,
1937
- sourceMailSubject: input.sourceMail?.subject,
1938
- sourceMailId: input.sourceMail?.id,
1939
- sourceMailThreadId: input.sourceMail?.threadId,
1940
- // Everything said before the mail that woke this run, minus that mail
1941
- // itself - it is already the task above. Listed as an index only; the
1942
- // prompt points at `read_mail_thread` for the text.
1943
- sourceMailThread: input.sourceMail
1944
- ? org
1945
- .thread(input.orgId, input.sourceMail.threadId, { who: mailWho })
1946
- .filter((entry) => entry.id !== input.sourceMail?.id)
1947
- : undefined,
1821
+ taskId: input.taskId,
1948
1822
  toolHints,
1949
1823
  skillsIndex,
1950
1824
  agentNotes: org.agentNotesSince(agent.id).slice(0, 2),
@@ -2079,44 +1953,8 @@ export class OrgController extends EventEmitter {
2079
1953
  }
2080
1954
  if (this.#config.org.autoReview)
2081
1955
  void this.#review(agent, done, input.task, text, usedProvider);
2082
- if (input.onAskedRequester) {
2083
- // Who asked for this: the sender of the mail that started the run,
2084
- // or else whoever handed the assignment over.
2085
- const requester = input.sourceMail
2086
- ? { kind: input.sourceMail.fromKind, id: input.sourceMail.fromAgentId }
2087
- : { kind: input.requesterKind, id: input.requesterAgentId };
2088
- input.onAskedRequester(this.#answeredDuringTurn(input.orgId, { kind: 'agent', id: agent.id }, requester, started, 'to'));
2089
- }
2090
- if (input.sourceMail) {
2091
- const sourceMail = input.sourceMail;
2092
- const replier = { kind: 'agent', id: agent.id };
2093
- const sender = { kind: sourceMail.fromKind, id: sourceMail.fromAgentId };
2094
- // An agent that mailed the requester itself has already answered;
2095
- // the report would arrive behind it as a duplicate.
2096
- if (this.#answeredDuringTurn(input.orgId, replier, sender, started))
2097
- return done;
2098
- this.#deliverMail({
2099
- orgId: input.orgId,
2100
- from: replier,
2101
- to: [sender],
2102
- // Everyone the mail was addressed to stays addressed: a reply that
2103
- // drops the Cc is where a thread silently loses its audience.
2104
- cc: this.#replyCc(this.#store.org.getMail(sourceMail.id), replier, sender),
2105
- subject: 'Re: ' + sourceMail.subject,
2106
- body: text,
2107
- inReplyTo: sourceMail.id,
2108
- threadId: sourceMail.threadId,
2109
- depth: sourceMail.depth + 1,
2110
- // The reply carries the run that produced it; the thread's task, if
2111
- // it has one, is one `task_assignments` hop away from here.
2112
- parentAssignmentId: assignment.id,
2113
- projectId: project?.id,
2114
- autoReply: true,
2115
- emit: input.emit,
2116
- }).catch((error) => {
2117
- this.#log.warn('Mail reply failed', { agent: agent.slug, error: String(error) });
2118
- });
2119
- }
1956
+ // Asked by the run itself, through `ask_requester` - nothing to infer.
1957
+ input.onAskedRequester?.(this.#askedRequester.has(assignment.id));
2120
1958
  return done;
2121
1959
  }
2122
1960
  catch (error) {
@@ -2158,6 +1996,7 @@ export class OrgController extends EventEmitter {
2158
1996
  // `done` is reserved for a run that actually ended in `done`.
2159
1997
  const settled = this.#store.org.getAssignment(assignment.id) ?? assignment;
2160
1998
  this.#store.turns.settle(assignment.id, settled.status === 'done' ? 'done' : 'interrupted', Date.now());
1999
+ this.#askedRequester.delete(assignment.id);
2161
2000
  this.#active.delete(assignment.id);
2162
2001
  input.signal?.removeEventListener('abort', onAbort);
2163
2002
  this.#release();
@@ -2442,8 +2281,9 @@ export class OrgController extends EventEmitter {
2442
2281
  }
2443
2282
  }
2444
2283
  // The status goes through `setTaskStatus`, which is what makes this tool
2445
- // tell the task's mail thread what it did - closing a task from here
2446
- // used to leave whoever was waiting in that thread waiting for good.
2284
+ // record on the card what it did and tell whoever is owed the ending -
2285
+ // closing a task from here used to leave whoever was waiting waiting for
2286
+ // good.
2447
2287
  //
2448
2288
  // It runs *first*. Writing the fields first meant a refused status left
2449
2289
  // the other edits standing and unannounced: the caller read "that is not
@@ -2555,21 +2395,150 @@ export class OrgController extends EventEmitter {
2555
2395
  finally {
2556
2396
  this.#activeTasks.delete(task.id);
2557
2397
  outer.signal?.removeEventListener('abort', onAbort);
2398
+ // Every ending of every run passes here, thrown or not, so this is the
2399
+ // one place a report-back can be neither forgotten nor sent twice.
2400
+ this.#detached.delete(task.id);
2401
+ this.#reportBack(reload());
2402
+ }
2403
+ }
2404
+ /**
2405
+ * A task that ended outside any run - failed by the startup sweep after a
2406
+ * restart killed its run. It is reported back like any other ending: the
2407
+ * conversation that handed it off must not wait for ever on a run that no
2408
+ * longer exists.
2409
+ */
2410
+ reportEnded(task) {
2411
+ // On the card and to the user as well, by the same rules as any other
2412
+ // ending: a card the user put up must not end in silence because the
2413
+ // process that ran it died.
2414
+ this.#recordStatus(task, 'system');
2415
+ if (task.status === 'done' || task.status === 'failed' || task.status === 'cancelled') {
2416
+ this.#deliverEnding(task, task.status, { by: 'assistant', fromRun: true });
2417
+ }
2418
+ this.#reportBack(task);
2419
+ }
2420
+ /** `runTask` for a caller that blocks on the result - it hears the ending itself. */
2421
+ async #runAwaited(context, task) {
2422
+ this.#awaited.add(task.id);
2423
+ try {
2424
+ return await this.runTask(context, task);
2425
+ }
2426
+ finally {
2427
+ this.#awaited.delete(task.id);
2428
+ }
2429
+ }
2430
+ /**
2431
+ * Tell whoever handed this work off how it ended (R2). Only a conversation
2432
+ * is told here: a caller blocked on the run gets its return value, a
2433
+ * subtask reports to the task it belongs to, and a card nobody handed over
2434
+ * - the board, a schedule - is told through `#deliverEnding`. A
2435
+ * conversation that cannot take a turn (a schedule's, say) is the
2436
+ * runtime's to fall back from: it turns the event into a notification.
2437
+ */
2438
+ #reportBack(task) {
2439
+ if (!task.requesterSessionId || task.parentId || this.#awaited.has(task.id))
2440
+ return;
2441
+ if (task.status !== 'done' && task.status !== 'failed' && task.status !== 'cancelled' && task.status !== 'blocked') {
2442
+ return;
2443
+ }
2444
+ const agent = task.assigneeId ? this.#store.org.getAgent(task.assigneeId) : null;
2445
+ const event = {
2446
+ sessionId: task.requesterSessionId,
2447
+ taskId: task.id,
2448
+ status: task.status,
2449
+ notice: reportBackNotice(task, agent, task.status === 'blocked' ? this.#questionFor(task) : undefined),
2450
+ };
2451
+ this.emit('report-back', event);
2452
+ }
2453
+ /**
2454
+ * The leaf is finished, but work it handed off in the background may not
2455
+ * be (R4). Wait for all of it, then - if the leaf itself had finished
2456
+ * cleanly - run it once more with the results, so the task's report is
2457
+ * built on them instead of on a promise that they are coming. A cancelled
2458
+ * task takes its handed-off work down with it.
2459
+ */
2460
+ async #awaitDelegated(context, task, agent, first) {
2461
+ let outcome = first;
2462
+ for (let round = 0;; round += 1) {
2463
+ const pending = this.#detached.get(task.id);
2464
+ if (!pending || pending.size === 0) {
2465
+ this.#detached.delete(task.id);
2466
+ return outcome;
2467
+ }
2468
+ const entries = [...pending.entries()];
2469
+ pending.clear();
2470
+ const cancelAll = () => {
2471
+ for (const [id] of entries)
2472
+ this.cancelTask(id);
2473
+ };
2474
+ if (context.signal?.aborted || outcome.status === 'cancelled') {
2475
+ cancelAll();
2476
+ this.#detached.delete(task.id);
2477
+ return outcome;
2478
+ }
2479
+ context.signal?.addEventListener('abort', cancelAll, { once: true });
2480
+ let children;
2481
+ try {
2482
+ children = await Promise.all(entries.map(([, promise]) => promise));
2483
+ }
2484
+ finally {
2485
+ context.signal?.removeEventListener('abort', cancelAll);
2486
+ }
2487
+ // Cancelled while it waited: the task ends cancelled, not with the
2488
+ // interim report it had written before the work came back.
2489
+ if (context.signal?.aborted) {
2490
+ this.#detached.delete(task.id);
2491
+ return { ...outcome, status: 'cancelled' };
2492
+ }
2493
+ // A leaf that failed or is waiting on a question is not picked back up:
2494
+ // the children's results are on the board, and a re-run would paper
2495
+ // over the question or the failure. Nor is one past either ceiling.
2496
+ // A child that came back with a question then has nobody left to ask
2497
+ // it of, and a question is never silent: it goes to the user.
2498
+ const current = children.map((child) => this.#store.org.getTask(child.id) ?? child);
2499
+ if (outcome.status !== 'done' ||
2500
+ outcome.askedRequester ||
2501
+ round >= MAX_DELEGATION_ROUNDS ||
2502
+ this.#store.org.taskRunCount(task.id) >= this.#config.org.maxTaskRuns) {
2503
+ for (const child of current)
2504
+ if (child.status === 'blocked')
2505
+ this.#escalateQuestion(child);
2506
+ continue;
2507
+ }
2508
+ const results = current
2509
+ .map((child) => {
2510
+ const who = child.assigneeId ? (this.#store.org.getAgent(child.assigneeId)?.slug ?? 'agent') : 'agent';
2511
+ const head = '### ' + child.title + ' (' + who + ', ' + child.status + ', task ' + child.id.slice(0, 8) + ')\n';
2512
+ if (child.status === 'blocked') {
2513
+ // R4 meets ask_requester: the child asked its requester, and the
2514
+ // requester is this run. The question comes back here with the
2515
+ // results, and answering it carries the child on.
2516
+ const question = this.#questionFor(child);
2517
+ return (head + 'It stopped with a question for you:\n' + clip(question ?? child.result ?? '(no text)', 6000) +
2518
+ '\nAnswer it with answer_task("' + child.id.slice(0, 8) + '", ...) - it then carries on in the ' +
2519
+ 'background, and you are started again once it is back. If you cannot answer it, say so in your ' +
2520
+ 'report instead.');
2521
+ }
2522
+ return head + clip(child.result ?? (child.error ? 'FAILED: ' + child.error : 'no output'), 6000);
2523
+ })
2524
+ .join('\n\n');
2525
+ const note = 'The work you handed off in the background while doing this task has come back:\n\n' + results +
2526
+ '\n\nYour own report from before it came back:\n' + clip(outcome.result ?? '', 6000) +
2527
+ '\n\nPick the task back up with these results and finish it. What you answer now is the final report.';
2528
+ outcome = await this.#runTaskLeaf({ ...context, taskNote: note }, this.#store.org.getTask(task.id) ?? task, agent);
2558
2529
  }
2559
2530
  }
2560
2531
  async #runTask(context, task) {
2561
2532
  const org = this.#store.org;
2562
2533
  const reload = () => org.getTask(task.id) ?? task;
2563
2534
  const started = Date.now();
2564
- // How a run ends is the thread's business, not an HTTP route's: every
2565
- // ending passes here, and `notifyTaskStatus` decides for itself whether
2566
- // the thread still needs to be told (decision E7).
2535
+ // How a run ends is the card's business, not an HTTP route's: every
2536
+ // ending passes here, and `setTaskStatus` records it and decides who is
2537
+ // owed it (decision E7).
2567
2538
  // Through the one writer like everyone else. `fromRun` is what lets it
2568
2539
  // move a card that is `running`: this loop owns that card for the
2569
2540
  // duration, and it is the only writer that may decide the outcome from
2570
- // inside rather than having to cancel first. `started` keeps the
2571
- // thread's "has it already heard about this ending" check pinned to
2572
- // this run, not to the task's first one.
2541
+ // inside rather than having to cancel first.
2573
2542
  const finish = async (status, patch) => {
2574
2543
  const moved = await this.setTaskStatus({
2575
2544
  task: reload(),
@@ -2583,8 +2552,8 @@ export class OrgController extends EventEmitter {
2583
2552
  return moved.ok ? moved.task : reload();
2584
2553
  };
2585
2554
  try {
2586
- // Planning and opening the thread belong inside the guard. They ran
2587
- // before it, so a failure in either escaped `#runTask` entirely - and
2555
+ // Planning belongs inside the guard. It ran before it once, so a
2556
+ // failure there escaped `#runTask` entirely - and
2588
2557
  // `Runtime.assign` had already put the card on the board by then,
2589
2558
  // leaving it sitting at `open` with no run, no error and no
2590
2559
  // explanation. The claim below is what makes the card `running`, and
@@ -2595,10 +2564,6 @@ export class OrgController extends EventEmitter {
2595
2564
  await this.planTask(context, reload());
2596
2565
  children = org.listTasks(context.orgId, { parentId: task.id }).filter((c) => c.status !== 'cancelled');
2597
2566
  }
2598
- // Every task is negotiated in a thread, whichever way it got here: one
2599
- // that was not born as mail has its work order written before it runs,
2600
- // so its result, its questions and its ending all have somewhere to go.
2601
- await this.#ensureTaskThread(reload(), context.emit);
2602
2567
  if (!org.claimTaskForRun(task.id, started)) {
2603
2568
  // Somebody finished or cancelled it while this was getting ready.
2604
2569
  return reload();
@@ -2637,15 +2602,15 @@ export class OrgController extends EventEmitter {
2637
2602
  const agent = current.assigneeId ? org.getAgent(current.assigneeId) : null;
2638
2603
  if (!agent)
2639
2604
  return await finish('failed', { error: 'Nobody is assigned and nobody could be found to do it.' });
2640
- const outcome = await this.#runTaskLeaf(context, current, agent);
2605
+ const leaf = await this.#runTaskLeaf(context, current, agent);
2606
+ const outcome = await this.#awaitDelegated(context, current, agent, leaf);
2641
2607
  return await finish(taskStatusFor(outcome), { result: outcome.result, error: outcome.error });
2642
2608
  }
2643
2609
  const waves = buildTaskWaves(children.filter((c) => c.status !== 'done'));
2644
- // A task that arrived as mail must not let every subtask's leaf answer
2645
- // the thread in turn - three subtasks would mail three replies. The
2646
- // waves run without the mail context; the parent speaks for the split
2647
- // once, below, with the combined result.
2648
- const waveContext = { ...context, sourceMail: undefined, taskNote: undefined };
2610
+ // The note that continued the parent is the parent's; each subtask runs
2611
+ // on its own brief. The parent speaks for the split once, below, with
2612
+ // the combined result.
2613
+ const waveContext = { ...context, taskNote: undefined };
2649
2614
  for (const wave of waves) {
2650
2615
  if (waveContext.signal?.aborted)
2651
2616
  break;
@@ -2669,32 +2634,6 @@ export class OrgController extends EventEmitter {
2669
2634
  result: combined,
2670
2635
  error: failed.length ? failed.length + ' of ' + all.length + ' subtasks failed.' : undefined,
2671
2636
  };
2672
- // The one answer the mailed split makes: the parent's combined report,
2673
- // through the same auto-reply path a leaf would have used. It goes out
2674
- // before the task is closed, so that the status note `finish()` may add
2675
- // sees a thread that has already heard how the work ended.
2676
- if (context.sourceMail && outcome.status === 'done') {
2677
- const sourceMail = context.sourceMail;
2678
- const replier = { kind: 'assistant' };
2679
- const sender = { kind: sourceMail.fromKind, id: sourceMail.fromAgentId };
2680
- if (!this.#answeredDuringTurn(context.orgId, replier, sender, started)) {
2681
- void this.#deliverMail({
2682
- orgId: context.orgId,
2683
- from: replier,
2684
- to: [sender],
2685
- cc: this.#replyCc(this.#store.org.getMail(sourceMail.id), replier, sender),
2686
- subject: 'Re: ' + sourceMail.subject,
2687
- body: combined,
2688
- inReplyTo: sourceMail.id,
2689
- threadId: sourceMail.threadId,
2690
- depth: sourceMail.depth + 1,
2691
- autoReply: true,
2692
- emit: context.emit,
2693
- }).catch((error) => {
2694
- this.#log.warn('Task completion mail failed', { task: task.id, error: String(error) });
2695
- });
2696
- }
2697
- }
2698
2637
  return await finish(outcome.status, { result: outcome.result, error: outcome.error });
2699
2638
  }
2700
2639
  /** One subtask inside a wave: mark it, run its leaf, record the outcome. */
@@ -2722,6 +2661,7 @@ export class OrgController extends EventEmitter {
2722
2661
  }
2723
2662
  finally {
2724
2663
  this.#activeTasks.delete(child.id);
2664
+ this.#detached.delete(child.id);
2725
2665
  outer.signal?.removeEventListener('abort', onAbort);
2726
2666
  }
2727
2667
  }
@@ -2753,7 +2693,10 @@ export class OrgController extends EventEmitter {
2753
2693
  });
2754
2694
  }
2755
2695
  else {
2756
- const outcome = await this.#runTaskLeaf(context, child, agent, deps.filter((t) => t.result));
2696
+ // A subtask's agent may hand work on in the background as well; the
2697
+ // subtask is not done before that work is back (R4).
2698
+ const leaf = await this.#runTaskLeaf(context, child, agent, deps.filter((t) => t.result));
2699
+ const outcome = await this.#awaitDelegated(context, child, agent, leaf);
2757
2700
  org.updateTask(child.id, {
2758
2701
  status: taskStatusFor(outcome),
2759
2702
  result: outcome.result,
@@ -2762,7 +2705,22 @@ export class OrgController extends EventEmitter {
2762
2705
  });
2763
2706
  }
2764
2707
  }
2765
- this.#announceTask(org.getTask(child.id) ?? child, context.emit);
2708
+ const ended = org.getTask(child.id) ?? child;
2709
+ this.#announceTask(ended, context.emit);
2710
+ // A subtask's ending is written straight to its row above - the parent's
2711
+ // loop owns it - but it still goes on the card, and a question on it
2712
+ // still has to reach somebody: the split's parent only collects results.
2713
+ if (ended.status === 'done' || ended.status === 'failed' || ended.status === 'cancelled' || ended.status === 'blocked') {
2714
+ this.#recordStatus(ended, 'system');
2715
+ this.#deliverEnding(ended, ended.status, { by: 'assistant', fromRun: true });
2716
+ }
2717
+ }
2718
+ /** The card's own line about where it now stands. */
2719
+ #recordStatus(task, actor) {
2720
+ if (task.status !== 'done' && task.status !== 'failed' && task.status !== 'cancelled' && task.status !== 'blocked') {
2721
+ return;
2722
+ }
2723
+ this.#taskEvent({ taskId: task.id, kind: 'status', actorKind: actor, text: statusNote(task, task.status) });
2766
2724
  }
2767
2725
  /** One task, one agent, one assignment. */
2768
2726
  async #runTaskLeaf(context, task, agent, deps = []) {
@@ -2771,10 +2729,11 @@ export class OrgController extends EventEmitter {
2771
2729
  deps.map((dep) => '### ' + dep.title + '\n' + clip(dep.result ?? '', 6000)).join('\n\n') +
2772
2730
  '\n\n---\n\n'
2773
2731
  : '';
2774
- // What continued the thread comes after the work order: the order is
2775
- // what the task is, the note is what changed about it.
2732
+ // What continued the task comes after the work order: the order is what
2733
+ // the task is, the note is what changed about it.
2776
2734
  const note = context.taskNote ? '\n\n---\n\n' + context.taskNote : '';
2777
2735
  let askedRequester = false;
2736
+ const runNumber = this.#store.org.taskRunCount(task.id) + 1;
2778
2737
  const assignment = await this.run({
2779
2738
  orgId: context.orgId,
2780
2739
  agent,
@@ -2793,26 +2752,42 @@ export class OrgController extends EventEmitter {
2793
2752
  // Who is waiting for this comes off the card, not off the audience
2794
2753
  // that happens to be driving the run. They are not the same thing: a
2795
2754
  // task the user put on the board is carried out by the assistant, so
2796
- // reading the audience said "assistant" and the agent's question went
2797
- // looking for an answer from a party that was never asked. Then
2798
- // `askedRequester` saw nobody waiting and the task closed as `done`
2799
- // with a real question still open in the user's inbox.
2755
+ // reading the audience said "assistant" and the agent was told the
2756
+ // work came from a party that never asked for it.
2800
2757
  //
2801
- // `notifyTaskStatus` and `partyToTask` already answer this question
2802
- // from `task.createdBy`; this is the third place agreeing with them.
2758
+ // `#deliverEnding` answers this question from `task.createdBy` as
2759
+ // well; the two have to agree.
2803
2760
  requesterKind: task.createdBy,
2804
2761
  requesterAgentId: task.createdBy === 'agent' ? task.createdByAgentId : undefined,
2805
2762
  depth: context.depth + 1,
2806
2763
  emit: context.emit,
2807
2764
  signal: context.signal,
2808
- // A task that arrived as mail answers in its thread: the leaf's run
2809
- // mails its result back to the sender, the way a To-line run does.
2810
- sourceMail: context.sourceMail,
2811
2765
  onAskedRequester: (asked) => {
2812
2766
  askedRequester = asked;
2813
2767
  },
2768
+ onStarted: (started) => {
2769
+ this.#taskEvent({
2770
+ taskId: task.id,
2771
+ kind: 'run-started',
2772
+ actorKind: 'agent',
2773
+ actorAgentId: agent.id,
2774
+ text: agent.name + ' started run ' + runNumber + (context.taskNote ? ', carrying on with new input' : '') + '.',
2775
+ assignmentId: started.id,
2776
+ });
2777
+ },
2814
2778
  });
2815
2779
  this.#store.org.linkTaskAssignment(task.id, assignment.id);
2780
+ this.#taskEvent({
2781
+ taskId: task.id,
2782
+ kind: 'run-ended',
2783
+ actorKind: 'agent',
2784
+ actorAgentId: agent.id,
2785
+ text: 'Run ' + runNumber + ' ' + (askedRequester && assignment.status === 'done' ? 'ended with a question' : assignment.status) +
2786
+ (assignment.durationMs !== undefined ? ' after ' + Math.round(assignment.durationMs / 1000) + ' s' : '') +
2787
+ (assignment.error ? ': ' + assignment.error : '.') +
2788
+ (assignment.result ? '\n\n' + clip(assignment.result, 4000) : ''),
2789
+ assignmentId: assignment.id,
2790
+ });
2816
2791
  return {
2817
2792
  status: assignment.status,
2818
2793
  result: assignment.result,
@@ -2829,13 +2804,14 @@ export class OrgController extends EventEmitter {
2829
2804
  * idea of what else has to happen. The route checked for a conflicting
2830
2805
  * run and wrote a note into the task's mail thread; the tool did neither;
2831
2806
  * the CLI did not even emit an event, so an open browser never heard that
2832
- * the card had moved. Whether the thread learned a task was finished
2807
+ * the card had moved. Whether anybody learned a task was finished
2833
2808
  * depended on which process happened to finish it, and that is what made
2834
2809
  * the board feel arbitrary.
2835
2810
  *
2836
2811
  * Three things belong together and now cannot come apart: the guard, the
2837
- * write, and telling everyone. `by` is who is asking, which decides
2838
- * whether a running task may be touched at all.
2812
+ * write, and telling everyone - the card's activity, and whoever is owed
2813
+ * the ending. `by` is who is asking, which decides whether a running task
2814
+ * may be touched at all.
2839
2815
  *
2840
2816
  * Reopening clears what the previous life left behind. A card moved back
2841
2817
  * to `open` kept its old `finishedAt` and `result`, so every duration on
@@ -2903,22 +2879,13 @@ export class OrgController extends EventEmitter {
2903
2879
  org.updateTask(current.id, patch);
2904
2880
  const updated = org.getTask(current.id) ?? current;
2905
2881
  this.#announceTask(updated, input.emit ?? (() => undefined));
2906
- // A card from a schedule has no thread and no counterpart waiting in
2907
- // one - the schedule's own inbox mail is its delivery. Telling it how
2908
- // the work ended would put a second notification on top of that, every
2909
- // firing, for ever.
2910
- // Who still needs telling, once the card itself has moved.
2911
- //
2912
- // Not a schedule's card - its own inbox mail is the delivery. Not
2913
- // `blocked`, because being blocked *is* an agent's question sitting in
2914
- // the thread already, and a note saying "this is waiting for an answer"
2915
- // underneath the answer it is waiting for is pure noise. And not a
2916
- // cancellation the person just performed: they know, they did it.
2917
- const silent = Boolean(updated.scheduleId) ||
2918
- input.to === 'blocked' ||
2919
- (input.to === 'cancelled' && input.by === 'user' && !input.fromRun);
2920
- if (!silent && (input.to === 'done' || input.to === 'failed' || input.to === 'cancelled')) {
2921
- await this.notifyTaskStatus(updated, input.to, input.since ?? now);
2882
+ // Every ending and every wait goes on the card, whoever moved it; then
2883
+ // whoever is owed the news gets it (`#deliverEnding` has the rules - who
2884
+ // hears, and the old silences: a schedule's card, the person's own
2885
+ // cancel).
2886
+ if (input.to === 'done' || input.to === 'failed' || input.to === 'cancelled' || input.to === 'blocked') {
2887
+ this.#recordStatus(updated, input.fromRun ? 'system' : input.by);
2888
+ this.#deliverEnding(updated, input.to, { by: input.by, fromRun: Boolean(input.fromRun) });
2922
2889
  }
2923
2890
  return { ok: true, task: updated };
2924
2891
  }
@@ -3453,16 +3420,16 @@ function briefFor(task) {
3453
3420
  return derived ? description : 'TASK: ' + task.title + '\n\n' + description;
3454
3421
  }
3455
3422
  /**
3456
- * What the thread is told when a task ends - the work, not the bookkeeping.
3423
+ * The card's `status` line when a task ends or waits - the work, not the
3424
+ * bookkeeping.
3457
3425
  *
3458
3426
  * This used to say "The task X was marked as done." and nothing else, which
3459
- * is the worst of both worlds: a mail that interrupts somebody and then
3427
+ * is the worst of both worlds: a line that interrupts somebody and then
3460
3428
  * makes them go somewhere else to find the thing it is about. If a note is
3461
- * worth sending at all it carries the result; if the result is not worth
3462
- * reading, the note was not worth sending.
3429
+ * worth writing at all it carries the result; if the result is not worth
3430
+ * reading, the note was not worth writing.
3463
3431
  *
3464
- * Clipped rather than whole: the full text is on the card and on the run,
3465
- * and a mail is a notification, not an archive.
3432
+ * Clipped rather than whole: the full text is on the card and on the run.
3466
3433
  */
3467
3434
  function statusNote(task, status) {
3468
3435
  const name = 'The task "' + task.title + '"';
@@ -3476,26 +3443,12 @@ function statusNote(task, status) {
3476
3443
  return name + ' is waiting for an answer.';
3477
3444
  return name + ' failed' + (task.error ? ': ' + task.error : '.');
3478
3445
  }
3479
- /**
3480
- * Whether a recipient is a party to a task: the agent who does it, or
3481
- * whoever asked for it. Their mail in the task's thread is the negotiation
3482
- * of the task itself and is dispatched by the task (`#continueTask`).
3483
- * Anybody else on the To line is being asked for something new and keeps the
3484
- * run the mail trigger has always given them.
3485
- */
3486
- function partyToTask(task, who) {
3487
- if (who.kind === 'agent' && who.id && who.id === task.assigneeId)
3488
- return true;
3489
- if (who.kind !== task.createdBy)
3490
- return false;
3491
- return who.kind !== 'agent' || who.id === task.createdByAgentId;
3492
- }
3493
3446
  /**
3494
3447
  * What one finished leaf run means for its card. A run that ended by asking
3495
3448
  * its requester a question is not done, whatever its own status says: the
3496
3449
  * work waits for an answer, and the card says so (decision E6). The error
3497
3450
  * falls the safe way round - a task wrongly left `blocked` sits on the board
3498
- * and is carried on by the next reply, while a task wrongly called `done`
3451
+ * and is carried on by the next answer, while a task wrongly called `done`
3499
3452
  * disappears.
3500
3453
  */
3501
3454
  function taskStatusFor(outcome) {